UK
apps/winzik / src / Model / SkinDocument.php · commit 6576d6f
<?phpnamespace App\Model;/** * A skin being made in the editor (EDT of 2001): it starts from a skin (cskin), its changes go into a folder of its * own (current = var/skins/<name>), piece by piece, each with its undo / redo (the SAVEnnmm.und files of 2001). * Pictures are GD images; when saved, the pieces not changed are copied from the skin it started from, so the new * folder is a whole skin (Form_Unload of EDT did the same), and INFO.txt gets the name and the colours. */final class SkinDocument{    /** how many strokes of a piece Annuler goes back (Ctrl+Z) */    public const HISTORY = 100;    public Skin $source;    /** @var array<string, \GdImage> */    private array $images = [];    /** @var array<string, bool> pieces changed since the last save */    private array $dirty = [];    /** @var array<string, list<string>> PNG of each piece before a change */    private array $undo = [];    /** @var array<string, list<string>> */    private array $redo = [];    /** @var array<string, list<string>> Rétablir before the stroke under way (given back when it changed nothing) */    private array $redoBefore = [];    /** @var array<string, int> how many times a piece changed (the preview reloads it) */    private array $versions = [];    /** @var array<string, string> the colours of INFO.txt */    public array $colors;    /** @var list<string> */    public array $lineColors;    public bool $colorsChanged = false;    /** why the last save() failed, in French ('' = it worked) */    public string $error = '';    public function __construct(string $sourceDir, public string $targetDir, public string $name)    {        $this->source = new Skin($sourceDir);        $own = Skin::isSkin($targetDir) ? new Skin($targetDir) : $this->source;        $this->colors = $own->colors;        $this->lineColors = $own->lineColors;    }    /** A name of a skin folder: letters, digits, - and _ (2001: "Veuiller ne pas insérer d'espace"). */    public static function cleanName(string $name): string    {        $name = Text::toUtf8(trim($name));        $ascii = function_exists('iconv') ? (string)@iconv('UTF-8', 'ASCII//TRANSLIT', $name) : $name;        return substr((string)preg_replace('/[^A-Za-z0-9_-]+/', '', $ascii !== '' ? $ascii : $name), 0, 40);    }    public function image(string $part): \GdImage    {        if (!isset($this->images[$part])) {            $this->images[$part] = $this->load($part);        }        return $this->images[$part];    }    private function load(string $part): \GdImage    {        [$w, $h] = SkinParts::size($part);        foreach ([$this->targetDir . '/' . $part . '.png', $this->source->image($part)] as $file) {            if ($file !== null && is_file($file)) {                $data = (string)@file_get_contents($file);                $img = $data !== '' ? @imagecreatefromstring($data) : false;                if ($img instanceof \GdImage) {                    return $this->trueColor($img);                }            }        }        $img = imagecreatetruecolor($w, $h);        imagealphablending($img, false);        imagesavealpha($img, true);        imagefill($img, 0, 0, (int)imagecolorallocatealpha($img, 0, 0, 0, 127));        return $img;    }    /** GIF / palette pictures as true colour with alpha (a pixel set is the colour asked, exactly). */    private function trueColor(\GdImage $img): \GdImage    {        if (!imageistruecolor($img)) {            imagepalettetotruecolor($img);        }        imagealphablending($img, false);        imagesavealpha($img, true);        return $img;    }    /** @return array{0: int, 1: int} */    public function size(string $part): array    {        $img = $this->image($part);        return [imagesx($img), imagesy($img)];    }    /** '#rrggbb', or '' for a transparent pixel. */    public function pixel(string $part, int $x, int $y): string    {        [$w, $h] = $this->size($part);        if ($x < 0 || $y < 0 || $x >= $w || $y >= $h) {            return '';        }        $c = imagecolorat($this->image($part), $x, $y);        if ((($c >> 24) & 0x7F) > 100) {            return '';        }        return sprintf('#%02x%02x%02x', ($c >> 16) & 0xFF, ($c >> 8) & 0xFF, $c & 0xFF);    }    /** Before a stroke: what it was, for Annuler. */    public function checkpoint(string $part): void    {        $this->undo[$part][] = $this->png($this->image($part));        while (count($this->undo[$part]) > self::HISTORY) {            array_shift($this->undo[$part]);        }        $this->redoBefore[$part] = $this->redo[$part] ?? [];        $this->redo[$part] = [];    }    /** After a stroke: a stroke that changed nothing (a click outside, the pot on its own colour) is no step of Annuler. */    public function endStroke(string $part): void    {        $last = empty($this->undo[$part]) ? null : end($this->undo[$part]);        if (is_string($last) && $last === $this->png($this->image($part))) {            array_pop($this->undo[$part]);            $this->redo[$part] = $this->redoBefore[$part] ?? [];    // Rétablir is still there        }        unset($this->redoBefore[$part]);    }    /** How many steps Annuler / Rétablir have for a piece. @return array{0: int, 1: int} */    public function history(string $part): array    {        return [count($this->undo[$part] ?? []), count($this->redo[$part] ?? [])];    }    /** A pixel of a colour ('' = transparent, the eraser). */    public function plot(string $part, int $x, int $y, string $color): void    {        [$w, $h] = $this->size($part);        if ($x < 0 || $y < 0 || $x >= $w || $y >= $h) {            return;        }        $img = $this->image($part);        imagesetpixel($img, $x, $y, $this->allocate($img, $color));        $this->changed($part);    }    /** The pot of paint: the area of the same colour around the pixel. */    public function fill(string $part, int $x, int $y, string $color): void    {        [$w, $h] = $this->size($part);        if ($x < 0 || $y < 0 || $x >= $w || $y >= $h || $this->pixel($part, $x, $y) === $color) {            return;        }        // by hand: imagefill() does not handle the alpha of true colour pictures the same everywhere        $img = $this->image($part);        $target = imagecolorat($img, $x, $y);        $new = $this->allocate($img, $color);        $stack = [[$x, $y]];        $seen = [];        while ($stack !== []) {            [$px, $py] = array_pop($stack);            if ($px < 0 || $py < 0 || $px >= $w || $py >= $h || isset($seen[$py * $w + $px]) || imagecolorat($img, $px, $py) !== $target) {                continue;            }            $seen[$py * $w + $px] = true;            imagesetpixel($img, $px, $py, $new);            array_push($stack, [$px + 1, $py], [$px - 1, $py], [$px, $py + 1], [$px, $py - 1]);        }        $this->changed($part);    }    /** A picture of the computer replaces the piece, fitted to its size (2001: the piece was redone in Photoshop). */    public function import(string $part, string $file): bool    {        $data = is_file($file) ? (string)@file_get_contents($file) : '';        $src = $data !== '' ? @imagecreatefromstring($data) : false;        if (!$src instanceof \GdImage) {            return false;        }        $this->checkpoint($part);        [$w, $h] = SkinParts::size($part);        $img = imagecreatetruecolor($w, $h);        imagealphablending($img, false);        imagesavealpha($img, true);        imagefill($img, 0, 0, (int)imagecolorallocatealpha($img, 0, 0, 0, 127));        imagecopyresampled($img, $this->trueColor($src), 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));        $this->images[$part] = $img;        $this->changed($part);        return true;    }    /** The piece read again from its file (changed by another program: Image4_Click, redess, of 2001). */    public function reload(string $part): void    {        unset($this->images[$part], $this->dirty[$part]);        $this->versions[$part] = ($this->versions[$part] ?? 0) + 1;    }    public function canUndo(string $part): bool    {        return !empty($this->undo[$part]);    }    public function canRedo(string $part): bool    {        return !empty($this->redo[$part]);    }    public function undo(string $part): bool    {        if (empty($this->undo[$part])) {            return false;        }        $this->redo[$part][] = $this->png($this->image($part));        $this->images[$part] = $this->fromPng((string)array_pop($this->undo[$part]));        $this->changed($part);        return true;    }    public function redo(string $part): bool    {        if (empty($this->redo[$part])) {            return false;        }        $this->undo[$part][] = $this->png($this->image($part));        $this->images[$part] = $this->fromPng((string)array_pop($this->redo[$part]));        $this->changed($part);        return true;    }    /** A piece of this skin, not of the one it started from (the green dot of 2001: Shape5). */    public function isModified(string $part): bool    {        return isset($this->dirty[$part]) || is_file($this->targetDir . '/' . $part . '.png');    }    public function hasChanges(): bool    {        return $this->dirty !== [] || $this->colorsChanged;    }    public function version(string $part): int    {        return $this->versions[$part] ?? 0;    }    /** The picture as a PNG file (for the preview, or to open it in another program). */    public function export(string $part, string $file): string    {        $this->exportTo($part, $file);        return $file;    }    /** export(), saying whether the whole file was written (false: read-only folder, disk full). */    public function exportTo(string $part, string $file): bool    {        if (!is_dir(dirname($file))) {            @mkdir(dirname($file), 0777, true);        }        return self::write($file, $this->png($this->image($part)));    }    /** A whole file or nothing, without a PHP warning: a partial file (disk full) is removed. */    private static function write(string $file, string $data): bool    {        $written = @file_put_contents($file, $data);        if ($written === strlen($data)) {            return true;        }        if ($written !== false && is_file($file)) {            @unlink($file);        }        return false;    }    /**     * Writes the skin: the pieces changed, the others copied from the skin it started from, INFO.txt. False when     * something could not be written ($error says what, in French); the pieces not written stay to be saved.     */    public function save(): bool    {        $this->error = '';        if (!is_dir($this->targetDir) && !@mkdir($this->targetDir, 0777, true)) {            $this->error = 'Impossible de créer le dossier ' . $this->targetDir . ' (disque en lecture seule ou plein ?)';            return false;        }        $failed = [];        foreach (array_keys($this->dirty) as $part) {            if ($this->exportTo((string)$part, $this->targetDir . '/' . $part . '.png')) {                unset($this->dirty[$part]);            } else {                $failed[] = $part . '.png';            }        }        foreach (SkinParts::all() as $part) {            $own = $this->targetDir . '/' . $part . '.png';            $from = $this->source->image($part);            if (!is_file($own) && $from !== null && is_file($from)) {                $ok = str_ends_with(strtolower($from), '.png')                    ? self::write($own, (string)@file_get_contents($from))                    : $this->exportTo($part, $own);    // a BMP / GIF of 2001: saved as PNG                if (!$ok) {                    $failed[] = $part . '.png';                }            }        }        $vb = static function (string $hex): string {            $hex = ltrim($hex, '#');            return sprintf('&H00%s%s%s&', strtoupper(substr($hex, 4, 2)), strtoupper(substr($hex, 2, 2)), strtoupper(substr($hex, 0, 2)));        };        $lines = ['[INF]', $this->name];        foreach (Skin::COLORS as $key) {            $lines[] = $vb($this->colors[$key]);        }        foreach ($this->lineColors as $color) {            $lines[] = $vb($color);        }        if (self::write($this->targetDir . '/INFO.txt', implode("\r\n", $lines) . "\r\n")) {            $this->colorsChanged = false;        } else {            $failed[] = 'INFO.txt';        }        if ($failed !== []) {            $this->error = 'Disque plein ou en lecture seule : ' . (count($failed) === 1 ? $failed[0] . ' non écrit' : count($failed) . ' fichiers non écrits (' . implode(', ', array_slice($failed, 0, 3)) . (count($failed) > 3 ? '…' : '') . ')')                . ' dans ' . $this->targetDir;            return false;        }        return true;    }    private function changed(string $part): void    {        $this->dirty[$part] = true;        $this->versions[$part] = ($this->versions[$part] ?? 0) + 1;    }    private function allocate(\GdImage $img, string $color): int    {        if ($color === '' || $color === 'transparent') {            return (int)imagecolorallocatealpha($img, 0, 0, 0, 127);        }        $c = \JumPHP\Util\Color::of($color);        return (int)imagecolorallocatealpha($img, (int)$c->r, (int)$c->g, (int)$c->b, 0);    }    private function png(\GdImage $img): string    {        ob_start();        imagepng($img);        return (string)ob_get_clean();    }    private function fromPng(string $png): \GdImage    {        $img = imagecreatefromstring($png);        return $this->trueColor($img instanceof \GdImage ? $img : imagecreatetruecolor(1, 1));    }}