refactor(plugin): split orca.host bindings into host/ by domain

PluginHostApi.cpp had grown into one TU holding the module entry point plus
three unrelated domains (presets, model/mesh graph, app access), and
PluginHostSlicing.cpp mixed ownable geometry value types with the
non-owning live print graph. Reorganize the orca.host surface into
plugin/host/ with one registrar per domain:

- PluginHost.hpp/.cpp        entry point (replaces PluginHostApi)
- PluginHostBindings.hpp     internal per-domain registrar declarations
- PluginHostGeometry.cpp     BoundingBox, Point, Polygon, ExPolygon + ndarray parsing
- PluginHostMesh.hpp/.cpp    TriangleMesh snapshot (own TU ahead of planned
                             mesh construct/mutate APIs)
- PluginHostPresets.cpp      Preset, PresetCollection, PresetBundle
- PluginHostModel.cpp        scene graph: Model, ModelObject, ModelInstance, ModelVolume
- PluginHostApp.cpp          Plater + plater()/model()/preset_bundle() accessors
- PluginHostSlicing.cpp      live print graph only, now with a single lifetime story
- PluginHostUi.hpp/.cpp      moved unchanged

PluginBindingUtils.hpp stays at plugin/ root: it is shared with pluginTypes/
and tests, not host/-specific.

No Python-visible change: same submodules, class names and docstrings.
Verified with slic3rutils and fff_print suites.
This commit is contained in:
SoftFever
2026-07-11 16:18:59 +08:00
parent a04ce5f81e
commit 126e4d5445
20 changed files with 838 additions and 717 deletions

View File

@@ -0,0 +1,26 @@
#include "PluginHost.hpp"
#include "PluginHostBindings.hpp"
#include "PluginHostUi.hpp"
namespace Slic3r {
void PluginHost::RegisterBindings(pybind11::module_& module)
{
auto host = module.def_submodule("host", "Host application API");
// Value types first so the docstring signatures of later registrars
// resolve to the bound Python names.
host_bindings::register_geometry(host);
host_bindings::register_mesh(host);
host_bindings::register_presets(host);
host_bindings::register_model(host);
host_bindings::register_app(host);
// UI: native dialogs and interactive HTML windows for plugins.
PluginHostUi::RegisterBindings(host);
// Slicing print-graph data model (Print, Layer, Surface, ...).
host_bindings::register_slicing(host);
}
} // namespace Slic3r

View File

@@ -0,0 +1,17 @@
#pragma once
#include <pybind11/pybind11.h>
namespace Slic3r {
// Entry point of the `orca.host` Python API surface. Each domain of the
// surface (geometry, mesh, presets, model, app access, ui, slicing graph)
// lives in its own translation unit in this directory; RegisterBindings
// creates the submodule and runs the per-domain registrars.
class PluginHost
{
public:
static void RegisterBindings(pybind11::module_& module);
};
} // namespace Slic3r

View File

@@ -0,0 +1,60 @@
#include "PluginHostBindings.hpp"
#include <libslic3r/Model.hpp>
#include <libslic3r/PresetBundle.hpp>
#include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/GUI/Plater.hpp>
#include <memory>
#include <stdexcept>
namespace py = pybind11;
namespace Slic3r {
namespace {
GUI::Plater* current_plater()
{
if (wxTheApp == nullptr)
throw std::runtime_error("OrcaSlicer application is not initialized");
GUI::Plater* plater = GUI::wxGetApp().plater();
if (plater == nullptr)
throw std::runtime_error("Plater is not available");
return plater;
}
PresetBundle* current_preset_bundle()
{
if (wxTheApp == nullptr)
throw std::runtime_error("OrcaSlicer application is not initialized");
PresetBundle* preset_bundle = GUI::wxGetApp().preset_bundle;
if (preset_bundle == nullptr)
throw std::runtime_error("Preset bundle is not available");
return preset_bundle;
}
} // namespace
// Access to the live GUI application: the Plater and the module-level
// plater()/model()/preset_bundle() accessors. Everything here is owned by the
// app and only reachable once the GUI is up (the accessors throw before that).
void host_bindings::register_app(py::module_& host)
{
py::class_<GUI::Plater, std::unique_ptr<GUI::Plater, py::nodelete>>(host, "Plater")
.def("model", static_cast<Model& (GUI::Plater::*)()>(&GUI::Plater::model), py::return_value_policy::reference_internal)
.def("is_project_dirty", &GUI::Plater::is_project_dirty)
.def("is_presets_dirty", &GUI::Plater::is_presets_dirty)
.def("inside_snapshot_capture", &GUI::Plater::inside_snapshot_capture);
host.def("plater", &current_plater, py::return_value_policy::reference);
host.def("model", []() -> Model& {
return current_plater()->model();
}, py::return_value_policy::reference);
host.def("preset_bundle", &current_preset_bundle, py::return_value_policy::reference);
}
} // namespace Slic3r

View File

@@ -0,0 +1,16 @@
#pragma once
#include <pybind11/pybind11.h>
// Internal to plugin/host/: the per-domain registrars of the `orca.host`
// surface, one per translation unit, called by PluginHost::RegisterBindings.
namespace Slic3r::host_bindings {
void register_geometry(pybind11::module_& host); // PluginHostGeometry.cpp
void register_mesh(pybind11::module_& host); // PluginHostMesh.cpp
void register_presets(pybind11::module_& host); // PluginHostPresets.cpp
void register_model(pybind11::module_& host); // PluginHostModel.cpp
void register_app(pybind11::module_& host); // PluginHostApp.cpp
void register_slicing(pybind11::module_& host); // PluginHostSlicing.cpp
} // namespace Slic3r::host_bindings

View File

