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