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 struct buffer *
183 current_buffer(void)
185 if (in_minibuffer)
186 return &ministate.buffer;
187 return &current_tab->buffer;
190 static int
191 readkey(void)
193 uint32_t state = 0;
195 if ((thiskey.key = wgetch(body)) == ERR)
196 return 0;
198 thiskey.meta = thiskey.key == 27;
199 if (thiskey.meta) {
200 thiskey.key = wgetch(body);
201 if (thiskey.key == ERR || thiskey.key == 27) {
202 thiskey.meta = 0;
203 thiskey.key = 27;
207 thiskey.cp = 0;
208 if ((unsigned int)thiskey.key < UINT8_MAX) {
209 while (1) {
210 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
211 break;
212 if ((thiskey.key = wgetch(body)) == ERR) {
213 message("Error decoding user input");
214 return 0;
219 return 1;
222 static void
223 dispatch_stdio(int fd, short ev, void *d)
225 struct keymap *k;
226 const char *keyname;
227 char tmp[5] = {0};
229 /* TODO: schedule a redraw? */
230 if (too_small)
231 return;
233 if (!readkey())
234 return;
236 if (keybuf[0] != '\0')
237 strlcat(keybuf, " ", sizeof(keybuf));
238 if (thiskey.meta)
239 strlcat(keybuf, "M-", sizeof(keybuf));
240 if (thiskey.cp != 0) {
241 utf8_encode(thiskey.cp, tmp);
242 strlcat(keybuf, tmp, sizeof(keybuf));
243 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
244 strlcat(keybuf, keyname, sizeof(keybuf));
245 } else {
246 tmp[0] = thiskey.key;
247 strlcat(keybuf, tmp, sizeof(keybuf));
250 TAILQ_FOREACH(k, &current_map->m, keymaps) {
251 if (k->meta == thiskey.meta &&
252 k->key == thiskey.key) {
253 if (k->fn == NULL)
254 current_map = &k->map;
255 else {
256 current_map = base_map;
257 strlcpy(keybuf, "", sizeof(keybuf));
258 k->fn(current_buffer());
260 goto done;
264 if (current_map->unhandled_input != NULL)
265 current_map->unhandled_input();
266 else
267 global_key_unbound();
269 strlcpy(keybuf, "", sizeof(keybuf));
270 current_map = base_map;
272 done:
273 if (side_window)
274 recompute_help();
276 if (should_rearrange_windows)
277 rearrange_windows();
278 redraw_tab(current_tab);
281 static void
282 handle_clear_echoarea(int fd, short ev, void *d)
284 free(ministate.curmesg);
285 ministate.curmesg = NULL;
287 redraw_minibuffer();
288 place_cursor(0);
291 static void
292 handle_resize(int sig, short ev, void *d)
294 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
295 event_del(&resizeev);
297 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
298 evtimer_add(&resizeev, &resize_timer);
301 static void
302 handle_resize_nodelay(int s, short ev, void *d)
304 endwin();
305 refresh();
306 clear();
308 rearrange_windows();
311 static void
312 rearrange_windows(void)
314 int lines;
316 should_rearrange_windows = 0;
318 lines = LINES;
320 if ((too_small = lines < 15)) {
321 erase();
322 printw("Window too small.");
323 refresh();
324 return;
327 /* move and resize the windows, in reverse order! */
329 if (in_minibuffer == MB_COMPREAD) {
330 mvwin(minibuffer, lines-10, 0);
331 wresize(minibuffer, 10, COLS);
332 lines -= 10;
334 wrap_page(&ministate.compl.buffer, COLS);
337 mvwin(echoarea, --lines, 0);
338 wresize(echoarea, 1, COLS);
340 mvwin(modeline, --lines, 0);
341 wresize(modeline, 1, COLS);
343 body_lines = --lines;
344 body_cols = COLS;
346 if (side_window) {
347 help_cols = 0.3 * COLS;
348 help_lines = lines;
349 mvwin(help, 1, 0);
350 wresize(help, help_lines, help_cols);
352 wrap_page(&helpwin, help_cols);
354 body_cols = COLS - help_cols - 1;
355 mvwin(body, 1, help_cols);
356 } else
357 mvwin(body, 1, 0);
359 update_x_offset();
360 wresize(body, body_lines, body_cols);
362 wresize(tabline, 1, COLS);
364 wrap_page(&current_tab->buffer, body_cols);
365 redraw_tab(current_tab);
368 static int
369 wrap_page(struct buffer *buffer, int width)
371 struct line *l;
372 const struct line *top_orig, *orig;
373 struct vline *vl;
374 int pre_width;
375 const char *prfx;
377 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
378 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
380 buffer->top_line = NULL;
381 buffer->current_line = NULL;
383 buffer->force_redraw = 1;
384 buffer->curs_y = 0;
385 buffer->line_off = 0;
387 empty_vlist(buffer);
389 TAILQ_FOREACH(l, &buffer->page.head, lines) {
390 prfx = line_prefixes[l->type].prfx1;
391 switch (l->type) {
392 case LINE_TEXT:
393 case LINE_LINK:
394 case LINE_TITLE_1:
395 case LINE_TITLE_2:
396 case LINE_TITLE_3:
397 case LINE_ITEM:
398 case LINE_QUOTE:
399 case LINE_PRE_START:
400 case LINE_PRE_END:
401 wrap_text(buffer, prfx, l, MIN(fill_column, width));
402 break;
403 case LINE_PRE_CONTENT:
404 if (olivetti_mode)
405 pre_width = MIN(fill_column, width);
406 else
407 pre_width = width;
408 hardwrap_text(buffer, l, pre_width);
409 break;
410 case LINE_COMPL:
411 case LINE_COMPL_CURRENT:
412 wrap_one(buffer, prfx, l, width);
413 break;
416 if (top_orig == l && buffer->top_line == NULL) {
417 buffer->line_off = buffer->line_max-1;
418 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
420 while (1) {
421 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
422 if (vl == NULL || vl->parent != orig)
423 break;
424 buffer->top_line = vl;
425 buffer->line_off--;
429 if (orig == l && buffer->current_line == NULL) {
430 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
432 while (1) {
433 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
434 if (vl == NULL || vl->parent != orig)
435 break;
436 buffer->current_line = vl;
441 if (buffer->current_line == NULL)
442 buffer->current_line = TAILQ_FIRST(&buffer->head);
444 if (buffer->top_line == NULL)
445 buffer->top_line = buffer->current_line;
447 return 1;
450 static void
451 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
452 const char **prfx_ret, const char **text_ret)
454 int type, i, cont, width;
455 char *space, *t;
457 if ((*text_ret = vl->line) == NULL)
458 *text_ret = "";
460 cont = vl->flags & L_CONTINUATION;
461 type = vl->parent->type;
462 if (!cont)
463 *prfx_ret = line_prefixes[type].prfx1;
464 else
465 *prfx_ret = line_prefixes[type].prfx2;
467 space = vl->parent->data;
468 if (!emojify_link || type != LINE_LINK || space == NULL)
469 return;
471 if (cont) {
472 memset(buf, 0, len);
473 width = utf8_swidth_between(vl->parent->line, space);
474 for (i = 0; i < width + 1; ++i)
475 strlcat(buf, " ", len);
476 } else {
477 strlcpy(buf, *text_ret, len);
478 if ((t = strchr(buf, ' ')) != NULL)
479 *t = '\0';
480 strlcat(buf, " ", len);
482 /* skip the emoji */
483 *text_ret += (space - vl->parent->line) + 1;
486 *prfx_ret = buf;
489 /*
490 * Core part of the rendering. It prints a vline starting from the
491 * current cursor position. Printing a vline consists of skipping
492 * `off' columns (for olivetti-mode), print the correct prefix (which
493 * may be the emoji in case of emojified links-lines), printing the
494 * text itself, filling until width - off and filling off columns
495 * again.
496 */
497 static void
498 print_vline(int off, int width, WINDOW *window, struct vline *vl)
500 /*
501 * Believe me or not, I've seen emoji ten code points long!
502 * That means, to stay large, 4*10 bytes + NUL.
503 */
504 char emojibuf[41] = {0};
505 const char *text, *prfx;
506 struct line_face *f;
507 int i, left, x, y;
509 f = &line_faces[vl->parent->type];
511 /* unused, set by getyx */
512 (void)y;
514 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
516 wattr_on(window, body_face.left, NULL);
517 for (i = 0; i < off; i++)
518 waddch(window, ' ');
519 wattr_off(window, body_face.left, NULL);
521 wattr_on(window, f->prefix, NULL);
522 wprintw(window, "%s", prfx);
523 wattr_off(window, f->prefix, NULL);
525 wattr_on(window, f->text, NULL);
526 wprintw(window, "%s", text);
527 wattr_off(window, f->text, NULL);
529 getyx(window, y, x);
531 left = width - x;
533 wattr_on(window, f->trail, NULL);
534 for (i = 0; i < left - off; ++i)
535 waddch(window, ' ');
536 wattr_off(window, f->trail, NULL);
538 wattr_on(window, body_face.right, NULL);
539 for (i = 0; i < off; i++)
540 waddch(window, ' ');
541 wattr_off(window, body_face.right, NULL);
545 static void
546 redraw_tabline(void)
548 struct tab *tab;
549 size_t toskip, ots, tabwidth, space, x;
550 int current, y, truncated, pair;
551 const char *title;
552 char buf[25];
554 x = 0;
556 /* unused, but setted by a getyx */
557 (void)y;
559 tabwidth = sizeof(buf)+1;
560 space = COLS-2;
562 toskip = 0;
563 TAILQ_FOREACH(tab, &tabshead, tabs) {
564 toskip++;
565 if (tab == current_tab)
566 break;
569 if (toskip * tabwidth < space)
570 toskip = 0;
571 else {
572 ots = toskip;
573 toskip--;
574 while (toskip != 0 &&
575 (ots - toskip+1) * tabwidth < space)
576 toskip--;
579 werase(tabline);
580 wattr_on(tabline, tab_face.background, NULL);
581 wprintw(tabline, toskip == 0 ? " " : "<");
582 wattr_off(tabline, tab_face.background, NULL);
584 truncated = 0;
585 TAILQ_FOREACH(tab, &tabshead, tabs) {
586 if (truncated)
587 break;
588 if (toskip != 0) {
589 toskip--;
590 continue;
593 getyx(tabline, y, x);
594 if (x + sizeof(buf)+2 >= (size_t)COLS)
595 truncated = 1;
597 current = tab == current_tab;
599 if (*(title = tab->buffer.page.title) == '\0')
600 title = tab->hist_cur->h;
602 if (tab->flags & TAB_URGENT)
603 strlcpy(buf, "!", sizeof(buf));
604 else
605 strlcpy(buf, " ", sizeof(buf));
607 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
608 /* truncation happens */
609 strlcpy(&buf[sizeof(buf)-4], "...", 4);
610 } else {
611 /* pad with spaces */
612 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
613 /* nop */ ;
616 pair = current ? tab_face.current : tab_face.tab;
617 wattr_on(tabline, pair, NULL);
618 wprintw(tabline, "%s", buf);
619 wattr_off(tabline, pair, NULL);
621 wattr_on(tabline, tab_face.background, NULL);
622 if (TAILQ_NEXT(tab, tabs) != NULL)
623 wprintw(tabline, "│");
624 wattr_off(tabline, tab_face.background, NULL);
627 wattr_on(tabline, tab_face.background, NULL);
628 for (; x < (size_t)COLS; ++x)
629 waddch(tabline, ' ');
630 if (truncated)
631 mvwprintw(tabline, 0, COLS-1, ">");
632 wattr_off(tabline, tab_face.background, NULL);
635 /*
636 * Compute the first visible line around vl. Try to search forward
637 * until the end of the buffer; if a visible line is not found, search
638 * backward. Return NULL if no viable line was found.
639 */
640 struct vline *
641 adjust_line(struct vline *vl, struct buffer *buffer)
643 struct vline *t;
645 if (vl == NULL)
646 return NULL;
648 if (!(vl->parent->flags & L_HIDDEN))
649 return vl;
651 /* search forward */
652 for (t = vl;
653 t != NULL && t->parent->flags & L_HIDDEN;
654 t = TAILQ_NEXT(t, vlines))
655 ; /* nop */
657 if (t != NULL)
658 return t;
660 /* search backward */
661 for (t = vl;
662 t != NULL && t->parent->flags & L_HIDDEN;
663 t = TAILQ_PREV(t, vhead, vlines))
664 ; /* nop */
666 return t;
669 static void
670 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
672 struct vline *vl;
673 int l, onscreen;
675 restore_curs_x(buffer);
677 /*
678 * TODO: ignoring buffer->force_update and always
679 * re-rendering. In theory we can recompute the y position
680 * without a re-render, and optimize here. It's not the only
681 * optimisation possible here, wscrl wolud also be an
682 * interesting one.
683 */
685 again:
686 werase(win);
687 buffer->curs_y = 0;
689 if (TAILQ_EMPTY(&buffer->head))
690 goto end;
692 if (buffer->top_line == NULL)
693 buffer->top_line = TAILQ_FIRST(&buffer->head);
695 buffer->top_line = adjust_line(buffer->top_line, buffer);
696 if (buffer->top_line == NULL)
697 goto end;
699 buffer->current_line = adjust_line(buffer->current_line, buffer);
701 l = 0;
702 onscreen = 0;
703 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
704 if (vl->parent->flags & L_HIDDEN)
705 continue;
707 wmove(win, l, 0);
708 print_vline(off, width, win, vl);
710 if (vl == buffer->current_line)
711 onscreen = 1;
713 if (!onscreen)
714 buffer->curs_y++;
716 l++;
717 if (l == height)
718 break;
721 if (!onscreen) {
722 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
723 if (vl == buffer->current_line)
724 break;
725 if (vl->parent->flags & L_HIDDEN)
726 continue;
727 buffer->line_off++;
728 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
731 if (vl != NULL)
732 goto again;
735 buffer->last_line_off = buffer->line_off;
736 buffer->force_redraw = 0;
737 end:
738 wmove(win, buffer->curs_y, buffer->curs_x);
741 static void
742 redraw_help(void)
744 redraw_window(help, 0, help_lines, help_cols, &helpwin);
747 static void
748 redraw_body(struct tab *tab)
750 static struct tab *last_tab;
752 if (last_tab != tab)
753 tab->buffer.force_redraw =1;
754 last_tab = tab;
756 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
759 static inline char
760 trust_status_char(enum trust_state ts)
762 switch (ts) {
763 case TS_UNKNOWN: return 'u';
764 case TS_UNTRUSTED: return '!';
765 case TS_TEMP_TRUSTED: return '!';
766 case TS_TRUSTED: return 'v';
767 case TS_VERIFIED: return 'V';
768 default: return 'X';
772 static void
773 redraw_modeline(struct tab *tab)
775 double pct;
776 int x, y, max_x, max_y;
777 const char *mode = tab->buffer.page.name;
778 const char *spin = "-\\|/";
780 werase(modeline);
781 wattr_on(modeline, modeline_face.background, NULL);
782 wmove(modeline, 0, 0);
784 wprintw(modeline, "-%c%c %s ",
785 spin[tab->loading_anim_step],
786 trust_status_char(tab->trust),
787 mode == NULL ? "(none)" : mode);
789 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
790 / tab->buffer.line_max;
792 if (tab->buffer.line_max <= (size_t)body_lines)
793 wprintw(modeline, "All ");
794 else if (tab->buffer.line_off == 0)
795 wprintw(modeline, "Top ");
796 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
797 wprintw(modeline, "Bottom ");
798 else
799 wprintw(modeline, "%.0f%% ", pct);
801 wprintw(modeline, "%d/%d %s ",
802 tab->buffer.line_off + tab->buffer.curs_y,
803 tab->buffer.line_max,
804 tab->hist_cur->h);
806 getyx(modeline, y, x);
807 getmaxyx(modeline, max_y, max_x);
809 (void)y;
810 (void)max_y;
812 for (; x < max_x; ++x)
813 waddstr(modeline, "-");
815 wattr_off(modeline, modeline_face.background, NULL);
818 static void
819 redraw_minibuffer(void)
821 wattr_on(echoarea, minibuffer_face.background, NULL);
822 werase(echoarea);
824 if (in_minibuffer)
825 do_redraw_minibuffer();
826 else
827 do_redraw_echoarea();
829 if (in_minibuffer == MB_COMPREAD)
830 do_redraw_minibuffer_compl();
832 wattr_off(echoarea, minibuffer_face.background, NULL);
835 static void
836 do_redraw_echoarea(void)
838 struct vline *vl;
840 if (ministate.curmesg != NULL)
841 wprintw(echoarea, "%s", ministate.curmesg);
842 else if (*keybuf != '\0')
843 waddstr(echoarea, keybuf);
844 else {
845 /* If nothing else, show the URL at point */
846 vl = current_tab->buffer.current_line;
847 if (vl != NULL && vl->parent->type == LINE_LINK)
848 waddstr(echoarea, vl->parent->alt);
852 static void
853 do_redraw_minibuffer(void)
855 size_t off_y, off_x = 0;
856 const char *start, *c;
858 /* unused, set by getyx */
859 (void)off_y;
861 wmove(echoarea, 0, 0);
863 if (in_minibuffer == MB_COMPREAD)
864 wprintw(echoarea, "(%2d) ",
865 ministate.compl.buffer.line_max);
867 wprintw(echoarea, "%s", ministate.prompt);
868 if (ministate.hist_cur != NULL)
869 wprintw(echoarea, "(%zu/%zu) ",
870 ministate.hist_off + 1,
871 ministate.history->len);
873 getyx(echoarea, off_y, off_x);
875 start = ministate.hist_cur != NULL
876 ? ministate.hist_cur->h
877 : ministate.buf;
878 c = utf8_nth(ministate.buffer.current_line->line,
879 ministate.buffer.cpoff);
880 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
881 start = utf8_next_cp(start);
884 waddstr(echoarea, start);
886 if (ministate.curmesg != NULL)
887 wprintw(echoarea, " [%s]", ministate.curmesg);
889 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
892 static void
893 do_redraw_minibuffer_compl(void)
895 redraw_window(minibuffer, 0, 10, body_cols,
896 &ministate.compl.buffer);
899 /*
900 * Place the cursor in the right ncurses window. If soft is 1, use
901 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
902 * wrefresh.
903 */
904 static void
905 place_cursor(int soft)
907 int (*touch)(WINDOW *);
909 if (soft)
910 touch = wnoutrefresh;
911 else
912 touch = wrefresh;
914 if (in_minibuffer) {
915 touch(body);
916 touch(echoarea);
917 } else {
918 touch(echoarea);
919 touch(body);
923 static void
924 redraw_tab(struct tab *tab)
926 if (too_small)
927 return;
929 if (side_window) {
930 redraw_help();
931 wnoutrefresh(help);
934 redraw_tabline();
935 redraw_body(tab);
936 redraw_modeline(tab);
937 redraw_minibuffer();
939 wnoutrefresh(tabline);
940 wnoutrefresh(modeline);
942 if (in_minibuffer == MB_COMPREAD)
943 wnoutrefresh(minibuffer);
945 place_cursor(1);
947 doupdate();
949 if (set_title)
950 dprintf(1, "\033]0;%s - Telescope\a",
951 current_tab->buffer.page.title);
954 static void
955 emit_help_item(char *prfx, void *fn)
957 struct line *l;
958 struct cmd *cmd;
960 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
961 if (fn == cmd->fn)
962 break;
964 assert(cmd != NULL);
966 if ((l = calloc(1, sizeof(*l))) == NULL)
967 abort();
969 l->type = LINE_TEXT;
970 l->alt = NULL;
972 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
974 if (TAILQ_EMPTY(&helpwin.page.head))
975 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
976 else
977 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
980 static void
981 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
983 struct keymap *k;
984 char p[32];
985 const char *kn;
987 TAILQ_FOREACH(k, &keymap->m, keymaps) {
988 strlcpy(p, prfx, sizeof(p));
989 if (*p != '\0')
990 strlcat(p, " ", sizeof(p));
991 if (k->meta)
992 strlcat(p, "M-", sizeof(p));
993 if ((kn = unkbd(k->key)) != NULL)
994 strlcat(p, kn, sizeof(p));
995 else
996 strlcat(p, keyname(k->key), sizeof(p));
998 if (k->fn == NULL)
999 rec_compute_help(&k->map, p, sizeof(p));
1000 else
1001 emit_help_item(p, k->fn);
1005 static void
1006 recompute_help(void)
1008 char p[32] = { 0 };
1010 empty_vlist(&helpwin);
1011 empty_linelist(&helpwin);
1012 rec_compute_help(current_map, p, sizeof(p));
1013 wrap_page(&helpwin, help_cols);
1016 void
1017 vmessage(const char *fmt, va_list ap)
1019 if (evtimer_pending(&clechoev, NULL))
1020 evtimer_del(&clechoev);
1022 free(ministate.curmesg);
1023 ministate.curmesg = NULL;
1025 if (fmt != NULL) {
1026 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1027 evtimer_add(&clechoev, &clechoev_timer);
1029 /* TODO: what to do if the allocation fails here? */
1030 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1031 ministate.curmesg = NULL;
1034 redraw_minibuffer();
1035 place_cursor(0);
1038 void
1039 message(const char *fmt, ...)
1041 va_list ap;
1043 va_start(ap, fmt);
1044 vmessage(fmt, ap);
1045 va_end(ap);
1048 void
1049 start_loading_anim(struct tab *tab)
1051 if (tab->loading_anim)
1052 return;
1053 tab->loading_anim = 1;
1054 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1055 evtimer_add(&tab->loadingev, &loadingev_timer);
1058 static void
1059 update_loading_anim(int fd, short ev, void *d)
1061 struct tab *tab = d;
1063 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1065 if (tab == current_tab) {
1066 redraw_modeline(tab);
1067 wrefresh(modeline);
1068 wrefresh(body);
1069 if (in_minibuffer)
1070 wrefresh(echoarea);
1073 evtimer_add(&tab->loadingev, &loadingev_timer);
1076 static void
1077 stop_loading_anim(struct tab *tab)
1079 if (!tab->loading_anim)
1080 return;
1081 evtimer_del(&tab->loadingev);
1082 tab->loading_anim = 0;
1083 tab->loading_anim_step = 0;
1085 if (tab != current_tab)
1086 return;
1088 redraw_modeline(tab);
1090 wrefresh(modeline);
1091 wrefresh(body);
1092 if (in_minibuffer)
1093 wrefresh(echoarea);
1096 void
1097 load_url_in_tab(struct tab *tab, const char *url)
1099 if (!operating) {
1100 load_url(tab, url);
1101 return;
1104 message("Loading %s...", url);
1105 start_loading_anim(tab);
1106 load_url(tab, url);
1108 redraw_tab(tab);
1111 void
1112 switch_to_tab(struct tab *tab)
1114 current_tab = tab;
1115 tab->flags &= ~TAB_URGENT;
1117 if (operating && tab->flags & TAB_LAZY)
1118 load_url_in_tab(tab, tab->hist_cur->h);
1121 unsigned int
1122 tab_new_id(void)
1124 return tab_counter++;
1127 struct tab *
1128 new_tab(const char *url)
1130 struct tab *tab;
1132 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1133 event_loopbreak();
1134 return NULL;
1136 tab->fd = -1;
1138 TAILQ_INIT(&tab->hist.head);
1140 TAILQ_INIT(&tab->buffer.head);
1142 tab->id = tab_new_id();
1143 if (!operating)
1144 tab->flags |= TAB_LAZY;
1145 switch_to_tab(tab);
1147 if (TAILQ_EMPTY(&tabshead))
1148 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1149 else
1150 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1152 load_url_in_tab(tab, url);
1153 return tab;
1156 int
1157 ui_print_colors(void)
1159 int colors = 0, pairs = 0, can_change = 0;
1160 int columns = 16, lines, color, i, j;
1162 initscr();
1163 if (has_colors()) {
1164 start_color();
1165 use_default_colors();
1167 colors = COLORS;
1168 pairs = COLOR_PAIRS;
1169 can_change = can_change_color();
1171 endwin();
1173 printf("Term info:\n");
1174 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1175 getenv("TERM"), colors, pairs, can_change);
1176 printf("\n");
1178 if (colors == 0) {
1179 printf("No color support\n");
1180 return 0;
1183 printf("Available colors:\n\n");
1184 lines = (colors - 1) / columns + 1;
1185 color = 0;
1186 for (i = 0; i < lines; ++i) {
1187 for (j = 0; j < columns; ++j, ++color) {
1188 printf("\033[0;38;5;%dm %03d", color, color);
1190 printf("\n");
1193 printf("\033[0m");
1194 fflush(stdout);
1195 return 0;
1198 int
1199 ui_init()
1201 setlocale(LC_ALL, "");
1203 TAILQ_INIT(&eecmd_history.head);
1204 TAILQ_INIT(&ir_history.head);
1205 TAILQ_INIT(&lu_history.head);
1207 ministate.line.type = LINE_TEXT;
1208 ministate.vline.parent = &ministate.line;
1209 ministate.buffer.current_line = &ministate.vline;
1211 /* initialize help window */
1212 TAILQ_INIT(&helpwin.head);
1214 base_map = &global_map;
1215 current_map = &global_map;
1217 initscr();
1219 if (enable_colors) {
1220 if (has_colors()) {
1221 start_color();
1222 use_default_colors();
1223 } else
1224 enable_colors = 0;
1227 config_apply_style();
1229 raw();
1230 noecho();
1231 nonl();
1232 intrflush(stdscr, FALSE);
1234 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1235 return 0;
1236 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1237 return 0;
1238 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1239 return 0;
1240 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1241 return 0;
1242 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1243 return 0;
1244 if ((help = newwin(1, 1, 1, 0)) == NULL)
1245 return 0;
1247 body_lines = LINES-3;
1248 body_cols = COLS;
1250 wbkgd(body, body_face.body);
1251 wbkgd(echoarea, minibuffer_face.background);
1253 update_x_offset();
1255 keypad(body, TRUE);
1256 scrollok(body, FALSE);
1258 /* non-blocking input */
1259 wtimeout(body, 0);
1261 mvwprintw(body, 0, 0, "");
1264 * Dummy so libevent2 won't complain that no event_base is set
1265 * when checking event_pending for the first time
1267 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1268 evtimer_add(&clechoev, &clechoev_timer);
1269 evtimer_set(&resizeev, handle_resize, NULL);
1270 evtimer_add(&resizeev, &resize_timer);
1272 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1273 event_add(&stdioev, NULL);
1275 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1276 signal_add(&winchev, NULL);
1278 return 1;
1281 void
1282 ui_main_loop(void)
1284 operating = 1;
1285 switch_to_tab(current_tab);
1286 redraw_tab(current_tab);
1288 event_dispatch();
1291 void
1292 ui_on_tab_loaded(struct tab *tab)
1294 stop_loading_anim(tab);
1295 message("Loaded %s", tab->hist_cur->h);
1297 redraw_tabline();
1298 wrefresh(tabline);
1299 place_cursor(0);
1302 void
1303 ui_on_tab_refresh(struct tab *tab)
1305 wrap_page(&tab->buffer, body_cols);
1306 if (tab == current_tab)
1307 redraw_tab(tab);
1308 else
1309 tab->flags |= TAB_URGENT;
1312 const char *
1313 ui_keyname(int k)
1315 return keyname(k);
1318 void
1319 ui_toggle_side_window(void)
1321 side_window = !side_window;
1322 if (side_window)
1323 recompute_help();
1326 * ugly hack, but otherwise the window doesn't get updated
1327 * until I call rearrange_windows a second time (e.g. via
1328 * C-l). I will be happy to know why something like this is
1329 * needed.
1331 rearrange_windows();
1332 rearrange_windows();
1335 void
1336 ui_schedule_redraw(void)
1338 should_rearrange_windows = 1;
1341 void
1342 ui_require_input(struct tab *tab, int hide)
1344 /* TODO: hard-switching to another tab is ugly */
1345 switch_to_tab(tab);
1347 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1348 &ir_history, NULL, NULL);
1349 strlcpy(ministate.prompt, "Input required: ",
1350 sizeof(ministate.prompt));
1351 redraw_tab(tab);
1354 void
1355 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1356 struct tab *data)
1358 yornp(prompt, fn, data);
1359 redraw_tab(current_tab);
1362 void
1363 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1364 struct tab *data)
1366 completing_read(prompt, fn, data);
1367 redraw_tab(current_tab);
1370 void
1371 ui_suspend(void)
1373 endwin();
1375 kill(getpid(), SIGSTOP);
1377 refresh();
1378 clear();
1379 rearrange_windows();
1382 void
1383 ui_end(void)
1385 endwin();