diff --git a/README.md b/README.md index a30325e..b0a09bf 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ PDF→image and PDF split write into a new `Name pages` folder containing `Page ## Capture history library -Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. The main window's **Recent** card is that library: +Every capture, conversion result and received file is written by Rust into one library in the app data directory (`history.json`, capped at 300 entries), so all windows share a single list and a webview cache clear cannot throw it away. Because it sits outside the bundle, **it survives an update and a reinstall**; the first launch after upgrading also adopts whatever the 0.1 webview had kept in its own store, so a list built before that change is not lost either. The main window's **Recent** card is that library: - **Search** once the list grows past a few rows; it filters on the file name. - **Pin** a row to keep it through the capacity limit, a deleted file, and Clear. diff --git a/README.zh-CN.md b/README.zh-CN.md index 557f3ec..1693088 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -214,7 +214,7 @@ PDF 转图片与 PDF 拆分会新建 `名称 pages` 文件夹,内含 `Page 001 ## 截图历史库 -每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。主窗口的「最近使用」卡片就是这个历史库: +每一次截图、每一个转换结果、每一个收到的文件,都由 Rust 写入应用数据目录中的同一个历史库(`history.json`,上限 300 条),因此所有窗口共用一份列表,清理 Webview 缓存也不会丢失。这份文件在应用包之外,**升级与重装都不会清空它**;升级后的首次启动还会接管 0.1 版本留在 Webview 自己的存储里的旧记录,因此那条改动之前积累的列表也不会丢。主窗口的「最近使用」卡片就是这个历史库: - 列表超过几行后出现**搜索**框,按文件名过滤。 - **收藏**某一行,即可在容量上限、文件被删除、以及「清空」之后仍然保留。 diff --git a/docs/RELEASE.md b/docs/RELEASE.md index 70cdbfb..6c05f54 100644 --- a/docs/RELEASE.md +++ b/docs/RELEASE.md @@ -266,13 +266,13 @@ test, which is the proof that the check is real and not a pass-through. Checked against the live `releases` branch of this repository: -Version **0.1.2**, checked by downloading each artifact back from the raw endpoint rather +Version **0.1.3**, checked by downloading each artifact back from the raw endpoint rather than trusting the local copy: | Key | Artifact | Verified from the remote | | --- | --- | --- | -| `macos` | `Shift-macOS-universal.dmg` (55,509,300 B) | bytes downloaded, SHA256 matches the manifest | -| `windows` | `Shift-Setup-0.1.2-win-x64.exe` (24,524,080 B) | bytes downloaded, SHA256 matches the manifest | +| `macos` | `Shift-macOS-universal.dmg` (55,528,662 B) | bytes downloaded, SHA256 matches the manifest | +| `windows` | `Shift-Setup-0.1.3-win-x64.exe` (24,517,835 B) | bytes downloaded, SHA256 matches the manifest | | `windows-arm64` | not published | by choice — see "Supported release targets" | | `linux` | not published | by choice: Linux is a build target here, not a shipped product | diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 2a6058c..3ded83b 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -98,6 +98,12 @@ names what is still missing. a busy image left the old copy running instead of leaving Shift closed. The Windows script is cross-built and its `${Silent}` gate compiles, but the restart itself needs real hardware. See "Applying an update" in `docs/RELEASE.md`. +- An update no longer costs the user the Recent list. That library lives in the app data + directory rather than in the bundle, and since the move out of the webview's own storage + it had no bridge from the old store: `history_import` adopts those rows on the first + launch after an upgrade, re-deriving each entry's kind from the file rather than trusting + the older store's guess, then the legacy key is dropped so a later upgrade cannot + resurrect rows the user has since removed. - Signed and notarized macOS package: pending (builds are signed with a local identity). - Signed Windows installer: pending. - Manifest signing is done. `scripts/release-key.py` mints the release key, diff --git a/package.json b/package.json index 11fcfe5..f660e58 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "shift", "private": true, - "version": "0.1.2", + "version": "0.1.3", "type": "module", "scripts": { "prepare:ocr": "bash scripts/prepare-ocr-assets.sh", diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index b36f3b1..b98dae7 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -3899,7 +3899,7 @@ dependencies = [ [[package]] name = "shift" -version = "0.1.2" +version = "0.1.3" dependencies = [ "base64 0.22.1", "calamine", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 23ffa5f..0a763f8 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "shift" -version = "0.1.2" +version = "0.1.3" description = "A radial file utility with screenshot, recording and OCR." authors = ["Shift Contributors"] edition = "2021" diff --git a/src-tauri/src/history.rs b/src-tauri/src/history.rs index 6d26c4a..c6df1b5 100644 --- a/src-tauri/src/history.rs +++ b/src-tauri/src/history.rs @@ -26,8 +26,12 @@ const CAPACITY: usize = 300; pub struct HistoryEntry { pub path: String, /// "image" | "video" | "text" | "file", matching the editor's own kinds. + /// Defaults so a row imported from an older store, which may not have recorded + /// it, still parses; every writer re-derives it from the path anyway. + #[serde(default)] pub kind: String, /// Milliseconds since the epoch, as the webview already reports them. + #[serde(default)] pub at: i64, /// Pinned entries survive both the capacity limit and a missing file. #[serde(default)] @@ -109,6 +113,29 @@ fn publish(app: &AppHandle, entries: Vec) { let _ = app.emit("history://changed", entries); } +/// Merge imported rows into the library. An entry the library already lists keeps +/// its own timestamp, so an import cannot make yesterday's file look new. +/// +/// The kind is re-derived from the path rather than taken from the store being +/// imported from: that field is the importer's own opinion about a file it may not +/// have been able to read, and the current classifier is the one the editor uses. +fn merge(existing: Vec, incoming: Vec) -> Vec { + let mut merged = existing; + for entry in incoming { + if entry.path.trim().is_empty() { + continue; + } + if merged.iter().any(|have| have.path == entry.path) { + continue; + } + merged.push(HistoryEntry { + kind: crate::files::editor_kind(Path::new(&entry.path)).to_string(), + ..entry + }); + } + tidy(merged) +} + /// Record files that just became available. Called by the result pipeline rather /// than by whichever window happens to be open. pub fn record(app: &AppHandle, paths: &[String]) { @@ -192,6 +219,25 @@ pub async fn history_remove(app: AppHandle, path: String) -> Result, +) -> Result, String> { + tauri::async_runtime::spawn_blocking(move || { + let entries = merge(snapshot(&app), entries); + write(&app, &entries)?; + publish(&app, entries.clone()); + Ok(entries) + }) + .await + .map_err(|error| error.to_string())? +} + #[tauri::command] pub async fn history_clear(app: AppHandle) -> Result, String> { tauri::async_runtime::spawn_blocking(move || { @@ -222,6 +268,60 @@ mod tests { } } + #[test] + fn a_row_from_the_older_webview_store_parses() { + // What 0.1.0 kept in localStorage: a path, a kind it guessed, and a + // timestamp. No pin, since that column did not exist yet. + let here = real_path(); + let json = format!(r#"[{{"path":"{here}","kind":"image","at":1730000000000}}]"#); + let legacy: Vec = serde_json::from_str(&json).unwrap(); + assert_eq!(legacy.len(), 1); + assert!(!legacy[0].pinned); + let merged = merge(vec![], legacy); + assert_eq!(merged.len(), 1); + // The importer's guess is replaced by what this build's classifier says. + assert_eq!(merged[0].kind, "file"); + assert_eq!(merged[0].at, 1_730_000_000_000); + } + + fn an_import_adds_unknown_paths_and_never_refreshes_a_timestamp() { + let here = real_path(); + // The folder holding the test binary: a second path that really exists, + // since a tidy pass drops anything that does not. + let other = std::env::current_exe() + .unwrap() + .parent() + .unwrap() + .to_string_lossy() + .to_string(); + let merged = merge( + vec![entry(&here, 500, false)], + vec![ + // Same file, older stamp: the library's own row wins. + entry(&here, 100, false), + entry(&other, 400, false), + ], + ); + assert_eq!(merged.len(), 2, "the imported path should have landed"); + let kept = merged.iter().find(|e| e.path == here).unwrap(); + assert_eq!(kept.at, 500, "an import must not refresh a timestamp"); + } + + #[test] + fn an_import_drops_entries_that_point_at_nothing() { + let missing = format!("/nonexistent/shift-import-{}.png", std::process::id()); + let merged = merge(vec![], vec![entry(&missing, 100, false)]); + assert!(merged.is_empty()); + } + + #[test] + fn an_import_keeps_a_pinned_flag_from_the_older_store() { + let here = real_path(); + let merged = merge(vec![], vec![entry(&here, 100, true)]); + assert_eq!(merged.len(), 1); + assert!(merged[0].pinned); + } + #[test] fn entries_kind_follows_the_editor_classification() { assert_eq!(HistoryEntry::new("/x/a.png").kind, "image"); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 61cb94b..9236671 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -391,6 +391,7 @@ pub fn run() { history::history_record, history::history_set_pinned, history::history_remove, + history::history_import, history::history_clear, settings::get_app_settings, settings::set_output_directory, diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 33cf2a6..cdaef45 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Shift", - "version": "0.1.2", + "version": "0.1.3", "identifier": "app.nex.shift", "build": { "beforeDevCommand": "pnpm dev", diff --git a/src/components/MainWindow.tsx b/src/components/MainWindow.tsx index 8956998..5f317b6 100644 --- a/src/components/MainWindow.tsx +++ b/src/components/MainWindow.tsx @@ -540,7 +540,7 @@ export function MainWindow() { .catch(() => setHotkeys(null)); // Rust prunes entries whose file is gone as it reads the library, so there is // no separate sweep to run here. - void history.list().then(setRecent).catch(() => undefined); + void history.adopt().then(setRecent).catch(() => undefined); // Settings are loaded once when the main window starts. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); diff --git a/src/components/UpdatePanel.tsx b/src/components/UpdatePanel.tsx index cd6d672..f4aef73 100644 --- a/src/components/UpdatePanel.tsx +++ b/src/components/UpdatePanel.tsx @@ -68,8 +68,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P } = useUpdateFlow(); const verified = status?.state === "ready"; - // Rust reports the key it resolved; the panel only repeats it. - const artifactKey = status?.artifactKey ?? ""; const available = status?.state === "available" || verified; const failed = status?.state === "error" || status?.state === "unavailable"; @@ -92,15 +90,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P ) : ( {t("updateSystemPending")} )} - {artifactKey ? ( - - {t("updateSystemArtifact", { key: artifactKey })} - - ) : status && status.state === "unavailable" ? ( - - {t("updateSystemArtifactUnknown")} - - ) : null}
@@ -133,15 +122,6 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P
- {available && status ? ( - - - - {status.availableVersion} - - {status.date} - - ) : null} {status ? t( @@ -155,6 +135,15 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P ) : t("updateIdle")} + {available && status ? ( + + + + {status.availableVersion} + + {status.date} + + ) : null}
{status?.notes ?

{status.notes}

: null} diff --git a/src/i18n.ts b/src/i18n.ts index 92dc780..7088a72 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -200,8 +200,6 @@ const messages: Record> = { updateFeedNone: "Not configured for this build", updateSystem: "This machine", updateSystemPending: "Reading operating system…", - updateSystemArtifact: "Installs the \u201c{key}\u201d artifact", - updateSystemArtifactUnknown: "This release names no artifact for this machine", updateIdle: "Not checked yet", updateAvailable: "Update available", updateCurrent: "Up to date", @@ -471,8 +469,6 @@ const messages: Record> = { updateFeedNone: "当前构建未配置更新源", updateSystem: "本机", updateSystemPending: "正在读取系统信息…", - updateSystemArtifact: "将安装「{key}」产物", - updateSystemArtifactUnknown: "本次发布没有为本机准备产物", updateIdle: "尚未检查", updateAvailable: "发现新版本", updateCurrent: "已是最新版本", diff --git a/src/lib/history.ts b/src/lib/history.ts index ad21ac6..cb2d76b 100644 --- a/src/lib/history.ts +++ b/src/lib/history.ts @@ -3,9 +3,11 @@ import { listen } from "@tauri-apps/api/event"; import { invoke } from "@tauri-apps/api/core"; import { announceRecentChange, + clearLegacyRecentItems, getLocalRecentItems, type RecentItem, setLocalRecentItems, + takeLegacyRecentItems, } from "./utils"; /** @@ -31,6 +33,25 @@ export const history = { return request("history_list"); }, + /** + * Read the library, adopting the rows a 0.1 webview kept for itself if any are + * waiting. Rust merges them, so this is safe to call more than once and cannot + * reorder or re-date what the library already lists. + */ + async adopt(): Promise { + if (!isTauri()) return getLocalRecentItems(); + const legacy = takeLegacyRecentItems(); + if (legacy.length === 0) return request("history_list"); + try { + const merged = await request("history_import", { entries: legacy }); + // Only drop the old store once its rows are safe in the library. + clearLegacyRecentItems(); + return merged; + } catch { + return request("history_list"); + } + }, + /** Record paths that just became available, e.g. an editor save. */ async record(paths: string[]): Promise { const usable = paths.filter(Boolean); diff --git a/src/lib/recent.test.ts b/src/lib/recent.test.ts new file mode 100644 index 0000000..d4f2f21 --- /dev/null +++ b/src/lib/recent.test.ts @@ -0,0 +1,64 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { getLocalRecentItems, takeLegacyRecentItems, clearLegacyRecentItems } from "./utils.ts"; + +/** Minimal store stand-in, installed before the module reads it. */ +function withStore(items: Record, run: () => void) { + const store = new Map(Object.entries(items)); + const previous = Object.getOwnPropertyDescriptor(globalThis, "localStorage"); + Object.defineProperty(globalThis, "localStorage", { + configurable: true, + value: { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => void store.set(key, value), + removeItem: (key: string) => void store.delete(key), + }, + }); + try { + run(); + } finally { + if (previous) Object.defineProperty(globalThis, "localStorage", previous); + else delete (globalThis as Record).localStorage; + } +} + +test("an empty store yields nothing", () => { + withStore({}, () => { + assert.deepEqual(takeLegacyRecentItems(), []); + assert.deepEqual(getLocalRecentItems(), []); + }); +}); + +test("the 0.1 rows are read whole, including paths outside the eight it displayed", () => { + const rows = JSON.stringify([ + { path: "/tmp/a.png", kind: "image", at: 5 }, + { path: "/tmp/b.pdf", kind: "file", at: 4 }, + ]); + withStore({ "shift.recent": rows }, () => { + assert.deepEqual(takeLegacyRecentItems(), [ + { path: "/tmp/a.png", kind: "image", at: 5 }, + { path: "/tmp/b.pdf", kind: "file", at: 4 }, + ]); + }); +}); + +test("clearing the legacy key makes the handoff a one-shot", () => { + withStore({ "shift.recent": JSON.stringify([{ path: "/tmp/a.png", kind: "image", at: 5 }]) }, () => { + assert.equal(takeLegacyRecentItems().length, 1); + clearLegacyRecentItems(); + assert.deepEqual(takeLegacyRecentItems(), []); + }); +}); + +test("junk in the store is ignored rather than imported", () => { + withStore({ "shift.recent": "[null,{\"path\":\"\"},{\"path\":\"/tmp/ok.png\",\"at\":1}]" }, () => { + assert.deepEqual(takeLegacyRecentItems(), [{ path: "/tmp/ok.png", at: 1 }]); + }); + withStore({ "shift.recent": "{not json" }, () => { + assert.deepEqual(takeLegacyRecentItems(), []); + }); + withStore({ "shift.recent": "{\"path\":\"/tmp/a.png\"}" }, () => { + assert.deepEqual(takeLegacyRecentItems(), []); + }); +}); diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 7b5b3b3..9b8b9ae 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -130,6 +130,39 @@ export function setLocalRecentItems(items: RecentItem[]) { announceRecentChange(); } +/** + * Rows the 0.1 webview wrote for itself, before Rust owned the library. + * + * That list lived in `localStorage`, which a reinstall does not survive, so the + * first launch of a newer build shows an empty Recent list even though every file + * it names is still on disk. Read it once, hand it to Rust, then drop the key: the + * store keeps no authority after that, and dropping it means a later upgrade cannot + * resurrect rows the user has since removed. + */ +export function takeLegacyRecentItems(): RecentItem[] { + try { + const stored = localStorage.getItem(RECENT_KEY); + if (!stored) return []; + const parsed = JSON.parse(stored); + if (!Array.isArray(parsed)) return []; + const items = parsed.filter( + (entry: RecentItem) => typeof entry?.path === "string" && entry.path.length > 0, + ); + return items; + } catch { + return []; + } +} + +/** Forget the legacy key once its rows are safe in the Rust library. */ +export function clearLegacyRecentItems() { + try { + localStorage.removeItem(RECENT_KEY); + } catch { + // A store we cannot clear only risks a second harmless import. + } +} + /** Notify listeners in this window; other windows hear the Rust broadcast. */ export function announceRecentChange() { window.dispatchEvent(new Event(RECENT_EVENT)); diff --git a/src/styles.css b/src/styles.css index c759e99..a6ca171 100644 --- a/src/styles.css +++ b/src/styles.css @@ -2375,20 +2375,6 @@ kbd { font-weight: 620; } -.update-system-key { - padding: 2px 7px; - border-radius: 999px; - color: #12703f; - background: rgba(26, 162, 96, 0.1); - font-size: 10.5px; - font-weight: 620; -} - -.update-system-key.is-unknown { - color: #a3401b; - background: rgba(242, 106, 51, 0.12); -} - .home-main { position: relative; z-index: 2; @@ -4501,7 +4487,6 @@ body[data-view="radial"] .share-backdrop { } .update-state { - margin-left: auto; font-size: 12px; font-weight: 600; color: rgba(91, 55, 35, 0.6);