@@ -0,0 +1,216 @@
#include "PluginHostBindings.hpp"
#include "slic3r/plugin/PluginBindingUtils.hpp"
#include <libslic3r/BoundingBox.hpp>
#include <libslic3r/ClipperUtils.hpp> // offset/offset_ex/union_ex/diff_ex/intersection_ex
#include <libslic3r/ExPolygon.hpp>
#include <pybind11/stl.h>
#include <string>
#include <utility>
#include <vector>
namespace py = pybind11;
namespace Slic3r {
namespace {
// --- Input path: Python geometry -> C++ Polygon/ExPolygon, with validation. ---------------
// The mutators take scaled integer coords (the same units the read views hand out). A Python
// raise here surfaces as ValueError (pybind translates) so malformed input is rejected up
// front rather than silently corrupting the slicing graph.
// One (N,2) int64 ndarray -> Polygon. Rejects wrong dtype/shape and degenerate (<3 pt) rings.
// Float / NaN / inf are rejected implicitly: only a signed-integer, 8-byte (coord_t==int64)
// dtype is accepted, and integer arrays cannot hold NaN/inf.
Polygon parse_polygon(py::handle h, const char* who)
{
if (!py::isinstance<py::array>(h))
throw py::value_error(std::string(who) + ": each contour/hole must be an (N,2) int64 ndarray");
py::array a = py::reinterpret_borrow<py::array>(h);
if (a.dtype().kind() != 'i' || a.itemsize() != (py::ssize_t) sizeof(coord_t))
throw py::value_error(std::string(who) + ": polygon coordinates must be int64 (scaled coords)");
if (a.ndim() != 2 || a.shape(1) != 2)
throw py::value_error(std::string(who) + ": each polygon array must have shape (N,2)");
if (a.shape(0) < 3)
throw py::value_error(std::string(who) + ": a polygon needs at least 3 points");
// dtype already validated as int64; forcecast here only guarantees a C-contiguous buffer.
auto arr = py::array_t<coord_t, py::array::c_style | py::array::forcecast>::ensure(a);
if (!arr)
throw py::value_error(std::string(who) + ": could not read polygon as a contiguous int64 array");
auto r = arr.unchecked<2>();
Polygon poly;
poly.points.reserve((size_t) arr.shape(0));
for (py::ssize_t i = 0; i < arr.shape(0); ++i)
poly.points.emplace_back((coord_t) r(i, 0), (coord_t) r(i, 1));
return poly;
}
// Accept a bound orca.host.Polygon (copied) or an (N,2) int64 ndarray. Used by the ExPolygon
// binding, whose constructor/contour-setter/set_holes must accept the Polygon it itself hands
// out (e.g. `ExPolygon(some_polygon_ref)`) in addition to the ndarray-only parse_polygon() path.
Polygon as_polygon(py::handle h, const char* who)
{
if (py::isinstance<Polygon>(h))
return h.cast<Polygon>();
return parse_polygon(h, who);
}
} // namespace
void host_bindings::register_geometry(py::module_& host)
{
// ------------------------------------------------------------------
// Geometry value types of the `orca.host` surface. All use pybind's
// default holder, so plugins can construct and own instances. When
// obtained from the live slicing graph they are non-owning references
// instead — see the lifetime rule in PluginHostSlicing.cpp.
// ------------------------------------------------------------------
// Axis-aligned bounding box, returned by value (a copy) so its lifetime is
// independent of the model object it was computed from. Coordinates are in mm.
py::class_<BoundingBoxf3>(host, "BoundingBox", "Axis-aligned bounding box in millimetres")
.def_property_readonly("defined", [](const BoundingBoxf3& bb) { return bb.defined; })
.def_property_readonly("min", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.min); })
.def_property_readonly("max", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.max); })
.def_property_readonly("size", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.size()); })
.def_property_readonly("center", [](const BoundingBoxf3& bb) { return vec3_to_tuple(bb.center()); })
.def_property_readonly("radius", [](const BoundingBoxf3& bb) { return bb.radius(); });
// Point: a constructible value type (default holder, so Python-owned instances
// are freed). Returned-by-reference from Polygon.points, it aliases the buffer;
// x()/y() are Eigen lvalues, so the properties are read/write. p+q / p-q go
// through Eigen expression templates, wrapped back into a Point.
py::class_<Point>(host, "Point")
.def(py::init([](coord_t x, coord_t y) { return Point(x, y); }), py::arg("x"), py::arg("y"))
.def_property("x", [](const Point& p) { return p.x(); },
[](Point& p, coord_t v) { p.x() = v; })
.def_property("y", [](const Point& p) { return p.y(); },
[](Point& p, coord_t v) { p.y() = v; })
.def("__add__", [](const Point& a, const Point& b) { return Point(a + b); }, py::is_operator())
.def("__sub__", [](const Point& a, const Point& b) { return Point(a - b); }, py::is_operator())
.def("__mul__", [](const Point& a, double s) { return Point(a.x() * s, a.y() * s); }, py::is_operator())
.def("__repr__", [](const Point& p) {
return "orca.host.Point(" + std::to_string(p.x()) + ", " + std::to_string(p.y()) + ")";
});
py::class_<Polygon>(host, "Polygon")
.def(py::init<>())
.def("size", [](const Polygon& p) { return p.points.size(); })
.def("is_valid", [](const Polygon& p) { return p.is_valid(); })
.def("is_counter_clockwise", [](const Polygon& p) { return p.is_counter_clockwise(); })
.def("is_clockwise", [](const Polygon& p) { return p.is_clockwise(); })
.def("make_counter_clockwise", [](Polygon& p) { return p.make_counter_clockwise(); },
"Reorient to CCW in place. Returns True if it reversed the winding.")
.def("make_clockwise", [](Polygon& p) { return p.make_clockwise(); })
.def("area", [](const Polygon& p) { return p.area(); })
.def("centroid", [](const Polygon& p) { return p.centroid(); })
.def("contains", [](const Polygon& p, const Point& pt) { return p.contains(pt); }, py::arg("point"))
.def("translate", [](Polygon& p, double x, double y) { p.translate(x, y); }, py::arg("x"), py::arg("y"))
.def("rotate", [](Polygon& p, double angle) { p.rotate(angle); }, py::arg("angle"))
.def("rotate", [](Polygon& p, double angle, const Point& c) { p.rotate(angle, c); },
py::arg("angle"), py::arg("center"))
.def("douglas_peucker", [](Polygon& p, double tol) { p.douglas_peucker(tol); }, py::arg("tolerance"))
.def("simplify", [](const Polygon& p, double tol) { return p.simplify(tol); }, py::arg("tolerance"),
"Return simplified geometry as a list of Polygon (may split into several).")
.def("offset", [](const Polygon& p, coord_t delta) { return offset(p, (float) delta); }, py::arg("delta"),
"Clipper offset by `delta` scaled units (negative shrinks). Returns [Polygon].")
// --- Point-object idiom: references into the buffer (in-place element edit). ---
.def_property_readonly("points", [](py::object self) {
Polygon& p = self.cast<Polygon&>();
py::list out;
for (Point& pt : p.points)
out.append(py::cast(&pt, py::return_value_policy::reference_internal, self));
return out;
}, "Vertices as [Point] references into this polygon. Editing a Point mutates the "
"buffer in place. Structural changes (count) go through set_points/append, which "
"invalidate previously returned Point refs and array views (C++ vector semantics).")
.def("append", [](Polygon& p, const Point& pt) { p.points.push_back(pt); }, py::arg("point"),
"Append a vertex. Structural change (count): invalidates previously returned "
"Point refs and array views into this polygon (C++ vector semantics).")
// --- numpy idiom: writable zero-copy (N,2) view (bulk affine edits). ---
.def("as_array", [](py::object self) {
Polygon& p = self.cast<Polygon&>();
return with_numpy([&] {
return py::object(make_writable_rows<coord_t, 2>(
self, p.points.empty() ? nullptr : p.points.front().data(),
(py::ssize_t) p.points.size()));
});
}, "Vertices as a WRITABLE int64 (N,2) numpy view in scaled coords, aliasing the "
"buffer. Count-preserving in-place edits only; valid during execute(ctx). Requires numpy.")
.def("set_points", [](Polygon& p, py::handle src) { p = parse_polygon(src, "Polygon.set_points"); },
py::arg("points"),
"Replace all vertices from an (N,2) int64 ndarray (scaled coords). Count-changing; "
"invalidates prior Point refs and array views. Raises ValueError on malformed input.");
// ExPolygon: default holder (Python-owned instances are freed) so plugins can construct
// their own geometry, not just navigate the live slicing graph. contour/holes accessors
// still use reference_internal, so refs into a graph-owned ExPolygon stay non-owning views
// tied to that owner's lifetime, same as Polygon/Surface.
py::class_<ExPolygon>(host, "ExPolygon")
.def(py::init([](py::handle contour, py::handle holes) {
// Accept bound Polygons or (N,2) ndarrays for both contour and each hole.
ExPolygon ex;
ex.contour = as_polygon(contour, "ExPolygon.contour");
if (!holes.is_none()) {
if (!py::isinstance<py::sequence>(holes) || py::isinstance<py::str>(holes))
throw py::value_error("ExPolygon: holes must be a list of Polygon or (N,2) ndarrays");
for (py::handle h : py::reinterpret_borrow<py::sequence>(holes)) {
Polygon hole = as_polygon(h, "ExPolygon.hole");
hole.make_clockwise();
ex.holes.emplace_back(std::move(hole));
}
}
ex.contour.make_counter_clockwise();
return ex;
}), py::arg("contour"), py::arg("holes") = py::none(),
"Construct from a Polygon/ndarray contour and optional list of hole Polygons/ndarrays. "
"Orientation is normalized (contour CCW, holes CW).")
.def_property("contour",
[](ExPolygon& e) -> Polygon& { return e.contour; },
[](ExPolygon& e, py::handle v) { e.contour = as_polygon(v, "ExPolygon.contour"); },
py::return_value_policy::reference_internal,
"Outer contour (CCW). Read returns a live Polygon ref; assign a Polygon/ndarray to replace it.")
.def_property_readonly("holes", [](py::object self) {
ExPolygon& e = self.cast<ExPolygon&>();
py::list out;
for (Polygon& h : e.holes)
out.append(py::cast(&h, py::return_value_policy::reference_internal, self));
return out;
}, "Hole contours (CW) as [Polygon] references (in-place editable). set_holes replaces them.")
.def("set_holes", [](ExPolygon& e, py::handle holes) {
ExPolygon tmp;
if (!py::isinstance<py::sequence>(holes) || py::isinstance<py::str>(holes))
throw py::value_error("set_holes: expected a list of Polygon or (N,2) ndarrays");
for (py::handle h : py::reinterpret_borrow<py::sequence>(holes)) {
Polygon hole = as_polygon(h, "ExPolygon.set_holes");
hole.make_clockwise();
tmp.holes.emplace_back(std::move(hole));
}
e.holes = std::move(tmp.holes);
}, py::arg("holes"), "Replace all holes. Invalidates prior hole refs (C++ vector semantics).")
.def("translate", [](ExPolygon& e, double x, double y) { e.translate(x, y); }, py::arg("x"), py::arg("y"))
.def("rotate", [](ExPolygon& e, double a) { e.rotate(a); }, py::arg("angle"))
.def("rotate", [](ExPolygon& e, double a, const Point& c) { e.rotate(a, c); },
py::arg("angle"), py::arg("center"))
.def("scale", [](ExPolygon& e, double f) { e.scale(f); }, py::arg("factor"))
.def("douglas_peucker", [](ExPolygon& e, double t) { e.douglas_peucker(t); }, py::arg("tolerance"))
.def("area", [](const ExPolygon& e) { return e.area(); })
.def("is_valid", [](const ExPolygon& e) { return e.is_valid(); })
.def("contains", [](const ExPolygon& e, const Point& p) { return e.contains(p); }, py::arg("point"))
.def("num_contours", [](const ExPolygon& e) { return e.num_contours(); })
.def("simplify", [](const ExPolygon& e, double t) { return e.simplify(t); }, py::arg("tolerance"),
"Return simplified geometry as [ExPolygon].")
.def("offset", [](const ExPolygon& e, coord_t delta) { return offset_ex(e, (float) delta); },
py::arg("delta"), "Clipper offset by `delta` scaled units (negative shrinks). Returns [ExPolygon].")
.def("union_ex", [](const ExPolygon& a, const ExPolygon& b) {
return union_ex(ExPolygons{ a, b });
}, py::arg("other"), "Union with another ExPolygon. Returns [ExPolygon].")
.def("diff_ex", [](const ExPolygon& a, const ExPolygon& b) {
return diff_ex(ExPolygons{ a }, ExPolygons{ b });
}, py::arg("other"), "This minus `other`. Returns [ExPolygon].")
.def("intersection_ex", [](const ExPolygon& a, const ExPolygon& b) {
return intersection_ex(ExPolygons{ a }, ExPolygons{ b });
}, py::arg("other"), "Intersection with `other`. Returns [ExPolygon].");
}
} // namespace Slic3r

View File

@@ -0,0 +1,105 @@
#include "PluginHostBindings.hpp"
#include "PluginHostMesh.hpp"
#include "slic3r/plugin/PluginBindingUtils.hpp"
#include <pybind11/numpy.h>
#include <cstdint>
#include <memory>
#include <vector>
namespace py = pybind11;
namespace Slic3r {
namespace {
// Zero-copy export of its.vertices / its.indices relies on these Eigen
// row-vectors being tightly packed (no padding between the 3 components).
static_assert(sizeof(stl_vertex) == 3 * sizeof(float),
"stl_vertex must be a packed float[3] for zero-copy numpy export");
static_assert(sizeof(stl_triangle_vertex_indices) == 3 * sizeof(std::int32_t),
"triangle index must be a packed int32[3] for zero-copy numpy export");
// Read-only, zero-copy (rows, 3) numpy view over a packed T[rows][3] buffer.
// The array's base is a capsule owning a strong ref to `mesh`, so the view
// stays valid even if the volume's mesh is later replaced on the main thread.
template<typename T>
py::array make_readonly_rows3(const std::shared_ptr<const TriangleMesh>& mesh,
const T* data, py::ssize_t rows)
{
if (rows == 0 || data == nullptr)
return py::array_t<T>(std::vector<py::ssize_t>{ 0, 3 });
auto* owner = new std::shared_ptr<const TriangleMesh>(mesh);
py::capsule base(owner, [](void* p) {
delete reinterpret_cast<std::shared_ptr<const TriangleMesh>*>(p);
});
return make_readonly_rows<T, 3>(base, data, rows);
}
} // namespace
void host_bindings::register_mesh(py::module_& host)
{
py::class_<HostTriangleMesh>(host, "TriangleMesh",
"Immutable snapshot of a ModelVolume's mesh in local (untransformed) coordinates, mm.")
.def("vertex_count", [](const HostTriangleMesh& mesh) { return mesh.its().vertices.size(); })
.def("triangle_count", [](const HostTriangleMesh& mesh) { return mesh.its().indices.size(); })
.def("facets_count", [](const HostTriangleMesh& mesh) { return mesh.its().indices.size(); })
.def("is_empty", [](const HostTriangleMesh& mesh) { return mesh.its().indices.empty(); })
// Read-only, zero-copy (N, 3) float32 view of vertex positions. Requires numpy.
.def("vertices", [](const HostTriangleMesh& mesh) {
return with_numpy([&] {
const indexed_triangle_set& its = mesh.its();
return make_readonly_rows3<float>(
mesh.mesh,
its.vertices.empty() ? nullptr : its.vertices.front().data(),
static_cast<py::ssize_t>(its.vertices.size()));
});
}, "Read-only zero-copy (N, 3) float32 ndarray of vertex positions (local mm). Requires numpy.")
// Read-only, zero-copy (M, 3) int32 view of triangle vertex indices. Requires numpy.
.def("triangles", [](const HostTriangleMesh& mesh) {
return with_numpy([&] {
const indexed_triangle_set& its = mesh.its();
return make_readonly_rows3<std::int32_t>(
mesh.mesh,
its.indices.empty() ? nullptr : its.indices.front().data(),
static_cast<py::ssize_t>(its.indices.size()));
});
}, "Read-only zero-copy (M, 3) int32 ndarray of triangle vertex indices. Requires numpy.")
// One normalized normal per triangle as an (M, 3) float32 copy. Requires numpy.
.def("face_normals", [](const HostTriangleMesh& mesh) {
return with_numpy([&] {
std::vector<Vec3f> normals = its_face_normals(mesh.its());
py::array_t<float> array({ static_cast<py::ssize_t>(normals.size()), py::ssize_t(3) });
if (!normals.empty()) {
auto view = array.mutable_unchecked<2>();
for (size_t i = 0; i < normals.size(); ++i) {
view(i, 0) = normals[i].x();
view(i, 1) = normals[i].y();
view(i, 2) = normals[i].z();
}
}
return py::object(std::move(array));
});
}, "Per-triangle normalized normals as an (M, 3) float32 ndarray (copy). Requires numpy.")
// numpy-free element access, bounds-checked.
.def("vertex", [](const HostTriangleMesh& mesh, size_t index) {
const std::vector<stl_vertex>& vertices = mesh.its().vertices;
if (index >= vertices.size())
throw py::index_error("vertex index out of range");
const stl_vertex& vertex = vertices[index];
return py::make_tuple(vertex.x(), vertex.y(), vertex.z());
})
.def("triangle", [](const HostTriangleMesh& mesh, size_t index) {
const std::vector<stl_triangle_vertex_indices>& indices = mesh.its().indices;
if (index >= indices.size())
throw py::index_error("triangle index out of range");
const stl_triangle_vertex_indices& triangle = indices[index];
return py::make_tuple(triangle[0], triangle[1], triangle[2]);
})
.def("volume", [](const HostTriangleMesh& mesh) { return mesh.mesh->stats().volume; })
.def("bounding_box", [](const HostTriangleMesh& mesh) { return bbox_from_stats(mesh.mesh->stats()); })
.def("is_manifold", [](const HostTriangleMesh& mesh) { return mesh.mesh->stats().manifold(); });
}
} // namespace Slic3r

View File

@@ -0,0 +1,28 @@
#pragma once
#include <libslic3r/BoundingBox.hpp>
#include <libslic3r/TriangleMesh.hpp>
#include <memory>
namespace Slic3r {
// Immutable snapshot of a ModelVolume's mesh. Holding a strong reference to the
// const mesh keeps any zero-copy numpy views valid even if the volume's mesh is
// later replaced on the main thread. Bound as `orca.host.TriangleMesh` in
// PluginHostMesh.cpp; constructed by ModelVolume.mesh() in PluginHostModel.cpp.
struct HostTriangleMesh
{
std::shared_ptr<const TriangleMesh> mesh;
const indexed_triangle_set& its() const { return mesh->its; }
};
// Build a BoundingBoxf3 from precomputed (float) triangle-mesh stats min/max.
inline BoundingBoxf3 bbox_from_stats(const TriangleMeshStats& stats)
{
if (stats.number_of_facets == 0)
return BoundingBoxf3();
return BoundingBoxf3(stats.min.cast<double>(), stats.max.cast<double>());
}
} // namespace Slic3r

View File

@@ -0,0 +1,203 @@
#include "PluginHostBindings.hpp"
#include "PluginHostMesh.hpp"
#include "slic3r/plugin/PluginBindingUtils.hpp"
#include <libslic3r/Model.hpp>
#include <pybind11/stl.h>
#include <string>
namespace py = pybind11;
namespace Slic3r {
// The scene/document graph: Model -> ModelObject -> ModelInstance/ModelVolume.
// Everything is bound py::nodelete — non-owning references into a graph owned
// by the app (the live Plater model) or by a Print's model snapshot.
void host_bindings::register_model(py::module_& host)
{
py::enum_<ModelVolumeType>(host, "ModelVolumeType")
.value("Invalid", ModelVolumeType::INVALID)
.value("ModelPart", ModelVolumeType::MODEL_PART)
.value("NegativeVolume", ModelVolumeType::NEGATIVE_VOLUME)
.value("ParameterModifier", ModelVolumeType::PARAMETER_MODIFIER)
.value("SupportBlocker", ModelVolumeType::SUPPORT_BLOCKER)
.value("SupportEnforcer", ModelVolumeType::SUPPORT_ENFORCER);
py::class_<ModelVolume, std::unique_ptr<ModelVolume, py::nodelete>>(host, "ModelVolume")
.def("id", [](const ModelVolume& volume) { return volume.id().id; })
.def_readonly("name", &ModelVolume::name)
.def("type", &ModelVolume::type)
.def("is_model_part", &ModelVolume::is_model_part)
.def("is_modifier", &ModelVolume::is_modifier)
.def("is_negative_volume", &ModelVolume::is_negative_volume)
.def("is_support_enforcer", &ModelVolume::is_support_enforcer)
.def("is_support_blocker", &ModelVolume::is_support_blocker)
.def("is_support_modifier", &ModelVolume::is_support_modifier)
// Extruder ID is 1-based for FFF, -1 for SLA or support volumes.
.def("extruder_id", &ModelVolume::extruder_id)
.def("offset", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_offset()); })
.def("rotation", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_rotation()); })
.def("scaling_factor", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_scaling_factor()); })
.def("mirror", [](const ModelVolume& volume) { return vec3_to_tuple(volume.get_mirror()); })
// 4x4 float64 affine matrix mapping this volume into its parent object frame. Requires numpy.
.def("matrix", [](const ModelVolume& volume) { return mat4_to_numpy(volume.get_matrix()); },
"Volume-to-object 4x4 float64 affine matrix (copy). Requires numpy.")
.def("facets_count", [](const ModelVolume& volume) { return volume.mesh().facets_count(); })
// Raw (untransformed) mesh volume in mm^3; -1 if it was never computed.
.def("volume", [](const ModelVolume& volume) { return volume.mesh().stats().volume; })
// Bounding box of the raw (untransformed) mesh, in the volume's local frame.
.def("bounding_box", [](const ModelVolume& volume) { return bbox_from_stats(volume.mesh().stats()); })
.def("is_manifold", [](const ModelVolume& volume) { return volume.mesh().stats().manifold(); })
// Full mesh geometry (vertices/triangles) as an immutable snapshot.
.def("mesh", [](const ModelVolume& volume) {
return HostTriangleMesh{ volume.get_mesh_shared_ptr() };
}, "Return the volume's TriangleMesh (local coordinates) for vertex/triangle access.")
.def("mesh_errors_count", [](const ModelVolume& volume) { return volume.get_repaired_errors_count(); })
.def("is_fdm_support_painted", &ModelVolume::is_fdm_support_painted)
.def("is_seam_painted", &ModelVolume::is_seam_painted)
.def("is_mm_painted", &ModelVolume::is_mm_painted)
.def("is_fuzzy_skin_painted", &ModelVolume::is_fuzzy_skin_painted)
.def("config_keys", [](const ModelVolume& volume) { return volume.config.keys(); })
.def("config_value", [](const ModelVolume& volume, const std::string& key) {
return config_value_or_none(volume.config.get(), key);
});
py::class_<ModelInstance, std::unique_ptr<ModelInstance, py::nodelete>>(host, "ModelInstance")
.def("id", [](const ModelInstance& instance) { return instance.id().id; })
.def_readonly("printable", &ModelInstance::printable)
// True only if the object is printable, this instance is printable and it
// currently sits fully inside the print volume (set during slicing).
.def("is_printable", &ModelInstance::is_printable)
.def("offset", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_offset()); })
.def("rotation", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_rotation()); })
.def("scaling_factor", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_scaling_factor()); })
.def("mirror", [](const ModelInstance& instance) { return vec3_to_tuple(instance.get_mirror()); })
// 4x4 float64 affine matrix mapping the object into world space. Requires numpy.
// World vertices = instance.matrix() @ volume.matrix() applied to mesh vertices.
.def("matrix", [](const ModelInstance& instance) { return mat4_to_numpy(instance.get_matrix()); },
"Object-to-world 4x4 float64 affine matrix (copy). Requires numpy.")
.def("is_left_handed", &ModelInstance::is_left_handed)
// Assemble-view placement. Each instance carries a second transform used only by
// the Assemble view, set from stored 3mf assemble data or derived from the regular
// transform. Until then (is_assemble_initialized() false) it is identity.
.def("is_assemble_initialized", [](ModelInstance& instance) { return instance.is_assemble_initialized(); })
.def("assemble_offset", [](const ModelInstance& instance) {
return vec3_to_tuple(instance.get_assemble_transformation().get_offset());
})
.def("assemble_rotation", [](const ModelInstance& instance) {
return vec3_to_tuple(instance.get_assemble_transformation().get_rotation());
})
// 4x4 float64 affine matrix placing the object in the Assemble view. Requires numpy.
.def("assemble_matrix", [](const ModelInstance& instance) {
return mat4_to_numpy(instance.get_assemble_transformation().get_matrix());
}, "Assemble-view 4x4 float64 affine matrix (copy). Requires numpy.")
// Offset from the instance origin to its position within the source assembly,
// recorded at import time (e.g. from a STEP assembly).
.def("offset_to_assembly", [](const ModelInstance& instance) {
return vec3_to_tuple(instance.get_offset_to_assembly());
})
// World-space bounding box of this instance.
.def("bounding_box", [](ModelInstance& instance) {
const ModelObject* object = instance.get_object();
if (object == nullptr)
return BoundingBoxf3();
return object->instance_bounding_box(instance);
});
py::class_<ModelObject, std::unique_ptr<ModelObject, py::nodelete>>(host, "ModelObject")
.def("id", [](const ModelObject& object) { return object.id().id; })
.def_readonly("name", &ModelObject::name)
.def_readonly("module_name", &ModelObject::module_name)
.def_readonly("input_file", &ModelObject::input_file)
// Import-time flag only: the GUI's printable toggle writes the per-instance
// ModelInstance::printable and never updates this field, so derive an
// object's effective state from its instances.
.def_readonly("printable", &ModelObject::printable)
.def("instance_count", [](const ModelObject& object) {
return object.instances.size();
})
.def("volume_count", [](const ModelObject& object) {
return object.volumes.size();
})
.def("instances", [](ModelObject& object) {
py::list instances;
for (ModelInstance* instance : object.instances)
instances.append(py::cast(instance, py::return_value_policy::reference));
return instances;
})
.def("instance", [](ModelObject& object, size_t index) -> ModelInstance* {
if (index >= object.instances.size())
throw py::index_error("instance index out of range");
return object.instances[index];
}, py::return_value_policy::reference_internal)
.def("volumes", [](ModelObject& object) {
py::list volumes;
for (ModelVolume* volume : object.volumes)
volumes.append(py::cast(volume, py::return_value_policy::reference));
return volumes;
})
.def("volume", [](ModelObject& object, size_t index) -> ModelVolume* {
if (index >= object.volumes.size())
throw py::index_error("volume index out of range");
return object.volumes[index];
}, py::return_value_policy::reference_internal)
// World-space bounding box over all instances of this object.
.def("bounding_box", [](const ModelObject& object) { return object.bounding_box_exact(); })
// Bounding box of the object's raw (untransformed) part meshes — its intrinsic size.
.def("raw_mesh_bounding_box", [](const ModelObject& object) { return object.raw_mesh_bounding_box(); })
.def("min_z", &ModelObject::min_z)
.def("max_z", &ModelObject::max_z)
.def("facets_count", [](const ModelObject& object) { return object.facets_count(); })
.def("parts_count", [](const ModelObject& object) { return object.parts_count(); })
.def("materials_count", [](const ModelObject& object) { return object.materials_count(); })
.def("mesh_errors_count", [](const ModelObject& object) { return object.get_repaired_errors_count(); })
.def("is_multiparts", &ModelObject::is_multiparts)
.def("is_cut", &ModelObject::is_cut)
.def("has_custom_layering", &ModelObject::has_custom_layering)
.def("is_fdm_support_painted", &ModelObject::is_fdm_support_painted)
.def("is_seam_painted", &ModelObject::is_seam_painted)
.def("is_mm_painted", &ModelObject::is_mm_painted)
.def("is_fuzzy_skin_painted", &ModelObject::is_fuzzy_skin_painted)
.def("config_keys", [](const ModelObject& object) {
return object.config.keys();
})
.def("config_value", [](const ModelObject& object, const std::string& key) {
return config_value_or_none(object.config.get(), key);
});
py::class_<Model, std::unique_ptr<Model, py::nodelete>>(host, "Model")
.def("id", [](const Model& model) { return model.id().id; })
.def("object_count", [](const Model& model) {
return model.objects.size();
})
.def("object", [](Model& model, size_t index) -> ModelObject* {
if (index >= model.objects.size())
throw py::index_error("model object index out of range");
return model.objects[index];
}, py::return_value_policy::reference_internal)
.def("objects", [](Model& model) {
py::list objects;
for (ModelObject* object : model.objects)
objects.append(py::cast(object, py::return_value_policy::reference));
return objects;
})
// World-space bounding box of the whole model. bounding_box() is exact;
// bounding_box_approx() is faster and cached.
.def("bounding_box", [](const Model& model) { return model.bounding_box_exact(); })
.def("bounding_box_approx", [](const Model& model) { return model.bounding_box_approx(); })
.def("max_z", &Model::max_z)
.def("material_count", [](const Model& model) { return model.materials.size(); })
.def("is_fdm_support_painted", &Model::is_fdm_support_painted)
.def("is_seam_painted", &Model::is_seam_painted)
.def("is_mm_painted", &Model::is_mm_painted)
.def("is_fuzzy_skin_painted", &Model::is_fuzzy_skin_painted)
.def("current_plate_index", [](const Model& model) { return model.curr_plate_index; })
.def("designer", [](const Model& model) {
return model.design_info ? model.design_info->Designer : std::string();
})
.def("design_id", [](const Model& model) { return model.stl_design_id; });
}
} // namespace Slic3r

