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 "util.h"
32 
33 LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {
34 #ifndef _WIN32
35  const char* term = getenv("TERM");
36  smart_terminal_ = isatty(1) && term && string(term) != "dumb";
37 #else
38  // Disable output buffer. It'd be nice to use line buffering but
39  // MSDN says: "For some systems, [_IOLBF] provides line
40  // buffering. However, for Win32, the behavior is the same as _IOFBF
41  // - Full Buffering."
42  setvbuf(stdout, NULL, _IONBF, 0);
43  console_ = GetStdHandle(STD_OUTPUT_HANDLE);
44  CONSOLE_SCREEN_BUFFER_INFO csbi;
45  smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi);
46 #endif
48  if (!supports_color_) {
49  const char* clicolor_force = getenv("CLICOLOR_FORCE");
50  supports_color_ = clicolor_force && string(clicolor_force) != "0";
51  }
52 #ifdef _WIN32
53  // Try enabling ANSI escape sequence support on Windows 10 terminals.
54  if (supports_color_) {
55  DWORD mode;
56  if (GetConsoleMode(console_, &mode)) {
57  SetConsoleMode(console_, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
58  }
59  }
60 #endif
61 }
62 
63 void LinePrinter::Print(string to_print, LineType type) {
64  if (console_locked_) {
65  line_buffer_ = to_print;
66  line_type_ = type;
67  return;
68  }
69 
70  if (smart_terminal_) {
71  printf("\r"); // Print over previous line, if any.
72  // On Windows, calling a C library function writing to stdout also handles
73  // pausing the executable when the "Pause" key or Ctrl-S is pressed.
74  }
75 
76  if (smart_terminal_ && type == ELIDE) {
77 #ifdef _WIN32
78  CONSOLE_SCREEN_BUFFER_INFO csbi;
79  GetConsoleScreenBufferInfo(console_, &csbi);
80 
81  to_print = ElideMiddle(to_print, static_cast<size_t>(csbi.dwSize.X));
82  // We don't want to have the cursor spamming back and forth, so instead of
83  // printf use WriteConsoleOutput which updates the contents of the buffer,
84  // but doesn't move the cursor position.
85  COORD buf_size = { csbi.dwSize.X, 1 };
86  COORD zero_zero = { 0, 0 };
87  SMALL_RECT target = {
88  csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y,
89  static_cast<SHORT>(csbi.dwCursorPosition.X + csbi.dwSize.X - 1),
90  csbi.dwCursorPosition.Y
91  };
92  vector<CHAR_INFO> char_data(csbi.dwSize.X);
93  for (size_t i = 0; i < static_cast<size_t>(csbi.dwSize.X); ++i) {
94  char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' ';
95  char_data[i].Attributes = csbi.wAttributes;
96  }
97  WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target);
98 #else
99  // Limit output to width of the terminal if provided so we don't cause
100  // line-wrapping.
101  winsize size;
102  if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) && size.ws_col) {
103  to_print = ElideMiddle(to_print, size.ws_col);
104  }
105  printf("%s", to_print.c_str());
106  printf("\x1B[K"); // Clear to end of line.
107  fflush(stdout);
108 #endif
109 
110  have_blank_line_ = false;
111  } else {
112  printf("%s\n", to_print.c_str());
113  }
114 }
115 
116 void LinePrinter::PrintOrBuffer(const char* data, size_t size) {
117  if (console_locked_) {
118  output_buffer_.append(data, size);
119  } else {
120  // Avoid printf and C strings, since the actual output might contain null
121  // bytes like UTF-16 does (yuck).
122  fwrite(data, 1, size, stdout);
123  }
124 }
125 
126 void LinePrinter::PrintOnNewLine(const string& to_print) {
127  if (console_locked_ && !line_buffer_.empty()) {
129  output_buffer_.append(1, '\n');
130  line_buffer_.clear();
131  }
132  if (!have_blank_line_) {
133  PrintOrBuffer("\n", 1);
134  }
135  if (!to_print.empty()) {
136  PrintOrBuffer(&to_print[0], to_print.size());
137  }
138  have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\n';
139 }
140 
141 void LinePrinter::SetConsoleLocked(bool locked) {
142  if (locked == console_locked_)
143  return;
144 
145  if (locked)
146  PrintOnNewLine("");
147 
148  console_locked_ = locked;
149 
150  if (!locked) {
152  if (!line_buffer_.empty()) {
154  }
155  output_buffer_.clear();
156  line_buffer_.clear();
157  }
158 }
bool have_blank_line_
Whether the caret is at the beginning of a blank line.
Definition: line_printer.h:55
bool supports_color_
Whether we can use ISO 6429 (ANSI) color sequences.
Definition: line_printer.h:52
void PrintOnNewLine(const string &to_print)
Prints a string on a new line, not overprinting previous output.
bool console_locked_
Whether console is locked.
Definition: line_printer.h:58
LineType line_type_
Buffered line type while console is locked.
Definition: line_printer.h:64
void SetConsoleLocked(bool locked)
Lock or unlock the console.
void PrintOrBuffer(const char *data, size_t size)
Print the given data to the console, or buffer it if it is locked.
string line_buffer_
Buffered current line while console is locked.
Definition: line_printer.h:61
void Print(string to_print, LineType type)
Overprints the current line.
Definition: line_printer.cc:63
bool smart_terminal_
Whether we can do fancy terminal control codes.
Definition: line_printer.h:49
string output_buffer_
Buffered console output while console is locked.
Definition: line_printer.h:67
string ElideMiddle(const string &str, size_t width)
Elide the given string str with &#39;...&#39; in the middle if the length exceeds width.
Definition: util.cc:587