1 /* SPDX-License-Identifier: LGPL-2.1+ */
5 #include "alloc-util.h"
8 #include "format-table.h"
11 #include "parse-util.h"
12 #include "string-util.h"
13 #include "terminal-util.h"
14 #include "time-util.h"
18 #define DEFAULT_WEIGHT 100
21 A few notes on implementation details:
23 - TableCell is a 'fake' structure, it's just used as data type to pass references to specific cell positions in the
24 table. It can be easily converted to an index number and back.
26 - TableData is where the actual data is stored: it encapsulates the data and formatting for a specific cell. It's
27 'pseudo-immutable' and ref-counted. When a cell's data's formatting is to be changed, we duplicate the object if the
28 ref-counting is larger than 1. Note that TableData and its ref-counting is mostly not visible to the outside. The
29 outside only sees Table and TableCell.
31 - The Table object stores a simple one-dimensional array of references to TableData objects, one row after the
34 - There's no special concept of a "row" or "column" in the table, and no special concept of the "header" row. It's all
35 derived from the cell index: we know how many cells are to be stored in a row, and can determine the rest from
36 that. The first row is always the header row. If header display is turned off we simply skip outputting the first
37 row. Also, when sorting rows we always leave the first row where it is, as the header shouldn't move.
39 - Note because there's no row and no column object some properties that might be approproate as row/column properties
40 are exposed as cell properties instead. For example, the "weight" of a column (which is used to determine where to
41 add/remove space preferable when expanding/compressing tables horizontally) is actually made the "weight" of a
42 cell. Given that we usually need it per-column though we will calculate the average across every cell of the column
45 - To make things easy, when cells are added without any explicit configured formatting, then we'll copy the formatting
46 from the same cell in the previous cell. This is particularly useful for the "weight" of the cell (see above), as
47 this means setting the weight of the cells of the header row will nicely propagate to all cells in the other rows.
50 typedef struct TableData {
54 size_t minimum_width; /* minimum width for the column */
55 size_t maximum_width; /* maximum width for the column */
56 unsigned weight; /* the horizontal weight for this column, in case the table is expanded/compressed */
57 unsigned ellipsize_percent; /* 0 … 100, where to place the ellipsis when compression is needed */
58 unsigned align_percent; /* 0 … 100, where to pad with spaces when expanding is needed. 0: left-aligned, 100: right-aligned */
60 const char *color; /* ANSI color string to use for this cell. When written to terminal should not move cursor. Will automatically be reset after the cell */
61 char *formatted; /* A cached textual representation of the cell data, before ellipsation/alignment */
64 uint8_t data[0]; /* data is generic array */
71 /* … add more here as we start supporting more cell data types … */
75 static size_t TABLE_CELL_TO_INDEX(TableCell *cell) {
80 i = PTR_TO_UINT(cell);
86 static TableCell* TABLE_INDEX_TO_CELL(size_t index) {
87 assert(index != (size_t) -1);
88 return UINT_TO_PTR((unsigned) (index + 1));
95 bool header; /* Whether to show the header row? */
96 size_t width; /* If != (size_t) -1 the width to format this table in */
101 size_t *display_map; /* List of columns to show (by their index). It's fine if columns are listed multiple times or not at all */
102 size_t n_display_map;
104 size_t *sort_map; /* The columns to order rows by, in order of preference. */
108 Table *table_new_raw(size_t n_columns) {
109 _cleanup_(table_unrefp) Table *t = NULL;
111 assert(n_columns > 0);
117 *t = (struct Table) {
118 .n_columns = n_columns,
120 .width = (size_t) -1,
126 Table *table_new_internal(const char *first_header, ...) {
127 _cleanup_(table_unrefp) Table *t = NULL;
128 size_t n_columns = 1;
132 assert(first_header);
134 va_start(ap, first_header);
138 h = va_arg(ap, const char*);
146 t = table_new_raw(n_columns);
150 r = table_add_cell(t, NULL, TABLE_STRING, first_header);
154 va_start(ap, first_header);
158 h = va_arg(ap, const char*);
162 r = table_add_cell(t, NULL, TABLE_STRING, h);
170 assert(t->n_columns == t->n_cells);
174 static TableData *table_data_unref(TableData *d) {
178 assert(d->n_ref > 0);
188 DEFINE_TRIVIAL_CLEANUP_FUNC(TableData*, table_data_unref);
190 static TableData *table_data_ref(TableData *d) {
194 assert(d->n_ref > 0);
200 Table *table_unref(Table *t) {
206 for (i = 0; i < t->n_cells; i++)
207 table_data_unref(t->data[i]);
210 free(t->display_map);
216 static size_t table_data_size(TableDataType type, const void *data) {
224 return strlen(data) + 1;
229 case TABLE_TIMESTAMP:
231 return sizeof(usec_t);
234 return sizeof(uint64_t);
237 return sizeof(uint32_t);
240 assert_not_reached("Uh? Unexpected cell type");
244 static bool table_data_matches(
248 size_t minimum_width,
249 size_t maximum_width,
251 unsigned align_percent,
252 unsigned ellipsize_percent) {
260 if (d->minimum_width != minimum_width)
263 if (d->maximum_width != maximum_width)
266 if (d->weight != weight)
269 if (d->align_percent != align_percent)
272 if (d->ellipsize_percent != ellipsize_percent)
275 k = table_data_size(type, data);
276 l = table_data_size(d->type, d->data);
281 return memcmp(data, d->data, l) == 0;
284 static TableData *table_data_new(
287 size_t minimum_width,
288 size_t maximum_width,
290 unsigned align_percent,
291 unsigned ellipsize_percent) {
296 data_size = table_data_size(type, data);
298 d = malloc0(offsetof(TableData, data) + data_size);
304 d->minimum_width = minimum_width;
305 d->maximum_width = maximum_width;
307 d->align_percent = align_percent;
308 d->ellipsize_percent = ellipsize_percent;
309 memcpy_safe(d->data, data, data_size);
314 int table_add_cell_full(
316 TableCell **ret_cell,
319 size_t minimum_width,
320 size_t maximum_width,
322 unsigned align_percent,
323 unsigned ellipsize_percent) {
325 _cleanup_(table_data_unrefp) TableData *d = NULL;
330 assert(type < _TABLE_DATA_TYPE_MAX);
332 /* Determine the cell adjacent to the current one, but one row up */
333 if (t->n_cells >= t->n_columns)
334 assert_se(p = t->data[t->n_cells - t->n_columns]);
338 /* If formatting parameters are left unspecified, copy from the previous row */
339 if (minimum_width == (size_t) -1)
340 minimum_width = p ? p->minimum_width : 1;
342 if (weight == (unsigned) -1)
343 weight = p ? p->weight : DEFAULT_WEIGHT;
345 if (align_percent == (unsigned) -1)
346 align_percent = p ? p->align_percent : 0;
348 if (ellipsize_percent == (unsigned) -1)
349 ellipsize_percent = p ? p->ellipsize_percent : 100;
351 assert(align_percent <= 100);
352 assert(ellipsize_percent <= 100);
354 /* Small optimization: Pretty often adjacent cells in two subsequent lines have the same data and
355 * formatting. Let's see if we can reuse the cell data and ref it once more. */
357 if (p && table_data_matches(p, type, data, minimum_width, maximum_width, weight, align_percent, ellipsize_percent))
358 d = table_data_ref(p);
360 d = table_data_new(type, data, minimum_width, maximum_width, weight, align_percent, ellipsize_percent);
365 if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns)))
369 *ret_cell = TABLE_INDEX_TO_CELL(t->n_cells);
371 t->data[t->n_cells++] = TAKE_PTR(d);
376 #if 0 /// UNNEEDED by elogind
377 int table_dup_cell(Table *t, TableCell *cell) {
382 /* Add the data of the specified cell a second time as a new cell to the end. */
384 i = TABLE_CELL_TO_INDEX(cell);
388 if (!GREEDY_REALLOC(t->data, t->n_allocated, MAX(t->n_cells + 1, t->n_columns)))
391 t->data[t->n_cells++] = table_data_ref(t->data[i]);
396 static int table_dedup_cell(Table *t, TableCell *cell) {
402 /* Helper call that ensures the specified cell's data object has a ref count of 1, which we can use before
403 * changing a cell's formatting without effecting every other cell's formatting that shares the same data */
405 i = TABLE_CELL_TO_INDEX(cell);
409 assert_se(od = t->data[i]);
413 assert(od->n_ref > 1);
415 nd = table_data_new(od->type, od->data, od->minimum_width, od->maximum_width, od->weight, od->align_percent, od->ellipsize_percent);
419 table_data_unref(od);
422 assert(nd->n_ref == 1);
427 static TableData *table_get_data(Table *t, TableCell *cell) {
433 /* Get the data object of the specified cell, or NULL if it doesn't exist */
435 i = TABLE_CELL_TO_INDEX(cell);
440 assert(t->data[i]->n_ref > 0);
445 #if 0 /// UNNEEDED by elogind
446 int table_set_minimum_width(Table *t, TableCell *cell, size_t minimum_width) {
452 if (minimum_width == (size_t) -1)
455 r = table_dedup_cell(t, cell);
459 table_get_data(t, cell)->minimum_width = minimum_width;
463 int table_set_maximum_width(Table *t, TableCell *cell, size_t maximum_width) {
469 r = table_dedup_cell(t, cell);
473 table_get_data(t, cell)->maximum_width = maximum_width;
477 int table_set_weight(Table *t, TableCell *cell, unsigned weight) {
483 if (weight == (unsigned) -1)
484 weight = DEFAULT_WEIGHT;
486 r = table_dedup_cell(t, cell);
490 table_get_data(t, cell)->weight = weight;
495 int table_set_align_percent(Table *t, TableCell *cell, unsigned percent) {
501 if (percent == (unsigned) -1)
504 assert(percent <= 100);
506 r = table_dedup_cell(t, cell);
510 table_get_data(t, cell)->align_percent = percent;
514 #if 0 /// UNNEEDED by elogind
515 int table_set_ellipsize_percent(Table *t, TableCell *cell, unsigned percent) {
521 if (percent == (unsigned) -1)
524 assert(percent <= 100);
526 r = table_dedup_cell(t, cell);
530 table_get_data(t, cell)->ellipsize_percent = percent;
534 int table_set_color(Table *t, TableCell *cell, const char *color) {
540 r = table_dedup_cell(t, cell);
544 table_get_data(t, cell)->color = empty_to_null(color);
549 int table_add_many_internal(Table *t, TableDataType first_type, ...) {
555 assert(first_type >= 0);
556 assert(first_type < _TABLE_DATA_TYPE_MAX);
560 va_start(ap, first_type);
577 data = va_arg(ap, const char *);
581 buffer.b = va_arg(ap, int);
585 case TABLE_TIMESTAMP:
587 buffer.usec = va_arg(ap, usec_t);
592 buffer.size = va_arg(ap, uint64_t);
597 buffer.uint32 = va_arg(ap, uint32_t);
598 data = &buffer.uint32;
601 case _TABLE_DATA_TYPE_MAX:
602 /* Used as end marker */
607 assert_not_reached("Uh? Unexpected data type.");
610 r = table_add_cell(t, NULL, type, data);
616 type = va_arg(ap, TableDataType);
620 void table_set_header(Table *t, bool b) {
626 void table_set_width(Table *t, size_t width) {
632 int table_set_display(Table *t, size_t first_column, ...) {
633 size_t allocated, column;
638 allocated = t->n_display_map;
639 column = first_column;
641 va_start(ap, first_column);
643 assert(column < t->n_columns);
645 if (!GREEDY_REALLOC(t->display_map, allocated, MAX(t->n_columns, t->n_display_map+1))) {
650 t->display_map[t->n_display_map++] = column;
652 column = va_arg(ap, size_t);
653 if (column == (size_t) -1)
662 int table_set_sort(Table *t, size_t first_column, ...) {
663 size_t allocated, column;
668 allocated = t->n_sort_map;
669 column = first_column;
671 va_start(ap, first_column);
673 assert(column < t->n_columns);
675 if (!GREEDY_REALLOC(t->sort_map, allocated, MAX(t->n_columns, t->n_sort_map+1))) {
680 t->sort_map[t->n_sort_map++] = column;
682 column = va_arg(ap, size_t);
683 if (column == (size_t) -1)
691 static int cell_data_compare(TableData *a, size_t index_a, TableData *b, size_t index_b) {
695 if (a->type == b->type) {
697 /* We only define ordering for cells of the same data type. If cells with different data types are
698 * compared we follow the order the cells were originally added in */
703 return strcmp(a->string, b->string);
706 if (!a->boolean && b->boolean)
708 if (a->boolean && !b->boolean)
712 case TABLE_TIMESTAMP:
713 if (a->timestamp < b->timestamp)
715 if (a->timestamp > b->timestamp)
720 if (a->timespan < b->timespan)
722 if (a->timespan > b->timespan)
727 if (a->size < b->size)
729 if (a->size > b->size)
734 if (a->uint32 < b->uint32)
736 if (a->uint32 > b->uint32)
745 /* Generic fallback using the orginal order in which the cells where added. */
746 if (index_a < index_b)
748 if (index_a > index_b)
754 static int table_data_compare(const void *x, const void *y, void *userdata) {
755 const size_t *a = x, *b = y;
763 /* Make sure the header stays at the beginning */
764 if (*a < t->n_columns && *b < t->n_columns)
766 if (*a < t->n_columns)
768 if (*b < t->n_columns)
771 /* Order other lines by the sorting map */
772 for (i = 0; i < t->n_sort_map; i++) {
775 d = t->data[*a + t->sort_map[i]];
776 dd = t->data[*b + t->sort_map[i]];
778 r = cell_data_compare(d, *a, dd, *b);
783 /* Order identical lines by the order there were originally added in */
792 static const char *table_data_format(TableData *d) {
806 return yes_no(d->boolean);
808 case TABLE_TIMESTAMP: {
809 _cleanup_free_ char *p;
811 p = new(char, FORMAT_TIMESTAMP_MAX);
815 if (!format_timestamp(p, FORMAT_TIMESTAMP_MAX, d->timestamp))
818 d->formatted = TAKE_PTR(p);
822 case TABLE_TIMESPAN: {
823 _cleanup_free_ char *p;
825 p = new(char, FORMAT_TIMESPAN_MAX);
829 if (!format_timespan(p, FORMAT_TIMESPAN_MAX, d->timestamp, 0))
832 d->formatted = TAKE_PTR(p);
837 _cleanup_free_ char *p;
839 p = new(char, FORMAT_BYTES_MAX);
843 if (!format_bytes(p, FORMAT_BYTES_MAX, d->size))
846 d->formatted = TAKE_PTR(p);
851 _cleanup_free_ char *p;
853 p = new(char, DECIMAL_STR_WIDTH(d->uint32) + 1);
857 sprintf(p, "%" PRIu32, d->uint32);
858 d->formatted = TAKE_PTR(p);
863 assert_not_reached("Unexpected type?");
869 static int table_data_requested_width(TableData *d, size_t *ret) {
873 t = table_data_format(d);
877 l = utf8_console_width(t);
878 if (l == (size_t) -1)
881 if (d->maximum_width != (size_t) -1 && l > d->maximum_width)
882 l = d->maximum_width;
884 if (l < d->minimum_width)
885 l = d->minimum_width;
891 static char *align_string_mem(const char *str, size_t new_length, unsigned percent) {
892 size_t w = 0, space, lspace, old_length;
897 /* As with ellipsize_mem(), 'old_length' is a byte size while 'new_length' is a width in character cells */
900 assert(percent <= 100);
902 old_length = strlen(str);
904 /* Determine current width on screen */
906 while (p < str + old_length) {
909 if (utf8_encoded_to_unichar(p, &c) < 0) {
910 p++, w++; /* count invalid chars as 1 */
914 p = utf8_next_char(p);
915 w += unichar_iswide(c) ? 2 : 1;
918 /* Already wider than the target, if so, don't do anything */
920 return strndup(str, old_length);
922 /* How much spaces shall we add? An how much on the left side? */
923 space = new_length - w;
924 lspace = space * percent / 100U;
926 ret = new(char, space + old_length + 1);
930 for (i = 0; i < lspace; i++)
932 memcpy(ret + lspace, str, old_length);
933 for (i = lspace + old_length; i < space + old_length; i++)
936 ret[space + old_length] = 0;
940 int table_print(Table *t, FILE *f) {
941 size_t n_rows, *minimum_width, *maximum_width, display_columns, *requested_width,
942 i, j, table_minimum_width, table_maximum_width, table_requested_width, table_effective_width,
944 _cleanup_free_ size_t *sorted = NULL;
945 uint64_t *column_weight, weight_sum;
953 /* Ensure we have no incomplete rows */
954 assert(t->n_cells % t->n_columns == 0);
956 n_rows = t->n_cells / t->n_columns;
957 assert(n_rows > 0); /* at least the header row must be complete */
960 /* If sorting is requested, let's calculate an index table we use to lookup the actual index to display with. */
962 sorted = new(size_t, n_rows);
966 for (i = 0; i < n_rows; i++)
967 sorted[i] = i * t->n_columns;
969 qsort_r_safe(sorted, n_rows, sizeof(size_t), table_data_compare, t);
973 display_columns = t->n_display_map;
975 display_columns = t->n_columns;
977 assert(display_columns > 0);
979 minimum_width = newa(size_t, display_columns);
980 maximum_width = newa(size_t, display_columns);
981 requested_width = newa(size_t, display_columns);
982 width = newa(size_t, display_columns);
983 column_weight = newa0(uint64_t, display_columns);
985 for (j = 0; j < display_columns; j++) {
986 minimum_width[j] = 1;
987 maximum_width[j] = (size_t) -1;
988 requested_width[j] = (size_t) -1;
991 /* First pass: determine column sizes */
992 for (i = t->header ? 0 : 1; i < n_rows; i++) {
995 /* Note that we don't care about ordering at this time, as we just want to determine column sizes,
996 * hence we don't care for sorted[] during the first pass. */
997 row = t->data + i * t->n_columns;
999 for (j = 0; j < display_columns; j++) {
1003 assert_se(d = row[t->display_map ? t->display_map[j] : j]);
1005 r = table_data_requested_width(d, &req);
1009 /* Determine the biggest width that any cell in this column would like to have */
1010 if (requested_width[j] == (size_t) -1 ||
1011 requested_width[j] < req)
1012 requested_width[j] = req;
1014 /* Determine the minimum width any cell in this column needs */
1015 if (minimum_width[j] < d->minimum_width)
1016 minimum_width[j] = d->minimum_width;
1018 /* Determine the maximum width any cell in this column needs */
1019 if (d->maximum_width != (size_t) -1 &&
1020 (maximum_width[j] == (size_t) -1 ||
1021 maximum_width[j] > d->maximum_width))
1022 maximum_width[j] = d->maximum_width;
1024 /* Determine the full columns weight */
1025 column_weight[j] += d->weight;
1029 /* One space between each column */
1030 table_requested_width = table_minimum_width = table_maximum_width = display_columns - 1;
1032 /* Calculate the total weight for all columns, plus the minimum, maximum and requested width for the table. */
1034 for (j = 0; j < display_columns; j++) {
1035 weight_sum += column_weight[j];
1037 table_minimum_width += minimum_width[j];
1039 if (maximum_width[j] == (size_t) -1)
1040 table_maximum_width = (size_t) -1;
1042 table_maximum_width += maximum_width[j];
1044 table_requested_width += requested_width[j];
1047 /* Calculate effective table width */
1048 if (t->width == (size_t) -1)
1049 table_effective_width = pager_have() ? table_requested_width : MIN(table_requested_width, columns());
1051 table_effective_width = t->width;
1053 if (table_maximum_width != (size_t) -1 && table_effective_width > table_maximum_width)
1054 table_effective_width = table_maximum_width;
1056 if (table_effective_width < table_minimum_width)
1057 table_effective_width = table_minimum_width;
1059 if (table_effective_width >= table_requested_width) {
1062 /* We have extra room, let's distribute it among columns according to their weights. We first provide
1063 * each column with what it asked for and the distribute the rest. */
1065 extra = table_effective_width - table_requested_width;
1067 for (j = 0; j < display_columns; j++) {
1070 if (weight_sum == 0)
1071 width[j] = requested_width[j] + extra / (display_columns - j); /* Avoid division by zero */
1073 width[j] = requested_width[j] + (extra * column_weight[j]) / weight_sum;
1075 if (maximum_width[j] != (size_t) -1 && width[j] > maximum_width[j])
1076 width[j] = maximum_width[j];
1078 if (width[j] < minimum_width[j])
1079 width[j] = minimum_width[j];
1081 assert(width[j] >= requested_width[j]);
1082 delta = width[j] - requested_width[j];
1084 /* Subtract what we just added from the rest */
1090 assert(weight_sum >= column_weight[j]);
1091 weight_sum -= column_weight[j];
1095 /* We need to compress the table, columns can't get what they asked for. We first provide each column
1096 * with the minimum they need, and then distribute anything left. */
1097 bool finalize = false;
1100 extra = table_effective_width - table_minimum_width;
1102 for (j = 0; j < display_columns; j++)
1103 width[j] = (size_t) -1;
1106 bool restart = false;
1108 for (j = 0; j < display_columns; j++) {
1111 /* Did this column already get something assigned? If so, let's skip to the next */
1112 if (width[j] != (size_t) -1)
1115 if (weight_sum == 0)
1116 w = minimum_width[j] + extra / (display_columns - j); /* avoid division by zero */
1118 w = minimum_width[j] + (extra * column_weight[j]) / weight_sum;
1120 if (w >= requested_width[j]) {
1121 /* Never give more than requested. If we hit a column like this, there's more
1122 * space to allocate to other columns which means we need to restart the
1123 * iteration. However, if we hit a column like this, let's assign it the space
1124 * it wanted for good early.*/
1126 w = requested_width[j];
1129 } else if (!finalize)
1134 assert(w >= minimum_width[j]);
1135 delta = w - minimum_width[j];
1137 assert(delta <= extra);
1140 assert(weight_sum >= column_weight[j]);
1141 weight_sum -= column_weight[j];
1157 /* Second pass: show output */
1158 for (i = t->header ? 0 : 1; i < n_rows; i++) {
1162 row = t->data + sorted[i];
1164 row = t->data + i * t->n_columns;
1166 for (j = 0; j < display_columns; j++) {
1167 _cleanup_free_ char *buffer = NULL;
1172 assert_se(d = row[t->display_map ? t->display_map[j] : j]);
1174 field = table_data_format(d);
1178 l = utf8_console_width(field);
1180 /* Field is wider than allocated space. Let's ellipsize */
1182 buffer = ellipsize(field, width[j], d->ellipsize_percent);
1188 } else if (l < width[j]) {
1189 /* Field is shorter than allocated space. Let's align with spaces */
1191 buffer = align_string_mem(field, width[j], d->align_percent);
1199 fputc(' ', f); /* column separator */
1207 fputs(ansi_normal(), f);
1213 return fflush_and_check(f);
1216 int table_format(Table *t, char **ret) {
1217 _cleanup_fclose_ FILE *f = NULL;
1222 f = open_memstream(&buf, &sz);
1226 (void) __fsetlocking(f, FSETLOCKING_BYCALLER);
1228 r = table_print(t, f);
1239 size_t table_get_rows(Table *t) {
1243 assert(t->n_columns > 0);
1244 return t->n_cells / t->n_columns;
1247 #if 0 /// UNNEEDED by elogind
1248 size_t table_get_columns(Table *t) {
1252 assert(t->n_columns > 0);
1253 return t->n_columns;