1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
9 #include "alloc-util.h"
12 #include "format-table.h"
13 #include "format-util.h"
15 #include "glyph-util.h"
17 #include "id128-util.h"
18 #include "in-addr-util.h"
19 #include "memory-util.h"
21 #include "parse-util.h"
22 #include "path-util.h"
23 #include "pretty-print.h"
24 #include "process-util.h"
25 #include "signal-util.h"
26 #include "sort-util.h"
27 #include "string-util.h"
29 #include "terminal-util.h"
30 #include "time-util.h"
31 #include "user-util.h"
35 #define DEFAULT_WEIGHT 100
38 A few notes on implementation details:
40 - TableCell is a 'fake' structure, it's just used as data type to pass references to specific cell positions in the
41 table. It can be easily converted to an index number and back.
43 - TableData is where the actual data is stored: it encapsulates the data and formatting for a specific cell. It's
44 'pseudo-immutable' and ref-counted. When a cell's data's formatting is to be changed, we duplicate the object if the
45 ref-counting is larger than 1. Note that TableData and its ref-counting is mostly not visible to the outside. The
46 outside only sees Table and TableCell.
48 - The Table object stores a simple one-dimensional array of references to TableData objects, one row after the
51 - There's no special concept of a "row" or "column" in the table, and no special concept of the "header" row. It's all
52 derived from the cell index: we know how many cells are to be stored in a row, and can determine the rest from
53 that. The first row is always the header row. If header display is turned off we simply skip outputting the first
54 row. Also, when sorting rows we always leave the first row where it is, as the header shouldn't move.
56 - Note because there's no row and no column object some properties that might be appropriate as row/column properties
57 are exposed as cell properties instead. For example, the "weight" of a column (which is used to determine where to
58 add/remove space preferable when expanding/compressing tables horizontally) is actually made the "weight" of a
59 cell. Given that we usually need it per-column though we will calculate the average across every cell of the column
62 - To make things easy, when cells are added without any explicit configured formatting, then we'll copy the formatting
63 from the same cell in the previous cell. This is particularly useful for the "weight" of the cell (see above), as
64 this means setting the weight of the cells of the header row will nicely propagate to all cells in the other rows.
67 typedef struct TableData
{
71 size_t minimum_width
; /* minimum width for the column */
72 size_t maximum_width
; /* maximum width for the column */
73 size_t formatted_for_width
; /* the width we tried to format for */
74 unsigned weight
; /* the horizontal weight for this column, in case the table is expanded/compressed */
75 unsigned ellipsize_percent
; /* 0 … 100, where to place the ellipsis when compression is needed */
76 unsigned align_percent
; /* 0 … 100, where to pad with spaces when expanding is needed. 0: left-aligned, 100: right-aligned */
78 bool uppercase
; /* Uppercase string on display */
80 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 */
81 const char *rgap_color
; /* The ANSI color to use for the gap right of this cell. Usually used to underline entire rows in a gapless fashion */
82 char *url
; /* A URL to use for a clickable hyperlink */
83 char *formatted
; /* A cached textual representation of the cell data, before ellipsation/alignment */
86 uint8_t data
[0]; /* data is generic array */
103 int percent
; /* we use 'int' as datatype for percent values in order to match the result of parse_percent() */
105 union in_addr_union address
;
111 /* … add more here as we start supporting more cell data types … */
115 static size_t TABLE_CELL_TO_INDEX(TableCell
*cell
) {
120 i
= PTR_TO_SIZE(cell
);
126 static TableCell
* TABLE_INDEX_TO_CELL(size_t index
) {
127 assert(index
!= SIZE_MAX
);
128 return SIZE_TO_PTR(index
+ 1);
135 bool header
; /* Whether to show the header row? */
136 size_t width
; /* If == 0 format this as wide as necessary. If SIZE_MAX format this to console
137 * width or less wide, but not wider. Otherwise the width to format this table in. */
138 size_t cell_height_max
; /* Maximum number of lines per cell. (If there are more, ellipsis is shown. If SIZE_MAX then no limit is set, the default. == 0 is not allowed.) */
142 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 */
143 size_t n_display_map
;
145 size_t *sort_map
; /* The columns to order rows by, in order of preference. */
149 size_t n_json_fields
;
156 Table
*table_new_raw(size_t n_columns
) {
157 _cleanup_(table_unrefp
) Table
*t
= NULL
;
159 assert(n_columns
> 0);
165 *t
= (struct Table
) {
166 .n_columns
= n_columns
,
169 .cell_height_max
= SIZE_MAX
,
175 Table
*table_new_internal(const char *first_header
, ...) {
176 _cleanup_(table_unrefp
) Table
*t
= NULL
;
177 size_t n_columns
= 1;
181 assert(first_header
);
183 va_start(ap
, first_header
);
185 if (!va_arg(ap
, const char*))
192 t
= table_new_raw(n_columns
);
196 va_start(ap
, first_header
);
197 for (const char *h
= first_header
; h
; h
= va_arg(ap
, const char*)) {
200 r
= table_add_cell(t
, &cell
, TABLE_STRING
, h
);
206 /* Make the table header uppercase */
207 r
= table_set_uppercase(t
, cell
, true);
215 assert(t
->n_columns
== t
->n_cells
);
219 static TableData
*table_data_free(TableData
*d
) {
225 if (IN_SET(d
->type
, TABLE_STRV
, TABLE_STRV_WRAPPED
))
231 DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(TableData
, table_data
, table_data_free
);
232 DEFINE_TRIVIAL_CLEANUP_FUNC(TableData
*, table_data_unref
);
234 Table
*table_unref(Table
*t
) {
238 for (size_t i
= 0; i
< t
->n_cells
; i
++)
239 table_data_unref(t
->data
[i
]);
242 free(t
->display_map
);
244 free(t
->reverse_map
);
245 free(t
->empty_string
);
247 for (size_t i
= 0; i
< t
->n_json_fields
; i
++)
248 free(t
->json_fields
[i
]);
250 free(t
->json_fields
);
255 static size_t table_data_size(TableDataType type
, const void *data
) {
264 return strlen(data
) + 1;
267 case TABLE_STRV_WRAPPED
:
268 return sizeof(char **);
270 case TABLE_BOOLEAN_CHECKMARK
:
274 case TABLE_TIMESTAMP
:
275 case TABLE_TIMESTAMP_UTC
:
276 case TABLE_TIMESTAMP_RELATIVE
:
278 case TABLE_TIMESPAN_MSEC
:
279 return sizeof(usec_t
);
284 case TABLE_UINT64_HEX
:
286 return sizeof(uint64_t);
290 return sizeof(uint32_t);
294 return sizeof(uint16_t);
298 return sizeof(uint8_t);
308 return sizeof(struct in_addr
);
311 return sizeof(struct in6_addr
);
315 return sizeof(sd_id128_t
);
318 return sizeof(uid_t
);
320 return sizeof(gid_t
);
322 return sizeof(pid_t
);
325 return sizeof(mode_t
);
328 assert_not_reached();
332 static bool table_data_matches(
336 size_t minimum_width
,
337 size_t maximum_width
,
339 unsigned align_percent
,
340 unsigned ellipsize_percent
) {
348 if (d
->minimum_width
!= minimum_width
)
351 if (d
->maximum_width
!= maximum_width
)
354 if (d
->weight
!= weight
)
357 if (d
->align_percent
!= align_percent
)
360 if (d
->ellipsize_percent
!= ellipsize_percent
)
363 /* If a color/url/uppercase flag is set, refuse to merge */
364 if (d
->color
|| d
->rgap_color
)
371 k
= table_data_size(type
, data
);
372 l
= table_data_size(d
->type
, d
->data
);
376 return memcmp_safe(data
, d
->data
, l
) == 0;
379 static TableData
*table_data_new(
382 size_t minimum_width
,
383 size_t maximum_width
,
385 unsigned align_percent
,
386 unsigned ellipsize_percent
) {
388 _cleanup_free_ TableData
*d
= NULL
;
391 data_size
= table_data_size(type
, data
);
393 d
= malloc0(offsetof(TableData
, data
) + data_size
);
399 d
->minimum_width
= minimum_width
;
400 d
->maximum_width
= maximum_width
;
402 d
->align_percent
= align_percent
;
403 d
->ellipsize_percent
= ellipsize_percent
;
405 if (IN_SET(type
, TABLE_STRV
, TABLE_STRV_WRAPPED
)) {
406 d
->strv
= strv_copy(data
);
410 memcpy_safe(d
->data
, data
, data_size
);
415 int table_add_cell_full(
417 TableCell
**ret_cell
,
420 size_t minimum_width
,
421 size_t maximum_width
,
423 unsigned align_percent
,
424 unsigned ellipsize_percent
) {
426 _cleanup_(table_data_unrefp
) TableData
*d
= NULL
;
431 assert(type
< _TABLE_DATA_TYPE_MAX
);
433 /* Special rule: patch NULL data fields to the empty field */
437 /* Determine the cell adjacent to the current one, but one row up */
438 if (t
->n_cells
>= t
->n_columns
)
439 assert_se(p
= t
->data
[t
->n_cells
- t
->n_columns
]);
443 /* If formatting parameters are left unspecified, copy from the previous row */
444 if (minimum_width
== SIZE_MAX
)
445 minimum_width
= p
? p
->minimum_width
: 1;
447 if (weight
== UINT_MAX
)
448 weight
= p
? p
->weight
: DEFAULT_WEIGHT
;
450 if (align_percent
== UINT_MAX
)
451 align_percent
= p
? p
->align_percent
: 0;
453 if (ellipsize_percent
== UINT_MAX
)
454 ellipsize_percent
= p
? p
->ellipsize_percent
: 100;
456 assert(align_percent
<= 100);
457 assert(ellipsize_percent
<= 100);
459 /* Small optimization: Pretty often adjacent cells in two subsequent lines have the same data and
460 * formatting. Let's see if we can reuse the cell data and ref it once more. */
462 if (p
&& table_data_matches(p
, type
, data
, minimum_width
, maximum_width
, weight
, align_percent
, ellipsize_percent
))
463 d
= table_data_ref(p
);
465 d
= table_data_new(type
, data
, minimum_width
, maximum_width
, weight
, align_percent
, ellipsize_percent
);
470 if (!GREEDY_REALLOC(t
->data
, MAX(t
->n_cells
+ 1, t
->n_columns
)))
474 *ret_cell
= TABLE_INDEX_TO_CELL(t
->n_cells
);
476 t
->data
[t
->n_cells
++] = TAKE_PTR(d
);
481 int table_add_cell_stringf(Table
*t
, TableCell
**ret_cell
, const char *format
, ...) {
482 _cleanup_free_
char *buffer
= NULL
;
486 va_start(ap
, format
);
487 r
= vasprintf(&buffer
, format
, ap
);
492 return table_add_cell(t
, ret_cell
, TABLE_STRING
, buffer
);
495 int table_fill_empty(Table
*t
, size_t until_column
) {
500 /* Fill the rest of the current line with empty cells until we reach the specified column. Will add
501 * at least one cell. Pass 0 in order to fill a line to the end or insert an empty line. */
503 if (until_column
>= t
->n_columns
)
507 r
= table_add_cell(t
, NULL
, TABLE_EMPTY
, NULL
);
511 } while ((t
->n_cells
% t
->n_columns
) != until_column
);
516 int table_dup_cell(Table
*t
, TableCell
*cell
) {
521 /* Add the data of the specified cell a second time as a new cell to the end. */
523 i
= TABLE_CELL_TO_INDEX(cell
);
527 if (!GREEDY_REALLOC(t
->data
, MAX(t
->n_cells
+ 1, t
->n_columns
)))
530 t
->data
[t
->n_cells
++] = table_data_ref(t
->data
[i
]);
534 static int table_dedup_cell(Table
*t
, TableCell
*cell
) {
535 _cleanup_free_
char *curl
= NULL
;
541 /* Helper call that ensures the specified cell's data object has a ref count of 1, which we can use before
542 * changing a cell's formatting without effecting every other cell's formatting that shares the same data */
544 i
= TABLE_CELL_TO_INDEX(cell
);
548 assert_se(od
= t
->data
[i
]);
552 assert(od
->n_ref
> 1);
555 curl
= strdup(od
->url
);
567 od
->ellipsize_percent
);
571 nd
->color
= od
->color
;
572 nd
->rgap_color
= od
->rgap_color
;
573 nd
->url
= TAKE_PTR(curl
);
574 nd
->uppercase
= od
->uppercase
;
576 table_data_unref(od
);
579 assert(nd
->n_ref
== 1);
584 static TableData
*table_get_data(Table
*t
, TableCell
*cell
) {
590 /* Get the data object of the specified cell, or NULL if it doesn't exist */
592 i
= TABLE_CELL_TO_INDEX(cell
);
597 assert(t
->data
[i
]->n_ref
> 0);
602 int table_set_minimum_width(Table
*t
, TableCell
*cell
, size_t minimum_width
) {
608 if (minimum_width
== SIZE_MAX
)
611 r
= table_dedup_cell(t
, cell
);
615 table_get_data(t
, cell
)->minimum_width
= minimum_width
;
619 int table_set_maximum_width(Table
*t
, TableCell
*cell
, size_t maximum_width
) {
625 r
= table_dedup_cell(t
, cell
);
629 table_get_data(t
, cell
)->maximum_width
= maximum_width
;
633 int table_set_weight(Table
*t
, TableCell
*cell
, unsigned weight
) {
639 if (weight
== UINT_MAX
)
640 weight
= DEFAULT_WEIGHT
;
642 r
= table_dedup_cell(t
, cell
);
646 table_get_data(t
, cell
)->weight
= weight
;
650 int table_set_align_percent(Table
*t
, TableCell
*cell
, unsigned percent
) {
656 if (percent
== UINT_MAX
)
659 assert(percent
<= 100);
661 r
= table_dedup_cell(t
, cell
);
665 table_get_data(t
, cell
)->align_percent
= percent
;
669 int table_set_ellipsize_percent(Table
*t
, TableCell
*cell
, unsigned percent
) {
675 if (percent
== UINT_MAX
)
678 assert(percent
<= 100);
680 r
= table_dedup_cell(t
, cell
);
684 table_get_data(t
, cell
)->ellipsize_percent
= percent
;
688 int table_set_color(Table
*t
, TableCell
*cell
, const char *color
) {
694 r
= table_dedup_cell(t
, cell
);
698 table_get_data(t
, cell
)->color
= empty_to_null(color
);
702 int table_set_rgap_color(Table
*t
, TableCell
*cell
, const char *color
) {
708 r
= table_dedup_cell(t
, cell
);
712 table_get_data(t
, cell
)->rgap_color
= empty_to_null(color
);
716 int table_set_url(Table
*t
, TableCell
*cell
, const char *url
) {
717 _cleanup_free_
char *copy
= NULL
;
729 r
= table_dedup_cell(t
, cell
);
733 return free_and_replace(table_get_data(t
, cell
)->url
, copy
);
736 int table_set_uppercase(Table
*t
, TableCell
*cell
, bool b
) {
743 r
= table_dedup_cell(t
, cell
);
747 assert_se(d
= table_get_data(t
, cell
));
749 if (d
->uppercase
== b
)
752 d
->formatted
= mfree(d
->formatted
);
757 int table_update(Table
*t
, TableCell
*cell
, TableDataType type
, const void *data
) {
758 _cleanup_free_
char *curl
= NULL
;
765 i
= TABLE_CELL_TO_INDEX(cell
);
769 assert_se(od
= t
->data
[i
]);
772 curl
= strdup(od
->url
);
784 od
->ellipsize_percent
);
788 nd
->color
= od
->color
;
789 nd
->rgap_color
= od
->rgap_color
;
790 nd
->url
= TAKE_PTR(curl
);
791 nd
->uppercase
= od
->uppercase
;
793 table_data_unref(od
);
799 int table_add_many_internal(Table
*t
, TableDataType first_type
, ...) {
800 TableCell
*last_cell
= NULL
;
805 assert(first_type
>= 0);
806 assert(first_type
< _TABLE_DATA_TYPE_MAX
);
808 va_start(ap
, first_type
);
810 for (TableDataType type
= first_type
;; type
= va_arg(ap
, TableDataType
)) {
828 union in_addr_union address
;
844 data
= va_arg(ap
, const char *);
848 case TABLE_STRV_WRAPPED
:
849 data
= va_arg(ap
, char * const *);
852 case TABLE_BOOLEAN_CHECKMARK
:
854 buffer
.b
= va_arg(ap
, int);
858 case TABLE_TIMESTAMP
:
859 case TABLE_TIMESTAMP_UTC
:
860 case TABLE_TIMESTAMP_RELATIVE
:
862 case TABLE_TIMESPAN_MSEC
:
863 buffer
.usec
= va_arg(ap
, usec_t
);
869 buffer
.size
= va_arg(ap
, uint64_t);
875 buffer
.int_val
= va_arg(ap
, int);
876 data
= &buffer
.int_val
;
880 int x
= va_arg(ap
, int);
881 assert(x
>= INT8_MIN
&& x
<= INT8_MAX
);
889 int x
= va_arg(ap
, int);
890 assert(x
>= INT16_MIN
&& x
<= INT16_MAX
);
893 data
= &buffer
.int16
;
898 buffer
.int32
= va_arg(ap
, int32_t);
899 data
= &buffer
.int32
;
903 buffer
.int64
= va_arg(ap
, int64_t);
904 data
= &buffer
.int64
;
908 buffer
.uint_val
= va_arg(ap
, unsigned);
909 data
= &buffer
.uint_val
;
913 unsigned x
= va_arg(ap
, unsigned);
914 assert(x
<= UINT8_MAX
);
917 data
= &buffer
.uint8
;
922 unsigned x
= va_arg(ap
, unsigned);
923 assert(x
<= UINT16_MAX
);
926 data
= &buffer
.uint16
;
931 buffer
.uint32
= va_arg(ap
, uint32_t);
932 data
= &buffer
.uint32
;
936 case TABLE_UINT64_HEX
:
937 buffer
.uint64
= va_arg(ap
, uint64_t);
938 data
= &buffer
.uint64
;
942 buffer
.percent
= va_arg(ap
, int);
943 data
= &buffer
.percent
;
947 buffer
.ifindex
= va_arg(ap
, int);
948 data
= &buffer
.ifindex
;
952 buffer
.address
= *va_arg(ap
, union in_addr_union
*);
953 data
= &buffer
.address
.in
;
957 buffer
.address
= *va_arg(ap
, union in_addr_union
*);
958 data
= &buffer
.address
.in6
;
963 buffer
.id128
= va_arg(ap
, sd_id128_t
);
964 data
= &buffer
.id128
;
968 buffer
.uid
= va_arg(ap
, uid_t
);
973 buffer
.gid
= va_arg(ap
, gid_t
);
978 buffer
.pid
= va_arg(ap
, pid_t
);
983 buffer
.mode
= va_arg(ap
, mode_t
);
987 case TABLE_SET_MINIMUM_WIDTH
: {
988 size_t w
= va_arg(ap
, size_t);
990 r
= table_set_minimum_width(t
, last_cell
, w
);
994 case TABLE_SET_MAXIMUM_WIDTH
: {
995 size_t w
= va_arg(ap
, size_t);
996 r
= table_set_maximum_width(t
, last_cell
, w
);
1000 case TABLE_SET_WEIGHT
: {
1001 unsigned w
= va_arg(ap
, unsigned);
1002 r
= table_set_weight(t
, last_cell
, w
);
1006 case TABLE_SET_ALIGN_PERCENT
: {
1007 unsigned p
= va_arg(ap
, unsigned);
1008 r
= table_set_align_percent(t
, last_cell
, p
);
1012 case TABLE_SET_ELLIPSIZE_PERCENT
: {
1013 unsigned p
= va_arg(ap
, unsigned);
1014 r
= table_set_ellipsize_percent(t
, last_cell
, p
);
1018 case TABLE_SET_COLOR
: {
1019 const char *c
= va_arg(ap
, const char*);
1020 r
= table_set_color(t
, last_cell
, c
);
1024 case TABLE_SET_RGAP_COLOR
: {
1025 const char *c
= va_arg(ap
, const char*);
1026 r
= table_set_rgap_color(t
, last_cell
, c
);
1030 case TABLE_SET_BOTH_COLORS
: {
1031 const char *c
= va_arg(ap
, const char*);
1033 r
= table_set_color(t
, last_cell
, c
);
1039 r
= table_set_rgap_color(t
, last_cell
, c
);
1043 case TABLE_SET_URL
: {
1044 const char *u
= va_arg(ap
, const char*);
1045 r
= table_set_url(t
, last_cell
, u
);
1049 case TABLE_SET_UPPERCASE
: {
1050 int u
= va_arg(ap
, int);
1051 r
= table_set_uppercase(t
, last_cell
, u
);
1055 case _TABLE_DATA_TYPE_MAX
:
1056 /* Used as end marker */
1061 assert_not_reached();
1064 r
= table_add_cell(t
, &last_cell
, type
, data
);
1073 void table_set_header(Table
*t
, bool b
) {
1079 void table_set_width(Table
*t
, size_t width
) {
1085 void table_set_cell_height_max(Table
*t
, size_t height
) {
1087 assert(height
>= 1 || height
== SIZE_MAX
);
1089 t
->cell_height_max
= height
;
1092 int table_set_empty_string(Table
*t
, const char *empty
) {
1095 return free_and_strdup(&t
->empty_string
, empty
);
1098 static int table_set_display_all(Table
*t
) {
1103 /* Initialize the display map to the identity */
1105 d
= reallocarray(t
->display_map
, t
->n_columns
, sizeof(size_t));
1109 for (size_t i
= 0; i
< t
->n_columns
; i
++)
1113 t
->n_display_map
= t
->n_columns
;
1118 int table_set_display_internal(Table
*t
, size_t first_column
, ...) {
1124 column
= first_column
;
1126 va_start(ap
, first_column
);
1128 assert(column
< t
->n_columns
);
1130 if (!GREEDY_REALLOC(t
->display_map
, MAX(t
->n_columns
, t
->n_display_map
+1))) {
1135 t
->display_map
[t
->n_display_map
++] = column
;
1137 column
= va_arg(ap
, size_t);
1138 if (column
== SIZE_MAX
)
1147 int table_set_sort_internal(Table
*t
, size_t first_column
, ...) {
1153 column
= first_column
;
1155 va_start(ap
, first_column
);
1157 assert(column
< t
->n_columns
);
1159 if (!GREEDY_REALLOC(t
->sort_map
, MAX(t
->n_columns
, t
->n_sort_map
+1))) {
1164 t
->sort_map
[t
->n_sort_map
++] = column
;
1166 column
= va_arg(ap
, size_t);
1167 if (column
== SIZE_MAX
)
1175 int table_hide_column_from_display_internal(Table
*t
, ...) {
1181 /* If the display map is empty, initialize it with all available columns */
1182 if (!t
->display_map
) {
1183 r
= table_set_display_all(t
);
1188 for (size_t i
= 0; i
< t
->n_display_map
; i
++) {
1189 bool listed
= false;
1196 column
= va_arg(ap
, size_t);
1197 if (column
== SIZE_MAX
)
1199 if (column
== t
->display_map
[i
]) {
1209 t
->display_map
[cur
++] = t
->display_map
[i
];
1212 t
->n_display_map
= cur
;
1217 static int cell_data_compare(TableData
*a
, size_t index_a
, TableData
*b
, size_t index_b
) {
1221 if (a
->type
== b
->type
) {
1223 /* We only define ordering for cells of the same data type. If cells with different data types are
1224 * compared we follow the order the cells were originally added in */
1229 return strcmp(a
->string
, b
->string
);
1232 return path_compare(a
->string
, b
->string
);
1235 case TABLE_STRV_WRAPPED
:
1236 return strv_compare(a
->strv
, b
->strv
);
1239 if (!a
->boolean
&& b
->boolean
)
1241 if (a
->boolean
&& !b
->boolean
)
1245 case TABLE_TIMESTAMP
:
1246 case TABLE_TIMESTAMP_UTC
:
1247 case TABLE_TIMESTAMP_RELATIVE
:
1248 return CMP(a
->timestamp
, b
->timestamp
);
1250 case TABLE_TIMESPAN
:
1251 case TABLE_TIMESPAN_MSEC
:
1252 return CMP(a
->timespan
, b
->timespan
);
1256 return CMP(a
->size
, b
->size
);
1260 return CMP(a
->int_val
, b
->int_val
);
1263 return CMP(a
->int8
, b
->int8
);
1266 return CMP(a
->int16
, b
->int16
);
1269 return CMP(a
->int32
, b
->int32
);
1272 return CMP(a
->int64
, b
->int64
);
1275 return CMP(a
->uint_val
, b
->uint_val
);
1278 return CMP(a
->uint8
, b
->uint8
);
1281 return CMP(a
->uint16
, b
->uint16
);
1284 return CMP(a
->uint32
, b
->uint32
);
1287 case TABLE_UINT64_HEX
:
1288 return CMP(a
->uint64
, b
->uint64
);
1291 return CMP(a
->percent
, b
->percent
);
1294 return CMP(a
->ifindex
, b
->ifindex
);
1297 return CMP(a
->address
.in
.s_addr
, b
->address
.in
.s_addr
);
1299 case TABLE_IN6_ADDR
:
1300 return memcmp(&a
->address
.in6
, &b
->address
.in6
, FAMILY_ADDRESS_SIZE(AF_INET6
));
1304 return memcmp(&a
->id128
, &b
->id128
, sizeof(sd_id128_t
));
1307 return CMP(a
->uid
, b
->uid
);
1310 return CMP(a
->gid
, b
->gid
);
1313 return CMP(a
->pid
, b
->pid
);
1316 return CMP(a
->mode
, b
->mode
);
1323 /* Generic fallback using the original order in which the cells where added. */
1324 return CMP(index_a
, index_b
);
1327 static int table_data_compare(const size_t *a
, const size_t *b
, Table
*t
) {
1331 assert(t
->sort_map
);
1333 /* Make sure the header stays at the beginning */
1334 if (*a
< t
->n_columns
&& *b
< t
->n_columns
)
1336 if (*a
< t
->n_columns
)
1338 if (*b
< t
->n_columns
)
1341 /* Order other lines by the sorting map */
1342 for (size_t i
= 0; i
< t
->n_sort_map
; i
++) {
1345 d
= t
->data
[*a
+ t
->sort_map
[i
]];
1346 dd
= t
->data
[*b
+ t
->sort_map
[i
]];
1348 r
= cell_data_compare(d
, *a
, dd
, *b
);
1350 return t
->reverse_map
&& t
->reverse_map
[t
->sort_map
[i
]] ? -r
: r
;
1353 /* Order identical lines by the order there were originally added in */
1357 static char* format_strv_width(char **strv
, size_t column_width
) {
1358 _cleanup_free_
char *buf
= NULL
; /* buf must be freed after f */
1359 _cleanup_fclose_
FILE *f
= NULL
;
1362 f
= open_memstream_unlocked(&buf
, &sz
);
1366 size_t position
= 0;
1368 STRV_FOREACH(p
, strv
) {
1369 size_t our_len
= utf8_console_width(*p
); /* This returns -1 on invalid utf-8 (which shouldn't happen).
1370 * If that happens, we'll just print one item per line. */
1372 if (position
== 0) {
1375 } else if (size_add(size_add(position
, 1), our_len
) <= column_width
) {
1376 fprintf(f
, " %s", *p
);
1377 position
= size_add(size_add(position
, 1), our_len
);
1379 fprintf(f
, "\n%s", *p
);
1384 if (fflush_and_check(f
) < 0)
1388 return TAKE_PTR(buf
);
1391 static const char *table_data_format(Table
*t
, TableData
*d
, bool avoid_uppercasing
, size_t column_width
, bool *have_soft
) {
1395 /* Only TABLE_STRV_WRAPPED adjust based on column_width so far… */
1396 (d
->type
!= TABLE_STRV_WRAPPED
|| d
->formatted_for_width
== column_width
))
1397 return d
->formatted
;
1401 return strempty(t
->empty_string
);
1405 if (d
->uppercase
&& !avoid_uppercasing
) {
1406 d
->formatted
= new(char, strlen(d
->string
) + 1);
1410 char *q
= d
->formatted
;
1411 for (char *p
= d
->string
; *p
; p
++, q
++)
1412 *q
= (char) toupper((unsigned char) *p
);
1415 return d
->formatted
;
1421 if (strv_isempty(d
->strv
))
1422 return strempty(t
->empty_string
);
1424 d
->formatted
= strv_join(d
->strv
, "\n");
1429 case TABLE_STRV_WRAPPED
: {
1430 if (strv_isempty(d
->strv
))
1431 return strempty(t
->empty_string
);
1433 char *buf
= format_strv_width(d
->strv
, column_width
);
1437 free_and_replace(d
->formatted
, buf
);
1438 d
->formatted_for_width
= column_width
;
1446 return yes_no(d
->boolean
);
1448 case TABLE_BOOLEAN_CHECKMARK
:
1449 return special_glyph(d
->boolean
? SPECIAL_GLYPH_CHECK_MARK
: SPECIAL_GLYPH_CROSS_MARK
);
1451 case TABLE_TIMESTAMP
:
1452 case TABLE_TIMESTAMP_UTC
:
1453 case TABLE_TIMESTAMP_RELATIVE
: {
1454 _cleanup_free_
char *p
= NULL
;
1457 p
= new(char, d
->type
== TABLE_TIMESTAMP_RELATIVE
? FORMAT_TIMESTAMP_RELATIVE_MAX
: FORMAT_TIMESTAMP_MAX
);
1461 if (d
->type
== TABLE_TIMESTAMP
)
1462 ret
= format_timestamp(p
, FORMAT_TIMESTAMP_MAX
, d
->timestamp
);
1463 else if (d
->type
== TABLE_TIMESTAMP_UTC
)
1464 ret
= format_timestamp_style(p
, FORMAT_TIMESTAMP_MAX
, d
->timestamp
, TIMESTAMP_UTC
);
1466 ret
= format_timestamp_relative(p
, FORMAT_TIMESTAMP_RELATIVE_MAX
, d
->timestamp
);
1470 d
->formatted
= TAKE_PTR(p
);
1474 case TABLE_TIMESPAN
:
1475 case TABLE_TIMESPAN_MSEC
: {
1476 _cleanup_free_
char *p
= NULL
;
1478 p
= new(char, FORMAT_TIMESPAN_MAX
);
1482 if (!format_timespan(p
, FORMAT_TIMESPAN_MAX
, d
->timespan
,
1483 d
->type
== TABLE_TIMESPAN
? 0 : USEC_PER_MSEC
))
1486 d
->formatted
= TAKE_PTR(p
);
1491 _cleanup_free_
char *p
= NULL
;
1493 p
= new(char, FORMAT_BYTES_MAX
);
1497 if (!format_bytes(p
, FORMAT_BYTES_MAX
, d
->size
))
1500 d
->formatted
= TAKE_PTR(p
);
1505 _cleanup_free_
char *p
= NULL
;
1508 p
= new(char, FORMAT_BYTES_MAX
+2);
1512 if (!format_bytes_full(p
, FORMAT_BYTES_MAX
, d
->size
, 0))
1516 strscpy(p
+ n
, FORMAT_BYTES_MAX
+ 2 - n
, "bps");
1518 d
->formatted
= TAKE_PTR(p
);
1523 _cleanup_free_
char *p
= NULL
;
1525 p
= new(char, DECIMAL_STR_WIDTH(d
->int_val
) + 1);
1529 sprintf(p
, "%i", d
->int_val
);
1530 d
->formatted
= TAKE_PTR(p
);
1535 _cleanup_free_
char *p
= NULL
;
1537 p
= new(char, DECIMAL_STR_WIDTH(d
->int8
) + 1);
1541 sprintf(p
, "%" PRIi8
, d
->int8
);
1542 d
->formatted
= TAKE_PTR(p
);
1547 _cleanup_free_
char *p
= NULL
;
1549 p
= new(char, DECIMAL_STR_WIDTH(d
->int16
) + 1);
1553 sprintf(p
, "%" PRIi16
, d
->int16
);
1554 d
->formatted
= TAKE_PTR(p
);
1559 _cleanup_free_
char *p
= NULL
;
1561 p
= new(char, DECIMAL_STR_WIDTH(d
->int32
) + 1);
1565 sprintf(p
, "%" PRIi32
, d
->int32
);
1566 d
->formatted
= TAKE_PTR(p
);
1571 _cleanup_free_
char *p
= NULL
;
1573 p
= new(char, DECIMAL_STR_WIDTH(d
->int64
) + 1);
1577 sprintf(p
, "%" PRIi64
, d
->int64
);
1578 d
->formatted
= TAKE_PTR(p
);
1583 _cleanup_free_
char *p
= NULL
;
1585 p
= new(char, DECIMAL_STR_WIDTH(d
->uint_val
) + 1);
1589 sprintf(p
, "%u", d
->uint_val
);
1590 d
->formatted
= TAKE_PTR(p
);
1595 _cleanup_free_
char *p
= NULL
;
1597 p
= new(char, DECIMAL_STR_WIDTH(d
->uint8
) + 1);
1601 sprintf(p
, "%" PRIu8
, d
->uint8
);
1602 d
->formatted
= TAKE_PTR(p
);
1606 case TABLE_UINT16
: {
1607 _cleanup_free_
char *p
= NULL
;
1609 p
= new(char, DECIMAL_STR_WIDTH(d
->uint16
) + 1);
1613 sprintf(p
, "%" PRIu16
, d
->uint16
);
1614 d
->formatted
= TAKE_PTR(p
);
1618 case TABLE_UINT32
: {
1619 _cleanup_free_
char *p
= NULL
;
1621 p
= new(char, DECIMAL_STR_WIDTH(d
->uint32
) + 1);
1625 sprintf(p
, "%" PRIu32
, d
->uint32
);
1626 d
->formatted
= TAKE_PTR(p
);
1630 case TABLE_UINT64
: {
1631 _cleanup_free_
char *p
= NULL
;
1633 p
= new(char, DECIMAL_STR_WIDTH(d
->uint64
) + 1);
1637 sprintf(p
, "%" PRIu64
, d
->uint64
);
1638 d
->formatted
= TAKE_PTR(p
);
1642 case TABLE_UINT64_HEX
: {
1643 _cleanup_free_
char *p
= NULL
;
1645 p
= new(char, 16 + 1);
1649 sprintf(p
, "%" PRIx64
, d
->uint64
);
1650 d
->formatted
= TAKE_PTR(p
);
1654 case TABLE_PERCENT
: {
1655 _cleanup_free_
char *p
= NULL
;
1657 p
= new(char, DECIMAL_STR_WIDTH(d
->percent
) + 2);
1661 sprintf(p
, "%i%%" , d
->percent
);
1662 d
->formatted
= TAKE_PTR(p
);
1666 case TABLE_IFINDEX
: {
1667 _cleanup_free_
char *p
= NULL
;
1669 if (format_ifname_full_alloc(d
->ifindex
, FORMAT_IFNAME_IFINDEX
, &p
) < 0)
1672 d
->formatted
= TAKE_PTR(p
);
1677 case TABLE_IN6_ADDR
: {
1678 _cleanup_free_
char *p
= NULL
;
1680 if (in_addr_to_string(d
->type
== TABLE_IN_ADDR
? AF_INET
: AF_INET6
,
1681 &d
->address
, &p
) < 0)
1684 d
->formatted
= TAKE_PTR(p
);
1691 p
= new(char, SD_ID128_STRING_MAX
);
1695 d
->formatted
= sd_id128_to_string(d
->id128
, p
);
1702 p
= new(char, SD_ID128_UUID_STRING_MAX
);
1706 d
->formatted
= sd_id128_to_uuid_string(d
->id128
, p
);
1713 if (!uid_is_valid(d
->uid
))
1716 p
= new(char, DECIMAL_STR_WIDTH(d
->uid
) + 1);
1719 sprintf(p
, UID_FMT
, d
->uid
);
1728 if (!gid_is_valid(d
->gid
))
1731 p
= new(char, DECIMAL_STR_WIDTH(d
->gid
) + 1);
1734 sprintf(p
, GID_FMT
, d
->gid
);
1743 if (!pid_is_valid(d
->pid
))
1746 p
= new(char, DECIMAL_STR_WIDTH(d
->pid
) + 1);
1749 sprintf(p
, PID_FMT
, d
->pid
);
1755 case TABLE_SIGNAL
: {
1759 suffix
= signal_to_string(d
->int_val
);
1763 p
= strjoin("SIG", suffix
);
1774 if (d
->mode
== MODE_INVALID
)
1777 p
= new(char, 4 + 1);
1781 sprintf(p
, "%04o", d
->mode
& 07777);
1787 assert_not_reached();
1790 return d
->formatted
;
1793 static int console_width_height(
1796 size_t *ret_height
) {
1798 size_t max_width
= 0, height
= 0;
1803 /* Determine the width and height in console character cells the specified string needs. */
1808 p
= strchr(s
, '\n');
1810 _cleanup_free_
char *c
= NULL
;
1812 c
= strndup(s
, p
- s
);
1816 k
= utf8_console_width(c
);
1819 k
= utf8_console_width(s
);
1828 } while (!isempty(s
));
1831 *ret_width
= max_width
;
1834 *ret_height
= height
;
1839 static int table_data_requested_width_height(
1842 size_t available_width
,
1847 _cleanup_free_
char *truncated
= NULL
;
1848 bool truncation_applied
= false;
1849 size_t width
, height
;
1854 t
= table_data_format(table
, d
, false, available_width
, &soft
);
1858 if (table
->cell_height_max
!= SIZE_MAX
) {
1859 r
= string_truncate_lines(t
, table
->cell_height_max
, &truncated
);
1863 truncation_applied
= true;
1868 r
= console_width_height(t
, &width
, &height
);
1872 if (d
->maximum_width
!= SIZE_MAX
&& width
> d
->maximum_width
)
1873 width
= d
->maximum_width
;
1875 if (width
< d
->minimum_width
)
1876 width
= d
->minimum_width
;
1881 *ret_height
= height
;
1882 if (have_soft
&& soft
)
1885 return truncation_applied
;
1888 static char *align_string_mem(const char *str
, const char *url
, size_t new_length
, unsigned percent
) {
1889 size_t w
= 0, space
, lspace
, old_length
, clickable_length
;
1890 _cleanup_free_
char *clickable
= NULL
;
1895 /* As with ellipsize_mem(), 'old_length' is a byte size while 'new_length' is a width in character cells */
1898 assert(percent
<= 100);
1900 old_length
= strlen(str
);
1903 r
= terminal_urlify(url
, str
, &clickable
);
1907 clickable_length
= strlen(clickable
);
1909 clickable_length
= old_length
;
1911 /* Determine current width on screen */
1913 while (p
< str
+ old_length
) {
1916 if (utf8_encoded_to_unichar(p
, &c
) < 0) {
1917 p
++, w
++; /* count invalid chars as 1 */
1921 p
= utf8_next_char(p
);
1922 w
+= unichar_iswide(c
) ? 2 : 1;
1925 /* Already wider than the target, if so, don't do anything */
1926 if (w
>= new_length
)
1927 return clickable
? TAKE_PTR(clickable
) : strdup(str
);
1929 /* How much spaces shall we add? An how much on the left side? */
1930 space
= new_length
- w
;
1931 lspace
= space
* percent
/ 100U;
1933 ret
= new(char, space
+ clickable_length
+ 1);
1937 for (size_t i
= 0; i
< lspace
; i
++)
1939 memcpy(ret
+ lspace
, clickable
?: str
, clickable_length
);
1940 for (size_t i
= lspace
+ clickable_length
; i
< space
+ clickable_length
; i
++)
1943 ret
[space
+ clickable_length
] = 0;
1947 static bool table_data_isempty(TableData
*d
) {
1950 if (d
->type
== TABLE_EMPTY
)
1953 /* Let's also consider an empty strv as truly empty. */
1954 if (IN_SET(d
->type
, TABLE_STRV
, TABLE_STRV_WRAPPED
))
1955 return strv_isempty(d
->strv
);
1957 /* Note that an empty string we do not consider empty here! */
1961 static const char* table_data_color(TableData
*d
) {
1967 /* Let's implicitly color all "empty" cells in grey, in case an "empty_string" is set that is not empty */
1968 if (table_data_isempty(d
))
1974 static const char* table_data_rgap_color(TableData
*d
) {
1978 return d
->rgap_color
;
1983 int table_print(Table
*t
, FILE *f
) {
1984 size_t n_rows
, *minimum_width
, *maximum_width
, display_columns
, *requested_width
,
1985 table_minimum_width
, table_maximum_width
, table_requested_width
, table_effective_width
,
1987 _cleanup_free_
size_t *sorted
= NULL
;
1988 uint64_t *column_weight
, weight_sum
;
1996 /* Ensure we have no incomplete rows */
1997 assert(t
->n_cells
% t
->n_columns
== 0);
1999 n_rows
= t
->n_cells
/ t
->n_columns
;
2000 assert(n_rows
> 0); /* at least the header row must be complete */
2003 /* If sorting is requested, let's calculate an index table we use to lookup the actual index to display with. */
2005 sorted
= new(size_t, n_rows
);
2009 for (size_t i
= 0; i
< n_rows
; i
++)
2010 sorted
[i
] = i
* t
->n_columns
;
2012 typesafe_qsort_r(sorted
, n_rows
, table_data_compare
, t
);
2016 display_columns
= t
->n_display_map
;
2018 display_columns
= t
->n_columns
;
2020 assert(display_columns
> 0);
2022 minimum_width
= newa(size_t, display_columns
);
2023 maximum_width
= newa(size_t, display_columns
);
2024 requested_width
= newa(size_t, display_columns
);
2025 column_weight
= newa0(uint64_t, display_columns
);
2027 for (size_t j
= 0; j
< display_columns
; j
++) {
2028 minimum_width
[j
] = 1;
2029 maximum_width
[j
] = SIZE_MAX
;
2032 for (unsigned pass
= 0; pass
< 2; pass
++) {
2033 /* First pass: determine column sizes */
2035 for (size_t j
= 0; j
< display_columns
; j
++)
2036 requested_width
[j
] = SIZE_MAX
;
2038 bool any_soft
= false;
2040 for (size_t i
= t
->header
? 0 : 1; i
< n_rows
; i
++) {
2043 /* Note that we don't care about ordering at this time, as we just want to determine column sizes,
2044 * hence we don't care for sorted[] during the first pass. */
2045 row
= t
->data
+ i
* t
->n_columns
;
2047 for (size_t j
= 0; j
< display_columns
; j
++) {
2049 size_t req_width
, req_height
;
2051 assert_se(d
= row
[t
->display_map
? t
->display_map
[j
] : j
]);
2053 r
= table_data_requested_width_height(t
, d
,
2054 width
? width
[j
] : SIZE_MAX
,
2055 &req_width
, &req_height
, &any_soft
);
2058 if (r
> 0) { /* Truncated because too many lines? */
2059 _cleanup_free_
char *last
= NULL
;
2062 /* If we are going to show only the first few lines of a cell that has
2063 * multiple make sure that we have enough space horizontally to show an
2064 * ellipsis. Hence, let's figure out the last line, and account for its
2065 * length plus ellipsis. */
2067 field
= table_data_format(t
, d
, false,
2068 width
? width
[j
] : SIZE_MAX
,
2073 assert_se(t
->cell_height_max
> 0);
2074 r
= string_extract_line(field
, t
->cell_height_max
-1, &last
);
2078 req_width
= MAX(req_width
,
2079 utf8_console_width(last
) +
2080 utf8_console_width(special_glyph(SPECIAL_GLYPH_ELLIPSIS
)));
2083 /* Determine the biggest width that any cell in this column would like to have */
2084 if (requested_width
[j
] == SIZE_MAX
||
2085 requested_width
[j
] < req_width
)
2086 requested_width
[j
] = req_width
;
2088 /* Determine the minimum width any cell in this column needs */
2089 if (minimum_width
[j
] < d
->minimum_width
)
2090 minimum_width
[j
] = d
->minimum_width
;
2092 /* Determine the maximum width any cell in this column needs */
2093 if (d
->maximum_width
!= SIZE_MAX
&&
2094 (maximum_width
[j
] == SIZE_MAX
||
2095 maximum_width
[j
] > d
->maximum_width
))
2096 maximum_width
[j
] = d
->maximum_width
;
2098 /* Determine the full columns weight */
2099 column_weight
[j
] += d
->weight
;
2103 /* One space between each column */
2104 table_requested_width
= table_minimum_width
= table_maximum_width
= display_columns
- 1;
2106 /* Calculate the total weight for all columns, plus the minimum, maximum and requested width for the table. */
2108 for (size_t j
= 0; j
< display_columns
; j
++) {
2109 weight_sum
+= column_weight
[j
];
2111 table_minimum_width
+= minimum_width
[j
];
2113 if (maximum_width
[j
] == SIZE_MAX
)
2114 table_maximum_width
= SIZE_MAX
;
2116 table_maximum_width
+= maximum_width
[j
];
2118 table_requested_width
+= requested_width
[j
];
2121 /* Calculate effective table width */
2122 if (t
->width
!= 0 && t
->width
!= SIZE_MAX
)
2123 table_effective_width
= t
->width
;
2124 else if (t
->width
== 0 ||
2125 ((pass
> 0 || !any_soft
) && (pager_have() || !isatty(STDOUT_FILENO
))))
2126 table_effective_width
= table_requested_width
;
2128 table_effective_width
= MIN(table_requested_width
, columns());
2130 if (table_maximum_width
!= SIZE_MAX
&& table_effective_width
> table_maximum_width
)
2131 table_effective_width
= table_maximum_width
;
2133 if (table_effective_width
< table_minimum_width
)
2134 table_effective_width
= table_minimum_width
;
2137 width
= newa(size_t, display_columns
);
2139 if (table_effective_width
>= table_requested_width
) {
2142 /* We have extra room, let's distribute it among columns according to their weights. We first provide
2143 * each column with what it asked for and the distribute the rest. */
2145 extra
= table_effective_width
- table_requested_width
;
2147 for (size_t j
= 0; j
< display_columns
; j
++) {
2150 if (weight_sum
== 0)
2151 width
[j
] = requested_width
[j
] + extra
/ (display_columns
- j
); /* Avoid division by zero */
2153 width
[j
] = requested_width
[j
] + (extra
* column_weight
[j
]) / weight_sum
;
2155 if (maximum_width
[j
] != SIZE_MAX
&& width
[j
] > maximum_width
[j
])
2156 width
[j
] = maximum_width
[j
];
2158 if (width
[j
] < minimum_width
[j
])
2159 width
[j
] = minimum_width
[j
];
2161 delta
= LESS_BY(width
[j
], requested_width
[j
]);
2163 /* Subtract what we just added from the rest */
2169 assert(weight_sum
>= column_weight
[j
]);
2170 weight_sum
-= column_weight
[j
];
2173 break; /* Every column should be happy, no need to repeat calculations. */
2175 /* We need to compress the table, columns can't get what they asked for. We first provide each column
2176 * with the minimum they need, and then distribute anything left. */
2177 bool finalize
= false;
2180 extra
= table_effective_width
- table_minimum_width
;
2182 for (size_t j
= 0; j
< display_columns
; j
++)
2183 width
[j
] = SIZE_MAX
;
2186 bool restart
= false;
2188 for (size_t j
= 0; j
< display_columns
; j
++) {
2191 /* Did this column already get something assigned? If so, let's skip to the next */
2192 if (width
[j
] != SIZE_MAX
)
2195 if (weight_sum
== 0)
2196 w
= minimum_width
[j
] + extra
/ (display_columns
- j
); /* avoid division by zero */
2198 w
= minimum_width
[j
] + (extra
* column_weight
[j
]) / weight_sum
;
2200 if (w
>= requested_width
[j
]) {
2201 /* Never give more than requested. If we hit a column like this, there's more
2202 * space to allocate to other columns which means we need to restart the
2203 * iteration. However, if we hit a column like this, let's assign it the space
2204 * it wanted for good early. */
2206 w
= requested_width
[j
];
2209 } else if (!finalize
)
2214 assert(w
>= minimum_width
[j
]);
2215 delta
= w
- minimum_width
[j
];
2217 assert(delta
<= extra
);
2220 assert(weight_sum
>= column_weight
[j
]);
2221 weight_sum
-= column_weight
[j
];
2223 if (restart
&& !finalize
)
2234 if (!any_soft
) /* Some columns got less than requested. If some cells were "soft",
2235 * let's try to reformat them with the new widths. Otherwise, let's
2241 /* Second pass: show output */
2242 for (size_t i
= t
->header
? 0 : 1; i
< n_rows
; i
++) {
2243 size_t n_subline
= 0;
2248 row
= t
->data
+ sorted
[i
];
2250 row
= t
->data
+ i
* t
->n_columns
;
2253 const char *gap_color
= NULL
;
2254 more_sublines
= false;
2256 for (size_t j
= 0; j
< display_columns
; j
++) {
2257 _cleanup_free_
char *buffer
= NULL
, *extracted
= NULL
;
2258 bool lines_truncated
= false;
2259 const char *field
, *color
= NULL
;
2263 assert_se(d
= row
[t
->display_map
? t
->display_map
[j
] : j
]);
2265 field
= table_data_format(t
, d
, false, width
[j
], NULL
);
2269 r
= string_extract_line(field
, n_subline
, &extracted
);
2273 /* There are more lines to come */
2274 if ((t
->cell_height_max
== SIZE_MAX
|| n_subline
+ 1 < t
->cell_height_max
))
2275 more_sublines
= true; /* There are more lines to come */
2277 lines_truncated
= true;
2282 l
= utf8_console_width(field
);
2284 /* Field is wider than allocated space. Let's ellipsize */
2286 buffer
= ellipsize(field
, width
[j
], /* ellipsize at the end if we truncated coming lines, otherwise honour configuration */
2287 lines_truncated
? 100 : d
->ellipsize_percent
);
2293 if (lines_truncated
) {
2294 _cleanup_free_
char *padded
= NULL
;
2296 /* We truncated more lines of this cell, let's add an
2297 * ellipsis. We first append it, but that might make our
2298 * string grow above what we have space for, hence ellipsize
2299 * right after. This will truncate the ellipsis and add a new
2302 padded
= strjoin(field
, special_glyph(SPECIAL_GLYPH_ELLIPSIS
));
2306 buffer
= ellipsize(padded
, width
[j
], 100);
2311 l
= utf8_console_width(field
);
2315 _cleanup_free_
char *aligned
= NULL
;
2316 /* Field is shorter than allocated space. Let's align with spaces */
2318 aligned
= align_string_mem(field
, d
->url
, width
[j
], d
->align_percent
);
2322 /* Drop trailing white spaces of last column when no cosmetics is set. */
2323 if (j
== display_columns
- 1 &&
2324 (!colors_enabled() || (!table_data_color(d
) && row
!= t
->data
)) &&
2325 (!urlify_enabled() || !d
->url
))
2326 delete_trailing_chars(aligned
, NULL
);
2328 free_and_replace(buffer
, aligned
);
2333 if (l
>= width
[j
] && d
->url
) {
2334 _cleanup_free_
char *clickable
= NULL
;
2336 r
= terminal_urlify(d
->url
, field
, &clickable
);
2340 free_and_replace(buffer
, clickable
);
2344 if (colors_enabled()) {
2346 fputs(gap_color
, f
);
2347 else if (row
== t
->data
) /* underline header line fully, including the column separator */
2348 fputs(ansi_underline(), f
);
2352 fputc(' ', f
); /* column separator left of cell */
2354 if (colors_enabled()) {
2355 color
= table_data_color(d
);
2357 /* Undo gap color */
2358 if (gap_color
|| (color
&& row
== t
->data
))
2359 fputs(ANSI_NORMAL
, f
);
2363 else if (gap_color
&& row
== t
->data
) /* underline header line cell */
2364 fputs(ansi_underline(), f
);
2369 if (colors_enabled() && (color
|| row
== t
->data
))
2370 fputs(ANSI_NORMAL
, f
);
2372 gap_color
= table_data_rgap_color(d
);
2377 } while (more_sublines
);
2380 return fflush_and_check(f
);
2383 int table_format(Table
*t
, char **ret
) {
2384 _cleanup_free_
char *buf
= NULL
;
2385 _cleanup_fclose_
FILE *f
= NULL
;
2389 f
= open_memstream_unlocked(&buf
, &sz
);
2393 r
= table_print(t
, f
);
2399 *ret
= TAKE_PTR(buf
);
2404 size_t table_get_rows(Table
*t
) {
2408 assert(t
->n_columns
> 0);
2409 return t
->n_cells
/ t
->n_columns
;
2412 size_t table_get_columns(Table
*t
) {
2416 assert(t
->n_columns
> 0);
2417 return t
->n_columns
;
2420 int table_set_reverse(Table
*t
, size_t column
, bool b
) {
2422 assert(column
< t
->n_columns
);
2424 if (!t
->reverse_map
) {
2428 t
->reverse_map
= new0(bool, t
->n_columns
);
2429 if (!t
->reverse_map
)
2433 t
->reverse_map
[column
] = b
;
2437 TableCell
*table_get_cell(Table
*t
, size_t row
, size_t column
) {
2442 if (column
>= t
->n_columns
)
2445 i
= row
* t
->n_columns
+ column
;
2446 if (i
>= t
->n_cells
)
2449 return TABLE_INDEX_TO_CELL(i
);
2452 const void *table_get(Table
*t
, TableCell
*cell
) {
2457 d
= table_get_data(t
, cell
);
2464 const void* table_get_at(Table
*t
, size_t row
, size_t column
) {
2467 cell
= table_get_cell(t
, row
, column
);
2471 return table_get(t
, cell
);
2474 static int table_data_to_json(TableData
*d
, JsonVariant
**ret
) {
2479 return json_variant_new_null(ret
);
2483 return json_variant_new_string(ret
, d
->string
);
2486 case TABLE_STRV_WRAPPED
:
2487 return json_variant_new_array_strv(ret
, d
->strv
);
2489 case TABLE_BOOLEAN_CHECKMARK
:
2491 return json_variant_new_boolean(ret
, d
->boolean
);
2493 case TABLE_TIMESTAMP
:
2494 case TABLE_TIMESTAMP_UTC
:
2495 case TABLE_TIMESTAMP_RELATIVE
:
2496 if (d
->timestamp
== USEC_INFINITY
)
2497 return json_variant_new_null(ret
);
2499 return json_variant_new_unsigned(ret
, d
->timestamp
);
2501 case TABLE_TIMESPAN
:
2502 case TABLE_TIMESPAN_MSEC
:
2503 if (d
->timespan
== USEC_INFINITY
)
2504 return json_variant_new_null(ret
);
2506 return json_variant_new_unsigned(ret
, d
->timespan
);
2510 if (d
->size
== UINT64_MAX
)
2511 return json_variant_new_null(ret
);
2513 return json_variant_new_unsigned(ret
, d
->size
);
2516 return json_variant_new_integer(ret
, d
->int_val
);
2519 return json_variant_new_integer(ret
, d
->int8
);
2522 return json_variant_new_integer(ret
, d
->int16
);
2525 return json_variant_new_integer(ret
, d
->int32
);
2528 return json_variant_new_integer(ret
, d
->int64
);
2531 return json_variant_new_unsigned(ret
, d
->uint_val
);
2534 return json_variant_new_unsigned(ret
, d
->uint8
);
2537 return json_variant_new_unsigned(ret
, d
->uint16
);
2540 return json_variant_new_unsigned(ret
, d
->uint32
);
2543 case TABLE_UINT64_HEX
:
2544 return json_variant_new_unsigned(ret
, d
->uint64
);
2547 return json_variant_new_integer(ret
, d
->percent
);
2550 if (d
->ifindex
<= 0)
2551 return json_variant_new_null(ret
);
2553 return json_variant_new_integer(ret
, d
->ifindex
);
2556 return json_variant_new_array_bytes(ret
, &d
->address
, FAMILY_ADDRESS_SIZE(AF_INET
));
2558 case TABLE_IN6_ADDR
:
2559 return json_variant_new_array_bytes(ret
, &d
->address
, FAMILY_ADDRESS_SIZE(AF_INET6
));
2562 return json_variant_new_string(ret
, SD_ID128_TO_STRING(d
->id128
));
2565 return json_variant_new_string(ret
, SD_ID128_TO_UUID_STRING(d
->id128
));
2568 if (!uid_is_valid(d
->uid
))
2569 return json_variant_new_null(ret
);
2571 return json_variant_new_integer(ret
, d
->uid
);
2574 if (!gid_is_valid(d
->gid
))
2575 return json_variant_new_null(ret
);
2577 return json_variant_new_integer(ret
, d
->gid
);
2580 if (!pid_is_valid(d
->pid
))
2581 return json_variant_new_null(ret
);
2583 return json_variant_new_integer(ret
, d
->pid
);
2586 if (!SIGNAL_VALID(d
->int_val
))
2587 return json_variant_new_null(ret
);
2589 return json_variant_new_integer(ret
, d
->int_val
);
2592 if (d
->mode
== MODE_INVALID
)
2593 return json_variant_new_null(ret
);
2595 return json_variant_new_unsigned(ret
, d
->mode
);
2602 static char* string_to_json_field_name(const char *f
) {
2603 /* Tries to make a string more suitable as JSON field name. There are no strict rules defined what a
2604 * field name can be hence this is a bit vague and black magic. Right now we only convert spaces to
2605 * underscores and leave everything as is. */
2607 char *c
= strdup(f
);
2611 for (char *x
= c
; *x
; x
++)
2618 static const char *table_get_json_field_name(Table
*t
, size_t column
) {
2621 return column
< t
->n_json_fields
? t
->json_fields
[column
] : NULL
;
2624 int table_to_json(Table
*t
, JsonVariant
**ret
) {
2625 JsonVariant
**rows
= NULL
, **elements
= NULL
;
2626 _cleanup_free_
size_t *sorted
= NULL
;
2627 size_t n_rows
, display_columns
;
2632 /* Ensure we have no incomplete rows */
2633 assert(t
->n_cells
% t
->n_columns
== 0);
2635 n_rows
= t
->n_cells
/ t
->n_columns
;
2636 assert(n_rows
> 0); /* at least the header row must be complete */
2639 /* If sorting is requested, let's calculate an index table we use to lookup the actual index to display with. */
2641 sorted
= new(size_t, n_rows
);
2647 for (size_t i
= 0; i
< n_rows
; i
++)
2648 sorted
[i
] = i
* t
->n_columns
;
2650 typesafe_qsort_r(sorted
, n_rows
, table_data_compare
, t
);
2654 display_columns
= t
->n_display_map
;
2656 display_columns
= t
->n_columns
;
2657 assert(display_columns
> 0);
2659 elements
= new0(JsonVariant
*, display_columns
* 2);
2665 for (size_t j
= 0; j
< display_columns
; j
++) {
2666 _cleanup_free_
char *mangled
= NULL
;
2670 c
= t
->display_map
? t
->display_map
[j
] : j
;
2672 /* Use explicitly set JSON field name, if we have one. Otherwise mangle the column field value. */
2673 n
= table_get_json_field_name(t
, c
);
2675 const char *formatted
;
2678 assert_se(d
= t
->data
[c
]);
2680 /* Field names must be strings, hence format whatever we got here as a string first */
2681 formatted
= table_data_format(t
, d
, true, SIZE_MAX
, NULL
);
2687 /* Arbitrary strings suck as field names, try to mangle them into something more suitable hence */
2688 mangled
= string_to_json_field_name(formatted
);
2696 r
= json_variant_new_string(elements
+ j
*2, n
);
2701 rows
= new0(JsonVariant
*, n_rows
-1);
2707 for (size_t i
= 1; i
< n_rows
; i
++) {
2711 row
= t
->data
+ sorted
[i
];
2713 row
= t
->data
+ i
* t
->n_columns
;
2715 for (size_t j
= 0; j
< display_columns
; j
++) {
2719 assert_se(d
= row
[t
->display_map
? t
->display_map
[j
] : j
]);
2722 elements
[k
] = json_variant_unref(elements
[k
]);
2724 r
= table_data_to_json(d
, elements
+ k
);
2729 r
= json_variant_new_object(rows
+ i
- 1, elements
, display_columns
* 2);
2734 r
= json_variant_new_array(ret
, rows
, n_rows
- 1);
2738 json_variant_unref_many(rows
, n_rows
-1);
2743 json_variant_unref_many(elements
, display_columns
*2);
2750 int table_print_json(Table
*t
, FILE *f
, JsonFormatFlags flags
) {
2751 _cleanup_(json_variant_unrefp
) JsonVariant
*v
= NULL
;
2756 if (flags
& JSON_FORMAT_OFF
) /* If JSON output is turned off, use regular output */
2757 return table_print(t
, f
);
2762 r
= table_to_json(t
, &v
);
2766 json_variant_dump(v
, flags
, f
, NULL
);
2768 return fflush_and_check(f
);
2771 int table_print_with_pager(
2773 JsonFormatFlags json_format_flags
,
2774 PagerFlags pager_flags
,
2782 /* An all-in-one solution for showing tables, and turning on a pager first. Also optionally suppresses
2783 * the table header and logs about any error. */
2785 if (json_format_flags
& (JSON_FORMAT_OFF
|JSON_FORMAT_PRETTY
|JSON_FORMAT_PRETTY_AUTO
))
2786 pager_open(pager_flags
);
2788 saved_header
= t
->header
;
2789 t
->header
= show_header
;
2790 r
= table_print_json(t
, stdout
, json_format_flags
);
2791 t
->header
= saved_header
;
2793 return table_log_print_error(r
);
2798 int table_set_json_field_name(Table
*t
, size_t column
, const char *name
) {
2806 m
= MAX(column
+ 1, t
->n_json_fields
);
2807 if (!GREEDY_REALLOC0(t
->json_fields
, m
))
2810 r
= free_and_strdup(t
->json_fields
+ column
, name
);
2814 t
->n_json_fields
= m
;
2817 if (column
>= t
->n_json_fields
)
2820 t
->json_fields
[column
] = mfree(t
->json_fields
[column
]);