IT
apps/winzik / src / Mobile / CloudPages.php · commit 6576d6f
<?phpnamespace App\Mobile;use App\Audio\Player;use App\Cloud\Cloud;use JumPHP\Native\Clipboard;/** * The cloud on the phone (App\Cloud\Cloud, AGENTS.md "Cloud"): the page « Mon compte (cloud) » (create the account and * show the recovery code once, sign in, the recovery code, the devices, the name of this one, the options of the copies, * sign out), the Playlist tab's switch « Ce téléphone | Cloud », the cloud playlist (each song's state: here, copying, * PC offline, YouTube, to copy, error), its sheets (a song, the menu of the cloud playlist). */trait CloudPages{    /** what the account page shows signed out: login | signup | recover */    public string $cloudMode = 'login';    /** the recovery code just given (shown once on the page, '' none; never saved) */    public string $cloudCode = '';    /** the last answer of the server, in French ('' none) */    public string $cloudStatus = '';    public bool $cloudError = false;    private int $cloudBusy = 0;    /** the Playlist tab shows the cloud (also signed out: then it asks to sign in) */    public bool $cloudTab = false;    /** the entry of the cloud sheets */    public string $cloudEntry = '';    /** the device whose sign out is being confirmed */    public string $cloudRevoke = '';    /** dp the finger pulled the cloud list down (pull to refresh) */    private float $cloudPull = 0.0;    /** seconds the "updating" ring stays after a refresh */    private float $cloudSyncing = 0.0;    private bool $cloudDevicesAsked = false;    public function cloud(): ?Cloud    {        $cloud = $this->wz?->cloud();        return $cloud !== null && $cloud->state() !== 'off' ? $cloud : null;    }    /** The Playlist tab shows the cloud playlist. */    public function inCloudView(): bool    {        $cloud = $this->cloud();        return $cloud !== null && ($this->cloudTab || $cloud->view() === 'cloud');    }    private function enterCloud(): void    {        $cloud = $this->cloud();        $this->cloudCode = '';        $this->cloudStatus = '';        $this->cloudError = false;        $this->fields['cdPass'] = '';        $this->fields['cdCode'] = '';        if ($cloud !== null) {            $this->fields['cdLogin'] = $cloud->login();            $this->fields['cdDevice'] = $cloud->deviceName();            if ($cloud->signedIn()) {                $this->askDevices();            }        }    }    private function askDevices(): void    {        $this->cloud()?->refreshDevices()->then(fn () => null, function (\Throwable $e): void {            $this->cloudStatus = $e->getMessage();            $this->cloudError = true;        });    }    // the account page --------------------------------------------------------------------------------------------    private function renderCloud(): void    {        $cloud = $this->wz?->cloud();        if ($cloud === null || $cloud->state() === 'off') {            $this->renderPage('Mon compte (cloud)', 'Indisponible', [                ['space', 16],                ['note', 'Pas de cloud ici : WinZik n\'a pas de serveur à joindre. Vérifiez la connexion à Internet, puis revenez sur cette page.'],            ]);            return;        }        if ($this->cloudCode !== '') {            $this->renderPage('Code de secours', 'À noter maintenant', [                ['cloudWarn', 'Notez ce code maintenant', 'Sans e-mail, c\'est le seul moyen de récupérer votre compte si vous oubliez le mot de passe. Il ne sera plus jamais affiché.'],                ['cloudCode', $this->cloudCode],                ['pills', [['Copier le code', 'cdCopy', null, false, 'copy']]],                ['space', 8],                ['button', 'J\'ai noté le code', 'cdNoted', null, true],            ]);            return;        }        $rows = $cloud->signedIn() ? $this->signedInRows($cloud) : $this->signInRows();        $sub = match ($cloud->state()) {            'online' => 'Connecté : ' . $cloud->login(),            'connecting' => 'Connexion de ' . $cloud->login() . '…',            'offline' => 'Hors ligne (' . $cloud->login() . ')',            default => 'Non connecté',        };        $this->renderPage('Mon compte (cloud)', $sub, $rows);    }    /** @return list<array> */    private function signInRows(): array    {        $mode = $this->cloudMode;        $rows = [            ['note', 'Le même compte sur le PC et sur le téléphone : la playlist cloud, les paroles, les MP3 envoyés par le PC. Un pseudo et un mot de passe, rien d\'autre : pas d\'e-mail.'],            ['chipset', [['Connexion', 'cdMode', 'login', $mode === 'login'], ['Créer un compte', 'cdMode', 'signup', $mode === 'signup'],                ['Code de secours', 'cdMode', 'recover', $mode === 'recover']]],            ['input', 'Pseudo', 'cdLogin', 'Votre pseudo (pas une adresse e-mail)'],        ];        if ($mode === 'recover') {            $rows[] = ['input', 'Code de secours', 'cdCode', 'Donné à la création du compte'];        }        $rows[] = ['input', $mode === 'recover' ? 'Nouveau mot de passe' : 'Mot de passe', 'cdPass', $mode === 'login' ? 'Votre mot de passe' : '8 caractères au moins', true];        $rows[] = ['input', 'Nom de ce téléphone', 'cdDevice', 'Montré sur vos autres appareils'];        if ($mode === 'recover') {            $rows[] = ['note', 'Tous vos appareils seront déconnectés, celui-ci reconnecté avec le nouveau mot de passe. Un nouveau code de secours vous sera donné.'];        }        if ($this->cloudBusy > 0) {            $rows[] = ['busy', $this->cloudStatus];        } elseif ($this->cloudStatus !== '') {            $rows[] = ['note', $this->cloudStatus, $this->cloudError ? $this->col('danger') : $this->col('accent')];        }        $rows[] = ['button', match ($mode) {            'signup' => 'Créer le compte',            'recover' => 'Changer le mot de passe',            default => 'Se connecter',        }, 'cdEnter', null, true];        return $rows;    }    /** @return list<array> */    private function signedInRows(Cloud $cloud): array    {        // the name of this phone, written when the keyboard closes        $name = trim($this->fields['cdDevice'] ?? '');        if ($this->field !== 'cdDevice' && $name !== '' && $name !== $cloud->deviceName()) {            $cloud->setDeviceName($name);            $this->fields['cdDevice'] = $cloud->deviceName();        }        $online = $cloud->state() === 'online';        $rows = [            ['cloudAccount', $cloud->login(), match ($cloud->state()) {                'online' => 'En ligne',                'offline' => 'Hors ligne : les changements partiront au retour du réseau',                default => 'Connexion…',            }, $online],            ['section', 'Mes appareils', (string)count($cloud->devices())],        ];        foreach ($cloud->devices() as $d) {            $kind = (string)($d['kind'] ?? 'desktop');            $current = !empty($d['current']);            $sub = $current ? 'Cet appareil' : (!empty($d['online']) ? 'En ligne' : 'Hors ligne' . self::seen((string)($d['lastSeen'] ?? '')));            $rows[] = ['cloudDevice', (string)($d['name'] ?? ''), $sub, !empty($d['online']), $current, (string)($d['id'] ?? ''), $kind];        }        if ($cloud->devices() === []) {            $rows[] = ['busy', 'Lecture des appareils…'];        }        $rows[] = ['input', 'Nom de ce téléphone', 'cdDevice', 'Montré sur vos autres appareils'];        if ($cloud->playSync !== null) {            // Synchronisé (default) / Indépendant: the same song, pause, position and volume as the other devices            $rows[] = ['section', 'Lecture synchronisée'];            $rows[] = ['toggle', 'Avec mes appareils', 'Morceau, pause, position, volume', 'cdSync', null, $cloud->playSynced()];            $rows[] = ['note', $cloud->syncText(), $cloud->syncCount() >= 2 ? $this->col('accent') : null];            if ($cloud->playSynced()) {                $rows[] = ['note', 'Le dernier appareil touché mène, les autres le suivent (aussi pendant un cast sur la TV).'];            }        }        $rows[] = ['section', 'Copies vers ce téléphone'];        array_push($rows, ...$this->cloudOptionRows($cloud));        if ($this->cloudStatus !== '') {            $rows[] = ['note', $this->cloudStatus, $this->cloudError ? $this->col('danger') : $this->col('accent')];        }        $rows[] = ['space', 8];        $rows[] = ['pills', [['Ouvrir la playlist cloud', 'cdOpenList', null, true, 'cloud']]];        $rows[] = ['pills', [['Se déconnecter', 'cdSignOut', null, false, 'logout']]];        return $rows;    }    /** @return list<array> Copier automatiquement, Wi-Fi seulement, the folder */    private function cloudOptionRows(Cloud $cloud): array    {        return [            ['toggle', 'Copier automatiquement', 'Les morceaux mis dans le cloud arrivent seuls', 'cdAuto', null, $cloud->autoCopy],            ['toggle', 'Wi-Fi seulement', 'Copies automatiques à la maison uniquement', 'cdWifi', null, $cloud->wifiOnly],            ['note', $cloud->wifiOnly                ? 'Les copies automatiques attendent que le PC et le téléphone soient sur le même Wi-Fi. Une copie demandée à la main peut passer par le relais.'                : 'Hors de la maison, la copie passe par le relais de jumphp.net (données mobiles) : chiffrée (le relais ne voit que des données illisibles), rien n\'est gardé sur le serveur.'],            ['row2', 'folder', 'Dossier de réception', $cloud->receiveDir, 'cdDir', null, ''],        ];    }    /** "· vu le 20/11 à 10:00" from an ISO date ('' unknown) */    private static function seen(string $iso): string    {        $t = $iso !== '' ? strtotime($iso) : false;        return $t === false ? '' : ' · vu le ' . date('d/m', $t) . ' à ' . date('H:i', $t);    }    // the cloud playlist --------------------------------------------------------------------------------------------    /** the switch « Ce téléphone | Cloud » of the Playlist tab, at $y (48 dp) */    private function renderSegment(float $y): void    {        $W = $this->W;        $cloud = $this->inCloudView();        $this->box(16, $y, $W - 32, 44, self::alpha($this->col('surface'), 170), 22);        $half = ($W - 32 - 8) / 2;        foreach ([['local', 'phone', 'Ce téléphone', !$cloud], ['cloud', 'cloud', 'Cloud', $cloud]] as $k => [$id, $icon, $label, $on]) {            $x = 20 + $k * $half;            if ($on) {                $this->shadow($x, $y + 4, $half, 36, 18, 14);                $this->box($x, $y + 4, $half, 36, $this->col('surface'), 18);            } elseif ($this->pressed('cloudView', $id)) {                $this->box($x, $y + 4, $half, 36, self::alpha($this->col('accent'), 25), 18);            }            $ink = $on ? $this->col('accent') : $this->col('muted');            $tw = $this->textWidth($label, 14, $on) + 26;            $this->icon($icon, $x + ($half - $tw) / 2, $y + 13, 18, $ink);            $this->text($label, $x + ($half - $tw) / 2 + 26, $y + 22, 14, $on ? $this->col('text') : $this->col('muted'), $on);            $this->hit($x, $y - 2, $half, 48, 'cloudView', $id);        }    }    /** the Playlist tab in the cloud view */    private function renderCloudList(): void    {        $wz = $this->wz;        $W = $this->W;        $cloud = $this->cloud();        $navTop = $this->H - self::NAV;        if ($cloud === null || !$cloud->signedIn()) {            $this->header('Playlist cloud', 'Non connecté', []);            $this->renderSegment(72);            $this->renderCloudEmpty(124, $navTop, 'Votre playlist cloud',                'Connectez votre compte WinZik : les morceaux mis dans le cloud par le PC arrivent sur ce téléphone, avec leurs paroles.',                'Mon compte (cloud)', 'goto', 'cloud');            return;        }        $rows = $cloud->rows();        $top = 72.0 + 52 + 76;        $miniTop = $navTop - self::MINI - 10;        $bottom = $wz->player->file !== null ? $miniTop - 4 : $navTop;        $this->scrollMax['list'] = max(0.0, count($rows) * self::ROW + 12 - ($bottom - $top));        $this->scroll['list'] = min($this->scroll['list'], $this->scrollMax['list']);        $off = $this->scroll['list'];        $pull = min(90.0, $this->cloudPull);        $this->hit(0, $top, $W, $bottom - $top, 'list', null, 'list');        if ($rows === []) {            $this->renderCloudEmpty($top, $bottom, 'La playlist cloud est vide',                'Sur le PC : clic droit sur un morceau > Mettre dans le cloud. Ici : ⋮ sur un morceau de « Ce téléphone » > Mettre dans le cloud.',                'Ce téléphone', 'cloudView', 'local');        }        $first = max(0, (int)floor($off / self::ROW));        $last = min(count($rows) - 1, (int)ceil(($off + $bottom - $top) / self::ROW));        for ($k = $first; $k <= $last; $k++) {            $this->renderCloudRow($rows[$k], $top + $k * self::ROW - $off + $pull);        }        if ($this->scrollMax['list'] > 0 && ($this->press !== null || $this->speed['list'] != 0)) {            $h = $bottom - $top;            $bh = max(40.0, $h * $h / ($h + $this->scrollMax['list']));            $this->box($W - 6, $top + ($h - $bh) * $off / $this->scrollMax['list'], 3, $bh, self::alpha($this->col('muted'), 120), 1.5);        }        $until = $top - 4;        $this->hits = array_values(array_filter($this->hits, fn (array $h) => $h[4] === 'list' || ($h[1] + $h[3] / 2 > $until && $h[1] + $h[3] / 2 < $bottom)));        $this->paintBackground(0, $until);        $this->paintBackground($bottom, $navTop);        // pulled down: a ring under the top, blue once far enough to read the playlist again        if ($pull > 8) {            $cy = $top + max(24.0, min(40.0, $pull / 2 + 4));            $this->shadow($W / 2 - 20, $cy - 20, 40, 40, 20, 14);            $this->circle($W / 2, $cy, 20, $this->col('surface'));            $this->icon('retry', $W / 2 - 11, $cy - 11, 22, $pull >= 70 ? $this->col('accent') : $this->col('muted'));        }        $here = count(array_filter($rows, fn (array $r) => $r['state'] === 'here'));        $sub = count($rows) . (count($rows) > 1 ? ' morceaux' : ' morceau') . ' · ' . $here . ' sur ce téléphone';        // the refresh button turns into a spinner while the playlist is read again        $this->header('Playlist cloud', $sub, [[$this->cloudSyncing > 0 ? '' : 'retry', 'cloudSync'], ['more', 'headerMore']]);        if ($this->cloudSyncing > 0) {            $this->spinner($W - 8 - 96 + 24, 32, 9);        }        $this->renderSegment(72);        $this->renderCloudCard(124, $cloud, $rows);        if ($wz->player->file !== null) {            $this->renderMini($miniTop);        }    }    /** the account, whether the PC is online, « Tout copier » */    private function renderCloudCard(float $y, Cloud $cloud, array $rows): void    {        $W = $this->W;        $this->box(16, $y, $W - 32, 64, self::alpha($this->col('surface'), 235), 18);        $this->hit(16, $y, $W - 32 - 132, 64, 'goto', 'cloud');        $this->circle(48, $y + 32, 20, $this->col('soft'));        $this->icon('user', 37, $y + 21, 22, $this->col('accent'));        $state = $cloud->state();        $this->text($cloud->login(), 78, $y + 22, 15, $this->col('text'), true, 'left', $W - 78 - 150);        $pcs = array_values(array_filter($cloud->devices(), fn (array $d) => ($d['kind'] ?? '') === 'desktop'));        $pcOn = array_filter($pcs, fn (array $d) => !empty($d['online']));        [$dot, $line] = match (true) {            $state === 'offline' => [$this->col('danger'), 'Téléphone hors ligne'],            $state === 'connecting' => [$this->col('muted'), 'Connexion…'],            $pcOn !== [] => [$this->col('accent'), 'PC en ligne : ' . (string)(array_values($pcOn)[0]['name'] ?? '')],            $pcs !== [] => [$this->col('muted'), 'PC hors ligne'],            default => [$this->col('muted'), 'Aucun PC sur le compte'],        };        $this->circle(82, $y + 44, 4, $dot);        $this->text($line, 92, $y + 44, 13, $this->col('muted'), false, 'left', $W - 92 - 150);        $missing = count(array_filter($rows, fn (array $r) => in_array($r['state'], ['absent', 'error', 'offline'], true)));        if ($missing > 0) {            $bw = 116.0;            $bx = $W - 24 - $bw;            $fill = $this->pressed('cloudAll') ? self::mix($this->col('accent'), '#000000', 0.12) : $this->col('accent');            $this->box($bx, $y + 12, $bw, 40, $fill, 20);            $this->icon('download', $bx + 12, $y + 22, 20, $this->col('onAccent'));            $this->text('Tout copier', $bx + 38, $y + 32, 13.5, $this->col('onAccent'), true, 'left', $bw - 44);            $this->hit($bx, $y + 8, $bw, 48, 'cloudAll');        } elseif ($rows !== []) {            $this->icon('check', $W - 132, $y + 22, 20, $this->col('accent'));            $this->text('Tout est ici', $W - 106, $y + 32, 13.5, $this->col('accent'), true);        }    }    private function renderCloudEmpty(float $top, float $bottom, string $title, string $text, string $button, string $id, string $data): void    {        $W = $this->W;        $cy = $top + ($bottom - $top) * 0.32;        $this->circle($W / 2, $cy - 30, 48, $this->col('soft'));        $this->icon('cloud', $W / 2 - 24, $cy - 54, 48, $this->col('accent'));        $this->text($title, $W / 2, $cy + 46, 20, $this->col('text'), true, 'center');        $y = $cy + 78;        foreach ($this->wrap($text, 15, false, $W - 64) as $line) {            $this->text($line, $W / 2, $y, 15, $this->col('muted'), false, 'center');            $y += 22;        }        $this->pill($W / 2 - 120, $y + 12, 240, $id === 'goto' ? 'user' : 'phone', $button, $id, $data);    }    /** the line of the play list of a cloud row ('' none yet) */    private function cloudItem(array $row): string    {        $file = $row['file'] ?? null;        $item = $file !== null ? $this->wz->relative((string)$file) : Cloud::PSEUDO . $row['id'] . '.mp3';        $at = array_search($item, $this->wz->playlist->items, true);        return $at === false ? '' : (string)$at;    }    /** a song of the cloud playlist and its state */    private function renderCloudRow(array $row, float $y): void    {        $wz = $this->wz;        $W = $this->W;        $id = (string)$row['id'];        $state = (string)$row['state'];        $line = $this->cloudItem($row);        $active = $line !== '' && (int)$line === $wz->playlist->active && $wz->player->file !== null && $state === 'here';        if ($active) {            $this->box(8, $y + 2, $W - 16, self::ROW - 4, self::alpha($this->col('surface'), 235), 16);            $this->box(8, $y + 2, 4, self::ROW - 4, $this->col('accent'), 2);        }        if ($this->pressed('cloudRow', $id) || ($this->sheet === 'cloudActions' && $this->cloudEntry === $id)) {            $this->box(8, $y + 2, $W - 16, self::ROW - 4, self::alpha($this->col('accent'), 30), 16);        }        // the badge: the song here (a note, bars while it plays), on its way (a ring of progress), not here (a cloud)        $bx = 20.0;        $by = $y + 12;        $here = $state === 'here' || $state === 'sending';        $this->box($bx, $by, 44, 44, $active ? $this->col('accent') : ($here ? $this->col('soft') : self::alpha($this->col('surface'), 200)), 12);        if ($active && $wz->player->state === Player::PLAYING) {            for ($k = 0; $k < 3; $k++) {                $h = 8 + 14 * abs(sin($this->clock * (3.1 + $k * 1.3) + $k));                $this->box($bx + 12 + $k * 8, $by + 32 - $h, 5, $h, $this->col('onAccent'), 2);            }        } elseif (in_array($state, ['copying', 'waiting', 'youtube'], true)) {            $this->spinner($bx + 22, $by + 22, 11);        } else {            $icon = match ($state) {                'here', 'sending' => 'note',                'error' => 'warning',                'offline' => 'computer',                default => 'cloud',            };            $ink = $active ? $this->col('onAccent') : ($state === 'error' ? $this->col('danger') : ($here ? $this->col('accent') : $this->col('muted')));            $this->icon($icon, $bx + 11, $by + 11, 22, $ink);        }        $textX = 76.0;        $right = $W - 56 - ($state === 'error' ? 48 : 0);        $title = (string)$row['title'] !== '' ? (string)$row['title'] : 'Sans titre';        $this->text($title, $textX, $y + 24, 16, $active ? $this->col('accent') : ($here ? $this->col('text') : self::mix($this->col('text'), $this->col('muted'), 0.35)), true, 'left', $right - $textX - 4);        $artist = (string)$row['artist'] !== '' ? (string)$row['artist'] : 'Artiste inconnu';        $length = (float)$row['duration'] > 0 ? ' · ' . self::clock((float)$row['duration']) : '';        // the second line: what is going on (its icon, its words), the bar of the copy        [$icon, $words, $tone] = match ($state) {            'here' => ['check', $artist . $length, 'muted'],            'sending' => ['cloud', 'Envoi ' . (int)floor((float)$row['progress'] * 100) . ' %', 'accent'],            'copying' => ['download', 'Copie ' . (int)floor((float)$row['progress'] * 100) . ' %', 'accent'],            'waiting' => ['computer', 'En attente du PC…', 'muted'],            'offline' => ['computer', 'PC hors ligne – en attente', 'muted'],            'youtube' => ['youtube', 'YouTube ↓ téléchargement', 'accent'],            'error' => ['warning', (string)$row['text'] !== '' ? (string)$row['text'] : 'Copie impossible', 'danger'],            default => [($row['source']['type'] ?? '') === 'youtube' ? 'youtube' : 'download', 'Copier sur le téléphone', 'accent'],        };        $ink = $this->col($tone);        $this->icon($icon, $textX, $y + 40, 14, $state === 'here' ? $this->col('accent') : $ink);        $this->text($words, $textX + 20, $y + 47, 13, $ink, $tone === 'accent', 'left', $right - $textX - 24);        if ($state === 'copying' || $state === 'sending') {            $bw = $right - $textX - 8;            $this->box($textX, $y + 59, $bw, 4, $this->col('surface2'), 2);            $this->box($textX, $y + 59, max(4, $bw * min(1.0, (float)$row['progress'])), 4, $this->col('accent'), 2);        }        $this->hit(8, $y, $right - 8, self::ROW, 'cloudRow', $id, 'list');        if ($state === 'error') {            $this->roundButton($W - 104, $y + 10, 48, 'retry', 'cloudRetry', $id, $this->col('accent'), null, 22);            $this->hits[count($this->hits) - 1][6] = 'list';        }        $this->roundButton($W - 56, $y + 10, 48, 'more', 'cloudMore', $id, $this->col('muted'), null, 22);        $this->hits[count($this->hits) - 1][6] = 'list';    }    // the rows of the sheets and pages of the cloud ---------------------------------------------------------------    private function cloudRowHeight(array $row): ?float    {        return match ($row[0]) {            'cloudWarn' => 52.0 + 21.0 * count($this->wrap((string)$row[2], 14.5, false, $this->W - 48 - 32)) + 18,            'cloudCode' => 104.0,            'cloudAccount' => 76.0,            'cloudDevice' => 68.0,            default => null,        };    }    private function drawCloudRow(array $row, float $y, float $h): void    {        $W = $this->W;        switch ($row[0]) {            case 'cloudWarn':                // the big warning: the code is the only way back into the account                $this->box(16, $y + 4, $W - 32, $h - 8, self::mix($this->col('danger'), $this->col('surface'), 0.88), 18);                $this->box(16, $y + 4, 5, $h - 8, $this->col('danger'), 2.5);                $this->icon('warning', 32, $y + 18, 26, $this->col('danger'));                $this->text((string)$row[1], 66, $y + 31, 17, $this->col('danger'), true, 'left', $W - 66 - 28);                $ty = $y + 62;                foreach ($this->wrap((string)$row[2], 14.5, false, $W - 48 - 32) as $l) {                    $this->text($l, 34, $ty, 14.5, $this->col('text'));                    $ty += 21;                }                break;            case 'cloudCode':                $this->box(16, $y + 8, $W - 32, $h - 16, $this->col('accent'), 18);                $this->box(18, $y + 10, $W - 36, $h - 20, $this->col('surface'), 16);                $this->icon('key', 34, $y + $h / 2 - 12, 24, $this->col('accent'));                $size = 22.0;                while ($size > 14 && $this->textWidth((string)$row[1], $size, true) > $W - 120) {                    $size -= 1;                }                $this->text((string)$row[1], $W / 2 + 14, $y + $h / 2, $size, $this->col('text'), true, 'center');                break;            case 'cloudAccount':                [, $login, $sub, $online] = $row;                $this->box(12, $y + 4, $W - 24, $h - 8, self::alpha($this->col('surface'), 235), 18);                $this->gradientBox(28, $y + 16, 44, 44, $this->col('art1'), $this->col('art2'), 22);                $this->icon('user', 39, $y + 27, 22, '#ffffff');                $this->text((string)$login, 86, $y + 30, 18, $this->col('text'), true, 'left', $W - 86 - 28);                $this->circle(90, $y + 52, 4, $online ? $this->col('accent') : $this->col('muted'));                $this->text((string)$sub, 100, $y + 52, 13, $this->col('muted'), false, 'left', $W - 100 - 28);                break;            case 'cloudDevice':                [, $name, $sub, $online, $current, $id, $kind] = $row;                $this->box(24, $y + 12, 44, 44, $this->col('soft'), 12);                $this->icon($kind === 'phone' ? 'phone' : 'computer', 34, $y + 22, 24, $this->col('accent'));                $this->circle(64, $y + 52, 7, $this->col('surface'));                $this->circle(64, $y + 52, 5, $online ? $this->col('accent') : $this->col('line'));                $max = $W - 80 - ($current ? 30 : 76);                $this->text((string)$name, 80, $y + 24, 16, $this->col('text'), true, 'left', $max);                $this->text((string)$sub, 80, $y + 46, 13, $current ? $this->col('accent') : $this->col('muted'), $current, 'left', $max);                if (!$current) {                    $this->roundButton($W - 72, $y + 10, 48, 'logout', 'cdRevoke', $id, $this->col('danger'), null, 22);                }                break;        }    }    // the sheets --------------------------------------------------------------------------------------------------    private function cloudSheet(): ?array    {        $cloud = $this->cloud();        if ($cloud === null || !in_array($this->sheet, ['cloudActions', 'cloudRemove', 'cloudMenu', 'cloudRevoke'], true)) {            return null;        }        if ($this->sheet === 'cloudMenu') {            return [                ['title', 'Playlist cloud', 'Compte ' . $cloud->login()],                ['row', 'download', 'Tout copier sur le téléphone', 'cloudAll', null, 'text', ''],                ['row', 'retry', 'Actualiser', 'cloudSync', null, 'text', ''],                ['row', 'user', 'Mon compte (cloud)', 'goto', 'cloud', 'text', 'chevron'],                ...array_slice($this->cloudOptionRows($cloud), 0, 2),            ];        }        if ($this->sheet === 'cloudRevoke') {            $name = '';            foreach ($cloud->devices() as $d) {                if (($d['id'] ?? '') === $this->cloudRevoke) {                    $name = (string)$d['name'];                }            }            return [                ['title', 'Déconnecter « ' . $name . ' » ?', 'Il quitte le compte'],                ['text', 'Cet appareil devra se reconnecter avec le pseudo et le mot de passe. Ses morceaux copiés restent sur lui.'],                ['button', 'Déconnecter', 'cdRevokeYes', null, true],                ['button', 'Annuler', 'sheetClose', null, false],            ];        }        $row = null;        foreach ($cloud->rows() as $r) {            if ($r['id'] === $this->cloudEntry) {                $row = $r;            }        }        if ($row === null) {            return [['title', 'Playlist cloud', 'Ce morceau n\'est plus dans le cloud'], ['button', 'Fermer', 'sheetClose', null, true]];        }        $title = (string)$row['title'] !== '' ? (string)$row['title'] : 'Sans titre';        $artist = (string)$row['artist'] !== '' ? (string)$row['artist'] : 'Artiste inconnu';        if ($this->sheet === 'cloudRemove') {            return [                ['title', 'Retirer du cloud ?', $title],                ['text', 'Le morceau quitte la playlist cloud sur tous vos appareils. Les fichiers déjà copiés restent où ils sont.'],                ['button', 'Retirer du cloud', 'cloudRemoveYes', null, true],                ['button', 'Annuler', 'sheetClose', null, false],            ];        }        $here = $row['state'] === 'here' || $row['state'] === 'sending';        $from = ($row['source']['type'] ?? '') === 'youtube' ? 'Récupéré sur YouTube' : 'Envoyé par le PC';        $rows = [['title', $title, $artist . ' · ' . $from]];        if ($here) {            $rows[] = ['row', 'play', 'Lire', 'cloudAct', 'play', 'text', ''];        } else {            $rows[] = ['row', $row['state'] === 'error' ? 'retry' : 'download', $row['state'] === 'error' ? 'Réessayer la copie' : 'Copier sur le téléphone', 'cloudAct', 'fetch', 'text', ''];        }        if (!empty($row['lyrics'])) {            $rows[] = ['row', 'lyrics', $here ? 'Paroles' : 'Paroles (après la copie)', 'cloudAct', 'lyrics', 'text', $here ? 'chevron' : ''];        }        $rows[] = ['row', 'trash', 'Retirer du cloud', 'cloudAct', 'remove', 'danger', ''];        if (!$here) {            $rows[] = ['note', 'État : ' . (string)$row['text']];        }        return $rows;    }    // taps ------------------------------------------------------------------------------------------------------------    private function tapCloud(string $id, mixed $data): bool    {        $wz = $this->wz;        $cloud = $this->cloud();        switch ($id) {            case 'cloudView':                $this->cloudTab = $data === 'cloud';                $cloud?->useView($this->cloudTab ? 'cloud' : 'local');                $this->scroll['list'] = 0.0;                $this->searching = false;                if ($this->cloudTab && $cloud?->signedIn() && !$this->cloudDevicesAsked) {                    $this->cloudDevicesAsked = true;                    $this->askDevices();                }                return true;            case 'cloudSync':                $this->closeSheet();                $cloud?->sync();                $this->askDevices();                $this->cloudSyncing = 1.2;                $wz->notice('Playlist cloud actualisée', 2);                return true;            case 'cloudAll':                $this->closeSheet();                $n = 0;                foreach ($cloud?->rows() ?? [] as $r) {                    if (in_array($r['state'], ['absent', 'error', 'offline'], true)) {                        $cloud->fetch((string)$r['id']);                        $n++;                    }                }                $wz->notice($n > 0 ? $n . ' morceau(x) en copie vers ce téléphone' : 'Tout est déjà sur ce téléphone', 3);                return true;            case 'cloudRow':                $this->tapCloudRow((string)$data);                return true;            case 'cloudRetry':                $cloud?->fetch((string)$data);                return true;            case 'cloudMore':                $this->cloudEntry = (string)$data;                $this->openSheet('cloudActions');                return true;            case 'cloudAct':                $this->cloudAction((string)$data);                return true;            case 'cloudRemoveYes':                $cloud?->remove([$this->cloudEntry]);                $this->closeSheet();                $wz->notice('Retiré du cloud', 3);                return true;            case 'cdMode':                $this->cloudMode = in_array($data, ['signup', 'recover'], true) ? (string)$data : 'login';                $this->cloudStatus = '';                return true;            case 'cdEnter':                $this->cloudEnter();                return true;            case 'cdCopy':                $wz->notice(Clipboard::copy($this->cloudCode) ? 'Code copié : collez-le dans vos notes' : 'Copie impossible ici : recopiez le code à la main', 4);                return true;            case 'cdNoted':                $this->cloudCode = '';                $this->scroll['page:cloud'] = 0.0;                $this->askDevices();                return true;            case 'cdAuto':            case 'cdWifi':                if ($cloud !== null) {                    $id === 'cdAuto' ? $cloud->autoCopy = !$cloud->autoCopy : $cloud->wifiOnly = !$cloud->wifiOnly;                    $cloud->saveSettings();                }                return true;            case 'cdSync':                $cloud?->setPlaySync(!$cloud->playSynced());                return true;            case 'cdDir':                $wz->notice('Les morceaux copiés vont dans ' . ($cloud !== null ? $cloud->receiveDir : ''), 5);                return true;            case 'cdRevoke':                $this->cloudRevoke = (string)$data;                $this->openSheet('cloudRevoke');                return true;            case 'cdRevokeYes':                $this->closeSheet();                $cloud?->revoke($this->cloudRevoke)->then(function (): void {                    $this->cloudStatus = 'L\'appareil est déconnecté du compte.';                    $this->cloudError = false;                }, function (\Throwable $e): void {                    $this->cloudStatus = $e->getMessage();                    $this->cloudError = true;                });                return true;            case 'cdOpenList':                $this->cloudTab = true;                $cloud?->useView('cloud');                $this->back();                $this->go('playlist');                return true;            case 'cdSignOut':                $cloud?->signOut();                $this->cloudTab = false;                $this->cloudMode = 'login';                $this->cloudStatus = 'Ce téléphone est déconnecté du compte. Les morceaux copiés restent sur lui.';                $this->cloudError = false;                $this->fields['cdPass'] = '';                return true;        }        return false;    }    /** A cloud song touched: played when here, else its copy starts (or starts again). */    private function tapCloudRow(string $id): void    {        $wz = $this->wz;        $cloud = $this->cloud();        $row = null;        foreach ($cloud?->rows() ?? [] as $r) {            if ($r['id'] === $id) {                $row = $r;            }        }        if ($row === null) {            return;        }        switch ($row['state']) {            case 'here':            case 'sending':                $line = $this->cloudItem($row);                if ($line === '') {                    $cloud->useView('cloud');                    $line = $this->cloudItem($row);                }                if ($line !== '') {                    $wz->playlist->active === (int)$line && $wz->player->state === Player::PLAYING ? $this->go('player') : $wz->playIndex((int)$line);                }                break;            case 'copying':            case 'waiting':            case 'youtube':                $wz->notice('Copie en cours : ' . $row['text'], 3);                break;            default:                $cloud->fetch($id);                $wz->notice('Copie vers ce téléphone : ' . trim($row['artist'] . ' - ' . $row['title'], ' -'), 4);        }    }    private function cloudAction(string $what): void    {        $wz = $this->wz;        $cloud = $this->cloud();        $id = $this->cloudEntry;        if ($cloud === null) {            $this->closeSheet();            return;        }        switch ($what) {            case 'play':                $this->closeSheet();                $this->tapCloudRow($id);                break;            case 'fetch':                $this->closeSheet();                $cloud->fetch($id);                $wz->notice('Copie vers ce téléphone…', 3);                break;            case 'lyrics':                $this->closeSheet();                $file = $cloud->playlist->fileOf($id);                if ($file === null) {                    $wz->notice('Les paroles arrivent avec le morceau : copiez-le d\'abord', 4);                    break;                }                $this->tapCloudRow($id);                $this->go('karaoke');                break;            case 'remove':                $this->openSheet('cloudRemove');                break;        }    }    /** « Mettre dans le cloud » from the phone: the other devices get it from YouTube. */    private function cloudPut(int $line): void    {        $wz = $this->wz;        $cloud = $this->cloud();        $file = $wz->playlist->items[$line] ?? null;        $this->closeSheet();        if ($cloud === null || $file === null) {            return;        }        if (!$cloud->signedIn()) {            $wz->notice('Connectez-vous d\'abord à votre compte', 3);            $this->go('cloud');            return;        }        $n = $cloud->putFromYoutube([$file]);        $wz->notice($n > 0 ? 'Mis dans le cloud : vos autres appareils le récupèrent sur YouTube' : 'Ce morceau ne peut pas aller dans le cloud', 4);    }    /** @return list<array> the row « Mettre dans le cloud » of a song's sheet (none without a cloud) */    private function cloudPutRow(int $line): array    {        $cloud = $this->cloud();        $file = $this->wz?->playlist->items[$line] ?? null;        if ($cloud === null || $file === null || Cloud::isPseudo($file)) {            return [];        }        if ($cloud->signedIn() && $cloud->fileState($file)['cloud']) {            return [['row', 'cloud', 'Déjà dans le cloud', 'act', 'none', 'text', 'check']];        }        return [['row', 'cloud', 'Mettre dans le cloud', 'act', 'cloudPut', 'text', '']];    }    private function cloudEnter(): void    {        $cloud = $this->cloud();        if ($cloud === null || $this->cloudBusy > 0) {            return;        }        $this->field = '';        $login = trim($this->fields['cdLogin'] ?? '');        $password = (string)($this->fields['cdPass'] ?? '');        $mode = $this->cloudMode;        $this->cloudError = true;        if ($login === '' || $password === '' || ($mode === 'recover' && trim((string)($this->fields['cdCode'] ?? '')) === '')) {            $this->cloudStatus = $login === '' ? 'Tapez votre pseudo.' : ($password === '' ? 'Tapez le mot de passe.' : 'Tapez le code de secours.');            return;        }        if ($mode !== 'login' && mb_strlen($password) < 8) {            $this->cloudStatus = 'Mot de passe trop court : 8 caractères au moins.';            return;        }        $name = trim($this->fields['cdDevice'] ?? '');        $name = $name !== '' ? $name : null;        $this->cloudError = false;        $this->cloudStatus = match ($mode) {            'signup' => 'Création du compte…',            'recover' => 'Changement du mot de passe…',            default => 'Connexion…',        };        $this->cloudBusy++;        $task = match ($mode) {            'signup' => $cloud->signUp($login, $password, $name),            'recover' => $cloud->recover($login, trim((string)($this->fields['cdCode'] ?? '')), $password, $name),            default => $cloud->signIn($login, $password, $name),        };        $task->then(function (array $data) use ($cloud): void {            $this->cloudBusy--;            $this->fields['cdPass'] = '';            $this->fields['cdCode'] = '';            $this->fields['cdDevice'] = $cloud->deviceName();            $this->cloudStatus = '';            $this->cloudError = false;            $this->cloudCode = (string)($data['recovery'] ?? '');      // shown once, never kept            $this->scroll['page:cloud'] = 0.0;            if ($this->cloudTab) {                $cloud->useView('cloud');            }            if ($this->cloudCode === '') {                $this->wz?->notice('Connecté : ' . ($data['login'] ?? ''), 3);                $this->askDevices();            }        }, function (\Throwable $e): void {            $this->cloudBusy--;            $this->cloudStatus = $e->getMessage();            $this->cloudError = true;        });    }    private function submitCloud(string $id): bool    {        if (in_array($id, ['cdLogin', 'cdPass', 'cdCode'], true) && !($this->cloud()?->signedIn() ?? true)) {            if ($id === 'cdLogin') {                $this->tap('field', $this->cloudMode === 'recover' ? 'cdCode' : 'cdPass');            } elseif ($id === 'cdCode') {                $this->tap('field', 'cdPass');            } else {                $this->cloudEnter();            }            return true;        }        return str_starts_with($id, 'cd');    }    // pull to refresh -------------------------------------------------------------------------------------------------    /** the finger pulls the top of the cloud list down: @return bool whether it is a pull (not a scroll) */    private function cloudPulling(array $press, float $y): bool    {        if ($press['scroll'] !== 'list' || !$this->inCloudView() || $this->screen !== 'playlist' || $press['from'] > 0) {            $this->cloudPull = 0.0;            return false;        }        $this->cloudPull = max(0.0, ($y - $press['y']) * 0.6);        return $this->cloudPull > 0;    }    /** the finger let go: far enough, the playlist is read again */    private function cloudPulled(): void    {        if ($this->cloudPull >= 70 && ($this->cloud()?->signedIn() ?? false)) {            $this->tapCloud('cloudSync', null);        }        $this->cloudPull = 0.0;    }}