php-kilo/src/functions.php

47 lines
1.0 KiB
PHP

<?php declare(strict_types=1);
namespace Kilo;
use FFI;
$ffi = FFI::load(__DIR__ . '/ffi.h');
$original_termios = $ffi->new('struct termios');
function enableRawMode(): void
{
global $ffi;
global $original_termios;
// Populate the original terminal settings
$ffi->tcgetattr(STDIN_FILENO, FFI::addr($original_termios));
$termios = $ffi->new('struct termios');
$termios->c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);
$termios->c_oflag &= ~(OPOST);
$termios->c_cflag |= (CS8);
$termios->c_lflag &= ~(_ECHO | ICANON | IEXTEN | ISIG);
$termios->c_cc[VMIN] = 0;
$termios->c_cc[VTIME] = 1;
// Turn on raw mode
$ffi->tcsetattr(STDIN_FILENO, TCSAFLUSH, FFI::addr($termios));
}
function disableRawMode(): void
{
global $ffi;
global $original_termios;
$ffi->tcsetattr(STDIN_FILENO, TCSAFLUSH, FFI::addr($original_termios));
}
function read_stdin(int $len = 128): string
{
$handle = fopen('php://stdin', 'rb');
$input = fread($handle, $len);
$input = rtrim($input);
fclose($handle);
return $input;
}