KO
apps/winzik / src / Form / LyricsSearchForm.php · commit 6576d6f
<?phpnamespace App\Form;use App\Media\LyricsSearch;use App\Model\Text;use JumPHP\Gui\Button;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\TextBox;/** * The search of lyrics on the Internet (WinZik::lyricsHelp() / searchLyrics(): LRCLIB, the marketplace, the old site of * 2001, Claude Code on a computer that has it), in the style of the dialogs of 2001: the artist and the title filled in * from the tag (or the file's name), the candidates listed as they come (SYNC = with times, ≡ = lines only), the first * lines of the one chosen, what each source does ("Claude cherche sur le web…"). Importer: the song's lyrics * (WinZik::importLyrics()), then "Ouvrir dans l'éditeur". Opened from the lyrics editor (param `editor`): "Mettre dans * l'éditeur" gives the candidate back to it (close($candidate)). * Params: song (the song; default the one playing), editor (bool). (Not `file`: a form's own param, its .yaml.) * * @property Label $heading * @property Label $song * @property TextBox $artist * @property TextBox $title * @property Button $find * @property \JumPHP\Gui\ProgressBar $busy * @property Label $sources * @property ListBox $items * @property Label $info * @property TextBox $preview * @property Button $import * @property Button $editor * @property Button $quit * @property Label $status */final class LyricsSearchForm extends WinZikDialog{    /** the song the lyrics are for */    public string $songFile = '';    /** opened from the lyrics editor: the candidate goes back to it */    public bool $forEditor = false;    /** @var list<array<string, mixed>> the candidates listed (best first) */    public array $candidates = [];    public ?LyricsSearch $search = null;    /** the path of the lyrics imported (then "Ouvrir dans l'éditeur") */    public ?string $imported = null;    private float $spin = 0.0;    /** what each source's state says */    private const STATES = ['searching' => 'cherche…', 'found' => 'trouvé', 'none' => 'rien', 'error' => 'injoignable'];    protected function loaded(array $params = []): void    {        $this->forEditor = !empty($params['editor']);        $this->songFile = (string)($params['song'] ?? $this->wz->playlist->current() ?? '');        $this->candidates = [];        $this->search = null;        $this->imported = null;        $this->items->items = [];        $this->items->selected = -1;        $this->preview->text = '';        $this->info->text = '';        $this->sources->text = '';        $this->editor->props['visible'] = false;        $this->import->text = $this->forEditor ? 'Mettre dans l\'éditeur' : 'Importer';        $this->import->tooltip = $this->forEditor ? 'Le texte des paroles dans l\'éditeur (les temps gardés quand elles sont synchronisées)'            : 'Les paroles de ce morceau (les temps gardés quand elles sont synchronisées)';        $this->song->text = $this->songFile === '' ? '' : Text::baseName($this->songFile);        if ($this->songFile === '') {            $this->status->text = 'Choisissez d\'abord un morceau dans la playlist.';            return;        }        $help = $this->wz->lyricsHelp($this->songFile);        $this->artist->text = $help['artist'];        $this->title->text = $help['title'];        $this->search = $help['search'];        $this->status->text = $help['text'];        $this->setFocus($help['title'] === '' ? $this->title : $this->artist);        if ($this->search === null) {            $this->find->enabled = false;        }    }    public function onSearchSubmit(TextBox $sender): void    {        $this->onFindClick($this->find);    }    public function onFindClick(Button $sender): void    {        $artist = trim($this->artist->text);        $title = trim($this->title->text);        if ($artist === '' && $title === '') {            $this->status->text = 'Donnez l\'artiste et le titre, puis « Chercher ».';            return;        }        $this->search = $this->wz->searchLyrics($artist, $title, $this->songFile !== '' ? $this->songFile : null);        $this->candidates = [];        $this->items->items = [];        $this->items->selected = -1;        $this->preview->text = '';        $this->status->text = $this->search === null ? 'Pas de réseau ici : collez les paroles dans l\'éditeur.' : 'Recherche des paroles de « ' . trim($artist . ' - ' . $title, ' -') . ' »...';    }    /** One line of the list: SYNC (with times) or ≡ (lines only), the source, the song, its length, how many lines. @param array<string, mixed> $c */    public static function line(array $c): string    {        $song = trim((string)$c['artist'] . ' - ' . (string)$c['title'], ' -');        $d = (int)round((float)($c['duration'] ?? 0));        return ($c['synced'] ? 'SYNC' : '≡    ') . '   ' . $c['sourceName'] . '  —  ' . ($song !== '' ? $song : '?')            . ($d > 0 ? sprintf('  (%d:%02d)', intdiv($d, 60), $d % 60) : '') . '   ' . (int)$c['lines'] . ' lignes';    }    /** What each source does now (the ones asked). */    public function sourcesText(): string    {        $parts = [];        foreach ($this->search->sources ?? [] as $source => $state) {            if ($state === 'off') {                continue;            }            if ($source === 'claude' && $state === 'searching') {                $parts[] = 'Claude cherche sur le web…';                continue;            }            $parts[] = (LyricsSearch::SOURCES[$source] ?? $source) . ' : ' . (self::STATES[$state] ?? $state);        }        return implode('   ·   ', $parts);    }    protected function tick(float $dt): void    {        parent::tick($dt);        $search = $this->search;        $searching = $search !== null && !$search->done();        $this->busy->props['visible'] = $searching;        if ($searching) {            $this->spin = fmod($this->spin + $dt * 90, 100);            $this->busy->value = round($this->spin);        }        if ($search !== null) {            $this->sources->text = $this->sourcesText();            if (count($search->candidates) !== count($this->candidates) || array_column($search->candidates, 'id') !== array_column($this->candidates, 'id')) {                $this->fill($search->candidates);            }            if ($this->imported === null && ($searching || $this->candidates === [] || str_starts_with($this->status->text, 'Recherche'))) {                $this->status->text = $search->describe();            }        }        $this->import->enabled = isset($this->candidates[(int)$this->items->selected]);    }    /** @param list<array<string, mixed>> $candidates the list again, the line chosen kept (by its id) */    private function fill(array $candidates): void    {        $chosen = $this->candidates[(int)$this->items->selected]['id'] ?? null;        $this->candidates = $candidates;        $this->items->items = array_map(fn (array $c) => self::line($c), $candidates);        $at = $chosen === null ? false : array_search($chosen, array_column($candidates, 'id'), true);        $this->items->selected = $at === false ? ($candidates === [] ? -1 : 0) : (int)$at;        $this->showChosen();    }    public function onItemsChange(ListBox $sender, int $index, string $item): void    {        $this->showChosen();    }    public function onItemsActivate(ListBox $sender, int $index, string $item): void    {        $this->onImportClick($this->import);    }    /** The candidate chosen: where it comes from, and its first lines (with their moments when it has times). */    private function showChosen(): void    {        $c = $this->candidates[(int)$this->items->selected] ?? null;        if ($c === null) {            $this->info->text = '';            $this->preview->text = '';            return;        }        $this->info->text = ($c['synced'] ? 'Synchronisées (les temps de chaque ligne)' : 'Non synchronisées (les lignes seules : à défiler, ou à synchroniser dans l\'éditeur)')            . '  -  ' . $c['sourceName'] . (($c['album'] ?? '') !== '' ? '  -  ' . $c['album'] : '');        $lyrics = $c['lyrics'] ?? null;        $rows = [];        if ($lyrics instanceof \App\Model\Lyrics) {            foreach (array_slice($lyrics->lines, 0, 14) as [$time, $text]) {                $plain = \App\Model\Karaoke::plain((string)$text);                $rows[] = $lyrics->synced ? sprintf('[%d:%05.2f]  %s', intdiv((int)$time, 60), fmod((float)$time, 60), $plain) : $plain;            }        } else {            $rows = array_slice(preg_split('/\r\n|\r|\n/', (string)$c['text']) ?: [], 0, 14);        }        $this->preview->text = implode("\n", $rows);    }    public function onImportClick(Button $sender): void    {        $c = $this->candidates[(int)$this->items->selected] ?? null;        if ($c === null) {            return;        }        if ($this->forEditor) {            $this->search?->cancel();            $this->close($c);       // the editor takes its text (and its times)            return;        }        $this->imported = $this->wz->importLyrics($c, $this->songFile);        if ($this->imported === null) {            $this->status->text = 'Paroles NON importées : ce morceau ne peut pas en recevoir (morceau du cloud absent ?)';            return;        }        $this->status->text = ($c['synced'] ? 'Paroles synchronisées importées' : 'Paroles importées (non synchronisées : elles défilent pendant la lecture)')            . ' pour ' . Text::baseName($this->songFile) . '.';        $this->editor->props['visible'] = true;        $this->setFocus($this->editor);    }    /** The lyrics imported, in the editor (the song plays: the editor works on the song playing). */    public function onEditorClick(Button $sender): void    {        $this->search?->cancel();        $this->close(['openEditor' => $this->songFile]);    }    public function onQuitClick(Button $sender): void    {        if ($this->search !== null && !$this->search->done()) {            $this->search->cancel();        }        $this->close();    }}