TableTower/tests/test_navigation.gd

404 lines
18 KiB
GDScript3
Raw Normal View History

extends SceneTree
## 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
var _failures := 0
var main: Main
func _init() -> void:
if not OS.get_cmdline_user_args().has("--sample"):
print("Run with -- --sample so the test can't touch saved data.")
quit(2)
return
_test_fold_and_layout()
main = load("res://ui/main.tscn").instantiate()
root.add_child(main)
for i in 5:
await process_frame
if main._saving_enabled:
print("Saving is enabled; refusing to run.")
quit(2)
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)
main.size = Vector2(1440, 900)
await _load(_board_dict())
await _test_lazy_cards()
_test_search()
await _test_search_panel()
await _test_focus()
await _test_minimap()
await _load(_board_dict())
await _test_pack()
await _test_zoom_range()
await _test_panels()
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
quit(1 if _failures else 0)
## start -> agent (in Careers, 30 results); careers and skills groups
## collapsed, far apart; a variable card and a choice card loose.
func _board_dict() -> Dictionary:
var long_entries: Array = []
for i in 30:
long_entries.append({"id": "e%d" % i, "text": "Posting %d" % i})
long_entries[25]["text"] = "Ráre [b]gem[/b] posting"
return {"format_version": 2, "id": "nav-test", "name": "Nav test", "tables": [
{"id": "start", "name": "Start", "x": 40, "y": 60, "entries": [
{"id": "e1", "text": "Go to work", "pipes": ["agent"]},
{"id": "e2", "text": "Learn", "pipes": ["skill"]}]},
{"id": "agent", "name": "Agent", "x": 3000, "y": 60, "entries": long_entries},
{"id": "army", "name": "Army", "x": 3400, "y": 60, "details": "Soldiers and gems", "entries": [
{"id": "e1", "text": "Infantry"}]},
{"id": "skill", "name": "Gem", "x": 8000, "y": 60, "entries": [{"id": "e1", "text": "Gemology", "pipes": ["gems"]}]},
{"id": "gems", "name": "Gemstones", "x": 8400, "y": 60, "entries": [{"id": "e1", "text": "Ruby"}]},
{"id": "end", "name": "Endurance", "kind": "variable", "var_name": "endurance", "x": 40, "y": 3000, "entries": []},
{"id": "pick", "name": "Pick", "kind": "choice", "prompt": "Which career calls you?", "x": 6000, "y": 3000, "entries": [
{"id": "e1", "text": "Agent", "pipes": ["agent"]}, {"id": "e2", "text": "Army"}]},
], "groups": [
{"id": "careers", "name": "Careers", "x": 2978, "y": -8, "w": 760, "h": 600, "members": ["agent", "army"], "collapsed": true},
{"id": "skills", "name": "Skills", "x": 7978, "y": -8, "w": 760, "h": 300, "members": ["skill", "gems"], "collapsed": true},
]}
func _load(d: Dictionary) -> void:
main.data.load_dict(d)
main.lit_entries.clear()
main.lit_pipes.clear()
main.lit_texts.clear()
main._rebuild_cards()
for i in 4:
await process_frame
func _test_fold_and_layout() -> void:
_check(BoardSearch.fold("Ráre ÉCOLE") == "rare ecole", "fold lowers case and drops accents: %s" % BoardSearch.fold("Ráre ÉCOLE"))
_check(BoardSearch.fold("Ráre").length() == 4, "fold keeps positions")
# Pack: three blocks in a row with big gaps, one below.
var rects := [Rect2(0, 0, 100, 100), Rect2(1000, 0, 100, 50), Rect2(3000, 20, 100, 100), Rect2(2000, 900, 100, 100)]
var off := BoardLayout.pack(rects, 60.0, 60.0)
var moved: Array = []
for i in rects.size():
moved.append(Rect2((rects[i] as Rect2).position + off[i], (rects[i] as Rect2).size))
_check(moved[1].position.x == 160.0 and moved[2].position.x == 320.0, "pack closes the gaps along a row: %s" % str(moved))
_check(moved[2].position.y == 20.0, "keeping each block's height in its row")
_check(moved[3].position == Vector2(0, 180), "the next row moves up and to the left edge: %s" % str(moved[3]))
_check(not _overlaps(moved), "nothing overlaps after packing")
# Make room: a block grows from 100x100 to 600x400 in place.
var room := [Rect2(160, 0, 100, 100), Rect2(0, 160, 100, 100), Rect2(2000, 0, 100, 100)]
var ro := BoardLayout.make_room(room, Rect2(0, 0, 100, 100), Rect2(0, 0, 600, 400), 60.0)
_check(ro[0] == Vector2(500, 0), "the block to the right moves right just enough: %s" % str(ro[0]))
_check(ro[1] == Vector2(0, 300), "the block below moves down just enough: %s" % str(ro[1]))
_check(ro[2] == Vector2(500, 0), "the rest of the row moves with it, keeping order")
func _test_lazy_cards() -> void:
_check(main.card_for("agent") == null and main.card_for("army") == null, "members of a collapsed group have no card")
_check(main.card_for("start") != null and main.card_for("pick") != null, "cards on show are built")
_check(main.cards.size() == 3, "only the three loose cards are built: %d" % main.cards.size())
await process_frame
var paths: Dictionary = main.board.pipes._paths
var gn := main.group_node("careers")
var into: PackedVector2Array = paths.get("start:e1>agent", PackedVector2Array())
_check(not into.is_empty() and into[into.size() - 1].distance_to(gn.inlet_point()) < 0.5, "a thread into a hidden member still routes to its group")
var out: PackedVector2Array = paths.get("skill:e1>gems", PackedVector2Array())
_check(out.is_empty(), "threads inside one collapsed group aren't drawn")
main.toggle_group("careers")
await process_frame
_check(main.card_for("agent") != null and main.card_for("army") != null, "expanding the group builds its cards")
main.toggle_group("careers")
await process_frame
_check(main.card_for("agent") == null, "collapsing it again frees them")
# Fast roll through the hidden card still works and lights the group.
main.prompt_hook = func(_req: Dictionary) -> Variant: return 0
main.start_roll("start", true)
for i in 10:
await process_frame
_check(main.current.get("done", false), "a roll through hidden members finishes")
var rev := main.board.geometry_rev
for i in 5:
await process_frame
_check(main.board.geometry_rev == rev, "nothing redraws while the spread is idle")
main.board.world.position += Vector2(30, 10)
await process_frame
_check(main.board.geometry_rev == rev, "panning doesn't redraw the thread, port or card layers")
func _test_search() -> void:
var s := BoardSearch.new(main.data)
var r := s.find("gem")
_check(not r.is_empty() and r[0]["table_id"] == "skill" and r[0]["field"] == BoardSearch.FIELD_NAME, "an exact name ranks first: %s" % str(r.slice(0, 3)))
_check(r.size() > 1 and r[1]["table_id"] == "gems", "then a name that starts with it")
var entry := _find(r, "agent", "e25")
_check(not entry.is_empty() and entry["field"] == BoardSearch.FIELD_RESULT, "entry text matches, BBCode stripped")
_check(not entry.is_empty() and str(entry["snippet"]).substr(entry["hl_from"], entry["hl_len"]) == "gem", "and the snippet marks the match: %s" % str(entry))
_check(not entry.is_empty() and entry["group"] == "Careers" and entry["name"] == "Agent" and entry["kind"] == "Roll table", "results name the card, its kind and its group")
_check(not _find(r, "army", "").is_empty(), "details match too")
var acc := s.find("RARE")
_check(not acc.is_empty() and acc[0]["table_id"] == "agent" and acc[0]["entry_id"] == "e25", "matching ignores case and accents")
var v := s.find("endurance")
_check(v.size() >= 2 and v[0]["table_id"] == "end", "a variable card by name: %s" % str(v))
var has_var := false
for x: Dictionary in v:
if x["field"] == BoardSearch.FIELD_VARIABLE:
has_var = true
_check(has_var, "and by its variable name")
var g := s.find("careers")
_check(not g.is_empty() and g[0]["group_id"] == "careers" and g[0]["kind"] == "Group", "group names match")
var p := s.find("career calls")
_check(not p.is_empty() and p[0]["table_id"] == "pick" and p[0]["field"] == BoardSearch.FIELD_PROMPT, "choice prompts match")
var words := s.find("posting gem")
_check(not words.is_empty() and words[0]["entry_id"] == "e25", "every word must match, in any order")
_check(s.find("zzzz").is_empty() and s.find(" ").is_empty(), "no match, no results")
func _find(results: Array, tid: String, eid: String) -> Dictionary:
for r: Dictionary in results:
if r["table_id"] == tid and (eid == "" or r["entry_id"] == eid):
return r
return {}
func _test_search_panel() -> void:
var p := main.nav.open_search()
await process_frame
_check(p.visible and p.field.has_focus(), "Search opens with the field focused")
p.field.text = "posting"
p.refresh()
_check(p.results.size() > 1 and p.selected == 0, "results show as you type")
var ev := InputEventKey.new()
ev.keycode = KEY_DOWN
ev.pressed = true
p._on_field_input(ev)
_check(p.selected == 1, "Down picks the next result")
ev.keycode = KEY_ESCAPE
p._on_field_input(ev)
_check(not p.visible, "Esc closes it")
# Ctrl+F opens it again.
var cf := InputEventKey.new()
cf.keycode = KEY_F
cf.ctrl_pressed = true
cf.pressed = true
main._shortcut_input(cf)
_check(p.visible, "Ctrl+F opens search")
p.field.text = "Gemstones"
p.refresh()
ev.keycode = KEY_ENTER
p._on_field_input(ev)
_check(not p.visible, "Enter jumps and closes")
for i in 40:
await process_frame
_check(main.card_for("gems") != null and not main.data.get_group("skills").collapsed, "jumping to a hidden card opens its group")
func _test_focus() -> void:
var g := main.data.get_group("careers")
if not g.collapsed:
main.toggle_group("careers")
await process_frame
main.board.set_zoom(0.2)
main.focus_table("agent", "e25")
for i in 120:
await process_frame
if not main.board.is_animating() and i > 5:
break
var card := main.card_for("agent")
_check(not g.collapsed and main.data.to_dict()["groups"][0].get("collapsed", false) == false, "focus expands the collapsed group (saved)")
_check(main.top_bar._toast.visible and main.top_bar._toast_label.text.contains("Opened group Careers"), "and says so: %s" % main.top_bar._toast_label.text)
_check(card != null, "the card is built")
if card == null:
return
var view := main.board.view_rect()
var r := Rect2(card.position, card.size)
_check(main.board.zoom >= MainNavigation.MIN_FOCUS_ZOOM, "the view zooms in to read it: %.2f" % main.board.zoom)
_check(view.encloses(Rect2(r.position, Vector2(r.size.x, minf(r.size.y, view.size.y - 20.0)))), "the card is in view: %s in %s" % [str(r), str(view)])
_check(absf(view.get_center().x - r.get_center().x) < 2.0, "and centred")
_check(card.list_scroll != null and card.list_scroll.scroll_vertical > 0, "the long list scrolls to the result")
var a := card.anchor_for("e25")
_check(not a.is_empty() and a["visible"], "the result's row is in view")
_check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == r, "a ring flashes around the card")
var row := main.board.cards.flash_row_rect()
_check(row.size.y > 0.0 and absf(row.get_center().y - (a["pos"] as Vector2).y) < 1.0, "and around the row: %s" % str(row))
# The ring fades after about 1.5 s.
main.board.cards._process(2.0)
_check(not main.board.cards.is_flashing(), "the flash ends")
# A collapsed loose card opens when a result is asked for.
main.data.get_table("start").collapsed = true
main.card_for("start").rebuild()
main.focus_table("start", "e2")
for i in 6:
await process_frame
_check(not main.data.get_table("start").collapsed, "focus on a result expands a collapsed card")
main.focus_table("nope")
_check(true, "an unknown id does nothing")
func _test_minimap() -> void:
var mm := main.board.minimap
main.nav.set_minimap_visible(true)
await process_frame
main.top_bar.view_menu.sync()
var view_pm := main.top_bar.view_menu.get_popup()
_check(mm.visible and view_pm.is_item_checked(view_pm.get_item_index(ViewMenu.ID_MINIMAP)), "the minimap shows, and View ▾ has it checked")
_check(mm.position.x + mm.size.x <= main.board.size.x and mm.position.y + mm.size.y <= main.board.size.y, "in the spread's bottom-right corner")
mm.set_world(Rect2(-100, -100, 4000, 2000))
var p := Vector2(1234, 567)
_check(mm.map_to_world(mm.world_to_map(p)).distance_to(p) < 0.01, "map and world coordinates round-trip")
main.board.set_zoom(0.5)
main.board.center_on(Vector2(1900, 900))
var v := main.board.view_rect()
var vm := mm.view_rect_on_map()
_check(vm.position.distance_to(mm.world_to_map(v.position)) < 0.01 and absf(vm.size.x - v.size.x * mm._scale) < 0.01, "the view rect is the spread's view, scaled")
var target := mm.world_to_map(Vector2(500, 300))
mm.pan_to_map_point(target)
_check(main.board.view_rect().get_center().distance_to(Vector2(500, 300)) < 1.0, "clicking the map pans there")
var click := InputEventMouseButton.new()
click.button_index = MOUSE_BUTTON_LEFT
click.pressed = true
click.position = mm.world_to_map(Vector2(2500, 1000))
mm._gui_input(click)
var drag := InputEventMouseMotion.new()
drag.position = mm.world_to_map(Vector2(2600, 1200))
mm._gui_input(drag)
_check(main.board.view_rect().get_center().distance_to(Vector2(2600, 1200)) < 1.0, "dragging on it pans along")
click.pressed = false
mm._gui_input(click)
# M toggles it (not while typing).
var m := InputEventKey.new()
m.keycode = KEY_M
m.pressed = true
main._shortcut_input(m)
_check(not mm.visible, "M hides it")
main._shortcut_input(m)
_check(mm.visible, "M shows it again")
main.set_mode(Main.Mode.PLAY)
_check(not mm.visible, "it's off by default in Play")
main.set_mode(Main.Mode.BUILD)
main.set_mode(Main.Mode.PLAY)
await process_frame
func _test_pack() -> void:
main.set_mode(Main.Mode.BUILD)
var before := _blocks()
var bounds0 := main.board.content_bounds()
var moved: int = await main.nav.pack_collapsed_groups()
var after := _blocks()
_check(moved > 0, "Pack moves blocks: %d" % moved)
_check(not _overlaps(after.values()), "nothing overlaps after Pack: %s" % str(after))
_check(after["careers"].position.x < after["skills"].position.x and after["start"].position.x < after["careers"].position.x,
"reading order holds along the top row")
_check(after["end"].position.y > after["start"].position.y and after["pick"].position.x > after["end"].position.x, "and in the row below")
var bounds1 := main.board.content_bounds()
_check(bounds1.size.x < bounds0.size.x * 0.5 and bounds1.size.y < bounds0.size.y, "the spread gets much smaller: %s -> %s" % [str(bounds0.size), str(bounds1.size)])
var agent := main.data.get_table("agent")
_check(agent.position - main.data.get_group("careers").position == Vector2(22, 68), "members move with their group")
_check(main.top_bar._toast.visible and main.top_bar._toast_undo.visible, "with an undo toast")
main.top_bar._undo()
await process_frame
var back := _blocks()
_check(back["skills"].position == before["skills"].position and back["start"].position == before["start"].position
and back["careers"].position == before["careers"].position, "undo puts everything back")
# Expanding a packed group makes room instead of overlapping.
await main.nav.pack_collapsed_groups()
main.toggle_group("careers")
for i in 3:
await process_frame
var grown := _blocks()
_check(not _overlaps(grown.values()), "expanding a packed group pushes its neighbours clear: %s" % str(grown))
_check(grown["careers"].position.x < grown["skills"].position.x, "keeping their order")
_check(main.top_bar._toast_label.text.contains("make room") and main.top_bar._toast_undo.visible, "and says so, with undo: %s" % main.top_bar._toast_label.text)
func _test_zoom_range() -> void:
await _load(_board_dict())
main.board.set_zoom(0.01)
_check(is_equal_approx(main.board.zoom, BoardView.MIN_ZOOM) and BoardView.MIN_ZOOM <= 0.1, "zoom goes down to about 0.1")
main.board.fit()
_check(main.board.zoom < 0.35, "Fit can zoom below the old minimum for a wide spread: %.2f" % main.board.zoom)
## Rects of the blocks Pack works on: groups (compact or frame) and loose cards.
func _blocks() -> Dictionary:
var out := {}
for b: Dictionary in main.nav._layout_blocks():
out[b["group"] if b["group"] != "" else b["table"]] = b["rect"]
return out
func _overlaps(rects: Array) -> bool:
for i in rects.size():
for j in range(i + 1, rects.size()):
if (rects[i] as Rect2).intersects(rects[j]):
return true
return false
func _check(ok: bool, what: String) -> void:
if not ok:
_failures += 1
print("FAIL ", what)
func _test_panels() -> void:
print("Resizable tray and inspector")
var foot: PanelSplitter = null
var side: PanelSplitter = null
for n in main.find_children("*", "PanelSplitter", true, false):
if (n as PanelSplitter).vertical:
foot = n
else:
side = n
_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.
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:
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(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()
_check(absf(main.tray.size.y - 400.0) < 2.0, "dragging makes the tray 400 tall (%.0f)" % main.tray.size.y)
foot.set_size_px(10.0)
_eq(foot.size_px, ResultTray.MIN_HEIGHT, "the tray has a smallest height")
foot.set_size_px(5000.0)
_check(foot.size_px <= main.size.y * foot.max_share + 1.0, "the tray can't take the whole window")
foot.set_size_px(ResultTray.HEIGHT)
# The inspector's handle shows with it, and sizes it.
main.set_mode(Main.Mode.BUILD)
await _frames()
_check(side.visible, "the inspector's handle shows in Build mode")
side.set_size_px(500.0)
await _frames()
_check(absf(main.inspector.size.x - 500.0) < 2.0, "dragging makes the inspector 500 wide (%.0f)" % main.inspector.size.x)
main.inspector.set_collapsed(true)
_check(not side.visible, "a collapsed inspector has no handle")
main.inspector.set_collapsed(false)
_check(absf(main.inspector.custom_minimum_size.x - 500.0) < 1.0, "opening it again keeps its width")
side.set_size_px(Inspector.WIDTH)
main.set_mode(Main.Mode.PLAY)
_check(not side.visible, "no handle in Play mode")
main.history.clear()
func _eq(got: Variant, want: Variant, what: String) -> void:
_check(typeof(got) == typeof(want) and got == want, "%s: got %s, want %s" % [what, str(got), str(want)])
func _frames(n: int = 4) -> void:
for i in n:
await process_frame