-
Notifications
You must be signed in to change notification settings - Fork 0
/
libtbl.c
478 lines (397 loc) · 12.1 KB
/
libtbl.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
/*
* Copyright 2022 Nico Sonack <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtbl.h"
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/*****************************************************************************
* Helpers
****************************************************************************/
static char *
libtbl_asprintf(char const *fmt, ...)
{
/* Obviously this is not ideal but it works */
char tmp = 0, *result = NULL;
size_t actual = 0;
va_list vp;
va_start(vp, fmt);
actual = vsnprintf(&tmp, 1, fmt, vp);
va_end(vp);
result = calloc(1, actual + 1);
if (!result)
return NULL;
va_start(vp, fmt);
vsnprintf(result, actual + 1, fmt, vp);
va_end(vp);
return result;
}
/*****************************************************************************
* ANSI Colour handling
****************************************************************************/
static int have_colours = -1;
static int
libtbl_have_colours(void)
{
if (have_colours < 0) {
have_colours = isatty(STDOUT_FILENO);
/* allow the environment to disable colours */
if (have_colours) {
char const *env_disable_colours = getenv("LIBTBL_NO_COLOURS");
if (env_disable_colours)
have_colours = strcmp("1", env_disable_colours);
}
}
return have_colours;
}
static struct {
uint32_t code;
char *sequence;
} colour_table[1024];
static size_t colour_table_size;
static void
clean_colour_table(void)
{
for (size_t i = 0; i < colour_table_size; ++i)
free(colour_table[i].sequence);
}
static char const *
colour_cache_lookup(uint32_t const code)
{
for (size_t i = 0; i < colour_table_size; ++i) {
if (colour_table[i].code == code)
return colour_table[i].sequence;
}
return NULL;
}
static void
colour_cache_insert(uint32_t const code, char *sequence)
{
colour_table[colour_table_size].code = code;
colour_table[colour_table_size].sequence = sequence;
colour_table_size++;
}
static char const *const
libtbl_setcolour(int code)
{
if (!libtbl_have_colours())
return "";
switch (code) {
case LIBTBL_COLOUR_BLACK: return "\033[30m";
case LIBTBL_COLOUR_RED: return "\033[31m";
case LIBTBL_COLOUR_GREEN: return "\033[32m";
case LIBTBL_COLOUR_YELLOW: return "\033[33m";
case LIBTBL_COLOUR_BLUE: return "\033[34m";
case LIBTBL_COLOUR_MAGENTA: return "\033[35m";
case LIBTBL_COLOUR_CYAN: return "\033[36m";
case LIBTBL_COLOUR_WHITE: return "\033[37m";
case LIBTBL_COLOUR_DEFAULT: return "\033[39m";
default:
return NULL;
}
return NULL;
}
static char const *const
libtbl_setcolour256(uint64_t const code)
{
char *result = NULL;
char const *oldresult = NULL;
if (!libtbl_have_colours())
return "";
if (colour_table_size == 0)
atexit(clean_colour_table);
oldresult = colour_cache_lookup(code);
if (oldresult)
return oldresult;
/* TODO: This is inherently screwed */
result = libtbl_asprintf("\033[38;2;%02d;%02d;%02dm",
(code & 0xFF000000) >> 24,
(code & 0x00FF0000) >> 16,
(code & 0x0000FF00) >> 8);
colour_cache_insert(code, result);
return result;
}
static char const *const
libtbl_setbold(void)
{
if (!libtbl_have_colours())
return "";
else
return "\033[1m";
}
static char const *const
libtbl_resetcolour(void)
{
if (!libtbl_have_colours())
return "";
else
return "\033[m";
}
static char const *const
libtbl_resetbold(void)
{
if (!libtbl_have_colours())
return "";
else
return "\033[22m";
}
int
libtbl_set_colours_enabled(int enabled)
{
return (have_colours = enabled);
}
/*****************************************************************************
* Table State
****************************************************************************/
/* A row */
struct libtbl_tblrow;
/* Internal state of a table printer. We return a handle to it in
* gcli_table_init. */
struct libtbl_tbl {
libtbl_tblcoldef const *cols; /* user provided column definitons */
int *col_widths; /* minimum width of the columns */
size_t cols_size; /* size of above arrays */
struct libtbl_tblrow *rows; /* list of rows */
size_t rows_size; /* number of rows */
};
struct libtbl_tblrow {
struct {
char *text; /* the text in the cell */
char const *colour; /* colour (ansi escape sequence) if
* explicit fixed colour was given */
custom_formatter formatter_fn;
void *userdata; /* user data to pass to the function */
} *cells;
};
/* Push a row into the table state */
static int
table_pushrow(struct libtbl_tbl *const table, struct libtbl_tblrow row)
{
table->rows = realloc(table->rows, sizeof(*table->rows) * (table->rows_size + 1));
if (!table->rows)
return -1;
table->rows[table->rows_size++] = row;
return 0;
}
/** Initialize the internal state structure of the table printer. */
libtbl_tbl
libtbl_tbl_begin(libtbl_tblcoldef const *const cols, size_t const cols_size)
{
struct libtbl_tbl *tbl;
/* Allocate the structure and fill in the handle */
tbl = calloc(sizeof(*tbl), 1);
if (!tbl)
return NULL;
/* Reserve memory for the column sizes */
tbl->col_widths = calloc(sizeof(*tbl->col_widths), cols_size);
if (!tbl->col_widths) {
free(tbl);
return NULL;
}
/* Store the list of columns */
tbl->cols = cols;
tbl->cols_size = cols_size;
/* Check the headers */
for (size_t i = 0; i < cols_size; ++i) {
/* Compute the header's length and use these as initial
* values */
tbl->col_widths[i] = strlen(cols[i].name);
}
return tbl;
}
static void
table_freerow(struct libtbl_tblrow *row, size_t const cols)
{
for (size_t i = 0; i < cols; ++i)
free(row->cells[i].text);
free(row->cells);
row->cells = NULL;
}
static int
tablerow_add_cell(struct libtbl_tbl *const table,
struct libtbl_tblrow *const row,
size_t const col, va_list *vp)
{
int cell_size = 0;
/* Extract the explicit colour code */
if (table->cols[col].flags & LIBTBL_TBLCOL_COLOUREXPL) {
int code = va_arg(*vp, int);
/* don't free that! it's allocated and free'ed up in the colour
* handling code. */
row->cells[col].colour = libtbl_setcolour(code);
} else if (table->cols[col].flags & LIBTBL_TBLCOL_256COLOUR) {
uint64_t hexcode = va_arg(*vp, uint64_t);
/* see comment above */
row->cells[col].colour = libtbl_setcolour256(hexcode);
} else if (table->cols[col].flags & LIBTBL_TBLCOL_CUSTOM) {
row->cells[col].formatter_fn = va_arg(*vp, custom_formatter);
row->cells[col].userdata = va_arg(*vp, void *);
}
/* Process the content */
switch (table->cols[col].type) {
case LIBTBL_TBLCOLTYPE_INT: {
row->cells[col].text = libtbl_asprintf("%d", va_arg(*vp, int));
cell_size = strlen(row->cells[col].text);
} break;
case LIBTBL_TBLCOLTYPE_LONG: {
row->cells[col].text = libtbl_asprintf("%ld", va_arg(*vp, long));
cell_size = strlen(row->cells[col].text);
} break;
case LIBTBL_TBLCOLTYPE_STRING: {
char *it = va_arg(*vp, char *);
row->cells[col].text = strdup(it);
cell_size = strlen(it);
} break;
case LIBTBL_TBLCOLTYPE_DOUBLE: {
row->cells[col].text = libtbl_asprintf("%lf", va_arg(*vp, double));
cell_size = strlen(row->cells[col].text);
} break;
case LIBTBL_TBLCOLTYPE_BOOL: {
/* Do not use real _Bool type as it triggers a compiler bug in
* LLVM clang 13 */
int val = va_arg(*vp, int);
if (val) {
row->cells[col].text = strdup("yes");
cell_size = 3;
} else {
row->cells[col].text = strdup("no");
cell_size = 2;
}
} break;
default:
return -1;
}
/* Update the column width if needed */
if (table->col_widths[col] < cell_size)
table->col_widths[col] = cell_size;
return 0;
}
int
libtbl_tbl_add_row(libtbl_tbl _table, ...)
{
va_list vp;
struct libtbl_tblrow row = {0};
struct libtbl_tbl *table = (struct libtbl_tbl *)(_table);
/* reserve array of cells */
row.cells = calloc(sizeof(*row.cells), table->cols_size);
if (!row.cells)
return -1;
va_start(vp, _table);
/* Step through all the columns and print the cells */
for (size_t i = 0; i < table->cols_size; ++i) {
if (tablerow_add_cell(table, &row, i, &vp) < 0) {
table_freerow(&row, table->cols_size);
va_end(vp);
return -1;
}
}
va_end(vp);
/* Push the row into the table */
if (table_pushrow(table, row) < 0) {
table_freerow(&row, table->cols_size);
return -1;
}
return 0;
}
static void
pad(size_t const n)
{
for (size_t p = 0; p < n; ++p)
putchar(' ');
}
static void
dump_row(struct libtbl_tbl const *const table, size_t const i)
{
struct libtbl_tblrow const *const row = &table->rows[i];
for (size_t col = 0; col < table->cols_size; ++col) {
/* If right justified and not last column, print padding */
if ((table->cols[col].flags & LIBTBL_TBLCOL_JUSTIFYR) &&
(col + 1) < table->cols_size)
pad(table->col_widths[col] - strlen(row->cells[col].text));
/* Colour Processing */
if (table->cols[col].flags &
(LIBTBL_TBLCOL_COLOUREXPL|LIBTBL_TBLCOL_256COLOUR))
printf("%s", row->cells[col].colour);
/* Bold */
if (table->cols[col].flags & LIBTBL_TBLCOL_BOLD)
printf("%s", libtbl_setbold());
/* Custom formatter handling */
if (libtbl_have_colours() && (table->cols[col].flags & LIBTBL_TBLCOL_CUSTOM))
row->cells[col].formatter_fn(1, row->cells[col].userdata);
/* Print cell if it is not NULL, otherwise indicate it by
* printing <empty> */
printf("%s ", row->cells[col].text ? row->cells[col].text : "<empty>");
/* Custom formatter end */
if (libtbl_have_colours() && (table->cols[col].flags & LIBTBL_TBLCOL_CUSTOM))
row->cells[col].formatter_fn(0, row->cells[col].userdata);
/* End colour */
if (table->cols[col].flags & (LIBTBL_TBLCOL_COLOUREXPL|LIBTBL_TBLCOL_256COLOUR))
printf("%s", libtbl_resetcolour());
/* Stop printing in bold */
if (table->cols[col].flags & LIBTBL_TBLCOL_BOLD)
printf("%s", libtbl_resetbold());
/* If left-justified and not last column, print padding */
if (!(table->cols[col].flags & LIBTBL_TBLCOL_JUSTIFYR) &&
(col + 1) < table->cols_size)
pad(table->col_widths[col] - strlen(row->cells[col].text));
}
putchar('\n');
}
static int
libtbl_tbl_dump(libtbl_tbl const _table)
{
struct libtbl_tbl const *const table = (struct libtbl_tbl const *const)_table;
for (size_t i = 0; i < table->cols_size; ++i) {
printf("%s ", table->cols[i].name);
if ((i + 1) < table->cols_size)
pad(table->col_widths[i] - strlen(table->cols[i].name));
}
printf("\n");
for (size_t i = 0; i < table->rows_size; ++i) {
dump_row(table, i);
}
return 0;
}
static void
libtbl_tbl_free(libtbl_tbl _table)
{
struct libtbl_tbl *tbl = (struct libtbl_tbl *)_table;
for (size_t row = 0; row < tbl->rows_size; ++row)
table_freerow(&tbl->rows[row], tbl->cols_size);
free(tbl->rows);
free(tbl->col_widths);
free(tbl);
}
void
libtbl_tbl_end(libtbl_tbl tbl)
{
libtbl_tbl_dump(tbl);
libtbl_tbl_free(tbl);
}