java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 15 Aug 2015 16:12:06 +0200
branchv_0
changeset 218 8e38caf43ca8
parent 207 2bba68ef47c1
child 219 3b1733fb3793
permissions -rw-r--r--
SingleRecordFormatter: escape whitespace characters in the same way as in TabularFormatter
     1 /**
     2  * SQL-DK
     3  * Copyright © 2013 František Kučera (frantovo.cz)
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, either version 3 of the License, or
     8  * (at your option) any later version.
     9  *
    10  * This program is distributed in the hope that it will be useful,
    11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  * GNU General Public License for more details.
    14  *
    15  * You should have received a copy of the GNU General Public License
    16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
    17  */
    18 package info.globalcode.sql.dk.formatting;
    19 
    20 import info.globalcode.sql.dk.ColorfulPrintWriter;
    21 import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
    22 import info.globalcode.sql.dk.Functions;
    23 import static info.globalcode.sql.dk.Functions.lpad;
    24 import static info.globalcode.sql.dk.Functions.rpad;
    25 import static info.globalcode.sql.dk.Functions.repeat;
    26 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
    27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
    28 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
    29 import java.util.List;
    30 
    31 /**
    32  * <p>
    33  * Prints human-readable output – tables of result sets and text messages with update counts.
    34  * </p>
    35  *
    36  * <p>
    37  * Longer values might break the table – overflow the cells – see alternative tabular formatters
    38  * and the {@linkplain #PROPERTY_TRIM} property.
    39  * </p>
    40  *
    41  * @author Ing. František Kučera (frantovo.cz)
    42  * @see TabularPrefetchingFormatter
    43  * @see TabularWrappingFormatter
    44  */
    45 @PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
    46 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
    47 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
    48 public class TabularFormatter extends AbstractFormatter {
    49 
    50 	public static final String NAME = "tabular"; // bash-completion:formatter
    51 	private static final String HEADER_TYPE_PREFIX = " (";
    52 	private static final String HEADER_TYPE_SUFFIX = ")";
    53 	public static final String PROPERTY_ASCII = "ascii";
    54 	public static final String PROPERTY_TRIM = "trim";
    55 	protected ColorfulPrintWriter out;
    56 	private boolean firstResult = true;
    57 	private int[] columnWidth;
    58 	/**
    59 	 * use ASCII borders instead of unicode ones
    60 	 */
    61 	private final boolean asciiNostalgia;
    62 	/**
    63 	 * Trim values if they are longer than cell size
    64 	 */
    65 	private final boolean trimValues;
    66 
    67 	public TabularFormatter(FormatterContext formatterContext) {
    68 		super(formatterContext);
    69 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    70 		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
    71 		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
    72 		out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
    73 	}
    74 
    75 	@Override
    76 	public void writeStartResultSet(ColumnsHeader header) {
    77 		super.writeStartResultSet(header);
    78 		printResultSeparator();
    79 
    80 		initColumnWidths(header.getColumnCount());
    81 
    82 		printTableIndent();
    83 		printTableBorder("╭");
    84 
    85 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    86 
    87 		for (ColumnDescriptor cd : columnDescriptors) {
    88 			// padding: make header cell at least same width as data cells in this column
    89 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    90 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    91 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    92 
    93 			if (!cd.isFirstColumn()) {
    94 				printTableBorder("┬");
    95 			}
    96 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    97 		}
    98 		printTableBorder("╮");
    99 		out.println();
   100 
   101 		for (ColumnDescriptor cd : columnDescriptors) {
   102 			if (cd.isFirstColumn()) {
   103 				printTableIndent();
   104 				printTableBorder("│ ");
   105 			} else {
   106 				printTableBorder(" │ ");
   107 			}
   108 			out.print(TerminalStyle.Bright, cd.getLabel());
   109 			out.print(HEADER_TYPE_PREFIX);
   110 			out.print(cd.getTypeName());
   111 			out.print(HEADER_TYPE_SUFFIX);
   112 			if (cd.isLastColumn()) {
   113 				printTableBorder(" │");
   114 			}
   115 		}
   116 		out.println();
   117 
   118 		printTableIndent();
   119 		printTableBorder("├");
   120 		for (int i = 1; i <= header.getColumnCount(); i++) {
   121 			if (i > 1) {
   122 				printTableBorder("┼");
   123 			}
   124 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   125 		}
   126 		printTableBorder("┤");
   127 		out.println();
   128 
   129 		out.flush();
   130 	}
   131 
   132 	/**
   133 	 * Must be called before
   134 	 * {@linkplain #updateColumnWidth(int, int)}
   135 	 * and {@linkplain #getColumnWidth(int)}
   136 	 * for each result set.
   137 	 *
   138 	 * @param columnCount number of columns in current result set
   139 	 */
   140 	protected void initColumnWidths(int columnCount) {
   141 		if (columnWidth == null) {
   142 			columnWidth = new int[columnCount];
   143 		}
   144 	}
   145 
   146 	protected void cleanColumnWidths() {
   147 		columnWidth = null;
   148 	}
   149 
   150 	@Override
   151 	public void writeColumnValue(Object value) {
   152 		super.writeColumnValue(value);
   153 		writeColumnValueInternal(value);
   154 	}
   155 
   156 	protected void writeColumnValueInternal(Object value) {
   157 
   158 		if (isCurrentColumnFirst()) {
   159 			printTableIndent();
   160 			printTableBorder("│ ");
   161 		} else {
   162 			printTableBorder(" │ ");
   163 		}
   164 
   165 		Functions.printValueWithWhitespaceReplaced(out, toString(value), TerminalColor.Cyan, TerminalColor.Red);
   166 
   167 		if (isCurrentColumnLast()) {
   168 			printTableBorder(" │");
   169 		}
   170 
   171 	}
   172 
   173 	protected int getColumnWidth(int columnNumber) {
   174 		return columnWidth[columnNumber - 1];
   175 	}
   176 
   177 	private void setColumnWidth(int columnNumber, int width) {
   178 		columnWidth[columnNumber - 1] = width;
   179 	}
   180 
   181 	protected void updateColumnWidth(int columnNumber, int width) {
   182 		int oldWidth = getColumnWidth(columnNumber);
   183 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   184 
   185 	}
   186 
   187 	protected String toString(Object value) {
   188 		final int width = getColumnWidth(getCurrentColumnsCount());
   189 		String result;
   190 		if (value instanceof Number || value instanceof Boolean) {
   191 			result = lpad(String.valueOf(value), width);
   192 		} else {
   193 			result = rpad(String.valueOf(value), width);
   194 		}
   195 		// ?	value = (boolean) value ? "✔" : "✗";
   196 
   197 		if (trimValues && result.length() > width) {
   198 			result = result.substring(0, width - 1) + "…";
   199 		}
   200 
   201 		return result;
   202 	}
   203 
   204 	@Override
   205 	public void writeEndRow() {
   206 		super.writeEndRow();
   207 		writeEndRowInternal();
   208 	}
   209 
   210 	public void writeEndRowInternal() {
   211 		out.println();
   212 		out.flush();
   213 	}
   214 
   215 	@Override
   216 	public void writeEndResultSet() {
   217 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   218 		super.writeEndResultSet();
   219 
   220 		printTableIndent();
   221 		printTableBorder("╰");
   222 		for (int i = 1; i <= columnCount; i++) {
   223 			if (i > 1) {
   224 				printTableBorder("┴");
   225 			}
   226 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   227 		}
   228 		printTableBorder("╯");
   229 		out.println();
   230 
   231 		cleanColumnWidths();
   232 
   233 		out.print(TerminalColor.Yellow, "Record count: ");
   234 		out.println(getCurrentRowCount());
   235 		out.bell();
   236 		out.flush();
   237 	}
   238 
   239 	@Override
   240 	public void writeUpdatesResult(int updatedRowsCount) {
   241 		super.writeUpdatesResult(updatedRowsCount);
   242 		printResultSeparator();
   243 		out.print(TerminalColor.Red, "Updated records: ");
   244 		out.println(updatedRowsCount);
   245 		out.bell();
   246 		out.flush();
   247 	}
   248 
   249 	@Override
   250 	public void writeEndDatabase() {
   251 		super.writeEndDatabase();
   252 		out.flush();
   253 	}
   254 
   255 	private void printResultSeparator() {
   256 		if (firstResult) {
   257 			firstResult = false;
   258 		} else {
   259 			out.println();
   260 		}
   261 	}
   262 
   263 	protected void printTableBorder(String border) {
   264 		if (asciiNostalgia) {
   265 			border = border.replaceAll("─", "-");
   266 			border = border.replaceAll("│", "|");
   267 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   268 		}
   269 
   270 		out.print(TerminalColor.Green, border);
   271 	}
   272 
   273 	protected void printTableIndent() {
   274 		out.print(" ");
   275 	}
   276 }