docs/ARCHITECTURE.md

Native application architecture

Development guide · User guide

Splotch & Blot is a Linux GTK4 raster editor. cmd/native, built with -tags gtk, owns each window's document and editing lifecycle. GTK, Pango, Cairo and mutable editor state stay on the GTK main thread; workers receive independent pixel copies or exclusive ownership of filesystem work.

main.go runs a GtkApplication. Activation opens a blank editor; file-open signals open one window per file, including files forwarded by a second launch. Windows have independent history and recovery records even when they open the same source. The application is offline: runtime inputs are local files, clipboard data and text, not remote resources.

Boundaries and file map

Root packages are application components, not a stable external library API. They do not depend on editor widgets:

PackageResponsibility
toolsTool catalog, icons, mnemonic keys and shared-option flags
colorspaceOpaque RGB colors and picker conversions
rasterMasks, connected regions, fill, edge coverage and changed-region detection
texteditUTF-8 text and caret editing
imagefileBounded PNG/JPEG decoding, EXIF orientation and destination coordination
capacityIncremental allocation estimates and Linux memory observations
sessionstorePrivate artwork, canonical metadata, ownership and publication
stickersBuilt-in designs and size helpers; only render.go requires GTK/Cairo

Keep editor state in cmd/native; extract a package when it has an independent boundary, not merely to shorten a file.

Area in cmd/nativeStarting points
Window assembly, actions, shortcuts and statusui.go, ui_actions.go, ui_keys.go, ui_header.go, ui_status.go
Tool selection, options, palette and color pickerui_toolbox.go, options.go, color.go
Dialogs, theme and Helpui_dialogs.go, ui_theme.go, help.go, shortcuts.go
Document lifecycle and manual I/Oeditor.go, document.go, manual_io.go
Session creation, publication and artifact stagingsession.go
Visible snapshots and autosavesession_snapshot.go
Session retirement and recoverysession_retirement.go, recovery.go, recovery_async.go, recovery_delete.go
Canvas input and renderingui_canvas.go, ui_workarea.go, canvas_gesture.go, touch.go, canvas_view.go, view.go
Drawing tools and resize previewspaint.go, rectangle.go, curve.go, resize_preview.go, text.go, sticker.go
Selection and clipboardselection.go, canvas_selection_ops.go, clipboard_stream.go
Pending edits and historycanvas_state.go, undo.go
Capacity admission and large-image importcapacity.go, large_image.go

Document and edit ownership

The editor owns committed pixels (surface), pending floating pixels, curve and text drafts, history and revision state. Embedded UI/text state marks ownership, not separate goroutines. View surfaces cache zoomed-out rendering; they are not additional documents. The committed canvas is always opaque.

An edit has three distinct stages:

  1. Checkpoint before mutation. checkpoint must succeed before painting. It assigns a revision and retains the prior state for undo.
  2. Change pixels and invalidate rendering. imageChanged invalidates the affected cached region. Dimension changes use replaceCanvasSurface to replace the surface and reset dimension-dependent selection/view state.
  3. Finish the edit. finishEdit stores only the changed rectangle. A no-op restores the revision, redo and other state disturbed by checkpointing.

commit applies pending artwork; it is not the same as finalizing its history entry. settleEdit finishes a checkpoint only when no draft can still paint into it. Read canvas_state.go and undo.go before adding a mutation path: bypassing this lifecycle can make pixels, undo and saved state disagree. status also calls syncUI; it is not a label-only setter.

Unsaved state compares the current revision with the saved revision. Undoing past a save is therefore unsaved again. New and Open reset history rather than allowing undo into a discarded document. confirmDiscard inspects visible pending work without applying it: Cancel must leave drafts and history intact. Save must successfully commit drafts before capturing the revision it will mark saved; Export and recovery instead capture the visible image without committing. A failed I/O step after Save has committed a draft does not roll that commitment back.

Delayed chooser, clipboard and save callbacks must belong to the document that started them. Document epochs, operation/request generations and text-draft identity reject stale delivery after replacement, another operation or close. Finish GDK results even when ignoring them. A successful old Save is not permission for a continuation to discard newer artwork or drafts.

Workers and responsiveness

Autosave detaches the visible image on GTK, excluding handles and caret, then encodes off-thread. There is one encoder and no image queue per document. A pixel digest avoids unchanged snapshots. Newer gestures do not invalidate a completed point-in-time snapshot: otherwise continuous drawing could prevent recovery publication indefinitely. The polling interval is not a durability deadline.

