Zum Hauptinhalt springen
info
Dieser Teil ist für Entwickler und nur auf Englisch verfügbar.

Desktop app

Preview

The desktop app is a preview. This page describes apps/desktop on dev, which can be ahead of the latest release.

The desktop app is a Tauri 2 app: a Rust core in apps/desktop/src-tauri and a React UI in apps/desktop/src, shown in the system webview (WebView2 on Windows, WKWebView on macOS). Every command, event and URL the two sides exchange is listed in apps/desktop/CONTRACT.md, which src/ipc.ts, src/db/ and src/server/ mirror in TypeScript; change both sides and the contract together. This page explains how the parts work and why they are built the way they are.

Rust platform layer, shared TypeScript packages​

The rule that shapes the app: Rust does what needs the platform, TypeScript does what the other apps share.

ConcernLives inRust's part
Pixels: decoding, scaling, caching, deep zoomRust (decode/, pipeline.rs, diskcache.rs, tiles/)all of it
File operations: trash, rotate, reveal, clipboard, default-app settingsRust (ops.rs, jpegmeta.rs, orient.rs)all of it
Metadata reads and XMP writesRust (info.rs, xmp/)all of it; the UI decides the target
The library, search, upload queue, outboxpackages/local-db (schema, migrations, queries, writers)only executes SQL, applies the migrations and reports changed tables (localdb/); no library SQL in Rust
What the disk knows about filesRust (platform/), the "file seams"walks, watches, reads headers and hashes, and hands the facts over as data; writes no database
Every server requestpackages/api-client (endpoint functions and zod schemas, the core entry)carries the bytes (server/http.rs) and keeps the refresh token in the OS keychain

So the desktop runs the same schemas, queries and API contracts as the web and mobile apps, and a server answer that breaks a shared schema fails here the way it fails there.

