KO
apps/winzik / src / Gui / PlaylistWindow.php · commit 6576d6f
<?phpnamespace App\Gui;use App\Model\Playlist;use App\Model\Text;use JumPHP\Gui\Pointer;/** * The play list (Form2 of 2001): mainpl.bmp, 23 lines of 13 pixels, an icon for the lyrics (lyrok / lyrno) and one for * the kind of file (infomp3 / infowav / infomid / infocd), the line playing in the skin's colour, its own scroll bar * (posplay.gif + btnplay.gif). Buttons: + (add files), - (remove the line), Mode édition, L (load a .FLS), * S (save a .FLS), and the bin (remove the lines chosen in the edit mode). */final class PlaylistWindow extends SkinWindow{    public const WIDTH = 258;    public const HEIGHT = 362;    public const ROWS = 23;    public const ROW_HEIGHT = 13;    /** the first line's top (malist(1).Top = 13 + List1.Top - 13 + 2 + 13 * 0) */    public const LIST_TOP = 50;    private const TRACK_TOP = 48;    private const TRACK_HEIGHT = 296;    private const THUMB = 17;    public const MIN_ROWS = 6;    public const MIN_WIDTH = 200;    public const MAX_WIDTH = 900;    public const MAX_ROWS = 70;    /** the bottom of mainpl.bmp drawn as it is (below the list), the middle stretched */    private const FOOT = 26;    /** @var array<int, bool> the lines chosen in the edit mode (only the chosen ones: count() is how many) */    public array $selection = [];    /** the line of the keyboard (a line of what is shown: the songs, the search's, the folders), -1 none */    public int $cursor = -1;    /** the line under the pointer (-1 none) */    private int $hoverRow = -1;    private float $hoverX = -1;    private float $shiftClock = 0;    private float $thumbGrab = 0;    /** drag and drop of a line: where it was taken, whether it moved (then it is not a click) */    private int $dragFrom = -1;    private bool $dragMoved = false;    /** the phone: a finger on the lines scrolls them (from the first line shown when it went down) */    private bool $fingerScroll = false;    private int $fingerTop = 0;    private float $pressY = 0;    /** the right edge while the left dot is dragged (the list grows to the left) */    private float $rightEdge = 0;    public function id(): string    {        return 'playlist';    }    public function width(): float    {        return (float)max(self::MIN_WIDTH, min(self::MAX_WIDTH, (int)($this->wz->ui['playlist']['width'] ?? self::WIDTH)));    }    public function height(): float    {        return self::HEIGHT + ($this->rows() - self::ROWS) * self::ROW_HEIGHT;    }    /** how many lines show: 23 in 2001, the corner dots make it longer or shorter */    public function rows(): int    {        return max(self::MIN_ROWS, min(self::MAX_ROWS, (int)($this->wz->ui['playlist']['rows'] ?? self::ROWS)));    }    private function trackHeight(): float    {        return self::TRACK_HEIGHT + ($this->rows() - self::ROWS) * self::ROW_HEIGHT;    }    public function visible(): bool    {        $ui = $this->wz->ui;        return $ui['playlist']['visible'] && !$ui['compact']['active'] && !$ui['lyricsOnly'] && !$ui['tray'];    }    public function editing(): bool    {        return (bool)$this->wz->ui['playlist']['edit'];    }    public function top(): int    {        $max = max(0, $this->lineCount() - $this->rows());        return max(0, min($max, (int)$this->wz->ui['playlist']['top']));    }    public function setTop(int $top): void    {        $this->wz->ui['playlist']['top'] = max(0, min(max(0, $this->lineCount() - $this->rows()), $top));    }    public function controls(): array    {        $h = $this->height();        $w = $this->width();        return [            // the two dots of the bottom corners: drag them to make the list longer / shorter, wider / narrower            'gripL' => [0, $h - 12, 16, 12],            // the mini buttons of the foot: what the lines say (their tag, or their whole path)            'showTags' => [19, $h - 11, 25, 9],            'showPaths' => [45, $h - 11, 33, 9],            'showGroups' => [79, $h - 11, 41, 9],            'showPrefs' => [121, $h - 11, 41, 9],            'search' => [163, $h - 11, 12, 9],            // the target: back to the song playing (follow)            'locate' => [176, $h - 11, 12, 9],            // the count of the foot: a click shows the song playing            'status' => [190, $h - 11, max(1, $w - 19 - 190), 9],            'gripR' => [$w - 16, $h - 12, 16, 12],            'add' => [0, 0, 25, 17],                        // Image3 plp.gif: + (Form3, the files)            'remove' => [$w - 26, 0, 25, 17],               // Image2 plm.gif: -            'edit' => [round(($w - 82) / 2), 0, 82, 16],    // Image7 pledit.gif: Mode édition / Mode playlist            'load' => [0, 16, 25, 17],                      // Image6 plload.gif            'save' => [$w - 26, 16, 25, 17],                // Image5 plsave.gif            'delete' => [round(($w - 18) / 2), 16, 25, 17], // Image4 plrem.gif            'scroll' => [$w - 10, self::TRACK_TOP, 10, $this->trackHeight()],            'list' => [0, self::LIST_TOP, $w - 10, $this->rows() * self::ROW_HEIGHT],        ];    }    public function render(Canvas $c): void    {        $wz = $this->wz;        $h = $this->height();        $w = $this->width();        $controls = $this->controls();        $size = $c->imageSize('mainpl');        if ($size === null) {            $c->fill(0, 0, $w, $h, '#404040');        } else {            // mainpl.bmp in nine: its corners as they are, its middle stretched to the length and the width of the list            [$iw, $ih] = $size;            $top = $ih - self::FOOT;            $mid = $h - self::FOOT;            if ($mid <= $top) {                $this->row9($c, $iw, 0, $mid, 0, $mid, $w);            } else {                $this->row9($c, $iw, 0, $top, 0, $top, $w);                $this->row9($c, $iw, $top - 40, 40, $top, $mid - $top, $w);            }            if ($w > $iw && $top > self::HEAD) {                $this->header($c, $iw, $w);     // its title ("LISTE DE LECTURE") at its size, centred: never stretched            }            $this->row9($c, $iw, $ih - self::FOOT, self::FOOT, $mid, self::FOOT, $w);        }        $c->image('plp', 0, 0);        $c->image('plm', $controls['remove'][0], 0);        $c->image($this->editing() ? 'pledit2' : 'pledit', $controls['edit'][0], 0);        $c->image('plload', 0, 16);        $c->image('plsave', $controls['save'][0], 16);        $c->image('plrem', $controls['delete'][0], 16);        foreach (['add', 'remove', 'edit', 'load', 'save', 'delete'] as $id) {            $this->pushed($c, $id);        }        $list = $wz->playlist;        $top = $this->top();        $shift = max(0, (int)$wz->ui['playlist']['shift']);        if ($this->grouped()) {            $this->renderTree($c, $w);        }        for ($row = 0; $row < ($this->grouped() ? 0 : $this->rows()); $row++) {            $index = $this->indexAt($top + $row);            $file = $list->items[$index] ?? null;            if ($index < 0 || $file === null) {                break;            }            $y = self::LIST_TOP + $row * self::ROW_HEIGHT;            // a line chosen (or carried): a veil lighter (darker on a light list) than the list, its text in a colour that reads on it            $veil = 0;            if (!empty($this->selection[$index])) {                $veil = 50;                $c->fill(0, $y, $w - 10, self::ROW_HEIGHT, self::veil($wz->skin, $veil));            } elseif ($index === $this->dragFrom && $this->dragMoved) {                $veil = 70;                $c->fill(0, $y, $w - 10, self::ROW_HEIGHT, self::veil($wz->skin, $veil));       // the line being carried                $c->fill(0, $y, $w - 10, 1, $wz->skin->colors['active']);            } elseif ($row === $this->hoverRow && !$this->editing()) {                $c->fill(44, $y, $w - 54, self::ROW_HEIGHT, [255, 255, 255, 18]);            }            $this->lyricsDot($c, $file, 0, $y + 2);            $c->image('info' . Playlist::kind($file), 24, $y + 2);            $color = $index === $list->active ? $wz->skin->colors['active'] : $wz->skin->lineColor($row);            if ($veil > 0) {                $color = self::inkOnVeil($wz->skin, $color, $veil);            }            $text = $this->label($index, $file);            $text = $shift > 0 ? mb_substr($text, $shift) : $text;            $length = $this->length($file);            // --- cloud: a cloud before a song of the cloud playlist, its percentage while this PC sends it            $mark = $this->wz->cloud()?->fileState($file);            $tx = 48;            if ($mark !== null && $mark['cloud']) {                self::cloudIcon($c, 48, $y + 3.5, $color);                $tx = 60;            }            if ($mark !== null && $mark['sending'] !== null) {                $length = (int)floor($mark['sending'] * 100) . ' %' . ($length !== '' ? '  ' . $length : '');            }            // --- end cloud            $lw = $length === '' ? 0 : $c->textWidth($length, 8) + 6;            $sx = $w - 13 - $lw - self::STARS_W - 2;            $this->starsAt[$row] = $sx;            $c->text($c->fit($text, $w - 10 - $tx - $lw - self::STARS_W - 4, 8.5), $tx, $y + 1.5, 8.5, $color);            $this->stars($c, $sx, $y + 3, $wz->stats()->rating($wz->path($file)), $row === $this->hoverRow && !$this->editing());            if ($length !== '') {                $c->text($length, $w - 13, $y + 2, 8, $color, 'right');      // the length, at the right            }        }        $this->renderCursor($c, $w, $top);        $this->renderEmpty($c, $w);        // the scroll bar        $c->image('posplay', $w - 8, self::TRACK_TOP, null, $this->trackHeight());        $c->image('btnplay', $w - 8, $this->thumbY());        $paths = (bool)($wz->ui['playlist']['paths'] ?? false);        foreach ([['showTags', 'TAGS', !$paths], ['showPaths', 'CHEMIN', $paths], ['showGroups', 'DOSSIERS', $this->grouped()], ['showPrefs', 'PRÉFÉRÉS', $wz->byPreference()]] as [$id, $label, $on]) {            [$bx, $by, $bw, $bh] = $controls[$id];            // solid and dark under light letters: readable on every skin (Givre's bottom is ice)            $c->fill($bx, $by, $bw, $bh, $on ? '#2a3c68' : '#0c1222');            $c->frame($bx, $by, $bw, $bh, $on ? '#ffffff' : '#56607a');            $c->text($label, $bx + $bw / 2, $by + 1.2, 6.2, $on ? '#ffffff' : '#b8c2d8', 'center');        }        // the magnifier: the search        [$bx, $by, $bw, $bh] = $controls['search'];        $c->fill($bx, $by, $bw, $bh, $this->searching ? '#2a3c68' : '#0c1222');        $c->frame($bx, $by, $bw, $bh, $this->searching ? '#ffffff' : '#56607a');        $c->frame($bx + 2.5, $by + 1.5, 5, 5, '#ffffff');        $c->fill($bx + 7, $by + 6, 1.5, 1.5, '#ffffff');        $c->fill($bx + 8, $by + 7, 1.5, 1.5, '#ffffff');        $this->renderLocate($c, $controls['locate']);        $status = $this->editing() ? count($this->selection) . ' ligne(s) choisie(s)' : $list->count() . ' fichier(s)' . ($list->shuffle ? ' - Hasard' : '');        if ($wz->cloud()?->view() === 'cloud') {            $status = 'CLOUD ' . $status;      // cloud: the cloud playlist is shown        }        if ($wz->playsLyricsOnly() && !$this->editing()) {            // lyrics: only the songs with lyrics play (how many have some, of how many)            $status = ($wz->cloud()?->view() === 'cloud' ? 'CLOUD ' : '') . 'PAROLES ' . $wz->songsWithLyrics() . '/' . $list->count();        }        // after the mini buttons, before the right dot; on a dark band (the skins' bottoms are light there)        if ($this->filter !== '') {            $status = count($this->found()) . ' trouvé(s)';        }        $room = $w - 19 - ($controls['locate'][0] + $controls['locate'][2] + 3);        if ($c->textWidth($status, 7) > $room) {            $status = $c->fit((string)preg_replace('/ - Hasard$/', '', $status), $room, 7);        }        $tw = $c->textWidth($status, 7);        $c->fill($w - 18 - $tw - 3, $h - 11, $tw + 5, 9, '#0c1222');        $c->text($status, $w - 18, $h - 10.8, 7, $this->editing() ? '#ffff80' : '#e0e6f4', 'right');        // the search: the letters typed, over the title band ("LISTE DE LECTURE")        if ($this->searching) {            $text = 'Chercher : ' . $this->filter . (fmod($this->desk->clock, 1.0) < 0.55 ? '_' : ' ');            $c->fill(6, self::LIST_TOP - 16, $w - 12, 13, '#0c1222');            $c->frame(6, self::LIST_TOP - 16, $w - 12, 13, '#ffffff');            $c->text($c->fit($text, $w - 20, 8), 10, self::LIST_TOP - 14.5, 8, '#ffffff');        }    }    public function grouped(): bool    {        return (bool)($this->wz->ui['playlist']['grouped'] ?? false) && $this->filter === '';    }    /** How many lines the list has: its songs (those of the search), or (by folders) the artists, albums and songs open. */    public function lineCount(): int    {        if ($this->grouped()) {            return count($this->tree());        }        return $this->filter !== '' ? count($this->found()) : $this->wz->playlist->count();    }    // the search (the magnifier): a few letters typed, only the songs that have them -------------------------------    /** the search is open (the letters typed go to it) */    public bool $searching = false;    /** the letters typed */    public string $filter = '';    private string $foundKey = '';    /** @var list<int> the songs of the search (indexes in the play list) */    private array $foundLines = [];    /** @return list<int> the songs whose title, artist or file name has the letters typed (no accents, no case) */    public function found(): array    {        $generation = $this->generation();        $info = $this->infoSeen();        $key = $generation . '|' . $info;        $filter = $this->filter;        if ($key === $this->foundKey && $filter === $this->foundFilter) {            return $this->foundLines;        }        $want = \App\Media\YouTube::normalize($filter);        // one more letter typed: only the songs found with the letters before can still match        $narrower = $key === $this->foundKey && $this->foundWant !== '' && str_contains($want, $this->foundWant);        $from = $narrower ? $this->foundLines : array_keys($this->wz->playlist->items);        $this->foundKey = $key;        $this->foundFilter = $filter;        $this->foundWant = $want;        $items = $this->wz->playlist->items;        $lines = [];        foreach ($from as $i) {            if ($want === '' || str_contains($this->hay($items[$i]), $want)) {                $lines[] = $i;            }        }        return $this->foundLines = $lines;    }    // what the drawing and the search need, kept between frames and made again only when the list changed -------------    /** @var list<string> the songs when last looked at: while nothing changes it is the same array (compared in O(1)) */    private array $seenItems = [];    /** grows each time the songs of the list (or their order) change */    private int $generation = 0;    /** the tags known when last looked at (WinZik::$infoVersion), taken at most twice a second while they pour in */    private int $infoSeen = -1;    private float $infoAt = -1.0;    private string $foundFilter = '';    private string $foundWant = '';    /** @var array<string, array{0: \App\Model\Id3Tag, 1: string}> per file: its tag and the letters searched in */    private array $hays = [];    private string $longestKey = '';    private int $longest = 0;    /** The list's generation: a new one when its songs changed (no hash, no copy: PHP compares the same array at once). */    private function generation(): int    {        $items = $this->wz->playlist->items;        if ($items !== $this->seenItems) {            $this->generation++;        }        $this->seenItems = $items;        return $this->generation;    }    /** The tags known: a helper process sends them one by one; the list, the folders and the search follow every 0.5 s. */    private function infoSeen(): int    {        $version = $this->wz->infoVersion;        if ($version !== $this->infoSeen && ($this->infoSeen < 0 || abs($this->desk->clock - $this->infoAt) >= 0.5)) {            $this->infoSeen = $version;            $this->infoAt = $this->desk->clock;        }        return $this->infoSeen;    }    /** The letters a song is searched by (its artist, title, album and file name, no accents, no case), kept per tag. */    private function hay(string $file): string    {        [$tag] = $this->wz->describeLater($file);        $known = $this->hays[$file] ?? null;        if ($known !== null && ($known[0] === $tag || ($tag->artist === '' && $tag->title === '' && $tag->album === ''            && $known[0]->artist === '' && $known[0]->title === '' && $known[0]->album === ''))) {            return $known[1];        }        if (count($this->hays) > 2 * count($this->wz->playlist->items) + 1000) {            $this->hays = [];      // songs gone long ago        }        $hay = \App\Media\YouTube::normalize($tag->artist . ' ' . $tag->title . ' ' . $tag->album . ' ' . Text::baseName($file));        $this->hays[$file] = [$tag, $hay];        return $hay;    }    /** The longest text of a line (letters): how far the long lines may shift to the left. */    private function longest(): int    {        $key = $this->generation() . '|' . $this->infoSeen() . '|' . (int)($this->wz->ui['playlist']['paths'] ?? false);        if ($key !== $this->longestKey) {            $this->longestKey = $key;            $this->longest = 0;            foreach ($this->wz->playlist->items as $i => $file) {                $this->longest = max($this->longest, mb_strlen($this->label($i, $file)));            }        }        return $this->longest;    }    /** The song of a line of the list (the search: only its songs), -1: none. */    public function indexAt(int $line): int    {        if ($this->filter !== '') {            return $this->found()[$line] ?? -1;        }        return $line >= 0 && $line < $this->wz->playlist->count() ? $line : -1;    }    /** The magnifier: the search opened (or closed, its letters gone). */    public function toggleSearch(): void    {        $this->searching = !$this->searching;        $this->filter = '';        $this->cursor = -1;        $this->setTop(0);    }    /** A key while the search is open. @return bool it was for it */    public function searchKey(?int $key, string $text): bool    {        if (!$this->searching) {            return false;        }        if ($key === Pointer::ESCAPE) {            $this->toggleSearch();        } elseif ($key === Pointer::BACKSPACE) {            $this->filter = mb_substr($this->filter, 0, -1);        } elseif ($key === Pointer::RETURN || $key === Pointer::KP_ENTER) {            // Return: the song of the keyboard's line plays (the arrows go through the songs found), else the first one            $index = $this->indexAt($this->cursor >= 0 ? $this->cursor : 0);            if ($index >= 0) {                $this->wz->playIndex($index);            }            return true;        } elseif ($text !== '') {            $this->filter .= $text;        } else {            return false;        }        $this->cursor = -1;        $this->setTop(0);        return true;    }    /**     * The list by folders: artist > album > songs, each folder open or closed (ui.playlist.open).     * @return list<array{kind: string, key: string, label: string, index: int, count: int, open: bool}>     */    public function tree(): array    {        // made again only when something changed (the list, a tag that came back, a folder opened): not each frame        $open = (array)($this->wz->ui['playlist']['open'] ?? []);        $key = $this->generation() . '|' . $this->infoSeen() . '|' . json_encode($open);        if ($key === $this->treeKey) {            return $this->treeLines;        }        $this->treeKey = $key;        return $this->treeLines = $this->buildTree($open);    }    private string $treeKey = '';    /** @var list<array{kind: string, key: string, label: string, index: int, count: int, open: bool}> */    private array $treeLines = [];    /**     * @param array<string, mixed> $open     * @return list<array{kind: string, key: string, label: string, index: int, count: int, open: bool}>     */    private function buildTree(array $open): array    {        $groups = [];        foreach ($this->wz->playlist->items as $index => $file) {            [$tag] = $this->wz->describeLater($file);            $name = Text::baseName(Text::withoutExtension($file));            $artist = $tag->artist;            $title = $tag->title;            if ($artist === '' && str_contains($name, ' - ')) {                [$artist, $title] = array_map('trim', explode(' - ', $name, 2));            }            $artist = $artist !== '' ? $artist : '(Artiste inconnu)';            $album = $tag->album !== '' ? $tag->album : '(Sans album)';            $groups[$artist][$album][] = [$index, $title !== '' ? $title : $name];        }        ksort($groups, SORT_NATURAL | SORT_FLAG_CASE);        $lines = [];        foreach ($groups as $artist => $albums) {            $key = 'a:' . $artist;            $isOpen = !empty($open[$key]);            $lines[] = ['kind' => 'artist', 'key' => $key, 'label' => $artist, 'index' => -1, 'count' => array_sum(array_map('count', $albums)), 'open' => $isOpen];            if (!$isOpen) {                continue;            }            ksort($albums, SORT_NATURAL | SORT_FLAG_CASE);            foreach ($albums as $album => $songs) {                $akey = 'b:' . $artist . '|' . $album;                $aOpen = !empty($open[$akey]) || count($albums) === 1;                if (count($albums) > 1) {                    $lines[] = ['kind' => 'album', 'key' => $akey, 'label' => $album, 'index' => -1, 'count' => count($songs), 'open' => $aOpen];                }                if ($aOpen) {                    foreach ($songs as [$index, $title]) {                        $lines[] = ['kind' => 'song', 'key' => '', 'label' => $title, 'index' => $index, 'count' => 0, 'open' => false];                    }                }            }        }        return $lines;    }    /** By folders: the line drawn at a row (its folder, or its song). */    private function renderTree(Canvas $c, float $w): void    {        $wz = $this->wz;        $tree = $this->tree();        $top = $this->top();        for ($row = 0; $row < $this->rows(); $row++) {            $line = $tree[$top + $row] ?? null;            if ($line === null) {                break;            }            $y = self::LIST_TOP + $row * self::ROW_HEIGHT;            if ($row === $this->hoverRow) {                $c->fill(0, $y, $w - 10, self::ROW_HEIGHT, [255, 255, 255, 18]);            }            if ($line['kind'] === 'song') {                $file = $wz->playlist->items[$line['index']];                // its lyrics or not, at a glance (as in the plain list), then its kind                $this->lyricsDot($c, $file, 8, $y + 2);                $c->image('info' . Playlist::kind($file), 32, $y + 2);                $color = $line['index'] === $wz->playlist->active ? $wz->skin->colors['active'] : $wz->skin->lineColor($row);                $length = $this->length($file);                $lw = $length === '' ? 0 : $c->textWidth($length, 8) + 6;                $sx = $w - 13 - $lw - self::STARS_W - 2;                $this->starsAt[$row] = $sx;                $c->text($c->fit($line['label'], $w - 70 - $lw - self::STARS_W - 4, 8.5), 56, $y + 1.5, 8.5, $color);                $this->stars($c, $sx, $y + 3, $wz->stats()->rating($wz->path($file)), $row === $this->hoverRow);                if ($length !== '') {                    $c->text($length, $w - 13, $y + 2, 8, $color, 'right');                }                continue;            }            $indent = $line['kind'] === 'album' ? 14 : 2;            $color = $line['kind'] === 'artist' ? $wz->skin->colors['title'] : $wz->skin->colors['volume'];            // the arrow, drawn (the fonts have no ▶ ▼): down when open, right when closed            for ($i = 0; $i < 4; $i++) {                if ($line['open']) {                    $c->fill($indent + 3 + $i, $y + 4 + $i, 7 - 2 * $i, 1, $color);                } else {                    $c->fill($indent + 4 + $i, $y + 2 + $i, 1, 7 - 2 * $i, $color);                }            }            $c->text($c->fit($line['label'] . '  (' . $line['count'] . ')', $w - 40 - $indent, 8.5), $indent + 14, $y + 1.5, 8.5, $color);        }    }    /** One band of mainpl.bmp across the width: its left and right as they are, its middle stretched. */    /** the five stars of a line (drawn: the fonts have no ★), 6 pixels each */    public const STARS_W = 30;    /** @var array<int, float> where the stars of each row start (the clicks on them give the stars) */    private array $starsAt = [];    /** the contrast asked of the text of a line chosen (WCAG AA, normal text) */    public const MIN_CONTRAST = 4.5;    /** The veil over a line chosen: white on a dark list, black on a light one. @return array{0: int, 1: int, 2: int, 3: int} */    public static function veil(\App\Model\Skin $skin, int $alpha): array    {        $v = self::luminance(self::rgb($skin->palette()['list'])) > 0.4 ? 0 : 255;        return [$v, $v, $v, $alpha];    }    /** What a line chosen looks like under its veil (the list's colour where the skin draws it). @return array{0: int, 1: int, 2: int} */    public static function veiled(\App\Model\Skin $skin, int $alpha): array    {        $bg = self::rgb($skin->palette()['list']);        [$v] = self::veil($skin, $alpha);        return array_map(fn (int $c): int => (int)round($c + ($v - $c) * $alpha / 255), $bg);    }    /**     * The colour of the text of a line chosen: its own (the skin's line or "active" colour) when it reads on the veil     * (contrast of 4.5 or more), else white or black, the one that reads best.     */    public static function inkOnVeil(\App\Model\Skin $skin, string $color, int $alpha): string    {        static $cache = [];        $bg = self::veiled($skin, $alpha);        $key = implode(',', $bg) . $color;        if (isset($cache[$key])) {            return $cache[$key];        }        if (self::contrast(self::rgb($color), $bg) >= self::MIN_CONTRAST) {            return $cache[$key] = $color;        }        return $cache[$key] = self::contrast([255, 255, 255], $bg) >= self::contrast([0, 0, 0], $bg) ? '#ffffff' : '#000000';    }    /** WCAG's contrast ratio of two colours (1..21). @param array{0: int, 1: int, 2: int} $a @param array{0: int, 1: int, 2: int} $b */    public static function contrast(array $a, array $b): float    {        [$hi, $lo] = [max(self::luminance($a), self::luminance($b)), min(self::luminance($a), self::luminance($b))];        return ($hi + 0.05) / ($lo + 0.05);    }    /** @param array{0: int, 1: int, 2: int} $c */    private static function luminance(array $c): float    {        $lin = fn (int $v): float => ($x = $v / 255) <= 0.03928 ? $x / 12.92 : (($x + 0.055) / 1.055) ** 2.4;        return 0.2126 * $lin($c[0]) + 0.7152 * $lin($c[1]) + 0.0722 * $lin($c[2]);    }    /** '#rrggbb' -> [r, g, b] @return array{0: int, 1: int, 2: int} */    private static function rgb(string $hex): array    {        $hex = ltrim($hex, '#');        return [(int)hexdec(substr($hex, 0, 2)), (int)hexdec(substr($hex, 2, 2)), (int)hexdec(substr($hex, 4, 2))];    }    /** Its stars: lit up to its mark; the empty ones shown only while the pointer is on the line (to give some). */    private function stars(Canvas $c, float $x, float $y, int $rating, bool $hovered): void    {        if ($rating === 0 && !$hovered) {            return;        }        for ($k = 0; $k < 5; $k++) {            $lit = $k < $rating;            if (!$lit && !$hovered) {                continue;            }            $color = $lit ? '#ffd040' : [255, 255, 255, 70];            $sx = $x + $k * 6;            $c->fill($sx + 2, $y, 1, 1, $color);          // a star of 5 x 5            $c->fill($sx + 1, $y + 1, 3, 1, $color);            $c->fill($sx, $y + 2, 5, 1, $color);            $c->fill($sx + 1, $y + 3, 3, 1, $color);            $c->fill($sx, $y + 4, 2, 1, $color);            $c->fill($sx + 3, $y + 4, 2, 1, $color);        }    }    /** A click on the stars of a row: that many stars given. @return bool it was on them */    private function starClick(int $row, float $x, string $file): bool    {        $sx = $this->starsAt[$row] ?? null;        if ($sx === null || $x < $sx - 1 || $x >= $sx + self::STARS_W) {            return false;        }        $this->wz->rate($file, max(1, min(5, (int)floor(($x - $sx) / 6) + 1)));        return true;    }    /** the head of mainpl.bmp (its buttons, its lines, its title band) */    private const HEAD = 48;    /**     * The head of a list wider than its picture: its two sides and its middle (the title) as they are, the middle centred;     * the room between them filled with the picture next to the middle, repeated (its lines go on, no letter stretched).     */    private function header(Canvas $c, float $iw, float $w): void    {        $c0 = floor($iw / 2) - 75;        $cw = 150.0;        $tile = 20.0;        $at = floor(($w - $cw) / 2);        // left: the picture up to the middle, then its 20 columns before the middle, again and again        $c->image('mainpl', 0, 0, $c0, self::HEAD, [0, 0, $c0, self::HEAD]);        for ($x = $c0; $x < $at; $x += $tile) {            $c->image('mainpl', $x, 0, min($tile, $at - $x), self::HEAD, [$c0 - $tile, 0, min($tile, $at - $x), self::HEAD]);        }        $c->image('mainpl', $at, 0, $cw, self::HEAD, [$c0, 0, $cw, self::HEAD]);        // right: the 20 columns after the middle, again and again, then the picture's right side        $rightW = $iw - ($c0 + $cw);        $end = $w - $rightW;        for ($x = $at + $cw; $x < $end; $x += $tile) {            $c->image('mainpl', $x, 0, min($tile, $end - $x), self::HEAD, [$c0 + $cw, 0, min($tile, $end - $x), self::HEAD]);        }        $c->image('mainpl', $end, 0, $rightW, self::HEAD, [$c0 + $cw, 0, $rightW, self::HEAD]);    }    private function row9(Canvas $c, float $iw, float $sy, float $sh, float $dy, float $dh, float $w): void    {        $side = min(100.0, floor($w / 2), floor($iw / 2) - 10);        $c->image('mainpl', 0, $dy, $side, $dh, [0, $sy, $side, $sh]);        $c->image('mainpl', $side, $dy, $w - 2 * $side, $dh, [$side, $sy, $iw - 2 * $side, $sh]);        $c->image('mainpl', $w - $side, $dy, $side, $dh, [$iw - $side, $sy, $side, $sh]);    }    /** The text of a line: the path, as in 2001 (the file name alone when the path is the application's). */    /** The text of a line: "Artiste - Titre" of its tag (else its name), or its whole path (the mini button CHEMIN). */    private function label(int $index, string $file): string    {        $number = ($index + 1) . '. ';        // --- cloud: a song of the cloud not on this device: its title and where its copy is        $cloud = \App\Cloud\Cloud::isPseudo($file) ? $this->wz->cloud() : null;        if ($cloud !== null) {            $id = (string)\App\Cloud\Cloud::idOfPseudo($file);            $e = $cloud->playlist->entry($id) ?? [];            $what = ($e['artist'] ?? '') !== '' ? $e['artist'] . ' - ' . ($e['title'] ?? '') : (string)($e['title'] ?? '?');            return $number . $what . '  [' . $cloud->rowState($id)['text'] . ']';        }        // --- end cloud        if ($this->wz->ui['playlist']['paths'] ?? false) {            return $number . (str_starts_with($file, 'assets/') ? Text::baseName($file) : $file);        }        [$tag] = $this->wz->describeLater($file);        $name = Text::baseName(Text::withoutExtension($file));        $what = $tag->artist !== '' && $tag->title !== '' && !str_contains($tag->title, $tag->artist)            ? $tag->artist . ' - ' . $tag->title            : ($tag->title !== '' ? $tag->title : $name);        return $number . $what;    }    /** The cloud of the lines of the cloud playlist: 10 x 6 pixels of the line's colour. */    public static function cloudIcon(Canvas $c, float $x, float $y, string|array $color): void    {        foreach ([[3, 0, 3], [2, 1, 6], [1, 2, 8], [0, 3, 10], [0, 4, 10], [1, 5, 8]] as [$dx, $dy, $w]) {            $c->fill($x + $dx, $y + $dy, $w, 1, $color);        }    }    /** "3:42" of a line, '' when its length is not known. */    private function length(string $file): string    {        // --- cloud: a song not here yet: the length the cloud gives        $e = \App\Cloud\Cloud::isPseudo($file) ? $this->wz->cloud()?->entryOfItem($file) : null;        if ($e !== null) {            $s = (int)round((float)($e['duration'] ?? 0));            return $s <= 0 ? '' : sprintf('%d:%02d', intdiv($s, 60), $s % 60);        }        // --- end cloud        [, $info] = $this->wz->describeLater($file);        $s = (int)round($info->duration);        return $s <= 0 ? '' : ($s >= 3600 ? sprintf('%d:%02d:%02d', intdiv($s, 3600), intdiv($s % 3600, 60), $s % 60) : sprintf('%d:%02d', intdiv($s, 60), $s % 60));    }    private function thumbY(): float    {        $over = $this->lineCount() - $this->rows();        if ($over <= 0) {            return self::TRACK_TOP - 1;        }        // unprc = (Image1.Height - Image8.Height) / (ListCount - 23)        return self::TRACK_TOP - 1 + ($this->trackHeight() - self::THUMB) * $this->top() / $over;    }    public function rowAt(float $y): int    {        if ($y < self::LIST_TOP || $y >= self::LIST_TOP + $this->rows() * self::ROW_HEIGHT) {            return -1;        }        return (int)floor(($y - self::LIST_TOP) / self::ROW_HEIGHT);    }    public function press(float $x, float $y, Pointer $p): bool    {        if (!parent::press($x, $y, $p)) {            return false;        }        $this->fingerScroll = false;        if ($this->pressed === 'scroll') {            $thumb = $this->thumbY();            $this->thumbGrab = $y >= $thumb && $y < $thumb + self::THUMB ? $y - $thumb : self::THUMB / 2;            $this->drag($x, $y);        }        if ($this->pressed === 'list' && $this->rowAt($y) >= 0 && $this->top() + $this->rowAt($y) >= $this->lineCount()) {            $this->pressed = '';            return false;    // the empty bottom of the list: the window moves        }        if ($this->pressed === 'list' && $this->rowAt($y) >= 0) {            $this->cursor = $this->top() + $this->rowAt($y);     // the keyboard goes on from the line clicked        }        if ($this->pressed === 'list' && !$this->editing() && $this->desk->phone) {            // a finger: slid up or down, the list scrolls with it (a tap plays the line, a long press opens the menu)            $this->dragFrom = -1;            $this->dragMoved = false;            $this->pressY = $y;            $this->fingerTop = $this->top();            $this->fingerScroll = true;        } elseif ($this->pressed === 'list' && !$this->editing() && !$this->grouped() && $this->filter === '') {            // a line taken: dragged up or down, it moves in the list (drag and drop)            $this->dragFrom = $this->top() + $this->rowAt($y);            $this->dragMoved = false;            $this->pressY = $y;        }        if ($this->pressed === 'list' && $this->editing() && !$this->grouped()) {            $line = $this->top() + $this->rowAt($y);            $index = $this->indexAt($line);            if ($index >= 0) {                $shift = $p->shift || (function_exists('SDL_GetModState') && (\SDL_GetModState() & 0x0003) !== 0);                if ($shift && $this->anchor >= 0) {                    // Shift + click: every line shown from the last one clicked to this one                    foreach (range(min($this->anchor, $line), max($this->anchor, $line)) as $l) {                        if (($i = $this->indexAt($l)) >= 0) {                            $this->choose($i, true);                        }                    }                    $this->selectMode = null;                } else {                    // a click chooses the line (or not); held and dragged, the lines gone over the same way                    $this->selectMode = empty($this->selection[$index]);                    $this->choose($index, $this->selectMode);                    $this->anchor = $line;                    $this->selectFrom = $this->top() + $this->rowAt($y);                }            }        }        if ($this->pressed === 'gripL') {            $this->rightEdge = $this->x + $this->width();        }        return true;    }    public function drag(float $x, float $y): void    {        if ($this->pressed === 'gripL' || $this->pressed === 'gripR') {            $rows = self::ROWS + (int)round(($y + 6 - self::HEIGHT) / self::ROW_HEIGHT);            $this->wz->ui['playlist']['rows'] = max(self::MIN_ROWS, min(self::MAX_ROWS, $rows));            if ($this->pressed === 'gripR') {                // the right edge sticks to the player's (the same width), the other windows', the screen's                $right = ($this->wz->options['snap'] ?? true) ? $this->desk->magnetEdge($this, $this->x + $x + 8, $this->y) : $this->x + $x + 8;                $width = $right - $this->x;            } else {                // the left dot: the left edge follows it (and sticks), the right one stays                $left = ($this->wz->options['snap'] ?? true) ? $this->desk->magnetEdge($this, $this->x + $x - 8, $this->y) : $this->x + $x - 8;                $width = $this->rightEdge - $left;            }            $width = max(self::MIN_WIDTH, min(self::MAX_WIDTH, (int)round($width)));            $this->wz->ui['playlist']['width'] = $width;            if ($this->pressed === 'gripL') {                $this->x = $this->rightEdge - $width;                $main = $this->desk->main;                if ($main !== null && $this->wz->ui['playlist']['attached']) {                    // docked: the player follows the left edge (they never part; only the menu undocks them)                    $main->x = $this->x;                    $main->remember();                }                $this->remember();            }            $this->setTop($this->top());            $this->wz->touch();            return;        }        if ($this->pressed === 'list' && $this->fingerScroll) {            if (!$this->dragMoved && abs($y - $this->pressY) < 4) {                return;            }            $this->dragMoved = true;            $this->byHand();            $this->setTop($this->fingerTop + (int)round(($this->pressY - $y) / self::ROW_HEIGHT));            return;        }        if ($this->pressed === 'list' && $this->editing() && $this->selectMode !== null) {            $this->dragY = $y;            $this->selectTo($y);            return;        }        if ($this->pressed === 'list' && $this->dragFrom >= 0) {            if (!$this->dragMoved && abs($y - $this->pressY) < 4) {                return;            }            $this->dragMoved = true;            // near the top or the bottom, the list scrolls            if ($y < self::LIST_TOP + 4) {                $this->setTop($this->top() - 1);            } elseif ($y > self::LIST_TOP + $this->rows() * self::ROW_HEIGHT - 4) {                $this->setTop($this->top() + 1);            }            $row = max(0, min($this->rows() - 1, (int)floor(($y - self::LIST_TOP) / self::ROW_HEIGHT)));            $to = max(0, min($this->wz->playlist->count() - 1, $this->top() + $row));            if ($to !== $this->dragFrom) {                $this->wz->moveLine($this->dragFrom, $to);                $this->dragFrom = $to;                $this->cursor = $to;            }            return;        }        if ($this->pressed === 'scroll') {            $over = $this->lineCount() - $this->rows();            if ($over > 0) {                $this->byHand();                $at = ($y - $this->thumbGrab - self::TRACK_TOP) / ($this->trackHeight() - self::THUMB);                $this->setTop((int)round($at * $over));            }        }    }    /** edit mode: the line of the last click (Shift + click: from it), choosing or not while dragged (null: not dragging) */    private int $anchor = -1;    private ?bool $selectMode = null;    private int $selectFrom = -1;    private float $dragY = -1;    private float $scrollClock = 0.0;    /** Edit mode, the pointer held at $y: the lines from the one pressed to this one chosen (or not). */    private function selectTo(float $y): void    {        $row = max(0, min($this->rows() - 1, (int)floor(($y - self::LIST_TOP) / self::ROW_HEIGHT)));        $to = $this->top() + $row;        foreach (range(min($this->selectFrom, $to), max($this->selectFrom, $to)) as $line) {            $index = $this->indexAt($line);            if ($index >= 0) {                $this->choose($index, (bool)$this->selectMode);            }        }    }    public function release(float $x, float $y, bool $double): void    {        if ($this->pressed === 'list' && $this->editing() && !$this->grouped()) {            // edit mode: chosen when pressed (and while dragged); a double click plays the line (its two presses            // chose it and let it go again: the lines chosen stay as they were)            $this->pressed = '';            $this->selectMode = null;            $this->dragY = -1;            $index = $this->rowAt($y) >= 0 ? $this->indexAt($this->top() + $this->rowAt($y)) : -1;            if ($double && $index >= 0 && $x < $this->width() - 10) {                $this->wz->playIndex($index);            }            return;        }        if (in_array($this->pressed, ['scroll', 'gripL', 'gripR'], true)) {            $this->pressed = '';            return;        }        if ($this->pressed === 'list') {            $this->pressed = '';            $this->fingerScroll = false;            $moved = $this->dragMoved;            $this->dragFrom = -1;            $this->dragMoved = false;            if ($moved) {                return;     // a line moved, not a click            }            $row = $this->rowAt($y);            if ($this->grouped()) {                // by folders: a folder opens / closes, a song plays                $line = $this->tree()[$this->top() + $row] ?? null;                if ($row < 0 || $line === null) {                    return;                }                if ($line['kind'] === 'song') {                    if ($this->starClick($row, $x, $this->wz->playlist->items[$line['index']])) {                        return;                    }                    if ($x >= 6 && $x < 8 + self::DOT_W) {                        $this->desk->lyricsSearch($this->wz->playlist->items[$line['index']]);      // lyrics: its dot                        return;                    }                    $this->wz->playIndex($line['index']);                } else {                    $this->wz->ui['playlist']['open'][$line['key']] = !$line['open'];                    $this->wz->touch();                }                return;            }            $index = $this->indexAt($this->top() + $row);            if ($row < 0 || $index < 0 || $x >= $this->width() - 10) {                return;            }            $file = $this->wz->playlist->items[$index];            if (!$this->editing() && $x < self::DOT_W) {                $this->desk->lyricsSearch($file);      // lyrics: the dot of the line, help to find its lyrics                return;            }            if (!$this->editing() && Playlist::isVideo($file) && $x >= 22 && $x < 44) {                // its VID badge: the video player opens (the film plays if it was not the one playing)                $this->wz->ui['video']['visible'] = true;                if ($index !== $this->wz->playlist->active || $this->wz->player->state !== 'playing') {                    $this->wz->playIndex($index);                }                $this->wz->touch();                return;            }            if (!$this->editing() && $this->starClick($row, $x, $file)) {                return;     // its stars            }            if ($this->editing()) {                $this->choose($index, empty($this->selection[$index]));            } else {                // malist_MouseUp: the line clicked plays                $this->wz->playIndex($index);            }            return;        }        parent::release($x, $y, $double);    }    protected function clicked(string $id, bool $double): void    {        $wz = $this->wz;        switch ($id) {            case 'search':                $this->toggleSearch();                break;            case 'status':            case 'locate':                $this->revealActive();                break;            case 'showPrefs':                // par préférence: sorted by the stars, then how much it is listened to; again: the order before                $wz->togglePreferenceOrder();                break;            case 'showGroups':                $wz->ui['playlist']['grouped'] = !$this->grouped();                $wz->ui['playlist']['top'] = 0;                $wz->touch();                break;            case 'showTags':            case 'showPaths':                $wz->ui['playlist']['paths'] = $id === 'showPaths';                $wz->ui['playlist']['shift'] = 0;                $wz->touch();                break;            case 'add':                $this->desk->openLoad($this->x + 4, $this->y + 18);     // the installed WinZik: the system's window                break;            case 'remove':                $chosen = array_keys($this->selection);                $wz->removeLines($chosen !== [] ? $chosen : ($wz->playlist->active >= 0 ? [$wz->playlist->active] : []));                $this->selection = [];                break;            case 'edit':                $wz->ui['playlist']['edit'] = !$this->editing();                $this->selection = [];                $wz->touch();                break;            case 'delete':                if ($this->editing()) {                    $wz->removeLines(array_keys($this->selection));                    $this->selection = [];                }                break;            case 'load':                $this->desk->host()->openFls(false);                break;            case 'save':                $this->desk->host()->openFls(true);                break;        }    }    public function dragsItself(string $control): bool    {        return in_array($control, ['scroll', 'gripL', 'gripR'], true) || $control === 'list';     // edit mode: the drag chooses lines    }    public function hover(float $x, float $y): void    {        $this->hoverRow = $this->rowAt($y);        $this->hoverX = $this->hoverRow >= 0 ? $x : -1;        // the card of the line: after 2 s still on it; it goes when the pointer moves        if ($x !== $this->stillX || $y !== $this->stillY) {            [$this->stillX, $this->stillY] = [$x, $y];            $this->still = 0.0;            $this->desk->card?->hide();        }    }    private float $stillX = -1;    private float $stillY = -1;    private float $still = 0.0;    public function wheel(float $notches): bool    {        $this->byHand();        $this->setTop($this->top() - (int)round($notches * 3));        return true;    }    /** Timer2 of Form2: the pointer near the right edge of the list moves the long paths to the left, near the left edge back. */    public function update(float $dt): void    {        $this->still += $dt;        $this->followLater();        // choosing lines past the top or the bottom of the list: it scrolls, the lines come chosen        if ($this->selectMode !== null && $this->dragY >= 0) {            $this->scrollClock += $dt;            $bottom = self::LIST_TOP + $this->rows() * self::ROW_HEIGHT;            if ($this->scrollClock > 0.05 && ($this->dragY < self::LIST_TOP + 3 || $this->dragY > $bottom - 3)) {                $this->scrollClock = 0.0;                $this->setTop($this->top() + ($this->dragY < self::LIST_TOP + 3 ? -1 : 1));                $this->selectTo($this->dragY);            }        }        $card = $this->desk->card;        if ($card !== null && $card->index < 0 && $this->still >= 2.0 && $this->hoverRow >= 0 && $this->pressed === '' && !$this->editing()) {            $index = $this->indexAt($this->top() + $this->hoverRow);            if ($index >= 0 && isset($this->wz->playlist->items[$index])) {                $card->showAt($index, $this->x + $this->stillX, $this->y + $this->stillY);            }        }        $this->shiftClock += $dt;        if ($this->hoverX < 0 || $this->shiftClock < 0.06) {            return;        }        $this->shiftClock = 0;        $shift = (int)$this->wz->ui['playlist']['shift'];        if ($this->hoverX > $this->width() - 26) {            $shift = min($shift + 1, max(0, $this->longest() - 20));        } elseif ($this->hoverX < 40) {            $shift = max(0, $shift - 1);        }        $this->wz->ui['playlist']['shift'] = $shift;    }    // the keyboard --------------------------------------------------------------------------------------------------    /**     * The keys of the play list (given by the desktop while the list is under the pointer or was clicked last):     * arrows, Page préc. / suiv., Début / Fin move the line of the keyboard (Maj in the edit mode: the lines between are     * chosen; Ctrl + arrow: the song moves up or down), Entrée plays it (a folder opens), Suppr removes the chosen lines     * (else that line), Ctrl+A chooses every line, Ctrl+F the search, Ctrl+J shows the song playing, Échap lets the     * lines go, and a letter starts the search with it.     * @return bool the keys were for the list     */    public function keys(Pointer $p): bool    {        $used = false;        foreach ($p->keys as $key) {            $used = $this->key($key, $p->shift, $p->ctrl) || $used;        }        if (!$p->ctrl) {            foreach ($p->text as $char) {                if (!$this->searching && ($char === ' ' || $this->wz->playlist->count() === 0)) {                    continue;      // Space stays play / pause (a space of a search goes to it)                }                if (!$this->searching) {                    $this->toggleSearch();                }                $used = $this->searchKey(null, $char) || $used;            }        }        return $used;    }    /** One key (see keys()). @return bool it was for the list */    public function key(int $key, bool $shift = false, bool $ctrl = false): bool    {        if ($ctrl && ($key === ord('a') || $key === ord('A'))) {            $this->selectAll();            return true;        }        if ($ctrl && ($key === ord('f') || $key === ord('F'))) {            $this->toggleSearch();            return true;        }        if ($ctrl && ($key === ord('j') || $key === ord('J'))) {            $this->revealActive();            return true;        }        $page = max(1, $this->rows() - 1);        // no line of the keyboard yet: the first arrow puts it on the song playing (or the first line shown)        $step = $this->cursor >= 0 && $this->cursor < $this->lineCount() ? 1 : 0;        $to = match ($key) {            Pointer::UP => $this->cursorLine() - $step,            Pointer::DOWN => $this->cursorLine() + $step,            Pointer::PAGEUP => $this->cursorLine() - $page * $step,            Pointer::PAGEDOWN => $this->cursorLine() + $page * $step,            Pointer::HOME => 0,            Pointer::END => $this->lineCount() - 1,            default => null,        };        if ($to !== null) {            if ($this->lineCount() === 0) {                return true;            }            $to = max(0, min($this->lineCount() - 1, $to));            if ($ctrl && ($key === Pointer::UP || $key === Pointer::DOWN) && $this->cursor >= 0 && $this->movable()) {                $this->wz->moveLine($this->cursor, $to);     // Ctrl + arrow: the song itself goes up or down            } elseif ($shift && $this->editing() && !$this->grouped()) {                $from = $this->cursor >= 0 ? $this->cursor : $to;                foreach (range(min($from, $to), max($from, $to)) as $line) {                    $index = $this->indexAt($line);                    if ($index >= 0) {                        $this->choose($index, true);                    }                }            }            $this->cursor = $to;            $this->byHand();            $this->showLine($to);            return true;        }        switch ($key) {            case Pointer::RETURN:            case Pointer::KP_ENTER:                return $this->openLine($this->cursorLine());            case Pointer::DELETE:                return $this->deleteKey();            case Pointer::ESCAPE:                if ($this->selection !== []) {                    $this->selection = [];                    return true;                }                return false;        }        return false;    }    /** The line of the keyboard: where it is, else the song playing (if shown), else the first line shown. */    private function cursorLine(): int    {        if ($this->cursor >= 0 && $this->cursor < $this->lineCount()) {            return $this->cursor;        }        $active = $this->wz->playlist->active;        if ($active >= 0 && !$this->grouped()) {            $line = $this->filter !== '' ? array_search($active, $this->found(), true) : $active;            if (is_int($line)) {                return $line;            }        }        return min($this->top(), max(0, $this->lineCount() - 1));    }    /** The line of the list scrolled into view (at the edge it went past). */    private function showLine(int $line): void    {        if ($line < $this->top()) {            $this->setTop($line);        } elseif ($line >= $this->top() + $this->rows()) {            $this->setTop($line - $this->rows() + 1);        }    }    /** Entrée on a line: its song plays; by folders a folder opens or closes. @return bool there was a line */    private function openLine(int $line): bool    {        if ($this->grouped()) {            $node = $this->tree()[$line] ?? null;            if ($node === null) {                return false;            }            if ($node['kind'] === 'song') {                $this->wz->playIndex($node['index']);            } else {                $this->wz->ui['playlist']['open'][$node['key']] = !$node['open'];                $this->wz->touch();            }            return true;        }        $index = $this->indexAt($line);        if ($index < 0) {            return false;        }        $this->cursor = $line;        $this->wz->playIndex($index);        return true;    }    /** Suppr: the lines chosen go, else the line of the keyboard; the keyboard stays at the same place. */    private function deleteKey(): bool    {        if ($this->selection !== []) {            $this->wz->removeLines(array_keys($this->selection));            $this->selection = [];        } elseif (!$this->grouped() && ($index = $this->indexAt($this->cursorLine())) >= 0) {            $this->wz->removeLines([$index]);        } else {            return false;        }        $this->cursor = $this->lineCount() === 0 ? -1 : min($this->cursorLine(), $this->lineCount() - 1);        $this->setTop($this->top());        return true;    }    /** The songs can be moved one by one (the plain list: not by folders, not the search's). */    private function movable(): bool    {        return !$this->grouped() && $this->filter === '';    }    /** A line chosen or not (only the chosen ones are kept). */    private function choose(int $index, bool $on): void    {        if ($on) {            $this->selection[$index] = true;        } else {            unset($this->selection[$index]);        }    }    /** Ctrl+A: the edit mode, every line shown chosen (the search's only, when searching). */    public function selectAll(): void    {        $this->wz->ui['playlist']['edit'] = true;        $indexes = $this->filter !== '' ? $this->found() : array_keys($this->wz->playlist->items);        $this->selection = $indexes === [] ? [] : array_fill_keys($indexes, true);        $this->wz->touch();    }    public function chosenCount(): int    {        return count($this->selection);    }    /** Ctrl+J or a click on the count of the foot: the song playing shown in the middle of the list, the keyboard on it. */    public function revealActive(): void    {        $active = $this->wz->playlist->active;        if ($active < 0) {            return;        }        if ($this->filter !== '' && !in_array($active, $this->found(), true)) {            $this->toggleSearch();      // not among the songs found: the whole list again        }        if ($this->grouped()) {            $this->wz->ui['playlist']['grouped'] = false;            $this->wz->touch();        }        $line = $this->filter !== '' ? (int)array_search($active, $this->found(), true) : $active;        $this->cursor = $line;        $this->setTop($line - intdiv($this->rows(), 2));        $this->handAt = -100.0;      // the button: the list follows the songs again at once        $this->followPending = false;    }    /** The line of the keyboard: a dotted frame around it. */    private function renderCursor(Canvas $c, float $w, int $top): void    {        $row = $this->cursor - $top;        if ($this->cursor < 0 || $row < 0 || $row >= $this->rows() || $this->cursor >= $this->lineCount()) {            return;        }        $y = self::LIST_TOP + $row * self::ROW_HEIGHT;        $color = [255, 255, 255, 150];        for ($x = 1; $x < $w - 12; $x += 4) {            $c->fill($x, $y, 2, 1, $color);            $c->fill($x, $y + self::ROW_HEIGHT - 1, 2, 1, $color);        }        for ($yy = $y; $yy < $y + self::ROW_HEIGHT; $yy += 4) {            $c->fill(0, $yy, 1, 2, $color);            $c->fill($w - 11, $yy, 1, 2, $color);        }    }    /** What to do when there is nothing to show: an empty list, or a search that found nothing. */    private function renderEmpty(Canvas $c, float $w): void    {        if ($this->wz->playlist->count() === 0) {            $lines = ['Liste vide', 'Cliquer sur + pour ajouter des fichiers', 'ou un dossier entier', 'L : charger une liste .FLS'];        } elseif ($this->filter !== '' && $this->found() === []) {            $lines = ['Aucun morceau ne contient', '« ' . $this->filter . ' »', 'Retour arrière : effacer une lettre', 'Échap : toute la liste'];        } else {            return;        }        $mid = self::LIST_TOP + $this->rows() * self::ROW_HEIGHT / 2 - count($lines) * 6;        foreach ($lines as $k => $line) {            $size = $k === 0 ? 9.0 : 7.5;            $c->text($c->fit($line, $w - 24, $size), ($w - 10) / 2, $mid + $k * 12, $size, $k === 0 ? '#e0e6f4' : '#a0a8bc', 'center');        }    }    // --- follow: the list follows the song playing (unless scrolled by hand a moment ago); the target of the foot -------    /** seconds after a scroll by hand before the list follows the songs again */    public const FOLLOW_AFTER = 8.0;    /** the desktop's clock when the list was last scrolled by hand (wheel, bar, finger, keyboard) */    private float $handAt = -100.0;    /** a song changed while the list was scrolled by hand: shown once the hand has left it long enough */    private bool $followPending = false;    /** The list scrolled by hand: it does not follow the songs for FOLLOW_AFTER seconds. */    public function byHand(): void    {        $this->handAt = $this->desk->clock;    }    /** The list was scrolled by hand a moment ago (it does not follow now). */    public function heldByHand(): bool    {        return $this->desk->clock - $this->handAt < self::FOLLOW_AFTER;    }    /** The line of the list where a song is shown (the search's, the folders open), -1: not shown. */    public function lineOf(int $index): int    {        if ($index < 0 || !isset($this->wz->playlist->items[$index])) {            return -1;        }        if ($this->grouped()) {            foreach ($this->tree() as $line => $node) {                if ($node['kind'] === 'song' && $node['index'] === $index) {                    return $line;                }            }            return -1;        }        if ($this->filter !== '') {            $line = array_search($index, $this->found(), true);            return is_int($line) ? $line : -1;        }        return $index;    }    /**     * A song changed (next, previous, end, Hasard, a click): its line shown, in the middle, when it is out of view     * (Form2.List1.ListIndex = actif). Not shown by the search or a closed folder: nothing moves. Scrolled by hand a moment     * ago: the list stays, and shows it once left alone FOLLOW_AFTER seconds.     */    public function reveal(int $index): void    {        $line = $this->lineOf($index);        if ($line < 0) {            $this->followPending = false;            return;        }        if ($this->heldByHand()) {            $this->followPending = true;            return;        }        $this->followPending = false;        $rows = $this->rows();        if ($line < $this->top() || $line >= $this->top() + $rows) {            $this->setTop($line - intdiv($rows, 2));        }    }    /** Each frame: a song that changed while the list was held is shown once the hand has left it. */    private function followLater(): void    {        if ($this->followPending && !$this->heldByHand()) {            $this->reveal($this->wz->playlist->active);        }    }    /** The target of the foot (« Aller au morceau en cours »): a ring, a dot and four ticks, on the dark band of the foot. */    private function renderLocate(Canvas $c, array $at): void    {        [$bx, $by, $bw, $bh] = $at;        $lost = $this->wz->playlist->active >= 0 && !$this->activeInView();        $c->fill($bx, $by, $bw, $bh, $lost ? '#2a3c68' : '#0c1222');        $c->frame($bx, $by, $bw, $bh, $lost ? '#ffffff' : '#56607a');        [$cx, $cy] = [$bx + $bw / 2, $by + $bh / 2];        $c->disc($cx, $cy, 2.6, '#ffffff');        $c->disc($cx, $cy, 1.7, $lost ? '#2a3c68' : '#0c1222');        $c->disc($cx, $cy, 0.8, '#ffffff');        $c->fill($cx - 0.5, $by + 0.8, 1, 1, '#ffffff');        $c->fill($cx - 0.5, $by + $bh - 1.8, 1, 1, '#ffffff');        $c->fill($bx + 1.8, $cy - 0.5, 1, 1, '#ffffff');        $c->fill($bx + $bw - 2.8, $cy - 0.5, 1, 1, '#ffffff');    }    /** The song playing is on a line shown now. */    public function activeInView(): bool    {        $line = $this->lineOf($this->wz->playlist->active);        return $line >= $this->top() && $line < $this->top() + $this->rows();    }    public function tip(string $control): string    {        if ($control === 'list' && !$this->editing() && $this->hoverRow >= 0 && $this->hoverX >= 0) {            // lyrics: the dot of a line says what lyrics the song has, and that a click helps to find them            $file = $this->fileOfRow($this->hoverRow);            if ($file !== null && $this->hoverX < ($this->grouped() ? 8 : 0) + self::DOT_W) {                return self::MARKS[$this->lyricsMark($file)] . ' : cliquer pour chercher les paroles';            }        }        return $control === 'locate' ? 'Aller au morceau en cours' : parent::tip($control);    }    // --- lyrics: the dot of each line (none / synced / without times / translated), a click helps to find them ---    /** how wide the dot of a line is (lyrok / lyrno: 17, and the mark after it) */    public const DOT_W = 22;    /** what each mark says */    public const MARKS = ['none' => 'Pas de paroles', 'synced' => 'Paroles synchronisées', 'plain' => 'Paroles non synchronisées',        'translated' => 'Paroles traduites'];    /** @var array<string, array{0: string, 1: float, 2: string}> file => [mark, when it was read, the .LYR's path + mtime] */    private array $marks = [];    /** The song of a row shown (plain list or folders), null when the row is no song. */    private function fileOfRow(int $row): ?string    {        if ($this->grouped()) {            $line = $this->tree()[$this->top() + $row] ?? null;            return $line !== null && $line['kind'] === 'song' ? ($this->wz->playlist->items[$line['index']] ?? null) : null;        }        $index = $this->indexAt($this->top() + $row);        return $index >= 0 ? ($this->wz->playlist->items[$index] ?? null) : null;    }    /** none | synced | plain (lines without times) | translated: read from the song's .LYR, looked at again every few seconds. */    public function lyricsMark(string $file): string    {        $wz = $this->wz;        if (!$wz->hasLyrics($file)) {            unset($this->marks[$file]);            return 'none';        }        $now = $this->desk->clock;        $known = $this->marks[$file] ?? null;        if ($known !== null && $now - $known[1] < 3.0 && $now >= $known[1]) {            return $known[0];        }        $found = \App\Cloud\Cloud::isPseudo($file) ? null : $wz->findLyricsFile($file);        $key = $found === null ? '' : $found . '@' . (int)@filemtime($found);        if ($known !== null && $known[2] === $key) {            $this->marks[$file] = [$known[0], $now, $key];            return $known[0];        }        $lyrics = $found === null ? null : \App\Model\Lyrics::load($found);        $mark = match (true) {            $lyrics === null => 'synced',      // a song of the cloud: the account has its lyrics            $lyrics->translations !== [] => 'translated',            !$lyrics->synced => 'plain',            default => 'synced',        };        $this->marks[$file] = [$mark, $now, $key];        return $mark;    }    /**     * The dot of the skin (lyrok / lyrno) and, after it, a small mark: two lines = lyrics without times, a blue dot =     * translated (on a dark square: readable on every skin).     */    private function lyricsDot(Canvas $c, string $file, float $x, float $y): void    {        $mark = $this->lyricsMark($file);        $c->image($mark === 'none' ? 'lyrno' : 'lyrok', $x, $y);        if ($mark === 'plain') {            $c->fill($x + 17.5, $y + 1, 5, 7, '#0c1222');            $c->fill($x + 18.5, $y + 2.5, 3, 1.2, '#ffd040');            $c->fill($x + 18.5, $y + 5, 3, 1.2, '#ffd040');        } elseif ($mark === 'translated') {            $c->fill($x + 17.5, $y + 1, 5, 7, '#0c1222');            $c->disc($x + 20, $y + 4.5, 1.8, '#5a8cff');        }    }    // --- end lyrics    // --- end follow}