DE
apps/winzik / tests / LyricsUiTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Core\WinZik;use App\Form\LyricsEditorForm;use App\Form\LyricsSearchForm;use App\Form\MainForm;use App\Gui\LyricsBar;use App\Media\LyricsTranslator;use App\Media\Process;use App\Model\Lyrics;use JumPHP\Gui\Pointer;use JumPHP\Http\HttpResponse;use Tests\Lyrics\FakeLyricsHttp;/** * The lyrics on the desktop: the search dialog (fake Internet), the editor filled from it, the lyrics without times as * a page to scroll, the translations under the lines, the dot of the play list, "only the songs with lyrics", the * buttons on the left of the karaoke and Escape. */final class LyricsUiTest extends PlayerTestCase{    private const PLAIN = "Sous le ciel de la ville\nLes lumières s'allument\n\nEt la nuit nous emporte\nLes lumières s'allument";    private const ENGLISH = "I walk alone tonight\nAnd the city is my friend\n\nYou know that I will stay\nAnd the city is my friend";    private const FRENCH = [0 => 'Je marche seul ce soir', 1 => 'Et la ville est mon amie', 3 => 'Tu sais que je resterai', 4 => 'Et la ville est mon amie'];    /** @var list<string> the lyrics files written by a test (removed after it) */    private array $written = [];    protected function tearDown(): void    {        if (isset($this->wz)) {            foreach ($this->written as $file) {                @unlink($this->wz->lyricsCachePath($file));            }            $this->wz->options['lyricsOnly'] = false;            $this->wz->options['lyricsShowTranslation'] = true;            $this->wz->ui['lyrics']['full'] = false;            $this->wz->stop();            @unlink($this->wz->storagePath('stats.json'));            (new \ReflectionProperty(WinZik::class, 'stats'))->setValue($this->wz, null);        }        parent::tearDown();    }    /** WinZik started, its windows unrolled (the pictures show them whole). */    protected function startPlayer(array $params = []): void    {        parent::startPlayer($params);        $this->game->run(90);    }    private static function json(mixed $data): HttpResponse    {        return new HttpResponse(200, (string)json_encode($data), ['content-type' => 'application/json']);    }    /** LRCLIB answers $hits, everything else is not found; no Claude. */    private function fakeLrclib(array $hits): FakeLyricsHttp    {        $engine = $this->form->engineOrNull();        self::assertNotNull($engine);        $http = new FakeLyricsHttp($engine->bridge, fn (string $m, string $url) => str_starts_with($url, 'https://lrclib.net/api/search?')            ? self::json($hits) : new HttpResponse(404, ''));        $this->wz->useLyricsServices($http, fn (array $cmd) => Process::finished($cmd, [], 1), false);        (new \ReflectionProperty(WinZik::class, 'market'))->setValue($this->wz, null);     // a fake marketplace of a test before: none        LyricsTranslator::forgetCache();        return $http;    }    /** The song "partage.mp3" playing, without lyrics. */    private function playPartage(): string    {        $this->wz->playIndex(3);        $file = (string)$this->wz->playlist->current();        self::assertStringEndsWith('partage.mp3', $file);        @unlink($this->wz->lyricsCachePath($file));        $this->written[] = $file;        $this->wz->refreshLyrics();        self::assertNull($this->wz->lyrics);        return $file;    }    /** Lyrics written for a song (through the core, as the UI does). */    private function give(string $file, Lyrics $lyrics): void    {        $this->written[] = $file;        self::assertNotNull($this->wz->saveLyrics($file, $lyrics, false));    }    private function scene(): object    {        $this->game->run(1);        return $this->game->scene();    }    private function key(int $key, string $text = ''): void    {        $p = new Pointer();        if ($key !== 0) {            $p->keys = [$key];        }        if ($text !== '') {            $p->text = [$text];        }        $this->game->scene()->handle($p);        $this->game->run(1);    }    public function testTheSearchDialogListsTheCandidatesAndImportsThemSyncedOrPlain(): void    {        $this->startPlayer();        $this->fakeLrclib([            ['id' => 1, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'albumName' => 'Live', 'duration' => 200, 'plainLyrics' => self::PLAIN, 'syncedLyrics' => null],            ['id' => 2, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'albumName' => 'Live', 'duration' => 200,                'plainLyrics' => 'Un', 'syncedLyrics' => "[00:01.00] On partage la musique\n[00:04.00] Des paroles qui tombent du ciel"],        ]);        $file = $this->playPartage();        $this->desk->lyricsSearch($file);        $form = $this->scene();        self::assertInstanceOf(LyricsSearchForm::class, $form);        self::assertSame($file, $form->songFile);        self::assertNotSame('', $form->title->text, 'the title filled in (tag or file name)');        $this->game->run(3);        self::assertCount(2, $form->candidates);        self::assertStringStartsWith('SYNC', $form->items->items[0], 'the synchronised ones first');        self::assertStringStartsWith('≡', $form->items->items[1]);        self::assertStringContainsString('LRCLIB : trouvé', $form->sources->text);        self::assertStringContainsString('On partage la musique', $form->preview->text, 'the first lines of the one chosen');        $this->game->shot('lyrics-search');        // synchronised: the times kept, then "Ouvrir dans l'éditeur" is offered        $form->click($form->import);        $this->game->run(1);        self::assertTrue($this->wz->lyricsSynced());        self::assertSame([[1.0, 'On partage la musique'], [4.0, 'Des paroles qui tombent du ciel']], $this->wz->lyrics?->lines);        self::assertTrue((bool)($form->editor->props['visible'] ?? false));        // plain: lines to scroll        $form->items->selected = 1;        $form->onItemsChange($form->items, 1, '');        $form->click($form->import);        $this->game->run(1);        self::assertNotNull($this->wz->lyrics);        self::assertFalse($this->wz->lyricsSynced());        self::assertStringContainsString('non synchronisées', $form->status->text);        // into the editor: the lines without times        $form->click($form->editor);        $editor = $this->scene();        $this->game->run(2);        $editor = $this->game->scene();        self::assertInstanceOf(LyricsEditorForm::class, $editor);        self::assertSame(['Sous le ciel de la ville', 'Les lumières s\'allument', 'Et la nuit nous emporte', 'Les lumières s\'allument'], $editor->lines());        self::assertStringContainsString("allument\n\nEt la nuit", $editor->text->text, 'the blank between the verses kept');        self::assertFalse($editor->preview()->synced);        self::assertFalse($editor->hasChanges());        self::assertStringStartsWith('[   ?   ]', $editor->synced->items[0], 'no time yet');    }    public function testTheEditorTakesACandidateFromTheSearchAndSavesKeepingTheTranslations(): void    {        $this->startPlayer();        $this->fakeLrclib([['id' => 5, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'duration' => 0,            'syncedLyrics' => "[00:01.00] I walk alone tonight\n[00:03.50] And the city is my friend\n[00:06.00] You know that I will stay\n[00:08.00] And the city is my friend"]]);        $file = $this->playPartage();        $plain = Lyrics::fromText(self::ENGLISH);        self::assertNotNull($plain);        $plain->language = 'en';        $plain->setTranslations(self::FRENCH, 'fr');        $this->give($file, $plain);        self::assertFalse($this->wz->lyricsSynced());        $this->form->openLyricsEditor();        $editor = $this->scene();        $this->game->run(1);        $editor = $this->game->scene();        self::assertInstanceOf(LyricsEditorForm::class, $editor);        self::assertCount(4, $editor->lines(), 'the lines without times, as plain lines');        // "Chercher sur internet…": the synchronised candidate comes into the editor with its times        $editor->click($editor->webSearch);        $search = $this->scene();        self::assertInstanceOf(LyricsSearchForm::class, $search);        self::assertTrue($search->forEditor);        self::assertSame('Mettre dans l\'éditeur', $search->import->text);        $this->game->run(3);        self::assertCount(1, $search->candidates);        $search->click($search->import);        $this->game->run(2);        self::assertSame($editor, $this->game->scene());        self::assertTrue($editor->preview()->synced, 'the times kept');        self::assertSame([1.0, 3.5, 6.0, 8.0], array_map(fn (array $l) => $l[0], $editor->preview()->lines));        self::assertTrue($editor->hasChanges());        // saved through the core: the translations of the lines that did not change are still there        $editor->click($editor->save);        $this->game->run(1);        $saved = Lyrics::load($this->wz->lyricsCachePath($file));        self::assertNotNull($saved);        self::assertTrue($saved->synced);        self::assertSame('fr', $saved->translationLang);        self::assertSame('Je marche seul ce soir', $saved->translation(0));        self::assertSame('Tu sais que je resterai', $saved->translation(2));        self::assertFalse($editor->hasChanges());        self::assertTrue($this->wz->lyricsSynced());    }    public function testLyricsWithoutTimesAreAPageToScrollOnTheWholeScreen(): void    {        $this->startPlayer();        $this->fakeLrclib([]);        $file = $this->playPartage();        $text = '';        for ($v = 1; $v <= 6; $v++) {            $text .= "Couplet $v : sous le ciel de la ville\nLes lumières s'allument une à une\nEt la nuit nous emporte au loin\nLa musique ne s'arrête pas\n\n";        }        $lyrics = Lyrics::fromText($text);        self::assertNotNull($lyrics);        $this->give($file, $lyrics);        $bar = $this->desk->lyrics;        self::assertInstanceOf(LyricsBar::class, $bar);        self::assertTrue($bar->unsynced());        $this->wz->ui['lyrics']['visible'] = true;        $this->game->run(2);        // the bar: the badge of lyrics without times, no -0.5 s / +0.5 s        self::assertArrayHasKey('sync', $bar->controls());        self::assertArrayNotHasKey('earlier', $bar->controls());        $this->game->shot('lyrics-bar-unsynced');        // the wheel over the bar: the line before / after (the song is not followed for a moment)        $line = $bar->barIndex();        $bar->wheel(-1);        self::assertSame($line + 1, $bar->barIndex());        $this->game->run((int)(LyricsBar::FOLLOW_AFTER * 60) + 5);        self::assertTrue($bar->followsSong(), 'then it follows the song again');        // the whole screen: the page follows the line about sung, slowly        $bar->toggleFull();        $this->wz->seek($this->wz->player->duration() * 0.6);        $this->game->run(240);        self::assertTrue($bar->followsSong());        $followed = $bar->page;        self::assertGreaterThan(100, $followed, 'scrolled down to the verse sung');        $this->game->shot('karaoke-unsynced');        // the wheel: up, and it stays there a moment        self::assertTrue($bar->wheel(3));        self::assertEqualsWithDelta($followed - 144, $bar->page, 1);        self::assertFalse($bar->followsSong());        $this->game->run(30);        self::assertEqualsWithDelta($followed - 144, $bar->page, 1, 'not followed while scrolled by hand');        // dragged by the mouse: the page goes with it        [$px, $py, $pw, $ph] = $bar->controls()['page'];        $before = $bar->page;        [$fx, $fy] = $this->at($bar, $px + $pw / 2, $py + $ph / 2);        [, $ty] = $this->at($bar, $px + $pw / 2, $py + $ph / 2 - 80);        $this->dragView($fx, $fy, $fx, $ty);        self::assertEqualsWithDelta($before + 80, $bar->page, 2);        self::assertTrue($this->wz->ui['lyrics']['full'], 'a drag never closes it');        // "Synchroniser dans l'éditeur"        $this->clickControl($bar, 'sync');        $this->game->run(2);        self::assertInstanceOf(LyricsEditorForm::class, $this->game->scene());    }    public function testTheTranslationIsDrawnUnderEachLineAndTTogglesIt(): void    {        $this->startPlayer();        $this->fakeLrclib([]);        $file = $this->playPartage();        $lyrics = new Lyrics([[0.5, 'I walk alone tonight'], [3.0, 'And the city is my friend'], [6.0, 'You know that I will stay'], [9.0, 'And the city is my friend']]);        $lyrics->language = 'en';        $lyrics->setTranslations([0 => 'Je marche seul ce soir', 1 => 'Et la ville est mon amie', 2 => 'Tu sais que je resterai', 3 => 'Et la ville est mon amie'], 'fr');        $this->give($file, $lyrics);        $bar = $this->desk->lyrics;        self::assertNotNull($bar);        self::assertSame('Et la ville est mon amie', $bar->translationOf(1));        $this->wz->ui['lyrics']['visible'] = true;        $this->wz->seek(3.4);        $this->game->run(3);        $this->game->shot('lyrics-bar-translation');        $bar->toggleFull();        $this->wz->seek(3.4);        $this->game->run(40);        $this->game->shot('karaoke-translation');        // T: hidden, then shown again        $this->key(0, 't');        self::assertFalse($this->wz->showsTranslation());        self::assertSame('', $bar->translationOf(1));        $this->clickControl($bar, 'trans');        self::assertTrue($this->wz->showsTranslation());        // the menu: the toggle and "Traduire les paroles maintenant"        $labels = array_column($this->desk->menuItems()[0]['sub'], 'label');        self::assertContains('Afficher la traduction (T)', $labels);        self::assertContains('Traduire les paroles maintenant (Français)', $labels);    }    public function testTheDotOfALineShowsItsLyricsAndOpensTheirSearch(): void    {        $this->startPlayer();        $this->fakeLrclib([['id' => 9, 'trackName' => 'Chaine', 'artistName' => 'X', 'plainLyrics' => "Une ligne\nDeux lignes"]]);        $list = $this->desk->playlist;        self::assertNotNull($list);        $items = $this->wz->playlist->items;        // a song with lines without times, one translated, one with nothing        $plain = Lyrics::fromText(self::PLAIN);        self::assertNotNull($plain);        $this->give($items[2], $plain);        $translated = new Lyrics([[1.0, 'I walk alone tonight'], [3.0, 'And the city is my friend']]);        $translated->setTranslations([0 => 'Je marche seul ce soir', 1 => 'Et la ville est mon amie'], 'fr');        $this->give($items[3], $translated);        @unlink($this->wz->lyricsCachePath($items[1]));        $this->wz->refreshLyrics();        self::assertSame('synced', $list->lyricsMark($items[0]), 'winzik.lyr');        self::assertSame('none', $list->lyricsMark($items[1]));        self::assertSame('plain', $list->lyricsMark($items[2]));        self::assertSame('translated', $list->lyricsMark($items[3]));        $this->game->run(2);        $this->game->shot('playlist-lyrics-dots');        // the tooltip of the dot        $row = $list->lineOf(2) - $list->top();        $list->hover(5, \App\Gui\PlaylistWindow::LIST_TOP + $row * \App\Gui\PlaylistWindow::ROW_HEIGHT + 5);        self::assertSame('Paroles non synchronisées : cliquer pour chercher les paroles', $list->tip('list'));        // a click on the dot of the line: the search for that song (it does not play)        $playing = $this->wz->playlist->active;        $row = $list->lineOf(1) - $list->top();        $this->clickIn($list, 6, \App\Gui\PlaylistWindow::LIST_TOP + $row * \App\Gui\PlaylistWindow::ROW_HEIGHT + 6);        $form = $this->scene();        self::assertInstanceOf(LyricsSearchForm::class, $form);        self::assertSame($items[1], $form->songFile);        self::assertSame($playing, $this->wz->playlist->active, 'the line did not play');        $this->game->run(3);        self::assertCount(1, $form->candidates);        $form->click($form->quit);        $this->game->run(1);        self::assertInstanceOf(MainForm::class, $this->game->scene());    }    public function testOnlyTheSongsWithLyricsFromTheMenu(): void    {        $this->startPlayer();        $item = array_values(array_filter($this->desk->menuItems(), fn (array $i) => ($i['label'] ?? '') === 'Seulement les morceaux avec paroles'))[0] ?? null;        self::assertNotNull($item);        self::assertFalse($item['checked']);        $item['run']();        self::assertTrue($this->wz->playsLyricsOnly());        $again = array_values(array_filter($this->desk->menuItems(), fn (array $i) => ($i['label'] ?? '') === 'Seulement les morceaux avec paroles'))[0];        self::assertTrue($again['checked']);        $this->game->run(2);        $this->game->shot('playlist-lyrics-only');        $again['run']();        self::assertFalse($this->wz->playsLyricsOnly());    }    public function testTheKaraokeHasPreviousAndNextOnItsLeftAndEscapeClosesIt(): void    {        $this->startPlayer();        $this->wz->playIndex(0);        $bar = $this->desk->lyrics;        self::assertNotNull($bar);        $this->wz->ui['lyrics']['visible'] = true;        $bar->toggleFull();        $this->wz->seek(8.0);        $this->game->run(40);        $controls = $bar->controls();        foreach (['prev', 'play', 'next'] as $id) {            self::assertArrayHasKey($id, $controls);            self::assertLessThan(120, $controls[$id][0], 'on the left');            self::assertGreaterThanOrEqual(40, $controls[$id][2], 'big');        }        $this->game->shot('karaoke-buttons');        $this->clickControl($bar, 'next');        self::assertSame(1, $this->wz->playlist->active);        $this->clickControl($bar, 'prev');        self::assertSame(0, $this->wz->playlist->active);        $this->clickControl($bar, 'play');        self::assertSame(\App\Audio\Player::PAUSED, $this->wz->player->state);        $this->clickControl($bar, 'play');        self::assertSame(\App\Audio\Player::PLAYING, $this->wz->player->state);        self::assertTrue($bar->full());        $this->desk->playlist?->toggleSearch();      // even with the search of the play list open        $this->key(Pointer::ESCAPE);        self::assertFalse($bar->full(), 'Escape closes the whole screen');        $this->game->run(30);        self::assertSame((float)LyricsBar::HEIGHT, $bar->height());    }    public function testTheSearchDialogIsAWholeScreenOnTheOriginalPhone(): void    {        $this->startPlayer(['phone' => true]);        $this->fakeLrclib([['id' => 1, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'plainLyrics' => self::PLAIN]]);        $file = $this->playPartage();        $this->desk->lyricsSearch($file);        $form = $this->scene();        self::assertInstanceOf(LyricsSearchForm::class, $form);        self::assertNotNull($form->phoneScreen());        $this->game->run(3);        self::assertCount(1, $form->candidates);        $this->game->shot('original-phone-lyrics-search');        $this->key(Pointer::ESCAPE);        self::assertInstanceOf(MainForm::class, $this->scene(), 'back closes it');    }}