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