aboutsummaryrefslogtreecommitdiff
path: root/core/pager.c
blob: cda53005f4a14f9809c92c12d6e1e2951943d6f2 (plain)
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
#include "../lib/container/container.h"
#include "../lib/io/io.h"
#include "../lib/aec/aec.h"
#include "../lib/tctl/tctl.h"
#include "../lib/cstr/cstr.h"


#define BUFFER_SIZE 128
char buf[BUFFER_SIZE];
container_t *string;


u64 scroll = 0;
u64 maxscroll = 0;
u64 num_lines = 0;
termios_t original;
termios_t current;


void scroll_delta(int d)
{
	scroll += d;

	if ((i64)(scroll) < 0) {
		scroll = 0;
	} else if (scroll > maxscroll) {
		scroll = maxscroll;
	}
}

void draw_screen()
{
	window_size_t ws = tctl_get_window_size();
	clear_screen();
	move_cursor(0, 0);

	substr_t line = getline(string->data, scroll);

	for (int i = 0; i < ws.height - 1 && line.begin; ++i) {
		write(STDOUT_FD, line.begin, line.end - line.begin + 1);
		line = nextline(line);
	}

	move_cursor(0, ws.height);
	wstdf("%S Line: %i/%i %S", SGR_REVERSE, scroll + 1, num_lines, SGR_REVERSE_OFF);

	flush(STDOUT_FD);
}


int main(int argc, const char **argv)
{
	if (argc != 1) {
		wf(STDERR_FD, "pager\n");
		return -1;
	}

	if (!isatty()) {
		wf(STDERR_FD, "error: stdout is no tty! exiting.\n");
		return -1;
	}

	string = new_container(sizeof(char));
	u64 size;

	while ((size = rstd(buf, BUFFER_SIZE))) {
		container_append(string, buf, size);
	}

	container_push(string, 0);

	tcgetattr(STDOUT_FD, &original);
	current = original;
	setcanonical(&current, 0);
	setecho(&current, 0);
	cursor_enabled(0);
	tcsetattr(STDOUT_FD, &current);


	char key;
	int running = 1;
	window_size_t ws = tctl_get_window_size();
	num_lines = number_of_lines(string->data);
	maxscroll = num_lines < ws.height ? 0 : num_lines - ws.height + 1;

	draw_screen();

	while (running && read(STDERR_FD, &key, 1) == 1) {
		switch (key) {
			case 'j': scroll_delta(1);    break;
			case 'k': scroll_delta(-1);   break;
			case 'g': scroll = 0;         break;
			case 'G': scroll = maxscroll; break;

			case 'q':
			case '\033': running = 0; break;
		}

		draw_screen();
	}

	tcsetattr(STDOUT_FD, &original);
	cursor_enabled(1);

	clear_screen();
	move_cursor(0, 0);

	return 0;
}