KO
apps/winzik / tests / MobileLyricsTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Core\Market;use App\Core\WinZik;use App\Form\MobileForm;use App\Media\LyricsTranslator;use App\Mobile\MobileView;use App\Model\Lyrics;use JumPHP\Gui\Pointer;use JumPHP\Http\HttpResponse;use JumPHP\Testing\GameTestCase;use Tests\Lyrics\FakeLyricsHttp;/** * The lyrics on the phone (390 x 844 dp): the page « Chercher des paroles » (fake Internet), the editor filled by a search * and saved through WinZik::saveLyrics(), the lyrics without times scrolled by the finger (portrait and landscape, a tap * does not seek), the translations under the lines (« Traduction »), the play list's marks and « Seulement avec paroles ». */final class MobileLyricsTest extends GameTestCase{    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 PARTAGE = 'assets/music/partage.mp3';    private MobileForm $form;    private MobileView $view;    private WinZik $wz;    private ?FakeLyricsHttp $http = null;    protected function tearDown(): void    {        if (isset($this->wz)) {            // the lyrics made here stay out of the other tests            foreach ($this->wz->playlist->items as $file) {                if (!str_ends_with((string)$file, 'winzik.mp3')) {                    @unlink($this->wz->lyricsCachePath((string)$file));                }            }            @unlink($this->wz->lyricsCachePath('assets/music/winzik.mp3'));            $this->wz->options['lyricsOnly'] = false;            $this->wz->stop();        }        parent::tearDown();    }    private function startPhone(array $params = []): void    {        $this->game->start(MobileForm::class, ['fresh' => true, 'phone' => true] + $params);        $form = $this->game->scene();        self::assertInstanceOf(MobileForm::class, $form);        $this->form = $form;        $view = $form->widget('view');        self::assertInstanceOf(MobileView::class, $view);        $this->view = $view;        $this->wz = $form->winzik();        $this->wz->playlist->shuffle = false;        $this->wz->notice = '';        foreach ($this->wz->playlist->items as $file) {            if (!str_ends_with((string)$file, 'winzik.mp3')) {                @unlink($this->wz->lyricsCachePath((string)$file));            }        }        @unlink($this->wz->lyricsCachePath('assets/music/winzik.mp3'));        $this->wz->refreshLyrics();        $this->game->run(3);    }    /** No real network: LRCLIB answers two versions of « Partage » (one with times, one without), the rest nothing. */    private function fakeInternet(?\Closure $route = null): void    {        $engine = $this->form->engineOrNull();        self::assertNotNull($engine);        $route ??= function (string $method, string $url): HttpResponse {            if (str_starts_with($url, 'https://lrclib.net/api/search?')) {                return self::json([                    ['id' => 1, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'albumName' => 'Demo', 'duration' => 120, 'instrumental' => false,                        'plainLyrics' => self::PLAIN, 'syncedLyrics' => null],                    ['id' => 2, 'trackName' => 'Partage', 'artistName' => 'WinZik Band', 'albumName' => 'Live', 'duration' => 121, 'instrumental' => false,                        'plainLyrics' => 'Un', 'syncedLyrics' => "[00:01.00] On partage la musique\n[00:04.00] Des paroles qui tombent du ciel"],                ]);            }            return new HttpResponse(404, '<html>none</html>');        };        $this->http = new FakeLyricsHttp($engine->bridge, $route);        $this->wz->useLyricsServices($this->http, fn (array $cmd) => \App\Media\Process::finished($cmd, [], 1), false);        (new \ReflectionProperty(WinZik::class, 'market'))->setValue($this->wz, new Market($this->http, 'https://market.test'));        LyricsTranslator::forgetCache();    }    private static function json(mixed $data): HttpResponse    {        return new HttpResponse(200, (string)json_encode($data), ['content-type' => 'application/json']);    }    private function line(string $file): int    {        $line = array_search($file, $this->wz->playlist->items, true);        self::assertIsInt($line, "$file in the play list");        return $line;    }    private function playPartage(float $at = 0.0): void    {        $this->wz->playIndex($this->line(self::PARTAGE));        if ($at > 0) {            $this->wz->seek($at);        }        $this->game->wait(0.3);    }    private function tap(string $id, mixed $data = null, int $frames = 2): void    {        $at = $this->view->at($id, $data);        self::assertNotNull($at, "$id " . json_encode($data) . ' is on the screen (' . implode(', ', $this->view->touchable()) . ')');        $this->form->clickAt($at[0], $at[1]);        $this->game->run($frames);    }    private function pointer(float $x, float $y, string $what): void    {        $p = new Pointer();        [$p->x, $p->y] = [$x, $y];        match ($what) {            'down' => [$p->down, $p->held] = [true, true],            'move' => $p->held = true,            default => $p->up = true,        };        $this->form->handle($p);    }    /** A finger along something touchable, up the (turned) screen by $dp dp (> 0: towards the end). */    private function drag(string $id, mixed $data, float $dp, int $steps = 5): void    {        $at = $this->view->at($id, $data);        self::assertNotNull($at, "$id on the screen");        $s = $this->view->screenRect()[2] / $this->view->W;        [$dx, $dy] = $this->view->turned() ? [$dp * $s, 0.0] : [0.0, -$dp * $s];        $this->pointer($at[0], $at[1], 'down');        for ($k = 1; $k <= $steps; $k++) {            $this->game->run(1);            $this->pointer($at[0] + $dx * $k / $steps, $at[1] + $dy * $k / $steps, 'move');        }        $this->pointer($at[0] + $dx, $at[1] + $dy, 'up');        $this->game->run(1);    }    /** The page scrolled until that row is on the screen. */    private function scrollPageTo(string $id, mixed $data = null): void    {        for ($y = 0.0; $y < 4000 && $this->view->at($id, $data) === null; $y += 150) {            $this->view->scroll['page:' . $this->view->screen] = $y;            $this->game->run(2);        }        self::assertNotNull($this->view->at($id, $data), "$id on the page");    }    private function shot(string $name): void    {        $this->game->run(1);        $file = $this->game->shot($name);        $image = @imagecreatefrompng($file);        if ($image === false) {            return;        }        [$x, $y, $w, $h] = $this->view->screenRect();        $crop = imagecrop($image, ['x' => (int)$x, 'y' => (int)$y, 'width' => (int)round($w), 'height' => (int)round($h)]);        if ($crop !== false) {            imagepng($crop, $file);        }    }    public function testTheSearchPageShowsTheCandidatesAndImportsOne(): void    {        $this->startPhone();        $this->fakeInternet();        $this->playPartage();        self::assertNull($this->wz->lyrics);        // « Pas de paroles · touchez pour en trouver »: the search, for that song        $this->tap('lyricsBox', null, 5);        self::assertSame('lyricsFind', $this->view->screen);        self::assertSame(self::PARTAGE, $this->view->lfFile);        self::assertNotSame('', trim($this->view->fields['lfTitle'] ?? ''), 'the title filled from the song');        $this->tap('field', 'lfArtist');        $this->view->fields['lfArtist'] = '';        $this->form->type('WinZik Band');        $this->view->fields['lfTitle'] = 'Partage';        $this->tap('lfStart', null, 4);        self::assertSame('', $this->view->field, 'the keyboard closed');        $search = $this->view->lfSearch;        self::assertNotNull($search);        self::assertTrue($search->done(), $search->describe());        self::assertCount(2, $search->candidates);        self::assertTrue($search->candidates[0]['synced'], 'the synchronised version first');        self::assertNotEmpty(array_filter($this->http->urls(), fn (string $u) => str_starts_with($u, 'https://lrclib.net/api/search?')), 'LRCLIB asked (no real network)');        $this->wz->notice = '';        $this->shot('mobile-paroles-recherche');        // the version without times: its preview sheet, then Importer        $this->tap('lfPick', 1, 15);        self::assertSame('lyPreview', $this->view->sheet);        self::assertNotNull($this->view->at('lfToEditor', 1), 'Importer dans l\'éditeur');        $this->shot('mobile-paroles-apercu');        $this->tap('lfImport', 1, 5);        self::assertSame('player', $this->view->screen, 'back where it came from');        self::assertNotNull($this->wz->lyrics);        self::assertFalse($this->wz->lyricsSynced());        self::assertSame('Sous le ciel de la ville', $this->wz->lyrics->texts()[0]);        self::assertFileExists($this->wz->lyricsCachePath(self::PARTAGE));        // from the play list: ⋮ of a song > Paroles…        $this->tap('tab', 'playlist', 3);        $winzik = $this->line('assets/music/winzik.mp3');        $this->tap('rowMore', $winzik, 15);        $this->tap('lyFind', $winzik, 5);        self::assertSame('lyricsFind', $this->view->screen);        self::assertSame('assets/music/winzik.mp3', $this->view->lfFile);        self::assertNull($this->view->lfSearch, 'a search of its own');        // and from the karaoke's sheet        $this->view->go('karaoke');        $this->game->run(2);        $this->tap('lyricsMenu', null, 15);        $this->tap('lyFind', null, 5);        self::assertSame('lyricsFind', $this->view->screen);        self::assertSame(self::PARTAGE, $this->view->lfFile);    }    public function testTheEditorIsFilledByASearchAndSavesThroughWinZik(): void    {        $this->startPhone();        $this->fakeInternet();        $this->playPartage();        $this->view->go('lyricsEdit');        $this->game->run(2);        self::assertSame('', $this->view->fields['edText']);        $this->tap('edSearch', null, 5);        self::assertSame('lyricsFind', $this->view->screen);        self::assertSame('editor', $this->view->lfFor);        $this->view->fields['lfArtist'] = 'WinZik Band';        $this->view->fields['lfTitle'] = 'Partage';        $this->tap('lfStart', null, 4);        $this->tap('lfPick', 1, 15);        self::assertNull($this->view->at('lfImport', 1), 'for the editor: only « Mettre dans l\'éditeur »');        $this->tap('lfToEditor', 1, 5);        self::assertSame('lyricsEdit', $this->view->screen, 'back to the editor');        self::assertSame(self::PLAIN, $this->view->fields['edText'], 'the text filled, its blank between verses kept');        self::assertCount(4, $this->view->edLines);        self::assertSame([null, null, null, null], $this->view->edTimes, 'no times yet');        $this->wz->notice = '';        $this->shot('mobile-editeur-recherche');        // saved as it is: lyrics without times, through saveLyrics (var/lyr, UTF-8, its language guessed)        $this->tap('edSaveText', null, 5);        self::assertSame('player', $this->view->screen);        self::assertNotNull($this->wz->lyrics);        self::assertFalse($this->wz->lyricsSynced());        $content = (string)file_get_contents($this->wz->lyricsCachePath(self::PARTAGE));        self::assertStringContainsString(Lyrics::UNSYNCED, $content);        self::assertStringContainsString('[LANGUE fr]', $content);        // opened again: the lines without times come back as plain lines, ready to be timed        $this->view->edSong = '';        $this->view->go('lyricsEdit');        $this->game->run(2);        self::assertSame(self::PLAIN, $this->view->fields['edText']);        $this->tap('edStart', null, 3);        foreach ([0.6, 0.6, 0.6, 0.6] as $wait) {            $this->game->wait($wait);            $this->tap('edStamp');        }        $this->tap('edSave', null, 5);        self::assertTrue($this->wz->lyricsSynced(), 'timed: synchronised now');        self::assertCount(4, $this->wz->lyrics->lines);    }    public function testLyricsWithoutTimesScrollByHandInBothOrientations(): void    {        $this->startPhone();        $rows = [];        for ($i = 1; $i <= 24; $i++) {            $rows[] = "Ligne numéro $i de la chanson sans temps";        }        $this->wz->saveLyrics(self::PARTAGE, Lyrics::fromText(implode("\n", $rows)) ?? new Lyrics());        $this->playPartage(20.0);        self::assertFalse($this->wz->lyricsSynced());        // the Lecteur's card: « non synchronisées », the finger scrolls it        $before = $this->view->scroll['lyCard'] ?? 0.0;        $this->drag('lyricsBox', null, 80);        self::assertSame('player', $this->view->screen, 'a drag is not a tap');        self::assertGreaterThan($before + 40, $this->view->scroll['lyCard'], 'the card scrolled');        $this->wz->notice = '';        $this->shot('mobile-lecteur-non-synchro');        // the karaoke: Défiler seul, Synchroniser, no ±0,5 s        $this->tap('karaokeOpen', null, 5);        self::assertSame('karaoke', $this->view->screen);        foreach (['lyAuto', 'karaSync'] as $id) {            self::assertNotNull($this->view->at($id), "$id on the screen");        }        self::assertNull($this->view->at('lyShift', 1), 'nothing to shift without times');        // a tap on a line does not seek (said quietly)        $this->wz->pause();        $pos = $this->wz->player->position;        $line = $this->wz->estimatedLine() + 1;        $this->tap('karaLine', $line, 2);        self::assertEqualsWithDelta($pos, $this->wz->player->position, 0.05);        self::assertStringContainsString('non synchronisées', $this->wz->notice);        // the finger scrolls the text, it stays there        $from = $this->view->karaScroll;        $this->drag('karaLine', $line, 150);        self::assertTrue($this->view->karaFree);        self::assertGreaterThan($from + 2, $this->view->karaScroll);        $this->wz->notice = '';        $this->wz->play();        $this->shot('mobile-karaoke-non-synchro');        // « Suivre la chanson »: back to the estimated line, slowly        $this->tap('karaFollow', null, 120);        self::assertFalse($this->view->karaFree);        self::assertEqualsWithDelta((float)$this->wz->estimatedLine(), $this->view->karaScroll, 1.0);        // landscape: the same, turned        $this->tap('karaTurn', null, 3);        self::assertTrue($this->view->turned());        $this->wz->pause();        $now = $this->view->karaScroll;        $line = max(0, (int)round($now));        $this->drag('karaLine', $line, 120);        self::assertTrue($this->view->karaFree);        self::assertGreaterThan($now + 1, $this->view->karaScroll, 'scrolled in landscape too');        $pos = $this->wz->player->position;        $this->tap('karaLine', (int)floor($this->view->karaScroll), 2);        self::assertEqualsWithDelta($pos, $this->wz->player->position, 0.05, 'no seek in landscape either');        $this->wz->notice = '';        $this->shot('mobile-karaoke-non-synchro-paysage');        // « Défiler seul » off: only the finger moves it        $this->tap('lyAuto', null, 3);        self::assertFalse($this->view->lyricsAutoScroll());        $this->tap('karaTurn', null, 3);        // « Synchroniser »: the editor with the lines        $this->tap('karaSync', null, 3);        self::assertSame('lyricsEdit', $this->view->screen);        self::assertCount(24, $this->view->edLines);    }    public function testTheTranslationsShowUnderTheLinesAndTheChipHidesThem(): void    {        $this->startPhone();        $lrc = "[00:01.00]I walk alone tonight\n[00:04.00]And the city is my friend\n[00:07.00]You know that I will stay\n[00:10.00]Under the lights of the town\n[00:13.00]We sing until the morning";        $lyrics = Lyrics::fromText($lrc) ?? new Lyrics();        self::assertTrue($lyrics->synced);        $lyrics->setTranslations([0 => 'Je marche seul ce soir', 1 => 'Et la ville est mon amie', 2 => 'Tu sais que je resterai',            3 => 'Sous les lumières de la ville', 4 => 'Nous chantons jusqu\'au matin'], 'fr');        $this->wz->saveLyrics(self::PARTAGE, $lyrics, false);        $this->playPartage(4.5);        $this->wz->pause();        self::assertTrue($this->wz->hasTranslation());        self::assertTrue($this->view->showTranslation());        $this->wz->notice = '';        $this->shot('mobile-lecteur-traduction');        // the karaoke: the translation under each line, « Traduction » hides / shows it (remembered)        $this->tap('karaokeOpen', null, 5);        self::assertNotNull($this->view->at('trToggle'));        $this->wz->notice = '';        $this->shot('mobile-karaoke-traduction');        $height = (new \ReflectionMethod(MobileView::class, 'karaHeight'))->invoke($this->view, 2, false);        $this->tap('trToggle', null, 2);        self::assertFalse($this->view->showTranslation());        self::assertFalse($this->wz->ui['mobile']['translation']);        self::assertLessThan($height, (new \ReflectionMethod(MobileView::class, 'karaHeight'))->invoke($this->view, 2, false), 'the lines shorter without it');        $this->tap('trToggle', null, 2);        self::assertTrue($this->view->showTranslation());        // landscape        $this->tap('karaTurn', null, 3);        self::assertTrue($this->view->turned());        self::assertNotNull($this->view->at('trToggle'));        $this->wz->notice = '';        $this->shot('mobile-karaoke-traduction-paysage');        $this->tap('karaTurn', null, 3);        // Options: the language, « Traduire maintenant » (the free translation, faked) with its progress        $this->fakeInternet(function (string $method, string $url): HttpResponse {            parse_str((string)parse_url($url, PHP_URL_QUERY), $q);            $rows = explode("\n", (string)($q['q'] ?? ''));            return self::json(['responseData' => ['translatedText' => implode("\n", array_map(fn ($r) => 'ES ' . $r, $rows))], 'responseStatus' => 200, 'quotaFinished' => false]);        });        $this->view->go('options');        $this->game->run(2);        $this->scrollPageTo('lyLang', 'es');        $this->tap('lyLang', 'es', 2);        self::assertSame('es', $this->wz->translationLang());        $this->scrollPageTo('trNow');        $this->tap('trNow', null, 4);        self::assertSame('done', $this->wz->translationState()['state'], $this->wz->translationState()['text']);        self::assertTrue($this->wz->hasTranslation(null, 'es'));        self::assertSame('ES I walk alone tonight', $this->wz->lyrics?->translation(0));        $this->wz->notice = '';        $this->shot('mobile-options-traduction');        $this->scrollPageTo('lyAutoTr');        $this->tap('lyAutoTr', null, 2);        self::assertFalse($this->wz->options['autoTranslate']);    }    public function testThePlaylistMarksTheLyricsAndPlaysOnlyTheSongsThatHaveSome(): void    {        $this->startPhone(['screen' => 'playlist']);        $this->wz->saveLyrics(self::PARTAGE, Lyrics::fromText(self::PLAIN) ?? new Lyrics());        $this->view->go('playlist');        $this->game->run(3);        $marks = new \ReflectionMethod(MobileView::class, 'lyricsMarks');        self::assertSame(['clock'], $marks->invoke($this->view, $this->line('assets/music/winzik.mp3')), 'synchronised');        self::assertSame(['list'], $marks->invoke($this->view, $this->line(self::PARTAGE)), 'to scroll');        $others = array_values(array_diff(array_keys($this->wz->playlist->items), [$this->line('assets/music/winzik.mp3'), $this->line(self::PARTAGE)]));        self::assertSame([], $marks->invoke($this->view, $others[0]));        self::assertSame(2, $this->wz->songsWithLyrics());        $this->wz->notice = '';        $this->shot('mobile-playlist-paroles');        // « Seulement avec paroles »: the play mode, and the list shows the songs that will play        $this->tap('lyOnly', null, 3);        self::assertTrue($this->wz->playsLyricsOnly());        self::assertCount(2, $this->view->shownLines());        $this->wz->playIndex($this->line('assets/music/winzik.mp3'));        $this->wz->next();        self::assertSame(self::PARTAGE, $this->wz->playlist->current(), 'the songs without lyrics skipped');        $this->wz->notice = '';        $this->shot('mobile-playlist-seulement-paroles');        // none has lyrics: what to do        $this->wz->stop();        $this->wz->removeLines([$this->line('assets/music/winzik.mp3')]);        $this->wz->removeLines([$this->line(self::PARTAGE)]);        $this->game->run(3);        self::assertSame(0, $this->wz->songsWithLyrics());        self::assertSame([], $this->view->shownLines());        self::assertNotNull($this->view->at('lyFind'), 'Chercher des paroles');        $this->wz->notice = '';        $this->shot('mobile-playlist-aucune-parole');        $this->tap('lyOnly', null, 3);        self::assertFalse($this->wz->playsLyricsOnly());        self::assertCount($this->wz->playlist->count(), $this->view->shownLines());    }}