import { convertFileSrc, isTauri } from "@tauri-apps/api/core"; import { emitTo, listen } from "@tauri-apps/api/event"; import { getCurrentWebview } from "@tauri-apps/api/webview"; import { open } from "@tauri-apps/plugin-dialog"; import { openUrl } from "@tauri-apps/plugin-opener"; import { Check, Circle, Clock3, Cpu, Download, FileAudio, File as FileGeneric, FileImage, FileSpreadsheet, FileText, FileType, FileVideo, FolderCog, FolderOpen, FolderSearch, FileOutput, LoaderCircle, Maximize, MoveRight, Pin, Presentation, RefreshCw, ScanLine, ScanText, Search, Send, Settings2, ShieldAlert, ShieldCheck, Sparkle, Star, Wrench, X, } from "lucide-react"; import { useEffect, useMemo, useRef, useState, type CSSProperties, type DragEvent, } from "react"; import { getInitialLang, publishLang, tLive, useI18n } from "../i18n"; import { api } from "../lib/api"; import { FEEDBACK } from "../lib/feedback"; import { hitTestDropTarget, releasePoint, toWindowPoint } from "../lib/dropTargets"; import { actionCanServe, dropEffectFor, OCR_IMAGE_EXTENSIONS, type DropAction, } from "../lib/dropCapabilities"; import { SetupPanel } from "./SetupPanel"; import { SharePanel } from "./SharePanel"; import { UpdatePanel } from "./UpdatePanel"; import { basename, dirname, extensionOf, getLocalRecentItems, IS_MAC, messageFrom, type RecentItem, subscribeRecent, timeAgo, } from "../lib/utils"; import { dragOutPayload } from "../lib/dragOut"; import { fileDragImage } from "../lib/dragImage"; import { history } from "../lib/history"; import type { AppSettings, HotkeyStatus, RuntimeComponent, RuntimeInfo, ShareTransfer, SwitchState, SwitchUpdate, WriteCheck, } from "../types"; const FALLBACK_SETTINGS: AppSettings = { fileOutputMode: "alongside", fileOutputDir: "~/Downloads/Shift", screenshotDir: "~/Pictures/Shift", recordingDir: "~/Movies/Shift", autoReveal: true, dragEnabled: true, shareEnabled: true, autostart: false, defaultFileOutputDir: "~/Downloads/Shift", defaultScreenshotDir: "~/Pictures/Shift", defaultRecordingDir: "~/Movies/Shift", language: "", updateCheckEnabled: true, updateFeedUrl: "", wedgeOrders: {}, setupReviewed: false, }; type SettingsTab = "system" | "runtime" | "updates"; const DROP_ICONS = [ { icon: FileType, tone: "pdf" }, { icon: FileText, tone: "document" }, { icon: FileVideo, tone: "video" }, { icon: FileImage, tone: "image" }, { icon: FileAudio, tone: "audio" }, { icon: FileSpreadsheet, tone: "sheet" }, { icon: Presentation, tone: "presentation" }, ]; type OutputKind = "files" | "screenshot" | "recording"; /* The three primary buttons double as drop targets: files dropped on a button run that action. Which button a drag may land on is decided by `lib/dropCapabilities`. */ const ARC_STEP_DEG = 13; const ARC_RADIUS = 140; const ARC_LIFT = 32; // WKWebView renders HEIC/AVIF natively; the icon fallback covers any decode failure. const THUMB_EXTENSIONS = [ "png", "jpg", "jpeg", "webp", "gif", "bmp", "tiff", "tif", "heic", "avif", ]; function RecentThumb({ item }: { item: RecentItem }) { const [failed, setFailed] = useState(false); const extension = extensionOf(item.path); const showImage = item.kind === "image" && THUMB_EXTENSIONS.includes(extension) && !failed; if (showImage) { return ( setFailed(true)} /> ); } return ( {item.kind === "image" ? ( ) : item.kind === "video" ? ( ) : item.kind === "text" ? ( ) : ( )} ); } interface OutputLocationProps { label: string; path: string; onChoose: () => void; onReveal: () => void; onReset?: () => void; resetLabel: string; chooseLabel: string; revealLabel: string; } function OutputLocation({ label, path, onChoose, onReveal, onReset, resetLabel, chooseLabel, revealLabel, }: OutputLocationProps) { return (
{label} {onReset ? ( ) : null}
{path}
); } export function MainWindow() { const { lang, setLang, t } = useI18n(); const [dragging, setDragging] = useState(false); const [busy, setBusy] = useState(null); const [toast, setToast] = useState(null); const [languageError, setLanguageError] = useState(null); // Every switch uses this snapshot until the real settings arrive. Starting // empty made the first click wait for a disk read before it could change. const [settings, setSettings] = useState(FALLBACK_SETTINGS); const [setupOpen, setSetupOpen] = useState(false); const [settingsOpen, setSettingsOpen] = useState(false); const [settingsTab, setSettingsTab] = useState("system"); const [screenAccess, setScreenAccess] = useState(null); const [checks, setChecks] = useState(null); const [checking, setChecking] = useState(false); const [runtimeInfo, setRuntimeInfo] = useState(null); const [runtimeLoading, setRuntimeLoading] = useState(false); const [runtimeInstalling, setRuntimeInstalling] = useState([]); const [runtimeError, setRuntimeError] = useState(null); const [runtimeInstallHelp, setRuntimeInstallHelp] = useState< "homebrew" | "winget" | null >(null); const [recent, setRecent] = useState(getLocalRecentItems); /** Filter text for the history library, matched against the file name. */ const [historyQuery, setHistoryQuery] = useState(""); const [sharePaths, setSharePaths] = useState(null); const toastTimer = useRef(null); const [, setNowTick] = useState(0); const [dropAction, setDropAction] = useState(null); /** True while a Recent row is being dragged, which the native `dragging` never covers. */ const [rowDragging, setRowDragging] = useState(false); /** * The files the drag in flight is carrying, so a button can say "not this one" * before the file is released. Both drag sources report them: the native event * on `enter`, a Recent row on `dragstart`. */ const [dragPaths, setDragPaths] = useState(null); const [hotkeys, setHotkeys] = useState(null); const dropTargets = useRef>>({}); /** * The Recent row that is in flight, and whether it has already landed. A row leaves * Shift as a real file drag, so one gesture can be reported twice: once by the DOM, * once by the native drop events. Only the first of the two may run an action. */ const recentDrag = useRef<{ path: string; landed: boolean } | null>(null); /** * The last position the drag in flight moved through, in CSS pixels inside this * window. Chromium reports `dragend` at the origin rather than where the pointer * stopped, so this is the only aim that engine can be given. */ const dragPointer = useRef<{ x: number; y: number } | null>(null); const runtimeCheckStarted = useRef(false); async function finishSetup() { setSetupOpen(false); try { await api.setSetupReviewed(true); } catch { // A failed write only means the flow may appear again next launch; the // checks it reported are all re-runnable from Settings. } } /** Leave the guided flow and land on the panel that can install what it found. */ function openRuntimeFromSetup() { void finishSetup(); setSettingsTab("runtime"); setSettingsOpen(true); } async function flash(message: string, duration: number = FEEDBACK.notice) { if (toastTimer.current) window.clearTimeout(toastTimer.current); setToast(message); toastTimer.current = window.setTimeout(() => setToast(null), duration); } async function spring(action: string, task: () => Promise) { if (busy) return; setBusy(action); try { await task(); } catch (error) { flash(t(messageFrom(error)), FEEDBACK.error); } finally { setBusy(null); } } async function chooseOcr() { const selected = await open({ multiple: false, directory: false, filters: [ { name: "Images", extensions: OCR_IMAGE_EXTENSIONS, }, ], }); if (!selected || Array.isArray(selected)) return; await api.openInEditor(selected); window.setTimeout(() => { void emitTo("editor", "editor://run-ocr", {}); }, 450); } async function runOcrOn(paths: string[]) { // The button already showed it could not take this file, so a release on it // stays silent: no action, no message, nothing to acknowledge. if (!actionCanServe("ocr", paths)) return; await api.openInEditor(paths[0]); window.setTimeout(() => { void emitTo("editor", "editor://run-ocr", {}); }, 450); } function localPoint(position: { x: number; y: number }) { return toWindowPoint(position, IS_MAC ? "mac" : "other", window.devicePixelRatio || 1); } /** Hit-test a point that is already in CSS pixels inside this window. */ function actionAtPoint(point: { x: number; y: number }): DropAction | null { const boxes: Array<[DropAction, DOMRect | null | undefined]> = [ ["formats", dropTargets.current.formats?.getBoundingClientRect()], ["tools", dropTargets.current.tools?.getBoundingClientRect()], ["ocr", dropTargets.current.ocr?.getBoundingClientRect()], ]; return hitTestDropTarget(boxes, point); } function actionAt(position: { x: number; y: number }): DropAction | null { const point = localPoint(position); if (point) dragPointer.current = point; return point ? actionAtPoint(point) : null; } /** * Run the one action a drop was aimed at. * * The button *is* the choice. `null` means the file was released on the panel * rather than on a button, and that runs nothing and says nothing - the same * nothing a row released off a button does, which is why a file from outside and * a row from the list are now one gesture with one set of consequences. */ function dropFiles(paths: string[], action: DropAction | null) { if (paths.length === 0) return Promise.resolve(); if (!action) return Promise.resolve(); // The same rule the button's appearance already applied: a button that cannot // serve this file runs nothing, rather than opening a wheel with nothing in it. if (!actionCanServe(action, paths)) return Promise.resolve(); if (action === "ocr") return runOcrOn(paths); return api.showFilesInRadial(paths, action).then(() => undefined); } /** * Land a dragged Recent row, at most once per gesture. */ function landRecentRow(action: DropAction | null, token?: { path: string; landed: boolean }) { const drag = recentDrag.current; if (!drag || drag.landed) return; // A timer from the gesture before this one must not land it on the row's behalf. if (token && token !== drag) return; drag.landed = true; setDropAction(null); // The gesture is over, whether or not `dragend` arrives to say so. dragPointer.current = null; setDragPaths(null); void dropFiles([drag.path], action).catch((error) => flash(tLive(messageFrom(error)), FEEDBACK.error)); } /** * DOM half of the same gesture, armed on the window root. Whether a file drag that * started inside the webview is reported here, to the native handler, or to both * differs by engine, so both are listening and `landRecentRow` decides who was first. */ function rowDragOver(event: DragEvent) { const drag = recentDrag.current; if (!drag) return; event.preventDefault(); const point = { x: event.clientX, y: event.clientY }; dragPointer.current = point; const next = actionAtPoint(point); // A spent button must show the same refusal before release that it shows on // release: `none` turns the operating system's cursor into a prohibition. event.dataTransfer.dropEffect = dropEffectFor(next, [drag.path]); if (dropAction !== next) setDropAction(next); } function rowDropped(event: DragEvent) { if (!recentDrag.current) return; event.preventDefault(); landRecentRow(actionAtPoint({ x: event.clientX, y: event.clientY })); } async function chooseFiles(mode: "formats" | "tools") { const selected = await open({ multiple: true, directory: false }); if (!selected) return; const files = Array.isArray(selected) ? selected : [selected]; if (files.length === 0) return; await api.showFilesInRadial(files, mode); } async function applySettings(task: () => Promise) { try { setSettings(await task()); } catch (error) { flash(t(messageFrom(error)), FEEDBACK.error); } } // Toggles flip their visual state at once and reconcile with the backend // snapshot afterwards, so a slow disk or login-item call cannot stall the switch. async function applyToggle( patch: Partial, task: () => Promise, ) { const previous = settings; if (previous) setSettings({ ...previous, ...patch }); try { const response = await task(); setSettings((current) => { if (!current) return current; const enabled = "state" in response ? response.state.enabled : response.enabled; return { ...current, ...patch, ...("autostart" in response && response.autostart !== null ? { autostart: response.autostart } : { autostart: "autostart" in patch ? enabled : current.autostart }), dragEnabled: "dragEnabled" in patch ? enabled : current.dragEnabled, shareEnabled: "shareEnabled" in patch ? enabled : current.shareEnabled, autoReveal: "autoReveal" in patch ? enabled : current.autoReveal, }; }); } catch (error) { if (previous) setSettings(previous); flash(t(messageFrom(error)), FEEDBACK.error); } } async function changeLanguage(next: "en" | "zh") { setLanguageError(null); // publishLang persists the choice and notifies Rust exactly once. `setLang` // also updates this webview, so the switch does not wait for that IPC. setLang(next); } async function chooseFolder(kind: OutputKind) { if (!settings) return; const current = kind === "screenshot" ? settings.screenshotDir : kind === "recording" ? settings.recordingDir : settings.fileOutputDir; const selected = await open({ directory: true, multiple: false, defaultPath: current }); if (!selected || Array.isArray(selected)) return; await applySettings(() => api.setOutputDirectory(kind, selected)); setChecks(null); } async function resetFolder(kind: OutputKind) { await applySettings(() => api.setOutputDirectory(kind, null)); setChecks(null); } async function refreshHotkeys() { try { setHotkeys(await api.hotkeyStatus()); } catch { setHotkeys(null); } } async function refreshRuntime() { if (!isTauri()) return; setRuntimeLoading(true); setRuntimeError(null); setRuntimeInstallHelp(null); try { setRuntimeInfo(await api.getRuntimeInfo()); } catch (error) { setRuntimeError(t(messageFrom(error))); } finally { setRuntimeLoading(false); } } function describeRuntimeInstallError(error: unknown) { const message = messageFrom(error); setRuntimeInstallHelp( message === "homebrew-missing" ? "homebrew" : message === "winget-missing" ? "winget" : null, ); if (message === "homebrew-missing") { return t("runtimeInstallNeedsHomebrew"); } if (message === "winget-missing") { return t("runtimeInstallNeedsWinget"); } if ( message === "runtime-install-unsupported" || message === "unsupported-runtime-component" ) { return t("runtimeInstallUnsupported"); } if (message.startsWith("homebrew-install-failed:")) { // The tail is the installer's own exit status - worth having in a log, // useless as a sentence a user has to read. console.error(message); return t("runtimeInstallFailed"); } if (message.startsWith("winget-install-failed:")) { console.error(message); return t("runtimeInstallFailed"); } if ( message === "homebrew-install-missing-binary" || message === "winget-install-missing-binary" ) { return t("runtimeInstallFailed"); } // Every failure the installer raises is a code it names here, so anything // still unrecognised is worded by the dictionary or shown as it came. return t(message); } async function installRuntimeComponents(components: RuntimeComponent[]) { if (runtimeInstalling.length > 0 || components.length === 0) return; setRuntimeInstalling(components.map((component) => component.id)); setRuntimeError(null); setRuntimeInstallHelp(null); try { await api.installRuntimeComponents(components.map((component) => component.id)); flash( components.length === 1 ? t("runtimeInstallComplete", { name: components[0].name }) : t("runtimeInstallManyComplete", { count: components.length }), FEEDBACK.done, ); } catch (error) { setRuntimeError(describeRuntimeInstallError(error)); } finally { setRuntimeInstalling([]); // A batch can stop at its first failure with the earlier installs already // on disk, so the panel re-reads either way rather than trusting the reply. await refreshRuntime(); } } async function reclaimHotkeys() { try { await api.quitOtherInstances(); // Give the other copies a beat to release the hotkeys they own. window.setTimeout(() => void api.reclaimHotkeys().then(setHotkeys).catch(() => refreshHotkeys()), 900); } catch (error) { flash(t(messageFrom(error)), FEEDBACK.error); } } async function runAccessCheck() { setChecking(true); try { setChecks(await api.checkOutputAccess()); } catch (error) { flash(t(messageFrom(error)), FEEDBACK.error); } finally { setChecking(false); } } useEffect(() => { if (!isTauri()) { setSettings(FALLBACK_SETTINGS); return; } void api .getSettings() .then((loaded) => { setSettings(loaded); // The tray menu is native, so it can only show the language the backend // knows about. Adopt the stored choice, or hand it ours on a first run; // the backend only writes when the value actually changed. if (!loaded.setupReviewed) setSetupOpen(true); const stored = loaded.language; const effective = stored === "en" || stored === "zh" ? stored : getInitialLang(); if (effective !== stored) publishLang(effective); }) .catch((error) => { setSettings(FALLBACK_SETTINGS); flash(t(messageFrom(error)), FEEDBACK.error); }); void api .screenCaptureAccessStatus() .then(setScreenAccess) .catch(() => setScreenAccess(null)); void api .hotkeyStatus() .then(setHotkeys) .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.adopt().then(setRecent).catch(() => undefined); // Settings are loaded once when the main window starts. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { const onLanguageError = (event: Event) => { const detail = (event as CustomEvent).detail; setLanguageError(detail || t("languageSaveFailed")); }; window.addEventListener("shift:language-error", onLanguageError); return () => window.removeEventListener("shift:language-error", onLanguageError); }, [t]); // Reading the status also consumes a "second copy tried to start" marker. useEffect(() => { if (settingsOpen && isTauri()) void refreshHotkeys(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [settingsOpen]); // Every dismissible surface answers to Escape: the send panel already did, and // the settings sheet only answered to its close button and its backdrop. The // panel owns the key while it is open, so one press never closes two things. useEffect(() => { if (!settingsOpen) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Escape" || sharePaths || setupOpen) return; setSettingsOpen(false); }; window.addEventListener("keydown", onKeyDown); return () => window.removeEventListener("keydown", onKeyDown); }, [settingsOpen, sharePaths, setupOpen]); // Announce files that another Shift pushed to this machine. A dedicated effect so // the message re-subscribes when the language changes. useEffect(() => { if (!isTauri()) return; const unlisten = listen("share://transfer", (event) => { const transfer = event.payload; if (transfer.state === "received" && transfer.path) { flash(t("shareReceived", { name: transfer.fileName, peer: transfer.peerName }), FEEDBACK.notice); } }); return () => { void unlisten.then((release) => release()); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [t]); useEffect(() => { if (!isTauri() || runtimeCheckStarted.current) return; runtimeCheckStarted.current = true; // Probe while the home screen is idle so opening Runtime components does not // wait for every external tool to start once. const timer = window.setTimeout(() => void refreshRuntime(), 600); return () => window.clearTimeout(timer); // Automatic detection runs only once; later checks come from the refresh button. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { const unlisteners: Array<() => void> = []; if (isTauri()) { void getCurrentWebview() .onDragDropEvent((event) => { const drag = recentDrag.current; if (event.payload.type === "enter") { setDragging(true); // `enter` is the first moment the carried files are known, which is // early enough to mark a button that cannot serve them. setDragPaths(event.payload.paths); setDropAction(actionAt(event.payload.position)); return; } if (event.payload.type === "over") { setDropAction(actionAt(event.payload.position)); return; } if (event.payload.type === "leave") { setDragging(false); setDropAction(null); setDragPaths(null); return; } if (event.payload.type === "drop") { const action = actionAt(event.payload.position); setDragging(false); setDropAction(null); setDragPaths(null); // A Recent row is a real file drag, so it can reach here as well as the // panel's own DOM handler; nothing else can be in flight at the same time. if (drag) { landRecentRow(action); return; } void dropFiles(event.payload.paths, action).catch((error) => flash(tLive(messageFrom(error)), FEEDBACK.error)); return; } }) .then((unlisten) => unlisteners.push(unlisten)); void listen("app://error", (event) => flash(tLive(event.payload), FEEDBACK.error)).then((unlisten) => unlisteners.push(unlisten), ); void listen("app://open-ocr", () => void chooseOcr()).then((unlisten) => unlisteners.push(unlisten), ); // The tray's update row lands here: open Settings on the Updates tab so the // download and its SHA256 are the next thing the user sees. void listen("app://open-updates", () => { setSettingsTab("updates"); setSettingsOpen(true); }).then((unlisten) => unlisteners.push(unlisten)); // A capture card's Send button: this window owns the peer list, so the card // asks here rather than duplicating the discovery UI. void listen<{ paths: string[] }>("app://send-files", (event) => setSharePaths(event.payload.paths), ).then((unlisten) => unlisteners.push(unlisten)); } const unsubscribeRecent = subscribeRecent(() => void history.list().then(setRecent)); // Rust owns the library, so its broadcast is the only cross-window signal needed. const unsubscribeHistory = history.onChanged(setRecent); // Keeps the relative timestamps honest without re-reading storage constantly. // The same slow tick keeps relative timestamps and the hotkey-ownership // notice honest, so a copy that quits clears the warning without a restart. const clockTimer = window.setInterval(() => { setNowTick((value) => value + 1); if (isTauri()) void refreshHotkeys(); }, 30_000); return () => { unlisteners.forEach((unlisten) => unlisten()); unsubscribeRecent(); unsubscribeHistory(); window.clearInterval(clockTimer); if (toastTimer.current) window.clearTimeout(toastTimer.current); }; // Handlers only use stable setters and imported APIs. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // The library holds hundreds of rows, so the filter runs where the list is // rendered rather than as a second request to Rust. const visibleRecent = useMemo(() => { const needle = historyQuery.trim().toLowerCase(); if (!needle) return recent; return recent.filter((item) => basename(item.path).toLowerCase().includes(needle)); }, [recent, historyQuery]); // One rule for all three buttons and both platforms: a button that cannot serve the // files in flight shows spent, and a release on it does nothing. The button under the // pointer also gets a forbidden edge and the engine's no-drop cursor, so the refusal // is visible before the user lets go. const spent = (action: DropAction) => dragPaths !== null && !actionCanServe(action, dragPaths); // A button that cannot serve the drag is not a candidate, so it never lights up. const aimedAction = dropAction && actionCanServe(dropAction, dragPaths) ? dropAction : null; const forbiddenAction = dropAction && spent(dropAction) ? dropAction : null; const outputLabel = (kind: WriteCheck["kind"]) => kind === "screenshot" ? t("screenshots") : kind === "recording" ? t("recordings") : t("fileResults"); const runtimeGroups = runtimeInfo ? [ { id: "documents", label: t("runtimeDocuments") }, { id: "graphics", label: t("runtimeGraphics") }, { id: "video", label: t("runtimeVideo") }, { id: "capture", label: t("runtimeCapture") }, { id: "ocr", label: t("runtimeOcr") }, ] .map((group) => ({ ...group, components: runtimeInfo.components.filter( (component) => component.category === group.id, ), })) .filter((group) => group.components.length > 0) : []; // What the panel can fix by itself, in the order the rows appear. A shared package // (Poppler answers both PDF rows on Windows) is listed twice here; the backend // installs it once. const runtimeInstallable = runtimeInfo ? runtimeInfo.components.filter((component) => !component.available && component.installable) : []; return (
Shift Your Files
{setupOpen ? ( void finishSetup()} onOpenRuntime={openRuntimeFromSetup} /> ) : null}
{screenAccess === false ? (
{t("screenPermissionPrompt")}
) : hotkeys && !hotkeys.live ? (
{hotkeys.others.length > 0 ? t("hotkeysDead") : t("hotkeysNotLive")}
) : null}

{t("homeDropTitle")}

{/* The buttons are the only thing a drag reacts to: while one is in flight all three show as candidates, so the aim is visible before the pointer reaches one, and the panel itself never animates. */}

{t("homeDropHint")}

{settingsOpen ? (
setSettingsOpen(false)} /> ) : null} {sharePaths ? ( setSharePaths(null)} onNotice={(message) => flash(message, FEEDBACK.notice)} /> ) : null} {toast ? (
{toast}
) : null}
); }