Group cards and templates
Groups: an optional groups list on a collection (frame rect, collapsed,
members, details), saved by TowerBoard and kept by JsonIO. Expanded groups
draw a frame behind their cards with a title bar; collapsed ones become one
compact card that lists the members' lit results, with pipes re-routed to
its inlet and right edge. Build mode adds multi-select (Ctrl/Shift-click,
Ctrl-drag), Group (Ctrl+G), drop in/out of frames, rename, ungroup, delete
with undo and a details editor.
Templates: TemplateKit saves cards, groups or selections with relative
positions, internal pipes and outside pipes by name, detects {$name}
parameters and inserts with fresh ids. TemplateLibrary keeps user templates
in user://templates and lists the built-in ones in templates/.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2ddf8c7c42
commit
9fdf65c00b
33 changed files with 3513 additions and 63 deletions
87
core/table_group.gd
Normal file
87
core/table_group.gd
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
class_name TableGroup
|
||||
extends RefCounted
|
||||
## A group card: a named frame around some of the board's tables, so a whole
|
||||
## block of cards can be moved, collapsed and saved as a template at once.
|
||||
## Groups are presentation only; rolling never looks at them. A table belongs
|
||||
## to at most one group, and groups don't nest.
|
||||
##
|
||||
## The rect is the frame in world coordinates, title bar included. While the
|
||||
## group is expanded the board refits it around the member cards; collapsed,
|
||||
## its top-left is where the compact group card sits.
|
||||
|
||||
## Space between the frame and its member cards.
|
||||
const PAD := 22.0
|
||||
## Height of the title bar at the top of the frame.
|
||||
const TITLE_H := 46.0
|
||||
|
||||
var id: String = ""
|
||||
var name: String = ""
|
||||
var position: Vector2 = Vector2.ZERO
|
||||
var size: Vector2 = Vector2(320, 200)
|
||||
var collapsed: bool = false
|
||||
## Longer description (BBCode), shown in the title bar's hover pop-up.
|
||||
var details: String = ""
|
||||
## Ids of the member tables, in the order they were added.
|
||||
var members: Array[String] = []
|
||||
|
||||
|
||||
func _init(p_id: String = "", p_name: String = "") -> void:
|
||||
id = p_id
|
||||
name = p_name
|
||||
|
||||
|
||||
func rect() -> Rect2:
|
||||
return Rect2(position, size)
|
||||
|
||||
|
||||
func has(table_id: String) -> bool:
|
||||
return members.has(table_id)
|
||||
|
||||
|
||||
## The frame that fits around `rects` (member cards, world coordinates), with
|
||||
## padding and room for the title bar. Returns the current rect for no rects.
|
||||
func fit_rect(rects: Array) -> Rect2:
|
||||
if rects.is_empty():
|
||||
return rect()
|
||||
var r: Rect2 = rects[0]
|
||||
for i in range(1, rects.size()):
|
||||
r = r.merge(rects[i])
|
||||
return Rect2(r.position - Vector2(PAD, PAD + TITLE_H), r.size + Vector2(PAD * 2.0, PAD * 2.0 + TITLE_H))
|
||||
|
||||
|
||||
## Moves the frame to fit `rects`. Returns true when it changed.
|
||||
func fit_to(rects: Array) -> bool:
|
||||
if rects.is_empty():
|
||||
return false
|
||||
var r := fit_rect(rects)
|
||||
r = Rect2(r.position.round(), r.size.round())
|
||||
if r == rect():
|
||||
return false
|
||||
position = r.position
|
||||
size = r.size
|
||||
return true
|
||||
|
||||
|
||||
func to_dict() -> Dictionary:
|
||||
var d := {"id": id, "name": name, "x": roundi(position.x), "y": roundi(position.y),
|
||||
"w": roundi(size.x), "h": roundi(size.y), "members": members.duplicate()}
|
||||
if collapsed:
|
||||
d["collapsed"] = true
|
||||
if details != "":
|
||||
d["details"] = details
|
||||
return d
|
||||
|
||||
|
||||
static func from_dict(d: Dictionary) -> TableGroup:
|
||||
var g := TableGroup.new(str(d.get("id", "")), str(d.get("name", "")))
|
||||
g.position = Vector2(float(d.get("x", 0)), float(d.get("y", 0)))
|
||||
g.size = Vector2(maxf(80.0, float(d.get("w", 320))), maxf(TITLE_H, float(d.get("h", 200))))
|
||||
g.collapsed = bool(d.get("collapsed", false))
|
||||
g.details = str(d.get("details", ""))
|
||||
var src: Variant = d.get("members", [])
|
||||
if src is Array:
|
||||
for m: Variant in src:
|
||||
var s := str(m)
|
||||
if s != "" and not g.members.has(s):
|
||||
g.members.append(s)
|
||||
return g
|
||||
1
core/table_group.gd.uid
Normal file
1
core/table_group.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://fprfxvlr1drh
|
||||
373
core/template_kit.gd
Normal file
373
core/template_kit.gd
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
class_name TemplateKit
|
||||
extends RefCounted
|
||||
## Templates: reusable blocks of cards saved from a board and dropped into any
|
||||
## collection. Pure data work, no UI; storage is TemplateLibrary.
|
||||
##
|
||||
## A template file:
|
||||
## {"format_version": 1, "name", "description", "kind": "card"|"group"|"selection",
|
||||
## "params": [{"name", "label", "default"}], "tables": [table, ...], "groups": [group, ...]}
|
||||
## Tables and groups use the collection format (JsonIO), with positions
|
||||
## relative to the template's top-left corner. Pipes between the template's own
|
||||
## tables keep their table ids. A pipe to a table outside the template is
|
||||
## recorded by that table's name, as {"table": "<name>", "outside": true, ...},
|
||||
## and is relinked by name when the template is inserted.
|
||||
##
|
||||
## Parameters are placeholders written {$name} in any text: table and entry
|
||||
## names, entry text, details, effects, expressions, prompts, variable names,
|
||||
## save_as. Inserting asks for their values and substitutes them everywhere.
|
||||
|
||||
const FORMAT_VERSION := 1
|
||||
const KINDS: Array[String] = ["card", "group", "selection"]
|
||||
const _PARAM_RE := "\\{\\$([A-Za-z_][A-Za-z0-9_]*)\\}"
|
||||
## Rough size of a card, for placing templates without groups.
|
||||
const CARD_SIZE := Vector2(256, 180)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- save
|
||||
|
||||
## Builds a template from tables on `board`. `table_ids` are the tables to
|
||||
## include (a group's members are added for every id in `group_ids`). Params
|
||||
## are detected from the {$name} placeholders, with an empty label and default.
|
||||
static func make(board: TowerBoard, table_ids: Array, kind: String, tname: String,
|
||||
description: String = "", group_ids: Array = []) -> Dictionary:
|
||||
var want := {}
|
||||
for tid: Variant in table_ids:
|
||||
if board.get_table(str(tid)):
|
||||
want[str(tid)] = true
|
||||
var groups: Array[TableGroup] = []
|
||||
for gid: Variant in group_ids:
|
||||
var g := board.get_group(str(gid))
|
||||
if g:
|
||||
groups.append(g)
|
||||
for m in g.members:
|
||||
want[m] = true
|
||||
# The top-left corner: the tables' corner, or a group frame's when it's further out.
|
||||
var origin := Vector2(INF, INF)
|
||||
for t in board.tables:
|
||||
if want.has(t.id):
|
||||
origin = Vector2(minf(origin.x, t.position.x), minf(origin.y, t.position.y))
|
||||
for g in groups:
|
||||
origin = Vector2(minf(origin.x, g.position.x), minf(origin.y, g.position.y))
|
||||
if origin.x == INF:
|
||||
origin = Vector2.ZERO
|
||||
var tables: Array = []
|
||||
for t in board.tables:
|
||||
if not want.has(t.id):
|
||||
continue
|
||||
var d := JsonIO._canon_table(t.to_dict())
|
||||
d["x"] = int(d["x"] - origin.x)
|
||||
d["y"] = int(d["y"] - origin.y)
|
||||
for ed: Dictionary in d["entries"]:
|
||||
if not ed.has("pipes"):
|
||||
continue
|
||||
var pipes: Array = []
|
||||
for p: Variant in ed["pipes"]:
|
||||
var info := JsonIO.pipe_info(p)
|
||||
var target: String = info["table"]
|
||||
if want.has(target):
|
||||
pipes.append(p)
|
||||
continue
|
||||
var other := board.get_table(target)
|
||||
if other == null:
|
||||
continue
|
||||
var np := {"table": other.name, "outside": true}
|
||||
if p is Dictionary:
|
||||
for k in ["count", "save_as"]:
|
||||
if (p as Dictionary).has(k):
|
||||
np[k] = p[k]
|
||||
pipes.append(np)
|
||||
ed["pipes"] = pipes
|
||||
tables.append(d)
|
||||
var group_list: Array = []
|
||||
for g in groups:
|
||||
var gd := g.to_dict()
|
||||
gd["x"] = int(gd["x"] - origin.x)
|
||||
gd["y"] = int(gd["y"] - origin.y)
|
||||
var members: Array = []
|
||||
for m in g.members:
|
||||
if want.has(m):
|
||||
members.append(m)
|
||||
gd["members"] = members
|
||||
gd.erase("id")
|
||||
group_list.append(gd)
|
||||
var tpl := {
|
||||
"format_version": FORMAT_VERSION,
|
||||
"name": tname,
|
||||
"description": description,
|
||||
"kind": kind if KINDS.has(kind) else "selection",
|
||||
"params": [],
|
||||
"tables": tables,
|
||||
"groups": group_list,
|
||||
}
|
||||
var params: Array = []
|
||||
for n in detect_params(tpl):
|
||||
params.append({"name": n, "label": n.capitalize(), "default": ""})
|
||||
tpl["params"] = params
|
||||
return tpl
|
||||
|
||||
|
||||
## Every {$name} placeholder in a template's tables and groups, in the order
|
||||
## they first appear.
|
||||
static func detect_params(tpl: Dictionary) -> Array[String]:
|
||||
var found: Array[String] = []
|
||||
var re := RegEx.create_from_string(_PARAM_RE)
|
||||
var stack: Array = [tpl.get("tables", []), tpl.get("groups", [])]
|
||||
var strings: Array[String] = []
|
||||
_collect_strings(stack, strings)
|
||||
for s in strings:
|
||||
for m in re.search_all(s):
|
||||
var n := m.get_string(1)
|
||||
if not found.has(n):
|
||||
found.append(n)
|
||||
return found
|
||||
|
||||
|
||||
## Every String inside nested Arrays and Dictionaries (values only), in order.
|
||||
static func _collect_strings(v: Variant, out: Array[String]) -> void:
|
||||
# Iterative, so a deep template can't overflow the stack.
|
||||
var stack: Array = [v]
|
||||
while not stack.is_empty():
|
||||
var x: Variant = stack.pop_back()
|
||||
if x is String:
|
||||
out.append(x)
|
||||
elif x is Array:
|
||||
for i in range((x as Array).size() - 1, -1, -1):
|
||||
stack.append(x[i])
|
||||
elif x is Dictionary:
|
||||
var keys: Array = (x as Dictionary).keys()
|
||||
for i in range(keys.size() - 1, -1, -1):
|
||||
stack.append(x[keys[i]])
|
||||
|
||||
|
||||
## Replaces {$name} placeholders in every String of `v` (a deep copy is
|
||||
## returned). Names missing from `values` are left as typed.
|
||||
static func substitute(v: Variant, values: Dictionary) -> Variant:
|
||||
if v is String:
|
||||
return _sub_text(v, values)
|
||||
if v is Array:
|
||||
var a: Array = []
|
||||
for x: Variant in v:
|
||||
a.append(substitute(x, values))
|
||||
return a
|
||||
if v is Dictionary:
|
||||
var d := {}
|
||||
for k: Variant in v:
|
||||
d[k] = substitute(v[k], values)
|
||||
return d
|
||||
return v
|
||||
|
||||
|
||||
static func _sub_text(s: String, values: Dictionary) -> String:
|
||||
if not s.contains("{$"):
|
||||
return s
|
||||
var re := RegEx.create_from_string(_PARAM_RE)
|
||||
var out := ""
|
||||
var at := 0
|
||||
for m in re.search_all(s):
|
||||
out += s.substr(at, m.get_start() - at)
|
||||
var n := m.get_string(1)
|
||||
out += str(values[n]) if values.has(n) else m.get_string()
|
||||
at = m.get_end()
|
||||
return out + s.substr(at)
|
||||
|
||||
|
||||
## Text for checking an expression, name or effect that may hold
|
||||
## placeholders: every {$name} reads as the plain name `p`, so `@{$skill}`,
|
||||
## `2d6 + {$dm}` and a variable name `{$name}` all check as well formed.
|
||||
static func probe(text: String) -> String:
|
||||
if not text.contains("{$"):
|
||||
return text
|
||||
return RegEx.create_from_string(_PARAM_RE).sub(text, "p", true)
|
||||
|
||||
|
||||
## Parameter values with each param's default filled in where `given` lacks
|
||||
## one. A param with neither stays as typed ({$name}), so it shows.
|
||||
static func values_with_defaults(tpl: Dictionary, given: Dictionary = {}) -> Dictionary:
|
||||
var out := {}
|
||||
for p: Variant in tpl.get("params", []):
|
||||
if p is Dictionary:
|
||||
var n := str(p.get("name", ""))
|
||||
if n != "" and (given.has(n) or str(p.get("default", "")) != ""):
|
||||
out[n] = str(given.get(n, p.get("default", "")))
|
||||
for k: Variant in given:
|
||||
if not out.has(k):
|
||||
out[k] = str(given[k])
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- insert
|
||||
|
||||
## The template's size on the board: its group frames and cards (roughly).
|
||||
static func extent(tpl: Dictionary) -> Vector2:
|
||||
var e := Vector2.ZERO
|
||||
for t: Dictionary in tpl.get("tables", []):
|
||||
e = e.max(Vector2(float(t.get("x", 0)), float(t.get("y", 0))) + CARD_SIZE)
|
||||
for g: Dictionary in tpl.get("groups", []):
|
||||
e = e.max(Vector2(float(g.get("x", 0)) + float(g.get("w", 0)), float(g.get("y", 0)) + float(g.get("h", 0))))
|
||||
return e
|
||||
|
||||
|
||||
## Makes the template's tables and groups for `board`, without adding them:
|
||||
## parameters substituted (defaults for missing values), fresh table, entry
|
||||
## and group ids, positions offset by `origin`. Pipes to outside tables relink
|
||||
## to a table of that name on `board`, or are dropped.
|
||||
## Returns {"tables": Array[RollTable], "groups": Array[TableGroup],
|
||||
## "relinked": Array[String], "dropped": Array[String]} (the last two describe
|
||||
## each outside pipe, "Entry → Table").
|
||||
static func instantiate(tpl: Dictionary, values: Dictionary, board: TowerBoard, origin: Vector2) -> Dictionary:
|
||||
var vals := values_with_defaults(tpl, values)
|
||||
var src: Dictionary = substitute({"tables": tpl.get("tables", []), "groups": tpl.get("groups", [])}, vals)
|
||||
var id_map := {}
|
||||
for td: Variant in src["tables"]:
|
||||
if td is Dictionary:
|
||||
id_map[str(td.get("id", ""))] = TowerBoard.new_id("t")
|
||||
var by_name := {}
|
||||
for t in board.tables:
|
||||
var key := Formatter.strip_tags(t.name).strip_edges().to_lower()
|
||||
if not by_name.has(key):
|
||||
by_name[key] = t.id
|
||||
var tables: Array[RollTable] = []
|
||||
var relinked: Array[String] = []
|
||||
var dropped: Array[String] = []
|
||||
for td: Variant in src["tables"]:
|
||||
if not (td is Dictionary):
|
||||
continue
|
||||
var d: Dictionary = (td as Dictionary).duplicate(true)
|
||||
d["id"] = id_map[str(d.get("id", ""))]
|
||||
d["x"] = roundi(float(d.get("x", 0)) + origin.x)
|
||||
d["y"] = roundi(float(d.get("y", 0)) + origin.y)
|
||||
var entries: Array = []
|
||||
for ev: Variant in d.get("entries", []):
|
||||
if not (ev is Dictionary):
|
||||
continue
|
||||
var ed: Dictionary = ev
|
||||
ed["id"] = TowerBoard.new_id("e")
|
||||
var pipes: Array = []
|
||||
for p: Variant in ed.get("pipes", []):
|
||||
var info := JsonIO.pipe_info(p)
|
||||
var target: String = info["table"]
|
||||
var outside: bool = p is Dictionary and bool((p as Dictionary).get("outside", false))
|
||||
var what := "%s → %s" % [Formatter.strip_tags(str(ed.get("text", ""))), Formatter.strip_tags(target)]
|
||||
var to := ""
|
||||
if not outside and id_map.has(target):
|
||||
to = id_map[target]
|
||||
elif by_name.has(Formatter.strip_tags(target).strip_edges().to_lower()):
|
||||
to = by_name[Formatter.strip_tags(target).strip_edges().to_lower()]
|
||||
relinked.append(what)
|
||||
else:
|
||||
dropped.append(what)
|
||||
continue
|
||||
var np := {"table": to}
|
||||
if p is Dictionary:
|
||||
for k in ["count", "save_as"]:
|
||||
if (p as Dictionary).has(k):
|
||||
np[k] = p[k]
|
||||
pipes.append(np)
|
||||
ed["pipes"] = pipes
|
||||
entries.append(ed)
|
||||
d["entries"] = entries
|
||||
tables.append(RollTable.from_dict(d))
|
||||
var groups: Array[TableGroup] = []
|
||||
for gv: Variant in src["groups"]:
|
||||
if not (gv is Dictionary):
|
||||
continue
|
||||
var g := TableGroup.from_dict(gv)
|
||||
g.id = TowerBoard.new_id("g")
|
||||
g.position += origin
|
||||
var members: Array[String] = []
|
||||
for m in g.members:
|
||||
if id_map.has(m):
|
||||
members.append(id_map[m])
|
||||
g.members = members
|
||||
groups.append(g)
|
||||
return {"tables": tables, "groups": groups, "relinked": relinked, "dropped": dropped}
|
||||
|
||||
|
||||
## Adds an instantiated template (see instantiate) to the board. Returns the
|
||||
## same result.
|
||||
static func insert(tpl: Dictionary, values: Dictionary, board: TowerBoard, origin: Vector2) -> Dictionary:
|
||||
var r := instantiate(tpl, values, board, origin)
|
||||
for t: RollTable in r["tables"]:
|
||||
board.tables.append(t)
|
||||
for g: TableGroup in r["groups"]:
|
||||
board.groups.append(g)
|
||||
board.clean_groups()
|
||||
return r
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- checks
|
||||
|
||||
## Checks a parsed template file. Returns {"ok", "template", "errors"}; the
|
||||
## template has every key, with params cleaned up and placeholders found in
|
||||
## the text but not listed added.
|
||||
static func validate(data: Variant) -> Dictionary:
|
||||
var errors: Array[String] = []
|
||||
if not (data is Dictionary):
|
||||
errors.append("The file is not a template (expected a JSON object).")
|
||||
return {"ok": false, "template": {}, "errors": errors}
|
||||
var d: Dictionary = data
|
||||
var fv: Variant = JsonIO._num(d.get("format_version", 1), 1)
|
||||
if (fv is int or fv is float) and fv > FORMAT_VERSION:
|
||||
errors.append("format_version %s is newer than this version supports (%d)." % [str(fv), FORMAT_VERSION])
|
||||
if not (d.get("tables") is Array) or (d["tables"] as Array).is_empty():
|
||||
errors.append("The template has no \"tables\" list.")
|
||||
else:
|
||||
for i in (d["tables"] as Array).size():
|
||||
var t: Variant = d["tables"][i]
|
||||
if not (t is Dictionary) or not (t.get("entries", []) is Array):
|
||||
errors.append("Table #%d is not a table." % (i + 1))
|
||||
if not errors.is_empty():
|
||||
return {"ok": false, "template": {}, "errors": errors}
|
||||
var groups: Array = []
|
||||
if d.get("groups") is Array:
|
||||
for g: Variant in d["groups"]:
|
||||
if g is Dictionary:
|
||||
groups.append(g)
|
||||
var tpl := {
|
||||
"format_version": FORMAT_VERSION,
|
||||
"name": str(d.get("name", "")).strip_edges(),
|
||||
"description": str(d.get("description", "")),
|
||||
"kind": str(d.get("kind", "selection")) if KINDS.has(str(d.get("kind", ""))) else "selection",
|
||||
"params": [],
|
||||
"tables": d["tables"],
|
||||
"groups": groups,
|
||||
}
|
||||
if tpl["name"] == "":
|
||||
tpl["name"] = "Untitled template"
|
||||
var params: Array = []
|
||||
var seen := {}
|
||||
if d.get("params") is Array:
|
||||
for p: Variant in d["params"]:
|
||||
if p is Dictionary and str(p.get("name", "")) != "" and not seen.has(str(p["name"])):
|
||||
seen[str(p["name"])] = true
|
||||
params.append({"name": str(p["name"]), "label": str(p.get("label", str(p["name"]).capitalize())),
|
||||
"default": str(p.get("default", ""))})
|
||||
for n in detect_params(tpl):
|
||||
if not seen.has(n):
|
||||
params.append({"name": n, "label": n.capitalize(), "default": ""})
|
||||
tpl["params"] = params
|
||||
return {"ok": true, "template": tpl, "errors": errors}
|
||||
|
||||
|
||||
## "3 cards: roll, choice ×2 · 1 group" for the template list.
|
||||
static func summary(tpl: Dictionary) -> String:
|
||||
var kinds := {}
|
||||
var order: Array[String] = []
|
||||
var n := 0
|
||||
for t: Variant in tpl.get("tables", []):
|
||||
if not (t is Dictionary):
|
||||
continue
|
||||
n += 1
|
||||
var k := str(t.get("kind", "roll"))
|
||||
if not kinds.has(k):
|
||||
kinds[k] = 0
|
||||
order.append(k)
|
||||
kinds[k] += 1
|
||||
var parts := PackedStringArray()
|
||||
for k in order:
|
||||
parts.append(k if kinds[k] == 1 else "%s ×%d" % [k, kinds[k]])
|
||||
var s := "%d %s: %s" % [n, "card" if n == 1 else "cards", ", ".join(parts)]
|
||||
var g := (tpl.get("groups", []) as Array).size()
|
||||
if g > 0:
|
||||
s += " · %d %s" % [g, "group" if g == 1 else "groups"]
|
||||
return s
|
||||
1
core/template_kit.gd.uid
Normal file
1
core/template_kit.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dl3tlhrwdg73h
|
||||
158
core/template_library.gd
Normal file
158
core/template_library.gd
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
class_name TemplateLibrary
|
||||
extends RefCounted
|
||||
## Saved templates (see TemplateKit), shared by every collection: one JSON
|
||||
## file per template in <root>/templates/<slug>.json, plus the read-only
|
||||
## built-in templates shipped in res://templates/. With an empty root the
|
||||
## user's templates live in memory only (--sample runs and tests).
|
||||
|
||||
const BUILTIN_DIR := "res://templates"
|
||||
const BUILTIN_PREFIX := "builtin:"
|
||||
|
||||
var root: String
|
||||
var builtin_dir: String
|
||||
## Messages about files that couldn't be read or written (most recent last).
|
||||
var errors: PackedStringArray = []
|
||||
var _memory: Dictionary = {} # id -> template, when root is ""
|
||||
|
||||
|
||||
func _init(p_root: String = "user://", p_builtin_dir: String = BUILTIN_DIR) -> void:
|
||||
root = p_root
|
||||
builtin_dir = p_builtin_dir
|
||||
|
||||
|
||||
func templates_dir() -> String:
|
||||
return root.path_join("templates")
|
||||
|
||||
|
||||
func path_for(id: String) -> String:
|
||||
return templates_dir().path_join(id + ".json")
|
||||
|
||||
|
||||
static func is_builtin(id: String) -> bool:
|
||||
return id.begins_with(BUILTIN_PREFIX)
|
||||
|
||||
|
||||
## [{id, name, description, kind, builtin, template}]: the built-in templates
|
||||
## and the user's, sorted by name.
|
||||
func list() -> Array[Dictionary]:
|
||||
var out: Array[Dictionary] = []
|
||||
for f in _json_files(builtin_dir):
|
||||
var tpl := _read(builtin_dir.path_join(f))
|
||||
if not tpl.is_empty():
|
||||
out.append(_row(BUILTIN_PREFIX + f.get_basename(), tpl, true))
|
||||
if root == "":
|
||||
for id: String in _memory:
|
||||
out.append(_row(id, _memory[id], false))
|
||||
else:
|
||||
for f in _json_files(templates_dir()):
|
||||
var tpl2 := _read(templates_dir().path_join(f))
|
||||
if not tpl2.is_empty():
|
||||
out.append(_row(f.get_basename(), tpl2, false))
|
||||
out.sort_custom(func(a: Dictionary, b: Dictionary) -> bool:
|
||||
return str(a["name"]).naturalnocasecmp_to(str(b["name"])) < 0)
|
||||
return out
|
||||
|
||||
|
||||
func _row(id: String, tpl: Dictionary, builtin: bool) -> Dictionary:
|
||||
return {"id": id, "name": str(tpl.get("name", id)), "description": str(tpl.get("description", "")),
|
||||
"kind": str(tpl.get("kind", "selection")), "builtin": builtin, "template": tpl}
|
||||
|
||||
|
||||
static func _json_files(dir: String) -> PackedStringArray:
|
||||
var out := PackedStringArray()
|
||||
if dir == "" or not DirAccess.dir_exists_absolute(dir):
|
||||
return out
|
||||
for f in DirAccess.get_files_at(dir):
|
||||
if f.get_extension() == "json":
|
||||
out.append(f)
|
||||
return out
|
||||
|
||||
|
||||
func _read(path: String) -> Dictionary:
|
||||
var parsed: Variant = JSON.parse_string(FileAccess.get_file_as_string(path))
|
||||
var r := TemplateKit.validate(parsed)
|
||||
if not r["ok"]:
|
||||
errors.append("Template %s is unreadable: %s" % [path, "; ".join(r["errors"])])
|
||||
return {}
|
||||
return r["template"]
|
||||
|
||||
|
||||
## The template with this id, or {}.
|
||||
func get_template(id: String) -> Dictionary:
|
||||
if is_builtin(id):
|
||||
var p := builtin_dir.path_join(id.substr(BUILTIN_PREFIX.length()) + ".json")
|
||||
return _read(p) if FileAccess.file_exists(p) else {}
|
||||
if not LibraryStore.is_valid_id(id):
|
||||
return {}
|
||||
if root == "":
|
||||
return (_memory.get(id, {}) as Dictionary).duplicate(true)
|
||||
return _read(path_for(id)) if FileAccess.file_exists(path_for(id)) else {}
|
||||
|
||||
|
||||
func exists(id: String) -> bool:
|
||||
if root == "":
|
||||
return _memory.has(id)
|
||||
return LibraryStore.is_valid_id(id) and FileAccess.file_exists(path_for(id))
|
||||
|
||||
|
||||
## Saves a new template under a unique slug of its name. Returns the id, or "".
|
||||
func add(tpl: Dictionary) -> String:
|
||||
var base := LibraryStore.slugify(str(tpl.get("name", "template")))
|
||||
var id := base
|
||||
var n := 2
|
||||
while exists(id):
|
||||
id = "%s-%d" % [base, n]
|
||||
n += 1
|
||||
return id if _write(id, tpl) else ""
|
||||
|
||||
|
||||
func _write(id: String, tpl: Dictionary) -> bool:
|
||||
if root == "":
|
||||
_memory[id] = tpl.duplicate(true)
|
||||
return true
|
||||
var err := TowerBoard.write_text_atomic(path_for(id), JSON.stringify(tpl, " ", false))
|
||||
if err != OK:
|
||||
errors.append("Couldn't save %s: %s" % [path_for(id), error_string(err)])
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Renames a user template (the file keeps its id). Built-ins can't be renamed.
|
||||
func rename(id: String, new_name: String) -> bool:
|
||||
if is_builtin(id) or new_name.strip_edges() == "":
|
||||
return false
|
||||
var tpl := get_template(id)
|
||||
if tpl.is_empty():
|
||||
return false
|
||||
tpl["name"] = new_name.strip_edges()
|
||||
return _write(id, tpl)
|
||||
|
||||
|
||||
## Deletes a user template. Built-ins can't be deleted.
|
||||
func delete(id: String) -> bool:
|
||||
if is_builtin(id) or not exists(id):
|
||||
return false
|
||||
if root == "":
|
||||
return _memory.erase(id)
|
||||
return DirAccess.remove_absolute(path_for(id)) == OK
|
||||
|
||||
|
||||
## The template as file text, for exporting.
|
||||
func export_text(id: String) -> String:
|
||||
var tpl := get_template(id)
|
||||
return JSON.stringify(tpl, " ", false) if not tpl.is_empty() else ""
|
||||
|
||||
|
||||
## Imports template file text as a new user template.
|
||||
## Returns {"ok", "id", "name", "errors"}.
|
||||
func import_text(text: String) -> Dictionary:
|
||||
var json := JSON.new()
|
||||
if json.parse(text) != OK:
|
||||
return {"ok": false, "id": "", "name": "", "errors": ["Not valid JSON (line %d): %s" % [json.get_error_line(), json.get_error_message()]]}
|
||||
var r := TemplateKit.validate(json.data)
|
||||
if not r["ok"]:
|
||||
return {"ok": false, "id": "", "name": "", "errors": r["errors"]}
|
||||
var id := add(r["template"])
|
||||
if id == "":
|
||||
return {"ok": false, "id": "", "name": "", "errors": ["Couldn't save the template."]}
|
||||
return {"ok": true, "id": id, "name": str(r["template"]["name"]), "errors": []}
|
||||
1
core/template_library.gd.uid
Normal file
1
core/template_library.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bsrl76s1nghlo
|
||||
|
|
@ -14,6 +14,9 @@ var id: String = ""
|
|||
## Display name; free to change.
|
||||
var name: String = ""
|
||||
var tables: Array[RollTable] = []
|
||||
## Group cards (frames around blocks of tables). Optional; a table is in at
|
||||
## most one group. See TableGroup.
|
||||
var groups: Array[TableGroup] = []
|
||||
|
||||
|
||||
static func new_id(prefix: String) -> String:
|
||||
|
|
@ -30,7 +33,7 @@ func get_table(id: String) -> RollTable:
|
|||
return null
|
||||
|
||||
|
||||
## Removes a table and every pipe that pointed at it.
|
||||
## Removes a table, every pipe that pointed at it and its group membership.
|
||||
func remove_table(id: String) -> void:
|
||||
for i in range(tables.size() - 1, -1, -1):
|
||||
if tables[i].id == id:
|
||||
|
|
@ -38,6 +41,112 @@ func remove_table(id: String) -> void:
|
|||
for t in tables:
|
||||
for e in t.entries:
|
||||
e.pipes.erase(id)
|
||||
for g in groups:
|
||||
g.members.erase(id)
|
||||
|
||||
|
||||
# ---------- Groups ----------
|
||||
|
||||
func get_group(gid: String) -> TableGroup:
|
||||
for g in groups:
|
||||
if g.id == gid:
|
||||
return g
|
||||
return null
|
||||
|
||||
|
||||
## The group a table belongs to, or null.
|
||||
func group_of(table_id: String) -> TableGroup:
|
||||
for g in groups:
|
||||
if g.members.has(table_id):
|
||||
return g
|
||||
return null
|
||||
|
||||
|
||||
## True when the table is hidden inside a collapsed group.
|
||||
func is_hidden(table_id: String) -> bool:
|
||||
var g := group_of(table_id)
|
||||
return g != null and g.collapsed
|
||||
|
||||
|
||||
## Makes a group of the given tables (taking them out of any other group).
|
||||
func add_group(gname: String, member_ids: Array, gid: String = "") -> TableGroup:
|
||||
var g := TableGroup.new(gid if gid != "" else new_id("g"), gname)
|
||||
groups.append(g)
|
||||
for tid: Variant in member_ids:
|
||||
add_to_group(str(tid), g.id)
|
||||
return g
|
||||
|
||||
|
||||
## Puts a table in a group, taking it out of its old one. False if either is missing.
|
||||
func add_to_group(table_id: String, gid: String) -> bool:
|
||||
var g := get_group(gid)
|
||||
if g == null or get_table(table_id) == null:
|
||||
return false
|
||||
var old := group_of(table_id)
|
||||
if old == g:
|
||||
return true
|
||||
if old:
|
||||
old.members.erase(table_id)
|
||||
g.members.append(table_id)
|
||||
return true
|
||||
|
||||
|
||||
func remove_from_group(table_id: String) -> void:
|
||||
var g := group_of(table_id)
|
||||
if g:
|
||||
g.members.erase(table_id)
|
||||
|
||||
|
||||
## Removes the group only; its cards stay on the board.
|
||||
func ungroup(gid: String) -> void:
|
||||
for i in range(groups.size() - 1, -1, -1):
|
||||
if groups[i].id == gid:
|
||||
groups.remove_at(i)
|
||||
|
||||
|
||||
## Removes the group and every table in it. Returns the removed table ids.
|
||||
func delete_group(gid: String) -> Array[String]:
|
||||
var g := get_group(gid)
|
||||
var gone: Array[String] = []
|
||||
if g == null:
|
||||
return gone
|
||||
gone.assign(g.members.duplicate())
|
||||
ungroup(gid)
|
||||
for tid in gone:
|
||||
remove_table(tid)
|
||||
return gone
|
||||
|
||||
|
||||
## Moves a group's frame and every member table by `delta`.
|
||||
func move_group(gid: String, delta: Vector2) -> void:
|
||||
var g := get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
g.position += delta
|
||||
for tid in g.members:
|
||||
var t := get_table(tid)
|
||||
if t:
|
||||
t.position += delta
|
||||
|
||||
|
||||
## Drops members that aren't tables, keeps each table in its first group only,
|
||||
## and gives groups unique ids. Empty groups are kept (they can be refilled).
|
||||
func clean_groups() -> void:
|
||||
var ids := {}
|
||||
for t in tables:
|
||||
ids[t.id] = true
|
||||
var taken := {}
|
||||
var gids := {}
|
||||
for g in groups:
|
||||
if g.id == "" or gids.has(g.id):
|
||||
g.id = new_id("g")
|
||||
gids[g.id] = true
|
||||
var keep: Array[String] = []
|
||||
for m in g.members:
|
||||
if ids.has(m) and not taken.has(m):
|
||||
taken[m] = true
|
||||
keep.append(m)
|
||||
g.members = keep
|
||||
|
||||
|
||||
## Upgrades a parsed file to FORMAT_VERSION, one version step at a time.
|
||||
|
|
@ -69,7 +178,13 @@ func to_dict() -> Dictionary:
|
|||
var list: Array = []
|
||||
for t in tables:
|
||||
list.append(t.to_dict())
|
||||
return {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
|
||||
var d := {"format_version": FORMAT_VERSION, "id": id, "name": name, "tables": list}
|
||||
if not groups.is_empty():
|
||||
var gl: Array = []
|
||||
for g in groups:
|
||||
gl.append(g.to_dict())
|
||||
d["groups"] = gl
|
||||
return d
|
||||
|
||||
|
||||
func to_json() -> String:
|
||||
|
|
@ -95,6 +210,14 @@ func load_dict(src: Dictionary) -> bool:
|
|||
if td is Dictionary:
|
||||
loaded.append(RollTable.from_dict(td))
|
||||
tables = loaded
|
||||
var loaded_groups: Array[TableGroup] = []
|
||||
var src_groups: Variant = d.get("groups", [])
|
||||
if src_groups is Array:
|
||||
for gd: Variant in src_groups:
|
||||
if gd is Dictionary:
|
||||
loaded_groups.append(TableGroup.from_dict(gd))
|
||||
groups = loaded_groups
|
||||
clean_groups()
|
||||
if str(d.get("id", "")) != "":
|
||||
id = str(d["id"])
|
||||
if str(d.get("name", "")) != "":
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ extends RefCounted
|
|||
## form), never on the model classes.
|
||||
##
|
||||
## Canonical collection form:
|
||||
## {"format_version": 2, "id", "name", "tables": [table, ...]}
|
||||
## {"format_version": 2, "id", "name", "tables": [table, ...], ["groups": [group, ...]]}
|
||||
## group: id, name, x, y, w, h, [collapsed], [details], members (table ids)
|
||||
## table: id, name, x, y, [collapsed], [details], [tags], [dice], [card_mode],
|
||||
## [deck_empty], [kind], [choice], [prompt], [save_as], [min], [max],
|
||||
## [loop], [loop_expr], [var_name], [var_type], [initial], entries
|
||||
|
|
@ -178,11 +179,47 @@ static func import_dict(data: Dictionary, sanitize: Callable = Callable()) -> Di
|
|||
else:
|
||||
pipes.append(target)
|
||||
ed["pipes"] = pipes
|
||||
_import_groups(c, id_map, by_name, clean, warnings)
|
||||
result["ok"] = true
|
||||
result["collection"] = c
|
||||
return result
|
||||
|
||||
|
||||
## Groups on import: members follow renamed table ids (or match a table by
|
||||
## name); unknown members are dropped, a table stays in its first group only,
|
||||
## and group ids are made unique.
|
||||
static func _import_groups(c: Dictionary, id_map: Dictionary, by_name: Dictionary, clean: Callable, warnings: Array[String]) -> void:
|
||||
if not c.has("groups"):
|
||||
return
|
||||
var taken := {}
|
||||
var gids := {}
|
||||
for g: Dictionary in c["groups"]:
|
||||
g["name"] = clean.call(str(g["name"]))
|
||||
if g.has("details"):
|
||||
g["details"] = clean.call(str(g["details"]))
|
||||
var gid := str(g["id"])
|
||||
if gid == "" or gids.has(gid):
|
||||
gid = unique_id(slug(str(g["name"]), "group"), gids)
|
||||
g["id"] = gid
|
||||
else:
|
||||
gids[gid] = true
|
||||
var keep: Array = []
|
||||
for m: String in g["members"]:
|
||||
var target := ""
|
||||
if id_map.has(m):
|
||||
target = id_map[m]
|
||||
elif by_name.has(m.to_lower()):
|
||||
target = by_name[m.to_lower()]
|
||||
if target == "":
|
||||
warnings.append("Group \"%s\" lists unknown table \"%s\"; left out." % [str(g["name"]), m])
|
||||
elif taken.has(target):
|
||||
warnings.append("\"%s\" was in more than one group; kept in the first." % m)
|
||||
else:
|
||||
taken[target] = true
|
||||
keep.append(target)
|
||||
g["members"] = keep
|
||||
|
||||
|
||||
# ------------------------------------------------------------ canonical
|
||||
|
||||
## Normalizes a collection to format version 2: legacy keys are converted
|
||||
|
|
@ -196,7 +233,40 @@ static func canonical(src: Dictionary) -> Dictionary:
|
|||
if t is Dictionary:
|
||||
tables.append(_canon_table(t))
|
||||
var cname := str(src.get("name", src.get("collection", "")))
|
||||
return {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
|
||||
var out := {"format_version": FORMAT_VERSION, "id": str(src.get("id", "")), "name": cname, "tables": tables}
|
||||
var groups: Array = []
|
||||
var src_groups: Variant = src.get("groups", [])
|
||||
if src_groups is Array:
|
||||
for g in src_groups:
|
||||
if g is Dictionary:
|
||||
groups.append(_canon_group(g))
|
||||
if not groups.is_empty():
|
||||
out["groups"] = groups
|
||||
return out
|
||||
|
||||
|
||||
static func _canon_group(gd: Dictionary) -> Dictionary:
|
||||
var g := {
|
||||
"id": str(gd.get("id", "")),
|
||||
"name": str(gd.get("name", "")),
|
||||
"x": int(_num(gd.get("x", 0), 0)),
|
||||
"y": int(_num(gd.get("y", 0), 0)),
|
||||
"w": int(_num(gd.get("w", 320), 320)),
|
||||
"h": int(_num(gd.get("h", 200), 200)),
|
||||
}
|
||||
if bool(gd.get("collapsed", false)):
|
||||
g["collapsed"] = true
|
||||
var details := str(gd.get("details", ""))
|
||||
if details != "":
|
||||
g["details"] = details
|
||||
var members: Array = []
|
||||
var src: Variant = gd.get("members", [])
|
||||
if src is Array:
|
||||
for m in src:
|
||||
if str(m) != "" and not members.has(str(m)):
|
||||
members.append(str(m))
|
||||
g["members"] = members
|
||||
return g
|
||||
|
||||
|
||||
static func _canon_table(td: Dictionary) -> Dictionary:
|
||||
|
|
|
|||
25
templates/2d-check.json
Normal file
25
templates/2d-check.json
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"format_version": 1,
|
||||
"name": "2D skill check",
|
||||
"description": "Pass or fail on 2d6 plus a skill's DM against a target number, as in most 2D games. The DM is read from a board variable, so effects elsewhere can raise it.",
|
||||
"kind": "card",
|
||||
"params": [
|
||||
{"name": "skill", "label": "Variable holding the DM (no @)", "default": "skill"},
|
||||
{"name": "target", "label": "Target number", "default": "8"}
|
||||
],
|
||||
"tables": [
|
||||
{
|
||||
"id": "check",
|
||||
"name": "{$skill} check, {$target}+",
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"details": "Rolls 2d6 + @{$skill} − {$target}, the check's Effect. An Effect of 0 or more passes.",
|
||||
"dice": "2d6 + @{$skill} - {$target}",
|
||||
"entries": [
|
||||
{"id": "e1", "text": "Fail", "range": [-1, -1]},
|
||||
{"id": "e2", "text": "Pass", "range": [0, 0]}
|
||||
]
|
||||
}
|
||||
],
|
||||
"groups": []
|
||||
}
|
||||
51
templates/ask-and-repeat.json
Normal file
51
templates/ask-and-repeat.json
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
{
|
||||
"format_version": 1,
|
||||
"name": "Ask how many, then repeat",
|
||||
"description": "Asks the player for a number, then rolls a table that many times. Fill the table with your own results.",
|
||||
"kind": "group",
|
||||
"params": [
|
||||
{"name": "what", "label": "What is rolled (plural)", "default": "Encounters"},
|
||||
{"name": "most", "label": "Highest number allowed", "default": "6"}
|
||||
],
|
||||
"tables": [
|
||||
{
|
||||
"id": "ask",
|
||||
"name": "How many {$what}?",
|
||||
"kind": "choice",
|
||||
"choice": "number",
|
||||
"prompt": "How many {$what}?",
|
||||
"min": "1",
|
||||
"max": "{$most}",
|
||||
"x": 22,
|
||||
"y": 68,
|
||||
"entries": [{"id": "e1", "text": "Answer", "pipes": ["repeat"]}]
|
||||
},
|
||||
{
|
||||
"id": "repeat",
|
||||
"name": "Repeat",
|
||||
"kind": "loop",
|
||||
"loop_expr": "answer",
|
||||
"x": 342,
|
||||
"y": 68,
|
||||
"entries": [
|
||||
{"id": "e1", "text": "{$what} {i}", "pipes": ["table"]},
|
||||
{"id": "e2", "text": "Done"}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "table",
|
||||
"name": "{$what}",
|
||||
"x": 662,
|
||||
"y": 68,
|
||||
"entries": [
|
||||
{"id": "e1", "text": "Result 1"},
|
||||
{"id": "e2", "text": "Result 2"},
|
||||
{"id": "e3", "text": "Result 3"},
|
||||
{"id": "e4", "text": "Result 4"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"groups": [
|
||||
{"name": "Repeat {$what}", "x": 0, "y": 0, "w": 940, "h": 330, "members": ["ask", "repeat", "table"]}
|
||||
]
|
||||
}
|
||||
39
templates/counter.json
Normal file
39
templates/counter.json
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"format_version": 1,
|
||||
"name": "Counter",
|
||||
"description": "A number variable and a card that adds one, takes one away or resets it. Read the variable in any expression, or show it in text with {@name}.",
|
||||
"kind": "group",
|
||||
"params": [
|
||||
{"name": "label", "label": "Name shown on the cards", "default": "Counter"},
|
||||
{"name": "name", "label": "Variable name (lowercase, no @)", "default": "counter"},
|
||||
{"name": "start", "label": "Starting value", "default": "0"}
|
||||
],
|
||||
"tables": [
|
||||
{
|
||||
"id": "var",
|
||||
"name": "{$label}",
|
||||
"kind": "variable",
|
||||
"var_name": "{$name}",
|
||||
"initial": "{$start}",
|
||||
"x": 22,
|
||||
"y": 68,
|
||||
"entries": []
|
||||
},
|
||||
{
|
||||
"id": "change",
|
||||
"name": "Change {$label}",
|
||||
"kind": "choice",
|
||||
"prompt": "{$label} is {@{$name}}. Change it?",
|
||||
"x": 342,
|
||||
"y": 68,
|
||||
"entries": [
|
||||
{"id": "e1", "text": "+1", "effects": "@{$name} += 1"},
|
||||
{"id": "e2", "text": "−1", "effects": "@{$name} -= 1"},
|
||||
{"id": "e3", "text": "Reset", "effects": "reset @{$name}"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"groups": [
|
||||
{"name": "{$label}", "x": 0, "y": 0, "w": 620, "h": 300, "members": ["var", "change"]}
|
||||
]
|
||||
}
|
||||
28
templates/pick-menu.json
Normal file
28
templates/pick-menu.json
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"format_version": 1,
|
||||
"name": "Pick menu",
|
||||
"description": "A question with three options. The player picks one, or presses Random to let the dice decide. Pipe each option onward.",
|
||||
"kind": "card",
|
||||
"params": [
|
||||
{"name": "question", "label": "Question", "default": "Which way?"},
|
||||
{"name": "option1", "label": "First option", "default": "Left"},
|
||||
{"name": "option2", "label": "Second option", "default": "Ahead"},
|
||||
{"name": "option3", "label": "Third option", "default": "Right"}
|
||||
],
|
||||
"tables": [
|
||||
{
|
||||
"id": "menu",
|
||||
"name": "{$question}",
|
||||
"kind": "choice",
|
||||
"prompt": "{$question}",
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"entries": [
|
||||
{"id": "e1", "text": "{$option1}"},
|
||||
{"id": "e2", "text": "{$option2}"},
|
||||
{"id": "e3", "text": "{$option3}"}
|
||||
]
|
||||
}
|
||||
],
|
||||
"groups": []
|
||||
}
|
||||
45
templates/simple-sheet.json
Normal file
45
templates/simple-sheet.json
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
{
|
||||
"format_version": 1,
|
||||
"name": "Simple sheet",
|
||||
"description": "Asks for a name, rolls a background, then prints both on a sheet card that stays up to date.",
|
||||
"kind": "group",
|
||||
"params": [
|
||||
{"name": "title", "label": "Sheet title", "default": "Character"}
|
||||
],
|
||||
"tables": [
|
||||
{
|
||||
"id": "name",
|
||||
"name": "Name",
|
||||
"kind": "choice",
|
||||
"choice": "text",
|
||||
"prompt": "What is the {$title}'s name?",
|
||||
"save_as": "@name",
|
||||
"x": 22,
|
||||
"y": 68,
|
||||
"entries": [{"id": "e1", "text": "Answer", "pipes": ["background"]}]
|
||||
},
|
||||
{
|
||||
"id": "background",
|
||||
"name": "Background",
|
||||
"x": 342,
|
||||
"y": 68,
|
||||
"entries": [
|
||||
{"id": "e1", "text": "Farmer", "effects": "@background = \"Farmer\"", "pipes": ["sheet"]},
|
||||
{"id": "e2", "text": "Soldier", "effects": "@background = \"Soldier\"", "pipes": ["sheet"]},
|
||||
{"id": "e3", "text": "Scholar", "effects": "@background = \"Scholar\"", "pipes": ["sheet"]},
|
||||
{"id": "e4", "text": "Merchant", "effects": "@background = \"Merchant\"", "pipes": ["sheet"]}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "sheet",
|
||||
"name": "{$title} sheet",
|
||||
"kind": "sheet",
|
||||
"x": 662,
|
||||
"y": 68,
|
||||
"entries": [{"id": "e1", "text": "[b]{$title}[/b]\nName: {@name}\nBackground: {@background}"}]
|
||||
}
|
||||
],
|
||||
"groups": [
|
||||
{"name": "{$title}", "x": 0, "y": 0, "w": 940, "h": 330, "members": ["name", "background", "sheet"]}
|
||||
]
|
||||
}
|
||||
345
tests/test_groups.gd
Normal file
345
tests/test_groups.gd
Normal file
|
|
@ -0,0 +1,345 @@
|
|||
extends SceneTree
|
||||
## Group cards: the model and file format, membership, and in the app the
|
||||
## frame, collapsing (hidden members, re-routed pipes, lit results, choice
|
||||
## pop-ups), moving, dropping cards in and out, ungroup and delete.
|
||||
## Run: godot --headless --path . -s res://tests/test_groups.gd -- --sample
|
||||
|
||||
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_model()
|
||||
_test_json()
|
||||
_test_import()
|
||||
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.rng.seed = 5
|
||||
await _load(_board_dict())
|
||||
await _test_group_from_selection()
|
||||
await _test_collapse()
|
||||
await _test_lit_and_choice()
|
||||
await _test_move()
|
||||
await _test_drop_in_and_out()
|
||||
await _test_collapse_all_and_fit()
|
||||
await _test_ungroup_and_delete()
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
## start -> a (in G) -> b (choice, in G) -> out
|
||||
func _board_dict() -> Dictionary:
|
||||
return {"format_version": 2, "id": "groups-test", "name": "Groups test", "tables": [
|
||||
{"id": "start", "name": "Start", "x": 40, "y": 60, "entries": [{"id": "e1", "text": "Go", "pipes": ["a"]}]},
|
||||
{"id": "a", "name": "Alpha", "x": 420, "y": 60, "entries": [
|
||||
{"id": "e1", "text": "A one", "pipes": ["b"]}, {"id": "e2", "text": "A two", "pipes": ["b"]}]},
|
||||
{"id": "b", "name": "Bravo", "kind": "choice", "prompt": "Which?", "x": 760, "y": 60, "entries": [
|
||||
{"id": "e1", "text": "B one", "pipes": ["out"]}, {"id": "e2", "text": "B two", "pipes": ["out"]}]},
|
||||
{"id": "out", "name": "Outside", "x": 1200, "y": 60, "entries": [{"id": "e1", "text": "Done"}]},
|
||||
{"id": "loose", "name": "Loose", "x": 40, "y": 520, "entries": [{"id": "e1", "text": "Free"}]},
|
||||
]}
|
||||
|
||||
|
||||
func _load(d: Dictionary) -> void:
|
||||
main.data.load_dict(d)
|
||||
main.lit_entries.clear()
|
||||
main.lit_pipes.clear()
|
||||
main.lit_texts.clear()
|
||||
main._rebuild_cards()
|
||||
for i in 4:
|
||||
await process_frame
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- model
|
||||
|
||||
func _test_model() -> void:
|
||||
var b := TowerBoard.new()
|
||||
b.load_dict(_board_dict())
|
||||
var g := b.add_group("G", ["a", "b"])
|
||||
_check(b.group_of("a") == g and b.group_of("b") == g and b.group_of("start") == null, "add_group puts tables in the group")
|
||||
var h := b.add_group("H", ["b", "nope"])
|
||||
_check(b.group_of("b") == h and not g.has("b"), "a table moves to its new group (one group per table)")
|
||||
_check(h.members == ["b"], "missing tables aren't added: %s" % str(h.members))
|
||||
b.remove_from_group("b")
|
||||
_check(b.group_of("b") == null and h.members.is_empty(), "remove_from_group")
|
||||
_check(b.add_to_group("b", g.id) and g.members == ["a", "b"], "add_to_group")
|
||||
b.move_group(g.id, Vector2(10, 20))
|
||||
_check(b.get_table("a").position == Vector2(430, 80) and g.position == Vector2(10, 20), "move_group moves the frame and members")
|
||||
b.remove_table("a")
|
||||
_check(not g.has("a"), "removing a table removes its membership")
|
||||
var r := g.fit_rect([Rect2(100, 100, 50, 50)])
|
||||
_check(r == Rect2(100 - TableGroup.PAD, 100 - TableGroup.PAD - TableGroup.TITLE_H, 50 + TableGroup.PAD * 2, 50 + TableGroup.PAD * 2 + TableGroup.TITLE_H), "fit_rect pads the members and leaves room for the title: %s" % str(r))
|
||||
var gone := b.delete_group(g.id)
|
||||
_check(gone == ["b"] and b.get_table("b") == null and b.get_group(g.id) == null, "delete_group removes the group and its tables")
|
||||
b.ungroup(h.id)
|
||||
_check(b.groups.is_empty(), "ungroup removes the group")
|
||||
_check(b.get_table("start").entries[0].pipes.is_empty(), "pipes into deleted tables go")
|
||||
|
||||
|
||||
func _test_json() -> void:
|
||||
var b := TowerBoard.new()
|
||||
b.load_dict(_board_dict())
|
||||
var g := b.add_group("Middle", ["a", "b"])
|
||||
g.collapsed = true
|
||||
g.details = "The [b]middle[/b] bit"
|
||||
g.position = Vector2(400, 0)
|
||||
g.size = Vector2(700, 300)
|
||||
var text := b.to_json()
|
||||
var b2 := TowerBoard.new()
|
||||
_check(b2.load_json(text), "a board with groups loads")
|
||||
_check(b2.groups.size() == 1, "one group back")
|
||||
var g2 := b2.groups[0]
|
||||
_check(g2.id == g.id and g2.name == "Middle" and g2.collapsed and g2.details == g.details, "id, name, collapsed and details round-trip")
|
||||
_check(g2.position == Vector2(400, 0) and g2.size == Vector2(700, 300), "rect round-trips")
|
||||
_check(g2.members == ["a", "b"], "members round-trip")
|
||||
_check(b2.to_json() == text, "JSON round trip is exact")
|
||||
# Old files without groups load unchanged, and save without a groups key.
|
||||
var old := TowerBoard.new()
|
||||
var src := SampleBoard.create().to_dict()
|
||||
_check(not src.has("groups"), "boards without groups write no groups key")
|
||||
_check(old.load_dict(src) and old.groups.is_empty(), "an old file loads with no groups")
|
||||
_check(old.to_json() == SampleBoard.create().to_json() or JSON.parse_string(old.to_json())["tables"].size() == src["tables"].size(), "an old file saves the same tables")
|
||||
var v1 := TowerBoard.new()
|
||||
_check(v1.load_json(JSON.stringify({"format_version": 1, "tables": src["tables"]})) and v1.groups.is_empty(), "a version 1 file still loads")
|
||||
# Bad group data is cleaned on load.
|
||||
var messy := _board_dict()
|
||||
messy["groups"] = [{"id": "g1", "name": "One", "members": ["a", "ghost", "a"]},
|
||||
{"id": "g1", "name": "Two", "members": ["a", "b"]}, "not a group"]
|
||||
var b3 := TowerBoard.new()
|
||||
b3.load_dict(messy)
|
||||
_check(b3.groups.size() == 2 and b3.groups[0].members == ["a"], "unknown and repeated members dropped: %s" % str(b3.groups[0].members))
|
||||
_check(b3.groups[1].members == ["b"], "a table stays in its first group only")
|
||||
_check(b3.groups[0].id != b3.groups[1].id, "duplicate group ids are made unique")
|
||||
|
||||
|
||||
func _test_import() -> void:
|
||||
var d := _board_dict()
|
||||
d["groups"] = [{"id": "g", "name": "G", "x": 1, "y": 2, "w": 300, "h": 200, "collapsed": true,
|
||||
"members": ["a", "Bravo", "ghost"], "details": ""}]
|
||||
var canon := JsonIO.canonical(d)
|
||||
_check(canon.has("groups") and canon["groups"][0] == {"id": "g", "name": "G", "x": 1, "y": 2, "w": 300, "h": 200, "collapsed": true, "members": ["a", "Bravo", "ghost"]},
|
||||
"canonical keeps groups and drops empty details: %s" % str(canon.get("groups")))
|
||||
_check(not JsonIO.canonical(_board_dict()).has("groups"), "canonical has no groups key without groups")
|
||||
var r := JsonIO.import_dict(d)
|
||||
var gl: Array = r["collection"]["groups"]
|
||||
_check(r["ok"] and gl[0]["members"] == ["a", "b"], "import maps members by id or name and drops unknown ones: %s" % str(gl[0]["members"]))
|
||||
_check(str(r["warnings"]).contains("ghost"), "import warns about unknown members")
|
||||
var b := TowerBoard.new()
|
||||
_check(b.load_dict(r["collection"]) and b.groups.size() == 1 and b.groups[0].collapsed, "an imported collection keeps its groups")
|
||||
var res := JsonIO.import_json(JsonIO.export_json(b.to_dict()))
|
||||
_check(res["ok"] and res["collection"]["groups"][0]["members"] == ["a", "b"], "export and import round-trip groups")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- app
|
||||
|
||||
func _group() -> TableGroup:
|
||||
return main.data.groups[0] if not main.data.groups.is_empty() else null
|
||||
|
||||
|
||||
func _test_group_from_selection() -> void:
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
main.set_selection(["a", "b"])
|
||||
_check(main.card_for("a").is_selected() and main.selection.size() == 2, "cards show as selected")
|
||||
_check(main._sel_bar.visible, "the selection toolbar shows in Build")
|
||||
var g := main.group_selection()
|
||||
for i in 3:
|
||||
await process_frame
|
||||
_check(g != null and g.members == ["a", "b"], "Group makes a group of the selection")
|
||||
_check(main.selection.is_empty() and not main._sel_bar.visible, "grouping clears the selection")
|
||||
var node := main.group_node(g.id)
|
||||
_check(node != null and node.get_parent() == main.board.groups, "an expanded group's frame sits behind the pipes")
|
||||
var ra := Rect2(main.card_for("a").position, main.card_for("a").size)
|
||||
var rb := Rect2(main.card_for("b").position, main.card_for("b").size)
|
||||
_check(g.rect().encloses(ra) and g.rect().encloses(rb), "the frame fits around its members")
|
||||
_check(is_equal_approx(g.position.x, ra.position.x - TableGroup.PAD), "with padding: %s vs %s" % [str(g.position), str(ra.position)])
|
||||
_check(node.position == g.position and node.size == g.size, "the frame node follows the group")
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
|
||||
|
||||
func _test_collapse() -> void:
|
||||
var g := _group()
|
||||
main.toggle_group(g.id)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
var node := main.group_node(g.id)
|
||||
_check(g.collapsed and node.get_parent() == main.board.cards, "a collapsed group shows as a card")
|
||||
_check(not main.card_for("a").visible and not main.card_for("b").visible, "its members are hidden")
|
||||
_check(main.card_for("start").visible and main.card_for("out").visible, "other cards stay")
|
||||
var paths: Dictionary = main.board.pipes._paths
|
||||
var into: PackedVector2Array = paths.get("start:e1>a", PackedVector2Array())
|
||||
_check(not into.is_empty() and into[into.size() - 1].distance_to(node.inlet_point()) < 0.5, "a pipe into a member attaches to the group's inlet")
|
||||
var outp: PackedVector2Array = paths.get("b:e1>out", PackedVector2Array())
|
||||
_check(not outp.is_empty() and is_equal_approx(outp[0].x, node.position.x + node.size.x), "a pipe out of a member leaves from the group's right edge")
|
||||
_check(outp.is_empty() or outp[outp.size() - 1].distance_to(main.card_for("out").inlet_point()) < 0.5, "and still reaches its target")
|
||||
_check(not paths.has("a:e1>b"), "pipes inside the collapsed group aren't drawn")
|
||||
_check(main.board.pipes.pipe_at(into[into.size() / 2], 3.0) == "", "re-routed pipes can't be clicked")
|
||||
var gp: Dictionary = main.board.pipes.group_ports
|
||||
_check(not gp.is_empty(), "the group card gets an outlet port")
|
||||
_check(main.data.to_dict()["groups"][0]["collapsed"] == true, "collapsed is saved")
|
||||
|
||||
|
||||
func _test_lit_and_choice() -> void:
|
||||
var g := _group()
|
||||
var node := main.group_node(g.id)
|
||||
# A real roll through the hidden choice card: the pop-up opens and answers.
|
||||
main.prompt_hook = main._ask_player
|
||||
main.start_roll("start")
|
||||
var d: ChoiceDialog = null
|
||||
for i in 60:
|
||||
await process_frame
|
||||
d = main.pending_choice()
|
||||
if d:
|
||||
break
|
||||
_check(d != null, "a choice card hidden in a collapsed group still asks")
|
||||
_check(main.is_entry_lit("start", "e1") and main.lit_pipes.has("start:e1>a"), "the steps so far light up behind the pop-up")
|
||||
if d:
|
||||
d.answer(1)
|
||||
for i in 240:
|
||||
await process_frame
|
||||
if main.current.get("done", false):
|
||||
break
|
||||
_check(main.current.get("done", false), "the roll finishes after the answer")
|
||||
_check(main.is_entry_lit("b", "e2") and main.is_entry_lit("out", "e1"), "the picked option and what follows are lit")
|
||||
_check(main.lit_pipes.has("b:e2>out"), "the pipe out of the group is lit")
|
||||
node = main.group_node(g.id)
|
||||
var keys := main.lit_keys_for_group(g)
|
||||
_check(keys.has("b:e2") and (keys.has("a:e1") or keys.has("a:e2")), "the group knows its members' lit results: %s" % str(keys))
|
||||
_check(node.lit_rows.has("b:e2"), "the collapsed group card lists the lit results")
|
||||
await process_frame
|
||||
var outp: PackedVector2Array = main.board.pipes._paths.get("b:e2>out", PackedVector2Array())
|
||||
var row: Control = node.lit_rows.get("b:e2")
|
||||
if row and not outp.is_empty():
|
||||
var to_world := main.board.world.get_global_transform().affine_inverse()
|
||||
var mid := (to_world * row.get_global_rect().get_center()).y
|
||||
_check(absf(outp[0].y - mid) < 1.0, "a lit result's pipe leaves from its row on the group card")
|
||||
main.prompt_hook = func(_req: Dictionary) -> Variant: return 0
|
||||
# Fast roll: lights at once.
|
||||
main.start_roll("start", true)
|
||||
for i in 30:
|
||||
await process_frame
|
||||
if main.current.get("done", false):
|
||||
break
|
||||
_check(main.is_entry_lit("b", "e1"), "a fast roll lights hidden members too")
|
||||
main.set_group_collapsed(g.id, false)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
_check(main.card_for("a").visible and main.group_node(g.id).get_parent() == main.board.groups, "expanding shows the members again")
|
||||
|
||||
|
||||
func _test_move() -> void:
|
||||
var g := _group()
|
||||
var before_a := main.data.get_table("a").position
|
||||
var before_g := g.position
|
||||
main.move_group(g.id, Vector2(100, 50))
|
||||
_check(main.data.get_table("a").position == before_a + Vector2(100, 50), "moving a group moves its members")
|
||||
_check(main.card_for("b").position == main.data.get_table("b").position, "member cards follow")
|
||||
_check(g.position == before_g + Vector2(100, 50) and main.group_node(g.id).position == g.position, "and the frame")
|
||||
_check(main.data.get_table("start").position == Vector2(40, 60), "non-members stay put")
|
||||
# Collapsed groups move their hidden members too.
|
||||
main.set_group_collapsed(g.id, true)
|
||||
await process_frame
|
||||
main.move_group(g.id, Vector2(-100, -50))
|
||||
_check(main.data.get_table("a").position == before_a, "a collapsed group moves its hidden members")
|
||||
main.set_group_collapsed(g.id, false)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
|
||||
|
||||
func _test_drop_in_and_out() -> void:
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
var g := _group()
|
||||
var loose := main.card_for("loose")
|
||||
main.begin_card_drag(loose)
|
||||
var inside := g.position + Vector2(40, TableGroup.TITLE_H + 30)
|
||||
main.drag_card(loose, inside)
|
||||
_check(main._drag_over == main.group_node(g.id), "the frame under a dragged card lights as a drop target")
|
||||
main.end_card_drag(loose)
|
||||
_check(g.has("loose"), "dropping a card in a frame adds it to the group")
|
||||
for i in 3:
|
||||
await process_frame
|
||||
_check(g.rect().encloses(Rect2(loose.position, loose.size)), "the frame grows to fit")
|
||||
main.begin_card_drag(loose)
|
||||
main.drag_card(loose, g.position + g.size + Vector2(300, 300))
|
||||
main.end_card_drag(loose)
|
||||
_check(not g.has("loose") and main.data.group_of("loose") == null, "dragging a card out of its frame takes it out")
|
||||
# Multi-select drag moves every selected card.
|
||||
main.set_selection(["start", "loose"])
|
||||
var s0 := main.card_for("start").position
|
||||
var l0 := loose.position
|
||||
main.begin_card_drag(loose)
|
||||
main.drag_card(loose, l0 + Vector2(30, 40))
|
||||
main.end_card_drag(loose)
|
||||
_check(main.card_for("start").position == s0 + Vector2(30, 40) and loose.position == l0 + Vector2(30, 40), "selected cards move together")
|
||||
main.clear_selection()
|
||||
main.select_in_rect(Rect2(main.card_for("out").position - Vector2(5, 5), Vector2(20, 20)))
|
||||
_check(main.selection.keys() == ["out"], "a rubber band selects the cards it touches: %s" % str(main.selection.keys()))
|
||||
main.clear_selection()
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
for i in 3:
|
||||
await process_frame
|
||||
|
||||
|
||||
func _test_collapse_all_and_fit() -> void:
|
||||
var g := _group()
|
||||
main.set_all_collapsed(true)
|
||||
await process_frame
|
||||
_check(g.collapsed and not main.card_for("a").visible, "Collapse all collapses groups too")
|
||||
_check(main._collapse_all.text == "Expand all", "the button then offers Expand all")
|
||||
# Fit ignores hidden members: move one far away; the bounds don't reach it.
|
||||
main.data.get_table("a").position = Vector2(30000, 30000)
|
||||
main.card_for("a").position = Vector2(30000, 30000)
|
||||
var bounds := main.board.content_bounds()
|
||||
_check(bounds.end.x < 5000.0 and bounds.has_point(main.group_node(g.id).position + Vector2(5, 5)),
|
||||
"Fit counts the group card and leaves out its hidden cards: %s" % str(bounds))
|
||||
main.data.get_table("a").position = Vector2(420, 60)
|
||||
main.card_for("a").position = Vector2(420, 60)
|
||||
main.set_all_collapsed(false)
|
||||
await process_frame
|
||||
_check(not g.collapsed and main.card_for("a").visible, "Expand all expands groups")
|
||||
|
||||
|
||||
func _test_ungroup_and_delete() -> void:
|
||||
var g := _group()
|
||||
main.ungroup(g.id)
|
||||
await process_frame
|
||||
_check(main.data.groups.is_empty() and main.data.get_table("a") != null and main.card_for("a").visible, "Ungroup keeps the cards")
|
||||
main._undo()
|
||||
await process_frame
|
||||
g = _group()
|
||||
_check(g != null and g.members == ["a", "b"], "Ungroup can be undone")
|
||||
main.confirm_delete_group(g.id)
|
||||
await process_frame
|
||||
var modal: ModalCard = null
|
||||
for c in main.get_children():
|
||||
if c is ModalCard:
|
||||
modal = c
|
||||
_check(modal != null, "Delete group asks first")
|
||||
if modal:
|
||||
for b in modal.footer.get_children():
|
||||
if b is Button and (b as Button).text == "Delete group and cards":
|
||||
(b as Button).pressed.emit()
|
||||
await process_frame
|
||||
_check(main.data.groups.is_empty() and main.data.get_table("a") == null and main.data.get_table("b") == null, "deleting the group deletes its cards")
|
||||
_check(main.card_for("a") == null and main.data.get_table("start").entries[0].pipes.is_empty(), "their cards and the pipes into them go")
|
||||
_check(main._toast.visible and main._toast_undo.visible, "with an undo toast")
|
||||
main._undo()
|
||||
await process_frame
|
||||
_check(main.data.groups.size() == 1 and main.data.get_table("a") != null and main.card_for("b") != null, "undo brings the group and its cards back")
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print("FAIL ", what)
|
||||
1
tests/test_groups.gd.uid
Normal file
1
tests/test_groups.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://h61an7o1xats
|
||||
334
tests/test_templates.gd
Normal file
334
tests/test_templates.gd
Normal file
|
|
@ -0,0 +1,334 @@
|
|||
extends SceneTree
|
||||
## Templates: saving (placeholder detection, relative positions, pipes kept or
|
||||
## recorded by name), inserting (substitution, fresh ids, internal pipes kept,
|
||||
## outside pipes relinked or reported), the library and the built-in
|
||||
## templates, and the app's save, list and insert.
|
||||
## Run: godot --headless --path . -s res://tests/test_templates.gd -- --sample
|
||||
|
||||
const TMP_ROOT := "user://test_templates_tmp"
|
||||
|
||||
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_make()
|
||||
_test_insert()
|
||||
_test_validate()
|
||||
_test_library_memory()
|
||||
_test_library_files()
|
||||
_test_builtins()
|
||||
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
|
||||
await _test_app()
|
||||
print("%s: %d failure(s)" % ["PASS" if _failures == 0 else "FAIL", _failures])
|
||||
quit(1 if _failures else 0)
|
||||
|
||||
|
||||
## A check table and its outcome table, piping to "Wounds" outside.
|
||||
func _board() -> TowerBoard:
|
||||
var b := TowerBoard.new()
|
||||
b.load_dict({"tables": [
|
||||
{"id": "chk", "name": "{$skill} check", "x": 300, "y": 200, "dice": "2d6 + @{$skill} - {$target}",
|
||||
"details": "Target {$target}", "entries": [
|
||||
{"id": "e1", "text": "Fail", "range": [-1, -1], "effects": "@{$skill}_fails += 1", "pipes": ["wounds"]},
|
||||
{"id": "e2", "text": "Pass", "range": [0, 0], "pipes": [{"table": "outcome", "count": "{$n}", "save_as": "{$skill}_result"}]}]},
|
||||
{"id": "outcome", "name": "Outcome", "kind": "choice", "prompt": "How did {$skill} go?", "save_as": "@{$skill}_how",
|
||||
"x": 600, "y": 260, "entries": [{"id": "e1", "text": "Well"}, {"id": "e2", "text": "Badly", "pipes": ["wounds"]}]},
|
||||
{"id": "wounds", "name": "Wounds", "x": 900, "y": 200, "entries": [{"id": "e1", "text": "Ouch"}]},
|
||||
]})
|
||||
return b
|
||||
|
||||
|
||||
func _test_make() -> void:
|
||||
var b := _board()
|
||||
var tpl := TemplateKit.make(b, ["chk", "outcome"], "selection", "Skill check", "A check")
|
||||
_check(tpl["format_version"] == 1 and tpl["kind"] == "selection" and tpl["name"] == "Skill check", "header fields")
|
||||
var names: Array = []
|
||||
for p: Dictionary in tpl["params"]:
|
||||
names.append(p["name"])
|
||||
_check(names == ["skill", "target", "n"], "placeholders detected in order: %s" % str(names))
|
||||
var t0: Dictionary = tpl["tables"][0]
|
||||
var t1: Dictionary = tpl["tables"][1]
|
||||
_check(t0["x"] == 0 and t0["y"] == 0 and t1["x"] == 300 and t1["y"] == 60, "positions are relative to the top-left: %s %s" % [str(t0["x"]), str(t1["x"])])
|
||||
_check(t0["entries"][1]["pipes"] == [{"table": "outcome", "count": "{$n}", "save_as": "{$skill}_result"}], "internal pipes keep their target and options: %s" % str(t0["entries"][1]["pipes"]))
|
||||
_check(t0["entries"][0]["pipes"] == [{"table": "Wounds", "outside": true}], "an outside pipe is recorded by name: %s" % str(t0["entries"][0]["pipes"]))
|
||||
_check(not JSON.stringify(tpl).contains("\"wounds\""), "the outside table itself isn't in the template")
|
||||
_check(TemplateKit.summary(tpl) == "2 cards: roll, choice", "summary: %s" % TemplateKit.summary(tpl))
|
||||
# A group template keeps its group, relative to the frame's corner.
|
||||
var g := b.add_group("Check {$skill}", ["chk", "outcome"])
|
||||
g.position = Vector2(270, 130)
|
||||
g.size = Vector2(620, 400)
|
||||
var gt := TemplateKit.make(b, [], "group", "Group", "", [g.id])
|
||||
_check((gt["tables"] as Array).size() == 2 and (gt["groups"] as Array).size() == 1, "a group template has its members and the group")
|
||||
_check(gt["groups"][0]["x"] == 0 and gt["groups"][0]["y"] == 0 and gt["tables"][0]["x"] == 30 and gt["tables"][0]["y"] == 70, "positions relative to the group's corner")
|
||||
_check(gt["groups"][0]["members"] == ["chk", "outcome"] and not gt["groups"][0].has("id"), "group members by template table id")
|
||||
_check(TemplateKit.detect_params(gt).has("skill"), "placeholders in a group name count")
|
||||
_check(TemplateKit.probe("2d6 + @{$skill} - {$target}") == "2d6 + @p - p" and Expr.check(TemplateKit.probe("@{$x} + {$y}")) == "", "probe makes placeholder text checkable")
|
||||
_check(TableSettingsDialog.dice_ok_text("2d6 + @{$skill} - {$target}"), "Build accepts placeholders in dice")
|
||||
|
||||
|
||||
func _test_insert() -> void:
|
||||
var src := _board()
|
||||
var tpl := TemplateKit.make(src, ["chk", "outcome"], "selection", "Skill check")
|
||||
var b := TowerBoard.new()
|
||||
b.load_dict({"tables": [{"id": "w1", "name": "wounds", "x": 0, "y": 0, "entries": [{"id": "e1", "text": "Hurt"}]}]})
|
||||
var r := TemplateKit.insert(tpl, {"skill": "pilot", "target": "8", "n": "2"}, b, Vector2(1000, 500))
|
||||
var tables: Array = r["tables"]
|
||||
_check(tables.size() == 2 and b.tables.size() == 3, "insert adds the template's tables")
|
||||
var chk: RollTable = tables[0]
|
||||
var oc: RollTable = tables[1]
|
||||
_check(chk.name == "pilot check" and chk.dice == "2d6 + @pilot - 8" and chk.details == "Target 8", "names, dice and details substituted: %s / %s" % [chk.name, chk.dice])
|
||||
_check(chk.entries[0].effects == "@pilot_fails += 1", "effects substituted")
|
||||
_check(oc.prompt == "How did pilot go?" and oc.save_as == "@pilot_how", "prompts and save_as substituted")
|
||||
_check(chk.id != "chk" and oc.id != "outcome" and chk.id != oc.id, "fresh table ids")
|
||||
_check(chk.entries[0].id != "e1" and chk.entries[0].id != chk.entries[1].id, "fresh entry ids")
|
||||
_check(chk.position == Vector2(1000, 500) and oc.position == Vector2(1300, 560), "placed at the origin, keeping the layout")
|
||||
_check(chk.entries[1].pipes == [oc.id] and chk.entries[1].count_expr(oc.id) == "" and chk.entries[1].count_for(oc.id) == 2, "internal pipes follow the new ids, with their count")
|
||||
_check(chk.entries[1].save_for(oc.id) == "pilot_result", "and their save_as, substituted")
|
||||
_check(chk.entries[0].pipes == ["w1"] and oc.entries[1].pipes == ["w1"], "outside pipes relink to the table with that name (any case)")
|
||||
_check((r["relinked"] as Array).size() == 2 and (r["dropped"] as Array).is_empty(), "relinked pipes are reported: %s" % str(r["relinked"]))
|
||||
var again := TemplateKit.insert(tpl, {}, b, Vector2.ZERO)
|
||||
_check((again["tables"][0] as RollTable).id != chk.id, "a second insert gets new ids again")
|
||||
_check((again["tables"][0] as RollTable).name == "{$skill} check", "missing values without a default stay as typed")
|
||||
var empty := TowerBoard.new()
|
||||
var r2 := TemplateKit.insert(tpl, {"skill": "a", "target": "1", "n": "1"}, empty, Vector2.ZERO)
|
||||
_check((r2["dropped"] as Array).size() == 2 and (r2["tables"][0] as RollTable).entries[0].pipes.is_empty(), "outside pipes with no table of that name are dropped and listed: %s" % str(r2["dropped"]))
|
||||
# Group templates make the group.
|
||||
var gsrc := _board()
|
||||
var g := gsrc.add_group("{$skill} block", ["chk", "outcome"])
|
||||
g.position = Vector2(280, 140)
|
||||
var gt := TemplateKit.make(gsrc, [], "group", "G", "", [g.id])
|
||||
var b3 := TowerBoard.new()
|
||||
var r3 := TemplateKit.insert(gt, {"skill": "stealth"}, b3, Vector2(100, 100))
|
||||
_check(b3.groups.size() == 1 and b3.groups[0].name == "stealth block", "inserting a group template creates the group")
|
||||
_check(b3.groups[0].members.size() == 2 and b3.groups[0].members[0] == (r3["tables"][0] as RollTable).id, "with the new tables as members")
|
||||
_check(b3.groups[0].id != g.id and b3.groups[0].position == Vector2(100, 100), "a fresh group id, placed at the origin")
|
||||
|
||||
|
||||
func _test_validate() -> void:
|
||||
_check(not TemplateKit.validate("nope")["ok"], "text isn't a template")
|
||||
_check(not TemplateKit.validate({"tables": []})["ok"], "a template needs tables")
|
||||
_check(not TemplateKit.validate({"format_version": 9, "tables": [{"entries": []}]})["ok"], "newer versions are refused")
|
||||
var r := TemplateKit.validate({"tables": [{"name": "{$a}", "entries": []}], "params": [{"name": "b"}]})
|
||||
var names: Array = []
|
||||
for p: Dictionary in r["template"]["params"]:
|
||||
names.append(p["name"])
|
||||
_check(r["ok"] and names == ["b", "a"], "listed params are kept and unlisted placeholders added: %s" % str(names))
|
||||
_check(r["template"]["name"] == "Untitled template" and r["template"]["kind"] == "selection", "defaults filled in")
|
||||
|
||||
|
||||
func _test_library_memory() -> void:
|
||||
var lib := TemplateLibrary.new("")
|
||||
var tpl := TemplateKit.make(_board(), ["chk"], "card", "My check")
|
||||
var id := lib.add(tpl)
|
||||
_check(id == "my-check" and lib.exists(id), "add saves under a slug of the name")
|
||||
_check(lib.add(tpl) == "my-check-2", "names that are taken get a number")
|
||||
_check(lib.get_template(id)["name"] == "My check", "get_template")
|
||||
_check(lib.rename(id, "Renamed") and lib.get_template(id)["name"] == "Renamed", "rename keeps the id")
|
||||
var text := lib.export_text(id)
|
||||
_check(text.contains("\"Renamed\""), "export text")
|
||||
var imp := lib.import_text(text)
|
||||
_check(imp["ok"] and lib.get_template(imp["id"])["name"] == "Renamed", "import text")
|
||||
_check(not lib.import_text("{\"tables\": 3}")["ok"] and not lib.import_text("garbage")["ok"], "bad files are refused")
|
||||
_check(lib.delete(id) and not lib.exists(id), "delete")
|
||||
var builtin_id := ""
|
||||
for row: Dictionary in lib.list():
|
||||
if row["builtin"]:
|
||||
builtin_id = row["id"]
|
||||
_check(builtin_id != "" and not lib.rename(builtin_id, "x") and not lib.delete(builtin_id), "built-in templates can't be renamed or deleted")
|
||||
|
||||
|
||||
func _test_library_files() -> void:
|
||||
_wipe(TMP_ROOT)
|
||||
var lib := TemplateLibrary.new(TMP_ROOT)
|
||||
var id := lib.add(TemplateKit.make(_board(), ["chk", "outcome"], "selection", "Two cards"))
|
||||
_check(FileAccess.file_exists(TMP_ROOT.path_join("templates/two-cards.json")), "user templates are files in templates/")
|
||||
var lib2 := TemplateLibrary.new(TMP_ROOT)
|
||||
var found := false
|
||||
for row: Dictionary in lib2.list():
|
||||
if row["id"] == id and not row["builtin"]:
|
||||
found = true
|
||||
_check(found, "a new library lists the saved template")
|
||||
_check(lib2.rename(id, "Renamed") and TemplateLibrary.new(TMP_ROOT).get_template(id)["name"] == "Renamed", "rename is saved")
|
||||
_check(lib2.delete(id) and not FileAccess.file_exists(TMP_ROOT.path_join("templates/two-cards.json")), "delete removes the file")
|
||||
_wipe(TMP_ROOT)
|
||||
|
||||
|
||||
func _test_builtins() -> void:
|
||||
var lib := TemplateLibrary.new("")
|
||||
var rows: Array = []
|
||||
for row: Dictionary in lib.list():
|
||||
if row["builtin"]:
|
||||
rows.append(row)
|
||||
_check(rows.size() >= 5, "five built-in templates ship: %d" % rows.size())
|
||||
_check(lib.errors.is_empty(), "every built-in template reads: %s" % str(lib.errors))
|
||||
var want := {"builtin:2d-check": false, "builtin:ask-and-repeat": false, "builtin:pick-menu": false, "builtin:counter": false, "builtin:simple-sheet": false}
|
||||
for row: Dictionary in rows:
|
||||
if want.has(row["id"]):
|
||||
want[row["id"]] = true
|
||||
var tpl: Dictionary = row["template"]
|
||||
var b := TowerBoard.new()
|
||||
var r := TemplateKit.insert(tpl, {}, b, Vector2(50, 50))
|
||||
var text := b.to_json()
|
||||
_check(not text.contains("{$"), "%s: defaults fill every placeholder" % row["id"])
|
||||
_check((r["dropped"] as Array).is_empty(), "%s: no pipes lead outside" % row["id"])
|
||||
var declared := TemplateKit.detect_params(tpl)
|
||||
for p: Dictionary in tpl["params"]:
|
||||
_check(declared.has(str(p["name"])), "%s: param %s is used" % [row["id"], p["name"]])
|
||||
_check(str(p.get("label", "")) != "" and str(p.get("default", "")) != "", "%s: param %s has a label and default" % [row["id"], p["name"]])
|
||||
# Every inserted card rolls headless without errors.
|
||||
for t in b.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE:
|
||||
continue
|
||||
var ctx := Roller.new_context(b, RandomNumberGenerator.new())
|
||||
var n := Roller.roll(b, t.id, ctx.rng, 0, {}, ctx)
|
||||
_check(not n.is_empty() and not n.has("stop"), "%s: %s rolls" % [row["id"], t.name])
|
||||
var steps := Roller.flatten(n, [])
|
||||
for s: Dictionary in steps:
|
||||
for l: Variant in s.get("log", []):
|
||||
if l is Dictionary and l.get("error", false):
|
||||
_check(false, "%s: %s logs an error: %s" % [row["id"], t.name, str(l)])
|
||||
for k: String in want:
|
||||
_check(want[k], "built-in %s is listed" % k)
|
||||
var chk := lib.get_template("builtin:2d-check")
|
||||
var b2 := TowerBoard.new()
|
||||
var r2 := TemplateKit.insert(chk, {"skill": "pilot", "target": "8"}, b2, Vector2.ZERO)
|
||||
var t2: RollTable = r2["tables"][0]
|
||||
_check(t2.dice == "2d6 + @pilot - 8" and t2.name == "pilot check, 8+", "the 2D check reads 2d6 + @pilot against 8: %s" % t2.dice)
|
||||
var passes := 0
|
||||
var rng := RandomNumberGenerator.new()
|
||||
rng.seed = 3
|
||||
for i in 400:
|
||||
var ctx := Roller.new_context(b2, rng, {"pilot": {"value": 2, "source": ""}})
|
||||
var n := Roller.roll(b2, t2.id, rng, 0, {}, ctx)
|
||||
if (n["entry"] as TableEntry).text == "Pass":
|
||||
passes += 1
|
||||
# 2d6 + 2 >= 8 means 2d6 >= 6: 26/36 = 72%.
|
||||
_check(passes > 250 and passes < 330, "with DM +2, a target of 8 passes about 72%% of the time (%d/400)" % passes)
|
||||
|
||||
|
||||
func _test_app() -> void:
|
||||
main.data.load_dict({"id": "tpl-test", "name": "Templates", "tables": [
|
||||
{"id": "start", "name": "Start", "x": 40, "y": 40, "entries": [{"id": "e1", "text": "Go"}]},
|
||||
{"id": "wounds", "name": "Wounds", "x": 40, "y": 400, "entries": [{"id": "e1", "text": "Ouch"}]}]})
|
||||
main._rebuild_cards()
|
||||
await process_frame
|
||||
var lib := main.templates()
|
||||
_check(lib.root == "", "with --sample, templates stay in memory")
|
||||
# Save a card from the board through the dialog.
|
||||
var before := lib.list().size()
|
||||
main.data.get_table("start").name = "{$who} starts"
|
||||
main.save_template_from(["start"], "card")
|
||||
await process_frame
|
||||
var dlg := _top_modal()
|
||||
_check(dlg != null and dlg.title_label.text == "Save as template", "the save dialog opens")
|
||||
if dlg:
|
||||
_check(dlg.body.get_child_count() > 3, "it lists the parameters")
|
||||
_press(dlg, "Save template")
|
||||
await process_frame
|
||||
_check(lib.list().size() == before + 1, "Save template adds it to the library")
|
||||
main.data.get_table("start").name = "Start"
|
||||
# The picker lists built-ins and user templates, and searches.
|
||||
var picker := main.open_template_picker()
|
||||
await process_frame
|
||||
var ids := picker.shown_ids()
|
||||
_check(ids.has("builtin:2d-check") and ids.has("builtin:counter"), "the list shows the built-in templates")
|
||||
picker._search.text = "counter"
|
||||
picker.refresh()
|
||||
_check(picker.shown_ids() == ["builtin:counter"], "search filters the list: %s" % str(picker.shown_ids()))
|
||||
picker.select("builtin:counter")
|
||||
_press(picker, "Insert")
|
||||
await process_frame
|
||||
var form := _top_modal()
|
||||
_check(form != null and form.title_label.text.begins_with("Insert"), "a template with parameters asks for them")
|
||||
if form:
|
||||
_press(form, "Insert")
|
||||
for i in 3:
|
||||
await process_frame
|
||||
var counter := main.data.groups.back() as TableGroup if not main.data.groups.is_empty() else null
|
||||
_check(counter != null and counter.name == "Counter" and counter.members.size() == 2, "inserting the counter makes its group")
|
||||
var var_card: RollTable = null
|
||||
for t in main.data.tables:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name == "counter":
|
||||
var_card = t
|
||||
_check(var_card != null and main.card_for(var_card.id) != null, "its variable card is on the board")
|
||||
# Insert with values and an outside pipe that relinks.
|
||||
var tpl := TemplateKit.make(_board(), ["chk", "outcome"], "selection", "Check")
|
||||
var r := main.insert_template(tpl, {"skill": "stealth", "target": "9", "n": "1"})
|
||||
await process_frame
|
||||
var chk: RollTable = r["tables"][0]
|
||||
_check(main.card_for(chk.id) != null and chk.name == "stealth check", "the inserted cards appear")
|
||||
_check(chk.entries[0].pipes == ["wounds"], "an outside pipe relinks to Wounds on this board")
|
||||
var center := main.board.screen_to_world(main.board.size / 2.0)
|
||||
var ext := TemplateKit.extent(tpl)
|
||||
_check(chk.position.distance_to((center - ext / 2.0).round().max(Vector2(20, 20 + TableGroup.TITLE_H))) < 2.0, "placed around the view centre")
|
||||
_check(main._toast.visible and main._toast_undo.visible, "an undo toast follows")
|
||||
main._undo()
|
||||
await process_frame
|
||||
_check(main.data.get_table(chk.id) == null, "undo removes the inserted cards")
|
||||
# Dropped pipes get a report.
|
||||
main.data.remove_table("wounds")
|
||||
main._rebuild_cards()
|
||||
main.insert_template(tpl, {"skill": "x", "target": "1", "n": "1"})
|
||||
await process_frame
|
||||
var rep := _top_modal()
|
||||
_check(rep != null and rep.title_label.text.begins_with("Inserted"), "pipes that can't relink are listed in a report")
|
||||
if rep:
|
||||
rep.close()
|
||||
# The card settings dialog offers Save as template.
|
||||
main.set_mode(Main.Mode.BUILD)
|
||||
main.open_table_settings("start")
|
||||
await process_frame
|
||||
var sd := _top_modal()
|
||||
var has_btn := false
|
||||
if sd:
|
||||
for b in sd.footer.get_children():
|
||||
if b is Button and (b as Button).text == "Save as template…":
|
||||
has_btn = true
|
||||
_press(sd, "Save as template…")
|
||||
await process_frame
|
||||
_check(has_btn and _top_modal() != null and _top_modal().title_label.text == "Save as template", "⚙ settings → Save as template opens the save dialog")
|
||||
main.set_mode(Main.Mode.PLAY)
|
||||
|
||||
|
||||
func _top_modal() -> ModalCard:
|
||||
var top: ModalCard = null
|
||||
for c in main.get_children():
|
||||
if c is ModalCard and not c.is_queued_for_deletion():
|
||||
top = c
|
||||
return top
|
||||
|
||||
|
||||
func _press(d: ModalCard, text: String) -> void:
|
||||
for b in d.footer.get_children():
|
||||
if b is Button and (b as Button).text == text:
|
||||
(b as Button).pressed.emit()
|
||||
return
|
||||
_check(false, "no button %s" % text)
|
||||
|
||||
|
||||
func _wipe(dir: String) -> void:
|
||||
var tdir := dir.path_join("templates")
|
||||
if DirAccess.dir_exists_absolute(tdir):
|
||||
for f in DirAccess.get_files_at(tdir):
|
||||
DirAccess.remove_absolute(tdir.path_join(f))
|
||||
DirAccess.remove_absolute(tdir)
|
||||
if DirAccess.dir_exists_absolute(dir):
|
||||
DirAccess.remove_absolute(dir)
|
||||
|
||||
|
||||
func _check(ok: bool, what: String) -> void:
|
||||
if not ok:
|
||||
_failures += 1
|
||||
print("FAIL ", what)
|
||||
1
tests/test_templates.gd.uid
Normal file
1
tests/test_templates.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b1x4qfggccjm8
|
||||
|
|
@ -10,12 +10,18 @@ const WORLD_SIZE := 40000.0
|
|||
|
||||
var main: Main
|
||||
var world: Control
|
||||
var groups: GroupLayer
|
||||
var pipes: PipeLayer
|
||||
var cards: CardLayer
|
||||
var ports: PortLayer
|
||||
var overlay: Control
|
||||
var zoom: float = 1.0
|
||||
|
||||
var _panning := false
|
||||
var _banding := false
|
||||
var _band_from := Vector2.ZERO
|
||||
var _band_to := Vector2.ZERO
|
||||
var _press_at := Vector2(-1, -1)
|
||||
var _glow: GradientTexture2D
|
||||
var _dots: ImageTexture
|
||||
|
||||
|
|
@ -30,6 +36,9 @@ func setup(p_main: Main) -> void:
|
|||
world = Control.new()
|
||||
world.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
add_child(world)
|
||||
groups = GroupLayer.new()
|
||||
groups.main = main
|
||||
world.add_child(groups)
|
||||
pipes = PipeLayer.new()
|
||||
pipes.main = main
|
||||
world.add_child(pipes)
|
||||
|
|
@ -38,6 +47,12 @@ func setup(p_main: Main) -> void:
|
|||
ports = PortLayer.new()
|
||||
ports.main = main
|
||||
world.add_child(ports)
|
||||
# Drawn over the world: the rubber band of a Ctrl-drag selection.
|
||||
overlay = Control.new()
|
||||
overlay.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
overlay.set_anchors_and_offsets_preset(PRESET_FULL_RECT)
|
||||
overlay.draw.connect(_draw_band)
|
||||
add_child(overlay)
|
||||
|
||||
var img := Image.create(6, 6, false, Image.FORMAT_RGBA8)
|
||||
img.fill(Color(0, 0, 0, 0))
|
||||
|
|
@ -80,16 +95,11 @@ func set_zoom(z: float, around: Vector2 = Vector2(-1, -1)) -> void:
|
|||
world.position = around - anchor * zoom
|
||||
|
||||
|
||||
## Zooms to show every table, centred horizontally.
|
||||
## Zooms to show every table, centred horizontally. Cards hidden in collapsed
|
||||
## groups don't count; the group cards and frames do.
|
||||
func fit() -> void:
|
||||
var first := true
|
||||
var bounds := Rect2()
|
||||
for c in cards.get_children():
|
||||
var card := c as Control
|
||||
var r := Rect2(card.position, card.size)
|
||||
bounds = r if first else bounds.merge(r)
|
||||
first = false
|
||||
if first:
|
||||
var bounds := content_bounds()
|
||||
if bounds.size == Vector2.ZERO:
|
||||
return
|
||||
bounds = bounds.grow(20.0)
|
||||
zoom = clampf(minf(1.0, minf((size.x - 16.0) / bounds.size.x, (size.y - 16.0) / bounds.size.y)), MIN_ZOOM, MAX_ZOOM)
|
||||
|
|
@ -97,21 +107,58 @@ func fit() -> void:
|
|||
world.position = Vector2(maxf(8.0, (size.x - bounds.size.x * zoom) / 2.0), 8.0) - bounds.position * zoom
|
||||
|
||||
|
||||
## The world rect of every visible card, group card and group frame (empty
|
||||
## when there are none).
|
||||
func content_bounds() -> Rect2:
|
||||
var first := true
|
||||
var bounds := Rect2()
|
||||
for c in cards.get_children() + groups.get_children():
|
||||
var card := c as Control
|
||||
if card == null or not card.visible or card.is_queued_for_deletion():
|
||||
continue
|
||||
var r := Rect2(card.position, card.size)
|
||||
bounds = r if first else bounds.merge(r)
|
||||
first = false
|
||||
return bounds
|
||||
|
||||
|
||||
func _gui_input(ev: InputEvent) -> void:
|
||||
var mb := ev as InputEventMouseButton
|
||||
if mb:
|
||||
match mb.button_index:
|
||||
MOUSE_BUTTON_LEFT, MOUSE_BUTTON_MIDDLE:
|
||||
var build_left := mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD
|
||||
if mb.pressed:
|
||||
if mb.button_index == MOUSE_BUTTON_LEFT and main.mode == Main.Mode.BUILD:
|
||||
if build_left and (mb.ctrl_pressed or mb.meta_pressed):
|
||||
# Ctrl-drag on the felt: rubber-band selection.
|
||||
_banding = true
|
||||
_band_from = mb.position
|
||||
_band_to = mb.position
|
||||
overlay.queue_redraw()
|
||||
accept_event()
|
||||
return
|
||||
if build_left:
|
||||
var key := pipes.pipe_at(world_mouse(), 11.0)
|
||||
if key != "":
|
||||
main.open_pipe_options(key, mb.global_position)
|
||||
accept_event()
|
||||
return
|
||||
_press_at = mb.position
|
||||
_panning = true
|
||||
mouse_default_cursor_shape = CURSOR_DRAG
|
||||
else:
|
||||
if _banding and mb.button_index == MOUSE_BUTTON_LEFT:
|
||||
_banding = false
|
||||
overlay.queue_redraw()
|
||||
var a := screen_to_world(_band_from)
|
||||
var b := screen_to_world(_band_to)
|
||||
main.select_in_rect(Rect2(a.min(b), (a - b).abs()))
|
||||
accept_event()
|
||||
return
|
||||
# A plain click on the felt (no drag) clears the selection.
|
||||
if build_left and _press_at.x >= 0.0 and mb.position.distance_to(_press_at) < 4.0:
|
||||
main.clear_selection()
|
||||
_press_at = Vector2(-1, -1)
|
||||
_panning = false
|
||||
mouse_default_cursor_shape = CURSOR_ARROW
|
||||
accept_event()
|
||||
|
|
@ -132,7 +179,10 @@ func _gui_input(ev: InputEvent) -> void:
|
|||
return
|
||||
var mm := ev as InputEventMouseMotion
|
||||
if mm:
|
||||
if _panning:
|
||||
if _banding:
|
||||
_band_to = mm.position
|
||||
overlay.queue_redraw()
|
||||
elif _panning:
|
||||
world.position += mm.relative
|
||||
elif main.mode == Main.Mode.BUILD:
|
||||
pipes.hover_key = pipes.pipe_at(world_mouse(), 11.0)
|
||||
|
|
@ -149,6 +199,14 @@ func _gui_input(ev: InputEvent) -> void:
|
|||
accept_event()
|
||||
|
||||
|
||||
func _draw_band() -> void:
|
||||
if not _banding:
|
||||
return
|
||||
var r := Rect2(_band_from.min(_band_to), (_band_from - _band_to).abs())
|
||||
overlay.draw_rect(r, Color(Style.BRASS, 0.12))
|
||||
overlay.draw_rect(r, Style.BRASS, false, 1.5)
|
||||
|
||||
|
||||
func _notification(what: int) -> void:
|
||||
if what == NOTIFICATION_MOUSE_EXIT and pipes:
|
||||
pipes.hover_key = ""
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ var open: bool = true:
|
|||
set(value):
|
||||
open = value
|
||||
queue_redraw()
|
||||
## Drawn in light colours for the felt (see use_felt_colors).
|
||||
var on_felt := false
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
|
|
@ -26,4 +28,16 @@ func _draw() -> void:
|
|||
pts = PackedVector2Array([c + Vector2(-4, -2), c + Vector2(0, 2), c + Vector2(4, -2)])
|
||||
else:
|
||||
pts = PackedVector2Array([c + Vector2(-2, -4), c + Vector2(2, 0), c + Vector2(-2, 4)])
|
||||
draw_polyline(pts, Style.INK if is_hovered() else Style.MUTED, 2.0, true)
|
||||
if on_felt:
|
||||
draw_polyline(pts, Style.ON_FELT if is_hovered() else Style.ON_FELT_MUTED, 2.0, true)
|
||||
else:
|
||||
draw_polyline(pts, Style.INK if is_hovered() else Style.MUTED, 2.0, true)
|
||||
|
||||
|
||||
## Light colours, for a chevron on the felt (group title bars).
|
||||
func use_felt_colors() -> void:
|
||||
on_felt = true
|
||||
var normal := Style.box(Color(0, 0, 0, 0), 6)
|
||||
var hover := Style.box(Color(1, 1, 1, 0.08), 6)
|
||||
Style.skin_button(self, normal, hover, hover, Style.ON_FELT_MUTED)
|
||||
queue_redraw()
|
||||
|
|
|
|||
467
ui/group_card.gd
Normal file
467
ui/group_card.gd
Normal file
|
|
@ -0,0 +1,467 @@
|
|||
class_name GroupCard
|
||||
extends MarginContainer
|
||||
## A group on the board (see TableGroup). Expanded, it's a frame a little
|
||||
## darker than the felt, drawn behind its member cards, with a title bar
|
||||
## (chevron, name, member count, details pop-up; in Build a ⋯ menu). Dragging
|
||||
## the title bar moves the group and its members.
|
||||
##
|
||||
## Collapsed, the members are hidden and the group shows as one compact card
|
||||
## (drawn as a little stack) with its name, "N cards" and the last rolled
|
||||
## results of any lit members. Pipes into members then attach to its inlet, and
|
||||
## pipes out of members leave from its right edge (PipeLayer asks anchor_for).
|
||||
##
|
||||
## Main keeps expanded groups in BoardView.groups (behind the pipes) and
|
||||
## collapsed ones in BoardView.cards, with the table cards.
|
||||
|
||||
const INLET_Y := 30.0
|
||||
## Most lit results a collapsed group lists.
|
||||
const MAX_LIT := 6
|
||||
const MENU_DETAILS := 0
|
||||
const MENU_TEMPLATE := 1
|
||||
const MENU_UNGROUP := 2
|
||||
const MENU_DELETE := 3
|
||||
const MENU_TOGGLE := 4
|
||||
|
||||
var main: Main
|
||||
var group: TableGroup
|
||||
## "tid:eid" -> row, for the lit results a collapsed group lists.
|
||||
var lit_rows: Dictionary = {}
|
||||
|
||||
var _card: PanelContainer
|
||||
var _header: Control
|
||||
var _lit_keys: Array = []
|
||||
var _rolling := false
|
||||
var _drop := false
|
||||
var _dragging := false
|
||||
var _drag_last := Vector2.ZERO
|
||||
var _frame_box: StyleBoxFlat
|
||||
var _frame_drop: StyleBoxFlat
|
||||
var _band_box: StyleBoxFlat
|
||||
var _stack_box: StyleBoxFlat
|
||||
var _card_box: StyleBoxFlat
|
||||
var _card_rolling: StyleBoxFlat
|
||||
|
||||
|
||||
func setup(p_main: Main, p_group: TableGroup) -> void:
|
||||
main = p_main
|
||||
group = p_group
|
||||
mouse_filter = MOUSE_FILTER_IGNORE
|
||||
theme = Style.card_theme()
|
||||
_frame_box = Style.box(Color(0, 0, 0, 0.16), 16)
|
||||
Style.bordered(_frame_box, 1, Color(1, 1, 1, 0.08))
|
||||
_frame_drop = Style.box(Color(Style.BRASS, 0.08), 16)
|
||||
Style.bordered(_frame_drop, 2, Style.BRASS)
|
||||
_band_box = Style.box(Color(0, 0, 0, 0.16), 0)
|
||||
_band_box.corner_radius_top_left = 16
|
||||
_band_box.corner_radius_top_right = 16
|
||||
_stack_box = Style.bordered(Style.box(Color("#d9d3c2"), 10), 1, Color(0, 0, 0, 0.12))
|
||||
_card_box = Style.box(Style.CARD, 10)
|
||||
_card_box.shadow_color = Color(0, 0, 0, 0.32)
|
||||
_card_box.shadow_size = 16
|
||||
_card_box.shadow_offset = Vector2(0, 8)
|
||||
_card_rolling = _card_box.duplicate() as StyleBoxFlat
|
||||
Style.bordered(_card_rolling, 3, Style.BRASS)
|
||||
_card_rolling.set_expand_margin_all(3)
|
||||
_card_rolling.shadow_color = Color(Style.BRASS, 0.45)
|
||||
_card_rolling.shadow_size = 26
|
||||
_card_rolling.shadow_offset = Vector2.ZERO
|
||||
minimum_size_changed.connect(func() -> void: _shrink.call_deferred())
|
||||
rebuild()
|
||||
|
||||
|
||||
func rebuild() -> void:
|
||||
for c in get_children():
|
||||
remove_child(c)
|
||||
c.queue_free()
|
||||
lit_rows.clear()
|
||||
_card = null
|
||||
_header = null
|
||||
position = group.position
|
||||
if group.collapsed:
|
||||
_lit_keys = main.lit_keys_for_group(group)
|
||||
_build_compact()
|
||||
else:
|
||||
_lit_keys = []
|
||||
_build_frame()
|
||||
queue_redraw()
|
||||
|
||||
|
||||
## Follows the model's rect after the board refits the frame.
|
||||
func sync_rect() -> void:
|
||||
position = group.position
|
||||
if not group.collapsed:
|
||||
custom_minimum_size = group.size
|
||||
size = group.size
|
||||
queue_redraw()
|
||||
|
||||
|
||||
func _shrink() -> void:
|
||||
if group == null:
|
||||
return
|
||||
if group.collapsed:
|
||||
size = Vector2(card_width(), 0)
|
||||
else:
|
||||
size = group.size
|
||||
|
||||
|
||||
func card_width() -> float:
|
||||
return TableCard.BUILD_WIDTH if main.mode == Main.Mode.BUILD else TableCard.WIDTH
|
||||
|
||||
|
||||
func _draw() -> void:
|
||||
if group == null:
|
||||
return
|
||||
if group.collapsed:
|
||||
# Two card edges peeking out behind: a stack of cards.
|
||||
for k in [2, 1]:
|
||||
var off := Vector2(5.0 * k, 5.0 * k)
|
||||
draw_style_box(_stack_box, Rect2(off, size))
|
||||
return
|
||||
var r := Rect2(Vector2.ZERO, size)
|
||||
draw_style_box(_frame_drop if _drop else _frame_box, r)
|
||||
draw_style_box(_band_box, Rect2(0, 0, size.x, TableGroup.TITLE_H))
|
||||
|
||||
|
||||
# ---------- Expanded frame ----------
|
||||
|
||||
func _build_frame() -> void:
|
||||
custom_minimum_size = group.size
|
||||
size = group.size
|
||||
var col := VBoxContainer.new()
|
||||
col.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
col.add_theme_constant_override("separation", 0)
|
||||
add_child(col)
|
||||
var bar := PanelContainer.new()
|
||||
bar.add_theme_stylebox_override("panel", Style.box(Color(0, 0, 0, 0), 0, [10, 0, 10, 0]))
|
||||
bar.custom_minimum_size = Vector2(0, TableGroup.TITLE_H)
|
||||
bar.mouse_filter = MOUSE_FILTER_STOP
|
||||
bar.mouse_default_cursor_shape = CURSOR_MOVE
|
||||
bar.gui_input.connect(_on_title_input.bind(bar))
|
||||
bar.mouse_entered.connect(_show_details.bind(bar))
|
||||
col.add_child(bar)
|
||||
_header = bar
|
||||
var h := _hbox(8)
|
||||
h.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
bar.add_child(h)
|
||||
var chevron := ChevronButton.new()
|
||||
chevron.use_felt_colors()
|
||||
chevron.open = true
|
||||
chevron.tooltip_text = "Collapse %s into one card" % Formatter.strip_tags(group.name)
|
||||
chevron.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
chevron.pressed.connect(func() -> void: main.toggle_group(group.id))
|
||||
h.add_child(chevron)
|
||||
var build := main.mode == Main.Mode.BUILD
|
||||
if build:
|
||||
h.add_child(_name_edit(true))
|
||||
else:
|
||||
var title := Style.make_label(Formatter.strip_tags(group.name), Style.display(true), 20, Style.ON_FELT)
|
||||
title.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
title.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
title.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
title.custom_minimum_size = Vector2(30, 0)
|
||||
title.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
h.add_child(title)
|
||||
var count := Style.make_label(count_text(), Style.body(true), 13, Style.ON_FELT_MUTED)
|
||||
count.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
count.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
if group.details.strip_edges() != "":
|
||||
count.text += " " + RichText.INFO_MARK
|
||||
h.add_child(count)
|
||||
if build:
|
||||
h.add_child(_menu_button(true))
|
||||
|
||||
|
||||
func count_text() -> String:
|
||||
var n := group.members.size()
|
||||
return "%d %s" % [n, "card" if n == 1 else "cards"]
|
||||
|
||||
|
||||
func set_drop_target(on: bool) -> void:
|
||||
if _drop != on:
|
||||
_drop = on
|
||||
queue_redraw()
|
||||
|
||||
|
||||
# ---------- Collapsed card ----------
|
||||
|
||||
func _build_compact() -> void:
|
||||
custom_minimum_size = Vector2(card_width(), 0)
|
||||
_shrink.call_deferred()
|
||||
_card = PanelContainer.new()
|
||||
_card.mouse_filter = MOUSE_FILTER_STOP
|
||||
_card.add_theme_stylebox_override("panel", _card_rolling if _rolling else _card_box)
|
||||
_card.gui_input.connect(func(ev: InputEvent) -> void:
|
||||
# Clicks on the card body shouldn't pan the board.
|
||||
var mb := ev as InputEventMouseButton
|
||||
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
|
||||
_card.accept_event()
|
||||
)
|
||||
add_child(_card)
|
||||
var col := _vbox(0)
|
||||
_card.add_child(col)
|
||||
|
||||
var header := PanelContainer.new()
|
||||
var hs := Style.box(Color(0, 0, 0, 0), 0, [12, 10, 10, 9])
|
||||
hs.border_width_bottom = 1
|
||||
hs.border_color = Style.RULE
|
||||
header.add_theme_stylebox_override("panel", hs)
|
||||
header.mouse_filter = MOUSE_FILTER_STOP
|
||||
header.mouse_default_cursor_shape = CURSOR_MOVE
|
||||
header.gui_input.connect(_on_title_input.bind(header))
|
||||
header.mouse_entered.connect(_show_details.bind(header))
|
||||
col.add_child(header)
|
||||
_header = header
|
||||
var row := _hbox(8)
|
||||
header.add_child(row)
|
||||
var chevron := ChevronButton.new()
|
||||
chevron.open = false
|
||||
chevron.tooltip_text = "Expand %s" % Formatter.strip_tags(group.name)
|
||||
chevron.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
chevron.pressed.connect(func() -> void: main.toggle_group(group.id))
|
||||
row.add_child(chevron)
|
||||
var build := main.mode == Main.Mode.BUILD
|
||||
if build:
|
||||
row.add_child(_name_edit(false))
|
||||
else:
|
||||
var titles := _vbox(3)
|
||||
titles.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
titles.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
var title := Style.make_label(Formatter.strip_tags(group.name), Style.display(true), 20, Style.INK)
|
||||
title.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
title.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
titles.add_child(title)
|
||||
var sub := Style.make_label("Group · " + count_text(), Style.body(true), 12, Style.MUTED)
|
||||
if group.details.strip_edges() != "":
|
||||
sub.text += " " + RichText.INFO_MARK
|
||||
sub.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
titles.add_child(sub)
|
||||
row.add_child(titles)
|
||||
var badge := _stack_badge()
|
||||
row.add_child(badge)
|
||||
if build:
|
||||
row.add_child(_menu_button(false))
|
||||
|
||||
var pad := MarginContainer.new()
|
||||
pad.mouse_filter = MOUSE_FILTER_PASS
|
||||
pad.add_theme_constant_override("margin_top", 6)
|
||||
pad.add_theme_constant_override("margin_bottom", 8)
|
||||
col.add_child(pad)
|
||||
var list := _vbox(2)
|
||||
pad.add_child(list)
|
||||
var shown := _lit_keys.slice(maxi(0, _lit_keys.size() - MAX_LIT))
|
||||
if _lit_keys.size() > shown.size():
|
||||
var more := Style.make_label("+%d earlier results" % (_lit_keys.size() - shown.size()), Style.body_italic(true), 13, Style.MUTED)
|
||||
more.add_theme_constant_override("line_spacing", 0)
|
||||
var mm := MarginContainer.new()
|
||||
mm.add_theme_constant_override("margin_left", 14)
|
||||
mm.add_child(more)
|
||||
list.add_child(mm)
|
||||
for key: String in shown:
|
||||
list.add_child(_lit_row(key))
|
||||
if shown.is_empty():
|
||||
var names := PackedStringArray()
|
||||
for tid in group.members.slice(0, 3):
|
||||
var t := main.data.get_table(tid)
|
||||
if t:
|
||||
names.append(Formatter.strip_tags(t.name))
|
||||
var txt := ", ".join(names)
|
||||
if group.members.size() > 3:
|
||||
txt += " and %d more" % (group.members.size() - 3)
|
||||
var note := Style.make_label(txt if txt != "" else "No cards yet", Style.body_italic(true), 14, Style.MUTED)
|
||||
note.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
var nm := MarginContainer.new()
|
||||
nm.mouse_filter = MOUSE_FILTER_PASS
|
||||
nm.add_theme_constant_override("margin_left", 14)
|
||||
nm.add_theme_constant_override("margin_right", 14)
|
||||
nm.add_theme_constant_override("margin_top", 2)
|
||||
nm.add_theme_constant_override("margin_bottom", 2)
|
||||
nm.add_child(note)
|
||||
list.add_child(nm)
|
||||
|
||||
|
||||
## A small pile-of-cards mark with the member count, at the header's right.
|
||||
func _stack_badge() -> Control:
|
||||
var c := Control.new()
|
||||
c.custom_minimum_size = Vector2(30, 28)
|
||||
c.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
c.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
c.tooltip_text = count_text()
|
||||
c.draw.connect(func() -> void:
|
||||
var back := Style.bordered(Style.box(Color("#ddd6c4"), 3), 1, Style.COPPER_DARK)
|
||||
var front := Style.bordered(Style.box(Style.FELT, 3), 1, Style.FELT_DEEP)
|
||||
c.draw_style_box(back, Rect2(8, 2, 18, 22))
|
||||
c.draw_style_box(front, Rect2(3, 6, 18, 22))
|
||||
var s := str(group.members.size())
|
||||
var f := Style.display(true)
|
||||
var w := f.get_string_size(s, HORIZONTAL_ALIGNMENT_LEFT, -1, 14).x
|
||||
c.draw_string(f, Vector2(12.0 - w / 2.0, 22), s, HORIZONTAL_ALIGNMENT_LEFT, -1, 14, Style.BRASS)
|
||||
)
|
||||
return c
|
||||
|
||||
|
||||
func _lit_row(key: String) -> Control:
|
||||
var i := key.rfind(":")
|
||||
var tid := key.substr(0, i)
|
||||
var eid := key.substr(i + 1)
|
||||
var t := main.data.get_table(tid)
|
||||
var row := PanelContainer.new()
|
||||
row.mouse_filter = MOUSE_FILTER_PASS
|
||||
row.add_theme_stylebox_override("panel", Style.box(Style.LIT, 0, [14, 5, 22, 6]))
|
||||
var v := _vbox(1)
|
||||
row.add_child(v)
|
||||
var cap := Style.make_label(Formatter.strip_tags(t.name if t else tid).to_upper(), Style.caps(), 10, Style.COPPER_DARK)
|
||||
cap.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
cap.custom_minimum_size = Vector2(20, 0)
|
||||
cap.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(cap)
|
||||
var text := RichText.label(RichText.decorate(main.lit_text(tid, eid)), 15, Style.INK, true)
|
||||
text.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
RichText.hook_hover(text, main)
|
||||
v.add_child(text)
|
||||
row.mouse_entered.connect(func() -> void: main.details().show_entry(row, tid, eid))
|
||||
lit_rows[key] = row
|
||||
return row
|
||||
|
||||
|
||||
## Re-renders a collapsed group when the lit results of its members changed.
|
||||
func refresh_lit(keys: Array) -> void:
|
||||
if group.collapsed and keys != _lit_keys:
|
||||
rebuild()
|
||||
|
||||
|
||||
func set_rolling(on: bool) -> void:
|
||||
_rolling = on
|
||||
if is_instance_valid(_card):
|
||||
_card.add_theme_stylebox_override("panel", _card_rolling if on else _card_box)
|
||||
|
||||
|
||||
# ---------- Shared parts ----------
|
||||
|
||||
func _vbox(sep: int) -> VBoxContainer:
|
||||
var v := VBoxContainer.new()
|
||||
v.add_theme_constant_override("separation", sep)
|
||||
v.mouse_filter = MOUSE_FILTER_PASS
|
||||
return v
|
||||
|
||||
|
||||
func _hbox(sep: int) -> HBoxContainer:
|
||||
var h := HBoxContainer.new()
|
||||
h.add_theme_constant_override("separation", sep)
|
||||
h.mouse_filter = MOUSE_FILTER_PASS
|
||||
return h
|
||||
|
||||
|
||||
func _name_edit(on_felt: bool) -> LineEdit:
|
||||
var le := LineEdit.new()
|
||||
le.text = group.name
|
||||
le.placeholder_text = "Group name"
|
||||
le.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
le.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
le.custom_minimum_size = Vector2(40, 0)
|
||||
le.add_theme_font_override("font", Style.display(true))
|
||||
le.add_theme_font_size_override("font_size", 18)
|
||||
if on_felt:
|
||||
le.add_theme_color_override("font_color", Style.ON_FELT)
|
||||
le.add_theme_color_override("caret_color", Style.ON_FELT)
|
||||
le.add_theme_color_override("font_placeholder_color", Style.ON_FELT_MUTED)
|
||||
le.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color(0, 0, 0, 0.12), 6, [7, 3, 7, 3]), 1, Color(1, 1, 1, 0.14)))
|
||||
le.add_theme_stylebox_override("focus", Style.bordered(Style.box(Color(0, 0, 0, 0.25), 6, [7, 3, 7, 3]), 1, Style.BRASS))
|
||||
else:
|
||||
le.add_theme_stylebox_override("normal", Style.bordered(Style.box(Color.WHITE, 6, [7, 3, 7, 3]), 1, Style.RULE))
|
||||
le.tooltip_text = "Rename this group"
|
||||
le.text_changed.connect(func(s: String) -> void:
|
||||
group.name = s
|
||||
main.mark_dirty()
|
||||
)
|
||||
return le
|
||||
|
||||
|
||||
func _menu_button(on_felt: bool) -> MenuButton:
|
||||
var mb := MenuButton.new()
|
||||
mb.text = "⋯"
|
||||
mb.flat = false
|
||||
mb.tooltip_text = "Group options"
|
||||
mb.custom_minimum_size = Vector2(30, 26)
|
||||
mb.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
mb.add_theme_font_override("font", Style.body_bold(true))
|
||||
mb.add_theme_font_size_override("font_size", 16)
|
||||
var hover := Style.box(Color(1, 1, 1, 0.1) if on_felt else Color("#e6dfcd"), 6)
|
||||
for n in ["normal", "disabled", "focus"]:
|
||||
mb.add_theme_stylebox_override(n, Style.box(Color(0, 0, 0, 0), 6))
|
||||
for n in ["hover", "pressed", "hover_pressed"]:
|
||||
mb.add_theme_stylebox_override(n, hover)
|
||||
var fg := Style.ON_FELT if on_felt else Style.MUTED
|
||||
for c in ["font_color", "font_hover_color", "font_focus_color", "font_pressed_color", "font_hover_pressed_color"]:
|
||||
mb.add_theme_color_override(c, fg)
|
||||
mb.mouse_default_cursor_shape = CURSOR_POINTING_HAND
|
||||
var pm := mb.get_popup()
|
||||
ModalCard.style_popup(pm)
|
||||
pm.add_item("Expand" if group.collapsed else "Collapse", MENU_TOGGLE)
|
||||
pm.add_item("Details…", MENU_DETAILS)
|
||||
pm.add_item("Save as template…", MENU_TEMPLATE)
|
||||
pm.add_separator()
|
||||
pm.add_item("Ungroup (keep the cards)", MENU_UNGROUP)
|
||||
pm.add_item("Delete group and its cards…", MENU_DELETE)
|
||||
pm.id_pressed.connect(func(id: int) -> void:
|
||||
match id:
|
||||
MENU_TOGGLE:
|
||||
main.toggle_group(group.id)
|
||||
MENU_DETAILS:
|
||||
main.edit_group_details(group.id)
|
||||
MENU_TEMPLATE:
|
||||
main.save_template_from([], "group", [group.id])
|
||||
MENU_UNGROUP:
|
||||
main.ungroup(group.id)
|
||||
MENU_DELETE:
|
||||
main.confirm_delete_group(group.id)
|
||||
)
|
||||
return mb
|
||||
|
||||
|
||||
func _show_details(owner: Control) -> void:
|
||||
if _dragging or group.details.strip_edges() == "":
|
||||
return
|
||||
main.details().show_for(owner, Formatter.strip_tags(group.name), group.details,
|
||||
"Group · %s%s" % [count_text(), " · collapsed" if group.collapsed else ""])
|
||||
|
||||
|
||||
# ---------- Geometry (world coordinates) ----------
|
||||
|
||||
func inlet_point() -> Vector2:
|
||||
return Vector2(position.x, position.y + INLET_Y)
|
||||
|
||||
|
||||
## Where a pipe from a hidden member's entry leaves the collapsed card: that
|
||||
## result's row when it's listed, otherwise the right edge by the title.
|
||||
func anchor_for(tid: String, eid: String) -> Vector2:
|
||||
var row: Control = lit_rows.get(Roller.entry_key(tid, eid))
|
||||
if row != null and row.is_inside_tree():
|
||||
var to_world := main.board.world.get_global_transform().affine_inverse()
|
||||
var r := row.get_global_rect()
|
||||
return Vector2(position.x + size.x, (to_world * (r.position + Vector2(0, r.size.y / 2.0))).y)
|
||||
return Vector2(position.x + size.x, position.y + INLET_Y)
|
||||
|
||||
|
||||
# ---------- Input ----------
|
||||
|
||||
func _on_title_input(ev: InputEvent, owner: Control) -> void:
|
||||
var mb := ev as InputEventMouseButton
|
||||
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
|
||||
if mb.pressed:
|
||||
main.details().hide_for()
|
||||
_dragging = true
|
||||
_drag_last = main.board.world_mouse()
|
||||
if group.collapsed:
|
||||
get_parent().move_child(self, -1)
|
||||
elif _dragging:
|
||||
_dragging = false
|
||||
main.mark_dirty()
|
||||
owner.accept_event()
|
||||
return
|
||||
var mm := ev as InputEventMouseMotion
|
||||
if mm and _dragging:
|
||||
var delta := (main.board.world_mouse() - _drag_last).round()
|
||||
if delta != Vector2.ZERO:
|
||||
main.move_group(group.id, delta)
|
||||
_drag_last += delta
|
||||
owner.accept_event()
|
||||
1
ui/group_card.gd.uid
Normal file
1
ui/group_card.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://cilvo2ngxilho
|
||||
37
ui/group_layer.gd
Normal file
37
ui/group_layer.gd
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
class_name GroupLayer
|
||||
extends Control
|
||||
## Holds the frames of expanded groups, behind the pipes and the cards, and
|
||||
## keeps each frame fitted around its member cards. A group whose member is
|
||||
## being dragged is frozen, so the card can be dragged out of the frame.
|
||||
|
||||
var main: Main
|
||||
## Group ids that don't refit right now (a member is being dragged).
|
||||
var frozen: Dictionary = {}
|
||||
|
||||
|
||||
func _init() -> void:
|
||||
mouse_filter = MOUSE_FILTER_IGNORE
|
||||
# Controls only draw inside their own rect, so cover the whole world.
|
||||
size = Vector2(BoardView.WORLD_SIZE, BoardView.WORLD_SIZE)
|
||||
|
||||
|
||||
func _process(_delta: float) -> void:
|
||||
if main == null or main.data == null:
|
||||
return
|
||||
refit()
|
||||
|
||||
|
||||
## Fits every expanded, unfrozen group's frame around its visible members.
|
||||
func refit() -> void:
|
||||
for g in main.data.groups:
|
||||
if g.collapsed or frozen.has(g.id):
|
||||
continue
|
||||
var rects: Array = []
|
||||
for tid in g.members:
|
||||
var c := main.card_for(tid)
|
||||
if c and c.visible and c.size.x > 0.0:
|
||||
rects.append(Rect2(c.position, c.size))
|
||||
if g.fit_to(rects):
|
||||
var n := main.group_node(g.id)
|
||||
if n:
|
||||
n.sync_rect()
|
||||
1
ui/group_layer.gd.uid
Normal file
1
ui/group_layer.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://d2cejpciboh36
|
||||
746
ui/main.gd
746
ui/main.gd
|
|
@ -137,6 +137,7 @@ func _build_ui() -> void:
|
|||
board = BoardView.new()
|
||||
board.setup(self)
|
||||
root.add_child(board)
|
||||
_build_selection_bar()
|
||||
tray = ResultTray.new()
|
||||
tray.setup(self)
|
||||
root.add_child(tray)
|
||||
|
|
@ -341,12 +342,16 @@ func _rebuild_cards() -> void:
|
|||
board.cards.add_child(card)
|
||||
card.setup(self, t)
|
||||
cards[t.id] = card
|
||||
selection.clear()
|
||||
_rebuild_groups()
|
||||
_update_selection_bar()
|
||||
_update_collapse_all()
|
||||
|
||||
|
||||
func _refresh_lit() -> void:
|
||||
for card in cards.values():
|
||||
(card as TableCard).refresh_lit()
|
||||
_refresh_group_lits()
|
||||
|
||||
|
||||
func set_mode(m: Mode) -> void:
|
||||
|
|
@ -356,8 +361,11 @@ func set_mode(m: Mode) -> void:
|
|||
_hint.text = HINTS[m]
|
||||
_build_tools.visible = m == Mode.BUILD
|
||||
board.pipes.hover_key = ""
|
||||
clear_selection()
|
||||
for card in cards.values():
|
||||
(card as TableCard).rebuild()
|
||||
for n in _group_nodes.values():
|
||||
(n as GroupCard).rebuild()
|
||||
_update_endless_chip()
|
||||
|
||||
|
||||
|
|
@ -371,9 +379,15 @@ func mark_dirty() -> void:
|
|||
refresh_live()
|
||||
|
||||
|
||||
## True when an expanded group, or a table that isn't hidden in a collapsed
|
||||
## group, could still be collapsed.
|
||||
func _any_expanded() -> bool:
|
||||
for g in data.groups:
|
||||
if not g.collapsed:
|
||||
return true
|
||||
var hidden := hidden_groups()
|
||||
for t in data.tables:
|
||||
if not t.collapsed:
|
||||
if not t.collapsed and not hidden.has(t.id):
|
||||
return true
|
||||
return false
|
||||
|
||||
|
|
@ -394,11 +408,19 @@ func toggle_collapse(tid: String) -> void:
|
|||
mark_dirty()
|
||||
|
||||
|
||||
## Collapses or expands every table and every group.
|
||||
func set_all_collapsed(collapsed: bool) -> void:
|
||||
for t in data.tables:
|
||||
if t.collapsed != collapsed:
|
||||
t.collapsed = collapsed
|
||||
card_for(t.id).rebuild()
|
||||
var changed := false
|
||||
for g in data.groups:
|
||||
if g.collapsed != collapsed:
|
||||
g.collapsed = collapsed
|
||||
changed = true
|
||||
if changed:
|
||||
_rebuild_groups()
|
||||
mark_dirty()
|
||||
|
||||
|
||||
|
|
@ -436,13 +458,34 @@ func _make_add_menu() -> MenuButton:
|
|||
if i == 1:
|
||||
pm.add_separator("Logic cards")
|
||||
pm.add_item(str(ADD_KINDS[i][0]), i)
|
||||
pm.add_separator("Groups and templates")
|
||||
pm.add_item("From template…", MENU_FROM_TEMPLATE)
|
||||
pm.add_item("Group selected cards Ctrl+G", MENU_GROUP)
|
||||
pm.add_item("Save selection as template…", MENU_SAVE_SELECTION)
|
||||
pm.about_to_popup.connect(func() -> void:
|
||||
pm.set_item_disabled(pm.get_item_index(MENU_GROUP), selection.is_empty())
|
||||
pm.set_item_disabled(pm.get_item_index(MENU_SAVE_SELECTION), selection.is_empty())
|
||||
)
|
||||
pm.id_pressed.connect(func(id: int) -> void:
|
||||
var k: Array = ADD_KINDS[id]
|
||||
add_table(str(k[1]), str(k[2]))
|
||||
match id:
|
||||
MENU_FROM_TEMPLATE:
|
||||
open_template_picker()
|
||||
MENU_GROUP:
|
||||
group_selection()
|
||||
MENU_SAVE_SELECTION:
|
||||
save_selection_as_template()
|
||||
_:
|
||||
var k: Array = ADD_KINDS[id]
|
||||
add_table(str(k[1]), str(k[2]))
|
||||
)
|
||||
return mb
|
||||
|
||||
|
||||
const MENU_FROM_TEMPLATE := 100
|
||||
const MENU_GROUP := 101
|
||||
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:
|
||||
var center := board.screen_to_world(board.size / 2.0)
|
||||
|
|
@ -484,6 +527,7 @@ func _free_var_name(base: String) -> String:
|
|||
func reset_sample() -> void:
|
||||
var snap := _snapshot()
|
||||
data.tables = SampleBoard.create().tables
|
||||
data.groups.clear()
|
||||
lit_entries.clear()
|
||||
lit_pipes.clear()
|
||||
_rebuild_cards()
|
||||
|
|
@ -528,13 +572,18 @@ func delete_table(tid: String) -> void:
|
|||
if t == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
var in_group := data.group_of(tid)
|
||||
data.remove_table(tid)
|
||||
forget_table_state(tid)
|
||||
selection.erase(tid)
|
||||
var card := card_for(tid)
|
||||
cards.erase(tid)
|
||||
card.queue_free()
|
||||
for c in cards.values():
|
||||
(c as TableCard).rebuild()
|
||||
if in_group:
|
||||
_groups_changed()
|
||||
_update_selection_bar()
|
||||
mark_dirty()
|
||||
toast("Deleted %s" % t.name, snap)
|
||||
|
||||
|
|
@ -608,11 +657,603 @@ func _card_under_mouse() -> TableCard:
|
|||
var kids := board.cards.get_children()
|
||||
for i in range(kids.size() - 1, -1, -1):
|
||||
var card := kids[i] as TableCard
|
||||
if card and card.get_global_rect().has_point(gp):
|
||||
if card and card.visible and card.get_global_rect().has_point(gp):
|
||||
return card
|
||||
return null
|
||||
|
||||
|
||||
# ---------- Groups ----------
|
||||
# A group is a frame around a block of cards (TableGroup). Expanded, its
|
||||
# GroupCard sits in board.groups behind the pipes; collapsed, it sits with the
|
||||
# cards and its members are hidden. Groups are presentation only: rolling,
|
||||
# lighting and the tray never look at them.
|
||||
|
||||
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_over: GroupCard
|
||||
|
||||
|
||||
func group_node(gid: String) -> GroupCard:
|
||||
var n: GroupCard = _group_nodes.get(gid)
|
||||
return n if is_instance_valid(n) else null
|
||||
|
||||
|
||||
## Table id -> the GroupCard of the collapsed group hiding it.
|
||||
func hidden_groups() -> Dictionary:
|
||||
if _hidden_cache == null:
|
||||
var out := {}
|
||||
if data:
|
||||
for g in data.groups:
|
||||
var n := group_node(g.id)
|
||||
if g.collapsed and n:
|
||||
for tid in g.members:
|
||||
out[tid] = n
|
||||
_hidden_cache = out
|
||||
return _hidden_cache
|
||||
|
||||
|
||||
## Rebuilds every group's node, in the right layer, and hides the members of
|
||||
## collapsed groups.
|
||||
func _rebuild_groups() -> void:
|
||||
for n in _group_nodes.values():
|
||||
if is_instance_valid(n):
|
||||
if (n as Node).get_parent():
|
||||
(n as Node).get_parent().remove_child(n)
|
||||
(n as Node).queue_free()
|
||||
_group_nodes.clear()
|
||||
_hidden_cache = null
|
||||
if data == null or board == null:
|
||||
return
|
||||
for g in data.groups:
|
||||
var n := GroupCard.new()
|
||||
if g.collapsed:
|
||||
board.cards.add_child(n)
|
||||
else:
|
||||
board.groups.add_child(n)
|
||||
n.setup(self, g)
|
||||
_group_nodes[g.id] = n
|
||||
_apply_group_visibility()
|
||||
|
||||
|
||||
## After a membership or group change: rebuild the group nodes and keep the
|
||||
## rest in step.
|
||||
func _groups_changed() -> void:
|
||||
_rebuild_groups()
|
||||
_update_collapse_all()
|
||||
|
||||
|
||||
func _apply_group_visibility() -> void:
|
||||
_hidden_cache = null
|
||||
var hidden := hidden_groups()
|
||||
for tid: String in cards:
|
||||
var c: TableCard = cards[tid]
|
||||
var hide := hidden.has(tid)
|
||||
c.visible = not hide
|
||||
if hide and selection.erase(tid):
|
||||
c.set_selected(false)
|
||||
_update_selection_bar()
|
||||
|
||||
|
||||
## "tid:eid" keys of a group's lit results, in roll order.
|
||||
func lit_keys_for_group(g: TableGroup) -> Array:
|
||||
var members := {}
|
||||
for tid in g.members:
|
||||
members[tid] = true
|
||||
var out: Array = []
|
||||
for k: String in lit_texts:
|
||||
var i := k.rfind(":")
|
||||
if i > 0 and members.has(k.substr(0, i)):
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
func _refresh_group_lits() -> void:
|
||||
for g in data.groups:
|
||||
var n := group_node(g.id)
|
||||
if n and g.collapsed:
|
||||
n.refresh_lit(lit_keys_for_group(g))
|
||||
|
||||
|
||||
func toggle_group(gid: String) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
g.collapsed = not g.collapsed
|
||||
details().hide_for()
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
|
||||
|
||||
func set_group_collapsed(gid: String, collapsed: bool) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g and g.collapsed != collapsed:
|
||||
toggle_group(gid)
|
||||
|
||||
|
||||
## Moves a group and its members (dragging the title bar).
|
||||
func move_group(gid: String, delta: Vector2) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
data.move_group(gid, delta)
|
||||
for tid in g.members:
|
||||
var c := card_for(tid)
|
||||
if c:
|
||||
c.position = data.get_table(tid).position
|
||||
var n := group_node(gid)
|
||||
if n:
|
||||
n.sync_rect()
|
||||
|
||||
|
||||
## "Group 1", "Group 2"… whichever isn't used.
|
||||
func _free_group_name() -> String:
|
||||
var used := {}
|
||||
for g in data.groups:
|
||||
used[g.name] = true
|
||||
var k := 1
|
||||
while used.has("Group %d" % k):
|
||||
k += 1
|
||||
return "Group %d" % k
|
||||
|
||||
|
||||
## Ctrl+G: groups the selected cards (taking them out of any other group).
|
||||
func group_selection() -> TableGroup:
|
||||
var ids: Array[String] = []
|
||||
for t in data.tables:
|
||||
if selection.has(t.id):
|
||||
ids.append(t.id)
|
||||
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()
|
||||
var g := data.add_group(_free_group_name(), ids)
|
||||
var rects: Array = []
|
||||
for tid in ids:
|
||||
var c := card_for(tid)
|
||||
rects.append(Rect2(c.position, c.size))
|
||||
g.fit_to(rects)
|
||||
# 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)
|
||||
return g
|
||||
|
||||
|
||||
## Removes the group; its cards stay where they are.
|
||||
func ungroup(gid: String) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
data.ungroup(gid)
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
toast("Ungrouped “%s”" % Formatter.strip_tags(g.name), snap)
|
||||
|
||||
|
||||
func confirm_delete_group(gid: String) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var n := g.members.size()
|
||||
_add_modal(ModalCard.confirm("Delete group",
|
||||
"Delete “%s” and the %d %s in it? Pipes from other cards into them are removed too. You can undo this from the message that follows." % [Formatter.strip_tags(g.name), n, "card" if n == 1 else "cards"],
|
||||
"Delete group and cards", func() -> void: delete_group(gid), true))
|
||||
|
||||
|
||||
## Deletes a group and every card in it (undo from the toast).
|
||||
func delete_group(gid: String) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var snap := _snapshot()
|
||||
var gname := Formatter.strip_tags(g.name)
|
||||
var gone := data.delete_group(gid)
|
||||
for tid in gone:
|
||||
forget_table_state(tid)
|
||||
selection.erase(tid)
|
||||
var card := card_for(tid)
|
||||
cards.erase(tid)
|
||||
if card:
|
||||
card.get_parent().remove_child(card)
|
||||
card.queue_free()
|
||||
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)
|
||||
|
||||
|
||||
## The group details editor (Build): a card-styled dialog with the text.
|
||||
func edit_group_details(gid: String) -> void:
|
||||
var g := data.get_group(gid)
|
||||
if g == null:
|
||||
return
|
||||
var d := ModalCard.new("Details for %s" % Formatter.strip_tags(g.name), 520.0)
|
||||
var te := TextEdit.new()
|
||||
te.text = g.details
|
||||
te.placeholder_text = "Shown when hovering the group's title (BBCode)"
|
||||
te.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
||||
te.custom_minimum_size = Vector2(0, 120)
|
||||
ModalCard.style_text_edit(te)
|
||||
d.body.add_child(te)
|
||||
d.add_button("Cancel", "plain", d.close)
|
||||
d.add_button("Save", "primary", func() -> void:
|
||||
g.details = te.text.strip_edges()
|
||||
d.close()
|
||||
var n := group_node(gid)
|
||||
if n:
|
||||
n.rebuild()
|
||||
mark_dirty()
|
||||
)
|
||||
_add_modal(d)
|
||||
|
||||
|
||||
## The expanded group frame containing a world point (the smallest, if they overlap).
|
||||
func _frame_at(p: Vector2) -> TableGroup:
|
||||
var best: TableGroup = null
|
||||
for g in data.groups:
|
||||
if g.collapsed or not g.rect().has_point(p):
|
||||
continue
|
||||
if best == null or g.rect().get_area() < best.rect().get_area():
|
||||
best = g
|
||||
return best
|
||||
|
||||
|
||||
# ----- Card drags (TableCard calls these) -----
|
||||
|
||||
func begin_card_drag(card: TableCard) -> void:
|
||||
_drag_set.clear()
|
||||
if mode == Mode.BUILD and selection.has(card.table.id) and selection.size() > 1:
|
||||
for tid: String in selection:
|
||||
if cards.has(tid):
|
||||
_drag_set.append(tid)
|
||||
else:
|
||||
_drag_set.append(card.table.id)
|
||||
# The frames of the dragged cards' groups hold still, so a card can leave them.
|
||||
for tid in _drag_set:
|
||||
var g := data.group_of(tid)
|
||||
if g:
|
||||
board.groups.frozen[g.id] = true
|
||||
|
||||
|
||||
## Moves the dragged card (and the rest of a multi-selection) so `card` lands at `to`.
|
||||
func drag_card(card: TableCard, to: Vector2) -> void:
|
||||
var delta := to - card.position
|
||||
if _drag_set.size() > 1:
|
||||
# Keep every selected card on the board.
|
||||
for tid in _drag_set:
|
||||
var c := card_for(tid)
|
||||
delta.x = maxf(delta.x, 10.0 - c.position.x)
|
||||
delta.y = maxf(delta.y, 10.0 - c.position.y)
|
||||
for tid in _drag_set:
|
||||
var c := card_for(tid)
|
||||
c.position += delta
|
||||
c.table.position = c.position
|
||||
else:
|
||||
card.position = to
|
||||
card.table.position = to
|
||||
if mode == Mode.BUILD:
|
||||
var over := _frame_at(card.position + card.size / 2.0)
|
||||
var node := group_node(over.id) if over else null
|
||||
if node != _drag_over:
|
||||
if is_instance_valid(_drag_over):
|
||||
_drag_over.set_drop_target(false)
|
||||
_drag_over = node
|
||||
if node:
|
||||
node.set_drop_target(true)
|
||||
|
||||
|
||||
## Drop: in Build, a card dropped in a group frame joins it, and one dropped
|
||||
## outside its own (held) frame leaves it.
|
||||
func end_card_drag(_card: TableCard) -> void:
|
||||
if is_instance_valid(_drag_over):
|
||||
_drag_over.set_drop_target(false)
|
||||
_drag_over = null
|
||||
var joined := {}
|
||||
var left := 0
|
||||
if mode == Mode.BUILD:
|
||||
for tid in _drag_set:
|
||||
var c := card_for(tid)
|
||||
if c == null:
|
||||
continue
|
||||
var center := c.position + c.size / 2.0
|
||||
var g0 := data.group_of(tid)
|
||||
var target := _frame_at(center)
|
||||
if target != null and target != g0:
|
||||
data.add_to_group(tid, target.id)
|
||||
joined[target.name] = int(joined.get(target.name, 0)) + 1
|
||||
elif target == null and g0 != null and not g0.rect().has_point(center):
|
||||
data.remove_from_group(tid)
|
||||
left += 1
|
||||
board.groups.frozen.clear()
|
||||
_drag_set.clear()
|
||||
if not joined.is_empty() or left > 0:
|
||||
_groups_changed()
|
||||
var parts := PackedStringArray()
|
||||
for gname: String in joined:
|
||||
parts.append("added %d to “%s”" % [joined[gname], Formatter.strip_tags(gname)])
|
||||
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()
|
||||
|
||||
|
||||
# ----- Selection (Build) -----
|
||||
|
||||
## Table ids selected in Build mode (Ctrl/Shift-click, Ctrl-drag on the felt).
|
||||
var selection: Dictionary = {}
|
||||
var _sel_bar: PanelContainer
|
||||
var _sel_label: Label
|
||||
|
||||
|
||||
func is_selected(tid: String) -> bool:
|
||||
return selection.has(tid)
|
||||
|
||||
|
||||
func toggle_selected(tid: String) -> void:
|
||||
var c := card_for(tid)
|
||||
if c == null or not c.visible:
|
||||
return
|
||||
if selection.has(tid):
|
||||
selection.erase(tid)
|
||||
else:
|
||||
selection[tid] = true
|
||||
c.set_selected(selection.has(tid))
|
||||
_update_selection_bar()
|
||||
|
||||
|
||||
func set_selection(ids: Array) -> void:
|
||||
clear_selection()
|
||||
for tid: Variant in ids:
|
||||
var c := card_for(str(tid))
|
||||
if c and c.visible:
|
||||
selection[str(tid)] = true
|
||||
c.set_selected(true)
|
||||
_update_selection_bar()
|
||||
|
||||
|
||||
func clear_selection() -> void:
|
||||
for tid: String in selection:
|
||||
var c := card_for(tid)
|
||||
if c:
|
||||
c.set_selected(false)
|
||||
selection.clear()
|
||||
_update_selection_bar()
|
||||
|
||||
|
||||
## Adds every visible card touching a world rectangle to the selection.
|
||||
func select_in_rect(r: Rect2) -> void:
|
||||
for tid: String in cards:
|
||||
var c: TableCard = cards[tid]
|
||||
if c.visible and Rect2(c.position, c.size).intersects(r):
|
||||
selection[tid] = true
|
||||
c.set_selected(true)
|
||||
_update_selection_bar()
|
||||
|
||||
|
||||
func _build_selection_bar() -> void:
|
||||
_sel_bar = PanelContainer.new()
|
||||
var sb := Style.box(Style.FELT_DEEP, 10, [14, 7, 8, 7])
|
||||
Style.bordered(sb, 1, Color(1, 1, 1, 0.12))
|
||||
sb.shadow_color = Color(0, 0, 0, 0.4)
|
||||
sb.shadow_size = 14
|
||||
sb.shadow_offset = Vector2(0, 6)
|
||||
_sel_bar.add_theme_stylebox_override("panel", sb)
|
||||
var h := HBoxContainer.new()
|
||||
h.add_theme_constant_override("separation", 8)
|
||||
_sel_bar.add_child(h)
|
||||
_sel_label = Style.make_label("", Style.body_bold(), 15, Style.ON_FELT)
|
||||
_sel_label.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
h.add_child(_sel_label)
|
||||
var grp := Style.bar_button("Group", true)
|
||||
grp.tooltip_text = "Put the selected cards in a group (Ctrl+G)"
|
||||
grp.pressed.connect(func() -> void: group_selection())
|
||||
h.add_child(grp)
|
||||
var tpl := Style.bar_button("Save as template…")
|
||||
tpl.tooltip_text = "Save the selected cards as a reusable template"
|
||||
tpl.pressed.connect(save_selection_as_template)
|
||||
h.add_child(tpl)
|
||||
var clr := Style.bar_button("Clear")
|
||||
clr.tooltip_text = "Clear the selection (Esc)"
|
||||
clr.pressed.connect(clear_selection)
|
||||
h.add_child(clr)
|
||||
_sel_bar.hide()
|
||||
board.add_child(_sel_bar)
|
||||
board.resized.connect(_place_selection_bar)
|
||||
|
||||
|
||||
func _update_selection_bar() -> void:
|
||||
if _sel_bar == null:
|
||||
return
|
||||
var n := selection.size()
|
||||
_sel_bar.visible = n > 0 and mode == Mode.BUILD
|
||||
_sel_label.text = "%d %s selected" % [n, "card" if n == 1 else "cards"]
|
||||
_place_selection_bar.call_deferred()
|
||||
|
||||
|
||||
func _place_selection_bar() -> void:
|
||||
if _sel_bar and _sel_bar.visible:
|
||||
_sel_bar.reset_size()
|
||||
_sel_bar.position = Vector2((board.size.x - _sel_bar.size.x) / 2.0, 14.0)
|
||||
|
||||
|
||||
func _unhandled_input(ev: InputEvent) -> void:
|
||||
var k := ev as InputEventKey
|
||||
if k == null or not k.pressed or k.echo or mode != Mode.BUILD:
|
||||
return
|
||||
if k.keycode == KEY_G and (k.ctrl_pressed or k.meta_pressed):
|
||||
group_selection()
|
||||
get_viewport().set_input_as_handled()
|
||||
elif k.keycode == KEY_ESCAPE and not selection.is_empty():
|
||||
clear_selection()
|
||||
get_viewport().set_input_as_handled()
|
||||
|
||||
|
||||
# ---------- Templates ----------
|
||||
# Saved in user://templates (TemplateLibrary), shared by every collection.
|
||||
# --sample runs keep them in memory only.
|
||||
|
||||
var _templates: TemplateLibrary
|
||||
|
||||
|
||||
func templates() -> TemplateLibrary:
|
||||
if _templates == null:
|
||||
_templates = TemplateLibrary.new("user://" if _saving_enabled else "")
|
||||
return _templates
|
||||
|
||||
|
||||
## Opens the save dialog for a template of these tables (and groups).
|
||||
func save_template_from(table_ids: Array, kind: String, group_ids: Array = []) -> void:
|
||||
var tname := "Template"
|
||||
if kind == "card" and table_ids.size() == 1 and data.get_table(str(table_ids[0])):
|
||||
tname = Formatter.strip_tags(data.get_table(str(table_ids[0])).name)
|
||||
elif kind == "group" and group_ids.size() == 1 and data.get_group(str(group_ids[0])):
|
||||
tname = Formatter.strip_tags(data.get_group(str(group_ids[0])).name)
|
||||
var tpl := TemplateKit.make(data, table_ids, kind, tname, "", group_ids)
|
||||
if (tpl["tables"] as Array).is_empty():
|
||||
toast("Nothing to save: the template would have no cards")
|
||||
return
|
||||
if kind == "selection":
|
||||
tpl["name"] = "%d cards" % (tpl["tables"] as Array).size()
|
||||
_add_modal(TemplateForms.save_dialog(tpl, func(out: Dictionary) -> void:
|
||||
var id := templates().add(out)
|
||||
if id == "":
|
||||
toast("Couldn't save the template")
|
||||
else:
|
||||
toast("Saved template “%s”. Insert it from + Table ▾ → From template…" % out["name"])
|
||||
))
|
||||
|
||||
|
||||
## The selection as a template; groups whose cards are all selected come along.
|
||||
func save_selection_as_template() -> void:
|
||||
if selection.is_empty():
|
||||
toast("Select some cards first")
|
||||
return
|
||||
var gids: Array = []
|
||||
for g in data.groups:
|
||||
if g.members.is_empty():
|
||||
continue
|
||||
var all := true
|
||||
for m in g.members:
|
||||
if not selection.has(m):
|
||||
all = false
|
||||
break
|
||||
if all:
|
||||
gids.append(g.id)
|
||||
save_template_from(selection.keys(), "selection", gids)
|
||||
|
||||
|
||||
func open_template_picker() -> TemplatePicker:
|
||||
var p := TemplatePicker.new(self, templates())
|
||||
_add_modal(p)
|
||||
return p
|
||||
|
||||
|
||||
## Asks for the template's parameters (if it has any), then inserts it.
|
||||
func begin_template_insert(tpl: Dictionary) -> void:
|
||||
if (tpl.get("params", []) as Array).is_empty():
|
||||
insert_template(tpl, {})
|
||||
return
|
||||
_add_modal(TemplateForms.params_dialog(tpl, func(values: Dictionary) -> void: insert_template(tpl, values)))
|
||||
|
||||
|
||||
## Inserts a template at the view centre: parameters substituted, fresh ids,
|
||||
## 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()
|
||||
var ext := TemplateKit.extent(tpl)
|
||||
var center := board.screen_to_world(board.size / 2.0)
|
||||
var origin := (center - ext / 2.0).round()
|
||||
origin = Vector2(maxf(20.0, origin.x), maxf(20.0 + TableGroup.TITLE_H, origin.y))
|
||||
var r := TemplateKit.insert(tpl, values, data, origin)
|
||||
for t: RollTable in r["tables"]:
|
||||
if t.kind == RollTable.KIND_VARIABLE and t.var_name == "":
|
||||
t.var_name = _free_var_name("var")
|
||||
var card := TableCard.new()
|
||||
board.cards.add_child(card)
|
||||
card.setup(self, t)
|
||||
cards[t.id] = card
|
||||
_groups_changed()
|
||||
mark_dirty()
|
||||
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"]
|
||||
if not relinked.is_empty():
|
||||
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)
|
||||
else:
|
||||
toast(msg + " · %d left out" % dropped.size(), snap)
|
||||
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()))
|
||||
for what: String in dropped:
|
||||
d.body.add_child(ModalCard.note("• " + what, Style.INK))
|
||||
if not relinked.is_empty():
|
||||
d.body.add_child(ModalCard.section("Relinked (%d)" % relinked.size()))
|
||||
for what: String in relinked:
|
||||
d.body.add_child(ModalCard.note("• " + what))
|
||||
d.add_button("Done", "primary", d.close)
|
||||
_add_modal(d)
|
||||
return r
|
||||
|
||||
|
||||
func export_template(id: String) -> void:
|
||||
var text := templates().export_text(id)
|
||||
if text == "":
|
||||
toast("Couldn't read that template")
|
||||
return
|
||||
var dlg := FileDialog.new()
|
||||
dlg.use_native_dialog = true
|
||||
dlg.access = FileDialog.ACCESS_FILESYSTEM
|
||||
dlg.file_mode = FileDialog.FILE_MODE_SAVE_FILE
|
||||
dlg.title = "Export template"
|
||||
dlg.filters = PackedStringArray(["*.json ; TableTower template"])
|
||||
dlg.current_file = id.trim_prefix(TemplateLibrary.BUILTIN_PREFIX) + ".template.json"
|
||||
dlg.file_selected.connect(func(path: String) -> void:
|
||||
var err := TowerBoard.write_text_atomic(path, text)
|
||||
toast("Exported to %s" % path.get_file() if err == OK else "Couldn't write %s" % path.get_file())
|
||||
)
|
||||
dlg.visibility_changed.connect(func() -> void:
|
||||
if not dlg.visible:
|
||||
dlg.queue_free.call_deferred()
|
||||
)
|
||||
add_child(dlg)
|
||||
dlg.popup_centered_ratio(0.6)
|
||||
|
||||
|
||||
func import_template_file(picker: TemplatePicker = null) -> void:
|
||||
var dlg := FileDialog.new()
|
||||
dlg.use_native_dialog = true
|
||||
dlg.access = FileDialog.ACCESS_FILESYSTEM
|
||||
dlg.file_mode = FileDialog.FILE_MODE_OPEN_FILE
|
||||
dlg.title = "Import a template"
|
||||
dlg.filters = PackedStringArray(["*.json ; TableTower template"])
|
||||
dlg.file_selected.connect(func(path: String) -> void:
|
||||
var r := templates().import_text(FileAccess.get_file_as_string(path))
|
||||
if r["ok"]:
|
||||
toast("Imported template “%s”" % r["name"])
|
||||
if is_instance_valid(picker):
|
||||
picker.refresh()
|
||||
picker.select(r["id"])
|
||||
else:
|
||||
_add_modal(IoMenu.report_dialog("Couldn't import %s" % path.get_file(), {"errors": r["errors"]}))
|
||||
)
|
||||
dlg.visibility_changed.connect(func() -> void:
|
||||
if not dlg.visible:
|
||||
dlg.queue_free.call_deferred()
|
||||
)
|
||||
add_child(dlg)
|
||||
dlg.popup_centered_ratio(0.6)
|
||||
|
||||
|
||||
# ---------- Rolling ----------
|
||||
|
||||
## Rolls a table and plays the result down its pipes. A fast roll (Shift held
|
||||
|
|
@ -771,7 +1412,17 @@ func _play_one(n: Dictionary, my: int, depth: int) -> void:
|
|||
var stopped := n.has("stop")
|
||||
var card := card_for(t.id)
|
||||
var tumble: bool = not n.has("kind") or bool(n.get("random", false))
|
||||
if not stopped and card and tumble:
|
||||
# A table hidden in a collapsed group rolls on the group's card.
|
||||
var gcard: GroupCard = hidden_groups().get(t.id)
|
||||
if not stopped and gcard and tumble:
|
||||
gcard.set_rolling(true)
|
||||
await get_tree().create_timer(0.35).timeout
|
||||
if my != _token:
|
||||
return
|
||||
gcard = hidden_groups().get(t.id)
|
||||
if gcard:
|
||||
gcard.set_rolling(false)
|
||||
elif not stopped and card and tumble:
|
||||
card.set_rolling(true)
|
||||
for k in 8:
|
||||
card = card_for(t.id)
|
||||
|
|
@ -950,6 +1601,7 @@ func _run_cli(args: PackedStringArray) -> void:
|
|||
set_all_collapsed(true)
|
||||
_run_shell_cli(args)
|
||||
_run_logic_cli(args)
|
||||
await _run_group_cli(args)
|
||||
var roll := _arg_value(args, "--roll")
|
||||
if roll != "":
|
||||
start_roll(roll, args.has("--fast"))
|
||||
|
|
@ -958,6 +1610,13 @@ func _run_cli(args: PackedStringArray) -> void:
|
|||
if shot == "":
|
||||
return
|
||||
var delay := _arg_value(args, "--shot-delay")
|
||||
if args.has("--fit") or _arg_value(args, "--view") != "":
|
||||
# Let the tray settle first (it can change the board's size).
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
if args.has("--fit"):
|
||||
board.fit()
|
||||
_apply_view_flag(args)
|
||||
await get_tree().create_timer(delay.to_float() if delay != "" else (2.5 if roll != "" else 0.8)).timeout
|
||||
var img := get_viewport().get_texture().get_image()
|
||||
img.save_png(shot)
|
||||
|
|
@ -990,6 +1649,7 @@ func open_table_settings(table_id: String) -> void:
|
|||
if t == null:
|
||||
return
|
||||
var d := TableSettingsDialog.new(t)
|
||||
d.template_requested.connect(func() -> void: save_template_from([table_id], "card"))
|
||||
var snap := _snapshot()
|
||||
d.applied.connect(func(result: Dictionary) -> void:
|
||||
if result.get("deck_reset", false) and state and data.id != "":
|
||||
|
|
@ -1262,6 +1922,78 @@ func _run_logic_cli(args: PackedStringArray) -> void:
|
|||
tray._vars.confirm_reset_all()
|
||||
|
||||
|
||||
# ----- Group and template screenshot flags -----
|
||||
# --select=<id>,<id>… select cards (Build)
|
||||
# --group-selected[=<name>] group the selection
|
||||
# --collapse-groups / --expand-groups every group
|
||||
# --toggle-group=<group id> collapse or expand one group
|
||||
# --templates[=<search>] open the template list
|
||||
# --insert-template=<id> insert a template (builtin:<file> or a user id)
|
||||
# [--template-values=<name>=<value>|…]
|
||||
# --save-template=<table id> open the save dialog for one card
|
||||
# --save-group-template=<group id>
|
||||
# --view=<x>,<y>[,<zoom>] centre the view on a world point (after Fit)
|
||||
|
||||
func _run_group_cli(args: PackedStringArray) -> void:
|
||||
var sel := _arg_value(args, "--select")
|
||||
if sel != "":
|
||||
set_selection(Array(sel.split(",")))
|
||||
for a in args:
|
||||
if a == "--group-selected" or a.begins_with("--group-selected="):
|
||||
var g := group_selection()
|
||||
if g and a.contains("="):
|
||||
g.name = a.get_slice("=", 1)
|
||||
_groups_changed()
|
||||
if args.has("--collapse-groups") or args.has("--expand-groups"):
|
||||
for g in data.groups:
|
||||
g.collapsed = args.has("--collapse-groups")
|
||||
_groups_changed()
|
||||
var tg := _arg_value(args, "--toggle-group")
|
||||
if tg != "":
|
||||
for gid in tg.split(","):
|
||||
toggle_group(gid)
|
||||
var ins := _arg_value(args, "--insert-template")
|
||||
if ins != "":
|
||||
var tpl := templates().get_template(ins)
|
||||
var values := {}
|
||||
for pair in _arg_value(args, "--template-values").split("|", false):
|
||||
values[pair.get_slice("=", 0)] = pair.substr(pair.find("=") + 1)
|
||||
if tpl.is_empty():
|
||||
push_warning("No template %s" % ins)
|
||||
else:
|
||||
insert_template(tpl, values)
|
||||
var st := _arg_value(args, "--save-template")
|
||||
if st != "":
|
||||
save_template_from([st], "card")
|
||||
var sg := _arg_value(args, "--save-group-template")
|
||||
if sg != "":
|
||||
save_template_from([], "group", [sg])
|
||||
for a in args:
|
||||
if a == "--templates" or a.begins_with("--templates="):
|
||||
var p := open_template_picker()
|
||||
if a.contains("="):
|
||||
p._search.text = a.get_slice("=", 1)
|
||||
p.refresh()
|
||||
var shown := p.shown_ids()
|
||||
if not shown.is_empty():
|
||||
p.select(str(shown[0]))
|
||||
if args.has("--group-selected") or sel != "" or ins != "":
|
||||
# Let new cards and frames lay out.
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
|
||||
|
||||
func _apply_view_flag(args: PackedStringArray) -> void:
|
||||
var v := _arg_value(args, "--view")
|
||||
if v == "":
|
||||
return
|
||||
var parts := v.split(",")
|
||||
if parts.size() >= 3:
|
||||
board.set_zoom(parts[2].to_float())
|
||||
var p := Vector2(parts[0].to_float(), parts[1].to_float())
|
||||
board.world.position = board.size / 2.0 - p * board.zoom
|
||||
|
||||
|
||||
# ---------- Local state: decks, persistent variables, history ----------
|
||||
# Everything here is keyed by the current collection id (data.id). With saving
|
||||
# disabled (--sample / --screenshot) `state` is null and it all stays in memory.
|
||||
|
|
@ -1598,6 +2330,10 @@ func _load_board_file(path: String) -> void:
|
|||
|
||||
|
||||
func _run_cli_extras(args: PackedStringArray) -> void:
|
||||
if args.has("--clear-result"):
|
||||
# Keeps the board lit but empties the tray (a tall sheet result can fill it).
|
||||
current = {}
|
||||
tray.render()
|
||||
if _arg_value(args, "--tray") == "variables":
|
||||
tray.set_side(ResultTray.Side.VARIABLES)
|
||||
var edit := _arg_value(args, "--edit-details")
|
||||
|
|
|
|||
|
|
@ -5,6 +5,11 @@ extends Control
|
|||
##
|
||||
## [[References]] in an entry's text draw as thinner dashed pipes. They come from
|
||||
## the text, so they can't be clicked or removed here.
|
||||
##
|
||||
## Pipes to or from tables hidden in a collapsed group attach to that group's
|
||||
## card instead (GroupCard.inlet_point / anchor_for). They keep their keys, so
|
||||
## they still light up and carry the bead; pipes inside one collapsed group
|
||||
## aren't drawn.
|
||||
|
||||
const SAMPLES := 40
|
||||
|
||||
|
|
@ -17,6 +22,11 @@ var pulse_t: float = 0.0
|
|||
|
||||
## pipe key -> polyline in world coordinates, from the last frame.
|
||||
var _paths: Dictionary = {}
|
||||
## Keys of pipes drawn to or from a collapsed group card (not clickable: many
|
||||
## share one line).
|
||||
var _rerouted: Dictionary = {}
|
||||
## Vector2i -> lit: where pipes leave collapsed group cards, for PortLayer.
|
||||
var group_ports: Dictionary = {}
|
||||
var _label_box: StyleBoxFlat
|
||||
|
||||
|
||||
|
|
@ -44,46 +54,70 @@ static func curve(a: Vector2, b: Vector2) -> PackedVector2Array:
|
|||
|
||||
func _draw() -> void:
|
||||
_paths.clear()
|
||||
_rerouted.clear()
|
||||
group_ports.clear()
|
||||
var lit_list: Array = []
|
||||
var lit_refs: Array = []
|
||||
var labels: Array = []
|
||||
var drawn := {} # endpoints of rerouted pipes already drawn (they overlap)
|
||||
var build := main.mode == Main.Mode.BUILD
|
||||
# Tables hidden in a collapsed group -> that group's card. Their pipes leave
|
||||
# from the group card's right edge and arrive at its inlet.
|
||||
var hidden := main.hidden_groups()
|
||||
for t in main.data.tables:
|
||||
var card := main.card_for(t.id)
|
||||
if card == null:
|
||||
continue
|
||||
var src_g: GroupCard = hidden.get(t.id)
|
||||
for e in t.entries:
|
||||
var refs := main.ref_targets_for(e)
|
||||
if e.pipes.is_empty() and refs.is_empty():
|
||||
continue
|
||||
var a := card.anchor_for(e.id)
|
||||
var a: Dictionary
|
||||
if src_g:
|
||||
a = {"pos": src_g.anchor_for(t.id, e.id), "visible": true}
|
||||
else:
|
||||
a = card.anchor_for(e.id)
|
||||
if a.is_empty():
|
||||
continue
|
||||
for to in refs:
|
||||
for i in refs.size() + e.pipes.size():
|
||||
var is_ref := i < refs.size()
|
||||
var to: String = refs[i] if is_ref else e.pipes[i - refs.size()]
|
||||
var target := main.card_for(to)
|
||||
if target == null:
|
||||
continue
|
||||
var key := Roller.ref_key(t.id, e.id, to)
|
||||
var pts := curve(a["pos"], target.inlet_point())
|
||||
var dst_g: GroupCard = hidden.get(to)
|
||||
if src_g != null and dst_g == src_g:
|
||||
continue # inside one collapsed group
|
||||
var key := Roller.ref_key(t.id, e.id, to) if is_ref else Roller.pipe_key(t.id, e.id, to)
|
||||
var end: Vector2 = dst_g.inlet_point() if dst_g else target.inlet_point()
|
||||
var pts := curve(a["pos"], end)
|
||||
_paths[key] = pts
|
||||
if main.lit_pipes.has(key):
|
||||
lit_refs.append(pts)
|
||||
else:
|
||||
var lit := main.lit_pipes.has(key)
|
||||
var rerouted := src_g != null or dst_g != null
|
||||
if rerouted:
|
||||
_rerouted[key] = true
|
||||
if src_g:
|
||||
var pk := Vector2i(a["pos"])
|
||||
group_ports[pk] = bool(group_ports.get(pk, false)) or main.is_entry_lit(t.id, e.id)
|
||||
if lit:
|
||||
(lit_refs if is_ref else lit_list).append(pts)
|
||||
continue
|
||||
if rerouted:
|
||||
var dk := "%s|%s|%s" % [Vector2i(a["pos"]), Vector2i(end), is_ref]
|
||||
if drawn.has(dk):
|
||||
continue
|
||||
drawn[dk] = true
|
||||
if is_ref:
|
||||
_draw_ref(pts, false)
|
||||
for to in e.pipes:
|
||||
var target := main.card_for(to)
|
||||
if target == null:
|
||||
continue
|
||||
var key := Roller.pipe_key(t.id, e.id, to)
|
||||
var pts := curve(a["pos"], target.inlet_point())
|
||||
_paths[key] = pts
|
||||
if main.lit_pipes.has(key):
|
||||
lit_list.append(pts)
|
||||
elif rerouted:
|
||||
_draw_bundle(pts)
|
||||
else:
|
||||
_draw_pipe(pts, false, build and (key == hover_key or key == select_key))
|
||||
var tag := _pipe_tag(e, to)
|
||||
if tag != "":
|
||||
labels.append([pts, tag])
|
||||
if not is_ref and not rerouted:
|
||||
var tag := _pipe_tag(e, to)
|
||||
if tag != "":
|
||||
labels.append([pts, tag])
|
||||
# Lit pipes go on top so the path of the last roll reads clearly.
|
||||
for pts in lit_refs:
|
||||
_draw_ref(pts, true)
|
||||
|
|
@ -135,6 +169,13 @@ func _draw_pipe(pts: PackedVector2Array, lit: bool, hovered: bool) -> void:
|
|||
draw_set_transform(Vector2.ZERO)
|
||||
|
||||
|
||||
## An unlit pipe to or from a collapsed group: thinner and quieter, so the
|
||||
## lit path of the last roll stands out on a big board.
|
||||
func _draw_bundle(pts: PackedVector2Array) -> void:
|
||||
draw_polyline(pts, Color(Style.COPPER_DARK, 0.55), 6.0, true)
|
||||
draw_polyline(pts, Color(Style.COPPER, 0.6), 3.0, true)
|
||||
|
||||
|
||||
## A reference pipe: thinner, in dashes.
|
||||
func _draw_ref(pts: PackedVector2Array, lit: bool) -> void:
|
||||
if lit:
|
||||
|
|
@ -207,7 +248,7 @@ static func point_along(pts: PackedVector2Array, t: float) -> Vector2:
|
|||
## Reference pipes come from entry text, so they're never picked.
|
||||
func pipe_at(p: Vector2, tolerance: float) -> String:
|
||||
for key: String in _paths:
|
||||
if Roller.is_ref_key(key):
|
||||
if Roller.is_ref_key(key) or _rerouted.has(key):
|
||||
continue
|
||||
var pts: PackedVector2Array = _paths[key]
|
||||
for i in range(1, pts.size()):
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ func setup(p_main: Main) -> void:
|
|||
_save.add_theme_stylebox_override("normal", field_ok)
|
||||
_save.add_theme_stylebox_override("focus", field_focus)
|
||||
_save.text_changed.connect(func(s: String) -> void:
|
||||
var ok := s.strip_edges() == "" or _re.search(s.strip_edges()) != null
|
||||
var ok := s.strip_edges() == "" or _re.search(TemplateKit.probe(s.strip_edges())) != null
|
||||
_save.add_theme_stylebox_override("normal", _save_ok if ok else _save_bad)
|
||||
_save.add_theme_stylebox_override("focus", field_focus if ok else _save_bad)
|
||||
)
|
||||
|
|
@ -175,7 +175,7 @@ static func _count_error(text: String) -> String:
|
|||
var s := text.strip_edges()
|
||||
if s == "" or s.is_valid_int():
|
||||
return ""
|
||||
var err := Expr.check(s)
|
||||
var err := Expr.check(TemplateKit.probe(s))
|
||||
return "" if err == "" else "Not a number or expression: " + err
|
||||
|
||||
|
||||
|
|
@ -183,7 +183,7 @@ func _commit_save() -> void:
|
|||
if _entry == null:
|
||||
return
|
||||
var s := _save.text.strip_edges()
|
||||
if s != "" and _re.search(s) == null:
|
||||
if s != "" and _re.search(TemplateKit.probe(s)) == null:
|
||||
return
|
||||
if s != _entry.save_for(_to):
|
||||
_entry.set_pipe_save(_to, s)
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ func _draw() -> void:
|
|||
var mouse := get_local_mouse_position()
|
||||
for t in main.data.tables:
|
||||
var card := main.card_for(t.id)
|
||||
if card == null or not card.is_inside_tree():
|
||||
if card == null or not card.is_inside_tree() or not card.visible:
|
||||
continue
|
||||
# Variable cards are never rolled, so nothing pipes into them.
|
||||
if t.kind != RollTable.KIND_VARIABLE:
|
||||
|
|
@ -73,6 +73,18 @@ func _draw() -> void:
|
|||
var on_hidden := card.hidden_has_pipes()
|
||||
if not m.is_empty() and (on_hidden or build):
|
||||
_port(m["pos"], Style.COPPER if on_hidden else Style.CARD, Style.COPPER_DARK, 1.0)
|
||||
# Collapsed groups: an inlet, and an outlet wherever member pipes leave.
|
||||
for g in main.data.groups:
|
||||
if g.collapsed:
|
||||
var gn := main.group_node(g.id)
|
||||
if gn and gn.is_inside_tree():
|
||||
_port(gn.inlet_point(), Style.COPPER, Style.COPPER_DARK, 1.0)
|
||||
var gp: Dictionary = main.board.pipes.group_ports
|
||||
for p: Vector2i in gp:
|
||||
if gp[p]:
|
||||
_port(Vector2(p), Style.BRASS, Style.BRASS_DARK, 1.0)
|
||||
else:
|
||||
_port(Vector2(p), Style.COPPER, Style.COPPER_DARK, 1.0)
|
||||
if _linking:
|
||||
_draw_ghost(PipeLayer.curve(_ghost_from, _ghost_to))
|
||||
|
||||
|
|
|
|||
|
|
@ -43,6 +43,8 @@ var _style_normal: StyleBoxFlat
|
|||
var _style_rolling: StyleBoxFlat
|
||||
var _style_dragging: StyleBoxFlat
|
||||
var _style_drop: StyleBoxFlat
|
||||
var _style_selected: StyleBoxFlat
|
||||
var _selected := false
|
||||
var _deck_row: Control
|
||||
var _deck_label: Label
|
||||
## Entry ids whose details editor is open (Build mode).
|
||||
|
|
@ -80,6 +82,12 @@ func setup(p_main: Main, p_table: RollTable) -> void:
|
|||
_style_drop.shadow_color = Color(0, 0, 0, 0.32)
|
||||
_style_drop.shadow_size = 16
|
||||
_style_drop.shadow_offset = Vector2(0, 8)
|
||||
_style_selected = _style_normal.duplicate() as StyleBoxFlat
|
||||
Style.bordered(_style_selected, 3, Style.COPPER)
|
||||
_style_selected.set_expand_margin_all(4)
|
||||
_style_selected.shadow_color = Color(Style.COPPER, 0.5)
|
||||
_style_selected.shadow_size = 14
|
||||
_style_selected.shadow_offset = Vector2.ZERO
|
||||
_style_dragging = _style_normal.duplicate() as StyleBoxFlat
|
||||
_style_dragging.shadow_color = Color(0, 0, 0, 0.4)
|
||||
_style_dragging.shadow_size = 26
|
||||
|
|
@ -538,7 +546,7 @@ func _make_row(e: TableEntry, index: int, build: bool, ranged: bool, numw: float
|
|||
if not ranged and not fixed:
|
||||
h.add_child(_weight_edit(e))
|
||||
h.add_child(_toggle_button("ƒ", "Effects: statements such as @hp -= 1 that run when this comes up",
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty()))
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
|
||||
h.add_child(_toggle_button("i", "Details shown when hovering this result",
|
||||
_open_details, e.id, e.details.strip_edges() != "", false))
|
||||
if not fixed:
|
||||
|
|
@ -632,7 +640,7 @@ func _row_text(e: TableEntry) -> String:
|
|||
|
||||
## Play mode: a subtle brass chip summarising an entry's effects ("STR = 2d6").
|
||||
func _effects_chip(e: TableEntry) -> Control:
|
||||
var bad := not Effects.validate(e.effects).is_empty()
|
||||
var bad := not Effects.validate(TemplateKit.probe(e.effects)).is_empty()
|
||||
var chip := PanelContainer.new()
|
||||
chip.mouse_filter = MOUSE_FILTER_PASS
|
||||
chip.size_flags_horizontal = SIZE_SHRINK_BEGIN
|
||||
|
|
@ -706,7 +714,7 @@ func _effects_editor(e: TableEntry, left: float) -> Control:
|
|||
msg.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
v.add_child(msg)
|
||||
var check := func() -> void:
|
||||
var problems := Effects.validate(te.text)
|
||||
var problems := Effects.validate(TemplateKit.probe(te.text))
|
||||
var lines := PackedStringArray()
|
||||
for p: Dictionary in problems:
|
||||
lines.append("⚠ %s: %s" % [p["src"], p["error"]])
|
||||
|
|
@ -753,7 +761,7 @@ func _make_sheet_row(e: TableEntry, build: bool) -> Control:
|
|||
v.add_child(te)
|
||||
var tools := _hbox(4)
|
||||
tools.add_child(_toggle_button("ƒ", "Effects that run when the chain reaches this sheet",
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(e.effects).is_empty()))
|
||||
_open_effects, e.id, e.effects.strip_edges() != "", not Effects.validate(TemplateKit.probe(e.effects)).is_empty()))
|
||||
tools.add_child(_toggle_button("i", "Details shown when hovering the sheet",
|
||||
_open_details, e.id, e.details.strip_edges() != "", false))
|
||||
var pv := Style.make_label("Preview on the board in Play", Style.body_italic(true), 12, Style.MUTED)
|
||||
|
|
@ -1075,11 +1083,24 @@ func _apply_style() -> void:
|
|||
s = _style_drop
|
||||
elif _rolling:
|
||||
s = _style_rolling
|
||||
elif _selected:
|
||||
s = _style_selected
|
||||
elif _dragging:
|
||||
s = _style_dragging
|
||||
add_theme_stylebox_override("panel", s)
|
||||
|
||||
|
||||
## Build-mode selection (Main.selection): a copper ring around the card.
|
||||
func set_selected(on: bool) -> void:
|
||||
if _selected != on:
|
||||
_selected = on
|
||||
_apply_style()
|
||||
|
||||
|
||||
func is_selected() -> bool:
|
||||
return _selected
|
||||
|
||||
|
||||
func _shrink() -> void:
|
||||
size = Vector2(card_width(), 0)
|
||||
|
||||
|
|
@ -1188,16 +1209,29 @@ func _gui_input(ev: InputEvent) -> void:
|
|||
accept_event()
|
||||
|
||||
|
||||
## Dragging the header moves the card (and, in Build, every selected card).
|
||||
## In Build, Ctrl- or Shift-click adds the card to the selection or takes it
|
||||
## out; dropping a card into a group frame adds it to that group (Main).
|
||||
func _on_header_input(ev: InputEvent, header: Control) -> void:
|
||||
var mb := ev as InputEventMouseButton
|
||||
if mb and mb.button_index == MOUSE_BUTTON_LEFT:
|
||||
if mb.pressed:
|
||||
main.details().hide_for()
|
||||
var build := main.mode == Main.Mode.BUILD
|
||||
if build and (mb.ctrl_pressed or mb.shift_pressed or mb.meta_pressed):
|
||||
main.toggle_selected(table.id)
|
||||
header.accept_event()
|
||||
return
|
||||
if build and not main.is_selected(table.id):
|
||||
main.clear_selection()
|
||||
_dragging = true
|
||||
_drag_offset = main.board.world_mouse() - position
|
||||
get_parent().move_child(self, -1)
|
||||
else:
|
||||
main.begin_card_drag(self)
|
||||
elif _dragging:
|
||||
_dragging = false
|
||||
main.end_card_drag(self)
|
||||
else:
|
||||
main.mark_dirty()
|
||||
_apply_style()
|
||||
header.accept_event()
|
||||
|
|
@ -1205,6 +1239,5 @@ func _on_header_input(ev: InputEvent, header: Control) -> void:
|
|||
var mm := ev as InputEventMouseMotion
|
||||
if mm and _dragging:
|
||||
var p := main.board.world_mouse() - _drag_offset
|
||||
position = Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y)))
|
||||
table.position = position
|
||||
main.drag_card(self, Vector2(maxf(10.0, roundf(p.x)), maxf(10.0, roundf(p.y))))
|
||||
header.accept_event()
|
||||
|
|
|
|||
|
|
@ -5,6 +5,8 @@ extends ModalCard
|
|||
## they can be tested without a window.
|
||||
|
||||
signal applied(settings: Dictionary)
|
||||
## The footer's "Save as template…" (the dialog closes first; Main opens the save dialog).
|
||||
signal template_requested
|
||||
|
||||
const COLORS := [
|
||||
["Red", Color("#a33a2c")],
|
||||
|
|
@ -177,6 +179,14 @@ func _build() -> void:
|
|||
body.add_child(card_box)
|
||||
_card_box = card_box
|
||||
|
||||
var tpl := add_button("Save as template…", "plain", func() -> void:
|
||||
close()
|
||||
template_requested.emit()
|
||||
)
|
||||
tpl.tooltip_text = "Save this card as a reusable template ({$name} in any text becomes a parameter)"
|
||||
var gap := Control.new()
|
||||
gap.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
footer.add_child(gap)
|
||||
add_button("Close", "plain", close)
|
||||
add_button("Apply", "primary", _on_apply)
|
||||
_refresh()
|
||||
|
|
@ -360,6 +370,7 @@ func _build_kind() -> void:
|
|||
pbox.add_child(_template_preview)
|
||||
box.add_child(pbox)
|
||||
_:
|
||||
box.free() # roll tables have no kind fields
|
||||
return
|
||||
_kind_problem = note("", Style.DANGER_INK)
|
||||
box.add_child(_kind_problem)
|
||||
|
|
@ -385,14 +396,14 @@ func _refresh_kind() -> void:
|
|||
else:
|
||||
msg = "The answer goes in {answer}; the Answer row's effects and pipes run after it."
|
||||
_choice_note.text = msg
|
||||
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(s["save_as"]) != null)
|
||||
_mark(_min, Expr.check(s["min"]) == "" and s["min"] != "")
|
||||
_mark(_max, Expr.check(s["max"]) == "" and s["max"] != "")
|
||||
_mark(_save_as, s["save_as"] == "" or _re(SAVE_PATTERN).search(TemplateKit.probe(s["save_as"])) != null)
|
||||
_mark(_min, Expr.check(TemplateKit.probe(s["min"])) == "" and s["min"] != "")
|
||||
_mark(_max, Expr.check(TemplateKit.probe(s["max"])) == "" and s["max"] != "")
|
||||
RollTable.KIND_LOOP:
|
||||
_loop_note.text = LOOP_NOTES.get(_loop_mode, "")
|
||||
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(s["loop_expr"]) == "")
|
||||
_mark(_loop_expr, s["loop_expr"] != "" and Expr.check(TemplateKit.probe(s["loop_expr"])) == "")
|
||||
RollTable.KIND_VARIABLE:
|
||||
_mark(_var_name, _re(VAR_PATTERN).search(s["var_name"]) != null)
|
||||
_mark(_var_name, _re(VAR_PATTERN).search(TemplateKit.probe(s["var_name"])) != null)
|
||||
_mark(_initial, _initial_error(s["initial"], _var_type) == "")
|
||||
RollTable.KIND_SHEET:
|
||||
var ctx := Roller.live_context(table_board(), _live_vars())
|
||||
|
|
@ -473,23 +484,24 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
|||
var out := PackedStringArray()
|
||||
match t.kind:
|
||||
RollTable.KIND_CHOICE:
|
||||
var save := str(s.get("save_as", t.save_as)).strip_edges()
|
||||
# Template placeholders ({$name}) check as a plain name (TemplateKit.probe).
|
||||
var save := TemplateKit.probe(str(s.get("save_as", t.save_as)).strip_edges())
|
||||
if save != "" and _re(SAVE_PATTERN).search(save) == null:
|
||||
out.append("Save as: use a name like career, or @career to keep it.")
|
||||
if str(s.get("choice", t.choice)) == "number":
|
||||
for k in [["min", "Lowest"], ["max", "Highest"]]:
|
||||
var src := str(s.get(k[0], "")).strip_edges()
|
||||
var src := TemplateKit.probe(str(s.get(k[0], "")).strip_edges())
|
||||
var err := Expr.check(src) if src != "" else "it's empty"
|
||||
if err != "":
|
||||
out.append("%s: %s" % [k[1], err])
|
||||
RollTable.KIND_LOOP:
|
||||
var src := str(s.get("loop_expr", t.loop_expr)).strip_edges()
|
||||
var src := TemplateKit.probe(str(s.get("loop_expr", t.loop_expr)).strip_edges())
|
||||
if src == "":
|
||||
out.append("The loop needs a count or a condition.")
|
||||
elif Expr.check(src) != "":
|
||||
out.append("Loop rule: " + Expr.check(src))
|
||||
RollTable.KIND_VARIABLE:
|
||||
var n := str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@")
|
||||
var n := TemplateKit.probe(str(s.get("var_name", t.var_name)).strip_edges().trim_prefix("@"))
|
||||
if _re(VAR_PATTERN).search(n) == null:
|
||||
out.append("Variable name: lowercase letters, digits and _ only.")
|
||||
var err := _initial_error(str(s.get("initial", t.initial)), str(s.get("var_type", t.var_type)))
|
||||
|
|
@ -499,7 +511,7 @@ static func kind_problems(t: RollTable, s: Dictionary) -> PackedStringArray:
|
|||
|
||||
|
||||
static func _initial_error(src: String, type: String) -> String:
|
||||
src = src.strip_edges()
|
||||
src = TemplateKit.probe(src.strip_edges())
|
||||
if src == "":
|
||||
return ""
|
||||
if type != "number" and RollTable._looks_literal(src):
|
||||
|
|
@ -515,7 +527,7 @@ static func _re(pattern: String) -> RegEx:
|
|||
## variable, dice or a function ("2d6 + dm(@end)", "@terms"). A lone word
|
||||
## such as "banana" is not accepted.
|
||||
static func dice_ok_text(text: String) -> bool:
|
||||
var s := text.strip_edges()
|
||||
var s := TemplateKit.probe(text.strip_edges())
|
||||
if Dice.is_valid_text(s):
|
||||
return true
|
||||
if s == "" or Expr.check(s) != "":
|
||||
|
|
|
|||
157
ui/template_forms.gd
Normal file
157
ui/template_forms.gd
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
class_name TemplateForms
|
||||
extends RefCounted
|
||||
## Card-styled dialogs for templates: saving one (name, description and the
|
||||
## detected {$parameters}), filling in parameters before an insert, and the
|
||||
## small board preview the template list shows.
|
||||
|
||||
|
||||
## The "Save as template" dialog. `on_save` gets the template with the name,
|
||||
## description and parameter labels and defaults the user typed.
|
||||
static func save_dialog(tpl: Dictionary, on_save: Callable) -> ModalCard:
|
||||
var d := ModalCard.new("Save as template", 580.0)
|
||||
var top := HBoxContainer.new()
|
||||
top.add_theme_constant_override("separation", 16)
|
||||
var pv := preview(tpl, Vector2(150, 92))
|
||||
pv.size_flags_vertical = Control.SIZE_SHRINK_BEGIN
|
||||
top.add_child(pv)
|
||||
var fields := VBoxContainer.new()
|
||||
fields.add_theme_constant_override("separation", 10)
|
||||
fields.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||||
top.add_child(fields)
|
||||
var name_edit := LineEdit.new()
|
||||
name_edit.text = str(tpl.get("name", ""))
|
||||
ModalCard.style_line_edit(name_edit)
|
||||
fields.add_child(ModalCard.field("Name", name_edit))
|
||||
fields.add_child(ModalCard.note(TemplateKit.summary(tpl)))
|
||||
d.body.add_child(top)
|
||||
|
||||
var desc := TextEdit.new()
|
||||
desc.text = str(tpl.get("description", ""))
|
||||
desc.placeholder_text = "What it's for, and what to fill in (shown in the template list)"
|
||||
desc.wrap_mode = TextEdit.LINE_WRAPPING_BOUNDARY
|
||||
desc.custom_minimum_size = Vector2(0, 64)
|
||||
desc.scroll_fit_content_height = true
|
||||
ModalCard.style_text_edit(desc)
|
||||
d.body.add_child(ModalCard.field("Description", desc))
|
||||
|
||||
var outside := 0
|
||||
for t: Dictionary in tpl.get("tables", []):
|
||||
for e: Dictionary in t.get("entries", []):
|
||||
for p: Variant in e.get("pipes", []):
|
||||
if p is Dictionary and bool((p as Dictionary).get("outside", false)):
|
||||
outside += 1
|
||||
if outside > 0:
|
||||
d.body.add_child(ModalCard.note("%d %s to cards outside the template. When it's inserted they relink to a card with the same name, if there is one." % [outside, "pipe leads" if outside == 1 else "pipes lead"]))
|
||||
|
||||
d.body.add_child(ModalCard.section("Parameters"))
|
||||
var rows: Array = []
|
||||
var params: Array = tpl.get("params", [])
|
||||
if params.is_empty():
|
||||
d.body.add_child(ModalCard.note("None found. Write {$name} in any text (card names, results, effects, expressions, prompts, variable names) and it becomes a parameter you fill in when inserting."))
|
||||
else:
|
||||
d.body.add_child(ModalCard.note("Found in the cards' text. Give each a label and a default for the insert form."))
|
||||
for p: Dictionary in params:
|
||||
var row := HBoxContainer.new()
|
||||
row.add_theme_constant_override("separation", 8)
|
||||
var chip := PanelContainer.new()
|
||||
chip.add_theme_stylebox_override("panel", Style.bordered(Style.box(Color(Style.BRASS, 0.18), 6, [8, 4, 8, 4]), 1, Color(Style.BRASS_DARK, 0.4)))
|
||||
chip.custom_minimum_size = Vector2(120, 0)
|
||||
chip.size_flags_vertical = Control.SIZE_SHRINK_CENTER
|
||||
chip.add_child(Style.make_label("{$%s}" % p["name"], Style.body_bold(), 14, Style.COPPER_DARK))
|
||||
row.add_child(chip)
|
||||
var label := LineEdit.new()
|
||||
label.text = str(p.get("label", ""))
|
||||
label.placeholder_text = "Label"
|
||||
ModalCard.style_line_edit(label)
|
||||
row.add_child(label)
|
||||
var def := LineEdit.new()
|
||||
def.text = str(p.get("default", ""))
|
||||
def.placeholder_text = "Default"
|
||||
ModalCard.style_line_edit(def)
|
||||
row.add_child(def)
|
||||
d.body.add_child(row)
|
||||
rows.append([p, label, def])
|
||||
d.add_button("Cancel", "plain", d.close)
|
||||
d.add_button("Save template", "primary", func() -> void:
|
||||
var out := tpl.duplicate(true)
|
||||
out["name"] = name_edit.text.strip_edges() if name_edit.text.strip_edges() != "" else "Untitled template"
|
||||
out["description"] = desc.text.strip_edges()
|
||||
var plist: Array = []
|
||||
for r: Array in rows:
|
||||
var p: Dictionary = r[0]
|
||||
plist.append({"name": p["name"], "label": (r[1] as LineEdit).text.strip_edges(), "default": (r[2] as LineEdit).text})
|
||||
out["params"] = plist
|
||||
d.close()
|
||||
on_save.call(out)
|
||||
)
|
||||
d.ready.connect(func() -> void:
|
||||
name_edit.grab_focus()
|
||||
name_edit.select_all()
|
||||
)
|
||||
return d
|
||||
|
||||
|
||||
## Asks for the template's parameter values; `on_ok` gets {name: value}.
|
||||
static func params_dialog(tpl: Dictionary, on_ok: Callable) -> ModalCard:
|
||||
var d := ModalCard.new("Insert “%s”" % str(tpl.get("name", "template")), 480.0)
|
||||
if str(tpl.get("description", "")) != "":
|
||||
d.body.add_child(ModalCard.note(str(tpl["description"])))
|
||||
var edits: Array = []
|
||||
for p: Dictionary in tpl.get("params", []):
|
||||
var le := LineEdit.new()
|
||||
le.text = str(p.get("default", ""))
|
||||
le.placeholder_text = "{$%s}" % p["name"]
|
||||
ModalCard.style_line_edit(le)
|
||||
var label := str(p.get("label", ""))
|
||||
d.body.add_child(ModalCard.field(label if label != "" else str(p["name"]).capitalize(), le))
|
||||
edits.append([str(p["name"]), le])
|
||||
var accept := func() -> void:
|
||||
var values := {}
|
||||
for pair: Array in edits:
|
||||
values[pair[0]] = (pair[1] as LineEdit).text
|
||||
d.close()
|
||||
on_ok.call(values)
|
||||
for pair: Array in edits:
|
||||
(pair[1] as LineEdit).text_submitted.connect(func(_t: String) -> void: accept.call())
|
||||
d.add_button("Cancel", "plain", d.close)
|
||||
d.add_button("Insert", "primary", accept)
|
||||
d.ready.connect(func() -> void:
|
||||
if not edits.is_empty():
|
||||
(edits[0][1] as LineEdit).grab_focus()
|
||||
(edits[0][1] as LineEdit).select_all()
|
||||
)
|
||||
return d
|
||||
|
||||
|
||||
## A small picture of the template's layout: group frames on a felt tile and
|
||||
## each card as a little paper rectangle (choice cards brass, loops copper,
|
||||
## variables and sheets outlined).
|
||||
static func preview(tpl: Dictionary, box: Vector2 = Vector2(120, 74)) -> Control:
|
||||
var c := Control.new()
|
||||
c.custom_minimum_size = box
|
||||
c.mouse_filter = Control.MOUSE_FILTER_IGNORE
|
||||
c.draw.connect(func() -> void:
|
||||
c.draw_style_box(Style.box(Style.FELT, 8), Rect2(Vector2.ZERO, box))
|
||||
var ext := TemplateKit.extent(tpl)
|
||||
if ext.x <= 0.0 or ext.y <= 0.0:
|
||||
return
|
||||
var inner := box - Vector2(16, 16)
|
||||
var s := minf(inner.x / ext.x, inner.y / ext.y)
|
||||
var off := Vector2(8, 8) + (inner - ext * s) / 2.0
|
||||
for g: Dictionary in tpl.get("groups", []):
|
||||
var gr := Rect2(off + Vector2(float(g.get("x", 0)), float(g.get("y", 0))) * s,
|
||||
Vector2(float(g.get("w", 0)), float(g.get("h", 0))) * s)
|
||||
c.draw_style_box(Style.box(Color(0, 0, 0, 0.22), 4), gr)
|
||||
for t: Dictionary in tpl.get("tables", []):
|
||||
var r := Rect2(off + Vector2(float(t.get("x", 0)), float(t.get("y", 0))) * s, TemplateKit.CARD_SIZE * s * Vector2(1.0, 0.8))
|
||||
var kind := str(t.get("kind", "roll"))
|
||||
var fill := Style.CARD
|
||||
if kind == "choice":
|
||||
fill = Style.LIT
|
||||
c.draw_style_box(Style.box(fill, 3), r)
|
||||
var band := Color(Style.COPPER, 0.9) if kind == "loop" else (Style.FELT_HOVER if kind == "variable" else Style.RULE)
|
||||
if kind == "sheet":
|
||||
band = Style.BRASS_DARK
|
||||
c.draw_rect(Rect2(r.position + Vector2(0, 2), Vector2(r.size.x, maxf(2.0, r.size.y * 0.16))), band)
|
||||
)
|
||||
return c
|
||||
1
ui/template_forms.gd.uid
Normal file
1
ui/template_forms.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bra3jl7h3hod7
|
||||
196
ui/template_picker.gd
Normal file
196
ui/template_picker.gd
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
class_name TemplatePicker
|
||||
extends ModalCard
|
||||
## "+ Table ▾ → From template…": the template list with search, each row
|
||||
## showing its name, description and a small preview. The user's own
|
||||
## templates can be renamed, exported and deleted here; built-in ones are
|
||||
## read-only. Import… adds a template file. Insert asks for parameters (if
|
||||
## any) and drops the template at the view centre (Main.insert_template).
|
||||
|
||||
var main: Main
|
||||
var lib: TemplateLibrary
|
||||
var _search: LineEdit
|
||||
var _list: VBoxContainer
|
||||
var _insert: Button
|
||||
var _selected := ""
|
||||
var _rows: Dictionary = {} # id -> row PanelContainer
|
||||
|
||||
|
||||
func _init(p_main: Main, p_lib: TemplateLibrary) -> void:
|
||||
super._init("Insert a template", 640.0)
|
||||
main = p_main
|
||||
lib = p_lib
|
||||
_search = LineEdit.new()
|
||||
_search.placeholder_text = "Search templates"
|
||||
_search.clear_button_enabled = true
|
||||
ModalCard.style_line_edit(_search)
|
||||
_search.text_changed.connect(func(_s: String) -> void: refresh())
|
||||
_search.text_submitted.connect(func(_s: String) -> void:
|
||||
if _selected != "":
|
||||
_choose(_selected)
|
||||
)
|
||||
body.add_child(_search)
|
||||
_list = VBoxContainer.new()
|
||||
_list.add_theme_constant_override("separation", 8)
|
||||
body.add_child(_list)
|
||||
var imp := add_button("Import…", "plain", func() -> void: main.import_template_file(self))
|
||||
imp.tooltip_text = "Add a template file (.json) to your templates"
|
||||
var gap := Control.new()
|
||||
gap.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
footer.add_child(gap)
|
||||
add_button("Cancel", "plain", close)
|
||||
_insert = add_button("Insert", "primary", func() -> void:
|
||||
if _selected != "":
|
||||
_choose(_selected)
|
||||
)
|
||||
_insert.disabled = true
|
||||
refresh()
|
||||
ready.connect(func() -> void: _search.grab_focus())
|
||||
|
||||
|
||||
## Rebuilds the list from the library, filtered by the search text.
|
||||
func refresh() -> void:
|
||||
for c in _list.get_children():
|
||||
_list.remove_child(c)
|
||||
c.queue_free()
|
||||
_rows.clear()
|
||||
var q := _search.text.strip_edges().to_lower()
|
||||
var any := false
|
||||
for r: Dictionary in lib.list():
|
||||
var tpl: Dictionary = r["template"]
|
||||
var hay := ("%s %s %s" % [r["name"], r["description"], TemplateKit.summary(tpl)]).to_lower()
|
||||
if q != "" and not hay.contains(q):
|
||||
continue
|
||||
any = true
|
||||
_list.add_child(_row(r))
|
||||
if not any:
|
||||
_list.add_child(ModalCard.note("No templates match." if q != "" else "No templates yet. Save one from a card's ⚙, a group's ⋯ menu or a selection."))
|
||||
if not _rows.has(_selected):
|
||||
_selected = ""
|
||||
_insert.disabled = _selected == ""
|
||||
_paint()
|
||||
if is_inside_tree():
|
||||
_fit()
|
||||
|
||||
|
||||
## Ids of the rows shown, in order (tests use it).
|
||||
func shown_ids() -> Array:
|
||||
return _rows.keys()
|
||||
|
||||
|
||||
func select(id: String) -> void:
|
||||
if _rows.has(id):
|
||||
_selected = id
|
||||
_insert.disabled = false
|
||||
_paint()
|
||||
|
||||
|
||||
func _paint() -> void:
|
||||
for id: String in _rows:
|
||||
var on := id == _selected
|
||||
var sb := Style.bordered(Style.box(Style.LIT if on else Color("#f7f3e8"), 10, [12, 10, 12, 10]), 1, Style.COPPER if on else Style.DASH)
|
||||
(_rows[id] as PanelContainer).add_theme_stylebox_override("panel", sb)
|
||||
|
||||
|
||||
func _row(r: Dictionary) -> Control:
|
||||
var id: String = r["id"]
|
||||
var tpl: Dictionary = r["template"]
|
||||
var row := PanelContainer.new()
|
||||
row.mouse_filter = MOUSE_FILTER_STOP
|
||||
row.mouse_default_cursor_shape = CURSOR_POINTING_HAND
|
||||
row.gui_input.connect(func(ev: InputEvent) -> void:
|
||||
var mb := ev as InputEventMouseButton
|
||||
if mb and mb.button_index == MOUSE_BUTTON_LEFT and mb.pressed:
|
||||
select(id)
|
||||
if mb.double_click:
|
||||
_choose(id)
|
||||
)
|
||||
var h := HBoxContainer.new()
|
||||
h.add_theme_constant_override("separation", 14)
|
||||
h.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
row.add_child(h)
|
||||
var pv := TemplateForms.preview(tpl)
|
||||
pv.size_flags_vertical = SIZE_SHRINK_BEGIN
|
||||
h.add_child(pv)
|
||||
var v := VBoxContainer.new()
|
||||
v.add_theme_constant_override("separation", 3)
|
||||
v.size_flags_horizontal = SIZE_EXPAND_FILL
|
||||
v.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
h.add_child(v)
|
||||
var title_row := HBoxContainer.new()
|
||||
title_row.add_theme_constant_override("separation", 8)
|
||||
title_row.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
var title := Style.make_label(str(r["name"]), Style.display(), 20, Style.INK)
|
||||
title.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
title_row.add_child(title)
|
||||
title_row.add_child(_badge(str({"card": "Card", "group": "Group", "selection": "Cards"}.get(r["kind"], "Cards")), Style.FELT, Style.BRASS))
|
||||
if r["builtin"]:
|
||||
title_row.add_child(_badge("Built in", Color(0, 0, 0, 0.07), Style.MUTED))
|
||||
v.add_child(title_row)
|
||||
if str(r["description"]) != "":
|
||||
var desc := ModalCard.note(str(r["description"]), Style.INK)
|
||||
desc.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(desc)
|
||||
var info := TemplateKit.summary(tpl)
|
||||
var params: Array = tpl.get("params", [])
|
||||
if not params.is_empty():
|
||||
var names := PackedStringArray()
|
||||
for p: Dictionary in params:
|
||||
names.append(str(p.get("label", "")) if str(p.get("label", "")) != "" else str(p["name"]))
|
||||
info += " · asks for " + ", ".join(names)
|
||||
var sub := Style.make_label(info, Style.body(), 13, Style.MUTED)
|
||||
sub.autowrap_mode = TextServer.AUTOWRAP_WORD_SMART
|
||||
sub.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
v.add_child(sub)
|
||||
if not r["builtin"]:
|
||||
var tools := VBoxContainer.new()
|
||||
tools.add_theme_constant_override("separation", 2)
|
||||
tools.size_flags_vertical = SIZE_SHRINK_BEGIN
|
||||
for spec in [["Rename", func() -> void: _rename(id, str(r["name"]))],
|
||||
["Export", func() -> void: main.export_template(id)],
|
||||
["Delete", func() -> void: _delete(id, str(r["name"]))]]:
|
||||
var b := Button.new()
|
||||
b.text = spec[0]
|
||||
b.add_theme_font_override("font", Style.body())
|
||||
b.add_theme_font_size_override("font_size", 13)
|
||||
var n := Style.box(Color(0, 0, 0, 0), 5, [8, 2, 8, 2])
|
||||
var hv := Style.box(Style.HOVER_ROW, 5, [8, 2, 8, 2])
|
||||
Style.skin_button(b, n, hv, hv, Style.MUTED, Style.DANGER_INK if spec[0] == "Delete" else Style.INK)
|
||||
b.pressed.connect(spec[1])
|
||||
tools.add_child(b)
|
||||
h.add_child(tools)
|
||||
_rows[id] = row
|
||||
return row
|
||||
|
||||
|
||||
func _badge(text: String, bg: Color, fg: Color) -> Control:
|
||||
var p := PanelContainer.new()
|
||||
p.add_theme_stylebox_override("panel", Style.box(bg, 5, [6, 1, 6, 2]))
|
||||
p.size_flags_vertical = SIZE_SHRINK_CENTER
|
||||
p.mouse_filter = MOUSE_FILTER_IGNORE
|
||||
p.add_child(Style.make_label(text, Style.body_bold(), 11, fg))
|
||||
return p
|
||||
|
||||
|
||||
func _choose(id: String) -> void:
|
||||
var tpl := lib.get_template(id)
|
||||
if tpl.is_empty():
|
||||
main.toast("Couldn't read that template")
|
||||
return
|
||||
close()
|
||||
main.begin_template_insert(tpl)
|
||||
|
||||
|
||||
func _rename(id: String, old: String) -> void:
|
||||
main._add_modal(ModalCard.ask_text("Rename template", "Name", old, "Rename", func(n: String) -> void:
|
||||
if lib.rename(id, n):
|
||||
refresh()
|
||||
))
|
||||
|
||||
|
||||
func _delete(id: String, tname: String) -> void:
|
||||
main._add_modal(ModalCard.confirm("Delete template", "Delete the template “%s”? Cards already inserted from it stay on their boards." % tname,
|
||||
"Delete", func() -> void:
|
||||
if lib.delete(id):
|
||||
refresh()
|
||||
main.toast("Deleted template “%s”" % tname)
|
||||
, true))
|
||||
1
ui/template_picker.gd.uid
Normal file
1
ui/template_picker.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b4wyonp5ye8wt
|
||||
Loading…
Reference in a new issue