Skip to main content

brep_app/panels/
plm_workspace.rs

1//! The workspace browser (plm-cad-integration-todo §3 S14): in PLM mode it replaces the
2//! file explorer. Decisions D9, D12 and D13; the server half is P6
3//! (`BREP_plm/src/workspace.rs`).
4//!
5//! * **Folders of links and files, per user.** A user arranges folders; a **link** points at
6//!   a part and follows its newest revision (drafts included), or is pinned to one revision.
7//!   A link is never a copy: opening it opens the part's document, and deleting it never
8//!   touches the part. A folder can also hold **files** (a customer's photo, notes), whose
9//!   every replace keeps the version before.
10//! * **Other users' workspaces**, read-only, when the administrator lets workspaces be
11//!   browsed (`workspaces_browsable`, on by default). The server refuses otherwise, and its
12//!   sentence is shown.
13//! * **Open by number (D13).** Part and Revision fields: a part id or number fills Revision
14//!   with the newest revision, drafts included; the user may pick another before opening.
15//! * **The verbs are the workspace's (D9).** New folder, Rename, Move and Delete act on the
16//!   workspace alone. Delete removes the link or the file, never a part or a revision.
17//! * **Files:** add one (the host hands the bytes in — [`WorkspaceBrowser::add_file`]; the
18//!   shell has no native file chooser, so a file arrives by drag and drop), open or download
19//!   a version, list versions, restore one (as a new version), and **Promote to attachment**
20//!   on a part or revision, which obeys every attachment refusal (S8).
21//!
22//! Every refusal is the server's own sentence, shown as sent. The browser talks through
23//! [`Workspaces`], which S1's client implements ([`PlmWorkspaces`]); the golden tests below
24//! run it against the REAL router. Nothing here is constructed without a server.
25
26use crate::http::query_component;
27use crate::plm::PlmFuture;
28use eframe::egui;
29use serde::Deserialize;
30use serde_json::{json, Value};
31use std::collections::HashMap;
32use std::task::Waker;
33
34use super::plm_attachments::{human_size, Attachment};
35use super::plm_parts::Pending;
36
37// --- the wire ------------------------------------------------------------------
38//
39// These mirror `BREP_plm/src/workspace.rs` and `src/api/workspace.rs`. The golden tests
40// below pin them against the REAL router. Every field defaults, so a server that adds a
41// field breaks nothing.
42
43/// A workspace the user may open (`GET /api/workspaces`).
44#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
45#[serde(default)]
46pub struct WorkspaceRow {
47    pub user_id: String,
48    pub username: String,
49    pub display_name: String,
50    pub mine: bool,
51    pub entries: usize,
52}
53
54#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
55#[serde(default)]
56pub struct WorkspaceList {
57    pub workspaces: Vec<WorkspaceRow>,
58    /// The administrator's setting: whether other users' workspaces may be browsed.
59    pub browsable: bool,
60}
61
62/// What a link resolves to now.
63#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
64#[serde(default)]
65pub struct LinkView {
66    pub thumbnail_url: String,
67    pub part_id: String,
68    /// Pinned to one revision; `false` follows the newest, drafts included.
69    pub pinned: bool,
70    pub number: String,
71    pub name: String,
72    pub document_class: String,
73    pub revision_id: String,
74    pub revision_label: String,
75    pub lifecycle: String,
76    /// `part/<part>/rev/<revision>`: what opens.
77    pub document_key: String,
78    pub part_missing: bool,
79    /// Pinned to a draft that was since deleted.
80    pub revision_missing: bool,
81}
82
83/// A file's current version, in brief.
84#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
85#[serde(default)]
86pub struct FileView {
87    pub version: u32,
88    pub versions: usize,
89    pub size: u64,
90    pub media_type: String,
91    pub sha256: String,
92    pub uploaded_at: u64,
93    pub uploaded_by_name: String,
94}
95
96/// One entry: a folder, a link or a file.
97#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
98#[serde(default)]
99pub struct Entry {
100    pub id: String,
101    pub owner: String,
102    pub owner_name: String,
103    pub parent: String,
104    pub name: String,
105    /// `folder`, `link` or `file`.
106    pub kind: String,
107    pub created_at: u64,
108    pub modified_at: u64,
109    /// A folder's entry count.
110    pub children: Option<usize>,
111    pub link: Option<LinkView>,
112    pub file: Option<FileView>,
113}
114
115impl Entry {
116    pub fn is_folder(&self) -> bool {
117        self.kind == "folder"
118    }
119
120    /// What the row says after the name.
121    pub fn detail(&self) -> String {
122        match (&self.link, &self.file, self.children) {
123            (Some(link), _, _) if link.part_missing => "the part is gone".into(),
124            (Some(link), _, _) if link.revision_missing => format!("{} — the pinned revision was deleted", link.number),
125            (Some(link), _, _) => {
126                let how = if link.pinned { "pinned" } else { "newest" };
127                format!("{} rev {} ({}, {how})", link.number, link.revision_label, link.lifecycle)
128            }
129            (_, Some(file), _) => format!("v{} of {} · {}", file.version, file.versions, human_size(file.size)),
130            (_, _, Some(n)) => format!("{n} item(s)"),
131            _ => String::new(),
132        }
133    }
134}
135
136#[derive(Deserialize)]
137struct Folder {
138    #[serde(default)]
139    entries: Vec<Entry>,
140}
141
142#[derive(Deserialize)]
143struct Made {
144    entry: Entry,
145}
146
147#[derive(Deserialize)]
148struct Promoted {
149    attachment: Attachment,
150}
151
152/// One version of a file (`GET …/versions`).
153#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
154#[serde(default)]
155pub struct Version {
156    pub version: u32,
157    pub sha256: String,
158    pub size: u64,
159    pub media_type: String,
160    pub uploaded_at: u64,
161    pub uploaded_by_name: String,
162    /// The version this one restored.
163    pub restored_from: Option<u32>,
164    pub current: bool,
165}
166
167#[derive(Deserialize)]
168struct Versions {
169    #[serde(default)]
170    versions: Vec<Version>,
171}
172
173/// A revision as `GET /api/parts/:id` lists it.
174#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
175#[serde(default)]
176pub struct RevisionRef {
177    pub id: String,
178    pub label: String,
179    pub lifecycle: String,
180    pub document_key: String,
181}
182
183/// A part looked up by id or number (D13).
184#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
185#[serde(default)]
186pub struct PartLookup {
187    pub id: String,
188    pub number: String,
189    pub name: String,
190    /// The newest by creation, drafts included — what the Revision field is filled with.
191    pub newest_revision: Option<RevisionRef>,
192    pub revision_views: Vec<RevisionRef>,
193}
194
195/// Where a file is promoted to.
196#[derive(Clone, Debug, Default, PartialEq)]
197pub struct PromoteTo {
198    /// A part id or number.
199    pub part: String,
200    /// A revision id or label; empty attaches it to the part.
201    pub revision: String,
202    /// 0: the current version.
203    pub version: u32,
204    pub kind: String,
205}
206
207/// The PLM's workspace routes, as the browser needs them. An `Err` is the sentence to
208/// show: the server's refusal, word for word, or why no answer came.
209pub trait Workspaces {
210    fn session(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> { None }
211    fn thumbnail(&self, _url: &str) -> PlmFuture<Option<Vec<u8>>> {
212        Box::pin(async { Ok(None) })
213    }
214    fn workspaces(&self) -> PlmFuture<WorkspaceList>;
215    /// One folder of `owner`'s workspace (empty `owner`: mine; empty `parent`: the top).
216    fn folder(&self, owner: &str, parent: &str) -> PlmFuture<Vec<Entry>>;
217    fn create_folder(&self, parent: &str, name: &str) -> PlmFuture<Entry>;
218    /// Link a part (id or number) here; `revision` (id or label) pins it, empty follows.
219    fn link(&self, parent: &str, part: &str, revision: &str) -> PlmFuture<Entry>;
220    fn add_file(&self, parent: &str, name: &str, bytes: Vec<u8>) -> PlmFuture<Entry>;
221    fn replace_file(&self, id: &str, name: &str, bytes: Vec<u8>) -> PlmFuture<Entry>;
222    /// `{name}`, `{parent}`, `{revision}` — any of them.
223    fn update(&self, id: &str, fields: Value) -> PlmFuture<Entry>;
224    fn delete(&self, id: &str, recursive: bool) -> PlmFuture<()>;
225    fn versions(&self, id: &str) -> PlmFuture<Vec<Version>>;
226    fn restore(&self, id: &str, version: u32) -> PlmFuture<Entry>;
227    /// A version's bytes (0: the current one).
228    fn download(&self, id: &str, version: u32) -> PlmFuture<Vec<u8>>;
229    fn promote(&self, id: &str, to: &PromoteTo) -> PlmFuture<Attachment>;
230    /// `GET /api/parts/:id` by id or number.
231    fn lookup(&self, part: &str) -> PlmFuture<PartLookup>;
232}
233
234/// [`Workspaces`] over S1's [`PlmClient`](crate::plm::client::PlmClient).
235pub struct PlmWorkspaces {
236    pub client: std::rc::Rc<crate::plm::client::PlmClient>,
237}
238
239impl PlmWorkspaces {
240    fn read<T: for<'de> Deserialize<'de> + 'static>(
241        &self,
242        method: &'static str,
243        path: String,
244        body: Option<Value>,
245    ) -> PlmFuture<T> {
246        let client = self.client.clone();
247        Box::pin(async move {
248            let body = body.map(|b| serde_json::to_vec(&b).unwrap_or_default());
249            let response = client.call(method, &path, body).await.map_err(|e| e.to_string())?;
250            serde_json::from_slice(&response.body)
251                .map_err(|e| format!("the PLM answered {path} with something this app cannot read: {e}"))
252        })
253    }
254
255    fn entry(&self, method: &'static str, path: String, body: Option<Value>) -> PlmFuture<Entry> {
256        let made: PlmFuture<Made> = self.read(method, path, body);
257        Box::pin(async move { Ok(made.await?.entry) })
258    }
259
260    fn bytes_entry(&self, method: &'static str, path: String, name: &str, bytes: Vec<u8>) -> PlmFuture<Entry> {
261        let client = self.client.clone();
262        let media_type = crate::store::media_type(name).to_string();
263        Box::pin(async move {
264            let response = client.call_typed(method, &path, bytes, &media_type).await.map_err(|e| e.to_string())?;
265            serde_json::from_slice::<Made>(&response.body)
266                .map(|m| m.entry)
267                .map_err(|e| format!("the PLM answered the upload with something this app cannot read: {e}"))
268        })
269    }
270}
271
272impl Workspaces for PlmWorkspaces {
273    fn session(&self) -> Option<std::rc::Rc<crate::plm::client::PlmClient>> { Some(self.client.clone()) }
274    fn thumbnail(&self, url: &str) -> PlmFuture<Option<Vec<u8>>> {
275        crate::plm::thumbnail_view::fetch(self.client.clone(), url.to_string())
276    }
277    fn workspaces(&self) -> PlmFuture<WorkspaceList> {
278        self.read("GET", "/api/workspaces".into(), None)
279    }
280
281    fn folder(&self, owner: &str, parent: &str) -> PlmFuture<Vec<Entry>> {
282        let folder: PlmFuture<Folder> =
283            self.read("GET", format!("/api/workspace/entries?owner={}&parent={}", query_component(owner), query_component(parent)), None);
284        Box::pin(async move { Ok(folder.await?.entries) })
285    }
286
287    fn create_folder(&self, parent: &str, name: &str) -> PlmFuture<Entry> {
288        self.entry("POST", "/api/workspace/folders".into(), Some(json!({ "parent": parent, "name": name })))
289    }
290
291    fn link(&self, parent: &str, part: &str, revision: &str) -> PlmFuture<Entry> {
292        self.entry("POST", "/api/workspace/links".into(), Some(json!({ "parent": parent, "part": part, "revision": revision })))
293    }
294
295    fn add_file(&self, parent: &str, name: &str, bytes: Vec<u8>) -> PlmFuture<Entry> {
296        let path = format!("/api/workspace/files?parent={}&name={}", query_component(parent), query_component(name));
297        self.bytes_entry("POST", path, name, bytes)
298    }
299
300    fn replace_file(&self, id: &str, name: &str, bytes: Vec<u8>) -> PlmFuture<Entry> {
301        self.bytes_entry("PUT", format!("/api/workspace/entries/{}/content", query_component(id)), name, bytes)
302    }
303
304    fn update(&self, id: &str, fields: Value) -> PlmFuture<Entry> {
305        self.entry("PATCH", format!("/api/workspace/entries/{}", query_component(id)), Some(fields))
306    }
307
308    fn delete(&self, id: &str, recursive: bool) -> PlmFuture<()> {
309        let client = self.client.clone();
310        let path = format!("/api/workspace/entries/{}?recursive={recursive}", query_component(id));
311        Box::pin(async move {
312            client.call("DELETE", &path, None).await.map_err(|e| e.to_string())?;
313            Ok(())
314        })
315    }
316
317    fn versions(&self, id: &str) -> PlmFuture<Vec<Version>> {
318        let versions: PlmFuture<Versions> = self.read("GET", format!("/api/workspace/entries/{}/versions", query_component(id)), None);
319        Box::pin(async move { Ok(versions.await?.versions) })
320    }
321
322    fn restore(&self, id: &str, version: u32) -> PlmFuture<Entry> {
323        self.entry("POST", format!("/api/workspace/entries/{}/versions/{version}/restore", query_component(id)), None)
324    }
325
326    fn download(&self, id: &str, version: u32) -> PlmFuture<Vec<u8>> {
327        let client = self.client.clone();
328        let path = format!("/api/workspace/entries/{}/content?version={version}", query_component(id));
329        Box::pin(async move { Ok(client.call("GET", &path, None).await.map_err(|e| e.to_string())?.body) })
330    }
331
332    fn promote(&self, id: &str, to: &PromoteTo) -> PlmFuture<Attachment> {
333        let body = json!({ "part": to.part, "revision": to.revision, "version": to.version, "kind": to.kind });
334        let promoted: PlmFuture<Promoted> = self.read("POST", format!("/api/workspace/entries/{}/promote", query_component(id)), Some(body));
335        Box::pin(async move { Ok(promoted.await?.attachment) })
336    }
337
338    fn lookup(&self, part: &str) -> PlmFuture<PartLookup> {
339        self.read("GET", format!("/api/parts/{}", query_component(part.trim())), None)
340    }
341}
342
343// --- the host's half ---------------------------------------------------------------
344
345/// The name the store opens the document `key` under: its one spelling, as the explorer
346/// spelled it before S14 (`/models/part/<p>/rev/<r>.nbrep` on the mirror store), so a
347/// document opened from the workspace and one opened any other way are the same tab.
348pub fn document_name(store: &dyn crate::store::ModelStore, key: &str) -> String {
349    store.canonical_identity(key)
350}
351
352/// Files dropped on the window this frame: (name, bytes). The web hands the bytes; a
353/// native drop hands a path, read here. This is how a file reaches the workspace — the
354/// shell has no file chooser of its own for arbitrary files.
355pub fn dropped(ctx: &egui::Context) -> Vec<(String, Vec<u8>)> {
356    let files = ctx.input(|i| i.raw.dropped_files.clone());
357    files
358        .into_iter()
359        .filter_map(|file| {
360            let name = if file.name.is_empty() {
361                file.path.as_ref()?.file_name()?.to_string_lossy().into_owned()
362            } else {
363                file.name.clone()
364            };
365            let bytes = match (&file.bytes, &file.path) {
366                (Some(bytes), _) => bytes.to_vec(),
367                (None, Some(path)) => std::fs::read(path).ok()?,
368                _ => return None,
369            };
370            Some((name, bytes))
371        })
372        .collect()
373}
374
375// --- the browser -----------------------------------------------------------------
376
377/// A pinned folder: its path from the top of the user's own workspace, (id, name) each.
378pub type Pin = Vec<(String, String)>;
379
380/// How a workspace folder is spelled in `@pinned` (the reserved preference S0 set aside
381/// for workspace folders in PLM mode): `workspace:` and the folder's path as JSON. The
382/// list stays an array of strings, the shape the file explorer keeps its pins in.
383pub fn pin_text(pin: &Pin) -> String {
384    format!("workspace:{}", serde_json::to_string(pin).unwrap_or_default())
385}
386
387/// The workspace folders in an `@pinned` value; anything else in it is left alone.
388pub fn pins_in(value: Option<&str>) -> Vec<Pin> {
389    let list: Vec<String> = value.and_then(|v| serde_json::from_str(v).ok()).unwrap_or_default();
390    list.iter()
391        .filter_map(|item| serde_json::from_str::<Pin>(item.strip_prefix("workspace:")?).ok())
392        .filter(|pin| !pin.is_empty())
393        .collect()
394}
395
396/// `value` (an `@pinned` value) with its workspace folders replaced by `pins`; the other
397/// entries are kept as they were.
398pub fn with_pins(value: Option<&str>, pins: &[Pin]) -> String {
399    let list: Vec<String> = value.and_then(|v| serde_json::from_str(v).ok()).unwrap_or_default();
400    let mut out: Vec<String> = list.into_iter().filter(|item| !item.starts_with("workspace:")).collect();
401    out.extend(pins.iter().map(pin_text));
402    serde_json::to_string(&out).unwrap_or_else(|_| "[]".into())
403}
404
405/// Read the pinned workspace folders from the store's `@pinned`.
406pub fn load_pins(store: &dyn crate::store::ModelStore) -> Vec<Pin> {
407    pins_in(store.read(crate::store::PINNED_KEY).as_deref())
408}
409
410/// Write `pins` into the store's `@pinned`, keeping whatever else it holds.
411pub fn save_pins(store: &dyn crate::store::ModelStore, pins: &[Pin]) -> Result<(), String> {
412    let current = store.read(crate::store::PINNED_KEY);
413    store.write(crate::store::PINNED_KEY, &with_pins(current.as_deref(), pins))
414}
415
416/// What the host does after a frame.
417#[derive(Debug, Default, PartialEq)]
418pub struct WorkspaceOutcome {
419    /// Open this document (`part/<part>/rev/<revision>`): a link was activated, or
420    /// Open by number was pressed.
421    pub open: Option<String>,
422    /// The folder `(id, name)` a link was opened from (`None` at the top, and
423    /// for Open by number): new PLM items the document's Save makes go there.
424    pub open_folder: Option<(String, String)>,
425    /// A file's bytes, to save where the user chooses: (file name, bytes).
426    pub downloaded: Option<(String, Vec<u8>)>,
427    /// The pinned folders changed: save this list to `@pinned` ([`save_pins`]).
428    pub pins: Option<Vec<Pin>>,
429    /// "Add file…" was pressed: open the file chooser, then
430    /// [`WorkspaceBrowser::add_file`] what it delivers.
431    pub pick_file: bool,
432}
433
434/// What a finished request changed.
435enum Done {
436    Entry(Entry),
437    Nothing,
438    Attachment(Attachment),
439}
440
441/// One user's workspace, one folder at a time.
442pub struct WorkspaceBrowser {
443    session: Option<std::rc::Rc<crate::plm::client::PlmClient>>,
444    thumbnails: crate::plm::thumbnail_view::ThumbnailCache,
445    /// Whether the host has a file chooser: "Add file…" beside drag and drop.
446    pub can_pick_files: bool,
447    pub browse_only: bool,
448    /// "Add file…" was pressed this frame.
449    pick_asked: bool,
450    /// Whose workspace: empty is the signed-in user's own.
451    pub owner: String,
452    pub owner_label: String,
453    /// The folders from the top down to the one shown: (id, name).
454    pub path: Vec<(String, String)>,
455    pub entries: Option<Vec<Entry>>,
456    pub workspaces: Option<WorkspaceList>,
457    /// The selected entry, by id.
458    pub selected: Option<String>,
459    /// An entry cut for a move, pasted into the folder shown.
460    pub cut: Option<Entry>,
461    /// A file's versions, once asked for: (entry id, versions).
462    pub versions: Option<(String, Vec<Version>)>,
463    /// The last refusal or failure, word for word.
464    pub problem: Option<String>,
465    /// What just happened, for the status line.
466    pub notice: Option<String>,
467    pub new_folder_name: String,
468    pub rename: Option<String>,
469    pub link_part: String,
470    pub link_revision: String,
471    pub open_part: String,
472    pub open_revision: String,
473    /// The part Open by number looked up, for its revision picker.
474    pub open_lookup: Option<PartLookup>,
475    pub promote: Option<PromoteTo>,
476    /// Delete was pressed once on the selected entry; the second press deletes.
477    pub delete_armed: bool,
478    /// When (egui input time) a finger's tap last walked into a folder, and
479    /// when the pointer was last pressed: a row tap pressed within egui's
480    /// double-click delay after the walk is ignored, so the second tap of a
481    /// double tap never acts on the row the new folder draws under it
482    /// (`file_explorer::double_tap_twin`).
483    touch_nav_at: Option<f64>,
484    last_press_at: Option<f64>,
485    /// The user's pinned folders (`@pinned`), once the host has read them.
486    pub pins: Option<Vec<Pin>>,
487    list_pending: Option<Pending<Vec<Entry>>>,
488    owners_pending: Option<Pending<WorkspaceList>>,
489    /// Every change still out: two started in one frame (a catalog link and a New part)
490    /// both land.
491    action_pending: Vec<(String, Pending<Done>)>,
492    /// A lookup, and whether to open what it finds.
493    lookup_pending: Option<(bool, Pending<PartLookup>)>,
494    download_pending: Option<(String, Pending<Vec<u8>>)>,
495    versions_pending: Option<(String, Pending<Vec<Version>>)>,
496    pub hits: HashMap<String, egui::Rect>,
497    /// A pin toggled while the browser drew, handed out in the frame's outcome.
498    pins_changed: Option<Vec<Pin>>,
499}
500
501impl Default for WorkspaceBrowser {
502    fn default() -> Self {
503        Self::new()
504    }
505}
506
507impl WorkspaceBrowser {
508    /// The signed-in user's own workspace, at the top.
509    pub fn new() -> Self {
510        WorkspaceBrowser {
511            touch_nav_at: None,
512            last_press_at: None,
513            session: None,
514            thumbnails: Default::default(),
515            can_pick_files: false,
516            browse_only: false,
517            pick_asked: false,
518            owner: String::new(),
519            owner_label: "My workspace".into(),
520            path: Vec::new(),
521            entries: None,
522            workspaces: None,
523            selected: None,
524            cut: None,
525            versions: None,
526            problem: None,
527            notice: None,
528            new_folder_name: String::new(),
529            rename: None,
530            link_part: String::new(),
531            link_revision: String::new(),
532            open_part: String::new(),
533            open_revision: String::new(),
534            open_lookup: None,
535            promote: None,
536            delete_armed: false,
537            pins: None,
538            list_pending: None,
539            owners_pending: None,
540            action_pending: Vec::new(),
541            lookup_pending: None,
542            download_pending: None,
543            versions_pending: None,
544            hits: HashMap::new(),
545            pins_changed: None,
546        }
547    }
548
549    /// The folder shown, by id; empty at the top. A new part saved from here is linked
550    /// into it (D9).
551    pub fn current_folder(&self) -> &str {
552        self.path.last().map(|(id, _)| id.as_str()).unwrap_or("")
553    }
554
555    pub fn thumbnail_entries(&self) -> Vec<&str> {
556        self.entries.iter().flatten().filter(|entry| entry.link.as_ref()
557            .is_some_and(|link| self.thumbnails.ready(&link.thumbnail_url)))
558            .map(|entry| entry.id.as_str()).collect()
559    }
560
561    /// Another user's workspace: browse only.
562    pub fn read_only(&self) -> bool {
563        self.browse_only || !self.owner.is_empty()
564    }
565
566    pub fn busy(&self) -> bool {
567        self.thumbnails.busy()
568            || self.list_pending.as_ref().is_some_and(Pending::is_open)
569            || self.owners_pending.as_ref().is_some_and(Pending::is_open)
570            || self.action_pending.iter().any(|(_, p)| p.is_open())
571            || self.lookup_pending.as_ref().is_some_and(|(_, p)| p.is_open())
572            || self.download_pending.as_ref().is_some_and(|(_, p)| p.is_open())
573            || self.versions_pending.as_ref().is_some_and(|(_, p)| p.is_open())
574    }
575
576    /// Ask again for the folder shown, and for whose workspaces may be opened.
577    pub fn reload(&mut self, plm: &dyn Workspaces) {
578        self.list_pending = Some(Pending::new(plm.folder(&self.owner, self.current_folder())));
579        self.owners_pending = Some(Pending::new(plm.workspaces()));
580    }
581
582    fn reload_folder(&mut self, plm: &dyn Workspaces) {
583        self.list_pending = Some(Pending::new(plm.folder(&self.owner, self.current_folder())));
584    }
585
586    /// Show another user's workspace (read-only), or the user's own (`owner` empty).
587    pub fn set_owner(&mut self, plm: &dyn Workspaces, owner: &str, label: &str) {
588        self.owner = owner.to_string();
589        self.owner_label = label.to_string();
590        self.path.clear();
591        self.selection_cleared();
592        self.entries = None;
593        self.reload_folder(plm);
594    }
595
596    fn selection_cleared(&mut self) {
597        self.selected = None;
598        self.rename = None;
599        self.promote = None;
600        self.versions = None;
601        self.delete_armed = false;
602    }
603
604    /// Walk into a folder of the one shown.
605    pub fn enter(&mut self, plm: &dyn Workspaces, folder: &Entry) {
606        self.path.push((folder.id.clone(), folder.name.clone()));
607        self.selection_cleared();
608        self.entries = None;
609        self.reload_folder(plm);
610    }
611
612    /// The user's own Home, at its top: where every opening of the dialog
613    /// starts. Every folder reachable from it (linked folders included) is a
614    /// folder to walk into.
615    pub fn go_home(&mut self) {
616        self.owner.clear();
617        self.owner_label = "My workspace".into();
618        self.path.clear();
619        self.selection_cleared();
620        self.cut = None;
621        self.entries = None;
622        self.list_pending = None;
623    }
624
625    /// Go to a pinned folder of the user's own workspace.
626    pub fn go_to_pin(&mut self, plm: &dyn Workspaces, pin: &Pin) {
627        self.owner.clear();
628        self.owner_label = "My workspace".into();
629        self.path = pin.clone();
630        self.selection_cleared();
631        self.entries = None;
632        self.reload_folder(plm);
633    }
634
635    /// Pin the folder shown, or unpin it if it is pinned: the new list for `@pinned`.
636    pub fn toggle_pin(&mut self) -> Option<Vec<Pin>> {
637        if self.read_only() || self.path.is_empty() {
638            return None;
639        }
640        let mut pins = self.pins.clone().unwrap_or_default();
641        let here = self.current_folder().to_string();
642        let before = pins.len();
643        pins.retain(|pin| pin.last().map(|(id, _)| id.as_str()) != Some(here.as_str()));
644        if pins.len() == before {
645            pins.push(self.path.clone());
646        }
647        self.pins = Some(pins.clone());
648        Some(pins)
649    }
650
651    /// Walk back up to `depth` folders from the top (0: the top).
652    pub fn up_to(&mut self, plm: &dyn Workspaces, depth: usize) {
653        self.path.truncate(depth);
654        self.selection_cleared();
655        self.entries = None;
656        self.reload_folder(plm);
657    }
658
659    fn entry(&self, id: &str) -> Option<&Entry> {
660        self.entries.as_ref()?.iter().find(|e| e.id == id)
661    }
662
663    /// The selected entry.
664    pub fn selection(&self) -> Option<&Entry> {
665        self.entry(self.selected.as_deref()?)
666    }
667
668    /// Select the entry named `name` in the folder shown (what a click does).
669    pub fn select_named(&mut self, name: &str) -> bool {
670        let found = self.entries.as_ref().and_then(|list| list.iter().find(|e| e.name == name)).map(|e| e.id.clone());
671        let changed = found != self.selected;
672        if changed {
673            self.selection_cleared();
674        }
675        self.selected = found;
676        self.selected.is_some()
677    }
678
679    /// A double click: walk into a folder, open a link's document, download a file.
680    pub fn activate(&mut self, plm: &dyn Workspaces, entry: &Entry, outcome: &mut WorkspaceOutcome) {
681        match (entry.kind.as_str(), &entry.link) {
682            ("folder", _) => self.enter(plm, entry),
683            ("link", Some(link)) if link.part_missing => self.problem = Some(format!("{}: the part it links is gone", entry.name)),
684            ("link", Some(link)) if link.revision_missing || link.document_key.is_empty() => {
685                self.problem = Some(format!(
686                    "{}: it is pinned to a revision of {} that was deleted — pin it to another, or let it follow the newest",
687                    entry.name, link.number
688                ))
689            }
690            ("link", Some(link)) => {
691                outcome.open = Some(link.document_key.clone());
692                outcome.open_folder = self.path.last().cloned();
693            }
694            ("file", _) => self.download(plm, entry, 0),
695            _ => {}
696        }
697    }
698
699    fn act(&mut self, what: impl Into<String>, future: PlmFuture<Done>) {
700        self.problem = None;
701        self.action_pending.push((what.into(), Pending::new(future)));
702    }
703
704    fn map<T: 'static>(future: PlmFuture<T>, done: impl FnOnce(T) -> Done + 'static) -> PlmFuture<Done> {
705        Box::pin(async move { future.await.map(done) })
706    }
707
708    /// New folder in the folder shown.
709    pub fn new_folder(&mut self, plm: &dyn Workspaces, name: &str) {
710        let future = Self::map(plm.create_folder(self.current_folder(), name.trim()), Done::Entry);
711        self.act(format!("made folder {}", name.trim()), future);
712    }
713
714    /// Link a part (id or number) into the folder shown; `revision` pins it, empty follows.
715    pub fn link(&mut self, plm: &dyn Workspaces, part: &str, revision: &str) {
716        let future = Self::map(plm.link(self.current_folder(), part.trim(), revision.trim()), Done::Entry);
717        self.act(format!("linked {}", part.trim()), future);
718    }
719
720    /// A file the host was handed (dropped on the pane): a new file in the folder shown,
721    /// or — when a file of that name is already there — its next version, the one before
722    /// kept.
723    pub fn add_file(&mut self, plm: &dyn Workspaces, name: &str, bytes: Vec<u8>) {
724        let existing = self
725            .entries
726            .as_ref()
727            .and_then(|list| list.iter().find(|e| e.kind == "file" && e.name.eq_ignore_ascii_case(name)))
728            .map(|e| e.id.clone());
729        match existing {
730            Some(id) => {
731                let future = Self::map(plm.replace_file(&id, name, bytes), Done::Entry);
732                self.act(format!("{name}: a new version, the one before kept"), future);
733            }
734            None => {
735                let future = Self::map(plm.add_file(self.current_folder(), name, bytes), Done::Entry);
736                self.act(format!("added {name}"), future);
737            }
738        }
739    }
740
741    pub fn rename(&mut self, plm: &dyn Workspaces, id: &str, name: &str) {
742        let future = Self::map(plm.update(id, json!({ "name": name.trim() })), Done::Entry);
743        self.act(format!("renamed to {}", name.trim()), future);
744    }
745
746    /// Cut an entry, to paste it into another folder of the same workspace.
747    pub fn cut(&mut self, id: &str) {
748        self.cut = self.entry(id).cloned();
749        if let Some(entry) = &self.cut {
750            self.notice = Some(format!("{} cut — open a folder and paste it there", entry.name));
751        }
752    }
753
754    /// Move the cut entry into the folder shown.
755    pub fn paste(&mut self, plm: &dyn Workspaces) {
756        let Some(entry) = self.cut.take() else { return };
757        let future = Self::map(plm.update(&entry.id, json!({ "parent": self.current_folder() })), Done::Entry);
758        self.act(format!("moved {}", entry.name), future);
759    }
760
761    /// Remove an entry: a link or a file, never a part (D9). A folder goes with everything in
762    /// it — the browser asks first ([`Self::delete_armed`]).
763    pub fn delete(&mut self, plm: &dyn Workspaces, id: &str) {
764        let Some(entry) = self.entry(id).cloned() else { return };
765        let future = Self::map(plm.delete(&entry.id, entry.is_folder()), |()| Done::Nothing);
766        let what = match entry.kind.as_str() {
767            "link" => format!("removed the link {} — the part is untouched", entry.name),
768            _ => format!("deleted {}", entry.name),
769        };
770        self.selection_cleared();
771        self.act(what, future);
772    }
773
774    /// Pin a link to `revision` (id or label), or let it follow the newest (empty).
775    pub fn pin(&mut self, plm: &dyn Workspaces, id: &str, revision: &str) {
776        let future = Self::map(plm.update(id, json!({ "revision": revision })), Done::Entry);
777        let what = if revision.is_empty() { "the link follows the newest revision".to_string() } else { format!("pinned to {revision}") };
778        self.act(what, future);
779    }
780
781    pub fn load_versions(&mut self, plm: &dyn Workspaces, id: &str) {
782        self.versions_pending = Some((id.to_string(), Pending::new(plm.versions(id))));
783    }
784
785    /// Make version `n` current again — as a new version, so none is lost.
786    pub fn restore(&mut self, plm: &dyn Workspaces, id: &str, version: u32) {
787        let future = Self::map(plm.restore(id, version), Done::Entry);
788        self.act(format!("restored version {version} as a new version"), future);
789    }
790
791    pub fn download(&mut self, plm: &dyn Workspaces, entry: &Entry, version: u32) {
792        self.download_pending = Some((entry.name.clone(), Pending::new(plm.download(&entry.id, version))));
793    }
794
795    /// Promote a file to a real attachment; the server's attachment refusals apply (S8).
796    pub fn promote(&mut self, plm: &dyn Workspaces, id: &str, to: &PromoteTo) {
797        let future = Self::map(plm.promote(id, to), Done::Attachment);
798        self.act("promoted", future);
799    }
800
801    /// Open by number: look the part up and fill Revision with its newest revision
802    /// (drafts included). With `open`, open it once found — or the revision the user
803    /// typed, if they typed one.
804    pub fn look_up(&mut self, plm: &dyn Workspaces, open: bool) {
805        // A lookup already asked to open (Open pressed) stays an opening one:
806        // the Part field reports losing focus on the frame AFTER the click.
807        let open = open || self.lookup_pending.as_ref().is_some_and(|(opening, _)| *opening);
808        self.problem = None;
809        self.lookup_pending = Some((open, Pending::new(plm.lookup(&self.open_part))));
810    }
811
812    /// Open the revision in the Revision field of the part looked up.
813    /// What went wrong, as the browser shows it: the server not answering is
814    /// one plain sentence, not the transport's words.
815    pub fn problem_text(&self) -> Option<String> {
816        self.problem.as_deref().map(|problem| {
817            if problem.starts_with("the PLM server did not answer") {
818                "The PLM server is not reachable. Your open tabs are kept; try again (Reload) when it is back.".to_string()
819            } else {
820                problem.to_string()
821            }
822        })
823    }
824
825    pub fn open_by_number(&mut self, plm: &dyn Workspaces, outcome: &mut WorkspaceOutcome) {
826        let looked_up = self.open_lookup.as_ref().filter(|p| {
827            let typed = self.open_part.trim();
828            p.id == typed || p.number.eq_ignore_ascii_case(typed)
829        });
830        match looked_up {
831            Some(part) => {
832                let wanted = self.open_revision.trim();
833                let revision = part
834                    .revision_views
835                    .iter()
836                    .find(|r| r.id == wanted || r.label.eq_ignore_ascii_case(wanted))
837                    .or(part.newest_revision.as_ref().filter(|_| wanted.is_empty()));
838                match revision {
839                    Some(r) if !r.document_key.is_empty() => {
840                        outcome.open = Some(r.document_key.clone());
841                        // Opened: the fields start empty next time, not as a picker of
842                        // this part's revisions.
843                        self.open_part.clear();
844                        self.open_revision.clear();
845                        self.open_lookup = None;
846                    }
847                    _ => self.problem = Some(format!("{} has no revision '{wanted}'", part.number)),
848                }
849            }
850            None => self.look_up(plm, true),
851        }
852    }
853
854    /// Drive every request: apply what the server answered.
855    pub fn poll(&mut self, waker: &Waker, plm: &dyn Workspaces, outcome: &mut WorkspaceOutcome) {
856        self.thumbnails.poll(waker);
857        if let Some(answer) = self.list_pending.as_mut().and_then(|p| p.poll(waker)) {
858            self.list_pending = None;
859            match answer {
860                Ok(entries) => {
861                    if self.selected.as_deref().is_some_and(|id| !entries.iter().any(|e| e.id == id)) {
862                        self.selection_cleared();
863                    }
864                    self.entries = Some(entries);
865                }
866                Err(problem) => {
867                    // The rows stay up while a reload is in flight, but not past
868                    // its refusal: a listing the server would not give (a
869                    // workspace made private under a viewer) is not shown from
870                    // memory either (plan S14; `workspaces_browsable` off).
871                    if self.selected.is_some() { self.selection_cleared(); }
872                    self.entries = Some(Vec::new());
873                    self.problem = Some(problem);
874                }
875            }
876        }
877        if let Some(answer) = self.owners_pending.as_mut().and_then(|p| p.poll(waker)) {
878            self.owners_pending = None;
879            match answer {
880                Ok(list) => self.workspaces = Some(list),
881                Err(problem) => self.problem = Some(problem),
882            }
883        }
884        let mut answered = Vec::new();
885        self.action_pending.retain_mut(|(what, pending)| match pending.poll(waker) {
886            Some(answer) => {
887                answered.push((std::mem::take(what), answer));
888                false
889            }
890            None => true,
891        });
892        for (what, answer) in answered {
893            {
894                match answer {
895                    Ok(done) => {
896                        self.notice = Some(what);
897                        match done {
898                            Done::Entry(entry) => {
899                                if self.versions.as_ref().is_some_and(|(id, _)| *id == entry.id) {
900                                    self.load_versions(plm, &entry.id);
901                                }
902                                self.selected = Some(entry.id);
903                            }
904                            Done::Attachment(a) => {
905                                self.notice = Some(format!("promoted to an attachment: {} ({})", a.name, a.kind));
906                                self.promote = None;
907                            }
908                            Done::Nothing => {}
909                        }
910                        self.reload_folder(plm);
911                    }
912                    Err(problem) => self.problem = Some(problem),
913                }
914            }
915        }
916        if let Some((open, pending)) = self.lookup_pending.as_mut() {
917            let open = *open;
918            if let Some(answer) = pending.poll(waker) {
919                self.lookup_pending = None;
920                match answer {
921                    Ok(part) => {
922                        let typed = self.open_revision.trim().to_string();
923                        if typed.is_empty() || !part.revision_views.iter().any(|r| r.label.eq_ignore_ascii_case(&typed) || r.id == typed) {
924                            self.open_revision = part.newest_revision.as_ref().map(|r| r.label.clone()).unwrap_or_default();
925                        }
926                        self.open_part = part.number.clone();
927                        self.open_lookup = Some(part);
928                        if open {
929                            self.open_by_number(plm, outcome);
930                        }
931                    }
932                    Err(problem) => {
933                        self.open_lookup = None;
934                        self.problem = Some(problem);
935                    }
936                }
937            }
938        }
939        if let Some((name, pending)) = self.download_pending.as_mut() {
940            if let Some(answer) = pending.poll(waker) {
941                let name = std::mem::take(name);
942                self.download_pending = None;
943                match answer {
944                    Ok(bytes) => outcome.downloaded = Some((name, bytes)),
945                    Err(problem) => self.problem = Some(problem),
946                }
947            }
948        }
949        if let Some((id, pending)) = self.versions_pending.as_mut() {
950            if let Some(answer) = pending.poll(waker) {
951                let id = std::mem::take(id);
952                self.versions_pending = None;
953                match answer {
954                    Ok(list) => self.versions = Some((id, list)),
955                    Err(problem) => self.problem = Some(problem),
956                }
957            }
958        }
959    }
960}
961
962// --- drawing ----------------------------------------------------------------------
963
964/// A waker that repaints: an answer is drawn the frame it arrives.
965fn repaint_waker(ctx: &egui::Context) -> Waker {
966    struct Repaint(egui::Context);
967    impl std::task::Wake for Repaint {
968        fn wake(self: std::sync::Arc<Self>) {
969            self.0.request_repaint();
970        }
971    }
972    Waker::from(std::sync::Arc::new(Repaint(ctx.clone())))
973}
974
975/// A row's kind, in plain text: the app ships no symbol font, and an emoji folder draws
976/// as an empty box.
977fn icon(entry: &Entry) -> &'static str {
978    match entry.kind.as_str() {
979        "folder" => "[folder]",
980        "link" => "[link]",
981        _ => "[file]",
982    }
983}
984
985impl WorkspaceBrowser {
986    fn hit(&mut self, prefix: &str, key: &str, response: &egui::Response) {
987        self.hits.insert(format!("{prefix}ws:{key}"), response.rect);
988    }
989
990    /// Draw the browser, poll its requests, and say what the host must do. `prefix` is
991    /// the host's hit-key prefix (`plm/workspace:` in the PLM pane, `open:` in the Open
992    /// modal).
993    pub fn show(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str) -> WorkspaceOutcome {
994        if let Some(client) = plm.session() {
995            if self.session.as_ref().is_some_and(|old| !std::rc::Rc::ptr_eq(old, &client)) {
996                // The Open modal reuses this browser across connections too.
997                let can_pick_files = self.can_pick_files;
998                let browse_only = self.browse_only;
999                *self = Self::new();
1000                self.can_pick_files = can_pick_files;
1001                self.browse_only = browse_only;
1002            }
1003            self.session = Some(client);
1004        }
1005        let mut outcome = WorkspaceOutcome::default();
1006        let ctx = ui.ctx().clone();
1007        let waker = repaint_waker(&ctx);
1008        if self.entries.is_none() && !self.busy() {
1009            self.reload(plm);
1010        }
1011        self.poll(&waker, plm, &mut outcome);
1012        self.hits.clear();
1013        if let Some(now) = ui.input(|i| i.pointer.any_pressed().then_some(i.time)) {
1014            self.last_press_at = Some(now);
1015        }
1016
1017        self.owner_row(ui, plm, prefix);
1018        self.open_row(ui, plm, prefix, &mut outcome);
1019        ui.separator();
1020        self.crumbs(ui, plm, prefix);
1021        self.rows(ui, plm, prefix, &mut outcome);
1022        self.selection_verbs(ui, plm, prefix, &mut outcome);
1023        if !self.read_only() {
1024            ui.separator();
1025            self.make_row(ui, plm, prefix);
1026        }
1027        outcome.pick_file = std::mem::take(&mut self.pick_asked);
1028        if let Some(problem) = self.problem_text() {
1029            ui.colored_label(ui.visuals().error_fg_color, problem);
1030        } else if let Some(notice) = &self.notice {
1031            ui.label(egui::RichText::new(notice).weak());
1032        }
1033        // Anything the frame started is answered on a later one: poll again now so a
1034        // request that is already answered (the in-process router) lands this frame.
1035        self.poll(&waker, plm, &mut outcome);
1036        outcome.pins = self.pins_changed.take();
1037        outcome
1038    }
1039
1040    fn owner_row(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str) {
1041        let rows: Vec<WorkspaceRow> = self.workspaces.as_ref().map(|w| w.workspaces.clone()).unwrap_or_default();
1042        let mut chosen: Option<(String, String)> = None;
1043        ui.horizontal(|ui| {
1044            let combo = egui::ComboBox::from_id_salt((prefix, "ws-owner")).selected_text(&self.owner_label).show_ui(ui, |ui| {
1045                for row in &rows {
1046                    let label = if row.mine { "My workspace".to_string() } else { format!("{}'s workspace", row.display_name.trim().is_empty().then_some(&row.username).unwrap_or(&row.display_name)) };
1047                    let owner = if row.mine { String::new() } else { row.user_id.clone() };
1048                    if ui.selectable_label(self.owner == owner, &label).clicked() {
1049                        chosen = Some((owner, label));
1050                    }
1051                }
1052            });
1053            self.hit(prefix, "owner", &combo.response);
1054            if self.read_only() {
1055                ui.label(egui::RichText::new("read-only").weak());
1056            }
1057            if self.workspaces.as_ref().is_some_and(|w| !w.browsable) {
1058                ui.label(egui::RichText::new("other workspaces are private on this server").weak());
1059            }
1060            let reload = ui.small_button("\u{21BB}").on_hover_text("Reload");
1061            self.hit(prefix, "reload", &reload);
1062            if reload.clicked() {
1063                self.reload(plm);
1064            }
1065        });
1066        if let Some((owner, label)) = chosen {
1067            self.set_owner(plm, &owner, &label);
1068        }
1069    }
1070
1071    /// The Revision field's width, the SAME for the text box shown before a
1072    /// lookup answers and the combo shown after. The widgets are drawn in
1073    /// one row with the Open button to their right, and the lookup answers
1074    /// asynchronously — a click already pressed on Open while the field was
1075    /// the 60 pt text box released on a combo 100 pt wide (egui's default)
1076    /// that had pushed the button 40 pt to the right; egui saw a press on one
1077    /// widget and a release on another, and nothing opened (2026-10-03, the
1078    /// open-by-number scripts). A width shared by both widgets keeps the
1079    /// button where the pointer is.
1080    const REVISION_FIELD_WIDTH: f32 = 80.0;
1081
1082    fn open_row(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str, outcome: &mut WorkspaceOutcome) {
1083        ui.horizontal(|ui| {
1084            ui.label("Part");
1085            let part = ui.add(egui::TextEdit::singleline(&mut self.open_part).desired_width(110.0).hint_text("number or id"));
1086            self.hit(prefix, "open-part", &part);
1087            if part.lost_focus() && !self.open_part.trim().is_empty() {
1088                // Typing a part fills Revision with its newest (D13).
1089                self.look_up(plm, false);
1090            }
1091            ui.label("Revision");
1092            let labels: Vec<(String, String)> = self
1093                .open_lookup
1094                .as_ref()
1095                .map(|p| p.revision_views.iter().map(|r| (r.label.clone(), format!("{} ({})", r.label, r.lifecycle))).collect())
1096                .unwrap_or_default();
1097            let revision = if labels.is_empty() {
1098                ui.add_sized(
1099                    [Self::REVISION_FIELD_WIDTH, ui.spacing().interact_size.y],
1100                    egui::TextEdit::singleline(&mut self.open_revision).hint_text("newest"),
1101                )
1102            } else {
1103                let text = self.open_revision.clone();
1104                egui::ComboBox::from_id_salt((prefix, "ws-open-revision"))
1105                    .width(Self::REVISION_FIELD_WIDTH)
1106                    .selected_text(text)
1107                    .show_ui(ui, |ui| {
1108                        for (label, shown) in labels.iter().rev() {
1109                            ui.selectable_value(&mut self.open_revision, label.clone(), shown);
1110                        }
1111                    })
1112                    .response
1113            };
1114            self.hit(prefix, "open-revision", &revision);
1115            let go = ui.add_enabled(!self.open_part.trim().is_empty(), egui::Button::new("Open"));
1116            self.hit(prefix, "open-go", &go);
1117            if go.clicked() {
1118                self.open_by_number(plm, outcome);
1119            }
1120        });
1121    }
1122
1123    fn crumbs(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str) {
1124        let mut up_to: Option<usize> = None;
1125        let mut paste = false;
1126        ui.horizontal_wrapped(|ui| {
1127            let top = ui.link(&self.owner_label);
1128            self.hit(prefix, "crumb:0", &top);
1129            if top.clicked() {
1130                up_to = Some(0);
1131            }
1132            for (depth, (_, name)) in self.path.clone().iter().enumerate() {
1133                ui.label("/");
1134                let crumb = ui.link(name);
1135                self.hit(prefix, &format!("crumb:{}", depth + 1), &crumb);
1136                if crumb.clicked() {
1137                    up_to = Some(depth + 1);
1138                }
1139            }
1140            if let Some(cut) = self.cut.clone().filter(|_| !self.read_only()) {
1141                let button = ui.small_button(format!("Paste {} here", cut.name));
1142                self.hit(prefix, "paste", &button);
1143                paste = button.clicked();
1144            }
1145            if !self.read_only() && !self.path.is_empty() {
1146                let here = self.current_folder().to_string();
1147                let pinned = self.pins.as_ref().is_some_and(|pins| pins.iter().any(|p| p.last().map(|(id, _)| id.as_str()) == Some(here.as_str())));
1148                let button = ui.small_button(if pinned { "Unpin folder" } else { "Pin folder" });
1149                self.hit(prefix, "pin-folder", &button);
1150                if button.clicked() {
1151                    self.pins_changed = self.toggle_pin();
1152                }
1153            }
1154        });
1155        let mut go_to: Option<Pin> = None;
1156        if let Some(pins) = self.pins.clone().filter(|pins| !pins.is_empty()) {
1157            ui.horizontal_wrapped(|ui| {
1158                ui.label(egui::RichText::new("Pinned:").weak());
1159                for (index, pin) in pins.iter().enumerate() {
1160                    let name = pin.last().map(|(_, name)| name.as_str()).unwrap_or("");
1161                    let button = ui.small_button(name).on_hover_text(pin.iter().map(|(_, n)| n.as_str()).collect::<Vec<_>>().join(" / "));
1162                    self.hit(prefix, &format!("pinned:{index}"), &button);
1163                    if button.clicked() {
1164                        go_to = Some(pin.clone());
1165                    }
1166                }
1167            });
1168        }
1169        if let Some(pin) = go_to {
1170            self.go_to_pin(plm, &pin);
1171        }
1172        if let Some(depth) = up_to {
1173            self.up_to(plm, depth);
1174        }
1175        if paste {
1176            self.paste(plm);
1177        }
1178    }
1179
1180    /// The folder's rows. Only the rows in view are laid out (a folder of
1181    /// 2000 links cost ~35 ms a frame drawing every row); the rest publish
1182    /// their hit keys where they sit, so a click on one scrolls it in.
1183    fn rows(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str, outcome: &mut WorkspaceOutcome) {
1184        let Some(entries) = self.entries.take() else {
1185            ui.label(egui::RichText::new("Reading the workspace…").weak());
1186            return;
1187        };
1188        if entries.is_empty() {
1189            let empty = if self.read_only() { "Empty." } else { "Empty. Make a folder, link a part, or drop a file here." };
1190            ui.label(egui::RichText::new(empty).weak());
1191        }
1192        let mut activated: Option<Entry> = None;
1193        let mut clicked: Option<String> = None;
1194        let row_height = crate::plm::thumbnail_view::SIDE;
1195        let pitch = row_height + ui.spacing().item_spacing.y;
1196        egui::ScrollArea::vertical().id_salt((prefix, "ws-rows")).max_height(260.0).show_rows(ui, row_height, entries.len(), |ui, shown| {
1197            let top = ui.cursor().top() - shown.start as f32 * pitch;
1198            let (left, width) = (ui.cursor().left(), ui.available_width());
1199            for (index, entry) in entries.iter().enumerate() {
1200                if shown.contains(&index) {
1201                    continue;
1202                }
1203                let rect = egui::Rect::from_min_size(egui::pos2(left, top + index as f32 * pitch), egui::vec2(width, row_height));
1204                self.hits.insert(format!("{prefix}ws:entry:{}", entry.name), rect);
1205            }
1206            for entry in &entries[shown] {
1207                ui.push_id(&entry.id, |ui| {
1208                let selected = self.selected.as_deref() == Some(entry.id.as_str());
1209                let text = format!("{} {}   {}", icon(entry), entry.name, entry.detail());
1210                let row = ui.horizontal(|ui| {
1211                    let url = entry.link.as_ref().map_or("", |link| link.thumbnail_url.as_str());
1212                    let preview = self.thumbnails.show(ui, url, |url| plm.thumbnail(url));
1213                    ui.add_sized(
1214                        [ui.available_width(), crate::plm::thumbnail_view::SIDE],
1215                        egui::Button::selectable(selected, text).wrap_mode(egui::TextWrapMode::Truncate),
1216                    ).union(preview)
1217                }).inner;
1218                self.hit(prefix, &format!("entry:{}", entry.name), &row);
1219                // Click selects, double click opens (every tree in this app).
1220                // Under a finger a double tap rarely reads as a double click,
1221                // so one tap walks into a folder; anything else is selected
1222                // and opened by the selection's Open verb.
1223                if crate::viewport::touch::enabled(ui.ctx()) {
1224                    let now = ui.input(|i| i.time);
1225                    let settling = crate::panels::file_explorer::double_tap_twin(ui.ctx(), self.touch_nav_at, self.last_press_at);
1226                    if row.clicked() && !settling {
1227                        if entry.is_folder() {
1228                            activated = Some(entry.clone());
1229                            self.touch_nav_at = Some(now);
1230                        } else {
1231                            clicked = Some(entry.name.clone());
1232                        }
1233                    }
1234                } else {
1235                    if row.clicked() {
1236                        clicked = Some(entry.name.clone());
1237                    }
1238                    if row.double_clicked() {
1239                        activated = Some(entry.clone());
1240                    }
1241                }
1242                });
1243            }
1244        });
1245        if self.entries.is_none() {
1246            self.entries = Some(entries);
1247        }
1248        if let Some(name) = clicked {
1249            self.select_named(&name);
1250        }
1251        if let Some(entry) = activated {
1252            self.activate(plm, &entry, outcome);
1253        }
1254    }
1255
1256    fn selection_verbs(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str, outcome: &mut WorkspaceOutcome) {
1257        let Some(entry) = self.selection().cloned() else { return };
1258        let writable = !self.read_only();
1259        ui.separator();
1260        ui.label(egui::RichText::new(format!("{} {}", icon(&entry), entry.name)).strong());
1261        ui.horizontal_wrapped(|ui| {
1262            // A finger has no double click: a selected link opens here.
1263            if entry.kind == "link" && crate::viewport::touch::enabled(ui.ctx()) {
1264                let open = ui.button("Open");
1265                self.hit(prefix, "sel:open", &open);
1266                if open.clicked() {
1267                    self.activate(plm, &entry, outcome);
1268                }
1269            }
1270            if writable {
1271                let rename = ui.small_button("Rename");
1272                self.hit(prefix, "sel:rename", &rename);
1273                if rename.clicked() {
1274                    self.rename = Some(entry.name.clone());
1275                }
1276                let cut = ui.small_button("Move…");
1277                self.hit(prefix, "sel:cut", &cut);
1278                if cut.clicked() {
1279                    self.cut(&entry.id);
1280                }
1281                let label = if self.delete_armed {
1282                    "Really delete?"
1283                } else if entry.kind == "link" {
1284                    "Remove link"
1285                } else {
1286                    "Delete"
1287                };
1288                let delete = ui.small_button(label).on_hover_text(match entry.kind.as_str() {
1289                    "link" => "Removes the link only: the part and its revisions are untouched.",
1290                    "folder" => "Deletes the folder and everything in it (links, files). No part is touched.",
1291                    _ => "Deletes the file and every version of it.",
1292                });
1293                self.hit(prefix, if self.delete_armed { "sel:delete-confirm" } else { "sel:delete" }, &delete);
1294                if delete.clicked() {
1295                    if self.delete_armed || entry.kind == "link" {
1296                        self.delete(plm, &entry.id);
1297                    } else {
1298                        self.delete_armed = true;
1299                    }
1300                }
1301            }
1302            if let Some(link) = entry.link.clone() {
1303                if writable && !link.part_missing {
1304                    if link.pinned {
1305                        let follow = ui.small_button("Follow newest");
1306                        self.hit(prefix, "sel:follow", &follow);
1307                        if follow.clicked() {
1308                            self.pin(plm, &entry.id, "");
1309                        }
1310                    } else if !link.revision_label.is_empty() {
1311                        let pin = ui.small_button(format!("Pin to {}", link.revision_label));
1312                        self.hit(prefix, "sel:pin", &pin);
1313                        if pin.clicked() {
1314                            self.pin(plm, &entry.id, &link.revision_id);
1315                        }
1316                    }
1317                }
1318            }
1319            if entry.kind == "file" {
1320                let download = ui.small_button("Download");
1321                self.hit(prefix, "sel:download", &download);
1322                if download.clicked() {
1323                    self.download(plm, &entry, 0);
1324                }
1325                let versions = ui.small_button("Versions");
1326                self.hit(prefix, "sel:versions", &versions);
1327                if versions.clicked() {
1328                    self.load_versions(plm, &entry.id);
1329                }
1330                if writable {
1331                    let promote = ui.small_button("Promote to attachment…");
1332                    self.hit(prefix, "sel:promote", &promote);
1333                    if promote.clicked() {
1334                        self.promote = Some(PromoteTo { kind: "other".into(), ..PromoteTo::default() });
1335                    }
1336                }
1337            }
1338        });
1339        if let Some(mut name) = self.rename.take() {
1340            let mut keep = true;
1341            ui.horizontal(|ui| {
1342                let field = ui.text_edit_singleline(&mut name);
1343                self.hit(prefix, "sel:rename-name", &field);
1344                let go = ui.small_button("Rename");
1345                self.hit(prefix, "sel:rename-go", &go);
1346                if go.clicked() {
1347                    self.rename(plm, &entry.id, &name);
1348                    keep = false;
1349                }
1350            });
1351            if keep {
1352                self.rename = Some(name);
1353            }
1354        }
1355        if let Some((id, versions)) = self.versions.clone().filter(|(id, _)| *id == entry.id) {
1356            for v in versions.iter().rev() {
1357                ui.horizontal(|ui| {
1358                    let restored = v.restored_from.map(|n| format!(", restored from v{n}")).unwrap_or_default();
1359                    ui.label(format!(
1360                        "v{}{} · {} · {}{restored}",
1361                        v.version,
1362                        if v.current { " (current)" } else { "" },
1363                        human_size(v.size),
1364                        v.uploaded_by_name
1365                    ));
1366                    let download = ui.small_button("Download");
1367                    self.hit(prefix, &format!("version:{}:download", v.version), &download);
1368                    if download.clicked() {
1369                        self.download(plm, &entry, v.version);
1370                    }
1371                    if writable && !v.current {
1372                        let restore = ui.small_button("Restore");
1373                        self.hit(prefix, &format!("version:{}:restore", v.version), &restore);
1374                        if restore.clicked() {
1375                            self.restore(plm, &id, v.version);
1376                        }
1377                    }
1378                });
1379            }
1380        }
1381        if let Some(mut to) = self.promote.take() {
1382            let mut keep = true;
1383            ui.horizontal_wrapped(|ui| {
1384                ui.label("Part");
1385                let part = ui.add(egui::TextEdit::singleline(&mut to.part).desired_width(100.0).hint_text("number"));
1386                self.hit(prefix, "sel:promote-part", &part);
1387                ui.label("Revision");
1388                let revision = ui.add(egui::TextEdit::singleline(&mut to.revision).desired_width(50.0).hint_text("part"));
1389                self.hit(prefix, "sel:promote-revision", &revision);
1390                let kinds = ["drawing", "datasheet", "spec", "image", "other"].map(|kind| (kind.to_string(), kind, kind));
1391                crate::form::enum_dropdown(ui, &format!("{prefix}ws:sel:promote-kind"), &kinds, &mut to.kind, None, Some(&mut self.hits));
1392                let go = ui.add_enabled(!to.part.trim().is_empty(), egui::Button::new("Promote"));
1393                self.hit(prefix, "sel:promote-go", &go);
1394                if go.clicked() {
1395                    self.promote(plm, &entry.id, &to);
1396                }
1397                if ui.small_button("Cancel").clicked() {
1398                    keep = false;
1399                }
1400            });
1401            if keep {
1402                self.promote = Some(to);
1403            }
1404        }
1405    }
1406
1407    fn make_row(&mut self, ui: &mut egui::Ui, plm: &dyn Workspaces, prefix: &str) {
1408        ui.horizontal(|ui| {
1409            let name = ui.add(egui::TextEdit::singleline(&mut self.new_folder_name).desired_width(120.0).hint_text("folder name"));
1410            self.hit(prefix, "new-folder-name", &name);
1411            let go = ui.add_enabled(!self.new_folder_name.trim().is_empty(), egui::Button::new("New folder"));
1412            self.hit(prefix, "new-folder", &go);
1413            if go.clicked() {
1414                let name = std::mem::take(&mut self.new_folder_name);
1415                self.new_folder(plm, &name);
1416            }
1417        });
1418        ui.horizontal(|ui| {
1419            let part = ui.add(egui::TextEdit::singleline(&mut self.link_part).desired_width(100.0).hint_text("part number"));
1420            self.hit(prefix, "link-part", &part);
1421            let revision = ui.add(egui::TextEdit::singleline(&mut self.link_revision).desired_width(50.0).hint_text("newest"));
1422            self.hit(prefix, "link-revision", &revision);
1423            let go = ui.add_enabled(!self.link_part.trim().is_empty(), egui::Button::new("Link here"));
1424            self.hit(prefix, "link-go", &go);
1425            if go.clicked() {
1426                let (part, revision) = (std::mem::take(&mut self.link_part), std::mem::take(&mut self.link_revision));
1427                self.link(plm, &part, &revision);
1428            }
1429        });
1430        ui.horizontal_wrapped(|ui| {
1431            if self.can_pick_files {
1432                let add = ui.button("Add file\u{2026}").on_hover_text("Choose a file on this machine to add to this folder");
1433                self.hit(prefix, "add-file", &add);
1434                self.pick_asked |= add.clicked();
1435            }
1436            ui.label(egui::RichText::new("Drop a file on this pane to add it here (a file of the same name gets a new version).").weak().small());
1437        });
1438    }
1439}
1440
1441