Skip to content

Commit

Permalink
Merge pull request #63 from clue-labs/readline
Browse files Browse the repository at this point in the history
Optionally use `ext-readline` to enable raw input mode if available
  • Loading branch information
clue authored Dec 18, 2017
2 parents 1cf2db1 + e3ec4c0 commit e061b63
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,13 @@ If this extension is missing, then this library will use a slighty slower Regex
work-around that should otherwise work equally well.
Installing `ext-mbstring` is highly recommended.

Internally, it will use the `ext-readline` to enable raw terminal input mode.
If this extension is missing, then this library will manually set the required
TTY settings on start and will try to restore previous settings on exit.
Input line editing is handled entirely within this library and does not rely on
`ext-readline`.
Installing `ext-readline` is entirely optional.

Note that *Microsoft Windows is not supported*.
Due to platform inconsistencies, PHP does not provide support for reading from
standard console input without blocking.
Expand Down
20 changes: 19 additions & 1 deletion src/Stdin.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ class Stdin extends Stream
{
private $oldMode = null;

/**
* @param LoopInterface $loop
* @codeCoverageIgnore this is covered by functional tests with/without ext-readline
*/
public function __construct(LoopInterface $loop)
{
// STDIN not defined ("php -a") or already closed (`fclose(STDIN)`)
Expand All @@ -28,6 +32,14 @@ public function __construct(LoopInterface $loop)
return $this->close();
}

if (function_exists('readline_callback_handler_install')) {
// Prefer `ext-readline` to install dummy handler to turn on raw input mode.
// We will nevery actually feed the readline handler and instead
// handle all input in our `Readline` implementation.
readline_callback_handler_install('', function () { });
return;
}

if ($this->isTty()) {
$this->oldMode = shell_exec('stty -g');

Expand All @@ -51,9 +63,15 @@ public function __destruct()
$this->restore();
}

/**
* @codeCoverageIgnore this is covered by functional tests with/without ext-readline
*/
private function restore()
{
if ($this->oldMode !== null && $this->isTty()) {
if (function_exists('readline_callback_handler_remove')) {
// remove dummy readline handler to turn to default input mode
readline_callback_handler_remove();
} elseif ($this->oldMode !== null && $this->isTty()) {
// Reset stty so it behaves normally again
shell_exec(sprintf('stty %s', $this->oldMode));
$this->oldMode = null;
Expand Down

0 comments on commit e061b63

Please sign in to comment.