Skip to content
pi-c Artifact [e9262216a6]
Login

Artifact [e9262216a6]

Artifact e9262216a6ffc69d46b1b7d5993edffd0bac3db3c13b7e29b15484d358fe2606:


/* Inline differential renderer; see render.h.
 *
 * Model: the live area is rows 0..nprev-1 below the point where it started.
 * at_row is the row the terminal cursor is on (column unknown, so every
 * cursor placement starts with "\r"). Each call builds its whole output in
 * memory and writes it once, wrapped in synchronized output. */
#include "tui/render.h"

#include "tui/term.h"
#include "tui/theme.h"
#include "tui/viewport.h"
#include "tui/width.h"

#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#define SYNC_ON "\x1b[?2026h"
#define SYNC_OFF "\x1b[?2026l"
#define CURSOR_HIDE "\x1b[?25l"
#define CURSOR_SHOW "\x1b[?25h"
#define CLEAR_DOWN "\x1b[J"

struct tui_render {
    int fd;
    char **prev; /* the live area as last drawn (clipped to the rows) */
    size_t nprev;
    size_t at_row;   /* terminal cursor row within the live area */
    int crow, ccol;  /* where the cursor should be (crow < 0: hidden) */
    int invalid;     /* redraw everything next time */
    char *out;       /* output being built */
    size_t out_n, out_cap;
    int oom;
    tui_lines hist;  /* every committed line, as given */
    /* fullscreen */
    int full;
    int cols, rows;
    int bar, exit_transcript;
    long bar_until;      /* auto: the scrollbar shows until then (ms) */
    tui_lines view;      /* hist laid out for view_cols */
    size_t view_cols;    /* 0: lay everything out again */
    size_t view_from;    /* hist lines laid out so far */
    tui_lines body;      /* the live end of the transcript, laid out */
    tui_lines dock;      /* as last drawn */
    int dcrow, dccol;    /* the cursor in the dock (dcrow < 0: hidden) */
    size_t vh;           /* viewport rows as last drawn */
    tui_scroll sc;
    tui_selection sel;
    int selecting;       /* the button is down */
    char **screen;       /* each row as last written */
    size_t nscreen;
    int repaint;         /* clear and write every row next time */
    /* transcript search (Pi's tui.altScreen.search*) */
    struct {
        int on;
        char q[512];     /* the query as typed */
        tui_found f;     /* its matches in the transcript as of sig */
        int valid;       /* f matches q and sig */
        uint64_t sig;
        long sel;        /* the current match, -1: none */
        size_t key[4];   /* its tui_hit_key, to find it again when the text changes */
        int has_key;
        size_t anchor;   /* a new query selects the first match from this row */
        int mode;        /* TUI_PICK_*: how the next refresh selects */
        char prev[32], next[32]; /* the keys shown in the box */
    } sr;
};

static void out_add(tui_render *r, const char *s, size_t n)
{
    if (r->oom)
        return;
    if (r->out_n + n > r->out_cap) {
        size_t cap = r->out_cap ? r->out_cap : 256;
        while (cap < r->out_n + n)
            cap *= 2;
        char *p = realloc(r->out, cap);
        if (!p) {
            r->oom = 1;
            return;
        }
        r->out = p, r->out_cap = cap;
    }
    memcpy(r->out + r->out_n, s, n);
    r->out_n += n;
}

static void out_str(tui_render *r, const char *s)
{
    out_add(r, s, strlen(s));
}

static void out_csi(tui_render *r, size_t n, char fin)
{
    char b[32];
    int len = snprintf(b, sizeof b, "\x1b[%zu%c", n, fin);
    out_add(r, b, (size_t)len);
}

/* Moves the cursor between rows of the live area. */
static void move_rows(tui_render *r, size_t from, size_t to)
{
    if (to < from)
        out_csi(r, from - to, 'A');
    else if (to > from)
        out_csi(r, to - from, 'B');
}

