Compare commits

..

2 commits

Author SHA1 Message Date
7ea2bbf3a8 Speed: lazy format menus, one-call dashed threads, kept inspector sections, queued card rebuilds
Profiling showed the delays come from Godot's own calls, not GDScript:
- Right-click format menus are made on the first right-click, not for
  every text field at build time.
- Dashed reference threads draw all their dashes in one call.
- Inspector rebuilds keep the closed sections and only remake open ones.
- Card rows are styled before they join the card.
- A Play/Build switch rebuilds cards in view at once and the rest a few
  per frame (CardRefreshQueue); threads redraw only now and then meanwhile.

Adds tests/perf_actions.gd, a timing tool for everyday actions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:20:31 -06:00
d41a6e40aa Tests: 15 s budget, shared Godot workers; a freed Main cancels its roll
tools/run_tests.sh stops every run at 15 s and lists what was not run.
Suites are nodes run by tests/run_suites.gd, several per Godot process;
TestBase no longer compiles the app (AppTestBase does). Audit: fewer
repeats and less setup; 51 suites in about 12 s (was 45 s).

Fix a crash when a roll was still animating as its Main was freed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 16:19:30 -06:00
79 changed files with 963 additions and 293 deletions

15
CLAUDE.md Normal file
View file

@ -0,0 +1,15 @@
# TableTarot (folder and repo are still named TableTower)
How to work on it: `docs/DESIGN.md` §5. Module map: `docs/ARCHITECTURE.md`.
## Test time budget: always follow
- Run tests only through `tools/run_tests.sh [filter]`. It stops every run at **15 seconds**.
- Only the user changes `BUDGET_SECS`. If the tests can't reasonably fit, ask them, with timings.
- Don't get around it: no looping over suites, no several filtered runs to cover a full run,
no background or repeated runs.
- While working, run the suites for the area you changed, by filter. Do one full run at the end.
- `NOT RUN` means not tested. Say which suites were not run; never report them as passing.
- A new test must fit. Prefer adding to an existing suite; a new app suite costs about half a second to start.
No real waiting: the runner uses simulated time (`--fixed-fps 60`).
- A suite that loads its own board calls `start_main(false)`: building the demo is slow.
- Suites extend `TestBase` (no UI) or, only if they need the app, `AppTestBase`.

View file

@ -156,7 +156,7 @@ docs/ design document
## Tests
```sh
for t in tests/test_*.gd; do godot --headless --path . -s "res://$t" -- --sample; done
tools/run_tests.sh [name-filter] # stops after 15 seconds
```
## Screenshots from the command line

View file

