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 int kbd(const char*);
82 static void kmap_define_key(struct kmap*, const char*, void(*)(struct tab*));
83 static void load_default_keys(void);
84 static int push_line(struct tab*, const struct line*, const char*, size_t);
85 static void empty_vlist(struct tab*);
86 static void restore_cursor(struct tab *);
88 static void cmd_previous_line(struct tab*);
89 static void cmd_next_line(struct tab*);
90 static void cmd_forward_char(struct tab*);
91 static void cmd_backward_char(struct tab*);
92 static void cmd_move_beginning_of_line(struct tab*);
93 static void cmd_move_end_of_line(struct tab*);
94 static void cmd_redraw(struct tab*);
95 static void cmd_scroll_line_down(struct tab*);
96 static void cmd_scroll_line_up(struct tab*);
97 static void cmd_scroll_up(struct tab*);
98 static void cmd_scroll_down(struct tab*);
99 static void cmd_beginning_of_buffer(struct tab*);
100 static void cmd_end_of_buffer(struct tab*);
101 static void cmd_kill_telescope(struct tab*);
102 static void cmd_push_button(struct tab*);
103 static void cmd_clear_minibuf(struct tab*);
104 static void cmd_execute_extended_command(struct tab*);
105 static void cmd_tab_close(struct tab*);
106 static void cmd_tab_new(struct tab*);
107 static void cmd_tab_next(struct tab*);
108 static void cmd_tab_previous(struct tab*);
109 static void cmd_load_url(struct tab*);
110 static void cmd_load_current_url(struct tab*);
112 static void global_key_unbound(void);
114 static void cmd_mini_delete_char(struct tab*);
115 static void cmd_mini_delete_backward_char(struct tab*);
116 static void cmd_mini_forward_char(struct tab*);
117 static void cmd_mini_backward_char(struct tab*);
118 static void cmd_mini_move_end_of_line(struct tab*);
119 static void cmd_mini_move_beginning_of_line(struct tab*);
120 static void cmd_mini_kill_line(struct tab*);
121 static void cmd_mini_abort(struct tab*);
122 static void cmd_mini_complete_and_exit(struct tab*);
123 static void cmd_mini_previous_history_element(struct tab*);
124 static void cmd_mini_next_history_element(struct tab*);
126 static void minibuffer_hist_save_entry(void);
127 static void minibuffer_taint_hist(void);
128 static void minibuffer_self_insert(void);
129 static void eecmd_self_insert(void);
130 static void eecmd_select(void);
131 static void ir_self_insert(void);
132 static void ir_select(void);
133 static void lu_self_insert(void);
134 static void lu_select(void);
136 static struct line *nth_line(struct tab*, size_t);
137 static struct tab *current_tab(void);
138 static void dispatch_stdio(int, short, void*);
139 static void handle_clear_minibuf(int, short, void*);
140 static void handle_resize(int, short, void*);
141 static int word_bourdaries(const char*, const char*, const char**, const char**);
142 static void wrap_text(struct tab*, const char*, struct line*);
143 static int hardwrap_text(struct tab*, struct line*);
144 static int wrap_page(struct tab*);
145 static void print_line(struct line*);
146 static void redraw_tabline(void);
147 static void redraw_body(struct tab*);
148 static void redraw_modeline(struct tab*);
149 static void redraw_minibuffer(void);
150 static void redraw_tab(struct tab*);
151 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
152 static void start_loading_anim(struct tab*);
153 static void update_loading_anim(int, short, void*);
154 static void stop_loading_anim(struct tab*);
155 static void load_url_in_tab(struct tab*, const char*);
156 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void), struct minibuf_histhead*);
157 static void exit_minibuffer(void);
158 static void switch_to_tab(struct tab*);
159 static void new_tab(void);
161 static struct { int meta, key; } thiskey;
163 static WINDOW *tabline, *body, *modeline, *minibuf;
164 static int body_lines, body_cols;
166 static struct event clminibufev;
167 static int clminibufev_set;
168 static struct timeval clminibufev_timer = { 5, 0 };
169 static struct timeval loadingev_timer = { 0, 250000 };
171 static uint32_t tab_counter;
173 struct ui_state {
174 int curs_x;
175 int curs_y;
176 size_t line_off;
177 size_t line_max;
179 short loading_anim;
180 short loading_anim_step;
181 struct event loadingev;
183 TAILQ_HEAD(, line) head;
184 };
186 static char keybuf[64];
188 #define CTRL(n) ((n)&0x1F)
190 struct keytable {
191 char *p;
192 int k;
193 } keytable[] = {
194 { "<up>", KEY_UP },
195 { "<down>", KEY_DOWN },
196 { "<left>", KEY_LEFT },
197 { "<right>", KEY_RIGHT },
198 { "<prior>", KEY_PPAGE },
199 { "<next>", KEY_NPAGE },
200 { "<home>", KEY_HOME },
201 { "<end>", KEY_END },
202 /* ... */
203 { "del", KEY_BACKSPACE },
204 { "esc", 27 },
205 { "space", ' ' },
206 { "spc", ' ' },
207 { "enter", CTRL('m') },
208 { "ret", CTRL('m' )},
209 { "tab", CTRL('i') },
210 /* ... */
211 { NULL, 0 },
212 };
214 struct kmap {
215 TAILQ_HEAD(map, keymap) m;
216 void (*unhandled_input)(void);
217 };
219 struct kmap global_map,
220 minibuffer_map,
221 *current_map,
222 *base_map;
224 struct keymap {
225 int meta;
226 int key;
227 struct kmap map;
228 void (*fn)(struct tab*);
230 TAILQ_ENTRY(keymap) keymaps;
231 };
233 /* TODO: limit to a maximum number of entries */
234 struct minibuf_histhead {
235 TAILQ_HEAD(mhisthead, minibuf_hist) head;
236 size_t len;
237 };
238 struct minibuf_hist {
239 char h[1025];
240 TAILQ_ENTRY(minibuf_hist) entries;
241 };
243 static struct minibuf_histhead eecmd_history,
244 ir_history,
245 lu_history;
247 static int in_minibuffer;
249 static struct {
250 char *curmesg;
252 char buf[1025];
253 size_t off, len;
254 char prompt[32];
255 void (*donefn)(void);
256 void (*abortfn)(void);
258 struct minibuf_histhead *history;
259 struct minibuf_hist *hist_cur;
260 size_t hist_off;
261 } ministate;
263 struct lineprefix {
264 const char *prfx1;
265 const char *prfx2;
266 } line_prefixes[] = {
267 [LINE_TEXT] = { "", "" },
268 [LINE_LINK] = { "=> ", " " },
269 [LINE_TITLE_1] = { "# ", " " },
270 [LINE_TITLE_2] = { "## ", " " },
271 [LINE_TITLE_3] = { "### ", " " },
272 [LINE_ITEM] = { "* ", " " },
273 [LINE_QUOTE] = { "> ", "> " },
274 [LINE_PRE_START] = { "```", "```" },
275 [LINE_PRE_CONTENT] = { "", "" },
276 [LINE_PRE_END] = { "```", "```" },
277 };
279 struct line_face {
280 int prop;
281 } line_faces[] = {
282 [LINE_TEXT] = { 0 },
283 [LINE_LINK] = { A_UNDERLINE },
284 [LINE_TITLE_1] = { A_BOLD },
285 [LINE_TITLE_2] = { A_BOLD },
286 [LINE_TITLE_3] = { A_BOLD },
287 [LINE_ITEM] = { 0 },
288 [LINE_QUOTE] = { A_DIM },
289 [LINE_PRE_START] = { 0 },
290 [LINE_PRE_CONTENT] = { 0 },
291 [LINE_PRE_END] = { 0 },
292 };
294 static int
295 kbd(const char *key)
297 struct keytable *t;
299 for (t = keytable; t->p != NULL; ++t) {
300 if (has_prefix(key, t->p))
301 return t->k;
304 return *key;
307 static const char *
308 unkbd(int k)
310 struct keytable *t;
312 for (t = keytable; t->p != NULL; ++t) {
313 if (k == t->k)
314 return t->p;
317 return NULL;
320 static void
321 kmap_define_key(struct kmap *map, const char *key, void (*fn)(struct tab*))
323 int ctrl, meta, k;
324 struct keymap *entry;
326 again:
327 if ((ctrl = has_prefix(key, "C-")))
328 key += 2;
329 if ((meta = has_prefix(key, "M-")))
330 key += 2;
331 if (*key == '\0')
332 _exit(1);
333 k = kbd(key);
335 if (ctrl)
336 k = CTRL(k);
338 /* skip key & spaces */
339 while (*key != '\0' && !isspace(*key))
340 ++key;
341 while (*key != '\0' && isspace(*key))
342 ++key;
344 TAILQ_FOREACH(entry, &map->m, keymaps) {
345 if (entry->meta == meta && entry->key == k) {
346 if (*key == '\0') {
347 entry->fn = fn;
348 return;
350 map = &entry->map;
351 goto again;
355 if ((entry = calloc(1, sizeof(*entry))) == NULL)
356 abort();
358 entry->meta = meta;
359 entry->key = k;
360 TAILQ_INIT(&entry->map.m);
362 if (TAILQ_EMPTY(&map->m))
363 TAILQ_INSERT_HEAD(&map->m, entry, keymaps);
364 else
365 TAILQ_INSERT_TAIL(&map->m, entry, keymaps);
367 if (*key != '\0') {
368 map = &entry->map;
369 goto again;
372 entry->fn = fn;
375 static inline void
376 global_set_key(const char *key, void (*fn)(struct tab*))
378 kmap_define_key(&global_map, key, fn);
381 static inline void
382 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
384 kmap_define_key(&minibuffer_map, key, fn);
387 static void
388 load_default_keys(void)
390 /* === global map === */
392 /* emacs */
393 global_set_key("C-p", cmd_previous_line);
394 global_set_key("C-n", cmd_next_line);
395 global_set_key("C-f", cmd_forward_char);
396 global_set_key("C-b", cmd_backward_char);
397 global_set_key("C-a", cmd_move_beginning_of_line);
398 global_set_key("C-e", cmd_move_end_of_line);
400 global_set_key("M-v", cmd_scroll_up);
401 global_set_key("C-v", cmd_scroll_down);
403 global_set_key("C-x C-c", cmd_kill_telescope);
405 global_set_key("C-g", cmd_clear_minibuf);
407 global_set_key("M-x", cmd_execute_extended_command);
408 global_set_key("C-x C-f", cmd_load_url);
409 global_set_key("C-x M-f", cmd_load_current_url);
411 global_set_key("C-x t 0", cmd_tab_close);
412 global_set_key("C-x t 2", cmd_tab_new);
413 global_set_key("C-x t o", cmd_tab_next);
414 global_set_key("C-x t O", cmd_tab_previous);
416 global_set_key("M-<", cmd_beginning_of_buffer);
417 global_set_key("M->", cmd_end_of_buffer);
419 /* vi/vi-like */
420 global_set_key("k", cmd_previous_line);
421 global_set_key("j", cmd_next_line);
422 global_set_key("l", cmd_forward_char);
423 global_set_key("h", cmd_backward_char);
424 global_set_key("^", cmd_move_beginning_of_line);
425 global_set_key("$", cmd_move_end_of_line);
427 global_set_key("K", cmd_scroll_line_up);
428 global_set_key("J", cmd_scroll_line_down);
430 global_set_key("g g", cmd_beginning_of_buffer);
431 global_set_key("G", cmd_end_of_buffer);
433 /* tmp */
434 global_set_key("q", cmd_kill_telescope);
436 global_set_key("esc", cmd_clear_minibuf);
438 global_set_key(":", cmd_execute_extended_command);
440 /* cua */
441 global_set_key("<up>", cmd_previous_line);
442 global_set_key("<down>", cmd_next_line);
443 global_set_key("<right>", cmd_forward_char);
444 global_set_key("<left>", cmd_backward_char);
445 global_set_key("<prior>", cmd_scroll_up);
446 global_set_key("<next>", cmd_scroll_down);
448 /* "ncurses standard" */
449 global_set_key("C-l", cmd_redraw);
451 /* global */
452 global_set_key("C-m", cmd_push_button);
454 /* === minibuffer map === */
455 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
456 minibuffer_set_key("C-g", cmd_mini_abort);
457 minibuffer_set_key("esc", cmd_mini_abort);
458 minibuffer_set_key("C-d", cmd_mini_delete_char);
459 minibuffer_set_key("del", cmd_mini_delete_backward_char);
461 minibuffer_set_key("C-f", cmd_mini_forward_char);
462 minibuffer_set_key("C-b", cmd_mini_backward_char);
463 minibuffer_set_key("<right>", cmd_mini_forward_char);
464 minibuffer_set_key("<left>", cmd_mini_backward_char);
465 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
466 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
467 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
468 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
469 minibuffer_set_key("C-k", cmd_mini_kill_line);
471 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
472 minibuffer_set_key("M-n", cmd_mini_next_history_element);
473 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
474 minibuffer_set_key("<down>", cmd_mini_next_history_element);
477 static int
478 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
480 struct line *vl;
482 tab->s->line_max++;
484 if ((vl = calloc(1, sizeof(*vl))) == NULL)
485 return 0;
487 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
488 free(vl);
489 return 0;
492 vl->type = l->type;
493 if (len != 0)
494 memcpy(vl->line, buf, len);
495 vl->alt = l->alt;
497 if (TAILQ_EMPTY(&tab->s->head))
498 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
499 else
500 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
501 return 1;
504 static void
505 empty_vlist(struct tab *tab)
507 struct line *l, *t;
509 tab->s->line_max = 0;
511 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
512 TAILQ_REMOVE(&tab->s->head, l, lines);
513 free(l->line);
514 /* l->alt references the original line! */
515 free(l);
519 static void
520 restore_cursor(struct tab *tab)
522 wmove(body, tab->s->curs_y, tab->s->curs_x);
525 static void
526 cmd_previous_line(struct tab *tab)
528 if (--tab->s->curs_y < 0) {
529 tab->s->curs_y = 0;
530 cmd_scroll_line_up(tab);
533 restore_cursor(tab);
536 static void
537 cmd_next_line(struct tab *tab)
539 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
540 return;
542 if (++tab->s->curs_y > body_lines-1) {
543 tab->s->curs_y = body_lines-1;
544 cmd_scroll_line_down(tab);
547 restore_cursor(tab);
550 static void
551 cmd_forward_char(struct tab *tab)
553 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
554 restore_cursor(tab);
557 static void
558 cmd_backward_char(struct tab *tab)
560 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
561 restore_cursor(tab);
564 static void
565 cmd_move_beginning_of_line(struct tab *tab)
567 tab->s->curs_x = 0;
568 restore_cursor(tab);
571 static void
572 cmd_move_end_of_line(struct tab *tab)
574 struct line *line;
575 size_t off;
576 const char *prfx;
578 off = tab->s->line_off + tab->s->curs_y;
579 if (off >= tab->s->line_max) {
580 tab->s->curs_x = 0;
581 goto end;
584 line = nth_line(tab, off);
585 if (line->line != NULL)
586 tab->s->curs_x = strlen(line->line);
587 else
588 tab->s->curs_x = 0;
590 prfx = line_prefixes[line->type].prfx1;
591 tab->s->curs_x += strlen(prfx);
593 end:
594 restore_cursor(tab);
597 static void
598 cmd_redraw(struct tab *tab)
600 handle_resize(0, 0, NULL);
603 static void
604 cmd_scroll_line_up(struct tab *tab)
606 struct line *l;
608 if (tab->s->line_off == 0)
609 return;
611 l = nth_line(tab, --tab->s->line_off);
612 wscrl(body, -1);
613 wmove(body, 0, 0);
614 print_line(l);
617 static void
618 cmd_scroll_line_down(struct tab *tab)
620 struct line *l;
621 size_t n;
623 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
624 return;
626 tab->s->line_off++;
627 wscrl(body, 1);
629 if (tab->s->line_max - tab->s->line_off < body_lines)
630 return;
632 l = nth_line(tab, tab->s->line_off + body_lines-1);
633 wmove(body, body_lines-1, 0);
634 print_line(l);
637 static void
638 cmd_scroll_up(struct tab *tab)
640 size_t off;
642 off = body_lines+1;
644 for (; off > 0; --off)
645 cmd_scroll_line_up(tab);
648 static void
649 cmd_scroll_down(struct tab *tab)
651 ssize_t off;
653 off = tab->s->line_off + body_lines;
654 off = MIN(tab->s->line_max, off);
656 for (; off >= 0; --off)
657 cmd_scroll_line_down(tab);
660 static void
661 cmd_beginning_of_buffer(struct tab *tab)
663 tab->s->line_off = 0;
664 tab->s->curs_y = 0;
665 redraw_body(tab);
668 static void
669 cmd_end_of_buffer(struct tab *tab)
671 ssize_t off;
673 off = tab->s->line_max - body_lines;
674 off = MAX(0, off);
676 tab->s->line_off = off;
677 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
679 redraw_body(tab);
682 static void
683 cmd_kill_telescope(struct tab *tab)
685 event_loopbreak();
688 static void
689 cmd_push_button(struct tab *tab)
691 struct line *l;
692 size_t nth;
694 nth = tab->s->line_off + tab->s->curs_y;
695 if (nth > tab->s->line_max)
696 return;
697 l = nth_line(tab, nth);
698 if (l->type != LINE_LINK)
699 return;
701 load_url_in_tab(tab, l->alt);
704 static void
705 cmd_clear_minibuf(struct tab *tab)
707 handle_clear_minibuf(0, 0, NULL);
710 static void
711 cmd_execute_extended_command(struct tab *tab)
713 size_t len;
715 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer,
716 &eecmd_history);
718 len = sizeof(ministate.prompt);
719 strlcpy(ministate.prompt, "", len);
721 if (thiskey.meta)
722 strlcat(ministate.prompt, "M-", len);
724 strlcat(ministate.prompt, keyname(thiskey.key), len);
725 strlcat(ministate.prompt, " ", len);
728 static void
729 cmd_tab_close(struct tab *tab)
731 struct tab *t;
733 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
734 TAILQ_NEXT(tab, tabs) == NULL) {
735 message("Can't close the only tab.");
736 return;
739 stop_tab(tab);
741 t = TAILQ_PREV(tab, tabshead, tabs);
742 t->flags |= TAB_CURRENT;
744 TAILQ_REMOVE(&tabshead, tab, tabs);
746 free(tab->s);
747 free(tab);
750 static void
751 cmd_tab_new(struct tab *tab)
753 new_tab();
756 static void
757 cmd_tab_next(struct tab *tab)
759 struct tab *t;
761 tab->flags &= ~TAB_CURRENT;
763 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
764 t = TAILQ_FIRST(&tabshead);
765 t->flags |= TAB_CURRENT;
768 static void
769 cmd_tab_previous(struct tab *tab)
771 struct tab *t;
773 tab->flags &= ~TAB_CURRENT;
775 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
776 t = TAILQ_LAST(&tabshead, tabshead);
777 t->flags |= TAB_CURRENT;
780 static void
781 cmd_load_url(struct tab *tab)
783 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
784 &lu_history);
785 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
788 static void
789 cmd_load_current_url(struct tab *tab)
791 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
792 &lu_history);
793 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
794 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
795 ministate.off = strlen(tab->urlstr);
796 ministate.len = ministate.off;
799 static void
800 global_key_unbound(void)
802 message("%s is undefined", keybuf);
805 static void
806 cmd_mini_delete_char(struct tab *tab)
808 minibuffer_taint_hist();
810 if (ministate.len == 0 || ministate.off == ministate.len)
811 return;
813 memmove(&ministate.buf[ministate.off],
814 &ministate.buf[ministate.off+1],
815 ministate.len - ministate.off + 1);
816 ministate.len--;
819 static void
820 cmd_mini_delete_backward_char(struct tab *tab)
822 minibuffer_taint_hist();
824 if (ministate.len == 0 || ministate.off == 0)
825 return;
827 memmove(&ministate.buf[ministate.off-1],
828 &ministate.buf[ministate.off],
829 ministate.len - ministate.off + 1);
830 ministate.off--;
831 ministate.len--;
834 static void
835 cmd_mini_forward_char(struct tab *tab)
837 if (ministate.off == ministate.len)
838 return;
839 ministate.off++;
842 static void
843 cmd_mini_backward_char(struct tab *tab)
845 if (ministate.off == 0)
846 return;
847 ministate.off--;
850 static void
851 cmd_mini_move_end_of_line(struct tab *tab)
853 ministate.off = ministate.len;
856 static void
857 cmd_mini_move_beginning_of_line(struct tab *tab)
859 ministate.off = 0;
862 static void
863 cmd_mini_kill_line(struct tab *tab)
865 minibuffer_taint_hist();
867 if (ministate.off == ministate.len)
868 return;
869 ministate.buf[ministate.off] = '\0';
870 ministate.len -= ministate.off;
873 static void
874 cmd_mini_abort(struct tab *tab)
876 ministate.abortfn();
879 static void
880 cmd_mini_complete_and_exit(struct tab *tab)
882 minibuffer_taint_hist();
883 ministate.donefn();
886 static void
887 cmd_mini_previous_history_element(struct tab *tab)
889 if (ministate.history == NULL) {
890 message("No history");
891 return;
894 if (ministate.hist_cur == NULL ||
895 (ministate.hist_cur = TAILQ_PREV(ministate.hist_cur, mhisthead, entries)) == NULL) {
896 ministate.hist_cur = TAILQ_LAST(&ministate.history->head, mhisthead);
897 ministate.hist_off = ministate.history->len - 1;
898 if (ministate.hist_cur == NULL)
899 message("No prev item");
900 } else {
901 ministate.hist_off--;
904 if (ministate.hist_cur != NULL) {
905 ministate.off = 0;
906 ministate.len = strlen(ministate.hist_cur->h);
910 static void
911 cmd_mini_next_history_element(struct tab *tab)
913 if (ministate.history == NULL) {
914 message("No history");
915 return;
918 if (ministate.hist_cur == NULL ||
919 (ministate.hist_cur = TAILQ_NEXT(ministate.hist_cur, entries)) == NULL) {
920 ministate.hist_cur = TAILQ_FIRST(&ministate.history->head);
921 ministate.hist_off = 0;
922 if (ministate.hist_cur == NULL)
923 message("No next item");
924 } else {
925 ministate.hist_off++;
928 if (ministate.hist_cur != NULL) {
929 ministate.off = 0;
930 ministate.len = strlen(ministate.hist_cur->h);
934 static void
935 minibuffer_hist_save_entry(void)
937 struct minibuf_hist *hist;
939 if (ministate.history == NULL)
940 return;
942 if ((hist = calloc(1, sizeof(*hist))) == NULL)
943 abort();
945 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
947 if (TAILQ_EMPTY(&ministate.history->head))
948 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
949 else
950 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
951 ministate.history->len++;
954 /*
955 * taint the minibuffer cache: if we're currently showing a history
956 * element, copy that to the current buf and reset the "history
957 * navigation" thing.
958 */
959 static void
960 minibuffer_taint_hist(void)
962 if (ministate.hist_cur == NULL)
963 return;
965 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
966 ministate.hist_cur = NULL;
969 static void
970 minibuffer_self_insert(void)
972 minibuffer_taint_hist();
974 if (ministate.len == sizeof(ministate.buf) -1)
975 return;
977 /* TODO: utf8 handling! */
979 memmove(&ministate.buf[ministate.off+1],
980 &ministate.buf[ministate.off],
981 ministate.len - ministate.off + 1);
982 ministate.buf[ministate.off] = thiskey.key;
983 ministate.off++;
984 ministate.len++;
987 static void
988 eecmd_self_insert(void)
990 if (thiskey.meta || isspace(thiskey.key) ||
991 !isgraph(thiskey.key)) {
992 global_key_unbound();
993 return;
996 minibuffer_self_insert();
999 static void
1000 eecmd_select(void)
1002 exit_minibuffer();
1003 minibuffer_hist_save_entry();
1004 message("TODO: try to execute %s", ministate.buf);
1007 static void
1008 ir_self_insert(void)
1010 minibuffer_self_insert();
1013 static void
1014 ir_select(void)
1016 char buf[1025] = {0};
1017 struct url url;
1018 struct tab *tab;
1020 tab = current_tab();
1022 exit_minibuffer();
1023 minibuffer_hist_save_entry();
1025 /* a bit ugly but... */
1026 memcpy(&url, &tab->url, sizeof(tab->url));
1027 url_set_query(&url, ministate.buf);
1028 url_unparse(&url, buf, sizeof(buf));
1029 load_url_in_tab(tab, buf);
1032 static void
1033 lu_self_insert(void)
1035 if (thiskey.meta || isspace(thiskey.key) ||
1036 !isgraph(thiskey.key)) {
1037 global_key_unbound();
1038 return;
1041 minibuffer_self_insert();
1044 static void
1045 lu_select(void)
1047 exit_minibuffer();
1048 minibuffer_hist_save_entry();
1049 load_url_in_tab(current_tab(), ministate.buf);
1052 static struct line *
1053 nth_line(struct tab *tab, size_t n)
1055 struct line *l;
1056 size_t i;
1058 i = 0;
1059 TAILQ_FOREACH(l, &tab->s->head, lines) {
1060 if (i == n)
1061 return l;
1062 i++;
1065 /* unreachable */
1066 abort();
1069 static struct tab *
1070 current_tab(void)
1072 struct tab *t;
1074 TAILQ_FOREACH(t, &tabshead, tabs) {
1075 if (t->flags & TAB_CURRENT)
1076 return t;
1079 /* unreachable */
1080 abort();
1083 static void
1084 dispatch_stdio(int fd, short ev, void *d)
1086 struct tab *tab;
1087 struct keymap *k;
1088 const char *keyname;
1089 char tmp[2] = {0};
1091 thiskey.key = wgetch(body);
1092 if (thiskey.key == ERR)
1093 return;
1094 if (thiskey.key == 27) {
1095 /* TODO: make escape-time customizable */
1097 thiskey.meta = 1;
1098 thiskey.key = wgetch(body);
1099 if (thiskey.key == ERR || thiskey.key == 27) {
1100 thiskey.meta = 0;
1101 thiskey.key = 27;
1103 } else
1104 thiskey.meta = 0;
1106 if (keybuf[0] != '\0')
1107 strlcat(keybuf, " ", sizeof(keybuf));
1108 if (thiskey.meta)
1109 strlcat(keybuf, "M-", sizeof(keybuf));
1110 if ((keyname = unkbd(thiskey.key)) != NULL)
1111 strlcat(keybuf, keyname, sizeof(keybuf));
1112 else {
1113 tmp[0] = thiskey.key;
1114 strlcat(keybuf, tmp, sizeof(keybuf));
1117 TAILQ_FOREACH(k, &current_map->m, keymaps) {
1118 if (k->meta == thiskey.meta &&
1119 k->key == thiskey.key) {
1120 if (k->fn == NULL)
1121 current_map = &k->map;
1122 else {
1123 current_map = base_map;
1124 strlcpy(keybuf, "", sizeof(keybuf));
1125 k->fn(current_tab());
1127 goto done;
1131 if (current_map->unhandled_input != NULL)
1132 current_map->unhandled_input();
1133 else {
1134 global_key_unbound();
1137 strlcpy(keybuf, "", sizeof(keybuf));
1138 current_map = base_map;
1140 done:
1141 redraw_tab(current_tab());
1144 static void
1145 handle_clear_minibuf(int fd, short ev, void *d)
1147 clminibufev_set = 0;
1149 free(ministate.curmesg);
1150 ministate.curmesg = NULL;
1152 redraw_minibuffer();
1153 if (in_minibuffer) {
1154 wrefresh(body);
1155 wrefresh(minibuf);
1156 } else {
1157 wrefresh(minibuf);
1158 wrefresh(body);
1162 static void
1163 handle_resize(int sig, short ev, void *d)
1165 struct tab *tab;
1167 endwin();
1168 refresh();
1169 clear();
1171 /* move and resize the windows, in reverse order! */
1173 mvwin(minibuf, LINES-1, 0);
1174 wresize(minibuf, 1, COLS);
1176 mvwin(modeline, LINES-2, 0);
1177 wresize(modeline, 1, COLS);
1179 wresize(body, LINES-3, COLS);
1180 body_lines = LINES-3;
1181 body_cols = COLS;
1183 wresize(tabline, 1, COLS);
1185 tab = current_tab();
1187 wrap_page(tab);
1188 redraw_tab(tab);
1192 * Helper function for wrap_text. Find the end of the current word
1193 * and the end of the separator after the word.
1195 static int
1196 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
1198 *endword = s;
1199 *endword = s;
1201 if (*s == '\0')
1202 return 0;
1204 /* find the end of the current world */
1205 for (; *s != '\0'; ++s) {
1206 if (strchr(sep, *s) != NULL)
1207 break;
1210 *endword = s;
1212 /* find the end of the separator */
1213 for (; *s != '\0'; ++s) {
1214 if (strchr(sep, *s) == NULL)
1215 break;
1218 *endspc = s;
1220 return 1;
1223 static inline int
1224 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1225 const char **line)
1227 if (!push_line(tab, l, *line, *off - zero))
1228 return 0;
1229 *line += *off - zero;
1230 *off = zero;
1231 return 1;
1234 static inline void
1235 emitstr(const char **s, size_t len, size_t *off)
1237 size_t i;
1239 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1240 for (i = 0; i < len; ++i)
1241 addch((*s)[i]);
1242 *off += len;
1243 *s += len;
1247 * Build a list of visual line by wrapping the given line, assuming
1248 * that when printed will have a leading prefix prfx.
1250 * TODO: it considers each byte one cell on the screen!
1252 static void
1253 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1255 size_t zero, off, len, split;
1256 const char *endword, *endspc, *line, *linestart;
1258 zero = strlen(prfx);
1259 off = zero;
1260 line = l->line;
1261 linestart = l->line;
1263 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1264 len = endword - line;
1265 if (off + len >= body_cols) {
1266 emitline(tab, zero, &off, l, &linestart);
1267 while (len >= body_cols) {
1268 /* hard wrap */
1269 emitline(tab, zero, &off, l, &linestart);
1270 len -= body_cols-1;
1271 line += body_cols-1;
1274 if (len != 0)
1275 off += len;
1276 } else
1277 off += len;
1279 /* print the spaces iff not at bol */
1280 len = endspc - endword;
1281 /* line = endspc; */
1282 if (off != zero) {
1283 if (off + len >= body_cols) {
1284 emitline(tab, zero, &off, l, &linestart);
1285 linestart = endspc;
1286 } else
1287 off += len;
1290 line = endspc;
1293 emitline(tab, zero, &off, l, &linestart);
1296 static int
1297 hardwrap_text(struct tab *tab, struct line *l)
1299 size_t off, len;
1300 const char *linestart;
1302 if (l->line == NULL)
1303 return emitline(tab, 0, &off, l, &linestart);
1305 len = strlen(l->line);
1306 off = 0;
1307 linestart = l->line;
1309 while (len >= COLS) {
1310 len -= COLS-1;
1311 off = COLS-1;
1312 if (!emitline(tab, 0, &off, l, &linestart))
1313 return 0;
1316 if (len != 0)
1317 return emitline(tab, 0, &len, l, &linestart);
1319 return 1;
1322 static int
1323 wrap_page(struct tab *tab)
1325 struct line *l;
1326 const char *prfx;
1328 empty_vlist(tab);
1330 TAILQ_FOREACH(l, &tab->page.head, lines) {
1331 prfx = line_prefixes[l->type].prfx1;
1332 switch (l->type) {
1333 case LINE_TEXT:
1334 case LINE_LINK:
1335 case LINE_TITLE_1:
1336 case LINE_TITLE_2:
1337 case LINE_TITLE_3:
1338 case LINE_ITEM:
1339 case LINE_QUOTE:
1340 wrap_text(tab, prfx, l);
1341 break;
1342 case LINE_PRE_START:
1343 case LINE_PRE_END:
1344 push_line(tab, l, NULL, 0);
1345 break;
1346 case LINE_PRE_CONTENT:
1347 hardwrap_text(tab, l);
1348 break;
1351 return 1;
1354 static inline void
1355 print_line(struct line *l)
1357 const char *text = l->line;
1358 const char *prfx = line_prefixes[l->type].prfx1;
1359 int face = line_faces[l->type].prop;
1361 if (text == NULL)
1362 text = "";
1364 if (face != 0)
1365 wattron(body, face);
1366 wprintw(body, "%s%s", prfx, text);
1367 if (face != 0)
1368 wattroff(body, face);
1371 static void
1372 redraw_tabline(void)
1374 struct tab *tab;
1375 int current;
1377 wclear(tabline);
1378 wbkgd(tabline, A_REVERSE);
1380 wprintw(tabline, " ");
1381 TAILQ_FOREACH(tab, &tabshead, tabs) {
1382 current = tab->flags & TAB_CURRENT;
1384 if (current)
1385 wattron(tabline, A_UNDERLINE);
1387 wprintw(tabline, "%s%d:todo title ",
1388 current ? "*" : " ", tab->id);
1390 if (current)
1391 wattroff(tabline, A_UNDERLINE);
1395 static void
1396 redraw_modeline(struct tab *tab)
1398 double pct;
1399 int x, y, max_x, max_y;
1400 const char *mode = tab->page.name;
1401 const char *spin = "-\\|/";
1403 wclear(modeline);
1404 wattron(modeline, A_REVERSE);
1405 wmove(modeline, 0, 0);
1407 wprintw(modeline, "-%c %s-mode ",
1408 spin[tab->s->loading_anim_step], mode);
1410 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1412 if (tab->s->line_max <= body_lines)
1413 wprintw(modeline, "All ");
1414 else if (tab->s->line_off == 0)
1415 wprintw(modeline, "Top ");
1416 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1417 wprintw(modeline, "Bottom ");
1418 else
1419 wprintw(modeline, "%.0f%% ", pct);
1421 wprintw(modeline, "%d/%d %s ",
1422 tab->s->line_off + tab->s->curs_y,
1423 tab->s->line_max,
1424 tab->urlstr);
1426 getyx(modeline, y, x);
1427 getmaxyx(modeline, max_y, max_x);
1429 (void)y;
1430 (void)max_y;
1432 for (; x < max_x; ++x)
1433 waddstr(modeline, "-");
1436 static void
1437 redraw_minibuffer(void)
1439 size_t skip = 0, off_x = 0, off_y = 0;
1441 wclear(minibuf);
1442 if (in_minibuffer) {
1443 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1444 if (ministate.hist_cur != NULL)
1445 wprintw(minibuf, "(%zu/%zu) ",
1446 ministate.hist_off + 1,
1447 ministate.history->len);
1449 getyx(minibuf, off_y, off_x);
1451 while (ministate.off - skip > COLS / 2) {
1452 skip += MIN(ministate.off/4, 1);
1455 if (ministate.hist_cur != NULL)
1456 wprintw(minibuf, "%s", ministate.hist_cur->h + skip);
1457 else
1458 wprintw(minibuf, "%s", ministate.buf + skip);
1461 if (ministate.curmesg != NULL) {
1462 if (in_minibuffer)
1463 wprintw(minibuf, " [%s]", ministate.curmesg);
1464 else
1465 wprintw(minibuf, "%s", ministate.curmesg);
1468 wmove(minibuf, 0, off_x + ministate.off - skip);
1471 static void
1472 redraw_tab(struct tab *tab)
1474 redraw_tabline();
1475 redraw_body(tab);
1476 redraw_modeline(tab);
1477 redraw_minibuffer();
1479 restore_cursor(tab);
1480 wrefresh(tabline);
1481 wrefresh(modeline);
1483 if (in_minibuffer) {
1484 wrefresh(body);
1485 wrefresh(minibuf);
1486 } else {
1487 wrefresh(minibuf);
1488 wrefresh(body);
1492 static void
1493 redraw_body(struct tab *tab)
1495 struct line *l;
1496 int line;
1498 werase(body);
1500 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1501 if (TAILQ_EMPTY(&tab->s->head))
1502 return;
1504 line = 0;
1505 l = nth_line(tab, tab->s->line_off);
1506 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1507 wmove(body, line, 0);
1508 print_line(l);
1509 line++;
1510 if (line == body_lines)
1511 break;
1515 static void
1516 message(const char *fmt, ...)
1518 va_list ap;
1520 if (clminibufev_set)
1521 evtimer_del(&clminibufev);
1522 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1523 evtimer_add(&clminibufev, &clminibufev_timer);
1524 clminibufev_set = 1;
1526 va_start(ap, fmt);
1527 /* TODO: what to do if the allocation fails here? */
1528 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1529 ministate.curmesg = NULL;
1530 va_end(ap);
1532 redraw_minibuffer();
1534 if (in_minibuffer) {
1535 wrefresh(body);
1536 wrefresh(minibuf);
1537 } else {
1538 wrefresh(minibuf);
1539 wrefresh(body);
1543 static void
1544 start_loading_anim(struct tab *tab)
1546 if (tab->s->loading_anim)
1547 return;
1548 tab->s->loading_anim = 1;
1549 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1550 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1553 static void
1554 update_loading_anim(int fd, short ev, void *d)
1556 struct tab *tab = d;
1558 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1560 redraw_modeline(tab);
1561 wrefresh(modeline);
1563 wrefresh(body);
1564 if (in_minibuffer)
1565 wrefresh(minibuf);
1567 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1570 static void
1571 stop_loading_anim(struct tab *tab)
1573 if (!tab->s->loading_anim)
1574 return;
1575 evtimer_del(&tab->s->loadingev);
1576 tab->s->loading_anim = 0;
1577 tab->s->loading_anim_step = 0;
1579 redraw_modeline(tab);
1581 wrefresh(modeline);
1582 wrefresh(body);
1583 if (in_minibuffer)
1584 wrefresh(minibuf);
1587 static void
1588 load_url_in_tab(struct tab *tab, const char *url)
1590 empty_vlist(tab);
1591 message("Loading %s...", url);
1592 start_loading_anim(tab);
1593 load_url(tab, url);
1595 tab->s->curs_x = 0;
1596 tab->s->curs_y = 0;
1597 redraw_tab(tab);
1600 static void
1601 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1602 void (*abortfn)(void), struct minibuf_histhead *hist)
1604 in_minibuffer = 1;
1605 base_map = &minibuffer_map;
1606 current_map = &minibuffer_map;
1608 base_map->unhandled_input = self_insert_fn;
1610 ministate.donefn = donefn;
1611 ministate.abortfn = abortfn;
1612 memset(ministate.buf, 0, sizeof(ministate.buf));
1613 ministate.off = 0;
1614 ministate.len = 0;
1615 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1617 ministate.history = hist;
1618 ministate.hist_cur = NULL;
1619 ministate.hist_off = 0;
1622 static void
1623 exit_minibuffer(void)
1625 wclear(minibuf);
1627 in_minibuffer = 0;
1628 base_map = &global_map;
1629 current_map = &global_map;
1632 static void
1633 switch_to_tab(struct tab *tab)
1635 struct tab *t;
1637 TAILQ_FOREACH(t, &tabshead, tabs) {
1638 t->flags &= ~TAB_CURRENT;
1641 tab->flags |= TAB_CURRENT;
1644 static void
1645 new_tab(void)
1647 struct tab *tab, *t;
1648 const char *url = "about:new";
1650 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1651 goto err;
1653 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1654 goto err;
1656 TAILQ_INIT(&tab->s->head);
1658 tab->id = tab_counter++;
1659 switch_to_tab(tab);
1661 if (TAILQ_EMPTY(&tabshead))
1662 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1663 else
1664 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1666 load_url_in_tab(tab, url);
1667 return;
1669 err:
1670 event_loopbreak();
1673 int
1674 ui_init(void)
1676 setlocale(LC_ALL, "");
1678 TAILQ_INIT(&global_map.m);
1679 global_map.unhandled_input = global_key_unbound;
1681 TAILQ_INIT(&minibuffer_map.m);
1683 TAILQ_INIT(&eecmd_history.head);
1684 TAILQ_INIT(&ir_history.head);
1685 TAILQ_INIT(&lu_history.head);
1687 base_map = &global_map;
1688 current_map = &global_map;
1689 load_default_keys();
1691 initscr();
1692 raw();
1693 noecho();
1695 nonl();
1696 intrflush(stdscr, FALSE);
1698 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1699 return 0;
1700 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1701 return 0;
1702 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1703 return 0;
1704 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1705 return 0;
1707 body_lines = LINES-3;
1708 body_cols = COLS;
1710 keypad(body, TRUE);
1711 scrollok(body, TRUE);
1713 /* non-blocking input */
1714 wtimeout(body, 0);
1716 mvwprintw(body, 0, 0, "");
1718 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1719 event_add(&stdioev, NULL);
1721 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1722 signal_add(&winchev, NULL);
1724 new_tab();
1726 return 1;
1729 void
1730 ui_on_tab_loaded(struct tab *tab)
1732 stop_loading_anim(tab);
1733 message("Loaded %s", tab->urlstr);
1736 void
1737 ui_on_tab_refresh(struct tab *tab)
1739 if (!(tab->flags & TAB_CURRENT))
1740 return;
1742 wrap_page(tab);
1743 redraw_tab(tab);
1746 void
1747 ui_require_input(struct tab *tab, int hide)
1749 /* TODO: hard-switching to another tab is ugly */
1750 switch_to_tab(tab);
1752 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1753 &ir_history);
1754 strlcpy(ministate.prompt, "Input required: ",
1755 sizeof(ministate.prompt));
1756 redraw_tab(tab);
1759 void
1760 ui_end(void)
1762 endwin();