Saved brush presets

Canoli Studio provides a local brush library for Brush, Pencil, Eraser, Clone, Dodge, Burn and Spot Healing. Open Brush presets… in their tool options. Four read-only starting presets are supplied: Hard round, Soft shading, Pixel pencil and Soft eraser. Select a preset and Apply, or double-click its row. Search matches names and tool names. Applying changes future tool settings and selects the preset's tool; existing artwork and ordinary/filter-mask paint targets remain unchanged. Opening the modal cancels transient gestures. Applying through the trusted controller validates the complete value before cancelling a live gesture.

Use Preset name and Save current as new to capture the current toolbar settings. Include current foreground color is unchecked by default: a preset without color preserves the current foreground when applied. Named values contain size, hardness, opacity, flow, spacing, smoothing, pressure-size/opacity flags, the authored pressure curve, optional tip/symmetry metadata, aligned clone sampling, tonal range/exposure/protection, and healing radius/sampling/detail. Image-backed texture presets retain their original source blob and TIFF/AVIF decode choices. They do not contain clone anchors/sample tiles, document/layer IDs, selections, paint targets, paths, scripts or permissions. Active settings remain transient; saved named values persist independently.

Rename edits a saved name. Update from current tool replaces the selected saved preset's tool/settings and optional color with the current toolbar state. Duplicate creates a separate editable copy, including of built-ins; Delete removes only that saved value. Preset preferences are outside document undo. Each subsequent stroke still captures its complete parameters and commits through the normal shared commands/history. Native projects remain self-contained without access to the preset library that produced them.

Local persistence and conflicts

The canoli-brush-presets IndexedDB database, version 1, contains a presets store keyed by ID. Each strict record is {id, revision, preset, source?}; local revisions begin at 1. A textured v4 preset requires its matching original source in the same record. The physical database/store version remains 1: IndexedDB already supports Blob fields, and existing metadata records require no rewrite or migration. Older readers reject the newer value/field and preserve stored bytes. Updates/deletes require the selected revision. All changes re-read and validate the actual stored records within one native read/write transaction. Source checksums and native decoded dimensions are validated before writes. While asynchronous source checks await, read-only count requests keep the native write transaction alive; writes queue only from an active request callback. This retains the write lock across validation and prevents same-size binary replacement between verification and commit. Commits update/add/delete only changed records; renaming one preset does not rewrite unrelated original blobs. Cancellation/disposal aborts both private source work and the transaction. Immutable decoded-content proofs are cached for at most 256 source signatures; eviction causes revalidation, not source rejection. Transaction aborts, quota failures and invalid records cannot partially install an import or replace the last successful cache. Concurrent additions in different tabs retain both values; a stale update/delete rejects instead of overwriting newer work.

BroadcastChannel messages only request a validated reload; they never supply preset data. The library refreshes on browser focus if notifications are unavailable. A selected editing snapshot retains its original revision/draft when another tab changes it. Reload selected preset explicitly accepts the newer saved value. Failed reads preserve persisted bytes and the last valid cache. They never silently turn a corrupt library into an empty writable one. Editor disposal closes database/channel resources and aborts active transactions.

Storage errors offer Retry loading and Download current brush. Export saved library remains available for a last valid cache. For damaged data, Download recovery backup retains every raw record, including invalid ones. Reset saved brush presets requires the backup and an explicit checkbox; the transaction refuses if any record changed since that backup. Reset does not alter documents or built-ins. Import a valid brush pack afterward to restore saved values. Recovery is an archival data dump, not executable content or a normal brush pack; repair/convert invalid data before importing it. Metadata-only backups remain JSON. Backups containing blobs use a checksummed binary envelope that preserves every original byte, MIME type and raw record, including invalid preset records. Reset hashes the complete current raw snapshot under its write lock, including blob contents, so a changed blob cannot be erased using an older backup even when its size and record revision stay unchanged.

Portable packs

Export selected, Export saved library and Download current brush produce .canoli-brushes.json files with MIME type application/json for source-free values. Texture-bearing collections use .canoli-brushes with MIME application/x-canoli-brush-pack; their v4/v5 payload and original blobs are described below. Legacy JSON example:

JSON
{ "format": "canoli-brush-presets", "version": 1, "presets": [] }

The example above shows the envelope only; a valid pack contains at least one complete preset. Each preset has a supported version (1–5, subject to field-age rules below), a unique string id, a nonempty trimmed name of at most 120 characters, a supported tool, complete settings, and optional six-digit hex color. Unknown keys/versions/tools, duplicate pack IDs, nonfinite/out-of-range parameters and malformed pressure knots reject the entire pack before storage. Import always creates fresh IDs and revision-1 copies; even a pack exported from the current library cannot overwrite saved values. Packs are data only and never execute code or install plugins. Cancelling file reading or an active import transaction stops publication; an already completed save remains saved.

