added _ungetch

This commit is contained in:
R. Eric Wheeler 2021-01-07 13:56:08 -08:00
parent 624e659a26
commit c909fa19f1
5 changed files with 20 additions and 10 deletions

View File

@ -8,9 +8,9 @@ $ composer require sikofitt/getch:dev-master
```php
use Sikofitt\Console\Getch;
$g = new Getch($linuxLibrary = null); // can also be a library that implements a function called _getwch;
// by default uses the bundled Resources/libgetwch.so
// on windows uses the built in _getwch function.
$g = new Getch($linuxLibrary = null); // can also be a library that implements a function called _getch;
// by default uses the bundled Resources/libgetch.so
// on windows uses the built in _getch function.
$char = $g->getch();
print $char;
```

View File

@ -17,7 +17,7 @@ use RuntimeException;
final class Getch
{
private const LINUX_LIBRARY = __DIR__ . '/Resources/libgetwch.so';
private const LINUX_LIBRARY = __DIR__ . '/Resources/libgetch.so';
private const WINDOWS_LIBRARY = 'ucrtbase.dll';
private static ?FFI $ffi = null;
@ -31,13 +31,13 @@ final class Getch
if (self::$ffi === null) {
$osFamily = PHP_OS_FAMILY;
if ($osFamily === 'Windows') {
self::$ffi = FFI::cdef('char _getwch();', self::WINDOWS_LIBRARY);
self::$ffi = FFI::cdef('char _getch();', self::WINDOWS_LIBRARY);
} elseif ($osFamily === 'Linux') {
if (!file_exists($linuxLibrary)) {
throw new RuntimeException(sprintf('Could not find library file %s.', $linuxLibrary));
}
self::$ffi = FFI::cdef('char _getwch();', $linuxLibrary);
self::$ffi = FFI::cdef('char _getch(); int _ungetch(int ch);', $linuxLibrary);
} else {
throw new RuntimeException(sprintf('Sorry, %s is not supported yet.', $osFamily));
}
@ -46,6 +46,11 @@ final class Getch
public function getch(): string
{
return self::$ffi->_getwch();
return self::$ffi->_getch();
}
public function ungetch(string $char)
{
return self::$ffi->_ungetch($char);
}
}

View File

@ -2,8 +2,8 @@ CC = gcc
CFLAGS = -shared -Wall -fPIC
all:
@${CC} ${CFLAGS} getwch.c -o libgetwch.so
@${CC} ${CFLAGS} getch.c -o libgetch.so
clean:
@rm -f libgetwch.so
@rm -f libgetch.so

View File

@ -3,7 +3,7 @@
#include <unistd.h>
/* reads from keypress, doesn't echo */
int _getwch(void)
int _getch(void)
{
struct termios oldattr, newattr;
int ch;
@ -15,3 +15,8 @@ int _getwch(void)
tcsetattr( STDIN_FILENO, TCSANOW, &oldattr );
return ch;
}
int _ungetch(int ch)
{
return ungetc(ch, stdin);
}