java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Sat, 04 Jan 2014 23:27:17 +0100
branchv_0
changeset 135 ef432015fdee
parent 124 9277b02a3b02
child 142 da1e38386d84
permissions -rw-r--r--
XHTML formatter: CSS and other improvements
     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 
    27 /**
    28  *
    29  * @author Ing. František Kučera (frantovo.cz)
    30  */
    31 public class TabularFormatter extends AbstractFormatter {
    32 
    33 	public static final String NAME = "tabular"; // bash-completion:formatter
    34 	private static final String HEADER_TYPE_PREFIX = " (";
    35 	private static final String HEADER_TYPE_SUFFIX = ")";
    36 	public static final String PROPERTY_ASCII = "ascii";
    37 	public static final String PROPERTY_COLORFUL = "color";
    38 	public static final String PROPERTY_TRIM = "trim";
    39 	protected ColorfulPrintWriter out;
    40 	private boolean firstResult = true;
    41 	private int[] columnWidth;
    42 	/**
    43 	 * use ASCII borders instead of unicode ones
    44 	 */
    45 	private final boolean asciiNostalgia;
    46 	/**
    47 	 * Trim values if they are longer than cell size
    48 	 */
    49 	private final boolean trimValues;
    50 
    51 	public TabularFormatter(FormatterContext formatterContext) {
    52 		super(formatterContext);
    53 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    54 		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
    55 		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
    56 		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
    57 	}
    58 
    59 	@Override
    60 	public void writeStartResultSet() {
    61 		super.writeStartResultSet();
    62 		printResultSeparator();
    63 	}
    64 
    65 	@Override
    66 	public void writeColumnsHeader(ColumnsHeader header) {
    67 		super.writeColumnsHeader(header);
    68 
    69 		initColumnWidths(header.getColumnCount());
    70 
    71 		printTableIndent();
    72 		printTableBorder("╭");
    73 
    74 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    75 
    76 		for (ColumnDescriptor cd : columnDescriptors) {
    77 			// padding: make header cell at least same width as data cells in this column
    78 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    79 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    80 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    81 
    82 			if (!cd.isFirstColumn()) {
    83 				printTableBorder("┬");
    84 			}
    85 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    86 		}
    87 		printTableBorder("╮");
    88 		out.println();
    89 
    90 		for (ColumnDescriptor cd : columnDescriptors) {
    91 			if (cd.isFirstColumn()) {
    92 				printTableIndent();
    93 				printTableBorder("│ ");
    94 			} else {
    95 				printTableBorder(" │ ");
    96 			}
    97 			out.print(TerminalStyle.Bright, cd.getLabel());
    98 			out.print(HEADER_TYPE_PREFIX);
    99 			out.print(cd.getTypeName());
   100 			out.print(HEADER_TYPE_SUFFIX);
   101 			if (cd.isLastColumn()) {
   102 				printTableBorder(" │");
   103 			}
   104 		}
   105 		out.println();
   106 
   107 		printTableIndent();
   108 		printTableBorder("├");
   109 		for (int i = 1; i <= header.getColumnCount(); i++) {
   110 			if (i > 1) {
   111 				printTableBorder("┼");
   112 			}
   113 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   114 		}
   115 		printTableBorder("┤");
   116 		out.println();
   117 
   118 		out.flush();
   119 	}
   120 
   121 	/**
   122 	 * Must be called before
   123 	 * {@linkplain #updateColumnWidth(int, int)}
   124 	 * and {@linkplain #getColumnWidth(int)}
   125 	 * for each result set.
   126 	 *
   127 	 * @param columnCount number of columns in current result set
   128 	 */
   129 	protected void initColumnWidths(int columnCount) {
   130 		if (columnWidth == null) {
   131 			columnWidth = new int[columnCount];
   132 		}
   133 	}
   134 
   135 	protected void cleanColumnWidths() {
   136 		columnWidth = null;
   137 	}
   138 
   139 	@Override
   140 	public void writeColumnValue(Object value) {
   141 		super.writeColumnValue(value);
   142 		writeColumnValueInternal(value);
   143 	}
   144 
   145 	protected void writeColumnValueInternal(Object value) {
   146 
   147 		if (isCurrentColumnFirst()) {
   148 			printTableIndent();
   149 			printTableBorder("│ ");
   150 		} else {
   151 			printTableBorder(" │ ");
   152 		}
   153 
   154 		String valueString = toString(value);
   155 		printValueWithNewLinesReplaced(valueString);
   156 
   157 		if (isCurrentColumnLast()) {
   158 			printTableBorder(" │");
   159 		}
   160 
   161 	}
   162 
   163 	protected int getColumnWidth(int columnNumber) {
   164 		return columnWidth[columnNumber - 1];
   165 	}
   166 
   167 	private void setColumnWidth(int columnNumber, int width) {
   168 		columnWidth[columnNumber - 1] = width;
   169 	}
   170 
   171 	protected void updateColumnWidth(int columnNumber, int width) {
   172 		int oldWidth = getColumnWidth(columnNumber);
   173 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   174 
   175 	}
   176 
   177 	protected String toString(Object value) {
   178 		final int width = getColumnWidth(getCurrentColumnsCount());
   179 		String result;
   180 		if (value instanceof Number || value instanceof Boolean) {
   181 			result = lpad(String.valueOf(value), width);
   182 		} else {
   183 			result = rpad(String.valueOf(value), width);
   184 		}
   185 		// ?	value = (boolean) value ? "✔" : "✗";
   186 
   187 		if (trimValues && result.length() > width) {
   188 			result = result.substring(0, width - 1) + "…";
   189 		}
   190 
   191 		return result;
   192 	}
   193 
   194 	@Override
   195 	public void writeEndRow() {
   196 		super.writeEndRow();
   197 		writeEndRowInternal();
   198 	}
   199 
   200 	public void writeEndRowInternal() {
   201 		out.println();
   202 		out.flush();
   203 	}
   204 
   205 	@Override
   206 	public void writeEndResultSet() {
   207 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   208 		super.writeEndResultSet();
   209 
   210 		printTableIndent();
   211 		printTableBorder("╰");
   212 		for (int i = 1; i <= columnCount; i++) {
   213 			if (i > 1) {
   214 				printTableBorder("┴");
   215 			}
   216 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   217 		}
   218 		printTableBorder("╯");
   219 		out.println();
   220 
   221 		cleanColumnWidths();
   222 
   223 		out.print(TerminalColor.Yellow, "Record count: ");
   224 		out.println(getCurrentRowCount());
   225 		out.bell();
   226 		out.flush();
   227 	}
   228 
   229 	@Override
   230 	public void writeStartUpdatesResult() {
   231 		super.writeStartUpdatesResult();
   232 		printResultSeparator();
   233 	}
   234 
   235 	@Override
   236 	public void writeUpdatedRowsCount(int updatedRowsCount) {
   237 		super.writeUpdatedRowsCount(updatedRowsCount);
   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 printValueWithNewLinesReplaced(String valueString) {
   273 		String[] valueParts = valueString.split("\n");
   274 		for (int i = 0; i < valueParts.length; i++) {
   275 			String valuePart = valueParts[i];
   276 			// TODO: replace also TABs
   277 			out.print(TerminalColor.Cyan, valuePart);
   278 			if (i < valueParts.length - 1) {
   279 				out.print(TerminalColor.Red, "↲");
   280 			}
   281 		}
   282 	}
   283 }