View File

@@ -0,0 +1,138 @@
#include "PluginHostBindings.hpp"
#include "slic3r/plugin/PluginBindingUtils.hpp"
#include <libslic3r/Preset.hpp>
#include <libslic3r/PresetBundle.hpp>
#include <pybind11/stl.h>
#include <string>
#include <vector>
namespace py = pybind11;
namespace Slic3r {
namespace {
py::list current_filament_presets(PresetBundle& bundle)
{
py::list presets;
for (const std::string& preset_name : bundle.filament_presets) {
Preset* preset = bundle.filaments.find_preset(preset_name);
if (preset == nullptr)
presets.append(py::none());
else
presets.append(py::cast(preset, py::return_value_policy::reference));
}
return presets;
}
PresetCollection& printer_presets(PresetBundle& bundle)
{
return static_cast<PresetCollection&>(bundle.printers);
}
} // namespace
void host_bindings::register_presets(py::module_& host)
{
py::enum_<Preset::Type>(host, "PresetType")
.value("Invalid", Preset::TYPE_INVALID)
.value("Print", Preset::TYPE_PRINT)
.value("SlaPrint", Preset::TYPE_SLA_PRINT)
.value("Filament", Preset::TYPE_FILAMENT)
.value("SlaMaterial", Preset::TYPE_SLA_MATERIAL)
.value("Printer", Preset::TYPE_PRINTER)
.value("PhysicalPrinter", Preset::TYPE_PHYSICAL_PRINTER)
.value("Plate", Preset::TYPE_PLATE)
.value("Model", Preset::TYPE_MODEL);
py::class_<Preset, std::unique_ptr<Preset, py::nodelete>>(host, "Preset")
.def_readonly("type", &Preset::type)
.def_readonly("name", &Preset::name)
.def_readonly("alias", &Preset::alias)
.def_readonly("file", &Preset::file)
.def_readonly("is_default", &Preset::is_default)
.def_readonly("is_external", &Preset::is_external)
.def_readonly("is_system", &Preset::is_system)
.def_readonly("is_visible", &Preset::is_visible)
.def_readonly("is_dirty", &Preset::is_dirty)
.def_readonly("is_compatible", &Preset::is_compatible)
.def_readonly("is_project_embedded", &Preset::is_project_embedded)
.def_readonly("bundle_id", &Preset::bundle_id)
.def("is_user", &Preset::is_user)
.def("is_from_bundle", &Preset::is_from_bundle)
.def("label", &Preset::label, py::arg("no_alias") = false)
.def("config_keys", [](const Preset& preset) { return preset.config.keys(); })
.def("config_value", [](const Preset& preset, const std::string& key) {
return config_value_or_none(preset.config, key);
});
py::class_<PresetCollection, std::unique_ptr<PresetCollection, py::nodelete>>(host, "PresetCollection")
.def("size", &PresetCollection::size)
.def("get_selected_preset", [](PresetCollection& collection) -> Preset& {
return collection.get_selected_preset();
}, py::return_value_policy::reference_internal)
.def("selected_preset", [](PresetCollection& collection) -> Preset& {
return collection.get_selected_preset();
}, py::return_value_policy::reference_internal)
.def("get_selected_preset_name", &PresetCollection::get_selected_preset_name)
.def("selected_preset_name", &PresetCollection::get_selected_preset_name)
.def("get_edited_preset", [](PresetCollection& collection) -> Preset& {
return collection.get_edited_preset();
}, py::return_value_policy::reference_internal)
.def("edited_preset", [](PresetCollection& collection) -> Preset& {
return collection.get_edited_preset();
}, py::return_value_policy::reference_internal)
.def("preset", [](PresetCollection& collection, size_t index) -> Preset& {
if (index >= collection.size())
throw py::index_error("preset index out of range");
return collection.preset(index);
}, py::return_value_policy::reference_internal)
.def("find_preset", [](PresetCollection& collection, const std::string& name) -> Preset* {
return collection.find_preset(name);
}, py::return_value_policy::reference_internal)
.def("preset_names", [](const PresetCollection& collection) {
std::vector<std::string> names;
names.reserve(collection.get_presets().size());
for (const Preset& preset : collection.get_presets())
names.push_back(preset.name);
return names;
});
py::class_<PresetBundle, std::unique_ptr<PresetBundle, py::nodelete>>(host, "PresetBundle")
.def_property_readonly("prints", [](PresetBundle& bundle) -> PresetCollection& {
return bundle.prints;
}, py::return_value_policy::reference_internal)
.def_property_readonly("printers", &printer_presets, py::return_value_policy::reference_internal)
.def_property_readonly("filaments", [](PresetBundle& bundle) -> PresetCollection& {
return bundle.filaments;
}, py::return_value_policy::reference_internal)
.def_property_readonly("sla_prints", [](PresetBundle& bundle) -> PresetCollection& {
return bundle.sla_prints;
}, py::return_value_policy::reference_internal)
.def_property_readonly("sla_materials", [](PresetBundle& bundle) -> PresetCollection& {
return bundle.sla_materials;
}, py::return_value_policy::reference_internal)
.def("current_process_preset", [](PresetBundle& bundle) -> Preset& {
return bundle.prints.get_edited_preset();
}, py::return_value_policy::reference_internal)
.def("current_print_preset", [](PresetBundle& bundle) -> Preset& {
return bundle.prints.get_edited_preset();
}, py::return_value_policy::reference_internal)
.def("current_printer_preset", [](PresetBundle& bundle) -> Preset& {
return bundle.printers.get_edited_preset();
}, py::return_value_policy::reference_internal)
.def("current_filament_preset_names", [](PresetBundle& bundle) {
return bundle.filament_presets;
})
.def("current_filament_presets", &current_filament_presets)
.def("full_config_keys", [](const PresetBundle& bundle) {
return bundle.full_config().keys();
})
.def("full_config_value", [](const PresetBundle& bundle, const std::string& key) {
return config_value_or_none(bundle.full_config(), key);
});
}
} // namespace Slic3r

