java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 15 Aug 2015 10:34:18 +0200
branchv_0
changeset 207 2bba68ef47c1
parent 206 e2f24eea8543
child 218 8e38caf43ca8
permissions -rw-r--r--
property annotations: default values
     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 static info.globalcode.sql.dk.Functions.lpad;
    23 import static info.globalcode.sql.dk.Functions.rpad;
    24 import static info.globalcode.sql.dk.Functions.repeat;
    25 import info.globalcode.sql.dk.configuration.PropertyDeclaration;
    26 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL;
    27 import static info.globalcode.sql.dk.formatting.CommonProperties.COLORFUL_DESCRIPTION;
    28 import java.util.List;
    29 import java.util.regex.Matcher;
    30 import java.util.regex.Pattern;
    31 
    32 /**
    33  * <p>
    34  * Prints human-readable output – tables of result sets and text messages with update counts.
    35  * </p>
    36  *
    37  * <p>
    38  * Longer values might break the table – overflow the cells – see alternative tabular formatters
    39  * and the {@linkplain #PROPERTY_TRIM} property.
    40  * </p>
    41  *
    42  * @author Ing. František Kučera (frantovo.cz)
    43  * @see TabularPrefetchingFormatter
    44  * @see TabularWrappingFormatter
    45  */
    46 @PropertyDeclaration(name = COLORFUL, defaultValue = "true", type = Boolean.class, description = COLORFUL_DESCRIPTION)
    47 @PropertyDeclaration(name = TabularFormatter.PROPERTY_ASCII, defaultValue = "false", type = Boolean.class, description = "whether to use ASCII table borders instead of unicode ones")
    48 @PropertyDeclaration(name = TabularFormatter.PROPERTY_TRIM, defaultValue = "false", type = Boolean.class, description = "whether to trim the values to fit the column width")
    49 public class TabularFormatter extends AbstractFormatter {
    50 
    51 	public static final String NAME = "tabular"; // bash-completion:formatter
    52 	private static final String HEADER_TYPE_PREFIX = " (";
    53 	private static final String HEADER_TYPE_SUFFIX = ")";
    54 	public static final String PROPERTY_ASCII = "ascii";
    55 	public static final String PROPERTY_TRIM = "trim";
    56 	private static final String NBSP = " ";
    57 	private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\r|\\t|" + NBSP);
    58 	protected ColorfulPrintWriter out;
    59 	private boolean firstResult = true;
    60 	private int[] columnWidth;
    61 	/**
    62 	 * use ASCII borders instead of unicode ones
    63 	 */
    64 	private final boolean asciiNostalgia;
    65 	/**
    66 	 * Trim values if they are longer than cell size
    67 	 */
    68 	private final boolean trimValues;
    69 
    70 	public TabularFormatter(FormatterContext formatterContext) {
    71 		super(formatterContext);
    72 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    73 		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
    74 		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
    75 		out.setColorful(formatterContext.getProperties().getBoolean(COLORFUL, true));
    76 	}
    77 
    78 	@Override
    79 	public void writeStartResultSet(ColumnsHeader header) {
    80 		super.writeStartResultSet(header);
    81 		printResultSeparator();
    82 
    83 		initColumnWidths(header.getColumnCount());
    84 
    85 		printTableIndent();
    86 		printTableBorder("╭");
    87 
    88 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    89 
    90 		for (ColumnDescriptor cd : columnDescriptors) {
    91 			// padding: make header cell at least same width as data cells in this column
    92 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    93 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    94 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    95 
    96 			if (!cd.isFirstColumn()) {
    97 				printTableBorder("┬");
    98 			}
    99 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
   100 		}
   101 		printTableBorder("╮");
   102 		out.println();
   103 
   104 		for (ColumnDescriptor cd : columnDescriptors) {
   105 			if (cd.isFirstColumn()) {
   106 				printTableIndent();
   107 				printTableBorder("│ ");
   108 			} else {
   109 				printTableBorder(" │ ");
   110 			}
   111 			out.print(TerminalStyle.Bright, cd.getLabel());
   112 			out.print(HEADER_TYPE_PREFIX);
   113 			out.print(cd.getTypeName());
   114 			out.print(HEADER_TYPE_SUFFIX);
   115 			if (cd.isLastColumn()) {
   116 				printTableBorder(" │");
   117 			}
   118 		}
   119 		out.println();
   120 
   121 		printTableIndent();
   122 		printTableBorder("├");
   123 		for (int i = 1; i <= header.getColumnCount(); i++) {
   124 			if (i > 1) {
   125 				printTableBorder("┼");
   126 			}
   127 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   128 		}
   129 		printTableBorder("┤");
   130 		out.println();
   131 
   132 		out.flush();
   133 	}
   134 
   135 	/**
   136 	 * Must be called before
   137 	 * {@linkplain #updateColumnWidth(int, int)}
   138 	 * and {@linkplain #getColumnWidth(int)}
   139 	 * for each result set.
   140 	 *
   141 	 * @param columnCount number of columns in current result set
   142 	 */
   143 	protected void initColumnWidths(int columnCount) {
   144 		if (columnWidth == null) {
   145 			columnWidth = new int[columnCount];
   146 		}
   147 	}
   148 
   149 	protected void cleanColumnWidths() {
   150 		columnWidth = null;
   151 	}
   152 
   153 	@Override
   154 	public void writeColumnValue(Object value) {
   155 		super.writeColumnValue(value);
   156 		writeColumnValueInternal(value);
   157 	}
   158 
   159 	protected void writeColumnValueInternal(Object value) {
   160 
   161 		if (isCurrentColumnFirst()) {
   162 			printTableIndent();
   163 			printTableBorder("│ ");
   164 		} else {
   165 			printTableBorder(" │ ");
   166 		}
   167 
   168 		String valueString = toString(value);
   169 		printValueWithWhitespaceReplaced(valueString);
   170 
   171 		if (isCurrentColumnLast()) {
   172 			printTableBorder(" │");
   173 		}
   174 
   175 	}
   176 
   177 	protected int getColumnWidth(int columnNumber) {
   178 		return columnWidth[columnNumber - 1];
   179 	}
   180 
   181 	private void setColumnWidth(int columnNumber, int width) {
   182 		columnWidth[columnNumber - 1] = width;
   183 	}
   184 
   185 	protected void updateColumnWidth(int columnNumber, int width) {
   186 		int oldWidth = getColumnWidth(columnNumber);
   187 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   188 
   189 	}
   190 
   191 	protected String toString(Object value) {
   192 		final int width = getColumnWidth(getCurrentColumnsCount());
   193 		String result;
   194 		if (value instanceof Number || value instanceof Boolean) {
   195 			result = lpad(String.valueOf(value), width);
   196 		} else {
   197 			result = rpad(String.valueOf(value), width);
   198 		}
   199 		// ?	value = (boolean) value ? "✔" : "✗";
   200 
   201 		if (trimValues && result.length() > width) {
   202 			result = result.substring(0, width - 1) + "…";
   203 		}
   204 
   205 		return result;
   206 	}
   207 
   208 	@Override
   209 	public void writeEndRow() {
   210 		super.writeEndRow();
   211 		writeEndRowInternal();
   212 	}
   213 
   214 	public void writeEndRowInternal() {
   215 		out.println();
   216 		out.flush();
   217 	}
   218 
   219 	@Override
   220 	public void writeEndResultSet() {
   221 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   222 		super.writeEndResultSet();
   223 
   224 		printTableIndent();
   225 		printTableBorder("╰");
   226 		for (int i = 1; i <= columnCount; i++) {
   227 			if (i > 1) {
   228 				printTableBorder("┴");
   229 			}
   230 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   231 		}
   232 		printTableBorder("╯");
   233 		out.println();
   234 
   235 		cleanColumnWidths();
   236 
   237 		out.print(TerminalColor.Yellow, "Record count: ");
   238 		out.println(getCurrentRowCount());
   239 		out.bell();
   240 		out.flush();
   241 	}
   242 
   243 	@Override
   244 	public void writeUpdatesResult(int updatedRowsCount) {
   245 		super.writeUpdatesResult(updatedRowsCount);
   246 		printResultSeparator();
   247 		out.print(TerminalColor.Red, "Updated records: ");
   248 		out.println(updatedRowsCount);
   249 		out.bell();
   250 		out.flush();
   251 	}
   252 
   253 	@Override
   254 	public void writeEndDatabase() {
   255 		super.writeEndDatabase();
   256 		out.flush();
   257 	}
   258 
   259 	private void printResultSeparator() {
   260 		if (firstResult) {
   261 			firstResult = false;
   262 		} else {
   263 			out.println();
   264 		}
   265 	}
   266 
   267 	protected void printTableBorder(String border) {
   268 		if (asciiNostalgia) {
   269 			border = border.replaceAll("─", "-");
   270 			border = border.replaceAll("│", "|");
   271 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   272 		}
   273 
   274 		out.print(TerminalColor.Green, border);
   275 	}
   276 
   277 	protected void printTableIndent() {
   278 		out.print(" ");
   279 	}
   280 
   281 	protected void printValueWithWhitespaceReplaced(String valueString) {
   282 
   283 		Matcher m = whitespaceToReplace.matcher(valueString);
   284 
   285 		int start = 0;
   286 		while (m.find(start)) {
   287 
   288 			out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
   289 
   290 			switch (m.group()) {
   291 				case "\n":
   292 					out.print(TerminalColor.Red, "↲");
   293 					break;
   294 				case "\r":
   295 					out.print(TerminalColor.Red, "⏎");
   296 					break;
   297 				case "\t":
   298 					out.print(TerminalColor.Red, "↹");
   299 					break;
   300 				case NBSP:
   301 					out.print(TerminalColor.Red, "⎵");
   302 					break;
   303 				default:
   304 					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
   305 			}
   306 
   307 			start = m.end();
   308 		}
   309 
   310 		out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));
   311 	}
   312 }