TR
apps/winzik / src / Form / TagForm.php · commit 6576d6f
<?phpnamespace App\Form;use App\Model\Id3Tag;use App\Model\Text;use JumPHP\Gui\Button;use JumPHP\Gui\ComboBox;use JumPHP\Gui\Label;use JumPHP\Gui\TextBox;/** * Form6 of 2001: the ID3v1 tag of the song (only MP3 files have one). "Mettre à jour" writes it and goes on, * "Ok" writes it and closes, "Annuler" closes. * * @property Label $fileName * @property TextBox $songTitle * @property TextBox $artist * @property TextBox $album * @property TextBox $comment * @property TextBox $year * @property ComboBox $genre * @property Label $info * @property Label $error * @property TextBox $markStart * @property TextBox $markEnd * @property Button $startHere * @property Button $endHere * @property Button $marksClear * @property Button $update * @property Button $cancel * @property Button $ok */final class TagForm extends WinZikDialog{    private string $path = '';    protected function loaded(array $params = []): void    {        $this->genre->items = Id3Tag::genreItems();        $this->showError('');        $player = $this->wz->player;        $this->path = (string)$player->file;        $editable = $this->path !== '' && Text::extension($this->path) === 'mp3';        $tag = $this->wz->tag;        $this->fileName->text = $this->path === '' ? 'Pas de chanson chargée' : Text::baseName($this->path);        $this->songTitle->text = $tag->title;        $this->artist->text = $tag->artist;        $this->album->text = $tag->album;        $this->comment->text = $tag->comment;        $this->year->text = $tag->year;        $this->genre->selected = $tag->present ? $tag->genre : Id3Tag::OTHER;        foreach ([$this->songTitle, $this->artist, $this->album, $this->comment, $this->year, $this->genre, $this->update, $this->ok] as $widget) {            $widget->enabled = $editable;        }        $info = $player->info;        $this->info->text = $this->path === '' ? '' : sprintf('%s  -  %d:%02d  -  %s kbps  -  %s Hz%s',            strtoupper(Text::extension($this->path)), intdiv((int)$info->duration, 60), (int)$info->duration % 60,            $info->kbps > 0 ? (string)$info->kbps : 'N/A', $info->sampleRate > 0 ? (string)$info->sampleRate : '?',            $editable ? '' : '  -  pas de tag ID3 pour ce format');        // where it is played from / to (its marks: by hand, YouTube's chapters, or found in its sound)        [$start, $end, $src] = $this->path !== '' ? $this->wz->bounds($this->path) : [0.0, 0.0, ''];        $this->markStart->text = $start > 0 ? sprintf('%.2f', $start) : '';        $this->markEnd->text = $end > 0 ? sprintf('%.2f', $end) : '';        $this->marksFrom = [$this->markStart->text, $this->markEnd->text];        foreach ([$this->markStart, $this->markEnd, $this->startHere, $this->endHere, $this->marksClear] as $widget) {            $widget->enabled = $this->path !== '';        }        $this->ok->enabled = $this->path !== '';        if ($src !== '') {            $this->info->text .= '  -  repères : ' . ['manual' => 'à la main', 'yt' => 'chapitres YouTube', 'auto' => 'trouvés dans le son'][$src];        }        $this->setFocus($editable ? $this->songTitle : $this->cancel);    }    /** @var array{0: string, 1: string} the marks shown when it opened (changed: written) */    private array $marksFrom = ['', ''];    public function onStartHereClick(Button $sender): void    {        $this->markStart->text = sprintf('%.2f', $this->wz->player->position);    }    public function onEndHereClick(Button $sender): void    {        $this->markEnd->text = sprintf('%.2f', $this->wz->player->position);    }    public function onMarksClearClick(Button $sender): void    {        $this->markStart->text = $this->markEnd->text = '';    }    /** The marks typed, when they changed: into the ID3 tag (MP3) and marks.json. */    private function writeMarks(): void    {        if ($this->path === '' || [$this->markStart->text, $this->markEnd->text] === $this->marksFrom) {            return;        }        $num = fn (string $v) => max(0.0, (float)str_replace(',', '.', trim($v)));        $this->wz->setBounds($this->path, $num($this->markStart->text), $num($this->markEnd->text));        $this->marksFrom = [$this->markStart->text, $this->markEnd->text];    }    /** Text5_Change: four digits typed, the genre comes next. */    public function onYearChange(TextBox $sender, string $text): void    {        if (strlen($text) === 4) {            $this->setFocus($this->genre);        }    }    public function onUpdateClick(Button $sender): void    {        if ($this->check()) {            $this->write();            $this->writeMarks();        }    }    public function onOkClick(Button $sender): void    {        if (!$this->check()) {            return;        }        $editable = Text::extension($this->path) === 'mp3';        if (!$editable || $this->write()) {            $this->writeMarks();            $this->close();        }    }    public function onCancelClick(Button $sender): void    {        $this->close();    }    /** What was typed can be written: else the error says what is wrong and what to do, and the field gets the focus. */    private function check(): bool    {        $year = trim($this->year->text);        if ($this->year->isEnabled() && $year !== '' && !preg_match('/^\d{4}$/', $year)) {            return $this->fail($this->year, "L'année doit faire 4 chiffres (ex : 2001) : corrigez-la ou laissez-la vide.");        }        $mark = fn (string $v) => trim($v) === '' ? 0.0 : (is_numeric($n = str_replace(',', '.', trim($v))) ? (float)$n : null);        $start = $mark($this->markStart->text);        $end = $mark($this->markEnd->text);        if ($start === null || $start < 0) {            return $this->fail($this->markStart, 'Début : un nombre de secondes (ex : 12,5), ou vide pour le début du morceau.');        }        if ($end === null || $end < 0) {            return $this->fail($this->markEnd, "Fin : un nombre de secondes (ex : 185), ou vide pour aller jusqu'à la fin.");        }        if ($end > 0 && $end <= $start) {            return $this->fail($this->markEnd, 'La fin doit venir après le début : changez l\'une des deux, ou videz la fin.');        }        $this->showError('');        return true;    }    private function fail(TextBox $field, string $message): bool    {        $this->showError($message);        $this->setFocus($field);        return false;    }    private function showError(string $message): void    {        $this->error->text = $message;        $this->error->visible = $message !== '';    }    private function write(): bool    {        if ($this->path === '' || Text::extension($this->path) !== 'mp3') {            return false;        }        $tag = new Id3Tag(trim($this->songTitle->text), trim($this->artist->text), trim($this->album->text),            trim($this->year->text), trim($this->comment->text), max(0, (int)$this->genre->selected));        if (!$tag->write($this->path)) {            $this->showError("Impossible d'écrire le tag dans ce fichier : il est peut-être en lecture seule ou ouvert ailleurs. Vérifiez ses droits, puis réessayez.");            return false;        }        $this->wz->tag = $tag;        $this->wz->forget($this->path);        $this->info->text = 'Tag écrit dans ' . Text::baseName($this->path);        return true;    }}