// Copyright 2012 The Kyua Authors.1// All rights reserved.2//3// Redistribution and use in source and binary forms, with or without4// modification, are permitted provided that the following conditions are5// met:6//7// * Redistributions of source code must retain the above copyright8// notice, this list of conditions and the following disclaimer.9// * Redistributions in binary form must reproduce the above copyright10// notice, this list of conditions and the following disclaimer in the11// documentation and/or other materials provided with the distribution.12// * Neither the name of Google Inc. nor the names of its contributors13// may be used to endorse or promote products derived from this software14// without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.2728#include "utils/text/table.hpp"2930#include <algorithm>31#include <iterator>32#include <limits>33#include <sstream>3435#include "utils/sanity.hpp"36#include "utils/text/operations.ipp"3738namespace text = utils::text;394041namespace {424344/// Applies user overrides to the column widths of a table.45///46/// \param table The table from which to calculate the column widths.47/// \param user_widths The column widths provided by the user. This vector must48/// have less or the same number of elements as the columns of the table.49/// Values of width_auto are ignored; any other explicit values are copied50/// to the output widths vector, including width_refill.51///52/// \return A vector with the widths of the columns of the input table with any53/// user overrides applied.54static text::widths_vector55override_column_widths(const text::table& table,56const text::widths_vector& user_widths)57{58PRE(user_widths.size() <= table.ncolumns());59text::widths_vector widths = table.column_widths();6061// Override the actual width of the columns based on user-specified widths.62for (text::widths_vector::size_type i = 0; i < user_widths.size(); ++i) {63const text::widths_vector::value_type& user_width = user_widths[i];64if (user_width != text::table_formatter::width_auto) {65PRE_MSG(user_width == text::table_formatter::width_refill ||66user_width >= widths[i],67"User-provided column widths must be larger than the "68"column contents (except for the width_refill column)");69widths[i] = user_width;70}71}7273return widths;74}757677/// Locates the refill column, if any.78///79/// \param widths The widths of the columns as returned by80/// override_column_widths(). Note that one of the columns may or may not81/// be width_refill, which is the column we are looking for.82///83/// \return The index of the refill column with a width_refill width if any, or84/// otherwise the index of the last column (which is the default refill column).85static text::widths_vector::size_type86find_refill_column(const text::widths_vector& widths)87{88text::widths_vector::size_type i = 0;89for (; i < widths.size(); ++i) {90if (widths[i] == text::table_formatter::width_refill)91return i;92}93return i - 1;94}959697/// Pads the widths of the table to fit within a maximum width.98///99/// On output, a column of the widths vector is truncated to a shorter length100/// than its current value, if the total width of the table would exceed the101/// maximum table width.102///103/// \param [in,out] widths The widths of the columns as returned by104/// override_column_widths(). One of these columns should have a value of105/// width_refill; if not, a default column is refilled.106/// \param user_max_width The target width of the table; must not be zero.107/// \param column_padding The padding between the cells, if any. The target108/// width should be larger than the padding times the number of columns; if109/// that is not the case, we attempt a readjustment here.110static void111refill_widths(text::widths_vector& widths,112const text::widths_vector::value_type user_max_width,113const std::size_t column_padding)114{115PRE(user_max_width != 0);116117// widths.size() is a proxy for the number of columns of the table.118const std::size_t total_padding = column_padding * (widths.size() - 1);119const text::widths_vector::value_type max_width = std::max(120user_max_width, total_padding) - total_padding;121122const text::widths_vector::size_type refill_column =123find_refill_column(widths);124INV(refill_column < widths.size());125126text::widths_vector::value_type width = 0;127for (text::widths_vector::size_type i = 0; i < widths.size(); ++i) {128if (i != refill_column)129width += widths[i];130}131widths[refill_column] = max_width - width;132}133134135/// Pads an input text to a specified width with spaces.136///137/// \param input The text to add padding to (may be empty).138/// \param length The desired length of the output.139/// \param is_last Whether the text being processed belongs to the last column140/// of a row or not. Values in the last column should not be padded to141/// prevent trailing whitespace on the screen (which affects copy/pasting142/// for example).143///144/// \return The padded cell. If the input string is longer than the desired145/// length, the input string is returned verbatim. The padded table won't be146/// correct, but we don't expect this to be a common case to worry about.147static std::string148pad_cell(const std::string& input, const std::size_t length, const bool is_last)149{150if (is_last)151return input;152else {153if (input.length() < length)154return input + std::string(length - input.length(), ' ');155else156return input;157}158}159160161/// Refills a cell and adds it to the output lines.162///163/// \param row The row containing the cell to be refilled.164/// \param widths The widths of the row.165/// \param column The column being refilled.166/// \param [in,out] textual_rows The output lines as processed so far. This is167/// updated to accomodate for the contents of the refilled cell, extending168/// the rows as necessary.169static void170refill_cell(const text::table_row& row, const text::widths_vector& widths,171const text::table_row::size_type column,172std::vector< text::table_row >& textual_rows)173{174const std::vector< std::string > rows = text::refill(row[column],175widths[column]);176177if (textual_rows.size() < rows.size())178textual_rows.resize(rows.size(), text::table_row(row.size()));179180for (std::vector< std::string >::size_type i = 0; i < rows.size(); ++i) {181for (text::table_row::size_type j = 0; j < row.size(); ++j) {182const bool is_last = j == row.size() - 1;183if (j == column)184textual_rows[i][j] = pad_cell(rows[i], widths[j], is_last);185else {186if (textual_rows[i][j].empty())187textual_rows[i][j] = pad_cell("", widths[j], is_last);188}189}190}191}192193194/// Formats a single table row.195///196/// \param row The row to format.197/// \param widths The widths of the columns to apply during formatting. Cells198/// wider than the specified width are refilled to attempt to fit in the199/// cell. Cells narrower than the width are right-padded with spaces.200/// \param separator The column separator to use.201///202/// \return The textual lines that contain the formatted row.203static std::vector< std::string >204format_row(const text::table_row& row, const text::widths_vector& widths,205const std::string& separator)206{207PRE(row.size() == widths.size());208209std::vector< text::table_row > textual_rows(1, text::table_row(row.size()));210211for (text::table_row::size_type column = 0; column < row.size(); ++column) {212if (widths[column] > row[column].length())213textual_rows[0][column] = pad_cell(row[column], widths[column],214column == row.size() - 1);215else216refill_cell(row, widths, column, textual_rows);217}218219std::vector< std::string > lines;220for (std::vector< text::table_row >::const_iterator221iter = textual_rows.begin(); iter != textual_rows.end(); ++iter) {222lines.push_back(text::join(*iter, separator));223}224return lines;225}226227228} // anonymous namespace229230231/// Constructs a new table.232///233/// \param ncolumns_ The number of columns that the table will have.234text::table::table(const table_row::size_type ncolumns_)235{236_column_widths.resize(ncolumns_, 0);237}238239240/// Gets the number of columns in the table.241///242/// \return The number of columns in the table. This value remains constant243/// during the existence of the table.244text::widths_vector::size_type245text::table::ncolumns(void) const246{247return _column_widths.size();248}249250251/// Gets the width of a column.252///253/// The returned value is not valid if add_row() is called again, as the column254/// may have grown in width.255///256/// \param column The index of the column of which to get the width. Must be257/// less than the total number of columns.258///259/// \return The width of a column.260text::widths_vector::value_type261text::table::column_width(const widths_vector::size_type column) const262{263PRE(column < _column_widths.size());264return _column_widths[column];265}266267268/// Gets the widths of all columns.269///270/// The returned value is not valid if add_row() is called again, as the columns271/// may have grown in width.272///273/// \return A vector with the width of all columns.274const text::widths_vector&275text::table::column_widths(void) const276{277return _column_widths;278}279280281/// Checks whether the table is empty or not.282///283/// \return True if the table is empty; false otherwise.284bool285text::table::empty(void) const286{287return _rows.empty();288}289290291/// Adds a row to the table.292///293/// \param row The row to be added. This row must have the same amount of294/// columns as defined during the construction of the table.295void296text::table::add_row(const table_row& row)297{298PRE(row.size() == _column_widths.size());299_rows.push_back(row);300301for (table_row::size_type i = 0; i < row.size(); ++i)302if (_column_widths[i] < row[i].length())303_column_widths[i] = row[i].length();304}305306307/// Gets an iterator pointing to the beginning of the rows of the table.308///309/// \return An iterator on the rows.310text::table::const_iterator311text::table::begin(void) const312{313return _rows.begin();314}315316317/// Gets an iterator pointing to the end of the rows of the table.318///319/// \return An iterator on the rows.320text::table::const_iterator321text::table::end(void) const322{323return _rows.end();324}325326327/// Column width to denote that the column has to fit all of its cells.328const std::size_t text::table_formatter::width_auto = 0;329330331/// Column width to denote that the column can be refilled to fit the table.332const std::size_t text::table_formatter::width_refill =333std::numeric_limits< std::size_t >::max();334335336/// Constructs a new table formatter.337text::table_formatter::table_formatter(void) :338_separator(""),339_table_width(0)340{341}342343344/// Sets the width of a column.345///346/// All columns except one must have a width that is, at least, as wide as the347/// widest cell in the column. One of the columns can have a width of348/// width_refill, which indicates that the column will be refilled if the table349/// does not fit in its maximum width.350///351/// \param column The index of the column to set the width for.352/// \param width The width to set the column to.353///354/// \return A reference to this formatter to allow using the builder pattern.355text::table_formatter&356text::table_formatter::set_column_width(const table_row::size_type column,357const std::size_t width)358{359#if !defined(NDEBUG)360if (width == width_refill) {361for (widths_vector::size_type i = 0; i < _column_widths.size(); i++) {362if (i != column)363PRE_MSG(_column_widths[i] != width_refill,364"Only one column width can be set to width_refill");365}366}367#endif368369if (_column_widths.size() < column + 1)370_column_widths.resize(column + 1, width_auto);371_column_widths[column] = width;372return *this;373}374375376/// Sets the separator to use between the cells.377///378/// \param separator The separator to use.379///380/// \return A reference to this formatter to allow using the builder pattern.381text::table_formatter&382text::table_formatter::set_separator(const char* separator)383{384_separator = separator;385return *this;386}387388389/// Sets the maximum width of the table.390///391/// \param table_width The maximum width of the table; cannot be zero.392///393/// \return A reference to this formatter to allow using the builder pattern.394text::table_formatter&395text::table_formatter::set_table_width(const std::size_t table_width)396{397PRE(table_width > 0);398_table_width = table_width;399return *this;400}401402403/// Formats a table into a collection of textual lines.404///405/// \param t Table to format.406///407/// \return A collection of textual lines.408std::vector< std::string >409text::table_formatter::format(const table& t) const410{411std::vector< std::string > lines;412413if (!t.empty()) {414widths_vector widths = override_column_widths(t, _column_widths);415if (_table_width != 0)416refill_widths(widths, _table_width, _separator.length());417418for (table::const_iterator iter = t.begin(); iter != t.end(); ++iter) {419const std::vector< std::string > sublines =420format_row(*iter, widths, _separator);421std::copy(sublines.begin(), sublines.end(),422std::back_inserter(lines));423}424}425426return lines;427}428429430