Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 27 additions & 8 deletions cadquery/assembly.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from typish import instance_of
from uuid import uuid1 as uuid
from warnings import warn
from pathlib import Path

from .cq import Workplane
from .occ_impl.shapes import Shape, Compound, isSubshape
Expand Down Expand Up @@ -507,7 +508,7 @@ def solve(self, verbosity: int = 0) -> Self:
@deprecate()
def save(
self,
path: str,
path: Path | str,
exportType: Optional[ExportLiterals] = None,
mode: STEPExportModeLiterals = "default",
tolerance: float = 0.1,
Expand All @@ -528,13 +529,16 @@ def save(
:type ascii: bool
"""

if isinstance(path, str):
path = Path(path)
Comment on lines +532 to +533
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if isinstance(path, str):
path = Path(path)
path = Path(path)

or

Suggested change
if isinstance(path, str):
path = Path(path)
path = Path(path) if isinstance(path, str) else path


return self.export(
path, exportType, mode, tolerance, angularTolerance, **kwargs
)

def export(
self,
path: str,
path: Path | str,
exportType: Optional[ExportLiterals] = None,
mode: STEPExportModeLiterals = "default",
tolerance: float = 0.1,
Expand All @@ -555,12 +559,15 @@ def export(
:type ascii: bool
"""

if isinstance(path, str):
path = Path(path)

# Make sure the export mode setting is correct
if mode not in get_args(STEPExportModeLiterals):
raise ValueError(f"Unknown assembly export mode {mode} for STEP")

if exportType is None:
t = path.split(".")[-1].upper()
t = path.suffix.upper().lstrip(".")
if t in ("STEP", "XML", "XBF", "VRML", "VTKJS", "GLTF", "GLB", "STL"):
exportType = cast(ExportLiterals, t)
else:
Expand Down Expand Up @@ -591,24 +598,32 @@ def export(
return self

@classmethod
def importStep(cls, path: str) -> Self:
def importStep(cls, path: Path | str) -> Self:
"""
Reads an assembly from a STEP file.

:param path: Path and filename for reading.
:return: An Assembly object.
"""

if isinstance(path, str):
path = Path(path)

return cls.load(path, importType="STEP")

@classmethod
def load(cls, path: str, importType: Optional[ImportLiterals] = None,) -> Self:
def load(
cls, path: Path | str, importType: Optional[ImportLiterals] = None,
) -> Self:
"""
Load step, xbf or xml.
"""

if isinstance(path, str):
path = Path(path)

if importType is None:
t = path.split(".")[-1].upper()
t = path.suffix.upper().lstrip(".")
if t in ("STEP", "XML", "XBF"):
importType = cast(ImportLiterals, t)
else:
Expand Down Expand Up @@ -680,8 +695,12 @@ def __iter__(
color = self.color if self.color else color

if self.obj:
yield self.obj if isinstance(self.obj, Shape) else Compound.makeCompound(
s for s in self.obj.vals() if isinstance(s, Shape)
yield (
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this changed?

self.obj
if isinstance(self.obj, Shape)
else Compound.makeCompound(
s for s in self.obj.vals() if isinstance(s, Shape)
)
), name, loc, color

for ch in self.children:
Expand Down
12 changes: 10 additions & 2 deletions cadquery/cq.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
)
from typing_extensions import Literal
from inspect import Parameter, Signature
from pathlib import Path


from .occ_impl.geom import Vector, Plane, Location
Expand Down Expand Up @@ -4304,7 +4305,7 @@ def text(
combine: CombineMode = False,
clean: bool = True,
font: str = "Arial",
fontPath: Optional[str] = None,
fontPath: Optional[Path | str] = None,
kind: Literal["regular", "bold", "italic"] = "regular",
halign: Literal["center", "left", "right"] = "center",
valign: Literal["center", "top", "bottom"] = "center",
Expand Down Expand Up @@ -4352,6 +4353,10 @@ def text(
cq.Workplane().box(8, 8, 8).faces(">Z").workplane().text("Z", 5, -1.0)

"""

if isinstance(fontPath, str):
fontPath = Path(fontPath)

r = Compound.makeText(
txt,
fontsize,
Expand Down Expand Up @@ -4582,7 +4587,7 @@ def invoke(

def export(
self: T,
fname: str,
fname: Path | str,
tolerance: float = 0.1,
angularTolerance: float = 0.1,
opt: Optional[Dict[str, Any]] = None,
Expand All @@ -4597,6 +4602,9 @@ def export(
:return: Self.
"""

if isinstance(fname, str):
fname = Path(fname)

export(
self, fname, tolerance=tolerance, angularTolerance=angularTolerance, opt=opt
)
Expand Down
16 changes: 10 additions & 6 deletions cadquery/occ_impl/exporters/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import tempfile
import os
import io as StringIO
from pathlib import Path

from typing import IO, Optional, Union, cast, Dict, Any, Iterable
from typing_extensions import Literal
Expand Down Expand Up @@ -39,13 +40,12 @@ class ExportTypes:

def export(
w: Union[Shape, Iterable[Shape]],
fname: str,
fname: Path | str,
exportType: Optional[ExportLiterals] = None,
tolerance: float = 0.1,
angularTolerance: float = 0.1,
opt: Optional[Dict[str, Any]] = None,
):

"""
Export Workplane or Shape to file. Multiple entities are converted to compound.

Expand All @@ -57,6 +57,9 @@ def export(
:param opt: additional options passed to the specific exporter. Default None.
"""

if isinstance(fname, str):
fname = Path(fname)

shape: Shape
f: IO

Expand All @@ -69,7 +72,7 @@ def export(
shape = compound(*w)

if exportType is None:
t = fname.split(".")[-1].upper()
t = fname.suffix.upper().lstrip(".")
if t in ExportTypes.__dict__.values():
exportType = cast(ExportLiterals, t)
else:
Expand Down Expand Up @@ -121,7 +124,7 @@ def export(

elif exportType == ExportTypes.VRML:
shape.mesh(tolerance, angularTolerance)
VrmlAPI.Write_s(shape.wrapped, fname)
VrmlAPI.Write_s(shape.wrapped, str(fname))

elif exportType == ExportTypes.VTP:
exportVTP(shape, fname, tolerance, angularTolerance)
Expand Down Expand Up @@ -200,6 +203,7 @@ def tessellate(shape, angularTolerance):
# all these types required writing to a file and then
# re-reading. this is due to the fact that FreeCAD writes these
(h, outFileName) = tempfile.mkstemp()
outFileName = Path(outFileName) # type: ignore
# weird, but we need to close this file. the next step is going to write to
# it from c code, so it needs to be closed.
os.close(h)
Expand All @@ -216,7 +220,7 @@ def tessellate(shape, angularTolerance):


@deprecate()
def readAndDeleteFile(fileName):
def readAndDeleteFile(fileName: Path):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this really needed? No changes to legacy functions please.

"""
Read data from file provided, and delete it when done
return the contents as a string
Expand All @@ -225,5 +229,5 @@ def readAndDeleteFile(fileName):
with open(fileName, "r") as f:
res = "{}".format(f.read())

os.remove(fileName)
fileName.unlink()
return res
Loading