Debian Codegraph @

vendor/clue/stdio-react/src/Stdio.php

raw
1 <?php
2
3 namespace Clue\React\Stdio;
4
5 use Evenement\EventEmitter;
6 use React\EventLoop\LoopInterface;
7 use React\Stream\DuplexStreamInterface;
8 use React\Stream\ReadableResourceStream;
9 use React\Stream\ReadableStreamInterface;
10 use React\Stream\Util;
11 use React\Stream\WritableResourceStream;
12 use React\Stream\WritableStreamInterface;
13
14 class Stdio extends EventEmitter implements DuplexStreamInterface
15 {
16 private $input;
17 private $output;
18 private $readline;
19
20 private $ending = false;
21 private $closed = false;
22 private $incompleteLine = '';
23 private $originalTtyMode = null;
24
25 /**
26 *
27 * This class takes an optional `LoopInterface|null $loop` parameter that can be used to
28 * pass the event loop instance to use for this object. You can use a `null` value
29 * here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
30 * This value SHOULD NOT be given unless you're sure you want to explicitly use a
31 * given event loop instance.
32 *
33 * @param ?LoopInterface $loop
34 * @param ?ReadableStreamInterface $input
35 * @param ?WritableStreamInterface $output
36 * @param ?Readline $readline
37 */
38 public function __construct($loop = null, $input = null, $output = null, $readline = null)
39 {
40 if ($loop !== null && !$loop instanceof LoopInterface) { // manual type check to support legacy PHP < 7.1
41 throw new \InvalidArgumentException('Argument #1 ($loop) expected null|React\EventLoop\LoopInterface');
42 }
43
44 if ($input !== null && !$input instanceof ReadableStreamInterface) { // manual type check to support legacy PHP < 7.1
45 throw new \InvalidArgumentException('Argument #2 ($input) expected null|React\Stream\ReadableStreamInterface');
46 }
47
48 if ($output !== null && !$output instanceof WritableStreamInterface) { // manual type check to support legacy PHP < 7.1
49 throw new \InvalidArgumentException('Argument #3 ($output) expected null|React\Stream\WritableStreamInterface');
50 }
51
52 if ($readline !== null && !$readline instanceof Readline) { // manual type check to support legacy PHP < 7.1
53 throw new \InvalidArgumentException('Argument #4 ($readline) expected null|Clue\React\Stdio\Readline');
54 }
55
56 if ($input === null) {
57 $input = $this->createStdin($loop); // @codeCoverageIgnore
58 }
59
60 if ($output === null) {
61 $output = $this->createStdout($loop); // @codeCoverageIgnore
62 }
63
64 if ($readline === null) {
65 $readline = new Readline($input, $output, $this);
66 }
67
68 $this->input = $input;
69 $this->output = $output;
70 $this->readline = $readline;
71
72 $that = $this;
73
74 // readline data emits a new line
75 $incomplete =& $this->incompleteLine;
76 $this->readline->on('data', function($line) use ($that, &$incomplete) {
77 // readline emits a new line on enter, so start with a blank line
78 $incomplete = '';
79 $that->emit('data', array($line));
80 });
81
82 // handle all input events (readline forwards all input events)
83 $this->readline->on('error', array($this, 'handleError'));
84 $this->readline->on('end', array($this, 'handleEnd'));
85 $this->readline->on('close', array($this, 'handleCloseInput'));
86
87 // handle all output events
88 $this->output->on('error', array($this, 'handleError'));
89 $this->output->on('close', array($this, 'handleCloseOutput'));
90 }
91
92 public function __destruct()
93 {
94 $this->restoreTtyMode();
95 }
96
97 public function pause()
98 {
99 $this->input->pause();
100 }
101
102 public function resume()
103 {
104 $this->input->resume();
105 }
106
107 public function isReadable()
108 {
109 return $this->input->isReadable();
110 }
111
112 public function isWritable()
113 {
114 return $this->output->isWritable();
115 }
116
117 public function pipe(WritableStreamInterface $dest, array $options = array())
118 {
119 Util::pipe($this, $dest, $options);
120
121 return $dest;
122 }
123
124 public function write($data)
125 {
126 // return false if already ended, return true if writing empty string
127 if ($this->ending || $data === '') {
128 return !$this->ending;
129 }
130
131 $out = $data;
132
133 $lastNewline = strrpos($data, "\n");
134
135 $restoreReadline = false;
136
137 if ($this->incompleteLine !== '') {
138 // the last write did not end with a newline => append to existing row
139
140 // move one line up and move cursor to last position before writing data
141 $out = "\033[A" . "\r\033[" . $this->width($this->incompleteLine) . "C" . $out;
142
143 // data contains a newline, so this will overwrite the readline prompt
144 if ($lastNewline !== false) {
145 // move cursor to beginning of readline prompt and clear line
146 // clearing is important because $data may not overwrite the whole line
147 $out = "\r\033[K" . $out;
148
149 // make sure to restore readline after this output
150 $restoreReadline = true;
151 }
152 } else {
153 // here, we're writing to a new line => overwrite readline prompt
154
155 // move cursor to beginning of readline prompt and clear line
156 $out = "\r\033[K" . $out;
157
158 // we always overwrite the readline prompt, so restore it on next line
159 $restoreReadline = true;
160 }
161
162 // following write will have have to append to this line if it does not end with a newline
163 $endsWithNewline = substr($data, -1) === "\n";
164
165 if ($endsWithNewline) {
166 // line ends with newline, so this is line is considered complete
167 $this->incompleteLine = '';
168 } else {
169 // always end data with newline in order to append readline on next line
170 $out .= "\n";
171
172 if ($lastNewline === false) {
173 // contains no newline at all, everything is incomplete
174 $this->incompleteLine .= $data;
175 } else {
176 // contains a newline, everything behind it is incomplete
177 $this->incompleteLine = (string)substr($data, $lastNewline + 1);
178 }
179 }
180
181 if ($restoreReadline) {
182 // write output and restore original readline prompt and line buffer
183 return $this->output->write($out . $this->readline->getDrawString());
184 } else {
185 // restore original cursor position in readline prompt
186 $pos = $this->width($this->readline->getPrompt()) + $this->readline->getCursorCell();
187 if ($pos !== 0) {
188 // we always start at beginning of line, move right by X
189 $out .= "\033[" . $pos . "C";
190 }
191
192 // write to actual output stream
193 return $this->output->write($out);
194 }
195 }
196
197 public function end($data = null)
198 {
199 if ($this->ending) {
200 return;
201 }
202
203 if ($data !== null) {
204 $this->write($data);
205 }
206
207 $this->ending = true;
208
209 // clear readline output, close input and end output
210 $this->readline->setInput('')->setPrompt('');
211 $this->input->close();
212 $this->output->end();
213 }
214
215 public function close()
216 {
217 if ($this->closed) {
218 return;
219 }
220
221 $this->ending = true;
222 $this->closed = true;
223
224 $this->input->close();
225 $this->output->close();
226
227 $this->emit('close');
228 $this->removeAllListeners();
229 }
230
231 /**
232 * @deprecated
233 * @return Readline
234 */
235 public function getReadline()
236 {
237 return $this->readline;
238 }
239
240
241 /**
242 * prompt to prepend to input line
243 *
244 * Will redraw the current input prompt with the current input buffer.
245 *
246 * @param string $prompt
247 * @return void
248 */
249 public function setPrompt($prompt)
250 {
251 $this->readline->setPrompt($prompt);
252 }
253
254 /**
255 * returns the prompt to prepend to input line
256 *
257 * @return string
258 * @see self::setPrompt()
259 */
260 public function getPrompt()
261 {
262 return $this->readline->getPrompt();
263 }
264
265 /**
266 * sets whether/how to echo text input
267 *
268 * The default setting is `true`, which means that every character will be
269 * echo'ed as-is, i.e. you can see what you're typing.
270 * For example: Typing "test" shows "test".
271 *
272 * You can turn this off by supplying `false`, which means that *nothing*
273 * will be echo'ed while you're typing. This could be a good idea for
274 * password prompts. Note that this could be confusing for users, so using
275 * a character replacement as following is often preferred.
276 * For example: Typing "test" shows "" (nothing).
277 *
278 * Alternative, you can supply a single character replacement character
279 * that will be echo'ed for each character in the text input. This could
280 * be a good idea for password prompts, where an asterisk character ("*")
281 * is often used to indicate typing activity and password length.
282 * For example: Typing "test" shows "****" (with asterisk replacement)
283 *
284 * Changing this setting will redraw the current prompt and echo the current
285 * input buffer according to the new setting.
286 *
287 * @param boolean|string $echo echo can be turned on (boolean true) or off (boolean true), or you can supply a single character replacement string
288 * @return void
289 */
290 public function setEcho($echo)
291 {
292 $this->readline->setEcho($echo);
293 }
294
295 /**
296 * whether or not to support moving cursor left and right
297 *
298 * switching cursor support moves the cursor to the end of the current
299 * input buffer (if any).
300 *
301 * @param boolean $move
302 * @return void
303 */
304 public function setMove($move)
305 {
306 $this->readline->setMove($move);
307 }
308
309 /**
310 * Gets current cursor position measured in number of text characters.
311 *
312 * Note that the number of text characters doesn't necessarily reflect the
313 * number of monospace cells occupied by the text characters. If you want
314 * to know the latter, use `self::getCursorCell()` instead.
315 *
316 * @return int
317 * @see self::getCursorCell() to get the position measured in monospace cells
318 * @see self::moveCursorTo() to move the cursor to a given character position
319 * @see self::moveCursorBy() to move the cursor by given number of characters
320 * @see self::setMove() to toggle whether the user can move the cursor position
321 */
322 public function getCursorPosition()
323 {
324 return $this->readline->getCursorPosition();
325 }
326
327 /**
328 * Gets current cursor position measured in monospace cells.
329 *
330 * Note that the cell position doesn't necessarily reflect the number of
331 * text characters. If you want to know the latter, use
332 * `self::getCursorPosition()` instead.
333 *
334 * Most "normal" characters occupy a single monospace cell, i.e. the ASCII
335 * sequence for "A" requires a single cell, as do most UTF-8 sequences
336 * like "Ä".
337 *
338 * However, there are a number of code points that do not require a cell
339 * (i.e. invisible surrogates) or require two cells (e.g. some asian glyphs).
340 *
341 * Also note that this takes the echo mode into account, i.e. the cursor is
342 * always at position zero if echo is off. If using a custom echo character
343 * (like asterisk), it will take its width into account instead of the actual
344 * input characters.
345 *
346 * @return int
347 * @see self::getCursorPosition() to get current cursor position measured in characters
348 * @see self::moveCursorTo() to move the cursor to a given character position
349 * @see self::moveCursorBy() to move the cursor by given number of characters
350 * @see self::setMove() to toggle whether the user can move the cursor position
351 * @see self::setEcho()
352 */
353 public function getCursorCell()
354 {
355 return $this->readline->getCursorCell();
356 }
357
358 /**
359 * Moves cursor to right by $n chars (or left if $n is negative).
360 *
361 * Zero value or values out of range (exceeding current input buffer) are
362 * simply ignored.
363 *
364 * Will redraw() the readline only if the visible cell position changes,
365 * see `self::getCursorCell()` for more details.
366 *
367 * @param int $n
368 * @return void
369 */
370 public function moveCursorBy($n)
371 {
372 $this->readline->moveCursorBy($n);
373 }
374
375 /**
376 * Moves cursor to given position in current line buffer.
377 *
378 * Values out of range (exceeding current input buffer) are simply ignored.
379 *
380 * Will redraw() the readline only if the visible cell position changes,
381 * see `self::getCursorCell()` for more details.
382 *
383 * @param int $n
384 * @return void
385 */
386 public function moveCursorTo($n)
387 {
388 $this->readline->moveCursorTo($n);
389 }
390
391 /**
392 * Appends the given input to the current text input buffer at the current position
393 *
394 * This moves the cursor accordingly to the number of characters added.
395 *
396 * @param string $input
397 * @return void
398 */
399 public function addInput($input)
400 {
401 $this->readline->addInput($input);
402 }
403
404 /**
405 * set current text input buffer
406 *
407 * this moves the cursor to the end of the current
408 * input buffer (if any).
409 *
410 * @param string $input
411 * @return void
412 */
413 public function setInput($input)
414 {
415 $this->readline->setInput($input);
416 }
417
418 /**
419 * get current text input buffer
420 *
421 * @return string
422 */
423 public function getInput()
424 {
425 return $this->readline->getInput();
426 }
427
428 /**
429 * Adds a new line to the (bottom position of the) history list
430 *
431 * @param string $line
432 * @return void
433 */
434 public function addHistory($line)
435 {
436 $this->readline->addHistory($line);
437 }
438
439 /**
440 * Clears the complete history list
441 *
442 * @return void
443 */
444 public function clearHistory()
445 {
446 $this->readline->clearHistory();
447 }
448
449 /**
450 * Returns an array with all lines in the history
451 *
452 * @return string[]
453 */
454 public function listHistory()
455 {
456 return $this->readline->listHistory();
457 }
458
459 /**
460 * Limits the history to a maximum of N entries and truncates the current history list accordingly
461 *
462 * @param int|null $limit
463 * @return void
464 */
465 public function limitHistory($limit)
466 {
467 $this->readline->limitHistory($limit);
468 }
469
470 /**
471 * set autocompletion handler to use
472 *
473 * The autocomplete handler will be called whenever the user hits the TAB
474 * key.
475 *
476 * @param callable|null $autocomplete
477 * @return void
478 * @throws \InvalidArgumentException if the given callable is invalid
479 */
480 public function setAutocomplete($autocomplete)
481 {
482 $this->readline->setAutocomplete($autocomplete);
483 }
484
485 /**
486 * whether or not to emit a audible/visible BELL signal when using a disabled function
487 *
488 * By default, this class will emit a BELL signal when using a disable function,
489 * such as using the <kbd>left</kbd> or <kbd>backspace</kbd> keys when
490 * already at the beginning of the line.
491 *
492 * Whether or not the BELL is audible/visible depends on the termin and its
493 * settings, i.e. some terminals may "beep" or flash the screen or emit a
494 * short vibration.
495 *
496 * @param bool $bell
497 * @return void
498 */
499 public function setBell($bell)
500 {
501 $this->readline->setBell($bell);
502 }
503
504 private function width($str)
505 {
506 return $this->readline->strwidth($str) - 2 * substr_count($str, "\x08");
507 }
508
509 /** @internal */
510 public function handleError(\Exception $e)
511 {
512 $this->emit('error', array($e));
513 $this->close();
514 }
515
516 /** @internal */
517 public function handleEnd()
518 {
519 $this->emit('end');
520 }
521
522 /** @internal */
523 public function handleCloseInput()
524 {
525 $this->restoreTtyMode();
526
527 if (!$this->output->isWritable()) {
528 $this->close();
529 }
530 }
531
532 /** @internal */
533 public function handleCloseOutput()
534 {
535 if (!$this->input->isReadable()) {
536 $this->close();
537 }
538 }
539
540 /**
541 * @codeCoverageIgnore this is covered by functional tests with/without ext-readline
542 */
543 private function restoreTtyMode()
544 {
545 if (function_exists('readline_callback_handler_remove')) {
546 // remove dummy readline handler to turn to default input mode
547 readline_callback_handler_remove();
548 } elseif ($this->originalTtyMode !== null && is_resource(STDIN) && $this->isTty()) {
549 // Reset stty so it behaves normally again
550 shell_exec('stty ' . escapeshellarg($this->originalTtyMode));
551 $this->originalTtyMode = null;
552 }
553
554 // restore blocking mode so following programs behave normally
555 if (defined('STDIN') && is_resource(STDIN)) {
556 stream_set_blocking(STDIN, true);
557 }
558 }
559
560 /**
561 * @param ?LoopInterface $loop
562 * @return ReadableStreamInterface
563 * @codeCoverageIgnore this is covered by functional tests with/without ext-readline
564 */
565 private function createStdin($loop = null)
566 {
567 // STDIN not defined ("php -a") or already closed (`fclose(STDIN)`)
568 // also support starting program with closed STDIN ("example.php 0<&-")
569 // the stream is a valid resource and is not EOF, but fstat fails
570 if (!defined('STDIN') || !is_resource(STDIN) || fstat(STDIN) === false) {
571 $stream = new ReadableResourceStream(fopen('php://memory', 'r'), $loop);
572 $stream->close();
573 return $stream;
574 }
575
576 $stream = new ReadableResourceStream(STDIN, $loop);
577
578 if (function_exists('readline_callback_handler_install')) {
579 // Prefer `ext-readline` to install dummy handler to turn on raw input mode.
580 // We will never actually feed the readline handler and instead
581 // handle all input in our `Readline` implementation.
582 readline_callback_handler_install('', function () { });
583 return $stream;
584 }
585
586 if ($this->isTty()) {
587 $this->originalTtyMode = rtrim(shell_exec('stty -g'), PHP_EOL);
588
589 // Disable icanon (so we can fread each keypress) and echo (we'll do echoing here instead)
590 shell_exec('stty -icanon -echo');
591 }
592
593 // register shutdown function to restore TTY mode in case of unclean shutdown (uncaught exception)
594 // this will not trigger on SIGKILL etc., but the terminal should take care of this
595 register_shutdown_function(array($this, 'close'));
596
597 return $stream;
598 }
599
600 /**
601 * @param ?LoopInterface $loop
602 * @return WritableStreamInterface
603 * @codeCoverageIgnore this is covered by functional tests
604 */
605 private function createStdout($loop = null)
606 {
607 // STDOUT not defined ("php -a") or already closed (`fclose(STDOUT)`)
608 // also support starting program with closed STDOUT ("example.php >&-")
609 // the stream is a valid resource and is not EOF, but fstat fails
610 if (!defined('STDOUT') || !is_resource(STDOUT) || fstat(STDOUT) === false) {
611 $output = new WritableResourceStream(fopen('php://memory', 'r+'), $loop);
612 $output->close();
613 } else {
614 $output = new WritableResourceStream(STDOUT, $loop);
615 }
616
617 return $output;
618 }
619
620 /**
621 * @return bool
622 * @codeCoverageIgnore
623 */
624 private function isTty()
625 {
626 if (PHP_VERSION_ID >= 70200) {
627 // Prefer `stream_isatty()` (available as of PHP 7.2 only)
628 return stream_isatty(STDIN);
629 } elseif (function_exists('posix_isatty')) {
630 // Otherwise use `posix_isatty` if available (requires `ext-posix`)
631 return posix_isatty(STDIN);
632 }
633
634 // otherwise try to guess based on stat file mode and device major number
635 // Must be special character device: ($mode & S_IFMT) === S_IFCHR
636 // And device major number must be allocated to TTYs (2-5 and 128-143)
637 // For what it's worth, checking for device gid 5 (tty) is less reliable.
638 // @link http://man7.org/linux/man-pages/man7/inode.7.html
639 // @link https://www.kernel.org/doc/html/v4.11/admin-guide/devices.html#terminal-devices
640 $stat = fstat(STDIN);
641 $mode = isset($stat['mode']) ? ($stat['mode'] & 0170000) : 0;
642 $major = isset($stat['dev']) ? (($stat['dev'] >> 8) & 0xff) : 0;
643
644 return ($mode === 0020000 && $major >= 2 && $major <= 143 && ($major <=5 || $major >= 128));
645 }
646 }