/src/barebox/common/console_countdown.c
Line | Count | Source |
1 | | // SPDX-License-Identifier: GPL-2.0-only |
2 | | /* |
3 | | * console_countdown - contdown on the console - interruptible by a keypress |
4 | | * |
5 | | * Copyright (c) 2007 Sascha Hauer <s.hauer@pengutronix.de>, Pengutronix |
6 | | */ |
7 | | |
8 | | #include <clock.h> |
9 | | #include <command.h> |
10 | | #include <errno.h> |
11 | | #include <console_countdown.h> |
12 | | #include <stdio.h> |
13 | | #include <readkey.h> |
14 | | |
15 | | static bool console_countdown_timeout_abort; |
16 | | |
17 | | void console_countdown_abort(const char *reason) |
18 | 0 | { |
19 | 0 | if (reason && !console_countdown_timeout_abort) |
20 | 0 | pr_info("\nCount down aborted by %s\n", reason); |
21 | 0 | console_countdown_timeout_abort = true; |
22 | 0 | } |
23 | | |
24 | | static int key_in_list(char key, const char *keys) |
25 | 0 | { |
26 | 0 | if (!keys) |
27 | 0 | return false; |
28 | | |
29 | 0 | while (*keys) { |
30 | 0 | if (key == *keys) |
31 | 0 | return true; |
32 | 0 | keys++; |
33 | 0 | } |
34 | | |
35 | 0 | return false; |
36 | 0 | } |
37 | | |
38 | | int console_countdown(int timeout_s, unsigned flags, const char *keys, |
39 | | char *out_key) |
40 | 0 | { |
41 | 0 | uint64_t start, second; |
42 | 0 | int countdown, ret = -EINTR; |
43 | 0 | int key = 0; |
44 | |
|
45 | 0 | start = get_time_ns(); |
46 | 0 | second = start; |
47 | |
|
48 | 0 | countdown = timeout_s; |
49 | |
|
50 | 0 | if (!(flags & CONSOLE_COUNTDOWN_SILENT)) |
51 | 0 | printf("%4d", countdown--); |
52 | |
|
53 | 0 | do { |
54 | 0 | if (tstc()) { |
55 | 0 | key = getchar(); |
56 | 0 | if (key >= 0) { |
57 | 0 | if (key_in_list(key, keys)) |
58 | 0 | goto out; |
59 | 0 | if (flags & CONSOLE_COUNTDOWN_ANYKEY) |
60 | 0 | goto out; |
61 | 0 | if (flags & CONSOLE_COUNTDOWN_RETURN && (key == '\n' || key == '\r')) |
62 | 0 | goto out; |
63 | 0 | if (flags & CONSOLE_COUNTDOWN_CTRLC && key == CTL_CH('c')) |
64 | 0 | goto out; |
65 | 0 | } |
66 | 0 | key = 0; |
67 | 0 | } |
68 | 0 | if ((flags & CONSOLE_COUNTDOWN_EXTERN) && |
69 | 0 | console_countdown_timeout_abort) |
70 | 0 | goto out; |
71 | 0 | if (!(flags & CONSOLE_COUNTDOWN_SILENT) && |
72 | 0 | is_timeout(second, SECOND)) { |
73 | 0 | printf("\b\b\b\b%4d", countdown--); |
74 | 0 | second += SECOND; |
75 | 0 | } |
76 | 0 | } while (!is_timeout(start, timeout_s * SECOND)); |
77 | | |
78 | 0 | if ((flags & CONSOLE_COUNTDOWN_EXTERN) && |
79 | 0 | console_countdown_timeout_abort) |
80 | 0 | goto out; |
81 | | |
82 | 0 | ret = 0; |
83 | |
|
84 | 0 | out: |
85 | 0 | if (!(flags & CONSOLE_COUNTDOWN_SILENT)) |
86 | 0 | printf("\n"); |
87 | 0 | if (key && out_key) |
88 | 0 | *out_key = key; |
89 | 0 | console_countdown_timeout_abort = false; |
90 | |
|
91 | 0 | return ret; |
92 | 0 | } |