ES
apps/winzik / tests / SkinEditorTest.php · commit 6576d6f
<?phpnamespace Tests;use App\Form\MainForm;use App\Form\SkinEditorForm;use App\Gui\PixelEditor;use App\Gui\SkinPreview;use App\Model\Skin;use App\Model\SkinDocument;use App\Model\SkinParts;use JumPHP\Gui\Pointer;/** EDT, the skin editor of 2001: a skin made from another one, piece by piece, then put on the player. */final class SkinEditorTest extends PlayerTestCase{    private function openEditor(): SkinEditorForm    {        $this->startPlayer();        $this->form->openSkinEditor();        $this->game->run(3);        $editor = $this->game->scene();        self::assertInstanceOf(SkinEditorForm::class, $editor);        return $editor;    }    /** A press, a drag through some points, a release on the canvas (view pixels). @param list<array{0: float, 1: float}> $points */    private function stroke(SkinEditorForm $editor, array $points): void    {        foreach ($points as $i => [$x, $y]) {            $p = new Pointer();            [$p->x, $p->y] = [$x, $y];            if ($i === 0) {                [$p->down, $p->held] = [true, true];            } else {                $p->held = true;            }            $editor->handle($p);        }        $up = new Pointer();        [$up->x, $up->y, $up->up] = [end($points)[0], end($points)[1], true];        $editor->handle($up);        $this->game->run(1);    }    /** @return array{0: float, 1: float} the view point of a pixel of the piece on the canvas */    private function pixel(SkinEditorForm $editor, int $x, int $y): array    {        $canvas = $editor->widget('canvas');        self::assertInstanceOf(PixelEditor::class, $canvas);        return [$canvas->x + $canvas->panX + ($x + 0.5) * $canvas->zoom, $canvas->y + $canvas->panY + ($y + 0.5) * $canvas->zoom];    }    public function testTheEditorStartsFromTheSkinOfThePlayerUnderTheNameSansTitre(): void    {        $editor = $this->openEditor();        self::assertSame('SANSTITRE', $editor->widget('skinName')->props['text']);        self::assertSame(['Fenêtre principale', 'Playlist', 'Mode compact'], $editor->widget('windows')->props['items']);        self::assertCount(20, $editor->widget('parts')->props['items'], 'main.bmp and the 19 pieces of REF.NUN');        $this->game->shot('edt');    }    public function testAClickOnAPieceOfTheWindowChoosesIt(): void    {        $editor = $this->openEditor();        $preview = $editor->widget('preview');        self::assertInstanceOf(SkinPreview::class, $preview);        // the play button: 112, 76 in the window        for ($x = $preview->x; $x < $preview->x + $preview->w; $x += 2) {            if ($preview->partAt($x, $preview->y + $preview->h / 2) !== null) {                break;            }        }        $z = ($preview->w - 8) / 258;        $found = null;        for ($vx = $preview->x; $vx < $preview->x + $preview->w && $found !== 'bplay'; $vx += 1) {            for ($vy = $preview->y; $vy < $preview->y + $preview->h; $vy += 3) {                if ($preview->partAt($vx, $vy) === 'bplay') {                    $found = 'bplay';                    $editor->clickAt($vx + 2, $vy + 2);                    break;                }            }        }        self::assertSame('bplay', $editor->part);    }    public function testDrawingAPieceThenUndoAndRedo(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $editor->setColor('#ff0000');        $this->stroke($editor, [$this->pixel($editor, 2, 2), $this->pixel($editor, 3, 2), $this->pixel($editor, 4, 2)]);        $doc = $editor->document();        self::assertSame('#ff0000', $doc->pixel('bplay', 3, 2));        self::assertTrue($doc->isModified('bplay'));        $editor->click($editor->widget('undo'));        self::assertNotSame('#ff0000', $doc->pixel('bplay', 3, 2));        $editor->click($editor->widget('redo'));        self::assertSame('#ff0000', $doc->pixel('bplay', 3, 2));        $this->game->shot('edt-drawn');    }    public function testThePotOfPaintAndThePipette(): void    {        $editor = $this->openEditor();        $editor->selectPart('mainp');        $this->game->run(2);        $editor->click($editor->widget('toolPot'));        $editor->setColor('#0000ff');        self::assertSame('pot', $editor->tool);        $this->stroke($editor, [$this->pixel($editor, 50, 6)]);        self::assertSame('#0000ff', $editor->document()->pixel('mainp', 50, 6));        $editor->setColor('#123456');        $editor->click($editor->widget('toolPipette'));        $this->stroke($editor, [$this->pixel($editor, 50, 6)]);        self::assertSame('#0000ff', $editor->color, 'the pipette takes the colour');    }    public function testVoirDansWinZikWritesTheSkinAndPutsItOnThePlayer(): void    {        $editor = $this->openEditor();        $editor->click($editor->widget('skinName'));        $editor->key(Pointer::END);        for ($i = 0; $i < 12; $i++) {            $editor->key(Pointer::BACKSPACE);        }        $editor->type("MonSkin\n");        $editor->selectPart('bstop');        $this->game->run(2);        $editor->setColor('#00ff00');        $this->stroke($editor, [$this->pixel($editor, 1, 1)]);        $editor->widget('colorKey')->select(0);        $editor->click($editor->widget('colorHex'));        $editor->key(Pointer::END);        for ($i = 0; $i < 10; $i++) {            $editor->key(Pointer::BACKSPACE);        }        $editor->type("#ff00ff\n");        $editor->click($editor->widget('view'));        $this->game->run(3);        self::assertInstanceOf(MainForm::class, $this->game->scene());        $dir = $this->wz->storagePath('skins/MonSkin');        self::assertTrue(Skin::isSkin($dir), 'a whole skin: INFO.txt and every picture');        foreach (SkinParts::all() as $part) {            self::assertFileExists($dir . '/' . $part . '.png');        }        self::assertSame('MonSkin', $this->wz->skin->name);        self::assertSame('#ff00ff', $this->wz->skin->colors['title']);        $saved = new SkinDocument($dir, $dir, 'MonSkin');        self::assertSame('#00ff00', $saved->pixel('bstop', 1, 1));        $this->game->shot('mon-skin');    }    public function testASpaceIsRefusedInTheName(): void    {        self::assertSame('Monbeauskin', SkinDocument::cleanName('Mon beau skin!'));        self::assertSame('Ete', SkinDocument::cleanName('Été'));    }    /** A key pressed with Ctrl (Ctrl+Z...), as the form gets it. */    private function ctrlKey(SkinEditorForm $editor, string $letter, bool $shift = false): void    {        $p = new Pointer();        [$p->keys, $p->ctrl, $p->shift] = [[ord($letter)], true, $shift];        $editor->handle($p);    }    /** A key of the keyboard as the engine reports it (the letters of the tools come this way). */    private function rawKey(SkinEditorForm $editor, int $sym): void    {        $editor->engineOrNull()?->input->emit('key', [$sym]);    }    public function testCtrlZAndCtrlYGoBackAndForthStrokeByStrokeAndAClickThatChangesNothingIsNoStep(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $doc = $editor->document();        $editor->setColor('#ff0000');        $this->stroke($editor, [$this->pixel($editor, 1, 1)]);        $editor->setColor('#00ff00');        $this->stroke($editor, [$this->pixel($editor, 2, 1)]);        $editor->setColor('#0000ff');        $this->stroke($editor, [$this->pixel($editor, 3, 1)]);        self::assertSame([3, 0], $doc->history('bplay'));        // the same colour again on the same pixel: nothing changed, no step        $this->stroke($editor, [$this->pixel($editor, 3, 1)]);        self::assertSame([3, 0], $doc->history('bplay'), 'a stroke that changed nothing is not a step of Annuler');        $this->ctrlKey($editor, 'z');        $this->ctrlKey($editor, 'z');        self::assertNotSame('#00ff00', $doc->pixel('bplay', 2, 1));        self::assertSame('#ff0000', $doc->pixel('bplay', 1, 1));        self::assertSame([1, 2], $doc->history('bplay'));        $this->ctrlKey($editor, 'y');        self::assertSame('#00ff00', $doc->pixel('bplay', 2, 1));        $this->ctrlKey($editor, 'z', true);    // Ctrl+Maj+Z: Rétablir too        self::assertSame('#0000ff', $doc->pixel('bplay', 3, 1));        $this->ctrlKey($editor, 'y');        self::assertStringContainsString('Rien à rétablir', $editor->widget('help')->props['text']);        $this->game->run(1);        self::assertStringContainsString('annuler : 3', $editor->widget('status')->props['text']);    }    public function testAnnulerGoesBackAHundredStrokes(): void    {        $editor = $this->openEditor();        $doc = $editor->document();        for ($i = 0; $i < SkinDocument::HISTORY + 5; $i++) {            $doc->checkpoint('bstop');            $doc->plot('bstop', $i % 20, 1, sprintf('#%02x0000', $i));        }        self::assertSame([SkinDocument::HISTORY, 0], $doc->history('bstop'));        while ($doc->undo('bstop')) {        }        self::assertSame('#040000', $doc->pixel('bstop', 4, 1), 'the 100 last strokes undone, the 5 first ones kept');    }    public function testTheToolsAndTheZoomHaveTheirKeys(): void    {        $editor = $this->openEditor();        $editor->selectPart('mainp');        $this->game->run(2);        foreach (['p' => 'pot', 'i' => 'pipette', 'e' => 'gomme', 'm' => 'main', 'c' => 'crayon'] as $key => $tool) {            $this->rawKey($editor, ord($key));            self::assertSame($tool, $editor->tool, 'key ' . $key);        }        self::assertTrue($editor->widget('toolCrayon')->props['checked']);        $canvas = $editor->widget('canvas');        self::assertInstanceOf(PixelEditor::class, $canvas);        $fit = $canvas->zoom;        $this->rawKey($editor, ord('+'));        self::assertGreaterThan($fit, $canvas->zoom);        $this->rawKey($editor, ord('-'));        $this->rawKey($editor, ord('-'));        self::assertLessThan($fit, $canvas->zoom);        $this->rawKey($editor, ord('0'));        self::assertSame($fit, $canvas->zoom, '0: the whole piece again');        // typing in a text field is typing, not a tool        $editor->click($editor->widget('brush'));        $this->rawKey($editor, ord('p'));        self::assertSame('crayon', $editor->tool);        $this->game->run(1);        $this->game->shot('edt-keys');    }    public function testTheWheelZoomsAroundThePixelUnderThePointer(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $canvas = $editor->widget('canvas');        self::assertInstanceOf(PixelEditor::class, $canvas);        [$x, $y] = $this->pixel($editor, 20, 4);        $before = $canvas->zoom;        $editor->wheelAt($x, $y, 1);        self::assertGreaterThan($before, $canvas->zoom);        self::assertSame([20, 4], $canvas->pixelAt($x, $y), 'the pixel under the pointer stays under it');        $editor->wheelAt($x, $y, -1);        $editor->wheelAt($x, $y, -1);        self::assertLessThan($before, $canvas->zoom);        self::assertSame([20, 4], $canvas->pixelAt($x, $y));    }    public function testARightClickOnThePieceTakesItsColourAndTheColoursAreTypedShortOrLong(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $editor->setColor('#ff00ff');        $this->stroke($editor, [$this->pixel($editor, 5, 5)]);        $editor->setColor('#123456');        $editor->click($editor->widget('toolPot'));        $p = new Pointer();        [$p->x, $p->y] = $this->pixel($editor, 5, 5);        $p->right = true;        $editor->handle($p);        self::assertSame('#ff00ff', $editor->color);        self::assertSame('pot', $editor->tool, 'the tool stays');        // the brush: #rgb or #rrggbb, Entrée        $editor->widget('brush')->text = '#0F0';        $editor->click($editor->widget('brush'));        $editor->type("\n");        self::assertSame('#00ff00', $editor->color);        $editor->widget('brush')->text = 'vert';        $editor->type("\n");        self::assertSame('#00ff00', $editor->color, 'not a colour: the brush keeps its own');        self::assertStringContainsString('Couleur inconnue', $editor->widget('help')->props['text']);        self::assertSame('#00ff00', $editor->widget('brush')->props['text']);    }    public function testClosingWithChangesNotSavedAsksFirstEscapeThenEscapeAgainCloses(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $editor->setColor('#ff0000');        $this->stroke($editor, [$this->pixel($editor, 2, 2)]);        $editor->key(Pointer::ESCAPE);        $this->game->run(2);        self::assertSame($editor, $this->game->scene(), 'not closed: the changes are not saved');        self::assertStringContainsString('ne sont pas enregistrées', $editor->widget('help')->props['text']);        $this->game->shot('edt-quit-asked');        $editor->key(Pointer::ESCAPE);        $this->game->run(3);        self::assertInstanceOf(MainForm::class, $this->game->scene());    }    public function testAnotherSkinToStartFromIsAskedTwiceWhenChangesAreNotSaved(): void    {        $editor = $this->openEditor();        $source = $editor->widget('source');        $first = $source->props['selected'];        $other = $first === 0 ? 1 : 0;        $editor->selectPart('bplay');        $this->game->run(2);        $editor->setColor('#ff0000');        $this->stroke($editor, [$this->pixel($editor, 2, 2)]);        $source->select($other);        self::assertSame($first, $editor->widget('source')->props['selected'], 'kept: asked first');        self::assertSame('#ff0000', $editor->document()->pixel('bplay', 2, 2));        self::assertStringContainsString('choisir encore', $editor->widget('help')->props['text']);        $source->select($other);        self::assertSame($other, $editor->widget('source')->props['selected']);        self::assertFalse($editor->document()->hasChanges(), 'chosen again: the changes are dropped');    }    public function testASaveOnAFullDiskSaysSoInFrenchWithoutAPhpWarningAndKeepsTheChanges(): void    {        $editor = $this->openEditor();        $editor->selectPart('bplay');        $this->game->run(2);        $editor->setColor('#ff0000');        $this->stroke($editor, [$this->pixel($editor, 2, 2)]);        $doc = $editor->document();        if (!in_array('fulldisk', stream_get_wrappers(), true)) {            stream_wrapper_register('fulldisk', FullDiskStream::class);        }        $doc->targetDir = 'fulldisk://skins/Plein';        $warnings = [];        set_error_handler(function (int $no, string $message) use (&$warnings): bool {            if ((error_reporting() & $no) !== 0) {                $warnings[] = $message;    // a warning silenced by @ is not one            }            return true;        });        try {            $this->ctrlKey($editor, 's');        } finally {            restore_error_handler();        }        self::assertSame([], $warnings, 'no PHP warning');        self::assertStringContainsString('Disque plein ou en lecture seule', $editor->widget('help')->props['text']);        self::assertStringContainsString('Skin non enregistré', $editor->widget('help')->props['text']);        self::assertTrue($doc->hasChanges(), 'the piece is still to be saved');        self::assertSame($editor, $this->game->scene());        // a folder that cannot be made (under a file)        $file = (string)tempnam(sys_get_temp_dir(), 'edt');        $doc->targetDir = $file . '/Skin';        set_error_handler(function (int $no, string $message) use (&$warnings): bool {            if ((error_reporting() & $no) !== 0) {                $warnings[] = $message;    // a warning silenced by @ is not one            }            return true;        });        try {            $editor->click($editor->widget('save'));        } finally {            restore_error_handler();            unlink($file);        }        self::assertSame([], $warnings);        self::assertStringContainsString('Impossible de créer le dossier', $editor->widget('help')->props['text']);        $this->game->run(1);        $this->game->shot('edt-disk-full');    }}/** A disk that is full: folders exist, every write gives 0 bytes (file_put_contents warns "possibly out of free disk space"). */final class FullDiskStream{    /** @var resource|null */    public $context;    public function stream_open(string $path, string $mode, int $options, ?string &$opened): bool    {        return true;    }    public function stream_write(string $data): int    {        return 0;    }    public function stream_read(int $count): string|false    {        return false;    }    public function stream_eof(): bool    {        return true;    }    public function stream_close(): void    {    }    public function stream_stat(): array|false    {        return false;    }    public function url_stat(string $path, int $flags): array|false    {        return rtrim($path, '/') === 'fulldisk://skins/Plein' ? ['mode' => 040777, 'size' => 0] : false;    }    public function mkdir(string $path, int $mode, int $options): bool    {        return true;    }}