KO
games/rob-revisited / src / Revisited / Ui / SaveScreen.php · commit f9a1307
<?phpnamespace App\Revisited\Ui;use App\Revisited\I18n\Translator;use JumPHP\Gui\Form;use JumPHP\Input\Keyboard;use JumPHP\Renderer\Sdl;/** * "Charger une partie" / "Sauvegarder la partie": the list of the saved games (SaveStore), each row with its preview, its * name, the real date, the game's day and hour, the zone, the chapter, a few vitals, the play time, the shuttle's parts. * The autosave ("Sauvegarde automatique", its own slot: never one of the 20) comes first in the load list, set apart: it * loads and can be deleted, not renamed nor written by hand. Row actions: load / save here / overwrite (asked first), rename (a text field: the keyboard types, the pad and the mouse * use the letters drawn under it, a phone opens its own keyboard), delete (asked first). Loading over a game with unsaved * progress asks "Quitter la partie en cours sans sauvegarder ?". * * Keys: ↑ ↓ the row, ← → its buttons, Entrée the button, R rename, Suppr delete, Échap back. Mouse: click, wheel; phones: * one column of big rows, a drag scrolls. update() returns what the scene must do: ['load', key], ['save', key], ['close']. */final class SaveScreen{    /** load | save */    public string $mode = 'load';    /** @var list<array{type: string, key: string}> */    public array $rows = [];    public int $sel = 0;    /** the focused button of the selected row */    public int $btn = 0;    /** the first row shown */    public int $top = 0;    private Wheel $wheel;    /** @var array{kind: string, key: string, yes: bool}|null a question: overwrite | delete | leave */    public ?array $ask = null;    /** @var array{key: string, text: string, key_sel: int, caps: bool}|null the name being typed */    public ?array $edit = null;    /** the game running has progress not saved (a load asks first) */    public bool $dirty = false;    public bool $inGame = false;    public bool $touch = false;    /** a line shown at the bottom for a moment ("Partie sauvegardée.") */    public string $note = '';    private float $noteAge = 9.0;    private float $clock = 0.0;    private float $drag = 0.0;    private ?float $dragY = null;    /** @var array<string, string> slot key => the preview stamp its texture was made from */    private array $tex = [];    /** the letters under the name field: [label, typed text | action]; rows of keys */    private const KEYS = [        [['1', '1'], ['2', '2'], ['3', '3'], ['4', '4'], ['5', '5'], ['6', '6'], ['7', '7'], ['8', '8'], ['9', '9'], ['0', '0']],        [['a', 'a'], ['z', 'z'], ['e', 'e'], ['r', 'r'], ['t', 't'], ['y', 'y'], ['u', 'u'], ['i', 'i'], ['o', 'o'], ['p', 'p']],        [['q', 'q'], ['s', 's'], ['d', 'd'], ['f', 'f'], ['g', 'g'], ['h', 'h'], ['j', 'j'], ['k', 'k'], ['l', 'l'], ['m', 'm']],        [['w', 'w'], ['x', 'x'], ['c', 'c'], ['v', 'v'], ['b', 'b'], ['n', 'n'], ['é', 'é'], ['è', 'è'], ['à', 'à'], ['ç', 'ç']],        [['Maj', '#caps'], ['Espace', ' '], ['-', '-'], ['\'', '\''], [',', ','], ['Effacer', '#del']],        [['Annuler', '#cancel'], ['OK', '#ok']],    ];    /** widths of the keys, in key units */    private const WIDE = ['Maj' => 1.6, 'Espace' => 3.4, 'Effacer' => 1.8, 'Annuler' => 3.0, 'OK' => 3.0];    public function __construct(public SaveStore $store, private Sdl $sdl)    {        $this->wheel = new Wheel();    }    public function open(string $mode, bool $inGame, bool $dirty): void    {        $this->mode = $mode;        $this->inGame = $inGame;        $this->dirty = $dirty;        $this->ask = null;        $this->edit = null;        $this->sel = 0;        $this->btn = 0;        $this->top = 0;        $this->note = '';        $this->refresh();    }    /** The rows again (after a save, a delete): the selection stays on the same slot when it is still there. */    public function refresh(?string $keep = null): void    {        $keep ??= $this->rows[$this->sel]['key'] ?? null;        $this->rows = [];        if ($this->mode === 'save') {            $free = $this->store->firstFree();            if ($free !== null) {                $this->rows[] = ['type' => 'new', 'key' => $free];            }            foreach ($this->store->recent() as $k) {                if ($k !== SaveStore::AUTO) {                    $this->rows[] = ['type' => 'slot', 'key' => $k];                }            }        } else {            // the autosave first, set apart; then the player's games, the most recent first            if ($this->store->has(SaveStore::AUTO)) {                $this->rows[] = ['type' => 'slot', 'key' => SaveStore::AUTO];            }            foreach ($this->store->recent() as $k) {                if ($k !== SaveStore::AUTO) {                    $this->rows[] = ['type' => 'slot', 'key' => $k];                }            }        }        $this->sel = 0;        foreach ($this->rows as $i => $r) {            if ($r['type'] === 'slot' && $r['key'] === $keep) {                $this->sel = $i;            }        }        $this->btn = min($this->btn, count($this->buttons($this->sel)) - 1);        $this->btn = max(0, $this->btn);        $this->see();    }    public function editing(): bool    {        return $this->edit !== null;    }    public function say(string $text): void    {        $this->note = $text;        $this->noteAge = 0.0;    }    /** @return list<array{0: string, 1: string}> the buttons of a row: [label, action] */    private function buttons(int $i): array    {        $r = $this->rows[$i] ?? null;        if ($r === null) {            return [];        }        if ($r['type'] === 'new') {            return [['Sauvegarder ici', 'save']];        }        if ($r['key'] === SaveStore::AUTO) {            return [['Charger', 'load'], ['Supprimer', 'delete']];     // the autosave keeps its name        }        return $this->mode === 'save'            ? [['Écraser', 'overwrite'], ['Renommer', 'rename'], ['Supprimer', 'delete']]            : [['Charger', 'load'], ['Renommer', 'rename'], ['Supprimer', 'delete']];    }    /** the text size factor of phones (Canvas::$boost), kept from the last drawing: the rows' height follows it */    private float $boost = 1.0;    private function rowH(): float    {        if (!$this->touch) {            return 104.0;        }        // the title, three lines of 13 (line height 1.6), the buttons under them: nothing overlaps whatever the boost        $b = $this->boost;        return ceil(8 + 18 * 1.45 * $b + 3 * 13 * 1.6 * $b + 12 + 40 + 8 + 8);    }    /** @return array{0: float, 1: float, 2: float, 3: float} the list's area: x, y, w, h */    private function area(): array    {        return $this->touch ? [16.0, 92.0, 928.0, 548.0] : [100.0, 92.0, 760.0, 540.0];    }    private function visible(): int    {        return max(1, (int) floor($this->area()[3] / $this->rowH()));    }    /** Scrolls so that the selected row shows. */    private function see(): void    {        $n = $this->visible();        if ($this->sel < $this->top) {            $this->top = $this->sel;        } elseif ($this->sel >= $this->top + $n) {            $this->top = $this->sel - $n + 1;        }        $this->top = max(0, min($this->top, max(0, count($this->rows) - $n)));    }    // ------------------------------------------------------------------------------------------ input    /** @return array{0: string, 1?: string}|null what the scene does now */    public function update(UiInput $in, ?Keyboard $kb, bool $rename, float $dt): ?array    {        $this->clock += $dt;        $this->noteAge += $dt;        if ($this->edit !== null) {            $this->updateEdit($in, $kb);            return null;        }        if ($this->ask !== null) {            return $this->updateAsk($in);        }        if ($in->back || ($in->click && $in->hit === 'sv:back')) {            return ['close'];        }        $n = count($this->rows);        if ($n === 0) {            return null;        }        if ($in->up) {            $this->sel = ($this->sel - 1 + $n) % $n;        }        if ($in->down) {            $this->sel = ($this->sel + 1) % $n;        }        $nb = count($this->buttons($this->sel));        if ($in->up || $in->down) {            $this->btn = min($this->btn, $nb - 1);            $this->see();        }        if ($in->left) {            $this->btn = ($this->btn - 1 + $nb) % $nb;        }        if ($in->right) {            $this->btn = ($this->btn + 1) % $nb;        }        // the wheel and a finger's drag scroll the list        $this->top = Wheel::clamp($this->top, $n, $this->visible());     // the list may have shrunk (a slot deleted)        $steps = $this->wheel->steps($in->wheel);        if ($steps !== 0) {            $this->top = Wheel::clamp($this->top + $steps, $n, $this->visible());        }        if ($in->held && $this->dragY !== null) {            $this->drag += $in->my - $this->dragY;            while (abs($this->drag) > $this->rowH() * 0.6) {                $dir = $this->drag > 0 ? -1 : 1;                $this->drag -= -$dir * $this->rowH() * 0.6;                $this->top = max(0, min($this->top + $dir, max(0, $n - $this->visible())));            }        } else {            $this->drag = 0.0;        }        $this->dragY = $in->held ? $in->my : null;        if ($in->moved && $in->hover !== null && preg_match('/^sv:btn:(\d+):(\d+)$/', $in->hover, $m)) {            $this->sel = (int) $m[1];            $this->btn = (int) $m[2];        }        $run = $in->ok ? ($this->buttons($this->sel)[$this->btn][1] ?? null) : null;        if ($in->click && $in->hit !== null) {            if (preg_match('/^sv:btn:(\d+):(\d+)$/', $in->hit, $m)) {                $this->sel = (int) $m[1];                $this->btn = (int) $m[2];                $run = $this->buttons($this->sel)[$this->btn][1] ?? null;            } elseif (preg_match('/^sv:row:(\d+)$/', $in->hit, $m)) {                $again = $this->sel === (int) $m[1];                $this->sel = (int) $m[1];                $this->btn = 0;                if ($again) {                    $run = $this->buttons($this->sel)[0][1] ?? null;     // a second click on the row: its first button                }            }        }        if ($rename && ($this->rows[$this->sel]['type'] ?? '') === 'slot' && $this->rows[$this->sel]['key'] !== SaveStore::AUTO) {            $run = 'rename';        }        if ($in->drop && ($this->rows[$this->sel]['type'] ?? '') === 'slot') {            $run = 'delete';        }        return $run === null ? null : $this->run($run);    }    /** @return array{0: string, 1?: string}|null */    private function run(string $action): ?array    {        $row = $this->rows[$this->sel] ?? null;        if ($row === null) {            return null;        }        $key = $row['key'];        switch ($action) {            case 'save':                return ['save', $key];            case 'overwrite':                $this->ask = ['kind' => 'overwrite', 'key' => $key, 'yes' => false];                return null;            case 'delete':                $this->ask = ['kind' => 'delete', 'key' => $key, 'yes' => false];                return null;            case 'load':                if ($this->inGame && $this->dirty) {                    $this->ask = ['kind' => 'leave', 'key' => $key, 'yes' => false];                    return null;                }                return ['load', $key];            case 'rename':                $this->startRename($key);                return null;        }        return null;    }    public function startRename(string $key): void    {        $this->edit = ['key' => $key, 'text' => (string) ($this->store->metaOf($key)['name'] ?? ''), 'key_sel' => $this->okIndex(), 'caps' => false];    }    /** @return array{0: string, 1?: string}|null */    private function updateAsk(UiInput $in): ?array    {        $a = &$this->ask;        if ($in->left || $in->right) {            $a['yes'] = !$a['yes'];        }        if ($in->moved && ($in->hover === 'sv:yes' || $in->hover === 'sv:no')) {            $a['yes'] = $in->hover === 'sv:yes';        }        $answer = null;        if ($in->back || ($in->click && $in->hit === 'sv:no')) {            $answer = false;        } elseif ($in->click && $in->hit === 'sv:yes') {            $answer = true;        } elseif ($in->ok) {            $answer = $a['yes'];        }        if ($answer === null) {            return null;        }        $ask = $this->ask;        $this->ask = null;        if (!$answer) {            return null;        }        if ($ask['kind'] === 'delete') {            $name = (string) ($this->store->metaOf($ask['key'])['name'] ?? '');            $this->store->delete($ask['key']);            $this->refresh();            $this->sel = min($this->sel, max(0, count($this->rows) - 1));            $this->see();            $this->say('« ' . $name . ' » supprimée.');            return null;        }        return [$ask['kind'] === 'leave' ? 'load' : 'save', $ask['key']];    }    /** @return list<array{0: string, 1: string, 2: int, 3: int}> every key: label, value, row, index in the row */    private static function flatKeys(): array    {        $out = [];        foreach (self::KEYS as $r => $row) {            foreach ($row as $i => [$label, $value]) {                $out[] = [$label, $value, $r, $i];            }        }        return $out;    }    private function okIndex(): int    {        foreach (self::flatKeys() as $k => $key) {            if ($key[1] === '#ok') {                return $k;            }        }        return 0;    }    private function updateEdit(UiInput $in, ?Keyboard $kb): void    {        $e = &$this->edit;        $typed = $kb?->getTyped() ?? [];        $physical = $typed !== [] || ($kb !== null && $kb->getText() !== '');        if ($kb !== null) {            $system = $kb->hasTextEvents();            foreach ($typed as $code) {                if ($code === 8) {                    $this->key('#del');                } elseif ($code === 13 || $code === 1073741912) {                    $this->key('#ok');                    return;                } elseif ($code === 27) {                    $this->key('#cancel');                    return;                } elseif (!$system) {                    $ch = Form::character($code, $kb->shiftHeld());                    if ($ch !== null) {                        $this->type($ch);                    }                }            }            if ($system) {                foreach (mb_str_split($kb->getText()) ?: [] as $ch) {                    if ($ch >= ' ' && $ch !== "\x7f") {                        $this->type($ch);                    }                }            }        }        if ($this->edit === null) {            return;        }        if ($in->click && $in->hit !== null) {            if (preg_match('/^sv:key:(\d+)$/', $in->hit, $m)) {                $e['key_sel'] = (int) $m[1];                $this->key(self::flatKeys()[(int) $m[1]][1] ?? '');            }            return;        }        if ($physical) {            return;      // the keyboard typed: its letters are not moves in the grid (W, A, Z, Q, E, Space...)        }        $keys = self::flatKeys();        $cur = $keys[$e['key_sel']] ?? $keys[0];        if ($in->left || $in->right) {            $e['key_sel'] = max(0, min(count($keys) - 1, $e['key_sel'] + ($in->left ? -1 : 1)));        }        if ($in->up || $in->down) {            $row = max(0, min(count(self::KEYS) - 1, $cur[2] + ($in->up ? -1 : 1)));            // the key of that row nearest the same place across            $x = self::keyX($cur[2], $cur[3]);            $best = $e['key_sel'];            $bd = 1e9;            foreach ($keys as $k => $key) {                if ($key[2] === $row && abs(self::keyX($row, $key[3]) - $x) < $bd) {                    $bd = abs(self::keyX($row, $key[3]) - $x);                    $best = $k;                }            }            $e['key_sel'] = $best;        }        if ($in->back) {            $this->key('#cancel');            return;        }        if ($in->ok) {            $this->key($keys[$e['key_sel']][1]);        }    }    private function type(string $ch): void    {        if ($this->edit === null || mb_strlen($this->edit['text']) >= SaveStore::NAME_MAX) {            return;        }        $this->edit['text'] .= $ch;    }    private function key(string $value): void    {        if ($this->edit === null) {            return;        }        switch ($value) {            case '#del':                $this->edit['text'] = mb_substr($this->edit['text'], 0, max(0, mb_strlen($this->edit['text']) - 1));                return;            case '#caps':                $this->edit['caps'] = !$this->edit['caps'];                return;            case '#cancel':                $this->edit = null;                return;            case '#ok':                $name = SaveStore::cleanName($this->edit['text']);                if ($name !== '') {                    $this->store->rename($this->edit['key'], $name);                    $this->say('Renommée : « ' . $name . ' ».');                }                $this->edit = null;                return;        }        $this->type($this->edit['caps'] ? mb_strtoupper($value) : $value);    }    /** the centre of a key across its row, in key units */    private static function keyX(int $row, int $i): float    {        $x = 0.0;        foreach (self::KEYS[$row] as $k => [$label]) {            $w = self::WIDE[$label] ?? 1.0;            if ($k === $i) {                return $x + $w / 2 - self::rowWidth($row) / 2;            }            $x += $w + 0.12;        }        return 0.0;    }    private static function rowWidth(int $row): float    {        $w = 0.0;        foreach (self::KEYS[$row] as [$label]) {            $w += (self::WIDE[$label] ?? 1.0) + 0.12;        }        return $w - 0.12;    }    // ------------------------------------------------------------------------------------------ drawing    public function draw(Canvas $c): void    {        $phone = $this->touch;        $this->boost = $phone ? max(1.0, (float) $c->boost) : 1.0;        // opaque enough that the game's own buttons behind do not show through        $c->rect(0, 0, Canvas::W, Canvas::H, [4, 8, 12, $phone ? 235 : 175]);        [$x0, $y0, $w, $h] = $this->area();        $c->panel($x0 - 8, 16, $w + 16, Canvas::H - 32, 222);        $title = $this->mode === 'save' ? 'Sauvegarder la partie' : 'Charger une partie';        $c->text($title, 480, 30, $phone ? 26 : 28, [255, 255, 255], 'center');        $used = count(array_filter(array_keys($this->store->index()), static fn ($k): bool => (string) $k !== SaveStore::AUTO));        $c->text($used . ' / ' . SaveStore::SLOTS . ' emplacements utilisés', 480, 64, 13, [160, 176, 190], 'center');        if ($this->rows === []) {            $c->text('Aucune partie sauvegardée.', 480, 300, 18, [200, 210, 220], 'center');        }        $rh = $this->rowH();        $n = $this->visible();        for ($i = $this->top; $i < min(count($this->rows), $this->top + $n); $i++) {            $this->drawRow($c, $i, $x0, $y0 + ($i - $this->top) * $rh, $w, $rh - 8);        }        // the scroll bar        if (count($this->rows) > $n) {            $bh = $h * $n / count($this->rows);            $by = $y0 + ($h - $bh) * $this->top / max(1, count($this->rows) - $n);            $c->rect($x0 + $w + 2, $y0, 3, $h, [255, 255, 255, 24]);            $c->rect($x0 + $w + 2, $by, 3, $bh, [150, 210, 255, 160]);        }        // the foot: the keys, back        $fy = Canvas::H - 70;        if (!$phone) {            $c->text('↑ ↓ une partie · ← → un bouton · Entrée valider · R renommer · Suppr supprimer · Échap retour', $x0 + 4, $fy + 12, 12, [160, 176, 190]);        }        $bw = $phone ? 200.0 : 120.0;        $bh = $phone ? 44.0 : 32.0;        $bx = $phone ? 480 - $bw / 2 : $x0 + $w - $bw;        $c->pill($bx, $fy + 4, $bw, $bh, [255, 255, 255, 34]);        $c->text('Retour', $bx + $bw / 2, $fy + 4 + ($bh - 18) / 2, 18, [236, 240, 244], 'center');        $c->hit($bx, $fy + 4, $bw, $bh, 'sv:back');        if ($this->note !== '' && $this->noteAge < 3.0) {            $tw = $c->measure($this->note, 15) + 40;            $c->panel(480 - $tw / 2, $fy - 44, $tw, 32, 230, [130, 220, 150]);            $c->text($this->note, 480, $fy - 37, 15, [230, 255, 236], 'center');        }        if ($this->ask !== null) {            $this->drawAsk($c);        }        if ($this->edit !== null) {            $this->drawEdit($c);        }    }    private function drawRow(Canvas $c, int $i, float $x, float $y, float $w, float $h): void    {        $phone = $this->touch;        $row = $this->rows[$i];        $on = $i === $this->sel && $this->ask === null && $this->edit === null;        $c->rect($x, $y, $w, $h, $on ? [120, 190, 255, 40] : [255, 255, 255, 12]);        $c->border($x, $y, $w, $h, $on ? [150, 210, 255, 140] : [190, 210, 230, 30]);        if ($on) {            $c->rect($x, $y, 3, $h, [150, 210, 255, 220]);        }        $c->hit($x, $y, $w, $h, 'sv:row:' . $i);        $pw = $phone ? 128.0 : 120.0;        $ph = $pw * 0.75;        $px = $x + 10;        $py = $y + ($phone ? 10 : ($h - $ph) / 2);        $tx = $px + $pw + 14;        $buttons = $this->buttons($i);        $btnW = $phone ? 0.0 : 124.0;        $textW = $w - ($tx - $x) - $btnW - 18;        if ($row['type'] === 'new') {            $c->rect($px, $py, $pw, $ph, [255, 255, 255, 16]);            $c->border($px, $py, $pw, $ph, [190, 210, 230, 60]);            $c->text('+', $px + $pw / 2, $py + $ph / 2 - 24, 40, [200, 230, 255], 'center');            $c->text('Nouvelle sauvegarde', $tx, $y + 12, $phone ? 20 : 19, [255, 255, 255]);            $c->text('Emplacement ' . $row['key'] . ' — libre. Tu pourras la nommer.', $tx, $y + ($phone ? 44 : 40), 14, [176, 192, 206]);        } else {            $m = $this->store->metaOf($row['key']) ?? [];            $tex = $this->texture($row['key'], $m);            if ($tex !== null) {                $c->image($tex, $px, $py, $pw, $ph);            } else {                $c->rect($px, $py, $pw, $ph, [30, 40, 48, 220]);                $c->text('pas d\'aperçu', $px + $pw / 2, $py + $ph / 2 - 7, 11, [140, 150, 160], 'center');            }            $c->border($px, $py, $pw, $ph, [255, 255, 255, 50]);            $auto = $row['key'] === SaveStore::AUTO;            $name = (string) ($m['name'] ?? '');            $fs = 18.0;            $c->text($this->fit($c, $auto ? SaveStore::AUTO_NAME : $name, $fs, $textW), $tx, $y + 8, $fs, $auto ? [255, 214, 140] : [255, 255, 255]);            $ls = 13.0;            $lh = $phone ? 13 * 1.6 * $c->boost : 19.0;            $l1 = SaveStore::dateText((int) ($m['at'] ?? 0)) . ($auto ? '' : '  ·  n° ' . $row['key']);            $l2 = ($m['clock'] ?? '') . '  ·  ' . ($m['zoneName'] ?? '');            $l3 = 'Chapitre ' . ($m['chapter'] ?? '?') . ' — ' . ($m['title'] ?? '');            $l4 = sprintf('Santé %d %%  ·  Faim %d  ·  Soif %d  ·  %s °C  ·  %s de jeu  ·  navette %d/%d', (int) ($m['health'] ?? 0), (int) ($m['hunger'] ?? 0),                (int) ($m['thirst'] ?? 0), Translator::num((float) ($m['temp'] ?? '37'), 1), SaveStore::playedText((int) ($m['played'] ?? 0)),                (int) ($m['parts'] ?? 0), (int) ($m['partsOf'] ?? 4));            $ty = $y + 8 + $fs * 1.45 * ($phone ? $c->boost : 1.0);            $lines = [[$l1, [170, 186, 200]], [$l2, [214, 222, 230]], [$l3, [190, 214, 236]], [$l4, [160, 176, 190]]];            if ($phone) {                // three lines: where and when in the game, the chapter, the real date with the play time and health                $lines = [[$l2, [214, 222, 230]], [$l3, [190, 214, 236]], [SaveStore::dateText((int) ($m['at'] ?? 0)) . '  ·  ' . SaveStore::playedText((int) ($m['played'] ?? 0))                    . ' de jeu  ·  santé ' . (int) ($m['health'] ?? 0) . ' %  ·  navette ' . (int) ($m['parts'] ?? 0) . '/' . (int) ($m['partsOf'] ?? 4), [160, 176, 190]]];            }            foreach ($lines as $k => [$line, $col]) {                $c->text($this->fit($c, $line, $k === 3 ? $ls - 1 : $ls, $textW), $tx, $ty + $k * $lh, $k === 3 ? $ls - 1 : $ls, $col);            }        }        // the buttons: a column on the right (computer), a line under the text (phone)        foreach ($buttons as $k => [$label]) {            if ($phone) {                // a line of big buttons across the row, under the picture and the text                $bh = 40.0;                $bw = $row['type'] === 'new' ? 300.0 : ($w - 20 - 12 * (count($buttons) - 1)) / count($buttons);                $bx = $row['type'] === 'new' ? $x + $w - $bw - 10 : $x + 10 + $k * ($bw + 12);                $by = $y + $h - $bh - 8;            } else {                $bw = 116.0;                $bh = count($buttons) > 1 ? 26.0 : 34.0;                $bx = $x + $w - $bw - 10;                $by = count($buttons) > 1 ? $y + 8 + $k * ($bh + 6) : $y + ($h - $bh) / 2;            }            $focus = $on && $k === $this->btn;            $danger = $buttons[$k][1] === 'delete';            $c->pill($bx, $by, $bw, $bh, $focus ? ($danger ? [255, 130, 110, 200] : [150, 210, 255, 210]) : [255, 255, 255, 30]);            $c->text($this->fit($c, $label, 15, $bw - 12), $bx + $bw / 2, $by + ($bh - 15) / 2 - 1, 15, $focus ? [12, 18, 26] : [226, 232, 238], 'center', !$focus);            $c->hit($bx, $by, $bw, $bh, "sv:btn:$i:$k");        }    }    /** The text cut with "…" to fit $w units. */    private function fit(Canvas $c, string $text, float $size, float $w): string    {        if ($c->measure($text, $size) <= $w) {            return $text;        }        while (mb_strlen($text) > 3 && $c->measure($text . '…', $size) > $w) {            $text = mb_substr($text, 0, -1);        }        return rtrim($text) . '…';    }    /** The slot's preview as a texture (made again when the slot's picture changed), null: none. */    private function texture(string $key, array $m): mixed    {        $stamp = (string) ($m['preview'] ?? '');        $name = 'rv-save-' . $key;        if ($stamp === '') {            return null;        }        if (($this->tex[$key] ?? null) !== $stamp) {            $path = $this->store->previewPath($key);            $this->tex[$key] = $stamp;            $this->sdl->releaseTexture($name);            if ($path !== null) {                try {                    $this->sdl->loadTexture($name, $path);                } catch (\Throwable) {                    return null;                }            }        }        return $this->sdl->hasTexture($name) ? $this->sdl->getTexture($name)['texture'] : null;    }    public function dispose(): void    {        foreach (array_keys($this->tex) as $key) {            $this->sdl->releaseTexture('rv-save-' . $key);        }        $this->tex = [];    }    private function drawAsk(Canvas $c): void    {        $a = $this->ask;        $name = (string) ($this->store->metaOf($a['key'])['name'] ?? '');        if ($a['key'] === SaveStore::AUTO) {            $name = SaveStore::AUTO_NAME;        }        [$q, $sub] = match ($a['kind']) {            'overwrite' => ['Écraser « ' . $name . ' » ?', 'La partie en cours la remplace. L\'ancienne est perdue.'],            'delete' => ['Supprimer « ' . $name . ' » ?', 'Elle sera effacée pour de bon.'],            default => ['Quitter la partie en cours sans sauvegarder ?', 'Ce que tu as fait depuis la dernière sauvegarde sera perdu.'],        };        $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, 120]);        $w = $this->touch ? 760.0 : 560.0;        $lines = $c->wrap($q, 20, $w - 48);        $h = 128 + count($lines) * 28;        $x = 480 - $w / 2;        $y = 360 - $h / 2;        $c->panel($x, $y, $w, $h, 240, $a['kind'] === 'overwrite' ? [255, 196, 90] : [255, 130, 110]);        foreach ($lines as $i => $line) {            $c->text($line, 480, $y + 20 + $i * 28, 20, [255, 255, 255], 'center');        }        $c->text($sub, 480, $y + 26 + count($lines) * 28, 13, [176, 190, 204], 'center');        $bw = $this->touch ? 200.0 : 140.0;        $bh = $this->touch ? 46.0 : 34.0;        $by = $y + $h - $bh - 16;        foreach ([['Oui', 'sv:yes', true, 480 - $bw - 10], ['Non', 'sv:no', false, 480 + 10]] as [$label, $id, $yes, $bx]) {            $focus = $a['yes'] === $yes;            $c->pill($bx, $by, $bw, $bh, $focus ? ($yes ? [255, 160, 120, 220] : [150, 210, 255, 220]) : [255, 255, 255, 30]);            $c->text($label, $bx + $bw / 2, $by + ($bh - 18) / 2 - 1, 18, $focus ? [12, 18, 26] : [230, 236, 242], 'center', !$focus);            $c->hit($bx, $by, $bw, $bh, $id);        }    }    private function drawEdit(Canvas $c): void    {        $e = $this->edit;        $phone = $this->touch;        $c->rect(0, 0, Canvas::W, Canvas::H, [0, 0, 0, 140]);        // phones: up top (their own keyboard covers the bottom half)        $u = $phone ? 60.0 : 54.0;        $kh = $phone ? 46.0 : 40.0;        $w = min(920.0, 10 * $u + 9 * $u * 0.12 + 48);        $h = 128 + count(self::KEYS) * ($kh + 6);        $x = 480 - $w / 2;        $y = $phone ? 24.0 : 360 - $h / 2;        $c->panel($x, $y, $w, $h, 245, [150, 210, 255]);        $c->text('Nom de la sauvegarde', 480, $y + 14, 20, [255, 255, 255], 'center');        $fx = $x + 24;        $fw = $w - 48;        $c->rect($fx, $y + 48, $fw, 40, [0, 0, 0, 150]);        $c->border($fx, $y + 48, $fw, 40, [150, 210, 255, 160]);        $shown = $this->fit($c, $e['text'], 20, $fw - 30);        $tw = $c->text($shown === '…' ? '' : $shown, $fx + 12, $y + 57, 20, [255, 255, 255]);        if (fmod($this->clock, 1.0) < 0.6) {            $c->rect($fx + 14 + ($e['text'] === '' ? 0 : $tw), $y + 55, 2, 26, [150, 210, 255, 230]);        }        $c->text(mb_strlen($e['text']) . ' / ' . SaveStore::NAME_MAX, $fx + $fw - 8, $y + 92, 11, [150, 160, 170], 'right');        $flat = self::flatKeys();        $ky = $y + 110;        foreach ($flat as $k => [$label, $value, $row, $i]) {            $kw = (self::WIDE[$label] ?? 1.0) * $u;            $kx = 480 + self::keyX($row, $i) * $u - $kw / 2;            $yy = $ky + $row * ($kh + 6);            $on = $k === $e['key_sel'];            $caps = $value === '#caps' && $e['caps'];            $col = $on ? [150, 210, 255, 220] : ($value === '#ok' ? [130, 220, 150, 90] : ($caps ? [255, 214, 120, 120] : [255, 255, 255, 30]));            $c->pill($kx, $yy, $kw, $kh, $col);            $text = $e['caps'] && mb_strlen($label) === 1 ? mb_strtoupper($label) : $label;            $c->text($text, $kx + $kw / 2, $yy + ($kh - 17) / 2 - 1, 17, $on ? [12, 18, 26] : [236, 240, 244], 'center', !$on);            $c->hit($kx, $yy, $kw, $kh, 'sv:key:' . $k);        }        if (!$phone) {            $c->text('Tape le nom au clavier, ou choisis les lettres (flèches, Entrée / A). Entrée : valider, Échap : annuler.', 480, $y + $h - 22, 11, [160, 176, 190], 'center');        }    }}