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 <ctype.h>
62 #include <curses.h>
63 #include <event.h>
64 #include <locale.h>
65 #include <signal.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
71 #define TAB_CURRENT 0x1
73 #define MIN(a, b) ((a) < (b) ? (a) : (b))
74 #define MAX(a, b) ((a) > (b) ? (a) : (b))
76 struct kmap;
77 struct minibuf_histhead;
79 static struct event stdioev, winchev;
81 static void load_default_keys(void);
82 static int push_line(struct tab*, const struct line*, const char*, size_t, int);
83 static void empty_vlist(struct tab*);
84 static void restore_cursor(struct tab *);
86 static void cmd_previous_line(struct tab*);
87 static void cmd_next_line(struct tab*);
88 static void cmd_forward_char(struct tab*);
89 static void cmd_backward_char(struct tab*);
90 static void cmd_move_beginning_of_line(struct tab*);
91 static void cmd_move_end_of_line(struct tab*);
92 static void cmd_redraw(struct tab*);
93 static void cmd_scroll_line_down(struct tab*);
94 static void cmd_scroll_line_up(struct tab*);
95 static void cmd_scroll_up(struct tab*);
96 static void cmd_scroll_down(struct tab*);
97 static void cmd_beginning_of_buffer(struct tab*);
98 static void cmd_end_of_buffer(struct tab*);
99 static void cmd_kill_telescope(struct tab*);
100 static void cmd_push_button(struct tab*);
101 static void cmd_push_button_new_tab(struct tab*);
102 static void cmd_clear_minibuf(struct tab*);
103 static void cmd_execute_extended_command(struct tab*);
104 static void cmd_tab_close(struct tab*);
105 static void cmd_tab_new(struct tab*);
106 static void cmd_tab_next(struct tab*);
107 static void cmd_tab_previous(struct tab*);
108 static void cmd_load_url(struct tab*);
109 static void cmd_load_current_url(struct tab*);
111 static void global_key_unbound(void);
113 static void cmd_mini_delete_char(struct tab*);
114 static void cmd_mini_delete_backward_char(struct tab*);
115 static void cmd_mini_forward_char(struct tab*);
116 static void cmd_mini_backward_char(struct tab*);
117 static void cmd_mini_move_end_of_line(struct tab*);
118 static void cmd_mini_move_beginning_of_line(struct tab*);
119 static void cmd_mini_kill_line(struct tab*);
120 static void cmd_mini_abort(struct tab*);
121 static void cmd_mini_complete_and_exit(struct tab*);
122 static void cmd_mini_previous_history_element(struct tab*);
123 static void cmd_mini_next_history_element(struct tab*);
125 static void minibuffer_hist_save_entry(void);
126 static void minibuffer_taint_hist(void);
127 static void minibuffer_self_insert(void);
128 static void eecmd_self_insert(void);
129 static void eecmd_select(void);
130 static void ir_self_insert(void);
131 static void ir_select(void);
132 static void lu_self_insert(void);
133 static void lu_select(void);
135 static struct line *nth_line(struct tab*, size_t);
136 static struct tab *current_tab(void);
137 static void dispatch_stdio(int, short, void*);
138 static void handle_clear_minibuf(int, short, void*);
139 static void handle_resize(int, short, void*);
140 static int word_bourdaries(const char*, const char*, const char**, const char**);
141 static void wrap_text(struct tab*, const char*, struct line*);
142 static int hardwrap_text(struct tab*, struct line*);
143 static int wrap_page(struct tab*);
144 static void print_line(struct line*);
145 static void redraw_tabline(void);
146 static void redraw_body(struct tab*);
147 static void redraw_modeline(struct tab*);
148 static void redraw_minibuffer(void);
149 static void redraw_tab(struct tab*);
150 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
151 static void start_loading_anim(struct tab*);
152 static void update_loading_anim(int, short, void*);
153 static void stop_loading_anim(struct tab*);
154 static void load_url_in_tab(struct tab*, const char*);
155 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void), struct minibuf_histhead*);
156 static void exit_minibuffer(void);
157 static void switch_to_tab(struct tab*);
158 static struct tab *new_tab(void);
160 static struct { int meta, key; } thiskey;
162 static WINDOW *tabline, *body, *modeline, *minibuf;
163 static int body_lines, body_cols;
165 static struct event clminibufev;
166 static int clminibufev_set;
167 static struct timeval clminibufev_timer = { 5, 0 };
168 static struct timeval loadingev_timer = { 0, 250000 };
170 static uint32_t tab_counter;
172 struct ui_state {
173 int curs_x;
174 int curs_y;
175 size_t line_off;
176 size_t line_max;
178 short loading_anim;
179 short loading_anim_step;
180 struct event loadingev;
182 TAILQ_HEAD(, line) head;
183 };
185 static char keybuf[64];
187 struct kmap global_map,
188 minibuffer_map,
189 *current_map,
190 *base_map;
192 /* TODO: limit to a maximum number of entries */
193 struct minibuf_histhead {
194 TAILQ_HEAD(mhisthead, minibuf_hist) head;
195 size_t len;
196 };
197 struct minibuf_hist {
198 char h[1025];
199 TAILQ_ENTRY(minibuf_hist) entries;
200 };
202 static struct minibuf_histhead eecmd_history,
203 ir_history,
204 lu_history;
206 static int in_minibuffer;
208 static struct {
209 char *curmesg;
211 char buf[1025];
212 size_t off, len;
213 char prompt[32];
214 void (*donefn)(void);
215 void (*abortfn)(void);
217 struct minibuf_histhead *history;
218 struct minibuf_hist *hist_cur;
219 size_t hist_off;
220 } ministate;
222 struct lineprefix {
223 const char *prfx1;
224 const char *prfx2;
225 } line_prefixes[] = {
226 [LINE_TEXT] = { "", "" },
227 [LINE_LINK] = { "=> ", " " },
228 [LINE_TITLE_1] = { "# ", " " },
229 [LINE_TITLE_2] = { "## ", " " },
230 [LINE_TITLE_3] = { "### ", " " },
231 [LINE_ITEM] = { "* ", " " },
232 [LINE_QUOTE] = { "> ", "> " },
233 [LINE_PRE_START] = { "```", "```" },
234 [LINE_PRE_CONTENT] = { "", "" },
235 [LINE_PRE_END] = { "```", "```" },
236 };
238 struct line_face {
239 int prop;
240 } line_faces[] = {
241 [LINE_TEXT] = { 0 },
242 [LINE_LINK] = { A_UNDERLINE },
243 [LINE_TITLE_1] = { A_BOLD },
244 [LINE_TITLE_2] = { A_BOLD },
245 [LINE_TITLE_3] = { A_BOLD },
246 [LINE_ITEM] = { 0 },
247 [LINE_QUOTE] = { A_DIM },
248 [LINE_PRE_START] = { 0 },
249 [LINE_PRE_CONTENT] = { 0 },
250 [LINE_PRE_END] = { 0 },
251 };
253 static inline void
254 global_set_key(const char *key, void (*fn)(struct tab*))
256 if (!kmap_define_key(&global_map, key, fn))
257 _exit(1);
260 static inline void
261 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
263 if (!kmap_define_key(&minibuffer_map, key, fn))
264 _exit(1);
267 static void
268 load_default_keys(void)
270 /* === global map === */
272 /* emacs */
273 global_set_key("C-p", cmd_previous_line);
274 global_set_key("C-n", cmd_next_line);
275 global_set_key("C-f", cmd_forward_char);
276 global_set_key("C-b", cmd_backward_char);
277 global_set_key("C-a", cmd_move_beginning_of_line);
278 global_set_key("C-e", cmd_move_end_of_line);
280 global_set_key("M-v", cmd_scroll_up);
281 global_set_key("C-v", cmd_scroll_down);
282 global_set_key("M-space", cmd_scroll_up);
283 global_set_key("space", cmd_scroll_down);
285 global_set_key("C-x C-c", cmd_kill_telescope);
287 global_set_key("C-g", cmd_clear_minibuf);
289 global_set_key("M-x", cmd_execute_extended_command);
290 global_set_key("C-x C-f", cmd_load_url);
291 global_set_key("C-x M-f", cmd_load_current_url);
293 global_set_key("C-x t 0", cmd_tab_close);
294 global_set_key("C-x t 2", cmd_tab_new);
295 global_set_key("C-x t o", cmd_tab_next);
296 global_set_key("C-x t O", cmd_tab_previous);
298 global_set_key("M-<", cmd_beginning_of_buffer);
299 global_set_key("M->", cmd_end_of_buffer);
301 /* vi/vi-like */
302 global_set_key("k", cmd_previous_line);
303 global_set_key("j", cmd_next_line);
304 global_set_key("l", cmd_forward_char);
305 global_set_key("h", cmd_backward_char);
306 global_set_key("^", cmd_move_beginning_of_line);
307 global_set_key("$", cmd_move_end_of_line);
309 global_set_key("K", cmd_scroll_line_up);
310 global_set_key("J", cmd_scroll_line_down);
312 global_set_key("g g", cmd_beginning_of_buffer);
313 global_set_key("G", cmd_end_of_buffer);
315 /* tmp */
316 global_set_key("q", cmd_kill_telescope);
318 global_set_key("esc", cmd_clear_minibuf);
320 global_set_key(":", cmd_execute_extended_command);
322 /* cua */
323 global_set_key("<up>", cmd_previous_line);
324 global_set_key("<down>", cmd_next_line);
325 global_set_key("<right>", cmd_forward_char);
326 global_set_key("<left>", cmd_backward_char);
327 global_set_key("<prior>", cmd_scroll_up);
328 global_set_key("<next>", cmd_scroll_down);
330 /* "ncurses standard" */
331 global_set_key("C-l", cmd_redraw);
333 /* global */
334 global_set_key("C-m", cmd_push_button);
335 global_set_key("M-enter", cmd_push_button_new_tab);
337 /* === minibuffer map === */
338 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
339 minibuffer_set_key("C-g", cmd_mini_abort);
340 minibuffer_set_key("esc", cmd_mini_abort);
341 minibuffer_set_key("C-d", cmd_mini_delete_char);
342 minibuffer_set_key("del", cmd_mini_delete_backward_char);
344 minibuffer_set_key("C-f", cmd_mini_forward_char);
345 minibuffer_set_key("C-b", cmd_mini_backward_char);
346 minibuffer_set_key("<right>", cmd_mini_forward_char);
347 minibuffer_set_key("<left>", cmd_mini_backward_char);
348 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
349 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
350 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
351 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
352 minibuffer_set_key("C-k", cmd_mini_kill_line);
354 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
355 minibuffer_set_key("M-n", cmd_mini_next_history_element);
356 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
357 minibuffer_set_key("<down>", cmd_mini_next_history_element);
360 static int
361 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len, int cont)
363 struct line *vl;
365 tab->s->line_max++;
367 if ((vl = calloc(1, sizeof(*vl))) == NULL)
368 return 0;
370 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
371 free(vl);
372 return 0;
375 vl->type = l->type;
376 if (len != 0)
377 memcpy(vl->line, buf, len);
378 vl->alt = l->alt;
379 vl->flags = cont;
381 if (TAILQ_EMPTY(&tab->s->head))
382 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
383 else
384 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
385 return 1;
388 static void
389 empty_vlist(struct tab *tab)
391 struct line *l, *t;
393 tab->s->line_max = 0;
395 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
396 TAILQ_REMOVE(&tab->s->head, l, lines);
397 free(l->line);
398 /* l->alt references the original line! */
399 free(l);
403 static void
404 restore_cursor(struct tab *tab)
406 wmove(body, tab->s->curs_y, tab->s->curs_x);
409 static void
410 cmd_previous_line(struct tab *tab)
412 if (--tab->s->curs_y < 0) {
413 tab->s->curs_y = 0;
414 cmd_scroll_line_up(tab);
417 restore_cursor(tab);
420 static void
421 cmd_next_line(struct tab *tab)
423 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
424 return;
426 if (++tab->s->curs_y > body_lines-1) {
427 tab->s->curs_y = body_lines-1;
428 cmd_scroll_line_down(tab);
431 restore_cursor(tab);
434 static void
435 cmd_forward_char(struct tab *tab)
437 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
438 restore_cursor(tab);
441 static void
442 cmd_backward_char(struct tab *tab)
444 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
445 restore_cursor(tab);
448 static void
449 cmd_move_beginning_of_line(struct tab *tab)
451 tab->s->curs_x = 0;
452 restore_cursor(tab);
455 static void
456 cmd_move_end_of_line(struct tab *tab)
458 struct line *line;
459 size_t off;
460 const char *prfx;
462 off = tab->s->line_off + tab->s->curs_y;
463 if (off >= tab->s->line_max) {
464 tab->s->curs_x = 0;
465 goto end;
468 line = nth_line(tab, off);
469 if (line->line != NULL)
470 tab->s->curs_x = strlen(line->line);
471 else
472 tab->s->curs_x = 0;
474 prfx = line_prefixes[line->type].prfx1;
475 tab->s->curs_x += strlen(prfx);
477 end:
478 restore_cursor(tab);
481 static void
482 cmd_redraw(struct tab *tab)
484 handle_resize(0, 0, NULL);
487 static void
488 cmd_scroll_line_up(struct tab *tab)
490 struct line *l;
492 if (tab->s->line_off == 0)
493 return;
495 l = nth_line(tab, --tab->s->line_off);
496 wscrl(body, -1);
497 wmove(body, 0, 0);
498 print_line(l);
501 static void
502 cmd_scroll_line_down(struct tab *tab)
504 struct line *l;
505 size_t n;
507 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
508 return;
510 tab->s->line_off++;
511 wscrl(body, 1);
513 if (tab->s->line_max - tab->s->line_off < body_lines)
514 return;
516 l = nth_line(tab, tab->s->line_off + body_lines-1);
517 wmove(body, body_lines-1, 0);
518 print_line(l);
521 static void
522 cmd_scroll_up(struct tab *tab)
524 size_t off;
526 off = body_lines+1;
528 for (; off > 0; --off)
529 cmd_scroll_line_up(tab);
532 static void
533 cmd_scroll_down(struct tab *tab)
535 size_t off;
537 off = body_lines+1;
539 for (; off > 0; --off)
540 cmd_scroll_line_down(tab);
543 static void
544 cmd_beginning_of_buffer(struct tab *tab)
546 tab->s->line_off = 0;
547 tab->s->curs_y = 0;
548 redraw_body(tab);
551 static void
552 cmd_end_of_buffer(struct tab *tab)
554 ssize_t off;
556 off = tab->s->line_max - body_lines;
557 off = MAX(0, off);
559 tab->s->line_off = off;
560 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
562 redraw_body(tab);
565 static void
566 cmd_kill_telescope(struct tab *tab)
568 event_loopbreak();
571 static void
572 cmd_push_button(struct tab *tab)
574 struct line *l;
575 size_t nth;
577 nth = tab->s->line_off + tab->s->curs_y;
578 if (nth >= tab->s->line_max)
579 return;
580 l = nth_line(tab, nth);
581 if (l->type != LINE_LINK)
582 return;
584 load_url_in_tab(tab, l->alt);
587 static void
588 cmd_push_button_new_tab(struct tab *tab)
590 struct tab *t;
591 struct line *l;
592 size_t nth;
594 nth = tab->s->line_off + tab->s->curs_y;
595 if (nth > tab->s->line_max)
596 return;
597 l = nth_line(tab, nth);
598 if (l->type != LINE_LINK)
599 return;
601 t = new_tab();
602 memcpy(&t->url, &tab->url, sizeof(tab->url));
603 memcpy(&t->urlstr, &tab->urlstr, sizeof(tab->urlstr));
604 load_url_in_tab(t, l->alt);
607 static void
608 cmd_clear_minibuf(struct tab *tab)
610 handle_clear_minibuf(0, 0, NULL);
613 static void
614 cmd_execute_extended_command(struct tab *tab)
616 size_t len;
618 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer,
619 &eecmd_history);
621 len = sizeof(ministate.prompt);
622 strlcpy(ministate.prompt, "", len);
624 if (thiskey.meta)
625 strlcat(ministate.prompt, "M-", len);
627 strlcat(ministate.prompt, keyname(thiskey.key), len);
628 strlcat(ministate.prompt, " ", len);
631 static void
632 cmd_tab_close(struct tab *tab)
634 struct tab *t;
636 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
637 TAILQ_NEXT(tab, tabs) == NULL) {
638 message("Can't close the only tab.");
639 return;
642 stop_tab(tab);
644 t = TAILQ_PREV(tab, tabshead, tabs);
645 t->flags |= TAB_CURRENT;
647 TAILQ_REMOVE(&tabshead, tab, tabs);
649 free(tab->s);
650 free(tab);
653 static void
654 cmd_tab_new(struct tab *tab)
656 new_tab();
659 static void
660 cmd_tab_next(struct tab *tab)
662 struct tab *t;
664 tab->flags &= ~TAB_CURRENT;
666 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
667 t = TAILQ_FIRST(&tabshead);
668 t->flags |= TAB_CURRENT;
671 static void
672 cmd_tab_previous(struct tab *tab)
674 struct tab *t;
676 tab->flags &= ~TAB_CURRENT;
678 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
679 t = TAILQ_LAST(&tabshead, tabshead);
680 t->flags |= TAB_CURRENT;
683 static void
684 cmd_load_url(struct tab *tab)
686 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
687 &lu_history);
688 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
691 static void
692 cmd_load_current_url(struct tab *tab)
694 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
695 &lu_history);
696 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
697 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
698 ministate.off = strlen(tab->urlstr);
699 ministate.len = ministate.off;
702 static void
703 global_key_unbound(void)
705 message("%s is undefined", keybuf);
708 static void
709 cmd_mini_delete_char(struct tab *tab)
711 minibuffer_taint_hist();
713 if (ministate.len == 0 || ministate.off == ministate.len)
714 return;
716 memmove(&ministate.buf[ministate.off],
717 &ministate.buf[ministate.off+1],
718 ministate.len - ministate.off + 1);
719 ministate.len--;
722 static void
723 cmd_mini_delete_backward_char(struct tab *tab)
725 minibuffer_taint_hist();
727 if (ministate.len == 0 || ministate.off == 0)
728 return;
730 memmove(&ministate.buf[ministate.off-1],
731 &ministate.buf[ministate.off],
732 ministate.len - ministate.off + 1);
733 ministate.off--;
734 ministate.len--;
737 static void
738 cmd_mini_forward_char(struct tab *tab)
740 if (ministate.off == ministate.len)
741 return;
742 ministate.off++;
745 static void
746 cmd_mini_backward_char(struct tab *tab)
748 if (ministate.off == 0)
749 return;
750 ministate.off--;
753 static void
754 cmd_mini_move_end_of_line(struct tab *tab)
756 ministate.off = ministate.len;
759 static void
760 cmd_mini_move_beginning_of_line(struct tab *tab)
762 ministate.off = 0;
765 static void
766 cmd_mini_kill_line(struct tab *tab)
768 minibuffer_taint_hist();
770 if (ministate.off == ministate.len)
771 return;
772 ministate.buf[ministate.off] = '\0';
773 ministate.len -= ministate.off;
776 static void
777 cmd_mini_abort(struct tab *tab)
779 ministate.abortfn();
782 static void
783 cmd_mini_complete_and_exit(struct tab *tab)
785 minibuffer_taint_hist();
786 ministate.donefn();
789 static void
790 cmd_mini_previous_history_element(struct tab *tab)
792 if (ministate.history == NULL) {
793 message("No history");
794 return;
797 if (ministate.hist_cur == NULL ||
798 (ministate.hist_cur = TAILQ_PREV(ministate.hist_cur, mhisthead, entries)) == NULL) {
799 ministate.hist_cur = TAILQ_LAST(&ministate.history->head, mhisthead);
800 ministate.hist_off = ministate.history->len - 1;
801 if (ministate.hist_cur == NULL)
802 message("No prev item");
803 } else {
804 ministate.hist_off--;
807 if (ministate.hist_cur != NULL) {
808 ministate.off = 0;
809 ministate.len = strlen(ministate.hist_cur->h);
813 static void
814 cmd_mini_next_history_element(struct tab *tab)
816 if (ministate.history == NULL) {
817 message("No history");
818 return;
821 if (ministate.hist_cur == NULL ||
822 (ministate.hist_cur = TAILQ_NEXT(ministate.hist_cur, entries)) == NULL) {
823 ministate.hist_cur = TAILQ_FIRST(&ministate.history->head);
824 ministate.hist_off = 0;
825 if (ministate.hist_cur == NULL)
826 message("No next item");
827 } else {
828 ministate.hist_off++;
831 if (ministate.hist_cur != NULL) {
832 ministate.off = 0;
833 ministate.len = strlen(ministate.hist_cur->h);
837 static void
838 minibuffer_hist_save_entry(void)
840 struct minibuf_hist *hist;
842 if (ministate.history == NULL)
843 return;
845 if ((hist = calloc(1, sizeof(*hist))) == NULL)
846 abort();
848 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
850 if (TAILQ_EMPTY(&ministate.history->head))
851 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
852 else
853 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
854 ministate.history->len++;
857 /*
858 * taint the minibuffer cache: if we're currently showing a history
859 * element, copy that to the current buf and reset the "history
860 * navigation" thing.
861 */
862 static void
863 minibuffer_taint_hist(void)
865 if (ministate.hist_cur == NULL)
866 return;
868 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
869 ministate.hist_cur = NULL;
872 static void
873 minibuffer_self_insert(void)
875 minibuffer_taint_hist();
877 if (ministate.len == sizeof(ministate.buf) -1)
878 return;
880 /* TODO: utf8 handling! */
882 memmove(&ministate.buf[ministate.off+1],
883 &ministate.buf[ministate.off],
884 ministate.len - ministate.off + 1);
885 ministate.buf[ministate.off] = thiskey.key;
886 ministate.off++;
887 ministate.len++;
890 static void
891 eecmd_self_insert(void)
893 if (thiskey.meta || isspace(thiskey.key) ||
894 !isgraph(thiskey.key)) {
895 global_key_unbound();
896 return;
899 minibuffer_self_insert();
902 static void
903 eecmd_select(void)
905 exit_minibuffer();
906 minibuffer_hist_save_entry();
907 message("TODO: try to execute %s", ministate.buf);
910 static void
911 ir_self_insert(void)
913 minibuffer_self_insert();
916 static void
917 ir_select(void)
919 char buf[1025] = {0};
920 struct url url;
921 struct tab *tab;
923 tab = current_tab();
925 exit_minibuffer();
926 minibuffer_hist_save_entry();
928 /* a bit ugly but... */
929 memcpy(&url, &tab->url, sizeof(tab->url));
930 url_set_query(&url, ministate.buf);
931 url_unparse(&url, buf, sizeof(buf));
932 load_url_in_tab(tab, buf);
935 static void
936 lu_self_insert(void)
938 if (thiskey.meta || isspace(thiskey.key) ||
939 !isgraph(thiskey.key)) {
940 global_key_unbound();
941 return;
944 minibuffer_self_insert();
947 static void
948 lu_select(void)
950 exit_minibuffer();
951 minibuffer_hist_save_entry();
952 load_url_in_tab(current_tab(), ministate.buf);
955 static struct line *
956 nth_line(struct tab *tab, size_t n)
958 struct line *l;
959 size_t i;
961 i = 0;
962 TAILQ_FOREACH(l, &tab->s->head, lines) {
963 if (i == n)
964 return l;
965 i++;
968 /* unreachable */
969 abort();
972 static struct tab *
973 current_tab(void)
975 struct tab *t;
977 TAILQ_FOREACH(t, &tabshead, tabs) {
978 if (t->flags & TAB_CURRENT)
979 return t;
982 /* unreachable */
983 abort();
986 static void
987 dispatch_stdio(int fd, short ev, void *d)
989 struct tab *tab;
990 struct keymap *k;
991 const char *keyname;
992 char tmp[2] = {0};
994 thiskey.key = wgetch(body);
995 if (thiskey.key == ERR)
996 return;
997 if (thiskey.key == 27) {
998 /* TODO: make escape-time customizable */
1000 thiskey.meta = 1;
1001 thiskey.key = wgetch(body);
1002 if (thiskey.key == ERR || thiskey.key == 27) {
1003 thiskey.meta = 0;
1004 thiskey.key = 27;
1006 } else
1007 thiskey.meta = 0;
1009 if (keybuf[0] != '\0')
1010 strlcat(keybuf, " ", sizeof(keybuf));
1011 if (thiskey.meta)
1012 strlcat(keybuf, "M-", sizeof(keybuf));
1013 if ((keyname = unkbd(thiskey.key)) != NULL)
1014 strlcat(keybuf, keyname, sizeof(keybuf));
1015 else {
1016 tmp[0] = thiskey.key;
1017 strlcat(keybuf, tmp, sizeof(keybuf));
1020 TAILQ_FOREACH(k, &current_map->m, keymaps) {
1021 if (k->meta == thiskey.meta &&
1022 k->key == thiskey.key) {
1023 if (k->fn == NULL)
1024 current_map = &k->map;
1025 else {
1026 current_map = base_map;
1027 strlcpy(keybuf, "", sizeof(keybuf));
1028 k->fn(current_tab());
1030 goto done;
1034 if (current_map->unhandled_input != NULL)
1035 current_map->unhandled_input();
1036 else {
1037 global_key_unbound();
1040 strlcpy(keybuf, "", sizeof(keybuf));
1041 current_map = base_map;
1043 done:
1044 redraw_tab(current_tab());
1047 static void
1048 handle_clear_minibuf(int fd, short ev, void *d)
1050 clminibufev_set = 0;
1052 free(ministate.curmesg);
1053 ministate.curmesg = NULL;
1055 redraw_minibuffer();
1056 if (in_minibuffer) {
1057 wrefresh(body);
1058 wrefresh(minibuf);
1059 } else {
1060 wrefresh(minibuf);
1061 wrefresh(body);
1065 static void
1066 handle_resize(int sig, short ev, void *d)
1068 struct tab *tab;
1070 endwin();
1071 refresh();
1072 clear();
1074 /* move and resize the windows, in reverse order! */
1076 mvwin(minibuf, LINES-1, 0);
1077 wresize(minibuf, 1, COLS);
1079 mvwin(modeline, LINES-2, 0);
1080 wresize(modeline, 1, COLS);
1082 wresize(body, LINES-3, COLS);
1083 body_lines = LINES-3;
1084 body_cols = COLS;
1086 wresize(tabline, 1, COLS);
1088 tab = current_tab();
1090 wrap_page(tab);
1091 redraw_tab(tab);
1095 * Helper function for wrap_text. Find the end of the current word
1096 * and the end of the separator after the word.
1098 static int
1099 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
1101 *endword = s;
1102 *endword = s;
1104 if (*s == '\0')
1105 return 0;
1107 /* find the end of the current world */
1108 for (; *s != '\0'; ++s) {
1109 if (strchr(sep, *s) != NULL)
1110 break;
1113 *endword = s;
1115 /* find the end of the separator */
1116 for (; *s != '\0'; ++s) {
1117 if (strchr(sep, *s) == NULL)
1118 break;
1121 *endspc = s;
1123 return 1;
1126 static inline int
1127 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1128 const char **line, int *cont)
1130 if (!push_line(tab, l, *line, *off - zero, *cont))
1131 return 0;
1132 if (!*cont)
1133 *cont = 1;
1134 *line += *off - zero;
1135 *off = zero;
1136 return 1;
1139 static inline void
1140 emitstr(const char **s, size_t len, size_t *off)
1142 size_t i;
1144 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1145 for (i = 0; i < len; ++i)
1146 addch((*s)[i]);
1147 *off += len;
1148 *s += len;
1152 * Build a list of visual line by wrapping the given line, assuming
1153 * that when printed will have a leading prefix prfx.
1155 * TODO: it considers each byte one cell on the screen!
1157 static void
1158 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1160 size_t zero, off, len, split;
1161 int cont = 0;
1162 const char *endword, *endspc, *line, *linestart;
1164 zero = strlen(prfx);
1165 off = zero;
1166 line = l->line;
1167 linestart = l->line;
1169 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1170 len = endword - line;
1171 if (off + len >= body_cols) {
1172 emitline(tab, zero, &off, l, &linestart, &cont);
1173 while (len >= body_cols) {
1174 /* hard wrap */
1175 emitline(tab, zero, &off, l, &linestart, &cont);
1176 len -= body_cols-1;
1177 line += body_cols-1;
1180 if (len != 0)
1181 off += len;
1182 } else
1183 off += len;
1185 /* print the spaces iff not at bol */
1186 len = endspc - endword;
1187 /* line = endspc; */
1188 if (off != zero) {
1189 if (off + len >= body_cols) {
1190 emitline(tab, zero, &off, l, &linestart, &cont);
1191 linestart = endspc;
1192 } else
1193 off += len;
1196 line = endspc;
1199 emitline(tab, zero, &off, l, &linestart, &cont);
1202 static int
1203 hardwrap_text(struct tab *tab, struct line *l)
1205 size_t off, len;
1206 int cont;
1207 const char *linestart;
1209 if (l->line == NULL)
1210 return emitline(tab, 0, &off, l, &linestart, &cont);
1212 len = strlen(l->line);
1213 off = 0;
1214 linestart = l->line;
1216 while (len >= COLS) {
1217 len -= COLS-1;
1218 off = COLS-1;
1219 if (!emitline(tab, 0, &off, l, &linestart, &cont))
1220 return 0;
1223 if (len != 0)
1224 return emitline(tab, 0, &len, l, &linestart, &cont);
1226 return 1;
1229 static int
1230 wrap_page(struct tab *tab)
1232 struct line *l;
1233 const char *prfx;
1235 empty_vlist(tab);
1237 TAILQ_FOREACH(l, &tab->page.head, lines) {
1238 prfx = line_prefixes[l->type].prfx1;
1239 switch (l->type) {
1240 case LINE_TEXT:
1241 case LINE_LINK:
1242 case LINE_TITLE_1:
1243 case LINE_TITLE_2:
1244 case LINE_TITLE_3:
1245 case LINE_ITEM:
1246 case LINE_QUOTE:
1247 wrap_text(tab, prfx, l);
1248 break;
1249 case LINE_PRE_START:
1250 case LINE_PRE_END:
1251 push_line(tab, l, NULL, 0, 0);
1252 break;
1253 case LINE_PRE_CONTENT:
1254 hardwrap_text(tab, l);
1255 break;
1258 return 1;
1261 static inline void
1262 print_line(struct line *l)
1264 const char *text = l->line;
1265 const char *prfx;
1266 int face = line_faces[l->type].prop;
1268 if (!l->flags)
1269 prfx = line_prefixes[l->type].prfx1;
1270 else
1271 prfx = line_prefixes[l->type].prfx2;
1273 if (text == NULL)
1274 text = "";
1276 if (face != 0)
1277 wattron(body, face);
1278 wprintw(body, "%s%s", prfx, text);
1279 if (face != 0)
1280 wattroff(body, face);
1283 static void
1284 redraw_tabline(void)
1286 struct tab *tab;
1287 int current;
1289 werase(tabline);
1290 wbkgd(tabline, A_REVERSE);
1292 wprintw(tabline, " ");
1293 TAILQ_FOREACH(tab, &tabshead, tabs) {
1294 current = tab->flags & TAB_CURRENT;
1296 if (current)
1297 wattron(tabline, A_UNDERLINE);
1299 wprintw(tabline, "%s%d:todo title ",
1300 current ? "*" : " ", tab->id);
1302 if (current)
1303 wattroff(tabline, A_UNDERLINE);
1307 static void
1308 redraw_modeline(struct tab *tab)
1310 double pct;
1311 int x, y, max_x, max_y;
1312 const char *mode = tab->page.name;
1313 const char *spin = "-\\|/";
1315 werase(modeline);
1316 wattron(modeline, A_REVERSE);
1317 wmove(modeline, 0, 0);
1319 wprintw(modeline, "-%c %s-mode ",
1320 spin[tab->s->loading_anim_step], mode);
1322 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1324 if (tab->s->line_max <= body_lines)
1325 wprintw(modeline, "All ");
1326 else if (tab->s->line_off == 0)
1327 wprintw(modeline, "Top ");
1328 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1329 wprintw(modeline, "Bottom ");
1330 else
1331 wprintw(modeline, "%.0f%% ", pct);
1333 wprintw(modeline, "%d/%d %s ",
1334 tab->s->line_off + tab->s->curs_y,
1335 tab->s->line_max,
1336 tab->urlstr);
1338 getyx(modeline, y, x);
1339 getmaxyx(modeline, max_y, max_x);
1341 (void)y;
1342 (void)max_y;
1344 for (; x < max_x; ++x)
1345 waddstr(modeline, "-");
1348 static void
1349 redraw_minibuffer(void)
1351 size_t skip = 0, off_x = 0, off_y = 0;
1353 werase(minibuf);
1354 if (in_minibuffer) {
1355 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1356 if (ministate.hist_cur != NULL)
1357 wprintw(minibuf, "(%zu/%zu) ",
1358 ministate.hist_off + 1,
1359 ministate.history->len);
1361 getyx(minibuf, off_y, off_x);
1363 while (ministate.off - skip > COLS / 2) {
1364 skip += MIN(ministate.off/4, 1);
1367 if (ministate.hist_cur != NULL)
1368 wprintw(minibuf, "%s", ministate.hist_cur->h + skip);
1369 else
1370 wprintw(minibuf, "%s", ministate.buf + skip);
1373 if (ministate.curmesg != NULL) {
1374 if (in_minibuffer)
1375 wprintw(minibuf, " [%s]", ministate.curmesg);
1376 else
1377 wprintw(minibuf, "%s", ministate.curmesg);
1380 if (!in_minibuffer && ministate.curmesg == NULL)
1381 wprintw(minibuf, "%s", keybuf);
1383 if (in_minibuffer)
1384 wmove(minibuf, 0, off_x + ministate.off - skip);
1387 static void
1388 redraw_tab(struct tab *tab)
1390 redraw_tabline();
1391 redraw_body(tab);
1392 redraw_modeline(tab);
1393 redraw_minibuffer();
1395 restore_cursor(tab);
1396 wrefresh(tabline);
1397 wrefresh(modeline);
1399 if (in_minibuffer) {
1400 wrefresh(body);
1401 wrefresh(minibuf);
1402 } else {
1403 wrefresh(minibuf);
1404 wrefresh(body);
1408 static void
1409 redraw_body(struct tab *tab)
1411 struct line *l;
1412 int line;
1414 werase(body);
1416 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1417 if (TAILQ_EMPTY(&tab->s->head))
1418 return;
1420 line = 0;
1421 l = nth_line(tab, tab->s->line_off);
1422 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1423 wmove(body, line, 0);
1424 print_line(l);
1425 line++;
1426 if (line == body_lines)
1427 break;
1431 static void
1432 message(const char *fmt, ...)
1434 va_list ap;
1436 if (clminibufev_set)
1437 evtimer_del(&clminibufev);
1438 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1439 evtimer_add(&clminibufev, &clminibufev_timer);
1440 clminibufev_set = 1;
1442 free(ministate.curmesg);
1444 va_start(ap, fmt);
1445 /* TODO: what to do if the allocation fails here? */
1446 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1447 ministate.curmesg = NULL;
1448 va_end(ap);
1450 redraw_minibuffer();
1452 if (in_minibuffer) {
1453 wrefresh(body);
1454 wrefresh(minibuf);
1455 } else {
1456 wrefresh(minibuf);
1457 wrefresh(body);
1461 static void
1462 start_loading_anim(struct tab *tab)
1464 if (tab->s->loading_anim)
1465 return;
1466 tab->s->loading_anim = 1;
1467 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1468 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1471 static void
1472 update_loading_anim(int fd, short ev, void *d)
1474 struct tab *tab = d;
1476 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1478 redraw_modeline(tab);
1479 wrefresh(modeline);
1481 wrefresh(body);
1482 if (in_minibuffer)
1483 wrefresh(minibuf);
1485 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1488 static void
1489 stop_loading_anim(struct tab *tab)
1491 if (!tab->s->loading_anim)
1492 return;
1493 evtimer_del(&tab->s->loadingev);
1494 tab->s->loading_anim = 0;
1495 tab->s->loading_anim_step = 0;
1497 redraw_modeline(tab);
1499 wrefresh(modeline);
1500 wrefresh(body);
1501 if (in_minibuffer)
1502 wrefresh(minibuf);
1505 static void
1506 load_url_in_tab(struct tab *tab, const char *url)
1508 empty_vlist(tab);
1509 message("Loading %s...", url);
1510 start_loading_anim(tab);
1511 load_url(tab, url);
1513 tab->s->curs_x = 0;
1514 tab->s->curs_y = 0;
1515 redraw_tab(tab);
1518 static void
1519 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1520 void (*abortfn)(void), struct minibuf_histhead *hist)
1522 in_minibuffer = 1;
1523 base_map = &minibuffer_map;
1524 current_map = &minibuffer_map;
1526 base_map->unhandled_input = self_insert_fn;
1528 ministate.donefn = donefn;
1529 ministate.abortfn = abortfn;
1530 memset(ministate.buf, 0, sizeof(ministate.buf));
1531 ministate.off = 0;
1532 ministate.len = 0;
1533 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1535 ministate.history = hist;
1536 ministate.hist_cur = NULL;
1537 ministate.hist_off = 0;
1540 static void
1541 exit_minibuffer(void)
1543 werase(minibuf);
1545 in_minibuffer = 0;
1546 base_map = &global_map;
1547 current_map = &global_map;
1550 static void
1551 switch_to_tab(struct tab *tab)
1553 struct tab *t;
1555 TAILQ_FOREACH(t, &tabshead, tabs) {
1556 t->flags &= ~TAB_CURRENT;
1559 tab->flags |= TAB_CURRENT;
1562 static struct tab *
1563 new_tab(void)
1565 struct tab *tab, *t;
1566 const char *url = "about:new";
1568 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1569 goto err;
1571 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1572 goto err;
1574 TAILQ_INIT(&tab->s->head);
1576 tab->id = tab_counter++;
1577 switch_to_tab(tab);
1579 if (TAILQ_EMPTY(&tabshead))
1580 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1581 else
1582 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1584 load_url_in_tab(tab, url);
1585 return tab;
1587 err:
1588 event_loopbreak();
1589 return NULL;
1592 int
1593 ui_init(void)
1595 setlocale(LC_ALL, "");
1597 TAILQ_INIT(&global_map.m);
1598 global_map.unhandled_input = global_key_unbound;
1600 TAILQ_INIT(&minibuffer_map.m);
1602 TAILQ_INIT(&eecmd_history.head);
1603 TAILQ_INIT(&ir_history.head);
1604 TAILQ_INIT(&lu_history.head);
1606 base_map = &global_map;
1607 current_map = &global_map;
1608 load_default_keys();
1610 initscr();
1611 raw();
1612 noecho();
1614 nonl();
1615 intrflush(stdscr, FALSE);
1617 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1618 return 0;
1619 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1620 return 0;
1621 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1622 return 0;
1623 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1624 return 0;
1626 body_lines = LINES-3;
1627 body_cols = COLS;
1629 keypad(body, TRUE);
1630 scrollok(body, TRUE);
1632 /* non-blocking input */
1633 wtimeout(body, 0);
1635 mvwprintw(body, 0, 0, "");
1637 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1638 event_add(&stdioev, NULL);
1640 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1641 signal_add(&winchev, NULL);
1643 new_tab();
1645 return 1;
1648 void
1649 ui_on_tab_loaded(struct tab *tab)
1651 stop_loading_anim(tab);
1652 message("Loaded %s", tab->urlstr);
1655 void
1656 ui_on_tab_refresh(struct tab *tab)
1658 if (!(tab->flags & TAB_CURRENT))
1659 return;
1661 wrap_page(tab);
1662 redraw_tab(tab);
1665 void
1666 ui_require_input(struct tab *tab, int hide)
1668 /* TODO: hard-switching to another tab is ugly */
1669 switch_to_tab(tab);
1671 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1672 &ir_history);
1673 strlcpy(ministate.prompt, "Input required: ",
1674 sizeof(ministate.prompt));
1675 redraw_tab(tab);
1678 void
1679 ui_end(void)
1681 endwin();