The UI imports both packages from source, like the web app does: a Vite alias in vite.config.ts and the same mapping under paths in tsconfig.json point @librephotos/api-client/core at packages/api-client/src/core.ts and @librephotos/local-db at packages/local-db/src/index.ts. resolve.dedupe makes the packages' bare zod and drizzle-orm imports resolve to the desktop's own install, so the bundle holds one copy of each. apps/desktop is not an npm workspace: it keeps its own package.json and package-lock.json (the api-client workflow's nested-lockfile guard allows exactly that one), and node scripts/check-shared-deps.mjs checks that its zod, and React or React Query when it declares them, satisfy packages/api-client's peer ranges, and that its drizzle-orm matches the one packages/local-db is tested with.

The Vite dev server uses a fixed port and keeps the terminal (Tauri expects the port and has to show Rust's compile errors).

Where things are​

Rust (src-tauri/src)
lib.rsstart-up, the lpview scheme registration, the command list
protocol.rs, request.rsthe lpview handler and URL parsing
pipeline.rs, cache.rs, diskcache.rsdecode scheduling, the byte-budgeted memory LRU, the disk cache
decode/ (mod.rs, wic.rs, raw.rs, generic.rs), heif.rs, pixels.rs, orient.rs, jpegmeta.rsdecoders, resizing and encoding, EXIF orientation and JPEG header surgery
tiles/ (geom.rs, source.rs, disk.rs, mod.rs)deep zoom
listing.rs, info.rs, formats.rs, ops.rslist_folder, image_info, file kinds, file operations
localdb/ (mod.rs, value.rs, migrate.rs, changes.rs)the SQL engine behind packages/local-db
platform/ (mod.rs, files.rs, watch.rs)the file seams
server/ (mod.rs, auth.rs, http.rs, backup.rs)settings, keychain, the native transport, the media proxy, MD5 and chunk reads
commands.rs, appdirs.rsthe Tauri commands and events of the above, where the app keeps its state
UI (src)
App.tsx, ipc.ts, platform.tsthe app shell, the contract's commands and URLs (with a browser mock), window helpers
stage/, chrome/, lib/the viewer: stage, tiles, slideshow, top bar, filmstrip, info panel, caches and queues
edits/metadata edits and their server replay
library/the library window: indexer, timeline layout and grid, search, folders, server pages
db/the local database's executor, live queries, file seams, benchmark
server/session, native transport, backup engine, contract errors
ui/, styles.cssthe design tokens and the shared primitives

The lpview scheme​

Every picture the webview shows comes from a custom URI scheme, lpview, so images load through <img> and <video> like any URL, are cached by the webview (Cache-Control: immutable, the URL carries the file's mtime) and never cross the JSON IPC. On Windows WebView2 reaches it as http://lpview.localhost/..., elsewhere as lpview://localhost/...; imageUrl() in src/ipc.ts builds both. The kinds (thumb, screen, full, tile, remote) and the headers are in the contract.

  • request.rs parses the URL. URLSearchParams encodes spaces as +, so + is read as a space. A thumb is at most 320 px on its long edge (THUMB_EDGE); a screen request without a size gets 1920 x 1080 (DEFAULT_SCREEN), and no box edge goes beyond 16384 px.
  • p= is a scheduling class, not part of the picture's identity: no p is High (the stage and its neighbours), p=low the filmstrip, p=idle folder pre-warming.
  • Videos are served from the file with Range support so <video> can seek; an open-ended range is answered with at most 8 MB (MAX_RANGE_CHUNK).
  • Every handler calls its responder exactly once, possibly from another thread.

Decode pipeline​

pipeline.rs decides when a request runs, decode/ how it is made.

  • A request first looks in the memory LRU of encoded thumb and screen responses (256 MB, keyed by path, mtime, kind and box; an entry bigger than a quarter of the budget is not kept), then in the disk cache on one of two I/O threads (so a disk hit never waits behind a decode), then goes to a pool of six decode workers. Identical requests in flight share one decode.
  • Three lanes: High before Low before Idle. High and Low are LIFO, because the newest request is the picture the user is looking at; Idle runs in the order the UI gave. Low and Idle never take the last free worker, so a screen request always finds one; Idle uses at most two workers (IDLE_WORKERS), runs only when nothing else is queued, and lowers its thread's CPU and I/O priority. A request asked for again moves to the top of its lane, or to a better lane (a filmstrip thumb the stage asks for becomes High).
  • Pre-warmed thumbs nobody asked for go to the disk cache only, so they never push the pictures being looked at out of memory.
  • The lane rules live in State::enqueue, pick and State::finish, which only change the queue state; the worker and I/O threads lock it and call them. Tests of the rules drive those three step by step instead of timing real decodes, so they give the same answer on a busy CI runner.

decode/mod.rs picks the cheapest way to make what was asked:

  1. Pass-through: the file's own bytes, when the webview decodes the format (JPEG, PNG, GIF, WebP, BMP) and no resize is needed. GIFs always pass through, so they keep their animation. LPVIEW_SCREEN_PASSTHROUGH=<n> lets a JPEG screen pass through up to n times the box's pixel count (default 1: only when it fits), which moves the decode into the webview.
  2. Embedded thumbnails: a JPEG's EXIF thumbnail for thumb when its long edge is at least 120 px; a HEIC's thmb item (iPhones up to iOS 16, many cameras), which heif.rs rebuilds into a minimal HEIF holding only that item, so the decoder spends one 320 x 240 HEVC frame instead of the whole 12 MP grid. Embedded thumbnails and RAW previews are served with an EXIF orientation injected (jpegmeta.rs), so the webview turns them itself.
  3. Explorer's thumbnail cache (Windows): about 15 ms on a hit, already oriented. Formats that are slow to decode (HEVC, AV1) and very big JPEGs (a 1/8 decode of a 300 MP JPEG still entropy-decodes all of it, about 0.6 s) let the shell make the thumbnail once and serve it from its cache afterwards; the rest only take a hit. Formats with alpha are left out, since shell bitmaps lose it. Videos get their thumbnail from the shell too.
  4. WIC (Windows Imaging Component; JPEG, PNG, GIF, BMP, TIFF, WebP, HEIC/HEIF, AVIF, JXL and RAW with the Store codecs). JPEGs decode at 1/2, 1/4 or 1/8 through IWICBitmapSourceTransform (DCT scaling), so a 298 MP JPEG never exists at full size for a screen. A scaled decode down to 85 % of the box (DCT_TOLERANCE) is served as it is: a 1/2 decode of a 3840 x 2560 JPEG for a 2160 x 1440 box saves about 40 % of the time. COM is initialised multithreaded once per thread that touches WIC.
  5. ImageIO (macOS; decode/imageio.rs): the system codecs take WIC's place, including HEIC, HEIF and AVIF, decoded straight to the box's size; see Desktop app: macOS builds.
  6. Pure-Rust decoders (decode/generic.rs: image with zune-jpeg, png, gif, webp, tiff and bmp, plus jxl-oxide), on every platform and as the fallback when WIC or ImageIO fails. Off Windows and macOS, HEIC, HEIF and AVIF are refused.
  7. Camera RAW through FlashRaw (decode/raw.rs): the embedded JPEG previews (smallest first) for thumb and screen; a preview up to 480 px passes through with the RAW's orientation injected; the largest preview is used when it reaches about 90 % of the box; otherwise, and for full, a develop.

Decoded pixels are resized with fast_image_resize and encoded as JPEG q90 4:2:0, or as PNG when the image uses its alpha channel (pixels.rs). On Windows the WIC encoder does the JPEG (two to three times faster than jpeg-encoder, which is the encoder elsewhere); its output buffer is sized for the worst case and shrunk afterwards, so cached JPEGs do not keep megabytes committed that the caches' budgets never see. A full image is capped at 120 MP (FULL_MAX_PIXELS), which also keeps it within JPEG's 65535 px limit.

Orientation (orient.rs) is modelled as "rotate the stored pixels by r quarter turns clockwise, then mirror if m", which covers all eight EXIF values; orientations 5 to 8 swap width and height. rotate_file composes a quarter turn onto that: a JPEG's EXIF orientation is patched in place (two bytes) when the tag exists, otherwise its EXIF header is rebuilt with the tag (IFD0 copied to the end of the TIFF data, so no other offset moves) and the file replaced atomically, and an XMP tiff:Orientation is kept in step. TIFF files are patched when the tag exists, PNG and BMP re-encoded losslessly; other formats turn in the view only.

Windows 11 does not let an app make itself the default photo viewer, so open_default_apps_settings opens the Settings page where the user can. That page exists only when the installer registered the app under Software\RegisteredApplications with its product name; a dev build gets the generic Default apps page.

The installer hooks (src-tauri/windows/installer-hooks.nsh) write Windows' Default Programs registration into the install's hive (HKCU for just for me, HKLM for anyone): the ProgIDs LibrePhotosViewer.Image and LibrePhotosViewer.Raw (from fileAssociations), each type's Software\Classes\.<ext>\OpenWithProgids, Software\Classes\Applications\librephotos-viewer.exe with FriendlyAppName and SupportedTypes, App Paths\librephotos-viewer.exe, and Software\LibrePhotos Viewer\Capabilities listed in RegisteredApplications. Tauri's own association macro also points each Software\Classes\.<ext> default at our ProgID and keeps the previous value as <ProgID>_backup; the post-install hook puts that previous value back, because taking over a type is the user's choice. Before Tauri's uninstall macro restores from <ProgID>_backup, the pre-uninstall hook sets it to the type's current class, so an uninstall leaves the user's defaults as they are. The list of types in the hooks matches fileAssociations in tauri.conf.json. The finish page links to the app's Default apps page (registeredAppMachine or registeredAppUser, after the chosen scope); it is a link and not a third checkbox because Tauri's template already uses both of MUI's finish-page checkboxes, for the desktop shortcut and for starting the app.

On Windows 11 24H2 the app's Default apps page and the Open with list showed up only for an install for everyone. The same registration in HKCU was ignored, even after restarting Explorer, while SHAssocEnumHandlers already listed the app as a recommended handler. That is why the installer offers both scopes (installMode: "both"); the catch is that NSIS MultiUser with Highest asks an administrator account for elevation as soon as setup starts.

Start-up​

Rust starts the thumb of the file given on the command line before the page exists, and its screen as soon as the window exists. The stage box it predicts is the window minus the top bar (48 px) and the filmstrip (76 px): TOPBAR_HEIGHT_CSS_PX and FILMSTRIP_HEIGHT_CSS_PX in lib.rs mirror --lp-topbar-height and --lp-filmstrip-height in src/styles.css and useStageSize in src/stage/Stage.tsx; change them together (a wrong guess costs one extra decode). The folder is listed while the webview boots (about 50 ms for 2,000 files; on Windows DirEntry::metadata comes from the directory enumeration, no extra system call per file), and the page's first list_folder for that path gets that listing. src/lib/startupMarks.ts logs when the first stage pixel and the first sharp one appeared (ms since navigation start; add performance.timeOrigin to compare with the process start). The local database's migrations also run before the window exists, so the UI's first query never waits for them.

On macOS the file comes as an Apple Event instead of an argument and is listed as soon as it arrives (Opening files).

Release builds on Windows use the windows subsystem, so no console window opens next to the viewer.

The viewer in the UI​

  • src/lib/viewport.ts applies zoom and pan straight to a DOM element as a CSS transform, with no React state per wheel event. scale is CSS px per original image px, so 100 % (one image pixel per device pixel) is 1 / devicePixelRatio. The layer is sized to the original pixel size and the loaded image stretches to fill it, so the geometry does not change when a sharper image arrives. Rotation counts quarter turns without wrapping, so a CSS transition always turns the short way. Only the top bar's zoom readout subscribes to the zoom (zoomStore.ts).
  • src/stage/useProgressiveImage.ts shows the thumb at once, the screen (fitted to the stage's device-pixel box) over it once decoded, and full when zoomed past screen. While the user flips fast only thumbnails load and screen waits 140 ms for them to settle; the previous picture stays up for 160 ms while the next one has nothing decoded, and a file rotated on disk (same path, new mtime) keeps its old pixels until the new ones are ready. Results of a file the user already left are dropped.
  • src/lib/imageCache.ts fetches and fully decodes a picture off-screen (img.decode()), so swapping it into the DOM paints in one frame; when every caller of a URL aborts, the request is cancelled. The stage prefetches the screen of the neighbours in the order +1, -1, +2, -2 once the current picture is up, and aborts a prefetch on the next tick so a request the stage picks up when the user steps onto that neighbour is not restarted.
  • src/lib/thumbQueue.ts: the webview sends every <img> request at once and in DOM order, which the LIFO lanes would serve last-item-first. The filmstrip and the library grid therefore hand out their loads six at a time (one more than the thumb workers), visible items centre-out first, ranks read when a slot frees up, so scrolling re-orders what still waits.
  • src/lib/infoCache.ts shares image_info per path and mtime between the stage (for 100 %) and the info panel, and delays it while the user flips fast.

Deep zoom tiles​

Pictures with more than 24 MP (MIN_TILED_PIXELS, displayed size, opaque) are zoomed through a tile pyramid instead of full. The geometry (512 px tiles with a 1 px overlap, level L at 1/2^L) and the URLs are in the contract; tiles/geom.rs holds it as pure functions.

Producing tiles (tiles/):

  • Tiles are made a band at a time: one row of tiles, or one column when the orientation swaps the axes, which is a run of full-width rows of the stored image. Decoders stream rows forward cheaply, so a band is the natural unit. Each level is produced by at most one job at a time, which owns its own row source and streams forward: bands someone waits for first (the nearest one at or below the decoder's position, so it rarely rewinds), then, while the picture is the one being viewed, the rest of the level ("fill"), so panning soon hits the cache only. Bands an earlier session already put on disk are skipped.
  • Row sources (tiles/source.rs): on Windows WIC's CopyPixels with a row rectangle. Decoders keep their position, so consecutive runs stream (a 512-row strip of a 23040 px wide JPEG costs about 47 ms however deep it is) and rows above a rectangle are skipped with entropy decoding only (the middle band of a 298 MP JPEG comes out in about 0.35 s cold); JPEG coarse levels decode at 1/2 to 1/8 scale with a rectangle, so they never touch full resolution. A RAW develop, or a pure-Rust decode off Windows, is decoded once and sliced. Coarser levels are box-reduced from the closest native scale, at most 256 source rows at a time.
  • Tiles are cut in stored orientation and turned one by one on six encode threads (orienting a whole band first would be a serial transpose of up to 35 MB). They are JPEG q90 4:4:4: with 4:2:0 every tile edge shows a faint seam, because a decoder reconstructs chroma at an image edge differently than between two blocks.
  • Tile work has its own threads (four job threads, two I/O threads), never the thumb/screen workers; background fill runs at below-normal priority. Measured: an uncached screen decode of an 81 MP JPEG takes about 1.3 times as long while a 298 MP pyramid is built from scratch.
  • Caches: a 96 MB memory LRU of encoded tiles, and tiles/<id>/<L>-<x>-<y>.jpg on disk (tiles/disk.rs), one folder per image version (<id> is an FNV-1a hash of the canonical path, mtime, size and TILE_FORMAT, which is bumped when the tile format changes so old tiles are never served). A used file's mtime records when the picture was last viewed; past the 2 GB cap whole folders go, least recently viewed first, down to 90 %. <L>.done marks a complete level. Tiles are written as temp file plus rename, off the request path (creating a file costs about 2 ms on Windows with real-time scanning).

Drawing tiles (src/stage/tileLayer.ts): one canvas over the stage, drawn in device pixels from refs in requestAnimationFrame, with no React state per frame.

  • The geometry comes from the stage layer's computed transform, so the tiles follow the image exactly, also during CSS zoom and rotate transitions (redrawn every frame while one runs). Tiles appear once the picture shows 1.1 times more detail than the screen image has.
  • The level is the coarsest with at least one tile pixel per device pixel. Every tile corner is rounded to a device pixel and neighbours share corners, so there are no gaps at fractional zoom; each tile's 1 px overlap feeds the interpolation at its edge, so magnified edges show no seam.
  • Missing tiles are drawn from the nearest loaded coarser tile, and the next coarser level is fetched first, so panning never falls back to the blurry screen. Then the tiles of this level nearest the centre, then a ring around the view while it holds at most 40 tiles. Levels passed mid-animation are not fetched.
  • At most six requests in flight and 128 decoded tiles (about 1 MB each), closing the least recently drawn bitmaps (never one drawn in this frame). window.__lpTiles.stats() in DevTools shows the live layer.

Caches​

CacheWhereSizeNotes
Encoded thumb/screen responsesmemory256 MBcache.rs, byte-budgeted LRU
The same, on disk<data dir>/cache, on macOS ~/Library/Caches/com.librephotos.viewer/thumbs (or LPVIEW_CACHE_DIR)1 GBonly responses that took 12 ms or more
Tilesmemory and <data dir>/tiles, on macOS ~/Library/Caches/com.librephotos.viewer/tiles96 MB and 2 GBsee above
Server thumbnails<data dir>/server-media/<server>-<user id>/the remote route
Decoded images in the webviewsrc/lib/imageCache.ts48 pictures

The disk cache (diskcache.rs) keeps one file per response under <root>/v1/<hh>/<hash>.lpc. The file starts with the full cache id (kind, box, mtime, size and path of the source), so a hash collision or a torn file is a miss, never a wrong picture. Writes go through one background thread (temp file plus rename, so readers and a second app instance never see half a file); when 512 writes wait, more are dropped, since the cache is best effort. "Used" is the file's mtime, refreshed by a hit at most once an hour; a sweep deletes the least recently used files down to 90 % of the cap, plus temp files older than an hour left by a crash. The first sweep waits 20 s after start-up so it does not compete with the first pictures. Several processes can share the directory: every operation tolerates files appearing or vanishing underneath it.

appdirs.rs puts everything under one data directory (%LOCALAPPDATA%\com.librephotos.viewer, macOS ~/Library/Application Support/com.librephotos.viewer, else $XDG_DATA_HOME/com.librephotos.viewer); LPVIEW_DATA_DIR moves all of it, the WebView2 profile included, so test runs never touch the user's state. The Microsoft Store package keeps it in its own package folder and imports the installer build's library once, see Desktop app: Microsoft Store package; the Mac App Store build keeps it in its sandbox container and imports nothing, see Desktop app: macOS builds.

Local database​

The desktop's executor for packages/local-db is src/db/executor.ts over the Rust commands db_exec and db_batch (localdb/). The wire format (row shapes, value tags, transaction rules) is in the contract; the reasons behind it:

  • Answers are JSON that Rust writes while SQLite steps, sent as raw bytes (an ArrayBuffer the executor parses), so no row is copied out of SQLite first. Handing the answer over as a script instead (webview.eval) measured about 45 % slower for a 900 KB page on WebView2.
  • Exact values: plain JSON for null, strings, finite reals and integers within 2^53 - 1; anything else is a one-key tag object ($bigint, $blob, $real). A result says whether it holds a tag at all (tagged), so the executor only walks the rows that need it. SQLite stores NaN as NULL, so the only non-finite reals are the infinities. Parameters are deserialised by hand (localdb/value.rs): serde's untagged buffers every value first, which made a 2,000-statement batch spend about 60 ms in parsing alone.
  • One connection behind a mutex (WAL, synchronous=NORMAL, foreign keys off like mobile's expo-sqlite connection), with a cache of 256 prepared statements, since Drizzle sends the same SQL again and again. A transaction never outlives one call, so the package writes several statements with db.batch([...]), never db.transaction().
  • Changed tables: sqlite3_update_hook collects the tables a call writes; once it committed they go to the change hub (localdb/changes.rs), which opens a 40 ms window at the first change and sends one db://changed with every table touched in it, so a walk inserting thousands of rows is a handful of events and the first is never more than a window late. Writes to a virtual table's shadow tables (the FTS index, written by triggers) are left out: a listener of the indexed table hears about the change already. A DELETE FROM t without WHERE would empty the table without visiting rows (the truncate optimisation), which the update hook does not see, so the authoriser answers SQLITE_IGNORE to that delete, which keeps the delete and turns the optimisation off; DROP TABLE and DROP VIEW ask for the same authorisation right after their own, where SQLITE_IGNORE would skip the drop, so those (and the schema table's) are allowed.
  • Migrations (localdb/migrate.rs) apply the package's migrations/migrations.json, compiled in with include_str!, the way the package's runMigrations does: each missing tag in its own transaction with its row in __local_db_migrations. If one fails the database is wiped and rebuilt: the rows of outbox and upload_queue (PRESERVED_TABLES) are read out, every view and table is dropped, every migration applied from scratch, and the saved rows go back with the columns that still exist (INSERT OR IGNORE). The server mirror is disposable and the library is walked again. db_info reports it. The file is local.db; the Rust library before the shared package used library.db, which is no longer read.
  • Live queries (src/db/live.ts) follow mobile's, without React Query: a query runs when a view shows it and again when the change hub flushes a write to one of its tables, answers are cached per key (a view shown again paints at once while it re-reads), and the newest read wins. While the grid scrolls the hub holds its re-reads (defer).

window.__lpDbBench() (src/db/bench.ts) measures the IPC round trip in the real app on its own __bench_photo table shaped like mobile's remote_photo; targets are a 5,000-row timeline page under 30 ms and a 2,000-row batch insert under 100 ms. cargo run --example localdb measures the Rust half alone on a 50,000-row table.

File seams​

platform/ is what the desktop knows about files on disk, handed to the TypeScript writers of packages/local-db as data, the way mobile's native modules hand over the camera roll. Nothing in it writes a database.

  • Walk: supported files in batches of 500 as they are found. Hidden folders, $RECYCLE.BIN and Synology's @eaDir are never entered; a subfolder that cannot be read is skipped, but a root that cannot be read fails.
  • Watch (platform/watch.rs): one recursive notify watcher per root, events debounced per root (350 ms quiet, 2 s at most) and resolved against the disk, so the final state wins (a file created and deleted within one batch is only removed). A folder that appears is walked. Removed paths may be folders, so the writer deletes the path and everything below it. Renames keep the row (its MD5 and server state): Windows reports a rename in two events and Linux in one (plus the halves), macOS (FSEvents) in two unpaired name events, which are paired when the first path is gone and the next one exists, a chain a -> b -> c is one move, a rename to a kind the library does not keep (a.jpg -> a.txt) is a removal, and renames out of or into the root are removals and creations.
  • Metadata: headers only, no pixels, on four threads, at most 4,096 paths a call. Dates taken are local wall-clock milliseconds (an EXIF date has no time zone), which the UI reads with the UTC getters of Date.
  • Symlinked roots (macOS): FSEvents reports real paths, so under a root like /var/folders/... (really /private/var/folders/...) the events are rebased onto the root that was watched (rebase in platform/watch.rs).
  • XMP sidecars: Noch nicht erschienen (kommt nach 1.7.0) a file's sidecarMs is the mtime of its sidecar (IMG.xmp, else IMG.jpg.xmp, the names existing_sidecar tries; compared ignoring case on Windows and macOS, exactly elsewhere). A walk reads it from the directory listing it already has. fs_stat (stat_many) lists a folder once when a call asks for 16 or more of its files (a walk batch) and finds names in that listing through a hash set; a call with fewer files stats each one and checks the four sidecar names. The watcher lists a folder only to find the pictures of a changed sidecar, once per batch. The indexer keeps it in its own column (sidecar_modified_at): a changed sidecar only asks for the metadata again, the picture keeps its hash and dates. The info cache keys on sidecarMs too. A sidecar's own event reports its picture as modified.
  • Names on disk: Noch nicht erschienen (kommt nach 1.7.0) fs_stat answers the whole path as it is on disk, folders included, from the OS: GetFinalPathNameByHandleW on Windows (through std::fs::canonicalize) and fcntl(F_GETPATH) on macOS (real_path in platform/files.rs); Linux volumes are case-sensitive and need nothing. So a path asked in another case (trip/a.jpg for Trip/A.jpg, or ä for Ä, folded the way NTFS and APFS fold names) answers the real path, and on a case-sensitive volume it answers nothing. Only the trailing components that differ from the asked path by case alone are taken from the real path; a prefix it spells differently (an 8.3 short name, a symlink or junction on the way) stays as asked, and so does every component down to the deepest symlink or junction among them: a junction photos that points at a folder Photos keeps its own spelling, and only the names below it are corrected. The corrected path is used only when it exists as spelled; on a case-sensitive volume, or a Windows folder made case-sensitive (fsutil file setCaseSensitiveInfo), the OS answers the path as asked, so nothing is respelled there. On macOS the file is opened with O_EVTONLY for F_GETPATH, which needs no read access and does not hold up an unmount. The indexer renames the rows of paths found under another spelling in one batch, so a case-only rename of a file or a folder keeps one row per file with its edits.
  • Lost events: Noch nicht erschienen (kommt nach 1.7.0) notify's Rescan flag (an overflowing event queue) and a watcher error end in rescan: true; the indexer watches the root again and walks it, at once the first time and then after 30 s doubling up to 15 minutes while the root keeps losing its watcher (Linux's inotify limit). Notify 8's Windows backend reports neither an overflow nor a root it stopped watching, so on Windows the indexer also watches every root again and walks it every 15 minutes (safetyWalk). That walk passes the folder times of the last walk (fs_walk's since): Rust still reads every folder (one directory listing and one stat each) but sends only the files of folders whose own mtime changed, which NTFS updates when an entry is added, removed or renamed. The indexer then reads the known rows of those folders only, and re-stats the rows below a folder that is gone. Each folder's time is read before the folder is listed, so a file added while it is listed leaves the folder newer than the time kept, and the next walk reads it again. FAT, FAT32 and exFAT volumes (USB sticks, SD cards) do not keep folder times current on Windows; fs_walk asks the volume's file system (GetVolumeInformationW) and walks them fully every time. A file changed in place, in a folder that nothing was added to or removed from, is not caught by this walk. A root whose walk is still running skips the cycle; after a start the first cycle walks fully. On a network share (SMB) the listing and the stat of every folder go over the network, so a share with many folders costs that many round trips every 15 minutes even when nothing changed. At the end of every walk the indexer reads the root's rows again in the chain, then re-stats the rows the walk did not see and the walked files whose rows changed meanwhile, so a file a watcher event added and removed during the walk does not keep a row.
  • Normalised roots: C:\Pics\ becomes C:\Pics and, on Windows, / becomes \ (normalize_dir in platform/files.rs, mirrored by the indexer in src/library/indexer.ts); a drive root keeps its separator.

The indexer (src/library/indexer.ts) drives the writers from these seams: it walks and watches every root at start and diffs each batch against the known rows by size and mtime, runs the metadata pass (256 files a batch, newest first) and, while signed in, the hash pass (32 files a batch, four at a time), then wakes the backup engine. The steps and the writers are listed in the contract's "Library" section.

Noch nicht erschienen (kommt nach 1.7.0) Every write the indexer makes from the disk goes through one chain (inLane): walk batches, the walk's gone-sweep, the known rows a walk starts from, and the watcher's batches. Each write stats its paths again right before it writes (syncPaths), so a batch never writes a stat older than one already applied, and a change that happens between the stat and the write sends a new event that comes later in the same chain. A rename from a path without a row (a temp file or a .crdownload) keeps the target's row and updates it from the stat. Pictures opened from elsewhere get their row through the same chain (writeLooseFile). New rows take their path as id unless a renamed row still holds that id. The metadata pass stores a result only WHERE the row still has the size, mtime and sidecar time it claimed, the hash pass the size and mtime. The model verification/desktop-data/LibraryIndex.tla checks this, including lost watcher events and case-only renames on a case-insensitive volume; it caught that the known rows must be read in the chain too.

The timeline's layout (src/library/layout.ts) follows the web app's react-pig: day groups of justified rows, a day short enough for one line sharing it with the next days, as in Immich and Google Photos. It is plain arithmetic over aspect ratios the library rows already carry (3:2 until a file's header is read), so it never reads the DOM; the result is a flat list of blocks sorted by top, which Grid.tsx binary-searches to render only what is in view (plus 800 px).

Server connection and backup​

Every request is an endpoint function of packages/api-client (src/server/session.ts holds the one client). Rust only:

  • carries the bytes (server/http.rs): the api-client's native transport (see Native transports) hands over a framed request, reqwest sends it, and the framed answer comes back, so CORS and the webview's cookie jar and limits never apply. Only URLs of the connected server, or the one being signed in to (server_prepare_sign_in), are sent. A request's nativeFilePart markers are replaced by up to 64 MB of a library file, read in Rust, so an upload chunk never crosses IPC.
  • keeps the session: the server address, user and backup switch in settings.json, the refresh token in the OS keychain (Windows Credential Manager, macOS Keychain, the Linux kernel keyring, via keyring), never in web storage. auth.rs normalises the address typed into the sign-in form (https:// assumed, http:// only for this machine and the local network, a pasted /api dropped) and reads the access token's user_id and exp claims without verifying them (the server does that; the client only needs to know who it is and when to refresh).
  • proxies server thumbnails for the remote route (square_thumbnails and thumbnails_big of the connected server only), with the access token the UI last handed over (server_set_access) and a disk cache. The UI refreshes the access token a minute before it expires (endpoints.refreshAccessToken), so server thumbnails keep loading while no API request is due. Noch nicht erschienen (kommt nach 1.7.0) A request takes the address, the user and the token in one step (media_session), and a sign-in forgets the old tokens before it stores the new address, so they always belong to the same sign-in. verification/desktop-io/DesktopSession.tla checks the first half. In the app, and in the model, a sign-in always follows a sign-out, so the old tokens are gone before it starts; the test a_new_address_is_never_seen_with_the_former_tokens in src-tauri/src/server/mod.rs checks that a sign-in forgets them itself too.

Contract errors (src/server/errors.ts): an answer that breaks its schema is logged with its endpoint and shown as a toast, at most once per endpoint every 30 s, and is never read as an empty answer.

The backup engine (src/server/backup.ts) is TypeScript and its queue is the shared database's upload_queue, so nothing is lost on a restart or a reloaded UI. One checker (32 rows a claim, four uploadExists at a time) and two uploaders (8 MB chunks, a re-stat and a dedupe check before each upload) run while the window is open; the steps, the backoff and the resume rules are in the contract's "Backup" section. A network error, a 5xx, 429 or 401 is not the file's fault: the row goes back in line and the attempt does not count, and the loop waits 15 s. Noch nicht erschienen (kommt nach 1.7.0) The same goes for a page that a proxy or a captive portal answers while the server is away (isUnreachable, see local database); when the server is up and the page comes all the same, as from a proxy that refuses large requests, the try counts and the file stops after five. Before, a 404 from a proxy during a restart counted against the file. Idle loops look for work every 5 s even without a wake-up. When the queue runs dry the collected job_ids are sealed (sealUploadImports), so the server's import jobs finish at once instead of after a few idle minutes. device_modified_at is the file's mtime in ISO 8601 local time with its UTC offset.

Noch nicht erschienen (kommt nach 1.7.0) Each check and upload remembers the account it runs for and sends its requests through forUser (a request refuses to go out once another user's token is held). An upload's requests also carry its own AbortController's signal: setUploadsPaused(true) and a sign-in to another account (stopJobsOfOtherAccounts) abort it, which cancels the request in flight (http_fetch_abort) and refuses the next one, and the row goes back to pending with the offset the app last recorded (setUploadProgress after each answered chunk; a server that holds more answers 400 with its offset, and the upload continues there). Answers are written with an UploadClaim (see local database), so an answer for a row that an account switch replaced is dropped, and one that arrives after its account signed out puts its row back in line. The models verification/desktop-io/BackupSwitch.tla and BackupPause.tla check both.

Edits​

Ratings, captions, keywords and the date taken are written where other photo apps read them: an XMP sidecar by default, the JPEG's own XMP segment, or the local database only. src-tauri/src/xmp/ is a small XML scanner that splices the changed properties into the original packet, so everything else in it stays byte for byte; a sidecar that does not parse is refused, never overwritten. When signed in, each edit is also queued in outbox and replayed against the server by src/edits/serverSync.ts. Noch nicht erschienen (kommt nach 1.7.0) An entry names the server and user it was made for, and the replay claims only the signed-in account's entries and checks before every request that the session is still that account, so an entry neither blocks another account's nor reaches a server with the same user id. Offline and server errors back off without using up attempts. Each send goes through its own client that checks the account in the fetch that sends the request, so a sign-in while it awaits a token cannot send it elsewhere. Entries an older version queued without a server are adopted once, by the live account if it is folder_account and they were queued since its last switch, and parked with Discard otherwise. Transient failures back off up to 16 minutes without counting; repeated 500s count and stop after 8. An edit is refused only by an error of the server's own; a page from a proxy or a captive portal is an outage, unless the server is up, and then the try counts (judgeFailure in packages/api-client, see local database). Before, a proxy's 404 during a restart ended the edit, and it was sent only after "Try again". A keyword edit is the keywords added and removed, and a picture saved into its file is found on the server by any of the MD5s it had before the app's saves (app_meta server_md5s:<path>). The tags, the sidecar names and the replay are in the contract's "Edits" section; what users see is in Editing a picture's details.

Noch nicht erschienen (kommt nach 1.7.0) Every write into a file, a save of details or a rotation, holds a lock on each file it writes (src-tauri/src/filelock.rs, keyed on the canonical path, so two pictures sharing one sidecar share its lock) from its read to its rename, writes a temp file of its own and syncs it, and renames it over the file only if the file's size and mtime are still the ones it read. The next write of a file removes temp files a crashed run left next to it. A rotation that only changes an existing orientation tag patches those bytes in place under the lock. The model verification/desktop-data/WriteBack.tla checks it, with the check and the rename as two steps; another app that saves between those two system calls still loses its save.

Noch nicht erschienen (kommt nach 1.7.0) A JPEG whose XMP packet also carries tiff:Orientation is no longer patched in two places in turn: both the EXIF tag and the XMP digit are changed in a copy that replace_file renames over the file, so a crash never leaves them disagreeing (verification/desktop-io/RotateWrite.tla). After every write (replace_file and rotate_file) filelock::move_mtime_past makes sure the file's mtime, in milliseconds, is newer than the one it read; when the file system kept it (FAT32 stores 2 s steps, HFS+ 1 s, and NTFS can land in the same millisecond) it is set to the old mtime plus MTIME_STEP (2 s), or to the current time when that is later. On a coarse file system each further rotation within the step moves it another 2 s ahead of the clock; the first write after the clock has caught up keeps the file system's own time again. Every cache is keyed by mtime (the memory and disk caches, tiles, the lpview URL's v= that the webview keeps as immutable), so a rotation always gets a new key (MtimeCache.tla). Rotating a PNG keeps its metadata: pngmeta::carry_metadata copies the colour chunks (iCCP, sRGB, gAMA, cHRM, cICP, mDCV, cLLI), eXIf and the text chunks (tEXt, zTXt, iTXt, where XMP lives) into the re-encoded file, applies an EXIF orientation to the pixels first and resets it to 1 in eXIf and in the XMP packet's Orientation of the TIFF namespace (a compressed iTXt XMP chunk is stored uncompressed then, and a malformed one is copied as it is), so what was shown is what is turned, and swaps the axes of pHYs only when the stored picture's axes swap (orientations 5 to 8 turned once more do not). An animated PNG (one with an acTL chunk) is not rotated on disk, since image would keep its first frame only; the call rejects and the viewer turns it on screen. The same goes for a compressed XMP chunk that inflates to more than 8 MB (MAX_XMP): a few KB can hold gigabytes, and a copied chunk with its old orientation would make XMP readers turn the rotated picture once more. JPEG and PNG find the XMP orientation with the same function (xmp/orientation.rs): attributes in either quote and elements, with spaces allowed around the = and the digit, for the prefixes bound to http://ns.adobe.com/tiff/1.0/ (tiff when none is declared), only where the whole name matches. It answers the positions of the digits, so a JPEG's packet keeps its length.

Noch nicht erschienen (kommt nach 1.7.0) A rewrite is a new file, so replace_file first gives its temp file what the old one had: on macOS the extended attributes (Finder tags, quarantine) and the ACL through fcopyfile, and on every Unix the permission bits; only then is the data written. Times are not copied, and the write and move_mtime_past come after the copy, so it cannot bring back the old mtime. A failure to copy is ignored. Not kept: the creation date, extended attributes on Linux, and on Windows alternate data streams and ACL entries set on the file itself, as with every rename over a file; ReplaceFileW would keep those, but it can leave the photo under the temp file's name when it fails halfway.

Noch nicht erschienen (kommt nach 1.7.0) Moving a file to the trash takes the file's lock too. lpview requests never get the pre-warm priority (p=idle is read as p=low), since prewarm_thumbs drops that lane, and a request in it would never be answered.

Design tokens and UI primitives​

The desktop has no Mantine; it draws the web app's Mantine 9 theme with plain CSS so it reads as the same product. src/styles.css holds the tokens (--lp-color-*, --lp-radius-*, --lp-space-*, --lp-font-*, --lp-shadow-*, --lp-z-*, sizes such as --lp-topbar-height), taken from apps/frontend/src/theme; new CSS uses them, never raw colours (the short legacy names at the end of the file, --bg, --surface, --text, are only for older code). :root follows prefers-color-scheme; .lp-dark forces the dark values on the viewer (top bar, stage, filmstrip, info panel), which is dark in both schemes like the web lightbox; .lp-app-scheme brings the app's scheme back for menus and dialogs opened from the viewer, as Mantine's portalled dropdowns do on the web. Photo-side colours (--lp-stage, the scrims) are the same in both schemes.

src/ui/ re-creates the Mantine components the desktop needs as small React components over plain classes: ui.css (buttons, icon buttons, CSS-only tooltips through data-tip, menus, panels, detail rows, checkboxes) and controls.css (Button variants, inputs, Switch, SegmentedControl, Badge, Progress, Card, NavLink, Alert, Loader, Modal, EmptyState, Avatar, PageHeader). Each class names the web component it follows; the web sources are the reference when one of them changes.

Running, testing and measuring​

npm ci, npx tauri dev / npx tauri build (in apps/desktop)run or build the app
npm run devthe UI alone in a browser, answering from a mock in src/ipc.ts; ?empty starts with nothing open, ?big with 2,000 files
node node_modules/typescript/bin/tsc --noEmit, node node_modules/vite/bin/vite.js buildthe UI's checks
npm testNoch nicht erschienen (kommt nach 1.7.0) the UI's vitest tests (src/**/*.test.ts); src/test/nodeDb.ts gives them the shared database's migrations on Node's built-in node:sqlite, behind an executor that answers asynchronously like the Tauri one
cargo fmt --check, cargo clippy --all-targets -- -D warnings, cargo test (in src-tauri)the Rust checks
cargo test --test corpus -- --ignored --nocapture --test-threads=1tests against the real files of desktop-test-corpus
cargo run --example bench -- [--full] [--quick] [paths...]decode times per file (thumb, a 2560 x 1440 screen, full), cold and cached, as Markdown tables with per-format medians
cargo run --example tiles -- [image] [--all] [--fill]cold tile latency per level, the whole pyramid with --all, background fill on with --fill; uses a fresh disk cache in %TEMP%. It also measures the colour step across tile edges against the step across the source JPEG's own 8 px block edges (1.0: tiling adds nothing)
cargo run --example localdbthe Rust half of the local database's IPC cost

The dev profile builds every dependency at opt-level = 3 (decoders are unusably slow unoptimised) and the app's own crate at 2, so its pixel loops are fast while it still rebuilds quickly.

For test runs over the Chrome DevTools Protocol the page exposes window.__lpDev() (library and server calls a native dialog or a click would make, such as addLibraryRoot(path)), window.__lpDbBench() and window.__lpTiles, each loaded on first use.

VariableDoes
LPVIEW_DATA_DIRmoves the database, settings, every cache and the WebView2 profile
LPVIEW_CACHE_DIR, LPVIEW_DISK_CACHE=0move or turn off the thumbnail disk cache
LPVIEW_TILE_CACHE=<dir> or =off, LPVIEW_TILES=offmove or turn off the tile disk cache; no tiling at all (big pictures load full, for comparisons)
LPVIEW_SCREEN_PASSTHROUGH=<n>see Decode pipeline
LPVIEW_TRACE=1, LPVIEW_TILE_TRACE=1, LPVIEW_DB_TRACE=1log every lpview request (queued, memory or disk hit, decode), the cost of every tile band, every database call's statements, time and answer size to stderr
LPVIEW_KEYRING_SERVICEthe keychain service the refresh token is stored under (tests)
LPVIEW_MULTI_INSTANCE=1lets several copies run side by side (test harnesses)

CI and releases​

Neu in 1.7.0

.github/workflows/desktop.yml runs on Windows and macOS for every pull request and push to dev that changes apps/desktop, packages/api-client or packages/local-db, and for every release:

JobDoes
checknpm ci, the UI's typecheck, tests and build, cargo fmt --check, cargo clippy --all-targets -- -D warnings and cargo test
installerbuilds the NSIS installer with npx tauri build --bundles nsis, stamped with the release tag (0.0.0 outside a release), and smoke-tests it with apps/desktop/scripts/smoke-installer.mjs
msixpackages the same exe as an MSIX for the Microsoft Store, installs, launches, imports and removes it on the runner, runs the Windows App Certification Kit and, when configured, submits it to the Store; see Desktop app: Microsoft Store package
macos, macos-smoke, macos-releaseclippy and the tests on macOS, the universal app as a disk image and a Mac App Store package, both installed, opened and removed on Apple Silicon and Intel runners, signed, notarized and uploaded when configured, the disk image attached to releases; see Desktop app: macOS builds

The smoke test is what a user does, once per install scope (--scope user, the default, and --scope machine): it installs silently (/S with /CurrentUser or /AllUsers), reads where the program went from InstallLocation of the scope's Uninstall\LibrePhotos Viewer key (HKCU or HKLM, which must also carry the CurrentUser or AllUsers marker) and fails unless that folder is under %LOCALAPPDATA% for user or %ProgramW6432% for machine, checks the registry entries the installer hooks write for Open with and Set as default photo viewer (RegisteredApplications, Capabilities\FileAssociations, the LibrePhotosViewer.Image ProgID, .jpg\OpenWithProgids, the Applications entry, App Paths) and that .jpg's default class is the one it found before installing, starts the installed app on a picture and waits until its window title is <picture> - LibrePhotos Viewer (the viewer sets it once it has listed the folder and opened the picture; GitHub's Windows runners don't answer on WebView2's remote-debugging port, so the test reads the title through Windows instead), then uninstalls silently and checks that the program, its Uninstall entry and its registration are gone and .jpg's default class is unchanged. When it fails it prints every librephotos-viewer.exe under %LOCALAPPDATA%, %LOCALAPPDATA%\Programs and Program Files, and the Uninstall and Software\librephotos\LibrePhotos Viewer keys of both hives, so the log shows where an install actually landed. Run it locally with node apps/desktop/scripts/smoke-installer.mjs [--scope user|machine] <setup.exe> <picture>; user installs into your own profile, machine needs an elevated shell.

Every build uploads the installer as the workflow artifact librephotos-desktop-windows-x64. For a release (release: created, not drafts or pre-releases) it is also attached to the release as librephotos-desktop-<tag>-windows-x64-setup.exe, as librephotos-desktop-windows-x64-setup.exe (the name the user guide's releases/latest/download link uses) and with SHA256SUMS-desktop. A tag must be X.Y.Z. A failed release build opens an issue. To build a release's installer again, dispatch the workflow from the tag: gh workflow run desktop.yml --ref <tag> -f tag=<tag> (-f replace_asset=true to overwrite assets it already has).

Third-party notices​

apps/desktop/public/THIRD-PARTY-NOTICES.txt lists every open-source component the app ships, with its license text, which the licenses require in every copy. apps/desktop/scripts/notices/generate.mjs writes it from the lockfiles: the Rust crates cargo metadata --filter-platform x86_64-pc-windows-msvc resolves as normal dependencies of the app (build and dev dependencies are not shipped), and the npm packages in apps/desktop/package-lock.json that are not dev, each with the LICENSE, COPYING, NOTICE and similar files from its folder. Identical license texts are printed once and referred to by number. --target picks the platform (repeat it for a universal build) and with it the header's last paragraph, which names the system components that decode HEIC, HEIF, AVIF and video there: Windows Imaging Component, Media Foundation and WebView2 on Windows, ImageIO and WebKit on macOS. The committed file is the Windows one. The header carries the sentences two licenses ask for word for word: Adobe's DNG patent license ("This product includes DNG technology under license by Adobe.") and the IJG license of jpeg-encoder, plus where the MPL-2.0 crates' source is.

The file ships three ways: Vite copies public/ into the UI, so it is inside the exe and Settings > About LibrePhotos Viewer > Open-source licences shows it (library/AboutCard.tsx); bundle.resources puts it next to the exe in the NSIS install; and scripts/msix/pack.mjs --notices puts it into the MSIX. The macos job writes it again with --target aarch64-apple-darwin --target x86_64-apple-darwin before building, so the Mac app (in its UI and in Contents/Resources) lists the crates it contains, and the macOS smoke test checks it. The installer job generates it again before building, so a release always matches its lockfiles, and the smoke test and the msix job fail when it is missing. After changing dependencies, run node apps/desktop/scripts/notices/generate.mjs (after npm ci in apps/desktop) and commit the result; node --test apps/desktop/scripts/notices/generate.test.mjs tests the generator.

The installer asks whether to install just for the user (%LOCALAPPDATA%\Programs\LibrePhotos Viewer, no administrator rights) or for everyone (C:\Program Files\LibrePhotos Viewer, installMode: "both") and is not signed yet, so Windows SmartScreen warns about it. With installMode: "both" Tauri's template leaves the folder to NSIS's MultiUser.nsh, which puts a per-user install into FOLDERID_UserProgramFiles (%LOCALAPPDATA%\Programs), not into %LOCALAPPDATA%\LibrePhotos Viewer like Tauri's own currentUser mode. A machine that installed an earlier build keeps that build's folder: the template restores the previous location from Software\librephotos\LibrePhotos Viewer in the install's hive, and a silent uninstall leaves that value behind. Scripts therefore find an install through InstallLocation in Software\Microsoft\Windows\CurrentVersion\Uninstall\LibrePhotos Viewer, never through a fixed path. The app keeps its data in a different folder named after the bundle identifier (com.librephotos.viewer, appdirs::DIR_NAME, held equal to tauri.conf.json by a test), which is the folder the uninstaller's Delete the application data option removes.