From e0a9d066ca735dcb2c29b590d10bfeff36034262 Mon Sep 17 00:00:00 2001 From: Timothy J Warren Date: Fri, 11 Oct 2019 16:32:47 -0400 Subject: [PATCH] Up to step 21 --- kilo | 29 ++++------------------------- src/editor.php | 27 +++++++++++++++++++++++++++ src/functions.php | 7 +++++++ 3 files changed, 38 insertions(+), 25 deletions(-) create mode 100644 src/editor.php diff --git a/kilo b/kilo index 6a45220..6a28dcf 100755 --- a/kilo +++ b/kilo @@ -5,41 +5,20 @@ namespace Kilo; require_once __DIR__ . '/src/constants.php'; require_once __DIR__ . '/src/functions.php'; +require_once __DIR__ . '/src/editor.php'; function main(): int { - global $ffi; - enableRawMode(); + $editor = new Editor(); + // Input Loop while (true) { - $char = read_stdin(1); - $c = ord($char); - - if (empty($char)) - { - continue; - } - - if ($ffi->iscntrl($c)) - { - printf("%d\r\n", $c); - } - else - { - printf("%d ('%c')\r\n", $c, $c); - } - - if ($char === 'q') - { - break; - } + $editor->processKeypress(); } - disableRawMode(); - return 0; } diff --git a/src/editor.php b/src/editor.php new file mode 100644 index 0000000..8057c43 --- /dev/null +++ b/src/editor.php @@ -0,0 +1,27 @@ +readKey(); + + switch($c) + { + case chr(ctrl_key('q')): + exit(0); + break; + } + } + + protected function readKey(): string + { + return read_stdin(1); + } +} \ No newline at end of file diff --git a/src/functions.php b/src/functions.php index 6139640..b825691 100644 --- a/src/functions.php +++ b/src/functions.php @@ -12,6 +12,8 @@ function enableRawMode(): void global $ffi; global $original_termios; + register_shutdown_function('Kilo\\disableRawMode'); + // Populate the original terminal settings $ffi->tcgetattr(STDIN_FILENO, FFI::addr($original_termios)); @@ -44,4 +46,9 @@ function read_stdin(int $len = 128): string fclose($handle); return $input; +} + +function ctrl_key(string $char): int +{ + return ord($char) & 0x1f; } \ No newline at end of file