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 global_key_unbound(void);
49 static void minibuffer_hist_save_entry(void);
50 static void minibuffer_self_insert(void);
51 static void yornp_self_insert(void);
52 static void yornp_abort(void);
53 static void read_self_insert(void);
54 static void read_abort(void);
55 static void read_select(void);
57 static struct vline *nth_line(struct buffer*, size_t);
58 static struct buffer *current_buffer(void);
59 static int readkey(void);
60 static void dispatch_stdio(int, short, void*);
61 static void handle_clear_minibuf(int, short, void*);
62 static void handle_resize(int, short, void*);
63 static void handle_resize_nodelay(int, short, void*);
64 static int wrap_page(struct buffer*, int);
65 static void print_vline(int, int, WINDOW*, struct vline*);
66 static void redraw_tabline(void);
67 static void redraw_window(WINDOW*, int, int, struct buffer*);
68 static void redraw_help(void);
69 static void redraw_body(struct tab*);
70 static void redraw_modeline(struct tab*);
71 static void redraw_minibuffer(void);
72 static void redraw_tab(struct tab*);
73 static void emit_help_item(char*, void*);
74 static void rec_compute_help(struct kmap*, char*, size_t);
75 static void recompute_help(void);
76 static void update_loading_anim(int, short, void*);
77 static void stop_loading_anim(struct tab*);
78 static void session_new_tab_cb(const char*);
79 static void usage(void);
81 static int x_offset;
83 struct thiskey thiskey;
85 static struct event resizeev;
86 static struct timeval resize_timer = { 0, 250000 };
88 static WINDOW *tabline, *body, *modeline, *minibuf;
90 int body_lines, body_cols;
92 static WINDOW *help;
93 static struct buffer helpwin;
94 static int help_lines, help_cols;
96 static int side_window;
98 static struct event clminibufev;
99 static struct timeval clminibufev_timer = { 5, 0 };
100 static struct timeval loadingev_timer = { 0, 250000 };
102 static uint32_t tab_counter;
104 static char keybuf[64];
106 static void (*yornp_cb)(int, unsigned int);
107 static unsigned int yornp_data;
109 static void (*read_cb)(const char*, unsigned int);
110 static unsigned int read_data;
112 struct kmap global_map,
113 minibuffer_map,
114 *current_map,
115 *base_map;
117 struct histhead eecmd_history,
118 ir_history,
119 lu_history,
120 read_history;
122 int in_minibuffer;
124 struct ministate ministate;
126 static inline void
127 update_x_offset(void)
129 if (olivetti_mode && fill_column < body_cols)
130 x_offset = (body_cols - fill_column)/2;
131 else
132 x_offset = 0;
135 void
136 save_excursion(struct excursion *place, struct buffer *buffer)
138 place->curs_x = buffer->curs_x;
139 place->curs_y = buffer->curs_y;
140 place->line_off = buffer->line_off;
141 place->current_line = buffer->current_line;
142 place->cpoff = buffer->cpoff;
145 void
146 restore_excursion(struct excursion *place, struct buffer *buffer)
148 buffer->curs_x = place->curs_x;
149 buffer->curs_y = place->curs_y;
150 buffer->line_off = place->line_off;
151 buffer->current_line = place->current_line;
152 buffer->cpoff = place->cpoff;
155 void
156 restore_cursor(struct buffer *buffer)
158 struct vline *vl;
159 const char *prfx;
161 vl = buffer->current_line;
162 if (vl == NULL || vl->line == NULL)
163 buffer->curs_x = buffer->cpoff = 0;
164 else
165 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
167 buffer->curs_x += x_offset;
169 if (vl != NULL) {
170 prfx = line_prefixes[vl->parent->type].prfx1;
171 buffer->curs_x += utf8_swidth(prfx);
175 static void
176 global_key_unbound(void)
178 message("%s is undefined", keybuf);
181 static void
182 minibuffer_hist_save_entry(void)
184 struct hist *hist;
186 if (ministate.history == NULL)
187 return;
189 if ((hist = calloc(1, sizeof(*hist))) == NULL)
190 abort();
192 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
194 if (TAILQ_EMPTY(&ministate.history->head))
195 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
196 else
197 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
198 ministate.history->len++;
201 /*
202 * taint the minibuffer cache: if we're currently showing a history
203 * element, copy that to the current buf and reset the "history
204 * navigation" thing.
205 */
206 void
207 minibuffer_taint_hist(void)
209 if (ministate.hist_cur == NULL)
210 return;
212 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
213 ministate.hist_cur = NULL;
216 static void
217 minibuffer_self_insert(void)
219 char *c, tmp[5] = {0};
220 size_t len;
222 minibuffer_taint_hist();
224 if (thiskey.cp == 0)
225 return;
227 len = utf8_encode(thiskey.cp, tmp);
228 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
229 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
230 return;
232 memmove(c + len, c, strlen(c)+1);
233 memcpy(c, tmp, len);
234 ministate.buffer.cpoff++;
237 void
238 eecmd_self_insert(void)
240 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
241 !unicode_isgraph(thiskey.cp)) {
242 global_key_unbound();
243 return;
246 minibuffer_self_insert();
249 void
250 eecmd_select(void)
252 struct cmd *cmd;
254 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
255 if (!strcmp(cmd->cmd, ministate.buf)) {
256 exit_minibuffer();
257 minibuffer_hist_save_entry();
258 cmd->fn(current_buffer());
259 return;
263 message("No match");
266 void
267 ir_self_insert(void)
269 minibuffer_self_insert();
272 void
273 ir_select(void)
275 char buf[1025] = {0};
276 struct phos_uri uri;
277 struct tab *tab;
279 tab = current_tab();
281 exit_minibuffer();
282 minibuffer_hist_save_entry();
284 /* a bit ugly but... */
285 memcpy(&uri, &tab->uri, sizeof(tab->uri));
286 phos_uri_set_query(&uri, ministate.buf);
287 phos_serialize_uri(&uri, buf, sizeof(buf));
288 load_url_in_tab(tab, buf);
291 void
292 lu_self_insert(void)
294 if (thiskey.meta || unicode_isspace(thiskey.key) ||
295 !unicode_isgraph(thiskey.key)) {
296 global_key_unbound();
297 return;
300 minibuffer_self_insert();
303 void
304 lu_select(void)
306 exit_minibuffer();
307 minibuffer_hist_save_entry();
308 load_url_in_tab(current_tab(), ministate.buf);
311 void
312 bp_select(void)
314 exit_minibuffer();
315 if (*ministate.buf != '\0')
316 add_to_bookmarks(ministate.buf);
317 else
318 message("Abort.");
321 static void
322 yornp_self_insert(void)
324 if (thiskey.key != 'y' && thiskey.key != 'n') {
325 message("Please answer y or n");
326 return;
329 exit_minibuffer();
330 yornp_cb(thiskey.key == 'y', yornp_data);
333 static void
334 yornp_abort(void)
336 exit_minibuffer();
337 yornp_cb(0, yornp_data);
340 static void
341 read_self_insert(void)
343 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
344 global_key_unbound();
345 return;
348 minibuffer_self_insert();
351 static void
352 read_abort(void)
354 exit_minibuffer();
355 read_cb(NULL, read_data);
358 static void
359 read_select(void)
361 exit_minibuffer();
362 minibuffer_hist_save_entry();
363 read_cb(ministate.buf, read_data);
366 static struct vline *
367 nth_line(struct buffer *buffer, size_t n)
369 struct vline *vl;
370 size_t i;
372 i = 0;
373 TAILQ_FOREACH(vl, &buffer->head, vlines) {
374 if (i == n)
375 return vl;
376 i++;
379 /* unreachable */
380 abort();
383 struct tab *
384 current_tab(void)
386 struct tab *t;
388 TAILQ_FOREACH(t, &tabshead, tabs) {
389 if (t->flags & TAB_CURRENT)
390 return t;
393 /* unreachable */
394 abort();
397 struct buffer *
398 current_buffer(void)
400 if (in_minibuffer)
401 return &ministate.buffer;
402 return &current_tab()->buffer;
405 static int
406 readkey(void)
408 uint32_t state = 0;
410 if ((thiskey.key = wgetch(body)) == ERR)
411 return 0;
413 thiskey.meta = thiskey.key == 27;
414 if (thiskey.meta) {
415 thiskey.key = wgetch(body);
416 if (thiskey.key == ERR || thiskey.key == 27) {
417 thiskey.meta = 0;
418 thiskey.key = 27;
422 thiskey.cp = 0;
423 if ((unsigned int)thiskey.key < UINT8_MAX) {
424 while (1) {
425 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
426 break;
427 if ((thiskey.key = wgetch(body)) == ERR) {
428 message("Error decoding user input");
429 return 0;
434 return 1;
437 static void
438 dispatch_stdio(int fd, short ev, void *d)
440 struct keymap *k;
441 const char *keyname;
442 char tmp[5] = {0};
444 if (!readkey())
445 return;
447 if (keybuf[0] != '\0')
448 strlcat(keybuf, " ", sizeof(keybuf));
449 if (thiskey.meta)
450 strlcat(keybuf, "M-", sizeof(keybuf));
451 if (thiskey.cp != 0) {
452 utf8_encode(thiskey.cp, tmp);
453 strlcat(keybuf, tmp, sizeof(keybuf));
454 } else {
455 if ((keyname = unkbd(thiskey.key)) != NULL)
456 strlcat(keybuf, keyname, sizeof(keybuf));
457 else {
458 tmp[0] = thiskey.key;
459 strlcat(keybuf, tmp, sizeof(keybuf));
463 TAILQ_FOREACH(k, &current_map->m, keymaps) {
464 if (k->meta == thiskey.meta &&
465 k->key == thiskey.key) {
466 if (k->fn == NULL)
467 current_map = &k->map;
468 else {
469 current_map = base_map;
470 strlcpy(keybuf, "", sizeof(keybuf));
471 k->fn(current_buffer());
473 goto done;
477 if (current_map->unhandled_input != NULL)
478 current_map->unhandled_input();
479 else
480 global_key_unbound();
482 strlcpy(keybuf, "", sizeof(keybuf));
483 current_map = base_map;
485 done:
486 if (side_window)
487 recompute_help();
489 redraw_tab(current_tab());
492 static void
493 handle_clear_minibuf(int fd, short ev, void *d)
495 free(ministate.curmesg);
496 ministate.curmesg = NULL;
498 redraw_minibuffer();
499 if (in_minibuffer) {
500 wrefresh(body);
501 wrefresh(minibuf);
502 } else {
503 wrefresh(minibuf);
504 wrefresh(body);
508 static void
509 handle_resize(int sig, short ev, void *d)
511 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
512 event_del(&resizeev);
514 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
515 evtimer_add(&resizeev, &resize_timer);
518 static void
519 handle_resize_nodelay(int s, short ev, void *d)
521 struct tab *tab;
523 endwin();
524 refresh();
525 clear();
527 /* move and resize the windows, in reverse order! */
529 mvwin(minibuf, LINES-1, 0);
530 wresize(minibuf, 1, COLS);
532 mvwin(modeline, LINES-2, 0);
533 wresize(modeline, 1, COLS);
535 body_lines = LINES-3;
536 body_cols = COLS;
538 if (side_window) {
539 help_cols = 0.3 * COLS;
540 help_lines = LINES-3;
541 mvwin(help, 1, 0);
542 wresize(help, help_lines, help_cols);
544 wrap_page(&helpwin, help_cols);
546 body_cols = COLS - help_cols - 1;
547 mvwin(body, 1, help_cols);
548 } else
549 mvwin(body, 1, 0);
551 update_x_offset();
552 wresize(body, body_lines, body_cols);
554 wresize(tabline, 1, COLS);
556 tab = current_tab();
558 wrap_page(&tab->buffer, body_cols);
559 redraw_tab(tab);
562 static int
563 wrap_page(struct buffer *buffer, int width)
565 struct line *l;
566 const struct line *top_orig, *orig;
567 struct vline *vl;
568 int pre_width;
569 const char *prfx;
571 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
572 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
574 buffer->top_line = NULL;
575 buffer->current_line = NULL;
577 buffer->force_redraw = 1;
578 buffer->curs_y = 0;
579 buffer->line_off = 0;
581 empty_vlist(buffer);
583 TAILQ_FOREACH(l, &buffer->page.head, lines) {
584 prfx = line_prefixes[l->type].prfx1;
585 switch (l->type) {
586 case LINE_TEXT:
587 case LINE_LINK:
588 case LINE_TITLE_1:
589 case LINE_TITLE_2:
590 case LINE_TITLE_3:
591 case LINE_ITEM:
592 case LINE_QUOTE:
593 case LINE_PRE_START:
594 case LINE_PRE_END:
595 wrap_text(buffer, prfx, l, MIN(fill_column, width));
596 break;
597 case LINE_PRE_CONTENT:
598 if (olivetti_mode)
599 pre_width = MIN(fill_column, width);
600 else
601 pre_width = width;
602 hardwrap_text(buffer, l, pre_width);
603 break;
606 if (top_orig == l && buffer->top_line == NULL) {
607 buffer->line_off = buffer->line_max-1;
608 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
610 while (1) {
611 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
612 if (vl == NULL || vl->parent != orig)
613 break;
614 buffer->top_line = vl;
615 buffer->line_off--;
619 if (orig == l && buffer->current_line == NULL) {
620 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
622 while (1) {
623 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
624 if (vl == NULL || vl->parent != orig)
625 break;
626 buffer->current_line = vl;
631 if (buffer->current_line == NULL)
632 buffer->current_line = TAILQ_FIRST(&buffer->head);
634 if (buffer->top_line == NULL)
635 buffer->top_line = buffer->current_line;
637 return 1;
640 static void
641 print_vline(int off, int width, WINDOW *window, struct vline *vl)
643 const char *text;
644 const char *prfx;
645 struct line_face *f;
646 int i, left, x, y;
648 f = &line_faces[vl->parent->type];
650 /* unused, set by getyx */
651 (void)y;
653 if (!vl->flags)
654 prfx = line_prefixes[vl->parent->type].prfx1;
655 else
656 prfx = line_prefixes[vl->parent->type].prfx2;
658 text = vl->line;
659 if (text == NULL)
660 text = "";
662 wattr_on(window, body_face.left, NULL);
663 for (i = 0; i < off; i++)
664 waddch(window, ' ');
665 wattr_off(window, body_face.left, NULL);
667 wattr_on(window, f->prefix, NULL);
668 wprintw(window, "%s", prfx);
669 wattr_off(window, f->prefix, NULL);
671 wattr_on(window, f->text, NULL);
672 wprintw(window, "%s", text);
673 wattr_off(window, f->text, NULL);
675 getyx(window, y, x);
677 left = width - x;
679 wattr_on(window, f->trail, NULL);
680 for (i = 0; i < left - off - 1; ++i)
681 waddch(window, ' ');
682 wattr_off(window, f->trail, NULL);
684 wattr_on(window, body_face.right, NULL);
685 for (i = 0; i < off; i++)
686 waddch(window, ' ');
687 wattr_off(window, body_face.right, NULL);
691 static void
692 redraw_tabline(void)
694 struct tab *tab;
695 size_t toskip, ots, tabwidth, space, x;
696 int current, y, truncated;
697 const char *title;
698 char buf[25];
700 x = 0;
702 /* unused, but setted by a getyx */
703 (void)y;
705 tabwidth = sizeof(buf)+1;
706 space = COLS-2;
708 toskip = 0;
709 TAILQ_FOREACH(tab, &tabshead, tabs) {
710 toskip++;
711 if (tab->flags & TAB_CURRENT)
712 break;
715 if (toskip * tabwidth < space)
716 toskip = 0;
717 else {
718 ots = toskip;
719 toskip--;
720 while (toskip != 0 &&
721 (ots - toskip+1) * tabwidth < space)
722 toskip--;
725 werase(tabline);
726 wattr_on(tabline, tab_face.background, NULL);
727 wprintw(tabline, toskip == 0 ? " " : "<");
728 wattr_off(tabline, tab_face.background, NULL);
730 truncated = 0;
731 TAILQ_FOREACH(tab, &tabshead, tabs) {
732 if (truncated)
733 break;
734 if (toskip != 0) {
735 toskip--;
736 continue;
739 getyx(tabline, y, x);
740 if (x + sizeof(buf)+2 >= (size_t)COLS)
741 truncated = 1;
743 current = tab->flags & TAB_CURRENT;
745 if (*(title = tab->buffer.page.title) == '\0')
746 title = tab->hist_cur->h;
748 if (tab->flags & TAB_URGENT)
749 strlcpy(buf, "!", sizeof(buf));
750 else
751 strlcpy(buf, " ", sizeof(buf));
753 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
754 /* truncation happens */
755 strlcpy(&buf[sizeof(buf)-4], "...", 4);
756 } else {
757 /* pad with spaces */
758 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
759 /* nop */ ;
762 if (current)
763 wattr_on(tabline, tab_face.current, NULL);
764 else
765 wattr_on(tabline, tab_face.tab, NULL);
767 wprintw(tabline, "%s", buf);
768 if (TAILQ_NEXT(tab, tabs) != NULL)
769 wprintw(tabline, " ");
771 if (current)
772 wattr_off(tabline, tab_face.current, NULL);
773 else
774 wattr_off(tabline, tab_face.tab, NULL);
777 wattr_on(tabline, tab_face.background, NULL);
778 for (; x < (size_t)COLS; ++x)
779 waddch(tabline, ' ');
780 if (truncated)
781 mvwprintw(tabline, 0, COLS-1, ">");
782 wattr_off(tabline, tab_face.background, NULL);
785 static void
786 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
788 struct vline *vl;
789 int l, onscreen;
791 /*
792 * Don't bother redraw the body if nothing changed. Cursor
793 * movements count as "nothing changed" if it hasn't produced
794 * a scroll. Ensure that wmove is called though!
795 */
796 if (!buffer->force_redraw &&
797 buffer->last_line_off == buffer->line_off)
798 goto end;
800 again:
801 werase(win);
802 buffer->curs_y = 0;
804 if (TAILQ_EMPTY(&buffer->head))
805 goto end;
807 l = 0;
808 onscreen = 0;
809 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
810 wmove(win, l, 0);
811 print_vline(x_offset, width, win, vl);
813 if (vl == buffer->current_line)
814 onscreen = 1;
816 if (!onscreen)
817 buffer->curs_y++;
819 l++;
820 if (l == height)
821 break;
824 if (!onscreen) {
825 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
826 if (vl == buffer->current_line)
827 break;
828 buffer->line_off++;
829 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
832 goto again;
835 buffer->last_line_off = buffer->line_off;
836 restore_cursor(buffer);
837 buffer->force_redraw = 0;
838 end:
839 wmove(win, buffer->curs_y, buffer->curs_x);
842 static void
843 redraw_help(void)
845 redraw_window(help, help_lines, help_cols, &helpwin);
848 static void
849 redraw_body(struct tab *tab)
851 static struct tab *last_tab;
853 if (last_tab != tab)
854 tab->buffer.force_redraw =1;
855 last_tab = tab;
857 redraw_window(body, body_lines, body_cols, &tab->buffer);
860 static inline char
861 trust_status_char(enum trust_state ts)
863 switch (ts) {
864 case TS_UNKNOWN: return 'u';
865 case TS_UNTRUSTED: return '!';
866 case TS_TRUSTED: return 'v';
867 case TS_VERIFIED: return 'V';
868 default: return 'X';
872 static void
873 redraw_modeline(struct tab *tab)
875 double pct;
876 int x, y, max_x, max_y;
877 const char *mode = tab->buffer.page.name;
878 const char *spin = "-\\|/";
880 werase(modeline);
881 wattr_on(modeline, modeline_face.background, NULL);
882 wmove(modeline, 0, 0);
884 wprintw(modeline, "-%c%c %s ",
885 spin[tab->loading_anim_step],
886 trust_status_char(tab->trust),
887 mode == NULL ? "(none)" : mode);
889 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
891 if (tab->buffer.line_max <= (size_t)body_lines)
892 wprintw(modeline, "All ");
893 else if (tab->buffer.line_off == 0)
894 wprintw(modeline, "Top ");
895 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
896 wprintw(modeline, "Bottom ");
897 else
898 wprintw(modeline, "%.0f%% ", pct);
900 wprintw(modeline, "%d/%d %s ",
901 tab->buffer.line_off + tab->buffer.curs_y,
902 tab->buffer.line_max,
903 tab->hist_cur->h);
905 getyx(modeline, y, x);
906 getmaxyx(modeline, max_y, max_x);
908 (void)y;
909 (void)max_y;
911 for (; x < max_x; ++x)
912 waddstr(modeline, "-");
914 wattr_off(modeline, modeline_face.background, NULL);
917 static void
918 redraw_minibuffer(void)
920 struct tab *tab;
921 size_t off_y, off_x = 0;
922 char *start = NULL, *c = NULL;
924 /* unused, but set by getyx */
925 (void)off_y;
927 wattr_on(minibuf, minibuffer_face.background, NULL);
928 werase(minibuf);
930 if (in_minibuffer) {
931 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
932 if (ministate.hist_cur != NULL)
933 wprintw(minibuf, "(%zu/%zu) ",
934 ministate.hist_off + 1,
935 ministate.history->len);
937 getyx(minibuf, off_y, off_x);
939 start = ministate.hist_cur != NULL
940 ? ministate.hist_cur->h
941 : ministate.buf;
942 c = utf8_nth(ministate.buffer.current_line->line,
943 ministate.buffer.cpoff);
944 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
945 start = utf8_next_cp(start);
948 waddstr(minibuf, start);
951 if (ministate.curmesg != NULL)
952 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
953 ministate.curmesg);
955 if (!in_minibuffer && ministate.curmesg == NULL)
956 waddstr(minibuf, keybuf);
958 /* If nothing else, show the URL at point */
959 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
960 tab = current_tab();
961 if (tab->buffer.current_line != NULL &&
962 tab->buffer.current_line->parent->type == LINE_LINK)
963 waddstr(minibuf, tab->buffer.current_line->parent->alt);
966 if (in_minibuffer)
967 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
969 wattr_off(minibuf, minibuffer_face.background, NULL);
972 static void
973 redraw_tab(struct tab *tab)
975 if (side_window) {
976 redraw_help();
977 wnoutrefresh(help);
980 restore_cursor(&tab->buffer);
982 redraw_tabline();
983 redraw_body(tab);
984 redraw_modeline(tab);
985 redraw_minibuffer();
987 wnoutrefresh(tabline);
988 wnoutrefresh(modeline);
990 if (in_minibuffer) {
991 wnoutrefresh(body);
992 wnoutrefresh(minibuf);
993 } else {
994 wnoutrefresh(minibuf);
995 wnoutrefresh(body);
998 doupdate();
1001 static void
1002 emit_help_item(char *prfx, void *fn)
1004 struct line *l;
1005 struct cmd *cmd;
1007 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1008 if (fn == cmd->fn)
1009 break;
1011 assert(cmd != NULL);
1013 if ((l = calloc(1, sizeof(*l))) == NULL)
1014 abort();
1016 l->type = LINE_TEXT;
1017 l->alt = NULL;
1019 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1021 if (TAILQ_EMPTY(&helpwin.page.head))
1022 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1023 else
1024 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1027 static void
1028 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1030 struct keymap *k;
1031 char p[32];
1032 const char *kn;
1034 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1035 strlcpy(p, prfx, sizeof(p));
1036 if (*p != '\0')
1037 strlcat(p, " ", sizeof(p));
1038 if (k->meta)
1039 strlcat(p, "M-", sizeof(p));
1040 if ((kn = unkbd(k->key)) != NULL)
1041 strlcat(p, kn, sizeof(p));
1042 else
1043 strlcat(p, keyname(k->key), sizeof(p));
1045 if (k->fn == NULL)
1046 rec_compute_help(&k->map, p, sizeof(p));
1047 else
1048 emit_help_item(p, k->fn);
1052 static void
1053 recompute_help(void)
1055 char p[32] = { 0 };
1057 empty_vlist(&helpwin);
1058 empty_linelist(&helpwin);
1059 rec_compute_help(current_map, p, sizeof(p));
1060 wrap_page(&helpwin, help_cols);
1063 void
1064 vmessage(const char *fmt, va_list ap)
1066 if (evtimer_pending(&clminibufev, NULL))
1067 evtimer_del(&clminibufev);
1069 free(ministate.curmesg);
1070 ministate.curmesg = NULL;
1072 if (fmt != NULL) {
1073 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1074 evtimer_add(&clminibufev, &clminibufev_timer);
1076 /* TODO: what to do if the allocation fails here? */
1077 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1078 ministate.curmesg = NULL;
1081 redraw_minibuffer();
1082 if (in_minibuffer) {
1083 wrefresh(body);
1084 wrefresh(minibuf);
1085 } else {
1086 wrefresh(minibuf);
1087 wrefresh(body);
1091 void
1092 message(const char *fmt, ...)
1094 va_list ap;
1096 va_start(ap, fmt);
1097 vmessage(fmt, ap);
1098 va_end(ap);
1101 void
1102 start_loading_anim(struct tab *tab)
1104 if (tab->loading_anim)
1105 return;
1106 tab->loading_anim = 1;
1107 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1108 evtimer_add(&tab->loadingev, &loadingev_timer);
1111 static void
1112 update_loading_anim(int fd, short ev, void *d)
1114 struct tab *tab = d;
1116 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1118 if (tab->flags & TAB_CURRENT) {
1119 redraw_modeline(tab);
1120 wrefresh(modeline);
1121 wrefresh(body);
1122 if (in_minibuffer)
1123 wrefresh(minibuf);
1126 evtimer_add(&tab->loadingev, &loadingev_timer);
1129 static void
1130 stop_loading_anim(struct tab *tab)
1132 if (!tab->loading_anim)
1133 return;
1134 evtimer_del(&tab->loadingev);
1135 tab->loading_anim = 0;
1136 tab->loading_anim_step = 0;
1138 if (!(tab->flags & TAB_CURRENT))
1139 return;
1141 redraw_modeline(tab);
1143 wrefresh(modeline);
1144 wrefresh(body);
1145 if (in_minibuffer)
1146 wrefresh(minibuf);
1149 void
1150 load_url_in_tab(struct tab *tab, const char *url)
1152 message("Loading %s...", url);
1153 start_loading_anim(tab);
1154 load_url(tab, url);
1156 tab->buffer.curs_x = 0;
1157 tab->buffer.curs_y = 0;
1158 redraw_tab(tab);
1161 void
1162 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1163 void (*abortfn)(void), struct histhead *hist)
1165 in_minibuffer = 1;
1166 base_map = &minibuffer_map;
1167 current_map = &minibuffer_map;
1169 base_map->unhandled_input = self_insert_fn;
1171 ministate.donefn = donefn;
1172 ministate.abortfn = abortfn;
1173 memset(ministate.buf, 0, sizeof(ministate.buf));
1174 ministate.buffer.current_line = &ministate.vline;
1175 ministate.buffer.current_line->line = ministate.buf;
1176 ministate.buffer.cpoff = 0;
1177 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1179 ministate.history = hist;
1180 ministate.hist_cur = NULL;
1181 ministate.hist_off = 0;
1184 void
1185 exit_minibuffer(void)
1187 werase(minibuf);
1189 in_minibuffer = 0;
1190 base_map = &global_map;
1191 current_map = &global_map;
1194 void
1195 switch_to_tab(struct tab *tab)
1197 struct tab *t;
1199 TAILQ_FOREACH(t, &tabshead, tabs) {
1200 t->flags &= ~TAB_CURRENT;
1203 tab->flags |= TAB_CURRENT;
1204 tab->flags &= ~TAB_URGENT;
1207 unsigned int
1208 tab_new_id(void)
1210 return tab_counter++;
1213 struct tab *
1214 new_tab(const char *url)
1216 struct tab *tab;
1218 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1219 event_loopbreak();
1220 return NULL;
1222 tab->fd = -1;
1224 TAILQ_INIT(&tab->hist.head);
1226 TAILQ_INIT(&tab->buffer.head);
1228 tab->id = tab_new_id();
1229 switch_to_tab(tab);
1231 if (TAILQ_EMPTY(&tabshead))
1232 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1233 else
1234 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1236 load_url_in_tab(tab, url);
1237 return tab;
1240 static void
1241 session_new_tab_cb(const char *url)
1243 new_tab(url);
1246 static void
1247 usage(void)
1249 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1250 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1253 int
1254 ui_init(int argc, char * const *argv)
1256 char path[PATH_MAX];
1257 const char *url = NEW_TAB_URL;
1258 int ch, configtest = 0, fonf = 0;
1260 if (getenv("NO_COLOR") != NULL)
1261 enable_colors = 0;
1263 strlcpy(path, getenv("HOME"), sizeof(path));
1264 strlcat(path, "/.telescope/config", sizeof(path));
1266 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1267 switch (ch) {
1268 case 'c':
1269 fonf = 1;
1270 strlcpy(path, optarg, sizeof(path));
1271 break;
1272 case 'n':
1273 configtest = 1;
1274 break;
1275 case 'h':
1276 usage();
1277 return 0;
1278 default:
1279 usage();
1280 return 1;
1283 argc -= optind;
1284 argv += optind;
1286 /* setup keys before reading the config */
1287 TAILQ_INIT(&global_map.m);
1288 global_map.unhandled_input = global_key_unbound;
1290 TAILQ_INIT(&minibuffer_map.m);
1292 config_init();
1293 parseconfig(path, fonf);
1294 if (configtest){
1295 puts("config OK");
1296 exit(0);
1299 if (argc != 0)
1300 url = argv[0];
1302 setlocale(LC_ALL, "");
1304 TAILQ_INIT(&eecmd_history.head);
1305 TAILQ_INIT(&ir_history.head);
1306 TAILQ_INIT(&lu_history.head);
1308 ministate.line.type = LINE_TEXT;
1309 ministate.vline.parent = &ministate.line;
1310 ministate.buffer.current_line = &ministate.vline;
1312 /* initialize help window */
1313 TAILQ_INIT(&helpwin.head);
1315 base_map = &global_map;
1316 current_map = &global_map;
1318 initscr();
1320 if (enable_colors) {
1321 if (has_colors()) {
1322 start_color();
1323 use_default_colors();
1324 } else
1325 enable_colors = 0;
1328 config_apply_style();
1330 raw();
1331 noecho();
1332 nonl();
1333 intrflush(stdscr, FALSE);
1335 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1336 return 0;
1337 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1338 return 0;
1339 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1340 return 0;
1341 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1342 return 0;
1343 if ((help = newwin(1, 1, 1, 0)) == NULL)
1344 return 0;
1346 body_lines = LINES-3;
1347 body_cols = COLS;
1349 wbkgd(body, body_face.body);
1350 wbkgd(minibuf, minibuffer_face.background);
1352 update_x_offset();
1354 keypad(body, TRUE);
1355 scrollok(body, FALSE);
1357 /* non-blocking input */
1358 wtimeout(body, 0);
1360 mvwprintw(body, 0, 0, "");
1362 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1363 event_add(&stdioev, NULL);
1365 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1366 signal_add(&winchev, NULL);
1368 load_last_session(session_new_tab_cb);
1369 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1370 new_tab(url);
1372 return 1;
1375 void
1376 ui_on_tab_loaded(struct tab *tab)
1378 stop_loading_anim(tab);
1379 message("Loaded %s", tab->hist_cur->h);
1381 redraw_tabline();
1382 wrefresh(tabline);
1383 if (in_minibuffer)
1384 wrefresh(minibuf);
1385 else
1386 wrefresh(body);
1389 void
1390 ui_on_tab_refresh(struct tab *tab)
1392 wrap_page(&tab->buffer, body_cols);
1393 if (tab->flags & TAB_CURRENT) {
1394 restore_cursor(&tab->buffer);
1395 redraw_tab(tab);
1396 } else
1397 tab->flags |= TAB_URGENT;
1400 const char *
1401 ui_keyname(int k)
1403 return keyname(k);
1406 void
1407 ui_toggle_side_window(void)
1409 side_window = !side_window;
1410 if (side_window)
1411 recompute_help();
1414 * ugly hack, but otherwise the window doesn't get updated
1415 * until I call handle_resize a second time (i.e. C-l). I
1416 * will be happy to know why something like this is needed.
1418 handle_resize_nodelay(0, 0, NULL);
1419 handle_resize_nodelay(0, 0, NULL);
1422 void
1423 ui_schedule_redraw(void)
1425 handle_resize_nodelay(0, 0, NULL);
1428 void
1429 ui_require_input(struct tab *tab, int hide)
1431 /* TODO: hard-switching to another tab is ugly */
1432 switch_to_tab(tab);
1434 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1435 &ir_history);
1436 strlcpy(ministate.prompt, "Input required: ",
1437 sizeof(ministate.prompt));
1438 redraw_tab(tab);
1441 void
1442 ui_yornp(const char *prompt, void (*fn)(int, unsigned int),
1443 unsigned int data)
1445 size_t len;
1447 if (in_minibuffer) {
1448 fn(0, data);
1449 return;
1452 yornp_cb = fn;
1453 yornp_data = data;
1454 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1455 yornp_abort, NULL);
1457 len = sizeof(ministate.prompt);
1458 strlcpy(ministate.prompt, prompt, len);
1459 strlcat(ministate.prompt, " (y or n) ", len);
1460 redraw_tab(current_tab());
1463 void
1464 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1465 unsigned int data)
1467 size_t len;
1469 if (in_minibuffer)
1470 return;
1472 read_cb = fn;
1473 read_data = data;
1474 enter_minibuffer(read_self_insert, read_select, read_abort,
1475 &read_history);
1477 len = sizeof(ministate.prompt);
1478 strlcpy(ministate.prompt, prompt, len);
1479 strlcat(ministate.prompt, ": ", len);
1480 redraw_tab(current_tab());
1483 void
1484 ui_end(void)
1486 endwin();