<?phpnamespace App\Form;use App\Model\Playlist;use App\Model\Text;use JumPHP\Gui\Button;use JumPHP\Gui\CheckBox;use JumPHP\Gui\ComboBox;use JumPHP\Gui\Label;use JumPHP\Gui\ListBox;use JumPHP\Gui\ProgressBar;use JumPHP\Gui\TextBox;use JumPHP\Kernel\Platform;use JumPHP\Native\FilePicker;use JumPHP\Native\Native;/** * Form3 of 2001 (DriveListBox, DirListBox, FileListBox, "Ajouter le répertoire", "Autres chemins") and Form13 (the * search in the sub-folders: "RECHERCHE EN COURS", the MP3 / WAV / MID found, the folder being read, Annuler). * The search never blocks: a few hundred entries per frame. In the browser the songs of the computer come through * the system's file chooser and are kept in var/music. * * @property ComboBox $places * @property Button $import * @property TextBox $path * @property Button $go * @property ListBox $dirs * @property ListBox $files * @property CheckBox $subdirs * @property Label $status * @property ProgressBar $progress * @property Button $addDir * @property Button $addFile * @property Button $cancel */final class FilesForm extends WinZikDialog{ private string $dir = ''; /** @var list<string> the places of the combo box (DriveListBox) */ private array $placeDirs = []; /** @var list<string> the folders shown, full paths */ private array $dirPaths = []; /** @var list<string> */ private array $filePaths = []; /** the search (Recherche.cls): folders left, files found, counters */ private ?array $search = null; protected function loaded(array $params = []): void { $places = ['Musique de démo' => $this->wz->path('assets/music'), 'Fichiers importés' => $this->wz->storagePath('music')]; if (Platform::isDesktop()) { $home = (string)(getenv('HOME') ?: getenv('USERPROFILE') ?: '/'); $places['Dossier personnel'] = $home; foreach (['Musique', 'Music', 'Téléchargements', 'Downloads'] as $sub) { if (is_dir($home . '/' . $sub)) { $places[$sub] = $home . '/' . $sub; } } $places['Racine (/)'] = '/'; } @mkdir($places['Fichiers importés'], 0777, true); $this->places->items = array_keys($places); $this->placeDirs = array_values($places); $this->places->selected = 0; $this->search = null; $this->progress->visible = false; $this->status->text = ''; $last = (string)($this->wz->ui['filesDir'] ?? ''); $this->open($last !== '' && is_dir($last) ? $last : $this->placeDirs[0]); $this->import->enabled = Native::supports('open'); $this->import->tooltip = $this->import->enabled ? '' : 'Pas de sélecteur de fichiers ici : tapez le chemin du dossier, puis Entrée'; // the songs at hand: arrows, then Entrée adds the one chosen $this->setFocus($this->filePaths !== [] ? $this->files : $this->path); } private function open(string $dir): void { $dir = rtrim($dir, '/') ?: '/'; if (!is_dir($dir) || !is_readable($dir)) { $this->status->text = "Ce dossier n'existe pas ou ne peut pas être lu : " . $dir . ' - vérifiez le chemin (ex : /home/moi/Musique).'; return; } $this->dir = $dir; $this->path->text = $dir; $this->wz->ui['filesDir'] = $dir; $dirs = []; $files = []; foreach (scandir($dir) ?: [] as $entry) { if ($entry === '.' || $entry === '..' || $entry[0] === '.') { continue; } $full = ($dir === '/' ? '' : $dir) . '/' . $entry; if (is_dir($full)) { $dirs[] = $full; } elseif (Playlist::isMedia($entry)) { $files[] = $full; } } natcasesort($dirs); natcasesort($files); $this->dirPaths = $dir === '/' ? array_values($dirs) : array_merge([dirname($dir)], array_values($dirs)); $this->dirs->items = array_map(fn (string $d) => $d === dirname($dir) && $dir !== '/' && $d === $this->dirPaths[0] ? '[..]' : '[' . basename($d) . ']', $this->dirPaths); $this->filePaths = array_values($files); $this->files->items = array_map(fn (string $f) => basename($f), $this->filePaths); $this->files->selected = $this->filePaths === [] ? -1 : 0; $this->dirs->selected = -1; $this->addFile->enabled = $this->filePaths !== []; $this->status->text = count($this->filePaths) . ' fichier(s) audio, ' . count($dirs) . ' répertoire(s)'; } public function onPlacesChange(ComboBox $sender, int $index, string $item): void { $this->open($this->placeDirs[$index] ?? '/'); } public function onPathSubmit(TextBox $sender): void { $this->open(trim($this->path->text)); } /** Command2_Click: "Quel chemin désiré vous (ex: c:\WinZik\)" */ public function onGoClick(Button $sender): void { $this->open(trim($this->path->text)); } public function onDirsActivate(ListBox $sender, int $index, string $item): void { if (isset($this->dirPaths[$index])) { $this->open($this->dirPaths[$index]); } } /** File1_DblClick: the file goes into the list. */ public function onFilesActivate(ListBox $sender, int $index, string $item): void { if (isset($this->filePaths[$index])) { $this->wz->addFiles([$this->filePaths[$index]]); $this->status->text = basename($this->filePaths[$index]) . ' ajouté à la playlist'; } } /** Command3_Click: the file selected goes into the list. */ public function onAddFileClick(Button $sender): void { $this->onFilesActivate($this->files, (int)$this->files->selected, ''); } /** Command1_Click: the files of the folder (and of its sub-folders: Recherche.cls, Form13). */ public function onAddDirClick(Button $sender): void { if (!$this->subdirs->checked) { $added = $this->wz->addFiles($this->filePaths); $this->status->text = $added . ' fichier(s) ajouté(s) à la playlist'; return; } $this->search = ['dirs' => [$this->dir], 'files' => [], 'mp3' => 0, 'wav' => 0, 'mid' => 0, 'other' => 0, 'seen' => 0, 'current' => $this->dir]; $this->progress->visible = true; $this->addDir->enabled = false; $this->cancel->text = 'Annuler la recherche'; } protected function tick(float $dt): void { parent::tick($dt); if ($this->search === null) { return; } $budget = 300; while ($budget > 0 && $this->search['dirs'] !== []) { $dir = array_shift($this->search['dirs']); $this->search['current'] = $dir; foreach (@scandir($dir) ?: [] as $entry) { $budget--; if ($entry === '.' || $entry === '..' || $entry[0] === '.') { continue; } $full = ($dir === '/' ? '' : $dir) . '/' . $entry; if (is_dir($full) && !is_link($full)) { $this->search['dirs'][] = $full; } elseif (Playlist::isMedia($entry)) { $this->search['files'][] = $full; $kind = Text::extension($entry); $key = match ($kind) { 'mp3' => 'mp3', 'wav' => 'wav', 'mid', 'midi' => 'mid', default => 'other' }; $this->search[$key]++; } } $this->search['seen']++; } $s = $this->search; $this->status->text = sprintf('RECHERCHE EN COURS - MP3 : %d WAV : %d MID : %d autres : %d - %s', $s['mp3'], $s['wav'], $s['mid'], $s['other'], $s['current']); $total = $s['seen'] + count($s['dirs']); $this->progress->value = $total > 0 ? (int)(100 * $s['seen'] / $total) : 100; if ($s['dirs'] === []) { $files = $s['files']; natcasesort($files); $added = $this->wz->addFiles(array_values($files)); $this->endSearch($added . ' fichier(s) ajouté(s) à la playlist (MP3 : ' . $s['mp3'] . ', WAV : ' . $s['wav'] . ', MID : ' . $s['mid'] . ', autres : ' . $s['other'] . ')'); } } private function endSearch(string $message): void { $this->search = null; $this->progress->visible = false; $this->addDir->enabled = true; $this->cancel->text = 'Fermer'; $this->status->text = $message; } /** The system's file chooser (in the browser the only way to the computer's files): copied into var/music. */ public function onImportClick(Button $sender): void { if (!Native::supports('open')) { $this->status->text = 'Pas de sélecteur de fichiers ici : tapez le chemin du dossier, puis Entrée.'; return; } FilePicker::open(['multiple' => true, 'title' => 'Ajouter des fichiers', 'filters' => ['Musique et paroles' => ['mp3', 'wav', 'ogg', 'flac', 'mid', 'lyr', 'fls']]]) ->then(fn (mixed $files) => $this->imported(is_array($files) ? $files : ($files === null ? [] : [(string)$files])), fn (\Throwable $e) => $this->status->text = 'Import impossible (' . $e->getMessage() . ') : réessayez, ou tapez le chemin du dossier.'); } /** @param list<string> $files */ private function imported(array $files): void { $songs = $lyrics = []; foreach ($files as $file) { $ext = Text::extension($file); if ($ext === 'lyr') { $lyrics[] = $file; continue; } $keep = $file; if (Platform::isWasm() || str_starts_with($file, sys_get_temp_dir())) { // the chosen file is in the engine's memory only: kept in var/ (saved with the application) $keep = $this->wz->storagePath('music/' . basename($file)); @mkdir(dirname($keep), 0777, true); @copy($file, $keep); } if ($ext === 'fls') { $this->wz->loadFls($keep); } else { $songs[] = $keep; } $this->wz->forget($keep); } $added = $this->wz->addFiles($songs); foreach ($lyrics as $file) { $this->keepLyrics($file); } $this->status->text = $files === [] ? 'Aucun fichier choisi' : $added . ' fichier(s) ajouté(s) à la playlist'; $this->open($this->dir); } /** * A .LYR chosen: the lyrics of each song of the list of that name (WinZik::lyricsCachePath(): looked for first, for that * song only); no such song yet: in var/lyr under its own name (the lookup of before 0.10.6 finds it for any song of * that name), only when the file is in the engine's memory (else it stays where it is, next to its song). */ private function keepLyrics(string $file): void { $name = Text::baseName(Text::withoutExtension($file)); $targets = []; foreach ($this->wz->playlist->items as $song) { if (Text::baseName(Text::withoutExtension($this->wz->path($song))) === $name) { $targets[$this->wz->lyricsCachePath($song)] = $song; } } if ($targets === [] && (Platform::isWasm() || str_starts_with($file, sys_get_temp_dir()))) { $targets[$this->wz->storagePath('lyr/' . basename($file))] = $file; } foreach ($targets as $target => $song) { @mkdir(dirname($target), 0777, true); @copy($file, $target); $this->wz->forget($song); } } public function onCancelClick(Button $sender): void { if ($this->search !== null) { // Form13.Command1_Click: the search stops, what was found is kept $files = $this->search['files']; $added = $this->wz->addFiles($files); $this->endSearch('Recherche annulée : ' . $added . ' fichier(s) ajouté(s)'); return; } $this->close(); }}