967 lines
50 KiB
Python
967 lines
50 KiB
Python
"""Summit's in-game overlay: the settings panel that opens over the picture (Insert by default; the launcher's
|
|
Settings page picks the key). Drawn as an image the GL window blits over the game (framegen/ui_draw.py draws it).
|
|
|
|
Rows come from settings.SPECS, so a new setting shows up here without changes to this file. Tabs along the top: Home
|
|
(the big choices that apply live, the performance overlay, and Restart / Save a clip / Quit), then one for each section
|
|
(Spec.group, as on the launcher's Settings page). Keys: Up and Down pick a row (Up from the first row goes to the
|
|
tabs, where Left and Right change tab), Left and Right change the value, Enter is the next value (or opens a row's
|
|
list, or does its action), Tab and Shift+Tab change tab, Esc or Backspace closes the overlay (or an open list). Esc
|
|
never closes the game or Summit's picture: Quit is a row on Home, and asks twice.
|
|
|
|
The mouse works as in any desktop program: the overlay is a window, moved by dragging its title bar (framegen/io.py
|
|
keeps where it was put). On/off settings are switches, a few short choices are buttons side by side, numbers that go
|
|
in order (the frame multiplier, qualities, sizes) are sliders to click or drag, and longer lists open a drop-down
|
|
list. The wheel scrolls the page (the highlighted row stays where it is), and the scrollbar can be dragged.
|
|
|
|
Drawing happens only when something on the overlay changes (the window caches the image), so an open overlay costs
|
|
nothing per frame.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from dataclasses import dataclass
|
|
from typing import Callable
|
|
|
|
import numpy as np
|
|
|
|
from . import ui_draw as U
|
|
from .settings import SPECS, Settings, Spec
|
|
|
|
VISIBLE = 11 # rows shown at once (headings count); longer tabs scroll
|
|
DROP_VISIBLE = 7 # choices shown at once in a drop-down list
|
|
HOME = "Home"
|
|
TAB_NAMES: dict[str, str] = {} # shorter names for the tab strip, if a section's is too long
|
|
|
|
PERF = "perf" # Home's "Performance overlay": the settings "overlay" and "overlay_style" as one row
|
|
PERF_CHOICES = ("off", "minimal", "detailed", "graphs", "bar")
|
|
PERF_NAMES = {"off": "Off", "minimal": "Minimal", "detailed": "Detailed", "graphs": "Graphs", "bar": "Bar"}
|
|
PERF_HELP = ("Live numbers in a corner of the picture. Minimal: frames on screen, the game's own frame rate, the delay, "
|
|
"and a dot for how well your PC keeps up. Detailed adds the AI's time per frame and the upscaler. Graphs "
|
|
"draws frametime, the pipeline's time, delay and the graphics card's load over time. Bar is one line along the "
|
|
"top or bottom edge. Which numbers show, and the corner, size and colours, are on the Overlay tab.")
|
|
ACTION_HELP = {
|
|
"restart": "Restarts Summit's pipeline with the new settings. The game keeps running; it takes a few seconds.",
|
|
"clip": "Saves what you just played to your Videos folder. Ctrl+Alt+R does the same without opening this.",
|
|
"summary": "Writes this session's numbers so far (averages, lows, the time of each stage, the settings and what "
|
|
"changed) to a .json and a .txt file in Summit's data folder, and shows where. Summit also does it when "
|
|
"it stops.",
|
|
# framegen/optimize.py, on the Optimize tab
|
|
"optimize": "Tries Summit's own settings one after another for a few seconds each (with a countdown at the top) and "
|
|
"keeps the best that holds your minimums, by your priority. Only Summit's settings change, never the "
|
|
"game's own graphics options. Your settings come back exactly if you stop it.",
|
|
"optimize_cancel": "Stops and puts your settings back exactly as they were.",
|
|
"optimize_apply": "Keeps the best result shown on the card and saves it as your settings.",
|
|
}
|
|
OPTIMIZE_ROWS = {"idle": (("optimize", "Find my settings"),),
|
|
"running": (("optimize_cancel", "Stop optimizing"),),
|
|
"card": (("optimize_apply", "Apply the result"), ("optimize_cancel", "Keep my settings"))}
|
|
QUIT_HELP = "Closes Summit's picture. A game started from Summit's launcher is closed with it."
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Row:
|
|
kind: str # "setting" | "perf" | "action" | "header" (a heading inside a tab: drawn, never highlighted)
|
|
key: str # the setting's key, "perf", or the action: "restart", "clip", "quit"
|
|
label: str
|
|
spec: Spec | None = None
|
|
|
|
|
|
class Menu:
|
|
"""allowed(key, value): whether a choice can be picked now (e.g. RTX VSR when the SDK isn't installed).
|
|
disabled(key): a reason to grey out a whole row, or None. restart_reasons(): labels of settings changed since
|
|
start that need a restart. Changes go through Settings, whose watchers apply them.
|
|
|
|
title: the game's name, for the header. toggle_key: the key that opens and closes the overlay, as shown.
|
|
quit_label / quit_help: what the Quit row says (it differs over a game and in the video window).
|
|
window_keys: the video window has the keyboard, so its one-letter keys work (F, S, U...) and the help may name
|
|
them; over a game they're the game's, and the help leaves them out.
|
|
status: (health, main, rest), the live line in the header ("good", "118 fps", "game 60 - 21 ms"), set by the window.
|
|
|
|
tab, and each tab's highlighted row, stay when the overlay closes, so the player comes back to where they were."""
|
|
|
|
def __init__(self, settings: Settings, specs: tuple[Spec, ...] = SPECS,
|
|
allowed: Callable[[str, object], bool] | None = None,
|
|
disabled: Callable[[str], str | None] | None = None,
|
|
restart_reasons: Callable[[], list[str]] | None = None, title: str = "",
|
|
toggle_key: str = "Insert", quit_label: str = "Quit", quit_help: str = QUIT_HELP,
|
|
window_keys: bool = True) -> None:
|
|
self.settings, self.specs = settings, specs
|
|
self.allowed = allowed or (lambda k, v: True)
|
|
self.disabled = disabled or (lambda k: None)
|
|
self.restart_reasons = restart_reasons or (lambda: [])
|
|
self.title, self.toggle_key = title, toggle_key
|
|
self.quit_label, self.quit_help, self.window_keys = quit_label, quit_help, window_keys
|
|
self._open = False
|
|
self.tab: str | None = None # the section shown; None: Home
|
|
self.focus = "rows" # "rows" or "tabs": where the arrow keys are
|
|
self.index = 0
|
|
self.armed = False # Quit was picked once: once more quits
|
|
self.status: tuple[str, str, str] = ("", "", "")
|
|
self._sel: str | None = None # the highlighted row's key, and the index it was at (see _follow)
|
|
self._at = 0
|
|
self._left: dict[str | None, str] = {} # each tab's highlighted row when the player last left it
|
|
self._scroll = 0
|
|
self._wheel = 0.0 # wheel movement not yet a whole row (a touchpad's small steps add up)
|
|
self._drop: str | None = None # the row whose drop-down list is open (its key)
|
|
self._drop_index = 0 # the highlighted choice in it
|
|
self._drop_scroll = 0
|
|
self._drag: tuple | None = None # what the mouse is dragging inside: ("slider", row index) or ("scrollbar", y0, scroll0)
|
|
self._hover: tuple | None = None # ("tab", i), ("close",): what the mouse is over, besides rows
|
|
self._hit: dict = {} # render()'s layout in the image's pixels, for the mouse
|
|
# Compare's Same area (framegen/compare.py Live): area_view() -> {"n", "box", "cell", "zoom", "sel"} or None,
|
|
# drawn as a map of the picture in the help card while the Area row is highlighted; area_click(fx, fy): the
|
|
# map clicked at that point of the picture. Set by the window; None: no map.
|
|
self.area_view: Callable[[], dict | None] | None = None
|
|
self.area_click: Callable[[float, float], None] | None = None
|
|
self._drawn: tuple = (None, None) # render()'s last picture and what it showed (see there)
|
|
self.optimizer_state: Callable[[], str] | None = None # framegen/optimize.py Control.state, when it can run
|
|
self.optimizer_note: Callable[[], str] = lambda: "" # its headroom line, beside Find my settings
|
|
|
|
@property
|
|
def open(self) -> bool:
|
|
return self._open
|
|
|
|
@open.setter
|
|
def open(self, on: bool) -> None:
|
|
if on != self._open: # (what the mouse was over, an open list and a half-asked Quit don't outlive a visit)
|
|
self._open, self._hover, self.armed, self._drop, self._drag = on, None, False, None, None
|
|
|
|
# ---- what there is ---------------------------------------------------------
|
|
def sections(self) -> list[str]:
|
|
"""The sections that have a setting that applies right now, in SPECS order."""
|
|
values = self.settings.values()
|
|
out: list[str] = []
|
|
for s in self.specs:
|
|
if s.group and s.group not in out and s.applies_to(values):
|
|
out.append(s.group)
|
|
return out
|
|
|
|
def tabs(self) -> list[str | None]:
|
|
return [None] + self.sections()
|
|
|
|
def tab_rows(self, tab: str | None) -> list[Row]:
|
|
"""A tab's rows: the settings that apply right now (VFG quality only while NVIDIA VFG is picked, and so on).
|
|
Home: the big choices that apply live, the performance overlay, and the actions. Restart now is on every tab
|
|
while something needs it."""
|
|
values = self.settings.values()
|
|
if tab is None:
|
|
rows = [Row("setting", s.key, s.label, s) for s in self.specs
|
|
if (s.quick and s.live or not s.group) and s.applies_to(values)]
|
|
if "overlay" in values and "overlay_style" in values:
|
|
rows.append(Row(PERF, PERF, "Performance overlay"))
|
|
else:
|
|
rows, sub = [], None
|
|
for s in self.specs:
|
|
if s.group != tab or not s.applies_to(values):
|
|
continue
|
|
if s.sub and s.sub != sub:
|
|
rows.append(Row("header", "#" + s.sub, s.sub))
|
|
sub = s.sub
|
|
rows.append(Row("setting", s.key, s.label, s))
|
|
if tab == "Optimize" and self.optimizer_state is not None:
|
|
rows += [Row("action", k, label) for k, label in OPTIMIZE_ROWS.get(self.optimizer_state(), ())]
|
|
if self.restart_reasons():
|
|
rows.append(Row("action", "restart", "Restart now"))
|
|
if tab is None:
|
|
if values.get("replay"):
|
|
rows.append(Row("action", "clip", "Save a clip"))
|
|
rows.append(Row("action", "summary", "Save a stats summary"))
|
|
rows.append(Row("action", "quit", self.quit_label))
|
|
return rows
|
|
|
|
def rows(self) -> list[Row]:
|
|
"""The rows of the tab shown (Home, if its section has gone: nothing in it applies any more)."""
|
|
if self.tab is not None and self.tab not in self.sections():
|
|
self.tab = None
|
|
return self.tab_rows(self.tab)
|
|
|
|
# ---- a row's value ---------------------------------------------------------
|
|
def choices(self, row: Row) -> tuple:
|
|
return PERF_CHOICES if row.kind == PERF else row.spec.choices if row.kind == "setting" else ()
|
|
|
|
def value(self, row: Row):
|
|
if row.kind == PERF:
|
|
return self.settings.overlay_style if self.settings.overlay else "off"
|
|
return getattr(self.settings, row.key) if row.kind == "setting" else None
|
|
|
|
def name(self, row: Row, value) -> str:
|
|
return PERF_NAMES[value] if row.kind == PERF else row.spec.name(value)
|
|
|
|
def can(self, row: Row, value) -> bool:
|
|
return row.kind == PERF or self.allowed(row.key, value)
|
|
|
|
def off(self, row: Row) -> str | None:
|
|
"""Why the row can't be changed, or None."""
|
|
return self.disabled(row.key) if row.kind == "setting" else None
|
|
|
|
def set_value(self, row: Row, value) -> None:
|
|
if row.kind == "action" or self.off(row) or value not in self.choices(row) or not self.can(row, value):
|
|
return
|
|
if row.kind == PERF:
|
|
if value == "off":
|
|
self.settings.set("overlay", False)
|
|
else:
|
|
self.settings.set("overlay_style", value)
|
|
self.settings.set("overlay", True)
|
|
else:
|
|
self.settings.set(row.key, value)
|
|
|
|
def step(self, row: Row, delta: int) -> None:
|
|
"""The next (or previous) choice that can be picked, going round (a slider: rightwards is up, and it stops
|
|
at its ends instead)."""
|
|
choices = self.ordered(row)
|
|
if self.kind_of(row) == "slider" and choices and self.value(row) in choices:
|
|
i = choices.index(self.value(row)) + delta
|
|
while 0 <= i < len(choices):
|
|
if self.can(row, choices[i]):
|
|
self.set_value(row, choices[i])
|
|
return
|
|
i += delta
|
|
return
|
|
if not choices or self.off(row):
|
|
return
|
|
i = choices.index(self.value(row))
|
|
for _ in range(len(choices)):
|
|
i = (i + delta) % len(choices)
|
|
if self.can(row, choices[i]):
|
|
self.set_value(row, choices[i])
|
|
return
|
|
|
|
# ---- moving about ----------------------------------------------------------
|
|
def _follow(self, rows: list[Row]) -> None:
|
|
"""Keeps the highlight on the same row when rows appear or go (a model or upscaler change)."""
|
|
keys = [r.key for r in rows]
|
|
if self.index == self._at and self._sel in keys: # (index set from outside: that row, as given)
|
|
self.index = keys.index(self._sel)
|
|
self.index = max(0, min(self.index, len(rows) - 1))
|
|
self.index = self._usable(rows, self.index, 1)
|
|
self._sel, self._at = keys[self.index], self.index
|
|
self._scroll = max(0, min(self._scroll, len(rows) - VISIBLE))
|
|
if self._drop is not None and self._drop not in keys:
|
|
self._drop = None
|
|
|
|
@staticmethod
|
|
def _usable(rows: list[Row], i: int, direction: int) -> int:
|
|
"""The row at i, or (a heading) the nearest one that isn't a heading, looking `direction` first."""
|
|
for d in (direction, -direction):
|
|
j = i
|
|
while 0 <= j < len(rows):
|
|
if rows[j].kind != "header":
|
|
return j
|
|
j += d
|
|
return i
|
|
|
|
def _reveal(self) -> None:
|
|
"""Scrolls the highlighted row into view (the keyboard moved it; the mouse never needs this)."""
|
|
if self.index < self._scroll:
|
|
self._scroll = self.index
|
|
elif self.index >= self._scroll + VISIBLE:
|
|
self._scroll = self.index - VISIBLE + 1
|
|
|
|
def _select(self, i: int, rows: list[Row] | None = None, reveal: bool = True, direction: int = 1) -> None:
|
|
rows = self.rows() if rows is None else rows
|
|
self.index = self._usable(rows, max(0, min(i, len(rows) - 1)), direction)
|
|
self._sel, self._at = rows[self.index].key, self.index
|
|
self._follow(rows)
|
|
if reveal:
|
|
self._reveal()
|
|
# a heading just above the first row shown comes into view with it
|
|
if self._scroll > 0 and rows[self._scroll - 1].kind == "header" and self.index == self._scroll:
|
|
self._scroll -= 1
|
|
|
|
def show(self, tab: str | None) -> None:
|
|
"""Goes to a tab, on the row it was left on."""
|
|
if tab == self.tab:
|
|
return
|
|
self._left[self.tab] = self._sel
|
|
self.tab, self.armed, self._scroll, self._drop = tab, False, 0, None
|
|
rows = self.rows()
|
|
keys = [r.key for r in rows]
|
|
want = self._left.get(self.tab)
|
|
self._select(keys.index(want) if want in keys else 0, rows)
|
|
|
|
def _turn(self, delta: int) -> None:
|
|
tabs = self.tabs()
|
|
self.show(tabs[(tabs.index(self.tab) + delta) % len(tabs)])
|
|
|
|
def _act(self, row: Row) -> str | None:
|
|
if row.key == "restart":
|
|
return "restart"
|
|
if row.key == "clip":
|
|
return "save_replay"
|
|
if row.key == "summary":
|
|
return "save_summary"
|
|
if row.key.startswith("optimize"):
|
|
return row.key
|
|
if self.armed:
|
|
self.armed = False
|
|
return "quit"
|
|
self.armed = True
|
|
return None
|
|
|
|
def key(self, name: str) -> str | None:
|
|
"""name: up / down / left / right / enter / back / next_tab / prev_tab. Returns "close", "restart", "quit",
|
|
"save_replay" or None."""
|
|
rows = self.rows()
|
|
self._follow(rows)
|
|
row = rows[self.index]
|
|
if not (name == "enter" and self.focus == "rows" and row.key == "quit"):
|
|
self.armed = False
|
|
if self._drop is not None: # an open list has the keys
|
|
drow = next((r for r in rows if r.key == self._drop), None)
|
|
choices = self.choices(drow) if drow else ()
|
|
if name in ("back", "next_tab", "prev_tab") or not choices:
|
|
self._drop = None
|
|
elif name in ("up", "down", "left", "right"):
|
|
self._drop_index = max(0, min(len(choices) - 1, self._drop_index + (-1 if name in ("up", "left") else 1)))
|
|
self._drop_reveal(len(choices))
|
|
elif name == "enter":
|
|
self.set_value(drow, choices[self._drop_index])
|
|
self._drop = None
|
|
return None
|
|
if name == "back":
|
|
return "close"
|
|
if name in ("next_tab", "prev_tab"):
|
|
self._turn(1 if name == "next_tab" else -1)
|
|
return None
|
|
if self.focus == "tabs":
|
|
if name in ("left", "right"):
|
|
self._turn(-1 if name == "left" else 1)
|
|
elif name in ("down", "enter"):
|
|
self.focus = "rows"
|
|
return None
|
|
if name == "up":
|
|
if all(r.kind == "header" for r in rows[:self.index]):
|
|
self.focus = "tabs"
|
|
else:
|
|
self._select(self.index - 1, rows, direction=-1)
|
|
elif name == "down":
|
|
self._select(self.index + 1, rows)
|
|
elif row.kind == "action":
|
|
if name == "enter":
|
|
return self._act(row)
|
|
elif name == "enter" and self.kind_of(row) == "list" and not self.off(row):
|
|
self._open_drop(row)
|
|
elif name in ("left", "right", "enter"):
|
|
self.step(row, -1 if name == "left" else 1)
|
|
return None
|
|
|
|
# ---- controls: which one a row gets ---------------------------------------
|
|
def kind_of(self, row: Row) -> str:
|
|
""""switch" (on/off), "buttons" (a few short choices side by side), "slider" (numbers that go in order) or
|
|
"list" (a drop-down list)."""
|
|
choices = self.choices(row)
|
|
if row.kind != "setting" and row.kind != PERF:
|
|
return ""
|
|
if set(choices) == {True, False}:
|
|
return "switch"
|
|
numeric = all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in choices)
|
|
if numeric and len(choices) >= 3 and list(choices) in (sorted(choices), sorted(choices, reverse=True)):
|
|
return "slider"
|
|
total = sum(len(self.name(row, v)) for v in choices)
|
|
if len(choices) <= 4 and total <= 34 or len(choices) <= 6 and total <= 16:
|
|
return "buttons"
|
|
return "list"
|
|
|
|
def _open_drop(self, row: Row) -> None:
|
|
choices = self.choices(row)
|
|
value = self.value(row)
|
|
self._drop = row.key
|
|
self._drop_index = choices.index(value) if value in choices else 0
|
|
self._drop_scroll = 0
|
|
self._drop_reveal(len(choices))
|
|
|
|
def _drop_reveal(self, n: int) -> None:
|
|
if self._drop_index < self._drop_scroll:
|
|
self._drop_scroll = self._drop_index
|
|
elif self._drop_index >= self._drop_scroll + DROP_VISIBLE:
|
|
self._drop_scroll = self._drop_index - DROP_VISIBLE + 1
|
|
self._drop_scroll = max(0, min(self._drop_scroll, n - DROP_VISIBLE))
|
|
|
|
def ordered(self, row: Row) -> list:
|
|
"""A slider's choices from its left end to its right: smallest first, whichever order the setting lists them."""
|
|
choices = list(self.choices(row))
|
|
return sorted(choices) if self.kind_of(row) == "slider" else choices
|
|
|
|
def _slide(self, row: Row, x: float, track: tuple[float, float]) -> None:
|
|
"""A slider pressed or dragged at x: the nearest choice that can be picked."""
|
|
choices = self.ordered(row)
|
|
if not choices or self.off(row):
|
|
return
|
|
t = 0.0 if track[1] <= track[0] else min(1.0, max(0.0, (x - track[0]) / (track[1] - track[0])))
|
|
want = t * (len(choices) - 1)
|
|
for i in sorted(range(len(choices)), key=lambda i: abs(i - want)):
|
|
if self.can(row, choices[i]):
|
|
if choices[i] != self.value(row):
|
|
self.set_value(row, choices[i])
|
|
return
|
|
|
|
# ---- mouse (x, y: pixels in the image render() made, from its top-left corner)
|
|
@staticmethod
|
|
def _in(box, x: float, y: float) -> bool:
|
|
"""Whether (x, y) is in box; None (no scrollbar on a short tab, no open list) holds nothing."""
|
|
return box is not None and box[0] <= x < box[2] and box[1] <= y < box[3]
|
|
|
|
def _row_at(self, x: float, y: float) -> int | None:
|
|
h = self._hit
|
|
if not h or not self._in(h["rows"], x, y):
|
|
return None
|
|
i = self._scroll + int((y - h["rows"][1]) // h["row_h"])
|
|
return i if 0 <= i < len(self.rows()) else None
|
|
|
|
def hover(self, x: float, y: float) -> None:
|
|
"""The mouse over a row highlights it (and shows its help); over a tab, Close or a list's choice, lights that
|
|
up. Nothing scrolls: the page moves only with the wheel or the scrollbar."""
|
|
if self._drag is not None:
|
|
return self.drag(x, y)
|
|
self._hover = None
|
|
if self._drop is not None:
|
|
for box, value, ok in self._hit.get("drop_items", ()):
|
|
if self._in(box, x, y):
|
|
self._hover = ("drop", value)
|
|
if ok:
|
|
self._drop_index = self.choices(self._drop_row()).index(value)
|
|
return
|
|
if self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
|
return
|
|
for i, box in enumerate(self._hit.get("tabs", ())):
|
|
if self._in(box, x, y):
|
|
self._hover = ("tab", i)
|
|
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
|
|
self._hover = ("close",)
|
|
i = self._row_at(x, y)
|
|
if i is not None and self.rows()[i].kind != "header" and (i != self.index or self.focus != "rows"):
|
|
self.focus, self.armed = "rows", False
|
|
self._select(i, reveal=False)
|
|
|
|
def cursor(self, x: float, y: float) -> str:
|
|
"""The mouse pointer to show here: "move" on the title bar, "hand" on something to click, else "arrow"."""
|
|
if self._drag is not None:
|
|
return "hand"
|
|
if self._drop is not None and self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
|
return "hand"
|
|
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y) or any(self._in(b, x, y) for b in self._hit.get("tabs", ())):
|
|
return "hand"
|
|
if self._in(self._hit.get("title", (0, 0, 0, 0)), x, y):
|
|
return "move"
|
|
if self._in(self._hit.get("map"), x, y):
|
|
return "hand"
|
|
i = self._row_at(x, y)
|
|
if i is not None and any(self._in(b, x, y) for b, _, _ in self._hit.get("controls", {}).get(i, ())):
|
|
return "hand"
|
|
if self._in(self._hit.get("scrollbar", (0, 0, 0, 0)), x, y):
|
|
return "hand"
|
|
return "arrow"
|
|
|
|
def scroll(self, dy: float) -> None:
|
|
"""The wheel scrolls the page (or an open list) a row a step; the highlight stays on its row."""
|
|
if not dy:
|
|
return
|
|
self._wheel += dy
|
|
steps = int(self._wheel) # whole rows; a touchpad's fractions wait until they add up to one
|
|
if not steps:
|
|
return
|
|
self._wheel -= steps
|
|
if self._drop is not None:
|
|
n = len(self.choices(self._drop_row()))
|
|
self._drop_scroll = max(0, min(self._drop_scroll - steps, n - DROP_VISIBLE))
|
|
return
|
|
n = len(self.rows())
|
|
self._scroll = max(0, min(self._scroll - steps, n - VISIBLE))
|
|
|
|
def _drop_row(self) -> Row | None:
|
|
return next((r for r in self.rows() if r.key == self._drop), None)
|
|
|
|
def grab(self, x: float, y: float) -> str | None:
|
|
"""A press that may start a drag: "move" on the title bar (the window moves the overlay: framegen/io.py),
|
|
"drag" on a slider or the scrollbar (followed here by drag() until release()), else None (then click())."""
|
|
if self._drop is not None:
|
|
return None # a list is open: a press picks from it or closes it (click)
|
|
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
|
|
return None
|
|
if self._in(self._hit.get("title", (0, 0, 0, 0)), x, y):
|
|
return "move"
|
|
sb = self._hit.get("scrollbar")
|
|
if sb and self._in(sb, x, y):
|
|
thumb = self._hit.get("thumb", sb)
|
|
if not (thumb[1] <= y < thumb[3]): # on the track: the page jumps there, then follows the drag
|
|
frac = (y - sb[1]) / max(1, sb[3] - sb[1])
|
|
self._scroll = max(0, min(len(self.rows()) - VISIBLE, round(frac * len(self.rows()) - VISIBLE / 2)))
|
|
self._drag = ("scrollbar", y, self._scroll)
|
|
return "drag"
|
|
i = self._row_at(x, y)
|
|
if i is not None:
|
|
for box, what, arg in self._hit.get("controls", {}).get(i, ()):
|
|
if what == "slider" and self._in(box, x, y):
|
|
rows = self.rows()
|
|
self.focus, self.armed = "rows", False
|
|
self._select(i, rows, reveal=False)
|
|
self._drag = ("slider", i, arg)
|
|
self._slide(rows[i], x, arg)
|
|
return "drag"
|
|
return None
|
|
|
|
def drag(self, x: float, y: float) -> None:
|
|
d = self._drag
|
|
if d is None:
|
|
return
|
|
if d[0] == "slider":
|
|
rows = self.rows()
|
|
if d[1] < len(rows):
|
|
self._slide(rows[d[1]], x, d[2])
|
|
elif d[0] == "scrollbar":
|
|
sb = self._hit.get("scrollbar", (0, 0, 0, 1))
|
|
n = len(self.rows())
|
|
per_px = n / max(1, sb[3] - sb[1])
|
|
self._scroll = max(0, min(n - VISIBLE, d[2] + round((y - d[1]) * per_px)))
|
|
|
|
def release(self) -> None:
|
|
self._drag = None
|
|
|
|
def click(self, x: float, y: float, right: bool = False) -> str | None:
|
|
"""A click: Close, a tab, a choice in an open list (outside it: the list closes), an action row, or a
|
|
setting's control: a switch flips, a button picks its choice, a list opens; anywhere else on a setting's row
|
|
is the next choice (right-click: the one before). Returns as key()."""
|
|
if self._drop is not None:
|
|
for box, value, ok in self._hit.get("drop_items", ()):
|
|
if self._in(box, x, y):
|
|
if ok:
|
|
self.set_value(self._drop_row(), value)
|
|
self._drop = None
|
|
return None
|
|
if not self._in(self._hit.get("drop", (0, 0, 0, 0)), x, y):
|
|
self._drop = None
|
|
return None
|
|
if self._in(self._hit.get("close", (0, 0, 0, 0)), x, y):
|
|
return "close"
|
|
m = self._hit.get("map")
|
|
if self._in(m, x, y) and self.area_click is not None:
|
|
self.area_click((x - m[0]) / max(1, m[2] - m[0]), (y - m[1]) / max(1, m[3] - m[1]))
|
|
return None
|
|
tabs = self.tabs()
|
|
for i, box in enumerate(self._hit.get("tabs", ())):
|
|
if self._in(box, x, y) and i < len(tabs):
|
|
self.show(tabs[i])
|
|
self.focus = "rows"
|
|
return None
|
|
i = self._row_at(x, y)
|
|
if i is None or self.rows()[i].kind == "header":
|
|
self.armed = False
|
|
return None
|
|
rows = self.rows()
|
|
self.focus = "rows"
|
|
self._select(i, rows, reveal=False)
|
|
row = rows[i]
|
|
if row.kind == "action":
|
|
if right:
|
|
self.armed = False
|
|
return None
|
|
if row.key != "quit":
|
|
self.armed = False
|
|
return self._act(row)
|
|
self.armed = False
|
|
if self.off(row):
|
|
return None
|
|
for box, what, arg in self._hit.get("controls", {}).get(i, ()):
|
|
if self._in(box, x, y):
|
|
if what == "set":
|
|
self.set_value(row, arg)
|
|
elif what == "list":
|
|
self._open_drop(row)
|
|
elif what == "slider":
|
|
self._slide(row, x, arg)
|
|
else:
|
|
self.step(row, arg)
|
|
return None
|
|
if self.kind_of(row) == "list" and not right:
|
|
self._open_drop(row)
|
|
else:
|
|
self.step(row, -1 if right else 1)
|
|
return None
|
|
|
|
def _shown(self) -> tuple:
|
|
"""What the drawing depends on, but for the header's live numbers."""
|
|
return (self.tab, self.focus, self.index, self._scroll, self.armed, self._hover, self.title, self.toggle_key,
|
|
self._drop, self._drop_index, self._drop_scroll, self._drag and self._drag[0],
|
|
tuple(self.settings.values().items()), tuple(self.restart_reasons()),
|
|
tuple(self.disabled(s.key) for s in self.specs),
|
|
self.optimizer_state and self.optimizer_state(), self.optimizer_note())
|
|
|
|
def state(self) -> tuple:
|
|
"""Everything the drawing depends on (the window redraws only when this changes)."""
|
|
return (self.status, self._shown())
|
|
|
|
# ---- drawing ---------------------------------------------------------------
|
|
def _help(self, row: Row) -> tuple[str, list[tuple[str, str]]]:
|
|
"""A row's help, and its rough effect on the picture and on speed as (name, text) pairs."""
|
|
if row.kind == "action":
|
|
return (self.quit_help if row.key == "quit" else ACTION_HELP[row.key]), []
|
|
if row.kind == PERF:
|
|
return PERF_HELP, []
|
|
why = self.off(row)
|
|
if why:
|
|
return why, []
|
|
text = row.spec.help
|
|
if not self.window_keys: # "Key: U." and the like: over a game those keys are the game's
|
|
text = re.sub(r"\s*Key: [^.]*\.", "", text)
|
|
return text, [(name, row.spec.impact[k]) for k, name in (("picture", "PICTURE"), ("speed", "SPEED"))
|
|
if row.spec.impact.get(k)]
|
|
|
|
def render(self, ui: float = 1.0, opacity: float = 1.0, max_w: int | None = None) -> np.ndarray:
|
|
"""The overlay as an RGBA image: clear outside its rounded corners, and its background lets `1 - opacity` of
|
|
the game through (text and controls stay solid). ui scales it (1.0 suits a 1080p-tall picture); max_w: the
|
|
widest it may be (the picture's width, less a margin), narrower than its own width the panel is made
|
|
narrower, never cut."""
|
|
def px(v: float) -> int:
|
|
return max(1, int(round(v * ui)))
|
|
|
|
rows = self.rows()
|
|
self._follow(rows)
|
|
tabs = self.tabs()
|
|
W, pad = px(1100), px(32)
|
|
if max_w is not None:
|
|
W = max(px(560), min(W, int(max_w)))
|
|
head_h, tabs_h, row_h, help_h, foot_h = px(72), px(42), px(44), px(150), px(46)
|
|
y_tabs = head_h + px(12)
|
|
y_rows = y_tabs + tabs_h + px(12)
|
|
y_help = y_rows + VISIBLE * row_h + px(12)
|
|
y_foot = y_help + help_h + px(4)
|
|
H = y_foot + foot_h + px(4)
|
|
x0, x1 = pad - px(10), W - pad + px(10) # rows, cards and tabs reach a little past the text's margins
|
|
# Only the header's numbers change while nothing is touched (once a second): then just the header is drawn
|
|
# again, over the picture kept from last time.
|
|
area = self.area_view() if self.area_view is not None and rows[self.index].key == "compare_cell" else None
|
|
key = (round(ui, 3), W, self._shown(), repr(area))
|
|
if key == self._drawn[0]:
|
|
c = self._drawn[1]
|
|
c.d.rectangle((pad - px(2), px(8), W - pad + px(4), head_h - px(4)), fill=U.BG)
|
|
self._hit["close"] = self._header(c, px, W, pad, head_h)
|
|
return c.rgba(opacity, (U.SURFACE,))
|
|
c = U.Canvas(W, H, U.BG, px(18), border=U.BORDER)
|
|
f_label, f_value = U.font(px(16), "medium"), U.font(px(15), "medium")
|
|
f_small, f_tag, f_help = U.font(px(13)), U.font(px(10), "bold"), U.font(px(14))
|
|
close = self._header(c, px, W, pad, head_h)
|
|
c.line(1, head_h, W - 2, head_h, U.BORDER, 1)
|
|
|
|
# -- tabs
|
|
f_tab = U.font(px(15), "semibold")
|
|
tab_boxes, x = [], x0
|
|
for i, tab in enumerate(tabs):
|
|
name = HOME if tab is None else TAB_NAMES.get(tab, tab)
|
|
tw = U.text_w(name, f_tab)
|
|
box = (x, y_tabs, x + tw + 2 * px(15), y_tabs + tabs_h)
|
|
active, hover = tab == self.tab, self._hover == ("tab", i)
|
|
if active and self.focus == "tabs":
|
|
c.rrect(*box, px(10), fill=U.ACCENT)
|
|
col = U.ON_ACCENT
|
|
elif active:
|
|
c.rrect(*box, px(10), fill=U.RAISED, outline=U.BORDER)
|
|
col = U.TEXT
|
|
else:
|
|
col = U.TEXT if hover else U.DIM
|
|
c.text(x + px(15), y_tabs + tabs_h // 2, name, f_tab, col)
|
|
if active and self.focus != "tabs":
|
|
c.rrect(x + px(15), box[3] - px(6), box[2] - px(15), box[3] - px(3), px(2), fill=U.ACCENT)
|
|
tab_boxes.append(box)
|
|
x = box[2] + px(4)
|
|
|
|
# -- rows
|
|
controls: dict[int, list] = {}
|
|
for i in range(self._scroll, min(len(rows), self._scroll + VISIBLE)):
|
|
row, ry = rows[i], y_rows + (i - self._scroll) * row_h
|
|
mid = ry + row_h // 2
|
|
if row.kind == "header": # a heading: small capitals in the accent, a rule after it
|
|
hy = ry + row_h - px(14)
|
|
tw = c.spaced(pad + px(8), hy, row.label.upper(), U.font(px(11), "bold"), U.ACCENT, px(1.6))
|
|
c.line(pad + px(8) + tw + px(12), hy, x1 - px(8), hy, U.BORDER, 1)
|
|
continue
|
|
selected = i == self.index
|
|
lit = selected and self.focus == "rows"
|
|
if selected:
|
|
c.rrect(x0, ry + px(2), x1, ry + row_h - px(2), px(10), fill=U.RAISED if lit else U.SURFACE)
|
|
if lit:
|
|
c.rrect(x0, ry + px(12), x0 + px(4), ry + row_h - px(12), px(2), fill=U.ACCENT)
|
|
xr = x1 - px(14)
|
|
if row.kind == "action":
|
|
danger = row.key == "quit"
|
|
again = "Press Enter again to " + self.quit_label[:1].lower() + self.quit_label[1:]
|
|
label = again if danger and self.armed else row.label
|
|
colour = U.BAD if danger else U.ACCENT
|
|
c.text(pad + px(8), mid, label, f_label, colour)
|
|
if row.key == "optimize" and self.optimizer_note():
|
|
c.text(xr, mid, U.fit(self.optimizer_note(), f_small, px(430)), f_small, U.DIM, "rm")
|
|
if row.key == "restart":
|
|
note = "Applies: " + ", ".join(self.restart_reasons())
|
|
c.text(xr, mid, U.fit(note, f_small, px(430)), f_small, U.DIM, "rm")
|
|
elif row.key == "clip":
|
|
c.text(xr, mid, "the last " + _span(min(self.settings.replay_clip, self.settings.replay)),
|
|
f_small, U.DIM, "rm")
|
|
continue
|
|
why = self.off(row)
|
|
x = pad + px(8) + c.text(pad + px(8), mid, row.label, f_label, U.FAINT if why else U.TEXT) + px(12)
|
|
spec = row.spec
|
|
for tag, on in (("EXPERIMENTAL", spec is not None and spec.experimental),
|
|
("RESTART", spec is not None and not spec.live)):
|
|
if on: # built without the hardware to test it; applies after Restart now
|
|
tw = U.text_w(tag, f_tag) + px(0.8) * (len(tag) - 1)
|
|
c.rrect(x, mid - px(9), x + tw + px(14), mid + px(9), px(9), fill=U.SURFACE, outline=U.BORDER)
|
|
c.spaced(x + px(7), mid, tag, f_tag, U.FAINT if why else U.DIM, px(0.8))
|
|
x += tw + px(20)
|
|
if why:
|
|
c.text(xr, mid, "Not available", f_value, U.FAINT, "rm")
|
|
continue
|
|
controls[i] = self._control(c, row, xr, mid, lit, px, f_value)
|
|
|
|
n = len(rows)
|
|
scrollbar = thumb = None
|
|
if n > VISIBLE: # a scrollbar at the right edge: drag its thumb, or click the track to jump
|
|
top, span = y_rows + px(4), VISIBLE * row_h - px(8)
|
|
bx = W - px(12)
|
|
c.rrect(bx, top, bx + px(6), top + span, px(3), fill=U.SURFACE)
|
|
th = max(px(28), span * VISIBLE // n)
|
|
ty = top + (span - th) * self._scroll // (n - VISIBLE)
|
|
dragging = self._drag is not None and self._drag[0] == "scrollbar"
|
|
c.rrect(bx, ty, bx + px(6), ty + th, px(3), fill=U.DIM if dragging else U.FAINT)
|
|
scrollbar, thumb = (bx - px(6), top, W, top + span), (bx - px(6), ty, W, ty + th)
|
|
|
|
# -- what the highlighted row does
|
|
row = rows[self.index]
|
|
c.rrect(x0, y_help, x1, y_help + help_h, px(12), fill=U.SURFACE, outline=U.BORDER)
|
|
hx, hy, hw = x0 + px(18), y_help + px(26), x1 - x0 - 2 * px(18)
|
|
c.text(hx, hy, row.label, U.font(px(15), "semibold"), U.TEXT)
|
|
self._hit["map"] = None
|
|
if area is not None: # Same area's map: the picture, its cells numbered, the area picked; click to pick
|
|
mh = help_h - px(28)
|
|
mw = mh * 16 // 9
|
|
mx1, my0 = x1 - px(14), y_help + px(14)
|
|
m = (mx1 - mw, my0, mx1, my0 + mh)
|
|
self._map(c, m, area, px)
|
|
self._hit["map"] = m
|
|
hw -= mw + px(24)
|
|
text, impact = self._help(row)
|
|
hy += px(12)
|
|
room = 6 # lines: the help, then each effect, which gets a second line if there's room for it
|
|
lines = U.wrap(text, f_help, hw, room - len(impact))
|
|
for line in lines:
|
|
hy += px(21)
|
|
c.text(hx, hy, line, f_help, U.DIM)
|
|
room -= len(lines)
|
|
hy += px(4) if impact else 0
|
|
for k, (name, what) in enumerate(impact):
|
|
mine = U.wrap(what, f_help, hw - px(64), max(1, room - (len(impact) - 1 - k)))
|
|
room -= len(mine)
|
|
for j, line in enumerate(mine):
|
|
hy += px(21)
|
|
if j == 0:
|
|
c.spaced(hx, hy, name, f_tag, U.ACCENT, px(0.8))
|
|
c.text(hx + px(64), hy, line, f_help, U.TEXT)
|
|
|
|
# -- the keys
|
|
fy = y_foot + foot_h // 2
|
|
f_key, f_hint = U.font(px(11), "semibold"), U.font(px(12))
|
|
|
|
def cap(x: int, label: str | None, arrows: str = "", right: bool = False) -> int:
|
|
"""A key's cap ending (right) or starting at x; returns its other edge."""
|
|
w = (U.text_w(label, f_key) if label else px(26)) + px(14)
|
|
a = x - w if right else x
|
|
c.rrect(a, fy - px(11), a + w, fy + px(11), px(6), fill=U.RAISED, outline=U.BORDER)
|
|
if label:
|
|
c.text(a + w // 2, fy, label, f_key, U.TEXT, "mm")
|
|
for k, direction in enumerate(arrows):
|
|
c.chevron(a + w // 2 + (px(6) if k else -px(6)), fy, px(8),
|
|
{"u": "up", "d": "down", "l": "left", "r": "right"}[direction], U.TEXT)
|
|
return a if right else a + w
|
|
|
|
x = x0 + px(4)
|
|
for label, arrows, what in ((None, "ud", "Select"), (None, "lr", "Change"), ("Tab", "", "Section"),
|
|
("Esc", "", "Close")):
|
|
x = cap(x, label, arrows) + px(8)
|
|
x += c.text(x, fy, what, f_hint, U.DIM) + px(18)
|
|
x = x1 - px(4)
|
|
x -= c.text(x, fy, "Show / hide", f_hint, U.DIM, "rm") + px(8)
|
|
x = cap(x, self.toggle_key, right=True) - px(18)
|
|
c.text(x, fy, "Drag the title to move", f_hint, U.FAINT, "rm")
|
|
|
|
# -- an open drop-down list, over everything below its row
|
|
drop_box, drop_items = None, []
|
|
drow = next((r for r in rows if r.key == self._drop), None)
|
|
di = rows.index(drow) if drow is not None else -1
|
|
if drow is not None and self._scroll <= di < self._scroll + VISIBLE and di in controls:
|
|
anchor = next((b for b, what, _ in controls[di] if what == "list"), None)
|
|
if anchor is not None:
|
|
choices = self.choices(drow)
|
|
item_h = px(36)
|
|
shown = min(len(choices), DROP_VISIBLE)
|
|
lw = max(anchor[2] - anchor[0], max(U.text_w(self.name(drow, v), f_value) for v in choices) + px(52))
|
|
lx1 = anchor[2]
|
|
lx0 = max(px(8), lx1 - lw)
|
|
lh = shown * item_h + px(12)
|
|
ly0 = anchor[3] + px(4)
|
|
if ly0 + lh > H - px(8): # no room below: above the row instead
|
|
ly0 = max(px(8), anchor[1] - px(4) - lh)
|
|
drop_box = (lx0, ly0, lx1, ly0 + lh)
|
|
c.rrect(lx0 + px(2), ly0 + px(4), lx1 + px(2), ly0 + lh + px(4), px(12), fill=(6, 8, 12)) # shadow
|
|
c.rrect(*drop_box, px(12), fill=U.RAISED, outline=U.BORDER)
|
|
value = self.value(drow)
|
|
for k in range(self._drop_scroll, min(len(choices), self._drop_scroll + shown)):
|
|
v = choices[k]
|
|
iy = ly0 + px(6) + (k - self._drop_scroll) * item_h
|
|
box = (lx0 + px(6), iy, lx1 - px(6), iy + item_h)
|
|
ok = self.can(drow, v)
|
|
if k == self._drop_index and ok:
|
|
c.rrect(*box, px(8), fill=U.HILITE)
|
|
if v == value:
|
|
c.chevron(box[0] + px(16), iy + item_h // 2, px(9), "right", U.ACCENT) # the one in use
|
|
c.text(box[0] + px(30), iy + item_h // 2, self.name(drow, v), f_value,
|
|
(U.ACCENT if v == value else U.TEXT) if ok else U.OFF)
|
|
drop_items.append((box, v, ok))
|
|
if len(choices) > shown: # more below or above: a thin bar
|
|
span = lh - px(16)
|
|
th = max(px(18), span * shown // len(choices))
|
|
ty = ly0 + px(8) + (span - th) * self._drop_scroll // (len(choices) - shown)
|
|
c.rrect(lx1 - px(6), ty, lx1 - px(3), ty + th, px(2), fill=U.FAINT)
|
|
|
|
self._hit = {"w": W, "h": H, "rows": (x0, y_rows, x1, y_rows + VISIBLE * row_h), "row_h": row_h,
|
|
"map": self._hit.get("map"),
|
|
"tabs": tab_boxes, "close": close, "controls": controls, "title": (0, 0, W, head_h),
|
|
"scrollbar": scrollbar, "thumb": thumb, "drop": drop_box, "drop_items": drop_items}
|
|
self._drawn = (key, c)
|
|
return c.rgba(opacity, (U.SURFACE,))
|
|
|
|
@staticmethod
|
|
def _map(c: U.Canvas, box, area: dict, px) -> None:
|
|
"""The Same area map: the picture's outline, its cells (numbered; the picked one, or while picking the
|
|
highlighted one, lit) and the area as a box."""
|
|
x0, y0, x1, y1 = box
|
|
w, h = x1 - x0, y1 - y0
|
|
c.rrect(x0, y0, x1, y1, px(6), fill=U.BG, outline=U.BORDER)
|
|
n = area["n"]
|
|
cols, rows = {2: (2, 1), 3: (3, 1)}.get(n, (2, 2))
|
|
f = U.font(px(15), "bold")
|
|
lit = area["cell"] if area["box"] is not None else area["sel"] + 1
|
|
for k in range(n):
|
|
i, j = k % cols, k // cols
|
|
cx0, cy0 = x0 + w * i // cols, y0 + h * j // rows
|
|
cx1, cy1 = x0 + w * (i + 1) // cols, y0 + h * (j + 1) // rows
|
|
on = k + 1 == lit
|
|
c.rrect(cx0 + px(3), cy0 + px(3), cx1 - px(3), cy1 - px(3), px(4), fill=U.HILITE if on else U.SURFACE)
|
|
c.text((cx0 + cx1) // 2, (cy0 + cy1) // 2, str(k + 1), f, U.TEXT if on else U.FAINT, "mm")
|
|
if area["box"] is not None:
|
|
bx0, by0, bx1, by1 = area["box"]
|
|
r = (x0 + int(bx0 * w), y0 + int(by0 * h), x0 + max(int(bx1 * w), int(bx0 * w) + px(4)),
|
|
y0 + max(int(by1 * h), int(by0 * h) + px(4)))
|
|
c.d.rectangle((r[0], r[1], r[2] - 1, r[3] - 1), outline=U.ACCENT, width=max(1, px(2)))
|
|
else:
|
|
c.text(x0 + w // 2, y1 - px(10), "picking", U.font(px(11), "medium"), U.DIM, "mm")
|
|
|
|
def _header(self, c: U.Canvas, px, W: int, pad: int, head_h: int) -> tuple[int, int, int, int]:
|
|
"""The mark, the game's name, the live numbers and Close. Returns Close's box."""
|
|
f_label = U.font(px(16), "medium")
|
|
cy = head_h // 2 + px(2)
|
|
c.logo(pad, cy - px(14), px(28))
|
|
x = pad + px(38)
|
|
x += c.spaced(x, cy, "SUMMIT", U.font(px(15), "bold"), U.TEXT, px(2.6)) + px(14)
|
|
close = (W - pad - px(26), cy - px(14), W - pad + px(2), cy + px(14))
|
|
right = close[0] - px(14)
|
|
health, main, rest = self.status
|
|
if main:
|
|
f_main, f_rest = U.font(px(15), "semibold"), U.font(px(14))
|
|
chip_w = px(12) + px(20) + U.text_w(main, f_main) + (px(10) + U.text_w(rest, f_rest) if rest else 0) + px(14)
|
|
c.rrect(right - chip_w, cy - px(15), right, cy + px(15), px(15), fill=U.SURFACE, outline=U.BORDER)
|
|
cx = right - chip_w + px(16)
|
|
c.circle(cx, cy, px(5), U.HEALTH.get(health, U.FAINT))
|
|
cx += px(14)
|
|
cx += c.text(cx, cy, main, f_main, U.TEXT) + px(10)
|
|
c.text(cx, cy, rest, f_rest, U.DIM)
|
|
right -= chip_w + px(14)
|
|
if self.title and right - x > px(60):
|
|
c.line(x, cy - px(9), x, cy + px(9), U.BORDER, max(1, px(1.5)))
|
|
c.text(x + px(14), cy, U.fit(self.title, f_label, right - x - px(14)), f_label, U.DIM)
|
|
if self._hover == ("close",):
|
|
c.rrect(*close, px(8), fill=U.RAISED)
|
|
col = U.TEXT if self._hover == ("close",) else U.FAINT
|
|
mx, a, t = (close[0] + close[2]) // 2, px(5.5), max(2, px(2))
|
|
c.line(mx - a, cy - a, mx + a, cy + a, col, t)
|
|
c.line(mx - a, cy + a, mx + a, cy - a, col, t)
|
|
return close
|
|
|
|
def _control(self, c: U.Canvas, row: Row, xr: int, mid: int, lit: bool, px, f) -> list:
|
|
"""Draws a row's control, ending at xr (kind_of): a switch, buttons side by side, a slider, or a drop-down
|
|
button. Returns what a click does where: [(box, "set" | "step" | "slider" | "list", arg)]."""
|
|
choices, value = self.choices(row), self.value(row)
|
|
kind = self.kind_of(row)
|
|
hits: list = []
|
|
if kind == "switch":
|
|
w, h = px(42), px(24)
|
|
on = bool(value)
|
|
box = (xr - w, mid - h // 2, xr, mid - h // 2 + h)
|
|
c.rrect(*box, h // 2, fill=U.ACCENT if on else U.HILITE)
|
|
r = h // 2 - px(3)
|
|
c.circle(xr - h // 2 if on else xr - w + h // 2, mid, r, (255, 255, 255) if on else U.DIM)
|
|
c.text(xr - w - px(12), mid, self.name(row, value), f, U.TEXT if on else U.DIM, "rm")
|
|
return [((xr - w - px(60), mid - h, xr, mid + h), "step", 1)]
|
|
if kind == "buttons":
|
|
names = [self.name(row, v) for v in choices]
|
|
widths = [U.text_w(n, f) + 2 * px(13) for n in names]
|
|
h = px(30)
|
|
x = xr - sum(widths)
|
|
c.rrect(x - px(3), mid - h // 2 - px(3), xr + px(3), mid + h // 2 + px(3), px(10), fill=U.BG, outline=U.BORDER)
|
|
for v, n, w in zip(choices, names, widths):
|
|
ok = self.can(row, v)
|
|
if v == value:
|
|
c.rrect(x, mid - h // 2, x + w, mid + h // 2, px(7), fill=U.ACCENT if lit else U.HILITE)
|
|
col = U.ON_ACCENT if lit else U.TEXT
|
|
else:
|
|
col = U.DIM if ok else U.OFF
|
|
c.text(x + w // 2, mid, n, f, col, "mm")
|
|
if ok:
|
|
hits.append(((x, mid - h, x + w, mid + h), "set", v))
|
|
x += w
|
|
return hits
|
|
if kind == "slider":
|
|
# A track with a mark for each choice (the ones that can't be picked are dim), the value before it
|
|
choices = self.ordered(row)
|
|
tw, knob = px(220), px(9)
|
|
tx1 = xr - knob
|
|
tx0 = tx1 - tw
|
|
n = len(choices)
|
|
i = choices.index(value) if value in choices else None
|
|
pos = (tx0 + tw * i / (n - 1)) if i is not None else None
|
|
if pos is None and isinstance(value, (int, float)): # a value between the choices (a custom one)
|
|
lo, hi = choices[0], choices[-1]
|
|
k = 0.0 if hi == lo else (value - lo) / (hi - lo)
|
|
below = [j for j, v in enumerate(choices) if v <= value]
|
|
j = below[-1] if below else 0
|
|
if j < n - 1:
|
|
k = j + (value - choices[j]) / (choices[j + 1] - choices[j])
|
|
pos = tx0 + tw * k / (n - 1)
|
|
else:
|
|
pos = tx1
|
|
pos = tx0 if pos is None else pos
|
|
c.rrect(tx0, mid - px(3), tx1, mid + px(3), px(3), fill=U.HILITE)
|
|
c.rrect(tx0, mid - px(3), max(tx0 + px(6), int(pos)), mid + px(3), px(3), fill=U.ACCENT if lit else U.DIM)
|
|
for j, v in enumerate(choices):
|
|
mx = int(tx0 + tw * j / (n - 1))
|
|
c.circle(mx, mid, px(2), U.TEXT if j <= (i if i is not None else -1) else (U.FAINT if self.can(row, v) else U.OFF))
|
|
dragging = self._drag is not None and self._drag[0] == "slider" and self._drag[1] == self.index and lit
|
|
c.circle(int(pos), mid, knob + (px(2) if dragging else 0), (255, 255, 255))
|
|
c.circle(int(pos), mid, knob - px(4), U.ACCENT if lit else U.DIM)
|
|
c.text(tx0 - px(16), mid, self.name(row, value), f, U.TEXT if lit else U.DIM, "rm")
|
|
return [((tx0 - knob - px(4), mid - px(16), tx1 + knob + px(4), mid + px(16)), "slider", (tx0, tx1))]
|
|
# a drop-down list: the value in a box with a down arrow; a click opens the list (drawn in render)
|
|
text = self.name(row, value)
|
|
bw = max(px(190), U.text_w(text, f) + px(56))
|
|
box = (xr - bw, mid - px(16), xr, mid + px(16))
|
|
is_open = self._drop == row.key
|
|
c.rrect(*box, px(8), fill=U.RAISED if (lit or is_open) else U.SURFACE, outline=U.ACCENT if is_open else U.BORDER)
|
|
c.text(box[0] + px(14), mid, U.fit(text, f, bw - px(48)), f, U.TEXT if lit or is_open else U.DIM)
|
|
c.chevron(xr - px(18), mid, px(10), "up" if is_open else "down", U.ACCENT if lit or is_open else U.FAINT)
|
|
return [(box, "list", None)]
|
|
|
|
|
|
def _span(seconds: int) -> str:
|
|
"""15 -> "15 seconds", 180 -> "3 minutes"."""
|
|
if seconds < 60:
|
|
return f"{seconds} seconds"
|
|
return "minute" if seconds == 60 else f"{seconds // 60} minutes"
|