Manual operations first join an outstanding encoder without blocking GTK, then transfer exclusive session ownership to one worker. The affected editor pauses editing; sibling windows remain usable. Buffered result channels return ownership before GTK updates. No nested event loop or queued manual operation is used. Open decoding, destination inspection and recovery filesystem work also run off-thread; GTK rendering and immutable pixel capture do not.

Widget-free editor entry points provide synchronous Save, replacement and restore paths for tests. Window actions use the asynchronous paths; the synchronous helpers are not GTK I/O callbacks. Tests of a synchronous entry point alone do not exercise worker hand-off, stale completion or recovery consent in the window path.

The shared metadata lock can delay every window's recovery publication. Editor stores bound metadata-lock waits to five seconds and expose retryable errors; this does not bound arbitrary filesystem/kernel I/O stalls. Replacement and teardown must invalidate continuations and join workers before retiring or removing private artwork.

Saving: preserve file identity, not atomic visibility

imagefile/target.go coordinates cooperating local clients with canonical pathname locks, followed by a descriptor lock for existing inodes. Path locks serialize new-file creators; inode locks coordinate symlink/hardlink aliases. Identity checks compare device, inode, size and timestamps against Open/last Save or explicit Save As confirmation. Destination I/O never holds the recovery metadata lock.

Save stages and verifies the exact encoded output privately, retains a baseline when needed, and publishes write intent before writing through the destination descriptor. Existing inodes, permissions and aliases are preserved. New targets use exclusive creation. Sync, byte verification and completion publication must succeed before the editor becomes clean. Working-file Save uses its exact path; only Save As normalizes an extensionless chooser name.

This is deliberately not atomic to unlocked readers. An interrupted write can leave an incomplete destination, so recovery retains staged output and original bytes. Original image retention covers the bounded decoder-consumed prefix, not arbitrary trailers. A confirmed non-image overwrite retains complete original bytes only up to 4 MiB; larger unrecognized destinations are refused.

JPEG Export is a separate atomic copy. It excludes the working pathname and remembered/current inode aliases, and does not change the saved revision or apply drafts. Absent export targets are published exclusively, not overwritten by rename. Advisory locks coordinate cooperating local clients, not hostile writers, cross-host filesystems or physical power loss.

Private recovery store

sessionstore is the Linux-only, GTK-independent authority for recovery metadata and artifact ownership. The editor decides Save success, captures visible artwork and supplies user consent; the store does not write destination images or decide which versions are disposable.

Layout and trust

The caller supplies an absolute root, normally $XDG_STATE_HOME/splotch-blot (default ~/.local/state/splotch-blot):

text
1splotch-blot/ private owned directory (0700)
2 index.lock stable lock inode (0600)
3 index.json atomically published schema-1 metadata (0600)
4 .index-* publication temporaries retained on failure
5 <random ID>/ independent document directory (0700)
6 .pending-* unfinished private artifact (0600)
7 <random ID>.blob immutable finished artwork (0600)

The root's parents must be caller-trusted. Validation rejects unsafe private files/directories and internal names, but this is not a sandbox against another process with the same Unix account.

The schema-1 index associates each random session ID with a versioned owner, source association, snapshot, optional save intent/baseline, restore origin, retirement reason and advisory successor. See the types and validation in sessionstore/store.go for exact fields. Source paths are associations, never session keys or destination-write authority. Unknown schemas and malformed or incomplete metadata are errors; only an absent index initializes an empty store. Do not replace an unreadable index with an empty one.

Coordination and uncertain outcomes

  • Every transaction locks index.lock before reading the index and merges only its selected record. Never unlink or replace the lock inode: two processes could otherwise lock different files and lose coordination.
  • Leases carry session ID, owner and transaction version. Publication and ownership changes require a current active lease; caller-owned inputs remain unchanged until the call returns. Separate clients/windows never share a document lease merely because the source is the same.
  • Encoding, hashing, artifact sync and destination I/O happen outside the global metadata lock. No production callback runs under it. Artifact hashes establish byte identity, not image validity; callers verify encoded images before publication.
  • Index publication syncs a same-directory temporary, renames it and syncs the directory. An error after rename may mean the update is visible but durability is uncertain. Reconcile with canonical metadata, not an assumed rollback or a speculative lease. A failed Create proposal may locate retained bytes but is not ownership authority until publication is confirmed.
  • Failed publication preserves stages and unreferenced bytes, including a failed first publication. Retirement records a terminal tombstone; it does not unlink artwork. RemoveRetired is the guarded, retryable removal boundary, after workers have joined. No age expiry, quota eviction, index compaction or automatic orphan garbage collection is implemented.

Fault hooks are deterministic test seams, not production extensions, and must not reenter the store. Tests model specific failures; they are not proof of physical-power-loss or remote-filesystem durability.

