From 860eed26a6fd480543e3d5f80a4499960de37cad Mon Sep 17 00:00:00 2001 From: Dev-lib4n Date: Wed, 18 Nov 2026 13:28:07 -0300 Subject: [PATCH] feat(tui): implement numeric menu navigation and automatic screen clearing --- .../Concerns/InteractsWithTerminal.php | 242 ++++++++++++++++++ app/Commands/ToolboxMenuCommand.php | 193 +++++++++----- lang/en/messages.php | 10 +- lang/pt_BR/messages.php | 18 +- 4 files changed, 396 insertions(+), 67 deletions(-) create mode 100644 app/Commands/Concerns/InteractsWithTerminal.php diff --git a/app/Commands/Concerns/InteractsWithTerminal.php b/app/Commands/Concerns/InteractsWithTerminal.php new file mode 100644 index 0000000..a4e730a --- /dev/null +++ b/app/Commands/Concerns/InteractsWithTerminal.php @@ -0,0 +1,242 @@ +input) || ! $this->input->isInteractive()) { + return false; + } + + if (! defined('STDIN') || ! defined('STDOUT')) { + return false; + } + + if (function_exists('stream_isatty')) { + return @stream_isatty(STDIN) && @stream_isatty(STDOUT); + } + + return false; + } + + /** + * Clear the terminal viewport and reposition the cursor at the top-left corner. + */ + protected function clearScreen(): void + { + if (! $this->isInteractiveTty()) { + return; + } + + if (PHP_OS_FAMILY === 'Windows' && function_exists('sapi_windows_vt100_support')) { + @sapi_windows_vt100_support(STDOUT, true); + } + + fwrite(STDOUT, "\033[2J\033[H\033[3J"); + fflush(STDOUT); + } + + /** + * Render the compact top banner showing tool name, detected OS, privilege level, and active locale. + */ + protected function renderHeader(?string $locale = null): void + { + $activeLocale = $locale ?? (app()->getLocale() ?: 'en'); + $langBadge = $activeLocale === 'pt_BR' ? 'PT-BR' : 'EN'; + $privilegeLabel = $this->isElevatedPrivilege() + ? (string) __('messages.app.privilege_admin') + : (string) __('messages.app.privilege_user'); + + info(sprintf( + '=== %s — %s ===', + strtoupper((string) __('messages.app.name')), + (string) __('messages.app.tagline') + )); + + note((string) __('messages.app.header_status', [ + 'os' => PHP_OS_FAMILY, + 'privilege' => $privilegeLabel, + 'lang' => $langBadge, + ])); + } + + /** + * Display a numbered menu ([1]..[N], [0]) and capture the user's numeric selection. + * + * @param string $promptLabel + * @param array $options Map of numeric key ('1', '2', ..., '0') to translated label. + * @param string $defaultKey + * @return string The selected key from $options. + */ + protected function promptNumericMenu(string $promptLabel, array $options, string $defaultKey = '1'): string + { + $lines = []; + foreach ($options as $key => $label) { + $lines[] = sprintf(' [%s] %s', $key, $label); + } + + note($promptLabel . PHP_EOL . PHP_EOL . implode(PHP_EOL, $lines)); + + $validKeys = array_map('strval', array_keys($options)); + $optionsList = implode(', ', $validKeys); + + if (PHP_OS_FAMILY !== 'Windows' && $this->isInteractiveTty() && Process::isTtySupported()) { + $singleKey = $this->readSingleKeyUnix($validKeys, $optionsList); + if ($singleKey !== null) { + return $singleKey; + } + } + + $selected = text( + label: (string) __('messages.menu.numeric_hint', ['options' => $optionsList]), + default: in_array($defaultKey, $validKeys, true) ? $defaultKey : ($validKeys[0] ?? '0'), + validate: fn (string $value): ?string => in_array(trim($value), $validKeys, true) + ? null + : (string) __('messages.menu.invalid_option', ['options' => $optionsList]), + ); + + return trim($selected); + } + + /** + * Pause execution after running a submenu command until the user presses Enter or any key. + */ + protected function waitForKeyPress(): void + { + if (! isset($this->input) || ! $this->input->isInteractive()) { + return; + } + + $prompt = (string) __('messages.menu.press_any_key'); + + if (! defined('STDIN') || ! defined('STDOUT')) { + return; + } + + fwrite(STDOUT, PHP_EOL . ' ' . $prompt . ' '); + fflush(STDOUT); + + if (PHP_OS_FAMILY !== 'Windows' && $this->isInteractiveTty() && Process::isTtySupported()) { + if ($this->setUnixSttyMode(['-icanon', '-echo'])) { + try { + @fread(STDIN, 1); + } finally { + $this->setUnixSttyMode(['sane']); + } + fwrite(STDOUT, PHP_EOL); + + return; + } + } + + @fgets(STDIN); + } + + /** + * Read a single valid numeric keystroke immediately on Unix/Linux interactive terminals using stty. + * + * @param array $validKeys + */ + protected function readSingleKeyUnix(array $validKeys, string $optionsList): ?string + { + if (! $this->setUnixSttyMode(['-icanon', '-echo'])) { + return null; + } + + fwrite(STDOUT, ' > ' . (string) __('messages.menu.numeric_hint', ['options' => $optionsList]) . ': '); + fflush(STDOUT); + + try { + while (true) { + $char = @fread(STDIN, 1); + if ($char === false || $char === '') { + return null; + } + + // Handle Ctrl+C (\x03) gracefully + if ($char === "\x03") { + $this->setUnixSttyMode(['sane']); + fwrite(STDOUT, PHP_EOL); + exit(130); + } + + if (in_array($char, $validKeys, true)) { + fwrite(STDOUT, $char . PHP_EOL); + fflush(STDOUT); + + return $char; + } + } + } finally { + $this->setUnixSttyMode(['sane']); + } + } + + /** + * Configure Unix terminal line settings safely via Symfony Process with argument arrays. + * + * @param array $sttyArgs + */ + protected function setUnixSttyMode(array $sttyArgs): bool + { + try { + $process = new Process(['stty', ...$sttyArgs]); + $process->setTty(true); + $process->run(); + + return $process->isSuccessful(); + } catch (Throwable) { + return false; + } + } + + /** + * Detect whether the current process is running with Administrator (Windows) or Root (Linux) privileges. + */ + protected function isElevatedPrivilege(): bool + { + if ($this->cachedIsElevated !== null) { + return $this->cachedIsElevated; + } + + try { + /** @var ProcessExecutorInterface $executor */ + $executor = app(ProcessExecutorInterface::class); + + if (PHP_OS_FAMILY === 'Windows') { + $result = $executor->run(['net', 'session'], 5); + $this->cachedIsElevated = $result->successful; + + return $this->cachedIsElevated; + } + + $this->cachedIsElevated = $executor->getEffectiveUid() === 0; + + return $this->cachedIsElevated; + } catch (Throwable) { + $this->cachedIsElevated = false; + + return false; + } + } +} diff --git a/app/Commands/ToolboxMenuCommand.php b/app/Commands/ToolboxMenuCommand.php index 8f8ab36..1d9d67d 100644 --- a/app/Commands/ToolboxMenuCommand.php +++ b/app/Commands/ToolboxMenuCommand.php @@ -5,15 +5,15 @@ namespace App\Commands; use App\Commands\Concerns\InteractsWithLocale; +use App\Commands\Concerns\InteractsWithTerminal; use LaravelZero\Framework\Commands\Command; use function Laravel\Prompts\info; -use function Laravel\Prompts\note; -use function Laravel\Prompts\select; class ToolboxMenuCommand extends Command { use InteractsWithLocale; + use InteractsWithTerminal; /** * The signature of the command. @@ -36,34 +36,46 @@ class ToolboxMenuCommand extends Command */ public function handle(): int { - $locale = $this->resolveLocale(promptIfMissing: true); - - $this->renderHeader(); + $locale = $this->resolveInitialLocale(); while (true) { - $category = (string) select( - label: (string) __('messages.menu.main_prompt'), + $this->clearScreen(); + $this->renderHeader($locale); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.menu.main_prompt'), options: [ - 'system' => (string) __('messages.menu.categories.system'), - 'printers' => (string) __('messages.menu.categories.printers'), - 'network' => (string) __('messages.menu.categories.network'), - 'maintenance' => (string) __('messages.menu.categories.maintenance'), - 'reports' => (string) __('messages.menu.categories.reports'), - 'language' => (string) __('messages.menu.categories.language'), - 'exit' => (string) __('messages.menu.exit'), + '1' => (string) __('messages.menu.categories.system'), + '2' => (string) __('messages.menu.categories.printers'), + '3' => (string) __('messages.menu.categories.network'), + '4' => (string) __('messages.menu.categories.maintenance'), + '5' => (string) __('messages.menu.categories.reports'), + '6' => (string) __('messages.menu.categories.language'), + '0' => (string) __('messages.menu.exit'), ], + defaultKey: '1', ); - if ($category === 'exit') { + if ($choice === '0') { + $this->clearScreen(); info((string) __('messages.app.goodbye')); return self::SUCCESS; } - if ($category === 'language') { - $locale = $this->promptForLanguage(); - $this->renderHeader(); + if ($choice === '5') { + $this->executeSubcommand('report:export', $locale); + } elseif ($choice === '6') { + $locale = $this->promptNumericLanguageSwitch($locale); } else { + $category = match ($choice) { + '1' => 'system', + '2' => 'printers', + '3' => 'network', + '4' => 'maintenance', + default => 'system', + }; + $this->handleCategorySubmenu($category, $locale); } @@ -74,58 +86,121 @@ public function handle(): int } /** - * Render the TUI header banner. + * Resolve the initial locale from --lang or display the numeric language selector. */ - protected function renderHeader(): void + protected function resolveInitialLocale(): string { - info(sprintf('%s — %s', (string) __('messages.app.name'), (string) __('messages.app.tagline'))); - note((string) __('messages.app.detected_os', ['os' => PHP_OS_FAMILY])); + $optionLocale = $this->option('lang'); + + if (is_string($optionLocale) && $optionLocale !== '') { + return $this->resolveLocale(promptIfMissing: false); + } + + $this->clearScreen(); + $this->renderHeader('en'); + + return $this->promptNumericLanguageSwitch('en', allowBack: false); } /** - * Display the submenu for the chosen category and dispatch the selected command. + * Display a numbered language switcher ([1] English, [2] Português, and optionally [0] Back). */ - protected function handleCategorySubmenu(string $category, string $locale): void + protected function promptNumericLanguageSwitch(string $currentLocale, bool $allowBack = true): string { - $options = match ($category) { - 'system' => [ - 'system:info' => (string) __('messages.menu.actions.system_info'), - 'system:top' => (string) __('messages.menu.actions.system_top'), - 'back' => (string) __('messages.menu.back'), - ], - 'printers' => [ - 'printer:list' => (string) __('messages.menu.actions.printer_list'), - 'printer:clear' => (string) __('messages.menu.actions.printer_clear'), - 'back' => (string) __('messages.menu.back'), - ], - 'network' => [ - 'network:check' => (string) __('messages.menu.actions.network_check'), - 'network:flush' => (string) __('messages.menu.actions.network_flush'), - 'network:ports' => (string) __('messages.menu.actions.network_ports'), - 'back' => (string) __('messages.menu.back'), - ], - 'maintenance' => [ - 'clean:temp' => (string) __('messages.menu.actions.clean_temp'), - 'back' => (string) __('messages.menu.back'), - ], - 'reports' => [ - 'report:export' => (string) __('messages.menu.actions.report_export'), - 'back' => (string) __('messages.menu.back'), - ], - default => [ - 'back' => (string) __('messages.menu.back'), - ], - }; - - $action = (string) select( - label: (string) __('messages.menu.sub_prompt'), + if ($allowBack) { + $this->clearScreen(); + $this->renderHeader($currentLocale); + } + + $options = [ + '1' => (string) __('messages.language.en'), + '2' => (string) __('messages.language.pt_BR'), + ]; + + if ($allowBack) { + $options['0'] = (string) __('messages.menu.back'); + } + + $defaultKey = $currentLocale === 'pt_BR' ? '2' : '1'; + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.language.select_prompt'), options: $options, + defaultKey: $defaultKey, ); - if ($action === 'back') { - return; + if ($choice === '0') { + return $currentLocale; + } + + $selectedLocale = $choice === '2' ? 'pt_BR' : 'en'; + $this->applyLocale($selectedLocale); + + return $selectedLocale; + } + + /** + * Display the numbered submenu for the chosen category in a loop until [0] Back is selected. + */ + protected function handleCategorySubmenu(string $category, string $locale): void + { + while (true) { + $this->clearScreen(); + $this->renderHeader($locale); + + /** @var array $actionsMap */ + $actionsMap = match ($category) { + 'system' => [ + '1' => ['label' => (string) __('messages.menu.actions.system_info'), 'command' => 'system:info'], + '2' => ['label' => (string) __('messages.menu.actions.system_top'), 'command' => 'system:top'], + ], + 'printers' => [ + '1' => ['label' => (string) __('messages.menu.actions.printer_list'), 'command' => 'printer:list'], + '2' => ['label' => (string) __('messages.menu.actions.printer_clear'), 'command' => 'printer:clear'], + ], + 'network' => [ + '1' => ['label' => (string) __('messages.menu.actions.network_check'), 'command' => 'network:check'], + '2' => ['label' => (string) __('messages.menu.actions.network_flush'), 'command' => 'network:flush'], + '3' => ['label' => (string) __('messages.menu.actions.network_ports'), 'command' => 'network:ports'], + ], + 'maintenance' => [ + '1' => ['label' => (string) __('messages.menu.actions.clean_temp'), 'command' => 'clean:temp'], + ], + default => [], + }; + + $menuOptions = []; + foreach ($actionsMap as $num => $item) { + $menuOptions[$num] = $item['label']; + } + $menuOptions['0'] = (string) __('messages.menu.back'); + + $choice = $this->promptNumericMenu( + promptLabel: (string) __('messages.menu.sub_prompt'), + options: $menuOptions, + defaultKey: '1', + ); + + if ($choice === '0' || ! isset($actionsMap[$choice])) { + return; + } + + $this->executeSubcommand($actionsMap[$choice]['command'], $locale); + + if ($this->option('once')) { + return; + } } + } - $this->call($action, ['--lang' => $locale]); + /** + * Clear the screen, render the header, execute a subcommand, and wait for user acknowledgment. + */ + protected function executeSubcommand(string $command, string $locale): void + { + $this->clearScreen(); + $this->renderHeader($locale); + $this->call($command, ['--lang' => $locale]); + $this->waitForKeyPress(); } } diff --git a/lang/en/messages.php b/lang/en/messages.php index 3777d1e..4669079 100644 --- a/lang/en/messages.php +++ b/lang/en/messages.php @@ -7,6 +7,9 @@ 'name' => 'IT Toolbox CLI', 'tagline' => 'Cross-Platform IT Support & System Diagnostics Suite', 'detected_os' => 'Detected OS Family: :os', + 'header_status' => 'OS: :os | Privilege: :privilege | Lang: :lang', + 'privilege_admin' => 'Admin / Root', + 'privilege_user' => 'Standard User', 'goodbye' => 'Thank you for using IT Toolbox CLI. Goodbye!', ], @@ -21,6 +24,9 @@ 'menu' => [ 'main_prompt' => 'Select a module or action:', 'sub_prompt' => 'Select an operation:', + 'numeric_hint' => 'Enter an option number (:options)', + 'invalid_option' => 'Invalid option. Please enter one of the available numbers (:options).', + 'press_any_key' => 'Press Enter or any key to return...', 'back' => '← Back to Main Menu', 'exit' => '✖ Exit IT Toolbox', 'categories' => [ @@ -28,8 +34,8 @@ 'printers' => '🖨 Printers & Spooler Management', 'network' => '🌐 Network & Connectivity Diagnostics', 'maintenance' => '🧹 System Maintenance & Cleanup', - 'reports' => '📄 Diagnostic Reports & Export', - 'language' => '🌍 Switch Language (English / Português)', + 'reports' => '📄 Export Diagnostic Report', + 'language' => '🌍 Switch Language (EN / PT-BR)', ], 'actions' => [ 'system_info' => 'View OS, CPU, RAM & Storage Health (system:info)', diff --git a/lang/pt_BR/messages.php b/lang/pt_BR/messages.php index 92ec191..8912a92 100644 --- a/lang/pt_BR/messages.php +++ b/lang/pt_BR/messages.php @@ -7,6 +7,9 @@ 'name' => 'IT Toolbox CLI', 'tagline' => 'Suíte Multiplataforma de Suporte Técnico e Diagnóstico de Sistemas', 'detected_os' => 'Família de SO Detectada: :os', + 'header_status' => 'SO: :os | Privilégio: :privilege | Idioma: :lang', + 'privilege_admin' => 'Admin / Root', + 'privilege_user' => 'Usuário Padrão', 'goodbye' => 'Obrigado por utilizar o IT Toolbox CLI. Até logo!', ], @@ -21,15 +24,18 @@ 'menu' => [ 'main_prompt' => 'Selecione um módulo ou ação:', 'sub_prompt' => 'Selecione uma operação:', + 'numeric_hint' => 'Digite o número da opção (:options)', + 'invalid_option' => 'Opção inválida. Digite um dos números disponíveis (:options).', + 'press_any_key' => 'Pressione Enter ou qualquer tecla para voltar...', 'back' => '← Voltar ao Menu Principal', 'exit' => '✖ Sair do IT Toolbox', 'categories' => [ - 'system' => '🖥 Diagnóstico de Sistema e Hardware', - 'printers' => '🖨 Gerenciamento de Impressoras e Spooler', - 'network' => '🌐 Diagnóstico de Rede e Conectividade', - 'maintenance' => '🧹 Manutenção e Limpeza do Sistema', - 'reports' => '📄 Relatórios de Diagnóstico e Exportação', - 'language' => '🌍 Alternar Idioma (Português / English)', + 'system' => '🖥 Diagnóstico de Sistema & Hardware', + 'printers' => '🖨 Impressoras & Spooler', + 'network' => '🌐 Rede & Conectividade', + 'maintenance' => '🧹 Limpeza & Manutenção', + 'reports' => '📄 Exportar Relatório de Atendimento', + 'language' => '🌍 Alterar Idioma (EN / PT-BR)', ], 'actions' => [ 'system_info' => 'Exibir SO, CPU, RAM e Saúde de Discos (system:info)',