TR
apps/winzik / src / Mobile / MediaPages.php · commit 6576d6f
<?phpnamespace App\Mobile;use App\Audio\Player;use App\Model\Id3Tag;use App\Model\Lyrics;use App\Model\Skin;use App\Model\SkinPack;use App\Model\Text;use JumPHP\Native\Shell;/** * The other pages of MobileView: the film (on the Lecteur instead of the cover, on the whole screen with a tap, turned a * quarter when it is wide), the tag (TagForm: title, artist, album, year, genre, comment, the marks of the start and the * end, the stars and the listens), the marketplace (lyrics and skins), the Options of the computer that mean something on * a phone, the skins (for the interface of 2001), the play lists (.FLS), and the updates of the Android app. */trait MediaPages{    /** seconds the controls of the film stay over it */    public float $videoUi = 0.0;    private string $frameFile = '';    /** @var array{0: mixed, 1: int, 2: int}|null the texture of the picture shown, its size */    private ?array $frameTexture = null;    /** the line of the tag page */    public int $tagLine = -1;    public int $tagGenre = Id3Tag::OTHER;    public string $tagError = '';    /** @var array{0: string, 1: string} the marks when the page opened */    private array $tagMarks = ['', ''];    public string $marketKind = 'lyrics';    /** @var list<array<string, mixed>> */    public array $marketEntries = [];    public int $marketLoading = 0;    public string $marketStatus = '';    /** seconds left to confirm the reset of the options (0: not asked) */    private float $resetAsked = 0.0;    /**     * Where the updates of the Android app come from: WinZik itself (androidUpdate(): null or [version, notes, size, state     * available | downloading | opened | error, progress, error], installAndroidUpdate(), checkUpdates()) or, in the tests,     * a fake with these methods.     */    public ?object $updates = null;    // the film ------------------------------------------------------------------------------------------------------    private function enterVideo(): void    {        $this->videoUi = 3.0;    }    private function updateVideo(float $dt): void    {        $this->videoUi = max(0.0, $this->videoUi - $dt);        $this->resetAsked = max(0.0, $this->resetAsked - $dt);    }    /** @return array{0: mixed, 1: int, 2: int}|null the picture of the film now as a texture */    private function videoTexture(): ?array    {        $file = $this->wz?->videoFrame();        $sdl = $this->form?->sdlOrNull();        if ($file === null || $sdl === null) {            return null;        }        if ($file !== $this->frameFile || $this->frameTexture === null) {            try {                if ($sdl->hasTexture('mobile-video-frame')) {                    $sdl->releaseTexture('mobile-video-frame');                }                $sdl->loadTexture('mobile-video-frame', $file);                $t = $sdl->getTexture('mobile-video-frame');                $this->frameTexture = [$t['texture'], (int)$t['width'], (int)$t['height']];                $this->frameFile = $file;            } catch (\Throwable) {                return $this->frameTexture;            }        }        return $this->frameTexture;    }    /** The film in a box of the Lecteur (letterboxed, black around). */    private function renderVideoBox(float $x, float $y, float $w, float $h, float $radius): void    {        $this->box($x, $y, $w, $h, '#000000', $radius);        $tex = $this->videoTexture();        if ($tex !== null && $tex[1] > 0 && $tex[2] > 0) {            $k = min(($w - 8) / $tex[1], ($h - 8) / $tex[2]);            $dw = $tex[1] * $k;            $dh = $tex[2] * $k;            $this->r->copy($tex[0], null, $this->ox + ($x + ($w - $dw) / 2) * $this->s, $this->oy + ($y + ($h - $dh) / 2) * $this->s, $dw * $this->s, $dh * $this->s);            $this->circle($x + $w - 30, $y + 30, 20, [0, 0, 0, 140]);            $this->icon('fullscreen', $x + $w - 41, $y + 19, 22, '#ffffff');            return;        }        $wait = $this->wz->waitVideo !== '';        if ($wait) {            $this->spinner($x + $w / 2, $y + $h / 2 - 16, 14, '#ffffff');        } else {            $this->icon('film', $x + $w / 2 - 24, $y + $h / 2 - 40, 48, [255, 255, 255, 200]);        }        $this->text($wait ? 'Préparation de la vidéo…' : 'Vidéo', $x + $w / 2, $y + $h / 2 + 22, 15, [255, 255, 255, 220], false, 'center');    }    /** The film on the whole screen: a wide film turned a quarter (the phone held sideways), the controls on a tap. */    private function renderVideo(): void    {        $wz = $this->wz;        $W = $this->W;        $H = $this->H;        $this->rect(0, 0, $W, $H, '#000000');        $this->hit(0, 0, $W, $H, 'videoTap');        $tex = $this->videoTexture();        $turn = (bool)($wz->ui['mobile']['rotate'] ?? true);        if ($tex !== null && $tex[1] > 0 && $tex[2] > 0) {            [$t, $tw, $th] = $tex;            $rotate = $turn && $tw > $th;            $k = $rotate ? min($H / $tw, $W / $th) : min($W / $tw, $H / $th);            $dw = $tw * $k;            $dh = $th * $k;            // SDL turns the picture around the middle of its box            $this->r->copy($t, null, $this->ox + ($W - $dw) / 2 * $this->s, $this->oy + ($H - $dh) / 2 * $this->s, $dw * $this->s, $dh * $this->s, false, false, $rotate ? 90.0 : 0.0);        } else {            $wait = $wz->waitVideo !== '';            $wait ? $this->spinner($W / 2, $H / 2 - 20, 16, '#ffffff') : $this->icon('film', $W / 2 - 28, $H / 2 - 50, 56, [255, 255, 255, 160]);            $this->text($wait ? 'Préparation de la vidéo…' : ($wz->playingVideo() ? 'Pas encore d\'image' : 'Ce morceau n\'est pas une vidéo'), $W / 2, $H / 2 + 24, 16, '#ffffff', false, 'center');        }        if ($this->videoUi <= 0 && $wz->player->state === Player::PLAYING && $this->seekAt === null) {            return;        }        // the controls, over the picture        $this->shade(0, 96, 170, 0);        $this->roundButton(8, 8, 48, 'back', 'addBack', null, '#ffffff');        $this->roundButton($W - 56, 8, 48, 'rotate', 'videoRotate', null, $turn ? '#ffffff' : [255, 255, 255, 120]);        [$title] = $this->titleOf($wz->playlist->active);        $this->text($title, 64, 32, 16, '#ffffff', true, 'left', $W - 128);        $this->shade($H - 170, 170, 0, 190);        $d = $wz->player->duration();        $pos = $this->seekAt !== null ? $this->seekAt * $d : $wz->player->position;        $ratio = $d > 0 ? max(0.0, min(1.0, $pos / $d)) : 0.0;        $y = $H - 110;        $this->box(28, $y - 2, $W - 56, 4, [255, 255, 255, 70], 2);        $this->box(28, $y - 2, max(4, ($W - 56) * $ratio), 4, $this->col('accent2'), 2);        $this->circle(28 + ($W - 56) * $ratio, $y, 8, '#ffffff');        $this->text(self::clock($pos), 28, $y + 20, 12, [255, 255, 255, 200]);        $this->text($d > 0 ? self::clock($d) : '--:--', $W - 28, $y + 20, 12, [255, 255, 255, 200], false, 'right');        $this->hit(14, $y - 22, $W - 28, 44, 'vseek');        $playing = $wz->player->state === Player::PLAYING;        $this->roundButton($W / 2 - 110, $H - 72, 56, 'prev', 'prev', null, '#ffffff', null, 30);        $this->circle($W / 2, $H - 44, 32, '#ffffff');        $this->icon($playing ? 'pause' : 'play', $W / 2 - 16, $H - 60, 32, '#000000');        $this->hit($W / 2 - 34, $H - 78, 68, 68, 'play');        $this->roundButton($W / 2 + 54, $H - 72, 56, 'next', 'next', null, '#ffffff', null, 30);    }    /** a black veil over the film that fades from one alpha to another (the controls stay readable) */    private function shade(float $y, float $h, int $from, int $to): void    {        $bands = 16;        for ($i = 0; $i < $bands; $i++) {            $this->rect(0, $y + $h * $i / $bands, $this->W, $h / $bands + 0.5, [0, 0, 0, (int)round($from + ($to - $from) * ($i + 0.5) / $bands)]);        }    }    // the tag -----------------------------------------------------------------------------------------------------    private function enterTag(): void    {        $wz = $this->wz;        $file = $wz?->playlist->items[$this->tagLine] ?? null;        if ($wz === null || $file === null) {            return;        }        $path = $wz->path($file);        $tag = $path === $wz->player->file ? $wz->tag : Id3Tag::read($path);        $this->fields['tagTitle'] = $tag->title;        $this->fields['tagArtist'] = $tag->artist;        $this->fields['tagAlbum'] = $tag->album;        $this->fields['tagYear'] = $tag->year;        $this->fields['tagComment'] = $tag->comment;        $this->tagGenre = $tag->present ? $tag->genre : Id3Tag::OTHER;        [$start, $end] = $wz->bounds($path);        $this->fields['tagStart'] = $start > 0 ? sprintf('%.2f', $start) : '';        $this->fields['tagEnd'] = $end > 0 ? sprintf('%.2f', $end) : '';        $this->tagMarks = [$this->fields['tagStart'], $this->fields['tagEnd']];        $this->tagError = '';    }    /** The tag written (MP3) and the marks kept: TagForm::onOkClick. */    public function tagSave(): bool    {        $wz = $this->wz;        $file = $wz?->playlist->items[$this->tagLine] ?? null;        if ($wz === null || $file === null) {            return false;        }        $path = $wz->path($file);        $year = trim($this->fields['tagYear'] ?? '');        if ($year !== '' && !preg_match('/^\d{4}$/', $year)) {            $this->tagError = "L'année doit faire 4 chiffres (ex : 2001) : corrigez-la ou laissez-la vide.";            return false;        }        $mark = fn (string $v) => trim($v) === '' ? 0.0 : (is_numeric($n = str_replace(',', '.', trim($v))) ? (float)$n : null);        $start = $mark($this->fields['tagStart'] ?? '');        $end = $mark($this->fields['tagEnd'] ?? '');        if ($start === null || $start < 0 || $end === null || $end < 0) {            $this->tagError = 'Début et fin : un nombre de secondes (ex : 12,5), ou vide.';            return false;        }        if ($end > 0 && $end <= $start) {            $this->tagError = 'La fin doit venir après le début : changez l\'une des deux, ou videz la fin.';            return false;        }        if (Text::extension($path) === 'mp3') {            $tag = new Id3Tag(trim($this->fields['tagTitle'] ?? ''), trim($this->fields['tagArtist'] ?? ''), trim($this->fields['tagAlbum'] ?? ''),                $year, trim($this->fields['tagComment'] ?? ''), $this->tagGenre);            if (!$tag->write($path)) {                $this->tagError = "Impossible d'écrire le tag dans ce fichier : il est peut-être en lecture seule. Vérifiez les autorisations de WinZik.";                return false;            }            if ($path === $wz->player->file) {                $wz->tag = $tag;            }            $wz->forget($file);        }        if ([$this->fields['tagStart'] ?? '', $this->fields['tagEnd'] ?? ''] !== $this->tagMarks) {            $wz->setBounds($path, $start, $end);        }        $this->tagError = '';        $wz->notice('Enregistré : ' . Text::baseName($path), 3);        return true;    }    private function renderTag(): void    {        $wz = $this->wz;        $file = $wz->playlist->items[$this->tagLine] ?? null;        if ($file === null) {            $this->renderPage('Tag', '', [['note', 'Ce morceau n\'est plus dans la playlist.']]);            return;        }        $path = $wz->path($file);        $mp3 = Text::extension($path) === 'mp3';        $current = $path === $wz->player->file;        $stats = $wz->stats();        $rows = [];        if ($this->tagError !== '') {            $rows[] = ['note', $this->tagError, $this->col('danger')];        }        if ($mp3) {            $rows[] = ['input', 'Titre', 'tagTitle', 'Le titre du morceau'];            $rows[] = ['input', 'Artiste', 'tagArtist', 'L\'artiste'];            $rows[] = ['input', 'Album', 'tagAlbum', 'L\'album'];            $rows[] = ['input', 'Année', 'tagYear', 'Ex : 2001'];            $rows[] = ['row2', 'tag', 'Genre', Id3Tag::GENRES[$this->tagGenre] ?? 'Other', 'goto', 'genre', 'chevron'];            $rows[] = ['input', 'Commentaire', 'tagComment', ''];        } else {            $rows[] = ['note', 'Pas de tag ID3 pour ce format (' . strtoupper(Text::extension($path)) . ') : seuls les repères se gardent.'];        }        $rows[] = ['section', 'Repères', 'en secondes'];        $rows[] = ['input', 'Début de la lecture', 'tagStart', 'Le début du morceau'];        $rows[] = ['input', 'Fin de la lecture', 'tagEnd', 'La fin du morceau'];        $marks = [];        if ($current) {            $marks[] = ['Début ici', 'tagHere', 'start', false];            $marks[] = ['Fin ici', 'tagHere', 'end', false];        }        $marks[] = ['Effacer', 'tagHere', 'clear', false];        $rows[] = ['pills', $marks];        $rows[] = ['section', 'Statistiques'];        $rows[] = ['stars', $this->tagLine, 'tagStar'];        $rows[] = ['field', 'Écoutes', (string)$stats->plays($path)];        $rows[] = ['field', 'Passés', (string)$stats->skips($path)];        $rows[] = ['field', 'Score', (string)$stats->score($path)];        $rows[] = ['field', 'Fichier', Text::baseName($path)];        $rows[] = ['pills', [['Enregistrer', 'tagSave', null, true, 'check']]];        [$title] = $this->titleOf($this->tagLine);        $this->renderPage('Tag', $title, $rows, [['check', 'tagSave']]);    }    private function renderGenre(): void    {        $rows = [];        foreach (Id3Tag::GENRES as $k => $name) {            $rows[] = ['row', $k === $this->tagGenre ? 'check' : 'note', $name, 'genrePick', $k, 'text', ''];        }        $this->renderPage('Genre', Id3Tag::GENRES[$this->tagGenre] ?? '', $rows);    }    // the marketplace --------------------------------------------------------------------------------------------    private function enterMarket(): void    {        $wz = $this->wz;        $this->fields['author'] = (string)($wz?->options['author'] ?? '');        $this->fields['mkQuery'] = $this->marketKind === 'lyrics' && ($wz?->tag->artist ?? '') !== '' ? trim($wz->tag->artist . ' ' . $wz->tag->title) : '';        $this->marketEntries = [];        $this->marketFind();    }    public function marketFind(): void    {        $market = $this->wz?->market();        $this->field = '';        if ($market === null || !$market->enabled()) {            $this->marketStatus = 'Pas de marketplace ici : pas de réseau. Vérifiez la connexion, puis rouvrez cette page.';            return;        }        $this->marketStatus = '';        $this->marketLoading++;        $kind = $this->marketKind;        $market->list($kind, trim($this->fields['mkQuery'] ?? ''))->then(function (mixed $items) use ($kind): void {            $this->marketLoading--;            if ($kind !== $this->marketKind) {                return;            }            $this->marketEntries = is_array($items) ? array_values($items) : [];            $this->marketStatus = count($this->marketEntries) . ' ' . ($kind === 'skin' ? 'skin(s)' : 'parole(s)') . ' sur jumphp.net';        }, function (\Throwable $e): void {            $this->marketLoading--;            $this->marketStatus = 'Marketplace injoignable (' . $e->getMessage() . ') : vérifiez la connexion, puis réessayez.';        });    }    /** An entry installed: lyrics for the song playing, a skin into var/skins and put on (MarketForm). */    public function marketInstall(int $index): void    {        $wz = $this->wz;        $e = $this->marketEntries[$index] ?? null;        $market = $wz?->market();        if ($wz === null || $e === null || $market === null) {            return;        }        $kind = $this->marketKind;        $this->marketStatus = 'Téléchargement de ' . $e['name'] . '...';        $this->marketLoading++;        $market->download($kind, (string)$e['id'])->then(function (mixed $bytes) use ($e, $kind, $wz): void {            $this->marketLoading--;            $bytes = (string)$bytes;            if ($kind === 'skin') {                $dir = $wz->storagePath('skins/' . (\App\Model\SkinDocument::cleanName((string)$e['name']) ?: 'skin-' . $e['id']));                try {                    $ok = SkinPack::install($bytes, $dir);                } catch (\Throwable) {                    $ok = false;                }                if (!$ok || !$wz->useSkin($dir)) {                    $this->marketStatus = "Ce fichier n'est pas un skin de WinZik : choisissez-en un autre.";                    return;                }                $wz->save();                $this->marketStatus = 'Skin « ' . $wz->skin->name . ' » installé : il habille l\'interface WinZik original.';                return;            }            $file = $wz->playlist->current();            if ($file === null || Lyrics::parse($bytes) === null) {                $this->marketStatus = $file === null ? "Lancez d'abord le morceau de ces paroles, puis touchez-les." : "Ce fichier n'est pas un .LYR : choisissez d'autres paroles.";                return;            }            $target = $wz->lyricsCachePath($file);            @mkdir(dirname($target), 0777, true);            file_put_contents($target, $bytes);            $wz->refreshLyrics();            $wz->loadLyrics($file);            $this->marketStatus = 'Paroles installées pour ' . Text::baseName($file);            $wz->notice('Paroles installées', 3);        }, function (\Throwable $ex): void {            $this->marketLoading--;            $this->marketStatus = 'Téléchargement impossible (' . $ex->getMessage() . ') : réessayez dans un instant.';        });    }    /** The lyrics of the song playing, or a skin of var/skins, sent to the marketplace. */    public function marketShare(string $what): void    {        $wz = $this->wz;        $market = $wz?->market();        if ($wz === null || $market === null || !$market->enabled()) {            return;        }        $author = mb_substr(trim($this->fields['author'] ?? ''), 0, 40);        $wz->options['author'] = $author;        if ($what === 'lyrics') {            if ($wz->lyrics === null || $wz->lyricsFile === '') {                return;            }            $meta = ['name' => Text::baseName(Text::withoutExtension($wz->lyricsFile)), 'artist' => $wz->tag->artist, 'title' => $wz->tag->title, 'author' => $author, 'ext' => 'lyr'];            $bytes = (string)file_get_contents($wz->lyricsFile);        } else {            $skin = new Skin($what);            $meta = ['name' => $skin->name, 'author' => $author, 'ext' => 'zip'];            $bytes = SkinPack::pack($what);        }        $this->marketStatus = 'Envoi de ' . $meta['name'] . '...';        $this->marketLoading++;        $market->upload($what === 'lyrics' ? 'lyrics' : 'skin', $meta, $bytes)->then(function (mixed $entry): void {            $this->marketLoading--;            $this->marketStatus = '« ' . (is_array($entry) ? $entry['name'] ?? '' : '') . ' » est partagé : tout le monde peut l\'installer.';        }, function (\Throwable $e): void {            $this->marketLoading--;            $this->marketStatus = 'Envoi impossible (' . $e->getMessage() . ') : réessayez dans un instant.';        });    }    private function renderMarket(): void    {        $wz = $this->wz;        $lyrics = $this->marketKind === 'lyrics';        $rows = [['chipset', [['Paroles', 'mkKind', 'lyrics', $lyrics], ['Skins', 'mkKind', 'skin', !$lyrics]]]];        $rows[] = ['input', $lyrics ? 'Chercher des paroles' : 'Chercher un skin', 'mkQuery', $lyrics ? 'Artiste, titre' : 'Nom du skin'];        $rows[] = ['pills', [['Chercher', 'mkFind', null, true, 'search']]];        if ($this->marketLoading > 0) {            $rows[] = ['busy', $this->marketStatus !== '' ? $this->marketStatus : 'Recherche en cours...'];        } elseif ($this->marketStatus !== '') {            $rows[] = ['note', $this->marketStatus];        }        if (!$lyrics) {            $rows[] = ['note', 'Les skins habillent l\'interface WinZik original (Options > Interface).'];        }        if ($this->marketEntries !== []) {            $rows[] = ['section', $lyrics ? 'Paroles partagées' : 'Skins partagés', (string)count($this->marketEntries)];            foreach ($this->marketEntries as $k => $e) {                $what = $lyrics && ($e['artist'] ?? '') !== '' ? $e['artist'] . ' - ' . $e['title'] : (string)($e['name'] ?? '');                $sub = (($e['author'] ?? '') !== '' ? 'par ' . $e['author'] . ' · ' : '') . (int)($e['downloads'] ?? 0) . ' téléchargement(s)';                $rows[] = ['row2', $lyrics ? 'lyrics' : 'palette', $what, $sub, 'mkInstall', $k, 'download'];            }        }        // what one can share: the lyrics of the song playing, the skins made on a computer (var/skins)        $share = [];        if ($lyrics && $wz->lyrics !== null && $wz->lyricsFile !== '') {            $share[] = ['row', 'lyrics', 'Partager les paroles de ce morceau', 'mkShare', 'lyrics', 'text', ''];        }        if (!$lyrics) {            foreach (Skin::findAll([$wz->storagePath('skins')]) as $skin) {                $share[] = ['row', 'palette', 'Partager « ' . $skin->name . ' »', 'mkShare', $skin->dir, 'text', ''];            }        }        if ($share !== [] && ($wz->market()?->enabled() ?? false)) {            $rows[] = ['section', 'Partager'];            $rows[] = ['input', 'Votre pseudo', 'author', 'Montré avec ce que vous partagez'];            array_push($rows, ...$share);        }        $this->renderPage('Marketplace', $lyrics ? 'Les paroles des utilisateurs de WinZik' : 'Les skins des utilisateurs de WinZik', $rows);    }    // the options -------------------------------------------------------------------------------------------------    private function enterOptions(): void    {        $o = $this->wz->options ?? [];        foreach (['spotifyId', 'spotifySecret', 'author', 'lyricsDir'] as $key) {            $this->fields[$key] = (string)($o[$key] ?? '');        }        $this->resetAsked = 0.0;    }    /** What is typed in the options goes to WinZik's options (saved a moment later). */    private function commitOptions(): string    {        $wz = $this->wz;        $error = '';        foreach (['spotifyId', 'spotifySecret', 'author'] as $key) {            $v = trim($this->fields[$key] ?? '');            if ((string)($wz->options[$key] ?? '') !== $v) {                $wz->options[$key] = $v;                $wz->touch();            }        }        $dir = trim($this->fields['lyricsDir'] ?? '');        if ($this->field !== 'lyricsDir' && $dir !== (string)($wz->options['lyricsDir'] ?? '')) {            if ($dir === '' || is_dir($dir)) {                $wz->options['lyricsDir'] = $dir;                $wz->refreshLyrics();                $wz->touch();            } else {                $error = "Ce dossier n'existe pas : " . $dir . '. Corrigez-le, ou videz la case.';            }        }        return $error;    }    private function renderOptions(): void    {        $wz = $this->wz;        $o = $wz->options;        $dirError = $this->commitOptions();        $toggle = fn (string $key) => ['toggle', self::OPTIONS[$key][0], self::OPTIONS[$key][1], 'opt', $key, (bool)($o[$key] ?? self::OPTIONS[$key][2])];        $balance = $wz->player->balance;        $karaoke = [];        foreach (\App\Gui\LyricsBar::KARAOKE as $key => $label) {            $karaoke[] = [$label, 'karaMode', $key, $key === $this->karaokeMode()];        }        $rows = [            ['section', 'Interface'],            ['row2', 'window', 'Interface : WinZik original (skin)', 'Les fenêtres de 2001, sur le téléphone', 'original', null, 'chevron'],            ['row2', 'palette', 'Thème de couleurs', MobileTheme::get($this->themeId())['name'], 'more', 'theme', 'chevron'],            ['row2', 'window', 'Skin de l\'interface originale', $wz->skin->name, 'goto', 'skins', 'chevron'],            ['section', 'Lecture'],            $toggle('skipBlanks'),            $toggle('timeLeft'),            ['stepper', 'Balance', $balance === 0 ? 'Au centre' : ($balance < 0 ? 'Gauche ' . -$balance . ' %' : 'Droite ' . $balance . ' %'), 'Gauche', 'Droite', 'balance'],            ['section', 'Paroles'],            $toggle('lrclib'),            $toggle('marketLyrics'),            $toggle('autoLyrics'),            ['note', 'Animation du karaoké sur les syllabes :'],            ['chipset', $karaoke],            ['input', 'Répertoire secondaire des paroles', 'lyricsDir', 'Un dossier de .LYR (facultatif)'],            ...($dirError !== '' ? [['note', $dirError, $this->col('danger')]] : []),            ...$this->lyricsOptionRows(),            ['section', 'Spotify'],            ['note', 'Votre propre app Spotify (gratuite) : Redirect URI ' . self::SPOTIFY_REDIRECT . ', « Web API ». Le Client ID suffit pour vos playlists ; le secret sert à la recherche « Spotify ».'],            ['input', 'Client ID', 'spotifyId', 'Collez votre Client ID'],            ['input', 'Client Secret', 'spotifySecret', 'Pour la recherche Spotify', true],            ['pills', [['Obtenir mes identifiants', 'spDashboard', null, false], ['Copier l\'adresse', 'spCopy', null, false]]],            ['section', 'Marketplace'],            ['input', 'Votre pseudo', 'author', 'Montré avec ce que vous partagez'],            ['section', 'Démarrage'],            $toggle('splash'),            ['space', 8],            ['pills', [[$this->resetAsked > 0 ? 'Confirmer : tout effacer ?' : 'Réinitialiser les options', 'optReset', null, $this->resetAsked > 0]]],            ['row2', 'info', 'À propos de WinZik', 'Version ' . $wz->version(), 'more', 'about', 'chevron'],        ];        $this->renderPage('Options', 'WinZik ' . $wz->version(), $rows);    }    private function renderSkins(): void    {        $wz = $this->wz;        $rows = [['note', 'Le skin habille l\'interface WinZik original (les fenêtres de 2001). D\'autres skins : la Marketplace.']];        foreach ($wz->skins() as $skin) {            $on = realpath($skin->dir) === realpath($wz->skin->dir);            $rows[] = ['row', $on ? 'check' : 'palette', $skin->name, 'skinPick', $skin->dir, 'text', ''];        }        $rows[] = ['pills', [['Marketplace des skins', 'mkSkins', null, false, 'store']]];        $this->renderPage('Skins', $wz->skin->name, $rows);    }    // the play lists (.FLS) -------------------------------------------------------------------------------------------    private function enterLibrary(): void    {        $this->fields['flsName'] ??= 'Ma playlist';    }    /** @return list<string> the play lists saved on the phone (var/playlists) */    public function savedPlaylists(): array    {        $files = glob(rtrim($this->wz?->storagePath('playlists') ?? '', '/') . '/*.fls') ?: [];        natcasesort($files);        return array_values($files);    }    public function flsSave(): bool    {        $wz = $this->wz;        $name = trim(preg_replace('#[\\\\/:*?"<>|]+#', ' ', $this->fields['flsName'] ?? '') ?? '');        $this->field = '';        if ($wz === null || $name === '') {            $wz?->notice('Donnez un nom à la playlist', 3);            return false;        }        $ok = $wz->saveFls($wz->storagePath('playlists/' . $name . '.fls'));        $wz->notice($ok ? 'Playlist enregistrée : ' . $name : 'Impossible d\'enregistrer la playlist', 4);        return $ok;    }    /** A file chosen in the add screen in another mode: lyrics for the song, or a play list. */    private function pickFile(string $path): void    {        $wz = $this->wz;        if ($this->pickMode === 'lyrics') {            if ($this->importLyrics($path)) {                $this->back();            }            return;        }        if ($wz !== null && $this->pickMode === 'fls') {            if ($wz->loadFls($path)) {                $wz->notice('Playlist ouverte : ' . Text::baseName($path), 4);                $this->pickMode = 'music';                $this->from = [];                $this->go('playlist');            } else {                $wz->notice('Ce fichier n\'est pas une playlist de WinZik (.FLS)', 4);            }        }    }    private function renderLibrary(): void    {        $wz = $this->wz;        $rows = [            ['note', 'La playlist en fichier .FLS (le format de WinZik 2001) : on la retrouve plus tard, ou sur l\'ordinateur.'],            ['input', 'Nom de la playlist', 'flsName', 'Ma playlist'],            ['pills', [['Enregistrer la playlist', 'flsSave', null, true, 'save']]],            ['section', 'Playlists enregistrées'],        ];        $saved = $this->savedPlaylists();        foreach ($saved as $f) {            $rows[] = ['row2', 'list', Text::baseName(Text::withoutExtension($f)), 'Toucher pour l\'ouvrir (remplace la playlist)', 'flsOpen', $f, 'chevron'];        }        if ($saved === []) {            $rows[] = ['note', 'Aucune pour l\'instant.'];        }        $rows[] = ['row', 'folder', 'Ouvrir un fichier .FLS du téléphone…', 'flsBrowse', null, 'text', 'chevron'];        $this->renderPage('Playlists', $wz->playlist->count() . ' morceau(x) dans la playlist', $rows);    }    // the updates of the Android app ----------------------------------------------------------------------------------    private function updateSource(): ?object    {        return $this->updates ?? $this->wz;    }    /**     * @return array{version: string, notes: string, size: int, state: string, progress: float, error: string, phase: string}|null a newer     *         WinZik for this phone, null: none     */    public function androidUpdate(): ?array    {        $src = $this->updateSource();        if ($src === null || !method_exists($src, 'androidUpdate')) {            return null;        }        $u = $src->androidUpdate();        return is_array($u) && ($u['version'] ?? '') !== '' ? ['version' => (string)$u['version'], 'notes' => (string)($u['notes'] ?? ''),            'size' => (int)($u['size'] ?? 0), 'state' => (string)($u['state'] ?? 'available'), 'progress' => (float)($u['progress'] ?? 0),            'error' => (string)($u['error'] ?? ''), 'phase' => (string)($u['phase'] ?? $u['state'] ?? '')] : null;    }    /** @return float|null 0..1 while the new APK downloads (1: Android's installer opened), null when it does not */    private function updateProgress(): ?float    {        $u = $this->androidUpdate();        return match ($u['state'] ?? '') {            'downloading' => $u['progress'],            'opened' => 1.0,            default => null,        };    }    /** The banner of a new version (once per version, until « Plus tard »). */    private function renderUpdateBanner(float $y): void    {        $u = $this->androidUpdate();        if ($u === null || ($this->wz->ui['mobile']['updateLater'] ?? '') === $u['version'] || $this->sheet !== '') {            return;        }        $W = $this->W;        $this->shadow(12, $y, $W - 24, 52, 26, 24);        $this->box(12, $y, $W - 24, 52, $this->col('accent'), 26);        $this->icon('download', 28, $y + 14, 24, $this->col('onAccent'));        $this->text('Nouvelle version ' . $u['version'] . ' disponible', 62, $y + 26, 15, $this->col('onAccent'), true, 'left', $W - 140);        $this->text('Voir', $W - 34, $y + 26, 15, $this->col('onAccent'), true, 'right');        $this->hit(12, $y, $W - 24, 52, 'more', 'update');    }    private function mediaSheet(): ?array    {        if ($this->sheet !== 'update') {            return null;        }        $u = $this->androidUpdate();        $progress = $this->updateProgress();        if ($u === null) {            $updater = $this->wz?->updater;            $state = $updater->state ?? '';            return [                ['title', 'Mise à jour', 'WinZik ' . $this->wz?->version()],                ['text', match ($state) {                    'checking' => 'Recherche d\'une mise à jour...',                    'error' => 'Impossible de savoir s\'il y a une mise à jour' . (($updater->error ?? '') !== '' ? ' (' . $updater->error . ')' : '') . ' : vérifiez la connexion, puis réessayez.',                    'off' => 'Les mises à jour se font par la boutique d\'applications ici.',                    default => 'WinZik est à jour.',                }],                ['button', 'Rechercher une mise à jour', 'updateCheck', null, false],                ['button', 'Fermer', 'sheetClose', null, true],            ];        }        $rows = [['title', 'Nouvelle version ' . $u['version'], 'Vous avez WinZik ' . $this->wz?->version() . ($u['size'] > 0 ? ' · ' . round($u['size'] / 1048576, 1) . ' Mo' : '')]];        if ($u['notes'] !== '') {            $rows[] = ['text', $u['notes']];        }        if ($u['state'] === 'error' && $u['error'] !== '') {            $rows[] = ['note', 'La mise à jour a échoué : ' . $u['error'] . '. Réessayez.', $this->col('danger')];        }        if ($progress !== null) {            $done = match ($u['phase']) {                'ready' => 'Téléchargée : elle s\'installera toute seule à la pause ou écran éteint, puis WinZik reprendra la musique',                'installing' => 'Installation en cours : WinZik va redémarrer et reprendre la musique',                'confirm' => 'Téléchargée : Android demande de confirmer l\'installation',                default => 'Téléchargée : l\'installateur d\'Android s\'ouvre',            };            $rows[] = ['progress', $progress >= 1 ? $done : 'Téléchargement · ' . (int)round($progress * 100) . ' %', $progress];            $rows[] = ['space', 8];            if ($progress >= 1) {                // the installer closed without installing: it opens again                $rows[] = ['button', $u['phase'] === 'ready' ? 'Installer maintenant' : 'Ouvrir l\'installateur', 'updateInstall', null, true];            }            $rows[] = ['button', 'Fermer', 'sheetClose', null, false];            return $rows;        }        $rows[] = ['button', 'Mettre à jour', 'updateInstall', null, true];        $rows[] = ['button', 'Plus tard', 'updateLater', null, false];        return $rows;    }    // taps ------------------------------------------------------------------------------------------------------------    private function tapMedia(string $id, mixed $data): bool    {        $wz = $this->wz;        if ($wz === null) {            return false;        }        switch ($id) {            case 'videoTap':                $this->videoUi = $this->videoUi > 0 ? 0.0 : 3.0;                return true;            case 'videoRotate':                $wz->ui['mobile']['rotate'] = !($wz->ui['mobile']['rotate'] ?? true);                $wz->touch();                $this->videoUi = 3.0;                return true;            case 'tagSave':                if ($this->tagSave()) {                    $this->back();                }                return true;            case 'tagHere':                $pos = sprintf('%.2f', $wz->player->position);                match ((string)$data) {                    'start' => $this->fields['tagStart'] = $pos,                    'end' => $this->fields['tagEnd'] = $pos,                    default => [$this->fields['tagStart'], $this->fields['tagEnd']] = ['', ''],                };                return true;            case 'tagStar':                $file = $wz->playlist->items[$this->tagLine] ?? null;                if ($file !== null) {                    $wz->rate($file, (int)$data);                }                return true;            case 'genrePick':                $this->tagGenre = (int)$data;                $this->back();                return true;            case 'mkKind':                $this->marketKind = $data === 'skin' ? 'skin' : 'lyrics';                $this->marketEntries = [];                $this->fields['mkQuery'] = '';                $this->marketFind();                return true;            case 'mkFind':                $this->marketFind();                return true;            case 'mkInstall':                $this->marketInstall((int)$data);                return true;            case 'mkShare':                $this->marketShare((string)$data);                return true;            case 'mkSkins':                $this->marketKind = 'skin';                $this->go('market');                return true;            case 'karaMode':                $wz->options['karaoke'] = (string)$data;                $wz->touch();                return true;            case 'balance':                $wz->setBalance($wz->player->balance + 10 * (int)$data);                return true;            case 'optReset':                if ($this->resetAsked > 0) {                    // everything of WinZik's settings erased, its defaults back (the phone app does not restart itself)                    $this->resetAsked = 0.0;                    $this->form?->engineOrNull()?->storage->delete(\App\Core\WinZik::SETTINGS);                    $wz->reset();                    $wz->save();                    $this->enterOptions();                    $wz->notice('Options effacées : WinZik est revenu à ses réglages de départ', 4);                } else {                    $this->resetAsked = 5.0;                }                return true;            case 'skinPick':                if ($wz->useSkin((string)$data)) {                    $wz->save();                    $wz->notice('Skin « ' . $wz->skin->name . ' » : il habille l\'interface WinZik original', 4);                }                return true;            case 'flsSave':                $this->flsSave();                return true;            case 'flsOpen':                $this->pickMode = 'fls';                $this->pickFile((string)$data);                return true;            case 'flsBrowse':                $this->pickMode = 'fls';                $this->folder = '';                $this->go('add');                return true;            case 'clearList':                $wz->removeLines(array_keys($wz->playlist->items));                $this->closeSheet();                $wz->notice('Playlist vidée', 3);                return true;            case 'website':                if (!Shell::openUrl(\App\Form\MainForm::SITE)) {                    $wz->notice('Le site : ' . \App\Form\MainForm::SITE, 8);                }                return true;            case 'updateCheck':                $src = $this->updateSource();                if ($src !== null && method_exists($src, 'checkUpdates')) {                    $src->checkUpdates();                } else {                    $wz->updater?->check();                }                $wz->notice('Recherche d\'une mise à jour...', 3);                $this->openSheet('update');                return true;            case 'updateInstall':                $src = $this->updateSource();                if ($src !== null && method_exists($src, 'installAndroidUpdate') && !$src->installAndroidUpdate()) {                    $wz->notice('La mise à jour est déjà en cours', 3);                }                return true;            case 'updateLater':                $u = $this->androidUpdate();                if ($u !== null) {                    $wz->ui['mobile']['updateLater'] = $u['version'];                    $wz->touch();                }                $this->closeSheet();                return true;        }        return false;    }    private function submitMedia(string $id): bool    {        if ($id === 'mkQuery') {            $this->marketFind();        } elseif ($id === 'flsName') {            $this->flsSave();        }        return true;     // the other fields: Entrée closes the keyboard    }}