Debian Codegraph @

src/shared/prompt-util.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "sd-varlink.h"
6
7 #include "alloc-util.h"
8 #include "glyph-util.h"
9 #include "log.h"
10 #include "macro.h"
11 #include "os-util.h"
12 #include "parse-util.h"
13 #include "pretty-print.h"
14 #include "prompt-util.h"
15 #include "stdio-util.h"
16 #include "string-util.h"
17 #include "strv.h"
18 #include "terminal-util.h"
19
20 typedef struct CompletionData {
21 char **menu; /* What to show in menu */
22 char **accepted; /* What to accept (usually larger than the menu, but may be NULL if same) */
23 } CompletionData;
24
25 static int get_completions(
26 const char *key,
27 GetCompletionsFlags flags,
28 char ***ret_list,
29 void *userdata) {
30
31 CompletionData *data = ASSERT_PTR(userdata);
32 int r;
33
34 assert(ret_list);
35
36 /* Figure out the list to operate on. We'll generally work based on the "accepted" list, if it is
37 * set. If not we'll operate with the full menu. When doing pre-selection we'll also pick the menu */
38 char **l = data->accepted && !FLAGS_SET(flags, GET_COMPLETIONS_PRESELECT) ? data->accepted : data->menu;
39
40 if (strv_isempty(l)) {
41 *ret_list = NULL;
42 return 0;
43 }
44
45 _cleanup_strv_free_ char **copy = strv_copy(l);
46 if (!copy)
47 return -ENOMEM;
48
49 /* Never consider "list" for preselecting an item, but do consider it when doing a regular completion */
50 if (!FLAGS_SET(flags, GET_COMPLETIONS_PRESELECT)) {
51 r = strv_extend(&copy, "list");
52 if (r < 0)
53 return r;
54 }
55
56 *ret_list = TAKE_PTR(copy);
57 return 0;
58 }
59
60 int prompt_loop(
61 const char *text,
62 Glyph emoji,
63 const char *prefill, /* if non-NULL: prefill prompt with this string */
64 char **menu, /* if non-NULL: choices to suggest */
65 char **accepted, /* if non-NULL: choices to accept (should be a superset of 'menu') */
66 unsigned ellipsize_percentage,
67 size_t n_columns,
68 size_t column_width,
69 int (*is_valid)(const char *name, void *userdata),
70 int (*refresh)(char ***ret_menu, char ***ret_accepted, void *userdata),
71 void *userdata,
72 PromptFlags flags,
73 char **ret) {
74
75 _cleanup_strv_free_ char **refreshed_menu = NULL, **refreshed_accepted = NULL;
76 int r;
77
78 assert(text);
79 assert(ret);
80
81 if (!emoji_enabled()) /* If emojis aren't available, simpler unicode chars might still be around,
82 * hence try to downgrade. (Consider the Linux Console!) */
83 emoji = GLYPH_TRIANGULAR_BULLET;
84
85 /* If requested show menu right-away */
86 if (FLAGS_SET(flags, PROMPT_SHOW_MENU_NOW) && !strv_isempty(menu)) {
87 r = show_menu(menu,
88 n_columns,
89 column_width,
90 ellipsize_percentage,
91 /* grey_prefix= */ NULL,
92 /* with_numbers= */ true);
93 if (r < 0)
94 return log_error_errno(r, "Failed to show menu: %m");
95
96 putchar('\n');
97 }
98
99 for (;;) {
100 _cleanup_free_ char *a = NULL;
101
102 if (!FLAGS_SET(flags, PROMPT_HIDE_MENU_HINT) && !strv_isempty(menu))
103 if (!strextend_with_separator(&a, ", ", "\"list\" to list options"))
104 return log_oom();
105 if (!FLAGS_SET(flags, PROMPT_HIDE_SKIP_HINT) && FLAGS_SET(flags, PROMPT_MAY_SKIP))
106 if (!strextend_with_separator(&a, ", ", "empty to skip"))
107 return log_oom();
108
109 if (a) {
110 char *b = strjoin(" (", a, ")");
111 if (!b)
112 return log_oom();
113
114 free_and_replace(a, b);
115 }
116
117 _cleanup_free_ char *p = NULL;
118 r = ask_string_full(
119 &p,
120 prefill,
121 get_completions,
122 &(CompletionData) { menu, accepted },
123 "%s%s%s%s: ",
124 emoji >= 0 ? glyph(emoji) : "",
125 emoji >= 0 ? " " : "",
126 text,
127 strempty(a));
128 if (r < 0)
129 return log_error_errno(r, "Failed to query user: %m");
130
131 if (isempty(p)) {
132 if (FLAGS_SET(flags, PROMPT_MAY_SKIP)) {
133 log_info("No data entered, skipping.");
134 *ret = NULL;
135 return 0;
136 }
137
138 log_info("No data entered, try again.");
139 continue;
140 }
141
142 /* NB: here we treat non-NULL but empty list different from NULL list. In the former case we
143 * support the "list" command, in the latter we don't. */
144 if (FLAGS_SET(flags, PROMPT_SHOW_MENU) && streq(p, "list")) {
145 putchar('\n');
146
147 if (refresh) {
148 _cleanup_strv_free_ char **rm = NULL, **ra = NULL;
149
150 /* If a refresh method is provided, then use it now to refresh the menu
151 * before redisplaying it. */
152 r = refresh(&rm, &ra, userdata);
153 if (r < 0)
154 return r;
155
156 strv_free_and_replace(refreshed_menu, rm);
157 strv_free_and_replace(refreshed_accepted, ra);
158
159 menu = refreshed_menu;
160 accepted = refreshed_accepted;
161 }
162
163 if (strv_isempty(menu)) {
164 log_warning("No entries known.");
165 continue;
166 }
167
168 r = show_menu(menu,
169 n_columns,
170 column_width,
171 ellipsize_percentage,
172 /* grey_prefix= */ NULL,
173 /* with_numbers= */ true);
174 if (r < 0)
175 return log_error_errno(r, "Failed to show menu: %m");
176
177 putchar('\n');
178 continue;
179 }
180
181 unsigned u;
182 if (safe_atou(p, &u) >= 0) {
183 if (u <= 0 || u > strv_length(menu)) {
184 log_error("Specified entry number out of range.");
185 continue;
186 }
187
188 log_info("Selected '%s'.", menu[u-1]);
189 return strdup_to_full(ret, menu[u-1]);
190 }
191
192 bool good = accepted ? strv_contains(accepted, p) : true;
193 if (good && is_valid) {
194 r = is_valid(p, userdata);
195 if (r < 0)
196 return r;
197
198 good = good && r;
199 }
200 if (good) {
201 *ret = TAKE_PTR(p);
202 return 1;
203 }
204
205 if (!FLAGS_SET(flags, PROMPT_SILENT_VALIDATE)) {
206 /* Be more helpful to the user, and give a hint what the user might have wanted to type. */
207 const char *best_match = strv_find_closest(accepted ?: menu, p);
208 if (best_match)
209 log_error("Invalid input '%s', did you mean '%s'?", p, best_match);
210 else
211 log_error("Invalid input '%s'.", p);
212 }
213 }
214 }
215
216 /* Default: bright white on blue background */
217 #define ANSI_COLOR_CHROME "\x1B[0;44;1;37m"
218
219 static unsigned chrome_visible = 0; /* if non-zero chrome is visible and value is saved number of lines */
220
221 int chrome_show(
222 const char *top,
223 const char *bottom) {
224 int r;
225
226 assert(top);
227
228 /* Shows our "chrome", i.e. a blue bar at top and bottom. Reduces the scrolling area to the area in
229 * between */
230
231 if (terminal_is_dumb())
232 return 0;
233
234 unsigned n = lines();
235 if (n < 12) /* Do not bother with the chrome on tiny screens */
236 return 0;
237
238 _cleanup_free_ char *b = NULL, *ansi_color_reverse = NULL;
239 if (!bottom) {
240 _cleanup_free_ char *pretty_name = NULL, *os_name = NULL, *ansi_color = NULL, *documentation_url = NULL, *fancy_name = NULL;
241
242 r = parse_os_release(
243 /* root= */ NULL,
244 "PRETTY_NAME", &pretty_name,
245 "FANCY_NAME", &fancy_name,
246 "NAME", &os_name,
247 "ANSI_COLOR", &ansi_color,
248 "ANSI_COLOR_REVERSE", &ansi_color_reverse,
249 "DOCUMENTATION_URL", &documentation_url);
250 if (r < 0)
251 log_full_errno(r == -ENOENT ? LOG_DEBUG : LOG_WARNING, r,
252 "Failed to read os-release file, ignoring: %m");
253
254 const char *m = os_release_pretty_name(pretty_name, os_name);
255 const char *c = ansi_color ?: "0";
256
257 if (ansi_color_reverse) {
258 _cleanup_free_ char *j = strjoin("\x1B[0;", ansi_color_reverse, "m");
259 if (!j)
260 return log_oom_debug();
261
262 free_and_replace(ansi_color_reverse, j);
263 }
264
265 if (use_fancy_name(unescape_fancy_name(&fancy_name)))
266 b = asprintf_safe("\x1B[0;%sm \x1B[0m%s\x1B[0;%sm %s", c, fancy_name, c, ansi_color_reverse ?: ANSI_COLOR_CHROME);
267 else
268 b = asprintf_safe("\x1B[0;%sm %s %s", c, m, ansi_color_reverse ?: ANSI_COLOR_CHROME);
269 if (!b)
270 return log_oom_debug();
271
272 if (documentation_url) {
273 _cleanup_free_ char *u = NULL;
274 if (terminal_urlify(documentation_url, "documentation", &u) < 0)
275 return log_oom_debug();
276
277 if (!strextend(&b, " - See ", u, " for more information."))
278 return log_oom_debug();
279 }
280
281 bottom = b;
282 }
283
284 const char *chrome_color = ansi_color_reverse ?: ANSI_COLOR_CHROME;
285
286 WITH_BUFFERED_STDOUT;
287
288 fputs("\033[H" /* move home */
289 "\033[2J", /* clear screen */
290 stdout);
291
292 /* Blue bar on top (followed by one empty regular one) */
293 printf("\x1B[1;1H" /* jump to top left */
294 "%1$s" ANSI_ERASE_TO_END_OF_LINE "\n"
295 "%1$s %2$s" ANSI_ERASE_TO_END_OF_LINE "\n"
296 "%1$s" ANSI_ERASE_TO_END_OF_LINE "\n"
297 ANSI_NORMAL ANSI_ERASE_TO_END_OF_LINE,
298 chrome_color,
299 top);
300
301 /* Blue bar on bottom (with one empty regular one before) */
302 printf("\x1B[%1$u;1H" /* jump to bottom left, above the blue bar */
303 ANSI_NORMAL ANSI_ERASE_TO_END_OF_LINE "\n"
304 "%2$s" ANSI_ERASE_TO_END_OF_LINE "\n"
305 "%2$s %3$s" ANSI_ERASE_TO_END_OF_LINE "\n"
306 "%2$s" ANSI_ERASE_TO_END_OF_LINE ANSI_NORMAL,
307 n - 3,
308 chrome_color,
309 bottom);
310
311 /* Reduce scrolling area (DECSTBM), cutting off top and bottom bars */
312 printf("\x1B[5;%ur", n - 4);
313
314 /* Position cursor in fifth line */
315 fputs("\x1B[5;1H", stdout);
316
317 fflush(stdout);
318
319 chrome_visible = n;
320 return 1;
321 }
322
323 void chrome_hide(void) {
324 int r;
325
326 if (chrome_visible == 0)
327 return;
328
329 unsigned n = chrome_visible;
330 chrome_visible = 0;
331
332 unsigned saved_row = 0;
333 r = terminal_get_cursor_position(STDIN_FILENO, STDOUT_FILENO, &saved_row, /* ret_column= */ NULL);
334 if (r < 0)
335 return (void) log_debug_errno(r, "Failed to get terminal cursor position, skipping chrome hiding: %m");
336
337 WITH_BUFFERED_STDOUT;
338
339 /* Erase Blue bar on bottom */
340 assert(n >= 2);
341 printf("\x1B[%u;1H"
342 ANSI_NORMAL ANSI_ERASE_TO_END_OF_LINE "\n"
343 ANSI_NORMAL ANSI_ERASE_TO_END_OF_LINE "\n"
344 ANSI_NORMAL ANSI_ERASE_TO_END_OF_LINE,
345 n - 2);
346
347 /* Reset scrolling area (DECSTBM) */
348 fputs("\x1B[r\n", stdout);
349
350 /* Place the cursor where it was again, but not in the former blue bars */
351 assert(n >= 9);
352 unsigned k = CLAMP(saved_row, 5U, n - 4);
353 printf("\x1B[%u;1H", k);
354
355 fflush(stdout);
356 }
357
358 static int vl_on_reply(sd_varlink *link, sd_json_variant *parameters, const char *error_id, sd_varlink_reply_flags_t flags, void *userdata) {
359 assert(link);
360
361 /* We want to keep the link around (since its lifetime defines the lifetime of the console muting),
362 * hence let's detach it from the event loop now, and then exit the event loop. */
363
364 _cleanup_(sd_event_unrefp) sd_event *e = sd_event_ref(ASSERT_PTR(sd_varlink_get_event(link)));
365 sd_varlink_detach_event(link);
366 (void) sd_event_exit(e, (error_id || !FLAGS_SET(flags, SD_VARLINK_REPLY_CONTINUES)) ? -EBADR : 0);
367
368 return 0;
369 }
370
371 int mute_console(sd_varlink **ret_link) {
372 int r;
373
374 assert(ret_link);
375
376 /* Talks to the MuteConsole service, and asks for output to the console to be muted, as long as the
377 * connection is retained */
378
379 _cleanup_(sd_varlink_flush_close_unrefp) sd_varlink *link = NULL;
380 r = sd_varlink_connect_address(&link, "/run/systemd/io.systemd.MuteConsole");
381 if (r < 0)
382 return log_debug_errno(r, "Failed to connect to console muting service: %m");
383
384 _cleanup_(sd_event_unrefp) sd_event* event = NULL;
385 r = sd_event_new(&event);
386 if (r < 0)
387 return r;
388
389 r = sd_varlink_attach_event(link, event, /* priority= */ 0);
390 if (r < 0)
391 return r;
392
393 r = sd_varlink_bind_reply(link, vl_on_reply);
394 if (r < 0)
395 return r;
396
397 r = sd_varlink_set_relative_timeout(link, UINT64_MAX);
398 if (r < 0)
399 return log_debug_errno(r, "Failed to disable method call time-out: %m");
400
401 r = sd_varlink_observe(link, "io.systemd.MuteConsole.Mute", /* parameters= */ NULL);
402 if (r < 0)
403 return log_debug_errno(r, "Failed to issue Mute() call to io.systemd.MuteConsole: %m");
404
405 /* Now run the event loop, it will exit on the first reply, which is when we know the console output
406 * is now muted. */
407 r = sd_event_loop(event);
408 if (r < 0)
409 return r;
410
411 *ret_link = TAKE_PTR(link);
412 return 0;
413 }