Bounds mirror supported controls: size 0.1–2048 px, hardness/opacity 0–1, flow 0.01–1, spacing 0.01–10, smoothing 0–0.9, tonal exposure 0–1, healing search radius 1–1024 px. Pressure curves retain their existing 2–16 normalized monotonic-knot contract, or null for default response. The toolbar's spacing track now exposes the engine's complete 1–1000% range. These are brush-setting contracts, not image-import resolution limits. Library/pack memory and browser quota remain device dependent.

Trusted application API

BrushPreset is a pure immutable value exported from src/brushes/presets.ts, separate from the isolated document constructor namespace:

TypeScript
const preset = BrushPreset.capture(
  "Firm ink",
  "brush",
  editor.tools.getSnapshot().settings,
  false,
);
const saved = await editor.brushPresets.save(preset); // new ID: expectedRevision defaults to 0
await editor.brushPresets.save(
  saved.preset.with({ name: "Renamed ink" }),
  saved.revision,
);

These methods are trusted host preferences/file operations. Isolated Scripts/plugins retain the existing stroke constructors and document commands; they gain no library, file, network or browser-preference access. Separate headless REST sessions do not control browser tool settings and gain no preset endpoint. Authored symmetry uses document schema 31; project 3 and workspace 2 remain unchanged. Texture source-bearing presets are connected and in verification. Physical tablet validation, mixer/smudge, broader asset libraries and sustained F06/F14 gates remain unfinished.

The library pages visible rows in groups of 100; search covers the complete saved collection. This is a UI rendering budget, not a limit on saved presets or imported image resolution.

Legacy recovery JSON is emitted only for losslessly representable JSON trees. The new binary recovery path additionally permits immutable Blob values, preserving their bytes/type explicitly; it does not silently coerce other non-JSON objects. Unexpected binary/typed/date values, nonfinite numbers, undefined fields, sparse arrays, accessors, cycles and shared references reject backup and reset rather than silently dropping data. Last-valid exports remain available; unsupported raw browser data stays preserved for recovery.

Spacing and smoothing preserve fractional percentages in both the toolbar and preset summaries; applying/importing a preset must not round displayed values to integer percentages.

Tip compatibility (preset and pack version 2)

Optional settings.tip contains the strict BrushTip DTO, including any normalized tilt response curve. Capturing a nondefault tip creates preset version 2; exporting version-2 presets without a version-3 preset creates pack version 2. Version-2 packs can contain both preset versions. Version-1 presets cannot contain the tip field, even null, and version-1 packs cannot contain version-2 presets. Existing version-1 packs/built-ins stay readable and unchanged; applying one resets the tool tip to default. Constructors normalize version-2 null tip to an absent default field after validation. Updating a preset with a tip upgrades it to at least version 2; removing shape does not downgrade an existing v2 identity. Older readers reject v2 instead of silently losing shape. The IndexedDB record/store version stays 1 because validated preset values carry their own version. Atomic imports, optimistic record revisions, backups and conflict behavior stay unchanged. Shaped strokes remain self-contained after deleting library presets.

Symmetry compatibility (preset and pack version 3)

Optional settings.symmetry retains a strict {copies:[{a,b,c,d,e,f},...]} BrushSymmetry DTO in document coordinates. Original ink is implicit; 1–31 distinct invertible nonidentity copies are allowed. Capturing symmetry creates preset 3, and packs use the greatest contained preset version. Pack 3 accepts presets 1–3; packs 1/2 reject newer preset versions. Presets 1/2 cannot carry a symmetry field, even null. After validating the version boundary, constructor shorthand v3 null normalizes to absent symmetry. Removing shape/symmetry does not downgrade an existing version identity.

Existing v1/v2 values and built-ins remain readable; applying any preset without symmetry resets it to Off. A tip-only value still uses v2, an ordinary legacy value still uses v1, and old readers reject v3 rather than discarding copies. Saved centers/lines use absolute document pixels. Applying to another canvas preserves those positions; use Symmetry → Center on canvas to reposition explicitly. Actual strokes store complete conjugated copy transforms independently of library records, so deleting a preset cannot damage project or undo data. The IndexedDB record/store version remains 1; existing transaction/revision/conflict/backup rules apply. The metadata copy budget is unrelated to source-image resolution. Export computes the greatest version incrementally, without a variadic call over an arbitrarily large collection.

Original-image textures (preset/pack version 4)

