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 <limits.h>
39 #include <locale.h>
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
46 static struct event stdioev, winchev;
48 static void restore_curs_x(struct buffer *);
49 static void global_key_unbound(void);
50 static void minibuffer_hist_save_entry(void);
51 static void minibuffer_self_insert(void);
52 static void yornp_self_insert(void);
53 static void yornp_abort(void);
54 static void read_self_insert(void);
55 static void read_abort(void);
56 static void read_select(void);
58 static struct vline *nth_line(struct buffer*, size_t);
59 static struct buffer *current_buffer(void);
60 static int readkey(void);
61 static void dispatch_stdio(int, short, void*);
62 static void handle_clear_minibuf(int, short, void*);
63 static void handle_resize(int, short, void*);
64 static void handle_resize_nodelay(int, short, void*);
65 static int wrap_page(struct buffer*, int);
66 static void print_vline(int, int, WINDOW*, struct vline*);
67 static void redraw_tabline(void);
68 static void redraw_window(WINDOW*, int, int, struct buffer*);
69 static void redraw_help(void);
70 static void redraw_body(struct tab*);
71 static void redraw_modeline(struct tab*);
72 static void redraw_minibuffer(void);
73 static void redraw_tab(struct tab*);
74 static void emit_help_item(char*, void*);
75 static void rec_compute_help(struct kmap*, char*, size_t);
76 static void recompute_help(void);
77 static void update_loading_anim(int, short, void*);
78 static void stop_loading_anim(struct tab*);
79 static void session_new_tab_cb(const char*);
80 static void usage(void);
82 static int x_offset;
84 struct thiskey thiskey;
86 static struct event resizeev;
87 static struct timeval resize_timer = { 0, 250000 };
89 static WINDOW *tabline, *body, *modeline, *minibuf;
91 int body_lines, body_cols;
93 static WINDOW *help;
94 static struct buffer helpwin;
95 static int help_lines, help_cols;
97 static int side_window;
99 static struct event clminibufev;
100 static struct timeval clminibufev_timer = { 5, 0 };
101 static struct timeval loadingev_timer = { 0, 250000 };
103 static uint32_t tab_counter;
105 static char keybuf[64];
107 static void (*yornp_cb)(int, struct tab *);
108 static struct tab *yornp_data;
110 static void (*read_cb)(const char*, unsigned int);
111 static unsigned int read_data;
113 struct kmap global_map,
114 minibuffer_map,
115 *current_map,
116 *base_map;
118 struct histhead eecmd_history,
119 ir_history,
120 lu_history,
121 read_history;
123 int in_minibuffer;
125 struct ministate ministate;
127 static inline void
128 update_x_offset(void)
130 if (olivetti_mode && fill_column < body_cols)
131 x_offset = (body_cols - fill_column)/2;
132 else
133 x_offset = 0;
136 void
137 save_excursion(struct excursion *place, struct buffer *buffer)
139 place->curs_x = buffer->curs_x;
140 place->curs_y = buffer->curs_y;
141 place->line_off = buffer->line_off;
142 place->current_line = buffer->current_line;
143 place->cpoff = buffer->cpoff;
146 void
147 restore_excursion(struct excursion *place, struct buffer *buffer)
149 buffer->curs_x = place->curs_x;
150 buffer->curs_y = place->curs_y;
151 buffer->line_off = place->line_off;
152 buffer->current_line = place->current_line;
153 buffer->cpoff = place->cpoff;
156 static void
157 restore_curs_x(struct buffer *buffer)
159 struct vline *vl;
160 const char *prfx;
162 vl = buffer->current_line;
163 if (vl == NULL || vl->line == NULL)
164 buffer->curs_x = buffer->cpoff = 0;
165 else
166 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
168 buffer->curs_x += x_offset;
170 if (vl != NULL) {
171 prfx = line_prefixes[vl->parent->type].prfx1;
172 buffer->curs_x += utf8_swidth(prfx);
176 static void
177 global_key_unbound(void)
179 message("%s is undefined", keybuf);
182 static void
183 minibuffer_hist_save_entry(void)
185 struct hist *hist;
187 if (ministate.history == NULL)
188 return;
190 if ((hist = calloc(1, sizeof(*hist))) == NULL)
191 abort();
193 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
195 if (TAILQ_EMPTY(&ministate.history->head))
196 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
197 else
198 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
199 ministate.history->len++;
202 /*
203 * taint the minibuffer cache: if we're currently showing a history
204 * element, copy that to the current buf and reset the "history
205 * navigation" thing.
206 */
207 void
208 minibuffer_taint_hist(void)
210 if (ministate.hist_cur == NULL)
211 return;
213 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
214 ministate.hist_cur = NULL;
217 static void
218 minibuffer_self_insert(void)
220 char *c, tmp[5] = {0};
221 size_t len;
223 minibuffer_taint_hist();
225 if (thiskey.cp == 0)
226 return;
228 len = utf8_encode(thiskey.cp, tmp);
229 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
230 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
231 return;
233 memmove(c + len, c, strlen(c)+1);
234 memcpy(c, tmp, len);
235 ministate.buffer.cpoff++;
238 void
239 eecmd_self_insert(void)
241 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
242 !unicode_isgraph(thiskey.cp)) {
243 global_key_unbound();
244 return;
247 minibuffer_self_insert();
250 void
251 eecmd_select(void)
253 struct cmd *cmd;
255 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
256 if (!strcmp(cmd->cmd, ministate.buf)) {
257 exit_minibuffer();
258 minibuffer_hist_save_entry();
259 cmd->fn(current_buffer());
260 return;
264 message("No match");
267 void
268 ir_self_insert(void)
270 minibuffer_self_insert();
273 void
274 ir_select(void)
276 char buf[1025] = {0};
277 struct phos_uri uri;
278 struct tab *tab;
280 tab = current_tab();
282 exit_minibuffer();
283 minibuffer_hist_save_entry();
285 /* a bit ugly but... */
286 memcpy(&uri, &tab->uri, sizeof(tab->uri));
287 phos_uri_set_query(&uri, ministate.buf);
288 phos_serialize_uri(&uri, buf, sizeof(buf));
289 load_url_in_tab(tab, buf);
292 void
293 lu_self_insert(void)
295 if (thiskey.meta || unicode_isspace(thiskey.key) ||
296 !unicode_isgraph(thiskey.key)) {
297 global_key_unbound();
298 return;
301 minibuffer_self_insert();
304 void
305 lu_select(void)
307 exit_minibuffer();
308 minibuffer_hist_save_entry();
309 load_url_in_tab(current_tab(), ministate.buf);
312 void
313 bp_select(void)
315 exit_minibuffer();
316 if (*ministate.buf != '\0')
317 add_to_bookmarks(ministate.buf);
318 else
319 message("Abort.");
322 static void
323 yornp_self_insert(void)
325 if (thiskey.key != 'y' && thiskey.key != 'n') {
326 message("Please answer y or n");
327 return;
330 exit_minibuffer();
331 yornp_cb(thiskey.key == 'y', yornp_data);
334 static void
335 yornp_abort(void)
337 exit_minibuffer();
338 yornp_cb(0, yornp_data);
341 static void
342 read_self_insert(void)
344 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
345 global_key_unbound();
346 return;
349 minibuffer_self_insert();
352 static void
353 read_abort(void)
355 exit_minibuffer();
356 read_cb(NULL, read_data);
359 static void
360 read_select(void)
362 exit_minibuffer();
363 minibuffer_hist_save_entry();
364 read_cb(ministate.buf, read_data);
367 static struct vline *
368 nth_line(struct buffer *buffer, size_t n)
370 struct vline *vl;
371 size_t i;
373 i = 0;
374 TAILQ_FOREACH(vl, &buffer->head, vlines) {
375 if (i == n)
376 return vl;
377 i++;
380 /* unreachable */
381 abort();
384 struct tab *
385 current_tab(void)
387 struct tab *t;
389 TAILQ_FOREACH(t, &tabshead, tabs) {
390 if (t->flags & TAB_CURRENT)
391 return t;
394 /* unreachable */
395 abort();
398 struct buffer *
399 current_buffer(void)
401 if (in_minibuffer)
402 return &ministate.buffer;
403 return &current_tab()->buffer;
406 static int
407 readkey(void)
409 uint32_t state = 0;
411 if ((thiskey.key = wgetch(body)) == ERR)
412 return 0;
414 thiskey.meta = thiskey.key == 27;
415 if (thiskey.meta) {
416 thiskey.key = wgetch(body);
417 if (thiskey.key == ERR || thiskey.key == 27) {
418 thiskey.meta = 0;
419 thiskey.key = 27;
423 thiskey.cp = 0;
424 if ((unsigned int)thiskey.key < UINT8_MAX) {
425 while (1) {
426 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
427 break;
428 if ((thiskey.key = wgetch(body)) == ERR) {
429 message("Error decoding user input");
430 return 0;
435 return 1;
438 static void
439 dispatch_stdio(int fd, short ev, void *d)
441 struct keymap *k;
442 const char *keyname;
443 char tmp[5] = {0};
445 if (!readkey())
446 return;
448 if (keybuf[0] != '\0')
449 strlcat(keybuf, " ", sizeof(keybuf));
450 if (thiskey.meta)
451 strlcat(keybuf, "M-", sizeof(keybuf));
452 if (thiskey.cp != 0) {
453 utf8_encode(thiskey.cp, tmp);
454 strlcat(keybuf, tmp, sizeof(keybuf));
455 } else {
456 if ((keyname = unkbd(thiskey.key)) != NULL)
457 strlcat(keybuf, keyname, sizeof(keybuf));
458 else {
459 tmp[0] = thiskey.key;
460 strlcat(keybuf, tmp, sizeof(keybuf));
464 TAILQ_FOREACH(k, &current_map->m, keymaps) {
465 if (k->meta == thiskey.meta &&
466 k->key == thiskey.key) {
467 if (k->fn == NULL)
468 current_map = &k->map;
469 else {
470 current_map = base_map;
471 strlcpy(keybuf, "", sizeof(keybuf));
472 k->fn(current_buffer());
474 goto done;
478 if (current_map->unhandled_input != NULL)
479 current_map->unhandled_input();
480 else
481 global_key_unbound();
483 strlcpy(keybuf, "", sizeof(keybuf));
484 current_map = base_map;
486 done:
487 if (side_window)
488 recompute_help();
490 redraw_tab(current_tab());
493 static void
494 handle_clear_minibuf(int fd, short ev, void *d)
496 free(ministate.curmesg);
497 ministate.curmesg = NULL;
499 redraw_minibuffer();
500 if (in_minibuffer) {
501 wrefresh(body);
502 wrefresh(minibuf);
503 } else {
504 wrefresh(minibuf);
505 wrefresh(body);
509 static void
510 handle_resize(int sig, short ev, void *d)
512 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
513 event_del(&resizeev);
515 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
516 evtimer_add(&resizeev, &resize_timer);
519 static void
520 handle_resize_nodelay(int s, short ev, void *d)
522 struct tab *tab;
524 endwin();
525 refresh();
526 clear();
528 /* move and resize the windows, in reverse order! */
530 mvwin(minibuf, LINES-1, 0);
531 wresize(minibuf, 1, COLS);
533 mvwin(modeline, LINES-2, 0);
534 wresize(modeline, 1, COLS);
536 body_lines = LINES-3;
537 body_cols = COLS;
539 if (side_window) {
540 help_cols = 0.3 * COLS;
541 help_lines = LINES-3;
542 mvwin(help, 1, 0);
543 wresize(help, help_lines, help_cols);
545 wrap_page(&helpwin, help_cols);
547 body_cols = COLS - help_cols - 1;
548 mvwin(body, 1, help_cols);
549 } else
550 mvwin(body, 1, 0);
552 update_x_offset();
553 wresize(body, body_lines, body_cols);
555 wresize(tabline, 1, COLS);
557 tab = current_tab();
559 wrap_page(&tab->buffer, body_cols);
560 redraw_tab(tab);
563 static int
564 wrap_page(struct buffer *buffer, int width)
566 struct line *l;
567 const struct line *top_orig, *orig;
568 struct vline *vl;
569 int pre_width;
570 const char *prfx;
572 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
573 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
575 buffer->top_line = NULL;
576 buffer->current_line = NULL;
578 buffer->force_redraw = 1;
579 buffer->curs_y = 0;
580 buffer->line_off = 0;
582 empty_vlist(buffer);
584 TAILQ_FOREACH(l, &buffer->page.head, lines) {
585 prfx = line_prefixes[l->type].prfx1;
586 switch (l->type) {
587 case LINE_TEXT:
588 case LINE_LINK:
589 case LINE_TITLE_1:
590 case LINE_TITLE_2:
591 case LINE_TITLE_3:
592 case LINE_ITEM:
593 case LINE_QUOTE:
594 case LINE_PRE_START:
595 case LINE_PRE_END:
596 wrap_text(buffer, prfx, l, MIN(fill_column, width));
597 break;
598 case LINE_PRE_CONTENT:
599 if (olivetti_mode)
600 pre_width = MIN(fill_column, width);
601 else
602 pre_width = width;
603 hardwrap_text(buffer, l, pre_width);
604 break;
607 if (top_orig == l && buffer->top_line == NULL) {
608 buffer->line_off = buffer->line_max-1;
609 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
611 while (1) {
612 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
613 if (vl == NULL || vl->parent != orig)
614 break;
615 buffer->top_line = vl;
616 buffer->line_off--;
620 if (orig == l && buffer->current_line == NULL) {
621 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
623 while (1) {
624 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
625 if (vl == NULL || vl->parent != orig)
626 break;
627 buffer->current_line = vl;
632 if (buffer->current_line == NULL)
633 buffer->current_line = TAILQ_FIRST(&buffer->head);
635 if (buffer->top_line == NULL)
636 buffer->top_line = buffer->current_line;
638 return 1;
641 static void
642 print_vline(int off, int width, WINDOW *window, struct vline *vl)
644 const char *text;
645 const char *prfx;
646 struct line_face *f;
647 int i, left, x, y;
649 f = &line_faces[vl->parent->type];
651 /* unused, set by getyx */
652 (void)y;
654 if (!vl->flags)
655 prfx = line_prefixes[vl->parent->type].prfx1;
656 else
657 prfx = line_prefixes[vl->parent->type].prfx2;
659 text = vl->line;
660 if (text == NULL)
661 text = "";
663 wattr_on(window, body_face.left, NULL);
664 for (i = 0; i < off; i++)
665 waddch(window, ' ');
666 wattr_off(window, body_face.left, NULL);
668 wattr_on(window, f->prefix, NULL);
669 wprintw(window, "%s", prfx);
670 wattr_off(window, f->prefix, NULL);
672 wattr_on(window, f->text, NULL);
673 wprintw(window, "%s", text);
674 wattr_off(window, f->text, NULL);
676 getyx(window, y, x);
678 left = width - x;
680 wattr_on(window, f->trail, NULL);
681 for (i = 0; i < left - off - 1; ++i)
682 waddch(window, ' ');
683 wattr_off(window, f->trail, NULL);
685 wattr_on(window, body_face.right, NULL);
686 for (i = 0; i < off; i++)
687 waddch(window, ' ');
688 wattr_off(window, body_face.right, NULL);
692 static void
693 redraw_tabline(void)
695 struct tab *tab;
696 size_t toskip, ots, tabwidth, space, x;
697 int current, y, truncated;
698 const char *title;
699 char buf[25];
701 x = 0;
703 /* unused, but setted by a getyx */
704 (void)y;
706 tabwidth = sizeof(buf)+1;
707 space = COLS-2;
709 toskip = 0;
710 TAILQ_FOREACH(tab, &tabshead, tabs) {
711 toskip++;
712 if (tab->flags & TAB_CURRENT)
713 break;
716 if (toskip * tabwidth < space)
717 toskip = 0;
718 else {
719 ots = toskip;
720 toskip--;
721 while (toskip != 0 &&
722 (ots - toskip+1) * tabwidth < space)
723 toskip--;
726 werase(tabline);
727 wattr_on(tabline, tab_face.background, NULL);
728 wprintw(tabline, toskip == 0 ? " " : "<");
729 wattr_off(tabline, tab_face.background, NULL);
731 truncated = 0;
732 TAILQ_FOREACH(tab, &tabshead, tabs) {
733 if (truncated)
734 break;
735 if (toskip != 0) {
736 toskip--;
737 continue;
740 getyx(tabline, y, x);
741 if (x + sizeof(buf)+2 >= (size_t)COLS)
742 truncated = 1;
744 current = tab->flags & TAB_CURRENT;
746 if (*(title = tab->buffer.page.title) == '\0')
747 title = tab->hist_cur->h;
749 if (tab->flags & TAB_URGENT)
750 strlcpy(buf, "!", sizeof(buf));
751 else
752 strlcpy(buf, " ", sizeof(buf));
754 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
755 /* truncation happens */
756 strlcpy(&buf[sizeof(buf)-4], "...", 4);
757 } else {
758 /* pad with spaces */
759 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
760 /* nop */ ;
763 if (current)
764 wattr_on(tabline, tab_face.current, NULL);
765 else
766 wattr_on(tabline, tab_face.tab, NULL);
768 wprintw(tabline, "%s", buf);
769 if (TAILQ_NEXT(tab, tabs) != NULL)
770 wprintw(tabline, " ");
772 if (current)
773 wattr_off(tabline, tab_face.current, NULL);
774 else
775 wattr_off(tabline, tab_face.tab, NULL);
778 wattr_on(tabline, tab_face.background, NULL);
779 for (; x < (size_t)COLS; ++x)
780 waddch(tabline, ' ');
781 if (truncated)
782 mvwprintw(tabline, 0, COLS-1, ">");
783 wattr_off(tabline, tab_face.background, NULL);
786 /*
787 * Compute the first visible line around vl. Try to search forward
788 * until the end of the buffer; if a visible line is not found, search
789 * backward. Return NULL if no viable line was found.
790 */
791 static inline struct vline *
792 adjust_line(struct vline *vl, struct buffer *buffer)
794 struct vline *t;
796 if (!(vl->parent->flags & L_HIDDEN))
797 return vl;
799 /* search forward */
800 for (t = vl;
801 t != NULL && t->parent->flags & L_HIDDEN;
802 t = TAILQ_NEXT(t, vlines))
803 ; /* nop */
805 if (t != NULL)
806 return t;
808 /* search backward */
809 for (t = vl;
810 t != NULL && t->parent->flags & L_HIDDEN;
811 t = TAILQ_PREV(t, vhead, vlines))
812 ; /* nop */
814 return t;
817 static void
818 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
820 struct vline *vl;
821 int l, onscreen;
823 restore_curs_x(buffer);
825 /*
826 * TODO: ignoring buffer->force_update and always
827 * re-rendering. In theory we can recompute the y position
828 * without a re-render, and optimize here. It's not the only
829 * optimisation possible here, wscrl wolud also be an
830 * interesting one.
831 */
833 again:
834 werase(win);
835 buffer->curs_y = 0;
837 if (TAILQ_EMPTY(&buffer->head))
838 goto end;
840 buffer->top_line = adjust_line(buffer->top_line, buffer);
841 if (buffer->top_line == NULL)
842 goto end;
844 buffer->current_line = adjust_line(buffer->current_line, buffer);
846 l = 0;
847 onscreen = 0;
848 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
849 if (vl->parent->flags & L_HIDDEN)
850 continue;
852 wmove(win, l, 0);
853 print_vline(x_offset, width, win, vl);
855 if (vl == buffer->current_line)
856 onscreen = 1;
858 if (!onscreen)
859 buffer->curs_y++;
861 l++;
862 if (l == height)
863 break;
866 if (!onscreen) {
867 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
868 if (vl == buffer->current_line)
869 break;
870 if (vl->parent->flags & L_HIDDEN)
871 continue;
872 buffer->line_off++;
873 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
876 goto again;
879 buffer->last_line_off = buffer->line_off;
880 buffer->force_redraw = 0;
881 end:
882 wmove(win, buffer->curs_y, buffer->curs_x);
885 static void
886 redraw_help(void)
888 redraw_window(help, help_lines, help_cols, &helpwin);
891 static void
892 redraw_body(struct tab *tab)
894 static struct tab *last_tab;
896 if (last_tab != tab)
897 tab->buffer.force_redraw =1;
898 last_tab = tab;
900 redraw_window(body, body_lines, body_cols, &tab->buffer);
903 static inline char
904 trust_status_char(enum trust_state ts)
906 switch (ts) {
907 case TS_UNKNOWN: return 'u';
908 case TS_UNTRUSTED: return '!';
909 case TS_TEMP_TRUSTED: return '!';
910 case TS_TRUSTED: return 'v';
911 case TS_VERIFIED: return 'V';
912 default: return 'X';
916 static void
917 redraw_modeline(struct tab *tab)
919 double pct;
920 int x, y, max_x, max_y;
921 const char *mode = tab->buffer.page.name;
922 const char *spin = "-\\|/";
924 werase(modeline);
925 wattr_on(modeline, modeline_face.background, NULL);
926 wmove(modeline, 0, 0);
928 wprintw(modeline, "-%c%c %s ",
929 spin[tab->loading_anim_step],
930 trust_status_char(tab->trust),
931 mode == NULL ? "(none)" : mode);
933 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
935 if (tab->buffer.line_max <= (size_t)body_lines)
936 wprintw(modeline, "All ");
937 else if (tab->buffer.line_off == 0)
938 wprintw(modeline, "Top ");
939 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
940 wprintw(modeline, "Bottom ");
941 else
942 wprintw(modeline, "%.0f%% ", pct);
944 wprintw(modeline, "%d/%d %s ",
945 tab->buffer.line_off + tab->buffer.curs_y,
946 tab->buffer.line_max,
947 tab->hist_cur->h);
949 getyx(modeline, y, x);
950 getmaxyx(modeline, max_y, max_x);
952 (void)y;
953 (void)max_y;
955 for (; x < max_x; ++x)
956 waddstr(modeline, "-");
958 wattr_off(modeline, modeline_face.background, NULL);
961 static void
962 redraw_minibuffer(void)
964 struct tab *tab;
965 size_t off_y, off_x = 0;
966 char *start = NULL, *c = NULL;
968 /* unused, but set by getyx */
969 (void)off_y;
971 wattr_on(minibuf, minibuffer_face.background, NULL);
972 werase(minibuf);
974 if (in_minibuffer) {
975 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
976 if (ministate.hist_cur != NULL)
977 wprintw(minibuf, "(%zu/%zu) ",
978 ministate.hist_off + 1,
979 ministate.history->len);
981 getyx(minibuf, off_y, off_x);
983 start = ministate.hist_cur != NULL
984 ? ministate.hist_cur->h
985 : ministate.buf;
986 c = utf8_nth(ministate.buffer.current_line->line,
987 ministate.buffer.cpoff);
988 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
989 start = utf8_next_cp(start);
992 waddstr(minibuf, start);
995 if (ministate.curmesg != NULL)
996 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
997 ministate.curmesg);
999 if (!in_minibuffer && ministate.curmesg == NULL)
1000 waddstr(minibuf, keybuf);
1002 /* If nothing else, show the URL at point */
1003 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1004 tab = current_tab();
1005 if (tab->buffer.current_line != NULL &&
1006 tab->buffer.current_line->parent->type == LINE_LINK)
1007 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1010 if (in_minibuffer)
1011 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1013 wattr_off(minibuf, minibuffer_face.background, NULL);
1016 static void
1017 redraw_tab(struct tab *tab)
1019 if (side_window) {
1020 redraw_help();
1021 wnoutrefresh(help);
1024 redraw_tabline();
1025 redraw_body(tab);
1026 redraw_modeline(tab);
1027 redraw_minibuffer();
1029 wnoutrefresh(tabline);
1030 wnoutrefresh(modeline);
1032 if (in_minibuffer) {
1033 wnoutrefresh(body);
1034 wnoutrefresh(minibuf);
1035 } else {
1036 wnoutrefresh(minibuf);
1037 wnoutrefresh(body);
1040 doupdate();
1043 static void
1044 emit_help_item(char *prfx, void *fn)
1046 struct line *l;
1047 struct cmd *cmd;
1049 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1050 if (fn == cmd->fn)
1051 break;
1053 assert(cmd != NULL);
1055 if ((l = calloc(1, sizeof(*l))) == NULL)
1056 abort();
1058 l->type = LINE_TEXT;
1059 l->alt = NULL;
1061 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1063 if (TAILQ_EMPTY(&helpwin.page.head))
1064 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1065 else
1066 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1069 static void
1070 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1072 struct keymap *k;
1073 char p[32];
1074 const char *kn;
1076 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1077 strlcpy(p, prfx, sizeof(p));
1078 if (*p != '\0')
1079 strlcat(p, " ", sizeof(p));
1080 if (k->meta)
1081 strlcat(p, "M-", sizeof(p));
1082 if ((kn = unkbd(k->key)) != NULL)
1083 strlcat(p, kn, sizeof(p));
1084 else
1085 strlcat(p, keyname(k->key), sizeof(p));
1087 if (k->fn == NULL)
1088 rec_compute_help(&k->map, p, sizeof(p));
1089 else
1090 emit_help_item(p, k->fn);
1094 static void
1095 recompute_help(void)
1097 char p[32] = { 0 };
1099 empty_vlist(&helpwin);
1100 empty_linelist(&helpwin);
1101 rec_compute_help(current_map, p, sizeof(p));
1102 wrap_page(&helpwin, help_cols);
1105 void
1106 vmessage(const char *fmt, va_list ap)
1108 if (evtimer_pending(&clminibufev, NULL))
1109 evtimer_del(&clminibufev);
1111 free(ministate.curmesg);
1112 ministate.curmesg = NULL;
1114 if (fmt != NULL) {
1115 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1116 evtimer_add(&clminibufev, &clminibufev_timer);
1118 /* TODO: what to do if the allocation fails here? */
1119 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1120 ministate.curmesg = NULL;
1123 redraw_minibuffer();
1124 if (in_minibuffer) {
1125 wrefresh(body);
1126 wrefresh(minibuf);
1127 } else {
1128 wrefresh(minibuf);
1129 wrefresh(body);
1133 void
1134 message(const char *fmt, ...)
1136 va_list ap;
1138 va_start(ap, fmt);
1139 vmessage(fmt, ap);
1140 va_end(ap);
1143 void
1144 start_loading_anim(struct tab *tab)
1146 if (tab->loading_anim)
1147 return;
1148 tab->loading_anim = 1;
1149 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1150 evtimer_add(&tab->loadingev, &loadingev_timer);
1153 static void
1154 update_loading_anim(int fd, short ev, void *d)
1156 struct tab *tab = d;
1158 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1160 if (tab->flags & TAB_CURRENT) {
1161 redraw_modeline(tab);
1162 wrefresh(modeline);
1163 wrefresh(body);
1164 if (in_minibuffer)
1165 wrefresh(minibuf);
1168 evtimer_add(&tab->loadingev, &loadingev_timer);
1171 static void
1172 stop_loading_anim(struct tab *tab)
1174 if (!tab->loading_anim)
1175 return;
1176 evtimer_del(&tab->loadingev);
1177 tab->loading_anim = 0;
1178 tab->loading_anim_step = 0;
1180 if (!(tab->flags & TAB_CURRENT))
1181 return;
1183 redraw_modeline(tab);
1185 wrefresh(modeline);
1186 wrefresh(body);
1187 if (in_minibuffer)
1188 wrefresh(minibuf);
1191 void
1192 load_url_in_tab(struct tab *tab, const char *url)
1194 message("Loading %s...", url);
1195 start_loading_anim(tab);
1196 load_url(tab, url);
1198 tab->buffer.curs_x = 0;
1199 tab->buffer.curs_y = 0;
1200 redraw_tab(tab);
1203 void
1204 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1205 void (*abortfn)(void), struct histhead *hist)
1207 in_minibuffer = 1;
1208 base_map = &minibuffer_map;
1209 current_map = &minibuffer_map;
1211 base_map->unhandled_input = self_insert_fn;
1213 ministate.donefn = donefn;
1214 ministate.abortfn = abortfn;
1215 memset(ministate.buf, 0, sizeof(ministate.buf));
1216 ministate.buffer.current_line = &ministate.vline;
1217 ministate.buffer.current_line->line = ministate.buf;
1218 ministate.buffer.cpoff = 0;
1219 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1221 ministate.history = hist;
1222 ministate.hist_cur = NULL;
1223 ministate.hist_off = 0;
1226 void
1227 exit_minibuffer(void)
1229 werase(minibuf);
1231 in_minibuffer = 0;
1232 base_map = &global_map;
1233 current_map = &global_map;
1236 void
1237 switch_to_tab(struct tab *tab)
1239 struct tab *t;
1241 TAILQ_FOREACH(t, &tabshead, tabs) {
1242 t->flags &= ~TAB_CURRENT;
1245 tab->flags |= TAB_CURRENT;
1246 tab->flags &= ~TAB_URGENT;
1249 unsigned int
1250 tab_new_id(void)
1252 return tab_counter++;
1255 struct tab *
1256 new_tab(const char *url)
1258 struct tab *tab;
1260 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1261 event_loopbreak();
1262 return NULL;
1264 tab->fd = -1;
1266 TAILQ_INIT(&tab->hist.head);
1268 TAILQ_INIT(&tab->buffer.head);
1270 tab->id = tab_new_id();
1271 switch_to_tab(tab);
1273 if (TAILQ_EMPTY(&tabshead))
1274 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1275 else
1276 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1278 load_url_in_tab(tab, url);
1279 return tab;
1282 static void
1283 session_new_tab_cb(const char *url)
1285 new_tab(url);
1288 static void
1289 usage(void)
1291 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1292 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1295 int
1296 ui_init(int argc, char * const *argv)
1298 char path[PATH_MAX];
1299 const char *url = NEW_TAB_URL;
1300 int ch, configtest = 0, fonf = 0;
1302 if (getenv("NO_COLOR") != NULL)
1303 enable_colors = 0;
1305 strlcpy(path, getenv("HOME"), sizeof(path));
1306 strlcat(path, "/.telescope/config", sizeof(path));
1308 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1309 switch (ch) {
1310 case 'c':
1311 fonf = 1;
1312 strlcpy(path, optarg, sizeof(path));
1313 break;
1314 case 'n':
1315 configtest = 1;
1316 break;
1317 case 'h':
1318 usage();
1319 return 0;
1320 default:
1321 usage();
1322 return 1;
1325 argc -= optind;
1326 argv += optind;
1328 /* setup keys before reading the config */
1329 TAILQ_INIT(&global_map.m);
1330 global_map.unhandled_input = global_key_unbound;
1332 TAILQ_INIT(&minibuffer_map.m);
1334 config_init();
1335 parseconfig(path, fonf);
1336 if (configtest){
1337 puts("config OK");
1338 exit(0);
1341 if (argc != 0)
1342 url = argv[0];
1344 setlocale(LC_ALL, "");
1346 TAILQ_INIT(&eecmd_history.head);
1347 TAILQ_INIT(&ir_history.head);
1348 TAILQ_INIT(&lu_history.head);
1350 ministate.line.type = LINE_TEXT;
1351 ministate.vline.parent = &ministate.line;
1352 ministate.buffer.current_line = &ministate.vline;
1354 /* initialize help window */
1355 TAILQ_INIT(&helpwin.head);
1357 base_map = &global_map;
1358 current_map = &global_map;
1360 initscr();
1362 if (enable_colors) {
1363 if (has_colors()) {
1364 start_color();
1365 use_default_colors();
1366 } else
1367 enable_colors = 0;
1370 config_apply_style();
1372 raw();
1373 noecho();
1374 nonl();
1375 intrflush(stdscr, FALSE);
1377 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1378 return 0;
1379 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1380 return 0;
1381 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1382 return 0;
1383 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1384 return 0;
1385 if ((help = newwin(1, 1, 1, 0)) == NULL)
1386 return 0;
1388 body_lines = LINES-3;
1389 body_cols = COLS;
1391 wbkgd(body, body_face.body);
1392 wbkgd(minibuf, minibuffer_face.background);
1394 update_x_offset();
1396 keypad(body, TRUE);
1397 scrollok(body, FALSE);
1399 /* non-blocking input */
1400 wtimeout(body, 0);
1402 mvwprintw(body, 0, 0, "");
1404 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1405 event_add(&stdioev, NULL);
1407 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1408 signal_add(&winchev, NULL);
1410 load_last_session(session_new_tab_cb);
1411 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1412 new_tab(url);
1414 return 1;
1417 void
1418 ui_on_tab_loaded(struct tab *tab)
1420 stop_loading_anim(tab);
1421 message("Loaded %s", tab->hist_cur->h);
1423 redraw_tabline();
1424 wrefresh(tabline);
1425 if (in_minibuffer)
1426 wrefresh(minibuf);
1427 else
1428 wrefresh(body);
1431 void
1432 ui_on_tab_refresh(struct tab *tab)
1434 wrap_page(&tab->buffer, body_cols);
1435 if (tab->flags & TAB_CURRENT)
1436 redraw_tab(tab);
1437 else
1438 tab->flags |= TAB_URGENT;
1441 const char *
1442 ui_keyname(int k)
1444 return keyname(k);
1447 void
1448 ui_toggle_side_window(void)
1450 side_window = !side_window;
1451 if (side_window)
1452 recompute_help();
1455 * ugly hack, but otherwise the window doesn't get updated
1456 * until I call handle_resize a second time (i.e. C-l). I
1457 * will be happy to know why something like this is needed.
1459 handle_resize_nodelay(0, 0, NULL);
1460 handle_resize_nodelay(0, 0, NULL);
1463 void
1464 ui_schedule_redraw(void)
1466 handle_resize_nodelay(0, 0, NULL);
1469 void
1470 ui_require_input(struct tab *tab, int hide)
1472 /* TODO: hard-switching to another tab is ugly */
1473 switch_to_tab(tab);
1475 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1476 &ir_history);
1477 strlcpy(ministate.prompt, "Input required: ",
1478 sizeof(ministate.prompt));
1479 redraw_tab(tab);
1482 void
1483 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1484 struct tab *data)
1486 size_t len;
1488 if (in_minibuffer) {
1489 fn(0, data);
1490 return;
1493 yornp_cb = fn;
1494 yornp_data = data;
1495 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1496 yornp_abort, NULL);
1498 len = sizeof(ministate.prompt);
1499 strlcpy(ministate.prompt, prompt, len);
1500 strlcat(ministate.prompt, " (y or n) ", len);
1501 redraw_tab(current_tab());
1504 void
1505 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1506 unsigned int data)
1508 size_t len;
1510 if (in_minibuffer)
1511 return;
1513 read_cb = fn;
1514 read_data = data;
1515 enter_minibuffer(read_self_insert, read_select, read_abort,
1516 &read_history);
1518 len = sizeof(ministate.prompt);
1519 strlcpy(ministate.prompt, prompt, len);
1520 strlcat(ministate.prompt, ": ", len);
1521 redraw_tab(current_tab());
1524 void
1525 ui_end(void)
1527 endwin();