1use std::path::{Path, PathBuf};
6use std::sync::{Arc, Mutex, MutexGuard};
7
8use re_agent::capability::{CapabilityRegistry, ToolSpec};
9use re_core::project::Project;
10use serde_json::json;
11
12use crate::workspace::Workspace;
13
14#[derive(Clone)]
16pub struct ProjectDoc {
17 pub project: Option<Project>,
18 pub path: Option<PathBuf>,
19 pub dirty: bool,
20}
21
22impl ProjectDoc {
23 pub fn new_empty() -> Self {
24 Self {
25 project: None,
26 path: None,
27 dirty: false,
28 }
29 }
30
31 pub fn new_with(project: Project) -> Self {
32 Self {
33 project: Some(project),
34 path: None,
35 dirty: true,
36 }
37 }
38
39 pub fn new_named(name: impl Into<String>) -> Self {
40 Self {
41 project: Some(Project::new(name)),
42 path: None,
43 dirty: true,
44 }
45 }
46
47 pub fn load(path: impl AsRef<Path>) -> anyhow::Result<Self> {
48 let p = Project::load(path.as_ref())?;
49 Ok(Self {
50 project: Some(p),
51 path: Some(path.as_ref().to_path_buf()),
52 dirty: false,
53 })
54 }
55
56 pub fn save(&mut self, path: Option<&Path>) -> anyhow::Result<PathBuf> {
57 let target = path
58 .map(PathBuf::from)
59 .or_else(|| self.path.clone())
60 .ok_or_else(|| anyhow::anyhow!("kein Speicherpfad gesetzt"))?;
61 let proj = self
62 .project
63 .as_ref()
64 .ok_or_else(|| anyhow::anyhow!("kein Projekt geladen"))?;
65 proj.save(&target)?;
66 self.path = Some(target.clone());
67 self.dirty = false;
68 Ok(target)
69 }
70
71 pub fn close(&mut self) {
72 self.project = None;
73 self.path = None;
74 self.dirty = false;
75 }
76
77 pub fn name(&self) -> Option<String> {
78 self.project.as_ref().map(|p| p.name.clone())
79 }
80
81 pub fn is_loaded(&self) -> bool {
82 self.project.is_some()
83 }
84 pub fn is_dirty(&self) -> bool {
85 self.dirty
86 }
87 pub fn mark_dirty(&mut self) {
88 self.dirty = true;
89 }
90
91 pub fn mesh_count(&self) -> usize {
92 self.project
93 .as_ref()
94 .map(|p| p.library.meshes.len())
95 .unwrap_or(0)
96 }
97
98 pub fn material_count(&self) -> usize {
99 self.project
100 .as_ref()
101 .map(|p| p.library.materials.len())
102 .unwrap_or(0)
103 }
104
105 pub fn node_count(&self) -> usize {
106 self.project
107 .as_ref()
108 .map(|p| p.scene.nodes.len())
109 .unwrap_or(0)
110 }
111
112 pub fn fingerprint(&self) -> Option<String> {
113 self.project.as_ref().map(|p| p.fingerprint())
114 }
115}
116
117pub type SharedProjectDoc = Arc<Mutex<ProjectDoc>>;
118
119fn lock(doc: &SharedProjectDoc) -> Result<MutexGuard<'_, ProjectDoc>, String> {
120 doc.lock()
121 .map_err(|_| "Projekt-Sperre vergiftet".to_string())
122}
123
124pub fn register_project_tools(
125 reg: &mut CapabilityRegistry,
126 doc: SharedProjectDoc,
127 ws: Arc<Workspace>,
128) {
129 {
130 let d = doc.clone();
131 reg.register(
132 ToolSpec::new(
133 "project.new",
134 "Neues leeres Projekt anlegen",
135 json!({ "typ": "object", "felder": { "name": { "typ": "string" } } }),
136 ),
137 move |args| {
138 let mut doc = lock(&d)?;
139 let name = args
140 .get("name")
141 .and_then(|v| v.as_str())
142 .unwrap_or("untitled");
143 doc.project = Some(Project::new(name));
144 doc.path = None;
145 doc.dirty = true;
146 Ok(json!({ "ok": true, "name": name }))
147 },
148 );
149 }
150 {
151 let d = doc.clone();
152 let w = ws.clone();
153 reg.register(
154 ToolSpec::new(
155 "project.load",
156 "Projekt aus Datei laden (innerhalb des Workspace)",
157 json!({ "typ": "object", "felder": { "path": { "typ": "string" } } }),
158 ),
159 move |args| {
160 let path = args
161 .get("path")
162 .and_then(|v| v.as_str())
163 .ok_or("Parameter 'path' fehlt")?;
164 let path = w.resolve(path)?;
165 let loaded = ProjectDoc::load(path).map_err(|e| e.to_string())?;
166 let mut doc = lock(&d)?;
167 *doc = loaded;
168 Ok(json!({ "ok": true, "name": doc.name(), "pfad": doc.path }))
169 },
170 );
171 }
172 {
173 let d = doc.clone();
174 let w = ws.clone();
175 reg.register(
176 ToolSpec::new(
177 "project.save",
178 "Projekt speichern (Pfad optional, sonst zuletzt geladener; Workspace-intern)",
179 json!({ "typ": "object", "felder": { "path": { "typ": "string" } } }),
180 ),
181 move |args| {
182 let p = args
183 .get("path")
184 .and_then(|v| v.as_str())
185 .map(|raw| w.resolve(raw))
186 .transpose()?;
187 let mut doc = lock(&d)?;
188 let target = doc.save(p.as_deref()).map_err(|e| e.to_string())?;
189 Ok(json!({ "ok": true, "pfad": target }))
190 },
191 );
192 }
193 {
194 let d = doc.clone();
195 reg.register(
196 ToolSpec::simple("project.close", "Aktuelles Projekt schließen"),
197 move |_| {
198 let mut doc = lock(&d)?;
199 doc.close();
200 Ok(json!({ "ok": true }))
201 },
202 );
203 }
204 {
205 let d = doc.clone();
206 reg.register(
207 ToolSpec::simple(
208 "project.info",
209 "Projekt-Überblick: Name, Pfad, Dirty, Zähler",
210 ),
211 move |_| {
212 let doc = lock(&d)?;
213 Ok(json!({
214 "geladen": doc.is_loaded(),
215 "name": doc.name(),
216 "pfad": doc.path,
217 "dirty": doc.is_dirty(),
218 "meshes": doc.mesh_count(),
219 "materialien": doc.material_count(),
220 "knoten": doc.node_count(),
221 }))
222 },
223 );
224 }
225}
226
227#[cfg(test)]
228mod tests {
229 use super::*;
230 use re_agent::CapabilityRegistry;
231 use serde_json::json;
232 use std::fs;
233
234 #[test]
235 fn neu_und_info() {
236 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
237 let mut reg = CapabilityRegistry::new();
238 register_project_tools(
239 &mut reg,
240 doc.clone(),
241 Arc::new(Workspace::from_env_or_cwd()),
242 );
243 assert!(!reg.call("project.info", json!({})).unwrap()["geladen"]
244 .as_bool()
245 .unwrap());
246 reg.call("project.new", json!({ "name": "Demo" })).unwrap();
247 let info = reg.call("project.info", json!({})).unwrap();
248 assert!(info["geladen"].as_bool().unwrap());
249 assert_eq!(info["name"], json!("Demo"));
250 assert!(info["dirty"].as_bool().unwrap());
251 }
252
253 #[test]
254 fn save_und_load_roundtrip() {
255 let dir = std::env::temp_dir().join(format!("re_editor_proj_{}", std::process::id()));
256 let _ = fs::remove_dir_all(&dir);
257 fs::create_dir_all(&dir).unwrap();
258 let path = dir.join("demo.wbproj");
259
260 let ws = Arc::new(Workspace::new(&dir));
261 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
262 let mut reg = CapabilityRegistry::new();
263 register_project_tools(&mut reg, doc.clone(), ws.clone());
264 reg.call("project.new", json!({ "name": "Roundtrip" }))
265 .unwrap();
266 reg.call("project.save", json!({ "path": "demo.wbproj" }))
267 .unwrap();
268 assert!(reg
270 .call("project.save", json!({ "path": "../../entkommen.wbproj" }))
271 .is_err());
272 assert!(reg
273 .call("project.save", json!({ "path": "/tmp/entkommen.wbproj" }))
274 .is_err());
275 assert!(!std::path::Path::new("/tmp/entkommen.wbproj").exists());
276
277 let doc2 = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
279 let mut reg2 = CapabilityRegistry::new();
280 register_project_tools(&mut reg2, doc2.clone(), ws);
281 reg2.call("project.load", json!({ "path": path })).unwrap();
282 let info = reg2.call("project.info", json!({})).unwrap();
283 assert_eq!(info["name"], json!("Roundtrip"));
284 assert!(!info["dirty"].as_bool().unwrap());
285 assert!(info["pfad"].as_str().unwrap().ends_with("demo.wbproj"));
286
287 let _ = fs::remove_dir_all(&dir);
288 }
289
290 #[test]
291 fn close_leert_das_dokument() {
292 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_named("X")));
293 let mut reg = CapabilityRegistry::new();
294 register_project_tools(
295 &mut reg,
296 doc.clone(),
297 Arc::new(Workspace::from_env_or_cwd()),
298 );
299 assert!(reg.call("project.info", json!({})).unwrap()["geladen"]
300 .as_bool()
301 .unwrap());
302 reg.call("project.close", json!({})).unwrap();
303 assert!(!reg.call("project.info", json!({})).unwrap()["geladen"]
304 .as_bool()
305 .unwrap());
306 }
307
308 #[test]
309 fn load_fehlender_pfad_fehler() {
310 let dir = std::env::temp_dir().join(format!("re_editor_proj_err_{}", std::process::id()));
311 let _ = fs::remove_dir_all(&dir);
312 fs::create_dir_all(&dir).unwrap();
313 let doc = SharedProjectDoc::new(Mutex::new(ProjectDoc::new_empty()));
314 let mut reg = CapabilityRegistry::new();
315 register_project_tools(&mut reg, doc.clone(), Arc::new(Workspace::new(&dir)));
316 assert!(reg
317 .call("project.load", json!({ "path": "gibt-es-nicht.wbproj" }))
318 .is_err());
319 assert!(reg
320 .call("project.load", json!({ "path": "/etc/passwd" }))
321 .is_err());
322 assert!(reg.call("project.save", json!({})).is_err()); let _ = fs::remove_dir_all(&dir);
324 }
325}