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 /*
81 * Used to know when we're finished loading.
82 */
83 static int operating;
85 static int should_rearrange_windows;
86 static int too_small;
87 static int x_offset;
89 struct thiskey thiskey;
90 struct tab *current_tab;
92 static struct event resizeev;
93 static struct timeval resize_timer = { 0, 250000 };
95 static WINDOW *tabline, *body, *modeline, *echoarea, *minibuffer;
97 int body_lines, body_cols;
99 static WINDOW *help;
100 static struct buffer helpwin;
101 static int help_lines, help_cols;
103 static int side_window;
105 static struct event clechoev;
106 static struct timeval clechoev_timer = { 5, 0 };
107 static struct timeval loadingev_timer = { 0, 250000 };
109 static uint32_t tab_counter;
111 static char keybuf[64];
113 struct kmap global_map,
114 minibuffer_map,
115 *current_map,
116 *base_map;
118 int in_minibuffer;
120 static inline void
121 update_x_offset(void)
123 if (olivetti_mode && fill_column < body_cols)
124 x_offset = (body_cols - fill_column)/2;
125 else
126 x_offset = 0;
129 void
130 save_excursion(struct excursion *place, struct buffer *buffer)
132 place->curs_x = buffer->curs_x;
133 place->curs_y = buffer->curs_y;
134 place->line_off = buffer->line_off;
135 place->current_line = buffer->current_line;
136 place->cpoff = buffer->cpoff;
139 void
140 restore_excursion(struct excursion *place, struct buffer *buffer)
142 buffer->curs_x = place->curs_x;
143 buffer->curs_y = place->curs_y;
144 buffer->line_off = place->line_off;
145 buffer->current_line = place->current_line;
146 buffer->cpoff = place->cpoff;
149 static void
150 restore_curs_x(struct buffer *buffer)
152 struct vline *vl;
153 const char *prfx;
155 vl = buffer->current_line;
156 if (vl == NULL || vl->line == NULL)
157 buffer->curs_x = buffer->cpoff = 0;
158 else if (vl->parent->data != NULL)
159 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
160 else
161 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
163 buffer->curs_x += x_offset;
165 if (vl == NULL)
166 return;
168 if (vl->parent->data != NULL)
169 buffer->curs_x += utf8_swidth_between(vl->parent->line, vl->parent->data);
170 else {
171 prfx = line_prefixes[vl->parent->type].prfx1;
172 buffer->curs_x += utf8_swidth(prfx);
176 void
177 global_key_unbound(void)
179 message("%s is undefined", keybuf);
182 static struct vline *
183 nth_line(struct buffer *buffer, size_t n)
185 struct vline *vl;
186 size_t i;
188 i = 0;
189 TAILQ_FOREACH(vl, &buffer->head, vlines) {
190 if (i == n)
191 return vl;
192 i++;
195 /* unreachable */
196 abort();
199 struct buffer *
200 current_buffer(void)
202 if (in_minibuffer)
203 return &ministate.buffer;
204 return &current_tab->buffer;
207 static int
208 readkey(void)
210 uint32_t state = 0;
212 if ((thiskey.key = wgetch(body)) == ERR)
213 return 0;
215 thiskey.meta = thiskey.key == 27;
216 if (thiskey.meta) {
217 thiskey.key = wgetch(body);
218 if (thiskey.key == ERR || thiskey.key == 27) {
219 thiskey.meta = 0;
220 thiskey.key = 27;
224 thiskey.cp = 0;
225 if ((unsigned int)thiskey.key < UINT8_MAX) {
226 while (1) {
227 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
228 break;
229 if ((thiskey.key = wgetch(body)) == ERR) {
230 message("Error decoding user input");
231 return 0;
236 return 1;
239 static void
240 dispatch_stdio(int fd, short ev, void *d)
242 struct keymap *k;
243 const char *keyname;
244 char tmp[5] = {0};
246 /* TODO: schedule a redraw? */
247 if (too_small)
248 return;
250 if (!readkey())
251 return;
253 if (keybuf[0] != '\0')
254 strlcat(keybuf, " ", sizeof(keybuf));
255 if (thiskey.meta)
256 strlcat(keybuf, "M-", sizeof(keybuf));
257 if (thiskey.cp != 0) {
258 utf8_encode(thiskey.cp, tmp);
259 strlcat(keybuf, tmp, sizeof(keybuf));
260 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
261 strlcat(keybuf, keyname, sizeof(keybuf));
262 } else {
263 tmp[0] = thiskey.key;
264 strlcat(keybuf, tmp, sizeof(keybuf));
267 TAILQ_FOREACH(k, &current_map->m, keymaps) {
268 if (k->meta == thiskey.meta &&
269 k->key == thiskey.key) {
270 if (k->fn == NULL)
271 current_map = &k->map;
272 else {
273 current_map = base_map;
274 strlcpy(keybuf, "", sizeof(keybuf));
275 k->fn(current_buffer());
277 goto done;
281 if (current_map->unhandled_input != NULL)
282 current_map->unhandled_input();
283 else
284 global_key_unbound();
286 strlcpy(keybuf, "", sizeof(keybuf));
287 current_map = base_map;
289 done:
290 if (side_window)
291 recompute_help();
293 if (should_rearrange_windows)
294 rearrange_windows();
295 redraw_tab(current_tab);
298 static void
299 handle_clear_echoarea(int fd, short ev, void *d)
301 free(ministate.curmesg);
302 ministate.curmesg = NULL;
304 redraw_minibuffer();
305 place_cursor(0);
308 static void
309 handle_resize(int sig, short ev, void *d)
311 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
312 event_del(&resizeev);
314 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
315 evtimer_add(&resizeev, &resize_timer);
318 static void
319 handle_resize_nodelay(int s, short ev, void *d)
321 endwin();
322 refresh();
323 clear();
325 rearrange_windows();
328 static void
329 rearrange_windows(void)
331 int lines;
333 should_rearrange_windows = 0;
335 lines = LINES;
337 if ((too_small = lines < 15)) {
338 erase();
339 printw("Window too small.");
340 refresh();
341 return;
344 /* move and resize the windows, in reverse order! */
346 if (in_minibuffer == MB_COMPREAD) {
347 mvwin(minibuffer, lines-10, 0);
348 wresize(minibuffer, 10, COLS);
349 lines -= 10;
351 wrap_page(&ministate.compl.buffer, COLS);
354 mvwin(echoarea, --lines, 0);
355 wresize(echoarea, 1, COLS);
357 mvwin(modeline, --lines, 0);
358 wresize(modeline, 1, COLS);
360 body_lines = --lines;
361 body_cols = COLS;
363 if (side_window) {
364 help_cols = 0.3 * COLS;
365 help_lines = lines;
366 mvwin(help, 1, 0);
367 wresize(help, help_lines, help_cols);
369 wrap_page(&helpwin, help_cols);
371 body_cols = COLS - help_cols - 1;
372 mvwin(body, 1, help_cols);
373 } else
374 mvwin(body, 1, 0);
376 update_x_offset();
377 wresize(body, body_lines, body_cols);
379 wresize(tabline, 1, COLS);
381 wrap_page(&current_tab->buffer, body_cols);
382 redraw_tab(current_tab);
385 static int
386 wrap_page(struct buffer *buffer, int width)
388 struct line *l;
389 const struct line *top_orig, *orig;
390 struct vline *vl;
391 int pre_width;
392 const char *prfx;
394 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
395 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
397 buffer->top_line = NULL;
398 buffer->current_line = NULL;
400 buffer->force_redraw = 1;
401 buffer->curs_y = 0;
402 buffer->line_off = 0;
404 empty_vlist(buffer);
406 TAILQ_FOREACH(l, &buffer->page.head, lines) {
407 prfx = line_prefixes[l->type].prfx1;
408 switch (l->type) {
409 case LINE_TEXT:
410 case LINE_LINK:
411 case LINE_TITLE_1:
412 case LINE_TITLE_2:
413 case LINE_TITLE_3:
414 case LINE_ITEM:
415 case LINE_QUOTE:
416 case LINE_PRE_START:
417 case LINE_PRE_END:
418 wrap_text(buffer, prfx, l, MIN(fill_column, width));
419 break;
420 case LINE_PRE_CONTENT:
421 if (olivetti_mode)
422 pre_width = MIN(fill_column, width);
423 else
424 pre_width = width;
425 hardwrap_text(buffer, l, pre_width);
426 break;
427 case LINE_COMPL:
428 case LINE_COMPL_CURRENT:
429 wrap_one(buffer, prfx, l, width);
430 break;
433 if (top_orig == l && buffer->top_line == NULL) {
434 buffer->line_off = buffer->line_max-1;
435 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
437 while (1) {
438 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
439 if (vl == NULL || vl->parent != orig)
440 break;
441 buffer->top_line = vl;
442 buffer->line_off--;
446 if (orig == l && buffer->current_line == NULL) {
447 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
449 while (1) {
450 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
451 if (vl == NULL || vl->parent != orig)
452 break;
453 buffer->current_line = vl;
458 if (buffer->current_line == NULL)
459 buffer->current_line = TAILQ_FIRST(&buffer->head);
461 if (buffer->top_line == NULL)
462 buffer->top_line = buffer->current_line;
464 return 1;
467 static void
468 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
469 const char **prfx_ret, const char **text_ret)
471 int type, i, cont, width;
472 char *space, *t;
474 if ((*text_ret = vl->line) == NULL)
475 *text_ret = "";
477 cont = vl->flags & L_CONTINUATION;
478 type = vl->parent->type;
479 if (!cont)
480 *prfx_ret = line_prefixes[type].prfx1;
481 else
482 *prfx_ret = line_prefixes[type].prfx2;
484 space = vl->parent->data;
485 if (!emojify_link || type != LINE_LINK || space == NULL)
486 return;
488 if (cont) {
489 memset(buf, 0, len);
490 width = utf8_swidth_between(vl->parent->line, space);
491 for (i = 0; i < width + 1; ++i)
492 strlcat(buf, " ", len);
493 } else {
494 strlcpy(buf, *text_ret, len);
495 if ((t = strchr(buf, ' ')) != NULL)
496 *t = '\0';
497 strlcat(buf, " ", len);
499 /* skip the emoji */
500 *text_ret += (space - vl->parent->line) + 1;
503 *prfx_ret = buf;
506 /*
507 * Core part of the rendering. It prints a vline starting from the
508 * current cursor position. Printing a vline consists of skipping
509 * `off' columns (for olivetti-mode), print the correct prefix (which
510 * may be the emoji in case of emojified links-lines), printing the
511 * text itself, filling until width - off and filling off columns
512 * again.
513 */
514 static void
515 print_vline(int off, int width, WINDOW *window, struct vline *vl)
517 /*
518 * Believe me or not, I've seen emoji ten code points long!
519 * That means, to stay large, 4*10 bytes + NUL.
520 */
521 char emojibuf[41] = {0};
522 const char *text, *prfx;
523 struct line_face *f;
524 int i, left, x, y;
526 f = &line_faces[vl->parent->type];
528 /* unused, set by getyx */
529 (void)y;
531 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
533 wattr_on(window, body_face.left, NULL);
534 for (i = 0; i < off; i++)
535 waddch(window, ' ');
536 wattr_off(window, body_face.left, NULL);
538 wattr_on(window, f->prefix, NULL);
539 wprintw(window, "%s", prfx);
540 wattr_off(window, f->prefix, NULL);
542 wattr_on(window, f->text, NULL);
543 wprintw(window, "%s", text);
544 wattr_off(window, f->text, NULL);
546 getyx(window, y, x);
548 left = width - x;
550 wattr_on(window, f->trail, NULL);
551 for (i = 0; i < left - off; ++i)
552 waddch(window, ' ');
553 wattr_off(window, f->trail, NULL);
555 wattr_on(window, body_face.right, NULL);
556 for (i = 0; i < off; i++)
557 waddch(window, ' ');
558 wattr_off(window, body_face.right, NULL);
562 static void
563 redraw_tabline(void)
565 struct tab *tab;
566 size_t toskip, ots, tabwidth, space, x;
567 int current, y, truncated, pair;
568 const char *title;
569 char buf[25];
571 x = 0;
573 /* unused, but setted by a getyx */
574 (void)y;
576 tabwidth = sizeof(buf)+1;
577 space = COLS-2;
579 toskip = 0;
580 TAILQ_FOREACH(tab, &tabshead, tabs) {
581 toskip++;
582 if (tab == current_tab)
583 break;
586 if (toskip * tabwidth < space)
587 toskip = 0;
588 else {
589 ots = toskip;
590 toskip--;
591 while (toskip != 0 &&
592 (ots - toskip+1) * tabwidth < space)
593 toskip--;
596 werase(tabline);
597 wattr_on(tabline, tab_face.background, NULL);
598 wprintw(tabline, toskip == 0 ? " " : "<");
599 wattr_off(tabline, tab_face.background, NULL);
601 truncated = 0;
602 TAILQ_FOREACH(tab, &tabshead, tabs) {
603 if (truncated)
604 break;
605 if (toskip != 0) {
606 toskip--;
607 continue;
610 getyx(tabline, y, x);
611 if (x + sizeof(buf)+2 >= (size_t)COLS)
612 truncated = 1;
614 current = tab == current_tab;
616 if (*(title = tab->buffer.page.title) == '\0')
617 title = tab->hist_cur->h;
619 if (tab->flags & TAB_URGENT)
620 strlcpy(buf, "!", sizeof(buf));
621 else
622 strlcpy(buf, " ", sizeof(buf));
624 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
625 /* truncation happens */
626 strlcpy(&buf[sizeof(buf)-4], "...", 4);
627 } else {
628 /* pad with spaces */
629 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
630 /* nop */ ;
633 pair = current ? tab_face.current : tab_face.tab;
634 wattr_on(tabline, pair, NULL);
635 wprintw(tabline, "%s", buf);
636 wattr_off(tabline, pair, NULL);
638 wattr_on(tabline, tab_face.background, NULL);
639 if (TAILQ_NEXT(tab, tabs) != NULL)
640 wprintw(tabline, "│");
641 wattr_off(tabline, tab_face.background, NULL);
644 wattr_on(tabline, tab_face.background, NULL);
645 for (; x < (size_t)COLS; ++x)
646 waddch(tabline, ' ');
647 if (truncated)
648 mvwprintw(tabline, 0, COLS-1, ">");
649 wattr_off(tabline, tab_face.background, NULL);
652 /*
653 * Compute the first visible line around vl. Try to search forward
654 * until the end of the buffer; if a visible line is not found, search
655 * backward. Return NULL if no viable line was found.
656 */
657 struct vline *
658 adjust_line(struct vline *vl, struct buffer *buffer)
660 struct vline *t;
662 if (vl == NULL)
663 return NULL;
665 if (!(vl->parent->flags & L_HIDDEN))
666 return vl;
668 /* search forward */
669 for (t = vl;
670 t != NULL && t->parent->flags & L_HIDDEN;
671 t = TAILQ_NEXT(t, vlines))
672 ; /* nop */
674 if (t != NULL)
675 return t;
677 /* search backward */
678 for (t = vl;
679 t != NULL && t->parent->flags & L_HIDDEN;
680 t = TAILQ_PREV(t, vhead, vlines))
681 ; /* nop */
683 return t;
686 static void
687 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
689 struct vline *vl;
690 int l, onscreen;
692 restore_curs_x(buffer);
694 /*
695 * TODO: ignoring buffer->force_update and always
696 * re-rendering. In theory we can recompute the y position
697 * without a re-render, and optimize here. It's not the only
698 * optimisation possible here, wscrl wolud also be an
699 * interesting one.
700 */
702 again:
703 werase(win);
704 buffer->curs_y = 0;
706 if (TAILQ_EMPTY(&buffer->head))
707 goto end;
709 if (buffer->top_line == NULL)
710 buffer->top_line = TAILQ_FIRST(&buffer->head);
712 buffer->top_line = adjust_line(buffer->top_line, buffer);
713 if (buffer->top_line == NULL)
714 goto end;
716 buffer->current_line = adjust_line(buffer->current_line, buffer);
718 l = 0;
719 onscreen = 0;
720 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
721 if (vl->parent->flags & L_HIDDEN)
722 continue;
724 wmove(win, l, 0);
725 print_vline(off, width, win, vl);
727 if (vl == buffer->current_line)
728 onscreen = 1;
730 if (!onscreen)
731 buffer->curs_y++;
733 l++;
734 if (l == height)
735 break;
738 if (!onscreen) {
739 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
740 if (vl == buffer->current_line)
741 break;
742 if (vl->parent->flags & L_HIDDEN)
743 continue;
744 buffer->line_off++;
745 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
748 if (vl != NULL)
749 goto again;
752 buffer->last_line_off = buffer->line_off;
753 buffer->force_redraw = 0;
754 end:
755 wmove(win, buffer->curs_y, buffer->curs_x);
758 static void
759 redraw_help(void)
761 redraw_window(help, 0, help_lines, help_cols, &helpwin);
764 static void
765 redraw_body(struct tab *tab)
767 static struct tab *last_tab;
769 if (last_tab != tab)
770 tab->buffer.force_redraw =1;
771 last_tab = tab;
773 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
776 static inline char
777 trust_status_char(enum trust_state ts)
779 switch (ts) {
780 case TS_UNKNOWN: return 'u';
781 case TS_UNTRUSTED: return '!';
782 case TS_TEMP_TRUSTED: return '!';
783 case TS_TRUSTED: return 'v';
784 case TS_VERIFIED: return 'V';
785 default: return 'X';
789 static void
790 redraw_modeline(struct tab *tab)
792 double pct;
793 int x, y, max_x, max_y;
794 const char *mode = tab->buffer.page.name;
795 const char *spin = "-\\|/";
797 werase(modeline);
798 wattr_on(modeline, modeline_face.background, NULL);
799 wmove(modeline, 0, 0);
801 wprintw(modeline, "-%c%c %s ",
802 spin[tab->loading_anim_step],
803 trust_status_char(tab->trust),
804 mode == NULL ? "(none)" : mode);
806 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
807 / tab->buffer.line_max;
809 if (tab->buffer.line_max <= (size_t)body_lines)
810 wprintw(modeline, "All ");
811 else if (tab->buffer.line_off == 0)
812 wprintw(modeline, "Top ");
813 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
814 wprintw(modeline, "Bottom ");
815 else
816 wprintw(modeline, "%.0f%% ", pct);
818 wprintw(modeline, "%d/%d %s ",
819 tab->buffer.line_off + tab->buffer.curs_y,
820 tab->buffer.line_max,
821 tab->hist_cur->h);
823 getyx(modeline, y, x);
824 getmaxyx(modeline, max_y, max_x);
826 (void)y;
827 (void)max_y;
829 for (; x < max_x; ++x)
830 waddstr(modeline, "-");
832 wattr_off(modeline, modeline_face.background, NULL);
835 static void
836 redraw_minibuffer(void)
838 wattr_on(echoarea, minibuffer_face.background, NULL);
839 werase(echoarea);
841 if (in_minibuffer)
842 do_redraw_minibuffer();
843 else
844 do_redraw_echoarea();
846 if (in_minibuffer == MB_COMPREAD)
847 do_redraw_minibuffer_compl();
849 wattr_off(echoarea, minibuffer_face.background, NULL);
852 static void
853 do_redraw_echoarea(void)
855 struct vline *vl;
857 if (ministate.curmesg != NULL)
858 wprintw(echoarea, "%s", ministate.curmesg);
859 else if (*keybuf != '\0')
860 waddstr(echoarea, keybuf);
861 else {
862 /* If nothing else, show the URL at point */
863 vl = current_tab->buffer.current_line;
864 if (vl != NULL && vl->parent->type == LINE_LINK)
865 waddstr(echoarea, vl->parent->alt);
869 static void
870 do_redraw_minibuffer(void)
872 size_t off_y, off_x = 0;
873 const char *start, *c;
875 /* unused, set by getyx */
876 (void)off_y;
878 wmove(echoarea, 0, 0);
880 if (in_minibuffer == MB_COMPREAD)
881 wprintw(echoarea, "(%2d) ",
882 ministate.compl.buffer.line_max);
884 wprintw(echoarea, "%s", ministate.prompt);
885 if (ministate.hist_cur != NULL)
886 wprintw(echoarea, "(%zu/%zu) ",
887 ministate.hist_off + 1,
888 ministate.history->len);
890 getyx(echoarea, off_y, off_x);
892 start = ministate.hist_cur != NULL
893 ? ministate.hist_cur->h
894 : ministate.buf;
895 c = utf8_nth(ministate.buffer.current_line->line,
896 ministate.buffer.cpoff);
897 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
898 start = utf8_next_cp(start);
901 waddstr(echoarea, start);
903 if (ministate.curmesg != NULL)
904 wprintw(echoarea, " [%s]", ministate.curmesg);
906 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
909 static void
910 do_redraw_minibuffer_compl(void)
912 redraw_window(minibuffer, 0, 10, body_cols,
913 &ministate.compl.buffer);
916 /*
917 * Place the cursor in the right ncurses window. If soft is 1, use
918 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
919 * wrefresh.
920 */
921 static void
922 place_cursor(int soft)
924 int (*touch)(WINDOW *);
926 if (soft)
927 touch = wnoutrefresh;
928 else
929 touch = wrefresh;
931 if (in_minibuffer) {
932 touch(body);
933 touch(echoarea);
934 } else {
935 touch(echoarea);
936 touch(body);
940 static void
941 redraw_tab(struct tab *tab)
943 if (too_small)
944 return;
946 if (side_window) {
947 redraw_help();
948 wnoutrefresh(help);
951 redraw_tabline();
952 redraw_body(tab);
953 redraw_modeline(tab);
954 redraw_minibuffer();
956 wnoutrefresh(tabline);
957 wnoutrefresh(modeline);
959 if (in_minibuffer == MB_COMPREAD)
960 wnoutrefresh(minibuffer);
962 place_cursor(1);
964 doupdate();
966 if (set_title)
967 dprintf(1, "\033]0;%s - Telescope\a",
968 current_tab->buffer.page.title);
971 static void
972 emit_help_item(char *prfx, void *fn)
974 struct line *l;
975 struct cmd *cmd;
977 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
978 if (fn == cmd->fn)
979 break;
981 assert(cmd != NULL);
983 if ((l = calloc(1, sizeof(*l))) == NULL)
984 abort();
986 l->type = LINE_TEXT;
987 l->alt = NULL;
989 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
991 if (TAILQ_EMPTY(&helpwin.page.head))
992 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
993 else
994 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
997 static void
998 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1000 struct keymap *k;
1001 char p[32];
1002 const char *kn;
1004 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1005 strlcpy(p, prfx, sizeof(p));
1006 if (*p != '\0')
1007 strlcat(p, " ", sizeof(p));
1008 if (k->meta)
1009 strlcat(p, "M-", sizeof(p));
1010 if ((kn = unkbd(k->key)) != NULL)
1011 strlcat(p, kn, sizeof(p));
1012 else
1013 strlcat(p, keyname(k->key), sizeof(p));
1015 if (k->fn == NULL)
1016 rec_compute_help(&k->map, p, sizeof(p));
1017 else
1018 emit_help_item(p, k->fn);
1022 static void
1023 recompute_help(void)
1025 char p[32] = { 0 };
1027 empty_vlist(&helpwin);
1028 empty_linelist(&helpwin);
1029 rec_compute_help(current_map, p, sizeof(p));
1030 wrap_page(&helpwin, help_cols);
1033 void
1034 vmessage(const char *fmt, va_list ap)
1036 if (evtimer_pending(&clechoev, NULL))
1037 evtimer_del(&clechoev);
1039 free(ministate.curmesg);
1040 ministate.curmesg = NULL;
1042 if (fmt != NULL) {
1043 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1044 evtimer_add(&clechoev, &clechoev_timer);
1046 /* TODO: what to do if the allocation fails here? */
1047 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1048 ministate.curmesg = NULL;
1051 redraw_minibuffer();
1052 place_cursor(0);
1055 void
1056 message(const char *fmt, ...)
1058 va_list ap;
1060 va_start(ap, fmt);
1061 vmessage(fmt, ap);
1062 va_end(ap);
1065 void
1066 start_loading_anim(struct tab *tab)
1068 if (tab->loading_anim)
1069 return;
1070 tab->loading_anim = 1;
1071 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1072 evtimer_add(&tab->loadingev, &loadingev_timer);
1075 static void
1076 update_loading_anim(int fd, short ev, void *d)
1078 struct tab *tab = d;
1080 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1082 if (tab == current_tab) {
1083 redraw_modeline(tab);
1084 wrefresh(modeline);
1085 wrefresh(body);
1086 if (in_minibuffer)
1087 wrefresh(echoarea);
1090 evtimer_add(&tab->loadingev, &loadingev_timer);
1093 static void
1094 stop_loading_anim(struct tab *tab)
1096 if (!tab->loading_anim)
1097 return;
1098 evtimer_del(&tab->loadingev);
1099 tab->loading_anim = 0;
1100 tab->loading_anim_step = 0;
1102 if (tab != current_tab)
1103 return;
1105 redraw_modeline(tab);
1107 wrefresh(modeline);
1108 wrefresh(body);
1109 if (in_minibuffer)
1110 wrefresh(echoarea);
1113 void
1114 load_url_in_tab(struct tab *tab, const char *url)
1116 if (!operating) {
1117 load_url(tab, url);
1118 return;
1121 message("Loading %s...", url);
1122 start_loading_anim(tab);
1123 load_url(tab, url);
1125 redraw_tab(tab);
1128 void
1129 switch_to_tab(struct tab *tab)
1131 current_tab = tab;
1132 tab->flags &= ~TAB_URGENT;
1134 if (operating && tab->flags & TAB_LAZY)
1135 load_url_in_tab(tab, tab->hist_cur->h);
1138 unsigned int
1139 tab_new_id(void)
1141 return tab_counter++;
1144 struct tab *
1145 new_tab(const char *url)
1147 struct tab *tab;
1149 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1150 event_loopbreak();
1151 return NULL;
1153 tab->fd = -1;
1155 TAILQ_INIT(&tab->hist.head);
1157 TAILQ_INIT(&tab->buffer.head);
1159 tab->id = tab_new_id();
1160 if (!operating)
1161 tab->flags |= TAB_LAZY;
1162 switch_to_tab(tab);
1164 if (TAILQ_EMPTY(&tabshead))
1165 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1166 else
1167 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1169 load_url_in_tab(tab, url);
1170 return tab;
1173 int
1174 ui_print_colors(void)
1176 int colors = 0, pairs = 0, can_change = 0;
1177 int columns = 16, lines, color, i, j;
1179 initscr();
1180 if (has_colors()) {
1181 start_color();
1182 use_default_colors();
1184 colors = COLORS;
1185 pairs = COLOR_PAIRS;
1186 can_change = can_change_color();
1188 endwin();
1190 printf("Term info:\n");
1191 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1192 getenv("TERM"), colors, pairs, can_change);
1193 printf("\n");
1195 if (colors == 0) {
1196 printf("No color support\n");
1197 return 0;
1200 printf("Available colors:\n\n");
1201 lines = (colors - 1) / columns + 1;
1202 color = 0;
1203 for (i = 0; i < lines; ++i) {
1204 for (j = 0; j < columns; ++j, ++color) {
1205 printf("\033[0;38;5;%dm %03d", color, color);
1207 printf("\n");
1210 printf("\033[0m");
1211 fflush(stdout);
1212 return 0;
1215 int
1216 ui_init()
1218 setlocale(LC_ALL, "");
1220 TAILQ_INIT(&eecmd_history.head);
1221 TAILQ_INIT(&ir_history.head);
1222 TAILQ_INIT(&lu_history.head);
1224 ministate.line.type = LINE_TEXT;
1225 ministate.vline.parent = &ministate.line;
1226 ministate.buffer.current_line = &ministate.vline;
1228 /* initialize help window */
1229 TAILQ_INIT(&helpwin.head);
1231 base_map = &global_map;
1232 current_map = &global_map;
1234 initscr();
1236 if (enable_colors) {
1237 if (has_colors()) {
1238 start_color();
1239 use_default_colors();
1240 } else
1241 enable_colors = 0;
1244 config_apply_style();
1246 raw();
1247 noecho();
1248 nonl();
1249 intrflush(stdscr, FALSE);
1251 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1252 return 0;
1253 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1254 return 0;
1255 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1256 return 0;
1257 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1258 return 0;
1259 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1260 return 0;
1261 if ((help = newwin(1, 1, 1, 0)) == NULL)
1262 return 0;
1264 body_lines = LINES-3;
1265 body_cols = COLS;
1267 wbkgd(body, body_face.body);
1268 wbkgd(echoarea, minibuffer_face.background);
1270 update_x_offset();
1272 keypad(body, TRUE);
1273 scrollok(body, FALSE);
1275 /* non-blocking input */
1276 wtimeout(body, 0);
1278 mvwprintw(body, 0, 0, "");
1281 * Dummy so libevent2 won't complain that no event_base is set
1282 * when checking event_pending for the first time
1284 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1285 evtimer_add(&clechoev, &clechoev_timer);
1286 evtimer_set(&resizeev, handle_resize, NULL);
1287 evtimer_add(&resizeev, &resize_timer);
1289 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1290 event_add(&stdioev, NULL);
1292 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1293 signal_add(&winchev, NULL);
1295 return 1;
1298 void
1299 ui_main_loop(void)
1301 operating = 1;
1302 switch_to_tab(current_tab);
1303 redraw_tab(current_tab);
1305 event_dispatch();
1308 void
1309 ui_on_tab_loaded(struct tab *tab)
1311 stop_loading_anim(tab);
1312 message("Loaded %s", tab->hist_cur->h);
1314 redraw_tabline();
1315 wrefresh(tabline);
1316 place_cursor(0);
1319 void
1320 ui_on_tab_refresh(struct tab *tab)
1322 wrap_page(&tab->buffer, body_cols);
1323 if (tab == current_tab)
1324 redraw_tab(tab);
1325 else
1326 tab->flags |= TAB_URGENT;
1329 const char *
1330 ui_keyname(int k)
1332 return keyname(k);
1335 void
1336 ui_toggle_side_window(void)
1338 side_window = !side_window;
1339 if (side_window)
1340 recompute_help();
1343 * ugly hack, but otherwise the window doesn't get updated
1344 * until I call rearrange_windows a second time (e.g. via
1345 * C-l). I will be happy to know why something like this is
1346 * needed.
1348 rearrange_windows();
1349 rearrange_windows();
1352 void
1353 ui_schedule_redraw(void)
1355 should_rearrange_windows = 1;
1358 void
1359 ui_require_input(struct tab *tab, int hide)
1361 /* TODO: hard-switching to another tab is ugly */
1362 switch_to_tab(tab);
1364 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1365 &ir_history, NULL, NULL);
1366 strlcpy(ministate.prompt, "Input required: ",
1367 sizeof(ministate.prompt));
1368 redraw_tab(tab);
1371 void
1372 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1373 struct tab *data)
1375 yornp(prompt, fn, data);
1376 redraw_tab(current_tab);
1379 void
1380 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1381 struct tab *data)
1383 completing_read(prompt, fn, data);
1384 redraw_tab(current_tab);
1387 void
1388 ui_suspend(void)
1390 endwin();
1392 kill(getpid(), SIGSTOP);
1394 refresh();
1395 clear();
1396 rearrange_windows();
1399 void
1400 ui_end(void)
1402 endwin();