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 <assert.h>
34 #include <curses.h>
35 #include <event.h>
36 #include <locale.h>
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
43 #include "defaults.h"
44 #include "minibuffer.h"
45 #include "telescope.h"
46 #include "ui.h"
47 #include "utf8.h"
49 static struct event stdioev, winchev;
51 static void restore_curs_x(struct buffer *);
53 static struct vline *nth_line(struct buffer*, size_t);
54 static int readkey(void);
55 static void dispatch_stdio(int, short, void*);
56 static void handle_clear_echoarea(int, short, void*);
57 static void handle_resize(int, short, void*);
58 static void handle_resize_nodelay(int, short, void*);
59 static void rearrange_windows(void);
60 static int wrap_page(struct buffer*, int);
61 static void line_prefix_and_text(struct vline *, char *, size_t, const char **, const char **);
62 static void print_vline(int, int, WINDOW*, struct vline*);
63 static void redraw_tabline(void);
64 static void redraw_window(WINDOW*, int, int, int, struct buffer*);
65 static void redraw_help(void);
66 static void redraw_body(struct tab*);
67 static void redraw_modeline(struct tab*);
68 static void redraw_minibuffer(void);
69 static void do_redraw_echoarea(void);
70 static void do_redraw_minibuffer(void);
71 static void do_redraw_minibuffer_compl(void);
72 static void place_cursor(int);
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*);
80 static int should_rearrange_windows;
81 static int too_small;
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, *echoarea, *minibuffer;
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 clechoev;
100 static struct timeval clechoev_timer = { 5, 0 };
101 static struct timeval loadingev_timer = { 0, 250000 };
103 static uint32_t tab_counter;
105 static char keybuf[64];
107 struct kmap global_map,
108 minibuffer_map,
109 *current_map,
110 *base_map;
112 int in_minibuffer;
114 static inline void
115 update_x_offset(void)
117 if (olivetti_mode && fill_column < body_cols)
118 x_offset = (body_cols - fill_column)/2;
119 else
120 x_offset = 0;
123 void
124 save_excursion(struct excursion *place, struct buffer *buffer)
126 place->curs_x = buffer->curs_x;
127 place->curs_y = buffer->curs_y;
128 place->line_off = buffer->line_off;
129 place->current_line = buffer->current_line;
130 place->cpoff = buffer->cpoff;
133 void
134 restore_excursion(struct excursion *place, struct buffer *buffer)
136 buffer->curs_x = place->curs_x;
137 buffer->curs_y = place->curs_y;
138 buffer->line_off = place->line_off;
139 buffer->current_line = place->current_line;
140 buffer->cpoff = place->cpoff;
143 static void
144 restore_curs_x(struct buffer *buffer)
146 struct vline *vl;
147 const char *prfx;
149 vl = buffer->current_line;
150 if (vl == NULL || vl->line == NULL)
151 buffer->curs_x = buffer->cpoff = 0;
152 else if (vl->parent->data != NULL)
153 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
154 else
155 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
157 buffer->curs_x += x_offset;
159 if (vl != NULL) {
160 prfx = line_prefixes[vl->parent->type].prfx1;
161 buffer->curs_x += utf8_swidth(prfx);
165 void
166 global_key_unbound(void)
168 message("%s is undefined", keybuf);
171 static struct vline *
172 nth_line(struct buffer *buffer, size_t n)
174 struct vline *vl;
175 size_t i;
177 i = 0;
178 TAILQ_FOREACH(vl, &buffer->head, vlines) {
179 if (i == n)
180 return vl;
181 i++;
184 /* unreachable */
185 abort();
188 struct tab *
189 current_tab(void)
191 struct tab *t;
193 TAILQ_FOREACH(t, &tabshead, tabs) {
194 if (t->flags & TAB_CURRENT)
195 return t;
198 /* unreachable */
199 abort();
202 struct buffer *
203 current_buffer(void)
205 if (in_minibuffer)
206 return &ministate.buffer;
207 return &current_tab()->buffer;
210 static int
211 readkey(void)
213 uint32_t state = 0;
215 if ((thiskey.key = wgetch(body)) == ERR)
216 return 0;
218 thiskey.meta = thiskey.key == 27;
219 if (thiskey.meta) {
220 thiskey.key = wgetch(body);
221 if (thiskey.key == ERR || thiskey.key == 27) {
222 thiskey.meta = 0;
223 thiskey.key = 27;
227 thiskey.cp = 0;
228 if ((unsigned int)thiskey.key < UINT8_MAX) {
229 while (1) {
230 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
231 break;
232 if ((thiskey.key = wgetch(body)) == ERR) {
233 message("Error decoding user input");
234 return 0;
239 return 1;
242 static void
243 dispatch_stdio(int fd, short ev, void *d)
245 struct keymap *k;
246 const char *keyname;
247 char tmp[5] = {0};
249 /* TODO: schedule a redraw? */
250 if (too_small)
251 return;
253 if (!readkey())
254 return;
256 if (keybuf[0] != '\0')
257 strlcat(keybuf, " ", sizeof(keybuf));
258 if (thiskey.meta)
259 strlcat(keybuf, "M-", sizeof(keybuf));
260 if (thiskey.cp != 0) {
261 utf8_encode(thiskey.cp, tmp);
262 strlcat(keybuf, tmp, sizeof(keybuf));
263 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
264 strlcat(keybuf, keyname, sizeof(keybuf));
265 } else {
266 tmp[0] = thiskey.key;
267 strlcat(keybuf, tmp, sizeof(keybuf));
270 TAILQ_FOREACH(k, &current_map->m, keymaps) {
271 if (k->meta == thiskey.meta &&
272 k->key == thiskey.key) {
273 if (k->fn == NULL)
274 current_map = &k->map;
275 else {
276 current_map = base_map;
277 strlcpy(keybuf, "", sizeof(keybuf));
278 k->fn(current_buffer());
280 goto done;
284 if (current_map->unhandled_input != NULL)
285 current_map->unhandled_input();
286 else
287 global_key_unbound();
289 strlcpy(keybuf, "", sizeof(keybuf));
290 current_map = base_map;
292 done:
293 if (side_window)
294 recompute_help();
296 if (should_rearrange_windows)
297 rearrange_windows();
298 redraw_tab(current_tab());
301 static void
302 handle_clear_echoarea(int fd, short ev, void *d)
304 free(ministate.curmesg);
305 ministate.curmesg = NULL;
307 redraw_minibuffer();
308 place_cursor(0);
311 static void
312 handle_resize(int sig, short ev, void *d)
314 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
315 event_del(&resizeev);
317 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
318 evtimer_add(&resizeev, &resize_timer);
321 static void
322 handle_resize_nodelay(int s, short ev, void *d)
324 endwin();
325 refresh();
326 clear();
328 rearrange_windows();
331 static void
332 rearrange_windows(void)
334 struct tab *tab;
335 int lines;
337 should_rearrange_windows = 0;
339 lines = LINES;
341 if ((too_small = lines < 15)) {
342 erase();
343 printw("Window too small.");
344 refresh();
345 return;
348 /* move and resize the windows, in reverse order! */
350 if (in_minibuffer == MB_COMPREAD) {
351 mvwin(minibuffer, lines-10, 0);
352 wresize(minibuffer, 10, COLS);
353 lines -= 10;
355 wrap_page(&ministate.compl.buffer, COLS);
358 mvwin(echoarea, --lines, 0);
359 wresize(echoarea, 1, COLS);
361 mvwin(modeline, --lines, 0);
362 wresize(modeline, 1, COLS);
364 body_lines = --lines;
365 body_cols = COLS;
367 if (side_window) {
368 help_cols = 0.3 * COLS;
369 help_lines = lines;
370 mvwin(help, 1, 0);
371 wresize(help, help_lines, help_cols);
373 wrap_page(&helpwin, help_cols);
375 body_cols = COLS - help_cols - 1;
376 mvwin(body, 1, help_cols);
377 } else
378 mvwin(body, 1, 0);
380 update_x_offset();
381 wresize(body, body_lines, body_cols);
383 wresize(tabline, 1, COLS);
385 tab = current_tab();
387 wrap_page(&tab->buffer, body_cols);
388 redraw_tab(tab);
391 static int
392 wrap_page(struct buffer *buffer, int width)
394 struct line *l;
395 const struct line *top_orig, *orig;
396 struct vline *vl;
397 int pre_width;
398 const char *prfx;
400 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
401 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
403 buffer->top_line = NULL;
404 buffer->current_line = NULL;
406 buffer->force_redraw = 1;
407 buffer->curs_y = 0;
408 buffer->line_off = 0;
410 empty_vlist(buffer);
412 TAILQ_FOREACH(l, &buffer->page.head, lines) {
413 prfx = line_prefixes[l->type].prfx1;
414 switch (l->type) {
415 case LINE_TEXT:
416 case LINE_LINK:
417 case LINE_TITLE_1:
418 case LINE_TITLE_2:
419 case LINE_TITLE_3:
420 case LINE_ITEM:
421 case LINE_QUOTE:
422 case LINE_PRE_START:
423 case LINE_PRE_END:
424 wrap_text(buffer, prfx, l, MIN(fill_column, width));
425 break;
426 case LINE_PRE_CONTENT:
427 if (olivetti_mode)
428 pre_width = MIN(fill_column, width);
429 else
430 pre_width = width;
431 hardwrap_text(buffer, l, pre_width);
432 break;
433 case LINE_COMPL:
434 case LINE_COMPL_CURRENT:
435 wrap_one(buffer, prfx, l, width);
436 break;
439 if (top_orig == l && buffer->top_line == NULL) {
440 buffer->line_off = buffer->line_max-1;
441 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
443 while (1) {
444 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
445 if (vl == NULL || vl->parent != orig)
446 break;
447 buffer->top_line = vl;
448 buffer->line_off--;
452 if (orig == l && buffer->current_line == NULL) {
453 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
455 while (1) {
456 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
457 if (vl == NULL || vl->parent != orig)
458 break;
459 buffer->current_line = vl;
464 if (buffer->current_line == NULL)
465 buffer->current_line = TAILQ_FIRST(&buffer->head);
467 if (buffer->top_line == NULL)
468 buffer->top_line = buffer->current_line;
470 return 1;
473 static void
474 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
475 const char **prfx_ret, const char **text_ret)
477 int type, i, cont, width;
478 char *space, *t;
480 if ((*text_ret = vl->line) == NULL)
481 *text_ret = "";
483 cont = vl->flags & L_CONTINUATION;
484 type = vl->parent->type;
485 if (!cont)
486 *prfx_ret = line_prefixes[type].prfx1;
487 else
488 *prfx_ret = line_prefixes[type].prfx2;
490 space = vl->parent->data;
491 if (!emojify_link || type != LINE_LINK || space == NULL)
492 return;
494 if (cont) {
495 memset(buf, 0, len);
496 width = utf8_swidth_between(vl->parent->line, space);
497 for (i = 0; i < width + 1; ++i)
498 strlcat(buf, " ", len);
499 } else {
500 strlcpy(buf, *text_ret, len);
501 if ((t = strchr(buf, ' ')) != NULL)
502 *t = '\0';
503 strlcat(buf, " ", len);
505 /* skip the emoji */
506 *text_ret += (space - vl->parent->line) + 1;
509 *prfx_ret = buf;
512 /*
513 * Core part of the rendering. It prints a vline starting from the
514 * current cursor position. Printing a vline consists of skipping
515 * `off' columns (for olivetti-mode), print the correct prefix (which
516 * may be the emoji in case of emojified links-lines), printing the
517 * text itself, filling until width - off and filling off columns
518 * again.
519 */
520 static void
521 print_vline(int off, int width, WINDOW *window, struct vline *vl)
523 /*
524 * Believe me or not, I've seen emoji ten code points long!
525 * That means, to stay large, 4*10 bytes + NUL.
526 */
527 char emojibuf[41] = {0};
528 const char *text, *prfx;
529 struct line_face *f;
530 int i, left, x, y;
532 f = &line_faces[vl->parent->type];
534 /* unused, set by getyx */
535 (void)y;
537 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
539 wattr_on(window, body_face.left, NULL);
540 for (i = 0; i < off; i++)
541 waddch(window, ' ');
542 wattr_off(window, body_face.left, NULL);
544 wattr_on(window, f->prefix, NULL);
545 wprintw(window, "%s", prfx);
546 wattr_off(window, f->prefix, NULL);
548 wattr_on(window, f->text, NULL);
549 wprintw(window, "%s", text);
550 wattr_off(window, f->text, NULL);
552 getyx(window, y, x);
554 left = width - x;
556 wattr_on(window, f->trail, NULL);
557 for (i = 0; i < left - off; ++i)
558 waddch(window, ' ');
559 wattr_off(window, f->trail, NULL);
561 wattr_on(window, body_face.right, NULL);
562 for (i = 0; i < off; i++)
563 waddch(window, ' ');
564 wattr_off(window, body_face.right, NULL);
568 static void
569 redraw_tabline(void)
571 struct tab *tab;
572 size_t toskip, ots, tabwidth, space, x;
573 int current, y, truncated;
574 const char *title;
575 char buf[25];
577 x = 0;
579 /* unused, but setted by a getyx */
580 (void)y;
582 tabwidth = sizeof(buf)+1;
583 space = COLS-2;
585 toskip = 0;
586 TAILQ_FOREACH(tab, &tabshead, tabs) {
587 toskip++;
588 if (tab->flags & TAB_CURRENT)
589 break;
592 if (toskip * tabwidth < space)
593 toskip = 0;
594 else {
595 ots = toskip;
596 toskip--;
597 while (toskip != 0 &&
598 (ots - toskip+1) * tabwidth < space)
599 toskip--;
602 werase(tabline);
603 wattr_on(tabline, tab_face.background, NULL);
604 wprintw(tabline, toskip == 0 ? " " : "<");
605 wattr_off(tabline, tab_face.background, NULL);
607 truncated = 0;
608 TAILQ_FOREACH(tab, &tabshead, tabs) {
609 if (truncated)
610 break;
611 if (toskip != 0) {
612 toskip--;
613 continue;
616 getyx(tabline, y, x);
617 if (x + sizeof(buf)+2 >= (size_t)COLS)
618 truncated = 1;
620 current = tab->flags & TAB_CURRENT;
622 if (*(title = tab->buffer.page.title) == '\0')
623 title = tab->hist_cur->h;
625 if (tab->flags & TAB_URGENT)
626 strlcpy(buf, "!", sizeof(buf));
627 else
628 strlcpy(buf, " ", sizeof(buf));
630 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
631 /* truncation happens */
632 strlcpy(&buf[sizeof(buf)-4], "...", 4);
633 } else {
634 /* pad with spaces */
635 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
636 /* nop */ ;
639 if (current)
640 wattr_on(tabline, tab_face.current, NULL);
641 else
642 wattr_on(tabline, tab_face.tab, NULL);
644 wprintw(tabline, "%s", buf);
645 if (TAILQ_NEXT(tab, tabs) != NULL)
646 wprintw(tabline, " ");
648 if (current)
649 wattr_off(tabline, tab_face.current, NULL);
650 else
651 wattr_off(tabline, tab_face.tab, NULL);
654 wattr_on(tabline, tab_face.background, NULL);
655 for (; x < (size_t)COLS; ++x)
656 waddch(tabline, ' ');
657 if (truncated)
658 mvwprintw(tabline, 0, COLS-1, ">");
659 wattr_off(tabline, tab_face.background, NULL);
662 /*
663 * Compute the first visible line around vl. Try to search forward
664 * until the end of the buffer; if a visible line is not found, search
665 * backward. Return NULL if no viable line was found.
666 */
667 struct vline *
668 adjust_line(struct vline *vl, struct buffer *buffer)
670 struct vline *t;
672 if (vl == NULL)
673 return NULL;
675 if (!(vl->parent->flags & L_HIDDEN))
676 return vl;
678 /* search forward */
679 for (t = vl;
680 t != NULL && t->parent->flags & L_HIDDEN;
681 t = TAILQ_NEXT(t, vlines))
682 ; /* nop */
684 if (t != NULL)
685 return t;
687 /* search backward */
688 for (t = vl;
689 t != NULL && t->parent->flags & L_HIDDEN;
690 t = TAILQ_PREV(t, vhead, vlines))
691 ; /* nop */
693 return t;
696 static void
697 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
699 struct vline *vl;
700 int l, onscreen;
702 restore_curs_x(buffer);
704 /*
705 * TODO: ignoring buffer->force_update and always
706 * re-rendering. In theory we can recompute the y position
707 * without a re-render, and optimize here. It's not the only
708 * optimisation possible here, wscrl wolud also be an
709 * interesting one.
710 */
712 again:
713 werase(win);
714 buffer->curs_y = 0;
716 if (TAILQ_EMPTY(&buffer->head))
717 goto end;
719 if (buffer->top_line == NULL)
720 buffer->top_line = TAILQ_FIRST(&buffer->head);
722 buffer->top_line = adjust_line(buffer->top_line, buffer);
723 if (buffer->top_line == NULL)
724 goto end;
726 buffer->current_line = adjust_line(buffer->current_line, buffer);
728 l = 0;
729 onscreen = 0;
730 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
731 if (vl->parent->flags & L_HIDDEN)
732 continue;
734 wmove(win, l, 0);
735 print_vline(off, width, win, vl);
737 if (vl == buffer->current_line)
738 onscreen = 1;
740 if (!onscreen)
741 buffer->curs_y++;
743 l++;
744 if (l == height)
745 break;
748 if (!onscreen) {
749 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
750 if (vl == buffer->current_line)
751 break;
752 if (vl->parent->flags & L_HIDDEN)
753 continue;
754 buffer->line_off++;
755 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
758 if (vl != NULL)
759 goto again;
762 buffer->last_line_off = buffer->line_off;
763 buffer->force_redraw = 0;
764 end:
765 wmove(win, buffer->curs_y, buffer->curs_x);
768 static void
769 redraw_help(void)
771 redraw_window(help, 0, help_lines, help_cols, &helpwin);
774 static void
775 redraw_body(struct tab *tab)
777 static struct tab *last_tab;
779 if (last_tab != tab)
780 tab->buffer.force_redraw =1;
781 last_tab = tab;
783 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
786 static inline char
787 trust_status_char(enum trust_state ts)
789 switch (ts) {
790 case TS_UNKNOWN: return 'u';
791 case TS_UNTRUSTED: return '!';
792 case TS_TEMP_TRUSTED: return '!';
793 case TS_TRUSTED: return 'v';
794 case TS_VERIFIED: return 'V';
795 default: return 'X';
799 static void
800 redraw_modeline(struct tab *tab)
802 double pct;
803 int x, y, max_x, max_y;
804 const char *mode = tab->buffer.page.name;
805 const char *spin = "-\\|/";
807 werase(modeline);
808 wattr_on(modeline, modeline_face.background, NULL);
809 wmove(modeline, 0, 0);
811 wprintw(modeline, "-%c%c %s ",
812 spin[tab->loading_anim_step],
813 trust_status_char(tab->trust),
814 mode == NULL ? "(none)" : mode);
816 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
817 / tab->buffer.line_max;
819 if (tab->buffer.line_max <= (size_t)body_lines)
820 wprintw(modeline, "All ");
821 else if (tab->buffer.line_off == 0)
822 wprintw(modeline, "Top ");
823 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
824 wprintw(modeline, "Bottom ");
825 else
826 wprintw(modeline, "%.0f%% ", pct);
828 wprintw(modeline, "%d/%d %s ",
829 tab->buffer.line_off + tab->buffer.curs_y,
830 tab->buffer.line_max,
831 tab->hist_cur->h);
833 getyx(modeline, y, x);
834 getmaxyx(modeline, max_y, max_x);
836 (void)y;
837 (void)max_y;
839 for (; x < max_x; ++x)
840 waddstr(modeline, "-");
842 wattr_off(modeline, modeline_face.background, NULL);
845 static void
846 redraw_minibuffer(void)
848 wattr_on(echoarea, minibuffer_face.background, NULL);
849 werase(echoarea);
851 if (in_minibuffer)
852 do_redraw_minibuffer();
853 else
854 do_redraw_echoarea();
856 if (in_minibuffer == MB_COMPREAD)
857 do_redraw_minibuffer_compl();
859 wattr_off(echoarea, minibuffer_face.background, NULL);
862 static void
863 do_redraw_echoarea(void)
865 struct tab *tab;
867 if (ministate.curmesg != NULL)
868 wprintw(echoarea, "%s", ministate.curmesg);
869 else if (*keybuf != '\0')
870 waddstr(echoarea, keybuf);
871 else {
872 /* If nothing else, show the URL at point */
873 tab = current_tab();
874 if (tab->buffer.current_line != NULL &&
875 tab->buffer.current_line->parent->type == LINE_LINK)
876 waddstr(echoarea,
877 tab->buffer.current_line->parent->alt);
881 static void
882 do_redraw_minibuffer(void)
884 size_t off_y, off_x = 0;
885 const char *start, *c;
887 /* unused, set by getyx */
888 (void)off_y;
890 wmove(echoarea, 0, 0);
892 if (in_minibuffer == MB_COMPREAD)
893 wprintw(echoarea, "(%2d) ",
894 ministate.compl.buffer.line_max);
896 wprintw(echoarea, "%s", ministate.prompt);
897 if (ministate.hist_cur != NULL)
898 wprintw(echoarea, "(%zu/%zu) ",
899 ministate.hist_off + 1,
900 ministate.history->len);
902 getyx(echoarea, off_y, off_x);
904 start = ministate.hist_cur != NULL
905 ? ministate.hist_cur->h
906 : ministate.buf;
907 c = utf8_nth(ministate.buffer.current_line->line,
908 ministate.buffer.cpoff);
909 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
910 start = utf8_next_cp(start);
913 waddstr(echoarea, start);
915 if (ministate.curmesg != NULL)
916 wprintw(echoarea, " [%s]", ministate.curmesg);
918 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
921 static void
922 do_redraw_minibuffer_compl(void)
924 redraw_window(minibuffer, 0, 10, body_cols,
925 &ministate.compl.buffer);
928 /*
929 * Place the cursor in the right ncurses window. If soft is 1, use
930 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
931 * wrefresh.
932 */
933 static void
934 place_cursor(int soft)
936 int (*touch)(WINDOW *);
938 if (soft)
939 touch = wnoutrefresh;
940 else
941 touch = wrefresh;
943 if (in_minibuffer) {
944 touch(body);
945 touch(echoarea);
946 } else {
947 touch(echoarea);
948 touch(body);
952 static void
953 redraw_tab(struct tab *tab)
955 if (too_small)
956 return;
958 if (side_window) {
959 redraw_help();
960 wnoutrefresh(help);
963 redraw_tabline();
964 redraw_body(tab);
965 redraw_modeline(tab);
966 redraw_minibuffer();
968 wnoutrefresh(tabline);
969 wnoutrefresh(modeline);
971 if (in_minibuffer == MB_COMPREAD)
972 wnoutrefresh(minibuffer);
974 place_cursor(1);
976 doupdate();
979 static void
980 emit_help_item(char *prfx, void *fn)
982 struct line *l;
983 struct cmd *cmd;
985 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
986 if (fn == cmd->fn)
987 break;
989 assert(cmd != NULL);
991 if ((l = calloc(1, sizeof(*l))) == NULL)
992 abort();
994 l->type = LINE_TEXT;
995 l->alt = NULL;
997 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
999 if (TAILQ_EMPTY(&helpwin.page.head))
1000 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1001 else
1002 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1005 static void
1006 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1008 struct keymap *k;
1009 char p[32];
1010 const char *kn;
1012 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1013 strlcpy(p, prfx, sizeof(p));
1014 if (*p != '\0')
1015 strlcat(p, " ", sizeof(p));
1016 if (k->meta)
1017 strlcat(p, "M-", sizeof(p));
1018 if ((kn = unkbd(k->key)) != NULL)
1019 strlcat(p, kn, sizeof(p));
1020 else
1021 strlcat(p, keyname(k->key), sizeof(p));
1023 if (k->fn == NULL)
1024 rec_compute_help(&k->map, p, sizeof(p));
1025 else
1026 emit_help_item(p, k->fn);
1030 static void
1031 recompute_help(void)
1033 char p[32] = { 0 };
1035 empty_vlist(&helpwin);
1036 empty_linelist(&helpwin);
1037 rec_compute_help(current_map, p, sizeof(p));
1038 wrap_page(&helpwin, help_cols);
1041 void
1042 vmessage(const char *fmt, va_list ap)
1044 if (evtimer_pending(&clechoev, NULL))
1045 evtimer_del(&clechoev);
1047 free(ministate.curmesg);
1048 ministate.curmesg = NULL;
1050 if (fmt != NULL) {
1051 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1052 evtimer_add(&clechoev, &clechoev_timer);
1054 /* TODO: what to do if the allocation fails here? */
1055 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1056 ministate.curmesg = NULL;
1059 redraw_minibuffer();
1060 place_cursor(0);
1063 void
1064 message(const char *fmt, ...)
1066 va_list ap;
1068 va_start(ap, fmt);
1069 vmessage(fmt, ap);
1070 va_end(ap);
1073 void
1074 start_loading_anim(struct tab *tab)
1076 if (tab->loading_anim)
1077 return;
1078 tab->loading_anim = 1;
1079 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1080 evtimer_add(&tab->loadingev, &loadingev_timer);
1083 static void
1084 update_loading_anim(int fd, short ev, void *d)
1086 struct tab *tab = d;
1088 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1090 if (tab->flags & TAB_CURRENT) {
1091 redraw_modeline(tab);
1092 wrefresh(modeline);
1093 wrefresh(body);
1094 if (in_minibuffer)
1095 wrefresh(echoarea);
1098 evtimer_add(&tab->loadingev, &loadingev_timer);
1101 static void
1102 stop_loading_anim(struct tab *tab)
1104 if (!tab->loading_anim)
1105 return;
1106 evtimer_del(&tab->loadingev);
1107 tab->loading_anim = 0;
1108 tab->loading_anim_step = 0;
1110 if (!(tab->flags & TAB_CURRENT))
1111 return;
1113 redraw_modeline(tab);
1115 wrefresh(modeline);
1116 wrefresh(body);
1117 if (in_minibuffer)
1118 wrefresh(echoarea);
1121 void
1122 load_url_in_tab(struct tab *tab, const char *url)
1124 message("Loading %s...", url);
1125 start_loading_anim(tab);
1126 load_url(tab, url);
1128 tab->buffer.curs_x = 0;
1129 tab->buffer.curs_y = 0;
1130 redraw_tab(tab);
1133 void
1134 switch_to_tab(struct tab *tab)
1136 struct tab *t;
1138 TAILQ_FOREACH(t, &tabshead, tabs) {
1139 t->flags &= ~TAB_CURRENT;
1142 tab->flags |= TAB_CURRENT;
1143 tab->flags &= ~TAB_URGENT;
1146 unsigned int
1147 tab_new_id(void)
1149 return tab_counter++;
1152 struct tab *
1153 new_tab(const char *url)
1155 struct tab *tab;
1157 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1158 event_loopbreak();
1159 return NULL;
1161 tab->fd = -1;
1163 TAILQ_INIT(&tab->hist.head);
1165 TAILQ_INIT(&tab->buffer.head);
1167 tab->id = tab_new_id();
1168 switch_to_tab(tab);
1170 if (TAILQ_EMPTY(&tabshead))
1171 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1172 else
1173 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1175 load_url_in_tab(tab, url);
1176 return tab;
1179 int
1180 ui_print_colors(void)
1182 int colors = 0, pairs = 0, can_change = 0;
1183 int columns = 16, lines, color, i, j;
1185 initscr();
1186 if (has_colors()) {
1187 start_color();
1188 use_default_colors();
1190 colors = COLORS;
1191 pairs = COLOR_PAIRS;
1192 can_change = can_change_color();
1194 endwin();
1196 printf("Term info:\n");
1197 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1198 getenv("TERM"), colors, pairs, can_change);
1199 printf("\n");
1201 if (colors == 0) {
1202 printf("No color support\n");
1203 return 0;
1206 printf("Available colors:\n\n");
1207 lines = (colors - 1) / columns + 1;
1208 color = 0;
1209 for (i = 0; i < lines; ++i) {
1210 for (j = 0; j < columns; ++j, ++color) {
1211 printf("\033[0;38;5;%dm %03d", color, color);
1213 printf("\n");
1216 printf("\033[0m");
1217 fflush(stdout);
1218 return 0;
1221 int
1222 ui_init()
1224 setlocale(LC_ALL, "");
1226 TAILQ_INIT(&eecmd_history.head);
1227 TAILQ_INIT(&ir_history.head);
1228 TAILQ_INIT(&lu_history.head);
1230 ministate.line.type = LINE_TEXT;
1231 ministate.vline.parent = &ministate.line;
1232 ministate.buffer.current_line = &ministate.vline;
1234 /* initialize help window */
1235 TAILQ_INIT(&helpwin.head);
1237 base_map = &global_map;
1238 current_map = &global_map;
1240 initscr();
1242 if (enable_colors) {
1243 if (has_colors()) {
1244 start_color();
1245 use_default_colors();
1246 } else
1247 enable_colors = 0;
1250 config_apply_style();
1252 raw();
1253 noecho();
1254 nonl();
1255 intrflush(stdscr, FALSE);
1257 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1258 return 0;
1259 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1260 return 0;
1261 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1262 return 0;
1263 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1264 return 0;
1265 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1266 return 0;
1267 if ((help = newwin(1, 1, 1, 0)) == NULL)
1268 return 0;
1270 body_lines = LINES-3;
1271 body_cols = COLS;
1273 wbkgd(body, body_face.body);
1274 wbkgd(echoarea, minibuffer_face.background);
1276 update_x_offset();
1278 keypad(body, TRUE);
1279 scrollok(body, FALSE);
1281 /* non-blocking input */
1282 wtimeout(body, 0);
1284 mvwprintw(body, 0, 0, "");
1287 * Dummy so libevent2 won't complain that no event_base is set
1288 * when checking event_pending for the first time
1290 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1291 evtimer_add(&clechoev, &clechoev_timer);
1292 evtimer_set(&resizeev, handle_resize, NULL);
1293 evtimer_add(&resizeev, &resize_timer);
1295 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1296 event_add(&stdioev, NULL);
1298 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1299 signal_add(&winchev, NULL);
1301 return 1;
1304 void
1305 ui_on_tab_loaded(struct tab *tab)
1307 stop_loading_anim(tab);
1308 message("Loaded %s", tab->hist_cur->h);
1310 redraw_tabline();
1311 wrefresh(tabline);
1312 place_cursor(0);
1315 void
1316 ui_on_tab_refresh(struct tab *tab)
1318 wrap_page(&tab->buffer, body_cols);
1319 if (tab->flags & TAB_CURRENT)
1320 redraw_tab(tab);
1321 else
1322 tab->flags |= TAB_URGENT;
1325 const char *
1326 ui_keyname(int k)
1328 return keyname(k);
1331 void
1332 ui_toggle_side_window(void)
1334 side_window = !side_window;
1335 if (side_window)
1336 recompute_help();
1339 * ugly hack, but otherwise the window doesn't get updated
1340 * until I call rearrange_windows a second time (e.g. via
1341 * C-l). I will be happy to know why something like this is
1342 * needed.
1344 rearrange_windows();
1345 rearrange_windows();
1348 void
1349 ui_schedule_redraw(void)
1351 should_rearrange_windows = 1;
1354 void
1355 ui_require_input(struct tab *tab, int hide)
1357 /* TODO: hard-switching to another tab is ugly */
1358 switch_to_tab(tab);
1360 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1361 &ir_history, NULL, NULL);
1362 strlcpy(ministate.prompt, "Input required: ",
1363 sizeof(ministate.prompt));
1364 redraw_tab(tab);
1367 void
1368 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1369 struct tab *data)
1371 yornp(prompt, fn, data);
1372 redraw_tab(current_tab());
1375 void
1376 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1377 struct tab *data)
1379 completing_read(prompt, fn, data);
1380 redraw_tab(current_tab());
1383 void
1384 ui_suspend(void)
1386 endwin();
1388 kill(getpid(), SIGSTOP);
1390 refresh();
1391 clear();
1392 rearrange_windows();
1395 void
1396 ui_end(void)
1398 endwin();