diff --git a/kilo b/kilo index ebb29d1..6a45220 100755 --- a/kilo +++ b/kilo @@ -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(); diff --git a/src/constants.php b/src/constants.php index c9c4c1c..4c1f434 100644 --- a/src/constants.php +++ b/src/constants.php @@ -3,6 +3,8 @@ namespace Kilo; define('STDIN_FILENO', 0); +define('STDOUT_FILENO', 1); +define('STDERR_FILENO', 2); define('TCSAFLUSH', 2); // ----------------------------------------------------------------------------- diff --git a/src/functions.php b/src/functions.php index 2185df5..6139640 100644 --- a/src/functions.php +++ b/src/functions.php @@ -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;