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