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)
franta-hg@32
     1
/**
franta-hg@32
     2
 * SQL-DK
franta-hg@32
     3
 * Copyright © 2013 František Kučera (frantovo.cz)
franta-hg@32
     4
 *
franta-hg@32
     5
 * This program is free software: you can redistribute it and/or modify
franta-hg@32
     6
 * it under the terms of the GNU General Public License as published by
franta-hg@32
     7
 * the Free Software Foundation, either version 3 of the License, or
franta-hg@32
     8
 * (at your option) any later version.
franta-hg@32
     9
 *
franta-hg@32
    10
 * This program is distributed in the hope that it will be useful,
franta-hg@32
    11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
franta-hg@32
    12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
franta-hg@32
    13
 * GNU General Public License for more details.
franta-hg@32
    14
 *
franta-hg@32
    15
 * You should have received a copy of the GNU General Public License
franta-hg@32
    16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
franta-hg@32
    17
 */
franta-hg@32
    18
package info.globalcode.sql.dk.formatting;
franta-hg@32
    19
franta-hg@34
    20
import info.globalcode.sql.dk.ColorfulPrintWriter;
franta-hg@37
    21
import static info.globalcode.sql.dk.ColorfulPrintWriter.*;
franta-hg@39
    22
import static info.globalcode.sql.dk.Functions.lpad;
franta-hg@39
    23
import static info.globalcode.sql.dk.Functions.rpad;
franta-hg@40
    24
import static info.globalcode.sql.dk.Functions.repeat;
franta-hg@88
    25
import java.util.List;
franta-hg@169
    26
import java.util.regex.Matcher;
franta-hg@169
    27
import java.util.regex.Pattern;
franta-hg@34
    28
franta-hg@32
    29
/**
franta-hg@155
    30
 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
franta-hg@155
    31
 *
franta-hg@155
    32
 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
franta-hg@155
    33
 * and the {@linkplain #PROPERTY_TRIM} property.</p>
franta-hg@32
    34
 *
franta-hg@32
    35
 * @author Ing. František Kučera (frantovo.cz)
franta-hg@155
    36
 * @see TabularPrefetchingFormatter
franta-hg@155
    37
 * @see TabularWrappingFormatter
franta-hg@32
    38
 */
franta-hg@32
    39