View File

@@ -0,0 +1,352 @@
#include "PluginHostBindings.hpp"
#include "slic3r/plugin/PluginBindingUtils.hpp"
#include "libslic3r/BoundingBox.hpp"
#include "libslic3r/ExPolygon.hpp"
#include "libslic3r/Surface.hpp"
#include "libslic3r/SurfaceCollection.hpp"
#include "libslic3r/ExtrusionEntity.hpp"
#include "libslic3r/ExtrusionEntityCollection.hpp"
#include "libslic3r/Layer.hpp" // LayerRegion, Layer, SupportLayer
#include "libslic3r/Print.hpp" // PrintRegion, PrintObject, Print
#include <pybind11/stl.h>
#include <memory>
#include <vector>
namespace py = pybind11;
namespace Slic3r {
namespace {
// Flatten an extrusion graph into a list of leaf ExtrusionPath* while walking the
// ORIGINAL Print-owned tree (never a temporary copy): the returned pointers stay
// valid for the execute(ctx) lifetime pinned by `owner`, so points() can hand out
// zero-copy views into path->polyline.points.
//
// This is deliberately NOT ExtrusionEntityCollection::flatten(): flatten() only
// unwraps nested collections (is_collection() is true solely for collections) and
// returns them by value, so it would (a) dangle if we viewed into the copy and
// (b) leave ExtrusionLoop/ExtrusionMultiPath intact — dropping every perimeter
// loop, since dynamic_cast<ExtrusionPath*> fails on a loop. We descend into
// loops/multipaths here to reach their contained paths.
static void collect_extrusion_paths(const ExtrusionEntity* ee, std::vector<const ExtrusionPath*>& out)
{
if (ee == nullptr)
return;
if (const auto* coll = dynamic_cast<const ExtrusionEntityCollection*>(ee)) {
for (const ExtrusionEntity* child : coll->entities)
collect_extrusion_paths(child, out);
} else if (const auto* loop = dynamic_cast<const ExtrusionLoop*>(ee)) {
for (const ExtrusionPath& p : loop->paths)
out.push_back(&p);
} else if (const auto* mp = dynamic_cast<const ExtrusionMultiPath*>(ee)) {
for (const ExtrusionPath& p : mp->paths)
out.push_back(&p);
} else if (const auto* path = dynamic_cast<const ExtrusionPath*>(ee)) {
// Catches ExtrusionPath and its subclasses (Sloped/Contoured/Oriented) last,
// after the composite types above have been ruled out.
out.push_back(path);
}
}
// Rebuild a layer's per-island bbox cache from lslices — the same inline pattern
// every C++ call site uses (PrintObjectSlice.cpp, Print.cpp, TreeSupport.cpp); no
// libslic3r helper exists to reuse.
static void refresh_lslices_bboxes(Layer& l)
{
l.lslices_bboxes.clear();
l.lslices_bboxes.reserve(l.lslices.size());
for (const ExPolygon& island : l.lslices)
l.lslices_bboxes.emplace_back(get_extents(island));
}
} // namespace
void host_bindings::register_slicing(py::module_& host)
{
// ------------------------------------------------------------------
// Slicing print-graph data model — raw bindings of the classes the C++
// pipeline itself uses, same nodelete/reference style as the Model and
// Preset graphs in PluginHostModel.cpp / PluginHostPresets.cpp.
//
// LIFETIME (C++ semantics, the one rule of this API): every object handed
// out below is a non-owning reference into the live slicing graph owned by
// the Print. References — and every numpy view they hand out — are valid
// only while the plugin hook (execute(ctx)) runs, and a container-replacing
// mutator (SurfaceCollection.set / append / clear, Polygon.set_points / append,
// ExPolygon.set_holes) invalidates previously obtained references into that
// container, exactly as std::vector operations invalidate C++ iterators. Do
// not stash references or arrays across execute() calls; copy what you need.
// ------------------------------------------------------------------
py::enum_<SurfaceType>(host, "SurfaceType")
.value("stTop", stTop)
.value("stBottom", stBottom)
.value("stBottomBridge", stBottomBridge)
.value("stInternalAfterExternalBridge", stInternalAfterExternalBridge)
.value("stInternal", stInternal)
.value("stInternalSolid", stInternalSolid)
.value("stInternalBridge", stInternalBridge)
.value("stSecondInternalBridge", stSecondInternalBridge)
.value("stInternalVoid", stInternalVoid)
.value("stPerimeter", stPerimeter)
.value("stCount", stCount)
.export_values();
// Surface: default holder (Python-owned instances are freed), so plugins can construct
// their own Surface(surface_type, expolygon) — not just navigate the live slicing graph.
// expolygon is a reference_internal property, same idiom as the Polygon/ExPolygon
// accessors in PluginHostGeometry.cpp.
py::class_<Surface>(host, "Surface")
.def(py::init([](SurfaceType t, const ExPolygon& e) { return Surface(t, e); }),
py::arg("surface_type"), py::arg("expolygon"))
.def(py::init([](SurfaceType t) { return Surface(t); }), py::arg("surface_type"))
.def_readwrite("surface_type", &Surface::surface_type,
"This surface's SurfaceType. Assigning reclassifies it in place (geometry unchanged).")
.def_readwrite("thickness", &Surface::thickness)
.def_readwrite("bridge_angle", &Surface::bridge_angle)
.def_readwrite("extra_perimeters", &Surface::extra_perimeters)
.def_property("expolygon",
[](Surface& s) -> ExPolygon& { return s.expolygon; },
[](Surface& s, const ExPolygon& e) { s.expolygon = e; },
py::return_value_policy::reference_internal,
"This surface's geometry. Read returns a live ExPolygon ref; assign to replace it.")
.def("area", [](const Surface& s) { return s.area(); })
.def("is_top", [](const Surface& s) { return s.is_top(); })
.def("is_bottom", [](const Surface& s) { return s.is_bottom(); })
.def("is_bridge", [](const Surface& s) { return s.is_bridge(); })
.def("is_internal", [](const Surface& s) { return s.is_internal(); })
.def("is_external", [](const Surface& s) { return s.is_external(); })
.def("is_solid", [](const Surface& s) { return s.is_solid(); });
// SurfaceCollection: kept on py::nodelete — it is only ever a reference into the live
// slicing graph (LayerRegion::slices/fill_surfaces), never constructed by a plugin.
py::class_<SurfaceCollection, std::unique_ptr<SurfaceCollection, py::nodelete>>(host, "SurfaceCollection")
.def("size", [](const SurfaceCollection& c) { return c.surfaces.size(); })
.def("empty", [](const SurfaceCollection& c) { return c.empty(); })
.def("clear", [](SurfaceCollection& c) { c.clear(); })
.def("has", [](const SurfaceCollection& c, SurfaceType t) { return c.has(t); }, py::arg("surface_type"))
.def("set_type", [](SurfaceCollection& c, SurfaceType t) { c.set_type(t); }, py::arg("surface_type"))
.def("set", [](SurfaceCollection& c, const std::vector<ExPolygon>& src, SurfaceType t) { c.set(src, t); },
py::arg("expolygons"), py::arg("surface_type"),
"Replace all surfaces from a list of ExPolygon, all tagged `surface_type`.")
.def("set", [](SurfaceCollection& c, const std::vector<Surface>& src) { c.set(src); },
py::arg("surfaces"), "Replace all surfaces from a list of Surface (types preserved per surface).")
.def("append", [](SurfaceCollection& c, const std::vector<ExPolygon>& src, SurfaceType t) { c.append(src, t); },
py::arg("expolygons"), py::arg("surface_type"))
.def("filter_by_type", [](py::object self, SurfaceType t) {
SurfaceCollection& c = self.cast<SurfaceCollection&>();
py::list out;
// SurfaceCollection::filter_by_type returns SurfacesPtr, which is
// std::vector<const Surface*> (see Surface.hpp), so iterate by const
// pointer (py::cast accepts `const itype*` directly, see cast.h cast(const itype*)).
for (const Surface* s : c.filter_by_type(t))
out.append(py::cast(s, py::return_value_policy::reference_internal, self));
return out;
}, py::arg("surface_type"), "Surfaces of a given type as [Surface] refs. Invalidated by "
"set()/append()/clear() on this collection (C++ vector semantics), same as .surfaces.")
.def_property_readonly("surfaces", [](py::object self) {
SurfaceCollection& c = self.cast<SurfaceCollection&>();
py::list out;
for (Surface& s : c.surfaces)
out.append(py::cast(&s, py::return_value_policy::reference_internal, self));
return out;
}, "Surfaces as [Surface] references into the live collection. Invalidated by "
"set()/append()/clear() on this collection (C++ vector semantics).");
// --- Extrusion tree (read-only). Registered polymorphically: when a returned
// ExtrusionEntity*'s dynamic type IS one of the classes registered below, pybind
// hands the plugin that concrete type, so plugins walk the same tree shape C++ does.
// When the dynamic type is NOT registered (e.g. ExtrusionLoopSloped, produced with
// scarf seams), pybind falls back to the STATIC type at the cast site -- so such a
// `.entities` child surfaces as a bare ExtrusionEntity (only .role is available).
// flatten_paths() (a dynamic_cast walk) still yields proper ExtrusionPath leaves and
// is the robust way to extract toolpaths.
py::class_<ExtrusionEntity, std::unique_ptr<ExtrusionEntity, py::nodelete>>(host, "ExtrusionEntity")
.def_property_readonly("role", [](const ExtrusionEntity& e) {
return ExtrusionEntity::role_to_string(e.role());
}, "Extrusion role as a human-readable string (e.g. \"Outer wall\", \"Sparse infill\").");
py::class_<ExtrusionPath, ExtrusionEntity, std::unique_ptr<ExtrusionPath, py::nodelete>>(host, "ExtrusionPath")
.def("points", [](py::object self) {
const ExtrusionPath& p = self.cast<const ExtrusionPath&>();
const Points3& pts = p.polyline.points;
return with_numpy([&] {
return py::object(make_readonly_rows<coord_t, 3>(
self, pts.empty() ? nullptr : pts.front().data(), (py::ssize_t) pts.size()));
});
}, "Path vertices as a read-only int64 (N,3) numpy view in scaled coords "
"(the polyline is natively 3D on this branch). Requires numpy.")
.def_readonly("width", &ExtrusionPath::width)
.def_readonly("height", &ExtrusionPath::height)
.def_readonly("mm3_per_mm", &ExtrusionPath::mm3_per_mm);
py::class_<ExtrusionLoop, ExtrusionEntity, std::unique_ptr<ExtrusionLoop, py::nodelete>>(host, "ExtrusionLoop")
.def_property_readonly("paths", [](py::object self) {
ExtrusionLoop& l = self.cast<ExtrusionLoop&>();
py::list out;
for (ExtrusionPath& p : l.paths)
out.append(py::cast(&p, py::return_value_policy::reference_internal, self));
return out;
}, "The loop's constituent paths as [ExtrusionPath].");
py::class_<ExtrusionMultiPath, ExtrusionEntity, std::unique_ptr<ExtrusionMultiPath, py::nodelete>>(host, "ExtrusionMultiPath")
.def_property_readonly("paths", [](py::object self) {
ExtrusionMultiPath& m = self.cast<ExtrusionMultiPath&>();
py::list out;
for (ExtrusionPath& p : m.paths)
out.append(py::cast(&p, py::return_value_policy::reference_internal, self));
return out;
}, "The multipath's constituent paths as [ExtrusionPath].");
py::class_<ExtrusionEntityCollection, ExtrusionEntity,
std::unique_ptr<ExtrusionEntityCollection, py::nodelete>>(host, "ExtrusionEntityCollection")
.def("size", [](const ExtrusionEntityCollection& c) { return c.entities.size(); })
.def_property_readonly("entities", [](py::object self) {
ExtrusionEntityCollection& c = self.cast<ExtrusionEntityCollection&>();
py::list out;
for (ExtrusionEntity* e : c.entities)
out.append(py::cast(e, py::return_value_policy::reference_internal, self));
return out;
}, "Child entities. Each is handed to you as its concrete type only when that type "
"is registered; a child whose concrete type is unregistered (e.g. a scarf-seam "
"ExtrusionLoopSloped) surfaces as a bare ExtrusionEntity exposing only .role. Use "
"flatten_paths() to robustly reach every ExtrusionPath leaf.")
.def("flatten_paths", [](py::object self) {
const ExtrusionEntityCollection& c = self.cast<const ExtrusionEntityCollection&>();
std::vector<const ExtrusionPath*> paths;
collect_extrusion_paths(&c, paths);
py::list out;
for (const ExtrusionPath* p : paths)
out.append(py::cast(const_cast<ExtrusionPath*>(p),
py::return_value_policy::reference_internal, self));
return out;
}, "Every leaf ExtrusionPath under this tree (collections recursed into, "
"loops/multipaths decomposed).");
py::class_<PrintRegion, std::unique_ptr<PrintRegion, py::nodelete>>(host, "PrintRegion")
.def("config_keys", [](const PrintRegion& r) { return r.config().keys(); })
.def("config_value", [](const PrintRegion& r, const std::string& key) {
return config_value_or_none(r.config(), key);
}, py::arg("key"),
"Serialized value of this region's resolved config option, or None if absent.");
auto layer_region = py::class_<LayerRegion, std::unique_ptr<LayerRegion, py::nodelete>>(host, "LayerRegion");
layer_region
.def_readonly("slices", &LayerRegion::slices,
"Sliced, typed surfaces (SurfaceCollection). Edit in place, or replace with "
"slices.set(expolygons, surface_type). At Step.posSlice this is the primary mutation "
"target; the split slice loop runs make_perimeters() afterward so edits cascade downstream.")
.def_readonly("fill_surfaces", &LayerRegion::fill_surfaces,
"Surfaces prepared for infill (SurfaceCollection). Edit in place or via fill_surfaces.set(...).")
.def_readonly("perimeters", &LayerRegion::perimeters,
"Perimeter toolpaths (ExtrusionEntityCollection, read-only).")
.def_readonly("fills", &LayerRegion::fills,
"Infill toolpaths (ExtrusionEntityCollection, read-only).")
.def("layer", [](LayerRegion& r) -> py::object {
Layer* l = r.layer();
if (l == nullptr)
return py::none();
return py::cast(l, py::return_value_policy::reference);
}, "Owning Layer, or None.")
.def("region", [](LayerRegion& r) -> const PrintRegion& { return r.region(); },
py::return_value_policy::reference,
"This region's PrintRegion (resolved per-region settings).")
.def("config_value", [](const LayerRegion& r, const std::string& key) {
return config_value_or_none(r.region().config(), key);
}, py::arg("key"),
"Serialized value of this region's resolved config option, or None if absent.");
auto layer = py::class_<Layer, std::unique_ptr<Layer, py::nodelete>>(host, "Layer");
layer
.def_readonly("print_z", &Layer::print_z)
.def_readonly("slice_z", &Layer::slice_z)
.def_readonly("height", &Layer::height)
.def_property_readonly("upper_layer", [](Layer& l) -> py::object {
if (l.upper_layer == nullptr) return py::none();
return py::cast(l.upper_layer, py::return_value_policy::reference);
}, "The layer above, or None (graph navigation, like C++).")
.def_property_readonly("lower_layer", [](Layer& l) -> py::object {
if (l.lower_layer == nullptr) return py::none();
return py::cast(l.lower_layer, py::return_value_policy::reference);
}, "The layer below, or None.")
.def("regions", [](py::object self) {
Layer& l = self.cast<Layer&>();
py::list out;
for (LayerRegion* r : l.regions())
out.append(py::cast(r, py::return_value_policy::reference_internal, self));
return out;
}, "Per-region data as [LayerRegion].")
.def("make_slices", [](Layer& l) {
l.make_slices();
refresh_lslices_bboxes(l);
}, "Re-derive lslices (merged islands) from the region slices and refresh the bbox "
"cache — the C++ invariant-maintenance call after in-place slice edits.")
.def("lslices", [](py::object self) {
Layer& l = self.cast<Layer&>();
py::list out;
for (ExPolygon& e : l.lslices)
out.append(py::cast(&e, py::return_value_policy::reference_internal, self));
return out;
}, "Merged per-layer islands as [ExPolygon] refs (in-place editable). Derived from the "
"region slices; call make_slices() to re-derive after edits. Invalidated by make_slices().");
py::class_<PrintObject, std::unique_ptr<PrintObject, py::nodelete>>(host, "PrintObject")
.def("id", [](const PrintObject& o) { return o.id().id; },
"Stable numeric object id (ObjectBase::id()).")
.def("layers", [](py::object self) {
PrintObject& o = self.cast<PrintObject&>();
py::list out;
for (Layer* l : o.layers())
out.append(py::cast(l, py::return_value_policy::reference_internal, self));
return out;
}, "Object layers, bottom-up, as [Layer].")
.def("support_layers", [](py::object self) {
PrintObject& o = self.cast<PrintObject&>();
py::list out;
for (SupportLayer* sl : o.support_layers())
out.append(py::cast(static_cast<Layer*>(sl),
py::return_value_policy::reference_internal, self));
return out;
}, "Support layers as [Layer] (support-specific fields are not exposed).")
.def("model_object", [](PrintObject& o) -> py::object {
// The Print's model SNAPSHOT (worker-thread stable), reusing the
// orca.host.ModelObject bindings — mesh access for slicing plugins.
// o is non-const here, so model_object() already returns a non-const ModelObject*.
return py::cast(o.model_object(), py::return_value_policy::reference);
}, "The source orca.host.ModelObject from the Print's own model snapshot.")
.def("bounding_box", [](const PrintObject& o) {
const BoundingBox bb = o.bounding_box();
return py::make_tuple(bb.min.x(), bb.min.y(), bb.max.x(), bb.max.y());
}, "Object XY bounding box in scaled coords as (min_x, min_y, max_x, max_y). The "
"sliced polygons live in this same frame, so its midpoint is the footprint center.")
.def("trafo", [](const PrintObject& o) { return mat4_to_numpy(o.trafo()); },
"Object-to-print 4x4 float64 affine matrix (copy). Requires numpy.")
.def("config_keys", [](const PrintObject& o) { return o.config().keys(); })
.def("config_value", [](const PrintObject& o, const std::string& key) {
return config_value_or_none(o.config(), key);
}, py::arg("key"),
"Serialized value of a resolved per-object config option, or None if absent.");
py::class_<Print, std::unique_ptr<Print, py::nodelete>>(host, "Print")
.def("objects", [](py::object self) {
Print& p = self.cast<Print&>();
py::list out;
for (PrintObject* o : p.objects())
out.append(py::cast(o, py::return_value_policy::reference_internal, self));
return out;
}, "The print's objects as [PrintObject].")
.def("model", [](Print& p) -> Model& { return const_cast<Model&>(p.model()); },
py::return_value_policy::reference_internal,
"The Print's own Model snapshot (worker-thread stable). Inside slicing "
"hooks use THIS — never orca.host.model(), which is the live GUI model "
"owned by another thread.")
.def("config_keys", [](const Print& p) { return p.full_print_config().keys(); })
.def("config_value", [](const Print& p, const std::string& key) {
return config_value_or_none(p.full_print_config(), key);
}, py::arg("key"),
"Serialized value of the resolved (full) print config for this slice, or None.")
.def("canceled", [](const Print& p) { return p.canceled(); },
"True once cancellation was requested (prefer ctx.cancelled()).");
}
} // namespace Slic3r

