ASCII控制台-如何处理窗口调整大小


ASCII console - how to handle window resize?

这是一段简单的代码,它绘制了一个几乎和屏幕一样长的绿色条,并在最后写了一个数字,定期刷新(代码是PHP的,但它只是普通的ascii码):

function update($x)
{
    // get the console width
    $width = exec('tput cols');
    // go back up a line if this isn't the first line
    if($x) {
        echo "'033[1A";
    }
    // print a green bar with a number at the end
    echo "'033[42m" . str_repeat(' ', $width - 4) . "$x ";
    // reset formatting and add a new line for next time
    echo "'033[0m'n";
}
for($i = 0; $i < 100; ++$i) {
    update($i);
    // sleep for 0.1 seconds
    usleep(100000);
}

当窗口的大小被调整成较大时,它会按预期填充新的空间,但是当你试图缩小窗口时,布局就会被打乱。

我不想重置整个窗口,只是确保行始终是控制台的宽度(以数字结尾)。这可能吗?

可以为SIGWINCH事件注册一个信号处理程序。如果窗口大小发生变化,将触发此事件。

在信号处理程序代码中,您将重新绘制绿色条:

declare(ticks = 1); 
// Called if the window will get resized
function sig_handler($signo) 
{
    update(123);
}
function update($x)
{
    // Restore Cursor
    echo "'033[u";
    // Erase line
    echo "'033[1K";
    // Get the console width
    $width = exec('tput cols');
    // Go back up a line if this isn't the first line
    if($x) {
        echo "'033[1A";
    }   
    // Print a green bar with a number at the end
    echo "'033[42m" . str_repeat(' ', $width - 4) . "$x ";
    // Reset formatting and add a new line for next time
    echo "'033[0m'n";
}
// Register Signal handler
pcntl_signal(SIGWINCH, "sig_handler");
// Save cursor position
echo "'033[s";
update(123);
// Your program ...
while(true) {
    sleep(1);
}

您可以遵循我使用的终端代码的ANSI终端参考。