brep_app/panels/
plm_launch.rs1use crate::document::{Document, Documents};
26use crate::panels::file::FileDialog;
27use crate::plm::PlmFuture;
28use crate::store::{ModelStore, Residency};
29
30pub fn open_key(search: &str) -> Option<String> {
34 let query = search.strip_prefix('?').unwrap_or(search);
35 let raw = query.split('&').find_map(|pair| pair.strip_prefix("open="))?;
36 let key = decode(raw);
37 let parts: Vec<&str> = key.split('/').collect();
38 match parts.as_slice() {
39 ["part", part, "rev", revision] if !part.is_empty() && !revision.is_empty() => Some(key.clone()),
40 _ => None,
41 }
42}
43
44fn decode(text: &str) -> String {
45 let bytes = text.as_bytes();
46 let mut out = Vec::with_capacity(bytes.len());
47 let mut i = 0;
48 while i < bytes.len() {
49 let hex = bytes
50 .get(i + 1..i + 3)
51 .and_then(|h| std::str::from_utf8(h).ok())
52 .and_then(|h| u8::from_str_radix(h, 16).ok());
53 match (bytes[i], hex) {
54 (b'%', Some(byte)) => {
55 out.push(byte);
56 i += 3;
57 }
58 (b'+', _) => {
59 out.push(b' ');
60 i += 1;
61 }
62 (byte, _) => {
63 out.push(byte);
64 i += 1;
65 }
66 }
67 }
68 String::from_utf8_lossy(&out).into_owned()
69}
70
71#[derive(Debug, PartialEq)]
73pub enum Step {
74 Pending,
76 Idle,
78 Opened(String),
80 OpenedEmpty(String),
82 SignIn(String),
85 Refused(String),
87}
88
89impl Step {
90 pub fn settles(&self) -> bool {
92 matches!(self, Step::Opened(_) | Step::OpenedEmpty(_) | Step::Refused(_))
93 }
94}
95
96#[derive(Debug, Default, serde::Deserialize)]
98#[serde(default)]
99struct PartCheck {
100 number: String,
101 document_class: String,
102 part_type: String,
103 revisions: Vec<RevisionCheck>,
104}
105
106#[derive(Debug, Default, serde::Deserialize)]
107#[serde(default)]
108struct RevisionCheck {
109 id: String,
110 label: String,
111}
112
113enum State {
114 Waiting,
115 Checking(PlmFuture<PartCheck>),
116 Done,
117}
118
119pub struct Launch {
121 pub key: String,
122 state: State,
123}
124
125impl Launch {
126 pub fn new(key: impl Into<String>) -> Self {
127 Launch { key: key.into(), state: State::Waiting }
128 }
129
130 #[cfg(target_arch = "wasm32")]
132 pub fn from_page() -> Option<Self> {
133 let search = web_sys::window()?.location().search().ok()?;
134 open_key(&search).map(Launch::new)
135 }
136
137 pub fn is_done(&self) -> bool {
138 matches!(self.state, State::Done)
139 }
140
141 pub fn step(&mut self, store: &dyn ModelStore, docs: &mut Documents, file: &mut FileDialog) -> Step {
144 if self.is_done() {
145 return Step::Idle;
146 }
147 let Some(client) = store.plm_client() else {
148 self.state = State::Done;
149 return match store.plm_session() {
150 Some(_) => Step::SignIn(format!(
151 "Sign in to the PLM to open {} — the page reloads onto it after you sign in.",
152 self.key
153 )),
154 None => Step::Refused(format!(
155 "{} can be opened only in the CAD app the PLM hosts (its Open in CAD button)",
156 self.key
157 )),
158 };
159 };
160 let name = store.canonical_identity(&self.key);
161 match store.residency(&name) {
162 Residency::Resident => {
163 self.state = State::Done;
164 file.open_document(docs, store, &name);
165 return if docs.active().name() == Some(name.as_str()) {
168 Step::Opened(name)
169 } else {
170 Step::Refused(format!("{} could not be opened: its document did not load", self.key))
171 };
172 }
173 Residency::OnDisk => {
174 let _ = store.read(&name);
176 return Step::Pending;
177 }
178 Residency::Absent => {}
179 }
180 if let State::Waiting = self.state {
183 let (part, _) = split(&self.key);
184 let path = crate::plm::identity::part_path(&part);
185 let client = client.clone();
186 self.state = State::Checking(Box::pin(async move {
187 let response = client.call("GET", &path, None).await.map_err(|e| e.to_string())?;
188 serde_json::from_slice(&response.body).map_err(|e| format!("the PLM's answer was not understood: {e}"))
189 }));
190 }
191 let State::Checking(future) = &mut self.state else { return Step::Pending };
192 let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
193 let std::task::Poll::Ready(answer) = future.as_mut().poll(&mut cx) else { return Step::Pending };
194 self.state = State::Done;
195 let (_, revision) = split(&self.key);
196 match answer {
197 Err(sentence) => Step::Refused(format!("{} could not be opened: {sentence}", self.key)),
198 Ok(part) => match part.revisions.iter().find(|r| r.id == revision) {
199 None => Step::Refused(format!("{} could not be opened: part {} has no revision {revision}", self.key, part.number)),
200 Some(found) => {
201 let mut engine = docs.spawn_engine();
202 engine.settings.workbench = match part.part_type.as_str() {
205 "assembly" => "assembly",
206 "drawing" => "drawing",
207 "diagram" => "diagram",
208 "wire_harness" | "wireHarness" => "wireHarness",
209 "pcb" => "pcb",
210 "symbol" => "symbol",
211 "pads" => "pads",
212 _ => "modeling",
213 }.into();
214 let class = match part.document_class.as_str() {
215 "family" => crate::document_class::DocumentClass::Family,
216 "template" => crate::document_class::DocumentClass::Template,
217 "instructions" => crate::document_class::DocumentClass::Instructions,
218 _ => crate::document_class::DocumentClass::Normal,
219 };
220 let mut doc = Document::fresh(engine, class);
221 doc.set_name(Some(name.clone()));
222 docs.open_document(doc);
223 let _ = found;
224 Step::OpenedEmpty(name)
225 }
226 },
227 }
228 }
229}
230
231fn split(key: &str) -> (String, String) {
232 crate::plm::family::key_ids(key).unwrap_or_default()
233}
234
235pub fn forget_query() {
237 #[cfg(target_arch = "wasm32")]
238 {
239 use wasm_bindgen::{JsCast, JsValue};
240 let Some(window) = web_sys::window() else { return };
241 let location = window.location();
242 let (Ok(path), Ok(search), Ok(hash)) = (location.pathname(), location.search(), location.hash()) else { return };
243 let kept: Vec<&str> = search
244 .trim_start_matches('?')
245 .split('&')
246 .filter(|pair| !pair.is_empty() && !pair.starts_with("open="))
247 .collect();
248 let query = if kept.is_empty() { String::new() } else { format!("?{}", kept.join("&")) };
249 let url = JsValue::from_str(&format!("{path}{query}{hash}"));
253 let Ok(history) = js_sys::Reflect::get(&window, &JsValue::from_str("history")) else { return };
254 let Ok(replace) = js_sys::Reflect::get(&history, &JsValue::from_str("replaceState")) else { return };
255 if let Ok(replace) = replace.dyn_into::<js_sys::Function>() {
256 let _ = replace.call3(&history, &JsValue::NULL, &JsValue::from_str(""), &url);
257 }
258 }
259}
260