• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
LinePrinter()33 LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {
34   const char* term = getenv("TERM");
35 #ifndef _WIN32
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   if (term && string(term) == "dumb") {
43     smart_terminal_ = false;
44   } else {
45     setvbuf(stdout, NULL, _IONBF, 0);
46     console_ = GetStdHandle(STD_OUTPUT_HANDLE);
47     CONSOLE_SCREEN_BUFFER_INFO csbi;
48     smart_terminal_ = GetConsoleScreenBufferInfo(console_, &csbi);
49   }
50 #endif
51   supports_color_ = smart_terminal_;
52   if (!supports_color_) {
53     const char* clicolor_force = getenv("CLICOLOR_FORCE");
54     supports_color_ = clicolor_force && string(clicolor_force) != "0";
55   }
56 #ifdef _WIN32
57   // Try enabling ANSI escape sequence support on Windows 10 terminals.
58   if (supports_color_) {
59     DWORD mode;
60     if (GetConsoleMode(console_, &mode)) {
61       if (!SetConsoleMode(console_, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
62         supports_color_ = false;
63       }
64     }
65   }
66 #endif
67 }
68 
Print(string to_print,LineType type)69 void LinePrinter::Print(string to_print, LineType type) {
70   if (console_locked_) {
71     line_buffer_ = to_print;
72     line_type_ = type;
73     return;
74   }
75 
76   if (smart_terminal_) {
77     printf("\r");  // Print over previous line, if any.
78     // On Windows, calling a C library function writing to stdout also handles
79     // pausing the executable when the "Pause" key or Ctrl-S is pressed.
80   }
81 
82   if (smart_terminal_ && type == ELIDE) {
83 #ifdef _WIN32
84     CONSOLE_SCREEN_BUFFER_INFO csbi;
85     GetConsoleScreenBufferInfo(console_, &csbi);
86 
87     to_print = ElideMiddle(to_print, static_cast<size_t>(csbi.dwSize.X));
88     // We don't want to have the cursor spamming back and forth, so instead of
89     // printf use WriteConsoleOutput which updates the contents of the buffer,
90     // but doesn't move the cursor position.
91     COORD buf_size = { csbi.dwSize.X, 1 };
92     COORD zero_zero = { 0, 0 };
93     SMALL_RECT target = {
94       csbi.dwCursorPosition.X, csbi.dwCursorPosition.Y,
95       static_cast<SHORT>(csbi.dwCursorPosition.X + csbi.dwSize.X - 1),
96       csbi.dwCursorPosition.Y
97     };
98     vector<CHAR_INFO> char_data(csbi.dwSize.X);
99     for (size_t i = 0; i < static_cast<size_t>(csbi.dwSize.X); ++i) {
100       char_data[i].Char.AsciiChar = i < to_print.size() ? to_print[i] : ' ';
101       char_data[i].Attributes = csbi.wAttributes;
102     }
103     WriteConsoleOutput(console_, &char_data[0], buf_size, zero_zero, &target);
104 #else
105     // Limit output to width of the terminal if provided so we don't cause
106     // line-wrapping.
107     winsize size;
108     if ((ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) == 0) && size.ws_col) {
109       to_print = ElideMiddle(to_print, size.ws_col);
110     }
111     printf("%s", to_print.c_str());
112     printf("\x1B[K");  // Clear to end of line.
113     fflush(stdout);
114 #endif
115 
116     have_blank_line_ = false;
117   } else {
118     printf("%s\n", to_print.c_str());
119   }
120 }
121 
PrintOrBuffer(const char * data,size_t size)122 void LinePrinter::PrintOrBuffer(const char* data, size_t size) {
123   if (console_locked_) {
124     output_buffer_.append(data, size);
125   } else {
126     // Avoid printf and C strings, since the actual output might contain null
127     // bytes like UTF-16 does (yuck).
128     fwrite(data, 1, size, stdout);
129   }
130 }
131 
PrintOnNewLine(const string & to_print)132 void LinePrinter::PrintOnNewLine(const string& to_print) {
133   if (console_locked_ && !line_buffer_.empty()) {
134     output_buffer_.append(line_buffer_);
135     output_buffer_.append(1, '\n');
136     line_buffer_.clear();
137   }
138   if (!have_blank_line_) {
139     PrintOrBuffer("\n", 1);
140   }
141   if (!to_print.empty()) {
142     PrintOrBuffer(&to_print[0], to_print.size());
143   }
144   have_blank_line_ = to_print.empty() || *to_print.rbegin() == '\n';
145 }
146 
SetConsoleLocked(bool locked)147 void LinePrinter::SetConsoleLocked(bool locked) {
148   if (locked == console_locked_)
149     return;
150 
151   if (locked)
152     PrintOnNewLine("");
153 
154   console_locked_ = locked;
155 
156   if (!locked) {
157     PrintOnNewLine(output_buffer_);
158     if (!line_buffer_.empty()) {
159       Print(line_buffer_, line_type_);
160     }
161     output_buffer_.clear();
162     line_buffer_.clear();
163   }
164 }
165