xref: /freebsd/contrib/kyua/utils/cmdline/ui.cpp (revision fe6060f10f634930ff71b7c50291ddc610da2475)
1 // Copyright 2011 The Kyua Authors.
2 // All rights reserved.
3 //
4 // Redistribution and use in source and binary forms, with or without
5 // modification, are permitted provided that the following conditions are
6 // met:
7 //
8 // * Redistributions of source code must retain the above copyright
9 //   notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 //   notice, this list of conditions and the following disclaimer in the
12 //   documentation and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors
14 //   may be used to endorse or promote products derived from this software
15 //   without specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 
29 #include "utils/cmdline/ui.hpp"
30 
31 #if defined(HAVE_CONFIG_H)
32 #   include "config.h"
33 #endif
34 
35 extern "C" {
36 #include <sys/param.h>
37 #include <sys/ioctl.h>
38 
39 #if defined(HAVE_TERMIOS_H)
40 #   include <termios.h>
41 #endif
42 #include <unistd.h>
43 }
44 
45 #include <iostream>
46 
47 #include "utils/cmdline/globals.hpp"
48 #include "utils/env.hpp"
49 #include "utils/format/macros.hpp"
50 #include "utils/fs/path.hpp"
51 #include "utils/logging/macros.hpp"
52 #include "utils/optional.ipp"
53 #include "utils/text/operations.ipp"
54 #include "utils/text/table.hpp"
55 
56 namespace cmdline = utils::cmdline;
57 namespace text = utils::text;
58 
59 using utils::none;
60 using utils::optional;
61 
62 
63 /// Destructor for the class.
64 cmdline::ui::~ui(void)
65 {
66 }
67 
68 
69 /// Writes a single line to stderr.
70 ///
71 /// The written line is printed as is, without being wrapped to fit within the
72 /// screen width.  If the caller wants to print more than one line, it shall
73 /// invoke this function once per line.
74 ///
75 /// \param message The line to print.  Should not include a trailing newline
76 ///     character.
77 /// \param newline Whether to append a newline to the message or not.
78 void
79 cmdline::ui::err(const std::string& message, const bool newline)
80 {
81     LI(F("stderr: %s") % message);
82     if (newline)
83         std::cerr << message << "\n";
84     else {
85         std::cerr << message;
86         std::cerr.flush();
87     }
88 }
89 
90 
91 /// Writes a single line to stdout.
92 ///
93 /// The written line is printed as is, without being wrapped to fit within the
94 /// screen width.  If the caller wants to print more than one line, it shall
95 /// invoke this function once per line.
96 ///
97 /// \param message The line to print.  Should not include a trailing newline
98 ///     character.
99 /// \param newline Whether to append a newline to the message or not.
100 void
101 cmdline::ui::out(const std::string& message, const bool newline)
102 {
103     LI(F("stdout: %s") % message);
104     if (newline)
105         std::cout << message << "\n";
106     else {
107         std::cout << message;
108         std::cout.flush();
109     }
110 }
111 
112 
113 /// Queries the width of the screen.
114 ///
115 /// This information comes first from the COLUMNS environment variable.  If not
116 /// present or invalid, and if the stdout of the current process is connected to
117 /// a terminal the width is deduced from the terminal itself.  Ultimately, if
118 /// all fails, none is returned.  This function shall not raise any errors.
119 ///
120 /// Be aware that the results of this query are cached during execution.
121 /// Subsequent calls to this function will always return the same value even if
122 /// the terminal size has actually changed.
123 ///
124 /// \todo Install a signal handler for SIGWINCH so that we can readjust our
125 /// knowledge of the terminal width when the user resizes the window.
126 ///
127 /// \return The width of the screen if it was possible to determine it, or none
128 /// otherwise.
129 optional< std::size_t >
130 cmdline::ui::screen_width(void) const
131 {
132     static bool done = false;
133     static optional< std::size_t > width = none;
134 
135     if (!done) {
136         const optional< std::string > columns = utils::getenv("COLUMNS");
137         if (columns) {
138             if (columns.get().length() > 0) {
139                 try {
140                     width = utils::make_optional(
141                         utils::text::to_type< std::size_t >(columns.get()));
142                 } catch (const utils::text::value_error& e) {
143                     LD(F("Ignoring invalid value in COLUMNS variable: %s") %
144                        e.what());
145                 }
146             }
147         }
148         if (!width) {
149             struct ::winsize ws;
150             if (::ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1)
151                 width = optional< std::size_t >(ws.ws_col);
152         }
153 
154         if (width && width.get() >= 80)
155             width.get() -= 5;
156 
157         done = true;
158     }
159 
160     return width;
161 }
162 
163 
164 /// Writes a line to stdout.
165 ///
166 /// The line is wrapped to fit on screen.
167 ///
168 /// \param message The line to print, without the trailing newline character.
169 void
170 cmdline::ui::out_wrap(const std::string& message)
171 {
172     const optional< std::size_t > max_width = screen_width();
173     if (max_width) {
174         const std::vector< std::string > lines = text::refill(
175             message, max_width.get());
176         for (std::vector< std::string >::const_iterator iter = lines.begin();
177              iter != lines.end(); iter++)
178             out(*iter);
179     } else
180         out(message);
181 }
182 
183 
184 /// Writes a line to stdout with a leading tag.
185 ///
186 /// If the line does not fit on the current screen width, the line is broken
187 /// into pieces and the tag is repeated on every line.
188 ///
189 /// \param tag The leading line tag.
190 /// \param message The message to be printed, without the trailing newline
191 ///     character.
192 /// \param repeat If true, print the tag on every line; otherwise, indent the
193 ///     text of all lines to match the width of the tag on the first line.
194 void
195 cmdline::ui::out_tag_wrap(const std::string& tag, const std::string& message,
196                           const bool repeat)
197 {
198     const optional< std::size_t > max_width = screen_width();
199     if (max_width && max_width.get() > tag.length()) {
200         const std::vector< std::string > lines = text::refill(
201             message, max_width.get() - tag.length());
202         for (std::vector< std::string >::const_iterator iter = lines.begin();
203              iter != lines.end(); iter++) {
204             if (repeat || iter == lines.begin())
205                 out(F("%s%s") % tag % *iter);
206             else
207                 out(F("%s%s") % std::string(tag.length(), ' ') % *iter);
208         }
209     } else {
210         out(F("%s%s") % tag % message);
211     }
212 }
213 
214 
215 /// Writes a table to stdout.
216 ///
217 /// \param table The table to write.
218 /// \param formatter The table formatter to use to convert the table to a
219 ///     console representation.
220 /// \param prefix Text to prepend to all the lines of the output table.
221 void
222 cmdline::ui::out_table(const text::table& table,
223                        text::table_formatter formatter,
224                        const std::string& prefix)
225 {
226     if (table.empty())
227         return;
228 
229     const optional< std::size_t > max_width = screen_width();
230     if (max_width)
231         formatter.set_table_width(max_width.get() - prefix.length());
232 
233     const std::vector< std::string > lines = formatter.format(table);
234     for (std::vector< std::string >::const_iterator iter = lines.begin();
235          iter != lines.end(); ++iter)
236         out(prefix + *iter);
237 }
238 
239 
240 /// Formats and prints an error message.
241 ///
242 /// \param ui_ The user interface object used to print the message.
243 /// \param message The message to print.  Should not end with a newline
244 ///     character.
245 void
246 cmdline::print_error(ui* ui_, const std::string& message)
247 {
248     LE(message);
249     ui_->err(F("%s: E: %s") % cmdline::progname() % message);
250 }
251 
252 
253 /// Formats and prints an informational message.
254 ///
255 /// \param ui_ The user interface object used to print the message.
256 /// \param message The message to print.  Should not end with a newline
257 ///     character.
258 void
259 cmdline::print_info(ui* ui_, const std::string& message)
260 {
261     LI(message);
262     ui_->err(F("%s: I: %s") % cmdline::progname() % message);
263 }
264 
265 
266 /// Formats and prints a warning message.
267 ///
268 /// \param ui_ The user interface object used to print the message.
269 /// \param message The message to print.  Should not end with a newline
270 ///     character.
271 void
272 cmdline::print_warning(ui* ui_, const std::string& message)
273 {
274     LW(message);
275     ui_->err(F("%s: W: %s") % cmdline::progname() % message);
276 }
277