/* Writes the buffer out (sync-wrapped by the caller); 0 or -1. */
static int out_flush(tui_render *r)
{
    int rc = r->oom ? -1 : 0;
    size_t off = 0;
    while (rc == 0 && off < r->out_n) {
        ssize_t w = write(r->fd, r->out + off, r->out_n - off);
        if (w < 0) {
            if (errno == EINTR)
                continue;
            rc = -1;
        } else {
            off += (size_t)w;
        }
    }
    r->out_n = 0;
    r->oom = 0;
    return rc;
}

/* Puts the cursor where r->crow/ccol say, from end_row, and shows or leaves
 * it hidden; closes the synchronized update. */
static void finish_frame(tui_render *r, size_t end_row)
{
    if (r->crow >= 0 && (size_t)r->crow < r->nprev) {
        move_rows(r, end_row, (size_t)r->crow);
        out_str(r, "\r");
        if (r->ccol > 0)
            out_csi(r, (size_t)r->ccol + 1, 'G');
        out_str(r, CURSOR_SHOW);
        r->at_row = (size_t)r->crow;
    } else {
        r->at_row = end_row;
        if (r->nprev == 0)
            out_str(r, CURSOR_SHOW); /* no live area: nothing to hide for */
    }
    out_str(r, SYNC_OFF);
}

static void free_prev(tui_render *r)
{
    for (size_t i = 0; i < r->nprev; i++)
        free(r->prev[i]);
    free(r->prev);
    r->prev = NULL;
    r->nprev = 0;
}

tui_render *tui_render_new(int fd)
{
    tui_render *r = calloc(1, sizeof *r);
    if (r)
        r->fd = fd;
    return r;
}

static void free_screen(tui_render *r);

void tui_render_free(tui_render *r)
{
    if (!r)
        return;
    free_prev(r);
    free_screen(r);
    tui_lines_clear(&r->hist);
    tui_lines_clear(&r->view);
    tui_lines_clear(&r->body);
    tui_lines_clear(&r->dock);
    tui_found_free(&r->sr.f);
    free(r->out);
    free(r);
}

/* Writes lines[from..n) separated by "\r\n"; the cursor ends on row n-1. */
static void write_lines(tui_render *r, const char *const *lines, size_t from, size_t n)
{
    for (size_t i = from; i < n; i++) {
        if (i > from)
            out_str(r, "\r\n");
        out_str(r, lines[i]);
    }
}

int tui_render_draw(tui_render *r, const char *const *lines, size_t n, int crow, int ccol, int rows)
{
    size_t max = rows > 1 ? (size_t)rows - 1 : 1;
    if (n > max) {
        size_t skip = n - max;
        lines += skip;
        n = max;
        crow = crow >= 0 && (size_t)crow >= skip ? crow - (int)skip : -1;
    }

    /* First row that differs from the last draw. */
    size_t d = 0, common = r->nprev < n ? r->nprev : n;
    if (!r->invalid)
        while (d < common && strcmp(r->prev[d], lines[d]) == 0)
            d++;

    out_str(r, SYNC_ON);
    out_str(r, CURSOR_HIDE);
    size_t end_row = r->at_row;
    if (r->nprev == 0) {
        write_lines(r, lines, 0, n); /* starts where the cursor is */
        end_row = n ? n - 1 : 0;
    } else if (!r->invalid && d == r->nprev && d == n) {
        /* identical: only the cursor may move */
    } else if (!r->invalid && d == r->nprev) {
        /* Append: below the last line. */
        move_rows(r, r->at_row, r->nprev - 1);
        out_str(r, "\r\n");
        write_lines(r, lines, d, n);
        end_row = n - 1;
    } else if (d == n) {
        /* Shrink: clear from the first removed row, then back onto the last. */
        move_rows(r, r->at_row, n);
        out_str(r, "\r" CLEAR_DOWN);
        if (n > 0) {
            out_csi(r, 1, 'A');
            end_row = n - 1;
        } else {
            end_row = 0;
        }
    } else {
        move_rows(r, r->at_row, d);
        out_str(r, "\r" CLEAR_DOWN);
        write_lines(r, lines, d, n);
        end_row = n - 1;
    }

    {
        /* Remember what is on screen. */
        char **copy = n ? calloc(n, sizeof *copy) : NULL;
        if (n && !copy)
            return -1;
        for (size_t i = 0; i < n; i++) {
            copy[i] = strdup(lines[i]);
            if (!copy[i]) {
                for (size_t j = 0; j < i; j++)
                    free(copy[j]);
                free(copy);
                return -1;
            }
        }
        free_prev(r);
        r->prev = copy;
        r->nprev = n;
    }
    r->invalid = 0;
    r->crow = crow;
    r->ccol = ccol;
    finish_frame(r, end_row);
    return out_flush(r);
}

int tui_render_commit(tui_render *r, const char *const *lines, size_t n)
{
    for (size_t i = 0; i < n; i++)
        if (tui_lines_add(&r->hist, lines[i], strlen(lines[i])) != 0)
            return -1;
    if (r->full)
        return 0; /* the next draw shows them */
    out_str(r, SYNC_ON);
    out_str(r, CURSOR_HIDE);
    if (r->nprev > 0) {
        move_rows(r, r->at_row, 0);
        out_str(r, "\r" CLEAR_DOWN);
    }
    for (size_t i = 0; i < n; i++) {
        out_str(r, lines[i]);
        out_str(r, "\r\n");
    }
    if (r->invalid) {
        /* The old lines were laid out for another width: leave them off
         * screen; the next draw rewrites the live area from scratch. */
        free_prev(r);
        r->at_row = 0;
        out_str(r, CURSOR_SHOW SYNC_OFF);
        return out_flush(r);
    }
    size_t end_row = 0;
    if (r->nprev > 0) {
        write_lines(r, (const char *const *)r->prev, 0, r->nprev);
        end_row = r->nprev - 1;
    }
    finish_frame(r, end_row);
    return out_flush(r);
}

int tui_render_replace(tui_render *r, const char *const *lines, size_t n)
{
    tui_lines_clear(&r->hist);
    for (size_t i = 0; i < n; i++)
        if (tui_lines_add(&r->hist, lines[i], strlen(lines[i])) != 0)
            return -1;
    tui_lines_clear(&r->view);
    r->view_cols = 0;
    r->view_from = 0;
    r->sel.on = 0;
    r->selecting = 0;
    r->sr.valid = 0; /* an open search finds its matches again */
    if (r->full)
        return 0; /* the next draw lays them out */
    out_str(r, SYNC_ON);
    out_str(r, CURSOR_HIDE);
    out_str(r, "\x1b[2J\x1b[H\x1b[3J"); /* Pi's full redraw: screen, home, scrollback */
    for (size_t i = 0; i < n; i++) {
        out_str(r, lines[i]);
        out_str(r, "\r\n");
    }
    free_prev(r);
    r->at_row = 0;
    r->crow = -1;
    r->invalid = 0;
    out_str(r, CURSOR_SHOW SYNC_OFF);
    return out_flush(r);
}

void tui_render_invalidate(tui_render *r)
{
    r->invalid = 1;
    r->repaint = 1;
}

static int leave(tui_render *r, int print, int with_dock);

int tui_render_finish(tui_render *r)
{
    if (r->full)
        return leave(r, r->exit_transcript, 1);
    if (r->nprev > 0) {
        move_rows(r, r->at_row, r->nprev - 1);
        out_str(r, "\r\n");
    }
    out_str(r, CURSOR_SHOW);
    free_prev(r);
    r->at_row = 0;
    r->crow = -1;
    return out_flush(r);
}

/* ---- fullscreen ---------------------------------------------------------- */

/* A row is cleared before it is written, as Pi does (\x1b[2K): an erase after
 * it would take the last column of a full-width row, where the cursor stays. */
#define ROW_START "\x1b[2K"
#define ROW_END "\x1b[0m"
/* Pi's scrollbar: a dim track, a lighter thumb (ScrollView's default styles). */
/* Pi's scrollToEndIndicator, on its selected-row background. */
/* The jump hint names the key bound to scrolling to the end (tui_render_jump_key). */
static char jump_label[96] = " \xe2\x86\x93 Jump to latest message \xc2\xb7 ctrl+end ";
#define JUMP_LABEL jump_label

void tui_render_jump_key(const char *keys)
{
    (void)snprintf(jump_label, sizeof jump_label, " \xe2\x86\x93 Jump to latest message \xc2\xb7 %.50s ", keys && *keys ? keys : "ctrl+end");
}
#define JUMP_STYLE "\x1b[7m"
/* ScrollView's scrollbarHideDelayMs. */
#define BAR_SHOW_MS 1000

static long clock_ms(void)
{
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}

static void free_screen(tui_render *r)
{
    for (size_t i = 0; i < r->nscreen; i++)
        free(r->screen[i]);
    free(r->screen);
    r->screen = NULL;
    r->nscreen = 0;
}

/* The transcript's width: a column less while the scrollbar always shows
 * (Pi's ScrollView renders its child narrower then). */
static size_t content_cols(const tui_render *r)
{
    size_t c = r->cols > 0 ? (size_t)r->cols : 1;
    return r->bar == TUI_BAR_ALWAYS && c > 1 ? c - 1 : c;
}

/* Lays out the lines committed since, or all of them again at a new width. */
static int sync_view(tui_render *r)
{
    size_t cols = content_cols(r);
    if (r->view_cols != cols) {
        tui_lines_clear(&r->view);
        r->view_cols = cols;
        r->view_from = 0;
        r->sel.on = 0;
        r->selecting = 0;
    }
    for (; r->view_from < r->hist.n; r->view_from++)
        if (tui_line_layout(r->hist.lines[r->view_from], cols, &r->view) != 0)
            return -1;
    return 0;
}

static const char *content_at(void *ctx, size_t i)
{
    const tui_render *r = ctx;
    if (i < r->view.n)
        return r->view.lines[i];
    i -= r->view.n;
    return i < r->body.n ? r->body.lines[i] : "";
}

/* Rows of the dock shown, and how many of its first lines are cut off: the
 * viewport keeps at least one row. */
static size_t dock_rows(const tui_render *r, size_t *skip)
{
    size_t rows = r->rows > 0 ? (size_t)r->rows : 1, shown = r->dock.n < rows ? r->dock.n : rows - 1;
    *skip = r->dock.n - shown;
    return shown;
}

static int bar_visible(const tui_render *r)
{
    if (r->bar == TUI_BAR_ALWAYS)
        return 1;
    return r->bar == TUI_BAR_AUTO && r->sc.content > r->sc.height && clock_ms() < r->bar_until;
}

/* Pi's match styles: the others underlined on searchMatchBg/searchMatchText, the current one bold and reversed. */
static char *match_line(const tui_render *r, const char *line, size_t i)
{
    tui_span sp[64];
    size_t n;
    char *cur;
    if (!r->sr.on || r->sr.sel < 0 || r->sr.f.nhits == 0)
        return NULL;
    n = tui_found_row(&r->sr.f, r->sr.sel, i, sp, sizeof sp / sizeof *sp);
    if (n == 0)
        return NULL;
    cur = strdup(line);
    for (size_t k = n; cur && k-- > 0;) {
        char open[160], *next;
        const char *close = sp[k].current ? "\x1b[39m\x1b[49m\x1b[27m\x1b[22m" : "\x1b[39m\x1b[49m\x1b[24m";
        (void)snprintf(open, sizeof open, "%s%s%s", sp[k].current ? "\x1b[1m\x1b[7m" : "\x1b[4m",
                       tui_bg(TUI_T_SEARCH_MATCH_BG), tui_fg(TUI_T_SEARCH_MATCH_TEXT));
        next = tui_line_style(cur, sp[k].c0, sp[k].c1, open, close);
        free(cur);
        cur = next;
    }
    return cur;
}

/* Row y of the viewport as it is to be shown; malloc'd. */
static char *viewport_row(tui_render *r, size_t y, int bar, const tui_scrollbar *g)
{
    size_t i = r->sc.top + y, c0, c1;
    const char *line = i < r->sc.content ? content_at(r, i) : "";
    char *s;
    if (!r->sc.follow && r->sc.top < tui_scroll_max(&r->sc) && y + 1 == r->sc.height) {
        /* Pi's jump-to-latest label, centered on the last row */
        size_t cols = content_cols(r), w = tui_width(JUMP_LABEL, strlen(JUMP_LABEL)), fit, pad;
        char buf[512];
        fit = tui_fit(JUMP_LABEL, strlen(JUMP_LABEL), cols);
        w = tui_width(JUMP_LABEL, fit);
        pad = (cols - w) / 2;
        (void)snprintf(buf, sizeof buf, "%*s" JUMP_STYLE "%.*s\x1b[0m", (int)pad, "", (int)fit, JUMP_LABEL);
        s = strdup(buf);
    } else {
        char *m = match_line(r, line, i);
        const char *shown = m ? m : line;
        if (tui_selection_cols(&r->sel, i, tui_width(line, strlen(line)), &c0, &c1))
            s = tui_line_highlight(shown, c0, c1);
        else
            s = strdup(shown);
        free(m);
    }
    if (s && bar) {
        int thumb = y >= g->thumb_top && y < g->thumb_top + g->thumb_height;
        char cell[48], *b;
        (void)snprintf(cell, sizeof cell, "%s%s\x1b[39m", tui_fg(thumb ? TUI_T_SCROLLBAR_THUMB : TUI_T_SCROLLBAR_TRACK),
                       thumb ? "\xe2\x94\x83" : "\xe2\x94\x82");
        b = tui_line_bar(s, r->cols > 0 ? (size_t)r->cols : 1, cell);
        free(s);
        s = b;
    }
    return s;
}

/* ---- transcript search ------------------------------------------------------ */

static int moved(tui_render *r, int did);

/* A hash of the transcript, to tell when the matches are stale. */
static uint64_t content_sig(tui_render *r)
{
    uint64_t h = 1469598103934665603ULL;
    size_t n = r->view.n + r->body.n;
    for (size_t i = 0; i < n; i++) {
        for (const unsigned char *p = (const unsigned char *)content_at(r, i); *p; p++)
            h = (h ^ *p) * 1099511628211ULL;
        h = (h ^ '\n') * 1099511628211ULL;
    }
    return h;
}

/* Pi's refreshSearch: finds the matches again when the query or the text
 * changed, selects one as the mode says, and scrolls it into view. */
static void search_refresh(tui_render *r)
{
    long exact, base;
    int reveal, changed;
    uint64_t sig;
    if (!r->sr.on)
        return;
    if (!r->sr.q[strspn(r->sr.q, " \t\r\n")]) {
        tui_found_free(&r->sr.f);
        r->sr.valid = 0;
        r->sr.sel = -1;
        r->sr.has_key = 0;
        r->sr.mode = TUI_PICK_RETAIN;
        return;
    }
    reveal = r->sr.mode != TUI_PICK_RETAIN;
    sig = content_sig(r);
    changed = !r->sr.valid || sig != r->sr.sig;
    if (changed) {
        tui_found_free(&r->sr.f);
        if (tui_search_find(r->view.n + r->body.n, content_at, r, r->sr.q, &r->sr.f) != 0)
            return;
        r->sr.sig = sig;
        r->sr.valid = 1;
    } else if (!reveal) {
        return;
    }
    exact = changed ? (r->sr.has_key ? tui_found_by_key(&r->sr.f, r->sr.key) : -1) : r->sr.sel;
    base = exact >= 0 ? exact : r->sr.sel;
    r->sr.sel = tui_search_pick(&r->sr.f, r->sr.mode, base, r->sr.anchor);
    r->sr.has_key = r->sr.sel >= 0;
    if (r->sr.has_key)
        tui_hit_key(&r->sr.f, (size_t)r->sr.sel, r->sr.key);
    r->sr.mode = TUI_PICK_RETAIN;
    if (reveal && r->sr.sel >= 0 && r->sc.height > 0) {
        size_t before = r->sc.top;
        tui_scroll_to(&r->sc, tui_search_reveal(&r->sc, &r->sr.f, (size_t)r->sr.sel), 1);
        (void)moved(r, r->sc.top != before);
    }
}

void tui_render_search_keys(tui_render *r, const char *prev, const char *next)
{
    (void)snprintf(r->sr.prev, sizeof r->sr.prev, "%s", prev);
    (void)snprintf(r->sr.next, sizeof r->sr.next, "%s", next);
}

int tui_render_search_toggle(tui_render *r)
{
    if (!r->full)
        return 0;
    if (r->sr.on) {
        tui_render_search_close(r);
        return 1;
    }
    memset(&r->sr.f, 0, sizeof r->sr.f);
    r->sr.on = 1;
    r->sr.q[0] = '\0';
    r->sr.valid = 0;
    r->sr.sel = -1;
    r->sr.has_key = 0;
    r->sr.anchor = r->sc.top;
    r->sr.mode = TUI_PICK_QUERY;
    return 1;
}

void tui_render_search_close(tui_render *r)
{
    if (!r->sr.on)
        return;
    tui_found_free(&r->sr.f);
    r->sr.on = 0;
    r->sr.valid = 0;
    r->repaint = 1;
}

int tui_render_search_active(const tui_render *r)
{
    return r->sr.on;
}

const char *tui_render_search_query(const tui_render *r)
{
    return r->sr.q;
}

void tui_render_search_set(tui_render *r, const char *query)
{
    if (!r->sr.on || strcmp(query, r->sr.q) == 0)
        return;
    r->sr.anchor = r->sr.valid && r->sr.sel >= 0 ? r->sr.f.segs[r->sr.f.hits[r->sr.sel].first].row : r->sc.top;
    (void)snprintf(r->sr.q, sizeof r->sr.q, "%s", query);
    r->sr.mode = TUI_PICK_QUERY;
    r->sr.valid = 0;
    r->sr.sel = -1;
}

void tui_render_search_step(tui_render *r, int dir)
{
    if (r->sr.on && r->sr.q[0])
        r->sr.mode = dir < 0 ? TUI_PICK_PREV : TUI_PICK_NEXT;
}

size_t tui_render_search_hits(const tui_render *r, long *index)
{
    if (index)
        *index = r->sr.sel;
    return r->sr.valid ? r->sr.f.nhits : 0;
}

/* Pi's overlay: top-right, 40% of the width but at least 32, one cell in
 * from the edge. Draws the box over rows 1..3 of next. */
static void search_overlay(tui_render *r, char **next, size_t rows)
{
    size_t cols = r->cols > 0 ? (size_t)r->cols : 1, avail = cols > 2 ? cols - 2 : 1, w = cols * 4 / 10;
    tui_lines box = {NULL, 0, 0};
    if (w < 32)
        w = 32;
    if (w > avail)
        w = avail;
    if (tui_search_box(r->sr.q, r->sr.sel, r->sr.valid ? r->sr.f.nhits : 0, r->sr.prev, r->sr.next, w, &box) == 0) {
        for (size_t k = 0; k < box.n && 1 + k < rows; k++) {
            char *line = tui_line_splice(next[1 + k], 1 + avail - w, w, box.lines[k]);
            if (line) {
                free(next[1 + k]);
                next[1 + k] = line;
            }
        }
    }
    tui_lines_clear(&box);
}

/* Draws the frame: each row that changed, at its place. */
static int paint(tui_render *r)
{
    size_t rows = r->rows > 0 ? (size_t)r->rows : 1, skip, nd, h;
    char **next;
    tui_scrollbar g = {0, 0};
    int bar;
    if (sync_view(r) != 0)
        return -1;
    nd = dock_rows(r, &skip);
    h = rows - nd;
    tui_scroll_layout(&r->sc, r->view.n + r->body.n, h);
    r->vh = h;
    search_refresh(r);
    bar = bar_visible(r) && tui_scrollbar_geometry(&r->sc, &g);
    next = calloc(rows, sizeof *next);
    if (!next)
        return -1;
    for (size_t y = 0; y < rows; y++) {
        next[y] = y < h ? viewport_row(r, y, bar, &g) : strdup(r->dock.lines[skip + y - h]);
        if (!next[y]) {
            for (size_t j = 0; j < y; j++)
                free(next[j]);
            free(next);
            return -1;
        }
    }
    if (r->sr.on)
        search_overlay(r, next, rows);
    out_str(r, SYNC_ON);
    out_str(r, CURSOR_HIDE);
    if (r->repaint || r->nscreen != rows)
        out_str(r, "\x1b[2J");
    for (size_t y = 0; y < rows; y++) {
        if (!r->repaint && r->nscreen == rows && strcmp(r->screen[y], next[y]) == 0)
            continue;
        char pos[32];
        (void)snprintf(pos, sizeof pos, "\x1b[%zu;1H", y + 1);
        out_str(r, pos);
        out_str(r, ROW_START);
        out_str(r, next[y]);
        out_str(r, ROW_END);
    }
    free_screen(r);
    r->screen = next;
    r->nscreen = rows;
    r->repaint = 0;
    if (!r->sr.on && r->dcrow >= 0 && (size_t)r->dcrow >= skip && (size_t)r->dcrow - skip < nd) {
        char pos[48];
        (void)snprintf(pos, sizeof pos, "\x1b[%zu;%dH", h + (size_t)r->dcrow - skip + 1, r->dccol + 1);
        out_str(r, pos);
        out_str(r, CURSOR_SHOW);
    }
    out_str(r, SYNC_OFF);
    return out_flush(r);
}

static int set_lines(tui_lines *l, const char *const *lines, size_t n, size_t cols)
{
    tui_lines_clear(l);
    for (size_t i = 0; i < n; i++) {
        int rc = cols ? tui_line_layout(lines[i], cols, l) : tui_lines_add(l, lines[i], strlen(lines[i]));
        if (rc != 0)
            return -1;
    }
    return 0;
}

int tui_render_draw_split(tui_render *r, const char *const *lines, size_t n, size_t split, int crow, int ccol, int rows)
{
    if (!r->full)
        return tui_render_draw(r, lines, n, crow, ccol, rows);
    if (split > n)
        split = n;
    r->rows = rows;
    if (set_lines(&r->body, lines, split, content_cols(r)) != 0 || set_lines(&r->dock, lines + split, n - split, 0) != 0)
        return -1;
    r->dcrow = crow >= 0 && (size_t)crow >= split ? crow - (int)split : -1;
    r->dccol = ccol;
    return paint(r);
}

/* Writes lines to the normal screen, each on its own row, then a new line. */
static void print_lines(tui_render *r, const tui_lines *l)
{
    for (size_t i = 0; i < l->n; i++) {
        out_str(r, "\r\x1b[2K");
        out_str(r, l->lines[i]);
        out_str(r, "\x1b[0m\r\n");
    }
}

/* Leaves the alternate screen; print: the transcript follows on the normal
 * screen (and the dock, with_dock). */
static int leave(tui_render *r, int print, int with_dock)
{
    tui_term_alt(r->fd, 0);
    r->full = 0;
    tui_render_search_close(r);
    free_screen(r);
    if (print) {
        (void)sync_view(r);
        out_str(r, SYNC_ON);
        print_lines(r, &r->view);
        print_lines(r, &r->body);
        if (with_dock)
            print_lines(r, &r->dock);
        out_str(r, CURSOR_SHOW SYNC_OFF);
    }
    tui_lines_clear(&r->body);
    free_prev(r);
    r->at_row = 0;
    r->crow = -1;
    return out_flush(r);
}

