terminal-util: beef up show_menu()

This modernizes the function a bit, and adds some bits:

1. whether to show numbers before entries is now optional, and if they
   are shown they are displayed in grey.

2. a common prefix can now be grayed out (later useful for completion
   support)

3. some variables have been named to clarify their purpose

4. the table display dimensions can now be auto-sized (by specifying
   SIZE_MAX and number of columns and column width)
This commit is contained in:
Lennart Poettering
2025-02-17 15:21:13 +01:00
parent 8fcd85768b
commit b6478aa12f
4 changed files with 90 additions and 20 deletions
+15 -4
View File
@@ -135,7 +135,13 @@ static void print_welcome(int rfd) {
done = true;
}
static int prompt_loop(int rfd, const char *text, char **l, unsigned percentage, bool (*is_valid)(int rfd, const char *name), char **ret) {
static int prompt_loop(
int rfd,
const char *text,
char **l,
unsigned ellipsize_percentage,
bool (*is_valid)(int rfd, const char *name),
char **ret) {
int r;
assert(text);
@@ -144,7 +150,6 @@ static int prompt_loop(int rfd, const char *text, char **l, unsigned percentage,
for (;;) {
_cleanup_free_ char *p = NULL;
unsigned u;
r = ask_string(&p, strv_isempty(l) ? "%s %s (empty to skip): "
: "%s %s (empty to skip, \"list\" to list options): ",
@@ -159,14 +164,20 @@ static int prompt_loop(int rfd, const char *text, char **l, unsigned percentage,
if (!strv_isempty(l)) {
if (streq(p, "list")) {
r = show_menu(l, 3, 20, percentage);
r = show_menu(l,
/* n_columns= */ 3,
/* column_width= */ 20,
ellipsize_percentage,
/* grey_prefix= */ NULL,
/* with_numbers= */ true);
if (r < 0)
return r;
return log_error_errno(r, "Failed to show menu: %m");
putchar('\n');
continue;
}
unsigned u;
r = safe_atou(p, &u);
if (r >= 0) {
if (u <= 0 || u > strv_length(l)) {