Native iCloud apps for Windows and Linux, built in Rust. Notes, Reminders, Calendar, Contacts, Drive and Photos, offline and in sync with your iPhone.
Rust apple-notesapple-reminderscloudkitcrdtdesktop-appicloudicloud-calendaricloud-driveicloud-notesicloud-photosiphonelinuxlinux-desktoplocal-firstoffline-firstprivacyrusttauritauri-appwindows
Drive: Copy and Paste across folders, as Finder
Yashwanth Kamireddicc967ce64d0d
diff --git a/.uiverify/drive-copy-name.test.mjs b/.uiverify/drive-copy-name.test.mjsnew file mode 100644index 0000000..033fd39--- /dev/null+++ b/.uiverify/drive-copy-name.test.mjs@@ -0,0 +1,24 @@+// The name a pasted copy shows under while it is made: Finder's, the same rule as the backend's+// copy_name (crates/quince-icloud/src/drive.rs), which names the real one.+import { test } from "node:test";+import assert from "node:assert/strict";+import { copyName } from "../src/lib/clipboard.ts";++test("its own name where that is free", () => {+ assert.equal(copyName("Report", "pdf", []), "Report.pdf");+ assert.equal(copyName("Trip", null, ["Report.pdf"]), "Trip");+});++test("then “copy”, then “copy 2”, whatever the case of what is there", () => {+ assert.equal(copyName("Report", "pdf", ["Report.pdf"]), "Report copy.pdf");+ assert.equal(copyName("Report", "pdf", ["report.PDF", "Report copy.pdf"]), "Report copy 2.pdf");+ assert.equal(copyName("Report", "pdf", ["Report.pdf", "Report copy.pdf", "Report copy 2.pdf"]), "Report copy 3.pdf");+ assert.equal(copyName("Trip", null, ["Trip"]), "Trip copy");+});++test("a copy of a copy counts on, never “copy copy”", () => {+ assert.equal(copyName("Report copy", "pdf", ["Report copy.pdf"]), "Report copy 2.pdf");+ assert.equal(copyName("Report copy 2", "pdf", ["Report copy.pdf", "Report copy 2.pdf"]), "Report copy 3.pdf");+ assert.equal(copyName("copy", "txt", ["copy.txt"]), "copy copy.txt");+ assert.equal(copyName("Hard copy 2b", null, ["Hard copy 2b"]), "Hard copy 2b copy");+});diff --git a/.uiverify/drive-paste.mjs b/.uiverify/drive-paste.mjsnew file mode 100644index 0000000..a596081--- /dev/null+++ b/.uiverify/drive-paste.mjs@@ -0,0 +1,156 @@+// Copy and Paste in Drive, as Finder: Ctrl-C on what is chosen, Ctrl-V in another folder makes+// copies there — shown at once under the name Finder gives a copy, gone again with the reason if+// Apple refuses; Ctrl-Alt-V moves instead. Files copied in the desktop's file manager paste as an+// upload. The menus have Copy, and a right-click on nothing has Paste.+import { engine } from "./engine.mjs";+import { SERVICES, installStub } from "./stub.mjs";+const b = await engine.launch();+const ctx = await b.newContext({ viewport: { width: 1280, height: 800 } });+await ctx.addInitScript(installStub, { screen: "library", services: SERVICES, twoFactor: null, driveFixture: true });+await ctx.addInitScript(() => {+ const ROOT = "FOLDER::com.apple.CloudDocs::root";+ const item = (id, name, kind, extension = null, parentId = ROOT) => ({+ drivewsid: `${kind === "APP_LIBRARY" ? "APPLIBRARY::com.apple.Keynote" : `${kind}::com.apple.CloudDocs`}::${id}`,+ parentId, name, extension, kind, size: kind === "FILE" ? 2048 : null, childCount: null,+ createdAt: 1787000000, modifiedAt: 1788600000, etag: "e",+ });+ window.__driveIn = {+ [ROOT]: [+ item("dl", "Downloads", "FOLDER"),+ item("pr", "Projects", "FOLDER"),+ item("plan", "Semester Plan", "FILE", "pdf"),+ item("kn", "Keynote", "APP_LIBRARY"),+ ],+ "FOLDER::com.apple.CloudDocs::dl": [],+ "FOLDER::com.apple.CloudDocs::pr": [],+ };+});+const page = await ctx.newPage();+await page.goto(process.env.BASE ?? process.env.URL ?? "http://localhost:4173", { waitUntil: "networkidle" });+await page.locator(".nav-item", { hasText: "Drive" }).click();+await page.locator("button.drive-row-hit", { hasText: "Semester Plan" }).waitFor();+let failures = 0;+const ok = (pass, what) => { console.log(`${pass ? "PASS" : "FAIL"} ${what}`); if (!pass) failures++; };+const PLAN = "FILE::com.apple.CloudDocs::plan";+const DL = "FOLDER::com.apple.CloudDocs::dl";+const PR = "FOLDER::com.apple.CloudDocs::pr";+const row = (name) => page.locator("button.drive-row-hit", { hasText: name }).first();+const names = () => page.locator(".drive-rows .drive-name").allInnerTexts();+const standIn = (name) => page.locator(".drive-rows li.is-busy", { hasText: name });+const copies = () => page.evaluate(() => window.__driveCopies ?? []);+const inFolder = (name) => page.waitForFunction((n) => [...document.querySelectorAll(".pane-head h1, .drive-title")].some((h) => h.textContent.includes(n)), name, { timeout: 5000 });+const errorShown = (text) => page.locator(".toast.is-error", { hasText: text }).waitFor({ timeout: 3000 }).then(() => true, () => false);+const dismissErrors = async () => {+ for (const close of await page.locator(".toast.is-error button").all()) await close.click().catch(() => {});+};+const open = async (name) => {+ await row(name).dblclick();+ await inFolder(name);+ await page.waitForTimeout(100);+};+const up = async () => {+ await page.locator(".drive-rows").click({ position: { x: 5, y: 5 } }).catch(() => {});+ await page.keyboard.press("Control+ArrowUp");+ await row("Semester Plan").waitFor();+};++// Copy in one folder, paste in another: the copy shows at once, under its own name.+await row("Semester Plan").click();+await page.keyboard.press("Control+c");+await open("Downloads");+await page.evaluate(() => { window.__driveCopyDelay = 500; });+const pressed = Date.now();+await page.keyboard.press("Control+v");+await standIn("Semester Plan.pdf").waitFor({ timeout: 1000 });+ok(Date.now() - pressed < 450, `the copy shows before Apple answers ${Date.now() - pressed}ms`);+ok((await standIn("Semester Plan.pdf").innerText()).includes("Copying"), "and says it is being copied");+await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });+const first = (await copies()).at(-1);+ok(first?.drivewsid === PLAN && first?.destinationId === DL, `Apple is asked to copy it here ${JSON.stringify(first)}`);+ok((await names()).includes("Semester Plan.pdf"), "the copy is in the folder once Apple has it");++// Pasted again where its name is taken: "Semester Plan copy.pdf", then "copy 2".+await page.evaluate(() => { window.__driveCopyName = "Semester Plan copy"; });+await page.keyboard.press("Control+v");+await standIn("Semester Plan copy.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a second paste is named “Semester Plan copy.pdf”"), () => ok(false, "a second paste is named “Semester Plan copy.pdf”"));+await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });+await page.evaluate(() => { window.__driveCopyName = "Semester Plan copy 2"; });+await page.keyboard.press("Control+v");+await standIn("Semester Plan copy 2.pdf").waitFor({ timeout: 1000 }).then(() => ok(true, "a third, “Semester Plan copy 2.pdf”"), () => ok(false, "a third, “Semester Plan copy 2.pdf”"));+await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });+ok((await copies()).length === 3, "each paste is one copy");++// Refused: the row that showed goes again, and the reason is said.+await page.evaluate(() => { window.__driveCopyFail = "iCloud Drive turned this down."; window.__driveCopyName = "Semester Plan copy 3"; });+await page.keyboard.press("Control+v");+await standIn("Semester Plan copy 3.pdf").waitFor({ timeout: 1000 }).catch(() => {});+ok(await errorShown("turned this down"), "a copy Apple refuses says why");+ok(!(await names()).includes("Semester Plan copy 3.pdf"), "and its row is gone again");+await page.evaluate(() => { window.__driveCopyFail = null; window.__driveCopyDelay = 0; });+await dismissErrors();++// Files copied in the file manager paste as an upload into the folder open.+await page.evaluate(() => { window.__clipFiles = ["/home/alex/Pictures/Lake.jpg", "/home/alex/Notes.txt"]; });+await page.keyboard.press("Control+v");+await page.waitForFunction(() => (window.__driveUploads ?? []).length === 1, null, { timeout: 3000 }).catch(() => {});+const sent = await page.evaluate(() => window.__driveUploads?.[0]);+ok(sent?.folderId === DL && sent?.paths?.length === 2, `the file manager's files go up into this folder ${JSON.stringify(sent)}`);+ok((await copies()).length === 4, "and nothing of Drive's is copied for them");+await page.evaluate(() => { window.__clipFiles = []; });++// Ctrl-Alt-V moves what was copied here instead: gone from where it was, shown here at once.+await up();+await row("Semester Plan").click();+await page.keyboard.press("Control+c");+await open("Projects");+await page.keyboard.press("Control+Alt+v");+await standIn("Semester Plan.pdf").waitFor({ timeout: 400 }).then(() => ok(true, "Ctrl-Alt-V shows it here at once"), () => ok(false, "Ctrl-Alt-V shows it here at once"));+ok((await standIn("Semester Plan.pdf").innerText().catch(() => "")).includes("Moving"), "as being moved");+await page.waitForFunction(() => (window.__moves ?? []).length === 1, null, { timeout: 3000 }).catch(() => {});+const moved = await page.evaluate(() => window.__moves?.[0]);+ok(moved?.drivewsid === PLAN && moved?.destinationId === PR, `Apple is asked to move it here ${JSON.stringify(moved)}`);+ok((await copies()).length === 4, "and nothing is copied");+await page.waitForFunction(() => !document.querySelector(".drive-rows li.is-busy"), null, { timeout: 4000 });+await page.keyboard.press("Control+ArrowUp");+await row("Downloads").waitFor();+await page.waitForTimeout(150);+ok(!(await names()).includes("Semester Plan.pdf"), "and it has left the folder it was in");+// Moved, it is not on the clipboard to paste again.+await open("Downloads");+await page.keyboard.press("Control+Alt+v");+await page.waitForTimeout(300);+ok((await page.evaluate(() => (window.__moves ?? []).length)) === 1, "a move pastes once");+await up().catch(() => {});++// A folder is never pasted into itself.+await page.locator("button.drive-row-hit", { hasText: "Downloads" }).waitFor();+await row("Downloads").click();+await page.keyboard.press("Control+c");+await open("Downloads");+await page.keyboard.press("Control+v");+ok(await errorShown("inside itself"), "a folder pasted into itself is refused, as Finder refuses it");+ok((await copies()).length === 4, "and nothing is asked of Apple");+await dismissErrors();+await page.keyboard.press("Control+ArrowUp");+await row("Projects").waitFor();++// The menus: Copy on an item (not on an app's library), Paste on a right-click on nothing.+await row("Keynote").click({ button: "right" });+ok(!(await page.locator(".row-menu [role='menuitem']", { hasText: /^Copy$/ }).count()), "an app's library has no Copy");+await page.keyboard.press("Escape");+await row("Projects").click({ button: "right" });+await page.locator(".row-menu [role='menuitem']", { hasText: /^Copy$/ }).click();+await page.evaluate(() => { window.__driveCopyDelay = 600; window.__driveCopyName = "Projects copy"; });+const box = await page.locator(".drive-rows").boundingBox();+await page.mouse.click(box.x + box.width / 2, Math.min(780, box.y + box.height + 60), { button: "right" });+const paste = page.locator(".row-menu [role='menuitem']", { hasText: /^Paste$/ });+await paste.waitFor({ timeout: 2000 }).catch(() => {});+ok((await paste.count()) === 1, "a right-click on nothing offers Paste");+await paste.click().catch(() => {});+await page.waitForFunction(() => (window.__driveCopies ?? []).length === 5, null, { timeout: 3000 }).catch(() => {});+const viaMenu = (await copies()).at(-1);+ok(viaMenu?.drivewsid === PR && viaMenu?.destinationId === "FOLDER::com.apple.CloudDocs::root", `Paste from the menu copies the folder here ${JSON.stringify(viaMenu)}`);+await standIn("Projects copy").waitFor({ timeout: 1000 }).then(() => ok(true, "named “Projects copy” beside itself"), () => ok(false, "named “Projects copy” beside itself"));++await b.close();+process.exitCode = failures ? 1 : 0;diff --git a/.uiverify/stub.mjs b/.uiverify/stub.mjsindex 2c8739d..1c16098 100644--- a/.uiverify/stub.mjs+++ b/.uiverify/stub.mjs@@ -980,6 +980,20 @@ export function installStub({ screen, services, twoFactor, calendarFixture, note}case "drive_thumbnails": return driveFixture ? { "FILE::d": "data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='80' height='60'><rect width='80' height='60' fill='%23eee'/></svg>" } : {};case "drive_duplicate": (window.__dups ??= []).push(args.drivewsid); return null;+ // Copy and Paste: each copy asked for, and — where a test keeps folders of its own in+ // __driveIn — the copy landing there under the name __driveCopyName gives it.+ case "drive_copy": {+ (window.__driveCopies ??= []).push(args);+ if (window.__driveCopyDelay) await new Promise((r) => setTimeout(r, window.__driveCopyDelay));+ if (window.__driveCopyFail) throw window.__driveCopyFail;+ const from = [...driveItems, ...Object.values(window.__driveIn ?? {}).flat()].find((i) => i.drivewsid === args.drivewsid);+ const into = window.__driveIn?.[args.destinationId];+ if (from && into) into.push({ ...from, drivewsid: `${from.drivewsid}-copy${window.__driveCopies.length}`, parentId: args.destinationId, name: window.__driveCopyName ?? from.name });+ return null;+ }+ // The desktop's clipboard as the backend reads it: files copied in the file manager, or text.+ case "clipboard_read": return { files: window.__clipFiles ?? [], text: window.__clipText ?? null };+ case "drive_upload": (window.__driveUploads ??= []).push(args); return [];case "storage_info": return { usedBytes: 182196857, totalBytes: 5368709120 };// The local copy's room, as settings.rs measures it; clearing takes away only the cached pictures.case "local_storage": return (window.__local ??= { library: 13_800_000, photos: 4_812_000_000, notes: 456_000_000, drive: 24_000, other: 7_400_000, total: 5_289_224_000, clearable: 4_480_000_000 });@@ -1017,6 +1031,8 @@ export function installStub({ screen, services, twoFactor, calendarFixture, notecase "drive_children":// A slow read, when a test asks for one.if (window.__slowDrive) await new Promise((r) => setTimeout(r, window.__slowDrive));+ // A folder of a test's own, where it keeps one (__driveIn); every folder holds the fixture otherwise.+ if (window.__driveIn?.[args.folderId]) return [...window.__driveIn[args.folderId]];return !driveFixture ? [] : driveItems;case "drive_recents": {if (!driveFixture) return [];diff --git a/src-tauri/src/clipboard.rs b/src-tauri/src/clipboard.rsnew file mode 100644index 0000000..5579e7c--- /dev/null+++ b/src-tauri/src/clipboard.rs@@ -0,0 +1,56 @@+//! What is on the desktop's clipboard, for Drive's Paste: files copied in the file manager+//! (Files, Dolphin, Thunar) are there as a `text/uri-list`, which the window's own clipboard+//! does not hand a page outside an editable field. Read here through GTK, the window's+//! toolkit, which speaks Wayland's clipboard and X11's alike.++use serde::Serialize;++/// The files on the clipboard, as paths on this computer, and its text when it holds no files.+#[derive(Serialize, Default)]+#[serde(rename_all = "camelCase")]+pub struct Clipboard {+ files: Vec<String>,+ text: Option<String>,+}++#[tauri::command]+pub async fn clipboard_read(app: tauri::AppHandle) -> Result<Clipboard, String> {+ #[cfg(target_os = "linux")]+ {+ read(&app).await+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = app;+ Ok(Clipboard::default())+ }+}++/// Asked on the thread GTK lives on, without waiting there: the answer comes back to it.+#[cfg(target_os = "linux")]+async fn read(app: &tauri::AppHandle) -> Result<Clipboard, String> {+ let (tx, rx) = tokio::sync::oneshot::channel();+ app.run_on_main_thread(move || {+ let clipboard = gtk::Clipboard::get(&gdk::SELECTION_CLIPBOARD);+ clipboard.request_uris(move |clipboard, uris| {+ let files: Vec<String> = uris+ .iter()+ .filter_map(|uri| glib::filename_from_uri(uri).ok())+ .map(|(path, _)| path.to_string_lossy().into_owned())+ .collect();+ if files.is_empty() {+ clipboard.request_text(move |_, text| {+ let _ = tx.send(Clipboard {+ files,+ text: text.map(str::to_string),+ });+ });+ } else {+ let _ = tx.send(Clipboard { files, text: None });+ }+ });+ })+ .map_err(|e| e.to_string())?;+ rx.await+ .map_err(|_| "The clipboard couldn’t be read.".to_string())+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex d08293f..3fda7f9 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -15,6 +15,7 @@ macro_rules! quiet {mod alerts;mod appearance;mod apps;+mod clipboard;mod contacts_cmds;mod contacts_merge;mod cpu;@@ -4813,20 +4814,7 @@ async fn drive_duplicate(.map_err(|e| e.to_string())?.ok_or("That item is no longer in the local library.")?};- let (http, drivews, docws, params) = {- let client = auth.client.lock().await;- let session = client.session();- (- client.http().clone(),- session- .service_url("drivews")- .ok_or("Apple hasn't offered iCloud Drive for this account.")?,- session- .service_url("docws")- .ok_or("Apple hasn't offered iCloud Drive for this account.")?,- client.service_params(),- )- };+ let (http, drivews, docws, params) = drive_hosts(&auth).await?;quince_icloud::drive::duplicate(&http, &docws, &drivews, params.clone(), &item).await.map_err(|e| e.to_string())?;@@ -4837,6 +4825,82 @@ async fn drive_duplicate(settle(resync_drive_folder(&http, &drivews, params, &data, parent).await)}+/// Drive's two hosts — `drivews` lists and writes, `docws` copies — and what goes with them.+async fn drive_hosts(+ auth: &State<'_, Auth>,+) -> Result<(reqwest::Client, String, String, Vec<(String, String)>), String> {+ let client = auth.client.lock().await;+ let session = client.session();+ Ok((+ client.http().clone(),+ session+ .service_url("drivews")+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?,+ session+ .service_url("docws")+ .ok_or("Apple hasn't offered iCloud Drive for this account.")?,+ client.service_params(),+ ))+}++/// Copy a file or folder into another folder, as Finder's Copy and Paste: named as Finder+/// names a copy where its name is taken there (quince_icloud::drive::copy_to). A folder is+/// never pasted into itself or into a folder inside it, as Finder will not.+#[tauri::command]+async fn drive_copy(+ drivewsid: String,+ destination_id: String,+ auth: State<'_, Auth>,+ data: State<'_, Data>,+) -> UiResult<()> {+ let item = {+ let library = data.0.lock().await;+ let item = library+ .drive_item(&drivewsid)+ .map_err(|e| e.to_string())?+ .ok_or("That item is no longer in the local library.")?;+ // Up from the destination through the folders the library knows: the folder copied+ // must not be one of them.+ let mut at = Some(destination_id.clone());+ for _ in 0..64 {+ let Some(id) = at.take() else { break };+ if id == item.drivewsid {+ return Err(format!(+ "“{}” can’t be copied into a folder inside itself.",+ item.display_name()+ ));+ }+ at = library+ .drive_item(&id)+ .ok()+ .flatten()+ .and_then(|f| f.parent_id);+ }+ item+ };+ let (http, drivews, docws, params) = drive_hosts(&auth).await?;+ quince_icloud::drive::copy_to(+ &http,+ &docws,+ &drivews,+ params.clone(),+ &item,+ &destination_id,+ )+ .await+ .map_err(|e| e.to_string())?;+ let source = item+ .parent_id+ .as_deref()+ .unwrap_or(quince_core::drive::ROOT);+ // The folder it was copied beside changed for a moment too, and is read again with it.+ settle(resync_drive_folder(&http, &drivews, params.clone(), &data, &destination_id).await)?;+ if source != destination_id {+ settle(resync_drive_folder(&http, &drivews, params, &data, source).await)?;+ }+ Ok(())+}+/// Apple's thumbnails for one folder's files, keyed by drivewsid: each an address the/// window's `<img>` loads from the cache on disk itself (`quince://…/dthumb/<file>`).///@@ -6740,6 +6804,8 @@ fn main() {drive_recents,storage_info,drive_duplicate,+ drive_copy,+ clipboard::clipboard_read,drive_thumbnails,drive_put_back,drive_delete_forever,diff --git a/src/lib/clipboard.ts b/src/lib/clipboard.tsnew file mode 100644index 0000000..fb98e3e--- /dev/null+++ b/src/lib/clipboard.ts@@ -0,0 +1,44 @@+/** Text onto the clipboard; the older way where the newer one is refused. */+export async function copyText(text: string): Promise<boolean> {+ try {+ await navigator.clipboard.writeText(text);+ return true;+ } catch {+ const field = document.createElement("textarea");+ field.value = text;+ field.setAttribute("readonly", "");+ field.style.position = "fixed";+ field.style.opacity = "0";+ // The field takes the focus to be copied from; it goes back to where it was after (a Drive+ // row, for one, whose arrows go on from it).+ const was = document.activeElement as HTMLElement | null;+ document.body.appendChild(field);+ field.select();+ let copied = false;+ try {+ copied = document.execCommand("copy");+ } catch {+ copied = false;+ }+ field.remove();+ was?.focus?.({ preventScroll: true });+ return copied;+ }+}++/**+ * The name Finder gives a copy put into a folder that already holds `taken`: its own name where+ * that is free, else "Report copy.pdf", then "Report copy 2.pdf". A copy of a copy counts on+ * ("Report copy 2.pdf"), never "Report copy copy.pdf". Compared without regard to case, as iCloud+ * Drive compares names. The same rule as the backend's `copy_name`, which names the real copy;+ * this one names the row shown while it is being made.+ */+export function copyName(stem: string, extension: string | null, taken: Iterable<string>): string {+ const ext = extension ? `.${extension}` : "";+ const used = new Set([...taken].map((t) => t.toLocaleLowerCase()));+ const free = (name: string) => !used.has(name.toLocaleLowerCase());+ if (free(`${stem}${ext}`)) return `${stem}${ext}`;+ const base = stem.match(/^(.+) copy(?: \d+)?$/)?.[1] ?? stem;+ if (free(`${base} copy${ext}`)) return `${base} copy${ext}`;+ for (let n = 2; ; n++) if (free(`${base} copy ${n}${ext}`)) return `${base} copy ${n}${ext}`;+}diff --git a/src/lib/ipc.ts b/src/lib/ipc.tsindex 2717ea5..9d5871e 100644--- a/src/lib/ipc.ts+++ b/src/lib/ipc.ts@@ -439,6 +439,11 @@ export const api = {invoke<{ drivewsid: string; reason: string }[]>("drive_trash_out", { items, recover }),driveMove: (drivewsid: string, destinationId: string) =>invoke<void>("drive_move", { drivewsid, destinationId }),+ /** A copy of a file or folder put into a folder, named as Finder names a copy. */+ driveCopy: (drivewsid: string, destinationId: string) =>+ invoke<void>("drive_copy", { drivewsid, destinationId }),+ /** The desktop's clipboard: files copied in the file manager, as paths, or else its text. */+ clipboardRead: () => invoke<{ files: string[]; text: string | null }>("clipboard_read"),};/** Tauri rejects with a plain string from our commands; keep it readable either way. */diff --git a/src/screens/ContactsView.tsx b/src/screens/ContactsView.tsxindex 05b4c19..bd33d4a 100644--- a/src/screens/ContactsView.tsx+++ b/src/screens/ContactsView.tsx@@ -37,6 +37,7 @@ import { PhotoSheet } from "./contacts/PhotoSheet";import { DuplicatesBanner, DuplicatesView } from "./contacts/Duplicates";import { keepSame } from "../lib/same";import { useArrivals } from "../lib/arrival";+import { copyText } from "../lib/clipboard";/** The sidebar row that is every contact rather than a list. */const ALL = "";@@ -1831,30 +1832,6 @@ function RowName({ contact: c }: { contact: Contact }) {return named ? <b>{name}</b> : <>{name}</>;}-/** Text onto the clipboard; the older way where the newer one is refused. */-async function copyText(text: string): Promise<boolean> {- try {- await navigator.clipboard.writeText(text);- return true;- } catch {- const field = document.createElement("textarea");- field.value = text;- field.setAttribute("readonly", "");- field.style.position = "fixed";- field.style.opacity = "0";- document.body.appendChild(field);- field.select();- let copied = false;- try {- copied = document.execCommand("copy");- } catch {- copied = false;- }- field.remove();- return copied;- }-}-/** A link a person typed without its scheme still opens: "example.com" is the web. One of a* kind Skykeep does not open (lib/links.ts) is no link: null, and it shows as its text. */const webHref = (value: string) => {diff --git a/src/screens/DriveView.tsx b/src/screens/DriveView.tsxindex c6fa0a0..7a4c270 100644--- a/src/screens/DriveView.tsx+++ b/src/screens/DriveView.tsx@@ -32,6 +32,7 @@ import { dateText, timeText } from "../lib/when";import { Clock } from "lucide-react";import { useReveal } from "../lib/reveal";import { keepSame } from "../lib/same";+import { copyName, copyText } from "../lib/clipboard";/** iCloud Drive's own four orders, as its "by Name" menu offers them. */const SORTS = [@@ -443,6 +444,12 @@ function sameItems(a: DriveItem[], b: DriveItem[]): boolean {return b.every((i) => seen.has(key(i)));}+/**+ * Files and folders of iCloud Drive's own: an app's library (Keynote, Shortcuts), and what is in+ * one, belongs to that app (see acceptsUploads), so it is not copied out of it.+ */+const copyable = (item: DriveItem) => (item.kind === "FILE" || item.kind === "FOLDER") && acceptsUploads(item.drivewsid);+export function DriveView() {const [trail, setTrail] = useState<Crumb[]>([{ id: DRIVE_ROOT, name: "Drive" }]);/**@@ -597,6 +604,8 @@ export function DriveView() {}, [items]);/** The ⋯ menu, or the same menu opened by a right-click, for one item. */const [menu, setMenu] = useState<{ item: DriveItem; x: number; y: number; alignRight: boolean } | null>(null);+ /** The folder's own menu, from a right-click on nothing; with what the clipboard held then. */+ const [spaceMenu, setSpaceMenu] = useState<{ x: number; y: number; alignRight: boolean; files: number; other: string | null } | null>(null);/** Items of Drive's own being dragged onto a folder — one, or all selected — and the folder it is over. */const dragItem = useRef<DriveItem[] | null>(null);const [dropOn, setDropOn] = useState<string | null>(null);@@ -610,6 +619,8 @@ export function DriveView() {// back to the previous location".const hereRef = useRef(here.id);hereRef.current = here.id;+ const trailRef = useRef(trail);+ trailRef.current = trail;/** Items deleted or moved out of a folder that Apple's listing of it may still carry for a* moment after — each kept as "folder:item", so it is hidden only in the folder it left.* By item alone, an item moved into another folder, or recovered from Recently Deleted,@@ -906,15 +917,25 @@ export function DriveView() {[refresh, here.id]);+ /**+ * Move, from the folder open (a drag, Move to Folder) or from the folder they were copied in+ * (Ctrl-Alt-V, as Finder's Option-Command-V). Gone from where they were at once, and shown+ * where they go when that is the folder open; back, with the reason, if Apple refuses.+ */const moveAll = useCallback(- async (list: DriveItem[], destinationId: string) => {+ async (list: DriveItem[], destinationId: string, from: string = hereRef.current) => {setMoving(null);setError(null);const going = list.filter((i) => i.drivewsid !== destinationId);if (going.length === 0) return;- // Out of this folder at once; back, with the reason, if Apple refuses.- const from = hereRef.current;setGone((g) => new Set([...g, ...going.map((i) => goneKey(from, i.drivewsid))]));+ const batch = `move-${Date.now()}`;+ if (destinationId === hereRef.current) {+ setPending((p) => [+ ...p,+ ...going.map((i) => ({ key: `${batch}:${i.drivewsid}`, folder: destinationId, name: driveName(i), doing: "Moving…" })),+ ]);+ }const refused: string[] = [];let reason = "";for (const item of going) {@@ -923,6 +944,7 @@ export function DriveView() {} catch (e) {refused.push(item.drivewsid);reason = messageOf(e);+ settle(`${batch}:${item.drivewsid}`);}}if (refused.length) {@@ -934,10 +956,76 @@ export function DriveView() {setError(going.length === 1 ? reason : `${refused.length} of ${going.length} items could not be moved: ${reason}`);}if (refused.length < going.length) await refresh();+ settle(batch);},[refresh]);+ /**+ * Copy and Paste, as Finder: Ctrl-C keeps what is chosen (and puts its names on the+ * desktop's clipboard as text, as Finder does, so the clipboard says what was copied last);+ * Ctrl-V in any folder puts copies there. Kept across folders, and for more than one paste.+ */+ const [clip, setClip] = useState<{ items: DriveItem[]; from: string; text: string | null } | null>(null);+ const clipRef = useRef(clip);+ clipRef.current = clip;+ const copyItems = useCallback(async (list: DriveItem[]) => {+ const copying = list.filter(copyable);+ if (copying.length === 0) return;+ const text = copying.map(driveName).join("\n");+ const from = hereRef.current;+ setClip({ items: copying, from, text: null });+ if (await copyText(text)) setClip((c) => (c && c.items === copying ? { ...c, text } : c));+ }, []);++ /**+ * Copies of `list` in the folder open, each shown at once under the name Finder would give+ * it there and made one after another (Apple turns a burst of writes away as busy). One that+ * fails leaves, with the reason; the rest still land.+ */+ const copyHere = useCallback(+ async (list: DriveItem[]) => {+ setError(null);+ const into = hereRef.current;+ const inside = trailRef.current.map((c) => c.id);+ // Never into itself, or into a folder within it, as Finder will not.+ const insideItself = list.find((i) => inside.includes(i.drivewsid));+ const copying = list.filter((i) => !inside.includes(i.drivewsid));+ if (insideItself) setError(`\u201c${driveName(insideItself)}\u201d can\u2019t be copied into a folder inside itself.`);+ if (copying.length === 0) return;+ const taken = new Set([+ ...itemsRef.current.map(driveName),+ ...pendingRef.current.filter((p) => p.folder === into).map((p) => p.name),+ ]);+ const batch = `paste-${Date.now()}`;+ const shown = copying.map((item, i) => {+ const name = copyName(item.name, isContainer(item) ? null : item.extension, taken);+ taken.add(name);+ return { key: `${batch}:${i}`, folder: into, name, doing: "Copying…" };+ });+ setPending((p) => [...p, ...shown]);+ const refused: string[] = [];+ let reason = "";+ for (const [i, item] of copying.entries()) {+ try {+ await api.driveCopy(item.drivewsid, into);+ // The backend has read the folder again: the library has the copy, so no new look.+ if (into === hereRef.current) await refresh(false);+ } catch (e) {+ refused.push(item.drivewsid);+ reason = messageOf(e);+ } finally {+ settle(shown[i].key);+ }+ }+ if (refused.length) {+ setError(copying.length === 1 ? reason : `${refused.length} of ${copying.length} items could not be copied: ${reason}`);+ }+ },+ [refresh]+ );++/*** Send files from this machine to the folder currently open.*@@ -956,6 +1044,8 @@ export function DriveView() {* seconds later — so a press seemed to do nothing, and then a folder appeared from nowhere.*/const [pending, setPending] = useState<{ key: string; folder: string; name: string; doing: string }[]>([]);+ const pendingRef = useRef(pending);+ pendingRef.current = pending;// What is kept on this computer — null while the iCloud Drive folder is off.const [kept, setKept] = useState<Set<string> | null>(null);useEffect(() => {@@ -1097,6 +1187,49 @@ export function DriveView() {[here.id, refresh]);+ /**+ * Paste into the folder open. Whatever was copied last decides: files copied in the+ * desktop's file manager go up into it, as a drop would send them; else what Drive copied+ * is copied here — or, with Alt (Option on a Mac), moved here, as Finder's Option-Command-V.+ */+ // Each render's own, as the keys are: it uploads into the folder open now.+ const paste = async (move: boolean) => {+ if (!acceptsUploads(hereRef.current)) {+ setError("This folder belongs to an app, which is the only thing that can add to it.");+ return;+ }+ const board = await api.clipboardRead().catch(() => null);+ if (board?.files.length) {+ await upload(board.files);+ return;+ }+ const c = clipRef.current;+ if (!c) return;+ // Something else copied since (text in another app): that is what is on the clipboard.+ if (c.text !== null && board?.text != null && board.text !== c.text) return;+ if (!move) {+ await copyHere(c.items);+ return;+ }+ const into = hereRef.current;+ if (c.from === into) return;+ const inside = trailRef.current.map((t) => t.id);+ const names = new Set(itemsRef.current.map((i) => driveName(i).toLocaleLowerCase()));+ const clash = c.items.find((i) => names.has(driveName(i).toLocaleLowerCase()));+ const insideItself = c.items.find((i) => inside.includes(i.drivewsid));+ if (clash || insideItself) {+ setError(+ clash+ ? `An item named \u201c${driveName(clash)}\u201d is already in this folder, so nothing was moved.`+ : `\u201c${driveName(insideItself!)}\u201d can\u2019t be moved into a folder inside itself.`,+ );+ return;+ }+ // Moved, it is no longer where it was copied: nothing is left to paste.+ setClip(null);+ await moveAll(c.items, into, c.from);+ };+const chooseAndUpload = useCallback(async (folders: boolean) => {setUploadMenu(false);@@ -1289,9 +1422,9 @@ export function DriveView() {// Finder's keys (Ctrl in place of Command): the arrows walk the selection — across and down// in Grid — and Shift with them widens it; Return or Ctrl-Down opens, Ctrl-Up goes up a- // folder, Ctrl-[ and Ctrl-] go back and forward, F2 renames, Ctrl-D duplicates, Delete moves- // to Recently Deleted, Ctrl-A selects all, and Space shows the selected file large, as Quick- // Look does.+ // folder, Ctrl-[ and Ctrl-] go back and forward, F2 renames, Ctrl-D duplicates, Ctrl-C and+ // Ctrl-V copy and paste (Ctrl-Alt-V moves), Delete moves to Recently Deleted, Ctrl-A selects+ // all, and Space shows the selected file large, as Quick Look does.const live = useActiveRef();const keys = useRef<(e: KeyboardEvent) => void>(() => {});keys.current = (e: KeyboardEvent) => {@@ -1346,6 +1479,16 @@ export function DriveView() {// Duplicate, as Finder's Command-D: each file chosen, beside itself (folders are not).e.preventDefault();for (const item of pickedItems) if (!isContainer(item) && !busyIds.has(item.drivewsid)) void duplicate(item);+ } else if (mod && k.toLowerCase() === "c" && !e.shiftKey && pickedItems.length && !window.getSelection()?.toString()) {+ // Copy, as Finder's Command-C: what is chosen, to paste into any folder.+ e.preventDefault();+ void copyItems(pickedItems);+ } else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && (k.toLowerCase() === "v" || (e.altKey && e.code === "KeyV"))) {+ // Paste, as Finder's Command-V; with Alt (Option), moved here instead, as Option-Command-V.+ // By the key's place too with Alt: Option-V on a Mac types "√".+ e.preventDefault();+ setPeeking(false);+ void paste(e.altKey);} else if (mod && k === "ArrowUp") {e.preventDefault();if (trail.length > 1) setTrail((t) => t.slice(0, -1));@@ -1444,6 +1587,20 @@ export function DriveView() {const t = e.target as HTMLElement;if (!t.closest("[data-id], button, input, form, a, [role='menu'], .modal-veil, .drive-peek-veil")) setPicked([]);}}+ // A right-click on nothing is for the folder itself, as Finder's: a new folder, and Paste+ // when the clipboard holds something to paste — files copied in the file manager, or what+ // was copied here.+ onContextMenu={(e) => {+ const t = e.target as HTMLElement;+ if (t.closest("[data-id], button, input, textarea, form, a, [role='menu'], .drive-bar, .modal-veil, .drive-peek-veil, .upload-tray")) return;+ e.preventDefault();+ setPicked([]);+ const at = { x: e.clientX, y: e.clientY, alignRight: false };+ void api.clipboardRead().then(+ (board) => setSpaceMenu({ ...at, files: board.files.length, other: board.text }),+ () => setSpaceMenu({ ...at, files: 0, other: null }),+ );+ }}><header className="pane-head drive-bar">{/* The folder's name with what is in it under it, as icloud.com writes them: one block@@ -1677,6 +1834,7 @@ export function DriveView() {run: () => void (async () => { for (const f of files) await download(f); })(),}]: []),+ ...(many.some(copyable) ? [{ label: "Copy", run: () => void copyItems(many) }] : []),{ label: "Move to Folder", run: () => setMoving(many) },null,{ label: `Delete ${many.length} Items`, danger: true, run: () => void removeAll(many) },@@ -1697,6 +1855,7 @@ export function DriveView() {{ label: "Get Info", run: () => setInfo(menu.item) },null,...(isContainer(menu.item) ? [] : [{ label: "Duplicate", run: () => void duplicate(menu.item) }]),+ ...(copyable(menu.item) ? [{ label: "Copy", run: () => void copyItems([menu.item]) }] : []),{ label: "Rename", run: () => setRenaming(menu.item.drivewsid) },{ label: "Move to Folder", run: () => setMoving([menu.item]) },null,@@ -1706,6 +1865,23 @@ export function DriveView() {);})()}+ {spaceMenu && (() => {+ // What Paste would put here: the file manager's files, or what was copied in Drive while+ // nothing else has been copied since (see paste).+ const theirs = spaceMenu.files > 0;+ const ours = !!clip && (clip.text === null || spaceMenu.other === null || spaceMenu.other === clip.text);+ return (+ <RowMenu+ at={spaceMenu}+ onClose={() => setSpaceMenu(null)}+ entries={[+ { label: "New Folder", run: () => setCreatingFolder(true) },+ ...(theirs || ours ? [null, { label: "Paste", run: () => void paste(false) }] : []),+ ]}+ />+ );+ })()}+{peeking && primary && (<QuickLookitem={primary}