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;
85 struct tab *current_tab;
87 static struct event resizeev;
88 static struct timeval resize_timer = { 0, 250000 };
90 static WINDOW *tabline, *body, *modeline, *echoarea, *minibuffer;
92 int body_lines, body_cols;
94 static WINDOW *help;
95 static struct buffer helpwin;
96 static int help_lines, help_cols;
98 static int side_window;
100 static struct event clechoev;
101 static struct timeval clechoev_timer = { 5, 0 };
102 static struct timeval loadingev_timer = { 0, 250000 };
104 static uint32_t tab_counter;
106 static char keybuf[64];
108 struct kmap global_map,
109 minibuffer_map,
110 *current_map,
111 *base_map;
113 int in_minibuffer;
115 static inline void
116 update_x_offset(void)
118 if (olivetti_mode && fill_column < body_cols)
119 x_offset = (body_cols - fill_column)/2;
120 else
121 x_offset = 0;
124 void
125 save_excursion(struct excursion *place, struct buffer *buffer)
127 place->curs_x = buffer->curs_x;
128 place->curs_y = buffer->curs_y;
129 place->line_off = buffer->line_off;
130 place->current_line = buffer->current_line;
131 place->cpoff = buffer->cpoff;
134 void
135 restore_excursion(struct excursion *place, struct buffer *buffer)
137 buffer->curs_x = place->curs_x;
138 buffer->curs_y = place->curs_y;
139 buffer->line_off = place->line_off;
140 buffer->current_line = place->current_line;
141 buffer->cpoff = place->cpoff;
144 static void
145 restore_curs_x(struct buffer *buffer)
147 struct vline *vl;
148 const char *prfx;
150 vl = buffer->current_line;
151 if (vl == NULL || vl->line == NULL)
152 buffer->curs_x = buffer->cpoff = 0;
153 else if (vl->parent->data != NULL)
154 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
155 else
156 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
158 buffer->curs_x += x_offset;
160 if (vl != NULL) {
161 prfx = line_prefixes[vl->parent->type].prfx1;
162 buffer->curs_x += utf8_swidth(prfx);
166 void
167 global_key_unbound(void)
169 message("%s is undefined", keybuf);
172 static struct vline *
173 nth_line(struct buffer *buffer, size_t n)
175 struct vline *vl;
176 size_t i;
178 i = 0;
179 TAILQ_FOREACH(vl, &buffer->head, vlines) {
180 if (i == n)
181 return vl;
182 i++;
185 /* unreachable */
186 abort();
189 struct buffer *
190 current_buffer(void)
192 if (in_minibuffer)
193 return &ministate.buffer;
194 return &current_tab->buffer;
197 static int
198 readkey(void)
200 uint32_t state = 0;
202 if ((thiskey.key = wgetch(body)) == ERR)
203 return 0;
205 thiskey.meta = thiskey.key == 27;
206 if (thiskey.meta) {
207 thiskey.key = wgetch(body);
208 if (thiskey.key == ERR || thiskey.key == 27) {
209 thiskey.meta = 0;
210 thiskey.key = 27;
214 thiskey.cp = 0;
215 if ((unsigned int)thiskey.key < UINT8_MAX) {
216 while (1) {
217 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
218 break;
219 if ((thiskey.key = wgetch(body)) == ERR) {
220 message("Error decoding user input");
221 return 0;
226 return 1;
229 static void
230 dispatch_stdio(int fd, short ev, void *d)
232 struct keymap *k;
233 const char *keyname;
234 char tmp[5] = {0};
236 /* TODO: schedule a redraw? */
237 if (too_small)
238 return;
240 if (!readkey())
241 return;
243 if (keybuf[0] != '\0')
244 strlcat(keybuf, " ", sizeof(keybuf));
245 if (thiskey.meta)
246 strlcat(keybuf, "M-", sizeof(keybuf));
247 if (thiskey.cp != 0) {
248 utf8_encode(thiskey.cp, tmp);
249 strlcat(keybuf, tmp, sizeof(keybuf));
250 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
251 strlcat(keybuf, keyname, sizeof(keybuf));
252 } else {
253 tmp[0] = thiskey.key;
254 strlcat(keybuf, tmp, sizeof(keybuf));
257 TAILQ_FOREACH(k, &current_map->m, keymaps) {
258 if (k->meta == thiskey.meta &&
259 k->key == thiskey.key) {
260 if (k->fn == NULL)
261 current_map = &k->map;
262 else {
263 current_map = base_map;
264 strlcpy(keybuf, "", sizeof(keybuf));
265 k->fn(current_buffer());
267 goto done;
271 if (current_map->unhandled_input != NULL)
272 current_map->unhandled_input();
273 else
274 global_key_unbound();
276 strlcpy(keybuf, "", sizeof(keybuf));
277 current_map = base_map;
279 done:
280 if (side_window)
281 recompute_help();
283 if (should_rearrange_windows)
284 rearrange_windows();
285 redraw_tab(current_tab);
288 static void
289 handle_clear_echoarea(int fd, short ev, void *d)
291 free(ministate.curmesg);
292 ministate.curmesg = NULL;
294 redraw_minibuffer();
295 place_cursor(0);
298 static void
299 handle_resize(int sig, short ev, void *d)
301 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
302 event_del(&resizeev);
304 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
305 evtimer_add(&resizeev, &resize_timer);
308 static void
309 handle_resize_nodelay(int s, short ev, void *d)
311 endwin();
312 refresh();
313 clear();
315 rearrange_windows();
318 static void
319 rearrange_windows(void)
321 int lines;
323 should_rearrange_windows = 0;
325 lines = LINES;
327 if ((too_small = lines < 15)) {
328 erase();
329 printw("Window too small.");
330 refresh();
331 return;
334 /* move and resize the windows, in reverse order! */
336 if (in_minibuffer == MB_COMPREAD) {
337 mvwin(minibuffer, lines-10, 0);
338 wresize(minibuffer, 10, COLS);
339 lines -= 10;
341 wrap_page(&ministate.compl.buffer, COLS);
344 mvwin(echoarea, --lines, 0);
345 wresize(echoarea, 1, COLS);
347 mvwin(modeline, --lines, 0);
348 wresize(modeline, 1, COLS);
350 body_lines = --lines;
351 body_cols = COLS;
353 if (side_window) {
354 help_cols = 0.3 * COLS;
355 help_lines = lines;
356 mvwin(help, 1, 0);
357 wresize(help, help_lines, help_cols);
359 wrap_page(&helpwin, help_cols);
361 body_cols = COLS - help_cols - 1;
362 mvwin(body, 1, help_cols);
363 } else
364 mvwin(body, 1, 0);
366 update_x_offset();
367 wresize(body, body_lines, body_cols);
369 wresize(tabline, 1, COLS);
371 wrap_page(&current_tab->buffer, body_cols);
372 redraw_tab(current_tab);
375 static int
376 wrap_page(struct buffer *buffer, int width)
378 struct line *l;
379 const struct line *top_orig, *orig;
380 struct vline *vl;
381 int pre_width;
382 const char *prfx;
384 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
385 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
387 buffer->top_line = NULL;
388 buffer->current_line = NULL;
390 buffer->force_redraw = 1;
391 buffer->curs_y = 0;
392 buffer->line_off = 0;
394 empty_vlist(buffer);
396 TAILQ_FOREACH(l, &buffer->page.head, lines) {
397 prfx = line_prefixes[l->type].prfx1;
398 switch (l->type) {
399 case LINE_TEXT:
400 case LINE_LINK:
401 case LINE_TITLE_1:
402 case LINE_TITLE_2:
403 case LINE_TITLE_3:
404 case LINE_ITEM:
405 case LINE_QUOTE:
406 case LINE_PRE_START:
407 case LINE_PRE_END:
408 wrap_text(buffer, prfx, l, MIN(fill_column, width));
409 break;
410 case LINE_PRE_CONTENT:
411 if (olivetti_mode)
412 pre_width = MIN(fill_column, width);
413 else
414 pre_width = width;
415 hardwrap_text(buffer, l, pre_width);
416 break;
417 case LINE_COMPL:
418 case LINE_COMPL_CURRENT:
419 wrap_one(buffer, prfx, l, width);
420 break;
423 if (top_orig == l && buffer->top_line == NULL) {
424 buffer->line_off = buffer->line_max-1;
425 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
427 while (1) {
428 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
429 if (vl == NULL || vl->parent != orig)
430 break;
431 buffer->top_line = vl;
432 buffer->line_off--;
436 if (orig == l && buffer->current_line == NULL) {
437 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
439 while (1) {
440 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
441 if (vl == NULL || vl->parent != orig)
442 break;
443 buffer->current_line = vl;
448 if (buffer->current_line == NULL)
449 buffer->current_line = TAILQ_FIRST(&buffer->head);
451 if (buffer->top_line == NULL)
452 buffer->top_line = buffer->current_line;
454 return 1;
457 static void
458 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
459 const char **prfx_ret, const char **text_ret)
461 int type, i, cont, width;
462 char *space, *t;
464 if ((*text_ret = vl->line) == NULL)
465 *text_ret = "";
467 cont = vl->flags & L_CONTINUATION;
468 type = vl->parent->type;
469 if (!cont)
470 *prfx_ret = line_prefixes[type].prfx1;
471 else
472 *prfx_ret = line_prefixes[type].prfx2;
474 space = vl->parent->data;
475 if (!emojify_link || type != LINE_LINK || space == NULL)
476 return;
478 if (cont) {
479 memset(buf, 0, len);
480 width = utf8_swidth_between(vl->parent->line, space);
481 for (i = 0; i < width + 1; ++i)
482 strlcat(buf, " ", len);
483 } else {
484 strlcpy(buf, *text_ret, len);
485 if ((t = strchr(buf, ' ')) != NULL)
486 *t = '\0';
487 strlcat(buf, " ", len);
489 /* skip the emoji */
490 *text_ret += (space - vl->parent->line) + 1;
493 *prfx_ret = buf;
496 /*
497 * Core part of the rendering. It prints a vline starting from the
498 * current cursor position. Printing a vline consists of skipping
499 * `off' columns (for olivetti-mode), print the correct prefix (which
500 * may be the emoji in case of emojified links-lines), printing the
501 * text itself, filling until width - off and filling off columns
502 * again.
503 */
504 static void
505 print_vline(int off, int width, WINDOW *window, struct vline *vl)
507 /*
508 * Believe me or not, I've seen emoji ten code points long!
509 * That means, to stay large, 4*10 bytes + NUL.
510 */
511 char emojibuf[41] = {0};
512 const char *text, *prfx;
513 struct line_face *f;
514 int i, left, x, y;
516 f = &line_faces[vl->parent->type];
518 /* unused, set by getyx */
519 (void)y;
521 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
523 wattr_on(window, body_face.left, NULL);
524 for (i = 0; i < off; i++)
525 waddch(window, ' ');
526 wattr_off(window, body_face.left, NULL);
528 wattr_on(window, f->prefix, NULL);
529 wprintw(window, "%s", prfx);
530 wattr_off(window, f->prefix, NULL);
532 wattr_on(window, f->text, NULL);
533 wprintw(window, "%s", text);
534 wattr_off(window, f->text, NULL);
536 getyx(window, y, x);
538 left = width - x;
540 wattr_on(window, f->trail, NULL);
541 for (i = 0; i < left - off; ++i)
542 waddch(window, ' ');
543 wattr_off(window, f->trail, NULL);
545 wattr_on(window, body_face.right, NULL);
546 for (i = 0; i < off; i++)
547 waddch(window, ' ');
548 wattr_off(window, body_face.right, NULL);
552 static void
553 redraw_tabline(void)
555 struct tab *tab;
556 size_t toskip, ots, tabwidth, space, x;
557 int current, y, truncated, pair;
558 const char *title;
559 char buf[25];
561 x = 0;
563 /* unused, but setted by a getyx */
564 (void)y;
566 tabwidth = sizeof(buf)+1;
567 space = COLS-2;
569 toskip = 0;
570 TAILQ_FOREACH(tab, &tabshead, tabs) {
571 toskip++;
572 if (tab == current_tab)
573 break;
576 if (toskip * tabwidth < space)
577 toskip = 0;
578 else {
579 ots = toskip;
580 toskip--;
581 while (toskip != 0 &&
582 (ots - toskip+1) * tabwidth < space)
583 toskip--;
586 werase(tabline);
587 wattr_on(tabline, tab_face.background, NULL);
588 wprintw(tabline, toskip == 0 ? " " : "<");
589 wattr_off(tabline, tab_face.background, NULL);
591 truncated = 0;
592 TAILQ_FOREACH(tab, &tabshead, tabs) {
593 if (truncated)
594 break;
595 if (toskip != 0) {
596 toskip--;
597 continue;
600 getyx(tabline, y, x);
601 if (x + sizeof(buf)+2 >= (size_t)COLS)
602 truncated = 1;
604 current = tab == current_tab;
606 if (*(title = tab->buffer.page.title) == '\0')
607 title = tab->hist_cur->h;
609 if (tab->flags & TAB_URGENT)
610 strlcpy(buf, "!", sizeof(buf));
611 else
612 strlcpy(buf, " ", sizeof(buf));
614 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
615 /* truncation happens */
616 strlcpy(&buf[sizeof(buf)-4], "...", 4);
617 } else {
618 /* pad with spaces */
619 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
620 /* nop */ ;
623 pair = current ? tab_face.current : tab_face.tab;
624 wattr_on(tabline, pair, NULL);
625 wprintw(tabline, "%s", buf);
626 wattr_off(tabline, pair, NULL);
628 wattr_on(tabline, tab_face.background, NULL);
629 if (TAILQ_NEXT(tab, tabs) != NULL)
630 wprintw(tabline, "│");
631 wattr_off(tabline, tab_face.background, NULL);
634 wattr_on(tabline, tab_face.background, NULL);
635 for (; x < (size_t)COLS; ++x)
636 waddch(tabline, ' ');
637 if (truncated)
638 mvwprintw(tabline, 0, COLS-1, ">");
639 wattr_off(tabline, tab_face.background, NULL);
642 /*
643 * Compute the first visible line around vl. Try to search forward
644 * until the end of the buffer; if a visible line is not found, search
645 * backward. Return NULL if no viable line was found.
646 */
647 struct vline *
648 adjust_line(struct vline *vl, struct buffer *buffer)
650 struct vline *t;
652 if (vl == NULL)
653 return NULL;
655 if (!(vl->parent->flags & L_HIDDEN))
656 return vl;
658 /* search forward */
659 for (t = vl;
660 t != NULL && t->parent->flags & L_HIDDEN;
661 t = TAILQ_NEXT(t, vlines))
662 ; /* nop */
664 if (t != NULL)
665 return t;
667 /* search backward */
668 for (t = vl;
669 t != NULL && t->parent->flags & L_HIDDEN;
670 t = TAILQ_PREV(t, vhead, vlines))
671 ; /* nop */
673 return t;
676 static void
677 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
679 struct vline *vl;
680 int l, onscreen;
682 restore_curs_x(buffer);
684 /*
685 * TODO: ignoring buffer->force_update and always
686 * re-rendering. In theory we can recompute the y position
687 * without a re-render, and optimize here. It's not the only
688 * optimisation possible here, wscrl wolud also be an
689 * interesting one.
690 */
692 again:
693 werase(win);
694 buffer->curs_y = 0;
696 if (TAILQ_EMPTY(&buffer->head))
697 goto end;
699 if (buffer->top_line == NULL)
700 buffer->top_line = TAILQ_FIRST(&buffer->head);
702 buffer->top_line = adjust_line(buffer->top_line, buffer);
703 if (buffer->top_line == NULL)
704 goto end;
706 buffer->current_line = adjust_line(buffer->current_line, buffer);
708 l = 0;
709 onscreen = 0;
710 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
711 if (vl->parent->flags & L_HIDDEN)
712 continue;
714 wmove(win, l, 0);
715 print_vline(off, width, win, vl);
717 if (vl == buffer->current_line)
718 onscreen = 1;
720 if (!onscreen)
721 buffer->curs_y++;
723 l++;
724 if (l == height)
725 break;
728 if (!onscreen) {
729 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
730 if (vl == buffer->current_line)
731 break;
732 if (vl->parent->flags & L_HIDDEN)
733 continue;
734 buffer->line_off++;
735 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
738 if (vl != NULL)
739 goto again;
742 buffer->last_line_off = buffer->line_off;
743 buffer->force_redraw = 0;
744 end:
745 wmove(win, buffer->curs_y, buffer->curs_x);
748 static void
749 redraw_help(void)
751 redraw_window(help, 0, help_lines, help_cols, &helpwin);
754 static void
755 redraw_body(struct tab *tab)
757 static struct tab *last_tab;
759 if (last_tab != tab)
760 tab->buffer.force_redraw =1;
761 last_tab = tab;
763 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
766 static inline char
767 trust_status_char(enum trust_state ts)
769 switch (ts) {
770 case TS_UNKNOWN: return 'u';
771 case TS_UNTRUSTED: return '!';
772 case TS_TEMP_TRUSTED: return '!';
773 case TS_TRUSTED: return 'v';
774 case TS_VERIFIED: return 'V';
775 default: return 'X';
779 static void
780 redraw_modeline(struct tab *tab)
782 double pct;
783 int x, y, max_x, max_y;
784 const char *mode = tab->buffer.page.name;
785 const char *spin = "-\\|/";
787 werase(modeline);
788 wattr_on(modeline, modeline_face.background, NULL);
789 wmove(modeline, 0, 0);
791 wprintw(modeline, "-%c%c %s ",
792 spin[tab->loading_anim_step],
793 trust_status_char(tab->trust),
794 mode == NULL ? "(none)" : mode);
796 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
797 / tab->buffer.line_max;
799 if (tab->buffer.line_max <= (size_t)body_lines)
800 wprintw(modeline, "All ");
801 else if (tab->buffer.line_off == 0)
802 wprintw(modeline, "Top ");
803 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
804 wprintw(modeline, "Bottom ");
805 else
806 wprintw(modeline, "%.0f%% ", pct);
808 wprintw(modeline, "%d/%d %s ",
809 tab->buffer.line_off + tab->buffer.curs_y,
810 tab->buffer.line_max,
811 tab->hist_cur->h);
813 getyx(modeline, y, x);
814 getmaxyx(modeline, max_y, max_x);
816 (void)y;
817 (void)max_y;
819 for (; x < max_x; ++x)
820 waddstr(modeline, "-");
822 wattr_off(modeline, modeline_face.background, NULL);
825 static void
826 redraw_minibuffer(void)
828 wattr_on(echoarea, minibuffer_face.background, NULL);
829 werase(echoarea);
831 if (in_minibuffer)
832 do_redraw_minibuffer();
833 else
834 do_redraw_echoarea();
836 if (in_minibuffer == MB_COMPREAD)
837 do_redraw_minibuffer_compl();
839 wattr_off(echoarea, minibuffer_face.background, NULL);
842 static void
843 do_redraw_echoarea(void)
845 struct vline *vl;
847 if (ministate.curmesg != NULL)
848 wprintw(echoarea, "%s", ministate.curmesg);
849 else if (*keybuf != '\0')
850 waddstr(echoarea, keybuf);
851 else {
852 /* If nothing else, show the URL at point */
853 vl = current_tab->buffer.current_line;
854 if (vl != NULL && vl->parent->type == LINE_LINK)
855 waddstr(echoarea, vl->parent->alt);
859 static void
860 do_redraw_minibuffer(void)
862 size_t off_y, off_x = 0;
863 const char *start, *c;
865 /* unused, set by getyx */
866 (void)off_y;
868 wmove(echoarea, 0, 0);
870 if (in_minibuffer == MB_COMPREAD)
871 wprintw(echoarea, "(%2d) ",
872 ministate.compl.buffer.line_max);
874 wprintw(echoarea, "%s", ministate.prompt);
875 if (ministate.hist_cur != NULL)
876 wprintw(echoarea, "(%zu/%zu) ",
877 ministate.hist_off + 1,
878 ministate.history->len);
880 getyx(echoarea, off_y, off_x);
882 start = ministate.hist_cur != NULL
883 ? ministate.hist_cur->h
884 : ministate.buf;
885 c = utf8_nth(ministate.buffer.current_line->line,
886 ministate.buffer.cpoff);
887 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
888 start = utf8_next_cp(start);
891 waddstr(echoarea, start);
893 if (ministate.curmesg != NULL)
894 wprintw(echoarea, " [%s]", ministate.curmesg);
896 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
899 static void
900 do_redraw_minibuffer_compl(void)
902 redraw_window(minibuffer, 0, 10, body_cols,
903 &ministate.compl.buffer);
906 /*
907 * Place the cursor in the right ncurses window. If soft is 1, use
908 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
909 * wrefresh.
910 */
911 static void
912 place_cursor(int soft)
914 int (*touch)(WINDOW *);
916 if (soft)
917 touch = wnoutrefresh;
918 else
919 touch = wrefresh;
921 if (in_minibuffer) {
922 touch(body);
923 touch(echoarea);
924 } else {
925 touch(echoarea);
926 touch(body);
930 static void
931 redraw_tab(struct tab *tab)
933 if (too_small)
934 return;
936 if (side_window) {
937 redraw_help();
938 wnoutrefresh(help);
941 redraw_tabline();
942 redraw_body(tab);
943 redraw_modeline(tab);
944 redraw_minibuffer();
946 wnoutrefresh(tabline);
947 wnoutrefresh(modeline);
949 if (in_minibuffer == MB_COMPREAD)
950 wnoutrefresh(minibuffer);
952 place_cursor(1);
954 doupdate();
957 static void
958 emit_help_item(char *prfx, void *fn)
960 struct line *l;
961 struct cmd *cmd;
963 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
964 if (fn == cmd->fn)
965 break;
967 assert(cmd != NULL);
969 if ((l = calloc(1, sizeof(*l))) == NULL)
970 abort();
972 l->type = LINE_TEXT;
973 l->alt = NULL;
975 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
977 if (TAILQ_EMPTY(&helpwin.page.head))
978 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
979 else
980 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
983 static void
984 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
986 struct keymap *k;
987 char p[32];
988 const char *kn;
990 TAILQ_FOREACH(k, &keymap->m, keymaps) {
991 strlcpy(p, prfx, sizeof(p));
992 if (*p != '\0')
993 strlcat(p, " ", sizeof(p));
994 if (k->meta)
995 strlcat(p, "M-", sizeof(p));
996 if ((kn = unkbd(k->key)) != NULL)
997 strlcat(p, kn, sizeof(p));
998 else
999 strlcat(p, keyname(k->key), sizeof(p));
1001 if (k->fn == NULL)
1002 rec_compute_help(&k->map, p, sizeof(p));
1003 else
1004 emit_help_item(p, k->fn);
1008 static void
1009 recompute_help(void)
1011 char p[32] = { 0 };
1013 empty_vlist(&helpwin);
1014 empty_linelist(&helpwin);
1015 rec_compute_help(current_map, p, sizeof(p));
1016 wrap_page(&helpwin, help_cols);
1019 void
1020 vmessage(const char *fmt, va_list ap)
1022 if (evtimer_pending(&clechoev, NULL))
1023 evtimer_del(&clechoev);
1025 free(ministate.curmesg);
1026 ministate.curmesg = NULL;
1028 if (fmt != NULL) {
1029 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1030 evtimer_add(&clechoev, &clechoev_timer);
1032 /* TODO: what to do if the allocation fails here? */
1033 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1034 ministate.curmesg = NULL;
1037 redraw_minibuffer();
1038 place_cursor(0);
1041 void
1042 message(const char *fmt, ...)
1044 va_list ap;
1046 va_start(ap, fmt);
1047 vmessage(fmt, ap);
1048 va_end(ap);
1051 void
1052 start_loading_anim(struct tab *tab)
1054 if (tab->loading_anim)
1055 return;
1056 tab->loading_anim = 1;
1057 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1058 evtimer_add(&tab->loadingev, &loadingev_timer);
1061 static void
1062 update_loading_anim(int fd, short ev, void *d)
1064 struct tab *tab = d;
1066 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1068 if (tab == current_tab) {
1069 redraw_modeline(tab);
1070 wrefresh(modeline);
1071 wrefresh(body);
1072 if (in_minibuffer)
1073 wrefresh(echoarea);
1076 evtimer_add(&tab->loadingev, &loadingev_timer);
1079 static void
1080 stop_loading_anim(struct tab *tab)
1082 if (!tab->loading_anim)
1083 return;
1084 evtimer_del(&tab->loadingev);
1085 tab->loading_anim = 0;
1086 tab->loading_anim_step = 0;
1088 if (tab != current_tab)
1089 return;
1091 redraw_modeline(tab);
1093 wrefresh(modeline);
1094 wrefresh(body);
1095 if (in_minibuffer)
1096 wrefresh(echoarea);
1099 void
1100 load_url_in_tab(struct tab *tab, const char *url)
1102 message("Loading %s...", url);
1103 start_loading_anim(tab);
1104 load_url(tab, url);
1106 tab->buffer.curs_x = 0;
1107 tab->buffer.curs_y = 0;
1108 redraw_tab(tab);
1111 void
1112 switch_to_tab(struct tab *tab)
1114 current_tab = tab;
1115 tab->flags &= ~TAB_URGENT;
1118 unsigned int
1119 tab_new_id(void)
1121 return tab_counter++;
1124 struct tab *
1125 new_tab(const char *url)
1127 struct tab *tab;
1129 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1130 event_loopbreak();
1131 return NULL;
1133 tab->fd = -1;
1135 TAILQ_INIT(&tab->hist.head);
1137 TAILQ_INIT(&tab->buffer.head);
1139 tab->id = tab_new_id();
1140 switch_to_tab(tab);
1142 if (TAILQ_EMPTY(&tabshead))
1143 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1144 else
1145 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1147 load_url_in_tab(tab, url);
1148 return tab;
1151 int
1152 ui_print_colors(void)
1154 int colors = 0, pairs = 0, can_change = 0;
1155 int columns = 16, lines, color, i, j;
1157 initscr();
1158 if (has_colors()) {
1159 start_color();
1160 use_default_colors();
1162 colors = COLORS;
1163 pairs = COLOR_PAIRS;
1164 can_change = can_change_color();
1166 endwin();
1168 printf("Term info:\n");
1169 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1170 getenv("TERM"), colors, pairs, can_change);
1171 printf("\n");
1173 if (colors == 0) {
1174 printf("No color support\n");
1175 return 0;
1178 printf("Available colors:\n\n");
1179 lines = (colors - 1) / columns + 1;
1180 color = 0;
1181 for (i = 0; i < lines; ++i) {
1182 for (j = 0; j < columns; ++j, ++color) {
1183 printf("\033[0;38;5;%dm %03d", color, color);
1185 printf("\n");
1188 printf("\033[0m");
1189 fflush(stdout);
1190 return 0;
1193 int
1194 ui_init()
1196 setlocale(LC_ALL, "");
1198 TAILQ_INIT(&eecmd_history.head);
1199 TAILQ_INIT(&ir_history.head);
1200 TAILQ_INIT(&lu_history.head);
1202 ministate.line.type = LINE_TEXT;
1203 ministate.vline.parent = &ministate.line;
1204 ministate.buffer.current_line = &ministate.vline;
1206 /* initialize help window */
1207 TAILQ_INIT(&helpwin.head);
1209 base_map = &global_map;
1210 current_map = &global_map;
1212 initscr();
1214 if (enable_colors) {
1215 if (has_colors()) {
1216 start_color();
1217 use_default_colors();
1218 } else
1219 enable_colors = 0;
1222 config_apply_style();
1224 raw();
1225 noecho();
1226 nonl();
1227 intrflush(stdscr, FALSE);
1229 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1230 return 0;
1231 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1232 return 0;
1233 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1234 return 0;
1235 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1236 return 0;
1237 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1238 return 0;
1239 if ((help = newwin(1, 1, 1, 0)) == NULL)
1240 return 0;
1242 body_lines = LINES-3;
1243 body_cols = COLS;
1245 wbkgd(body, body_face.body);
1246 wbkgd(echoarea, minibuffer_face.background);
1248 update_x_offset();
1250 keypad(body, TRUE);
1251 scrollok(body, FALSE);
1253 /* non-blocking input */
1254 wtimeout(body, 0);
1256 mvwprintw(body, 0, 0, "");
1259 * Dummy so libevent2 won't complain that no event_base is set
1260 * when checking event_pending for the first time
1262 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1263 evtimer_add(&clechoev, &clechoev_timer);
1264 evtimer_set(&resizeev, handle_resize, NULL);
1265 evtimer_add(&resizeev, &resize_timer);
1267 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1268 event_add(&stdioev, NULL);
1270 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1271 signal_add(&winchev, NULL);
1273 return 1;
1276 void
1277 ui_refresh(void)
1279 redraw_tab(current_tab);
1282 void
1283 ui_on_tab_loaded(struct tab *tab)
1285 stop_loading_anim(tab);
1286 message("Loaded %s", tab->hist_cur->h);
1288 redraw_tabline();
1289 wrefresh(tabline);
1290 place_cursor(0);
1293 void
1294 ui_on_tab_refresh(struct tab *tab)
1296 wrap_page(&tab->buffer, body_cols);
1297 if (tab == current_tab)
1298 redraw_tab(tab);
1299 else
1300 tab->flags |= TAB_URGENT;
1303 const char *
1304 ui_keyname(int k)
1306 return keyname(k);
1309 void
1310 ui_toggle_side_window(void)
1312 side_window = !side_window;
1313 if (side_window)
1314 recompute_help();
1317 * ugly hack, but otherwise the window doesn't get updated
1318 * until I call rearrange_windows a second time (e.g. via
1319 * C-l). I will be happy to know why something like this is
1320 * needed.
1322 rearrange_windows();
1323 rearrange_windows();
1326 void
1327 ui_schedule_redraw(void)
1329 should_rearrange_windows = 1;
1332 void
1333 ui_require_input(struct tab *tab, int hide)
1335 /* TODO: hard-switching to another tab is ugly */
1336 switch_to_tab(tab);
1338 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1339 &ir_history, NULL, NULL);
1340 strlcpy(ministate.prompt, "Input required: ",
1341 sizeof(ministate.prompt));
1342 redraw_tab(tab);
1345 void
1346 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1347 struct tab *data)
1349 yornp(prompt, fn, data);
1350 redraw_tab(current_tab);
1353 void
1354 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1355 struct tab *data)
1357 completing_read(prompt, fn, data);
1358 redraw_tab(current_tab);
1361 void
1362 ui_suspend(void)
1364 endwin();
1366 kill(getpid(), SIGSTOP);
1368 refresh();
1369 clear();
1370 rearrange_windows();
1373 void
1374 ui_end(void)
1376 endwin();