Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 /*
18 * Ncurses UI for telescope.
19 *
20 *
21 * Text wrapping
22 * =============
23 *
24 * There's a simple text wrapping algorithm.
25 *
26 * 1. if it's a line in a pre-formatted block:
27 * a. hard wrap.
28 * b. repeat
29 * 2. there is enough room for the next word?
30 * a. yes: render it
31 * b. no: break the current line.
32 * i. while there isn't enough space to draw the current
33 * word, hard-wrap it
34 * ii. draw the remainder of the current word (can be the
35 * the entirely)
36 * 3. render the spaces after the word
37 * a. but if there is not enough room break the line and
38 * forget them
39 * 4. repeat
40 *
41 *
42 * Text scrolling
43 * ==============
44 *
45 * ncurses allows you to scroll a window, but when a line goes out of
46 * the visible area it's forgotten. We keep a list of formatted lines
47 * (``visual lines'') that we know fits in the window, and draw them.
48 * This way is easy to scroll: just call wscrl and then render the
49 * first/last line!
50 *
51 * This means that on every resize we have to clear our list of lines
52 * and re-render everything. A clever approach would be to do this
53 * ``on-demand''.
54 *
55 * TODO: make the text formatting on-demand.
56 *
57 */
59 #include <telescope.h>
61 #include <curses.h>
62 #include <event.h>
63 #include <locale.h>
64 #include <signal.h>
65 #include <stdlib.h>
66 #include <string.h>
68 #define TAB_CURRENT 0x1
70 #define CTRL(x) ((x)&0x1F)
72 #define MIN(a, b) ((a) < (b) ? (a) : (b))
73 #define MAX(a, b) ((a) > (b) ? (a) : (b))
75 static struct event stdioev, winchev;
77 static int push_line(struct tab*, const struct line*, const char*, size_t);
78 static void empty_vlist(struct tab*);
79 static struct tab *current_tab(void);
80 static void dispatch_stdio(int, short, void*);
81 static void handle_resize(int, short, void*);
82 static int word_bourdaries(const char*, const char*, const char**, const char**);
83 static void wrap_text(struct tab*, const char*, struct line*);
84 static int hardwrap_text(struct tab*, struct line*);
85 static int wrap_page(struct tab*);
86 static void redraw_tab(struct tab*);
88 typedef void (*interactivefn)(int);
90 static void cmd_previous_line(int);
91 static void cmd_next_line(int);
92 static void cmd_forward_char(int);
93 static void cmd_backward_char(int);
94 static void cmd_redraw(int);
95 static void cmd_scroll_down(int);
96 static void cmd_scroll_up(int);
97 static void cmd_kill_telescope(int);
99 static void cmd_unbound(int);
101 struct ui_state {
102 int curs_x;
103 int curs_y;
104 int line_off;
106 TAILQ_HEAD(, line) head;
107 };
109 static int
110 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
112 struct line *vl;
114 if ((vl = calloc(1, sizeof(*vl))) == NULL)
115 return 0;
117 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
118 free(vl);
119 return 0;
122 vl->type = l->type;
123 if (len != 0)
124 memcpy(vl->line, buf, len);
125 vl->alt = l->alt;
127 if (TAILQ_EMPTY(&tab->s->head))
128 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
129 else
130 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
131 return 1;
134 static void
135 empty_vlist(struct tab *tab)
137 struct line *l, *t;
139 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
140 TAILQ_REMOVE(&tab->s->head, l, lines);
141 free(l->line);
142 /* l->alt references the original line! */
143 free(l);
147 struct binding {
148 int key;
149 interactivefn fn;
150 } bindings[] = {
151 { CTRL('p'), cmd_previous_line, },
152 { CTRL('n'), cmd_next_line, },
153 { CTRL('f'), cmd_forward_char, },
154 { CTRL('b'), cmd_backward_char, },
156 { CTRL('L'), cmd_redraw, },
158 { 'J', cmd_scroll_down, },
159 { 'K', cmd_scroll_up, },
161 { 'q', cmd_kill_telescope, },
163 { 0, NULL, },
164 };
166 static void
167 cmd_previous_line(int k)
169 struct tab *tab;
171 tab = current_tab();
172 tab->s->curs_y = MAX(0, tab->s->curs_y-1);
173 move(tab->s->curs_y, tab->s->curs_x);
176 static void
177 cmd_next_line(int k)
179 struct tab *tab;
181 tab = current_tab();
182 tab->s->curs_y = MIN(LINES, tab->s->curs_y-1);
183 move(tab->s->curs_y, tab->s->curs_x);
186 static void
187 cmd_forward_char(int k)
191 static void
192 cmd_backward_char(int k)
196 static void
197 cmd_redraw(int k)
199 clear();
200 redraw_tab(current_tab());
203 static void
204 cmd_scroll_down(int k)
206 wscrl(stdscr, -1);
209 static void
210 cmd_scroll_up(int k)
212 wscrl(stdscr, 1);
215 static void
216 cmd_kill_telescope(int k)
218 event_loopbreak();
221 static void
222 cmd_unbound(int k)
224 /* TODO: flash a message */
227 static struct tab *
228 current_tab(void)
230 struct tab *t;
232 TAILQ_FOREACH(t, &tabshead, tabs) {
233 if (t->flags & TAB_CURRENT)
234 return t;
237 /* unreachable */
238 abort();
241 static void
242 dispatch_stdio(int fd, short ev, void *d)
244 struct binding *b;
245 int k;
247 k = getch();
249 if (k == ERR)
250 return;
252 for (b = bindings; b->fn != NULL; ++b) {
253 if (k == b->key) {
254 b->fn(k);
255 goto done;
259 cmd_unbound(k);
261 done:
262 refresh();
265 static void
266 handle_resize(int sig, short ev, void *d)
268 struct tab *tab;
270 endwin();
271 refresh();
272 clear();
274 tab = current_tab();
276 wrap_page(tab);
277 redraw_tab(tab);
280 /*
281 * Helper function for wrap_text. Find the end of the current word
282 * and the end of the separator after the word.
283 */
284 static int
285 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
287 *endword = s;
288 *endword = s;
290 if (*s == '\0')
291 return 0;
293 /* find the end of the current world */
294 for (; *s != '\0'; ++s) {
295 if (strchr(sep, *s) != NULL)
296 break;
299 *endword = s;
301 /* find the end of the separator */
302 for (; *s != '\0'; ++s) {
303 if (strchr(sep, *s) == NULL)
304 break;
307 *endspc = s;
309 return 1;
312 static inline int
313 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
314 const char **line)
316 if (!push_line(tab, l, *line, *off - zero))
317 return 0;
318 *line += *off - zero;
319 *off = zero;
320 return 1;
323 static inline void
324 emitstr(const char **s, size_t len, size_t *off)
326 size_t i;
328 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
329 for (i = 0; i < len; ++i)
330 addch((*s)[i]);
331 *off += len;
332 *s += len;
335 /*
336 * Build a list of visual line by wrapping the given line, assuming
337 * that when printed will have a leading prefix prfx.
339 * TODO: it considers each byte one cell on the screen!
340 */
341 static void
342 wrap_text(struct tab *tab, const char *prfx, struct line *l)
344 size_t zero, off, len, split;
345 const char *endword, *endspc, *line, *linestart;
347 zero = strlen(prfx);
348 off = zero;
349 line = l->line;
350 linestart = l->line;
352 while (word_boundaries(line, " \t-", &endword, &endspc)) {
353 len = endword - line;
354 if (off + len >= COLS) {
355 emitline(tab, zero, &off, l, &linestart);
356 while (len >= COLS) {
357 /* hard wrap */
358 emitline(tab, zero, &off, l, &linestart);
359 len -= COLS-1;
360 line += COLS-1;
363 if (len != 0)
364 off += len;
365 } else
366 off += len;
368 /* print the spaces iff not at bol */
369 len = endspc - endword;
370 /* line = endspc; */
371 if (off != zero) {
372 if (off + len >= COLS) {
373 emitline(tab, zero, &off, l, &linestart);
374 linestart = endspc;
375 } else
376 off += len;
379 line = endspc;
382 emitline(tab, zero, &off, l, &linestart);
385 static int
386 hardwrap_text(struct tab *tab, struct line *l)
388 size_t off, len;
389 const char *linestart;
391 len = strlen(l->line);
392 off = 0;
393 linestart = l->line;
395 while (len >= COLS) {
396 len -= COLS-1;
397 off = COLS-1;
398 if (!emitline(tab, 0, &off, l, &linestart))
399 return 0;
402 return 1;
405 static int
406 wrap_page(struct tab *tab)
408 struct line *l;
410 empty_vlist(tab);
412 TAILQ_FOREACH(l, &tab->page.head, lines) {
413 switch (l->type) {
414 case LINE_TEXT:
415 wrap_text(tab, "", l);
416 break;
417 case LINE_LINK:
418 wrap_text(tab, "=> ", l);
419 break;
420 case LINE_TITLE_1:
421 wrap_text(tab, "# ", l);
422 break;
423 case LINE_TITLE_2:
424 wrap_text(tab, "## ", l);
425 break;
426 case LINE_TITLE_3:
427 wrap_text(tab, "### ", l);
428 break;
429 case LINE_ITEM:
430 wrap_text(tab, "* ", l);
431 break;
432 case LINE_QUOTE:
433 wrap_text(tab, "> ", l);
434 break;
435 case LINE_PRE_START:
436 case LINE_PRE_END:
437 push_line(tab, l, NULL, 0);
438 break;
439 case LINE_PRE_CONTENT:
440 hardwrap_text(tab, l);
441 break;
444 return 1;
447 static inline void
448 print_line(struct line *l)
450 switch (l->type) {
451 case LINE_TEXT:
452 break;
453 case LINE_LINK:
454 printw("=> ");
455 break;
456 case LINE_TITLE_1:
457 printw("# ");
458 break;
459 case LINE_TITLE_2:
460 printw("## ");
461 break;
462 case LINE_TITLE_3:
463 printw("### ");
464 break;
465 case LINE_ITEM:
466 printw("* ");
467 break;
468 case LINE_QUOTE:
469 printw("> ");
470 break;
471 case LINE_PRE_START:
472 case LINE_PRE_END:
473 printw("```");
474 break;
475 case LINE_PRE_CONTENT:
476 break;
479 if (l->line != NULL)
480 printw("%s", l->line);
481 printw("\n");
484 static void
485 redraw_tab(struct tab *tab)
487 struct line *l;
489 erase();
491 TAILQ_FOREACH(l, &tab->s->head, lines) {
492 print_line(l);
495 move(tab->s->curs_y, tab->s->curs_x);
496 refresh();
499 int
500 ui_init(void)
502 setlocale(LC_ALL, "");
504 initscr();
505 raw();
506 noecho();
508 nonl();
509 intrflush(stdscr, FALSE);
510 keypad(stdscr, TRUE);
512 scrollok(stdscr, TRUE);
514 /* non-blocking input */
515 timeout(0);
517 mvprintw(0, 0, "");
519 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
520 event_add(&stdioev, NULL);
522 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
523 signal_add(&winchev, NULL);
525 return 1;
528 int
529 ui_on_new_tab(struct tab *tab)
531 struct tab *t;
533 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
534 return 0;
536 TAILQ_INIT(&tab->s->head);
538 TAILQ_FOREACH(t, &tabshead, tabs) {
539 t->flags &= ~TAB_CURRENT;
541 tab->flags = TAB_CURRENT;
543 /* TODO: redraw the tab list */
544 /* TODO: switch to the new tab */
546 move(0, 0);
548 return 1;
551 void
552 ui_on_tab_refresh(struct tab *tab)
554 if (!(tab->flags & TAB_CURRENT))
555 return;
557 wrap_page(tab);
558 redraw_tab(tab);
561 void
562 ui_end(void)
564 endwin();