ConsoleSectionOutput.php 8.3 KB

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