<?phpnamespace App\Form;use App\Gui\Palette;use App\Gui\PixelEditor;use App\Gui\SkinPreview;use App\Model\Skin;use App\Model\SkinDocument;use App\Model\SkinParts;use JumPHP\Gui\Button;use JumPHP\Gui\ComboBox;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\Picture;use JumPHP\Gui\Pointer;use JumPHP\Gui\Radio;use JumPHP\Gui\TextBox;use JumPHP\Kernel\Platform;use JumPHP\Native\FilePicker;use JumPHP\Native\Native;use JumPHP\Native\Shell;/** * EDT of 2001, the skin editor of WinZik (EDT.frm, LOAD.frm, REF.NUN): a skin is chosen to start from (cskin), it gets * a name (LABEL5: a folder, no space), each window shows its pieces, a piece is drawn, Annuler / Rétablir, the pieces * changed get a green dot, "Voir dans WinZik" puts the skin on the player (Image11: winzik.exe SKIN:<folder>). * The new skin is written to var/skins/<name>/ with an INFO.txt, and the skin viewer lists it. * Params: skin (the folder to start from), name. * * Keys: Ctrl+Z Annuler, Ctrl+Y (or Ctrl+Maj+Z) Rétablir, Ctrl+S Enregistrer; out of a text field C crayon, P pot, * I pipette, E gomme, M main, + / - zoom, 0 the whole piece; a right click on the piece takes its colour; Échap = Fermer * (asked twice when something is not saved). * * @property TextBox $skinName * @property ComboBox $source * @property ListBox $windows * @property ListBox $parts * @property PixelEditor $canvas * @property Label $status * @property SkinPreview $preview * @property ComboBox $colorKey * @property TextBox $colorHex * @property Button $colorApply * @property Label $help * @property Radio $toolCrayon * @property Radio $toolPot * @property Radio $toolPipette * @property Radio $toolGomme * @property Radio $toolMain * @property TextBox $brush * @property Palette $palette * @property Button $undo * @property Button $redo * @property Button $import * @property Button $external * @property Button $reload * @property Button $save * @property Button $publish * @property Button $view * @property Button $quit */final class SkinEditorForm extends WinZikDialog{ private const COLOR_LABELS = [ 'title' => 'Titre qui défile', 'volume' => 'Texte du volume', 'balance' => 'Texte de la balance', 'kbps' => 'kbps', 'hours' => 'Heures', 'minutes' => 'Minutes', 'seconds' => 'Secondes', 'barGreenLeft' => 'Bargraph vert (gauche)', 'barGreenRight' => 'Bargraph vert (droite)', 'barOrangeLeft' => 'Bargraph orange (gauche)', 'barOrangeRight' => 'Bargraph orange (droite)', 'barRedLeft' => 'Bargraph rouge (gauche)', 'barRedRight' => 'Bargraph rouge (droite)', 'active' => 'Ligne en cours de la playlist', 'lines' => 'Lignes de la playlist (toutes)', ]; public string $window = 'main'; public string $part = 'main'; public string $tool = 'crayon'; /** the colour of the brush, '' = transparent */ public string $color = '#000000'; private ?SkinDocument $doc = null; /** @var list<Skin> */ private array $skins = []; /** @var array<string, int> the version of each preview file */ private array $previews = []; private string $previewDir = ''; private bool $quitAsked = false; /** the skin to start from asked while changes were not saved (chosen again: they are dropped), -1 none */ private int $sourceAsked = -1; private int $sourceIndex = 0; private bool $keysListened = false; /** the keys of the tools (out of a text field) */ private const TOOL_KEYS = ['c' => 'crayon', 'b' => 'crayon', 'p' => 'pot', 'i' => 'pipette', 'e' => 'gomme', 'm' => 'main', 'h' => 'main']; private const TOOL_NAMES = ['crayon' => 'Crayon', 'pot' => 'Pot de peinture', 'pipette' => 'Pipette', 'gomme' => 'Gomme', 'main' => 'Main']; protected function loaded(array $params = []): void { $this->previewDir = rtrim(sys_get_temp_dir(), '/') . '/winzik-edt/' . getmypid() . '-' . spl_object_id($this); $this->previews = []; $this->quitAsked = false; $this->sourceAsked = -1; if (!$this->keysListened) { // the letters of the tools: a key without text input still comes here (the form gets it as typed text) $this->keysListened = true; $this->engine->input->on('key', function (int $sym): void { if ($this->scenes()->current() === $this && !($this->focused() instanceof TextBox) && $this->overlay === null && !$this->engine->input->getKeyboard()->ctrlHeld()) { $this->shortcut($sym); } }); } $this->skins = $this->wz->skins(); $this->source->items = array_map(fn (Skin $s) => $s->name, $this->skins); $from = (string)($params['skin'] ?? $this->wz->skin->dir); $index = 0; foreach ($this->skins as $i => $skin) { if (realpath($skin->dir) === realpath($from)) { $index = $i; } } $this->source->selected = $index; $this->sourceIndex = $index; // a skin of the user is edited in place, a skin of the application is copied under a new name (SANSTITRE) $own = str_starts_with((string)realpath($from), (string)realpath($this->wz->storagePath('skins')) ?: "\0"); $name = (string)($params['name'] ?? ($own ? basename($from) : 'SANSTITRE')); $this->open($this->skins[$index]->dir ?? $from, $name); $this->windows->items = array_map(fn (array $w) => $w[0], array_values(SkinParts::WINDOWS)); $this->windows->selected = 0; $this->colorKey->items = array_values(self::COLOR_LABELS); $this->colorKey->selected = 0; $this->onColorKeyChange($this->colorKey, 0, ''); $this->selectWindow('main'); $this->useTool('crayon'); // the form is used again: the tool of last time is not the radio checked now $this->setColor('#000000'); $this->external->enabled = Platform::isDesktop() && !Platform::isWasm(); $this->reload->enabled = $this->external->enabled; $this->import->enabled = Native::supports('open'); } /** The pictures of the preview are temporary: removed when the editor goes. */ public function exit(): void { parent::exit(); if ($this->previewDir === '') { return; } foreach (glob($this->previewDir . '/*.png') ?: [] as $file) { Picture::forget($this->sdlOrNull(), $file); @unlink($file); } if (is_dir($this->previewDir)) { @rmdir($this->previewDir); } $this->previews = []; } public function document(): SkinDocument { return $this->doc ?? throw new \LogicException('No skin open'); } private function open(string $sourceDir, string $name): void { $name = SkinDocument::cleanName($name) ?: 'SANSTITRE'; $this->doc = new SkinDocument($sourceDir, $this->wz->storagePath('skins/' . $name), $name); $this->skinName->text = $name; $this->previews = []; } /** The picture of a piece as it is now, in a file the preview and the canvas draw (written again after a change). */ public function previewFile(string $part): string { $file = $this->previewDir . '/' . $part . '.png'; $version = $this->document()->version($part); if (($this->previews[$part] ?? -1) !== $version || !is_file($file)) { $this->document()->export($part, $file); Picture::forget($this->sdlOrNull(), $file); $this->previews[$part] = $version; } return $file; } // windows and pieces --------------------------------------------------------------------------------------- private function selectWindow(string $window): void { $this->window = $window; $parts = SkinParts::of($window); $this->part = $parts[0]; $this->refresh(); $this->parts->selected = 0; $this->canvas->zoom = 0; } public function selectPart(string $part): void { foreach (array_keys(SkinParts::WINDOWS) as $i => $window) { if ($window !== $this->window && in_array($part, SkinParts::of($window), true)) { $this->selectWindow($window); // a piece of another window: that window $this->windows->selected = $i; } } $parts = SkinParts::of($this->window); $i = array_search($part, $parts, true); if ($i === false) { return; } $this->part = $part; $this->parts->selected = (int)$i; $this->canvas->zoom = 0; $this->refresh(); } /** The list of the pieces (a * for the ones of this skin), the buttons, the status line. */ public function refresh(): void { $doc = $this->document(); $this->quitAsked = false; // something changed since Fermer was asked: asked again $this->parts->items = array_map(function (string $p) use ($doc): string { [$w, $h] = SkinParts::size($p); return ($doc->isModified($p) ? '* ' : ' ') . $p . ' (' . (SkinParts::LABELS[$p] ?? $p) . ', ' . $w . '×' . $h . ')'; }, SkinParts::of($this->window)); $this->undo->enabled = $doc->canUndo($this->part); $this->redo->enabled = $doc->canRedo($this->part); } protected function tick(float $dt): void { parent::tick($dt); if ($this->doc === null) { return; } [$w, $h] = $this->doc->size($this->part); $at = $this->canvas->hoverX >= 0 && $this->canvas->hoverX < $w && $this->canvas->hoverY >= 0 && $this->canvas->hoverY < $h ? sprintf(' x %d y %d %s', $this->canvas->hoverX, $this->canvas->hoverY, $this->doc->pixel($this->part, $this->canvas->hoverX, $this->canvas->hoverY) ?: 'transparent') : ''; [$undo, $redo] = $this->doc->history($this->part); $this->status->text = $this->part . '.png ' . $w . ' × ' . $h . ' zoom ' . (int)$this->canvas->zoom . ' ' . self::TOOL_NAMES[$this->tool] . ($undo > 0 ? ' annuler : ' . $undo : '') . ($redo > 0 ? ' rétablir : ' . $redo : '') . $at . ($this->doc->hasChanges() ? ' (non enregistré)' : ''); $this->undo->enabled = $this->doc->canUndo($this->part); $this->redo->enabled = $this->doc->canRedo($this->part); } public function onWindowsChange(ListBox $sender, int $index, string $item): void { $this->selectWindow(array_keys(SkinParts::WINDOWS)[$index] ?? 'main'); } public function onPartsChange(ListBox $sender, int $index, string $item): void { $parts = SkinParts::of($this->window); if (isset($parts[$index])) { $this->part = $parts[$index]; $this->canvas->zoom = 0; $this->refresh(); } } // the skin: its name, where it starts from ------------------------------------------------------------- /** LABEL5 / Text1_KeyPress: the name of the skin is its folder ("Veuiller ne pas insérer d'espace"). */ public function onNameChange(TextBox $sender, string $text): void { if (str_contains($text, ' ')) { $this->help->text = "Veuillez ne pas insérer d'espace"; $sender->text = str_replace(' ', '', $text); } } public function onNameSubmit(TextBox $sender): void { $name = SkinDocument::cleanName($sender->text) ?: 'SANSTITRE'; $sender->text = $name; $doc = $this->document(); $doc->name = $name; $doc->targetDir = $this->wz->storagePath('skins/' . $name); $doc->colorsChanged = true; $this->help->text = 'Le skin sera écrit dans ' . $doc->targetDir; $this->refresh(); } /** Image2_Click: another skin to start from (changes not saved: asked first, chosen again they are dropped). */ public function onSourceChange(ComboBox $sender, int $index, string $item): void { if (!isset($this->skins[$index]) || $index === $this->sourceIndex) { return; } if ($this->document()->hasChanges() && $this->sourceAsked !== $index) { $this->sourceAsked = $index; $sender->selected = $this->sourceIndex; $this->help->text = 'Des modifications ne sont pas enregistrées : Enregistrer d\'abord, ou choisir encore « ' . $this->skins[$index]->name . ' » pour les perdre.'; return; } $this->sourceAsked = -1; $this->sourceIndex = $index; $sender->selected = $index; $this->open($this->skins[$index]->dir, $this->skinName->text); $this->onColorKeyChange($this->colorKey, (int)$this->colorKey->selected, ''); $this->refresh(); $this->help->text = 'Nouveau départ : ' . $this->skins[$index]->name; } // the keys ---------------------------------------------------------------------------------------------- public function handle(Pointer $p): void { $this->canvas->aimX = $p->x; $this->canvas->aimY = $p->y; // a right click on the piece: its colour becomes the brush's (any tool) if ($p->right && $this->overlay === null && $this->canvas->contains($p->x, $p->y)) { [$px, $py] = $this->canvas->pixelAt($p->x, $p->y); [$w, $h] = $this->document()->size($this->part); if ($px >= 0 && $py >= 0 && $px < $w && $py < $h) { $tool = $this->tool; $this->pick($px, $py); $this->useTool($tool === 'pipette' ? 'crayon' : $tool); $this->help->text = 'Couleur prise : ' . ($this->color === '' ? 'transparent' : $this->color); } } if ($p->ctrl && $p->keys !== []) { $rest = []; foreach ($p->keys as $key) { if (!$this->shortcut($key, true, $p->shift)) { $rest[] = $key; } } $p->keys = $rest; } parent::handle($p); } /** A key of the editor: with Ctrl Z / Y / S, else the tools and the zoom. True when it was one. */ public function shortcut(int $sym, bool $ctrl = false, bool $shift = false): bool { $letter = $sym >= 65 && $sym <= 90 ? strtolower(chr($sym)) : ($sym >= 97 && $sym <= 122 ? chr($sym) : ''); if ($ctrl) { if ($letter === 'z' && !$shift) { return $this->undoStep(); } if ($letter === 'y' || $letter === 'z') { return $this->redoStep(); } if ($letter === 's') { $this->write(); return true; } return false; } if (isset(self::TOOL_KEYS[$letter])) { $this->useTool(self::TOOL_KEYS[$letter]); return true; } $zoom = match ($sym) { 43, 61, 1073741911 => 1, // + (and = of the same key), + of the keypad 45, 1073741910 => -1, // -, - of the keypad 48, 1073741922 => 0, // 0, 0 of the keypad default => null, }; if ($zoom === null) { return false; } $zoom === 0 ? $this->canvas->fit() : $this->canvas->zoomBy($zoom); return true; } private function undoStep(): bool { if (!$this->document()->undo($this->part)) { $this->help->text = 'Rien à annuler sur ' . $this->part . '.'; } $this->refresh(); return true; } private function redoStep(): bool { if (!$this->document()->redo($this->part)) { $this->help->text = 'Rien à rétablir sur ' . $this->part . '.'; } $this->refresh(); return true; } // the brush -------------------------------------------------------------------------------------------- public function onToolChange(Radio $sender, bool $checked): void { if (!$checked) { return; } $this->tool = match ($sender->props['id']) { 'toolPot' => 'pot', 'toolPipette' => 'pipette', 'toolGomme' => 'gomme', 'toolMain' => 'main', default => 'crayon', }; } public function setColor(string $color): void { $this->color = $color; $this->brush->text = $color === '' ? 'transparent' : $color; if ($this->tool === 'pipette' || $this->tool === 'gomme') { $this->useTool('crayon'); } } private function useTool(string $tool): void { $this->tool = $tool; foreach (['crayon' => 'toolCrayon', 'pot' => 'toolPot', 'pipette' => 'toolPipette', 'gomme' => 'toolGomme', 'main' => 'toolMain'] as $t => $id) { $this->$id->checked = $t === $tool; } } public function onBrushSubmit(TextBox $sender): void { $value = trim($sender->text); if (in_array(strtolower($value), ['transparent', 't', ''], true)) { $this->setColor(''); } elseif (($color = self::parseColor($value)) !== null) { $this->setColor($color); $this->help->text = 'Couleur du pinceau : ' . $color; } else { $this->help->text = 'Couleur inconnue : #rrggbb, #rgb (ex. #0f0) ou transparent'; $sender->text = $this->color === '' ? 'transparent' : $this->color; } } /** '#rrggbb' from '#rrggbb', 'rrggbb', '#rgb' or 'rgb' (any case), null when it is no colour. */ public static function parseColor(string $value): ?string { $value = strtolower(trim($value)); if (preg_match('/^#?([0-9a-f]{6})$/', $value, $m)) { return '#' . $m[1]; } if (preg_match('/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/', $value, $m)) { return '#' . $m[1] . $m[1] . $m[2] . $m[2] . $m[3] . $m[3]; } return null; } /** The pipette: the colour of a pixel becomes the brush's. */ public function pick(int $x, int $y): void { $this->setColor($this->document()->pixel($this->part, $x, $y)); } // undo, import, other programs ---------------------------------------------------------------------------- public function onUndoClick(Button $sender): void { $this->undoStep(); } public function onRedoClick(Button $sender): void { $this->redoStep(); } public function onImportClick(Button $sender): void { $part = $this->part; FilePicker::open(['title' => 'Une image pour ' . $part, 'filters' => ['Images' => ['png', 'gif', 'bmp', 'jpg', 'jpeg']]]) ->then(function (mixed $file) use ($part): void { if (is_string($file) && $file !== '') { $this->help->text = $this->document()->import($part, $file) ? basename($file) . ' mis à la taille de ' . $part : basename($file) . " n'est pas une image"; $this->refresh(); } }); } /** Image1_Click: the piece opened in the drawing program of the computer (Photoshop 5.0 in 2001). */ public function onExternalClick(Button $sender): void { $doc = $this->document(); if (!$doc->save()) { $this->help->text = $doc->error; return; } $file = $doc->targetDir . '/' . $this->part . '.png'; if (!Shell::openPath($file)) { $this->help->text = 'Impossible d\'ouvrir ' . $file; return; } $this->help->text = 'Une fois l\'image enregistrée dans l\'autre logiciel : Recharger.'; $this->refresh(); } /** Image4_Click (redess): the piece read again from its file. */ public function onReloadClick(Button $sender): void { $this->document()->reload($this->part); $this->refresh(); } // colours --------------------------------------------------------------------------------------------- public function onColorKeyChange(ComboBox $sender, int $index, string $item): void { $key = array_keys(self::COLOR_LABELS)[$index] ?? 'title'; $doc = $this->document(); $this->colorHex->text = $key === 'lines' ? ($doc->lineColors[0] ?? '#8080ff') : ($doc->colors[$key] ?? '#ffffff'); } public function onColorApply(mixed $sender): void { $key = array_keys(self::COLOR_LABELS)[(int)$this->colorKey->selected] ?? 'title'; $color = self::parseColor($this->colorHex->text); if ($color === null) { $this->help->text = 'Couleur inconnue : #rrggbb ou #rgb (ex. #ff00ff)'; return; } $this->colorHex->text = $color; $doc = $this->document(); if ($key === 'lines') { $doc->lineColors = array_fill(0, 23, $color); } else { $doc->colors[$key] = $color; } $doc->colorsChanged = true; $this->help->text = self::COLOR_LABELS[$key] . ' : ' . $color; } // the end --------------------------------------------------------------------------------------------- public function onSaveClick(Button $sender): void { $this->write(); } private function write(): bool { $doc = $this->document(); if (!$doc->save()) { $this->help->text = 'Skin non enregistré. ' . $doc->error; $this->refresh(); return false; } foreach (glob($doc->targetDir . '/*.png') ?: [] as $file) { Picture::forget($this->sdlOrNull(), $file); // the player draws the new pictures } if (realpath($this->wz->skin->dir) === realpath($doc->targetDir)) { $this->wz->useSkin($doc->targetDir); } $this->help->text = 'Skin « ' . $doc->name . ' » enregistré dans ' . $doc->targetDir; $this->refresh(); return true; } /** Saved in var/skins, then the marketplace to send it. */ public function onPublishClick(Button $sender): void { if ($this->write()) { $this->scenes()->push(MarketForm::class, ['kind' => 'skin']); } } /** Image11_Click: winzik.exe SKIN:<folder>. */ public function onViewClick(Button $sender): void { if ($this->write()) { $this->wz->useSkin($this->document()->targetDir); $this->wz->save(); $this->scenes()->switchTo(MainForm::class, [], false); } } public function onQuitClick(Button $sender): void { if ($this->document()->hasChanges() && !$this->quitAsked) { $this->quitAsked = true; $this->help->text = 'Des modifications ne sont pas enregistrées : Enregistrer (Ctrl+S), ou Fermer (Échap) encore une fois pour les perdre.'; return; } $this->scenes()->switchTo(MainForm::class, [], false); }}