java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sun, 30 Aug 2015 02:28:15 +0200
branchv_0
changeset 224 36db9fd27436
parent 219 3b1733fb3793
child 227 0094319a274a
permissions -rw-r--r--
BarChartFormatter: first version
     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 		printValueWithWhitespaceReplaced(toString(value));
   166 
   167 		if (isCurrentColumnLast()) {
   168 			printTableBorder(" │");
   169 		}
   170 
   171 	}
   172 
   173 	protected void printValueWithWhitespaceReplaced(String text) {
   174 		Functions.printValueWithWhitespaceReplaced(out, text, TerminalColor.Cyan, TerminalColor.Red);
   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 	/**
   282 	 * @return whether should print only ASCII characters instead of unlimited Unicode.
   283 	 */
   284 	protected boolean isAsciiNostalgia() {
   285 		return asciiNostalgia;
   286 	}
   287 }