Merge branch 'worktree-agent-a694f3c612ebce597' into undo-options
This commit is contained in:
commit
292d45e179
8 changed files with 1783 additions and 79 deletions
17
README.md
17
README.md
|
|
@ -23,7 +23,19 @@ godot --path .
|
|||
add or delete results and tables, and drag a card by its header. Drag from a result's ●
|
||||
onto another table to lay a pipe. Click a pipe to set how many times it rolls, save its
|
||||
result as a variable, or remove it. The ⚙ on a card opens its settings: details, tags,
|
||||
plain or dice table (e.g. 2d6), and Card mode. Deletions can be undone from the toast.
|
||||
plain or dice table (e.g. 2d6), and Card mode.
|
||||
- **Undo and redo:** every change to the board can be undone: typing, weights, effects,
|
||||
details and settings, adding and deleting results, cards and pipes, pipe options, moves,
|
||||
groups, templates, Pack and Reset sample. **Ctrl+Z** undoes and **Ctrl+Shift+Z** or
|
||||
**Ctrl+Y** redoes; Build mode's top bar has **Undo** and **Redo** buttons whose tooltips
|
||||
name the step ("Undo: Delete table Loot"), and the message after a deletion has an Undo
|
||||
button too. While a text field has focus, Ctrl+Z undoes typing in that field; click the
|
||||
felt first to undo on the board. Typing in one field until you move on is
|
||||
one step, a whole drag is one step, and quick changes to the same card or pipe merge.
|
||||
Undo keeps your view, mode, search and lit results, and rings the cards it changed.
|
||||
Collapsing and expanding cards and groups isn't an undo step (it's left as it is), and
|
||||
neither are rolls, decks or variables. In Play mode Ctrl+Z still works, for cards you
|
||||
moved there. Each collection keeps its own history (up to 200 steps) while the app runs.
|
||||
- **Text in results** can roll on other tables inline with `[[Table]]`, `[[3x Gems]]` or
|
||||
`[[Names -> hero]]` (saves the result as `{hero}` for the rest of the roll). `{@town|Towns}`
|
||||
keeps a value across rolls until you clear it in the tray's Variables tab. BBCode such as
|
||||
|
|
@ -147,6 +159,9 @@ Groups and templates: `--select=<id>,<id>`, `--group-selected[=<name>]`, `--coll
|
|||
`--save-template=<table>`, `--save-group-template=first`, `--view=<x>,<y>[,<zoom>]`, `--fit` and
|
||||
`--clear-result`.
|
||||
|
||||
Undo: `--undo-demo[=<table id>]` deletes a table and undoes it (the toast says so),
|
||||
`--undo-tooltip` makes an edit and hovers the Undo button.
|
||||
|
||||
Navigation: `--search=<text>` (the search panel with results), `--focus=<table id>[:<entry id>]`,
|
||||
`--minimap` / `--no-minimap`, `--pack` (Build), and `--perf` (prints load time and idle and
|
||||
panning frame times with vsync off, then quits; `--perf-layers` adds a per-layer breakdown).
|
||||
|
|
|
|||
655
tests/test_undo.gd
Normal file
655
tests/test_undo.gd
Normal file
|
|
@ -0,0 +1,655 @@
|
|||
extends SceneTree
|
||||
## 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
|
||||
## [--big-board=<collection.json>] times a real board instead of a made-up
|
||||
## 800-card one.
|
||||
|
||||
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_history_unit()
|
||||
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
|
||||
main.set_anchors_and_offsets_preset(Control.PRESET_TOP_LEFT)
|
||||
main.size = Vector2(1440, 900)
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
await _load()
|
||||
await _test_typing()
|
||||
await _test_card_fields()
|
||||
await _test_results_and_tables()
|
||||
await _test_pipes()
|
||||
await _test_drag()
|
||||
await _test_groups()
|
||||
await _test_template_and_reset()
|
||||
await _test_pack()
|
||||
await _test_redo_cleared()
|
||||
await _test_view_kept()
|
||||
await _test_toast()
|
||||
await _test_lazy_cards()
|
||||
await _test_collapse_not_undoable()
|
||||
await _test_shortcuts_and_buttons()
|
||||
await _test_play_mode()
|
||||
await _test_collections()
|
||||
await _test_big_board()
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if ok:
|
||||
print(" ok %s" % what)
|
||||
else:
|
||||
_failures += 1
|
||||
print(" FAIL %s" % what)
|
||||
|
||||
|
||||
## Loot (two results, one piping to Gems), Gems, Weapons and Armor in the
|
||||
## group Careers, far to the right.
|
||||
func _board_dict() -> Dictionary:
|
||||
return {"format_version": 2, "id": "undo-test", "name": "Undo test", "tables": [
|
||||
{"id": "a", "name": "Loot", "x": 40, "y": 60, "entries": [
|
||||
{"id": "e1", "text": "Gold", "pipes": ["b"]},
|
||||
{"id": "e2", "text": "Silver"}]},
|
||||
{"id": "b", "name": "Gems", "x": 400, "y": 60, "entries": [{"id": "e1", "text": "Ruby"}]},
|
||||
{"id": "c", "name": "Weapons", "x": 1500, "y": 90, "entries": [{"id": "e1", "text": "Sword"}]},
|
||||
{"id": "d", "name": "Armor", "x": 1860, "y": 90, "entries": [{"id": "e1", "text": "Mail"}]},
|
||||
], "groups": [
|
||||
{"id": "g1", "name": "Careers", "x": 1478, "y": 22, "w": 700, "h": 300, "members": ["c", "d"]},
|
||||
]}
|
||||
|
||||
|
||||
func _load(d: Dictionary = {}) -> void:
|
||||
main.data.load_dict(d if not d.is_empty() else _board_dict())
|
||||
main.lit_entries.clear()
|
||||
main.lit_pipes.clear()
|
||||
main.lit_texts.clear()
|
||||
main._rebuild_cards()
|
||||
for i in 4:
|
||||
await process_frame
|
||||
|
||||
|
||||
func _frames(n: int = 2) -> void:
|
||||
for i in n:
|
||||
await process_frame
|
||||
|
||||
|
||||
func _t(id: String) -> RollTable:
|
||||
return main.data.get_table(id)
|
||||
|
||||
|
||||
func _label() -> String:
|
||||
return main.edits.undo_label()
|
||||
|
||||
|
||||
func _steps() -> int:
|
||||
return main.edits.undo_stack.size()
|
||||
|
||||
|
||||
func _line_edit_with(n: Node, text: String) -> LineEdit:
|
||||
for c in n.get_children():
|
||||
if c is LineEdit and (c as LineEdit).text == text:
|
||||
return c
|
||||
var r := _line_edit_with(c, text)
|
||||
if r:
|
||||
return r
|
||||
return null
|
||||
|
||||
|
||||
# ---------- EditHistory on its own ----------
|
||||
|
||||
func _test_history_unit() -> void:
|
||||
print("EditHistory")
|
||||
var b := TowerBoard.new()
|
||||
b.load_dict(_board_dict())
|
||||
var h := EditHistory.new(b)
|
||||
_check(not h.can_undo() and not h.can_redo(), "a new history is empty")
|
||||
b.get_table("a").collapsed = true
|
||||
_check(not h.commit(b)["step"], "collapsing alone isn't a step")
|
||||
b.get_table("a").entries[0].text = "Platinum"
|
||||
var r := h.commit(b)
|
||||
_check(r["step"] and h.undo_label() == "Edit Loot", "an edit is a step named from the diff: %s" % h.undo_label())
|
||||
b.get_table("b").name = "Jewels"
|
||||
h.commit(b, "", 0, 100.0)
|
||||
_check(h.undo_label() == "Rename Gems → Jewels", "a rename: %s" % h.undo_label())
|
||||
var later := int(h.undo_stack.back()["snap"]["bytes"])
|
||||
var full := EditHistory.full_bytes(h.cache)
|
||||
_check(later < full / 2, "a later snapshot shares the unchanged cards' text: %d of %d" % [later, full])
|
||||
var e := h.pop_undo()
|
||||
h.cache = EditHistory.restore(b, e["snap"])
|
||||
_check(b.get_table("b").name == "Gems" and h.can_redo() and h.redo_label() == "Rename Gems → Jewels", "undo restores the name and offers redo")
|
||||
_check(b.get_table("a").collapsed, "restoring keeps a table collapsed as it is now")
|
||||
# The cap.
|
||||
var h2 := EditHistory.new(b)
|
||||
for i in EditHistory.MAX_STEPS + 50:
|
||||
b.get_table("a").entries[1].weight = i + 2
|
||||
h2.commit(b, "", 0, float(i) * 10.0)
|
||||
_check(h2.undo_stack.size() == EditHistory.MAX_STEPS, "the history keeps at most %d steps: %d" % [EditHistory.MAX_STEPS, h2.undo_stack.size()])
|
||||
_check(h2.bytes() < EditHistory.MAX_BYTES, "and stays within its memory budget: %d bytes" % h2.bytes())
|
||||
# Same-thing edits close together merge; different things don't.
|
||||
var h3 := EditHistory.new(b)
|
||||
b.get_table("a").entries[1].weight = 5
|
||||
h3.commit(b, "", 0, 1000.0)
|
||||
b.get_table("a").entries[1].weight = 6
|
||||
h3.commit(b, "", 0, 1000.3)
|
||||
_check(h3.undo_stack.size() == 1, "two quick edits to one card are one step")
|
||||
b.get_table("b").entries[0].text = "Opal"
|
||||
h3.commit(b, "", 0, 1000.5)
|
||||
_check(h3.undo_stack.size() == 2, "an edit to another card is a new step")
|
||||
b.get_table("b").entries[0].text = "Ruby"
|
||||
h3.commit(b, "", 0, 1000.6)
|
||||
_check(h3.undo_stack.size() == 1, "typing something and putting it back leaves no step")
|
||||
|
||||
|
||||
# ---------- Edits through the app ----------
|
||||
|
||||
func _test_typing() -> void:
|
||||
print("Typing coalesces")
|
||||
var card := main.card_for("a")
|
||||
var le := _line_edit_with(card, "Loot")
|
||||
_check(le != null, "the card has a name field")
|
||||
if le == null:
|
||||
return
|
||||
le.grab_focus()
|
||||
var s := "Loot"
|
||||
for ch in " of the deep":
|
||||
s += ch
|
||||
le.text = s
|
||||
le.text_changed.emit(s)
|
||||
_check(not main.edits.can_undo() and main.can_undo(), "while typing nothing is committed yet, but Undo is offered")
|
||||
await create_timer(Main.EDIT_PAUSE + 0.3).timeout
|
||||
_check(_steps() == 1 and _label() == "Rename Loot → Loot of the deep", "a pause commits the typing as one step: %d, %s" % [_steps(), _label()])
|
||||
for ch in "!!":
|
||||
s += ch
|
||||
le.text = s
|
||||
le.text_changed.emit(s)
|
||||
main._commit_edits()
|
||||
_check(_steps() == 1 and _t("a").name == "Loot of the deep!!", "more typing in the same field joins that step: %d" % _steps())
|
||||
le.release_focus()
|
||||
main.undo()
|
||||
_check(_t("a").name == "Loot", "undo puts the old name back")
|
||||
_check(main._toast_label.text == "Undid: Rename Loot → Loot of the deep!!", "a toast says what was undone: %s" % main._toast_label.text)
|
||||
main.redo()
|
||||
_check(_t("a").name == "Loot of the deep!!" and main._toast_label.text.begins_with("Redid: "), "redo brings it back")
|
||||
main.undo()
|
||||
await _frames()
|
||||
|
||||
|
||||
func _test_card_fields() -> void:
|
||||
print("Weights, effects, details, settings")
|
||||
var n0 := _steps()
|
||||
_t("a").entries[0].weight = 4
|
||||
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
|
||||
_t("a").entries[0].effects = "@hp -= 1"
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_t("a").details = "Treasure"
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_steps() == n0 + 2, "an effect and details right after merge into one step on the same card: %d" % (_steps() - n0))
|
||||
main.undo()
|
||||
_check(_t("a").entries[0].effects == "" and _t("a").details == "" and _t("a").entries[0].weight == 4, "undo takes both back, leaving the weight")
|
||||
main.undo()
|
||||
_check(_t("a").entries[0].weight == 1, "and then the weight")
|
||||
# Settings go through the dialog's applied signal.
|
||||
main.open_table_settings("b")
|
||||
await _frames()
|
||||
var dlg: TableSettingsDialog = null
|
||||
for c in main.get_children():
|
||||
if c is TableSettingsDialog:
|
||||
dlg = c
|
||||
_check(dlg != null, "the settings dialog opens")
|
||||
if dlg:
|
||||
_t("b").card_mode = true
|
||||
dlg.applied.emit({})
|
||||
dlg.close()
|
||||
await _frames()
|
||||
_check(_label() == "Edit settings of Gems", "settings are a step: %s" % _label())
|
||||
main.undo()
|
||||
_check(not _t("b").card_mode, "undo puts the settings back")
|
||||
|
||||
|
||||
func _test_results_and_tables() -> void:
|
||||
print("Results and tables")
|
||||
main.add_entry("a")
|
||||
_check(_label() == "Add result to Loot" and _t("a").entries.size() == 3, "adding a result: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t("a").entries.size() == 2, "undo removes it")
|
||||
main.redo()
|
||||
_check(_t("a").entries.size() == 3, "redo adds it back")
|
||||
main.undo()
|
||||
main.delete_entry("a", "e2")
|
||||
_check(_label() == "Delete result “Silver” from Loot", "deleting a result: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t("a").find_entry("e2") != null and _t("a").find_entry("e2").text == "Silver", "undo brings the result back")
|
||||
var t := main.add_table()
|
||||
_check(_label() == "Add table New table", "adding a table: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t(t.id) == null and main.card_for(t.id) == null, "undo removes the table and its card")
|
||||
main.add_table(RollTable.KIND_CHOICE, "pick")
|
||||
_check(_label() == "Add choice New choice", "adding a choice card: %s" % _label())
|
||||
main.undo()
|
||||
main.delete_table("b")
|
||||
_check(_label() == "Delete table Gems" and _t("a").entries[0].pipes.is_empty(), "deleting a table: %s" % _label())
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(_t("b") != null and main.card_for("b") != null and _t("a").entries[0].pipes == ["b"], "undo brings the table, its card and the pipe into it back")
|
||||
|
||||
|
||||
func _test_pipes() -> void:
|
||||
print("Pipes")
|
||||
main._begin_edit()
|
||||
_t("a").entries[1].pipes.append("c")
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_label() == "Add pipe Loot → Weapons", "laying a pipe: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t("a").entries[1].pipes.is_empty(), "undo takes the pipe away")
|
||||
main.remove_pipe("a:e1>b")
|
||||
_check(_label() == "Remove pipe Loot → Gems" and main._toast_undo.visible, "removing a pipe, with an undo toast: %s" % _label())
|
||||
main.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
|
||||
var n0 := _steps()
|
||||
e.set_pipe_count("b", 3)
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
e.set_pipe_count("b", 4)
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_steps() == n0 + 1 and _label() == "Edit pipe Loot → Gems", "nudging a pipe's count twice is one step: %s" % _label())
|
||||
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
|
||||
e.set_pipe_save("b", "gem")
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
|
||||
e.set_pipe_when("b", "@hp > 2")
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
await create_timer(EditHistory.COALESCE_SECS + 0.1).timeout
|
||||
e.set_pipe_when("b", "")
|
||||
e.set_pipe_otherwise("b", true)
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_steps() == n0 + 4, "save as, Only if and Otherwise are steps of their own: %d" % (_steps() - n0))
|
||||
main.undo()
|
||||
_check(_t("a").entries[0].when_for("b") == "@hp > 2" and not _t("a").entries[0].is_otherwise("b"), "undo: Only if back")
|
||||
main.undo()
|
||||
_check(_t("a").entries[0].when_for("b") == "" and _t("a").entries[0].save_for("b") == "gem", "undo: condition gone, save kept")
|
||||
main.undo()
|
||||
main.undo()
|
||||
_check(_t("a").entries[0].count_for("b") == 1 and _t("a").entries[0].save_for("b") == "", "undo: count back to 1")
|
||||
|
||||
|
||||
func _test_drag() -> void:
|
||||
print("Drags")
|
||||
var card := main.card_for("b")
|
||||
var p0 := card.position
|
||||
var n0 := _steps()
|
||||
main.begin_card_drag(card)
|
||||
main.end_card_drag(card)
|
||||
await _frames()
|
||||
_check(_steps() == n0, "a click on a header without a drag isn't a step")
|
||||
main.begin_card_drag(card)
|
||||
for i in 10:
|
||||
main.drag_card(card, p0 + Vector2(10 * i, 5 * i))
|
||||
await process_frame
|
||||
main.end_card_drag(card)
|
||||
await _frames()
|
||||
_check(_steps() == n0 + 1 and _label() == "Move Gems", "a whole drag is one step: %d, %s" % [_steps() - n0, _label()])
|
||||
main.undo()
|
||||
_check(_t("b").position == p0 and main.card_for("b").position == p0, "undo moves the card back")
|
||||
# Dragging into a group frame joins it.
|
||||
card = main.card_for("b")
|
||||
main.begin_card_drag(card)
|
||||
main.drag_card(card, Vector2(1600, 140))
|
||||
main.end_card_drag(card)
|
||||
await _frames()
|
||||
_check(_label() == "Add 1 card to group Careers" and main.data.group_of("b") != null, "dropping into a group: %s" % _label())
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(main.data.group_of("b") == null and _t("b").position == p0, "undo takes it back out")
|
||||
# Several selected cards move together as one step.
|
||||
main.set_selection(["a", "b"])
|
||||
card = main.card_for("a")
|
||||
var pa := card.position
|
||||
main.begin_card_drag(card)
|
||||
main.drag_card(card, pa + Vector2(0, 300))
|
||||
main.end_card_drag(card)
|
||||
await _frames()
|
||||
_check(_label() == "Move 2 cards", "moving a selection: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t("a").position == pa and main.selection.is_empty(), "undo moves them back and clears the selection")
|
||||
|
||||
|
||||
func _test_groups() -> void:
|
||||
print("Groups")
|
||||
main.set_selection(["a", "b"])
|
||||
var g := main.group_selection()
|
||||
_check(_label() == "Group %s" % g.name, "grouping: %s" % _label())
|
||||
main.undo()
|
||||
_check(main.data.get_group(g.id) == null and main.group_node(g.id) == null, "undo removes the group")
|
||||
main.redo()
|
||||
_check(main.data.get_group(g.id) != null and main.group_node(g.id) != null, "redo makes it again")
|
||||
main.undo()
|
||||
main.ungroup("g1")
|
||||
_check(_label() == "Ungroup Careers", "ungrouping: %s" % _label())
|
||||
main.undo()
|
||||
_check(main.data.get_group("g1") != null and main.data.get_group("g1").members == ["c", "d"], "undo puts the group back")
|
||||
main.delete_group("g1")
|
||||
_check(_label() == "Delete group Careers" and _t("c") == null, "deleting a group: %s" % _label())
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(_t("c") != null and main.card_for("d") != null and main.group_node("g1") != null, "undo brings the group and its cards back")
|
||||
var gpos := main.data.get_group("g1").position
|
||||
var cpos := _t("c").position
|
||||
main.move_group("g1", Vector2(100, 50))
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_label() == "Move group Careers", "moving a group: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t("c").position == cpos and main.data.get_group("g1").position == gpos, "undo moves it back")
|
||||
main.data.get_group("g1").name = "Jobs"
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_label() == "Rename group Jobs", "renaming a group: %s" % _label())
|
||||
main.undo()
|
||||
_check(main.data.get_group("g1").name == "Careers", "undo restores the name")
|
||||
main.data.remove_from_group("d")
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_label() == "Take 1 card out of group Careers", "taking a card out: %s" % _label())
|
||||
main.undo()
|
||||
_check(main.data.get_group("g1").members.has("d"), "undo puts it back in")
|
||||
|
||||
|
||||
func _test_template_and_reset() -> void:
|
||||
print("Templates and Reset sample")
|
||||
var tpl := TemplateKit.make(main.data, ["a"], "card", "Loot copy")
|
||||
var r := main.insert_template(tpl, {})
|
||||
await _frames()
|
||||
var nt: RollTable = r["tables"][0]
|
||||
_check(_label() == "Insert template Loot copy" and _t(nt.id) != null, "inserting a template: %s" % _label())
|
||||
main.undo()
|
||||
_check(_t(nt.id) == null and main.card_for(nt.id) == null, "undo removes the inserted cards")
|
||||
await main.reset_sample()
|
||||
_check(_label() == "Reset sample" and _t("a") == null, "Reset sample is a step: %s" % _label())
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(_t("a") != null and _t("a").name == "Loot" and main.data.get_group("g1") != null, "undo brings the board back")
|
||||
|
||||
|
||||
func _test_pack() -> void:
|
||||
print("Pack")
|
||||
main.set_group_collapsed("g1", true)
|
||||
await _frames(3)
|
||||
_check(not main.edits.can_redo() or true, "collapsing")
|
||||
var gpos := main.data.get_group("g1").position
|
||||
var moved: int = await main.pack_collapsed_groups()
|
||||
_check(moved > 0 and _label() == "Pack collapsed groups", "Pack is a step: %s" % _label())
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(main.data.get_group("g1").position == gpos, "undo puts the group back")
|
||||
_check(main.data.get_group("g1").collapsed, "and leaves it collapsed")
|
||||
main.set_group_collapsed("g1", false)
|
||||
await _frames(3)
|
||||
|
||||
|
||||
func _test_redo_cleared() -> void:
|
||||
print("Redo is cleared by a new edit")
|
||||
main.add_entry("b")
|
||||
main.undo()
|
||||
_check(main.edits.can_redo(), "after undo, redo is offered")
|
||||
main.add_entry("a")
|
||||
_check(not main.edits.can_redo(), "a new edit clears it")
|
||||
main.undo()
|
||||
|
||||
|
||||
func _test_view_kept() -> void:
|
||||
print("View, lit state, search and mode")
|
||||
await _frames(3)
|
||||
main.board.stop_animation()
|
||||
main.board.set_zoom(0.6)
|
||||
main.board.world.position = Vector2(-123, 45)
|
||||
main.lit_entries["a:e1"] = true
|
||||
main.lit_entries["b:e1"] = true
|
||||
var panel := main.open_search()
|
||||
panel.field.text = "loot"
|
||||
panel.refresh()
|
||||
main.delete_table("b")
|
||||
main.undo()
|
||||
await _frames()
|
||||
_check(is_equal_approx(main.board.zoom, 0.6) and main.board.world.position == Vector2(-123, 45), "zoom and pan stay")
|
||||
_check(main.lit_entries.has("a:e1") and main.lit_entries.has("b:e1") and main.is_entry_lit("b", "e1"), "lit results stay lit, also on the table brought back")
|
||||
_check(panel.visible and panel.field.text == "loot", "the search stays open")
|
||||
_check(main.mode == Main.Mode.BUILD, "and the mode stays")
|
||||
panel.close()
|
||||
main.lit_entries.clear()
|
||||
# A change on screen flashes.
|
||||
main.board.fit()
|
||||
await _frames()
|
||||
main.add_entry("a")
|
||||
main.undo()
|
||||
await _frames(3)
|
||||
_check(main.board.cards.is_flashing() and main.board.cards.flash_rect() == Rect2(main.card_for("a").position, main.card_for("a").size), "the changed card flashes")
|
||||
|
||||
|
||||
func _test_toast() -> void:
|
||||
print("Toast Undo")
|
||||
main.delete_entry("a", "e2")
|
||||
_check(main._toast.visible and main._toast_undo.visible, "deleting shows an undo toast")
|
||||
main._toast_undo.pressed.emit()
|
||||
_check(_t("a").find_entry("e2") != null and main.edits.can_redo(), "its Undo goes through the history (redo is offered)")
|
||||
main.redo()
|
||||
main.undo()
|
||||
main.delete_table("b")
|
||||
_check(main._toast_undo.visible, "another undo toast")
|
||||
main.add_entry("a")
|
||||
_check(not main._toast_undo.visible, "a newer edit hides the toast's Undo, so it can't undo the wrong thing")
|
||||
main.undo()
|
||||
main.undo()
|
||||
_check(_t("b") != null, "undo twice brings the table back")
|
||||
|
||||
|
||||
func _test_lazy_cards() -> void:
|
||||
print("Lazily built cards")
|
||||
main.set_group_collapsed("g1", true)
|
||||
await _frames(3)
|
||||
_check(main.card_for("c") == null, "Weapons is hidden in the collapsed group, with no card")
|
||||
_t("c").entries[0].text = "Axe"
|
||||
main.mark_dirty()
|
||||
await _frames()
|
||||
_check(_label() == "Edit Weapons", "an edit to a hidden card is a step: %s" % _label())
|
||||
main.undo()
|
||||
await _frames(3)
|
||||
_check(_t("c").entries[0].text == "Sword" and main.card_for("c") == null, "undo restores it and still doesn't build the card")
|
||||
_check(main.data.get_group("g1").collapsed and main.group_node("g1") != null, "the group stays collapsed")
|
||||
main.delete_group("g1")
|
||||
main.undo()
|
||||
await _frames(3)
|
||||
_check(main.data.get_group("g1").collapsed and main.card_for("c") == null, "a deleted collapsed group comes back collapsed, cards unbuilt")
|
||||
main.set_group_collapsed("g1", false)
|
||||
await _frames(3)
|
||||
var c := main.card_for("c")
|
||||
_check(c != null and c.visible and _line_edit_with(c, "Sword") != null, "expanding it builds the restored card")
|
||||
|
||||
|
||||
func _test_collapse_not_undoable() -> void:
|
||||
print("Collapsing isn't a step")
|
||||
var n0 := _steps()
|
||||
main.toggle_collapse("a")
|
||||
main.set_all_collapsed(true)
|
||||
main.set_all_collapsed(false)
|
||||
main.toggle_collapse("b")
|
||||
await _frames()
|
||||
_check(_steps() == n0, "collapsing and expanding add no steps")
|
||||
main.add_entry("a")
|
||||
main.undo()
|
||||
_check(_t("b").collapsed, "undo leaves Gems collapsed as it is")
|
||||
main.toggle_collapse("b")
|
||||
|
||||
|
||||
func _test_shortcuts_and_buttons() -> void:
|
||||
print("Shortcuts and buttons")
|
||||
main.add_entry("a")
|
||||
_check(not main._undo_button.disabled and main._undo_button.tooltip_text == "Undo: Add result to Loot (Ctrl+Z)", "the Undo button names the step: %s" % main._undo_button.tooltip_text)
|
||||
_check(main._redo_button.disabled, "Redo is disabled with nothing to redo")
|
||||
main._shortcut_input(_key(KEY_Z, false))
|
||||
_check(_t("a").entries.size() == 2, "Ctrl+Z undoes")
|
||||
_check(not main._redo_button.disabled and main._redo_button.tooltip_text.begins_with("Redo: Add result to Loot"), "Redo is enabled and named: %s" % main._redo_button.tooltip_text)
|
||||
main._shortcut_input(_key(KEY_Z, true))
|
||||
_check(_t("a").entries.size() == 3, "Ctrl+Shift+Z redoes")
|
||||
main._shortcut_input(_key(KEY_Z, false))
|
||||
main._shortcut_input(_key(KEY_Y, false))
|
||||
_check(_t("a").entries.size() == 3, "Ctrl+Y redoes too")
|
||||
var le := _line_edit_with(main.card_for("a"), "Loot")
|
||||
le.grab_focus()
|
||||
main._shortcut_input(_key(KEY_Z, false))
|
||||
_check(_t("a").entries.size() == 3, "with a text field focused, Ctrl+Z is left to the field")
|
||||
le.release_focus()
|
||||
main._undo_button.pressed.emit()
|
||||
_check(_t("a").entries.size() == 2, "the Undo button undoes")
|
||||
while main.edits.can_undo():
|
||||
main.undo()
|
||||
_check(main._undo_button.disabled and main._undo_button.tooltip_text == "Nothing to undo", "with nothing left, Undo is disabled")
|
||||
main.redo()
|
||||
|
||||
|
||||
func _key(code: Key, shift: bool) -> InputEventKey:
|
||||
var k := InputEventKey.new()
|
||||
k.keycode = code
|
||||
k.ctrl_pressed = true
|
||||
k.shift_pressed = shift
|
||||
k.pressed = true
|
||||
return k
|
||||
|
||||
|
||||
func _test_play_mode() -> void:
|
||||
print("Play mode")
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
var card := main.card_for("b")
|
||||
var p0 := card.position
|
||||
main.begin_card_drag(card)
|
||||
main.drag_card(card, p0 + Vector2(200, 0))
|
||||
main.end_card_drag(card)
|
||||
await _frames()
|
||||
_check(_label() == "Move Gems", "moving a card in Play is a step too")
|
||||
main._shortcut_input(_key(KEY_Z, false))
|
||||
_check(_t("b").position == p0 and main.mode == Main.Mode.PLAY, "Ctrl+Z undoes it in Play, staying in Play")
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
|
||||
|
||||
func _test_collections() -> void:
|
||||
print("Per-collection history")
|
||||
main.add_entry("a")
|
||||
var first := main.data
|
||||
var h := main.edits
|
||||
var other := TowerBoard.new()
|
||||
other.load_dict({"format_version": 2, "id": "other", "name": "Other", "tables": [
|
||||
{"id": "x", "name": "X", "x": 0, "y": 0, "entries": [{"id": "e1", "text": "x"}]}]})
|
||||
await main._show_collection(other)
|
||||
_check(main.edits != h and not main.edits.can_undo(), "another collection has its own, empty history")
|
||||
main.add_entry("x")
|
||||
_check(main.edits.undo_label() == "Add result to X", "edits there go to its history")
|
||||
await main._show_collection(first)
|
||||
_check(main.edits == h and main.edits.undo_label() == "Add result to Loot", "switching back keeps the first history")
|
||||
var n_before := _t("a").entries.size()
|
||||
main.undo()
|
||||
_check(_t("a").entries.size() == n_before - 1, "and undo still works: %d -> %d" % [n_before, _t("a").entries.size()])
|
||||
|
||||
|
||||
func _test_big_board() -> void:
|
||||
print("Big board")
|
||||
var d: Dictionary = {}
|
||||
var path := ""
|
||||
for a in OS.get_cmdline_user_args():
|
||||
if a.begins_with("--big-board="):
|
||||
path = a.trim_prefix("--big-board=")
|
||||
if path != "" and FileAccess.file_exists(path):
|
||||
d = JSON.parse_string(FileAccess.get_file_as_string(path))
|
||||
else:
|
||||
d = _synthetic_board(800)
|
||||
await _load(d)
|
||||
var t := main.data.tables[main.data.tables.size() / 2]
|
||||
var u := main.data.tables[main.data.tables.size() / 3]
|
||||
var n := main.data.tables.size()
|
||||
var full := EditHistory.full_bytes(main.edits.cache)
|
||||
# One committed edit: what typing costs once it pauses.
|
||||
t.name = t.name + " (edited)"
|
||||
main.mark_dirty()
|
||||
var t1 := Time.get_ticks_usec()
|
||||
main._commit_edits()
|
||||
var commit_ms := (Time.get_ticks_usec() - t1) / 1000.0
|
||||
var cap_ms := main.edits.last_capture_usec / 1000.0
|
||||
u.name = u.name + " (edited)"
|
||||
main.mark_dirty()
|
||||
main._commit_edits()
|
||||
# The oldest step holds the whole board; later ones only what changed.
|
||||
var step_bytes := int(main.edits.undo_stack.back()["snap"]["bytes"])
|
||||
# A keystroke: the history's part (restarting a timer) against all of mark_dirty.
|
||||
var le := LineEdit.new()
|
||||
main.add_child(le)
|
||||
le.grab_focus()
|
||||
var t2 := Time.get_ticks_usec()
|
||||
for i in 20:
|
||||
t.name += "x"
|
||||
main.mark_dirty()
|
||||
var key_ms := (Time.get_ticks_usec() - t2) / 1000.0 / 20.0
|
||||
var t4 := Time.get_ticks_usec()
|
||||
for i in 20:
|
||||
main._board_changed()
|
||||
var base_ms := (Time.get_ticks_usec() - t4) / 1000.0 / 20.0
|
||||
_check(main.edits.undo_stack.size() == 2, "keystrokes in a text field don't commit until typing pauses")
|
||||
le.release_focus()
|
||||
le.queue_free()
|
||||
main._commit_edits()
|
||||
var t3 := Time.get_ticks_usec()
|
||||
main.undo()
|
||||
var undo_ms := (Time.get_ticks_usec() - t3) / 1000.0
|
||||
var undo_one_ms := main._last_restore_usec / 1000.0
|
||||
# Undoing a deletion rebuilds the whole board.
|
||||
main.delete_table(u.id)
|
||||
var t5 := Time.get_ticks_usec()
|
||||
main.undo()
|
||||
var undo_del_ms := (Time.get_ticks_usec() - t5) / 1000.0
|
||||
_check(_t(u.id) != null, "undoing a deletion on the big board brings the card back")
|
||||
print(" TIMING %d cards: one committed edit %.1f ms (snapshot %.1f ms); keystroke %.2f ms, of which mark_dirty's existing refresh %.2f ms; undo of an edit %.1f ms (board update %.1f ms); undo of a deletion %.1f ms; board %d chars, later step %d bytes" % [
|
||||
n, commit_ms, cap_ms, key_ms, base_ms, undo_ms, undo_one_ms, undo_del_ms, full, step_bytes])
|
||||
_check(commit_ms < 250.0, "committing one edit stays quick: %.1f ms" % commit_ms)
|
||||
_check(key_ms - base_ms < 1.0, "a keystroke doesn't snapshot the board: %.2f ms over %.2f ms" % [key_ms, base_ms])
|
||||
_check(step_bytes < full / 10, "a later step stores only the changed cards: %d of %d" % [step_bytes, full])
|
||||
_check(_t(t.id).name.ends_with("(edited)") and not _t(t.id).name.ends_with("x"), "undo works on the big board")
|
||||
|
||||
|
||||
func _synthetic_board(n: int) -> Dictionary:
|
||||
var tables: Array = []
|
||||
var groups: Array = []
|
||||
for i in n:
|
||||
var entries: Array = []
|
||||
for j in 8:
|
||||
entries.append({"id": "e%d" % j, "text": "Result %d of table %d with some text" % [j, i], "pipes": ["t%d" % ((i + 1) % n)] if j == 0 else []})
|
||||
tables.append({"id": "t%d" % i, "name": "Table %d" % i, "x": (i % 40) * 300, "y": (i / 40) * 400, "entries": entries})
|
||||
for k in n / 40:
|
||||
var members: Array = []
|
||||
for i in range(k * 40, k * 40 + 40):
|
||||
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}
|
||||
1
tests/test_undo.gd.uid
Normal file
1
tests/test_undo.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://6w0wkvln8c5d
|
||||
|
|
@ -276,6 +276,10 @@ func _gui_input(ev: InputEvent) -> void:
|
|||
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE:
|
||||
var build_left := mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD
|
||||
if mb.pressed:
|
||||
# Clicking the felt leaves a text field, so Ctrl+Z undoes on the board.
|
||||
var f := get_viewport().gui_get_focus_owner()
|
||||
if f is LineEdit or f is TextEdit:
|
||||
f.release_focus()
|
||||
if build_left and (mb.ctrl_pressed or mb.meta_pressed):
|
||||
# Ctrl-drag on the felt: rubber-band selection.
|
||||
_banding = true
|
||||
|
|
|
|||
|
|
@ -22,6 +22,8 @@ var far := false
|
|||
var _shadow: StyleBoxFlat
|
||||
var _ring: StyleBoxFlat
|
||||
var _flash_node: Control = null
|
||||
## More nodes ringed along with _flash_node (flash_all: an undo's changes).
|
||||
var _flash_extra: Array[Control] = []
|
||||
var _flash_row: Rect2 = Rect2()
|
||||
var _flash_left := 0.0
|
||||
|
||||
|
|
@ -51,6 +53,7 @@ func _draw() -> void:
|
|||
## Flashes a ring around `node` (a TableCard or GroupCard) for FLASH_TIME.
|
||||
## `row` is a world rect inside it to ring as well (Rect2() for none).
|
||||
func flash(node: Control, row: Rect2 = Rect2()) -> void:
|
||||
_flash_extra.clear()
|
||||
_flash_node = node
|
||||
_flash_row = row
|
||||
_flash_left = FLASH_TIME
|
||||
|
|
@ -58,6 +61,14 @@ func flash(node: Control, row: Rect2 = Rect2()) -> void:
|
|||
overlay.queue_redraw()
|
||||
|
||||
|
||||
## Flashes rings around several nodes at once (none: nothing happens).
|
||||
func flash_all(nodes: Array[Control]) -> void:
|
||||
if nodes.is_empty():
|
||||
return
|
||||
flash(nodes[0])
|
||||
_flash_extra = nodes.slice(1)
|
||||
|
||||
|
||||
func is_flashing() -> bool:
|
||||
return _flash_left > 0.0 and is_instance_valid(_flash_node)
|
||||
|
||||
|
|
@ -78,6 +89,7 @@ func _process(delta: float) -> void:
|
|||
overlay.queue_redraw()
|
||||
if _flash_left <= 0.0:
|
||||
_flash_node = null
|
||||
_flash_extra.clear()
|
||||
set_process(false)
|
||||
|
||||
|
||||
|
|
@ -90,10 +102,16 @@ func _draw_flash() -> void:
|
|||
# Two quick pulses, then a fade.
|
||||
var pulse := 0.65 + 0.35 * cos((1.0 - t) * TAU * 2.0)
|
||||
var a := minf(1.0, t * 2.5) * pulse
|
||||
var r := Rect2(_flash_node.position, _flash_node.size).grow(8.0)
|
||||
overlay.draw_style_box(_glow_box(a), r.grow(6.0))
|
||||
_ring.border_color = Color(Style.BRASS, a)
|
||||
overlay.draw_style_box(_ring, r)
|
||||
var glow := _glow_box(a)
|
||||
for v: Variant in [_flash_node] + _flash_extra:
|
||||
if not is_instance_valid(v):
|
||||
continue
|
||||
var n := v as Control
|
||||
if n.visible:
|
||||
var r := Rect2(n.position, n.size).grow(8.0)
|
||||
overlay.draw_style_box(glow, r.grow(6.0))
|
||||
overlay.draw_style_box(_ring, r)
|
||||
if _flash_row.size != Vector2.ZERO:
|
||||
overlay.draw_rect(_flash_row, Color(Style.BRASS, 0.28 * a))
|
||||
overlay.draw_rect(_flash_row, Color(Style.BRASS_DARK, a), false, 2.5)
|
||||
|
|
|
|||
596
ui/edit_history.gd
Normal file
596
ui/edit_history.gd
Normal file
|
|
@ -0,0 +1,596 @@
|
|||
class_name EditHistory
|
||||
extends RefCounted
|
||||
## Undo and redo for one collection's Build edits: a stack of whole-board
|
||||
## snapshots each way, plus `cache`, the snapshot of the last committed state
|
||||
## (the "before" of the next edit). Main keeps one per collection.
|
||||
##
|
||||
## A snapshot holds each table and group as its own compact JSON string, with
|
||||
## the collapsed flags kept apart (collapsing is view state, not an edit; see
|
||||
## restore). A table that didn't change shares its string with the snapshot
|
||||
## before it (Godot strings are copy-on-write), so a step costs roughly the
|
||||
## size of the cards it changed, not the whole board.
|
||||
##
|
||||
## Step labels come from diffing the snapshots on either side of the step
|
||||
## (label_for), unless the caller gives one.
|
||||
|
||||
## Most steps kept, and roughly the most memory they may use between them.
|
||||
const MAX_STEPS := 200
|
||||
const MAX_BYTES := 48 * 1024 * 1024
|
||||
## Edits to the same thing this close together become one step.
|
||||
const COALESCE_SECS := 0.8
|
||||
|
||||
var undo_stack: Array[Dictionary] = [] # {snap, label, key, time, focus, serial}
|
||||
var redo_stack: Array[Dictionary] = [] # {snap, label, serial}
|
||||
var cache: Dictionary = {}
|
||||
## How long the last capture took (microseconds), and its size in characters.
|
||||
var last_capture_usec := 0
|
||||
var _serial := 0
|
||||
|
||||
|
||||
func _init(board: TowerBoard = null) -> void:
|
||||
if board:
|
||||
cache = capture(board)
|
||||
|
||||
|
||||
func can_undo() -> bool:
|
||||
return not undo_stack.is_empty()
|
||||
|
||||
|
||||
func can_redo() -> bool:
|
||||
return not redo_stack.is_empty()
|
||||
|
||||
|
||||
func undo_label() -> String:
|
||||
return str(undo_stack.back()["label"]) if can_undo() else ""
|
||||
|
||||
|
||||
func redo_label() -> String:
|
||||
return str(redo_stack.back()["label"]) if can_redo() else ""
|
||||
|
||||
|
||||
## The serial of the newest undo step (-1 when there is none).
|
||||
func top_serial() -> int:
|
||||
return int(undo_stack.back()["serial"]) if can_undo() else -1
|
||||
|
||||
|
||||
func clear() -> void:
|
||||
undo_stack.clear()
|
||||
redo_stack.clear()
|
||||
|
||||
|
||||
## Takes the board as the new baseline. If it differs from the cached state
|
||||
## (the collection was replaced from outside), the history no longer applies
|
||||
## and is cleared.
|
||||
func resync(board: TowerBoard) -> void:
|
||||
var snap := capture(board, cache)
|
||||
if cache.is_empty() or not is_empty_diff(diff(cache, snap)):
|
||||
clear()
|
||||
cache = snap
|
||||
|
||||
|
||||
## Records the board's current state. Returns {step, merged, label, diff}:
|
||||
## `step` is false when nothing undoable changed (only collapsing, or group
|
||||
## frames refitting around their cards), in which case the baseline just
|
||||
## catches up. Without a `label`, an edit to the same single thing as the
|
||||
## newest step merges into it when it comes within COALESCE_SECS or from the
|
||||
## same text field (`focus`, an instance id, 0 for none).
|
||||
func commit(board: TowerBoard, label: String = "", focus: int = 0, now: float = -1.0) -> Dictionary:
|
||||
if now < 0.0:
|
||||
now = Time.get_ticks_msec() / 1000.0
|
||||
var t0 := Time.get_ticks_usec()
|
||||
var snap := capture(board, cache)
|
||||
last_capture_usec = Time.get_ticks_usec() - t0
|
||||
var d := diff(cache, snap)
|
||||
if is_empty_diff(d):
|
||||
# The old baseline goes, but strings it shared with the stacks stay
|
||||
# with the new one: count them there.
|
||||
snap["bytes"] = mini(int(snap["bytes"]) + int(cache.get("bytes", 0)), full_bytes(snap))
|
||||
cache = snap
|
||||
return {"step": false, "merged": false, "label": "", "diff": d}
|
||||
var key := coalesce_key(cache, snap, d) if label == "" else ""
|
||||
if key != "" and can_undo() and redo_stack.is_empty():
|
||||
var top: Dictionary = undo_stack.back()
|
||||
if str(top["key"]) == key and (now - float(top["time"]) < COALESCE_SECS or (focus != 0 and focus == int(top["focus"]))):
|
||||
var d2 := diff(top["snap"], snap)
|
||||
cache = snap
|
||||
if is_empty_diff(d2):
|
||||
# Typed and then put back: nothing left to undo.
|
||||
undo_stack.pop_back()
|
||||
return {"step": true, "merged": true, "label": "", "diff": d}
|
||||
top["label"] = label_for(top["snap"], snap, d2)
|
||||
top["time"] = now
|
||||
top["focus"] = focus
|
||||
return {"step": true, "merged": true, "label": top["label"], "diff": d}
|
||||
redo_stack.clear()
|
||||
_serial += 1
|
||||
var lbl := label if label != "" else label_for(cache, snap, d)
|
||||
undo_stack.push_back({"snap": cache, "label": lbl, "key": key, "time": now, "focus": focus, "serial": _serial})
|
||||
cache = snap
|
||||
_trim()
|
||||
return {"step": true, "merged": false, "label": lbl, "diff": d}
|
||||
|
||||
|
||||
## Pops the newest step for undoing: returns {snap (to restore), label, from
|
||||
## (the state being left)} and moves the current state onto the redo stack.
|
||||
## The caller restores `snap` and then sets `cache` (restore's result).
|
||||
func pop_undo() -> Dictionary:
|
||||
var e: Dictionary = undo_stack.pop_back()
|
||||
redo_stack.push_back({"snap": cache, "label": e["label"], "serial": e["serial"]})
|
||||
return {"snap": e["snap"], "label": e["label"], "from": cache}
|
||||
|
||||
|
||||
func pop_redo() -> Dictionary:
|
||||
var e: Dictionary = redo_stack.pop_back()
|
||||
undo_stack.push_back({"snap": cache, "label": e["label"], "key": "", "time": 0.0, "focus": 0, "serial": e["serial"]})
|
||||
return {"snap": e["snap"], "label": e["label"], "from": cache}
|
||||
|
||||
|
||||
## Rough memory held by the stacks (unshared characters plus per-card overhead).
|
||||
func bytes() -> int:
|
||||
var n := 0
|
||||
for e in undo_stack:
|
||||
n += int(e["snap"].get("bytes", 0))
|
||||
for e in redo_stack:
|
||||
n += int(e["snap"].get("bytes", 0))
|
||||
return n
|
||||
|
||||
|
||||
func _trim() -> void:
|
||||
while undo_stack.size() > MAX_STEPS:
|
||||
undo_stack.pop_front()
|
||||
var total := bytes()
|
||||
while undo_stack.size() > 1 and total > MAX_BYTES:
|
||||
total -= int(undo_stack[0]["snap"].get("bytes", 0))
|
||||
undo_stack.pop_front()
|
||||
|
||||
|
||||
# ---------- Snapshots ----------
|
||||
|
||||
## The board as {ids, tables, gids, groups, collapsed, bytes}. Strings equal
|
||||
## to the ones in `prev` are shared with it; `bytes` counts the rest.
|
||||
static func capture(board: TowerBoard, prev: Dictionary = {}) -> Dictionary:
|
||||
var old_t := _strings_by_id(prev, "ids", "tables")
|
||||
var old_g := _strings_by_id(prev, "gids", "groups")
|
||||
var ids := PackedStringArray()
|
||||
var tables := PackedStringArray()
|
||||
var gids := PackedStringArray()
|
||||
var groups := PackedStringArray()
|
||||
var collapsed := {}
|
||||
var n := 0
|
||||
for t in board.tables:
|
||||
var d := t.to_dict()
|
||||
d.erase("collapsed")
|
||||
var s := JSON.stringify(d)
|
||||
var o: Variant = old_t.get(t.id)
|
||||
if o != null and o == s:
|
||||
s = o
|
||||
else:
|
||||
n += s.length()
|
||||
ids.append(t.id)
|
||||
tables.append(s)
|
||||
if t.collapsed:
|
||||
collapsed["t:" + t.id] = true
|
||||
for g in board.groups:
|
||||
var d := g.to_dict()
|
||||
d.erase("collapsed")
|
||||
var s := JSON.stringify(d)
|
||||
var o: Variant = old_g.get(g.id)
|
||||
if o != null and o == s:
|
||||
s = o
|
||||
else:
|
||||
n += s.length()
|
||||
gids.append(g.id)
|
||||
groups.append(s)
|
||||
if g.collapsed:
|
||||
collapsed["g:" + g.id] = true
|
||||
n += (ids.size() + gids.size()) * 16
|
||||
return {"ids": ids, "tables": tables, "gids": gids, "groups": groups, "collapsed": collapsed, "bytes": n}
|
||||
|
||||
|
||||
## A snapshot's size if it shared nothing.
|
||||
static func full_bytes(snap: Dictionary) -> int:
|
||||
var n := 0
|
||||
for k in ["tables", "groups"]:
|
||||
for s in (snap[k] as PackedStringArray):
|
||||
n += s.length()
|
||||
return n + ((snap["ids"] as PackedStringArray).size() + (snap["gids"] as PackedStringArray).size()) * 16
|
||||
|
||||
|
||||
static func _strings_by_id(snap: Dictionary, ids_key: String, strs_key: String) -> Dictionary:
|
||||
var out := {}
|
||||
if snap.is_empty():
|
||||
return out
|
||||
var ids: PackedStringArray = snap[ids_key]
|
||||
var strs: PackedStringArray = snap[strs_key]
|
||||
for i in ids.size():
|
||||
out[ids[i]] = strs[i]
|
||||
return out
|
||||
|
||||
|
||||
## Replaces the board's tables and groups with the snapshot's. Collapsing
|
||||
## isn't undone: tables and groups that exist now keep their collapsed state;
|
||||
## ones brought back take the state they had. The collection's id and name
|
||||
## stay. Returns the snapshot with its collapsed flags as applied.
|
||||
static func restore(board: TowerBoard, snap: Dictionary) -> Dictionary:
|
||||
var now := {}
|
||||
for t in board.tables:
|
||||
now["t:" + t.id] = t.collapsed
|
||||
for g in board.groups:
|
||||
now["g:" + g.id] = g.collapsed
|
||||
var was: Dictionary = snap["collapsed"]
|
||||
var collapsed := {}
|
||||
var tables: Array = []
|
||||
var ids: PackedStringArray = snap["ids"]
|
||||
var strs: PackedStringArray = snap["tables"]
|
||||
for i in ids.size():
|
||||
var d: Dictionary = JSON.parse_string(strs[i])
|
||||
var k := "t:" + ids[i]
|
||||
if (bool(now[k]) if now.has(k) else was.has(k)):
|
||||
d["collapsed"] = true
|
||||
collapsed[k] = true
|
||||
tables.append(d)
|
||||
var groups: Array = []
|
||||
var gids: PackedStringArray = snap["gids"]
|
||||
var gstrs: PackedStringArray = snap["groups"]
|
||||
for i in gids.size():
|
||||
var d: Dictionary = JSON.parse_string(gstrs[i])
|
||||
var k := "g:" + gids[i]
|
||||
if (bool(now[k]) if now.has(k) else was.has(k)):
|
||||
d["collapsed"] = true
|
||||
collapsed[k] = true
|
||||
groups.append(d)
|
||||
board.load_dict({"format_version": TowerBoard.FORMAT_VERSION, "tables": tables, "groups": groups})
|
||||
var out := snap.duplicate()
|
||||
out["collapsed"] = collapsed
|
||||
return out
|
||||
|
||||
|
||||
## Restores a snapshot by touching only what differs from `from` (the board's
|
||||
## current snapshot): tables and groups whose text changed are updated in
|
||||
## place, new ones are made and missing ones dropped, so every other object
|
||||
## (and the card showing it) stays. Collapsed flags as in restore. Returns
|
||||
## {snap (as restore), tables (ids updated in place), added, removed, groups
|
||||
## (ids updated in place), groups_changed (true when any group came, went or
|
||||
## changed more than its frame)}, or {} without a `from`.
|
||||
static func patch(board: TowerBoard, snap: Dictionary, from: Dictionary) -> Dictionary:
|
||||
if from.is_empty():
|
||||
return {}
|
||||
var old_t := _strings_by_id(from, "ids", "tables")
|
||||
var old_g := _strings_by_id(from, "gids", "groups")
|
||||
var was: Dictionary = snap["collapsed"]
|
||||
var collapsed := {}
|
||||
var by_id := {}
|
||||
for t in board.tables:
|
||||
by_id[t.id] = t
|
||||
var ids: PackedStringArray = snap["ids"]
|
||||
var strs: PackedStringArray = snap["tables"]
|
||||
var tables: Array[RollTable] = []
|
||||
var updated: Array = []
|
||||
var added: Array = []
|
||||
for i in ids.size():
|
||||
var t: RollTable = by_id.get(ids[i])
|
||||
if t == null:
|
||||
t = RollTable.from_dict(JSON.parse_string(strs[i]))
|
||||
t.collapsed = was.has("t:" + ids[i])
|
||||
added.append(t.id)
|
||||
elif old_t.get(t.id) != strs[i]:
|
||||
var fresh := RollTable.from_dict(JSON.parse_string(strs[i]))
|
||||
fresh.collapsed = t.collapsed
|
||||
_copy_fields(fresh, t)
|
||||
updated.append(t.id)
|
||||
by_id.erase(ids[i])
|
||||
if t.collapsed:
|
||||
collapsed["t:" + t.id] = true
|
||||
tables.append(t)
|
||||
var removed: Array = by_id.keys()
|
||||
var gby_id := {}
|
||||
for g in board.groups:
|
||||
gby_id[g.id] = g
|
||||
var gids: PackedStringArray = snap["gids"]
|
||||
var gstrs: PackedStringArray = snap["groups"]
|
||||
var groups: Array[TableGroup] = []
|
||||
var gupdated: Array = []
|
||||
var regroup := false
|
||||
for i in gids.size():
|
||||
var g: TableGroup = gby_id.get(gids[i])
|
||||
if g == null:
|
||||
g = TableGroup.from_dict(JSON.parse_string(gstrs[i]))
|
||||
g.collapsed = was.has("g:" + gids[i])
|
||||
regroup = true
|
||||
elif old_g.get(g.id) != gstrs[i]:
|
||||
var fresh := TableGroup.from_dict(JSON.parse_string(gstrs[i]))
|
||||
fresh.collapsed = g.collapsed
|
||||
if fresh.name != g.name or fresh.details != g.details or fresh.members != g.members:
|
||||
regroup = true
|
||||
_copy_fields(fresh, g)
|
||||
gupdated.append(g.id)
|
||||
gby_id.erase(gids[i])
|
||||
if g.collapsed:
|
||||
collapsed["g:" + g.id] = true
|
||||
groups.append(g)
|
||||
if not gby_id.is_empty():
|
||||
regroup = true
|
||||
board.tables = tables
|
||||
board.groups = groups
|
||||
var out := snap.duplicate()
|
||||
out["collapsed"] = collapsed
|
||||
return {"snap": out, "tables": updated, "added": added, "removed": removed, "groups": gupdated, "groups_changed": regroup}
|
||||
|
||||
|
||||
## Copies every script variable of `src` onto `dst` (same class).
|
||||
static func _copy_fields(src: Object, dst: Object) -> void:
|
||||
for p: Dictionary in src.get_property_list():
|
||||
if int(p["usage"]) & PROPERTY_USAGE_SCRIPT_VARIABLE:
|
||||
dst.set(p["name"], src.get(p["name"]))
|
||||
|
||||
|
||||
# ---------- Diffs and labels ----------
|
||||
|
||||
## What changed from snapshot a to b, by id: tables added, removed, changed
|
||||
## (anything but position) and moved (position only); groups likewise, where
|
||||
## gmoved (frame only) is ignored for groups with members, whose frames
|
||||
## follow their cards.
|
||||
static func diff(a: Dictionary, b: Dictionary) -> Dictionary:
|
||||
var out := {"added": [], "removed": [], "changed": [], "moved": [],
|
||||
"gadded": [], "gremoved": [], "gchanged": [], "gmoved": [], "gmoved_empty": []}
|
||||
_diff_lists(_strings_by_id(a, "ids", "tables"), _strings_by_id(b, "ids", "tables"),
|
||||
["x", "y"], out, "added", "removed", "changed", "moved")
|
||||
_diff_lists(_strings_by_id(a, "gids", "groups"), _strings_by_id(b, "gids", "groups"),
|
||||
["x", "y", "w", "h"], out, "gadded", "gremoved", "gchanged", "gmoved")
|
||||
var gb := _strings_by_id(b, "gids", "groups")
|
||||
for gid: String in out["gmoved"]:
|
||||
var d: Variant = JSON.parse_string(gb[gid])
|
||||
if d is Dictionary and (d.get("members", []) as Array).is_empty():
|
||||
out["gmoved_empty"].append(gid)
|
||||
return out
|
||||
|
||||
|
||||
static func _diff_lists(ma: Dictionary, mb: Dictionary, geometry: Array, out: Dictionary,
|
||||
k_add: String, k_rem: String, k_chg: String, k_mov: String) -> void:
|
||||
for id: String in mb:
|
||||
if not ma.has(id):
|
||||
out[k_add].append(id)
|
||||
elif ma[id] != mb[id]:
|
||||
var da: Dictionary = JSON.parse_string(ma[id])
|
||||
var db: Dictionary = JSON.parse_string(mb[id])
|
||||
for g: String in geometry:
|
||||
da.erase(g)
|
||||
db.erase(g)
|
||||
out[k_chg if da != db else k_mov].append(id)
|
||||
for id: String in ma:
|
||||
if not mb.has(id):
|
||||
out[k_rem].append(id)
|
||||
|
||||
|
||||
static func is_empty_diff(d: Dictionary) -> bool:
|
||||
for k in ["added", "removed", "changed", "moved", "gadded", "gremoved", "gchanged", "gmoved_empty"]:
|
||||
if not (d[k] as Array).is_empty():
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Table ids whose cards changed in any way (added, changed or moved).
|
||||
static func touched_tables(d: Dictionary) -> Array:
|
||||
return (d["added"] as Array) + (d["changed"] as Array) + (d["moved"] as Array)
|
||||
|
||||
|
||||
## A key for edits that may merge with the step before: one table's or one
|
||||
## group's fields (text, weight, pipe options...), with nothing added or taken
|
||||
## away. "" for anything else.
|
||||
static func coalesce_key(a: Dictionary, b: Dictionary, d: Dictionary) -> String:
|
||||
for k in ["added", "removed", "moved", "gadded", "gremoved", "gmoved_empty"]:
|
||||
if not (d[k] as Array).is_empty():
|
||||
return ""
|
||||
var ch: Array = d["changed"]
|
||||
var gch: Array = d["gchanged"]
|
||||
if ch.size() == 1 and gch.is_empty():
|
||||
var ta: Dictionary = _parsed(a, "ids", "tables", ch[0])
|
||||
var tb: Dictionary = _parsed(b, "ids", "tables", ch[0])
|
||||
var e := _entry_changes(ta, tb)
|
||||
if e["added"].is_empty() and e["removed"].is_empty() and e["pipes_added"].is_empty() and e["pipes_removed"].is_empty():
|
||||
return "t:" + str(ch[0])
|
||||
elif gch.size() == 1 and ch.is_empty():
|
||||
var ga: Dictionary = _parsed(a, "gids", "groups", gch[0])
|
||||
var gb: Dictionary = _parsed(b, "gids", "groups", gch[0])
|
||||
if ga.get("members") == gb.get("members"):
|
||||
return "g:" + str(gch[0])
|
||||
return ""
|
||||
|
||||
|
||||
## Describes the step from a to b ("Edit Loot", "Delete table Weapons", "Add
|
||||
## pipe Loot → Gems", "Move 3 cards", "Group Careers"...).
|
||||
static func label_for(a: Dictionary, b: Dictionary, d: Dictionary = {}) -> String:
|
||||
if d.is_empty():
|
||||
d = diff(a, b)
|
||||
var added: Array = d["added"]
|
||||
var removed: Array = d["removed"]
|
||||
var gadded: Array = d["gadded"]
|
||||
var gremoved: Array = d["gremoved"]
|
||||
if not gadded.is_empty() and not added.is_empty():
|
||||
return "Add %s" % _count(added.size(), "card")
|
||||
if gadded.size() == 1:
|
||||
return "Group %s" % _name(b, "gids", "groups", gadded[0])
|
||||
if gremoved.size() == 1:
|
||||
var gname := _name(a, "gids", "groups", gremoved[0])
|
||||
return ("Delete group %s" if not removed.is_empty() else "Ungroup %s") % gname
|
||||
if not gadded.is_empty() or not gremoved.is_empty():
|
||||
return "Change groups"
|
||||
if added.size() == 1:
|
||||
return "Add %s %s" % [_kind_word(_parsed(b, "ids", "tables", added[0])), _name(b, "ids", "tables", added[0])]
|
||||
if not added.is_empty():
|
||||
return "Add %s" % _count(added.size(), "card")
|
||||
if removed.size() == 1:
|
||||
return "Delete %s %s" % [_kind_word(_parsed(a, "ids", "tables", removed[0])), _name(a, "ids", "tables", removed[0])]
|
||||
if not removed.is_empty():
|
||||
return "Delete %s" % _count(removed.size(), "card")
|
||||
var changed: Array = d["changed"]
|
||||
var gchanged: Array = d["gchanged"]
|
||||
# Group membership (a card dragged into or out of a group).
|
||||
for gid: String in gchanged:
|
||||
var ga := _parsed(a, "gids", "groups", gid)
|
||||
var gb := _parsed(b, "gids", "groups", gid)
|
||||
var ma: Array = ga.get("members", [])
|
||||
var mb: Array = gb.get("members", [])
|
||||
if ma != mb:
|
||||
var ins := 0
|
||||
var outs := 0
|
||||
for m: Variant in mb:
|
||||
if not ma.has(m):
|
||||
ins += 1
|
||||
for m: Variant in ma:
|
||||
if not mb.has(m):
|
||||
outs += 1
|
||||
var gname := Formatter.strip_tags(str(gb.get("name", "")))
|
||||
if ins > 0 and outs == 0:
|
||||
return "Add %s to group %s" % [_count(ins, "card"), gname]
|
||||
if outs > 0 and ins == 0:
|
||||
return "Take %s out of group %s" % [_count(outs, "card"), gname]
|
||||
return "Change group %s" % gname
|
||||
if changed.size() == 1:
|
||||
return _table_label(_parsed(a, "ids", "tables", changed[0]), _parsed(b, "ids", "tables", changed[0]), b)
|
||||
if changed.size() > 1:
|
||||
return "Edit %s" % _count(changed.size(), "card")
|
||||
if gchanged.size() == 1:
|
||||
var ga := _parsed(a, "gids", "groups", gchanged[0])
|
||||
var gb := _parsed(b, "gids", "groups", gchanged[0])
|
||||
var gname := Formatter.strip_tags(str(gb.get("name", "")))
|
||||
if ga.get("name") != gb.get("name"):
|
||||
return "Rename group %s" % gname
|
||||
return "Edit group %s" % gname
|
||||
if gchanged.size() > 1:
|
||||
return "Edit %s" % _count(gchanged.size(), "group")
|
||||
var moved: Array = d["moved"]
|
||||
if not moved.is_empty():
|
||||
# All the moved cards belong to one group whose frame moved too.
|
||||
for gid: String in d["gmoved"]:
|
||||
var gb := _parsed(b, "gids", "groups", gid)
|
||||
var members: Array = gb.get("members", [])
|
||||
var all := true
|
||||
for tid: Variant in moved:
|
||||
if not members.has(tid):
|
||||
all = false
|
||||
break
|
||||
if all and moved.size() == members.size():
|
||||
return "Move group %s" % Formatter.strip_tags(str(gb.get("name", "")))
|
||||
if moved.size() == 1:
|
||||
return "Move %s" % _name(b, "ids", "tables", moved[0])
|
||||
return "Move %s" % _count(moved.size(), "card")
|
||||
if not (d["gmoved_empty"] as Array).is_empty():
|
||||
return "Move group %s" % _name(b, "gids", "groups", d["gmoved_empty"][0])
|
||||
return "Edit"
|
||||
|
||||
|
||||
## One table's change: results added or deleted, pipes laid, removed or
|
||||
## changed, a rename, a reorder, or a plain edit.
|
||||
static func _table_label(ta: Dictionary, tb: Dictionary, b: Dictionary) -> String:
|
||||
var tname := Formatter.strip_tags(str(tb.get("name", "")))
|
||||
var e := _entry_changes(ta, tb)
|
||||
if not e["added"].is_empty():
|
||||
return ("Add result to %s" % tname) if e["added"].size() == 1 else "Add %d results to %s" % [e["added"].size(), tname]
|
||||
if not e["removed"].is_empty():
|
||||
if e["removed"].size() == 1:
|
||||
return "Delete result “%s” from %s" % [_short(Formatter.strip_tags(str(e["removed"][0].get("text", "")))), tname]
|
||||
return "Delete %d results from %s" % [e["removed"].size(), tname]
|
||||
if not e["pipes_added"].is_empty():
|
||||
return "Add pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_added"][0])]
|
||||
if not e["pipes_removed"].is_empty():
|
||||
return "Remove pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_removed"][0])]
|
||||
if not e["pipes_changed"].is_empty():
|
||||
return "Edit pipe %s → %s" % [tname, _name(b, "ids", "tables", e["pipes_changed"][0])]
|
||||
if ta.get("name") != tb.get("name"):
|
||||
var rest_a := ta.duplicate()
|
||||
var rest_b := tb.duplicate()
|
||||
rest_a.erase("name")
|
||||
rest_b.erase("name")
|
||||
if rest_a == rest_b:
|
||||
return "Rename %s → %s" % [Formatter.strip_tags(str(ta.get("name", ""))), tname]
|
||||
if e["reordered"]:
|
||||
return "Reorder %s" % tname
|
||||
return "Edit %s" % tname
|
||||
|
||||
|
||||
## Entries added and removed (dicts), pipe targets added, removed and changed,
|
||||
## and whether the order changed.
|
||||
static func _entry_changes(ta: Dictionary, tb: Dictionary) -> Dictionary:
|
||||
var ea := {}
|
||||
var order_a: Array = []
|
||||
for x: Variant in ta.get("entries", []):
|
||||
if x is Dictionary:
|
||||
ea[str(x.get("id", ""))] = x
|
||||
order_a.append(str(x.get("id", "")))
|
||||
var eb := {}
|
||||
var order_b: Array = []
|
||||
for x: Variant in tb.get("entries", []):
|
||||
if x is Dictionary:
|
||||
eb[str(x.get("id", ""))] = x
|
||||
order_b.append(str(x.get("id", "")))
|
||||
var out := {"added": [], "removed": [], "pipes_added": [], "pipes_removed": [], "pipes_changed": [], "reordered": false}
|
||||
for id: String in eb:
|
||||
if not ea.has(id):
|
||||
out["added"].append(eb[id])
|
||||
for id: String in ea:
|
||||
if not eb.has(id):
|
||||
out["removed"].append(ea[id])
|
||||
continue
|
||||
var pa := _pipes(ea[id])
|
||||
var pb := _pipes(eb[id])
|
||||
for to: String in pb:
|
||||
if not pa.has(to):
|
||||
out["pipes_added"].append(to)
|
||||
elif typeof(pa[to]) != typeof(pb[to]) or pa[to] != pb[to]:
|
||||
out["pipes_changed"].append(to)
|
||||
for to: String in pa:
|
||||
if not pb.has(to):
|
||||
out["pipes_removed"].append(to)
|
||||
if out["added"].is_empty() and out["removed"].is_empty() and order_a != order_b:
|
||||
out["reordered"] = true
|
||||
return out
|
||||
|
||||
|
||||
## target table id -> the pipe as written (an id or a dict of options).
|
||||
static func _pipes(entry: Dictionary) -> Dictionary:
|
||||
var out := {}
|
||||
for p: Variant in entry.get("pipes", []):
|
||||
if p is Dictionary:
|
||||
out[str(p.get("table", ""))] = p
|
||||
else:
|
||||
out[str(p)] = p
|
||||
return out
|
||||
|
||||
|
||||
static func _parsed(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> Dictionary:
|
||||
var ids: PackedStringArray = snap[ids_key]
|
||||
var i := ids.find(id)
|
||||
if i < 0:
|
||||
return {}
|
||||
var v: Variant = JSON.parse_string((snap[strs_key] as PackedStringArray)[i])
|
||||
return v if v is Dictionary else {}
|
||||
|
||||
|
||||
static func _name(snap: Dictionary, ids_key: String, strs_key: String, id: String) -> String:
|
||||
var d := _parsed(snap, ids_key, strs_key, id)
|
||||
var n := Formatter.strip_tags(str(d.get("name", ""))).strip_edges()
|
||||
return n if n != "" else id
|
||||
|
||||
|
||||
static func _kind_word(d: Dictionary) -> String:
|
||||
match str(d.get("kind", RollTable.KIND_ROLL)):
|
||||
RollTable.KIND_CHOICE:
|
||||
return "choice"
|
||||
RollTable.KIND_LOOP:
|
||||
return "loop"
|
||||
RollTable.KIND_ROUTER:
|
||||
return "router"
|
||||
RollTable.KIND_VARIABLE:
|
||||
return "variable"
|
||||
RollTable.KIND_SHEET:
|
||||
return "sheet"
|
||||
return "table"
|
||||
|
||||
|
||||
static func _count(n: int, noun: String) -> String:
|
||||
return "%d %s%s" % [n, noun, "" if n == 1 else "s"]
|
||||
|
||||
|
||||
static func _short(s: String) -> String:
|
||||
return s if s.length() <= 28 else s.substr(0, 27) + "…"
|
||||
1
ui/edit_history.gd.uid
Normal file
1
ui/edit_history.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://biq48t0v3lo3g
|
||||
564
ui/main.gd
564
ui/main.gd
|
|
@ -1,7 +1,8 @@
|
|||
class_name Main
|
||||
extends Control
|
||||
## The app window: top bar, felt board and result tray. Owns the board data,
|
||||
## the Play/Build mode, roll animation, and editing actions with undo.
|
||||
## the Play/Build mode, roll animation, and editing actions with undo and
|
||||
## redo (EditHistory, one per collection; see "Undo and redo" below).
|
||||
|
||||
enum Mode { PLAY, BUILD }
|
||||
|
||||
|
|
@ -44,7 +45,8 @@ var _toast_label: Label
|
|||
var _toast_undo: Button
|
||||
var _toast_timer: Timer
|
||||
var _save_timer: Timer
|
||||
var _undo_snapshot := ""
|
||||
## The undo step the toast's Undo button undoes (EditHistory serial), or -1.
|
||||
var _toast_serial := -1
|
||||
var _saving_enabled := true
|
||||
|
||||
# Local state for the current collection (see load_local_state). Kept in memory
|
||||
|
|
@ -146,6 +148,7 @@ func _build_ui() -> void:
|
|||
tray.setup(self)
|
||||
root.add_child(tray)
|
||||
_build_toast()
|
||||
_build_edit_timer()
|
||||
|
||||
_save_timer = Timer.new()
|
||||
_save_timer.one_shot = true
|
||||
|
|
@ -210,6 +213,7 @@ func _build_top_bar() -> Control:
|
|||
var tools := HBoxContainer.new()
|
||||
tools.add_theme_constant_override("separation", 6)
|
||||
_build_tools = tools
|
||||
_make_history_buttons(tools)
|
||||
_add_menu = _make_add_menu()
|
||||
tools.add_child(_add_menu)
|
||||
_board_menu = IoMenu.new()
|
||||
|
|
@ -294,6 +298,7 @@ func _build_toast() -> void:
|
|||
var uh := Style.box(Style.FELT_HOVER, 7, [12, 5, 12, 5])
|
||||
Style.skin_button(_toast_undo, un, uh, uh, Style.BRASS)
|
||||
_toast_undo.pressed.connect(_undo)
|
||||
_toast_undo.focus_mode = Control.FOCUS_NONE
|
||||
h.add_child(_toast_undo)
|
||||
_toast.hide()
|
||||
add_child(_toast)
|
||||
|
|
@ -302,15 +307,17 @@ func _build_toast() -> void:
|
|||
_toast_timer.wait_time = 5.0
|
||||
_toast_timer.timeout.connect(func() -> void:
|
||||
_toast.hide()
|
||||
_undo_snapshot = ""
|
||||
_toast_serial = -1
|
||||
)
|
||||
add_child(_toast_timer)
|
||||
|
||||
|
||||
func toast(message: String, snapshot: String = "") -> void:
|
||||
_undo_snapshot = snapshot
|
||||
## Shows a message at the bottom. With `undoable`, it has an Undo button for
|
||||
## the edit just committed (it goes through the edit history, like Ctrl+Z).
|
||||
func toast(message: String, undoable: bool = false) -> void:
|
||||
_toast_serial = edits.top_serial() if undoable and edits else -1
|
||||
_toast_label.text = message
|
||||
_toast_undo.visible = snapshot != ""
|
||||
_toast_undo.visible = _toast_serial >= 0
|
||||
_toast.show()
|
||||
_toast.reset_size()
|
||||
_place_toast()
|
||||
|
|
@ -323,18 +330,16 @@ func _place_toast() -> void:
|
|||
_toast.position = Vector2((size.x - _toast.size.x) / 2.0, size.y - _toast.size.y - 20.0)
|
||||
|
||||
|
||||
## The toast's Undo button: undoes the step the toast was about, if it is
|
||||
## still the newest one.
|
||||
func _undo() -> void:
|
||||
if _undo_snapshot == "":
|
||||
_commit_edits()
|
||||
if _toast_serial < 0 or edits == null or edits.top_serial() != _toast_serial:
|
||||
_toast_undo.hide()
|
||||
if edits and edits.can_undo():
|
||||
toast("Newer edits came after that one. Undo (Ctrl+Z) steps back through them.")
|
||||
return
|
||||
data.load_json(_undo_snapshot)
|
||||
_undo_snapshot = ""
|
||||
_toast.hide()
|
||||
_rebuild_cards()
|
||||
mark_dirty()
|
||||
|
||||
|
||||
func _snapshot() -> String:
|
||||
return data.to_json()
|
||||
undo()
|
||||
|
||||
|
||||
# ---------- Cards ----------
|
||||
|
|
@ -349,8 +354,11 @@ func is_entry_lit(tid: String, eid: String) -> bool:
|
|||
|
||||
## Rebuilds every card. Cards hidden in collapsed groups aren't built at all
|
||||
## (card_for gives null for them) until their group expands; see
|
||||
## _apply_group_visibility.
|
||||
## _apply_group_visibility. Called from outside an edit (a board loaded or
|
||||
## replaced), it also takes the board as the edit history's new baseline.
|
||||
func _rebuild_cards() -> void:
|
||||
if not _keep_history:
|
||||
_sync_history()
|
||||
for c in board.cards.get_children():
|
||||
board.cards.remove_child(c)
|
||||
c.queue_free()
|
||||
|
|
@ -388,7 +396,31 @@ func set_mode(m: Mode) -> void:
|
|||
_nav_mode_changed()
|
||||
|
||||
|
||||
func mark_dirty() -> void:
|
||||
## Call after changing the saved collection: schedules the save, refreshes
|
||||
## what depends on the board and records an undo step (see "Undo and redo").
|
||||
## `label` names the step and commits it at once; without one the step is
|
||||
## named from the change, and committed at the end of the frame, or once
|
||||
## typing pauses when a text field has focus. `undoable` false is for saved
|
||||
## view state (collapsing), which isn't an undo step.
|
||||
func mark_dirty(label: String = "", undoable: bool = true) -> void:
|
||||
_board_changed()
|
||||
if not undoable or edits == null or _restoring:
|
||||
return
|
||||
_edit_pending = true
|
||||
if label != "":
|
||||
_commit_edits(label)
|
||||
return
|
||||
var f := get_viewport().gui_get_focus_owner() if is_inside_tree() else null
|
||||
if f is LineEdit or f is TextEdit:
|
||||
_edit_focus = f.get_instance_id()
|
||||
_edit_timer.start()
|
||||
else:
|
||||
_edit_focus = 0
|
||||
_queue_commit()
|
||||
|
||||
|
||||
## What every change to the board needs: a save soon, fresh caches and redraws.
|
||||
func _board_changed() -> void:
|
||||
if _saving_enabled:
|
||||
_save_timer.start()
|
||||
_ref_cache.clear()
|
||||
|
|
@ -426,7 +458,7 @@ func toggle_collapse(tid: String) -> void:
|
|||
return
|
||||
t.collapsed = not t.collapsed
|
||||
card_for(tid).rebuild()
|
||||
mark_dirty()
|
||||
mark_dirty("", false)
|
||||
|
||||
|
||||
## Collapses or expands every table and every group.
|
||||
|
|
@ -444,7 +476,7 @@ func set_all_collapsed(collapsed: bool) -> void:
|
|||
changed = true
|
||||
if changed:
|
||||
_rebuild_groups()
|
||||
mark_dirty()
|
||||
mark_dirty("", false)
|
||||
|
||||
|
||||
## The "+ Table ▾" kinds: [label, kind, sub, default name].
|
||||
|
|
@ -512,6 +544,7 @@ const MENU_SAVE_SELECTION := 102
|
|||
|
||||
## Adds a card of any kind (RollTable.create) in the middle of the view.
|
||||
func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTable:
|
||||
_begin_edit()
|
||||
var center := board.screen_to_world(board.size / 2.0)
|
||||
var name := "New table"
|
||||
for k: Array in ADD_KINDS:
|
||||
|
|
@ -530,7 +563,7 @@ func add_table(kind: String = RollTable.KIND_ROLL, sub: String = "") -> RollTabl
|
|||
board.cards.add_child(card)
|
||||
card.setup(self, t)
|
||||
cards[t.id] = card
|
||||
mark_dirty()
|
||||
_end_edit()
|
||||
return t
|
||||
|
||||
|
||||
|
|
@ -549,20 +582,23 @@ func _free_var_name(base: String) -> String:
|
|||
|
||||
|
||||
func reset_sample() -> void:
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
data.tables = SampleBoard.create().tables
|
||||
data.groups.clear()
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
_keep_history = true
|
||||
_rebuild_cards()
|
||||
mark_dirty()
|
||||
_keep_history = false
|
||||
_end_edit("Reset sample")
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
board.fit()
|
||||
toast("Board reset to the sample tables", snap)
|
||||
toast("Board reset to the sample tables", true)
|
||||
|
||||
|
||||
func add_entry(tid: String) -> void:
|
||||
_begin_edit()
|
||||
var t := data.get_table(tid)
|
||||
var e := TableEntry.new(TowerBoard.new_id("e"), "Result %d" % (t.entries.size() + 1))
|
||||
if t.is_ranged():
|
||||
|
|
@ -576,7 +612,7 @@ func add_entry(tid: String) -> void:
|
|||
t.entries.append(e)
|
||||
t.collapsed = false
|
||||
card_for(tid).rebuild()
|
||||
mark_dirty()
|
||||
_end_edit()
|
||||
|
||||
|
||||
func delete_entry(tid: String, eid: String) -> void:
|
||||
|
|
@ -584,18 +620,18 @@ func delete_entry(tid: String, eid: String) -> void:
|
|||
var e := t.find_entry(eid)
|
||||
if e == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
t.entries.erase(e)
|
||||
card_for(tid).rebuild()
|
||||
mark_dirty()
|
||||
toast("Deleted “%s”" % e.text, snap)
|
||||
_end_edit()
|
||||
toast("Deleted “%s”" % e.text, true)
|
||||
|
||||
|
||||
func delete_table(tid: String) -> void:
|
||||
var t := data.get_table(tid)
|
||||
if t == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
var in_group := data.group_of(tid)
|
||||
data.remove_table(tid)
|
||||
forget_table_state(tid)
|
||||
|
|
@ -609,8 +645,8 @@ func delete_table(tid: String) -> void:
|
|||
if in_group:
|
||||
_groups_changed()
|
||||
_update_selection_bar()
|
||||
mark_dirty()
|
||||
toast("Deleted %s" % t.name, snap)
|
||||
_end_edit()
|
||||
toast("Deleted %s" % t.name, true)
|
||||
|
||||
|
||||
func remove_pipe(key: String) -> void:
|
||||
|
|
@ -623,13 +659,15 @@ func remove_pipe(key: String) -> void:
|
|||
var e := t.find_entry(from.get_slice(":", 1))
|
||||
if e == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
e.pipes.erase(to)
|
||||
lit_pipes.erase(key)
|
||||
board.pipes.hover_key = ""
|
||||
card_for(t.id).rebuild()
|
||||
mark_dirty()
|
||||
toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], snap)
|
||||
var card := card_for(t.id)
|
||||
if card:
|
||||
card.rebuild()
|
||||
_end_edit()
|
||||
toast("Removed pipe from “%s” to %s" % [e.text, target.name if target else to], true)
|
||||
|
||||
|
||||
func start_link(tid: String, eid: String) -> void:
|
||||
|
|
@ -662,6 +700,7 @@ func finish_link() -> void:
|
|||
if over.table.kind == RollTable.KIND_VARIABLE:
|
||||
toast("Variable cards aren't rolled, so pipes can't lead into them. Use an effect such as @%s += 1." % over.table.var_name)
|
||||
return
|
||||
_begin_edit()
|
||||
# Each range on a ranged table takes a single pipe, so a new one replaces the old.
|
||||
var replaced: RollTable = null
|
||||
if t.is_ranged():
|
||||
|
|
@ -670,11 +709,11 @@ func finish_link() -> void:
|
|||
e.pipes.clear()
|
||||
e.pipes.append(over.table.id)
|
||||
card_for(t.id).rebuild()
|
||||
mark_dirty()
|
||||
_end_edit()
|
||||
var msg := "“%s” now rolls on %s" % [e.text, over.table.name]
|
||||
if replaced:
|
||||
msg += " instead of %s" % replaced.name
|
||||
toast(msg)
|
||||
toast(msg, true)
|
||||
|
||||
|
||||
func _card_under_mouse() -> TableCard:
|
||||
|
|
@ -697,6 +736,7 @@ var _group_nodes: Dictionary = {} # group id -> GroupCard
|
|||
var _hidden_cache: Variant = null # table id -> GroupCard, or null when stale
|
||||
## Ids of the cards being dragged and the group the pointer is over (Build).
|
||||
var _drag_set: Array[String] = []
|
||||
var _drag_from: Dictionary = {} # table id -> its position when the drag began
|
||||
var _drag_over: GroupCard
|
||||
|
||||
|
||||
|
|
@ -813,12 +853,12 @@ func toggle_group(gid: String) -> void:
|
|||
g.collapsed = not g.collapsed
|
||||
details().hide_for()
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
mark_dirty("", false)
|
||||
if not g.collapsed:
|
||||
var room := _make_room_for(g, compact, blocks)
|
||||
if int(room["moved"]) > 0:
|
||||
toast("Opened %s and moved %d %s to make room" % [Formatter.strip_tags(g.name), room["moved"],
|
||||
"block" if int(room["moved"]) == 1 else "blocks"], room["snap"])
|
||||
"block" if int(room["moved"]) == 1 else "blocks"], true)
|
||||
|
||||
|
||||
func set_group_collapsed(gid: String, collapsed: bool) -> void:
|
||||
|
|
@ -862,7 +902,7 @@ func group_selection() -> TableGroup:
|
|||
if ids.is_empty():
|
||||
toast("Select some cards first: Ctrl- or Shift-click their headers, or Ctrl-drag on the felt")
|
||||
return null
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
var g := data.add_group(_free_group_name(), ids)
|
||||
var rects: Array = []
|
||||
for tid in ids:
|
||||
|
|
@ -872,8 +912,8 @@ func group_selection() -> TableGroup:
|
|||
# Groups don't nest: emptied groups stay, so they can be refilled or ungrouped.
|
||||
clear_selection()
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
toast("Grouped %d %s as “%s”" % [ids.size(), "card" if ids.size() == 1 else "cards", g.name], snap)
|
||||
_end_edit()
|
||||
toast("Grouped %d %s as “%s”" % [ids.size(), "card" if ids.size() == 1 else "cards", g.name], true)
|
||||
return g
|
||||
|
||||
|
||||
|
|
@ -882,11 +922,11 @@ func ungroup(gid: String) -> void:
|
|||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
data.ungroup(gid)
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), snap)
|
||||
_end_edit()
|
||||
toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), true)
|
||||
|
||||
|
||||
func confirm_delete_group(gid: String) -> void:
|
||||
|
|
@ -904,7 +944,7 @@ func delete_group(gid: String) -> void:
|
|||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
var gname := Formatter.strip_tags(g.name)
|
||||
var gone := data.delete_group(gid)
|
||||
for tid in gone:
|
||||
|
|
@ -918,8 +958,8 @@ func delete_group(gid: String) -> void:
|
|||
for c in cards.values():
|
||||
(c as TableCard).rebuild()
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
toast("Deleted “%s” and its %d %s" % [gname, gone.size(), "card" if gone.size() == 1 else "cards"], snap)
|
||||
_end_edit()
|
||||
toast("Deleted “%s” and its %d %s" % [gname, gone.size(), "card" if gone.size() == 1 else "cards"], true)
|
||||
|
||||
|
||||
## The group details editor (Build): a card-styled dialog with the text.
|
||||
|
|
@ -937,12 +977,13 @@ func edit_group_details(gid: String) -> void:
|
|||
d.body.add_child(te)
|
||||
d.add_button("Cancel", "plain", d.close)
|
||||
d.add_button("Save", "primary", func() -> void:
|
||||
_begin_edit()
|
||||
g.details = te.text.strip_edges()
|
||||
d.close()
|
||||
var n := group_node(gid)
|
||||
if n:
|
||||
n.rebuild()
|
||||
mark_dirty()
|
||||
_end_edit()
|
||||
)
|
||||
_add_modal(d)
|
||||
|
||||
|
|
@ -961,6 +1002,7 @@ func _frame_at(p: Vector2) -> TableGroup:
|
|||
# ----- Card drags (TableCard calls these) -----
|
||||
|
||||
func begin_card_drag(card: TableCard) -> void:
|
||||
_begin_edit()
|
||||
_drag_set.clear()
|
||||
if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1:
|
||||
for tid: String in selection:
|
||||
|
|
@ -968,8 +1010,10 @@ func begin_card_drag(card: TableCard) -> void:
|
|||
_drag_set.append(tid)
|
||||
else:
|
||||
_drag_set.append(card.table.id)
|
||||
_drag_from.clear()
|
||||
# The frames of the dragged cards' groups hold still, so a card can leave them.
|
||||
for tid in _drag_set:
|
||||
_drag_from[tid] = data.get_table(tid).position
|
||||
var g := data.group_of(tid)
|
||||
if g:
|
||||
board.groups.frozen[g.id] = true
|
||||
|
|
@ -1025,7 +1069,13 @@ func end_card_drag(_card: TableCard) -> void:
|
|||
data.remove_from_group(tid)
|
||||
left += 1
|
||||
board.groups.frozen.clear()
|
||||
var moved := false
|
||||
for tid in _drag_set:
|
||||
var t := data.get_table(tid)
|
||||
if t and t.position != _drag_from.get(tid, t.position):
|
||||
moved = true
|
||||
_drag_set.clear()
|
||||
_drag_from.clear()
|
||||
if not joined.is_empty() or left > 0:
|
||||
_groups_changed()
|
||||
var parts := PackedStringArray()
|
||||
|
|
@ -1034,8 +1084,11 @@ func end_card_drag(_card: TableCard) -> void:
|
|||
if left > 0:
|
||||
parts.append("took %d out of %s" % [left, "its group" if left == 1 else "their groups"])
|
||||
var msg := ", ".join(parts)
|
||||
toast(msg.substr(0, 1).to_upper() + msg.substr(1))
|
||||
mark_dirty()
|
||||
_end_edit()
|
||||
toast(msg.substr(0, 1).to_upper() + msg.substr(1), true)
|
||||
return
|
||||
# A click on a header without a drag isn't an edit.
|
||||
mark_dirty("", moved)
|
||||
|
||||
|
||||
# ----- Selection (Build) -----
|
||||
|
|
@ -1221,7 +1274,7 @@ func begin_template_insert(tpl: Dictionary) -> void:
|
|||
## outside pipes relinked by name (or dropped and reported). Returns
|
||||
## TemplateKit.instantiate's result.
|
||||
func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
var ext := TemplateKit.extent(tpl)
|
||||
var center := board.screen_to_world(board.size / 2.0)
|
||||
var origin := (center - ext / 2.0).round()
|
||||
|
|
@ -1235,7 +1288,7 @@ func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
|
|||
card.setup(self, t)
|
||||
cards[t.id] = card
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
_end_edit("Insert template %s" % Formatter.strip_tags(str(tpl.get("name", "template"))))
|
||||
var n := (r["tables"] as Array).size()
|
||||
var msg := "Inserted “%s” (%d %s)" % [str(tpl.get("name", "template")), n, "card" if n == 1 else "cards"]
|
||||
var relinked: Array = r["relinked"]
|
||||
|
|
@ -1243,9 +1296,9 @@ func insert_template(tpl: Dictionary, values: Dictionary) -> Dictionary:
|
|||
msg += " · %d %s relinked by name" % [relinked.size(), "pipe" if relinked.size() == 1 else "pipes"]
|
||||
var dropped: Array = r["dropped"]
|
||||
if dropped.is_empty():
|
||||
toast(msg, snap)
|
||||
toast(msg, true)
|
||||
else:
|
||||
toast(msg + " · %d left out" % dropped.size(), snap)
|
||||
toast(msg + " · %d left out" % dropped.size(), true)
|
||||
var d := ModalCard.new("Inserted “%s”" % str(tpl.get("name", "template")), 540.0)
|
||||
d.body.add_child(ModalCard.note("These pipes led to cards outside the template, and this collection has no card with that name, so they were left out. Lay them again by hand, or rename a card and insert again.", Style.INK))
|
||||
d.body.add_child(ModalCard.section("Left out (%d)" % dropped.size()))
|
||||
|
|
@ -1718,7 +1771,7 @@ func open_table_settings(table_id: String) -> void:
|
|||
return
|
||||
var d := TableSettingsDialog.new(t)
|
||||
d.template_requested.connect(func() -> void: save_template_from([table_id], "card"))
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
d.applied.connect(func(result: Dictionary) -> void:
|
||||
if result.get("deck_reset", false) and state and data.id != "":
|
||||
state.clear_deck(data.id, t.id)
|
||||
|
|
@ -1730,9 +1783,9 @@ func open_table_settings(table_id: String) -> void:
|
|||
var card := card_for(t.id)
|
||||
if card:
|
||||
card.rebuild()
|
||||
mark_dirty()
|
||||
_end_edit("Edit settings of %s" % Formatter.strip_tags(t.name))
|
||||
refresh_live()
|
||||
toast("Updated %s" % t.name, snap)
|
||||
toast("Updated %s" % t.name, true)
|
||||
)
|
||||
_add_modal(d)
|
||||
|
||||
|
|
@ -1742,6 +1795,7 @@ func open_table_settings(table_id: String) -> void:
|
|||
func switch_collection(id: String) -> void:
|
||||
if not collections_enabled() or id == data.id:
|
||||
return
|
||||
_commit_edits()
|
||||
_save_timer.stop()
|
||||
var b := CollectionSwitcher.switch_collection(library, data, id)
|
||||
if b == null:
|
||||
|
|
@ -1754,6 +1808,8 @@ func switch_collection(id: String) -> void:
|
|||
## history (lighting its last roll), rebuilds the cards, fits the view and
|
||||
## remembers it as the last collection.
|
||||
func _show_collection(b: TowerBoard) -> void:
|
||||
# Waiting edits belong to the collection being left.
|
||||
_commit_edits()
|
||||
data = b
|
||||
_token += 1
|
||||
cancel_choice()
|
||||
|
|
@ -1809,8 +1865,10 @@ func delete_collection() -> void:
|
|||
var msg := "Delete “%s” and its saved decks, variables and history? This can't be undone." % data.name
|
||||
_add_modal(ModalCard.confirm("Delete collection", msg, "Delete", func() -> void:
|
||||
var gone := data.name
|
||||
var gone_id := data.id
|
||||
var next := CollectionSwitcher.delete_collection(library, data)
|
||||
if next:
|
||||
_histories.erase(gone_id)
|
||||
_show_collection(next)
|
||||
toast("Deleted “%s”" % gone)
|
||||
, true))
|
||||
|
|
@ -2427,6 +2485,7 @@ func _load_board_file(path: String) -> void:
|
|||
func _run_cli_extras(args: PackedStringArray) -> void:
|
||||
if args.has("--perf"):
|
||||
_run_perf()
|
||||
await _run_undo_cli(args)
|
||||
_run_nav_cli(args)
|
||||
if args.has("--clear-result"):
|
||||
# Keeps the board lit but empties the tray (a tall sheet result can fill it).
|
||||
|
|
@ -2601,7 +2660,12 @@ func open_search() -> SearchPanel:
|
|||
|
||||
func _shortcut_input(ev: InputEvent) -> void:
|
||||
var k := ev as InputEventKey
|
||||
if k == null or not k.pressed or k.echo:
|
||||
if k == null or not k.pressed:
|
||||
return
|
||||
if _history_shortcut(k):
|
||||
get_viewport().set_input_as_handled()
|
||||
return
|
||||
if k.echo:
|
||||
return
|
||||
if k.keycode == KEY_F and (k.ctrl_pressed or k.meta_pressed) and not k.alt_pressed:
|
||||
open_search()
|
||||
|
|
@ -2628,7 +2692,7 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
|
|||
if entry_id != "" and t.find_entry(entry_id) == null:
|
||||
entry_id = ""
|
||||
var notes := PackedStringArray()
|
||||
var snap := ""
|
||||
var undoable := false
|
||||
var settle := false
|
||||
var g := data.group_of(table_id)
|
||||
if g and g.collapsed:
|
||||
|
|
@ -2636,14 +2700,14 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
|
|||
notes.append("Opened group %s" % Formatter.strip_tags(g.name))
|
||||
if int(info["moved"]) > 0:
|
||||
notes.append("moved %d %s to make room" % [info["moved"], "block" if int(info["moved"]) == 1 else "blocks"])
|
||||
snap = info["snap"]
|
||||
undoable = true
|
||||
settle = true
|
||||
if entry_id != "" and t.collapsed and t.kind != RollTable.KIND_VARIABLE and t.kind != RollTable.KIND_SHEET:
|
||||
t.collapsed = false
|
||||
var c0 := card_for(table_id)
|
||||
if c0:
|
||||
c0.rebuild()
|
||||
mark_dirty()
|
||||
mark_dirty("", false)
|
||||
settle = true
|
||||
var card := card_for(table_id)
|
||||
if card == null:
|
||||
|
|
@ -2663,7 +2727,7 @@ func focus_table(table_id: String, entry_id: String = "") -> void:
|
|||
board.animate_to(_focus_point(r), _focus_zoom(r))
|
||||
board.cards.flash(card)
|
||||
if not notes.is_empty():
|
||||
toast(", ".join(notes), snap)
|
||||
toast(", ".join(notes), undoable)
|
||||
if entry_id != "":
|
||||
# The list scrolls on the next layout pass; ring the row after it.
|
||||
await get_tree().process_frame
|
||||
|
|
@ -2717,7 +2781,7 @@ func _focus_point(r: Rect2) -> Vector2:
|
|||
|
||||
|
||||
## Expands a collapsed group (saved) and makes room for it. Returns
|
||||
## _make_room_for's {moved, snap}.
|
||||
## _make_room_for's {moved}.
|
||||
func _expand_group(g: TableGroup) -> Dictionary:
|
||||
var n := group_node(g.id)
|
||||
var compact := Rect2(n.position, n.size) if n else Rect2()
|
||||
|
|
@ -2725,7 +2789,7 @@ func _expand_group(g: TableGroup) -> Dictionary:
|
|||
g.collapsed = false
|
||||
details().hide_for()
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
mark_dirty("", false)
|
||||
return _make_room_for(g, compact, blocks)
|
||||
|
||||
|
||||
|
|
@ -2860,7 +2924,7 @@ func pack_collapsed_groups() -> int:
|
|||
for b: Dictionary in blocks:
|
||||
rects.append(b["rect"])
|
||||
var offsets := BoardLayout.pack(rects, PACK_GAP, PACK_GAP)
|
||||
var snap := _snapshot()
|
||||
_begin_edit()
|
||||
var moved := 0
|
||||
for i in blocks.size():
|
||||
var d := offsets[i].round()
|
||||
|
|
@ -2870,8 +2934,8 @@ func pack_collapsed_groups() -> int:
|
|||
if moved == 0:
|
||||
toast("Already packed")
|
||||
return 0
|
||||
mark_dirty()
|
||||
toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], snap)
|
||||
_end_edit("Pack collapsed groups")
|
||||
toast("Packed the board: moved %d %s" % [moved, "block" if moved == 1 else "blocks"], true)
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
board.fit()
|
||||
|
|
@ -2881,11 +2945,11 @@ func pack_collapsed_groups() -> int:
|
|||
## After a group expands in place: if its frame now covers other blocks, they
|
||||
## shift right or down to clear it (BoardLayout.make_room). `blocks` are the
|
||||
## other blocks (_layout_blocks) measured before the group expanded, while
|
||||
## every group card was laid out. Returns {moved, snap}, snap being the board
|
||||
## before the move (for an undo toast).
|
||||
## every group card was laid out. Returns {moved}; the move is an undo step
|
||||
## of its own (expanding the group isn't one).
|
||||
func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
|
||||
if compact.size == Vector2.ZERO or blocks.is_empty():
|
||||
return {"moved": 0, "snap": ""}
|
||||
return {"moved": 0}
|
||||
var grown := g.rect()
|
||||
var rects: Array = []
|
||||
var hits := false
|
||||
|
|
@ -2895,8 +2959,8 @@ func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
|
|||
if r.intersects(grown):
|
||||
hits = true
|
||||
if not hits:
|
||||
return {"moved": 0, "snap": ""}
|
||||
var snap := _snapshot()
|
||||
return {"moved": 0}
|
||||
_begin_edit()
|
||||
var offsets := BoardLayout.make_room(rects, compact, grown, PACK_GAP)
|
||||
var moved := 0
|
||||
for i in blocks.size():
|
||||
|
|
@ -2905,8 +2969,8 @@ func _make_room_for(g: TableGroup, compact: Rect2, blocks: Array) -> Dictionary:
|
|||
_move_block(blocks[i], d)
|
||||
moved += 1
|
||||
if moved > 0:
|
||||
mark_dirty()
|
||||
return {"moved": moved, "snap": snap}
|
||||
_end_edit("Make room for %s" % Formatter.strip_tags(g.name))
|
||||
return {"moved": moved}
|
||||
|
||||
|
||||
# ----- Navigation screenshot flags -----
|
||||
|
|
@ -2933,3 +2997,353 @@ func _run_nav_cli(args: PackedStringArray) -> void:
|
|||
var p := open_search()
|
||||
p.field.text = q
|
||||
p.refresh()
|
||||
|
||||
|
||||
# ---------- Undo and redo ----------
|
||||
# Every change to the saved collection goes through mark_dirty, which records
|
||||
# an undo step in `edits` (EditHistory; one per collection, kept in memory
|
||||
# while the app runs, so switching collections and back keeps it). Steps are
|
||||
# whole-board snapshots, so undo needs nothing from the card editors.
|
||||
#
|
||||
# Coalescing: typing in a text field commits once typing pauses for
|
||||
# EDIT_PAUSE, and later typing in the same field merges into that step until
|
||||
# focus moves; other edits commit at the end of the frame (a whole drag is one
|
||||
# step), and repeated edits to the same card or pipe within
|
||||
# EditHistory.COALESCE_SECS merge. Actions in this file call _begin_edit
|
||||
# before changing anything (committing pending typing as its own step) and
|
||||
# _end_edit after, which commits at once.
|
||||
#
|
||||
# Collapsing cards and groups is saved but treated as view state: it isn't a
|
||||
# step, and undo leaves things collapsed or expanded as they are.
|
||||
#
|
||||
# Ctrl+Z undoes, Ctrl+Shift+Z or Ctrl+Y redoes, in Build and Play, unless a
|
||||
# text field has focus (it keeps its own Ctrl+Z for the text being typed) or
|
||||
# a dialog is open.
|
||||
|
||||
const EDIT_PAUSE := 0.8
|
||||
|
||||
var edits: EditHistory
|
||||
var _histories: Dictionary = {} # collection id -> EditHistory
|
||||
var _edit_timer: Timer
|
||||
var _edit_pending := false
|
||||
var _edit_focus := 0
|
||||
var _commit_queued := false
|
||||
var _restoring := false
|
||||
var _keep_history := false
|
||||
var _undo_button: Button
|
||||
var _redo_button: Button
|
||||
|
||||
|
||||
func _build_edit_timer() -> void:
|
||||
_edit_timer = Timer.new()
|
||||
_edit_timer.one_shot = true
|
||||
_edit_timer.wait_time = EDIT_PAUSE
|
||||
_edit_timer.timeout.connect(func() -> void: _commit_edits())
|
||||
add_child(_edit_timer)
|
||||
get_viewport().gui_focus_changed.connect(_on_focus_changed)
|
||||
|
||||
|
||||
## Typing in one field and then moving to another makes two steps.
|
||||
func _on_focus_changed(c: Control) -> void:
|
||||
if _edit_pending and _edit_focus != 0 and (c == null or c.get_instance_id() != _edit_focus):
|
||||
_queue_commit()
|
||||
|
||||
|
||||
## Picks this collection's history (making one) and takes the board as its
|
||||
## baseline; a history whose board changed from outside starts over.
|
||||
func _sync_history() -> void:
|
||||
if data == null:
|
||||
return
|
||||
if _edit_timer:
|
||||
_edit_timer.stop()
|
||||
_edit_pending = false
|
||||
var h: EditHistory = _histories.get(data.id)
|
||||
if h == null:
|
||||
h = EditHistory.new(data)
|
||||
_histories[data.id] = h
|
||||
else:
|
||||
h.resync(data)
|
||||
edits = h
|
||||
_update_undo_buttons()
|
||||
|
||||
|
||||
## Before an action changes the board: commits edits still waiting (typing)
|
||||
## as a step of their own, so the action's step starts from here.
|
||||
func _begin_edit() -> void:
|
||||
_commit_edits()
|
||||
|
||||
|
||||
## After an action changed the board: like mark_dirty, but the step is
|
||||
## committed now (named `label`, or from the change).
|
||||
func _end_edit(label: String = "") -> void:
|
||||
_board_changed()
|
||||
if edits == null or _restoring:
|
||||
return
|
||||
_edit_pending = true
|
||||
_commit_edits(label)
|
||||
|
||||
|
||||
func _queue_commit() -> void:
|
||||
if not _commit_queued:
|
||||
_commit_queued = true
|
||||
_commit_edits.call_deferred()
|
||||
|
||||
|
||||
## Records waiting edits as an undo step now (see EditHistory.commit).
|
||||
func _commit_edits(label: String = "") -> void:
|
||||
_commit_queued = false
|
||||
if _edit_timer:
|
||||
_edit_timer.stop()
|
||||
if not _edit_pending or edits == null:
|
||||
return
|
||||
_edit_pending = false
|
||||
var r := edits.commit(data, label, _edit_focus)
|
||||
if r["step"]:
|
||||
if _toast_serial >= 0 and edits.top_serial() != _toast_serial:
|
||||
_toast_serial = -1
|
||||
_toast_undo.hide()
|
||||
_update_undo_buttons()
|
||||
|
||||
|
||||
func can_undo() -> bool:
|
||||
return edits != null and (edits.can_undo() or _edit_pending)
|
||||
|
||||
|
||||
func can_redo() -> bool:
|
||||
return edits != null and edits.can_redo() and not _edit_pending
|
||||
|
||||
|
||||
## Steps back one edit. Returns false when there was nothing to undo (or it
|
||||
## has to wait for a roll or a dialog).
|
||||
func undo() -> bool:
|
||||
if not _history_ready():
|
||||
return false
|
||||
_commit_edits()
|
||||
if not edits.can_undo():
|
||||
toast("Nothing to undo")
|
||||
return false
|
||||
var e := edits.pop_undo()
|
||||
_apply_history(e, "Undid")
|
||||
return true
|
||||
|
||||
|
||||
func redo() -> bool:
|
||||
if not _history_ready():
|
||||
return false
|
||||
_commit_edits()
|
||||
if not edits.can_redo():
|
||||
toast("Nothing to redo")
|
||||
return false
|
||||
var e := edits.pop_redo()
|
||||
_apply_history(e, "Redid")
|
||||
return true
|
||||
|
||||
|
||||
func _history_ready() -> bool:
|
||||
if edits == null:
|
||||
return false
|
||||
if rolling_ctx != null or _choice_waiting("Answer the waiting question first"):
|
||||
toast("Wait for the roll to finish before undoing")
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Puts the board back to a snapshot from the history, keeping the view, the
|
||||
## mode, the open search and the lit results of tables that still exist. Only
|
||||
## what changed is rebuilt (EditHistory.patch, _refresh_patched); cards hidden
|
||||
## in collapsed groups stay unbuilt.
|
||||
func _apply_history(e: Dictionary, verb: String) -> void:
|
||||
var t0 := Time.get_ticks_usec()
|
||||
var d := EditHistory.diff(e["from"], e["snap"])
|
||||
_restoring = true
|
||||
if _pipe_popover and _pipe_popover.visible:
|
||||
_pipe_popover.hide()
|
||||
details().hide_for()
|
||||
board.pipes.hover_key = ""
|
||||
_drop_card = null
|
||||
_link_from = {}
|
||||
clear_selection()
|
||||
var p := EditHistory.patch(data, e["snap"], e["from"])
|
||||
if not p.is_empty():
|
||||
edits.cache = p["snap"]
|
||||
_refresh_patched(p, d)
|
||||
else:
|
||||
edits.cache = EditHistory.restore(data, e["snap"])
|
||||
_keep_history = true
|
||||
_rebuild_cards()
|
||||
_keep_history = false
|
||||
_restoring = false
|
||||
_board_changed()
|
||||
_refresh_lit()
|
||||
tray.render()
|
||||
_update_undo_buttons()
|
||||
toast("%s: %s" % [verb, e["label"]])
|
||||
_last_restore_usec = Time.get_ticks_usec() - t0
|
||||
_flash_changes(d)
|
||||
|
||||
|
||||
## After EditHistory.patch: frees the cards of removed tables, rebuilds the
|
||||
## groups if they changed, builds cards for tables brought back (unless a
|
||||
## collapsed group hides them) and moves and rebuilds the changed ones. A
|
||||
## changed variable card rebuilds every card (other cards' effect chips name
|
||||
## it).
|
||||
func _refresh_patched(p: Dictionary, d: Dictionary) -> void:
|
||||
for tid: String in p["removed"]:
|
||||
var c := card_for(tid)
|
||||
cards.erase(tid)
|
||||
if c:
|
||||
c.get_parent().remove_child(c)
|
||||
c.queue_free()
|
||||
if p["groups_changed"]:
|
||||
_groups_changed()
|
||||
else:
|
||||
for gid: String in p["groups"]:
|
||||
var n := group_node(gid)
|
||||
if n:
|
||||
n.sync_rect()
|
||||
_apply_group_visibility()
|
||||
var all := false
|
||||
for tid: String in p["tables"]:
|
||||
var t := data.get_table(tid)
|
||||
if t and t.kind == RollTable.KIND_VARIABLE and (d["changed"] as Array).has(tid):
|
||||
all = true
|
||||
for tid: String in (cards.keys() if all else p["tables"]):
|
||||
var c := card_for(tid)
|
||||
if c == null:
|
||||
continue
|
||||
c.position = c.table.position
|
||||
if all or (d["changed"] as Array).has(tid):
|
||||
c.rebuild()
|
||||
_update_collapse_all()
|
||||
|
||||
|
||||
## How long the last undo or redo took to rebuild the board (microseconds).
|
||||
var _last_restore_usec := 0
|
||||
|
||||
|
||||
## Rings the cards an undo or redo changed, once they have laid out. One
|
||||
## changed card that's off screen is brought into view (without changing the
|
||||
## zoom); bigger changes leave the view alone.
|
||||
func _flash_changes(d: Dictionary) -> void:
|
||||
for i in 2:
|
||||
await get_tree().process_frame
|
||||
var nodes: Array[Control] = []
|
||||
var hidden := hidden_groups()
|
||||
for tid: String in EditHistory.touched_tables(d):
|
||||
var n: Control = card_for(tid)
|
||||
if n == null:
|
||||
n = hidden.get(tid)
|
||||
if n and is_instance_valid(n) and not nodes.has(n):
|
||||
nodes.append(n)
|
||||
for gid: String in (d["gadded"] as Array) + (d["gchanged"] as Array):
|
||||
var n := group_node(gid)
|
||||
if n and not nodes.has(n):
|
||||
nodes.append(n)
|
||||
if nodes.is_empty():
|
||||
return
|
||||
var view := board.view_rect()
|
||||
if nodes.size() == 1 and not view.intersects(Rect2(nodes[0].position, nodes[0].size)):
|
||||
board.animate_to(Rect2(nodes[0].position, nodes[0].size).get_center(), board.zoom)
|
||||
view = Rect2()
|
||||
var shown: Array[Control] = []
|
||||
for n in nodes:
|
||||
if view.size == Vector2.ZERO or view.intersects(Rect2(n.position, n.size)):
|
||||
shown.append(n)
|
||||
board.cards.flash_all(shown)
|
||||
|
||||
|
||||
func _make_history_buttons(tools: HBoxContainer) -> void:
|
||||
_undo_button = Style.bar_button("Undo")
|
||||
_undo_button.pressed.connect(func() -> void: undo())
|
||||
_bar_icon(_undo_button, func(c: Control) -> void: _draw_turn_arrow(c, false))
|
||||
_redo_button = Style.bar_button("Redo")
|
||||
_redo_button.pressed.connect(func() -> void: redo())
|
||||
_bar_icon(_redo_button, func(c: Control) -> void: _draw_turn_arrow(c, true))
|
||||
for b in [_undo_button, _redo_button]:
|
||||
(b as Button).focus_mode = Control.FOCUS_NONE
|
||||
(b as Button).add_theme_color_override("font_disabled_color", Color(Style.ON_FELT, 0.35))
|
||||
tools.add_child(b)
|
||||
|
||||
|
||||
## A curved arrow, pointing left (undo) or right (redo).
|
||||
func _draw_turn_arrow(c: Control, right: bool) -> void:
|
||||
var b := c.get_parent() as Button
|
||||
var col := Style.ON_FELT if b == null or not b.disabled else Color(Style.ON_FELT, 0.35)
|
||||
var s := -1.0 if right else 1.0
|
||||
var o := Vector2(8, 9)
|
||||
c.draw_arc(o, 5.0, -PI * 0.95 if not right else -PI * 0.05, PI * 0.5 if not right else -PI * 1.5, 16, col, 1.8, true)
|
||||
var tip := o + Vector2(-5.0 * s, -0.4)
|
||||
c.draw_colored_polygon(PackedVector2Array([tip + Vector2(-3.2 * s, -1.0), tip + Vector2(3.2 * s, -1.0), tip + Vector2(0, 3.6)]), col)
|
||||
|
||||
|
||||
func _update_undo_buttons() -> void:
|
||||
if _undo_button == null:
|
||||
return
|
||||
_undo_button.disabled = not can_undo()
|
||||
_redo_button.disabled = not can_redo()
|
||||
if edits and edits.can_undo() and not _edit_pending:
|
||||
_undo_button.tooltip_text = "Undo: %s (Ctrl+Z)" % edits.undo_label()
|
||||
elif _edit_pending:
|
||||
_undo_button.tooltip_text = "Undo your latest edit (Ctrl+Z)"
|
||||
else:
|
||||
_undo_button.tooltip_text = "Nothing to undo"
|
||||
_redo_button.tooltip_text = ("Redo: %s (Ctrl+Shift+Z or Ctrl+Y)" % edits.redo_label()) if can_redo() else "Nothing to redo"
|
||||
for b in [_undo_button, _redo_button]:
|
||||
for k in (b as Button).get_children():
|
||||
(k as CanvasItem).queue_redraw()
|
||||
|
||||
|
||||
## True while a dialog (a ModalCard) is open over the board.
|
||||
func _modal_open() -> bool:
|
||||
for c in get_children():
|
||||
if c is ModalCard and (c as ModalCard).visible:
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
## Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y outside text fields.
|
||||
func _history_shortcut(k: InputEventKey) -> bool:
|
||||
if not (k.ctrl_pressed or k.meta_pressed) or k.alt_pressed:
|
||||
return false
|
||||
var is_undo := k.keycode == KEY_Z and not k.shift_pressed
|
||||
var is_redo := (k.keycode == KEY_Z and k.shift_pressed) or (k.keycode == KEY_Y and not k.shift_pressed)
|
||||
if not is_undo and not is_redo:
|
||||
return false
|
||||
var f := get_viewport().gui_get_focus_owner()
|
||||
if f is LineEdit or f is TextEdit or _modal_open():
|
||||
return false
|
||||
if is_undo:
|
||||
undo()
|
||||
else:
|
||||
redo()
|
||||
return true
|
||||
|
||||
|
||||
# ----- Undo screenshot flags -----
|
||||
# --undo-demo=<table id> delete that table (or the last one), then undo: the toast says so
|
||||
# --undo-tooltip make an edit, then hover the Undo button so its tooltip shows
|
||||
|
||||
func _run_undo_cli(args: PackedStringArray) -> void:
|
||||
var demo := _arg_value(args, "--undo-demo")
|
||||
if args.has("--undo-demo") or demo != "":
|
||||
set_mode(Mode.BUILD)
|
||||
var t: RollTable = data.get_table(demo) if demo != "" else (data.tables.back() if not data.tables.is_empty() else null)
|
||||
if t:
|
||||
delete_table(t.id)
|
||||
await get_tree().process_frame
|
||||
undo()
|
||||
if args.has("--undo-tooltip"):
|
||||
set_mode(Mode.BUILD)
|
||||
if not data.tables.is_empty():
|
||||
delete_table(data.tables.back().id)
|
||||
_toast.hide()
|
||||
for i in 3:
|
||||
await get_tree().process_frame
|
||||
var at := _undo_button.get_global_rect().get_center()
|
||||
get_viewport().notification(NOTIFICATION_VP_MOUSE_ENTER)
|
||||
for i in 2:
|
||||
var ev := InputEventMouseMotion.new()
|
||||
ev.position = at + Vector2(i, 0)
|
||||
ev.global_position = ev.position
|
||||
get_viewport().push_input(ev)
|
||||
await get_tree().process_frame
|
||||
|
|
|
|||
Loading…
Reference in a new issue