Recovery authority and original retention

Owner observation uses local process identity, not idle time. A matching live process remains live indefinitely; PID reuse is checked using process start, boot and executable identity. A client token separately distinguishes leases from independent store clients in the same process. Different boots, permission errors and unverifiable identities are Unknown, not deletion permission. This assumes a locally meaningful /proc namespace, not coordination across machines sharing a home directory.

Inventory exposes recognized retained artwork, including unreferenced stages. It is non-destructive and does not validate images or grant ownership. Recovery rechecks the selected version and liveness under the lock:

  • Locally abandoned owner: the recipient may claim the current record.
  • Uncertain owner: only an indexed, read-only candidate can be copied. No original lease or deletion authority is installed in the restored editor.
  • Live or retired record: not a normal recovery offer. Unindexed artwork is preserved evidence, not a fabricated claimable record.

Restore starts the current executable with validated internal identifiers, makes a verified copy in a new independent unsaved session and never writes the source. It skips recursive recovery prompts. A failed recipient exits after its error is dismissed rather than hiding a claimed original behind an idle live process.

AcceptTransfer records only an advisory successor after the copied snapshot is safely indexed. One copied artifact cannot account for every snapshot, baseline or pending file, so the original remains active. A successor pointer must not filter recovery candidates or authorize cleanup. Repeated offers are intentional.

For a claimed original, successful Save-and-close or explicit Discard can retire it without another prompt only when verified correspondence proves there is exactly one original snapshot and no additional files/save stage. Otherwise the UI asks whether to keep or explicitly delete all original copies. Uncertain originals always remain unchanged. Cancel, failed Save and mere copying never authorize retirement.

Deletion and restored-close completion retain confirmed retry state across failures. RefreshOwned reconciles only an already-owned record; it cannot claim one. An uncertain completion must match the exact proposed transaction, not any later owned version. Unknown outcomes remain protected until reconciliation.

Capacity and input boundaries

capacity estimates incremental allocations using Linux MemAvailable, tightened by measurable cgroup limits including ancestors. Resident canvases, history and captures have already reduced headroom; do not charge them twice. Known zero means exhaustion. Unmeasurable memory uses a 256 MiB incremental fallback; measured systems reserve a quarter of headroom, at least 128 MiB.

Admission includes more than the destination raster: decoder/conversion copies, checkpoint storage, rendering, selection masks/outlines, recovery capture, encoding and verification can coexist. Canvas transitions preflight draft commitment and the old-canvas checkpoint together before mutation. Background encoding rechecks only allocations still ahead. Optional scaled import still decodes the full source; it is not streaming.

These are observations, not reservations or GPU-memory predictions. Structural bounds (32767 pixels per side) and the large-image warning (>8000 on either side) are not usable-memory guarantees. Pressure can reclaim spare storage and older undo/redo while keeping nearest useful entries, then remeasure actual headroom. Freed byte counts are not synthetic capacity credits. History owns its pixels exclusively; it never borrows a reusable spare. Low capacity must not silently make edits non-undoable or delete recovery artwork.

imagefile admits dimensions from a bounded header before decoding. It replays that exact prefix, rather than rewinding mutable input and accepting a different allocation-driving header. Header/EXIF reads are bounded to 4 MiB; decode input to 16 bytes per declared pixel plus 4 MiB. Trailers are not image content. Regular file checks reject special files without waiting for FIFO data, and before/after identity checks reject changed inputs.

Clipboard image streams pass this boundary before GDK texture decoding. Each editor has one active transfer/consumer and one latest queued request without data; superseded work is canceled before its successor starts. Cancellation cannot interrupt an individual Go decoder CPU operation, so generation checks remain the final delivery guard. Text drafts/paste are bounded to 64 KiB UTF-8.

File/chooser/drop/launch inputs require local filesystem paths. User text and metadata use plain GTK/Pango text, never markup, shell commands, SVG, a webview or URL launch. Built-in SVG is application-owned; arbitrary user SVG is not an import format. Build/source retrieval networking is separate from the runtime.

Extending the editor

For a tool, start with tools.All, then canvas gesture handling and its options. Catalog consumers supply toolbar keys and keyboard Help, but detailed Help prose in help.go still needs updating. Keep reusable pixel/text logic in the matching subpackage and respect preview-versus-commit and image-versus-screen coordinates.

For a document action, register it in ui_actions.go and the header menu as appropriate. Reuse the edit, admission and asynchronous ownership boundaries; do not add a second document or recovery authority. Add focused coverage for new contracts rather than asserting incidental UI structure. Build/test and dedicated-display requirements belong in DEVELOPMENT.md.