Skip to content

Designer App Layer

Pablo Martínez López edited this page Nov 28, 2026 · 17 revisions

Designer App Layer

English · Español

The Tauri-side half of the card designer ("Card editor", the "Design" view): everything that needs the network, the disk or the database around the pure engine in proxy_core::design. It builds drafts from Scryfall, owns the installed fonts/packs/symbols, registers designs for live preview, paints thumbnails for the deck, exports PNGs, and feeds designed cards into the PDF export.

The pure rendering engine (models, effective design, layout, text, painting) is documented in Designer Engine and Designer Composition; frame pack format in Frame Packs. The React side is in Designer UI. A general tour is in Designer Overview.

Boundaries

Layer Lives in Knows about
Engine (pure) src-tauri/crates/proxy-core/src/design/ CardDesign, Collection, EffectiveDesign, render, render_overlay; no Tauri, no network, no DB
App layer (this page) src-tauri/src/design/*.rs, src-tauri/src/commands/design.rs Scryfall, blob store, SQLite (presets, blob_refs), disk resources, pbimg://
Protocol src-tauri/src/protocol.rs /d/, /c/, /b/, /x/ routes that call into design::preview
Screen src/features/design/ Only talks to Rust through call() in src/lib/ipc.ts

src-tauri/src/design/mod.rs declares: art, draft, downloadable_packs, language, cjk_fonts, free_fonts, batch, original, paint, png, clipboard, resources, translation, preview. The downloadable-resource modules (downloadable_packs, cjk_fonts, free_fonts, original) are summarised below; the pack format they install is in Frame Packs.

File Responsibility
design/draft.rs Scryfall card (+ Spanish printing, + the printing in the deck's design language) to CardData, then to a DesignDraft
design/language.rs "Complete a design language": fetches the missing language for every designed card of the deck, as a cancellable job
design/cjk_fonts.rs Downloads the Japanese, Korean and Chinese fonts (Noto Sans JP/KR/SC/TC) on demand
design/resources.rs DesignResources: symbols, fonts, packs on disk; per-thread Engine; the decoded-image cache
design/paint.rs Effective design, render hash (fingerprint_of), paint/paint_layer, DeckDesigns for the PDF
design/preview.rs Live preview registry, design_save/rerender/renumber logic, overlay layer, reduced art
design/art.rs The four sources of artwork (upload/blob, clipboard, Scryfall art_crop, crop of a finished card); for two-half cards, the requested half of Scryfall's double art_crop (seam_of)
design/batch.rs "Design the whole deck": drafts in bulk as a cancellable job
design/png.rs Export designed cards as PNG files
design/translation.rs Experimental "suggested translation" into any printed language by matching identical official phrases
design/clipboard.rs Reads an image from the system clipboard (GTK on Linux, arboard elsewhere)
commands/design.rs The thin Tauri command layer over all of the above

Commands

All are registered in src-tauri/src/lib.rs and typed in src/lib/ipc.ts. Errors are AppError { code, params } (see IPC and Error Handling).

Drafts, collections, saving

Command Purpose
design_draft(card, used, collection, lang?) Build a DesignDraft for a deck card; lang (default Spanish) is the deck's design language, whose printing is fetched too (draft::full_data) and whose texts are pre-filled (draft::fill_texts). A custom card linked to a token Scryfall does not have (draft::external_ref, a Cockatrice token) takes its snapshot from the Cockatrice catalogue instead (draft::cockatrice_data: name, type with "Token", text and P/T in English; Spanish and the other languages flagged as without official text; scryfall_id empty and CardData.external set). Fails with InvalidInput { reason: "unlinked" } if the card has neither (draft::linked_scryfall_id). used = footer numbers already in the deck, so the next free number can be chosen.
collection_list / collection_save / collection_delete CRUD on collections, stored in presets (kind = 'collection') by src-tauri/src/store/collections.rs.
design_save(card, design, lang) Paint the thumbnail(s), store them in the blob store and return the new DeckCard. Does not write the deck; the screen applies it.
design_remove(card) Restore the card from design.before. Registered, but the screen currently uses its own removeDesign in src/features/design/groups.ts (same logic), so this command is unused by the UI.
design_rerender(cards, lang) Re-paint thumbnails whose thumb_key no longer matches the current render hash; returns only changed cards.
design_renumber(cards, lang) Renumber footer numbers by deck order; returns only changed cards (already re-thumbnailed).
design_drafts_for_deck(...) Job: drafts for all undesigned cards (see Bulk drafts). Returns a job_id.
design_complete_lang(cards, lang) Job: complete the design language lang on the designed cards (see Completing a design language). Returns a job_id.
design_export_png(...) Job: PNG export. Returns a job_id.

Preview, structure and warnings

Command Purpose
design_register(design, face, lang) Register the design being edited; returns the render hash used in pbimg://…/d/<hash>/<width>.
design_overlay(design, face, lang, width) The card without its artwork plus the artwork hole (LayerInfo), or None. Rejects widths outside protocol::WIDTHS with InvalidInput.
design_fit_report(design, lang) List of DesignWarning (text does not fit, missing symbols or fonts, collection lost, ...).
design_structure(design, face, lang) proxy_core::design::layout_engine::summary: layout kind and how the text is split (abilities, chapters, levels). Synchronous and pure.
design_suggest_translation(design, face, lang) translation::suggest for one face into lang. Rejected with InvalidInput { reason: "language" } for English and for the languages without printed cards (DesignLang::has_printed_cards() false: Romanian, Polish, Dutch, Ukrainian), where there is nothing to match against.

Resources

Command Purpose
fonts_list, font_import(path), font_remove(id) User fonts (.ttf/.otf), identified by SHA-256 of the file.
packs_list, pack_import(path), pack_remove(id) Frame packs from a folder or .zip.
fonts_free_list, font_free_download(id) The OFL catalogue in src-tauri/assets/free-fonts.json (design/free_fonts.rs).
original_info, original_download "Original" frames (Card Conjurer layers), downloaded on demand; progress on event original://progress (design/original.rs).
packs_downloadable_list, pack_downloadable_download(id), pack_extra_use(id, path) Packs from the packs repository (Balatro), manifest src-tauri/assets/downloadable-packs.json; progress on packs://progress (design/downloadable_packs.rs). pack_extra_use copies an extra (back, token, finished card) into the blob store and returns a FaceImage.
packs_missing(deck_id) The known packs (Original, the manifest's) that the saved deck asks for and are not installed, as MissingPack; the screen warns with a download button (downloadable_packs::missing). See Frame Packs.
symbols_status(refresh) Ensure Scryfall mana symbols are present (downloads if missing or older than 30 days, or if refresh), then return SymbolsInfo { loaded, date }.

Artwork

Command Source (ArtSource)
art_from_blob(blob) Upload: a file already imported with blob_import_files (the screen imports the picked file first).
art_from_clipboard Upload: image from the system clipboard, read by Rust because WebKitGTK refuses navigator.clipboard.read(); None if the clipboard has no image.
art_from_scryfall(scryfallId, face) ScryfallArtCrop { url }: the face's art_crop, falling back to the card-level one, then face 0; NotFound { reason: "no_art" } if none. For a two-half card (Scryfall layout: "split": split, Fuse, Room, aftermath) whose face has no art_crop of its own, the card-level image holds both illustrations side by side, so design::art::from_scryfall cuts out the requested half (face 0 or 1) with imaging::halves::half and stores it as a PNG blob; the source is still ScryfallArtCrop { url }. seam_of picks the seam: AFTERMATH_SEAM for aftermath (keyword Aftermath, or a face whose Oracle text starts with "Aftermath"), SPLIT_SEAM otherwise; see Imaging-and-PDF. Flip, adventure and Prepare cards are not split, so every face gets the whole image. Ignored live test halves_live (Fire // Ice, Dusk // Dawn, Akki Lavarunner).
art_from_card(blob, x, y, w, h) CardCrop { blob }: crops a fraction rectangle out of a finished card image; crops smaller than 8 px on a side fail with InvalidInput { reason: "empty_crop" }.

Every ArtRef starts with ArtFraming::default() (zoom 1, offsets 0, rotation 0). The fresh image goes to the blob store with ImageOrigin::Upload.

Heavy work off the async runtime

commands/design.rs → on_thread(app, f) runs closures on spawn_blocking with the AppState, because renders are CPU heavy. Preview-path commands (design_register, design_overlay, design_fit_report, design_save, design_rerender, design_renumber, art_from_clipboard's decode step, art_from_card) go through it. Network-bound ones (design_draft, art_from_scryfall, design_suggest_translation) are plain async.

Drafts (draft.rs)

flowchart LR
  A["design_draft"] --> B["full_card (cache or Scryfall)"]
  B --> C["spanish_printing"]
  B --> D["melded (meld only)"]
  C --> E["data_of -> CardData"]
  D --> F["with_melded"]
  E --> F
  F --> L["printing(lang) + add_language (other languages only)"]
  L --> G["assemble_draft -> DesignDraft"]
  G --> T["fill_texts(lang)"]
Loading
  • full_card(db, api, id) reads the Scryfall cache and uses it only if ScryCard::complete_for_design(); otherwise it fetches the card again and re-caches it (old cache entries lacked fields such as full_art).
  • printing(db, api, card, lang) returns the printing in lang used as the source of that language's official text; spanish_printing is the same call for Spanish (kept because the Spanish data are always fetched, as before there were more languages). It returns None without searching for English (the Oracle is the English text) and for the four languages without printed cards. Order in the code (find_printing): the card itself if its lang is already that code; otherwise the most recent printing found with oracleid:<id> lang:<code> that has printed text (the current wording, which fixes old templates); otherwise the same set + collector number (cache, then card_lang). With none, the draft falls back to the Oracle text. Some Spanish printings carry the printed text but no printed_type_line (Scryfall leaves it empty, e.g. the Final Fantasy Commander printings); complete_type_line then fills each missing line from another card in the same language whose English type_line is identical (translation::translate_type_line), so a land is not shown as "Land". Offline, or with no such card, the line comes from proxy_core::design::draft::translated_type_line(en, lang): Spanish uses spanish_type_line (a single card type with Basic/Legendary and known subtypes), the other languages the whole-phrase tables of proxy_core::design::language_types (see Designer Engine); both return None when something is unknown (creatures, tokens, mixed types), in which case the English line stays. Designs saved with the English line in a translated slot are repaired by fix_spanish_types and fix_types(card, lang) when preview::rerender runs on opening a deck. Tests: printing_without_type_line_borrows_it_from_same_type, french_searches_french_printing_and_romanian_nothing.
  • data_of(en, es, now) builds CardData: a face per entry of card_faces for the layouts in has_separate_faces (split, flip, transform, modal_dfc, adventure, meld, battle, double_faced_token, reversible_card) when there are at least two faces; otherwise a single face. Spanish type line, rules and name come from the Spanish printing's printed_* fields; missing Spanish falls back to the English text. textless_es is true when there is no Spanish printing or it has no printed text while the Oracle has text.
  • add_language(card_data, en, lang, printing) adds one more language (never Spanish or English, which data_of does) to an existing CardData: per face the printed type line (or translated_type_line, or English), the printed rules (without a printing the language gets no rules of its own and ByLang::get falls back to the Oracle), and the printed name (FaceData::set_printed_name); then CardData::set_textless(lang, …) with the same rule as textless_es. The fused face of a meld stays in English. Only the deck's design language is added, not all 15: each language is one more Scryfall search per card.
  • full_data(db, api, en, lang) is the whole snapshot used by design_draft and bulk drafts: English, Spanish, the fused meld card and, when lang is another language, that language.
  • fill_texts(design, lang) gives a design the FaceTexts of a new language (not Spanish or English) on faces that lack them: a themed name, if one was typed in English or Spanish (a name different from the official one), is copied; otherwise the printed name in lang, or the English one. Flavour text is copied from English, or from Spanish. Reason: a themed card renamed by the user keeps its name when the deck switches language; rules are never copied, so they come from the official printing.
  • Gotchas handled in face_of/strip_mdfc_tab: some printings put the whole card name ("Dusk // Dawn") in each face's printed_name (ignored); Spanish MDFC printings append the other face's type tab to each face's rules (stripped, because the engine paints the tab itself).
  • Meld: melded fetches the meld_result part, and with_melded appends it as a second face and sets CardData.meld_top (whether this part carries the top half; decided by matching collector numbers like 15a/15b).
  • assemble_draft(card, data, collection, used) produces the initial CardDesign:
    • style: FullArt for "Basic Land" cards, else the collection's default_style, else Borderless. pack_style comes from the collection's default_pack_style except for basic lands.
    • One FaceDesign per face with the name pre-filled in Spanish and English (Spanish uses printed_name_es); design_draft then calls fill_texts for any other design language.
    • before snapshots source/front/back/edits of the deck card so "Remove design" can restore it.
    • footer.number = proxy_core::design::draft::next_number(used, is_token) (0001…, tokens T001…).
    • options.show_flavor = true, status = Draft, thumb_key = None.
    • DesignWarning::NoOfficialText is added when data.textless_es.

draft::live_tests (ignored network tests)

#[cfg(test)] mod live_tests holds #[ignore] tests that need the network:

  • data_for_layouts downloads a fixed list of ~28 real cards (Liliana of the Veil, Urza's Saga, Fire // Ice, Bonecrusher Giant, Valakut Awakening, Invasion of Zendikar, Bruna the Fading Light, planes, a vanguard, a dungeon, an emblem, ...) and writes their CardData JSON to src-tauri/crates/proxy-core/tests/goldens/layouts/data/. Those fixtures feed the golden layout tests of the engine. Run with cargo test --lib draft::live_tests::data_for_layouts -- --ignored from src-tauri/.
  • progenitus_and_arcades_in_spanish checks the Spanish-printing search live; llanowar_elves_in_german checks the German name and type line.

Resources (resources.rs)

DesignResources (held as AppState.design) is opened once from app_data_dir by DesignResources::open, reading only the disk (no network).

The folders had Spanish names up to 4.1; data_folders::migrate moves them to these names at startup, and while only the old one is there it is the one used.

On disk (app_data_dir) Content
symbols/ One SVG per Scryfall symbol plus index.json ({ date, symbols: code -> file }). File name = sanitised code + 8 hex chars of its SHA-256.
fonts/<sha256>.<ext> Imported fonts (ttf/otf), id = SHA-256 of the file contents.
frames/<id>/ One folder per imported or downloaded pack (pack.json, SVG and PNG layers).
cjk-fonts/<code>.ttf Downloaded Japanese/Korean/Chinese fonts (ja, ko, zhs, zht), plus Noto-CJK-OFL.txt.

Internals:

  • State is an RwLock<ResourceState> with the symbols (Arc<Symbols> + a content hash), packs (BTreeMap<String, Arc<Pack>>) and fonts. The built-in pack ("builtin") comes from Pack::factory_default() and cannot be removed or overwritten (InvalidInput { reason: "pack_id" }).
  • snapshot(pack) returns an ResourceSnapshot { symbols, pack, fingerprint, generation, cjk_fingerprints }. An unknown pack id silently falls back to builtin (the caller is responsible for warning; the engine emits DesignWarning::StyleNotInPack/others). The pack's own symbols, if any, are layered on top of Scryfall's (Symbols::with_custom). fingerprint = pack.fingerprint | symbols-hash | comma-joined font ids and feeds the render hash, so changing a font, pack or the symbol set invalidates every cached render. The CJK fonts are deliberately not in fingerprint: ResourceSnapshot::fingerprint_for(lang) appends |cjk:<hash> only for the language whose font it is, so downloading the Japanese font re-renders only the Japanese cards (which were showing boxes) and leaves every other card's hash, and cached render, untouched.
  • generation (an AtomicU64) is bumped whenever fonts change. The text/paint Engine is kept in a thread_local! (ENGINES, a small stack of motors per thread); with_engine pops one, drops those whose stored generation differs, builds a new one if none is left (reloading all user fonts and every downloaded CJK font, Fonts::load_cjk with the language's WritingSystem) and pushes it back after the render. The motor is out of the cell while it paints because the engine resizes with fast_image_resize on rayon: while a worker of the export pool waits for that resize, rayon can hand it another card of the same job, which calls with_engine again on the same thread. Holding a RefCell borrow across the render made that a RefCell already borrowed panic that left the export stuck; now the nested render gets a second motor, kept for later. read_cjk loads cjk-fonts/<code>.ttf at start-up; save_cjk writes a new one atomically, adds it to the state and bumps generation, so every thread's motor picks it up. Reason: the engine holds mutable font state that cannot be shared across threads cheaply.
  • ensure_symbols(api, force): skips the download if the index is under 30 days old and non-empty (SYMBOLS_EXPIRY); with no network it logs a warning and keeps whatever exists (never an error). Writes are atomic (store::blobs::write_atomic).
  • import_pack(path) accepts a folder or .zip (read_zip strips a single wrapping folder by locating pack.json; reads only .json/.svg up to 8 MiB and .png up to 32 MiB per file, skipping paths with ..; oversize gives InvalidInput { reason: "pack_too_big" }). The pack is validated by Pack::load_with_images first; any PackError becomes InvalidInput { reason: "invalid_pack", ... } with the detail in params (pack_error). The id is sanitised to [A-Za-z0-9_-].
  • read_packs re-applies the current definition of the "Original" frames on every load (original::refresh_definition) so positions/layers match this app version even if the images were downloaded by an older one. That pack is loaded with original::load (here and in reload_pack): when images the new definition asks for are not on disk yet, it keeps the styles that are complete instead of failing, and original::complete (spawned from setup) downloads the rest. Right after it, downloadable_packs::complete brings an already installed downloadable pack (Balatro) to the files of this app's manifest. See Frame Packs.
  • remove_font / remove_pack delete files then bump state; cards that used them fall back to house resources (and show a warning).
  • StoreImages { db, blobs, cache } implements the engine's ImageSource trait: blob hash -> Arc<RgbaImage> via BlobStore::locate, decoding with proxy_core::imaging::decode::decode. ImageCache keeps the last 12 decoded images (MAX_CACHE), FIFO eviction, because artwork is large.

PackInfo (exposed to the screen) lists styles and pack_styles: Vec<PackStyle> — the pack's own styles (those not in proxy_core::design::pack::STOCK_STYLES) with id, names, a base built-in style and variants (PackVariant { id, names }). names is the pack's map language code -> name, passed through as is; the screen picks the interface language, then English, then the id (nameInLanguage in src/features/design/styles.ts). substitutes maps each built-in style the pack lacks to the own style it is painted with (Pack::substitute_for). See Frame Packs.

Painting and the render hash (paint.rs)

  • collections_by_id(state) loads all collections once per job; effective_of(design, cols) resolves a design against its collection (proxy_core::design::effective::effective). A deleted collection yields factory values and collection_lost = true.
  • fingerprint_of(state, e, face, lang) = effective::fingerprint(e, lang, face, inst.fingerprint_for(lang)): SHA-256 over the serialised effective design, language, face, resource hash and the engine version ENGINE_VERSION. It is the identity of "what this render looks like".
  • paint(...) takes the ResourceSnapshot, builds Resources { pack, symbols, images } and calls the engine's render inside with_engine; any engine error is mapped to ErrorCode::Image { detail }. paint_layer is the same for render_overlay.
  • RenderTarget::Screen yields transparent rounded corners (preview); RenderTarget::Print yields opaque square corners (thumbnails, PDF, PNG). A custom card corner radius (FineTuning.card_radius) applies to both outputs (compose.rs).

Live preview and pbimg:// URLs (preview.rs + protocol.rs)

Design: no image bytes cross IPC. The screen registers the design being edited, gets a hash, and sets an <img src="pbimg://…/d/<hash>/<width>">. WebKit caches by URL, and the protocol response carries Cache-Control: max-age=31536000, immutable, which is safe because the URL contains everything that changes the image.

Route Handler Content
/d/<fingerprint>/<width> preview::image PNG of the registered design, RenderTarget::Screen
/c/<fingerprint>/<width> preview::layer_image PNG of the card without artwork (overlay)
/b/<blob>/<side> preview::reduced_art Artwork reduced to side px on its long side (ART_SIDES = [1000, 2000])
/x/<pack>/<n> downloadable_packs::extra_by_index An extra image of a downloadable pack
/r/…, /t/…, /f/… other modules Not part of the designer
  • Allowed widths are protocol::WIDTHS = [146, 244, 488, 672, 745, 1000] (mirrored by WIDTHS in src/lib/image-url.ts); anything else is a 400. Hashes are validated with is_fingerprint (64 hex chars). The frontend builds URLs with designUrl, layerUrl, artUrl in src/lib/image-url.ts.
  • Each request takes a permit of AppState.renders (a tokio Semaphore) so many parallel <img> requests do not saturate the CPU, then renders in spawn_blocking.
  • PreviewRegistry is a FIFO map hash -> (EffectiveDesign, face, lang) capped at MAX = 64 entries. register stores it; /d/ looks the hash up. An unknown hash returns NotFound (HTTP 404). Hence the registry is the reason a pbimg://…/d/ URL only works while the design is registered in this process.
  • Disk cache: app_cache_dir/renders/d/<hash>-<width>.png, renders/c/…, renders/b/…. It is a derived cache and may be deleted at any time (architecture rule: the cache holds only derivatives). It is not invalidated explicitly: new inputs mean a new hash.
sequenceDiagram
  participant UI as use-draft
  participant C as design_register
  participant V as PreviewRegistry (64 entries)
  participant P as pbimg:// /d/
  participant R as paint + Engine
  UI->>C: design, face, lang (as fast as the last call finishes)
  C->>V: insert(fingerprint, (effective, face, lang))
  C-->>UI: fingerprint
  UI->>P: img src = /d/fingerprint/width
  P->>V: get(fingerprint)
  P->>R: render RenderTarget::Screen
  R-->>P: PNG (cached under renders/d)
  P-->>UI: bytes
Loading

Moving the artwork without waiting for Rust: design_overlay + render_overlay

Dragging the artwork would otherwise cost a full render per mouse move. Instead:

  1. preview::layer(state, design, face, lang, width) resets the ArtFraming of the face being moved (face) to default on the effective design before computing the hash, so the layer stays valid while only that framing changes. The other faces keep theirs: on a composed card the layer of one part has the other part's artwork painted in it, and resetting it made part 1 jump back to its initial framing while part 2 was selected.
  2. It registers that design in PreviewRegistry (so /c/<hash>/<w> can paint it), and if renders/c/<hash>-<w>.png and renders/c/<hash>.json exist it returns the cached LayerInfo.
  3. Otherwise paint_layer calls the engine's render_overlay ("the card painted once without that part's artwork, plus where the artwork goes"; render_overlay in src-tauri/crates/proxy-core/src/design/compose.rs). Composed and big cards get a layer too (the whole card with that part's art window transparent, see Designer-Composition); it returns None only when the part has no artwork of its own (part 2 of a flip or adventure), for the meld back, or when the face has no artwork. Otherwise the app writes the PNG and the JSON. The hash includes the requested part, so the two parts of a split card never share a cached layer.
  4. LayerInfo { fingerprint, art: [x, y, w, h], extension, background, radius: [rx, ry], face, rotation } is in fractions of the card: the artwork hole as seen on the card, the corner radii and rotation, the rotation of the artwork inside the hole in degrees (90 aftermath bottom half, -90 split halves; #[serde(default)], so layers cached before it read as 0).

The frontend composition (see Designer UI): a black box with rounded corners, the artwork <img src=/b/<blob>/<1000|2000>> placed in the hole with CSS using the same maths as the engine's paint_art (artGeometry in src/features/design/framing.ts), and the overlay <img src=/c/<hash>/<w>> on top. When dragging stops, the exact Rust render replaces it.

Warnings (design_fit_report)

preview::notices paints every face (0..faces.len()) with RenderTarget::Print at width 300 and merges each render's warnings without duplicates, adding DesignWarning::CollectionLost if the collection was deleted. It renders without caching, which is why the screen debounces it by 400 ms.

Saving, re-thumbnailing and renumbering (preview.rs)

apply(state, card, design, lang):

  1. Resolve the effective design; key = fingerprint_of(.., face 0, ..).
  2. Paint face 0 at THUMBNAIL_WIDTH = 1000 px with RenderTarget::Print, encode JPEG quality 92 and store it with ImageOrigin::Designed.
  3. If the layout prints two faces (d.faces.len() >= 2 && layout_engine(&d.card).0.printed_faces() == 2), paint face 1 too and set back = BackSpec::Dfc { image }. Otherwise keep d.before.back, except a former Scryfall DFC back becomes BackSpec::DeckDefault.
  4. Return a clone of the card with source = CardSource::Custom { scryfall_id: Some(..), external: None } (for a design of a card from another source, CardData.external with an empty scryfall_id, Custom { scryfall_id: None, external }, so the card stays linked to its token), front = thumbnail, edits = default, meta.is_dfc updated and design = Some(design with thumb_key = key).

The deck itself is not written: the screen swaps the card in with one setCards so undo works.

  • Consequence: a designed card behaves in the deck like a custom card whose image is the 1000 px thumbnail. Layout, stats and preview need no special case; only the PDF re-paints from the design.
  • thumb_key records the hash that produced the thumbnail. rerender compares it with the current hash (so a changed collection, font, pack, symbol set or engine version triggers a re-thumbnail) and only re-applies mismatches. The screen calls rebuildThumbnails() when opening a deck and when the collections/resources dialogs close.
  • renumber walks the deck in order, skips designs with footer.number_manual, assigns 0001… to cards and T001… to tokens (CardData::is_token), and gives copies (same CardData::key(): the Scryfall id, or cockatrice:<id>) the same number. It re-applies only cards whose number changes.
  • remove(card) restores source/front/back/edits from design.before. with_status (set Ready/Draft) exists but has no callers.

Bulk drafts: "Design the deck"

design_drafts_for_deck(cards, used, collection, lang) allocates a job (state.jobs.register() → (job_id, cancelled)), spawns an async task holding the state.start_job() guard (marks a long job running, which blocks e.g. blob_gc with Busy), and returns the job_id. batch::make_drafts then, in deck order:

  • Stops with Cancelled if the flag is set (job_cancel).
  • For each card with no design and a Scryfall id: builds the draft with draft_for (same pipeline as design_draft plus Scryfall art_crop artwork asked for each face index: halves of split, Fuse, Room and aftermath cards each get their own piece, while flip and adventure faces get the same image because Scryfall has a single one; for melds the second face has no art of its own), applies it with preview::apply in spawn_blocking, and emits design://progress (DesignProgressEvent { jobId, done, total, card?, failed }).
  • Copies of the same Scryfall card reuse the first draft (finished map) so they share the design and number; used grows with each new number.
  • Network and RateLimited errors abort the whole job; other per-card errors are logged, reported as failed: true, and the job continues.
  • At the end design://done (DesignDoneEvent { jobId, error? }) is emitted.

The dialog src/features/design/batch-dialog.tsx collects all cards and applies them in one setCards (even when cancelled), so one undo removes them all. src/lib/jobs.ts → runJob listens before launching so short jobs do not lose their final event.

Completing a design language (language.rs)

A design keeps Spanish and English always, plus only the languages it has been shown in (ByLang.others, see Designer Engine). When the deck's design language changes to a third language, the cards already designed have neither that language's official data nor its texts, so design_complete_lang(cards, lang) fills them in as a job (same jobs.register() + state.start_job() pattern as bulk drafts):

  1. If the language needs a downloaded font (cjk_fonts::needs: ja, ko, zhs, zht), cjk_fonts::download runs first, so that the thumbnails painted afterwards do not show boxes. For Spanish and English nothing else happens.
  2. Only designs for which language::lacks_language(design, lang) holds are processed: !card.has_language(lang) (no printing data and not known to lack one) or some face without texts in that language.
  3. complete: if the data are missing, draft::full_card + draft::printing(lang) + draft::add_language; then draft::fill_texts. The result is applied with preview::apply (new thumbnail in that language) in spawn_blocking.
  4. Copies sharing the same design (same JSON) are completed once (finished).
  5. Each card is emitted on designlang://progress (DesignProgressEvent, the same shape as bulk drafts); the end on designlang://done (DesignDoneEvent). Network and RateLimited errors stop the job (it can simply be launched again later; the cards keep the English fallback and the warning meanwhile); other per-card errors are logged and reported as failed: true. job_cancel stops it with Cancelled.

On screen this is completeLanguage in src/features/design/renumber.ts (job type "language" in job-store), which applies the returned cards without history, even after a cancel. setDesignLanguage (the design-language selectors) and the PNG dialog call it. Test: missing_until_it_has_language_data_and_texts.

Fonts for Japanese, Korean and Chinese (cjk_fonts.rs)

The house fonts cover Latin and Cyrillic, but not CJK. Noto Sans JP, KR, SC and TC (OFL) weigh between about 9.6 and 17.8 MB each, so they are not bundled in the installer: they are downloaded the first time a deck chooses one of those design languages (or from the "missing fonts" warning, which re-selects the language).

  • Catalogue src-tauri/assets/cjk-fonts.json: a fixed commit of the google/fonts repository, base ofl/, and per language its family, path (notosansjp/NotoSansJP[wght].ttf…), SHA-256 and size, plus the licence file and its SHA-256. Only the Sans: the Serif would double the size.
  • download(state, lang) does nothing for a language without an entry or whose font is already on disk; otherwise it downloads from raw.githubusercontent.com (brackets escaped in the URL), reading in chunks with a 32 MiB cap (CAP), and rejects anything whose SHA-256 is not the catalogue's (Network { reason: "fingerprint" }). The licence goes to cjk-fonts/Noto-CJK-OFL.txt and the font to cjk-fonts/<code>.ttf via DesignResources::save_cjk (under app_data_dir, see Storage and Blobs).
  • The engine registers each font as a fallback for its script and locale, so the same ideograph gets the Japanese or the Chinese form depending on the card's language (see Designer Engine). Without the font the render carries DesignWarning::MissingFonts { lang }.
  • Tests: catalog_has_the_four_asian_languages; ignored live test downloads_japanese_font.

PNG export (png.rs)

design_export_png(cards, folder, card_size, dpi, langs) accepts only 300, 600 or 900 dpi and a non-empty langs (InvalidInput { reason: "png" }), then runs in spawn_blocking as a job emitting designpng://progress and designpng://done (files, error?).

  • tasks builds the work list. Two copies with the same design count once: the key is the design JSON with thumb_key, status and before neutralised. For each language and each printed face (printed_faces) one task.
  • Size: compose::size_mm(&effective, card_size) gives millimetres; width px = mm / 25.4 * dpi. Painted with RenderTarget::Print at exactly the cut size, then seal::paint(&mut image, t.lang) adds the Tapete stamp in that task's language before encoding (The Card Stamp). The stamp is painted on the finished image, outside the engine, so it does not change the design's fingerprint.
  • Layout on disk: one folder per language, named by its code (<folder>/es/, <folder>/en/, <folder>/fr/…, folder); file name "<number> - <name>.png" (file_name_for replaces " // " with " - " and OS-illegal characters with -); multi-face cards add (1), (2); collisions get ~2, ~3.
  • Test png_has_exact_size_and_is_deterministic pins 744×1039 px at 300 dpi for 63×88 mm, byte-identical re-exports and a third language in its own folder.
  • Rust paints whatever data the design has: a language that was never completed falls back to English. That is why the PNG dialog (src/features/design/png-dialog.tsx) first runs completeLanguage for each chosen language other than Spanish and English, and only then launches the export.

How the PDF paints designed cards

flowchart TD
  X["commands/export.rs run_export"] --> D["DeckDesigns::load(state, deck)"]
  D --> E["render_order(): per slot RenderSpec"]
  E -->|"reference() returns DesignRef"| S["spec.design = Some; edits default; edge None"]
  S --> R["render_design_for_pdf"]
  R --> P["paint(RenderTarget::Print, width = trim px)"]
  P --> B["render_from_image: bleed + encode"]
Loading
  • DeckDesigns::load computes the effective design of every designed card (loading collections only if any card has a design) and records deck.settings.design_lang.
  • face_for_slot(card, slot) says which face goes on a slot: Front -> face 0; DfcFace/Back -> face 1 only if the card has BackSpec::Dfc and the design has two faces; otherwise None (the deck's default back is not part of the design, and a DFC back with a single-face design is not repainted).
  • reference produces a DesignRef { fingerprint, face, lang } for the slot's RenderSpec.design, so identical designs/faces dedupe through RenderSpec::key() and render once.
  • render_design_for_pdf paints at the trim width in pixels for the export dpi (trim_px(spec.card, spec.target)), then render_from_image adds bleed and encodes. The deck thumbnail is not used for printing; the 1000 px JPEG only serves screens.
  • Designed cards bypass user retouches and edge darkening (spec.edits = default, spec.edge = None). The deck preview, however, requests the thumbnail through /r/… with card.edits (src/features/preview/slot-view.tsx, thumbnail_spec), so a retouch made with "Edit card" (Card Editor Dialog) on a designed card shows on screen but never reaches the PDF.
  • The language used is the deck's settings.design_lang (English for new decks, Spanish for decks saved without it; it travels in .pbdeck). It is written by the "Language of designed cards" selector of the export panel and by the language selector of the Design preview, both through setDesignLanguage (src/features/design/renumber.ts), which completes the language and re-thumbnails the deck.

More on the PDF pipeline in Imaging and PDF and Export.

Suggested translation (translation.rs)

Experimental, never applied automatically. For a face with no printing in the requested language (any language with printed cards; the code is passed as code):

  1. sentences(text) splits the Oracle text per line into sentences at a period followed by a space, outside parentheses and quotes; a whole reminder text in parentheses is one sentence. Japanese and Chinese end sentences with 「。」 (and use full-width parentheses), so that character also ends a sentence, and when the result is reassembled the sentences are joined without a space in ja, zhs and zht.
  2. The card name (and its legendary short name from proxy_core::design::draft::short_name) is replaced by ~ so searches match other cards.
  3. For each sentence, translate_sentence searches Scryfall o:"<sentence without final period>" lang:<code> order:released (30 results), keeps prints in that language with printed text, newest first, and align takes the sentence at the same index in that card's printed text. Alignment only counts when the Oracle and printed texts split into the same number of sentences.
  4. A bare keyword list ("Vigilance, reach") that finds nothing is translated word by word.
  5. The type line is searched as t:"<type>" lang:<code>; the result must have an identical English type line.
  6. Output Suggestion { kind?, rules, sentences: [{ en, translated? }], translated, total } (SuggestedSentence.translated is the sentence in the requested language); untranslated sentences stay in English and are flagged in the UI. 4xx responses from Scryfall's query parser are treated as "not found" for that sentence.

Cost: one search per distinct sentence (memoised in completed), so it is slow. Tests: sentences_split_outside_parens_and_quotes, keyword_lists, name_becomes_tilde, aligns_by_position, french_searches_in_french, japanese_ends_sentences_with_its_period, and a live twenty_cards_without_spanish.

Protecting images from garbage collection (blob_refs)

The blob store deletes orphaned images in BlobStore::gc (command blob_gc, refused with Busy while a long job runs). A blob is orphaned if it is older than 24 h (GRACE_MS) and not referenced by any deck_cards.front_blob/back_blob, decks.default_back_blob, the generic-back setting, or any row of blob_refs. See Storage and Blobs.

Designs reference images that are neither a card's front nor back, so the table blob_refs (owner_kind, owner_id, blob) (migration src-tauri/src/store/migrations/0002_blob_refs.sql) records them:

owner_kind owner_id Written by Blobs
deck deck id store/decks.rs on every deck save (deck_refs -> write_refs) CardDesign::blobs() of every designed card: each face's artwork image, the source blob of a CardCrop art, an own emblem, and before.front / before.back images
preset collection id store/collections.rs save the collection's emblem

Details and invariants:

  • Deck save rejects the whole save with InvalidInput { reason: "blob_missing", blob } if any referenced blob does not exist; collection save does the same for its emblem.
  • Refs are rewritten from scratch inside the save transaction (DELETE then INSERT OR IGNORE), and removed on deck/collection delete.
  • backfill_refs backfills the table once from already stored decks, tracked by an app_settings key blob_refs_v1 (an "is the table empty" check would be wrong, since a deck without designs leaves it empty).
  • The .pbdeck package includes the same set of blobs (src-tauri/src/package.rs uses d.blobs()), see Deck Package Format.
  • New artwork has a 24 h grace period (imported before the card is saved), so drafts survive being edited for a while without a deck referencing them.
  • The designer's thumbnails are stored as normal front blobs of the card, so the regular deck references protect them.

Failure modes

Situation Result
Card not linked (neither Scryfall nor another source) InvalidInput { reason: "unlinked" } from design_draft
No network while building a draft Network; bulk job aborts, single card shows an error toast
Unknown render hash on /d/ or /c/ NotFound -> HTTP 404 (the design was evicted from the 64-entry registry or never registered)
Width/side not in the allowed lists InvalidInput (command) or HTTP 400 (protocol)
Engine render error Image { detail }
Invalid pack InvalidInput { reason: "invalid_pack" } + detail params
Font not .ttf/.otf or unparsable Unsupported
Symbols missing and offline No error; render shows DesignWarning::MissingSymbols
CJK design language without its font Render shows DesignWarning::MissingFonts { lang } (boxes instead of text); choosing the language again downloads it
CJK font download corrupted or too large Network { reason: "fingerprint" } / Network { reason: "size" }; nothing is written
Offline while completing a design language Network; the job stops, the cards keep the English fallback and DesignWarning::NoOfficialText
Suggested translation for English or an unprinted language InvalidInput { reason: "language" }
Clipboard has no image art_from_clipboard returns null (the screen shows an info toast)

Tests that guard this layer

  • src-tauri/src/design/draft.rs: spanish_dusk_dawn_gives_two_aftermath_faces, missing_spanish_printing_warns, basic_land_goes_full_art, printing_without_type_line_borrows_it_from_same_type, french_searches_french_printing_and_romanian_nothing.
  • src-tauri/src/design/language.rs: missing_until_it_has_language_data_and_texts; src-tauri/src/design/cjk_fonts.rs: catalog_has_the_four_asian_languages.
  • src-tauri/src/design/preview.rs: preview_save_and_remove, layer_for_moving_the_art, deck_numbers_and_renumbering.
  • src-tauri/src/design/paint.rs: slot-to-face mapping, effective design lookup, hash sensitivity (fingerprint_changes_with_face_and_language), DeckDesigns, painting_a_face_gives_requested_width.
  • src-tauri/src/design/png.rs, art.rs (paste_and_crop; ignored halves_live), resources.rs (imported_fonts_and_packs), translation.rs.
  • src-tauri/src/protocol.rs: good_route_parses, odd_routes_are_rejected, and others.
  • src-tauri/src/commands/export.rs tests that designed cards get a DesignRef per face in the export plan.
  • src-tauri/src/store/collections.rs: rename keeps id, empty name or missing emblem are rejected.

Run with pnpm test:rust (see Testing and CI).

Where to start when extending

  • New artwork source: add a function in design/art.rs returning ArtRef with a new ArtSource variant (in proxy-core), a command in commands/design.rs, register it in src-tauri/src/lib.rs, add it to src/lib/ipc.ts, then a button in ArtTab (src/features/design/form.tsx). Remember CardDesign::blobs() must list any new blob so it is protected.
  • Anything that changes how a card looks: it must be part of the effective design or of ResourceSnapshot.fingerprint, otherwise caches and thumb_key will not invalidate.
  • New preview route: add to protocol::Route, parse_route (validate hashes and sizes), and handle.

See also

Documentation · Documentación

Language: English · Español

Use and build · Uso y desarrollo

Architecture · Arquitectura

Data · Datos

Getting cards · Conseguir cartas

Layout, images, PDF · Maquetación, imagen y PDF

Card designer · Diseñador de cartas

Game table · Mesa de juego

Mobile · Móvil

Frontend · Frontend

Reference · Referencia

Clone this wiki locally