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 struct minibuf_histhead;
75 static struct event stdioev, winchev;
77 static void load_default_keys(void);
78 static int push_line(struct tab*, const struct line*, const char*, size_t, int);
79 static void empty_vlist(struct tab*);
80 static void restore_cursor(struct tab *);
82 static void cmd_previous_line(struct tab*);
83 static void cmd_next_line(struct tab*);
84 static void cmd_forward_char(struct tab*);
85 static void cmd_backward_char(struct tab*);
86 static void cmd_move_beginning_of_line(struct tab*);
87 static void cmd_move_end_of_line(struct tab*);
88 static void cmd_redraw(struct tab*);
89 static void cmd_scroll_line_down(struct tab*);
90 static void cmd_scroll_line_up(struct tab*);
91 static void cmd_scroll_up(struct tab*);
92 static void cmd_scroll_down(struct tab*);
93 static void cmd_beginning_of_buffer(struct tab*);
94 static void cmd_end_of_buffer(struct tab*);
95 static void cmd_kill_telescope(struct tab*);
96 static void cmd_push_button(struct tab*);
97 static void cmd_push_button_new_tab(struct tab*);
98 static void cmd_clear_minibuf(struct tab*);
99 static void cmd_execute_extended_command(struct tab*);
100 static void cmd_tab_close(struct tab*);
101 static void cmd_tab_new(struct tab*);
102 static void cmd_tab_next(struct tab*);
103 static void cmd_tab_previous(struct tab*);
104 static void cmd_load_url(struct tab*);
105 static void cmd_load_current_url(struct tab*);
107 static void global_key_unbound(void);
109 static void cmd_mini_delete_char(struct tab*);
110 static void cmd_mini_delete_backward_char(struct tab*);
111 static void cmd_mini_forward_char(struct tab*);
112 static void cmd_mini_backward_char(struct tab*);
113 static void cmd_mini_move_end_of_line(struct tab*);
114 static void cmd_mini_move_beginning_of_line(struct tab*);
115 static void cmd_mini_kill_line(struct tab*);
116 static void cmd_mini_abort(struct tab*);
117 static void cmd_mini_complete_and_exit(struct tab*);
118 static void cmd_mini_previous_history_element(struct tab*);
119 static void cmd_mini_next_history_element(struct tab*);
121 static void minibuffer_hist_save_entry(void);
122 static void minibuffer_taint_hist(void);
123 static void minibuffer_self_insert(void);
124 static void eecmd_self_insert(void);
125 static void eecmd_select(void);
126 static void ir_self_insert(void);
127 static void ir_select(void);
128 static void lu_self_insert(void);
129 static void lu_select(void);
131 static struct line *nth_line(struct tab*, size_t);
132 static struct tab *current_tab(void);
133 static void dispatch_stdio(int, short, void*);
134 static void handle_clear_minibuf(int, short, void*);
135 static void handle_resize(int, short, void*);
136 static int word_bourdaries(const char*, const char*, const char**, const char**);
137 static void wrap_text(struct tab*, const char*, struct line*);
138 static int hardwrap_text(struct tab*, struct line*);
139 static int wrap_page(struct tab*);
140 static void print_line(struct line*);
141 static void redraw_tabline(void);
142 static void redraw_body(struct tab*);
143 static void redraw_modeline(struct tab*);
144 static void redraw_minibuffer(void);
145 static void redraw_tab(struct tab*);
146 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
147 static void start_loading_anim(struct tab*);
148 static void update_loading_anim(int, short, void*);
149 static void stop_loading_anim(struct tab*);
150 static void load_url_in_tab(struct tab*, const char*);
151 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void), struct minibuf_histhead*);
152 static void exit_minibuffer(void);
153 static void switch_to_tab(struct tab*);
154 static struct tab *new_tab(void);
156 static struct { int meta, key; } thiskey;
158 static WINDOW *tabline, *body, *modeline, *minibuf;
159 static int body_lines, body_cols;
161 static struct event clminibufev;
162 static int clminibufev_set;
163 static struct timeval clminibufev_timer = { 5, 0 };
164 static struct timeval loadingev_timer = { 0, 250000 };
166 static uint32_t tab_counter;
168 struct ui_state {
169 int curs_x;
170 int curs_y;
171 size_t line_off;
172 size_t line_max;
174 short loading_anim;
175 short loading_anim_step;
176 struct event loadingev;
178 TAILQ_HEAD(, line) head;
179 };
181 static char keybuf[64];
183 struct kmap global_map,
184 minibuffer_map,
185 *current_map,
186 *base_map;
188 /* TODO: limit to a maximum number of entries */
189 struct minibuf_histhead {
190 TAILQ_HEAD(mhisthead, minibuf_hist) head;
191 size_t len;
192 };
193 struct minibuf_hist {
194 char h[1025];
195 TAILQ_ENTRY(minibuf_hist) entries;
196 };
198 static struct minibuf_histhead eecmd_history,
199 ir_history,
200 lu_history;
202 static int in_minibuffer;
204 static struct {
205 char *curmesg;
207 char buf[1025];
208 size_t off, len;
209 char prompt[32];
210 void (*donefn)(void);
211 void (*abortfn)(void);
213 struct minibuf_histhead *history;
214 struct minibuf_hist *hist_cur;
215 size_t hist_off;
216 } ministate;
218 struct lineprefix {
219 const char *prfx1;
220 const char *prfx2;
221 } line_prefixes[] = {
222 [LINE_TEXT] = { "", "" },
223 [LINE_LINK] = { "=> ", " " },
224 [LINE_TITLE_1] = { "# ", " " },
225 [LINE_TITLE_2] = { "## ", " " },
226 [LINE_TITLE_3] = { "### ", " " },
227 [LINE_ITEM] = { "* ", " " },
228 [LINE_QUOTE] = { "> ", "> " },
229 [LINE_PRE_START] = { "```", "```" },
230 [LINE_PRE_CONTENT] = { "", "" },
231 [LINE_PRE_END] = { "```", "```" },
232 };
234 struct line_face {
235 int prop;
236 } line_faces[] = {
237 [LINE_TEXT] = { 0 },
238 [LINE_LINK] = { A_UNDERLINE },
239 [LINE_TITLE_1] = { A_BOLD },
240 [LINE_TITLE_2] = { A_BOLD },
241 [LINE_TITLE_3] = { A_BOLD },
242 [LINE_ITEM] = { 0 },
243 [LINE_QUOTE] = { A_DIM },
244 [LINE_PRE_START] = { 0 },
245 [LINE_PRE_CONTENT] = { 0 },
246 [LINE_PRE_END] = { 0 },
247 };
249 static inline void
250 global_set_key(const char *key, void (*fn)(struct tab*))
252 if (!kmap_define_key(&global_map, key, fn))
253 _exit(1);
256 static inline void
257 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
259 if (!kmap_define_key(&minibuffer_map, key, fn))
260 _exit(1);
263 static void
264 load_default_keys(void)
266 /* === global map === */
268 /* emacs */
269 global_set_key("C-p", cmd_previous_line);
270 global_set_key("C-n", cmd_next_line);
271 global_set_key("C-f", cmd_forward_char);
272 global_set_key("C-b", cmd_backward_char);
273 global_set_key("C-a", cmd_move_beginning_of_line);
274 global_set_key("C-e", cmd_move_end_of_line);
276 global_set_key("M-v", cmd_scroll_up);
277 global_set_key("C-v", cmd_scroll_down);
278 global_set_key("M-space", cmd_scroll_up);
279 global_set_key("space", cmd_scroll_down);
281 global_set_key("C-x C-c", cmd_kill_telescope);
283 global_set_key("C-g", cmd_clear_minibuf);
285 global_set_key("M-x", cmd_execute_extended_command);
286 global_set_key("C-x C-f", cmd_load_url);
287 global_set_key("C-x M-f", cmd_load_current_url);
289 global_set_key("C-x t 0", cmd_tab_close);
290 global_set_key("C-x t 2", cmd_tab_new);
291 global_set_key("C-x t o", cmd_tab_next);
292 global_set_key("C-x t O", cmd_tab_previous);
294 global_set_key("M-<", cmd_beginning_of_buffer);
295 global_set_key("M->", cmd_end_of_buffer);
297 /* vi/vi-like */
298 global_set_key("k", cmd_previous_line);
299 global_set_key("j", cmd_next_line);
300 global_set_key("l", cmd_forward_char);
301 global_set_key("h", cmd_backward_char);
302 global_set_key("^", cmd_move_beginning_of_line);
303 global_set_key("$", cmd_move_end_of_line);
305 global_set_key("K", cmd_scroll_line_up);
306 global_set_key("J", cmd_scroll_line_down);
308 global_set_key("g g", cmd_beginning_of_buffer);
309 global_set_key("G", cmd_end_of_buffer);
311 /* tmp */
312 global_set_key("q", cmd_kill_telescope);
314 global_set_key("esc", cmd_clear_minibuf);
316 global_set_key(":", cmd_execute_extended_command);
318 /* cua */
319 global_set_key("<up>", cmd_previous_line);
320 global_set_key("<down>", cmd_next_line);
321 global_set_key("<right>", cmd_forward_char);
322 global_set_key("<left>", cmd_backward_char);
323 global_set_key("<prior>", cmd_scroll_up);
324 global_set_key("<next>", cmd_scroll_down);
326 /* "ncurses standard" */
327 global_set_key("C-l", cmd_redraw);
329 /* global */
330 global_set_key("C-m", cmd_push_button);
331 global_set_key("M-enter", cmd_push_button_new_tab);
333 /* === minibuffer map === */
334 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
335 minibuffer_set_key("C-g", cmd_mini_abort);
336 minibuffer_set_key("esc", cmd_mini_abort);
337 minibuffer_set_key("C-d", cmd_mini_delete_char);
338 minibuffer_set_key("del", cmd_mini_delete_backward_char);
340 minibuffer_set_key("C-f", cmd_mini_forward_char);
341 minibuffer_set_key("C-b", cmd_mini_backward_char);
342 minibuffer_set_key("<right>", cmd_mini_forward_char);
343 minibuffer_set_key("<left>", cmd_mini_backward_char);
344 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
345 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
346 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
347 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
348 minibuffer_set_key("C-k", cmd_mini_kill_line);
350 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
351 minibuffer_set_key("M-n", cmd_mini_next_history_element);
352 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
353 minibuffer_set_key("<down>", cmd_mini_next_history_element);
356 static int
357 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len, int cont)
359 struct line *vl;
361 tab->s->line_max++;
363 if ((vl = calloc(1, sizeof(*vl))) == NULL)
364 return 0;
366 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
367 free(vl);
368 return 0;
371 vl->type = l->type;
372 if (len != 0)
373 memcpy(vl->line, buf, len);
374 vl->alt = l->alt;
375 vl->flags = cont;
377 if (TAILQ_EMPTY(&tab->s->head))
378 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
379 else
380 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
381 return 1;
384 static void
385 empty_vlist(struct tab *tab)
387 struct line *l, *t;
389 tab->s->line_max = 0;
391 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
392 TAILQ_REMOVE(&tab->s->head, l, lines);
393 free(l->line);
394 /* l->alt references the original line! */
395 free(l);
399 static void
400 restore_cursor(struct tab *tab)
402 wmove(body, tab->s->curs_y, tab->s->curs_x);
405 static void
406 cmd_previous_line(struct tab *tab)
408 if (--tab->s->curs_y < 0) {
409 tab->s->curs_y = 0;
410 cmd_scroll_line_up(tab);
413 restore_cursor(tab);
416 static void
417 cmd_next_line(struct tab *tab)
419 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
420 return;
422 if (++tab->s->curs_y > body_lines-1) {
423 tab->s->curs_y = body_lines-1;
424 cmd_scroll_line_down(tab);
427 restore_cursor(tab);
430 static void
431 cmd_forward_char(struct tab *tab)
433 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
434 restore_cursor(tab);
437 static void
438 cmd_backward_char(struct tab *tab)
440 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
441 restore_cursor(tab);
444 static void
445 cmd_move_beginning_of_line(struct tab *tab)
447 tab->s->curs_x = 0;
448 restore_cursor(tab);
451 static void
452 cmd_move_end_of_line(struct tab *tab)
454 struct line *line;
455 size_t off;
456 const char *prfx;
458 off = tab->s->line_off + tab->s->curs_y;
459 if (off >= tab->s->line_max) {
460 tab->s->curs_x = 0;
461 goto end;
464 line = nth_line(tab, off);
465 if (line->line != NULL)
466 tab->s->curs_x = strlen(line->line);
467 else
468 tab->s->curs_x = 0;
470 prfx = line_prefixes[line->type].prfx1;
471 tab->s->curs_x += strlen(prfx);
473 end:
474 restore_cursor(tab);
477 static void
478 cmd_redraw(struct tab *tab)
480 handle_resize(0, 0, NULL);
483 static void
484 cmd_scroll_line_up(struct tab *tab)
486 struct line *l;
488 if (tab->s->line_off == 0)
489 return;
491 l = nth_line(tab, --tab->s->line_off);
492 wscrl(body, -1);
493 wmove(body, 0, 0);
494 print_line(l);
497 static void
498 cmd_scroll_line_down(struct tab *tab)
500 struct line *l;
501 size_t n;
503 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
504 return;
506 tab->s->line_off++;
507 wscrl(body, 1);
509 if (tab->s->line_max - tab->s->line_off < body_lines)
510 return;
512 l = nth_line(tab, tab->s->line_off + body_lines-1);
513 wmove(body, body_lines-1, 0);
514 print_line(l);
517 static void
518 cmd_scroll_up(struct tab *tab)
520 size_t off;
522 off = body_lines+1;
524 for (; off > 0; --off)
525 cmd_scroll_line_up(tab);
528 static void
529 cmd_scroll_down(struct tab *tab)
531 size_t off;
533 off = body_lines+1;
535 for (; off > 0; --off)
536 cmd_scroll_line_down(tab);
539 static void
540 cmd_beginning_of_buffer(struct tab *tab)
542 tab->s->line_off = 0;
543 tab->s->curs_y = 0;
544 redraw_body(tab);
547 static void
548 cmd_end_of_buffer(struct tab *tab)
550 ssize_t off;
552 off = tab->s->line_max - body_lines;
553 off = MAX(0, off);
555 tab->s->line_off = off;
556 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
558 redraw_body(tab);
561 static void
562 cmd_kill_telescope(struct tab *tab)
564 event_loopbreak();
567 static void
568 cmd_push_button(struct tab *tab)
570 struct line *l;
571 size_t nth;
573 nth = tab->s->line_off + tab->s->curs_y;
574 if (nth >= tab->s->line_max)
575 return;
576 l = nth_line(tab, nth);
577 if (l->type != LINE_LINK)
578 return;
580 load_url_in_tab(tab, l->alt);
583 static void
584 cmd_push_button_new_tab(struct tab *tab)
586 struct tab *t;
587 struct line *l;
588 size_t nth;
590 nth = tab->s->line_off + tab->s->curs_y;
591 if (nth > tab->s->line_max)
592 return;
593 l = nth_line(tab, nth);
594 if (l->type != LINE_LINK)
595 return;
597 t = new_tab();
598 memcpy(&t->url, &tab->url, sizeof(tab->url));
599 memcpy(&t->urlstr, &tab->urlstr, sizeof(tab->urlstr));
600 load_url_in_tab(t, l->alt);
603 static void
604 cmd_clear_minibuf(struct tab *tab)
606 handle_clear_minibuf(0, 0, NULL);
609 static void
610 cmd_execute_extended_command(struct tab *tab)
612 size_t len;
614 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer,
615 &eecmd_history);
617 len = sizeof(ministate.prompt);
618 strlcpy(ministate.prompt, "", len);
620 if (thiskey.meta)
621 strlcat(ministate.prompt, "M-", len);
623 strlcat(ministate.prompt, keyname(thiskey.key), len);
624 strlcat(ministate.prompt, " ", len);
627 static void
628 cmd_tab_close(struct tab *tab)
630 struct tab *t;
632 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
633 TAILQ_NEXT(tab, tabs) == NULL) {
634 message("Can't close the only tab.");
635 return;
638 stop_tab(tab);
640 t = TAILQ_PREV(tab, tabshead, tabs);
641 t->flags |= TAB_CURRENT;
643 TAILQ_REMOVE(&tabshead, tab, tabs);
645 free(tab->s);
646 free(tab);
649 static void
650 cmd_tab_new(struct tab *tab)
652 new_tab();
655 static void
656 cmd_tab_next(struct tab *tab)
658 struct tab *t;
660 tab->flags &= ~TAB_CURRENT;
662 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
663 t = TAILQ_FIRST(&tabshead);
664 t->flags |= TAB_CURRENT;
667 static void
668 cmd_tab_previous(struct tab *tab)
670 struct tab *t;
672 tab->flags &= ~TAB_CURRENT;
674 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
675 t = TAILQ_LAST(&tabshead, tabshead);
676 t->flags |= TAB_CURRENT;
679 static void
680 cmd_load_url(struct tab *tab)
682 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
683 &lu_history);
684 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
687 static void
688 cmd_load_current_url(struct tab *tab)
690 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
691 &lu_history);
692 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
693 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
694 ministate.off = strlen(tab->urlstr);
695 ministate.len = ministate.off;
698 static void
699 global_key_unbound(void)
701 message("%s is undefined", keybuf);
704 static void
705 cmd_mini_delete_char(struct tab *tab)
707 minibuffer_taint_hist();
709 if (ministate.len == 0 || ministate.off == ministate.len)
710 return;
712 memmove(&ministate.buf[ministate.off],
713 &ministate.buf[ministate.off+1],
714 ministate.len - ministate.off + 1);
715 ministate.len--;
718 static void
719 cmd_mini_delete_backward_char(struct tab *tab)
721 minibuffer_taint_hist();
723 if (ministate.len == 0 || ministate.off == 0)
724 return;
726 memmove(&ministate.buf[ministate.off-1],
727 &ministate.buf[ministate.off],
728 ministate.len - ministate.off + 1);
729 ministate.off--;
730 ministate.len--;
733 static void
734 cmd_mini_forward_char(struct tab *tab)
736 if (ministate.off == ministate.len)
737 return;
738 ministate.off++;
741 static void
742 cmd_mini_backward_char(struct tab *tab)
744 if (ministate.off == 0)
745 return;
746 ministate.off--;
749 static void
750 cmd_mini_move_end_of_line(struct tab *tab)
752 ministate.off = ministate.len;
755 static void
756 cmd_mini_move_beginning_of_line(struct tab *tab)
758 ministate.off = 0;
761 static void
762 cmd_mini_kill_line(struct tab *tab)
764 minibuffer_taint_hist();
766 if (ministate.off == ministate.len)
767 return;
768 ministate.buf[ministate.off] = '\0';
769 ministate.len -= ministate.off;
772 static void
773 cmd_mini_abort(struct tab *tab)
775 ministate.abortfn();
778 static void
779 cmd_mini_complete_and_exit(struct tab *tab)
781 minibuffer_taint_hist();
782 ministate.donefn();
785 static void
786 cmd_mini_previous_history_element(struct tab *tab)
788 if (ministate.history == NULL) {
789 message("No history");
790 return;
793 if (ministate.hist_cur == NULL ||
794 (ministate.hist_cur = TAILQ_PREV(ministate.hist_cur, mhisthead, entries)) == NULL) {
795 ministate.hist_cur = TAILQ_LAST(&ministate.history->head, mhisthead);
796 ministate.hist_off = ministate.history->len - 1;
797 if (ministate.hist_cur == NULL)
798 message("No prev item");
799 } else {
800 ministate.hist_off--;
803 if (ministate.hist_cur != NULL) {
804 ministate.off = 0;
805 ministate.len = strlen(ministate.hist_cur->h);
809 static void
810 cmd_mini_next_history_element(struct tab *tab)
812 if (ministate.history == NULL) {
813 message("No history");
814 return;
817 if (ministate.hist_cur == NULL ||
818 (ministate.hist_cur = TAILQ_NEXT(ministate.hist_cur, entries)) == NULL) {
819 ministate.hist_cur = TAILQ_FIRST(&ministate.history->head);
820 ministate.hist_off = 0;
821 if (ministate.hist_cur == NULL)
822 message("No next item");
823 } else {
824 ministate.hist_off++;
827 if (ministate.hist_cur != NULL) {
828 ministate.off = 0;
829 ministate.len = strlen(ministate.hist_cur->h);
833 static void
834 minibuffer_hist_save_entry(void)
836 struct minibuf_hist *hist;
838 if (ministate.history == NULL)
839 return;
841 if ((hist = calloc(1, sizeof(*hist))) == NULL)
842 abort();
844 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
846 if (TAILQ_EMPTY(&ministate.history->head))
847 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
848 else
849 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
850 ministate.history->len++;
853 /*
854 * taint the minibuffer cache: if we're currently showing a history
855 * element, copy that to the current buf and reset the "history
856 * navigation" thing.
857 */
858 static void
859 minibuffer_taint_hist(void)
861 if (ministate.hist_cur == NULL)
862 return;
864 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
865 ministate.hist_cur = NULL;
868 static void
869 minibuffer_self_insert(void)
871 minibuffer_taint_hist();
873 if (ministate.len == sizeof(ministate.buf) -1)
874 return;
876 /* TODO: utf8 handling! */
878 memmove(&ministate.buf[ministate.off+1],
879 &ministate.buf[ministate.off],
880 ministate.len - ministate.off + 1);
881 ministate.buf[ministate.off] = thiskey.key;
882 ministate.off++;
883 ministate.len++;
886 static void
887 eecmd_self_insert(void)
889 if (thiskey.meta || isspace(thiskey.key) ||
890 !isgraph(thiskey.key)) {
891 global_key_unbound();
892 return;
895 minibuffer_self_insert();
898 static void
899 eecmd_select(void)
901 exit_minibuffer();
902 minibuffer_hist_save_entry();
903 message("TODO: try to execute %s", ministate.buf);
906 static void
907 ir_self_insert(void)
909 minibuffer_self_insert();
912 static void
913 ir_select(void)
915 char buf[1025] = {0};
916 struct url url;
917 struct tab *tab;
919 tab = current_tab();
921 exit_minibuffer();
922 minibuffer_hist_save_entry();
924 /* a bit ugly but... */
925 memcpy(&url, &tab->url, sizeof(tab->url));
926 url_set_query(&url, ministate.buf);
927 url_unparse(&url, buf, sizeof(buf));
928 load_url_in_tab(tab, buf);
931 static void
932 lu_self_insert(void)
934 if (thiskey.meta || isspace(thiskey.key) ||
935 !isgraph(thiskey.key)) {
936 global_key_unbound();
937 return;
940 minibuffer_self_insert();
943 static void
944 lu_select(void)
946 exit_minibuffer();
947 minibuffer_hist_save_entry();
948 load_url_in_tab(current_tab(), ministate.buf);
951 static struct line *
952 nth_line(struct tab *tab, size_t n)
954 struct line *l;
955 size_t i;
957 i = 0;
958 TAILQ_FOREACH(l, &tab->s->head, lines) {
959 if (i == n)
960 return l;
961 i++;
964 /* unreachable */
965 abort();
968 static struct tab *
969 current_tab(void)
971 struct tab *t;
973 TAILQ_FOREACH(t, &tabshead, tabs) {
974 if (t->flags & TAB_CURRENT)
975 return t;
978 /* unreachable */
979 abort();
982 static void
983 dispatch_stdio(int fd, short ev, void *d)
985 struct tab *tab;
986 struct keymap *k;
987 const char *keyname;
988 char tmp[2] = {0};
990 thiskey.key = wgetch(body);
991 if (thiskey.key == ERR)
992 return;
993 if (thiskey.key == 27) {
994 /* TODO: make escape-time customizable */
996 thiskey.meta = 1;
997 thiskey.key = wgetch(body);
998 if (thiskey.key == ERR || thiskey.key == 27) {
999 thiskey.meta = 0;
1000 thiskey.key = 27;
1002 } else
1003 thiskey.meta = 0;
1005 if (keybuf[0] != '\0')
1006 strlcat(keybuf, " ", sizeof(keybuf));
1007 if (thiskey.meta)
1008 strlcat(keybuf, "M-", sizeof(keybuf));
1009 if ((keyname = unkbd(thiskey.key)) != NULL)
1010 strlcat(keybuf, keyname, sizeof(keybuf));
1011 else {
1012 tmp[0] = thiskey.key;
1013 strlcat(keybuf, tmp, sizeof(keybuf));
1016 TAILQ_FOREACH(k, &current_map->m, keymaps) {
1017 if (k->meta == thiskey.meta &&
1018 k->key == thiskey.key) {
1019 if (k->fn == NULL)
1020 current_map = &k->map;
1021 else {
1022 current_map = base_map;
1023 strlcpy(keybuf, "", sizeof(keybuf));
1024 k->fn(current_tab());
1026 goto done;
1030 if (current_map->unhandled_input != NULL)
1031 current_map->unhandled_input();
1032 else {
1033 global_key_unbound();
1036 strlcpy(keybuf, "", sizeof(keybuf));
1037 current_map = base_map;
1039 done:
1040 redraw_tab(current_tab());
1043 static void
1044 handle_clear_minibuf(int fd, short ev, void *d)
1046 clminibufev_set = 0;
1048 free(ministate.curmesg);
1049 ministate.curmesg = NULL;
1051 redraw_minibuffer();
1052 if (in_minibuffer) {
1053 wrefresh(body);
1054 wrefresh(minibuf);
1055 } else {
1056 wrefresh(minibuf);
1057 wrefresh(body);
1061 static void
1062 handle_resize(int sig, short ev, void *d)
1064 struct tab *tab;
1066 endwin();
1067 refresh();
1068 clear();
1070 /* move and resize the windows, in reverse order! */
1072 mvwin(minibuf, LINES-1, 0);
1073 wresize(minibuf, 1, COLS);
1075 mvwin(modeline, LINES-2, 0);
1076 wresize(modeline, 1, COLS);
1078 wresize(body, LINES-3, COLS);
1079 body_lines = LINES-3;
1080 body_cols = COLS;
1082 wresize(tabline, 1, COLS);
1084 tab = current_tab();
1086 wrap_page(tab);
1087 redraw_tab(tab);
1091 * Helper function for wrap_text. Find the end of the current word
1092 * and the end of the separator after the word.
1094 static int
1095 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
1097 *endword = s;
1098 *endword = s;
1100 if (*s == '\0')
1101 return 0;
1103 /* find the end of the current world */
1104 for (; *s != '\0'; ++s) {
1105 if (strchr(sep, *s) != NULL)
1106 break;
1109 *endword = s;
1111 /* find the end of the separator */
1112 for (; *s != '\0'; ++s) {
1113 if (strchr(sep, *s) == NULL)
1114 break;
1117 *endspc = s;
1119 return 1;
1122 static inline int
1123 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1124 const char **line, int *cont)
1126 if (!push_line(tab, l, *line, *off - zero, *cont))
1127 return 0;
1128 if (!*cont)
1129 *cont = 1;
1130 *line += *off - zero;
1131 *off = zero;
1132 return 1;
1135 static inline void
1136 emitstr(const char **s, size_t len, size_t *off)
1138 size_t i;
1140 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1141 for (i = 0; i < len; ++i)
1142 addch((*s)[i]);
1143 *off += len;
1144 *s += len;
1148 * Build a list of visual line by wrapping the given line, assuming
1149 * that when printed will have a leading prefix prfx.
1151 * TODO: it considers each byte one cell on the screen!
1153 static void
1154 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1156 size_t zero, off, len, split;
1157 int cont = 0;
1158 const char *endword, *endspc, *line, *linestart;
1160 zero = strlen(prfx);
1161 off = zero;
1162 line = l->line;
1163 linestart = l->line;
1165 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1166 len = endword - line;
1167 if (off + len >= body_cols) {
1168 emitline(tab, zero, &off, l, &linestart, &cont);
1169 while (len >= body_cols) {
1170 /* hard wrap */
1171 emitline(tab, zero, &off, l, &linestart, &cont);
1172 len -= body_cols-1;
1173 line += body_cols-1;
1176 if (len != 0)
1177 off += len;
1178 } else
1179 off += len;
1181 /* print the spaces iff not at bol */
1182 len = endspc - endword;
1183 /* line = endspc; */
1184 if (off != zero) {
1185 if (off + len >= body_cols) {
1186 emitline(tab, zero, &off, l, &linestart, &cont);
1187 linestart = endspc;
1188 } else
1189 off += len;
1192 line = endspc;
1195 emitline(tab, zero, &off, l, &linestart, &cont);
1198 static int
1199 hardwrap_text(struct tab *tab, struct line *l)
1201 size_t off, len;
1202 int cont;
1203 const char *linestart;
1205 if (l->line == NULL)
1206 return emitline(tab, 0, &off, l, &linestart, &cont);
1208 len = strlen(l->line);
1209 off = 0;
1210 linestart = l->line;
1212 while (len >= COLS) {
1213 len -= COLS-1;
1214 off = COLS-1;
1215 if (!emitline(tab, 0, &off, l, &linestart, &cont))
1216 return 0;
1219 if (len != 0)
1220 return emitline(tab, 0, &len, l, &linestart, &cont);
1222 return 1;
1225 static int
1226 wrap_page(struct tab *tab)
1228 struct line *l;
1229 const char *prfx;
1231 empty_vlist(tab);
1233 TAILQ_FOREACH(l, &tab->page.head, lines) {
1234 prfx = line_prefixes[l->type].prfx1;
1235 switch (l->type) {
1236 case LINE_TEXT:
1237 case LINE_LINK:
1238 case LINE_TITLE_1:
1239 case LINE_TITLE_2:
1240 case LINE_TITLE_3:
1241 case LINE_ITEM:
1242 case LINE_QUOTE:
1243 wrap_text(tab, prfx, l);
1244 break;
1245 case LINE_PRE_START:
1246 case LINE_PRE_END:
1247 push_line(tab, l, NULL, 0, 0);
1248 break;
1249 case LINE_PRE_CONTENT:
1250 hardwrap_text(tab, l);
1251 break;
1254 return 1;
1257 static inline void
1258 print_line(struct line *l)
1260 const char *text = l->line;
1261 const char *prfx;
1262 int face = line_faces[l->type].prop;
1264 if (!l->flags)
1265 prfx = line_prefixes[l->type].prfx1;
1266 else
1267 prfx = line_prefixes[l->type].prfx2;
1269 if (text == NULL)
1270 text = "";
1272 if (face != 0)
1273 wattron(body, face);
1274 wprintw(body, "%s%s", prfx, text);
1275 if (face != 0)
1276 wattroff(body, face);
1279 static void
1280 redraw_tabline(void)
1282 struct tab *tab;
1283 int current;
1284 const char *title;
1286 werase(tabline);
1287 wbkgd(tabline, A_REVERSE);
1289 wprintw(tabline, " ");
1290 TAILQ_FOREACH(tab, &tabshead, tabs) {
1291 current = tab->flags & TAB_CURRENT;
1293 if (*(title = tab->page.title) == '\0')
1294 title = tab->urlstr;
1296 if (current)
1297 wattron(tabline, A_UNDERLINE);
1299 wprintw(tabline, "%s%d: %s",
1300 current ? "*" : " ", tab->id, title);
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();