Skip to content

Instantly share code, notes, and snippets.

@srgoogleguy
Last active December 25, 2015 11:29
Show Gist options
  • Save srgoogleguy/6969276 to your computer and use it in GitHub Desktop.
Save srgoogleguy/6969276 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/php
<?php
/**
* Keypad input over STDIN (using non-blocking I/O)
*/
$base = event_base_new();
$input = event_new();
ncurses_init();
ncurses_savetty();
ncurses_curs_set(0);
ncurses_start_color();
ncurses_clear();
$fullscreen = ncurses_newwin(0, 0, 0, 0);
ncurses_move(0, 0);
if (!stream_set_blocking(STDIN, 0)) die('non-blocking failed!');
event_set($input, STDIN,
EV_READ | EV_PERSIST,
"get_input",
array($input, $base,
microtime(true), $fullscreen,
)
);
function shutdown() {
ncurses_resetty();
ncurses_end();
}
register_shutdown_function('shutdown');
event_base_set($input, $base);
event_add($input);
event_base_loop($base);
function get_input($fd, $events, $arg) {
static $buf = false;
static $buffer = '', $mode = 0;
$cursor = [[0,'+'],[1,'_'],[2,'a','b','c'],[3,'d','e','f'],[4,'g','h','i'],[5,'j','k','l'],[6,'m','n','o'],[7,'p','q','r','s'],[8,'t','u','v'],[9,'w','x','y','z']];
static $lastpress, $cx = 0, $cy = 0;
$q = false;
if (!$lastpress) $lastpress = microtime(true);
if (($buf = fgets($fd, 8192)) !== false) {
ncurses_move(5,0);
ncurses_clrtobot();
ncurses_addstr($lastpress);
ncurses_move(6,0);
ncurses_addstr($buf);
ncurses_move(7,0);
ncurses_addstr($buffer);
ncurses_move($cx, $cy);
}
if ($buf && $buf === $buffer && microtime(true) - $lastpress <= 1) {
$mode++;
} else {
$cy++;
ncurses_move($cx, $cy);
$q = true;
$buffer = $buf;
$mode = 0;
}
if ($buffer !== '') {
$n = (int)$buffer;
if ($n < 0) $n = 0;
if ($n > 9) $n = 9;
$mode = $mode ? $mode % count($cursor[$n]) : 0;
if (microtime(true) - $lastpress > 1 && !$q) {
$cy++;
ncurses_move($cx, $cy);
ncurses_addstr($cursor[$n][$mode]);
} else {
ncurses_addstr($cursor[$n][$mode]);
}
ncurses_refresh(0);
ncurses_wrefresh($arg[3]);
ncurses_getmaxyx($arg[3], $h, $w);
}
$lastpress = microtime(true);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment