Codebergdnkl
foot
master
Showing 4000 of 4853 lines.
1#include "terminal.h"
3#if defined(__GLIBC__)
4#include <malloc.h>
5#endif
6#include <signal.h>
7#include <string.h>
8#include <unistd.h>
9#include <errno.h>
10#include <limits.h>
12#include <sys/stat.h>
13#include <sys/wait.h>
14#include <sys/ioctl.h>
15#include <sys/epoll.h>
16#include <sys/eventfd.h>
17#include <sys/timerfd.h>
18#include <fcntl.h>
19#include <linux/input-event-codes.h>
20#include <xdg-shell.h>
22#define LOG_MODULE "terminal"
23#define LOG_ENABLE_DBG 0
24#include "log.h"
26#include "async.h"
27#include "commands.h"
28#include "config.h"
29#include "debug.h"
30#include "emoji-variation-sequences.h"
31#include "extract.h"
32#include "grid.h"
33#include "ime.h"
34#include "input.h"
35#include "notify.h"
36#include "quirks.h"
37#include "reaper.h"
38#include "render.h"
39#include "selection.h"
40#include "shm.h"
41#include "sixel.h"
42#include "slave.h"
43#include "spawn.h"
44#include "url-mode.h"
45#include "util.h"
46#include "vt.h"
47#include "xmalloc.h"
48#include "xsnprintf.h"
50#define PTMX_TIMING 0
52static void
53enqueue_data_for_slave(const void *data, size_t len, size_t offset,
54 ptmx_buffer_list_t *buffer_list)
55{
56 struct ptmx_buffer queued = {
57 .data = xmemdup(data, len),
58 .len = len,
59 .idx = offset,
60 };
61 tll_push_back(*buffer_list, queued);
62}
64static bool
65data_to_slave(struct terminal *term, const void *data, size_t len,
66 ptmx_buffer_list_t *buffer_list)
67{
68 /*
69 * Try a synchronous write first. If we fail to write everything,
70 * switch to asynchronous.
71 */
73 size_t async_idx = 0;
74 switch (async_write(term->ptmx, data, len, &async_idx)) {
75 case ASYNC_WRITE_REMAIN:
76 /* Switch to asynchronous mode; let FDM write the remaining data */
77 if (!fdm_event_add(term->fdm, term->ptmx, EPOLLOUT))
78 return false;
79 enqueue_data_for_slave(data, len, async_idx, buffer_list);
80 return true;
82 case ASYNC_WRITE_DONE:
83 return true;
85 case ASYNC_WRITE_ERR:
86 LOG_ERRNO("failed to synchronously write %zu bytes to slave", len);
87 return false;
88 }
90 BUG("Unexpected async_write() return value");
91 return false;
92}
94bool
95term_paste_data_to_slave(struct terminal *term, const void *data, size_t len)
96{
97 xassert(term->is_sending_paste_data);
99 if (term->ptmx < 0) {
100 /* We're probably in "hold" */
101 return false;
102 }
104 if (tll_length(term->ptmx_paste_buffers) > 0) {
105 /* Don't even try to send data *now* if there's queued up
106 * data, since that would result in events arriving out of
107 * order. */
108 enqueue_data_for_slave(data, len, 0, &term->ptmx_paste_buffers);
109 return true;
110 }
112 return data_to_slave(term, data, len, &term->ptmx_paste_buffers);
113}
115bool
116term_to_slave(struct terminal *term, const void *data, size_t len)
117{
118 if (term->ptmx < 0) {
119 /* We're probably in "hold" */
120 return false;
121 }
123 if (unlikely(tll_length(term->ptmx_buffers) > 0 ||
124 term->is_sending_paste_data ||
125 tll_length(term->ptmx_paste_buffers) > 0))
126 {
127 /*
128 * Don't even try to send data *now* if there's queued up
129 * data, since that would result in events arriving out of
130 * order.
131 *
132 * Furthermore, if we're currently sending paste data to the
133 * client, do *not* mix that stream with other events
134 * (https://codeberg.org/dnkl/foot/issues/101).
135 */
136 enqueue_data_for_slave(data, len, 0, &term->ptmx_buffers);
137 return true;
138 }
140 return data_to_slave(term, data, len, &term->ptmx_buffers);
141}
143static bool
144fdm_ptmx_out(struct fdm *fdm, int fd, int events, void *data)
145{
146 struct terminal *term = data;
148 /* If there is no queued data, then we shouldn't be in asynchronous mode */
149 xassert(tll_length(term->ptmx_buffers) > 0 ||
150 tll_length(term->ptmx_paste_buffers) > 0);
152 /* Writes a single buffer, returns if not all of it could be written */
153#define write_one_buffer(buffer_list) \
154 { \
155 switch (async_write(term->ptmx, it->item.data, it->item.len, &it->item.idx)) { \
156 case ASYNC_WRITE_DONE: \
157 free(it->item.data); \
158 tll_remove(buffer_list, it); \
159 break; \
160 case ASYNC_WRITE_REMAIN: \
161 /* to_slave() updated it->item.idx */ \
162 return true; \
163 case ASYNC_WRITE_ERR: \
164 LOG_ERRNO("failed to asynchronously write %zu bytes to slave", \
165 it->item.len - it->item.idx); \
166 return false; \
167 } \
168 }
170 tll_foreach(term->ptmx_paste_buffers, it)
171 write_one_buffer(term->ptmx_paste_buffers);
173 /* If we get here, *all* paste data buffers were successfully
174 * flushed */
176 if (!term->is_sending_paste_data) {
177 tll_foreach(term->ptmx_buffers, it)
178 write_one_buffer(term->ptmx_buffers);
179 }
181 /*
182 * If we get here, *all* buffers were successfully flushed.
183 *
184 * Or, we're still sending paste data, in which case we do *not*
185 * want to send the "normal" queued up data
186 *
187 * In both cases, we want to *disable* the FDM callback since
188 * otherwise we'd just be called right away again, with nothing to
189 * write.
190 */
191 fdm_event_del(term->fdm, term->ptmx, EPOLLOUT);
192 return true;
193}
195static bool
196add_utmp_record(const struct config *conf, struct reaper *reaper, int ptmx)
197{
198#if defined(UTMP_ADD)
199 if (ptmx < 0)
200 return true;
201 if (conf->utmp_helper_path == NULL)
202 return true;
204 char *const argv[] = {conf->utmp_helper_path, UTMP_ADD, getenv("WAYLAND_DISPLAY"), NULL};
205 return spawn(reaper, NULL, argv, ptmx, -1, -1, NULL, NULL, NULL) >= 0;
206#else
207 return true;
208#endif
209}
211static bool
212del_utmp_record(const struct config *conf, struct reaper *reaper, int ptmx)
213{
214#if defined(UTMP_DEL)
215 if (ptmx < 0)
216 return true;
217 if (conf->utmp_helper_path == NULL)
218 return true;
220 char *del_argument =
221#if defined(UTMP_DEL_HAVE_ARGUMENT)
222 getenv("WAYLAND_DISPLAY")
223#else
224 NULL
225#endif
226 ;
228 char *const argv[] = {conf->utmp_helper_path, UTMP_DEL, del_argument, NULL};
229 return spawn(reaper, NULL, argv, ptmx, -1, -1, NULL, NULL, NULL) >= 0;
230#else
231 return true;
232#endif
233}
235#if PTMX_TIMING
236static struct timespec last = {0};
237#endif
239static bool cursor_blink_rearm_timer(struct terminal *term);
241/* Externally visible, but not declared in terminal.h, to enable pgo
242 * to call this function directly */
243bool
244fdm_ptmx(struct fdm *fdm, int fd, int events, void *data)
245{
246 struct terminal *term = data;
248 const bool pollin = events & EPOLLIN;
249 const bool pollout = events & EPOLLOUT;
250 const bool hup = events & EPOLLHUP;
252 if (pollout) {
253 if (!fdm_ptmx_out(fdm, fd, events, data))
254 return false;
255 }
257 /* Prevent blinking while typing */
258 if (term->cursor_blink.fd >= 0) {
259 term->cursor_blink.state = CURSOR_BLINK_ON;
260 cursor_blink_rearm_timer(term);
261 }
263 if (unlikely(term->interactive_resizing.grid != NULL)) {
264 /*
265 * Don't consume PTMX while we're doing an interactive resize,
266 * since the 'normal' grid we're currently using is a
267 * temporary one - all changes done to it will be lost when
268 * the interactive resize ends.
269 */
270 return true;
271 }
273 uint8_t buf[24 * 1024];
274 const size_t max_iterations = !hup ? 10 : SIZE_MAX;
276 for (size_t i = 0; i < max_iterations && pollin; i++) {
277 xassert(pollin);
278 ssize_t count = read(term->ptmx, buf, sizeof(buf));
280 if (count < 0) {
281 if (errno == EAGAIN || errno == EIO) {
282 /*
283 * EAGAIN: no more to read - FDM will trigger us again
284 * EIO: assume PTY was closed - we already have, or will get, a EPOLLHUP
285 */
286 break;
287 }
289 LOG_ERRNO("failed to read from pseudo terminal");
290 return false;
291 } else if (count == 0) {
292 /* Reached end-of-file */
293 break;
294 }
296 xassert(term->interactive_resizing.grid == NULL);
297 vt_from_slave(term, buf, count);
298 }
300 if (!term->render.app_sync_updates.enabled) {
301 /*
302 * We likely need to re-render. But, we don't want to do it
303 * immediately. Often, a single client update is done through
304 * multiple writes. This could lead to us rendering one frame with
305 * "intermediate" state.
306 *
307 * For example, we might end up rendering a frame
308 * where the client just erased a line, while in the
309 * next frame, the client wrote to the same line. This
310 * causes screen "flickering".
311 *
312 * Mitigate by always incuring a small delay before
313 * rendering the next frame. This gives the client
314 * some time to finish the operation (and thus gives
315 * us time to receive the last writes before doing any
316 * actual rendering).
317 *
318 * We incur this delay *every* time we receive
319 * input. To ensure we don't delay rendering
320 * indefinitely, we start a second timer that is only
321 * reset when we render.
322 *
323 * Note that when the client is producing data at a
324 * very high pace, we're rate limited by the wayland
325 * compositor anyway. The delay we introduce here only
326 * has any effect when the renderer is idle.
327 */
328 uint64_t lower_ns = term->conf->tweak.delayed_render_lower_ns;
329 uint64_t upper_ns = term->conf->tweak.delayed_render_upper_ns;
331 if (lower_ns > 0 && upper_ns > 0) {
332#if PTMX_TIMING
333 struct timespec now;
335 clock_gettime(CLOCK_MONOTONIC, &now);
336 if (last.tv_sec > 0 || last.tv_nsec > 0) {
337 struct timespec diff;
339 timespec_sub(&now, &last, &diff);
340 LOG_INFO("waited %lds %ldns for more input",
341 (long)diff.tv_sec, diff.tv_nsec);
342 }
343 last = now;
344#endif
346 xassert(lower_ns < 1000000000);
347 xassert(upper_ns < 1000000000);
348 xassert(upper_ns > lower_ns);
350 timerfd_settime(
351 term->delayed_render_timer.lower_fd, 0,
352 &(struct itimerspec){.it_value = {.tv_nsec = lower_ns}},
353 NULL);
355 /* Second timeout - only reset when we render. Set to one
356 * frame (assuming 60Hz) */
357 if (!term->delayed_render_timer.is_armed) {
358 timerfd_settime(
359 term->delayed_render_timer.upper_fd, 0,
360 &(struct itimerspec){.it_value = {.tv_nsec = upper_ns}},
361 NULL);
362 term->delayed_render_timer.is_armed = true;
363 }
364 } else
365 render_refresh(term);
366 }
368 if (hup) {
369 del_utmp_record(term->conf, term->reaper, term->ptmx);
370 fdm_del(fdm, fd);
371 term->ptmx = -1;
373 /*
374 * Normally, we do *not* want to shutdown when the PTY is
375 * closed. Instead, we want to wait for the client application
376 * to exit.
377 *
378 * However, when we're using a pre-existing PTY (the --pty
379 * option), there _is_ no client application. That is, foot
380 * does *not* fork+exec anything, and thus the only way to
381 * shutdown is to wait for the PTY to be closed.
382 */
383 if (term->slave < 0 && !term->conf->hold_at_exit) {
384 term_shutdown(term);
385 }
386 }
388 return true;
389}
391bool
392term_ptmx_pause(struct terminal *term)
393{
394 if (term->ptmx < 0)
395 return false;
396 return fdm_event_del(term->fdm, term->ptmx, EPOLLIN);
397}
399bool
400term_ptmx_resume(struct terminal *term)
401{
402 if (term->ptmx < 0)
403 return false;
404 return fdm_event_add(term->fdm, term->ptmx, EPOLLIN);
405}
407static bool
408fdm_flash(struct fdm *fdm, int fd, int events, void *data)
409{
410 if (events & EPOLLHUP)
411 return false;
413 struct terminal *term = data;
414 uint64_t expiration_count;
415 ssize_t ret = read(
416 term->flash.fd, &expiration_count, sizeof(expiration_count));
418 if (ret < 0) {
419 if (errno == EAGAIN)
420 return true;
422 LOG_ERRNO("failed to read flash timer");
423 return false;
424 }
426 LOG_DBG("flash timer expired %llu times",
427 (unsigned long long)expiration_count);
429 term->flash.active = false;
430 render_overlay(term);
432 // since the overlay surface is synced with the main window surface, we have
433 // to commit the main surface for the compositor to acknowledge the new
434 // overlay state.
435 wl_surface_commit(term->window->surface.surf);
436 return true;
437}
439static bool
440fdm_blink(struct fdm *fdm, int fd, int events, void *data)
441{
442 if (events & EPOLLHUP)
443 return false;
445 struct terminal *term = data;
446 uint64_t expiration_count;
447 ssize_t ret = read(
448 term->blink.fd, &expiration_count, sizeof(expiration_count));
450 if (ret < 0) {
451 if (errno == EAGAIN)
452 return true;
454 LOG_ERRNO("failed to read blink timer");
455 return false;
456 }
458 LOG_DBG("blink timer expired %llu times",
459 (unsigned long long)expiration_count);
461 /* Invert blink state */
462 term->blink.state = term->blink.state == BLINK_ON
463 ? BLINK_OFF : BLINK_ON;
465 /* Scan all visible cells and mark rows with blinking cells dirty */
466 bool no_blinking_cells = true;
467 for (int r = 0; r < term->rows; r++) {
468 struct row *row = grid_row_in_view(term->grid, r);
469 for (int col = 0; col < term->cols; col++) {
470 struct cell *cell = &row->cells[col];
472 if (cell->attrs.blink) {
473 cell->attrs.clean = 0;
474 row->dirty = true;
475 no_blinking_cells = false;
476 }
477 }
478 }
480 if (no_blinking_cells) {
481 LOG_DBG("disarming blink timer");
483 term->blink.state = BLINK_ON;
484 fdm_del(term->fdm, term->blink.fd);
485 term->blink.fd = -1;
486 } else
487 render_refresh(term);
488 return true;
489}
491void
492term_arm_blink_timer(struct terminal *term)
493{
494 if (term->blink.fd >= 0)
495 return;
497 LOG_DBG("arming blink timer");
499 int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
500 if (fd < 0) {
501 LOG_ERRNO("failed to create blink timer FD");
502 return;
503 }
505 if (!fdm_add(term->fdm, fd, EPOLLIN, &fdm_blink, term)) {
506 close(fd);
507 return;
508 }
510 struct itimerspec alarm = {
511 .it_value = {.tv_sec = 0, .tv_nsec = 500 * 1000000},
512 .it_interval = {.tv_sec = 0, .tv_nsec = 500 * 1000000},
513 };
515 if (timerfd_settime(fd, 0, &alarm, NULL) < 0) {
516 LOG_ERRNO("failed to arm blink timer");
517 fdm_del(term->fdm, fd);
518 }
520 term->blink.fd = fd;
521}
523static void
524cursor_refresh(struct terminal *term)
525{
526 if (unlikely(!term->window->is_configured || term->shutdown.in_progress))
527 return;
529 term->grid->cur_row->cells[term->grid->cursor.point.col].attrs.clean = 0;
530 term->grid->cur_row->dirty = true;
531 render_refresh(term);
532}
534static bool
535fdm_cursor_blink(struct fdm *fdm, int fd, int events, void *data)
536{
537 if (events & EPOLLHUP)
538 return false;
540 struct terminal *term = data;
541 uint64_t expiration_count;
542 ssize_t ret = read(
543 term->cursor_blink.fd, &expiration_count, sizeof(expiration_count));
545 if (ret < 0) {
546 if (errno == EAGAIN)
547 return true;
549 LOG_ERRNO("failed to read cursor blink timer");
550 return false;
551 }
553 LOG_DBG("cursor blink timer expired %llu times",
554 (unsigned long long)expiration_count);
556 /* Invert blink state */
557 term->cursor_blink.state = term->cursor_blink.state == CURSOR_BLINK_ON
558 ? CURSOR_BLINK_OFF : CURSOR_BLINK_ON;
560 cursor_refresh(term);
561 return true;
562}
564static bool
565fdm_delayed_render(struct fdm *fdm, int fd, int events, void *data)
566{
567 if (events & EPOLLHUP)
568 return false;
570 struct terminal *term = data;
572 uint64_t unused;
573 ssize_t ret1 = 0;
574 ssize_t ret2 = 0;
576 if (fd == term->delayed_render_timer.lower_fd)
577 ret1 = read(term->delayed_render_timer.lower_fd, &unused, sizeof(unused));
578 if (fd == term->delayed_render_timer.upper_fd)
579 ret2 = read(term->delayed_render_timer.upper_fd, &unused, sizeof(unused));
581 if ((ret1 < 0 || ret2 < 0)) {
582 if (errno == EAGAIN)
583 return true;
585 LOG_ERRNO("failed to read timeout timer");
586 return false;
587 }
589 if (ret1 > 0)
590 LOG_DBG("lower delay timer expired");
591 else if (ret2 > 0)
592 LOG_DBG("upper delay timer expired");
594 if (ret1 == 0 && ret2 == 0)
595 return true;
597#if PTMX_TIMING
598 last = (struct timespec){0};
599#endif
601 /* Reset timers */
602 struct itimerspec reset = {{0}};
603 timerfd_settime(term->delayed_render_timer.lower_fd, 0, &reset, NULL);
604 timerfd_settime(term->delayed_render_timer.upper_fd, 0, &reset, NULL);
605 term->delayed_render_timer.is_armed = false;
607 render_refresh(term);
608 return true;
609}
611static bool
612fdm_app_sync_updates_timeout(
613 struct fdm *fdm, int fd, int events, void *data)
614{
615 if (events & EPOLLHUP)
616 return false;
618 struct terminal *term = data;
619 uint64_t unused;
620 ssize_t ret = read(term->render.app_sync_updates.timer_fd,
621 &unused, sizeof(unused));
623 if (ret < 0) {
624 if (errno == EAGAIN)
625 return true;
626 LOG_ERRNO("failed to read application synchronized updates timeout timer");
627 return false;
628 }
630 term_disable_app_sync_updates(term);
631 return true;
632}
634static bool
635fdm_title_update_timeout(struct fdm *fdm, int fd, int events, void *data)
636{
637 if (events & EPOLLHUP)
638 return false;
640 struct terminal *term = data;
641 uint64_t unused;
642 ssize_t ret = read(term->render.title.timer_fd, &unused, sizeof(unused));
644 if (ret < 0) {
645 if (errno == EAGAIN)
646 return true;
647 LOG_ERRNO("failed to read title update throttle timer");
648 return false;
649 }
651 struct itimerspec reset = {{0}};
652 timerfd_settime(term->render.title.timer_fd, 0, &reset, NULL);
654 render_refresh_title(term);
655 return true;
656}
658static bool
659fdm_icon_update_timeout(struct fdm *fdm, int fd, int events, void *data)
660{
661 if (events & EPOLLHUP)
662 return false;
664 struct terminal *term = data;
665 uint64_t unused;
666 ssize_t ret = read(term->render.icon.timer_fd, &unused, sizeof(unused));
668 if (ret < 0) {
669 if (errno == EAGAIN)
670 return true;
671 LOG_ERRNO("failed to read icon update throttle timer");
672 return false;
673 }
675 struct itimerspec reset = {{0}};
676 timerfd_settime(term->render.icon.timer_fd, 0, &reset, NULL);
678 render_refresh_icon(term);
679 return true;
680}
682static bool
683fdm_app_id_update_timeout(struct fdm *fdm, int fd, int events, void *data)
684{
685 if (events & EPOLLHUP)
686 return false;
688 struct terminal *term = data;
689 uint64_t unused;
690 ssize_t ret = read(term->render.app_id.timer_fd, &unused, sizeof(unused));
692 if (ret < 0) {
693 if (errno == EAGAIN)
694 return true;
695 LOG_ERRNO("failed to read app ID update throttle timer");
696 return false;
697 }
699 struct itimerspec reset = {{0}};
700 timerfd_settime(term->render.app_id.timer_fd, 0, &reset, NULL);
702 render_refresh_app_id(term);
703 return true;
704}
706static bool
707initialize_render_workers(struct terminal *term)
708{
709 LOG_INFO("using %hu rendering threads", term->render.workers.count);
711 if (sem_init(&term->render.workers.start, 0, 0) < 0 ||
712 sem_init(&term->render.workers.done, 0, 0) < 0)
713 {
714 LOG_ERRNO("failed to instantiate render worker semaphores");
715 return false;
716 }
718 int err;
719 if ((err = mtx_init(&term->render.workers.lock, mtx_plain)) != thrd_success) {
720 LOG_ERR("failed to instantiate render worker mutex: %s (%d)",
721 thrd_err_as_string(err), err);
722 goto err_sem_destroy;
723 }
725 mtx_init(&term->render.workers.preapplied_damage.lock, mtx_plain);
726 cnd_init(&term->render.workers.preapplied_damage.cond);
728 term->render.workers.threads = xcalloc(
729 term->render.workers.count, sizeof(term->render.workers.threads[0]));
731 for (size_t i = 0; i < term->render.workers.count; i++) {
732 struct render_worker_context *ctx = xmalloc(sizeof(*ctx));
733 *ctx = (struct render_worker_context) {
734 .term = term,
735 .my_id = 1 + i,
736 };
738 int ret = thrd_create(
739 &term->render.workers.threads[i], &render_worker_thread, ctx);
740 if (ret != thrd_success) {
742 LOG_ERR("failed to create render worker thread: %s (%d)",
743 thrd_err_as_string(ret), ret);
744 term->render.workers.threads[i] = 0;
745 return false;
746 }
747 }
749 return true;
751err_sem_destroy:
752 sem_destroy(&term->render.workers.start);
753 sem_destroy(&term->render.workers.done);
754 return false;
755}
757static void
758free_custom_glyph(struct fcft_glyph **glyph)
759{
760 if (*glyph == NULL)
761 return;
763 free(pixman_image_get_data((*glyph)->pix));
764 pixman_image_unref((*glyph)->pix);
765 free(*glyph);
766 *glyph = NULL;
767}
769static void
770free_custom_glyphs(struct fcft_glyph ***glyphs, size_t count)
771{
772 if (*glyphs == NULL)
773 return;
775 for (size_t i = 0; i < count; i++)
776 free_custom_glyph(&(*glyphs)[i]);
778 free(*glyphs);
779 *glyphs = NULL;
780}
782static void
783term_line_height_update(struct terminal *term)
784{
785 const struct config *conf = term->conf;
787 if (term->conf->line_height.px < 0) {
788 term->font_line_height.pt = 0;
789 term->font_line_height.px = -1;
790 return;
791 }
793 const float dpi = term->font_is_sized_by_dpi ? term->font_dpi : 96.;
795 const float font_original_pt_size =
796 conf->fonts[0].arr[0].px_size > 0
797 ? conf->fonts[0].arr[0].px_size * 72. / dpi
798 : conf->fonts[0].arr[0].pt_size;
799 const float font_current_pt_size =
800 term->font_sizes[0][0].px_size > 0
801 ? term->font_sizes[0][0].px_size * 72. / dpi
802 : term->font_sizes[0][0].pt_size;
804 const float change = font_current_pt_size / font_original_pt_size;
805 const float line_original_pt_size = conf->line_height.px > 0
806 ? conf->line_height.px * 72. / dpi
807 : conf->line_height.pt;
809 term->font_line_height.px = 0;
810 term->font_line_height.pt = fmaxf(line_original_pt_size * change, 0.);
811}
813static bool
814term_set_fonts(struct terminal *term, struct fcft_font *fonts[static 4],
815 bool resize_grid)
816{
817 for (size_t i = 0; i < 4; i++) {
818 xassert(fonts[i] != NULL);
820 fcft_destroy(term->fonts[i]);
821 term->fonts[i] = fonts[i];
822 }
824 free_custom_glyphs(
825 &term->custom_glyphs.box_drawing, GLYPH_BOX_DRAWING_COUNT);
826 free_custom_glyphs(
827 &term->custom_glyphs.braille, GLYPH_BRAILLE_COUNT);
828 free_custom_glyphs(
829 &term->custom_glyphs.legacy, GLYPH_LEGACY_COUNT);
830 free_custom_glyphs(
831 &term->custom_glyphs.octants, GLYPH_OCTANTS_COUNT);
833 const struct config *conf = term->conf;
835 const struct fcft_glyph *M = fcft_rasterize_char_utf32(
836 fonts[0], U'M', term->font_subpixel);
837 int advance = M != NULL ? M->advance.x : term->fonts[0]->max_advance.x;
839 term_line_height_update(term);
841 term->cell_width = advance +
842 term_pt_or_px_as_pixels(term, &conf->letter_spacing);
844 term->cell_height = term->font_line_height.px >= 0
845 ? term_pt_or_px_as_pixels(term, &term->font_line_height)
846 : max(term->fonts[0]->height,
847 term->fonts[0]->ascent + term->fonts[0]->descent);
849 if (term->cell_width <= 0)
850 term->cell_width = 1;
851 if (term->cell_height <= 0)
852 term->cell_height = 1;
854 term->font_x_ofs = term_pt_or_px_as_pixels(term, &conf->horizontal_letter_offset);
855 term->font_y_ofs = term_pt_or_px_as_pixels(term, &conf->vertical_letter_offset);
857 term->font_baseline = term_font_baseline(term);
859 LOG_INFO("cell width=%d, height=%d", term->cell_width, term->cell_height);
861 sixel_cell_size_changed(term);
863 /* Optimization - some code paths (are forced to) call
864 * render_resize() after this function */
865 if (resize_grid) {
866 /* Use force, since cell-width/height may have changed */
867 enum resize_options resize_opts = RESIZE_FORCE;
868 if (conf->resize_keep_grid)
869 resize_opts |= RESIZE_KEEP_GRID;
871 render_resize(
872 term,
873 (int)roundf(term->width / term->scale),
874 (int)roundf(term->height / term->scale),
875 resize_opts);
876 }
877 return true;
878}
880static float
881get_font_dpi(const struct terminal *term)
882{
883 /*
884 * Use output's DPI to scale font. This is to ensure the font has
885 * the same physical height (if measured by a ruler) regardless of
886 * monitor.
887 *
888 * Conceptually, we use the physical monitor specs to calculate
889 * the DPI, and we ignore the output's scaling factor.
890 *
891 * However, to deal with legacy fractional scaling, where we're
892 * told to render at e.g. 2x, but are then downscaled by the
893 * compositor to e.g. 1.25, we use the scaled DPI value multiplied
894 * by the scale factor instead.
895 *
896 * For integral scaling factors the resulting DPI is the same as
897 * if we had used the physical DPI.
898 *
899 * For legacy fractional scaling factors we'll get a DPI *larger*
900 * than the physical DPI, that ends up being right when later
901 * downscaled by the compositor.
902 *
903 * With the newer fractional-scale-v1 protocol, we use the
904 * monitor's real DPI, since we scale everything to the correct
905 * scaling factor (no downscaling done by the compositor).
906 */
908 const struct wl_window *win = term->window;
909 const struct monitor *mon = NULL;
911 if (tll_length(win->on_outputs) > 0)
912 mon = tll_back(win->on_outputs);
913 else {
914 if (term->font_dpi_before_unmap > 0.) {
915 /*
916 * Use last known "good" DPI
917 *
918 * This avoids flickering when window is unmapped/mapped
919 * (some compositors do this when a window is minimized),
920 * on a multi-monitor setup with different monitor DPIs.
921 */
922 return term->font_dpi_before_unmap;
923 }
925 if (tll_length(term->wl->monitors) > 0)
926 mon = &tll_front(term->wl->monitors);
927 }
929 const float monitor_dpi = mon != NULL
930 ? term_fractional_scaling(term)
931 ? mon->dpi.physical
932 : mon->dpi.scaled
933 : 96.;
935 return monitor_dpi > 0. ? monitor_dpi : 96.;
936}
938static enum fcft_subpixel
939get_font_subpixel(const struct terminal *term)
940{
941 if (term->colors.alpha != 0xffff) {
942 /* Can't do subpixel rendering on transparent background */
943 return FCFT_SUBPIXEL_NONE;
944 }
946 enum wl_output_subpixel wl_subpixel;
948 /*
949 * Wayland doesn't tell us *which* part of the surface that goes
950 * on a specific output, only whether the surface is mapped to an
951 * output or not.
952 *
953 * Thus, when determining which subpixel mode to use, we can't do
954 * much but select *an* output. So, we pick the one we were most
955 * recently mapped on.
956 *
957 * If we're not mapped at all, we pick the first available
958 * monitor, and hope that's where we'll eventually get mapped.
959 *
960 * If there aren't any monitors we use the "default" subpixel
961 * mode.
962 */
964 if (tll_length(term->window->on_outputs) > 0)
965 wl_subpixel = tll_back(term->window->on_outputs)->subpixel;
966 else if (tll_length(term->wl->monitors) > 0)
967 wl_subpixel = tll_front(term->wl->monitors).subpixel;
968 else
969 wl_subpixel = WL_OUTPUT_SUBPIXEL_UNKNOWN;
971 switch (wl_subpixel) {
972 case WL_OUTPUT_SUBPIXEL_UNKNOWN: return FCFT_SUBPIXEL_DEFAULT;
973 case WL_OUTPUT_SUBPIXEL_NONE: return FCFT_SUBPIXEL_NONE;
974 case WL_OUTPUT_SUBPIXEL_HORIZONTAL_RGB: return FCFT_SUBPIXEL_HORIZONTAL_RGB;
975 case WL_OUTPUT_SUBPIXEL_HORIZONTAL_BGR: return FCFT_SUBPIXEL_HORIZONTAL_BGR;
976 case WL_OUTPUT_SUBPIXEL_VERTICAL_RGB: return FCFT_SUBPIXEL_VERTICAL_RGB;
977 case WL_OUTPUT_SUBPIXEL_VERTICAL_BGR: return FCFT_SUBPIXEL_VERTICAL_BGR;
978 }
980 return FCFT_SUBPIXEL_DEFAULT;
981}
983int
984term_pt_or_px_as_pixels(const struct terminal *term,
985 const struct pt_or_px *pt_or_px)
986{
987 float scale = !term->font_is_sized_by_dpi ? term->scale : 1.;
988 float dpi = term->font_is_sized_by_dpi ? term->font_dpi : 96.;
990 return pt_or_px->px == 0
991 ? (int)roundf(pt_or_px->pt * scale * dpi / 72)
992 : (int)roundf(pt_or_px->px * scale);
993}
995struct font_load_data {
996 size_t count;
997 const char **names;
998 const char *attrs;
1000 const struct fcft_font_options *options;
1001 struct fcft_font **font;
1002};
1004static int
1005font_loader_thread(void *_data)
1006{
1007 struct font_load_data *data = _data;
1008 *data->font = fcft_from_name2(
1009 data->count, data->names, data->attrs, data->options);
1010 return *data->font != NULL;
1011}
1013static bool
1014reload_fonts(struct terminal *term, bool resize_grid)
1015{
1016 const struct config *conf = term->conf;
1018 const size_t counts[4] = {
1019 conf->fonts[0].count,
1020 conf->fonts[1].count,
1021 conf->fonts[2].count,
1022 conf->fonts[3].count,
1023 };
1025 /* Configure size (which may have been changed run-time) */
1026 char **names[4];
1027 for (size_t i = 0; i < 4; i++) {
1028 names[i] = xmalloc(counts[i] * sizeof(names[i][0]));
1030 const struct config_font_list *font_list = &conf->fonts[i];
1032 for (size_t j = 0; j < font_list->count; j++) {
1033 const struct config_font *font = &font_list->arr[j];
1034 bool use_px_size = term->font_sizes[i][j].px_size > 0;
1035 char size[64];
1037 const float scale = term->font_is_sized_by_dpi ? 1. : term->scale;
1039 if (use_px_size)
1040 snprintf(size, sizeof(size), ":pixelsize=%d",
1041 (int)roundf(term->font_sizes[i][j].px_size * scale));
1042 else
1043 snprintf(size, sizeof(size), ":size=%.2f",
1044 term->font_sizes[i][j].pt_size * scale);
1046 names[i][j] = xstrjoin(font->pattern, size);
1047 }
1048 }
1050 /* Did user configure custom bold/italic fonts?
1051 * Or should we use the regular font, with weight/slant attributes? */
1052 const bool custom_bold = counts[1] > 0;
1053 const bool custom_italic = counts[2] > 0;
1054 const bool custom_bold_italic = counts[3] > 0;
1056 const size_t count_regular = counts[0];
1057 const char **names_regular = (const char **)names[0];
1059 const size_t count_bold = custom_bold ? counts[1] : counts[0];
1060 const char **names_bold = (const char **)(custom_bold ? names[1] : names[0]);
1062 const size_t count_italic = custom_italic ? counts[2] : counts[0];
1063 const char **names_italic = (const char **)(custom_italic ? names[2] : names[0]);
1065 const size_t count_bold_italic = custom_bold_italic ? counts[3] : counts[0];
1066 const char **names_bold_italic = (const char **)(custom_bold_italic ? names[3] : names[0]);
1068 const bool use_dpi = term->font_is_sized_by_dpi;
1069 char *dpi = xasprintf("dpi=%.2f", use_dpi ? term->font_dpi : 96.);
1071 char *attrs[4] = {
1072 [0] = dpi, /* Takes ownership */
1073 [1] = xstrjoin(dpi, !custom_bold ? ":weight=bold" : ""),
1074 [2] = xstrjoin(dpi, !custom_italic ? ":slant=italic" : ""),
1075 [3] = xstrjoin(dpi, !custom_bold_italic ? ":weight=bold:slant=italic" : ""),
1076 };
1078 struct fcft_font_options *options = fcft_font_options_create();
1080 options->scaling_filter = conf->tweak.fcft_filter;
1081 options->color_glyphs.format = PIXMAN_a8r8g8b8;
1082 options->color_glyphs.srgb_decode =
1083 wayl_do_linear_blending(term->wl, term->conf);
1085 if (shm_chain_bit_depth(term->render.chains.grid) >= SHM_BITS_10) {
1086 /*
1087 * Use a high-res buffer type for emojis. We don't want to use
1088 * an a2r10g0b10 type of surface, since we need more than 2
1089 * bits for alpha.
1090 */
1091#if defined(HAVE_PIXMAN_RGBA_16)
1092 options->color_glyphs.format = PIXMAN_a16b16g16r16;
1093#else
1094 options->color_glyphs.format = PIXMAN_rgba_float;
1095#endif
1096 }
1098 struct fcft_font *fonts[4];
1099 struct font_load_data data[4] = {
1100 {count_regular, names_regular, attrs[0], options, &fonts[0]},
1101 {count_bold, names_bold, attrs[1], options, &fonts[1]},
1102 {count_italic, names_italic, attrs[2], options, &fonts[2]},
1103 {count_bold_italic, names_bold_italic, attrs[3], options, &fonts[3]},
1104 };
1106 thrd_t tids[4] = {0};
1107 for (size_t i = 0; i < 4; i++) {
1108 int ret = thrd_create(&tids[i], &font_loader_thread, &data[i]);
1109 if (ret != thrd_success) {
1110 LOG_ERR("failed to create font loader thread: %s (%d)",
1111 thrd_err_as_string(ret), ret);
1112 break;
1113 }
1114 }
1116 bool success = true;
1117 for (size_t i = 0; i < 4; i++) {
1118 if (tids[i] != 0) {
1119 int ret;
1120 if (thrd_join(tids[i], &ret) != thrd_success)
1121 success = false;
1122 else
1123 success = success && ret;
1124 } else
1125 success = false;
1126 }
1128 fcft_font_options_destroy(options);
1130 for (size_t i = 0; i < 4; i++) {
1131 for (size_t j = 0; j < counts[i]; j++)
1132 free(names[i][j]);
1133 free(names[i]);
1134 free(attrs[i]);
1135 }
1137 if (!success) {
1138 LOG_ERR("failed to load primary fonts");
1139 for (size_t i = 0; i < 4; i++) {
1140 fcft_destroy(fonts[i]);
1141 fonts[i] = NULL;
1142 }
1143 }
1145 return success ? term_set_fonts(term, fonts, resize_grid) : success;
1146}
1148static bool
1149load_fonts_from_conf(struct terminal *term)
1150{
1151 const struct config *conf = term->conf;
1153 for (size_t i = 0; i < 4; i++) {
1154 const struct config_font_list *font_list = &conf->fonts[i];
1156 for (size_t j = 0; j < font_list->count; j++) {
1157 const struct config_font *font = &font_list->arr[j];
1158 term->font_sizes[i][j] = (struct config_font){
1159 .pt_size = font->pt_size, .px_size = font->px_size};
1160 }
1161 }
1163 return reload_fonts(term, true);
1164}
1166static void fdm_client_terminated(
1167 struct reaper *reaper, pid_t pid, int status, void *data);
1169static const int PTY_OPEN_FLAGS = O_RDWR | O_NOCTTY;
1171struct terminal *
1172term_init(const struct config *conf, struct fdm *fdm, struct reaper *reaper,
1173 struct wayland *wayl, const char *foot_exe, const char *cwd,
1174 const char *token, const char *pty_path,
1175 int argc, char *const *argv, const char *const *envp,
1176 void (*shutdown_cb)(void *data, int exit_code), void *shutdown_data)
1177{
1178 int ptmx = -1;
1179 int flash_fd = -1;
1180 int delay_lower_fd = -1;
1181 int delay_upper_fd = -1;
1182 int app_sync_updates_fd = -1;
1183 int title_update_fd = -1;
1184 int icon_update_fd = -1;
1185 int app_id_update_fd = -1;
1187 struct terminal *term = malloc(sizeof(*term));
1188 if (unlikely(term == NULL)) {
1189 LOG_ERRNO("malloc() failed");
1190 return NULL;
1191 }
1193 ptmx = pty_path ? open(pty_path, PTY_OPEN_FLAGS) : posix_openpt(PTY_OPEN_FLAGS);
1194 if (ptmx < 0) {
1195 LOG_ERRNO("failed to open PTY");
1196 goto close_fds;
1197 }
1198 if ((flash_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0) {
1199 LOG_ERRNO("failed to create flash timer FD");
1200 goto close_fds;
1201 }
1202 if ((delay_lower_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0 ||
1203 (delay_upper_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0)
1204 {
1205 LOG_ERRNO("failed to create delayed rendering timer FDs");
1206 goto close_fds;
1207 }
1209 if ((app_sync_updates_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0)
1210 {
1211 LOG_ERRNO("failed to create application synchronized updates timer FD");
1212 goto close_fds;
1213 }
1215 if ((title_update_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0)
1216 {
1217 LOG_ERRNO("failed to create title update throttle timer FD");
1218 goto close_fds;
1219 }
1221 if ((icon_update_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0)
1222 {
1223 LOG_ERRNO("failed to create icon update throttle timer FD");
1224 goto close_fds;
1225 }
1227 if ((app_id_update_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK)) < 0)
1228 {
1229 LOG_ERRNO("failed to create app ID update throttle timer FD");
1230 goto close_fds;
1231 }
1233 if (ioctl(ptmx, (unsigned int)TIOCSWINSZ,
1234 &(struct winsize){.ws_row = 24, .ws_col = 80}) < 0)
1235 {
1236 LOG_ERRNO("failed to set initial TIOCSWINSZ");
1237 goto close_fds;
1238 }
1240 /* Need to register *very* early (before the first "goto err"), to
1241 * ensure term_destroy() doesn't unref a key-binding we haven't
1242 * yet ref:d */
1243 key_binding_new_for_conf(wayl->key_binding_manager, wayl, conf);
1245 int ptmx_flags;
1246 if ((ptmx_flags = fcntl(ptmx, F_GETFL)) < 0 ||
1247 fcntl(ptmx, F_SETFL, ptmx_flags | O_NONBLOCK) < 0)
1248 {
1249 LOG_ERRNO("failed to configure ptmx as non-blocking");
1250 goto err;
1251 }
1253 /*
1254 * Enable all FDM callbackes *except* ptmx - we can't do that
1255 * until the window has been 'configured' since we don't have a
1256 * size (and thus no grid) before then.
1257 */
1259 if (!fdm_add(fdm, flash_fd, EPOLLIN, &fdm_flash, term) ||
1260 !fdm_add(fdm, delay_lower_fd, EPOLLIN, &fdm_delayed_render, term) ||
1261 !fdm_add(fdm, delay_upper_fd, EPOLLIN, &fdm_delayed_render, term) ||
1262 !fdm_add(fdm, app_sync_updates_fd, EPOLLIN, &fdm_app_sync_updates_timeout, term) ||
1263 !fdm_add(fdm, title_update_fd, EPOLLIN, &fdm_title_update_timeout, term) ||
1264 !fdm_add(fdm, icon_update_fd, EPOLLIN, &fdm_icon_update_timeout, term) ||
1265 !fdm_add(fdm, app_id_update_fd, EPOLLIN, &fdm_app_id_update_timeout, term))
1266 {
1267 goto err;
1268 }
1270 const enum shm_bit_depth desired_bit_depth =
1271 conf->tweak.surface_bit_depth == SHM_BITS_AUTO
1272 ? wayl_do_linear_blending(wayl, conf) ? SHM_BITS_16 : SHM_BITS_8
1273 : conf->tweak.surface_bit_depth;
1275 const struct color_theme *theme = NULL;
1276 switch (conf->initial_color_theme) {
1277 case COLOR_THEME_DARK: theme = &conf->colors_dark; break;
1278 case COLOR_THEME_LIGHT: theme = &conf->colors_light; break;
1279 case COLOR_THEME_1: BUG("COLOR_THEME_1 should not be used"); break;
1280 case COLOR_THEME_2: BUG("COLOR_THEME_2 should not be used"); break;
1281 }
1283 /* Initialize configure-based terminal attributes */
1284 *term = (struct terminal) {
1285 .fdm = fdm,
1286 .reaper = reaper,
1287 .conf = conf,
1288 .slave = -1,
1289 .ptmx = ptmx,
1290 .ptmx_buffers = tll_init(),
1291 .ptmx_paste_buffers = tll_init(),
1292 .font_sizes = {
1293 xmalloc(sizeof(term->font_sizes[0][0]) * conf->fonts[0].count),
1294 xmalloc(sizeof(term->font_sizes[1][0]) * conf->fonts[1].count),
1295 xmalloc(sizeof(term->font_sizes[2][0]) * conf->fonts[2].count),
1296 xmalloc(sizeof(term->font_sizes[3][0]) * conf->fonts[3].count),
1297 },
1298 .font_dpi = 0.,
1299 .font_dpi_before_unmap = -1.,
1300 .font_subpixel = (theme->alpha == 0xffff /* Can't do subpixel rendering on transparent background */
1301 ? FCFT_SUBPIXEL_DEFAULT
1302 : FCFT_SUBPIXEL_NONE),
1303 .cursor_keys_mode = CURSOR_KEYS_NORMAL,
1304 .keypad_keys_mode = KEYPAD_NUMERICAL,
1305 .reverse_wrap = true,
1306 .auto_margin = true,
1307 .window_title_stack = tll_init(),
1308 .scale = 1.,
1309 .scale_before_unmap = -1,
1310 .flash = {.fd = flash_fd},
1311 .blink = {.fd = -1},
1312 .vt = {
1313 .state = 0, /* STATE_GROUND */
1314 },
1315 .colors = {
1316 .fg = theme->fg,
1317 .bg = theme->bg,
1318 .alpha = theme->alpha,
1319 .cursor_fg = (theme->use_custom.cursor ? 1u << 31 : 0) | theme->cursor.text,
1320 .cursor_bg = (theme->use_custom.cursor ? 1u << 31 : 0) | theme->cursor.cursor,
1321 .selection_fg = theme->selection_fg,
1322 .selection_bg = theme->selection_bg,
1323 .active_theme = conf->initial_color_theme,
1324 },
1325 .color_stack = {
1326 .stack = NULL,
1327 .size = 0,
1328 .idx = 0,
1329 },
1330 .origin = ORIGIN_ABSOLUTE,
1331 .cursor_style = conf->cursor.style,
1332 .cursor_blink = {
1333 .decset = false,
1334 .deccsusr = conf->cursor.blink.enabled,
1335 .state = CURSOR_BLINK_ON,
1336 .fd = -1,
1337 },
1338 .selection = {
1339 .coords = {
1340 .start = {-1, -1},
1341 .end = {-1, -1},
1342 },
1343 .pivot = {
1344 .start = {-1, -1},
1345 .end = {-1, -1},
1346 },
1347 .auto_scroll = {
1348 .fd = -1,
1349 },
1350 },
1351 .normal = {.scroll_damage = tll_init(), .sixel_images = tll_init()},
1352 .alt = {.scroll_damage = tll_init(), .sixel_images = tll_init()},
1353 .grid = &term->normal,
1354 .composed = NULL,
1355 .alt_scrolling = conf->mouse.alternate_scroll_mode,
1356 .meta = {
1357 .esc_prefix = true,
1358 .eight_bit = true,
1359 },
1360 .num_lock_modifier = true,
1361 .bell_action_enabled = true,
1362 .tab_stops = tll_init(),
1363 .wl = wayl,
1364 .render = {
1365 .chains = {
1366 .grid = shm_chain_new(wayl, true, 1 + conf->render_worker_count,
1367 desired_bit_depth, &render_buffer_release_callback, term),
1368 .search = shm_chain_new(wayl, false, 1 ,desired_bit_depth, NULL, NULL),
1369 .scrollback_indicator = shm_chain_new(wayl, false, 1, desired_bit_depth, NULL, NULL),
1370 .render_timer = shm_chain_new(wayl, false, 1, desired_bit_depth, NULL, NULL),
1371 .url = shm_chain_new(wayl, false, 1, desired_bit_depth, NULL, NULL),
1372 .csd = shm_chain_new(wayl, false, 1, desired_bit_depth, NULL, NULL),
1373 .overlay = shm_chain_new(wayl, false, 1, desired_bit_depth, NULL, NULL),
1374 },
1375 .scrollback_lines = conf->scrollback.lines,
1376 .app_sync_updates.timer_fd = app_sync_updates_fd,
1377 .title = {
1378 .timer_fd = title_update_fd,
1379 },
1380 .icon = {
1381 .timer_fd = icon_update_fd,
1382 },
1383 .app_id = {
1384 .timer_fd = app_id_update_fd,
1385 },
1386 .workers = {
1387 .count = conf->render_worker_count,
1388 .queue = tll_init(),
1389 },
1390 },
1391 .delayed_render_timer = {
1392 .is_armed = false,
1393 .lower_fd = delay_lower_fd,
1394 .upper_fd = delay_upper_fd,
1395 },
1396 .sixel = {
1397 .scrolling = true,
1398 .use_private_palette = true,
1399 .palette_size = SIXEL_MAX_COLORS,
1400 .max_width = SIXEL_MAX_WIDTH,
1401 .max_height = SIXEL_MAX_HEIGHT,
1402 },
1403 .shutdown = {
1404 .terminate_timeout_fd = -1,
1405 .cb = shutdown_cb,
1406 .cb_data = shutdown_data,
1407 },
1408 .foot_exe = xstrdup(foot_exe),
1409 .cwd = xstrdup(cwd),
1410 .grapheme_shaping = conf->tweak.grapheme_shaping,
1411#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
1412 .ime_enabled = true,
1413#endif
1414 .active_notifications = tll_init(),
1415 };
1417 pixman_region32_init(&term->render.last_overlay_clip);
1419 term_update_ascii_printer(term);
1420 memcpy(term->colors.table, theme->table, sizeof(term->colors.table));
1422 for (size_t i = 0; i < 4; i++) {
1423 const struct config_font_list *font_list = &conf->fonts[i];
1424 for (size_t j = 0; j < font_list->count; j++) {
1425 const struct config_font *font = &font_list->arr[j];
1426 term->font_sizes[i][j] = (struct config_font){
1427 .pt_size = font->pt_size, .px_size = font->px_size};
1428 }
1429 }
1431 for (size_t i = 0; i < ALEN(term->notification_icons); i++) {
1432 term->notification_icons[i].tmp_file_fd = -1;
1433 }
1435 add_utmp_record(conf, reaper, ptmx);
1437 if (!pty_path) {
1438 /* Start the slave/client */
1439 if ((term->slave = slave_spawn(
1440 term->ptmx, argc, term->cwd, argv, envp, &conf->env_vars,
1441 conf->term, conf->shell, conf->login_shell,
1442 &conf->notifications)) == -1)
1443 {
1444 goto err;
1445 }
1447 reaper_add(term->reaper, term->slave, &fdm_client_terminated, term);
1448 }
1450 /* Guess scale; we're not mapped yet, so we don't know on which
1451 * output we'll be. Use scaling factor from first monitor */
1452 xassert(tll_length(term->wl->monitors) > 0);
1453 term->scale = tll_front(term->wl->monitors).scale;
1455 /* Initialize the Wayland window backend */
1456 if ((term->window = wayl_win_init(term, token)) == NULL)
1457 goto err;
1459 /* Load fonts */
1460 if (!term_font_dpi_changed(term, 0.))
1461 goto err;
1463 term->font_subpixel = get_font_subpixel(term);
1465 term_set_window_title(term, conf->title);
1467 /* Let the Wayland backend know we exist */
1468 tll_push_back(wayl->terms, term);
1470 switch (conf->startup_mode) {
1471 case STARTUP_WINDOWED:
1472 break;
1474 case STARTUP_MAXIMIZED:
1475 xdg_toplevel_set_maximized(term->window->xdg_toplevel);
1476 break;
1478 case STARTUP_FULLSCREEN:
1479 xdg_toplevel_set_fullscreen(term->window->xdg_toplevel, NULL);
1480 break;
1481 }
1483 if (!initialize_render_workers(term))
1484 goto err;
1486 return term;
1488err:
1489 term->shutdown.in_progress = true;
1490 term_destroy(term);
1491 return NULL;
1493close_fds:
1494 close(ptmx);
1495 fdm_del(fdm, flash_fd);
1496 fdm_del(fdm, delay_lower_fd);
1497 fdm_del(fdm, delay_upper_fd);
1498 fdm_del(fdm, app_sync_updates_fd);
1499 fdm_del(fdm, title_update_fd);
1500 fdm_del(fdm, icon_update_fd);
1501 fdm_del(fdm, app_id_update_fd);
1503 free(term);
1504 return NULL;
1505}
1507void
1508term_window_configured(struct terminal *term)
1509{
1510 /* Enable ptmx FDM callback */
1511 if (!term->shutdown.in_progress) {
1512 xassert(term->window->is_configured);
1513 fdm_add(term->fdm, term->ptmx, EPOLLIN, &fdm_ptmx, term);
1515 const bool gamma_correct = wayl_do_linear_blending(term->wl, term->conf);
1516 LOG_INFO("gamma-correct blending: %s", gamma_correct ? "enabled" : "disabled");
1517 }
1518}
1520/*
1521 * Shutdown logic
1522 *
1523 * A foot instance can be terminated in two ways:
1524 *
1525 * - the client application terminates (user types 'exit', or pressed C-d in the
1526 * shell, etc)
1527 * - the foot window is closed
1528 *
1529 * Both variants need to trigger to "other" action. I.e. if the client
1530 * application is terminated, then we need to close the window. If the window is
1531 * closed, we need to terminate the client application.
1532 *
1533 * Only when *both* tasks have completed do we consider ourselves fully
1534 * shutdown. This is when we can call term_destroy(), and the user provided
1535 * shutdown callback.
1536 *
1537 * The functions involved with this are:
1538 *
1539 * - shutdown_maybe_done(): called after any of the two tasks above have
1540 * completed. When it determines that *both* tasks are done, it calls
1541 * term_destroy() and the user provided shutdown callback.
1542 *
1543 * - fdm_client_terminated(): reaper callback, called when the client
1544 * application has terminated.
1545 *
1546 * + Kills the "terminate" timeout timer
1547 * + Calls shutdown_maybe_done() if the shutdown procedure has already
1548 * started (i.e. the window being closed initiated the shutdown)
1549 * -OR-
1550 * Initiates the shutdown itself, by calling term_shutdown() (client
1551 * application termination initiated the shutdown).
1552 *
1553 * - term_shutdown(): unregisters all FDM callbacks, sends SIGTERM to the client
1554 * application and installs a "terminate" timeout timer (if it hasn't already
1555 * terminated). Finally registers an event FD with the FDM, which is
1556 * immediately triggered. This is done to ensure any pending FDM events are
1557 * handled before shutting down.
1558 *
1559 * - fdm_shutdown(): FDM callback, triggered by the event FD in
1560 * term_shutdown(). Unmaps and destroys the window resources, and ensures the
1561 * seats' focused pointers don't reference us. Finally calls
1562 * shutdown_maybe_done().
1563 *
1564 * - fdm_terminate_timeout(): FDM callback for the "terminate" timeout
1565 * timer. This function is called when the client application hasn't
1566 * terminated after 60 seconds (after the SIGTERM). Sends SIGKILL to the
1567 * client application.
1568 *
1569 * - term_destroy(): normally called from shutdown_maybe_done(), when both the
1570 * window has been unmapped, and the client application has terminated. In
1571 * this case, it simply destroys all resources.
1572 *
1573 * It may however also be called without term_shutdown() having been called
1574 * (typically in error code paths - for example, when the Wayland connection
1575 * is closed by the compositor). In this case, the client application is
1576 * typically still running, and we can't assume the FDM is running. To handle
1577 * this, we install configure a 60 second SIGALRM, send SIGTERM to the client
1578 * application, and then enter a blocking waitpid().
1579 *
1580 * If the alarm triggers, we send SIGKILL and once again enter a blocking
1581 * waitpid().
1582 */
1584static void
1585shutdown_maybe_done(struct terminal *term)
1586{
1587 bool shutdown_done =
1588 term->window == NULL && term->shutdown.client_has_terminated;
1590 LOG_DBG("window=%p, slave-has-been-reaped=%d --> %s",
1591 (void *)term->window, term->shutdown.client_has_terminated,
1592 (shutdown_done
1593 ? "shutdown done, calling term_destroy()"
1594 : "no action"));
1596 if (!shutdown_done)
1597 return;
1599 void (*cb)(void *, int) = term->shutdown.cb;
1600 void *cb_data = term->shutdown.cb_data;
1602 int exit_code = term_destroy(term);
1603 if (cb != NULL)
1604 cb(cb_data, exit_code);
1605}
1607static void
1608fdm_client_terminated(struct reaper *reaper, pid_t pid, int status, void *data)
1609{
1610 struct terminal *term = data;
1611 LOG_DBG("slave (PID=%u) died", pid);
1613 term->shutdown.client_has_terminated = true;
1614 term->shutdown.exit_status = status;
1616 if (term->shutdown.terminate_timeout_fd >= 0) {
1617 fdm_del(term->fdm, term->shutdown.terminate_timeout_fd);
1618 term->shutdown.terminate_timeout_fd = -1;
1619 }
1621 if (term->shutdown.in_progress)
1622 shutdown_maybe_done(term);
1623 else if (!term->conf->hold_at_exit)
1624 term_shutdown(term);
1625}
1627static bool
1628fdm_shutdown(struct fdm *fdm, int fd, int events, void *data)
1629{
1630 struct terminal *term = data;
1632 /* Kill the event FD */
1633 fdm_del(term->fdm, fd);
1635 wayl_win_destroy(term->window);
1636 term->window = NULL;
1638 struct wayland *wayl = term->wl;
1640 /*
1641 * Normally we'd get unmapped when we destroy the Wayland
1642 * above.
1643 *
1644 * However, it appears that under certain conditions, those events
1645 * are deferred (for example, when a screen locker is active), and
1646 * thus we can get here without having been unmapped.
1647 */
1648 tll_foreach(wayl->seats, it) {
1649 if (it->item.kbd_focus == term)
1650 it->item.kbd_focus = NULL;
1651 if (it->item.mouse_focus == term)
1652 it->item.mouse_focus = NULL;
1653 }
1655 shutdown_maybe_done(term);
1656 return true;
1657}
1659static bool
1660fdm_terminate_timeout(struct fdm *fdm, int fd, int events, void *data)
1661{
1662 uint64_t unused;
1663 ssize_t bytes = read(fd, &unused, sizeof(unused));
1664 if (bytes < 0) {
1665 LOG_ERRNO("failed to read from slave terminate timeout FD");
1666 return false;
1667 }
1669 struct terminal *term = data;
1670 xassert(!term->shutdown.client_has_terminated);
1672 LOG_DBG("slave (PID=%u) has not terminated, sending %s (%d)",
1673 term->slave,
1674 term->shutdown.next_signal == SIGTERM ? "SIGTERM"
1675 : term->shutdown.next_signal == SIGKILL ? "SIGKILL"
1676 : "<unknown>",
1677 term->shutdown.next_signal);
1679 kill(-term->slave, term->shutdown.next_signal);
1681 switch (term->shutdown.next_signal) {
1682 case SIGTERM:
1683 term->shutdown.next_signal = SIGKILL;
1684 break;
1686 case SIGKILL:
1687 /* Disarm. Shouldn't be necessary, as we should be able to
1688 shutdown completely after sending SIGKILL, before the next
1689 timeout occurs). But lets play it safe... */
1690 if (term->shutdown.terminate_timeout_fd >= 0) {
1691 timerfd_settime(
1692 term->shutdown.terminate_timeout_fd, 0,
1693 &(const struct itimerspec){0}, NULL);
1694 }
1695 break;
1697 default:
1698 BUG("can only handle SIGTERM and SIGKILL");
1699 return false;
1700 }
1702 return true;
1703}
1705bool
1706term_shutdown(struct terminal *term)
1707{
1708 if (term->shutdown.in_progress)
1709 return true;
1711 term->shutdown.in_progress = true;
1713 /*
1714 * Close FDs then postpone self-destruction to the next poll
1715 * iteration, by creating an event FD that we trigger immediately.
1716 */
1718 term_cursor_blink_update(term);
1719 xassert(term->cursor_blink.fd < 0);
1721 fdm_del(term->fdm, term->selection.auto_scroll.fd);
1722 fdm_del(term->fdm, term->render.app_sync_updates.timer_fd);
1723 fdm_del(term->fdm, term->render.app_id.timer_fd);
1724 fdm_del(term->fdm, term->render.icon.timer_fd);
1725 fdm_del(term->fdm, term->render.title.timer_fd);
1726 fdm_del(term->fdm, term->delayed_render_timer.lower_fd);
1727 fdm_del(term->fdm, term->delayed_render_timer.upper_fd);
1728 fdm_del(term->fdm, term->blink.fd);
1729 fdm_del(term->fdm, term->flash.fd);
1731 del_utmp_record(term->conf, term->reaper, term->ptmx);
1733 if (term->window != NULL && term->window->is_configured)
1734 fdm_del(term->fdm, term->ptmx);
1735 else
1736 close(term->ptmx);
1738 if (!term->shutdown.client_has_terminated) {
1739 if (term->slave <= 0) {
1740 term->shutdown.client_has_terminated = true;
1741 } else {
1742 LOG_DBG("initiating asynchronous terminate of slave; "
1743 "sending SIGHUP to PID=%u", term->slave);
1745 kill(-term->slave, SIGHUP);
1747 /*
1748 * Set up a timer, with an interval - on the first timeout
1749 * we'll send SIGTERM. If the the client application still
1750 * isn't terminating, we'll wait an additional interval,
1751 * and then send SIGKILL.
1752 */
1753 const struct itimerspec timeout = {.it_value = {.tv_sec = 30},
1754 .it_interval = {.tv_sec = 30}};
1756 int timeout_fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
1757 if (timeout_fd < 0 ||
1758 timerfd_settime(timeout_fd, 0, &timeout, NULL) < 0 ||
1759 !fdm_add(term->fdm, timeout_fd, EPOLLIN, &fdm_terminate_timeout, term))
1760 {
1761 if (timeout_fd >= 0)
1762 close(timeout_fd);
1763 LOG_ERRNO("failed to create slave terminate timeout FD");
1764 return false;
1765 }
1767 xassert(term->shutdown.terminate_timeout_fd < 0);
1768 term->shutdown.terminate_timeout_fd = timeout_fd;
1769 term->shutdown.next_signal = SIGTERM;
1770 }
1771 }
1773 term->selection.auto_scroll.fd = -1;
1774 term->render.app_sync_updates.timer_fd = -1;
1775 term->render.app_id.timer_fd = -1;
1776 term->render.icon.timer_fd = -1;
1777 term->render.title.timer_fd = -1;
1778 term->delayed_render_timer.lower_fd = -1;
1779 term->delayed_render_timer.upper_fd = -1;
1780 term->blink.fd = -1;
1781 term->flash.fd = -1;
1782 term->ptmx = -1;
1784 int event_fd = eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK);
1785 if (event_fd == -1) {
1786 LOG_ERRNO("failed to create terminal shutdown event FD");
1787 return false;
1788 }
1790 if (!fdm_add(term->fdm, event_fd, EPOLLIN, &fdm_shutdown, term)) {
1791 close(event_fd);
1792 return false;
1793 }
1795 if (write(event_fd, &(uint64_t){1}, sizeof(uint64_t)) != sizeof(uint64_t)) {
1796 LOG_ERRNO("failed to send terminal shutdown event");
1797 fdm_del(term->fdm, event_fd);
1798 return false;
1799 }
1801 return true;
1802}
1804static volatile sig_atomic_t alarm_raised;
1806static void
1807sig_alarm(int signo)
1808{
1809 LOG_DBG("SIGALRM");
1810 alarm_raised = 1;
1811}
1813int
1814term_destroy(struct terminal *term)
1815{
1816 if (term == NULL)
1817 return 0;
1819 tll_foreach(term->wl->terms, it) {
1820 if (it->item == term) {
1821 tll_remove(term->wl->terms, it);
1822 break;
1823 }
1824 }
1826 del_utmp_record(term->conf, term->reaper, term->ptmx);
1828 fdm_del(term->fdm, term->selection.auto_scroll.fd);
1829 fdm_del(term->fdm, term->render.app_sync_updates.timer_fd);
1830 fdm_del(term->fdm, term->render.app_id.timer_fd);
1831 fdm_del(term->fdm, term->render.icon.timer_fd);
1832 fdm_del(term->fdm, term->render.title.timer_fd);
1833 fdm_del(term->fdm, term->delayed_render_timer.lower_fd);
1834 fdm_del(term->fdm, term->delayed_render_timer.upper_fd);
1835 fdm_del(term->fdm, term->cursor_blink.fd);
1836 fdm_del(term->fdm, term->blink.fd);
1837 fdm_del(term->fdm, term->flash.fd);
1838 fdm_del(term->fdm, term->ptmx);
1839 if (term->shutdown.terminate_timeout_fd >= 0)
1840 fdm_del(term->fdm, term->shutdown.terminate_timeout_fd);
1842 if (term->window != NULL) {
1843 wayl_win_destroy(term->window);
1844 term->window = NULL;
1845 }
1847 mtx_lock(&term->render.workers.lock);
1848 xassert(tll_length(term->render.workers.queue) == 0);
1850 /* Count livinig threads - we may get here when only some of the
1851 * threads have been successfully started */
1852 size_t worker_count = 0;
1853 if (term->render.workers.threads != NULL) {
1854 for (size_t i = 0; i < term->render.workers.count; i++, worker_count++) {
1855 if (term->render.workers.threads[i] == 0)
1856 break;
1857 }
1859 for (size_t i = 0; i < worker_count; i++) {
1860 sem_post(&term->render.workers.start);
1861 tll_push_back(term->render.workers.queue, -2);
1862 }
1863 }
1864 mtx_unlock(&term->render.workers.lock);
1866 key_binding_unref(term->wl->key_binding_manager, term->conf);
1868 urls_reset(term);
1870 free(term->vt.osc.data);
1871 free(term->vt.osc8.uri);
1873 composed_free(term->composed);
1875 free(term->app_id);
1876 free(term->window_title);
1877 tll_free_and_free(term->window_title_stack, free);
1879 for (size_t i = 0; i < sizeof(term->fonts) / sizeof(term->fonts[0]); i++)
1880 fcft_destroy(term->fonts[i]);
1881 for (size_t i = 0; i < 4; i++)
1882 free(term->font_sizes[i]);
1885 free_custom_glyphs(
1886 &term->custom_glyphs.box_drawing, GLYPH_BOX_DRAWING_COUNT);
1887 free_custom_glyphs(
1888 &term->custom_glyphs.braille, GLYPH_BRAILLE_COUNT);
1889 free_custom_glyphs(
1890 &term->custom_glyphs.legacy, GLYPH_LEGACY_COUNT);
1891 free_custom_glyphs(
1892 &term->custom_glyphs.octants, GLYPH_OCTANTS_COUNT);
1894 free(term->search.buf);
1895 free(term->search.last.buf);
1897 if (term->render.workers.threads != NULL) {
1898 for (size_t i = 0; i < term->render.workers.count; i++) {
1899 if (term->render.workers.threads[i] != 0)
1900 thrd_join(term->render.workers.threads[i], NULL);
1901 }
1902 }
1903 free(term->render.workers.threads);
1904 mtx_destroy(&term->render.workers.preapplied_damage.lock);
1905 cnd_destroy(&term->render.workers.preapplied_damage.cond);
1906 mtx_destroy(&term->render.workers.lock);
1907 sem_destroy(&term->render.workers.start);
1908 sem_destroy(&term->render.workers.done);
1909 xassert(tll_length(term->render.workers.queue) == 0);
1910 tll_free(term->render.workers.queue);
1912 shm_unref(term->render.last_buf);
1913 shm_chain_free(term->render.chains.grid);
1914 shm_chain_free(term->render.chains.search);
1915 shm_chain_free(term->render.chains.scrollback_indicator);
1916 shm_chain_free(term->render.chains.render_timer);
1917 shm_chain_free(term->render.chains.url);
1918 shm_chain_free(term->render.chains.csd);
1919 shm_chain_free(term->render.chains.overlay);
1920 pixman_region32_fini(&term->render.last_overlay_clip);
1922 tll_free(term->tab_stops);
1924 tll_foreach(term->ptmx_buffers, it) {
1925 free(it->item.data);
1926 tll_remove(term->ptmx_buffers, it);
1927 }
1928 tll_foreach(term->ptmx_paste_buffers, it) {
1929 free(it->item.data);
1930 tll_remove(term->ptmx_paste_buffers, it);
1931 }
1933 notify_free(term, &term->kitty_notification);
1934 tll_foreach(term->active_notifications, it) {
1935 notify_free(term, &it->item);
1936 tll_remove(term->active_notifications, it);
1937 }
1939 for (size_t i = 0; i < ALEN(term->notification_icons); i++)
1940 notify_icon_free(&term->notification_icons[i]);
1942 sixel_fini(term);
1944 term_ime_reset(term);
1946 grid_free(&term->normal);
1947 grid_free(&term->alt);
1948 grid_free(term->interactive_resizing.grid);
1949 free(term->interactive_resizing.grid);
1951 free(term->foot_exe);
1952 free(term->cwd);
1953 free(term->mouse_user_cursor);
1954 free(term->color_stack.stack);
1956 int ret = EXIT_SUCCESS;
1958 if (term->slave > 0) {
1959 /* We'll deal with this explicitly */
1960 reaper_del(term->reaper, term->slave);
1962 int exit_status;
1964 if (term->shutdown.client_has_terminated)
1965 exit_status = term->shutdown.exit_status;
1966 else {
1967 LOG_DBG("initiating blocking terminate of slave; "
1968 "sending SIGHUP to PID=%u", term->slave);
1970 kill(-term->slave, SIGHUP);
1972 /*
1973 * we've closed the ptxm, and sent SIGTERM to the client
1974 * application. It *should* exit...
1975 *
1976 * But, since it is possible to write clients that ignore
1977 * this, we need to handle it in *some* way.
1978 *
1979 * So, what we do is register a SIGALRM handler, and configure a 30
1980 * second alarm. If the slave hasn't died after this time, we send
1981 * it a SIGKILL,
1982 *
1983 * Note that this solution is *not* asynchronous, and any
1984 * other events etc will be ignored during this time. This of
1985 * course only applies to a 'foot --server' instance, where
1986 * there might be other terminals running.
1987 */
1988 struct sigaction action = {.sa_handler = &sig_alarm};
1989 sigemptyset(&action.sa_mask);
1990 sigaction(SIGALRM, &action, NULL);
1992 /* Wait, then send SIGTERM, wait again, then send SIGKILL */
1993 int next_signal = SIGTERM;
1995 alarm_raised = 0;
1996 alarm(30);
1998 while (true) {
1999 int r = waitpid(term->slave, &exit_status, 0);
2001 if (r == term->slave)
2002 break;
2004 if (r == -1) {
2005 xassert(errno == EINTR);
2007 if (alarm_raised) {
2008 LOG_DBG("slave (PID=%u) has not terminated yet, "
2009 "sending: %s (%d)", term->slave,
2010 next_signal == SIGTERM ? "SIGTERM" : "SIGKILL",
2011 next_signal);
2013 kill(-term->slave, next_signal);
2014 next_signal = SIGKILL;
2016 alarm_raised = 0;
2017 alarm(30);
2018 }
2019 }
2020 }
2022 /* Cancel alarm */
2023 alarm(0);
2024 action.sa_handler = SIG_DFL;
2025 sigaction(SIGALRM, &action, NULL);
2026 }
2028 ret = EXIT_FAILURE;
2029 if (WIFEXITED(exit_status)) {
2030 ret = WEXITSTATUS(exit_status);
2031 LOG_DBG("slave exited with code %d", ret);
2032 } else if (WIFSIGNALED(exit_status)) {
2033 ret = WTERMSIG(exit_status);
2034 LOG_WARN("slave exited with signal %d (%s)", ret, strsignal(ret));
2035 } else {
2036 LOG_WARN("slave exited for unknown reason (status = 0x%08x)",
2037 exit_status);
2038 }
2039 }
2041 free(term);
2043#if defined(__GLIBC__)
2044 if (!malloc_trim(0))
2045 LOG_WARN("failed to trim memory");
2046#endif
2048 return ret;
2049}
2051static inline void
2052erase_cell_range(struct terminal *term, struct row *row, int start, int end)
2053{
2054 xassert(start < term->cols);
2055 xassert(end < term->cols);
2057 row->dirty = true;
2059 const enum color_source bg_src = term->vt.attrs.bg_src;
2061 if (unlikely(bg_src != COLOR_DEFAULT)) {
2062 for (int col = start; col <= end; col++) {
2063 struct cell *c = &row->cells[col];
2064 c->wc = 0;
2065 c->attrs = (struct attributes){.bg_src = bg_src, .bg = term->vt.attrs.bg};
2066 }
2067 } else
2068 memset(&row->cells[start], 0, (end - start + 1) * sizeof(row->cells[0]));
2070 if (unlikely(row->extra != NULL)) {
2071 grid_row_uri_range_erase(row, start, end);
2072 grid_row_underline_range_erase(row, start, end);
2073 }
2074}
2076static inline void
2077erase_line(struct terminal *term, struct row *row)
2078{
2079 erase_cell_range(term, row, 0, term->cols - 1);
2080 row->linebreak = true;
2081 row->shell_integration.prompt_marker = false;
2082 row->shell_integration.cmd_start = -1;
2083 row->shell_integration.cmd_end = -1;
2084}
2086static void
2087term_theme_apply(struct terminal *term, const struct color_theme *theme)
2088{
2089 term->colors.fg = theme->fg;
2090 term->colors.bg = theme->bg;
2091 term->colors.alpha = theme->alpha;
2092 term->colors.cursor_fg = (theme->use_custom.cursor ? 1u << 31 : 0) | theme->cursor.text;
2093 term->colors.cursor_bg = (theme->use_custom.cursor ? 1u << 31 : 0) | theme->cursor.cursor;
2094 term->colors.selection_fg = theme->selection_fg;
2095 term->colors.selection_bg = theme->selection_bg;
2096 memcpy(term->colors.table, theme->table, sizeof(term->colors.table));
2097}
2099void
2100term_reset(struct terminal *term, bool hard)
2101{
2102 LOG_INFO("%s resetting the terminal", hard ? "hard" : "soft");
2104 term->cursor_keys_mode = CURSOR_KEYS_NORMAL;
2105 term->keypad_keys_mode = KEYPAD_NUMERICAL;
2106 term->reverse = false;
2107 term->hide_cursor = false;
2108 term->reverse_wrap = true;
2109 term->auto_margin = true;
2110 term->insert_mode = false;
2111 term->bracketed_paste = false;
2112 term->focus_events = false;
2113 term->visibility_reports = false;
2114 term->num_lock_modifier = true;
2115 term->bell_action_enabled = true;
2116 term->mouse_tracking = MOUSE_NONE;
2117 term->mouse_reporting = MOUSE_NORMAL;
2118 term->charsets.selected = G0;
2119 term->charsets.set[G0] = CHARSET_ASCII;
2120 term->charsets.set[G1] = CHARSET_ASCII;
2121 term->charsets.set[G2] = CHARSET_ASCII;
2122 term->charsets.set[G3] = CHARSET_ASCII;
2123 term->saved_charsets = term->charsets;
2124 tll_free_and_free(term->window_title_stack, free);
2125 term_set_window_title(term, term->conf->title);
2126 term_set_app_id(term, NULL);
2128 term_set_user_mouse_cursor(term, NULL);
2130 term->modify_other_keys_2 = false;
2131 memset(term->normal.kitty_kbd.flags, 0, sizeof(term->normal.kitty_kbd.flags));
2132 memset(term->alt.kitty_kbd.flags, 0, sizeof(term->alt.kitty_kbd.flags));
2133 term->normal.kitty_kbd.idx = term->alt.kitty_kbd.idx = 0;
2135 term->scroll_region.start = 0;
2136 term->scroll_region.end = term->rows;
2138 free(term->vt.osc8.uri);
2139 free(term->vt.osc.data);
2141 term->vt = (struct vt){
2142 .state = 0, /* STATE_GROUND */
2143 };
2145 if (term->grid == &term->alt) {
2146 term->grid = &term->normal;
2147 selection_cancel(term);
2148 }
2150 term->meta.esc_prefix = true;
2151 term->meta.eight_bit = true;
2153 tll_foreach(term->normal.sixel_images, it) {
2154 sixel_destroy(&it->item);
2155 tll_remove(term->normal.sixel_images, it);
2156 }
2157 tll_foreach(term->alt.sixel_images, it) {
2158 sixel_destroy(&it->item);
2159 tll_remove(term->alt.sixel_images, it);
2160 }
2162 notify_free(term, &term->kitty_notification);
2163 tll_foreach(term->active_notifications, it) {
2164 notify_free(term, &it->item);
2165 tll_remove(term->active_notifications, it);
2166 }
2168 for (size_t i = 0; i < ALEN(term->notification_icons); i++)
2169 notify_icon_free(&term->notification_icons[i]);
2171 term->grapheme_shaping = term->conf->tweak.grapheme_shaping;
2173#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
2174 term_ime_enable(term);
2175#endif
2177 term->bits_affecting_ascii_printer.value = 0;
2178 term_update_ascii_printer(term);
2180 if (!hard)
2181 return;
2183 const struct color_theme *theme = NULL;
2185 switch (term->conf->initial_color_theme) {
2186 case COLOR_THEME_DARK: theme = &term->conf->colors_dark; break;
2187 case COLOR_THEME_LIGHT: theme = &term->conf->colors_light; break;
2188 case COLOR_THEME_1: BUG("COLOR_THEME_1 should not be used"); break;
2189 case COLOR_THEME_2: BUG("COLOR_THEME_2 should not be used"); break;
2190 }
2192 term->flash.active = false;
2193 term->blink.state = BLINK_ON;
2194 fdm_del(term->fdm, term->blink.fd); term->blink.fd = -1;
2195 term_theme_apply(term, theme);
2196 term->colors.active_theme = term->conf->initial_color_theme;
2197 free(term->color_stack.stack);
2198 term->color_stack.stack = NULL;
2199 term->color_stack.size = 0;
2200 term->color_stack.idx = 0;
2201 term->origin = ORIGIN_ABSOLUTE;
2202 term->normal.cursor.lcf = false;
2203 term->alt.cursor.lcf = false;
2204 term->normal.cursor = (struct cursor){.point = {0, 0}};
2205 term->normal.saved_cursor = (struct cursor){.point = {0, 0}};
2206 term->alt.cursor = (struct cursor){.point = {0, 0}};
2207 term->alt.saved_cursor = (struct cursor){.point = {0, 0}};
2208 term->cursor_style = term->conf->cursor.style;
2209 term->cursor_blink.decset = false;
2210 term->cursor_blink.deccsusr = term->conf->cursor.blink.enabled;
2211 term_cursor_blink_update(term);
2212 selection_cancel(term);
2213 term->normal.offset = term->normal.view = 0;
2214 term->alt.offset = term->alt.view = 0;
2215 for (size_t i = 0; i < term->rows; i++) {
2216 struct row *r = grid_row_and_alloc(&term->normal, i);
2217 erase_line(term, r);
2218 }
2219 for (size_t i = 0; i < term->rows; i++) {
2220 struct row *r = grid_row_and_alloc(&term->alt, i);
2221 erase_line(term, r);
2222 }
2223 for (size_t i = term->rows; i < term->normal.num_rows; i++) {
2224 grid_row_free(term->normal.rows[i]);
2225 term->normal.rows[i] = NULL;
2226 }
2227 for (size_t i = term->rows; i < term->alt.num_rows; i++) {
2228 grid_row_free(term->alt.rows[i]);
2229 term->alt.rows[i] = NULL;
2230 }
2231 term->normal.cur_row = term->normal.rows[0];
2232 term->alt.cur_row = term->alt.rows[0];
2233 tll_free(term->normal.scroll_damage);
2234 tll_free(term->alt.scroll_damage);
2235 term->render.last_cursor.row = NULL;
2236 term_damage_all(term);
2238 term->sixel.scrolling = true;
2239 term->sixel.cursor_right_of_graphics = false;
2240 term->sixel.use_private_palette = true;
2241 term->sixel.max_width = SIXEL_MAX_WIDTH;
2242 term->sixel.max_height = SIXEL_MAX_HEIGHT;
2243 term->sixel.palette_size = SIXEL_MAX_COLORS;
2244 free(term->sixel.private_palette);
2245 free(term->sixel.shared_palette);
2246 term->sixel.private_palette = term->sixel.shared_palette = NULL;
2247}
2249static bool
2250term_font_size_adjust_by_points(struct terminal *term, float amount)
2251{
2252 const struct config *conf = term->conf;
2253 const float dpi = term->font_is_sized_by_dpi ? term->font_dpi : 96.;
2255 for (size_t i = 0; i < 4; i++) {
2256 const struct config_font_list *font_list = &conf->fonts[i];
2258 for (size_t j = 0; j < font_list->count; j++) {
2259 struct config_font *font = &term->font_sizes[i][j];
2260 float old_pt_size = font->pt_size;
2262 if (font->px_size > 0)
2263 old_pt_size = font->px_size * 72. / dpi;
2265 font->pt_size = fmaxf(old_pt_size + amount, 0.);
2266 font->px_size = -1;
2267 }
2268 }
2270 return reload_fonts(term, true);
2271}
2273static bool
2274term_font_size_adjust_by_pixels(struct terminal *term, int amount)
2275{
2276 const struct config *conf = term->conf;
2277 const float dpi = term->font_is_sized_by_dpi ? term->font_dpi : 96.;
2279 for (size_t i = 0; i < 4; i++) {
2280 const struct config_font_list *font_list = &conf->fonts[i];
2282 for (size_t j = 0; j < font_list->count; j++) {
2283 struct config_font *font = &term->font_sizes[i][j];
2284 int old_px_size = font->px_size;
2286 if (font->px_size <= 0)
2287 old_px_size = font->pt_size * dpi / 72.;
2289 font->px_size = max(old_px_size + amount, 1);
2290 }
2291 }
2293 return reload_fonts(term, true);
2294}
2296static bool
2297term_font_size_adjust_by_percent(struct terminal *term, bool increment, float percent)
2298{
2299 const struct config *conf = term->conf;
2300 const float multiplier = increment
2301 ? 1. + percent
2302 : 1. / (1. + percent);
2304 for (size_t i = 0; i < 4; i++) {
2305 const struct config_font_list *font_list = &conf->fonts[i];
2307 for (size_t j = 0; j < font_list->count; j++) {
2308 struct config_font *font = &term->font_sizes[i][j];
2310 if (font->px_size > 0)
2311 font->px_size = max(font->px_size * multiplier, 1);
2312 else
2313 font->pt_size = fmax(font->pt_size * multiplier, 0);
2314 }
2315 }
2317 return reload_fonts(term, true);
2318}
2320bool
2321term_font_size_increase(struct terminal *term)
2322{
2323 const struct config *conf = term->conf;
2324 const struct font_size_adjustment *inc_dec = &conf->font_size_adjustment;
2326 if (inc_dec->percent > 0.)
2327 return term_font_size_adjust_by_percent(term, true, inc_dec->percent);
2328 else if (inc_dec->pt_or_px.px > 0)
2329 return term_font_size_adjust_by_pixels(term, inc_dec->pt_or_px.px);
2330 else
2331 return term_font_size_adjust_by_points(term, inc_dec->pt_or_px.pt);
2332}
2334bool
2335term_font_size_decrease(struct terminal *term)
2336{
2337 const struct config *conf = term->conf;
2338 const struct font_size_adjustment *inc_dec = &conf->font_size_adjustment;
2340 if (inc_dec->percent > 0.)
2341 return term_font_size_adjust_by_percent(term, false, inc_dec->percent);
2342 else if (inc_dec->pt_or_px.px > 0)
2343 return term_font_size_adjust_by_pixels(term, -inc_dec->pt_or_px.px);
2344 else
2345 return term_font_size_adjust_by_points(term, -inc_dec->pt_or_px.pt);
2346}
2348bool
2349term_font_size_reset(struct terminal *term)
2350{
2351 return load_fonts_from_conf(term);
2352}
2354bool
2355term_fractional_scaling(const struct terminal *term)
2356{
2357 return term->wl->fractional_scale_manager != NULL &&
2358 term->wl->viewporter != NULL &&
2359 term->window->scale > 0.;
2360}
2362bool
2363term_preferred_buffer_scale(const struct terminal *term)
2364{
2365 return term->window->preferred_buffer_scale > 0;
2366}
2368bool
2369term_update_scale(struct terminal *term)
2370{
2371 const struct wl_window *win = term->window;
2373 /*
2374 * We have a number of "sources" we can use as scale. We choose
2375 * the scale in the following order:
2376 *
2377 * - "preferred" scale, from the fractional-scale-v1 protocol
2378 * - "preferred" scale, from wl_compositor version 6.
2379 NOTE: if the compositor advertises version 6 we must use 1.0
2380 until wl_surface.preferred_buffer_scale is sent
2381 * - scaling factor of output we most recently were mapped on
2382 * - if we're not mapped, use the last known scaling factor
2383 * - if we're not mapped, and we don't have a last known scaling
2384 * factor, use the scaling factor from the first available
2385 * output.
2386 * - if there aren't any outputs available, use 1.0
2387 */
2388 const float new_scale = (term_fractional_scaling(term)
2389 ? win->scale
2390 : term_preferred_buffer_scale(term)
2391 ? win->preferred_buffer_scale
2392 : tll_length(win->on_outputs) > 0
2393 ? tll_back(win->on_outputs)->scale
2394 : term->scale_before_unmap > 0.
2395 ? term->scale_before_unmap
2396 : tll_length(term->wl->monitors) > 0
2397 ? tll_front(term->wl->monitors).scale
2398 : 1.);
2400 if (new_scale == term->scale)
2401 return false;
2403 LOG_DBG("scaling factor changed: %.2f -> %.2f", term->scale, new_scale);
2404 term->scale_before_unmap = new_scale;
2405 term->scale = new_scale;
2406 return true;
2407}
2409bool
2410term_font_dpi_changed(struct terminal *term, float old_scale)
2411{
2412 float dpi = get_font_dpi(term);
2413 xassert(term->scale > 0.);
2415 bool was_scaled_using_dpi = term->font_is_sized_by_dpi;
2416 bool will_scale_using_dpi = term->conf->dpi_aware;
2418 bool need_font_reload =
2419 was_scaled_using_dpi != will_scale_using_dpi ||
2420 (will_scale_using_dpi
2421 ? term->font_dpi != dpi
2422 : old_scale != term->scale);
2424 if (need_font_reload) {
2425 LOG_DBG("DPI/scale change: DPI-aware=%s, "
2426 "DPI: %.2f -> %.2f, scale: %.2f -> %.2f, "
2427 "sizing font based on monitor's %s",
2428 term->conf->dpi_aware ? "yes" : "no",
2429 term->font_dpi, dpi, old_scale, term->scale,
2430 will_scale_using_dpi ? "DPI" : "scaling factor");
2431 }
2433 term->font_dpi = dpi;
2434 term->font_dpi_before_unmap = dpi;
2435 term->font_is_sized_by_dpi = will_scale_using_dpi;
2437 if (!need_font_reload)
2438 return false;
2440 return reload_fonts(term, false);
2441}
2443void
2444term_font_subpixel_changed(struct terminal *term)
2445{
2446 enum fcft_subpixel subpixel = get_font_subpixel(term);
2448 if (term->font_subpixel == subpixel)
2449 return;
2451#if defined(_DEBUG) && LOG_ENABLE_DBG
2452 static const char *const str[] = {
2453 [FCFT_SUBPIXEL_DEFAULT] = "default",
2454 [FCFT_SUBPIXEL_NONE] = "disabled",
2455 [FCFT_SUBPIXEL_HORIZONTAL_RGB] = "RGB",
2456 [FCFT_SUBPIXEL_HORIZONTAL_BGR] = "BGR",
2457 [FCFT_SUBPIXEL_VERTICAL_RGB] = "V-RGB",
2458 [FCFT_SUBPIXEL_VERTICAL_BGR] = "V-BGR",
2459 };
2461 LOG_DBG("subpixel mode changed: %s -> %s", str[term->font_subpixel], str[subpixel]);
2462#endif
2464 term->font_subpixel = subpixel;
2465 term_damage_view(term);
2466 render_refresh(term);
2467}
2469int
2470term_font_baseline(const struct terminal *term)
2471{
2472 const struct fcft_font *font = term->fonts[0];
2473 const int line_height = term->cell_height;
2474 const int font_height = font->ascent + font->descent;
2476 /*
2477 * Center glyph on the line *if* using a custom line height,
2478 * otherwise the baseline is simply 'descent' pixels above the
2479 * bottom of the cell
2480 */
2481 const int glyph_top_y = term->font_line_height.px >= 0
2482 ? round((line_height - font_height) / 2.)
2483 : 0;
2485 return term->font_y_ofs + line_height - glyph_top_y - font->descent;
2486}
2488void
2489term_damage_rows(struct terminal *term, int start, int end)
2490{
2491 xassert(start <= end);
2492 for (int r = start; r <= end; r++) {
2493 struct row *row = grid_row(term->grid, r);
2494 row->dirty = true;
2495 for (int c = 0; c < term->grid->num_cols; c++)
2496 row->cells[c].attrs.clean = 0;
2497 }
2498}
2500void
2501term_damage_rows_in_view(struct terminal *term, int start, int end)
2502{
2503 xassert(start <= end);
2504 for (int r = start; r <= end; r++) {
2505 struct row *row = grid_row_in_view(term->grid, r);
2506 row->dirty = true;
2507 for (int c = 0; c < term->grid->num_cols; c++)
2508 row->cells[c].attrs.clean = 0;
2509 }
2510}
2512void
2513term_damage_all(struct terminal *term)
2514{
2515 term_damage_rows(term, 0, term->rows - 1);
2516}
2518void
2519term_damage_view(struct terminal *term)
2520{
2521 term_damage_rows_in_view(term, 0, term->rows - 1);
2522}
2524void
2525term_damage_cursor(struct terminal *term)
2526{
2527 term->grid->cur_row->cells[term->grid->cursor.point.col].attrs.clean = 0;
2528 term->grid->cur_row->dirty = true;
2529}
2531void
2532term_damage_margins(struct terminal *term)
2533{
2534 term->render.margins = true;
2535}
2537void
2538term_damage_color(struct terminal *term, enum color_source src, int idx)
2539{
2540 xassert(src == COLOR_DEFAULT || src == COLOR_BASE256);
2542 for (int r = 0; r < term->rows; r++) {
2543 struct row *row = grid_row_in_view(term->grid, r);
2544 struct cell *cell = &row->cells[0];
2545 const struct cell *end = &row->cells[term->cols];
2547 for (; cell < end; cell++) {
2548 bool dirty = false;
2550 switch (cell->attrs.fg_src) {
2551 case COLOR_BASE16:
2552 case COLOR_BASE256:
2553 if (src == COLOR_BASE256 && cell->attrs.fg == idx)
2554 dirty = true;
2555 break;
2557 case COLOR_DEFAULT:
2558 if (src == COLOR_DEFAULT) {
2559 /* Doesn't matter whether we've updated the
2560 default foreground, or background, we still
2561 want to dirty this cell, to be sure we handle
2562 all cases of color inversion/reversal */
2563 dirty = true;
2564 }
2565 break;
2567 case COLOR_RGB:
2568 /* Not affected */
2569 break;
2570 }
2572 switch (cell->attrs.bg_src) {
2573 case COLOR_BASE16:
2574 case COLOR_BASE256:
2575 if (src == COLOR_BASE256 && cell->attrs.bg == idx)
2576 dirty = true;
2577 break;
2579 case COLOR_DEFAULT:
2580 if (src == COLOR_DEFAULT) {
2581 /* Doesn't matter whether we've updated the
2582 default foreground, or background, we still
2583 want to dirty this cell, to be sure we handle
2584 all cases of color inversion/reversal */
2585 dirty = true;
2586 }
2587 break;
2589 case COLOR_RGB:
2590 /* Not affected */
2591 break;
2592 }
2594 if (dirty) {
2595 cell->attrs.clean = 0;
2596 row->dirty = true;
2597 }
2598 }
2600 /* Colored underlines */
2601 if (row->extra != NULL) {
2602 const struct row_ranges *underlines = &row->extra->underline_ranges;
2604 for (int i = 0; i < underlines->count; i++) {
2605 const struct row_range *range = &underlines->v[i];
2607 /* Underline colors are either default, or
2608 BASE256/RGB, but never BASE16 */
2609 xassert(range->underline.color_src == COLOR_DEFAULT ||
2610 range->underline.color_src == COLOR_BASE256 ||
2611 range->underline.color_src == COLOR_RGB);
2613 if (range->underline.color_src == src) {
2614 struct cell *c = &row->cells[range->start];
2615 const struct cell *e = &row->cells[range->end + 1];
2617 for (; c < e; c++)
2618 c->attrs.clean = 0;
2620 row->dirty = true;
2621 }
2622 }
2623 }
2624 }
2625}
2627void
2628term_damage_scroll(struct terminal *term, enum damage_type damage_type,
2629 struct scroll_region region, int lines)
2630{
2631 if (likely(tll_length(term->grid->scroll_damage) > 0)) {
2632 struct damage *dmg = &tll_back(term->grid->scroll_damage);
2634 if (likely(
2635 dmg->type == damage_type &&
2636 dmg->region.start == region.start &&
2637 dmg->region.end == region.end))
2638 {
2639 /* Make sure we don't overflow... */
2640 int new_line_count = (int)dmg->lines + lines;
2641 if (likely(new_line_count <= UINT16_MAX)) {
2642 dmg->lines = new_line_count;
2643 return;
2644 }
2645 }
2646 }
2647 struct damage dmg = {
2648 .type = damage_type,
2649 .region = region,
2650 .lines = lines,
2651 };
2652 tll_push_back(term->grid->scroll_damage, dmg);
2653}
2655void
2656term_erase(struct terminal *term, int start_row, int start_col,
2657 int end_row, int end_col)
2658{
2659 xassert(start_row <= end_row);
2660 xassert(start_col <= end_col || start_row < end_row);
2662 if (start_row == end_row) {
2663 struct row *row = grid_row(term->grid, start_row);
2664 erase_cell_range(term, row, start_col, end_col);
2665 sixel_overwrite_by_row(term, start_row, start_col, end_col - start_col + 1);
2666 return;
2667 }
2669 xassert(end_row > start_row);
2671 erase_cell_range(
2672 term, grid_row(term->grid, start_row), start_col, term->cols - 1);
2673 sixel_overwrite_by_row(term, start_row, start_col, term->cols - start_col);
2675 for (int r = start_row + 1; r < end_row; r++)
2676 erase_line(term, grid_row(term->grid, r));
2677 sixel_overwrite_by_rectangle(
2678 term, start_row + 1, 0, end_row - start_row, term->cols);
2680 erase_cell_range(term, grid_row(term->grid, end_row), 0, end_col);
2681 sixel_overwrite_by_row(term, end_row, 0, end_col + 1);
2682}
2684void
2685term_erase_scrollback(struct terminal *term)
2686{
2687 const struct grid *grid = term->grid;
2688 const int num_rows = grid->num_rows;
2689 const int mask = num_rows - 1;
2691 const int scrollback_history_size = num_rows - term->rows;
2692 if (scrollback_history_size == 0)
2693 return;
2695 const int start = (grid->offset + term->rows) & mask;
2696 const int end = (grid->offset - 1) & mask;
2698 const int rel_start = grid_row_abs_to_sb(grid, term->rows, start);
2699 const int rel_end = grid_row_abs_to_sb(grid, term->rows, end);
2701 const int sel_start = selection_get_start(term).row;
2702 const int sel_end = selection_get_end(term).row;
2704 if (sel_end >= 0) {
2705 /*
2706 * Cancel selection if it touches any of the rows in the
2707 * scrollback, since we can't have the selection reference
2708 * soon-to-be deleted rows.
2709 *
2710 * This is done by range checking the selection range against
2711 * the scrollback range.
2712 *
2713 * To make this comparison simpler, the start/end absolute row
2714 * numbers are "rebased" against the scrollback start, where
2715 * row 0 is the *first* row in the scrollback. A high number
2716 * thus means the row is further *down* in the scrollback,
2717 * closer to the screen bottom.
2718 */
2720 const int rel_sel_start = grid_row_abs_to_sb(grid, term->rows, sel_start);
2721 const int rel_sel_end = grid_row_abs_to_sb(grid, term->rows, sel_end);
2723 if ((rel_sel_start <= rel_start && rel_sel_end >= rel_start) ||
2724 (rel_sel_start <= rel_end && rel_sel_end >= rel_end) ||
2725 (rel_sel_start >= rel_start && rel_sel_end <= rel_end))
2726 {
2727 selection_cancel(term);
2728 }
2729 }
2731 tll_foreach(term->grid->sixel_images, it) {
2732 struct sixel *six = &it->item;
2733 const int six_start = grid_row_abs_to_sb(grid, term->rows, six->pos.row);
2734 const int six_end = grid_row_abs_to_sb(
2735 grid, term->rows, six->pos.row + six->rows - 1);
2737 if ((six_start <= rel_start && six_end >= rel_start) ||
2738 (six_start <= rel_end && six_end >= rel_end) ||
2739 (six_start >= rel_start && six_end <= rel_end))
2740 {
2741 sixel_destroy(six);
2742 tll_remove(term->grid->sixel_images, it);
2743 }
2744 }
2746 for (int i = start;; i = (i + 1) & mask) {
2747 struct row *row = term->grid->rows[i];
2748 if (row != NULL) {
2749 if (term->render.last_cursor.row == row)
2750 term->render.last_cursor.row = NULL;
2752 grid_row_free(row);
2753 term->grid->rows[i] = NULL;
2754 }
2756 if (i == end)
2757 break;
2758 }
2760 term->grid->view = term->grid->offset;
2762#if defined(_DEBUG)
2763 for (int i = 0; i < term->rows; i++) {
2764 xassert(grid_row_in_view(term->grid, i) != NULL);
2765 }
2766#endif
2768 term_damage_view(term);
2769}
2771UNITTEST
2772{
2773 const int scrollback_rows = 16;
2774 const int term_rows = 5;
2775 const int cols = 5;
2777 struct fdm *fdm = fdm_init();
2778 xassert(fdm != NULL);
2780 struct terminal term = {
2781 .fdm = fdm,
2782 .rows = term_rows,
2783 .cols = cols,
2784 .normal = {
2785 .rows = xcalloc(scrollback_rows, sizeof(term.normal.rows[0])),
2786 .num_rows = scrollback_rows,
2787 .num_cols = cols,
2788 },
2789 .grid = &term.normal,
2790 .selection = {
2791 .coords = {
2792 .start = {-1, -1},
2793 .end = {-1, -1},
2794 },
2795 .kind = SELECTION_NONE,
2796 .auto_scroll = {
2797 .fd = -1,
2798 },
2799 },
2800 };
2802#define populate_scrollback() do { \
2803 for (int i = 0; i < scrollback_rows; i++) { \
2804 if (term.normal.rows[i] == NULL) { \
2805 struct row *r = xcalloc(1, sizeof(*term.normal.rows[i])); \
2806 r->cells = xcalloc(cols, sizeof(r->cells[0])); \
2807 term.normal.rows[i] = r; \
2808 } \
2809 } \
2810 } while (0)
2812 /*
2813 * Test case 1 - no selection, just verify all rows except those
2814 * on screen have been deleted.
2815 */
2817 populate_scrollback();
2818 term.normal.offset = 11;
2819 term_erase_scrollback(&term);
2820 for (int i = 0; i < scrollback_rows; i++) {
2821 if (i >= term.normal.offset && i < term.normal.offset + term_rows)
2822 xassert(term.normal.rows[i] != NULL);
2823 else
2824 xassert(term.normal.rows[i] == NULL);
2825 }
2827 /*
2828 * Test case 2 - selection that touches the scrollback. Verify the
2829 * selection is cancelled.
2830 */
2832 term.normal.offset = 14; /* Screen covers rows 14,15,0,1,2 */
2834 /* Selection covers rows 15,0,1,2,3 */
2835 term.selection.coords.start = (struct coord){.row = 15};
2836 term.selection.coords.end = (struct coord){.row = 19};
2837 term.selection.kind = SELECTION_CHAR_WISE;
2839 populate_scrollback();
2840 term_erase_scrollback(&term);
2841 xassert(term.selection.coords.start.row < 0);
2842 xassert(term.selection.coords.end.row < 0);
2843 xassert(term.selection.kind == SELECTION_NONE);
2845 /*
2846 * Test case 3 - selection that does *not* touch the
2847 * scrollback. Verify the selection is *not* cancelled.
2848 */
2850 /* Selection covers rows 15,0 */
2851 term.selection.coords.start = (struct coord){.row = 15};
2852 term.selection.coords.end = (struct coord){.row = 16};
2853 term.selection.kind = SELECTION_CHAR_WISE;
2855 populate_scrollback();
2856 term_erase_scrollback(&term);
2857 xassert(term.selection.coords.start.row == 15);
2858 xassert(term.selection.coords.end.row == 16);
2859 xassert(term.selection.kind == SELECTION_CHAR_WISE);
2861 term.selection.coords.start = (struct coord){-1, -1};
2862 term.selection.coords.end = (struct coord){-1, -1};
2863 term.selection.kind = SELECTION_NONE;
2865 /*
2866 * Test case 4 - sixel that touch the scrollback
2867 */
2869 struct sixel six = {
2870 .rows = 5,
2871 .pos = {
2872 .row = 15,
2873 },
2874 };
2875 tll_push_back(term.normal.sixel_images, six);
2876 populate_scrollback();
2877 term_erase_scrollback(&term);
2878 xassert(tll_length(term.normal.sixel_images) == 0);
2880 /*
2881 * Test case 5 - sixel that does *not* touch the scrollback
2882 */
2883 six.rows = 3;
2884 tll_push_back(term.normal.sixel_images, six);
2885 populate_scrollback();
2886 term_erase_scrollback(&term);
2887 xassert(tll_length(term.normal.sixel_images) == 1);
2889 /* Cleanup */
2890 tll_free(term.normal.sixel_images);
2891 xassert(term.selection.auto_scroll.fd == -1);
2892 for (int i = 0; i < scrollback_rows; i++)
2893 grid_row_free(term.normal.rows[i]);
2894 free(term.normal.rows);
2895 fdm_destroy(fdm);
2896}
2898int
2899term_row_rel_to_abs(const struct terminal *term, int row)
2900{
2901 switch (term->origin) {
2902 case ORIGIN_ABSOLUTE:
2903 return min(row, term->rows - 1);
2905 case ORIGIN_RELATIVE:
2906 return min(row + term->scroll_region.start, term->scroll_region.end - 1);
2907 }
2909 BUG("Invalid cursor_origin value");
2910 return -1;
2911}
2913void
2914term_cursor_to(struct terminal *term, int row, int col)
2915{
2916 xassert(row < term->rows);
2917 xassert(col < term->cols);
2919 term->grid->cursor.lcf = false;
2921 term->grid->cursor.point.col = col;
2922 term->grid->cursor.point.row = row;
2924 term_reset_grapheme_state(term);
2926 term->grid->cur_row = grid_row(term->grid, row);
2927}
2929void
2930term_cursor_home(struct terminal *term)
2931{
2932 term_cursor_to(term, term_row_rel_to_abs(term, 0), 0);
2933}
2935void
2936term_cursor_col(struct terminal *term, int col)
2937{
2938 xassert(col < term->cols);
2940 term->grid->cursor.lcf = false;
2941 term->grid->cursor.point.col = col;
2942 term_reset_grapheme_state(term);
2943}
2945void
2946term_cursor_left(struct terminal *term, int count)
2947{
2948 int move_amount = min(term->grid->cursor.point.col, count);
2949 term->grid->cursor.point.col -= move_amount;
2950 xassert(term->grid->cursor.point.col >= 0);
2951 term->grid->cursor.lcf = false;
2952 term_reset_grapheme_state(term);
2953}
2955void
2956term_cursor_right(struct terminal *term, int count)
2957{
2958 int move_amount = min(term->cols - term->grid->cursor.point.col - 1, count);
2959 term->grid->cursor.point.col += move_amount;
2960 xassert(term->grid->cursor.point.col < term->cols);
2961 term->grid->cursor.lcf = false;
2962 term_reset_grapheme_state(term);
2963}
2965void
2966term_cursor_up(struct terminal *term, int count)
2967{
2968 int top = term->origin == ORIGIN_ABSOLUTE ? 0 : term->scroll_region.start;
2969 xassert(term->grid->cursor.point.row >= top);
2971 int move_amount = min(term->grid->cursor.point.row - top, count);
2972 term_cursor_to(term, term->grid->cursor.point.row - move_amount, term->grid->cursor.point.col);
2973}
2975void
2976term_cursor_down(struct terminal *term, int count)
2977{
2978 int bottom = term->origin == ORIGIN_ABSOLUTE ? term->rows : term->scroll_region.end;
2979 xassert(bottom >= term->grid->cursor.point.row);
2981 int move_amount = min(bottom - term->grid->cursor.point.row - 1, count);
2982 term_cursor_to(term, term->grid->cursor.point.row + move_amount, term->grid->cursor.point.col);
2983}
2985static bool
2986cursor_blink_rearm_timer(struct terminal *term)
2987{
2988 if (term->cursor_blink.fd < 0) {
2989 int fd = timerfd_create(CLOCK_MONOTONIC, TFD_CLOEXEC | TFD_NONBLOCK);
2990 if (fd < 0) {
2991 LOG_ERRNO("failed to create cursor blink timer FD");
2992 return false;
2993 }
2995 if (!fdm_add(term->fdm, fd, EPOLLIN, &fdm_cursor_blink, term)) {
2996 close(fd);
2997 return false;
2998 }
3000 term->cursor_blink.fd = fd;
3001 }
3003 const int rate_ms = term->conf->cursor.blink.rate_ms;
3004 const long secs = rate_ms / 1000;
3005 const long nsecs = (rate_ms % 1000) * 1000000;
3007 const struct itimerspec timer = {
3008 .it_value = {.tv_sec = secs, .tv_nsec = nsecs},
3009 .it_interval = {.tv_sec = secs, .tv_nsec = nsecs},
3010 };
3012 if (timerfd_settime(term->cursor_blink.fd, 0, &timer, NULL) < 0) {
3013 LOG_ERRNO("failed to arm cursor blink timer");
3014 fdm_del(term->fdm, term->cursor_blink.fd);
3015 term->cursor_blink.fd = -1;
3016 return false;
3017 }
3019 return true;
3020}
3022static bool
3023cursor_blink_disarm_timer(struct terminal *term)
3024{
3025 fdm_del(term->fdm, term->cursor_blink.fd);
3026 term->cursor_blink.fd = -1;
3027 return true;
3028}
3030void
3031term_cursor_blink_update(struct terminal *term)
3032{
3033 bool enable = term->cursor_blink.decset || term->cursor_blink.deccsusr;
3034 bool activate = !term->shutdown.in_progress && enable && term->visual_focus;
3036 LOG_DBG("decset=%d, deccsrusr=%d, focus=%d, shutting-down=%d, enable=%d, activate=%d",
3037 term->cursor_blink.decset, term->cursor_blink.deccsusr,
3038 term->visual_focus, term->shutdown.in_progress,
3039 enable, activate);
3041 if (activate && term->cursor_blink.fd < 0) {
3042 term->cursor_blink.state = CURSOR_BLINK_ON;
3043 cursor_blink_rearm_timer(term);
3044 } else if (!activate && term->cursor_blink.fd >= 0)
3045 cursor_blink_disarm_timer(term);
3046}
3048static bool
3049selection_on_top_region(const struct terminal *term,
3050 struct scroll_region region)
3051{
3052 return region.start > 0 &&
3053 selection_on_rows(term, 0, region.start - 1);
3054}
3056static bool
3057selection_on_bottom_region(const struct terminal *term,
3058 struct scroll_region region)
3059{
3060 return region.end < term->rows &&
3061 selection_on_rows(term, region.end, term->rows - 1);
3062}
3064void
3065term_scroll_partial(struct terminal *term, struct scroll_region region, int rows)
3066{
3067 LOG_DBG("scroll: rows=%d, region.start=%d, region.end=%d",
3068 rows, region.start, region.end);
3070 /* Verify scroll amount has been clamped */
3071 xassert(rows <= region.end - region.start);
3073 /* Cancel selections that cannot be scrolled */
3074 if (unlikely(term->selection.coords.end.row >= 0)) {
3075 /*
3076 * Selection is (partly) inside either the top or bottom
3077 * scrolling regions, or on (at least one) of the lines
3078 * scrolled in (i.e. reused lines).
3079 */
3080 if (selection_on_top_region(term, region) ||
3081 selection_on_bottom_region(term, region))
3082 {
3083 selection_cancel(term);
3084 } else
3085 selection_scroll_up(term, rows);
3086 }
3088 sixel_scroll_up(term, rows);
3090 /* How many lines from the scrollback start is the current viewport? */
3091 int view_sb_start_distance = grid_row_abs_to_sb(
3092 term->grid, term->rows, term->grid->view);
3094 bool view_follows = term->grid->view == term->grid->offset;
3095 term->grid->offset += rows;
3096 term->grid->offset &= term->grid->num_rows - 1;
3098 if (likely(view_follows)) {
3099 term_damage_scroll(term, DAMAGE_SCROLL, region, rows);
3100 selection_view_down(term, term->grid->offset);
3101 term->grid->view = term->grid->offset;
3102 } else if (unlikely(rows > view_sb_start_distance)) {
3103 /* Part of current view is being scrolled out */
3104 int new_view = grid_row_sb_to_abs(term->grid, term->rows, 0);
3105 selection_view_down(term, new_view);
3106 cmd_scrollback_down(term, rows - view_sb_start_distance);
3107 }
3109 /* Top non-scrolling region. */
3110 for (int i = region.start - 1; i >= 0; i--)
3111 grid_swap_row(term->grid, i - rows, i);
3113 /* Bottom non-scrolling region */
3114 for (int i = term->rows - 1; i >= region.end; i--)
3115 grid_swap_row(term->grid, i - rows, i);
3117 /* Erase scrolled in lines */
3118 for (int r = region.end - rows; r < region.end; r++) {
3119 struct row *row = grid_row_and_alloc(term->grid, r);
3120 erase_line(term, row);
3121 }
3123 term->grid->cur_row = grid_row(term->grid, term->grid->cursor.point.row);
3125#if defined(_DEBUG)
3126 for (int r = 0; r < term->rows; r++)
3127 xassert(grid_row(term->grid, r) != NULL);
3128#endif
3129}
3131void
3132term_scroll(struct terminal *term, int rows)
3133{
3134 term_scroll_partial(term, term->scroll_region, rows);
3135}
3137void
3138term_scroll_reverse_partial(struct terminal *term,
3139 struct scroll_region region, int rows)
3140{
3141 LOG_DBG("scroll reverse: rows=%d, region.start=%d, region.end=%d",
3142 rows, region.start, region.end);
3144 /* Verify scroll amount has been clamped */
3145 xassert(rows <= region.end - region.start);
3147 /* Cancel selections that cannot be scrolled */
3148 if (unlikely(term->selection.coords.end.row >= 0)) {
3149 /*
3150 * Selection is (partly) inside either the top or bottom
3151 * scrolling regions, or on (at least one) of the lines
3152 * scrolled in (i.e. reused lines).
3153 */
3154 if (selection_on_top_region(term, region) ||
3155 selection_on_bottom_region(term, region))
3156 {
3157 selection_cancel(term);
3158 } else
3159 selection_scroll_down(term, rows);
3160 }
3162 /* Unallocate scrolled out lines */
3163 for (int r = region.end - rows; r < region.end; r++) {
3164 const int abs_r = grid_row_absolute(term->grid, r);
3165 struct row *row = term->grid->rows[abs_r];
3167 grid_row_free(row);
3168 term->grid->rows[abs_r] = NULL;
3170 if (term->render.last_cursor.row == row)
3171 term->render.last_cursor.row = NULL;
3172 }
3174 sixel_scroll_down(term, rows);
3176 const bool view_follows = term->grid->view == term->grid->offset;
3177 term->grid->offset -= rows;
3178 term->grid->offset += term->grid->num_rows;
3179 term->grid->offset &= term->grid->num_rows - 1;
3181 /* How many lines from the scrollback start is the current viewport? */
3182 const int view_sb_start_distance = grid_row_abs_to_sb(
3183 term->grid, term->rows, term->grid->view);
3184 const int offset_sb_start_distance = grid_row_abs_to_sb(
3185 term->grid, term->rows, term->grid->offset);
3187 xassert(term->grid->offset >= 0);
3188 xassert(term->grid->offset < term->grid->num_rows);
3190 if (view_follows) {
3191 term_damage_scroll(term, DAMAGE_SCROLL_REVERSE, region, rows);
3192 selection_view_up(term, term->grid->offset);
3193 term->grid->view = term->grid->offset;
3194 } else if (unlikely(view_sb_start_distance > offset_sb_start_distance)) {
3195 /* Part of current view is being scrolled out */
3196 int new_view = term->grid->offset;
3197 selection_view_up(term, new_view);
3198 term->grid->view = new_view;
3199 }
3201 /* Bottom non-scrolling region */
3202 for (int i = region.end + rows; i < term->rows + rows; i++)
3203 grid_swap_row(term->grid, i, i - rows);
3205 /* Top non-scrolling region */
3206 for (int i = 0 + rows; i < region.start + rows; i++)
3207 grid_swap_row(term->grid, i, i - rows);
3209 /* Erase scrolled in lines */
3210 for (int r = region.start; r < region.start + rows; r++) {
3211 struct row *row = grid_row_and_alloc(term->grid, r);
3212 erase_line(term, row);
3213 }
3215 if (unlikely(view_sb_start_distance > offset_sb_start_distance))
3216 term_damage_view(term);
3218 term->grid->cur_row = grid_row(term->grid, term->grid->cursor.point.row);
3220#if defined(_DEBUG)
3221 for (int r = 0; r < term->rows; r++)
3222 xassert(grid_row(term->grid, r) != NULL);
3223 for (int r = 0; r < term->rows; r++)
3224 xassert(grid_row_in_view(term->grid, r) != NULL);
3225#endif
3226}
3228void
3229term_scroll_reverse(struct terminal *term, int rows)
3230{
3231 term_scroll_reverse_partial(term, term->scroll_region, rows);
3232}
3234void
3235term_carriage_return(struct terminal *term)
3236{
3237 term_cursor_left(term, term->grid->cursor.point.col);
3238}
3240void
3241term_linefeed(struct terminal *term)
3242{
3243 term->grid->cursor.lcf = false;
3245 if (term->grid->cursor.point.row == term->scroll_region.end - 1)
3246 term_scroll(term, 1);
3247 else
3248 term_cursor_down(term, 1);
3250 term_reset_grapheme_state(term);
3251}
3253void
3254term_reverse_index(struct terminal *term)
3255{
3256 if (term->grid->cursor.point.row == term->scroll_region.start)
3257 term_scroll_reverse(term, 1);
3258 else
3259 term_cursor_up(term, 1);
3260}
3262void
3263term_reset_view(struct terminal *term)
3264{
3265 if (term->grid->view == term->grid->offset)
3266 return;
3268 term->grid->view = term->grid->offset;
3269 term_damage_view(term);
3270}
3272void
3273term_save_cursor(struct terminal *term)
3274{
3275 term->grid->saved_cursor = term->grid->cursor;
3276 term->grid->saved_attrs = term->vt.attrs;
3277 term->saved_charsets = term->charsets;
3278}
3280void
3281term_restore_cursor(struct terminal *term, const struct cursor *cursor)
3282{
3283 int row = min(cursor->point.row, term->rows - 1);
3284 int col = min(cursor->point.col, term->cols - 1);
3286 term_cursor_to(term, row, col);
3287 term->grid->cursor.lcf = cursor->lcf;
3289 term->vt.attrs = term->grid->saved_attrs;
3290 term->charsets = term->saved_charsets;
3292 term->bits_affecting_ascii_printer.charset =
3293 term->charsets.set[term->charsets.selected] != CHARSET_ASCII;
3294 term_update_ascii_printer(term);
3295}
3297void
3298term_visual_focus_in(struct terminal *term)
3299{
3300 if (term->visual_focus)
3301 return;
3303 term->visual_focus = true;
3304 term_cursor_blink_update(term);
3305 render_refresh_csd(term);
3306}
3308void
3309term_visual_focus_out(struct terminal *term)
3310{
3311 if (!term->visual_focus)
3312 return;
3314 term->visual_focus = false;
3315 term_cursor_blink_update(term);
3316 render_refresh_csd(term);
3317}
3319void
3320term_send_visibility_report(struct terminal *term)
3321{
3322 term_to_slave(
3323 term,
3324 !term->window->is_suspended ? "\033[?999;1n" : "\033[?999;2n", 9);
3325}
3327void
3328term_kbd_focus_in(struct terminal *term)
3329{
3330 if (term->kbd_focus)
3331 return;
3333 term->kbd_focus = true;
3335 if (term->render.urgency) {
3336 term->render.urgency = false;
3337 term_damage_margins(term);
3338 }
3340 cursor_refresh(term);
3342 if (term->focus_events)
3343 term_to_slave(term, "\033[I", 3);
3344}
3346void
3347term_kbd_focus_out(struct terminal *term)
3348{
3349 if (!term->kbd_focus)
3350 return;
3352 tll_foreach(term->wl->seats, it)
3353 if (it->item.kbd_focus == term)
3354 return;
3356#if defined(FOOT_IME_ENABLED) && FOOT_IME_ENABLED
3357 if (term_ime_reset(term))
3358 render_refresh(term);
3359#endif
3361 term->kbd_focus = false;
3362 cursor_refresh(term);
3364 if (term->focus_events)
3365 term_to_slave(term, "\033[O", 3);
3366}
3368static int
3369linux_mouse_button_to_x(int button)
3370{
3371 /* Note: on X11, scroll events where reported as buttons. Not so
3372 * on Wayland. We manually map scroll events to custom "button"
3373 * defines (BTN_WHEEL_*).
3374 */
3375 switch (button) {
3376 case BTN_LEFT: return 1;
3377 case BTN_MIDDLE: return 2;
3378 case BTN_RIGHT: return 3;
3379 case BTN_WHEEL_BACK: return 4; /* Foot custom define */
3380 case BTN_WHEEL_FORWARD: return 5; /* Foot custom define */
3381 case BTN_WHEEL_LEFT: return 6; /* Foot custom define */
3382 case BTN_WHEEL_RIGHT: return 7; /* Foot custom define */
3383 case BTN_SIDE: return 8;
3384 case BTN_EXTRA: return 9;
3385 case BTN_FORWARD: return 10;
3386 case BTN_BACK: return 11;
3387 case BTN_TASK: return 12; /* Guessing... */
3389 default:
3390 LOG_WARN("unrecognized mouse button: %d (0x%x)", button, button);
3391 return -1;
3392 }
3393}
3395static int
3396encode_xbutton(int xbutton)
3397{
3398 switch (xbutton) {
3399 case 1: case 2: case 3:
3400 return xbutton - 1;
3402 case 4: case 5: case 6: case 7:
3403 /* Like button 1 and 2, but with 64 added */
3404 return xbutton - 4 + 64;
3406 case 8: case 9: case 10: case 11:
3407 /* Similar to 4 and 5, but adding 128 instead of 64 */
3408 return xbutton - 8 + 128;
3410 default:
3411 LOG_ERR("cannot encode X mouse button: %d", xbutton);
3412 return -1;
3413 }
3414}
3416static void
3417report_mouse_click(struct terminal *term, int encoded_button, int row, int col,
3418 int row_pixels, int col_pixels, bool release)
3419{
3420 char response[128];
3422 switch (term->mouse_reporting) {
3423 case MOUSE_NORMAL: {
3424 int encoded_col = 32 + col + 1;
3425 int encoded_row = 32 + row + 1;
3426 if (encoded_col > 255 || encoded_row > 255)
3427 return;
3429 snprintf(response, sizeof(response), "\033[M%c%c%c",
3430 32 + (release ? 3 : encoded_button), encoded_col, encoded_row);
3431 break;
3432 }
3434 case MOUSE_SGR:
3435 snprintf(response, sizeof(response), "\033[<%d;%d;%d%c",
3436 encoded_button, col + 1, row + 1, release ? 'm' : 'M');
3437 break;
3439 case MOUSE_SGR_PIXELS: {
3440 const int bounded_col = max(col_pixels, 0);
3441 const int bounded_row = max(row_pixels, 0);
3442 snprintf(response, sizeof(response), "\033[<%d;%d;%d%c",
3443 encoded_button, bounded_col + 1, bounded_row + 1, release ? 'm' : 'M');
3444 break;
3445 }
3447 case MOUSE_URXVT:
3448 snprintf(response, sizeof(response), "\033[%d;%d;%dM",
3449 32 + (release ? 3 : encoded_button), col + 1, row + 1);
3450 break;
3452 case MOUSE_UTF8:
3453 /* Unimplemented */
3454 return;
3455 }
3457 term_to_slave(term, response, strlen(response));
3458}
3460static void
3461report_mouse_motion(struct terminal *term, int encoded_button, int row, int col, int row_pixels, int col_pixels)
3462{
3463 report_mouse_click(term, encoded_button, row, col, row_pixels, col_pixels, false);
3464}
3466bool
3467term_mouse_grabbed(const struct terminal *term, const struct seat *seat)
3468{
3469 /*
3470 * Mouse is grabbed by us, regardless of whether mouse tracking
3471 * has been enabled or not.
3472 */
3474 xkb_mod_mask_t mods;
3475 get_current_modifiers(seat, &mods, NULL, 0, true);
3477 const struct key_binding_set *bindings =
3478 key_binding_for(term->wl->key_binding_manager, term->conf, seat);
3479 const xkb_mod_mask_t override_modmask = bindings->selection_overrides;
3480 bool override_mods_pressed = seat->kbd.xkb_keymap != NULL &&
3481 mods != 0 && (mods & override_modmask) == override_modmask;
3483 return term->mouse_tracking == MOUSE_NONE ||
3484 (seat->kbd_focus == term && override_mods_pressed);
3485}
3487void
3488term_mouse_down(struct terminal *term, int button, int row, int col,
3489 int row_pixels, int col_pixels,
3490 bool _shift, bool _alt, bool _ctrl)
3491{
3492 /* Map libevent button event code to X button number */
3493 int xbutton = linux_mouse_button_to_x(button);
3494 if (xbutton == -1)
3495 return;
3497 int encoded = encode_xbutton(xbutton);
3498 if (encoded == -1)
3499 return;
3502 bool has_focus = term->kbd_focus;
3503 bool shift = has_focus ? _shift : false;
3504 bool alt = has_focus ? _alt : false;
3505 bool ctrl = has_focus ? _ctrl : false;
3507 encoded += (shift ? 4 : 0) + (alt ? 8 : 0) + (ctrl ? 16 : 0);
3509 switch (term->mouse_tracking) {
3510 case MOUSE_NONE:
3511 break;
3513 case MOUSE_CLICK:
3514 case MOUSE_DRAG:
3515 case MOUSE_MOTION:
3516 report_mouse_click(term, encoded, row, col, row_pixels, col_pixels, false);
3517 break;
3519 case MOUSE_X10:
3520 /* Never enabled */
3521 BUG("X10 mouse mode not implemented");
3522 break;
3523 }
3524}
3526void
3527term_mouse_up(struct terminal *term, int button, int row, int col,
3528 int row_pixels, int col_pixels,
3529 bool _shift, bool _alt, bool _ctrl)
3530{
3531 /* Map libevent button event code to X button number */
3532 int xbutton = linux_mouse_button_to_x(button);
3533 if (xbutton == -1)
3534 return;
3536 if (xbutton == 4 || xbutton == 5) {
3537 /* No release events for vertical scroll wheel buttons */
3538 return;
3539 }
3541 int encoded = encode_xbutton(xbutton);
3542 if (encoded == -1)
3543 return;
3545 bool has_focus = term->kbd_focus;
3546 bool shift = has_focus ? _shift : false;
3547 bool alt = has_focus ? _alt : false;
3548 bool ctrl = has_focus ? _ctrl : false;
3550 encoded += (shift ? 4 : 0) + (alt ? 8 : 0) + (ctrl ? 16 : 0);
3552 switch (term->mouse_tracking) {
3553 case MOUSE_NONE:
3554 break;
3556 case MOUSE_CLICK:
3557 case MOUSE_DRAG:
3558 case MOUSE_MOTION:
3559 report_mouse_click(term, encoded, row, col, row_pixels, col_pixels, true);
3560 break;
3562 case MOUSE_X10:
3563 /* Never enabled */
3564 BUG("X10 mouse mode not implemented");
3565 break;
3566 }
3567}
3569void
3570term_mouse_motion(struct terminal *term, int button, int row, int col,
3571 int row_pixels, int col_pixels,
3572 bool _shift, bool _alt, bool _ctrl)
3573{
3574 int encoded = 0;
3576 if (button != 0) {
3577 /* Map libevent button event code to X button number */
3578 int xbutton = linux_mouse_button_to_x(button);
3579 if (xbutton == -1)
3580 return;
3582 encoded = encode_xbutton(xbutton);
3583 if (encoded == -1)
3584 return;
3585 } else
3586 encoded = 3; /* "released" */
3588 bool has_focus = term->kbd_focus;
3589 bool shift = has_focus ? _shift : false;
3590 bool alt = has_focus ? _alt : false;
3591 bool ctrl = has_focus ? _ctrl : false;
3593 encoded += 32; /* Motion event */
3594 encoded += (shift ? 4 : 0) + (alt ? 8 : 0) + (ctrl ? 16 : 0);
3596 switch (term->mouse_tracking) {
3597 case MOUSE_NONE:
3598 case MOUSE_CLICK:
3599 return;
3601 case MOUSE_DRAG:
3602 if (button == 0)
3603 return;
3604 /* FALLTHROUGH */
3606 case MOUSE_MOTION:
3607 report_mouse_motion(term, encoded, row, col, row_pixels, col_pixels);
3608 break;
3610 case MOUSE_X10:
3611 /* Never enabled */
3612 BUG("X10 mouse mode not implemented");
3613 break;
3614 }
3615}
3617void
3618term_xcursor_update_for_seat(struct terminal *term, struct seat *seat)
3619{
3620 enum cursor_shape shape = CURSOR_SHAPE_NONE;
3622 switch (term->active_surface) {
3623 case TERM_SURF_GRID:
3624 if (seat->pointer.hidden)
3625 shape = CURSOR_SHAPE_HIDDEN;
3627 else if (cursor_string_to_server_shape(
3628 term->mouse_user_cursor,
3629 term->wl->shape_manager_version) != 0 ||
3630 render_xcursor_is_valid(seat, term->mouse_user_cursor))
3631 {
3632 shape = CURSOR_SHAPE_CUSTOM;
3633 }
3635 else if (term_mouse_grabbed(term, seat)) {
3636 shape = CURSOR_SHAPE_TEXT;
3637 }
3639 else
3640 shape = CURSOR_SHAPE_LEFT_PTR;
3641 break;
3643 case TERM_SURF_TITLE:
3644 case TERM_SURF_BUTTON_MINIMIZE:
3645 case TERM_SURF_BUTTON_MAXIMIZE:
3646 case TERM_SURF_BUTTON_CLOSE:
3647 shape = CURSOR_SHAPE_LEFT_PTR;
3648 break;
3650 case TERM_SURF_BORDER_LEFT:
3651 case TERM_SURF_BORDER_RIGHT:
3652 case TERM_SURF_BORDER_TOP:
3653 case TERM_SURF_BORDER_BOTTOM:
3654 shape = xcursor_for_csd_border(term, seat->mouse.x, seat->mouse.y);
3655 break;
3657 case TERM_SURF_NONE:
3658 return;
3659 }
3661 if (shape == CURSOR_SHAPE_NONE)
3662 BUG("xcursor not set");
3664 render_xcursor_set(seat, term, shape);
3665}
3667void
3668term_xcursor_update(struct terminal *term)
3669{
3670 tll_foreach(term->wl->seats, it)
3671 term_xcursor_update_for_seat(term, &it->item);
3672}
3674void
3675term_set_window_title(struct terminal *term, const char *title)
3676{
3677 if (term->conf->locked_title && term->window_title_has_been_set)
3678 return;
3680 if (term->window_title != NULL && streq(term->window_title, title))
3681 return;
3683 if (!is_valid_utf8_and_printable(title)) {
3684 /* It's an xdg_toplevel::set_title() protocol violation to set
3685 a title with an invalid UTF-8 sequence */
3686 LOG_WARN("%s: title is not valid UTF-8, ignoring", title);
3687 return;
3688 }
3690 free(term->window_title);
3691 term->window_title = xstrdup(title);
3692 render_refresh_title(term);
3693 term->window_title_has_been_set = true;
3694}
3696void
3697term_set_app_id(struct terminal *term, const char *app_id)
3698{
3699 if (app_id != NULL && *app_id == '\0')
3700 app_id = NULL;
3702 if (term->app_id == NULL && app_id == NULL)
3703 return;
3705 if (term->app_id != NULL && app_id != NULL && streq(term->app_id, app_id))
3706 return;
3708 if (app_id != NULL && !is_valid_utf8_and_printable(app_id)) {
3709 LOG_WARN("%s: app-id is not valid UTF-8, ignoring", app_id);
3710 return;
3711 }
3713 free(term->app_id);
3714 if (app_id != NULL) {
3715 term->app_id = xstrdup(app_id);
3716 } else {
3717 term->app_id = NULL;
3718 }
3720 const size_t length = app_id != NULL ? strlen(app_id) : 0;
3721 if (length > 2048) {
3722 /*
3723 * Not sure if there's a limit in the protocol, or the
3724 * libwayland implementation, or e.g. wlroots, but too long
3725 * app-id's (not e.g. title) causes at least river and sway to
3726 * peg the CPU at 100%, and stop sending e.g. frame callbacks.
3727 *
3728 */
3729 term->app_id[2048] = '\0';
3730 }
3732 render_refresh_app_id(term);
3733 render_refresh_icon(term);
3734}
3736const char *
3737term_icon(const struct terminal *term)
3738{
3739 const char *app_id =
3740 term->app_id != NULL ? term->app_id : term->conf->app_id;
3742 return
3743#if 0
3744term->window_icon != NULL
3745 ? term->window_icon
3746 :
3747 #endif
3748 streq(app_id, "footclient")
3749 ? "foot"
3750 : app_id;
3751}
3753void
3754term_flash(struct terminal *term, unsigned duration_ms)
3755{
3756 LOG_DBG("FLASH for %ums", duration_ms);
3758 struct itimerspec alarm = {
3759 .it_value = {.tv_sec = 0, .tv_nsec = duration_ms * 1000000},
3760 };
3762 if (timerfd_settime(term->flash.fd, 0, &alarm, NULL) < 0)
3763 LOG_ERRNO("failed to arm flash timer");
3764 else {
3765 term->flash.active = true;
3766 }
3767}
3769void
3770term_bell(struct terminal *term)
3771{
3773 if (!term->bell_action_enabled)
3774 return;
3776 if (term->conf->bell.urgent && !term->kbd_focus) {
3777 if (!wayl_win_set_urgent(term->window)) {
3778 /*
3779 * Urgency (xdg-activation) is relatively new in
3780 * Wayland. Fallback to our old, "faked", urgency -
3781 * rendering our window margins in red
3782 */
3783 term->render.urgency = true;
3784 term_damage_margins(term);
3785 }
3786 }
3788 if (term->conf->bell.system_bell)
3789 wayl_win_ring_bell(term->window);
3791 if (term->conf->bell.notify) {
3792 notify_notify(term, &(struct notification){
3793 .title = xstrdup("Bell"),
3794 .body = xstrdup("Bell in terminal"),
3795 .expire_time = -1,
3796 .focus = true,
3797 });
3798 }
3800 if (term->conf->bell.flash)
3801 term_flash(term, 100);
3803 if ((term->conf->bell.command.argv.args != NULL) &&
3804 (!term->kbd_focus || term->conf->bell.command_focused))
3805 {
3806 int devnull = open("/dev/null", O_RDONLY);
3807 spawn(term->reaper, NULL, term->conf->bell.command.argv.args,
3808 devnull, -1, -1, NULL, NULL, NULL);
3810 if (devnull >= 0)
3811 close(devnull);
3812 }
3813}
3815bool
3816term_spawn_new(const struct terminal *term)
3817{
3818 char *argv[4];
3819 int argc = 0;
3821 argv[argc++] = term->foot_exe;
3822 if (term->conf->conf_path != NULL) {
3823 argv[argc++] = "--config";
3824 argv[argc++] = term->conf->conf_path;
3825 }
3826 argv[argc] = NULL;
3828 return spawn(
3829 term->reaper, term->cwd, argv,
3830 -1, -1, -1, NULL, NULL, NULL) >= 0;
3831}
3833void
3834term_enable_app_sync_updates(struct terminal *term)
3835{
3836 term->render.app_sync_updates.enabled = true;
3838 if (timerfd_settime(
3839 term->render.app_sync_updates.timer_fd, 0,
3840 &(struct itimerspec){.it_value = {.tv_sec = 1}}, NULL) < 0)
3841 {
3842 LOG_ERR("failed to arm timer for application synchronized updates");
3843 }
3845 /* Disable pending refresh *iff* the grid is the *only* thing
3846 * scheduled to be re-rendered */
3847 if (!term->render.refresh.csd && !term->render.refresh.search &&
3848 !term->render.pending.csd && !term->render.pending.search)
3849 {
3850 term->render.refresh.grid = false;
3851 term->render.pending.grid = false;
3852 }
3854 /* Disarm delayed rendering timers */
3855 timerfd_settime(
3856 term->delayed_render_timer.lower_fd, 0,
3857 &(struct itimerspec){{0}}, NULL);
3858 timerfd_settime(
3859 term->delayed_render_timer.upper_fd, 0,
3860 &(struct itimerspec){{0}}, NULL);
3861 term->delayed_render_timer.is_armed = false;
3862}
3864void
3865term_disable_app_sync_updates(struct terminal *term)
3866{
3867 if (!term->render.app_sync_updates.enabled)
3868 return;
3870 term->render.app_sync_updates.enabled = false;
3871 render_refresh(term);
3873 /* Reset timers */
3874 timerfd_settime(
3875 term->render.app_sync_updates.timer_fd, 0,
3876 &(struct itimerspec){{0}}, NULL);
3877}
3879static inline void
3880print_linewrap(struct terminal *term)
3881{
3882 if (likely(!term->grid->cursor.lcf)) {
3883 /* Not and end of line */
3884 return;
3885 }
3887 if (unlikely(!term->auto_margin)) {
3888 /* Auto-wrap disabled */
3889 return;
3890 }
3892 term->grid->cur_row->linebreak = false;
3893 term->grid->cursor.lcf = false;
3895 const int row = term->grid->cursor.point.row;
3897 if (row == term->scroll_region.end - 1)
3898 term_scroll(term, 1);
3899 else {
3900 const int new_row = min(row + 1, term->rows - 1);
3901 term->grid->cursor.point.row = new_row;
3902 term->grid->cur_row = grid_row(term->grid, new_row);
3903 }
3905 term->grid->cursor.point.col = 0;
3906}
3908static inline void
3909print_insert(struct terminal *term, int width)
3910{
3911 if (likely(!term->insert_mode))
3912 return;
3914 xassert(width > 0);
3916 struct row *row = term->grid->cur_row;
3917 const size_t move_count = max(0, term->cols - term->grid->cursor.point.col - width);
3919 memmove(
3920 &row->cells[term->grid->cursor.point.col + width],
3921 &row->cells[term->grid->cursor.point.col],
3922 move_count * sizeof(struct cell));
3924 /* Mark moved cells as dirty */
3925 for (size_t i = term->grid->cursor.point.col + width; i < term->cols; i++)
3926 row->cells[i].attrs.clean = 0;
3927}
3929static void
3930print_spacer(struct terminal *term, int col, int remaining)
3931{
3932 struct grid *grid = term->grid;
3933 struct row *row = grid->cur_row;
3934 struct cell *cell = &row->cells[col];
3936 cell->wc = CELL_SPACER + remaining;
3937 cell->attrs = (struct attributes){0};
3938}
3940/*
3941 * Puts a character on the grid. Coordinates are in screen coordinates
3942 * (i.e. ‘cursor’ coordinates).
3943 *
3944 * Does NOT:
3945 * - update the cursor
3946 * - linewrap
3947 * - erase sixels
3948 *
3949 * Limitations:
3950 * - double width characters not supported
3951 */
3952void
3953term_fill(struct terminal *term, int r, int c, uint8_t data, size_t count,
3954 bool use_sgr_attrs)
3955{
3956 struct row *row = grid_row(term->grid, r);
3957 row->dirty = true;
3959 xassert(c + count <= term->cols);
3961 struct attributes attrs = use_sgr_attrs
3962 ? term->vt.attrs
3963 : (struct attributes){0};
3965 const struct cell *last = &row->cells[c + count];
3966 for (struct cell *cell = &row->cells[c]; cell < last; cell++) {
3967 cell->wc = data;
3968 cell->attrs = attrs;
3970 /* TODO: why do we print the URI here, and then erase it below? */
3971 if (unlikely(use_sgr_attrs && term->vt.osc8.uri != NULL)) {
3972 grid_row_uri_range_put(row, c, term->vt.osc8.uri, term->vt.osc8.id);
3974 switch (term->conf->url.osc8_underline) {
3975 case OSC8_UNDERLINE_ALWAYS:
3976 cell->attrs.url = true;
3977 break;
3979 case OSC8_UNDERLINE_URL_MODE:
3980 break;
3981 }
3982 }
3984 if (unlikely(use_sgr_attrs &&
3985 (term->vt.underline.style > UNDERLINE_SINGLE ||
3986 term->vt.underline.color_src != COLOR_DEFAULT)))
3987 {
3988 grid_row_underline_range_put(row, c, term->vt.underline);
3989 }
3990 }
3992 if (unlikely(row->extra != NULL)) {
3993 if (likely(term->vt.osc8.uri != NULL))
3994 grid_row_uri_range_erase(row, c, c + count - 1);
3996 if (likely(term->vt.underline.style <= UNDERLINE_SINGLE &&
3997 term->vt.underline.color_src == COLOR_DEFAULT))
3998 {
3999 /* No extended/styled underlines active, so erase any such
4000 attributes at the target columns */
Diagnostics5 git calls · 669 ms
CallStatusSizeTime0669 ms
discover200178 B46 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=46 git.response.bytes=178 git.server.agent=git/2.56.1-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=178 git.pkt.payload.max=35
ls-refs20010 KiB630 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=575 git.response.bytes=10322 git.response.cache=EXPIRED git.response.duration_ms=584 git.protocol.version=2 git.pkt.frames=108 git.pkt.data=107 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=10322 git.pkt.payload.max=106 git.ls_refs.count=107 git.ls_refs.head=refs/heads/master
fetchtree:0 · deepen 102009.3 KiB · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=9489 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=c0d2c3e95d74cb60526ff28aec9f34ee3df545e0 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=9489 git.pkt.payload.max=9389 git.sideband.band1.bytes=9389 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=10 git.pack.bytes=9389 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=de930681b6073ba5b599a0f956bfbd114762ad5a git.pack.full=10Open pack map
fetchtree:02003.6 KiB · hit6 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=6 git.response.bytes=3708 git.response.cache=HIT git.response.duration_ms=6 git.fetch.filter=tree:0 git.fetch.wants=96f1228f4004ebd74530c7f0aea264108eff425f git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3708 git.pkt.payload.max=3681 git.sideband.band1.bytes=3681 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=3681 git.pack.trailer=731a22f61f25bdfdca1691647f2056631bcfdcf1Open pack map
fetch20033 KiB · hit29 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=29 git.response.bytes=33296 git.response.cache=HIT git.response.duration_ms=29 git.fetch.wants=beee1f9f8d3df682bcd527ced14cb87c1b168f2d git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=33296 git.pkt.payload.max=33269 git.sideband.band1.bytes=33269 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://codeberg.org/dnkl/foot
- Ref
- refs/heads/master
- Commit
- c0d2c3e95d74cb60526ff28aec9f34ee3df545e0
- cf-ray
- a5e9e3b53fb0f3c9
- Request
- d1080792…
- Protocol
- v2 · sha1
- Agent
- git/2.56.1-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format