static void enter(tui_render *r)
{
    tui_term_alt(r->fd, 1);
    r->full = 1;
    r->repaint = 1;
    free_screen(r);
}

int tui_render_fullscreen(tui_render *r, int on, int cols, int rows)
{
    tui_render_size(r, cols, rows);
    if (on && !r->full) {
        if (r->nprev > 0 && tui_render_finish(r) != 0)
            return -1;
        tui_scroll_init(&r->sc);
        r->sel.on = 0;
        enter(r);
        return 0;
    }
    if (!on && r->full)
        return leave(r, 1, 0);
    return 0;
}

int tui_render_is_fullscreen(const tui_render *r)
{
    return r->full;
}

void tui_render_size(tui_render *r, int cols, int rows)
{
    if (cols != r->cols)
        r->repaint = 1;
    r->cols = cols;
    r->rows = rows;
}

void tui_render_options(tui_render *r, int bar, int exit_transcript)
{
    if (bar != r->bar)
        r->repaint = 1;
    r->bar = bar;
    r->exit_transcript = exit_transcript;
}

/* After the view moved: the auto scrollbar shows for a while. */
static int moved(tui_render *r, int did)
{
    if (did)
        r->bar_until = clock_ms() + BAR_SHOW_MS;
    return did;
}

int tui_render_scroll(tui_render *r, long lines)
{
    return r->full && lines ? moved(r, tui_scroll_by(&r->sc, lines)) : 0;
}

int tui_render_page(tui_render *r, int dir)
{
    return r->full ? tui_render_scroll(r, tui_scroll_page(&r->sc, dir)) : 0;
}

int tui_render_edge(tui_render *r, int end)
{
    size_t top = r->sc.top;
    int follow = r->sc.follow;
    if (!r->full)
        return 0;
    if (end)
        tui_scroll_end(&r->sc);
    else
        tui_scroll_start(&r->sc);
    return moved(r, r->sc.top != top || r->sc.follow != follow);
}

int tui_render_scrolled(const tui_render *r)
{
    return r->full && !r->sc.follow && r->sc.top < tui_scroll_max(&r->sc);
}

int tui_render_jump_hit(const tui_render *r, int y)
{
    return tui_render_scrolled(r) && y >= 0 && (size_t)y + 1 == r->sc.height;
}

int tui_render_mouse(tui_render *r, int what, int x, int y)
{
    size_t row = y > 0 ? (size_t)y : 0, col = x > 0 ? (size_t)x : 0;
    tui_point p, a, b;
    if (!r->full)
        return 0;
    if (what == TUI_MOUSE_PRESS) {
        r->selecting = row < r->vh;
        r->sel.on = r->selecting;
        r->sel.anchor = r->sel.focus = (tui_point){r->sc.top + row, col};
        return 0;
    }
    if (!r->selecting)
        return 0;
    if (r->vh > 0 && row >= r->vh)
        row = r->vh - 1;
    p = (tui_point){r->sc.top + row, col};
    r->sel.focus = p;
    if (what != TUI_MOUSE_RELEASE)
        return 0;
    r->selecting = 0;
    if (!tui_selection_bounds(&r->sel, &a, &b)) {
        r->sel.on = 0;
        return 0;
    }
    return 1;
}

char *tui_render_selection(tui_render *r)
{
    return r->sel.on ? tui_selection_text(&r->sel, content_at, r) : NULL;
}

long tui_render_wake(const tui_render *r)
{
    long left;
    if (!r->full || r->bar != TUI_BAR_AUTO || r->bar_until == 0)
        return -1;
    left = r->bar_until - clock_ms();
    return left >= 0 ? left + 1 : -1;
}

int tui_render_pause(tui_render *r)
{
    if (!r->full)
        return tui_render_finish(r);
    tui_term_alt(r->fd, 0);
    free_screen(r);
    return 0;
}

int tui_render_resume(tui_render *r)
{
    if (r->full) {
        enter(r);
        return 0;
    }
    free_prev(r);
    r->at_row = 0;
    r->crow = -1;
    r->invalid = 0;
    return 0;
}