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