diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml index 30cade8c..b1e7c1ce 100755 --- a/.github/workflows/desktop.yml +++ b/.github/workflows/desktop.yml @@ -117,6 +117,9 @@ jobs: # where the file is, the duplicate findings, the worklist suggestions - name: Test the rules of new items from local files run: node scripts/desktop-new-files.test.mjs + # files dropped on the window (#418): New, Add files… or a refusal + - name: Test the drop routing + run: node scripts/desktop-drop-route.test.mjs # the mesh check of the shared 3D viewer: empty, cut-off or invalid # models end in a message, not in an empty canvas (#290) - name: Test the 3D viewer's mesh check diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b841f2..05d9f9ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ see the notices in the README. ### Added +- Desktop: drag and drop of files from Explorer, Finder or the file manager onto the window (#418). On a revision tab you have checked out (or that *Add files…* would check out) the drop opens *Add files…*; elsewhere it opens *New item* with the files. A frame shows what the drop does; frozen revisions, revisions checked out by someone else, viewers and editors without a group are refused with the reason. Only regular files are taken (folders are skipped), with the same checks as the file dialog. Tab reordering keeps working (pointer events, not HTML5 drag and drop). - **Getting started in the desktop app** (#422): after the first sign-in TeamCraft Desktop opens a short wizard – server (skipped when a policy fixes it), sign-in, the working folder (*Change…*, *Open folder*), *Get project diff --git a/CLAUDE.md b/CLAUDE.md index 14c55cb3..a5c32464 100755 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -221,6 +221,7 @@ desktop/ TeamCraft Desktop (Tauri 2, own Cargo project – never part list-thumbs.js = row pictures of Home and the search (lazy, IntersectionObserver, #420), crash.js = crash reports; desktop/src/workspace.rs + layout.rs = working folder, park, local changes; new-files.js + desktop/src/newfiles.rs = new items from local files, worklist *New on this computer* (#359); + drop.js + drop-rules.js = files dropped from the file manager → *New* / *Add files…* (#418, dragDropEnabled); desktop/src/localserver.rs = *Try TeamCraft on this computer* (starts the bundled teamcraft-server local); desktop/src/policy.rs = managed deployment policies (registry / macOS profile / /etc/teamcraft, #378); tauri.local-server.conf.json = the *with local server* installers (externalBin teamcraft-server + postgresql/) diff --git a/README.md b/README.md index 98fc03f4..02b10052 100755 --- a/README.md +++ b/README.md @@ -318,7 +318,8 @@ end-to-end tests against a real PostgreSQL. project group (with *New item here* on every folder, starting in a favourite folder, e.g. the one with the Inventor project file, if you like), a navigable *Graph* of every revision (BOM children, references and where-used, coloured by state, with quantities and preview - images), *Park* of work in progress, new items straight from the files + images), *Park* of work in progress, files dropped from the file manager into *New* + or *Add files…*, new items straight from the files saved in the working folder (group and folder taken from where they are, duplicates refused, the worklist suggesting the parts and assemblies that belong to no item yet), an Agent view, crash reports the user diff --git a/desktop/README.md b/desktop/README.md index f2ac669b..5286fef8 100755 --- a/desktop/README.md +++ b/desktop/README.md @@ -32,7 +32,8 @@ TeamCraft server – it is a client, not an offline copy. | Graph | A navigable reference/BOM graph around the revision: the focused item in the middle, its BOM children and references below, the assemblies that use it above. Node **colour** = lifecycle state, **size** and the ⚙ badge = the item's own BOM complexity, **×n in the top-left corner** = how many instances of that part or sub-assembly the assembly contains (summed over its BOM lines, ×1 included). Every node is clickable and takes the tab to that item – a sub-assembly shows its own graph, anything else its overview, the item in the middle its own overview – with a **back control that stays in the same place** (the left of the sub-tab row) and leads back the way you came, one step per click; `Ctrl`/`⌘`+click opens a node in a tab of its own. Mouse-wheel zooms on the cursor; drag to pan; the view fits itself while details load until you zoom or pan, a double-click on the background fits it again. More than 8 neighbours on one side are laid out in rows; above 48 only the first 48 are fetched for preview and complexity (one request each), the rest keep a basic card. Preview images and filenames on the nodes; pure SVG, no external engine | | Working folder | One folder per project group that **mirrors the folder structure of the files** (`///`, the folder is stored with every file on the server), one copy of each file – the revision is metadata in `/.teamcraft/state.json` (item, revision, file id, version, SHA-256, checked out). Files you have not checked out are **read-only** on disk; *Check out* takes the lock and makes them writable; *Check in…* uploads the chosen files as new versions, releases the lock in one step and makes them read-only again (files above 32 MiB go first as chunked, resumable uploads, then join the same check-in transaction). The check-in dialog shows the progress, and **Cancel** stops the check-in until its last byte is sent – before the next STEP export, between two chunks (the upload sessions are discarded, `DELETE /uploads/{id}`) or half-way through the streamed request with the small files: nothing is stored, the revision stays checked out (`src/abortable.rs`). Every check-in names the version each file is based on, so the server refuses (409) to overwrite a version somebody else checked in meanwhile. The Workspace tab shows *up to date* / *modified* / *outdated* / *conflict* / *new* / *missing* / *name clash* per file (from the server's file status) with its path, read-only flag and the lock owner. Two items with the same folder and file name are reported, never overwritten. Lock and backup files of the CAD programs are skipped; a SolidCraft design that is open in SolidCraft (a fresh `.~.lock` beside it, `src/cadlock.rs`) is marked *Open in SolidCraft* with the computer and user, and the check-in dialog warns that unsaved changes there are not checked in; Creo iterations count as one file. A tracked revision the server no longer shows (you left a restricted project group) is listed as *No longer accessible*: its local copies stay untouched and are never synced again – delete them yourself if you must In *Check in…*, a new part or assembly file next to a revision that has a model already is offered unticked, with *New item from this file* (#359) | | Get | *Get…* on a revision: the item with its BOM (revision rule *latest* or *released*) and the parts its CAD files reference, resolved by the server (`…/workset`); only missing and outdated files are downloaded (SHA-256, checked after the download), recorded one by one so an interrupted Get continues where it stopped – also inside a large file: the bytes received stay in `..teamcraft-download` and the next Get asks only for the rest (`Range` / `If-Range`, `src/resume.rs`), checks the SHA-256 of the whole file and renames it into place; progress and *Cancel* in the status bar. No browser downloads | -| Add files | *Add files…* (Files section and *More ▾*): file picker → the files are **copied** into the working folder of the revision (checked out first if needed; sub-folder selectable, originals untouched) and listed as *new* in *Check in…* (option *Check in now*; remembered in `.teamcraft/added.json` until checked in). A name that exists is a new version and asks first. The Files section says why it is unavailable (locked by someone else, in review, released = frozen → Revise). Pure logic and tests in `src/addfiles.rs`; drag and drop onto the window is not supported (`dragDropEnabled` is off) | +| Add files | *Add files…* (Files section and *More ▾*): file picker → the files are **copied** into the working folder of the revision (checked out first if needed; sub-folder selectable, originals untouched) and listed as *new* in *Check in…* (option *Check in now*; remembered in `.teamcraft/added.json` until checked in). A name that exists is a new version and asks first. The Files section says why it is unavailable (locked by someone else, in review, released = frozen → Revise). Pure logic and tests in `src/addfiles.rs`; files dropped on an open revision tab take the same way (*Drop files*) | +| Drop files | Files dragged from Explorer, Finder or the file manager onto the window (#418; Tauri's native file drop, `dragDropEnabled` on the main window): on a revision tab you have checked out – or that *Add files…* would check out – they open *Add files…* with the dropped paths instead of the picker; elsewhere *New item* with the files chosen (as *Create item* of the worklist suggestions). A frame over the window says what the drop does; a revision that takes no files (released, in review, checked out by someone else), viewers, editors without a group and an open dialog refuse it with the reason. The routing is a pure function (`ui/js/drop-rules.js`, tested by `scripts/desktop-drop-route.test.mjs`), the listener `ui/js/drop.js`. Only regular files are taken: `dropped_files` leaves folders out (with a note), and `addfiles::plan` and `new_item_copy` refuse anything that is not a regular file. The tabs are moved with pointer events, not HTML5 drag and drop, so tab dragging is unaffected | | Old workspaces | Folders of the older layout `///` (and `//`) are found after the sign-in; the app offers to move the files into the new layout – never overwriting a file, keeping files whose place is taken and listing them, writing every step to `.teamcraft/migration.log` | | Check in all | *Check in all* in the worklist (navigator and home page): the check-outs with local changes (modified, new, conflicting files) are listed first, with the offer to check them in with their files; then every check-out without local changes is checked in on the server (lock released, one revision at a time); check-outs with a conflict stay checked out. *Sign out* asks the same: *Check in and sign out*, *Park and sign out*, *Sign out anyway*. The list is the pure `layout::local_changes` | | Park | *Park…* (Workspace tab, *More ▾*, the check-in dialog): the ticked files go up as new versions through the upload endpoint (`POST …/files`) and the check-out **stays** – work in progress survives a lost laptop. After somebody else released your check-out, the Workspace tab shows *Released by X; your local changes are kept and need a new check-out* (`released` of the server's file status) | diff --git a/desktop/src/addfiles.rs b/desktop/src/addfiles.rs index 4bec7edc..fbc1e93a 100755 --- a/desktop/src/addfiles.rs +++ b/desktop/src/addfiles.rs @@ -85,6 +85,12 @@ pub fn plan( let disk = source.file_name().and_then(|n| n.to_str()).ok_or_else(|| { ApiError::local(format!("{} has no usable file name.", source.display())) })?; + // picked or dropped from the file manager (#418): regular files only + if !is_regular_file(source) { + return Err(ApiError::local(format!( + "{disk} is not a file – folders and other entries cannot be added." + ))); + } if is_ignored(disk) { return Err(ApiError::local(format!( "{disk} is a temporary or backup file and cannot be added." @@ -119,6 +125,28 @@ pub fn plan( Ok(out) } +/// A regular file (a symbolic link counts by what it points to); folders, +/// devices, pipes and paths that do not exist are not. +pub fn is_regular_file(path: &Path) -> bool { + std::fs::metadata(path).is_ok_and(|m| m.is_file()) +} + +/// Paths dropped on the window from the file manager (#418), split into the +/// regular files (in their order, each once) and the number of entries +/// left out – folders and everything else that is not a regular file. +pub fn split_dropped(paths: &[PathBuf]) -> (Vec, usize) { + let mut files: Vec = Vec::new(); + let mut skipped = 0; + for path in paths { + if !is_regular_file(path) { + skipped += 1; + } else if !files.contains(path) { + files.push(path.clone()); + } + } + (files, skipped) +} + fn same_file(a: &Path, b: &Path) -> bool { match (a.canonicalize(), b.canonicalize()) { (Ok(a), Ok(b)) => a == b, @@ -398,6 +426,27 @@ mod tests { plan(ws.path(), None, &[], "", &[a.clone(), a.clone()], "").is_err(), "picked twice" ); + // a dropped folder or a path that is gone is not a file (#418) + let folder = src.path().join("assembly"); + std::fs::create_dir(&folder).unwrap(); + let err = plan(ws.path(), None, &[], "", &[folder], "").unwrap_err(); + assert!(err.to_string().contains("not a file"), "{err}"); + let gone = src.path().join("gone.step"); + assert!(plan(ws.path(), None, &[], "", &[gone], "").is_err()); + } + + #[test] + fn dropped_paths_keep_regular_files_only() { + let src = tempfile::tempdir().unwrap(); + let a = write(src.path(), "a.step", "1"); + let b = write(src.path(), "b.ipt", "2"); + let folder = src.path().join("parts"); + std::fs::create_dir(&folder).unwrap(); + let gone = src.path().join("gone.prt"); + let (files, skipped) = split_dropped(&[b.clone(), folder, a.clone(), gone, b.clone()]); + assert_eq!(files, [b, a], "in order, each once"); + assert_eq!(skipped, 2); + assert_eq!(split_dropped(&[]), (Vec::new(), 0)); } #[test] diff --git a/desktop/src/commands.rs b/desktop/src/commands.rs index 1544bf02..e41ba085 100755 --- a/desktop/src/commands.rs +++ b/desktop/src/commands.rs @@ -1665,6 +1665,12 @@ pub async fn new_item_copy( let disk = src.file_name().and_then(|n| n.to_str()).ok_or_else(|| { ApiError::local(format!("{} has no usable file name.", src.display())) })?; + // picked or dropped from the file manager (#418): regular files only + if !addfiles::is_regular_file(&src) { + return Err(ApiError::local(format!( + "{disk} is not a file – nothing was copied." + ))); + } let rel = layout::local_rel(Some(group), &folder, &layout::nfc(disk)); let dst = layout::join_rel(&root, &rel); if dst == src { @@ -2521,6 +2527,26 @@ pub async fn pick_files(app: AppHandle) -> CmdResult> { .map_err(|e| ApiError::local(format!("The file dialog failed: {e}"))) } +/// Files dropped on the window from the file manager (#418): the regular +/// files among the dropped paths and how many entries (folders, anything +/// that is not a regular file) were left out. The paths then take the same +/// way as picked ones – *New* or *Add files…* with all their checks. +#[derive(Serialize)] +pub struct DroppedFiles { + pub files: Vec, + pub skipped: usize, +} + +#[tauri::command] +pub async fn dropped_files(paths: Vec) -> CmdResult { + tokio::task::spawn_blocking(move || { + let (files, skipped) = addfiles::split_dropped(&paths); + DroppedFiles { files, skipped } + }) + .await + .map_err(|e| ApiError::local(format!("The dropped files could not be read: {e}"))) +} + /// *Add files…*: what copying `paths` into the working folder would do /// (which names become new versions or replace a local file). #[tauri::command] diff --git a/desktop/src/main.rs b/desktop/src/main.rs index a8d76052..d5a6ac87 100755 --- a/desktop/src/main.rs +++ b/desktop/src/main.rs @@ -276,6 +276,7 @@ fn main() { commands::workspace_park, commands::workspace_local_changes, commands::pick_files, + commands::dropped_files, commands::workspace_add_plan, commands::workspace_add_files, commands::workspace_open, diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.json index f9df69fa..321770c9 100755 --- a/desktop/tauri.conf.json +++ b/desktop/tauri.conf.json @@ -17,7 +17,7 @@ "minWidth": 980, "minHeight": 620, "center": true, - "dragDropEnabled": false + "dragDropEnabled": true } ], "security": { diff --git a/desktop/ui/app.css b/desktop/ui/app.css index 6a062914..fd91f83a 100755 --- a/desktop/ui/app.css +++ b/desktop/ui/app.css @@ -975,6 +975,30 @@ canvas.viewer-measuring { cursor: crosshair; } .toast.info { box-shadow: inset 3px 0 0 var(--link), var(--shadow-pop); } .toast.info::before { content: "i"; color: var(--link); } +/* Files dragged from the file manager over the window (#418, js/drop.js): + a dashed frame over the whole window with what the drop does; a refusal + (viewer, frozen revision, checked out by someone else) in the danger colour. + The overlay never takes pointer events – the native drop reports to Tauri. */ +.drop-overlay { + position: fixed; inset: 8px; z-index: 55; + display: none; place-items: center; padding: 24px; + pointer-events: none; + background: var(--backdrop); + border: 2px dashed var(--accent); + border-radius: var(--radius-lg); +} +body.drop-target .drop-overlay { display: grid; } +.drop-overlay-text { + margin: 0; max-width: 520px; padding: 12px 16px; + color: var(--text); text-align: center; + background: var(--surface); + border: 1px solid var(--border-strong); + border-radius: var(--radius); + box-shadow: inset 3px 0 0 var(--accent), var(--shadow-pop); +} +body.drop-refused .drop-overlay { border-color: var(--st-danger-fg); } +body.drop-refused .drop-overlay-text { box-shadow: inset 3px 0 0 var(--st-danger-fg), var(--shadow-pop); } + @media (prefers-reduced-motion: reduce) { /* fades stay, movement goes */ .dialog, .toast, .toast.leaving { transform: none; } diff --git a/desktop/ui/js/drop-rules.js b/desktop/ui/js/drop-rules.js new file mode 100644 index 00000000..aa453c64 --- /dev/null +++ b/desktop/ui/js/drop-rules.js @@ -0,0 +1,69 @@ +// SPDX-License-Identifier: MPL-2.0 +// TeamCraft Desktop – pure rules of a file drop (#418): where files dropped +// on the window from the file manager go. +// No imports and no DOM: scripts/desktop-drop-route.test.mjs tests it with +// plain Node.js. js/drop.js listens for the drop and applies the result. + +/** The refusal for viewers and editors without a project group to create items in. */ +export var NO_CREATE_TEXT = "Only editors of a project group can create items – ask an admin or a group manager for edit rights."; + +/** The refusal while a dialog is open (the drop would land behind it). */ +export var DIALOG_OPEN_TEXT = "Finish or close the open dialog first, then drop the files again."; + +/** The refusal while a revision tab is still loading. */ +export var LOADING_TEXT = "The revision is still loading – drop the files again in a moment."; + +/** + * Where a drop of `paths` goes: + * + * * `{ kind: "add", tab, paths }` – the active tab is a revision whose + * *Add files…* works (`hint.ok`: checked out by the user, or free for the + * user to check out – Add files… does that first); + * * `{ kind: "refuse", text }` – the active tab is a revision that takes no + * files (released, in review, checked out by someone else, the user is not + * an editor of its group: the hint's text says which), a dialog is open, or + * the user may not create items anywhere; + * * `{ kind: "new", paths }` – everything else: *New* with the files; + * * `null` – nothing was dropped. + * + * `o.tab` is the active tab (null on the start page), `o.hint` is + * workspace.js filesHint() of a loaded revision tab (`{ ok, text }`), + * `o.canCreate` = the user may create items in at least one active group, + * `o.dialogOpen` = a dialog is open. + */ +export function routeDrop(o) { + var paths = (o && o.paths || []).filter(function (p) { return typeof p === "string" && p !== ""; }); + if (!paths.length) return null; + if (o.dialogOpen) return { kind: "refuse", text: DIALOG_OPEN_TEXT }; + var tab = o.tab || null; + if (tab && tab.kind === "revision") { + if (!tab.data || !tab.data.rev) return { kind: "refuse", text: LOADING_TEXT }; + var hint = o.hint || { ok: false, text: "Files cannot be added to this revision." }; + return hint.ok ? { kind: "add", tab: tab, paths: paths } : { kind: "refuse", text: hint.text }; + } + if (!o.canCreate) return { kind: "refuse", text: NO_CREATE_TEXT }; + return { kind: "new", paths: paths }; +} + +/** + * The line on the drop overlay while files are dragged over the window. + * It names no count: the dragged paths may hold folders, which the drop + * leaves out (src/commands.rs dropped_files) – skippedText() reports them. + */ +export function dropLabel(route) { + if (!route) return ""; + if (route.kind === "refuse") return route.text; + var t = "the dropped files"; + if (route.kind === "add") { + var rev = route.tab.data.rev; + return "Drop to add " + t + " to " + rev.item_number + "/" + rev.code; + } + return "Drop to create a new item with " + t; +} + +/** The note after folders or other entries were left out of a drop. */ +export function skippedText(skipped) { + if (!skipped) return ""; + return skipped === 1 ? "1 folder or other entry was skipped – only files are taken." : + skipped + " folders or other entries were skipped – only files are taken."; +} diff --git a/desktop/ui/js/drop.js b/desktop/ui/js/drop.js new file mode 100644 index 00000000..b658c2a4 --- /dev/null +++ b/desktop/ui/js/drop.js @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: MPL-2.0 +// TeamCraft Desktop – files dropped on the window from the file manager +// (#418). Tauri's native file drop (dragDropEnabled in tauri.conf.json) +// reports the absolute paths; js/drop-rules.js decides where they go: +// *New* with the files, *Add files…* of the open revision, or a refusal. +// The paths then take the same way as files chosen in the file dialog, with +// the same checks; src/commands.rs dropped_files keeps regular files only. +// +// The tabs are reordered with pointer events (tabs.js), not HTML5 drag and +// drop, so the native drop does not get in their way. + +import { $, TAURI, call, errorText, h, state, toast } from "./core.js"; +import { canEdit, canEditProject } from "./shell.js"; +import { activeTab } from "./tabs.js"; +import { addFilesDialog, filesHint } from "./workspace.js"; +import { newItemDialog } from "./dialogs.js"; +import { dropLabel, routeDrop, skippedText } from "./drop-rules.js"; + +var overlay = null, overlayText = null, dragged = []; + +/** May the user create items in at least one active project group? */ +function canCreate() { + return !!canEdit() && state.projects.some(function (p) { return p.active && canEditProject(p.id); }); +} + +/** Signed in with the main window showing (not the connect screen). */ +function shellShown() { + var shell = $("shell"); + return !!state.me && !!shell && !shell.classList.contains("hidden"); +} + +/** The route of `paths` for what is on screen now. */ +function route(paths) { + var tab = activeTab() || null; + var hint = null; + if (tab && tab.kind === "revision" && tab.data && tab.data.rev) { + try { hint = filesHint(tab.data); } catch (e) { hint = null; } + } + var root = $("dialog-root"); + return routeDrop({ paths: paths, tab: tab, hint: hint, canCreate: canCreate(), dialogOpen: !!(root && root.children.length) }); +} + +function showOverlay(r) { + if (!overlay) { + overlayText = h("p.drop-overlay-text"); + overlay = h("div.drop-overlay", { "aria-hidden": "true" }, overlayText); + document.body.appendChild(overlay); + } + overlayText.textContent = dropLabel(r); + document.body.classList.add("drop-target"); + document.body.classList.toggle("drop-refused", !!r && r.kind === "refuse"); +} + +function hideOverlay() { + document.body.classList.remove("drop-target", "drop-refused"); +} + +/** Shows the overlay for the dragged paths, or hides it when nothing droppable is dragged (text, a URL). */ +function updateOverlay() { + var r = dragged.length ? route(dragged) : null; + if (r) showOverlay(r); else hideOverlay(); +} + +/** Applies a drop: regular files only, then *New*, *Add files…* or the refusal. */ +function onDrop(paths) { + var first = route(paths); + if (!first) return; + if (first.kind === "refuse") { toast(first.text, "error"); return; } + call("dropped_files", { paths: first.paths }).then(function (d) { + var note = skippedText(d.skipped); + if (!d.files.length) { toast(note || "Nothing to add – only files can be dropped.", "error"); return; } + if (note) toast(note, "info"); + // the files may have changed the route (e.g. only folders): decide again + var r = route(d.files); + if (!r) return; + if (r.kind === "refuse") toast(r.text, "error"); + else if (r.kind === "add") addFilesDialog(r.tab, r.paths); + else newItemDialog({ paths: r.paths }); + }, function (e) { toast(errorText(e), "error"); }); +} + +/** Listens for the native file drop of the main window. */ +export function initDrop() { + var webview = TAURI.webview && TAURI.webview.getCurrentWebview ? TAURI.webview.getCurrentWebview() : null; + if (!webview || !webview.onDragDropEvent) return; + webview.onDragDropEvent(function (e) { + var p = e.payload || {}; + if (!shellShown()) { hideOverlay(); dragged = []; return; } + if (p.type === "enter") { + dragged = p.paths || []; + updateOverlay(); + } else if (p.type === "over") { + updateOverlay(); + } else if (p.type === "drop") { + hideOverlay(); + dragged = []; + onDrop(p.paths || []); + } else { + hideOverlay(); + dragged = []; + } + }).catch(function () {}); +} diff --git a/desktop/ui/js/main.js b/desktop/ui/js/main.js index 7b695e79..41a470bd 100755 --- a/desktop/ui/js/main.js +++ b/desktop/ui/js/main.js @@ -9,7 +9,7 @@ // Every server call goes through the Rust commands (src/commands.rs); data // from the server is only ever inserted as text, never as HTML. // -// Modules: core.js, skins.js, connect.js, shell.js, navigator.js, tabs.js, assistant.js, agent.js, revision.js, references.js, workspace.js, change.js, requests.js, dialogs.js, bom-import.js, bom-lines.js, group-sync.js, folder-import.js, settings.js, onboarding-rules.js, onboarding.js, crash.js, main.js. +// Modules: core.js, skins.js, connect.js, shell.js, navigator.js, tabs.js, assistant.js, agent.js, revision.js, references.js, workspace.js, change.js, requests.js, dialogs.js, bom-import.js, bom-lines.js, group-sync.js, folder-import.js, settings.js, onboarding-rules.js, onboarding.js, crash.js, drop.js, main.js. import { $, TAURI, call, errorText, h, invoke, setStatus, state, toast } from "./core.js"; import { applySkin } from "./skins.js"; @@ -29,6 +29,7 @@ import { reportDialog } from "./report.js"; import { checkCrashReports, initCrashWatch } from "./crash.js"; import { onSolidcraftRequest } from "./solidcraft-bridge.js"; import { initItemMenu } from "./item-menu.js"; +import { initDrop } from "./drop.js"; import { openOnboarding } from "./onboarding.js"; // ====================================================================== @@ -133,6 +134,7 @@ export function boot() { initConnect(); initShell(); initItemMenu(); + initDrop(); initZoom(); TAURI.event.listen("menu", function (e) { handleMenu(e.payload); }); // large files are sent in resumable chunks: show how far they are diff --git a/desktop/ui/js/workspace.js b/desktop/ui/js/workspace.js index ac0db3b3..08ba88e3 100755 --- a/desktop/ui/js/workspace.js +++ b/desktop/ui/js/workspace.js @@ -969,13 +969,16 @@ export function filesHint(d) { /** "Add files…": pick files, copy them into the working folder of the * revision (checking it out first if needed), optionally check in now. - * The originals stay where they are; a name that exists asks first. */ -export function addFilesDialog(tab) { + * The originals stay where they are; a name that exists asks first. + * `presetPaths`: files dropped on the window (#418, js/drop.js) – used + * instead of the file dialog, with the same checks. */ +export function addFilesDialog(tab, presetPaths) { var rev = tab.data.rev, hint = filesHint(tab.data); if (!hint.ok) { toast(hint.text, "error"); return; } var mine = rev.checked_out_by === state.me.id; var where = { project: rev.project_code, item: rev.item_number, code: rev.code }; - call("pick_files").then(function (paths) { + var chosen = presetPaths && presetPaths.length ? Promise.resolve(presetPaths.slice()) : call("pick_files"); + chosen.then(function (paths) { if (!paths.length) return; var subfolder = h("input", { type: "text", placeholder: "revision's main folder", spellcheck: "false" }); var checkNow = h("input", { type: "checkbox" }); diff --git a/docs/src/dev/threat-model.md b/docs/src/dev/threat-model.md index 2e751acf..dcd84670 100755 --- a/docs/src/dev/threat-model.md +++ b/docs/src/dev/threat-model.md @@ -179,6 +179,7 @@ enial of service, **E**levation of privilege. | Update download replaced or corrupted | T | *Update now* (#377) downloads only asset addresses of `github.com/WARR-eV/TeamCraft/releases/download/v/` from the release JSON (others are dropped), follows redirects over https only, stops at 1 GiB, and accepts the file only when its SHA-256 equals its one line in the same release's `SHA256SUMS.txt` – otherwise it is deleted; only the file verified last can be started (`update_install` takes no path from the web view), and an installer starts only after the user confirms | `desktop/src/update.rs` `checksums`, `release_assets_come_from_this_repository_only`, `the_asset_fits_the_install` | partly mitigated: the checksum list comes from the same release, so it proves integrity, not origin – until releases are signed (#377) | | Desktop policies abused or leaked | T / I | the policies (#378) are only read, once at start, and never sent; machine-wide sources (`HKLM`, the computer's managed preferences, `/etc/teamcraft/policies.json`) need administrator rights to change, and a machine value wins over the user's; every value is checked (an `http(s)` address normalised like a typed one, an absolute folder, one line of at most 64 characters) and anything else counts as not set; a fixed server is enforced in the app's commands (`set_server`, `switch_connection`, `local_server_start`), not only in the UI | `desktop/src/policy.rs` `wrong_types_and_ranges_count_as_not_set`, `the_registry_answer_is_read`, `the_computer_wins_value_by_value`, `a_fixed_server_refuses_others_unless_allowed` | mitigated; a user-level policy (`HKCU`, the user's profile) is only as strong as the user's own rights | | Update notice abused | T / I | the daily release check (opt-out) asks only `api.github.com` for the latest release, without redirects and with a 10 s timeout; a version from the answer is used only if it is a plain `x.y.z`; the notice opens a fixed release page – the app downloads and installs nothing. GitHub sees the address and app version once a day (`desktop/src/update.rs`) | `desktop/src/update.rs` `newer_versions`, `tags`, `at_most_daily` | mitigated | +| Dropped paths read the wrong things (#418) | T / I | the desktop app accepts absolute paths from the operating system's file drop (Tauri's native drag-drop event of the main window, no HTML5 drag and drop) – files the user dragged there, like files chosen in the file dialog; they take the same way as picked files with the same checks (duplicates, a name in another folder, copied – never moved – into the item's folder, nothing overwritten without a confirmation); only regular files are taken: `dropped_files` leaves folders and other entries out, `addfiles::plan`, `new_item_places` and `new_item_copy` refuse anything else; the drop only opens *New item* or *Add files…*, nothing is copied or uploaded before the user confirms the dialog | `desktop/src/addfiles.rs` `dropped_paths_keep_regular_files_only`, `refusals`; `scripts/desktop-drop-route.test.mjs` | mitigated | | Server writes outside the working folder | T | every server-supplied name goes through `safe_name` / `normalize_folder` (no `..`, no separators, reserved Windows names) before `join_rel` (`desktop/src/layout.rs` `local_rel`) | `desktop/src/layout.rs` `names`, `folders_like_the_server`, `layout_mapping` | mitigated | | Problem report leaks data | I | *Report a problem* (#381) shows the whole report for review and sends nothing by itself: the text is redacted in Rust (`crash::redact`: home folder, URLs, `tc_pat_`/`tc_sess_` tokens) before the dialog shows it, inputs are names and short values only (no file contents, no item data; a path is cut to its file name, at most 12 values of 200 characters, `ui/js/report-inputs.js`), the session log is the app's own error messages and only when ticked; the issue form address is GitHub's or an http(s) address the user set, with the text as query parameters (cut to 7000 characters) | `desktop/src/report.rs` `the_title_is_cut_at_a_word_and_redacted`, `the_body_names_action_inputs_error_versions_and_drops_an_unanswered_question`, `the_log_is_redacted_and_capped`, `the_form_address_fits_and_says_when_it_was_cut`; `scripts/desktop-report-inputs.test.mjs` | mitigated; what the user types into the report is sent as typed | | Forged request id in logs and error pages | T / R | every answer gets an `x-request-id` (#381); an incoming one is kept only when it is 1–64 characters of `[A-Za-z0-9-]` (no spaces, line breaks or markup that could forge a log line or break a header or the error page), otherwise a new UUID replaces it; the id is a correlation hint, never a credential, and the error page escapes it like any other text | `src/lib.rs` `only_short_plain_request_ids_are_taken_over`, `every_response_carries_the_request_id`; `tests/request_id.rs` | mitigated; a client can still choose a plain id of its own, so ids from outside are not unique | diff --git a/docs/src/guide/desktop.md b/docs/src/guide/desktop.md index 3c490131..f42ff6bc 100755 --- a/docs/src/guide/desktop.md +++ b/docs/src/guide/desktop.md @@ -643,8 +643,26 @@ files in *Check in…* – also files with an unrelated name, which TeamCraft remembers in `.teamcraft/added.json` until they are checked in – or tick *Check in now*. The Files section explains why the button is disabled: checked out by someone else (add after check-in), in review, or released (frozen: *Revise* and add the files to the new -revision). Dropping files -onto the window is not supported yet. +revision). + +**Drop files.** Drag CAD files from Explorer, Finder or your file manager +onto the window. A frame shows what the drop does before you let go: + +* on an open revision tab that you have checked out, or that *Add files…* + would check out for you, the files go into *Add files…* (with the same + dialog, sub-folder and confirmations as picked files); +* anywhere else (the start page, a change, a request) the drop opens + *New item* with the files already chosen – name, type, group and folder + follow from them like from picked files, and the duplicate check runs; +* a revision that takes no files (released, in review, checked out by + someone else) refuses the drop with the same reason the Files section + gives, and so does the app for viewers and for editors without a project + group to create items in. While a dialog is open, close it first. + +Only files are taken: dropped folders are skipped, with a note. The files +are copied, never moved, and nothing in the working folder is overwritten +without asking – a drop has exactly the checks of the file dialog. Tabs are +still reordered by dragging them. **Get.** *Get…* on a revision resolves its structure on the server – the multi-level BOM with the revision rule you choose (*latest*: the newest diff --git a/scripts/desktop-drop-route.test.mjs b/scripts/desktop-drop-route.test.mjs new file mode 100644 index 00000000..affc49ea --- /dev/null +++ b/scripts/desktop-drop-route.test.mjs @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: MPL-2.0 +// Unit tests of desktop/ui/js/drop-rules.js (where files dropped on the +// window from the file manager go – #418). +// Plain Node.js, no packages; run by the CI job `ui`: +// +// node scripts/desktop-drop-route.test.mjs +// +// The module sits in a folder without package.json, so it is imported as a +// data: URL module instead of by path. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const file = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../desktop/ui/js/drop-rules.js"); +const src = fs.readFileSync(file, "utf8"); +const { DIALOG_OPEN_TEXT, LOADING_TEXT, NO_CREATE_TEXT, dropLabel, routeDrop, skippedText } = await import( + "data:text/javascript;base64," + Buffer.from(src).toString("base64")); + +let n = 0; +function test(name, fn) { fn(); n++; console.log("ok - " + name); } + +const paths = ["/home/a/cad/bracket.ipt", "/home/a/cad/bracket.step"]; +function revTab(rev) { + return { key: "rev:PRT-000042:A", kind: "revision", data: { rev: { item_number: "PRT-000042", code: "A", ...rev } } }; +} +const editable = { ok: true, text: "Add files… copies files into your workspace; or edit the files there, then check in." }; +const lockedHint = { ok: false, text: "Checked out by Ada since 1 May – files can be added after check-in." }; +const releasedHint = { ok: false, text: "Released revisions are frozen – Revise to add files to a new revision." }; +const reviewHint = { ok: false, text: "PRT-000042/A is in review and frozen – files can be added once the change is decided, or to a new revision." }; +const viewerHint = { ok: false, text: "Only editors of the project group can add files." }; + +test("an empty drop does nothing", () => { + assert.equal(routeDrop({ paths: [], tab: null, canCreate: true }), null); + assert.equal(routeDrop({ tab: null, canCreate: true }), null); + assert.equal(routeDrop({ paths: ["", null], tab: null, canCreate: true }), null); + assert.equal(routeDrop(null), null); + assert.equal(dropLabel(null), ""); +}); + +test("no tab: New with the files", () => { + const r = routeDrop({ paths, tab: null, canCreate: true }); + assert.deepEqual(r, { kind: "new", paths }); + assert.equal(dropLabel(r), "Drop to create a new item with the dropped files"); + assert.equal(dropLabel(routeDrop({ paths: [paths[0]], tab: null, canCreate: true })), "Drop to create a new item with the dropped files"); +}); + +test("a change or other tab: New with the files", () => { + const r = routeDrop({ paths, tab: { kind: "change", data: {} }, canCreate: true }); + assert.equal(r.kind, "new"); +}); + +test("a revision checked out by me: Add files…", () => { + const tab = revTab({ state: "in_work", checked_out_by: "me" }); + const r = routeDrop({ paths, tab, hint: editable, canCreate: true }); + assert.equal(r.kind, "add"); + assert.equal(r.tab, tab); + assert.deepEqual(r.paths, paths); + assert.equal(dropLabel(r), "Drop to add the dropped files to PRT-000042/A"); +}); + +test("a free revision Add files… would check out: Add files…", () => { + const hint = { ok: true, text: "To add or replace files, check out this revision – Add files… does that for you." }; + assert.equal(routeDrop({ paths, tab: revTab({ state: "in_work" }), hint, canCreate: true }).kind, "add"); +}); + +test("a revision checked out by someone else is refused with the reason", () => { + const r = routeDrop({ paths, tab: revTab({ state: "in_work", checked_out_by: "ada" }), hint: lockedHint, canCreate: true }); + assert.deepEqual(r, { kind: "refuse", text: lockedHint.text }); + assert.equal(dropLabel(r), lockedHint.text); +}); + +test("a released revision is refused, not turned into New", () => { + const r = routeDrop({ paths, tab: revTab({ state: "released" }), hint: releasedHint, canCreate: true }); + assert.deepEqual(r, { kind: "refuse", text: releasedHint.text }); +}); + +test("a revision in review is refused", () => { + const r = routeDrop({ paths, tab: revTab({ state: "in_review" }), hint: reviewHint, canCreate: true }); + assert.equal(r.kind, "refuse"); + assert.match(r.text, /in review/); +}); + +test("a revision without a hint is refused, never added", () => { + const r = routeDrop({ paths, tab: revTab({ state: "in_work" }), canCreate: true }); + assert.equal(r.kind, "refuse"); +}); + +test("a revision still loading is refused", () => { + const r = routeDrop({ paths, tab: { kind: "revision", data: null }, canCreate: true }); + assert.deepEqual(r, { kind: "refuse", text: LOADING_TEXT }); +}); + +test("a viewer is refused: New and on a revision", () => { + assert.deepEqual(routeDrop({ paths, tab: null, canCreate: false }), { kind: "refuse", text: NO_CREATE_TEXT }); + const r = routeDrop({ paths, tab: revTab({ state: "in_work" }), hint: viewerHint, canCreate: false }); + assert.deepEqual(r, { kind: "refuse", text: viewerHint.text }); +}); + +test("an open dialog refuses the drop", () => { + const r = routeDrop({ paths, tab: null, canCreate: true, dialogOpen: true }); + assert.deepEqual(r, { kind: "refuse", text: DIALOG_OPEN_TEXT }); +}); + +test("skipped folders are named", () => { + assert.equal(skippedText(0), ""); + assert.match(skippedText(1), /^1 folder/); + assert.match(skippedText(3), /^3 folders/); +}); + +console.log(`${n} tests passed`);