aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils.c
blob: 7a762f7b4675a20161e9e0292467eebb2e59879b (plain) (blame)
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
#include "utils.h"
#include "err.h"
#include "fm.h"
#include "log.h"
#include <limits.h>
#include <ncurses.h>

int
get_input(const char *prompt, char *buf, size_t len)
{
	if (!prompt || !buf)
		return SF_ERR_INVALID_ARG;

	int ch;
	curs_set(1);

	werase(status_window->win);
	mvwprintw(status_window->win, 0, 0, "%s%s", prompt, buf);
	wrefresh(status_window->win);

	while ((ch = getch())) {
		werase(status_window->win);

		if (ch >= 32 && ch <= 126) {
			buf[len++] = ch;
		} else if (ch == KEY_BACKSPACE || ch == 127 || ch == '\b') {
			buf[--len] = '\0';
		} else if (ch == 27) {
			werase(status_window->win);
			curs_set(0);
			return SF_ERR_CANCEL;
		} else if (ch == KEY_ENTER || ch == '\n' || ch == '\r') {
			if (len < PATH_MAX) {
				buf[++len] = '\0';
				curs_set(0);
				return SF_OK;
			} else {
				return SF_ERR_INVALID_LEN;
			}
		} else {
			continue;
		}

		mvwprintw(status_window->win, 0, 0, "%s%s", prompt, buf);
		wrefresh(status_window->win);
	}

	curs_set(0);

	return SF_OK;
}

bool
y_or_n(const char *prompt)
{
	int ch;

	werase(status_window->win);
	mvwprintw(status_window->win, 0, 0, "%s (y or n)", prompt);
	wrefresh(status_window->win);
	ch = getch();

	return ch == 'y';
}

int
xsnprintf(char *str, size_t size, const char *restrict format, ...)
{
	va_list ap;
	va_start(ap, format);

	size_t len = vsnprintf(str, size, format, ap);
	if (len >= size) {
		die("Length of items error");
	}

	va_end(ap);

	return SF_OK;
}