From 5941733af1abf35da3316ad03e0f68d898a7f0d7 Mon Sep 17 00:00:00 2001 From: RobinFiredrake Date: Sun, 29 Nov 2026 16:52:41 -0600 Subject: [PATCH] Sheets phase D: sheets on spreads as linked Sheet cards - A Sheet card can show a sheet file (sheet, prefix): first-tab preview, Open sheet with a way back, the spread's Play/Build in the editor. - Rolls read and write "Use in tables" boxes as @name or @prefix_name; locked boxes and formulas/lists keep their values; changed boxes glow. - A roll reaching the card shows the sheet's text (SheetText) in the tray; text boxes also show spread values when on the spread. - Old template Sheet cards migrate to a sheet with one text box (not in Help demos). Card palette lists your sheets. - Sheet canvas: tiled grid (smooth panning); boxes no longer overlap (nearest free spot, drags stop short; Alt places freely). Co-Authored-By: Claude Opus 5.5 --- core/roll_table.gd | 5 + core/roll_table_io.gd | 7 ++ core/roller.gd | 10 ++ core/sheet_doc.gd | 24 +++++ core/sheet_links.gd | 94 +++++++++++++++++ core/sheet_links.gd.uid | 1 + core/sheet_text.gd | 73 +++++++++++++ core/sheet_text.gd.uid | 1 + docs/SHEETS.md | 16 ++- help/topics.txt | 10 +- io/json_canon.gd | 2 +- tests/test_logic_ui.gd | 14 ++- tests/test_sheet_editor.gd | 81 ++++++++++++++- tests/test_sheets.gd | 42 ++++++++ ui/actions.gd | 2 + ui/card_catalog.gd | 9 +- ui/card_palette.gd | 16 +++ ui/demo_mode.gd | 4 +- ui/inspector_card.gd | 24 +++++ ui/main.gd | 5 + ui/main_cli.gd | 5 + ui/main_editing.gd | 6 +- ui/main_layout.gd | 6 ++ ui/main_rolling.gd | 2 + ui/main_screens.gd | 2 + ui/main_sheet_links.gd | 203 +++++++++++++++++++++++++++++++++++++ ui/main_sheet_links.gd.uid | 1 + ui/main_state.gd | 2 + ui/sheet_box_view.gd | 13 ++- ui/sheet_canvas.gd | 41 +++++--- ui/sheet_editor.gd | 25 +++++ ui/sheet_field_views.gd | 7 +- ui/sheet_preview.gd | 70 +++++++++++++ ui/sheet_preview.gd.uid | 1 + ui/sheet_top_bar.gd | 9 ++ ui/sheets_screen.gd | 16 ++- ui/table_card_kind_rows.gd | 15 +++ 37 files changed, 818 insertions(+), 46 deletions(-) create mode 100644 core/sheet_links.gd create mode 100644 core/sheet_links.gd.uid create mode 100644 core/sheet_text.gd create mode 100644 core/sheet_text.gd.uid create mode 100644 ui/main_sheet_links.gd create mode 100644 ui/main_sheet_links.gd.uid create mode 100644 ui/sheet_preview.gd create mode 100644 ui/sheet_preview.gd.uid diff --git a/core/roll_table.gd b/core/roll_table.gd index c5287a9..c4441b8 100644 --- a/core/roll_table.gd +++ b/core/roll_table.gd @@ -130,6 +130,11 @@ var loop_expr: String = "" var var_name: String = "" var var_type: String = "number" var initial: String = "" +## Sheet cards: the sheet they show (a SheetStore id; "" = an old template +## card, migrated by MainSheetLinks) and the prefix tables read its boxes by +## (@prefix_name; "" = plain @name). docs/SHEETS.md, phase D. +var sheet_id: String = "" +var sheet_prefix: String = "" ## Scale variables: the ordered steps, lowest first. var steps: Array[String] = [] ## A cost to roll this card (RollCosts): the value ("@luck") and the amount diff --git a/core/roll_table_io.gd b/core/roll_table_io.gd index e0a847f..b2926d0 100644 --- a/core/roll_table_io.gd +++ b/core/roll_table_io.gd @@ -72,6 +72,11 @@ static func to_dict(t: RollTable) -> Dictionary: d["loop"] = t.loop_mode if t.loop_expr != "": d["loop_expr"] = t.loop_expr + elif t.kind == RollTable.KIND_SHEET: + if t.sheet_id != "": + d["sheet"] = t.sheet_id + if t.sheet_prefix != "": + d["prefix"] = t.sheet_prefix elif t.kind == RollTable.KIND_VARIABLE: if t.var_name != "": d["var_name"] = t.var_name @@ -150,6 +155,8 @@ static func from_dict(d: Dictionary) -> RollTable: var vt := str(d.get("var_type", "number")) t.var_type = vt if RollTable.VAR_TYPES.has(vt) else "number" t.initial = RollTable.expr_text(d.get("initial", ""), "") + t.sheet_id = str(d.get("sheet", "")) + t.sheet_prefix = str(d.get("prefix", "")) t.steps = Scales.clean(d.get("steps", [])) t.members = LedgerMembers.clean(d.get("members", [])) t.list_repeats = bool(d.get("repeats", false)) diff --git a/core/roller.gd b/core/roller.gd index c3c22f3..c1feb14 100644 --- a/core/roller.gd +++ b/core/roller.gd @@ -44,6 +44,10 @@ extends RefCounted ## and fills in ctx.root as it goes. roll() is the plain form: it never waits ## (choices get the headless answers) and returns the tree directly. +## Gives a linked Sheet card's text (RollTable.sheet_id): set by the app +## (MainSheetLinks), which can read sheet files. Unset in headless use. +static var sheet_text := Callable() + ## Deepest level inline references can nest (matches RollContext). const MAX_DEPTH := RollContext.DEFAULT_MAX_DEPTH ## Most actions one top-level roll may take (matches RollContext). @@ -247,7 +251,13 @@ static func _do_roll(board: TowerBoard, f: Dictionary, ctx: RollContext, stack: var sheet := {"table": t, "index": 0, "entry": t.entries[0], "children": [], "summary": "", "kind": RollTable.KIND_SHEET} _attach(f, sheet, ctx) + # A card showing a sheet file rolls the sheet's text (SheetText) in + # place of its own template, for this roll only. + var own := t.entries[0].text + if t.sheet_id != "" and sheet_text.is_valid(): + t.entries[0].text = str(sheet_text.call(t)) await _enter(sheet, f, ctx, stack, true, true) + t.entries[0].text = own _: var node := RollCards.pick_for(t, ctx, f) if node.has("nat"): diff --git a/core/sheet_doc.gd b/core/sheet_doc.gd index 06bc096..729703d 100644 --- a/core/sheet_doc.gd +++ b/core/sheet_doc.gd @@ -71,6 +71,30 @@ func new_box_id() -> String: return "b%d" % n +## True when `r` would cover a box on `tab` other than `skip_id` (touching +## edges is fine). +static func overlaps(tab: Dictionary, r: Rect2, skip_id: String = "") -> bool: + for box: SheetBox in tab["boxes"]: + if box.id != skip_id and box.rect().grow(-0.5).intersects(r.grow(-0.5)): + return true + return false + + +## The nearest free place for `r` on `tab`: scanning grid steps down and +## then across from where it was asked for. Boxes don't overlap unless +## placed freely (Alt). +static func free_spot(tab: Dictionary, r: Rect2, step: float, skip_id: String = "") -> Vector2: + if not overlaps(tab, r, skip_id): + return r.position + for ring in range(1, 200): + for dy in range(0, ring + 1): + for dx: int in [ring - dy, -(ring - dy)]: + var at := r.position + Vector2(dx, dy) * step + if at.x >= 0 and not overlaps(tab, Rect2(at, r.size), skip_id): + return at + return r.position + + func remove_box(box_id: String) -> void: var tab := tab_of(box_id) if not tab.is_empty(): diff --git a/core/sheet_links.gd b/core/sheet_links.gd new file mode 100644 index 0000000..1957b3a --- /dev/null +++ b/core/sheet_links.gd @@ -0,0 +1,94 @@ +class_name SheetLinks +extends RefCounted +## The bridge between a spread and the sheets on it (Sheet cards with a +## RollTable.sheet_id). Before a roll, every "Use in tables" box of each linked sheet +## becomes a spread variable: @var, or @prefix_var when the node has a prefix +## (RollTable.sheet_prefix: two characters on one spread). After the roll, values the roll changed go +## back into their boxes, unless the box is locked or its kind can't take a +## value (formulas, lists…); a locked box puts the variable back. + +## Kinds a roll can write into, and how the value is stored. +const WRITABLE := [SheetKinds.NUMBER, SheetKinds.SHORT_TEXT, SheetKinds.TEXT, SheetKinds.CHECKBOX, + SheetKinds.DROPDOWN, SheetKinds.RESOURCE, SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS, + SheetKinds.LADDER, SheetKinds.XP] + + +## The spread variable name for a box on a card: "str" or "brin_str". +static func var_for(card: RollTable, box: SheetBox) -> String: + var prefix := card.sheet_prefix.strip_edges() + return box.var_name if prefix == "" else "%s_%s" % [prefix, box.var_name] + + +## The spread's Sheet cards that show a sheet. +static func sheet_cards(board: TowerBoard) -> Array[RollTable]: + var out: Array[RollTable] = [] + for t in board.tables: + if t.kind == RollTable.KIND_SHEET and t.sheet_id != "": + out.append(t) + return out + + +## Puts every linked box's value into `vars` (name -> {"value", "source"}). +## Returns what was put in: name -> {"sheet", "box", "value"}, for write_back. +## `load_doc` gives a SheetDoc for a sheet id (null when it is gone). +static func inject(board: TowerBoard, vars: Dictionary, load_doc: Callable) -> Dictionary: + var given := {} + for card in sheet_cards(board): + var doc: SheetDoc = load_doc.call(card.sheet_id) + if doc == null: + continue + var values := SheetValues.vars(doc) + for tab in doc.tabs: + for box: SheetBox in tab["boxes"]: + if box.var_name == "" or not values.has(box.var_name): + continue + var name := var_for(card, box) + var v: Variant = _plain(values[box.var_name]) + vars[name] = {"value": v, "source": "sheet %s" % doc.name} + given[name] = {"sheet": doc.id, "box": box.id, "value": v} + return given + + +## After a roll: each variable that changed goes into its box. Returns +## [{"sheet", "box", "name", "value", "locked"}] for every change seen; locked +## boxes keep their value and their variable is put back. +static func changes(given: Dictionary, vars: Dictionary) -> Array: + var out: Array = [] + for name: String in given: + var g: Dictionary = given[name] + var entry: Variant = vars.get(name) + var now: Variant = (entry as Dictionary).get("value") if entry is Dictionary else entry + if now == null or str(now) == str(g["value"]): + continue + out.append({"sheet": g["sheet"], "box": g["box"], "name": name, "value": now}) + return out + + +## Writes `value` into `box` as its kind stores it. False when the box is +## locked or its kind can't take a value (the caller puts the variable back). +static func write(box: SheetBox, value: Variant) -> bool: + if box.locked or not WRITABLE.has(box.kind): + return false + match box.kind: + SheetKinds.NUMBER, SheetKinds.XP: + box.value = Expr.normalize(SheetValues.number(value)) + SheetKinds.CHECKBOX: + box.value = Expr.truthy(value) + SheetKinds.RESOURCE: + var v: Dictionary = (box.value as Dictionary).duplicate() if box.value is Dictionary else {"cur": 0, "max": 10} + v["cur"] = int(SheetValues.number(value)) + box.value = v + SheetKinds.TICKS, SheetKinds.CLOCK, SheetKinds.DOTS, SheetKinds.LADDER: + box.value = int(SheetValues.number(value)) + _: + box.value = str(value) + return true + + +## Spread variables hold numbers and text only. +static func _plain(v: Variant) -> Variant: + if v is int or v is float or v is String: + return Expr.normalize(v) + if v == null: + return "" + return str(v) diff --git a/core/sheet_links.gd.uid b/core/sheet_links.gd.uid new file mode 100644 index 0000000..ce7787a --- /dev/null +++ b/core/sheet_links.gd.uid @@ -0,0 +1 @@ +uid://vplavq1hccr2 diff --git a/core/sheet_text.gd b/core/sheet_text.gd new file mode 100644 index 0000000..9c59d14 --- /dev/null +++ b/core/sheet_text.gd @@ -0,0 +1,73 @@ +class_name SheetText +extends RefCounted +## A sheet as one block of BBCode, for when a roll reaches its card: the tray +## headline, "Copy" and "Save as a file" show it (docs/LOGIC.md §6). Boxes +## used in tables become {@name} (with the card's prefix), so the roll fills +## in the values it just set; other boxes show their current value. Text +## boxes keep their own BBCode and {@…}, so they can show spread values too. + + +static func summary(doc: SheetDoc, prefix: String = "") -> String: + var lines: Array[String] = [] + for tab in doc.tabs: + var boxes: Array = (tab["boxes"] as Array).duplicate() + boxes.sort_custom(func(a: SheetBox, b: SheetBox) -> bool: return a.y < b.y or (a.y == b.y and a.x < b.x)) + for box: SheetBox in boxes: + var line := _line(doc, box, prefix) + if line != "": + lines.append(line) + return "\n".join(lines) + + +static func _line(doc: SheetDoc, box: SheetBox, prefix: String) -> String: + match box.kind: + SheetKinds.HEADING: + return "[b]%s[/b]" % box.title + SheetKinds.DIVIDER, SheetKinds.PICTURE, SheetKinds.DICE: + return "" + SheetKinds.TEXT: + var text := str(box.value if box.value != null else "").strip_edges() + if text == "": + return "" + return text if box.title == "" else "[b]%s:[/b] %s" % [box.title, text] + var shown := "" + if box.var_name != "" and SheetLinks.WRITABLE.has(box.kind): + shown = "{@%s}" % (box.var_name if prefix == "" else "%s_%s" % [prefix, box.var_name]) + else: + shown = _value(doc, box) + if shown == "": + return "" + return "[b]%s:[/b] %s" % [box.title, shown] if box.title != "" else shown + + +## A box's value in words: lists by their names, currency with its total… +static func _value(doc: SheetDoc, box: SheetBox) -> String: + var v: Variant = box.value + match box.kind: + SheetKinds.RESOURCE: + var r: Dictionary = v if v is Dictionary else {} + return "%s / %s" % [SheetValues.show(r.get("cur", 0)), SheetValues.show(r.get("max", 0))] + SheetKinds.LIST: + var names: Array = [] + var cols: Array = box.config.get("columns", []) + var first := str((cols[0] as Dictionary).get("name", "Name")) if not cols.is_empty() else "Name" + for entry: Variant in (v if v is Array else []): + if entry is Dictionary: + names.append(str((entry as Dictionary).get(first, ""))) + return ", ".join(names) + SheetKinds.SLOTS: + return ", ".join((v if v is Array else []).map(func(it: Variant) -> String: return str((it as Dictionary).get("name", "")) if it is Dictionary else "")) + SheetKinds.CONDITIONS: + return ", ".join((v if v is Array else []).map(func(x: Variant) -> String: return str(x))) + SheetKinds.CURRENCY: + var coins: Array = box.config.get("coins", []) + return "%s %s" % [SheetValues.show(SheetValues.currency_total(box)), str((coins[0] as Dictionary).get("name", "")) if not coins.is_empty() else ""] + SheetKinds.STEP_DIE, SheetKinds.USAGE_DIE, SheetKinds.SHORT_TEXT, SheetKinds.DROPDOWN: + return str(v if v != null else "") + SheetKinds.CHECKBOX: + return "Yes" if bool(v) else "No" + SheetKinds.LADDER: + var steps: Array = box.config.get("steps", SheetKinds.FATE_LADDER) + var i := int(SheetValues.number(v)) + return str(steps[i]) if i >= 0 and i < steps.size() else "" + return SheetValues.show(SheetValues.value_of(doc, box)) diff --git a/core/sheet_text.gd.uid b/core/sheet_text.gd.uid new file mode 100644 index 0000000..aa10ab8 --- /dev/null +++ b/core/sheet_text.gd.uid @@ -0,0 +1 @@ +uid://b4rdf1t4kkobt diff --git a/docs/SHEETS.md b/docs/SHEETS.md index af4e8a5..3860f33 100644 --- a/docs/SHEETS.md +++ b/docs/SHEETS.md @@ -61,8 +61,20 @@ an old sheet card becomes a sheet with one text box. dispatch), `sheet_fields_trackers/smart/list/niche.gd`; settings: `ui/sheet_kind_settings.gd`; details side panel: `ui/sheet_detail_panel.gd`. Pictures are copied to `sheets/pictures/`. Not yet: per-entry variables in lists (phase D), BBCode buttons and Lore links in text (E). -- **D. Spread integration:** sheet node (first-tab preview), variables read/write, locks, - replace and migrate `KIND_SHEET`, document tabs. +- **D. Sheets on spreads** — built 2026-11-29: a sheet on a spread is a **Sheet card** linked to a + sheet file (`RollTable.sheet_id`, `sheet_prefix`; JSON `sheet`, `prefix`), so threads, groups, undo, + List view and the tray headline work as for any card. The card shows `SheetPreview` (first tab, + values, gold outline on boxes the last roll changed; double-click / "Open sheet" opens it with + "← spread"; the sheet editor then uses the spread's Play/Build). A roll reaching the card rolls + `SheetText.summary` (boxes as "Title: value", linked ones as {@prefix_name}) through + `Roller.sheet_text`. Bridge `core/sheet_links.gd` + `ui/main_sheet_links.gd`: before a roll "Use in + tables" boxes become @name / @prefix_name; after it changed values go back unless locked or not + writable. Text boxes on a sheet that is on the open spread also show spread values ({@answer}). + Migration: an old template Sheet card gets a sheet file (id `-`, one text box with + its template) when the spread loads or the card arrives (not inside Help demos). The user's picks: + prefix per card (blank allowed; the second sheet gets one from its name), only "Use in tables" boxes. + Card palette › Sheets: "New sheet" + your sheets. Sheet canvas: grid is one tiled texture (smooth + panning); boxes don't overlap (new ones take the nearest free spot, drags stop short; Alt = free). - **E. Lore Index library + items, export (PDF, PNG, share file), phone stacked view.** ## 5. Code map (phase B) diff --git a/help/topics.txt b/help/topics.txt index c24f938..bf48375 100644 --- a/help/topics.txt +++ b/help/topics.txt @@ -276,7 +276,7 @@ A result or a Lore Entry can have a picture: [b]Picture → Choose…[/b] in its The app opens on the [b]main menu[/b]: Spreads, Sheets, Settings and Quit. To come back to it, click the logo at the top left, or use [b]☰ → Main menu[/b]. [b]Sheets[/b] are pages for anything you keep track of: a character, a vehicle, a ship. They work on their own, without a spread. - [b]+ New sheet[/b] starts from a blank canvas or one of your templates. -- In [b]Build[/b], add fields from the [b]Fields[/b] palette on the left: click to add one in the middle, or drag it where you want it. Drag a box to move it and its corner to resize it. Boxes snap to the grid; hold [b]Alt[/b] to place one freely. +- In [b]Build[/b], add fields from the [b]Fields[/b] palette on the left: click to add one in the middle, or drag it where you want it. Drag a box to move it and its corner to resize it. Boxes snap to the grid and don't cover each other; hold [b]Alt[/b] to place one freely. Drag empty space to move around the sheet. - Click a box to edit its title, colour and frame on the right. With nothing selected, the right side edits the whole sheet: its name and tint. - [b]+ Tab[/b] adds a tab, each with its own canvas. Right-click a tab to rename, move or delete it. - In [b]Play[/b], type in the boxes to change values. Undo and redo work for both values and layout (Ctrl+Z, Ctrl+Shift+Z). @@ -286,6 +286,14 @@ The app opens on the [b]main menu[/b]: Spreads, Sheets, Settings and Quit. To co - Hover a list entry to see the start of its details; click its ⓘ (or a chip) to read and edit them in full in the side panel. - [b]Sheet ▾ → Save as template…[/b] keeps the layout to start new sheets from. +## Sheets on a spread +- In Build, drag one of your sheets from the card palette's [b]Sheets[/b] group onto the spread (or pick [b]New sheet[/b]). It becomes a Sheet card showing a small picture of its first tab. Threads can lead into it: a roll that reaches it shows the sheet in the tray, ready to copy or save. +- Every box with [b]Use in tables[/b] on becomes a value tables can use: a result's change like [b]@hp -= 4[/b] or [b]@background = "Soldier"[/b] writes into the sheet, and the box glows to show a roll changed it. A [b]locked[/b] box ignores rolls. +- Text boxes on the sheet can show the spread's values too, like {@name} saved by a choice card. +- Two sheets on one spread? Right-click one and give it a [b]Prefix for tables[/b], such as brin: its boxes are then @brin_str, @brin_hp… +- Double-click a sheet (or press [b]Open sheet[/b]) to open it; [b]←[/b] at the top goes back to the spread. +- Older spreads' Sheet cards turn into sheets by themselves: their template becomes a text box. + # Spreads, import and export A [b]spread[/b] is one layout of cards, saved under its own name. Use the switcher beside Play | Build (it shows the spread's name) to switch, or to make a new spread, rename, duplicate, delete one, or sort spreads into folders. - The spreads you opened last are at the top, under [b]Recent[/b]. Spreads with no folder come next, then each folder as a submenu. diff --git a/io/json_canon.gd b/io/json_canon.gd index 8a16668..b845ba5 100644 --- a/io/json_canon.gd +++ b/io/json_canon.gd @@ -131,7 +131,7 @@ static func _canon_table(td: Dictionary) -> Dictionary: for e in src_entries: entries.append(_canon_entry(e)) t["entries"] = entries - _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats", "cost"]) + _keep(td, t, ["color", "w", "list_h", "roll_floor", "roll_ceiling", "deck_empty_text", "columns", "column_rolls", "steps", "members", "repeats", "cost", "sheet", "prefix"]) # A separator may be just a space, so it isn't trimmed. if td.get("column_join") is String and td["column_join"] != "": t["column_join"] = td["column_join"] diff --git a/tests/test_logic_ui.gd b/tests/test_logic_ui.gd index 549144f..97b8a8c 100644 --- a/tests/test_logic_ui.gd +++ b/tests/test_logic_ui.gd @@ -138,8 +138,8 @@ func _test_scripted() -> void: var hp := main.card_for("v_hp") _eq(hp.value_ui.var_value.text, Expr.format_value(_var("hp")), "the HP card shows the new value after the roll") var sheet := main.card_for("report") - _check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the sheet card is up to date") - _check(Formatter.strip_tags(sheet.rows_ui.sheet_label.text).begins_with("Brin the delver"), "the sheet shows the name") + _check(sheet.table.sheet_id != "" and sheet.find_child("SheetPreview", true, false) != null, "the old sheet card was migrated to a sheet file") + _check(Formatter.strip_tags(main.tray._headline_text.text).contains("HP %s" % Expr.format_value(_var("hp"))), "the headline shows the sheet up to date") main.prompt_hook = main.rolling._ask_player @@ -306,7 +306,10 @@ func _test_live_edits() -> void: main.set_variable("gold", "42") _eq(_var("gold"), 42, "a number variable stays a number") _eq(main.card_for("v_gold").value_ui.var_value.text, "42", "the variable card follows an edit") - _check(Formatter.strip_tags(main.card_for("report").rows_ui.sheet_label.text).contains("Gold 42"), "the sheet follows an edit") + var report := main.data.get_table("report") + var report_doc := main.sheet_links.load_doc(report.sheet_id) + var shown := main.sheet_links.expand(report_doc, str(report_doc.tabs[0]["boxes"][0].value)) + _check(Formatter.strip_tags(shown).contains("Gold 42"), "the sheet's text box follows a spread value") main.reset_variable("gold") _eq(_var("gold"), 0, "reset goes back to the starting value") main.set_variable("hp", "3") @@ -325,11 +328,6 @@ func _test_live_edits() -> void: _check(dlg != null and dlg.is_inside_tree(), "Reset all asks first, in the app") dlg.close() main.tray.set_side(ResultTray.Side.EARLIER) - # Rendering live cards doesn't happen per frame: the sheet's text stays put. - var before := main.card_for("report").rows_ui.sheet_label.text - for i in 3: - await process_frame - _eq(main.card_for("report").rows_ui.sheet_label.text, before, "live cards only re-render on change") # ---------------------------------------------------------------- build rules diff --git a/tests/test_sheet_editor.gd b/tests/test_sheet_editor.gd index ad6e933..e4b2227 100644 --- a/tests/test_sheet_editor.gd +++ b/tests/test_sheet_editor.gd @@ -14,6 +14,8 @@ func run() -> void: await _test_tabs() await _test_keys() await _test_kinds() + await _test_links() + await _test_overlap() finish() @@ -57,7 +59,8 @@ func _test_boxes() -> void: var want := ed.canvas.drop_point(spot) _check(ed.palette.drop_at(ed.palette._add.bind(SheetKinds.TEXT), spot), "dropping on the canvas adds there") var text_box: SheetBox = ed.current_tab()["boxes"][1] - _eq(Vector2(text_box.x, text_box.y), Vector2(SheetKinds.snap(want.x), SheetKinds.snap(want.y)), "a dropped box snaps to the grid") + _eq(Vector2(text_box.x, text_box.y).posmod(SheetKinds.GRID), Vector2.ZERO, "a dropped box snaps to the grid") + _check(Vector2(text_box.x, text_box.y).distance_to(want) < 400, "near where it was dropped") var view: SheetBoxView = ed.canvas.views[box.id] view.begin_drag("move") view.drag_to(Vector2(37, 21), false) @@ -191,6 +194,82 @@ func _test_kinds() -> void: sheets.show_list() +## A sheet on the spread: its node draws, a roll writes its boxes (not the +## locked one), undo takes the node away and back, double-click opens it. +func _test_links() -> void: + var sheets := main.screens.sheets + main.screens.show(MainScreens.SPREAD) + var doc := sheets.store.create("Linked") + var boxes: Array = doc.tabs[0]["boxes"] + for spec: Array in [["short_text", "Background", "background", ""], ["number", "HP", "hp", 10], ["number", "Luck", "luck", 3]]: + var b := SheetKinds.make_box(spec[0], doc.new_box_id(), Vector2(0, boxes.size() * 96)) + b.title = spec[1] + b.var_name = spec[2] + b.value = spec[3] + b.locked = spec[1] == "Luck" + boxes.append(b) + sheets.store.save(doc) + main.set_mode(Main.Mode.BUILD) + var card := main.sheet_links.add_card(doc.id) + await _frames() + _check(card.kind == RollTable.KIND_SHEET and card.sheet_id == doc.id and card.name == "Linked", "placing a sheet adds a Sheet card for it") + _check(main.card_for(card.id).find_child("SheetPreview", true, false) != null, "the card shows the sheet's picture") + var t := main.editing.add_table() + t.entries.resize(1) + t.entries[0].effects = '@background = "Soldier"; @hp -= 4; @luck = 0' + t.entries[0].pipes = [card.id] + main.set_mode(Main.Mode.PLAY) + await main.rolling.start_roll(t.id, true) + await _frames() + var after := sheets.store.load_sheet(doc.id) + _eq(str(after.tabs[0]["boxes"][0].value), "Soldier", "a roll writes text into the sheet") + _eq(int(after.tabs[0]["boxes"][1].value), 6, "and numbers (HP 10 - 4)") + _eq(int(after.tabs[0]["boxes"][2].value), 3, "a locked box keeps its value") + _eq(int(main.persistent_vars["luck"]["value"]), 3, "and its variable goes back too") + _check((main.sheet_links.recent.get(doc.id, {}) as Dictionary).has(boxes[0].id), "the changed boxes are marked for a highlight") + var headline := TrayText.sheet_step(main.current.get("all", [])) + _check(str(headline.get("text", "")).contains("Soldier"), "a thread into the card ends on the sheet text: %s / %s" % [str(headline.get("text", "")).left(120), str((main.current.get("all", []) as Array).size())]) + main.sheet_links.open(card.id) + var ed := sheets.editor + _check(main.screens.showing(MainScreens.SHEETS) and ed.doc.id == doc.id and ed.top_bar.back_button.visible, "opening the card shows the sheet with a way back") + _check(not ed.building(), "in the spread's mode (Play)") + ed.back_to_spread() + _check(main.screens.showing(MainScreens.SPREAD), "← goes back to the spread") + main.set_mode(Main.Mode.BUILD) + var old := RollTable.create(RollTable.KIND_SHEET, TowerBoard.new_id("t"), "Hero") + old.entries[0].text = "[b]Hero[/b] {@background}" + main.data.tables.append(old) + main._board_changed() + await _frames() + _check(old.sheet_id != "", "an old template Sheet card gets a sheet file") + var made := sheets.store.load_sheet(old.sheet_id) + _eq(str(made.tabs[0]["boxes"][0].value), "[b]Hero[/b] {@background}", "holding its template in a text box") + + +## Boxes don't overlap: a new one lands on a free spot; a drag stops before +## covering another; Alt places it anywhere. +func _test_overlap() -> void: + var sheets := main.screens.sheets + main.screens.show(MainScreens.SHEETS) + sheets.open_doc(sheets.store.create("Tidy")) + var ed := sheets.editor + ed.set_mode(Main.Mode.BUILD) + var a := ed.add_box("number", Vector2(32, 32)) + var b := ed.add_box("number", Vector2(32, 32)) + _check(not a.rect().intersects(b.rect().grow(-0.5)), "a second box dropped on the first lands beside it") + var view: SheetBoxView = ed.canvas.views[b.id] + view.begin_drag("move") + view.drag_to(a.rect().position - b.rect().position, false) + view.end_drag() + _check(not a.rect().intersects(b.rect().grow(-0.5)), "dragging onto another box stops short") + view = ed.canvas.views[b.id] + view.begin_drag("move") + view.drag_to(a.rect().position - b.rect().position, true) + view.end_drag() + _eq(b.rect().position, a.rect().position, "Alt lets it overlap") + sheets.show_list() + + func _box(ed: SheetEditor, title: String) -> SheetBox: for tab in ed.doc.tabs: for b: SheetBox in tab["boxes"]: diff --git a/tests/test_sheets.gd b/tests/test_sheets.gd index 479430d..69c1443 100644 --- a/tests/test_sheets.gd +++ b/tests/test_sheets.gd @@ -13,6 +13,7 @@ func run() -> void: _test_store() _test_history() _test_values() + _test_links() _wipe(ROOT) finish() @@ -114,3 +115,44 @@ func _box(doc: SheetDoc, title: String) -> SheetBox: if b.title == title: return b return null + + +## The spread bridge: names with and without a prefix, what a roll may write, +## and locks. +func _test_links() -> void: + var doc := SheetDemo.create() + var board := TowerBoard.new() + var card := RollTable.create(RollTable.KIND_SHEET, "c1", "Brin") + card.sheet_id = doc.id + board.tables.append(card) + var vars := {} + var given := SheetLinks.inject(board, vars, func(_id: String) -> SheetDoc: return doc) + _eq(vars["str"]["value"], 14, "a linked box becomes @str") + _check(given.has("str_mod"), "formulas are lent too") + card.sheet_prefix = "brin" + vars = {} + given = SheetLinks.inject(board, vars, func(_id: String) -> SheetDoc: return doc) + _check(vars.has("brin_str") and not vars.has("str"), "a prefix makes it @brin_str") + vars["brin_str"] = {"value": 16, "source": "roll"} + var found := SheetLinks.changes(given, vars) + _eq(found.size(), 1, "only the changed value is seen") + var strength := doc.find_box(found[0]["box"]) + _check(SheetLinks.write(strength, 16) and int(strength.value) == 16, "a number box takes the rolled value") + strength.locked = true + _check(not SheetLinks.write(strength, 3) and int(strength.value) == 16, "a locked box keeps its value") + var mod: SheetBox = null + for b: SheetBox in doc.tabs[0]["boxes"]: + if b.var_name == "str_mod": + mod = b + _check(not SheetLinks.write(mod, 9), "a formula can't be written by a roll") + var saved := TowerBoard.new() + saved.load_dict(board.to_dict()) + _check(saved.tables[0].sheet_id == doc.id and saved.tables[0].sheet_prefix == "brin", "a Sheet card keeps its sheet and prefix") + var text := SheetText.summary(doc, "brin") + _check(text.contains("[b]Strength:[/b] {@brin_str}"), "a roll shows linked boxes as {@prefix_name}") + _check(text.contains("[b]Talents:[/b] Shield Wall, Keen Eye, Second Wind"), "and lists by their names") + var tab := doc.tabs[0] + var first: SheetBox = tab["boxes"][1] + _check(SheetDoc.overlaps(tab, first.rect()), "a box's own place overlaps it") + var spot := SheetDoc.free_spot(tab, first.rect(), SheetKinds.GRID) + _check(not SheetDoc.overlaps(tab, Rect2(spot, first.rect().size)), "free_spot finds a place that covers nothing") diff --git a/ui/actions.gd b/ui/actions.gd index bde7d05..a2e09e0 100644 --- a/ui/actions.gd +++ b/ui/actions.gd @@ -90,6 +90,8 @@ static func card(m: Main, t: RollTable) -> Array: list.append({"text": "Roll", "do": m.rolling.start_roll.bind(t.id)}) list.append({"text": "Roll several times…", "do": BatchRoll.ask.bind(m, t.id), "tip": "Roll the whole chain a number of times and see every result together"}) + if t.kind == RollTable.KIND_SHEET and t.sheet_id != "": + list.append_array(m.sheet_links.menu_items(t)) if t.card_mode: list.append({"text": "Shuffle the deck", "do": m.reshuffle_table.bind(t.id)}) if c and c.can_collapse(): diff --git a/ui/card_catalog.gd b/ui/card_catalog.gd index 81ad40a..908b95e 100644 --- a/ui/card_catalog.gd +++ b/ui/card_catalog.gd @@ -44,8 +44,8 @@ const ITEMS := [ "name": "Skills", "tip": "A named list of values: skills, contacts…", "words": "collection list skills contacts"}, {"label": "Scale", "group": GROUP_VALUES, "kind": RollTable.KIND_VARIABLE, "sub": RollTable.VAR_SCALE, "variant": "", "name": "New scale", "tip": "Ordered steps that move up or down", "words": "steps ladder ordered"}, - {"label": "Sheet", "group": GROUP_SHEETS, "kind": RollTable.KIND_SHEET, "sub": "", "variant": "", - "name": "Sheet", "tip": "Shows values as formatted text that stays up to date", "words": "character summary text"}, + {"label": "New sheet", "group": GROUP_SHEETS, "kind": RollTable.KIND_SHEET, "sub": "", "variant": "", + "name": "Sheet", "tip": "A new sheet on the spread (open it to add fields)", "words": "character summary text"}, ] @@ -82,3 +82,8 @@ static func apply_variant(t: RollTable, variant: String) -> void: TableSettingsRules.assign_ranges(t) VARIANT_DECK: t.card_mode = true + # "sheet::": a Sheet card showing that sheet (MainSheetLinks.add_card). + if variant.begins_with("sheet:"): + t.sheet_id = variant.get_slice(":", 1) + t.sheet_prefix = variant.get_slice(":", 2) + t.width = 340 diff --git a/ui/card_palette.gd b/ui/card_palette.gd index 995584f..d1e5aa9 100644 --- a/ui/card_palette.gd +++ b/ui/card_palette.gd @@ -17,6 +17,7 @@ var list: PaletteList var search: LineEdit var notice: PanelContainer var _templates: Array[Dictionary] = [] +var _sheets: Array[Dictionary] = [] func setup(p_main: Main) -> void: @@ -46,6 +47,9 @@ func _process(_delta: float) -> void: ## Reads the template list again (it lives in files, so not on every keystroke). func refresh_templates() -> void: _templates = m.templating.templates().list() if m.templating else [] + _sheets.clear() + if m.screens: + _sheets = m.screens.sheets.store.list() list.rebuild() @@ -56,6 +60,8 @@ func _sections(query: String) -> Array: for item: Dictionary in CardCatalog.ITEMS: if item["group"] == group and PaletteList.matches(item, query): entries.append([item, _add_card.bind(item)]) + if group == CardCatalog.GROUP_SHEETS: + entries.append_array(_sheet_entries(query)) out.append([group, entries]) var templates: Array = [] for row: Dictionary in _templates: @@ -69,6 +75,16 @@ func _sections(query: String) -> Array: return out +## Your sheets, to place on the spread as Sheet cards. +func _sheet_entries(query: String) -> Array: + var out: Array = [] + for row: Dictionary in _sheets: + var item := {"label": row["name"], "group": CardCatalog.GROUP_SHEETS, "tip": "Place this sheet on the spread; tables can then use its boxes", "words": "sheet character"} + if PaletteList.matches(item, query): + out.append([item, func(at: Vector2) -> void: m.sheet_links.add_card(str(row["id"]), at)]) + return out + + ## Adds through `on_add` with its top-left corner under a screen point on the spread. func drop_at(on_add: Callable, screen_point: Vector2) -> bool: var board := m.board diff --git a/ui/demo_mode.gd b/ui/demo_mode.gd index 59ae1b4..0e2cc74 100644 --- a/ui/demo_mode.gd +++ b/ui/demo_mode.gd @@ -26,8 +26,10 @@ func open(key: String) -> void: _return_id = m.data.id _was_saving = m._saving_enabled m._saving_enabled = false - m.collections._show_collection(DemoSpreads.build(key)) + # The bar first: while it shows, the demo counts as open (old Sheet cards + # in a demo aren't migrated to sheet files, MainSheetLinks.migrate). _show_bar(str(DemoSpreads.TITLES[key])) + m.collections._show_collection(DemoSpreads.build(key)) func back() -> void: diff --git a/ui/inspector_card.gd b/ui/inspector_card.gd index 6e237a4..63b6200 100644 --- a/ui/inspector_card.gd +++ b/ui/inspector_card.gd @@ -341,7 +341,31 @@ static func add_member(insp: Inspector, t: RollTable) -> String: # ---------- Sheet ---------- +## A Sheet card showing a sheet file: open it, and the prefix tables use. +static func _linked_sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: + var links := insp.main.sheet_links + var doc := links.load_doc(t.sheet_id) + box.add_child(InspectorKit.note("Shows the sheet “%s”. Its boxes with Use in tables on are values tables can read and change." % (doc.name if doc else t.sheet_id), Style.MUTED, 13)) + var open := ModalCard.make_button("Open sheet", "primary") + open.pressed.connect(links.open.bind(t.id)) + box.add_child(open) + var prefix := LineEdit.new() + prefix.name = "SheetPrefix" + prefix.text = t.sheet_prefix + prefix.placeholder_text = "blank = plain @name" + ModalCard.style_line_edit(prefix) + prefix.text_submitted.connect(func(text: String) -> void: links.set_prefix(t.id, text)) + prefix.focus_exited.connect(func() -> void: + if prefix.text != t.sheet_prefix: + links.set_prefix(t.id, prefix.text)) + box.add_child(InspectorKit.field("Prefix for tables", prefix)) + box.add_child(InspectorKit.note("With a prefix like brin, tables use @brin_str: two characters on one spread. A roll that reaches this card shows the sheet in the tray.", Style.MUTED, 12)) + + static func _sheet(insp: Inspector, box: VBoxContainer, t: RollTable) -> void: + if t.sheet_id != "": + _linked_sheet(insp, box, t) + return var tpl := InspectorKit.text_box(t.entries[0].text if not t.entries.is_empty() else "", "[b]{@name}[/b]\nStrength {@str}", 120.0) InspectorKit.code(tpl) InspectorKit.tag(tpl, "card.template") diff --git a/ui/main.gd b/ui/main.gd index 63f009e..3727718 100644 --- a/ui/main.gd +++ b/ui/main.gd @@ -50,6 +50,8 @@ var list_view: ListView var left_dock: LeftDock ## Main menu, spread or Sheets (MainScreens). var screens: MainScreens +## Sheets placed on the spread and their @variables (MainSheetLinks). +var sheet_links: MainSheetLinks ## The phone layout, when it is on (MobileLayout.wanted). var mobile: MobileLayout ## The Book panel (reusable results). @@ -96,6 +98,7 @@ var card_refresh: CardRefreshQueue func _init() -> void: layout = MainLayout.new(self) + sheet_links = MainSheetLinks.new(self) card_refresh = CardRefreshQueue.new(self) top_bar = MainTopBar.new(self) editing = MainEditing.new(self) @@ -162,6 +165,7 @@ func _exit_tree() -> void: _save_now() if screens: screens.sheets.leave() + Roller.sheet_text = Callable() # ---------- Cards ---------- @@ -179,6 +183,7 @@ func is_entry_lit(tid: String, eid: String) -> bool: func refresh_live() -> void: for card in cards.values(): (card as TableCard).refresh_live() + sheet_links.refresh_previews() func _add_modal(d: ModalCard) -> void: add_child(d) diff --git a/ui/main_cli.gd b/ui/main_cli.gd index 37da93b..a07c4cb 100644 --- a/ui/main_cli.gd +++ b/ui/main_cli.gd @@ -274,6 +274,11 @@ func _run_nav_cli(args: PackedStringArray) -> void: for b: SheetBox in tab["boxes"]: if select != "" and b.title == select: m.screens.sheets.editor.select(b.id) if args.has("--sheet-build") else m.screens.sheets.editor.show_details(b.id, 0) + if args.has("--sheet-node"): + # The example sheet placed on the spread, as a Sheet card. + var placed := SheetDemo.create() + m.screens.sheets.store.save(placed) + m.sheet_links.add_card(placed.id, m.board.screen_to_world(m.board.size * Vector2(0.62, 0.3))) if args.has("--new-sheet"): m.screens.show(MainScreens.SHEETS) m.screens.sheets.store.save_as_template(SheetDemo.create(), "OSR Character") diff --git a/ui/main_editing.gd b/ui/main_editing.gd index c635eaf..b286266 100644 --- a/ui/main_editing.gd +++ b/ui/main_editing.gd @@ -23,11 +23,11 @@ func _init(p_main: Main) -> void: ## Adds a card of any kind (RollTable.create) in the middle of the view, or ## with its top-left corner at `at` (world coordinates). `variant` gives it a ## CardCatalog variant's start settings ("dice", "deck"). -func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "", at: Vector2 = Vector2.INF, variant: String = "") -> RollTable: +func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "", at: Vector2 = Vector2.INF, variant: String = "", card_name: String = "") -> RollTable: m.undo_redo._begin_edit() var center := m.board.screen_to_world(m.board.size / 2.0) if at == Vector2.INF else at + Vector2(128, 120) - var item := CardCatalog.find(kind, sub, variant) - var name := str(item.get("name", "New table")) + var item := CardCatalog.find(kind, sub, variant.get_slice(":", 0)) + var name := card_name if card_name != "" else str(item.get("name", "New table")) var t := RollTable.create(kind, TowerBoard.new_id("t"), name, sub) if kind == RollTable.KIND_ROLL or kind == RollTable.KIND_CHECK: for e in t.entries: diff --git a/ui/main_layout.gd b/ui/main_layout.gd index 9113fea..cc6090a 100644 --- a/ui/main_layout.gd +++ b/ui/main_layout.gd @@ -118,6 +118,8 @@ func _build_ui() -> void: ## _apply_group_visibility. Called from outside an edit (a board loaded or ## replaced), it also takes the board as the edit history's new baseline. func _rebuild_cards() -> void: + # Old Sheet cards get their sheet file before the edit history takes the board. + m.sheet_links.migrate() if not m.undo_redo._keep_history: m.undo_redo._sync_history() for c in m.board.cards.get_children(): @@ -168,12 +170,16 @@ func set_mode(new_mode: Main.Mode) -> void: (n as GroupCard).rebuild() m.top_bar._update_endless_chip() m.nav._nav_mode_changed() + m.sheet_links.refresh_previews() ## What every change to the board needs: a save soon, fresh caches and redraws. func _board_changed() -> void: if m._saving_enabled: m._save_timer.start() + # A Sheet card that came in from a template or an import gets its sheet. + if m.sheet_links.migrate(): + m.card_refresh.rebuild_all() m.local_state._ref_cache.clear() m.view_rev += 1 m.edit_rev += 1 diff --git a/ui/main_rolling.gd b/ui/main_rolling.gd index 100f842..113e238 100644 --- a/ui/main_rolling.gd +++ b/ui/main_rolling.gd @@ -67,6 +67,8 @@ func start_roll(tid: String, fast: bool = false) -> void: for c in m.cards.values(): (c as TableCard).set_rolling(false) (c as TableCard).clear_flick() + # Sheets on the spread lend their boxes as @variables (MainSheetLinks). + m.sheet_links.before_roll(Formatter.strip_tags(t.name)) var ctx := Roller.new_context(m.data, m.rng, m.persistent_vars, m.decks) ctx.prompt = _prompt_for.bind(run) m.rolling_ctx = ctx diff --git a/ui/main_screens.gd b/ui/main_screens.gd index 9f83f8b..ba1e0bc 100644 --- a/ui/main_screens.gd +++ b/ui/main_screens.gd @@ -47,6 +47,8 @@ func show(which: String) -> void: sheets.visible = which == SHEETS if which == SHEETS: sheets.enter() + if which == SPREAD: + m.sheet_links.refresh_previews() func showing(which: String) -> bool: diff --git a/ui/main_sheet_links.gd b/ui/main_sheet_links.gd new file mode 100644 index 0000000..097a934 --- /dev/null +++ b/ui/main_sheet_links.gd @@ -0,0 +1,203 @@ +class_name MainSheetLinks +extends RefCounted +## Sheets on the open spread. A Sheet card shows a sheet file +## (RollTable.sheet_id) as a small picture of its first tab (SheetPreview); +## threads can lead into it like any card, and a roll that reaches it shows +## the sheet's text (SheetText via Roller.sheet_text). Old template-only +## Sheet cards are migrated: their text becomes a text box in a new sheet. +## Around each roll it runs the variable bridge (SheetLinks): linked boxes +## become @variables, changed values go back into the boxes. + +var m: Main +## sheet id -> {box id: "from "}: boxes the last roll wrote. +var recent: Dictionary = {} +var _given: Dictionary = {} +var _roll_label := "" + + +func _init(p_main: Main) -> void: + m = p_main + Roller.sheet_text = func(t: RollTable) -> String: + if not is_instance_valid(m) or not m.is_inside_tree(): + return t.entries[0].text + var doc := load_doc(t.sheet_id) + return SheetText.summary(doc, t.sheet_prefix) if doc else t.entries[0].text + + +func store() -> SheetStore: + return m.screens.sheets.store if m.screens else null + + +## The sheet with `id`: the editor's copy when it is open there. +func load_doc(id: String) -> SheetDoc: + if m.screens == null or id == "": + return null + var ed := m.screens.sheets.editor + if ed.doc and ed.doc.id == id: + return ed.doc + return store().load_sheet(id) + + +## Old Sheet cards (a BBCode template, no sheet file) get a sheet whose one +## text box holds the template; it keeps showing spread values like {@name}. +## The file id comes from the spread and card, so doing it again (after an +## undo) links the same file. True when any card changed. +func migrate() -> bool: + if m.data == null or store() == null: + return false + # Help demos save nothing: their old Sheet cards stay as they are there + # ("Keep a copy" makes a real spread, which migrates when it opens). + if m.demo and m.demo.active(): + return false + var changed := false + for t in m.data.tables: + if t.kind != RollTable.KIND_SHEET or t.sheet_id != "": + continue + var id := LibraryStore.slugify("%s-%s" % [m.data.id, t.id]) + if store().load_sheet(id) == null: + var doc := SheetDoc.new(id, Formatter.strip_tags(t.name).strip_edges() if Formatter.strip_tags(t.name).strip_edges() != "" else "Sheet") + var box := SheetKinds.make_box(SheetKinds.TEXT, doc.new_box_id(), Vector2(16, 16)) + box.title = "" + box.w = 24 * SheetKinds.GRID + box.h = 14 * SheetKinds.GRID + box.value = t.entries[0].text if not t.entries.is_empty() else "" + doc.tabs[0]["boxes"].append(box) + store().save(doc) + t.sheet_id = id + changed = true + return changed + + +## True when a Sheet card on the open spread shows sheet `id`. +func on_spread(id: String) -> bool: + return m.data != null and SheetLinks.sheet_cards(m.data).any(func(t: RollTable) -> bool: return t.sheet_id == id) + + +## Fills in {@name} in a sheet's text: the sheet's own boxes first, then (when +## the sheet is on the open spread) the spread's values, such as an answer a +## choice card saved. +func expand(doc: SheetDoc, text: String) -> String: + if not text.contains("{@"): + return text + var values := SheetValues.vars(doc) + if on_spread(doc.id): + for name: String in m.persistent_vars: + if not values.has(name): + var entry: Variant = m.persistent_vars[name] + values[name] = (entry as Dictionary).get("value", "") if entry is Dictionary else entry + for name: String in values: + text = text.replace("{@%s}" % name, "[b]%s[/b]" % SheetValues.show(values[name])) + return text + + +## Redraws the sheet pictures on the cards (after a roll or a sheet edit). +func refresh_previews() -> void: + for t in SheetLinks.sheet_cards(m.data) if m.data else []: + var card: TableCard = m.card_for(t.id) + var preview: SheetPreview = card.find_child("SheetPreview", true, false) if card else null + if preview: + preview.reload() + + +## Places sheet `sheet_id` on the spread as a Sheet card, top-left at `at` +## (INF = view centre). A second sheet gets a prefix from its name so their +## @names don't clash. +func add_card(sheet_id: String, at: Vector2 = Vector2.INF) -> RollTable: + var doc := load_doc(sheet_id) + if doc == null: + m.toast("Couldn't read that sheet") + return null + var prefix := "" + if not SheetLinks.sheet_cards(m.data).is_empty(): + prefix = LibraryStore.slugify(doc.name.get_slice(" ", 0)).replace("-", "_") + return m.editing.add_table(RollTable.KIND_SHEET, "", at, "sheet:%s:%s" % [sheet_id, prefix], doc.name) + + +func set_prefix(card_id: String, prefix: String) -> void: + var t := m.data.get_table(card_id) + if t == null: + return + m.undo_redo._begin_edit() + t.sheet_prefix = LibraryStore.slugify(prefix).replace("-", "_") + m.mark_dirty() + m.undo_redo._end_edit("Sheet prefix") + m.inspector_edited(card_id) + refresh_previews() + + +## Opens the card's sheet in the sheet editor, in the spread's mode, with a +## way back to the spread. +func open(card_id: String) -> void: + var t := m.data.get_table(card_id) + var doc := load_doc(t.sheet_id if t else "") + if doc == null: + m.toast("That sheet is gone. Delete the card, or link another sheet.") + return + m.screens.show(MainScreens.SHEETS) + m.screens.sheets.open_doc(doc) + m.screens.sheets.editor.open_from_spread(m.data.name) + + +## Right-click items for a linked Sheet card (Actions.card). +func menu_items(t: RollTable) -> Array: + return [ + {"text": "Open sheet", "do": open.bind(t.id)}, + {"text": "Prefix for tables…", "do": ask_prefix.bind(t.id), "disabled": m.mode != Main.Mode.BUILD, + "tip": "With a prefix like brin, tables use @brin_str. Blank = plain @str."}, + ] + + +func ask_prefix(card_id: String) -> void: + var t := m.data.get_table(card_id) + m._add_modal(ModalCard.ask_text("Prefix for tables", "Tables read this sheet's boxes as @prefix_name. Blank = plain @name.", + t.sheet_prefix, "Save", func(text: String) -> void: set_prefix(card_id, text), true)) + + +# ---------- The variable bridge around a roll ---------- + +## Before a roll: every linked box becomes a spread variable. +func before_roll(table_name: String) -> void: + _given = {} + _roll_label = table_name + if m.data == null or m.screens == null: + return + _given = SheetLinks.inject(m.data, m.persistent_vars, load_doc) + + +## After a roll: values it changed go into their boxes (one undo step when +## the sheet is open in the editor); locked boxes keep theirs. +func after_roll() -> void: + if _given.is_empty(): + return + var found := SheetLinks.changes(_given, m.persistent_vars) + var by_sheet := {} + for c: Dictionary in found: + if not by_sheet.has(c["sheet"]): + by_sheet[c["sheet"]] = [] + (by_sheet[c["sheet"]] as Array).append(c) + var said: Array[String] = [] + for sheet_id: String in by_sheet: + var doc := load_doc(sheet_id) + if doc == null: + continue + var marks := {} + var write := func() -> void: + for c: Dictionary in by_sheet[sheet_id]: + var box := doc.find_box(c["box"]) + if box and SheetLinks.write(box, c["value"]): + marks[box.id] = "from %s" % _roll_label + said.append("%s: %s → %s" % [doc.name, box.title, SheetText._value(doc, box)]) + else: + var g: Dictionary = _given[c["name"]] + m.persistent_vars[c["name"]] = {"value": g["value"], "source": "locked on %s" % doc.name} + var ed := m.screens.sheets.editor + if ed.doc == doc: + ed.edit("Roll: %s" % _roll_label, write) + else: + write.call() + store().save(doc) + recent[sheet_id] = marks + _given = {} + refresh_previews() + if not said.is_empty(): + m.toast(" · ".join(said)) diff --git a/ui/main_sheet_links.gd.uid b/ui/main_sheet_links.gd.uid new file mode 100644 index 0000000..102a482 --- /dev/null +++ b/ui/main_sheet_links.gd.uid @@ -0,0 +1 @@ +uid://ccqediupnuimv diff --git a/ui/main_state.gd b/ui/main_state.gd index 74ac4ca..8e2e1b6 100644 --- a/ui/main_state.gd +++ b/ui/main_state.gd @@ -54,6 +54,8 @@ func load_local_state() -> void: ## After a roll: saves the decks, any changed persistent variables and the ## history record. func _store_roll(ctx: RollContext) -> void: + # Values the roll changed go back into the sheets on the spread first. + m.sheet_links.after_roll() if m.state == null: return _store_decks() diff --git a/ui/sheet_box_view.gd b/ui/sheet_box_view.gd index 1b1ef62..0c118f9 100644 --- a/ui/sheet_box_view.gd +++ b/ui/sheet_box_view.gd @@ -3,8 +3,8 @@ extends Panel ## One box on the sheet canvas: a card with a title band on top (headings and ## frameless boxes have none). Its colour tints the card, band and border ## (look). In Play its field takes input (SheetFieldViews); in Build the -## whole box is a handle: click selects, drag moves (snapped to the grid; Alt -## places freely), the corner grip resizes. +## whole box is a handle: click selects, drag moves (snapped to the grid, +## never over another box; Alt places freely), the corner grip resizes. const GRIP := 14.0 const MIN_SIZE := Vector2(48, 32) @@ -104,6 +104,12 @@ func paint(selected: bool) -> void: sb = Style.bordered(sb, 1, Color(Style.ON_BG, 0.35)) else: sb = Style.bordered(sb, 1, colors["border"]) + var mark := ed.roll_mark(box.id) + if mark != "" and not selected: + sb = Style.bordered(sb, 2, Style.ACCENT) + sb.shadow_color = Color(Style.ACCENT, 0.4) + sb.shadow_size = 7 + tooltip_text = mark if selected: sb = Style.bordered(sb, 2, Style.SELECTED) sb.shadow_color = Color(Style.SELECTED, 0.45) @@ -163,6 +169,9 @@ func drag_to(delta: Vector2, free: bool) -> void: r.size = (_start.size + delta).max(MIN_SIZE) if not free: r.size = Vector2(maxf(SheetKinds.snap(r.size.x), MIN_SIZE.x), maxf(SheetKinds.snap(r.size.y), MIN_SIZE.y)) + # Boxes don't cover each other: stay at the last free place (Alt: anywhere). + if not free and SheetDoc.overlaps(ed.current_tab(), r, box.id): + return box.set_rect(r) position = r.position custom_minimum_size = r.size diff --git a/ui/sheet_canvas.gd b/ui/sheet_canvas.gd index c438e13..5e178d9 100644 --- a/ui/sheet_canvas.gd +++ b/ui/sheet_canvas.gd @@ -23,6 +23,8 @@ var _origin_x := -1.0 var _panning := false var _pan_from := Vector2.ZERO var _pan_scroll := Vector2.ZERO +## One grid step with a dot in its corner, drawn tiled (one draw call). +var _grid_tile: ImageTexture func setup(p_editor: SheetEditor) -> void: @@ -31,6 +33,8 @@ func setup(p_editor: SheetEditor) -> void: _backdrop = BoardBackdrop.new(ThemeStore.current) holder = Control.new() holder.mouse_filter = Control.MOUSE_FILTER_STOP + holder.texture_repeat = CanvasItem.TEXTURE_REPEAT_ENABLED + _grid_tile = _make_grid_tile() holder.draw.connect(_draw_back) holder.gui_input.connect(_area_input) add_child(holder) @@ -51,6 +55,7 @@ func rebuild() -> void: area.add_child(view) views[box.id] = view paint_selection() + holder.queue_redraw() if _origin_x < 0.0: _fit_area.call_deferred() else: @@ -99,8 +104,10 @@ func _fit_area() -> void: _origin_x = maxf(MARGIN, floorf((view_size.x - page.x - MARGIN) / 2.0)) area.position = Vector2(maxf(_origin_x, MARGIN), MARGIN) area.size = page + view_size - holder.custom_minimum_size = (area.position + area.size).max(view_size) - holder.queue_redraw() + var want := (area.position + area.size).max(view_size) + if want != holder.custom_minimum_size: + holder.custom_minimum_size = want + holder.queue_redraw() ## While a box is dragged near an edge, scrolls toward it. Returns how far @@ -121,7 +128,8 @@ func edge_scroll(screen_point: Vector2) -> Vector2: if step == Vector2.ZERO: return step var before := Vector2(scroll_horizontal, scroll_vertical) - _fit_area() + if before.x + size.x + step.x > holder.custom_minimum_size.x or before.y + size.y + step.y > holder.custom_minimum_size.y: + _fit_area() scroll_horizontal = int(before.x + step.x) scroll_vertical = int(before.y + step.y) return Vector2(scroll_horizontal, scroll_vertical) - before @@ -135,20 +143,22 @@ func _draw_back() -> void: ## The snap grid as dots over the whole canvas (Build only), lined up with the -## page's corner so boxes snap onto the dots. +## page's corner so boxes snap onto the dots: one tiled texture. func _draw_grid() -> void: if ed.doc == null or not ed.building(): return - var step := SheetKinds.GRID - var dot := Color(Style.ON_BG, 0.2) - var start := area.position.posmod(step) - var y := start.y - while y <= holder.size.y: - var x := start.x - while x <= holder.size.x: - holder.draw_circle(Vector2(x, y), 1.0, dot) - x += step - y += step + var start := area.position.posmod(SheetKinds.GRID) - Vector2.ONE * SheetKinds.GRID + holder.draw_texture_rect(_grid_tile, Rect2(start, holder.size + Vector2.ONE * SheetKinds.GRID * 2.0), true) + + +static func _make_grid_tile() -> ImageTexture: + var n := int(SheetKinds.GRID) + var img := Image.create(n, n, false, Image.FORMAT_RGBA8) + img.fill(Color(0, 0, 0, 0)) + var dot := Color(Style.ON_BG, 0.22) + for p: Vector2i in [Vector2i(0, 0), Vector2i(1, 0), Vector2i(0, 1), Vector2i(1, 1)]: + img.set_pixelv(p, dot) + return ImageTexture.create_from_image(img) ## Empty space: a click clears the selection; a left- or middle-drag pans. @@ -175,7 +185,8 @@ func _area_input(ev: InputEvent) -> void: ## Scrolls to `at` (scroll pixels), growing the canvas when needed. func pan_to(at: Vector2) -> void: - _fit_area() + if at.x + size.x > holder.custom_minimum_size.x or at.y + size.y > holder.custom_minimum_size.y: + _fit_area() scroll_horizontal = int(maxf(at.x, 0)) scroll_vertical = int(maxf(at.y, 0)) diff --git a/ui/sheet_editor.gd b/ui/sheet_editor.gd index 156f269..f90e1e8 100644 --- a/ui/sheet_editor.gd +++ b/ui/sheet_editor.gd @@ -31,6 +31,8 @@ var undo_label: Label var _save_timer: Timer var _dirty := false var _merge_key := "" +## Opened from a sheet node: the spread to go back to ("" = opened from Sheets). +var from_spread := "" var _merge_at := 0.0 @@ -112,6 +114,7 @@ func update_status() -> void: func open(p_doc: SheetDoc) -> void: + from_spread = "" doc = p_doc history.clear() _merge_key = "" @@ -147,7 +150,22 @@ func building() -> bool: return mode == Main.Mode.BUILD +## Opened from a node on a spread: the spread's mode, and a way back. +func open_from_spread(spread_name: String) -> void: + from_spread = spread_name + set_mode(m.mode) + + +## Saves and goes back to the spread this sheet was opened from. +func back_to_spread() -> void: + save_now() + m.screens.show(MainScreens.SPREAD) + + func set_mode(new_mode: Main.Mode) -> void: + # Inside a spread there is one Play/Build switch: the spread's. + if from_spread != "" and m.mode != new_mode: + m.set_mode(new_mode) mode = new_mode if not building(): selected = "" @@ -218,6 +236,11 @@ func edit_value(box: SheetBox, value: Variant, keep_id: String = "-") -> void: canvas.rebuild_except(box.id if keep_id == "-" else keep_id) +## The note a roll left on a box ("from Background table"), or "". +func roll_mark(box_id: String) -> String: + return str((m.sheet_links.recent.get(doc.id, {}) as Dictionary).get(box_id, "")) if doc else "" + + ## A value change from a click (a tick, a chip, + Add): one undo step, all redrawn. func set_value(box: SheetBox, value: Variant) -> void: edit("Change %s" % (box.title if box.title != "" else "a value"), func() -> void: box.value = value) @@ -271,6 +294,8 @@ func _step(state: Dictionary, verb: String) -> void: func add_box(kind: String, at: Vector2 = Vector2.INF) -> SheetBox: var spot := canvas.visible_center() - Vector2(96, 48) if at == Vector2.INF else at var box := SheetKinds.make_box(kind, doc.new_box_id(), spot.max(Vector2.ZERO)) + if not Input.is_key_pressed(KEY_ALT): + box.set_rect(Rect2(SheetDoc.free_spot(current_tab(), box.rect(), SheetKinds.GRID), box.rect().size)) edit("Add %s" % SheetKinds.label_of(box), func() -> void: current_tab()["boxes"].append(box)) select(box.id) return box diff --git a/ui/sheet_field_views.gd b/ui/sheet_field_views.gd index 1a86840..d6c9504 100644 --- a/ui/sheet_field_views.gd +++ b/ui/sheet_field_views.gd @@ -205,12 +205,7 @@ static func _text(ed: SheetEditor, box: SheetBox, ink: Color) -> Control: ## Live values: {@name} shows the value of the box used in tables as @name. static func expand(ed: SheetEditor, text: String) -> String: - if not text.contains("{@"): - return text - var values := SheetValues.vars(ed.doc) - for name: String in values: - text = text.replace("{@%s}" % name, "[b]%s[/b]" % SheetValues.show(values[name])) - return text + return ed.m.sheet_links.expand(ed.doc, text) static func parse_number(text: String, fallback: Variant) -> Variant: diff --git a/ui/sheet_preview.gd b/ui/sheet_preview.gd new file mode 100644 index 0000000..50c7896 --- /dev/null +++ b/ui/sheet_preview.gd @@ -0,0 +1,70 @@ +class_name SheetPreview +extends Control +## A small drawing of a sheet's first tab, values included, inside a Sheet +## card on the spread (TableCardKindRows.make_sheet_row). Boxes the last roll +## changed are outlined in the accent colour. Double-click opens the sheet. + +var links: MainSheetLinks +var card: RollTable +var doc: SheetDoc + + +func setup(p_links: MainSheetLinks, p_card: RollTable) -> void: + links = p_links + card = p_card + name = "SheetPreview" + custom_minimum_size = Vector2(0, 180) + size_flags_horizontal = Control.SIZE_EXPAND_FILL + mouse_filter = Control.MOUSE_FILTER_PASS + gui_input.connect(func(ev: InputEvent) -> void: + var mb := ev as InputEventMouseButton + if mb and mb.pressed and mb.double_click and mb.button_index == MOUSE_BUTTON_LEFT: + links.open(card.id) + accept_event()) + reload() + + +## Reads the sheet again and redraws. +func reload() -> void: + doc = links.load_doc(card.sheet_id) + tooltip_text = ("%s · double-click to open%s" % [doc.name, ("\nTables read it as @%s_…" % card.sheet_prefix) if card.sheet_prefix != "" else ""]) if doc else "Sheet not found" + queue_redraw() + + +func _draw() -> void: + var area := Rect2(Vector2.ZERO, size) + draw_rect(area, Color(Style.BG, 0.9)) + if doc == null: + draw_string(Style.body(), Vector2(8, 20), "Sheet not found", HORIZONTAL_ALIGNMENT_LEFT, size.x - 16, 13, Style.ON_BG_MUTED) + return + var boxes: Array = doc.tabs[0]["boxes"] + if boxes.is_empty(): + draw_string(Style.body(), Vector2(8, 20), "An empty sheet. Double-click to add fields.", HORIZONTAL_ALIGNMENT_LEFT, size.x - 16, 13, Style.ON_BG_MUTED) + return + area = area.grow(-6) + var bounds := Rect2((boxes[0] as SheetBox).rect()) + for b: SheetBox in boxes: + bounds = bounds.merge(b.rect()) + var k := minf(area.size.x / bounds.size.x, area.size.y / bounds.size.y) + var marks: Dictionary = links.recent.get(doc.id, {}) + for b: SheetBox in boxes: + var r := Rect2(area.position + (b.rect().position - bounds.position) * k, b.rect().size * k).grow(-1) + var look := SheetBoxView.look(b.color, b.frameless) + if not b.frameless: + var marked := marks.has(b.id) + draw_style_box(Style.bordered(Style.box(look["bg"], 3), 2 if marked else 1, Style.ACCENT if marked else look["border"]), r) + var px := clampi(int(12 * k * 1.6), 7, 14) + if r.size.y > px * 1.2 and b.title != "": + draw_string(Style.body_bold(), r.position + Vector2(3, px), b.title, HORIZONTAL_ALIGNMENT_LEFT, r.size.x - 6, px, look["ink"]) + var shown := _value_text(b) + if shown != "" and r.size.y > px * 2.4: + draw_string(Style.body(), r.position + Vector2(3, px * 2.2), shown, HORIZONTAL_ALIGNMENT_LEFT, r.size.x - 6, px, look["muted"]) + + +func _value_text(b: SheetBox) -> String: + match b.kind: + SheetKinds.HEADING, SheetKinds.DIVIDER, SheetKinds.PICTURE, SheetKinds.DICE: + return "" + SheetKinds.TEXT: + return Formatter.strip_tags(links.expand(doc, str(b.value if b.value != null else ""))).replace("\n", " ").left(80) + return SheetText._value(doc, b) diff --git a/ui/sheet_preview.gd.uid b/ui/sheet_preview.gd.uid new file mode 100644 index 0000000..7b5c0e4 --- /dev/null +++ b/ui/sheet_preview.gd.uid @@ -0,0 +1 @@ +uid://dpd5vyfacft8k diff --git a/ui/sheet_top_bar.gd b/ui/sheet_top_bar.gd index e5e1173..3369885 100644 --- a/ui/sheet_top_bar.gd +++ b/ui/sheet_top_bar.gd @@ -19,6 +19,8 @@ var undo_button: Button var redo_button: Button var _hint: Label var _tools: HBoxContainer +## "← Spread name" when the sheet was opened from a spread. +var back_button: Button func setup(p_editor: SheetEditor) -> void: @@ -28,6 +30,11 @@ func setup(p_editor: SheetEditor) -> void: h.add_theme_constant_override("separation", 10) add_child(h) h.add_child(MainTopBar.make_brand(func() -> void: ed.m.screens.show(MainScreens.MENU))) + back_button = Style.bar_button("") + back_button.name = "BackToSpread" + back_button.tooltip_text = "Back to the spread this sheet sits on" + back_button.pressed.connect(func() -> void: ed.back_to_spread()) + h.add_child(back_button) var seg := PanelContainer.new() seg.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0.28), 9, [3, 3, 3, 3])) seg.size_flags_vertical = Control.SIZE_SHRINK_CENTER @@ -129,6 +136,8 @@ func sync() -> void: play_button.set_pressed_no_signal(not build) build_button.set_pressed_no_signal(build) name_button.text = "%s ▾" % ed.doc.name + back_button.visible = ed.from_spread != "" + back_button.text = "← %s" % ed.from_spread _hint.text = HINTS[ed.mode] _tools.visible = build palette_button.set_pressed_no_signal(ed.palette_dock.visible) diff --git a/ui/sheets_screen.gd b/ui/sheets_screen.gd index d5796fa..41ea8b9 100644 --- a/ui/sheets_screen.gd +++ b/ui/sheets_screen.gd @@ -11,6 +11,7 @@ var m: Main var store: SheetStore var editor: SheetEditor var list_page: VBoxContainer +var scratch := SCRATCH var _sheet_rows: VBoxContainer var _template_rows: VBoxContainer @@ -22,8 +23,10 @@ func setup(p_main: Main) -> void: if m._saving_enabled: store = SheetStore.new() else: + # One scratch folder per process: test workers run side by side. + scratch = SCRATCH.path_join(str(OS.get_process_id())) _wipe_scratch() - store = SheetStore.new(SCRATCH) + store = SheetStore.new(scratch) var stack := Control.new() add_child(stack) list_page = _make_list_page() @@ -162,10 +165,15 @@ func _empty_note(text: String) -> Label: ## "+ New sheet": asks for a name and a start (blank or a template). -func open_new_sheet(template_id: String = "") -> void: +## `on_made` gets the new sheet instead of opening it (the card palette +## places it on the spread). +func open_new_sheet(template_id: String = "", on_made: Callable = Callable()) -> void: m._add_modal(NewSheetDialog.new(store, template_id, func(name: String, tpl: String) -> void: var doc := store.create(name, tpl) - open_doc(doc))) + if on_made.is_valid(): + on_made.call(doc) + else: + open_doc(doc))) func open_sheet(id: String) -> void: @@ -200,7 +208,7 @@ func _delete(id: String, name: String, templates: bool) -> void: func _wipe_scratch() -> void: for templates: bool in [false, true]: - var dir := SCRATCH.path_join(SheetStore.TEMPLATES if templates else SheetStore.SHEETS) + var dir := scratch.path_join(SheetStore.TEMPLATES if templates else SheetStore.SHEETS) if DirAccess.dir_exists_absolute(dir): for file in DirAccess.get_files_at(dir): DirAccess.remove_absolute(dir.path_join(file)) diff --git a/ui/table_card_kind_rows.gd b/ui/table_card_kind_rows.gd index eab93da..aa4240a 100644 --- a/ui/table_card_kind_rows.gd +++ b/ui/table_card_kind_rows.gd @@ -66,6 +66,21 @@ func make_sheet_row(e: TableEntry, build: bool) -> Control: row.custom_minimum_size = Vector2(0, 36) var v := TableCard.vbox(6) row.add_child(v) + if card.table.sheet_id != "": + # A sheet file: its first tab as a picture; double-click opens it. + var preview := SheetPreview.new() + preview.setup(main.sheet_links, card.table) + v.add_child(preview) + var open := Style.bar_button("Open sheet") + open.add_theme_color_override("font_color", Style.INK) + open.size_flags_horizontal = Control.SIZE_SHRINK_BEGIN + open.pressed.connect(main.sheet_links.open.bind(card.table.id)) + v.add_child(open) + if build: + card.edit_ui.hook_select(row, e.id) + rows.sheet_label = null + rows.register(e, row, null, null, 0) + return row if build: var te := TextEdit.new() FormatMenu.attach(te)