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 * Text scrolling
21 * ==============
22 *
23 * ncurses allows you to scroll a window, but when a line goes out of
24 * the visible area it's forgotten. We keep a list of formatted lines
25 * (``visual lines'') that we know fits in the window, and draw them.
26 *
27 * This means that on every resize we have to clear our list of lines
28 * and re-render everything. A clever approach would be to do this
29 * ``on-demand'', but it's still missing.
30 *
31 */
33 #include "telescope.h"
35 #include <assert.h>
36 #include <curses.h>
37 #include <event.h>
38 #include <locale.h>
39 #include <signal.h>
40 #include <stdarg.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h>
45 static struct event stdioev, winchev;
47 static void restore_curs_x(struct buffer *);
48 static void minibuffer_hist_save_entry(void);
49 static void minibuffer_self_insert(void);
50 static void yornp_self_insert(void);
51 static void yornp_abort(void);
52 static void read_self_insert(void);
53 static void read_abort(void);
54 static void read_select(void);
56 static struct vline *nth_line(struct buffer*, size_t);
57 static struct buffer *current_buffer(void);
58 static int readkey(void);
59 static void dispatch_stdio(int, short, void*);
60 static void handle_clear_minibuf(int, short, void*);
61 static void handle_resize(int, short, void*);
62 static void handle_resize_nodelay(int, short, void*);
63 static int wrap_page(struct buffer*, int);
64 static void print_vline(int, int, WINDOW*, struct vline*);
65 static void redraw_tabline(void);
66 static void redraw_window(WINDOW*, int, int, struct buffer*);
67 static void redraw_help(void);
68 static void redraw_body(struct tab*);
69 static void redraw_modeline(struct tab*);
70 static void redraw_minibuffer(void);
71 static void redraw_tab(struct tab*);
72 static void emit_help_item(char*, void*);
73 static void rec_compute_help(struct kmap*, char*, size_t);
74 static void recompute_help(void);
75 static void update_loading_anim(int, short, void*);
76 static void stop_loading_anim(struct tab*);
78 static int x_offset;
80 struct thiskey thiskey;
82 static struct event resizeev;
83 static struct timeval resize_timer = { 0, 250000 };
85 static WINDOW *tabline, *body, *modeline, *minibuf;
87 int body_lines, body_cols;
89 static WINDOW *help;
90 static struct buffer helpwin;
91 static int help_lines, help_cols;
93 static int side_window;
95 static struct event clminibufev;
96 static struct timeval clminibufev_timer = { 5, 0 };
97 static struct timeval loadingev_timer = { 0, 250000 };
99 static uint32_t tab_counter;
101 static char keybuf[64];
103 static void (*yornp_cb)(int, struct tab *);
104 static struct tab *yornp_data;
106 static void (*read_cb)(const char*, unsigned int);
107 static unsigned int read_data;
109 struct kmap global_map,
110 minibuffer_map,
111 *current_map,
112 *base_map;
114 struct histhead eecmd_history,
115 ir_history,
116 lu_history,
117 read_history;
119 int in_minibuffer;
121 struct ministate ministate;
123 static inline void
124 update_x_offset(void)
126 if (olivetti_mode && fill_column < body_cols)
127 x_offset = (body_cols - fill_column)/2;
128 else
129 x_offset = 0;
132 void
133 save_excursion(struct excursion *place, struct buffer *buffer)
135 place->curs_x = buffer->curs_x;
136 place->curs_y = buffer->curs_y;
137 place->line_off = buffer->line_off;
138 place->current_line = buffer->current_line;
139 place->cpoff = buffer->cpoff;
142 void
143 restore_excursion(struct excursion *place, struct buffer *buffer)
145 buffer->curs_x = place->curs_x;
146 buffer->curs_y = place->curs_y;
147 buffer->line_off = place->line_off;
148 buffer->current_line = place->current_line;
149 buffer->cpoff = place->cpoff;
152 static void
153 restore_curs_x(struct buffer *buffer)
155 struct vline *vl;
156 const char *prfx;
158 vl = buffer->current_line;
159 if (vl == NULL || vl->line == NULL)
160 buffer->curs_x = buffer->cpoff = 0;
161 else
162 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
164 buffer->curs_x += x_offset;
166 if (vl != NULL) {
167 prfx = line_prefixes[vl->parent->type].prfx1;
168 buffer->curs_x += utf8_swidth(prfx);
172 void
173 global_key_unbound(void)
175 message("%s is undefined", keybuf);
178 static void
179 minibuffer_hist_save_entry(void)
181 struct hist *hist;
183 if (ministate.history == NULL)
184 return;
186 if ((hist = calloc(1, sizeof(*hist))) == NULL)
187 abort();
189 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
191 if (TAILQ_EMPTY(&ministate.history->head))
192 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
193 else
194 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
195 ministate.history->len++;
198 /*
199 * taint the minibuffer cache: if we're currently showing a history
200 * element, copy that to the current buf and reset the "history
201 * navigation" thing.
202 */
203 void
204 minibuffer_taint_hist(void)
206 if (ministate.hist_cur == NULL)
207 return;
209 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
210 ministate.hist_cur = NULL;
213 static void
214 minibuffer_self_insert(void)
216 char *c, tmp[5] = {0};
217 size_t len;
219 minibuffer_taint_hist();
221 if (thiskey.cp == 0)
222 return;
224 len = utf8_encode(thiskey.cp, tmp);
225 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
226 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
227 return;
229 memmove(c + len, c, strlen(c)+1);
230 memcpy(c, tmp, len);
231 ministate.buffer.cpoff++;
234 void
235 eecmd_self_insert(void)
237 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
238 !unicode_isgraph(thiskey.cp)) {
239 global_key_unbound();
240 return;
243 minibuffer_self_insert();
246 void
247 eecmd_select(void)
249 struct cmd *cmd;
251 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
252 if (!strcmp(cmd->cmd, ministate.buf)) {
253 exit_minibuffer();
254 minibuffer_hist_save_entry();
255 cmd->fn(current_buffer());
256 return;
260 message("No match");
263 void
264 ir_self_insert(void)
266 minibuffer_self_insert();
269 void
270 ir_select(void)
272 char buf[1025] = {0};
273 struct phos_uri uri;
274 struct tab *tab;
276 tab = current_tab();
278 exit_minibuffer();
279 minibuffer_hist_save_entry();
281 /* a bit ugly but... */
282 memcpy(&uri, &tab->uri, sizeof(tab->uri));
283 phos_uri_set_query(&uri, ministate.buf);
284 phos_serialize_uri(&uri, buf, sizeof(buf));
285 load_url_in_tab(tab, buf);
288 void
289 lu_self_insert(void)
291 if (thiskey.meta || unicode_isspace(thiskey.key) ||
292 !unicode_isgraph(thiskey.key)) {
293 global_key_unbound();
294 return;
297 minibuffer_self_insert();
300 void
301 lu_select(void)
303 exit_minibuffer();
304 minibuffer_hist_save_entry();
305 load_url_in_tab(current_tab(), ministate.buf);
308 void
309 bp_select(void)
311 exit_minibuffer();
312 if (*ministate.buf != '\0')
313 add_to_bookmarks(ministate.buf);
314 else
315 message("Abort.");
318 static void
319 yornp_self_insert(void)
321 if (thiskey.key != 'y' && thiskey.key != 'n') {
322 message("Please answer y or n");
323 return;
326 exit_minibuffer();
327 yornp_cb(thiskey.key == 'y', yornp_data);
330 static void
331 yornp_abort(void)
333 exit_minibuffer();
334 yornp_cb(0, yornp_data);
337 static void
338 read_self_insert(void)
340 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
341 global_key_unbound();
342 return;
345 minibuffer_self_insert();
348 static void
349 read_abort(void)
351 exit_minibuffer();
352 read_cb(NULL, read_data);
355 static void
356 read_select(void)
358 exit_minibuffer();
359 minibuffer_hist_save_entry();
360 read_cb(ministate.buf, read_data);
363 static struct vline *
364 nth_line(struct buffer *buffer, size_t n)
366 struct vline *vl;
367 size_t i;
369 i = 0;
370 TAILQ_FOREACH(vl, &buffer->head, vlines) {
371 if (i == n)
372 return vl;
373 i++;
376 /* unreachable */
377 abort();
380 struct tab *
381 current_tab(void)
383 struct tab *t;
385 TAILQ_FOREACH(t, &tabshead, tabs) {
386 if (t->flags & TAB_CURRENT)
387 return t;
390 /* unreachable */
391 abort();
394 struct buffer *
395 current_buffer(void)
397 if (in_minibuffer)
398 return &ministate.buffer;
399 return &current_tab()->buffer;
402 static int
403 readkey(void)
405 uint32_t state = 0;
407 if ((thiskey.key = wgetch(body)) == ERR)
408 return 0;
410 thiskey.meta = thiskey.key == 27;
411 if (thiskey.meta) {
412 thiskey.key = wgetch(body);
413 if (thiskey.key == ERR || thiskey.key == 27) {
414 thiskey.meta = 0;
415 thiskey.key = 27;
419 thiskey.cp = 0;
420 if ((unsigned int)thiskey.key < UINT8_MAX) {
421 while (1) {
422 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
423 break;
424 if ((thiskey.key = wgetch(body)) == ERR) {
425 message("Error decoding user input");
426 return 0;
431 return 1;
434 static void
435 dispatch_stdio(int fd, short ev, void *d)
437 struct keymap *k;
438 const char *keyname;
439 char tmp[5] = {0};
441 if (!readkey())
442 return;
444 if (keybuf[0] != '\0')
445 strlcat(keybuf, " ", sizeof(keybuf));
446 if (thiskey.meta)
447 strlcat(keybuf, "M-", sizeof(keybuf));
448 if (thiskey.cp != 0) {
449 utf8_encode(thiskey.cp, tmp);
450 strlcat(keybuf, tmp, sizeof(keybuf));
451 } else {
452 if ((keyname = unkbd(thiskey.key)) != NULL)
453 strlcat(keybuf, keyname, sizeof(keybuf));
454 else {
455 tmp[0] = thiskey.key;
456 strlcat(keybuf, tmp, sizeof(keybuf));
460 TAILQ_FOREACH(k, &current_map->m, keymaps) {
461 if (k->meta == thiskey.meta &&
462 k->key == thiskey.key) {
463 if (k->fn == NULL)
464 current_map = &k->map;
465 else {
466 current_map = base_map;
467 strlcpy(keybuf, "", sizeof(keybuf));
468 k->fn(current_buffer());
470 goto done;
474 if (current_map->unhandled_input != NULL)
475 current_map->unhandled_input();
476 else
477 global_key_unbound();
479 strlcpy(keybuf, "", sizeof(keybuf));
480 current_map = base_map;
482 done:
483 if (side_window)
484 recompute_help();
486 redraw_tab(current_tab());
489 static void
490 handle_clear_minibuf(int fd, short ev, void *d)
492 free(ministate.curmesg);
493 ministate.curmesg = NULL;
495 redraw_minibuffer();
496 if (in_minibuffer) {
497 wrefresh(body);
498 wrefresh(minibuf);
499 } else {
500 wrefresh(minibuf);
501 wrefresh(body);
505 static void
506 handle_resize(int sig, short ev, void *d)
508 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
509 event_del(&resizeev);
511 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
512 evtimer_add(&resizeev, &resize_timer);
515 static void
516 handle_resize_nodelay(int s, short ev, void *d)
518 struct tab *tab;
520 endwin();
521 refresh();
522 clear();
524 /* move and resize the windows, in reverse order! */
526 mvwin(minibuf, LINES-1, 0);
527 wresize(minibuf, 1, COLS);
529 mvwin(modeline, LINES-2, 0);
530 wresize(modeline, 1, COLS);
532 body_lines = LINES-3;
533 body_cols = COLS;
535 if (side_window) {
536 help_cols = 0.3 * COLS;
537 help_lines = LINES-3;
538 mvwin(help, 1, 0);
539 wresize(help, help_lines, help_cols);
541 wrap_page(&helpwin, help_cols);
543 body_cols = COLS - help_cols - 1;
544 mvwin(body, 1, help_cols);
545 } else
546 mvwin(body, 1, 0);
548 update_x_offset();
549 wresize(body, body_lines, body_cols);
551 wresize(tabline, 1, COLS);
553 tab = current_tab();
555 wrap_page(&tab->buffer, body_cols);
556 redraw_tab(tab);
559 static int
560 wrap_page(struct buffer *buffer, int width)
562 struct line *l;
563 const struct line *top_orig, *orig;
564 struct vline *vl;
565 int pre_width;
566 const char *prfx;
568 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
569 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
571 buffer->top_line = NULL;
572 buffer->current_line = NULL;
574 buffer->force_redraw = 1;
575 buffer->curs_y = 0;
576 buffer->line_off = 0;
578 empty_vlist(buffer);
580 TAILQ_FOREACH(l, &buffer->page.head, lines) {
581 prfx = line_prefixes[l->type].prfx1;
582 switch (l->type) {
583 case LINE_TEXT:
584 case LINE_LINK:
585 case LINE_TITLE_1:
586 case LINE_TITLE_2:
587 case LINE_TITLE_3:
588 case LINE_ITEM:
589 case LINE_QUOTE:
590 case LINE_PRE_START:
591 case LINE_PRE_END:
592 wrap_text(buffer, prfx, l, MIN(fill_column, width));
593 break;
594 case LINE_PRE_CONTENT:
595 if (olivetti_mode)
596 pre_width = MIN(fill_column, width);
597 else
598 pre_width = width;
599 hardwrap_text(buffer, l, pre_width);
600 break;
603 if (top_orig == l && buffer->top_line == NULL) {
604 buffer->line_off = buffer->line_max-1;
605 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
607 while (1) {
608 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
609 if (vl == NULL || vl->parent != orig)
610 break;
611 buffer->top_line = vl;
612 buffer->line_off--;
616 if (orig == l && buffer->current_line == NULL) {
617 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
619 while (1) {
620 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
621 if (vl == NULL || vl->parent != orig)
622 break;
623 buffer->current_line = vl;
628 if (buffer->current_line == NULL)
629 buffer->current_line = TAILQ_FIRST(&buffer->head);
631 if (buffer->top_line == NULL)
632 buffer->top_line = buffer->current_line;
634 return 1;
637 static void
638 print_vline(int off, int width, WINDOW *window, struct vline *vl)
640 const char *text;
641 const char *prfx;
642 struct line_face *f;
643 int i, left, x, y;
645 f = &line_faces[vl->parent->type];
647 /* unused, set by getyx */
648 (void)y;
650 if (!vl->flags)
651 prfx = line_prefixes[vl->parent->type].prfx1;
652 else
653 prfx = line_prefixes[vl->parent->type].prfx2;
655 text = vl->line;
656 if (text == NULL)
657 text = "";
659 wattr_on(window, body_face.left, NULL);
660 for (i = 0; i < off; i++)
661 waddch(window, ' ');
662 wattr_off(window, body_face.left, NULL);
664 wattr_on(window, f->prefix, NULL);
665 wprintw(window, "%s", prfx);
666 wattr_off(window, f->prefix, NULL);
668 wattr_on(window, f->text, NULL);
669 wprintw(window, "%s", text);
670 wattr_off(window, f->text, NULL);
672 getyx(window, y, x);
674 left = width - x;
676 wattr_on(window, f->trail, NULL);
677 for (i = 0; i < left - off; ++i)
678 waddch(window, ' ');
679 wattr_off(window, f->trail, NULL);
681 wattr_on(window, body_face.right, NULL);
682 for (i = 0; i < off; i++)
683 waddch(window, ' ');
684 wattr_off(window, body_face.right, NULL);
688 static void
689 redraw_tabline(void)
691 struct tab *tab;
692 size_t toskip, ots, tabwidth, space, x;
693 int current, y, truncated;
694 const char *title;
695 char buf[25];
697 x = 0;
699 /* unused, but setted by a getyx */
700 (void)y;
702 tabwidth = sizeof(buf)+1;
703 space = COLS-2;
705 toskip = 0;
706 TAILQ_FOREACH(tab, &tabshead, tabs) {
707 toskip++;
708 if (tab->flags & TAB_CURRENT)
709 break;
712 if (toskip * tabwidth < space)
713 toskip = 0;
714 else {
715 ots = toskip;
716 toskip--;
717 while (toskip != 0 &&
718 (ots - toskip+1) * tabwidth < space)
719 toskip--;
722 werase(tabline);
723 wattr_on(tabline, tab_face.background, NULL);
724 wprintw(tabline, toskip == 0 ? " " : "<");
725 wattr_off(tabline, tab_face.background, NULL);
727 truncated = 0;
728 TAILQ_FOREACH(tab, &tabshead, tabs) {
729 if (truncated)
730 break;
731 if (toskip != 0) {
732 toskip--;
733 continue;
736 getyx(tabline, y, x);
737 if (x + sizeof(buf)+2 >= (size_t)COLS)
738 truncated = 1;
740 current = tab->flags & TAB_CURRENT;
742 if (*(title = tab->buffer.page.title) == '\0')
743 title = tab->hist_cur->h;
745 if (tab->flags & TAB_URGENT)
746 strlcpy(buf, "!", sizeof(buf));
747 else
748 strlcpy(buf, " ", sizeof(buf));
750 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
751 /* truncation happens */
752 strlcpy(&buf[sizeof(buf)-4], "...", 4);
753 } else {
754 /* pad with spaces */
755 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
756 /* nop */ ;
759 if (current)
760 wattr_on(tabline, tab_face.current, NULL);
761 else
762 wattr_on(tabline, tab_face.tab, NULL);
764 wprintw(tabline, "%s", buf);
765 if (TAILQ_NEXT(tab, tabs) != NULL)
766 wprintw(tabline, " ");
768 if (current)
769 wattr_off(tabline, tab_face.current, NULL);
770 else
771 wattr_off(tabline, tab_face.tab, NULL);
774 wattr_on(tabline, tab_face.background, NULL);
775 for (; x < (size_t)COLS; ++x)
776 waddch(tabline, ' ');
777 if (truncated)
778 mvwprintw(tabline, 0, COLS-1, ">");
779 wattr_off(tabline, tab_face.background, NULL);
782 /*
783 * Compute the first visible line around vl. Try to search forward
784 * until the end of the buffer; if a visible line is not found, search
785 * backward. Return NULL if no viable line was found.
786 */
787 static inline struct vline *
788 adjust_line(struct vline *vl, struct buffer *buffer)
790 struct vline *t;
792 if (!(vl->parent->flags & L_HIDDEN))
793 return vl;
795 /* search forward */
796 for (t = vl;
797 t != NULL && t->parent->flags & L_HIDDEN;
798 t = TAILQ_NEXT(t, vlines))
799 ; /* nop */
801 if (t != NULL)
802 return t;
804 /* search backward */
805 for (t = vl;
806 t != NULL && t->parent->flags & L_HIDDEN;
807 t = TAILQ_PREV(t, vhead, vlines))
808 ; /* nop */
810 return t;
813 static void
814 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
816 struct vline *vl;
817 int l, onscreen;
819 restore_curs_x(buffer);
821 /*
822 * TODO: ignoring buffer->force_update and always
823 * re-rendering. In theory we can recompute the y position
824 * without a re-render, and optimize here. It's not the only
825 * optimisation possible here, wscrl wolud also be an
826 * interesting one.
827 */
829 again:
830 werase(win);
831 buffer->curs_y = 0;
833 if (TAILQ_EMPTY(&buffer->head))
834 goto end;
836 buffer->top_line = adjust_line(buffer->top_line, buffer);
837 if (buffer->top_line == NULL)
838 goto end;
840 buffer->current_line = adjust_line(buffer->current_line, buffer);
842 l = 0;
843 onscreen = 0;
844 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
845 if (vl->parent->flags & L_HIDDEN)
846 continue;
848 wmove(win, l, 0);
849 print_vline(x_offset, width, win, vl);
851 if (vl == buffer->current_line)
852 onscreen = 1;
854 if (!onscreen)
855 buffer->curs_y++;
857 l++;
858 if (l == height)
859 break;
862 if (!onscreen) {
863 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
864 if (vl == buffer->current_line)
865 break;
866 if (vl->parent->flags & L_HIDDEN)
867 continue;
868 buffer->line_off++;
869 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
872 goto again;
875 buffer->last_line_off = buffer->line_off;
876 buffer->force_redraw = 0;
877 end:
878 wmove(win, buffer->curs_y, buffer->curs_x);
881 static void
882 redraw_help(void)
884 redraw_window(help, help_lines, help_cols, &helpwin);
887 static void
888 redraw_body(struct tab *tab)
890 static struct tab *last_tab;
892 if (last_tab != tab)
893 tab->buffer.force_redraw =1;
894 last_tab = tab;
896 redraw_window(body, body_lines, body_cols, &tab->buffer);
899 static inline char
900 trust_status_char(enum trust_state ts)
902 switch (ts) {
903 case TS_UNKNOWN: return 'u';
904 case TS_UNTRUSTED: return '!';
905 case TS_TEMP_TRUSTED: return '!';
906 case TS_TRUSTED: return 'v';
907 case TS_VERIFIED: return 'V';
908 default: return 'X';
912 static void
913 redraw_modeline(struct tab *tab)
915 double pct;
916 int x, y, max_x, max_y;
917 const char *mode = tab->buffer.page.name;
918 const char *spin = "-\\|/";
920 werase(modeline);
921 wattr_on(modeline, modeline_face.background, NULL);
922 wmove(modeline, 0, 0);
924 wprintw(modeline, "-%c%c %s ",
925 spin[tab->loading_anim_step],
926 trust_status_char(tab->trust),
927 mode == NULL ? "(none)" : mode);
929 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
931 if (tab->buffer.line_max <= (size_t)body_lines)
932 wprintw(modeline, "All ");
933 else if (tab->buffer.line_off == 0)
934 wprintw(modeline, "Top ");
935 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
936 wprintw(modeline, "Bottom ");
937 else
938 wprintw(modeline, "%.0f%% ", pct);
940 wprintw(modeline, "%d/%d %s ",
941 tab->buffer.line_off + tab->buffer.curs_y,
942 tab->buffer.line_max,
943 tab->hist_cur->h);
945 getyx(modeline, y, x);
946 getmaxyx(modeline, max_y, max_x);
948 (void)y;
949 (void)max_y;
951 for (; x < max_x; ++x)
952 waddstr(modeline, "-");
954 wattr_off(modeline, modeline_face.background, NULL);
957 static void
958 redraw_minibuffer(void)
960 struct tab *tab;
961 size_t off_y, off_x = 0;
962 char *start = NULL, *c = NULL;
964 /* unused, but set by getyx */
965 (void)off_y;
967 wattr_on(minibuf, minibuffer_face.background, NULL);
968 werase(minibuf);
970 if (in_minibuffer) {
971 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
972 if (ministate.hist_cur != NULL)
973 wprintw(minibuf, "(%zu/%zu) ",
974 ministate.hist_off + 1,
975 ministate.history->len);
977 getyx(minibuf, off_y, off_x);
979 start = ministate.hist_cur != NULL
980 ? ministate.hist_cur->h
981 : ministate.buf;
982 c = utf8_nth(ministate.buffer.current_line->line,
983 ministate.buffer.cpoff);
984 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
985 start = utf8_next_cp(start);
988 waddstr(minibuf, start);
991 if (ministate.curmesg != NULL)
992 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
993 ministate.curmesg);
995 if (!in_minibuffer && ministate.curmesg == NULL)
996 waddstr(minibuf, keybuf);
998 /* If nothing else, show the URL at point */
999 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1000 tab = current_tab();
1001 if (tab->buffer.current_line != NULL &&
1002 tab->buffer.current_line->parent->type == LINE_LINK)
1003 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1006 if (in_minibuffer)
1007 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1009 wattr_off(minibuf, minibuffer_face.background, NULL);
1012 static void
1013 redraw_tab(struct tab *tab)
1015 if (side_window) {
1016 redraw_help();
1017 wnoutrefresh(help);
1020 redraw_tabline();
1021 redraw_body(tab);
1022 redraw_modeline(tab);
1023 redraw_minibuffer();
1025 wnoutrefresh(tabline);
1026 wnoutrefresh(modeline);
1028 if (in_minibuffer) {
1029 wnoutrefresh(body);
1030 wnoutrefresh(minibuf);
1031 } else {
1032 wnoutrefresh(minibuf);
1033 wnoutrefresh(body);
1036 doupdate();
1039 static void
1040 emit_help_item(char *prfx, void *fn)
1042 struct line *l;
1043 struct cmd *cmd;
1045 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1046 if (fn == cmd->fn)
1047 break;
1049 assert(cmd != NULL);
1051 if ((l = calloc(1, sizeof(*l))) == NULL)
1052 abort();
1054 l->type = LINE_TEXT;
1055 l->alt = NULL;
1057 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1059 if (TAILQ_EMPTY(&helpwin.page.head))
1060 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1061 else
1062 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1065 static void
1066 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1068 struct keymap *k;
1069 char p[32];
1070 const char *kn;
1072 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1073 strlcpy(p, prfx, sizeof(p));
1074 if (*p != '\0')
1075 strlcat(p, " ", sizeof(p));
1076 if (k->meta)
1077 strlcat(p, "M-", sizeof(p));
1078 if ((kn = unkbd(k->key)) != NULL)
1079 strlcat(p, kn, sizeof(p));
1080 else
1081 strlcat(p, keyname(k->key), sizeof(p));
1083 if (k->fn == NULL)
1084 rec_compute_help(&k->map, p, sizeof(p));
1085 else
1086 emit_help_item(p, k->fn);
1090 static void
1091 recompute_help(void)
1093 char p[32] = { 0 };
1095 empty_vlist(&helpwin);
1096 empty_linelist(&helpwin);
1097 rec_compute_help(current_map, p, sizeof(p));
1098 wrap_page(&helpwin, help_cols);
1101 void
1102 vmessage(const char *fmt, va_list ap)
1104 if (evtimer_pending(&clminibufev, NULL))
1105 evtimer_del(&clminibufev);
1107 free(ministate.curmesg);
1108 ministate.curmesg = NULL;
1110 if (fmt != NULL) {
1111 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1112 evtimer_add(&clminibufev, &clminibufev_timer);
1114 /* TODO: what to do if the allocation fails here? */
1115 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1116 ministate.curmesg = NULL;
1119 redraw_minibuffer();
1120 if (in_minibuffer) {
1121 wrefresh(body);
1122 wrefresh(minibuf);
1123 } else {
1124 wrefresh(minibuf);
1125 wrefresh(body);
1129 void
1130 message(const char *fmt, ...)
1132 va_list ap;
1134 va_start(ap, fmt);
1135 vmessage(fmt, ap);
1136 va_end(ap);
1139 void
1140 start_loading_anim(struct tab *tab)
1142 if (tab->loading_anim)
1143 return;
1144 tab->loading_anim = 1;
1145 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1146 evtimer_add(&tab->loadingev, &loadingev_timer);
1149 static void
1150 update_loading_anim(int fd, short ev, void *d)
1152 struct tab *tab = d;
1154 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1156 if (tab->flags & TAB_CURRENT) {
1157 redraw_modeline(tab);
1158 wrefresh(modeline);
1159 wrefresh(body);
1160 if (in_minibuffer)
1161 wrefresh(minibuf);
1164 evtimer_add(&tab->loadingev, &loadingev_timer);
1167 static void
1168 stop_loading_anim(struct tab *tab)
1170 if (!tab->loading_anim)
1171 return;
1172 evtimer_del(&tab->loadingev);
1173 tab->loading_anim = 0;
1174 tab->loading_anim_step = 0;
1176 if (!(tab->flags & TAB_CURRENT))
1177 return;
1179 redraw_modeline(tab);
1181 wrefresh(modeline);
1182 wrefresh(body);
1183 if (in_minibuffer)
1184 wrefresh(minibuf);
1187 void
1188 load_url_in_tab(struct tab *tab, const char *url)
1190 message("Loading %s...", url);
1191 start_loading_anim(tab);
1192 load_url(tab, url);
1194 tab->buffer.curs_x = 0;
1195 tab->buffer.curs_y = 0;
1196 redraw_tab(tab);
1199 void
1200 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1201 void (*abortfn)(void), struct histhead *hist)
1203 in_minibuffer = 1;
1204 base_map = &minibuffer_map;
1205 current_map = &minibuffer_map;
1207 base_map->unhandled_input = self_insert_fn;
1209 ministate.donefn = donefn;
1210 ministate.abortfn = abortfn;
1211 memset(ministate.buf, 0, sizeof(ministate.buf));
1212 ministate.buffer.current_line = &ministate.vline;
1213 ministate.buffer.current_line->line = ministate.buf;
1214 ministate.buffer.cpoff = 0;
1215 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1217 ministate.history = hist;
1218 ministate.hist_cur = NULL;
1219 ministate.hist_off = 0;
1222 void
1223 exit_minibuffer(void)
1225 werase(minibuf);
1227 in_minibuffer = 0;
1228 base_map = &global_map;
1229 current_map = &global_map;
1232 void
1233 switch_to_tab(struct tab *tab)
1235 struct tab *t;
1237 TAILQ_FOREACH(t, &tabshead, tabs) {
1238 t->flags &= ~TAB_CURRENT;
1241 tab->flags |= TAB_CURRENT;
1242 tab->flags &= ~TAB_URGENT;
1245 unsigned int
1246 tab_new_id(void)
1248 return tab_counter++;
1251 struct tab *
1252 new_tab(const char *url)
1254 struct tab *tab;
1256 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1257 event_loopbreak();
1258 return NULL;
1260 tab->fd = -1;
1262 TAILQ_INIT(&tab->hist.head);
1264 TAILQ_INIT(&tab->buffer.head);
1266 tab->id = tab_new_id();
1267 switch_to_tab(tab);
1269 if (TAILQ_EMPTY(&tabshead))
1270 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1271 else
1272 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1274 load_url_in_tab(tab, url);
1275 return tab;
1278 int
1279 ui_init()
1281 setlocale(LC_ALL, "");
1283 TAILQ_INIT(&eecmd_history.head);
1284 TAILQ_INIT(&ir_history.head);
1285 TAILQ_INIT(&lu_history.head);
1287 ministate.line.type = LINE_TEXT;
1288 ministate.vline.parent = &ministate.line;
1289 ministate.buffer.current_line = &ministate.vline;
1291 /* initialize help window */
1292 TAILQ_INIT(&helpwin.head);
1294 base_map = &global_map;
1295 current_map = &global_map;
1297 initscr();
1299 if (enable_colors) {
1300 if (has_colors()) {
1301 start_color();
1302 use_default_colors();
1303 } else
1304 enable_colors = 0;
1307 config_apply_style();
1309 raw();
1310 noecho();
1311 nonl();
1312 intrflush(stdscr, FALSE);
1314 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1315 return 0;
1316 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1317 return 0;
1318 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1319 return 0;
1320 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1321 return 0;
1322 if ((help = newwin(1, 1, 1, 0)) == NULL)
1323 return 0;
1325 body_lines = LINES-3;
1326 body_cols = COLS;
1328 wbkgd(body, body_face.body);
1329 wbkgd(minibuf, minibuffer_face.background);
1331 update_x_offset();
1333 keypad(body, TRUE);
1334 scrollok(body, FALSE);
1336 /* non-blocking input */
1337 wtimeout(body, 0);
1339 mvwprintw(body, 0, 0, "");
1341 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1342 event_add(&stdioev, NULL);
1344 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1345 signal_add(&winchev, NULL);
1347 return 1;
1350 void
1351 ui_on_tab_loaded(struct tab *tab)
1353 stop_loading_anim(tab);
1354 message("Loaded %s", tab->hist_cur->h);
1356 redraw_tabline();
1357 wrefresh(tabline);
1358 if (in_minibuffer)
1359 wrefresh(minibuf);
1360 else
1361 wrefresh(body);
1364 void
1365 ui_on_tab_refresh(struct tab *tab)
1367 wrap_page(&tab->buffer, body_cols);
1368 if (tab->flags & TAB_CURRENT)
1369 redraw_tab(tab);
1370 else
1371 tab->flags |= TAB_URGENT;
1374 const char *
1375 ui_keyname(int k)
1377 return keyname(k);
1380 void
1381 ui_toggle_side_window(void)
1383 side_window = !side_window;
1384 if (side_window)
1385 recompute_help();
1388 * ugly hack, but otherwise the window doesn't get updated
1389 * until I call handle_resize a second time (i.e. C-l). I
1390 * will be happy to know why something like this is needed.
1392 handle_resize_nodelay(0, 0, NULL);
1393 handle_resize_nodelay(0, 0, NULL);
1396 void
1397 ui_schedule_redraw(void)
1399 handle_resize_nodelay(0, 0, NULL);
1402 void
1403 ui_require_input(struct tab *tab, int hide)
1405 /* TODO: hard-switching to another tab is ugly */
1406 switch_to_tab(tab);
1408 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1409 &ir_history);
1410 strlcpy(ministate.prompt, "Input required: ",
1411 sizeof(ministate.prompt));
1412 redraw_tab(tab);
1415 void
1416 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1417 struct tab *data)
1419 size_t len;
1421 if (in_minibuffer) {
1422 fn(0, data);
1423 return;
1426 yornp_cb = fn;
1427 yornp_data = data;
1428 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1429 yornp_abort, NULL);
1431 len = sizeof(ministate.prompt);
1432 strlcpy(ministate.prompt, prompt, len);
1433 strlcat(ministate.prompt, " (y or n) ", len);
1434 redraw_tab(current_tab());
1437 void
1438 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1439 unsigned int data)
1441 size_t len;
1443 if (in_minibuffer)
1444 return;
1446 read_cb = fn;
1447 read_data = data;
1448 enter_minibuffer(read_self_insert, read_select, read_abort,
1449 &read_history);
1451 len = sizeof(ministate.prompt);
1452 strlcpy(ministate.prompt, prompt, len);
1453 strlcat(ministate.prompt, ": ", len);
1454 redraw_tab(current_tab());
1457 void
1458 ui_end(void)
1460 endwin();