1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use std::{
io,
path::{Path, PathBuf},
process::Command,
str,
};
use fj::{abi, version::RawVersion};
use crate::{platform::HostPlatform, Parameters};
pub struct Model {
src_path: PathBuf,
lib_path: PathBuf,
manifest_path: PathBuf,
parameters: Parameters,
}
impl Model {
pub fn new(
path: impl AsRef<Path>,
parameters: Parameters,
) -> Result<Self, Error> {
let path = path.as_ref();
let crate_dir = path.canonicalize()?;
let metadata = cargo_metadata::MetadataCommand::new()
.current_dir(&crate_dir)
.exec()?;
let pkg = package_associated_with_directory(&metadata, &crate_dir)?;
let src_path = crate_dir.join("src");
let lib_path = {
let name = pkg.name.replace('-', "_");
let file = HostPlatform::lib_file_name(&name);
let target_dir =
metadata.target_directory.clone().into_std_path_buf();
target_dir.join("debug").join(file)
};
Ok(Self {
src_path,
lib_path,
manifest_path: pkg.manifest_path.as_std_path().to_path_buf(),
parameters,
})
}
pub fn watch_path(&self) -> PathBuf {
self.src_path.clone()
}
pub fn evaluate(&self) -> Result<Evaluation, Error> {
let manifest_path = self.manifest_path.display().to_string();
let cargo_output = Command::new("cargo")
.arg("rustc")
.args(["--manifest-path", &manifest_path])
.args(["--crate-type", "cdylib"])
.output()?;
if !cargo_output.status.success() {
let output =
String::from_utf8(cargo_output.stderr).unwrap_or_else(|_| {
String::from("Failed to fetch command output")
});
return Err(Error::Compile { output });
}
let seconds_taken = str::from_utf8(&cargo_output.stderr)
.unwrap()
.rsplit_once(' ')
.unwrap()
.1
.trim();
let shape = unsafe {
let lib = libloading::Library::new(&self.lib_path)
.map_err(Error::LoadingLibrary)?;
let version_pkg: libloading::Symbol<fn() -> RawVersion> =
lib.get(b"version_pkg").map_err(Error::LoadingVersion)?;
let version_pkg = version_pkg();
if fj::version::VERSION_PKG != version_pkg.as_str() {
let host = String::from_utf8_lossy(
fj::version::VERSION_PKG.as_bytes(),
)
.into_owned();
let model =
String::from_utf8_lossy(version_pkg.as_str().as_bytes())
.into_owned();
return Err(Error::VersionMismatch { host, model });
}
let init: libloading::Symbol<abi::InitFunction> = lib
.get(abi::INIT_FUNCTION_NAME.as_bytes())
.map_err(Error::LoadingInit)?;
let mut host = Host::new(&self.parameters);
match init(&mut abi::Host::from(&mut host)) {
abi::ffi_safe::Result::Ok(_metadata) => {}
abi::ffi_safe::Result::Err(e) => {
return Err(Error::InitializeModel(e.into()));
}
}
let model = host.take_model().ok_or(Error::NoModelRegistered)?;
model.shape(&host).map_err(Error::Shape)?
};
Ok(Evaluation {
shape,
compile_time: seconds_taken.into(),
})
}
}
pub struct Evaluation {
pub shape: fj::Shape,
pub compile_time: String,
}
pub struct Host<'a> {
args: &'a Parameters,
model: Option<Box<dyn fj::models::Model>>,
}
impl<'a> Host<'a> {
pub fn new(parameters: &'a Parameters) -> Self {
Self {
args: parameters,
model: None,
}
}
pub fn take_model(&mut self) -> Option<Box<dyn fj::models::Model>> {
self.model.take()
}
}
impl<'a> fj::models::Host for Host<'a> {
fn register_boxed_model(&mut self, model: Box<dyn fj::models::Model>) {
self.model = Some(model);
}
}
impl<'a> fj::models::Context for Host<'a> {
fn get_argument(&self, name: &str) -> Option<&str> {
self.args.get(name).map(|s| s.as_str())
}
}
fn package_associated_with_directory<'m>(
metadata: &'m cargo_metadata::Metadata,
dir: &Path,
) -> Result<&'m cargo_metadata::Package, Error> {
for pkg in metadata.workspace_packages() {
let crate_dir = pkg
.manifest_path
.parent()
.and_then(|p| p.canonicalize().ok());
if crate_dir.as_deref() == Some(dir) {
return Ok(pkg);
}
}
Err(ambiguous_path_error(metadata, dir))
}
fn ambiguous_path_error(
metadata: &cargo_metadata::Metadata,
dir: &Path,
) -> Error {
let mut possible_paths = Vec::new();
for id in &metadata.workspace_members {
let cargo_toml = &metadata[id].manifest_path;
let crate_dir = cargo_toml
.parent()
.expect("A Cargo.toml always has a parent");
let simplified_path = crate_dir
.strip_prefix(&metadata.workspace_root)
.unwrap_or(crate_dir);
possible_paths.push(simplified_path.into());
}
Error::AmbiguousPath {
dir: dir.to_path_buf(),
possible_paths,
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(
"Failed to load model library\n\
This might be a bug in Fornjot, or, at the very least, this error \
message should be improved. Please report this!"
)]
LoadingLibrary(#[source] libloading::Error),
#[error(
"Failed to load the Fornjot version that the model uses\n\
- Is your model using the `fj` library? All models must!\n\
- Was your model created with a really old version of Fornjot?"
)]
LoadingVersion(#[source] libloading::Error),
#[error(
"Failed to load the model's `init` function\n\
- Did you define a model function using `#[fj::model]`?"
)]
LoadingInit(#[source] libloading::Error),
#[error("Host version ({host}) and model version ({model}) do not match")]
VersionMismatch {
host: String,
model: String,
},
#[error("Error compiling model\n{output}")]
Compile {
output: String,
},
#[error("I/O error while loading model")]
Io(#[from] io::Error),
#[error("Unable to initialize the model")]
InitializeModel(#[source] fj::models::Error),
#[error("No model was registered")]
NoModelRegistered,
#[error("Unable to determine the model's geometry")]
Shape(#[source] fj::models::Error),
#[error("Error watching model for changes")]
Notify(#[from] notify::Error),
#[error("Unable to determine the crate's metadata")]
CargoMetadata(#[from] cargo_metadata::Error),
#[error(
"It doesn't look like \"{}\" is a crate directory. Did you mean one of {}?",
dir.display(),
possible_paths.iter().map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ")
)]
AmbiguousPath {
dir: PathBuf,
possible_paths: Vec<PathBuf>,
},
}