public class TabularFormatter extends AbstractFormatter {
franta-hg@32
    40
franta-hg@79
    41
	public static final String NAME = "tabular"; // bash-completion:formatter
franta-hg@39
    42
	private static final String HEADER_TYPE_PREFIX = " (";
franta-hg@39
    43
	private static final String HEADER_TYPE_SUFFIX = ")";
franta-hg@104
    44
	public static final String PROPERTY_ASCII = "ascii";
franta-hg@104
    45
	public static final String PROPERTY_COLORFUL = "color";
franta-hg@104
    46
	public static final String PROPERTY_TRIM = "trim";
franta-hg@170
    47
	private static final String NBSP = " ";
franta-hg@170
    48
	private static final Pattern whitespaceToReplace = Pattern.compile("\\n|\\t|" + NBSP);
franta-hg@123
    49
	protected ColorfulPrintWriter out;
franta-hg@37
    50
	private boolean firstResult = true;
franta-hg@39
    51
	private int[] columnWidth;
franta-hg@87
    52
	/**
franta-hg@87
    53
	 * use ASCII borders instead of unicode ones
franta-hg@87
    54
	 */
franta-hg@104
    55
	private final boolean asciiNostalgia;
franta-hg@87
    56
	/**
franta-hg@87
    57
	 * Trim values if they are longer than cell size
franta-hg@87
    58
	 */
franta-hg@104
    59
	private final boolean trimValues;
franta-hg@32
    60
franta-hg@32
    61
	public TabularFormatter(FormatterContext formatterContext) {
franta-hg@32
    62
		super(formatterContext);
franta-hg@34
    63
		out = new ColorfulPrintWriter(formatterContext.getOutputStream());
franta-hg@104
    64
		asciiNostalgia = formatterContext.getProperties().getBoolean(PROPERTY_ASCII, false);
franta-hg@104
    65
		trimValues = formatterContext.getProperties().getBoolean(PROPERTY_TRIM, false);
franta-hg@104
    66
		out.setColorful(formatterContext.getProperties().getBoolean(PROPERTY_COLORFUL, true));
franta-hg@34
    67
	}
franta-hg@34
    68
franta-hg@34
    69
	@Override
franta-hg@142
    70
	public void writeStartResultSet(ColumnsHeader header) {
franta-hg@142
    71
		super.writeStartResultSet(header);
franta-hg@37
    72
		printResultSeparator();
franta-hg@37
    73
franta-hg@88
    74
		initColumnWidths(header.getColumnCount());
franta-hg@39
    75
franta-hg@40
    76
		printTableIndent();
franta-hg@40
    77
		printTableBorder("╭");
franta-hg@88
    78
franta-hg@88
    79
		List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
franta-hg@88
    80
franta-hg@88
    81
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@88
    82
			// padding: make header cell at least same width as data cells in this column
franta-hg@88
    83
			int typeWidth = cd.getTypeName().length() + HEADER_TYPE_PREFIX.length() + HEADER_TYPE_SUFFIX.length();
franta-hg@88
    84
			cd.setLabel(rpad(cd.getLabel(), getColumnWidth(cd.getColumnNumber()) - typeWidth));
franta-hg@88
    85
			updateColumnWidth(cd.getColumnNumber(), cd.getLabel().length() + typeWidth);
franta-hg@88
    86
franta-hg@40
    87
			if (!cd.isFirstColumn()) {
franta-hg@40
    88
				printTableBorder("┬");
franta-hg@40
    89
			}
franta-hg@40
    90
			printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
franta-hg@40
    91
		}
franta-hg@40
    92
		printTableBorder("╮");
franta-hg@40
    93
		out.println();
franta-hg@40
    94
franta-hg@88
    95
		for (ColumnDescriptor cd : columnDescriptors) {
franta-hg@40
    96
			if (cd.isFirstColumn()) {
franta-hg@40
    97
				printTableIndent();
franta-hg@40
    98
				printTableBorder("│ ");
franta-hg@40
    99
			} else {
franta-hg@40
   100
				printTableBorder(" │ ");
franta-hg@40
   101
			}
franta-hg@37
   102
			out.print(TerminalStyle.Bright, cd.getLabel());
franta-hg@39
   103
			out.print(HEADER_TYPE_PREFIX);
franta-hg@37
   104
			out.print(cd.getTypeName());
franta-hg@39
   105
			out.print(HEADER_TYPE_SUFFIX);
franta-hg@40
   106
			if (cd.isLastColumn()) {
franta-hg@40
   107
				printTableBorder(" │");
franta-hg@37
   108
			}
franta-hg@37
   109
		}
franta-hg@37
   110
		out.println();
franta-hg@40
   111
franta-hg@40
   112
		printTableIndent();
franta-hg@40
   113
		printTableBorder("├");
franta-hg@40
   114
		for (int i = 1; i <= header.getColumnCount(); i++) {
franta-hg@40
   115
			if (i > 1) {
franta-hg@40
   116
				printTableBorder("┼");
franta-hg@40
   117
			}
franta-hg@40
   118
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   119
		}
franta-hg@40
   120
		printTableBorder("┤");
franta-hg@40
   121
		out.println();
franta-hg@40
   122
franta-hg@37
   123
		out.flush();
franta-hg@37
   124
	}
franta-hg@37
   125
franta-hg@88
   126
	/**
franta-hg@88
   127
	 * Must be called before
franta-hg@88
   128
	 * {@linkplain #updateColumnWidth(int, int)}
franta-hg@88
   129
	 * and {@linkplain #getColumnWidth(int)}
franta-hg@88
   130
	 * for each result set.
franta-hg@88
   131
	 *
franta-hg@88
   132
	 * @param columnCount number of columns in current result set
franta-hg@88
   133
	 */
franta-hg@88
   134
	protected void initColumnWidths(int columnCount) {
franta-hg@88
   135
		if (columnWidth == null) {
franta-hg@88
   136
			columnWidth = new int[columnCount];
franta-hg@88
   137
		}
franta-hg@88
   138
	}
