Tabular: replace also Non-breaking space with colored symbol (like newlines and TABs)
3 * Copyright © 2013 František Kučera (frantovo.cz)
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.
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.
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/>.
18 package info.globalcode.sql.dk.formatting;
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;
30 * <p>Prints human-readable output – tables of result sets and text messages with update counts.</p>
32 * <p>Longer values might break the table – overflow the cells – see alternative tabular formatters
33 * and the {@linkplain #PROPERTY_TRIM} property.</p>
35 * @author Ing. František Kučera (frantovo.cz)
36 * @see TabularPrefetchingFormatter
37 * @see TabularWrappingFormatter
39 public class TabularFormatter extends AbstractFormatter {
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;
53 * use ASCII borders instead of unicode ones
55 private final boolean asciiNostalgia;
57 * Trim values if they are longer than cell size
59 private final boolean trimValues;
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));
70 public void writeStartResultSet(ColumnsHeader header) {
71 super.writeStartResultSet(header);
72 printResultSeparator();
74 initColumnWidths(header.getColumnCount());
77 printTableBorder("╭");
79 List<ColumnDescriptor> columnDescriptors = header.getColumnDescriptors();
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);
87 if (!cd.isFirstColumn()) {
88 printTableBorder("┬");
90 printTableBorder(repeat('─', getColumnWidth(cd.getColumnNumber()) + 2));
92 printTableBorder("╮");
95 for (ColumnDescriptor cd : columnDescriptors) {
96 if (cd.isFirstColumn()) {
98 printTableBorder("│ ");
100 printTableBorder(" │ ");
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(" │");
113 printTableBorder("├");
114 for (int i = 1; i <= header.getColumnCount(); i++) {
116 printTableBorder("┼");
118 printTableBorder(repeat('─', getColumnWidth(i) + 2));
120 printTableBorder("┤");
127 * Must be called before
128 * {@linkplain #updateColumnWidth(int, int)}
129 * and {@linkplain #getColumnWidth(int)}
130 * for each result set.
132 * @param columnCount number of columns in current result set
134 protected void initColumnWidths(int columnCount) {
135 if (columnWidth == null) {
136 columnWidth = new int[columnCount];
140 protected void cleanColumnWidths() {
145 public void writeColumnValue(Object value) {
146 super.writeColumnValue(value);
147 writeColumnValueInternal(value);
150 protected void writeColumnValueInternal(Object value) {
152 if (isCurrentColumnFirst()) {
154 printTableBorder("│ ");
156 printTableBorder(" │ ");
159 String valueString = toString(value);
160 printValueWithWhitespaceReplaced(valueString);
162 if (isCurrentColumnLast()) {
163 printTableBorder(" │");
168 protected int getColumnWidth(int columnNumber) {
169 return columnWidth[columnNumber - 1];
172 private void setColumnWidth(int columnNumber, int width) {
173 columnWidth[columnNumber - 1] = width;
176 protected void updateColumnWidth(int columnNumber, int width) {
177 int oldWidth = getColumnWidth(columnNumber);
178 setColumnWidth(columnNumber, Math.max(width, oldWidth));
182 protected String toString(Object value) {
183 final int width = getColumnWidth(getCurrentColumnsCount());
185 if (value instanceof Number || value instanceof Boolean) {
186 result = lpad(String.valueOf(value), width);
188 result = rpad(String.valueOf(value), width);
190 // ? value = (boolean) value ? "✔" : "✗";
192 if (trimValues && result.length() > width) {
193 result = result.substring(0, width - 1) + "…";
200 public void writeEndRow() {
202 writeEndRowInternal();
205 public void writeEndRowInternal() {
211 public void writeEndResultSet() {
212 int columnCount = getCurrentColumnsHeader().getColumnCount();
213 super.writeEndResultSet();
216 printTableBorder("╰");
217 for (int i = 1; i <= columnCount; i++) {
219 printTableBorder("┴");
221 printTableBorder(repeat('─', getColumnWidth(i) + 2));
223 printTableBorder("╯");
228 out.print(TerminalColor.Yellow, "Record count: ");
229 out.println(getCurrentRowCount());
235 public void writeUpdatesResult(int updatedRowsCount) {
236 super.writeUpdatesResult(updatedRowsCount);
237 printResultSeparator();
238 out.print(TerminalColor.Red, "Updated records: ");
239 out.println(updatedRowsCount);
245 public void writeEndDatabase() {
246 super.writeEndDatabase();
250 private void printResultSeparator() {
258 protected void printTableBorder(String border) {
259 if (asciiNostalgia) {
260 border = border.replaceAll("─", "-");
261 border = border.replaceAll("│", "|");
262 border = border.replaceAll("[╭┬╮├┼┤╰┴╯]", "+");
265 out.print(TerminalColor.Green, border);
268 protected void printTableIndent() {
272 protected void printValueWithWhitespaceReplaced(String valueString) {
274 Matcher m = whitespaceToReplace.matcher(valueString);
277 while (m.find(start)) {
279 out.print(TerminalColor.Cyan, valueString.substring(start, m.start()));
283 out.print(TerminalColor.Red, "↲");
286 out.print(TerminalColor.Red, "↹");
289 out.print(TerminalColor.Red, "⎵");
292 throw new IllegalStateException("Unexpected whitespace token: „" + m.group() + "“");
298 out.print(TerminalColor.Cyan, valueString.substring(start, valueString.length()));