Ninja
line_printer.cc
Go to the documentation of this file.
1 // Copyright 2013 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "line_printer.h"
16 
17 #include <stdio.h>
18 #include <stdlib.h>
19 #ifdef _WIN32
20 #include <windows.h>
21 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
22 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
23 #endif
24 #else
25 #include <unistd.h>
26 #include <sys/ioctl.h>
27 #include <termios.h>
28 #include <sys/time.h>
29 #endif
30 
31 #include "elide_middle.h"
32 #include "util.h"
33 
34 using namespace std;
35 
36 LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {
37  const char* term = getenv("TERM");
38 #ifndef _WIN32
39  smart_terminal_ = isatty(1) && term && string(term) != "dumb";
40 #else
41  if (term && string(term) == "dumb") {
42  smart_terminal_ = false;
43  } else {
44  console_ = GetStdHandle(STD_OUTPUT_HANDLE);
45  CONSOLE_SCREEN_BUFFER_INFO csbi;
46  smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi);
47  }
48 #endif
50 #ifdef _WIN32
51  // Try enabling ANSI escape sequence support on Windows 10 terminals.
52  if (supports_color_) {
53  DWORD mode;
54  if (GetConsoleMode(console_, &mode)) {
55  if (!SetConsoleMode(console_, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
56  supports_color_ = false;
57  }
58  }
59  }
60 #endif
61  if (!supports_color_) {
62  const char* clicolor_force = getenv("CLICOLOR_FORCE");
63  supports_color_ = clicolor_force && std::string(clicolor_force) != "0";
64  }
65 }
66 
67 void LinePrinter::Print(string to_print, LineType type) {
68  if (console_locked_) {
69  line_buffer_ = to_print;
70  line_type_ = type;
71  return;
72  }
73 
74  if (smart_terminal_) {
75  printf("\r"); // Print over previous line, if any.
76  // On Windows, calling a C library function writing to stdout also handles
77  // pausing the executable when the "Pause" key or Ctrl-S is pressed.
78  }
79 
80  if (smart_terminal_ && type == ELIDE) {
81 #ifdef _WIN32
82  CONSOLE_SCREEN_BUFFER_INFO csbi;
83  GetConsoleScreenBufferInfo(console_, &csbi);
84 
85  ElideMiddleInPlace(to_print, static_cast<size_t>(csbi.dwSize.X));
86  if (supports_color_) { // this means ENABLE_VIRTUAL_TERMINAL_PROCESSING
87  // succeeded
88  printf("%s\x1B[K", to_print.c_str()); // Clear to end of line.
89  fflush(stdout);
90  } else {
91  // We don't want to have the cursor spamming back and forth, so instead of
92  // printf use WriteConsoleOutput which updates the contents of the buffer,
93  // but doesn't move the cursor position.
94  COORD buf_size = { csbi.dwSize.X, 1 };
95  COORD zero_zero = { 0, 0 };
96  SMALL_RECT target = { csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y,
97  static_cast<SHORT>(csbi.dwCursorPosition.X +
98  csbi.dwSize.X - 1),
99  csbi.dwCursorPosition.Y };
100  vector<CHAR_INFO> char_data(csbi.dwSize.X);
101  for (size_t i = 0; i < static_cast<size_t>(csbi.dwSize.X); ++i) {
102  char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' ';
103  char_data[i].Attributes = csbi.wAttributes;
104  }
105  WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target);
106  }
107 #else
108  // Limit output to width of the terminal if provided so we don't cause
109  // line-wrapping.
110  winsize size;
111  if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) && size.ws_col) {
112  ElideMiddleInPlace(to_print, size.ws_col);
113  }
114  printf("%s", to_print.c_str());
115  printf("\x1B[K"); // Clear to end of line.
116  fflush(stdout);
117 #endif
118 
119  have_blank_line_ = false;
120  } else {
121  printf("%s\n", to_print.c_str());
122  fflush(stdout);
123  }
124 }
125 
126 void LinePrinter::PrintOrBuffer(const char* data, size_t size) {
127  if (console_locked_) {
128  output_buffer_.append(data, size);
129  } else {
130  // Avoid printf and C strings, since the actual output might contain null
131  // bytes like UTF-16 does (yuck).
132  fwrite(data, 1, size, stdout);
133  }
134 }
135 
136 void LinePrinter::PrintOnNewLine(const string& to_print) {
137  if (console_locked_ && !line_buffer_.empty()) {
139  output_buffer_.append(1, '\n');
140  line_buffer_.clear();
141  }
142  if (!have_blank_line_) {
143  PrintOrBuffer("\n", 1);
144  }
145  if (!to_print.empty()) {
146  PrintOrBuffer(&to_print[0], to_print.size());
147  }
148  have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\n';
149 }
150 
151 void LinePrinter::SetConsoleLocked(bool locked) {
152  if (locked == console_locked_)
153  return;
154 
155  if (locked)
156  PrintOnNewLine("");
157 
158  console_locked_ = locked;
159 
160  if (!locked) {
162  if (!line_buffer_.empty()) {
164  }
165  output_buffer_.clear();
166  line_buffer_.clear();
167  }
168 }
void ElideMiddleInPlace(std::string &str, size_t max_width)
Elide the given string str with '...' in the middle if the length exceeds max_width.
Definition: hash_map.h:26
void PrintOrBuffer(const char *data, size_t size)
Print the given data to the console, or buffer it if it is locked.
bool smart_terminal_
Whether we can do fancy terminal control codes.
Definition: line_printer.h:48
void Print(std::string to_print, LineType type)
Overprints the current line.
Definition: line_printer.cc:67
bool console_locked_
Whether console is locked.
Definition: line_printer.h:57
bool have_blank_line_
Whether the caret is at the beginning of a blank line.
Definition: line_printer.h:54
void SetConsoleLocked(bool locked)
Lock or unlock the console.
std::string output_buffer_
Buffered console output while console is locked.
Definition: line_printer.h:66
bool supports_color_
Whether we can use ISO 6429 (ANSI) color sequences.
Definition: line_printer.h:51
std::string line_buffer_
Buffered current line while console is locked.
Definition: line_printer.h:60
void PrintOnNewLine(const std::string &to_print)
Prints a string on a new line, not overprinting previous output.
LineType line_type_
Buffered line type while console is locked.
Definition: line_printer.h:63