slidercad 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slidercad-0.1.0/.gitignore +20 -0
- slidercad-0.1.0/LICENSE +201 -0
- slidercad-0.1.0/PKG-INFO +89 -0
- slidercad-0.1.0/README.md +61 -0
- slidercad-0.1.0/pyproject.toml +40 -0
- slidercad-0.1.0/slidercad/__init__.py +23 -0
- slidercad-0.1.0/slidercad/libraries.py +299 -0
- slidercad-0.1.0/slidercad/params.py +261 -0
- slidercad-0.1.0/slidercad/py.typed +0 -0
- slidercad-0.1.0/slidercad/runner.py +123 -0
- slidercad-0.1.0/tests/test_slidercad_pkg.py +243 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
.task
|
|
2
|
+
bin
|
|
3
|
+
frontend/dist
|
|
4
|
+
frontend/bindings
|
|
5
|
+
frontend/node_modules
|
|
6
|
+
build/linux/*.desktop
|
|
7
|
+
build/linux/appimage/build
|
|
8
|
+
build/darwin/icons.icns
|
|
9
|
+
build/darwin/Assets.car
|
|
10
|
+
build/windows/icon.ico
|
|
11
|
+
build/windows/nsis/MicrosoftEdgeWebview2Setup.exe
|
|
12
|
+
__pycache__/
|
|
13
|
+
*.pyc
|
|
14
|
+
.venv/
|
|
15
|
+
venv/
|
|
16
|
+
.pytest_cache/
|
|
17
|
+
*.exe
|
|
18
|
+
|
|
19
|
+
# Wails embeds the Windows resource object at build time
|
|
20
|
+
*.syso
|
slidercad-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Work; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the NOTICE text file contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Work, in at least one of the
|
|
111
|
+
following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright notice to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the NOTICE text.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate intent and
|
|
156
|
+
gross negligence) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Luke Covalt
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
slidercad-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: slidercad
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Parameter metadata, cross-library imports, and standalone export helpers for SliderCAD build123d models.
|
|
5
|
+
Project-URL: Homepage, https://slidercad.com
|
|
6
|
+
Project-URL: Repository, https://github.com/slidercad/slidercad
|
|
7
|
+
Project-URL: Documentation, https://github.com/slidercad/slidercad/blob/main/docs/MODEL_CONTRACT.md
|
|
8
|
+
Project-URL: Issues, https://github.com/slidercad/slidercad/issues
|
|
9
|
+
Author: Luke Covalt
|
|
10
|
+
License-Expression: Apache-2.0
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: 3d-printing,build123d,cad,parametric,slidercad
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: Manufacturing
|
|
16
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
24
|
+
Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.10
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# slidercad
|
|
30
|
+
|
|
31
|
+
Zero-dependency Python helpers for writing parametric [`build123d`](https://build123d.readthedocs.io/) models compatible with [SliderCAD](https://slidercad.com).
|
|
32
|
+
|
|
33
|
+
Models remain plain Python `@dataclass` files that run standalone with or without the SliderCAD desktop app.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install slidercad
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
SliderCAD also bundles this package inside its worker and installs it automatically into its managed Python environment.
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
```python
|
|
46
|
+
from dataclasses import dataclass
|
|
47
|
+
from slidercad import default_preset, group, param, run_model
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass
|
|
51
|
+
class CoreParams:
|
|
52
|
+
width: float = param(40.0, desc="Overall width", unit="mm", min=5.0, max=300.0, step=1.0)
|
|
53
|
+
depth: float = param(30.0, desc="Overall depth", unit="mm", min=5.0, max=300.0, step=1.0)
|
|
54
|
+
height: float = param(10.0, desc="Overall height", unit="mm", min=1.0, max=200.0, step=0.5)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@default_preset("Standard Block", desc="Default starter dimensions")
|
|
58
|
+
@dataclass
|
|
59
|
+
class BlockParams:
|
|
60
|
+
core: CoreParams = group(CoreParams)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def create_block(params: BlockParams):
|
|
64
|
+
import build123d as b3d
|
|
65
|
+
|
|
66
|
+
with b3d.BuildPart() as bp:
|
|
67
|
+
b3d.Box(params.core.width, params.core.depth, params.core.height)
|
|
68
|
+
return bp.part
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
if __name__ == "__main__":
|
|
72
|
+
params = BlockParams()
|
|
73
|
+
part = create_block(params)
|
|
74
|
+
run_model(part, "block", stl=False, step=False)
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
### Public API
|
|
78
|
+
|
|
79
|
+
- **`param(default, *, label, desc, item_label, unit, min, max, step, when)`** — defines a typed dataclass field with standard `dataclasses.Field.metadata`.
|
|
80
|
+
- **`param_list(factory, *, ...)`** — defines a list-of-items dataclass field with structured metadata.
|
|
81
|
+
- **`group(factory, *, enabled=True, preset=None, params=None, label, desc, when)`** — embeds a nested parameter group or reusable component (with optional preset and sparse default overrides).
|
|
82
|
+
- **`@default_preset(label, *, desc=None)`** — attaches a display label and description to a root `Params` dataclass.
|
|
83
|
+
- **`register_libraries(caller_file=None, *, aliases=None)`** — adds the active library root to `sys.path` and binds cross-library namespaces declared in `library.json` for standalone CLI runs.
|
|
84
|
+
- **`run_model(part, stem, *, stl=False, step=False, threemf=False, output_dir=None, show_part=True)`** — exports requested formats to `<library_root>/exports/` and opens `ocp_viewer` / `ocp_vscode` when installed.
|
|
85
|
+
- **`show_in_viewer(*args, **kwargs)`** and **`get_exports_dir(output_dir=None)`** — standalone viewer and export-path helpers.
|
|
86
|
+
|
|
87
|
+
## License
|
|
88
|
+
|
|
89
|
+
Apache License 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# slidercad
|
|
2
|
+
|
|
3
|
+
Zero-dependency Python helpers for writing parametric [`build123d`](https://build123d.readthedocs.io/) models compatible with [SliderCAD](https://slidercad.com).
|
|
4
|
+
|
|
5
|
+
Models remain plain Python `@dataclass` files that run standalone with or without the SliderCAD desktop app.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install slidercad
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
SliderCAD also bundles this package inside its worker and installs it automatically into its managed Python environment.
|
|
14
|
+
|
|
15
|
+
## Usage
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
from slidercad import default_preset, group, param, run_model
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class CoreParams:
|
|
24
|
+
width: float = param(40.0, desc="Overall width", unit="mm", min=5.0, max=300.0, step=1.0)
|
|
25
|
+
depth: float = param(30.0, desc="Overall depth", unit="mm", min=5.0, max=300.0, step=1.0)
|
|
26
|
+
height: float = param(10.0, desc="Overall height", unit="mm", min=1.0, max=200.0, step=0.5)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@default_preset("Standard Block", desc="Default starter dimensions")
|
|
30
|
+
@dataclass
|
|
31
|
+
class BlockParams:
|
|
32
|
+
core: CoreParams = group(CoreParams)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def create_block(params: BlockParams):
|
|
36
|
+
import build123d as b3d
|
|
37
|
+
|
|
38
|
+
with b3d.BuildPart() as bp:
|
|
39
|
+
b3d.Box(params.core.width, params.core.depth, params.core.height)
|
|
40
|
+
return bp.part
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == "__main__":
|
|
44
|
+
params = BlockParams()
|
|
45
|
+
part = create_block(params)
|
|
46
|
+
run_model(part, "block", stl=False, step=False)
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Public API
|
|
50
|
+
|
|
51
|
+
- **`param(default, *, label, desc, item_label, unit, min, max, step, when)`** — defines a typed dataclass field with standard `dataclasses.Field.metadata`.
|
|
52
|
+
- **`param_list(factory, *, ...)`** — defines a list-of-items dataclass field with structured metadata.
|
|
53
|
+
- **`group(factory, *, enabled=True, preset=None, params=None, label, desc, when)`** — embeds a nested parameter group or reusable component (with optional preset and sparse default overrides).
|
|
54
|
+
- **`@default_preset(label, *, desc=None)`** — attaches a display label and description to a root `Params` dataclass.
|
|
55
|
+
- **`register_libraries(caller_file=None, *, aliases=None)`** — adds the active library root to `sys.path` and binds cross-library namespaces declared in `library.json` for standalone CLI runs.
|
|
56
|
+
- **`run_model(part, stem, *, stl=False, step=False, threemf=False, output_dir=None, show_part=True)`** — exports requested formats to `<library_root>/exports/` and opens `ocp_viewer` / `ocp_vscode` when installed.
|
|
57
|
+
- **`show_in_viewer(*args, **kwargs)`** and **`get_exports_dir(output_dir=None)`** — standalone viewer and export-path helpers.
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
Apache License 2.0 — see [LICENSE](LICENSE).
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.24"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "slidercad"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Parameter metadata, cross-library imports, and standalone export helpers for SliderCAD build123d models."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
requires-python = ">=3.10"
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "Luke Covalt" },
|
|
15
|
+
]
|
|
16
|
+
keywords = ["build123d", "cad", "parametric", "3d-printing", "slidercad"]
|
|
17
|
+
classifiers = [
|
|
18
|
+
"Development Status :: 3 - Alpha",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Intended Audience :: Manufacturing",
|
|
21
|
+
"License :: OSI Approved :: Apache Software License",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3.10",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
29
|
+
"Topic :: Multimedia :: Graphics :: 3D Modeling",
|
|
30
|
+
"Typing :: Typed",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
[project.urls]
|
|
34
|
+
Homepage = "https://slidercad.com"
|
|
35
|
+
Repository = "https://github.com/slidercad/slidercad"
|
|
36
|
+
Documentation = "https://github.com/slidercad/slidercad/blob/main/docs/MODEL_CONTRACT.md"
|
|
37
|
+
Issues = "https://github.com/slidercad/slidercad/issues"
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["slidercad"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: Copyright 2026 Luke Covalt
|
|
3
|
+
"""Parameter metadata, library resolution, and standalone export helpers for SliderCAD models."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from .libraries import register_libraries
|
|
8
|
+
from .params import default_preset, group, param, param_list
|
|
9
|
+
from .runner import get_exports_dir, run_model, show_in_viewer
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.0"
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"__version__",
|
|
15
|
+
"default_preset",
|
|
16
|
+
"get_exports_dir",
|
|
17
|
+
"group",
|
|
18
|
+
"param",
|
|
19
|
+
"param_list",
|
|
20
|
+
"register_libraries",
|
|
21
|
+
"run_model",
|
|
22
|
+
"show_in_viewer",
|
|
23
|
+
]
|
|
@@ -0,0 +1,299 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: Copyright 2026 Luke Covalt
|
|
3
|
+
"""Cross-library namespace resolution for standalone SliderCAD model execution."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import importlib.machinery
|
|
8
|
+
import importlib.util
|
|
9
|
+
import inspect
|
|
10
|
+
import json
|
|
11
|
+
import keyword
|
|
12
|
+
import os
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
import re
|
|
15
|
+
import sys
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _norm_ns_id(raw: Any) -> str:
|
|
20
|
+
if not isinstance(raw, str):
|
|
21
|
+
return ""
|
|
22
|
+
s = re.sub(r"[^a-z0-9_]+", "_", raw.strip().lower()).strip("_")
|
|
23
|
+
if not s or not s.isidentifier() or keyword.iskeyword(s):
|
|
24
|
+
return ""
|
|
25
|
+
return s
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _norm_lib_source(raw: Any) -> str:
|
|
29
|
+
if not isinstance(raw, str):
|
|
30
|
+
return ""
|
|
31
|
+
s = raw.strip()
|
|
32
|
+
if not s:
|
|
33
|
+
return ""
|
|
34
|
+
for prefix in ("https://", "http://", "ssh://", "git://"):
|
|
35
|
+
if s.lower().startswith(prefix):
|
|
36
|
+
s = s[len(prefix):]
|
|
37
|
+
break
|
|
38
|
+
if s.startswith("git@") and ":" in s:
|
|
39
|
+
host, rest = s[4:].split(":", 1)
|
|
40
|
+
s = f"{host}/{rest}"
|
|
41
|
+
s = s.rstrip("/")
|
|
42
|
+
if s.lower().endswith(".git"):
|
|
43
|
+
s = s[:-4]
|
|
44
|
+
return s.rstrip("/").lower()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _slidercad_config_path() -> Path:
|
|
48
|
+
if sys.platform == "win32":
|
|
49
|
+
base = os.environ.get("APPDATA") or str(Path.home() / "AppData" / "Roaming")
|
|
50
|
+
return Path(base) / "slidercad" / "config.json"
|
|
51
|
+
if sys.platform == "darwin":
|
|
52
|
+
return Path.home() / "Library" / "Application Support" / "slidercad" / "config.json"
|
|
53
|
+
base = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config")
|
|
54
|
+
return Path(base) / "slidercad" / "config.json"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _read_lib_manifest(root: Path) -> dict[str, Any]:
|
|
58
|
+
manifest_path = root / "library.json"
|
|
59
|
+
if not manifest_path.is_file():
|
|
60
|
+
return {"id": "", "source": "", "requires": []}
|
|
61
|
+
try:
|
|
62
|
+
raw = json.loads(manifest_path.read_text(encoding="utf-8-sig"))
|
|
63
|
+
except (OSError, ValueError):
|
|
64
|
+
return {"id": "", "source": "", "requires": []}
|
|
65
|
+
if not isinstance(raw, dict):
|
|
66
|
+
return {"id": "", "source": "", "requires": []}
|
|
67
|
+
manifest_id = _norm_ns_id(raw.get("id"))
|
|
68
|
+
source = _norm_lib_source(raw.get("source"))
|
|
69
|
+
requires: list[dict[str, str]] = []
|
|
70
|
+
for item in raw.get("requires") or []:
|
|
71
|
+
if not isinstance(item, dict):
|
|
72
|
+
continue
|
|
73
|
+
req_id = _norm_ns_id(item.get("id"))
|
|
74
|
+
req_source = _norm_lib_source(item.get("source"))
|
|
75
|
+
repo_alias = _norm_ns_id(req_source.rsplit("/", 1)[-1]) if req_source else ""
|
|
76
|
+
alias = _norm_ns_id(item.get("as")) or req_id or repo_alias
|
|
77
|
+
if alias and (req_id or req_source):
|
|
78
|
+
requires.append({"id": req_id, "source": req_source, "alias": alias})
|
|
79
|
+
return {"id": manifest_id, "source": source, "requires": requires}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _dir_has_py(directory: Path) -> bool:
|
|
83
|
+
if not directory.is_dir():
|
|
84
|
+
return False
|
|
85
|
+
for _dirpath, dirnames, filenames in os.walk(directory):
|
|
86
|
+
dirnames[:] = [d for d in dirnames if not d.startswith(".") and d != "__pycache__"]
|
|
87
|
+
if any(f.lower().endswith((".py", ".pyi", ".so", ".pyd")) for f in filenames):
|
|
88
|
+
return True
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _has_local_module(root: Path | None, alias: str) -> bool:
|
|
93
|
+
if root is None or not alias:
|
|
94
|
+
return False
|
|
95
|
+
base = root / alias
|
|
96
|
+
return base.with_suffix(".py").is_file() or (base / "__init__.py").is_file() or _dir_has_py(base)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _looks_like_library(directory: Path) -> bool:
|
|
100
|
+
if (directory / "library.json").is_file():
|
|
101
|
+
return True
|
|
102
|
+
if (directory / "utils" / "params.py").is_file():
|
|
103
|
+
return True
|
|
104
|
+
if (directory / "components").is_dir() or (directory / "models").is_dir():
|
|
105
|
+
return True
|
|
106
|
+
try:
|
|
107
|
+
for child in directory.iterdir():
|
|
108
|
+
if child.name.startswith(".") or child.name.startswith("_"):
|
|
109
|
+
continue
|
|
110
|
+
if child.is_file() and child.suffix == ".py":
|
|
111
|
+
return True
|
|
112
|
+
if child.is_dir() and (child / f"{child.name}.py").is_file():
|
|
113
|
+
return True
|
|
114
|
+
except OSError:
|
|
115
|
+
return False
|
|
116
|
+
return False
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _find_current_library_root(caller_file: str | Path | None) -> Path | None:
|
|
120
|
+
if caller_file is None:
|
|
121
|
+
frame = inspect.currentframe()
|
|
122
|
+
try:
|
|
123
|
+
caller = frame.f_back if frame is not None else None
|
|
124
|
+
caller_file = caller.f_code.co_filename if caller is not None else ""
|
|
125
|
+
finally:
|
|
126
|
+
del frame
|
|
127
|
+
if not caller_file:
|
|
128
|
+
return None
|
|
129
|
+
raw_str = str(caller_file)
|
|
130
|
+
if raw_str.startswith("<") and raw_str.endswith(">"):
|
|
131
|
+
return None
|
|
132
|
+
start = Path(raw_str).expanduser().resolve()
|
|
133
|
+
if start.is_file():
|
|
134
|
+
start = start.parent
|
|
135
|
+
for candidate in (start, *start.parents):
|
|
136
|
+
if (
|
|
137
|
+
(candidate / "library.json").is_file()
|
|
138
|
+
or (candidate / "components").is_dir()
|
|
139
|
+
or (candidate / "utils").is_dir()
|
|
140
|
+
or (candidate / ".git").exists()
|
|
141
|
+
):
|
|
142
|
+
return candidate
|
|
143
|
+
return start
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _ensure_on_sys_path(root: Path) -> None:
|
|
147
|
+
root_str = str(root)
|
|
148
|
+
norm_root = os.path.normcase(os.path.normpath(root_str))
|
|
149
|
+
for existing in sys.path:
|
|
150
|
+
if existing and os.path.normcase(os.path.normpath(existing)) == norm_root:
|
|
151
|
+
return
|
|
152
|
+
sys.path.append(root_str)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _install_namespace_pkg(alias: str, root: Path, *, active_root: Path | None = None) -> bool:
|
|
156
|
+
stdlib_names = getattr(sys, "stdlib_module_names", frozenset())
|
|
157
|
+
if not alias or alias in stdlib_names:
|
|
158
|
+
return False
|
|
159
|
+
if _has_local_module(active_root, alias):
|
|
160
|
+
return False
|
|
161
|
+
existing = sys.modules.get(alias)
|
|
162
|
+
if existing is not None:
|
|
163
|
+
if not getattr(existing, "__slidercad_library_namespace__", False):
|
|
164
|
+
return False
|
|
165
|
+
elif importlib.util.find_spec(alias) is not None:
|
|
166
|
+
return False
|
|
167
|
+
loc = str(root)
|
|
168
|
+
spec = importlib.machinery.ModuleSpec(alias, loader=None, is_package=True)
|
|
169
|
+
spec.submodule_search_locations = [loc]
|
|
170
|
+
mod = importlib.util.module_from_spec(spec)
|
|
171
|
+
mod.__path__ = [loc]
|
|
172
|
+
setattr(mod, "__slidercad_library_namespace__", True)
|
|
173
|
+
sys.modules[alias] = mod
|
|
174
|
+
return True
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def register_libraries(
|
|
178
|
+
caller_file: str | Path | None = None,
|
|
179
|
+
*,
|
|
180
|
+
aliases: dict[str, str | Path] | None = None,
|
|
181
|
+
) -> dict[str, Path]:
|
|
182
|
+
"""Register the current library root and sibling/configured SliderCAD libraries.
|
|
183
|
+
|
|
184
|
+
Appends the active library root to ``sys.path`` (so intra-library imports such as
|
|
185
|
+
``from components.foo import ...`` work during standalone ``python model.py`` runs),
|
|
186
|
+
resolves dependencies declared in ``library.json`` via explicit ``aliases``,
|
|
187
|
+
``SLIDERCAD_LIB_<ALIAS>`` environment variables, SliderCAD's ``config.json``,
|
|
188
|
+
and sibling folders, then binds each namespace in ``sys.modules``.
|
|
189
|
+
"""
|
|
190
|
+
if caller_file is None:
|
|
191
|
+
frame = inspect.currentframe()
|
|
192
|
+
try:
|
|
193
|
+
caller = frame.f_back if frame is not None else None
|
|
194
|
+
caller_file = caller.f_code.co_filename if caller is not None else ""
|
|
195
|
+
finally:
|
|
196
|
+
del frame
|
|
197
|
+
current_root = _find_current_library_root(caller_file)
|
|
198
|
+
if current_root is not None and current_root.is_dir():
|
|
199
|
+
_ensure_on_sys_path(current_root)
|
|
200
|
+
|
|
201
|
+
candidates: list[dict[str, Any]] = []
|
|
202
|
+
seen_roots: set[Path] = set()
|
|
203
|
+
|
|
204
|
+
def _add_candidate(path: Path, cfg_id: str = "", *, is_library: bool = True) -> None:
|
|
205
|
+
try:
|
|
206
|
+
resolved = path.expanduser().resolve()
|
|
207
|
+
except OSError:
|
|
208
|
+
return
|
|
209
|
+
if not resolved.is_dir() or resolved == current_root or resolved in seen_roots:
|
|
210
|
+
return
|
|
211
|
+
seen_roots.add(resolved)
|
|
212
|
+
manifest = _read_lib_manifest(resolved)
|
|
213
|
+
ns = manifest["id"] or _norm_ns_id(cfg_id) or _norm_ns_id(resolved.name)
|
|
214
|
+
candidates.append(
|
|
215
|
+
{
|
|
216
|
+
"root": resolved,
|
|
217
|
+
"cfg_id": _norm_ns_id(cfg_id),
|
|
218
|
+
"manifest_id": manifest["id"],
|
|
219
|
+
"source": manifest["source"],
|
|
220
|
+
"default_ns": ns,
|
|
221
|
+
"is_library": is_library,
|
|
222
|
+
}
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
cfg_path = _slidercad_config_path()
|
|
226
|
+
if cfg_path.is_file():
|
|
227
|
+
try:
|
|
228
|
+
cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
|
|
229
|
+
except (OSError, ValueError):
|
|
230
|
+
cfg = {}
|
|
231
|
+
if isinstance(cfg, dict):
|
|
232
|
+
for entry in cfg.get("libraries") or []:
|
|
233
|
+
if isinstance(entry, dict) and entry.get("path"):
|
|
234
|
+
_add_candidate(Path(str(entry["path"])), str(entry.get("id") or ""), is_library=True)
|
|
235
|
+
|
|
236
|
+
if current_root is not None and current_root.parent.is_dir():
|
|
237
|
+
try:
|
|
238
|
+
for child in sorted(current_root.parent.iterdir()):
|
|
239
|
+
if child.is_dir() and not child.name.startswith("."):
|
|
240
|
+
_add_candidate(child, is_library=_looks_like_library(child))
|
|
241
|
+
except OSError:
|
|
242
|
+
pass
|
|
243
|
+
|
|
244
|
+
resolved_aliases: dict[str, Path] = {}
|
|
245
|
+
|
|
246
|
+
if aliases:
|
|
247
|
+
for raw_alias, raw_path in aliases.items():
|
|
248
|
+
alias = _norm_ns_id(raw_alias)
|
|
249
|
+
if not alias:
|
|
250
|
+
continue
|
|
251
|
+
target = Path(raw_path).expanduser().resolve()
|
|
252
|
+
if target.is_dir() and _install_namespace_pkg(alias, target, active_root=current_root):
|
|
253
|
+
resolved_aliases[alias] = target
|
|
254
|
+
|
|
255
|
+
if current_root is not None:
|
|
256
|
+
manifest = _read_lib_manifest(current_root)
|
|
257
|
+
for req in manifest["requires"]:
|
|
258
|
+
alias = req["alias"]
|
|
259
|
+
if alias in resolved_aliases:
|
|
260
|
+
continue
|
|
261
|
+
env_path = os.environ.get(f"SLIDERCAD_LIB_{alias.upper()}") or (
|
|
262
|
+
os.environ.get(f"SLIDERCAD_LIB_{req['id'].upper()}") if req["id"] else ""
|
|
263
|
+
)
|
|
264
|
+
if env_path:
|
|
265
|
+
target = Path(env_path).expanduser().resolve()
|
|
266
|
+
if target.is_dir() and _install_namespace_pkg(alias, target, active_root=current_root):
|
|
267
|
+
resolved_aliases[alias] = target
|
|
268
|
+
continue
|
|
269
|
+
req_source = req["source"]
|
|
270
|
+
req_id = req["id"]
|
|
271
|
+
source_matches: list[dict[str, Any]] = []
|
|
272
|
+
id_matches: list[dict[str, Any]] = []
|
|
273
|
+
for c in candidates:
|
|
274
|
+
if req_source and c["source"]:
|
|
275
|
+
if req_source == c["source"]:
|
|
276
|
+
source_matches.append(c)
|
|
277
|
+
continue
|
|
278
|
+
if req_id and req_id in {c["manifest_id"], c["default_ns"], c["cfg_id"]}:
|
|
279
|
+
id_matches.append(c)
|
|
280
|
+
matches = source_matches if source_matches else id_matches
|
|
281
|
+
if len(matches) == 1 and _install_namespace_pkg(
|
|
282
|
+
alias, matches[0]["root"], active_root=current_root
|
|
283
|
+
):
|
|
284
|
+
resolved_aliases[alias] = matches[0]["root"]
|
|
285
|
+
|
|
286
|
+
by_ns: dict[str, list[dict[str, Any]]] = {}
|
|
287
|
+
for cand in candidates:
|
|
288
|
+
if not cand["is_library"]:
|
|
289
|
+
continue
|
|
290
|
+
ns = cand["default_ns"]
|
|
291
|
+
if ns:
|
|
292
|
+
by_ns.setdefault(ns, []).append(cand)
|
|
293
|
+
for ns, group in by_ns.items():
|
|
294
|
+
if ns in resolved_aliases or len(group) != 1:
|
|
295
|
+
continue
|
|
296
|
+
if _install_namespace_pkg(ns, group[0]["root"], active_root=current_root):
|
|
297
|
+
resolved_aliases[ns] = group[0]["root"]
|
|
298
|
+
|
|
299
|
+
return resolved_aliases
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: Copyright 2026 Luke Covalt
|
|
3
|
+
"""Structured parameter helpers for build123d dataclass models.
|
|
4
|
+
|
|
5
|
+
Produces standard ``dataclasses.Field.metadata`` consumed by SliderCAD
|
|
6
|
+
(``label``, ``description``, ``unit``, ``min``, ``max``, ``step``, ``when``,
|
|
7
|
+
``component_preset``) and optional root-class ``__default_preset__`` metadata
|
|
8
|
+
with zero external dependencies.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import field, fields, is_dataclass, replace
|
|
14
|
+
import inspect
|
|
15
|
+
import json
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import types
|
|
18
|
+
from typing import Any, Callable, Literal, TypeVar, Union, cast, get_args, get_origin, get_type_hints, overload
|
|
19
|
+
|
|
20
|
+
T = TypeVar("T")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def default_preset(
|
|
24
|
+
label: str,
|
|
25
|
+
*,
|
|
26
|
+
desc: str | None = None,
|
|
27
|
+
) -> Callable[[type[T]], type[T]]:
|
|
28
|
+
"""Attach a friendly preset label and description to a root Params dataclass."""
|
|
29
|
+
|
|
30
|
+
def _decorator(cls: type[T]) -> type[T]:
|
|
31
|
+
meta: dict[str, str] = {"label": label.strip()}
|
|
32
|
+
if desc is not None and desc.strip():
|
|
33
|
+
meta["description"] = desc.strip()
|
|
34
|
+
setattr(cls, "__default_preset__", meta)
|
|
35
|
+
return cls
|
|
36
|
+
|
|
37
|
+
return _decorator
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def param(
|
|
41
|
+
default: T,
|
|
42
|
+
*,
|
|
43
|
+
label: str | None = None,
|
|
44
|
+
desc: str | None = None,
|
|
45
|
+
item_label: str | None = None,
|
|
46
|
+
unit: str | None = None,
|
|
47
|
+
min: int | float | None = None,
|
|
48
|
+
max: int | float | None = None,
|
|
49
|
+
step: int | float | None = None,
|
|
50
|
+
when: dict[str, Any] | None = None,
|
|
51
|
+
) -> T:
|
|
52
|
+
"""Define a parametric dataclass field with structured UI metadata."""
|
|
53
|
+
meta: dict[str, Any] = {}
|
|
54
|
+
if label is not None:
|
|
55
|
+
meta["label"] = label
|
|
56
|
+
if desc is not None:
|
|
57
|
+
meta["description"] = desc
|
|
58
|
+
if item_label is not None:
|
|
59
|
+
meta["item_label"] = item_label
|
|
60
|
+
if unit is not None:
|
|
61
|
+
meta["unit"] = unit
|
|
62
|
+
if min is not None:
|
|
63
|
+
meta["min"] = min
|
|
64
|
+
if max is not None:
|
|
65
|
+
meta["max"] = max
|
|
66
|
+
if step is not None:
|
|
67
|
+
meta["step"] = step
|
|
68
|
+
if when is not None:
|
|
69
|
+
meta["when"] = when
|
|
70
|
+
return cast(T, field(default=default, metadata=meta))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def param_list(
|
|
74
|
+
factory: Callable[[], list[T]],
|
|
75
|
+
*,
|
|
76
|
+
label: str | None = None,
|
|
77
|
+
desc: str | None = None,
|
|
78
|
+
item_label: str | None = None,
|
|
79
|
+
unit: str | None = None,
|
|
80
|
+
min: int | float | None = None,
|
|
81
|
+
max: int | float | None = None,
|
|
82
|
+
step: int | float | None = None,
|
|
83
|
+
when: dict[str, Any] | None = None,
|
|
84
|
+
) -> list[T]:
|
|
85
|
+
"""Define a list-of-items parameter field with structured UI metadata."""
|
|
86
|
+
meta: dict[str, Any] = {}
|
|
87
|
+
if label is not None:
|
|
88
|
+
meta["label"] = label
|
|
89
|
+
if desc is not None:
|
|
90
|
+
meta["description"] = desc
|
|
91
|
+
if item_label is not None:
|
|
92
|
+
meta["item_label"] = item_label
|
|
93
|
+
if unit is not None:
|
|
94
|
+
meta["unit"] = unit
|
|
95
|
+
if min is not None:
|
|
96
|
+
meta["min"] = min
|
|
97
|
+
if max is not None:
|
|
98
|
+
meta["max"] = max
|
|
99
|
+
if step is not None:
|
|
100
|
+
meta["step"] = step
|
|
101
|
+
if when is not None:
|
|
102
|
+
meta["when"] = when
|
|
103
|
+
return cast(list[T], field(default_factory=factory, metadata=meta))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _load_component_preset_params(factory: Callable[[], Any], preset_key: str) -> dict[str, Any]:
|
|
107
|
+
"""Load sparse ``params`` for ``preset_key`` from the component's presets.json, or {}."""
|
|
108
|
+
try:
|
|
109
|
+
src = inspect.getsourcefile(factory)
|
|
110
|
+
except Exception:
|
|
111
|
+
src = None
|
|
112
|
+
if not src:
|
|
113
|
+
return {}
|
|
114
|
+
src_path = Path(src).resolve()
|
|
115
|
+
parent = src_path.parent
|
|
116
|
+
presets_path = (
|
|
117
|
+
parent / "presets.json"
|
|
118
|
+
if parent.name == src_path.stem
|
|
119
|
+
else parent / f"{src_path.stem}.presets.json"
|
|
120
|
+
)
|
|
121
|
+
if not presets_path.is_file():
|
|
122
|
+
return {}
|
|
123
|
+
try:
|
|
124
|
+
data = json.loads(presets_path.read_text(encoding="utf-8-sig"))
|
|
125
|
+
except Exception:
|
|
126
|
+
return {}
|
|
127
|
+
if not isinstance(data, dict):
|
|
128
|
+
return {}
|
|
129
|
+
presets = data.get("presets")
|
|
130
|
+
if not isinstance(presets, dict):
|
|
131
|
+
return {}
|
|
132
|
+
entry = presets.get(preset_key)
|
|
133
|
+
if not isinstance(entry, dict):
|
|
134
|
+
return {}
|
|
135
|
+
raw_params = entry.get("params")
|
|
136
|
+
return dict(raw_params) if isinstance(raw_params, dict) else {}
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _unwrap_optional_type(tp: Any) -> Any:
|
|
140
|
+
origin = get_origin(tp)
|
|
141
|
+
if origin is Union or origin is types.UnionType:
|
|
142
|
+
non_none = [a for a in get_args(tp) if a is not type(None)]
|
|
143
|
+
if len(non_none) == 1:
|
|
144
|
+
return non_none[0]
|
|
145
|
+
return tp
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _apply_group_overrides(instance: T, overrides: dict[str, Any]) -> T:
|
|
149
|
+
"""Return a copy of ``instance`` with sparse ``overrides`` applied recursively."""
|
|
150
|
+
if not is_dataclass(instance) or not isinstance(overrides, dict) or not overrides:
|
|
151
|
+
return instance
|
|
152
|
+
try:
|
|
153
|
+
hints = get_type_hints(type(instance))
|
|
154
|
+
except Exception:
|
|
155
|
+
hints = {}
|
|
156
|
+
|
|
157
|
+
updates: dict[str, Any] = {}
|
|
158
|
+
for f in fields(instance):
|
|
159
|
+
if f.name not in overrides:
|
|
160
|
+
continue
|
|
161
|
+
val = overrides[f.name]
|
|
162
|
+
cur = getattr(instance, f.name)
|
|
163
|
+
if is_dataclass(cur):
|
|
164
|
+
if val is None:
|
|
165
|
+
updates[f.name] = None
|
|
166
|
+
elif isinstance(val, dict):
|
|
167
|
+
updates[f.name] = _apply_group_overrides(cur, val)
|
|
168
|
+
elif cur is None and isinstance(val, dict):
|
|
169
|
+
unwrapped = _unwrap_optional_type(hints.get(f.name, f.type))
|
|
170
|
+
if is_dataclass(unwrapped) and isinstance(unwrapped, type):
|
|
171
|
+
updates[f.name] = _apply_group_overrides(unwrapped(), val)
|
|
172
|
+
elif isinstance(cur, tuple) and isinstance(val, list):
|
|
173
|
+
updates[f.name] = tuple(val)
|
|
174
|
+
elif isinstance(cur, float) and isinstance(val, int) and not isinstance(val, bool):
|
|
175
|
+
updates[f.name] = float(val)
|
|
176
|
+
else:
|
|
177
|
+
updates[f.name] = val
|
|
178
|
+
|
|
179
|
+
return replace(instance, **updates) if updates else instance
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _build_group_instance(
|
|
183
|
+
factory: Callable[[], T],
|
|
184
|
+
preset_key: str,
|
|
185
|
+
overrides: dict[str, Any] | None,
|
|
186
|
+
) -> T:
|
|
187
|
+
"""Instantiate ``factory()`` layered with optional ``preset_key`` and ``overrides``."""
|
|
188
|
+
instance = factory()
|
|
189
|
+
if preset_key:
|
|
190
|
+
preset_params = _load_component_preset_params(factory, preset_key)
|
|
191
|
+
if preset_params:
|
|
192
|
+
instance = _apply_group_overrides(instance, preset_params)
|
|
193
|
+
if overrides:
|
|
194
|
+
instance = _apply_group_overrides(instance, overrides)
|
|
195
|
+
return instance
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@overload
|
|
199
|
+
def group(
|
|
200
|
+
factory: Callable[[], T],
|
|
201
|
+
*,
|
|
202
|
+
enabled: Literal[True] = True,
|
|
203
|
+
preset: str | None = None,
|
|
204
|
+
params: dict[str, Any] | None = None,
|
|
205
|
+
label: str | None = None,
|
|
206
|
+
desc: str | None = None,
|
|
207
|
+
when: dict[str, Any] | None = None,
|
|
208
|
+
) -> T: ...
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
@overload
|
|
212
|
+
def group(
|
|
213
|
+
factory: Callable[[], T],
|
|
214
|
+
*,
|
|
215
|
+
enabled: Literal[False],
|
|
216
|
+
preset: str | None = None,
|
|
217
|
+
params: dict[str, Any] | None = None,
|
|
218
|
+
label: str | None = None,
|
|
219
|
+
desc: str | None = None,
|
|
220
|
+
when: dict[str, Any] | None = None,
|
|
221
|
+
) -> T | None: ...
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def group(
|
|
225
|
+
factory: Callable[[], T],
|
|
226
|
+
*,
|
|
227
|
+
enabled: bool = True,
|
|
228
|
+
preset: str | None = None,
|
|
229
|
+
params: dict[str, Any] | None = None,
|
|
230
|
+
label: str | None = None,
|
|
231
|
+
desc: str | None = None,
|
|
232
|
+
when: dict[str, Any] | None = None,
|
|
233
|
+
) -> Any:
|
|
234
|
+
"""Define a nested parameter-group dataclass field with optional UI metadata.
|
|
235
|
+
|
|
236
|
+
Pass ``enabled=False`` on a nullable group (``T | None``) to make the section
|
|
237
|
+
optional and disabled by default (``None``). Optionally pass ``preset`` (a
|
|
238
|
+
component preset key from the component's ``presets.json``) and/or ``params``
|
|
239
|
+
(sparse per-model overrides) to customize a shared component's defaults.
|
|
240
|
+
"""
|
|
241
|
+
meta: dict[str, Any] = {}
|
|
242
|
+
if label is not None:
|
|
243
|
+
meta["label"] = label
|
|
244
|
+
if desc is not None:
|
|
245
|
+
meta["description"] = desc
|
|
246
|
+
if when is not None:
|
|
247
|
+
meta["when"] = when
|
|
248
|
+
clean_preset = preset.strip() if isinstance(preset, str) else ""
|
|
249
|
+
if clean_preset == "default":
|
|
250
|
+
clean_preset = ""
|
|
251
|
+
if clean_preset:
|
|
252
|
+
meta["component_preset"] = clean_preset
|
|
253
|
+
if not enabled:
|
|
254
|
+
return field(default=None, metadata=meta)
|
|
255
|
+
if not clean_preset and not params:
|
|
256
|
+
return field(default_factory=factory, metadata=meta)
|
|
257
|
+
overrides = dict(params) if params else None
|
|
258
|
+
return field(
|
|
259
|
+
default_factory=lambda: _build_group_instance(factory, clean_preset, overrides),
|
|
260
|
+
metadata=meta,
|
|
261
|
+
)
|
|
File without changes
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
# SPDX-FileCopyrightText: Copyright 2026 Luke Covalt
|
|
3
|
+
"""Standalone script runner and export helpers for build123d models.
|
|
4
|
+
|
|
5
|
+
Provides a shared ``__main__`` entrypoint helper so model scripts stay concise
|
|
6
|
+
and side-effect-free on import while still allowing quick standalone execution
|
|
7
|
+
and STL/STEP/3MF exports into the library's ``exports/`` folder.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import inspect
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .libraries import _find_current_library_root
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_exports_dir(
|
|
20
|
+
output_dir: str | Path | None = None,
|
|
21
|
+
*,
|
|
22
|
+
caller_file: str | Path | None = None,
|
|
23
|
+
) -> Path:
|
|
24
|
+
"""Resolve the output directory for standalone exports.
|
|
25
|
+
|
|
26
|
+
Defaults to ``<library_root>/exports`` (walking up from the caller's script
|
|
27
|
+
to ``library.json``, ``components/``, ``utils/``, or ``.git``; falling back
|
|
28
|
+
to the current working directory). Relative paths are resolved relative to
|
|
29
|
+
that library root so files never scatter across subdirectories.
|
|
30
|
+
"""
|
|
31
|
+
if output_dir is not None:
|
|
32
|
+
path = Path(output_dir)
|
|
33
|
+
if path.is_absolute():
|
|
34
|
+
return path
|
|
35
|
+
else:
|
|
36
|
+
path = None
|
|
37
|
+
|
|
38
|
+
if caller_file is None:
|
|
39
|
+
frame = inspect.currentframe()
|
|
40
|
+
try:
|
|
41
|
+
caller = frame.f_back if frame is not None else None
|
|
42
|
+
caller_file = caller.f_code.co_filename if caller is not None else ""
|
|
43
|
+
finally:
|
|
44
|
+
del frame
|
|
45
|
+
|
|
46
|
+
root = _find_current_library_root(caller_file) or Path.cwd()
|
|
47
|
+
if path is None:
|
|
48
|
+
return root / "exports"
|
|
49
|
+
return root / path
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def show_in_viewer(*args: Any, **kwargs: Any) -> None:
|
|
53
|
+
"""Display generated geometry in ocp_viewer (or ocp_vscode fallback)."""
|
|
54
|
+
try:
|
|
55
|
+
from ocp_viewer import set_defaults, show # type: ignore[import-not-found]
|
|
56
|
+
|
|
57
|
+
set_defaults(orbit_control=True)
|
|
58
|
+
except ImportError:
|
|
59
|
+
try:
|
|
60
|
+
from ocp_vscode import set_defaults, show # type: ignore[import-not-found]
|
|
61
|
+
|
|
62
|
+
set_defaults(orbit_control=True)
|
|
63
|
+
except ImportError:
|
|
64
|
+
return
|
|
65
|
+
show(*args, **kwargs)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def run_model(
|
|
69
|
+
part: Any,
|
|
70
|
+
stem: str,
|
|
71
|
+
*,
|
|
72
|
+
stl: bool = False,
|
|
73
|
+
step: bool = False,
|
|
74
|
+
threemf: bool = False,
|
|
75
|
+
output_dir: str | Path | None = None,
|
|
76
|
+
show_part: bool = True,
|
|
77
|
+
caller_file: str | Path | None = None,
|
|
78
|
+
) -> list[Path]:
|
|
79
|
+
"""Export requested formats to ``<library_root>/exports/`` and preview in viewer."""
|
|
80
|
+
if caller_file is None:
|
|
81
|
+
frame = inspect.currentframe()
|
|
82
|
+
try:
|
|
83
|
+
caller = frame.f_back if frame is not None else None
|
|
84
|
+
caller_file = caller.f_code.co_filename if caller is not None else ""
|
|
85
|
+
finally:
|
|
86
|
+
del frame
|
|
87
|
+
|
|
88
|
+
exported: list[Path] = []
|
|
89
|
+
|
|
90
|
+
if stl or step or threemf:
|
|
91
|
+
exports_path = get_exports_dir(output_dir, caller_file=caller_file)
|
|
92
|
+
exports_path.mkdir(parents=True, exist_ok=True)
|
|
93
|
+
|
|
94
|
+
if stl:
|
|
95
|
+
from build123d import export_stl # type: ignore[import-not-found]
|
|
96
|
+
|
|
97
|
+
stl_file = exports_path / f"{stem}.stl"
|
|
98
|
+
export_stl(part, str(stl_file))
|
|
99
|
+
exported.append(stl_file)
|
|
100
|
+
print(f"Exported STL: {stl_file}")
|
|
101
|
+
|
|
102
|
+
if step:
|
|
103
|
+
from build123d import export_step # type: ignore[import-not-found]
|
|
104
|
+
|
|
105
|
+
step_file = exports_path / f"{stem}.step"
|
|
106
|
+
export_step(part, str(step_file))
|
|
107
|
+
exported.append(step_file)
|
|
108
|
+
print(f"Exported STEP: {step_file}")
|
|
109
|
+
|
|
110
|
+
if threemf:
|
|
111
|
+
from build123d import Mesher # type: ignore[import-not-found]
|
|
112
|
+
|
|
113
|
+
threemf_file = exports_path / f"{stem}.3mf"
|
|
114
|
+
mesher = Mesher()
|
|
115
|
+
mesher.add_shape(part)
|
|
116
|
+
mesher.write(str(threemf_file))
|
|
117
|
+
exported.append(threemf_file)
|
|
118
|
+
print(f"Exported 3MF: {threemf_file}")
|
|
119
|
+
|
|
120
|
+
if show_part:
|
|
121
|
+
show_in_viewer(part)
|
|
122
|
+
|
|
123
|
+
return exported
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass, fields
|
|
4
|
+
import importlib
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import re
|
|
8
|
+
import subprocess
|
|
9
|
+
import sys
|
|
10
|
+
import types
|
|
11
|
+
|
|
12
|
+
import pytest
|
|
13
|
+
|
|
14
|
+
PKG_ROOT = Path(__file__).resolve().parents[1]
|
|
15
|
+
if str(PKG_ROOT) not in sys.path:
|
|
16
|
+
sys.path.insert(0, str(PKG_ROOT))
|
|
17
|
+
|
|
18
|
+
import slidercad # noqa: E402
|
|
19
|
+
from slidercad import ( # noqa: E402
|
|
20
|
+
default_preset,
|
|
21
|
+
get_exports_dir,
|
|
22
|
+
group,
|
|
23
|
+
param,
|
|
24
|
+
param_list,
|
|
25
|
+
register_libraries,
|
|
26
|
+
run_model,
|
|
27
|
+
show_in_viewer,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def test_version_matches_pyproject() -> None:
|
|
32
|
+
pyproject = (PKG_ROOT / "pyproject.toml").read_text(encoding="utf-8")
|
|
33
|
+
match = re.search(r'(?m)^version\s*=\s*"([^"]+)"', pyproject)
|
|
34
|
+
assert match is not None
|
|
35
|
+
assert slidercad.__version__ == match.group(1)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def test_all_package_modules_carry_apache_spdx_header() -> None:
|
|
39
|
+
py_files = sorted((PKG_ROOT / "slidercad").glob("*.py"))
|
|
40
|
+
assert py_files
|
|
41
|
+
for py_file in py_files:
|
|
42
|
+
head = py_file.read_text(encoding="utf-8").splitlines()[:3]
|
|
43
|
+
assert any("SPDX-License-Identifier: Apache-2.0" in line for line in head), py_file.name
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def test_param_param_list_group_and_default_preset(tmp_path: Path) -> None:
|
|
47
|
+
comp_dir = tmp_path / "components" / "lip"
|
|
48
|
+
comp_dir.mkdir(parents=True)
|
|
49
|
+
(comp_dir / "lip.py").write_text(
|
|
50
|
+
"from dataclasses import dataclass\n"
|
|
51
|
+
"from slidercad import param\n"
|
|
52
|
+
"@dataclass\n"
|
|
53
|
+
"class LipParams:\n"
|
|
54
|
+
" height: float = param(4.4, unit='mm', min=1.0, max=10.0)\n"
|
|
55
|
+
" bevel: float = param(0.8, unit='mm')\n",
|
|
56
|
+
encoding="utf-8",
|
|
57
|
+
)
|
|
58
|
+
(comp_dir / "presets.json").write_text(
|
|
59
|
+
json.dumps({"presets": {"tall": {"label": "Tall", "params": {"height": 8.0}}}}),
|
|
60
|
+
encoding="utf-8",
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
spec = importlib.util.spec_from_file_location("test_lip_mod", comp_dir / "lip.py")
|
|
64
|
+
assert spec is not None and spec.loader is not None
|
|
65
|
+
lip_mod = importlib.util.module_from_spec(spec)
|
|
66
|
+
sys.modules[spec.name] = lip_mod
|
|
67
|
+
try:
|
|
68
|
+
spec.loader.exec_module(lip_mod)
|
|
69
|
+
LipParams = lip_mod.LipParams
|
|
70
|
+
|
|
71
|
+
@default_preset("Standard", desc="Baseline box")
|
|
72
|
+
@dataclass
|
|
73
|
+
class BoxParams:
|
|
74
|
+
width: float = param(40.0, label="Width", desc="Overall width", unit="mm", min=5.0, max=200.0, step=1.0)
|
|
75
|
+
holes: list[float] = param_list(lambda: [10.0, 20.0], item_label="Hole", unit="mm")
|
|
76
|
+
lip: LipParams = group(LipParams, preset="tall", params={"bevel": 1.2})
|
|
77
|
+
optional_lip: LipParams | None = group(LipParams, enabled=False)
|
|
78
|
+
|
|
79
|
+
assert getattr(BoxParams, "__default_preset__") == {"label": "Standard", "description": "Baseline box"}
|
|
80
|
+
meta_by_name = {f.name: dict(f.metadata) for f in fields(BoxParams)}
|
|
81
|
+
assert meta_by_name["width"] == {
|
|
82
|
+
"label": "Width",
|
|
83
|
+
"description": "Overall width",
|
|
84
|
+
"unit": "mm",
|
|
85
|
+
"min": 5.0,
|
|
86
|
+
"max": 200.0,
|
|
87
|
+
"step": 1.0,
|
|
88
|
+
}
|
|
89
|
+
assert meta_by_name["holes"] == {"item_label": "Hole", "unit": "mm"}
|
|
90
|
+
assert meta_by_name["lip"] == {"component_preset": "tall"}
|
|
91
|
+
|
|
92
|
+
inst = BoxParams()
|
|
93
|
+
assert inst.width == 40.0
|
|
94
|
+
assert inst.holes == [10.0, 20.0]
|
|
95
|
+
assert inst.lip.height == 8.0
|
|
96
|
+
assert inst.lip.bevel == 1.2
|
|
97
|
+
assert inst.optional_lip is None
|
|
98
|
+
finally:
|
|
99
|
+
sys.modules.pop(spec.name, None)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def test_register_libraries_adds_active_root_and_resolves_siblings(tmp_path: Path) -> None:
|
|
103
|
+
provider = tmp_path / "shared-parts"
|
|
104
|
+
(provider / "components" / "tab").mkdir(parents=True)
|
|
105
|
+
(provider / "library.json").write_text(
|
|
106
|
+
json.dumps({"id": "shared_parts", "source": "github.com/example/shared-parts"}),
|
|
107
|
+
encoding="utf-8",
|
|
108
|
+
)
|
|
109
|
+
(provider / "components" / "tab" / "__init__.py").write_text("TAB_W = 12.5\n", encoding="utf-8")
|
|
110
|
+
|
|
111
|
+
consumer = tmp_path / "my-lib"
|
|
112
|
+
(consumer / "components" / "local_foot").mkdir(parents=True)
|
|
113
|
+
(consumer / "components" / "local_foot" / "__init__.py").write_text("FOOT_H = 5.0\n", encoding="utf-8")
|
|
114
|
+
(consumer / "library.json").write_text(
|
|
115
|
+
json.dumps({"id": "my_lib", "requires": [{"id": "shared_parts", "source": "github.com/example/shared-parts"}]}),
|
|
116
|
+
encoding="utf-8",
|
|
117
|
+
)
|
|
118
|
+
model_file = consumer / "box" / "box.py"
|
|
119
|
+
model_file.parent.mkdir(parents=True)
|
|
120
|
+
model_file.write_text(
|
|
121
|
+
"from slidercad import register_libraries\n"
|
|
122
|
+
"resolved = register_libraries()\n"
|
|
123
|
+
"from components.local_foot import FOOT_H\n"
|
|
124
|
+
"from shared_parts.components.tab import TAB_W\n"
|
|
125
|
+
"print(f'{FOOT_H}|{TAB_W}|{sorted(resolved.keys())}')\n",
|
|
126
|
+
encoding="utf-8",
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
env = dict(**{k: v for k, v in __import__("os").environ.items() if not k.startswith("SLIDERCAD_LIB_")})
|
|
130
|
+
env["PYTHONPATH"] = str(PKG_ROOT)
|
|
131
|
+
env["APPDATA"] = str(tmp_path / "isolated-cfg")
|
|
132
|
+
env["XDG_CONFIG_HOME"] = str(tmp_path / "isolated-cfg")
|
|
133
|
+
proc = subprocess.run(
|
|
134
|
+
[sys.executable, str(model_file)],
|
|
135
|
+
capture_output=True,
|
|
136
|
+
text=True,
|
|
137
|
+
env=env,
|
|
138
|
+
)
|
|
139
|
+
assert proc.returncode == 0, f"stderr:\n{proc.stderr}\nstdout:\n{proc.stdout}"
|
|
140
|
+
assert proc.stdout.strip() == "5.0|12.5|['shared_parts']"
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def test_register_libraries_never_shadows_slidercad_or_local_modules(
|
|
144
|
+
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
|
145
|
+
) -> None:
|
|
146
|
+
consumer = tmp_path / "consumer"
|
|
147
|
+
consumer.mkdir(parents=True)
|
|
148
|
+
(consumer / "library.json").write_text(json.dumps({"id": "consumer"}), encoding="utf-8")
|
|
149
|
+
(consumer / "helpers").mkdir(parents=True)
|
|
150
|
+
(consumer / "helpers" / "util.py").write_text("X = 1\n", encoding="utf-8")
|
|
151
|
+
model_file = consumer / "part" / "part.py"
|
|
152
|
+
model_file.parent.mkdir(parents=True)
|
|
153
|
+
model_file.write_text("# model\n", encoding="utf-8")
|
|
154
|
+
|
|
155
|
+
collision = tmp_path / "slidercad"
|
|
156
|
+
collision.mkdir(parents=True)
|
|
157
|
+
(collision / "library.json").write_text(json.dumps({"id": "slidercad"}), encoding="utf-8")
|
|
158
|
+
local_collision = tmp_path / "helpers"
|
|
159
|
+
local_collision.mkdir(parents=True)
|
|
160
|
+
(local_collision / "library.json").write_text(json.dumps({"id": "helpers"}), encoding="utf-8")
|
|
161
|
+
|
|
162
|
+
monkeypatch.setattr("slidercad.libraries._slidercad_config_path", lambda: tmp_path / "missing-config.json")
|
|
163
|
+
orig_path = list(sys.path)
|
|
164
|
+
try:
|
|
165
|
+
resolved = register_libraries(model_file)
|
|
166
|
+
assert "slidercad" not in resolved
|
|
167
|
+
assert "helpers" not in resolved
|
|
168
|
+
assert str(consumer.resolve()) in sys.path
|
|
169
|
+
finally:
|
|
170
|
+
sys.path[:] = orig_path
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def test_get_exports_dir_and_run_model(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
174
|
+
lib_root = tmp_path / "my-lib"
|
|
175
|
+
lib_root.mkdir(parents=True)
|
|
176
|
+
(lib_root / "library.json").write_text(json.dumps({"id": "my_lib"}), encoding="utf-8")
|
|
177
|
+
model_file = lib_root / "widget" / "widget.py"
|
|
178
|
+
model_file.parent.mkdir(parents=True)
|
|
179
|
+
model_file.write_text("# widget\n", encoding="utf-8")
|
|
180
|
+
|
|
181
|
+
assert get_exports_dir(caller_file=model_file) == lib_root.resolve() / "exports"
|
|
182
|
+
assert get_exports_dir("custom_out", caller_file=model_file) == lib_root.resolve() / "custom_out"
|
|
183
|
+
abs_out = tmp_path / "abs_exports"
|
|
184
|
+
assert get_exports_dir(abs_out, caller_file=model_file) == abs_out
|
|
185
|
+
|
|
186
|
+
# show_in_viewer is a safe no-op when neither viewer is installed
|
|
187
|
+
monkeypatch.setitem(sys.modules, "ocp_viewer", None)
|
|
188
|
+
monkeypatch.setitem(sys.modules, "ocp_vscode", None)
|
|
189
|
+
show_in_viewer(object())
|
|
190
|
+
|
|
191
|
+
# show_in_viewer delegates to ocp_viewer when present
|
|
192
|
+
shown: list[tuple[tuple[object, ...], dict[str, object]]] = []
|
|
193
|
+
defaults_set: list[dict[str, object]] = []
|
|
194
|
+
fake_viewer = types.ModuleType("ocp_viewer")
|
|
195
|
+
setattr(fake_viewer, "set_defaults", lambda **kw: defaults_set.append(kw))
|
|
196
|
+
setattr(fake_viewer, "show", lambda *a, **kw: shown.append((a, kw)))
|
|
197
|
+
monkeypatch.setitem(sys.modules, "ocp_viewer", fake_viewer)
|
|
198
|
+
sentinel = object()
|
|
199
|
+
show_in_viewer(sentinel, names=["part"])
|
|
200
|
+
assert defaults_set == [{"orbit_control": True}]
|
|
201
|
+
assert shown == [((sentinel,), {"names": ["part"]})]
|
|
202
|
+
|
|
203
|
+
# Fake build123d module to exercise export paths without requiring OpenCASCADE
|
|
204
|
+
fake_b3d = types.ModuleType("build123d")
|
|
205
|
+
exported_calls: list[tuple[str, str]] = []
|
|
206
|
+
|
|
207
|
+
def _export_stl(_part: object, path: str) -> None:
|
|
208
|
+
Path(path).write_text("solid fake\nendsolid fake\n", encoding="utf-8")
|
|
209
|
+
exported_calls.append(("stl", path))
|
|
210
|
+
|
|
211
|
+
def _export_step(_part: object, path: str) -> None:
|
|
212
|
+
Path(path).write_text("ISO-10303-21;\n", encoding="utf-8")
|
|
213
|
+
exported_calls.append(("step", path))
|
|
214
|
+
|
|
215
|
+
class _FakeMesher:
|
|
216
|
+
def add_shape(self, _part: object) -> None:
|
|
217
|
+
pass
|
|
218
|
+
|
|
219
|
+
def write(self, path: str) -> None:
|
|
220
|
+
Path(path).write_bytes(b"PK\x03\x04")
|
|
221
|
+
exported_calls.append(("3mf", path))
|
|
222
|
+
|
|
223
|
+
setattr(fake_b3d, "export_stl", _export_stl)
|
|
224
|
+
setattr(fake_b3d, "export_step", _export_step)
|
|
225
|
+
setattr(fake_b3d, "Mesher", _FakeMesher)
|
|
226
|
+
monkeypatch.setitem(sys.modules, "build123d", fake_b3d)
|
|
227
|
+
|
|
228
|
+
out_files = run_model(
|
|
229
|
+
object(),
|
|
230
|
+
"widget_40mm",
|
|
231
|
+
stl=True,
|
|
232
|
+
step=True,
|
|
233
|
+
threemf=True,
|
|
234
|
+
show_part=False,
|
|
235
|
+
caller_file=model_file,
|
|
236
|
+
)
|
|
237
|
+
assert out_files == [
|
|
238
|
+
lib_root.resolve() / "exports" / "widget_40mm.stl",
|
|
239
|
+
lib_root.resolve() / "exports" / "widget_40mm.step",
|
|
240
|
+
lib_root.resolve() / "exports" / "widget_40mm.3mf",
|
|
241
|
+
]
|
|
242
|
+
assert all(p.is_file() for p in out_files)
|
|
243
|
+
assert [kind for kind, _ in exported_calls] == ["stl", "step", "3mf"]
|