UK
apps/winzik / tests / PhonePopupsTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Cloud\Cloud;use App\Cloud\CloudAccount;use App\Form\MainForm;use App\Form\WinZikDialog;use App\Gui\Canvas;use App\Gui\Desktop;use App\Gui\PopupMenu;use App\Gui\SkinWindow;use App\Media\Process;use App\Media\Tools;use JumPHP\Gui\Form;use JumPHP\Gui\Pointer;use PHPUnit\Framework\Attributes\DataProvider;use Tests\Cloud\FakeCloudServer;use Tests\Cloud\FakeRelay;/** * "WinZik original" on three phones (720 x 1280, 1080 x 2400, 1440 x 3200 pixels, their density): every menu, submenu and * dialog the windows of 2001 open is whole on the screen (above the bar of the phone for the menus), its rows readable and * as big as a finger, and the back button (Escape) closes it. Pictures var/screenshots/tests/phone-popups-<phone>-*.png. */final class PhonePopupsTest extends PlayerTestCase{    /** @var list<string> what is wrong, all of it (one test walks everything) */    private array $problems = [];    private string $phone = '';    private ?Canvas $canvas = null;    private float $density = 1.0;    /** @return array<string, array{0: int, 1: int, 2: float}> width, height (pixels), density (pixels per dp) */    public static function phones(): array    {        return [            'small' => [720, 1280, 2.0],            'medium' => [1080, 2400, 2.75],            'big' => [1440, 3200, 3.5],        ];    }    private function startPhone(int $width, int $height, float $density, string $name): void    {        $this->phone = $name;        $this->density = $density;        $this->startPlayer(['phone' => $width / $height]);        $this->wz->options['phoneUi'] = 'original';        $this->resize($width, $height, $density);        $this->wz->playIndex(0);          // a song with its lyrics: the bar of the lyrics, the karaoke        $this->wz->pause();        $this->wz->ui['lyrics']['visible'] = true;        $this->game->wait(1);             // the windows unroll at the start        self::assertTrue($this->desk->phone);        self::assertEqualsWithDelta($width, $this->desk->w, 1.0, 'the phone fills the view');    }    /** The view of a phone of this size (pixels), its forms at its density (dp), as on the phone. */    private function resize(int $width, int $height, float $density): void    {        $engine = $this->game->engine;        $config = $engine->config;        $values = new \ReflectionProperty($config, 'values');        $all = $values->getValue($config);        $all['view'] = $width === 900 && $height === 860 ? 'window' : 'fixed';        $values->setValue($config, $all);        $engine->sdl->getRenderer()->resizeView($width, $height);        $this->game->run(2);    }    protected function tearDown(): void    {        $this->resize(900, 860, 1.0);        WinZikDialog::$phoneAspect = 0.0;        parent::tearDown();    }    private function problem(string $text): void    {        $this->problems[] = $this->phone . ': ' . $text;    }    private function shot(string $name): void    {        $this->game->shot('phone-popups-' . $this->phone . '-' . $name);    }    // the finger, the back button ----------------------------------------------------------------------------------    private function finger(float $x, float $y, int $frames = 1): void    {        $p = new Pointer();        [$p->x, $p->y, $p->down, $p->held] = [$x, $y, true, true];        $this->game->scene()->handle($p);        $this->game->run($frames);        $up = new Pointer();        [$up->x, $up->y, $up->up] = [$x, $y, true];        $this->game->scene()->handle($up);        $this->game->run(1);    }    /** @return array{0: float, 1: float} the view point of a desktop point */    private function view(float $dx, float $dy): array    {        return [$this->desk->x + $dx * $this->desk->scale, $this->desk->y + $dy * $this->desk->scale];    }    private function longPress(SkinWindow $window, float $x, float $y): void    {        $this->finger(...$this->view($window->x + $x, $window->y + $y), frames: 40);    }    private function back(): void    {        $p = new Pointer();        [$p->x, $p->y] = [-1, -1];        $p->keys[] = Pointer::ESCAPE;        $scene = $this->game->scene();        $scene->handle($p);        $this->game->run(2);    }    // the checks ----------------------------------------------------------------------------------------------------    /** The menu shown: whole on the screen above the bar, rows a finger can take, every label whole in its row. */    private function checkMenu(string $what): void    {        $menu = $this->desk->menu()?->active();        if ($menu === null) {            $this->problem("$what: no menu");            return;        }        $this->checkMenuRect($menu, $what);    }    private function checkMenuRect(PopupMenu $menu, string $what): void    {        $dw = $this->desk->deskWidth();        $bottom = $this->desk->deskHeight() - Desktop::PHONE_BAR;        [$x, $y, $w, $h] = [$menu->x, $menu->y, $menu->width, $menu->height()];        if ($x < -0.01 || $y < -0.01 || $x + $w > $dw + 0.01 || $y + $h > $bottom + 0.01) {            $this->problem(sprintf('%s: the menu [%.0f, %.0f, %.0f x %.0f] goes past the screen [%.0f x %.0f above the bar]', $what, $x, $y, $w, $h, $dw, $bottom));        }        if (!$menu->touch || $menu->row < 26) {            $this->problem("$what: rows of {$menu->row} (not made for a finger)");        }        if ($menu->row * $this->desk->scale < 40) {            $this->problem(sprintf('%s: rows of %.0f pixels of the screen, under a finger', $what, $menu->row * $this->desk->scale));        }        $this->canvas ??= new Canvas($this->game->engine->sdl->getRenderer(), $this->game->engine->sdl);        $this->canvas->scale = $this->desk->scale;        foreach ($menu->items as $item) {            if (!empty($item['separator'])) {                continue;            }            $label = (string)$item['label'];            $font = $menu->labelFont($this->canvas, $item);            if ($this->canvas->textWidth($label, $font) > $menu->labelRoom($item) + 0.5) {                $this->problem(sprintf('%s: « %s » cut', $what, $label));            }            if ($font * $this->desk->scale < 22) {                $this->problem(sprintf('%s: « %s » in letters of %.0f pixels of the screen', $what, $label, $font * $this->desk->scale));            }        }    }    /** A window of the desktop whole on the screen (above the bar when it is not on the whole screen). */    private function checkWindow(SkinWindow $window, string $what, bool $aboveBar = true): void    {        if (!$window->visible()) {            $this->problem("$what: not shown");            return;        }        $turned = $this->desk->turned() === $window;        [$dw, $dh] = $turned ? [$this->desk->deskHeight(), $this->desk->deskWidth()] : [$this->desk->deskWidth(), $this->desk->deskHeight()];        $bottom = $aboveBar && !$turned ? $dh - Desktop::PHONE_BAR : $dh;        [$x, $y, $w, $h] = [$window->x, $window->y, $window->width(), $window->height()];        if ($x < -0.01 || $y < -0.01 || $x + $w > $dw + 0.5 || $y + $h > $bottom + 0.5) {            $this->problem(sprintf('%s: [%.0f, %.0f, %.0f x %.0f] goes past the screen [%.0f x %.0f]', $what, $x, $y, $w, $h, $dw, $bottom));        }        foreach ($window->controls() as $id => [$cx, $cy, $cw, $ch]) {            if ($cw <= 0 || $ch <= 0) {                continue;            }            if ($x + $cx < -0.01 || $x + $cx + $cw > $dw + 0.5 || $y + $cy < -0.01 || $y + $cy + $ch > $bottom + 0.5) {                $this->problem("$what: its button $id is off the screen");            }        }    }    /** The dialog on top: a whole screen, nothing past its right edge, its bottom reachable (it scrolls), back closes it. */    private function checkDialog(string $what): void    {        $this->game->run(3);        $dialog = $this->game->scene();        if (!$dialog instanceof Form || $dialog instanceof MainForm) {            $this->problem("$what: no dialog");            return;        }        $r = $this->game->engine->sdl->getRenderer();        [$vw, $vh] = [(float)$r->getWidth(), (float)$r->getHeight()];        $theme = (fn () => $this->theme)->call($dialog);        $scale = (float)$theme->scale;        if ($scale < $this->density * 0.85) {            $this->problem(sprintf('%s: drawn at %.2f pixels per dp, the phone has %.2f (too small)', $what, $scale, $this->density));        }        if ($dialog->isOverlay()) {            $this->problem("$what: a box over the windows, not the whole screen");        }        $root = (fn () => $this->root)->call($dialog);        $scrolls = (bool)($root?->props['scroll'] ?? false);        foreach ($root?->walk() ?? [] as $widget) {            if (!$widget->isShown($dialog->breakpoint()) || $widget->w <= 0 || $widget->h <= 0) {                continue;            }            $id = (string)($widget->props['id'] ?? (new \ReflectionClass($widget))->getShortName());            if ($widget->x < -0.5 || $widget->x + $widget->w > $vw + 0.5) {                $this->problem(sprintf('%s: %s [%.0f .. %.0f] past the width %.0f', $what, $id, $widget->x, $widget->x + $widget->w, $vw));            }            if ($widget instanceof \JumPHP\Gui\CheckBox || $widget instanceof \JumPHP\Gui\Button) {                // its text whole in it (a check box, a button never wrap their text)                $need = (fn () => $this->content($theme, 1e6, $dialog->breakpoint())[0])->call($widget);                if ($need > $widget->w + 1) {                    $this->problem(sprintf('%s: %s needs %.0f dp, has %.0f: its text is cut', $what, $id, $need / $scale, $widget->w / $scale));                }            }            if ($widget instanceof \JumPHP\Gui\Button && $widget->h < 36 * $scale) {                $this->problem(sprintf('%s: the button %s is %.0f dp high (a finger: 36 at least)', $what, $id, $widget->h / $scale));            }            if (!$scrolls && $widget->y + $widget->h > $vh + 0.5) {                $this->problem(sprintf('%s: %s ends at %.0f, under the screen (%.0f) and the dialog does not scroll', $what, $id, $widget->y + $widget->h, $vh));            }        }        $this->shot('dialog-' . $what);        $scene = $dialog;        $this->back();        if ($this->game->scene() === $scene) {            $this->problem("$what: the back button does not close it");            $scene->close();            $this->game->run(2);        }        if (!$this->game->scene() instanceof MainForm) {            $this->problem("$what: back did not go back to the windows (" . get_class($this->game->scene()) . ')');            $this->game->start(MainForm::class, []);        }        $this->game->run(2);    }    // the walk ------------------------------------------------------------------------------------------------------    /** @param list<string> $path labels of submenus opened in place, from the bar's menu */    private function walkMenu(string $name, array $path = []): void    {        $menu = $this->desk->menu()?->active();        if ($menu === null) {            return;        }        $this->checkMenu($name);        foreach ($menu->items as $item) {            if (empty($item['sub']) || ($item['enabled'] ?? true) === false) {                continue;            }            $label = (string)$item['label'];            $at = $this->desk->menu()?->rowCenter($label);            if ($at === null) {                // a menu taller than the screen: its rows slide; to the row first                $active = $this->desk->menu()?->active();                for ($k = 0; $k < 40 && $at === null && $active !== null; $k++) {                    $active->scrollBy($active->row);                    $at = $this->desk->menu()?->rowCenter($label);                }            }            if ($at === null) {                $this->problem("$name: « $label » cannot be reached");                continue;            }            $this->finger(...$this->view(...$at));            $sub = $this->desk->menu()?->active();            if ($sub === null || $sub === $menu) {                $this->problem("$name > $label: no submenu in place");                continue;            }            $this->walkMenu("$name > $label", [...$path, $label]);            $this->shot('menu-' . preg_replace('/[^a-z0-9]+/', '-', strtolower(iconv('UTF-8', 'ASCII//TRANSLIT', "$name $label") ?: $label)));            $this->back();            if ($this->desk->menu()?->active() !== $menu) {                $this->problem("$name > $label: back does not go back to $name");            }        }    }    /** A fake yt-dlp / ffmpeg: YouTube, Spotify and the films work (the pictures of a wide or tall film). */    private function useMedia(bool $tall = false): void    {        $tools = new Tools($this->wz->storagePath('bin'), $this->wz->storagePath('tmp'));        $tools->state = ['yt-dlp' => 'ready', 'ffmpeg' => 'ready'];        $tools->path = ['yt-dlp' => '/fake/yt-dlp', 'ffmpeg' => '/fake/ffmpeg'];        $runner = function (array $cmd) use ($tall): Process {            $line = implode(' ', $cmd);            if (str_ends_with($line, 'audio.wav')) {                return Process::finished($cmd, [], 0, fn () => copy($this->wz->path('assets/music/chaine-hifi.wav'), (string)end($cmd)));            }            if (str_contains($line, '%06d.jpg')) {                return Process::finished($cmd, [], 0, function () use ($cmd, $tall): void {                    foreach ([[200, 40, 40], [40, 200, 40]] as $i => [$r, $g, $b]) {                        $im = $tall ? imagecreatetruecolor(36, 64) : imagecreatetruecolor(64, 36);                        imagefill($im, 0, 0, (int)imagecolorallocate($im, $r, $g, $b));                        imagepng($im, sprintf(dirname((string)end($cmd)) . '/%06d.jpg', $i + 1));                    }                });            }            return Process::finished($cmd, [], 1);        };        $this->wz->useMedia($tools, \Closure::fromCallable($runner), $this->wz->storagePath('test/Musique'), $this->wz->storagePath('test/Videos'));    }    private function useCloud(): void    {        $server = new FakeCloudServer();        $relay = new FakeRelay();        $dir = $this->wz->storagePath('cloud-test/phone');        $account = new CloudAccount(fn (string $m, string $u, string|array|null $b, array $h) => $server->request($m, $u, $b, $h),            FakeCloudServer::BASE, "$dir/cloud.json", 'phone');        $this->wz->useCloud(new Cloud($this->wz, $account, "$dir/cloud", fn () => $relay->session(), null, "$dir/received"));    }    #[DataProvider('phones')]    public function testEveryMenuAndDialogOfTheOriginalInterfaceIsWholeOnThePhone(int $width, int $height, float $density): void    {        $name = array_search([$width, $height, $density], self::phones(), true);        $this->startPhone($width, $height, $density, (string)$name);        $this->useMedia();        $this->useCloud();        $desk = $this->desk;        $this->shot('windows');        foreach (['main' => $desk->main, 'playlist' => $desk->playlist, 'lyrics' => $desk->lyrics] as $what => $window) {            $this->checkWindow($window, $what);        }        // the "Menu" button of the bar, every submenu in place        [$bx, $by, $bw, $bh] = $desk->menuButton();        $this->finger(...$this->view($bx + $bw / 2, $by + $bh / 2));        $this->walkMenu('bar');        $this->shot('menu-bar');        $labels = $desk->menuLabels();        foreach (['Mode compact', 'Réduire dans la barre', 'Configurer le Joystick', 'Zoom', 'Toujours au-dessus', 'Playlist attachée au lecteur', 'Quitter'] as $nonsense) {            if (in_array($nonsense, $labels, true)) {                $this->problem("the menu has « $nonsense » (no sense on a phone)");            }        }        $this->back();        if ($desk->hasMenu()) {            $this->problem('bar: back does not close the menu');        }        // a long press on each window: its menu        $desk->eq->visible() || $this->wz->toggleEq();        $this->game->run(2);        $this->checkWindow($desk->eq, 'eq');        foreach (['main' => [$desk->main, 30, 40], 'eq' => [$desk->eq, 120, 5], 'playlist' => [$desk->playlist, 120, 60],            'lyrics' => [$desk->lyrics, 40, 30]] as $what => [$window, $x, $y]) {            $this->longPress($window, $x, $y);            if (!$desk->hasMenu()) {                $this->problem("long press on $what: no menu");                continue;            }            $this->checkMenu("long press on $what");            $this->shot('long-press-' . $what);            $this->back();        }        // the playlist's last line, near the bar: its menu        $this->longPress($desk->playlist, 120, $desk->playlist->height() - 8);        $this->checkMenu('long press at the bottom of the list');        $this->back();        // the presets of the equalizer, the "+" of the lyrics        $this->clickControl($desk->eq, 'presets');        $this->checkMenu('presets');        $this->shot('menu-presets');        $this->back();        $this->clickControl($desk->lyrics, 'more');        $this->checkMenu('lyrics +');        $this->shot('menu-lyrics');        $this->back();        if ($desk->hasMenu()) {            $this->problem('back does not close the menu of the lyrics');        }        // every dialog the original interface opens        $dialogs = [            'options' => fn () => $this->form->openOptions(),            'files' => fn () => $this->form->openFiles(),            'tags' => fn () => $this->form->openTags(),            'skins' => fn () => $this->form->openSkins(),            'market-skins' => fn () => $this->form->openMarket('skin'),            'market-lyrics' => fn () => $this->form->openMarket('lyrics'),            'plugins' => fn () => $this->form->openPlugins(),            'controls' => fn () => $this->form->openControls(),            'lyrics' => fn () => $this->form->downloadLyrics(),            'fls-load' => fn () => $this->form->openFls(false),            'fls-save' => fn () => $this->form->openFls(true),            'lock' => fn () => $this->form->openLock(),            'youtube' => fn () => $this->form->openYoutube(),            'spotify' => fn () => $this->form->openSpotify(),            'cloud' => fn () => $this->form->openCloud(),            'lyrics-editor' => fn () => $this->form->openLyricsEditor(),            'skin-editor' => fn () => $this->form->openSkinEditor(),        ];        foreach ($dialogs as $what => $open) {            $open();            $this->checkDialog($what);            $this->form = $this->game->scene() instanceof MainForm ? $this->game->scene() : $this->form;            $this->desk = $this->form->widget('desktop');            $desk = $this->desk;        }        // the karaoke on the whole screen: turned, whole        $desk->lyrics->toggleFull();        $this->game->wait(1);        $this->checkWindow($desk->lyrics, 'karaoke', false);        $this->shot('karaoke');        $this->back();        $this->game->wait(1);        if ($desk->lyrics->full()) {            $this->problem('karaoke: back does not close it');        }        // A propos: the whole screen, back goes back        $this->form->openAbout();        $this->game->wait(1);        $this->shot('about');        $this->game->engine->scenes->pop();     // any key or touch closes it (FullScreen::anyInput())        $this->game->run(2);        // a wide film on the whole screen: turned, whole; then the film in its window under the player        $film = $this->wz->storagePath('test/Videos/clip.mp4');        @mkdir(dirname($film), 0777, true);        file_put_contents($film, 'film');        $this->wz->addFiles([$film]);        $this->wz->playIndex($this->wz->playlist->count() - 1);        $this->game->run(20);        if ($desk->video->visible()) {            $this->checkWindow($desk->video, 'video');            $this->shot('video');            $desk->video->toggleFull();            $this->game->wait(1);            if ($desk->turned() !== $desk->video) {                $this->problem('a wide film on the whole screen is not turned');            }            $this->checkWindow($desk->video, 'video on the whole screen', false);            $this->shot('video-full');            $this->back();            $this->game->run(2);            if ($desk->video->full()) {                $this->problem('the film on the whole screen: back does not close it');            }        } else {            $this->problem('the film is not shown');        }        $this->wz->stop();        // the compact bar has no place on a phone: its button leaves the player there        $this->clickControl($desk->main, 'compact');        $this->game->run(2);        if ($desk->compact->visible() || !$desk->main->visible()) {            $this->problem('the compact bar on the phone');        }        $this->checkWindow($desk->main, 'main after compact');        // the note of the web version (beside the player on a computer) is not on a phone        $desk->note->forced = true;        if ($desk->note->visible()) {            $this->problem('the note of the web version is shown');        }        $desk->note->forced = false;        self::assertSame([], $this->problems, implode("\n", $this->problems));    }}