ConsoleSectionOutput.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. $this->clear();
  76. $this->writeln($message);
  77. }
  78. public function getContent(): string
  79. {
  80. return implode('', $this->content);
  81. }
  82. public function getVisibleContent(): string
  83. {
  84. if (0 === $this->maxHeight) {
  85. return $this->getContent();
  86. }
  87. return implode('', \array_slice($this->content, -$this->maxHeight));
  88. }
  89. /**
  90. * @internal
  91. */
  92. public function addContent(string $input, bool $newline = true): int
  93. {
  94. $width = $this->terminal->getWidth();
  95. $lines = explode(\PHP_EOL, $input);
  96. $linesAdded = 0;
  97. $count = \count($lines) - 1;
  98. foreach ($lines as $i => $lineContent) {
  99. // re-add the line break (that has been removed in the above `explode()` for
  100. // - every line that is not the last line
  101. // - if $newline is required, also add it to the last line
  102. if ($i < $count || $newline) {
  103. $lineContent .= \PHP_EOL;
  104. }
  105. // skip line if there is no text (or newline for that matter)
  106. if ('' === $lineContent) {
  107. continue;
  108. }
  109. // For the first line, check if the previous line (last entry of `$this->content`)
  110. // needs to be continued (i.e. does not end with a line break).
  111. if (0 === $i
  112. && (false !== $lastLine = end($this->content))
  113. && !str_ends_with($lastLine, \PHP_EOL)
  114. ) {
  115. // deduct the line count of the previous line
  116. $this->lines -= (int) ceil($this->getDisplayLength($lastLine) / $width) ?: 1;
  117. // concatenate previous and new line
  118. $lineContent = $lastLine.$lineContent;
  119. // replace last entry of `$this->content` with the new expanded line
  120. array_splice($this->content, -1, 1, $lineContent);
  121. } else {
  122. // otherwise just add the new content
  123. $this->content[] = $lineContent;
  124. }
  125. $linesAdded += (int) ceil($this->getDisplayLength($lineContent) / $width) ?: 1;
  126. }
  127. $this->lines += $linesAdded;
  128. return $linesAdded;
  129. }
  130. /**
  131. * @internal
  132. */
  133. public function addNewLineOfInputSubmit(): void
  134. {
  135. $this->content[] = \PHP_EOL;
  136. ++$this->lines;
  137. }
  138. protected function doWrite(string $message, bool $newline): void
  139. {
  140. // Simulate newline behavior for consistent output formatting, avoiding extra logic
  141. if (!$newline && str_ends_with($message, \PHP_EOL)) {
  142. $message = substr($message, 0, -\strlen(\PHP_EOL));
  143. $newline = true;
  144. }
  145. if (!$this->isDecorated()) {
  146. parent::doWrite($message, $newline);
  147. return;
  148. }
  149. // Check if the previous line (last entry of `$this->content`) needs to be continued
  150. // (i.e. does not end with a line break). In which case, it needs to be erased first.
  151. $linesToClear = $deleteLastLine = ($lastLine = end($this->content) ?: '') && !str_ends_with($lastLine, \PHP_EOL) ? 1 : 0;
  152. $linesAdded = $this->addContent($message, $newline);
  153. if ($lineOverflow = $this->maxHeight > 0 && $this->lines > $this->maxHeight) {
  154. // on overflow, clear the whole section and redraw again (to remove the first lines)
  155. $linesToClear = $this->maxHeight;
  156. }
  157. $erasedContent = $this->popStreamContentUntilCurrentSection($linesToClear);
  158. if ($lineOverflow) {
  159. // redraw existing lines of the section
  160. $previousLinesOfSection = \array_slice($this->content, $this->lines - $this->maxHeight, $this->maxHeight - $linesAdded);
  161. parent::doWrite(implode('', $previousLinesOfSection), false);
  162. }
  163. // if the last line was removed, re-print its content together with the new content.
  164. // otherwise, just print the new content.
  165. parent::doWrite($deleteLastLine ? $lastLine.$message : $message, true);
  166. parent::doWrite($erasedContent, false);
  167. }
  168. /**
  169. * At initial stage, cursor is at the end of stream output. This method makes cursor crawl upwards until it hits
  170. * current section. Then it erases content it crawled through. Optionally, it erases part of current section too.
  171. */
  172. private function popStreamContentUntilCurrentSection(int $numberOfLinesToClearFromCurrentSection = 0): string
  173. {
  174. $numberOfLinesToClear = $numberOfLinesToClearFromCurrentSection;
  175. $erasedContent = [];
  176. foreach ($this->sections as $section) {
  177. if ($section === $this) {
  178. break;
  179. }
  180. $numberOfLinesToClear += $section->maxHeight ? min($section->lines, $section->maxHeight) : $section->lines;
  181. if ('' !== $sectionContent = $section->getVisibleContent()) {
  182. if (!str_ends_with($sectionContent, \PHP_EOL)) {
  183. $sectionContent .= \PHP_EOL;
  184. }
  185. $erasedContent[] = $sectionContent;
  186. }
  187. }
  188. if ($numberOfLinesToClear > 0) {
  189. // move cursor up n lines
  190. parent::doWrite(\sprintf("\x1b[%dA", $numberOfLinesToClear), false);
  191. // erase to end of screen
  192. parent::doWrite("\x1b[0J", false);
  193. }
  194. return implode('', array_reverse($erasedContent));
  195. }
  196. private function getDisplayLength(string $text): int
  197. {
  198. return Helper::width(Helper::removeDecoration($this->getFormatter(), str_replace("\t", ' ', $text)));
  199. }
  200. }