franta-hg@88
   139
franta-hg@88
   140
	protected void cleanColumnWidths() {
franta-hg@88
   141
		columnWidth = null;
franta-hg@88
   142
	}
franta-hg@88
   143
franta-hg@37
   144
	@Override
franta-hg@34
   145
	public void writeColumnValue(Object value) {
franta-hg@34
   146
		super.writeColumnValue(value);
franta-hg@123
   147
		writeColumnValueInternal(value);
franta-hg@123
   148
	}
franta-hg@123
   149
franta-hg@123
   150
	protected void writeColumnValueInternal(Object value) {
franta-hg@34
   151
franta-hg@40
   152
		if (isCurrentColumnFirst()) {
franta-hg@40
   153
			printTableIndent();
franta-hg@40
   154
			printTableBorder("│ ");
franta-hg@40
   155
		} else {
franta-hg@90
   156
			printTableBorder(" │ ");
franta-hg@34
   157
		}
franta-hg@37
   158
franta-hg@123
   159
		String valueString = toString(value);
franta-hg@169
   160
		printValueWithWhitespaceReplaced(valueString);
franta-hg@40
   161
franta-hg@40
   162
		if (isCurrentColumnLast()) {
franta-hg@90
   163
			printTableBorder(" │");
franta-hg@40
   164
		}
franta-hg@40
   165
franta-hg@39
   166
	}
franta-hg@39
   167
franta-hg@123
   168
	protected int getColumnWidth(int columnNumber) {
franta-hg@39
   169
		return columnWidth[columnNumber - 1];
franta-hg@39
   170
	}
franta-hg@39
   171
franta-hg@39
   172
	private void setColumnWidth(int columnNumber, int width) {
franta-hg@39
   173
		columnWidth[columnNumber - 1] = width;
franta-hg@39
   174
	}
franta-hg@39
   175
franta-hg@88
   176
	protected void updateColumnWidth(int columnNumber, int width) {
franta-hg@39
   177
		int oldWidth = getColumnWidth(columnNumber);
franta-hg@39
   178
		setColumnWidth(columnNumber, Math.max(width, oldWidth));
franta-hg@39
   179
franta-hg@39
   180
	}
franta-hg@39
   181
franta-hg@39
   182
	protected String toString(Object value) {
franta-hg@39
   183
		final int width = getColumnWidth(getCurrentColumnsCount());
franta-hg@87
   184
		String result;
franta-hg@43
   185
		if (value instanceof Number || value instanceof Boolean) {
franta-hg@98
   186
			result = lpad(String.valueOf(value), width);
franta-hg@39
   187
		} else {
franta-hg@98
   188
			result = rpad(String.valueOf(value), width);
franta-hg@39
   189
		}
franta-hg@40
   190
		// ?	value = (boolean) value ? "✔" : "✗";
franta-hg@87
   191
franta-hg@87
   192
		if (trimValues && result.length() > width) {
franta-hg@87
   193
			result = result.substring(0, width - 1) + "…";
franta-hg@87
   194
		}
franta-hg@87
   195
franta-hg@87
   196
		return result;
franta-hg@34
   197
	}
franta-hg@34
   198
franta-hg@34
   199
	@Override
franta-hg@34
   200
	public void writeEndRow() {
franta-hg@34
   201
		super.writeEndRow();
franta-hg@123
   202
		writeEndRowInternal();
franta-hg@123
   203
	}
franta-hg@123
   204
franta-hg@123
   205
	public void writeEndRowInternal() {
franta-hg@34
   206
		out.println();
franta-hg@34
   207
		out.flush();
franta-hg@32
   208
	}
franta-hg@37
   209
franta-hg@37
   210
	@Override
