ConsoleSectionOutput.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Output;
  11. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  12. use Symfony\Component\Console\Helper\Helper;
  13. use Symfony\Component\Console\Terminal;
  14. /**
  15. * @author Pierre du Plessis <pdples@gmail.com>
  16. * @author Gabriel Ostrolucký <gabriel.ostrolucky@gmail.com>
  17. */
  18. class ConsoleSectionOutput extends StreamOutput
  19. {
  20. private array $content = [];
  21. private int $lines = 0;
  22. private array $sections;
  23. private Terminal $terminal;
  24. private int $maxHeight = 0;
  25. /**
  26. * @param resource $stream
  27. * @param ConsoleSectionOutput[] $sections
  28. */
  29. public function __construct($stream, array &$sections, int $verbosity, bool $decorated, OutputFormatterInterface $formatter)
  30. {
  31. parent::__construct($stream, $verbosity, $decorated, $formatter);
  32. array_unshift($sections, $this);
  33. $this->sections = &$sections;
  34. $this->terminal = new Terminal();
  35. }
  36. /**
  37. * Defines a maximum number of lines for this section.
  38. *
  39. * When more lines are added, the section will automatically scroll to the
  40. * end (i.e. remove the first lines to comply with the max height).
  41. */
  42. public function setMaxHeight(int $maxHeight): void
  43. {
  44. // when changing max height, clear output of current section and redraw again with the new height
  45. $previousMaxHeight = $this->maxHeight;
  46. $this->maxHeight = $maxHeight;
  47. $existingContent = $this->popStreamContentUntilCurrentSection($previousMaxHeight ? min($previousMaxHeight, $this->lines) : $this->lines);
  48. parent::doWrite($this->getVisibleContent(), false);
  49. parent::doWrite($existingContent, false);
  50. }
  51. /**
  52. * Clears previous output for this section.
  53. *
  54. * @param int $lines Number of lines to clear. If null, then the entire output of this section is cleared
  55. */
  56. public function clear(?int $lines = null): void
  57. {
  58. if (!$this->content || !$this->isDecorated()) {
  59. return;
  60. }
  61. if ($lines) {
  62. array_splice($this->content, -$lines);
  63. } else {
  64. $lines = $this->lines;
  65. $this->content = [];
  66. }
  67. $this->lines -= $lines;
  68. parent::doWrite($this->popStreamContentUntilCurrentSection($this->maxHeight ? min($this->maxHeight, $lines) : $lines), false);
  69. }
  70. /**
  71. * Overwrites the previous output with a new message.
  72. */
  73. public function overwrite(string|iterable $message): void
  74. {
  75. if (!$this->content || !$this->isDecorated()) {
  76. $this->writeln($message);
  77. return;
  78. }
  79. // Replace own content and write everything in a single cursor-up + erase
  80. // pass, to avoid the flicker (and the line-eating artifacts on some
  81. // terminals) caused by calling clear() then writeln() back-to-back.
  82. $linesCleared = $this->lines;
  83. $this->content = [];
  84. $this->lines = 0;
  85. if (!is_iterable($message)) {
  86. $message = [$message];
  87. }
  88. foreach ($message as $line) {
  89. $this->addContent($this->getFormatter()->format($line) ?? '', true);
  90. }
  91. $erasedContent = $this->popStreamContentUntilCurrentSection($this->maxHeight ? min($this->maxHeight, $linesCleared) : $linesCleared);
  92. parent::doWrite($this->getVisibleContent(), false);
  93. parent::doWrite($erasedContent, false);
  94. }
  95. public function getContent(): string
  96. {
  97. return implode('', $this->content);
  98. }
  99. public function getVisibleContent(): string
  100. {
  101. if (0 === $this->maxHeight) {
  102. return $this->getContent();
  103. }
  104. return implode('', \array_slice($this->content, -$this->maxHeight));
  105. }
  106. /**
  107. * @internal
  108. */
  109. public function addContent(string $input, bool $newline = true): int
  110. {
  111. $width = $this->terminal->getWidth();
  112. $lines = explode(\PHP_EOL, $input);
  113. $linesAdded = 0;
  114. $count = \count($lines) - 1;
  115. foreach ($lines as $i => $lineContent) {
  116. // re-add the line break (that has been removed in the above `explode()` for
  117. // - every line that is not the last line
  118. // - if $newline is required, also add it to the last line
  119. if ($i < $count || $newline) {
  120. $lineContent .= \PHP_EOL;
  121. }
  122. // skip line if there is no text (or newline for that matter)
  123. if ('' === $lineContent) {
  124. continue;
  125. }
  126. // For the first line, check if the previous line (last entry of `$this->content`)
  127. // needs to be continued (i.e. does not end with a line break).
  128. if (0 === $i
  129. && (false !== $lastLine = end($this->content))
  130. && !str_ends_with($lastLine, \PHP_EOL)
  131. ) {
  132. // deduct the line count of the previous line
  133. $this->lines -= (int) ceil($this->getDisplayLength($lastLine) / $width) ?: 1;
  134. // concatenate previous and new line
  135. $lineContent = $lastLine.$lineContent;
  136. // replace last entry of `$this->content` with the new expanded line
  137. array_splice($this->content, -1, 1, $lineContent);
  138. } else {
  139. // otherwise just add the new content
  140. $this->content[] = $lineContent;
  141. }
  142. $linesAdded += (int) ceil($this->getDisplayLength($lineContent) / $width) ?: 1;
  143. }
  144. $this->lines += $linesAdded;
  145. return $linesAdded;
  146. }
  147. /**
  148. * @internal
  149. */
  150. public function addNewLineOfInputSubmit(): void
  151. {
  152. $this->content[] = \PHP_EOL;
  153. ++$this->lines;
  154. }
  155. protected function doWrite(string $message, bool $newline): void
  156. {
  157. // Simulate newline behavior for consistent output formatting, avoiding extra logic
  158. if (!$newline && str_ends_with($message, \PHP_EOL)) {
  159. $message = substr($message, 0, -\strlen(\PHP_EOL));
  160. $newline = true;
  161. }
  162. if (!$this->isDecorated()) {
  163. parent::doWrite($message, $newline);
  164. return;
  165. }
  166. // Check if the previous line (last entry of `$this->content`) needs to be continued
  167. // (i.e. does not end with a line break). In which case, it needs to be erased first.
  168. $linesToClear = $deleteLastLine = ($lastLine = end($this->content) ?: '') && !str_ends_with($lastLine, \PHP_EOL) ? 1 : 0;
  169. $linesAdded = $this->addContent($message, $newline);
  170. if ($lineOverflow = $this->maxHeight > 0 && $this->lines > $this->maxHeight) {
  171. // on overflow, clear the whole section and redraw again (to remove the first lines)
  172. $linesToClear = $this->maxHeight;
  173. }
  174. $erasedContent = $this->popStreamContentUntilCurrentSection($linesToClear);
  175. if ($lineOverflow) {
  176. // redraw existing lines of the section
  177. $previousLinesOfSection = \array_slice($this->content, $this->lines - $this->maxHeight, $this->maxHeight - $linesAdded);
  178. parent::doWrite(implode('', $previousLinesOfSection), false);
  179. }
  180. // if the last line was removed, re-print its content together with the new content.
  181. // otherwise, just print the new content.
  182. parent::doWrite($deleteLastLine ? $lastLine.$message : $message, true);
  183. parent::doWrite($erasedContent, false);
  184. }
  185. /**
  186. * At initial stage, cursor is at the end of stream output. This method makes cursor crawl upwards until it hits
  187. * current section. Then it erases content it crawled through. Optionally, it erases part of current section too.
  188. */
  189. private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string
  190. {
  191. $numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection;
  192. $erasedContent = [];
  193. foreach ($this->sections as $section) {
  194. if ($section === $this) {
  195. break;
  196. }
  197. $numberOfLinesToClear += $section->maxHeight ? min($section->lines, $section->maxHeight) : $section->lines;
  198. if ('' !== $sectionContent = $section->getVisibleContent()) {
  199. if (!str_ends_with($sectionContent, \PHP_EOL)) {
  200. $sectionContent .= \PHP_EOL;
  201. }
  202. $erasedContent[] = $sectionContent;
  203. }
  204. }
  205. if ($numberOfLinesToClear > 0) {
  206. // move cursor up n lines
  207. parent::doWrite(\sprintf("\x1b[%dA", $numberOfLinesToClear), false);
  208. // erase to end of screen
  209. parent::doWrite("\x1b[0J", false);
  210. }
  211. return implode('', array_reverse($erasedContent));
  212. }
  213. private function getDisplayLength(string $text): int
  214. {
  215. return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text)));
  216. }
  217. }