1// Copyright 2011 Google Inc.
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
31extern "C" {
32#include <sys/ioctl.h>
33
34#include <unistd.h>
35}
36
37#include <iostream>
38
39#include "utils/cmdline/globals.hpp"
40#include "utils/env.hpp"
41#include "utils/format/macros.hpp"
42#include "utils/fs/path.hpp"
43#include "utils/logging/macros.hpp"
44#include "utils/optional.ipp"
45#include "utils/text/operations.ipp"
46#include "utils/sanity.hpp"
47#include "utils/text/table.hpp"
48
49namespace cmdline = utils::cmdline;
50namespace text = utils::text;
51
52using utils::none;
53using utils::optional;
54
55
56/// Destructor for the class.
57cmdline::ui::~ui(void)
58{
59}
60
61
62/// Writes a line to stderr.
63///
64/// The written line is printed as is, without being wrapped to fit within the
65/// screen width.
66///
67/// \param message The line to print, without the trailing newline character.
68/// \param newline Whether to append a newline to the message or not.
69void
70cmdline::ui::err(const std::string& message, const bool newline)
71{
72    PRE(message.empty() || message[message.length() - 1] != '\n');
73    LI(F("stderr: %s") % message);
74    if (newline)
75        std::cerr << message << "\n";
76    else {
77        std::cerr << message;
78        std::cerr.flush();
79    }
80}
81
82
83/// Writes a line to stdout.
84///
85/// The written line is printed as is, without being wrapped to fit within the
86/// screen width.
87///
88/// \param message The line to print, without the trailing newline character.
89/// \param newline Whether to append a newline to the message or not.
90void
91cmdline::ui::out(const std::string& message, const bool newline)
92{
93    PRE(message.empty() || message[message.length() - 1] != '\n');
94    LI(F("stdout: %s") % message);
95    if (newline)
96        std::cout << message << "\n";
97    else {
98        std::cout << message;
99        std::cout.flush();
100    }
101}
102
103
104/// Queries the width of the screen.
105///
106/// This information comes first from the COLUMNS environment variable.  If not
107/// present or invalid, and if the stdout of the current process is connected to
108/// a terminal the width is deduced from the terminal itself.  Ultimately, if
109/// all fails, none is returned.  This function shall not raise any errors.
110///
111/// Be aware that the results of this query are cached during execution.
112/// Subsequent calls to this function will always return the same value even if
113/// the terminal size has actually changed.
114///
115/// \todo Install a signal handler for SIGWINCH so that we can readjust our
116/// knowledge of the terminal width when the user resizes the window.
117///
118/// \return The width of the screen if it was possible to determine it, or none
119/// otherwise.
120optional< std::size_t >
121cmdline::ui::screen_width(void) const
122{
123    static bool done = false;
124    static optional< std::size_t > width = none;
125
126    if (!done) {
127        const optional< std::string > columns = utils::getenv("COLUMNS");
128        if (columns) {
129            if (columns.get().length() > 0) {
130                try {
131                    width = utils::make_optional(
132                        utils::text::to_type< std::size_t >(columns.get()));
133                } catch (const utils::text::value_error& e) {
134                    LD(F("Ignoring invalid value in COLUMNS variable: %s") %
135                       e.what());
136                }
137            }
138        }
139        if (!width) {
140            struct ::winsize ws;
141            if (::ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) != -1)
142                width = optional< std::size_t >(ws.ws_col);
143        }
144
145        if (width && width.get() >= 80)
146            width.get() -= 5;
147
148        done = true;
149    }
150
151    return width;
152}
153
154
155/// Writes a line to stdout.
156///
157/// The line is wrapped to fit on screen.
158///
159/// \param message The line to print, without the trailing newline character.
160void
161cmdline::ui::out_wrap(const std::string& message)
162{
163    const optional< std::size_t > max_width = screen_width();
164    if (max_width) {
165        const std::vector< std::string > lines = text::refill(
166            message, max_width.get());
167        for (std::vector< std::string >::const_iterator iter = lines.begin();
168             iter != lines.end(); iter++)
169            out(*iter);
170    } else
171        out(message);
172}
173
174
175/// Writes a line to stdout with a leading tag.
176///
177/// If the line does not fit on the current screen width, the line is broken
178/// into pieces and the tag is repeated on every line.
179///
180/// \param tag The leading line tag.
181/// \param message The message to be printed, without the trailing newline
182///     character.
183/// \param repeat If true, print the tag on every line; otherwise, indent the
184///     text of all lines to match the width of the tag on the first line.
185void
186cmdline::ui::out_tag_wrap(const std::string& tag, const std::string& message,
187                          const bool repeat)
188{
189    const optional< std::size_t > max_width = screen_width();
190    if (max_width && max_width.get() > tag.length()) {
191        const std::vector< std::string > lines = text::refill(
192            message, max_width.get() - tag.length());
193        for (std::vector< std::string >::const_iterator iter = lines.begin();
194             iter != lines.end(); iter++) {
195            if (repeat || iter == lines.begin())
196                out(F("%s%s") % tag % *iter);
197            else
198                out(F("%s%s") % std::string(tag.length(), ' ') % *iter);
199        }
200    } else {
201        out(F("%s%s") % tag % message);
202    }
203}
204
205
206/// Writes a table to stdout.
207///
208/// \param table The table to write.
209/// \param formatter The table formatter to use to convert the table to a
210///     console representation.
211/// \param prefix Text to prepend to all the lines of the output table.
212void
213cmdline::ui::out_table(const text::table& table,
214                       text::table_formatter formatter,
215                       const std::string& prefix)
216{
217    if (table.empty())
218        return;
219
220    const optional< std::size_t > max_width = screen_width();
221    if (max_width)
222        formatter.set_table_width(max_width.get() - prefix.length());
223
224    const std::vector< std::string > lines = formatter.format(table);
225    for (std::vector< std::string >::const_iterator iter = lines.begin();
226         iter != lines.end(); ++iter)
227        out(prefix + *iter);
228}
229
230
231/// Formats and prints an error message.
232///
233/// \param ui_ The user interface object used to print the message.
234/// \param message The message to print.  Must not end with a dot nor with a
235///     newline character.
236void
237cmdline::print_error(ui* ui_, const std::string& message)
238{
239    PRE(!message.empty() && message[message.length() - 1] != '.');
240    LE(message);
241    ui_->err(F("%s: E: %s.") % cmdline::progname() % message);
242}
243
244
245/// Formats and prints an informational message.
246///
247/// \param ui_ The user interface object used to print the message.
248/// \param message The message to print.  Must not end with a dot nor with a
249///     newline character.
250void
251cmdline::print_info(ui* ui_, const std::string& message)
252{
253    PRE(!message.empty() && message[message.length() - 1] != '.');
254    LI(message);
255    ui_->err(F("%s: I: %s.") % cmdline::progname() % message);
256}
257
258
259/// Formats and prints a warning message.
260///
261/// \param ui_ The user interface object used to print the message.
262/// \param message The message to print.  Must not end with a dot nor with a
263///     newline character.
264void
265cmdline::print_warning(ui* ui_, const std::string& message)
266{
267    PRE(!message.empty() && message[message.length() - 1] != '.');
268    LW(message);
269    ui_->err(F("%s: W: %s.") % cmdline::progname() % message);
270}
271