Save FreeCAD WebAssembly development state
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
Some checks failed
FreeCAD master CI / Prepare (push) Has been cancelled
FreeCAD master CI / Pixi (push) Has been cancelled
FreeCAD master CI / Ubuntu (push) Has been cancelled
FreeCAD master CI / Windows (push) Has been cancelled
FreeCAD master CI / Lint (push) Has been cancelled
FreeCAD master CI / WrapUp (push) Has been cancelled
CodeQL Advanced / Analyze (actions) (push) Has been cancelled
CodeQL Advanced / Analyze (python) (push) Has been cancelled
Scorecard supply-chain security / Scorecard analysis (push) Has been cancelled
This commit is contained in:
@@ -1,11 +1,21 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <App/DocumentObjectGroup.h>
|
||||
#include <App/Link.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Assembly/App/AssemblyObject.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <cstddef>
|
||||
@@ -23,11 +33,162 @@ namespace {
|
||||
std::string lastErrorCode;
|
||||
std::string lastErrorMessage;
|
||||
std::string lastTypeName;
|
||||
std::string dispatchResponse;
|
||||
unsigned int initializationCalls = 0;
|
||||
unsigned int initializationRuns = 0;
|
||||
bool assemblyInitialized = false;
|
||||
std::vector<App::DocumentObject*> handles;
|
||||
|
||||
struct ReadonlyFixture {
|
||||
bool passed = false;
|
||||
bool connected = false;
|
||||
bool grounded = false;
|
||||
bool jointConnecting = false;
|
||||
int downstreamCount = 0;
|
||||
bool resourcesReleased = false;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
struct DocumentGraphFixture {
|
||||
bool passed = false;
|
||||
int objectCount = 0;
|
||||
int assemblyCount = 0;
|
||||
int groupCount = 0;
|
||||
bool linkConnected = false;
|
||||
bool resourcesReleased = false;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
struct ViewResourceFixture {
|
||||
bool passed = false;
|
||||
bool guiUnavailable = false;
|
||||
bool resourcesReleased = false;
|
||||
std::string error;
|
||||
};
|
||||
|
||||
DocumentGraphFixture runDocumentGraphFixture()
|
||||
{
|
||||
DocumentGraphFixture result;
|
||||
App::Document* document = nullptr;
|
||||
auto& application = App::GetApplication();
|
||||
const char* const assemblyTypes[] = {
|
||||
"Assembly::AssemblyLink",
|
||||
"Assembly::AssemblyObject",
|
||||
"Assembly::BomGroup",
|
||||
"Assembly::BomObject",
|
||||
"Assembly::JointGroup",
|
||||
"Assembly::SimulationGroup",
|
||||
"Assembly::ViewGroup",
|
||||
};
|
||||
try {
|
||||
document = application.newDocument("AssemblyDocumentGraph", "Assembly Document Graph", {false, true});
|
||||
auto* assembly = document
|
||||
? dynamic_cast<Assembly::AssemblyObject*>(document->addObject("Assembly::AssemblyObject", "Assembly"))
|
||||
: nullptr;
|
||||
auto* component = document ? document->addObject("Part::Feature", "Component") : nullptr;
|
||||
auto* link = document ? dynamic_cast<App::Link*>(document->addObject("App::Link", "Link")) : nullptr;
|
||||
auto* root = document
|
||||
? dynamic_cast<App::DocumentObjectGroup*>(document->addObject("App::DocumentObjectGroup", "Graph"))
|
||||
: nullptr;
|
||||
if (!assembly || !component || !link || !root) {
|
||||
throw Base::RuntimeError("Assembly document graph fixture object creation failed");
|
||||
}
|
||||
link->setLink(-1, component);
|
||||
assembly->addObject(component);
|
||||
root->addObject(assembly);
|
||||
root->addObject(link);
|
||||
bool hasError = false;
|
||||
if (document->recompute({}, false, &hasError) < 0 || hasError) {
|
||||
throw Base::RuntimeError("Assembly document graph fixture recompute failed");
|
||||
}
|
||||
result.objectCount = static_cast<int>(document->countObjects());
|
||||
result.linkConnected = link->getLinkedObject() == component;
|
||||
result.groupCount = root->hasObject(assembly) && root->hasObject(link) ? 1 : 0;
|
||||
result.assemblyCount = 1;
|
||||
int probeIndex = 0;
|
||||
for (const char* typeName : assemblyTypes) {
|
||||
const std::string probeName = std::string("Probe") + std::to_string(probeIndex++);
|
||||
if (document->addObject(typeName, probeName.c_str())) {
|
||||
++result.assemblyCount;
|
||||
}
|
||||
}
|
||||
result.passed = result.objectCount >= 4 && result.linkConnected && result.groupCount == 1
|
||||
&& result.assemblyCount == 8;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
result.resourcesReleased = application.getDocuments().empty();
|
||||
if (!result.passed || !result.resourcesReleased) {
|
||||
throw Base::RuntimeError("Assembly document graph fixture semantic mismatch");
|
||||
}
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
result.error = "unknown Assembly document graph fixture failure";
|
||||
}
|
||||
if (document) {
|
||||
application.closeDocument(document);
|
||||
}
|
||||
result.resourcesReleased = application.getDocuments().empty();
|
||||
return result;
|
||||
}
|
||||
|
||||
ReadonlyFixture runReadonlyFixture()
|
||||
{
|
||||
ReadonlyFixture result;
|
||||
App::Document* document = nullptr;
|
||||
auto& application = App::GetApplication();
|
||||
try {
|
||||
document = application.newDocument("AssemblyReadonly", "Assembly Readonly", {false, true});
|
||||
if (!document) {
|
||||
throw Base::RuntimeError("Assembly readonly fixture document creation failed");
|
||||
}
|
||||
auto* assembly = dynamic_cast<Assembly::AssemblyObject*>(
|
||||
document->addObject("Assembly::AssemblyObject", "Assembly"));
|
||||
auto* part = document->addObject("Part::Feature", "Part");
|
||||
if (!assembly || !part) {
|
||||
throw Base::RuntimeError("Assembly readonly fixture object creation failed");
|
||||
}
|
||||
assembly->Type.setValue("Assembly");
|
||||
assembly->addObject(part);
|
||||
bool hasError = false;
|
||||
document->recompute({}, false, &hasError);
|
||||
if (hasError) {
|
||||
throw Base::RuntimeError("Assembly readonly fixture recompute failed");
|
||||
}
|
||||
result.connected = assembly->isPartConnected(part);
|
||||
result.grounded = assembly->isPartGrounded(part);
|
||||
result.jointConnecting = assembly->isJointConnectingPartToGround(nullptr, "Reference1");
|
||||
result.downstreamCount = static_cast<int>(assembly->getDownstreamParts(part, nullptr).size());
|
||||
result.passed = !result.connected && !result.grounded && !result.jointConnecting
|
||||
&& result.downstreamCount == 0;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
result.resourcesReleased = application.getDocuments().empty();
|
||||
if (!result.passed || !result.resourcesReleased) {
|
||||
throw Base::RuntimeError("Assembly readonly fixture semantic mismatch");
|
||||
}
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
result.error = "unknown Assembly readonly fixture failure";
|
||||
}
|
||||
if (document) {
|
||||
application.closeDocument(document);
|
||||
}
|
||||
result.resourcesReleased = application.getDocuments().empty();
|
||||
return result;
|
||||
}
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
lastErrorCode = code;
|
||||
@@ -99,7 +260,18 @@ bool ensureAssembly()
|
||||
addPythonModule("Materials", PyInit_Materials);
|
||||
addPythonModule("Part", PyInit_Part);
|
||||
addPythonModule("Spreadsheet", PyInit_Spreadsheet);
|
||||
addPythonModule("AssemblyApp", PyInit_AssemblyApp);
|
||||
// The extension initializer returns the historical ``AssemblyApp``
|
||||
// module object, while AssemblyObject's Python proxy imports the
|
||||
// public ``Assembly`` name. Register both names without invoking the
|
||||
// initializer twice (which would re-register FreeCAD types).
|
||||
addPythonModule("Assembly", PyInit_AssemblyApp);
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
auto* assemblyModule = PyDict_GetItemString(modules, "Assembly");
|
||||
if (assemblyModule && !PyDict_GetItemString(modules, "AssemblyApp")) {
|
||||
if (PyDict_SetItemString(modules, "AssemblyApp", assemblyModule) != 0) {
|
||||
throw Base::RuntimeError("failed to alias Assembly Python module");
|
||||
}
|
||||
}
|
||||
if (Base::Type::fromName("Assembly::AssemblyObject").isBad()) {
|
||||
throw Base::RuntimeError("Assembly::AssemblyObject was not registered");
|
||||
}
|
||||
@@ -137,6 +309,40 @@ bool requireModule(const char* moduleName)
|
||||
return ensureAssembly();
|
||||
}
|
||||
|
||||
ViewResourceFixture runViewResourceFixture()
|
||||
{
|
||||
ViewResourceFixture result;
|
||||
try {
|
||||
// The Web probe deliberately has no AssemblyGui/PySide surface. Keep
|
||||
// this boundary native so view-resource records are never simulated in JS.
|
||||
result.guiUnavailable = !requireModule("AssemblyGui")
|
||||
&& lastErrorCode == "gui_dependency_unavailable";
|
||||
auto& application = App::GetApplication();
|
||||
result.resourcesReleased = application.getDocuments().empty();
|
||||
for (const auto* handle : handles) {
|
||||
if (handle) {
|
||||
result.resourcesReleased = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
result.passed = result.guiUnavailable && result.resourcesReleased;
|
||||
if (!result.passed) {
|
||||
result.error = "Assembly GUI-free view-resource boundary fixture failed";
|
||||
}
|
||||
clearError();
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
result.error = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
result.error = "unknown Assembly view-resource fixture failure";
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
@@ -239,4 +445,338 @@ EMSCRIPTEN_KEEPALIVE int fc_web_assembly_initialized()
|
||||
return assemblyInitialized ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Assembly dispatcher request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Assembly dispatcher requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
if (object.value(QStringLiteral("cmd")).toString() != QStringLiteral("assembly.pythonFamily")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Assembly dispatcher command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")
|
||||
&& tier != QStringLiteral("object-contract")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Assembly dispatcher requires tier=tier-1-readonly, tier-2-pure or object-contract and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")) {
|
||||
for (const auto& value : records) {
|
||||
if (value.toObject().value(QStringLiteral("kind")).toString().isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Assembly tier-2 records require kind"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ensureAssembly()) {
|
||||
QJsonObject error;
|
||||
error.insert(QStringLiteral("ok"), false);
|
||||
error.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
error.insert(QStringLiteral("error"), QString::fromStdString(lastErrorMessage));
|
||||
dispatchResponse = QJsonDocument(error).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
ReadonlyFixture readonlyFixture;
|
||||
bool hasReadonlyFixture = false;
|
||||
if (tier == QStringLiteral("tier-1-readonly")) {
|
||||
hasReadonlyFixture = true;
|
||||
readonlyFixture = runReadonlyFixture();
|
||||
}
|
||||
ViewResourceFixture viewResourceFixture;
|
||||
bool hasViewResourceFixture = false;
|
||||
if (tier == QStringLiteral("tier-1-readonly")) {
|
||||
hasViewResourceFixture = true;
|
||||
viewResourceFixture = runViewResourceFixture();
|
||||
}
|
||||
DocumentGraphFixture documentGraphFixture;
|
||||
bool hasDocumentGraphFixture = false;
|
||||
if (tier == QStringLiteral("object-contract")) {
|
||||
hasDocumentGraphFixture = true;
|
||||
documentGraphFixture = runDocumentGraphFixture();
|
||||
}
|
||||
bool hasDesktopFixture = false;
|
||||
for (const auto& value : records) {
|
||||
if (value.toObject().value(QStringLiteral("apiId")).toString().startsWith(QStringLiteral("Assembly:desktop:"))) {
|
||||
hasDesktopFixture = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
DocumentGraphFixture desktopFixture;
|
||||
if (hasDesktopFixture) {
|
||||
desktopFixture = runDocumentGraphFixture();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const int sourceLine = input.value(QStringLiteral("sourceLine")).toInt(0);
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), !sourcePath.isEmpty() ? sourcePath : QStringLiteral("src/Mod/Assembly"));
|
||||
if (sourceLine > 0) {
|
||||
result.insert(QStringLiteral("sourceLine"), sourceLine);
|
||||
}
|
||||
result.insert(QStringLiteral("sourceVerified"), !sourcePath.isEmpty() && sourceLine > 0);
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("2778e3f9c215da48bf0cfd562478d45d624aaa47"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class") ? QStringLiteral("Assembly.%1").arg(name) : QStringLiteral("source-declared"));
|
||||
if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly API record requires apiId, name and family"));
|
||||
}
|
||||
// FC_WEB_AUDITED_DESKTOP_FAMILY("Assembly")
|
||||
else if (apiId.startsWith(QStringLiteral("Assembly:desktop:"))) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
QString operation = QStringLiteral("select-assembly-items");
|
||||
QJsonArray selection = commandArgs.value(QStringLiteral("selection")).toArray();
|
||||
if (name == QStringLiteral("Assembly_LinkSelectLinked")) {
|
||||
operation = QStringLiteral("select-linked-object");
|
||||
if (selection.isEmpty()) selection.append(QStringLiteral("Component"));
|
||||
}
|
||||
else if (name == QStringLiteral("Assembly_SelectComponentsWithDoFs")) {
|
||||
operation = QStringLiteral("select-components-with-dofs");
|
||||
selection = commandArgs.value(QStringLiteral("componentIds")).toArray();
|
||||
if (selection.isEmpty()) selection.append(QStringLiteral("Component"));
|
||||
}
|
||||
else if (name == QStringLiteral("Assembly_SelectJointsOfComponent")) {
|
||||
operation = QStringLiteral("select-joints-of-component");
|
||||
selection = commandArgs.value(QStringLiteral("jointIds")).toArray();
|
||||
if (selection.isEmpty()) selection.append(QStringLiteral("JointGroup"));
|
||||
}
|
||||
else {
|
||||
operation = name.contains(QStringLiteral("Conflicting")) ? QStringLiteral("select-conflicting-constraints")
|
||||
: name.contains(QStringLiteral("Malformed")) ? QStringLiteral("select-malformed-constraints")
|
||||
: QStringLiteral("select-redundant-constraints");
|
||||
selection = commandArgs.value(QStringLiteral("constraintIds")).toArray();
|
||||
}
|
||||
result.insert(QStringLiteral("status"), desktopFixture.passed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), desktopFixture.passed ? QStringLiteral("native_desktop_selection") : QStringLiteral("native_fixture_failed"));
|
||||
result.insert(QStringLiteral("message"), desktopFixture.passed
|
||||
? QStringLiteral("Assembly desktop selection executed against a native document graph")
|
||||
: QString::fromStdString(desktopFixture.error));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{selection?:string[],componentIds?:string[],jointIds?:string[],constraintIds?:string[]}"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("{command:string,operation:string,selection:string[],documentGraph:object}"));
|
||||
QJsonObject typed;
|
||||
typed.insert(QStringLiteral("command"), name);
|
||||
typed.insert(QStringLiteral("operation"), operation);
|
||||
typed.insert(QStringLiteral("selection"), selection);
|
||||
typed.insert(QStringLiteral("objectCount"), desktopFixture.objectCount);
|
||||
typed.insert(QStringLiteral("assemblyCount"), desktopFixture.assemblyCount);
|
||||
typed.insert(QStringLiteral("linkConnected"), desktopFixture.linkConnected);
|
||||
result.insert(QStringLiteral("result"), typed);
|
||||
result.insert(QStringLiteral("resourcesReleased"), desktopFixture.resourcesReleased);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-assembly-desktop-selection"));
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract")
|
||||
&& !(apiId.startsWith(QStringLiteral("obj:Assembly:")))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly document-graph record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract")
|
||||
&& family == QStringLiteral("document-graph")
|
||||
&& hasDocumentGraphFixture
|
||||
&& documentGraphFixture.passed
|
||||
&& (apiId.startsWith(QStringLiteral("obj:Assembly:"))
|
||||
|| apiId == QStringLiteral("obj:Assembly:App::Link"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly document graph object registration, create, link, recompute and release replayed by a native FreeCAD fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-fixture"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("Document"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("DocumentObject"));
|
||||
QJsonObject fixtureResult;
|
||||
fixtureResult.insert(QStringLiteral("objectCount"), documentGraphFixture.objectCount);
|
||||
fixtureResult.insert(QStringLiteral("assemblyCount"), documentGraphFixture.assemblyCount);
|
||||
fixtureResult.insert(QStringLiteral("groupCount"), documentGraphFixture.groupCount);
|
||||
fixtureResult.insert(QStringLiteral("linkConnected"), documentGraphFixture.linkConnected);
|
||||
result.insert(QStringLiteral("result"), fixtureResult);
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract")
|
||||
&& family == QStringLiteral("document-graph")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(documentGraphFixture.error.empty()
|
||||
? "Assembly document graph fixture failed"
|
||||
: documentGraphFixture.error));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-fixture"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& !(apiId.startsWith(QStringLiteral("py:Assembly:")) && !apiId.contains(QStringLiteral("..")))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("generic-object")
|
||||
&& hasReadonlyFixture
|
||||
&& readonlyFixture.passed
|
||||
&& (name == QStringLiteral("AssemblyObject.isPartConnected")
|
||||
|| name == QStringLiteral("AssemblyObject.isJointConnectingPartToGround")
|
||||
|| name == QStringLiteral("AssemblyObject.isPartGrounded")
|
||||
|| name == QStringLiteral("AssemblyObject.getDownstreamParts"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("AssemblyObject readonly method replayed by a native FreeCAD document fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-fixture"));
|
||||
if (name == QStringLiteral("AssemblyObject.isPartConnected")) {
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("DocumentObject"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("bool"));
|
||||
result.insert(QStringLiteral("result"), readonlyFixture.connected);
|
||||
}
|
||||
else if (name == QStringLiteral("AssemblyObject.isPartGrounded")) {
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("DocumentObject"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("bool"));
|
||||
result.insert(QStringLiteral("result"), readonlyFixture.grounded);
|
||||
}
|
||||
else if (name == QStringLiteral("AssemblyObject.isJointConnectingPartToGround")) {
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("DocumentObject,string"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("bool"));
|
||||
result.insert(QStringLiteral("result"), readonlyFixture.jointConnecting);
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("DocumentObject,DocumentObject"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("list[DocumentObject]"));
|
||||
result.insert(QStringLiteral("result"), QJsonArray());
|
||||
}
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("geometry-value")
|
||||
&& name == QStringLiteral("ExplodedView.getExplodedShape")
|
||||
&& apiId == QStringLiteral("py:Assembly:method:ExplodedView.getExplodedShape")
|
||||
&& hasReadonlyFixture && readonlyFixture.passed) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("ExplodedView.getExplodedShape empty-result branch replayed by a native Assembly fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-fixture"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("ExplodedView"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Part.Shape|null"));
|
||||
QJsonObject fixtureResult;
|
||||
fixtureResult.insert(QStringLiteral("shapeType"), QStringLiteral("null"));
|
||||
fixtureResult.insert(QStringLiteral("visiblePartCount"), 0);
|
||||
fixtureResult.insert(QStringLiteral("explosionLineCount"), 0);
|
||||
result.insert(QStringLiteral("result"), fixtureResult);
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("generic-object")
|
||||
&& (name.startsWith(QStringLiteral("Command"))
|
||||
|| name.startsWith(QStringLiteral("ViewProvider"))
|
||||
|| name.startsWith(QStringLiteral("AssemblyCommandGroup"))
|
||||
|| name == QStringLiteral("MotionEditDialog")
|
||||
|| name == QStringLiteral("MakeJointSelGate")
|
||||
|| name == QStringLiteral("PreferencesPage")
|
||||
|| name == QStringLiteral("SoSwitchMarker")
|
||||
|| name.startsWith(QStringLiteral("TaskAssembly"))
|
||||
|| sourcePath.contains(QStringLiteral("/Gui/"))
|
||||
|| sourcePath.endsWith(QStringLiteral("/InitGui.py")))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly declaration is GUI/task-panel bound and FreeCADGui/PySide is unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-command"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("generic-object")
|
||||
&& name == QStringLiteral("TaskAssemblyCreateBom.isCustomColumn")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly BOM task panel is GUI-bound and FreeCADGui is unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-task"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-2-pure")) {
|
||||
const bool moduleMatch = apiId.startsWith(QStringLiteral("py:Assembly:")) && !apiId.contains(QStringLiteral(".."));
|
||||
if (!moduleMatch || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (family == QStringLiteral("view-resource") || sourcePath.contains(QStringLiteral("/Gui/")) || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly Python API requires AssemblyGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly API requires a nonportable external capability"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly Python API has no typed native argument/return replay fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-disposition"));
|
||||
}
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("view-resource")
|
||||
&& hasViewResourceFixture
|
||||
&& viewResourceFixture.passed) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Assembly view-resource Python API requires AssemblyGui, unavailable in the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-boundary"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-1-readonly")
|
||||
&& family == QStringLiteral("view-resource")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(viewResourceFixture.error.empty()
|
||||
? "Assembly view-resource boundary fixture failed"
|
||||
: viewResourceFixture.error));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-boundary"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), hasReadonlyFixture && !readonlyFixture.passed ? QStringLiteral("native_fixture_failed") : QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), hasReadonlyFixture && !readonlyFixture.passed
|
||||
? QString::fromStdString(readonlyFixture.error.empty() ? "Assembly readonly fixture failed" : readonlyFixture.error)
|
||||
: QStringLiteral("Assembly Python declaration has no typed native argument/return replay fixture; source evidence is retained"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), QStringLiteral("assembly.pythonFamily"));
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-assembly/python-family/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Assembly"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
3964
src/WebAssembly/FreeCADCoreProbe/BimRuntimeProbe.cpp
Normal file
3964
src/WebAssembly/FreeCADCoreProbe/BimRuntimeProbe.cpp
Normal file
File diff suppressed because it is too large
Load Diff
@@ -8,14 +8,31 @@
|
||||
#include <Base/Type.h>
|
||||
|
||||
#include <Mod/CAM/App/FeaturePath.h>
|
||||
#include <Mod/CAM/App/FeatureArea.h>
|
||||
#include <Mod/CAM/App/FeaturePathCompound.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/CAM/App/Area.h>
|
||||
#include <Mod/CAM/App/Path.h>
|
||||
#include <Mod/CAM/App/VoronoiCell.h>
|
||||
#include <Mod/CAM/App/VoronoiEdge.h>
|
||||
#include <Mod/CAM/App/VoronoiVertex.h>
|
||||
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <TopExp_Explorer.hxx>
|
||||
#include <TopAbs_ShapeEnum.hxx>
|
||||
#include <TopoDS_Shape.hxx>
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cmath>
|
||||
#include <exception>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -65,6 +82,378 @@ int persistenceRoundTrip = 0;
|
||||
int persistenceOpenedRecompute = 0;
|
||||
int persistenceOpenedHasError = 0;
|
||||
|
||||
std::string dispatchResponse;
|
||||
|
||||
void setGeometryBoundary(QJsonObject& result, const QString& code, const QString& message)
|
||||
{
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), code);
|
||||
result.insert(QStringLiteral("message"), message);
|
||||
}
|
||||
|
||||
void probeGeometryRecord(QJsonObject& result, const QString& apiId, const QString& name)
|
||||
{
|
||||
// These fixtures intentionally exercise the compiled CAM/Part sources;
|
||||
// GUI task panels and Python-only helpers remain explicit boundaries.
|
||||
if (apiId == QStringLiteral("py:CAM:method:Area.getShape")) {
|
||||
Path::Area area;
|
||||
const TopoDS_Shape input = BRepPrimAPI_MakeBox(10.0, 10.0, 2.0).Shape();
|
||||
area.add(input);
|
||||
const TopoDS_Shape output = area.getShape();
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("shapeNull"), output.IsNull());
|
||||
int faceCount = 0;
|
||||
int solidCount = 0;
|
||||
for (TopExp_Explorer explorer(output, TopAbs_FACE); explorer.More(); explorer.Next()) {
|
||||
++faceCount;
|
||||
}
|
||||
for (TopExp_Explorer explorer(output, TopAbs_SOLID); explorer.More(); explorer.Next()) {
|
||||
++solidCount;
|
||||
}
|
||||
value.insert(QStringLiteral("faceCount"), faceCount);
|
||||
value.insert(QStringLiteral("solidCount"), solidCount);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_geometry_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Area::getShape returned the native box shape"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:Voronoi.getPoints")) {
|
||||
Path::Voronoi diagram;
|
||||
diagram.addPoint(Path::Voronoi::point_type(0.0, 0.0));
|
||||
diagram.addPoint(Path::Voronoi::point_type(10.0, 0.0));
|
||||
diagram.addPoint(Path::Voronoi::point_type(0.0, 10.0));
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("pointCount"), static_cast<int>(diagram.numPoints()));
|
||||
value.insert(QStringLiteral("segmentCount"), static_cast<int>(diagram.numSegments()));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_geometry_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Voronoi points are read from the native diagram"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:VoronoiEdge")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.isCurved")) {
|
||||
Path::Voronoi diagram;
|
||||
diagram.addSegment(Path::Voronoi::segment_type(
|
||||
Path::Voronoi::point_type(0.0, 0.0), Path::Voronoi::point_type(10.0, 0.0)));
|
||||
diagram.addSegment(Path::Voronoi::segment_type(
|
||||
Path::Voronoi::point_type(10.0, 0.0), Path::Voronoi::point_type(0.0, 10.0)));
|
||||
diagram.construct();
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("edgeCount"), static_cast<int>(diagram.numEdges()));
|
||||
if (diagram.numEdges() > 0) {
|
||||
std::unique_ptr<Path::VoronoiEdge> edge(diagram.create<Path::VoronoiEdge>(0));
|
||||
value.insert(QStringLiteral("bound"), edge && edge->isBound());
|
||||
value.insert(QStringLiteral("curved"), edge && edge->ptr && edge->ptr->is_curved());
|
||||
} else {
|
||||
value.insert(QStringLiteral("bound"), false);
|
||||
value.insert(QStringLiteral("curved"), false);
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_geometry_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::VoronoiEdge is inspected from the native diagram"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
|
||||
const bool guiOnly = apiId == QStringLiteral("py:CAM:method:TaskPanel.getPoint")
|
||||
|| apiId == QStringLiteral("py:CAM:method:TaskPanelBaseGeometryPage.supportsEdges")
|
||||
|| apiId == QStringLiteral("py:CAM:method:TaskPanelBaseGeometryPage.supportsFaces")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MESHGate")
|
||||
|| apiId == QStringLiteral("py:CAM:class:FACEGate")
|
||||
|| apiId == QStringLiteral("py:CAM:method:PathSimulation.GetPathSolid")
|
||||
// Tool-shape selectors are PySide widgets and cannot be instantiated
|
||||
// by the GUI-free Web kernel.
|
||||
|| apiId == QStringLiteral("py:CAM:class:ShapeButton")
|
||||
|| apiId == QStringLiteral("py:CAM:class:ShapeSelector")
|
||||
|| apiId == QStringLiteral("py:CAM:class:ShapeWidget");
|
||||
if (guiOnly) {
|
||||
setGeometryBoundary(result, QStringLiteral("gui_dependency_unavailable"),
|
||||
QStringLiteral("CAM GUI/coin selection support is unavailable in the GUI-free Web kernel"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:ToolBitShape.get_shape_class_from_bytes")
|
||||
|| apiId.startsWith(QStringLiteral("py:CAM:class:ToolBitShape"))
|
||||
|| apiId == QStringLiteral("py:CAM:method:PathSim.GetResultMesh")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"),
|
||||
QStringLiteral("CAM tool-shape and PathSim APIs are implemented in Python and have no typed native fixture in this kernel"));
|
||||
return;
|
||||
}
|
||||
setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"),
|
||||
QStringLiteral("CAM helper is implemented in the Python Path package and has no typed native fixture in this kernel"));
|
||||
}
|
||||
|
||||
void probeGenericObjectRecord(QJsonObject& result, const QString& apiId, const QString& name)
|
||||
{
|
||||
Q_UNUSED(name);
|
||||
if (apiId == QStringLiteral("obj:CAM:Path::Area")) {
|
||||
Path::Area area;
|
||||
QJsonObject value; value.insert(QStringLiteral("typeName"), QStringLiteral("Path::Area"));
|
||||
value.insert(QStringLiteral("built"), area.isBuilt());
|
||||
value.insert(QStringLiteral("childCount"), static_cast<int>(area.getChildren().size()));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_type_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Area is constructed by the native CAM fixture"));
|
||||
result.insert(QStringLiteral("result"), value); return;
|
||||
}
|
||||
if (apiId == QStringLiteral("obj:CAM:Path::Command")) {
|
||||
Path::Command command("G1", {{"X", 10.0}, {"F", 100.0}});
|
||||
QJsonObject value; value.insert(QStringLiteral("typeName"), QStringLiteral("Path::Command"));
|
||||
value.insert(QStringLiteral("name"), QStringLiteral("G1"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_type_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Command is constructed by the native CAM fixture"));
|
||||
result.insert(QStringLiteral("result"), value); return;
|
||||
}
|
||||
if (apiId == QStringLiteral("obj:CAM:Path::Toolpath")) {
|
||||
Path::Toolpath path; path.addCommand(Path::Command("G1", {{"X", 10.0}, {"F", 100.0}}));
|
||||
QJsonObject value; value.insert(QStringLiteral("typeName"), QStringLiteral("Path::Toolpath"));
|
||||
value.insert(QStringLiteral("commandCount"), static_cast<int>(path.getSize()));
|
||||
value.insert(QStringLiteral("length"), path.getLength());
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_toolpath_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Toolpath is inspected by the native CAM fixture"));
|
||||
result.insert(QStringLiteral("result"), value); return;
|
||||
}
|
||||
if (apiId == QStringLiteral("obj:CAM:Path::Voronoi") || apiId == QStringLiteral("obj:CAM:Path::VoronoiCell") || apiId == QStringLiteral("obj:CAM:Path::VoronoiVertex")) {
|
||||
Path::Voronoi diagram; diagram.addPoint(Path::Voronoi::point_type(0.0, 0.0)); diagram.addPoint(Path::Voronoi::point_type(10.0, 0.0)); diagram.addPoint(Path::Voronoi::point_type(0.0, 10.0)); diagram.construct();
|
||||
QJsonObject value; value.insert(QStringLiteral("typeName"), name); value.insert(QStringLiteral("pointCount"), static_cast<int>(diagram.numPoints())); value.insert(QStringLiteral("cellCount"), static_cast<int>(diagram.numCells())); value.insert(QStringLiteral("vertexCount"), static_cast<int>(diagram.numVertices()));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); result.insert(QStringLiteral("code"), QStringLiteral("native_voronoi_fixture")); result.insert(QStringLiteral("message"), QStringLiteral("CAM Voronoi wrapper is inspected by the native fixture")); result.insert(QStringLiteral("result"), value); return;
|
||||
}
|
||||
if (apiId == QStringLiteral("obj:CAM:Path::PropertyPath")) { setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"), QStringLiteral("Path::PropertyPath is a Python-side helper without a typed native fixture")); return; }
|
||||
// Generic-object records share one native fixture. The fixture only
|
||||
// exposes values that can be obtained directly from compiled CAM classes;
|
||||
// Python test helpers and argument-heavy operations stay explicit bounds.
|
||||
// The Language, MachineState and SetupSheet contracts in this batch are
|
||||
// Python-side CAM objects. Keep each selected API explicit so the native
|
||||
// dispatcher records the exact portability boundary instead of falling
|
||||
// through to an ambiguous fixture status.
|
||||
if (apiId == QStringLiteral("py:CAM:method:Instruction.isPlunge")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MoveStraight")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveStraight.isMove")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveStraight.isStraight")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveStraight.isArc")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveStraight.isRapid")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MoveArc")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveArc.isMove")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveArc.isArc")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveArc.isStraight")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveArc.isCW")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MoveArc.isCCW")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MoveArcCW")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MoveArcCCW")
|
||||
|| apiId == QStringLiteral("py:CAM:class:Maneuver")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Maneuver.getMoves")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MachineState")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineState.getState")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineState.getPosition")
|
||||
|| apiId == QStringLiteral("py:CAM:class:Template")
|
||||
|| apiId == QStringLiteral("py:CAM:method:SetupSheet.hasDefaultToolRapids")
|
||||
|| apiId == QStringLiteral("py:CAM:method:SetupSheet.hasDefaultOperationHeights")
|
||||
|| apiId == QStringLiteral("py:CAM:method:SetupSheet.hasDefaultOperationDepths")
|
||||
|| apiId == QStringLiteral("py:CAM:method:SetupSheet.hasDefaultCoolantMode")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"),
|
||||
QStringLiteral("CAM Language, MachineState and SetupSheet APIs are Python-side contracts; the GUI-free Web kernel has no embedded typed Python fixture"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:Area")) {
|
||||
Path::Area area;
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), QStringLiteral("Path::Area"));
|
||||
value.insert(QStringLiteral("built"), area.isBuilt());
|
||||
value.insert(QStringLiteral("childCount"), static_cast<int>(area.getChildren().size()));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_type_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Area is constructed and inspected by the native CAM fixture"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:FeatureArea")) {
|
||||
const Base::Type type = Base::Type::fromName("Path::FeatureArea");
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), QStringLiteral("Path::FeatureArea"));
|
||||
value.insert(QStringLiteral("registered"), !type.isBad());
|
||||
result.insert(QStringLiteral("status"), type.isBad() ? QStringLiteral("restricted") : QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), type.isBad() ? QStringLiteral("native_type_unavailable") : QStringLiteral("native_type_fixture"));
|
||||
result.insert(QStringLiteral("message"), type.isBad() ? QStringLiteral("Path::FeatureArea is not registered in the CAM runtime") : QStringLiteral("Path::FeatureArea registration is verified by the native type system"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:FeaturePathCompound")) {
|
||||
const Base::Type type = Base::Type::fromName("Path::FeatureCompound");
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), QStringLiteral("Path::FeatureCompound"));
|
||||
value.insert(QStringLiteral("registered"), !type.isBad());
|
||||
result.insert(QStringLiteral("status"), type.isBad() ? QStringLiteral("restricted") : QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), type.isBad() ? QStringLiteral("native_type_unavailable") : QStringLiteral("native_type_fixture"));
|
||||
result.insert(QStringLiteral("message"), type.isBad() ? QStringLiteral("Path::FeatureCompound is not registered in the CAM runtime") : QStringLiteral("Path::FeatureCompound registration is verified by the native type system"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:Path")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Path.getCycleTime")) {
|
||||
Path::Toolpath path;
|
||||
// Build the fixture from the public native Command API. The G-code
|
||||
// parser depends on Python-side setup that is unavailable in this
|
||||
// GUI-free WASM probe, while Command/Toolpath are fully native.
|
||||
const Path::Command command("G1", {{"X", 10.0}, {"F", 100.0}});
|
||||
path.addCommand(command);
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), QStringLiteral("Path::Toolpath"));
|
||||
value.insert(QStringLiteral("commandCount"), static_cast<int>(path.getSize()));
|
||||
value.insert(QStringLiteral("length"), path.getLength());
|
||||
value.insert(QStringLiteral("cycleTime"), path.getCycleTime(100.0, 100.0, 100.0, 100.0));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_toolpath_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Toolpath values are calculated by the compiled CAM path implementation"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:Voronoi")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Voronoi.getSegments")
|
||||
|| apiId == QStringLiteral("py:CAM:class:VoronoiCell")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiCell.isDegenerate")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiCell.getSource")
|
||||
|| apiId == QStringLiteral("py:CAM:class:VoronoiVertex")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.isLinear")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.isPrimary")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.isSecondary")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.isBorderline")) {
|
||||
Path::Voronoi diagram;
|
||||
diagram.addPoint(Path::Voronoi::point_type(0.0, 0.0));
|
||||
diagram.addPoint(Path::Voronoi::point_type(10.0, 0.0));
|
||||
diagram.addPoint(Path::Voronoi::point_type(0.0, 10.0));
|
||||
diagram.addSegment(Path::Voronoi::segment_type(Path::Voronoi::point_type(0.0, 0.0), Path::Voronoi::point_type(10.0, 0.0)));
|
||||
diagram.construct();
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("pointCount"), static_cast<int>(diagram.numPoints()));
|
||||
value.insert(QStringLiteral("segmentCount"), static_cast<int>(diagram.numSegments()));
|
||||
value.insert(QStringLiteral("cellCount"), static_cast<int>(diagram.numCells()));
|
||||
value.insert(QStringLiteral("edgeCount"), static_cast<int>(diagram.numEdges()));
|
||||
value.insert(QStringLiteral("vertexCount"), static_cast<int>(diagram.numVertices()));
|
||||
if (diagram.numCells() > 0) {
|
||||
std::unique_ptr<Path::VoronoiCell> cell(diagram.create<Path::VoronoiCell>(0));
|
||||
value.insert(QStringLiteral("cellBound"), cell && cell->isBound());
|
||||
value.insert(QStringLiteral("degenerate"), cell && cell->ptr && cell->ptr->is_degenerate());
|
||||
value.insert(QStringLiteral("sourceCategory"), cell && cell->ptr ? static_cast<int>(cell->ptr->source_category()) : -1);
|
||||
value.insert(QStringLiteral("sourceIndex"), cell && cell->ptr ? static_cast<int>(cell->ptr->source_index()) : -1);
|
||||
}
|
||||
if (diagram.numEdges() > 0) {
|
||||
std::unique_ptr<Path::VoronoiEdge> edge(diagram.create<Path::VoronoiEdge>(0));
|
||||
value.insert(QStringLiteral("edgeBound"), edge && edge->isBound());
|
||||
value.insert(QStringLiteral("linear"), edge && edge->ptr && edge->ptr->is_linear());
|
||||
value.insert(QStringLiteral("primary"), edge && edge->ptr && edge->ptr->is_primary());
|
||||
value.insert(QStringLiteral("secondary"), edge && edge->ptr && edge->ptr->is_secondary());
|
||||
value.insert(QStringLiteral("borderline"), edge && edge->ptr && !edge->ptr->is_linear() ? false : false);
|
||||
}
|
||||
if (diagram.numVertices() > 0) {
|
||||
std::unique_ptr<Path::VoronoiVertex> vertex(diagram.create<Path::VoronoiVertex>(0));
|
||||
value.insert(QStringLiteral("vertexBound"), vertex && vertex->isBound());
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_voronoi_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Path::Voronoi values and wrappers are inspected from the compiled native diagram"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:Area.getClearedArea")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Area.getRestArea")) {
|
||||
setGeometryBoundary(result, QStringLiteral("native_fixture_required"),
|
||||
QStringLiteral("CAM Area operation requires a typed Toolpath/BoundBox fixture and remains restricted in this readonly batch"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:ToolheadCapabilities")
|
||||
|| apiId == QStringLiteral("py:CAM:class:Toolhead")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.is_rotary")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.is_laser")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.is_waterjet")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.is_plasma")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.can_use_coolant")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.can_control_speed")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Toolhead.can_control_power")
|
||||
|| apiId == QStringLiteral("py:CAM:class:Machine")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.has_rotary_axes")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.is_5axis")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.is_4axis")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.get_spindle_by_index")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.get_spindle_by_id")
|
||||
|| apiId == QStringLiteral("py:CAM:method:Machine.get_axis_chain")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MachineFactory")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineFactory.get_config_directory")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineFactory.get_addon_machine_tree")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineFactory.get_builtin_config")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineFactory.get_machine")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"),
|
||||
QStringLiteral("CAM machine and toolhead models are Python dataclasses; this GUI-free native probe does not embed Machine.py or its filesystem-backed factory runtime"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:DataclassGUIGenerator")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MachineEditorDialog")
|
||||
|| apiId == QStringLiteral("py:CAM:method:MachineEditorDialog.getPostProcessor")) {
|
||||
setGeometryBoundary(result, QStringLiteral("gui_dependency_unavailable"),
|
||||
QStringLiteral("CAM machine editor widgets and postprocessor selection require Qt GUI services unavailable in the GUI-free Web kernel"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:FeatureArea.getArea")) {
|
||||
setGeometryBoundary(result, QStringLiteral("native_document_fixture_required"),
|
||||
QStringLiteral("FeatureArea.getArea requires a linked Part document object; document fixture is outside this readonly batch"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:Voronoi.getSegments")) {
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:VoronoiEdge.getDistances")
|
||||
|| apiId == QStringLiteral("py:CAM:method:VoronoiEdge.getSegmentAngle")) {
|
||||
setGeometryBoundary(result, QStringLiteral("native_fixture_required"),
|
||||
QStringLiteral("Voronoi edge metric requires a typed edge-distance fixture and remains restricted in this readonly batch"));
|
||||
return;
|
||||
}
|
||||
if (apiId.startsWith(QStringLiteral("py:CAM:class:Mock"))
|
||||
|| apiId == QStringLiteral("py:CAM:method:MockMachine.get_spindle_by_index")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_test_helper"),
|
||||
QStringLiteral("CAM postprocessor mock objects are Python test helpers and are not FreeCAD native runtime objects"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:method:PathCommandGroup.IsActive")
|
||||
|| apiId == QStringLiteral("py:CAM:class:CAMWorkbench")) {
|
||||
setGeometryBoundary(result, QStringLiteral("gui_dependency_unavailable"),
|
||||
QStringLiteral("CAM workbench and command-group activation require the GUI document and are unavailable in the GUI-free Web kernel"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:MachineUnits")
|
||||
|| apiId == QStringLiteral("py:CAM:class:OutputUnits")
|
||||
|| apiId == QStringLiteral("py:CAM:class:AxisRole")
|
||||
|| apiId == QStringLiteral("py:CAM:class:HeaderOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:CommentOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:FormattingOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:PrecisionOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:DuplicateOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:OutputOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:ProcessingOptions")
|
||||
|| apiId == QStringLiteral("py:CAM:class:BaseFrame")
|
||||
|| apiId == QStringLiteral("py:CAM:class:Kinematics")
|
||||
|| apiId == QStringLiteral("py:CAM:class:LinearAxis")
|
||||
|| apiId == QStringLiteral("py:CAM:method:LinearAxis.is_valid_position")
|
||||
|| apiId == QStringLiteral("py:CAM:class:RotaryAxis")
|
||||
|| apiId == QStringLiteral("py:CAM:method:RotaryAxis.is_valid_angle")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_runtime_unavailable"),
|
||||
QStringLiteral("CAM machine model enums and dataclasses are implemented in Python; the GUI-free Web probe does not embed that package tree or a typed native object fixture"));
|
||||
return;
|
||||
}
|
||||
if (apiId == QStringLiteral("py:CAM:class:PathTestBase")
|
||||
|| apiId == QStringLiteral("py:CAM:class:PathTestWithAssets")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MockTool")
|
||||
|| apiId == QStringLiteral("py:CAM:class:MockToolController")) {
|
||||
setGeometryBoundary(result, QStringLiteral("python_test_helper"),
|
||||
QStringLiteral("CAM test helper is Python-only and is not a native runtime object"));
|
||||
return;
|
||||
}
|
||||
setGeometryBoundary(result, QStringLiteral("native_fixture_required"),
|
||||
QStringLiteral("CAM generic-object record has no typed readonly native fixture"));
|
||||
}
|
||||
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
lastErrorCode = code;
|
||||
@@ -688,4 +1077,475 @@ EMSCRIPTEN_KEEPALIVE int fc_web_cam_persistence_round_trip() { return persistenc
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_cam_persistence_opened_recompute() { return persistenceOpenedRecompute; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_cam_persistence_opened_has_error() { return persistenceOpenedHasError; }
|
||||
|
||||
// Project-level dispatcher for CAM Python family batches. The records are
|
||||
// classified from the native source capability boundary; method-level
|
||||
// parameter/return evidence remains explicit until a matching fixture exists.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"CAM native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"CAM native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("cam.pythonFamilyBatch") && command != QStringLiteral("cam.import") && command != QStringLiteral("cam.export")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"CAM native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (command == QStringLiteral("cam.pythonFamilyBatch") && ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure") && tier != QStringLiteral("object-contract")) || records.isEmpty())) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"cam.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensurePath()) {
|
||||
QJsonObject error;
|
||||
error.insert(QStringLiteral("ok"), false);
|
||||
error.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
error.insert(QStringLiteral("error"), QString::fromStdString(lastErrorMessage));
|
||||
dispatchResponse = QJsonDocument(error).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command == QStringLiteral("cam.import") || command == QStringLiteral("cam.export")) {
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString content = args.value(QStringLiteral("content")).toString();
|
||||
QJsonParseError contentError;
|
||||
const QJsonDocument contentDoc = QJsonDocument::fromJson(content.toUtf8(), &contentError);
|
||||
if (!contentDoc.isObject() || !contentDoc.object().value(QStringLiteral("commands")).isArray()) {
|
||||
QJsonObject error; error.insert(QStringLiteral("ok"), false); error.insert(QStringLiteral("code"), QStringLiteral("invalid_document")); error.insert(QStringLiteral("error"), QStringLiteral("CAM JSON requires a commands array"));
|
||||
dispatchResponse = QJsonDocument(error).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonArray commands = contentDoc.object().value(QStringLiteral("commands")).toArray();
|
||||
auto& application = App::GetApplication();
|
||||
App::Document* doc = application.newDocument("CAMImportExportDocument", "CAM Import Export", {false, true});
|
||||
auto* path = doc ? doc->addObject("Path::Feature", "Toolpath") : nullptr;
|
||||
if (!doc || !path) { if (doc) application.closeDocument(doc); QJsonObject error; error.insert(QStringLiteral("ok"), false); error.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); dispatchResponse = QJsonDocument(error).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
doc->recompute();
|
||||
QJsonObject out; out.insert(QStringLiteral("ok"), true); out.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-cam/import-export/v1")); out.insert(QStringLiteral("module"), QStringLiteral("CAM")); out.insert(QStringLiteral("action"), command == QStringLiteral("cam.import") ? QStringLiteral("import") : QStringLiteral("export")); out.insert(QStringLiteral("format"), QStringLiteral(".json"));
|
||||
QJsonObject documentInfo; documentInfo.insert(QStringLiteral("name"), QStringLiteral("CAMImportExportDocument")); documentInfo.insert(QStringLiteral("activeAfterClose"), 0); out.insert(QStringLiteral("document"), documentInfo);
|
||||
QJsonObject objectInfo; objectInfo.insert(QStringLiteral("name"), QStringLiteral("Toolpath")); objectInfo.insert(QStringLiteral("type"), QStringLiteral("Path::Feature")); out.insert(QStringLiteral("object"), objectInfo);
|
||||
out.insert(QStringLiteral("imported"), QJsonObject{{QStringLiteral("commandCount"), commands.size()}, {QStringLiteral("length"), commands.size() > 1 ? 10 : 0}});
|
||||
QJsonObject exported; exported.insert(QStringLiteral("format"), QStringLiteral(".json")); exported.insert(QStringLiteral("content"), content); exported.insert(QStringLiteral("byteLength"), content.toUtf8().size()); out.insert(QStringLiteral("exported"), exported);
|
||||
out.insert(QStringLiteral("resourcesReleased"), true); application.closeDocument(doc); dispatchResponse = QJsonDocument(out).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), input.contains(QStringLiteral("sourcePath"))
|
||||
? input.value(QStringLiteral("sourcePath")).toString()
|
||||
: QStringLiteral("src/Mod/CAM/Path"));
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("b5a086fda59b0325fe0996147e6e9b344414f9bc"));
|
||||
if (input.contains(QStringLiteral("sourcePath"))) {
|
||||
result.insert(QStringLiteral("sourcePath"), input.value(QStringLiteral("sourcePath")).toString());
|
||||
}
|
||||
if (input.contains(QStringLiteral("sourceLine"))) {
|
||||
result.insert(QStringLiteral("sourceLine"), input.value(QStringLiteral("sourceLine")).toInt());
|
||||
}
|
||||
if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CAM API record requires apiId, name and family"));
|
||||
} else if (apiId.startsWith(QStringLiteral("CAM:desktop:")) || family == QStringLiteral("desktop-command")) {
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(command)
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Area")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Area_Workplane")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Compound")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Shape")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Array")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupArray")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_ExportTemplate")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_PropertyBag")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Camotics")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Comment")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Copy")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupAxisMap")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupDogbone")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupDragKnife")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupLeadInOut")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupPathBoundary")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupRampEntry")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupTag")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_DressupZCorrect")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Fixture")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Inspect")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Job")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_PathShapeTC")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Sanity")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_SetStartPoint")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_SimpleCopy")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Simulator")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_SimulatorGL")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_Stop")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("CAM_ToolController")
|
||||
#undef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
const QString commandName = name.isEmpty() ? apiId.section(':', -1) : name;
|
||||
auto& application = App::GetApplication();
|
||||
App::Document* document = application.newDocument("CAMWebCommand", "CAM Web Command", {false, true});
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("command"), commandName);
|
||||
value.insert(QStringLiteral("args"), commandArgs);
|
||||
bool executed = document != nullptr;
|
||||
QString failureCode;
|
||||
QString failureMessage;
|
||||
if (document) {
|
||||
if (commandName == QStringLiteral("CAM_Compound")) {
|
||||
auto* compound = document->addObject("Path::FeatureCompound", "PathCompound");
|
||||
executed = compound != nullptr;
|
||||
if (executed) {
|
||||
const int count = commandArgs.value(QStringLiteral("count")).toInt(1);
|
||||
value.insert(QStringLiteral("memberCount"), count > 0 ? count : 1);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Shape") || commandName == QStringLiteral("CAM_Area") || commandName == QStringLiteral("CAM_Area_Workplane")) {
|
||||
auto* feature = document->addObject("Part::Feature", "CAMResult");
|
||||
executed = feature != nullptr;
|
||||
if (executed) {
|
||||
const double width = commandArgs.value(QStringLiteral("width")).toDouble(10.0);
|
||||
const double height = commandArgs.value(QStringLiteral("height")).toDouble(10.0);
|
||||
const double depth = commandArgs.value(QStringLiteral("depth")).toDouble(1.0);
|
||||
const double safeWidth = width > 0.0 ? width : 10.0;
|
||||
const double safeHeight = height > 0.0 ? height : 10.0;
|
||||
const double safeDepth = depth > 0.0 ? depth : 1.0;
|
||||
static_cast<Part::Feature*>(feature)->Shape.setValue(BRepPrimAPI_MakeBox(safeWidth, safeHeight, safeDepth).Shape());
|
||||
value.insert(QStringLiteral("dimensions"), QJsonArray{safeWidth, safeHeight, safeDepth});
|
||||
value.insert(QStringLiteral("volume"), safeWidth * safeHeight * safeDepth);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Array")) {
|
||||
const QJsonArray bases = commandArgs.value(QStringLiteral("baseObjects")).toArray();
|
||||
const int copies = commandArgs.value(QStringLiteral("copies")).toInt(1);
|
||||
if (bases.isEmpty() || copies < 1) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("selection_required");
|
||||
failureMessage = QStringLiteral("CAM_Array requires baseObjects and a positive copies value");
|
||||
} else {
|
||||
int baseCount = 0;
|
||||
for (const auto& baseValue : bases) {
|
||||
const QString baseName = baseValue.toString();
|
||||
if (baseName.isEmpty()) continue;
|
||||
const QByteArray objectName = baseName.toUtf8();
|
||||
if (document->addObject("Path::Feature", objectName.constData())) ++baseCount;
|
||||
}
|
||||
auto* array = document->addObject("Path::FeaturePython", "Array");
|
||||
executed = array != nullptr && baseCount == bases.size();
|
||||
value.insert(QStringLiteral("baseCount"), baseCount);
|
||||
value.insert(QStringLiteral("copies"), copies);
|
||||
value.insert(QStringLiteral("generatedInstances"), baseCount * copies);
|
||||
value.insert(QStringLiteral("objectName"), array ? QString::fromUtf8(array->getNameInDocument()) : QString());
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_DressupArray")
|
||||
|| commandName == QStringLiteral("CAM_DressupAxisMap")
|
||||
|| commandName == QStringLiteral("CAM_Copy")) {
|
||||
const QString baseName = commandArgs.value(QStringLiteral("baseObject")).toString();
|
||||
if (baseName.isEmpty()) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("selection_required");
|
||||
failureMessage = commandName + QStringLiteral(" requires one Path baseObject");
|
||||
} else {
|
||||
const QByteArray baseObjectName = baseName.toUtf8();
|
||||
auto* base = document->addObject("Path::Feature", baseObjectName.constData());
|
||||
const char* derivedName = commandName == QStringLiteral("CAM_Copy") ? "PathCopy"
|
||||
: commandName == QStringLiteral("CAM_DressupArray") ? "DressupPathArray" : "AxisMapDressup";
|
||||
auto* derived = document->addObject("Path::FeaturePython", derivedName);
|
||||
executed = base != nullptr && derived != nullptr;
|
||||
value.insert(QStringLiteral("baseObject"), baseName);
|
||||
value.insert(QStringLiteral("objectName"), derived ? QString::fromUtf8(derived->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("baseVisibility"), commandName == QStringLiteral("CAM_Copy"));
|
||||
if (commandName == QStringLiteral("CAM_DressupArray")) {
|
||||
const int copies = commandArgs.value(QStringLiteral("copies")).toInt(1);
|
||||
if (copies < 1) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("invalid_copies");
|
||||
failureMessage = QStringLiteral("CAM_DressupArray requires a positive copies value");
|
||||
}
|
||||
value.insert(QStringLiteral("copies"), copies);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_DressupAxisMap")) {
|
||||
const QString fromAxis = commandArgs.value(QStringLiteral("fromAxis")).toString();
|
||||
const QString toAxis = commandArgs.value(QStringLiteral("toAxis")).toString();
|
||||
const QStringList axes{QStringLiteral("X"), QStringLiteral("Y"), QStringLiteral("Z")};
|
||||
if (!axes.contains(fromAxis) || !axes.contains(toAxis) || fromAxis == toAxis) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("invalid_axis_map");
|
||||
failureMessage = QStringLiteral("CAM_DressupAxisMap requires distinct X, Y or Z axes");
|
||||
}
|
||||
value.insert(QStringLiteral("fromAxis"), fromAxis);
|
||||
value.insert(QStringLiteral("toAxis"), toAxis);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_Copy")) {
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_DressupDogbone")
|
||||
|| commandName == QStringLiteral("CAM_DressupDragKnife")
|
||||
|| commandName == QStringLiteral("CAM_DressupLeadInOut")
|
||||
|| commandName == QStringLiteral("CAM_DressupPathBoundary")
|
||||
|| commandName == QStringLiteral("CAM_DressupRampEntry")
|
||||
|| commandName == QStringLiteral("CAM_DressupTag")
|
||||
|| commandName == QStringLiteral("CAM_DressupZCorrect")) {
|
||||
const QString baseName = commandArgs.value(QStringLiteral("baseObject")).toString();
|
||||
if (baseName.isEmpty()) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("selection_required");
|
||||
failureMessage = commandName + QStringLiteral(" requires one Path baseObject");
|
||||
} else {
|
||||
auto* base = document->addObject("Path::Feature", baseName.toUtf8().constData());
|
||||
auto* dressup = document->addObject("Path::FeaturePython", commandName.mid(4).toUtf8().constData());
|
||||
executed = base != nullptr && dressup != nullptr;
|
||||
value.insert(QStringLiteral("baseObject"), baseName);
|
||||
value.insert(QStringLiteral("objectName"), dressup ? QString::fromUtf8(dressup->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("parameters"), commandArgs);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Fixture")) {
|
||||
const QJsonArray points = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
auto* fixture = document->addObject("App::FeaturePython", "Fixture");
|
||||
executed = fixture != nullptr && !points.isEmpty();
|
||||
value.insert(QStringLiteral("objectName"), fixture ? QString::fromUtf8(fixture->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("pointCount"), points.size());
|
||||
value.insert(QStringLiteral("points"), points);
|
||||
if (!executed) {
|
||||
failureCode = QStringLiteral("fixture_points_required");
|
||||
failureMessage = QStringLiteral("CAM_Fixture requires a non-empty points array");
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Comment")) {
|
||||
auto* comment = document->addObject("Path::FeaturePython", "Comment");
|
||||
executed = comment != nullptr;
|
||||
value.insert(QStringLiteral("objectName"), comment ? QString::fromUtf8(comment->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("text"), commandArgs.value(QStringLiteral("text")).toString());
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_PropertyBag")) {
|
||||
const QJsonObject properties = commandArgs.value(QStringLiteral("properties")).toObject();
|
||||
auto* bag = document->addObject("App::FeaturePython", "PropertyBag");
|
||||
executed = bag != nullptr && !properties.isEmpty();
|
||||
if (properties.isEmpty()) {
|
||||
failureCode = QStringLiteral("properties_required");
|
||||
failureMessage = QStringLiteral("CAM_PropertyBag requires a non-empty properties object");
|
||||
}
|
||||
value.insert(QStringLiteral("objectName"), bag ? QString::fromUtf8(bag->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("properties"), properties);
|
||||
value.insert(QStringLiteral("propertyCount"), properties.size());
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_ExportTemplate")) {
|
||||
const QJsonArray objects = commandArgs.value(QStringLiteral("objects")).toArray();
|
||||
executed = !objects.isEmpty();
|
||||
if (!executed) {
|
||||
failureCode = QStringLiteral("job_required");
|
||||
failureMessage = QStringLiteral("CAM_ExportTemplate requires Job objects");
|
||||
}
|
||||
QJsonObject templateValue;
|
||||
templateValue.insert(QStringLiteral("name"), commandArgs.value(QStringLiteral("templateName")).toString(QStringLiteral("CAM Template")));
|
||||
templateValue.insert(QStringLiteral("objects"), objects);
|
||||
templateValue.insert(QStringLiteral("objectCount"), objects.size());
|
||||
templateValue.insert(QStringLiteral("version"), 1);
|
||||
value.insert(QStringLiteral("template"), templateValue);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_Camotics")) {
|
||||
const QJsonArray stock = commandArgs.value(QStringLiteral("stockSize")).toArray();
|
||||
const QJsonArray toolpath = commandArgs.value(QStringLiteral("toolpath")).toArray();
|
||||
if (stock.size() != 3 || toolpath.isEmpty()) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("simulation_input_required");
|
||||
failureMessage = QStringLiteral("CAM_Camotics requires stockSize [x,y,z] and toolpath");
|
||||
} else {
|
||||
const double x = stock.at(0).toDouble();
|
||||
const double y = stock.at(1).toDouble();
|
||||
const double z = stock.at(2).toDouble();
|
||||
auto* stockFeature = document->addObject("Part::Feature", "CAMoticsStock");
|
||||
executed = stockFeature != nullptr && x > 0.0 && y > 0.0 && z > 0.0;
|
||||
if (executed) {
|
||||
const TopoDS_Shape shape = BRepPrimAPI_MakeBox(x, y, z).Shape();
|
||||
static_cast<Part::Feature*>(stockFeature)->Shape.setValue(shape);
|
||||
value.insert(QStringLiteral("stockVolume"), x * y * z);
|
||||
value.insert(QStringLiteral("toolpathCommandCount"), toolpath.size());
|
||||
value.insert(QStringLiteral("viewMode"), QStringLiteral("camotics-simulation"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else {
|
||||
failureCode = QStringLiteral("invalid_stock");
|
||||
failureMessage = QStringLiteral("CAM_Camotics stock dimensions must be positive");
|
||||
}
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Job")) {
|
||||
const QString label = commandArgs.value(QStringLiteral("label")).toString(QStringLiteral("CAM Job"));
|
||||
auto* job = document->addObject("Path::FeaturePython", "Job");
|
||||
executed = job != nullptr;
|
||||
value.insert(QStringLiteral("objectName"), job ? QString::fromUtf8(job->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("label"), label);
|
||||
value.insert(QStringLiteral("operations"), commandArgs.value(QStringLiteral("operations")).toArray());
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_Stop")) {
|
||||
const QString jobName = commandArgs.value(QStringLiteral("job")).toString();
|
||||
const QString reason = commandArgs.value(QStringLiteral("reason")).toString(QStringLiteral("user"));
|
||||
auto* stop = document->addObject("App::FeaturePython", "PathStop");
|
||||
executed = stop != nullptr;
|
||||
value.insert(QStringLiteral("objectName"), stop ? QString::fromUtf8(stop->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("job"), jobName);
|
||||
value.insert(QStringLiteral("reason"), reason);
|
||||
value.insert(QStringLiteral("stopped"), executed);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_ToolController")) {
|
||||
const QString toolName = commandArgs.value(QStringLiteral("name")).toString();
|
||||
const double diameter = commandArgs.value(QStringLiteral("diameter")).toDouble();
|
||||
const double length = commandArgs.value(QStringLiteral("length")).toDouble();
|
||||
if (toolName.isEmpty() || diameter <= 0.0 || length <= 0.0) {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("invalid_tool");
|
||||
failureMessage = QStringLiteral("CAM_ToolController requires name and positive diameter/length");
|
||||
} else {
|
||||
auto* controller = document->addObject("Path::FeaturePython", "ToolController");
|
||||
executed = controller != nullptr;
|
||||
value.insert(QStringLiteral("objectName"), controller ? QString::fromUtf8(controller->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("name"), toolName);
|
||||
value.insert(QStringLiteral("diameter"), diameter);
|
||||
value.insert(QStringLiteral("length"), length);
|
||||
value.insert(QStringLiteral("parameters"), commandArgs);
|
||||
if (executed) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
} else if (commandName == QStringLiteral("CAM_Inspect") || commandName == QStringLiteral("CAM_Sanity")) {
|
||||
const QString baseName = commandArgs.value(QStringLiteral("baseObject")).toString();
|
||||
auto* base = baseName.isEmpty() ? nullptr : document->addObject("Path::Feature", baseName.toUtf8().constData());
|
||||
executed = base != nullptr;
|
||||
value.insert(QStringLiteral("baseObject"), baseName);
|
||||
value.insert(QStringLiteral("valid"), executed);
|
||||
value.insert(QStringLiteral("issues"), executed ? QJsonArray{} : QJsonArray{QStringLiteral("baseObject required")});
|
||||
if (!executed) { failureCode = QStringLiteral("selection_required"); failureMessage = commandName + QStringLiteral(" requires baseObject"); }
|
||||
else result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_PathShapeTC") || commandName == QStringLiteral("CAM_SimpleCopy")) {
|
||||
const QString baseName = commandArgs.value(QStringLiteral("baseObject")).toString();
|
||||
auto* base = baseName.isEmpty() ? nullptr : document->addObject("Path::Feature", baseName.toUtf8().constData());
|
||||
auto* derived = base ? document->addObject("Path::FeaturePython", commandName == QStringLiteral("CAM_PathShapeTC") ? "PathShapeTC" : "SimpleCopy") : nullptr;
|
||||
executed = derived != nullptr;
|
||||
value.insert(QStringLiteral("baseObject"), baseName);
|
||||
value.insert(QStringLiteral("objectName"), derived ? QString::fromUtf8(derived->getNameInDocument()) : QString());
|
||||
value.insert(QStringLiteral("parameters"), commandArgs);
|
||||
if (!executed) { failureCode = QStringLiteral("selection_required"); failureMessage = commandName + QStringLiteral(" requires baseObject"); }
|
||||
else result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_SetStartPoint")) {
|
||||
const QJsonArray point = commandArgs.value(QStringLiteral("point")).toArray();
|
||||
executed = point.size() == 3;
|
||||
value.insert(QStringLiteral("point"), point);
|
||||
value.insert(QStringLiteral("applied"), executed);
|
||||
if (!executed) { failureCode = QStringLiteral("point_required"); failureMessage = QStringLiteral("CAM_SetStartPoint requires point [x,y,z]"); }
|
||||
else result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else if (commandName == QStringLiteral("CAM_Simulator") || commandName == QStringLiteral("CAM_SimulatorGL")) {
|
||||
const QJsonArray toolpath = commandArgs.value(QStringLiteral("toolpath")).toArray();
|
||||
executed = !toolpath.isEmpty();
|
||||
value.insert(QStringLiteral("toolpathCommandCount"), toolpath.size());
|
||||
value.insert(QStringLiteral("viewMode"), commandName == QStringLiteral("CAM_SimulatorGL") ? QStringLiteral("simulator-gl") : QStringLiteral("simulator"));
|
||||
value.insert(QStringLiteral("simulated"), executed);
|
||||
if (!executed) { failureCode = QStringLiteral("toolpath_required"); failureMessage = commandName + QStringLiteral(" requires toolpath"); }
|
||||
else result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else {
|
||||
executed = false;
|
||||
failureCode = QStringLiteral("unsupported_desktop_command");
|
||||
failureMessage = QStringLiteral("CAM desktop command has no native handler");
|
||||
}
|
||||
document->recompute();
|
||||
value.insert(QStringLiteral("recomputed"), true);
|
||||
application.closeDocument(document);
|
||||
}
|
||||
value.insert(QStringLiteral("executed"), executed);
|
||||
value.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("status"), executed ? QStringLiteral("exposed") : QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), executed ? QStringLiteral("native_desktop_command")
|
||||
: failureCode.isEmpty() ? QStringLiteral("document_creation_failed") : failureCode);
|
||||
result.insert(QStringLiteral("message"), executed ? QStringLiteral("CAM desktop command executed through native Document semantics")
|
||||
: failureMessage.isEmpty() ? QStringLiteral("CAM desktop command could not create a native Document") : failureMessage);
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
} else if (!apiId.startsWith(QStringLiteral("py:CAM:")) && !apiId.startsWith(QStringLiteral("obj:CAM:"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CAM API record is not part of this module-scoped adapter"));
|
||||
} else if (family == QStringLiteral("geometry-recompute") && tier == QStringLiteral("object-contract")
|
||||
&& apiId.startsWith(QStringLiteral("obj:CAM:"))) {
|
||||
const QString objectType = name;
|
||||
const QByteArray typeName = objectType.toUtf8();
|
||||
const Base::Type type = Base::Type::fromName(typeName.constData());
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), objectType);
|
||||
value.insert(QStringLiteral("registered"), !type.isBad());
|
||||
if (objectType == QStringLiteral("Path::Feature")) {
|
||||
auto& application = App::GetApplication();
|
||||
App::Document* document = application.newDocument("CAMGeometryFixture", "CAM Geometry Fixture", {false, true});
|
||||
auto* feature = document ? document->addObject("Path::Feature", "Feature") : nullptr;
|
||||
if (document) document->recompute();
|
||||
value.insert(QStringLiteral("created"), feature != nullptr);
|
||||
value.insert(QStringLiteral("recomputed"), feature != nullptr && !feature->isError());
|
||||
if (document) application.closeDocument(document);
|
||||
value.insert(QStringLiteral("resourcesReleased"), true);
|
||||
} else {
|
||||
value.insert(QStringLiteral("created"), false);
|
||||
value.insert(QStringLiteral("recomputed"), false);
|
||||
value.insert(QStringLiteral("resourcesReleased"), true);
|
||||
}
|
||||
result.insert(QStringLiteral("status"), type.isBad() ? QStringLiteral("restricted") : QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), type.isBad() ? QStringLiteral("native_type_unavailable") : QStringLiteral("native_geometry_fixture"));
|
||||
result.insert(QStringLiteral("message"), type.isBad() ? QStringLiteral("CAM object type is not registered") : QStringLiteral("CAM object registration and geometry contract verified by native runtime"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
} else if (family == QStringLiteral("geometry-value") && tier == QStringLiteral("tier-1-readonly")) {
|
||||
probeGeometryRecord(result, apiId, name);
|
||||
} else if ((family == QStringLiteral("generic-object") && tier == QStringLiteral("tier-1-readonly")) || (family == QStringLiteral("generic-document-object") && tier == QStringLiteral("object-contract"))) {
|
||||
probeGenericObjectRecord(result, apiId, name);
|
||||
} else if (family == QStringLiteral("view-provider") && tier == QStringLiteral("object-contract")
|
||||
&& apiId.startsWith(QStringLiteral("obj:CAM:"))) {
|
||||
// View providers are GUI-side objects. Keep the source-backed
|
||||
// contract explicit while reporting the native type identity.
|
||||
QJsonObject value;
|
||||
value.insert(QStringLiteral("typeName"), name);
|
||||
const Base::Type type = Base::Type::fromName(name.toUtf8().constData());
|
||||
value.insert(QStringLiteral("registered"), !type.isBad());
|
||||
value.insert(QStringLiteral("guiRequired"), true);
|
||||
value.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CAM view-provider contract is source-backed but requires FreeCADGui/PathGui, unavailable in the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("result"), value);
|
||||
} else if (family == QStringLiteral("view-resource")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CAM view-resource Python API requires PathGui, unavailable in the GUI-free Web kernel"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CAM Python API has no method-level readonly native evidence"));
|
||||
}
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-cam/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("CAM"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,14 +1,24 @@
|
||||
# SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
# Incremental implementation/gate builds do not need the expensive wasm-opt
|
||||
# pass used by release artifacts. Keep the switch in CMake so the build profile
|
||||
# is explicit and can be turned off for final performance/release validation.
|
||||
option(FREECAD_WEB_FAST_LINK "Use -O0 for Web probe link optimization during incremental work" ON)
|
||||
if(FREECAD_WEB_FAST_LINK)
|
||||
set(_freecad_web_link_optimization "-O0")
|
||||
else()
|
||||
set(_freecad_web_link_optimization "-O2")
|
||||
endif()
|
||||
|
||||
add_executable(FreeCADWebPartBoxProbe PartBoxProbe.cpp)
|
||||
target_compile_features(FreeCADWebPartBoxProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPartBoxProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebPartBoxProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebPartBoxProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
"${CMAKE_SOURCE_DIR}/src"
|
||||
)
|
||||
set(_freecad_web_python_build "${FREECAD_WEB_DEPENDENCY_ROOT}/python-probe")
|
||||
set(_freecad_web_python_build "${FREECAD_WEB_PYTHON_BUILD_ROOT}")
|
||||
set(_freecad_web_python_encodings "${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/encodings")
|
||||
target_link_libraries(FreeCADWebPartBoxProbe PRIVATE
|
||||
Part
|
||||
@@ -17,6 +27,10 @@ target_link_libraries(FreeCADWebPartBoxProbe PRIVATE
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
set(_freecad_web_local_bzip2 "${CMAKE_SOURCE_DIR}/../.emscripten-cache/sysroot/lib/wasm32-emscripten/libbz2.a")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebPartBoxProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebPartBoxProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
@@ -25,20 +39,83 @@ target_link_options(FreeCADWebPartBoxProbe PRIVATE
|
||||
"-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebPartBoxProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
# Do not keep idle Node worker handles alive for synchronous dispatcher
|
||||
# probes. Native code can still create a pthread on demand when needed.
|
||||
"-sPTHREAD_POOL_SIZE=0"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall','FS_readFile','FS_readdir']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/enum.py@/freecad-python/enum.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/types.py@/freecad-python/types.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/App/AppPartPy.cpp@/freecad-mod/Part/AppPartPy.cpp"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/PartEnums.py@/freecad-mod/Part/PartEnums.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/MakeBottle.py@/freecad-mod/Part/MakeBottle.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/parttests@/freecad-mod/Part/parttests"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/JoinFeatures.py@/freecad-mod/Part/JoinFeatures.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/BasicShapes@/freecad-mod/Part/BasicShapes"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/BOPTools@/freecad-mod/Part/BOPTools"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/CompoundTools@/freecad-mod/Part/CompoundTools"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Part/AttachmentEditor@/freecad-mod/Part/AttachmentEditor"
|
||||
)
|
||||
set_target_properties(FreeCADWebPartBoxProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
|
||||
add_executable(FreeCADWebPartDesktopCommandProbe PartDesktopCommandProbe.cpp PartDesktopCommands.cpp)
|
||||
target_compile_features(FreeCADWebPartDesktopCommandProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPartDesktopCommandProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread")
|
||||
target_include_directories(FreeCADWebPartDesktopCommandProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
"${CMAKE_SOURCE_DIR}/src"
|
||||
"${OCC_INCLUDE_DIR}"
|
||||
)
|
||||
target_link_directories(FreeCADWebPartDesktopCommandProbe PRIVATE "${OCC_LIBRARY_DIR}")
|
||||
target_link_libraries(FreeCADWebPartDesktopCommandProbe PRIVATE Qt5::Core ${OCC_LIBRARIES})
|
||||
target_link_options(FreeCADWebPartDesktopCommandProbe PRIVATE
|
||||
"${_freecad_web_link_optimization}"
|
||||
"-g0"
|
||||
"--no-entry"
|
||||
"-sWASM=1"
|
||||
"-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebPartDesktopCommandProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=0"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sERROR_ON_UNDEFINED_SYMBOLS=1"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
)
|
||||
set_target_properties(FreeCADWebPartDesktopCommandProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
|
||||
add_executable(FreeCADWebPartGeometryFamilyProbe PartGeometryFamilyProbe.cpp)
|
||||
target_compile_features(FreeCADWebPartGeometryFamilyProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPartGeometryFamilyProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebPartGeometryFamilyProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebPartGeometryFamilyProbe PRIVATE Part ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebPartGeometryFamilyProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebPartGeometryFamilyProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebPartGeometryFamilyProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
add_executable(FreeCADWebPartIoProbe PartIoProbe.cpp)
|
||||
target_compile_features(FreeCADWebPartIoProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPartIoProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
@@ -76,7 +153,6 @@ target_link_options(FreeCADWebModuleLoaderProbe PRIVATE
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
@@ -89,7 +165,7 @@ set_target_properties(FreeCADWebModuleLoaderProbe PROPERTIES
|
||||
if(FREECAD_WEB_ENABLE_SANDBOX)
|
||||
add_executable(FreeCADWebSandboxRuntimeProbe SandboxRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebSandboxRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebSandboxRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebSandboxRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebSandboxRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
@@ -98,11 +174,15 @@ if(FREECAD_WEB_ENABLE_SANDBOX)
|
||||
target_link_libraries(FreeCADWebSandboxRuntimeProbe PRIVATE
|
||||
Sandbox
|
||||
Mesh
|
||||
Part
|
||||
${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebSandboxRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebSandboxRuntimeProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
@@ -114,11 +194,15 @@ if(FREECAD_WEB_ENABLE_SANDBOX)
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"--bind"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Sandbox/Init.py@/freecad-mod/Sandbox/Init.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Sandbox/exportDRAWEXE.py@/freecad-mod/Sandbox/exportDRAWEXE.py"
|
||||
)
|
||||
set_target_properties(FreeCADWebSandboxRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
@@ -152,13 +236,21 @@ set_target_properties(FreeCADWebPlotRuntimeProbe PROPERTIES
|
||||
if(FREECAD_WEB_ENABLE_REVERSEENGINEERING)
|
||||
add_executable(FreeCADWebReverseEngineeringRuntimeProbe ReverseEngineeringRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0")
|
||||
target_include_directories(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE ReverseEngineering Materials ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebReverseEngineeringRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebReverseEngineeringRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebReverseEngineeringRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node"
|
||||
"-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0"
|
||||
"-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebReverseEngineeringRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
@@ -166,19 +258,132 @@ if(FREECAD_WEB_ENABLE_ROBOT)
|
||||
add_executable(FreeCADWebRobotRuntimeProbe RobotRuntimeProbeFixed.cpp)
|
||||
target_sources(FreeCADWebRobotRuntimeProbe PRIVATE RobotInventoryApi.cpp)
|
||||
target_compile_features(FreeCADWebRobotRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebRobotRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebRobotRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebRobotRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebRobotRuntimeProbe PRIVATE Robot Part Materials ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebRobotRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebRobotRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebRobotRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebRobotRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebRobotRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_SHOW)
|
||||
add_executable(FreeCADWebShowRuntimeProbe ShowRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebShowRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebShowRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebShowRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebShowRuntimeProbe PRIVATE
|
||||
FreeCADApp
|
||||
${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebShowRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebShowRuntimeProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/weakref.py@/freecad-python/weakref.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/_weakrefset.py@/freecad-python/_weakrefset.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/_collections_abc.py@/freecad-python/_collections_abc.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/types.py@/freecad-python/types.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/copy.py@/freecad-python/copy.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/copyreg.py@/freecad-python/copyreg.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/abc.py@/freecad-python/abc.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Show@/freecad-mod/Show")
|
||||
set_target_properties(FreeCADWebShowRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_SPREADSHEET)
|
||||
add_executable(FreeCADWebSpreadsheetRuntimeProbe SpreadsheetRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebSpreadsheetRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebSpreadsheetRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebSpreadsheetRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebSpreadsheetRuntimeProbe PRIVATE
|
||||
Spreadsheet
|
||||
${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebSpreadsheetRuntimeProbe PRIVATE
|
||||
"-pthread" "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebSpreadsheetRuntimeProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sEXPORTED_RUNTIME_METHODS=['ccall','FS']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebSpreadsheetRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(BUILD_INSPECTION AND BUILD_JTREADER AND BUILD_MATERIAL AND BUILD_MEASURE AND FREECAD_WEB_ENABLE_SPREADSHEET)
|
||||
add_executable(FreeCADWebDataPropertyFamilyProbe DataPropertyFamilyProbe.cpp)
|
||||
target_compile_features(FreeCADWebDataPropertyFamilyProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebDataPropertyFamilyProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebDataPropertyFamilyProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebDataPropertyFamilyProbe PRIVATE
|
||||
Inspection JtReader Materials Measure Spreadsheet Part Mesh Points ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebDataPropertyFamilyProbe PRIVATE
|
||||
"-pthread" "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebDataPropertyFamilyProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=67108864"
|
||||
"-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebDataPropertyFamilyProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_START)
|
||||
add_executable(FreeCADWebStartRuntimeProbe StartRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebStartRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebStartRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebStartRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebStartRuntimeProbe PRIVATE Start ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebStartRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebStartRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebStartRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
add_executable(FreeCADWebStartRecoveryProbe StartRecoveryProbe.cpp)
|
||||
target_compile_features(FreeCADWebStartRecoveryProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebStartRecoveryProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebStartRecoveryProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebStartRecoveryProbe PRIVATE Start ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebStartRecoveryProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebStartRecoveryProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebStartRecoveryProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
add_executable(FreeCADWebStartInventoryProbe StartInventoryProbe.cpp)
|
||||
target_compile_features(FreeCADWebStartInventoryProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebStartInventoryProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebStartInventoryProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebStartInventoryProbe PRIVATE Start ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebStartInventoryProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebStartInventoryProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebStartInventoryProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_SURFACE)
|
||||
add_executable(FreeCADWebSurfaceRuntimeProbe SurfaceRuntimeProbe.cpp)
|
||||
target_sources(FreeCADWebSurfaceRuntimeProbe PRIVATE SurfaceRecoveryProbe.cpp SurfacePersistenceProbe.cpp SurfacePersistenceRecoveryProbe.cpp SurfaceInventoryProbe.cpp SurfacePythonProbe.cpp SurfacePythonRecoveryProbe.cpp SurfaceFamilyProbe.cpp)
|
||||
target_compile_features(FreeCADWebSurfaceRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebSurfaceRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0")
|
||||
target_include_directories(FreeCADWebSurfaceRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebSurfaceRuntimeProbe PRIVATE Surface Part Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebSurfaceRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebSurfaceRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebSurfaceRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
add_executable(FreeCADWebPartDesignRuntimeProbe PartDesignRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebPartDesignRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPartDesignRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebPartDesignRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebPartDesignRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
@@ -194,6 +399,9 @@ target_link_libraries(FreeCADWebPartDesignRuntimeProbe PRIVATE
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebPartDesignRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebPartDesignRuntimeProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
@@ -205,10 +413,15 @@ target_link_options(FreeCADWebPartDesignRuntimeProbe PRIVATE
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall','FS_readFile']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/PartDesign/fcgear@/freecad-mod/PartDesign/fcgear"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/PartDesign/fcsprocket@/freecad-mod/PartDesign/fcsprocket"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/PartDesign/WizardShaft@/freecad-mod/PartDesign/WizardShaft"
|
||||
)
|
||||
set_target_properties(FreeCADWebPartDesignRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
@@ -217,10 +430,10 @@ set_target_properties(FreeCADWebPartDesignRuntimeProbe PROPERTIES
|
||||
|
||||
add_executable(FreeCADWebPointsRuntimeProbe PointsRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebPointsRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebPointsRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebPointsRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebPointsRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebPointsRuntimeProbe PRIVATE Points Part ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebPointsRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebPointsRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebPointsRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebPointsRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebPointsRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
if(FREECAD_WEB_ENABLE_OPENSCAD)
|
||||
@@ -239,12 +452,14 @@ if(FREECAD_WEB_ENABLE_OPENSCAD)
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
target_link_options(FreeCADWebOpenSCADRuntimeProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
"--no-entry"
|
||||
"-sWASM=1"
|
||||
"-sMODULARIZE=1"
|
||||
target_link_options(FreeCADWebOpenSCADRuntimeProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
"--no-entry"
|
||||
"-sWASM=1"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebOpenSCADRuntimeProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
@@ -256,6 +471,12 @@ if(FREECAD_WEB_ENABLE_OPENSCAD)
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/Init.py@/freecad-mod/OpenSCAD/Init.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/OpenSCADUtils.py@/freecad-mod/OpenSCAD/OpenSCADUtils.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/OpenSCADCommands.py@/freecad-mod/OpenSCAD/OpenSCADCommands.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/OpenSCADFeatures.py@/freecad-mod/OpenSCAD/OpenSCADFeatures.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/OpenSCAD2Dgeom.py@/freecad-mod/OpenSCAD/OpenSCAD2Dgeom.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/importCSG.py@/freecad-mod/OpenSCAD/importCSG.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/prototype.py@/freecad-mod/OpenSCAD/prototype.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/OpenSCAD/InitGui.py@/freecad-mod/OpenSCAD/InitGui.py"
|
||||
)
|
||||
set_target_properties(FreeCADWebOpenSCADRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
@@ -278,6 +499,9 @@ target_link_libraries(FreeCADWebImportRuntimeProbe PRIVATE
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebImportRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebImportRuntimeProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
@@ -289,7 +513,9 @@ target_link_options(FreeCADWebImportRuntimeProbe PRIVATE
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
@@ -303,7 +529,9 @@ set_target_properties(FreeCADWebImportRuntimeProbe PROPERTIES
|
||||
if(BUILD_INSPECTION)
|
||||
add_executable(FreeCADWebInspectionRuntimeProbe InspectionRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebInspectionRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebInspectionRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebInspectionRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4"
|
||||
)
|
||||
target_include_directories(FreeCADWebInspectionRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
@@ -327,6 +555,9 @@ if(BUILD_INSPECTION)
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=0"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
@@ -350,17 +581,18 @@ if(BUILD_MATERIAL)
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMaterialRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebMaterialRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebMaterialRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebMaterialRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sERROR_ON_UNDEFINED_SYMBOLS=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMaterialRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
add_executable(FreeCADWebMaterialKernelProbe MaterialKernelProbe.cpp)
|
||||
target_compile_features(FreeCADWebMaterialKernelProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebMaterialKernelProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebMaterialKernelProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebMaterialKernelProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMaterialKernelProbe PRIVATE
|
||||
@@ -369,12 +601,16 @@ if(BUILD_MATERIAL)
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebMaterialKernelProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebMaterialKernelProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebMaterialKernelProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Material/MaterialEditor.py@/freecad-mod/Material/MaterialEditor.py")
|
||||
set_target_properties(FreeCADWebMaterialKernelProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
add_executable(FreeCADWebMaterialPythonKernelProbe MaterialPythonKernelProbe.cpp)
|
||||
@@ -423,17 +659,19 @@ endif()
|
||||
if(BUILD_MEASURE)
|
||||
add_executable(FreeCADWebMeasureRuntimeProbe MeasureRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebMeasureRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebMeasureRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebMeasureRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeasureRuntimeProbe PRIVATE Measure Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeasureRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeasureRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeasureRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
target_compile_options(FreeCADWebMeasureRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread")
|
||||
target_include_directories(FreeCADWebMeasureRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeasureRuntimeProbe PRIVATE Measure Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeasureRuntimeProbe PRIVATE "-pthread" "-sPTHREAD_POOL_SIZE=1")
|
||||
set_property(TARGET FreeCADWebMeasureRuntimeProbe APPEND PROPERTY LINK_OPTIONS "-sPTHREAD_POOL_SIZE=1")
|
||||
target_link_options(FreeCADWebMeasureRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeasureRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeasureRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
add_executable(FreeCADWebMeasureKernelProbe MeasureKernelProbe.cpp)
|
||||
target_compile_features(FreeCADWebMeasureKernelProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebMeasureKernelProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebMeasureKernelProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebMeasureKernelProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeasureKernelProbe PRIVATE Measure Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeasureKernelProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeasureKernelProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebMeasureKernelProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeasureKernelProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeasureKernelProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
@@ -443,17 +681,28 @@ if(BUILD_MESH)
|
||||
target_compile_options(FreeCADWebMeshRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebMeshRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeshRuntimeProbe PRIVATE Mesh ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeshRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeshRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebMeshRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebMeshRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeshRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeshRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
add_executable(FreeCADWebMeshGeometryFamilyProbe MeshGeometryFamilyProbe.cpp)
|
||||
target_compile_features(FreeCADWebMeshGeometryFamilyProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebMeshGeometryFamilyProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebMeshGeometryFamilyProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeshGeometryFamilyProbe PRIVATE Mesh ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeshGeometryFamilyProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeshGeometryFamilyProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeshGeometryFamilyProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(BUILD_MESH_PART)
|
||||
add_executable(FreeCADWebMeshPartRuntimeProbe MeshPartRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebMeshPartRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebMeshPartRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebMeshPartRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread")
|
||||
target_include_directories(FreeCADWebMeshPartRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebMeshPartRuntimeProbe PRIVATE MeshPart Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebMeshPartRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeshPartRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
target_link_options(FreeCADWebMeshPartRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-pthread" "-sUSE_PTHREADS=1" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebMeshPartRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebMeshPartRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
@@ -464,6 +713,17 @@ target_include_directories(FreeCADWebAssemblyProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
"${CMAKE_SOURCE_DIR}/src"
|
||||
"${CMAKE_SOURCE_DIR}/src/3rdParty/FastSignals/libfastsignals/include"
|
||||
"${CMAKE_SOURCE_DIR}/src/3rdParty/PyCXX"
|
||||
"${CMAKE_SOURCE_DIR}/src/3rdParty/OndselSolver"
|
||||
${QtCore_INCLUDE_DIRS}
|
||||
"${fmt_SOURCE_DIR}/include"
|
||||
${XercesC_INCLUDE_DIR}
|
||||
${XercesC_INCLUDE_DIRS}
|
||||
${Boost_INCLUDE_DIRS}
|
||||
${Python3_INCLUDE_DIRS}
|
||||
${Python3_INCLUDE_DIR}
|
||||
${OCC_INCLUDE_DIR}
|
||||
)
|
||||
target_link_libraries(FreeCADWebAssemblyProbe PRIVATE
|
||||
Assembly
|
||||
@@ -547,7 +807,7 @@ if(BUILD_CAM)
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
target_link_options(FreeCADWebCAMProbe PRIVATE
|
||||
"-O2"
|
||||
"${_freecad_web_link_optimization}"
|
||||
"-g0"
|
||||
"--no-entry"
|
||||
"-sWASM=1"
|
||||
@@ -604,9 +864,62 @@ set_target_properties(FreeCADWebDocumentProbe PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
|
||||
add_executable(FreeCADWebWorkbenchCommandProbe WorkbenchCommandProbe.cpp)
|
||||
target_compile_features(FreeCADWebWorkbenchCommandProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebWorkbenchCommandProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebWorkbenchCommandProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebWorkbenchCommandProbe PRIVATE
|
||||
FreeCADApp ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebWorkbenchCommandProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebWorkbenchCommandProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebWorkbenchCommandProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
add_executable(FreeCADWebDocumentGraphFamilyProbe DocumentGraphFamilyProbe.cpp)
|
||||
target_compile_features(FreeCADWebDocumentGraphFamilyProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebDocumentGraphFamilyProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebDocumentGraphFamilyProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebDocumentGraphFamilyProbe PRIVATE
|
||||
FreeCADApp Part ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebDocumentGraphFamilyProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1"
|
||||
"-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebDocumentGraphFamilyProbe"
|
||||
"-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=67108864"
|
||||
"-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebDocumentGraphFamilyProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
if(BUILD_FEM)
|
||||
add_executable(FreeCADWebFemGenericFamilyProbe FemGenericFamilyProbe.cpp FemDesktopCommands.cpp)
|
||||
target_compile_features(FreeCADWebFemGenericFamilyProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebFemGenericFamilyProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebFemGenericFamilyProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebFemGenericFamilyProbe PRIVATE Fem ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebFemGenericFamilyProbe PRIVATE "${_freecad_web_link_optimization}" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebFemGenericFamilyProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=67108864" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sERROR_ON_UNDEFINED_SYMBOLS=1" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/CreateLabels.py@/freecad-mod/Fem/CreateLabels.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femcommands@/freecad-mod/Fem/femcommands" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femguiutils@/freecad-mod/Fem/femguiutils" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femobjects@/freecad-mod/Fem/femobjects" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femtools@/freecad-mod/Fem/femtools" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femsolver@/freecad-mod/Fem/femsolver" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/femviewprovider@/freecad-mod/Fem/femviewprovider" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Fem/fempreferencepages@/freecad-mod/Fem/fempreferencepages")
|
||||
set_target_properties(FreeCADWebFemGenericFamilyProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
add_executable(FreeCADWebSketcherProbe SketcherProbe.cpp)
|
||||
target_compile_features(FreeCADWebSketcherProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebSketcherProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_compile_options(FreeCADWebSketcherProbe PRIVATE
|
||||
"-O2" "-g0" "-fexceptions"
|
||||
"-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebSketcherProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}"
|
||||
"${CMAKE_BINARY_DIR}/src"
|
||||
@@ -619,6 +932,9 @@ target_link_libraries(FreeCADWebSketcherProbe PRIVATE
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a"
|
||||
)
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebSketcherProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebSketcherProbe PRIVATE
|
||||
"-O2"
|
||||
"-g0"
|
||||
@@ -630,10 +946,15 @@ target_link_options(FreeCADWebSketcherProbe PRIVATE
|
||||
"-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=33554432"
|
||||
"-sENVIRONMENT=web,worker,node"
|
||||
"-sUSE_BZIP2=1"
|
||||
"-pthread"
|
||||
"-sUSE_PTHREADS=1"
|
||||
"-sPTHREAD_POOL_SIZE=4"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall','FS']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Sketcher/Profiles.py@/freecad-mod/Sketcher/Profiles.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Sketcher/ProfileLib/Hexagon.py@/freecad-mod/Sketcher/ProfileLib/Hexagon.py"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Sketcher/ProfileLib/RegularPolygon.py@/freecad-mod/Sketcher/ProfileLib/RegularPolygon.py"
|
||||
)
|
||||
set_target_properties(FreeCADWebSketcherProbe PROPERTIES
|
||||
SUFFIX ".js"
|
||||
@@ -650,6 +971,9 @@ target_include_directories(FreeCADWebPythonProbe PRIVATE
|
||||
)
|
||||
target_link_libraries(FreeCADWebPythonProbe PRIVATE
|
||||
Part
|
||||
Mesh
|
||||
Points
|
||||
MeshPart
|
||||
${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
@@ -676,6 +1000,144 @@ set_target_properties(FreeCADWebPythonProbe PROPERTIES
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
|
||||
# Headless Draft bridge: execute the official Draft Python source against the
|
||||
# FreeCAD App/Part WASM runtime. Qt imports are provided only as no-GUI import
|
||||
# shims inside the probe; geometry and Document recompute remain native.
|
||||
add_executable(FreeCADWebDraftRuntimeProbe DraftRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebDraftRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebDraftRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebDraftRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
if(FREECAD_WEB_ENABLE_TECHDRAW_NATIVE)
|
||||
target_compile_options(FreeCADWebDraftRuntimeProbe PRIVATE "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
endif()
|
||||
target_include_directories(FreeCADWebDraftRuntimeProbe PRIVATE
|
||||
"${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebDraftRuntimeProbe PRIVATE
|
||||
Part ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebDraftRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebDraftRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=201326592" "-sENVIRONMENT=web,worker,node"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/types.py@/freecad-python/types.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/copy.py@/freecad-python/copy.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/copyreg.py@/freecad-python/copyreg.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/abc.py@/freecad-python/abc.py"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12@/freecad-python/stdlib"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Draft@/freecad-mod/Draft"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/3rdParty/lazy_loader@/freecad-mod/lazy_loader")
|
||||
if(FREECAD_WEB_ENABLE_TECHDRAW_NATIVE)
|
||||
target_link_options(FreeCADWebDraftRuntimeProbe PRIVATE "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
endif()
|
||||
set_target_properties(FreeCADWebDraftRuntimeProbe PROPERTIES
|
||||
SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
# BIM is a Python workbench without a GUI-free C++ App target. Embed its
|
||||
# official source tree for native source inventory; execution remains bounded
|
||||
# until Arch/IFC dependencies have a real WebAssembly closure.
|
||||
add_executable(FreeCADWebBimRuntimeProbe BimRuntimeProbe.cpp)
|
||||
# Staging is regenerated by tools/prepare_bim_probe_resources.py before builds.
|
||||
target_compile_features(FreeCADWebBimRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebBimRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebBimRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebBimRuntimeProbe PRIVATE FreeCADApp ${Python3_LIBRARIES}
|
||||
Part Materials
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebBimRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
target_link_options(FreeCADWebBimRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebBimRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=268435456" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=0"
|
||||
"-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--preload-file=${CMAKE_BINARY_DIR}/bim-probe-staging@/")
|
||||
set_target_properties(FreeCADWebBimRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
set_property(TARGET FreeCADWebBimRuntimeProbe APPEND PROPERTY LINK_DEPENDS
|
||||
"${CMAKE_BINARY_DIR}/bim-probe-staging/.resource-manifest.sha256")
|
||||
|
||||
add_executable(FreeCADWebHelpRuntimeProbe HelpRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebHelpRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebHelpRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebHelpRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebHelpRuntimeProbe PRIVATE FreeCADApp ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebHelpRuntimeProbe PRIVATE
|
||||
"-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1"
|
||||
"-sEXPORT_NAME=FreeCADWebHelpRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1"
|
||||
"-sINITIAL_MEMORY=67108864" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1"
|
||||
"-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']"
|
||||
"--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings"
|
||||
"--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/re@/freecad-python/re"
|
||||
"--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Help@/freecad-mod/Help")
|
||||
set_target_properties(FreeCADWebHelpRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
if(FREECAD_WEB_ENABLE_WEB)
|
||||
add_executable(FreeCADWebWebRuntimeProbe WebRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebWebRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebWebRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebWebRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebWebRuntimeProbe PRIVATE Web ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebWebRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebWebRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebWebRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_TECHDRAW_NATIVE)
|
||||
add_executable(FreeCADWebTechDrawRuntimeProbe TechDrawRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebTechDrawRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebTechDrawRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebTechDrawRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebTechDrawRuntimeProbe PRIVATE TechDraw PartDesign Sketcher Spreadsheet Measure Part ${Python3_LIBRARIES}
|
||||
"${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a"
|
||||
"${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a"
|
||||
"${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
if(EXISTS "${_freecad_web_local_bzip2}")
|
||||
target_link_libraries(FreeCADWebTechDrawRuntimeProbe PRIVATE "${_freecad_web_local_bzip2}")
|
||||
endif()
|
||||
# The OCCT pthread prefix is compiled with atomics/bulk-memory metadata,
|
||||
# so the native TechDraw probe can use Emscripten shared memory directly.
|
||||
target_link_options(FreeCADWebTechDrawRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebTechDrawRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=67108864" "-sENVIRONMENT=web,worker,node" "--bind" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sERROR_ON_UNDEFINED_SYMBOLS=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall','FS']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TechDraw@/freecad-mod/TechDraw")
|
||||
set_target_properties(FreeCADWebTechDrawRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_TEST)
|
||||
add_executable(FreeCADWebTestRuntimeProbe TestRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebTestRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebTestRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebTestRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebTestRuntimeProbe PRIVATE Part ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebTestRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebTestRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/Test/Init.py@/freecad-mod/Test/Init.py")
|
||||
set_target_properties(FreeCADWebTestRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
if(FREECAD_WEB_ENABLE_TUX)
|
||||
add_executable(FreeCADWebTuxRuntimeProbe TuxRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebTuxRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebTuxRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions")
|
||||
target_include_directories(FreeCADWebTuxRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebTuxRuntimeProbe PRIVATE)
|
||||
target_link_options(FreeCADWebTuxRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebTuxRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings")
|
||||
set_target_properties(FreeCADWebTuxRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
endif()
|
||||
|
||||
add_executable(FreeCADWebTemplatePyModRuntimeProbe TemplatePyModRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebTemplatePyModRuntimeProbe PRIVATE cxx_std_17)
|
||||
target_compile_options(FreeCADWebTemplatePyModRuntimeProbe PRIVATE "-O2" "-g0" "-fexceptions" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4")
|
||||
target_include_directories(FreeCADWebTemplatePyModRuntimeProbe PRIVATE "${CMAKE_BINARY_DIR}" "${CMAKE_BINARY_DIR}/src" "${CMAKE_SOURCE_DIR}/src")
|
||||
target_link_libraries(FreeCADWebTemplatePyModRuntimeProbe PRIVATE Part Materials ${Python3_LIBRARIES} "${_freecad_web_python_build}/Modules/_decimal/libmpdec/libmpdec.a" "${_freecad_web_python_build}/Modules/_hacl/libHacl_Hash_SHA2.a" "${_freecad_web_python_build}/Modules/expat/libexpat.a")
|
||||
target_link_options(FreeCADWebTemplatePyModRuntimeProbe PRIVATE "-O2" "-g0" "--no-entry" "-sWASM=1" "-sMODULARIZE=1" "-sEXPORT_ES6=1" "-sEXPORT_NAME=FreeCADWebTemplatePyModRuntimeProbe" "-sALLOW_MEMORY_GROWTH=1" "-sINITIAL_MEMORY=33554432" "-sENVIRONMENT=web,worker,node" "-pthread" "-sUSE_PTHREADS=1" "-sPTHREAD_POOL_SIZE=4" "-sUSE_BZIP2=1" "-sDISABLE_EXCEPTION_CATCHING=0" "-sEXPORTED_RUNTIME_METHODS=['ccall']" "--embed-file=${_freecad_web_python_encodings}@/freecad-python/encodings" "--embed-file=${FREECAD_WEB_PYTHON_ROOT}/lib/python3.12/ast.py@/freecad-python/ast.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Init.py@/freecad-mod/TemplatePyMod/Init.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/DocumentObject.py@/freecad-mod/TemplatePyMod/DocumentObject.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Automation.py@/freecad-mod/TemplatePyMod/Automation.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Commands.py@/freecad-mod/TemplatePyMod/Commands.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/FeaturePython.py@/freecad-mod/TemplatePyMod/FeaturePython.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/InitGui.py@/freecad-mod/TemplatePyMod/InitGui.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/MengerSponge.py@/freecad-mod/TemplatePyMod/MengerSponge.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Mesh2Shape.py@/freecad-mod/TemplatePyMod/Mesh2Shape.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/PythonQt.py@/freecad-mod/TemplatePyMod/PythonQt.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/SplineSurface.py@/freecad-mod/TemplatePyMod/SplineSurface.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/TaskPanel.py@/freecad-mod/TemplatePyMod/TaskPanel.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Tests.py@/freecad-mod/TemplatePyMod/Tests.py" "--embed-file=${CMAKE_SOURCE_DIR}/src/Mod/TemplatePyMod/Texture.py@/freecad-mod/TemplatePyMod/Texture.py")
|
||||
set_target_properties(FreeCADWebTemplatePyModRuntimeProbe PROPERTIES SUFFIX ".js" RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
|
||||
|
||||
if(BUILD_CLOUD)
|
||||
add_executable(FreeCADWebCloudProbe CloudRuntimeProbe.cpp)
|
||||
target_compile_features(FreeCADWebCloudProbe PRIVATE cxx_std_17)
|
||||
@@ -749,3 +1211,17 @@ if(BUILD_CLOUD)
|
||||
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin"
|
||||
)
|
||||
endif()
|
||||
|
||||
# Apply the same development link profile to every probe declared in this
|
||||
# directory. This keeps later module batches from silently falling back to a
|
||||
# full `-O2` wasm-opt pass while the fast-link switch is enabled.
|
||||
if(FREECAD_WEB_FAST_LINK)
|
||||
get_property(_freecad_web_probe_targets DIRECTORY PROPERTY BUILDSYSTEM_TARGETS)
|
||||
foreach(_freecad_web_probe_target IN LISTS _freecad_web_probe_targets)
|
||||
get_target_property(_freecad_web_probe_link_options ${_freecad_web_probe_target} LINK_OPTIONS)
|
||||
if(_freecad_web_probe_link_options)
|
||||
list(TRANSFORM _freecad_web_probe_link_options REPLACE "^-O2$" "${_freecad_web_link_optimization}")
|
||||
set_property(TARGET ${_freecad_web_probe_target} PROPERTY LINK_OPTIONS "${_freecad_web_probe_link_options}")
|
||||
endif()
|
||||
endforeach()
|
||||
endif()
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <Base/Console.h>
|
||||
#include <Base/Exception.h>
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
|
||||
#include <exception>
|
||||
#include <string>
|
||||
@@ -78,6 +83,7 @@ int pythonModuleHandleBeforeRelease = 0;
|
||||
int pythonModuleHandleAfterRelease = 0;
|
||||
int pythonDocumentCountBefore = 0;
|
||||
int pythonDocumentCountAfter = 0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
constexpr const char* cloudSourceRevision = "b5a086fda59b0325fe0996147e6e9b344414f9bc";
|
||||
constexpr const char* cloudInventoryRevision = "4f4e9244e613ea2df06e70027074a562695048cb";
|
||||
@@ -633,6 +639,105 @@ EMSCRIPTEN_KEEPALIVE int fc_web_cloud_python_api(const char* sourceRevision)
|
||||
return 0;
|
||||
}
|
||||
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Cloud_Test")
|
||||
// Project-level dispatcher for the Cloud Python and desktop-command families.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Cloud native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Cloud native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("cloud.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Cloud native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-1-readonly") || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"cloud.pythonFamilyBatch requires tier=tier-1-readonly and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
addCloudModule();
|
||||
if (!PyDict_GetItemString(PyImport_GetModuleDict(), "Cloud")) {
|
||||
throw Base::RuntimeError("Cloud module was not registered");
|
||||
}
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Cloud/InitGui.py:8"));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(cloudSourceRevision));
|
||||
if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Cloud API record requires apiId, name and family"));
|
||||
}
|
||||
else if (apiId == QStringLiteral("Cloud:desktop:Cloud_Test")
|
||||
&& name == QStringLiteral("Cloud_Test")
|
||||
&& family == QStringLiteral("desktop-command-command")) {
|
||||
Base::Console().message("Hello, World!\n");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("ok"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Cloud/Gui/Command.cpp:50"));
|
||||
result.insert(QStringLiteral("command"), QStringLiteral("Cloud_Test"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Hello, World!"));
|
||||
}
|
||||
else if (apiId != QStringLiteral("py:Cloud:class:CloudWorkbench")
|
||||
|| name != QStringLiteral("CloudWorkbench")
|
||||
|| family != QStringLiteral("generic-object")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Cloud API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("CloudWorkbench is declared in InitGui.py and requires FreeCADGui in the GUI-free Web kernel"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-cloud/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Cloud"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_cloud_kernel_error_code()
|
||||
{
|
||||
return lastErrorCode.c_str();
|
||||
|
||||
427
src/WebAssembly/FreeCADCoreProbe/DataPropertyFamilyProbe.cpp
Normal file
427
src/WebAssembly/FreeCADCoreProbe/DataPropertyFamilyProbe.cpp
Normal file
@@ -0,0 +1,427 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/InventorObject.h>
|
||||
#include <App/Property.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Inspection/App/InspectionFeature.h>
|
||||
#include <Mod/Material/App/Materials.h>
|
||||
#include <Mod/Material/App/PropertyMaterial.h>
|
||||
#include <Mod/Measure/App/MeasureDistance.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <Mod/Spreadsheet/App/Sheet.h>
|
||||
#include <Python.h>
|
||||
#include <QString>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" PyObject* PyInit_Inspection();
|
||||
extern "C" PyObject* PyInit_JtReader();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
extern "C" PyObject* PyInit_Measure();
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Points();
|
||||
extern "C" PyObject* PyInit_Spreadsheet();
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const types[] = {
|
||||
"Inspection::PropertyDistanceList",
|
||||
"App::InventorObject",
|
||||
"Materials::Array2D",
|
||||
"Materials::Array3D",
|
||||
"Materials::Library",
|
||||
"Materials::Material",
|
||||
"Materials::MaterialFilter",
|
||||
"Materials::MaterialFilterOptions",
|
||||
"Materials::MaterialLibrary",
|
||||
"Materials::MaterialLibraryLocal",
|
||||
"Materials::MaterialManager",
|
||||
"Materials::MaterialManagerExternal",
|
||||
"Materials::MaterialManagerLocal",
|
||||
"Materials::MaterialProperty",
|
||||
"Materials::MaterialValue",
|
||||
"Materials::Model",
|
||||
"Materials::ModelLibrary",
|
||||
"Materials::ModelLibraryLocal",
|
||||
"Materials::ModelManager",
|
||||
"Materials::ModelManagerExternal",
|
||||
"Materials::ModelManagerLocal",
|
||||
"Materials::ModelProperty",
|
||||
"Materials::ModelUUIDs",
|
||||
"Materials::PropertyMaterial",
|
||||
"Measure::MeasureAngle",
|
||||
"Measure::MeasureArea",
|
||||
"Measure::MeasureBase",
|
||||
"Measure::MeasureDiameter",
|
||||
"Measure::MeasureDistance",
|
||||
"Measure::MeasureDistanceDetached",
|
||||
"Measure::MeasureLength",
|
||||
"Measure::MeasurePosition",
|
||||
"Measure::MeasureRadius",
|
||||
"Measure::Measurement",
|
||||
"Measure::Result",
|
||||
"Spreadsheet::PropertyColumnWidths",
|
||||
"Spreadsheet::PropertyRowHeights",
|
||||
"Spreadsheet::PropertySheet",
|
||||
"Spreadsheet::PropertySpreadsheetQuantity",
|
||||
"Spreadsheet::Sheet",
|
||||
};
|
||||
|
||||
std::string response;
|
||||
std::string fixtureError;
|
||||
bool initialized = false;
|
||||
|
||||
std::string jsonQuote(const std::string& value)
|
||||
{
|
||||
std::string out = "\"";
|
||||
for (const char character : value) {
|
||||
if (character == '\\' || character == '"') out += '\\';
|
||||
out += character;
|
||||
}
|
||||
return out + '"';
|
||||
}
|
||||
|
||||
std::string pythonError()
|
||||
{
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "PythonError";
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
message = PyUnicode_AsUTF8(text);
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
void addBuiltin(const char* name, PyObject* (*initializer)())
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (PyDict_GetItemString(modules, name)) return;
|
||||
PyObject* module = initializer();
|
||||
if (!module) throw Base::RuntimeError(std::string("PyInit_") + name + " failed: " + pythonError());
|
||||
if (PyDict_SetItemString(modules, name, module) != 0) {
|
||||
Py_DECREF(module);
|
||||
throw Base::RuntimeError(std::string("failed to register ") + name);
|
||||
}
|
||||
Py_DECREF(module);
|
||||
}
|
||||
|
||||
void initModules()
|
||||
{
|
||||
if (initialized) return;
|
||||
App::Application::initWebCore();
|
||||
addBuiltin("Materials", &PyInit_Materials);
|
||||
addBuiltin("Part", &PyInit_Part);
|
||||
addBuiltin("Mesh", &PyInit_Mesh);
|
||||
addBuiltin("Points", &PyInit_Points);
|
||||
addBuiltin("Inspection", &PyInit_Inspection);
|
||||
addBuiltin("JtReader", &PyInit_JtReader);
|
||||
addBuiltin("Measure", &PyInit_Measure);
|
||||
addBuiltin("Spreadsheet", &PyInit_Spreadsheet);
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
bool runInspectionFixture()
|
||||
{
|
||||
auto* value = static_cast<Inspection::PropertyDistanceList*>(
|
||||
Base::Type::fromName("Inspection::PropertyDistanceList").createInstance()
|
||||
);
|
||||
if (!value) return false;
|
||||
value->setValues({1.25F, 2.5F, 5.0F});
|
||||
const bool valid = value->getValues().size() == 3 && std::abs((*value)[1] - 2.5F) < 1e-6F;
|
||||
delete value;
|
||||
return valid;
|
||||
}
|
||||
|
||||
bool runJtReaderFixture()
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/DataPropertyJtReader.FCStd";
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("DataPropertyJtReader", "Data Property JtReader", {false, true});
|
||||
auto* inventor = document ? dynamic_cast<App::InventorObject*>(document->addObject("App::InventorObject", "JtScene")) : nullptr;
|
||||
if (!inventor) throw Base::RuntimeError("JtReader InventorObject creation failed");
|
||||
inventor->Buffer.setValue("#Inventor V2.1 ascii\\nSeparator { }\\n");
|
||||
inventor->FileName.setValue("DataProperty.jt");
|
||||
bool hasError = false;
|
||||
const int recompute = document->recompute({}, false, &hasError);
|
||||
if (hasError || recompute < 0 || !document->saveAs(path) || Base::FileInfo(path).size() <= 0) {
|
||||
throw Base::RuntimeError("JtReader property/recompute save failed");
|
||||
}
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = application.newDocument("DataPropertyJtReaderOpened", "Data Property JtReader Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
auto* restored = dynamic_cast<App::InventorObject*>(reopened->getObject("JtScene"));
|
||||
const bool valid = restored && std::string(restored->Buffer.getValue()).find("Separator") != std::string::npos;
|
||||
application.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (...) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool runMaterialFixture()
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/DataPropertyMaterial.FCStd";
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("DataPropertyMaterial", "Data Property Material", {false, true});
|
||||
auto* object = document ? document->addObject("App::DocumentObjectGroup", "MaterialFeature") : nullptr;
|
||||
auto* property = object ? dynamic_cast<Materials::PropertyMaterial*>(object->addDynamicProperty(
|
||||
"Materials::PropertyMaterial", "Material", "Material", "Data-property fixture")) : nullptr;
|
||||
if (!property) throw Base::RuntimeError("Material property creation failed");
|
||||
Materials::Material material(nullptr, QStringLiteral("/fixture"), QStringLiteral("data-property-material-v1"), QStringLiteral("Data Property Material"));
|
||||
property->setValue(material);
|
||||
bool hasError = false;
|
||||
if (document->recompute({}, false, &hasError) < 0 || hasError || !document->saveAs(path)) {
|
||||
throw Base::RuntimeError("Material property/recompute save failed");
|
||||
}
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = application.newDocument("DataPropertyMaterialOpened", "Data Property Material Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
auto* restored = reopened->getObject("MaterialFeature");
|
||||
const bool valid = restored && restored->getPropertyByName("Material") != nullptr;
|
||||
application.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (...) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool runMeasureFixture()
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/DataPropertyMeasure.FCStd";
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("DataPropertyMeasure", "Data Property Measure", {false, true});
|
||||
auto* object = document ? dynamic_cast<Measure::MeasureDistanceDetached*>(document->addObject("Measure::MeasureDistanceDetached", "Distance")) : nullptr;
|
||||
if (!object) throw Base::RuntimeError("Measure object creation failed");
|
||||
object->Position1.setValue(0.0, 0.0, 0.0);
|
||||
object->Position2.setValue(3.0, 4.0, 0.0);
|
||||
bool hasError = false;
|
||||
if (document->recompute({}, false, &hasError) < 0 || hasError || std::abs(object->Distance.getValue() - 5.0) > 1e-9 || !document->saveAs(path)) {
|
||||
throw Base::RuntimeError("Measure property/recompute save failed");
|
||||
}
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = application.newDocument("DataPropertyMeasureOpened", "Data Property Measure Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
auto* restored = dynamic_cast<Measure::MeasureDistanceDetached*>(reopened->getObject("Distance"));
|
||||
bool restoredError = false;
|
||||
reopened->recompute({}, false, &restoredError);
|
||||
const bool valid = restored && !restoredError && std::abs(restored->Distance.getValue() - 5.0) < 1e-9;
|
||||
application.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (...) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool runSpreadsheetFixture()
|
||||
{
|
||||
fixtureError.clear();
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/DataPropertySpreadsheet.FCStd";
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("DataPropertySpreadsheet", "Data Property Spreadsheet", {false, true});
|
||||
auto* sheet = document ? dynamic_cast<Spreadsheet::Sheet*>(document->addObject("Spreadsheet::Sheet", "Sheet")) : nullptr;
|
||||
if (!sheet) throw Base::RuntimeError("Spreadsheet sheet creation failed");
|
||||
sheet->setCell("A1", "21");
|
||||
sheet->setCell("B1", "=A1*2");
|
||||
bool hasError = false;
|
||||
if (document->recompute({}, false, &hasError) < 0 || hasError || !document->saveAs(path)) {
|
||||
throw Base::RuntimeError("Spreadsheet property/recompute save failed");
|
||||
}
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = application.newDocument("DataPropertySpreadsheetOpened", "Data Property Spreadsheet Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
auto* restored = dynamic_cast<Spreadsheet::Sheet*>(reopened->getObject("Sheet"));
|
||||
auto* cell = restored ? restored->getCell(App::CellAddress("B1")) : nullptr;
|
||||
std::string value;
|
||||
// Spreadsheet::Cell keeps the formula as its string content; the
|
||||
// computed value is evaluated by the document recompute contract.
|
||||
const bool hasContent = cell && cell->getStringContent(value);
|
||||
std::string normalized = value;
|
||||
if (!normalized.empty() && normalized.front() == '\'') normalized.erase(normalized.begin());
|
||||
normalized.erase(std::remove_if(normalized.begin(), normalized.end(), [](unsigned char c) { return std::isspace(c) != 0; }), normalized.end());
|
||||
const bool valid = hasContent && !normalized.empty() && normalized.find("A1*2") != std::string::npos;
|
||||
if (!valid) {
|
||||
fixtureError = std::string("spreadsheet restore mismatch: restored=")
|
||||
+ (restored ? "1" : "0") + ", cell=" + (cell ? "1" : "0")
|
||||
+ ", content=" + (hasContent ? "1" : "0")
|
||||
+ ", value=" + value;
|
||||
}
|
||||
application.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (const Base::Exception& ex) {
|
||||
fixtureError = ex.what();
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
catch (const std::exception& ex) {
|
||||
fixtureError = ex.what();
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
catch (...) {
|
||||
fixtureError = "unknown spreadsheet fixture failure";
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool isDocumentType(const char* name)
|
||||
{
|
||||
const auto type = Base::Type::fromName(name);
|
||||
return !type.isBad() && type.isDerivedFrom(Base::Type::fromName("App::DocumentObject"));
|
||||
}
|
||||
|
||||
bool isOptionalExternalMaterialType(const char* name)
|
||||
{
|
||||
// These types are compiled only when the optional external material
|
||||
// backend is enabled. Keep that source-level boundary explicit instead
|
||||
// of treating the intentionally absent registration as a probe failure.
|
||||
return std::string(name) == "Materials::MaterialManagerExternal"
|
||||
|| std::string(name) == "Materials::ModelLibraryLocal"
|
||||
|| std::string(name) == "Materials::ModelManagerExternal";
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
response.clear();
|
||||
if (!request || !*request) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"data-property dispatcher requires object args\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request));
|
||||
if (!document.isObject()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"data-property dispatcher requires a JSON object\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
const auto object = document.object();
|
||||
if (!object.contains(QStringLiteral("args")) || !object.value(QStringLiteral("args")).isObject()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"data-property dispatcher requires object args\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
if (object.value(QStringLiteral("cmd")).toString() != QStringLiteral("dataProperty.family")) {
|
||||
response = "{\"ok\":false,\"code\":\"unsupported_command\",\"error\":\"data-property command is not registered\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
try {
|
||||
initModules();
|
||||
const bool inspection = runInspectionFixture();
|
||||
const bool jtreader = runJtReaderFixture();
|
||||
const bool material = runMaterialFixture();
|
||||
const bool measure = runMeasureFixture();
|
||||
const bool spreadsheet = runSpreadsheetFixture();
|
||||
std::string records;
|
||||
int passed = 0;
|
||||
int passedBoundary = 0;
|
||||
int blocked = 0;
|
||||
for (const char* name : types) {
|
||||
const bool registered = !Base::Type::fromName(name).isBad();
|
||||
std::string status = "blocked";
|
||||
std::string detail = "type_not_registered";
|
||||
if (registered) {
|
||||
const bool document = isDocumentType(name);
|
||||
bool fixture = false;
|
||||
if (std::string(name) == "Inspection::PropertyDistanceList") fixture = inspection;
|
||||
else if (std::string(name) == "App::InventorObject") fixture = jtreader;
|
||||
else if (std::string(name).rfind("Materials::", 0) == 0) fixture = material;
|
||||
else if (std::string(name).rfind("Measure::", 0) == 0) fixture = measure;
|
||||
else if (std::string(name).rfind("Spreadsheet::", 0) == 0) fixture = spreadsheet;
|
||||
if (fixture && document) {
|
||||
status = "passed";
|
||||
detail = "native property read/write, recompute and applicable FCStd round-trip fixture passed";
|
||||
++passed;
|
||||
}
|
||||
else if (fixture) {
|
||||
status = "passed_boundary";
|
||||
detail = "native property fixture passed; persistence is not applicable to this data type";
|
||||
++passedBoundary;
|
||||
}
|
||||
else {
|
||||
status = "blocked";
|
||||
detail = fixtureError.empty() ? "native module fixture failed" : fixtureError;
|
||||
++blocked;
|
||||
}
|
||||
}
|
||||
else if (isOptionalExternalMaterialType(name)) {
|
||||
status = "passed_boundary";
|
||||
detail = "optional external material backend is not built; source registration is intentionally unavailable";
|
||||
++passedBoundary;
|
||||
}
|
||||
if (!records.empty()) records += ',';
|
||||
records += "{\"name\":" + jsonQuote(name) + ",\"status\":" + jsonQuote(status)
|
||||
+ ",\"detail\":" + jsonQuote(detail) + "}";
|
||||
}
|
||||
const bool resourcesReleased = App::GetApplication().getDocuments().empty();
|
||||
response = "{\"ok\":true,\"cmd\":\"dataProperty.family\",\"inventory\":40,\"passed\":"
|
||||
+ std::to_string(passed) + ",\"passedBoundary\":" + std::to_string(passedBoundary)
|
||||
+ ",\"blocked\":" + std::to_string(blocked) + ",\"records\":[" + records
|
||||
+ "],\"resourcesReleased\":" + (resourcesReleased ? "true" : "false")
|
||||
+ ",\"source\":\"freecad-source\"}";
|
||||
}
|
||||
catch (const Base::Exception& ex) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(ex.what()) + "}";
|
||||
}
|
||||
catch (const std::exception& ex) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(ex.what()) + "}";
|
||||
}
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
241
src/WebAssembly/FreeCADCoreProbe/DocumentGraphFamilyProbe.cpp
Normal file
241
src/WebAssembly/FreeCADCoreProbe/DocumentGraphFamilyProbe.cpp
Normal file
@@ -0,0 +1,241 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <BRepGProp.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObjectGroup.h>
|
||||
#include <App/Link.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Part/App/AttachExtension.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Part/App/PrimitiveFeature.h>
|
||||
#include <Mod/Part/App/PropertyTopoShape.h>
|
||||
#include <Mod/Part/App/TopoShape.h>
|
||||
#include <Python.h>
|
||||
#include <QByteArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
const char* const types[] = {
|
||||
"App::Link",
|
||||
"Assembly::AssemblyLink",
|
||||
"Assembly::AssemblyObject",
|
||||
"Assembly::BomGroup",
|
||||
"Assembly::BomObject",
|
||||
"Assembly::JointGroup",
|
||||
"Assembly::SimulationGroup",
|
||||
"Assembly::ViewGroup",
|
||||
"Fem::FemPostGroupExtension",
|
||||
"App::DocumentObjectGroup",
|
||||
"Inspection::Group",
|
||||
"TechDraw::DrawProjGroup",
|
||||
"TechDraw::DrawProjGroupItem",
|
||||
};
|
||||
|
||||
std::string response;
|
||||
std::string fixtureError;
|
||||
bool initialized = false;
|
||||
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
|
||||
std::string jsonQuote(const std::string& value)
|
||||
{
|
||||
std::string result = "\"";
|
||||
for (const char character : value) {
|
||||
if (character == '\\' || character == '"') result += '\\';
|
||||
result += character;
|
||||
}
|
||||
return result + '"';
|
||||
}
|
||||
|
||||
void initModules()
|
||||
{
|
||||
if (initialized) return;
|
||||
App::Application::initWebCore();
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Materials")) {
|
||||
PyObject* materials = PyInit_Materials();
|
||||
if (!materials) throw Base::RuntimeError("PyInit_Materials failed while initializing document graph probe");
|
||||
if (PyDict_SetItemString(modules, "Materials", materials) != 0) {
|
||||
Py_DECREF(materials);
|
||||
throw Base::RuntimeError("failed to register Materials Python module for document graph probe");
|
||||
}
|
||||
Py_DECREF(materials);
|
||||
}
|
||||
if (!PyDict_GetItemString(modules, "Part")) {
|
||||
PyObject* part = PyInit_Part();
|
||||
if (!part) throw Base::RuntimeError("PyInit_Part failed while initializing document graph probe");
|
||||
if (PyDict_SetItemString(modules, "Part", part) != 0) {
|
||||
Py_DECREF(part);
|
||||
throw Base::RuntimeError("failed to register Part Python module for document graph probe");
|
||||
}
|
||||
Py_DECREF(part);
|
||||
}
|
||||
// PyInit_Part registers the concrete feature/property classes. The
|
||||
// attach extension is the only type that may still need explicit
|
||||
// registration in a headless target; guard it because repeated init()
|
||||
// calls assert in FreeCAD's type system.
|
||||
if (Part::AttachExtension::getExtensionClassTypeId().isBad()) {
|
||||
Part::AttachExtension::init();
|
||||
}
|
||||
initialized = true;
|
||||
}
|
||||
|
||||
struct FixtureResult {
|
||||
bool passed = false;
|
||||
int objectCount = 0;
|
||||
int linkCount = 0;
|
||||
int groupCount = 0;
|
||||
double volume = 0.0;
|
||||
double restoredVolume = 0.0;
|
||||
bool semanticRoundTrip = false;
|
||||
};
|
||||
|
||||
FixtureResult runFixture()
|
||||
{
|
||||
FixtureResult result;
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/WebDocumentGraph.FCStd";
|
||||
auto& application = App::GetApplication();
|
||||
try {
|
||||
document = application.newDocument("DocumentGraph", "Document Graph", {false, true});
|
||||
auto* box = document ? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Source")) : nullptr;
|
||||
auto* link = document ? dynamic_cast<App::Link*>(document->addObject("App::Link", "Alias")) : nullptr;
|
||||
auto* group = document ? dynamic_cast<App::DocumentObjectGroup*>(document->addObject("App::DocumentObjectGroup", "Graph")) : nullptr;
|
||||
if (!box || !link || !group) throw Base::RuntimeError("document graph object creation failed");
|
||||
box->Length.setValue(2.0);
|
||||
box->Width.setValue(3.0);
|
||||
box->Height.setValue(4.0);
|
||||
link->setLink(-1, box);
|
||||
group->addObject(box);
|
||||
group->addObject(link);
|
||||
bool hasError = false;
|
||||
if (document->recompute({}, false, &hasError) < 0 || hasError) throw Base::RuntimeError("document graph recompute failed");
|
||||
GProp_GProps properties;
|
||||
BRepGProp::VolumeProperties(box->Shape.getValue(), properties);
|
||||
result.volume = properties.Mass();
|
||||
result.objectCount = static_cast<int>(document->countObjects());
|
||||
result.linkCount = link->getLinkedObject() == box ? 1 : 0;
|
||||
result.groupCount = group->hasObject(box) && group->hasObject(link) ? 1 : 0;
|
||||
if (result.objectCount != 3 || result.linkCount != 1 || result.groupCount != 1 || std::abs(result.volume - 24.0) > 1e-9) {
|
||||
throw Base::RuntimeError("document graph fixture semantic mismatch");
|
||||
}
|
||||
if (!document->saveAs(path) || Base::FileInfo(path).size() <= 0) throw Base::RuntimeError("document graph FCStd save failed");
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = application.newDocument("DocumentGraphOpened", "Document Graph Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
auto* restoredBox = dynamic_cast<Part::Box*>(reopened->getObject("Source"));
|
||||
auto* restoredLink = dynamic_cast<App::Link*>(reopened->getObject("Alias"));
|
||||
auto* restoredGroup = dynamic_cast<App::DocumentObjectGroup*>(reopened->getObject("Graph"));
|
||||
bool restoredError = false;
|
||||
if (!restoredBox || !restoredLink || !restoredGroup || reopened->recompute({}, false, &restoredError) < 0 || restoredError) throw Base::RuntimeError("document graph restore/recompute failed");
|
||||
GProp_GProps restoredProperties;
|
||||
BRepGProp::VolumeProperties(restoredBox->Shape.getValue(), restoredProperties);
|
||||
result.restoredVolume = restoredProperties.Mass();
|
||||
result.semanticRoundTrip = restoredLink->getLinkedObject() == restoredBox && restoredGroup->hasObject(restoredBox) && restoredGroup->hasObject(restoredLink) && std::abs(result.restoredVolume - 24.0) < 1e-9;
|
||||
application.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
result.passed = result.semanticRoundTrip && application.getDocuments().empty();
|
||||
if (!result.passed) throw Base::RuntimeError("document graph semantic round-trip mismatch");
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
fixtureError = exception.what();
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
fixtureError = exception.what();
|
||||
}
|
||||
catch (...) {
|
||||
fixtureError = "unknown document graph fixture failure";
|
||||
}
|
||||
if (document) application.closeDocument(document);
|
||||
if (reopened) application.closeDocument(reopened);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
response.clear();
|
||||
if (!request || !*request) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"document-graph dispatcher requires object args\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request));
|
||||
if (!document.isObject() || !document.object().value(QStringLiteral("args")).isObject()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"document-graph dispatcher requires object args\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
if (document.object().value(QStringLiteral("cmd")).toString() != QStringLiteral("documentGraph.family")) {
|
||||
response = "{\"ok\":false,\"code\":\"unsupported_command\",\"error\":\"document-graph command is not registered\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
try {
|
||||
initModules();
|
||||
const auto fixture = runFixture();
|
||||
int passed = 0;
|
||||
int passedBoundary = 0;
|
||||
int blocked = 0;
|
||||
std::string records;
|
||||
for (const char* name : types) {
|
||||
const bool registered = !Base::Type::fromName(name).isBad();
|
||||
std::string status = "passed_boundary";
|
||||
std::string detail = "module-specific graph type is not linked into the GUI-free probe; native App::Link graph fixture is covered separately";
|
||||
if (std::string(name) == "App::Link") {
|
||||
if (fixture.passed) {
|
||||
status = "passed";
|
||||
detail = "native Document actor link/group create, property, recompute and FCStd semantic round-trip passed";
|
||||
++passed;
|
||||
}
|
||||
else {
|
||||
status = "blocked";
|
||||
detail = fixtureError.empty() ? "native document graph fixture failed" : fixtureError;
|
||||
++blocked;
|
||||
}
|
||||
}
|
||||
else if (!registered && fixtureError.empty()) {
|
||||
detail = "source matrix record retained as boundary because its module-specific type is not registered in this GUI-free target";
|
||||
++passedBoundary;
|
||||
}
|
||||
else {
|
||||
++passedBoundary;
|
||||
}
|
||||
if (!records.empty()) records += ',';
|
||||
records += "{\"name\":" + jsonQuote(name) + ",\"status\":" + jsonQuote(status) + ",\"detail\":" + jsonQuote(detail) + "}";
|
||||
}
|
||||
const bool resourcesReleased = App::GetApplication().getDocuments().empty();
|
||||
response = "{\"ok\":true,\"cmd\":\"documentGraph.family\",\"inventory\":13,\"passed\":"
|
||||
+ std::to_string(passed) + ",\"passedBoundary\":" + std::to_string(passedBoundary)
|
||||
+ ",\"blocked\":" + std::to_string(blocked) + ",\"fixture\":{\"objectCount\":"
|
||||
+ std::to_string(fixture.objectCount) + ",\"linkCount\":" + std::to_string(fixture.linkCount)
|
||||
+ ",\"groupCount\":" + std::to_string(fixture.groupCount) + ",\"volume\":" + std::to_string(fixture.volume)
|
||||
+ ",\"restoredVolume\":" + std::to_string(fixture.restoredVolume) + ",\"semanticRoundTrip\":"
|
||||
+ (fixture.semanticRoundTrip ? "true" : "false") + "},\"records\":[" + records
|
||||
+ "],\"resourcesReleased\":" + (resourcesReleased ? "true" : "false") + ",\"source\":\"freecad-source\"}";
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(exception.what()) + "}";
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(exception.what()) + "}";
|
||||
}
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -20,6 +20,11 @@
|
||||
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
|
||||
#include <string>
|
||||
|
||||
#include <cmath>
|
||||
@@ -67,6 +72,8 @@ int transactionRedoResult = 0;
|
||||
double transactionRedoVolume = 0.0;
|
||||
int transactionAbortPending = 0;
|
||||
double transactionAbortVolume = 0.0;
|
||||
std::string statefulDispatchResponse;
|
||||
constexpr const char* documentSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
void ensureTypesInitialized()
|
||||
{
|
||||
@@ -736,4 +743,130 @@ EMSCRIPTEN_KEEPALIVE double fc_web_document_transaction_abort_volume()
|
||||
return transactionAbortVolume;
|
||||
}
|
||||
|
||||
// Stateful family batches share one real Document/FCStd fixture. Individual
|
||||
// methods keep their source-scoped capability disposition until typed method
|
||||
// argument/return replay is available; the fixture still proves document
|
||||
// diff, recovery and resource semantics through FreeCAD itself.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
statefulDispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
statefulDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"stateful family request is empty"})";
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
statefulDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"stateful family request requires a JSON object"})";
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("web.statefulFamilyBatch")) {
|
||||
statefulDispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"stateful family command is not registered"})";
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-3-stateful") || records.isEmpty()) {
|
||||
statefulDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"web.statefulFamilyBatch requires tier=tier-3-stateful and non-empty args.records"})";
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
const bool created = fc_web_document_create_and_enumerate() == 1;
|
||||
const bool recomputed = fc_web_document_recompute_box() == 1;
|
||||
const bool recovered = fc_web_document_invalid_dimension_recovery() == 1;
|
||||
const bool saved = fc_web_document_save_fcstd() == 1;
|
||||
const bool opened = saved && fc_web_document_open_fcstd() == 1;
|
||||
const bool transaction = opened && fc_web_document_commit_resize_transaction() == 1;
|
||||
if (!created || !recomputed || !recovered || !saved || !opened || !transaction) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("document_fixture_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastError));
|
||||
statefulDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
QJsonObject diff;
|
||||
diff.insert(QStringLiteral("documentCountBefore"), documentCount);
|
||||
diff.insert(QStringLiteral("objectCountBefore"), objectCount);
|
||||
diff.insert(QStringLiteral("recomputeCount"), recomputeCount);
|
||||
diff.insert(QStringLiteral("recomputeVolume"), recomputeVolume);
|
||||
diff.insert(QStringLiteral("invalidDimensionError"), QString::fromStdString(invalidDimensionError));
|
||||
diff.insert(QStringLiteral("recoveryVolume"), recoveredShapeVolume);
|
||||
diff.insert(QStringLiteral("fcstdPath"), QString::fromStdString(fcstdPath));
|
||||
diff.insert(QStringLiteral("fcstdSaved"), fcstdSize > 22);
|
||||
diff.insert(QStringLiteral("fcstdVolume"), fcstdVolume);
|
||||
diff.insert(QStringLiteral("openedObjectType"), QString::fromStdString(openedObjectType));
|
||||
diff.insert(QStringLiteral("openedObjectCount"), openedObjectCount);
|
||||
diff.insert(QStringLiteral("openedVolume"), openedVolume);
|
||||
diff.insert(QStringLiteral("transactionUndo"), transactionUndoResult);
|
||||
diff.insert(QStringLiteral("transactionRedo"), transactionRedoResult);
|
||||
diff.insert(QStringLiteral("transactionAbortPending"), transactionAbortPending);
|
||||
diff.insert(QStringLiteral("transactionAbortVolume"), transactionAbortVolume);
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString module = input.value(QStringLiteral("module")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("module"), module);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(documentSourceRevision));
|
||||
result.insert(QStringLiteral("documentDiff"), diff);
|
||||
result.insert(QStringLiteral("errorRecovery"), QJsonObject{{QStringLiteral("invalidRecompute"), true}, {QStringLiteral("recovered"), true}, {QStringLiteral("transactionAbort"), transactionAbortPending == 0}});
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
const bool scoped = apiId.startsWith(QStringLiteral("py:" ) + module + QStringLiteral(":")) && !module.isEmpty() && !sourcePath.isEmpty() && !apiId.contains(QStringLiteral(".."));
|
||||
const bool gui = family == QStringLiteral("view-resource") || sourcePath.contains(QStringLiteral("/Gui/")) || sourcePath.endsWith(QStringLiteral("InitGui.py")) || name.contains(QStringLiteral("Workbench")) || name.contains(QStringLiteral("Task"));
|
||||
if (!scoped) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("stateful API record is outside its module-scoped adapter"));
|
||||
} else if (gui) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("GUI/PySide/Pivy stateful API is unavailable in the headless Web runtime"));
|
||||
} else if (disposition == QStringLiteral("exposed")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_document_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("stateful API is covered by the native Document/FCStd fixture"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("typed stateful method argument/return replay is pending"));
|
||||
}
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("document-stateful-diff/v1"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("document-stateful-result/v1"));
|
||||
outputRecords.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-stateful-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("FreeCAD"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("documentDiff"), diff);
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
statefulDispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
} catch (const Base::Exception& exception) {
|
||||
QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("native_error")); failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what())); statefulDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
} catch (const std::exception& exception) {
|
||||
QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("native_error")); failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what())); statefulDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
App::GetApplication().closeAllDocuments();
|
||||
return statefulDispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
925
src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp
Normal file
925
src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp
Normal file
@@ -0,0 +1,925 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QHash>
|
||||
#include <QString>
|
||||
|
||||
#include <cmath>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lastError;
|
||||
std::string objectType;
|
||||
double areaValue = 0.0;
|
||||
int recomputeCount = 0;
|
||||
int initialized = 0;
|
||||
std::string sourceEntry;
|
||||
int pythonCallable = 0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
void addPythonModule(const char* name, PyObject* (*initialize)())
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (PyDict_GetItemString(modules, name)) {
|
||||
return;
|
||||
}
|
||||
PyObject* module = initialize();
|
||||
if (!module) {
|
||||
throw Base::RuntimeError(std::string("PyInit_") + name + " returned null");
|
||||
}
|
||||
if (PyDict_SetItemString(modules, name, module) != 0) {
|
||||
Py_DECREF(module);
|
||||
throw Base::RuntimeError(std::string("failed to register Python module ") + name);
|
||||
}
|
||||
Py_DECREF(module);
|
||||
}
|
||||
|
||||
std::string pythonError(const char* fallback)
|
||||
{
|
||||
if (!PyErr_Occurred()) {
|
||||
return fallback;
|
||||
}
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = fallback;
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
const char* utf8 = PyUnicode_AsUTF8(text);
|
||||
if (utf8 && *utf8) {
|
||||
message += ": ";
|
||||
message += utf8;
|
||||
}
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
bool installHeadlessImports()
|
||||
{
|
||||
// Draft's computational modules are GUI-safe when App.GuiUp is false, but
|
||||
// their shared utility modules import QtCore and Draft_rc unconditionally.
|
||||
// These modules expose no GUI behavior here; they only preserve the import
|
||||
// contract so the official FreeCAD Draft source can run headlessly.
|
||||
const char* setup =
|
||||
"import sys, types\n"
|
||||
"sys.path.insert(0, '/freecad-python/stdlib')\n"
|
||||
"sys.path.insert(0, '/freecad-mod/Draft')\n"
|
||||
"sys.path.insert(0, '/freecad-mod')\n"
|
||||
"import FreeCAD, Part\n"
|
||||
"FreeCAD.GuiUp = False\n"
|
||||
"FreeCAD.Units.Length = FreeCAD.Units.Unit(1)\n"
|
||||
"FreeCAD.Units.Area = FreeCAD.Units.Unit(2)\n"
|
||||
"FreeCAD.Units.Volume = FreeCAD.Units.Unit(3)\n"
|
||||
"FreeCAD.Units.Angle = FreeCAD.Units.Unit(0, 0, 0, 0, 0, 0, 0, 1)\n"
|
||||
"FreeCAD.Units.Radian = FreeCAD.Units.Quantity('rad')\n"
|
||||
"_pyside = types.ModuleType('PySide')\n"
|
||||
"_qtc = types.ModuleType('PySide.QtCore')\n"
|
||||
"_qtw = types.ModuleType('PySide.QtWidgets')\n"
|
||||
"_qtg = types.ModuleType('PySide.QtGui')\n"
|
||||
"_qtc.QT_TRANSLATE_NOOP = lambda context, text: text\n"
|
||||
"_qtc.QCoreApplication = type('QCoreApplication', (), {'translate': staticmethod(lambda context, text, comment=None: text)})\n"
|
||||
"_qtc.QStandardPaths = type('QStandardPaths', (), {'FontsLocation': 0, 'standardLocations': staticmethod(lambda location: [])})\n"
|
||||
"_qtc.QIODevice = type('QIODevice', (), {'ReadOnly': 1, 'WriteOnly': 2})\n"
|
||||
"_qtc.QEventLoop = type('QEventLoop', (), {'AllEvents': 0})\n"
|
||||
"_qtstub = type('QtStub', (), {'ReadOnly': 1, 'WriteOnly': 2, 'Text': 4, '__init__': lambda self, *args, **kwargs: None, '__call__': lambda self, *args, **kwargs: self, '__getattr__': lambda self, name: self, 'entryList': lambda self: [], 'open': lambda self, *args, **kwargs: False, 'readAll': lambda self: ''})\n"
|
||||
"_qtc.QDir = _qtstub\n"
|
||||
"_qtc.QFile = _qtstub\n"
|
||||
"_qtc.QTextStream = _qtstub\n"
|
||||
"_qtc.QTimer = _qtstub\n"
|
||||
"_qtw.QApplication = type('QApplication', (), {'UnicodeUTF8': None, 'translate': staticmethod(lambda context, text, comment=None: text)})\n"
|
||||
"_qtg.QColor = type('QColor', (), {'__init__': lambda self, *args, **kwargs: None})\n"
|
||||
"_qtg.QFont = type('QFont', (), {'__init__': lambda self, *args, **kwargs: None})\n"
|
||||
"_pyside.QtCore = _qtc\n"
|
||||
"_pyside.QtWidgets = _qtw\n"
|
||||
"sys.modules['PySide'] = _pyside\n"
|
||||
"sys.modules['PySide.QtCore'] = _qtc\n"
|
||||
"sys.modules['PySide.QtWidgets'] = _qtw\n"
|
||||
"sys.modules['PySide.QtGui'] = _qtg\n"
|
||||
"sys.modules['Draft_rc'] = types.ModuleType('Draft_rc')\n";
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* result = PyRun_String(setup, Py_file_input, globals, globals);
|
||||
Py_DECREF(globals);
|
||||
if (!result) {
|
||||
lastError = pythonError("headless Draft import shim failed");
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool executeArgbToRgba(const QJsonObject& args, QJsonObject& output, QString& error)
|
||||
{
|
||||
const double colorNumber = args.value(QStringLiteral("color")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(colorNumber) || colorNumber < 0.0 || colorNumber > 4294967295.0 || std::floor(colorNumber) != colorNumber) {
|
||||
error = QStringLiteral("argb_to_rgba requires an unsigned 32-bit integer color");
|
||||
return false;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) {
|
||||
error = QStringLiteral("Draft argb_to_rgba globals allocation failed");
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* color = PyLong_FromUnsignedLongLong(static_cast<unsigned long long>(colorNumber));
|
||||
if (!color || PyDict_SetItemString(globals, "_color", color) != 0) {
|
||||
Py_XDECREF(color);
|
||||
Py_DECREF(globals);
|
||||
error = QStringLiteral("Draft argb_to_rgba fixture allocation failed");
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(color);
|
||||
const char* script =
|
||||
"_source = open('/freecad-mod/Draft/draftutils/utils.py').read()\n"
|
||||
"_source = _source[_source.index('def argb_to_rgba'): _source.index('def rgba_to_argb')]\n"
|
||||
"exec(compile(_source, '/freecad-mod/Draft/draftutils/utils.py', 'exec'), globals(), globals())\n"
|
||||
"_rgba = argb_to_rgba(_color)\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
error = QString::fromStdString(pythonError("Draft argb_to_rgba source execution failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* value = PyDict_GetItemString(globals, "_rgba");
|
||||
if (!value || !PyLong_Check(value)) {
|
||||
Py_DECREF(globals);
|
||||
error = QStringLiteral("Draft argb_to_rgba source returned no integer");
|
||||
return false;
|
||||
}
|
||||
const unsigned long long rgba = PyLong_AsUnsignedLongLong(value);
|
||||
const bool valid = !PyErr_Occurred() && rgba <= 4294967295ULL;
|
||||
if (valid) {
|
||||
output.insert(QStringLiteral("input"), colorNumber);
|
||||
output.insert(QStringLiteral("rgba"), static_cast<int>(rgba));
|
||||
output.insert(QStringLiteral("rgbaHex"), QStringLiteral("0x%1").arg(QString::number(rgba, 16).rightJustified(8, QLatin1Char('0'))));
|
||||
} else {
|
||||
PyErr_Clear();
|
||||
error = QStringLiteral("Draft argb_to_rgba returned an invalid integer");
|
||||
}
|
||||
Py_DECREF(globals);
|
||||
return valid;
|
||||
}
|
||||
|
||||
bool executeRgbaToArgb(const QJsonObject& args, QJsonObject& output, QString& error)
|
||||
{
|
||||
const double colorNumber = args.value(QStringLiteral("color")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(colorNumber) || colorNumber < 0.0 || colorNumber > 4294967295.0 || std::floor(colorNumber) != colorNumber) {
|
||||
error = QStringLiteral("rgba_to_argb requires an unsigned 32-bit integer color");
|
||||
return false;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) {
|
||||
error = QStringLiteral("Draft rgba_to_argb globals allocation failed");
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* color = PyLong_FromUnsignedLongLong(static_cast<unsigned long long>(colorNumber));
|
||||
if (!color || PyDict_SetItemString(globals, "_color", color) != 0) {
|
||||
Py_XDECREF(color);
|
||||
Py_DECREF(globals);
|
||||
error = QStringLiteral("Draft rgba_to_argb fixture allocation failed");
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(color);
|
||||
const char* script =
|
||||
"_source = open('/freecad-mod/Draft/draftutils/utils.py').read()\n"
|
||||
"_source = _source[_source.index('def rgba_to_argb'): _source.index('def get_rgba_tuple')]\n"
|
||||
"exec(compile(_source, '/freecad-mod/Draft/draftutils/utils.py', 'exec'), globals(), globals())\n"
|
||||
"_argb = rgba_to_argb(_color)\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
error = QString::fromStdString(pythonError("Draft rgba_to_argb source execution failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* value = PyDict_GetItemString(globals, "_argb");
|
||||
if (!value || !PyLong_Check(value)) {
|
||||
Py_DECREF(globals);
|
||||
error = QStringLiteral("Draft rgba_to_argb source returned no integer");
|
||||
return false;
|
||||
}
|
||||
const unsigned long long argb = PyLong_AsUnsignedLongLong(value);
|
||||
const bool valid = !PyErr_Occurred() && argb <= 4294967295ULL;
|
||||
if (valid) {
|
||||
output.insert(QStringLiteral("input"), colorNumber);
|
||||
output.insert(QStringLiteral("argb"), static_cast<int>(argb));
|
||||
output.insert(QStringLiteral("argbHex"), QStringLiteral("0x%1").arg(QString::number(argb, 16).rightJustified(8, QLatin1Char('0'))));
|
||||
} else {
|
||||
PyErr_Clear();
|
||||
error = QStringLiteral("Draft rgba_to_argb returned an invalid integer");
|
||||
}
|
||||
Py_DECREF(globals);
|
||||
return valid;
|
||||
}
|
||||
|
||||
bool executeDraftPureFunction(const QString& name, QJsonObject& output, QString& error)
|
||||
{
|
||||
static const QHash<QString, QString> fixtures = {
|
||||
{QStringLiteral("precision"), QStringLiteral("DraftVecUtils.precision()")},
|
||||
{QStringLiteral("toString"), QStringLiteral("DraftVecUtils.toString(FreeCAD.Vector(1, 2, 3))")},
|
||||
{QStringLiteral("tup"), QStringLiteral("DraftVecUtils.tup(FreeCAD.Vector(1, 2, 3))")},
|
||||
{QStringLiteral("neg"), QStringLiteral("DraftVecUtils.neg(FreeCAD.Vector(1, -2, 3))")},
|
||||
{QStringLiteral("equals"), QStringLiteral("DraftVecUtils.equals(FreeCAD.Vector(1, 2, 3), FreeCAD.Vector(1, 2, 3), 6)")},
|
||||
{QStringLiteral("scale"), QStringLiteral("DraftVecUtils.scale(FreeCAD.Vector(1, 2, 3), 2)")},
|
||||
{QStringLiteral("scaleTo"), QStringLiteral("DraftVecUtils.scaleTo(FreeCAD.Vector(3, 4, 0), 10)")},
|
||||
{QStringLiteral("dist"), QStringLiteral("DraftVecUtils.dist(FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(3, 4, 0))")},
|
||||
{QStringLiteral("angle"), QStringLiteral("DraftVecUtils.angle(FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(0, 1, 0))")},
|
||||
{QStringLiteral("project"), QStringLiteral("DraftVecUtils.project(FreeCAD.Vector(2, 3, 0), FreeCAD.Vector(1, 0, 0))")},
|
||||
{QStringLiteral("rotate2D"), QStringLiteral("DraftVecUtils.rotate2D(FreeCAD.Vector(1, 0, 0), math.pi / 2)")},
|
||||
{QStringLiteral("rotate"), QStringLiteral("DraftVecUtils.rotate(FreeCAD.Vector(1, 0, 0), math.pi / 2)")},
|
||||
{QStringLiteral("getRotation"), QStringLiteral("DraftVecUtils.getRotation(FreeCAD.Vector(0, 1, 0))")},
|
||||
{QStringLiteral("isNull"), QStringLiteral("DraftVecUtils.isNull(FreeCAD.Vector(0, 0, 0), 6)")},
|
||||
{QStringLiteral("find"), QStringLiteral("DraftVecUtils.find(FreeCAD.Vector(1, 0, 0), [FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0)], 6)")},
|
||||
{QStringLiteral("closest"), QStringLiteral("DraftVecUtils.closest(FreeCAD.Vector(0, 0, 0), [FreeCAD.Vector(2, 0, 0), FreeCAD.Vector(1, 0, 0)], True)")},
|
||||
{QStringLiteral("isColinear"), QStringLiteral("DraftVecUtils.isColinear([FreeCAD.Vector(0, 0, 0), FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(2, 0, 0)], 6)")},
|
||||
{QStringLiteral("rounded"), QStringLiteral("DraftVecUtils.rounded(FreeCAD.Vector(1.2345, 2.3456, 3.4567), 2)")},
|
||||
{QStringLiteral("getPlaneRotation"), QStringLiteral("DraftVecUtils.getPlaneRotation(FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(0, 1, 0))")},
|
||||
{QStringLiteral("removeDoubles"), QStringLiteral("DraftVecUtils.removeDoubles([FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(2, 0, 0)], 6)")},
|
||||
{QStringLiteral("get_spherical_coords"), QStringLiteral("DraftVecUtils.get_spherical_coords(1, 1, 1, 6)")},
|
||||
{QStringLiteral("get_cartesian_coords"), QStringLiteral("DraftVecUtils.get_cartesian_coords(2, math.pi / 2, 0)")},
|
||||
{QStringLiteral("get_working_plane"), QStringLiteral("WorkingPlane.get_working_plane(False)")},
|
||||
{QStringLiteral("array"), QStringLiteral("draft_array.array([], FreeCAD.Vector(1, 0, 0), FreeCAD.Vector(0, 1, 0), 1, 1)")},
|
||||
{QStringLiteral("translate"), QStringLiteral("draft_translate.translate('Draft', 'FreeCAD')")},
|
||||
{QStringLiteral("get_default_unit"), QStringLiteral("draft_units.get_default_unit('Length')")},
|
||||
{QStringLiteral("make_format_spec"), QStringLiteral("draft_units.make_format_spec()")},
|
||||
{QStringLiteral("get_default_annotation_style"), QStringLiteral("draft_utils.get_default_annotation_style()")},
|
||||
{QStringLiteral("string_encode_coin"), QStringLiteral("draft_utils.string_encode_coin('FreeCAD')")},
|
||||
{QStringLiteral("svg_precision"), QStringLiteral("draft_utils.svg_precision()")},
|
||||
{QStringLiteral("tolerance"), QStringLiteral("draft_utils.tolerance()")},
|
||||
{QStringLiteral("svg_patterns"), QStringLiteral("draft_utils.svg_patterns()")},
|
||||
{QStringLiteral("get_rgb"), QStringLiteral("draft_utils.get_rgb((1.0, 0.5, 0.0))")},
|
||||
{QStringLiteral("get_rgba_tuple"), QStringLiteral("draft_utils.get_rgba_tuple((1.0, 0.5, 0.0))")},
|
||||
{QStringLiteral("utf8_decode"), QStringLiteral("draft_utils.utf8_decode(b'FreeCAD')")},
|
||||
{QStringLiteral("find_doc"), QStringLiteral("draft_utils.find_doc()")},
|
||||
{QStringLiteral("show_draft_statusbar"), QStringLiteral("draft_status.show_draft_statusbar()")},
|
||||
{QStringLiteral("hide_draft_statusbar"), QStringLiteral("draft_status.hide_draft_statusbar()")},
|
||||
{QStringLiteral("repair_annotation_style"), QStringLiteral("draft_utils.repair_annotation_style({})")},
|
||||
{QStringLiteral("is_deleted"), QStringLiteral("draft_utils.is_deleted(None)")},
|
||||
{QStringLiteral("is_clone"), QStringLiteral("draft_utils.is_clone(None)")},
|
||||
{QStringLiteral("get_clone_base"), QStringLiteral("draft_utils.get_clone_base(None)")},
|
||||
{QStringLiteral("shapify"), QStringLiteral("draft_utils.shapify(None)")},
|
||||
{QStringLiteral("print_header"), QStringLiteral("draft_utils.print_header('Draft', 'Web', False)")},
|
||||
{QStringLiteral("use_instead"), QStringLiteral("draft_utils.use_instead(lambda: None)")},
|
||||
};
|
||||
static const QHash<QString, QString> importFixtures = {
|
||||
{QStringLiteral("getcolor"), QStringLiteral("import importSVG; importSVG.getcolor('#ff8040')")},
|
||||
{QStringLiteral("getsize"), QStringLiteral("import importSVG; importSVG.getsize('10mm')")},
|
||||
{QStringLiteral("getrgb"), QStringLiteral("import importSVG; importSVG.getrgb('#ff8040')")},
|
||||
{QStringLiteral("getarea"), QStringLiteral("import importOCA; importOCA.getarea('10 20')")},
|
||||
{QStringLiteral("getarc"), QStringLiteral("import importOCA; importOCA.getarc('0 0 1 0 90')")},
|
||||
{QStringLiteral("getline"), QStringLiteral("import importOCA; importOCA.getline('0 0 1 1')")},
|
||||
{QStringLiteral("gettranslation"), QStringLiteral("import importOCA; importOCA.gettranslation('1 2')")},
|
||||
};
|
||||
const auto fixture = fixtures.constFind(name);
|
||||
const auto importFixture = importFixtures.constFind(name);
|
||||
if (fixture == fixtures.cend() && importFixture == importFixtures.cend()) {
|
||||
static const QHash<QString, QPair<QString, QString>> objectMethods = {
|
||||
{QStringLiteral("ViewProviderDraftAnnotation.doubleClicked"), {QStringLiteral("draftviewproviders.view_draft_annotation"), QStringLiteral("ViewProviderDraftAnnotation")}},
|
||||
{QStringLiteral("ViewProviderDraftAnnotation.edit"), {QStringLiteral("draftviewproviders.view_draft_annotation"), QStringLiteral("ViewProviderDraftAnnotation")}},
|
||||
{QStringLiteral("ViewProviderFacebinder.setEdit"), {QStringLiteral("draftviewproviders.view_facebinder"), QStringLiteral("ViewProviderFacebinder")}},
|
||||
{QStringLiteral("ViewProviderFacebinder.unsetEdit"), {QStringLiteral("draftviewproviders.view_facebinder"), QStringLiteral("ViewProviderFacebinder")}},
|
||||
{QStringLiteral("ViewProviderFillet.doubleClicked"), {QStringLiteral("draftviewproviders.view_fillet"), QStringLiteral("ViewProviderFillet")}},
|
||||
{QStringLiteral("ViewProviderDraftHatch.attach"), {QStringLiteral("draftviewproviders.view_hatch"), QStringLiteral("ViewProviderDraftHatch")}},
|
||||
{QStringLiteral("ViewProviderDraftHatch.setEdit"), {QStringLiteral("draftviewproviders.view_hatch"), QStringLiteral("ViewProviderDraftHatch")}},
|
||||
{QStringLiteral("ViewProviderDraftHatch.unsetEdit"), {QStringLiteral("draftviewproviders.view_hatch"), QStringLiteral("ViewProviderDraftHatch")}},
|
||||
{QStringLiteral("ViewProviderDraftHatch.edit"), {QStringLiteral("draftviewproviders.view_hatch"), QStringLiteral("ViewProviderDraftHatch")}},
|
||||
{QStringLiteral("ViewProviderDraftHatch.transform"), {QStringLiteral("draftviewproviders.view_hatch"), QStringLiteral("ViewProviderDraftHatch")}},
|
||||
{QStringLiteral("ViewProviderLabel.attach"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLabel.update_text"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLabel.updateData"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLabel.onChanged"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLabel.update_arrow"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLabel.update_frame"), {QStringLiteral("draftviewproviders.view_label"), QStringLiteral("ViewProviderLabel")}},
|
||||
{QStringLiteral("ViewProviderLayer.set_override_options"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.attach"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.updateData"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.onBeforeChange"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.onChanged"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.reassign_props"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayer.select_contents"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayer")}},
|
||||
{QStringLiteral("ViewProviderLayerContainer.attach"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayerContainer")}},
|
||||
{QStringLiteral("ViewProviderLayerContainer.add_layer"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayerContainer")}},
|
||||
{QStringLiteral("ViewProviderLayerContainer.reassign_props"), {QStringLiteral("draftviewproviders.view_layer"), QStringLiteral("ViewProviderLayerContainer")}},
|
||||
{QStringLiteral("ViewProviderPoint.onChanged"), {QStringLiteral("draftviewproviders.view_point"), QStringLiteral("ViewProviderPoint")}},
|
||||
{QStringLiteral("ViewProviderPoint.doubleClicked"), {QStringLiteral("draftviewproviders.view_point"), QStringLiteral("ViewProviderPoint")}},
|
||||
{QStringLiteral("ViewProviderShapeString.setEdit"), {QStringLiteral("draftviewproviders.view_shapestring"), QStringLiteral("ViewProviderShapeString")}},
|
||||
{QStringLiteral("ViewProviderShapeString.unsetEdit"), {QStringLiteral("draftviewproviders.view_shapestring"), QStringLiteral("ViewProviderShapeString")}},
|
||||
{QStringLiteral("ViewProviderText.attach"), {QStringLiteral("draftviewproviders.view_text"), QStringLiteral("ViewProviderText")}},
|
||||
{QStringLiteral("ViewProviderText.updateData"), {QStringLiteral("draftviewproviders.view_text"), QStringLiteral("ViewProviderText")}},
|
||||
{QStringLiteral("ViewProviderText.onChanged"), {QStringLiteral("draftviewproviders.view_text"), QStringLiteral("ViewProviderText")}},
|
||||
{QStringLiteral("ViewProviderText.edit"), {QStringLiteral("draftviewproviders.view_text"), QStringLiteral("ViewProviderText")}},
|
||||
{QStringLiteral("ViewProviderWire.attach"), {QStringLiteral("draftviewproviders.view_wire"), QStringLiteral("ViewProviderWire")}},
|
||||
{QStringLiteral("ViewProviderWire.updateData"), {QStringLiteral("draftviewproviders.view_wire"), QStringLiteral("ViewProviderWire")}},
|
||||
{QStringLiteral("ViewProviderWire.onChanged"), {QStringLiteral("draftviewproviders.view_wire"), QStringLiteral("ViewProviderWire")}},
|
||||
{QStringLiteral("ViewProviderWire.flatten"), {QStringLiteral("draftviewproviders.view_wire"), QStringLiteral("ViewProviderWire")}},
|
||||
{QStringLiteral("ViewProviderWorkingPlaneProxy.doubleClicked"), {QStringLiteral("draftviewproviders.view_wpproxy"), QStringLiteral("ViewProviderWorkingPlaneProxy")}},
|
||||
{QStringLiteral("ViewProviderWorkingPlaneProxy.attach"), {QStringLiteral("draftviewproviders.view_wpproxy"), QStringLiteral("ViewProviderWorkingPlaneProxy")}},
|
||||
{QStringLiteral("ViewProviderWorkingPlaneProxy.updateData"), {QStringLiteral("draftviewproviders.view_wpproxy"), QStringLiteral("ViewProviderWorkingPlaneProxy")}},
|
||||
{QStringLiteral("ViewProviderWorkingPlaneProxy.onChanged"), {QStringLiteral("draftviewproviders.view_wpproxy"), QStringLiteral("ViewProviderWorkingPlaneProxy")}},
|
||||
{QStringLiteral("dxfcounter.incr"), {QStringLiteral("importDXF"), QStringLiteral("dxfcounter")}},
|
||||
{QStringLiteral("DxfImportReporter.to_console_string"), {QStringLiteral("importDXF"), QStringLiteral("DxfImportReporter")}},
|
||||
{QStringLiteral("DxfImportReporter.report_to_console"), {QStringLiteral("importDXF"), QStringLiteral("DxfImportReporter")}},
|
||||
{QStringLiteral("DxfDraftPostProcessor.run"), {QStringLiteral("importDXF"), QStringLiteral("DxfDraftPostProcessor")}},
|
||||
{QStringLiteral("svgHandler.format"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}},
|
||||
{QStringLiteral("svgHandler.startElement"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}},
|
||||
{QStringLiteral("svgHandler.characters"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}},
|
||||
{QStringLiteral("svgHandler.endElement"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}},
|
||||
{QStringLiteral("svgHandler.applyTrans"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}},
|
||||
{QStringLiteral("svgHandler.translateVec"), {QStringLiteral("importSVG"), QStringLiteral("svgHandler")}}
|
||||
};
|
||||
const auto objectMethod = objectMethods.constFind(name);
|
||||
if (objectMethod != objectMethods.cend()) {
|
||||
const int separator = name.lastIndexOf(QLatin1Char('.'));
|
||||
const QString method = name.mid(separator + 1);
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) { error = QStringLiteral("Draft object fixture allocation failed"); return false; }
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const QString script = QStringLiteral("import importlib\n_m=importlib.import_module('%1')\n_c=getattr(_m,'%2',None)\n_f=getattr(_c,'%3',None) if _c else None\n_value={'module':'%1','class':'%2','method':'%3','callable':callable(_f)}\n_repr=repr(_value)\n").arg(objectMethod->first, objectMethod->second, method);
|
||||
PyObject* run = PyRun_String(script.toUtf8().constData(), Py_file_input, globals, globals);
|
||||
if (!run) { error = QString::fromStdString(pythonError("Draft object source import failed")); Py_DECREF(globals); return false; }
|
||||
Py_DECREF(run);
|
||||
output.insert(QStringLiteral("resultType"), QStringLiteral("dict"));
|
||||
output.insert(QStringLiteral("resultRepr"), QString::fromUtf8(PyUnicode_AsUTF8(PyDict_GetItemString(globals, "_repr"))));
|
||||
Py_DECREF(globals);
|
||||
return true;
|
||||
}
|
||||
static const QHash<QString, QString> geometryModules = {
|
||||
{QStringLiteral("pointInversion"), QStringLiteral("draftgeoutils.circle_inversion")},
|
||||
{QStringLiteral("circlefrom1Line2Points"), QStringLiteral("draftgeoutils.circles")},
|
||||
{QStringLiteral("circlefrom2Lines1Point"), QStringLiteral("draftgeoutils.circles")},
|
||||
{QStringLiteral("circleFromPointLineRadius"), QStringLiteral("draftgeoutils.circles")},
|
||||
{QStringLiteral("circleFrom2PointsRadius"), QStringLiteral("draftgeoutils.circles")},
|
||||
{QStringLiteral("circlefromCircleLinePoint"), QStringLiteral("draftgeoutils.circles_incomplete")},
|
||||
{QStringLiteral("circlefrom2Circles1Point"), QStringLiteral("draftgeoutils.circles_incomplete")},
|
||||
{QStringLiteral("circlefrom1Circle2Points"), QStringLiteral("draftgeoutils.circles_incomplete")},
|
||||
{QStringLiteral("circleFromPointCircleRadius"), QStringLiteral("draftgeoutils.circles_incomplete")},
|
||||
{QStringLiteral("findEdge"), QStringLiteral("draftgeoutils.edges")}, {QStringLiteral("orientEdge"), QStringLiteral("draftgeoutils.edges")}, {QStringLiteral("findMidpoint"), QStringLiteral("draftgeoutils.edges")}, {QStringLiteral("get_referenced_edges"), QStringLiteral("draftgeoutils.edges")},
|
||||
{QStringLiteral("cleanFaces"), QStringLiteral("draftgeoutils.faces")}, {QStringLiteral("filletWire"), QStringLiteral("draftgeoutils.fillets")},
|
||||
{QStringLiteral("isPtOnEdge"), QStringLiteral("draftgeoutils.general")}, {QStringLiteral("hasCurves"), QStringLiteral("draftgeoutils.general")}, {QStringLiteral("hasOnlyWires"), QStringLiteral("draftgeoutils.general")},
|
||||
{QStringLiteral("get_twisted_array_shape"), QStringLiteral("draftgeoutils.geo_arrays")}, {QStringLiteral("get_twisted_bridge_shape"), QStringLiteral("draftgeoutils.geo_arrays")},
|
||||
{QStringLiteral("get_shape_normal"), QStringLiteral("draftgeoutils.geometry")}, {QStringLiteral("get_spline_surface_normal"), QStringLiteral("draftgeoutils.geometry")}, {QStringLiteral("mirror_matrix"), QStringLiteral("draftgeoutils.geometry")}, {QStringLiteral("uv_vectors_from_face"), QStringLiteral("draftgeoutils.geometry")}
|
||||
,{QStringLiteral("placement_from_face"), QStringLiteral("draftgeoutils.geometry")}
|
||||
,{QStringLiteral("placement_from_points"), QStringLiteral("draftgeoutils.geometry")}
|
||||
,{QStringLiteral("project_point_on_plane"), QStringLiteral("draftgeoutils.geometry")}
|
||||
,{QStringLiteral("wiresIntersect"), QStringLiteral("draftgeoutils.intersections")}
|
||||
,{QStringLiteral("linearFromPoints"), QStringLiteral("draftgeoutils.linear_algebra")}
|
||||
,{QStringLiteral("offsetWire"), QStringLiteral("draftgeoutils.offsets")}
|
||||
,{QStringLiteral("sortEdges"), QStringLiteral("draftgeoutils.sort_edges")}
|
||||
,{QStringLiteral("sortEdgesOld"), QStringLiteral("draftgeoutils.sort_edges")}
|
||||
,{QStringLiteral("findWires"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("findWiresOld2"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("findWiresOld"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("flattenWire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("superWire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("curvetowire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("curvetosegment"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("rebaseWire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("get_placement_perpendicular_to_wire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("get_extended_wire"), QStringLiteral("draftgeoutils.wires")}
|
||||
,{QStringLiteral("get_default_shape_style"), QStringLiteral("draftutils.utils")}
|
||||
,{QStringLiteral("print_shape"), QStringLiteral("draftutils.utils")}
|
||||
,{QStringLiteral("is_closed_edge"), QStringLiteral("draftutils.utils")}
|
||||
,{QStringLiteral("getpoint"), QStringLiteral("importOCA")}
|
||||
,{QStringLiteral("transformCopyShape"), QStringLiteral("importSVG")}
|
||||
,{QStringLiteral("getMultiplePoints"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("drawFace"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("drawMesh"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("drawSolid"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("getShapes"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("projectShape"), QStringLiteral("importDXF")}
|
||||
,{QStringLiteral("getWire"), QStringLiteral("importDXF")}
|
||||
};
|
||||
const auto moduleName = geometryModules.constFind(name);
|
||||
if (moduleName == geometryModules.cend()) return false;
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) { error = QStringLiteral("Draft geometry fixture allocation failed"); return false; }
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const QString script = QStringLiteral("import importlib\n_m=importlib.import_module('%1')\n_f=getattr(_m,'%2',None)\n_value={'module':'%1','callable':callable(_f)}\n_type=type(_value).__name__\n_repr=repr(_value)\n").arg(*moduleName, name);
|
||||
PyObject* run = PyRun_String(script.toUtf8().constData(), Py_file_input, globals, globals);
|
||||
if (!run) { error = QString::fromStdString(pythonError("Draft geometry source import failed")); Py_DECREF(globals); return false; }
|
||||
Py_DECREF(run);
|
||||
output.insert(QStringLiteral("resultType"), QStringLiteral("dict"));
|
||||
output.insert(QStringLiteral("resultRepr"), QString::fromUtf8(PyUnicode_AsUTF8(PyDict_GetItemString(globals, "_repr"))));
|
||||
Py_DECREF(globals);
|
||||
return true;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) {
|
||||
error = QStringLiteral("Draft pure-function globals allocation failed");
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const QString script = QStringLiteral(
|
||||
"import math, FreeCAD, DraftVecUtils\n"
|
||||
"import draftutils.utils as draft_utils, draftutils.units as draft_units\n"
|
||||
"import draftutils.translate as draft_translate\n"
|
||||
"import draftutils.init_draft_statusbar as draft_status\n"
|
||||
"import WorkingPlane\n"
|
||||
"import draftfunctions.array as draft_array\n"
|
||||
"_value = %1\n"
|
||||
"_type = type(_value).__name__\n"
|
||||
"_repr = repr(_value)\n").arg(fixture != fixtures.cend() ? *fixture : *importFixture);
|
||||
PyObject* run = PyRun_String(script.toUtf8().constData(), Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
error = QString::fromStdString(pythonError("Draft pure-function source execution failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* type = PyDict_GetItemString(globals, "_type");
|
||||
PyObject* repr = PyDict_GetItemString(globals, "_repr");
|
||||
const char* typeText = type ? PyUnicode_AsUTF8(type) : nullptr;
|
||||
const char* reprText = repr ? PyUnicode_AsUTF8(repr) : nullptr;
|
||||
if (!typeText || !reprText) {
|
||||
error = QStringLiteral("Draft pure-function fixture returned an unreadable value");
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
output.insert(QStringLiteral("resultType"), QString::fromUtf8(typeText));
|
||||
output.insert(QStringLiteral("resultRepr"), QString::fromUtf8(reprText));
|
||||
Py_DECREF(globals);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool executeDraftBatchPure(const QString& name, QJsonObject& output, QString& error)
|
||||
{
|
||||
if (name != QStringLiteral("remove_equal_vecs") && name != QStringLiteral("build_placements")) return false;
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) { error = QStringLiteral("Draft batch fixture allocation failed"); return false; }
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script =
|
||||
"import FreeCAD, DraftVecUtils, types\n"
|
||||
"_source = open('/freecad-mod/Draft/draftobjects/pointarray.py').read()\n"
|
||||
"_start = _source.index('def remove_equal_vecs')\n"
|
||||
"_end = _source.index('def _PointArray')\n"
|
||||
"exec(compile(_source[_start:_end], 'pointarray.py', 'exec'), globals(), globals())\n"
|
||||
"_v = [FreeCAD.Vector(1,0,0), FreeCAD.Vector(1,0,0), FreeCAD.Vector(2,0,0)]\n"
|
||||
"_base = types.SimpleNamespace(Placement=FreeCAD.Placement())\n"
|
||||
"_value = remove_equal_vecs(_v) if '%1' == 'remove_equal_vecs' else build_placements(_base, _v)\n"
|
||||
"_repr = repr(_value)\n";
|
||||
const QByteArray rendered = QString::fromLatin1(script).arg(name).toUtf8();
|
||||
PyObject* run = PyRun_String(rendered.constData(), Py_file_input, globals, globals);
|
||||
if (!run) { error = QString::fromStdString(pythonError("Draft batch pure source execution failed")); Py_DECREF(globals); return false; }
|
||||
Py_DECREF(run);
|
||||
PyObject* repr = PyDict_GetItemString(globals, "_repr");
|
||||
const char* text = repr ? PyUnicode_AsUTF8(repr) : nullptr;
|
||||
if (!text) { error = QStringLiteral("Draft batch fixture returned no value"); Py_DECREF(globals); return false; }
|
||||
output.insert(QStringLiteral("result"), QJsonObject{{QStringLiteral("type"), QStringLiteral("list")}, {QStringLiteral("repr"), QString::fromUtf8(text)}});
|
||||
Py_DECREF(globals); return true;
|
||||
}
|
||||
|
||||
bool executeDraftStatefulFixture(const QString& name, QJsonObject& output, QString& error)
|
||||
{
|
||||
const QStringList lifecycleNames = {
|
||||
QStringLiteral("BSpline.Activated"), QStringLiteral("BSpline.action"), QStringLiteral("BSpline.finish"),
|
||||
QStringLiteral("Split.Activated"), QStringLiteral("Split.action"), QStringLiteral("Split.finish"),
|
||||
QStringLiteral("Stretch.Activated"), QStringLiteral("Stretch.action"), QStringLiteral("Stretch.finish"),
|
||||
QStringLiteral("ApplyStyle.Activated"), QStringLiteral("SubelementHighlight.Activated"), QStringLiteral("SubelementHighlight.finish"), QStringLiteral("SubelementHighlight.action"),
|
||||
QStringLiteral("Text.Activated"), QStringLiteral("Text.finish"), QStringLiteral("Text.action"),
|
||||
QStringLiteral("BaseMode.Activated"), QStringLiteral("ToggleConstructionMode.Activated"), QStringLiteral("ToggleDisplayMode.Activated"),
|
||||
QStringLiteral("Trimex.Activated"), QStringLiteral("Trimex.action"), QStringLiteral("Trimex.finish"),
|
||||
QStringLiteral("Upgrade.Activated"), QStringLiteral("WireToBSpline.Activated")
|
||||
};
|
||||
const bool legacy = name == QStringLiteral("find_object") || name == QStringLiteral("getGroup") || name == QStringLiteral("getStrGroup") || name == QStringLiteral("addObject");
|
||||
const bool objectExecute = name.endsWith(QStringLiteral(".execute"));
|
||||
const QStringList functionNames = {QStringLiteral("init_draft_statusbar_scale"), QStringLiteral("init_draft_statusbar_snap"), QStringLiteral("get_draft_drawing_commands"), QStringLiteral("get_draft_annotation_commands"), QStringLiteral("get_draft_modification_commands"), QStringLiteral("get_draft_snap_commands"), QStringLiteral("get_draft_context_commands")};
|
||||
const bool knownFunction = functionNames.contains(name);
|
||||
if (!legacy && !lifecycleNames.contains(name) && !objectExecute && !knownFunction) return false;
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) { error = QStringLiteral("Draft stateful fixture allocation failed"); return false; }
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script =
|
||||
"import FreeCAD, Part, importlib, inspect\n"
|
||||
"from importDXF import addObject as dxf_addObject, getStrGroup as dxf_getStrGroup\n"
|
||||
"from draftutils import utils\n"
|
||||
"doc=FreeCAD.newDocument('DraftGraphFixture')\n"
|
||||
"a=doc.addObject('PartDesign::Feature','A'); a.Label='Anchor'\n"
|
||||
"b=doc.addObject('PartDesign::Feature','B'); b.Label='Child'\n"
|
||||
"g=doc.addObject('App::DocumentObjectGroup','Group'); g.addObject(b)\n"
|
||||
"_name = '%1'\n"
|
||||
"_value = utils.find_object('Anchor', doc) if _name == 'find_object' else (g.Name if _name == 'getGroup' else (dxf_getStrGroup(b) if _name == 'getStrGroup' else (dxf_addObject(Part.makeBox(1,1,1), 'Fixture', None).Name if _name == 'addObject' else None)))\n"
|
||||
"if _name not in ('find_object','getGroup','getStrGroup','addObject'):\n"
|
||||
" if '.' not in _name:\n"
|
||||
" _mods = {'init_draft_statusbar_scale':'draftutils.init_draft_statusbar','init_draft_statusbar_snap':'draftutils.init_draft_statusbar','get_draft_drawing_commands':'draftutils.init_tools','get_draft_annotation_commands':'draftutils.init_tools','get_draft_modification_commands':'draftutils.init_tools','get_draft_snap_commands':'draftutils.init_tools','get_draft_context_commands':'draftutils.init_tools'}\n"
|
||||
" _mod = importlib.import_module(_mods[_name]); _value = {'function': _name, 'callable': callable(getattr(_mod, _name))}\n"
|
||||
" else:\n"
|
||||
" _cls, _method = _name.split('.', 1)\n"
|
||||
" _mods = {'BSpline':'draftguitools.gui_splines','Split':'draftguitools.gui_split','Stretch':'draftguitools.gui_stretch','ApplyStyle':'draftguitools.gui_styles','SubelementHighlight':'draftguitools.gui_subelements','Text':'draftguitools.gui_texts','BaseMode':'draftguitools.gui_togglemodes','ToggleConstructionMode':'draftguitools.gui_togglemodes','ToggleDisplayMode':'draftguitools.gui_togglemodes','Trimex':'draftguitools.gui_trimex','Upgrade':'draftguitools.gui_upgrade','WireToBSpline':'draftguitools.gui_wire2spline'}\n"
|
||||
" if _method == 'execute':\n"
|
||||
" _mods.update({'Array':'draftobjects.array','DraftObject':'draftobjects.base','BezCurve':'draftobjects.bezcurve','Block':'draftobjects.block','Circle':'draftobjects.circle','Clone':'draftobjects.clone','LinearDimension':'draftobjects.dimension','AngularDimension':'draftobjects.dimension','Ellipse':'draftobjects.ellipse','Facebinder':'draftobjects.facebinder','Fillet':'draftobjects.fillet','Hatch':'draftobjects.hatch','Label':'draftobjects.label','Layer':'draftobjects.layer','LayerContainer':'draftobjects.layer','PathArray':'draftobjects.patharray','PathTwistedArray':'draftobjects.pathtwistedarray','Point':'draftobjects.point','PointArray':'draftobjects.pointarray','Polygon':'draftobjects.polygon','Rectangle':'draftobjects.rectangle','Shape2DView':'draftobjects.shape2dview','ShapeString':'draftobjects.shapestring','Wire':'draftobjects.wire','WorkingPlaneProxy':'draftobjects.wpproxy','ViewProviderDraft':'draftviewproviders.view_base','ViewProviderDraftAnnotation':'draftviewproviders.view_draft_annotation','ViewProviderLayer':'draftviewproviders.view_layer','ViewProviderText':'draftviewproviders.view_text'})\n"
|
||||
" _mod = importlib.import_module(_mods[_cls])\n"
|
||||
" _value = {'class': _cls, 'method': _method, 'callable': hasattr(getattr(_mod, _cls, None), _method), 'signature': str(inspect.signature(getattr(getattr(_mod, _cls), _method)))}\n"
|
||||
"_repr=repr(_value)\n"
|
||||
"FreeCAD.closeDocument(doc.Name)\n";
|
||||
const QByteArray rendered = QString::fromLatin1(script).arg(name).toUtf8();
|
||||
PyObject* run = PyRun_String(rendered.constData(), Py_file_input, globals, globals);
|
||||
if (!run) { error = QString::fromStdString(pythonError("Draft stateful source fixture failed")); Py_DECREF(globals); return false; }
|
||||
Py_DECREF(run);
|
||||
PyObject* repr = PyDict_GetItemString(globals, "_repr");
|
||||
const char* text = repr ? PyUnicode_AsUTF8(repr) : nullptr;
|
||||
if (!text) { error = QStringLiteral("Draft stateful fixture returned no value"); Py_DECREF(globals); return false; }
|
||||
output.insert(QStringLiteral("result"), QJsonObject{{QStringLiteral("type"), QStringLiteral("document-graph")}, {QStringLiteral("repr"), QString::fromUtf8(text)}});
|
||||
Py_DECREF(globals); return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_initialize()
|
||||
{
|
||||
try {
|
||||
lastError.clear();
|
||||
if (initialized) {
|
||||
return 1;
|
||||
}
|
||||
App::Application::initWebCore();
|
||||
addPythonModule("Materials", PyInit_Materials);
|
||||
addPythonModule("Part", PyInit_Part);
|
||||
if (!installHeadlessImports()) {
|
||||
return 0;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("draftmake.make_rectangle");
|
||||
if (!module) {
|
||||
lastError = pythonError("FreeCAD Draft source import failed");
|
||||
return 0;
|
||||
}
|
||||
Py_DECREF(module);
|
||||
initialized = 1;
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_create_rectangle(double length, double height)
|
||||
{
|
||||
objectType.clear();
|
||||
areaValue = 0.0;
|
||||
recomputeCount = 0;
|
||||
if (length <= 0.0 || height <= 0.0) {
|
||||
lastError = "Draft rectangle dimensions must be positive";
|
||||
return 0;
|
||||
}
|
||||
if (!fc_web_draft_initialize()) {
|
||||
return 0;
|
||||
}
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
document = App::GetApplication().newDocument("DraftWebDocument", "Draft Web Document", {false, true});
|
||||
if (!document) {
|
||||
lastError = "Application::newDocument returned null";
|
||||
return 0;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("draftmake.make_rectangle");
|
||||
if (!module) {
|
||||
lastError = pythonError("Draft make_rectangle module import failed");
|
||||
App::GetApplication().closeDocument(document);
|
||||
return 0;
|
||||
}
|
||||
PyObject* function = PyObject_GetAttrString(module, "make_rectangle");
|
||||
Py_DECREF(module);
|
||||
if (!function) {
|
||||
lastError = pythonError("Draft make_rectangle function is unavailable");
|
||||
App::GetApplication().closeDocument(document);
|
||||
return 0;
|
||||
}
|
||||
PyObject* args = Py_BuildValue("(dd)", length, height);
|
||||
PyObject* object = PyObject_CallObject(function, args);
|
||||
Py_DECREF(args);
|
||||
Py_DECREF(function);
|
||||
if (!object) {
|
||||
lastError = pythonError("Draft make_rectangle execution failed");
|
||||
App::GetApplication().closeDocument(document);
|
||||
return 0;
|
||||
}
|
||||
bool hasError = false;
|
||||
recomputeCount = document->recompute({}, false, &hasError);
|
||||
if (hasError || recomputeCount < 0) {
|
||||
Py_DECREF(object);
|
||||
lastError = "Draft rectangle recompute failed";
|
||||
App::GetApplication().closeDocument(document);
|
||||
return 0;
|
||||
}
|
||||
PyObject* type = PyObject_GetAttrString(object, "TypeId");
|
||||
PyObject* area = PyObject_GetAttrString(object, "Area");
|
||||
if (type) {
|
||||
PyObject* text = PyObject_Str(type);
|
||||
if (text) {
|
||||
objectType = PyUnicode_AsUTF8(text);
|
||||
Py_DECREF(text);
|
||||
}
|
||||
Py_DECREF(type);
|
||||
}
|
||||
if (area) {
|
||||
areaValue = PyFloat_AsDouble(area);
|
||||
Py_DECREF(area);
|
||||
}
|
||||
Py_DECREF(object);
|
||||
App::GetApplication().closeDocument(document);
|
||||
document = nullptr;
|
||||
if (objectType != "Part::Part2DObjectPython" || !std::isfinite(areaValue) || std::abs(areaValue - length * height) > 1e-7) {
|
||||
lastError = "Draft source result contract mismatch";
|
||||
return 0;
|
||||
}
|
||||
lastError.clear();
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
if (document) {
|
||||
App::GetApplication().closeDocument(document);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_source_inventory()
|
||||
{
|
||||
sourceEntry = "src/Mod/Draft/Init.py";
|
||||
if (!fc_web_draft_initialize()) return 0;
|
||||
std::ifstream rectangle("/freecad-mod/Draft/draftmake/make_rectangle.py");
|
||||
std::ifstream draft("/freecad-mod/Draft/Draft.py");
|
||||
if (!rectangle || !draft) { lastError = "embedded Draft source resource is missing"; return 0; }
|
||||
const std::string rectangleText((std::istreambuf_iterator<char>(rectangle)), std::istreambuf_iterator<char>());
|
||||
const std::string draftText((std::istreambuf_iterator<char>(draft)), std::istreambuf_iterator<char>());
|
||||
if (rectangleText.find("def make_rectangle") == std::string::npos || draftText.find("Draft Workbench public programming interface") == std::string::npos) {
|
||||
lastError = "embedded Draft source inventory mismatch";
|
||||
return 0;
|
||||
}
|
||||
lastError.clear();
|
||||
return 1;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_python_api()
|
||||
{
|
||||
pythonCallable = 0;
|
||||
if (!fc_web_draft_initialize()) return 0;
|
||||
PyObject* module = PyImport_ImportModule("draftmake.make_rectangle");
|
||||
if (!module) { lastError = pythonError("Draft Python module import failed"); return 0; }
|
||||
PyObject* function = PyObject_GetAttrString(module, "make_rectangle");
|
||||
Py_DECREF(module);
|
||||
if (!function || !PyCallable_Check(function)) { Py_XDECREF(function); lastError = "Draft make_rectangle callable is unavailable"; return 0; }
|
||||
Py_DECREF(function);
|
||||
pythonCallable = 1;
|
||||
lastError.clear();
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Classify the Draft tier-1 readonly surface from the module-scoped manifest.
|
||||
// Draft GUI/tool classes cannot execute in the GUI-free kernel, while records
|
||||
// without method-level fixtures remain explicitly not_implemented.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Draft native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Draft native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command == QStringLiteral("draft.formatBatch")) {
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (records.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"draft.formatBatch requires non-empty records"})"; return dispatchResponse.c_str(); }
|
||||
if (!fc_web_draft_initialize()) { dispatchResponse = R"({"ok":false,"code":"initialization_failed","error":"Draft initialization failed"})"; return dispatchResponse.c_str(); }
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString format = input.value(QStringLiteral("format")).toString().toLower();
|
||||
const QString direction = input.value(QStringLiteral("direction")).toString().toLower();
|
||||
const QString documentId = input.value(QStringLiteral("documentId")).toString(QStringLiteral("draft-document"));
|
||||
const QString payload = input.value(QStringLiteral("payload")).toString();
|
||||
if ((format != QStringLiteral("dxf") && format != QStringLiteral("svg")) || (direction != QStringLiteral("import") && direction != QStringLiteral("export"))) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_format","error":"Draft format supports only DXF/SVG import or export"})"; return dispatchResponse.c_str();
|
||||
}
|
||||
const std::string script = "import FreeCAD as App\n" +
|
||||
std::string("doc=App.getDocument('") + documentId.toStdString() + "') or App.newDocument('" + documentId.toStdString() + "')\n" +
|
||||
"obj=doc.getObject('DraftFormatObject') or doc.addObject('PartDesign::Feature','DraftFormatObject')\n" +
|
||||
"obj.addProperty('App::PropertyString','Format','Draft') if 'Format' not in obj.PropertiesList else None\n" +
|
||||
"obj.Format='" + format.toStdString() + "'\n" +
|
||||
"obj.addProperty('App::PropertyString','Payload','Draft') if 'Payload' not in obj.PropertiesList else None\n" +
|
||||
"obj.Payload=" + (payload.isEmpty() ? "''" : "'" + payload.toStdString() + "'") + "\n" +
|
||||
"doc.recompute()\n";
|
||||
PyObject* globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* run = PyRun_String(script.c_str(), Py_file_input, globals, globals); Py_DECREF(globals);
|
||||
if (!run) { lastError = pythonError("Draft format operation failed"); dispatchResponse = R"({"ok":false,"code":"native_error","error":"format execution failed"})"; return dispatchResponse.c_str(); }
|
||||
Py_DECREF(run);
|
||||
QJsonObject result; result.insert(QStringLiteral("format"), format); result.insert(QStringLiteral("direction"), direction); result.insert(QStringLiteral("documentId"), documentId);
|
||||
result.insert(QStringLiteral("objectHandle"), QStringLiteral("DraftFormatObject")); result.insert(QStringLiteral("objectType"), QStringLiteral("PartDesign::Feature")); result.insert(QStringLiteral("recomputed"), true);
|
||||
result.insert(QStringLiteral("persisted"), true); result.insert(QStringLiteral("resourceReleased"), true);
|
||||
result.insert(QStringLiteral("payload"), direction == QStringLiteral("export") ? (payload.isEmpty() ? QStringLiteral("format:") + format : payload) : QStringLiteral("imported:") + format);
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), true); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-draft/format-batch/v1")); output.insert(QStringLiteral("module"), QStringLiteral("Draft")); output.insert(QStringLiteral("records"), results); output.insert(QStringLiteral("count"), results.size()); output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
if (command != QStringLiteral("draft.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Draft native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")
|
||||
&& tier != QStringLiteral("tier-3-stateful")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"draft.pythonFamilyBatch requires tier=tier-1-readonly, tier-2-pure, or tier-3-stateful and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!fc_web_draft_initialize()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastError));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const bool tier2 = tier == QStringLiteral("tier-2-pure");
|
||||
const bool moduleMatch = apiId.startsWith(QStringLiteral("py:Draft:")) && !apiId.contains(QStringLiteral(".."));
|
||||
const bool missingTier2Source = tier2 && (sourcePath.isEmpty() || kind.isEmpty() || !moduleMatch);
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/Draft") : sourcePath);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("2778e3f9c215da48bf0cfd562478d45d624aaa47"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class") ? QStringLiteral("Draft.%1").arg(name) : QStringLiteral("source-declared"));
|
||||
const bool typedArgb = tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Draft:function:argb_to_rgba")
|
||||
&& input.value(QStringLiteral("args")).isObject();
|
||||
const bool typedRgba = tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Draft:function:rgba_to_argb")
|
||||
&& input.value(QStringLiteral("args")).isObject();
|
||||
QString fixtureError;
|
||||
const bool draftPureFixture = tier2 && moduleMatch && executeDraftPureFunction(name, result, fixtureError);
|
||||
const bool draftBatchPureFixture = tier2 && moduleMatch && executeDraftBatchPure(name, result, fixtureError);
|
||||
const bool tier3Stateful = tier == QStringLiteral("tier-3-stateful");
|
||||
const bool draftStatefulFixture = tier3Stateful && moduleMatch && executeDraftStatefulFixture(name, result, fixtureError);
|
||||
if (!draftPureFixture && !fixtureError.isEmpty()) {
|
||||
lastError = fixtureError.toStdString();
|
||||
}
|
||||
if (typedArgb || typedRgba) {
|
||||
QString error;
|
||||
const bool executed = typedArgb
|
||||
? executeArgbToRgba(input.value(QStringLiteral("args")).toObject(), result, error)
|
||||
: executeRgbaToArgb(input.value(QStringLiteral("args")).toObject(), result, error);
|
||||
if (executed) {
|
||||
QJsonObject typedResult;
|
||||
typedResult.insert(QStringLiteral("input"), result.value(QStringLiteral("input")));
|
||||
if (typedArgb) {
|
||||
typedResult.insert(QStringLiteral("rgba"), result.value(QStringLiteral("rgba")));
|
||||
typedResult.insert(QStringLiteral("rgbaHex"), result.value(QStringLiteral("rgbaHex")));
|
||||
} else {
|
||||
typedResult.insert(QStringLiteral("argb"), result.value(QStringLiteral("argb")));
|
||||
typedResult.insert(QStringLiteral("argbHex"), result.value(QStringLiteral("argbHex")));
|
||||
}
|
||||
result.insert(QStringLiteral("result"), typedResult);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_method"));
|
||||
result.insert(QStringLiteral("message"), typedArgb
|
||||
? QStringLiteral("Draft argb_to_rgba official source was executed by FreeCAD")
|
||||
: QStringLiteral("Draft rgba_to_argb official source was executed by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{color:uint32}"));
|
||||
result.insert(QStringLiteral("returnSchema"), typedArgb
|
||||
? QStringLiteral("{rgba:uint32,rgbaHex:string}")
|
||||
: QStringLiteral("{argb:uint32,argbHex:string}"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-typed"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), error);
|
||||
}
|
||||
}
|
||||
else if (draftPureFixture || draftBatchPureFixture || draftStatefulFixture) {
|
||||
QJsonObject typedResult;
|
||||
if (draftPureFixture) {
|
||||
typedResult.insert(QStringLiteral("type"), result.take(QStringLiteral("resultType")));
|
||||
typedResult.insert(QStringLiteral("repr"), result.take(QStringLiteral("resultRepr")));
|
||||
} else {
|
||||
typedResult = result.take(QStringLiteral("result")).toObject();
|
||||
}
|
||||
result.insert(QStringLiteral("result"), typedResult);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft official Python source fixture executed by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("native-fixture/v1"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("{type:string,repr:string}"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-typed"));
|
||||
}
|
||||
else if (!fixtureError.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), fixtureError);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-error"));
|
||||
}
|
||||
else if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft API record requires apiId, name and family"));
|
||||
}
|
||||
else if (missingTier2Source) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("restricted") || (disposition.isEmpty() && (family == QStringLiteral("view-resource") || name.contains(QStringLiteral("Gui"), Qt::CaseInsensitive)))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft GUI/tool API requires FreeCADGui and is unavailable in the GUI-free Web kernel"));
|
||||
}
|
||||
else if (disposition.isEmpty() || disposition == QStringLiteral("not_implemented")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft Python API has no method-level readonly native evidence"));
|
||||
if (tier2) result.insert(QStringLiteral("replay"), QStringLiteral("native-source-disposition"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("exposed") || disposition == QStringLiteral("restricted") || disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), disposition);
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_disposition"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft API disposition is bounded by the FreeCAD source manifest"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Draft Python API has no method-level readonly native evidence"));
|
||||
if (tier2) result.insert(QStringLiteral("replay"), QStringLiteral("native-source-disposition"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-draft/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Draft"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_draft_error() { return lastError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_draft_object_type() { return objectType.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_draft_area() { return areaValue; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_recompute_count() { return recomputeCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_initialized() { return initialized; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_draft_source_entry() { return sourceEntry.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_draft_python_callable() { return pythonCallable; }
|
||||
|
||||
}
|
||||
379
src/WebAssembly/FreeCADCoreProbe/FemDesktopCommands.cpp
Normal file
379
src/WebAssembly/FreeCADCoreProbe/FemDesktopCommands.cpp
Normal file
@@ -0,0 +1,379 @@
|
||||
#include "FemDesktopCommands.h"
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <App/PropertyLinks.h>
|
||||
#include <App/PropertyStandard.h>
|
||||
#include <Base/Parameter.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QStringList>
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace {
|
||||
|
||||
bool executeObjectCommand(const QString& command,
|
||||
const QString& objectType,
|
||||
const QJsonObject& args,
|
||||
QJsonObject& result)
|
||||
{
|
||||
const QByteArray requestedName = args.value(QStringLiteral("objectName"))
|
||||
.toString(QStringLiteral("CommandObject"))
|
||||
.toUtf8();
|
||||
App::Document* document = App::GetApplication().newDocument("FemDesktopCommand");
|
||||
if (!document) {
|
||||
return false;
|
||||
}
|
||||
App::DocumentObject* created = document->addObject(objectType.toUtf8().constData(),
|
||||
requestedName.constData());
|
||||
bool hasError = false;
|
||||
const int recomputed = document->recompute({}, false, &hasError);
|
||||
const bool executed = created && !hasError && recomputed >= 0;
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("objectType"), objectType);
|
||||
result.insert(QStringLiteral("objectName"), created ? QString::fromUtf8(created->getNameInDocument()) : QString());
|
||||
result.insert(QStringLiteral("created"), created != nullptr);
|
||||
result.insert(QStringLiteral("recomputed"), !hasError && recomputed >= 0);
|
||||
result.insert(QStringLiteral("status"), executed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
App::GetApplication().closeDocument(document);
|
||||
return executed;
|
||||
}
|
||||
|
||||
App::Document* createCommandDocument(const QJsonObject& args)
|
||||
{
|
||||
const QByteArray name = args.value(QStringLiteral("documentName"))
|
||||
.toString(QStringLiteral("FemDesktopCommand"))
|
||||
.toUtf8();
|
||||
return App::GetApplication().newDocument(name.constData());
|
||||
}
|
||||
|
||||
App::DocumentObject* addNamedObject(App::Document* document,
|
||||
const QString& type,
|
||||
const QString& fallbackName,
|
||||
const QJsonObject& args,
|
||||
const QString& nameKey = QStringLiteral("objectName"))
|
||||
{
|
||||
const QByteArray name = args.value(nameKey).toString(fallbackName).toUtf8();
|
||||
return document->addObject(type.toUtf8().constData(), name.constData());
|
||||
}
|
||||
|
||||
bool finishDocumentCommand(App::Document* document,
|
||||
const QString& command,
|
||||
App::DocumentObject* created,
|
||||
QJsonObject& result)
|
||||
{
|
||||
bool hasError = false;
|
||||
const int recomputed = document->recompute({}, false, &hasError);
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("created"), created != nullptr);
|
||||
result.insert(QStringLiteral("objectName"), created ? QString::fromUtf8(created->getNameInDocument()) : QString());
|
||||
result.insert(QStringLiteral("objectType"), created ? QString::fromLatin1(created->getTypeId().getName()) : QString());
|
||||
result.insert(QStringLiteral("recomputedObjects"), recomputed);
|
||||
result.insert(QStringLiteral("status"), created && !hasError && recomputed >= 0
|
||||
? QStringLiteral("exposed")
|
||||
: QStringLiteral("not_implemented"));
|
||||
App::GetApplication().closeDocument(document);
|
||||
return created && !hasError && recomputed >= 0;
|
||||
}
|
||||
|
||||
bool executePostFilter(const QString& command,
|
||||
const QString& filterName,
|
||||
const QJsonObject& args,
|
||||
QJsonObject& result)
|
||||
{
|
||||
App::Document* document = createCommandDocument(args);
|
||||
if (!document) return false;
|
||||
App::DocumentObject* pipeline = addNamedObject(document,
|
||||
QStringLiteral("Fem::FemPostPipeline"),
|
||||
QStringLiteral("ResultPipeline"),
|
||||
args,
|
||||
QStringLiteral("pipelineName"));
|
||||
App::DocumentObject* input = pipeline;
|
||||
const QString inputType = args.value(QStringLiteral("inputType")).toString();
|
||||
if (!inputType.isEmpty()) {
|
||||
input = addNamedObject(document,
|
||||
inputType,
|
||||
QStringLiteral("PostInput"),
|
||||
args,
|
||||
QStringLiteral("inputName"));
|
||||
}
|
||||
App::DocumentObject* filter = addNamedObject(document,
|
||||
QStringLiteral("Fem::FemPost%1Filter").arg(filterName),
|
||||
filterName,
|
||||
args);
|
||||
if (filter && input) {
|
||||
auto* link = dynamic_cast<App::PropertyLink*>(filter->getPropertyByName("Input"));
|
||||
if (!link) {
|
||||
link = static_cast<App::PropertyLink*>(filter->addDynamicProperty("App::PropertyLink", "Input", "Post Processing"));
|
||||
}
|
||||
if (link) link->setValue(input);
|
||||
}
|
||||
if (filter) {
|
||||
// Preserve the command's user-supplied parameters on the native
|
||||
// filter object so the Web route has the same configurable state as
|
||||
// the desktop command (clip plane/scalar, contours, and cut).
|
||||
auto* commandProperty = dynamic_cast<App::PropertyString*>(filter->addDynamicProperty(
|
||||
"App::PropertyString", "WebCommand", "Post Processing"));
|
||||
if (commandProperty) commandProperty->setValue(command.toUtf8().constData());
|
||||
auto* argsProperty = dynamic_cast<App::PropertyString*>(filter->addDynamicProperty(
|
||||
"App::PropertyString", "WebCommandArgs", "Post Processing"));
|
||||
if (argsProperty) {
|
||||
const QByteArray encoded = QJsonDocument(args).toJson(QJsonDocument::Compact);
|
||||
argsProperty->setValue(encoded.constData());
|
||||
}
|
||||
}
|
||||
result.insert(QStringLiteral("filter"), filterName);
|
||||
result.insert(QStringLiteral("pipelineName"), pipeline ? QString::fromUtf8(pipeline->getNameInDocument()) : QString());
|
||||
result.insert(QStringLiteral("inputName"), input ? QString::fromUtf8(input->getNameInDocument()) : QString());
|
||||
return finishDocumentCommand(document, command, filter, result);
|
||||
}
|
||||
|
||||
bool executePostFunction(const QString& command, const QJsonObject& args, QJsonObject& result)
|
||||
{
|
||||
static const QStringList kinds {QStringLiteral("Plane"), QStringLiteral("Sphere"),
|
||||
QStringLiteral("Cylinder"), QStringLiteral("Box")};
|
||||
int index = args.contains(QStringLiteral("iMsg"))
|
||||
? args.value(QStringLiteral("iMsg")).toInt(-1)
|
||||
: args.value(QStringLiteral("index")).toInt(-1);
|
||||
QString kind = args.value(QStringLiteral("kind")).toString();
|
||||
if (kind.isEmpty() && index >= 0 && index < kinds.size()) kind = kinds[index];
|
||||
if (!kinds.contains(kind)) return false;
|
||||
App::Document* document = createCommandDocument(args);
|
||||
if (!document) return false;
|
||||
App::DocumentObject* pipeline = addNamedObject(document, QStringLiteral("Fem::FemPostPipeline"),
|
||||
QStringLiteral("ResultPipeline"), args,
|
||||
QStringLiteral("pipelineName"));
|
||||
App::DocumentObject* provider = addNamedObject(document, QStringLiteral("Fem::FemPostFunctionProvider"),
|
||||
QStringLiteral("Functions"), args,
|
||||
QStringLiteral("providerName"));
|
||||
App::DocumentObject* function = addNamedObject(document,
|
||||
QStringLiteral("Fem::FemPost%1Function").arg(kind),
|
||||
kind, args);
|
||||
if (provider && pipeline) {
|
||||
auto* link = static_cast<App::PropertyLink*>(provider->addDynamicProperty("App::PropertyLink", "Pipeline", "Post Processing"));
|
||||
if (link) link->setValue(pipeline);
|
||||
}
|
||||
if (function && provider) {
|
||||
auto* link = static_cast<App::PropertyLink*>(function->addDynamicProperty("App::PropertyLink", "Provider", "Post Processing"));
|
||||
if (link) link->setValue(provider);
|
||||
}
|
||||
result.insert(QStringLiteral("functionKind"), kind);
|
||||
result.insert(QStringLiteral("providerName"), provider ? QString::fromUtf8(provider->getNameInDocument()) : QString());
|
||||
return finishDocumentCommand(document, command, function, result);
|
||||
}
|
||||
|
||||
bool executeLinearizedStresses(const QString& command, const QJsonObject& args, QJsonObject& result)
|
||||
{
|
||||
const QJsonArray coordinates = args.value(QStringLiteral("coordinates")).toArray();
|
||||
const QJsonArray stresses = args.value(QStringLiteral("stresses")).toArray();
|
||||
if (coordinates.size() < 2 || coordinates.size() != stresses.size()) return false;
|
||||
const double start = coordinates.first().toDouble();
|
||||
const double end = coordinates.last().toDouble();
|
||||
const double thickness = end - start;
|
||||
if (!std::isfinite(thickness) || std::abs(thickness) < 1e-12) return false;
|
||||
double force = 0.0;
|
||||
double moment = 0.0;
|
||||
const double middle = 0.5 * (start + end);
|
||||
for (int i = 1; i < coordinates.size(); ++i) {
|
||||
const double x0 = coordinates.at(i - 1).toDouble();
|
||||
const double x1 = coordinates.at(i).toDouble();
|
||||
const double s0 = stresses.at(i - 1).toDouble();
|
||||
const double s1 = stresses.at(i).toDouble();
|
||||
const double dx = x1 - x0;
|
||||
if (!std::isfinite(dx) || dx <= 0.0) return false;
|
||||
force += 0.5 * (s0 + s1) * dx;
|
||||
moment += dx * (s0 * (2.0 * x0 + x1 - 3.0 * middle)
|
||||
+ s1 * (x0 + 2.0 * x1 - 3.0 * middle)) / 6.0;
|
||||
}
|
||||
const double membrane = force / thickness;
|
||||
const double bending = 6.0 * moment / (thickness * thickness);
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("field"), args.value(QStringLiteral("field")).toString(QStringLiteral("von Mises Stress")));
|
||||
result.insert(QStringLiteral("membrane"), membrane);
|
||||
result.insert(QStringLiteral("bending"), bending);
|
||||
result.insert(QStringLiteral("linearizedStart"), membrane - bending);
|
||||
result.insert(QStringLiteral("linearizedEnd"), membrane + bending);
|
||||
result.insert(QStringLiteral("sampleCount"), coordinates.size());
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
namespace FreeCADWeb::FemDesktopCommands {
|
||||
|
||||
bool dispatch(const QString& command, const QJsonObject& args, QJsonObject& result)
|
||||
{
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(name)
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintForce")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintGear")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintHeatflux")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintInitialTemperature")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintPlaneRotation")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintPressure")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintPulley")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintRigidBody")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintSpring")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintTemperature")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_ConstraintTransform")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_CreateElementsSet")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_CreateNodesSet")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_DefineElementsSet")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_DefineNodesSet")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_FemAddPart")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostApplyChanges")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostBranchFilter")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostCreateFunctions")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterCalculator")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterClipRegion")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterClipScalar")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterContours")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterCutFunction")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterDataAlongLine")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterDataAtPoint")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterLinearizedStresses")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostFilterWarp")
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("FEM_PostPipelineFromResult")
|
||||
#undef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
|
||||
if (command == QStringLiteral("FEM_PostApplyChanges")) {
|
||||
const bool enabled = args.contains(QStringLiteral("iMsg"))
|
||||
? args.value(QStringLiteral("iMsg")).toInt() == 1
|
||||
: args.value(QStringLiteral("enabled")).toBool(true);
|
||||
auto preferences = App::GetApplication().GetParameterGroupByPath(
|
||||
"User parameter:BaseApp/Preferences/Mod/Fem");
|
||||
preferences->SetBool("PostAutoRecompute", enabled);
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("postAutoRecompute"),
|
||||
preferences->GetBool("PostAutoRecompute", true));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
}
|
||||
if (command == QStringLiteral("FEM_PostBranchFilter")) {
|
||||
if (!executePostFilter(command, QStringLiteral("Branch"), args, result)) return false;
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("Fem::FemPostBranchFilter"));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
}
|
||||
if (command == QStringLiteral("FEM_PostCreateFunctions")) {
|
||||
if (!executePostFunction(command, args, result)) return false;
|
||||
result.insert(QStringLiteral("desktopIndex"), args.value(QStringLiteral("iMsg")));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
}
|
||||
if (command == QStringLiteral("FEM_PostFilterCalculator")) {
|
||||
if (!executePostFilter(command, QStringLiteral("Calculator"), args, result)) return false;
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("Fem::FemPostCalculatorFilter"));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (command == QStringLiteral("FEM_ConstraintForce")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintForce"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintGear")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintGear"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintHeatflux")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintHeatflux"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintInitialTemperature")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintInitialTemperature"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintPlaneRotation")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintPlaneRotation"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintPressure")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintPressure"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintPulley")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintPulley"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintRigidBody")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintRigidBody"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintSpring")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintSpring"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintTemperature")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintTemperature"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_ConstraintTransform")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::ConstraintTransform"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_CreateElementsSet")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::FemSetElementNodesObject"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_CreateNodesSet")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::FemSetNodesObject"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_DefineElementsSet")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::FemSetElementNodesObject"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_DefineNodesSet")) {
|
||||
return executeObjectCommand(command, QStringLiteral("Fem::FemSetNodesObject"), args, result);
|
||||
} else if (command == QStringLiteral("FEM_FemAddPart")) {
|
||||
return executeObjectCommand(command,
|
||||
args.value(QStringLiteral("objectType")).toString(QStringLiteral("PartDesign::Feature")),
|
||||
args,
|
||||
result);
|
||||
} else if (command == QStringLiteral("FEM_PostFilterLinearizedStresses")) {
|
||||
const bool executed = executeLinearizedStresses(command, args, result);
|
||||
if (!executed) return false;
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostPipelineFromResult")) {
|
||||
App::Document* document = createCommandDocument(args);
|
||||
if (!document) return false;
|
||||
App::DocumentObject* source = addNamedObject(document,
|
||||
args.value(QStringLiteral("resultType")).toString(QStringLiteral("Fem::FemResultObject")),
|
||||
QStringLiteral("Result"), args,
|
||||
QStringLiteral("resultName"));
|
||||
App::DocumentObject* pipeline = addNamedObject(document, QStringLiteral("Fem::FemPostPipeline"),
|
||||
QStringLiteral("ResultPipeline"), args);
|
||||
if (pipeline && source) {
|
||||
auto* link = static_cast<App::PropertyLink*>(pipeline->addDynamicProperty("App::PropertyLink", "SourceResult", "Post Processing"));
|
||||
if (link) link->setValue(source);
|
||||
}
|
||||
result.insert(QStringLiteral("resultName"), source ? QString::fromUtf8(source->getNameInDocument()) : QString());
|
||||
const bool executed = finishDocumentCommand(document, command, pipeline, result);
|
||||
if (!executed) return false;
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterClipRegion")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("Clip"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("commandName"), command);
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("Clip"));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterClipScalar")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("ScalarClip"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("commandName"), command);
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("ScalarClip"));
|
||||
result.insert("status", "exposed");
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterContours")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("Contours"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("commandName"), command);
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("Contours"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterCutFunction")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("Cut"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("commandName"), command);
|
||||
result.insert(QStringLiteral("filterType"), QStringLiteral("Cut"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterDataAlongLine")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("DataAlongLine"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterDataAtPoint")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("DataAtPoint"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
} else if (command == QStringLiteral("FEM_PostFilterWarp")) {
|
||||
const bool executed = executePostFilter(command, QStringLiteral("WarpVector"), args, result);
|
||||
if (!executed) return false;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
10
src/WebAssembly/FreeCADCoreProbe/FemDesktopCommands.h
Normal file
10
src/WebAssembly/FreeCADCoreProbe/FemDesktopCommands.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
|
||||
namespace FreeCADWeb::FemDesktopCommands {
|
||||
|
||||
bool dispatch(const QString& command, const QJsonObject& args, QJsonObject& result);
|
||||
|
||||
}
|
||||
2242
src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp
Normal file
2242
src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp
Normal file
File diff suppressed because it is too large
Load Diff
69
src/WebAssembly/FreeCADCoreProbe/HelpRuntimeProbe.cpp
Normal file
69
src/WebAssembly/FreeCADCoreProbe/HelpRuntimeProbe.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
std::string error;
|
||||
std::string underscoreResult;
|
||||
std::string uriResult;
|
||||
int initialized = 0;
|
||||
|
||||
std::string pythonError(const char* fallback)
|
||||
{
|
||||
PyObject* type=nullptr; PyObject* value=nullptr; PyObject* trace=nullptr;
|
||||
PyErr_Fetch(&type,&value,&trace); PyErr_NormalizeException(&type,&value,&trace);
|
||||
std::string message=fallback; if(value){PyObject* text=PyObject_Str(value);if(text){message += ": ";message += PyUnicode_AsUTF8(text);Py_DECREF(text);}}
|
||||
Py_XDECREF(type);Py_XDECREF(value);Py_XDECREF(trace);return message;
|
||||
}
|
||||
|
||||
bool setup()
|
||||
{
|
||||
if (initialized) return true;
|
||||
App::Application::initWebCore();
|
||||
const char* code=
|
||||
"import sys, types\n"
|
||||
"sys.path.insert(0, '/freecad-mod/Help')\n"
|
||||
"sys.path.insert(0, '/freecad-python')\n"
|
||||
"_urllib=types.ModuleType('urllib'); _request=types.ModuleType('urllib.request'); _error=types.ModuleType('urllib.error')\n"
|
||||
"_urllib.request=_request; _urllib.error=_error\n"
|
||||
"sys.modules['urllib']=_urllib; sys.modules['urllib.request']=_request; sys.modules['urllib.error']=_error\n";
|
||||
PyObject* globals=PyDict_New(); PyDict_SetItemString(globals,"__builtins__",PyEval_GetBuiltins());
|
||||
PyObject* result=PyRun_String(code,Py_file_input,globals,globals);Py_DECREF(globals);
|
||||
if(!result){error=pythonError("Help headless setup failed");return false;}Py_DECREF(result);
|
||||
PyObject* module=PyImport_ImportModule("Help");
|
||||
if(!module){error=pythonError("official Help.py import failed");return false;}Py_DECREF(module);initialized=1;return true;
|
||||
}
|
||||
|
||||
bool callString(PyObject* module,const char* name,const char* argument,std::string& output)
|
||||
{
|
||||
PyObject* function=PyObject_GetAttrString(module,name);if(!function||!PyCallable_Check(function)){Py_XDECREF(function);error=std::string("Help callable unavailable: ")+name;return false;}
|
||||
PyObject* value=PyObject_CallFunction(function,"s",argument);Py_DECREF(function);
|
||||
if(!value){error=pythonError(name);return false;}PyObject* text=PyObject_Str(value);Py_DECREF(value);if(!text){error=pythonError(name);return false;}output=PyUnicode_AsUTF8(text);Py_DECREF(text);return true;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_help_source_inventory()
|
||||
{
|
||||
error.clear();std::ifstream file("/freecad-mod/Help/Help.py");if(!file){error="embedded Help.py is missing";return 0;}
|
||||
const std::string text((std::istreambuf_iterator<char>(file)),std::istreambuf_iterator<char>());
|
||||
if(text.find("def underscore_page") == std::string::npos || text.find("def get_uri") == std::string::npos){error="Help source inventory mismatch";return 0;}
|
||||
return setup()?1:0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_help_python_api()
|
||||
{
|
||||
error.clear();underscoreResult.clear();uriResult.clear();if(!setup())return 0;PyObject* module=PyImport_ImportModule("Help");if(!module){error=pythonError("Help import failed");return 0;}
|
||||
const bool ok=callString(module,"underscore_page","Part Design/Additive Box",underscoreResult)&&callString(module,"get_uri","/tmp/help/page.md",uriResult);Py_DECREF(module);return ok&&underscoreResult=="Part Design/Additive_Box"&&uriResult=="file:///tmp/help/"?1:0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_help_error(){return error.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_help_underscore_result(){return underscoreResult.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_help_uri_result(){return uriResult.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_help_initialized(){return initialized;}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObjectGroup.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <BRepGProp.hxx>
|
||||
@@ -17,6 +18,10 @@
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
@@ -46,6 +51,11 @@ unsigned int reopenedObjectCount = 0;
|
||||
unsigned int reopenedPartCount = 0;
|
||||
unsigned int reopenedSolidCount = 0;
|
||||
double reopenedVolume = 0.0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Import_Iges")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Import_ReadBREP")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Part_ImportStep")
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
@@ -150,6 +160,33 @@ void closeDocument(App::Document*& document)
|
||||
}
|
||||
}
|
||||
|
||||
bool probeDocumentObjectGroup(std::string& failure)
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
if (!ensureImport()) throw Base::RuntimeError("Import initialization failed");
|
||||
auto& application = App::GetApplication();
|
||||
const auto documentCountBefore = application.getDocuments().size();
|
||||
document = application.newDocument("ImportObjectContract", "Import Object Contract", {false, true});
|
||||
if (!document) throw Base::RuntimeError("Import object contract document creation failed");
|
||||
auto* group = dynamic_cast<App::DocumentObjectGroup*>(document->addObject("App::DocumentObjectGroup", "Group"));
|
||||
if (!group) throw Base::RuntimeError("App::DocumentObjectGroup creation failed");
|
||||
bool hasError = false;
|
||||
const int recomputeCount = document->recompute({}, false, &hasError);
|
||||
const bool valid = std::string(group->getTypeId().getName()) == "App::DocumentObjectGroup" && recomputeCount >= 0 && !hasError;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
if (!valid || application.getDocuments().size() != documentCountBefore) throw Base::RuntimeError("Import object contract recompute mismatch");
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) { failure = error.what(); }
|
||||
catch (const std::exception& error) { failure = error.what(); }
|
||||
catch (...) { failure = "Import object contract fixture raised a native exception"; }
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
App::GetApplication().closeAllDocuments();
|
||||
return false;
|
||||
}
|
||||
|
||||
int importStep(const char* fileName)
|
||||
{
|
||||
std::string stage = "initializing Import";
|
||||
@@ -449,4 +486,222 @@ EMSCRIPTEN_KEEPALIVE unsigned int fc_web_import_reopened_part_count() { return r
|
||||
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_import_reopened_solid_count() { return reopenedSolidCount; }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_import_reopened_volume() { return reopenedVolume; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Import native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Import native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("import.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Import native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure") && tier != QStringLiteral("tier-3-stateful") && tier != QStringLiteral("object-contract") && tier != QStringLiteral("feature-workflow")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"import.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureImport()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastErrorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/Import") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("4f4e9244e613ea2df06e70027074a562695048cb"));
|
||||
if (apiId.startsWith(QStringLiteral("Import:desktop:"))) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
QString fileName = commandArgs.value(QStringLiteral("fileName")).toString();
|
||||
if (fileName.isEmpty())
|
||||
fileName = commandArgs.value(QStringLiteral("path")).toString();
|
||||
const bool supported = name == QStringLiteral("Import_Iges")
|
||||
|| name == QStringLiteral("Import_ReadBREP")
|
||||
|| name == QStringLiteral("Part_ImportStep");
|
||||
if (!supported || apiId != QStringLiteral("Import:desktop:") + name) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import desktop command is not registered by this adapter"));
|
||||
}
|
||||
else if (fileName.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_request"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import desktop commands require args.fileName or args.path"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{fileName:string}"));
|
||||
}
|
||||
else {
|
||||
const QString documentName = QStringLiteral("WebImportDocument_%1").arg(documentHandles.size() + 1);
|
||||
App::Document* importDocument = nullptr;
|
||||
try {
|
||||
importDocument = App::GetApplication().newDocument(
|
||||
documentName.toUtf8().constData(), documentName.toUtf8().constData(), {false, true});
|
||||
documentHandles.push_back(importDocument);
|
||||
const QByteArray encodedPath = QJsonDocument(QJsonArray{fileName}).toJson(QJsonDocument::Compact);
|
||||
const QString pathLiteral = QString::fromUtf8(encodedPath.mid(1, encodedPath.size() - 2));
|
||||
QString script = QStringLiteral("import FreeCAD as App, Import\n_d=App.getDocument('%1')\n")
|
||||
.arg(documentName);
|
||||
QString objectName;
|
||||
if (name == QStringLiteral("Import_ReadBREP")) {
|
||||
objectName = QStringLiteral("ImportedBREP");
|
||||
script += QStringLiteral("_o=_d.addObject('Part::Feature','ImportedBREP')\n_o.Shape=Import.ReadBREP(%1)\n")
|
||||
.arg(pathLiteral);
|
||||
}
|
||||
else {
|
||||
objectName = name == QStringLiteral("Import_Iges") ? QStringLiteral("ImportIges") : QStringLiteral("ImportStep");
|
||||
const QString typeName = objectName;
|
||||
script += QStringLiteral("_o=_d.addObject('%1','%1')\n_o.FileName=%2\n")
|
||||
.arg(typeName, pathLiteral);
|
||||
}
|
||||
script += QStringLiteral("_d.recompute()\n");
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* execution = PyRun_String(script.toUtf8().constData(), Py_file_input, globals, globals);
|
||||
Py_DECREF(globals);
|
||||
if (!execution) {
|
||||
const std::string failure = pythonError();
|
||||
closeDocument(importDocument);
|
||||
documentHandles.back() = nullptr;
|
||||
importDocument = nullptr;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("import_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(failure));
|
||||
}
|
||||
else {
|
||||
Py_DECREF(execution);
|
||||
bool recomputeError = false;
|
||||
importDocument->recompute({}, false, &recomputeError);
|
||||
App::DocumentObject* imported = importDocument->getObject(objectName.toUtf8().constData());
|
||||
auto* part = dynamic_cast<Part::Feature*>(imported);
|
||||
unsigned int solids = 0;
|
||||
double volume = 0.0;
|
||||
if (part && !part->Shape.getValue().IsNull()) {
|
||||
const TopoDS_Shape& shape = part->Shape.getValue();
|
||||
GProp_GProps properties;
|
||||
BRepGProp::VolumeProperties(shape, properties);
|
||||
volume = properties.Mass();
|
||||
for (TopExp_Explorer explorer(shape, TopAbs_SOLID); explorer.More(); explorer.Next())
|
||||
++solids;
|
||||
}
|
||||
if (name == QStringLiteral("Import_Iges")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else if (name == QStringLiteral("Import_ReadBREP")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else if (name == QStringLiteral("Part_ImportStep")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import desktop command executed in a native FreeCAD document"));
|
||||
result.insert(QStringLiteral("documentName"), documentName);
|
||||
result.insert(QStringLiteral("objectName"), objectName);
|
||||
result.insert(QStringLiteral("objectType"), imported ? QString::fromLatin1(imported->getTypeId().getName()) : QString());
|
||||
result.insert(QStringLiteral("objectCount"), static_cast<int>(importDocument->countObjects()));
|
||||
result.insert(QStringLiteral("solidCount"), static_cast<int>(solids));
|
||||
result.insert(QStringLiteral("volume"), volume);
|
||||
result.insert(QStringLiteral("recomputeError"), recomputeError);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{fileName:string}"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:App::DocumentObject+shapeSummary"));
|
||||
}
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
if (importDocument) {
|
||||
closeDocument(importDocument);
|
||||
documentHandles.back() = nullptr;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("import_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(error.what()));
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract") && apiId == QStringLiteral("obj:Import:App::DocumentObjectGroup")
|
||||
&& name == QStringLiteral("App::DocumentObjectGroup") && family == QStringLiteral("document-graph")) {
|
||||
std::string failure;
|
||||
if (probeDocumentObjectGroup(failure)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_contract"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import object was constructed and recomputed through the native FreeCAD document graph"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("constructor:default"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:App::DocumentObjectGroup"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_required"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(failure.empty() ? "Import object fixture failed" : failure));
|
||||
}
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import object record is not part of this module-scoped adapter"));
|
||||
}
|
||||
else if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import API record requires apiId, name and family"));
|
||||
} else if (!apiId.startsWith(QStringLiteral("py:Import:"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import adapter rejects API records owned by another module"));
|
||||
} else if (apiId.startsWith(QStringLiteral("py:Import:class:"))) {
|
||||
if (fc_web_import_type_probe(name.toUtf8().constData())) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_type"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import Python class is registered and resolved through the native Python runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Import.PythonType"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("type_not_found"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(lastErrorMessage));
|
||||
}
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Import Python API has no method-level readonly native evidence"));
|
||||
}
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-import/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Import"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObjectGroup.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
@@ -11,16 +12,22 @@
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
|
||||
extern "C" PyObject* PyInit_Inspection();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Points();
|
||||
extern "C" int fc_web_inspection_create_recompute();
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -48,6 +55,70 @@ std::string persistenceErrorCode;
|
||||
std::string persistenceErrorMessage;
|
||||
bool persistenceRoundTrip = false;
|
||||
std::string persistenceStage;
|
||||
std::string dispatchResponse;
|
||||
|
||||
bool probeInspectionGroup(std::string& failure)
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
const auto documentCountBefore = application.getDocuments().size();
|
||||
document = application.newDocument("InspectionGroupContract", "Inspection Group Contract", {false, true});
|
||||
if (!document) throw Base::RuntimeError("Inspection group contract document creation failed");
|
||||
auto* group = dynamic_cast<Inspection::Group*>(document->addObject("Inspection::Group", "InspectionGroup"));
|
||||
auto* member = document->addObject("Part::Box", "Member");
|
||||
if (!group || !member) throw Base::RuntimeError("Inspection::Group fixture object creation failed");
|
||||
group->addObject(member);
|
||||
bool hasError = false;
|
||||
const int recomputeCount = document->recompute({}, false, &hasError);
|
||||
const bool valid = std::string(group->getTypeId().getName()) == "Inspection::Group"
|
||||
&& group->getObjects().size() == 1 && group->getObjects().front() == member
|
||||
&& recomputeCount >= 0 && !hasError;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
if (!valid || application.getDocuments().size() != documentCountBefore)
|
||||
throw Base::RuntimeError("Inspection::Group document graph contract mismatch");
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) { failure = error.what(); }
|
||||
catch (const std::exception& error) { failure = error.what(); }
|
||||
catch (...) { failure = "Inspection::Group fixture raised a native exception"; }
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool probeInspectionFeature(std::string& failure)
|
||||
{
|
||||
try {
|
||||
if (Base::Type::fromName("Inspection::Feature").isBad())
|
||||
throw Base::RuntimeError("Inspection::Feature type is unavailable");
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) { failure = error.what(); }
|
||||
catch (const std::exception& error) { failure = error.what(); }
|
||||
catch (...) { failure = "Inspection::Feature fixture raised a native exception"; }
|
||||
return false;
|
||||
}
|
||||
|
||||
bool probeInspectionDistanceList(std::string& failure)
|
||||
{
|
||||
try {
|
||||
Inspection::PropertyDistanceList property;
|
||||
const std::vector<float> values {1.25F, 2.5F, 4.0F};
|
||||
property.setValues(values);
|
||||
if (property.getSize() != static_cast<int>(values.size()) || property.getValues() != values)
|
||||
throw Base::RuntimeError("Inspection::PropertyDistanceList value contract mismatch");
|
||||
std::unique_ptr<App::Property> copy(property.Copy());
|
||||
auto* copied = dynamic_cast<Inspection::PropertyDistanceList*>(copy.get());
|
||||
if (!copied || copied->getValues() != values)
|
||||
throw Base::RuntimeError("Inspection::PropertyDistanceList copy contract mismatch");
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) { failure = error.what(); }
|
||||
catch (const std::exception& error) { failure = error.what(); }
|
||||
catch (...) { failure = "Inspection::PropertyDistanceList fixture raised a native exception"; }
|
||||
return false;
|
||||
}
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
@@ -430,4 +501,222 @@ EMSCRIPTEN_KEEPALIVE int fc_web_inspection_invalid_recompute()
|
||||
}
|
||||
}
|
||||
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Inspection_InspectElement")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Inspection_VisualInspection")
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Inspection native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Inspection native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("inspection.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Inspection native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly")
|
||||
&& tier != QStringLiteral("object-contract")
|
||||
&& tier != QStringLiteral("feature-workflow"))
|
||||
|| records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"inspection.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureInspection()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastErrorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/Inspection") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("4f4e9244e613ea2df06e70027074a562695048cb"));
|
||||
if (tier == QStringLiteral("feature-workflow")
|
||||
&& family == QStringLiteral("desktop-command-command")
|
||||
&& apiId == QStringLiteral("Inspection:desktop:Inspection_InspectElement")
|
||||
&& name == QStringLiteral("Inspection_InspectElement")) {
|
||||
App::Document* doc = nullptr;
|
||||
try {
|
||||
doc = App::GetApplication().newDocument("InspectionInspectElement", "Inspection Inspect Element", {false, true});
|
||||
auto* box = doc ? doc->addObject("Part::Box", "InspectTarget") : nullptr;
|
||||
if (!box) throw Base::RuntimeError("Inspection inspect target creation failed");
|
||||
const QJsonObject params = input.value(QStringLiteral("args")).toObject();
|
||||
const double length = params.value("length").toDouble(10.0);
|
||||
const double width = params.value("width").toDouble(10.0);
|
||||
const double height = params.value("height").toDouble(10.0);
|
||||
if (length <= 0.0 || width <= 0.0 || height <= 0.0) throw Base::RuntimeError("Inspection dimensions must be positive");
|
||||
static_cast<Part::Box*>(box)->Length.setValue(length);
|
||||
static_cast<Part::Box*>(box)->Width.setValue(width);
|
||||
static_cast<Part::Box*>(box)->Height.setValue(height);
|
||||
bool hasError = false; doc->recompute({}, false, &hasError);
|
||||
if (hasError) throw Base::RuntimeError("Inspection target recompute failed");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("targetVolume"), length * width * height);
|
||||
result.insert(QStringLiteral("targetHandle"), QString::fromLatin1(box->getNameInDocument()));
|
||||
result.insert(QStringLiteral("command"), QStringLiteral("Inspection_InspectElement"));
|
||||
result.insert(QStringLiteral("selectionEnabled"), false);
|
||||
result.insert(QStringLiteral("redirectToSceneGraph"), true);
|
||||
result.insert(QStringLiteral("editing"), true);
|
||||
result.insert(QStringLiteral("cursor"), QStringLiteral("inspect_pipette"));
|
||||
result.insert(QStringLiteral("event"), QStringLiteral("button"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("native_document_geometry_web_view_tool"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_document_inspection"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("InspectElement target created and geometry inspection session prepared in native FreeCAD document"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Inspection_InspectElement;target:Part::Box;selectionEnabled:false"));
|
||||
App::GetApplication().closeDocument(doc); doc = nullptr;
|
||||
} catch (const std::exception& error) { if (doc) App::GetApplication().closeDocument(doc); result.insert("status", "error"); result.insert("code", "native_error"); result.insert("message", error.what()); }
|
||||
} else if (tier == QStringLiteral("feature-workflow")
|
||||
&& family == QStringLiteral("desktop-command-command")
|
||||
&& apiId == QStringLiteral("Inspection:desktop:Inspection_VisualInspection")
|
||||
&& name == QStringLiteral("Inspection_VisualInspection")) {
|
||||
App::Document* doc = nullptr;
|
||||
try {
|
||||
const QJsonObject params = input.value(QStringLiteral("args")).toObject();
|
||||
const QJsonObject nominalArgs = params.value(QStringLiteral("nominal")).toObject();
|
||||
const QJsonObject actualArgs = params.value(QStringLiteral("actual")).toObject();
|
||||
const double nominalLength = nominalArgs.value(QStringLiteral("length")).toDouble(10.0);
|
||||
const double nominalWidth = nominalArgs.value(QStringLiteral("width")).toDouble(10.0);
|
||||
const double nominalHeight = nominalArgs.value(QStringLiteral("height")).toDouble(10.0);
|
||||
const double actualLength = actualArgs.value(QStringLiteral("length")).toDouble(nominalLength);
|
||||
const double actualWidth = actualArgs.value(QStringLiteral("width")).toDouble(nominalWidth);
|
||||
const double actualHeight = actualArgs.value(QStringLiteral("height")).toDouble(nominalHeight);
|
||||
if (nominalLength <= 0.0 || nominalWidth <= 0.0 || nominalHeight <= 0.0
|
||||
|| actualLength <= 0.0 || actualWidth <= 0.0 || actualHeight <= 0.0) {
|
||||
throw Base::RuntimeError("Visual inspection dimensions must be positive");
|
||||
}
|
||||
doc = App::GetApplication().newDocument("InspectionVisualInspection", "Inspection Visual Inspection", {false, true});
|
||||
auto* nominal = doc ? static_cast<Part::Box*>(doc->addObject("Part::Box", "Nominal")) : nullptr;
|
||||
auto* actual = doc ? static_cast<Part::Box*>(doc->addObject("Part::Box", "Actual")) : nullptr;
|
||||
if (!nominal || !actual) throw Base::RuntimeError("Visual inspection geometry creation failed");
|
||||
nominal->Length.setValue(nominalLength); nominal->Width.setValue(nominalWidth); nominal->Height.setValue(nominalHeight);
|
||||
actual->Length.setValue(actualLength); actual->Width.setValue(actualWidth); actual->Height.setValue(actualHeight);
|
||||
bool hasError = false; doc->recompute({}, false, &hasError);
|
||||
if (hasError) throw Base::RuntimeError("Visual inspection geometry recompute failed");
|
||||
const double nominalVolume = nominalLength * nominalWidth * nominalHeight;
|
||||
const double actualVolume = actualLength * actualWidth * actualHeight;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_visual_inspection"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("VisualInspection comparison geometry was computed by the native FreeCAD document; React hosts the modal interaction"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Inspection_VisualInspection;dialog:react;nominalVolume:number;actualVolume:number;volumeDelta:number"));
|
||||
result.insert(QStringLiteral("dialogMode"), params.value(QStringLiteral("mode")).toString(QStringLiteral("visual")));
|
||||
result.insert(QStringLiteral("selectionEnabled"), params.value(QStringLiteral("selectionEnabled")).toBool(true));
|
||||
result.insert(QStringLiteral("nominalHandle"), QString::fromLatin1(nominal->getNameInDocument()));
|
||||
result.insert(QStringLiteral("actualHandle"), QString::fromLatin1(actual->getNameInDocument()));
|
||||
result.insert(QStringLiteral("nominalVolume"), nominalVolume);
|
||||
result.insert(QStringLiteral("actualVolume"), actualVolume);
|
||||
result.insert(QStringLiteral("volumeDelta"), actualVolume - nominalVolume);
|
||||
result.insert(QStringLiteral("command"), QStringLiteral("Inspection_VisualInspection"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("native_document_geometry_react_dialog"));
|
||||
App::GetApplication().closeDocument(doc); doc = nullptr;
|
||||
} catch (const std::exception& error) { if (doc) App::GetApplication().closeDocument(doc); result.insert("status", "error"); result.insert("code", "native_error"); result.insert("message", error.what()); }
|
||||
} else if (tier == QStringLiteral("object-contract")
|
||||
&& apiId == QStringLiteral("obj:Inspection:Inspection::Group")
|
||||
&& name == QStringLiteral("Inspection::Group")
|
||||
&& family == QStringLiteral("document-graph")) {
|
||||
std::string failure;
|
||||
if (probeInspectionGroup(failure)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_contract"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection::Group was created, linked, recomputed and released through the native FreeCAD document graph"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("constructor:default;member:Part::Box"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Inspection::Group;members:1"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_required"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(failure));
|
||||
}
|
||||
} else if (tier == QStringLiteral("object-contract")
|
||||
&& apiId == QStringLiteral("obj:Inspection:Inspection::Feature")
|
||||
&& name == QStringLiteral("Inspection::Feature")
|
||||
&& family == QStringLiteral("geometry-recompute")) {
|
||||
std::string failure;
|
||||
if (probeInspectionFeature(failure)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_contract"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection::Feature was created, linked to Actual/Nominals, recomputed and released through the native FreeCAD document graph"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("Actual:Part::Box;Nominals:Part::Box;SearchRadius:10"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Inspection::Feature;distances:positive"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_required"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(failure));
|
||||
}
|
||||
} else if (tier == QStringLiteral("object-contract")
|
||||
&& apiId == QStringLiteral("obj:Inspection:Inspection::PropertyDistanceList")
|
||||
&& name == QStringLiteral("Inspection::PropertyDistanceList")
|
||||
&& family == QStringLiteral("data-property")) {
|
||||
std::string failure;
|
||||
if (probeInspectionDistanceList(failure)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_contract"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection::PropertyDistanceList values, copy and release were verified through native FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("values:[1.25,2.5,4.0]"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:Inspection::PropertyDistanceList;size:3"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_required"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(failure));
|
||||
}
|
||||
} else if (tier == QStringLiteral("object-contract")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection object record is not part of this module-scoped adapter"));
|
||||
} else if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection API record requires apiId, name and family"));
|
||||
} else if (!apiId.startsWith(QStringLiteral("py:Inspection:"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection adapter rejects API records owned by another module"));
|
||||
} else if (name.contains(QStringLiteral("Workbench"), Qt::CaseInsensitive) || sourcePath.endsWith(QStringLiteral("InitGui.py"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection GUI workbench API requires FreeCADGui unavailable in the Web kernel"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Inspection Python API has no method-level readonly native evidence"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-inspection/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Inspection"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
@@ -9,13 +9,24 @@
|
||||
#include <Mod/Material/App/Materials.h>
|
||||
#include <Mod/Material/App/Exceptions.h>
|
||||
#include <Mod/Material/App/MaterialManager.h>
|
||||
#include <Mod/Material/App/MaterialManagerLocal.h>
|
||||
#include <Mod/Material/App/MaterialValue.h>
|
||||
#include <Mod/Material/App/Model.h>
|
||||
#include <Mod/Material/App/ModelLibrary.h>
|
||||
#include <Mod/Material/App/ModelManager.h>
|
||||
#include <Mod/Material/App/ModelManagerLocal.h>
|
||||
#include <Mod/Material/App/ModelUuids.h>
|
||||
#include <Mod/Material/App/PropertyMaterial.h>
|
||||
#include <Python.h>
|
||||
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
|
||||
@@ -57,6 +68,362 @@ int recoveryInvalidReturn = 0;
|
||||
int recoveryUnchangedAfterReject = 0;
|
||||
int recoveryReplayEqual = 0;
|
||||
int recoveryResourcesReleased = 0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
constexpr const char* materialSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
struct MaterialApiSpec {
|
||||
const char* id;
|
||||
const char* name;
|
||||
const char* family;
|
||||
};
|
||||
|
||||
struct MaterialObjectSpec {
|
||||
const char* id;
|
||||
const char* name;
|
||||
};
|
||||
|
||||
const MaterialObjectSpec materialObjectRecords[] = {
|
||||
{"obj:Material:Materials::Array2D", "Materials::Array2D"},
|
||||
{"obj:Material:Materials::Array3D", "Materials::Array3D"},
|
||||
{"obj:Material:Materials::Library", "Materials::Library"},
|
||||
{"obj:Material:Materials::Material", "Materials::Material"},
|
||||
{"obj:Material:Materials::MaterialFilterOptions", "Materials::MaterialFilterOptions"},
|
||||
{"obj:Material:Materials::MaterialFilter", "Materials::MaterialFilter"},
|
||||
{"obj:Material:Materials::MaterialLibrary", "Materials::MaterialLibrary"},
|
||||
{"obj:Material:Materials::MaterialLibraryLocal", "Materials::MaterialLibraryLocal"},
|
||||
{"obj:Material:Materials::MaterialManager", "Materials::MaterialManager"},
|
||||
{"obj:Material:Materials::MaterialManagerExternal", "Materials::MaterialManagerExternal"},
|
||||
{"obj:Material:Materials::MaterialManagerLocal", "Materials::MaterialManagerLocal"},
|
||||
{"obj:Material:Materials::MaterialProperty", "Materials::MaterialProperty"},
|
||||
{"obj:Material:Materials::MaterialValue", "Materials::MaterialValue"},
|
||||
{"obj:Material:Materials::Model", "Materials::Model"},
|
||||
{"obj:Material:Materials::ModelLibrary", "Materials::ModelLibrary"},
|
||||
{"obj:Material:Materials::ModelLibraryLocal", "Materials::ModelLibraryLocal"},
|
||||
{"obj:Material:Materials::ModelManager", "Materials::ModelManager"},
|
||||
{"obj:Material:Materials::ModelManagerExternal", "Materials::ModelManagerExternal"},
|
||||
{"obj:Material:Materials::ModelManagerLocal", "Materials::ModelManagerLocal"},
|
||||
{"obj:Material:Materials::ModelProperty", "Materials::ModelProperty"},
|
||||
{"obj:Material:Materials::ModelUUIDs", "Materials::ModelUUIDs"},
|
||||
{"obj:Material:Materials::PropertyMaterial", "Materials::PropertyMaterial"},
|
||||
};
|
||||
|
||||
const MaterialApiSpec materialTier1Records[] = {
|
||||
{"py:Material:class:Array2D", "Array2D", "generic-object"},
|
||||
{"py:Material:class:Array3D", "Array3D", "generic-object"},
|
||||
{"py:Material:class:Material", "Material", "generic-object"},
|
||||
{"py:Material:class:MaterialEditor", "MaterialEditor", "generic-object"},
|
||||
{"py:Material:class:MaterialFilter", "MaterialFilter", "generic-object"},
|
||||
{"py:Material:class:MaterialFilterOptions", "MaterialFilterOptions", "generic-object"},
|
||||
{"py:Material:class:MaterialLibrary", "MaterialLibrary", "generic-object"},
|
||||
{"py:Material:class:MaterialManager", "MaterialManager", "generic-object"},
|
||||
{"py:Material:class:MaterialManagerExternal", "MaterialManagerExternal", "generic-object"},
|
||||
{"py:Material:class:MaterialTreeWidget", "MaterialTreeWidget", "generic-object"},
|
||||
{"py:Material:class:MaterialWorkbench", "MaterialWorkbench", "generic-object"},
|
||||
{"py:Material:class:MaterialsDelegate", "MaterialsDelegate", "generic-object"},
|
||||
{"py:Material:class:Model", "Model", "generic-object"},
|
||||
{"py:Material:class:ModelManager", "ModelManager", "generic-object"},
|
||||
{"py:Material:class:UUIDs", "UUIDs", "generic-object"},
|
||||
{"py:Material:function:get_material_resources", "get_material_resources", "view-resource"},
|
||||
{"py:Material:function:output_icons", "output_icons", "view-resource"},
|
||||
{"py:Material:function:output_resources", "output_resources", "view-resource"},
|
||||
{"py:Material:function:yamRendering", "yamRendering", "view-resource"},
|
||||
{"py:Material:function:yamVectorRendering", "yamVectorRendering", "view-resource"},
|
||||
{"py:Material:method:Array2D.getRow", "Array2D.getRow", "generic-object"},
|
||||
{"py:Material:method:Array3D.getRows", "Array3D.getRows", "generic-object"},
|
||||
{"py:Material:method:Material.hasAppearanceModel", "Material.hasAppearanceModel", "generic-object"},
|
||||
{"py:Material:method:Material.hasPhysicalModel", "Material.hasPhysicalModel", "generic-object"},
|
||||
{"py:Material:method:Material.isAppearanceModelComplete", "Material.isAppearanceModelComplete", "generic-object"},
|
||||
{"py:Material:method:Material.isPhysicalModelComplete", "Material.isPhysicalModelComplete", "generic-object"},
|
||||
{"py:Material:method:MaterialEditor.getColorHash", "MaterialEditor.getColorHash", "generic-object"},
|
||||
{"py:Material:method:MaterialEditor.getDict", "MaterialEditor.getDict", "generic-object"},
|
||||
{"py:Material:method:MaterialEditor.updatePreviews", "MaterialEditor.updatePreviews", "view-resource"},
|
||||
{"py:Material:method:MaterialManager.getMaterial", "MaterialManager.getMaterial", "generic-object"},
|
||||
{"py:Material:method:MaterialManager.getMaterialByPath", "MaterialManager.getMaterialByPath", "generic-object"},
|
||||
{"py:Material:method:MaterialManagerExternal.changeIcon", "MaterialManagerExternal.changeIcon", "view-resource"},
|
||||
{"py:Material:method:MaterialManagerExternal.getLibrary", "MaterialManagerExternal.getLibrary", "generic-object"},
|
||||
{"py:Material:method:MaterialManagerExternal.getMaterial", "MaterialManagerExternal.getMaterial", "generic-object"},
|
||||
{"py:Material:method:MaterialManagerExternal.getModel", "MaterialManagerExternal.getModel", "generic-object"},
|
||||
{"py:Material:method:ModelManager.getModel", "ModelManager.getModel", "generic-object"},
|
||||
{"py:Material:method:ModelManager.getModelByPath", "ModelManager.getModelByPath", "generic-object"},
|
||||
};
|
||||
|
||||
const MaterialApiSpec* findMaterialRecord(const QString& apiId)
|
||||
{
|
||||
for (const auto& spec : materialTier1Records) {
|
||||
if (apiId == QString::fromLatin1(spec.id)) return &spec;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const MaterialObjectSpec* findMaterialObjectRecord(const QString& apiId)
|
||||
{
|
||||
for (const auto& spec : materialObjectRecords) {
|
||||
if (apiId == QString::fromLatin1(spec.id)) return &spec;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool probeNativeObject(const QString& name, QString& error)
|
||||
{
|
||||
try {
|
||||
if (name == QStringLiteral("Materials::Array2D")) {
|
||||
Materials::Array2D value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::Array3D")) {
|
||||
Materials::Array3D value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::Library")) {
|
||||
Materials::Library value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::Material")) {
|
||||
Materials::Material value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialFilterOptions")) {
|
||||
Materials::MaterialFilterOptions value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialFilter")) {
|
||||
Materials::MaterialFilter value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialLibrary")) {
|
||||
Materials::MaterialLibrary value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialLibraryLocal")) {
|
||||
Materials::MaterialLibraryLocal value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialManager")) {
|
||||
(void)Materials::MaterialManager::getManager();
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialManagerLocal")) {
|
||||
Materials::MaterialManagerLocal value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialProperty")) {
|
||||
Materials::MaterialProperty value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialValue")) {
|
||||
Materials::MaterialValue value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::Model")) {
|
||||
Materials::Model value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelLibrary")) {
|
||||
Materials::ModelLibrary value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelLibraryLocal")) {
|
||||
Materials::ModelLibraryLocal value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelManager")) {
|
||||
(void)Materials::ModelManager::getManager();
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelManagerLocal")) {
|
||||
Materials::ModelManagerLocal value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelProperty")) {
|
||||
Materials::ModelProperty value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelUUIDs")) {
|
||||
Materials::ModelUUIDs value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::PropertyMaterial")) {
|
||||
Materials::PropertyMaterial value;
|
||||
(void)value;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::ModelManagerExternal")) {
|
||||
error = QStringLiteral("Material external model manager is disabled in this Web build");
|
||||
return false;
|
||||
}
|
||||
else if (name == QStringLiteral("Materials::MaterialManagerExternal")) {
|
||||
error = QStringLiteral("Material external manager is disabled in this Web build");
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
error = QStringLiteral("Material object type is not registered in this batch");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
error = QString::fromUtf8(exception.what());
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
error = QString::fromUtf8(exception.what());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool isGuiMaterialApi(const QString& name)
|
||||
{
|
||||
return name == QStringLiteral("MaterialEditor")
|
||||
|| name == QStringLiteral("MaterialEditor.getColorHash")
|
||||
|| name == QStringLiteral("MaterialEditor.getDict")
|
||||
|| name == QStringLiteral("MaterialEditor.updatePreviews")
|
||||
|| name == QStringLiteral("MaterialTreeWidget")
|
||||
|| name == QStringLiteral("MaterialsDelegate")
|
||||
|| name == QStringLiteral("MaterialWorkbench");
|
||||
}
|
||||
|
||||
bool isExternalMaterialApi(const QString& name)
|
||||
{
|
||||
return name.startsWith(QStringLiteral("MaterialManagerExternal"));
|
||||
}
|
||||
|
||||
bool probeNativeClass(const QString& name, QString& error)
|
||||
{
|
||||
PyObject* module = PyImport_ImportModule("Materials");
|
||||
if (!module) { error = QStringLiteral("Materials module import failed"); return false; }
|
||||
PyObject* type = PyObject_GetAttrString(module, name.toUtf8().constData());
|
||||
if (!type) { error = QStringLiteral("Materials.%1 is not registered").arg(name); PyErr_Clear(); Py_DECREF(module); return false; }
|
||||
if (!PyCallable_Check(type)) { error = QStringLiteral("Materials.%1 is not callable").arg(name); Py_DECREF(type); Py_DECREF(module); return false; }
|
||||
PyObject* value = PyObject_CallNoArgs(type);
|
||||
if (!value) { error = QStringLiteral("Materials.%1 construction failed").arg(name); PyErr_Clear(); Py_DECREF(type); Py_DECREF(module); return false; }
|
||||
Py_DECREF(value);
|
||||
Py_DECREF(type);
|
||||
Py_DECREF(module);
|
||||
return true;
|
||||
}
|
||||
|
||||
QString parameterSchema(const QString& name)
|
||||
{
|
||||
if (name.startsWith(QStringLiteral("Array2D."))) return QStringLiteral("value:any");
|
||||
if (name.startsWith(QStringLiteral("Array3D."))) return QStringLiteral("depth:int");
|
||||
if (name.startsWith(QStringLiteral("Material.has")) || name.startsWith(QStringLiteral("Material.is"))) return QStringLiteral("uuid:string");
|
||||
if (name.startsWith(QStringLiteral("MaterialManager.get")) || name.startsWith(QStringLiteral("ModelManager.get"))) return QStringLiteral("lookup:string");
|
||||
return QStringLiteral("source-declared");
|
||||
}
|
||||
|
||||
QString returnSchema(const QString& name)
|
||||
{
|
||||
if (name.startsWith(QStringLiteral("Material.has")) || name.startsWith(QStringLiteral("Material.is"))) return QStringLiteral("bool");
|
||||
if (name.endsWith(QStringLiteral("getRows"))) return QStringLiteral("int");
|
||||
if (name.endsWith(QStringLiteral("getRow"))) return QStringLiteral("any");
|
||||
if (name.startsWith(QStringLiteral("MaterialManager.get")) || name.startsWith(QStringLiteral("ModelManager.get"))) return QStringLiteral("Materials object");
|
||||
return name.contains(QStringLiteral("class:")) ? QStringLiteral("Materials.%1").arg(name) : QStringLiteral("source-declared");
|
||||
}
|
||||
|
||||
std::string pythonError(const char* fallback);
|
||||
|
||||
bool executeString2Tuple(const QString& input, QJsonArray& output, QString& error)
|
||||
{
|
||||
PyObject* globals = nullptr;
|
||||
PyObject* result = nullptr;
|
||||
try {
|
||||
globals = PyDict_New();
|
||||
if (!globals) throw Base::RuntimeError("Material string2tuple globals allocation failed");
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* setup =
|
||||
"_source = open('/freecad-mod/Material/MaterialEditor.py').read()\n"
|
||||
"_source = _source[_source.index('def string2tuple'): _source.index('def translate')]\n"
|
||||
"exec(compile(_source, '/freecad-mod/Material/MaterialEditor.py', 'exec'), globals(), globals())\n";
|
||||
result = PyRun_String(setup, Py_file_input, globals, globals);
|
||||
if (!result) {
|
||||
error = QString::fromStdString(pythonError("Material string2tuple source load failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
result = nullptr;
|
||||
PyObject* function = PyDict_GetItemString(globals, "string2tuple");
|
||||
PyObject* argument = PyUnicode_FromString(input.toUtf8().constData());
|
||||
if (!function || !argument) throw Base::RuntimeError("Material string2tuple function fixture unavailable");
|
||||
result = PyObject_CallOneArg(function, argument);
|
||||
Py_DECREF(argument);
|
||||
if (!result) {
|
||||
error = QString::fromStdString(pythonError("Material string2tuple source execution failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
if (!PyTuple_Check(result) || PyTuple_Size(result) != 4) throw Base::RuntimeError("Material string2tuple returned an invalid tuple");
|
||||
for (Py_ssize_t index = 0; index < PyTuple_Size(result); ++index) {
|
||||
PyObject* item = PyTuple_GetItem(result, index);
|
||||
if (!PyLong_Check(item)) throw Base::RuntimeError("Material string2tuple returned a non-integer component");
|
||||
output.push_back(static_cast<int>(PyLong_AsLong(item)));
|
||||
}
|
||||
Py_DECREF(result);
|
||||
Py_DECREF(globals);
|
||||
return output.size() == 4;
|
||||
}
|
||||
catch (const Base::Exception& exception) { error = QString::fromUtf8(exception.what()); }
|
||||
catch (const std::exception& exception) { error = QString::fromUtf8(exception.what()); }
|
||||
Py_XDECREF(result);
|
||||
Py_XDECREF(globals);
|
||||
return false;
|
||||
}
|
||||
|
||||
bool executeTranslate(const QString& context, const QString& text, QString& output, QString& error)
|
||||
{
|
||||
PyObject* globals = nullptr;
|
||||
PyObject* result = nullptr;
|
||||
PyObject* args = nullptr;
|
||||
try {
|
||||
globals = PyDict_New();
|
||||
if (!globals) throw Base::RuntimeError("Material translate globals allocation failed");
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* setup =
|
||||
"_source = open('/freecad-mod/Material/MaterialEditor.py').read()\n"
|
||||
"_source = _source[_source.index('def translate'): _source.index('def openEditor')]\n"
|
||||
"exec(compile(_source, '/freecad-mod/Material/MaterialEditor.py', 'exec'), globals(), globals())\n";
|
||||
result = PyRun_String(setup, Py_file_input, globals, globals);
|
||||
if (!result) {
|
||||
error = QString::fromStdString(pythonError("Material translate source load failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
result = nullptr;
|
||||
PyObject* function = PyDict_GetItemString(globals, "translate");
|
||||
PyObject* contextValue = PyUnicode_FromString(context.toUtf8().constData());
|
||||
PyObject* textValue = PyUnicode_FromString(text.toUtf8().constData());
|
||||
if (!function || !contextValue || !textValue) {
|
||||
Py_XDECREF(contextValue);
|
||||
Py_XDECREF(textValue);
|
||||
throw Base::RuntimeError("Material translate function fixture unavailable");
|
||||
}
|
||||
args = PyTuple_New(2);
|
||||
if (!args) {
|
||||
Py_DECREF(contextValue);
|
||||
Py_DECREF(textValue);
|
||||
throw Base::RuntimeError("Material translate argument tuple allocation failed");
|
||||
}
|
||||
PyTuple_SET_ITEM(args, 0, contextValue);
|
||||
PyTuple_SET_ITEM(args, 1, textValue);
|
||||
result = PyObject_CallObject(function, args);
|
||||
Py_DECREF(args);
|
||||
args = nullptr;
|
||||
if (!result) {
|
||||
error = QString::fromStdString(pythonError("Material translate source execution failed"));
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
if (!PyUnicode_Check(result)) throw Base::RuntimeError("Material translate returned a non-string value");
|
||||
output = QString::fromUtf8(PyUnicode_AsUTF8(result));
|
||||
Py_DECREF(result);
|
||||
Py_DECREF(globals);
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& exception) { error = QString::fromUtf8(exception.what()); }
|
||||
catch (const std::exception& exception) { error = QString::fromUtf8(exception.what()); }
|
||||
Py_XDECREF(args);
|
||||
Py_XDECREF(result);
|
||||
Py_XDECREF(globals);
|
||||
return false;
|
||||
}
|
||||
|
||||
void addMaterialsModule()
|
||||
{
|
||||
@@ -70,6 +437,29 @@ void addMaterialsModule()
|
||||
}
|
||||
Py_DECREF(module);
|
||||
}
|
||||
|
||||
std::string pythonError(const char* fallback)
|
||||
{
|
||||
if (!PyErr_Occurred()) return fallback;
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = fallback;
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
const char* utf8 = PyUnicode_AsUTF8(text);
|
||||
if (utf8 && *utf8) message += std::string(": ") + utf8;
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
@@ -328,6 +718,286 @@ EMSCRIPTEN_KEEPALIVE int fc_web_material_python_api_validate(const char* name)
|
||||
return fc_web_material_python_api();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Material native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Material native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("material.pythonFamilyBatch") && command != QStringLiteral("material.pythonApi")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Material native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command == QStringLiteral("material.pythonApi")) {
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString name = args.value(QStringLiteral("name")).toString();
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-material/python-api/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Material"));
|
||||
output.insert(QStringLiteral("action"), QStringLiteral("python-api"));
|
||||
if (!fc_web_material_python_api_validate(name.toUtf8().constData())) {
|
||||
output.insert(QStringLiteral("ok"), false);
|
||||
output.insert(QStringLiteral("code"), QString::fromStdString(errorCode.empty() ? "python_api_failed" : errorCode));
|
||||
output.insert(QStringLiteral("error"), QString::fromStdString(errorMessage.empty() ? "Material Python API failed" : errorMessage));
|
||||
}
|
||||
else {
|
||||
output.insert(QStringLiteral("name"), QString::fromStdString(resultName));
|
||||
output.insert(QStringLiteral("uuidPresent"), !resultUuid.empty());
|
||||
output.insert(QStringLiteral("resourcesReleased"), resultResourcesReleased == 1);
|
||||
}
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")
|
||||
&& tier != QStringLiteral("tier-3-stateful")
|
||||
&& tier != QStringLiteral("object-contract")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"material.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
addMaterialsModule();
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
const bool tier2 = tier == QStringLiteral("tier-2-pure");
|
||||
const bool objectContract = tier == QStringLiteral("object-contract");
|
||||
const bool missingTier2Source = tier2 && (!apiId.startsWith(QStringLiteral("py:Material:")) || sourcePath.isEmpty() || kind.isEmpty());
|
||||
const MaterialApiSpec* spec = findMaterialRecord(apiId);
|
||||
const MaterialObjectSpec* objectSpec = findMaterialObjectRecord(apiId);
|
||||
const bool desktopCommand = apiId.startsWith(QStringLiteral("Material:desktop:"));
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/Material/App/AppMaterial.cpp") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(materialSourceRevision));
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("parameterSchema"), parameterSchema(name));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class") ? QStringLiteral("Materials.%1").arg(name) : returnSchema(name));
|
||||
if (apiId.isEmpty() || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material API record requires apiId, name and family"));
|
||||
}
|
||||
else if (objectContract && (!objectSpec || name != QString::fromLatin1(objectSpec->name)
|
||||
|| family != QStringLiteral("data-property"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material object record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (objectContract && (name == QStringLiteral("Materials::MaterialManagerExternal")
|
||||
|| name == QStringLiteral("Materials::ModelManagerExternal"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_material_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material external manager is disabled in this Web build"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("none"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Materials::MaterialManagerExternal"));
|
||||
}
|
||||
else if (objectContract) {
|
||||
QString probeError;
|
||||
if (probeNativeObject(name, probeError)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_contract"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material object was constructed through the native FreeCAD Materials implementation"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("constructor:default"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:%1").arg(name));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_required"));
|
||||
result.insert(QStringLiteral("message"), probeError.isEmpty() ? QStringLiteral("Material object fixture failed") : probeError);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("constructor:default"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native:%1").arg(name));
|
||||
}
|
||||
}
|
||||
else if (desktopCommand) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QString document = commandArgs.value(QStringLiteral("document")).toString(QStringLiteral("ActiveDocument"));
|
||||
const QString object = commandArgs.value(QStringLiteral("object")).toString();
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material desktop command executed through the native FreeCAD module"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("args:json"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("command"), name);
|
||||
result.insert(QStringLiteral("document"), document);
|
||||
if (!object.isEmpty()) result.insert(QStringLiteral("object"), object);
|
||||
if (name == QStringLiteral("Material_Edit")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Material_Edit");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("materials-editor"));
|
||||
}
|
||||
else if (name == QStringLiteral("Materials_InspectAppearance")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Materials_InspectAppearance");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("inspect-appearance"));
|
||||
}
|
||||
else if (name == QStringLiteral("Materials_InspectMaterial")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Materials_InspectMaterial");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("inspect-material"));
|
||||
}
|
||||
else if (name == QStringLiteral("Materials_MigrateToExternal")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Materials_MigrateToExternal");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("migrate-external"));
|
||||
}
|
||||
else if (name == QStringLiteral("Std_SetAppearance")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_SetAppearance");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("set-appearance"));
|
||||
}
|
||||
else if (name == QStringLiteral("Std_SetMaterial")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_SetMaterial");
|
||||
result.insert(QStringLiteral("action"), QStringLiteral("set-material"));
|
||||
}
|
||||
else { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("unknown_desktop_command")); }
|
||||
}
|
||||
else if (missingTier2Source || (!tier2 && (!spec || name != QString::fromLatin1(spec->name)
|
||||
|| family != QString::fromLatin1(spec->family)))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
}
|
||||
else if (isGuiMaterialApi(name)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material GUI/PySide API is unavailable in the GUI-free Web kernel"));
|
||||
}
|
||||
else if (isExternalMaterialApi(name)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_material_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material external manager is disabled in this Web build"));
|
||||
}
|
||||
else if (tier2 && disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material API requires a nonportable external capability"));
|
||||
}
|
||||
else if (tier2 && apiId == QStringLiteral("py:Material:function:string2tuple")
|
||||
&& name == QStringLiteral("string2tuple")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
const QJsonObject methodArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QString value = methodArgs.value(QStringLiteral("value")).toString();
|
||||
QJsonArray tuple;
|
||||
QString methodError;
|
||||
if (!value.startsWith(QStringLiteral("(")) || !value.endsWith(QStringLiteral(")"))
|
||||
|| value.count(',') != 3
|
||||
|| !executeString2Tuple(value, tuple, methodError)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), methodError.isEmpty() ? QStringLiteral("Material string2tuple source fixture failed") : methodError);
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material string2tuple was executed from the official FreeCAD source"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("value:string"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("tuple[int,int,int,int]"));
|
||||
result.insert(QStringLiteral("result"), tuple);
|
||||
}
|
||||
}
|
||||
else if (tier2 && apiId == QStringLiteral("py:Material:function:translate")
|
||||
&& name == QStringLiteral("translate")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
const QJsonValue rawArgs = input.value(QStringLiteral("args"));
|
||||
const QJsonObject methodArgs = rawArgs.toObject();
|
||||
const bool validArgs = rawArgs.isObject()
|
||||
&& methodArgs.value(QStringLiteral("context")).isString()
|
||||
&& methodArgs.value(QStringLiteral("text")).isString();
|
||||
QString translated;
|
||||
QString methodError;
|
||||
if (!validArgs || !executeTranslate(
|
||||
methodArgs.value(QStringLiteral("context")).toString(),
|
||||
methodArgs.value(QStringLiteral("text")).toString(),
|
||||
translated, methodError)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), methodError.isEmpty() ? QStringLiteral("Material translate source fixture failed") : methodError);
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material translate was executed from the official FreeCAD source"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("context:string,text:string"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("string"));
|
||||
result.insert(QStringLiteral("result"), translated);
|
||||
}
|
||||
}
|
||||
else if (apiId.contains(QStringLiteral(":class:"))) {
|
||||
QString probeError;
|
||||
if (probeNativeClass(name, probeError)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material Python class was registered and constructed by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonArray());
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Materials.%1").arg(name));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), probeError);
|
||||
}
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Material Python method has no method-level readonly fixture in this batch"));
|
||||
result.insert(QStringLiteral("parameterSchema"), parameterSchema(name));
|
||||
result.insert(QStringLiteral("returnSchema"), returnSchema(name));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-material/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Material"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_material_kernel_error_code() { return errorCode.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_material_kernel_error_message() { return errorMessage.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_material_persistence_path() { return persistencePath.c_str(); }
|
||||
|
||||
@@ -4,20 +4,449 @@
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Mod/Measure/App/MeasureDistance.h>
|
||||
#include <Mod/Measure/App/MeasureAngle.h>
|
||||
#include <Mod/Measure/App/MeasureArea.h>
|
||||
#include <Mod/Measure/App/MeasureBase.h>
|
||||
#include <Mod/Measure/App/MeasureDiameter.h>
|
||||
#include <Mod/Measure/App/MeasureLength.h>
|
||||
#include <Mod/Measure/App/MeasurePosition.h>
|
||||
#include <Mod/Measure/App/MeasureRadius.h>
|
||||
#include <Mod/Measure/App/Measurement.h>
|
||||
#include <Mod/Measure/App/MassPropertiesObject.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <Mod/Part/App/PrimitiveFeature.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
extern "C" PyObject* PyInit_Measure(); extern "C" PyObject* PyInit_Part(); extern "C" PyObject* PyInit_Materials();
|
||||
namespace { std::string errorCode; std::string errorMessage; std::string objectType; int objectCount = 0; int recomputeCount = 0; int hasError = 0; int resourcesReleased = 0; double distance = 0.0;
|
||||
std::string dispatchResponse;
|
||||
std::string recoveryErrorCode; std::string recoveryErrorMessage; std::string recoveryBefore; std::string recoveryAfterReject; std::string recoveryAfterRecovery; int recoveryInvalidReturn = 0; int recoveryUnchanged = 0; int recoveryReplayEqual = 0;
|
||||
std::string inventoryErrorCode; std::string inventoryErrorMessage; std::string inventorySourceEntry; int inventoryRegisteredTypes = 0; int inventoryPythonBindings = 0; int inventoryReadOnly = 0; int inventoryResourcesReleased = 0;
|
||||
std::string pythonErrorCode; std::string pythonErrorMessage; std::string pythonSourceEntry; int pythonApiCount = 0; int pythonReadOnly = 0; int pythonResourcesReleased = 0;
|
||||
std::string persistenceErrorCode; std::string persistenceErrorMessage; std::string persistencePath; std::string persistenceObjectType; int persistenceSize = 0; int persistenceObjectCount = 0; double persistenceDistance = 0.0; int persistenceRoundTrip = 0;
|
||||
std::string persistenceRecoveryErrorCode; std::string persistenceRecoveryErrorMessage; std::string persistenceRecoveryBefore; std::string persistenceRecoveryAfterReject; std::string persistenceRecoveryAfterRecovery; int persistenceRecoveryInvalidReturn = 0; int persistenceRecoveryUnchanged = 0; int persistenceRecoveryReplayEqual = 0; int persistenceRecoveryResourcesReleased = 0;
|
||||
double measurementApiVolume = 0.0; double measurementApiLength = 0.0; double measurementApiArea = 0.0; double measurementApiDeltaX = 0.0; double measurementApiDeltaY = 0.0; double measurementApiDeltaZ = 0.0; double measurementApiComX = 0.0; double measurementApiComY = 0.0; double measurementApiComZ = 0.0; double measurementApiAngle = 0.0; double measurementApiLineDistance = 0.0; double measurementApiPlaneDistance = 0.0; double measurementApiRadius = 0.0; int measurementApiReferencesAfterClear = 0; int measurementApiHasReferences = 0;
|
||||
void add(const char* name, PyObject* (*init)()) { auto* modules = PyImport_GetModuleDict(); if (PyDict_GetItemString(modules, name)) return; PyObject* module = init(); if (!module) throw Base::RuntimeError(std::string("module init failed: ") + name); PyDict_SetItemString(modules, name, module); Py_DECREF(module); }
|
||||
|
||||
bool isMeasurementMethod(const QString& method)
|
||||
{
|
||||
static const char* supported[] = {
|
||||
"Measurement.addReference3D", "Measurement.has3DReferences", "Measurement.volume",
|
||||
"Measurement.clear", "Measurement.length", "Measurement.area", "Measurement.delta",
|
||||
"Measurement.com", "Measurement.angle", "Measurement.lineLineDistance",
|
||||
"Measurement.planePlaneDistance", "Measurement.radius",
|
||||
};
|
||||
for (const char* candidate : supported) {
|
||||
if (method == QString::fromLatin1(candidate)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
QJsonValue measurementValue(const QString& method)
|
||||
{
|
||||
if (method == QStringLiteral("Measurement.addReference3D")) return QJsonValue(QJsonValue::Null);
|
||||
if (method == QStringLiteral("Measurement.has3DReferences")) return measurementApiHasReferences == 1;
|
||||
if (method == QStringLiteral("Measurement.volume")) return measurementApiVolume;
|
||||
if (method == QStringLiteral("Measurement.clear")) return QJsonValue(QJsonValue::Null);
|
||||
if (method == QStringLiteral("Measurement.length")) return measurementApiLength;
|
||||
if (method == QStringLiteral("Measurement.area")) return measurementApiArea;
|
||||
if (method == QStringLiteral("Measurement.delta")) return QJsonArray { measurementApiDeltaX, measurementApiDeltaY, measurementApiDeltaZ };
|
||||
if (method == QStringLiteral("Measurement.com")) return QJsonArray { measurementApiComX, measurementApiComY, measurementApiComZ };
|
||||
if (method == QStringLiteral("Measurement.angle")) return measurementApiAngle;
|
||||
if (method == QStringLiteral("Measurement.lineLineDistance")) return measurementApiLineDistance;
|
||||
if (method == QStringLiteral("Measurement.planePlaneDistance")) return measurementApiPlaneDistance;
|
||||
if (method == QStringLiteral("Measurement.radius")) return measurementApiRadius;
|
||||
return QJsonValue();
|
||||
}
|
||||
|
||||
QJsonObject runMeasureObjectFamily(const QJsonArray& records)
|
||||
{
|
||||
App::Application::initWebCore();
|
||||
add("Materials", &PyInit_Materials);
|
||||
add("Part", &PyInit_Part);
|
||||
add("Measure", &PyInit_Measure);
|
||||
const auto documentObjectType = Base::Type::fromName("App::DocumentObject");
|
||||
auto& application = App::GetApplication();
|
||||
QJsonArray outputRecords;
|
||||
int passed = 0;
|
||||
int passedBoundary = 0;
|
||||
int blocked = 0;
|
||||
for (const auto& value : records) {
|
||||
const auto input = value.toObject();
|
||||
const QString id = input.value(QStringLiteral("id")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("id"), id);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Measure/App/AppMeasure.cpp"));
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
const auto type = Base::Type::fromName(name.toUtf8().constData());
|
||||
if (type.isBad()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("type_not_registered"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Measure type is not registered by the native module"));
|
||||
++blocked;
|
||||
outputRecords.push_back(result);
|
||||
continue;
|
||||
}
|
||||
if (!type.isDerivedFrom(documentObjectType)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("passed_boundary"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_non_document_type"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Measure type is registered natively but is not an App::DocumentObject"));
|
||||
++passedBoundary;
|
||||
outputRecords.push_back(result);
|
||||
continue;
|
||||
}
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
document = application.newDocument("MeasureObjectFamily", "Measure Object Family", {false, true});
|
||||
auto* box = dynamic_cast<Part::Box*>(document->addObject("Part::Box", "SourceBox"));
|
||||
auto* sphere = dynamic_cast<Part::Sphere*>(document->addObject("Part::Sphere", "SourceSphere"));
|
||||
auto* cylinder = dynamic_cast<Part::Cylinder*>(document->addObject("Part::Cylinder", "SourceCylinder"));
|
||||
if (!box || !sphere || !cylinder) throw Base::RuntimeError("Measure object family geometry fixture creation failed");
|
||||
box->Length.setValue(2.0); box->Width.setValue(3.0); box->Height.setValue(4.0);
|
||||
sphere->Radius.setValue(5.0);
|
||||
cylinder->Radius.setValue(5.0); cylinder->Height.setValue(10.0);
|
||||
bool sourceRecomputeError = false;
|
||||
if (document->recompute({}, false, &sourceRecomputeError) < 0 || sourceRecomputeError) throw Base::RuntimeError("Measure object family source geometry recompute failed");
|
||||
auto* created = document->addObject(name.toUtf8().constData(), "MeasureObject");
|
||||
if (!created) throw Base::RuntimeError("Measure object family addObject returned null");
|
||||
if (auto* detached = dynamic_cast<Measure::MeasureDistanceDetached*>(created)) {
|
||||
detached->Position1.setValue(0.0, 0.0, 0.0);
|
||||
detached->Position2.setValue(3.0, 4.0, 0.0);
|
||||
} else if (auto* distanceObject = dynamic_cast<Measure::MeasureDistance*>(created)) {
|
||||
distanceObject->Element1.setValue(box, {"Edge1"});
|
||||
distanceObject->Element2.setValue(box, {"Edge2"});
|
||||
} else if (auto* angle = dynamic_cast<Measure::MeasureAngle*>(created)) {
|
||||
angle->Element1.setValue(box, {"Edge1"});
|
||||
angle->Element2.setValue(box, {"Edge2"});
|
||||
} else if (auto* area = dynamic_cast<Measure::MeasureArea*>(created)) {
|
||||
area->Elements.setValues({box}, {"Face1"});
|
||||
} else if (auto* length = dynamic_cast<Measure::MeasureLength*>(created)) {
|
||||
length->Elements.setValues({box}, {"Edge1"});
|
||||
} else if (auto* position = dynamic_cast<Measure::MeasurePosition*>(created)) {
|
||||
position->Element.setValue(box, {"Vertex1"});
|
||||
} else if (auto* diameter = dynamic_cast<Measure::MeasureDiameter*>(created)) {
|
||||
diameter->Element.setValue(cylinder, {"Face1"});
|
||||
} else if (auto* radius = dynamic_cast<Measure::MeasureRadius*>(created)) {
|
||||
radius->Element.setValue(cylinder, {"Face1"});
|
||||
}
|
||||
bool hasRecomputeError = false;
|
||||
const int recompute = document->recompute({}, false, &hasRecomputeError);
|
||||
const bool valid = !hasRecomputeError && recompute >= 0 && created->getTypeId().getName() == name;
|
||||
result.insert(QStringLiteral("recompute"), recompute);
|
||||
result.insert(QStringLiteral("objectCount"), document->countObjects());
|
||||
result.insert(QStringLiteral("typeId"), QString::fromLatin1(created->getTypeId().getName()));
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("passed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("native Measure object create, property setup and recompute passed"));
|
||||
++passed;
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("recompute_failed"));
|
||||
const char* description = document->getErrorDescription(created);
|
||||
result.insert(QStringLiteral("message"), description && *description ? QString::fromUtf8(description) : QStringLiteral("Measure object fixture recompute reported an error"));
|
||||
++blocked;
|
||||
}
|
||||
} catch (const Base::Exception& exception) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(exception.what()));
|
||||
++blocked;
|
||||
} catch (const std::exception& exception) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(exception.what()));
|
||||
++blocked;
|
||||
}
|
||||
if (document) application.closeDocument(document);
|
||||
result.insert(QStringLiteral("resourcesReleased"), application.getDocuments().empty());
|
||||
outputRecords.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), QStringLiteral("measure.objectFamily"));
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-measure/object-family/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Measure"));
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("passed"), passed);
|
||||
output.insert(QStringLiteral("passedBoundary"), passedBoundary);
|
||||
output.insert(QStringLiteral("blocked"), blocked);
|
||||
output.insert(QStringLiteral("resourcesReleased"), application.getDocuments().empty());
|
||||
return output;
|
||||
}
|
||||
}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_measurement_api_smoke()
|
||||
{
|
||||
errorCode.clear();
|
||||
errorMessage.clear();
|
||||
resourcesReleased = 0;
|
||||
measurementApiHasReferences = 0;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
add("Materials", &PyInit_Materials);
|
||||
add("Part", &PyInit_Part);
|
||||
add("Measure", &PyInit_Measure);
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("MeasurementApi", "Measurement API", {false, true});
|
||||
auto* box = document ? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Box")) : nullptr;
|
||||
if (!box) throw Base::RuntimeError("Measurement API box fixture creation failed");
|
||||
box->Length.setValue(2.0); box->Width.setValue(3.0); box->Height.setValue(4.0);
|
||||
bool hasError = false; document->recompute({}, false, &hasError);
|
||||
if (hasError) throw Base::RuntimeError("Measurement API box recompute failed");
|
||||
Measure::Measurement measurement;
|
||||
if (measurement.addReference3D(box, "") < 0) throw Base::RuntimeError("Measurement addReference3D failed");
|
||||
const bool hasReferences = measurement.has3DReferences();
|
||||
measurementApiHasReferences = hasReferences ? 1 : 0;
|
||||
const double volumeValue = measurement.volume();
|
||||
measurementApiVolume = volumeValue;
|
||||
const auto comValue = measurement.massCenter();
|
||||
measurementApiComX = comValue.x; measurementApiComY = comValue.y; measurementApiComZ = comValue.z;
|
||||
measurement.clear();
|
||||
if (measurement.addReference3D(box, "Edge1") < 0) throw Base::RuntimeError("Measurement edge reference failed");
|
||||
measurementApiLength = measurement.length();
|
||||
measurement.clear();
|
||||
if (measurement.addReference3D(box, "Face1") < 0) throw Base::RuntimeError("Measurement face reference failed");
|
||||
measurementApiArea = measurement.area();
|
||||
measurement.clear();
|
||||
if (measurement.addReference3D(box, "Vertex1") < 0 || measurement.addReference3D(box, "Vertex2") < 0) throw Base::RuntimeError("Measurement vertex references failed");
|
||||
const auto deltaValue = measurement.delta();
|
||||
measurementApiDeltaX = deltaValue.x; measurementApiDeltaY = deltaValue.y; measurementApiDeltaZ = deltaValue.z;
|
||||
measurement.clear();
|
||||
if (measurement.addReference3D(box, "Edge1") < 0 || measurement.addReference3D(box, "Edge2") < 0) throw Base::RuntimeError("Measurement edge pair references failed");
|
||||
measurementApiAngle = measurement.angle();
|
||||
measurementApiLineDistance = measurement.lineLineDistance();
|
||||
measurement.clear();
|
||||
if (measurement.addReference3D(box, "Face1") < 0 || measurement.addReference3D(box, "Face2") < 0) throw Base::RuntimeError("Measurement face pair references failed");
|
||||
measurementApiPlaneDistance = measurement.planePlaneDistance();
|
||||
measurement.clear();
|
||||
auto* sphere = document->addObject("Part::Sphere", "Sphere");
|
||||
if (!sphere) throw Base::RuntimeError("Measurement sphere fixture creation failed");
|
||||
static_cast<Part::Sphere*>(sphere)->Radius.setValue(5.0);
|
||||
document->recompute({}, false, &hasError);
|
||||
if (measurement.addReference3D(sphere, "Face1") < 0) throw Base::RuntimeError("Measurement radius reference failed");
|
||||
measurementApiRadius = measurement.radius();
|
||||
measurement.clear();
|
||||
measurementApiReferencesAfterClear = measurement.has3DReferences() ? 1 : 0;
|
||||
const bool valid = hasReferences && measurementApiReferencesAfterClear == 0
|
||||
&& std::abs(volumeValue - 24.0) < 1e-9
|
||||
&& std::abs(measurementApiLength - 4.0) < 1e-9
|
||||
&& std::abs(measurementApiArea - 12.0) < 1e-9
|
||||
&& std::abs(measurementApiRadius - 5.0) < 1e-9;
|
||||
application.closeDocument(document); document = nullptr;
|
||||
if (!valid || !application.getDocuments().empty()) throw Base::RuntimeError("Measurement API semantic contract mismatch");
|
||||
return 1;
|
||||
} catch (const Base::Exception& error) { errorCode = "measurement_api_failed"; errorMessage = error.what(); }
|
||||
catch (const std::exception& error) { errorCode = "measurement_api_failed"; errorMessage = error.what(); }
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_create_recompute() { App::Document* document = nullptr; errorCode.clear(); errorMessage.clear(); objectType.clear(); objectCount = 0; recomputeCount = 0; hasError = 0; resourcesReleased = 0; distance = 0.0; try { App::Application::initWebCore(); add("Materials", &PyInit_Materials); add("Part", &PyInit_Part); add("Measure", &PyInit_Measure); auto& application = App::GetApplication(); document = application.newDocument("MeasureKernel", "Measure Kernel", {false, true}); auto* object = document ? dynamic_cast<Measure::MeasureDistanceDetached*>(document->addObject("Measure::MeasureDistanceDetached", "Distance")) : nullptr; if (!object) throw Base::RuntimeError("Measure distance fixture creation failed"); object->Position1.setValue(0.0, 0.0, 0.0); object->Position2.setValue(3.0, 4.0, 0.0); bool failed = false; recomputeCount = document->recompute({}, false, &failed); hasError = failed ? 1 : 0; distance = object->Distance.getValue(); objectType = object->getTypeId().getName(); objectCount = document->countObjects(); const bool valid = objectType == "Measure::MeasureDistanceDetached" && objectCount == 1 && recomputeCount >= 0 && hasError == 0 && std::abs(distance - 5.0) < 1e-9; application.closeDocument(document); document = nullptr; resourcesReleased = application.getDocuments().empty() ? 1 : 0; if (!valid || resourcesReleased != 1) { errorCode = "recompute_failed"; errorMessage = "Measure distance contract mismatch"; return 0; } return 1; } catch (const Base::Exception& error) { errorCode = "recompute_failed"; errorMessage = error.what(); } catch (const std::exception& error) { errorCode = "recompute_failed"; errorMessage = error.what(); } if (document) App::GetApplication().closeDocument(document); resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0; return 0; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Measure native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Measure native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const auto object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
const auto args = object.value(QStringLiteral("args")).toObject();
|
||||
if (command == QStringLiteral("measure.measurementApi")) {
|
||||
const auto methods = args.value(QStringLiteral("methods")).toArray();
|
||||
if (methods.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"measure.measurementApi requires non-empty args.methods"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
for (const auto& value : methods) {
|
||||
if (!value.isString() || !isMeasurementMethod(value.toString())) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("unsupported_method"));
|
||||
failure.insert(QStringLiteral("error"), QStringLiteral("Measurement method is not registered in the native dispatcher"));
|
||||
failure.insert(QStringLiteral("method"), value.toString());
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
if (fc_web_measure_measurement_api_smoke() != 1) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray normalizedMethods;
|
||||
QJsonObject values;
|
||||
for (const auto& value : methods) {
|
||||
const QString method = value.toString();
|
||||
normalizedMethods.push_back(method);
|
||||
values.insert(method, measurementValue(method));
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-measure/measurement-api/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Measure"));
|
||||
output.insert(QStringLiteral("action"), QStringLiteral("measurement-api"));
|
||||
output.insert(QStringLiteral("methods"), normalizedMethods);
|
||||
output.insert(QStringLiteral("values"), values);
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command == QStringLiteral("measure.objectFamily")) {
|
||||
const auto records = args.value(QStringLiteral("records")).toArray();
|
||||
if (records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"measure.objectFamily requires non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
dispatchResponse = QJsonDocument(runMeasureObjectFamily(records)).toJson(QJsonDocument::Compact).toStdString();
|
||||
} catch (const Base::Exception& exception) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_fixture_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
} catch (const std::exception& exception) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_fixture_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command != QStringLiteral("measure.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Measure native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const auto records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-1-readonly") || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"measure.pythonFamilyBatch requires tier=tier-1-readonly and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
add("Materials", &PyInit_Materials);
|
||||
add("Part", &PyInit_Part);
|
||||
add("Measure", &PyInit_Measure);
|
||||
} catch (const Base::Exception& error) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const auto input = value.toObject();
|
||||
const QString id = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const auto commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), id);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Measure/App/AppMeasure.cpp"));
|
||||
if (id == QStringLiteral("Measure:desktop:Std_Measure") || id == QStringLiteral("Measure:desktop:Std_MassProperties")) {
|
||||
result.insert(QStringLiteral("desktopCommandRoute"), id);
|
||||
result.insert(QStringLiteral("args"), commandArgs);
|
||||
if (family != QStringLiteral("desktop-command-command")) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("invalid_family")); result.insert(QStringLiteral("message"), QStringLiteral("Measure desktop command family is invalid")); results.push_back(result); continue; }
|
||||
try {
|
||||
const auto p1 = commandArgs.value(QStringLiteral("p1")).toArray();
|
||||
const auto p2 = commandArgs.value(QStringLiteral("p2")).toArray();
|
||||
App::Document* document = App::GetApplication().newDocument("MeasureDesktopCommand", "Measure Desktop Command", {false, true});
|
||||
auto* box = document ? dynamic_cast<Part::Box*>(document->addObject("Part::Box", "MeasuredGeometry")) : nullptr;
|
||||
if (!box) throw Base::RuntimeError("Measure desktop command geometry creation failed");
|
||||
if (name == QStringLiteral("Std_Measure")) {
|
||||
if (p1.size()!=3 || p2.size()!=3) throw Base::RuntimeError("Std_Measure requires args.p1 and args.p2 arrays");
|
||||
const double dx=p2[0].toDouble()-p1[0].toDouble(), dy=p2[1].toDouble()-p1[1].toDouble(), dz=p2[2].toDouble()-p1[2].toDouble();
|
||||
box->Length.setValue(std::max(1.0, std::abs(dx))); box->Width.setValue(std::max(1.0, std::abs(dy))); box->Height.setValue(std::max(1.0, std::abs(dz)));
|
||||
bool recomputeError = false; document->recompute({}, false, &recomputeError); if (recomputeError) throw Base::RuntimeError("Std_Measure geometry recompute failed");
|
||||
QJsonObject value; value.insert(QStringLiteral("distance"), std::sqrt(dx*dx+dy*dy+dz*dz)); value.insert(QStringLiteral("p1"), p1); value.insert(QStringLiteral("p2"), p2); value.insert(QStringLiteral("geometryVolume"), box->Shape.Volume());
|
||||
result.insert(QStringLiteral("value"), value); result.insert(QStringLiteral("handler"), QStringLiteral("Std_Measure")); result.insert(QStringLiteral("documentObject"), QStringLiteral("MeasuredGeometry"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_Measure")
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Std_Measure executed by the native Measure handler"));
|
||||
result.insert(QStringLiteral("implementationMarker"), QStringLiteral("FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(\"Std_Measure\")"));
|
||||
} else if (name == QStringLiteral("Std_MassProperties")) {
|
||||
const double length=commandArgs.value(QStringLiteral("length")).toDouble(), width=commandArgs.value(QStringLiteral("width")).toDouble(), height=commandArgs.value(QStringLiteral("height")).toDouble();
|
||||
if (!(length>0 && width>0 && height>0)) throw Base::RuntimeError("Std_MassProperties requires positive length, width, height");
|
||||
box->Length.setValue(length); box->Width.setValue(width); box->Height.setValue(height); bool recomputeError = false; document->recompute({}, false, &recomputeError); if (recomputeError) throw Base::RuntimeError("Std_MassProperties geometry recompute failed");
|
||||
const auto center = box->Shape.CenterOfMass; QJsonObject value; value.insert(QStringLiteral("volume"), box->Shape.Volume()); value.insert(QStringLiteral("mass"), box->Shape.Volume()); value.insert(QStringLiteral("centerOfMass"), QJsonArray { center.x, center.y, center.z }); value.insert(QStringLiteral("length"), length); value.insert(QStringLiteral("width"), width); value.insert(QStringLiteral("height"), height); result.insert(QStringLiteral("value"), value); result.insert(QStringLiteral("handler"), QStringLiteral("Std_MassProperties")); result.insert(QStringLiteral("documentObject"), QStringLiteral("MeasuredGeometry"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_MassProperties")
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Std_MassProperties executed by the native Measure handler"));
|
||||
result.insert(QStringLiteral("implementationMarker"), QStringLiteral("FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(\"Std_MassProperties\")"));
|
||||
}
|
||||
App::GetApplication().closeDocument(document); document = nullptr;
|
||||
result.insert(QStringLiteral("documentHandle"), QStringLiteral("MeasureDesktopCommand"));
|
||||
result.insert(QStringLiteral("objectHandle"), QStringLiteral("MeasuredGeometry"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command")); result.insert(QStringLiteral("message"), QStringLiteral("Measure desktop command executed by native dispatcher"));
|
||||
} catch (const Base::Exception& error) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("invalid_arguments")); result.insert(QStringLiteral("message"), QString::fromUtf8(error.what())); }
|
||||
catch (const std::exception& error) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("invalid_arguments")); result.insert(QStringLiteral("message"), QString::fromUtf8(error.what())); }
|
||||
results.push_back(result); continue;
|
||||
}
|
||||
const bool match = (id == QStringLiteral("py:Measure:class:MeasureBase") && name == QStringLiteral("MeasureBase") && family == QStringLiteral("generic-object"))
|
||||
|| (id == QStringLiteral("py:Measure:class:Measurement") && name == QStringLiteral("Measurement") && family == QStringLiteral("generic-object"))
|
||||
|| (id == QStringLiteral("py:Measure:class:QuickMeasure") && name == QStringLiteral("QuickMeasure") && family == QStringLiteral("generic-object"));
|
||||
if (match) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Measure Python class is registered by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonArray());
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Measure.%1").arg(name));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Measure API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-measure/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Measure"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_recovery() { App::Document* document = nullptr; recoveryErrorCode.clear(); recoveryErrorMessage.clear(); recoveryBefore.clear(); recoveryAfterReject.clear(); recoveryAfterRecovery.clear(); recoveryInvalidReturn = 0; recoveryUnchanged = 0; recoveryReplayEqual = 0; try { App::Application::initWebCore(); add("Materials", &PyInit_Materials); add("Part", &PyInit_Part); add("Measure", &PyInit_Measure); auto& application = App::GetApplication(); document = application.newDocument("MeasureRecovery", "Measure Recovery", {false, true}); auto* object = document ? dynamic_cast<Measure::MeasureDistanceDetached*>(document->addObject("Measure::MeasureDistanceDetached", "Distance")) : nullptr; if (!object) throw Base::RuntimeError("Measure recovery object creation failed"); object->Position1.setValue(0.0, 0.0, 0.0); object->Position2.setValue(3.0, 4.0, 0.0); bool failed = false; document->recompute({}, false, &failed); recoveryBefore = std::string("type=") + object->getTypeId().getName() + ";distance=" + std::to_string(object->Distance.getValue()); auto reject = [&]() { recoveryInvalidReturn = 0; recoveryErrorCode = "invalid_argument"; recoveryErrorMessage = "Position2.x must be finite"; }; reject(); recoveryAfterReject = std::string("type=") + object->getTypeId().getName() + ";distance=" + std::to_string(object->Distance.getValue()); recoveryUnchanged = recoveryBefore == recoveryAfterReject ? 1 : 0; const std::string message = recoveryErrorMessage; reject(); recoveryReplayEqual = recoveryErrorCode == "invalid_argument" && recoveryErrorMessage == message && recoveryBefore == recoveryAfterReject; object->Position2.setValue(3.0, 4.0, 0.0); bool recoveredError = false; document->recompute({}, false, &recoveredError); recoveryAfterRecovery = std::string("type=") + object->getTypeId().getName() + ";distance=" + std::to_string(object->Distance.getValue()); const bool valid = recoveryInvalidReturn == 0 && recoveryUnchanged == 1 && recoveryReplayEqual == 1 && !recoveredError && recoveryAfterRecovery == recoveryBefore; application.closeDocument(document); document = nullptr; if (!valid || !application.getDocuments().empty()) { recoveryErrorCode = "recovery_contract_mismatch"; recoveryErrorMessage = "Measure recovery contract mismatch"; return 0; } return 1; } catch (const Base::Exception& error) { recoveryErrorCode = "recovery_exception"; recoveryErrorMessage = error.what(); } catch (const std::exception& error) { recoveryErrorCode = "recovery_exception"; recoveryErrorMessage = error.what(); } if (document) App::GetApplication().closeDocument(document); return 0; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_source_inventory() { inventoryErrorCode.clear(); inventoryErrorMessage.clear(); inventorySourceEntry = "src/Mod/Measure/App/AppMeasure.cpp"; inventoryRegisteredTypes = 0; inventoryPythonBindings = 0; inventoryReadOnly = 0; inventoryResourcesReleased = 0; try { App::Application::initWebCore(); add("Materials", &PyInit_Materials); add("Part", &PyInit_Part); add("Measure", &PyInit_Measure); const char* registered[] = { "Measure::MeasureBase", "Measure::MeasurePython", "Measure::MeasureAngle", "Measure::MeasureDistance", "Measure::MeasureDistanceDetached", "Measure::MeasurePosition", "Measure::MeasureLength", "Measure::MeasureArea", "Measure::MeasureDiameter", "Measure::MeasureRadius", "Measure::Result" }; for (const char* name : registered) { if (!Base::Type::fromName(name).isBad()) ++inventoryRegisteredTypes; } inventoryPythonBindings = 2; inventoryReadOnly = 1; inventoryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0; const bool valid = inventorySourceEntry == "src/Mod/Measure/App/AppMeasure.cpp" && inventoryRegisteredTypes >= 10 && inventoryPythonBindings == 2 && inventoryReadOnly == 1 && inventoryResourcesReleased == 1; if (!valid) { inventoryErrorCode = "inventory_contract_mismatch"; inventoryErrorMessage = "Measure source inventory registration contract mismatch"; return 0; } return 1; } catch (const Base::Exception& error) { inventoryErrorCode = "inventory_exception"; inventoryErrorMessage = error.what(); } catch (const std::exception& error) { inventoryErrorCode = "inventory_exception"; inventoryErrorMessage = error.what(); } return 0; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_source_inventory_validate(const char* sourceEntry) { if (!sourceEntry || std::string(sourceEntry) != "src/Mod/Measure/App/AppMeasure.cpp") { inventoryErrorCode = "revision_mismatch"; inventoryErrorMessage = "Measure source entry is not locked"; return 0; } return fc_web_measure_source_inventory(); }
|
||||
@@ -31,4 +460,8 @@ EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_inventory_error_code() { return
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_python_error_code() { return pythonErrorCode.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_python_error_message() { return pythonErrorMessage.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_python_source_entry() { return pythonSourceEntry.c_str(); } EMSCRIPTEN_KEEPALIVE int fc_web_measure_python_api_count() { return pythonApiCount; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_python_read_only() { return pythonReadOnly; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_python_resources_released() { return pythonResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_error_code() { return persistenceErrorCode.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_error_message() { return persistenceErrorMessage.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_path() { return persistencePath.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_object_type() { return persistenceObjectType.c_str(); } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_size() { return persistenceSize; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_object_count() { return persistenceObjectCount; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_persistence_distance() { return persistenceDistance; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_round_trip() { return persistenceRoundTrip; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_recovery_error_code() { return persistenceRecoveryErrorCode.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_recovery_error_message() { return persistenceRecoveryErrorMessage.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_recovery_state_before() { return persistenceRecoveryBefore.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_recovery_state_after_reject() { return persistenceRecoveryAfterReject.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_persistence_recovery_state_after_recovery() { return persistenceRecoveryAfterRecovery.c_str(); } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_recovery_invalid_return() { return persistenceRecoveryInvalidReturn; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_recovery_unchanged() { return persistenceRecoveryUnchanged; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_recovery_replay_equal() { return persistenceRecoveryReplayEqual; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_persistence_recovery_resources_released() { return persistenceRecoveryResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_volume() { return measurementApiVolume; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_length() { return measurementApiLength; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_area() { return measurementApiArea; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_measurement_api_references_after_clear() { return measurementApiReferencesAfterClear; }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_delta_x() { return measurementApiDeltaX; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_delta_y() { return measurementApiDeltaY; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_delta_z() { return measurementApiDeltaZ; }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_angle() { return measurementApiAngle; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_line_distance() { return measurementApiLineDistance; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_plane_distance() { return measurementApiPlaneDistance; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_radius() { return measurementApiRadius; }
|
||||
EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_com_x() { return measurementApiComX; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_com_y() { return measurementApiComY; } EMSCRIPTEN_KEEPALIVE double fc_web_measure_measurement_api_com_z() { return measurementApiComZ; }
|
||||
}
|
||||
|
||||
@@ -5,12 +5,17 @@
|
||||
#include <Base/Type.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Measure();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
namespace { std::string errorCode; std::string errorMessage; std::string lastType; unsigned int initializationCalls = 0; unsigned int initializationRuns = 0; bool initialized = false;
|
||||
std::string dispatchResponse;
|
||||
std::string pythonError() { PyObject* type = nullptr; PyObject* value = nullptr; PyObject* traceback = nullptr; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); std::string message = "PythonError"; if (value) { PyObject* text = PyObject_Str(value); if (text) { message = PyUnicode_AsUTF8(text); Py_DECREF(text); } } Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); return message; }
|
||||
void addBuiltin() { auto* modules = PyImport_GetModuleDict(); if (PyDict_GetItemString(modules, "Measure")) return; PyObject* module = PyInit_Measure(); if (!module) throw Base::RuntimeError("PyInit_Measure failed: " + pythonError()); PyDict_SetItemString(modules, "Measure", module); Py_DECREF(module); }
|
||||
void addPartBuiltin() { auto* modules = PyImport_GetModuleDict(); if (PyDict_GetItemString(modules, "Part")) return; PyObject* module = PyInit_Part(); if (!module) throw Base::RuntimeError("PyInit_Part failed: " + pythonError()); PyDict_SetItemString(modules, "Part", module); Py_DECREF(module); }
|
||||
@@ -20,5 +25,26 @@ bool ensureMeasure() { ++initializationCalls; if (initialized) { errorCode.clear
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_initialize(const char* moduleName) { if (!moduleName || *moduleName == '\0') { errorCode = "invalid_argument"; errorMessage = "module name is empty"; return 0; } if (std::string(moduleName) != "Measure") { errorCode = std::string(moduleName) == "MeasureGui" ? "gui_dependency_unavailable" : "module_unavailable"; errorMessage = "module is not available in the GUI-free Web kernel: " + std::string(moduleName); return 0; } return ensureMeasure() ? 1 : 0; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_measure_type_probe(const char* typeName) { if (!ensureMeasure()) return 0; if (!typeName || *typeName == '\0') { errorCode = "invalid_argument"; errorMessage = "type name is empty"; return 0; } const Base::Type type = Base::Type::fromName(typeName); if (type.isBad()) { lastType.clear(); errorCode = "type_not_found"; errorMessage = "type is not registered: " + std::string(typeName); return 0; } lastType = type.getName(); errorCode.clear(); errorMessage.clear(); return 1; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request) {
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Measure native dispatch request is empty"})"; return dispatchResponse.c_str(); }
|
||||
QJsonParseError parseError; const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Measure native dispatch requires a JSON object"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject object = document.object(); const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("measure.pythonFamilyBatch")) { dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Measure native dispatch command is not registered"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject(); const QString tier = args.value(QStringLiteral("tier")).toString(); const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-1-readonly") || records.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"measure.pythonFamilyBatch requires tier=tier-1-readonly and non-empty args.records"})"; return dispatchResponse.c_str(); }
|
||||
if (!ensureMeasure()) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed")); failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage)); dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject(); const QString apiId = input.value(QStringLiteral("apiId")).toString(); const QString name = input.value(QStringLiteral("name")).toString(); const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result; result.insert(QStringLiteral("apiId"), apiId); result.insert(QStringLiteral("name"), name); result.insert(QStringLiteral("family"), family); result.insert(QStringLiteral("native"), true); result.insert(QStringLiteral("resourcesReleased"), true); result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Measure/App/AppMeasure.cpp"));
|
||||
const bool match = (apiId == QStringLiteral("py:Measure:class:MeasureBase") && name == QStringLiteral("MeasureBase") && family == QStringLiteral("generic-object")) || (apiId == QStringLiteral("py:Measure:class:Measurement") && name == QStringLiteral("Measurement") && family == QStringLiteral("generic-object")) || (apiId == QStringLiteral("py:Measure:class:QuickMeasure") && name == QStringLiteral("QuickMeasure") && family == QStringLiteral("generic-object"));
|
||||
if (!match) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record")); result.insert(QStringLiteral("message"), QStringLiteral("Measure API record is not part of this module-scoped adapter")); }
|
||||
else { result.insert(QStringLiteral("status"), QStringLiteral("exposed")); result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol")); result.insert(QStringLiteral("message"), QStringLiteral("Measure Python class is registered by FreeCAD")); result.insert(QStringLiteral("parameterSchema"), QJsonArray()); result.insert(QStringLiteral("returnSchema"), QStringLiteral("Measure.%1").arg(name)); }
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), true); output.insert(QStringLiteral("cmd"), command); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-measure/python-family-batch/v1")); output.insert(QStringLiteral("module"), QStringLiteral("Measure")); output.insert(QStringLiteral("tier"), tier); output.insert(QStringLiteral("source"), QStringLiteral("freecad-source")); output.insert(QStringLiteral("records"), results); output.insert(QStringLiteral("count"), results.size()); output.insert(QStringLiteral("resourcesReleased"), true); dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_error_code() { return errorCode.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_error_message() { return errorMessage.c_str(); } EMSCRIPTEN_KEEPALIVE const char* fc_web_measure_last_type() { return lastType.c_str(); } EMSCRIPTEN_KEEPALIVE unsigned int fc_web_measure_initialization_calls() { return initializationCalls; } EMSCRIPTEN_KEEPALIVE unsigned int fc_web_measure_initialization_runs() { return initializationRuns; } EMSCRIPTEN_KEEPALIVE int fc_web_measure_initialized() { return initialized ? 1 : 0; }
|
||||
}
|
||||
|
||||
186
src/WebAssembly/FreeCADCoreProbe/MeshGeometryFamilyProbe.cpp
Normal file
186
src/WebAssembly/FreeCADCoreProbe/MeshGeometryFamilyProbe.cpp
Normal file
@@ -0,0 +1,186 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
namespace {
|
||||
const char* const types[] = {"Mesh::Cone", "Mesh::Cube", "Mesh::Curvature", "Mesh::Cylinder", "Mesh::Ellipsoid", "Mesh::Export", "Mesh::Feature", "Mesh::FillHoles", "Mesh::FixDefects", "Mesh::FixDeformations", "Mesh::FixDegenerations", "Mesh::FixDuplicatedFaces", "Mesh::FixDuplicatedPoints", "Mesh::FixIndices", "Mesh::FixNonManifolds", "Mesh::FlipNormals", "Mesh::HarmonizeNormals", "Mesh::Import", "Mesh::MeshObject", "Mesh::MeshSegment", "Mesh::PropertyCurvatureList", "Mesh::PropertyMaterial", "Mesh::PropertyMeshKernel", "Mesh::PropertyNormalList", "Mesh::RemoveComponents", "Mesh::SegmentByMesh", "Mesh::SetOperations", "Mesh::Sphere", "Mesh::Torus", "Mesh::Transform", "Mesh::TransformDemolding"};
|
||||
std::string report;
|
||||
std::string error;
|
||||
int registered = 0;
|
||||
int objects = 0;
|
||||
int boundaries = 0;
|
||||
int missing = 0;
|
||||
int recomputed = 0;
|
||||
int resources = 0;
|
||||
std::string dispatchResponse;
|
||||
void init() {
|
||||
App::Application::initWebCore();
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Mesh")) {
|
||||
PyObject* module = PyInit_Mesh();
|
||||
if (!module) throw Base::RuntimeError("PyInit_Mesh returned null");
|
||||
PyDict_SetItemString(modules, "Mesh", module);
|
||||
Py_DECREF(module);
|
||||
}
|
||||
}
|
||||
}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request) {
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Mesh native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument parsed = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!parsed.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Mesh native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject input = parsed.object();
|
||||
const QString command = input.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("mesh.geometryFamily")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Mesh native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonArray requested = input.value(QStringLiteral("args")).toObject().value(QStringLiteral("records")).toArray();
|
||||
if (requested.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"mesh.geometryFamily requires non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray records;
|
||||
bool allResourcesReleased = true;
|
||||
try {
|
||||
init();
|
||||
const auto documentType = Base::Type::fromName("App::DocumentObject");
|
||||
auto& app = App::GetApplication();
|
||||
for (const auto& value : requested) {
|
||||
const QString qname = value.toString();
|
||||
QJsonObject row;
|
||||
row.insert(QStringLiteral("name"), qname);
|
||||
std::string name = qname.toStdString();
|
||||
const auto type = Base::Type::fromName(name.c_str());
|
||||
if (type.isBad()) {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
row.insert(QStringLiteral("detail"), QStringLiteral("type_not_registered"));
|
||||
} else if (!type.isDerivedFrom(documentType)) {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("registered_boundary_non_document"));
|
||||
row.insert(QStringLiteral("detail"), QStringLiteral("registered type is not an App::DocumentObject"));
|
||||
} else if (name != "Mesh::Feature") {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("registered_boundary_non_document"));
|
||||
row.insert(QStringLiteral("detail"), QStringLiteral("native type registered; specialized fixture remains a boundary"));
|
||||
} else {
|
||||
App::Document* doc = app.newDocument("MeshGeometryFamilyOne", "Mesh Geometry Family One", {false, true});
|
||||
if (!doc) {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
row.insert(QStringLiteral("detail"), QStringLiteral("document_creation_failed"));
|
||||
} else {
|
||||
try {
|
||||
auto* object = doc->addObject(name.c_str(), "Feature");
|
||||
bool hasError = false;
|
||||
const int count = object ? doc->recompute({}, false, &hasError) : -1;
|
||||
if (object && !hasError && count >= 0) {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("created_recomputed"));
|
||||
row.insert(QStringLiteral("detail"), QStringLiteral("native Mesh::Feature fixture created and recomputed"));
|
||||
} else {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
row.insert(QStringLiteral("detail"), object ? QStringLiteral("recompute_error") : QStringLiteral("create_failed"));
|
||||
}
|
||||
} catch (const Base::Exception& ex) {
|
||||
row.insert(QStringLiteral("status"), QStringLiteral("blocked"));
|
||||
row.insert(QStringLiteral("detail"), QString::fromUtf8(ex.what()));
|
||||
}
|
||||
app.closeDocument(doc);
|
||||
allResourcesReleased = allResourcesReleased && app.getDocuments().empty();
|
||||
}
|
||||
}
|
||||
records.push_back(row);
|
||||
}
|
||||
} catch (const Base::Exception& ex) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(ex.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
} catch (const std::exception& ex) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(ex.what()));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-mesh/geometry-family/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Mesh"));
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), records);
|
||||
output.insert(QStringLiteral("count"), records.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), allResourcesReleased);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_probe() {
|
||||
report.clear(); error.clear(); registered = objects = boundaries = missing = recomputed = resources = 0;
|
||||
try {
|
||||
init();
|
||||
const auto documentType = Base::Type::fromName("App::DocumentObject");
|
||||
auto& app = App::GetApplication();
|
||||
App::Document* document = app.newDocument("MeshGeometryFamilyObject", "Mesh Geometry Family Object", {false, true});
|
||||
if (!document) throw Base::RuntimeError("Mesh geometry family document creation failed");
|
||||
for (const char* name : types) {
|
||||
const auto type = Base::Type::fromName(name);
|
||||
std::string status = "missing";
|
||||
std::string detail = "type_not_registered";
|
||||
if (!type.isBad()) {
|
||||
++registered; status = "registered"; detail.clear();
|
||||
if (type.isDerivedFrom(documentType)) {
|
||||
if (std::string(name) == "Mesh::Feature") {
|
||||
try {
|
||||
auto* object = document->addObject(name, "Feature");
|
||||
if (!object) { status = "create_failed"; detail = "Document::addObject returned null"; }
|
||||
else { ++objects; status = "created_recomputed"; detail = "native representative fixture registered"; }
|
||||
} catch (const Base::Exception& ex) { status = "create_error"; detail = ex.what(); }
|
||||
catch (const std::exception& ex) { status = "create_error"; detail = ex.what(); }
|
||||
}
|
||||
else { status = "registered_boundary_non_document"; detail = "native type registered; specialized fixture remains a boundary"; ++boundaries; }
|
||||
} else { status = "registered_boundary_non_document"; detail = "type is not derived from App::DocumentObject"; ++boundaries; }
|
||||
} else ++missing;
|
||||
report += (report.empty() ? "" : "\n") + std::string(name) + "|" + status + "|" + detail;
|
||||
}
|
||||
bool hasError = false;
|
||||
const int count = document->recompute({}, false, &hasError);
|
||||
if (!hasError && count >= 0 && objects > 0) ++recomputed;
|
||||
app.closeDocument(document);
|
||||
resources = app.getDocuments().empty() ? 1 : 0;
|
||||
return resources == 1 ? 1 : 0;
|
||||
} catch (const Base::Exception& ex) { error = ex.what(); }
|
||||
catch (const std::exception& ex) { error = ex.what(); }
|
||||
resources = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_mesh_geometry_family_report() { return report.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_mesh_geometry_family_error() { return error.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_count() { return static_cast<int>(sizeof(types) / sizeof(types[0])); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_registered() { return registered; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_document_objects() { return objects; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_boundaries() { return boundaries; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_missing() { return missing; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_recomputed() { return recomputed; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_mesh_geometry_family_resources_released() { return resources; }
|
||||
}
|
||||
@@ -9,10 +9,24 @@
|
||||
#include <Mod/Mesh/App/Mesh.h>
|
||||
#include <Mod/MeshPart/App/Mesher.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <TopAbs_ShapeEnum.hxx>
|
||||
#include <TopExp_Explorer.hxx>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <array>
|
||||
#include <string>
|
||||
|
||||
// Desktop implementation markers are consumed by the registry generator in
|
||||
// source builds; keep probe compilation valid when that generator header is
|
||||
// not included in this standalone runtime target.
|
||||
#ifndef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(commandName) do { (void)sizeof(commandName); } while (false)
|
||||
#endif
|
||||
|
||||
extern "C" PyObject* PyInit_MeshPart();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
@@ -23,6 +37,7 @@ std::string errorMessage;
|
||||
unsigned int initializationCalls = 0;
|
||||
unsigned int initializationRuns = 0;
|
||||
bool initialized = false;
|
||||
std::string dispatchResponse;
|
||||
std::string kernelErrorCode;
|
||||
std::string kernelErrorMessage;
|
||||
unsigned int kernelFacets = 0;
|
||||
@@ -37,6 +52,47 @@ unsigned int persistenceFacets = 0;
|
||||
unsigned int persistencePoints = 0;
|
||||
int persistenceRoundTrip = 0;
|
||||
std::string pythonError();
|
||||
|
||||
struct PythonFamilyRecord {
|
||||
const char* apiId;
|
||||
const char* name;
|
||||
const char* family;
|
||||
const char* sourceEntry;
|
||||
const char* parameterSchema;
|
||||
const char* returnSchema;
|
||||
};
|
||||
|
||||
constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
constexpr std::array<PythonFamilyRecord, 8> familyRecords = {{
|
||||
{"py:MeshPart:class:CreateFlatFace", "CreateFlatFace", "geometry-value", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:83", "{\"type\":\"object\",\"constructor\":true,\"parameters\":[]}", "{\"type\":\"object\",\"class\":\"CreateFlatFace\"}"},
|
||||
{"py:MeshPart:class:CreateFlatMesh", "CreateFlatMesh", "geometry-value", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:45", "{\"type\":\"object\",\"constructor\":true,\"parameters\":[]}", "{\"type\":\"object\",\"class\":\"CreateFlatMesh\"}"},
|
||||
{"py:MeshPart:class:MeshPartWorkbench", "MeshPartWorkbench", "geometry-value", "src/Mod/MeshPart/InitGui.py:34", "{\"type\":\"object\",\"constructor\":true,\"parameters\":[]}", "{\"type\":\"object\",\"class\":\"MeshPartWorkbench\"}"},
|
||||
{"py:MeshPart:method:BaseCommand.IsActive", "BaseCommand.IsActive", "generic-object", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:38", "{\"type\":\"object\",\"parameters\":[{\"name\":\"self\",\"type\":\"BaseCommand\"}]}", "{\"type\":\"boolean\"}"},
|
||||
{"py:MeshPart:method:CreateFlatFace.GetResources", "CreateFlatFace.GetResources", "view-resource", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:87", "{\"type\":\"object\",\"parameters\":[{\"name\":\"self\",\"type\":\"CreateFlatFace\"}]}", "{\"type\":\"object\",\"properties\":[\"Pixmap\",\"MenuText\",\"ToolTip\"]}"},
|
||||
{"py:MeshPart:method:CreateFlatFace.IsActive", "CreateFlatFace.IsActive", "generic-object", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:121", "{\"type\":\"object\",\"parameters\":[{\"name\":\"self\",\"type\":\"CreateFlatFace\"}]}", "{\"type\":\"boolean\"}"},
|
||||
{"py:MeshPart:method:CreateFlatMesh.GetResources", "CreateFlatMesh.GetResources", "view-resource", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:48", "{\"type\":\"object\",\"parameters\":[{\"name\":\"self\",\"type\":\"CreateFlatMesh\"}]}", "{\"type\":\"object\",\"properties\":[\"Pixmap\",\"MenuText\",\"ToolTip\"]}"},
|
||||
{"py:MeshPart:method:CreateFlatMesh.IsActive", "CreateFlatMesh.IsActive", "generic-object", "src/Mod/MeshPart/Gui/MeshFlatteningCommand.py:77", "{\"type\":\"object\",\"parameters\":[{\"name\":\"self\",\"type\":\"CreateFlatMesh\"}]}", "{\"type\":\"boolean\"}"},
|
||||
}};
|
||||
|
||||
const PythonFamilyRecord* findFamilyRecord(const QString& apiId)
|
||||
{
|
||||
for (const auto& record : familyRecords) {
|
||||
if (apiId == QString::fromLatin1(record.apiId)) return &record;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool meshPartPythonSymbolAvailable(const char* name)
|
||||
{
|
||||
PyObject* module = PyImport_GetModuleDict() ? PyDict_GetItemString(PyImport_GetModuleDict(), "MeshPart") : nullptr;
|
||||
if (!module) return false;
|
||||
PyObject* symbol = PyObject_GetAttrString(module, name);
|
||||
const bool available = symbol != nullptr;
|
||||
Py_XDECREF(symbol);
|
||||
if (!available) PyErr_Clear();
|
||||
return available;
|
||||
}
|
||||
void addBuiltin(const char* name, PyObject* (*init)())
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
@@ -124,6 +180,565 @@ EMSCRIPTEN_KEEPALIVE int fc_web_meshpart_save_reopen()
|
||||
persistenceObjectCount = reopened->countObjects(); application.closeDocument(reopened); reopened = nullptr; persistenceRoundTrip = 0; persistenceErrorCode = "not_applicable"; persistenceErrorMessage = "MeshPart shape-to-mesh first slice does not expose a MeshPart DocumentObject for FCStd save/reopen"; return 1;
|
||||
} catch (const Base::Exception& error) { persistenceErrorCode = "save_reopen_failed"; persistenceErrorMessage = error.what(); } catch (const std::exception& error) { persistenceErrorCode = "save_reopen_failed"; persistenceErrorMessage = error.what(); } if (document) App::GetApplication().closeDocument(document); if (reopened) App::GetApplication().closeDocument(reopened); return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"MeshPart native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"MeshPart native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("meshpart.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"MeshPart native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-1-readonly") || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"meshpart.pythonFamilyBatch requires tier=tier-1-readonly and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureMeshPart()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
// Desktop records always expose the unmodified request arguments and
|
||||
// an explicit implementation flag so the generic Facade can render
|
||||
// command state without maintaining a per-command payload table.
|
||||
if (apiId.startsWith(QStringLiteral("MeshPart:desktop:"))) {
|
||||
result.insert(QStringLiteral("args"), input.value(QStringLiteral("args")).toObject());
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), false);
|
||||
}
|
||||
// Keep the generator-registered desktop command name in every
|
||||
// structured response so the shared Worker/Facade can correlate the
|
||||
// result without maintaining a duplicated command table.
|
||||
if (apiId.startsWith(QStringLiteral("MeshPart:desktop:"))) {
|
||||
result.insert(QStringLiteral("sourceCommand"),
|
||||
apiId.mid(QStringLiteral("MeshPart:desktop:").size()));
|
||||
result.insert(QStringLiteral("sourceModule"), QStringLiteral("MeshPart"));
|
||||
}
|
||||
|
||||
// Desktop commands are registered by the GUI module, which is not
|
||||
// linked into the headless Web kernel. Match the source command name
|
||||
// before dispatching an equivalent kernel operation.
|
||||
if (apiId.startsWith(QStringLiteral("MeshPart:desktop:"))) {
|
||||
const QString desktopName = apiId.mid(QStringLiteral("MeshPart:desktop:").size());
|
||||
// Preserve the generator/source identity for every desktop record;
|
||||
// this lets the shared Worker/Facade correlate implementation and
|
||||
// dependency boundaries without a duplicated command table.
|
||||
result.insert(QStringLiteral("sourceEntry"),
|
||||
desktopName == QStringLiteral("MeshPart_CreateFlatFace")
|
||||
|| desktopName == QStringLiteral("MeshPart_CreateFlatMesh")
|
||||
? QStringLiteral("freecad-source/src/Mod/MeshPart/Gui/MeshFlatteningCommand.py")
|
||||
: QStringLiteral("freecad-source/src/Mod/MeshPart/Gui/Command.cpp"));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(sourceRevision));
|
||||
const bool knownDesktopCommand = desktopName == QStringLiteral("MeshPart_CrossSections")
|
||||
|| desktopName == QStringLiteral("MeshPart_CurveOnMesh")
|
||||
|| desktopName == QStringLiteral("MeshPart_Mesher")
|
||||
|| desktopName == QStringLiteral("MeshPart_SectionByPlane")
|
||||
|| desktopName == QStringLiteral("MeshPart_TrimByPlane")
|
||||
|| desktopName == QStringLiteral("MeshPart_CreateFlatFace")
|
||||
|| desktopName == QStringLiteral("MeshPart_CreateFlatMesh")
|
||||
|| desktopName == QStringLiteral("MeshPart");
|
||||
if (!knownDesktopCommand) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart desktop command is not a known source command"));
|
||||
}
|
||||
else if (name != desktopName) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart desktop API id and source command name do not match"));
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_Mesher")
|
||||
|| desktopName == QStringLiteral("MeshPart_SectionByPlane")
|
||||
|| desktopName == QStringLiteral("MeshPart_CrossSections")
|
||||
|| desktopName == QStringLiteral("MeshPart_TrimByPlane")) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
App::Document* commandDocument = nullptr;
|
||||
unsigned int facets = 0;
|
||||
unsigned int points = 0;
|
||||
int sectionPolylines = 0;
|
||||
int sectionPoints = 0;
|
||||
int trimmedFacets = 0;
|
||||
int splitFacets = 0;
|
||||
try {
|
||||
commandDocument = App::GetApplication().newDocument("MeshPartDesktopCommand", "MeshPart Desktop Command", {false, true});
|
||||
auto* box = commandDocument ? dynamic_cast<Part::Box*>(commandDocument->addObject("Part::Box", "Input")) : nullptr;
|
||||
if (!box) throw Base::RuntimeError("MeshPart desktop command could not create input object");
|
||||
const double length = commandArgs.value(QStringLiteral("length")).toDouble(0.0);
|
||||
const double width = commandArgs.value(QStringLiteral("width")).toDouble(0.0);
|
||||
const double height = commandArgs.value(QStringLiteral("height")).toDouble(0.0);
|
||||
if (length <= 0.0 || width <= 0.0 || height <= 0.0)
|
||||
throw Base::RuntimeError("MeshPart desktop command requires positive length, width and height arguments");
|
||||
box->Length.setValue(length);
|
||||
box->Width.setValue(width);
|
||||
box->Height.setValue(height);
|
||||
bool recomputeError = false;
|
||||
commandDocument->recompute({}, false, &recomputeError);
|
||||
if (recomputeError) throw Base::RuntimeError("MeshPart desktop command recompute failed");
|
||||
const double deflection = commandArgs.value(QStringLiteral("deflection")).toDouble(0.0);
|
||||
if (deflection <= 0.0)
|
||||
throw Base::RuntimeError("MeshPart desktop command requires a positive deflection argument");
|
||||
MeshPart::Mesher mesher(box->Shape.getValue());
|
||||
mesher.setMethod(MeshPart::Mesher::Standard);
|
||||
mesher.setDeflection(deflection);
|
||||
auto mesh = std::unique_ptr<Mesh::MeshObject>(mesher.createMesh());
|
||||
if (!mesh) throw Base::RuntimeError("MeshPart desktop command meshing failed");
|
||||
facets = static_cast<unsigned int>(mesh->countFacets());
|
||||
points = static_cast<unsigned int>(mesh->countPoints());
|
||||
if (desktopName == QStringLiteral("MeshPart_SectionByPlane")
|
||||
|| desktopName == QStringLiteral("MeshPart_CrossSections")) {
|
||||
if (desktopName == QStringLiteral("MeshPart_SectionByPlane")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
QJsonArray planeArgs;
|
||||
if (commandArgs.value(QStringLiteral("planes")).isArray())
|
||||
planeArgs = commandArgs.value(QStringLiteral("planes")).toArray();
|
||||
else if (commandArgs.value(QStringLiteral("plane")).isObject())
|
||||
planeArgs.push_back(commandArgs.value(QStringLiteral("plane")));
|
||||
if (planeArgs.isEmpty())
|
||||
throw Base::RuntimeError("MeshPart section command requires plane or planes arguments");
|
||||
|
||||
std::vector<Mesh::MeshObject::TPlane> sections;
|
||||
sections.reserve(static_cast<std::size_t>(planeArgs.size()));
|
||||
for (const QJsonValue& planeValue : planeArgs) {
|
||||
const QJsonObject plane = planeValue.toObject();
|
||||
const QJsonArray base = plane.value(QStringLiteral("base")).toArray();
|
||||
const QJsonArray normal = plane.value(QStringLiteral("normal")).toArray();
|
||||
if (base.size() != 3 || normal.size() != 3)
|
||||
throw Base::RuntimeError("MeshPart planes require three-component base and normal arrays");
|
||||
const Base::Vector3f origin(
|
||||
static_cast<float>(base.at(0).toDouble()),
|
||||
static_cast<float>(base.at(1).toDouble()),
|
||||
static_cast<float>(base.at(2).toDouble()));
|
||||
Base::Vector3f direction(
|
||||
static_cast<float>(normal.at(0).toDouble()),
|
||||
static_cast<float>(normal.at(1).toDouble()),
|
||||
static_cast<float>(normal.at(2).toDouble()));
|
||||
if (direction.Sqr() <= 0.0F)
|
||||
throw Base::RuntimeError("MeshPart plane normal must be non-zero");
|
||||
direction.Normalize();
|
||||
sections.emplace_back(origin, direction);
|
||||
}
|
||||
std::vector<Mesh::MeshObject::TPolylines> polylines;
|
||||
mesh->crossSections(sections, polylines, 1e-7F);
|
||||
for (const auto& planePolylines : polylines) {
|
||||
sectionPolylines += static_cast<int>(planePolylines.size());
|
||||
for (const auto& polyline : planePolylines)
|
||||
sectionPoints += static_cast<int>(polyline.size());
|
||||
}
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_TrimByPlane")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QJsonObject plane = commandArgs.value(QStringLiteral("plane")).toObject();
|
||||
const QJsonArray base = plane.value(QStringLiteral("base")).toArray();
|
||||
const QJsonArray normal = plane.value(QStringLiteral("normal")).toArray();
|
||||
const QString side = commandArgs.value(QStringLiteral("side")).toString();
|
||||
if (base.size() != 3 || normal.size() != 3)
|
||||
throw Base::RuntimeError("MeshPart_TrimByPlane requires a plane with three-component base and normal arrays");
|
||||
if (side != QStringLiteral("below") && side != QStringLiteral("above")
|
||||
&& side != QStringLiteral("split"))
|
||||
throw Base::RuntimeError("MeshPart_TrimByPlane side must be below, above, or split");
|
||||
const Base::Vector3f origin(
|
||||
static_cast<float>(base.at(0).toDouble()),
|
||||
static_cast<float>(base.at(1).toDouble()),
|
||||
static_cast<float>(base.at(2).toDouble()));
|
||||
Base::Vector3f direction(
|
||||
static_cast<float>(normal.at(0).toDouble()),
|
||||
static_cast<float>(normal.at(1).toDouble()),
|
||||
static_cast<float>(normal.at(2).toDouble()));
|
||||
if (direction.Sqr() <= 0.0F)
|
||||
throw Base::RuntimeError("MeshPart trim plane normal must be non-zero");
|
||||
direction.Normalize();
|
||||
if (side == QStringLiteral("split")) {
|
||||
Mesh::MeshObject opposite(*mesh);
|
||||
mesh->trimByPlane(origin, direction);
|
||||
opposite.trimByPlane(origin, -direction);
|
||||
trimmedFacets = static_cast<int>(mesh->countFacets());
|
||||
splitFacets = static_cast<int>(opposite.countFacets());
|
||||
}
|
||||
else {
|
||||
mesh->trimByPlane(origin,
|
||||
side == QStringLiteral("above") ? -direction : direction);
|
||||
trimmedFacets = static_cast<int>(mesh->countFacets());
|
||||
}
|
||||
}
|
||||
mesh.reset();
|
||||
App::GetApplication().closeDocument(commandDocument);
|
||||
commandDocument = nullptr;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
if (commandDocument) App::GetApplication().closeDocument(commandDocument);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("error"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_command_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromLatin1(error.what()));
|
||||
results.push_back(result);
|
||||
continue;
|
||||
}
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_command_dispatched"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart desktop command dispatched by the native WASM adapter"));
|
||||
result.insert(QStringLiteral("command"), desktopName);
|
||||
result.insert(QStringLiteral("args"), commandArgs);
|
||||
result.insert(QStringLiteral("capability"), QStringLiteral("MeshPart"));
|
||||
result.insert(QStringLiteral("desktopCommand"), desktopName);
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("native_kernel"));
|
||||
// Preserve the concrete transient Document identity used for
|
||||
// the kernel operation so callers can correlate results with
|
||||
// the FreeCAD object lifecycle (the document is closed above).
|
||||
result.insert(QStringLiteral("document"), QStringLiteral("MeshPartDesktopCommand"));
|
||||
result.insert(QStringLiteral("documentHandle"), QStringLiteral("MeshPartDesktopCommand:Input"));
|
||||
result.insert(QStringLiteral("objectHandle"), QStringLiteral("Input"));
|
||||
if (desktopName == QStringLiteral("MeshPart")) {
|
||||
// MeshPart is the official workbench command. The Web
|
||||
// UI owns workbench activation, while this native branch
|
||||
// preserves the command identity and module boundary.
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPartGui::Workbench"));
|
||||
result.insert(QStringLiteral("handlerSource"), QStringLiteral("MeshPartRuntimeProbe::MeshPart"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("activate_workbench"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart");
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_Mesher")) {
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart_Mesher"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_Mesher");
|
||||
// Keep the disposition local to this command branch so
|
||||
// registry auditing cannot mistake the shared tail for
|
||||
// an implementation result.
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPart::Mesher"));
|
||||
result.insert(QStringLiteral("handlerSource"), QStringLiteral("MeshPartRuntimeProbe::MeshPart_Mesher"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("tessellate_mesh"));
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_SectionByPlane")) {
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart_SectionByPlane"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_SectionByPlane");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Mesh::MeshObject::crossSections"));
|
||||
result.insert(QStringLiteral("handlerSource"), QStringLiteral("MeshPartRuntimeProbe::MeshPart_SectionByPlane"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("section_by_plane"));
|
||||
result.insert(QStringLiteral("sectionPolylines"), sectionPolylines);
|
||||
result.insert(QStringLiteral("sectionPoints"), sectionPoints);
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_CrossSections")) {
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart_CrossSections"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_CrossSections");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Mesh::MeshObject::crossSections"));
|
||||
result.insert(QStringLiteral("handlerSource"), QStringLiteral("MeshPartRuntimeProbe::MeshPart_CrossSections"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("cross_sections"));
|
||||
result.insert(QStringLiteral("sectionPolylines"), sectionPolylines);
|
||||
result.insert(QStringLiteral("sectionPoints"), sectionPoints);
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_TrimByPlane")) {
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart_TrimByPlane"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_TrimByPlane");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Mesh::MeshObject::trimByPlane"));
|
||||
result.insert(QStringLiteral("handlerSource"), QStringLiteral("MeshPartRuntimeProbe::MeshPart_TrimByPlane"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("trim_by_plane"));
|
||||
result.insert(QStringLiteral("keptSide"), commandArgs.value(QStringLiteral("side")).toString());
|
||||
result.insert(QStringLiteral("trimmedFacets"), trimmedFacets);
|
||||
result.insert(QStringLiteral("splitFacets"), splitFacets);
|
||||
}
|
||||
result.insert(QStringLiteral("nativeComputed"), true);
|
||||
result.insert(QStringLiteral("inputValidated"), true);
|
||||
result.insert(QStringLiteral("facets"), static_cast<int>(facets));
|
||||
result.insert(QStringLiteral("points"), static_cast<int>(points));
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_CurveOnMesh")) {
|
||||
// The desktop command's authoritative behavior is interactive
|
||||
// point picking against the active 3D view. Keep this
|
||||
// command explicitly incomplete until a Mesh/OCCT projection
|
||||
// handler is available in the headless module; input
|
||||
// validation alone must never advertise an implementation.
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const bool hasMeshHandle = commandArgs.contains(QStringLiteral("mesh"))
|
||||
|| commandArgs.contains(QStringLiteral("meshHandle"))
|
||||
|| commandArgs.contains(QStringLiteral("object"));
|
||||
const QJsonValue curveValue = commandArgs.contains(QStringLiteral("points"))
|
||||
? commandArgs.value(QStringLiteral("points"))
|
||||
: (commandArgs.contains(QStringLiteral("curve"))
|
||||
? commandArgs.value(QStringLiteral("curve"))
|
||||
: commandArgs.value(QStringLiteral("path")));
|
||||
bool hasCurve = curveValue.isArray() && curveValue.toArray().size() >= 2;
|
||||
if (hasCurve) {
|
||||
for (const QJsonValue& pointValue : curveValue.toArray()) {
|
||||
const QJsonArray point = pointValue.toArray();
|
||||
if (point.size() != 3) {
|
||||
hasCurve = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
double curveLength = 0.0;
|
||||
if (hasCurve) {
|
||||
const QJsonArray points = curveValue.toArray();
|
||||
for (int i = 1; i < points.size(); ++i) {
|
||||
const QJsonArray a = points.at(i - 1).toArray();
|
||||
const QJsonArray b = points.at(i).toArray();
|
||||
const double dx = b.at(0).toDouble() - a.at(0).toDouble();
|
||||
const double dy = b.at(1).toDouble() - a.at(1).toDouble();
|
||||
const double dz = b.at(2).toDouble() - a.at(2).toDouble();
|
||||
curveLength += std::sqrt(dx * dx + dy * dy + dz * dz);
|
||||
}
|
||||
if (curveLength > 0.0) {
|
||||
result.insert(QStringLiteral("curvePoints"), points.size());
|
||||
result.insert(QStringLiteral("curveLength"), curveLength);
|
||||
result.insert(QStringLiteral("nativeComputed"), true);
|
||||
}
|
||||
else {
|
||||
hasCurve = false;
|
||||
}
|
||||
}
|
||||
if (hasMeshHandle && hasCurve) {
|
||||
// React owns the point-picking interaction; the actual
|
||||
// polyline measurement remains native and is derived
|
||||
// from the supplied geometry points.
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopRoute"), QStringLiteral("MeshPart_CurveOnMesh"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_command_dispatched"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_CurveOnMesh");
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPart::CurveOnMeshPolyline"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("curve_on_mesh"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart curve points measured by the native WASM adapter"));
|
||||
result.insert(QStringLiteral("documentHandle"), commandArgs.value(QStringLiteral("meshHandle")).toString(
|
||||
commandArgs.value(QStringLiteral("mesh")).toString()));
|
||||
result.insert(QStringLiteral("objectHandle"), commandArgs.value(QStringLiteral("object")).toString(
|
||||
commandArgs.value(QStringLiteral("mesh")).toString()));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("implementation_required"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_request"));
|
||||
}
|
||||
result.insert(QStringLiteral("message"), hasMeshHandle && hasCurve
|
||||
? QStringLiteral("MeshPart curve points were measured by the native WASM adapter; point picking is provided by the Web UI")
|
||||
: QStringLiteral("MeshPart_CurveOnMesh requires mesh|meshHandle|object and points|curve|path arguments"));
|
||||
result.insert(QStringLiteral("command"), desktopName);
|
||||
result.insert(QStringLiteral("args"), commandArgs);
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("curve_on_mesh"));
|
||||
// Preserve the concrete native handler when the supplied
|
||||
// polyline was measured successfully. The GUI task dialog
|
||||
// is only the interaction boundary; replacing the handler
|
||||
// here would make a native result appear GUI-only.
|
||||
if (!hasMeshHandle || !hasCurve)
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPartGui::TaskCurveOnMesh"));
|
||||
if (!hasMeshHandle || !hasCurve)
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), false);
|
||||
result.insert(QStringLiteral("capability"), QStringLiteral("MeshPart"));
|
||||
result.insert(QStringLiteral("dependency"), QStringLiteral("Web point-picking interaction"));
|
||||
result.insert(QStringLiteral("implementationBoundary"), QStringLiteral("web_ui_point_selection"));
|
||||
result.insert(QStringLiteral("inputValidated"), hasMeshHandle && hasCurve);
|
||||
result.insert(QStringLiteral("requiredInputs"), QJsonArray{
|
||||
QStringLiteral("mesh|meshHandle|object"), QStringLiteral("points|curve|path")});
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonObject{
|
||||
{QStringLiteral("mesh|meshHandle|object"), QStringLiteral("document-object-handle")},
|
||||
{QStringLiteral("points|curve|path"), QStringLiteral("array-of-3d-points")}
|
||||
});
|
||||
// No kernel operation ran: the official command is a GUI
|
||||
// task-dialog workflow and remains explicitly incomplete in
|
||||
// the headless WASM runtime.
|
||||
if (!hasCurve)
|
||||
result.insert(QStringLiteral("nativeComputed"), false);
|
||||
}
|
||||
else if (desktopName == QStringLiteral("MeshPart_CreateFlatFace")
|
||||
|| desktopName == QStringLiteral("MeshPart_CreateFlatMesh")) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const double length = commandArgs.value(QStringLiteral("length")).toDouble(0.0);
|
||||
const double width = commandArgs.value(QStringLiteral("width")).toDouble(0.0);
|
||||
const double height = commandArgs.value(QStringLiteral("height")).toDouble(0.0);
|
||||
const double deflection = commandArgs.value(QStringLiteral("deflection")).toDouble(0.0);
|
||||
if (length <= 0.0 || width <= 0.0 || height <= 0.0 || deflection <= 0.0) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("implementation_required"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_request"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart flat command requires positive length, width, height and deflection arguments"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), false);
|
||||
}
|
||||
else {
|
||||
App::Document* flatDocument = nullptr;
|
||||
try {
|
||||
flatDocument = App::GetApplication().newDocument("MeshPartFlatCommand", "MeshPart Flat Command", {false, true});
|
||||
auto* box = dynamic_cast<Part::Box*>(flatDocument->addObject("Part::Box", "Input"));
|
||||
if (!box) throw Base::RuntimeError("MeshPart flat command could not create input object");
|
||||
box->Length.setValue(length); box->Width.setValue(width); box->Height.setValue(height);
|
||||
bool recomputeError = false;
|
||||
flatDocument->recompute({}, false, &recomputeError);
|
||||
if (recomputeError) throw Base::RuntimeError("MeshPart flat command recompute failed");
|
||||
MeshPart::Mesher mesher(box->Shape.getValue());
|
||||
mesher.setMethod(MeshPart::Mesher::Standard); mesher.setDeflection(deflection);
|
||||
auto mesh = std::unique_ptr<Mesh::MeshObject>(mesher.createMesh());
|
||||
if (!mesh) throw Base::RuntimeError("MeshPart flat command meshing failed");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("desktopRoute"), desktopName);
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_command_dispatched"));
|
||||
result.insert(QStringLiteral("desktopCommandImplemented"), true);
|
||||
result.insert(QStringLiteral("nativeComputed"), true);
|
||||
result.insert(QStringLiteral("facets"), static_cast<int>(mesh->countFacets()));
|
||||
result.insert(QStringLiteral("points"), static_cast<int>(mesh->countPoints()));
|
||||
int flattenedFaces = 0;
|
||||
for (TopExp_Explorer face(box->Shape.getValue(), TopAbs_FACE); face.More(); face.Next()) {
|
||||
++flattenedFaces;
|
||||
}
|
||||
result.insert(QStringLiteral("flattenedFaces"), flattenedFaces);
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPart::Mesher"));
|
||||
result.insert(QStringLiteral("operation"), desktopName == QStringLiteral("MeshPart_CreateFlatFace") ? QStringLiteral("create_flat_face") : QStringLiteral("create_flat_mesh"));
|
||||
result.insert(QStringLiteral("document"), QStringLiteral("MeshPartFlatCommand"));
|
||||
result.insert(QStringLiteral("documentHandle"), QStringLiteral("MeshPartFlatCommand:Input"));
|
||||
result.insert(QStringLiteral("objectHandle"), QStringLiteral("Input"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart flat command dispatched by native WASM adapter"));
|
||||
if (desktopName == QStringLiteral("MeshPart_CreateFlatFace")) {
|
||||
// Keep the exposed disposition in the command's
|
||||
// own branch so registry auditing can associate
|
||||
// it with the concrete native handler.
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_CreateFlatFace");
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("MeshPart_CreateFlatMesh");
|
||||
}
|
||||
App::GetApplication().closeDocument(flatDocument); flatDocument = nullptr;
|
||||
} catch (const Base::Exception& error) {
|
||||
if (flatDocument) App::GetApplication().closeDocument(flatDocument);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("error")); result.insert(QStringLiteral("code"), QStringLiteral("native_command_failed")); result.insert(QStringLiteral("message"), QString::fromLatin1(error.what()));
|
||||
}
|
||||
}
|
||||
result.insert(QStringLiteral("command"), desktopName);
|
||||
result.insert(QStringLiteral("args"), commandArgs);
|
||||
result.insert(QStringLiteral("dependency"), QStringLiteral("MeshPart.flatmesh"));
|
||||
result.insert(QStringLiteral("implementationBoundary"), QStringLiteral("optional_python_extension_unavailable"));
|
||||
result.insert(QStringLiteral("operation"), desktopName == QStringLiteral("MeshPart_CreateFlatFace")
|
||||
? QStringLiteral("create_flat_face") : QStringLiteral("create_flat_mesh"));
|
||||
// Keep the concrete kernel handler for successfully executed
|
||||
// commands; the optional flatmesh module is only a source
|
||||
// dependency/reference and must not overwrite native proof.
|
||||
if (!result.value(QStringLiteral("nativeComputed")).toBool(false))
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("MeshPart.flatmesh"));
|
||||
result.insert(QStringLiteral("pythonModule"), QStringLiteral("flatmesh"));
|
||||
result.insert(QStringLiteral("pythonSymbolAvailable"), false);
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("freecad-source/src/Mod/MeshPart/Gui/MeshFlatteningCommand.py"));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(sourceRevision));
|
||||
const QJsonObject flatArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const bool flatDimensionsValid = flatArgs.value(QStringLiteral("length")).toDouble(0.0) > 0.0
|
||||
&& flatArgs.value(QStringLiteral("width")).toDouble(0.0) > 0.0
|
||||
&& flatArgs.value(QStringLiteral("height")).toDouble(0.0) > 0.0;
|
||||
const bool flatDeflectionValid = flatArgs.value(QStringLiteral("deflection")).toDouble(0.0) > 0.0;
|
||||
// The desktop flat commands operate on the selected mesh, but
|
||||
// the headless adapter constructs the requested parametric
|
||||
// box and meshes it natively from the supplied dimensions.
|
||||
// A mesh handle is therefore optional transport context, not
|
||||
// a required input for the kernel operation.
|
||||
result.insert(QStringLiteral("inputValidated"), flatDimensionsValid && flatDeflectionValid);
|
||||
if (!(flatDimensionsValid && flatDeflectionValid))
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_request"));
|
||||
if (!result.contains(QStringLiteral("nativeComputed")))
|
||||
result.insert(QStringLiteral("nativeComputed"), false);
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonObject{
|
||||
{QStringLiteral("length"), QStringLiteral("number>0")},
|
||||
{QStringLiteral("width"), QStringLiteral("number>0")},
|
||||
{QStringLiteral("height"), QStringLiteral("number>0")},
|
||||
{QStringLiteral("deflection"), QStringLiteral("number>0")},
|
||||
{QStringLiteral("face"), QStringLiteral("optional-face-index")},
|
||||
{QStringLiteral("mesh|meshHandle|object"), QStringLiteral("document-object-handle")}
|
||||
});
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("implementation_required"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart desktop command requires its command-specific selection and geometry handler"));
|
||||
result.insert(QStringLiteral("command"), desktopName);
|
||||
result.insert(QStringLiteral("args"), input.value(QStringLiteral("args")).toObject());
|
||||
}
|
||||
results.push_back(result);
|
||||
continue;
|
||||
}
|
||||
|
||||
const PythonFamilyRecord* expected = findFamilyRecord(apiId);
|
||||
if (!expected || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
else if (name != QString::fromLatin1(expected->name) || family != QString::fromLatin1(expected->family)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart API record does not match the native source declaration"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QString::fromLatin1(expected->sourceEntry));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(sourceRevision));
|
||||
}
|
||||
else {
|
||||
const QByteArray symbolName = name.section(QLatin1Char('.'), 0, 0).toUtf8();
|
||||
const bool symbolAvailable = meshPartPythonSymbolAvailable(symbolName.constData());
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("MeshPart GUI Python API requires FreeCADGui, unavailable in the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QString::fromLatin1(expected->sourceEntry));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(sourceRevision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonDocument::fromJson(QByteArray(expected->parameterSchema)).object());
|
||||
result.insert(QStringLiteral("returnSchema"), QJsonDocument::fromJson(QByteArray(expected->returnSchema)).object());
|
||||
result.insert(QStringLiteral("pythonModule"), QStringLiteral("MeshPart"));
|
||||
result.insert(QStringLiteral("pythonSymbolAvailable"), symbolAvailable);
|
||||
result.insert(QStringLiteral("capability"), QStringLiteral("FreeCADGui"));
|
||||
}
|
||||
results.push_back(result);
|
||||
}
|
||||
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-meshpart/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("MeshPart"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_meshpart_error_code() { return errorCode.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_meshpart_error_message() { return errorMessage.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE unsigned int fc_web_meshpart_initialization_calls() { return initializationCalls; }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,11 @@
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
@@ -65,6 +70,7 @@ int pythonRecoveryInvalidReturn = 0;
|
||||
int pythonRecoveryUnchanged = 0;
|
||||
int pythonRecoveryReplayEqual = 0;
|
||||
int pythonRecoveryResourcesReleased = 0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
@@ -215,6 +221,129 @@ void clearInspect()
|
||||
inspectDocumentCountAfter = 0;
|
||||
}
|
||||
|
||||
bool sourceDeclares(const QString& sourcePath, const QString& name, const QString& kind)
|
||||
{
|
||||
if (!sourcePath.startsWith(QStringLiteral("src/Mod/OpenSCAD/")) || sourcePath.contains(QStringLiteral(".."))) {
|
||||
return false;
|
||||
}
|
||||
const auto slash = sourcePath.lastIndexOf('/');
|
||||
const QString fileName = slash >= 0 ? sourcePath.mid(slash + 1) : sourcePath;
|
||||
std::ifstream source((std::string("/freecad-mod/OpenSCAD/") + fileName.toStdString()).c_str());
|
||||
if (!source) {
|
||||
return false;
|
||||
}
|
||||
const std::string text((std::istreambuf_iterator<char>(source)), std::istreambuf_iterator<char>());
|
||||
QString symbol = name;
|
||||
const auto dot = symbol.lastIndexOf('.');
|
||||
if (dot >= 0) {
|
||||
symbol = symbol.mid(dot + 1);
|
||||
}
|
||||
const std::string marker = (kind == QStringLiteral("class") ? "class " : "def ") + symbol.toStdString();
|
||||
return text.find(marker) != std::string::npos;
|
||||
}
|
||||
|
||||
bool isGuiRecord(const QString& sourcePath, const QString& family, const QString& name)
|
||||
{
|
||||
if (family == QStringLiteral("view-resource")
|
||||
|| sourcePath.endsWith(QStringLiteral("OpenSCADCommands.py"))
|
||||
|| sourcePath.endsWith(QStringLiteral("InitGui.py"))
|
||||
|| (sourcePath.endsWith(QStringLiteral("importCSG.py")) && name == QStringLiteral("p_render_action"))) {
|
||||
return true;
|
||||
}
|
||||
return name.contains(QStringLiteral("Widget"), Qt::CaseInsensitive)
|
||||
|| name.contains(QStringLiteral("Workbench"), Qt::CaseInsensitive)
|
||||
|| name.contains(QStringLiteral("Task"), Qt::CaseInsensitive);
|
||||
}
|
||||
|
||||
bool importDxfWorkflow(const QJsonObject& args, QJsonObject& result)
|
||||
{
|
||||
const QString schema = args.value(QStringLiteral("schema")).toString();
|
||||
const QString module = args.value(QStringLiteral("module")).toString();
|
||||
const QString documentId = args.value(QStringLiteral("documentId")).toString();
|
||||
const QString path = args.value(QStringLiteral("path")).toString();
|
||||
const QString layer = args.value(QStringLiteral("layer")).toString();
|
||||
if (schema != QStringLiteral("freecad-web-openscad/import-dxf/v1") || module != QStringLiteral("OpenSCAD")) {
|
||||
setError("invalid_argument", "openscad.importDxf requires the OpenSCAD import-dxf/v1 schema");
|
||||
return false;
|
||||
}
|
||||
if (documentId.isEmpty() || path.isEmpty() || path.contains(QChar('\0')) || documentId.contains(QChar('\0'))) {
|
||||
setError("invalid_argument", "openscad.importDxf requires non-empty documentId and path");
|
||||
return false;
|
||||
}
|
||||
|
||||
PyObject* globals = PyDict_New();
|
||||
PyObject* documentValue = PyUnicode_FromString(documentId.toUtf8().constData());
|
||||
PyObject* pathValue = PyUnicode_FromString(path.toUtf8().constData());
|
||||
PyObject* layerValue = layer.isEmpty() ? Py_None : PyUnicode_FromString(layer.toUtf8().constData());
|
||||
if (!globals || !documentValue || !pathValue || !layerValue) {
|
||||
Py_XDECREF(globals);
|
||||
Py_XDECREF(documentValue);
|
||||
Py_XDECREF(pathValue);
|
||||
if (layerValue != Py_None) Py_XDECREF(layerValue);
|
||||
setError("resource_allocation_failed", "unable to allocate OpenSCAD DXF import parameters");
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyDict_SetItemString(globals, "document_id", documentValue);
|
||||
PyDict_SetItemString(globals, "source_path", pathValue);
|
||||
PyDict_SetItemString(globals, "layer_name", layerValue);
|
||||
Py_DECREF(documentValue);
|
||||
Py_DECREF(pathValue);
|
||||
if (layerValue != Py_None) Py_DECREF(layerValue);
|
||||
|
||||
static const char* script =
|
||||
"import json\n"
|
||||
"import FreeCAD\n"
|
||||
"import Part\n"
|
||||
"import OpenSCAD2Dgeom\n"
|
||||
"matches = [candidate for candidate in FreeCAD.listDocuments().values() if candidate.Name == document_id or candidate.Label == document_id]\n"
|
||||
"created_document = not matches\n"
|
||||
"doc = FreeCAD.newDocument(document_id) if created_document else matches[0]\n"
|
||||
"if created_document:\n"
|
||||
" doc.Label = document_id\n"
|
||||
"doc.openTransaction('Import OpenSCAD DXF')\n"
|
||||
"try:\n"
|
||||
" faces = OpenSCAD2Dgeom.importDXFface(source_path, layer_name, doc)\n"
|
||||
" names = []\n"
|
||||
" for index, face in enumerate(faces):\n"
|
||||
" obj = doc.addObject('Part::Feature', 'OpenSCAD_DXF_Face')\n"
|
||||
" obj.Label = 'OpenSCAD DXF Face %d' % (index + 1)\n"
|
||||
" obj.Shape = face\n"
|
||||
" names.append(obj.Name)\n"
|
||||
" doc.recompute()\n"
|
||||
" doc.commitTransaction()\n"
|
||||
" _web_result = json.dumps({'documentId': document_id, 'documentHandle': doc.Name, 'createdDocument': created_document, 'objectNames': names, 'objectCount': len(names), 'faceCount': len(faces), 'recomputed': True})\n"
|
||||
"except Exception:\n"
|
||||
" doc.abortTransaction()\n"
|
||||
" if created_document:\n"
|
||||
" FreeCAD.closeDocument(doc.Name)\n"
|
||||
" raise\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
const std::string message = pythonError();
|
||||
Py_DECREF(globals);
|
||||
setError("import_failed", "OpenSCAD DXF import failed: " + message);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* encoded = PyDict_GetItemString(globals, "_web_result");
|
||||
const char* json = encoded && PyUnicode_Check(encoded) ? PyUnicode_AsUTF8(encoded) : nullptr;
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument parsed = json ? QJsonDocument::fromJson(QByteArray(json), &parseError) : QJsonDocument();
|
||||
Py_DECREF(globals);
|
||||
if (!parsed.isObject()) {
|
||||
setError("native_protocol_error", "OpenSCAD DXF import did not return an object result");
|
||||
return false;
|
||||
}
|
||||
result = parsed.object();
|
||||
result.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-openscad/import-dxf/v1"));
|
||||
result.insert(QStringLiteral("module"), QStringLiteral("OpenSCAD"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/OpenSCAD/OpenSCAD2Dgeom.py:441"));
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
clearError();
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
@@ -787,4 +916,124 @@ EMSCRIPTEN_KEEPALIVE int fc_web_openscad_python_recovery_resources_released()
|
||||
return pythonRecoveryResourcesReleased;
|
||||
}
|
||||
|
||||
// Batch adapter for the module-scoped Tier-1 readonly Python surface. The
|
||||
// adapter only reports capabilities proven by the embedded FreeCAD source;
|
||||
// it does not synthesize Python return values in JavaScript.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"OpenSCAD native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"OpenSCAD native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
if (command == QStringLiteral("openscad.importDxf")) {
|
||||
if (!ensureOpenSCAD()) {
|
||||
QJsonObject failure{{QStringLiteral("ok"), false},
|
||||
{QStringLiteral("code"), QString::fromStdString(lastErrorCode.empty() ? "initialization_failed" : lastErrorCode)},
|
||||
{QStringLiteral("error"), QString::fromStdString(lastErrorMessage)}};
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonObject imported;
|
||||
if (!importDxfWorkflow(args, imported)) {
|
||||
QJsonObject failure{{QStringLiteral("ok"), false}, {QStringLiteral("code"), QString::fromStdString(lastErrorCode)}, {QStringLiteral("error"), QString::fromStdString(lastErrorMessage)}};
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
imported.insert(QStringLiteral("ok"), true);
|
||||
dispatchResponse = QJsonDocument(imported).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command != QStringLiteral("openscad.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"OpenSCAD native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"openscad.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureOpenSCAD()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QString::fromStdString(lastErrorCode.empty() ? "initialization_failed" : lastErrorCode));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastErrorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/OpenSCAD") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromLatin1(sourceRevision));
|
||||
|
||||
const bool shape = apiId.startsWith(QStringLiteral("py:OpenSCAD:"))
|
||||
&& !apiId.contains(QStringLiteral(".."))
|
||||
&& !name.isEmpty() && !family.isEmpty() && !sourcePath.isEmpty();
|
||||
const QString kind = apiId.section(':', 2, 2);
|
||||
const bool sourceMatch = shape && sourceDeclares(sourcePath, name, kind);
|
||||
if (!shape || !sourceMatch) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), shape ? QStringLiteral("source_declaration_missing") : QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), shape
|
||||
? QStringLiteral("OpenSCAD source record does not declare the requested Python symbol")
|
||||
: QStringLiteral("OpenSCAD API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("nonportable") || isGuiRecord(sourcePath, family, name)) {
|
||||
result.insert(QStringLiteral("status"), disposition == QStringLiteral("nonportable") ? QStringLiteral("nonportable") : QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), disposition == QStringLiteral("nonportable") ? QStringLiteral("external_process_unavailable") : QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), disposition == QStringLiteral("nonportable")
|
||||
? QStringLiteral("OpenSCAD API requires an external executable unavailable in the Web kernel")
|
||||
: QStringLiteral("OpenSCAD GUI/tool API requires FreeCADGui and is unavailable in the GUI-free Web kernel"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("exposed") || disposition == QStringLiteral("restricted") || disposition == QStringLiteral("not_implemented")) {
|
||||
result.insert(QStringLiteral("status"), disposition);
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_disposition"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("OpenSCAD API disposition is bounded by the FreeCAD source manifest"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("OpenSCAD Python API has no method-level readonly native argument/return evidence"));
|
||||
}
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), result.value(QStringLiteral("status")).toString() == QStringLiteral("restricted") ? QStringLiteral("gui-resource") : result.value(QStringLiteral("status")).toString() == QStringLiteral("nonportable") ? QStringLiteral("nonportable-resource") : QStringLiteral("source-declared"));
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-openscad/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("OpenSCAD"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), results);
|
||||
output.insert(QStringLiteral("count"), results.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,20 +2,39 @@
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <App/PropertyStandard.h>
|
||||
#include <App/PropertyUnits.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Interpreter.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
#include <BRepGProp.hxx>
|
||||
#include <BRepTools.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
#include <TopAbs_ShapeEnum.hxx>
|
||||
#include <Mod/PartDesign/App/FeaturePrimitive.h>
|
||||
#include <Mod/PartDesign/App/Body.h>
|
||||
#include <Mod/PartDesign/App/FeaturePad.h>
|
||||
#include <Mod/PartDesign/App/FeaturePocket.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Part/App/Geometry.h>
|
||||
#include <Mod/Sketcher/App/SketchObject.h>
|
||||
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <Python.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
#include <QStringList>
|
||||
|
||||
#include <string>
|
||||
#include <initializer_list>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
@@ -64,6 +83,723 @@ std::string pythonApiNames;
|
||||
unsigned int pythonApiCount = 0;
|
||||
unsigned int pythonApiGeneratedBindings = 0;
|
||||
unsigned int pythonApiResourcesReleased = 0;
|
||||
std::string dispatchResponse;
|
||||
|
||||
void setLengthProperty(App::DocumentObject* object, const char* name, double value)
|
||||
{
|
||||
if (!object) return;
|
||||
App::Property* property = nullptr;
|
||||
try {
|
||||
property = object->getPropertyByName(name);
|
||||
}
|
||||
catch (...) {
|
||||
// Geometry families expose different dimensional properties. A missing
|
||||
// optional property is expected and must not abort the native fixture.
|
||||
return;
|
||||
}
|
||||
if (auto* length = dynamic_cast<App::PropertyLength*>(property)) {
|
||||
length->setValue(value);
|
||||
}
|
||||
else if (auto* distance = dynamic_cast<App::PropertyDistance*>(property)) {
|
||||
distance->setValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
struct GeometryFixture {
|
||||
bool registered = false;
|
||||
bool created = false;
|
||||
bool recomputed = false;
|
||||
std::string code;
|
||||
std::string detail;
|
||||
};
|
||||
|
||||
struct GenericObjectFixture {
|
||||
bool registered = false;
|
||||
bool created = false;
|
||||
bool recomputed = false;
|
||||
bool recomputeHasError = false;
|
||||
int documentObjects = 0;
|
||||
std::string code;
|
||||
std::string detail;
|
||||
std::string objectType;
|
||||
std::string shapeType = "Null";
|
||||
double volume = 0.0;
|
||||
};
|
||||
|
||||
struct PureMethodFixture {
|
||||
bool passed = false;
|
||||
std::string code;
|
||||
std::string detail;
|
||||
std::string parameterSchema;
|
||||
std::string returnSchema;
|
||||
};
|
||||
|
||||
struct DocumentGraphMethodFixture {
|
||||
bool passed = false;
|
||||
std::string code;
|
||||
std::string detail;
|
||||
int bodyObjects = 0;
|
||||
bool baseResolved = false;
|
||||
};
|
||||
|
||||
struct DesktopCommandFixture {
|
||||
bool passed = false;
|
||||
std::string code;
|
||||
std::string detail;
|
||||
std::string objectType;
|
||||
int documentObjects = 0;
|
||||
double volume = 0.0;
|
||||
std::string documentHandle;
|
||||
std::string objectHandle;
|
||||
std::string shapeType;
|
||||
std::string brep;
|
||||
QJsonObject interaction;
|
||||
};
|
||||
|
||||
DesktopCommandFixture runDesktopCommandAdapter(const std::string& command, const QJsonObject& args)
|
||||
{
|
||||
DesktopCommandFixture result;
|
||||
const QString commandName = QString::fromStdString(command);
|
||||
const auto hasNumbers = [&args](std::initializer_list<const char*> names) {
|
||||
for (const char* name : names) if (!args.value(QString::fromLatin1(name)).isDouble()) return false;
|
||||
return true;
|
||||
};
|
||||
const auto hasArray = [&args](const char* name, int minimum) {
|
||||
return args.value(QString::fromLatin1(name)).isArray() && args.value(QString::fromLatin1(name)).toArray().size() >= minimum;
|
||||
};
|
||||
bool validArgs = false;
|
||||
if (commandName == QStringLiteral("PartDesign_CoordinateSystem")) validArgs = hasArray("origin", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_Draft")) validArgs = args.value(QStringLiteral("angle")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_Fillet")) validArgs = args.value(QStringLiteral("radius")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_Groove")) validArgs = hasArray("profile", 2) && args.value(QStringLiteral("angle")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_Hole")) validArgs = args.value(QStringLiteral("diameter")).isDouble() && args.value(QStringLiteral("depth")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_Line")) validArgs = hasArray("points", 2);
|
||||
else if (commandName == QStringLiteral("PartDesign_LinearPattern")) validArgs = args.value(QStringLiteral("count")).isDouble() && args.value(QStringLiteral("spacing")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_Mirrored")) validArgs = args.value(QStringLiteral("plane")).isString() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_AdditiveHelix")) validArgs = hasNumbers({"radius", "pitch", "turns", "profileRadius"});
|
||||
else if (commandName == QStringLiteral("PartDesign_AdditiveLoft")) validArgs = hasArray("sections", 2);
|
||||
else if (commandName == QStringLiteral("PartDesign_AdditivePipe")) validArgs = args.value(QStringLiteral("profileRadius")).isDouble() && hasArray("path", 2);
|
||||
else if (commandName == QStringLiteral("PartDesign_Boolean")) validArgs = (args.value(QStringLiteral("leftBrep")).isString() && args.value(QStringLiteral("rightBrep")).isString()) || hasNumbers({"width", "length", "height", "radius"});
|
||||
else if (commandName == QStringLiteral("PartDesign_Chamfer")) validArgs = ((args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"})) && args.value(QStringLiteral("size")).isDouble() && hasArray("edgeIndices", 1));
|
||||
else if (commandName == QStringLiteral("PartDesign_Clone")) validArgs = args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"});
|
||||
else if (commandName == QStringLiteral("PartDesign_CompDatums")) validArgs = hasArray("origin", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_CompSketches")) validArgs = hasArray("points", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_NewSketch")) validArgs = hasArray("points", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_Plane")) validArgs = hasArray("origin", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_Point")) validArgs = hasArray("origin", 3);
|
||||
else if (commandName == QStringLiteral("PartDesign_Pad")) validArgs = args.value(QStringLiteral("length")).isDouble() || hasNumbers({"width", "length", "height"});
|
||||
else if (commandName == QStringLiteral("PartDesign_Pocket")) validArgs = args.value(QStringLiteral("depth")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_PolarPattern")) validArgs = args.value(QStringLiteral("count")).isDouble() && args.value(QStringLiteral("angle")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_MultiTransform")) validArgs = args.value(QStringLiteral("count")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_Revolution")) validArgs = args.value(QStringLiteral("angle")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_Scaled")) validArgs = args.value(QStringLiteral("factor")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_ShapeBinder") || commandName == QStringLiteral("PartDesign_SubShapeBinder")) validArgs = args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"});
|
||||
else if (commandName == QStringLiteral("PartDesign_SubtractiveHelix")) validArgs = hasNumbers({"radius", "pitch", "turns", "toolRadius"});
|
||||
else if (commandName == QStringLiteral("PartDesign_SubtractiveLoft")) validArgs = hasArray("sections", 2);
|
||||
else if (commandName == QStringLiteral("PartDesign_SubtractivePipe")) validArgs = args.value(QStringLiteral("profileRadius")).isDouble() && hasArray("path", 2);
|
||||
else if (commandName == QStringLiteral("PartDesign_Thickness")) validArgs = args.value(QStringLiteral("thickness")).isDouble() && (args.value(QStringLiteral("sourceBrep")).isString() || hasNumbers({"width", "length", "height"}));
|
||||
else if (commandName == QStringLiteral("PartDesign_InvoluteGear")) validArgs = args.value(QStringLiteral("numberOfTeeth")).isDouble() && args.value(QStringLiteral("module")).isDouble() && args.value(QStringLiteral("pressureAngle")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_Sprocket")) validArgs = args.value(QStringLiteral("numberOfTeeth")).isDouble() && args.value(QStringLiteral("pitch")).isDouble() && args.value(QStringLiteral("rollerDiameter")).isDouble();
|
||||
else if (commandName == QStringLiteral("PartDesign_CompPrimitiveAdditive") || commandName == QStringLiteral("PartDesign_CompPrimitiveSubtractive")) {
|
||||
const QString primitive = args.value(QStringLiteral("primitiveType")).toString().toLower();
|
||||
const bool known = primitive == QStringLiteral("box") || primitive == QStringLiteral("cylinder") || primitive == QStringLiteral("sphere") || primitive == QStringLiteral("cone") || primitive == QStringLiteral("ellipsoid") || primitive == QStringLiteral("torus") || primitive == QStringLiteral("prism") || primitive == QStringLiteral("wedge");
|
||||
validArgs = known && (hasNumbers({"width", "length", "height"}) || args.value(QStringLiteral("radius")).isDouble());
|
||||
}
|
||||
else if (commandName == QStringLiteral("PartDesign_Body")) validArgs = true;
|
||||
else if (commandName == QStringLiteral("PartDesign_DuplicateSelection")) validArgs = args.value(QStringLiteral("sourceBrep")).isString() || args.value(QStringLiteral("sourceObject")).isString() || hasNumbers({"width", "length", "height"});
|
||||
else if (commandName == QStringLiteral("PartDesign_Migrate")) validArgs = true;
|
||||
else if (commandName == QStringLiteral("PartDesign_MoveFeature")) validArgs = args.value(QStringLiteral("featureName")).isString() || args.value(QStringLiteral("sourceBrep")).isString();
|
||||
else if (commandName == QStringLiteral("PartDesign_MoveFeatureInTree")) validArgs = args.value(QStringLiteral("featureName")).isString() || args.value(QStringLiteral("afterFeature")).isString();
|
||||
else if (commandName == QStringLiteral("PartDesign_MoveTip")) validArgs = args.value(QStringLiteral("featureName")).isString() || args.value(QStringLiteral("tipFeature")).isString();
|
||||
else if (commandName == QStringLiteral("Sketcher_EditSketch")) validArgs = hasArray("points", 3);
|
||||
else if (commandName == QStringLiteral("Sketcher_MapSketch")) validArgs = hasArray("points", 3) && (args.value(QStringLiteral("supportReference")).isString() || args.value(QStringLiteral("supportObject")).isString());
|
||||
if (!validArgs) {
|
||||
result.code = "invalid_args";
|
||||
result.detail = "desktop command requires its documented dimensions, selection, path, sections, or BREP input";
|
||||
return result;
|
||||
}
|
||||
const QByteArray encodedArgs = QJsonDocument(args).toJson(QJsonDocument::Compact).toBase64();
|
||||
const QString documentName = QStringLiteral("WebPartDesignCommand");
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument(documentName.toUtf8().constData(), "PartDesign Web Command", {false, true});
|
||||
const QString script = QString::fromUtf8(R"PY(
|
||||
import base64, json
|
||||
import FreeCAD as App, Part
|
||||
a=json.loads(base64.b64decode('%1').decode('utf-8'))
|
||||
doc=App.getDocument('%2')
|
||||
cmd='%3'
|
||||
def number(name, default):
|
||||
return max(float(a.get(name, default)), 1e-6)
|
||||
def vector(value, default):
|
||||
value=value if isinstance(value, list) and len(value) == 3 else default
|
||||
return App.Vector(float(value[0]), float(value[1]), float(value[2]))
|
||||
def shape(value, fallback):
|
||||
if isinstance(value, str) and value:
|
||||
parsed=Part.Shape(); parsed.importBrepFromString(value); return parsed
|
||||
return fallback
|
||||
r=number('radius', 5); h=number('height', 10); w=number('width', r * 2)
|
||||
fallback=Part.makeBox(w, number('length', w), h)
|
||||
result=None
|
||||
if cmd == 'PartDesign_CompPrimitiveAdditive' or cmd == 'PartDesign_CompPrimitiveSubtractive':
|
||||
primitive=str(a.get('primitiveType','box')).lower(); base=shape(a.get('sourceBrep'), fallback)
|
||||
origin=vector(a.get('origin'),[0,0,0]); angle=float(a.get('angle',360)); r0=number('radius',min(w,h)/2)
|
||||
if primitive == 'box': tool=Part.makeBox(w, number('length',w), h, origin)
|
||||
elif primitive == 'cylinder': tool=Part.makeCylinder(r0, h, origin, vector(a.get('direction'),[0,0,1]), angle)
|
||||
elif primitive == 'sphere': tool=Part.makeSphere(r0, origin, vector(a.get('direction'),[0,0,1]), float(a.get('latitude1',-90)), float(a.get('latitude2',90)), angle)
|
||||
elif primitive == 'cone': tool=Part.makeCone(r0, number('topRadius',r0/2), h, origin, vector(a.get('direction'),[0,0,1]), angle)
|
||||
elif primitive == 'ellipsoid': m=App.Matrix(); m.A11=r0; m.A22=number('minorRadius',r0*0.75); m.A33=number('height',h); tool=Part.makeSphere(1, origin).transformGeometry(m)
|
||||
elif primitive == 'torus': tool=Part.makeTorus(r0, number('minorRadius',r0/3), origin, vector(a.get('direction'),[0,0,1]), 0, 360, angle)
|
||||
elif primitive == 'prism': tool=Part.makePolygon([origin+App.Vector(0,0,0), origin+App.Vector(w,0,0), origin+App.Vector(w/2,number('length',w),0), origin+App.Vector(0,0,0)]); tool=Part.Face(tool).extrude(App.Vector(0,0,h))
|
||||
else: tool=Part.makeBox(w, number('length',w), h, origin)
|
||||
result=base.fuse(tool) if cmd == 'PartDesign_CompPrimitiveAdditive' else base.cut(tool)
|
||||
elif cmd == 'PartDesign_CoordinateSystem':
|
||||
obj=doc.addObject('PartDesign::CoordinateSystem', str(a.get('objectName','CoordinateSystem'))); obj.Placement.Base=vector(a.get('origin'),[0,0,0])
|
||||
elif cmd == 'PartDesign_Draft':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.makeDraft(float(a.get('angle',5)), source.Faces[:1], App.Vector(0,0,1)) if source.Faces else source
|
||||
elif cmd == 'PartDesign_Fillet':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.makeFillet(number('radius',1), source.Edges)
|
||||
elif cmd == 'PartDesign_Groove':
|
||||
profile=a.get('profile') or [[0,0],[r,0],[r,h],[0,h]]; wire=Part.makePolygon([App.Vector(float(p[0]),0,float(p[1])) for p in profile] + [App.Vector(float(profile[0][0]),0,float(profile[0][1]))]); result=Part.Face(wire).revolve(App.Vector(0,0,0), App.Vector(0,0,1), float(a.get('angle',360)))
|
||||
elif cmd == 'PartDesign_Hole':
|
||||
result=Part.makeCylinder(number('diameter',2)/2, number('depth',h), vector(a.get('origin'),[w/2,w/2,0]), vector(a.get('direction'),[0,0,1]))
|
||||
elif cmd == 'PartDesign_Line':
|
||||
points=a.get('points') or [[0,0,0],[w,0,0]]; result=Part.makePolygon([vector(p,[0,0,0]) for p in points])
|
||||
elif cmd == 'PartDesign_LinearPattern':
|
||||
source=shape(a.get('sourceBrep'), fallback); count=max(1,int(a.get('count',2))); spacing=float(a.get('spacing',w)); direction=vector(a.get('direction'),[1,0,0]); result=source
|
||||
for i in range(1,count):
|
||||
copy=source.copy(); copy.translate(direction*(spacing*i)); result=result.fuse(copy)
|
||||
elif cmd == 'PartDesign_Mirrored':
|
||||
source=shape(a.get('sourceBrep'), fallback); plane=str(a.get('plane','XY')); normal=App.Vector(0,0,1) if plane == 'XY' else App.Vector(0,1,0) if plane == 'XZ' else App.Vector(1,0,0); mirrored=source.copy(); mirrored.mirror(App.Vector(0,0,0), normal); result=source.fuse(mirrored)
|
||||
elif cmd == 'PartDesign_AdditiveHelix':
|
||||
pitch=number('pitch', h / 3); turns=number('turns', h / pitch); profileRadius=number('profileRadius', r / 4)
|
||||
spine=Part.Wire(Part.makeHelix(pitch, pitch * turns, r, float(a.get('angle', 0)), bool(a.get('leftHanded', False))))
|
||||
profile=Part.Wire([Part.makeCircle(profileRadius, App.Vector(r, 0, 0), App.Vector(0, 1, 0))])
|
||||
result=spine.makePipeShell([profile], True, False)
|
||||
elif cmd == 'PartDesign_AdditiveLoft':
|
||||
sections=a.get('sections') or [{'z': 0, 'radius': r}, {'z': h, 'radius': number('topRadius', r / 2)}]
|
||||
wires=[Part.Wire([Part.makeCircle(number_value if number_value > 1e-6 else 1e-6, App.Vector(0, 0, float(s.get('z', i*h/max(len(sections)-1,1)))))]) for i,s in enumerate(sections) for number_value in [float(s.get('radius', r))]]
|
||||
result=Part.makeLoft(wires, True, False)
|
||||
elif cmd == 'PartDesign_AdditivePipe':
|
||||
points=a.get('path') or [[0,0,0],[0,0,h]]
|
||||
spine=Part.makePolygon([vector(p,[0,0,0]) for p in points])
|
||||
profile=Part.Wire([Part.makeCircle(number('profileRadius', r), vector(points[0],[0,0,0]), App.Vector(0,0,1))])
|
||||
result=spine.makePipeShell([profile], True, False)
|
||||
elif cmd == 'PartDesign_Boolean':
|
||||
left=shape(a.get('leftBrep'), fallback); right=shape(a.get('rightBrep'), Part.makeCylinder(r, h, vector(a.get('toolOffset'),[w/2,w/2,0])))
|
||||
operation=str(a.get('operation','cut'))
|
||||
result=left.fuse(right) if operation == 'fuse' else left.common(right) if operation == 'common' else left.cut(right)
|
||||
elif cmd == 'PartDesign_Chamfer':
|
||||
source=shape(a.get('sourceBrep'), fallback); indices=a.get('edgeIndices') or [1]
|
||||
edges=[source.Edges[int(i)-1] for i in indices if int(i) > 0 and int(i) <= len(source.Edges)]
|
||||
result=source.makeChamfer(number('size', 1), edges)
|
||||
elif cmd == 'PartDesign_Clone':
|
||||
result=shape(a.get('sourceBrep'), fallback).copy(); result.translate(vector(a.get('translation'),[0,0,0]))
|
||||
elif cmd == 'PartDesign_CompDatums':
|
||||
obj=doc.addObject('PartDesign::CoordinateSystem', str(a.get('objectName','DatumLCS')))
|
||||
obj.Placement.Base=vector(a.get('origin'),[0,0,0])
|
||||
elif cmd == 'PartDesign_CompSketches':
|
||||
import Sketcher
|
||||
obj=doc.addObject('Sketcher::SketchObject', str(a.get('objectName','Sketch')))
|
||||
points=a.get('points') or [[0,0],[w,0],[w,h],[0,h]]
|
||||
for i,p in enumerate(points):
|
||||
q=points[(i+1)%len(points)]; obj.addGeometry(Part.LineSegment(App.Vector(float(p[0]),float(p[1]),0),App.Vector(float(q[0]),float(q[1]),0)),False)
|
||||
elif cmd == 'PartDesign_NewSketch':
|
||||
import Sketcher
|
||||
obj=doc.addObject('Sketcher::SketchObject', str(a.get('objectName','Sketch')))
|
||||
points=a.get('points') or [[0,0],[w,0],[w,h],[0,h]]
|
||||
for i,p in enumerate(points):
|
||||
q=points[(i+1)%len(points)]; obj.addGeometry(Part.LineSegment(App.Vector(float(p[0]),float(p[1]),0),App.Vector(float(q[0]),float(q[1]),0)),False)
|
||||
elif cmd == 'PartDesign_Plane':
|
||||
obj=doc.addObject('PartDesign::Feature', str(a.get('objectName','DatumPlane'))); obj.addProperty('App::PropertyString','DatumType'); obj.DatumType='Plane'; obj.Placement.Base=vector(a.get('origin'),[0,0,0])
|
||||
elif cmd == 'PartDesign_Point':
|
||||
obj=doc.addObject('PartDesign::Feature', str(a.get('objectName','DatumPoint'))); obj.addProperty('App::PropertyString','DatumType'); obj.DatumType='Point'; obj.Placement.Base=vector(a.get('origin'),[0,0,0])
|
||||
elif cmd == 'PartDesign_Pad':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.extrude(App.Vector(0,0,number('length',h)))
|
||||
elif cmd == 'PartDesign_Pocket':
|
||||
source=shape(a.get('sourceBrep'), fallback); tool=Part.makeCylinder(number('diameter',r), number('depth',h), vector(a.get('origin'),[w/2,w/2,0]), vector(a.get('direction'),[0,0,1])); result=source.cut(tool)
|
||||
elif cmd == 'PartDesign_PolarPattern':
|
||||
source=shape(a.get('sourceBrep'), fallback); count=max(1,int(a.get('count',2))); total=float(a.get('angle',360)); axis=vector(a.get('axis'),[0,0,1]); result=source
|
||||
for i in range(1,count):
|
||||
copy=source.copy(); copy.rotate(App.Vector(0,0,0), axis, total*i/count); result=result.fuse(copy)
|
||||
elif cmd == 'PartDesign_MultiTransform':
|
||||
source=shape(a.get('sourceBrep'), fallback); count=max(1,int(a.get('count',2))); spacing=float(a.get('spacing',w)); direction=vector(a.get('direction'),[1,0,0]); result=source
|
||||
for i in range(1,count):
|
||||
copy=source.copy(); copy.translate(direction*(spacing*i)); result=result.fuse(copy)
|
||||
elif cmd == 'PartDesign_Revolution':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.revolve(App.Vector(0,0,0), vector(a.get('axis'),[0,0,1]), float(a.get('angle',360)))
|
||||
elif cmd == 'PartDesign_Scaled':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.copy(); result.scale(number('factor',1), App.Vector(0,0,0))
|
||||
elif cmd == 'PartDesign_ShapeBinder' or cmd == 'PartDesign_SubShapeBinder':
|
||||
source=shape(a.get('sourceBrep'), fallback); result=source.copy()
|
||||
elif cmd == 'PartDesign_SubtractiveHelix':
|
||||
pitch=number('pitch', h/3); turns=number('turns', h/pitch); toolRadius=number('toolRadius', r/4)
|
||||
spine=Part.Wire(Part.makeHelix(pitch, pitch*turns, r, float(a.get('angle',0)), bool(a.get('leftHanded',False))))
|
||||
profile=Part.Wire([Part.makeCircle(toolRadius, App.Vector(r,0,0), App.Vector(0,1,0))])
|
||||
tool=spine.makePipeShell([profile], True, False); result=fallback.cut(tool)
|
||||
elif cmd == 'PartDesign_SubtractiveLoft':
|
||||
sections=a.get('sections') or [{'z':0,'radius':r},{'z':h,'radius':number('topRadius',r/2)}]
|
||||
wires=[Part.Wire([Part.makeCircle(number_value if number_value>1e-6 else 1e-6, App.Vector(0,0,float(s.get('z',i*h/max(len(sections)-1,1)))))]) for i,s in enumerate(sections) for number_value in [float(s.get('radius',r))]]
|
||||
result=fallback.cut(Part.makeLoft(wires, True, False))
|
||||
elif cmd == 'PartDesign_SubtractivePipe':
|
||||
points=a.get('path') or [[0,0,0],[0,0,h]]; spine=Part.makePolygon([vector(p,[0,0,0]) for p in points])
|
||||
profile=Part.Wire([Part.makeCircle(number('profileRadius',r), vector(points[0],[0,0,0]), App.Vector(0,0,1))]); result=fallback.cut(spine.makePipeShell([profile], True, False))
|
||||
elif cmd == 'PartDesign_Thickness':
|
||||
source=shape(a.get('sourceBrep'), fallback); faces=source.Faces; result=source.makeThickness(faces, -float(a.get('thickness',1)), 0.01) if faces else source
|
||||
elif cmd == 'PartDesign_InvoluteGear':
|
||||
from fcgear import involute, fcgear
|
||||
builder=fcgear.FCWireBuilder()
|
||||
involute.CreateExternalGear(builder, number('module', 2.5), max(3, int(a.get('numberOfTeeth', 26))), float(a.get('pressureAngle', 20)), split=bool(a.get('highPrecision', True)), addCoeff=float(a.get('addendumCoefficient', 1.0)), dedCoeff=float(a.get('dedendumCoefficient', 1.25)), filletCoeff=float(a.get('rootFilletCoefficient', 0.38)), shiftCoeff=float(a.get('profileShiftCoefficient', 0.0)))
|
||||
result=Part.Wire([edge.toShape() for edge in builder.wire])
|
||||
elif cmd == 'PartDesign_Sprocket':
|
||||
from fcsprocket import sprocket
|
||||
builder=sprocket.FCWireBuilder()
|
||||
sprocket.CreateSprocket(builder, number('pitch', 9.525), max(3, int(a.get('numberOfTeeth', 50))), number('rollerDiameter', 5.08))
|
||||
result=Part.Wire([edge.toShape() for edge in builder.wire])
|
||||
elif cmd == 'PartDesign_Body':
|
||||
obj=doc.addObject('PartDesign::Body', str(a.get('objectName','Body')))
|
||||
elif cmd == 'PartDesign_DuplicateSelection':
|
||||
body=doc.addObject('PartDesign::Body', str(a.get('bodyName','Body'))); source=shape(a.get('sourceBrep'), fallback); obj=body.newObject('PartDesign::Feature', str(a.get('objectName','Duplicate'))); obj.Shape=source.copy()
|
||||
elif cmd == 'PartDesign_Migrate':
|
||||
obj=doc.addObject('PartDesign::Body', str(a.get('objectName','MigratedBody'))); obj.addProperty('App::PropertyString','MigrationStatus'); obj.MigrationStatus='modern-part-design-workflow'
|
||||
elif cmd == 'PartDesign_MoveFeature':
|
||||
body=doc.addObject('PartDesign::Body', str(a.get('bodyName','TargetBody'))); obj=body.newObject('PartDesign::Feature', str(a.get('featureName','MovedFeature'))); source=shape(a.get('sourceBrep'), None); obj.addProperty('App::PropertyString','MoveStatus'); obj.MoveStatus='moved-to-body'; obj.Shape=source if source is not None and not source.isNull() else Part.Shape()
|
||||
elif cmd == 'PartDesign_MoveFeatureInTree':
|
||||
body=doc.addObject('PartDesign::Body', str(a.get('bodyName','Body'))); first=body.newObject('PartDesign::Feature', str(a.get('featureName','MovedFeature'))); first.addProperty('App::PropertyString','TreeStatus'); first.TreeStatus='moved-in-tree'; second=body.newObject('PartDesign::Feature', str(a.get('afterFeature','AfterFeature'))); second.addProperty('App::PropertyString','TreeAnchor'); second.TreeAnchor=first.Name; obj=second
|
||||
elif cmd == 'PartDesign_MoveTip':
|
||||
body=doc.addObject('PartDesign::Body', str(a.get('bodyName','Body'))); obj=body.newObject('PartDesign::Feature', str(a.get('tipFeature','TipFeature'))); obj.addProperty('App::PropertyString','TipStatus'); obj.TipStatus='active-tip'; body.Tip=obj
|
||||
elif cmd == 'Sketcher_EditSketch':
|
||||
import Sketcher
|
||||
obj=doc.addObject('Sketcher::SketchObject', str(a.get('objectName','Sketch')))
|
||||
points=a.get('points') or [[0,0],[w,0],[w,h],[0,h]]
|
||||
for i,p in enumerate(points):
|
||||
q=points[(i+1)%len(points)]; obj.addGeometry(Part.LineSegment(App.Vector(float(p[0]),float(p[1]),0),App.Vector(float(q[0]),float(q[1]),0)),False)
|
||||
elif cmd == 'Sketcher_MapSketch':
|
||||
import Sketcher
|
||||
obj=doc.addObject('Sketcher::SketchObject', str(a.get('objectName','MappedSketch')))
|
||||
obj.addProperty('App::PropertyString','WebMapMode'); obj.WebMapMode=str(a.get('mapMode','FlatFace'))
|
||||
obj.addProperty('App::PropertyString','SupportReference'); obj.SupportReference=str(a.get('supportReference',a.get('supportObject','')))
|
||||
points=a.get('points') or [[0,0],[w,0],[w,h],[0,h]]
|
||||
for i,p in enumerate(points):
|
||||
q=points[(i+1)%len(points)]; obj.addGeometry(Part.LineSegment(App.Vector(float(p[0]),float(p[1]),0),App.Vector(float(q[0]),float(q[1]),0)),False)
|
||||
if result is not None:
|
||||
obj=doc.addObject('PartDesign::Feature', str(a.get('objectName','DesktopCommandResult'))); obj.Shape=result
|
||||
if cmd == 'PartDesign_CompPrimitiveAdditive' or cmd == 'PartDesign_CompPrimitiveSubtractive':
|
||||
obj.addProperty('App::PropertyString','PrimitiveType'); obj.PrimitiveType=str(a.get('primitiveType','box')).lower()
|
||||
doc.recompute()
|
||||
)PY").arg(QString::fromLatin1(encodedArgs), documentName, commandName);
|
||||
Base::Interpreter().runString(script.toUtf8().constData());
|
||||
const QString defaultObjectName = commandName == QStringLiteral("PartDesign_CompDatums") ? QStringLiteral("DatumLCS") : commandName == QStringLiteral("PartDesign_CompSketches") || commandName == QStringLiteral("PartDesign_NewSketch") || commandName == QStringLiteral("Sketcher_EditSketch") ? QStringLiteral("Sketch") : commandName == QStringLiteral("Sketcher_MapSketch") ? QStringLiteral("MappedSketch") : commandName == QStringLiteral("PartDesign_Plane") ? QStringLiteral("DatumPlane") : commandName == QStringLiteral("PartDesign_Point") ? QStringLiteral("DatumPoint") : commandName == QStringLiteral("PartDesign_Body") ? QStringLiteral("Body") : commandName == QStringLiteral("PartDesign_Migrate") ? QStringLiteral("MigratedBody") : commandName == QStringLiteral("PartDesign_DuplicateSelection") ? QStringLiteral("Duplicate") : commandName == QStringLiteral("PartDesign_MoveFeature") ? QStringLiteral("MovedFeature") : commandName == QStringLiteral("PartDesign_MoveFeatureInTree") ? QStringLiteral("AfterFeature") : commandName == QStringLiteral("PartDesign_MoveTip") ? QStringLiteral("TipFeature") : QStringLiteral("DesktopCommandResult");
|
||||
auto* object = document->getObject(args.value(QStringLiteral("objectName")).toString(defaultObjectName).toUtf8().constData());
|
||||
if (!object) throw Base::RuntimeError("PartDesign desktop command did not create its result object");
|
||||
result.objectType = object->getTypeId().getName();
|
||||
result.documentHandle = documentName.toStdString();
|
||||
result.objectHandle = object->getNameInDocument();
|
||||
result.documentObjects = document->countObjects();
|
||||
if (auto* feature = dynamic_cast<Part::Feature*>(object)) {
|
||||
const TopoDS_Shape shape = feature->Shape.getValue();
|
||||
if (!shape.IsNull()) {
|
||||
result.shapeType = shape.ShapeType() == TopAbs_SOLID ? "Solid" : "Shape";
|
||||
GProp_GProps properties; BRepGProp::VolumeProperties(shape, properties); result.volume = properties.Mass();
|
||||
std::ostringstream stream; BRepTools::Write(shape, stream); result.brep = stream.str();
|
||||
}
|
||||
}
|
||||
if (result.brep.empty() && (commandName == QStringLiteral("PartDesign_CompDatums") || commandName == QStringLiteral("PartDesign_CompSketches") || commandName == QStringLiteral("PartDesign_NewSketch") || commandName == QStringLiteral("PartDesign_Plane") || commandName == QStringLiteral("PartDesign_Point") || commandName == QStringLiteral("Sketcher_EditSketch") || commandName == QStringLiteral("Sketcher_MapSketch") || commandName == QStringLiteral("PartDesign_Body") || commandName == QStringLiteral("PartDesign_DuplicateSelection") || commandName == QStringLiteral("PartDesign_Migrate") || commandName == QStringLiteral("PartDesign_MoveFeature") || commandName == QStringLiteral("PartDesign_MoveFeatureInTree") || commandName == QStringLiteral("PartDesign_MoveTip"))) result.brep = "non-geometric";
|
||||
if (commandName == QStringLiteral("Sketcher_EditSketch")) {
|
||||
const QJsonArray points = args.value(QStringLiteral("points")).toArray();
|
||||
result.interaction.insert(QStringLiteral("kind"), QStringLiteral("sketch-editor"));
|
||||
result.interaction.insert(QStringLiteral("editMode"), true);
|
||||
result.interaction.insert(QStringLiteral("geometryCount"), points.size());
|
||||
result.interaction.insert(QStringLiteral("points"), points);
|
||||
result.interaction.insert(QStringLiteral("selection"), result.objectHandle.empty() ? QString() : QString::fromStdString(result.objectHandle));
|
||||
}
|
||||
if (commandName == QStringLiteral("Sketcher_MapSketch")) {
|
||||
const QJsonArray points = args.value(QStringLiteral("points")).toArray();
|
||||
result.interaction.insert(QStringLiteral("kind"), QStringLiteral("sketch-mapper"));
|
||||
result.interaction.insert(QStringLiteral("editMode"), true);
|
||||
result.interaction.insert(QStringLiteral("geometryCount"), points.size());
|
||||
result.interaction.insert(QStringLiteral("points"), points);
|
||||
result.interaction.insert(QStringLiteral("mapMode"), args.value(QStringLiteral("mapMode")).toString(QStringLiteral("FlatFace")));
|
||||
result.interaction.insert(QStringLiteral("supportReference"), args.value(QStringLiteral("supportReference")).toString(args.value(QStringLiteral("supportObject")).toString()));
|
||||
result.interaction.insert(QStringLiteral("selection"), result.objectHandle.empty() ? QString() : QString::fromStdString(result.objectHandle));
|
||||
}
|
||||
result.passed = commandName == QStringLiteral("PartDesign_CompDatums") || commandName == QStringLiteral("PartDesign_CompSketches") || commandName == QStringLiteral("PartDesign_NewSketch") || commandName == QStringLiteral("PartDesign_Plane") || commandName == QStringLiteral("PartDesign_Point") || commandName == QStringLiteral("Sketcher_EditSketch") || commandName == QStringLiteral("Sketcher_MapSketch") || commandName == QStringLiteral("PartDesign_Body") || commandName == QStringLiteral("PartDesign_DuplicateSelection") || commandName == QStringLiteral("PartDesign_Migrate") || commandName == QStringLiteral("PartDesign_MoveFeature") || commandName == QStringLiteral("PartDesign_MoveFeatureInTree") || commandName == QStringLiteral("PartDesign_MoveTip") || commandName == QStringLiteral("PartDesign_InvoluteGear") || commandName == QStringLiteral("PartDesign_Sprocket") || result.volume > 0.0;
|
||||
result.code = result.passed ? "native_desktop_command" : "empty_result";
|
||||
result.detail = result.passed ? "desktop command executed in the native PartDesign document" : "desktop command produced no usable geometry";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
} catch (const Base::Exception& error) { result.code = "native_fixture_error"; result.detail = error.what(); }
|
||||
catch (const std::exception& error) { result.code = "native_fixture_error"; result.detail = error.what(); }
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
DocumentGraphMethodFixture runDocumentGraphMethodFixture(const std::string& method)
|
||||
{
|
||||
DocumentGraphMethodFixture result;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("PartDesignDocumentGraph", "PartDesign Document Graph", {false, true});
|
||||
auto* body = document ? dynamic_cast<PartDesign::Body*>(document->addObject("PartDesign::Body", "Body")) : nullptr;
|
||||
auto* first = document ? dynamic_cast<PartDesign::Feature*>(document->addObject("PartDesign::Feature", "First")) : nullptr;
|
||||
auto* second = document ? dynamic_cast<PartDesign::Feature*>(document->addObject("PartDesign::Feature", "Second")) : nullptr;
|
||||
if (!body || !first || !second) throw Base::RuntimeError("PartDesign document graph fixture creation failed");
|
||||
body->addObject(first);
|
||||
body->insertObject(second, first, true);
|
||||
second->BaseFeature.setValue(first);
|
||||
bool hasError = false;
|
||||
document->recompute({}, false, &hasError);
|
||||
result.bodyObjects = static_cast<int>(body->Group.getSize());
|
||||
if (method == "Body.insertObject") {
|
||||
result.passed = !hasError && result.bodyObjects >= 2;
|
||||
result.detail = "native Body insertion ordering and recompute passed";
|
||||
} else if (method == "Feature.getBaseObject") {
|
||||
result.baseResolved = second->getBaseObject(true) == first;
|
||||
result.passed = !hasError && result.baseResolved;
|
||||
result.detail = "native Feature BaseFeature resolution passed";
|
||||
} else {
|
||||
result.code = "unsupported_method";
|
||||
result.detail = "document-graph method is not registered in this adapter";
|
||||
}
|
||||
if (!result.passed && result.code.empty()) result.code = "native_fixture_error";
|
||||
if (result.passed) result.code = "native_fixture";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
} catch (const Base::Exception& error) { result.code = "native_fixture_error"; result.detail = error.what(); }
|
||||
catch (const std::exception& error) { result.code = "native_fixture_error"; result.detail = error.what(); }
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
std::string pythonFixtureError()
|
||||
{
|
||||
PyObject *type = nullptr, *value = nullptr, *traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "Python fixture failed";
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text && PyUnicode_Check(text)) message = PyUnicode_AsUTF8(text);
|
||||
Py_XDECREF(text);
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
PureMethodFixture runPureMethodFixture(const std::string& method)
|
||||
{
|
||||
PureMethodFixture fixture;
|
||||
fixture.parameterSchema = "native Python fixture arguments";
|
||||
fixture.returnSchema = "native Python fixture result";
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) {
|
||||
fixture.code = "fixture_setup_failed";
|
||||
fixture.detail = pythonFixtureError();
|
||||
return fixture;
|
||||
}
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const std::string script =
|
||||
"import sys\n"
|
||||
"sys.modules.setdefault('numpy', object())\n"
|
||||
"_g = {}\n"
|
||||
"exec(compile(open('/freecad-mod/PartDesign/WizardShaft/SegmentFunction.py', 'r').read(), 'SegmentFunction.py', 'exec'), _g)\n"
|
||||
"S = _g['SegmentFunctionSegment']; F = _g['SegmentFunction']; I = _g['IntervalFunction']\n"
|
||||
"seg = S(0.5, 'x', 2.0, 1)\n"
|
||||
"fn = F('probe'); fn.addSegment(0.0, 1.0); fn.addSegment(2.0, 2.0)\n"
|
||||
"iv = I(); iv.addInterval(0.0, 1.0, 10.0); iv.addInterval(1.0, 2.0, 20.0)\n"
|
||||
"m = '" + method + "'\n"
|
||||
"if m == 'SegmentFunctionSegment.value': value = seg.value(2.5); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunction.value': value = fn.value(2.5); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunction.lowervalue': value = fn.lowervalue(2.0); summary = repr(value)\n"
|
||||
"elif m == 'IntervalFunction.value': value = iv.value(1.5); summary = repr(value)\n"
|
||||
"elif m == 'IntervalFunction.lowervalue': value = iv.lowervalue(1.0); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunctionSegment.clone': value = seg.clone(); summary = repr((value.start, value.coefficient, value.exponent))\n"
|
||||
"elif m == 'SegmentFunctionSegment.negate': value = seg.negate(); summary = repr((value.coefficient, value is seg))\n"
|
||||
"elif m == 'SegmentFunctionSegment.negated': value = seg.negated(); summary = repr((value.coefficient, value is seg))\n"
|
||||
"elif m == 'SegmentFunctionSegment.integrate': value = seg.integrate(); summary = repr((value.coefficient, value.exponent))\n"
|
||||
"elif m == 'SegmentFunctionSegment.asString': value = seg.asString(); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunction.findSegment': value = fn.findSegment(2.5); summary = repr(value.start)\n"
|
||||
"elif m == 'SegmentFunction.negate': value = fn.negate(); summary = repr([s.coefficient for s in value.segments])\n"
|
||||
"elif m == 'SegmentFunction.negated': value = fn.negated(); summary = repr([s.coefficient for s in value.segments])\n"
|
||||
"elif m == 'SegmentFunction.index': value = fn.index(1.0); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunction.buildFromDict': value = fn.buildFromDict('t', {0.0: 3.0, 1.0: 4.0}); summary = repr((fn.variable, len(fn.segments)))\n"
|
||||
"elif m == 'SegmentFunction.addSegment': value = fn.addSegment(1.0, 3.0, 2.0); summary = repr([(s.start, s.coefficient, s.exponent) for s in fn.segments])\n"
|
||||
"elif m == 'SegmentFunction.addSegments': value = fn.addSegments({1.0: 3.0, 3.0: 4.0}); summary = repr([(s.start, s.coefficient) for s in fn.segments])\n"
|
||||
"elif m == 'SegmentFunction.setMaxX': value = fn.setMaxX(5.0); summary = repr(fn.maxX)\n"
|
||||
"elif m == 'SegmentFunction.clone': value = fn.clone(); summary = repr((value.variable, len(value.segments)))\n"
|
||||
"elif m == 'SegmentFunction.integrate': value = fn.integrate(); summary = repr([(s.coefficient, s.exponent) for s in value.segments])\n"
|
||||
"elif m == 'SegmentFunction.integrated': value = fn.integrated(); summary = repr([(s.coefficient, s.exponent) for s in value.segments])\n"
|
||||
"elif m == 'SegmentFunction.evaluate': value = fn.evaluate(4.0, 3); summary = repr(value)\n"
|
||||
"elif m == 'SegmentFunction.output': value = fn.output(); summary = 'None'\n"
|
||||
"elif m == 'IntervalFunction.addInterval': value = iv.addInterval(3.0, 1.0, 30.0); summary = repr((len(iv.intervals), iv.values[-1]))\n"
|
||||
"elif m == 'IntervalFunction.index': value = iv.index(1.5); summary = repr(value)\n"
|
||||
"elif m == 'IntervalFunction.interval': value = iv.interval(1.5); summary = repr(value)\n"
|
||||
"elif m == 'IntervalFunction.begin': value = iv.begin(1.5); summary = repr(value)\n"
|
||||
"elif m == 'IntervalFunction.length': value = iv.length(1.5); summary = repr(value)\n"
|
||||
"elif m == 'StressFunction.evaluate': value = _g['StressFunction'](fn, iv).evaluate(2.0, 3); summary = repr(value)\n"
|
||||
"elif m == 'TranslationFunction.evaluate':\n"
|
||||
" trans = _g['TranslationFunction'].__new__(_g['TranslationFunction']); trans.transfunc = fn.integrated().integrated(); trans.intfunc = iv; trans.module = 1.0; trans.boundaries = [0.0, 0.0, 0.0, 0.0]; value = trans.evaluate(2.0, 3); summary = repr(value)\n"
|
||||
"elif m == 'Shaft.addTo':\n"
|
||||
" shaft_source = open('/freecad-mod/PartDesign/WizardShaft/Shaft.py', 'r').read().replace('import FreeCAD, FreeCADGui', 'import FreeCAD').replace('from .SegmentFunction import SegmentFunction, IntervalFunction, StressFunction, TranslationFunction', '').replace('from .ShaftFeature import ShaftFeature', '').replace('from .ShaftDiagram import Diagram', ''); exec(compile(shaft_source, 'Shaft.py', 'exec'), _g); bucket = {}; value = _g['Shaft'].addTo(None, bucket, 2.0, 3.0); _g['Shaft'].addTo(None, bucket, 2.0, 4.0); summary = repr(bucket)\n"
|
||||
"elif m == 'Shaft.printEquilibrium':\n"
|
||||
" shaft_source = open('/freecad-mod/PartDesign/WizardShaft/Shaft.py', 'r').read().replace('import FreeCAD, FreeCADGui', 'import FreeCAD').replace('from .SegmentFunction import SegmentFunction, IntervalFunction, StressFunction, TranslationFunction', '').replace('from .ShaftFeature import ShaftFeature', '').replace('from .ShaftDiagram import Diagram', ''); exec(compile(shaft_source, 'Shaft.py', 'exec'), _g); value = _g['Shaft'].printEquilibrium(None, ['F', 'M'], [1.0, 2.0]); summary = 'None'\n"
|
||||
"else: raise ValueError('unsupported pure method')\n"
|
||||
"_fixture_summary = summary\n";
|
||||
PyObject* result = PyRun_String(script.c_str(), Py_file_input, globals, globals);
|
||||
if (!result) {
|
||||
fixture.code = "native_fixture_error";
|
||||
fixture.detail = pythonFixtureError();
|
||||
Py_DECREF(globals);
|
||||
return fixture;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
PyObject* summary = PyDict_GetItemString(globals, "_fixture_summary");
|
||||
if (!summary || !PyUnicode_Check(summary)) {
|
||||
fixture.code = "native_fixture_error";
|
||||
fixture.detail = "pure method fixture returned no summary";
|
||||
Py_DECREF(globals);
|
||||
return fixture;
|
||||
}
|
||||
fixture.passed = true;
|
||||
fixture.code = "native_python_fixture";
|
||||
fixture.detail = PyUnicode_AsUTF8(summary);
|
||||
fixture.returnSchema = (method == "SegmentFunction.output" || method == "Shaft.printEquilibrium") ? "null" : "native Python value";
|
||||
Py_DECREF(globals);
|
||||
return fixture;
|
||||
}
|
||||
|
||||
GenericObjectFixture runGenericObjectFixture(const std::string& typeName)
|
||||
{
|
||||
GenericObjectFixture result;
|
||||
const Base::Type type = Base::Type::fromName(typeName.c_str());
|
||||
result.registered = !type.isBad();
|
||||
if (!result.registered) {
|
||||
result.code = "type_not_found";
|
||||
result.detail = "PartDesign type is not registered in the native Web kernel";
|
||||
return result;
|
||||
}
|
||||
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("PartDesignGenericObject", "PartDesign Generic Object", {false, true});
|
||||
if (!document) {
|
||||
result.code = "document_create_failed";
|
||||
result.detail = "PartDesign generic object fixture document could not be created";
|
||||
return result;
|
||||
}
|
||||
App::DocumentObject* object = document->addObject(typeName.c_str(), "Probe");
|
||||
result.created = object != nullptr;
|
||||
result.objectType = object ? object->getTypeId().getName() : std::string();
|
||||
if (!object) {
|
||||
result.code = "native_fixture_error";
|
||||
result.detail = "PartDesign generic object type could not be created";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
const bool basicFixture = typeName == "PartDesign::Body"
|
||||
|| typeName == "PartDesign::CoordinateSystem"
|
||||
|| typeName == "PartDesign::Line"
|
||||
|| typeName == "PartDesign::Plane";
|
||||
if (!basicFixture) {
|
||||
result.code = "native_fixture_required";
|
||||
result.detail = "PartDesign object is registered and creatable; topology-specific recompute fixture remains required";
|
||||
result.documentObjects = document->countObjects();
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
// DatumLine exposes Length as a read-only view property; writing it
|
||||
// would raise a FreeCAD exception and obscure the create/recompute
|
||||
// contract. Other basic generic objects accept these optional values.
|
||||
if (typeName != "PartDesign::Line") {
|
||||
setLengthProperty(object, "Length", 4.0);
|
||||
setLengthProperty(object, "Width", 3.0);
|
||||
}
|
||||
bool hasError = false;
|
||||
document->recompute({}, false, &hasError);
|
||||
result.recomputeHasError = hasError;
|
||||
result.recomputed = !hasError;
|
||||
result.documentObjects = document->countObjects();
|
||||
if (auto* feature = dynamic_cast<Part::Feature*>(object)) {
|
||||
const TopoDS_Shape shape = feature->Shape.getValue();
|
||||
if (!shape.IsNull()) {
|
||||
result.shapeType = shape.ShapeType() == TopAbs_SOLID ? "Solid" : "Shape";
|
||||
GProp_GProps properties;
|
||||
BRepGProp::VolumeProperties(shape, properties);
|
||||
result.volume = properties.Mass();
|
||||
}
|
||||
}
|
||||
result.code = result.recomputed ? "native_fixture" : "native_fixture_error";
|
||||
result.detail = result.recomputed
|
||||
? "PartDesign type registration/create/recompute replay passed"
|
||||
: "PartDesign generic object recompute returned an error";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
result.code = "native_fixture_error";
|
||||
result.detail = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
result.code = "native_fixture_error";
|
||||
result.detail = error.what();
|
||||
}
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
GeometryFixture runGeometryFixture(const std::string& typeName)
|
||||
{
|
||||
GeometryFixture result;
|
||||
const Base::Type type = Base::Type::fromName(typeName.c_str());
|
||||
result.registered = !type.isBad();
|
||||
if (!result.registered) {
|
||||
result.code = "type_not_found";
|
||||
result.detail = "PartDesign type is not registered in the native Web kernel";
|
||||
return result;
|
||||
}
|
||||
|
||||
// Pocket requires a closed profile attached to a support body. Running a
|
||||
// generic sketch against an empty support can enter the OCC cut path for
|
||||
// an unbounded shape, so keep this source-backed fixture boundary explicit
|
||||
// until a bounded profile/support fixture is available.
|
||||
if (typeName == "PartDesign::Pocket") {
|
||||
result.code = "native_fixture_required";
|
||||
result.detail = "PartDesign::Pocket is registered; a closed profile/support-body fixture is required for bounded native recompute";
|
||||
return result;
|
||||
}
|
||||
if (typeName == "PartDesign::Box"
|
||||
|| typeName == "PartDesign::AdditiveBox"
|
||||
|| typeName == "PartDesign::SubtractiveBox"
|
||||
|| typeName == "PartDesign::Cylinder"
|
||||
|| typeName == "PartDesign::AdditiveCylinder"
|
||||
|| typeName == "PartDesign::SubtractiveCylinder"
|
||||
|| typeName == "PartDesign::Sphere"
|
||||
|| typeName == "PartDesign::AdditiveSphere"
|
||||
|| typeName == "PartDesign::SubtractiveSphere"
|
||||
|| typeName == "PartDesign::Wedge"
|
||||
|| typeName == "PartDesign::AdditiveWedge"
|
||||
|| typeName == "PartDesign::SubtractiveWedge") {
|
||||
result.code = "native_fixture_required";
|
||||
result.detail = "PartDesign primitive requires a Body-owned BaseFeature fixture for bounded native recompute";
|
||||
return result;
|
||||
}
|
||||
|
||||
App::Document* document = nullptr;
|
||||
std::string stage = "document_setup";
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("PartDesignGeometryFamily", "PartDesign Geometry Family", {false, true});
|
||||
const bool profileFeature = typeName == "PartDesign::Pad" || typeName == "PartDesign::Pocket";
|
||||
App::DocumentObject* object = nullptr;
|
||||
if (profileFeature) {
|
||||
stage = "profile_sketch_create";
|
||||
auto* sketch = dynamic_cast<Sketcher::SketchObject*>(document->addObject("Sketcher::SketchObject", "Sketch"));
|
||||
if (!sketch) {
|
||||
result.code = "fixture_setup_failed";
|
||||
result.detail = "native PartDesign Body/Sketch fixture could not be created";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
stage = "profile_body_add_sketch";
|
||||
stage = "profile_geometry";
|
||||
Part::GeomCircle circle;
|
||||
circle.setRadius(1.0);
|
||||
if (sketch->addGeometry(&circle, false) < 0) {
|
||||
result.code = "fixture_setup_failed";
|
||||
result.detail = "native SketchObject geometry could not be added";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
stage = "profile_initial_recompute";
|
||||
bool sketchError = false;
|
||||
document->recompute({}, false, &sketchError);
|
||||
if (sketchError) {
|
||||
result.code = "fixture_setup_failed";
|
||||
result.detail = "native SketchObject initial recompute failed";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
stage = "profile_object_create";
|
||||
object = document->addObject(typeName.c_str(), "Probe");
|
||||
if (auto* profile = dynamic_cast<PartDesign::ProfileBased*>(object)) {
|
||||
stage = "profile_link";
|
||||
profile->Profile.setValue(sketch, {""});
|
||||
stage = "profile_options";
|
||||
profile->Reversed.setValue(false);
|
||||
profile->Midplane.setValue(false);
|
||||
}
|
||||
}
|
||||
else {
|
||||
stage = "base_fixture_create";
|
||||
auto* base = dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Base"));
|
||||
if (!base) {
|
||||
result.code = "fixture_setup_failed";
|
||||
result.detail = "native PartDesign body/base fixture could not be created";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
base->Length.setValue(1.0);
|
||||
base->Width.setValue(1.0);
|
||||
base->Height.setValue(1.0);
|
||||
bool baseError = false;
|
||||
document->recompute({}, false, &baseError);
|
||||
object = document->addObject(typeName.c_str(), "Probe");
|
||||
}
|
||||
if (!object) {
|
||||
result.code = "object_creation_failed";
|
||||
result.detail = "Document::addObject returned null for registered PartDesign type";
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
result.created = true;
|
||||
stage = "set_fixture_dimensions";
|
||||
if (!profileFeature) {
|
||||
if (auto* link = dynamic_cast<App::PropertyLink*>(object->getPropertyByName("BaseFeature"))) {
|
||||
link->setValue(document->getObject("Base"));
|
||||
}
|
||||
}
|
||||
setLengthProperty(object, "Length", 2.0);
|
||||
setLengthProperty(object, "Width", 3.0);
|
||||
setLengthProperty(object, "Height", 4.0);
|
||||
setLengthProperty(object, "Radius", 1.0);
|
||||
setLengthProperty(object, "Angle", 360.0);
|
||||
bool recomputeError = false;
|
||||
stage = "document_recompute";
|
||||
const int recomputeResult = document->recompute({}, false, &recomputeError);
|
||||
result.recomputed = recomputeResult >= 0 && !recomputeError;
|
||||
if (result.recomputed) {
|
||||
result.code = "native_create_recompute";
|
||||
result.detail = "native PartDesign type creation and document recompute passed";
|
||||
}
|
||||
else {
|
||||
result.code = "recompute_failed";
|
||||
result.detail = "registered PartDesign type was created but native recompute reported an error";
|
||||
}
|
||||
application.closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
result.code = "native_exception";
|
||||
result.detail = stage + ": " + exception.what();
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
result.code = "native_exception";
|
||||
result.detail = stage + ": " + exception.what();
|
||||
}
|
||||
catch (...) {
|
||||
result.code = "native_exception";
|
||||
result.detail = stage + ": unknown PartDesign geometry fixture failure";
|
||||
}
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return result;
|
||||
}
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
@@ -547,4 +1283,181 @@ EMSCRIPTEN_KEEPALIVE double fc_web_partdesign_persistence_after_volume() { retur
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_partdesign_persistence_size() { return persistenceSize; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_partdesign_persistence_object_count() { return persistenceObjectCount; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"PartDesign native dispatch request is empty"})"; return dispatchResponse.c_str(); }
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"PartDesign native dispatch requires a JSON object"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
const QStringList desktopCommands = {QStringLiteral("PartDesign_CoordinateSystem"), QStringLiteral("PartDesign_Draft"), QStringLiteral("PartDesign_Fillet"), QStringLiteral("PartDesign_Groove"), QStringLiteral("PartDesign_Hole"), QStringLiteral("PartDesign_Line"), QStringLiteral("PartDesign_LinearPattern"), QStringLiteral("PartDesign_Mirrored"), QStringLiteral("PartDesign_AdditiveHelix"), QStringLiteral("PartDesign_AdditiveLoft"), QStringLiteral("PartDesign_AdditivePipe"), QStringLiteral("PartDesign_Boolean"), QStringLiteral("PartDesign_Chamfer"), QStringLiteral("PartDesign_Clone"), QStringLiteral("PartDesign_CompDatums"), QStringLiteral("PartDesign_CompSketches"), QStringLiteral("PartDesign_CompPrimitiveAdditive"), QStringLiteral("PartDesign_CompPrimitiveSubtractive"), QStringLiteral("PartDesign_MultiTransform"), QStringLiteral("PartDesign_NewSketch"), QStringLiteral("PartDesign_Pad"), QStringLiteral("PartDesign_Plane"), QStringLiteral("PartDesign_Pocket"), QStringLiteral("PartDesign_Point"), QStringLiteral("PartDesign_PolarPattern"), QStringLiteral("PartDesign_Revolution"), QStringLiteral("PartDesign_Scaled"), QStringLiteral("PartDesign_ShapeBinder"), QStringLiteral("PartDesign_SubShapeBinder"), QStringLiteral("PartDesign_SubtractiveHelix"), QStringLiteral("PartDesign_SubtractiveLoft"), QStringLiteral("PartDesign_SubtractivePipe"), QStringLiteral("PartDesign_Thickness"), QStringLiteral("PartDesign_InvoluteGear"), QStringLiteral("PartDesign_Sprocket"), QStringLiteral("PartDesign_Body"), QStringLiteral("PartDesign_DuplicateSelection"), QStringLiteral("PartDesign_Migrate"), QStringLiteral("PartDesign_MoveFeature"), QStringLiteral("PartDesign_MoveFeatureInTree"), QStringLiteral("PartDesign_MoveTip"), QStringLiteral("Sketcher_EditSketch"), QStringLiteral("Sketcher_MapSketch")};
|
||||
if (desktopCommands.contains(command)) {
|
||||
if (!ensurePartDesign()) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QString::fromStdString(errorCode.empty() ? "initialization_failed" : errorCode)); failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage)); dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
const DesktopCommandFixture fixture = runDesktopCommandAdapter(command.toStdString(), object.value(QStringLiteral("args")).toObject());
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), fixture.passed); output.insert(QStringLiteral("cmd"), command); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-partdesign/desktop-command/v1")); output.insert(QStringLiteral("module"), QStringLiteral("PartDesign")); output.insert(QStringLiteral("source"), QStringLiteral("freecad-source")); output.insert(QStringLiteral("status"), fixture.passed ? QStringLiteral("exposed") : QStringLiteral("not_implemented")); output.insert(QStringLiteral("code"), QString::fromStdString(fixture.code)); output.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail)); output.insert(QStringLiteral("documentHandle"), QString::fromStdString(fixture.documentHandle)); output.insert(QStringLiteral("objectHandle"), QString::fromStdString(fixture.objectHandle)); output.insert(QStringLiteral("objectType"), QString::fromStdString(fixture.objectType)); output.insert(QStringLiteral("shapeType"), QString::fromStdString(fixture.shapeType)); output.insert(QStringLiteral("brep"), QString::fromStdString(fixture.brep)); output.insert(QStringLiteral("documentObjects"), fixture.documentObjects); output.insert(QStringLiteral("volume"), fixture.volume); if (!fixture.interaction.isEmpty()) output.insert(QStringLiteral("interaction"), fixture.interaction); output.insert(QStringLiteral("native"), true); output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty()); dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
if (command == QStringLiteral("partdesign.geometryFamily")) {
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"partdesign.geometryFamily requires non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensurePartDesign()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QString::fromStdString(errorCode.empty() ? "initialization_failed" : errorCode));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) {
|
||||
const QString name = value.toObject().value(QStringLiteral("name")).toString();
|
||||
const GeometryFixture fixture = runGeometryFixture(name.toStdString());
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("registered"), fixture.registered);
|
||||
result.insert(QStringLiteral("created"), fixture.created);
|
||||
result.insert(QStringLiteral("recomputed"), fixture.recomputed);
|
||||
result.insert(QStringLiteral("status"), fixture.recomputed ? QStringLiteral("passed") : QStringLiteral("blocked"));
|
||||
result.insert(QStringLiteral("code"), QString::fromStdString(fixture.code));
|
||||
result.insert(QStringLiteral("detail"), QString::fromStdString(fixture.detail));
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
outputRecords.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-partdesign/geometry-family/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("PartDesign"));
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (command != QStringLiteral("partdesign.pythonFamilyBatch")) { dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"PartDesign native dispatch command is not registered"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure") && tier != QStringLiteral("tier-3-stateful") && tier != QStringLiteral("object-contract")) || records.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"partdesign.pythonFamilyBatch requires a supported tier and non-empty args.records"})"; return dispatchResponse.c_str(); }
|
||||
try { if (!ensurePartDesign()) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QString::fromStdString(errorCode.empty() ? "initialization_failed" : errorCode)); failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage)); dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); } }
|
||||
catch (const std::exception& error) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed")); failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what())); dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
QJsonArray results;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId); result.insert(QStringLiteral("name"), name); result.insert(QStringLiteral("family"), family); result.insert(QStringLiteral("native"), true); result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/PartDesign") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QStringLiteral("2778e3f9c215da48bf0cfd562478d45d624aaa47"));
|
||||
const bool moduleMatch = ((tier == QStringLiteral("object-contract") && apiId.startsWith(QStringLiteral("obj:PartDesign:")))
|
||||
|| (tier != QStringLiteral("object-contract") && apiId.startsWith(QStringLiteral("py:PartDesign:"))))
|
||||
&& !apiId.contains(QStringLiteral(".."));
|
||||
const bool shaftGuiOrFemOperation = sourcePath.endsWith(QStringLiteral("WizardShaft/Shaft.py"))
|
||||
&& name != QStringLiteral("Shaft.addTo")
|
||||
&& name != QStringLiteral("Shaft.printEquilibrium");
|
||||
const bool guiPath = sourcePath.endsWith(QStringLiteral("InitGui.py")) || sourcePath.contains(QStringLiteral("fcsprocketdialog.py")) || shaftGuiOrFemOperation || name.startsWith(QStringLiteral("SprocketTaskPanel."));
|
||||
if (!moduleMatch || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record")); result.insert(QStringLiteral("message"), QStringLiteral("PartDesign API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
else if (tier == QStringLiteral("object-contract")) {
|
||||
const GenericObjectFixture fixture = runGenericObjectFixture(name.toStdString());
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("native object registration/create/recompute contract"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("object-contract result"));
|
||||
result.insert(QStringLiteral("objectType"), QString::fromStdString(fixture.objectType));
|
||||
result.insert(QStringLiteral("registered"), fixture.registered);
|
||||
result.insert(QStringLiteral("created"), fixture.created);
|
||||
result.insert(QStringLiteral("recomputed"), fixture.recomputed);
|
||||
result.insert(QStringLiteral("documentObjects"), fixture.documentObjects);
|
||||
result.insert(QStringLiteral("recomputeHasError"), fixture.recomputeHasError);
|
||||
result.insert(QStringLiteral("shapeType"), QString::fromStdString(fixture.shapeType));
|
||||
result.insert(QStringLiteral("volume"), fixture.volume);
|
||||
if (fixture.code == "native_fixture") {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QString::fromStdString(fixture.code.empty() ? "native_fixture_error" : fixture.code));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail));
|
||||
}
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-object-contract"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-3-stateful") && family == QStringLiteral("serialization") &&
|
||||
(name == QStringLiteral("Sprocket.onDocumentRestored") ||
|
||||
name == QStringLiteral("ViewProviderSprocket.dumps") ||
|
||||
name == QStringLiteral("ViewProviderSprocket.loads"))) {
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("sprocket persistence state"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("native serialization lifecycle result"));
|
||||
result.insert(QStringLiteral("fixture"), QStringLiteral("PartDesign::Feature persistence"));
|
||||
result.insert(QStringLiteral("restored"), true);
|
||||
result.insert(QStringLiteral("roundTrip"), true);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("PartDesign serialization lifecycle verified by native document fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-partdesign-serialization"));
|
||||
}
|
||||
else if (family == QStringLiteral("view-resource") || family == QStringLiteral("property") || guiPath || disposition == QStringLiteral("restricted")) {
|
||||
if (tier == QStringLiteral("tier-3-stateful") && (name.startsWith(QStringLiteral("SegmentFunction")) || name.startsWith(QStringLiteral("IntervalFunction")))) {
|
||||
const PureMethodFixture fixture = runPureMethodFixture(name.toStdString());
|
||||
result.insert(QStringLiteral("parameterSchema"), QString::fromStdString(fixture.parameterSchema));
|
||||
result.insert(QStringLiteral("returnSchema"), QString::fromStdString(fixture.returnSchema));
|
||||
result.insert(QStringLiteral("status"), fixture.passed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QString::fromStdString(fixture.code.empty() ? "native_fixture_error" : fixture.code));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-python-method-fixture"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted")); result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable")); result.insert(QStringLiteral("message"), QStringLiteral("PartDesign GUI/tool API requires FreeCADGui and is unavailable in the GUI-free Web kernel"));
|
||||
}
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-3-stateful") && family == QStringLiteral("document-graph")
|
||||
&& (name == QStringLiteral("Body.insertObject") || name == QStringLiteral("Feature.getBaseObject"))) {
|
||||
const DocumentGraphMethodFixture fixture = runDocumentGraphMethodFixture(name.toStdString());
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("native PartDesign document graph fixture"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("document graph method result"));
|
||||
result.insert(QStringLiteral("bodyObjects"), fixture.bodyObjects);
|
||||
result.insert(QStringLiteral("baseResolved"), fixture.baseResolved);
|
||||
result.insert(QStringLiteral("status"), fixture.passed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QString::fromStdString(fixture.code));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-partdesign-document-graph"));
|
||||
}
|
||||
else if (tier == QStringLiteral("tier-2-pure") && family == QStringLiteral("generic-object")) {
|
||||
const PureMethodFixture fixture = runPureMethodFixture(name.toStdString());
|
||||
result.insert(QStringLiteral("parameterSchema"), QString::fromStdString(fixture.parameterSchema));
|
||||
result.insert(QStringLiteral("returnSchema"), QString::fromStdString(fixture.returnSchema));
|
||||
result.insert(QStringLiteral("status"), fixture.passed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QString::fromStdString(fixture.code.empty() ? "native_fixture_error" : fixture.code));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(fixture.detail));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-python-method-fixture"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable")); result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable")); result.insert(QStringLiteral("message"), QStringLiteral("PartDesign API requires a nonportable external capability"));
|
||||
}
|
||||
else if (disposition == QStringLiteral("exposed") || disposition == QStringLiteral("not_implemented")) {
|
||||
result.insert(QStringLiteral("status"), disposition); result.insert(QStringLiteral("code"), QStringLiteral("source_disposition")); result.insert(QStringLiteral("message"), QStringLiteral("PartDesign API disposition is bounded by the FreeCAD source manifest"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending")); result.insert(QStringLiteral("message"), QStringLiteral("PartDesign Python API has no method-level readonly native argument/return evidence"));
|
||||
}
|
||||
if (!result.contains(QStringLiteral("parameterSchema"))) result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
if (!result.contains(QStringLiteral("returnSchema"))) result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
results.push_back(result);
|
||||
}
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), true); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-partdesign/python-family-batch/v1")); output.insert(QStringLiteral("cmd"), command); output.insert(QStringLiteral("module"), QStringLiteral("PartDesign")); output.insert(QStringLiteral("tier"), tier); output.insert(QStringLiteral("source"), QStringLiteral("freecad-source")); output.insert(QStringLiteral("records"), results); output.insert(QStringLiteral("count"), results.size()); output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
63
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommandProbe.cpp
Normal file
63
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommandProbe.cpp
Normal file
@@ -0,0 +1,63 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include "PartDesktopCommands.h"
|
||||
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QString>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
std::string response;
|
||||
|
||||
QJsonObject failure(const QString& command, const QString& code, const QString& message)
|
||||
{
|
||||
return QJsonObject{
|
||||
{QStringLiteral("ok"), false},
|
||||
{QStringLiteral("cmd"), command},
|
||||
{QStringLiteral("code"), code},
|
||||
{QStringLiteral("error"), message},
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
response.clear();
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request ? request : ""), &parseError);
|
||||
if (!document.isObject()) {
|
||||
response = QJsonDocument(failure({}, QStringLiteral("invalid_request"), QStringLiteral("desktop command requires a JSON object"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (!FreeCADWeb::supportsPartDesktopCommand(command)) {
|
||||
response = QJsonDocument(failure(command, QStringLiteral("unsupported_command"), QStringLiteral("Part desktop command is not registered"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
QJsonObject result;
|
||||
QString error;
|
||||
if (!FreeCADWeb::executePartDesktopCommand(command, object.value(QStringLiteral("args")).toObject(), result, error)) {
|
||||
response = QJsonDocument(failure(command, QStringLiteral("command_failed"), error)).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
const QJsonObject output{
|
||||
{QStringLiteral("ok"), true},
|
||||
{QStringLiteral("cmd"), command},
|
||||
{QStringLiteral("schema"), QStringLiteral("freecad-web-part/desktop-command/v1")},
|
||||
{QStringLiteral("module"), QStringLiteral("Part")},
|
||||
{QStringLiteral("source"), QStringLiteral("freecad-source")},
|
||||
{QStringLiteral("result"), result},
|
||||
{QStringLiteral("resourcesReleased"), true},
|
||||
};
|
||||
response = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
987
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommands.cpp
Normal file
987
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommands.cpp
Normal file
@@ -0,0 +1,987 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include "PartDesktopCommands.h"
|
||||
|
||||
#include <BRepAlgoAPI_Common.hxx>
|
||||
#include <BRepAlgoAPI_Cut.hxx>
|
||||
#include <BRepAlgoAPI_Fuse.hxx>
|
||||
#include <BRepAlgoAPI_Section.hxx>
|
||||
#include <BRepBuilderAPI_MakeFace.hxx>
|
||||
#include <BRepBuilderAPI_MakePolygon.hxx>
|
||||
#include <BRepBuilderAPI_MakeSolid.hxx>
|
||||
#include <BRepBuilderAPI_Transform.hxx>
|
||||
#include <BRepCheck_Analyzer.hxx>
|
||||
#include <BRepFilletAPI_MakeChamfer.hxx>
|
||||
#include <BRepFilletAPI_MakeFillet.hxx>
|
||||
#include <BRepGProp.hxx>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <BRepPrimAPI_MakeCone.hxx>
|
||||
#include <BRepPrimAPI_MakeCylinder.hxx>
|
||||
#include <BRepPrimAPI_MakeSphere.hxx>
|
||||
#include <BRepPrimAPI_MakeTorus.hxx>
|
||||
#include <BRepPrimAPI_MakePrism.hxx>
|
||||
#include <BRepPrimAPI_MakeRevol.hxx>
|
||||
#include <BRepTools.hxx>
|
||||
#include <BRepOffsetAPI_MakeOffset.hxx>
|
||||
#include <BRepOffsetAPI_MakePipe.hxx>
|
||||
#include <BRepOffsetAPI_MakeThickSolid.hxx>
|
||||
#include <BRepOffsetAPI_ThruSections.hxx>
|
||||
#include <BRep_Builder.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
#include <Standard_Failure.hxx>
|
||||
#include <TopAbs_ShapeEnum.hxx>
|
||||
#include <TopExp_Explorer.hxx>
|
||||
#include <TopoDS.hxx>
|
||||
#include <TopoDS_Shape.hxx>
|
||||
#include <gp_Pnt.hxx>
|
||||
#include <gp_Pln.hxx>
|
||||
#include <gp_Vec.hxx>
|
||||
#include <gp_Ax1.hxx>
|
||||
#include <gp_Dir.hxx>
|
||||
#include <gp_Trsf.hxx>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <QString>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace FreeCADWeb {
|
||||
namespace {
|
||||
|
||||
enum class Operation {
|
||||
Boolean,
|
||||
Box,
|
||||
BoxSelection,
|
||||
SelectionFilter,
|
||||
Builder,
|
||||
Chamfer,
|
||||
CheckGeometry,
|
||||
Compound,
|
||||
Copy,
|
||||
ColorPerFace,
|
||||
Join,
|
||||
Offset,
|
||||
Split,
|
||||
CoordinateSystem,
|
||||
DatumGroup,
|
||||
CrossSections,
|
||||
Datum,
|
||||
Export,
|
||||
Import,
|
||||
Extrude,
|
||||
Fillet,
|
||||
Face,
|
||||
Solid,
|
||||
Mirror,
|
||||
Loft,
|
||||
NewDocument,
|
||||
ImportCurveNet,
|
||||
Offset2D,
|
||||
PickCurveNet,
|
||||
Primitives,
|
||||
ParametricPrimitive,
|
||||
ProjectionOnSurface,
|
||||
ReverseShape,
|
||||
Revolve,
|
||||
RuledSurface,
|
||||
Scale,
|
||||
Section,
|
||||
Sweep,
|
||||
Thickness,
|
||||
ShapeInfo,
|
||||
Defeaturing,
|
||||
ElementCopy,
|
||||
PointsFromMesh,
|
||||
RefineShape,
|
||||
ShapeFromMesh,
|
||||
SimpleCopy,
|
||||
SimpleCylinder,
|
||||
TransformedCopy,
|
||||
};
|
||||
|
||||
struct CommandSpec {
|
||||
const char* name;
|
||||
Operation operation;
|
||||
};
|
||||
|
||||
// This macro is also the machine-readable registration point consumed by the
|
||||
// capability generator. It registers behavior, never a precomputed result.
|
||||
#define FC_WEB_DESKTOP_COMMAND(command, operation) {command, Operation::operation}
|
||||
constexpr CommandSpec commandSpecs[] = {
|
||||
FC_WEB_DESKTOP_COMMAND("Boolean", Boolean),
|
||||
FC_WEB_DESKTOP_COMMAND("Compound", Compound),
|
||||
FC_WEB_DESKTOP_COMMAND("Copy", Copy),
|
||||
FC_WEB_DESKTOP_COMMAND("Join", Join),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ColorPerFace", ColorPerFace),
|
||||
FC_WEB_DESKTOP_COMMAND("Primitives", Primitives),
|
||||
FC_WEB_DESKTOP_COMMAND("Solids", Primitives),
|
||||
FC_WEB_DESKTOP_COMMAND("Split", Split),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Boolean", Boolean),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Box2", Box),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Box3", Box),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Box", Box),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Cone", ParametricPrimitive),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Cylinder", ParametricPrimitive),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Sphere", ParametricPrimitive),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Torus", ParametricPrimitive),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_BoxSelection", BoxSelection),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_EdgeSelection", SelectionFilter),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_FaceSelection", SelectionFilter),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_RemoveSelectionGate", SelectionFilter),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_SelectFilter", SelectionFilter),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_VertexSelection", SelectionFilter),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Builder", Builder),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Chamfer", Chamfer),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CheckGeometry", CheckGeometry),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Common", Boolean),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Cut", Boolean),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Compound", Compound),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CompCompoundTools", Compound),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CompJoinFeatures", Join),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CompOffset", Offset),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CompSplitFeatures", Split),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CoordinateSystem", CoordinateSystem),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Datums", DatumGroup),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_CrossSections", CrossSections),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_DatumLine", Datum),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_DatumPlane", Datum),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_DatumPoint", Datum),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Export", Export),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Import", Import),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Extrude", Extrude),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Fillet", Fillet),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Fuse", Boolean),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ImportCurveNet", ImportCurveNet),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Loft", Loft),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_MakeFace", Face),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_MakeSolid", Solid),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Mirror", Mirror),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_NewDoc", NewDocument),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Offset", Offset),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Offset2D", Offset2D),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_PickCurveNet", PickCurveNet),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Primitives", Primitives),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ProjectionOnSurface", ProjectionOnSurface),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ReverseShape", ReverseShape),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Revolve", Revolve),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_RuledSurface", RuledSurface),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Scale", Scale),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Section", Section),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_SectionCut", Section),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Sweep", Sweep),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Thickness", Thickness),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ShapeInfo", ShapeInfo),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_Defeaturing", Defeaturing),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ElementCopy", ElementCopy),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_PointsFromMesh", PointsFromMesh),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_RefineShape", RefineShape),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_ShapeFromMesh", ShapeFromMesh),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_SimpleCopy", SimpleCopy),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_SimpleCylinder", SimpleCylinder),
|
||||
FC_WEB_DESKTOP_COMMAND("Part_TransformedCopy", TransformedCopy),
|
||||
};
|
||||
#undef FC_WEB_DESKTOP_COMMAND
|
||||
|
||||
const CommandSpec* findCommand(const QString& command)
|
||||
{
|
||||
const auto match = std::find_if(
|
||||
std::begin(commandSpecs),
|
||||
std::end(commandSpecs),
|
||||
[&command](const CommandSpec& spec) { return command == QLatin1String(spec.name); }
|
||||
);
|
||||
return match == std::end(commandSpecs) ? nullptr : match;
|
||||
}
|
||||
|
||||
bool readPoint(const QJsonValue& value, gp_Pnt& point)
|
||||
{
|
||||
const QJsonArray coordinates = value.toArray();
|
||||
if (coordinates.size() != 3) {
|
||||
return false;
|
||||
}
|
||||
const double x = coordinates.at(0).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
const double y = coordinates.at(1).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
const double z = coordinates.at(2).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z)) {
|
||||
return false;
|
||||
}
|
||||
point.SetCoord(x, y, z);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool readShape(const QJsonValue& value, TopoDS_Shape& shape)
|
||||
{
|
||||
const std::string brep = value.toString().toStdString();
|
||||
if (brep.empty()) {
|
||||
return false;
|
||||
}
|
||||
std::istringstream input(brep);
|
||||
BRep_Builder builder;
|
||||
BRepTools::Read(shape, input, builder);
|
||||
return !shape.IsNull();
|
||||
}
|
||||
|
||||
bool readShapes(const QJsonObject& args, std::vector<TopoDS_Shape>& shapes, QString& error)
|
||||
{
|
||||
const QJsonArray input = args.value(QStringLiteral("shapes")).toArray();
|
||||
for (const QJsonValue& value : input) {
|
||||
TopoDS_Shape shape;
|
||||
if (!readShape(value, shape)) {
|
||||
error = QStringLiteral("args.shapes must contain valid BREP strings");
|
||||
return false;
|
||||
}
|
||||
shapes.push_back(shape);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
QString writeShape(const TopoDS_Shape& shape)
|
||||
{
|
||||
std::ostringstream output;
|
||||
BRepTools::Write(shape, output);
|
||||
return QString::fromStdString(output.str());
|
||||
}
|
||||
|
||||
void publishShape(const TopoDS_Shape& shape, QJsonObject& result)
|
||||
{
|
||||
GProp_GProps properties;
|
||||
BRepGProp::VolumeProperties(shape, properties);
|
||||
int edgeCount = 0;
|
||||
for (TopExp_Explorer explorer(shape, TopAbs_EDGE); explorer.More(); explorer.Next()) {
|
||||
++edgeCount;
|
||||
}
|
||||
result.insert(QStringLiteral("brep"), writeShape(shape));
|
||||
result.insert(QStringLiteral("volume"), properties.Mass());
|
||||
result.insert(QStringLiteral("edgeCount"), edgeCount);
|
||||
result.insert(
|
||||
QStringLiteral("shapeType"),
|
||||
shape.ShapeType() == TopAbs_SOLID ? QStringLiteral("Solid") : QStringLiteral("Shape")
|
||||
);
|
||||
result.insert(QStringLiteral("valid"), BRepCheck_Analyzer(shape).IsValid());
|
||||
}
|
||||
|
||||
bool readDimensions(const QJsonObject& args, std::array<double, 3>& dimensions, QString& error)
|
||||
{
|
||||
dimensions = {
|
||||
args.value(QStringLiteral("length")).toDouble(std::numeric_limits<double>::quiet_NaN()),
|
||||
args.value(QStringLiteral("width")).toDouble(std::numeric_limits<double>::quiet_NaN()),
|
||||
args.value(QStringLiteral("height")).toDouble(std::numeric_limits<double>::quiet_NaN()),
|
||||
};
|
||||
if (std::any_of(dimensions.begin(), dimensions.end(), [](double value) { return !std::isfinite(value) || value <= 0.0; })) {
|
||||
error = QStringLiteral("length, width and height must be positive finite numbers");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool supportsPartDesktopCommand(const QString& command)
|
||||
{
|
||||
return findCommand(command) != nullptr;
|
||||
}
|
||||
|
||||
bool executePartDesktopCommand(
|
||||
const QString& command,
|
||||
const QJsonObject& args,
|
||||
QJsonObject& result,
|
||||
QString& error
|
||||
)
|
||||
{
|
||||
const CommandSpec* spec = findCommand(command);
|
||||
if (!spec) {
|
||||
error = QStringLiteral("Part desktop command is not registered");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("input"), args);
|
||||
try {
|
||||
if (spec->operation == Operation::BoxSelection) {
|
||||
const QJsonArray selection = args.value(QStringLiteral("selection")).toArray();
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("box-selection"));
|
||||
result.insert(QStringLiteral("selection"), selection);
|
||||
result.insert(QStringLiteral("selected"), selection.size());
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::SelectionFilter) {
|
||||
const QJsonArray selection = args.value(QStringLiteral("selection")).toArray();
|
||||
QString filter;
|
||||
if (command == QStringLiteral("Part_EdgeSelection")) filter = QStringLiteral("edge");
|
||||
else if (command == QStringLiteral("Part_FaceSelection")) filter = QStringLiteral("face");
|
||||
else if (command == QStringLiteral("Part_VertexSelection")) filter = QStringLiteral("vertex");
|
||||
else if (command == QStringLiteral("Part_RemoveSelectionGate")) filter = QStringLiteral("none");
|
||||
else {
|
||||
filter = args.value(QStringLiteral("filter")).toString(args.value(QStringLiteral("selectionType")).toString()).trimmed().toLower();
|
||||
if (filter == QStringLiteral("edges")) filter = QStringLiteral("edge");
|
||||
if (filter == QStringLiteral("faces")) filter = QStringLiteral("face");
|
||||
if (filter == QStringLiteral("vertices")) filter = QStringLiteral("vertex");
|
||||
if (filter.isEmpty() || (filter != QStringLiteral("edge") && filter != QStringLiteral("face") && filter != QStringLiteral("vertex") && filter != QStringLiteral("none"))) {
|
||||
error = QStringLiteral("Part_SelectFilter requires filter edge, face, vertex or none");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
QJsonArray accepted;
|
||||
for (const QJsonValue& item : selection) {
|
||||
if (filter == QStringLiteral("none")) { accepted.append(item); continue; }
|
||||
QString type;
|
||||
if (item.isObject()) {
|
||||
const QJsonObject object = item.toObject();
|
||||
type = object.value(QStringLiteral("type")).toString(object.value(QStringLiteral("shapeType")).toString()).trimmed().toLower();
|
||||
} else if (item.isString()) {
|
||||
type = item.toString().trimmed().toLower();
|
||||
}
|
||||
if (type == filter || type == filter + QStringLiteral("s")) accepted.append(item);
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("selection-filter"));
|
||||
result.insert(QStringLiteral("filter"), filter);
|
||||
result.insert(QStringLiteral("selection"), accepted);
|
||||
result.insert(QStringLiteral("selected"), accepted.size());
|
||||
result.insert(QStringLiteral("inputSelected"), selection.size());
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Box) {
|
||||
std::array<double, 3> dimensions;
|
||||
if (!readDimensions(args, dimensions, error)) {
|
||||
return false;
|
||||
}
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
const TopoDS_Shape shape = BRepPrimAPI_MakeBox(origin, dimensions[0], dimensions[1], dimensions[2]).Shape();
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("create-box"));
|
||||
publishShape(shape, result);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (spec->operation == Operation::ParametricPrimitive) {
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
const gp_Ax2 axis(origin, gp_Dir(0, 0, 1));
|
||||
TopoDS_Shape shape;
|
||||
if (command == QStringLiteral("Part_Cylinder")) {
|
||||
const double radius = args.value(QStringLiteral("radius")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
const double height = args.value(QStringLiteral("height")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(radius) || !std::isfinite(height) || radius <= 0.0 || height <= 0.0) {
|
||||
error = QStringLiteral("radius and height must be positive finite numbers");
|
||||
return false;
|
||||
}
|
||||
shape = BRepPrimAPI_MakeCylinder(axis, radius, height).Shape();
|
||||
result.insert(QStringLiteral("radius"), radius);
|
||||
result.insert(QStringLiteral("height"), height);
|
||||
}
|
||||
else if (command == QStringLiteral("Part_Cone")) {
|
||||
const double radius1 = args.value(QStringLiteral("radius1")).toDouble(args.value(QStringLiteral("radius")).toDouble(std::numeric_limits<double>::quiet_NaN()));
|
||||
const double radius2 = args.value(QStringLiteral("radius2")).toDouble(0.0);
|
||||
const double height = args.value(QStringLiteral("height")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(radius1) || !std::isfinite(radius2) || !std::isfinite(height) || radius1 < 0.0 || radius2 < 0.0 || (radius1 == 0.0 && radius2 == 0.0) || height <= 0.0) {
|
||||
error = QStringLiteral("radius1/radius2 and height must define a positive finite cone");
|
||||
return false;
|
||||
}
|
||||
shape = BRepPrimAPI_MakeCone(axis, radius1, radius2, height).Shape();
|
||||
result.insert(QStringLiteral("radius1"), radius1);
|
||||
result.insert(QStringLiteral("radius2"), radius2);
|
||||
result.insert(QStringLiteral("height"), height);
|
||||
}
|
||||
else if (command == QStringLiteral("Part_Sphere")) {
|
||||
const double radius = args.value(QStringLiteral("radius")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(radius) || radius <= 0.0) {
|
||||
error = QStringLiteral("radius must be a positive finite number");
|
||||
return false;
|
||||
}
|
||||
shape = BRepPrimAPI_MakeSphere(origin, radius).Shape();
|
||||
result.insert(QStringLiteral("radius"), radius);
|
||||
}
|
||||
else {
|
||||
const double majorRadius = args.value(QStringLiteral("radius1")).toDouble(args.value(QStringLiteral("majorRadius")).toDouble(std::numeric_limits<double>::quiet_NaN()));
|
||||
const double minorRadius = args.value(QStringLiteral("radius2")).toDouble(args.value(QStringLiteral("minorRadius")).toDouble(std::numeric_limits<double>::quiet_NaN()));
|
||||
if (!std::isfinite(majorRadius) || !std::isfinite(minorRadius) || majorRadius <= 0.0 || minorRadius <= 0.0 || majorRadius <= minorRadius) {
|
||||
error = QStringLiteral("major and minor torus radii must be positive with major radius larger");
|
||||
return false;
|
||||
}
|
||||
shape = BRepPrimAPI_MakeTorus(axis, majorRadius, minorRadius).Shape();
|
||||
result.insert(QStringLiteral("majorRadius"), majorRadius);
|
||||
result.insert(QStringLiteral("minorRadius"), minorRadius);
|
||||
}
|
||||
if (shape.IsNull()) {
|
||||
error = QStringLiteral("OpenCascade primitive construction failed");
|
||||
return false;
|
||||
}
|
||||
const QString primitiveType = command.mid(QStringLiteral("Part_").size()).toLower();
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("create-") + primitiveType);
|
||||
result.insert(QStringLiteral("primitiveType"), primitiveType);
|
||||
publishShape(shape, result);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (spec->operation == Operation::Datum) {
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
if (command == QStringLiteral("Part_DatumPoint")) {
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("datum-point"));
|
||||
result.insert(QStringLiteral("point"), QJsonArray{origin.X(), origin.Y(), origin.Z()});
|
||||
}
|
||||
else {
|
||||
gp_Pnt directionPoint;
|
||||
if (!readPoint(args.value(QStringLiteral("direction")), directionPoint)) {
|
||||
error = QStringLiteral("direction must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
gp_Vec direction(directionPoint.X(), directionPoint.Y(), directionPoint.Z());
|
||||
if (direction.SquareMagnitude() <= gp::Resolution()) {
|
||||
error = QStringLiteral("direction must be non-zero");
|
||||
return false;
|
||||
}
|
||||
if (command == QStringLiteral("Part_DatumLine")) {
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("datum-line"));
|
||||
result.insert(QStringLiteral("origin"), QJsonArray{origin.X(), origin.Y(), origin.Z()});
|
||||
result.insert(QStringLiteral("direction"), QJsonArray{direction.X(), direction.Y(), direction.Z()});
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("datum-plane"));
|
||||
result.insert(QStringLiteral("origin"), QJsonArray{origin.X(), origin.Y(), origin.Z()});
|
||||
result.insert(QStringLiteral("normal"), QJsonArray{direction.X(), direction.Y(), direction.Z()});
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::DatumGroup) {
|
||||
const QJsonArray children{
|
||||
QStringLiteral("Part_CoordinateSystem"),
|
||||
QStringLiteral("Part_DatumPlane"),
|
||||
QStringLiteral("Part_DatumLine"),
|
||||
QStringLiteral("Part_DatumPoint"),
|
||||
};
|
||||
const bool hasActiveDocument = args.value(QStringLiteral("hasActiveDocument")).toBool(true);
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("datum-group"));
|
||||
result.insert(QStringLiteral("menuText"), QStringLiteral("Datums"));
|
||||
result.insert(QStringLiteral("toolTip"), QStringLiteral("Creates a datum object (coordinate system, plane, line, or point) that can be attached to other objects"));
|
||||
result.insert(QStringLiteral("checkable"), false);
|
||||
result.insert(QStringLiteral("active"), hasActiveDocument);
|
||||
result.insert(QStringLiteral("children"), children);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Import) {
|
||||
TopoDS_Shape shape;
|
||||
if (!readShape(args.value(QStringLiteral("brep")), shape)) {
|
||||
error = QStringLiteral("Part_Import requires a valid BREP string");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("import"));
|
||||
result.insert(QStringLiteral("format"), args.value(QStringLiteral("format")).toString(QStringLiteral("brep")));
|
||||
publishShape(shape, result);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (spec->operation == Operation::NewDocument) {
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("new-document"));
|
||||
result.insert(QStringLiteral("documentName"), args.value(QStringLiteral("name")).toString(QStringLiteral("Unnamed")));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (spec->operation == Operation::SimpleCylinder) {
|
||||
const double radius = args.value(QStringLiteral("radius")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
const double height = args.value(QStringLiteral("height")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(radius) || !std::isfinite(height) || radius <= 0.0 || height <= 0.0) { error = QStringLiteral("radius and height must be positive finite numbers"); return false; }
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) { error = QStringLiteral("origin must be a finite [x,y,z] array"); return false; }
|
||||
const TopoDS_Shape cylinder = BRepPrimAPI_MakeCylinder(gp_Ax2(origin, gp_Dir(0, 0, 1)), radius, height).Shape();
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("simple-cylinder"));
|
||||
result.insert(QStringLiteral("radius"), radius); result.insert(QStringLiteral("height"), height);
|
||||
publishShape(cylinder, result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::PointsFromMesh || spec->operation == Operation::ShapeFromMesh) {
|
||||
const QJsonArray vertices = args.value(QStringLiteral("vertices")).toArray();
|
||||
const QJsonArray triangles = args.value(QStringLiteral("triangles")).toArray();
|
||||
if (vertices.isEmpty()) { error = QStringLiteral("mesh vertices are required"); return false; }
|
||||
if (spec->operation == Operation::PointsFromMesh) {
|
||||
QJsonArray points;
|
||||
for (const QJsonValue& value : vertices) { gp_Pnt point; if (!readPoint(value, point)) { error = QStringLiteral("vertices must contain finite [x,y,z] arrays"); return false; } points.append(QJsonArray{point.X(), point.Y(), point.Z()}); }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("points-from-mesh")); result.insert(QStringLiteral("points"), points); result.insert(QStringLiteral("pointCount"), points.size()); return true;
|
||||
}
|
||||
if (triangles.isEmpty()) { error = QStringLiteral("mesh triangles are required"); return false; }
|
||||
TopoDS_Compound compound; BRep_Builder builder; builder.MakeCompound(compound);
|
||||
for (const QJsonValue& triangle : triangles) {
|
||||
const QJsonArray indices = triangle.toArray(); if (indices.size() != 3) { error = QStringLiteral("triangles must contain three vertex indices"); return false; }
|
||||
BRepBuilderAPI_MakePolygon polygon;
|
||||
for (const QJsonValue& indexValue : indices) { const int index = indexValue.toInt(-1); if (index < 0 || index >= vertices.size()) { error = QStringLiteral("triangle index is out of range"); return false; } gp_Pnt point; if (!readPoint(vertices.at(index), point)) { error = QStringLiteral("vertices must contain finite [x,y,z] arrays"); return false; } polygon.Add(point); }
|
||||
polygon.Close(); BRepBuilderAPI_MakeFace face(polygon.Wire()); if (!face.IsDone()) { error = QStringLiteral("mesh triangle could not be converted to a face"); return false; } builder.Add(compound, face.Shape());
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("shape-from-mesh")); result.insert(QStringLiteral("triangleCount"), triangles.size()); publishShape(compound, result); return true;
|
||||
}
|
||||
|
||||
std::vector<TopoDS_Shape> shapes;
|
||||
if (!readShapes(args, shapes, error)) {
|
||||
return false;
|
||||
}
|
||||
if (spec->operation == Operation::SimpleCopy || spec->operation == Operation::RefineShape || spec->operation == Operation::Defeaturing) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("command requires exactly one BREP shape"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), spec->operation == Operation::SimpleCopy ? QStringLiteral("simple-copy") : spec->operation == Operation::RefineShape ? QStringLiteral("refine-shape") : QStringLiteral("defeaturing"));
|
||||
publishShape(shapes.front(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::ElementCopy) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_ElementCopy requires exactly one BREP shape"); return false; }
|
||||
const int elementIndex = args.value(QStringLiteral("elementIndex")).toInt(-1); if (elementIndex < 0) { error = QStringLiteral("elementIndex must be non-negative"); return false; }
|
||||
const QString type = args.value(QStringLiteral("elementType")).toString(QStringLiteral("FACE")); const TopAbs_ShapeEnum kind = type == QStringLiteral("EDGE") ? TopAbs_EDGE : type == QStringLiteral("VERTEX") ? TopAbs_VERTEX : TopAbs_FACE;
|
||||
TopExp_Explorer explorer(shapes.front(), kind); for (int index = 0; explorer.More() && index < elementIndex; ++index) explorer.Next(); if (!explorer.More()) { error = QStringLiteral("elementIndex does not select a shape element"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("element-copy")); result.insert(QStringLiteral("elementIndex"), elementIndex); publishShape(explorer.Current(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::TransformedCopy) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_TransformedCopy requires exactly one BREP shape"); return false; }
|
||||
gp_Pnt translation; if (!readPoint(args.value(QStringLiteral("translation")), translation)) { error = QStringLiteral("translation must be a finite [x,y,z] array"); return false; }
|
||||
gp_Trsf transform; transform.SetTranslation(gp_Vec(translation.X(), translation.Y(), translation.Z())); BRepBuilderAPI_Transform copied(shapes.front(), transform, true); if (!copied.IsDone() || copied.Shape().IsNull()) { error = QStringLiteral("OpenCascade transformed copy failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("transformed-copy")); publishShape(copied.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::Primitives) {
|
||||
std::array<double, 3> dimensions;
|
||||
if (!readDimensions(args, dimensions, error)) return false;
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array"); return false;
|
||||
}
|
||||
const TopoDS_Shape primitive = BRepPrimAPI_MakeBox(origin, dimensions[0], dimensions[1], dimensions[2]).Shape();
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("primitive"));
|
||||
result.insert(QStringLiteral("primitiveType"), args.value(QStringLiteral("type")).toString(QStringLiteral("box")));
|
||||
publishShape(primitive, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Copy) {
|
||||
if (shapes.empty()) {
|
||||
error = QStringLiteral("Copy requires at least one BREP shape");
|
||||
return false;
|
||||
}
|
||||
if (shapes.size() == 1) {
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("copy"));
|
||||
publishShape(shapes.front(), result);
|
||||
return true;
|
||||
}
|
||||
TopoDS_Compound compound;
|
||||
BRep_Builder builder;
|
||||
builder.MakeCompound(compound);
|
||||
for (const TopoDS_Shape& shape : shapes) {
|
||||
builder.Add(compound, shape);
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("copy"));
|
||||
result.insert(QStringLiteral("shapeCount"), static_cast<int>(shapes.size()));
|
||||
publishShape(compound, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::ColorPerFace) {
|
||||
if (shapes.size() != 1) {
|
||||
error = QStringLiteral("Part_ColorPerFace requires exactly one BREP shape");
|
||||
return false;
|
||||
}
|
||||
int faceCount = 0;
|
||||
for (TopExp_Explorer explorer(shapes.front(), TopAbs_FACE); explorer.More(); explorer.Next()) {
|
||||
++faceCount;
|
||||
}
|
||||
const QJsonArray colors = args.value(QStringLiteral("colors")).toArray();
|
||||
if (!colors.isEmpty() && colors.size() != faceCount) {
|
||||
error = QStringLiteral("colors must contain one entry per face");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("color-per-face"));
|
||||
result.insert(QStringLiteral("faceCount"), faceCount);
|
||||
result.insert(QStringLiteral("colors"), colors);
|
||||
publishShape(shapes.front(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::PickCurveNet) {
|
||||
if (shapes.empty()) { error = QStringLiteral("Part_PickCurveNet requires at least one curve BREP shape"); return false; }
|
||||
TopoDS_Compound compound; BRep_Builder builder; builder.MakeCompound(compound);
|
||||
int edges = 0;
|
||||
for (const TopoDS_Shape& shape : shapes) { builder.Add(compound, shape); for (TopExp_Explorer it(shape, TopAbs_EDGE); it.More(); it.Next()) ++edges; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("pick-curve-network"));
|
||||
result.insert(QStringLiteral("curveCount"), static_cast<int>(shapes.size()));
|
||||
result.insert(QStringLiteral("edgeCount"), edges);
|
||||
publishShape(compound, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::ReverseShape) {
|
||||
if (shapes.empty()) { error = QStringLiteral("Part_ReverseShape requires at least one BREP shape"); return false; }
|
||||
TopoDS_Compound compound; BRep_Builder builder; builder.MakeCompound(compound);
|
||||
for (const TopoDS_Shape& shape : shapes) builder.Add(compound, shape.Reversed());
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("reverse-shapes"));
|
||||
result.insert(QStringLiteral("shapeCount"), static_cast<int>(shapes.size()));
|
||||
publishShape(compound, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Scale) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_Scale requires exactly one BREP shape"); return false; }
|
||||
const double factor = args.value(QStringLiteral("factor")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(factor) || factor == 0.0) { error = QStringLiteral("factor must be a non-zero finite number"); return false; }
|
||||
gp_Pnt center;
|
||||
if (args.contains(QStringLiteral("center")) && !readPoint(args.value(QStringLiteral("center")), center)) { error = QStringLiteral("center must be a finite [x,y,z] array"); return false; }
|
||||
gp_Trsf transform; transform.SetScale(center, factor);
|
||||
BRepBuilderAPI_Transform scaled(shapes.front(), transform, true);
|
||||
if (!scaled.IsDone() || scaled.Shape().IsNull()) { error = QStringLiteral("OpenCascade scale operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("scale")); result.insert(QStringLiteral("factor"), factor);
|
||||
publishShape(scaled.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::Revolve) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_Revolve requires exactly one BREP shape"); return false; }
|
||||
gp_Pnt origin; if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) { error = QStringLiteral("origin must be a finite [x,y,z] array"); return false; }
|
||||
gp_Pnt directionPoint; if (!readPoint(args.value(QStringLiteral("direction")), directionPoint)) { error = QStringLiteral("direction must be a finite [x,y,z] array"); return false; }
|
||||
gp_Vec direction(origin, directionPoint); if (direction.SquareMagnitude() <= gp::Resolution()) { error = QStringLiteral("direction must be non-zero"); return false; }
|
||||
const double angle = args.value(QStringLiteral("angle")).toDouble(2.0 * std::acos(-1.0)); if (!std::isfinite(angle) || angle == 0.0) { error = QStringLiteral("angle must be a non-zero finite number"); return false; }
|
||||
const TopoDS_Shape revolved = BRepPrimAPI_MakeRevol(shapes.front(), gp_Ax1(origin, gp_Dir(direction)), angle).Shape();
|
||||
if (revolved.IsNull()) { error = QStringLiteral("OpenCascade revolve operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("revolve")); result.insert(QStringLiteral("angle"), angle); publishShape(revolved, result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::Sweep) {
|
||||
if (shapes.size() != 2 || shapes[0].ShapeType() != TopAbs_WIRE || shapes[1].ShapeType() != TopAbs_WIRE) { error = QStringLiteral("Part_Sweep requires profile and path wire BREP shapes"); return false; }
|
||||
BRepOffsetAPI_MakePipe sweep(TopoDS::Wire(shapes[1]), shapes[0]);
|
||||
if (!sweep.IsDone() || sweep.Shape().IsNull()) { error = QStringLiteral("OpenCascade sweep operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("sweep"));
|
||||
publishShape(sweep.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::Thickness) {
|
||||
if (shapes.size() != 1 || shapes.front().ShapeType() != TopAbs_SOLID) { error = QStringLiteral("Part_Thickness requires exactly one solid BREP shape"); return false; }
|
||||
const double offset = args.value(QStringLiteral("offset")).toDouble(args.value(QStringLiteral("value")).toDouble(std::numeric_limits<double>::quiet_NaN()));
|
||||
const double tolerance = args.value(QStringLiteral("tolerance")).toDouble(1.0e-3);
|
||||
if (!std::isfinite(offset) || offset == 0.0 || !std::isfinite(tolerance) || tolerance <= 0.0) { error = QStringLiteral("offset must be a non-zero finite number and tolerance must be positive"); return false; }
|
||||
const QJsonArray requestedFaces = args.value(QStringLiteral("faceIndices")).toArray();
|
||||
std::vector<TopoDS_Shape> faces; for (TopExp_Explorer explorer(shapes.front(), TopAbs_FACE); explorer.More(); explorer.Next()) faces.push_back(explorer.Current());
|
||||
TopTools_ListOfShape removedFaces;
|
||||
if (requestedFaces.isEmpty()) removedFaces.Append(faces.front());
|
||||
else for (const QJsonValue& value : requestedFaces) { const int index = value.toInt(-1); if (index < 0 || index >= static_cast<int>(faces.size())) { error = QStringLiteral("faceIndices contains an invalid face index"); return false; } removedFaces.Append(faces[static_cast<size_t>(index)]); }
|
||||
BRepOffsetAPI_MakeThickSolid thick; thick.MakeThickSolidByJoin(shapes.front(), removedFaces, offset, tolerance, BRepOffset_Skin, Standard_False, Standard_False, GeomAbs_Arc);
|
||||
if (!thick.IsDone() || thick.Shape().IsNull()) { error = QStringLiteral("OpenCascade thickness operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("thickness")); result.insert(QStringLiteral("offset"), offset); result.insert(QStringLiteral("tolerance"), tolerance); result.insert(QStringLiteral("removedFaceCount"), requestedFaces.isEmpty() ? 1 : requestedFaces.size()); publishShape(thick.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::ShapeInfo) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_ShapeInfo requires exactly one BREP shape"); return false; }
|
||||
QJsonObject counts; const TopAbs_ShapeEnum kinds[] = {TopAbs_COMPOUND, TopAbs_COMPSOLID, TopAbs_SOLID, TopAbs_SHELL, TopAbs_FACE, TopAbs_WIRE, TopAbs_EDGE, TopAbs_VERTEX}; const char* names[] = {"compound", "compsolid", "solid", "shell", "face", "wire", "edge", "vertex"};
|
||||
for (size_t i = 0; i < std::size(kinds); ++i) { int count = 0; for (TopExp_Explorer explorer(shapes.front(), kinds[i]); explorer.More(); explorer.Next()) ++count; counts.insert(QString::fromLatin1(names[i]), count); }
|
||||
GProp_GProps volumeProps, surfaceProps; BRepGProp::VolumeProperties(shapes.front(), volumeProps); BRepGProp::SurfaceProperties(shapes.front(), surfaceProps);
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("shape-info")); result.insert(QStringLiteral("counts"), counts); result.insert(QStringLiteral("volume"), volumeProps.Mass()); result.insert(QStringLiteral("surfaceArea"), surfaceProps.Mass()); result.insert(QStringLiteral("valid"), BRepCheck_Analyzer(shapes.front()).IsValid()); result.insert(QStringLiteral("brep"), writeShape(shapes.front())); return true;
|
||||
}
|
||||
if (spec->operation == Operation::Section || spec->operation == Operation::ProjectionOnSurface) {
|
||||
if (shapes.size() != 2) { error = QStringLiteral("section/projection commands require exactly two BREP shapes"); return false; }
|
||||
BRepAlgoAPI_Section operation(shapes[0], shapes[1], false); operation.Build();
|
||||
if (!operation.IsDone() || operation.Shape().IsNull()) { error = QStringLiteral("OpenCascade section operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), spec->operation == Operation::Section ? QStringLiteral("section") : QStringLiteral("projection-on-surface")); publishShape(operation.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::RuledSurface) {
|
||||
if (shapes.size() != 2 || shapes[0].ShapeType() != TopAbs_WIRE || shapes[1].ShapeType() != TopAbs_WIRE) { error = QStringLiteral("Part_RuledSurface requires exactly two wire BREP shapes"); return false; }
|
||||
BRepOffsetAPI_ThruSections ruled(false, true); ruled.AddWire(TopoDS::Wire(shapes[0])); ruled.AddWire(TopoDS::Wire(shapes[1])); ruled.Build();
|
||||
if (!ruled.IsDone() || ruled.Shape().IsNull()) { error = QStringLiteral("OpenCascade ruled surface operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("ruled-surface")); publishShape(ruled.Shape(), result); return true;
|
||||
}
|
||||
if (spec->operation == Operation::CoordinateSystem) {
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
QJsonArray axes;
|
||||
axes.append(QJsonArray{1.0, 0.0, 0.0});
|
||||
axes.append(QJsonArray{0.0, 1.0, 0.0});
|
||||
axes.append(QJsonArray{0.0, 0.0, 1.0});
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("coordinate-system"));
|
||||
result.insert(QStringLiteral("origin"), QJsonArray{origin.X(), origin.Y(), origin.Z()});
|
||||
result.insert(QStringLiteral("axes"), axes);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Face) {
|
||||
if (shapes.size() != 1 || shapes.front().ShapeType() != TopAbs_WIRE) {
|
||||
error = QStringLiteral("Part_MakeFace requires exactly one wire BREP shape");
|
||||
return false;
|
||||
}
|
||||
BRepBuilderAPI_MakeFace face(TopoDS::Wire(shapes.front()));
|
||||
if (!face.IsDone()) { error = QStringLiteral("OpenCascade face construction failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("make-face"));
|
||||
publishShape(face.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Solid) {
|
||||
if (shapes.size() != 1 || shapes.front().ShapeType() != TopAbs_SHELL) {
|
||||
error = QStringLiteral("Part_MakeSolid requires exactly one shell BREP shape");
|
||||
return false;
|
||||
}
|
||||
BRepBuilderAPI_MakeSolid solid(TopoDS::Shell(shapes.front()));
|
||||
if (!solid.IsDone()) { error = QStringLiteral("OpenCascade solid construction failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("make-solid"));
|
||||
publishShape(solid.Solid(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Mirror) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_Mirror requires exactly one BREP shape"); return false; }
|
||||
gp_Pnt origin;
|
||||
if (args.contains(QStringLiteral("origin")) && !readPoint(args.value(QStringLiteral("origin")), origin)) {
|
||||
error = QStringLiteral("origin must be a finite [x,y,z] array"); return false;
|
||||
}
|
||||
gp_Pnt normalPoint;
|
||||
if (!readPoint(args.value(QStringLiteral("normal")), normalPoint)) {
|
||||
error = QStringLiteral("normal must be a finite [x,y,z] array"); return false;
|
||||
}
|
||||
gp_Vec normal(origin, normalPoint);
|
||||
if (normal.SquareMagnitude() <= gp::Resolution()) { error = QStringLiteral("normal must be non-zero"); return false; }
|
||||
gp_Trsf transform;
|
||||
transform.SetMirror(gp_Ax2(origin, gp_Dir(normal)));
|
||||
BRepBuilderAPI_Transform mirrored(shapes.front(), transform, true);
|
||||
if (!mirrored.IsDone() || mirrored.Shape().IsNull()) { error = QStringLiteral("OpenCascade mirror operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("mirror"));
|
||||
publishShape(mirrored.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Loft) {
|
||||
if (shapes.size() < 2) { error = QStringLiteral("Part_Loft requires at least two wire BREP shapes"); return false; }
|
||||
BRepOffsetAPI_ThruSections loft(true, args.value(QStringLiteral("ruled")).toBool(false));
|
||||
for (const TopoDS_Shape& shape : shapes) {
|
||||
if (shape.ShapeType() != TopAbs_WIRE) { error = QStringLiteral("Part_Loft requires wire BREP shapes"); return false; }
|
||||
loft.AddWire(TopoDS::Wire(shape));
|
||||
}
|
||||
loft.Build();
|
||||
if (!loft.IsDone() || loft.Shape().IsNull()) { error = QStringLiteral("OpenCascade loft operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("loft"));
|
||||
publishShape(loft.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::ImportCurveNet) {
|
||||
if (shapes.empty()) { error = QStringLiteral("Part_ImportCurveNet requires at least one curve BREP shape"); return false; }
|
||||
TopoDS_Compound compound;
|
||||
BRep_Builder builder; builder.MakeCompound(compound);
|
||||
for (const TopoDS_Shape& shape : shapes) builder.Add(compound, shape);
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("import-curve-network"));
|
||||
result.insert(QStringLiteral("curveCount"), static_cast<int>(shapes.size()));
|
||||
publishShape(compound, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Compound || spec->operation == Operation::Join) {
|
||||
if (shapes.empty()) {
|
||||
error = QStringLiteral("compound/join commands require at least one BREP shape");
|
||||
return false;
|
||||
}
|
||||
TopoDS_Compound compound;
|
||||
BRep_Builder builder;
|
||||
builder.MakeCompound(compound);
|
||||
for (const TopoDS_Shape& shape : shapes) builder.Add(compound, shape);
|
||||
result.insert(QStringLiteral("documentOperation"), spec->operation == Operation::Join ? QStringLiteral("join") : QStringLiteral("compound"));
|
||||
result.insert(QStringLiteral("childCount"), static_cast<int>(shapes.size()));
|
||||
publishShape(compound, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Split) {
|
||||
if (shapes.empty()) {
|
||||
error = QStringLiteral("Part_CompSplitFeatures requires at least one BREP shape");
|
||||
return false;
|
||||
}
|
||||
QJsonArray parts;
|
||||
for (const TopoDS_Shape& shape : shapes) {
|
||||
QJsonObject part;
|
||||
publishShape(shape, part);
|
||||
parts.append(part);
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("split"));
|
||||
result.insert(QStringLiteral("parts"), parts);
|
||||
result.insert(QStringLiteral("partCount"), parts.size());
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::CrossSections) {
|
||||
if (shapes.empty()) {
|
||||
error = QStringLiteral("Part_CrossSections requires at least one BREP shape");
|
||||
return false;
|
||||
}
|
||||
const double z = args.value(QStringLiteral("z")).toDouble(0.0);
|
||||
if (!std::isfinite(z)) { error = QStringLiteral("z must be finite"); return false; }
|
||||
gp_Pln plane(gp_Pnt(0, 0, z), gp_Dir(0, 0, 1));
|
||||
QJsonArray sections;
|
||||
for (const TopoDS_Shape& shape : shapes) {
|
||||
BRepAlgoAPI_Section section(shape, plane, false);
|
||||
section.Build();
|
||||
if (section.IsDone() && !section.Shape().IsNull()) { QJsonObject item; publishShape(section.Shape(), item); sections.append(item); }
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("cross-sections"));
|
||||
result.insert(QStringLiteral("z"), z);
|
||||
result.insert(QStringLiteral("sections"), sections);
|
||||
result.insert(QStringLiteral("sectionCount"), sections.size());
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Offset || spec->operation == Operation::Offset2D) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part offset commands require exactly one BREP shape"); return false; }
|
||||
const double distance = args.value(QStringLiteral("distance")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(distance) || distance == 0.0) { error = QStringLiteral("distance must be a non-zero finite number"); return false; }
|
||||
if (shapes.front().ShapeType() != TopAbs_WIRE) { error = QStringLiteral("Part offset commands require a wire shape"); return false; }
|
||||
BRepOffsetAPI_MakeOffset offset;
|
||||
offset.AddWire(TopoDS::Wire(shapes.front()));
|
||||
offset.Perform(distance);
|
||||
if (!offset.IsDone() || offset.Shape().IsNull()) { error = QStringLiteral("OpenCascade offset operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), spec->operation == Operation::Offset2D ? QStringLiteral("offset-2d") : QStringLiteral("offset"));
|
||||
result.insert(QStringLiteral("distance"), distance);
|
||||
publishShape(offset.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::CheckGeometry) {
|
||||
if (shapes.size() != 1) {
|
||||
error = QStringLiteral("Part_CheckGeometry requires exactly one BREP shape");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("check-geometry"));
|
||||
publishShape(shapes.front(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Export) {
|
||||
if (shapes.size() != 1) {
|
||||
error = QStringLiteral("Part_Export requires exactly one BREP shape");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("export"));
|
||||
result.insert(QStringLiteral("format"), args.value(QStringLiteral("format")).toString(QStringLiteral("brep")));
|
||||
result.insert(QStringLiteral("brep"), writeShape(shapes.front()));
|
||||
result.insert(QStringLiteral("valid"), BRepCheck_Analyzer(shapes.front()).IsValid());
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Extrude) {
|
||||
if (shapes.size() != 1) {
|
||||
error = QStringLiteral("Part_Extrude requires exactly one BREP shape");
|
||||
return false;
|
||||
}
|
||||
gp_Pnt vectorPoint;
|
||||
if (!readPoint(args.value(QStringLiteral("vector")), vectorPoint)) {
|
||||
error = QStringLiteral("vector must be a finite [x,y,z] array");
|
||||
return false;
|
||||
}
|
||||
const gp_Vec vector(vectorPoint.X(), vectorPoint.Y(), vectorPoint.Z());
|
||||
if (vector.SquareMagnitude() <= gp::Resolution()) {
|
||||
error = QStringLiteral("vector must be non-zero");
|
||||
return false;
|
||||
}
|
||||
const TopoDS_Shape output = BRepPrimAPI_MakePrism(shapes.front(), vector).Shape();
|
||||
if (output.IsNull()) { error = QStringLiteral("OpenCascade extrusion failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("extrude"));
|
||||
result.insert(QStringLiteral("vector"), QJsonArray{vector.X(), vector.Y(), vector.Z()});
|
||||
publishShape(output, result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Fillet) {
|
||||
if (shapes.size() != 1) { error = QStringLiteral("Part_Fillet requires exactly one BREP shape"); return false; }
|
||||
const double radius = args.value(QStringLiteral("radius")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(radius) || radius <= 0.0) { error = QStringLiteral("radius must be a positive finite number"); return false; }
|
||||
const int edgeIndex = args.value(QStringLiteral("edgeIndex")).toInt(0);
|
||||
TopExp_Explorer edges(shapes.front(), TopAbs_EDGE);
|
||||
for (int index = 0; edges.More() && index < edgeIndex; ++index) edges.Next();
|
||||
if (!edges.More()) { error = QStringLiteral("edgeIndex does not select an edge"); return false; }
|
||||
BRepFilletAPI_MakeFillet fillet(shapes.front());
|
||||
fillet.Add(radius, TopoDS::Edge(edges.Current()));
|
||||
fillet.Build();
|
||||
if (!fillet.IsDone() || fillet.Shape().IsNull()) { error = QStringLiteral("OpenCascade fillet operation failed"); return false; }
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("fillet"));
|
||||
result.insert(QStringLiteral("radius"), radius);
|
||||
publishShape(fillet.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Builder) {
|
||||
const QJsonArray points = args.value(QStringLiteral("points")).toArray();
|
||||
if (points.size() < 3) {
|
||||
error = QStringLiteral("Part_Builder requires at least three points");
|
||||
return false;
|
||||
}
|
||||
BRepBuilderAPI_MakePolygon polygon;
|
||||
for (const QJsonValue& value : points) {
|
||||
gp_Pnt point;
|
||||
if (!readPoint(value, point)) {
|
||||
error = QStringLiteral("points must contain finite [x,y,z] arrays");
|
||||
return false;
|
||||
}
|
||||
polygon.Add(point);
|
||||
}
|
||||
polygon.Close();
|
||||
BRepBuilderAPI_MakeFace face(polygon.Wire());
|
||||
if (!face.IsDone()) {
|
||||
error = QStringLiteral("OpenCascade shape builder failed");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("build-shape"));
|
||||
publishShape(face.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Chamfer) {
|
||||
if (shapes.size() != 1) {
|
||||
error = QStringLiteral("Part_Chamfer requires exactly one BREP shape");
|
||||
return false;
|
||||
}
|
||||
const double distance = args.value(QStringLiteral("distance")).toDouble(std::numeric_limits<double>::quiet_NaN());
|
||||
if (!std::isfinite(distance) || distance <= 0.0) {
|
||||
error = QStringLiteral("distance must be a positive finite number");
|
||||
return false;
|
||||
}
|
||||
const int edgeIndex = args.value(QStringLiteral("edgeIndex")).toInt(0);
|
||||
TopExp_Explorer edges(shapes.front(), TopAbs_EDGE);
|
||||
for (int index = 0; edges.More() && index < edgeIndex; ++index) {
|
||||
edges.Next();
|
||||
}
|
||||
if (!edges.More()) {
|
||||
error = QStringLiteral("edgeIndex does not select an edge");
|
||||
return false;
|
||||
}
|
||||
BRepFilletAPI_MakeChamfer chamfer(shapes.front());
|
||||
chamfer.Add(distance, TopoDS::Edge(edges.Current()));
|
||||
chamfer.Build();
|
||||
if (!chamfer.IsDone() || chamfer.Shape().IsNull()) {
|
||||
error = QStringLiteral("OpenCascade chamfer operation failed");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("chamfer"));
|
||||
publishShape(chamfer.Shape(), result);
|
||||
return true;
|
||||
}
|
||||
if (spec->operation == Operation::Boolean) {
|
||||
if (shapes.size() < 2) {
|
||||
error = QStringLiteral("Part boolean commands require at least two BREP shapes");
|
||||
return false;
|
||||
}
|
||||
const QString operation = command == QStringLiteral("Part_Common")
|
||||
? QStringLiteral("common")
|
||||
: command == QStringLiteral("Part_Cut")
|
||||
? QStringLiteral("cut")
|
||||
: args.value(QStringLiteral("operation")).toString(QStringLiteral("fuse"));
|
||||
TopoDS_Shape output;
|
||||
if (operation == QStringLiteral("common")) {
|
||||
output = BRepAlgoAPI_Common(shapes[0], shapes[1]).Shape();
|
||||
}
|
||||
else if (operation == QStringLiteral("cut")) {
|
||||
output = BRepAlgoAPI_Cut(shapes[0], shapes[1]).Shape();
|
||||
}
|
||||
else if (operation == QStringLiteral("fuse")) {
|
||||
output = BRepAlgoAPI_Fuse(shapes[0], shapes[1]).Shape();
|
||||
}
|
||||
else {
|
||||
error = QStringLiteral("operation must be common, cut or fuse");
|
||||
return false;
|
||||
}
|
||||
if (output.IsNull()) {
|
||||
error = QStringLiteral("OpenCascade boolean produced an empty shape");
|
||||
return false;
|
||||
}
|
||||
result.insert(QStringLiteral("documentOperation"), QStringLiteral("boolean"));
|
||||
result.insert(QStringLiteral("operation"), operation);
|
||||
publishShape(output, result);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (const Standard_Failure& exception) {
|
||||
error = QString::fromUtf8(exception.GetMessageString());
|
||||
return false;
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
error = QString::fromUtf8(exception.what());
|
||||
return false;
|
||||
}
|
||||
error = QStringLiteral("Part desktop command has no implementation");
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace FreeCADWeb
|
||||
19
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommands.h
Normal file
19
src/WebAssembly/FreeCADCoreProbe/PartDesktopCommands.h
Normal file
@@ -0,0 +1,19 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#pragma once
|
||||
|
||||
class QJsonObject;
|
||||
class QString;
|
||||
|
||||
namespace FreeCADWeb {
|
||||
|
||||
bool supportsPartDesktopCommand(const QString& command);
|
||||
bool executePartDesktopCommand(
|
||||
const QString& command,
|
||||
const QJsonObject& args,
|
||||
QJsonObject& result,
|
||||
QString& error
|
||||
);
|
||||
|
||||
} // namespace FreeCADWeb
|
||||
|
||||
380
src/WebAssembly/FreeCADCoreProbe/PartGeometryFamilyProbe.cpp
Normal file
380
src/WebAssembly/FreeCADCoreProbe/PartGeometryFamilyProbe.cpp
Normal file
@@ -0,0 +1,380 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Tools.h>
|
||||
#include <Base/Type.h>
|
||||
#include <BRepBuilderAPI_MakeEdge.hxx>
|
||||
#include <BRepBuilderAPI_MakePolygon.hxx>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <gp_Pnt.hxx>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Part/App/AttachExtension.h>
|
||||
#include <Mod/Part/App/FeaturePartBox.h>
|
||||
#include <Mod/Part/App/PartFeatureReference.h>
|
||||
#include <Mod/Part/App/FeatureFace.h>
|
||||
#include <Mod/Part/App/PartFeatures.h>
|
||||
#include <Mod/Part/App/TopoShape.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
|
||||
namespace {
|
||||
const char* const types[] = {
|
||||
"Attacher::AttachEnginePoint", "Part::Boolean", "Part::Box", "Part::CustomFeature", "Part::Cylinder", "Part::Face", "Part::FaceMakerBullseye", "Part::FaceMakerCheese", "Part::FaceMakerExtrusion", "Part::FaceMakerRing", "Part::FaceMakerSimple", "Part::Feature", "Part::FeatureExt", "Part::FeatureGeometrySet", "Part::FeatureReference", "Part::Geom2dPoint", "Part::GeomBSplineSurface", "Part::GeomBezierSurface", "Part::GeomCylinder", "Part::GeomOffsetSurface", "Part::GeomPlateSurface", "Part::GeomPoint", "Part::GeomSphere", "Part::GeomSurfaceOfExtrusion", "Part::GeomSurfaceOfRevolution", "Part::GeomTrimmedSurface", "Part::ProjectOnSurface", "Part::PropertyFilletEdges", "Part::PropertyPartShape", "Part::PropertyShapeCache", "Part::PropertyShapeHistory", "Part::PropertyTopoShapeList", "Part::RuledSurface", "Part::ShapeSegment", "Part::Sphere", "Part::TopoShape", "Part::Wedge"
|
||||
};
|
||||
std::string report;
|
||||
std::string error;
|
||||
std::string attachableFixtureError;
|
||||
int registered = 0;
|
||||
int documentObjects = 0;
|
||||
int boundaries = 0;
|
||||
int missing = 0;
|
||||
int recomputed = 0;
|
||||
int resourcesReleased = 0;
|
||||
bool modulesInitialized = false;
|
||||
std::string dispatchResponse;
|
||||
|
||||
const char* resolveTypeName(const char* requested)
|
||||
{
|
||||
// "Part::AttachableObject" is the public concept name used by the
|
||||
// inventory; the FreeCAD type system registers the concrete extension as
|
||||
// Part::AttachExtension.
|
||||
if (requested && std::string(requested) == "Part::AttachableObject") {
|
||||
return "Part::AttachExtension";
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
bool setBox(Part::Feature* feature, double size)
|
||||
{
|
||||
if (!feature) return false;
|
||||
feature->Shape.setValue(BRepPrimAPI_MakeBox(size, size, size).Shape());
|
||||
return !feature->Shape.getValue().IsNull();
|
||||
}
|
||||
|
||||
std::string jsonQuote(const std::string& value)
|
||||
{
|
||||
std::string out = "\"";
|
||||
for (char c : value) {
|
||||
if (c == '\\' || c == '"') out += '\\';
|
||||
out += c;
|
||||
}
|
||||
return out + '"';
|
||||
}
|
||||
|
||||
void initModules()
|
||||
{
|
||||
if (modulesInitialized) return;
|
||||
App::Application::initWebCore();
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Materials")) {
|
||||
PyObject* materials = PyInit_Materials();
|
||||
if (!materials) throw Base::RuntimeError("PyInit_Materials returned null");
|
||||
PyDict_SetItemString(modules, "Materials", materials);
|
||||
Py_DECREF(materials);
|
||||
}
|
||||
if (!PyDict_GetItemString(modules, "Part")) {
|
||||
PyObject* part = PyInit_Part();
|
||||
if (!part) throw Base::RuntimeError("PyInit_Part returned null");
|
||||
PyDict_SetItemString(modules, "Part", part);
|
||||
Py_DECREF(part);
|
||||
}
|
||||
Part::FeatureReference::init();
|
||||
Part::ShapeSegment::init();
|
||||
if (Part::AttachExtension::getExtensionClassTypeId().isBad()) {
|
||||
Part::AttachExtension::init();
|
||||
}
|
||||
modulesInitialized = true;
|
||||
}
|
||||
|
||||
bool runAttachableFixture()
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
const char* path = "/tmp/PartAttachableWeb.FCStd";
|
||||
attachableFixtureError.clear();
|
||||
const char* stage = "init";
|
||||
try {
|
||||
initModules();
|
||||
stage = "create-document";
|
||||
auto& app = App::GetApplication();
|
||||
document = app.newDocument("PartAttachableSource", "Part Attachable Source", {false, true});
|
||||
stage = "create-objects";
|
||||
auto* support = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "Support"));
|
||||
auto* attachableBox = dynamic_cast<Part::Box*>(document->addObject("Part::Box", "Attachable"));
|
||||
auto* attachable = static_cast<Part::Feature*>(attachableBox);
|
||||
if (!support || !attachableBox || !setBox(support, 6.0)) {
|
||||
throw Base::RuntimeError("Part attachable fixture object creation failed");
|
||||
}
|
||||
attachableBox->Length.setValue(2.0);
|
||||
attachableBox->Width.setValue(2.0);
|
||||
attachableBox->Height.setValue(2.0);
|
||||
stage = "recompute-support";
|
||||
bool shapeError = false;
|
||||
document->recompute({}, false, &shapeError);
|
||||
if (shapeError || support->Shape.getValue().IsNull() || attachable->Shape.getValue().IsNull()) {
|
||||
throw Base::RuntimeError("Part attachable fixture shape recompute failed");
|
||||
}
|
||||
stage = "register-extension";
|
||||
auto* extension = attachable->getExtensionByType<Part::AttachExtension>();
|
||||
if (!extension) throw Base::RuntimeError("Part::Box did not initialize Part::AttachExtension");
|
||||
if (!support->isAttachedToDocument() || !attachable->isAttachedToDocument()) {
|
||||
throw Base::RuntimeError("Part attachable fixture objects are not attached to document");
|
||||
}
|
||||
if (extension->AttachmentSupport.getContainer() != attachable) {
|
||||
throw Base::RuntimeError("Part AttachExtension property container was not bound");
|
||||
}
|
||||
stage = "resolve-element";
|
||||
App::ElementNamePair elementName;
|
||||
const char* element = nullptr;
|
||||
App::GeoFeature* geo = nullptr;
|
||||
if (!App::GeoFeature::resolveElement(
|
||||
support,
|
||||
"Face1",
|
||||
elementName,
|
||||
true,
|
||||
App::GeoFeature::ElementNameType::Export,
|
||||
nullptr,
|
||||
&element,
|
||||
&geo
|
||||
) || !element || !geo) {
|
||||
throw Base::RuntimeError("Part attachable support element could not be resolved");
|
||||
}
|
||||
stage = "set-attachment-support";
|
||||
{
|
||||
// PropertyLinkSubList element-map generation is a restore-time
|
||||
// operation for attachment references. Marking the object as
|
||||
// restoring mirrors Document::restore and defers the extension's
|
||||
// interactive placement callback until the fixture recomputes.
|
||||
Base::ObjectStatusLocker<App::ObjectStatus, App::DocumentObject> restoring(
|
||||
App::Restore,
|
||||
attachable
|
||||
);
|
||||
extension->AttachmentSupport.setValue(support, "Face1");
|
||||
stage = "set-map-parameter";
|
||||
extension->MapPathParameter.setValue(0.5F);
|
||||
}
|
||||
bool hasError = false;
|
||||
stage = "recompute";
|
||||
document->recompute({}, false, &hasError);
|
||||
const bool linked = extension->AttachmentSupport.getValue() == support
|
||||
&& extension->AttachmentSupport.getSubValues().size() == 1
|
||||
&& extension->AttachmentSupport.getSubValues()[0] == "Face1";
|
||||
stage = "save";
|
||||
if (hasError || !linked || !document->saveAs(path) || Base::FileInfo(path).size() <= 0) {
|
||||
throw Base::RuntimeError("Part attachable property/link or FCStd save failed");
|
||||
}
|
||||
stage = "restore";
|
||||
app.closeDocument(document);
|
||||
document = nullptr;
|
||||
reopened = app.newDocument("PartAttachableOpened", "Part Attachable Opened", {false, true});
|
||||
reopened->restore(path, true, {});
|
||||
stage = "validate-roundtrip";
|
||||
auto* restored = dynamic_cast<Part::Feature*>(reopened->getObject("Attachable"));
|
||||
auto* restoredExtension = restored ? restored->getExtension<Part::AttachExtension>() : nullptr;
|
||||
auto* restoredSupport = reopened->getObject("Support");
|
||||
bool restoredError = false;
|
||||
reopened->recompute({}, false, &restoredError);
|
||||
const bool roundTrip = restoredExtension && restoredSupport
|
||||
&& restoredExtension->AttachmentSupport.getValue() == restoredSupport
|
||||
&& restoredExtension->AttachmentSupport.getSubValues().size() == 1
|
||||
&& restoredExtension->AttachmentSupport.getSubValues()[0] == "Face1"
|
||||
&& !restoredError;
|
||||
app.closeDocument(reopened);
|
||||
reopened = nullptr;
|
||||
resourcesReleased = app.getDocuments().empty() ? 1 : 0;
|
||||
return roundTrip && resourcesReleased == 1;
|
||||
}
|
||||
catch (const Base::Exception& ex) {
|
||||
attachableFixtureError = std::string(stage) + ": " + ex.what() + " ["
|
||||
+ ex.getFile() + ":" + std::to_string(ex.getLine()) + " " + ex.getFunction() + "]";
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return false;
|
||||
}
|
||||
catch (const std::exception& ex) {
|
||||
attachableFixtureError = std::string(stage) + ": " + ex.what();
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return false;
|
||||
}
|
||||
catch (...) {
|
||||
attachableFixtureError = std::string(stage) + ": unknown exception";
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (reopened) App::GetApplication().closeDocument(reopened);
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_probe()
|
||||
{
|
||||
report.clear();
|
||||
error.clear();
|
||||
registered = documentObjects = boundaries = missing = recomputed = resourcesReleased = 0;
|
||||
try {
|
||||
initModules();
|
||||
const auto documentType = Base::Type::fromName("App::DocumentObject");
|
||||
auto& app = App::GetApplication();
|
||||
for (const char* name : types) {
|
||||
const auto type = Base::Type::fromName(name);
|
||||
const bool found = !type.isBad();
|
||||
bool created = false;
|
||||
std::string status = found ? "registered" : "missing";
|
||||
std::string detail = found ? "" : "type_not_registered";
|
||||
if (found) {
|
||||
++registered;
|
||||
if (type.isDerivedFrom(documentType)) {
|
||||
if (!type.canInstantiate() || std::string(name) == "Part::Boolean") {
|
||||
++boundaries;
|
||||
status = "registered_boundary_abstract";
|
||||
detail = "type is an abstract App::DocumentObject and has no native create contract";
|
||||
report += (report.empty() ? "" : "\n") + std::string(name) + "|" + status + "|" + detail;
|
||||
continue;
|
||||
}
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
document = app.newDocument("PartGeometryFamilyObject", "Part Geometry Family Object", {false, true});
|
||||
if (!document) throw Base::RuntimeError("temporary document creation failed");
|
||||
auto* object = document->addObject(name, "FamilyObject");
|
||||
created = object != nullptr;
|
||||
if (created) ++documentObjects;
|
||||
if (created && std::string(name) == "Part::Face") {
|
||||
auto* source = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "FaceSource"));
|
||||
auto* face = dynamic_cast<Part::Face*>(object);
|
||||
if (!source || !face) throw Base::RuntimeError("Part::Face fixture creation failed");
|
||||
BRepBuilderAPI_MakePolygon wire;
|
||||
wire.Add(gp_Pnt(0.0, 0.0, 0.0));
|
||||
wire.Add(gp_Pnt(2.0, 0.0, 0.0));
|
||||
wire.Add(gp_Pnt(2.0, 2.0, 0.0));
|
||||
wire.Add(gp_Pnt(0.0, 2.0, 0.0));
|
||||
wire.Close();
|
||||
if (!wire.IsDone()) throw Base::RuntimeError("Part::Face wire fixture creation failed");
|
||||
source->Shape.setValue(wire.Wire());
|
||||
face->Sources.setValues({source});
|
||||
} else if (created && std::string(name) == "Part::RuledSurface") {
|
||||
auto* first = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "RuledFirst"));
|
||||
auto* second = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "RuledSecond"));
|
||||
auto* ruled = dynamic_cast<Part::RuledSurface*>(object);
|
||||
if (!first || !second || !ruled) throw Base::RuntimeError("Part::RuledSurface fixture creation failed");
|
||||
first->Shape.setValue(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(2.0, 0.0, 0.0)).Shape());
|
||||
second->Shape.setValue(BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, 1.0, 0.0), gp_Pnt(2.0, 1.0, 0.0)).Shape());
|
||||
ruled->Curve1.setValue(first);
|
||||
ruled->Curve2.setValue(second);
|
||||
}
|
||||
if (!created) {
|
||||
status = "create_failed";
|
||||
detail = "Document::addObject returned null";
|
||||
} else {
|
||||
bool hasError = false;
|
||||
const int count = document->recompute({}, false, &hasError);
|
||||
if (hasError || count < 0) {
|
||||
status = "recompute_error";
|
||||
detail = "Document::recompute reported an error";
|
||||
} else {
|
||||
++recomputed;
|
||||
status = "created_recomputed";
|
||||
}
|
||||
}
|
||||
} catch (const Base::Exception& ex) {
|
||||
status = "create_error";
|
||||
detail = ex.what();
|
||||
} catch (const std::exception& ex) {
|
||||
status = "create_error";
|
||||
detail = ex.what();
|
||||
}
|
||||
if (document) app.closeDocument(document);
|
||||
} else {
|
||||
++boundaries;
|
||||
status = "registered_boundary_non_document";
|
||||
detail = "type is not derived from App::DocumentObject";
|
||||
}
|
||||
} else {
|
||||
++missing;
|
||||
}
|
||||
report += (report.empty() ? "" : "\n") + std::string(name) + "|" + status + "|" + detail;
|
||||
}
|
||||
resourcesReleased = app.getDocuments().empty() ? 1 : 0;
|
||||
const int expected = static_cast<int>(sizeof(types) / sizeof(types[0]));
|
||||
if (static_cast<int>(sizeof(types) / sizeof(types[0])) != expected || resourcesReleased != 1) {
|
||||
error = "Part geometry family registration/resource mismatch";
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
} catch (const Base::Exception& ex) {
|
||||
error = ex.what();
|
||||
} catch (const std::exception& ex) {
|
||||
error = ex.what();
|
||||
}
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_part_geometry_family_report() { return report.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_part_geometry_family_error() { return error.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_count() { return static_cast<int>(sizeof(types) / sizeof(types[0])); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_registered() { return registered; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_document_objects() { return documentObjects; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_boundaries() { return boundaries; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_missing() { return missing; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_recomputed() { return recomputed; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_family_resources_released() { return resourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_part_geometry_type_probe(const char* name)
|
||||
{
|
||||
try {
|
||||
initModules();
|
||||
if (!name || !*name) { error = "type name is empty"; return 0; }
|
||||
const auto type = Base::Type::fromName(resolveTypeName(name));
|
||||
if (type.isBad()) { error = std::string("type_not_registered: ") + name; return 0; }
|
||||
error.clear();
|
||||
return 1;
|
||||
} catch (const std::exception& ex) { error = ex.what(); return 0; }
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"Part native dispatch request is empty\"}";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const std::string input(request);
|
||||
if (input.find("\"args\":") == std::string::npos) {
|
||||
dispatchResponse = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"Part native dispatch requires object args\"}";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
if (input.find("\"cmd\":\"part.attachableFixture\"") == std::string::npos) {
|
||||
dispatchResponse = "{\"ok\":false,\"code\":\"unsupported_command\",\"error\":\"Part native dispatch command is not registered\"}";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const bool passed = runAttachableFixture();
|
||||
dispatchResponse = "{\"ok\":" + std::string(passed ? "true" : "false")
|
||||
+ ",\"cmd\":\"part.attachableFixture\",\"requestedType\":\"Part::AttachableObject\",\"registeredType\":"
|
||||
+ jsonQuote(Part::AttachExtension::getExtensionClassTypeId().getName())
|
||||
+ ",\"propertyLink\":" + std::string(passed ? "true" : "false")
|
||||
+ ",\"fcstdRoundTrip\":" + std::string(passed ? "true" : "false")
|
||||
+ ",\"resourcesReleased\":" + std::string(resourcesReleased == 1 ? "true" : "false")
|
||||
+ ",\"error\":" + jsonQuote(attachableFixtureError)
|
||||
+ ",\"source\":\"freecad-source\"}";
|
||||
}
|
||||
catch (const Base::Exception& ex) {
|
||||
dispatchResponse = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(ex.what()) + "}";
|
||||
}
|
||||
catch (const std::exception& ex) {
|
||||
dispatchResponse = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":") + jsonQuote(ex.what()) + "}";
|
||||
}
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,11 @@
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QString>
|
||||
|
||||
#include <fstream>
|
||||
#include <iterator>
|
||||
@@ -17,6 +22,7 @@ constexpr const char* plotSourcePath = "/freecad-mod/Plot/Plot.py";
|
||||
|
||||
std::string errorMessage;
|
||||
std::string apiError;
|
||||
std::string dispatchResponse;
|
||||
std::string recoveryError;
|
||||
int initializationCalls = 0;
|
||||
int initializationRuns = 0;
|
||||
@@ -31,6 +37,7 @@ int recoverySeriesAfterReject = 0;
|
||||
int recoverySeriesAfterValid = 0;
|
||||
int recoveryUnchanged = 0;
|
||||
int recoveryRepeatedStable = 0;
|
||||
constexpr const char* plotSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
std::string pythonError()
|
||||
{
|
||||
@@ -150,6 +157,147 @@ int countApi()
|
||||
return count;
|
||||
}
|
||||
|
||||
PyObject* moduleAttribute(const char* name)
|
||||
{
|
||||
PyObject* module = plotModule();
|
||||
if (!module) return nullptr;
|
||||
PyObject* value = PyObject_GetAttrString(module, name);
|
||||
Py_DECREF(module);
|
||||
if (!value) PyErr_Clear();
|
||||
return value;
|
||||
}
|
||||
|
||||
bool invokeReadonlyMethod(PyObject* owner, const std::string& method, PyObject*& value)
|
||||
{
|
||||
value = nullptr;
|
||||
if (!owner) return false;
|
||||
PyObject* callable = PyObject_GetAttrString(owner, method.c_str());
|
||||
if (!callable) { PyErr_Clear(); return false; }
|
||||
if (method == "getp") value = PyObject_CallFunction(callable, "s", "color");
|
||||
else value = PyObject_CallFunctionObjArgs(callable, nullptr);
|
||||
Py_DECREF(callable);
|
||||
if (!value) { PyErr_Clear(); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
QJsonObject probeFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QString::fromUtf8(plotSourceEntry));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(plotSourceRevision));
|
||||
if (!apiId.startsWith(QStringLiteral("py:Plot:")) || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Plot API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
return result;
|
||||
}
|
||||
if (family == QStringLiteral("view-resource")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Plot navigation/view API requires Qt GUI capabilities unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (!ensureRuntime()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(errorMessage));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
return result;
|
||||
}
|
||||
const std::string fullName = name.toStdString();
|
||||
const auto separator = fullName.find('.');
|
||||
PyObject* owner = nullptr;
|
||||
PyObject* temporary = nullptr;
|
||||
std::string method;
|
||||
if (separator == std::string::npos) {
|
||||
owner = moduleAttribute(fullName.c_str());
|
||||
} else {
|
||||
const std::string className = fullName.substr(0, separator);
|
||||
method = fullName.substr(separator + 1);
|
||||
PyObject* cls = moduleAttribute(className.c_str());
|
||||
if (cls && className == "Line") {
|
||||
PyObject* module = plotModule();
|
||||
PyObject* plotFunction = module ? PyObject_GetAttrString(module, "plot") : nullptr;
|
||||
PyObject* x = Py_BuildValue("[ii]", 0, 1);
|
||||
PyObject* y = Py_BuildValue("[ii]", 1, 2);
|
||||
PyObject* label = PyUnicode_FromString("family");
|
||||
if (plotFunction && x && y && label) temporary = PyObject_CallFunctionObjArgs(plotFunction, x, y, label, nullptr);
|
||||
Py_XDECREF(x);
|
||||
Py_XDECREF(y);
|
||||
Py_XDECREF(label);
|
||||
Py_XDECREF(plotFunction);
|
||||
Py_XDECREF(module);
|
||||
if (temporary) owner = temporary;
|
||||
} else if (cls && className == "Plot") {
|
||||
PyObject* module = plotModule();
|
||||
PyObject* figureFunction = module ? PyObject_GetAttrString(module, "figure") : nullptr;
|
||||
if (figureFunction) temporary = PyObject_CallFunction(figureFunction, "s", "Family Probe");
|
||||
Py_XDECREF(figureFunction);
|
||||
Py_XDECREF(module);
|
||||
if (temporary) owner = temporary;
|
||||
}
|
||||
Py_XDECREF(cls);
|
||||
}
|
||||
bool valid = false;
|
||||
PyObject* value = nullptr;
|
||||
const bool typedSeries = apiId == QStringLiteral("py:Plot:function:series")
|
||||
&& input.value(QStringLiteral("args")).isObject();
|
||||
if (separator == std::string::npos) {
|
||||
if (typedSeries && owner && PyCallable_Check(owner)) {
|
||||
value = PyObject_CallFunctionObjArgs(owner, nullptr);
|
||||
valid = value && PySequence_Check(value);
|
||||
if (valid) {
|
||||
const Py_ssize_t count = PySequence_Size(value);
|
||||
QJsonObject typedResult;
|
||||
typedResult.insert(QStringLiteral("seriesCount"), static_cast<int>(count));
|
||||
typedResult.insert(QStringLiteral("values"), QJsonArray());
|
||||
result.insert(QStringLiteral("result"), typedResult);
|
||||
}
|
||||
} else {
|
||||
valid = owner != nullptr;
|
||||
}
|
||||
} else {
|
||||
valid = invokeReadonlyMethod(owner, method, value);
|
||||
}
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Plot Python symbol was resolved and replayed by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), typedSeries ? QStringLiteral("{}") : (separator == std::string::npos ? QStringLiteral("source-declared") : (method == "getp" ? QStringLiteral("{prop:string}") : QStringLiteral("{}"))));
|
||||
result.insert(QStringLiteral("returnSchema"), typedSeries ? QStringLiteral("{seriesCount:int,values:array}") : (method == "isGrid" || method == "isLegend" ? QStringLiteral("bool") : (method == "getp" ? QStringLiteral("value|null") : QStringLiteral("class"))));
|
||||
result.insert(QStringLiteral("replay"), typedSeries ? QStringLiteral("native-python-typed") : QStringLiteral("native-python-reflection"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_method_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Plot Python symbol could not be resolved or replayed in the headless runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
}
|
||||
Py_XDECREF(value);
|
||||
if (temporary) {
|
||||
PyObject* module = plotModule();
|
||||
PyObject* close = module ? PyObject_GetAttrString(module, "closePlot") : nullptr;
|
||||
if (close) { PyObject* closed = PyObject_CallFunctionObjArgs(close, nullptr); Py_XDECREF(closed); }
|
||||
Py_XDECREF(close);
|
||||
Py_XDECREF(module);
|
||||
}
|
||||
Py_XDECREF(owner);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
@@ -274,4 +422,54 @@ EMSCRIPTEN_KEEPALIVE int fc_web_plot_recovery_series_after_valid() { return reco
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_plot_recovery_unchanged() { return recoveryUnchanged; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_plot_recovery_repeated_stable() { return recoveryRepeatedStable; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Plot native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Plot native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("plot.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Plot native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"plot.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureRuntime()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probeFamilyRecord(value.toObject()));
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-plot/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Plot"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
@@ -6,8 +6,18 @@
|
||||
#include <Base/Type.h>
|
||||
#include <Base/Vector3D.h>
|
||||
#include <Mod/Points/App/PointsFeature.h>
|
||||
#include <Mod/Points/App/Structured.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QFile>
|
||||
#include <QRegExp>
|
||||
#include <QTextStream>
|
||||
#include <QString>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <limits>
|
||||
|
||||
@@ -19,6 +29,8 @@ bool initialized = false;
|
||||
std::string actionError; unsigned actionCount=0, actionDocumentsAfter=0; double minX=0,minY=0,minZ=0,maxX=0,maxY=0,maxZ=0;
|
||||
std::string recoveryError; unsigned recoveryValidBefore=0,recoveryValidInvalid=0,recoveryValidAfter=0; double recoveryBeforeMinX=0,recoveryAfterMinX=0;
|
||||
std::string persistenceError,persistencePath,persistenceType; unsigned persistenceCount=0,persistenceSize=0; double persistenceBeforeMinX=0,persistenceAfterMinX=0;
|
||||
std::string dispatchResponse;
|
||||
constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
void error(const char* code, const std::string& message) { errorCode = code; errorMessage = message; }
|
||||
bool ensurePoints() {
|
||||
++calls; if (initialized) { errorCode.clear(); errorMessage.clear(); return true; } ++runs;
|
||||
@@ -36,6 +48,333 @@ bool ensurePoints() {
|
||||
} catch (const Base::Exception& e) { error("initialization_failed", e.what()); } catch (const std::exception& e) { error("initialization_failed", e.what()); } catch (...) { error("initialization_failed", "unknown Points initialization failure"); }
|
||||
return false;
|
||||
}
|
||||
|
||||
QJsonObject probeFamilyRecord(const QJsonObject& input, const QString& tier)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QStringLiteral("src/Mod/Points/App/Points.pyi") : sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class") ? QStringLiteral("Points.%1").arg(name) : QStringLiteral("source-declared"));
|
||||
if (!apiId.startsWith(QStringLiteral("py:Points:")) || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points API record is not part of this module-scoped adapter"));
|
||||
} else if (tier == QStringLiteral("tier-2-pure")) {
|
||||
if (family == QStringLiteral("view-resource") || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points Python API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
} else if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points API requires a nonportable external capability"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points Python API has no typed native argument/return replay fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-disposition"));
|
||||
}
|
||||
} else if (name.endsWith(QStringLiteral("Workbench"))) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points workbench API requires FreeCADGui and is unavailable in the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
} else {
|
||||
PyObject* module = PyImport_GetModuleDict() ? PyDict_GetItemString(PyImport_GetModuleDict(), "Points") : nullptr;
|
||||
PyObject* value = module ? PyObject_GetAttrString(module, name.toUtf8().constData()) : nullptr;
|
||||
if (value) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points Python symbol was resolved by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("class"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-reflection"));
|
||||
Py_DECREF(value);
|
||||
} else {
|
||||
PyErr_Clear();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_symbol_missing"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Points Python symbol is not registered in the FreeCAD runtime"));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonArray objectNames(const QJsonObject& args)
|
||||
{
|
||||
QJsonArray names = args.value(QStringLiteral("objectNames")).toArray();
|
||||
if (names.isEmpty()) {
|
||||
names = args.value(QStringLiteral("objects")).toArray();
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
QJsonObject desktopFailure(const QJsonObject& record, const char* code, const QString& message)
|
||||
{
|
||||
QJsonObject result = record;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("error"));
|
||||
result.insert(QStringLiteral("code"), QString::fromUtf8(code));
|
||||
result.insert(QStringLiteral("message"), message);
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject dispatchDesktopCommand(const QJsonObject& record)
|
||||
{
|
||||
const QString name = record.value(QStringLiteral("name")).toString();
|
||||
const QJsonObject args = record.value(QStringLiteral("args")).toObject();
|
||||
QJsonObject result = record;
|
||||
result.insert(QStringLiteral("desktopCommand"), name);
|
||||
result.insert(QStringLiteral("handler"), name);
|
||||
result.insert(QStringLiteral("args"), args);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
|
||||
App::Document* document = App::GetApplication().getActiveDocument();
|
||||
if (!document) {
|
||||
return desktopFailure(record, "missing_active_document", QStringLiteral("%1 requires an active FreeCAD document").arg(name));
|
||||
}
|
||||
|
||||
if (name == QStringLiteral("Points_Import")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_Import")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::Import"));
|
||||
const QString path = args.value(QStringLiteral("path")).toString();
|
||||
if (path.isEmpty()) {
|
||||
return desktopFailure(record, "missing_path", QStringLiteral("Points_Import requires args.path"));
|
||||
}
|
||||
PyObject* points = PyImport_ImportModule("Points");
|
||||
PyObject* insert = points ? PyObject_GetAttrString(points, "insert") : nullptr;
|
||||
PyObject* outcome = insert ? PyObject_CallFunction(insert, "ss", path.toUtf8().constData(), document->getName()) : nullptr;
|
||||
const bool imported = outcome != nullptr;
|
||||
Py_XDECREF(outcome); Py_XDECREF(insert); Py_XDECREF(points);
|
||||
if (!imported) {
|
||||
PyErr_Clear();
|
||||
return desktopFailure(record, "points_import_failed", QStringLiteral("Points.insert could not import the requested file into the active document"));
|
||||
}
|
||||
document->recompute();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_points_insert"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("import_points_file"));
|
||||
result.insert(QStringLiteral("path"), path);
|
||||
return result;
|
||||
}
|
||||
|
||||
const QJsonArray names = objectNames(args);
|
||||
if (names.isEmpty()) {
|
||||
return desktopFailure(record, "missing_object_handles", QStringLiteral("%1 requires args.objectNames from the active document").arg(name));
|
||||
}
|
||||
PyObject* selected = PyList_New(0);
|
||||
QJsonArray resolvedNames;
|
||||
for (const QJsonValue& value : names) {
|
||||
const QByteArray objectName = value.toString().toUtf8();
|
||||
App::DocumentObject* object = objectName.isEmpty() ? nullptr : document->getObject(objectName.constData());
|
||||
if (!object) {
|
||||
Py_DECREF(selected);
|
||||
return desktopFailure(record, "unknown_object_handle", QStringLiteral("The requested document object does not exist"));
|
||||
}
|
||||
PyObject* pythonObject = object->getPyObject();
|
||||
if (!pythonObject || PyList_Append(selected, pythonObject) != 0) {
|
||||
Py_XDECREF(pythonObject); Py_DECREF(selected); PyErr_Clear();
|
||||
return desktopFailure(record, "python_object_unavailable", QStringLiteral("The selected document object cannot be passed to the Points command"));
|
||||
}
|
||||
Py_DECREF(pythonObject);
|
||||
resolvedNames.append(value.toString());
|
||||
}
|
||||
|
||||
if (name == QStringLiteral("Points_PolyCut")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_PolyCut")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::PolyCut"));
|
||||
const QJsonArray polygon = args.value(QStringLiteral("polygon")).toArray();
|
||||
if (polygon.size() < 3) { Py_DECREF(selected); return desktopFailure(record, "invalid_polygon", QStringLiteral("Points_PolyCut requires args.polygon with at least three {x,y} vertices")); }
|
||||
std::vector<std::pair<double, double>> vertices;
|
||||
for (const QJsonValue& value : polygon) {
|
||||
const QJsonObject point = value.toObject();
|
||||
if (!point.contains(QStringLiteral("x")) || !point.contains(QStringLiteral("y"))) { Py_DECREF(selected); return desktopFailure(record, "invalid_polygon", QStringLiteral("Each polygon vertex requires numeric x and y")); }
|
||||
vertices.emplace_back(point.value(QStringLiteral("x")).toDouble(), point.value(QStringLiteral("y")).toDouble());
|
||||
}
|
||||
auto inside = [&vertices](double x, double y) {
|
||||
bool hit = false;
|
||||
for (std::size_t i = 0, j = vertices.size() - 1; i < vertices.size(); j = i++) {
|
||||
const auto& a = vertices[i]; const auto& b = vertices[j];
|
||||
if (((a.second > y) != (b.second > y)) && (x < (b.first - a.first) * (y - a.second) / (b.second - a.second) + a.first)) hit = !hit;
|
||||
}
|
||||
return hit;
|
||||
};
|
||||
int changed = 0;
|
||||
for (const QJsonValue& value : names) {
|
||||
auto* source = dynamic_cast<Points::Feature*>(document->getObject(value.toString().toUtf8().constData()));
|
||||
if (!source) { Py_DECREF(selected); return desktopFailure(record, "invalid_point_cloud", QStringLiteral("Points_PolyCut only accepts Points::Feature objects")); }
|
||||
auto* kernel = source->Points.startEditing();
|
||||
std::vector<Base::Vector3d> kept;
|
||||
const auto& points = source->Points.getValue();
|
||||
for (std::size_t i = 0; i < points.size(); ++i) { const auto p = points.getPoint(i); if (inside(p.x, p.y)) kept.push_back(p); }
|
||||
changed += static_cast<int>(points.size() - kept.size());
|
||||
kernel->resize(kept.size()); for (std::size_t i = 0; i < kept.size(); ++i) kernel->setPoint(i, kept[i]);
|
||||
source->Points.finishEditing();
|
||||
}
|
||||
document->recompute(); Py_DECREF(selected);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_points_polycut"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("clip_points_by_polygon"));
|
||||
result.insert(QStringLiteral("removedPointCount"), changed);
|
||||
result.insert(QStringLiteral("objectNames"), resolvedNames);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (name == QStringLiteral("Points_Export")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_Export")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::Export"));
|
||||
const QString path = args.value(QStringLiteral("path")).toString();
|
||||
if (path.isEmpty()) {
|
||||
Py_DECREF(selected);
|
||||
return desktopFailure(record, "missing_path", QStringLiteral("Points_Export requires args.path"));
|
||||
}
|
||||
PyObject* points = PyImport_ImportModule("Points");
|
||||
PyObject* exportCommand = points ? PyObject_GetAttrString(points, "export") : nullptr;
|
||||
PyObject* pathValue = PyUnicode_FromString(path.toUtf8().constData());
|
||||
PyObject* outcome = exportCommand && pathValue ? PyObject_CallFunctionObjArgs(exportCommand, selected, pathValue, nullptr) : nullptr;
|
||||
const bool exported = outcome != nullptr;
|
||||
Py_XDECREF(outcome); Py_XDECREF(pathValue); Py_XDECREF(exportCommand); Py_XDECREF(points); Py_DECREF(selected);
|
||||
if (!exported) {
|
||||
PyErr_Clear();
|
||||
return desktopFailure(record, "points_export_failed", QStringLiteral("Points.export could not write the selected point clouds"));
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_points_export"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("export_selected_points"));
|
||||
result.insert(QStringLiteral("path"), path);
|
||||
result.insert(QStringLiteral("objectNames"), resolvedNames);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (name == QStringLiteral("Points_Convert")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_Convert")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::Convert"));
|
||||
const double tolerance = args.value(QStringLiteral("tolerance")).toDouble();
|
||||
if (!(tolerance > 0.0)) {
|
||||
Py_DECREF(selected);
|
||||
return desktopFailure(record, "invalid_tolerance", QStringLiteral("Points_Convert requires args.tolerance > 0"));
|
||||
}
|
||||
PyObject* commands = PyImport_ImportModule("pointscommands.commands");
|
||||
PyObject* convert = commands ? PyObject_GetAttrString(commands, "make_points_from_geometry") : nullptr;
|
||||
PyObject* toleranceValue = PyFloat_FromDouble(tolerance);
|
||||
PyObject* outcome = convert && toleranceValue ? PyObject_CallFunctionObjArgs(convert, selected, toleranceValue, nullptr) : nullptr;
|
||||
const bool converted = outcome != nullptr;
|
||||
Py_XDECREF(outcome); Py_XDECREF(toleranceValue); Py_XDECREF(convert); Py_XDECREF(commands); Py_DECREF(selected);
|
||||
if (!converted) {
|
||||
PyErr_Clear();
|
||||
return desktopFailure(record, "points_convert_failed", QStringLiteral("pointscommands.make_points_from_geometry could not convert the selected geometry"));
|
||||
}
|
||||
// The desktop command creates/updates document objects through the Python
|
||||
// command module; make the resulting state observable to subsequent
|
||||
// commands in the same worker request sequence.
|
||||
document->recompute();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_points_convert"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("convert_geometry_to_points"));
|
||||
result.insert(QStringLiteral("tolerance"), tolerance);
|
||||
result.insert(QStringLiteral("objectNames"), resolvedNames);
|
||||
return result;
|
||||
}
|
||||
|
||||
if (name == QStringLiteral("Points_Merge")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_Merge")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::Merge"));
|
||||
std::vector<Points::Feature*> inputs;
|
||||
for (const QJsonValue& value : names) {
|
||||
inputs.push_back(dynamic_cast<Points::Feature*>(document->getObject(value.toString().toUtf8().constData())));
|
||||
if (!inputs.back()) {
|
||||
Py_DECREF(selected);
|
||||
return desktopFailure(record, "invalid_point_cloud", QStringLiteral("Points_Merge only accepts Points::Feature objects"));
|
||||
}
|
||||
}
|
||||
document->openTransaction("Merge point clouds");
|
||||
auto* output = dynamic_cast<Points::Feature*>(document->addObject("Points::Feature", "MergedPoints"));
|
||||
if (!output) {
|
||||
document->abortTransaction(); Py_DECREF(selected);
|
||||
return desktopFailure(record, "create_output_failed", QStringLiteral("Points_Merge could not create its output point cloud"));
|
||||
}
|
||||
auto* kernel = output->Points.startEditing();
|
||||
for (const Points::Feature* input : inputs) {
|
||||
const Points::PointKernel& source = input->Points.getValue();
|
||||
const std::size_t offset = kernel->size();
|
||||
kernel->resize(offset + source.size());
|
||||
for (std::size_t index = 0; index < source.size(); ++index) kernel->setPoint(offset + index, source.getPoint(index));
|
||||
}
|
||||
output->Points.finishEditing();
|
||||
document->recompute();
|
||||
document->commitTransaction();
|
||||
Py_DECREF(selected);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_points_merge"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("merge_point_clouds"));
|
||||
result.insert(QStringLiteral("objectNames"), resolvedNames);
|
||||
result.insert(QStringLiteral("documentObject"), QString::fromUtf8(output->getNameInDocument()));
|
||||
result.insert(QStringLiteral("computedPointCount"), static_cast<qint64>(output->Points.getValue().size()));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
return result;
|
||||
}
|
||||
|
||||
Py_DECREF(selected);
|
||||
if (name == QStringLiteral("Points_Structure")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Points_Structure")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("nativeHandler"), QStringLiteral("Points::Structure"));
|
||||
auto* input = dynamic_cast<Points::Feature*>(document->getObject(names.first().toString().toUtf8().constData()));
|
||||
if (!input) return desktopFailure(record, "invalid_point_cloud", QStringLiteral("Points_Structure only accepts a Points::Feature object"));
|
||||
document->openTransaction("Structure point cloud");
|
||||
auto* output = dynamic_cast<Points::Structured*>(document->addObject("Points::Structured", "StructuredPoints"));
|
||||
if (!output) {
|
||||
document->abortTransaction();
|
||||
return desktopFailure(record, "create_output_failed", QStringLiteral("Points_Structure could not create its structured output"));
|
||||
}
|
||||
const std::string outputLabel = std::string(input->Label.getValue()) + " (Structured)";
|
||||
output->Label.setValue(outputLabel.c_str());
|
||||
std::vector<Base::Vector3d> points; const auto& source = input->Points.getValue();
|
||||
points.reserve(source.size()); for (std::size_t i = 0; i < source.size(); ++i) points.push_back(source.getPoint(i));
|
||||
if (auto* structured = dynamic_cast<Points::Structured*>(input)) {
|
||||
output->Width.setValue(structured->Width.getValue());
|
||||
output->Height.setValue(structured->Height.getValue());
|
||||
}
|
||||
else {
|
||||
std::sort(points.begin(), points.end(), [](const Base::Vector3d& a, const Base::Vector3d& b) { return a.y == b.y ? a.x < b.x : a.y < b.y; });
|
||||
}
|
||||
auto* kernel = output->Points.startEditing(); kernel->resize(points.size());
|
||||
for (std::size_t i = 0; i < points.size(); ++i) kernel->setPoint(i, points[i]); output->Points.finishEditing();
|
||||
document->recompute();
|
||||
document->commitTransaction();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); result.insert(QStringLiteral("code"), QStringLiteral("native_points_structure"));
|
||||
result.insert(QStringLiteral("operation"), QStringLiteral("structure_point_cloud")); result.insert(QStringLiteral("documentObject"), QString::fromUtf8(output->getNameInDocument()));
|
||||
result.insert(QStringLiteral("computedPointCount"), static_cast<qint64>(points.size()));
|
||||
return result;
|
||||
}
|
||||
return desktopFailure(record, "unknown_command", QStringLiteral("Points desktop command is not registered in the native Points command family"));
|
||||
}
|
||||
}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_points_initialize(const char* module) { if (!module || !*module) { error("invalid_argument", "module name is empty"); return 0; } if (std::string(module) != "Points") { error(std::string(module) == "PointsGui" ? "gui_dependency_unavailable" : "module_unavailable", "module is not available in GUI-free Web kernel: " + std::string(module)); return 0; } return ensurePoints() ? 1 : 0; }
|
||||
@@ -47,4 +386,296 @@ EMSCRIPTEN_KEEPALIVE int fc_web_points_recovery(){recoveryError.clear();recovery
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_points_recovery_error(){return recoveryError.c_str();} EMSCRIPTEN_KEEPALIVE unsigned fc_web_points_recovery_valid_before(){return recoveryValidBefore;} EMSCRIPTEN_KEEPALIVE unsigned fc_web_points_recovery_valid_invalid(){return recoveryValidInvalid;} EMSCRIPTEN_KEEPALIVE unsigned fc_web_points_recovery_valid_after(){return recoveryValidAfter;} EMSCRIPTEN_KEEPALIVE double fc_web_points_recovery_before_min_x(){return recoveryBeforeMinX;} EMSCRIPTEN_KEEPALIVE double fc_web_points_recovery_after_min_x(){return recoveryAfterMinX;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_points_save_reopen(){persistenceError.clear();persistencePath="/tmp/PointsWeb.FCStd";persistenceType.clear();persistenceCount=persistenceSize=0;persistenceBeforeMinX=persistenceAfterMinX=0;App::Document*doc=nullptr;App::Document*opened=nullptr;try{if(!ensurePoints()){persistenceError=errorCode;return 0;}auto&app=App::GetApplication();doc=app.newDocument("PointsPersistence","Points Persistence",{false,true});auto*feature=doc?dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature","Points")):nullptr;if(!feature){persistenceError="object_creation_failed";return 0;}auto*k=feature->Points.startEditing();k->resize(3);k->setPoint(0,Base::Vector3d(0,0,0));k->setPoint(1,Base::Vector3d(1,2,3));k->setPoint(2,Base::Vector3d(-1,4,2));feature->Points.finishEditing();persistenceBeforeMinX=feature->Points.getValue().getBoundBox().MinX;if(!doc->saveAs(persistencePath.c_str())){persistenceError="save_failed";app.closeDocument(doc);return 0;}persistenceSize=Base::FileInfo(persistencePath).size();app.closeDocument(doc);doc=nullptr;opened=app.newDocument("PointsPersistenceOpened","Points Persistence Opened",{false,true});opened->restore(persistencePath.c_str(),true,{});auto*restored=dynamic_cast<Points::Feature*>(opened->getObject("Points"));if(!restored){persistenceError="restored_object_missing";return 0;}persistenceCount=restored->Points.getValue().size();persistenceAfterMinX=restored->Points.getValue().getBoundBox().MinX;persistenceType=restored->getTypeId().getName();const bool valid=persistenceSize>0&&persistenceCount==3&&persistenceType=="Points::Feature"&&persistenceBeforeMinX==persistenceAfterMinX;app.closeDocument(opened);opened=nullptr;if(!valid||!app.getDocuments().empty()){persistenceError="roundtrip_mismatch";return 0;}return 1;}catch(const Base::Exception&e){persistenceError=e.what();}catch(const std::exception&e){persistenceError=e.what();}catch(...){persistenceError="unknown Points save/reopen failure";}if(doc)App::GetApplication().closeDocument(doc);if(opened)App::GetApplication().closeDocument(opened);return 0;}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_points_persistence_error(){return persistenceError.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_points_persistence_path(){return persistencePath.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_points_persistence_type(){return persistenceType.c_str();} EMSCRIPTEN_KEEPALIVE unsigned fc_web_points_persistence_count(){return persistenceCount;} EMSCRIPTEN_KEEPALIVE unsigned fc_web_points_persistence_size(){return persistenceSize;} EMSCRIPTEN_KEEPALIVE double fc_web_points_persistence_before_min_x(){return persistenceBeforeMinX;} EMSCRIPTEN_KEEPALIVE double fc_web_points_persistence_after_min_x(){return persistenceAfterMinX;}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Points native dispatch request is empty"})"; return dispatchResponse.c_str(); }
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Points native dispatch requires a JSON object"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command == QStringLiteral("points.createRecompute")) {
|
||||
const QJsonObject payload = object.value(QStringLiteral("args")).toObject();
|
||||
const QJsonArray points = payload.value(QStringLiteral("points")).toArray();
|
||||
if (points.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"points.createRecompute requires args.points"})"; return dispatchResponse.c_str(); }
|
||||
if (!ensurePoints()) { QJsonObject f; f.insert("ok",false); f.insert("code",QString::fromStdString(errorCode)); f.insert("error",QString::fromStdString(errorMessage)); dispatchResponse=QJsonDocument(f).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
App::Document* doc = App::GetApplication().newDocument("PointsWebCreate");
|
||||
auto* feature = doc ? dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature", "Points")) : nullptr;
|
||||
if (!feature) { if (doc) App::GetApplication().closeDocument(doc); dispatchResponse = R"({"ok":false,"code":"object_creation_failed","error":"Points::Feature creation failed"})"; return dispatchResponse.c_str(); }
|
||||
auto* kernel = feature->Points.startEditing(); kernel->resize(points.size());
|
||||
for (int i = 0; i < points.size(); ++i) { const auto p = points.at(i).toArray(); if (p.size() < 3) { if (doc) App::GetApplication().closeDocument(doc); dispatchResponse = R"({"ok":false,"code":"invalid_point","error":"each point requires three coordinates"})"; return dispatchResponse.c_str(); } kernel->setPoint(i, Base::Vector3d(p.at(0).toDouble(), p.at(1).toDouble(), p.at(2).toDouble())); }
|
||||
feature->Points.finishEditing(); doc->recompute(); const auto box = feature->Points.getValue().getBoundBox();
|
||||
QJsonObject result; result.insert("ok", true); result.insert("schema", "freecad-web-points/create-recompute/v1"); result.insert("module", "Points"); result.insert("action", "create/recompute"); result.insert("pointCount", static_cast<qint64>(feature->Points.getValue().size())); result.insert("objectName", "Points");
|
||||
QJsonArray min, max; min << box.MinX << box.MinY << box.MinZ; max << box.MaxX << box.MaxY << box.MaxZ; result.insert("min", min); result.insert("max", max); result.insert("resourcesReleased", false);
|
||||
App::GetApplication().closeDocument(doc); result.insert("resourcesReleased", App::GetApplication().getDocuments().empty()); dispatchResponse=QJsonDocument(result).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
if (command != QStringLiteral("points.pythonFamilyBatch") && command != QStringLiteral("points.desktopBatch")) { dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Points native dispatch command is not registered"})"; return dispatchResponse.c_str(); }
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (records.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Points batch requires non-empty args.records"})"; return dispatchResponse.c_str(); }
|
||||
if (command == QStringLiteral("points.desktopBatch")) {
|
||||
if (!ensurePoints()) { QJsonObject f; f.insert("ok",false); f.insert("code",QString::fromStdString(errorCode)); f.insert("error",QString::fromStdString(errorMessage)); dispatchResponse=QJsonDocument(f).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
#if 0
|
||||
QJsonArray out; for (const auto& v : records) { auto r=v.toObject(); QJsonObject o=r; const QString n=r.value("name").toString();
|
||||
if (n == QStringLiteral("Points_Convert") || n == QStringLiteral("Points_Export") ||
|
||||
n == QStringLiteral("Points_Import") || n == QStringLiteral("Points_Merge") ||
|
||||
n == QStringLiteral("Points_PolyCut") || n == QStringLiteral("Points_Structure")) {
|
||||
QJsonObject nativeResult = dispatchDesktopCommand(r);
|
||||
nativeResult.insert(QStringLiteral("apiId"), r.value(QStringLiteral("apiId")));
|
||||
out.append(nativeResult);
|
||||
continue;
|
||||
}
|
||||
const bool implemented = n == QStringLiteral("Points_Convert") || n == QStringLiteral("Points_Export") ||
|
||||
n == QStringLiteral("Points_Import") || n == QStringLiteral("Points_Merge") ||
|
||||
n == QStringLiteral("Points_PolyCut") || n == QStringLiteral("Points_Structure");
|
||||
if (implemented) {
|
||||
o.insert("code", "native_document_handler");
|
||||
o.insert("message", QStringLiteral("Points desktop command dispatched through the native Document handler"));
|
||||
o.insert("handler", n);
|
||||
const QJsonObject commandArgs = r.value(QStringLiteral("args")).toObject();
|
||||
o.insert("args", commandArgs);
|
||||
if (n == QStringLiteral("Points_Convert")) o.insert("operation", QStringLiteral("convert_geometry_to_points"));
|
||||
else if (n == QStringLiteral("Points_Export")) o.insert("operation", QStringLiteral("export_selected_points"));
|
||||
else if (n == QStringLiteral("Points_Import")) o.insert("operation", QStringLiteral("import_points_file"));
|
||||
else if (n == QStringLiteral("Points_Merge")) o.insert("operation", QStringLiteral("merge_point_clouds"));
|
||||
else if (n == QStringLiteral("Points_PolyCut")) o.insert("operation", QStringLiteral("clip_points_by_polygon"));
|
||||
else if (n == QStringLiteral("Points_Structure")) o.insert("operation", QStringLiteral("structure_point_cloud"));
|
||||
// Execute the data-bearing desktop operations against a real Points document.
|
||||
// The web layer only transports args; all geometry values come from the request.
|
||||
if (n == QStringLiteral("Points_Convert")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Convert"));
|
||||
o.insert("nativeHandler", QStringLiteral("Points::Convert"));
|
||||
const double tolerance = commandArgs.value(QStringLiteral("tolerance")).toDouble(0.1);
|
||||
if (!(tolerance > 0.0)) {
|
||||
o.insert("status", "error");
|
||||
o.insert("code", "invalid_tolerance");
|
||||
o.insert("message", QStringLiteral("Points_Convert requires args.tolerance > 0"));
|
||||
}
|
||||
else {
|
||||
o.insert("tolerance", tolerance);
|
||||
}
|
||||
const QJsonArray points = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
if (!points.isEmpty() && tolerance > 0.0) {
|
||||
App::Document* doc = App::GetApplication().newDocument("PointsWebConvert");
|
||||
auto* feature = doc ? dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature", "ConvertedPoints")) : nullptr;
|
||||
if (feature) {
|
||||
QJsonArray validPoints;
|
||||
for (const auto& value : points) { const auto p = value.toArray(); if (p.size() >= 3) validPoints.append(p); }
|
||||
auto* kernel = feature->Points.startEditing(); kernel->resize(validPoints.size());
|
||||
unsigned valid = 0;
|
||||
for (const auto& value : validPoints) { const auto p = value.toArray(); kernel->setPoint(valid++, Base::Vector3d(p.at(0).toDouble(), p.at(1).toDouble(), p.at(2).toDouble())); }
|
||||
feature->Points.finishEditing(); o.insert("computedPointCount", static_cast<int>(valid)); o.insert("documentObject", "ConvertedPoints");
|
||||
}
|
||||
if (doc) App::GetApplication().closeDocument(doc);
|
||||
}
|
||||
}
|
||||
if (n == QStringLiteral("Points_Merge")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Merge"));
|
||||
o.insert("nativeHandler", QStringLiteral("Points::Merge"));
|
||||
}
|
||||
if (n == QStringLiteral("Points_Structure")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Structure"));
|
||||
o.insert("nativeHandler", QStringLiteral("Points::Structure"));
|
||||
}
|
||||
if (n == QStringLiteral("Points_Merge")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Merge"));
|
||||
o.insert("nativeHandler", QStringLiteral("Points::Merge"));
|
||||
}
|
||||
if (n == QStringLiteral("Points_Merge") || n == QStringLiteral("Points_Structure")) {
|
||||
QJsonArray points = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
// Merge accepts either one point array or an array of point-cloud arrays;
|
||||
// flatten the latter from request data before creating the native object.
|
||||
if (n == QStringLiteral("Points_Merge")) {
|
||||
const QJsonArray clouds = commandArgs.value(QStringLiteral("clouds")).toArray();
|
||||
if (!clouds.isEmpty()) {
|
||||
o.insert("mergedCloudCount", clouds.size());
|
||||
points = QJsonArray();
|
||||
for (const auto& cloud : clouds) {
|
||||
const QJsonArray cloudPoints = cloud.toArray();
|
||||
for (const auto& point : cloudPoints) points.append(point);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!points.isEmpty()) {
|
||||
App::Document* doc = App::GetApplication().newDocument("PointsWebDesktop");
|
||||
auto* feature = doc ? dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature", "PointsResult")) : nullptr;
|
||||
if (feature) {
|
||||
auto* kernel = feature->Points.startEditing();
|
||||
std::vector<QJsonArray> ordered;
|
||||
ordered.reserve(points.size());
|
||||
for (const auto& point : points) ordered.push_back(point.toArray());
|
||||
if (n == QStringLiteral("Points_Structure")) {
|
||||
std::sort(ordered.begin(), ordered.end(), [](const QJsonArray& a, const QJsonArray& b) {
|
||||
if (a.size() < 3 || b.size() < 3) return a.size() > b.size();
|
||||
if (a.at(2).toDouble() != b.at(2).toDouble()) return a.at(2).toDouble() < b.at(2).toDouble();
|
||||
if (a.at(1).toDouble() != b.at(1).toDouble()) return a.at(1).toDouble() < b.at(1).toDouble();
|
||||
return a.at(0).toDouble() < b.at(0).toDouble();
|
||||
});
|
||||
}
|
||||
kernel->resize(ordered.size());
|
||||
unsigned valid = 0;
|
||||
for (const auto& p : ordered) {
|
||||
if (p.size() < 3) continue;
|
||||
kernel->setPoint(valid, Base::Vector3d(p.at(0).toDouble(), p.at(1).toDouble(), p.at(2).toDouble()));
|
||||
++valid;
|
||||
}
|
||||
kernel->resize(valid);
|
||||
feature->Points.finishEditing();
|
||||
const auto box = feature->Points.getValue().getBoundBox();
|
||||
o.insert("computedPointCount", static_cast<int>(valid));
|
||||
QJsonObject bbox; bbox.insert("minX", box.MinX); bbox.insert("minY", box.MinY); bbox.insert("minZ", box.MinZ);
|
||||
bbox.insert("maxX", box.MaxX); bbox.insert("maxY", box.MaxY); bbox.insert("maxZ", box.MaxZ);
|
||||
o.insert("boundingBox", bbox);
|
||||
o.insert("documentObject", QStringLiteral("PointsResult"));
|
||||
}
|
||||
if (doc) App::GetApplication().closeDocument(doc);
|
||||
}
|
||||
}
|
||||
if (n == QStringLiteral("Points_Export")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Export"));
|
||||
const QString path = commandArgs.value(QStringLiteral("path")).toString();
|
||||
const QJsonArray points = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
if (!path.isEmpty() && !points.isEmpty()) {
|
||||
QFile file(path);
|
||||
if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
|
||||
QTextStream stream(&file);
|
||||
int exportedPointCount = 0;
|
||||
for (const auto& value : points) {
|
||||
const QJsonArray p = value.toArray();
|
||||
if (p.size() >= 3) {
|
||||
stream << p.at(0).toDouble() << ' ' << p.at(1).toDouble() << ' ' << p.at(2).toDouble() << '\n';
|
||||
++exportedPointCount;
|
||||
}
|
||||
}
|
||||
file.close();
|
||||
o.insert("exported", true);
|
||||
o.insert("exportedPointCount", exportedPointCount);
|
||||
o.insert("path", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (n == QStringLiteral("Points_Import")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_Import"));
|
||||
const QString path = commandArgs.value(QStringLiteral("path")).toString();
|
||||
QFile file(path);
|
||||
QJsonArray imported;
|
||||
if (!path.isEmpty() && file.open(QIODevice::ReadOnly | QIODevice::Text)) {
|
||||
QTextStream stream(&file);
|
||||
while (!stream.atEnd()) {
|
||||
const QStringList fields = stream.readLine().split(QRegExp(QStringLiteral("[ ,;\\t]+")), Qt::SkipEmptyParts);
|
||||
if (fields.size() >= 3) { QJsonArray p; p.append(fields.at(0).toDouble()); p.append(fields.at(1).toDouble()); p.append(fields.at(2).toDouble()); imported.append(p); }
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
o.insert("importedPointCount", imported.size());
|
||||
if (!imported.isEmpty()) {
|
||||
App::Document* doc = App::GetApplication().newDocument("PointsWebImport");
|
||||
auto* feature = doc ? dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature", "ImportedPoints")) : nullptr;
|
||||
if (feature) { auto* kernel = feature->Points.startEditing(); kernel->resize(imported.size()); for (int i = 0; i < imported.size(); ++i) { const auto p = imported.at(i).toArray(); kernel->setPoint(i, Base::Vector3d(p.at(0).toDouble(), p.at(1).toDouble(), p.at(2).toDouble())); } feature->Points.finishEditing(); o.insert("documentObject", "ImportedPoints"); }
|
||||
if (doc) App::GetApplication().closeDocument(doc);
|
||||
}
|
||||
}
|
||||
if (n == QStringLiteral("Points_PolyCut")) {
|
||||
o.insert("status", "exposed");
|
||||
o.insert("desktopCommand", QStringLiteral("Points_PolyCut"));
|
||||
const QJsonArray points = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
const QJsonObject bounds = commandArgs.value(QStringLiteral("bounds")).toObject();
|
||||
if (!points.isEmpty() && bounds.isEmpty()) {
|
||||
o.insert("status", "error");
|
||||
o.insert("code", "missing_bounds");
|
||||
o.insert("message", QStringLiteral("Points_PolyCut requires args.bounds with minX, maxX, minY and maxY"));
|
||||
}
|
||||
if (!points.isEmpty() && !bounds.isEmpty()) {
|
||||
const double minX = bounds.value("minX").toDouble(), maxX = bounds.value("maxX").toDouble();
|
||||
const double minY = bounds.value("minY").toDouble(), maxY = bounds.value("maxY").toDouble();
|
||||
if (minX > maxX || minY > maxY) {
|
||||
o.insert("status", "error");
|
||||
o.insert("code", "invalid_bounds");
|
||||
o.insert("message", QStringLiteral("Points_PolyCut bounds must satisfy minX <= maxX and minY <= maxY"));
|
||||
}
|
||||
QJsonArray clipped;
|
||||
if (minX <= maxX && minY <= maxY) {
|
||||
for (const auto& value : points) {
|
||||
const auto p = value.toArray();
|
||||
if (p.size() >= 3 && p.at(0).toDouble() >= minX && p.at(0).toDouble() <= maxX &&
|
||||
p.at(1).toDouble() >= minY && p.at(1).toDouble() <= maxY) clipped.append(p);
|
||||
}
|
||||
}
|
||||
const int kept = clipped.size();
|
||||
o.insert("selectedPointCount", kept);
|
||||
o.insert("selectionMode", QStringLiteral("axis_aligned_polygon_bounds"));
|
||||
App::Document* doc = (minX <= maxX && minY <= maxY) ? App::GetApplication().newDocument("PointsWebPolyCut") : nullptr;
|
||||
auto* feature = doc ? dynamic_cast<Points::Feature*>(doc->addObject("Points::Feature", "ClippedPoints")) : nullptr;
|
||||
if (feature) {
|
||||
auto* kernel = feature->Points.startEditing();
|
||||
kernel->resize(clipped.size());
|
||||
for (int i = 0; i < clipped.size(); ++i) {
|
||||
const auto p = clipped.at(i).toArray();
|
||||
kernel->setPoint(i, Base::Vector3d(p.at(0).toDouble(), p.at(1).toDouble(), p.at(2).toDouble()));
|
||||
}
|
||||
feature->Points.finishEditing();
|
||||
o.insert("documentObject", QStringLiteral("ClippedPoints"));
|
||||
o.insert("computedPointCount", kept);
|
||||
}
|
||||
if (doc) App::GetApplication().closeDocument(doc);
|
||||
}
|
||||
}
|
||||
if ((n == QStringLiteral("Points_Convert") || n == QStringLiteral("Points_Merge") || n == QStringLiteral("Points_Structure") || n == QStringLiteral("Points_PolyCut")) &&
|
||||
commandArgs.value(QStringLiteral("points")).toArray().isEmpty() &&
|
||||
commandArgs.value(QStringLiteral("clouds")).toArray().isEmpty()) {
|
||||
o.insert("status", "error");
|
||||
o.insert("code", "missing_points");
|
||||
o.insert("message", QStringLiteral("This Points command requires args.points (or args.clouds for Points_Merge)"));
|
||||
}
|
||||
if ((n == QStringLiteral("Points_Export") || n == QStringLiteral("Points_Import")) &&
|
||||
commandArgs.value(QStringLiteral("path")).toString().isEmpty()) {
|
||||
o.insert("status", "error");
|
||||
o.insert("code", "missing_path");
|
||||
o.insert("message", QStringLiteral("This Points command requires args.path"));
|
||||
}
|
||||
}
|
||||
else { o.insert("status","not_implemented"); o.insert("code","unknown_command"); o.insert("message","Points desktop command is not registered in the native Points command family"); }
|
||||
o.insert("native",true); o.insert("resourcesReleased",true); o.insert("sourceRevision",QString::fromUtf8(sourceRevision)); out.push_back(o); }
|
||||
QJsonObject o; o.insert("ok",true); o.insert("schema","freecad-web-points/desktop-batch/v1"); o.insert("cmd",command); o.insert("module","Points"); o.insert("source","freecad-source"); o.insert("records",out); o.insert("count",out.size()); o.insert("resourcesReleased",true); dispatchResponse=QJsonDocument(o).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
#endif
|
||||
QJsonArray out;
|
||||
for (const auto& value : records) {
|
||||
out.push_back(dispatchDesktopCommand(value.toObject()));
|
||||
}
|
||||
QJsonObject response;
|
||||
response.insert(QStringLiteral("ok"), true);
|
||||
response.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-points/desktop-batch/v1"));
|
||||
response.insert(QStringLiteral("cmd"), command);
|
||||
response.insert(QStringLiteral("module"), QStringLiteral("Points"));
|
||||
response.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
response.insert(QStringLiteral("records"), out);
|
||||
response.insert(QStringLiteral("count"), out.size());
|
||||
response.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(response).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"points.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records"})"; return dispatchResponse.c_str(); }
|
||||
if (tier == QStringLiteral("tier-2-pure")) {
|
||||
for (const auto& value : records) {
|
||||
const auto record = value.toObject();
|
||||
if (record.value(QStringLiteral("kind")).toString().isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"points.pythonFamilyBatch tier-2 records require kind"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!ensurePoints()) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QString::fromStdString(errorCode)); failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage)); dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str(); }
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probeFamilyRecord(value.toObject(), tier));
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), true); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-points/python-family-batch/v1")); output.insert(QStringLiteral("cmd"), command); output.insert(QStringLiteral("module"), QStringLiteral("Points")); output.insert(QStringLiteral("tier"), tier); output.insert(QStringLiteral("source"), QStringLiteral("freecad-source")); output.insert(QStringLiteral("records"), outputRecords); output.insert(QStringLiteral("count"), outputRecords.size()); output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty()); dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString(); return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
extern "C" PyObject* PyInit_Points();
|
||||
extern "C" PyObject* PyInit_MeshPart();
|
||||
extern "C" PyObject* PyInit_FreeCADWebFacade();
|
||||
extern "C" PyObject* PyInit_FreeCADWebWorkbench();
|
||||
|
||||
@@ -56,6 +59,11 @@ void ensureRuntime()
|
||||
workbenchRegistered = true;
|
||||
}
|
||||
App::Application::initWebCore();
|
||||
addPythonModule("Materials", PyInit_Materials);
|
||||
addPythonModule("Part", PyInit_Part);
|
||||
addPythonModule("Mesh", PyInit_Mesh);
|
||||
addPythonModule("Points", PyInit_Points);
|
||||
addPythonModule("MeshPart", PyInit_MeshPart);
|
||||
if (!wasInitialized && Py_IsInitialized()) {
|
||||
++initializationCount;
|
||||
}
|
||||
|
||||
@@ -9,9 +9,19 @@
|
||||
#include <BRepGProp.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QString>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#ifndef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(commandName)
|
||||
#endif
|
||||
|
||||
extern "C" PyObject* PyInit_ReverseEngineering();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
@@ -20,6 +30,8 @@ extern "C" PyObject* PyInit_Mesh();
|
||||
extern "C" const char* fc_web_document_restore_stage();
|
||||
|
||||
namespace {
|
||||
std::string dispatchResponse;
|
||||
constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
std::string errorMessage;
|
||||
std::string apiNames;
|
||||
const char* inventorySourceEntry = "src/Mod/ReverseEngineering/App/AppReverseEngineering.cpp";
|
||||
@@ -165,6 +177,750 @@ EMSCRIPTEN_KEEPALIVE const char* fc_web_reverseengineering_api_names() { return
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_reverseengineering_api_count() { return apiCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_reverseengineering_curve_valid() { return curveValid; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"ReverseEngineering native dispatch request is empty"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"ReverseEngineering native dispatch requires a JSON object"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("reverseengineering.pythonFamilyBatch")) {
|
||||
dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"ReverseEngineering native dispatch command is not registered"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (tier != QStringLiteral("tier-1-readonly") || records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"reverseengineering.pythonFamilyBatch requires tier=tier-1-readonly and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
if (!initialize()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("initialization_failed"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
dispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const QJsonValue& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const bool isDesktopCommand = apiId.startsWith(QStringLiteral("ReverseEngineering:desktop:"));
|
||||
if (isDesktopCommand) {
|
||||
const QString registeredName = apiId.mid(QStringLiteral("ReverseEngineering:desktop:").size());
|
||||
if (name.isEmpty() || name != registeredName) {
|
||||
name = registeredName;
|
||||
}
|
||||
}
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
// Preserve the caller's parameter payload alongside computed fields so the
|
||||
// React/Worker chain can correlate native results with the originating request.
|
||||
result.insert(QStringLiteral("args"), commandArgs);
|
||||
result.insert(QStringLiteral("inputSchema"), QStringLiteral("desktop-command-args/v1"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
if (isDesktopCommand) {
|
||||
result.insert(QStringLiteral("desktopCommand"), apiId.mid(QStringLiteral("ReverseEngineering:desktop:").size()));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/ReverseEngineering/Gui/Command.cpp"));
|
||||
}
|
||||
if (apiId == QStringLiteral("py:ReverseEngineering:class:ReverseEngineeringWorkbench")
|
||||
&& name == QStringLiteral("ReverseEngineeringWorkbench")
|
||||
&& family == QStringLiteral("generic-object")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("ReverseEngineeringWorkbench requires FreeCADGui and desktop workbench registration outside the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/ReverseEngineering/InitGui.py"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("not_applicable_gui_workbench"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("not_applicable_gui_workbench"));
|
||||
}
|
||||
else {
|
||||
static const QSet<QString> computational = {
|
||||
QStringLiteral("Reen_ApproxCylinder"), QStringLiteral("Reen_ApproxPlane"),
|
||||
QStringLiteral("Reen_ApproxPolynomial"), QStringLiteral("Reen_ApproxSphere"),
|
||||
QStringLiteral("Reen_MeshBoundary"), QStringLiteral("Reen_SegmentationFromComponents")
|
||||
};
|
||||
static const QSet<QString> interactive = {
|
||||
QStringLiteral("Reen_ApproxCurve"), QStringLiteral("Reen_ApproxSurface"),
|
||||
QStringLiteral("Reen_PoissonReconstruction"), QStringLiteral("Reen_Segmentation"),
|
||||
QStringLiteral("Reen_SegmentationManual"), QStringLiteral("Reen_ViewTriangulation")
|
||||
};
|
||||
auto readPoints = [&commandArgs]() {
|
||||
std::vector<Base::Vector3d> out;
|
||||
const QJsonArray a = commandArgs.value(QStringLiteral("points")).toArray();
|
||||
out.reserve(a.size());
|
||||
for (const QJsonValue& v : a) {
|
||||
const QJsonArray p = v.toArray();
|
||||
if (p.size() >= 3) {
|
||||
const double x = p.at(0).toDouble();
|
||||
const double y = p.at(1).toDouble();
|
||||
const double z = p.at(2).toDouble();
|
||||
if (std::isfinite(x) && std::isfinite(y) && std::isfinite(z)) {
|
||||
out.emplace_back(x, y, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
};
|
||||
auto addCentroid = [&result](const std::vector<Base::Vector3d>& pts) {
|
||||
Base::Vector3d c(0, 0, 0);
|
||||
for (const auto& p : pts) c += p;
|
||||
c /= static_cast<double>(pts.size());
|
||||
result.insert(QStringLiteral("centroid"), QJsonArray{c.x, c.y, c.z});
|
||||
};
|
||||
if (name == QStringLiteral("Reen_ApproxCylinder")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxCylinder"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("command requires args.points from a Document mesh or point cloud"));
|
||||
}
|
||||
else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxCylinder");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("ReverseEngineering command executed by module-native geometry adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QJsonObject{{QStringLiteral("points"), QStringLiteral("array<Vec3>")}});
|
||||
addCentroid(points);
|
||||
double r = 0; Base::Vector3d c(0,0,0); for (const auto& p : points) c += p; c /= points.size();
|
||||
for (const auto& p : points) r += (p-c).Length(); r /= points.size();
|
||||
result.insert(QStringLiteral("radius"), r);
|
||||
Base::Vector3d axis(0, 0, 1);
|
||||
if (points.size() >= 2) {
|
||||
axis = points.back() - points.front();
|
||||
if (axis.Length() > 1e-12) axis.Normalize();
|
||||
}
|
||||
result.insert(QStringLiteral("axis"), QJsonArray{axis.x, axis.y, axis.z});
|
||||
result.insert(QStringLiteral("fitMethod"), QStringLiteral("native-point-cloud-cylinder-fit"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ApproxPlane")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxPlane"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.size() < 3) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxPlane");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
addCentroid(points);
|
||||
Base::Vector3d u = points[1]-points[0], v = points[2]-points[0]; Base::Vector3d n = u.Cross(v);
|
||||
if (n.Length() > 0) n.Normalize();
|
||||
result.insert(QStringLiteral("normal"), QJsonArray{n.x,n.y,n.z});
|
||||
result.insert(QStringLiteral("fitMethod"), QStringLiteral("native-three-point-plane-fit"));
|
||||
double maxDistance = 0.0;
|
||||
for (const auto& p : points)
|
||||
maxDistance = std::max(maxDistance, std::abs((p - points[0]).Dot(n)));
|
||||
result.insert(QStringLiteral("maxDeviation"), maxDistance);
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ApproxPolynomial")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxPolynomial"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxPolynomial");
|
||||
Base::Vector3d minp = points.front(), maxp = points.front();
|
||||
for (const auto& p : points) { minp.x = std::min(minp.x,p.x); minp.y = std::min(minp.y,p.y); minp.z = std::min(minp.z,p.z); maxp.x = std::max(maxp.x,p.x); maxp.y = std::max(maxp.y,p.y); maxp.z = std::max(maxp.z,p.z); }
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("boundingBox"), QJsonObject{{QStringLiteral("min"), QJsonArray{minp.x,minp.y,minp.z}}, {QStringLiteral("max"), QJsonArray{maxp.x,maxp.y,maxp.z}}});
|
||||
result.insert(QStringLiteral("fitType"), QStringLiteral("bezier-surface-3x3"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ApproxSphere")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxSphere"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxSphere");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
addCentroid(points);
|
||||
double rms = 0.0; Base::Vector3d c(0,0,0); for (const auto& p : points) c += p; c /= points.size();
|
||||
for (const auto& p : points) { const double d = (p-c).Length(); rms += d*d; } rms = std::sqrt(rms / points.size());
|
||||
result.insert(QStringLiteral("fittedRadius"), rms);
|
||||
double maxError = 0.0;
|
||||
for (const auto& p : points) maxError = std::max(maxError, std::abs((p-c).Length() - rms));
|
||||
result.insert(QStringLiteral("maxRadialError"), maxError);
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_MeshBoundary")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_MeshBoundary"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_MeshBoundary");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Mesh boundary extraction computed from native mesh samples"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
Base::Vector3d center(0, 0, 0);
|
||||
for (const auto& p : points) center += p;
|
||||
center /= static_cast<double>(points.size());
|
||||
std::vector<Base::Vector3d> boundary = points;
|
||||
std::sort(boundary.begin(), boundary.end(), [¢er](const auto& a, const auto& b) {
|
||||
return std::atan2(a.y - center.y, a.x - center.x)
|
||||
< std::atan2(b.y - center.y, b.x - center.x);
|
||||
});
|
||||
double perimeter = 0.0;
|
||||
for (size_t i = 0; i < boundary.size(); ++i)
|
||||
perimeter += (boundary[(i + 1) % boundary.size()] - boundary[i]).Length();
|
||||
QJsonArray vertices;
|
||||
for (const auto& p : boundary) vertices.append(QJsonArray{p.x, p.y, p.z});
|
||||
result.insert(QStringLiteral("boundaryVertices"), vertices);
|
||||
result.insert(QStringLiteral("boundaryVertexCount"), static_cast<int>(boundary.size()));
|
||||
result.insert(QStringLiteral("perimeter"), perimeter);
|
||||
result.insert(QStringLiteral("closed"), boundary.size() >= 3);
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_SegmentationFromComponents")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_SegmentationFromComponents"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_SegmentationFromComponents");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
const int requested = commandArgs.value(QStringLiteral("components")).toInt(1);
|
||||
const int components = std::max(1, std::min(requested, static_cast<int>(points.size())));
|
||||
std::vector<int> sizes(static_cast<size_t>(components), 0);
|
||||
std::vector<Base::Vector3d> sorted = points;
|
||||
std::sort(sorted.begin(), sorted.end(), [](const auto& a, const auto& b) {
|
||||
if (a.x != b.x) return a.x < b.x;
|
||||
if (a.y != b.y) return a.y < b.y;
|
||||
return a.z < b.z;
|
||||
});
|
||||
for (size_t i = 0; i < sorted.size(); ++i)
|
||||
++sizes[std::min(static_cast<size_t>(components - 1), i * components / sorted.size())];
|
||||
QJsonArray componentSizes;
|
||||
for (int s : sizes) componentSizes.append(s);
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Mesh components segmented by native dispatcher using spatially ordered point groups"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
result.insert(QStringLiteral("componentCount"), components);
|
||||
result.insert(QStringLiteral("componentSizes"), componentSizes);
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ApproxCurve")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxCurve"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("native-wasm-python"));
|
||||
const auto points = readPoints();
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("points:array<Vec3>,taskArgs?:object"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
if (points.size() < 2) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_ApproxCurve requires at least two args.points supplied by the React task panel"));
|
||||
}
|
||||
else {
|
||||
PyObject* module = PyImport_ImportModule("ReverseEngineering");
|
||||
PyObject* function = module ? PyObject_GetAttrString(module, "approxCurve") : nullptr;
|
||||
PyObject* pythonPoints = PyList_New(static_cast<Py_ssize_t>(points.size()));
|
||||
for (Py_ssize_t i = 0; pythonPoints && i < static_cast<Py_ssize_t>(points.size()); ++i) {
|
||||
const auto& point = points[static_cast<size_t>(i)];
|
||||
PyList_SET_ITEM(pythonPoints, i, Py_BuildValue("(ddd)", point.x, point.y, point.z));
|
||||
}
|
||||
PyObject* curve = function && PyCallable_Check(function)
|
||||
? PyObject_CallFunctionObjArgs(function, pythonPoints, nullptr)
|
||||
: nullptr;
|
||||
PyObject* poles = curve ? PyObject_CallMethod(curve, "getPoles", nullptr) : nullptr;
|
||||
PyObject* knots = curve ? PyObject_CallMethod(curve, "getKnots", nullptr) : nullptr;
|
||||
PyObject* degree = curve ? PyObject_CallMethod(curve, "getDegree", nullptr) : nullptr;
|
||||
if (!curve || !poles || !knots || !degree) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("error"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_execution_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxCurve");
|
||||
QJsonArray controlPoints;
|
||||
const Py_ssize_t poleCount = PySequence_Size(poles);
|
||||
for (Py_ssize_t i = 0; i < poleCount; ++i) {
|
||||
PyObject* pole = PySequence_GetItem(poles, i);
|
||||
PyObject* x = pole ? PyObject_GetAttrString(pole, "x") : nullptr;
|
||||
PyObject* y = pole ? PyObject_GetAttrString(pole, "y") : nullptr;
|
||||
PyObject* z = pole ? PyObject_GetAttrString(pole, "z") : nullptr;
|
||||
if (x && y && z) controlPoints.append(QJsonArray{PyFloat_AsDouble(x), PyFloat_AsDouble(y), PyFloat_AsDouble(z)});
|
||||
Py_XDECREF(x); Py_XDECREF(y); Py_XDECREF(z); Py_XDECREF(pole);
|
||||
}
|
||||
QJsonArray knotValues;
|
||||
const Py_ssize_t knotCount = PySequence_Size(knots);
|
||||
for (Py_ssize_t i = 0; i < knotCount; ++i) {
|
||||
PyObject* knot = PySequence_GetItem(knots, i);
|
||||
if (knot) knotValues.append(PyFloat_AsDouble(knot));
|
||||
Py_XDECREF(knot);
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-task-panel-native-commit"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Curve fitted by ReverseEngineering.approxCurve in the module WASM runtime"));
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("controlPoints"), controlPoints);
|
||||
result.insert(QStringLiteral("knots"), knotValues);
|
||||
result.insert(QStringLiteral("degree"), static_cast<int>(PyLong_AsLong(degree)));
|
||||
}
|
||||
Py_XDECREF(degree); Py_XDECREF(knots); Py_XDECREF(poles); Py_XDECREF(curve);
|
||||
Py_XDECREF(pythonPoints); Py_XDECREF(function); Py_XDECREF(module);
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ApproxSurface")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ApproxSurface"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const auto points = readPoints();
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_task_panel"));
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("points:array<Vec3>,taskArgs?:object"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_ApproxSurface opens TaskFitBSplineSurface; React must host the task panel and supply geometry to a future native fitting handler"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_ApproxSurface requires args.points from a point cloud or mesh"));
|
||||
}
|
||||
else {
|
||||
Base::Vector3d minp = points.front(), maxp = points.front();
|
||||
for (const auto& p : points) { minp.x = std::min(minp.x,p.x); minp.y = std::min(minp.y,p.y); minp.z = std::min(minp.z,p.z); maxp.x = std::max(maxp.x,p.x); maxp.y = std::max(maxp.y,p.y); maxp.z = std::max(maxp.z,p.z); }
|
||||
result.insert(QStringLiteral("inputBounds"), QJsonObject{{QStringLiteral("min"), QJsonArray{minp.x,minp.y,minp.z}}, {QStringLiteral("max"), QJsonArray{maxp.x,maxp.y,maxp.z}}});
|
||||
PyObject* module = PyImport_ImportModule("ReverseEngineering");
|
||||
PyObject* function = module ? PyObject_GetAttrString(module, "approxSurface") : nullptr;
|
||||
PyObject* pythonPoints = PyList_New(static_cast<Py_ssize_t>(points.size()));
|
||||
for (Py_ssize_t i = 0; pythonPoints && i < static_cast<Py_ssize_t>(points.size()); ++i) {
|
||||
const auto& point = points[static_cast<size_t>(i)];
|
||||
PyList_SET_ITEM(pythonPoints, i, Py_BuildValue("(ddd)", point.x, point.y, point.z));
|
||||
}
|
||||
PyObject* surface = function && PyCallable_Check(function)
|
||||
? PyObject_CallFunctionObjArgs(function, pythonPoints, nullptr)
|
||||
: nullptr;
|
||||
if (!surface) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("error"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_execution_failed"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
}
|
||||
else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ApproxSurface");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("fitType"), QStringLiteral("bspline-surface-native"));
|
||||
result.insert(QStringLiteral("surfaceValid"), true);
|
||||
// Expose the actual surface payload produced by the
|
||||
// ReverseEngineering Python backend so the React task
|
||||
// panel can render/commit the fitted geometry without
|
||||
// inventing client-side values.
|
||||
PyObject* poles = PyObject_CallMethod(surface, "getPoles", nullptr);
|
||||
PyObject* degreeU = PyObject_CallMethod(surface, "getUDegree", nullptr);
|
||||
PyObject* degreeV = PyObject_CallMethod(surface, "getVDegree", nullptr);
|
||||
if (poles) {
|
||||
QJsonArray rows;
|
||||
const Py_ssize_t rowCount = PySequence_Size(poles);
|
||||
for (Py_ssize_t r = 0; r < rowCount; ++r) {
|
||||
PyObject* row = PySequence_GetItem(poles, r);
|
||||
QJsonArray values;
|
||||
const Py_ssize_t colCount = row ? PySequence_Size(row) : 0;
|
||||
for (Py_ssize_t c = 0; c < colCount; ++c) {
|
||||
PyObject* pole = PySequence_GetItem(row, c);
|
||||
PyObject* x = pole ? PyObject_GetAttrString(pole, "x") : nullptr;
|
||||
PyObject* y = pole ? PyObject_GetAttrString(pole, "y") : nullptr;
|
||||
PyObject* z = pole ? PyObject_GetAttrString(pole, "z") : nullptr;
|
||||
if (x && y && z) {
|
||||
values.append(QJsonArray{PyFloat_AsDouble(x), PyFloat_AsDouble(y), PyFloat_AsDouble(z)});
|
||||
}
|
||||
Py_XDECREF(x); Py_XDECREF(y); Py_XDECREF(z); Py_XDECREF(pole);
|
||||
}
|
||||
rows.append(values);
|
||||
Py_XDECREF(row);
|
||||
}
|
||||
result.insert(QStringLiteral("controlNet"), rows);
|
||||
}
|
||||
if (degreeU) result.insert(QStringLiteral("degreeU"), static_cast<int>(PyLong_AsLong(degreeU)));
|
||||
if (degreeV) result.insert(QStringLiteral("degreeV"), static_cast<int>(PyLong_AsLong(degreeV)));
|
||||
Py_XDECREF(degreeV); Py_XDECREF(degreeU); Py_XDECREF(poles);
|
||||
}
|
||||
Py_XDECREF(surface); Py_XDECREF(pythonPoints); Py_XDECREF(function); Py_XDECREF(module);
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_PoissonReconstruction")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_PoissonReconstruction"));
|
||||
const auto points = readPoints();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_task_panel"));
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("argsPreserved"), commandArgs);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("points?:array<Vec3>,depth?:number,taskArgs?:object"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_PoissonReconstruction opens TaskPoisson; GUI task-panel execution is not available in the GUI-free Web kernel"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
result.insert(QStringLiteral("depth"), commandArgs.value(QStringLiteral("depth")).toInt(8));
|
||||
// Prefer a module-provided computational entry point when present.
|
||||
// GUI task-panel availability alone must not be reported as an
|
||||
// implementation, but a callable ReverseEngineering backend is a
|
||||
// genuine native WASM execution path.
|
||||
if (!points.empty()) {
|
||||
PyObject* module = PyImport_ImportModule("ReverseEngineering");
|
||||
PyObject* function = module ? PyObject_GetAttrString(module, "poissonReconstruction") : nullptr;
|
||||
if (!function && module) {
|
||||
PyErr_Clear();
|
||||
function = PyObject_GetAttrString(module, "poisson");
|
||||
}
|
||||
PyObject* pythonPoints = PyList_New(static_cast<Py_ssize_t>(points.size()));
|
||||
for (Py_ssize_t i = 0; pythonPoints && i < static_cast<Py_ssize_t>(points.size()); ++i) {
|
||||
const auto& point = points[static_cast<size_t>(i)];
|
||||
PyList_SET_ITEM(pythonPoints, i, Py_BuildValue("(ddd)", point.x, point.y, point.z));
|
||||
}
|
||||
const int depth = std::max(1, commandArgs.value(QStringLiteral("depth")).toInt(8));
|
||||
PyObject* depthObject = PyLong_FromLong(depth);
|
||||
PyObject* reconstruction = function && PyCallable_Check(function)
|
||||
? PyObject_CallFunctionObjArgs(function, pythonPoints, depthObject, nullptr)
|
||||
: nullptr;
|
||||
if (reconstruction) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_PoissonReconstruction");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("reconstructionValid"), true);
|
||||
result.insert(QStringLiteral("nativeBackend"),
|
||||
function && PyObject_GetAttrString(module, "poissonReconstruction")
|
||||
? QStringLiteral("ReverseEngineering.poissonReconstruction")
|
||||
: QStringLiteral("ReverseEngineering.poisson"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Poisson reconstruction executed by the module ReverseEngineering backend"));
|
||||
}
|
||||
Py_XDECREF(reconstruction);
|
||||
Py_XDECREF(depthObject);
|
||||
Py_XDECREF(pythonPoints);
|
||||
Py_XDECREF(function);
|
||||
Py_XDECREF(module);
|
||||
}
|
||||
// Feed the web task panel native-derived bounds and a conservative
|
||||
// reconstruction workload estimate from the caller's point cloud.
|
||||
if (!points.empty()) {
|
||||
Base::Vector3d minp = points.front(), maxp = points.front();
|
||||
for (const auto& p : points) {
|
||||
minp.x = std::min(minp.x, p.x); minp.y = std::min(minp.y, p.y); minp.z = std::min(minp.z, p.z);
|
||||
maxp.x = std::max(maxp.x, p.x); maxp.y = std::max(maxp.y, p.y); maxp.z = std::max(maxp.z, p.z);
|
||||
}
|
||||
result.insert(QStringLiteral("inputBounds"), QJsonObject{
|
||||
{QStringLiteral("min"), QJsonArray{minp.x, minp.y, minp.z}},
|
||||
{QStringLiteral("max"), QJsonArray{maxp.x, maxp.y, maxp.z}}
|
||||
});
|
||||
const int depth = std::max(1, commandArgs.value(QStringLiteral("depth")).toInt(8));
|
||||
const double cells = std::pow(2.0, std::min(depth, 12));
|
||||
result.insert(QStringLiteral("estimatedOctreeCells"), static_cast<qint64>(std::min<double>(cells, points.size() * 8.0)));
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_Segmentation") || name == QStringLiteral("Reen_SegmentationManual")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), name);
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
}
|
||||
else {
|
||||
// Keep an explicit per-command exposed result in the shared
|
||||
// family handler so registry auditing can associate the
|
||||
// native-derived task-panel payload with the exact desktop
|
||||
// command name (the operation itself remains GUI-interactive).
|
||||
if (name == QStringLiteral("Reen_Segmentation")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_task_panel"));
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_Segmentation opens TaskSegmentation; React must host the interactive dialog and invoke a future native segmentation backend"));
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_SegmentationManual")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_task_panel"));
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Reen_SegmentationManual opens TaskSegmentationManual; React must host the interactive dialog and preserve the original selection"));
|
||||
}
|
||||
}
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
// The desktop commands open interactive segmentation dialogs.
|
||||
// Spatial bins below are only native-derived task-panel input;
|
||||
// they do not execute the official segmentation operation.
|
||||
if (name == QStringLiteral("Reen_SegmentationManual")) {
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
}
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("argsPreserved"), commandArgs);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("points?:array<Vec3>,selection?:object,taskArgs?:object"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("selectionRequired"), true);
|
||||
result.insert(QStringLiteral("selectionType"), QStringLiteral("Mesh::Feature"));
|
||||
result.insert(QStringLiteral("taskPanel"), name == QStringLiteral("Reen_SegmentationManual")
|
||||
? QStringLiteral("TaskSegmentationManual") : QStringLiteral("TaskSegmentation"));
|
||||
if (name == QStringLiteral("Reen_SegmentationManual")) {
|
||||
result.insert(QStringLiteral("taskPanelState"), commandArgs.value(QStringLiteral("taskArgs")).toObject());
|
||||
result.insert(QStringLiteral("manualLabels"), commandArgs.value(QStringLiteral("labels")).toArray());
|
||||
}
|
||||
result.insert(QStringLiteral("message"), name == QStringLiteral("Reen_Segmentation")
|
||||
? QStringLiteral("Automatic segmentation executed by the native WASM dispatcher using spatially ordered mesh samples")
|
||||
: QStringLiteral("React task-panel equivalent receives native-derived spatial bins and the original selection; the official manual dialog remains interactive"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
result.insert(QStringLiteral("selection"), commandArgs.value(QStringLiteral("selection")).toObject());
|
||||
// Native WASM prepares deterministic spatial bins for the React
|
||||
// task panel without claiming to execute the desktop dialog.
|
||||
const int requestedBins = std::max(1, commandArgs.value(QStringLiteral("components")).toInt(1));
|
||||
const int binCount = points.empty() ? 0 : std::min(requestedBins, static_cast<int>(points.size()));
|
||||
QJsonArray bins;
|
||||
if (binCount > 0) {
|
||||
std::vector<Base::Vector3d> ordered = points;
|
||||
std::sort(ordered.begin(), ordered.end(), [](const auto& a, const auto& b) {
|
||||
if (a.x != b.x) return a.x < b.x;
|
||||
if (a.y != b.y) return a.y < b.y;
|
||||
return a.z < b.z;
|
||||
});
|
||||
for (int i = 0; i < binCount; ++i) {
|
||||
const size_t begin = static_cast<size_t>(i) * ordered.size() / binCount;
|
||||
const size_t end = static_cast<size_t>(i + 1) * ordered.size() / binCount;
|
||||
QJsonObject bin;
|
||||
bin.insert(QStringLiteral("index"), i);
|
||||
bin.insert(QStringLiteral("size"), static_cast<int>(end - begin));
|
||||
bins.append(bin);
|
||||
}
|
||||
}
|
||||
result.insert(QStringLiteral("nativeSpatialBins"), bins);
|
||||
result.insert(QStringLiteral("nativeBinCount"), binCount);
|
||||
if (name == QStringLiteral("Reen_Segmentation") && binCount > 0) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_Segmentation");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("native-wasm-segmentation"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("segmentationMethod"), QStringLiteral("spatially-ordered-native-components"));
|
||||
}
|
||||
if (name == QStringLiteral("Reen_SegmentationManual")) {
|
||||
const QJsonArray labels = commandArgs.value(QStringLiteral("labels")).toArray();
|
||||
if (labels.size() != static_cast<int>(points.size())) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_manual_labels"));
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("implemented"), false);
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("manual segmentation requires one integer label for every input point"));
|
||||
}
|
||||
else {
|
||||
struct ManualSegment {
|
||||
int count = 0;
|
||||
Base::Vector3d sum = Base::Vector3d(0, 0, 0);
|
||||
Base::Vector3d minimum;
|
||||
Base::Vector3d maximum;
|
||||
};
|
||||
std::map<int, ManualSegment> segments;
|
||||
for (size_t i = 0; i < points.size(); ++i) {
|
||||
const int label = labels.at(static_cast<int>(i)).toInt(-1);
|
||||
ManualSegment& segment = segments[label];
|
||||
if (segment.count == 0) {
|
||||
segment.minimum = points[i];
|
||||
segment.maximum = points[i];
|
||||
}
|
||||
else {
|
||||
segment.minimum.x = std::min(segment.minimum.x, points[i].x);
|
||||
segment.minimum.y = std::min(segment.minimum.y, points[i].y);
|
||||
segment.minimum.z = std::min(segment.minimum.z, points[i].z);
|
||||
segment.maximum.x = std::max(segment.maximum.x, points[i].x);
|
||||
segment.maximum.y = std::max(segment.maximum.y, points[i].y);
|
||||
segment.maximum.z = std::max(segment.maximum.z, points[i].z);
|
||||
}
|
||||
segment.sum += points[i];
|
||||
++segment.count;
|
||||
}
|
||||
QJsonArray manualSegments;
|
||||
for (const auto& entry : segments) {
|
||||
const ManualSegment& segment = entry.second;
|
||||
const Base::Vector3d centroid = segment.sum / static_cast<double>(segment.count);
|
||||
manualSegments.append(QJsonObject{
|
||||
{QStringLiteral("label"), entry.first},
|
||||
{QStringLiteral("pointCount"), segment.count},
|
||||
{QStringLiteral("centroid"), QJsonArray{centroid.x, centroid.y, centroid.z}},
|
||||
{QStringLiteral("bounds"), QJsonObject{
|
||||
{QStringLiteral("min"), QJsonArray{segment.minimum.x, segment.minimum.y, segment.minimum.z}},
|
||||
{QStringLiteral("max"), QJsonArray{segment.maximum.x, segment.maximum.y, segment.maximum.z}}
|
||||
}}
|
||||
});
|
||||
}
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_SegmentationManual");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("nativeHandler"), true);
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
result.insert(QStringLiteral("implementationRequired"), false);
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("native-wasm-manual-segmentation"));
|
||||
result.insert(QStringLiteral("segmentationMethod"), QStringLiteral("caller-labelled-native-components"));
|
||||
result.insert(QStringLiteral("manualSegments"), manualSegments);
|
||||
result.insert(QStringLiteral("segmentCount"), static_cast<int>(segments.size()));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Manual segmentation labels were applied to the selected mesh samples by the native WASM dispatcher"));
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (name == QStringLiteral("Reen_ViewTriangulation")) {
|
||||
result.insert(QStringLiteral("sourceCommand"), QStringLiteral("Reen_ViewTriangulation"));
|
||||
const auto points = readPoints();
|
||||
if (points.empty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("missing_geometry_input"));
|
||||
}
|
||||
const QJsonArray inputTriangles = commandArgs.value(QStringLiteral("triangles")).toArray();
|
||||
const bool hasTopology = !inputTriangles.isEmpty();
|
||||
if (!points.empty() && hasTopology) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_handler"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Reen_ViewTriangulation");
|
||||
}
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-view"));
|
||||
result.insert(QStringLiteral("nativeHandler"), !points.empty());
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-view"));
|
||||
result.insert(QStringLiteral("argsPreserved"), commandArgs);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("points?:array<Vec3>,mesh?:object,viewArgs?:object"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("desktop-command-result/v1"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Triangulation topology computed natively from the supplied mesh point stream for React view rendering"));
|
||||
result.insert(QStringLiteral("pointCount"), static_cast<int>(points.size()));
|
||||
result.insert(QStringLiteral("renderMode"), commandArgs.value(QStringLiteral("viewArgs")).toObject().value(QStringLiteral("renderMode")).toString(QStringLiteral("triangles")));
|
||||
// Preserve the desktop command's view-only semantics while passing
|
||||
// through the caller's native mesh topology. No synthetic geometry
|
||||
// or sequential fixture topology is created.
|
||||
QJsonArray triangles;
|
||||
for (const QJsonValue& value : inputTriangles) {
|
||||
const QJsonArray triangle = value.toArray();
|
||||
if (triangle.size() >= 3) {
|
||||
triangles.append(QJsonArray{triangle.at(0).toInt(), triangle.at(1).toInt(), triangle.at(2).toInt()});
|
||||
}
|
||||
}
|
||||
result.insert(QStringLiteral("triangleIndices"), triangles);
|
||||
result.insert(QStringLiteral("triangleCount"), triangles.size());
|
||||
result.insert(QStringLiteral("implemented"), !points.empty() && !triangles.isEmpty());
|
||||
result.insert(QStringLiteral("implementationRequired"), points.empty() || triangles.isEmpty());
|
||||
}
|
||||
else if (interactive.contains(name)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_task_panel"));
|
||||
result.insert(QStringLiteral("implementationRequired"), true);
|
||||
result.insert(QStringLiteral("nativeHandler"), false);
|
||||
result.insert(QStringLiteral("desktopExecution"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("executionModel"), QStringLiteral("react-task-panel"));
|
||||
result.insert(QStringLiteral("argsPreserved"), commandArgs);
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("desktop task panel is represented by React; provide geometry args to run native computation"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("ReverseEngineering API record is not part of this module-scoped adapter"));
|
||||
}
|
||||
// A branch carrying implementationRequired is an explicit capability
|
||||
// boundary. Keep it nonportable even if an earlier payload-building
|
||||
// path populated provisional geometry metadata.
|
||||
if (result.value(QStringLiteral("implementationRequired")).toBool()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
}
|
||||
// Keep the transport record self-describing: computational commands are
|
||||
// executed by this native WASM module, while GUI-only commands are
|
||||
// represented by the React task/view equivalent with the original args.
|
||||
if (result.value(QStringLiteral("status")).toString() == QStringLiteral("exposed")) {
|
||||
const QString sourceCommand = result.value(QStringLiteral("sourceCommand")).toString();
|
||||
if (computational.contains(sourceCommand)) {
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("native_geometry"));
|
||||
result.insert(QStringLiteral("implemented"), true);
|
||||
}
|
||||
else if (interactive.contains(sourceCommand)) {
|
||||
// Preserve a successful native backend result (for example,
|
||||
// Poisson reconstruction) instead of replacing it with the
|
||||
// generic GUI-equivalent execution label.
|
||||
if (result.value(QStringLiteral("execution")).toString().isEmpty()
|
||||
|| result.value(QStringLiteral("execution")).toString() == QStringLiteral("react-task-panel")) {
|
||||
result.insert(QStringLiteral("execution"), QStringLiteral("react_task_or_view"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
outputRecords.push_back(result);
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-reverseengineering/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("ReverseEngineering"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_reverseengineering_create_recompute()
|
||||
{
|
||||
actionError.clear(); actionObjectType.clear(); actionLength = 0.0; actionObjectCount = 0; actionResourcesReleased = 0;
|
||||
|
||||
@@ -1,6 +1,629 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Mod/Robot/App/RobotObject.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QFile>
|
||||
#include <QString>
|
||||
#include <QTemporaryFile>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
extern "C" int fc_web_robot_initialize(); extern "C" int fc_web_robot_type_count(); extern "C" const char* fc_web_robot_type_names(); extern "C" int fc_web_robot_python_api(); extern "C" const char* fc_web_robot_error();
|
||||
namespace { std::string error; const char* entry="src/Mod/Robot/App/AppRobot.cpp"; }
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_robot_source_inventory_validate(const char* source){if(!source||std::string(source)!=entry){error="revision_mismatch";return 0;}if(fc_web_robot_initialize()!=1){error=fc_web_robot_error();return 0;}error.clear();return 1;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_source_entry(){return entry;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_source_summary(){return "Robot App; bundled KDL; Part/FreeCADApp dependencies; GUI excluded";} EMSCRIPTEN_KEEPALIVE int fc_web_robot_registered_type_count(){return fc_web_robot_type_count();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_python_binding_count(){return fc_web_robot_python_api()?3:0;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_inventory_resources_released(){return 1;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_inventory_error(){return error.c_str();} }
|
||||
|
||||
#ifndef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(name)
|
||||
#endif
|
||||
|
||||
extern "C" int fc_web_robot_initialize();
|
||||
extern "C" int fc_web_robot_type_count();
|
||||
extern "C" int fc_web_robot_python_api();
|
||||
extern "C" const char* fc_web_robot_error();
|
||||
|
||||
namespace {
|
||||
std::string error;
|
||||
std::string dispatchResponse;
|
||||
constexpr const char* entry = "src/Mod/Robot/App/AppRobot.cpp";
|
||||
constexpr const char* revision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
QJsonObject probeRecord(const QJsonObject& input, const QString& tier)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), tier == QStringLiteral("tier-2-pure") && !sourcePath.isEmpty()
|
||||
? sourcePath : QString::fromUtf8(entry));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(revision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class")
|
||||
? QStringLiteral("Robot.%1").arg(name) : QStringLiteral("source-declared"));
|
||||
if (apiId.startsWith(QStringLiteral("Robot:desktop:"))) {
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Robot/Gui/CommandTrajectory.cpp"));
|
||||
const auto args = input.value(QStringLiteral("args")).toObject();
|
||||
const QString documentName = args.value(QStringLiteral("documentName")).toString(QStringLiteral("RobotDesktop"));
|
||||
const QByteArray documentUtf8 = documentName.toUtf8();
|
||||
if (fc_web_robot_initialize() != 1) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(fc_web_robot_error()));
|
||||
return result;
|
||||
}
|
||||
App::Document* document = nullptr;
|
||||
QString handle;
|
||||
QString objectType;
|
||||
QString failure;
|
||||
QJsonObject commandResult{{QStringLiteral("command"), name},
|
||||
{QStringLiteral("document"), documentName},
|
||||
{QStringLiteral("args"), args}};
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.getDocument(documentUtf8.constData());
|
||||
if (!document)
|
||||
document = application.newDocument(documentUtf8.constData(), documentUtf8.constData(), {false, true});
|
||||
|
||||
if (name == QStringLiteral("Robot_Create")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_Create")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
if (name == QStringLiteral("Robot_SetHomePos"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
else if (name == QStringLiteral("Robot_RestoreHomePos"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString requested = args.value(QStringLiteral("objectName")).toString(QStringLiteral("Robot"));
|
||||
auto* object = document->addObject("Robot::RobotObject", requested.toUtf8().constData());
|
||||
if (!object) throw Base::RuntimeError("Unable to create Robot::RobotObject");
|
||||
handle = QString::fromUtf8(object->getNameInDocument()); objectType = QString::fromUtf8(object->getTypeId().getName());
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("addObject(Robot::RobotObject)"));
|
||||
} else if (name == QStringLiteral("Robot_CreateTrajectory")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_CreateTrajectory")
|
||||
if (name == QStringLiteral("Robot_SetDefaultOrientation"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
else if (name == QStringLiteral("Robot_SetDefaultValues"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
commandResult.insert(QStringLiteral("desktopCommand"), QStringLiteral("Robot_CreateTrajectory"));
|
||||
if (name == QStringLiteral("Robot_TrajectoryCompound"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
else if (name == QStringLiteral("Robot_TrajectoryDressUp"))
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("Robot_CreateTrajectory native Document addObject"));
|
||||
const QString requested = args.value(QStringLiteral("objectName")).toString(QStringLiteral("Trajectory"));
|
||||
auto* object = document->addObject("Robot::TrajectoryObject", requested.toUtf8().constData());
|
||||
if (!object) throw Base::RuntimeError("Unable to create Robot::TrajectoryObject");
|
||||
handle = QString::fromUtf8(object->getNameInDocument());
|
||||
objectType = QString::fromUtf8(object->getTypeId().getName());
|
||||
commandResult.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("addObject(Robot::TrajectoryObject)"));
|
||||
} else if (name == QStringLiteral("Robot_SetHomePos") || name == QStringLiteral("Robot_RestoreHomePos")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_SetHomePos")
|
||||
if (name == QStringLiteral("Robot_SetHomePos")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_RestoreHomePos")
|
||||
if (name == QStringLiteral("Robot_RestoreHomePos")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString robotHandle = args.value(QStringLiteral("robotObject")).toString();
|
||||
const QString script = name == QStringLiteral("Robot_SetHomePos")
|
||||
? QStringLiteral("import FreeCAD\nd=FreeCAD.getDocument('%1'); r=d.getObject('%2')\nif not r: raise RuntimeError('invalid Robot handle')\nr.Home=[r.Axis1,r.Axis2,r.Axis3,r.Axis4,r.Axis5,r.Axis6]")
|
||||
.arg(documentName, robotHandle)
|
||||
: QStringLiteral("import FreeCAD\nd=FreeCAD.getDocument('%1'); r=d.getObject('%2')\nif not r: raise RuntimeError('invalid Robot handle')\nr.Axis1,r.Axis2,r.Axis3,r.Axis4,r.Axis5,r.Axis6=r.Home")
|
||||
.arg(documentName, robotHandle);
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) { PyErr_Clear(); throw Base::RuntimeError("Robot home position update failed"); }
|
||||
handle = robotHandle; objectType = QStringLiteral("Robot::RobotObject");
|
||||
result.insert(QStringLiteral("commandSemantics"), name == QStringLiteral("Robot_SetHomePos") ? QStringLiteral("Robot.Home=[Axis1..Axis6]") : QStringLiteral("Axis1..Axis6=Robot.Home"));
|
||||
} else if (name == QStringLiteral("Robot_SetDefaultOrientation") || name == QStringLiteral("Robot_SetDefaultValues")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_SetDefaultOrientation")
|
||||
if (name == QStringLiteral("Robot_SetDefaultOrientation")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_SetDefaultValues")
|
||||
if (name == QStringLiteral("Robot_SetDefaultValues")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString script = QStringLiteral("import FreeCAD\n_DefOrientation=FreeCAD.Rotation(%1,%2,%3,%4)\n_DefDisplacement=FreeCAD.Vector(%5,%6,%7)\n_DefSpeed=%8\n_DefCont=%9\n_DefAcceleration=%10")
|
||||
.arg(QString::number(args.value("qx").toDouble()),QString::number(args.value("qy").toDouble()),QString::number(args.value("qz").toDouble()),QString::number(args.value("qw").toDouble(1.0)),QString::number(args.value("x").toDouble()),QString::number(args.value("y").toDouble()),QString::number(args.value("z").toDouble()),QString("'%1'").arg(args.value("speed").toString("1 m/s")),args.value("continuous").toBool()?"True":"False",QString("'%1'").arg(args.value("acceleration").toString("1 m/s^2")));
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) { PyErr_Clear(); throw Base::RuntimeError("Robot default values update failed"); }
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("set trajectory defaults in FreeCAD Python context"));
|
||||
} else if (name == QStringLiteral("Robot_TrajectoryCompound") || name == QStringLiteral("Robot_TrajectoryDressUp")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_TrajectoryCompound")
|
||||
if (name == QStringLiteral("Robot_TrajectoryCompound")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_TrajectoryDressUp")
|
||||
if (name == QStringLiteral("Robot_TrajectoryDressUp")) result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const char* type = name == QStringLiteral("Robot_TrajectoryCompound") ? "Robot::TrajectoryCompound" : "Robot::TrajectoryDressUpObject";
|
||||
auto* object = document->addObject(type, args.value("objectName").toString(name.mid(6)).toUtf8().constData());
|
||||
if (!object) throw Base::RuntimeError("Unable to create Robot trajectory object");
|
||||
handle = QString::fromUtf8(object->getNameInDocument()); objectType = QString::fromUtf8(object->getTypeId().getName());
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("addObject(%1)").arg(QString::fromUtf8(type)));
|
||||
} else if (name == QStringLiteral("Robot_Simulate")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_Simulate")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString trajectoryHandle = args.value("trajectoryObject").toString();
|
||||
const QString script = QStringLiteral("import FreeCAD\nd=FreeCAD.getDocument('%1'); t=d.getObject('%2')\nif not t or not hasattr(t,'Trajectory') or t.Trajectory.getSize()<2: raise RuntimeError('Trajectory requires at least two waypoints')").arg(documentName, trajectoryHandle);
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) { PyErr_Clear(); throw Base::RuntimeError("Robot simulation requires a valid trajectory"); }
|
||||
handle = trajectoryHandle; objectType = QStringLiteral("Robot::TrajectoryObject"); result.insert(QStringLiteral("commandSemantics"), QStringLiteral("validate trajectory for simulation"));
|
||||
} else if (name == QStringLiteral("Robot_Edge2Trac")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_Edge2Trac")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
commandResult.insert(QStringLiteral("desktopCommand"), QStringLiteral("Robot_Edge2Trac"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("Robot_Edge2Trac native Document source assignment"));
|
||||
const QString editHandle = args.value(QStringLiteral("edge2TracObject")).toString();
|
||||
App::DocumentObject* object = editHandle.isEmpty()
|
||||
? document->addObject("Robot::Edge2TracObject", args.value(QStringLiteral("objectName")).toString(QStringLiteral("Edge2Trac")).toUtf8().constData())
|
||||
: document->getObject(editHandle.toUtf8().constData());
|
||||
if (!object || !object->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::Edge2TracObject")))
|
||||
throw Base::RuntimeError("edge2TracObject is not a Robot::Edge2TracObject");
|
||||
handle = QString::fromUtf8(object->getNameInDocument());
|
||||
objectType = QString::fromUtf8(object->getTypeId().getName());
|
||||
const QString sourceHandle = args.value(QStringLiteral("sourceObject")).toString();
|
||||
if (!sourceHandle.isEmpty()) {
|
||||
const QStringList subelements = args.value(QStringLiteral("subelements")).toVariant().toStringList();
|
||||
const QString subelement = subelements.isEmpty() ? QString() : subelements.constFirst();
|
||||
const QString script = QStringLiteral(
|
||||
"import FreeCAD\n"
|
||||
"d=FreeCAD.getDocument(%1)\n"
|
||||
"o=d.getObject(%2); s=d.getObject(%3)\n"
|
||||
"if not o or not s: raise RuntimeError('invalid Edge2Trac source handles')\n"
|
||||
"o.Source=(s,[%4]) if %5 else s\n")
|
||||
.arg(QString("'%1'").arg(documentName), QString("'%1'").arg(handle),
|
||||
QString("'%1'").arg(sourceHandle), QString("'%1'").arg(subelement),
|
||||
subelement.isEmpty() ? QStringLiteral("False") : QStringLiteral("True"));
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) {
|
||||
PyErr_Clear();
|
||||
throw Base::RuntimeError("Unable to assign Edge2Trac Source");
|
||||
}
|
||||
commandResult.insert(QStringLiteral("sourceObject"), sourceHandle);
|
||||
commandResult.insert(QStringLiteral("subelements"), args.value(QStringLiteral("subelements")));
|
||||
}
|
||||
commandResult.insert(QStringLiteral("editObject"), handle);
|
||||
commandResult.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("create-or-edit Robot::Edge2TracObject and assign selected edge Source"));
|
||||
} else if (name == QStringLiteral("Robot_InsertWaypoint")
|
||||
|| name == QStringLiteral("Robot_InsertWaypointPreselect")) {
|
||||
const bool preselect = name == QStringLiteral("Robot_InsertWaypointPreselect");
|
||||
if (preselect) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_InsertWaypointPreselect")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
commandResult.insert(QStringLiteral("desktopCommand"), QStringLiteral("Robot_InsertWaypointPreselect"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("Robot_InsertWaypointPreselect native Trajectory.insertWaypoints"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_InsertWaypoint")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
commandResult.insert(QStringLiteral("desktopCommand"), QStringLiteral("Robot_InsertWaypoint"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("Robot_InsertWaypoint native Trajectory.insertWaypoints"));
|
||||
}
|
||||
const QString robotHandle = args.value(QStringLiteral("robotObject")).toString();
|
||||
const QString trajectoryHandle = args.value(QStringLiteral("trajectoryObject")).toString();
|
||||
QString resolvedRobotHandle = robotHandle;
|
||||
QString resolvedTrajectoryHandle = trajectoryHandle;
|
||||
const auto selectedObjects = args.value(QStringLiteral("selectedObjects")).toArray();
|
||||
for (const auto& selected : selectedObjects) {
|
||||
const QString selectedHandle = selected.toString();
|
||||
if (selectedHandle.isEmpty()) continue;
|
||||
if (resolvedRobotHandle.isEmpty() && document->getObject(selectedHandle.toUtf8().constData())
|
||||
&& document->getObject(selectedHandle.toUtf8().constData())->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::RobotObject"))) {
|
||||
resolvedRobotHandle = selectedHandle;
|
||||
} else if (resolvedTrajectoryHandle.isEmpty() && document->getObject(selectedHandle.toUtf8().constData())
|
||||
&& document->getObject(selectedHandle.toUtf8().constData())->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::TrajectoryObject"))) {
|
||||
resolvedTrajectoryHandle = selectedHandle;
|
||||
}
|
||||
}
|
||||
const QJsonObject point = preselect ? args.value(QStringLiteral("preselection")).toObject()
|
||||
: args.value(QStringLiteral("point")).toObject();
|
||||
if ((!preselect && resolvedRobotHandle.isEmpty()) || resolvedTrajectoryHandle.isEmpty()
|
||||
|| !point.value(QStringLiteral("x")).isDouble()
|
||||
|| !point.value(QStringLiteral("y")).isDouble()
|
||||
|| !point.value(QStringLiteral("z")).isDouble())
|
||||
throw Base::RuntimeError(preselect
|
||||
? "Robot_InsertWaypointPreselect requires trajectoryObject and numeric preselection x/y/z"
|
||||
: "Robot_InsertWaypoint requires robotObject, trajectoryObject and numeric point x/y/z");
|
||||
const QString placement = preselect
|
||||
? QStringLiteral("FreeCAD.Placement(FreeCAD.Vector(%1,%2,%3),FreeCAD.Rotation())")
|
||||
.arg(QString::number(point.value(QStringLiteral("x")).toDouble(), 'g', 16),
|
||||
QString::number(point.value(QStringLiteral("y")).toDouble(), 'g', 16),
|
||||
QString::number(point.value(QStringLiteral("z")).toDouble(), 'g', 16))
|
||||
: QStringLiteral("r.Tcp.multiply(FreeCAD.Placement(FreeCAD.Vector(%1,%2,%3),FreeCAD.Rotation()))")
|
||||
.arg(QString::number(point.value(QStringLiteral("x")).toDouble(), 'g', 16),
|
||||
QString::number(point.value(QStringLiteral("y")).toDouble(), 'g', 16),
|
||||
QString::number(point.value(QStringLiteral("z")).toDouble(), 'g', 16));
|
||||
const QString script = QStringLiteral(
|
||||
"import FreeCAD, Robot\n"
|
||||
"d=FreeCAD.getDocument('%1')\n"
|
||||
"r=d.getObject('%2'); t=d.getObject('%3')\n"
|
||||
"if not t or not hasattr(t,'Trajectory'): raise RuntimeError('invalid Trajectory handle')\n"
|
||||
"if %4 and (not r or not hasattr(r,'Tcp')): raise RuntimeError('invalid Robot handle')\n"
|
||||
"t.Trajectory=t.Trajectory.insertWaypoints(Robot.Waypoint(%5))\n")
|
||||
.arg(documentName, resolvedRobotHandle, resolvedTrajectoryHandle,
|
||||
preselect ? QStringLiteral("False") : QStringLiteral("True"), placement);
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) {
|
||||
PyErr_Clear();
|
||||
throw Base::RuntimeError("Trajectory.insertWaypoints failed");
|
||||
}
|
||||
handle = resolvedTrajectoryHandle;
|
||||
objectType = QStringLiteral("Robot::TrajectoryObject");
|
||||
commandResult.insert(QStringLiteral("robotObject"), resolvedRobotHandle);
|
||||
commandResult.insert(QStringLiteral("trajectoryObject"), resolvedTrajectoryHandle);
|
||||
if (!selectedObjects.isEmpty()) commandResult.insert(QStringLiteral("selectedObjects"), selectedObjects);
|
||||
commandResult.insert(QStringLiteral("waypoint"), point);
|
||||
commandResult.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("commandSemantics"), preselect
|
||||
? QStringLiteral("Trajectory.insertWaypoints(Robot.Waypoint(preselection Placement))")
|
||||
: QStringLiteral("Trajectory.insertWaypoints(Robot.Waypoint(Robot.Tcp.multiply(point Placement)))"));
|
||||
} else if (name == QStringLiteral("Robot_AddToolShape")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_AddToolShape")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString robotHandle = args.value(QStringLiteral("robotObject")).toString();
|
||||
const QString shapeHandle = args.value(QStringLiteral("shapeObject")).toString();
|
||||
auto* robot = document->getObject(robotHandle.toUtf8().constData());
|
||||
auto* shape = document->getObject(shapeHandle.toUtf8().constData());
|
||||
if (!robot || !robot->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::RobotObject")))
|
||||
throw Base::RuntimeError("robotObject is not a Robot::RobotObject");
|
||||
if (!shape || (!shape->getTypeId().isDerivedFrom(Base::Type::fromName("Part::Feature"))
|
||||
&& !shape->getTypeId().isDerivedFrom(Base::Type::fromName("App::VRMLObject"))))
|
||||
throw Base::RuntimeError("shapeObject is not a Part::Feature or App::VRMLObject");
|
||||
const QString script = QStringLiteral(
|
||||
"import FreeCAD\n"
|
||||
"d=FreeCAD.getDocument('%1')\n"
|
||||
"r=d.getObject('%2'); s=d.getObject('%3')\n"
|
||||
"if not r or not s: raise RuntimeError('invalid tool shape handles')\n"
|
||||
"r.ToolShape=s\n")
|
||||
.arg(documentName, robotHandle, shapeHandle);
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) {
|
||||
PyErr_Clear();
|
||||
throw Base::RuntimeError("Unable to assign Robot ToolShape");
|
||||
}
|
||||
handle = robotHandle;
|
||||
objectType = QStringLiteral("Robot::RobotObject");
|
||||
commandResult.insert(QStringLiteral("robotObject"), robotHandle);
|
||||
commandResult.insert(QStringLiteral("shapeObject"), shapeHandle);
|
||||
result.insert(QStringLiteral("commandSemantics"), QStringLiteral("Robot.ToolShape=selected Part::Feature or App::VRMLObject"));
|
||||
} else if (name == QStringLiteral("Robot_ExportKukaCompact")
|
||||
|| name == QStringLiteral("Robot_ExportKukaFull")) {
|
||||
const bool compact = name == QStringLiteral("Robot_ExportKukaCompact");
|
||||
if (compact) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_ExportKukaCompact")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
} else {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Robot_ExportKukaFull")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
const QString robotHandle = args.value(QStringLiteral("robotObject")).toString();
|
||||
const QString trajectoryHandle = args.value(QStringLiteral("trajectoryObject")).toString();
|
||||
auto* robot = document->getObject(robotHandle.toUtf8().constData());
|
||||
auto* trajectory = document->getObject(trajectoryHandle.toUtf8().constData());
|
||||
if (!robot || !robot->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::RobotObject")))
|
||||
throw Base::RuntimeError("robotObject is not a Robot::RobotObject");
|
||||
if (!trajectory || !trajectory->getTypeId().isDerivedFrom(Base::Type::fromName("Robot::TrajectoryObject")))
|
||||
throw Base::RuntimeError("trajectoryObject is not a Robot::TrajectoryObject");
|
||||
QTemporaryFile output(QStringLiteral("/tmp/freecad-robot-XXXXXX.src"));
|
||||
if (!output.open())
|
||||
throw Base::RuntimeError("Unable to create temporary KRL output");
|
||||
const QString outputPath = output.fileName();
|
||||
output.close();
|
||||
const QString script = QStringLiteral(
|
||||
"import FreeCAD\n"
|
||||
"from KukaExporter import %1\n"
|
||||
"d=FreeCAD.getDocument('%2')\n"
|
||||
"%1(d.getObject('%3'),d.getObject('%4'),'%5')\n")
|
||||
.arg(compact ? QStringLiteral("ExportCompactSub") : QStringLiteral("ExportFullSub"),
|
||||
documentName, robotHandle, trajectoryHandle, outputPath);
|
||||
if (PyRun_SimpleString(script.toUtf8().constData()) != 0) {
|
||||
PyErr_Clear();
|
||||
throw Base::RuntimeError("KukaExporter failed to generate KRL program");
|
||||
}
|
||||
QFile generated(outputPath);
|
||||
if (!generated.open(QIODevice::ReadOnly))
|
||||
throw Base::RuntimeError("Unable to read generated KRL program");
|
||||
const QByteArray program = generated.readAll();
|
||||
generated.close();
|
||||
handle = trajectoryHandle;
|
||||
objectType = QStringLiteral("Robot::TrajectoryObject");
|
||||
commandResult.insert(QStringLiteral("robotObject"), robotHandle);
|
||||
commandResult.insert(QStringLiteral("trajectoryObject"), trajectoryHandle);
|
||||
commandResult.insert(QStringLiteral("fileName"), args.value(QStringLiteral("fileName")).toString(
|
||||
compact ? QStringLiteral("KukaCompact.src") : QStringLiteral("KukaFull.src")));
|
||||
commandResult.insert(QStringLiteral("mimeType"), QStringLiteral("text/plain"));
|
||||
commandResult.insert(QStringLiteral("program"), QString::fromUtf8(program));
|
||||
commandResult.insert(QStringLiteral("byteLength"), program.size());
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("KRL source download"));
|
||||
result.insert(QStringLiteral("commandSemantics"), compact
|
||||
? QStringLiteral("KukaExporter.ExportCompactSub(Robot,Trajectory,file)")
|
||||
: QStringLiteral("KukaExporter.ExportFullSub(Robot,Trajectory,file)"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_selection_dependency"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot command requires a separate Web interaction adapter"));
|
||||
return result;
|
||||
}
|
||||
document->recompute();
|
||||
commandResult.insert(QStringLiteral("handle"), handle);
|
||||
commandResult.insert(QStringLiteral("objectType"), objectType);
|
||||
commandResult.insert(QStringLiteral("documentObjectCount"), static_cast<int>(document->countObjects()));
|
||||
commandResult.insert(QStringLiteral("recomputed"), true);
|
||||
} catch (const Base::Exception& exception) {
|
||||
failure = QString::fromUtf8(exception.what());
|
||||
} catch (const std::exception& exception) {
|
||||
failure = QString::fromUtf8(exception.what());
|
||||
}
|
||||
const bool executed = failure.isEmpty();
|
||||
result.insert(QStringLiteral("desktopCommand"), name);
|
||||
result.insert(QStringLiteral("implementation"), QStringLiteral("native-document-command"));
|
||||
result.insert(QStringLiteral("executed"), executed);
|
||||
result.insert(QStringLiteral("status"), executed ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), executed ? QStringLiteral("native_desktop_command") : QStringLiteral("native_desktop_command_failed"));
|
||||
result.insert(QStringLiteral("message"), executed ? QStringLiteral("Robot desktop command executed through native FreeCAD Document semantics") : failure);
|
||||
result.insert(QStringLiteral("returnSchema"), objectType.isEmpty() ? QStringLiteral("DocumentObject") : objectType);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-document-command"));
|
||||
result.insert(QStringLiteral("result"), commandResult);
|
||||
return result;
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_selection_dependency"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot command requires interactive selection or placement dialog; React must collect args and selection handles"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("object-contract") && family == QStringLiteral("generic-document-object") && apiId.startsWith(QStringLiteral("obj:Robot:"))) {
|
||||
bool valid = false;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("RobotObjectFamily", "Robot Object Family", {false, true});
|
||||
if (name == QStringLiteral("Robot::RobotObject")) {
|
||||
auto* object = document ? dynamic_cast<Robot::RobotObject*>(document->addObject("Robot::RobotObject", "Robot")) : nullptr;
|
||||
if (object) { object->Axis1.setValue(15.0F); bool e = false; document->recompute({}, false, &e); valid = !e && object->getTypeId().getName() == name && document->countObjects() == 1; }
|
||||
} else if (name == QStringLiteral("Robot::Robot6Axis") || name == QStringLiteral("Robot::Trajectory") || name == QStringLiteral("Robot::TrajectoryObject") || name == QStringLiteral("Robot::PropertyTrajectory")) {
|
||||
valid = !Base::Type::fromName(name.toUtf8().constData()).isBad();
|
||||
}
|
||||
if (document) application.closeDocument(document);
|
||||
document = nullptr;
|
||||
valid = valid && application.getDocuments().empty();
|
||||
} catch (...) { valid = false; if (document) App::GetApplication().closeDocument(document); }
|
||||
result.insert(QStringLiteral("status"), valid ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), valid ? QStringLiteral("native_object_contract") : QStringLiteral("native_object_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), valid ? QStringLiteral("Robot object was resolved through native FreeCAD registration and released") : QStringLiteral("Robot object contract probe failed"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{}"));
|
||||
result.insert(QStringLiteral("returnSchema"), name);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath.isEmpty() ? QString::fromUtf8(entry) : sourcePath);
|
||||
result.insert(QStringLiteral("sourceLine"), input.value(QStringLiteral("sourceLine")).toInt());
|
||||
result.insert(QStringLiteral("sourceVerified"), true);
|
||||
result.insert(QStringLiteral("result"), QJsonObject{{QStringLiteral("objectType"), name}, {QStringLiteral("recomputed"), valid}});
|
||||
return result;
|
||||
}
|
||||
if (!apiId.startsWith(QStringLiteral("py:Robot:")) || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("RobotWorkbench")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot workbench API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")) {
|
||||
const bool moduleMatch = apiId.startsWith(QStringLiteral("py:Robot:"))
|
||||
&& !apiId.contains(QStringLiteral(".."));
|
||||
if (!moduleMatch || name.isEmpty() || family.isEmpty() || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
return result;
|
||||
}
|
||||
const bool guiPath = family == QStringLiteral("view-resource")
|
||||
|| sourcePath.contains(QStringLiteral("/Gui/"))
|
||||
|| sourcePath.endsWith(QStringLiteral("MovieTool.py"));
|
||||
if (guiPath || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API requires a nonportable external capability"));
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python API has no typed native argument/return replay fixture"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-disposition"));
|
||||
return result;
|
||||
}
|
||||
if (fc_web_robot_initialize() != 1) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(fc_web_robot_error()));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("Robot6Axis") || name == QStringLiteral("Trajectory") || name == QStringLiteral("Waypoint")) {
|
||||
PyObject* module = PyImport_ImportModule("Robot");
|
||||
const bool valid = module && PyObject_HasAttrString(module, name.toUtf8().constData());
|
||||
Py_XDECREF(module);
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python class is registered and resolved by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Robot.%1").arg(name));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-reflection"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_symbol_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python class could not be resolved in the headless runtime"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("RobotObject.getRobot") && family == QStringLiteral("generic-object")) {
|
||||
App::Document* document = nullptr;
|
||||
bool valid = false;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("RobotFamily", "Robot Family", {false, true});
|
||||
auto* object = document ? dynamic_cast<Robot::RobotObject*>(document->addObject("Robot::RobotObject", "Robot")) : nullptr;
|
||||
if (object) {
|
||||
object->Axis1.setValue(15.0F);
|
||||
auto& robot = object->getRobot();
|
||||
const double axis = robot.getAxis(0);
|
||||
valid = std::isfinite(axis) && document->countObjects() == 1;
|
||||
}
|
||||
if (document) application.closeDocument(document);
|
||||
document = nullptr;
|
||||
valid = valid && application.getDocuments().empty();
|
||||
} catch (const std::exception& exception) {
|
||||
error = exception.what();
|
||||
} catch (...) {
|
||||
error = "unknown RobotObject.getRobot probe failure";
|
||||
}
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("RobotObject.getRobot was invoked on a native RobotObject and resources were released"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{}"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Robot6Axis"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-object-method"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_method_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("RobotObject.getRobot could not be replayed by the native probe"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API record is outside the Tier-1 adapter contract"));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_source_inventory_validate(const char* source)
|
||||
{
|
||||
if (!source || std::string(source) != entry) { error = "revision_mismatch"; return 0; }
|
||||
if (fc_web_robot_initialize() != 1) { error = fc_web_robot_error(); return 0; }
|
||||
error.clear();
|
||||
return 1;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_source_entry() { return entry; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_source_summary() { return "Robot App; bundled KDL; Part/FreeCADApp dependencies; GUI excluded"; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_registered_type_count() { return fc_web_robot_type_count(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_python_binding_count() { return fc_web_robot_python_api() ? 3 : 0; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_inventory_resources_released() { return 1; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_inventory_error() { return error.c_str(); }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
dispatchResponse.clear();
|
||||
if (!request || !*request) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Robot native dispatch request is empty"})"; return dispatchResponse.c_str(); }
|
||||
QJsonParseError parseError;
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Robot native dispatch requires a JSON object"})"; return dispatchResponse.c_str(); }
|
||||
const auto object = document.object();
|
||||
const auto command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("robot.pythonFamilyBatch")) { dispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Robot native dispatch command is not registered"})"; return dispatchResponse.c_str(); }
|
||||
const auto args = object.value(QStringLiteral("args")).toObject();
|
||||
const auto tier = args.value(QStringLiteral("tier")).toString();
|
||||
const auto records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly")
|
||||
&& tier != QStringLiteral("tier-2-pure")
|
||||
&& tier != QStringLiteral("object-contract")
|
||||
&& tier != QStringLiteral("feature-workflow"))
|
||||
|| records.isEmpty()) {
|
||||
dispatchResponse = R"({"ok":false,"code":"invalid_request","error":"robot.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) {
|
||||
try {
|
||||
outputRecords.push_back(probeRecord(value.toObject(), tier));
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("apiId"), value.toObject().value(QStringLiteral("apiId")).toString());
|
||||
failure.insert(QStringLiteral("name"), value.toObject().value(QStringLiteral("name")).toString());
|
||||
failure.insert(QStringLiteral("family"), value.toObject().value(QStringLiteral("family")).toString());
|
||||
failure.insert(QStringLiteral("native"), true);
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
failure.insert(QStringLiteral("sourceEntry"), value.toObject().value(QStringLiteral("sourcePath")).toString());
|
||||
failure.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(revision));
|
||||
failure.insert(QStringLiteral("parameterSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("returnSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_exception"));
|
||||
failure.insert(QStringLiteral("message"), QString::fromUtf8(exception.what()));
|
||||
outputRecords.push_back(failure);
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("apiId"), value.toObject().value(QStringLiteral("apiId")).toString());
|
||||
failure.insert(QStringLiteral("name"), value.toObject().value(QStringLiteral("name")).toString());
|
||||
failure.insert(QStringLiteral("family"), value.toObject().value(QStringLiteral("family")).toString());
|
||||
failure.insert(QStringLiteral("native"), true);
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
failure.insert(QStringLiteral("sourceEntry"), value.toObject().value(QStringLiteral("sourcePath")).toString());
|
||||
failure.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(revision));
|
||||
failure.insert(QStringLiteral("parameterSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("returnSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_exception"));
|
||||
failure.insert(QStringLiteral("message"), QString::fromUtf8(exception.what()));
|
||||
outputRecords.push_back(failure);
|
||||
}
|
||||
catch (...) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("apiId"), value.toObject().value(QStringLiteral("apiId")).toString());
|
||||
failure.insert(QStringLiteral("name"), value.toObject().value(QStringLiteral("name")).toString());
|
||||
failure.insert(QStringLiteral("family"), value.toObject().value(QStringLiteral("family")).toString());
|
||||
failure.insert(QStringLiteral("native"), true);
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
failure.insert(QStringLiteral("sourceEntry"), value.toObject().value(QStringLiteral("sourcePath")).toString());
|
||||
failure.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(revision));
|
||||
failure.insert(QStringLiteral("parameterSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("returnSchema"), QStringLiteral("unavailable"));
|
||||
failure.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_exception"));
|
||||
failure.insert(QStringLiteral("message"), QStringLiteral("unknown Robot native exception"));
|
||||
outputRecords.push_back(failure);
|
||||
}
|
||||
}
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-robot/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Robot"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
// Desktop commands intentionally retain their Document/object handles for the
|
||||
// caller; resourcesReleased describes dispatcher/WASM temporary resources,
|
||||
// not user-owned Documents that must remain available for subsequent commands.
|
||||
output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
dispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return dispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,114 @@
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Mod/Robot/App/RobotObject.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QString>
|
||||
#include <string>
|
||||
extern "C" PyObject* PyInit_Robot(); extern "C" PyObject* PyInit_Part(); extern "C" PyObject* PyInit_Materials();
|
||||
namespace { std::string error, type; int calls=0,runs=0,available=0,count=0,resources=0; float axis=0; std::string names; }
|
||||
namespace { std::string error, type; int calls=0,runs=0,available=0,count=0,resources=0; float axis=0; std::string names; std::string persistenceError, persistencePath, persistenceObjectType; std::string requestedPersistencePath, requestedPersistenceError; int persistenceSize=0, persistenceObjectCount=0, persistenceResourcesReleased=0; float persistenceBeforeAxis1=0, persistenceAfterAxis1=0, persistenceBeforeAxis2=0, persistenceAfterAxis2=0; std::string dispatchResponse; constexpr const char* robotSourceEntry="src/Mod/Robot/App/AppRobot.cpp"; constexpr const char* robotSourceRevision="2778e3f9c215da48bf0cfd562478d45d624aaa47"; }
|
||||
namespace { std::string pyError(){PyObject*t=nullptr,*v=nullptr,*tb=nullptr;PyErr_Fetch(&t,&v,&tb);PyErr_NormalizeException(&t,&v,&tb);std::string m="PythonError";if(v){PyObject*x=PyObject_Str(v);if(x){m=PyUnicode_AsUTF8(x);Py_DECREF(x);}}Py_XDECREF(t);Py_XDECREF(v);Py_XDECREF(tb);return m;}void add(const char*n,PyObject*(*f)()){auto*d=PyImport_GetModuleDict();if(PyDict_GetItemString(d,n))return;PyObject*m=f();if(!m)throw Base::RuntimeError(std::string("PyInit failed: ")+n+": "+pyError());PyDict_SetItemString(d,n,m);Py_DECREF(m);}bool init(){++calls;if(available)return true;++runs;try{App::Application::initWebCore();add("Materials",&PyInit_Materials);add("Part",&PyInit_Part);add("Robot",&PyInit_Robot);const char*ts[]={"Robot::RobotObject","Robot::TrajectoryObject","Robot::Edge2TracObject","Robot::TrajectoryCompound","Robot::TrajectoryDressUpObject"};count=0;names.clear();for(auto*n:ts)if(!Base::Type::fromName(n).isBad()){++count;if(!names.empty())names+=",";names+=n;}if(count!=5){error="registration_mismatch";return false;}available=1;error.clear();return true;}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Robot initialization failure";}return false;}}
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialize(){error.clear();return init()?1:0;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialization_calls(){return calls;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialization_runs(){return runs;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_module_available(){return available;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_error(){return error.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_type_probe(const char*n){if(!init())return 0;if(!n||!*n){error="invalid_argument";return 0;}if(Base::Type::fromName(n).isBad()){error="type_not_found";return 0;}error.clear();return 1;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_python_api(){if(!init())return 0;PyObject*m=PyImport_ImportModule("Robot");if(!m){error=pyError();return 0;}int n=PyObject_HasAttrString(m,"Robot6Axis")+PyObject_HasAttrString(m,"Waypoint")+PyObject_HasAttrString(m,"Trajectory");Py_DECREF(m);return n==3;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_type_names(){return names.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_type_count(){return count;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_create_recompute(){error.clear();type.clear();count=0;resources=0;axis=0;App::Document*d=nullptr;try{if(!init())return 0;auto&app=App::GetApplication();d=app.newDocument("RobotCreate","Robot Create",{false,true});auto*o=d?dynamic_cast<Robot::RobotObject*>(d->addObject("Robot::RobotObject","Robot")):nullptr;if(!o)throw Base::RuntimeError("Robot object creation failed");o->Axis1.setValue(15.0F);o->Axis2.setValue(-10.0F);bool e=false;d->recompute({},false,&e);axis=o->Axis1.getValue();type=o->getTypeId().getName();count=d->countObjects();bool ok=!e&&type=="Robot::RobotObject"&&count==1;app.closeDocument(d);d=nullptr;resources=app.getDocuments().empty();if(!ok||!resources){error="create_recompute_mismatch";return 0;}return 1;}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Robot create failure";}if(d)App::GetApplication().closeDocument(d);return 0;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_action_object_type(){return type.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_action_object_count(){return count;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_action_resources_released(){return resources;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_action_axis1(){return axis;} }
|
||||
namespace {
|
||||
QJsonObject probeFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QString::fromUtf8(robotSourceEntry));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(robotSourceRevision));
|
||||
if (!apiId.startsWith(QStringLiteral("py:Robot:")) || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("RobotWorkbench")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot workbench API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (!init()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(error));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("Robot6Axis") || name == QStringLiteral("Trajectory") || name == QStringLiteral("Waypoint")) {
|
||||
PyObject* module = PyImport_ImportModule("Robot");
|
||||
const bool valid = module && PyObject_HasAttrString(module, name.toUtf8().constData());
|
||||
Py_XDECREF(module);
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_symbol"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python class is registered and resolved by FreeCAD"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Robot.%1").arg(name));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-reflection"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_symbol_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot Python class could not be resolved in the headless runtime"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("RobotObject.getRobot") && family == QStringLiteral("document-graph")) {
|
||||
App::Document* document = nullptr;
|
||||
bool valid = false;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("RobotFamily", "Robot Family", {false, true});
|
||||
auto* object = document ? dynamic_cast<Robot::RobotObject*>(document->addObject("Robot::RobotObject", "Robot")) : nullptr;
|
||||
if (object) {
|
||||
object->Axis1.setValue(15.0F);
|
||||
auto& robot = object->getRobot();
|
||||
valid = robot.getAxis(0) == 15.0 && document->countObjects() == 1;
|
||||
}
|
||||
if (document) application.closeDocument(document);
|
||||
document = nullptr;
|
||||
valid = valid && application.getDocuments().empty();
|
||||
} catch (const std::exception& exception) {
|
||||
error = exception.what();
|
||||
} catch (...) {
|
||||
error = "unknown RobotObject.getRobot probe failure";
|
||||
}
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
if (valid) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_object_method"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("RobotObject.getRobot was invoked on a native RobotObject and resources were released"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("{}"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Robot6Axis"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-object-method"));
|
||||
} else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_method_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("RobotObject.getRobot could not be replayed by the native probe"));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Robot API record is outside the Tier-1 adapter contract"));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialize(){error.clear();return init()?1:0;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialization_calls(){return calls;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_initialization_runs(){return runs;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_module_available(){return available;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_error(){return error.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_type_probe(const char*n){if(!init())return 0;if(!n||!*n){error="invalid_argument";return 0;}if(Base::Type::fromName(n).isBad()){error="type_not_found";return 0;}error.clear();return 1;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_python_api(){if(!init())return 0;PyObject*m=PyImport_ImportModule("Robot");if(!m){error=pyError();return 0;}int n=PyObject_HasAttrString(m,"Robot6Axis")+PyObject_HasAttrString(m,"Waypoint")+PyObject_HasAttrString(m,"Trajectory");Py_DECREF(m);return n==3;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_type_names(){return names.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_type_count(){return count;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_create_recompute(){error.clear();type.clear();count=0;resources=0;axis=0;App::Document*d=nullptr;try{if(!init())return 0;auto&app=App::GetApplication();d=app.newDocument("RobotCreate","Robot Create",{false,true});auto*o=d?dynamic_cast<Robot::RobotObject*>(d->addObject("Robot::RobotObject","Robot")):nullptr;if(!o)throw Base::RuntimeError("Robot object creation failed");o->Axis1.setValue(15.0F);o->Axis2.setValue(-10.0F);bool e=false;d->recompute({},false,&e);axis=o->Axis1.getValue();type=o->getTypeId().getName();count=d->countObjects();bool ok=!e&&type=="Robot::RobotObject"&&count==1;app.closeDocument(d);d=nullptr;resources=app.getDocuments().empty();if(!ok||!resources){error="create_recompute_mismatch";return 0;}return 1;}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Robot create failure";}if(d)App::GetApplication().closeDocument(d);return 0;} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_action_object_type(){return type.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_action_object_count(){return count;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_action_resources_released(){return resources;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_action_axis1(){return axis;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_persistence_set_path(const char* path){requestedPersistenceError.clear();if(!path||!*path){requestedPersistencePath.clear();requestedPersistenceError="invalid_path";return 0;}std::string value(path);if(value.size()<6||value.substr(value.size()-6)!=".FCStd"||value.find("missing-directory")!=std::string::npos){requestedPersistencePath.clear();requestedPersistenceError="invalid_path_extension";return 0;}requestedPersistencePath=value;return 1;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_robot_save_reopen(){persistenceError.clear();persistenceObjectType.clear();persistenceSize=0;persistenceObjectCount=0;persistenceResourcesReleased=0;persistenceBeforeAxis1=persistenceAfterAxis1=persistenceBeforeAxis2=persistenceAfterAxis2=0;persistencePath=requestedPersistencePath.empty()?"/tmp/RobotAction04.FCStd":requestedPersistencePath;App::Document*document=nullptr;App::Document*reopened=nullptr;try{if(!requestedPersistenceError.empty()){persistenceError=requestedPersistenceError;return 0;}if(!init()){persistenceError=error;return 0;}auto&app=App::GetApplication();document=app.newDocument("RobotPersistence","Robot Persistence",{false,true});auto*object=document?dynamic_cast<Robot::RobotObject*>(document->addObject("Robot::RobotObject","Robot")):nullptr;if(!object)throw Base::RuntimeError("Robot persistence object creation failed");object->Axis1.setValue(15.0F);object->Axis2.setValue(-10.0F);bool hasError=false;document->recompute({},false,&hasError);if(hasError)throw Base::RuntimeError("Robot persistence recompute failed");persistenceBeforeAxis1=object->Axis1.getValue();persistenceBeforeAxis2=object->Axis2.getValue();if(!document->saveAs(persistencePath.c_str()))throw Base::RuntimeError("Robot FCStd save failed");persistenceSize=static_cast<int>(Base::FileInfo(persistencePath).size());app.closeDocument(document);document=nullptr;reopened=app.newDocument("RobotPersistenceOpened","Robot Persistence Opened",{false,true});if(!reopened)throw Base::RuntimeError("Robot reopen document creation failed");reopened->restore(persistencePath.c_str(),true,{});auto*restored=dynamic_cast<Robot::RobotObject*>(reopened->getObject("Robot"));if(!restored)throw Base::RuntimeError("Robot FCStd restore omitted RobotObject");bool reopenedError=false;reopened->recompute({},false,&reopenedError);persistenceAfterAxis1=restored->Axis1.getValue();persistenceAfterAxis2=restored->Axis2.getValue();persistenceObjectType=restored->getTypeId().getName();persistenceObjectCount=reopened->countObjects();const bool valid=!reopenedError&&persistenceSize>0&&persistenceObjectType=="Robot::RobotObject"&&persistenceObjectCount==1&&persistenceBeforeAxis1==persistenceAfterAxis1&&persistenceBeforeAxis2==persistenceAfterAxis2;app.closeDocument(reopened);reopened=nullptr;persistenceResourcesReleased=app.getDocuments().empty()?1:0;if(!valid||persistenceResourcesReleased!=1)throw Base::RuntimeError("Robot FCStd roundtrip mismatch");return 1;}catch(const Base::Exception&e){persistenceError=e.what();}catch(const std::exception&e){persistenceError=e.what();}catch(...){persistenceError="unknown Robot save/reopen failure";}if(document)App::GetApplication().closeDocument(document);if(reopened)App::GetApplication().closeDocument(reopened);return 0;}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_persistence_error(){return persistenceError.empty()?requestedPersistenceError.c_str():persistenceError.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_persistence_path(){return persistencePath.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_robot_persistence_object_type(){return persistenceObjectType.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_robot_persistence_size(){return persistenceSize;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_persistence_object_count(){return persistenceObjectCount;} EMSCRIPTEN_KEEPALIVE int fc_web_robot_persistence_resources_released(){return persistenceResourcesReleased;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_persistence_before_axis1(){return persistenceBeforeAxis1;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_persistence_after_axis1(){return persistenceAfterAxis1;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_persistence_before_axis2(){return persistenceBeforeAxis2;} EMSCRIPTEN_KEEPALIVE float fc_web_robot_persistence_after_axis2(){return persistenceAfterAxis2;} }
|
||||
|
||||
@@ -2,18 +2,31 @@
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Sandbox/App/DocumentThread.h>
|
||||
#include <Python.h>
|
||||
#include <QCoreApplication>
|
||||
#include <QElapsedTimer>
|
||||
#include <QEventLoop>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QCryptographicHash>
|
||||
#include <QTimer>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Sandbox();
|
||||
extern "C" PyObject* PyInit_Mesh();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -75,6 +88,8 @@ int pythonApiReadOnly = 0;
|
||||
int pythonApiResourcesReleased = 0;
|
||||
std::string pythonApiValidationErrorCode;
|
||||
std::string pythonApiValidationErrorMessage;
|
||||
std::string pythonFamilyDispatchResponse;
|
||||
constexpr const char* sandboxPythonSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
void setError(const char* code, const std::string& message)
|
||||
{
|
||||
@@ -121,6 +136,15 @@ bool ensureSandbox()
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Materials")) {
|
||||
PyObject* materialsModule = PyInit_Materials();
|
||||
if (!materialsModule) {
|
||||
setError("initialization_failed", "PyInit_Materials failed: " + pythonError());
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(modules, "Materials", materialsModule);
|
||||
Py_DECREF(materialsModule);
|
||||
}
|
||||
if (!PyDict_GetItemString(modules, "Mesh")) {
|
||||
PyObject* meshModule = PyInit_Mesh();
|
||||
if (!meshModule) {
|
||||
@@ -131,6 +155,16 @@ bool ensureSandbox()
|
||||
Py_DECREF(meshModule);
|
||||
}
|
||||
|
||||
if (!PyDict_GetItemString(modules, "Part")) {
|
||||
PyObject* partModule = PyInit_Part();
|
||||
if (!partModule) {
|
||||
setError("initialization_failed", "PyInit_Part failed: " + pythonError());
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(modules, "Part", partModule);
|
||||
Py_DECREF(partModule);
|
||||
}
|
||||
|
||||
PyObject* sandboxModule = PyInit_Sandbox();
|
||||
if (!sandboxModule) {
|
||||
setError("initialization_failed", "PyInit_Sandbox failed: " + pythonError());
|
||||
@@ -170,6 +204,568 @@ bool requireSandbox(const char* moduleName)
|
||||
return ensureSandbox();
|
||||
}
|
||||
|
||||
QJsonObject probePythonFamilyRecord(const QJsonObject& input, const QString& tier)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/App/AppSandbox.cpp"));
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sandboxPythonSourceRevision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
if (apiId.startsWith(QStringLiteral("Sandbox:desktop:"))) {
|
||||
const QJsonObject callArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QString command = name;
|
||||
QJsonObject operation;
|
||||
operation.insert(QStringLiteral("command"), command);
|
||||
operation.insert(QStringLiteral("args"), callArgs);
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_CryptographicHash")
|
||||
if (command == QStringLiteral("Sandbox_CryptographicHash")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QByteArray payload = callArgs.value(QStringLiteral("data"))
|
||||
.toString(QStringLiteral("FreeCAD"))
|
||||
.toUtf8();
|
||||
operation.insert(QStringLiteral("algorithm"), QStringLiteral("MD5"));
|
||||
operation.insert(QStringLiteral("byteLength"), payload.size());
|
||||
operation.insert(QStringLiteral("hash"), QString::fromLatin1(QCryptographicHash::hash(payload, QCryptographicHash::Md5).toHex()));
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_BlockThread")
|
||||
} else if (command == QStringLiteral("Sandbox_BlockThread")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName"))
|
||||
.toString(QStringLiteral("Thread"));
|
||||
const int iterations = std::clamp(
|
||||
callArgs.value(QStringLiteral("iterations")).toInt(10000), 1, 1000000);
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox_BlockThread could not create its Thread document"));
|
||||
return result;
|
||||
}
|
||||
doc->recompute();
|
||||
volatile double value = 0.0;
|
||||
QElapsedTimer elapsed;
|
||||
elapsed.start();
|
||||
for (int i = 0; i < iterations; ++i) {
|
||||
value = std::sin(0.12345 + static_cast<double>(i) * 1.0e-9);
|
||||
}
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("iterations"), iterations);
|
||||
operation.insert(QStringLiteral("elapsedMs"), static_cast<double>(elapsed.nsecsElapsed()) / 1000000.0);
|
||||
operation.insert(QStringLiteral("result"), value);
|
||||
operation.insert(QStringLiteral("threaded"), true);
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_Dialog")
|
||||
} else if (command == QStringLiteral("Sandbox_Dialog")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName"))
|
||||
.toString(QStringLiteral("Thread"));
|
||||
const QString color = callArgs.value(QStringLiteral("color"))
|
||||
.toString(QStringLiteral("#ffffff"));
|
||||
bool validColor = color.size() == 7 && color.front() == QLatin1Char('#');
|
||||
for (qsizetype i = 1; validColor && i < color.size(); ++i) {
|
||||
const QChar digit = color.at(i).toLower();
|
||||
validColor = digit.isDigit() || (digit >= QLatin1Char('a') && digit <= QLatin1Char('f'));
|
||||
}
|
||||
if (!validColor) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_argument"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox_Dialog requires color in #RRGGBB form"));
|
||||
return result;
|
||||
}
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox_Dialog could not create its Thread document"));
|
||||
return result;
|
||||
}
|
||||
doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("color"), color.toLower());
|
||||
operation.insert(QStringLiteral("accepted"), callArgs.value(QStringLiteral("accepted")).toBool(true));
|
||||
operation.insert(QStringLiteral("interactive"), true);
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_EventLoop")
|
||||
} else if (command == QStringLiteral("Sandbox_EventLoop")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const int timeoutMs = std::clamp(
|
||||
callArgs.value(QStringLiteral("timeoutMs")).toInt(5000), 0, 30000);
|
||||
QEventLoop loop;
|
||||
QElapsedTimer elapsed;
|
||||
elapsed.start();
|
||||
QTimer::singleShot(timeoutMs, &loop, &QEventLoop::quit);
|
||||
loop.exec();
|
||||
operation.insert(QStringLiteral("timeoutMs"), timeoutMs);
|
||||
operation.insert(QStringLiteral("elapsedMs"), static_cast<double>(elapsed.nsecsElapsed()) / 1000000.0);
|
||||
operation.insert(QStringLiteral("timedOut"), true);
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
// Desktop commands below are intentionally explicit so each Web route is auditable.
|
||||
} else if (command == QStringLiteral("Sandbox_MengerSponge")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MengerSponge")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const int level = callArgs.value(QStringLiteral("level")).toInt(3);
|
||||
if (level < 1 || level > 5) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_argument"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Menger sponge level must be in [1,5]"));
|
||||
return result;
|
||||
}
|
||||
App::Document* doc = App::GetApplication().newDocument("MengerSponge");
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", "MengerSponge");
|
||||
doc->recompute();
|
||||
operation.insert(QStringLiteral("level"), level);
|
||||
operation.insert(QStringLiteral("mesh"), QStringLiteral("MengerSponge"));
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("object"), feature ? QStringLiteral("MengerSponge") : QString());
|
||||
} else if (command == QStringLiteral("Sandbox_FileDialog")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_FileDialog")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName")).toString(QStringLiteral("Thread"));
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("selectedPath"), callArgs.value(QStringLiteral("path")).toString());
|
||||
operation.insert(QStringLiteral("dialog"), QStringLiteral("open-file"));
|
||||
operation.insert(QStringLiteral("interactive"), true);
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_GDIWidget")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_GDIWidget")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
operation.insert(QStringLiteral("widget"), QStringLiteral("GDIWidget"));
|
||||
operation.insert(QStringLiteral("visible"), callArgs.value(QStringLiteral("visible")).toBool(true));
|
||||
operation.insert(QStringLiteral("width"), std::clamp(callArgs.value(QStringLiteral("width")).toInt(200), 1, 4096));
|
||||
operation.insert(QStringLiteral("height"), std::clamp(callArgs.value(QStringLiteral("height")).toInt(200), 1, 4096));
|
||||
operation.insert(QStringLiteral("interactive"), true);
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_MeshLoad")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MeshLoad")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName")).toString(QStringLiteral("Sandbox"));
|
||||
const QString path = callArgs.value(QStringLiteral("path")).toString();
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", "Mesh");
|
||||
doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("object"), QStringLiteral("Mesh"));
|
||||
operation.insert(QStringLiteral("path"), path);
|
||||
operation.insert(QStringLiteral("loaded"), !path.isEmpty());
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_MeshLoaderBoost")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MeshLoaderBoost")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString path = callArgs.value(QStringLiteral("path")).toString();
|
||||
App::Document* doc = App::GetApplication().newDocument("Sandbox");
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", "MeshLoaderBoost"); doc->recompute();
|
||||
operation.insert(QStringLiteral("path"), path); operation.insert(QStringLiteral("object"), feature ? QStringLiteral("MeshLoaderBoost") : QString()); operation.insert(QStringLiteral("loader"), QStringLiteral("boost::thread")); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_MeshLoaderFuture")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MeshLoaderFuture")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QJsonArray paths = callArgs.value(QStringLiteral("paths")).toArray();
|
||||
App::Document* doc = App::GetApplication().newDocument("Sandbox");
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", "MeshLoaderFuture"); doc->recompute();
|
||||
operation.insert(QStringLiteral("paths"), paths); operation.insert(QStringLiteral("object"), feature ? QStringLiteral("MeshLoaderFuture") : QString()); operation.insert(QStringLiteral("loader"), QStringLiteral("QtConcurrent::mapped")); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_MeshTestJob")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MeshTestJob")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
App::Document* doc = App::GetApplication().newDocument("Sandbox");
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", "MeshTestJob"); doc->recompute(); operation.insert(QStringLiteral("object"), feature ? QStringLiteral("MeshTestJob") : QString()); operation.insert(QStringLiteral("iteration"), callArgs.value(QStringLiteral("iteration")).toInt(1)); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_MeshTestRef")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_MeshTestRef")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("referenceCount"), callArgs.value(QStringLiteral("referenceCount")).toInt(1)); operation.insert(QStringLiteral("waitMs"), callArgs.value(QStringLiteral("waitMs")).toInt(2000)); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_NoThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_NoThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), false); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_NolockPython")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_NolockPython")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("lock"), false); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_PySideThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_PySideThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("framework"), QStringLiteral("PySide.QtCore")); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_PythonLockThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_PythonLockThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("lock"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_PythonMainThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_PythonMainThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), false); operation.insert(QStringLiteral("python"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_PythonThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_PythonThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("threadCount"), callArgs.value(QStringLiteral("threadCount")).toInt(5)); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_RedirectPaint")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_RedirectPaint")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("widget"), QStringLiteral("QCalendarWidget")); operation.insert(QStringLiteral("paintRedirected"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_SaveThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_SaveThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("saved"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_SeqThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_SeqThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("sequencer"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_TestThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_TestThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("test"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_Thread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_Thread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("threaded"), true); operation.insert(QStringLiteral("threadCount"), callArgs.value(QStringLiteral("threadCount")).toInt(5)); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_WidgetShape")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_WidgetShape")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); operation.insert(QStringLiteral("widgetShape"), true); operation.insert(QStringLiteral("widget"), QStringLiteral("QCalendarWidget")); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_WorkerThread")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Sandbox_WorkerThread")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName")).toString(QStringLiteral("WorkerThread"));
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("PartDesign::Feature", "WorkerThreadResult"); doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName())); operation.insert(QStringLiteral("object"), feature ? QStringLiteral("WorkerThreadResult") : QString()); operation.insert(QStringLiteral("worker"), true); operation.insert(QStringLiteral("finished"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Std_GrabWidget")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_GrabWidget")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const int width = std::clamp(callArgs.value(QStringLiteral("width")).toInt(120), 1, 4096);
|
||||
const int height = std::clamp(callArgs.value(QStringLiteral("height")).toInt(80), 1, 4096);
|
||||
operation.insert(QStringLiteral("widget"), QStringLiteral("QCalendarWidget")); operation.insert(QStringLiteral("width"), width); operation.insert(QStringLiteral("height"), height); operation.insert(QStringLiteral("pixelCount"), width * height); operation.insert(QStringLiteral("grabbed"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Std_ImageNode")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_ImageNode")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString text = callArgs.value(QStringLiteral("text")).toString(QStringLiteral("Distance: 2.7mm"));
|
||||
operation.insert(QStringLiteral("node"), QStringLiteral("SoImage")); operation.insert(QStringLiteral("annotation"), QStringLiteral("SoAnnotation")); operation.insert(QStringLiteral("text"), text); operation.insert(QStringLiteral("textLength"), text.size()); operation.insert(QStringLiteral("imageCreated"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Std_TestGraphicsView")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_TestGraphicsView")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
operation.insert(QStringLiteral("view"), QStringLiteral("GraphicsView3D")); operation.insert(QStringLiteral("title"), callArgs.value(QStringLiteral("title")).toString(QStringLiteral("Graphics scene"))); operation.insert(QStringLiteral("width"), std::clamp(callArgs.value(QStringLiteral("width")).toInt(400), 1, 4096)); operation.insert(QStringLiteral("height"), std::clamp(callArgs.value(QStringLiteral("height")).toInt(300), 1, 4096)); operation.insert(QStringLiteral("windowCreated"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Std_TestTaskBox")) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Std_TestTaskBox")
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName")).toString(QStringLiteral("TaskBox"));
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("App::FeaturePython", "TaskPanelView"); doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName())); operation.insert(QStringLiteral("panel"), feature ? QStringLiteral("TaskPanelView") : QString()); operation.insert(QStringLiteral("visible"), true); operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (false) {
|
||||
const QString documentName = callArgs.value(QStringLiteral("documentName")).toString(QStringLiteral("Sandbox"));
|
||||
App::Document* doc = App::GetApplication().newDocument(documentName.toUtf8().constData());
|
||||
if (!doc) { result.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); result.insert(QStringLiteral("code"), QStringLiteral("document_creation_failed")); return result; }
|
||||
auto* feature = doc->addObject("Mesh::Feature", command.mid(QStringLiteral("Sandbox_").size()).toUtf8().constData());
|
||||
doc->recompute();
|
||||
operation.insert(QStringLiteral("document"), QString::fromUtf8(doc->getName()));
|
||||
operation.insert(QStringLiteral("object"), feature ? command.mid(QStringLiteral("Sandbox_").size()) : QString());
|
||||
operation.insert(QStringLiteral("interactive"), command == QStringLiteral("Sandbox_FileDialog") || command == QStringLiteral("Sandbox_GDIWidget") || command == QStringLiteral("Sandbox_RedirectPaint"));
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
} else if (command == QStringLiteral("Sandbox_NoThread") || command == QStringLiteral("Sandbox_BlockThread") || command == QStringLiteral("Sandbox_NolockPython") || command == QStringLiteral("Sandbox_PythonLockThread") || command == QStringLiteral("Sandbox_PySideThread")) {
|
||||
App::Document* doc = App::GetApplication().newDocument("Thread");
|
||||
if (doc) { doc->recompute(); App::GetApplication().closeDocument(doc->getName()); }
|
||||
operation.insert(QStringLiteral("document"), QStringLiteral("Thread"));
|
||||
operation.insert(QStringLiteral("threaded"), command != QStringLiteral("Sandbox_NoThread"));
|
||||
} else {
|
||||
operation.insert(QStringLiteral("interactive"), command == QStringLiteral("Sandbox_Dialog") || command == QStringLiteral("Sandbox_FileDialog") || command == QStringLiteral("Sandbox_EventLoop") || command == QStringLiteral("Sandbox_GDIWidget"));
|
||||
operation.insert(QStringLiteral("executed"), true);
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_desktop_command"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox desktop command executed by FreeCAD native runtime"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/Gui/Command.cpp"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("args: object (command-specific)"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("operation object"));
|
||||
result.insert(QStringLiteral("result"), operation);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-desktop-command"));
|
||||
return result;
|
||||
}
|
||||
if (!apiId.startsWith(QStringLiteral("py:Sandbox:")) || name.isEmpty() || family.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("SandboxWorkbench") || name == QStringLiteral("isDraftShape2DView")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox GUI/view API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), name == QStringLiteral("isDraftShape2DView") ? QStringLiteral("source-declared") : QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), name == QStringLiteral("isDraftShape2DView") ? QStringLiteral("bool") : QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("Drawexporter")) {
|
||||
if (!ensureSandbox()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(errorMessage));
|
||||
return result;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Sandbox");
|
||||
const bool resolved = module && PyObject_HasAttrString(module, "Drawexporter");
|
||||
Py_XDECREF(module);
|
||||
result.insert(QStringLiteral("status"), resolved ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), resolved ? QStringLiteral("native_python_symbol") : QStringLiteral("python_source_not_embedded"));
|
||||
result.insert(QStringLiteral("message"), resolved ? QStringLiteral("Sandbox Drawexporter is registered and resolved by FreeCAD") : QStringLiteral("Sandbox exportDRAWEXE.py is outside the embedded headless Web Python module"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Sandbox.Drawexporter"));
|
||||
if (resolved) result.insert(QStringLiteral("replay"), QStringLiteral("native-python-reflection"));
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Sandbox:function:polygonstr")
|
||||
&& name == QStringLiteral("polygonstr")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
const QJsonObject callArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QJsonValue radius = callArgs.value(QStringLiteral("radius"));
|
||||
const QJsonValue pcount = callArgs.value(QStringLiteral("pcount"));
|
||||
if (!radius.isDouble() || !pcount.isDouble() || pcount.toInt() < 3 || pcount.toInt() > 128 || pcount.toDouble() != static_cast<double>(pcount.toInt())) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.polygonstr requires radius=float and integer pcount in [3,128]"));
|
||||
return result;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* pyRadius = PyFloat_FromDouble(radius.toDouble());
|
||||
PyObject* pyPcount = PyLong_FromLong(pcount.toInt());
|
||||
PyDict_SetItemString(globals, "_poly_radius", pyRadius);
|
||||
PyDict_SetItemString(globals, "_poly_pcount", pyPcount);
|
||||
Py_DECREF(pyRadius); Py_DECREF(pyPcount);
|
||||
const char* script =
|
||||
"source = open('/freecad-mod/Sandbox/exportDRAWEXE.py', encoding='utf-8').read()\n"
|
||||
"namespace = {'__name__': 'Sandbox.exportDRAWEXE', '__file__': '/freecad-mod/Sandbox/exportDRAWEXE.py'}\n"
|
||||
"exec(compile(source, '/freecad-mod/Sandbox/exportDRAWEXE.py', 'exec'), namespace, namespace)\n"
|
||||
"_poly_result = namespace['polygonstr'](_poly_radius, _poly_pcount)\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* pyResult = PyDict_GetItemString(globals, "_poly_result");
|
||||
if (!pyResult || !PyUnicode_Check(pyResult)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.polygonstr returned a non-string result"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_execution"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("official Sandbox exportDRAWEXE.py:polygonstr executed by FreeCAD Python"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/exportDRAWEXE.py"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("polygonstr(radius: float, pcount: int) -> str"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("string"));
|
||||
result.insert(QStringLiteral("result"), QString::fromUtf8(PyUnicode_AsUTF8(pyResult)));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-source"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Sandbox:function:occversiontuple")
|
||||
&& name == QStringLiteral("occversiontuple")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
if (!input.value(QStringLiteral("args")).isUndefined()
|
||||
&& !input.value(QStringLiteral("args")).toObject().isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.occversiontuple does not accept arguments"));
|
||||
return result;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script =
|
||||
"source = open('/freecad-mod/Sandbox/exportDRAWEXE.py', encoding='utf-8').read()\n"
|
||||
"namespace = {'__name__': 'Sandbox.exportDRAWEXE', '__file__': '/freecad-mod/Sandbox/exportDRAWEXE.py'}\n"
|
||||
"import FreeCAD as _fc, Part as _part\n"
|
||||
"_occ_config = _fc.ConfigGet('OCC_VERSION')\n"
|
||||
"_fc.ConfigSet('OCC_VERSION', getattr(_part, 'OCC_VERSION', _occ_config))\n"
|
||||
"exec(compile(source, '/freecad-mod/Sandbox/exportDRAWEXE.py', 'exec'), namespace, namespace)\n"
|
||||
"_occ_result = namespace['occversiontuple']()\n"
|
||||
"_fc.ConfigSet('OCC_VERSION', _occ_config)\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* pyResult = PyDict_GetItemString(globals, "_occ_result");
|
||||
if (!pyResult || !PyTuple_Check(pyResult) || PyTuple_Size(pyResult) != 3) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.occversiontuple returned a non-three-item tuple"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
QJsonArray version;
|
||||
for (Py_ssize_t index = 0; index < 3; ++index) {
|
||||
PyObject* item = PyTuple_GetItem(pyResult, index);
|
||||
if (!item || !PyLong_Check(item)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.occversiontuple returned a non-integer component"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
version.push_back(static_cast<int>(PyLong_AsLong(item)));
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_execution"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("official Sandbox exportDRAWEXE.py:occversiontuple executed by FreeCAD Python"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/exportDRAWEXE.py"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("occversiontuple() -> tuple[int, int, int]"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("tuple[int, int, int]"));
|
||||
result.insert(QStringLiteral("result"), version);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-source"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Sandbox:function:ax2_xdir")
|
||||
&& name == QStringLiteral("ax2_xdir")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
const QJsonObject callArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QJsonObject normal = callArgs.value(QStringLiteral("normal")).toObject();
|
||||
const QJsonValue x = normal.value(QStringLiteral("x"));
|
||||
const QJsonValue y = normal.value(QStringLiteral("y"));
|
||||
const QJsonValue z = normal.value(QStringLiteral("z"));
|
||||
if (!x.isDouble() || !y.isDouble() || !z.isDouble()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.ax2_xdir requires normal={x,y,z} numeric components"));
|
||||
return result;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* freecad = PyImport_ImportModule("FreeCAD");
|
||||
PyObject* vector = freecad ? PyObject_GetAttrString(freecad, "Vector") : nullptr;
|
||||
PyObject* vectorArgs = Py_BuildValue("(ddd)", x.toDouble(), y.toDouble(), z.toDouble());
|
||||
PyObject* normalObject = vector ? PyObject_CallObject(vector, vectorArgs) : nullptr;
|
||||
Py_DECREF(vectorArgs);
|
||||
Py_XDECREF(vector);
|
||||
Py_XDECREF(freecad);
|
||||
if (!normalObject) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
PyDict_SetItemString(globals, "_ax2_normal", normalObject);
|
||||
const char* script =
|
||||
"source = open('/freecad-mod/Sandbox/exportDRAWEXE.py', encoding='utf-8').read()\n"
|
||||
"namespace = {'__name__': 'Sandbox.exportDRAWEXE', '__file__': '/freecad-mod/Sandbox/exportDRAWEXE.py'}\n"
|
||||
"exec(compile(source, '/freecad-mod/Sandbox/exportDRAWEXE.py', 'exec'), namespace, namespace)\n"
|
||||
"_ax2_result = namespace['ax2_xdir'](_ax2_normal)\n";
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
Py_DECREF(normalObject);
|
||||
if (!run) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* pyResult = PyDict_GetItemString(globals, "_ax2_result");
|
||||
PyObject* pyX = pyResult ? PyObject_GetAttrString(pyResult, "x") : nullptr;
|
||||
PyObject* pyY = pyResult ? PyObject_GetAttrString(pyResult, "y") : nullptr;
|
||||
PyObject* pyZ = pyResult ? PyObject_GetAttrString(pyResult, "z") : nullptr;
|
||||
if (!pyX || !pyY || !pyZ || !PyFloat_Check(pyX) || !PyFloat_Check(pyY) || !PyFloat_Check(pyZ)) {
|
||||
Py_XDECREF(pyX); Py_XDECREF(pyY); Py_XDECREF(pyZ);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.ax2_xdir returned a non-Vector result"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
QJsonObject vectorResult;
|
||||
vectorResult.insert(QStringLiteral("x"), PyFloat_AsDouble(pyX));
|
||||
vectorResult.insert(QStringLiteral("y"), PyFloat_AsDouble(pyY));
|
||||
vectorResult.insert(QStringLiteral("z"), PyFloat_AsDouble(pyZ));
|
||||
Py_DECREF(pyX); Py_DECREF(pyY); Py_DECREF(pyZ);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_execution"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("official Sandbox exportDRAWEXE.py:ax2_xdir executed by FreeCAD Python"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/exportDRAWEXE.py"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("ax2_xdir(normal: Vector) -> Vector"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Vector"));
|
||||
result.insert(QStringLiteral("result"), vectorResult);
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-source"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")
|
||||
&& apiId == QStringLiteral("py:Sandbox:function:f2s")
|
||||
&& name == QStringLiteral("f2s")
|
||||
&& family == QStringLiteral("pure-function")) {
|
||||
const QJsonObject callArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QJsonValue value = callArgs.value(QStringLiteral("value"));
|
||||
const QJsonValue angle = callArgs.value(QStringLiteral("angle"));
|
||||
const QJsonValue axis = callArgs.value(QStringLiteral("axis"));
|
||||
if (!value.isDouble() || (!angle.isUndefined() && !angle.isBool()) || (!axis.isUndefined() && !axis.isBool())) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.f2s requires numeric value and optional boolean angle/axis arguments"));
|
||||
return result;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script =
|
||||
"source = open('/freecad-mod/Sandbox/exportDRAWEXE.py', encoding='utf-8').read()\n"
|
||||
"namespace = {'__name__': 'Sandbox.exportDRAWEXE', '__file__': '/freecad-mod/Sandbox/exportDRAWEXE.py'}\n"
|
||||
"exec(compile(source, '/freecad-mod/Sandbox/exportDRAWEXE.py', 'exec'), namespace, namespace)\n"
|
||||
"_f2s_result = namespace['f2s'](_f2s_value, _f2s_angle, _f2s_axis)\n";
|
||||
PyObject* pyValue = PyFloat_FromDouble(value.toDouble());
|
||||
PyObject* pyAngle = PyBool_FromLong(angle.isUndefined() ? 0 : (angle.toBool() ? 1 : 0));
|
||||
PyObject* pyAxis = PyBool_FromLong(axis.isUndefined() ? 0 : (axis.toBool() ? 1 : 0));
|
||||
PyDict_SetItemString(globals, "_f2s_value", pyValue);
|
||||
PyDict_SetItemString(globals, "_f2s_angle", pyAngle);
|
||||
PyDict_SetItemString(globals, "_f2s_axis", pyAxis);
|
||||
Py_DECREF(pyValue); Py_DECREF(pyAngle); Py_DECREF(pyAxis);
|
||||
PyObject* run = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!run) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromStdString(pythonError()));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
Py_DECREF(run);
|
||||
PyObject* pyResult = PyDict_GetItemString(globals, "_f2s_result");
|
||||
if (!pyResult || !PyUnicode_Check(pyResult)) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("source_error"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox.f2s returned a non-string result"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_execution"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("official Sandbox exportDRAWEXE.py:f2s executed by FreeCAD Python"));
|
||||
result.insert(QStringLiteral("sourceEntry"), QStringLiteral("src/Mod/Sandbox/exportDRAWEXE.py"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("f2s(value: float, angle: bool = False, axis: bool = False) -> str"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("string"));
|
||||
result.insert(QStringLiteral("result"), QString::fromUtf8(PyUnicode_AsUTF8(pyResult)));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-python-source"));
|
||||
Py_DECREF(globals);
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Sandbox API record is outside the Tier-1 adapter contract"));
|
||||
return result;
|
||||
}
|
||||
|
||||
void clearAction()
|
||||
{
|
||||
actionErrorCode.clear();
|
||||
@@ -862,4 +1458,54 @@ EMSCRIPTEN_KEEPALIVE int fc_web_sandbox_module_visible()
|
||||
return moduleVisible ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
pythonFamilyDispatchResponse.clear();
|
||||
if (!request || *request == '\0') {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Sandbox native dispatch request is empty"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Sandbox native dispatch requires a JSON object"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
const auto object = document.object();
|
||||
const auto command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("sandbox.pythonFamilyBatch")) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Sandbox native dispatch command is not registered"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
const auto args = object.value(QStringLiteral("args")).toObject();
|
||||
const auto tier = args.value(QStringLiteral("tier")).toString();
|
||||
const auto records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"sandbox.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
if (!ensureSandbox()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage));
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probePythonFamilyRecord(value.toObject(), tier));
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-sandbox/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Sandbox"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
389
src/WebAssembly/FreeCADCoreProbe/ShowRuntimeProbe.cpp
Normal file
389
src/WebAssembly/FreeCADCoreProbe/ShowRuntimeProbe.cpp
Normal file
@@ -0,0 +1,389 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr const char* sourceEntry = "src/Mod/Show/__init__.py";
|
||||
constexpr const char* sourcePath = "/freecad-mod/Show/__init__.py";
|
||||
|
||||
std::string errorMessage;
|
||||
std::string apiError;
|
||||
int initializationCalls = 0;
|
||||
int initializationRuns = 0;
|
||||
int moduleAvailable = 0;
|
||||
int apiCount = 0;
|
||||
int tempoState = -1;
|
||||
int resourcesReleased = 0;
|
||||
int dependencyProbe = 0;
|
||||
std::string familyDispatchResponse;
|
||||
constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
std::string pythonError()
|
||||
{
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "PythonError";
|
||||
if (type) {
|
||||
PyObject* name = PyObject_GetAttrString(type, "__name__");
|
||||
if (name) {
|
||||
message = PyUnicode_AsUTF8(name);
|
||||
Py_DECREF(name);
|
||||
}
|
||||
}
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
message += ": ";
|
||||
message += PyUnicode_AsUTF8(text);
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
bool addShowPath()
|
||||
{
|
||||
const char* script =
|
||||
"import sys\n"
|
||||
"_show_path = '/freecad-mod'\n"
|
||||
"if _show_path not in sys.path:\n"
|
||||
" sys.path.insert(0, _show_path)\n";
|
||||
if (PyRun_SimpleString(script) != 0) {
|
||||
errorMessage = pythonError();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool exposeGuiFreeFlag()
|
||||
{
|
||||
PyObject* freecad = PyImport_ImportModule("FreeCAD");
|
||||
if (!freecad) {
|
||||
errorMessage = pythonError();
|
||||
return false;
|
||||
}
|
||||
const int result = PyObject_SetAttrString(freecad, "GuiUp", Py_False);
|
||||
Py_DECREF(freecad);
|
||||
if (result != 0) {
|
||||
errorMessage = pythonError();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ensureRuntime()
|
||||
{
|
||||
++initializationCalls;
|
||||
if (moduleAvailable) {
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
if (!exposeGuiFreeFlag()) {
|
||||
return false;
|
||||
}
|
||||
if (!addShowPath()) {
|
||||
return false;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Show");
|
||||
if (!module) {
|
||||
errorMessage = pythonError();
|
||||
return false;
|
||||
}
|
||||
const bool hasTempoVis = PyObject_HasAttrString(module, "TempoVis") == 1;
|
||||
const bool hasDepGraph = PyObject_HasAttrString(module, "DepGraphTools") == 1;
|
||||
Py_DECREF(module);
|
||||
if (!hasTempoVis || !hasDepGraph) {
|
||||
errorMessage = "registration_mismatch";
|
||||
return false;
|
||||
}
|
||||
moduleAvailable = 1;
|
||||
++initializationRuns;
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
errorMessage.clear();
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
errorMessage = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
errorMessage = error.what();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool readInt(PyObject* globals, const char* name, int& target)
|
||||
{
|
||||
PyObject* value = PyDict_GetItemString(globals, name);
|
||||
if (!value || !PyLong_Check(value)) {
|
||||
return false;
|
||||
}
|
||||
target = static_cast<int>(PyLong_AsLong(value));
|
||||
return !PyErr_Occurred();
|
||||
}
|
||||
|
||||
bool executeScript(const char* script, PyObject** globalsOut)
|
||||
{
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* result = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!result) {
|
||||
errorMessage = pythonError();
|
||||
Py_DECREF(globals);
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
*globalsOut = globals;
|
||||
return true;
|
||||
}
|
||||
|
||||
int countApi()
|
||||
{
|
||||
PyObject* module = PyImport_ImportModule("Show");
|
||||
if (!module) {
|
||||
apiError = pythonError();
|
||||
return 0;
|
||||
}
|
||||
const char* names[] = {"TempoVis", "DepGraphTools"};
|
||||
int count = 0;
|
||||
for (const char* name : names) {
|
||||
count += PyObject_HasAttrString(module, name) ? 1 : 0;
|
||||
}
|
||||
Py_DECREF(module);
|
||||
return count;
|
||||
}
|
||||
|
||||
std::string moduleForSourcePath(const QString& sourcePath)
|
||||
{
|
||||
QString module = sourcePath;
|
||||
if (module.startsWith(QStringLiteral("src/Mod/"))) module = module.mid(8);
|
||||
if (module.endsWith(QStringLiteral(".py"))) module.chop(3);
|
||||
module.replace('/', '.');
|
||||
return module.toStdString();
|
||||
}
|
||||
|
||||
QJsonObject probeFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
if (!apiId.startsWith(QStringLiteral("py:Show:")) || name.isEmpty() || family.isEmpty() || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Show API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
if (name == QStringLiteral("Workbench")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Show Workbench API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
const std::string moduleName = moduleForSourcePath(sourcePath);
|
||||
PyObject* module = PyImport_ImportModule(moduleName.c_str());
|
||||
if (!module) {
|
||||
PyErr_Clear();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_python_import_failed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Show Python source module could not be imported by the headless runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
return result;
|
||||
}
|
||||
bool resolved = false;
|
||||
if (name.contains(QStringLiteral("."))) {
|
||||
const auto parts = name.split('.');
|
||||
if (parts.size() == 2) {
|
||||
PyObject* owner = PyObject_GetAttrString(module, parts[0].toUtf8().constData());
|
||||
resolved = owner && PyObject_HasAttrString(owner, parts[1].toUtf8().constData());
|
||||
Py_XDECREF(owner);
|
||||
}
|
||||
} else {
|
||||
resolved = PyObject_HasAttrString(module, name.toUtf8().constData());
|
||||
}
|
||||
Py_DECREF(module);
|
||||
result.insert(QStringLiteral("status"), resolved ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), resolved ? (name.contains('.') ? QStringLiteral("native_object_method") : QStringLiteral("native_python_symbol")) : QStringLiteral("native_python_symbol_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), resolved ? QStringLiteral("Show Python symbol/method is registered and resolved by FreeCAD") : QStringLiteral("Show Python symbol/method could not be resolved by the headless runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), name.contains('.') ? QStringLiteral("source-declared") : QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), name.contains('.') ? QStringLiteral("source-declared") : QStringLiteral("Show.%1").arg(name));
|
||||
if (resolved) result.insert(QStringLiteral("replay"), name.contains('.') ? QStringLiteral("native-object-method") : QStringLiteral("native-python-reflection"));
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_initialize()
|
||||
{
|
||||
errorMessage.clear();
|
||||
return ensureRuntime() ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_initialization_calls() { return initializationCalls; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_initialization_runs() { return initializationRuns; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_module_available() { return moduleAvailable; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_show_last_error() { return errorMessage.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_show_source_entry() { return sourceEntry; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_show_source_path() { return sourcePath; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_source_inventory_validate(const char* entry)
|
||||
{
|
||||
if (!entry || std::string(entry) != sourceEntry) {
|
||||
errorMessage = "revision_mismatch";
|
||||
return 0;
|
||||
}
|
||||
return ensureRuntime() ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_python_api_validate(const char* entry)
|
||||
{
|
||||
if (!entry || std::string(entry) != sourceEntry) {
|
||||
apiError = "revision_mismatch";
|
||||
return 0;
|
||||
}
|
||||
if (!ensureRuntime()) {
|
||||
apiError = errorMessage;
|
||||
return 0;
|
||||
}
|
||||
apiCount = countApi();
|
||||
apiError.clear();
|
||||
return apiCount == 2 ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_python_api()
|
||||
{
|
||||
if (!ensureRuntime()) {
|
||||
apiError = errorMessage;
|
||||
return 0;
|
||||
}
|
||||
const char* script =
|
||||
"import FreeCAD as App\n"
|
||||
"import Show\n"
|
||||
"from Show.SceneDetail import SceneDetail\n"
|
||||
"from Show import Containers, TVStack\n"
|
||||
"doc = App.newDocument('ShowWeb')\n"
|
||||
"tv = Show.TempoVis(doc, None, tag='web-fixture')\n"
|
||||
"_show_tempo_state = tv.state\n"
|
||||
"_show_api_count = sum(hasattr(Show, name) for name in ('TempoVis', 'DepGraphTools'))\n"
|
||||
"_show_scene_detail = SceneDetail.__name__\n"
|
||||
"_show_container = Containers.Container.__name__\n"
|
||||
"_show_stack = TVStack.TVStack.__name__\n"
|
||||
"tv.restore()\n"
|
||||
"App.closeDocument(doc.Name)\n"
|
||||
"_show_resources_released = len(App.listDocuments()) == 0\n";
|
||||
PyObject* globals = nullptr;
|
||||
if (!executeScript(script, &globals)) {
|
||||
apiError = errorMessage;
|
||||
return 0;
|
||||
}
|
||||
int scriptApiCount = 0;
|
||||
int released = 0;
|
||||
const bool valid = readInt(globals, "_show_api_count", scriptApiCount)
|
||||
&& readInt(globals, "_show_tempo_state", tempoState)
|
||||
&& readInt(globals, "_show_resources_released", released);
|
||||
Py_DECREF(globals);
|
||||
apiCount = countApi();
|
||||
resourcesReleased = released;
|
||||
dependencyProbe = valid && scriptApiCount == 2 && tempoState == 0 ? 1 : 0;
|
||||
apiError.clear();
|
||||
return valid && apiCount == 2 && scriptApiCount == 2 && tempoState == 0 && resourcesReleased == 1;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_dependency_probe(const char* name)
|
||||
{
|
||||
if (!ensureRuntime()) {
|
||||
dependencyProbe = 0;
|
||||
return 0;
|
||||
}
|
||||
if (!name || !*name) {
|
||||
errorMessage = "invalid_argument";
|
||||
dependencyProbe = 0;
|
||||
return 0;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Show");
|
||||
if (!module) {
|
||||
errorMessage = pythonError();
|
||||
dependencyProbe = 0;
|
||||
return 0;
|
||||
}
|
||||
const bool known = PyObject_HasAttrString(module, name) == 1;
|
||||
Py_DECREF(module);
|
||||
if (!known) {
|
||||
errorMessage = "type_not_found";
|
||||
dependencyProbe = 0;
|
||||
return 0;
|
||||
}
|
||||
errorMessage.clear();
|
||||
dependencyProbe = 1;
|
||||
return 1;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_python_api_count() { return apiCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_tempo_state() { return tempoState; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_resources_released() { return resourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_show_dependency_available() { return dependencyProbe; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_show_api_error() { return apiError.c_str(); }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
familyDispatchResponse.clear();
|
||||
if (!request || *request == '\0') { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Show native dispatch request is empty"})"; return familyDispatchResponse.c_str(); }
|
||||
QJsonParseError parseError;
|
||||
const auto document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Show native dispatch requires a JSON object"})"; return familyDispatchResponse.c_str(); }
|
||||
const auto object = document.object();
|
||||
const auto command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("show.pythonFamilyBatch")) { familyDispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Show native dispatch command is not registered"})"; return familyDispatchResponse.c_str(); }
|
||||
const auto args = object.value(QStringLiteral("args")).toObject();
|
||||
const auto tier = args.value(QStringLiteral("tier")).toString();
|
||||
const auto records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"show.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records"})"; return familyDispatchResponse.c_str(); }
|
||||
if (!ensureRuntime()) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable")); failure.insert(QStringLiteral("error"), QString::fromStdString(errorMessage)); familyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return familyDispatchResponse.c_str(); }
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probeFamilyRecord(value.toObject()));
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-show/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Show"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
familyDispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
return familyDispatchResponse.c_str();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
3
src/WebAssembly/FreeCADCoreProbe/SketcherKernelProbe.cpp
Normal file
3
src/WebAssembly/FreeCADCoreProbe/SketcherKernelProbe.cpp
Normal file
@@ -0,0 +1,3 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
// Compatibility translation unit for legacy probe inventory diagnostics.
|
||||
// The maintained Sketcher native implementation is SketcherRuntimeProbe.cpp.
|
||||
File diff suppressed because it is too large
Load Diff
993
src/WebAssembly/FreeCADCoreProbe/SpreadsheetRuntimeProbe.cpp
Normal file
993
src/WebAssembly/FreeCADCoreProbe/SpreadsheetRuntimeProbe.cpp
Normal file
@@ -0,0 +1,993 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Spreadsheet/App/Cell.h>
|
||||
#include <Mod/Spreadsheet/App/Sheet.h>
|
||||
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QFile>
|
||||
#include <QString>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <set>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Spreadsheet();
|
||||
|
||||
namespace {
|
||||
|
||||
std::string lastError;
|
||||
std::string typeName;
|
||||
std::string cellA1;
|
||||
std::string cellB1;
|
||||
std::string recoveryError;
|
||||
std::string recoveryBefore;
|
||||
std::string recoveryAfter;
|
||||
std::string inventoryError;
|
||||
std::string inventoryEntry;
|
||||
std::string inventorySummary;
|
||||
std::string inventorySourceFiles;
|
||||
std::string inventoryFormats;
|
||||
std::string pythonApiError;
|
||||
std::string pythonApiA1;
|
||||
std::string pythonApiB1;
|
||||
std::string pythonRecoveryError;
|
||||
std::string pythonRecoveryBefore;
|
||||
std::string pythonRecoveryAfter;
|
||||
std::string persistenceRecoveryError;
|
||||
std::string persistenceRecoveryBefore;
|
||||
std::string persistenceRecoveryAfter;
|
||||
std::string persistenceError;
|
||||
std::string persistencePath;
|
||||
std::string persistenceA1;
|
||||
std::string persistenceB1;
|
||||
int initializationCalls = 0;
|
||||
int initializationRuns = 0;
|
||||
int moduleAvailable = 0;
|
||||
int typeCount = 0;
|
||||
int objectCount = 0;
|
||||
int recomputeCount = 0;
|
||||
int recomputeHasError = 0;
|
||||
int createResourcesReleased = 0;
|
||||
int recoveryRejected = 0;
|
||||
int recoveryRepeated = 0;
|
||||
int recoveryResourcesReleased = 0;
|
||||
int inventoryRegisteredTypes = 0;
|
||||
int inventoryFormatCount = 0;
|
||||
int inventoryPythonBindings = 0;
|
||||
int inventoryResourcesReleased = 0;
|
||||
int pythonApiCount = 0;
|
||||
int pythonApiResourcesReleased = 0;
|
||||
int pythonRecoveryRejected = 0;
|
||||
int pythonRecoveryRepeated = 0;
|
||||
int pythonRecoveryResourcesReleased = 0;
|
||||
int persistenceRecoveryRejected = 0;
|
||||
int persistenceRecoveryRecovered = 0;
|
||||
int persistenceRecoveryResourcesReleased = 0;
|
||||
int persistenceSize = 0;
|
||||
int persistenceObjectCount = 0;
|
||||
int persistenceResourcesReleased = 0;
|
||||
int persistenceRoundTrip = 0;
|
||||
std::string pythonFamilyDispatchResponse;
|
||||
constexpr const char* spreadsheetPythonSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
std::string pythonError()
|
||||
{
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "PythonError";
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
message = PyUnicode_AsUTF8(text);
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
void addSpreadsheetModule()
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (PyDict_GetItemString(modules, "Spreadsheet")) {
|
||||
return;
|
||||
}
|
||||
PyObject* module = PyInit_Spreadsheet();
|
||||
if (!module) {
|
||||
throw Base::RuntimeError("PyInit_Spreadsheet failed: " + pythonError());
|
||||
}
|
||||
if (PyDict_SetItemString(modules, "Spreadsheet", module) != 0) {
|
||||
Py_DECREF(module);
|
||||
throw Base::RuntimeError("failed to register Spreadsheet");
|
||||
}
|
||||
Py_DECREF(module);
|
||||
}
|
||||
|
||||
bool ensureSpreadsheet()
|
||||
{
|
||||
++initializationCalls;
|
||||
if (moduleAvailable) {
|
||||
lastError.clear();
|
||||
return true;
|
||||
}
|
||||
++initializationRuns;
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
addSpreadsheetModule();
|
||||
if (Base::Type::fromName("Spreadsheet::Sheet").isBad()) {
|
||||
lastError = "Spreadsheet::Sheet registration missing";
|
||||
return false;
|
||||
}
|
||||
moduleAvailable = 1;
|
||||
typeCount = 1;
|
||||
lastError.clear();
|
||||
return true;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
lastError = "unknown Spreadsheet initialization failure";
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void closeDocument(App::Document*& document)
|
||||
{
|
||||
if (document) {
|
||||
App::GetApplication().closeDocument(document);
|
||||
document = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
Spreadsheet::Sheet* createSheet(App::Document*& document, const char* name);
|
||||
|
||||
QJsonObject importExportCsv(const QJsonObject& args)
|
||||
{
|
||||
const QString csv = args.value(QStringLiteral("csv")).toString();
|
||||
const QString delimiter = args.value(QStringLiteral("delimiter")).toString(QStringLiteral(","));
|
||||
const QString quote = args.value(QStringLiteral("quote")).toString(QStringLiteral("\""));
|
||||
const QString escape = args.value(QStringLiteral("escape")).toString(QStringLiteral("\\"));
|
||||
if (csv.isEmpty() || delimiter.size() != 1 || quote.size() != 1 || escape.size() != 1
|
||||
|| delimiter.at(0).toLatin1() == '\0' || quote.at(0).toLatin1() == '\0' || escape.at(0).toLatin1() == '\0') {
|
||||
throw Base::ValueError("spreadsheet.importExportCsv requires non-empty csv and single-character delimiter, quote, and escape");
|
||||
}
|
||||
|
||||
const QString inputPath = QStringLiteral("/tmp/FreeCADWebSpreadsheetImport.csv");
|
||||
const QString outputPath = QStringLiteral("/tmp/FreeCADWebSpreadsheetExport.csv");
|
||||
App::Document* document = nullptr;
|
||||
QFile::remove(inputPath);
|
||||
QFile::remove(outputPath);
|
||||
try {
|
||||
QFile input(inputPath);
|
||||
if (!input.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
|
||||
throw Base::RuntimeError("unable to create Spreadsheet CSV input");
|
||||
}
|
||||
const QByteArray inputBytes = csv.toUtf8();
|
||||
if (input.write(inputBytes) != inputBytes.size()) {
|
||||
throw Base::RuntimeError("unable to write complete Spreadsheet CSV input");
|
||||
}
|
||||
input.close();
|
||||
|
||||
auto* sheet = createSheet(document, "SpreadsheetCsvWorkflow");
|
||||
if (!sheet->importFromFile(inputPath.toStdString(), delimiter.at(0).toLatin1(), quote.at(0).toLatin1(), escape.at(0).toLatin1())) {
|
||||
throw Base::RuntimeError("Spreadsheet CSV import failed");
|
||||
}
|
||||
bool recomputeError = false;
|
||||
document->recompute({}, false, &recomputeError);
|
||||
if (recomputeError) throw Base::RuntimeError("Spreadsheet CSV recompute failed");
|
||||
if (!sheet->exportToFile(outputPath.toStdString(), delimiter.at(0).toLatin1(), quote.at(0).toLatin1(), escape.at(0).toLatin1())) {
|
||||
throw Base::RuntimeError("Spreadsheet CSV export failed");
|
||||
}
|
||||
QFile output(outputPath);
|
||||
if (!output.open(QIODevice::ReadOnly)) throw Base::RuntimeError("unable to read Spreadsheet CSV export");
|
||||
const QByteArray exported = output.readAll();
|
||||
const auto used = sheet->getUsedRange();
|
||||
const std::string usedRange = std::get<0>(used).toString() + ":" + std::get<1>(used).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("ok"), true);
|
||||
result.insert(QStringLiteral("cmd"), QStringLiteral("spreadsheet.importExportCsv"));
|
||||
result.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-spreadsheet/csv-import-export/v1"));
|
||||
result.insert(QStringLiteral("document"), QString::fromUtf8(document->getName()));
|
||||
result.insert(QStringLiteral("object"), QString::fromUtf8(sheet->getNameInDocument()));
|
||||
result.insert(QStringLiteral("objectType"), QString::fromUtf8(sheet->getTypeId().getName()));
|
||||
result.insert(QStringLiteral("usedRange"), QString::fromStdString(usedRange));
|
||||
result.insert(QStringLiteral("csv"), QString::fromUtf8(exported));
|
||||
result.insert(QStringLiteral("importBytes"), inputBytes.size());
|
||||
result.insert(QStringLiteral("exportBytes"), exported.size());
|
||||
result.insert(QStringLiteral("recomputed"), true);
|
||||
closeDocument(document);
|
||||
QFile::remove(inputPath);
|
||||
QFile::remove(outputPath);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
return result;
|
||||
}
|
||||
catch (...) {
|
||||
closeDocument(document);
|
||||
QFile::remove(inputPath);
|
||||
QFile::remove(outputPath);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
QJsonObject probePythonFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(spreadsheetPythonSourceRevision));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
if (apiId.startsWith(QStringLiteral("Spreadsheet:desktop:"))) {
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignTop")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignVCenter")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignBottom")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignCenter")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignLeft")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_AlignRight")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_CreateSheet")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_Export")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_Import")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_MergeCells")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_SetAlias")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_SplitCell")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_StyleBold")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_StyleItalic")
|
||||
// FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Spreadsheet_StyleUnderline")
|
||||
const QString command = apiId.mid(QStringLiteral("Spreadsheet:desktop:").size());
|
||||
const QJsonObject args = input.value(QStringLiteral("args")).toObject();
|
||||
const QString range = args.value(QStringLiteral("range")).toString(QStringLiteral("A1"));
|
||||
const QString sheetName = args.value(QStringLiteral("sheet")).toString(QStringLiteral("Sheet"));
|
||||
App::Document* desktopDocument = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) throw Base::RuntimeError(lastError.c_str());
|
||||
auto* sheet = createSheet(desktopDocument, "SpreadsheetWebDesktop");
|
||||
sheet->setCell("A1", "1");
|
||||
if (command == QStringLiteral("Spreadsheet_MergeCells")) { sheet->mergeCells(App::Range(range.toUtf8().constData())); result.insert(QStringLiteral("status"), QStringLiteral("exposed")); }
|
||||
else if (command == QStringLiteral("Spreadsheet_SplitCell")) { sheet->splitCell(App::CellAddress(range.toStdString().c_str())); result.insert(QStringLiteral("status"), QStringLiteral("exposed")); }
|
||||
else if (command == QStringLiteral("Spreadsheet_SetAlias")) { sheet->setAlias(App::CellAddress(range.toStdString().c_str()), args.value(QStringLiteral("alias")).toString().toStdString()); result.insert(QStringLiteral("status"), QStringLiteral("exposed")); }
|
||||
else if (command == QStringLiteral("Spreadsheet_StyleBold") || command == QStringLiteral("Spreadsheet_StyleItalic") || command == QStringLiteral("Spreadsheet_StyleUnderline")) {
|
||||
std::set<std::string> styles; styles.insert(command == QStringLiteral("Spreadsheet_StyleBold") ? "bold" : command == QStringLiteral("Spreadsheet_StyleItalic") ? "italic" : "underline");
|
||||
sheet->setStyle(App::CellAddress(range.toStdString().c_str()), styles);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else if (command == QStringLiteral("Spreadsheet_AlignTop") || command == QStringLiteral("Spreadsheet_AlignVCenter") || command == QStringLiteral("Spreadsheet_AlignLeft") || command == QStringLiteral("Spreadsheet_AlignCenter") || command == QStringLiteral("Spreadsheet_AlignRight") || command == QStringLiteral("Spreadsheet_AlignBottom")) {
|
||||
const char* alignment = command == QStringLiteral("Spreadsheet_AlignTop") ? "top" : command == QStringLiteral("Spreadsheet_AlignVCenter") ? "vcenter" : command == QStringLiteral("Spreadsheet_AlignLeft") ? "left" : command == QStringLiteral("Spreadsheet_AlignCenter") ? "center" : command == QStringLiteral("Spreadsheet_AlignRight") ? "right" : "bottom";
|
||||
App::Range cells(range.toUtf8().constData());
|
||||
const int alignmentCode = Spreadsheet::Cell::decodeAlignment(alignment, 0);
|
||||
do {
|
||||
sheet->setAlignment(*cells, alignmentCode);
|
||||
} while (cells.next());
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("desktop_command_executed"));
|
||||
result.insert(QStringLiteral("command"), command);
|
||||
result.insert(QStringLiteral("range"), range);
|
||||
result.insert(QStringLiteral("alignment"), QString::fromUtf8(alignment));
|
||||
}
|
||||
else if (command == QStringLiteral("Spreadsheet_CreateSheet")) {
|
||||
const QString name = args.value(QStringLiteral("name")).toString(QStringLiteral("Sheet2"));
|
||||
if (!desktopDocument->addObject("Spreadsheet::Sheet", name.toStdString().c_str())) throw Base::RuntimeError("Spreadsheet_CreateSheet failed");
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("createdSheet"), name);
|
||||
}
|
||||
else if (command == QStringLiteral("Spreadsheet_Import")) {
|
||||
const QString path = args.value(QStringLiteral("path")).toString();
|
||||
if (path.isEmpty()) throw Base::RuntimeError("Spreadsheet_Import requires args.path");
|
||||
char delim, quote, escape; std::string error;
|
||||
if (!sheet->getCharsFromPrefs(delim, quote, escape, error)) throw Base::RuntimeError(error.c_str());
|
||||
sheet->importFromFile(path.toStdString(), delim, quote, escape);
|
||||
sheet->execute();
|
||||
result.insert(QStringLiteral("path"), path);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else if (command == QStringLiteral("Spreadsheet_Export")) {
|
||||
const QString path = args.value(QStringLiteral("path")).toString();
|
||||
if (path.isEmpty()) throw Base::RuntimeError("Spreadsheet_Export requires args.path");
|
||||
char delim, quote, escape; std::string error;
|
||||
if (!sheet->getCharsFromPrefs(delim, quote, escape, error)) throw Base::RuntimeError(error.c_str());
|
||||
if (!sheet->exportToFile(path.toStdString(), delim, quote, escape)) throw Base::RuntimeError("Spreadsheet export failed");
|
||||
result.insert(QStringLiteral("path"), path);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
}
|
||||
else {
|
||||
throw Base::RuntimeError("Spreadsheet desktop command is not registered");
|
||||
}
|
||||
desktopDocument->recompute();
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("desktop_command_executed"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Spreadsheet desktop command executed in native Document"));
|
||||
result.insert(QStringLiteral("replay"), command);
|
||||
App::GetApplication().closeDocument(desktopDocument);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
return result;
|
||||
} catch (const std::exception& error) {
|
||||
if (desktopDocument) App::GetApplication().closeDocument(desktopDocument);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("desktop_command_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(error.what()));
|
||||
return result;
|
||||
}
|
||||
}
|
||||
const bool moduleMatch = apiId.startsWith(QStringLiteral("py:Spreadsheet:")) && !apiId.contains(QStringLiteral(".."));
|
||||
if (!moduleMatch || name.isEmpty() || family.isEmpty() || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Spreadsheet API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
const bool guiPath = family == QStringLiteral("view-resource")
|
||||
|| sourcePath.contains(QStringLiteral("/Gui/"))
|
||||
|| sourcePath.endsWith(QStringLiteral("InitGui.py"));
|
||||
if (guiPath || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Spreadsheet GUI/view API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Spreadsheet API requires a nonportable external capability"));
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Spreadsheet Python symbol/method has no method-level native argument/return replay"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
return result;
|
||||
}
|
||||
|
||||
Spreadsheet::Sheet* createSheet(App::Document*& document, const char* name)
|
||||
{
|
||||
document = App::GetApplication().newDocument(name, name, {false, true});
|
||||
if (!document) {
|
||||
throw Base::RuntimeError("Application::newDocument returned null");
|
||||
}
|
||||
auto* object = document->addObject("Spreadsheet::Sheet", "Sheet");
|
||||
auto* sheet = dynamic_cast<Spreadsheet::Sheet*>(object);
|
||||
if (!sheet) {
|
||||
throw Base::RuntimeError("Document::addObject returned a non-Sheet object");
|
||||
}
|
||||
typeName = sheet->getTypeId().getName();
|
||||
return sheet;
|
||||
}
|
||||
|
||||
bool readCell(Spreadsheet::Sheet& sheet, const char* address, std::string& value)
|
||||
{
|
||||
auto* cell = sheet.getCell(App::CellAddress(address));
|
||||
if (!cell || !cell->getStringContent(value)) {
|
||||
return false;
|
||||
}
|
||||
if (!value.empty() && value.front() == '\'') {
|
||||
value.erase(value.begin());
|
||||
}
|
||||
value.erase(std::remove_if(value.begin(), value.end(), [](unsigned char character) {
|
||||
return std::isspace(character) != 0;
|
||||
}), value.end());
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_initialize()
|
||||
{
|
||||
lastError.clear();
|
||||
return ensureSpreadsheet() ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_initialization_calls() { return initializationCalls; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_initialization_runs() { return initializationRuns; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_module_available() { return moduleAvailable; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_type_count() { return typeCount; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_type_name() { return typeName.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_last_error() { return lastError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_object_count() { return objectCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recompute_count() { return recomputeCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recompute_has_error() { return recomputeHasError; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_create_resources_released() { return createResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_cell_a1() { return cellA1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_cell_b1() { return cellB1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_recovery_error() { return recoveryError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_recovery_before() { return recoveryBefore.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_recovery_after() { return recoveryAfter.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recovery_rejected() { return recoveryRejected; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recovery_repeated() { return recoveryRepeated; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recovery_resources_released() { return recoveryResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_inventory_error() { return inventoryError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_inventory_entry() { return inventoryEntry.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_inventory_summary() { return inventorySummary.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_inventory_source_files() { return inventorySourceFiles.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_inventory_formats() { return inventoryFormats.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_inventory_registered_types() { return inventoryRegisteredTypes; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_inventory_format_count() { return inventoryFormatCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_inventory_python_bindings() { return inventoryPythonBindings; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_inventory_resources_released() { return inventoryResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_api_error() { return pythonApiError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_api_a1() { return pythonApiA1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_api_b1() { return pythonApiB1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_api_count() { return pythonApiCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_api_resources_released() { return pythonApiResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_recovery_error() { return pythonRecoveryError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_recovery_before() { return pythonRecoveryBefore.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_python_recovery_after() { return pythonRecoveryAfter.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_recovery_rejected() { return pythonRecoveryRejected; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_recovery_repeated() { return pythonRecoveryRepeated; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_recovery_resources_released() { return pythonRecoveryResourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_recovery_error() { return persistenceRecoveryError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_recovery_before() { return persistenceRecoveryBefore.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_recovery_after() { return persistenceRecoveryAfter.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_recovery_rejected() { return persistenceRecoveryRejected; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_recovery_recovered() { return persistenceRecoveryRecovered; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_recovery_resources_released() { return persistenceRecoveryResourcesReleased; }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_api()
|
||||
{
|
||||
if (!ensureSpreadsheet()) {
|
||||
return 0;
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Spreadsheet");
|
||||
if (!module) {
|
||||
lastError = pythonError();
|
||||
return 0;
|
||||
}
|
||||
// Sheet is registered as a PyCXX type for DocumentObject wrapping; the
|
||||
// module itself is the stable Python API boundary exposed by AppSpreadsheet.
|
||||
const bool hasModule = module != nullptr;
|
||||
Py_DECREF(module);
|
||||
if (!hasModule) {
|
||||
lastError = "Spreadsheet Python module import failed";
|
||||
}
|
||||
return hasModule ? 1 : 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_create_recompute()
|
||||
{
|
||||
lastError.clear();
|
||||
typeName.clear();
|
||||
cellA1.clear();
|
||||
cellB1.clear();
|
||||
objectCount = 0;
|
||||
recomputeCount = 0;
|
||||
recomputeHasError = 0;
|
||||
createResourcesReleased = 0;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
return 0;
|
||||
}
|
||||
auto* sheet = createSheet(document, "SpreadsheetCreate");
|
||||
sheet->setCell("A1", "21");
|
||||
sheet->setCell("B1", "=A1*2");
|
||||
bool hasError = false;
|
||||
recomputeCount = document->recompute({}, false, &hasError);
|
||||
recomputeHasError = hasError ? 1 : 0;
|
||||
const bool hasA1 = readCell(*sheet, "A1", cellA1);
|
||||
const bool hasB1 = readCell(*sheet, "B1", cellB1);
|
||||
objectCount = document->countObjects();
|
||||
const bool valid = typeName == "Spreadsheet::Sheet" && objectCount == 1
|
||||
&& recomputeCount == 1 && !hasError && hasA1 && hasB1 && cellA1 == "21"
|
||||
&& cellB1 == "=A1*2";
|
||||
closeDocument(document);
|
||||
createResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (!valid || createResourcesReleased != 1) {
|
||||
lastError = "Spreadsheet create/recompute contract mismatch";
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
lastError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
lastError = "unknown Spreadsheet create/recompute failure";
|
||||
}
|
||||
closeDocument(document);
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_save_reopen()
|
||||
{
|
||||
persistenceError.clear();
|
||||
persistencePath = "/tmp/SpreadsheetWeb.FCStd";
|
||||
persistenceA1.clear();
|
||||
persistenceB1.clear();
|
||||
persistenceSize = 0;
|
||||
persistenceObjectCount = 0;
|
||||
persistenceResourcesReleased = 0;
|
||||
persistenceRoundTrip = 0;
|
||||
App::Document* document = nullptr;
|
||||
App::Document* reopened = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
persistenceError = lastError;
|
||||
return 0;
|
||||
}
|
||||
auto* sheet = createSheet(document, "SpreadsheetPersistence");
|
||||
sheet->setCell("A1", "21");
|
||||
sheet->setCell("B1", "=A1*2");
|
||||
bool hasError = false;
|
||||
document->recompute({}, false, &hasError);
|
||||
if (hasError || !document->saveAs(persistencePath.c_str())) {
|
||||
throw Base::RuntimeError("Spreadsheet FCStd save failed");
|
||||
}
|
||||
persistenceSize = static_cast<int>(Base::FileInfo(persistencePath).size());
|
||||
closeDocument(document);
|
||||
|
||||
reopened = App::GetApplication().newDocument(
|
||||
"SpreadsheetPersistenceOpened", "Spreadsheet Persistence Opened", {false, true});
|
||||
if (!reopened) {
|
||||
throw Base::RuntimeError("Spreadsheet reopen document creation failed");
|
||||
}
|
||||
reopened->restore(persistencePath.c_str(), true, {});
|
||||
auto* restored = dynamic_cast<Spreadsheet::Sheet*>(reopened->getObject("Sheet"));
|
||||
if (!restored) {
|
||||
throw Base::RuntimeError("Spreadsheet FCStd restore omitted Sheet");
|
||||
}
|
||||
const bool hasA1 = readCell(*restored, "A1", persistenceA1);
|
||||
const bool hasB1 = readCell(*restored, "B1", persistenceB1);
|
||||
bool reopenedError = false;
|
||||
reopened->recompute({}, false, &reopenedError);
|
||||
persistenceObjectCount = reopened->countObjects();
|
||||
const bool valid = persistenceSize > 0 && persistenceObjectCount == 1
|
||||
&& !reopenedError && hasA1 && hasB1 && persistenceA1 == "21"
|
||||
&& persistenceB1 == "=A1*2";
|
||||
closeDocument(reopened);
|
||||
persistenceResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (!valid || persistenceResourcesReleased != 1) {
|
||||
throw Base::RuntimeError("Spreadsheet FCStd reopen contract mismatch");
|
||||
}
|
||||
persistenceRoundTrip = 1;
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
persistenceError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
persistenceError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
persistenceError = "unknown Spreadsheet save/reopen failure";
|
||||
}
|
||||
closeDocument(document);
|
||||
closeDocument(reopened);
|
||||
persistenceResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_recovery_probe()
|
||||
{
|
||||
recoveryError.clear();
|
||||
recoveryBefore.clear();
|
||||
recoveryAfter.clear();
|
||||
recoveryRejected = 0;
|
||||
recoveryRepeated = 0;
|
||||
recoveryResourcesReleased = 0;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
recoveryError = lastError;
|
||||
return 0;
|
||||
}
|
||||
auto* sheet = createSheet(document, "SpreadsheetRecovery");
|
||||
sheet->setCell("A1", "21");
|
||||
sheet->setCell("B1", "=A1*2");
|
||||
bool initialError = false;
|
||||
document->recompute({}, false, &initialError);
|
||||
std::string beforeA1;
|
||||
std::string beforeB1;
|
||||
if (initialError || !readCell(*sheet, "A1", beforeA1) || !readCell(*sheet, "B1", beforeB1)) {
|
||||
throw Base::RuntimeError("Spreadsheet recovery baseline recompute failed");
|
||||
}
|
||||
recoveryBefore = "A1=" + beforeA1 + ";B1=" + beforeB1;
|
||||
|
||||
bool rejected = false;
|
||||
try {
|
||||
sheet->setCell("C1", "=A1+");
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
recoveryError = error.what();
|
||||
rejected = !recoveryError.empty();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
recoveryError = error.what();
|
||||
rejected = !recoveryError.empty();
|
||||
}
|
||||
document->recompute();
|
||||
std::string afterA1;
|
||||
std::string afterB1;
|
||||
if (!readCell(*sheet, "A1", afterA1) || !readCell(*sheet, "B1", afterB1)) {
|
||||
throw Base::RuntimeError("Spreadsheet recovery state was lost");
|
||||
}
|
||||
recoveryAfter = "A1=" + afterA1 + ";B1=" + afterB1;
|
||||
recoveryRejected = rejected && recoveryBefore == recoveryAfter ? 1 : 0;
|
||||
|
||||
std::string repeatedError;
|
||||
try {
|
||||
sheet->setCell("C1", "=A1+");
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
repeatedError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
repeatedError = error.what();
|
||||
}
|
||||
recoveryRepeated = recoveryRejected && !recoveryError.empty() && repeatedError == recoveryError ? 1 : 0;
|
||||
closeDocument(document);
|
||||
recoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (!recoveryRejected || !recoveryRepeated || recoveryResourcesReleased != 1) {
|
||||
if (recoveryError.empty()) {
|
||||
recoveryError = "Spreadsheet recovery contract mismatch";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
recoveryError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
recoveryError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
recoveryError = "unknown Spreadsheet recovery failure";
|
||||
}
|
||||
closeDocument(document);
|
||||
recoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_source_inventory_validate(const char* sourceEntry)
|
||||
{
|
||||
constexpr const char* expectedEntry = "src/Mod/Spreadsheet/App/AppSpreadsheet.cpp";
|
||||
inventoryError.clear();
|
||||
if (!sourceEntry || std::string(sourceEntry) != expectedEntry) {
|
||||
inventoryError = "Spreadsheet source entry is not locked";
|
||||
return 0;
|
||||
}
|
||||
inventoryEntry.clear();
|
||||
inventorySummary.clear();
|
||||
inventorySourceFiles.clear();
|
||||
inventoryFormats.clear();
|
||||
inventoryRegisteredTypes = 0;
|
||||
inventoryFormatCount = 0;
|
||||
inventoryPythonBindings = 0;
|
||||
inventoryResourcesReleased = 0;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
inventoryError = lastError;
|
||||
return 0;
|
||||
}
|
||||
const char* types[] = {"Spreadsheet::Sheet"};
|
||||
for (const char* type : types) {
|
||||
if (!Base::Type::fromName(type).isBad()) {
|
||||
++inventoryRegisteredTypes;
|
||||
}
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Spreadsheet");
|
||||
if (module) {
|
||||
inventoryPythonBindings = 1;
|
||||
Py_DECREF(module);
|
||||
}
|
||||
inventoryEntry = expectedEntry;
|
||||
inventorySummary = "Spreadsheet::Sheet cell/property evaluation";
|
||||
inventorySourceFiles = "src/Mod/Spreadsheet/App/AppSpreadsheet.cpp,src/Mod/Spreadsheet/App/Sheet.cpp,src/Mod/Spreadsheet/App/Cell.cpp";
|
||||
inventoryFormats = ".csv";
|
||||
inventoryFormatCount = 1;
|
||||
inventoryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (inventoryRegisteredTypes != 1 || inventoryPythonBindings != 1 || inventoryFormatCount != 1
|
||||
|| inventoryResourcesReleased != 1) {
|
||||
inventoryError = "Spreadsheet source inventory contract mismatch";
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
inventoryError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
inventoryError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
inventoryError = "unknown Spreadsheet source inventory failure";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_api_probe()
|
||||
{
|
||||
pythonApiError.clear();
|
||||
pythonApiA1.clear();
|
||||
pythonApiB1.clear();
|
||||
pythonApiCount = 0;
|
||||
pythonApiResourcesReleased = 0;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
pythonApiError = lastError;
|
||||
return 0;
|
||||
}
|
||||
PyObject* globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script =
|
||||
"import FreeCAD as App\n"
|
||||
"import Spreadsheet\n"
|
||||
"doc = App.newDocument('SpreadsheetPython')\n"
|
||||
"sheet = doc.addObject('Spreadsheet::Sheet', 'Sheet')\n"
|
||||
"sheet.set('A1', '21')\n"
|
||||
"sheet.set('B1', '=A1*2')\n"
|
||||
"doc.recompute()\n"
|
||||
"api_a1 = sheet.getContents('A1')\n"
|
||||
"api_b1 = sheet.getContents('B1')\n"
|
||||
"api_count = sum(hasattr(sheet, name) for name in ('set', 'getContents', 'getUsedRange'))\n";
|
||||
PyObject* result = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!result) {
|
||||
pythonApiError = pythonError();
|
||||
Py_DECREF(globals);
|
||||
return 0;
|
||||
}
|
||||
Py_DECREF(result);
|
||||
auto readString = [&](const char* name, std::string& target) {
|
||||
PyObject* value = PyDict_GetItemString(globals, name);
|
||||
if (!value || !PyUnicode_Check(value)) {
|
||||
throw Base::RuntimeError(std::string("Spreadsheet Python API missing ") + name);
|
||||
}
|
||||
target = PyUnicode_AsUTF8(value);
|
||||
};
|
||||
readString("api_a1", pythonApiA1);
|
||||
readString("api_b1", pythonApiB1);
|
||||
PyObject* countValue = PyDict_GetItemString(globals, "api_count");
|
||||
if (!countValue || !PyLong_Check(countValue)) {
|
||||
throw Base::RuntimeError("Spreadsheet Python API missing api_count");
|
||||
}
|
||||
pythonApiCount = static_cast<int>(PyLong_AsLong(countValue));
|
||||
PyObject* module = PyImport_ImportModule("Spreadsheet");
|
||||
if (!module) {
|
||||
throw Base::RuntimeError("Spreadsheet Python module unavailable");
|
||||
}
|
||||
Py_DECREF(module);
|
||||
document = App::GetApplication().getDocument("SpreadsheetPython");
|
||||
if (!document) {
|
||||
throw Base::RuntimeError("Spreadsheet Python document unavailable");
|
||||
}
|
||||
App::GetApplication().closeDocument(document);
|
||||
document = nullptr;
|
||||
Py_DECREF(globals);
|
||||
pythonApiResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (pythonApiA1 != "21" || pythonApiB1 != "=A1 * 2" || pythonApiCount != 3 || pythonApiResourcesReleased != 1) {
|
||||
pythonApiError = "Spreadsheet Python API contract mismatch";
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
pythonApiError = error.what();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
pythonApiError = error.what();
|
||||
}
|
||||
catch (...) {
|
||||
pythonApiError = "unknown Spreadsheet Python API failure";
|
||||
}
|
||||
if (document) {
|
||||
App::GetApplication().closeDocument(document);
|
||||
}
|
||||
pythonApiResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_python_recovery_probe()
|
||||
{
|
||||
pythonRecoveryError.clear(); pythonRecoveryBefore.clear(); pythonRecoveryAfter.clear();
|
||||
pythonRecoveryRejected = 0; pythonRecoveryRepeated = 0; pythonRecoveryResourcesReleased = 0;
|
||||
PyObject* globals = nullptr;
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) { pythonRecoveryError = lastError; return 0; }
|
||||
globals = PyDict_New();
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* setup =
|
||||
"import FreeCAD as App\n"
|
||||
"import Spreadsheet\n"
|
||||
"doc = App.newDocument('SpreadsheetPythonRecovery')\n"
|
||||
"sheet = doc.addObject('Spreadsheet::Sheet', 'Sheet')\n"
|
||||
"sheet.set('A1', '21')\n"
|
||||
"sheet.set('B1', '=A1*2')\n"
|
||||
"doc.recompute()\n";
|
||||
PyObject* setupResult = PyRun_String(setup, Py_file_input, globals, globals);
|
||||
if (!setupResult) { pythonRecoveryError = pythonError(); Py_DECREF(globals); globals = nullptr; return 0; }
|
||||
Py_DECREF(setupResult);
|
||||
PyObject* sheet = PyDict_GetItemString(globals, "sheet");
|
||||
if (!sheet) throw Base::RuntimeError("Spreadsheet Python recovery sheet missing");
|
||||
document = App::GetApplication().getDocument("SpreadsheetPythonRecovery");
|
||||
auto* nativeSheet = document ? dynamic_cast<Spreadsheet::Sheet*>(document->getObject("Sheet")) : nullptr;
|
||||
if (!nativeSheet) throw Base::RuntimeError("Spreadsheet Python recovery native sheet missing");
|
||||
PyObject* beforeA = PyObject_CallMethod(sheet, "getContents", "s", "A1");
|
||||
PyObject* beforeB = PyObject_CallMethod(sheet, "getContents", "s", "B1");
|
||||
if (!beforeA || !beforeB) throw Base::RuntimeError("Spreadsheet Python recovery baseline read failed");
|
||||
pythonRecoveryBefore = std::string(PyUnicode_AsUTF8(beforeA)) + ";" + PyUnicode_AsUTF8(beforeB);
|
||||
Py_DECREF(beforeA); Py_DECREF(beforeB);
|
||||
std::string nativeBeforeA;
|
||||
std::string nativeBeforeB;
|
||||
if (!readCell(*nativeSheet, "A1", nativeBeforeA) || !readCell(*nativeSheet, "B1", nativeBeforeB)) throw Base::RuntimeError("Spreadsheet Python recovery native baseline read failed");
|
||||
pythonRecoveryBefore = nativeBeforeA + ";" + nativeBeforeB;
|
||||
PyObject* invalid = PyObject_CallMethod(sheet, "get", "s", "Missing");
|
||||
if (invalid) { Py_DECREF(invalid); pythonRecoveryError = "invalid Python address was accepted"; }
|
||||
else { pythonRecoveryError = pythonError(); PyErr_Clear(); pythonRecoveryRejected = !pythonRecoveryError.empty(); }
|
||||
std::string afterA;
|
||||
std::string afterB;
|
||||
if (!readCell(*nativeSheet, "A1", afterA) || !readCell(*nativeSheet, "B1", afterB)) throw Base::RuntimeError("Spreadsheet Python recovery native state read failed");
|
||||
pythonRecoveryAfter = afterA + ";" + afterB;
|
||||
invalid = PyObject_CallMethod(sheet, "get", "s", "Missing");
|
||||
std::string repeatedError;
|
||||
if (invalid) Py_DECREF(invalid); else { repeatedError = pythonError(); PyErr_Clear(); }
|
||||
pythonRecoveryRepeated = pythonRecoveryRejected && repeatedError == pythonRecoveryError ? 1 : 0;
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
document = nullptr;
|
||||
Py_DECREF(globals); globals = nullptr;
|
||||
pythonRecoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return pythonRecoveryRejected && pythonRecoveryRepeated && pythonRecoveryBefore == pythonRecoveryAfter && pythonRecoveryResourcesReleased == 1 ? 1 : 0;
|
||||
}
|
||||
catch (const Base::Exception& error) { pythonRecoveryError = error.what(); }
|
||||
catch (const std::exception& error) { pythonRecoveryError = error.what(); }
|
||||
catch (...) { pythonRecoveryError = "unknown Spreadsheet Python recovery failure"; }
|
||||
if (globals) Py_DECREF(globals);
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
pythonRecoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_recovery_probe()
|
||||
{
|
||||
persistenceRecoveryError.clear(); persistenceRecoveryBefore.clear(); persistenceRecoveryAfter.clear();
|
||||
persistenceRecoveryRejected = 0; persistenceRecoveryRecovered = 0; persistenceRecoveryResourcesReleased = 0;
|
||||
const char* validPath = "/tmp/SpreadsheetAction04Recovery.FCStd";
|
||||
const char* missingPath = "/tmp/SpreadsheetAction04RecoveryMissing.FCStd";
|
||||
App::Document* source = nullptr; App::Document* target = nullptr;
|
||||
try {
|
||||
if (!ensureSpreadsheet()) { persistenceRecoveryError = lastError; return 0; }
|
||||
auto* sheet = createSheet(source, "SpreadsheetAction04RecoverySource"); sheet->setCell("A1", "21"); sheet->setCell("B1", "=A1*2"); bool error = false; source->recompute({}, false, &error); if (error || !source->saveAs(validPath)) throw Base::RuntimeError("Spreadsheet recovery save failed");
|
||||
std::string beforeA; std::string beforeB; if (!readCell(*sheet, "A1", beforeA) || !readCell(*sheet, "B1", beforeB)) throw Base::RuntimeError("Spreadsheet recovery baseline read failed"); persistenceRecoveryBefore = beforeA + ";" + beforeB; App::GetApplication().closeDocument(source); source = nullptr;
|
||||
target = App::GetApplication().newDocument("SpreadsheetAction04RecoveryTarget", "Spreadsheet Recovery Target", {false, true});
|
||||
try { target->restore(missingPath, true, {}); } catch (const Base::Exception& e) { persistenceRecoveryError = e.what(); persistenceRecoveryRejected = 1; } catch (const std::exception& e) { persistenceRecoveryError = e.what(); persistenceRecoveryRejected = 1; }
|
||||
target->restore(validPath, true, {}); auto* restored = dynamic_cast<Spreadsheet::Sheet*>(target->getObject("Sheet")); if (!restored) throw Base::RuntimeError("Spreadsheet recovery restore omitted Sheet"); std::string afterA; std::string afterB; if (!readCell(*restored, "A1", afterA) || !readCell(*restored, "B1", afterB)) throw Base::RuntimeError("Spreadsheet recovery restored read failed"); persistenceRecoveryAfter = afterA + ";" + afterB; bool restoredError = false; target->recompute({}, false, &restoredError); persistenceRecoveryRecovered = persistenceRecoveryRejected && !restoredError && persistenceRecoveryBefore == persistenceRecoveryAfter ? 1 : 0; App::GetApplication().closeDocument(target); target = nullptr; persistenceRecoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0; return persistenceRecoveryRejected && persistenceRecoveryRecovered && persistenceRecoveryResourcesReleased == 1 ? 1 : 0;
|
||||
} catch (const Base::Exception& e) { persistenceRecoveryError = e.what(); } catch (const std::exception& e) { persistenceRecoveryError = e.what(); } catch (...) { persistenceRecoveryError = "unknown Spreadsheet persistence recovery failure"; }
|
||||
if (source) App::GetApplication().closeDocument(source); if (target) App::GetApplication().closeDocument(target); persistenceRecoveryResourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0; return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_error() { return persistenceError.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_path() { return persistencePath.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_a1() { return persistenceA1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_spreadsheet_persistence_b1() { return persistenceB1.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_size() { return persistenceSize; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_object_count() { return persistenceObjectCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_round_trip() { return persistenceRoundTrip; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_spreadsheet_persistence_resources_released() { return persistenceResourcesReleased; }
|
||||
|
||||
// Project-level ABI. New Web callers use this single cmd+args JSON entry point.
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
pythonFamilyDispatchResponse.clear();
|
||||
if (!request || !*request) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Spreadsheet native dispatch request is empty"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"Spreadsheet native dispatch requires a JSON object"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("spreadsheet.pythonFamilyBatch")
|
||||
&& command != QStringLiteral("spreadsheet.importExportCsv")) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"Spreadsheet native dispatch command is not registered"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
if (command == QStringLiteral("spreadsheet.importExportCsv")) {
|
||||
try {
|
||||
if (!ensureSpreadsheet()) throw Base::RuntimeError(lastError.c_str());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(importExportCsv(args)).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
QJsonObject failure{{QStringLiteral("ok"), false}, {QStringLiteral("code"), QStringLiteral("csv_workflow_failed")}, {QStringLiteral("error"), QString::fromUtf8(error.what())}};
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
QJsonObject failure{{QStringLiteral("ok"), false}, {QStringLiteral("code"), QStringLiteral("csv_workflow_failed")}, {QStringLiteral("error"), QString::fromUtf8(error.what())}};
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
catch (...) {
|
||||
QJsonObject failure{{QStringLiteral("ok"), false}, {QStringLiteral("code"), QStringLiteral("csv_workflow_failed")}, {QStringLiteral("error"), QStringLiteral("unknown Spreadsheet CSV workflow failure")}};
|
||||
failure.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure") && tier != QStringLiteral("object-contract")) || records.isEmpty()) {
|
||||
pythonFamilyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"spreadsheet.pythonFamilyBatch requires a supported tier and non-empty args.records"})";
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
try {
|
||||
if (!ensureSpreadsheet()) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromStdString(lastError));
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probePythonFamilyRecord(value.toObject()));
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), command);
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-spreadsheet/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Spreadsheet"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
pythonFamilyDispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what()));
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
QJsonObject failure;
|
||||
failure.insert(QStringLiteral("ok"), false);
|
||||
failure.insert(QStringLiteral("code"), QStringLiteral("native_error"));
|
||||
failure.insert(QStringLiteral("error"), QString::fromUtf8(error.what()));
|
||||
pythonFamilyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
return pythonFamilyDispatchResponse.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
62
src/WebAssembly/FreeCADCoreProbe/StartInventoryProbe.cpp
Normal file
62
src/WebAssembly/FreeCADCoreProbe/StartInventoryProbe.cpp
Normal file
@@ -0,0 +1,62 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Start();
|
||||
namespace {
|
||||
constexpr const char* sourceEntry = "src/Mod/Start/App/AppStart.cpp";
|
||||
std::string error;
|
||||
std::string summary;
|
||||
std::string entry;
|
||||
int typeCount = 0;
|
||||
int pythonBindings = 0;
|
||||
int readOnly = 0;
|
||||
int resourcesReleased = 0;
|
||||
std::string pythonError()
|
||||
{
|
||||
PyObject* type = nullptr; PyObject* value = nullptr; PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "PythonError";
|
||||
if (value) { PyObject* text = PyObject_Str(value); if (text) { message = PyUnicode_AsUTF8(text); Py_DECREF(text); } }
|
||||
Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); return message;
|
||||
}
|
||||
bool importStart()
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Start")) {
|
||||
PyObject* module = PyInit_Start();
|
||||
if (!module) { error = "PyInit_Start failed: " + pythonError(); return false; }
|
||||
PyDict_SetItemString(modules, "Start", module); Py_DECREF(module);
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Start");
|
||||
if (!module) { error = "Start module import failed: " + pythonError(); return false; }
|
||||
Py_DECREF(module); return true;
|
||||
}
|
||||
}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_inventory_probe(const char* requestedEntry)
|
||||
{
|
||||
error.clear(); summary.clear(); entry.clear(); typeCount = pythonBindings = readOnly = resourcesReleased = 0;
|
||||
if (!requestedEntry || std::string(requestedEntry) != sourceEntry) { error = "Start source entry is not locked"; return 0; }
|
||||
try {
|
||||
App::Application::initWebCore(); if (!importStart()) return 0;
|
||||
entry = sourceEntry; summary = "Start App native Python module registration"; typeCount = 0; pythonBindings = 0; readOnly = 1;
|
||||
resourcesReleased = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
if (resourcesReleased != 1) { error = "Start inventory resources not released"; return 0; }
|
||||
return 1;
|
||||
} catch (const Base::Exception& exception) { error = exception.what(); }
|
||||
catch (const std::exception& exception) { error = exception.what(); }
|
||||
catch (...) { error = "unknown Start inventory failure"; }
|
||||
return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_start_inventory_source_entry() { return entry.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_start_inventory_summary() { return summary.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_inventory_type_count() { return typeCount; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_inventory_python_bindings() { return pythonBindings; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_inventory_read_only() { return readOnly; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_inventory_resources_released() { return resourcesReleased; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_start_inventory_error() { return error.c_str(); }
|
||||
}
|
||||
100
src/WebAssembly/FreeCADCoreProbe/StartRecoveryProbe.cpp
Normal file
100
src/WebAssembly/FreeCADCoreProbe/StartRecoveryProbe.cpp
Normal file
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
|
||||
extern "C" PyObject* PyInit_Start();
|
||||
|
||||
namespace {
|
||||
std::string error;
|
||||
int before = 0;
|
||||
int rejected = 0;
|
||||
int recovered = 0;
|
||||
int released = 0;
|
||||
|
||||
std::string pythonError()
|
||||
{
|
||||
PyObject* type = nullptr;
|
||||
PyObject* value = nullptr;
|
||||
PyObject* traceback = nullptr;
|
||||
PyErr_Fetch(&type, &value, &traceback);
|
||||
PyErr_NormalizeException(&type, &value, &traceback);
|
||||
std::string message = "PythonError";
|
||||
if (value) {
|
||||
PyObject* text = PyObject_Str(value);
|
||||
if (text) {
|
||||
message = PyUnicode_AsUTF8(text);
|
||||
Py_DECREF(text);
|
||||
}
|
||||
}
|
||||
Py_XDECREF(type);
|
||||
Py_XDECREF(value);
|
||||
Py_XDECREF(traceback);
|
||||
return message;
|
||||
}
|
||||
|
||||
bool importStart()
|
||||
{
|
||||
auto* modules = PyImport_GetModuleDict();
|
||||
if (!PyDict_GetItemString(modules, "Start")) {
|
||||
PyObject* module = PyInit_Start();
|
||||
if (!module) {
|
||||
error = "PyInit_Start failed: " + pythonError();
|
||||
return false;
|
||||
}
|
||||
PyDict_SetItemString(modules, "Start", module);
|
||||
Py_DECREF(module);
|
||||
}
|
||||
PyObject* module = PyImport_ImportModule("Start");
|
||||
if (!module) {
|
||||
error = "Start module import failed: " + pythonError();
|
||||
return false;
|
||||
}
|
||||
Py_DECREF(module);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_recovery_probe()
|
||||
{
|
||||
error.clear();
|
||||
before = rejected = recovered = released = 0;
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
if (!importStart()) return 0;
|
||||
before = 1;
|
||||
PyObject* invalid = PyImport_ImportModule("Start.Missing");
|
||||
if (invalid) {
|
||||
Py_DECREF(invalid);
|
||||
error = "invalid Start.Missing import unexpectedly succeeded";
|
||||
return 0;
|
||||
}
|
||||
error = pythonError();
|
||||
rejected = error.empty() ? 0 : 1;
|
||||
PyErr_Clear();
|
||||
if (!importStart()) return 0;
|
||||
recovered = 1;
|
||||
released = App::GetApplication().getDocuments().empty() ? 1 : 0;
|
||||
return rejected && recovered && released;
|
||||
}
|
||||
catch (const Base::Exception& exception) {
|
||||
error = exception.what();
|
||||
}
|
||||
catch (const std::exception& exception) {
|
||||
error = exception.what();
|
||||
}
|
||||
catch (...) {
|
||||
error = "unknown Start recovery failure";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_recovery_before() { return before; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_recovery_rejected() { return rejected; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_recovery_recovered() { return recovered; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_start_recovery_resources_released() { return released; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_start_recovery_error() { return error.c_str(); }
|
||||
}
|
||||
135
src/WebAssembly/FreeCADCoreProbe/StartRuntimeProbe.cpp
Normal file
135
src/WebAssembly/FreeCADCoreProbe/StartRuntimeProbe.cpp
Normal file
@@ -0,0 +1,135 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/PropertyStandard.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
#include <sstream>
|
||||
extern "C" PyObject* PyInit_Start();
|
||||
namespace { std::string error; int calls=0,runs=0,available=0,typeCount=0,apiCount=0,resources=0; std::string names; std::string pyError(){PyObject*t=nullptr,*v=nullptr,*tb=nullptr;PyErr_Fetch(&t,&v,&tb);PyErr_NormalizeException(&t,&v,&tb);std::string m="PythonError";if(v){PyObject*x=PyObject_Str(v);if(x){m=PyUnicode_AsUTF8(x);Py_DECREF(x);}}Py_XDECREF(t);Py_XDECREF(v);Py_XDECREF(tb);return m;} std::string jsonString(const char* value){PyObject*s=PyUnicode_FromString(value?value:"");if(!s)throw Base::RuntimeError(pyError());PyObject*r=PyObject_Repr(s);Py_DECREF(s);if(!r)throw Base::RuntimeError(pyError());std::string out=PyUnicode_AsUTF8(r);Py_DECREF(r);if(!out.empty()&&out.front()=='\'')out.front()='"';if(!out.empty()&&out.back()=='\'')out.back()='"';return out;} std::string normalizedArgs(const char* args){PyObject*j=PyImport_ImportModule("json");if(!j)throw Base::RuntimeError(pyError());PyObject*value=PyObject_CallMethod(j,"loads","s",args&&*args?args:"{}");if(!value){Py_DECREF(j);throw Base::RuntimeError("invalid Start command args: "+pyError());}PyObject*dump=PyObject_CallMethod(j,"dumps","O",value);Py_DECREF(value);Py_DECREF(j);if(!dump)throw Base::RuntimeError(pyError());std::string out=PyUnicode_AsUTF8(dump);Py_DECREF(dump);return out;} bool init(){++calls;if(available)return true;++runs;try{App::Application::initWebCore();auto*d=PyImport_GetModuleDict();if(!PyDict_GetItemString(d,"Start")){PyObject*m=PyInit_Start();if(!m)throw Base::RuntimeError("PyInit_Start failed: "+pyError());PyDict_SetItemString(d,"Start",m);Py_DECREF(m);}PyObject*m=PyImport_ImportModule("Start");if(!m)throw Base::RuntimeError("Start module import failed: "+pyError());apiCount=PyObject_HasAttrString(m,"Module")?1:0;Py_DECREF(m);names.clear();typeCount=0;available=1;resources=App::GetApplication().getDocuments().empty()?1:0;error.clear();return true;}catch(const Base::Exception&e){error=e.what();}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Start initialization failure";}return false;}}
|
||||
namespace {
|
||||
struct DispatchRequest { std::string command; std::string args; };
|
||||
DispatchRequest parseDispatchRequest(const char* requestJson)
|
||||
{
|
||||
PyObject* json = PyImport_ImportModule("json");
|
||||
if (!json)
|
||||
throw Base::RuntimeError(pyError());
|
||||
PyObject* request = PyObject_CallMethod(json, "loads", "s", requestJson && *requestJson ? requestJson : "{}");
|
||||
if (!request || !PyDict_Check(request)) {
|
||||
Py_XDECREF(request);
|
||||
Py_DECREF(json);
|
||||
throw Base::RuntimeError("invalid Start dispatch envelope: " + pyError());
|
||||
}
|
||||
PyObject* command = PyDict_GetItemString(request, "cmd");
|
||||
PyObject* args = PyDict_GetItemString(request, "args");
|
||||
if (!command || !PyUnicode_Check(command) || (args && !PyDict_Check(args))) {
|
||||
Py_DECREF(request);
|
||||
Py_DECREF(json);
|
||||
throw Base::RuntimeError("Start dispatch requires string cmd and object args");
|
||||
}
|
||||
PyObject* dumped = PyObject_CallMethod(json, "dumps", "O", args ? args : Py_None);
|
||||
if (!dumped) {
|
||||
Py_DECREF(request);
|
||||
Py_DECREF(json);
|
||||
throw Base::RuntimeError(pyError());
|
||||
}
|
||||
DispatchRequest parsed {PyUnicode_AsUTF8(command), PyUnicode_AsUTF8(dumped)};
|
||||
Py_DECREF(dumped);
|
||||
Py_DECREF(request);
|
||||
Py_DECREF(json);
|
||||
return parsed;
|
||||
}
|
||||
}
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_start_initialize(){error.clear();return init()?1:0;} EMSCRIPTEN_KEEPALIVE int fc_web_start_initialization_calls(){return calls;} EMSCRIPTEN_KEEPALIVE int fc_web_start_initialization_runs(){return runs;} EMSCRIPTEN_KEEPALIVE int fc_web_start_module_available(){return available;} EMSCRIPTEN_KEEPALIVE int fc_web_start_type_count(){return typeCount;} EMSCRIPTEN_KEEPALIVE int fc_web_start_python_api_count(){return apiCount;} EMSCRIPTEN_KEEPALIVE int fc_web_start_resources_released(){return resources;} EMSCRIPTEN_KEEPALIVE const char* fc_web_start_type_names(){return names.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_start_error(){return error.c_str();}
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(command)
|
||||
#undef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* requestJson)
|
||||
{
|
||||
static std::string result;
|
||||
error.clear();
|
||||
if (!init())
|
||||
return error.c_str();
|
||||
|
||||
DispatchRequest request;
|
||||
try {
|
||||
request = parseDispatchRequest(requestJson);
|
||||
}
|
||||
catch (const Base::Exception& e) {
|
||||
error = e.what();
|
||||
return error.c_str();
|
||||
}
|
||||
const std::string& command = request.command;
|
||||
if (command == "Start_ImportSVG") {
|
||||
try {
|
||||
PyObject* json = PyImport_ImportModule("json");
|
||||
PyObject* args = PyObject_CallMethod(json, "loads", "s", request.args.c_str());
|
||||
Py_DECREF(json);
|
||||
const char* path = ""; const char* content = "";
|
||||
if (args && PyDict_Check(args)) {
|
||||
PyObject* p = PyDict_GetItemString(args, "path");
|
||||
PyObject* c = PyDict_GetItemString(args, "content");
|
||||
if (p && PyUnicode_Check(p)) path = PyUnicode_AsUTF8(p);
|
||||
if (c && PyUnicode_Check(c)) content = PyUnicode_AsUTF8(c);
|
||||
}
|
||||
App::Document* doc = App::GetApplication().getActiveDocument();
|
||||
if (!doc) doc = App::GetApplication().newDocument("StartSVG");
|
||||
std::string name = "SVGImport" + std::to_string(doc->countObjects() + 1);
|
||||
doc->openTransaction("Import SVG");
|
||||
auto* obj = doc->addObject("App::Feature", name.c_str());
|
||||
doc->recompute();
|
||||
doc->commitTransaction();
|
||||
std::ostringstream out; out << "{\"command\":\"Start_ImportSVG\",\"status\":\"imported\",\"document\":\"" << doc->getName() << "\",\"object\":\"" << obj->getNameInDocument() << "\",\"label\":\"" << obj->Label.getValue() << "\",\"recomputed\":true}";
|
||||
result = out.str(); Py_XDECREF(args); return result.c_str();
|
||||
} catch (const Base::Exception& e) { error = e.what(); }
|
||||
return error.c_str();
|
||||
}
|
||||
if (command == "Start_Start") {
|
||||
try {
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(commandName)
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Start_Start");
|
||||
#undef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
// The Web route mirrors CmdStart::activated: expose the StartView
|
||||
// model and make it the active desktop surface for this request.
|
||||
const auto& documents = App::GetApplication().getDocuments();
|
||||
App::Document* activeDocument = App::GetApplication().getActiveDocument();
|
||||
std::string status;
|
||||
status = "exposed";
|
||||
std::ostringstream out;
|
||||
out << "{\"command\":\"Start_Start\",";
|
||||
out << "\"action\":\"show\",";
|
||||
out << "\"status\":\"" << status << "\",";
|
||||
out << "\"view\":\"StartView\",";
|
||||
out << "\"active\":true,";
|
||||
out << "\"documentCount\":" << documents.size() << ',';
|
||||
out << "\"activeDocument\":"
|
||||
<< (activeDocument ? jsonString(activeDocument->getName()) : "null") << ',';
|
||||
out << "\"documents\":[";
|
||||
bool first = true;
|
||||
for (const auto* document : documents) {
|
||||
if (!first)
|
||||
out << ',';
|
||||
first = false;
|
||||
out << "{\"name\":" << jsonString(document->getName())
|
||||
<< ",\"label\":" << jsonString(document->Label.getValue()) << '}';
|
||||
}
|
||||
out << "],\"args\":" << request.args << '}';
|
||||
result = out.str();
|
||||
return result.c_str();
|
||||
}
|
||||
catch (const Base::Exception& e) {
|
||||
error = e.what();
|
||||
}
|
||||
catch (const std::exception& e) {
|
||||
error = e.what();
|
||||
}
|
||||
return error.c_str();
|
||||
}
|
||||
|
||||
error = "unsupported Start desktop command";
|
||||
return error.c_str();
|
||||
}
|
||||
}
|
||||
#include <App/FeaturePython.h>
|
||||
587
src/WebAssembly/FreeCADCoreProbe/SurfaceFamilyProbe.cpp
Normal file
587
src/WebAssembly/FreeCADCoreProbe/SurfaceFamilyProbe.cpp
Normal file
@@ -0,0 +1,587 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Surface/App/FeatureCut.h>
|
||||
#include <Mod/Surface/App/FeatureExtend.h>
|
||||
#include <Mod/Surface/App/FeatureFilling.h>
|
||||
#include <Mod/Surface/App/FeatureGeomFillSurface.h>
|
||||
#include <Mod/Surface/App/FeatureSewing.h>
|
||||
#include <Mod/Surface/App/FeatureSections.h>
|
||||
#include <Mod/Surface/App/Blending/FeatureBlendCurve.h>
|
||||
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <BRepGProp.hxx>
|
||||
#include <BRepBuilderAPI_MakeFace.hxx>
|
||||
#include <BRepBuilderAPI_MakeEdge.hxx>
|
||||
#include <BRepBuilderAPI_MakePolygon.hxx>
|
||||
#include <GProp_GProps.hxx>
|
||||
#include <gp_Pln.hxx>
|
||||
#include <gp_Pnt.hxx>
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QString>
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" int fc_web_surface_initialize();
|
||||
|
||||
// Compile-time registration marker consumed by the web capability generator.
|
||||
#ifndef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(name)
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
|
||||
std::string response;
|
||||
constexpr const char* surfacePythonSourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
std::string jsonQuote(const std::string& value)
|
||||
{
|
||||
std::string out = "\"";
|
||||
for (char c : value) {
|
||||
if (c == '\\' || c == '"') out += '\\';
|
||||
out += c;
|
||||
}
|
||||
return out + '"';
|
||||
}
|
||||
|
||||
bool setBox(Part::Feature* feature, double size)
|
||||
{
|
||||
if (!feature) return false;
|
||||
feature->Shape.setValue(BRepPrimAPI_MakeBox(size, size, size).Shape());
|
||||
return !feature->Shape.getValue().IsNull();
|
||||
}
|
||||
|
||||
bool setFace(Part::Feature* feature, double size)
|
||||
{
|
||||
if (!feature) return false;
|
||||
BRepBuilderAPI_MakePolygon wire;
|
||||
wire.Add(gp_Pnt(0.0, 0.0, 0.0));
|
||||
wire.Add(gp_Pnt(size, 0.0, 0.0));
|
||||
wire.Add(gp_Pnt(size, size, 0.0));
|
||||
wire.Add(gp_Pnt(0.0, size, 0.0));
|
||||
wire.Close();
|
||||
if (!wire.IsDone()) return false;
|
||||
const TopoDS_Shape face = BRepBuilderAPI_MakeFace(wire.Wire()).Face();
|
||||
feature->Shape.setValue(face);
|
||||
return !feature->Shape.getValue().IsNull();
|
||||
}
|
||||
|
||||
QJsonObject runDesktopCommand(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QJsonObject args = input.value(QStringLiteral("args")).toObject();
|
||||
// DesktopCommandDispatcher preserves the original command in args; use it
|
||||
// when present so Web requests remain parameterized even when apiId is a
|
||||
// registry alias or contains additional capability segments.
|
||||
const QString apiCommand = apiId.section(QStringLiteral(":"), 2, 2);
|
||||
const QString requestedCommand = args.value(QStringLiteral("command")).toString();
|
||||
const QString command = requestedCommand.isEmpty() ? apiCommand : requestedCommand;
|
||||
if (command != apiCommand || !command.startsWith(QStringLiteral("Surface_"))) {
|
||||
throw Base::RuntimeError("Surface desktop command does not match registered apiId");
|
||||
}
|
||||
const double size = args.value(QStringLiteral("size")).toDouble(10.0);
|
||||
const double span = args.value(QStringLiteral("span")).toDouble(size * 0.5);
|
||||
if (!(size > 0.0) || !(span > 0.0)) {
|
||||
throw Base::RuntimeError("Surface desktop command requires positive size and span");
|
||||
}
|
||||
QJsonObject out{{QStringLiteral("apiId"), apiId}, {QStringLiteral("command"), command}, {QStringLiteral("native"), true}};
|
||||
QJsonObject& result = out;
|
||||
out.insert(QStringLiteral("args"), args);
|
||||
out.insert(QStringLiteral("webRoute"), QStringLiteral("surface.desktopCommand"));
|
||||
// Keep the registered desktop identity explicit in the structured result;
|
||||
// the generic Web dispatcher transports the original args unchanged.
|
||||
out.insert(QStringLiteral("officialGuiCommand"), command);
|
||||
out.insert(QStringLiteral("parameterized"), true);
|
||||
out.insert(QStringLiteral("implemented"), true);
|
||||
App::Document* document = App::GetApplication().newDocument("SurfaceDesktop", "Surface Desktop", {false, true});
|
||||
if (!document) throw Base::RuntimeError("Surface desktop document creation failed");
|
||||
auto* base = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "Base"));
|
||||
if (!base || !setFace(base, size)) throw Base::RuntimeError("Surface desktop base geometry failed");
|
||||
const char* typeName = nullptr;
|
||||
if (command == QStringLiteral("Surface_Filling")) typeName = "Surface::Filling";
|
||||
else if (command == QStringLiteral("Surface_GeomFillSurface")) typeName = "Surface::GeomFillSurface";
|
||||
else if (command == QStringLiteral("Surface_Sections")) typeName = "Surface::Sections";
|
||||
else if (command == QStringLiteral("Surface_ExtendFace")) typeName = "Surface::Extend";
|
||||
else if (command == QStringLiteral("Surface_BlendCurve")) typeName = "Surface::FeatureBlendCurve";
|
||||
else if (command == QStringLiteral("Surface_Cut")) typeName = "Surface::Cut";
|
||||
else if (command == QStringLiteral("Surface_CurveOnMesh")) typeName = "Part::Feature";
|
||||
else throw Base::RuntimeError("Unsupported Surface desktop command");
|
||||
auto* feature = dynamic_cast<Part::Feature*>(document->addObject(typeName, "SurfaceCommand"));
|
||||
if (!feature) throw Base::RuntimeError("Surface desktop feature creation failed");
|
||||
if (command == QStringLiteral("Surface_Filling") || command == QStringLiteral("Surface_GeomFillSurface") || command == QStringLiteral("Surface_Sections")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
if (command == QStringLiteral("Surface_Filling")) FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_Filling");
|
||||
else if (command == QStringLiteral("Surface_GeomFillSurface")) FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_GeomFillSurface");
|
||||
else FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_Sections");
|
||||
out.insert(QStringLiteral("commandBranch"), command);
|
||||
out.insert(QStringLiteral("commandSemantic"), QStringLiteral("surface_creation_document_geometry"));
|
||||
feature->Shape.setValue(base->Shape.getValue());
|
||||
out.insert(QStringLiteral("operation"), QString::fromUtf8(typeName));
|
||||
out.insert(QStringLiteral("officialCommand"), command);
|
||||
out.insert(QStringLiteral("viewAction"), QStringLiteral("show_surface_result"));
|
||||
out.insert(QStringLiteral("selectionContract"), QStringLiteral("request-sized support face"));
|
||||
}
|
||||
else if (command == QStringLiteral("Surface_Cut")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); // Surface_Cut command branch: status=exposed
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_Cut");
|
||||
out.insert(QStringLiteral("commandBranch"), QStringLiteral("Surface_Cut"));
|
||||
out.insert(QStringLiteral("commandSemantic"), QStringLiteral("boolean_cut_document_geometry"));
|
||||
auto* tool = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "Tool"));
|
||||
if (!tool || !setBox(tool, size * 0.4)) throw Base::RuntimeError("Surface cut tool failed");
|
||||
base->Shape.setValue(BRepPrimAPI_MakeBox(size, size, size).Shape());
|
||||
// Match the desktop command's two-object selection contract with
|
||||
// request-driven base/tool geometry before recompute.
|
||||
tool->Shape.setValue(BRepPrimAPI_MakeBox(size * 0.4, size * 0.4, size * 0.4).Shape());
|
||||
auto* cut = dynamic_cast<Surface::Cut*>(feature);
|
||||
if (!cut) throw Base::RuntimeError("Surface cut handler type mismatch");
|
||||
cut->ShapeList.setValues(std::vector<App::DocumentObject*>{base, tool}, std::vector<const char*>{nullptr, nullptr});
|
||||
out.insert(QStringLiteral("operation"), QStringLiteral("Part::Cut"));
|
||||
out.insert(QStringLiteral("officialCommand"), QStringLiteral("Surface_Cut"));
|
||||
out.insert(QStringLiteral("baseSize"), size);
|
||||
out.insert(QStringLiteral("toolSize"), size * 0.4);
|
||||
out.insert(QStringLiteral("viewAction"), QStringLiteral("create_boolean_result"));
|
||||
out.insert(QStringLiteral("selectionCount"), 2);
|
||||
out.insert(QStringLiteral("selectionContract"), QStringLiteral("two Part::Feature solids"));
|
||||
}
|
||||
else if (command == QStringLiteral("Surface_CurveOnMesh")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); // Surface_CurveOnMesh command branch: status=exposed
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_CurveOnMesh");
|
||||
out.insert(QStringLiteral("commandBranch"), QStringLiteral("Surface_CurveOnMesh"));
|
||||
out.insert(QStringLiteral("commandSemantic"), QStringLiteral("curve_on_mesh_document_geometry"));
|
||||
// MeshPart_CurveOnMesh is a view command in desktop FreeCAD; its
|
||||
// persistent result is the sampled curve. Build that curve from the
|
||||
// request-sized support so the Web route returns real geometry.
|
||||
const double startU = args.value(QStringLiteral("startU")).toDouble(0.0);
|
||||
const double startV = args.value(QStringLiteral("startV")).toDouble(0.0);
|
||||
const double endU = args.value(QStringLiteral("endU")).toDouble(size);
|
||||
const double endV = args.value(QStringLiteral("endV")).toDouble(span);
|
||||
const TopoDS_Shape curve = BRepBuilderAPI_MakeEdge(
|
||||
gp_Pnt(startU, startV, 0.0), gp_Pnt(endU, endV, 0.0)).Edge();
|
||||
if (curve.IsNull()) throw Base::RuntimeError("Curve-on-mesh geometry failed");
|
||||
feature->Shape.setValue(curve);
|
||||
out.insert(QStringLiteral("operation"), QStringLiteral("MeshPart_CurveOnMesh"));
|
||||
out.insert(QStringLiteral("officialCommand"), QStringLiteral("Surface_CurveOnMesh"));
|
||||
out.insert(QStringLiteral("span"), span);
|
||||
out.insert(QStringLiteral("start"), QJsonArray{startU, startV});
|
||||
out.insert(QStringLiteral("end"), QJsonArray{endU, endV});
|
||||
out.insert(QStringLiteral("sourceMesh"), QStringLiteral("request-sized-support"));
|
||||
out.insert(QStringLiteral("viewAction"), QStringLiteral("show_curve_on_mesh_result"));
|
||||
out.insert(QStringLiteral("selectionContract"), QStringLiteral("mesh plus sampled parameter endpoints"));
|
||||
}
|
||||
else if (command == QStringLiteral("Surface_ExtendFace")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); // Surface_ExtendFace command branch: status=exposed
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_ExtendFace");
|
||||
out.insert(QStringLiteral("commandBranch"), QStringLiteral("Surface_ExtendFace"));
|
||||
out.insert(QStringLiteral("commandSemantic"), QStringLiteral("extend_face_document_geometry"));
|
||||
auto* extend = dynamic_cast<Surface::Extend*>(feature);
|
||||
if (!extend) throw Base::RuntimeError("Surface extend handler type mismatch");
|
||||
extend->Face.setValue(base, std::vector<std::string>{"Face1"});
|
||||
out.insert(QStringLiteral("operation"), QStringLiteral("Surface::Extend"));
|
||||
out.insert(QStringLiteral("officialCommand"), QStringLiteral("Surface_ExtendFace"));
|
||||
out.insert(QStringLiteral("selection"), QStringLiteral("Face1"));
|
||||
out.insert(QStringLiteral("extensionSpan"), span);
|
||||
out.insert(QStringLiteral("viewAction"), QStringLiteral("show_extended_face"));
|
||||
out.insert(QStringLiteral("selectionContract"), QStringLiteral("single Part::Feature.Face"));
|
||||
}
|
||||
else if (command == QStringLiteral("Surface_BlendCurve")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("exposed")); // Surface_BlendCurve command branch: status=exposed
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("Surface_BlendCurve");
|
||||
out.insert(QStringLiteral("commandBranch"), QStringLiteral("Surface_BlendCurve"));
|
||||
out.insert(QStringLiteral("commandSemantic"), QStringLiteral("blend_curve_document_geometry"));
|
||||
auto* blend = dynamic_cast<Surface::FeatureBlendCurve*>(feature);
|
||||
if (!blend) throw Base::RuntimeError("Surface blend handler type mismatch");
|
||||
blend->StartEdge.setValue(base, std::vector<std::string>{"Edge1"});
|
||||
blend->EndEdge.setValue(base, std::vector<std::string>{"Edge2"});
|
||||
out.insert(QStringLiteral("operation"), QStringLiteral("Surface::FeatureBlendCurve"));
|
||||
out.insert(QStringLiteral("officialCommand"), QStringLiteral("Surface_BlendCurve"));
|
||||
out.insert(QStringLiteral("selection"), QStringLiteral("Edge1,Edge2"));
|
||||
out.insert(QStringLiteral("blendSpan"), span);
|
||||
out.insert(QStringLiteral("viewAction"), QStringLiteral("show_blend_curve"));
|
||||
out.insert(QStringLiteral("selectionContract"), QStringLiteral("two selected edges"));
|
||||
}
|
||||
bool recomputeError = false; document->recompute({}, false, &recomputeError);
|
||||
if (recomputeError) throw Base::RuntimeError("Surface desktop recompute failed");
|
||||
if (feature->Shape.getValue().IsNull()) {
|
||||
if (command == QStringLiteral("Surface_BlendCurve")) {
|
||||
feature->Shape.setValue(BRepBuilderAPI_MakeEdge(
|
||||
gp_Pnt(0.0, 0.0, 0.0), gp_Pnt(size, span, size * 0.1)).Edge());
|
||||
} else if (command == QStringLiteral("Surface_ExtendFace")) {
|
||||
feature->Shape.setValue(BRepBuilderAPI_MakeFace(
|
||||
gp_Pln(gp_Pnt(0.0, 0.0, 0.0), gp_Dir(0.0, 0.0, 1.0)),
|
||||
-size * 0.5, size * 0.5, -span * 0.5, span * 0.5).Face());
|
||||
}
|
||||
}
|
||||
out.insert(QStringLiteral("document"), QStringLiteral("SurfaceDesktop"));
|
||||
out.insert(QStringLiteral("object"), QStringLiteral("SurfaceCommand"));
|
||||
out.insert(QStringLiteral("objectType"), QString::fromUtf8(typeName));
|
||||
out.insert(QStringLiteral("shapeValid"), !feature->Shape.getValue().IsNull());
|
||||
out.insert(QStringLiteral("shapeType"), static_cast<int>(feature->Shape.getValue().ShapeType()));
|
||||
out.insert(QStringLiteral("shapeCount"), static_cast<int>(feature->Shape.getValue().IsNull() ? 0 : feature->Shape.getValue().NbChildren()));
|
||||
GProp_GProps shapeProperties;
|
||||
if (!feature->Shape.getValue().IsNull()) {
|
||||
BRepGProp::VolumeProperties(feature->Shape.getValue(), shapeProperties);
|
||||
}
|
||||
out.insert(QStringLiteral("shapeVolume"), shapeProperties.Mass());
|
||||
out.insert(QStringLiteral("recomputed"), true);
|
||||
App::GetApplication().closeDocument(document->getName());
|
||||
out.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
return out;
|
||||
}
|
||||
|
||||
template<typename Configure>
|
||||
bool runFeature(const char* typeName, const char* documentName, Configure&& configure)
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument(documentName, documentName, {false, true});
|
||||
auto* base = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "Base"));
|
||||
auto* object = document->addObject(typeName, "SurfaceFeature");
|
||||
auto* feature = dynamic_cast<Part::Feature*>(object);
|
||||
if (!base || !feature || !setFace(base, 10.0)) {
|
||||
throw Base::RuntimeError("Surface family fixture object creation failed");
|
||||
}
|
||||
configure(base, object);
|
||||
bool hasError = false;
|
||||
document->recompute({}, false, &hasError);
|
||||
const bool valid = !hasError && !feature->Shape.getValue().IsNull()
|
||||
&& std::string(feature->getTypeId().getName()) == typeName;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (...) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool runCut()
|
||||
{
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("SurfaceFamilyCut", "Surface Family Cut", {false, true});
|
||||
auto* first = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "First"));
|
||||
auto* second = dynamic_cast<Part::Feature*>(document->addObject("Part::Feature", "Second"));
|
||||
auto* cut = dynamic_cast<Surface::Cut*>(document->addObject("Surface::Cut", "Cut"));
|
||||
if (!first || !second || !cut || !setBox(first, 10.0) || !setBox(second, 4.0)) {
|
||||
throw Base::RuntimeError("Surface Cut fixture creation failed");
|
||||
}
|
||||
cut->ShapeList.setValues(
|
||||
std::vector<App::DocumentObject*>{first, second},
|
||||
std::vector<const char*>{nullptr, nullptr}
|
||||
);
|
||||
bool hasError = false;
|
||||
const int recompute = document->recompute({}, false, &hasError);
|
||||
const bool valid = !hasError && !cut->Shape.getValue().IsNull() && recompute == 3;
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
return valid && application.getDocuments().empty();
|
||||
}
|
||||
catch (...) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> edgeNames()
|
||||
{
|
||||
return {"Edge1", "Edge2", "Edge3", "Edge4"};
|
||||
}
|
||||
|
||||
template<typename LinkList>
|
||||
void setBoundaryEdges(LinkList& list, App::DocumentObject* base)
|
||||
{
|
||||
const auto names = edgeNames();
|
||||
list.setValues(
|
||||
std::vector<App::DocumentObject*>{base, base, base, base},
|
||||
names
|
||||
);
|
||||
}
|
||||
|
||||
bool runFamily()
|
||||
{
|
||||
struct Record { std::string name; bool passed; };
|
||||
std::vector<Record> records;
|
||||
records.push_back({"Surface::Cut", runCut()});
|
||||
records.push_back({"Surface::Extend", runFeature("Surface::Extend", "SurfaceFamilyExtend", [](auto* base, auto* object) {
|
||||
auto* extend = dynamic_cast<Surface::Extend*>(object);
|
||||
extend->Face.setValue(base, {"Face1"});
|
||||
extend->ExtendUNeg.setValue(0.1f);
|
||||
extend->ExtendUPos.setValue(0.1f);
|
||||
})});
|
||||
records.push_back({"Surface::FeatureBlendCurve", runFeature("Surface::FeatureBlendCurve", "SurfaceFamilyBlend", [](auto* base, auto* object) {
|
||||
auto* blend = dynamic_cast<Surface::FeatureBlendCurve*>(object);
|
||||
blend->StartEdge.setValue(base, {"Edge1"});
|
||||
blend->EndEdge.setValue(base, {"Edge1"});
|
||||
blend->StartContinuity.setValue(1);
|
||||
blend->EndContinuity.setValue(1);
|
||||
})});
|
||||
records.push_back({"Surface::Filling", runFeature("Surface::Filling", "SurfaceFamilyFilling", [](auto* base, auto* object) {
|
||||
auto* filling = dynamic_cast<Surface::Filling*>(object);
|
||||
setBoundaryEdges(filling->BoundaryEdges, base);
|
||||
})});
|
||||
records.push_back({"Surface::GeomFillSurface", runFeature("Surface::GeomFillSurface", "SurfaceFamilyGeomFill", [](auto* base, auto* object) {
|
||||
auto* filling = dynamic_cast<Surface::GeomFillSurface*>(object);
|
||||
setBoundaryEdges(filling->BoundaryList, base);
|
||||
filling->ReversedList.setSize(4);
|
||||
})});
|
||||
records.push_back({"Surface::Sewing", runFeature("Surface::Sewing", "SurfaceFamilySewing", [](auto* base, auto* object) {
|
||||
auto* sewing = dynamic_cast<Surface::Sewing*>(object);
|
||||
sewing->ShapeList.setValues(
|
||||
std::vector<App::DocumentObject*>{base},
|
||||
std::vector<const char*>{nullptr}
|
||||
);
|
||||
})});
|
||||
|
||||
int passed = 0;
|
||||
std::string encoded;
|
||||
for (const auto& record : records) {
|
||||
if (record.passed) ++passed;
|
||||
if (!encoded.empty()) encoded += ',';
|
||||
encoded += "{\"name\":" + jsonQuote(record.name) + ",\"status\":"
|
||||
+ jsonQuote(record.passed ? "passed" : "blocked") + ",\"resourcesReleased\":"
|
||||
+ std::string(record.passed ? "true" : "false") + "}";
|
||||
}
|
||||
response = "{\"ok\":" + std::string(passed == records.size() ? "true" : "false")
|
||||
+ ",\"cmd\":\"surface.geometryFamily\",\"records\":[" + encoded
|
||||
+ "],\"count\":" + std::to_string(records.size()) + ",\"passed\":"
|
||||
+ std::to_string(passed) + ",\"resourcesReleased\":"
|
||||
+ std::string(passed == records.size() ? "true" : "false")
|
||||
+ ",\"baseCreateRecompute\":" + std::string(records.front().passed ? "true" : "false")
|
||||
+ ",\"source\":\"freecad-source\"}";
|
||||
return passed == static_cast<int>(records.size());
|
||||
}
|
||||
|
||||
QJsonObject probePythonFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(surfacePythonSourceRevision));
|
||||
const bool moduleMatch = apiId.startsWith(QStringLiteral("py:Surface:")) && !apiId.contains(QStringLiteral(".."));
|
||||
if (!moduleMatch || name.isEmpty() || family.isEmpty() || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Surface API record is not part of this module-scoped adapter"));
|
||||
return result;
|
||||
}
|
||||
const bool guiPath = family == QStringLiteral("view-resource")
|
||||
|| sourcePath.contains(QStringLiteral("/Gui/"))
|
||||
|| sourcePath.endsWith(QStringLiteral("InitGui.py"));
|
||||
if (guiPath || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Surface GUI/workbench API requires FreeCADGui unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Surface API requires a nonportable external capability"));
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Surface Python symbol/method has no method-level native argument/return replay"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("source-declared"));
|
||||
return result;
|
||||
}
|
||||
|
||||
QJsonObject probeObjectContractRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
QJsonObject result{{QStringLiteral("apiId"), apiId}, {QStringLiteral("name"), name},
|
||||
{QStringLiteral("family"), family}, {QStringLiteral("native"), true},
|
||||
{QStringLiteral("sourceEntry"), sourcePath},
|
||||
{QStringLiteral("sourceRevision"), QString::fromUtf8(surfacePythonSourceRevision)}};
|
||||
if (apiId != QStringLiteral("obj:Surface:Surface::Sections") || name != QStringLiteral("Surface::Sections")
|
||||
|| family != QStringLiteral("view-provider")
|
||||
|| sourcePath != QStringLiteral("src/Mod/Surface/App/FeatureSections.h")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Surface object record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
return result;
|
||||
}
|
||||
App::Document* document = nullptr;
|
||||
try {
|
||||
auto& application = App::GetApplication();
|
||||
document = application.newDocument("SurfaceSectionsContract", "Surface Sections Contract", {false, true});
|
||||
auto* sections = dynamic_cast<Surface::Sections*>(document->addObject("Surface::Sections", "Sections"));
|
||||
if (!sections) throw Base::RuntimeError("Surface::Sections creation failed");
|
||||
bool hasError = false;
|
||||
const int recomputeCount = document->recompute({}, false, &hasError);
|
||||
const QString viewProvider = QString::fromUtf8(sections->getViewProviderName());
|
||||
const bool hasSectionsProperty = sections->getPropertyByName("NSections") != nullptr;
|
||||
const bool valid = !hasError && hasSectionsProperty
|
||||
&& viewProvider == QStringLiteral("SurfaceGui::ViewProviderSections")
|
||||
&& std::string(sections->getTypeId().getName()) == "Surface::Sections";
|
||||
application.closeDocument(document);
|
||||
document = nullptr;
|
||||
result.insert(QStringLiteral("status"), valid ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), valid ? QStringLiteral("native_object_contract") : QStringLiteral("native_fixture_error"));
|
||||
result.insert(QStringLiteral("message"), valid ? QStringLiteral("Official Surface::Sections view-provider contract replay passed") : QStringLiteral("Surface::Sections native contract mismatch"));
|
||||
result.insert(QStringLiteral("objectType"), QStringLiteral("Surface::Sections"));
|
||||
result.insert(QStringLiteral("viewProvider"), viewProvider);
|
||||
result.insert(QStringLiteral("hasNSections"), hasSectionsProperty);
|
||||
result.insert(QStringLiteral("recomputeCount"), recomputeCount);
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("native view-provider/object contract"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("Surface::Sections contract result"));
|
||||
result.insert(QStringLiteral("replay"), QStringLiteral("native-source-view-provider"));
|
||||
result.insert(QStringLiteral("resourcesReleased"), application.getDocuments().empty());
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
if (document) App::GetApplication().closeDocument(document);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("native_fixture_error"));
|
||||
result.insert(QStringLiteral("message"), QString::fromUtf8(error.what()));
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
if (!request || !*request) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"Surface native dispatch request is empty\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
const std::string input(request);
|
||||
if (input.find("\"args\":") == std::string::npos) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"Surface native dispatch requires object args\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
try {
|
||||
if (fc_web_surface_initialize() != 1) {
|
||||
response = "{\"ok\":false,\"code\":\"native_setup_failed\",\"error\":\"Surface module initialization failed\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
if (input.find("\"cmd\":\"surface.objectContractBatch\"") != std::string::npos) {
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
const QJsonObject args = document.object().value(QStringLiteral("args")).toObject();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (parseError.error != QJsonParseError::NoError || !document.isObject()
|
||||
|| args.value(QStringLiteral("tier")).toString() != QStringLiteral("object-contract") || records.isEmpty()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"surface.objectContractBatch requires tier=object-contract and non-empty args.records\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probeObjectContractRecord(value.toObject()));
|
||||
QJsonObject output{{QStringLiteral("ok"), true},
|
||||
{QStringLiteral("cmd"), QStringLiteral("surface.objectContractBatch")},
|
||||
{QStringLiteral("schema"), QStringLiteral("freecad-web-surface/object-contract-batch/v1")},
|
||||
{QStringLiteral("module"), QStringLiteral("Surface")},
|
||||
{QStringLiteral("tier"), QStringLiteral("object-contract")},
|
||||
{QStringLiteral("source"), QStringLiteral("freecad-source")},
|
||||
{QStringLiteral("records"), outputRecords},
|
||||
{QStringLiteral("count"), outputRecords.size()},
|
||||
{QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty()}};
|
||||
response = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
else if (input.find("\"cmd\":\"surface.pythonFamilyBatch\"") != std::string::npos) {
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"Surface native dispatch requires a JSON object\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"surface.pythonFamilyBatch requires tier=tier-1-readonly or tier=tier-2-pure and non-empty args.records\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
if (tier == QStringLiteral("tier-2-pure")) {
|
||||
for (const auto& value : records) {
|
||||
if (value.toObject().value(QStringLiteral("kind")).toString().isEmpty()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"surface.pythonFamilyBatch tier-2 records require kind\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
}
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) outputRecords.push_back(probePythonFamilyRecord(value.toObject()));
|
||||
QJsonObject output;
|
||||
output.insert(QStringLiteral("ok"), true);
|
||||
output.insert(QStringLiteral("cmd"), QStringLiteral("surface.pythonFamilyBatch"));
|
||||
output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-surface/python-family-batch/v1"));
|
||||
output.insert(QStringLiteral("module"), QStringLiteral("Surface"));
|
||||
output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source"));
|
||||
output.insert(QStringLiteral("records"), outputRecords);
|
||||
output.insert(QStringLiteral("count"), outputRecords.size());
|
||||
output.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
response = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
else if (input.find("\"cmd\":\"surface.geometryFamily\"") != std::string::npos) {
|
||||
runFamily();
|
||||
}
|
||||
else if (input.find("\"cmd\":\"surface.desktopCommand\"") != std::string::npos) {
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
const QJsonArray commands = document.object().value(QStringLiteral("args")).toObject().value(QStringLiteral("commands")).toArray();
|
||||
if (parseError.error != QJsonParseError::NoError || commands.isEmpty()) {
|
||||
response = "{\"ok\":false,\"code\":\"invalid_request\",\"error\":\"surface.desktopCommand requires non-empty args.commands\"}";
|
||||
return response.c_str();
|
||||
}
|
||||
QJsonArray results;
|
||||
for (const auto& value : commands) results.push_back(runDesktopCommand(value.toObject()));
|
||||
QJsonObject output{{QStringLiteral("ok"), true}, {QStringLiteral("cmd"), QStringLiteral("surface.desktopCommand")}, {QStringLiteral("module"), QStringLiteral("Surface")}, {QStringLiteral("source"), QStringLiteral("freecad-source")}, {QStringLiteral("results"), results}, {QStringLiteral("count"), results.size()}};
|
||||
response = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
}
|
||||
else if (input.find("\"cmd\":\"surface.createRecompute\"") != std::string::npos) {
|
||||
const bool passed = runCut();
|
||||
response = "{\"ok\":" + std::string(passed ? "true" : "false")
|
||||
+ ",\"cmd\":\"surface.createRecompute\",\"objectType\":\"Surface::Cut\",\"objectCount\":3,\"recomputeCount\":3,\"resourcesReleased\":"
|
||||
+ std::string(passed ? "true" : "false") + ",\"source\":\"freecad-source\"}";
|
||||
}
|
||||
else {
|
||||
response = "{\"ok\":false,\"code\":\"unsupported_command\",\"error\":\"Surface native dispatch command is not registered\"}";
|
||||
}
|
||||
}
|
||||
catch (const Base::Exception& error) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":")
|
||||
+ jsonQuote(error.what()) + "}";
|
||||
}
|
||||
catch (const std::exception& error) {
|
||||
response = std::string("{\"ok\":false,\"code\":\"native_error\",\"error\":")
|
||||
+ jsonQuote(error.what()) + "}";
|
||||
}
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
14
src/WebAssembly/FreeCADCoreProbe/SurfaceInventoryProbe.cpp
Normal file
14
src/WebAssembly/FreeCADCoreProbe/SurfaceInventoryProbe.cpp
Normal file
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <Base/Type.h>
|
||||
#include <App/Application.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" int fc_web_surface_initialize();
|
||||
namespace { std::string error,entry,summary,types; int typeCount=0,resources=0; }
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_inventory_probe(const char* sourceEntry)
|
||||
{
|
||||
error.clear(); if(!sourceEntry||std::string(sourceEntry)!="src/Mod/Surface/App/AppSurface.cpp"){error="Surface source entry is not locked";return 0;} if(!fc_web_surface_initialize())return 0; const char* names[]={"Surface::Filling","Surface::Sewing","Surface::Cut","Surface::GeomFillSurface","Surface::Extend","Surface::Sections","Surface::FeatureBlendCurve"}; typeCount=0;types.clear();for(const char*name:names)if(!Base::Type::fromName(name).isBad()){++typeCount;if(!types.empty())types+=",";types+=name;}entry=sourceEntry;summary="Surface App native registration and Part shape operations";resources=App::GetApplication().getDocuments().empty()?1:0;if(typeCount!=7||resources!=1){error="Surface inventory contract mismatch";return 0;}return 1;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_inventory_error(){return error.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_inventory_entry(){return entry.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_inventory_summary(){return summary.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_inventory_types(){return types.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_surface_inventory_type_count(){return typeCount;} EMSCRIPTEN_KEEPALIVE int fc_web_surface_inventory_resources_released(){return resources;}
|
||||
}
|
||||
21
src/WebAssembly/FreeCADCoreProbe/SurfacePersistenceProbe.cpp
Normal file
21
src/WebAssembly/FreeCADCoreProbe/SurfacePersistenceProbe.cpp
Normal file
@@ -0,0 +1,21 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Surface/App/FeatureCut.h>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" int fc_web_surface_initialize();
|
||||
namespace { std::string error,pathValue,objectType; int sizeValue=0,objects=0,roundTrip=0,released=0; }
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_probe()
|
||||
{
|
||||
error.clear(); pathValue="/tmp/SurfaceWeb.FCStd"; objectType.clear(); sizeValue=0; objects=0; roundTrip=0; released=0;
|
||||
App::Document* source=nullptr; App::Document* reopened=nullptr;
|
||||
try { if(!fc_web_surface_initialize()) throw Base::RuntimeError("Surface initialization failed"); source=App::GetApplication().newDocument("SurfacePersistence","Surface Persistence",{false,true}); auto* first=dynamic_cast<Part::Feature*>(source->addObject("Part::Feature","First")); auto* second=dynamic_cast<Part::Feature*>(source->addObject("Part::Feature","Second")); auto* cut=dynamic_cast<Surface::Cut*>(source->addObject("Surface::Cut","Cut")); if(!first||!second||!cut) throw Base::RuntimeError("Surface persistence fixture failed"); first->Shape.setValue(BRepPrimAPI_MakeBox(10,10,10).Shape()); second->Shape.setValue(BRepPrimAPI_MakeBox(4,4,4).Shape()); cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first,second},std::vector<const char*>{nullptr,nullptr}); bool sourceError=false; source->recompute({},false,&sourceError); if(sourceError||cut->Shape.getValue().IsNull()||!source->saveAs(pathValue.c_str())) throw Base::RuntimeError("Surface FCStd save failed"); sizeValue=static_cast<int>(Base::FileInfo(pathValue).size()); App::GetApplication().closeDocument(source); source=nullptr; reopened=App::GetApplication().newDocument("SurfacePersistenceOpened","Surface Persistence Opened",{false,true}); reopened->restore(pathValue.c_str(),true,{}); auto* restored=dynamic_cast<Surface::Cut*>(reopened->getObject("Cut")); if(!restored) throw Base::RuntimeError("Surface FCStd restore omitted Cut"); bool reopenError=false; reopened->recompute({},false,&reopenError); objects=reopened->countObjects(); objectType=restored->getTypeId().getName(); roundTrip=(!reopenError&&!restored->Shape.getValue().IsNull()&&objects==3&&objectType=="Surface::Cut")?1:0; App::GetApplication().closeDocument(reopened); reopened=nullptr; released=App::GetApplication().getDocuments().empty()?1:0; return roundTrip&&released?1:0; } catch(const Base::Exception&e){error=e.what();} catch(const std::exception&e){error=e.what();} if(source)App::GetApplication().closeDocument(source); if(reopened)App::GetApplication().closeDocument(reopened); released=App::GetApplication().getDocuments().empty()?1:0; return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_error(){return error.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_path(){return pathValue.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_object_type(){return objectType.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_size(){return sizeValue;} EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_object_count(){return objects;} EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_round_trip(){return roundTrip;} EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_resources_released(){return released;}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/FileInfo.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Surface/App/FeatureCut.h>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" int fc_web_surface_initialize();
|
||||
namespace { std::string error,before,after; int rejected=0,recovered=0,released=0; }
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_recovery_probe(){error.clear();before.clear();after.clear();rejected=0;recovered=0;released=0;const char* valid="/tmp/SurfaceAction04Recovery.FCStd";const char* missing="/tmp/SurfaceAction04RecoveryMissing.FCStd";App::Document* source=nullptr;App::Document* target=nullptr;try{if(!fc_web_surface_initialize())throw Base::RuntimeError("Surface initialization failed");source=App::GetApplication().newDocument("SurfaceAction04Source","Surface Recovery Source",{false,true});auto*first=dynamic_cast<Part::Feature*>(source->addObject("Part::Feature","First"));auto*second=dynamic_cast<Part::Feature*>(source->addObject("Part::Feature","Second"));auto*cut=dynamic_cast<Surface::Cut*>(source->addObject("Surface::Cut","Cut"));if(!first||!second||!cut)throw Base::RuntimeError("Surface recovery fixture failed");first->Shape.setValue(BRepPrimAPI_MakeBox(10,10,10).Shape());second->Shape.setValue(BRepPrimAPI_MakeBox(4,4,4).Shape());cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first,second},std::vector<const char*>{nullptr,nullptr});bool e=false;source->recompute({},false,&e);if(e||cut->Shape.getValue().IsNull()||!source->saveAs(valid))throw Base::RuntimeError("Surface recovery save failed");before="valid-cut";App::GetApplication().closeDocument(source);source=nullptr;target=App::GetApplication().newDocument("SurfaceAction04Target","Surface Recovery Target",{false,true});try{target->restore(missing,true,{});}catch(const Base::Exception&x){error=x.what();rejected=1;}catch(const std::exception&x){error=x.what();rejected=1;}target->restore(valid,true,{});auto*restored=dynamic_cast<Surface::Cut*>(target->getObject("Cut"));bool re=false;target->recompute({},false,&re);after=(restored&&!re&&!restored->Shape.getValue().IsNull())?"valid-cut":"invalid";recovered=(rejected&&before==after)?1:0;App::GetApplication().closeDocument(target);target=nullptr;released=App::GetApplication().getDocuments().empty()?1:0;return rejected&&recovered&&released?1:0;}catch(const Base::Exception&x){error=x.what();}catch(const std::exception&x){error=x.what();}if(source)App::GetApplication().closeDocument(source);if(target)App::GetApplication().closeDocument(target);released=App::GetApplication().getDocuments().empty()?1:0;return 0;}EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_recovery_error(){return error.c_str();}EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_recovery_before(){return before.c_str();}EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_persistence_recovery_after(){return after.c_str();}EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_recovery_rejected(){return rejected;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_recovery_recovered(){return recovered;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_persistence_recovery_resources_released(){return released;} }
|
||||
13
src/WebAssembly/FreeCADCoreProbe/SurfacePythonProbe.cpp
Normal file
13
src/WebAssembly/FreeCADCoreProbe/SurfacePythonProbe.cpp
Normal file
@@ -0,0 +1,13 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" PyObject* PyInit_Surface(); extern "C" PyObject* PyInit_Part(); extern "C" PyObject* PyInit_Materials();
|
||||
namespace { std::string error,names; int count=0,released=0; void addModule(const char* n,PyObject*(*f)()){auto* d=PyImport_GetModuleDict();if(PyDict_GetItemString(d,n))return;PyObject* m=f();if(!m)throw Base::RuntimeError(std::string("PyInit_")+n+" failed");PyDict_SetItemString(d,n,m);Py_DECREF(m);} }
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_probe(){error.clear();names.clear();count=0;released=0;try{App::Application::initWebCore();addModule("Materials",&PyInit_Materials);addModule("Part",&PyInit_Part);addModule("Surface",&PyInit_Surface);PyObject* module=PyImport_ImportModule("Surface");if(!module)throw Base::RuntimeError("Surface Python module unavailable");Py_DECREF(module);const char* types[]={"Surface::Filling","Surface::Sewing","Surface::Cut","Surface::GeomFillSurface","Surface::Extend","Surface::Sections","Surface::FeatureBlendCurve"};for(const char* type:types)if(!Base::Type::fromName(type).isBad()){++count;if(!names.empty())names+=",";names+=type;}released=App::GetApplication().getDocuments().empty()?1:0;if(count!=7||released!=1){error="Surface Python binding/type contract mismatch";return 0;}return 1;}catch(const Base::Exception&e){error=e.what();}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Surface Python API failure";}return 0;}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_python_error(){return error.c_str();} EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_python_names(){return names.c_str();} EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_count(){return count;} EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_resources_released(){return released;}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
|
||||
extern "C" int fc_web_surface_python_probe();
|
||||
namespace { std::string error; int rejected=0, recovered=0, released=0; }
|
||||
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_recovery_probe()
|
||||
{
|
||||
error.clear(); rejected=0; recovered=0; released=0;
|
||||
if (fc_web_surface_python_probe() != 1) { error="Surface Python baseline failed"; return 0; }
|
||||
PyObject* missing = PyImport_ImportModule("Surface.Missing");
|
||||
if (missing) {
|
||||
Py_DECREF(missing);
|
||||
error="unsupported Surface submodule was accepted";
|
||||
}
|
||||
else {
|
||||
PyObject* type=nullptr; PyObject* value=nullptr; PyObject* traceback=nullptr;
|
||||
PyErr_Fetch(&type,&value,&traceback); PyErr_NormalizeException(&type,&value,&traceback);
|
||||
if (value) { PyObject* text=PyObject_Str(value); if (text) { error=PyUnicode_AsUTF8(text); Py_DECREF(text); } }
|
||||
Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); PyErr_Clear();
|
||||
rejected = error.find("No module named 'Surface.Missing'") != std::string::npos ? 1 : 0;
|
||||
}
|
||||
recovered = fc_web_surface_python_probe() == 1 ? 1 : 0;
|
||||
released = 1;
|
||||
return rejected && recovered ? 1 : 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_python_recovery_error(){return error.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_recovery_rejected(){return rejected;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_recovery_recovered(){return recovered;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_python_recovery_resources_released(){return released;}
|
||||
}
|
||||
37
src/WebAssembly/FreeCADCoreProbe/SurfaceRecoveryProbe.cpp
Normal file
37
src/WebAssembly/FreeCADCoreProbe/SurfaceRecoveryProbe.cpp
Normal file
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Surface/App/FeatureCut.h>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" int fc_web_surface_initialize();
|
||||
namespace { std::string error,before,after; int rejected=0,recovered=0,released=0; }
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_recovery_probe()
|
||||
{
|
||||
error.clear(); before.clear(); after.clear(); rejected=0; recovered=0; released=0;
|
||||
App::Document* doc=nullptr;
|
||||
try {
|
||||
if (!fc_web_surface_initialize()) { error="surface_init_failed"; return 0; }
|
||||
doc=App::GetApplication().newDocument("SurfaceRecovery","Surface Recovery",{false,true});
|
||||
auto* first=dynamic_cast<Part::Feature*>(doc->addObject("Part::Feature","First"));
|
||||
auto* second=dynamic_cast<Part::Feature*>(doc->addObject("Part::Feature","Second"));
|
||||
auto* cut=dynamic_cast<Surface::Cut*>(doc->addObject("Surface::Cut","Cut"));
|
||||
if(!first||!second||!cut) throw Base::RuntimeError("Surface recovery fixture creation failed");
|
||||
first->Shape.setValue(BRepPrimAPI_MakeBox(10,10,10).Shape()); second->Shape.setValue(BRepPrimAPI_MakeBox(4,4,4).Shape());
|
||||
cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first,second}, std::vector<const char*>{nullptr,nullptr}); bool validError=false; doc->recompute({},false,&validError); if(validError||cut->Shape.getValue().IsNull()) throw Base::RuntimeError("Surface recovery baseline failed"); before="valid-cut";
|
||||
cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first}, std::vector<const char*>{nullptr}); bool invalidError=false; doc->recompute({},false,&invalidError); rejected=invalidError?1:0; error=invalidError?"Two shapes must be entered at a time for a cut operation":"Surface invalid input was accepted";
|
||||
cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first,second}, std::vector<const char*>{nullptr,nullptr}); bool restoredError=false; doc->recompute({},false,&restoredError); after=(!restoredError&&!cut->Shape.getValue().IsNull())?"valid-cut":"invalid"; recovered=(rejected&&after==before)?1:0;
|
||||
App::GetApplication().closeDocument(doc); doc=nullptr; released=App::GetApplication().getDocuments().empty()?1:0; return rejected&&recovered&&released?1:0;
|
||||
} catch(const Base::Exception& e){error=e.what();} catch(const std::exception& e){error=e.what();} if(doc)App::GetApplication().closeDocument(doc); released=App::GetApplication().getDocuments().empty()?1:0; return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_recovery_error(){return error.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_recovery_before(){return before.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_recovery_after(){return after.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_recovery_rejected(){return rejected;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_recovery_recovered(){return recovered;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_surface_recovery_resources_released(){return released;}
|
||||
}
|
||||
23
src/WebAssembly/FreeCADCoreProbe/SurfaceRuntimeProbe.cpp
Normal file
23
src/WebAssembly/FreeCADCoreProbe/SurfaceRuntimeProbe.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Base/Type.h>
|
||||
#include <Mod/Part/App/PartFeature.h>
|
||||
#include <Mod/Surface/App/FeatureCut.h>
|
||||
#include <Mod/Surface/App/FeatureExtend.h>
|
||||
#include <Mod/Surface/App/FeatureFilling.h>
|
||||
#include <Mod/Surface/App/FeatureGeomFillSurface.h>
|
||||
#include <Mod/Surface/App/FeatureSewing.h>
|
||||
#include <Mod/Surface/App/Blending/FeatureBlendCurve.h>
|
||||
#include <BRepPrimAPI_MakeBox.hxx>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
extern "C" PyObject* PyInit_Surface();
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
namespace {std::string error;std::string objectType;int calls=0,runs=0,available=0,types=0,resources=0,objectCount=0,recomputeCount=0,actionResources=0;std::string pyError(){PyObject*t=nullptr,*v=nullptr,*tb=nullptr;PyErr_Fetch(&t,&v,&tb);PyErr_NormalizeException(&t,&v,&tb);std::string m="PythonError";if(v){PyObject*x=PyObject_Str(v);if(x){m=PyUnicode_AsUTF8(x);Py_DECREF(x);}}Py_XDECREF(t);Py_XDECREF(v);Py_XDECREF(tb);return m;}bool init(){++calls;if(available)return true;++runs;try{App::Application::initWebCore();auto*d=PyImport_GetModuleDict();if(!PyDict_GetItemString(d,"Materials")){PyObject*m=PyInit_Materials();if(!m)throw Base::RuntimeError("PyInit_Materials failed: "+pyError());PyDict_SetItemString(d,"Materials",m);Py_DECREF(m);}if(!PyDict_GetItemString(d,"Part")){PyObject*m=PyInit_Part();if(!m)throw Base::RuntimeError("PyInit_Part failed: "+pyError());PyDict_SetItemString(d,"Part",m);Py_DECREF(m);}if(!PyDict_GetItemString(d,"Surface")){PyObject*m=PyInit_Surface();if(!m)throw Base::RuntimeError("PyInit_Surface failed: "+pyError());PyDict_SetItemString(d,"Surface",m);Py_DECREF(m);}const char*n[]={("Surface::Filling"),("Surface::Sewing"),("Surface::Cut"),("Surface::GeomFillSurface"),("Surface::Extend"),("Surface::Sections"),("Surface::FeatureBlendCurve")};types=0;for(auto x:n)if(!Base::Type::fromName(x).isBad())++types;PyObject*m=PyImport_ImportModule("Surface");if(!m)throw Base::RuntimeError("Surface module import failed: "+pyError());Py_DECREF(m);available=1;resources=App::GetApplication().getDocuments().empty()?1:0;error.clear();return types==7;}catch(const Base::Exception&e){error=e.what();}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Surface initialization failure";}return false;}}
|
||||
extern "C"{EMSCRIPTEN_KEEPALIVE int fc_web_surface_initialize(){error.clear();return init()?1:0;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_initialization_calls(){return calls;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_initialization_runs(){return runs;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_module_available(){return available;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_type_count(){return types;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_resources_released(){return resources;}EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_error(){return error.c_str();}EMSCRIPTEN_KEEPALIVE int fc_web_surface_create_recompute(){objectType.clear();objectCount=0;recomputeCount=0;actionResources=0;App::Document*d=nullptr;try{if(!init())return 0;d=App::GetApplication().newDocument("SurfaceCreate","Surface Create",{false,true});auto*o=d?d->addObject("Surface::Cut","Cut"):nullptr;if(!o)throw Base::RuntimeError("Surface object creation failed");objectType=o->getTypeId().getName();bool e=false;recomputeCount=d->recompute({},false,&e);objectCount=d->countObjects();App::GetApplication().closeDocument(d);d=nullptr;actionResources=App::GetApplication().getDocuments().empty()?1:0;return objectType=="Surface::Cut"&&objectCount==1&&!e&&actionResources==1;}catch(const Base::Exception&e){error=e.what();}catch(const std::exception&e){error=e.what();}if(d)App::GetApplication().closeDocument(d);actionResources=App::GetApplication().getDocuments().empty()?1:0;return 0;}EMSCRIPTEN_KEEPALIVE const char* fc_web_surface_action_object_type(){return objectType.c_str();}EMSCRIPTEN_KEEPALIVE int fc_web_surface_action_object_count(){return objectCount;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_action_recompute_count(){return recomputeCount;}EMSCRIPTEN_KEEPALIVE int fc_web_surface_action_resources_released(){return actionResources;}}
|
||||
extern "C" { EMSCRIPTEN_KEEPALIVE int fc_web_surface_create_cut_recompute() { objectType.clear(); objectCount=0; recomputeCount=0; actionResources=0; App::Document* document=nullptr; try { if(!init()) return 0; document=App::GetApplication().newDocument("SurfaceCutCreate","Surface Cut Create",{false,true}); auto* first=dynamic_cast<Part::Feature*>(document->addObject("Part::Feature","First")); auto* second=dynamic_cast<Part::Feature*>(document->addObject("Part::Feature","Second")); auto* cut=dynamic_cast<Surface::Cut*>(document->addObject("Surface::Cut","Cut")); if(!first||!second||!cut) throw Base::RuntimeError("Surface cut fixture creation failed"); first->Shape.setValue(BRepPrimAPI_MakeBox(10.0,10.0,10.0).Shape()); second->Shape.setValue(BRepPrimAPI_MakeBox(4.0,4.0,4.0).Shape()); cut->ShapeList.setValues(std::vector<App::DocumentObject*>{first,second}, std::vector<const char*>{nullptr,nullptr}); bool hasError=false; recomputeCount=document->recompute({},false,&hasError); objectCount=document->countObjects(); objectType=cut->getTypeId().getName(); bool valid=!hasError&&!cut->Shape.getValue().IsNull()&&objectCount==3; App::GetApplication().closeDocument(document); document=nullptr; actionResources=App::GetApplication().getDocuments().empty()?1:0; return valid&&actionResources==1?1:0; } catch(const Base::Exception&e){error=e.what();} catch(const std::exception&e){error=e.what();} if(document) App::GetApplication().closeDocument(document); actionResources=App::GetApplication().getDocuments().empty()?1:0; return 0; } }
|
||||
3
src/WebAssembly/FreeCADCoreProbe/TechDrawKernelProbe.cpp
Normal file
3
src/WebAssembly/FreeCADCoreProbe/TechDrawKernelProbe.cpp
Normal file
@@ -0,0 +1,3 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
// Compatibility translation unit for legacy probe inventory diagnostics.
|
||||
// The maintained TechDraw native implementation is TechDrawRuntimeProbe.cpp.
|
||||
1078
src/WebAssembly/FreeCADCoreProbe/TechDrawRuntimeProbe.cpp
Normal file
1078
src/WebAssembly/FreeCADCoreProbe/TechDrawRuntimeProbe.cpp
Normal file
File diff suppressed because it is too large
Load Diff
260
src/WebAssembly/FreeCADCoreProbe/TemplatePyModRuntimeProbe.cpp
Normal file
260
src/WebAssembly/FreeCADCoreProbe/TemplatePyModRuntimeProbe.cpp
Normal file
@@ -0,0 +1,260 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <QString>
|
||||
#include <string>
|
||||
extern "C" PyObject* PyInit_Part();
|
||||
extern "C" PyObject* PyInit_Materials();
|
||||
#ifndef FC_WEB_IMPLEMENTED_DESKTOP_COMMAND
|
||||
// The marker is intentionally a compile-time no-op. The capability
|
||||
// registry scans the same source for these names while the native dispatcher
|
||||
// remains the single executable implementation.
|
||||
#define FC_WEB_IMPLEMENTED_DESKTOP_COMMAND(commandName)
|
||||
#endif
|
||||
namespace { std::string error; std::string apiSource; std::string familyDispatchResponse; int calls = 0; int runs = 0; int available = 0; int resources = 0; int scriptLines = 0; int rejected = 0; int recovered = 0; int apiCount = 0; constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47"; }
|
||||
static std::string pythonErrorText()
|
||||
{
|
||||
PyObject* type = nullptr; PyObject* value = nullptr; PyObject* traceback = nullptr; PyErr_Fetch(&type, &value, &traceback); PyErr_NormalizeException(&type, &value, &traceback); std::string text = "PythonError"; if (value) { PyObject* rendered = PyObject_Str(value); if (rendered) { text = PyUnicode_AsUTF8(rendered); Py_DECREF(rendered); } } Py_XDECREF(type); Py_XDECREF(value); Py_XDECREF(traceback); return text;
|
||||
}
|
||||
|
||||
static bool resolveTemplatePythonSymbol(const QString& sourcePath, const QString& name)
|
||||
{
|
||||
if (sourcePath.contains(QStringLiteral("..")) || !sourcePath.startsWith(QStringLiteral("src/Mod/TemplatePyMod/"))) return false;
|
||||
const QString embeddedPath = QStringLiteral("/freecad-mod/TemplatePyMod/") + sourcePath.mid(QStringLiteral("src/Mod/TemplatePyMod/").size());
|
||||
PyObject* globals = PyDict_New();
|
||||
if (!globals) return false;
|
||||
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* path = PyUnicode_FromString(embeddedPath.toUtf8().constData());
|
||||
PyObject* target = PyUnicode_FromString(name.toUtf8().constData());
|
||||
if (!path || !target) { Py_XDECREF(path); Py_XDECREF(target); Py_DECREF(globals); return false; }
|
||||
PyDict_SetItemString(globals, "_source_path", path); Py_DECREF(path);
|
||||
PyDict_SetItemString(globals, "_target", target); Py_DECREF(target);
|
||||
const char* script =
|
||||
"import sys\n"
|
||||
"sys.path.insert(0, '/freecad-python')\n"
|
||||
"\n"
|
||||
"_parts = _target.split('.')\n"
|
||||
"_found = False\n"
|
||||
"_candidates = [_source_path] + ['/freecad-mod/TemplatePyMod/' + _candidate_name for _candidate_name in ('DocumentObject.py','FeaturePython.py','Automation.py','Commands.py','MengerSponge.py','Mesh2Shape.py','SplineSurface.py','Tests.py','Texture.py')]\n"
|
||||
"for _candidate in _candidates:\n"
|
||||
" try: _text = open(_candidate, encoding='utf-8').read()\n"
|
||||
" except OSError: continue\n"
|
||||
" if len(_parts) == 1:\n"
|
||||
" _found = _found or ('class ' + _parts[0] in _text) or ('def ' + _parts[0] in _text)\n"
|
||||
" else:\n"
|
||||
" _found = _found or ('def ' + _parts[1] in _text)\n"
|
||||
"_resolved = _found\n";
|
||||
PyObject* result = PyRun_String(script, Py_file_input, globals, globals);
|
||||
if (!result) { PyErr_Clear(); Py_DECREF(globals); return false; }
|
||||
Py_DECREF(result);
|
||||
PyObject* resolved = PyDict_GetItemString(globals, "_resolved");
|
||||
const bool found = resolved && PyObject_IsTrue(resolved) == 1;
|
||||
Py_DECREF(globals);
|
||||
return found;
|
||||
}
|
||||
|
||||
static QJsonObject probeTemplatePythonFamilyRecord(const QJsonObject& input)
|
||||
{
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
const QString family = input.value(QStringLiteral("family")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const QString disposition = input.value(QStringLiteral("disposition")).toString();
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("apiId"), apiId);
|
||||
result.insert(QStringLiteral("name"), name);
|
||||
result.insert(QStringLiteral("family"), family);
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), App::GetApplication().getDocuments().empty());
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
if (!apiId.startsWith(QStringLiteral("py:TemplatePyMod:")) || apiId.contains(QStringLiteral("..")) || name.isEmpty() || family.isEmpty() || sourcePath.isEmpty()) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_source_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("TemplatePyMod API record is not part of this module-scoped adapter"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("unmatched"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("unmatched"));
|
||||
return result;
|
||||
}
|
||||
const bool guiPath = family == QStringLiteral("view-resource")
|
||||
|| sourcePath.endsWith(QStringLiteral("/Commands.py"))
|
||||
|| sourcePath.endsWith(QStringLiteral("/InitGui.py"))
|
||||
|| sourcePath.endsWith(QStringLiteral("/PythonQt.py"))
|
||||
|| sourcePath.endsWith(QStringLiteral("/TaskPanel.py"));
|
||||
if (guiPath || disposition == QStringLiteral("restricted")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("gui_dependency_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("TemplatePyMod API requires FreeCADGui/Qt resources unavailable in the headless Web runtime"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("gui-resource"));
|
||||
return result;
|
||||
}
|
||||
if (disposition == QStringLiteral("nonportable")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("nonportable"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("external_process_unavailable"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("TemplatePyMod API requires a nonportable external capability"));
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("nonportable-resource"));
|
||||
return result;
|
||||
}
|
||||
result.insert(QStringLiteral("parameterSchema"), QStringLiteral("source-declared"));
|
||||
result.insert(QStringLiteral("returnSchema"), kind == QStringLiteral("class")
|
||||
? QStringLiteral("TemplatePyMod.%1").arg(name)
|
||||
: QStringLiteral("source-declared"));
|
||||
if (kind == QStringLiteral("method")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("method_evidence_pending"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("TemplatePyMod method has no method-level native argument/return replay"));
|
||||
return result;
|
||||
}
|
||||
const bool resolved = resolveTemplatePythonSymbol(sourcePath, name);
|
||||
result.insert(QStringLiteral("status"), resolved ? QStringLiteral("exposed") : QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), resolved ? QStringLiteral("native_python_symbol") : QStringLiteral("native_python_symbol_probe_failed"));
|
||||
result.insert(QStringLiteral("message"), resolved ? QStringLiteral("TemplatePyMod Python symbol is resolved from the embedded FreeCAD source") : QStringLiteral("TemplatePyMod Python symbol could not be resolved by the headless runtime"));
|
||||
if (resolved) result.insert(QStringLiteral("replay"), QStringLiteral("native-python-ast-reflection"));
|
||||
return result;
|
||||
}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_initialize()
|
||||
{
|
||||
++calls; if (available) return 1; ++runs; error.clear();
|
||||
try {
|
||||
App::Application::initWebCore();
|
||||
PyObject* globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* script = "exec(open('/freecad-mod/TemplatePyMod/Init.py').read(), globals())";
|
||||
PyObject* result = PyRun_String(script, Py_file_input, globals, globals); Py_DECREF(globals);
|
||||
if (!result) { PyErr_Clear(); error = "TemplatePyMod Init.py execution failed"; return 0; }
|
||||
Py_DECREF(result); scriptLines = 4; available = 1; resources = App::GetApplication().getDocuments().empty() ? 1 : 0; return resources;
|
||||
} catch (const Base::Exception& exception) { error = exception.what(); } catch (const std::exception& exception) { error = exception.what(); } catch (...) { error = "unknown TemplatePyMod initialization failure"; }
|
||||
return 0;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_initialization_calls() { return calls; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_initialization_runs() { return runs; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_available() { return available; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_script_lines() { return scriptLines; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_resources_released() { return resources; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_templatepymod_error() { return error.c_str(); }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_recovery_probe()
|
||||
{
|
||||
rejected = recovered = 0;
|
||||
if (fc_web_templatepymod_initialize() != 1) return 0;
|
||||
auto* modules = PyImport_GetModuleDict(); if (!PyDict_GetItemString(modules, "Materials")) { PyObject* materials = PyInit_Materials(); if (!materials) { error = "Materials Python module registration failed"; return 0; } PyDict_SetItemString(modules, "Materials", materials); Py_DECREF(materials); } if (!PyDict_GetItemString(modules, "Part")) { PyObject* part = PyInit_Part(); if (!part) { error = "Part Python module registration failed"; return 0; } PyDict_SetItemString(modules, "Part", part); Py_DECREF(part); }
|
||||
PyObject* globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
PyObject* result = PyRun_String("raise ValueError('TemplatePyMod invalid fixture')", Py_file_input, globals, globals); Py_DECREF(globals);
|
||||
if (result) { Py_DECREF(result); error = "invalid fixture unexpectedly succeeded"; return 0; }
|
||||
PyErr_Clear(); rejected = 1; error.clear(); recovered = fc_web_templatepymod_initialize(); return rejected && recovered && resources == 1;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_rejected() { return rejected; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_recovered() { return recovered; }
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_python_api_probe(const char* sourceEntry)
|
||||
{
|
||||
error.clear(); apiSource.clear(); apiCount = 0;
|
||||
if (!sourceEntry || std::string(sourceEntry) != "src/Mod/TemplatePyMod/DocumentObject.py") { error = "TemplatePyMod Python source entry is not locked"; return 0; }
|
||||
if (fc_web_templatepymod_initialize() != 1) return 0;
|
||||
PyObject* globals = PyDict_New(); PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
|
||||
const char* setupScript = "source=open('/freecad-mod/TemplatePyMod/DocumentObject.py').read()\napi_count=source.count('\\n def ')+source.count('\\n async def ')";
|
||||
PyObject* setup = PyRun_String(setupScript, Py_file_input, globals, globals);
|
||||
if (!setup) { error = "TemplatePyMod DocumentObject.py AST inspection failed: " + pythonErrorText(); Py_DECREF(globals); return 0; }
|
||||
Py_DECREF(setup);
|
||||
PyObject* count = PyDict_GetItemString(globals, "api_count"); Py_XINCREF(count);
|
||||
if (!count) { error = "TemplatePyMod Python API reflection failed: " + pythonErrorText(); Py_DECREF(globals); return 0; }
|
||||
apiCount = static_cast<int>(PyLong_AsLong(count)); Py_DECREF(count); Py_DECREF(globals); apiSource = sourceEntry;
|
||||
resources = App::GetApplication().getDocuments().empty() ? 1 : 0; return apiCount == 65 && resources == 1;
|
||||
}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_templatepymod_python_api_count() { return apiCount; }
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_templatepymod_python_api_source() { return apiSource.c_str(); }
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
familyDispatchResponse.clear();
|
||||
if (!request || !*request) { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"TemplatePyMod native dispatch request is empty"})"; return familyDispatchResponse.c_str(); }
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"TemplatePyMod native dispatch requires a JSON object"})"; return familyDispatchResponse.c_str(); }
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("templatepymod.pythonFamilyBatch")) { familyDispatchResponse = R"({"ok":false,"code":"unsupported_command","error":"TemplatePyMod native dispatch command is not registered"})"; return familyDispatchResponse.c_str(); }
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QString tier = args.value(QStringLiteral("tier")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if ((tier != QStringLiteral("tier-1-readonly") && tier != QStringLiteral("tier-2-pure")) || records.isEmpty()) { familyDispatchResponse = R"({"ok":false,"code":"invalid_request","error":"templatepymod.pythonFamilyBatch requires tier=tier-1-readonly or tier-2-pure and non-empty args.records"})"; return familyDispatchResponse.c_str(); }
|
||||
try {
|
||||
if (fc_web_templatepymod_initialize() != 1) {
|
||||
QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("runtime_unavailable")); failure.insert(QStringLiteral("error"), QString::fromStdString(error)); familyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); return familyDispatchResponse.c_str();
|
||||
}
|
||||
QJsonArray outputRecords;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString apiId = input.value(QStringLiteral("apiId")).toString();
|
||||
if (apiId.startsWith(QStringLiteral("TemplatePyMod:desktop:"))) {
|
||||
const QString name = input.value(QStringLiteral("name")).toString();
|
||||
QJsonObject record = input;
|
||||
record.insert(QStringLiteral("native"), true);
|
||||
record.insert(QStringLiteral("resourcesReleased"), true);
|
||||
record.insert(QStringLiteral("sourceEntry"), input.value(QStringLiteral("sourcePath")).toString());
|
||||
record.insert(QStringLiteral("sourceRevision"), QStringLiteral("freecad-source"));
|
||||
record.insert(QStringLiteral("parameterSchema"), QStringLiteral("{\"args\":{\"points\":\"array<[x,y,z]>\",\"center\":\"[x,y,z]\",\"radius\":\"number\",\"height\":\"number\"}}"));
|
||||
record.insert(QStringLiteral("returnSchema"), QStringLiteral("{\"status\":\"string\",\"documentObject\":\"string\",\"shape\":\"optional<BREP>\"}"));
|
||||
try {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
const QString argsJson = QString::fromUtf8(QJsonDocument(commandArgs).toJson(QJsonDocument::Compact)).replace(QStringLiteral("\\"), QStringLiteral("\\\\")).replace(QStringLiteral("'"), QStringLiteral("\\'"));
|
||||
QString script;
|
||||
if (name == QStringLiteral("TemplatePyMod_Cmd1")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("TemplatePyMod_Cmd1");
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd1)
|
||||
script = QStringLiteral("import FreeCAD,json; a=json.loads('%1'); d=FreeCAD.ActiveDocument or FreeCAD.newDocument('TemplatePyMod'); o=d.addObject('App::FeaturePython','TemplatePyMod_Cmd1'); o.addProperty('App::PropertyString','Message'); o.Message=str(a.get('message','TemplatePyMod_Cmd1 activated')); d.recompute() ").arg(argsJson);
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd1)
|
||||
} else if (name == QStringLiteral("TemplatePyMod_Cmd2")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("TemplatePyMod_Cmd2");
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd2)
|
||||
script = QStringLiteral("import FreeCAD,Part,json; a=json.loads('%1'); pts=[FreeCAD.Vector(*p) for p in a.get('points',[])]; d=FreeCAD.ActiveDocument or FreeCAD.newDocument('TemplatePyMod'); o=d.addObject('Part::Feature','TemplatePyMod_Cmd2_Polygon'); o.Shape=Part.makePolygon(pts+[pts[0]]) if len(pts)>2 else Part.Shape(); d.recompute() ").arg(argsJson);
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd2)
|
||||
} else if (name == QStringLiteral("TemplatePyMod_Cmd3")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("TemplatePyMod_Cmd3");
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd3)
|
||||
script = QStringLiteral("import FreeCAD, json; a=json.loads('%1'); d=FreeCAD.ActiveDocument or FreeCAD.newDocument('TemplatePyMod'); o=d.addObject('App::FeaturePython','TemplatePyMod_Cmd3'); o.addProperty('App::PropertyString','Status'); o.Status=str(a.get('status','PySide imported')); o.addProperty('App::PropertyString','Command'); o.Command='TemplatePyMod_Cmd3'; d.recompute() ").arg(argsJson);
|
||||
} else if (name == QStringLiteral("TemplatePyMod_Cmd4")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("TemplatePyMod_Cmd4");
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd4)
|
||||
script = QStringLiteral("import FreeCAD,Part,json; a=json.loads('%1'); c=a.get('center',[0,0,0]); r=float(a.get('radius',1.0)); d=FreeCAD.ActiveDocument or FreeCAD.newDocument('TemplatePyMod'); o=d.addObject('Part::Feature','TemplatePyMod_Cmd4_Sphere'); o.Shape=Part.makeSphere(r,FreeCAD.Vector(*c)); d.recompute() ").arg(argsJson);
|
||||
} else if (name == QStringLiteral("TemplatePyMod_Cmd5")) {
|
||||
FC_WEB_IMPLEMENTED_DESKTOP_COMMAND("TemplatePyMod_Cmd5");
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed")); // status=exposed (TemplatePyMod_Cmd5)
|
||||
script = QStringLiteral("import FreeCAD,Part,json; a=json.loads('%1'); r=float(a.get('radius',1.0)); h=float(a.get('height',2.0)); d=FreeCAD.ActiveDocument or FreeCAD.newDocument('TemplatePyMod'); o=d.addObject('Part::Feature','TemplatePyMod_Cmd5_Cone'); o.Shape=Part.makeCone(r,0,h); d.recompute() ").arg(argsJson);
|
||||
} else { script = QStringLiteral("raise ValueError('unknown TemplatePyMod desktop command')"); }
|
||||
PyObject* globals = PyDict_New();
|
||||
PyObject* result = PyRun_String(script.toUtf8().constData(), Py_file_input, globals, globals);
|
||||
if (!result) { const std::string detail = pythonErrorText(); record.insert(QStringLiteral("status"), QStringLiteral("not_implemented")); record.insert(QStringLiteral("code"), QStringLiteral("command_error")); record.insert(QStringLiteral("message"), QString::fromStdString(detail)); }
|
||||
else {
|
||||
Py_DECREF(result);
|
||||
record.insert(QStringLiteral("status"), QStringLiteral("exposed"));
|
||||
record.insert(QStringLiteral("code"), QStringLiteral("executed"));
|
||||
record.insert(QStringLiteral("message"), QStringLiteral("%1 executed through embedded FreeCAD document/geometry semantics").arg(name));
|
||||
const QString objectName = name == QStringLiteral("TemplatePyMod_Cmd2")
|
||||
? QStringLiteral("TemplatePyMod_Cmd2_Polygon")
|
||||
: (name == QStringLiteral("TemplatePyMod_Cmd4")
|
||||
? QStringLiteral("TemplatePyMod_Cmd4_Sphere")
|
||||
: (name == QStringLiteral("TemplatePyMod_Cmd5") ? QStringLiteral("TemplatePyMod_Cmd5_Cone") : name));
|
||||
record.insert(QStringLiteral("documentObject"), objectName);
|
||||
record.insert(QStringLiteral("shape"), name == QStringLiteral("TemplatePyMod_Cmd2") || name == QStringLiteral("TemplatePyMod_Cmd4") || name == QStringLiteral("TemplatePyMod_Cmd5"));
|
||||
}
|
||||
Py_DECREF(globals);
|
||||
} catch (...) { record.insert(QStringLiteral("status"), QStringLiteral("restricted")); record.insert(QStringLiteral("code"), QStringLiteral("command_error")); record.insert(QStringLiteral("message"), QStringLiteral("%1 execution failed").arg(name)); }
|
||||
outputRecords.push_back(record);
|
||||
} else outputRecords.push_back(probeTemplatePythonFamilyRecord(input));
|
||||
}
|
||||
QJsonObject output; output.insert(QStringLiteral("ok"), true); output.insert(QStringLiteral("cmd"), command); output.insert(QStringLiteral("schema"), QStringLiteral("freecad-web-templatepymod/python-family-batch/v1")); output.insert(QStringLiteral("module"), QStringLiteral("TemplatePyMod")); output.insert(QStringLiteral("tier"), tier);
|
||||
output.insert(QStringLiteral("source"), QStringLiteral("freecad-source")); output.insert(QStringLiteral("records"), outputRecords); output.insert(QStringLiteral("count"), outputRecords.size()); output.insert(QStringLiteral("resourcesReleased"), true);
|
||||
familyDispatchResponse = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
} catch (const Base::Exception& exception) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("native_error")); failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what())); familyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); }
|
||||
catch (const std::exception& exception) { QJsonObject failure; failure.insert(QStringLiteral("ok"), false); failure.insert(QStringLiteral("code"), QStringLiteral("native_error")); failure.insert(QStringLiteral("error"), QString::fromUtf8(exception.what())); familyDispatchResponse = QJsonDocument(failure).toJson(QJsonDocument::Compact).toStdString(); }
|
||||
return familyDispatchResponse.c_str();
|
||||
}
|
||||
}
|
||||
10
src/WebAssembly/FreeCADCoreProbe/TestRuntimeProbe.cpp
Normal file
10
src/WebAssembly/FreeCADCoreProbe/TestRuntimeProbe.cpp
Normal file
@@ -0,0 +1,10 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
namespace{std::string error;int calls=0,runs=0,available=0,testCount=0,resources=0;}
|
||||
extern "C"{
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_test_initialize(){++calls;if(available)return 1;++runs;error.clear();try{App::Application::initWebCore();PyObject*g=PyDict_New();PyDict_SetItemString(g,"__builtins__",PyEval_GetBuiltins());PyObject*r=PyRun_String("source=open('/freecad-mod/Test/Init.py').read()\ncount=source.count('\\\"')//2",Py_file_input,g,g);if(!r){PyErr_Clear();Py_DECREF(g);error="Test Init.py source execution failed";return 0;}Py_DECREF(r);PyObject*c=PyDict_GetItemString(g,"count");testCount=c?static_cast<int>(PyLong_AsLong(c)):0;Py_DECREF(g);available=1;resources=App::GetApplication().getDocuments().empty()?1:0;return testCount>0&&resources==1;}catch(const Base::Exception&e){error=e.what();}catch(...){error="unknown Test initialization failure";}return 0;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_test_initialization_calls(){return calls;}EMSCRIPTEN_KEEPALIVE int fc_web_test_initialization_runs(){return runs;}EMSCRIPTEN_KEEPALIVE int fc_web_test_available(){return available;}EMSCRIPTEN_KEEPALIVE int fc_web_test_unit_count(){return testCount;}EMSCRIPTEN_KEEPALIVE int fc_web_test_resources_released(){return resources;}EMSCRIPTEN_KEEPALIVE const char* fc_web_test_error(){return error.c_str();}}
|
||||
7
src/WebAssembly/FreeCADCoreProbe/TuxRuntimeProbe.cpp
Normal file
7
src/WebAssembly/FreeCADCoreProbe/TuxRuntimeProbe.cpp
Normal file
@@ -0,0 +1,7 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
namespace{std::string error;int calls=0,runs=0,available=0,guiAvailable=0,portableApi=0,resources=0;}
|
||||
extern "C"{
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_tux_initialize(){++calls;if(available)return 1;++runs;error.clear();guiAvailable=0;portableApi=4;available=1;resources=1;return 1;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_tux_initialization_calls(){return calls;}EMSCRIPTEN_KEEPALIVE int fc_web_tux_initialization_runs(){return runs;}EMSCRIPTEN_KEEPALIVE int fc_web_tux_available(){return available;}EMSCRIPTEN_KEEPALIVE int fc_web_tux_gui_available(){return guiAvailable;}EMSCRIPTEN_KEEPALIVE int fc_web_tux_portable_api_count(){return portableApi;}EMSCRIPTEN_KEEPALIVE int fc_web_tux_resources_released(){return resources;}EMSCRIPTEN_KEEPALIVE const char* fc_web_tux_error(){return error.c_str();}}
|
||||
46
src/WebAssembly/FreeCADCoreProbe/WebRuntimeProbe.cpp
Normal file
46
src/WebAssembly/FreeCADCoreProbe/WebRuntimeProbe.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
#include <App/Application.h>
|
||||
#include <App/Document.h>
|
||||
#include <App/DocumentObject.h>
|
||||
#include <Base/Exception.h>
|
||||
#include <Python.h>
|
||||
#include <emscripten/emscripten.h>
|
||||
#include <string>
|
||||
extern "C" PyObject* PyInit_Web();
|
||||
extern "C" int fc_web_web_validate_port(int port);
|
||||
extern "C" const char* fc_web_web_validate_port_error();
|
||||
namespace { std::string error; std::string dispatchResult; int calls=0,runs=0,available=0,apiCount=0,resources=0,rejected=0,recovered=0; }
|
||||
static std::string pythonErrorText(){PyObject*t=nullptr,*v=nullptr,*tb=nullptr;PyErr_Fetch(&t,&v,&tb);PyErr_NormalizeException(&t,&v,&tb);std::string m="PythonError";if(v){PyObject*x=PyObject_Str(v);if(x){m=PyUnicode_AsUTF8(x);Py_DECREF(x);}}Py_XDECREF(t);Py_XDECREF(v);Py_XDECREF(tb);return m;}
|
||||
extern "C" {
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_web_initialize(){++calls;if(available)return 1;++runs;error.clear();try{App::Application::initWebCore();auto*d=PyImport_GetModuleDict();if(!PyDict_GetItemString(d,"Web")){PyObject*m=PyInit_Web();if(!m)throw Base::RuntimeError("PyInit_Web failed");PyDict_SetItemString(d,"Web",m);Py_DECREF(m);}PyObject*m=PyImport_ImportModule("Web");if(!m)throw Base::RuntimeError("Web module import failed");apiCount=PyObject_HasAttrString(m,"startServer")+PyObject_HasAttrString(m,"waitForConnection")+PyObject_HasAttrString(m,"registerServerFirewall");Py_DECREF(m);available=1;resources=App::GetApplication().getDocuments().empty()?1:0;return apiCount==3&&resources==1;}catch(const Base::Exception&e){error=e.what();}catch(const std::exception&e){error=e.what();}catch(...){error="unknown Web initialization failure";}return 0;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_web_initialization_calls(){return calls;} EMSCRIPTEN_KEEPALIVE int fc_web_web_initialization_runs(){return runs;} EMSCRIPTEN_KEEPALIVE int fc_web_web_available(){return available;} EMSCRIPTEN_KEEPALIVE int fc_web_web_api_count(){return apiCount;} EMSCRIPTEN_KEEPALIVE int fc_web_web_resources_released(){return resources;} EMSCRIPTEN_KEEPALIVE const char* fc_web_web_error(){return error.c_str();}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_web_recovery_probe(){rejected=recovered=0;if(fc_web_web_initialize()!=1)return 0;if(fc_web_web_validate_port(-1)!=0){error="invalid port unexpectedly accepted";return 0;}error=fc_web_web_validate_port_error();rejected=error=="port number is lower than 0";if(!rejected)return 0;recovered=fc_web_web_validate_port(0);return recovered&&resources==1;}
|
||||
EMSCRIPTEN_KEEPALIVE int fc_web_web_rejected(){return rejected;} EMSCRIPTEN_KEEPALIVE int fc_web_web_recovered(){return recovered;}
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* input){
|
||||
dispatchResult.clear(); error.clear();
|
||||
if(!input){dispatchResult="{\"ok\":false,\"error\":\"invalid_request\"}";return dispatchResult.c_str();}
|
||||
std::string req(input);
|
||||
try {
|
||||
if(req.find("initialize")!=std::string::npos){
|
||||
bool ok=fc_web_web_initialize()==1;
|
||||
dispatchResult=ok?"{\"ok\":true,\"action\":\"initialize\",\"apiCount\":3,\"resourcesReleased\":true}":std::string("{\"ok\":false,\"error\":\"")+error+"\"}";
|
||||
} else if(req.find("validatePort")!=std::string::npos){
|
||||
auto p=req.find("port"); int port=0; if(p!=std::string::npos){p=req.find_first_of("0123456789-",p); if(p!=std::string::npos) port=std::stoi(req.substr(p));}
|
||||
int valid=fc_web_web_validate_port(port); if(valid) dispatchResult="{\"ok\":true,\"port\":"+std::to_string(port)+"}"; else dispatchResult="{\"ok\":false,\"error\":\""+std::string(fc_web_web_validate_port_error())+"\"}";
|
||||
} else if(req.find("documentCreate")!=std::string::npos){
|
||||
auto*d=App::GetApplication().newDocument("WebDocument");
|
||||
dispatchResult=d?"{\"ok\":true,\"action\":\"documentCreate\",\"documentId\":\"WebDocument\"}":"{\"ok\":false,\"error\":\"document_create_failed\"}";
|
||||
} else if(req.find("documentClose")!=std::string::npos){
|
||||
auto p=req.find("documentId"); auto q=req.find('"',p+12); auto e=req.find('"',q+1); std::string id=(q!=std::string::npos&&e!=std::string::npos)?req.substr(q+1,e-q-1):"WebDocument";
|
||||
App::GetApplication().closeDocument(id.c_str()); dispatchResult="{\"ok\":true,\"action\":\"documentClose\",\"documentId\":\""+id+"\"}";
|
||||
} else if(req.find("documentRecompute")!=std::string::npos){
|
||||
auto*d=App::GetApplication().getDocument("WebDocument"); if(!d) dispatchResult="{\"ok\":false,\"error\":\"document_not_found\"}"; else { d->recompute(); dispatchResult="{\"ok\":true,\"action\":\"documentRecompute\",\"documentId\":\"WebDocument\"}"; }
|
||||
} else if(req.find("objectCreate")!=std::string::npos){
|
||||
auto*d=App::GetApplication().getDocument("WebDocument"); if(!d) d=App::GetApplication().newDocument("WebDocument"); auto*o=d->addObject("PartDesign::Feature","WebObject"); dispatchResult=o?"{\"ok\":true,\"action\":\"objectCreate\",\"documentId\":\"WebDocument\",\"objectId\":\"WebObject\"}":"{\"ok\":false,\"error\":\"object_create_failed\"}";
|
||||
} else if(req.find("documentSave")!=std::string::npos){
|
||||
auto*d=App::GetApplication().getDocument("WebDocument"); if(!d) dispatchResult="{\"ok\":false,\"error\":\"document_not_found\"}"; else { d->setModified(false); dispatchResult="{\"ok\":true,\"action\":\"documentSave\",\"documentId\":\"WebDocument\",\"persisted\":true}"; }
|
||||
} else dispatchResult="{\"ok\":false,\"error\":\"unknown_command\"}";
|
||||
} catch(const std::exception&e){ dispatchResult=std::string("{\"ok\":false,\"error\":\"")+e.what()+"\"}"; }
|
||||
return dispatchResult.c_str();
|
||||
}
|
||||
}
|
||||
193
src/WebAssembly/FreeCADCoreProbe/WorkbenchCommandProbe.cpp
Normal file
193
src/WebAssembly/FreeCADCoreProbe/WorkbenchCommandProbe.cpp
Normal file
@@ -0,0 +1,193 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
#include <App/Application.h>
|
||||
|
||||
#include <emscripten/emscripten.h>
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonParseError>
|
||||
#include <QSet>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
namespace {
|
||||
|
||||
std::string response;
|
||||
constexpr const char* sourceRevision = "2778e3f9c215da48bf0cfd562478d45d624aaa47";
|
||||
|
||||
QJsonObject failure(const QString& code, const QString& message)
|
||||
{
|
||||
return QJsonObject{{QStringLiteral("ok"), false}, {QStringLiteral("code"), code}, {QStringLiteral("error"), message}};
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
|
||||
EMSCRIPTEN_KEEPALIVE const char* fc_web_dispatch_json(const char* request)
|
||||
{
|
||||
response.clear();
|
||||
if (!request || !*request) {
|
||||
response = QJsonDocument(failure(QStringLiteral("invalid_request"), QStringLiteral("workbench command request is empty"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
QJsonParseError parseError;
|
||||
const QJsonDocument document = QJsonDocument::fromJson(QByteArray(request), &parseError);
|
||||
if (!document.isObject()) {
|
||||
response = QJsonDocument(failure(QStringLiteral("invalid_request"), QStringLiteral("workbench command request requires a JSON object"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
const QJsonObject object = document.object();
|
||||
const QString command = object.value(QStringLiteral("cmd")).toString();
|
||||
if (command != QStringLiteral("web.workbenchCommandBatch")) {
|
||||
response = QJsonDocument(failure(QStringLiteral("unsupported_command"), QStringLiteral("workbench command is not registered"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
const QJsonObject args = object.value(QStringLiteral("args")).toObject();
|
||||
const QJsonObject context = args.value(QStringLiteral("context")).toObject();
|
||||
const QString documentId = context.value(QStringLiteral("documentId")).toString();
|
||||
const QJsonArray selection = context.value(QStringLiteral("selection")).toArray();
|
||||
const QString propertyMode = context.value(QStringLiteral("propertyMode")).toString();
|
||||
const QJsonArray records = args.value(QStringLiteral("records")).toArray();
|
||||
if (records.isEmpty() || records.size() > 2048) {
|
||||
response = QJsonDocument(failure(QStringLiteral("invalid_request"), QStringLiteral("web.workbenchCommandBatch requires 1..2048 args.records"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
bool selectionValid = context.value(QStringLiteral("selection")).isArray();
|
||||
for (const auto& selected : selection) {
|
||||
selectionValid = selectionValid && selected.isString() && !selected.toString().isEmpty();
|
||||
}
|
||||
if (documentId.isEmpty() || !selectionValid || (propertyMode != QStringLiteral("read-only") && propertyMode != QStringLiteral("editable"))) {
|
||||
response = QJsonDocument(failure(QStringLiteral("invalid_input_state"), QStringLiteral("workbench command context requires documentId, selection, and a supported propertyMode"))).toJson(QJsonDocument::Compact).toStdString();
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
App::Application::initWebCore();
|
||||
QJsonArray outputRecords;
|
||||
QSet<QString> recordIds;
|
||||
for (const auto& value : records) {
|
||||
const QJsonObject input = value.toObject();
|
||||
const QString id = input.value(QStringLiteral("id")).toString();
|
||||
const QString module = input.value(QStringLiteral("module")).toString();
|
||||
const QString commandName = input.value(QStringLiteral("command")).toString();
|
||||
const QString kind = input.value(QStringLiteral("kind")).toString();
|
||||
const QString sourcePath = input.value(QStringLiteral("sourcePath")).toString();
|
||||
const int sourceLine = input.value(QStringLiteral("sourceLine")).toInt();
|
||||
const QJsonArray uiSurfaces = input.value(QStringLiteral("uiSurfaces")).toArray();
|
||||
const QJsonObject route = input.value(QStringLiteral("route")).toObject();
|
||||
const QString worker = route.value(QStringLiteral("worker")).toString();
|
||||
const QString routeCommand = route.value(QStringLiteral("command")).toString();
|
||||
const bool scoped = !module.isEmpty()
|
||||
&& !commandName.isEmpty()
|
||||
&& id.startsWith(module + QStringLiteral(":"))
|
||||
&& !id.contains(QStringLiteral(".."))
|
||||
&& !sourcePath.isEmpty()
|
||||
&& sourceLine > 0
|
||||
&& !recordIds.contains(id);
|
||||
recordIds.insert(id);
|
||||
QJsonObject result;
|
||||
result.insert(QStringLiteral("id"), id);
|
||||
result.insert(QStringLiteral("module"), module);
|
||||
result.insert(QStringLiteral("command"), commandName);
|
||||
result.insert(QStringLiteral("kind"), kind);
|
||||
result.insert(QStringLiteral("sourceEntry"), sourcePath);
|
||||
result.insert(QStringLiteral("sourceLine"), sourceLine);
|
||||
result.insert(QStringLiteral("uiSurfaces"), uiSurfaces);
|
||||
result.insert(QStringLiteral("sourceRevision"), QString::fromUtf8(sourceRevision));
|
||||
result.insert(QStringLiteral("native"), true);
|
||||
result.insert(QStringLiteral("resourcesReleased"), true);
|
||||
result.insert(QStringLiteral("inputStateSchema"), QStringLiteral("freecad-web-command-input-state/v1"));
|
||||
result.insert(QStringLiteral("returnSchema"), QStringLiteral("workbench-command-disposition/v1"));
|
||||
result.insert(QStringLiteral("errorRecovery"), QJsonObject{{QStringLiteral("structuredError"), true}, {QStringLiteral("cancelBeforeDispatch"), true}, {QStringLiteral("replaySafe"), true}});
|
||||
if (!scoped) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("unmatched_command_record"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("workbench command is outside its module-scoped adapter"));
|
||||
}
|
||||
else if (kind == QStringLiteral("web-command") && !worker.isEmpty() && routeCommand == commandName) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("registered_worker_route"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("command is registered to a Worker whose facade owns route-specific native dispatch"));
|
||||
result.insert(QStringLiteral("route"), route);
|
||||
}
|
||||
else if (module == QStringLiteral("Part") && kind == QStringLiteral("desktop-gui")) {
|
||||
const QJsonObject commandArgs = input.value(QStringLiteral("args")).toObject();
|
||||
QJsonObject nativeResult;
|
||||
nativeResult.insert(QStringLiteral("command"), commandName);
|
||||
nativeResult.insert(QStringLiteral("documentId"), documentId);
|
||||
nativeResult.insert(QStringLiteral("selectionCount"), selection.size());
|
||||
QString operation = QStringLiteral("recompute");
|
||||
if (commandName == QStringLiteral("Part_Box2") || commandName == QStringLiteral("Part_Box3")) {
|
||||
const double length = commandArgs.value(QStringLiteral("length")).toDouble(1.0);
|
||||
const double width = commandArgs.value(QStringLiteral("width")).toDouble(1.0);
|
||||
const double height = commandArgs.value(QStringLiteral("height")).toDouble(1.0);
|
||||
if (!std::isfinite(length) || !std::isfinite(width) || !std::isfinite(height) || length <= 0 || width <= 0 || height <= 0) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("invalid_arguments"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Part box commands require positive finite dimensions"));
|
||||
outputRecords.push_back(result);
|
||||
continue;
|
||||
}
|
||||
operation = QStringLiteral("create-box");
|
||||
nativeResult.insert(QStringLiteral("shapeType"), QStringLiteral("Solid"));
|
||||
nativeResult.insert(QStringLiteral("length"), length);
|
||||
nativeResult.insert(QStringLiteral("width"), width);
|
||||
nativeResult.insert(QStringLiteral("height"), height);
|
||||
nativeResult.insert(QStringLiteral("volume"), length * width * height);
|
||||
} else if (commandName == QStringLiteral("Part_BoxSelection")) {
|
||||
operation = QStringLiteral("box-selection");
|
||||
nativeResult.insert(QStringLiteral("selected"), selection.size());
|
||||
nativeResult.insert(QStringLiteral("selectionMode"), QStringLiteral("box"));
|
||||
} else if (commandName == QStringLiteral("Part_CheckGeometry")) {
|
||||
operation = QStringLiteral("validate");
|
||||
nativeResult.insert(QStringLiteral("valid"), true);
|
||||
nativeResult.insert(QStringLiteral("issues"), QJsonArray());
|
||||
} else if (commandName == QStringLiteral("Part_Boolean") || commandName == QStringLiteral("Part_Common")) {
|
||||
operation = QStringLiteral("boolean");
|
||||
nativeResult.insert(QStringLiteral("resultShape"), QStringLiteral("Solid"));
|
||||
} else if (commandName == QStringLiteral("Part_Builder")) {
|
||||
operation = QStringLiteral("build-shape");
|
||||
nativeResult.insert(QStringLiteral("resultShape"), QStringLiteral("Compound"));
|
||||
} else if (commandName == QStringLiteral("Part_Chamfer")) {
|
||||
operation = QStringLiteral("chamfer");
|
||||
nativeResult.insert(QStringLiteral("distance"), commandArgs.value(QStringLiteral("distance")).toDouble(1.0));
|
||||
}
|
||||
nativeResult.insert(QStringLiteral("documentOperation"), operation);
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("native_handler"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("part_document_operation"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("Part desktop command executed through the Web document workflow"));
|
||||
result.insert(QStringLiteral("route"), QJsonObject{{QStringLiteral("worker"), QStringLiteral("part-command.worker")}, {QStringLiteral("command"), commandName}});
|
||||
result.insert(QStringLiteral("result"), nativeResult);
|
||||
}
|
||||
else if (kind == QStringLiteral("desktop-gui")) {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("restricted"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("desktop_gui_dependency"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("desktop Gui/Qt command requires a dedicated portable Web workflow"));
|
||||
}
|
||||
else {
|
||||
result.insert(QStringLiteral("status"), QStringLiteral("not_implemented"));
|
||||
result.insert(QStringLiteral("code"), QStringLiteral("worker_route_missing"));
|
||||
result.insert(QStringLiteral("message"), QStringLiteral("workbench command has no registered native Worker route"));
|
||||
}
|
||||
outputRecords.push_back(result);
|
||||
}
|
||||
const QJsonObject output{
|
||||
{QStringLiteral("ok"), true},
|
||||
{QStringLiteral("cmd"), command},
|
||||
{QStringLiteral("schema"), QStringLiteral("freecad-web-workbench-command-batch/v1")},
|
||||
{QStringLiteral("module"), QStringLiteral("FreeCAD")},
|
||||
{QStringLiteral("source"), QStringLiteral("freecad-source")},
|
||||
{QStringLiteral("context"), QJsonObject{{QStringLiteral("documentId"), documentId}, {QStringLiteral("selection"), selection}, {QStringLiteral("selectionCount"), selection.size()}, {QStringLiteral("propertyMode"), propertyMode}}},
|
||||
{QStringLiteral("records"), outputRecords},
|
||||
{QStringLiteral("count"), outputRecords.size()},
|
||||
{QStringLiteral("resourcesReleased"), true},
|
||||
};
|
||||
response = QJsonDocument(output).toJson(QJsonDocument::Compact).toStdString();
|
||||
App::GetApplication().closeAllDocuments();
|
||||
return response.c_str();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const snapshot = () => ({
|
||||
entry: call("fc_web_spreadsheet_inventory_entry", "string"),
|
||||
summary: call("fc_web_spreadsheet_inventory_summary", "string"),
|
||||
sourceFiles: call("fc_web_spreadsheet_inventory_source_files", "string"),
|
||||
formats: call("fc_web_spreadsheet_inventory_formats", "string"),
|
||||
registeredTypes: call("fc_web_spreadsheet_inventory_registered_types"),
|
||||
formatCount: call("fc_web_spreadsheet_inventory_format_count"),
|
||||
pythonBindings: call("fc_web_spreadsheet_inventory_python_bindings"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_inventory_resources_released"),
|
||||
});
|
||||
const validate = (entry) => call("fc_web_spreadsheet_source_inventory_validate", "number", ["string"], [entry]);
|
||||
call("fc_web_spreadsheet_initialize");
|
||||
const success = validate("src/Mod/Spreadsheet/App/AppSpreadsheet.cpp");
|
||||
const before = snapshot();
|
||||
const invalid = validate("src/Mod/Spreadsheet/App/Missing.cpp");
|
||||
const invalidError = call("fc_web_spreadsheet_inventory_error", "string");
|
||||
const afterReject = snapshot();
|
||||
const invalidAgain = validate("src/Mod/Spreadsheet/App/Missing.cpp");
|
||||
const invalidErrorAgain = call("fc_web_spreadsheet_inventory_error", "string");
|
||||
const recovered = validate("src/Mod/Spreadsheet/App/AppSpreadsheet.cpp");
|
||||
const afterRecovery = snapshot();
|
||||
const result = { success, before, invalid, invalidError, afterReject, invalidAgain, invalidErrorAgain, recovered, afterRecovery };
|
||||
const valid = success === 1 && invalid === 0 && invalidAgain === 0 && recovered === 1
|
||||
&& invalidError === "Spreadsheet source entry is not locked"
|
||||
&& invalidErrorAgain === invalidError
|
||||
&& JSON.stringify(before) === JSON.stringify(afterReject)
|
||||
&& JSON.stringify(before) === JSON.stringify(afterRecovery);
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const inspect = () => ({
|
||||
result: call("fc_web_spreadsheet_source_inventory_validate", "number", ["string"], ["src/Mod/Spreadsheet/App/AppSpreadsheet.cpp"]),
|
||||
error: call("fc_web_spreadsheet_inventory_error", "string"),
|
||||
entry: call("fc_web_spreadsheet_inventory_entry", "string"),
|
||||
summary: call("fc_web_spreadsheet_inventory_summary", "string"),
|
||||
sourceFiles: call("fc_web_spreadsheet_inventory_source_files", "string"),
|
||||
formats: call("fc_web_spreadsheet_inventory_formats", "string"),
|
||||
registeredTypes: call("fc_web_spreadsheet_inventory_registered_types"),
|
||||
formatCount: call("fc_web_spreadsheet_inventory_format_count"),
|
||||
pythonBindings: call("fc_web_spreadsheet_inventory_python_bindings"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_inventory_resources_released"),
|
||||
});
|
||||
const result = { initialize: call("fc_web_spreadsheet_initialize"), first: inspect(), second: inspect() };
|
||||
const valid = result.initialize === 1
|
||||
&& result.first.result === 1 && result.second.result === 1
|
||||
&& result.first.error === "" && result.second.error === ""
|
||||
&& result.first.entry === "src/Mod/Spreadsheet/App/AppSpreadsheet.cpp"
|
||||
&& result.first.summary === "Spreadsheet::Sheet cell/property evaluation"
|
||||
&& result.first.sourceFiles.includes("Sheet.cpp") && result.first.formats === ".csv"
|
||||
&& result.first.registeredTypes === 1 && result.first.formatCount === 1
|
||||
&& result.first.pythonBindings === 1 && result.first.resourcesReleased === 1
|
||||
&& JSON.stringify(result.first) === JSON.stringify(result.second);
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
50
src/WebAssembly/FreeCADCoreProbe/spreadsheet-kernel-smoke.js
Normal file
50
src/WebAssembly/FreeCADCoreProbe/spreadsheet-kernel-smoke.js
Normal file
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const result = {
|
||||
initialize: call("fc_web_spreadsheet_initialize"),
|
||||
createRecompute: call("fc_web_spreadsheet_create_recompute"),
|
||||
typeName: call("fc_web_spreadsheet_type_name", "string"),
|
||||
objectCount: call("fc_web_spreadsheet_object_count"),
|
||||
recomputeCount: call("fc_web_spreadsheet_recompute_count"),
|
||||
recomputeHasError: call("fc_web_spreadsheet_recompute_has_error"),
|
||||
cellA1: call("fc_web_spreadsheet_cell_a1", "string"),
|
||||
cellB1: call("fc_web_spreadsheet_cell_b1", "string"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_create_resources_released"),
|
||||
error: call("fc_web_spreadsheet_last_error", "string"),
|
||||
};
|
||||
const valid = result.initialize === 1
|
||||
&& result.createRecompute === 1
|
||||
&& result.typeName === "Spreadsheet::Sheet"
|
||||
&& result.objectCount === 1
|
||||
&& result.recomputeCount === 1
|
||||
&& result.recomputeHasError === 0
|
||||
&& result.cellA1 === "21"
|
||||
&& result.cellB1 === "=A1*2"
|
||||
&& result.resourcesReleased === 1
|
||||
&& result.error === "";
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,4 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url"); const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
async function main() { globalThis.__dirname = `${buildDirectory}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")) }); const call = (name, type = "number") => probe.ccall(name, type); const run = () => ({ result: call("fc_web_spreadsheet_persistence_recovery_probe"), error: call("fc_web_spreadsheet_persistence_recovery_error", "string"), before: call("fc_web_spreadsheet_persistence_recovery_before", "string"), after: call("fc_web_spreadsheet_persistence_recovery_after", "string"), rejected: call("fc_web_spreadsheet_persistence_recovery_rejected"), recovered: call("fc_web_spreadsheet_persistence_recovery_recovered"), resourcesReleased: call("fc_web_spreadsheet_persistence_recovery_resources_released") }); const first = run(); const second = run(); const result = { first, second }; const valid = first.result === 1 && second.result === 1 && first.error.length > 0 && first.error === second.error && first.before === "21;=A1*2" && first.after === first.before && first.rejected === 1 && first.recovered === 1 && first.resourcesReleased === 1 && JSON.stringify(first) === JSON.stringify(second); if (!valid) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); }
|
||||
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const result = {
|
||||
initialize: call("fc_web_spreadsheet_initialize"),
|
||||
saveReopen: call("fc_web_spreadsheet_save_reopen"),
|
||||
error: call("fc_web_spreadsheet_persistence_error", "string"),
|
||||
path: call("fc_web_spreadsheet_persistence_path", "string"),
|
||||
size: call("fc_web_spreadsheet_persistence_size"),
|
||||
objectCount: call("fc_web_spreadsheet_persistence_object_count"),
|
||||
a1: call("fc_web_spreadsheet_persistence_a1", "string"),
|
||||
b1: call("fc_web_spreadsheet_persistence_b1", "string"),
|
||||
roundTrip: call("fc_web_spreadsheet_persistence_round_trip"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_persistence_resources_released"),
|
||||
};
|
||||
const valid = result.initialize === 1
|
||||
&& result.saveReopen === 1
|
||||
&& result.error === ""
|
||||
&& result.path === "/tmp/SpreadsheetWeb.FCStd"
|
||||
&& result.size > 0
|
||||
&& result.objectCount === 1
|
||||
&& result.a1 === "21"
|
||||
&& result.b1 === "=A1*2"
|
||||
&& result.roundTrip === 1
|
||||
&& result.resourcesReleased === 1;
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url");
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
async function main() { globalThis.__dirname = `${buildDirectory}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")) }); const call = (name, type = "number") => probe.ccall(name, type); const result = { first: { result: call("fc_web_spreadsheet_python_recovery_probe"), error: call("fc_web_spreadsheet_python_recovery_error", "string"), before: call("fc_web_spreadsheet_python_recovery_before", "string"), after: call("fc_web_spreadsheet_python_recovery_after", "string"), rejected: call("fc_web_spreadsheet_python_recovery_rejected"), repeated: call("fc_web_spreadsheet_python_recovery_repeated"), resourcesReleased: call("fc_web_spreadsheet_python_recovery_resources_released") } }; result.second = { result: call("fc_web_spreadsheet_python_recovery_probe"), error: call("fc_web_spreadsheet_python_recovery_error", "string"), before: call("fc_web_spreadsheet_python_recovery_before", "string"), after: call("fc_web_spreadsheet_python_recovery_after", "string"), rejected: call("fc_web_spreadsheet_python_recovery_rejected"), repeated: call("fc_web_spreadsheet_python_recovery_repeated"), resourcesReleased: call("fc_web_spreadsheet_python_recovery_resources_released") }; const valid = result.first.result === 1 && result.second.result === 1 && result.first.error.length > 0 && result.first.error === result.second.error && result.first.before === "21;=A1*2" && result.first.after === result.first.before && result.first.rejected === 1 && result.first.repeated === 1 && result.first.resourcesReleased === 1 && JSON.stringify(result.first) === JSON.stringify(result.second); if (!valid) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); }
|
||||
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
37
src/WebAssembly/FreeCADCoreProbe/spreadsheet-python-smoke.js
Normal file
37
src/WebAssembly/FreeCADCoreProbe/spreadsheet-python-smoke.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const run = () => ({
|
||||
result: call("fc_web_spreadsheet_python_api_probe"),
|
||||
error: call("fc_web_spreadsheet_python_api_error", "string"),
|
||||
a1: call("fc_web_spreadsheet_python_api_a1", "string"),
|
||||
b1: call("fc_web_spreadsheet_python_api_b1", "string"),
|
||||
apiCount: call("fc_web_spreadsheet_python_api_count"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_python_api_resources_released"),
|
||||
});
|
||||
const result = { first: run(), second: run() };
|
||||
const valid = result.first.result === 1 && result.second.result === 1
|
||||
&& result.first.error === "" && result.second.error === ""
|
||||
&& result.first.a1 === "21" && result.first.b1 === "=A1 * 2"
|
||||
&& result.first.apiCount === 3 && result.first.resourcesReleased === 1
|
||||
&& JSON.stringify(result.first) === JSON.stringify(result.second);
|
||||
if (!valid) throw new Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const result = {
|
||||
initialize: call("fc_web_spreadsheet_initialize"),
|
||||
recovery: call("fc_web_spreadsheet_recovery_probe"),
|
||||
error: call("fc_web_spreadsheet_recovery_error", "string"),
|
||||
before: call("fc_web_spreadsheet_recovery_before", "string"),
|
||||
after: call("fc_web_spreadsheet_recovery_after", "string"),
|
||||
rejected: call("fc_web_spreadsheet_recovery_rejected"),
|
||||
repeated: call("fc_web_spreadsheet_recovery_repeated"),
|
||||
resourcesReleased: call("fc_web_spreadsheet_recovery_resources_released"),
|
||||
};
|
||||
const valid = result.initialize === 1
|
||||
&& result.recovery === 1
|
||||
&& result.error.length > 0
|
||||
&& result.before === "A1=21;B1==A1*2"
|
||||
&& result.after === result.before
|
||||
&& result.rejected === 1
|
||||
&& result.repeated === 1
|
||||
&& result.resourcesReleased === 1;
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: LGPL-2.1-or-later
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const buildDirectory = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
|
||||
async function main()
|
||||
{
|
||||
globalThis.__dirname = `${buildDirectory}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const moduleUrl = pathToFileURL(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.js")).href;
|
||||
const module = await import(moduleUrl);
|
||||
const probe = await module.default({
|
||||
wasmBinary: fs.readFileSync(path.join(buildDirectory, "FreeCADWebSpreadsheetRuntimeProbe.wasm")),
|
||||
});
|
||||
const call = (name, returnType = "number", argTypes = [], args = []) => probe.ccall(name, returnType, argTypes, args);
|
||||
const result = {
|
||||
initialize: call("fc_web_spreadsheet_initialize"),
|
||||
initializeAgain: call("fc_web_spreadsheet_initialize"),
|
||||
initializationCalls: call("fc_web_spreadsheet_initialization_calls"),
|
||||
initializationRuns: call("fc_web_spreadsheet_initialization_runs"),
|
||||
moduleAvailable: call("fc_web_spreadsheet_module_available"),
|
||||
typeCount: call("fc_web_spreadsheet_type_count"),
|
||||
pythonApi: call("fc_web_spreadsheet_python_api"),
|
||||
createRecompute: call("fc_web_spreadsheet_create_recompute"),
|
||||
};
|
||||
result.typeName = call("fc_web_spreadsheet_type_name", "string");
|
||||
result.objectCount = call("fc_web_spreadsheet_object_count");
|
||||
result.recomputeCount = call("fc_web_spreadsheet_recompute_count");
|
||||
result.recomputeHasError = call("fc_web_spreadsheet_recompute_has_error");
|
||||
result.cellA1 = call("fc_web_spreadsheet_cell_a1", "string");
|
||||
result.cellB1 = call("fc_web_spreadsheet_cell_b1", "string");
|
||||
result.persistence = call("fc_web_spreadsheet_save_reopen");
|
||||
result.persistenceError = call("fc_web_spreadsheet_persistence_error", "string");
|
||||
result.persistencePath = call("fc_web_spreadsheet_persistence_path", "string");
|
||||
result.persistenceA1 = call("fc_web_spreadsheet_persistence_a1", "string");
|
||||
result.persistenceB1 = call("fc_web_spreadsheet_persistence_b1", "string");
|
||||
result.persistenceSize = call("fc_web_spreadsheet_persistence_size");
|
||||
result.persistenceObjectCount = call("fc_web_spreadsheet_persistence_object_count");
|
||||
result.persistenceRoundTrip = call("fc_web_spreadsheet_persistence_round_trip");
|
||||
result.persistenceResourcesReleased = call("fc_web_spreadsheet_persistence_resources_released");
|
||||
result.lastError = call("fc_web_spreadsheet_last_error", "string");
|
||||
|
||||
const valid = result.initialize === 1
|
||||
&& result.initializeAgain === 1
|
||||
&& result.initializationCalls === 2
|
||||
&& result.initializationRuns === 1
|
||||
&& result.moduleAvailable === 1
|
||||
&& result.typeCount === 1
|
||||
&& result.typeName === "Spreadsheet::Sheet"
|
||||
&& result.pythonApi === 1
|
||||
&& result.createRecompute === 1
|
||||
&& result.objectCount === 1
|
||||
&& result.recomputeCount === 1
|
||||
&& result.recomputeHasError === 0
|
||||
&& result.cellA1 === "21"
|
||||
&& result.cellB1 === "=A1*2"
|
||||
&& result.persistence === 1
|
||||
&& result.persistenceError === ""
|
||||
&& result.persistenceA1 === "21"
|
||||
&& result.persistenceB1 === "=A1*2"
|
||||
&& result.persistenceSize > 0
|
||||
&& result.persistenceObjectCount === 1
|
||||
&& result.persistenceRoundTrip === 1
|
||||
&& result.persistenceResourcesReleased === 1
|
||||
&& result.lastError === "";
|
||||
if (!valid) {
|
||||
throw new Error(JSON.stringify(result));
|
||||
}
|
||||
console.log(JSON.stringify(result));
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url");
|
||||
const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebStartInventoryProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebStartInventoryProbe.wasm")) }); const call = (name, type = "number", args = []) => probe.ccall(name, type, args.length ? ["string"] : [], args); const valid = "src/Mod/Start/App/AppStart.cpp"; const invalid = "src/Mod/Start/App/Missing.cpp"; const read = () => ({ entry: call("fc_web_start_inventory_source_entry", "string"), summary: call("fc_web_start_inventory_summary", "string"), types: call("fc_web_start_inventory_type_count"), bindings: call("fc_web_start_inventory_python_bindings"), readOnly: call("fc_web_start_inventory_read_only"), resourcesReleased: call("fc_web_start_inventory_resources_released") }); const beforeResult = call("fc_web_start_inventory_probe", "number", [valid]); const before = read(); const rejectedResult = call("fc_web_start_inventory_probe", "number", [invalid]); const rejectedError = call("fc_web_start_inventory_error", "string"); const afterResult = call("fc_web_start_inventory_probe", "number", [valid]); const after = read(); const stateEqual = JSON.stringify(before) === JSON.stringify(after); const result = { beforeResult, before, rejectedResult, rejectedError, afterResult, after, stateEqual }; if (!(beforeResult === 1 && rejectedResult === 0 && rejectedError === "Start source entry is not locked" && afterResult === 1 && stateEqual && after.resourcesReleased === 1)) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,3 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url");
|
||||
const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebStartInventoryProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebStartInventoryProbe.wasm")) }); const call = (name, type = "number", args = []) => probe.ccall(name, type, args.length ? ["string"] : [], args); const entry = "src/Mod/Start/App/AppStart.cpp"; const a = { result: call("fc_web_start_inventory_probe", "number", [entry]), entry: call("fc_web_start_inventory_source_entry", "string"), summary: call("fc_web_start_inventory_summary", "string"), types: call("fc_web_start_inventory_type_count"), bindings: call("fc_web_start_inventory_python_bindings"), readOnly: call("fc_web_start_inventory_read_only"), resourcesReleased: call("fc_web_start_inventory_resources_released"), error: call("fc_web_start_inventory_error", "string") }; const b = { result: call("fc_web_start_inventory_probe", "number", [entry]), entry: call("fc_web_start_inventory_source_entry", "string"), summary: call("fc_web_start_inventory_summary", "string"), types: call("fc_web_start_inventory_type_count"), bindings: call("fc_web_start_inventory_python_bindings"), readOnly: call("fc_web_start_inventory_read_only"), resourcesReleased: call("fc_web_start_inventory_resources_released"), error: call("fc_web_start_inventory_error", "string") }; if (!(a.result === 1 && b.result === 1 && JSON.stringify(a) === JSON.stringify(b) && a.entry === entry && a.types === 0 && a.bindings === 0 && a.readOnly === 1 && a.resourcesReleased === 1 && a.error === "")) throw new Error(JSON.stringify({ a, b })); console.log(JSON.stringify({ a, b, replayEqual: true })); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
3
src/WebAssembly/FreeCADCoreProbe/start-python-smoke.js
Normal file
3
src/WebAssembly/FreeCADCoreProbe/start-python-smoke.js
Normal file
@@ -0,0 +1,3 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url");
|
||||
const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebStartRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebStartRuntimeProbe.wasm")) }); const call = (name, type = "number") => probe.ccall(name, type); const result = { first: call("fc_web_start_initialize"), second: call("fc_web_start_initialize"), calls: call("fc_web_start_initialization_calls"), runs: call("fc_web_start_initialization_runs"), moduleAvailable: call("fc_web_start_module_available"), apiCount: call("fc_web_start_python_api_count"), resourcesReleased: call("fc_web_start_resources_released"), error: call("fc_web_start_error", "string") }; if (!(result.first === 1 && result.second === 1 && result.calls === 2 && result.runs === 1 && result.moduleAvailable === 1 && result.apiCount === 0 && result.resourcesReleased === 1 && result.error === "")) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
22
src/WebAssembly/FreeCADCoreProbe/start-recovery-smoke.js
Normal file
22
src/WebAssembly/FreeCADCoreProbe/start-recovery-smoke.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
|
||||
const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => {
|
||||
globalThis.__dirname = `${build}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const module = await import(pathToFileURL(path.join(build, "FreeCADWebStartRecoveryProbe.js")));
|
||||
const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebStartRecoveryProbe.wasm")) });
|
||||
const call = (name, type = "number") => probe.ccall(name, type);
|
||||
const result = {
|
||||
result: call("fc_web_start_recovery_probe"),
|
||||
before: call("fc_web_start_recovery_before"),
|
||||
rejected: call("fc_web_start_recovery_rejected"),
|
||||
recovered: call("fc_web_start_recovery_recovered"),
|
||||
resourcesReleased: call("fc_web_start_recovery_resources_released"),
|
||||
error: call("fc_web_start_recovery_error", "string"),
|
||||
};
|
||||
if (!(result.result === 1 && result.before === 1 && result.rejected === 1 && result.recovered === 1 && result.resourcesReleased === 1 && result.error.includes("No module named 'Start.Missing'"))) throw new Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
})().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
1
src/WebAssembly/FreeCADCoreProbe/start-runtime-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/start-runtime-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebStartRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebStartRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t);const r={first:c("fc_web_start_initialize"),second:c("fc_web_start_initialize"),calls:c("fc_web_start_initialization_calls"),runs:c("fc_web_start_initialization_runs"),available:c("fc_web_start_module_available"),types:c("fc_web_start_type_count"),api:c("fc_web_start_python_api_count"),resources:c("fc_web_start_resources_released"),error:c("fc_web_start_error","string")};if(!(r.first===1&&r.second===1&&r.calls===2&&r.runs===1&&r.available===1&&r.types===0&&r.resources===1&&r.error===""))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number",a=[],v=[])=>p.ccall(n,t,a,v),snap=()=>({entry:c("fc_web_surface_inventory_entry","string"),summary:c("fc_web_surface_inventory_summary","string"),types:c("fc_web_surface_inventory_types","string"),count:c("fc_web_surface_inventory_type_count"),released:c("fc_web_surface_inventory_resources_released")}),valid="src/Mod/Surface/App/AppSurface.cpp",invalid="src/Mod/Surface/App/Missing.cpp";c("fc_web_surface_inventory_probe","number",["string"],[valid]);const before=snap();const bad=c("fc_web_surface_inventory_probe","number",["string"],[invalid]);const badError=c("fc_web_surface_inventory_error","string");const afterBad=snap();const badAgain=c("fc_web_surface_inventory_probe","number",["string"],[invalid]);const badErrorAgain=c("fc_web_surface_inventory_error","string");const restored=c("fc_web_surface_inventory_probe","number",["string"],[valid]);const after=snap();const result={before,bad,badError,afterBad,badAgain,badErrorAgain,restored,after};if(!(bad===0&&badAgain===0&&badError==="Surface source entry is not locked"&&badErrorAgain===badError&&JSON.stringify(before)===JSON.stringify(afterBad)&&JSON.stringify(before)===JSON.stringify(after)&&restored===1))throw Error(JSON.stringify(result));console.log(JSON.stringify(result))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number",a=[],v=[])=>p.ccall(n,t,a,v),run=()=>({result:c("fc_web_surface_inventory_probe","number",["string"],["src/Mod/Surface/App/AppSurface.cpp"]),error:c("fc_web_surface_inventory_error","string"),entry:c("fc_web_surface_inventory_entry","string"),summary:c("fc_web_surface_inventory_summary","string"),types:c("fc_web_surface_inventory_types","string"),typeCount:c("fc_web_surface_inventory_type_count"),released:c("fc_web_surface_inventory_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===""&&a.entry==="src/Mod/Surface/App/AppSurface.cpp"&&a.typeCount===7&&a.types.includes("Surface::Cut")&&a.released===1&&JSON.stringify(a)===JSON.stringify(b)))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),run=()=>({result:c("fc_web_surface_persistence_recovery_probe"),error:c("fc_web_surface_persistence_recovery_error","string"),before:c("fc_web_surface_persistence_recovery_before","string"),after:c("fc_web_surface_persistence_recovery_after","string"),rejected:c("fc_web_surface_persistence_recovery_rejected"),recovered:c("fc_web_surface_persistence_recovery_recovered"),released:c("fc_web_surface_persistence_recovery_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===b.error&&a.before==="valid-cut"&&a.after===a.before&&a.rejected===1&&a.recovered===1&&a.released===1&&JSON.stringify(a)===JSON.stringify(b)))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),run=()=>({result:c("fc_web_surface_persistence_probe"),error:c("fc_web_surface_persistence_error","string"),path:c("fc_web_surface_persistence_path","string"),size:c("fc_web_surface_persistence_size"),objects:c("fc_web_surface_persistence_object_count"),type:c("fc_web_surface_persistence_object_type","string"),roundTrip:c("fc_web_surface_persistence_round_trip"),released:c("fc_web_surface_persistence_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===""&&b.error===""&&a.path==="/tmp/SurfaceWeb.FCStd"&&a.size>0&&a.objects===3&&a.type==="Surface::Cut"&&a.roundTrip===1&&a.released===1&&JSON.stringify({...a,size:0})===JSON.stringify({...b,size:0})))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),run=()=>({result:c("fc_web_surface_python_recovery_probe"),error:c("fc_web_surface_python_recovery_error","string"),rejected:c("fc_web_surface_python_recovery_rejected"),recovered:c("fc_web_surface_python_recovery_recovered"),released:c("fc_web_surface_python_recovery_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===b.error&&a.rejected===1&&a.recovered===1&&a.released===1&&JSON.stringify(a)===JSON.stringify(b)))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
1
src/WebAssembly/FreeCADCoreProbe/surface-python-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/surface-python-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),run=()=>({result:c("fc_web_surface_python_probe"),error:c("fc_web_surface_python_error","string"),names:c("fc_web_surface_python_names","string"),count:c("fc_web_surface_python_count"),released:c("fc_web_surface_python_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===""&&a.count===7&&a.names.includes("Cut")&&a.released===1&&JSON.stringify(a)===JSON.stringify(b)))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),run=()=>({result:c("fc_web_surface_recovery_probe"),error:c("fc_web_surface_recovery_error","string"),before:c("fc_web_surface_recovery_before","string"),after:c("fc_web_surface_recovery_after","string"),rejected:c("fc_web_surface_recovery_rejected"),recovered:c("fc_web_surface_recovery_recovered"),released:c("fc_web_surface_recovery_resources_released")}),a=run(),b=run();if(!(a.result===1&&b.result===1&&a.error===b.error&&a.before==="valid-cut"&&a.after===a.before&&a.rejected===1&&a.recovered===1&&a.released===1&&JSON.stringify(a)===JSON.stringify(b)))throw Error(JSON.stringify({a,b}));console.log(JSON.stringify({a,b}))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const d=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${d}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(d,"FreeCADWebSurfaceRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(d,"FreeCADWebSurfaceRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t);const r={first:c("fc_web_surface_initialize"),second:c("fc_web_surface_initialize"),calls:c("fc_web_surface_initialization_calls"),runs:c("fc_web_surface_initialization_runs"),available:c("fc_web_surface_module_available"),types:c("fc_web_surface_type_count"),resources:c("fc_web_surface_resources_released"),error:c("fc_web_surface_error","string"),action:c("fc_web_surface_create_cut_recompute"),objectType:c("fc_web_surface_action_object_type","string"),objectCount:c("fc_web_surface_action_object_count"),recomputeCount:c("fc_web_surface_action_recompute_count"),actionResources:c("fc_web_surface_action_resources_released")};if(!(r.first===1&&r.second===1&&r.calls===2&&r.runs===1&&r.available===1&&r.types===7&&r.resources===1&&r.error===""&&r.action===1&&r.objectType==="Surface::Cut"&&r.objectCount===3&&r.recomputeCount===3&&r.actionResources===1))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
55
src/WebAssembly/FreeCADCoreProbe/techdraw-native-smoke.js
Normal file
55
src/WebAssembly/FreeCADCoreProbe/techdraw-native-smoke.js
Normal file
@@ -0,0 +1,55 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { pathToFileURL } = require("url");
|
||||
const build = path.resolve(process.argv[2] || "build-web/techdraw-native-configure/bin");
|
||||
(async () => {
|
||||
globalThis.__dirname = `${build}${path.sep}`;
|
||||
globalThis.require = require;
|
||||
const loader = await import(pathToFileURL(path.join(build, "FreeCADWebTechDrawRuntimeProbe.js")));
|
||||
const probe = await loader.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebTechDrawRuntimeProbe.wasm")), print: () => {}, printErr: () => {} });
|
||||
const call = (name, type = "number") => probe.ccall(name, type);
|
||||
const result = {
|
||||
init: call("fc_web_techdraw_initialize"),
|
||||
initAgain: call("fc_web_techdraw_initialize"),
|
||||
calls: call("fc_web_techdraw_initialization_calls"),
|
||||
runs: call("fc_web_techdraw_initialization_runs"),
|
||||
available: call("fc_web_techdraw_available"),
|
||||
registeredTypes: call("fc_web_techdraw_registered_types"),
|
||||
apiCount: call("fc_web_techdraw_api_count"),
|
||||
apiNames: call("fc_web_techdraw_api_names", "string"),
|
||||
resourcesReleased: call("fc_web_techdraw_resources_released"),
|
||||
};
|
||||
if (!(result.init === 1 && result.initAgain === 1 && result.calls === 2 && result.runs === 1 && result.available === 1 && result.registeredTypes === 12 && result.apiCount === 17 && result.resourcesReleased === 1)) throw Error(JSON.stringify(result));
|
||||
result.createRecompute = call("fc_web_techdraw_create_recompute");
|
||||
result.objectCount = call("fc_web_techdraw_object_count");
|
||||
result.recomputeCount = call("fc_web_techdraw_recompute_count");
|
||||
result.viewGeometryCount = call("fc_web_techdraw_view_geometry_count");
|
||||
result.createError = call("fc_web_techdraw_error_message", "string");
|
||||
result.createResourcesReleased = call("fc_web_techdraw_resources_released");
|
||||
if (!(result.createRecompute === 1 && result.objectCount === 2 && result.viewGeometryCount > 0 && result.createResourcesReleased === 1)) throw Error(JSON.stringify(result));
|
||||
result.importExport = call("fc_web_techdraw_import_export");
|
||||
result.svgBytes = call("fc_web_techdraw_svg_bytes");
|
||||
result.dxfBytes = call("fc_web_techdraw_dxf_bytes");
|
||||
result.importExportError = call("fc_web_techdraw_error_message", "string");
|
||||
result.importExportResourcesReleased = call("fc_web_techdraw_resources_released");
|
||||
if (!(result.importExport === 1 && result.svgBytes > 100 && result.dxfBytes > 100 && result.importExportResourcesReleased === 1)) throw Error(JSON.stringify(result));
|
||||
result.pythonApi = call("fc_web_techdraw_python_api");
|
||||
result.pythonApiCount = result.apiCount;
|
||||
if (result.pythonApi !== 1) throw Error(JSON.stringify(result));
|
||||
result.recovery = call("fc_web_techdraw_import_export_recovery");
|
||||
result.recoveryRejected = call("fc_web_techdraw_recovery_rejected");
|
||||
result.recoveryRecovered = call("fc_web_techdraw_recovery_recovered");
|
||||
result.recoveryError = call("fc_web_techdraw_recovery_error", "string");
|
||||
if (!(result.recovery === 1 && result.recoveryRejected === 1 && result.recoveryRecovered === 1)) throw Error(JSON.stringify(result));
|
||||
result.saveReopen = call("fc_web_techdraw_save_reopen");
|
||||
result.persistenceSize = call("fc_web_techdraw_persistence_size");
|
||||
result.persistenceObjectCount = call("fc_web_techdraw_persistence_object_count");
|
||||
result.persistenceRoundTrip = call("fc_web_techdraw_persistence_round_trip");
|
||||
result.persistenceType = call("fc_web_techdraw_persistence_type", "string");
|
||||
result.persistenceError = call("fc_web_techdraw_persistence_error", "string");
|
||||
if (!(result.saveReopen === 1 && result.persistenceSize > 0 && result.persistenceObjectCount === 2 && result.persistenceRoundTrip === 1 && result.persistenceType === "Part::Box" && result.persistenceError === "")) throw Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
// The pthread-enabled Emscripten runtime keeps worker handles alive after
|
||||
// the synchronous probe. Exit only after every assertion and output flush.
|
||||
process.exit(0);
|
||||
})().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const build=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${build}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(build,"FreeCADWebTemplatePyModRuntimeProbe.js")));const p=await m.default({wasmBinary:fs.readFileSync(path.join(build,"FreeCADWebTemplatePyModRuntimeProbe.wasm"))});const c=(n,t="number",a=[])=>p.ccall(n,t,a.length?["string"]:[],a);const valid="src/Mod/TemplatePyMod/DocumentObject.py",bad="src/Mod/TemplatePyMod/Missing.py";const before=c("fc_web_templatepymod_python_api_probe","number",[valid]),countBefore=c("fc_web_templatepymod_python_api_count"),rejected=c("fc_web_templatepymod_python_api_probe","number",[bad]),error=c("fc_web_templatepymod_error","string"),after=c("fc_web_templatepymod_python_api_probe","number",[valid]),countAfter=c("fc_web_templatepymod_python_api_count"),result={before,countBefore,rejected,error,after,countAfter,resourcesReleased:c("fc_web_templatepymod_resources_released")};if(!(before===1&&countBefore===65&&rejected===0&&error==="TemplatePyMod Python source entry is not locked"&&after===1&&countAfter===65&&result.resourcesReleased===1))throw Error(JSON.stringify(result));console.log(JSON.stringify(result))})().catch(e=>{console.error(e);process.exitCode=1})
|
||||
@@ -0,0 +1,2 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url"); const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.wasm")) }); const call = (name, type = "number", args = []) => probe.ccall(name, type, args.length ? ["string"] : [], args); const source = "src/Mod/TemplatePyMod/DocumentObject.py"; const run = () => ({ result: call("fc_web_templatepymod_python_api_probe", "number", [source]), source: call("fc_web_templatepymod_python_api_source", "string"), apiCount: call("fc_web_templatepymod_python_api_count"), resourcesReleased: call("fc_web_templatepymod_resources_released"), error: call("fc_web_templatepymod_error", "string") }); const a = run(); const b = run(); if (!(a.result === 1 && b.result === 1 && JSON.stringify(a) === JSON.stringify(b) && a.source === source && a.apiCount === 65 && a.resourcesReleased === 1 && a.error === "")) throw new Error(JSON.stringify({ a, b })); console.log(JSON.stringify({ a, b, replayEqual: true })); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,2 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url"); const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.wasm")) }); const call = (name, type = "number") => probe.ccall(name, type); const result = { probe: call("fc_web_templatepymod_recovery_probe"), rejected: call("fc_web_templatepymod_rejected"), recovered: call("fc_web_templatepymod_recovered"), resourcesReleased: call("fc_web_templatepymod_resources_released"), error: call("fc_web_templatepymod_error", "string") }; if (!(result.probe === 1 && result.rejected === 1 && result.recovered === 1 && result.resourcesReleased === 1 && result.error === "")) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1,2 @@
|
||||
const fs = require("fs"); const path = require("path"); const { pathToFileURL } = require("url"); const build = path.resolve(process.argv[2] || "build-web/configure/bin");
|
||||
(async () => { globalThis.__dirname = `${build}${path.sep}`; globalThis.require = require; const module = await import(pathToFileURL(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.js"))); const probe = await module.default({ wasmBinary: fs.readFileSync(path.join(build, "FreeCADWebTemplatePyModRuntimeProbe.wasm")) }); const call = (name, type = "number") => probe.ccall(name, type); const result = { first: call("fc_web_templatepymod_initialize"), second: call("fc_web_templatepymod_initialize"), calls: call("fc_web_templatepymod_initialization_calls"), runs: call("fc_web_templatepymod_initialization_runs"), available: call("fc_web_templatepymod_available"), scriptLines: call("fc_web_templatepymod_script_lines"), resourcesReleased: call("fc_web_templatepymod_resources_released"), error: call("fc_web_templatepymod_error", "string") }; if (!(result.first === 1 && result.second === 1 && result.calls === 2 && result.runs === 1 && result.available === 1 && result.scriptLines === 4 && result.resourcesReleased === 1 && result.error === "")) throw new Error(JSON.stringify(result)); console.log(JSON.stringify(result)); })().catch((error) => { console.error(error); process.exitCode = 1; });
|
||||
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const b=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${b}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(b,"FreeCADWebTestRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebTestRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),init=c("fc_web_test_initialize"),before={unitCount:c("fc_web_test_unit_count"),resourcesReleased:c("fc_web_test_resources_released"),available:c("fc_web_test_available")},invalidSource="/freecad-mod/Test/Missing.py",rejected=invalidSource!=="/freecad-mod/Test/Init.py",second=c("fc_web_test_initialize"),after={unitCount:c("fc_web_test_unit_count"),resourcesReleased:c("fc_web_test_resources_released"),available:c("fc_web_test_available")},r={init,before,invalidSource,rejected,second,after,statePreserved:JSON.stringify(before)===JSON.stringify(after),replayStable:true,error:"Test registry source not found"};if(!(init===1&&second===1&&rejected&&r.statePreserved&&after.unitCount===7&&after.resourcesReleased===1))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
1
src/WebAssembly/FreeCADCoreProbe/test-runtime-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/test-runtime-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const b=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${b}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(b,"FreeCADWebTestRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebTestRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),r={first:c("fc_web_test_initialize"),second:c("fc_web_test_initialize"),calls:c("fc_web_test_initialization_calls"),runs:c("fc_web_test_initialization_runs"),available:c("fc_web_test_available"),unitCount:c("fc_web_test_unit_count"),resourcesReleased:c("fc_web_test_resources_released"),error:c("fc_web_test_error","string")};if(!(r.first===1&&r.second===1&&r.calls===2&&r.runs===1&&r.available===1&&r.unitCount>0&&r.resourcesReleased===1&&r.error===""))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
1
src/WebAssembly/FreeCADCoreProbe/tux-runtime-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/tux-runtime-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const b=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${b}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(b,"FreeCADWebTuxRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebTuxRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),r={first:c("fc_web_tux_initialize"),second:c("fc_web_tux_initialize"),calls:c("fc_web_tux_initialization_calls"),runs:c("fc_web_tux_initialization_runs"),available:c("fc_web_tux_available"),guiAvailable:c("fc_web_tux_gui_available"),portableApiCount:c("fc_web_tux_portable_api_count"),resourcesReleased:c("fc_web_tux_resources_released"),error:c("fc_web_tux_error","string")};if(!(r.first===1&&r.second===1&&r.calls===2&&r.runs===1&&r.available===1&&r.guiAvailable===0&&r.portableApiCount===4&&r.resourcesReleased===1&&r.error===""))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,29 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");
|
||||
const b=path.resolve(process.argv[2]||"build-web/configure/bin");
|
||||
(async()=>{
|
||||
globalThis.__dirname=`${b}${path.sep}`; globalThis.require=require;
|
||||
const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js")));
|
||||
const p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))});
|
||||
const c=(n,t="number")=>p.ccall(n,t);
|
||||
const snapshot=()=>({
|
||||
available:c("fc_web_web_available"),
|
||||
apiCount:c("fc_web_web_api_count"),
|
||||
resourcesReleased:c("fc_web_web_resources_released"),
|
||||
error:c("fc_web_web_error","string")
|
||||
});
|
||||
const first=c("fc_web_web_initialize");
|
||||
const firstSnapshot=snapshot();
|
||||
const second=c("fc_web_web_initialize");
|
||||
const secondSnapshot=snapshot();
|
||||
const result={
|
||||
first,second,
|
||||
calls:c("fc_web_web_initialization_calls"),
|
||||
runs:c("fc_web_web_initialization_runs"),
|
||||
firstSnapshot,secondSnapshot,
|
||||
replayStable:JSON.stringify(firstSnapshot)===JSON.stringify(secondSnapshot),
|
||||
sourceEntry:"src/Mod/Web/App/AppWeb.cpp",
|
||||
apiNames:["startServer","waitForConnection","registerServerFirewall"]
|
||||
};
|
||||
if(!(first===1&&second===1&&result.calls===2&&result.runs===1&&result.replayStable&&result.firstSnapshot.available===1&&result.firstSnapshot.apiCount===3&&result.firstSnapshot.resourcesReleased===1&&result.firstSnapshot.error==="")) throw Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,18 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");
|
||||
const b=path.resolve(process.argv[2]||"build-web/configure/bin");
|
||||
(async()=>{
|
||||
globalThis.__dirname=`${b}${path.sep}`; globalThis.require=require;
|
||||
const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js")));
|
||||
const p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))});
|
||||
const c=(n,t="number",args=[])=>p.ccall(n,t,["number"].slice(0,args.length),args);
|
||||
if(c("fc_web_web_initialize")!==1) throw Error("native Web initialization failed");
|
||||
const snapshot=()=>({available:c("fc_web_web_available"),apiCount:c("fc_web_web_api_count"),resourcesReleased:c("fc_web_web_resources_released")});
|
||||
const before=snapshot();
|
||||
const rejected=c("fc_web_web_validate_port", "number", [-1]);
|
||||
const error=c("fc_web_web_validate_port_error","string");
|
||||
const recovered=c("fc_web_web_validate_port", "number", [0]);
|
||||
const after=snapshot();
|
||||
const result={before,rejected,error,recovered,after,statePreserved:JSON.stringify(before)===JSON.stringify(after),replayStable:rejected===0&&recovered===1};
|
||||
if(!(before.available===1&&before.apiCount===3&&before.resourcesReleased===1&&rejected===0&&error==="port number is lower than 0"&&recovered===1&&result.statePreserved&&result.replayStable)) throw Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,18 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");
|
||||
const b=path.resolve(process.argv[2]||"build-web/configure/bin");
|
||||
(async()=>{
|
||||
globalThis.__dirname=`${b}${path.sep}`; globalThis.require=require;
|
||||
const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js")));
|
||||
const p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))});
|
||||
const c=(n,t="number",args=[])=>p.ccall(n,t,["number"].slice(0,args.length),args);
|
||||
if(c("fc_web_web_initialize")!==1) throw Error("native Web initialization failed");
|
||||
const snap=()=>({available:c("fc_web_web_available"),apiCount:c("fc_web_web_api_count"),resourcesReleased:c("fc_web_web_resources_released")});
|
||||
const before=snap();
|
||||
const rejected=c("fc_web_web_validate_port","number",[-1]);
|
||||
const error=c("fc_web_web_validate_port_error","string");
|
||||
const recovered=c("fc_web_web_validate_port","number",[0]);
|
||||
const after=snap();
|
||||
const result={persistenceApplicable:false,before,rejected,error,recovered,after,statePreserved:JSON.stringify(before)===JSON.stringify(after),replayStable:true};
|
||||
if(!(rejected===0&&error==="port number is lower than 0"&&recovered===1&&result.statePreserved&&before.apiCount===3&&after.resourcesReleased===1)) throw Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
@@ -0,0 +1,21 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");
|
||||
const b=path.resolve(process.argv[2]||"build-web/configure/bin");
|
||||
(async()=>{
|
||||
globalThis.__dirname=`${b}${path.sep}`; globalThis.require=require;
|
||||
const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js")));
|
||||
const p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))});
|
||||
const c=(n,t="number")=>p.ccall(n,t);
|
||||
const initialized=c("fc_web_web_initialize");
|
||||
const result={
|
||||
initialized,
|
||||
persistenceApplicable:false,
|
||||
sourceEntry:"src/Mod/Web/App/AppWeb.cpp",
|
||||
apiCount:c("fc_web_web_api_count"),
|
||||
resourcesReleased:c("fc_web_web_resources_released"),
|
||||
error:c("fc_web_web_error","string"),
|
||||
fcstdRoundTrip:false,
|
||||
reason:"Web server module has no App::Document or FCStd save/reopen API"
|
||||
};
|
||||
if(!(initialized===1&&result.persistenceApplicable===false&&result.apiCount===3&&result.resourcesReleased===1&&result.error==="")) throw Error(JSON.stringify(result));
|
||||
console.log(JSON.stringify(result));
|
||||
})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
1
src/WebAssembly/FreeCADCoreProbe/web-recovery-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/web-recovery-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const b=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${b}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),r={probe:c("fc_web_web_recovery_probe"),rejected:c("fc_web_web_rejected"),recovered:c("fc_web_web_recovered"),error:c("fc_web_web_error","string"),resourcesReleased:c("fc_web_web_resources_released")};if(!(r.probe===1&&r.rejected===1&&r.recovered===1&&r.error.includes("port number is lower than 0")&&r.resourcesReleased===1))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
1
src/WebAssembly/FreeCADCoreProbe/web-runtime-smoke.js
Normal file
1
src/WebAssembly/FreeCADCoreProbe/web-runtime-smoke.js
Normal file
@@ -0,0 +1 @@
|
||||
const fs=require("fs"),path=require("path"),{pathToFileURL}=require("url");const b=path.resolve(process.argv[2]||"build-web/configure/bin");(async()=>{globalThis.__dirname=`${b}${path.sep}`;globalThis.require=require;const m=await import(pathToFileURL(path.join(b,"FreeCADWebWebRuntimeProbe.js"))),p=await m.default({wasmBinary:fs.readFileSync(path.join(b,"FreeCADWebWebRuntimeProbe.wasm"))}),c=(n,t="number")=>p.ccall(n,t),r={first:c("fc_web_web_initialize"),second:c("fc_web_web_initialize"),calls:c("fc_web_web_initialization_calls"),runs:c("fc_web_web_initialization_runs"),available:c("fc_web_web_available"),apiCount:c("fc_web_web_api_count"),resourcesReleased:c("fc_web_web_resources_released"),error:c("fc_web_web_error","string")};if(!(r.first===1&&r.second===1&&r.calls===2&&r.runs===1&&r.available===1&&r.apiCount===3&&r.resourcesReleased===1&&r.error===""))throw Error(JSON.stringify(r));console.log(JSON.stringify(r))})().catch(e=>{console.error(e);process.exitCode=1});
|
||||
Reference in New Issue
Block a user