java/sql-dk/src/info/globalcode/sql/dk/formatting/TabularFormatter.java
author František Kučera <franta-hg@frantovo.cz>
Mon, 30 Dec 2013 23:46:41 +0100
branchv_0
changeset 103 5410b6afc839
parent 98 4d420f8b3320
child 104 245f1b88a3e6
permissions -rw-r--r--
TabularFormatter: values with line ends will not break our tables
     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 	private ColorfulPrintWriter out;
    37 	private boolean firstResult = true;
    38 	private int[] columnWidth;
    39 	/**
    40 	 * use ASCII borders instead of unicode ones
    41 	 */
    42 	private final boolean asciiNostalgia = false;
    43 	/**
    44 	 * Trim values if they are longer than cell size
    45 	 */
    46 	private final boolean trimValues = false;
    47 
    48 	public TabularFormatter(FormatterContext formatterContext) {
    49 		super(formatterContext);
    50 		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
    51 	}
    52 
    53 	@Override
    54 	public void writeStartResultSet() {
    55 		super.writeStartResultSet();
    56 		printResultSeparator();
    57 	}
    58 
    59 	@Override
    60 	public void writeColumnsHeader(ColumnsHeader header) {
    61 		super.writeColumnsHeader(header);
    62 
    63 		initColumnWidths(header.getColumnCount());
    64 
    65 		printTableIndent();
    66 		printTableBorder("╭");
    67 
    68 		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
    69 
    70 		for (ColumnDescriptor cd : columnDescriptors) {
    71 			// padding: make header cell at least same width as data cells in this column
    72 			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
    73 			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
    74 			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
    75 
    76 			if (!cd.isFirstColumn()) {
    77 				printTableBorder("┬");
    78 			}
    79 			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
    80 		}
    81 		printTableBorder("╮");
    82 		out.println();
    83 
    84 		for (ColumnDescriptor cd : columnDescriptors) {
    85 			if (cd.isFirstColumn()) {
    86 				printTableIndent();
    87 				printTableBorder("│ ");
    88 			} else {
    89 				printTableBorder(" │ ");
    90 			}
    91 			out.print(TerminalStyle.Bright, cd.getLabel());
    92 			out.print(HEADER_TYPE_PREFIX);
    93 			out.print(cd.getTypeName());
    94 			out.print(HEADER_TYPE_SUFFIX);
    95 			if (cd.isLastColumn()) {
    96 				printTableBorder(" │");
    97 			}
    98 		}
    99 		out.println();
   100 
   101 		printTableIndent();
   102 		printTableBorder("├");
   103 		for (int i = 1; i <= header.getColumnCount(); i++) {
   104 			if (i > 1) {
   105 				printTableBorder("┼");
   106 			}
   107 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   108 		}
   109 		printTableBorder("┤");
   110 		out.println();
   111 
   112 		out.flush();
   113 	}
   114 
   115 	/**
   116 	 * Must be called before
   117 	 * {@linkplain #updateColumnWidth(int, int)}
   118 	 * and {@linkplain #getColumnWidth(int)}
   119 	 * for each result set.
   120 	 *
   121 	 * @param columnCount number of columns in current result set
   122 	 */
   123 	protected void initColumnWidths(int columnCount) {
   124 		if (columnWidth == null) {
   125 			columnWidth = new int[columnCount];
   126 		}
   127 	}
   128 
   129 	protected void cleanColumnWidths() {
   130 		columnWidth = null;
   131 	}
   132 
   133 	@Override
   134 	public void writeColumnValue(Object value) {
   135 		super.writeColumnValue(value);
   136 
   137 		if (isCurrentColumnFirst()) {
   138 			printTableIndent();
   139 			printTableBorder("│ ");
   140 		} else {
   141 			printTableBorder(" │ ");
   142 		}
   143 
   144 		String[] valueParts = toString(value).split("\n");
   145 		for (int i = 0; i < valueParts.length; i++) {
   146 			String valuePart = valueParts[i];
   147 			out.print(TerminalColor.Cyan, valuePart);
   148 			if (i < valueParts.length - 1) {
   149 				out.print(TerminalColor.Red, "↲");
   150 			}
   151 		}
   152 
   153 		if (isCurrentColumnLast()) {
   154 			printTableBorder(" │");
   155 		}
   156 
   157 	}
   158 
   159 	private int getColumnWidth(int columnNumber) {
   160 		return columnWidth[columnNumber - 1];
   161 	}
   162 
   163 	private void setColumnWidth(int columnNumber, int width) {
   164 		columnWidth[columnNumber - 1] = width;
   165 	}
   166 
   167 	protected void updateColumnWidth(int columnNumber, int width) {
   168 		int oldWidth = getColumnWidth(columnNumber);
   169 		setColumnWidth(columnNumber, Math.max(width, oldWidth));
   170 
   171 	}
   172 
   173 	protected String toString(Object value) {
   174 		final int width = getColumnWidth(getCurrentColumnsCount());
   175 		String result;
   176 		if (value instanceof Number || value instanceof Boolean) {
   177 			result = lpad(String.valueOf(value), width);
   178 		} else {
   179 			result = rpad(String.valueOf(value), width);
   180 		}
   181 		// ?	value = (boolean) value ? "✔" : "✗";
   182 
   183 		if (trimValues && result.length() > width) {
   184 			result = result.substring(0, width - 1) + "…";
   185 		}
   186 
   187 		return result;
   188 	}
   189 
   190 	@Override
   191 	public void writeEndRow() {
   192 		super.writeEndRow();
   193 		out.println();
   194 		out.flush();
   195 	}
   196 
   197 	@Override
   198 	public void writeEndResultSet() {
   199 		int columnCount = getCurrentColumnsHeader().getColumnCount();
   200 		super.writeEndResultSet();
   201 
   202 		printTableIndent();
   203 		printTableBorder("╰");
   204 		for (int i = 1; i <= columnCount; i++) {
   205 			if (i > 1) {
   206 				printTableBorder("┴");
   207 			}
   208 			printTableBorder(repeat('─', getColumnWidth(i) + 2));
   209 		}
   210 		printTableBorder("╯");
   211 		out.println();
   212 
   213 		cleanColumnWidths();
   214 
   215 		out.print(TerminalColor.Yellow, "Record count: ");
   216 		out.println(getCurrentRowCount());
   217 		out.bell();
   218 		out.flush();
   219 	}
   220 
   221 	@Override
   222 	public void writeStartUpdatesResult() {
   223 		super.writeStartUpdatesResult();
   224 		printResultSeparator();
   225 	}
   226 
   227 	@Override
   228 	public void writeUpdatedRowsCount(int updatedRowsCount) {
   229 		super.writeUpdatedRowsCount(updatedRowsCount);
   230 		out.print(TerminalColor.Red, "Updated records: ");
   231 		out.println(updatedRowsCount);
   232 		out.bell();
   233 		out.flush();
   234 	}
   235 
   236 	@Override
   237 	public void writeEndDatabase() {
   238 		super.writeEndDatabase();
   239 		out.flush();
   240 	}
   241 
   242 	private void printResultSeparator() {
   243 		if (firstResult) {
   244 			firstResult = false;
   245 		} else {
   246 			out.println();
   247 		}
   248 	}
   249 
   250 	private void printTableBorder(String border) {
   251 		if (asciiNostalgia) {
   252 			border = border.replaceAll("─", "-");
   253 			border = border.replaceAll("│", "|");
   254 			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
   255 		}
   256 
   257 		out.print(TerminalColor.Green, border);
   258 	}
   259 
   260 	private void printTableIndent() {
   261 		out.print(" ");
   262 	}
   263 }