KO
apps/winzik / src / Form / LyricsEditorForm.php · commit 6576d6f
<?phpnamespace App\Form;use App\Audio\Player;use App\Model\Lyrics;use App\Model\Text;use JumPHP\Gui\Button;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\Pointer;use JumPHP\Gui\TextBox;/** * The lyrics editor: the lines of the song typed or pasted on the left; "Démarrer la synchro" plays the song from the * start, and each press of "Ligne suivante" (or Return) gives the next line the time of the song at that moment, as the * .LYR files of 2001 were made ([ 1.2625274 ] = the moment the line was given). A line of the right list activated * (double click) sends the song to its time. Saved next to the song, else in var/lyr. * * Keys (out of the lyrics text): Entrée = the next line takes the time of the song now (a line chosen while the song * plays: from that line), Espace = the next syllable, Gauche / Droite = the line's (or syllable's) time -100 / +100 ms * (Maj: 10 ms), Ctrl+Z / Ctrl+Y = the times as they were / again, Ctrl+S = Enregistrer, Échap = Fermer (asked twice * when the lyrics are not saved). * * Lyrics without times (`[NON SYNCHRONISEES]`, from the Internet): loaded as plain lines (blank lines between the verses * kept), saved as such while no line has a time. "Chercher sur internet…" opens LyricsSearchForm: the candidate chosen * fills the text (its times kept when it is synchronised). Saved through WinZik::saveLyrics() (the translations of * the lines that did not change are kept, the language guessed, the cloud account told). * * @property Label $song * @property Label $clock * @property TextBox $text * @property ListBox $synced * @property Label $now * @property Button $start * @property Button $stamp * @property Button $back * @property Button $pause * @property Button $auto * @property Button $web * @property Button $clear * @property Button $save * @property Button $publish * @property Button $quit * @property Label $status * @property \App\Gui\SyllableStrip $strip * @property Button $sylStamp * @property Button $m100 * @property Button $m10 * @property Button $p10 * @property Button $p100 * @property Button $replay * @property Button $estimate * @property Button $webSearch */final class LyricsEditorForm extends WinZikDialog{    /** @var list<float|null> the time of each line, null = not given yet */    private array $times = [];    /** the next line to stamp, -1 = not syncing */    public int $next = -1;    private string $lastText = '';    /** the lyrics as last read or saved (.LYR text): what "not saved" is compared with */    private string $savedLyr = '';    /** the lyrics when Fermer was asked: closed on a second Fermer if nothing changed since */    private ?string $quitAskedFor = null;    /** how many changes of the times Ctrl+Z goes back */    public const HISTORY = 100;    /** @var list<array{times: list<float|null>, syl: array<int, array{text: string, times: list<float|null>}>, next: int}> */    private array $undoStack = [];    /** @var list<array{times: list<float|null>, syl: array<int, array{text: string, times: list<float|null>}>, next: int}> */    private array $redoStack = [];    private bool $spaceListened = false;    protected function loaded(array $params = []): void    {        if (!$this->spaceListened) {            // Space: the next syllable (not while typing the lyrics)            $this->spaceListened = true;            $this->engine->input->on('key', function (int $sym): void {                if ($sym === \SDLK_SPACE && $this->scenes()->current() === $this && !($this->focused() instanceof TextBox) && $this->synced->selected >= 0) {                    $this->onSylStampClick($this->sylStamp);                }            });        }        $this->quitAskedFor = null;        $this->inView = -1;        $this->synced->scrollY = 0;        $this->undoStack = $this->redoStack = [];        $this->next = -1;        $file = $this->wz->player->file;        $this->song->text = $file === null ? 'Pas de morceau : choisir un morceau dans la playlist d\'abord'            : Text::baseName($file) . ($this->wz->tag->artist !== '' ? '  -  ' . $this->wz->tag->artist . ' - ' . $this->wz->tag->title : '');        $lyrics = $this->wz->lyrics;        $this->syl = [];        $this->sylLine = -1;        $this->sylAt = -1;        if ($lyrics !== null && !$lyrics->isEmpty()) {            $this->fillFrom($lyrics);            $this->status->text = ($lyrics->synced ? 'Paroles chargées : ' : 'Paroles non synchronisées chargées (« Démarrer la synchro » pour leur donner des temps) : ')                . Text::baseName($this->wz->lyricsFile);        } else {            $this->text->text = '';            $this->times = [];            $this->status->text = 'Taper ou coller les paroles (ou « Chercher sur internet… »), puis « Démarrer la synchro ».';        }        $this->lastText = $this->text->text;        foreach ([$this->start, $this->stamp, $this->back, $this->pause, $this->save] as $b) {            $b->enabled = $file !== null;        }        $this->refreshList();        $this->savedLyr = $this->preview()->toLyr();        $this->hideOnPhone('hint', 'auto');     // the keys of a keyboard: a finger taps the buttons; no Whisper on a phone    }    /**     * Lyrics into the editor: synchronised ones, their lines sung with their times (and the moments of their syllables);     * without times, every line as it is (the blanks between the verses kept), no time.     */    private function fillFrom(\App\Model\Lyrics $lyrics): void    {        $this->syl = [];        $this->sylLine = -1;        $this->sylAt = -1;        $this->times = [];        if (!$lyrics->synced) {            $this->text->text = implode("\n", $lyrics->texts());            $this->refreshList();            return;        }        // the lines sung only (an empty line kept its time: the times went one line late), their syllables' moments apart        $texts = [];        foreach ($lyrics->lines as $k => [$time, $raw]) {            $plain = \App\Model\Karaoke::plain((string)$raw);            if ($plain === '') {                continue;            }            if (\App\Model\Karaoke::enhanced((string)$raw) !== null) {                [, $syllableTimes] = \App\Model\Karaoke::timing((string)$raw, (float)$time, (float)($lyrics->lines[$k + 1][0] ?? $time + 6));                $this->syl[count($texts)] = ['text' => $plain, 'times' => $syllableTimes];            }            $texts[] = $plain;            $this->times[] = (float)$time;        }        $this->text->text = implode("\n", $texts);        $this->refreshList();    }    /** "Chercher sur internet…": the search of lyrics; the one chosen comes back into the editor (resume()). */    public function onWebSearchClick(Button $sender): void    {        $file = $this->wz->player->file;        if ($file === null) {            $this->status->text = 'Choisissez d\'abord un morceau dans la playlist.';            return;        }        $this->scenes()->push(LyricsSearchForm::class, ['song' => $this->wz->playlist->current() ?? $file, 'editor' => true]);    }    /** Back from the search: the candidate chosen fills the editor (nothing saved yet). */    public function resume(mixed $result = null): void    {        parent::resume($result);        if (!is_array($result)) {            return;        }        $lyrics = $result['lyrics'] ?? null;        if (!$lyrics instanceof \App\Model\Lyrics) {            $lyrics = \App\Model\Lyrics::fromText((string)($result['text'] ?? ''));        }        if ($lyrics === null || $lyrics->isEmpty()) {            return;        }        $this->snapshot();        $this->next = -1;        $this->fillFrom($lyrics);        $this->lastText = $this->text->text;        $this->quitAskedFor = null;        $this->status->text = 'Paroles de ' . ($result['sourceName'] ?? 'Internet') . ($lyrics->synced ? ' (synchronisées)' : ' (non synchronisées : « Démarrer la synchro » pour leur donner des temps)')            . ' dans l\'éditeur : vérifier, puis Enregistrer.';    }    /** Lines or times changed since the lyrics were read or saved. */    public function hasChanges(): bool    {        return $this->preview()->toLyr() !== $this->savedLyr;    }    // undo / redo of the times ----------------------------------------------------------------------------------------    /** Before a change of the times: what they were, for Ctrl+Z. */    private function snapshot(): void    {        $this->undoStack[] = ['times' => $this->times, 'syl' => $this->syl, 'next' => $this->next];        while (count($this->undoStack) > self::HISTORY) {            array_shift($this->undoStack);        }        $this->redoStack = [];    }    /** @param array{times: list<float|null>, syl: array<int, array{text: string, times: list<float|null>}>, next: int} $state */    private function restore(array $state): void    {        $this->times = $state['times'];        $this->syl = $state['syl'];        $this->next = $state['next'];        $this->refreshList();    }    public function undoTimes(): bool    {        $state = array_pop($this->undoStack);        if ($state === null) {            $this->status->text = 'Rien à annuler.';            return false;        }        $this->redoStack[] = ['times' => $this->times, 'syl' => $this->syl, 'next' => $this->next];        $this->restore($state);        $this->status->text = 'Temps annulés (' . count($this->undoStack) . ' de plus possible' . (count($this->undoStack) > 1 ? 's' : '') . ').';        return true;    }    public function redoTimes(): bool    {        $state = array_pop($this->redoStack);        if ($state === null) {            $this->status->text = 'Rien à rétablir.';            return false;        }        $this->undoStack[] = ['times' => $this->times, 'syl' => $this->syl, 'next' => $this->next];        $this->restore($state);        $this->status->text = 'Temps rétablis.';        return true;    }    /** @return array{0: int, 1: int} how many steps Ctrl+Z / Ctrl+Y have */    public function history(): array    {        return [count($this->undoStack), count($this->redoStack)];    }    // the keys --------------------------------------------------------------------------------------------------------    public function handle(Pointer $p): void    {        if ($p->keys !== [] && !($this->focused() instanceof TextBox) && $this->overlay === null) {            $rest = [];            foreach ($p->keys as $key) {                if ($key === Pointer::SPACE) {                    continue;    // Espace: the next syllable (the key listener), never also a click of the focused button                }                if (($key === Pointer::RETURN || $key === Pointer::KP_ENTER) && !$p->ctrl && $this->focused() === $this->synced                    && $this->wz->player->state === Player::PLAYING) {                    $this->onStampClick($this->stamp);    // Entrée on the list while it plays: a time, not a jump back                    continue;                }                if (!$this->shortcut($key, $p->ctrl, $p->shift)) {                    $rest[] = $key;                }            }            $p->keys = $rest;        } elseif ($p->ctrl && $p->pressed(115)) {            $p->keys = array_values(array_diff($p->keys, [115]));    // Ctrl+S from the text too            $this->onSaveClick($this->save);        }        parent::handle($p);    }    /** A key of the editor (out of the text of the lyrics). True when it was one. */    public function shortcut(int $sym, bool $ctrl = false, bool $shift = false): bool    {        if ($ctrl) {            return match (true) {                $sym === 122 && !$shift => $this->undoTimes() || true,       // Ctrl+Z                $sym === 121, $sym === 122 => $this->redoTimes() || true,    // Ctrl+Y, Ctrl+Maj+Z                $sym === 115 => $this->saved(),                              // Ctrl+S                default => false,            };        }        if ($sym === Pointer::LEFT || $sym === Pointer::RIGHT) {            $this->nudge(($sym === Pointer::LEFT ? -1 : 1) * ($shift ? 10 : 100));            return true;        }        return false;    }    private function saved(): bool    {        $this->onSaveClick($this->save);        return true;    }    /** @return list<string> the lines typed (the empty ones are not sung) */    public function lines(): array    {        return array_values(array_filter(array_map('trim', preg_split('/\r\n|\r|\n/', $this->text->text) ?: []), fn (string $l) => $l !== ''));    }    private function refreshList(): void    {        $lines = $this->lines();        $this->times = array_slice(array_pad($this->times, count($lines), null), 0, count($lines));        $this->synced->items = array_map(fn (string $line, ?float $t) => ($t === null ? '[   ?   ]' : sprintf('[ %6.2f ]', $t)) . '  ' . $line, $lines, $this->times);        if ($this->next >= 0) {            $this->synced->selected = min($this->next, count($lines) - 1);        }    }    protected function tick(float $dt): void    {        $t = $this->wz->transcriber;        if ($t !== null) {            $this->auto->enabled = $this->web->enabled = !$t->busy() && $this->wz->player->file !== null;            $this->web->props['visible'] = \App\Media\Transcriber::claude() !== null;            if ($this->waitTranscriber) {                $this->status->text = $t->describe();                if (!$t->busy()) {                    $this->waitTranscriber = false;                    if ($t->state === 'done') {                        $this->loaded();      // the lyrics made: in the editor, ready to be put right                        $this->status->text = $t->describe() . '  -  à vérifier, puis Enregistrer';                    }                }            }        } else {            $this->auto->props['visible'] = $this->web->props['visible'] = false;        }        parent::tick($dt);        $p = $this->wz->player;        $t = $p->position;        $this->clock->text = sprintf('%02d:%05.2f', intdiv((int)$t, 60), fmod($t, 60));        if ($this->text->text !== $this->lastText) {            $this->lastText = $this->text->text;            $this->refreshList();        }        $this->keepChosenInView();        $this->showStrip();        $lines = $this->lines();        if ($this->next >= 0) {            $this->now->text = $this->next < count($lines) ? 'À donner : ' . $lines[$this->next] : 'Toutes les lignes ont leur temps : Enregistrer.';        } else {            // the test: the line of this moment, as the lyrics bar will show it            $this->now->text = $this->preview()->lineAt($t);        }    }    /** the line of the list last brought in sight */    private int $inView = -1;    /** The line chosen (the next one to give while syncing) comes in sight when it changes; the wheel is free otherwise. */    private function keepChosenInView(): void    {        $line = $this->synced->selected;        if ($line === $this->inView || $this->synced->h <= 0) {            return;        }        $this->inView = $line;        if ($line >= 0) {            $rh = $this->synced->rowHeight($this->theme);            $this->synced->scrollY = max(min($this->synced->scrollY, $line * $rh), ($line + 1) * $rh - $this->synced->h + 2);        }    }    /** The lyrics as they are now (lines with a time; no line has one yet: the lines without times). */    public function preview(): Lyrics    {        if (array_filter($this->times, fn (?float $t) => $t !== null) === []) {            $plain = Lyrics::fromText($this->text->text);            if ($plain !== null && !$plain->synced) {                return $plain;            }            return new Lyrics([], false);        }        $out = [];        foreach ($this->lines() as $i => $line) {            if (isset($this->times[$i])) {                $out[] = [(float)$this->times[$i], $this->withSyllables($i, $line)];            }        }        usort($out, fn (array $a, array $b) => $a[0] <=> $b[0]);        return new Lyrics($out);    }    // the syllables ---------------------------------------------------------------------------------------------------    /** @var array<int, array{text: string, times: list<float|null>}> the moments of the syllables of a line (its text then) */    private array $syl = [];    /** the line shown in the strip, the syllable chosen in it */    private int $sylLine = -1;    public int $sylAt = -1;    /** @return list<string> */    private function syllablesOf(int $line): array    {        return \App\Model\Karaoke::syllables($this->lines()[$line] ?? '');    }    /** @return list<float|null> its syllables' moments: given, else estimated from the line's time (null: the line has none) */    public function syllableTimes(int $line): array    {        $text = $this->lines()[$line] ?? '';        if (isset($this->syl[$line]) && $this->syl[$line]['text'] === $text) {            return $this->syl[$line]['times'];        }        $start = $this->times[$line] ?? null;        if ($start === null) {            return array_fill(0, count($this->syllablesOf($line)), null);        }        $next = null;        for ($k = $line + 1; $k < count($this->times) && $next === null; $k++) {            $next = $this->times[$k];        }        return \App\Model\Karaoke::timing($text, (float)$start, (float)($next ?? $start + 6))[1];    }    /** One syllable's moment given (the first one is the line's own). */    private function setSyllable(int $line, int $k, float $time): void    {        $times = $this->syllableTimes($line);        if (!array_key_exists($k, $times)) {            return;        }        $times[$k] = max(0.0, round($time, 3));        $this->syl[$line] = ['text' => $this->lines()[$line] ?? '', 'times' => $times];        if ($k === 0) {            $this->times[$line] = $times[0];        }        $this->refreshList();    }    /** The line as saved: with the moment of each syllable when they were given (<mm:ss.xx>syl: an enhanced LRC line). */    private function withSyllables(int $line, string $text): string    {        if (!isset($this->syl[$line]) || $this->syl[$line]['text'] !== $text) {            return $text;        }        $out = '';        foreach ($this->syllablesOf($line) as $k => $s) {            $t = $this->syl[$line]['times'][$k] ?? null;            $out .= ($t === null ? '' : sprintf('<%02d:%05.2f>', intdiv((int)$t, 60), fmod((float)$t, 60))) . $s;        }        return $out;    }    private function showStrip(): void    {        $line = $this->synced->selected;        if ($line !== $this->sylLine) {            $this->sylLine = $line;            $this->sylAt = $line >= 0 ? 0 : -1;        }        $this->strip->props['syllables'] = $line >= 0 ? $this->syllablesOf($line) : [];        $this->strip->props['times'] = $line >= 0 ? $this->syllableTimes($line) : [];        $this->strip->props['selected'] = $this->sylAt;        $this->strip->props['now'] = $this->wz->player->position;        foreach ([$this->m100, $this->m10, $this->p10, $this->p100, $this->replay, $this->sylStamp, $this->estimate] as $b) {            $b->enabled = $line >= 0 && $this->wz->player->file !== null;        }    }    public function onStripSelect(\App\Gui\SyllableStrip $sender, int $index): void    {        $this->sylAt = $index;    }    /** While it plays: the syllable chosen begins now; the next one is chosen (the next line after the last one). */    public function onSylStampClick(Button $sender): void    {        $line = $this->synced->selected;        if ($line < 0) {            return;        }        $this->snapshot();        $this->setSyllable($line, max(0, $this->sylAt), $this->wz->player->position);        $this->sylAt = max(0, $this->sylAt) + 1;        if ($this->sylAt >= count($this->syllablesOf($line)) && $line + 1 < count($this->lines())) {            $this->synced->selected = $line + 1;            $this->sylLine = $line + 1;            $this->sylAt = 0;        }    }    /** -100 / -10 / +10 / +100 ms on the syllable chosen (the first one: the line). */    public function onNudgeClick(Button $sender): void    {        $this->nudge(['m100' => -100, 'm10' => -10, 'p10' => 10, 'p100' => 100][(string)$sender->props['id']] ?? 0);    }    /** The time of the line chosen (its first syllable) or of the syllable chosen, moved by some milliseconds. */    public function nudge(int $ms): void    {        $line = $this->synced->selected;        if ($line < 0 || $ms === 0) {            return;        }        $at = max(0, $this->sylAt);        if ($at === 0 && !isset($this->syl[$line])) {            // the line itself: its syllables stay estimated (not written one by one in the file)            $current = $this->times[$line] ?? null;            if ($current === null) {                $this->status->text = 'Cette ligne n\'a pas encore de temps : Entrée pendant la lecture pour lui en donner un.';                return;            }            $this->snapshot();            $this->times[$line] = max(0.0, round((float)$current + $ms / 1000, 3));            $this->refreshList();            $this->status->text = sprintf('Ligne « %s » : %.2f s (%+d ms)', $this->lines()[$line] ?? '', $this->times[$line], $ms);            return;        }        $current = $this->syllableTimes($line)[$at] ?? null;        if ($current === null) {            return;        }        $this->snapshot();        $this->setSyllable($line, $at, (float)$current + $ms / 1000);        $this->status->text = sprintf('Syllabe « %s » : %.2f s (%+d ms)', trim($this->syllablesOf($line)[$at] ?? ''), max(0.0, (float)$current + $ms / 1000), $ms);    }    /** Heard again from a little before the syllable chosen. */    public function onReplayClick(Button $sender): void    {        $line = $this->synced->selected;        $t = $line >= 0 ? ($this->syllableTimes($line)[max(0, $this->sylAt)] ?? $this->times[$line] ?? null) : null;        if ($t === null) {            return;        }        $this->wz->seek(max(0, (float)$t - 1.5));        if ($this->wz->player->state !== Player::PLAYING) {            $this->wz->play();        }    }    /** The syllables of the line back to their estimated moments. */    public function onEstimateClick(Button $sender): void    {        $this->snapshot();        unset($this->syl[$this->synced->selected]);        $this->refreshList();    }    public function onStartClick(Button $sender): void    {        if ($this->lines() === []) {            $this->status->text = 'Il faut d\'abord les paroles, une ligne par ligne chantée.';            return;        }        $this->snapshot();        $this->times = [];        $this->next = 0;        $this->wz->seek(0);        $this->wz->play();        $this->refreshList();        $this->setFocus($this->stamp);        $this->status->text = 'Appuyer sur Entrée (ou « Ligne suivante ») au début de chaque ligne chantée.';    }    /** The next line gets the time of the song now (not syncing: from the line chosen, while the song plays). */    public function onStampClick(Button $sender): void    {        $lines = $this->lines();        if ($this->next < 0) {            $chosen = $this->synced->selected;            if ($chosen < 0 || $chosen >= count($lines) || $this->wz->player->state !== Player::PLAYING) {                $this->status->text = $lines === [] ? 'Il faut d\'abord les paroles, une ligne par ligne chantée.'                    : '« Démarrer la synchro », ou choisir une ligne pendant la lecture puis Entrée pour la synchroniser à partir d\'elle.';                return;            }            $this->next = $chosen;        }        if ($this->next >= count($lines)) {            return;        }        $this->snapshot();        $this->times[$this->next] = round($this->wz->player->position, 7);        $this->next++;        if ($this->next >= count($lines)) {            $this->status->text = 'Synchro finie : « Enregistrer », ou double-cliquer une ligne pour la réécouter.';        }        $this->refreshList();        $this->setFocus($this->stamp);    }    public function onBackClick(Button $sender): void    {        $this->wz->seek($this->wz->player->position - 5);        // the lines given after that moment are given again        if ($this->next > 0 && ($this->times[$this->next - 1] ?? 0) > $this->wz->player->position) {            $this->snapshot();            while ($this->next > 0 && ($this->times[$this->next - 1] ?? 0) > $this->wz->player->position) {                $this->next--;                $this->times[$this->next] = null;            }            $this->refreshList();        }    }    public function onPauseClick(Button $sender): void    {        $this->wz->togglePause();    }    public function onSyncedActivate(ListBox $sender, int $index, string $item): void    {        if (isset($this->times[$index])) {            $this->wz->seek(max(0, (float)$this->times[$index] - 1));            if ($this->wz->player->state !== Player::PLAYING) {                $this->wz->play();            }        }    }    /** Whisper listens (and Claude puts its words right): the lines and their times come into the editor. */    public function onAutoClick(Button $sender): void    {        $this->waitTranscriber = $this->wz->transcribe();    }    /** Claude searches the web for the real lyrics (aligned on Whisper when it is there). */    public function onWebClick(Button $sender): void    {        $this->waitTranscriber = $this->wz->transcribe('internet');    }    private bool $waitTranscriber = false;    public function onClearClick(Button $sender): void    {        $this->snapshot();        $this->syl = [];        $this->times = [];        $this->next = -1;        $this->refreshList();    }    public function onSaveClick(Button $sender): void    {        $file = $this->wz->player->file;        $lyrics = $this->preview();        if ($file === null || $lyrics->isEmpty()) {            $this->status->text = $file === null ? 'Rien à enregistrer : pas de morceau.' : 'Rien à enregistrer : pas de paroles.';            return;        }        // the song's own copy (var/lyr/<name>-<crc>.lyr, looked at first): its translations kept for the lines unchanged        $target = $this->wz->saveLyrics($this->wz->playlist->current() ?? $file, clone $lyrics);        if ($target === null) {            $this->status->text = 'Paroles NON enregistrées : impossible d\'écrire dans ' . $this->wz->storagePath('lyr') . ' (disque plein ou en lecture seule ?)';            return;        }        $this->wz->refreshLyrics();        $this->savedLyr = $lyrics->toLyr();        $this->quitAskedFor = null;        $this->status->text = 'Enregistré' . ($lyrics->synced ? '' : ' (non synchronisées)') . ' : ' . $target;    }    /** Saved, then sent to the marketplace (everybody gets them with this song). */    public function onPublishClick(Button $sender): void    {        $this->onSaveClick($this->save);        if ($this->wz->lyrics !== null && !$this->hasChanges()) {            $this->scenes()->push(MarketForm::class, ['kind' => 'lyrics']);        }    }    public function onQuitClick(Button $sender): void    {        $now = $this->preview()->toLyr();        if ($now !== $this->savedLyr && $this->quitAskedFor !== $now) {            $this->quitAskedFor = $now;            $this->status->text = 'Pas enregistré : « Enregistrer » (Ctrl+S), ou Fermer (Échap) encore une fois pour perdre les changements.';            return;        }        $this->scenes()->switchTo(MainForm::class, [], false);    }}