View File

@@ -0,0 +1,562 @@
#include "PluginHostUi.hpp"
#include "slic3r/plugin/PluginAuditManager.hpp"
#include "slic3r/plugin/PythonInterpreter.hpp" // PythonGILState
#include <slic3r/GUI/GUI_App.hpp>
#include <slic3r/GUI/MainFrame.hpp>
#include <slic3r/GUI/MsgDialog.hpp>
#include <slic3r/GUI/PluginProgressDialog.hpp>
#include <slic3r/GUI/PluginWebDialog.hpp>
#include <nlohmann/json.hpp>
#include <pybind11/pybind11.h>
#include <boost/log/trivial.hpp>
#include <wx/app.h>
#include <wx/defs.h>
#include <wx/window.h>
#include <cstdint>
#include <future>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <type_traits>
#include <unordered_map>
#include <vector>
namespace py = pybind11;
using json = nlohmann::json;
namespace Slic3r {
namespace {
// --------------------------------------------------------------------------
// JSON <-> Python conversion (caller must hold the GIL).
// --------------------------------------------------------------------------
py::object json_to_py(const json& j)
{
switch (j.type()) {
case json::value_t::null: return py::none();
case json::value_t::boolean: return py::bool_(j.get<bool>());
case json::value_t::number_integer: return py::int_(j.get<std::int64_t>());
case json::value_t::number_unsigned: return py::int_(j.get<std::uint64_t>());
case json::value_t::number_float: return py::float_(j.get<double>());
case json::value_t::string: return py::str(j.get<std::string>());
case json::value_t::array: {
py::list lst;
for (const auto& e : j)
lst.append(json_to_py(e));
return lst;
}
case json::value_t::object: {
py::dict d;
for (auto it = j.begin(); it != j.end(); ++it)
d[py::str(it.key())] = json_to_py(it.value());
return d;
}
default: return py::none();
}
}
json py_to_json(const py::handle& o)
{
if (o.is_none())
return json(nullptr);
if (py::isinstance<py::bool_>(o)) // bool before int (bool subclasses int in Python)
return o.cast<bool>();
if (py::isinstance<py::int_>(o))
return o.cast<std::int64_t>();
if (py::isinstance<py::float_>(o))
return o.cast<double>();
if (py::isinstance<py::str>(o))
return o.cast<std::string>();
if (py::isinstance<py::bytes>(o))
return o.cast<std::string>();
if (py::isinstance<py::dict>(o)) {
json obj = json::object();
for (auto item : py::reinterpret_borrow<py::dict>(o))
obj[py::str(item.first).cast<std::string>()] = py_to_json(item.second);
return obj;
}
if (py::isinstance<py::list>(o) || py::isinstance<py::tuple>(o)) {
json arr = json::array();
for (auto e : o)
arr.push_back(py_to_json(e));
return arr;
}
return py::str(o).cast<std::string>(); // fallback: str()
}
// --------------------------------------------------------------------------
// GIL-safe holder for a Python callable. A std::function that captured a bare
// py::object could be destroyed on the main thread without the GIL (a dialog
// teardown), which would Py_DECREF unsafely. Wrapping the callable here means
// the GIL is acquired exactly when the last reference is released, on any thread.
// --------------------------------------------------------------------------
struct GilSafeCallable
{
py::object fn;
explicit GilSafeCallable(py::object f) : fn(std::move(f)) {}
~GilSafeCallable()
{
if (fn) {
PythonGILState gil;
fn = py::object();
}
}
};
using CallablePtr = std::shared_ptr<GilSafeCallable>;
CallablePtr make_holder(py::object obj)
{
if (!obj || obj.is_none())
return nullptr;
return std::make_shared<GilSafeCallable>(std::move(obj));
}
// Adapt a Python callable to a GUI message handler that acquires the GIL and
// swallows/logs exceptions (a raising handler must not escape into wx events).
GUI::PluginWebDialog::MessageHandler make_message_adapter(py::object on_message)
{
CallablePtr holder = make_holder(std::move(on_message));
if (!holder)
return nullptr;
return [holder](const json& data) {
PythonGILState gil;
try {
holder->fn(json_to_py(data));
} catch (py::error_already_set& e) {
BOOST_LOG_TRIVIAL(error) << "orca.host.ui on_message handler raised: " << e.what();
PyErr_Clear();
}
};
}
// --------------------------------------------------------------------------
// Registry of live plugin UI resources. Keyed by an opaque id; tracks the
// owning plugin so all of a plugin's UI can be torn down on unload.
// --------------------------------------------------------------------------
class UiRegistry
{
public:
static UiRegistry& instance()
{
static UiRegistry r;
return r;
}
int reserve_id()
{
std::lock_guard<std::mutex> lk(m_mtx);
return m_next_id++;
}
void bind(int id, wxWindow* window, const std::string& plugin_key)
{
std::lock_guard<std::mutex> lk(m_mtx);
m_resources[id] = window;
m_owners[id] = plugin_key;
}
void remove(int id)
{
std::lock_guard<std::mutex> lk(m_mtx);
m_resources.erase(id);
m_owners.erase(id);
}
template<typename T>
T* get_as(int id)
{
std::lock_guard<std::mutex> lk(m_mtx);
auto it = m_resources.find(id);
if (it == m_resources.end())
return nullptr;
return dynamic_cast<T*>(it->second);
}
bool is_open(int id)
{
std::lock_guard<std::mutex> lk(m_mtx);
return m_resources.count(id) > 0; // presence only; no pointer deref -> thread-safe
}
std::vector<wxWindow*> take_for_plugin(const std::string& plugin_key)
{
std::lock_guard<std::mutex> lk(m_mtx);
std::vector<wxWindow*> out;
for (auto it = m_owners.begin(); it != m_owners.end();) {
if (it->second == plugin_key) {
auto rit = m_resources.find(it->first);
if (rit != m_resources.end()) {
out.push_back(rit->second);
m_resources.erase(rit);
}
it = m_owners.erase(it);
} else {
++it;
}
}
return out;
}
private:
std::mutex m_mtx;
std::unordered_map<int, wxWindow*> m_resources;
std::unordered_map<int, std::string> m_owners;
int m_next_id{1};
};
// --------------------------------------------------------------------------
// Run a (pure C++/wx) callable on the main/UI thread, blocking the caller until
// it completes, with the GIL released across the wait. If already on the main
// thread, run inline (also with the GIL released so other Python threads run).
// --------------------------------------------------------------------------
template<typename Fn>
auto run_on_ui_blocking(Fn&& fn) -> std::invoke_result_t<Fn&>
{
using R = std::invoke_result_t<Fn&>;
if (wxTheApp == nullptr)
throw std::runtime_error("OrcaSlicer application is not initialized");
if (wxIsMainThread()) {
py::gil_scoped_release nogil;
return fn();
}
std::promise<R> prom;
std::future<R> fut = prom.get_future();
py::gil_scoped_release nogil;
GUI::wxGetApp().CallAfter([&prom, &fn]() {
try {
if constexpr (std::is_void_v<R>) {
fn();
prom.set_value();
} else {
prom.set_value(fn());
}
} catch (...) {
prom.set_exception(std::current_exception());
}
});
return fut.get();
}
wxWindow* ui_parent()
{
return wxTheApp == nullptr ? nullptr : dynamic_cast<wxWindow*>(GUI::wxGetApp().mainframe);
}
// --------------------------------------------------------------------------
// orca.host.ui.message
// --------------------------------------------------------------------------
long message_style(const std::string& buttons, const std::string& icon)
{
long style = wxOK;
if (buttons == "ok_cancel")
style = wxOK | wxCANCEL;
else if (buttons == "yes_no")
style = wxYES_NO;
else if (buttons == "yes_no_cancel")
style = wxYES_NO | wxCANCEL;
if (icon == "warning")
style |= wxICON_WARNING;
else if (icon == "error")
style |= wxICON_ERROR;
else if (icon == "question")
style |= wxICON_QUESTION;
else
style |= wxICON_INFORMATION;
return style;
}
std::string button_to_string(int rc)
{
switch (rc) {
case wxID_OK: return "ok";
case wxID_YES: return "yes";
case wxID_NO: return "no";
default: return "cancel";
}
}
std::string ui_message(const std::string& text, const std::string& title,
const std::string& buttons, const std::string& icon)
{
const long style = message_style(buttons, icon);
return run_on_ui_blocking([&]() -> std::string {
GUI::MessageDialog dlg(nullptr, wxString::FromUTF8(text), wxString::FromUTF8(title), style);
return button_to_string(dlg.ShowModal());
});
}
// --------------------------------------------------------------------------
// orca.host.ui.show_dialog (modal)
// --------------------------------------------------------------------------
py::object ui_show_dialog(const std::string& html, const std::string& title,
int width, int height, py::object on_message)
{
auto handler = make_message_adapter(std::move(on_message));
const int w = width > 0 ? width : 820;
const int h = height > 0 ? height : 600;
std::optional<json> result = run_on_ui_blocking([&]() -> std::optional<json> {
return GUI::PluginWebDialog::show_modal_dialog(ui_parent(), wxString::FromUTF8(title), html, wxSize(w, h),
std::move(handler));
});
if (!result.has_value())
return py::none();
return json_to_py(*result); // GIL held in the binding body
}
// --------------------------------------------------------------------------
// orca.host.ui.create_window (non-modal) + UiWindow handle
// --------------------------------------------------------------------------
struct UiWindowHandle
{
int id{0};
};
struct UiProgressHandle
{
int id{0};
};
py::object ui_create_window(const std::string& html, const std::string& title, int width, int height,
py::object on_message, py::object on_close)
{
auto msg_adapter = make_message_adapter(std::move(on_message));
CallablePtr close_holder = make_holder(std::move(on_close));
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
const int w = width > 0 ? width : 820;
const int h = height > 0 ? height : 600;
const int id = run_on_ui_blocking([&]() -> int {
const int new_id = UiRegistry::instance().reserve_id();
// Plugin's on_close: fired only on a user/JS-initiated close (not forced
// teardown), while the dialog is alive. Empty if the plugin passed None.
GUI::PluginWebDialog::CloseHandler on_close;
if (close_holder) {
on_close = [close_holder]() {
PythonGILState gil;
try {
close_holder->fn();
} catch (py::error_already_set& e) {
BOOST_LOG_TRIVIAL(error) << "orca.host.ui on_close handler raised: " << e.what();
PyErr_Clear();
}
};
}
// Registry cleanup: GIL-free, runs from the dialog destructor on every path.
auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); };
auto* dlg = GUI::PluginWebDialog::create_modeless_dialog(ui_parent(), wxString::FromUTF8(title), html,
wxSize(w, h), std::move(msg_adapter),
std::move(on_close), std::move(on_destroyed));
UiRegistry::instance().bind(new_id, dlg, plugin_key);
GUI::PluginWebDialog::show_modeless_dialog(dlg);
return new_id;
});
return py::cast(UiWindowHandle{id});
}
void handle_post(int id, py::object data)
{
if (wxTheApp == nullptr)
return;
json j = py_to_json(data); // GIL held (binding body)
GUI::wxGetApp().CallAfter([id, j = std::move(j)]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginWebDialog>(id);
GUI::PluginWebDialog::post_message(d, j);
});
}
void handle_close(int id)
{
if (wxTheApp == nullptr)
return;
GUI::wxGetApp().CallAfter([id]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginWebDialog>(id);
GUI::PluginWebDialog::request_close(d);
});
}
UiProgressHandle ui_create_progress_dialog(const std::string& title, const std::string& message, int maximum, int style)
{
const std::string plugin_key = PluginAuditManager::instance().current_plugin();
const int max_value = maximum > 0 ? maximum : 100;
return run_on_ui_blocking([&]() -> UiProgressHandle {
const int new_id = UiRegistry::instance().reserve_id();
// Registry cleanup: GIL-free, runs from the dialog destructor on every path.
auto on_destroyed = [new_id]() { UiRegistry::instance().remove(new_id); };
auto* dlg = GUI::PluginProgressDialog::create_dialog(ui_parent(), wxString::FromUTF8(title),
wxString::FromUTF8(message), max_value, style,
std::move(on_destroyed));
UiRegistry::instance().bind(new_id, dlg, plugin_key);
return UiProgressHandle{new_id};
});
}
UiProgressHandle* new_progress_dialog(const std::string& title, const std::string& message, int maximum, int style)
{
return new UiProgressHandle(ui_create_progress_dialog(title, message, maximum, style));
}
bool progress_is_open(int id)
{
return UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id) != nullptr;
}
bool progress_pulse(int id, const std::string& message)
{
return run_on_ui_blocking([&]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id);
return GUI::PluginProgressDialog::pulse(d, wxString::FromUTF8(message));
});
}
bool progress_update(int id, int value, const std::string& message)
{
return run_on_ui_blocking([&]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id);
return GUI::PluginProgressDialog::update(d, value, wxString::FromUTF8(message));
});
}
void progress_start_pulse(int id, int interval_ms, const std::string& message)
{
run_on_ui_blocking([&]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id);
GUI::PluginProgressDialog::start_pulse(d, interval_ms, wxString::FromUTF8(message));
});
}
void progress_stop_pulse(int id)
{
run_on_ui_blocking([&]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id);
GUI::PluginProgressDialog::stop_pulse(d);
});
}
void progress_close(int id)
{
run_on_ui_blocking([&]() {
auto* d = UiRegistry::instance().get_as<GUI::PluginProgressDialog>(id);
GUI::PluginProgressDialog::request_close(d);
});
}
} // namespace
void PluginHostUi::RegisterBindings(pybind11::module_& host)
{
auto ui = host.def_submodule(
"ui",
"Host UI: native dialogs and interactive HTML windows. Calls run on the main/UI "
"thread (marshaled from the plugin thread). See the plugin docs for the window.orca bridge.");
ui.def("message", &ui_message, py::arg("text"), py::arg("title") = "OrcaSlicer", py::arg("buttons") = "ok",
py::arg("icon") = "info",
"Show a native modal message box; returns the clicked button id "
"(\"ok\"/\"cancel\"/\"yes\"/\"no\"). buttons: \"ok\"|\"ok_cancel\"|\"yes_no\"|\"yes_no_cancel\"; "
"icon: \"info\"|\"warning\"|\"error\"|\"question\".");
ui.def("show_dialog", &ui_show_dialog, py::arg("html"), py::arg("title") = "OrcaSlicer", py::arg("width") = 820,
py::arg("height") = 600, py::arg("on_message") = py::none(),
"Show a modal dialog rendering the given raw HTML. The page talks to the plugin via "
"window.orca (postMessage/onMessage/submit/close). Blocks until closed; returns the "
"orca.submit() payload as a dict, or None.");
ui.attr("PD_APP_MODAL") = py::int_(wxPD_APP_MODAL);
ui.attr("PD_AUTO_HIDE") = py::int_(wxPD_AUTO_HIDE);
ui.attr("PD_CAN_ABORT") = py::int_(wxPD_CAN_ABORT);
ui.attr("PD_CAN_SKIP") = py::int_(wxPD_CAN_SKIP);
ui.attr("PD_ELAPSED_TIME") = py::int_(wxPD_ELAPSED_TIME);
ui.attr("PD_ESTIMATED_TIME") = py::int_(wxPD_ESTIMATED_TIME);
ui.attr("PD_REMAINING_TIME") = py::int_(wxPD_REMAINING_TIME);
py::class_<UiWindowHandle>(ui, "UiWindow", "Handle to a non-modal plugin window created by create_window().")
.def_property_readonly("id", [](const UiWindowHandle& h) { return h.id; })
.def(
"post", [](const UiWindowHandle& h, py::object data) { handle_post(h.id, std::move(data)); },
py::arg("data"), "Send a payload to the page (delivered to window.orca.onMessage handlers).")
.def(
"close", [](const UiWindowHandle& h) { handle_close(h.id); }, "Close the window (fires on_close).")
.def(
"is_open", [](const UiWindowHandle& h) { return UiRegistry::instance().is_open(h.id); },
"Return True while the window is open.");
ui.def("create_window", &ui_create_window, py::arg("html"), py::arg("title") = "OrcaSlicer", py::arg("width") = 820,
py::arg("height") = 600, py::arg("on_message") = py::none(), py::arg("on_close") = py::none(),
"Open a non-modal, persistent HTML window and return a UiWindow. on_message(data) is called on "
"the UI thread when the page posts; offload heavy work to a thread and push results back with "
"window.post().");
py::class_<UiProgressHandle>(ui, "ProgressDialog", "Handle to a native progress dialog.")
.def(py::init(&new_progress_dialog), py::arg("title"), py::arg("message"), py::arg("maximum") = 100,
py::arg("style") = wxPD_APP_MODAL | wxPD_AUTO_HIDE)
.def_property_readonly("id", [](const UiProgressHandle& h) { return h.id; })
.def(
"pulse", [](const UiProgressHandle& h, const std::string& message) { return progress_pulse(h.id, message); },
py::arg("message") = "", "Pulse the dialog gauge; returns False if the dialog is closed or cancelled.")
.def(
"update",
[](const UiProgressHandle& h, int value, const std::string& message) {
return progress_update(h.id, value, message);
},
py::arg("value"), py::arg("message") = "",
"Set the dialog progress value; returns False if the dialog is closed or cancelled.")
.def(
"start_pulse",
[](const UiProgressHandle& h, int interval_ms, const std::string& message) {
progress_start_pulse(h.id, interval_ms, message);
},
py::arg("interval_ms") = 100, py::arg("message") = "", "Start periodic pulsing.")
.def(
"stop_pulse", [](const UiProgressHandle& h) { progress_stop_pulse(h.id); }, "Stop periodic pulsing.")
.def(
"close", [](const UiProgressHandle& h) { progress_close(h.id); }, "Close the progress dialog.")
.def(
"is_open", [](const UiProgressHandle& h) { return progress_is_open(h.id); },
"Return True while this progress dialog is registered.")
.def("__enter__", [](UiProgressHandle& h) -> UiProgressHandle& { return h; }, py::return_value_policy::reference_internal)
.def("__exit__", [](const UiProgressHandle& h, py::object, py::object, py::object) {
progress_close(h.id);
return false;
});
ui.def("create_progress_dialog", &ui_create_progress_dialog, py::arg("title"), py::arg("message"),
py::arg("maximum") = 100, py::arg("style") = wxPD_APP_MODAL | wxPD_AUTO_HIDE,
"Create a native progress dialog and return a ProgressDialog handle.");
}
void PluginHostUi::close_windows_for_plugin(const std::string& plugin_key)
{
if (wxTheApp == nullptr)
return;
auto teardown = [plugin_key]() {
// Destroy() bypasses wxEVT_CLOSE, so the plugin's on_close is not fired on
// forced teardown (intended); the resource destructor still cleans the registry.
for (auto* window : UiRegistry::instance().take_for_plugin(plugin_key)) {
if (window != nullptr)
window->Destroy();
}
};
if (wxIsMainThread())
teardown();
else
GUI::wxGetApp().CallAfter(teardown);
}
} // namespace Slic3r

View File

@@ -0,0 +1,24 @@
#pragma once
#include <pybind11/pybind11.h>
#include <string>
namespace Slic3r {
// Binds the `orca.host.ui` submodule: native message boxes, progress dialogs,
// and interactive HTML windows for plugins. All calls run on the main/UI thread
// (marshaled from the plugin worker thread) and the host owns every window.
class PluginHostUi
{
public:
static void RegisterBindings(pybind11::module_& host);
// Lifecycle hook: close and tear down every UI window owned by a plugin.
// Registered via PluginLoader::subscribe_on_unload_callback so UI windows
// are destroyed on plugin unload/reload and at app shutdown (before the
// Python interpreter is finalized). Matches PluginLifecycleCompleteFn.
static void close_windows_for_plugin(const std::string& plugin_key);
};
} // namespace Slic3r