An optional top-level preset texture is {sourceId, channel: "alpha" | "luminance", invert: boolean} and requires preset version 4. The separate source record is {id, name, type, width, height, sha256, blob, tiff?, avif?}. Types are PNG/JPEG/WebP/TIFF/AVIF; dimensions are positive safe integers; SHA-256 is lowercase hexadecimal. TIFF requires its canonical {page, allowPrecisionLoss} choices; other image types cannot carry TIFF options. AVIF requires canonical {allowPrecisionLoss, assumeSrgb} choices, which reject on other types. AVIF texture review shares explicit precision/fallback consent and applies supported encoded crop/orientation to derived presentation pixels while preserving original bytes. Original compressed bytes remain separate from decoded editing pixels and the 128-square cursor preview. No image megapixel/file-size cap is introduced. Browser decode limits, quota, source-sized checksum buffers, retained decoded sources and compressed/output memory remain device/workload dependent.

toJSON() deliberately returns source references/metadata without the blob; construct it again with the matching source record, or use with/duplicate to retain the immutable original. The asynchronous capture helper is the source-preserving toolbar path. Synchronous capture without a source continues to reject enabled texture. Legacy application disables texture while retaining the ready preference source for reuse. Existing artwork, project sources and history survive library deletion/reset independently.

The binary file begins with ASCII CANBLOB1, an unsigned little-endian 64-bit UTF-8 manifest length, and a 32-byte SHA-256 manifest digest (48-byte header total). The strict envelope is {format:"canoli-brush-container", version:1, data, blobs:[{type,size,offset,sha256,file?}]}; offsets are contiguous from the payload start, and the final extent must equal file length. data for a pack is {format:"canoli-brush-presets", version:4, presets, sources:[{...sourceMetadata, blobIndex}]}. Every source and blob must be used exactly once by the manifest source table; presets may share a source. A collection may mix older source-free values with v4 texture values. Duplicate IDs/indices, unsupported keys/versions, missing/unused sources, malformed extents, metadata/source checksum failures and native dimension/codec errors reject the whole import before storage. No source-sized JSON/base64 conversion or executable source is included.

Export deduplicates complete source metadata/content identities and remaps pack source IDs. Import remaps portable source IDs and generates fresh saved preset IDs/revision 1. Source IDs are scoped references within values/packs, never document asset IDs: Apply prepares an independently owned original, and each later gesture obtains a collision-safe document lease. A document image with the same string ID cannot be overwritten by a preset source.

Source-aware library methods, preserving the old source-free methods:

Example for trusted browser application code (not the isolated Scripts editor):

TypeScript
import { captureBrushPreset, exportBrushPack } from "../src/brushes/portable";
const preset = await captureBrushPreset(
  "Original grain",
  "brush",
  editor.tools.getSnapshot().settings,
  editor.brushTextureSource,
  true,
);
const saved = await editor.brushPresets.save(preset);
const file = await exportBrushPack([saved.preset]);
await editor.applyBrushPreset(saved.preset);
// The host owns file/download selection; isolated scripts gain no Blob/library access.

Wet preferences (version 5)

smudge and mixer are supported preset tools. Version 5 wet presets require both settings.smudge and settings.mixer, each a strict {load, wetness, pickup} object with finite values in 0–1. Capturing either wet tool stores both independently owned preferences. Wet fields/tools in versions 1–4 reject. Applying a legacy preset resets Smudge to {load:0, wetness:0, pickup:0.5} and Mixer to {load:1, wetness:0.25, pickup:0.5}; document/mask targets remain untouched. Ordinary captures continue using the lowest sufficient prior version. Changing a legacy value to a wet tool through with adds those defaults and upgrades its version. Source-free JSON packs support v5; source-bearing binary payloads accept v4/v5 and export the highest required data version, retaining original source validation and bytes. Container and physical IndexedDB versions remain unchanged. No preset executes code or changes document undo. Actual UI/runtime verification for this integration is pending.

RAW-bearing textures (version 6)

A texture captured from accepted RAW pixels retains source.raw with the complete original sensor Blob and normalized development/provenance record, independently of its accepted PNG source.blob. Such presets require version 6; ordinary source-free and existing source-bearing captures keep the lowest earlier version. Pack v6 source metadata contains the Blob-free RAW descriptor and a rawBlobIndex alongside the PNG blobIndex. Both indices must identify unique used payloads; invalid/missing/unused originals, mismatched hashes/type/extent/geometry or old-version RAW records reject before installation. Shared presets deduplicate complete source identities. Source capture/Apply, library persistence, binary recovery and source-document closure preserve both byte streams; neither library install nor reopening accepted pixels executes RAW development. Container and IndexedDB versions remain unchanged. This adds no isolated plugin/Script privilege.