@ -119,7 +119,7 @@ ui/ main.gd: the app shell (shared fields, _ready, cards, collapse, inpu
template_*, io_menu, collection_switcher, variables_panel, modal_card, rich_text, style
help/ topics.txt: the Help window's text (# Title per topic)
tools/ simulate_board.gd (headless simulator CLI), test_window.sh (background test windows)
tests/ test_*.gd: 27 headless suites
tests/ test_*.gd: 51 headless suites; run_suites (runs them in one process), testbase, app_testbase
templates/ built-in templates · examples/logic_demo.json (original demo board) · assets/fonts (OFL)
```
@ -261,6 +261,14 @@ Each original file keeps one-line delegators, so callers are unchanged.
`InspectorSync.sync_texts` and `TableCardEditing.sync_text` / `text_fields` update them in
place. Timing tool: `tests/perf_typing.gd` (SPREAD=… CARD=…; not in the suite).
## 3i. Modules added 2026-11-25 (speed round 1)
- `ui/card_refresh_queue.gd` `CardRefreshQueue` (`Main.card_refresh`): after a mode switch, rebuilds
cards in view at once and the rest within a time budget per frame; `ensure(tid)` rebuilds a
waiting card now (Inspector.select, focusing a card); `finish()` before layout work
(`MainNavigation._layout_blocks`); `holds_redraw()` lets `BoardView` skip thread redraws while
only off-screen cards change. Tests set `frame_usec` very high (AppTestBase).
- `tests/perf_actions.gd`: times everyday actions on a real spread (see its header).
## 4. Data and storage
- **Collections:** `user://collections/<id>.json`, format_version 2 (`{format_version, id,
name, tables, groups?}`). On Linux that's `~/.local/share/godot/app_userdata/TableTower/`.

View file

@ -1,7 +1,7 @@
# Table Tarot (repo: TableTower) — Status and Plan
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-16 (papercuts + card threads
round hand-tested, merged to `main` and pushed)
**Engine:** Godot 4.7.2 (GDScript) · **Started:** 2026-11-08 · **Last updated:** 2026-11-25 (test time
budget and test audit, branch `test-budget`)
The short page to read at the start of every session. Everything else is read only when needed:
- `docs/ARCHITECTURE.md`: feature summary, file map (§3b lists the 2026-11-10 modules), storage, known gaps.
@ -243,15 +243,39 @@ that works on any theme (solid background, stronger text, thicker borders, no ef
Now rows/cells skip restyling when their look is unchanged, and Earlier reuses its rows: ~240 ms
per roll, flat (most of it is the 2–3 questions, each relighting ~70 ms first). Timing tool:
`tests/perf_roll.gd` (SPREAD=… CARD=…; not in the suite).
- **Test budget and audit: done 2026-11-25** (merged to `main`). 51 suites in ~12 s
(was 45 s). Cut coverage: fewer repeats in `test_roller`, `test_logic_ui` (chain of 321, above
the cap of 300), `test_undo` (320 cards), `test_navigation` (20 rows); the 10,000-action limit
stays in `test_logic` and `test_check_inputs` only, so nothing checks that message in the tray.
App crash fixed: a roll still animating went on after `Main` was freed (`Main._exit_tree`).
- **Sluggish app: round 1 done 2026-11-25** (merged to `main` and pushed with `test-budget`;
not hand-tested). The user first asked to port the heaviest code to C#; profiling showed the time
is in Godot's own calls, not GDScript, so C# was dropped (the user agreed). Fixed: right-click
format menus are made on first right-click (`FormatMenu`); dashed reference threads draw in one
call (`PipeGeometry.dash_segments`); inspector rebuilds keep closed sections (`InspectorList`);
card rows are styled before they join the card; a mode switch rebuilds cards in view at once and
the rest a few per frame (`CardRefreshQueue`; threads redraw only now and then meanwhile).
Windowed timings, Perilous Void (152 cards), before → after: one key 359 → 53 ms, add a result
945 → 178 ms, connect a thread 1,009 → 200 ms, card drag 374 → 53 ms per move, to Build
6.7 s frozen → 0.35 s, then the rest catches up over ~2.6 s while the app keeps running.
Timing tool: `tests/perf_actions.gd` (SPREAD=… STATE_DIR=…; not in the suite). Left: every
thread still redraws when anything moves (~26 ms on Perilous Void); a card rebuild is ~40 ms;
roll animation timing is deliberate (the user: keep it; Skip animations exists).
`board_view.gd` is at 422 lines, over the limit (size audit).
- Known gaps: ARCHITECTURE.md §7.
## 5. Working on it
- **Godot:** `~/apps/Godot_v4.7.2-stable_linux.x86_64`. New `class_name` files need
`godot --headless --path . --import` (the test runner does this).
- **Tests:** `tools/run_tests.sh [filter]`: 51 suites in parallel, ~40 s. One line per suite; a
failing suite prints 8 lines; a compile error shared by many suites prints once. Suites extend
`TestBase` (`tests/testbase.gd`, named so the `test_*.gd` glob skips it): `start_main()`,
`require_sample()`, `_check`, `_eq`, `_frames`, `_wipe` (temp folders), `finish()`.
- **Tests:** `tools/run_tests.sh [filter]`: a hard 15 s budget per run (rules in `CLAUDE.md`).
Six Godot workers (`tests/run_suites.gd`) share the suites, longest first; what doesn't fit is
listed as NOT RUN (exit code 2). A full run takes ~12 s on an idle machine (2026-11-25). One
line per suite; a failing suite prints 8 lines; a compile error shared by many suites prints
once. A suite is a Node with `run()`, ending in `finish()`. It extends `TestBase`
(`tests/testbase.gd`, no UI: `require_sample()`, `_check`, `_eq`, `_frames`, `_wipe`) or
`AppTestBase` (`tests/app_testbase.gd`: `main`, `start_main()`; pass false to start on an
empty spread). The suites' demo spread has tables of 12 rows at most. Suites share a process,
so one that changes static state puts it back (`clean_up()`).
- **Smoke test:** `godot --headless --path . --quit-after 120 -- --sample` (no SCRIPT ERROR; the
"resources still in use at exit" line is normal).
- **Windowed runs/screenshots: always `tools/test_window.sh -- --sample --screenshot=/path.png [flags]`**

64
tests/app_testbase.gd Normal file
View file

@ -0,0 +1,64 @@
class_name AppTestBase
extends TestBase
## For suites that load the app. Call `if not await start_main(): return` first.
## Long demo tables are cut to this many rows: rebuilding them costs up to a
## second per mode switch. test_roller checks the demo's full tables.
const MAX_DEMO_ROWS := 12
var main: Main
## Hook: suites that need a customised Main override this.
func _create_main() -> Main:
return load("res://ui/main.tscn").instantiate()
## The app's demo spread with short tables.
func _short_demo() -> TowerBoard:
var board := SampleBoard.create()
board.id = "fantasy-loot"
board.name = "Fantasy Loot"
for table in board.tables:
if not table.is_ranged() and table.entries.size() > MAX_DEMO_ROWS:
table.entries.resize(MAX_DEMO_ROWS)
return board
func _empty_spread() -> TowerBoard:
var board := TowerBoard.new()
board.id = "fantasy-loot"
board.name = "Fantasy Loot"
return board
## A suite that loads its own board first should pass `with_demo` false: the
## demo's cards take about half a second to build. Guard, then loads the app under root and waits for it. Returns false (after
## aborting) if the guard fails or the app would save.
func start_main(with_demo: bool = true) -> bool:
if not require_sample():
return false
main = _create_main()
if main.data == null:
main.data = _short_demo() if with_demo else _empty_spread()
root.add_child(main)
main.card_refresh.frame_usec = 1 << 40
await _frames(5)
if main._saving_enabled:
abort("Saving is enabled; refusing to run.")
return false
return true
## Back to the default theme, window and shared UI state.
func clean_up() -> void:
if main != null:
main.queue_free()
ThemeStore.DIR = "user://themes/"
ThemeStore.carry_board = null
ThemeStore.current = {}
ThemeAssets._cache.clear()
Spellcheck.ignored.clear()
TestBoardDialog.last = {}
RulesView.fallback_plain = true
SpreadLinks.loader = Callable()

View file

@ -0,0 +1 @@
uid://cai0ym8kthl6s

177
tests/perf_actions.gd Normal file
View file

@ -0,0 +1,177 @@
extends AppTestBase
## Times everyday actions on one spread: rolling, typing, adding a result,
## connecting a thread, dragging a card, switching modes and saving. Each line
## is the median of a few runs: the call itself, then the slowest of the next
## four frames. Not part of the suite (the name doesn't start with test_). Run:
## SPREAD=/path/to/spread.json STATE_DIR=/folder/holding/a/copy/of/state/ \
## SUITES=perf_actions godot --headless --path . -s res://tests/run_suites.gd -- --sample
## STATE_DIR must be a copy: the tool saves into it.
const RUNS := 5
const FRAMES_AFTER := 4
var card_id := ""
func run() -> void:
if not await start_main(false):
return
DisplayServer.window_set_vsync_mode(DisplayServer.VSYNC_DISABLED)
Engine.max_fps = 0
main.card_refresh.frame_usec = CardRefreshQueue.FRAME_USEC
main.prompt_hook = func(req: Dictionary) -> Variant:
return 0 if not (req.get("options", []) as Array).is_empty() else req.get("default", 1)
main.data.load_json(FileAccess.get_file_as_string(OS.get_environment("SPREAD")))
main._rebuild_cards()
await _frames(20)
card_id = _longest_card()
var table := main.data.get_table(card_id)
print("PERF spread %s: %d cards, %d built, %d nodes; timing card %s (%d results)" % [main.data.name,
main.data.tables.size(), main.cards.size(), Performance.get_monitor(Performance.OBJECT_NODE_COUNT),
table.name, table.entries.size()])
await _time("idle frame", func() -> void: pass)
await _play_timings()
await _build_timings()
_save_timings()
finish()
## The expanded card on the board with the most results.
func _longest_card() -> String:
var best := ""
var most := 0
for tid: String in main.cards:
var table := main.data.get_table(tid)
if table.kind == RollTable.KIND_ROLL and not table.has_columns() and table.entries.size() > most:
best = tid
most = table.entries.size()
return best
func _play_timings() -> void:
await _time("fast roll", func() -> void: await main.rolling.start_roll(card_id, true))
var started := Time.get_ticks_usec()
await main.rolling.start_roll(card_id)
print("PERF animated roll, whole: %.0f ms, %d steps" % [_ms(started), (main.current["all"] as Array).size()])
_part(" part: relight all cards", main._refresh_lit)
_part(" part: live cards", main.refresh_live)
_part(" part: results tray", main.tray.render)
_part(" part: board changed", main._board_changed)
await _time_switch("to Build", Main.Mode.BUILD)
func _build_timings() -> void:
var table := main.data.get_table(card_id)
table.collapsed = false
main.select_card(card_id)
await _frames(20)
main.card_for(card_id).rebuild()
await _frames(5)
var first_id := table.entries[0].id
await _time("type one key", func() -> void:
var edit: LineEdit = main.card_for(card_id).edit_ui.text_fields[first_id]
edit.grab_focus()
edit.text += "x"
edit.text_changed.emit(edit.text))
await _time("undo step after typing", func() -> void: main.undo_redo._commit_edits())
main.get_viewport().gui_release_focus()
await _frames(5)
await _time("add a result", func() -> void: main.add_entry(card_id))
await _time("connect a thread", _connect_thread)
await _time("drag a card (one move)", func() -> void: main.card_for(card_id).position += Vector2(7, 3))
await _time("select another card", _select_next)
await _time("add a card", func() -> void: main.editing.add_table())
_part(" part: rebuild that card", main.card_for(card_id).rebuild)
_part(" part: rebuild inspector", main.inspector.rebuild)
_part(" part: board changed", main._board_changed)
_part(" part: undo snapshot", func() -> void: EditHistory.capture(main.data))
_part(" part: inspector signature", func() -> void: main.inspector._signature())
_part(" part: board signature (every frame)", main.board._signature)
await _time("redraw all threads", func() -> void: main.board.pipes.queue_redraw())
await _time_switch("to Play", Main.Mode.PLAY)
func _save_timings() -> void:
_part(" part: spread to JSON", func() -> void: main.data.to_json())
var dir := OS.get_environment("STATE_DIR")
if dir == "":
return
var store := StateStore.new(dir)
store.get_history()
_part("save state after a roll (history file)", func() -> void:
store.add_history({"collection": main.data.id, "root": card_id, "root_name": "x", "time": 1.0, "steps": main.current["all"], "chain_vars": {}})
store.save())
## A mode switch: the call, the slowest frame until every card is rebuilt, and
## how long that takes.
func _time_switch(label: String, mode: Main.Mode) -> void:
var started := Time.get_ticks_usec()
main.set_mode(mode)
var call_ms := _ms(started)
var frames: Array[float] = []
while not main.card_refresh.is_idle() or frames.size() < FRAMES_AFTER:
var frame_started := Time.get_ticks_usec()
await process_frame
frames.append(_ms(frame_started))
print("PERF %s: call %.1f ms, slowest frame %.1f, median frame %.1f, all cards ready after %.0f ms (%d frames)" % [label,
call_ms, frames.max(), _median(frames.duplicate()), _ms(started), frames.size()])
var _thread_row := 0
func _connect_thread() -> void:
var table := main.data.get_table(card_id)
for target: RollTable in main.data.tables:
var entry := table.entries[_thread_row % table.entries.size()]
if target.kind != RollTable.KIND_VARIABLE and target.id != card_id and main.card_for(target.id) and not entry.pipes.has(target.id):
main.editing._card_under_mouse_override = main.card_for(target.id)
main.editing.start_link(card_id, entry.id)
main.editing.finish_link()
main.editing._card_under_mouse_override = null
_thread_row += 1
return
_thread_row += 1
var _pick := 0
func _select_next() -> void:
var ids: Array = main.cards.keys()
main.select_card(ids[_pick % ids.size()])
_pick += 1
## Runs an action a few times and prints the median call time and the median
## of the slowest frame after it.
func _time(label: String, action: Callable) -> void:
var calls: Array[float] = []
var slowest: Array[float] = []
for i in RUNS:
var started := Time.get_ticks_usec()
await action.call()
calls.append(_ms(started))
var worst := 0.0
for frame in FRAMES_AFTER:
started = Time.get_ticks_usec()
await process_frame
worst = maxf(worst, _ms(started))
slowest.append(worst)
await _frames(3)
print("PERF %s: call %.1f ms, slowest frame after %.1f ms" % [label, _median(calls), _median(slowest)])
func _part(label: String, action: Callable) -> void:
var times: Array[float] = []
for i in RUNS:
var started := Time.get_ticks_usec()
action.call()
times.append(_ms(started))
print("PERF %s: %.1f ms" % [label, _median(times)])
func _ms(started: int) -> float:
return (Time.get_ticks_usec() - started) / 1000.0
func _median(values: Array[float]) -> float:
values.sort()
return values[values.size() / 2]

View file

@ -0,0 +1 @@
uid://clf7kk0xpqpom

View file

@ -1,13 +1,13 @@
extends TestBase
extends AppTestBase
## Times rolling one card on a big spread: the roll logic alone, then the
## whole app roll (fast), then the parts of the screen update after it.
## Not part of the suite (the name doesn't start with test_). Run:
## SPREAD=/path/to/spread.json CARD=start \
## godot --headless --path . -s res://tests/perf_roll.gd -- --sample
## SUITES=perf_roll godot --headless --path . -s res://tests/run_suites.gd -- --sample
## (--sample keeps the app from reading or writing saved spreads.)
func _init() -> void:
func run() -> void:
if not await start_main():
return
var card_id := OS.get_environment("CARD") if OS.get_environment("CARD") != "" else "start"

View file

@ -1,13 +1,13 @@
extends TestBase
extends AppTestBase
## Times typing on a long card in Build mode: one key in a result's field on
## the card, in the card's name, and in the inspector's text field. Each number
## is the frame after the key (an idle frame is ~7 ms headless). Not part of
## the suite (the name doesn't start with test_). Run:
## SPREAD=/path/to/spread.json CARD=card_id \
## godot --headless --path . -s res://tests/perf_typing.gd -- --sample
## SUITES=perf_typing godot --headless --path . -s res://tests/run_suites.gd -- --sample
func _init() -> void:
func run() -> void:
if not await start_main():
return
main.data.load_json(FileAccess.get_file_as_string(OS.get_environment("SPREAD")))

70
tests/run_suites.gd Normal file
View file

@ -0,0 +1,70 @@
extends SceneTree
## Runs suites one after another in this process. SUITES (environment) lists
## them in order; workers started with the same CLAIMS folder share the list,
## each suite going to whichever worker claims it first.
## Output per suite: "SUITE name", the suite's output, then
## "DONE name <milliseconds> <failures>". tools/run_tests.sh reads it.
## After a script error, a suite that awaited the crashed function never ends:
## it is abandoned this many frames later.
const FRAMES_AFTER_ERROR := 30
## Notices script errors, which don't reach the suite's own checks.
class ErrorWatch extends Logger:
var script_errors := 0
func _log_error(_function: String, _file: String, _line: int, _code: String, _rationale: String,
_editor_notify: bool, error_type: int, _backtraces: Array[ScriptBacktrace]) -> void:
if error_type == ERROR_TYPE_SCRIPT:
script_errors += 1
var _errors := ErrorWatch.new()
var _original_children: Array[Node] = []
func _init() -> void:
OS.add_logger(_errors)
await process_frame
_original_children = root.get_children()
var claims := OS.get_environment("CLAIMS")
var failed := false
for suite in OS.get_environment("SUITES").split(",", false):
# Making a folder is atomic, so only one worker gets each suite.
if claims == "" or DirAccess.make_dir_absolute(claims.path_join(suite)) == OK:
failed = await _run_suite(suite) > 0 or failed
quit(1 if failed else 0)
func _run_suite(suite_name: String) -> int:
print("SUITE ", suite_name)
var started := Time.get_ticks_msec()
_errors.script_errors = 0
var failures := 1
var script: GDScript = load("res://tests/%s.gd" % suite_name)
if script != null and script.can_instantiate():
var suite: TestBase = script.new()
root.add_child(suite)
suite.run()
var frames_left := FRAMES_AFTER_ERROR
while not suite.done and frames_left > 0:
await process_frame
if _errors.script_errors > 0:
frames_left -= 1
failures = suite.failures + _errors.script_errors
suite.clean_up()
await _reset_tree()
print("DONE %s %d %d" % [suite_name, Time.get_ticks_msec() - started, failures])
return failures
## Frees whatever the suite left under root and resets the window.
func _reset_tree() -> void:
paused = false
Engine.time_scale = 1.0
root.gui_release_focus()
for child in root.get_children():
if child not in _original_children:
child.queue_free()
await process_frame

1
tests/run_suites.gd.uid Normal file
View file

@ -0,0 +1 @@
uid://07ee6hcw84gf

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## The shared action menus (Actions): what the card, thread, group and spread
## menus offer in Play and Build, the ☰ menu, running an action, and placing
## a new card where the spread was right-clicked.
## Run: godot --headless --path . -s res://tests/test_actions.gd -- --sample
## Run: tools/run_tests.sh actions
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_lists()
@ -75,8 +75,6 @@ func _test_popup_and_run() -> void:
## The Delete key: asks first (by default), deletes the selection as one undo
## step, and skips the question when "Ask before deleting" is off.
func _test_delete_key() -> void:
main.set_mode(Main.Mode.BUILD)
await _frames()
main.clear_selection()
main.editing.toggle_selected("loot")
main.editing.toggle_selected("names")
@ -97,4 +95,3 @@ func _test_delete_key() -> void:
_check(main.data.get_table("loot") != null and main.data.get_table("names") != null, "one undo brings both back")
DeleteKey.set_asks(main, true)
main.clear_selection()
main.set_mode(Main.Mode.PLAY)

View file

@ -2,7 +2,7 @@ extends TestBase
## BoardTester: static checks, simulated runs, isolation from the caller's
## variables and decks, batches, start-table detection, and the Test board
## dialog driven through its methods.
## Run: godot --headless --path . -s res://tests/test_board_tester.gd
## Run: tools/run_tests.sh board_tester
@ -16,7 +16,7 @@ class FakeMain extends Control:
focused.append([table_id, entry_id])
func _init() -> void:
func run() -> void:
var b := _board()
# ----- Static checks -----

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## The Book: pages saved from results, linked results following a page's edits,
## dropping a page onto a result or a card, unlinking, saving and undo.
## Run: godot --headless --path . -s res://tests/test_book.gd -- --sample
## Run: tools/run_tests.sh book
func _init() -> void:
func run() -> void:
if not await start_main():
return
main.set_mode(Main.Mode.BUILD)

View file

@ -3,10 +3,10 @@ extends TestBase
## phrase (column_join), "roll twice and combine" rows (TableEntry.repeat),
## saving results into a list value, and a pick with one option answering
## itself.
## Run: godot --headless --path . -s res://tests/test_book_collect.gd -- --sample
## Run: tools/run_tests.sh book_collect
func _init() -> void:
func run() -> void:
await _test_join_and_repeat()
await _test_repeat_reroll()
await _test_repeat_one_column()

View file

@ -1,10 +1,10 @@
extends TestBase
## Book-table features in the engine: scale values, cards with columns, and
## threads that roll with other dice or roll again on some results.
## Run: godot --headless --path . -s res://tests/test_book_tables.gd -- --sample
## Run: tools/run_tests.sh book_tables
func _init() -> void:
func run() -> void:
_test_scales()
_test_scale_effects()
await _test_columns_row()

View file

@ -2,10 +2,10 @@ extends TestBase
## Headless checks for Builder (docs/PLAIN.md §2): effect and condition models
## that round-trip exactly with the stored text, the cases that don't fit a
## builder (ok: false), and known_values().
## Run: godot --headless --path . -s res://tests/test_builder.gd
## Run: tools/run_tests.sh builder
func _init() -> void:
func run() -> void:
_test_parse_effect()
_test_effect_round_trips()
_test_effect_not_ok()

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## Resizable cards: the grip's corner hit area, a dragged width and list
## height (the list scrolls), saving them, and double-click back to automatic.
## Run: godot --headless --path . -s res://tests/test_card_size.gd -- --sample
## Run: tools/run_tests.sh card_size
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_resize()
@ -94,6 +94,9 @@ func _test_play_drag_selects() -> void:
## A long card opened with "show all" has "▲ Show less" to fold it up again.
func _test_show_less() -> void:
var t := main.data.get_table("trinkets")
# The suites' demo has short tables: make this one long again.
for entry in SampleBoard.create().get_table("trinkets").entries.slice(t.entries.size()):
t.entries.append(entry)
if not t.collapsed:
main.toggle_collapse("trinkets")
await _frames(2)

View file

@ -2,10 +2,10 @@ extends TestBase
## Card threads (CardThreads, LOGIC.md §3g): threads off a card's bottom edge
## that run after the card's result and that result's own threads, whatever
## the result was ("Always"), or only when no result thread ran ("Otherwise").
## Run: godot --headless --path . -s res://tests/test_card_threads.gd
## Run: tools/run_tests.sh card_threads
func _init() -> void:
func run() -> void:
_test_always_runs_after()
_test_otherwise()
_test_card_condition()

View file

@ -2,10 +2,10 @@ extends TestBase
## Headless checks for the new engine features of docs/PLAIN.md §3–§4: check
## cards, card inputs (pipe "with" values), collections, "nat" on roll tables,
## the why facts they record, the file format and the lint.
## Run: godot --headless --path . -s res://tests/test_check_inputs.gd
## Run: tools/run_tests.sh check_inputs
func _init() -> void:
func run() -> void:
_test_check_success_failure()
_test_check_le_and_dice()
_test_check_errors()

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## The choice pop-up's minimize pill and hover preview, and TablePreview.
## Run: godot --headless --path . -s res://tests/test_choice_dialog.gd -- --sample
## Run: tools/run_tests.sh choice_dialog
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
# Headless windows are tiny; give the app a real size.
main.set_anchors_preset(Control.PRESET_TOP_LEFT)

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## Help's demo spreads: every demo builds and rolls cleanly, Help links to
## them, and opening one shows it unsaved with a way back.
## Run: godot --headless --path . -s res://tests/test_demos.gd -- --sample
## Run: tools/run_tests.sh demos
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_builds()

View file

@ -3,10 +3,10 @@ extends TestBase
## every effect op, the condition forms, dice, dynamic options, pipes, check
## cards and why facts, with labels from variable cards, collections and card
## inputs, and the fallbacks to the original text.
## Run: godot --headless --path . -s res://tests/test_describe.gd
## Run: tools/run_tests.sh describe
func _init() -> void:
func run() -> void:
_test_labels()
_test_effects()
_test_conditions()

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## Build mode: dragging a result's handle reorders the card's results. Ranged
## cards keep their ranges in place; the move is one undo step.
## Run: godot --headless --path . -s res://tests/test_entry_drag.gd -- --sample
## Run: tools/run_tests.sh entry_drag
func _init() -> void:
func run() -> void:
if not await start_main():
return
main.set_mode(Main.Mode.BUILD)

View file

@ -1,9 +1,9 @@
extends TestBase
## if(condition, then, else) in expressions, and the refused inline ternary.
## Run: godot --headless --path . -s res://tests/test_expr_if.gd -- --sample
## Run: tools/run_tests.sh expr_if
func _init() -> void:
func run() -> void:
_value("if(1 > 2, 10, 20)", 20)
_value("if(3 > 2, 10, 20)", 10)
_value("if(1 = 1, \"yes\", \"no\")", "yes")

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## Fast roll (Shift-click): the whole result shows at once, with no animation.
## Run: godot --headless --path . -s res://tests/test_fast_roll.gd -- --sample
## Run: tools/run_tests.sh fast_roll
## (--sample keeps the app from reading or writing saved collections.)
func _init() -> void:
func run() -> void:
if not await start_main():
return
main.rng.seed = 7

View file

@ -1,12 +1,12 @@
extends TestBase
extends AppTestBase
## Group marks: a member card's top-right corner shows its group's colour (its
## own, else the theme's GROUP); a card that only lies inside the frame has
## none. The colour is saved and undoable.
## Run: godot --headless --path . -s res://tests/test_group_marks.gd -- --sample
## Run: tools/run_tests.sh group_marks
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.data.load_dict({"format_version": 2, "id": "marks-test", "name": "Marks", "tables": [
{"id": "a", "name": "Alpha", "x": 40, "y": 60, "entries": [{"id": "e1", "text": "One"}]},

View file

@ -1,17 +1,17 @@
extends TestBase
extends AppTestBase
## Group cards: the model and file format, membership, and in the app the
## frame, collapsing (hidden members, re-routed pipes, lit results, choice
## pop-ups), moving, dropping cards in and out, ungroup and delete.
## Run: godot --headless --path . -s res://tests/test_groups.gd -- --sample
## Run: tools/run_tests.sh groups
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_model()
_test_json()
_test_import()
if not await start_main():
if not await start_main(false):
return
main.rng.seed = 5
await _load(_board_dict())

View file

@ -1,15 +1,15 @@
extends TestBase
extends AppTestBase
## The Build inspector (docs/PLAIN.md §6): selection, the effects and
## condition builders, Otherwise, pipe inputs, check fields and the modifier
## picker, collection members, options source, the value picker, the
## Plain/Text switch, undo, and dirty/save.
## Run: godot --headless --path . -s res://tests/test_inspector.gd -- --sample
## Run: tools/run_tests.sh inspector
var insp: Inspector
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)

View file

@ -1,15 +1,15 @@
extends TestBase
extends AppTestBase
## The inspector's card page as one list (InspectorList): a section for the
## card and one per result; selecting on the spread opens only that section;
## sections opened by hand stay open and edits go to the section clicked in;
## a result's weight, range and position (InspectorRange).
## Run: godot --headless --path . -s res://tests/test_inspector_list.gd -- --sample
## Run: tools/run_tests.sh inspector_list
var insp: Inspector
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
@ -27,8 +27,10 @@ func _init() -> void:
await _frames(4)
await _test_sections()
await _test_open_by_hand()
await _test_closed_sections_stay()
await _test_position_and_weight()
await _test_lore_tab()
await _test_mode_switch_queue()
finish()
@ -78,6 +80,28 @@ func _test_open_by_hand() -> void:
_eq(_open_keys(), ["d"], "a click on the spread closes the rest again")
## A rebuild keeps closed sections (and refreshes their titles) but not open ones.
func _test_closed_sections_stay() -> void:
main.select_result("work", "b")
await _frames()
var closed: Control = insp.section_boxes["c"]
var open: Control = insp.section_boxes["b"]
main.add_entry("work")
await _frames()
var added := _t().entries[-1].id
_eq(insp.section_parts.keys(), ["card", "a", "b", "c", "d", added], "a new result gets its section, last")
_check(insp.section_boxes["c"] == closed and insp.section_boxes["b"] != open, "closed sections stay, the open one is built again")
_eq(insp.section_list.get_children(), insp.section_boxes.values(), "the sections are in the results' order, with none left over")
_t().find_entry("c").text = "Joan"
insp.rebuild()
_eq((insp.section_parts["c"]["title"] as Label).text, "Joan", "a kept section shows its new title")
_check(insp.section_boxes["c"] == closed, "and is the same one")
main.delete_entry("work", added)
await _frames()
_eq(insp.section_list.get_children(), insp.section_boxes.values(), "a deleted result's section goes")
_t().find_entry("c").text = "Joe"
func _test_position_and_weight() -> void:
var t := _t()
InspectorRange.set_weight(insp, t, t.find_entry("a"), 10)
@ -104,3 +128,19 @@ func _test_lore_tab() -> void:
main.book.toggle()
main.set_mode(Main.Mode.BUILD)
_check(insp.visible, "back in Build the inspector shows")
## A mode switch rebuilds the cards in view now and the rest afterwards.
func _test_mode_switch_queue() -> void:
main.set_mode(Main.Mode.PLAY)
var far_card := main.editing.add_table(RollTable.KIND_ROLL, "", Vector2(9000, 9000))
await _frames()
main.set_mode(Main.Mode.BUILD)
_check(main.card_refresh.is_waiting(far_card.id) and not main.card_refresh.is_waiting("work"), "only the card out of view waits")
main.select_card(far_card.id)
_check(not main.card_refresh.is_waiting(far_card.id), "selecting a waiting card rebuilds it at once")
main.set_mode(Main.Mode.PLAY)
main.set_mode(Main.Mode.BUILD)
await _frames()
_check(not main.card_refresh.is_waiting(far_card.id), "a waiting card is rebuilt soon after")
_eq(main.card_for(far_card.id).edit_ui.text_fields.size(), far_card.entries.size(), "with Build's text fields")

View file

@ -1,10 +1,10 @@
extends TestBase
## Headless checks for the roller working with RollContext, TextExpander,
## pipes that save variables, card decks and StateStore.
## Run: godot --headless --path . -s res://tests/test_integration.gd
## Run: tools/run_tests.sh integration
func _init() -> void:
func run() -> void:
_test_refs_and_vars()
_test_pipe_save()
_test_persistent_across_rolls()

View file

@ -1,11 +1,11 @@
extends TestBase
## Headless checks for the import/export converters.
## Run: godot --headless --path . -s res://tests/test_io.gd
## Run: tools/run_tests.sh io
const TMP_DIR := "user://test_io_tmp/"
func _init() -> void:
func run() -> void:
DirAccess.make_dir_recursive_absolute(TMP_DIR)
_test_json()
_test_canvas()

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## List view: rows for every card with thread counts and Roll, search, new
## groups, and drag-and-drop moves (reorder, into a group, group in group).
## Run: godot --headless --path . -s res://tests/test_list_view.gd -- --sample
## Run: tools/run_tests.sh list_view
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_rows()

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## List values: the "Add to list" change row (picking a list, the result's own
## text as the item, a new value made there is a list), and "Allow repeats".
## Run: godot --headless --path . -s res://tests/test_lists.gd -- --sample
## Run: tools/run_tests.sh lists
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.set_mode(Main.Mode.BUILD)
main.data.load_dict({"format_version": 2, "id": "list-test", "name": "List test", "tables": [

View file

@ -2,10 +2,10 @@ extends TestBase
## Headless checks for logic cards (docs/LOGIC.md): expressions, effects,
## variables, choice / loop / variable / sheet cards, the action limit, long
## chains and the file format.
## Run: godot --headless --path . -s res://tests/test_logic.gd
## Run: tools/run_tests.sh logic
func _init() -> void:
func run() -> void:
_test_expressions()
_test_effects()
_test_variables()

View file

@ -1,15 +1,15 @@
extends TestBase
extends AppTestBase
## Logic cards in the app: the choice pop-up, progress while it's open,
## cancelling, a new roll replacing an open question, live variable and sheet
## cards, the long-chain tray and the Build-mode settings rules.
## Run: godot --headless --path . -s res://tests/test_logic_ui.gd -- --sample
## Run: tools/run_tests.sh logic_ui
## (--sample keeps the app from reading or writing saved collections.)
const DEMO := "res://examples/logic_demo.json"
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.rng.seed = 11
@ -26,7 +26,6 @@ func _init() -> void:
_test_settings_rules()
_test_add_kinds()
await _test_long_chain()
await _test_action_limit()
finish()
@ -416,13 +415,13 @@ func _chips() -> int:
func _test_long_chain() -> void:
_long_chain(3000)
_long_chain(320)
await process_frame
var t0 := Time.get_ticks_msec()
main.start_roll("long_start")
var ms := Time.get_ticks_msec() - t0
var all: Array = main.current["all"]
_eq(all.size(), 3001, "a 3,001-step chain")
_eq(all.size(), 321, "a 321-step chain")
_check(main.current.get("done", false), "a long chain shows at once, without animating")
_check(main.is_entry_lit("long_link", "e1"), "its path is lit")
_eq(_chips(), ResultTray.TAIL, "the tray shows only the last %d steps" % ResultTray.TAIL)
@ -430,26 +429,17 @@ func _test_long_chain() -> void:
for c in main.tray._flow.get_children():
if c is HBoxContainer and c.get_child(0) is Button:
toggle = c.get_child(0)
_check(toggle != null and toggle.text == "+2,989 earlier steps", "a +N earlier steps toggle: %s" % (toggle.text if toggle else "none"))
_check(toggle != null and toggle.text == "+309 earlier steps", "a +N earlier steps toggle: %s" % (toggle.text if toggle else "none"))
if toggle:
toggle.pressed.emit()
_eq(_chips(), ResultTray.MAX_EXPANDED, "expanding shows more steps (capped)")
_check(ms < 4000, "lighting 3,000 steps is quick (%d ms)" % ms)
print(" (3,001-step roll, lit and shown in %d ms)" % ms)
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 3001 * 40, "copy text indents are capped")
_check(ms < 4000, "lighting 320 steps is quick (%d ms)" % ms)
print(" (321-step roll, lit and shown in %d ms)" % ms)
_check(main.rolling.result_text(all, ResultTray.COPY_TEXT).length() < 321 * 40, "copy text indents are capped")
var line := EarlierRolls.earlier_line({"root_name": "x", "steps": all})
_check(line.length() < 2000, "Earlier rows show the last few steps of a long chain")
await process_frame
func _test_action_limit() -> void:
_long_chain(20000)
await process_frame
main.start_roll("long_start")
_check(str(main.current.get("halted", "")).begins_with("Stopped after 10,000"), "the action limit is reported: %s" % str(main.current.get("halted", "")))
_check(main.tray._halt.visible and main.tray._halt_label.text.contains("10,000"), "the tray shows the limit clearly")
await process_frame
# ---------------------------------------------------------------- checks

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## The phone layout (List fills the screen, Spread/List swap, slim bar and
## tray, View/Help/Play-Build in ☰) and touch gestures (pinch zoom, a long
## press timing out into a right-click).
## Run: godot --headless --path . -s res://tests/test_mobile.gd -- --sample
## Run: tools/run_tests.sh mobile
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_layout()

View file

@ -1,9 +1,9 @@
extends TestBase
## Headless checks for dice, weights, pipe options, card mode and JSON.
## Run: godot --headless --path . -s res://tests/test_model.gd
## Run: tools/run_tests.sh model
func _init() -> void:
func run() -> void:
_test_dice()
_test_weights()
_test_ranged_dice()

View file

@ -3,10 +3,10 @@ extends TestBase
## RollRange): results past the dice, using the nearest result past the ends,
## chances with a modifier, the file format, plain words and the Why line,
## and the ModifierEditor's plain forms.
## Run: godot --headless --path . -s res://tests/test_modifier.gd
## Run: tools/run_tests.sh modifier
func _init() -> void:
func run() -> void:
_test_model()
_test_chances()
_test_rolls()

View file

@ -1,16 +1,16 @@
extends TestBase
extends AppTestBase
## Navigation on big boards: search (BoardSearch and the panel), focus_table,
## the minimap, Pack collapsed groups (and making room when a packed group
## expands), lazily built cards for collapsed groups, and the resizable tray
## and inspector.
## Run: godot --headless --path . -s res://tests/test_navigation.gd -- --sample
## Run: tools/run_tests.sh navigation
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_fold_and_layout()
if not await start_main():
if not await start_main(false):
return
# The headless window is tiny; give the app a real screen's worth of room.
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
@ -339,17 +339,17 @@ func _test_panels() -> void:
_check(foot != null and side != null, "the tray and the inspector each have a drag handle")
if foot == null or side == null:
return
# Sixty long Earlier rows scroll inside the tray instead of growing it.
# Twenty long Earlier rows scroll inside the tray instead of growing it.
var steps: Array = []
for k in 8:
steps.append({"text": "A long step with plenty of words in it, number %d" % k})
main.history.clear()
for i in 60:
for i in 20:
main.history.append({"root_name": "Start", "time": 0.0, "steps": steps})
main.tray.set_side(ResultTray.Side.EARLIER)
main.tray.render()
await _frames()
_check(absf(main.tray.size.y - foot.size_px) < 2.0, "the tray keeps its height with 60 earlier rolls (%.0f vs %.0f)" % [main.tray.size.y, foot.size_px])
_check(absf(main.tray.size.y - foot.size_px) < 2.0, "the tray keeps its height with 20 earlier rolls (%.0f vs %.0f)" % [main.tray.size.y, foot.size_px])
_check(main.tray._earlier.scroll.get_v_scroll_bar().max_value > main.tray._earlier.scroll.size.y, "Earlier scrolls")
foot.set_size_px(400.0)
await _frames()

View file

@ -4,10 +4,10 @@ extends TestBase
## docs/LOGIC.md §2a: candidates, labels and values, fixed extras, Random,
## "No options available", the file format, lint, a small "raise a skill you
## already have" board and the choice pop-up's rendering.
## Run: godot --headless --path . -s res://tests/test_options.gd -- --sample
## Run: tools/run_tests.sh options
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_prefix_options()
@ -527,6 +527,7 @@ func _test_settings() -> void:
func _test_card() -> void:
var main: Main = load("res://ui/main.tscn").instantiate()
main.data = TowerBoard.new()
root.add_child(main)
for i in 5:
await process_frame

View file

@ -1,9 +1,9 @@
extends TestBase
extends AppTestBase
## The display side of Plain Build (docs/PLAIN.md §6): plain chips and lines
## on cards and their text-mode twins, the switch refreshing them, pipe
## labels, check / collection / inputs visuals, "Why this?" sentences and the
## tray's button, and Build-mode row selection.
## Run: godot --headless --path . -s res://tests/test_plain_display.gd -- --sample
## Run: tools/run_tests.sh plain_display
##
## Main here is a small subclass with the hooks the Build inspector adds
## (rules_plain(), rules_view_changed, select_result(), select_card()), so the
@ -53,12 +53,12 @@ const BOARD := {
]}
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_why_sentences()
_test_rules_view_helpers()
if not await start_main():
if not await start_main(false):
return
main.rng.seed = 7
main.data.load_json(JSON.stringify(BOARD))

View file

@ -2,10 +2,10 @@ extends TestBase
## Headless checks for ranged cards edited by weight or by range (RangeWeights):
## turning gaps into empty results, laying ranges out from weights, the total
## warning, auto-sort, the file format, and an empty card switching to Ranged.
## Run: godot --headless --path . -s res://tests/test_range_weights.gd
## Run: tools/run_tests.sh range_weights
func _init() -> void:
func run() -> void:
_test_to_weights()
_test_total_warning()
_test_auto_sort()

View file

@ -2,10 +2,10 @@ extends TestBase
## Roll features in the engine: combining a thread's repeated rolls (add,
## highest, lowest, choose), saving the combined value, and only the kept roll
## following its threads.
## Run: godot --headless --path . -s res://tests/test_roll_features.gd
## Run: tools/run_tests.sh roll_features
func _init() -> void:
func run() -> void:
_test_combine()
_test_no_repeats()
await _test_choose()

View file

@ -1,9 +1,9 @@
extends TestBase
## Headless checks for the data model and roller.
## Run: godot --headless --path . -s res://tests/test_roller.gd
## Run: tools/run_tests.sh roller
func _init() -> void:
func run() -> void:
var board := SampleBoard.create()
var rng := RandomNumberGenerator.new()
rng.seed = 12345
@ -27,13 +27,13 @@ func _init() -> void:
# Range weighting: 01–30 should come up about 30% of the time.
var counts := {}
for i in 20000:
for i in 4000:
var n := Roller.roll(board, "wilderness", rng)
var text: String = (n["entry"] as TableEntry).text
counts[text] = counts.get(text, 0) + 1
var share := float(counts.get("Travelers on the road", 0)) / 20000.0
var share := float(counts.get("Travelers on the road", 0)) / 4000.0
_check(absf(share - 0.30) < 0.02, "01–30 rolls about 30%% of the time (got %.3f)" % share)
var rare := float(counts.get("An odd find", 0)) / 20000.0
var rare := float(counts.get("An odd find", 0)) / 4000.0
_check(absf(rare - 0.05) < 0.01, "96–00 rolls about 5%% of the time (got %.3f)" % rare)
# Chains follow pipes.
@ -66,16 +66,6 @@ func _init() -> void:
stops += 1
_check(stops > 50 and stops < 150, "rolls into a gap stop with a message (%d/200)" % stops)
# A self-pipe stops at the action limit (docs/LOGIC.md §7) instead of looping forever.
var loop := RollTable.new("loop", "Repeat")
var again := TableEntry.new("e1", "Again")
again.pipes.append("loop")
loop.entries.append(again)
var b3 := TowerBoard.new()
b3.tables.append(loop)
var steps := Roller.flatten(Roller.roll(b3, "loop", rng), [])
_check(steps.size() == Roller.MAX_ACTIONS + 1 and str(steps[steps.size() - 1]["text"]) == Roller.limit_text(), "self-thread stops at the action limit (%d steps)" % steps.size())
# JSON round trip keeps everything.
var copy := TowerBoard.new()
_check(copy.load_json(board.to_json()), "spread JSON loads back")

View file

@ -3,10 +3,10 @@ extends TestBase
## and §3b): when / otherwise selection, the snapshot rule, expression errors,
## first-match routing, "No case matched", the file format, lint_pipes() and a
## small board where a router replaces a chain-variable workaround.
## Run: godot --headless --path . -s res://tests/test_router.gd
## Run: tools/run_tests.sh router
func _init() -> void:
func run() -> void:
_test_when_otherwise()
_test_snapshot()
_test_errors()

View file

@ -1,11 +1,11 @@
extends TestBase
## Headless checks for the app-shell logic: table settings, collections, import.
## Run: godot --headless --path . -s res://tests/test_shell.gd
## Run: tools/run_tests.sh shell
const ROOT := "user://test_shell_tmp"
func _init() -> void:
func run() -> void:
_wipe(ROOT)
_test_settings()
_test_ranges()

View file

@ -1,10 +1,10 @@
extends TestBase
## Keeps the simulator (BoardTester, and its CLI tools/simulate_board.gd) working: runs it on a small inline board with
## a choice, a loop, a check, a bad effect, an unreachable table and a sheet.
## Run: godot --headless --path . -s res://tests/test_simulate.gd
## Run: tools/run_tests.sh simulate
func _init() -> void:
func run() -> void:
var b := _board()
var r: Dictionary = await BoardTester.simulate(b, "start", {"runs": 60, "seed": 3, "track": ["gold", "@name"]})
_eq(r["runs"], 60, "60 runs")

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## Small UI items: backwards ranges warn and block rolling (no auto-swap), the
## inspector's thread lists, replacing a template, the tray chip's bold source
## name, and the export menu's diagram formats.
## Run: godot --headless --path . -s res://tests/test_small_ui.gd -- --sample
## Run: tools/run_tests.sh small_ui
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_backwards_range()

View file

@ -1,9 +1,9 @@
extends TestBase
extends AppTestBase
## Spellchecking in Build (Spellcheck, SpellWords, SpellUnderline), with a
## stand-in checker so the test needs no native add-on: which words are
## checked, underlines on card and inspector fields, suggestions replacing a
## word, the spread's own dictionary (saved with it) and Ignore.
## Run: godot --headless --path . -s res://tests/test_spellcheck.gd -- --sample
## Run: tools/run_tests.sh spellcheck
## Knows a few words; suggests from a fixed table.
@ -18,11 +18,11 @@ class FakeChecker:
return PackedStringArray({"tinkerr": ["tinker", "tinkers"], "wrok": ["work"]}.get(word.to_lower(), []))
func _init() -> void:
func run() -> void:
_test_words()
Spellcheck.use_backend(FakeChecker.new())
_test_checking()
if not await start_main():
if not await start_main(false):
return
main.set_mode(Main.Mode.BUILD)
main.data.load_dict({"format_version": 2, "id": "spell-test", "name": "Spell test", "tables": [

View file

@ -1,13 +1,13 @@
extends TestBase
extends AppTestBase
## Headless checks for spread folders (core/spread_folders.gd) and the recent
## spreads list (core/recent_spreads.gd), and the spread switcher's menu built
## from them (on a temporary library, never the saved one).
## Run: godot --headless --path . -s res://tests/test_spread_folders.gd -- --sample
## Run: tools/run_tests.sh spread_folders
const ROOT := "user://test_spread_folders_tmp"
func _init() -> void:
func run() -> void:
_wipe(ROOT)
_test_paths()
_test_listing()

View file

@ -2,10 +2,10 @@ extends TestBase
## Rolling a card from another spread: [[Treasure::Loot]] rolls Loot in the
## Treasure spread (its own references resolve there), changes this spread's
## values, and a missing spread or card shows the missing marker.
## Run: godot --headless --path . -s res://tests/test_spread_links.gd
## Run: tools/run_tests.sh spread_links
func _init() -> void:
func run() -> void:
var treasure := TowerBoard.new()
treasure.id = "treasure"
treasure.name = "Treasure"

View file

@ -1,11 +1,11 @@
extends TestBase
## Headless checks for collections, LibraryStore and StateStore.
## Run: godot --headless --path . -s res://tests/test_storage.gd
## Run: tools/run_tests.sh storage
const ROOT := "user://test_storage_tmp"
func _init() -> void:
func run() -> void:
_wipe(ROOT)
_test_versions()
_test_library()

View file

@ -1,14 +1,14 @@
extends TestBase
extends AppTestBase
## Templates: saving (placeholder detection, relative positions, pipes kept or
## recorded by name), inserting (substitution, fresh ids, internal pipes kept,
## outside pipes relinked or reported), the library and the built-in
## templates, and the app's save, list and insert.
## Run: godot --headless --path . -s res://tests/test_templates.gd -- --sample
## Run: tools/run_tests.sh templates
const TMP_ROOT := "user://test_templates_tmp"
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_make()

View file

@ -1,6 +1,6 @@
extends TestBase
## Headless checks for RollContext, TextExpander and Formatter.
## Run: godot --headless --path . -s res://tests/test_text.gd
## Run: tools/run_tests.sh text
const TABLES := {
"names": "Names",
@ -21,7 +21,7 @@ var _ctx: RollContext
var _rolls: Dictionary = {}
func _init() -> void:
func run() -> void:
_test_expander()
_test_formatter()
_test_format_menu()
@ -213,7 +213,14 @@ func _test_format_menu() -> void:
var line := LineEdit.new()
line.text = "A legendary sword"
FormatMenu.attach(line)
var right_click := InputEventMouseButton.new()
right_click.button_index = MOUSE_BUTTON_RIGHT
right_click.pressed = true
line.gui_input.emit(right_click)
var menu := line.get_menu()
var item_count := menu.item_count
line.gui_input.emit(right_click)
_eq(menu.item_count, item_count, "a second right-click doesn't add the items again")
var labels: Array[String] = []
for i in menu.item_count:
labels.append(menu.get_item_text(i))

View file

@ -1,10 +1,10 @@
extends TestBase
extends AppTestBase
## Theme sets: applying built-ins sets Style tokens and fills, saving and
## deleting a user set, and the Theme dialog building its editors.
## Run: godot --headless --path . -s res://tests/test_theme.gd -- --sample
## Run: tools/run_tests.sh theme
func _init() -> void:
func run() -> void:
if not require_sample():
return
ThemeStore.DIR = OS.get_temp_dir().path_join("tt_theme_test_%d/" % OS.get_process_id())

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## Theme files: every built-in theme's pictures, sounds and fonts load; frame
## sets, thread strips, the backdrop and the recoloured mascot build; a copy of
## a built-in keeps its file paths; the sound board follows the volume.
## Run: godot --headless --path . -s res://tests/test_theme_assets.gd -- --sample
## Run: tools/run_tests.sh theme_assets
func _init() -> void:
func run() -> void:
if not require_sample():
return
ThemeStore.DIR = OS.get_temp_dir().path_join("tt_theme_assets_%d/" % OS.get_process_id())

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## The top bar's menus (View ▾, the zoom control, Board ▾ with Pack, Help ▾),
## striped result rows, the Build card's ⋯ menu and the row × that shows on
## hover or selection, and the Help window's topics and links.
## Run: godot --headless --path . -s res://tests/test_top_bar.gd -- --sample
## Run: tools/run_tests.sh top_bar
func _init() -> void:
func run() -> void:
if not await start_main():
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
@ -115,8 +115,6 @@ func _test_card_menu() -> void:
main.undo_redo.undo()
await _frames()
_check(main.data.get_table("loot") != null, "and undo brings it back")
main.set_mode(Main.Mode.PLAY)
await _frames()
func _test_help() -> void:

View file

@ -1,15 +1,15 @@
extends TestBase
extends AppTestBase
## Cards with columns on the spread and in the inspector: the header and the
## cells, the lit cells after a roll, inline cell editing, and the inspector's
## Columns section (add, rename, move, remove, roll mode, one phrase, save as,
## only if) with the result's cell fields and roll twice and combine, all undoable.
## Run: godot --headless --path . -s res://tests/test_ui_columns.gd -- --sample
## Run: tools/run_tests.sh ui_columns
var insp: Inspector
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)

View file

@ -1,17 +1,17 @@
extends TestBase
extends AppTestBase
## Scale values in the UI (Scales): making one (+ Card, the inspector's steps
## and starting step, switching type), showing one (the card's value and row
## of steps, the Variables tab), the effect and condition rows for a scale,
## and the help topic.
## Run: godot --headless --path . -s res://tests/test_ui_scales.gd -- --sample
## Run: tools/run_tests.sh ui_scales
const CLIMATE := ["Supercold", "Cold", "Temperate", "Hot", "Superhot"]
var insp: Inspector
func _init() -> void:
if not await start_main():
func run() -> void:
if not await start_main(false):
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)

View file

@ -1,11 +1,11 @@
extends TestBase
extends AppTestBase
## The thread inspector's "Roll it with … instead" field and "Roll again if
## it comes up" list: shown for a card with numbered ranges, edits land on the
## result, undo puts them back.
## Run: godot --headless --path . -s res://tests/test_ui_threads.gd -- --sample
## Run: tools/run_tests.sh ui_threads
func _init() -> void:
func run() -> void:
if not await start_main():
return
await _test_ranged_target()
@ -35,8 +35,7 @@ func _test_ports_under_cards() -> void:
## Build mode: each card has a port on its bottom edge; a thread laid from it
## is a card thread, drawn from there, listed on the card and undoable.
func _test_card_thread_port() -> void:
main.set_mode(Main.Mode.BUILD)
await _frames(10)
await _frames(40)
var road := main.data.get_table("road")
var card := main.card_for("road")
main.board.set_zoom(1.0)
@ -61,8 +60,6 @@ func _test_card_thread_port() -> void:
main.undo_redo.undo()
await _frames(2)
_check(main.data.get_table("road").outlet.pipes.is_empty(), "undo takes it away")
main.set_mode(Main.Mode.PLAY)
await _frames()
func _find_text(n: Node, prefix: String) -> bool:

View file

@ -1,18 +1,18 @@
extends TestBase
extends AppTestBase
## Undo and redo of Build edits (EditHistory and Main's "Undo and redo"):
## every kind of edit, coalescing, redo being cleared, the cap, per-collection
## histories, labels, view and lit state, the toast's Undo, lazily built cards,
## the shortcuts and buttons, and the snapshot cost on a big board.
## Run: godot --headless --path . -s res://tests/test_undo.gd -- --sample
## Run: tools/run_tests.sh undo
## [--big-board=<collection.json>] times a real board instead of a made-up
## 800-card one.
## 320-card one.
func _init() -> void:
func run() -> void:
if not require_sample():
return
_test_history_unit()
if not await start_main():
if not await start_main(false):
return
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
main.size = Vector2(1440, 900)
@ -171,7 +171,7 @@ func _test_card_fields() -> void:
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 1 and _label() == "Edit Loot", "a weight is a step: %s" % _label())
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_pass_coalesce_window()
_t("a").entries[0].effects = "@hp -= 1"
main.mark_dirty()
await _frames()
@ -242,7 +242,7 @@ func _test_pipes() -> void:
main.undo_redo.undo()
_check(_t("a").entries[0].pipes == ["b"], "undo lays it again")
var e := _t("a").entries[0]
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_pass_coalesce_window()
var n0 := _steps()
e.set_pipe_count("b", 3)
main.mark_dirty()
@ -251,15 +251,15 @@ func _test_pipes() -> void:
main.mark_dirty()
await _frames()
_check(_steps() == n0 + 1 and _label() == "Edit thread Loot → Gems", "nudging a thread's count twice is one step: %s" % _label())
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_pass_coalesce_window()
e.set_pipe_save("b", "gem")
main.mark_dirty()
await _frames()
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_pass_coalesce_window()
e.set_pipe_when("b", "@hp > 2")
main.mark_dirty()
await _frames()
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
_pass_coalesce_window()
e.set_pipe_when("b", "")
e.set_pipe_otherwise("b", true)
main.mark_dirty()
@ -561,7 +561,7 @@ func _test_big_board() -> void:
if path != "" and FileAccess.file_exists(path):
d = JSON.parse_string(FileAccess.get_file_as_string(path))
else:
d = _synthetic_board(800)
d = _synthetic_board(320)
await _load(d)
var t := main.data.tables[main.data.tables.size() / 2]
var u := main.data.tables[main.data.tables.size() / 3]
@ -628,3 +628,9 @@ func _synthetic_board(n: int) -> Dictionary:
members.append("t%d" % i)
groups.append({"id": "g%d" % k, "name": "Group %d" % k, "x": 0, "y": k * 400, "w": 12000, "h": 380, "members": members, "collapsed": true})
return {"format_version": 2, "id": "big", "name": "Big", "tables": tables, "groups": groups}
## Ages the newest step past the merge window, instead of really waiting.
func _pass_coalesce_window() -> void:
if main.undo_redo.edits.can_undo():
main.undo_redo.edits.undo_stack.back()["time"] -= EditHistory.COALESCE_SECS + 0.1

View file

@ -1,42 +1,38 @@
class_name TestBase
extends SceneTree
## Shared boilerplate for the headless suites: the --sample guard, loading the
## app, frame waiting, the check helpers and the PASS/FAIL summary the runner
## (tools/run_tests.sh) looks for. A suite extends this and calls
## `if not await start_main(): return` first when it needs the app.
extends Node
## Shared boilerplate for the headless suites: the --sample guard, frame
## waiting and the check helpers. tests/run_suites.gd runs several suites in one
## Godot process: it adds the suite to the tree, calls run() and waits for
## finish(). Suites that need the app extend AppTestBase.
## Never mention Main or other UI classes here: every suite would then compile
## the whole app (about 1 s each).
var _failures := 0
var main: Main
var failures := 0
var done := false
# The tree's own names, so suites read like a SceneTree script.
var root: Window:
get: return get_tree().root
var process_frame: Signal:
get: return get_tree().process_frame
## Returns false (after quitting with 2) unless the suite was started with
## `-- --sample`, so a test can't touch saved data.
## The suite's checks; overridden by each suite, ends with finish().
func run() -> void:
pass
## False (and the suite fails) unless started with `-- --sample`, so a test
## can't touch saved data.
func require_sample() -> bool:
if OS.get_cmdline_user_args().has("--sample"):
return true
print("Run with -- --sample so the test can't touch saved data.")
quit(2)
abort("Run with -- --sample so the test can't touch saved data.")
return false
## Hook: suites that need a customised Main override this.
func _create_main() -> Main:
return load("res://ui/main.tscn").instantiate()
## Guard, then loads the app under root and waits for it. Returns false (after
## quitting) if the guard fails or the app would save.
func start_main() -> bool:
if not require_sample():
return false
main = _create_main()
root.add_child(main)
await _frames(5)
if main._saving_enabled:
print("Saving is enabled; refusing to run.")
quit(2)
return false
return true
func create_timer(secs: float) -> SceneTreeTimer:
return get_tree().create_timer(secs)
func _frames(n: int = 2) -> void:
@ -46,7 +42,7 @@ func _frames(n: int = 2) -> void:
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
failures += 1
print("FAIL ", what)
@ -57,10 +53,19 @@ func _eq(got: Variant, want: Variant, what: String) -> void:
_check(same, "%s\n got: %s\n want: %s" % [what, str(got), str(want)])
## Prints the summary line the runner greps for, then quits.
func finish() -> void:
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
done = true
## Fails and ends the suite before its checks.
func abort(why: String) -> void:
_check(false, why)
finish()
## Puts back what the suite changed for the next one in this process.
func clean_up() -> void:
pass
## Deletes a folder and everything in it (for temporary test folders).

View file

@ -1,45 +1,118 @@
#!/usr/bin/env bash
# Runs every headless suite in parallel and prints one line per suite.
# A suite fails if it doesn't print "PASS: 0 failure(s)" or if its output has
# a SCRIPT ERROR (a crashed test function can still print PASS).
# Runs the headless suites in a few parallel Godot processes, inside a fixed time budget.
#
# The budget is a hard limit on the whole run. At the deadline, running suites
# are stopped and the rest don't start; those are listed as NOT RUN. Only the
# user changes BUDGET_SECS. Suites run longest first (by their last time), which
# fills the workers best; one that was never timed runs first.
#
# A suite fails on a failed check, a SCRIPT ERROR or a Godot crash.
#
# Usage: tools/run_tests.sh [name-filter] e.g. tools/run_tests.sh inspector
# Exit codes: 0 all passed, 1 a suite failed, 2 over budget, nothing failed.
# Failing suites print their first 8 error lines; passing output is discarded.
set -u
cd "$(dirname "$0")/.."
readonly BUDGET_SECS=15
cd "$(dirname "$0")/.." || exit 1
GODOT="${GODOT:-$HOME/apps/Godot_v4.7.2-stable_linux.x86_64}"
TIMES=.godot/test_times # git-ignored: "<milliseconds> <suite>"
CLASSES=.godot/global_script_class_cache.cfg
start_ms=$(date +%s%3N)
now_ms() { echo $(( $(date +%s%3N) - start_ms )); }
# 1 s is kept back for stopping suites and printing the report.
left_ms() { echo $(( BUDGET_SECS * 1000 - 1000 - $(now_ms) )); }
# Runs a command at low priority; it is killed at the deadline.
in_budget() {
local left; left=$(left_ms)
(( left < 100 )) && return 124
nice -n 10 timeout -s KILL "$(( left / 1000 )).$(printf %03d $(( left % 1000 )))" "$@"
}
OUT="$(mktemp -d)"
trap 'rm -rf "$OUT"' EXIT
suites=(tests/test_*${1:-}*.gd)
# Register any new class_name scripts first (cheap when nothing changed).
"$GODOT" --headless --path . --import >/dev/null 2>&1
for t in "${suites[@]}"; do
n="$(basename "$t" .gd)"
( timeout 300 "$GODOT" --headless --path . -s "res://$t" -- --sample >"$OUT/$n.log" 2>&1 ) &
while (( $(jobs -rp | wc -l) >= ${JOBS:-8} )); do wait -n; done
# Register class_name scripts, only when a script was added or changed its list.
# Compares names, not dates, so ordinary edits don't cost an import.
declared="$(grep -rhoE --include='*.gd' --exclude-dir=.godot --exclude-dir=.claude '^class_name +[A-Za-z0-9_]+' . | awk '{print $2}' | sort)"
known="$(grep -oE '"class": &"[^"]+"' "$CLASSES" 2>/dev/null | cut -d'"' -f4 | sort)"
if [[ "$declared" != "$known" ]]; then
in_budget "$GODOT" --headless --path . --import >/dev/null 2>&1
fi
shopt -s nullglob
declare -A last_ms
while read -r ms n; do last_ms[$n]=$ms; done < <(cat "$TIMES" 2>/dev/null)
mapfile -t suites < <(for t in tests/test_*"${1:-}"*.gd; do
n="$(basename "$t" .gd)"; echo "${last_ms[$n]:-99999} $n"
done | sort -rn | cut -d' ' -f2)
(( ${#suites[@]} )) || { echo "No suite matches '${1:-}'"; exit 1; }
# A few Godot workers share the list (tests/run_suites.gd). --fixed-fps makes
# timers and animations use simulated time, not real waiting.
mkdir "$OUT/claims"
SUITES="$(IFS=,; echo "${suites[*]}")"
export SUITES CLAIMS="$OUT/claims"
jobs_wanted=${JOBS:-6}
(( jobs_wanted > ${#suites[@]} )) && jobs_wanted=${#suites[@]}
for (( w = 0; w < jobs_wanted; w++ )); do
in_budget "$GODOT" --headless --fixed-fps 60 --path . -s res://tests/run_suites.gd -- --sample >"$OUT/worker$w" 2>&1 &
done
wait
# Cut the workers' output into one log per suite; "DONE" gives its time.
awk -v out="$OUT" '
/^SUITE test_/ { suite = $2; log_file = out "/" suite ".log"; printf "" >log_file; next }
/^DONE test_/ { print $3 >(out "/" $2 ".ms"); print $4 >(out "/" $2 ".failures"); suite = ""; next }
suite != "" { print >log_file }
' "$OUT"/worker*
fail=0
not_run=()
stopped=()
declare -A first_err
for t in "${suites[@]}"; do
n="$(basename "$t" .gd)"
for n in "${suites[@]}"; do
log="$OUT/$n.log"
if grep -q "PASS: 0 failure(s)" "$log" && ! grep -q "SCRIPT ERROR" "$log"; then
echo "ok $n"
crashed=0
if [[ -e "$OUT/$n.ms" ]]; then
last_ms[$n]=$(<"$OUT/$n.ms")
if [[ $(<"$OUT/$n.failures") == 0 ]] && ! grep -q "SCRIPT ERROR" "$log"; then
echo "ok $n"
continue
fi
elif [[ -e "$log" ]] && grep -q "handle_crash" "$log"; then
crashed=1
else
not_run+=("$n")
# Started but stopped at the deadline: it may be what ate the budget.
[[ -e "$log" ]] && stopped+=("$n")
continue
fi
fail=1
e="$(grep -m1 -E "SCRIPT ERROR|^ *FAIL [^:]" "$log")"
# A shared compile error fails many suites the same way: report it once.
if [[ "$e" == *"SCRIPT ERROR"* ]]; then
if (( ! crashed )) && [[ "$e" == *"SCRIPT ERROR"* ]]; then
first_err["$e"]+="$n "
else
echo "FAIL $n"
grep -E "FAIL|SCRIPT ERROR|ERROR" "$log" | head -8
(( crashed )) && echo " Godot crashed"
grep -E "FAIL|SCRIPT ERROR|ERROR|^ +\[[0-9]+\] .*res://" "$log" | head -8
fi
done
for e in "${!first_err[@]}"; do
echo "FAIL ${first_err[$e]}"
echo " $e"
done
(( fail )) && echo "SOME SUITES FAILED" || echo "ALL ${#suites[@]} SUITES PASSED"
exit $fail
for n in "${!last_ms[@]}"; do
[[ -e "tests/$n.gd" ]] && echo "${last_ms[$n]} $n"
done | sort -n >"$TIMES"
took="$(awk -v ms="$(now_ms)" 'BEGIN { printf "%.1f", ms / 1000 }')s of ${BUDGET_SECS}s"
if (( ${#not_run[@]} )); then
echo "NOT RUN (${#not_run[@]}): ${not_run[*]}"
(( ${#stopped[@]} )) && echo "Stopped while running: ${stopped[*]}"
echo "Slowest: $(sort -rn "$TIMES" | head -5 | awk '{ printf "%s %.1fs ", $2, $1 / 1000 }')"
fi
if (( fail )); then echo "SOME SUITES FAILED ($took)"; exit 1; fi
if (( ${#not_run[@]} )); then
echo "OVER BUDGET: $(( ${#suites[@]} - ${#not_run[@]} )) of ${#suites[@]} suites passed ($took)"; exit 2
fi
echo "ALL ${#suites[@]} SUITES PASSED ($took)"

View file

@ -92,6 +92,7 @@ func setup(p_main: Main) -> void:
func _process(_delta: float) -> void:
if main == null or main.data == null:
return
main.card_refresh.step()
_signature()
var v := PackedFloat32Array([world.position.x, world.position.y, zoom, size.x, size.y])
if v != _view_sig or _culled_rev != geometry_rev:
@ -155,7 +156,9 @@ func _signature() -> void:
elif _settle > 0:
_settle -= 1
changed = true
if changed:
if changed and main.card_refresh.holds_redraw():
_settle = 2
elif changed:
geometry_rev += 1
cards.queue_redraw()
if cards.far:

94
ui/card_refresh_queue.gd Normal file
View file

@ -0,0 +1,94 @@
class_name CardRefreshQueue
extends RefCounted
## Rebuilds cards after a switch between Play and Build without stopping the
## app: cards in view at once, the rest a few per frame, the ones that have
## come into view first. Until its turn, a card out of view keeps its old
## layout. Cards are held by id, so a deleted card just drops out.
## How long one frame may spend on waiting cards (at least one is rebuilt).
const FRAME_USEC := 6000
## While cards wait, threads redraw in the first frames after a switch (the
## cards in view settle) and then only every so many frames.
const SETTLE_FRAMES := 4
const REDRAW_EVERY := 12
var m: Main
## FRAME_USEC; tests raise it so they don't depend on the machine's speed.
var frame_usec := FRAME_USEC
## Waiting card ids (id -> true). TableCard.rebuild takes its card out.
var _waiting: Dictionary = {}
var _frames_since_switch := 0
func _init(p_main: Main) -> void:
m = p_main
## Rebuilds every card: now when it's in view, soon when it isn't.
func rebuild_all() -> void:
var view := m.board.view_rect()
_waiting.clear()
_frames_since_switch = 0
for tid: String in m.cards:
var card: TableCard = m.cards[tid]
if _in_view(card, view):
card.rebuild()
else:
_waiting[tid] = true
## Rebuilds the card now if it was waiting.
func ensure(tid: String) -> void:
if _waiting.has(tid) and m.cards.has(tid):
(m.cards[tid] as TableCard).rebuild()
func forget(tid: String) -> void:
_waiting.erase(tid)
func is_waiting(tid: String) -> bool:
return _waiting.has(tid)
func is_idle() -> bool:
return _waiting.is_empty()
## Rebuilds everything still waiting.
func finish() -> void:
for tid: String in _waiting.keys():
ensure(tid)
_waiting.clear()
## True when a redraw of the threads can wait: only cards out of view are
## changing (nothing is being dragged) and more of them are to come.
func holds_redraw() -> bool:
return not _waiting.is_empty() and _frames_since_switch > SETTLE_FRAMES \
and _frames_since_switch % REDRAW_EVERY != 0 and not Input.is_mouse_button_pressed(MOUSE_BUTTON_LEFT)
## Called every frame.
func step() -> void:
if _waiting.is_empty():
return
_frames_since_switch += 1
var view := m.board.view_rect()
var later: Array[String] = []
var started := Time.get_ticks_usec()
for tid: String in _waiting.keys():
if not m.cards.has(tid):
_waiting.erase(tid)
elif _in_view(m.cards[tid], view):
ensure(tid)
else:
later.append(tid)
for tid in later:
if Time.get_ticks_usec() - started >= frame_usec:
return
ensure(tid)
func _in_view(card: TableCard, view: Rect2) -> bool:
return card.visible and view.intersects(Rect2(card.position, card.size).grow(TableCard.INLET_Y))

View file

@ -0,0 +1 @@
uid://cqreee6o6l6l3

View file

@ -30,8 +30,21 @@ const SIZES := [["Small", "[font_size=12]", "[/font_size]"], ["Big", "[font_size
const FIRST_ID := 2000
## Adds the formatting items to `field`'s right-click menu.
## Gives `field` the formatting items, added the first time its menu is about
## to open: a menu with three submenus per field made long cards slow to build.
static func attach(field: Control) -> void:
field.gui_input.connect(_add_before_opening.bind(field))
## Runs before the field's own input handling, which opens the menu.
static func _add_before_opening(event: InputEvent, field: Control) -> void:
var click := event as InputEventMouseButton
var right_click := click != null and click.pressed and click.button_index == MOUSE_BUTTON_RIGHT
if right_click or event.is_action_pressed("ui_menu", true):
_add_to(field)
static func _add_to(field: Control) -> void:
var menu: PopupMenu = field.call("get_menu") if field.has_method("get_menu") else null
if menu == null or menu.has_meta("format_menu"):
return

View file

@ -47,6 +47,9 @@ var fields: Dictionary = {}
var open_sections: Dictionary = {}
var section_parts: Dictionary = {}
var section_boxes: Dictionary = {}
## The box holding the sections and the card it shows, kept between rebuilds.
var section_list: VBoxContainer
var section_list_tid := ""
func setup(p_main: Main) -> void:
@ -68,6 +71,7 @@ func select(sel: Dictionary) -> void:
if main and main.book and main.book.visible:
SideTabs.show_tab(main, SideTabs.INSPECTOR)
selection = sel
main.card_refresh.ensure(str(sel.get("tid", "")))
var kind := str(sel.get("kind", ""))
if kind == "card" or kind == "result":
open_sections = {InspectorList.key_of(sel): true}
@ -329,26 +333,27 @@ func rebuild() -> void:
if f is LineEdit:
caret = (f as LineEdit).caret_column
for c in _content.get_children():
_content.remove_child(c)
c.queue_free()
if c != section_list:
_content.remove_child(c)
c.queue_free()
_live.clear()
effects = null
show_if_builder = null
case_builder = null
pipe_parts = {}
fields = {}
section_parts.clear()
section_boxes.clear()
var t := selected_table()
var e := selected_entry()
if selection.has("eid") and e == null:
t = null
if t == null:
selection = {}
InspectorList.drop_list(self)
InspectorFrame.show_empty(self)
else:
match str(selection.get("kind", "card")):
"pipe":
InspectorList.drop_list(self)
InspectorThread.section(self, t, e, str(selection.get("to", "")))
_:
InspectorList.build(self, t)

View file

@ -5,7 +5,8 @@ extends RefCounted
##
## Clicking the card or a result on the spread opens that section and closes the
## rest (Inspector.select). Sections opened by hand stay open until then.
## Only open sections build their fields, so long cards stay quick.
## Only open sections build their fields, so long cards stay quick, and a
## rebuild of the same card keeps the closed sections' headers (`_keep_closed`).
##
## The older section code edits "the selected result" (Inspector.selection,
## fields, effects, ...). So each open section keeps its own parts, and a click
@ -17,20 +18,27 @@ const CARD := "card"
## Builds the whole page for card `t` into the inspector's content box.
static func build(insp: Inspector, t: RollTable) -> void:
var kept := _keep_closed(insp, t)
insp.section_parts.clear()
insp.section_boxes.clear()
var keep_selection := insp.selection.duplicate()
insp._content.add_child(insp._head("Card · " + Describe.kind_label(t), Inspector._title_of(t.name, "(no name)")))
var list := InspectorKit.vbox(6)
insp._content.add_child(list)
_section(insp, list, CARD, "Card", "Settings", "", func(body: VBoxContainer) -> void:
var list := insp.section_list
if list == null:
list = InspectorKit.vbox(6)
insp.section_list = list
insp.section_list_tid = t.id
insp._content.add_child(list)
else:
insp._content.move_child(list, -1)
_section(insp, list, kept, CARD, "Card", "Settings", "", func(body: VBoxContainer) -> void:
insp.selection = {"kind": "card", "tid": t.id}
InspectorCard.build(insp, body, t, false))
if t.kind != RollTable.KIND_VARIABLE:
for i in t.entries.size():
var e := t.entries[i]
var span := t.num_label(e, i) if t.is_ranged() and e.has_range else ""
_section(insp, list, e.id, _kind_word(t), Inspector._title_of(e.text, "(nothing)"), span, func(body: VBoxContainer) -> void:
_section(insp, list, kept, e.id, _kind_word(t), Inspector._title_of(e.text, "(nothing)"), span, func(body: VBoxContainer) -> void:
insp.selection = {"kind": "result", "tid": t.id, "eid": e.id}
InspectorRange.build(insp, body, t, e)
var outer := insp._content
@ -38,9 +46,49 @@ static func build(insp: Inspector, t: RollTable) -> void:
InspectorResult.section(insp, t, e, false)
insp._content = outer)
insp.selection = keep_selection
for key: String in kept:
var box: Control = kept[key]["box"]
list.remove_child(box)
box.queue_free()
var at := 0
for key: String in insp.section_boxes:
list.move_child(insp.section_boxes[key], at)
at += 1
activate(insp, key_of(insp.selection))
## Before a rebuild: the closed sections that can stay, as {key: {box, parts}}.
## Sections with fields go. The list itself goes when the page shows another
## card or isn't a list (Inspector.rebuild keeps only `section_list`).
static func _keep_closed(insp: Inspector, t: RollTable) -> Dictionary:
var kept := {}
if insp.section_list == null:
return kept
if insp.section_list_tid != t.id:
drop_list(insp)
return kept
for key: String in insp.section_boxes:
var box: Control = insp.section_boxes[key]
var parts: Dictionary = insp.section_parts[key]
if parts["built"]:
insp.section_list.remove_child(box)
box.queue_free()
else:
kept[key] = {"box": box, "parts": parts}
return kept
## Forgets the list of sections and everything in it.
static func drop_list(insp: Inspector) -> void:
if insp.section_list != null:
insp.section_list.get_parent().remove_child(insp.section_list)
insp.section_list.queue_free()
insp.section_list = null
insp.section_list_tid = ""
insp.section_parts.clear()
insp.section_boxes.clear()
## "card" for a card selection, the result's id for a result.
static func key_of(sel: Dictionary) -> String:
return str(sel.get("eid", "")) if str(sel.get("kind", "")) == "result" else CARD
@ -56,8 +104,17 @@ static func _kind_word(t: RollTable) -> String:
## One section: a header (▸/▾, kind, title, range) and, when open, its body.
static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: String, title: String, span: String, fill: Callable) -> void:
## `kept`: closed sections from before the rebuild; one that still fits is used
## again (and taken out of `kept`).
static func _section(insp: Inspector, list: VBoxContainer, kept: Dictionary, key: String, kind: String, title: String, span: String, fill: Callable) -> void:
var open: bool = insp.open_sections.get(key, false)
var look := "%s|%s" % [kind, span]
if not open and kept.has(key) and kept[key]["parts"]["look"] == look:
insp.section_boxes[key] = kept[key]["box"]
insp.section_parts[key] = kept[key]["parts"]
(kept[key]["parts"]["title"] as Label).text = title
kept.erase(key)
return
var box := InspectorKit.vbox(0)
list.add_child(box)
insp.section_boxes[key] = box
@ -82,10 +139,10 @@ static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: St
if ev is InputEventMouseButton and (ev as InputEventMouseButton).pressed and (ev as InputEventMouseButton).button_index == MOUSE_BUTTON_LEFT:
toggle(insp, key))
box.add_child(head)
var parts := {"head": head, "title": title_label, "fields": {}, "pipe_parts": {}, "built": open}
var parts := {"head": head, "title": title_label, "fields": {}, "pipe_parts": {}, "built": open, "look": look}
insp.section_parts[key] = parts
if not open:
_style_head(head, false, false)
_style_head(parts, false)
return
var pad := MarginContainer.new()
for side: String in ["margin_left", "margin_right"]:
@ -104,13 +161,19 @@ static func _section(insp: Inspector, list: VBoxContainer, key: String, kind: St
parts["effects"] = insp.effects
parts["show_if_builder"] = insp.show_if_builder
parts["case_builder"] = insp.case_builder
_style_head(head, true, false)
_style_head(parts, false)
static func _style_head(head: PanelContainer, open: bool, active: bool) -> void:
## Outlines the active section's header. A header that already looks this way
## is left alone (restyling makes it lay out again).
static func _style_head(parts: Dictionary, active: bool) -> void:
if parts.get("active") == active:
return
parts["active"] = active
var open: bool = parts["built"]
var fill := Style.HOVER_ROW if open else Color(0, 0, 0, 0.04)
var sb := Style.bordered(Style.box(fill, 7, [10, 7, 10, 7]), 2 if active else 1, Style.TRIM if active else Style.RULE)
head.add_theme_stylebox_override("panel", sb)
(parts["head"] as PanelContainer).add_theme_stylebox_override("panel", sb)
## Opens or closes a section by its header. Opening one makes it active.
@ -142,8 +205,7 @@ static func activate(insp: Inspector, key: String) -> void:
var was := key_of(insp.selection)
insp.selection = {"kind": "card", "tid": t.id} if key == CARD else {"kind": "result", "tid": t.id, "eid": key}
for k: String in insp.section_parts:
var p: Dictionary = insp.section_parts[k]
_style_head(p["head"], p.get("built", false), k == key)
_style_head(insp.section_parts[k], k == key)
if was != key:
insp._mark_cards()

View file

@ -88,9 +88,11 @@ var inspecting: MainInspectorLink
var sound: SoundBoard
var cli: MainCli
var layout: MainLayout
var card_refresh: CardRefreshQueue
func _init() -> void:
layout = MainLayout.new(self)
card_refresh = CardRefreshQueue.new(self)
top_bar = MainTopBar.new(self)
editing = MainEditing.new(self)
grouping = MainGroups.new(self)
@ -148,6 +150,9 @@ func _ready() -> void:
WelcomeDialog.maybe_show(self)
func _exit_tree() -> void:
# A roll still animating must not go on after this scene is freed (a theme
# change mid-roll reloads it).
rolling._token += 1
_save_now()
# ---------- Cards ----------

View file

@ -163,8 +163,7 @@ func set_mode(new_mode: Main.Mode) -> void:
SideTabs.sync(m)
if new_mode != Main.Mode.BUILD:
m.inspector.clear()
for card in m.cards.values():
(card as TableCard).rebuild()
m.card_refresh.rebuild_all()
for n in m.grouping._group_nodes.values():
(n as GroupCard).rebuild()
m.top_bar._update_endless_chip()

View file

@ -75,6 +75,9 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
c0.rebuild()
m.mark_dirty("", false)
settle = true
if m.card_refresh.is_waiting(table_id):
m.card_refresh.ensure(table_id)
settle = true
var card := m.card_for(table_id)
if card == null:
return
@ -194,6 +197,7 @@ func _nav_mode_changed() -> void:
## [{rect, group, table}] with one of group / table set. `skip` is a group id
## to leave out.
func _layout_blocks(skip: String = "") -> Array:
m.card_refresh.finish() # it needs every card's real size
var out: Array = []
var grouped := {}
for g in m.data.groups:

View file

@ -105,8 +105,8 @@ func add_ref(pts: PackedVector2Array) -> void:
if far:
coarse(rid, pts, Color(Style.THREAD, 0.7), 4.0)
return
var dashes := PipeGeometry.dashes(pts, 12.0, 7.0)
for dash in dashes:
line(rid, dash, Style.THREAD_DARK, 6.0)
for dash in dashes:
line(rid, dash, Style.THREAD, 3.0)
var segments := PipeGeometry.dash_segments(pts, 12.0, 7.0)
if segments.is_empty():
return
RenderingServer.canvas_item_add_multiline(rid, segments, PackedColorArray([Style.THREAD_DARK]), 6.0, true)
RenderingServer.canvas_item_add_multiline(rid, segments, PackedColorArray([Style.THREAD]), 3.0, true)

View file

@ -41,6 +41,17 @@ static func point_along(pts: PackedVector2Array, fraction: float) -> Vector2:
return pts[pts.size() - 1]
## The dashes of a polyline as point pairs, so all of them can be drawn in one
## call (draw_multiline): a call per dash made long dashed threads very slow.
static func dash_segments(pts: PackedVector2Array, on: float, off: float) -> PackedVector2Array:
var segments := PackedVector2Array()
for dash in dashes(pts, on, off):
for i in range(1, dash.size()):
segments.append(dash[i - 1])
segments.append(dash[i])
return segments
## Splits a polyline into dashes `on` long with gaps `off` long.
static func dashes(pts: PackedVector2Array, on: float, off: float) -> Array[PackedVector2Array]:
var out: Array[PackedVector2Array] = []

View file

@ -294,11 +294,11 @@ func _draw_bundle(pts: PackedVector2Array) -> void:
func _draw_ref(pts: PackedVector2Array, lit: bool) -> void:
if lit:
draw_polyline(pts, Color(Style.ACCENT, 0.14), 12.0, true)
var dashes := PipeGeometry.dashes(pts, 12.0, 7.0)
for d in dashes:
draw_polyline(d, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true)
for d in dashes:
draw_polyline(d, Style.ACCENT if lit else Style.THREAD, 3.0, true)
var segments := PipeGeometry.dash_segments(pts, 12.0, 7.0)
if segments.is_empty():
return
draw_multiline(segments, Style.ACCENT_DARK if lit else Style.THREAD_DARK, 6.0, true)
draw_multiline(segments, Style.ACCENT if lit else Style.THREAD, 3.0, true)
func path_length(key: String) -> float:

View file

@ -39,15 +39,17 @@ func fill(col: VBoxContainer, build: bool, ranged: bool, collapsed: bool) -> voi
var lit := card.main.is_entry_lit(card.table.id, e.id)
if collapsed and not lit:
continue
var row: Control
if card.table.kind == RollTable.KIND_SHEET:
card._list_box.add_child(card.rows_ui.make_sheet_row(e, build))
row = card.rows_ui.make_sheet_row(e, build)
elif card.table.kind == RollTable.KIND_ROUTER and build:
card._list_box.add_child(card.edit_ui.make_case_row(e, i, numw))
row = card.edit_ui.make_case_row(e, i, numw)
elif card.table.kind == RollTable.KIND_CHECK:
card._list_box.add_child(card.rows_ui.make_check_row(e, i, build, numw))
row = card.rows_ui.make_check_row(e, i, build, numw)
else:
card._list_box.add_child(card.rows_ui.make_row(e, i, build, ranged, numw))
row = card.rows_ui.make_row(e, i, build, ranged, numw)
card.rows_ui.set_row_state(e.id, TableCardRows.RowState.LIT if lit else TableCardRows.RowState.NORMAL)
card._list_box.add_child(row)
if collapsed:
card.more_row = card.rows_ui.make_more_row(numw)
card._list_box.add_child(card.more_row)

View file

@ -15,6 +15,7 @@ func _init(p_card: TableCard) -> void:
func run() -> void:
var table := card.table
var main := card.main
main.card_refresh.forget(table.id)
for child in card.get_children():
if child == card.frame or child == card.group_mark or child == card.grip or child == card.shield:
continue
@ -37,8 +38,9 @@ func run() -> void:
card._shrink.call_deferred()
var ranged := table.is_ranged()
var collapsed := card.is_collapsed()
# Built before it joins the card: styling rows already on screen makes their
# text be measured again each time.
var column := TableCard.vbox(0)
card.add_child(column)
column.add_child(card.header_ui.make(build, ranged))
if not table.inputs.is_empty() and table.kind != RollTable.KIND_VARIABLE:
column.add_child(card.header_ui.make_inputs_box())
@ -79,6 +81,7 @@ func _finish(column: VBoxContainer, build: bool, ranged: bool) -> void:
card.update_warning()
if build:
column.add_child(card.edit_ui.make_footer(ranged))
card.add_child(column)
card.skin.apply_style()
card.refresh_live()
card.input.raise_covers()