Get raw mode sorted out

This commit is contained in:
Timothy Warren 2019-10-10 15:49:01 -04:00
parent 8522d9fb33
commit 08cf93b9c7
3 changed files with 34 additions and 19 deletions

28
kilo
View File

@ -3,14 +3,9 @@
namespace Kilo;
use FFI;
require_once __DIR__ . '/src/constants.php';
require_once __DIR__ . '/src/functions.php';
$ffi = FFI::load(__DIR__ . '/src/ffi.h');
$original_termios = $ffi->new("struct termios");
function main(): int
{
global $ffi;
@ -18,19 +13,30 @@ function main(): int
enableRawMode();
// Input Loop
do
while (true)
{
$input = read_stdin();
if ($ffi->iscntrl($input))
$char = read_stdin(1);
$c = ord($char);
if (empty($char))
{
printf("%d\n", $input);
continue;
}
if ($ffi->iscntrl($c))
{
printf("%d\r\n", $c);
}
else
{
printf("%d ('%c')\n", $input, $input);
printf("%d ('%c')\r\n", $c, $c);
}
if ($char === 'q')
{
break;
}
}
while ($input !== 'q');
disableRawMode();

View File

@ -3,6 +3,8 @@
namespace Kilo;
define('STDIN_FILENO', 0);
define('STDOUT_FILENO', 1);
define('STDERR_FILENO', 2);
define('TCSAFLUSH', 2);
// -----------------------------------------------------------------------------

View File

@ -4,20 +4,24 @@ namespace Kilo;
use FFI;
// require_once 'constants.php';
$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 = clone $original_termios;
$termios->c_lflag &= ~(_ECHO | ICANON);
$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));
@ -31,9 +35,12 @@ function disableRawMode(): void
$ffi->tcsetattr(STDIN_FILENO, TCSAFLUSH, FFI::addr($original_termios));
}
function read_stdin() {
$handle = fopen('php://stdin', 'r');
$input = rtrim(fgets($handle, 128));
function read_stdin(int $len = 128): string
{
$handle = fopen('php://stdin', 'rb');
$input = fread($handle, $len);
$input = rtrim($input);
fclose($handle);
return $input;