diff --git a/README.md b/README.md index 852f1fe..b20e141 100644 --- a/README.md +++ b/README.md @@ -72,7 +72,7 @@ Shift lives in the menu bar (macOS) and the notification area (Windows), and it **Use a tool (`Option + Shift`, or `Alt + Shift` on Windows).** Same gesture, and the wedges become tools for that file type instead of formats. While the ring is open, keep `Shift` held and press or release `Option`/`Alt` to flip between the format ring and the tool ring. -**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. **OCR** refuses a file it cannot read rather than handing it to another ring. +**Prefer not to drag?** In the main window, **Convert files** and **File tools** open a picker and then show the same ring for what you chose; **OCR** picks an image and reads it. Dropping a file is **aimed**: the three buttons are the only drop targets, and the button you release on is the action it runs - **Convert files** opens the format ring, **File tools** the tool ring, **OCR** reads the image. All three light up as candidates while a drag is in flight, and only they react: the panel around them stays still. Release anywhere else and nothing happens at all. **OCR** greyed out means the file you are dragging is not one it can read: it refuses such a drop quietly rather than handing it to another ring, and it never answers with a message you have to dismiss. **Several files at once.** Multi-select with `⌘`/`Ctrl`-click, then drag. Every file is processed. With 2+ images or 2+ PDFs selected, a **Merge** wedge appears that combines them into a single PDF. diff --git a/README.zh-CN.md b/README.zh-CN.md index 30bd513..65d3efb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -72,7 +72,7 @@ Shift 常驻菜单栏(macOS)与通知区域(Windows),同时也有普 **使用工具(`Option + Shift`,Windows 为 `Alt + Shift`)** 操作相同,扇区会从格式换成该类型文件可用的工具。圆环打开时,保持按住 `Shift`,再按下或松开 `Option`/`Alt`,即可在格式环与工具环之间来回切换。 -**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。「文字识别」遇到无法读取的格式会直接拒绝,不再转交给别的圆环。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。 +**不想拖动?** 主窗口中的「文件转换」与「文件工具」会先让你挑选文件,然后对选中的文件弹出同一个圆环;「文字识别」则选取图片并识别。拖放文件必须**对准按钮**:三个按钮是唯一的落点,松开在哪个按钮上就执行那个按钮的动作——「文件转换」打开格式环,「文件工具」打开工具环,「文字识别」直接识别图片。拖拽进行中三个按钮会同时显示为候选落点,并且只有按钮会响应,周围的面板保持静止;松开在其他位置什么都不会发生。「文字识别」变灰,表示你正在拖动的文件不是它能读取的格式:这样的拖放会被安静地拒绝,不再转交给别的圆环,也不会弹出需要你确认的提示。右侧「最近使用」里的条目同样可以拖到这三个按钮上,用同一次拖拽复用已经处理过的文件。 **一次处理多个文件。** 用 `⌘`/`Ctrl` 点选多个文件后一起拖动,每个文件都会被处理。选中 2 张以上图片或 2 个以上 PDF 时,会出现「合并」扇区,把它们合成一个 PDF。 diff --git a/docs/ENGINEERING-NOTES.md b/docs/ENGINEERING-NOTES.md index 9027b8b..3b4fa35 100644 --- a/docs/ENGINEERING-NOTES.md +++ b/docs/ENGINEERING-NOTES.md @@ -404,6 +404,13 @@ cargo test --lib runtime - 0.1.10 连提示也去掉:既然不执行任何操作,解释"为什么没执行"的浮层只是在用户没有松手的位置 制造动静,落在面板其他位置现在是彻底静默。 +「文字识别」的拒绝方式在同一步收紧里改成了**事前可见**:0.1.10 用提示说明"这个格式识别不了", +但那仍是让用户先做错、再由浮层告知。现在拖拽一开始就按携带的文件判定,识别不了的按钮直接进入 +不可用态(`is-drop-unavailable`,`aria-disabled`,与全应用统一的 `--dimmed` 一致),松手时 +什么都不发生,也不再有任何提示。`dragPaths` 是判定唯一依据:原生路径在 `enter` 拿到 `paths`, +内部路径在 `dragstart` 写入这一行——`over` 事件不带路径,`dataTransfer` 在 `dragover` 里也读不到, +所以两条路都必须在开始时登记。 + 外部拖入和内部拖拽始终遵循同一条规则,`dropFiles` 因此接受 `DropAction | null`,`null` 直接 原样返回——它不是"未知动作",而是"没有动作",两条投递路径共用这一个判断。 @@ -431,7 +438,8 @@ cargo test --lib runtime | 两条投递路径都必须把"没命中按钮"当作同一种结果处理 | 内部拖拽与外部拖入的语义必须一致;只在 DOM 路径静默、原生路径仍兜底开环或弹提示,就会出现同一个动作两种结果。 | | 点亮候选按钮的开关有两个来源 | 外部拖拽靠原生 `enter` 设置的 `dragging`,内部拖拽原生事件不一定到,必须另有 `rowDragging`,否则从列表拖起时按钮毫无反应。 | | 面板不要用 `is-dragging` 自己做拖放反馈 | 内部拖拽拿不到原生事件,只有外部拖拽会点亮面板,两种拖法观感不同;把反馈收在按钮上,两条路径共用同一套 `has-drop-target`。 | -| 「文字识别」不接受兜底 | `runOcrOn` 遇到非图片直接拒绝并提示,不再转交格式环:按钮说做什么就做什么,"拖到 OCR 却弹出转换环"会让用户以为按钮被忽略了。 | +| 「文字识别」不接受兜底,也不解释拒绝 | `runOcrOn` 遇到非图片直接返回,既不转交格式环也不弹提示:按钮说做什么就做什么,"拖到 OCR 却弹出转换环"会让用户以为按钮被忽略了,而弹一条"为什么不行"等于让用户先做错再被纠正。判定发生在 `ocrCanRead(dragPaths)`,落在按钮的视觉状态上。 | +| 拖拽结束时三处都要清空 `dragPaths` | 原生 `leave`、原生 `drop`、行的 `dragEnd` 都要清;`landRecentRow` 也清一次,因为部分引擎在落点已确定后才补 `dragEnd`,只靠它会让按钮在下一笔拖拽前一直显示为不可用。 | ### 回归测试 @@ -440,11 +448,40 @@ WKWebView 两条路径都要走一遍): 1. 「最近使用」某行 → 拖到「文件转换」→ 只弹出一个格式环,且文件是这一行。 2. 同一行 → 拖到「文件工具」→ 只弹出工具环。 -3. 图片行 → 拖到「文字识别」→ 打开编辑器并自动开始识别;非图片行 → 不打开编辑器、不开环,只提示"文字识别仅支持图片格式"。 +3. 图片行 → 拖到「文字识别」→ 按钮正常点亮,打开编辑器并自动开始识别;非图片行 → 「文字识别」拖拽全程为不可用态且不会点亮,松手后不打开编辑器、不开环、**不出现任何提示**,另外两个按钮仍可正常落点。 4. 同一行 → 拖到面板空白处 / 标题栏 / 列表本身 → 不开环、不执行、**不出现任何提示浮层**。 5. 从访达拖文件到面板空白处 → 同样不执行、不提示;拖到任一按钮 → 执行该按钮的动作。 6. 行拖出到访达/聊天窗口 → 仍是文件本体,没有被 Shift 自己吃掉。 7. 两种拖法各拖一次 → 面板(`.home-drop`)在拖拽全程不缩放、不变色,标题文案不变;只有三个按钮在拖拽开始时同时亮起虚线候选态、松开后熄灭。 +8. 松手之后(无论落在哪里)→ 按钮立刻恢复正常亮度,下一次拖拽不会残留不可用态。 + +## 提示语由界面措辞,后端只报代号 + +同一件事在两个地方各说一遍,就一定会说成两样。0.1.10 之前正是这样:`perform_action` 直接返回 +`"Saved 1 file."` 这类英文句子,界面在中文环境里也就照原样显示,而同一个环里别的结果用的是 +`t("saved")`;写目录被拒的提示同样由 Rust 拼成英文长句,macOS 首次运行必然看到它。 + +现在约定只有一条:**后端说"是哪件事",界面说"这句话怎么说"。** + +- 结果:`ActionOutcome.message` 只能是 `outcome*` 代号,由 `src/lib/feedback.ts` 的 + `outcomeMessage()` 措辞;数量取自 `outputs.length`,不再把数字写进句子再让人解析。 +- 失败:`Err("…")` 用 `err*` 或 `share-*` / `homebrew-*` 这类既有小写代号;显示前统一走 + `t(messageFrom(error))`。`translate()` 查不到 key 时原样返回,所以第三方库抛出的原始句子 + (`ffmpeg exited with status 137`)仍会照实显示,不会被压成一句无信息的话。 +- 措辞查不到就不要显示代号:`outcomeMessage()` 对未知 `outcome*` 回落到 `saved`。 + +`src/lib/feedback.test.ts` 会扫过 `src-tauri/src/*.rs`,要求每一个 `err*` / `outcome*` 代号在 +两种语言里都有措辞,且 `outcome*` 必须被 `feedback.ts` 认识。新增代号时不必改测试——它会自己发现漏掉的 +那一个;删掉一个还在用的代号同样会红。 + +另一条容易踩的约束:**一次性注册的监听器不要闭包捕获 `t`。** 挂载时注册的回调拿到的是首帧的 `t`, +之后切换语言,它弹出的消息仍是启动时的语言;`app://error` 与两条落点失败的回调因此用 +`tLive()`(按当前存储的语言即时翻译),而不是 `t`。 + +反馈的时长收在 `FEEDBACK` 一处(`done` / `hint` / `notice` / `error` / `running` / `hold`), +`hold` 专用于进度会持续刷新、中途不能过期的长任务;`src/lib/utils.ts` 的 `messageFrom()` 是 +把 unknown 变成文案的唯一途径。不可用控件统一用 `--dimmed` 与 `cursor: default`, +`:hover` 一律带 `:not(:disabled)`。 ## 修改这些路径时的统一回归命令 diff --git a/src-tauri/src/capture.rs b/src-tauri/src/capture.rs index 36ca5f8..de73db6 100644 --- a/src-tauri/src/capture.rs +++ b/src-tauri/src/capture.rs @@ -28,10 +28,7 @@ fn ensure_screen_capture_access() -> Result<(), String> { return Ok(()); } } - Err( - "Screen Recording permission is required. Enable Shift in System Settings > Privacy & Security > Screen Recording, then restart Shift if macOS asks." - .into(), - ) + Err("errScreenPermission".into()) } #[cfg(not(target_os = "macos"))] @@ -70,7 +67,7 @@ fn monitor_at_cursor(app: &AppHandle) -> Result { && cursor.y <= y + monitor.size().height as f64 }) .or_else(|| app.primary_monitor().ok().flatten()) - .ok_or_else(|| "No monitor found under the cursor.".to_string()) + .ok_or_else(|| "errNoMonitor".to_string()) } fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result { @@ -100,10 +97,7 @@ fn capture_screen(app: &AppHandle, monitor: &tauri::Monitor) -> Result Result Result<(), }; if width <= 0 || height <= 0 { restore_awareness(); - return Err("Windows did not report a usable screen size.".into()); + return Err("errWinScreenSize".into()); } let screen = GetDC(std::ptr::null_mut()); if screen.is_null() { restore_awareness(); - return Err("Windows could not open the desktop surface.".into()); + return Err("errWinDesktopDC".into()); } let memory = CreateCompatibleDC(screen); let bitmap = CreateCompatibleBitmap(screen, width, height); @@ -198,7 +192,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(), } ReleaseDC(std::ptr::null_mut(), screen); restore_awareness(); - return Err("Windows could not allocate a screenshot surface.".into()); + return Err("errWinSurfaceAlloc".into()); } let previous = SelectObject(memory, bitmap as HGDIOBJ); let copied = BitBlt( @@ -251,7 +245,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(), if copied == 0 || rows == 0 { restore_awareness(); - return Err("Windows could not copy the screen surface.".into()); + return Err("errWinSurfaceCopy".into()); } for pixel in pixels.chunks_exact_mut(4) { pixel.swap(0, 2); @@ -259,7 +253,7 @@ fn capture_windows_screen(monitor: &tauri::Monitor, output: &Path) -> Result<(), } let Some(image) = image::RgbaImage::from_raw(width as u32, height as u32, pixels) else { restore_awareness(); - return Err("Windows returned an invalid screenshot buffer.".into()); + return Err("errWinSurfaceBuffer".into()); }; let result = image .save_with_format(output, image::ImageFormat::Png) @@ -423,7 +417,7 @@ pub fn crop_session( let crop_width = (rect.width.clamp(0.0, 1.0) * width as f64).round() as u32; let crop_height = (rect.height.clamp(0.0, 1.0) * height as f64).round() as u32; if crop_width < 2 || crop_height < 2 || x >= width || y >= height { - return Err("Select an area first.".into()); + return Err("errNoSelection".into()); } let cropped = image.crop_imm(x, y, crop_width.min(width - x), crop_height.min(height - y)); let directory = screenshot_directory(app)?; @@ -523,7 +517,7 @@ fn finish_capture( app, ActionOutcome { outputs: vec![output.to_string_lossy().to_string()], - message: "Screenshot saved.".into(), + message: "outcomeSaved".into(), }, ); Ok(output.to_string_lossy().to_string()) diff --git a/src-tauri/src/drag_bridge.rs b/src-tauri/src/drag_bridge.rs index a2bebfb..a60608b 100644 --- a/src-tauri/src/drag_bridge.rs +++ b/src-tauri/src/drag_bridge.rs @@ -550,7 +550,7 @@ pub async fn show_files_in_radial( mode: Option, ) -> Result { if files.is_empty() { - return Err("No files selected.".into()); + return Err("errNoFiles".into()); } tauri::async_runtime::spawn_blocking(move || { show_radial( diff --git a/src-tauri/src/files.rs b/src-tauri/src/files.rs index d2fae27..e6d78ad 100644 --- a/src-tauri/src/files.rs +++ b/src-tauri/src/files.rs @@ -204,13 +204,11 @@ fn save_image( fn describe_write_error(output: &Path, error: std::io::Error) -> String { if error.kind() == std::io::ErrorKind::PermissionDenied { - return format!( - "Shift cannot write to {}. Allow access in System Settings > Privacy & Security > Files and Folders, or choose another output folder in Settings.", - output - .parent() - .unwrap_or(output) - .display() - ); + // The interface words this; a sentence written here could only ever be + // English, and the panel that shows it knows the language. The folder is + // what a log needs, so it goes there instead of into the message. + eprintln!("cannot write to {}", output.display()); + return "errWriteDenied".into(); } format!("Could not write {}: {error}", output.display()) } @@ -1649,20 +1647,20 @@ pub fn perform_action( on_progress: Option<&(dyn Fn(u32, u32, bool) + Sync)>, ) -> Result { if paths.is_empty() { - return Err("No files selected.".into()); + return Err("errNoFiles".into()); } if action == "reveal" { reveal_path(Path::new(&paths[0]))?; return Ok(ActionOutcome { outputs: vec![], - message: "Revealed in file manager.".into(), + message: "outcomeRevealed".into(), }); } if action == "open" { open_path(Path::new(&paths[0]))?; return Ok(ActionOutcome { outputs: vec![], - message: "Opened.".into(), + message: "outcomeOpened".into(), }); } @@ -1676,7 +1674,7 @@ pub fn perform_action( let output = pdf::merge(&pdf_paths, output_dir)?; return Ok(ActionOutcome { outputs: vec![output.to_string_lossy().to_string()], - message: "Merged PDFs.".into(), + message: "outcomeMergedPdfs".into(), }); } let image_paths: Vec = paths @@ -1688,21 +1686,21 @@ pub fn perform_action( let output = pdf::images_to_pdf(&image_paths, output_dir)?; return Ok(ActionOutcome { outputs: vec![output.to_string_lossy().to_string()], - message: "Combined images into a PDF.".into(), + message: "outcomeImagesToPdf".into(), }); } - return Err("Merge works with multiple PDFs or multiple images.".into()); + return Err("errMergeKinds".into()); } if action == "split" { if pdf_paths.is_empty() { - return Err("Split works with PDF files.".into()); + return Err("errSplitPdf".into()); } let mut outputs = Vec::new(); for path in &pdf_paths { outputs.extend(pdf::split(path, output_dir)?); } return Ok(ActionOutcome { - message: format!("Saved {} PDF pages.", outputs.len()), + message: "outcomePdfPages".into(), outputs: outputs .into_iter() .map(|path| path.to_string_lossy().to_string()) @@ -1711,14 +1709,14 @@ pub fn perform_action( } if action == "text" { if pdf_paths.is_empty() { - return Err("Text extraction currently works with PDF files.".into()); + return Err("errTextPdf".into()); } let mut outputs = Vec::new(); for path in &pdf_paths { outputs.push(pdf::extract_text(path, output_dir)?); } return Ok(ActionOutcome { - message: "Extracted PDF text.".into(), + message: "outcomePdfText".into(), outputs: outputs .into_iter() .map(|path| path.to_string_lossy().to_string()) @@ -1742,7 +1740,7 @@ pub fn perform_action( outputs.extend(pdf::to_images(path, extension, output_dir)?); } return Ok(ActionOutcome { - message: format!("Saved {} PDF pages.", outputs.len()), + message: "outcomePdfPages".into(), outputs: outputs .into_iter() .map(|path| path.to_string_lossy().to_string()) @@ -1796,12 +1794,7 @@ pub fn perform_action( let _ = fs::remove_file(&temporary); result? } - "convert" if is_pdf => { - return Err( - "Pick a supported target for this PDF: an image format, TXT, MD, DOCX or RTF." - .into(), - ) - } + "convert" if is_pdf => return Err("errPdfTarget".into()), "convert" if is_image && target @@ -1899,11 +1892,7 @@ pub fn perform_action( outputs.push(output.to_string_lossy().to_string()); } Ok(ActionOutcome { - message: if outputs.len() == 1 { - "Saved 1 file.".into() - } else { - format!("Saved {} files.", outputs.len()) - }, + message: "outcomeSaved".into(), outputs, }) } @@ -2879,7 +2868,7 @@ mod tests { None, ) .unwrap_err(); - assert!(error.contains("DOCX or RTF"), "{error}"); + assert_eq!(error, "errPdfTarget"); fs::remove_dir_all(dir).unwrap(); } diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 9055a9f..67d3a42 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -138,7 +138,7 @@ fn spawn_capture_work( let reporter = app.clone(); tauri::async_runtime::spawn(async move { let result = tauri::async_runtime::spawn_blocking(move || work(worker)).await; - if let Err(error) = result.unwrap_or_else(|_| Err("Capture was interrupted.".into())) { + if let Err(error) = result.unwrap_or_else(|_| Err("errCaptureInterrupted".into())) { report_error(&reporter, error); show_main(&reporter); } diff --git a/src-tauri/src/recording.rs b/src-tauri/src/recording.rs index 3bc9f76..d85048e 100644 --- a/src-tauri/src/recording.rs +++ b/src-tauri/src/recording.rs @@ -412,7 +412,7 @@ pub fn stop(app: &AppHandle, state: &AppState) -> Result, app, ActionOutcome { outputs: vec![info.output.clone()], - message: "Recording saved.".into(), + message: "outcomeSaved".into(), }, ); Ok(Some(info)) diff --git a/src-tauri/src/settings.rs b/src-tauri/src/settings.rs index f356154..5e2e8c9 100644 --- a/src-tauri/src/settings.rs +++ b/src-tauri/src/settings.rs @@ -109,7 +109,6 @@ pub struct WriteCheck { pub kind: String, pub path: String, pub ok: bool, - pub message: String, } fn settings_path(app: &AppHandle) -> Result { @@ -338,14 +337,15 @@ pub fn test_output_access(app: &AppHandle) -> Result, String> { let probe = directory.join(format!(".shift-write-test-{}", uuid::Uuid::new_v4())); let result = fs::write(&probe, b"Shift"); let _ = fs::remove_file(&probe); + // Only the verdict travels: the wording belongs to the interface, which + // knows the language and does not have to guess the operating system. + if let Err(error) = &result { + eprintln!("{kind} output directory is not writable: {error}"); + } WriteCheck { kind: kind.into(), path: directory.to_string_lossy().to_string(), ok: result.is_ok(), - message: match result { - Ok(()) => "Write access confirmed.".into(), - Err(error) => format!("{error}. Allow access in System Settings > Privacy & Security > Files and Folders."), - }, } }) .collect()) diff --git a/src/components/CaptureOverlay.tsx b/src/components/CaptureOverlay.tsx index f20a4ea..a296ca6 100644 --- a/src/components/CaptureOverlay.tsx +++ b/src/components/CaptureOverlay.tsx @@ -4,7 +4,8 @@ import { Check, Gauge, LoaderCircle, Mic, MicOff, ScanLine, Square, X } from "lu import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; -import { normalizeSelection } from "../lib/utils"; +import { messageFrom, normalizeSelection } from "../lib/utils"; +import { FEEDBACK } from "../lib/feedback"; import type { CaptureSession, RecordingCapabilities } from "../types"; interface Point { @@ -94,7 +95,7 @@ export function CaptureOverlay() { async function confirm() { if (busy || !selection || selection.width < 8 || selection.height < 8) { setStatus(t("dragSelect")); - window.setTimeout(() => setStatus(null), 1600); + window.setTimeout(() => setStatus(null), FEEDBACK.hint); return; } if (!isTauri()) { @@ -121,8 +122,8 @@ export function CaptureOverlay() { } } catch (error) { setBusy(false); - setStatus(String(error)); - window.setTimeout(() => setStatus(null), 3000); + setStatus(t(messageFrom(error))); + window.setTimeout(() => setStatus(null), FEEDBACK.error); } } @@ -277,12 +278,12 @@ export function CaptureOverlay() { )} {busy ? ( -
+
{status || t("processing")}
) : status ? ( -
{status}
+
{status}
) : null}
); diff --git a/src/components/Editor.tsx b/src/components/Editor.tsx index d2141da..c68b2a1 100644 --- a/src/components/Editor.tsx +++ b/src/components/Editor.tsx @@ -4,6 +4,7 @@ import { writeImage, writeText } from "@tauri-apps/plugin-clipboard-manager"; import { save } from "@tauri-apps/plugin-dialog"; import { Check, + CircleAlert, Clipboard, Copy, ExternalLink, @@ -18,7 +19,8 @@ import { useEffect, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; import { recognizeImage } from "../lib/ocr"; -import { basename, dirname, extensionOf, IS_MAC } from "../lib/utils"; +import { FEEDBACK } from "../lib/feedback"; +import { basename, dirname, extensionOf, IS_MAC, messageFrom } from "../lib/utils"; import { history } from "../lib/history"; import type { EditorInfo } from "../types"; import { ImageAnnotator } from "./ImageAnnotator"; @@ -31,8 +33,10 @@ export function Editor() { const [ocrProgress, setOcrProgress] = useState(0); const [ocrStatus, setOcrStatus] = useState(""); const [ocrRunning, setOcrRunning] = useState(false); + const [ocrFailed, setOcrFailed] = useState(false); const [pinBusy, setPinBusy] = useState(false); const [copied, setCopied] = useState(null); + const [copiedIsError, setCopiedIsError] = useState(false); const [textContent, setTextContent] = useState(""); const copyTimer = useRef(null); const sessionRef = useRef(null); @@ -85,23 +89,25 @@ export function Editor() { }; }, [session?.kind, session?.path]); - function flashCopied(label: string) { + /** The window's one transient notice. A failure must not arrive wearing a tick. */ + function flashNotice(label: string, failed = false) { if (copyTimer.current) window.clearTimeout(copyTimer.current); setCopied(label); - copyTimer.current = window.setTimeout(() => setCopied(null), 1400); + setCopiedIsError(failed); + copyTimer.current = window.setTimeout(() => setCopied(null), FEEDBACK.done); } async function copy() { if (!session) return; - if (session.kind === "image") { - await writeImage(session.path); - flashCopied(t("copy")); - } else if (session.kind === "text") { - await writeText(textContent); - flashCopied(t("copy")); - } else { - await writeText(session.path); - flashCopied(t("copy")); + // A clipboard the OS refuses is a result the user has to be told about; it + // used to fail in silence here while every other window reported it. + try { + if (session.kind === "image") await writeImage(session.path); + else if (session.kind === "text") await writeText(textContent); + else await writeText(session.path); + flashNotice(t("copy")); + } catch (error) { + flashNotice(t(messageFrom(error)), true); } } @@ -113,8 +119,12 @@ export function Editor() { filters: ext ? [{ name: ext.toUpperCase(), extensions: [ext] }] : undefined, }); if (!target) return; - await api.copyFileTo(session.path, target); - flashCopied(t("saved")); + try { + await api.copyFileTo(session.path, target); + flashNotice(t("saved")); + } catch (error) { + flashNotice(t(messageFrom(error)), true); + } } async function runOcr() { @@ -124,6 +134,7 @@ export function Editor() { setOcrRunning(true); setOcrText(""); setOcrProgress(0); + setOcrFailed(false); setOcrStatus(t("ocrRunning")); try { const source = isTauri() ? convertFileSrc(current.path) : current.path; @@ -134,12 +145,15 @@ export function Editor() { setOcrText(result.text || t("ocrEmpty")); if (result.text) { await writeText(result.text); - flashCopied(t("copyText")); + flashNotice(t("copyText")); } setOcrProgress(1); setOcrStatus(""); } catch (error) { - setOcrText(String(error)); + // Nothing was read, so the panel says only that and stays out of the way; + // the reason belongs on the notice, which is where this window reports. + setOcrFailed(true); + flashNotice(t(messageFrom(error)), true); setOcrStatus(""); } finally { setOcrRunning(false); @@ -153,7 +167,7 @@ export function Editor() { try { await api.pinImage(current.path); } catch (error) { - flashCopied(String(error).replace(/^Error:\s*/, "")); + flashNotice(t(messageFrom(error)), true); } finally { setPinBusy(false); } @@ -177,7 +191,12 @@ export function Editor() {
{name}
- @@ -229,7 +248,7 @@ export function Editor() { path={session.path} onSaved={(nextPath) => { applySession({ path: nextPath, kind: "image" }); - flashCopied(t("saved")); + flashNotice(t("saved")); }} /> ) : session.kind === "video" ? ( @@ -252,7 +271,12 @@ export function Editor() { {t("ocr")}

{t("ocrTitle")}

- @@ -272,11 +296,11 @@ export function Editor() { className="ocr-output" value={ocrText} onChange={(event) => setOcrText(event.target.value)} - placeholder={t("ocrEmpty")} + placeholder={t(ocrFailed ? "ocrNothing" : "ocrEmpty")} spellCheck={false} />
- @@ -290,8 +314,12 @@ export function Editor() { {copied ? ( -
- +
+ {copiedIsError ? : } {copied}
) : null} diff --git a/src/components/ImageAnnotator.tsx b/src/components/ImageAnnotator.tsx index 4f4db24..6aba5e3 100644 --- a/src/components/ImageAnnotator.tsx +++ b/src/components/ImageAnnotator.tsx @@ -24,6 +24,7 @@ import { import { useEffect, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; +import { messageFrom } from "../lib/utils"; type Tool = | "rectangle" @@ -305,7 +306,7 @@ export function ImageAnnotator({ path, onSaved }: Props) { if (!cancelled) image.src = url; }) .catch((reason) => { - if (!cancelled) setError(String(reason).replace(/^Error:\s*/, "")); + if (!cancelled) setError(t(messageFrom(reason))); }); } else { image.src = "/demo-preview.svg"; @@ -382,7 +383,7 @@ export function ImageAnnotator({ path, onSaved }: Props) { await writeImage(saved); } } catch (reason) { - setError(String(reason)); + setError(t(messageFrom(reason))); } finally { setBusy(false); setCopying(false); @@ -685,7 +686,7 @@ export function ImageAnnotator({ path, onSaved }: Props) { event.currentTarget.releasePointerCapture(event.pointerId); }} /> - {error ?
{error}
: null} + {error ?
{error}
: null} {textPoint ? (
) : hotkeys && !hotkeys.live ? ( -
+
{hotkeys.others.length > 0 ? t("hotkeysDead") : t("hotkeysNotLive")} @@ -858,7 +894,7 @@ export function MainWindow() { }`} >
))} @@ -1331,7 +1372,7 @@ export function MainWindow() {
{languageError ? ( -
+
{languageError}
) : null} @@ -1361,7 +1402,7 @@ export function MainWindow() {

{t("runtimeSummary")}

{runtimeError ? ( -
+
{runtimeError} {runtimeInstallHelp ? (
); } diff --git a/src/components/PinnedImage.tsx b/src/components/PinnedImage.tsx index ac3fa53..b16d620 100644 --- a/src/components/PinnedImage.tsx +++ b/src/components/PinnedImage.tsx @@ -5,7 +5,7 @@ import { Copy, X } from "lucide-react"; import { useEffect, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; -import { decodeHexParam } from "../lib/utils"; +import { decodeHexParam, messageFrom } from "../lib/utils"; interface PinnedPreview { id: number; @@ -68,7 +68,7 @@ export function PinnedImage() { .then(apply) .catch((reason) => { if (disposed) return; - setError(String(reason).replace(/^Error:\s*/, "")); + setError(t(messageFrom(reason))); void api.pinReady(null); }); }; @@ -102,7 +102,7 @@ export function PinnedImage() { } if (error) { - return
{error}
; + return
{error}
; } return ( diff --git a/src/components/RadialMenu.tsx b/src/components/RadialMenu.tsx index 9fe7faf..9f5fc0c 100644 --- a/src/components/RadialMenu.tsx +++ b/src/components/RadialMenu.tsx @@ -49,7 +49,8 @@ import { type WedgeOrders, } from "../lib/radialOrder"; import { recognizeImage } from "../lib/ocr"; -import { formatBytes } from "../lib/utils"; +import { formatBytes, messageFrom } from "../lib/utils"; +import { FEEDBACK, outcomeMessage } from "../lib/feedback"; import type { FileInfo, RadialContext } from "../types"; import { useI18n } from "../i18n"; import { SharePanel } from "./SharePanel"; @@ -226,11 +227,6 @@ function buildWedge( return actionWedge(id, t(wedgeLabelKey(id)), WEDGE_ICONS[id] ?? File); } -function messageOf(error: unknown) { - const message = error instanceof Error ? error.message : String(error); - return message.replace(/^Error:\s*/, "") || "Unknown error"; -} - function waitForPaint() { return new Promise((resolve) => { requestAnimationFrame(() => { @@ -294,7 +290,7 @@ export function RadialMenu() { const wedgeCount = Math.max(wedges.length, 1); const hoveredWedge = hovered !== null ? wedges[hovered] : undefined; - function flash(message: string, duration = 1600) { + function flash(message: string, duration: number = FEEDBACK.hint) { if (statusTimer.current) window.clearTimeout(statusTimer.current); setError(null); setStatus(message); @@ -304,7 +300,9 @@ export function RadialMenu() { function showError(reason: unknown) { if (statusTimer.current) window.clearTimeout(statusTimer.current); setStatus(null); - setError(messageOf(reason)); + // The backend names a failure with a code, so the code is looked up here; an + // unrecognised sentence is shown as it came rather than swallowed. + setError(t(messageFrom(reason)) || t("unknownError")); } function applyContext(next: RadialContext | null) { @@ -533,7 +531,7 @@ export function RadialMenu() { } } } catch (error) { - flash(String(error), 2400); + showError(error); } }) .then((stop) => { @@ -560,11 +558,11 @@ export function RadialMenu() { currentKind !== "presentation" && currentKind !== "spreadsheet" ) { - flash(t("comingSoon"), 1800); + flash(t("comingSoon"), FEEDBACK.hint); return; } setBusy(true); - flash(t("processing"), 12000); + flash(t("processing"), FEEDBACK.running); await waitForPaint(); try { const outcome = await api.performFileAction( @@ -576,11 +574,11 @@ export function RadialMenu() { packaging ? t("fileActionPackaging") : t("fileActionPageProgress", { done, total }), - 120000, + FEEDBACK.hold, ); }, ); - flash(outcome.message || t("saved"), 900); + flash(outcomeMessage(outcome.message, outcome.outputs.length, t), FEEDBACK.done); window.setTimeout(() => void api.hideRadial(), 850); } catch (error) { showError(error); @@ -604,20 +602,22 @@ export function RadialMenu() { current.fileInfo[0]?.extension ?? "", ); if (activeFormats.length === 0) { - flash(t("unsupported"), 1600); + flash(t("unsupported"), FEEDBACK.hint); return; } setRing("formats"); ringRef.current = "formats"; setHovered(null); hoveredRef.current = null; - flash(t("chooseFormat"), 1200); + flash(t("chooseFormat"), FEEDBACK.hint); return; } if (id === "pdfOcr") { setBusy(true); - flash(t("processing"), 120000); + // Page rendering reports nothing until the first page is read, which on a + // long PDF outlasts any short-lived notice, so this one cannot expire. + flash(t("processing"), FEEDBACK.hold); await waitForPaint(); try { const pages = await api.renderPdfPages(current.files[0]); @@ -626,12 +626,12 @@ export function RadialMenu() { for (let index = 0; index < pages.length; index += 1) { flash( `${t("ocrRunning")} ${index + 1}/${pages.length}`, - 120000, + FEEDBACK.hold, ); const result = await recognizeImage(convertFileSrc(pages[index]), (progress) => { flash( `${t("ocrRunning")} ${index + 1}/${pages.length} · ${Math.round(progress * 100)}%`, - 120000, + FEEDBACK.hold, ); }); chunks.push(`--- Page ${index + 1} ---\n${result.text}`); @@ -657,14 +657,14 @@ export function RadialMenu() { await api.openInEditor(current.files[0]); void api.hideRadial(); } catch (error) { - flash(String(error), 2200); + showError(error); } return; } if (id === "extractAudio" || id === "plain") { setBusy(true); - flash(t("processing"), 12000); + flash(t("processing"), FEEDBACK.running); await waitForPaint(); try { const outcome = await api.performFileAction( @@ -672,7 +672,7 @@ export function RadialMenu() { current.files, id === "extractAudio" ? "m4a" : "txt", ); - flash(outcome.message || t("saved"), 900); + flash(outcomeMessage(outcome.message, outcome.outputs.length, t), FEEDBACK.done); window.setTimeout(() => void api.hideRadial(), 850); } catch (error) { showError(error); @@ -701,15 +701,15 @@ export function RadialMenu() { }; const action = mapping[id]; if (!action) { - flash(t("comingSoon")); + flash(t("comingSoon"), FEEDBACK.hint); return; } setBusy(true); - flash(t("processing"), 12000); + flash(t("processing"), FEEDBACK.running); await waitForPaint(); try { const outcome = await api.performFileAction(action, current.files); - flash(outcome.message || t("saved"), 900); + flash(outcomeMessage(outcome.message, outcome.outputs.length, t), FEEDBACK.done); window.setTimeout(() => void api.hideRadial(), 850); } catch (error) { showError(error); @@ -917,7 +917,7 @@ export function RadialMenu() { ) : null} {!error && !busy && !sharePaths && (status || context.dragging) ? ( -
+
{hoveredWedge ? ( ring === "formats" ? ( <> @@ -954,7 +954,7 @@ export function RadialMenu() { }} onNotice={(message) => { shareNoticeRef.current = true; - flash(message, 2_600); + flash(message, FEEDBACK.notice); }} /> ) : null} diff --git a/src/components/RecorderHud.tsx b/src/components/RecorderHud.tsx index 640651b..16f6bd0 100644 --- a/src/components/RecorderHud.tsx +++ b/src/components/RecorderHud.tsx @@ -3,7 +3,7 @@ import { listen } from "@tauri-apps/api/event"; import { useEffect, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; -import { formatDuration } from "../lib/utils"; +import { formatDuration, messageFrom } from "../lib/utils"; import type { RecordingInfo } from "../types"; export function RecorderHud() { @@ -42,7 +42,7 @@ export function RecorderHud() { try { await api.stopRecording(); } catch (stopError) { - setError(String(stopError)); + setError(t(messageFrom(stopError))); } finally { setStopping(false); } @@ -55,7 +55,11 @@ export function RecorderHud() {
{recording ? formatDuration(now - recording.startedAt) : "00:00"} - + {error || t("record")}
diff --git a/src/components/ResultCard.tsx b/src/components/ResultCard.tsx index d5184e3..bb1f870 100644 --- a/src/components/ResultCard.tsx +++ b/src/components/ResultCard.tsx @@ -6,7 +6,7 @@ import { Copy, FileVideo, FolderSearch, Images, Send } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; -import { basename, decodeHexParam } from "../lib/utils"; +import { basename, decodeHexParam, messageFrom } from "../lib/utils"; import type { CaptureResult } from "../types"; const THUMB_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "gif", "bmp", "tiff", "tif"]; @@ -75,7 +75,7 @@ export function ResultCard() { else await writeText(info.path); setNote(t("copied")); } catch (error) { - setNote(String(error)); + setNote(t(messageFrom(error))); } } diff --git a/src/components/SetupPanel.tsx b/src/components/SetupPanel.tsx index 83ddcb5..c6dc86b 100644 --- a/src/components/SetupPanel.tsx +++ b/src/components/SetupPanel.tsx @@ -48,6 +48,16 @@ export function SetupPanel({ const patch = (id: Row["id"], next: Partial) => setRows((current) => current.map((row) => (row.id === id ? { ...row, ...next } : row))); + // Escape leaves the guided flow the way it leaves every other panel. Everything + // the flow checks is re-runnable from Settings, so closing it loses nothing. + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.key === "Escape") onDone(); + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [onDone]); + const refresh = useCallback(async () => { setRows((current) => current.map((row) => ({ ...row, state: "checking" as State }))); @@ -79,7 +89,7 @@ export function SetupPanel({ "folders", broken.length === 0 ? { state: "ok", detail: t("setupFoldersOk") } - : { state: "problem", detail: broken.map((check) => check.message).join(" ") }, + : { state: "problem", detail: t("accessDenied") }, ); }) .catch(() => patch("folders", { state: "unknown", detail: t("setupCheckFailed") })); diff --git a/src/components/SharePanel.tsx b/src/components/SharePanel.tsx index 6ec01df..70ff198 100644 --- a/src/components/SharePanel.tsx +++ b/src/components/SharePanel.tsx @@ -17,7 +17,7 @@ import { useEffect, useRef, useState, type DragEvent } from "react"; import { useI18n } from "../i18n"; import { api } from "../lib/api"; import { parseSharePaths, SHARE_PATHS_TYPE } from "../lib/dragOut"; -import { basename, dirname, formatBytes } from "../lib/utils"; +import { basename, dirname, formatBytes, messageFrom } from "../lib/utils"; import type { SharePeer, ShareTransfer } from "../types"; interface SharePanelProps { @@ -48,7 +48,8 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) { const [searching, setSearching] = useState(true); const [busyPeer, setBusyPeer] = useState(null); const [progress, setProgress] = useState(null); - const [failed, setFailed] = useState(false); + /** Why the last send failed, in the user's language; the panel reports it once. */ + const [failure, setFailure] = useState(null); const sendingRef = useRef(false); const [selectedPaths, setSelectedPaths] = useState(paths); const [dragOverPeer, setDragOverPeer] = useState(null); @@ -101,7 +102,7 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) { async function send(peer: SharePeer, files: string[] = selectedPaths) { if (busyPeer || files.length === 0) return; setBusyPeer(peer.id); - setFailed(false); + setFailure(null); setProgress(null); setWaitingFor(peer.name); sendingRef.current = true; @@ -117,22 +118,28 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) { ); onClose(); } catch (error) { - const message = String(error); - setFailed(true); + const message = messageFrom(error); setProgress(null); setWaitingFor(null); const name = files.length > 1 ? t("shareFilesCount", { count: files.length }) : basename(files[0]); - if (message.includes("share-peer-gone")) onNotice(t("sharePeerGone")); - else if (message.includes("share-unreachable")) onNotice(t("shareUnreachable")); - // The peer's own answer arrives as an error, so these are not failures of ours. - else if (message.includes("share-declined")) - onNotice(t("shareDeclined", { name, peer: peer.name })); - else if (message.includes("share-timeout")) - onNotice(t("shareTimeout", { name, peer: peer.name })); - else onNotice(t("shareFailed", { name })); + // The peer's own answer arrives as an error, so a decline or a timeout is + // not a failure of ours and says so. One message, in the panel that raised + // it: it used to appear twice, once as a banner and once as a toast that + // named a different reason. + setFailure( + message.includes("share-peer-gone") + ? t("sharePeerGone") + : message.includes("share-unreachable") + ? t("shareUnreachable") + : message.includes("share-declined") + ? t("shareDeclined", { name, peer: peer.name }) + : message.includes("share-timeout") + ? t("shareTimeout", { name, peer: peer.name }) + : t("shareFailed", { name }), + ); } finally { sendingRef.current = false; setBusyPeer(null); @@ -141,7 +148,7 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) { function searchAgain() { setSearching(true); - setFailed(false); + setFailure(null); if (!isTauri()) { setSearching(false); return; @@ -366,13 +373,10 @@ export function SharePanel({ paths, onClose, onNotice }: SharePanelProps) {
) : null} - {failed ? ( -
+ {failure ? ( +
- {t("shareFailed", { - name: - paths.length > 1 ? t("shareFilesCount", { count: paths.length }) : basename(paths[0]), - })} + {failure}
) : null} diff --git a/src/components/UpdatePanel.tsx b/src/components/UpdatePanel.tsx index 8b62fa7..ba6e750 100644 --- a/src/components/UpdatePanel.tsx +++ b/src/components/UpdatePanel.tsx @@ -159,7 +159,13 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P ) : null} {percent !== null ? ( -
+
{progress ? `${formatBytes(progress.downloaded)} / ${formatBytes(progress.total)}` : ""} @@ -175,7 +181,10 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P ) : null} {status?.message && (failed || verified) ? ( -
+
{verified ? t("updateVerified") : status.message}
) : null} @@ -183,7 +192,7 @@ export function UpdatePanel({ feedUrl, autoCheck, onAutoCheckChange, system }: P {/* An install that could not run leaves the verified download in place, so it is reported beside the button instead of rewriting the status. */} {installError ? ( -
+
{installError}
) : null} diff --git a/src/i18n.ts b/src/i18n.ts index 0990ca7..9f3dc04 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -1,6 +1,7 @@ import { isTauri } from "@tauri-apps/api/core"; import { useCallback, useEffect, useState } from "react"; import { api } from "./lib/api"; +import { messageFrom } from "./lib/utils"; export type Lang = "en" | "zh"; @@ -54,12 +55,17 @@ const messages: Record> = { merge: "Merge", split: "Split", files: "files", - file: "file", - ready: "Ready", processing: "Processing…", fileActionPageProgress: "Converting page {done}/{total}…", fileActionPackaging: "Building document…", saved: "Saved", + outcomeSaved: "Saved {count} files", + outcomePdfPages: "Saved {count} PDF pages", + outcomeRevealed: "Shown in the folder", + outcomeOpened: "Opened", + outcomeMergedPdfs: "PDFs merged", + outcomeImagesToPdf: "Images combined into a PDF", + outcomePdfText: "PDF text extracted", copy: "Copy", pin: "Pin", pinLoadFailed: "The pinned image could not be displayed.", @@ -77,16 +83,39 @@ const messages: Record> = { ocrTitle: "Extract text", ocrRunning: "Reading text…", ocrEmpty: "No readable text found.", + ocrNothing: "Nothing was read.", extractText: "Extract text", revealFile: "Show in folder", actionFailed: "That action could not be completed", + errNoFiles: "No files selected.", + errNoMonitor: "No display was found for this capture.", + errCaptureBlocked: + "Screen capture was cancelled or blocked. Allow Screen Recording in System Settings.", + errCaptureFailed: "Screen capture failed.", + errCaptureInterrupted: "Capture was interrupted.", + errCaptureToolMissing: "Install grim or gnome-screenshot to capture the screen on Linux.", + errNoSelection: "Select an area first.", + errScreenPermission: + "Screen Recording permission is required. Enable Shift in System Settings > Privacy & Security > Screen Recording, and restart Shift if macOS asks.", + errMergeKinds: "Merge works with several PDFs or several images.", + errSplitPdf: "Split works with PDF files.", + errTextPdf: "Text extraction works with PDF files.", + errPdfTarget: "Pick a supported target for this PDF: an image format, TXT, MD, DOCX or RTF.", + errNoActionResult: "The action finished without a result.", + errWinScreenSize: "Windows did not report a usable screen size.", + errWinDesktopDC: "Windows could not open the desktop surface.", + errWinSurfaceAlloc: "Windows could not allocate a screenshot surface.", + errWinSurfaceCopy: "Windows could not copy the screen surface.", + errWinSurfaceBuffer: "Windows returned an invalid screenshot buffer.", + errWriteDenied: + "Shift cannot write to the output folder. Allow access in System Settings > Privacy & Security > Files and Folders, or choose another folder in Settings.", + unknownError: "Unknown error", comingSoon: "Coming soon.", openScreenSettings: "Open screen recording settings", tools: "Tools", unsupported: "No formats for this file type", homeDropTitle: "Drop files to get started", homeDropHint: "Drop a file on a button to run that action.", - ocrUnsupported: "OCR works on image files only.", convertFiles: "Convert files", fileTools: "File tools", nothingYet: "Nothing yet", @@ -142,6 +171,8 @@ const messages: Record> = { checking: "Checking…", checkAccess: "Check folders", accessOk: "Write access confirmed.", + accessDenied: + "This folder cannot be written. Allow access in System Settings > Privacy & Security > Files and Folders, or choose another folder.", runtimeComponents: "Runtime components", runtimeOpenPanel: "Open Runtime components", languageSaveFailed: "The language could not be saved. Try again.", @@ -194,7 +225,6 @@ const messages: Record> = { updateAutoCheck: "Check for updates daily", updateBody: "Releases come from this repository’s release branch. Every download is re-hashed and must match the manifest before it can be installed. Installing replaces this copy and restarts it; a conversion still running is interrupted.", - radial: "Radial rings", setupTitle: "Before you start", setupIntro: "Shift works offline and installs nothing. These are the four things that can quietly stop it working on this machine.", setupRecheck: "Run the checks again", @@ -281,12 +311,17 @@ const messages: Record> = { merge: "合并", split: "拆分", files: "个文件", - file: "个文件", - ready: "就绪", processing: "处理中…", fileActionPageProgress: "正在转换第 {done}/{total} 页…", fileActionPackaging: "正在生成文档…", saved: "已保存", + outcomeSaved: "已保存 {count} 个文件", + outcomePdfPages: "已保存 {count} 页 PDF", + outcomeRevealed: "已在文件夹中显示", + outcomeOpened: "已打开", + outcomeMergedPdfs: "已合并 PDF", + outcomeImagesToPdf: "已将图片合成为 PDF", + outcomePdfText: "已提取 PDF 文字", copy: "复制", pin: "钉在屏幕上", pinLoadFailed: "无法显示钉住的图片。", @@ -304,16 +339,36 @@ const messages: Record> = { ocrTitle: "提取文字", ocrRunning: "正在识别文字…", ocrEmpty: "没有识别到可读文字。", + ocrNothing: "未能读到文字。", extractText: "提取文字", revealFile: "在文件夹中显示", actionFailed: "操作未能完成", + errNoFiles: "没有选择文件。", + errNoMonitor: "没有找到可用于截取的显示器。", + errCaptureBlocked: "截图被取消或被阻止,请在系统设置中允许屏幕录制。", + errCaptureFailed: "屏幕截取失败。", + errCaptureInterrupted: "截取过程被中断。", + errCaptureToolMissing: "在 Linux 上需要安装 grim 或 gnome-screenshot 才能截屏。", + errNoSelection: "请先框选一个区域。", + errScreenPermission: "需要屏幕录制权限。请在「系统设置 › 隐私与安全性 › 屏幕录制」中允许 Shift,如 macOS 提示请重启应用。", + errMergeKinds: "合并仅支持多个 PDF 或多个图片。", + errSplitPdf: "拆分仅支持 PDF 文件。", + errTextPdf: "提取文字仅支持 PDF 文件。", + errPdfTarget: "请为该 PDF 选择受支持的目标:图片格式、TXT、MD、DOCX 或 RTF。", + errNoActionResult: "操作已完成,但没有产生结果。", + errWinScreenSize: "Windows 未报告可用的屏幕尺寸。", + errWinDesktopDC: "Windows 无法打开桌面表面。", + errWinSurfaceAlloc: "Windows 无法分配截图所需的表面。", + errWinSurfaceCopy: "Windows 无法复制桌面表面。", + errWinSurfaceBuffer: "Windows 返回的截图数据无效。", + errWriteDenied: "Shift 无法写入输出目录。请在「系统设置 › 隐私与安全性 › 文件与文件夹」中允许,或在设置中改用其他目录。", + unknownError: "未知错误", comingSoon: "该功能即将推出。", openScreenSettings: "打开屏幕录制设置", tools: "工具", unsupported: "此文件类型暂时没有可用格式", homeDropTitle: "拖入文件开始处理", homeDropHint: "把文件拖到对应按钮上,执行该操作。", - ocrUnsupported: "文字识别仅支持图片格式。", convertFiles: "文件转换", fileTools: "文件工具", nothingYet: "暂无内容", @@ -334,6 +389,9 @@ const messages: Record> = { shareFilesCount: "{count} 个文件", shareReceived: "{peer} 给你发送了 {name}。", shareFailed: "{name} 发送失败。", + sharePeerGone: "该设备已不可达。", + shareUnreachable: "设备拒绝了连接,请检查它的防火墙设置。", + shareSendingTo: "正在将 {name} 发送到 {peer}", shareNoticeKicker: "{peer} 想发送一个文件给你", shareNoticeAccept: "接收", shareNoticeDecline: "拒绝", @@ -341,9 +399,6 @@ const messages: Record> = { shareWaiting: "等待 {peer} 确认接收…", shareDeclined: "{peer} 拒绝了 {name}。", shareTimeout: "{peer} 未应答,{name} 未发送。", - sharePeerGone: "该设备已不可达。", - shareUnreachable: "设备拒绝了连接,请检查它的防火墙设置。", - shareSendingTo: "正在将 {name} 发送到 {peer}", shareMac: "Mac", shareWindows: "Windows", shareLinux: "Linux", @@ -368,6 +423,7 @@ const messages: Record> = { checking: "检测中…", checkAccess: "检测目录", accessOk: "写入权限正常。", + accessDenied: "该目录无法写入。请在「系统设置 › 隐私与安全性 › 文件与文件夹」中允许,或改用其他目录。", runtimeComponents: "运行组件", runtimeOpenPanel: "打开运行组件", languageSaveFailed: "语言设置保存失败,请重试。", @@ -418,7 +474,6 @@ const messages: Record> = { updateAutoCheck: "每天自动检查更新", updateBody: "更新包来自本仓库的 release 分支。下载后会重新计算 SHA256,只有与清单一致才允许安装。安装会替换当前版本并自动重启,正在进行的转换会被中断。", - radial: "环形菜单", setupTitle: "开始前先检查", setupIntro: "Shift 全程离线运行,也不会往系统里装任何东西。以下四项是唯一可能让它在当前电脑上悄悄失效的地方。", setupRecheck: "重新检查", @@ -474,7 +529,7 @@ export function publishLang(lang: Lang) { void api.setLanguage(lang).catch((error) => { window.dispatchEvent( new CustomEvent("shift:language-error", { - detail: String(error).replace(/^Error:\s*/, ""), + detail: messageFrom(error), }), ); }); @@ -491,6 +546,17 @@ export function translate(lang: Lang, key: string, vars?: Record): string { + return translate(getInitialLang(), key, vars); +} + export function useI18n() { const [lang, setLangState] = useState(getInitialLang); useEffect(() => { diff --git a/src/lib/api.ts b/src/lib/api.ts index f600a7f..eef6340 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -58,7 +58,7 @@ async function performFileAction( if (event.payload.jobId !== jobId) return; if (event.payload.error) rejectOutcome(new Error(event.payload.error)); else if (event.payload.outcome) resolveOutcome(event.payload.outcome); - else rejectOutcome(new Error("File action returned no result.")); + else rejectOutcome(new Error("errNoActionResult")); }, ); const unlistenProgress = onProgress diff --git a/src/lib/feedback.test.ts b/src/lib/feedback.test.ts new file mode 100644 index 0000000..639cf70 --- /dev/null +++ b/src/lib/feedback.test.ts @@ -0,0 +1,83 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; + +import { outcomeMessage } from "./feedback.ts"; + +// A dictionary stand-in that shows what a lookup asked for, so the test reads as +// "which words did the interface choose" rather than as a copy of i18n. +const phrase = (key: string, vars?: Record) => + vars ? `${key}:${vars.count}` : key; + +test("a named outcome is worded by the interface, not by the backend", () => { + assert.equal(outcomeMessage("outcomePdfText", 1, phrase), "outcomePdfText"); + assert.equal(outcomeMessage("outcomePdfPages", 12, phrase), "outcomePdfPages:12"); +}); + +test("one output is not counted out loud", () => { + assert.equal(outcomeMessage("outcomeSaved", 1, phrase), "saved"); + assert.equal(outcomeMessage("outcomeSaved", 4, phrase), "outcomeSaved:4"); +}); + +test("an unknown token falls back instead of being shown as-is", () => { + // An older backend still sending sentences, or a newer one naming something + // this build has no words for: neither may reach the screen verbatim. + assert.equal(outcomeMessage("Saved 1 file.", 1, phrase), "saved"); + assert.equal(outcomeMessage("outcomeFutureThing", 3, phrase), "saved"); +}); + +test("every code the backend may name has words in both languages", async () => { + // `err*` and `outcome*` keys are looked up by the token the backend raised, so + // no `t("…")` call names them and a stale one would pass for dead. Read the + // Rust sources and require each code they raise to be translated. + const fs = await import("node:fs"); + const path = await import("node:path"); + const root = path.join(process.cwd(), "src-tauri", "src"); + const raised = new Set(); + for (const entry of fs.readdirSync(root)) { + if (!entry.endsWith(".rs")) continue; + const text = fs.readFileSync(path.join(root, entry), "utf8"); + for (const match of text.matchAll(/"(err[A-Z]\w*|outcome[A-Z]\w*)"/g)) { + raised.add(match[1]); + } + } + assert.ok(raised.size > 0, "the backend raises no codes at all"); + // The dictionary is read as text rather than imported: it pulls in React and the + // Tauri bridge, neither of which has a webview to talk to in a test run. + const i18n = fs.readFileSync(path.join(process.cwd(), "src", "i18n.ts"), "utf8"); + const blocks = { + en: i18n.slice(i18n.indexOf(" en: {"), i18n.indexOf(" zh: {")), + zh: i18n.slice(i18n.indexOf(" zh: {")), + }; + for (const code of raised) { + for (const lang of ["en", "zh"] as const) { + assert.ok( + new RegExp(`^\\s{4}${code}:`, "m").test(blocks[lang]), + `${code} is raised by Rust but has no ${lang} wording`, + ); + } + } + + // An outcome that is translated but absent from the two sets below still shows + // something - just the plain "Saved", which quietly loses what happened. + const here = await import("./feedback.ts"); + for (const code of raised) { + if (!code.startsWith("outcome")) continue; + const worded = here.outcomeMessage(code, 3, (key) => (key === "saved" ? "" : key)); + assert.equal(worded, code, `${code} is named by Rust but not worded here`); + } +}); + +test("both dictionaries offer exactly the same words", async () => { + // A key missing from one dictionary falls back to the other in silence, so a + // Chinese user reads English and nothing appears to have gone wrong. Listing + // them in one order is what keeps the pair readable, so assert that too. + const fs = await import("node:fs"); + const path = await import("node:path"); + const i18n = fs.readFileSync(path.join(process.cwd(), "src", "i18n.ts"), "utf8"); + const keys = (block: string) => + [...block.matchAll(/^\s{4}([A-Za-z0-9_]+):/gm)].map((match) => match[1]); + const en = keys(i18n.slice(i18n.indexOf(" en: {"), i18n.indexOf(" zh: {"))); + const zh = keys(i18n.slice(i18n.indexOf(" zh: {"))); + assert.ok(en.length > 0, "neither dictionary was found in the source"); + assert.deepEqual(zh, en, "the two dictionaries list different keys"); +}); diff --git a/src/lib/feedback.ts b/src/lib/feedback.ts new file mode 100644 index 0000000..efbc0bd --- /dev/null +++ b/src/lib/feedback.ts @@ -0,0 +1,56 @@ +/** + * How long each class of transient message stays on screen, in every window. + * + * The same news used to be shown for six different lengths - a failed action for + * 2.2s here and 3.8s there, the identical share result for 2.6s in the ring and + * 3.6s in the main window - which reads as a different app each time. One ladder, + * and a message of the same kind takes the same time wherever it lands. + */ +export const FEEDBACK = { + /** A thing finished. */ + done: 1400, + /** A short prompt about the gesture in progress. */ + hint: 1800, + /** A result the user asked for, with no follow-up needed. */ + notice: 2600, + /** Something failed; the sentence is long and has to be read. */ + error: 3800, + /** A task is running; the next progress line replaces this one. */ + running: 12_000, + /** A task is running and reports progress slowly, so nothing may expire. */ + hold: 120_000, +} as const; + +/** + * The outcome keys Rust is allowed to name. + * + * A result used to arrive as an English sentence written in Rust, so a Chinese + * interface answered "Convert" with `Saved 1 file.` while it answered every other + * action in Chinese. Rust now names the outcome and this decides the wording, so + * the count comes from the outputs rather than a number baked into a sentence. + */ +const PLAIN_OUTCOMES = new Set([ + "outcomeRevealed", + "outcomeOpened", + "outcomeMergedPdfs", + "outcomeImagesToPdf", + "outcomePdfText", +]); +/** The two that count outputs, so one output needs no number at all. */ +const COUNTED_OUTCOMES = new Set(["outcomeSaved", "outcomePdfPages"]); + +/** + * Word an action's result. Anything Rust does not name - a plain save, or a build + * whose Rust is older than this list - is simply "saved", never a raw token. + */ +export function outcomeMessage( + message: string, + outputs: number, + translate: (key: string, vars?: Record) => string, +): string { + if (PLAIN_OUTCOMES.has(message)) return translate(message); + if (COUNTED_OUTCOMES.has(message) && outputs !== 1) { + return translate(message, { count: outputs }); + } + return translate("saved"); +} diff --git a/src/lib/useUpdate.ts b/src/lib/useUpdate.ts index ae0f745..0400eb7 100644 --- a/src/lib/useUpdate.ts +++ b/src/lib/useUpdate.ts @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { api } from "./api"; +import { messageFrom } from "./utils"; import type { UpdateProgress, UpdateStatus } from "../types"; export interface UpdateFlow { @@ -92,7 +93,7 @@ export function useUpdateFlow(): UpdateFlow { // moment before the windows close. } catch (error) { if (mounted.current) { - setInstallError(String(error).replace(/^Error:\s*/, "")); + setInstallError(messageFrom(error)); setInstalling(false); } } diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 3ad034c..5c4cba2 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -2,6 +2,18 @@ export function basename(path: string): string { return path.split(/[\\/]/).pop() || path; } +/** + * The one way a thrown value becomes text a user can read. + * + * A Rust error arrives as a plain string and a JS-layer error as a real `Error`, + * and `String(error)` on the second keeps its `Error: ` prefix, so the same + * failure used to read one way in the main window and another in the ring. + */ +export function messageFrom(error: unknown): string { + const message = error instanceof Error ? error.message : String(error); + return message.replace(/^Error:\s*/, "").trim(); +} + export const IS_MAC = /Mac/i.test(navigator.platform) || /Mac OS X/i.test(navigator.userAgent); export function dirname(path: string): string { diff --git a/src/styles.css b/src/styles.css index 0566db3..7252d4f 100644 --- a/src/styles.css +++ b/src/styles.css @@ -26,6 +26,10 @@ --text-xl: 21px; --text-hero: clamp(28px, 3vw, 38px); + /* A control that cannot be used reads the same everywhere: dimmed, no pointer, + no hover answer. Each panel used to invent its own dimming. */ + --dimmed: 0.55; + --radius-sm: 13px; --radius-md: 16px; } @@ -86,6 +90,7 @@ button { } button:focus-visible, +input:focus-visible, textarea:focus-visible, a:focus-visible { outline: 2px solid rgba(242, 106, 51, 0.58); @@ -131,7 +136,9 @@ kbd { position: fixed; left: 50%; bottom: 26px; - z-index: 20; + /* Above every sheet of this window (settings 40, share 61, setup 60), so a + result never lands behind the panel that caused it. */ + z-index: 70; max-width: min(620px, 80vw); transform: translateX(-50%); padding: 12px 18px; @@ -264,7 +271,7 @@ kbd { .radial-label span { max-width: 100px; overflow: hidden; - font-size: 13px; + font-size: var(--text-xs); font-weight: 720; line-height: 1.02; letter-spacing: -0.01em; @@ -289,7 +296,7 @@ kbd { } .radial-label.is-format span { - font-size: 14px; + font-size: var(--text-sm); font-weight: 780; letter-spacing: 0.08em; } @@ -568,7 +575,7 @@ kbd { color: #5b3a2b; background: rgba(255, 255, 255, 0.72); box-shadow: none; - font-size: 11.5px; + font-size: var(--text-3xs); font-weight: 650; backdrop-filter: blur(8px); } @@ -641,7 +648,7 @@ kbd { color: #604032; background: rgba(255, 248, 241, 0.76); box-shadow: 0 9px 28px rgba(74, 37, 20, 0.12); - font-size: 12.5px; + font-size: var(--text-2xs); font-weight: 560; white-space: nowrap; backdrop-filter: blur(16px); @@ -937,7 +944,7 @@ kbd { } .recorder-copy strong { - font-size: 18px; + font-size: var(--text-lg); font-variant-numeric: tabular-nums; letter-spacing: 0.02em; } @@ -974,12 +981,13 @@ kbd { cursor: pointer; } -.recorder-stop:hover { +.recorder-stop:hover:not(:disabled) { background: #f05b5f; } .recorder-stop:disabled { - opacity: 0.7; + opacity: var(--dimmed); + cursor: default; } /* ------------------------------------------------------------------------- */ @@ -1067,12 +1075,18 @@ kbd { cursor: pointer; } -.editor-button:hover, -.editor-secondary:hover { +.editor-button:hover:not(:disabled), +.editor-secondary:hover:not(:disabled) { color: #44281b; background: white; } +.editor-button:disabled, +.editor-secondary:disabled { + opacity: var(--dimmed); + cursor: default; +} + .editor-button.is-active { border-color: rgba(242, 106, 51, 0.28); color: #c84c20; @@ -1184,7 +1198,7 @@ kbd { cursor: pointer; } -.annotator-tool:hover { +.annotator-tool:hover:not(:disabled) { color: white; background: rgba(255, 255, 255, 0.1); } @@ -1200,7 +1214,7 @@ kbd { } .annotator-tool:disabled { - opacity: 0.35; + opacity: var(--dimmed); cursor: default; } @@ -1275,6 +1289,10 @@ kbd { outline: none; } +.annotator-text-entry:focus-within { + border-color: rgba(242, 106, 51, 0.6); +} + .annotator-text-entry button { width: 30px; height: 30px; @@ -1298,7 +1316,7 @@ kbd { align-items: center; gap: 14px; color: rgba(255, 255, 255, 0.75); - font-size: 13px; + font-size: var(--text-xs); } .editor-text-preview { @@ -1312,7 +1330,7 @@ kbd { color: #f3ece7; background: rgba(31, 28, 27, 0.92); font-family: "SF Mono", "Cascadia Code", ui-monospace, monospace; - font-size: 12px; + font-size: var(--text-2xs); line-height: 1.7; white-space: pre-wrap; word-break: break-word; @@ -1402,7 +1420,7 @@ kbd { height: 4px; margin-top: 8px; overflow: hidden; - border-radius: 99px; + border-radius: 999px; background: #ece1d9; } @@ -1422,7 +1440,7 @@ kbd { padding: 13px; resize: none; border: 1px solid rgba(90, 53, 34, 0.11); - border-radius: 13px; + border-radius: var(--radius-sm); color: #453025; background: white; font-family: "SF Mono", "Cascadia Code", ui-monospace, monospace; @@ -1432,8 +1450,8 @@ kbd { .ocr-output:focus { outline: none; - border-color: rgba(235, 104, 51, 0.42); - box-shadow: 0 0 0 3px rgba(235, 104, 51, 0.08); + border-color: rgba(242, 106, 51, 0.42); + box-shadow: 0 0 0 3px rgba(242, 106, 51, 0.08); } .ocr-actions { @@ -1442,6 +1460,11 @@ kbd { margin-top: 12px; } +.editor-toast.is-error { + color: #ffe4dd; + background: rgba(126, 40, 22, 0.92); +} + .editor-toast { position: absolute; left: 50%; @@ -1458,7 +1481,7 @@ kbd { box-shadow: 0 12px 32px rgba(42, 22, 14, 0.23); font-size: var(--text-2xs); backdrop-filter: blur(14px); - animation: toast-in 0.2s ease-out; + animation: toast-in 0.22s ease-out; } @@ -1552,13 +1575,19 @@ kbd { color 0.16s ease; } -.home-quick:hover, -.home-icon-button:hover { +.home-icon-button:hover:not(:disabled), +.home-quick:hover:not(:disabled) { border-color: rgba(242, 106, 51, 0.24); color: #3f281e; background: rgba(255, 255, 255, 0.94); } +.home-icon-button:disabled, +.home-quick:disabled { + opacity: var(--dimmed); + cursor: default; +} + .home-quick kbd { margin-left: 1px; min-width: 20px; @@ -1888,6 +1917,20 @@ kbd { background: #fff1e7; } +/* The drag carries a file this button cannot serve: spent, so it is read as a + candidate no more than a control that is switched off elsewhere in the app. */ +.home-primary.is-drop-unavailable, +.home-secondary.is-drop-unavailable { + opacity: var(--dimmed); + cursor: default; + transform: none; +} + +.home-primary.is-drop-unavailable:hover, +.home-secondary.is-drop-unavailable:hover { + transform: none; +} + .home-side { display: flex; flex-direction: column; @@ -2436,7 +2479,7 @@ kbd { cursor: pointer; } -.settings-link:hover { +.settings-link:hover:not(:disabled) { color: #9c401a; } @@ -2629,7 +2672,7 @@ kbd { .runtime-refresh:disabled { cursor: default; - opacity: 0.62; + opacity: var(--dimmed); } .runtime-summary { @@ -2826,7 +2869,7 @@ kbd { .runtime-install:disabled { cursor: default; - opacity: 0.65; + opacity: var(--dimmed); } .runtime-bundled { @@ -3084,6 +3127,13 @@ kbd { user-select: none; } +/* "Select all" follows the rows it selects: while a transfer locks the panel the + label stayed bright with nothing behind it left to click. */ +.share-select-all:has(input:disabled) { + opacity: var(--dimmed); + cursor: default; +} + .share-file-row { display: flex; align-items: center; @@ -3100,7 +3150,7 @@ kbd { background 0.14s ease; } -.share-file-row:hover { +.share-file-row:hover:not(:has(input:disabled)) { border-color: rgba(228, 92, 42, 0.2); background: #fff; } @@ -3123,6 +3173,29 @@ kbd { pointer-events: none; } +/* The checkbox carries the state, so the row has to show it. Ignored on a webview + without `:has`, which leaves the row looking live as it did before. */ +.share-file-row:has(input:disabled) { + opacity: var(--dimmed); + cursor: default; +} + +/* The real checkbox is a hidden 1px box, so the ring belongs on the row it names. */ +.share-file-row input, +.share-select-all input { + outline: none; +} + +.share-file-row:focus-within { + border-color: rgba(242, 106, 51, 0.55); + box-shadow: 0 0 0 3px rgba(242, 106, 51, 0.14); +} + +/* "Select all" has no border of its own, so its ring is drawn as a shadow. */ +.share-select-all:focus-within { + box-shadow: 0 0 0 3px rgba(242, 106, 51, 0.14); +} + .share-checkmark { display: grid; place-items: center; @@ -3198,7 +3271,7 @@ kbd { } .share-reshow:disabled { - opacity: 0.55; + opacity: var(--dimmed); cursor: default; } @@ -3243,7 +3316,7 @@ kbd { } .share-peer:disabled { - opacity: 0.48; + opacity: var(--dimmed); cursor: default; } @@ -3695,7 +3768,7 @@ kbd { border-radius: 12px; color: #fff5ed; background: rgba(32, 24, 21, 0.88); - font-size: 12px; + font-size: var(--text-2xs); text-align: center; } @@ -3913,7 +3986,7 @@ body[data-view="radial"] .share-backdrop { .update-action:disabled { cursor: default; - opacity: 0.72; + opacity: var(--dimmed); } .update-action.is-commit { @@ -4077,7 +4150,7 @@ body[data-view="radial"] .share-backdrop { border: 0; background: transparent; color: #3a251b; - font-size: 12px; + font-size: var(--text-2xs); outline: none; } @@ -4109,7 +4182,7 @@ body[data-view="radial"] .share-backdrop { padding: 24px; background: rgba(48, 26, 14, 0.32); backdrop-filter: blur(6px); - animation: setup-fade 220ms ease-out; + animation: setup-fade 0.22s ease-out; } .setup-card { @@ -4121,7 +4194,7 @@ body[data-view="radial"] .share-backdrop { border-radius: 16px; background: #fffaf6; box-shadow: 0 26px 60px rgba(70, 32, 14, 0.24); - animation: setup-rise 260ms cubic-bezier(0.22, 0.8, 0.3, 1); + animation: setup-rise 0.26s cubic-bezier(0.22, 0.8, 0.3, 1); } .setup-head { @@ -4180,7 +4253,7 @@ body[data-view="radial"] .share-backdrop { border: 1px solid rgba(120, 70, 40, 0.12); border-radius: 11px; background: rgba(255, 255, 255, 0.7); - transition: border-color 160ms ease; + transition: border-color 0.16s ease; } .setup-row.is-problem { diff --git a/src/types.ts b/src/types.ts index e268c4a..65c2387 100644 --- a/src/types.ts +++ b/src/types.ts @@ -122,7 +122,6 @@ export interface WriteCheck { kind: "screenshot" | "recording" | "files"; path: string; ok: boolean; - message: string; } export type RuntimeComponentCategory = "documents" | "graphics" | "video" | "capture" | "ocr";