Compare commits

...

61 Commits

Author SHA1 Message Date
pre-commit-ci[bot] 25c3ba7338 All: Reformat according to new standard 2025-11-11 13:49:01 +01:00
Kacper Donat eafd18dac0 Part,PartDesign,Gui: Add to pre-commit formatting 2025-11-11 13:45:27 +01:00
Kacper Donat b70b31226b All: Update formatting style 2025-11-11 13:45:27 +01:00
pre-commit-ci[bot] 28a5bcdf8e [pre-commit.ci] pre-commit autoupdate
updates:
- [github.com/psf/black-pre-commit-mirror: fe95161893684893d68b1225356702ca71f8d388 → 2892f1f81088477370d4fbc56545c05d33d2493f](https://github.com/psf/black-pre-commit-mirror/compare/fe95161893684893d68b1225356702ca71f8d388...2892f1f81088477370d4fbc56545c05d33d2493f)
- [github.com/pre-commit/mirrors-clang-format: 719856d56a62953b8d2839fb9e851f25c3cfeef8 → 317810f3c6a0ad3572367dc86cb6e41863e16e08](https://github.com/pre-commit/mirrors-clang-format/compare/719856d56a62953b8d2839fb9e851f25c3cfeef8...317810f3c6a0ad3572367dc86cb6e41863e16e08)
2025-11-11 09:47:59 +01:00
Billy Huddleston ec2a41b86b CAM: Fix ReferenceError when accessing deleted toolbit object
Prevent crash (CAMTests) in ToolBitRecomputeObserver when the toolbit object has been deleted/missing
by catching ReferenceError before accessing its Document attribute. This ensures slotRecomputedDocument
exits gracefully if the object is no longer valid.

src/Mod/CAM/Path/Tool/toolbit/models/base.py
- Wrapped access to self.toolbit_proxy.obj.Document in try/except to handle ReferenceError
if object is deleted/missing, preventing crash during document recompute.
2025-11-10 18:44:02 -06:00
Kacper Donat 5556821e7e Gui: Add special handling for too small overlay side panel
This basically is due to how OverlayTabWidget::setRect is implemented. If it faces width (or
height) of 0 it forces the width to be minimumOverlayWidth * 3, which in the default config
appears to be 90. 90 is obviously way too small of a value to display any widget in the side
panel, so we need to basically need to treat anything smaller or equal to that as an
incorrect value for width. We use here 100 just to be safe.

For the height value of 100 may be reasonable, so we leave it as is.
2025-11-10 18:40:17 -06:00
Chris Hennes 44c73fdd5b Gui: Restore 'Exit' menu text for Linux/Windows
Only macOS appears to set the text based on the menu item's role.
2025-11-11 00:17:00 +01:00
Chris Hennes 80080d9fde Merge pull request #25216 from kadet1090/fix-overlay-task-panel
Gui: Enable Overlay only for new users
2025-11-10 16:46:16 -06:00
pjcreath 280addd21c Gui: Fix crash in placement window after closing a document. (#25110)
Fixes #18156
2025-11-10 11:03:05 -06:00
Chris Hennes 483d0ef6fe Gui: Ensure Quit menu item is QAction::QuitRole 2025-11-10 17:52:31 +01:00
PaddleStroke 0ff0359524 PartDesign: Fix 'UpToShape' not saving correctly 2025-11-10 10:49:50 -06:00
FEA-eng b038f4130c FEM: Add ccx capacitance two spheres example (#25117)
* FEM: Update CMakeLists.txt

* FEM: add new ccx electrostatics example

* FEM: Update equation_electrostatics_capacitance_two_balls.py

* FEM: Update equation_electrostatics_capacitance_two_balls_ccx.py
2025-11-10 10:47:33 -06:00
Billy Huddleston 2d83e86f07 CAM: Improve Z retract reliability in rotational scan after geometry recompute
Introduced FLOAT_EPSILON for robust floating point comparisons, resolving cases
where Z axis retract moves were missing after geometry recompute in 3D Surface
rotational scan operations. This prevents precision errors from causing the
cutter to skip intended lifts between rings or scan lines.

src/Mod/CAM/Path/Op/Surface.py
 - Added FLOAT_EPSILON constant
 - Updated Z move comparison logic to use tolerance
2025-11-10 10:45:58 -06:00
Billy Huddleston 871ab6df64 CAM: Fix infinite recompute loop when ToolBit properties use expressions
A bug in the ToolBit model caused an infinite recompute loop and UI freeze when properties such as Diameter, Flutes, or CuttingEdgeHeight were set to expressions. The visual representation update was being triggered during document recompute, which could recursively trigger further recomputes. This fix defers visual updates by queuing them and processing only after the document recompute completes, using a document observer. The observer is cleaned up after use and on object deletion, preventing memory leaks and repeated recompute cycles.

src/Mod/CAM/Path/Tool/toolbit/models/base.py:
- ToolBitRecomputeObserver: Document observer class that triggers queued visual updates after recompute completes via slotRecomputedDocument.
- _queue_visual_update: Queues a visual update to be processed after document recompute.
- _setup_recompute_observer: Registers the document observer for recompute completion.
- _process_queued_visual_update: Processes the queued visual update and cleans up the observer.
- onChanged: Now queues visual updates instead of calling them directly.
- onDelete: Cleans up any pending document observer before object removal.
2025-11-10 10:43:15 -06:00
neurallambda df7ee72171 Fix CAM job "no attribute Proxy" (#25034) 2025-11-10 10:42:32 -06:00
tarman3 2e37667371 CAM: Slot - Fix references enumeration 2025-11-10 10:41:58 -06:00
marbocub b5b00f7aff Fix legacy mmTangentPlane orientation in 1.1.0dev (resolves #24254) (#24529)
* Add legacy TangentPlane orientation compatibility layer

* Refactor: extract lambda for object identifier construction

* Refactor: axis calculation using std::ranges::max_element and std::distance

* Apply suggestions from code review

Co-authored-by: Pieter Hijma <pieterhijma@users.noreply.github.com>

* Part: Add regression test for issue 24254

---------

Co-authored-by: Pieter Hijma <pieterhijma@users.noreply.github.com>
Co-authored-by: Chris Hennes <chennes@gmail.com>
2025-11-10 10:36:42 -06:00
Kacper Donat f7908335e5 Gui: Make overlay dragger respect palette
This changes Overlay Dragger to not have hardcoded color but instead
respect the palette from theme.
2025-11-10 17:05:25 +01:00
Kacper Donat f43c6906ff Gui: Enable Overlay only for new users
This change tries to detect invalid state where overlay was
half-initialized that resulted in overlay being enabled for more users
that we initially aimed for.
2025-11-10 17:05:25 +01:00
pjcreath 3071cc847c Gui: Fix crash in measuring tool after an undo. (#25129)
Co-authored-by: Chris Hennes <chennes@pioneerlibrarysystem.org>
2025-11-09 20:04:22 -06:00
Steven James 5c464e0746 Fix setting Bool value in VarSet add properties dialog. (#24873)
* Connect Bool checkbox checkStateChanged to the editor callback so changes will actually happen.
Make the change compatible with Qt versions <6.7.0

* Remove delayed singleshot-value changed from the event filter for Checkbox as suggested by @pieterhijma

* Remove no longer relevent comment
2025-11-09 17:45:57 -06:00
theo-vt 484c724ac6 Techdraw: Assign AutoDistribute when creating a projection group (#25103) 2025-11-09 17:41:50 -06:00
tetektoza 6bed2e663e Sketcher: Clear selection on selected geometry when hiding
When a geometry element is selected and then hidden using the visibility
checkbox in the Elements panel, it remains in the selection.
Subsequently, if another geometry element is selected and deleted, both
the visible element AND the hidden element are deleted.

Root cause of that is basically that `changeLayer()` functions change
the geometry's visual layer, but never clear the geometry from
`Gui::Selection()`.

So, this patch adds the handling to collect every sub-element name of
the hidden geometry and then formats it and calls remove selection on
the geometry during layer change transaction.
2025-11-09 17:40:08 -06:00
chris ffea3da872 freecad issue #25069 fix issue with selecting the plot tab / window from the menu bar 2025-11-09 17:20:15 -06:00
Florian Foinant-Willig ee34d09f7a Core: add a check on object deletion 2025-11-09 16:44:40 -06:00
Chris Hennes 948f284472 Merge pull request #25186 from Roy-043/BIM-fix-human-figure
BIM: Fix human figure
2025-11-09 16:36:52 -06:00
pjcreath b92b54de0e Gui: prevent native macOS color picker crash.
Fixes #25153
2025-11-09 16:23:17 -06:00
paul 50d22e2bb7 [ArchStairs] Fix StringerOverlap with Base at Angle (#25167)
* [ArchStairs] Fix StringerOverlap Base at Angle

Github Issue Discussion
- https://github.com/FreeCAD/FreeCAD/issues/24321#issuecomment-3492459309

"... error when Stringer Overlap is set above certain threshold combined with a non-baseless stair which does not have orthogonal direction - this means that the base line or sketch is rotated to a degree, which is not 0, 90, 180 or 270 degrees."

Further
Fix #24321

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2025-11-09 18:59:14 +01:00
Roy-043 071e7f3dfa Remove HumanFigure.brep from Arch.qrc resources 2025-11-09 18:49:00 +01:00
Roy-043 ce0a3dd526 BIM: Fix human figure
Fixes #25084.

Instead of a brep file a point list is now used to generate the figure.

Additionally:
Two points have been added to make the head of the figure less 'pointy'.

It would make sense to move the `get_human_figure` function to a different file in the future.

With 1.7m the figure is not very tall BTW.
2025-11-09 16:49:37 +01:00
marioalexis 9e7b5f6444 Fem: Fix CapacitanceBody default value 2025-11-08 14:15:42 -06:00
Chris Hennes ca5d22ebca Merge pull request #25162 from Rexbas/sketcher-cleanup-grid-icon
Sketcher: Remove unused icons and fix SIGSEGV
2025-11-08 14:13:49 -06:00
Bas Ruigrok 3d0db63193 TechDraw: Fix ignored "Zoom at Cursor" for TouchPad style 2025-11-08 11:37:37 -06:00
Chris Hennes 924dfe29c8 CI: Update Python version to 3.13 in fetch-crowdin (#25149) 2025-11-08 18:23:17 +01:00
Bas Ruigrok d95f56b39b Sketcher: Remove unused rendering order icons 2025-11-08 14:12:33 +01:00
Bas Ruigrok a479197f0b Sketcher: Remove unused snap icons and fix SIGSEGV 2025-11-08 14:08:32 +01:00
Bas Ruigrok c828c5d1d1 Sketcher: Remove unused grid toggle icons and fix SIGSEGV 2025-11-08 13:42:39 +01:00
pjcreath be93298afd Gui: process remaining deferredDelete events before stopping event loop 2025-11-07 13:18:47 +01:00
marioalexis 06131ce8b5 Base: Restore schema spec for electromagnetic potential unit - fix #25093 2025-11-06 15:05:25 +01:00
FEA-eng 66600f9f1f Gui: Fix unreadable Choose Folder button in the macro recording panel 2025-11-06 15:04:04 +01:00
Florian Foinant-Willig 3ae8f3d57a OCC usage: fix deprecated Handle_* 2025-11-06 10:43:52 +01:00
Chris Hennes af41a9dcef Merge pull request #24317 from kpemartin/Issue24314
Update unit test to use new storage for DXF import settings
2025-11-05 14:25:58 -06:00
dependabot[bot] 7ecdb0236b Bump prefix-dev/setup-pixi from 0.9.2 to 0.9.3
Bumps [prefix-dev/setup-pixi](https://github.com/prefix-dev/setup-pixi) from 0.9.2 to 0.9.3.
- [Release notes](https://github.com/prefix-dev/setup-pixi/releases)
- [Commits](https://github.com/prefix-dev/setup-pixi/compare/28eb668aafebd9dede9d97c4ba1cd9989a4d0004...82d477f15f3a381dbcc8adc1206ce643fe110fb7)

---
updated-dependencies:
- dependency-name: prefix-dev/setup-pixi
  dependency-version: 0.9.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-05 13:19:26 -06:00
marioalexis 6c7187b54f Fem: Fix magnetodynamic2D boundary condition 2025-11-05 13:06:53 -06:00
Pieter Hijma 011b6cdfbf Gui: Fix supporting xlinks in add property dialog 2025-11-05 12:49:47 -06:00
Ajinkya Dahale 857190a20a Sketcher: Only transfer equality in specific cases in trim
The transfer on should apply to (arcs of) conics.

Fixes #25008.
2025-11-05 12:48:05 -06:00
wandererfan 37af704998 [TD]fix angle dim in detail view 2025-11-05 12:46:35 -06:00
PhoneDroid f2d60d7abe [ Plot ]: Update SPDX License Identifiers 2025-11-05 12:45:42 -06:00
ᴩʜᴏɴᴇᴅʀᴏɪᴅ 54948b441d SPDX [ 34 ][ Src / Mod / Points ] (#25073) 2025-11-05 12:44:17 -06:00
PhoneDroid 28d5539fc7 [ Reverse ]: Update SPDX License Identifier 2025-11-05 12:42:10 -06:00
PhoneDroid bde82f19cb [ MacAppBundle ]: Update SPDX License Identifiers 2025-11-05 12:40:53 -06:00
marioalexis 123aee6b1b Fem: Fix CalculiX body heat source writer for 2D case 2025-11-05 12:37:52 -06:00
PhoneDroid 4e9fe02b9a [ Ext ]: Update SPDX License Identifiers 2025-11-05 12:37:18 -06:00
PaddleStroke cb108249f2 Sketcher: Fix offset of open profile (#25091)
* Sketcher: Fix offset of open profile

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2025-11-05 12:35:45 -06:00
dependabot[bot] a8ce12f2b4 Bump step-security/harden-runner from 2.13.1 to 2.13.2
Bumps [step-security/harden-runner](https://github.com/step-security/harden-runner) from 2.13.1 to 2.13.2.
- [Release notes](https://github.com/step-security/harden-runner/releases)
- [Commits](https://github.com/step-security/harden-runner/compare/f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a...95d9a5deda9de15063e7595e9719c11c38c90ae2)

---
updated-dependencies:
- dependency-name: step-security/harden-runner
  dependency-version: 2.13.2
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-05 11:20:34 -06:00
pre-commit-ci[bot] 8ddecd21a1 [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
2025-11-05 13:32:09 +00:00
Kevin Martin 520dd7b2b7 Remove test from old location 2025-11-05 08:28:35 -05:00
Kevin Martin 5afe1e64f8 Transplant the test code from the old location
For some reason the app hangs after the test GUI is run
2025-11-05 08:28:34 -05:00
Kevin Martin 2d5bb51734 Add the sample input file 2025-11-05 08:28:34 -05:00
Kevin Martin 44bb16cae7 Enable Python Draft import tests
A failing test was added to Draft tests to ensure CI catches it
2025-11-05 08:28:17 -05:00
Furgo 2d2684cc3d BIM: remove BIM Project command from toolbar (#25086)
- The BIM_Project command is removed from the toolbar and relocated to
  the Utils menu
- The default when creating a new project has been changed to
  non-IFC-native
- The BIM_Project and IFC_MakeProject command menu text have been
  reworded to remove ambiguity
2025-11-05 09:56:46 +01:00
2508 changed files with 157839 additions and 120361 deletions
+76 -49
View File
@@ -1,22 +1,22 @@
# Generated from CLion C/C++ Code Style settings
# --- Based on Qt Coding Style ---
BasedOnStyle: LLVM
# --- Bracket and Indentation Behavior ---
IndentWidth: 4
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
TabWidth: 4
ColumnLimit: 100
UseTab: Never
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: None
AlignOperands: DontAlign
AllowAllArgumentsOnNextLine: false
AlignAfterOpenBracket: BlockIndent
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Empty
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: Empty
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakTemplateDeclarations: Yes
BinPackArguments: false
BinPackParameters: false
BinPackArguments: false
BreakBeforeBraces: Custom
BreakTemplateDeclarations: Yes
BreakBeforeBinaryOperators: All
BraceWrapping:
AfterCaseLabel: false
AfterClass: true
@@ -31,41 +31,68 @@ BraceWrapping:
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: true
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeComma
BreakInheritanceList: BeforeColon
ColumnLimit: 100
CompactNamespaces: false
ContinuationIndentWidth: 4
IndentCaseLabels: true
IndentPPDirectives: None
IndentWidth: 4
InsertBraces: true
KeepEmptyLinesAtTheStartOfBlocks: true
MaxEmptyLinesToKeep: 2
NamespaceIndentation: None
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PackConstructorInitializers: Never
PointerAlignment: Left
ReflowComments: true
SortIncludes: Never
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: false
# --- Special: Lambdas and Short Things ---
AllowShortFunctionsOnASingleLine: None
AllowShortBlocksOnASingleLine: Never
AllowShortEnumsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortLambdasOnASingleLine: Inline
AllowAllArgumentsOnNextLine: false
# --- Spaces ---
SpaceBeforeParens: ControlStatements
SpaceAfterCStyleCast: false
Cpp11BracedListStyle: true
SpaceBeforeCpp11BracedList: true
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: false
SpacesInCStyleCastParentheses: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
TabWidth: 4
UseTab: Never
SpaceAfterTemplateKeyword: false
SpaceBeforeInheritanceColon: false
# --- Alignment & Formatting Tweaks ---
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignOperands: DontAlign
BreakConstructorInitializers: BeforeComma
PointerAlignment: Left
ReferenceAlignment: Left
# --- Comment Style ---
CommentPragmas: '^ IWYU pragma:'
# --- Namespace handling ---
NamespaceIndentation: None
# --- Others ---
SortIncludes: Never
IncludeBlocks: Preserve
MaxEmptyLinesToKeep: 2
IndentCaseLabels: true
InsertBraces: true
AlignEscapedNewlines: DontAlign
PPIndentWidth: 1
IndentPPDirectives: AfterHash
ReflowComments: true
# --- Penalties (Fine-tuning when to break lines) ---
PenaltyBreakAssignment: 80
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 60
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakOpenParenthesis: 5
PenaltyExcessCharacter: 10
PenaltyReturnTypeOnItsOwnLine: 600
+1 -2
View File
@@ -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,
+1 -1
View File
@@ -58,7 +58,7 @@ jobs:
logdir: /tmp/log/
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -21,7 +21,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -64,7 +64,7 @@ jobs:
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -68,7 +68,7 @@ jobs:
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -26,7 +26,7 @@ jobs:
- name: Setup Python & dependencies
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c
with:
python-version: "3.x"
python-version: "3.13"
- name: Install Python packages
run: |
python3 -m pip install --upgrade pip
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -26,7 +26,7 @@ jobs:
- name: Setup Python & dependencies
uses: actions/setup-python@e797f83bcb11b83ae66e0230d6156d7c80228e7c
with:
python-version: "3.x"
python-version: "3.13"
- name: Install Python packages
run: |
python3 -m pip install --upgrade pip
+1 -1
View File
@@ -36,7 +36,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+2 -2
View File
@@ -75,7 +75,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -116,7 +116,7 @@ jobs:
mkdir -p ${{ env.reportdir }}
echo "reportFile=${{ env.reportfilename }}" >> $GITHUB_OUTPUT
- uses: prefix-dev/setup-pixi@28eb668aafebd9dede9d97c4ba1cd9989a4d0004 # v0.9.2
- uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3
with:
pixi-version: v0.59.0
cache: false
+1 -1
View File
@@ -77,7 +77,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -66,7 +66,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -198,7 +198,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+1 -1
View File
@@ -81,7 +81,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+3 -3
View File
@@ -14,7 +14,7 @@ jobs:
build_tag: ${{ steps.tag_build.outputs.build_tag }}
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -72,7 +72,7 @@ jobs:
environment: weekly-build
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
@@ -104,7 +104,7 @@ jobs:
fetch-tags: true
submodules: 'recursive'
- uses: prefix-dev/setup-pixi@28eb668aafebd9dede9d97c4ba1cd9989a4d0004 # v0.9.2
- uses: prefix-dev/setup-pixi@82d477f15f3a381dbcc8adc1206ce643fe110fb7 # v0.9.3
with:
pixi-version: v0.59.0
cache: false
+1 -1
View File
@@ -54,7 +54,7 @@ jobs:
steps:
- name: Harden the runner (Audit all outbound calls)
uses: step-security/harden-runner@f4a75cfd619ee5ce8d5b864b0d183aff3c69b55a # v2.13.1
uses: step-security/harden-runner@95d9a5deda9de15063e7595e9719c11c38c90ae2 # v2.13.2
with:
egress-policy: audit
+8 -5
View File
@@ -6,9 +6,9 @@ files: |
(?x)^(
.github|
src/Base|
src/Gui|
src/Main|
src/Tools|
tests/src|
src/Mod/Assembly|
src/Mod/BIM|
src/Mod/CAM|
@@ -20,8 +20,10 @@ files: |
src/Mod/Inspection|
src/Mod/JtReader|
src/Mod/Measure|
src/Mod/Mesh|
src/Mod/MeshPart|
src/Mod/Mesh|
src/Mod/PartDesign|
src/Mod/Part|
src/Mod/Plot|
src/Mod/Points|
src/Mod/ReverseEngineering|
@@ -33,7 +35,8 @@ files: |
src/Mod/Surface|
src/Mod/Test|
src/Mod/Tux|
src/Mod/Web
src/Mod/Web|
tests/src
)
exclude: |
(?x)^(
@@ -66,11 +69,11 @@ repos:
- id: check-added-large-files
- id: mixed-line-ending
- repo: https://github.com/psf/black-pre-commit-mirror
rev: fe95161893684893d68b1225356702ca71f8d388 # frozen: 25.9.0
rev: 2892f1f81088477370d4fbc56545c05d33d2493f # frozen: 25.11.0
hooks:
- id: black
args: ['--line-length', '100']
- repo: https://github.com/pre-commit/mirrors-clang-format
rev: 719856d56a62953b8d2839fb9e851f25c3cfeef8 # frozen: v21.1.2
rev: 317810f3c6a0ad3572367dc86cb6e41863e16e08 # frozen: v21.1.5
hooks:
- id: clang-format
+4
View File
@@ -3221,6 +3221,10 @@ bool Document::containsObject(const DocumentObject* pcObject) const
void Document::removeObject(const char* sName)
{
auto pos = d->objectMap.find(sName);
if (pos == d->objectMap.end()){
FC_MSG("Object " << sName << " already deleted in document " << getName());
return;
}
if (pos->second->testStatus(ObjectStatus::PendingRecompute)) {
// TODO: shall we allow removal if there is active undo transaction?
+1 -2
View File
@@ -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<VectorPy*>(o)->value(), static_cast<VectorPy*>(d)->value());
*getAxisPtr() = Axis(static_cast<VectorPy*>(o)->value(), static_cast<VectorPy*>(d)->value());
return 0;
}
+1 -2
View File
@@ -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<std::size_t, std::size_t>
Base::base64_decode(void* _out, char const* in, std::size_t in_len)
std::pair<std::size_t, std::size_t> Base::base64_decode(void* _out, char const* in, std::size_t in_len)
{
auto* out = reinterpret_cast<unsigned char*>(_out); // NOLINT
unsigned char* ret = out;
+1 -2
View File
@@ -85,8 +85,7 @@ BaseExport std::array<const signed char, base64DecodeTableSize> 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<std::size_t, std::size_t>
base64_decode(void* out, char const*, std::size_t len);
BaseExport std::pair<std::size_t, std::size_t> 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
+32 -23
View File
@@ -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<std::streamsize>(
base64_encode_size(line_size != 0U ? line_size : defaultBufferSize));
base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)
);
}
template<typename Device>
@@ -174,7 +173,8 @@ struct base64_decoder
{
static constexpr int defaultBufferSize {1024};
return static_cast<std::streamsize>(
base64_encode_size(line_size != 0U ? line_size : defaultBufferSize));
base64_encode_size(line_size != 0U ? line_size : defaultBufferSize)
);
}
template<typename Device>
@@ -226,12 +226,15 @@ struct base64_decoder
}
if (pending_in == 4) {
pending_out = pending_in = 0;
char_array_3[0] =
static_cast<char>((char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4));
char_array_3[1] = static_cast<char>(((char_array_4[1] & 0xf) << 4)
+ ((char_array_4[2] & 0x3c) >> 2));
char_array_3[2] =
static_cast<char>(((char_array_4[2] & 0x3) << 6) + char_array_4[3]);
char_array_3[0] = static_cast<char>(
(char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4)
);
char_array_3[1] = static_cast<char>(
((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2)
);
char_array_3[2] = static_cast<char>(
((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<std::ostream>
create_base64_encoder(std::ostream& out, std::size_t line_size = base64DefaultBufferSize)
inline std::unique_ptr<std::ostream> create_base64_encoder(
std::ostream& out,
std::size_t line_size = base64DefaultBufferSize
)
{
std::unique_ptr<std::ostream> res(new bio::filtering_ostream);
auto* filteringStream = dynamic_cast<bio::filtering_ostream*>(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<std::ostream>
create_base64_encoder(const std::string& filepath, std::size_t line_size = base64DefaultBufferSize)
inline std::unique_ptr<std::ostream> create_base64_encoder(
const std::string& filepath,
std::size_t line_size = base64DefaultBufferSize
)
{
std::unique_ptr<std::ostream> res(new bio::filtering_ostream);
auto* filteringStream = dynamic_cast<bio::filtering_ostream*>(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<std::istream>
create_base64_decoder(std::istream& in,
std::size_t line_size = base64DefaultBufferSize,
Base64ErrorHandling errHandling = Base64ErrorHandling::silent)
inline std::unique_ptr<std::istream> create_base64_decoder(
std::istream& in,
std::size_t line_size = base64DefaultBufferSize,
Base64ErrorHandling errHandling = Base64ErrorHandling::silent
)
{
std::unique_ptr<std::istream> res(new bio::filtering_istream);
auto* filteringStream = dynamic_cast<bio::filtering_istream*>(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<std::istream>
create_base64_decoder(const std::string& filepath,
std::size_t line_size = base64DefaultBufferSize,
Base64ErrorHandling errHandling = Base64ErrorHandling::silent)
inline std::unique_ptr<std::istream> create_base64_decoder(
const std::string& filepath,
std::size_t line_size = base64DefaultBufferSize,
Base64ErrorHandling errHandling = Base64ErrorHandling::silent
)
{
std::unique_ptr<std::istream> res(new bio::filtering_istream);
auto* filteringStream = dynamic_cast<bio::filtering_istream*>(res.get());
+6 -4
View File
@@ -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());
+79 -77
View File
@@ -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
+120 -81
View File
@@ -61,12 +61,14 @@ public:
//@}
/** Builds box from pairs of x,y,z values. */
inline explicit BoundBox3(Precision fMinX = std::numeric_limits<Precision>::max(),
Precision fMinY = std::numeric_limits<Precision>::max(),
Precision fMinZ = std::numeric_limits<Precision>::max(),
Precision fMaxX = -std::numeric_limits<Precision>::max(),
Precision fMaxY = -std::numeric_limits<Precision>::max(),
Precision fMaxZ = -std::numeric_limits<Precision>::max());
inline explicit BoundBox3(
Precision fMinX = std::numeric_limits<Precision>::max(),
Precision fMinY = std::numeric_limits<Precision>::max(),
Precision fMinZ = std::numeric_limits<Precision>::max(),
Precision fMaxX = -std::numeric_limits<Precision>::max(),
Precision fMaxY = -std::numeric_limits<Precision>::max(),
Precision fMaxZ = -std::numeric_limits<Precision>::max()
);
BoundBox3(const BoundBox3<Precision>& rcBB) = default;
BoundBox3(BoundBox3<Precision>&& rcBB) noexcept = default;
/** Builds box from an array of points. */
@@ -178,8 +180,7 @@ public:
*/
inline Vector3<Precision> CalcPoint(unsigned short usPoint) const;
/** Returns the plane of the given side. */
void
CalcPlane(unsigned short usPlane, Vector3<Precision>& rBase, Vector3<Precision>& rNormal) const;
void CalcPlane(unsigned short usPlane, Vector3<Precision>& rBase, Vector3<Precision>& rNormal) const;
/** Calculates the two points of an edge.
*/
bool CalcEdge(unsigned short usEdge, Vector3<Precision>& rcP0, Vector3<Precision>& 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<Precision>& rcVct,
const Vector3<Precision>& rcVctDir,
Vector3<Precision>& cVctRes,
Precision epsilon) const;
bool IntersectionPoint(
const Vector3<Precision>& rcVct,
const Vector3<Precision>& rcVctDir,
Vector3<Precision>& cVctRes,
Precision epsilon
) const;
/** Checks for intersection with line incl. search tolerance. */
bool IsCutLine(const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Precision fTolerance = 0.0F) const;
bool IsCutLine(
const Vector3<Precision>& rcBase,
const Vector3<Precision>& 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<Precision>& rclBase,
const Vector3<Precision>& rclNormal) const;
inline bool IsCutPlane(const Vector3<Precision>& rclBase, const Vector3<Precision>& rclNormal) const;
/** Computes the intersection points of line and bounding box. */
bool IntersectWithLine(const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1) const;
bool IntersectWithLine(
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1
) const;
/** Computes the intersection point of line and a plane of the bounding box. */
bool IntersectPlaneWithLine(unsigned short usSide,
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0) const;
bool IntersectPlaneWithLine(
unsigned short usSide,
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0
) const;
/** Returns the side of the bounding box the ray exits. */
typename BoundBox3<Precision>::SIDE GetSideFromRay(const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir) const;
typename BoundBox3<Precision>::SIDE GetSideFromRay(
const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir
) const;
/** Returns the side of the bounding box the ray exits. */
typename BoundBox3<Precision>::SIDE GetSideFromRay(const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir,
Vector3<Precision>& rcInt) const;
typename BoundBox3<Precision>::SIDE GetSideFromRay(
const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir,
Vector3<Precision>& rcInt
) const;
/**
* Searches for the closest point of the bounding box.
@@ -288,12 +300,14 @@ bool BoundBox3<Precision>::isOnRayS(Precision min, Precision max, Precision val)
// NOLINTBEGIN(bugprone-easily-swappable-parameters)
template<class Precision>
inline BoundBox3<Precision>::BoundBox3(Precision fMinX,
Precision fMinY,
Precision fMinZ,
Precision fMaxX,
Precision fMaxY,
Precision fMaxZ)
inline BoundBox3<Precision>::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<Precision>::operator&&(const BoundBox2d& rcBB) const
}
template<class Precision>
inline BoundBox3<Precision>
BoundBox3<Precision>::Intersected(const BoundBox3<Precision>& rcBB) const
inline BoundBox3<Precision> BoundBox3<Precision>::Intersected(const BoundBox3<Precision>& rcBB) const
{
BoundBox3<Precision> cBBRes;
@@ -478,8 +491,10 @@ inline bool BoundBox3<Precision>::IsValid() const
}
template<class Precision>
inline bool BoundBox3<Precision>::GetOctantFromVector(const Vector3<Precision>& rclVct,
OCTANT& rclOctant) const
inline bool BoundBox3<Precision>::GetOctantFromVector(
const Vector3<Precision>& rclVct,
OCTANT& rclOctant
) const
{
if (!IsInBox(rclVct)) {
return false;
@@ -500,8 +515,9 @@ inline bool BoundBox3<Precision>::GetOctantFromVector(const Vector3<Precision>&
}
template<class Precision>
inline BoundBox3<Precision>
BoundBox3<Precision>::CalcOctant(typename BoundBox3<Precision>::OCTANT Octant) const
inline BoundBox3<Precision> BoundBox3<Precision>::CalcOctant(
typename BoundBox3<Precision>::OCTANT Octant
) const
{
BoundBox3<Precision> cOct(*this);
@@ -584,9 +600,11 @@ inline Vector3<Precision> BoundBox3<Precision>::CalcPoint(unsigned short usPoint
// NOLINTBEGIN(bugprone-easily-swappable-parameters)
template<class Precision>
inline void BoundBox3<Precision>::CalcPlane(unsigned short usPlane,
Vector3<Precision>& rBase,
Vector3<Precision>& rNormal) const
inline void BoundBox3<Precision>::CalcPlane(
unsigned short usPlane,
Vector3<Precision>& rBase,
Vector3<Precision>& rNormal
) const
// NOLINTEND(bugprone-easily-swappable-parameters)
{
switch (usPlane) {
@@ -625,9 +643,11 @@ inline void BoundBox3<Precision>::CalcPlane(unsigned short usPlane,
}
template<class Precision>
inline bool BoundBox3<Precision>::CalcEdge(unsigned short usEdge,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1) const
inline bool BoundBox3<Precision>::CalcEdge(
unsigned short usEdge,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1
) const
{
switch (usEdge) {
case TLB_TLF:
@@ -686,10 +706,12 @@ inline bool BoundBox3<Precision>::CalcEdge(unsigned short usEdge,
}
template<class Precision>
inline bool BoundBox3<Precision>::IntersectionPoint(const Vector3<Precision>& rcVct,
const Vector3<Precision>& rcVctDir,
Vector3<Precision>& cVctRes,
Precision epsilon) const
inline bool BoundBox3<Precision>::IntersectionPoint(
const Vector3<Precision>& rcVct,
const Vector3<Precision>& rcVctDir,
Vector3<Precision>& cVctRes,
Precision epsilon
) const
{
const unsigned short num = 6;
bool rc = false;
@@ -721,9 +743,11 @@ inline bool BoundBox3<Precision>::IntersectionPoint(const Vector3<Precision>& rc
}
template<class Precision>
inline bool BoundBox3<Precision>::IsCutLine(const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Precision fTolerance) const
inline bool BoundBox3<Precision>::IsCutLine(
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Precision fTolerance
) const
{
const unsigned short num = 6;
Precision fDist;
@@ -777,8 +801,10 @@ inline bool BoundBox3<Precision>::IsCutLine(const Vector3<Precision>& rcBase,
}
template<class Precision>
inline bool BoundBox3<Precision>::IsCutPlane(const Vector3<Precision>& rclBase,
const Vector3<Precision>& rclNormal) const
inline bool BoundBox3<Precision>::IsCutPlane(
const Vector3<Precision>& rclBase,
const Vector3<Precision>& rclNormal
) const
{
const unsigned short num = 8;
if (fabs(GetCenter().DistanceToPlane(rclBase, rclNormal)) < CalcDiagonalLength()) {
@@ -794,10 +820,12 @@ inline bool BoundBox3<Precision>::IsCutPlane(const Vector3<Precision>& rclBase,
// NOLINTBEGIN(bugprone-easily-swappable-parameters)
template<class Precision>
inline bool BoundBox3<Precision>::IntersectWithLine(const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1) const
inline bool BoundBox3<Precision>::IntersectWithLine(
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0,
Vector3<Precision>& rcP1
) const
// NOLINTEND(bugprone-easily-swappable-parameters)
{
const unsigned short num = 6;
@@ -819,18 +847,24 @@ inline bool BoundBox3<Precision>::IntersectWithLine(const Vector3<Precision>& rc
switch (i) {
case LEFT: // left and right plane
case RIGHT:
checkIntersect(Vector3<Precision> {MinY, MaxY, clVectRes.y},
Vector3<Precision> {MinZ, MaxZ, clVectRes.z});
checkIntersect(
Vector3<Precision> {MinY, MaxY, clVectRes.y},
Vector3<Precision> {MinZ, MaxZ, clVectRes.z}
);
break;
case TOP: // top and bottom plane
case BOTTOM:
checkIntersect(Vector3<Precision> {MinX, MaxX, clVectRes.x},
Vector3<Precision> {MinZ, MaxZ, clVectRes.z});
checkIntersect(
Vector3<Precision> {MinX, MaxX, clVectRes.x},
Vector3<Precision> {MinZ, MaxZ, clVectRes.z}
);
break;
case FRONT: // front and back plane
case BACK:
checkIntersect(Vector3<Precision> {MinX, MaxX, clVectRes.x},
Vector3<Precision> {MinY, MaxY, clVectRes.y});
checkIntersect(
Vector3<Precision> {MinX, MaxX, clVectRes.x},
Vector3<Precision> {MinY, MaxY, clVectRes.y}
);
break;
}
}
@@ -857,10 +891,12 @@ inline bool BoundBox3<Precision>::IntersectWithLine(const Vector3<Precision>& rc
// NOLINTBEGIN(bugprone-easily-swappable-parameters)
template<class Precision>
inline bool BoundBox3<Precision>::IntersectPlaneWithLine(unsigned short usSide,
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0) const
inline bool BoundBox3<Precision>::IntersectPlaneWithLine(
unsigned short usSide,
const Vector3<Precision>& rcBase,
const Vector3<Precision>& rcDir,
Vector3<Precision>& rcP0
) const
// NOLINTEND(bugprone-easily-swappable-parameters)
{
Precision value;
@@ -880,19 +916,21 @@ inline bool BoundBox3<Precision>::IntersectPlaneWithLine(unsigned short usSide,
}
template<class Precision>
inline typename BoundBox3<Precision>::SIDE
BoundBox3<Precision>::GetSideFromRay(const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir) const
inline typename BoundBox3<Precision>::SIDE BoundBox3<Precision>::GetSideFromRay(
const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir
) const
{
Vector3<Precision> cIntersection;
return GetSideFromRay(rclPt, rclDir, cIntersection);
}
template<class Precision>
inline typename BoundBox3<Precision>::SIDE
BoundBox3<Precision>::GetSideFromRay(const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir,
Vector3<Precision>& rcInt) const
inline typename BoundBox3<Precision>::SIDE BoundBox3<Precision>::GetSideFromRay(
const Vector3<Precision>& rclPt,
const Vector3<Precision>& rclDir,
Vector3<Precision>& rcInt
) const
{
Vector3<Precision> cP0;
Vector3<Precision> cP1;
@@ -1027,9 +1065,10 @@ inline Vector3<Precision> BoundBox3<Precision>::GetMaximum() const
template<class Precision>
inline Precision BoundBox3<Precision>::CalcDiagonalLength() const
{
return static_cast<Precision>(sqrt(((MaxX - MinX) * (MaxX - MinX))
+ ((MaxY - MinY) * (MaxY - MinY))
+ ((MaxZ - MinZ) * (MaxZ - MinZ))));
return static_cast<Precision>(sqrt(
((MaxX - MinX) * (MaxX - MinX)) + ((MaxY - MinY) * (MaxY - MinY))
+ ((MaxZ - MinZ) * (MaxZ - MinZ))
));
}
template<class Precision>
+54 -44
View File
@@ -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<BoundBoxPy*>(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<VectorPy*>(object1)->getVectorPtr()),
*(static_cast<VectorPy*>(object2)->getVectorPtr()));
if (PyArg_ParseTuple(args, "O!O!", &(VectorPy::Type), &object1, &(VectorPy::Type), &object2)) {
retVal = getBoundBoxPtr()->IsCutLine(
*(static_cast<VectorPy*>(object1)->getVectorPtr()),
*(static_cast<VectorPy*>(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<BoundBoxPy*>(object1)->getBoundBoxPtr()));
retVal = getBoundBoxPtr()->Intersect(
*(static_cast<BoundBoxPy*>(object1)->getBoundBoxPtr())
);
break;
}
@@ -294,8 +297,9 @@ PyObject* BoundBoxPy::intersected(PyObject* args)
return nullptr;
}
BoundBox3d bbox =
getBoundBoxPtr()->Intersected(*static_cast<BoundBoxPy*>(object)->getBoundBoxPtr());
BoundBox3d bbox = getBoundBoxPtr()->Intersected(
*static_cast<BoundBoxPy*>(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<VectorPy*>(object1)->getVectorPtr()),
*(static_cast<VectorPy*>(object2)->getVectorPtr()),
point,
epsilon);
bool ok = getBoundBoxPtr()->IntersectionPoint(
*(static_cast<VectorPy*>(object1)->getVectorPtr()),
*(static_cast<VectorPy*>(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<VectorPy*>(object)->getVectorPtr()),
*(static_cast<VectorPy*>(object2)->getVectorPtr()));
retVal = getBoundBoxPtr()->IsCutPlane(
*(static_cast<VectorPy*>(object)->getVectorPtr()),
*(static_cast<VectorPy*>(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<BoundBoxPy*>(object)->getBoundBoxPtr()));
retVal = getBoundBoxPtr()->IsInBox(*(static_cast<BoundBoxPy*>(object)->getBoundBoxPtr()));
break;
}
+27 -19
View File
@@ -248,9 +248,11 @@ public:
};
template<typename T>
void InventorFieldWriter::write(const char* fieldName,
const std::vector<T>& fieldData,
InventorOutput& out) const
void InventorFieldWriter::write(
const char* fieldName,
const std::vector<T>& fieldData,
InventorOutput& out
) const
{
if (fieldData.empty()) {
return;
@@ -273,9 +275,11 @@ void InventorFieldWriter::write(const char* fieldName,
}
template<>
void InventorFieldWriter::write<int>(const char* fieldName,
const std::vector<int>& fieldData,
InventorOutput& out) const
void InventorFieldWriter::write<int>(
const char* fieldName,
const std::vector<int>& 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<float>& uKnots,
const std::vector<float>& vKnots)
void NurbsSurfaceItem::setKnotVector(const std::vector<float>& uKnots, const std::vector<float>& 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<std::vector<int32_t>> InventorLoader::split(const std::vector<int32_
return splitdata;
}
std::vector<InventorLoader::Face>
InventorLoader::convert(const std::vector<std::vector<int32_t>>& coordIndex) const
std::vector<InventorLoader::Face> InventorLoader::convert(
const std::vector<std::vector<int32_t>>& coordIndex
) const
{
std::vector<Face> faces;
faces.reserve(coordIndex.size());
+28 -20
View File
@@ -33,7 +33,7 @@
#include <cstdint>
#include <Base/Tools3D.h>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#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<Vector3f> points,
DrawStyle drawStyle,
const ColorRGB& rgb = ColorRGB {1.0F, 1.0F, 1.0F});
explicit MultiLineItem(
std::vector<Vector3f> 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:
+14 -12
View File
@@ -27,7 +27,7 @@
#define APP_COLOR_H
#ifdef __GNUC__
#include <cstdint>
# include <cstdint>
#endif
#include <cmath>
#include <string>
@@ -165,10 +165,12 @@ public:
template<typename T>
static T fromPackedRGBA(uint32_t color)
{
return color_traits<T>::makeColor((color >> 24) & 0xff,
(color >> 16) & 0xff,
(color >> 8) & 0xff,
(color & 0xff));
return color_traits<T>::makeColor(
(color >> 24) & 0xff,
(color >> 16) & 0xff,
(color >> 8) & 0xff,
(color & 0xff)
);
}
template<typename T>
@@ -181,9 +183,7 @@ public:
template<typename T>
static T fromPackedRGB(uint32_t color)
{
return color_traits<T>::makeColor((color >> 24) & 0xff,
(color >> 16) & 0xff,
(color >> 8) & 0xff);
return color_traits<T>::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<Base::Color>
}
static color_type makeColor(int red, int green, int blue, int alpha = 255)
{
return color_type {static_cast<float>(red) / 255.0F,
static_cast<float>(green) / 255.0F,
static_cast<float>(blue) / 255.0F,
static_cast<float>(alpha) / 255.0F};
return color_type {
static_cast<float>(red) / 255.0F,
static_cast<float>(green) / 255.0F,
static_cast<float>(blue) / 255.0F,
static_cast<float>(alpha) / 255.0F
};
}
private:
+160 -115
View File
@@ -26,9 +26,9 @@
#include <FCConfig.h>
#if defined(FC_OS_WIN32)
#include <windows.h>
# include <windows.h>
#elif defined(FC_OS_LINUX) || defined(FC_OS_MACOSX)
#include <unistd.h>
# include <unistd.h>
#endif
#include <cstring>
#include <functional>
@@ -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<ConsoleEvent*>(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<LogStyle::Message, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
"%s",
msg);
instance().send<LogStyle::Message, IntendedRecipient::Developer, ContentType::Untranslatable>(
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<LogStyle::Warning, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
"%s",
msg);
instance().send<LogStyle::Warning, IntendedRecipient::Developer, ContentType::Untranslatable>(
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<LogStyle::Warning, IntendedRecipient::User, ContentType::Untranslated>(
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<LogStyle::Warning, IntendedRecipient::User, ContentType::Translated>(
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<LogStyle::Error, IntendedRecipient::All, ContentType::Untranslated>(
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<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
"%s",
msg);
instance().send<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
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<LogStyle::Error, IntendedRecipient::User, ContentType::Untranslated>(
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<LogStyle::Error, IntendedRecipient::User, ContentType::Translated>(
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<LogStyle::Log, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
"%s",
msg);
instance().send<LogStyle::Log, IntendedRecipient::Developer, ContentType::Untranslatable>(
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<LogStyle::Critical, IntendedRecipient::All, ContentType::Untranslated>(
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<LogStyle::Notification, IntendedRecipient::User, ContentType::Untranslated>(
notifier,
"%s",
msg);
instance().send<LogStyle::Notification, IntendedRecipient::User, ContentType::Untranslated>(
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<LogStyle::Notification, IntendedRecipient::User, ContentType::Translated>(
notifier,
"%s",
msg);
instance().send<LogStyle::Notification, IntendedRecipient::User, ContentType::Translated>(
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;
+98 -84
View File
@@ -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<LogStyle,
IntendedRecipient = IntendedRecipient::All,
ContentType = ContentType::Untranslated,
typename... Args>
template<LogStyle, IntendedRecipient = IntendedRecipient::All, ContentType = ContentType::Untranslated, typename... Args>
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<LogStyle,
IntendedRecipient = IntendedRecipient::All,
ContentType = ContentType::Untranslated>
template<LogStyle, IntendedRecipient = IntendedRecipient::All, ContentType = ContentType::Untranslated>
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<std::size_t>(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<typename... Args>
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<LogStyle::Warning, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
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<LogStyle::Warning, IntendedRecipient::User, ContentType::Untranslated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
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<LogStyle::Warning, IntendedRecipient::User, ContentType::Translated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
@@ -1071,26 +1077,28 @@ void Base::ConsoleSingleton::error(const std::string& notifier, const char* pMsg
}
template<typename... Args>
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<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
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<LogStyle::Error, IntendedRecipient::Developer, ContentType::Untranslatable>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(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<typename... Args>
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<LogStyle::Error, IntendedRecipient::User, ContentType::Untranslated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
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<LogStyle::Error, IntendedRecipient::User, ContentType::Translated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
@@ -1138,14 +1148,13 @@ void Base::ConsoleSingleton::userNotification(const char* pMsg, Args&&... args)
}
template<typename... Args>
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<LogStyle::Notification, IntendedRecipient::User, ContentType::Untranslated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
@@ -1155,14 +1164,17 @@ void Base::ConsoleSingleton::userTranslatedNotification(const char* pMsg, Args&&
}
template<typename... Args>
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<LogStyle::Notification, IntendedRecipient::User, ContentType::Translated>(
notifier,
pMsg,
std::forward<Args>(args)...);
std::forward<Args>(args)...
);
}
template<typename... Args>
@@ -1177,10 +1189,11 @@ void Base::ConsoleSingleton::log(const std::string& notifier, const char* pMsg,
send<LogStyle::Log>(notifier, pMsg, std::forward<Args>(args)...);
}
template<Base::LogStyle category,
Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/,
Base::ContentType contenttype /*= Base::ContentType::Untranslated*/,
typename... Args>
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<Base::LogStyle category,
Base::IntendedRecipient recipient /*= Base::IntendedRecipient::All*/,
Base::ContentType contenttype /*= Base::ContentType::Untranslated*/>
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
+38 -27
View File
@@ -26,7 +26,7 @@
#include <FCConfig.h>
#ifdef FC_OS_WIN32
#include <windows.h>
# include <windows.h>
#endif
#include <cstring>
#include <Python.h>
@@ -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
+21 -19
View File
@@ -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);
+11 -7
View File
@@ -101,9 +101,11 @@ Vec make_vec(const std::tuple<float_type, float_type, float_type>&& ft)
{
using traits_type = vec_traits<Vec>;
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<float_type, float_type, float_type, float_type>&&
{
using traits_type = vec_traits<Vec>;
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<class Vec1, class Vec2>
+11 -7
View File
@@ -41,8 +41,7 @@ std::string CoordinateSystemPy::representation() const
return {"<CoordinateSystem object>"};
}
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<AxisPy*>(axis)->getAxisPtr(),
*static_cast<VectorPy*>(xdir)->getVectorPtr());
getCoordinateSystemPtr()->setAxes(
*static_cast<AxisPy*>(axis)->getAxisPtr(),
*static_cast<VectorPy*>(xdir)->getVectorPtr()
);
Py_Return;
}
PyErr_Clear();
if (PyArg_ParseTuple(args, "O!O!", &(VectorPy::Type), &axis, &(VectorPy::Type), &xdir)) {
getCoordinateSystemPtr()->setAxes(*static_cast<VectorPy*>(axis)->getVectorPtr(),
*static_cast<VectorPy*>(xdir)->getVectorPtr());
getCoordinateSystemPtr()->setAxes(
*static_cast<VectorPy*>(axis)->getVectorPtr(),
*static_cast<VectorPy*>(xdir)->getVectorPtr()
);
Py_Return;
}
@@ -82,7 +85,8 @@ PyObject* CoordinateSystemPy::displacement(PyObject* args) const
return nullptr;
}
Placement plm = getCoordinateSystemPtr()->displacement(
*static_cast<CoordinateSystemPy*>(cs)->getCoordinateSystemPtr());
*static_cast<CoordinateSystemPy*>(cs)->getCoordinateSystemPtr()
);
return new PlacementPy(new Placement(plm));
}
+1 -1
View File
@@ -29,7 +29,7 @@
#include <QEventLoop>
#include <QObject>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
namespace Base
+14 -10
View File
@@ -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)
+7 -7
View File
@@ -590,9 +590,9 @@ PyObject* RestoreError::getPyExceptionType() const
// ---------------------------------------------------------
#if defined(__GNUC__) && defined(FC_OS_LINUX)
#include <stdexcept>
#include <iostream>
#include <csignal>
# include <stdexcept>
# include <iostream>
# include <csignal>
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)
+56 -45
View File
@@ -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<exc>((msg), std::source_location::current());
#define THROWMT(exc, msg) \
Base::setupAndThrowException<exc>((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<exc>((msg), std::source_location::current());
# define THROWMT(exc, msg) \
Base::setupAndThrowException<exc>((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<typename ExceptionType>
[[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<typename ExceptionType>
#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<exc>(msg, FC_THROW_INFO);
#define THROWMT(exc, msg) Base::setupAndThrowException<exc>(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<exc>(msg, FC_THROW_INFO);
# define THROWMT(exc, msg) Base::setupAndThrowException<exc>(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<typename ExceptionType>
[[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<typename ExceptionType>
//--------------------------------------------------------------------------------------------------
template<typename Exception>
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<Exception>(msg, location);
}
template<typename Exception>
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<Exception>(msg, location, true);
}
template<typename Exception>
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_<Exception>(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;
};
+1 -1
View File
@@ -31,7 +31,7 @@
#include <map>
#include <string>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
+4 -7
View File
@@ -32,9 +32,9 @@
#include <iostream>
#include <system_error>
#ifdef FC_OS_WIN32
#include <Windows.h>
# include <Windows.h>
#else
#include <unistd.h>
# include <unistd.h>
#endif
#include "FileInfo.h"
@@ -285,9 +285,7 @@ bool FileInfo::hasExtension(const char* Ext) const
bool FileInfo::hasExtension(std::initializer_list<const char*> 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<typename TP>
std::time_t to_time_t(TP tp)
{
using namespace std::chrono;
auto sctp =
time_point_cast<system_clock::duration>(tp - TP::clock::now() + system_clock::now());
auto sctp = time_point_cast<system_clock::duration>(tp - TP::clock::now() + system_clock::now());
return system_clock::to_time_t(sctp);
}
+3 -2
View File
@@ -117,8 +117,9 @@ Py::PythonClassObject<Vector2dPy> Vector2dPy::create(double vx, double vy)
Py::Tuple arg(2);
arg.setItem(0, Py::Float(vx));
arg.setItem(1, Py::Float(vy));
Py::PythonClassObject<Vector2dPy> py =
Py::PythonClassObject<Vector2dPy>(class_type.apply(arg, Py::Dict()));
Py::PythonClassObject<Vector2dPy> py = Py::PythonClassObject<Vector2dPy>(
class_type.apply(arg, Py::Dict())
);
return py;
}
+2 -4
View File
@@ -284,12 +284,10 @@ private:
};
// PyCXX wrapper classes Py::Matrix, Py::Rotation, Py::Placement, ...
using BoundingBox =
GeometryT<Base::BoundBox3d, Base::BoundBoxPy, &Base::BoundBoxPy::getBoundBoxPtr>;
using BoundingBox = GeometryT<Base::BoundBox3d, Base::BoundBoxPy, &Base::BoundBoxPy::getBoundBoxPtr>;
using Matrix = GeometryT<Base::Matrix4D, Base::MatrixPy, &Base::MatrixPy::getMatrixPtr>;
using Rotation = GeometryT<Base::Rotation, Base::RotationPy, &Base::RotationPy::getRotationPtr>;
using Placement =
GeometryT<Base::Placement, Base::PlacementPy, &Base::PlacementPy::getPlacementPtr>;
using Placement = GeometryT<Base::Placement, Base::PlacementPy, &Base::PlacementPy::getPlacementPtr>;
} // namespace Py
+1 -1
View File
@@ -28,7 +28,7 @@
#define BASE_HANDLE_H
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
+16 -13
View File
@@ -26,18 +26,18 @@
#include <qglobal.h>
#if QT_VERSION < 0x060000
#include <QTextCodec>
# include <QTextCodec>
#else
#include <QByteArray>
#include <QStringDecoder>
#include <QStringEncoder>
# include <QByteArray>
# include <QStringDecoder>
# include <QStringEncoder>
#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<char*>(toFill),
static_cast<int>(len),
&state);
const QString text
= textCodec->toUnicode(reinterpret_cast<char*>(toFill), static_cast<int>(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)
{
+8 -6
View File
@@ -31,11 +31,11 @@
#include <xercesc/util/BinInputStream.hpp>
#include <xercesc/sax/InputSource.hpp>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#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;
+58 -41
View File
@@ -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;
+39 -37
View File
@@ -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 <FCConfig.h>
#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 <CXX/Extensions.hxx>
@@ -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);
//@}
+17 -23
View File
@@ -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<Vector3d>(rclBase);
Vector3d dir = convertTo<Vector3d>(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, 4> Matrix4D::decompose() const
residualMatrix.setCol(3, Vector3d());
// find and extract rotation
int prim_dir = -1;
std::array<Vector3d, 3> dirs = {Vector3d(1., 0., 0.),
Vector3d(0., 1., 0.),
Vector3d(0., 0., 1.)};
std::array<Vector3d, 3> 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, 4> 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
+2 -3
View File
@@ -32,7 +32,7 @@
#include "Vector3D.h"
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#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);
+16 -10
View File
@@ -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<VectorPy*>(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<VectorPy*>(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<int>(type)))));
mod.callMemberFunction("ScaleType", Py::TupleN(Py::Long(static_cast<int>(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;
}
+28 -17
View File
@@ -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<void*>(ToObserv));
Base::Console().developerWarning(
std::string("Subject::Attach"),
"Observer %p already attached\n",
static_cast<void*>(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<void*>(ToObserv));
Base::Console().developerWarning(
std::string("Subject::Detach"),
"Observer %p already detached\n",
static_cast<void*>(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__)
+138 -114
View File
@@ -47,7 +47,7 @@
#include <FCConfig.h>
#ifdef FC_OS_LINUX
#include <unistd.h>
# include <unistd.h>
#endif
#include <boost/algorithm/string.hpp>
@@ -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<ParameterGrp>& 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<std::pair<std::string, std::string>>
ParameterGrp::GetAttributeMap(ParamType Type, const char* sFilter) const
std::vector<std::pair<std::string, std::string>> ParameterGrp::GetAttributeMap(
ParamType Type,
const char* sFilter
) const
{
std::vector<std::pair<std::string, std::string>> 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<DOMElement*>(pcTemp)
->getAttributes()
->getNamedItem(XStrLiteral("Name").unicodeForm())
->getNodeValue())
Name = StrX(
static_cast<DOMElement*>(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<DOMElement*>(pcTemp)->getAttribute(
XStrLiteral("Value").unicodeForm()))
.c_str());
res.emplace_back(
Name,
StrX(static_cast<DOMElement*>(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<long> 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<std::pair<std::string, long>> 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<unsigned long> 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<unsigned long> ParameterGrp::GetUnsigneds(const char* sFilter) const
return vrValues;
}
std::vector<std::pair<std::string, unsigned long>>
ParameterGrp::GetUnsignedMap(const char* sFilter) const
std::vector<std::pair<std::string, unsigned long>> ParameterGrp::GetUnsignedMap(const char* sFilter) const
{
std::vector<std::pair<std::string, unsigned long>> 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<double> 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<std::pair<std::string, double>> 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<std::string> ParameterGrp::GetASCIIs(const char* sFilter) const
return vrValues;
}
std::vector<std::pair<std::string, std::string>>
ParameterGrp::GetASCIIMap(const char* sFilter) const
std::vector<std::pair<std::string, std::string>> ParameterGrp::GetASCIIMap(const char* sFilter) const
{
std::vector<std::pair<std::string, std::string>> 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<Base::Color> ParameterGrp::GetColors(const char* sFilter) const
auto packed = GetUnsigneds(sFilter);
std::vector<Base::Color> result;
std::transform(packed.begin(),
packed.end(),
std::back_inserter(result),
[](const unsigned long lValue) {
return Color(static_cast<uint32_t>(lValue));
});
std::transform(
packed.begin(),
packed.end(),
std::back_inserter(result),
[](const unsigned long lValue) { return Color(static_cast<uint32_t>(lValue)); }
);
return result;
}
std::vector<std::pair<std::string, Base::Color>>
ParameterGrp::GetColorMap(const char* sFilter) const
std::vector<std::pair<std::string, Base::Color>> ParameterGrp::GetColorMap(const char* sFilter) const
{
auto packed = GetUnsignedMap(sFilter);
std::vector<std::pair<std::string, Base::Color>> result;
std::transform(packed.begin(),
packed.end(),
std::back_inserter(result),
[](const std::pair<std::string, unsigned long>& lValue) {
return std::make_pair(lValue.first,
Color(static_cast<uint32_t>(lValue.second)));
});
std::transform(
packed.begin(),
packed.end(),
std::back_inserter(result),
[](const std::pair<std::string, unsigned long>& lValue) {
return std::make_pair(lValue.first, Color(static_cast<uint32_t>(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<DOMElement*>(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<std::pair<ParameterGrp::ParamType, std::string>>
ParameterGrp::GetParameterNames(const char* sFilter) const
std::vector<std::pair<ParameterGrp::ParamType, std::string>> ParameterGrp::GetParameterNames(
const char* sFilter
) const
{
std::vector<std::pair<ParameterGrp::ParamType, std::string>> 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<DOMImplementationLS*>(impl)->createLSSerializer();
DOMLSSerializer* theSerializer = static_cast<DOMImplementationLS*>(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<DOMPrintFilter>(
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<const XMLByte*>(xsdStr.c_str()),
xsdStr.size(),
"Parameter.xsd");
MemBufInputSource xsdFile(
reinterpret_cast<const XMLByte*>(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) {
+56 -48
View File
@@ -40,13 +40,13 @@ using PyObject = struct _object;
#include <FCConfig.h>
#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 <map>
@@ -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<std::pair<std::string, std::string>>
GetAttributeMap(ParamType Type, const char* sFilter = nullptr) const;
std::vector<std::pair<std::string, std::string>> 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<std::pair<ParamType, std::string>>
GetParameterNames(const char* sFilter = nullptr) const;
std::vector<std::pair<ParamType, std::string>> GetParameterNames(
const char* sFilter = nullptr
) const;
//@}
@@ -348,8 +350,9 @@ public:
/// get a vector of all uint values in this group
std::vector<unsigned long> GetUnsigneds(const char* sFilter = nullptr) const;
/// get a map with all uint values and the keys of this group
std::vector<std::pair<std::string, unsigned long>>
GetUnsignedMap(const char* sFilter = nullptr) const;
std::vector<std::pair<std::string, unsigned long>> 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<Base::Color> GetColors(const char* sFilter = nullptr) const;
/// get a map with all color values and the keys of this group
std::vector<std::pair<std::string, Base::Color>>
GetColorMap(const char* sFilter = nullptr) const;
std::vector<std::pair<std::string, Base::Color>> 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<std::string> GetASCIIs(const char* sFilter = nullptr) const;
/// Same as GetASCIIs() but with key,value map
std::vector<std::pair<std::string, std::string>>
GetASCIIMap(const char* sFilter = nullptr) const;
std::vector<std::pair<std::string, std::string>> 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<void(ParameterGrp* /*param*/,
ParamType /*type*/,
const char* /*name*/,
const char* /*value*/)>
boost::signals2::signal<
void(ParameterGrp* /*param*/, ParamType /*type*/, const char* /*name*/, const char* /*value*/)>
signalParamChanged;
int LoadDocument(const char* sFileName);
+36 -29
View File
@@ -26,7 +26,7 @@
#include <FCConfig.h>
#ifdef FC_OS_WIN32
#include <xercesc/sax/SAXParseException.hpp>
# include <xercesc/sax/SAXParseException.hpp>
#endif
#include <list>
#include <sstream>
@@ -34,7 +34,7 @@
#include <utility>
#ifdef FC_OS_LINUX
#include <unistd.h>
# include <unistd.h>
#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();
+7 -4
View File
@@ -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 (...) {
+1 -2
View File
@@ -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;
+8 -13
View File
@@ -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<PlacementPy*>(v)->getPlacementPtr();
Placement p2 = *static_cast<PlacementPy*>(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<PlacementPy*>(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<double>(Py::Float(tuple[0])),
static_cast<double>(Py::Float(tuple[1])),
static_cast<double>(Py::Float(tuple[2])),
static_cast<double>(Py::Float(tuple[3]))));
getPlacementPtr()->setRotation(Rotation(
static_cast<double>(Py::Float(tuple[0])),
static_cast<double>(Py::Float(tuple[1])),
static_cast<double>(Py::Float(tuple[2])),
static_cast<double>(Py::Float(tuple[3]))
));
return;
}
+8 -8
View File
@@ -44,17 +44,17 @@
#include <locale>
#ifdef FC_OS_WIN32
#include <direct.h>
#include <windows.h>
#include <crtdbg.h>
#include <shellapi.h>
#include <Rpc.h>
# include <direct.h>
# include <windows.h>
# include <crtdbg.h>
# include <shellapi.h>
# include <Rpc.h>
#endif
#if defined(FC_OS_LINUX) || defined(FC_OS_CYGWIN) || defined(FC_OS_MACOSX) || defined(FC_OS_BSD)
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
# include <dirent.h>
# include <unistd.h>
# include <sys/stat.h>
#endif
// STL
+89 -89
View File
@@ -22,113 +22,113 @@
***************************************************************************/
#ifdef TRACY_ENABLE
#include <tracy/Tracy.hpp>
# include <tracy/Tracy.hpp>
#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
+1 -2
View File
@@ -87,8 +87,7 @@ public:
* @param isForce If true, indicates a forced update even if the change threshold (1%) hasnt
* 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)
{}
};
+1 -2
View File
@@ -58,8 +58,7 @@ bool ProgressIndicatorPy::check(PyObject* py)
return Py::PythonExtension<ProgressIndicatorPy>::check(py);
}
PyObject*
ProgressIndicatorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/)
PyObject* ProgressIndicatorPy::PyMake(PyTypeObject* /*unused*/, PyObject* /*unused*/, PyObject* /*unused*/)
{
return new ProgressIndicatorPy();
}
+9 -9
View File
@@ -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 <Python.h>
@@ -46,13 +46,13 @@
#include <FCConfig.h>
#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
+9 -7
View File
@@ -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<size_t arraySize>
bool Wrapped_ParseTupleAndKeywords(PyObject* args,
PyObject* kw,
const char* format,
const std::array<const char*, arraySize> keywords,
...)
bool Wrapped_ParseTupleAndKeywords(
PyObject* args,
PyObject* kw,
const char* format,
const std::array<const char*, arraySize> 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<char**>(keywords.data()), va);
int retval
= PyArg_VaParseTupleAndKeywords(args, kw, format, const_cast<char**>(keywords.data()), va);
va_end(va);
return retval != 0; // Convert to a true C++ boolean
}
+6 -5
View File
@@ -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;
+6 -4
View File
@@ -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;
+31 -27
View File
@@ -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<signed char>(other.myValue)));
return Quantity(
std::pow(myValue, other.myValue),
myUnit.pow(static_cast<signed char>(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<double>::min());
+2 -4
View File
@@ -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
+2 -5
View File
@@ -229,11 +229,8 @@ PyObject* QuantityPy::getValueAs(PyObject* args) const
return Quantity::parse(str);
};
const std::vector<std::function<std::optional<Quantity>()>> funcs = {tryQuantity,
tryUnit,
tryUnitAndValue,
tryUnitPartsAndValue,
tryString};
const std::vector<std::function<std::optional<Quantity>()>> funcs
= {tryQuantity, tryUnit, tryUnitAndValue, tryUnitPartsAndValue, tryString};
auto tryFuncs = [&]() -> std::optional<Quantity> {
for (const auto& func : funcs) {
+41 -31
View File
@@ -43,13 +43,13 @@
#include "XMLTools.h"
#ifdef _MSC_VER
#include <zipios++/zipios-config.h>
# include <zipios++/zipios-config.h>
#endif
#include <zipios++/zipinputstream.h>
#include <boost/iostreams/filtering_stream.hpp>
#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<bool>(const char* AttrName,
bool defaultValue) const;
template BaseExport bool Base::XMLReader::getAttribute<bool>(
const char* AttrName,
bool defaultValue
) const;
template BaseExport bool Base::XMLReader::getAttribute<bool>(const char* AttrName) const;
template BaseExport const char*
Base::XMLReader::getAttribute<const char*>(const char* AttrName, const char* defaultValue) const;
template BaseExport const char*
Base::XMLReader::getAttribute<const char*>(const char* AttrName) const;
template BaseExport double Base::XMLReader::getAttribute<double>(const char* AttrName,
double defaultValue) const;
template BaseExport const char* Base::XMLReader::getAttribute<const char*>(
const char* AttrName,
const char* defaultValue
) const;
template BaseExport const char* Base::XMLReader::getAttribute<const char*>(const char* AttrName) const;
template BaseExport double Base::XMLReader::getAttribute<double>(
const char* AttrName,
double defaultValue
) const;
template BaseExport double Base::XMLReader::getAttribute<double>(const char* AttrName) const;
template BaseExport int Base::XMLReader::getAttribute<int>(const char* AttrName,
int defaultValue) const;
template BaseExport int Base::XMLReader::getAttribute<int>(const char* AttrName, int defaultValue) const;
template BaseExport int Base::XMLReader::getAttribute<int>(const char* AttrName) const;
template BaseExport long Base::XMLReader::getAttribute<long>(const char* AttrName,
long defaultValue) const;
template BaseExport long Base::XMLReader::getAttribute<long>(
const char* AttrName,
long defaultValue
) const;
template BaseExport long Base::XMLReader::getAttribute<long>(const char* AttrName) const;
template BaseExport unsigned long
Base::XMLReader::getAttribute<unsigned long>(const char* AttrName,
unsigned long defaultValue) const;
template BaseExport unsigned long
Base::XMLReader::getAttribute<unsigned long>(const char* AttrName) const;
template BaseExport unsigned long Base::XMLReader::getAttribute<unsigned long>(
const char* AttrName,
unsigned long defaultValue
) const;
template BaseExport unsigned long Base::XMLReader::getAttribute<unsigned long>(
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<std::streamsize>(Characters.size()) - CharacterOffset;
std::streamsize copy_size = static_cast<std::streamsize>(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<boost::iostreams::filtering_istream*>(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();
+15 -14
View File
@@ -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<typename T>
static constexpr bool instantiated =
std::is_same_v<T, bool> || std::is_same_v<T, const char*> || std::is_same_v<T, double>
|| std::is_same_v<T, int> || std::is_same_v<T, long> || std::is_same_v<T, unsigned long>;
static constexpr bool instantiated = std::is_same_v<T, bool> || std::is_same_v<T, const char*>
|| std::is_same_v<T, double> || std::is_same_v<T, int> || std::is_same_v<T, long>
|| std::is_same_v<T, unsigned long>;
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<T>(
getAttribute<unsigned long>(AttrName, static_cast<unsigned long>(defaultValue)));
getAttribute<unsigned long>(AttrName, static_cast<unsigned long>(defaultValue))
);
}
/// Enum classes
template<typename T>
@@ -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;
//@}
+49 -41
View File
@@ -167,8 +167,10 @@ void Rotation::getValue(Matrix4D& matrix) const
{
// Taken from <http://de.wikipedia.org/wiki/Quaternionen>
//
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);
+8 -7
View File
@@ -28,7 +28,7 @@
#include "Vector3D.h"
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#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();
+2 -3
View File
@@ -44,9 +44,8 @@ std::string RotationPy::representation() const
Py::Float q3(ptr->getValue()[3]);
std::stringstream str;
str << "Rotation (";
str << static_cast<std::string>(q0.repr()) << ", " << static_cast<std::string>(q1.repr())
<< ", " << static_cast<std::string>(q2.repr()) << ", "
<< static_cast<std::string>(q3.repr());
str << static_cast<std::string>(q0.repr()) << ", " << static_cast<std::string>(q1.repr()) << ", "
<< static_cast<std::string>(q2.repr()) << ", " << static_cast<std::string>(q3.repr());
str << ")";
return str.str();
+6 -6
View File
@@ -130,12 +130,12 @@ public:
std::list<T*> result(source.size());
std::transform(source.begin(),
source.end(),
result.begin(),
[](const ServiceDescriptor& descriptor) {
return descriptor.get<T>();
});
std::transform(
source.begin(),
source.end(),
result.begin(),
[](const ServiceDescriptor& descriptor) { return descriptor.get<T>(); }
);
return result;
}
+204 -185
View File
@@ -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
}
+10 -10
View File
@@ -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
+28 -35
View File
@@ -25,7 +25,7 @@
#include <QBuffer>
#include <QIODevice>
#ifdef __GNUC__
#include <cstdint>
# include <cstdint>
#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);
}
+54 -30
View File
@@ -27,7 +27,7 @@
#define BASE_STREAM_H
#ifdef __GNUC__
#include <cstdint>
# include <cstdint>
#endif
#include <fstream>
@@ -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
+2 -2
View File
@@ -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<Py_ssize_t>(s.size()), "strict");
PyObject* unicode
= PyUnicode_DecodeUnicodeEscape(s.c_str(), static_cast<Py_ssize_t>(s.size()), "strict");
if (!unicode) {
return string;
}
+1 -1
View File
@@ -27,7 +27,7 @@
#define SRC_BASE_TOOLS_H_
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
#include <cmath>
#include <numbers>
+1 -2
View File
@@ -335,8 +335,7 @@ bool Polygon2d::Contains(const Vector2d& rclV) const
return sTorsion != 0;
}
void Polygon2d::Intersect(const Polygon2d& rclPolygon,
std::list<Polygon2d>& rclResultPolygonList) const
void Polygon2d::Intersect(const Polygon2d& rclPolygon, std::list<Polygon2d>& 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
+1 -1
View File
@@ -32,7 +32,7 @@
#include <vector>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
+1 -1
View File
@@ -27,7 +27,7 @@
#define BASE_TOOLS3D_H
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
#include <cmath>
+55 -43
View File
@@ -33,49 +33,61 @@ using namespace Base;
Translate::Translate()
: Py::ExtensionModule<Translate>("__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
}
+1 -1
View File
@@ -31,7 +31,7 @@
#include <memory>
#include <list>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
namespace Py
+15 -14
View File
@@ -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;
}
+11 -5
View File
@@ -33,7 +33,7 @@
#include <set>
#include <vector>
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
namespace Base
@@ -112,13 +112,19 @@ public:
/// Returns all descendants from the given type
static int getAllDerivedFrom(const Type type, std::vector<Type>& 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
+20 -17
View File
@@ -29,8 +29,9 @@
#include "UniqueNameManager.h"
std::tuple<std::string, std::string, unsigned int, Base::UnlimitedUnsigned>
Base::UniqueNameManager::decomposeName(const std::string& name) const
std::tuple<std::string, std::string, unsigned int, Base::UnlimitedUnsigned> 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<PiecewiseSparseIntegerSet<UnlimitedUnsigned>>())
.first;
baseNameEntry
= uniqueSeeds
.emplace(baseName, std::vector<PiecewiseSparseIntegerSet<UnlimitedUnsigned>>())
.first;
}
if (digitCount >= baseNameEntry->second.size()) {
// First use of this digitCount
baseNameEntry->second.resize(digitCount + 1);
}
PiecewiseSparseIntegerSet<UnlimitedUnsigned>& baseNameAndDigitCountEntry =
baseNameEntry->second[digitCount];
PiecewiseSparseIntegerSet<UnlimitedUnsigned>& 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);
+5 -5
View File
@@ -26,7 +26,7 @@
#define SRC_BASE_UNIQUENAMEMANAGER_H_
#ifndef FC_GLOBAL_H
#include <FCGlobal.h>
# include <FCGlobal.h>
#endif
#include <vector>
#include <string>
@@ -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<std::string, std::string, unsigned int, UnlimitedUnsigned>
decomposeName(const std::string& name) const;
std::tuple<std::string, std::string, unsigned int, UnlimitedUnsigned> decomposeName(
const std::string& name
) const;
public:
UniqueNameManager() = default;
+22 -17
View File
@@ -110,20 +110,24 @@ constexpr auto unitSpecs = std::to_array<UnitSpec>({
{ "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<int8_t>(std::clamp<decltype(val)>(val,
std::numeric_limits<int8_t>::min(),
std::numeric_limits<int8_t>::max()));
return static_cast<int8_t>(std::clamp<decltype(val)>(
val,
std::numeric_limits<int8_t>::min(),
std::numeric_limits<int8_t>::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
@@ -342,10 +347,10 @@ constexpr Unit Unit::InverseArea = make("InverseArea"
constexpr Unit Unit::InverseLength = make("InverseLength" );
constexpr Unit Unit::InverseVolume = make("InverseVolume" );
constexpr Unit Unit::KinematicViscosity = make("KinematicViscosity" );
constexpr Unit Unit::MagneticFieldStrength = make("Magnetization" );
constexpr Unit Unit::MagneticFieldStrength = make("MagneticFieldStrength" );
constexpr Unit Unit::MagneticFlux = make("MagneticFlux" );
constexpr Unit Unit::MagneticFluxDensity = make("MagneticFluxDensity" );
constexpr Unit Unit::Magnetization = make("MagneticFieldStrength" );
constexpr Unit Unit::Magnetization = make("Magnetization" );
constexpr Unit Unit::Moment = make("Moment" );
constexpr Unit Unit::Pressure = make("Pressure" );
constexpr Unit Unit::Power = make("Power" );
+13 -10
View File
@@ -36,8 +36,9 @@
namespace Base
{
constexpr auto unitSymbols =
std::to_array<std::string_view>({"mm", "kg", "s", "A", "K", "mol", "cd", "deg"});
constexpr auto unitSymbols = std::to_array<std::string_view>(
{"mm", "kg", "s", "A", "K", "mol", "cd", "deg"}
);
constexpr auto unitNumExponents {unitSymbols.size()};
using UnitExponents = std::array<int8_t, unitNumExponents>;
@@ -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;
+1 -2
View File
@@ -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;
+1 -2
View File
@@ -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);
}
+2 -4
View File
@@ -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<UnitsSchemas>(UnitsSchemasData::unitSchemasDataPack);
static inline auto schemas = std::make_unique<UnitsSchemas>(UnitsSchemasData::unitSchemasDataPack);
static inline int decimals {-1};
static inline int denominator {-1};
+4 -2
View File
@@ -160,8 +160,10 @@ PyObject* UnitsApi::sSchemaTranslate(PyObject* /*self*/, PyObject* args)
}
if (index < 0 || index >= static_cast<int>(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;
}
+20 -20
View File
@@ -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<QLocale::NumberOptions>(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;

Some files were not shown because too many files have changed in this diff Show More