use std::path::PathBuf;
use std::sync::OnceLock;
use pyo3::prelude::*;
use pyo3::types::PyAnyMethods;
use serde::Deserialize;
static ENTRY_MODULE: OnceLock<String> = OnceLock::new();
static APP_PATHS: OnceLock<Vec<PathBuf>> = OnceLock::new();
static MODS_PATHS: OnceLock<Vec<PathBuf>> = OnceLock::new();
pub fn configure(entry_module: &str, python_paths: &[PathBuf], mods_paths: &[PathBuf]) {
let _ = ENTRY_MODULE.set(entry_module.to_string());
let _ = APP_PATHS.set(python_paths.to_vec());
let _ = MODS_PATHS.set(mods_paths.to_vec());
}
fn entry_module() -> &'static str {
ENTRY_MODULE.get().map(String::as_str).unwrap_or("ferrocad_shell")
}
#[derive(Debug, Clone, Deserialize)]
pub struct Bootstrap {
pub version: String,
pub backend: String,
pub document: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct WorkbenchReport {
#[serde(default)]
pub loaded: Vec<String>,
#[serde(default)]
pub errors: Vec<WorkbenchError>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct WorkbenchError {
pub workbench: String,
pub script: String,
#[serde(default)]
pub traceback: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct DocumentNode {
pub name: String,
pub label: String,
pub objects: Vec<ObjectNode>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ObjectNode {
pub name: String,
pub label: String,
#[serde(rename = "type")]
pub type_id: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct PropRow {
pub name: String,
#[serde(rename = "type")]
pub type_id: String,
pub value: String,
pub status: String,
#[serde(default)]
pub editable: bool,
#[serde(default)]
#[allow(dead_code)]
pub kind: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct SetResult {
pub ok: bool,
#[serde(default)]
pub error: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct EvalResult {
pub ok: bool,
pub output: String,
}
pub fn find_python_dir() -> Result<PathBuf, String> {
if let Ok(path) = std::env::var("FERROCAD_PYTHON_PATH") {
return Ok(PathBuf::from(path));
}
if let Some(paths) = APP_PATHS.get() {
if let Some(found) = paths.iter().find(|p| is_facade(p)) {
return Ok(found.clone());
}
}
if let Ok(exe) = std::env::current_exe() {
if let Some(dir) = exe.parent() {
for candidate in [dir.join("python"), dir.join("..").join("python")] {
if is_facade(&candidate) {
return Ok(candidate);
}
}
}
}
let mut dir = std::env::current_dir().map_err(|e| e.to_string())?;
loop {
let candidate = dir.join("python");
if is_facade(&candidate) {
return Ok(candidate);
}
if !dir.pop() {
break;
}
}
Err("could not locate the python/ facade directory (set FERROCAD_PYTHON_PATH)".to_string())
}
fn is_facade(dir: &std::path::Path) -> bool {
dir.join("FreeCAD").join("__init__.py").is_file()
}
fn call_json<T: for<'de> Deserialize<'de>>(func: &str, arg: Option<&str>) -> Result<T, String> {
let raw = Python::with_gil(|py| -> Result<String, String> {
let module = py.import(entry_module()).map_err(|e| e.to_string())?;
let f = module.getattr(func).map_err(|e| e.to_string())?;
let value = match arg {
Some(a) => f.call1((a,)),
None => f.call0(),
}
.map_err(|e| e.to_string())?;
value.extract::<String>().map_err(|e| e.to_string())
})?;
serde_json::from_str(&raw).map_err(|e| e.to_string())
}
pub fn bootstrap() -> Result<Bootstrap, String> {
let dir = find_python_dir()?;
let dir = dir.to_string_lossy().into_owned();
let app: Vec<String> = APP_PATHS
.get()
.map(|paths| {
paths
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect()
})
.unwrap_or_default();
let raw = Python::with_gil(|py| -> Result<String, String> {
let sys = py.import("sys").map_err(|e| e.to_string())?;
let path = sys.getattr("path").map_err(|e| e.to_string())?;
for p in app.iter().rev() {
path.call_method1("insert", (0, p.as_str()))
.map_err(|e| e.to_string())?;
}
path.call_method1("insert", (0, dir.as_str())).map_err(|e| e.to_string())?;
let module = py.import(entry_module()).map_err(|e| e.to_string())?;
module
.getattr("bootstrap")
.map_err(|e| e.to_string())?
.call0()
.map_err(|e| e.to_string())?
.extract::<String>()
.map_err(|e| e.to_string())
})?;
serde_json::from_str(&raw).map_err(|e| e.to_string())
}
fn mods_dirs() -> Vec<PathBuf> {
if let Some(paths) = MODS_PATHS.get() {
if !paths.is_empty() {
return paths.clone();
}
}
if let Ok(value) = std::env::var("FERROCAD_MODS_PATH") {
let paths: Vec<PathBuf> = std::env::split_paths(&value).collect();
if !paths.is_empty() {
return paths;
}
}
if let Ok(python_dir) = find_python_dir() {
if let Some(parent) = python_dir.parent() {
let mods = parent.join("mods");
if mods.is_dir() {
return vec![mods];
}
}
}
Vec::new()
}
pub fn load_workbenches() -> Result<WorkbenchReport, String> {
let dirs: Vec<String> = mods_dirs()
.iter()
.map(|p| p.to_string_lossy().into_owned())
.collect();
let arg = serde_json::to_string(&dirs).map_err(|e| e.to_string())?;
call_json("load_workbenches", Some(&arg))
}
pub fn hello() -> Result<String, String> {
Python::with_gil(|py| {
let module = py.import(entry_module()).map_err(|e| e.to_string())?;
module
.getattr("hello")
.map_err(|e| e.to_string())?
.call0()
.map_err(|e| e.to_string())?
.extract::<String>()
.map_err(|e| e.to_string())
})
}
pub fn model_tree() -> Result<Vec<DocumentNode>, String> {
call_json("model_tree", None)
}
pub fn properties(object: &str) -> Result<Vec<PropRow>, String> {
call_json("properties", Some(object))
}
pub fn evaluate(code: &str) -> Result<EvalResult, String> {
call_json("evaluate", Some(code))
}
pub fn set_property(object: &str, property: &str, value: &str) -> Result<SetResult, String> {
let raw = Python::with_gil(|py| -> Result<String, String> {
let module = py.import(entry_module()).map_err(|e| e.to_string())?;
module
.getattr("set_property")
.map_err(|e| e.to_string())?
.call1((object, property, value))
.map_err(|e| e.to_string())?
.extract::<String>()
.map_err(|e| e.to_string())
})?;
serde_json::from_str(&raw).map_err(|e| e.to_string())
}