franta-hg@37
   211
	public void writeEndResultSet() {
franta-hg@40
   212
		int columnCount = getCurrentColumnsHeader().getColumnCount();
franta-hg@37
   213
		super.writeEndResultSet();
franta-hg@40
   214
franta-hg@40
   215
		printTableIndent();
franta-hg@40
   216
		printTableBorder("╰");
franta-hg@40
   217
		for (int i = 1; i <= columnCount; i++) {
franta-hg@40
   218
			if (i > 1) {
franta-hg@40
   219
				printTableBorder("┴");
franta-hg@40
   220
			}
franta-hg@40
   221
			printTableBorder(repeat('─', getColumnWidth(i) + 2));
franta-hg@40
   222
		}
franta-hg@40
   223
		printTableBorder("╯");
franta-hg@40
   224
		out.println();
franta-hg@40
   225
franta-hg@88
   226
		cleanColumnWidths();
franta-hg@40
   227
franta-hg@37
   228
		out.print(TerminalColor.Yellow, "Record count: ");
franta-hg@37
   229
		out.println(getCurrentRowCount());
franta-hg@40
   230
		out.bell();
franta-hg@37
   231
		out.flush();
franta-hg@37
   232
	}
franta-hg@37
   233
franta-hg@37
   234
	@Override
franta-hg@142
   235
	public void writeUpdatesResult(int updatedRowsCount) {
franta-hg@142
   236
		super.writeUpdatesResult(updatedRowsCount);
franta-hg@37
   237
		printResultSeparator();
franta-hg@37
   238
		out.print(TerminalColor.Red, "Updated records: ");
franta-hg@37
   239
		out.println(updatedRowsCount);
franta-hg@40
   240
		out.bell();
franta-hg@37
   241
		out.flush();
franta-hg@37
   242
	}
franta-hg@37
   243
franta-hg@37
   244
	@Override
franta-hg@37
   245
	public void writeEndDatabase() {
franta-hg@37
   246
		super.writeEndDatabase();
franta-hg@37
   247
		out.flush();
franta-hg@37
   248
	}
franta-hg@37
   249
franta-hg@37
   250
	private void printResultSeparator() {
franta-hg@37
   251
		if (firstResult) {
franta-hg@37
   252
			firstResult = false;
franta-hg@37
   253
		} else {
franta-hg@37
   254
			out.println();
franta-hg@37
   255
		}
franta-hg@37
   256
	}
franta-hg@40
   257
franta-hg@123
   258
	protected void printTableBorder(String border) {
franta-hg@76
   259
		if (asciiNostalgia) {
franta-hg@76
   260
			border = border.replaceAll("─", "-");
franta-hg@76
   261
			border = border.replaceAll("│", "|");
franta-hg@76
   262
			border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
franta-hg@76
   263
		}
franta-hg@87
   264
franta-hg@40
   265
		out.print(TerminalColor.Green, border);
franta-hg@40
   266
	}
franta-hg@40
   267
franta-hg@123
   268
	protected void printTableIndent() {
franta-hg@40
   269
		out.print(" ");
franta-hg@40
   270
	}
franta-hg@123
   271
franta-hg@169
   272
	protected void printValueWithWhitespaceReplaced(String valueString) {
franta-hg@169
   273
franta-hg@169
   274
		Matcher m = whitespaceToReplace.matcher(valueString);
franta-hg@169
   275
franta-hg@169
   276
		int start = 0;
franta-hg@169
   277
		while (m.find(start)) {
franta-hg@169
   278
franta-hg@169
   279
			out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
franta-hg@169
   280
franta-hg@169
   281
			switch (m.group()) {
franta-hg@169
   282
				case "\n":
franta-hg@169
   283
					out.print(TerminalColor.Red, "↲");
franta-hg@169
   284
					break;
franta-hg@169
   285
				case "\t":
franta-hg@169
   286
					out.print(TerminalColor.Red, "↹");
franta-hg@169
   287
					break;
franta-hg@170
   288
				case NBSP:
franta-hg@170
   289
					out.print(TerminalColor.Red, "⎵");
franta-hg@170
   290
					break;
franta-hg@169
   291
				default:
franta-hg@169
   292
					throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
franta-hg@123
   293
			}
franta-hg@169
   294
franta-hg@169
   295
			start = m.end();
franta-hg@123
   296
		}
franta-hg@167
   297
franta-hg@169
   298
		out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));
franta-hg@123
   299
	}
franta-hg@32
   300
}