#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define GHOSTTY_STATIC 1
#include <ghostty/vt.h>

#define STB_TRUETYPE_IMPLEMENTATION
#define STBTT_STATIC
#include <stb_truetype.h>

// Kitty graphics' PNG payloads; the terminal stores the decoded pixels.
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_STATIC
#define STBI_ONLY_PNG
#define STBI_NO_STDIO
#include <stb_image.h>

#include <dolly/display.h>
#include <dolly/input.h>

enum {
  DRIVER_ABI_VERSION = 5,
  MIN_FONT_MILLI = 8000,
  MAX_FONT_MILLI = 32000,
  DEFAULT_FONT_MILLI = 20000,
  NARROW_WIDTH_CSS = 640,
  NARROW_MIN_FONT_MILLI = 12000,
  NARROW_COLUMNS = 48,
  DEFAULT_SCALE_MILLI = 1000,
  PTY_RESPONSE_CAPACITY = 512 * 1024,
  MAX_GRAPHEME_CODEPOINTS = 16,
};

// Kitty graphics images the terminal keeps, in bytes of decoded pixels.
static const uint64_t kitty_image_storage_limit = 64u << 20;

typedef struct {
  const char *code;
  GhosttyKey key;
} key_mapping;

static const key_mapping key_mappings[] = {
    {"Backquote", GHOSTTY_KEY_BACKQUOTE},
    {"Backslash", GHOSTTY_KEY_BACKSLASH},
    {"BracketLeft", GHOSTTY_KEY_BRACKET_LEFT},
    {"BracketRight", GHOSTTY_KEY_BRACKET_RIGHT},
    {"Comma", GHOSTTY_KEY_COMMA},
    {"Digit0", GHOSTTY_KEY_DIGIT_0},
    {"Digit1", GHOSTTY_KEY_DIGIT_1},
    {"Digit2", GHOSTTY_KEY_DIGIT_2},
    {"Digit3", GHOSTTY_KEY_DIGIT_3},
    {"Digit4", GHOSTTY_KEY_DIGIT_4},
    {"Digit5", GHOSTTY_KEY_DIGIT_5},
    {"Digit6", GHOSTTY_KEY_DIGIT_6},
    {"Digit7", GHOSTTY_KEY_DIGIT_7},
    {"Digit8", GHOSTTY_KEY_DIGIT_8},
    {"Digit9", GHOSTTY_KEY_DIGIT_9},
    {"Equal", GHOSTTY_KEY_EQUAL},
    {"IntlBackslash", GHOSTTY_KEY_INTL_BACKSLASH},
    {"IntlRo", GHOSTTY_KEY_INTL_RO},
    {"IntlYen", GHOSTTY_KEY_INTL_YEN},
    {"KeyA", GHOSTTY_KEY_A}, {"KeyB", GHOSTTY_KEY_B},
    {"KeyC", GHOSTTY_KEY_C}, {"KeyD", GHOSTTY_KEY_D},
    {"KeyE", GHOSTTY_KEY_E}, {"KeyF", GHOSTTY_KEY_F},
    {"KeyG", GHOSTTY_KEY_G}, {"KeyH", GHOSTTY_KEY_H},
    {"KeyI", GHOSTTY_KEY_I}, {"KeyJ", GHOSTTY_KEY_J},
    {"KeyK", GHOSTTY_KEY_K}, {"KeyL", GHOSTTY_KEY_L},
    {"KeyM", GHOSTTY_KEY_M}, {"KeyN", GHOSTTY_KEY_N},
    {"KeyO", GHOSTTY_KEY_O}, {"KeyP", GHOSTTY_KEY_P},
    {"KeyQ", GHOSTTY_KEY_Q}, {"KeyR", GHOSTTY_KEY_R},
    {"KeyS", GHOSTTY_KEY_S}, {"KeyT", GHOSTTY_KEY_T},
    {"KeyU", GHOSTTY_KEY_U}, {"KeyV", GHOSTTY_KEY_V},
    {"KeyW", GHOSTTY_KEY_W}, {"KeyX", GHOSTTY_KEY_X},
    {"KeyY", GHOSTTY_KEY_Y}, {"KeyZ", GHOSTTY_KEY_Z},
    {"Minus", GHOSTTY_KEY_MINUS},
    {"Period", GHOSTTY_KEY_PERIOD},
    {"Quote", GHOSTTY_KEY_QUOTE},
    {"Semicolon", GHOSTTY_KEY_SEMICOLON},
    {"Slash", GHOSTTY_KEY_SLASH},
    {"AltLeft", GHOSTTY_KEY_ALT_LEFT},
    {"AltRight", GHOSTTY_KEY_ALT_RIGHT},
    {"Backspace", GHOSTTY_KEY_BACKSPACE},
    {"CapsLock", GHOSTTY_KEY_CAPS_LOCK},
    {"ContextMenu", GHOSTTY_KEY_CONTEXT_MENU},
    {"ControlLeft", GHOSTTY_KEY_CONTROL_LEFT},
    {"ControlRight", GHOSTTY_KEY_CONTROL_RIGHT},
    {"Enter", GHOSTTY_KEY_ENTER},
    {"MetaLeft", GHOSTTY_KEY_META_LEFT},
    {"MetaRight", GHOSTTY_KEY_META_RIGHT},
    {"ShiftLeft", GHOSTTY_KEY_SHIFT_LEFT},
    {"ShiftRight", GHOSTTY_KEY_SHIFT_RIGHT},
    {"Space", GHOSTTY_KEY_SPACE},
    {"Tab", GHOSTTY_KEY_TAB},
    {"Delete", GHOSTTY_KEY_DELETE},
    {"End", GHOSTTY_KEY_END},
    {"Home", GHOSTTY_KEY_HOME},
    {"Insert", GHOSTTY_KEY_INSERT},
    {"PageDown", GHOSTTY_KEY_PAGE_DOWN},
    {"PageUp", GHOSTTY_KEY_PAGE_UP},
    {"ArrowDown", GHOSTTY_KEY_ARROW_DOWN},
    {"ArrowLeft", GHOSTTY_KEY_ARROW_LEFT},
    {"ArrowRight", GHOSTTY_KEY_ARROW_RIGHT},
    {"ArrowUp", GHOSTTY_KEY_ARROW_UP},
    {"NumLock", GHOSTTY_KEY_NUM_LOCK},
    {"Numpad0", GHOSTTY_KEY_NUMPAD_0},
    {"Numpad1", GHOSTTY_KEY_NUMPAD_1},
    {"Numpad2", GHOSTTY_KEY_NUMPAD_2},
    {"Numpad3", GHOSTTY_KEY_NUMPAD_3},
    {"Numpad4", GHOSTTY_KEY_NUMPAD_4},
    {"Numpad5", GHOSTTY_KEY_NUMPAD_5},
    {"Numpad6", GHOSTTY_KEY_NUMPAD_6},
    {"Numpad7", GHOSTTY_KEY_NUMPAD_7},
    {"Numpad8", GHOSTTY_KEY_NUMPAD_8},
    {"Numpad9", GHOSTTY_KEY_NUMPAD_9},
    {"NumpadAdd", GHOSTTY_KEY_NUMPAD_ADD},
    {"NumpadDecimal", GHOSTTY_KEY_NUMPAD_DECIMAL},
    {"NumpadDivide", GHOSTTY_KEY_NUMPAD_DIVIDE},
    {"NumpadEnter", GHOSTTY_KEY_NUMPAD_ENTER},
    {"NumpadEqual", GHOSTTY_KEY_NUMPAD_EQUAL},
    {"NumpadMultiply", GHOSTTY_KEY_NUMPAD_MULTIPLY},
    {"NumpadSubtract", GHOSTTY_KEY_NUMPAD_SUBTRACT},
    {"Escape", GHOSTTY_KEY_ESCAPE},
    {"F1", GHOSTTY_KEY_F1}, {"F2", GHOSTTY_KEY_F2},
    {"F3", GHOSTTY_KEY_F3}, {"F4", GHOSTTY_KEY_F4},
    {"F5", GHOSTTY_KEY_F5}, {"F6", GHOSTTY_KEY_F6},
    {"F7", GHOSTTY_KEY_F7}, {"F8", GHOSTTY_KEY_F8},
    {"F9", GHOSTTY_KEY_F9}, {"F10", GHOSTTY_KEY_F10},
    {"F11", GHOSTTY_KEY_F11}, {"F12", GHOSTTY_KEY_F12},
    {"PrintScreen", GHOSTTY_KEY_PRINT_SCREEN},
    {"ScrollLock", GHOSTTY_KEY_SCROLL_LOCK},
    {"Pause", GHOSTTY_KEY_PAUSE},
};

static GhosttyTerminal terminal;
static GhosttyKeyEncoder key_encoder;
static GhosttyKeyEvent key_event;
static dolly_display_mailbox *mailbox;
static unsigned char *frames[DOLLY_DISPLAY_FRAME_COUNT];
static size_t frame_capacity;
static unsigned char *copy_buffer;
static size_t copy_capacity;
static stbtt_fontinfo font;
// Fonts for what the terminal's font has no glyph for, tried in order and
// read when first needed: Chinese, Japanese and Korean, then emoji, drawn in
// the text's colour.
typedef struct {
  const char *path;
  stbtt_fontinfo info;
  int loaded;  // 1 once read, -1 when it could not be
} fallback_font;
static fallback_font fallback_fonts[] = {
    {"/usr/share/fonts/DroidSansFallback.ttf"},
    {"/usr/share/fonts/NotoEmoji-Regular.ttf"},
};
static unsigned char *glyph_bitmap;
static size_t glyph_bitmap_capacity;
typedef struct {
  unsigned char *bitmap;
  int width;
  int height;
  int x0;
  int y0;
  int advance;
  bool ready;
} cached_glyph;
static cached_glyph ascii_glyphs[128];
static uint32_t viewport_width_css = 1000;
static uint32_t viewport_height_css = 650;
static uint32_t device_scale_milli = DEFAULT_SCALE_MILLI;
static uint32_t font_size_milli = DEFAULT_FONT_MILLI;
// Set by Ctrl+= and Ctrl+-; until then the surface decides the font.
static bool font_chosen;
static uint32_t framebuffer_width;
static uint32_t framebuffer_height;
static uint32_t framebuffer_stride;
static uint32_t cell_width;
static uint32_t cell_height;
static uint32_t padding_x;
static uint32_t padding_y;
static float font_scale;
static int font_ascent;
static unsigned char pty_response[PTY_RESPONSE_CAPACITY];
static size_t pty_response_read;
static size_t pty_response_write;
static GhosttySelectionGesture selection_gesture;
static GhosttySelectionGestureEvent selection_press;
static GhosttySelectionGestureEvent selection_drag;
static GhosttySelectionGestureEvent selection_release;
static int32_t scroll_remainder_milli;
// The button held as the records tell it, whether its press was reported to
// the program, and where the pointer last was: a wheel step is reported
// there. Motion is reported once per cell.
static GhosttyMouseEncoder mouse_encoder;
static GhosttyMouseEvent mouse_event;
static GhosttyMouseButton held_button = GHOSTTY_MOUSE_BUTTON_UNKNOWN;
static bool held_reported;
static GhosttyMousePosition pointer_position;
static uint32_t reported_column = UINT32_MAX;
static uint32_t reported_row = UINT32_MAX;
static bool suspended;
static bool frame_dirty;
static GhosttyKittyGraphicsPlacementIterator placements;

static const GhosttyColorRgb background = {0x26, 0x26, 0x26};
static const GhosttyColorRgb foreground = {0xe8, 0xe3, 0xd7};
static const GhosttyColorRgb accent = {0xf2, 0xd4, 0x5c};
static const GhosttyColorRgb dim = {0x77, 0x73, 0x6c};
static GhosttyColorRgb terminal_palette[256];

static uint32_t clamp_u32(uint32_t value, uint32_t low, uint32_t high) {
  if (value < low) return low;
  if (value > high) return high;
  return value;
}

// The font's bytes stay for as long as the terminal draws.
static int load_font(const char *path, stbtt_fontinfo *info) {
  FILE *file = fopen(path, "rb");
  if (file == NULL) return -1;
  long length = -1;
  if (fseek(file, 0, SEEK_END) == 0) length = ftell(file);
  unsigned char *bytes = length > 0 && fseek(file, 0, SEEK_SET) == 0
      ? malloc((size_t)length) : NULL;
  const bool read = bytes != NULL &&
      fread(bytes, 1, (size_t)length, file) == (size_t)length;
  fclose(file);
  const int offset = read ? stbtt_GetFontOffsetForIndex(bytes, 0) : -1;
  if (offset >= 0 && stbtt_InitFont(info, bytes, offset)) return 0;
  free(bytes);
  return -1;
}

static void configure_theme(void) {
  ghostty_color_palette_default(terminal_palette);
  for (size_t index = 0; index < 16; ++index) {
    terminal_palette[index] = foreground;
  }
  terminal_palette[0] = background;
  terminal_palette[3] = accent;
  terminal_palette[8] = dim;
  terminal_palette[11] = accent;
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_FOREGROUND,
                       &foreground);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_BACKGROUND,
                       &background);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_CURSOR, &accent);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_COLOR_PALETTE,
                       terminal_palette);
  size_t scrollback_bytes = 16u * 1024u * 1024u;
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_SCROLLBACK_MAX_BYTES,
                       &scrollback_bytes);
}

// XTWINOPS size queries (CSI 14/16/18 t) and in-band size reports: the grid
// and its cells in the frame's pixels, by which programs (pi) size images.
static bool terminal_size(GhosttyTerminal reporting, void *userdata,
                          GhosttySizeReportSize *size) {
  (void)userdata;
  uint16_t cols = 0;
  uint16_t rows = 0;
  if (ghostty_terminal_get(reporting, GHOSTTY_TERMINAL_DATA_COLS, &cols) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(reporting, GHOSTTY_TERMINAL_DATA_ROWS, &rows) != GHOSTTY_SUCCESS) {
    return false;
  }
  *size = (GhosttySizeReportSize){.rows = rows, .columns = cols,
                                  .cell_width = cell_width, .cell_height = cell_height};
  return true;
}

static void terminal_write_pty(GhosttyTerminal ignored,
                               void *userdata,
                               const uint8_t *bytes,
                               size_t length) {
  (void)ignored;
  (void)userdata;
  for (size_t index = 0; index < length; ++index) {
    if (pty_response_write - pty_response_read >= PTY_RESPONSE_CAPACITY) break;
    pty_response[pty_response_write++ & (PTY_RESPONSE_CAPACITY - 1)] = bytes[index];
  }
}

static GhosttyColorRgb theme_color(const GhosttyStyleColor *value,
                                   bool is_background) {
  if (value->tag == GHOSTTY_STYLE_COLOR_RGB) return value->value.rgb;
  if (value->tag == GHOSTTY_STYLE_COLOR_PALETTE) {
    return terminal_palette[value->value.palette];
  }
  return is_background ? background : foreground;
}

static void publish_selection(void) {
  uint32_t flags = 0;
  uint32_t length = 0;
  if (terminal != NULL && copy_buffer != NULL && copy_capacity != 0) {
    GhosttyTerminalSelectionFormatOptions options =
        GHOSTTY_INIT_SIZED(GhosttyTerminalSelectionFormatOptions);
    options.emit = GHOSTTY_FORMATTER_FORMAT_PLAIN;
    options.unwrap = true;
    options.trim = true;
    options.selection = NULL;
    size_t required = 0;
    GhosttyResult result = ghostty_terminal_selection_format_buf(
        terminal, options, NULL, 0, &required);
    if (result == GHOSTTY_SUCCESS || result == GHOSTTY_OUT_OF_SPACE) {
      flags = DOLLY_DISPLAY_COPY_AVAILABLE;
      if (required > copy_capacity) {
        flags |= DOLLY_DISPLAY_COPY_TRUNCATED;
      } else if (required != 0) {
        size_t written = 0;
        if (ghostty_terminal_selection_format_buf(
                terminal, options, copy_buffer, copy_capacity,
                &written) == GHOSTTY_SUCCESS) {
          length = (uint32_t)written;
        } else {
          flags = 0;
        }
      }
    }
  }
  __c11_atomic_store(&mailbox->copy_length, length, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->copy_flags, flags, __ATOMIC_RELAXED);
  __c11_atomic_fetch_add(&mailbox->copy_sequence, 1, __ATOMIC_RELEASE);
}

static void fill_rect(unsigned char *frame, int x, int y, int width, int height,
                      GhosttyColorRgb color) {
  if (x < 0) { width += x; x = 0; }
  if (y < 0) { height += y; y = 0; }
  if (x + width > (int)framebuffer_width) width = (int)framebuffer_width - x;
  if (y + height > (int)framebuffer_height) height = (int)framebuffer_height - y;
  if (width <= 0 || height <= 0) return;
  for (int row = 0; row < height; ++row) {
    unsigned char *pixel = frame + (size_t)(y + row) * framebuffer_stride +
                           (size_t)x * 4;
    for (int column = 0; column < width; ++column) {
      pixel[0] = color.r;
      pixel[1] = color.g;
      pixel[2] = color.b;
      pixel[3] = 255;
      pixel += 4;
    }
  }
}

static bool decode_png(void *userdata, const GhosttyAllocator *allocator,
                       const uint8_t *data, size_t length, GhosttySysImage *out) {
  (void)userdata;
  int width = 0;
  int height = 0;
  if (length > INT32_MAX) return false;
  stbi_uc *pixels = stbi_load_from_memory(data, (int)length, &width, &height, NULL, 4);
  if (pixels == NULL) return false;
  const size_t size = (size_t)width * (size_t)height * 4;
  uint8_t *copy = ghostty_alloc(allocator, size);
  if (copy != NULL) memcpy(copy, pixels, size);
  stbi_image_free(pixels);
  if (copy == NULL) return false;
  *out = (GhosttySysImage){.width = (uint32_t)width, .height = (uint32_t)height,
                           .data = copy, .data_len = size};
  return true;
}

// The kitty graphics placements of one layer, each scaled to its cells by
// the nearest source pixel and blended over the frame.
static void draw_images(unsigned char *frame, GhosttyKittyPlacementLayer layer) {
  GhosttyKittyGraphics graphics = NULL;
  if (ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_KITTY_GRAPHICS,
                           &graphics) != GHOSTTY_SUCCESS || graphics == NULL ||
      ghostty_kitty_graphics_placement_iterator_set(
          placements, GHOSTTY_KITTY_GRAPHICS_PLACEMENT_ITERATOR_OPTION_LAYER,
          &layer) != GHOSTTY_SUCCESS ||
      ghostty_kitty_graphics_get(graphics, GHOSTTY_KITTY_GRAPHICS_DATA_PLACEMENT_ITERATOR,
                                 &placements) != GHOSTTY_SUCCESS) return;
  while (ghostty_kitty_graphics_placement_next(placements)) {
    uint32_t id = 0, x_offset = 0, y_offset = 0, width = 0, height = 0;
    GhosttyKittyImageFormat format = GHOSTTY_KITTY_IMAGE_FORMAT_RGBA;
    const uint8_t *pixels = NULL;
    GhosttyKittyGraphicsPlacementRenderInfo info =
        GHOSTTY_INIT_SIZED(GhosttyKittyGraphicsPlacementRenderInfo);
    if (ghostty_kitty_graphics_placement_get_multi(placements, 3,
            (GhosttyKittyGraphicsPlacementData[]){
                GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_IMAGE_ID,
                GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_X_OFFSET,
                GHOSTTY_KITTY_GRAPHICS_PLACEMENT_DATA_Y_OFFSET},
            (void *[]){&id, &x_offset, &y_offset}, NULL) != GHOSTTY_SUCCESS) continue;
    GhosttyKittyGraphicsImage image = ghostty_kitty_graphics_image(graphics, id);
    if (image == NULL ||
        ghostty_kitty_graphics_image_get_multi(image, 4,
            (GhosttyKittyGraphicsImageData[]){
                GHOSTTY_KITTY_IMAGE_DATA_WIDTH, GHOSTTY_KITTY_IMAGE_DATA_HEIGHT,
                GHOSTTY_KITTY_IMAGE_DATA_FORMAT, GHOSTTY_KITTY_IMAGE_DATA_DATA_PTR},
            (void *[]){&width, &height, &format, &pixels}, NULL) != GHOSTTY_SUCCESS ||
        ghostty_kitty_graphics_placement_render_info(placements, image, terminal,
                                                     &info) != GHOSTTY_SUCCESS ||
        !info.viewport_visible || pixels == NULL || info.pixel_width == 0 ||
        info.pixel_height == 0) continue;
    // Stored pixels are decoded and decompressed: one of four layouts.
    const size_t channels = format == GHOSTTY_KITTY_IMAGE_FORMAT_RGBA ? 4
        : format == GHOSTTY_KITTY_IMAGE_FORMAT_RGB ? 3
        : format == GHOSTTY_KITTY_IMAGE_FORMAT_GRAY_ALPHA ? 2
        : format == GHOSTTY_KITTY_IMAGE_FORMAT_GRAY ? 1 : 0;
    if (channels == 0) continue;
    const int64_t left = (int64_t)padding_x + (int64_t)info.viewport_col * cell_width + x_offset;
    const int64_t top = (int64_t)padding_y + (int64_t)info.viewport_row * cell_height + y_offset;
    for (uint32_t dy = 0; dy < info.pixel_height; ++dy) {
      const int64_t y = top + dy;
      const uint64_t sy = info.source_y + (uint64_t)dy * info.source_height / info.pixel_height;
      if (y < 0 || y >= framebuffer_height || sy >= height) continue;
      unsigned char *row = frame + (size_t)y * framebuffer_stride;
      for (uint32_t dx = 0; dx < info.pixel_width; ++dx) {
        const int64_t x = left + dx;
        const uint64_t sx = info.source_x + (uint64_t)dx * info.source_width / info.pixel_width;
        if (x < 0 || x >= framebuffer_width || sx >= width) continue;
        const uint8_t *source = pixels + ((size_t)sy * width + sx) * channels;
        const unsigned red = source[0];
        const unsigned green = channels >= 3 ? source[1] : red;
        const unsigned blue = channels >= 3 ? source[2] : red;
        const unsigned alpha = channels == 4 ? source[3] : channels == 2 ? source[1] : 255;
        unsigned char *pixel = row + (size_t)x * 4;
        pixel[0] = (unsigned char)((red * alpha + pixel[0] * (255 - alpha)) / 255);
        pixel[1] = (unsigned char)((green * alpha + pixel[1] * (255 - alpha)) / 255);
        pixel[2] = (unsigned char)((blue * alpha + pixel[2] * (255 - alpha)) / 255);
      }
    }
  }
}

static int ensure_glyph_bitmap(size_t size) {
  if (size <= glyph_bitmap_capacity) return 0;
  unsigned char *grown = realloc(glyph_bitmap, size);
  if (grown == NULL) return -1;
  glyph_bitmap = grown;
  glyph_bitmap_capacity = size;
  return 0;
}

static void clear_glyph_cache(void) {
  for (size_t index = 0; index < sizeof(ascii_glyphs) / sizeof(ascii_glyphs[0]); index++) {
    free(ascii_glyphs[index].bitmap);
    memset(&ascii_glyphs[index], 0, sizeof(ascii_glyphs[index]));
  }
}

// The first fallback font with a glyph for codepoint, its glyph and its
// scale: the terminal font's em, and at most the width of the cells the
// character takes. The terminal's font and glyph 0 when none has one.
static const stbtt_fontinfo *fallback_glyph(uint32_t codepoint, int span_pixels,
                                            int *glyph, float *scale) {
  for (size_t index = 0; index < sizeof(fallback_fonts) / sizeof(fallback_fonts[0]); ++index) {
    fallback_font *fallback = &fallback_fonts[index];
    if (fallback->loaded == 0) {
      fallback->loaded = load_font(fallback->path, &fallback->info) == 0 ? 1 : -1;
    }
    if (fallback->loaded < 0 ||
        (*glyph = stbtt_FindGlyphIndex(&fallback->info, (int)codepoint)) == 0) continue;
    const float em_pixels = font_scale / stbtt_ScaleForMappingEmToPixels(&font, 1.0f);
    *scale = stbtt_ScaleForMappingEmToPixels(&fallback->info, em_pixels);
    int advance = 0, bearing = 0;
    stbtt_GetGlyphHMetrics(&fallback->info, *glyph, &advance, &bearing);
    if (advance * *scale > span_pixels) *scale = (float)span_pixels / (float)advance;
    return &fallback->info;
  }
  return &font;
}

// Draws one codepoint of a cell span cells wide. A grapheme's later
// codepoints (combining marks, variation selectors, joined emoji) are drawn
// over its first only from the terminal's font.
static void draw_codepoint(unsigned char *frame, uint32_t codepoint, bool first,
                           int cell_x, int cell_y, int span, GhosttyColorRgb color) {
  int x0, y0, width, height, advance;
  const unsigned char *bitmap;
  const int span_pixels = span * (int)cell_width;
  float scale = font_scale;
  cached_glyph *cached = codepoint < 128 ? &ascii_glyphs[codepoint] : NULL;
  if (cached != NULL && cached->ready) {
    x0 = cached->x0;
    y0 = cached->y0;
    width = cached->width;
    height = cached->height;
    advance = cached->advance;
    bitmap = cached->bitmap;
  } else {
    // A character two cells wide comes from a fallback font that has it:
    // the terminal's font draws in one cell.
    int glyph = 0;
    const stbtt_fontinfo *face = first && span == 2
        ? fallback_glyph(codepoint, span_pixels, &glyph, &scale) : &font;
    if (glyph == 0) glyph = stbtt_FindGlyphIndex(&font, (int)codepoint);
    if (glyph == 0 && first && span == 1) {
      face = fallback_glyph(codepoint, span_pixels, &glyph, &scale);
    }
    if (glyph == 0 && !first) return;
    int x1, y1, left_bearing = 0;
    stbtt_GetGlyphBitmapBox(face, glyph, scale, scale, &x0, &y0, &x1, &y1);
    width = x1 - x0;
    height = y1 - y0;
    stbtt_GetGlyphHMetrics(face, glyph, &advance, &left_bearing);
    (void)left_bearing;
    if (width <= 0 || height <= 0) return;
    const size_t bitmap_size = (size_t)width * (size_t)height;
    if (cached != NULL) {
      cached->bitmap = malloc(bitmap_size);
      if (cached->bitmap == NULL) return;
      stbtt_MakeGlyphBitmap(face, cached->bitmap, width, height, width,
                            scale, scale, glyph);
      cached->width = width;
      cached->height = height;
      cached->x0 = x0;
      cached->y0 = y0;
      cached->advance = advance;
      cached->ready = true;
      bitmap = cached->bitmap;
    } else {
      if (ensure_glyph_bitmap(bitmap_size) != 0) return;
      stbtt_MakeGlyphBitmap(face, glyph_bitmap, width, height, width,
                            scale, scale, glyph);
      bitmap = glyph_bitmap;
    }
  }
  const int drawn_advance = (int)(advance * scale + 0.5f);
  const int origin_x = cell_x + (span_pixels - drawn_advance) / 2 + x0;
  const int baseline = cell_y + ((int)cell_height +
      (int)(font_ascent * font_scale + 0.5f)) / 2;
  const int origin_y = baseline + y0;
  for (int row = 0; row < height; ++row) {
    const int destination_y = origin_y + row;
    if (destination_y < 0 || destination_y >= (int)framebuffer_height) continue;
    for (int column = 0; column < width; ++column) {
      const int destination_x = origin_x + column;
      if (destination_x < 0 || destination_x >= (int)framebuffer_width) continue;
      const unsigned alpha = bitmap[(size_t)row * width + column];
      if (alpha == 0) continue;
      unsigned char *pixel = frame + (size_t)destination_y * framebuffer_stride +
                             (size_t)destination_x * 4;
      pixel[0] = (unsigned char)((pixel[0] * (255 - alpha) + color.r * alpha) / 255);
      pixel[1] = (unsigned char)((pixel[1] * (255 - alpha) + color.g * alpha) / 255);
      pixel[2] = (unsigned char)((pixel[2] * (255 - alpha) + color.b * alpha) / 255);
      pixel[3] = 255;
    }
  }
}

static float font_pixels_of(uint32_t font_milli) {
  return ((float)font_milli * device_scale_milli) / 1000000.0f;
}

static uint32_t cell_width_of(float font_pixels) {
  int advance = 0;
  int bearing = 0;
  stbtt_GetCodepointHMetrics(&font, 'M', &advance, &bearing);
  (void)bearing;
  const uint32_t width = (uint32_t)(
      advance * stbtt_ScaleForPixelHeight(&font, font_pixels) + 0.5f);
  return width < 4 ? 4 : width;
}

// 20 CSS pixels, or on a surface narrower than 640 (a phone) the largest size
// down to 12 that gives 48 columns.
static uint32_t surface_font_milli(uint32_t usable_width) {
  uint32_t font_milli = DEFAULT_FONT_MILLI;
  while (viewport_width_css < NARROW_WIDTH_CSS &&
         font_milli > NARROW_MIN_FONT_MILLI &&
         usable_width < NARROW_COLUMNS *
             cell_width_of(font_pixels_of(font_milli))) font_milli -= 1000;
  return font_milli;
}

static int set_layout(uint32_t width_css, uint32_t height_css,
                      uint32_t scale_milli) {
  viewport_width_css = clamp_u32(width_css, 160, 8192);
  viewport_height_css = clamp_u32(height_css, 100, 8192);
  device_scale_milli = clamp_u32(scale_milli, 500, 4000);

  uint64_t width = ((uint64_t)viewport_width_css * device_scale_milli + 500) / 1000;
  uint64_t height = ((uint64_t)viewport_height_css * device_scale_milli + 500) / 1000;
  if (width > DOLLY_DISPLAY_MAX_WIDTH) width = DOLLY_DISPLAY_MAX_WIDTH;
  if (height > DOLLY_DISPLAY_MAX_HEIGHT) height = DOLLY_DISPLAY_MAX_HEIGHT;
  framebuffer_width = (uint32_t)width;
  framebuffer_height = (uint32_t)height;
  framebuffer_stride = framebuffer_width * 4;
  if ((uint64_t)framebuffer_stride * framebuffer_height > frame_capacity) return -1;
  // Geometry belongs to the shared display surface, even while terminal frame
  // publication is suspended by a graphics lease. The sequence is advanced
  // only after a renderer has filled and presented a complete buffer.
  __c11_atomic_store(&mailbox->frame_width, framebuffer_width,
                     __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->frame_height, framebuffer_height,
                     __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->frame_stride, framebuffer_stride,
                     __ATOMIC_RELAXED);

  padding_x = (12u * device_scale_milli + 500) / 1000;
  padding_y = (10u * device_scale_milli + 500) / 1000;
  if (!font_chosen) {
    font_size_milli = surface_font_milli(framebuffer_width > 2 * padding_x
        ? framebuffer_width - 2 * padding_x : 0);
  }
  const float font_pixels = font_pixels_of(font_size_milli);
  clear_glyph_cache();
  font_scale = stbtt_ScaleForPixelHeight(&font, font_pixels);
  int descent = 0;
  int line_gap = 0;
  stbtt_GetFontVMetrics(&font, &font_ascent, &descent, &line_gap);
  cell_width = cell_width_of(font_pixels);
  cell_height = (uint32_t)(font_pixels * 1.32f + 0.5f);
  if (cell_height < 8) cell_height = 8;
  uint32_t usable_width = framebuffer_width > 2 * padding_x
      ? framebuffer_width - 2 * padding_x : cell_width;
  uint32_t usable_height = framebuffer_height > 2 * padding_y
      ? framebuffer_height - 2 * padding_y : cell_height;
  uint32_t cols = clamp_u32(usable_width / cell_width, 1, UINT16_MAX);
  uint32_t rows = clamp_u32(usable_height / cell_height, 1, UINT16_MAX);
  if (ghostty_terminal_resize(terminal, (uint16_t)cols, (uint16_t)rows,
                              cell_width, cell_height) != GHOSTTY_SUCCESS) return -1;
  __c11_atomic_store(&mailbox->terminal_cols, cols, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->terminal_rows, rows, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->font_size_milli, font_size_milli,
                     __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->cell_width, cell_width, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->cell_height, cell_height, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->padding_x, padding_x, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->padding_y, padding_y, __ATOMIC_RELAXED);
  return 0;
}

// Whether the program asked for mouse reports (CSI ? 1000 h and the modes
// beside it).
static bool mouse_reporting(void) {
  bool tracking = false;
  return ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_MOUSE_TRACKING,
                              &tracking) == GHOSTTY_SUCCESS && tracking;
}

static void render_frame(void) {
  if (suspended || terminal == NULL || frames[0] == NULL ||
      frames[1] == NULL) return;
  // The arrow, as terminals show it, while a program asks for the mouse: the
  // page then gives the program every button (host/input/input.mjs).
  __c11_atomic_store(&mailbox->cursor_style, mouse_reporting()
      ? DOLLY_DISPLAY_CURSOR_DEFAULT : DOLLY_DISPLAY_CURSOR_TEXT, __ATOMIC_RELAXED);
  uint16_t cols = 0;
  uint16_t rows = 0;
  uint16_t cursor_x = 0;
  uint16_t cursor_y = 0;
  bool cursor_visible = false;
  GhosttyTerminalScrollbar scrollbar = {0};
  if (ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_COLS, &cols) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_ROWS, &rows) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_CURSOR_X, &cursor_x) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_CURSOR_Y, &cursor_y) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_CURSOR_VISIBLE,
                           &cursor_visible) != GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_SCROLLBAR,
                           &scrollbar) != GHOSTTY_SUCCESS) return;
  const bool viewport_at_bottom = scrollbar.offset >= scrollbar.total ||
      scrollbar.len >= scrollbar.total - scrollbar.offset;
  cursor_visible = cursor_visible && viewport_at_bottom;

  GhosttySelection selection = GHOSTTY_INIT_SIZED(GhosttySelection);
  const bool has_selection = ghostty_terminal_get(
      terminal, GHOSTTY_TERMINAL_DATA_SELECTION, &selection) == GHOSTTY_SUCCESS;
  publish_selection();

  const uint32_t active = __c11_atomic_load(&mailbox->frame_index,
                                             __ATOMIC_ACQUIRE) & 1u;
  const uint32_t next = active ^ 1u;
  unsigned char *frame = frames[next];
  fill_rect(frame, 0, 0, (int)framebuffer_width, (int)framebuffer_height,
            background);
  // Images below the text lie under the cells' own backgrounds too (kitty
  // keeps those of z below -1073741824 only beneath them).
  draw_images(frame, GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_BG);
  draw_images(frame, GHOSTTY_KITTY_PLACEMENT_LAYER_BELOW_TEXT);

  for (uint16_t row = 0; row < rows; ++row) {
    for (uint16_t column = 0; column < cols; ++column) {
      GhosttyGridRef ref = GHOSTTY_INIT_SIZED(GhosttyGridRef);
      const GhosttyPoint point = {
          .tag = GHOSTTY_POINT_TAG_VIEWPORT,
          .value = {.coordinate = {.x = column, .y = row}},
      };
      if (ghostty_terminal_grid_ref(terminal, point, &ref) != GHOSTTY_SUCCESS) continue;
      GhosttyCell cell = 0;
      GhosttyStyle style = GHOSTTY_INIT_SIZED(GhosttyStyle);
      GhosttyCellContentTag content = GHOSTTY_CELL_CONTENT_CODEPOINT;
      bool has_text = false;
      GhosttyCellWide wide = GHOSTTY_CELL_WIDE_NARROW;
      if (ghostty_grid_ref_cell(&ref, &cell) != GHOSTTY_SUCCESS ||
          ghostty_grid_ref_style(&ref, &style) != GHOSTTY_SUCCESS ||
          ghostty_cell_get(cell, GHOSTTY_CELL_DATA_CONTENT_TAG, &content) != GHOSTTY_SUCCESS ||
          ghostty_cell_get(cell, GHOSTTY_CELL_DATA_HAS_TEXT, &has_text) != GHOSTTY_SUCCESS ||
          ghostty_cell_get(cell, GHOSTTY_CELL_DATA_WIDE, &wide) != GHOSTTY_SUCCESS) continue;

      GhosttyColorRgb fg = theme_color(&style.fg_color, false);
      GhosttyColorRgb bg = theme_color(&style.bg_color, true);
      // Erased cells store their background in the cell, not its text style.
      if (content == GHOSTTY_CELL_CONTENT_BG_COLOR_RGB) {
        (void)ghostty_cell_get(cell, GHOSTTY_CELL_DATA_COLOR_RGB, &bg);
      } else if (content == GHOSTTY_CELL_CONTENT_BG_COLOR_PALETTE) {
        GhosttyColorPaletteIndex index = 0;
        (void)ghostty_cell_get(cell, GHOSTTY_CELL_DATA_COLOR_PALETTE, &index);
        bg = terminal_palette[index];
      }
      if (style.inverse) {
        GhosttyColorRgb temporary = fg;
        fg = bg;
        bg = temporary;
      }
      const int x = (int)padding_x + (int)column * (int)cell_width;
      const int y = (int)padding_y + (int)row * (int)cell_height;
      if (bg.r != background.r || bg.g != background.g || bg.b != background.b) {
        fill_rect(frame, x, y, (int)cell_width, (int)cell_height, bg);
      }
      bool selected = false;
      if (has_selection) {
        (void)ghostty_terminal_selection_contains(
            terminal, &selection, point, &selected);
      }
      const bool cursor_here = cursor_visible && cursor_x == column &&
                               cursor_y == row;
      if (selected || cursor_here) {
        bg = accent;
        fg = background;
        fill_rect(frame, x, y, (int)cell_width, (int)cell_height, bg);
      }
      if (style.faint) {
        fg.r = (uint8_t)((fg.r + background.r) / 2);
        fg.g = (uint8_t)((fg.g + background.g) / 2);
        fg.b = (uint8_t)((fg.b + background.b) / 2);
      }
      if (has_text && !style.invisible &&
          wide != GHOSTTY_CELL_WIDE_SPACER_TAIL) {
        const int span = wide == GHOSTTY_CELL_WIDE_WIDE ? 2 : 1;
        uint32_t codepoints[MAX_GRAPHEME_CODEPOINTS];
        size_t count = 0;
        GhosttyResult result = ghostty_grid_ref_graphemes(
            &ref, codepoints, MAX_GRAPHEME_CODEPOINTS, &count);
        if (result == GHOSTTY_SUCCESS) {
          for (size_t index = 0; index < count; ++index) {
            draw_codepoint(frame, codepoints[index], index == 0, x, y, span, fg);
          }
        } else {
          uint32_t codepoint = 0;
          if (ghostty_cell_get(cell, GHOSTTY_CELL_DATA_CODEPOINT,
                               &codepoint) == GHOSTTY_SUCCESS) {
            draw_codepoint(frame, codepoint, true, x, y, span, fg);
          }
        }
      }
      if (style.underline != 0) {
        fill_rect(frame, x, y + (int)cell_height - 2,
                  (int)cell_width, 1, fg);
      }
      if (style.strikethrough) {
        fill_rect(frame, x, y + (int)cell_height / 2,
                  (int)cell_width, 1, fg);
      }
    }
  }

  draw_images(frame, GHOSTTY_KITTY_PLACEMENT_LAYER_ABOVE_TEXT);

  __c11_atomic_store(&mailbox->frame_width, framebuffer_width, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->frame_height, framebuffer_height, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->frame_stride, framebuffer_stride, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->terminal_cols, cols, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->terminal_rows, rows, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->cursor_col,
                     cursor_visible ? cursor_x : UINT32_MAX, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->cursor_row,
                     cursor_visible ? cursor_y : UINT32_MAX, __ATOMIC_RELAXED);
  __c11_atomic_store(&mailbox->frame_index, next, __ATOMIC_RELEASE);
  __c11_atomic_fetch_add(&mailbox->frame_sequence, 1, __ATOMIC_ACQ_REL);
  frame_dirty = false;
}

static const dolly_input_decoder decoder;

static int initialize(dolly_display_mailbox *shared_mailbox,
                      unsigned char *frame_a,
                      unsigned char *frame_b,
                      size_t capacity,
                      unsigned char *shared_copy_buffer,
                      size_t shared_copy_capacity) {
  static const char font_path[] = "/usr/share/fonts/IosevkaTerm-SemiBold.ttf";
  if (shared_mailbox == NULL || frame_a == NULL || frame_b == NULL ||
      capacity < (size_t)160 * 100 * 4 ||
      shared_copy_buffer == NULL || shared_copy_capacity == 0) return -1;
  mailbox = shared_mailbox;
  frames[0] = frame_a;
  frames[1] = frame_b;
  frame_capacity = capacity;
  copy_buffer = shared_copy_buffer;
  copy_capacity = shared_copy_capacity;
  ghostty_sys_set(GHOSTTY_SYS_OPT_DECODE_PNG, (const void *)decode_png);
  if (load_font(font_path, &font) != 0 ||
      ghostty_terminal_new(NULL, &terminal, 100, 30) != GHOSTTY_SUCCESS ||
      ghostty_kitty_graphics_placement_iterator_new(NULL, &placements) != GHOSTTY_SUCCESS ||
      ghostty_key_encoder_new(NULL, &key_encoder) != GHOSTTY_SUCCESS ||
      ghostty_key_event_new(NULL, &key_event) != GHOSTTY_SUCCESS ||
      ghostty_mouse_encoder_new(NULL, &mouse_encoder) != GHOSTTY_SUCCESS ||
      ghostty_mouse_event_new(NULL, &mouse_event) != GHOSTTY_SUCCESS ||
      ghostty_selection_gesture_new(NULL, &selection_gesture) !=
          GHOSTTY_SUCCESS ||
      ghostty_selection_gesture_event_new(
          NULL, &selection_press,
          GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_PRESS) != GHOSTTY_SUCCESS ||
      ghostty_selection_gesture_event_new(
          NULL, &selection_drag,
          GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_DRAG) != GHOSTTY_SUCCESS ||
      ghostty_selection_gesture_event_new(
          NULL, &selection_release,
          GHOSTTY_SELECTION_GESTURE_EVENT_TYPE_RELEASE) != GHOSTTY_SUCCESS) {
    return -1;
  }
  configure_theme();
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_KITTY_IMAGE_STORAGE_LIMIT,
                       &kitty_image_storage_limit);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_USERDATA, NULL);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_WRITE_PTY,
                       terminal_write_pty);
  ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_SIZE, terminal_size);
  if (set_layout(viewport_width_css, viewport_height_css,
                 device_scale_milli) != 0) return -1;
  render_frame();
  return dolly_input_decoder_install(&decoder);
}

static void write_terminal(const unsigned char *bytes, size_t length) {
  if (terminal == NULL || bytes == NULL || length == 0) return;
  ghostty_terminal_vt_write(terminal, bytes, length);
  frame_dirty = true;
}

// Copies the replies the terminal owes its program.
static size_t read_replies(unsigned char *output, size_t capacity) {
  size_t length = pty_response_write - pty_response_read;
  if (length > capacity) length = capacity;
  for (size_t index = 0; index < length; ++index) {
    output[index] = pty_response[pty_response_read++ & (PTY_RESPONSE_CAPACITY - 1)];
  }
  if (pty_response_read == pty_response_write) {
    pty_response_read = 0;
    pty_response_write = 0;
  }
  return length;
}

static int resize(uint32_t width_css, uint32_t height_css, uint32_t scale_milli) {
  frame_dirty = true;
  return set_layout(width_css, height_css, scale_milli);
}

static void present(void) {
  if (frame_dirty) render_frame();
}

static void set_suspended(int value) {
  const bool was_suspended = suspended;
  suspended = value != 0;
  if (was_suspended && !suspended) render_frame();
}

static GhosttyKey map_key(const char *code) {
  for (size_t index = 0;
       index < sizeof(key_mappings) / sizeof(key_mappings[0]); ++index) {
    if (strcmp(code, key_mappings[index].code) == 0) return key_mappings[index].key;
  }
  return GHOSTTY_KEY_UNIDENTIFIED;
}

static uint32_t unshifted_codepoint(const char *code) {
  if (code[0] == 'K' && code[1] == 'e' && code[2] == 'y' &&
      code[3] >= 'A' && code[3] <= 'Z' && code[4] == '\0') {
    return (uint32_t)('a' + code[3] - 'A');
  }
  if (strncmp(code, "Digit", 5) == 0 && code[5] >= '0' &&
      code[5] <= '9' && code[6] == '\0') return (uint32_t)code[5];
  static const struct { const char *code; uint32_t value; } values[] = {
      {"Backquote", '`'}, {"Backslash", '\\'}, {"BracketLeft", '['},
      {"BracketRight", ']'}, {"Comma", ','}, {"Equal", '='},
      {"Minus", '-'}, {"Period", '.'}, {"Quote", '\''},
      {"Semicolon", ';'}, {"Slash", '/'}, {"Space", ' '},
  };
  for (size_t index = 0; index < sizeof(values) / sizeof(values[0]); ++index) {
    if (strcmp(code, values[index].code) == 0) return values[index].value;
  }
  return 0;
}

static bool printable_key(const char *key, size_t length) {
  if (length == 0 || (unsigned char)key[0] < 0x20 ||
      (length == 1 && (unsigned char)key[0] == 0x7f)) return false;
  static const char *special[] = {
      "Alt", "AltGraph", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp",
      "Backspace", "CapsLock", "Control", "Dead", "Delete", "End", "Enter",
      "Escape", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9",
      "F10", "F11", "F12", "Home", "Insert", "Meta", "PageDown", "PageUp",
      "Pause", "Process", "ScrollLock", "Shift", "Tab", "Unidentified",
  };
  for (size_t index = 0; index < sizeof(special) / sizeof(special[0]); ++index) {
    if (strlen(special[index]) == length &&
        memcmp(key, special[index], length) == 0) return false;
  }
  return true;
}

static GhosttyMods ghostty_mods(uint32_t modifiers) {
  GhosttyMods mods = 0;
  if ((modifiers & DOLLY_INPUT_MOD_SHIFT) != 0) mods |= GHOSTTY_MODS_SHIFT;
  if ((modifiers & DOLLY_INPUT_MOD_CONTROL) != 0) mods |= GHOSTTY_MODS_CTRL;
  if ((modifiers & DOLLY_INPUT_MOD_ALT) != 0) mods |= GHOSTTY_MODS_ALT;
  if ((modifiers & DOLLY_INPUT_MOD_META) != 0) mods |= GHOSTTY_MODS_SUPER;
  if ((modifiers & DOLLY_INPUT_MOD_CAPS_LOCK) != 0) mods |= GHOSTTY_MODS_CAPS_LOCK;
  if ((modifiers & DOLLY_INPUT_MOD_NUM_LOCK) != 0) mods |= GHOSTTY_MODS_NUM_LOCK;
  return mods;
}

typedef struct {
  const unsigned char *bytes;
  size_t length;
} paste_source;

static bool read_paste(void *userdata, GhosttyString mime,
                       GhosttyWriter writer) {
  (void)mime;
  const paste_source *source = userdata;
  return source->length == 0 ||
         writer.write(writer.userdata, source->bytes, source->length);
}

static int decode_paste(const unsigned char *bytes, size_t size,
                        unsigned char *output, size_t capacity,
                        size_t *length) {
  static const uint8_t mime_bytes[] = "text/plain";
  const GhosttyString mime = {
      .ptr = mime_bytes,
      .len = sizeof(mime_bytes) - 1,
  };
  const paste_source source = {
      .bytes = bytes,
      .length = size,
  };
  const GhosttyPaste paste = {
      .size = sizeof(GhosttyPaste),
      .location = GHOSTTY_CLIPBOARD_LOCATION_STANDARD,
      .source = GHOSTTY_PASTE_SOURCE_CLIPBOARD,
      .mimes = &mime,
      .mimes_len = 1,
      .reader = {.read = read_paste, .userdata = (void *)&source},
      // The browser only creates this event from an explicit user paste.
      .allow_unsafe = true,
  };
  *length = 0;
  if (ghostty_terminal_paste(terminal, &paste, NULL) != GHOSTTY_SUCCESS) return -1;
  *length = read_replies(output, capacity);
  return 0;
}

// Writes the report of one press, release or motion at the pointer, in the
// form the program asked for, where the terminal's replies go. The encoder
// leaves out what the program's mode does not report.
static void report_mouse(GhosttyMouseAction action, GhosttyMouseButton button,
                         uint32_t modifiers, uint32_t column, uint32_t row) {
  if (action == GHOSTTY_MOUSE_ACTION_MOTION && column == reported_column &&
      row == reported_row) return;
  const GhosttyMouseEncoderSize size = {
      .size = sizeof(GhosttyMouseEncoderSize),
      .screen_width = framebuffer_width,
      .screen_height = framebuffer_height,
      .cell_width = cell_width,
      .cell_height = cell_height,
      .padding_top = padding_y,
      .padding_bottom = padding_y,
      .padding_right = padding_x,
      .padding_left = padding_x,
  };
  const bool pressed = held_button != GHOSTTY_MOUSE_BUTTON_UNKNOWN || action == GHOSTTY_MOUSE_ACTION_PRESS;
  ghostty_mouse_encoder_setopt_from_terminal(mouse_encoder, terminal);
  ghostty_mouse_encoder_setopt(mouse_encoder, GHOSTTY_MOUSE_ENCODER_OPT_SIZE, &size);
  ghostty_mouse_encoder_setopt(mouse_encoder,
                               GHOSTTY_MOUSE_ENCODER_OPT_ANY_BUTTON_PRESSED, &pressed);
  ghostty_mouse_event_set_action(mouse_event, action);
  if (button == GHOSTTY_MOUSE_BUTTON_UNKNOWN) ghostty_mouse_event_clear_button(mouse_event);
  else ghostty_mouse_event_set_button(mouse_event, button);
  ghostty_mouse_event_set_mods(mouse_event, ghostty_mods(modifiers));
  ghostty_mouse_event_set_position(mouse_event, pointer_position);
  char report[64];
  size_t length = 0;
  if (ghostty_mouse_encoder_encode(mouse_encoder, mouse_event, report,
                                   sizeof(report), &length) != GHOSTTY_SUCCESS ||
      length == 0) return;
  terminal_write_pty(terminal, NULL, (const uint8_t *)report, length);
  reported_column = column;
  reported_row = row;
}

// A press and what follows up to its release go to a program that asked for
// the mouse, unless Shift is held: then, and while no program asks, the
// primary button's are the terminal's selection. Motion without a button is
// the program's alone.
static int handle_pointer(const dolly_input_event *event) {
  const uint32_t x = event->x > 0 ? (uint32_t)event->x : 0;
  const uint32_t y = event->y > 0 ? (uint32_t)event->y : 0;
  uint16_t cols = 0;
  uint16_t rows = 0;
  if (ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_COLS, &cols) !=
          GHOSTTY_SUCCESS ||
      ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_ROWS, &rows) !=
          GHOSTTY_SUCCESS ||
      cols == 0 || rows == 0) return -1;

  uint32_t column = x > padding_x ? (x - padding_x) / cell_width : 0;
  uint32_t row = y > padding_y ? (y - padding_y) / cell_height : 0;
  if (column >= cols) column = cols - 1;
  if (row >= rows) row = rows - 1;
  pointer_position = (GhosttyMousePosition){.x = (float)x, .y = (float)y};
  const bool shifted = (event->modifiers & DOLLY_INPUT_MOD_SHIFT) != 0;
  if (event->action == DOLLY_POINTER_ACTION_PRESS) {
    // The record's button as a browser numbers them: primary, middle, secondary.
    const uint32_t number = event->flags >> 8;
    held_button = number == 1 ? GHOSTTY_MOUSE_BUTTON_MIDDLE
        : number == 2 ? GHOSTTY_MOUSE_BUTTON_RIGHT : GHOSTTY_MOUSE_BUTTON_LEFT;
    held_reported = !shifted && mouse_reporting();
    if (held_reported) {
      ghostty_selection_gesture_reset(selection_gesture, terminal);
      (void)ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_SELECTION, NULL);
      frame_dirty = true;
      report_mouse(GHOSTTY_MOUSE_ACTION_PRESS, held_button, event->modifiers, column, row);
      return 0;
    }
    // Only the primary button selects.
    if (held_button != GHOSTTY_MOUSE_BUTTON_LEFT) {
      held_button = GHOSTTY_MOUSE_BUTTON_UNKNOWN;
      return 0;
    }
  } else if (event->action == DOLLY_POINTER_ACTION_RELEASE) {
    const GhosttyMouseButton released = held_button;
    const bool reported = held_reported;
    held_button = GHOSTTY_MOUSE_BUTTON_UNKNOWN;
    held_reported = false;
    if (reported) {
      report_mouse(GHOSTTY_MOUSE_ACTION_RELEASE, released, event->modifiers, column, row);
      return 0;
    }
  } else if (event->action != DOLLY_POINTER_ACTION_DRAG) {
    return -1;
  } else if (held_reported || held_button == GHOSTTY_MOUSE_BUTTON_UNKNOWN) {
    if (held_reported || (!shifted && mouse_reporting())) {
      report_mouse(GHOSTTY_MOUSE_ACTION_MOTION, held_button, event->modifiers, column, row);
    }
    return 0;
  }

  const GhosttyPoint point = {
      .tag = GHOSTTY_POINT_TAG_VIEWPORT,
      .value = {.coordinate = {.x = (uint16_t)column, .y = row}},
  };
  GhosttyGridRef ref = GHOSTTY_INIT_SIZED(GhosttyGridRef);
  if (ghostty_terminal_grid_ref(terminal, point, &ref) != GHOSTTY_SUCCESS) {
    return -1;
  }
  GhosttySurfacePosition position = {.x = x, .y = y};
  GhosttySelectionGestureEvent gesture_event = NULL;
  if (event->action == DOLLY_POINTER_ACTION_PRESS) {
    (void)ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_SELECTION, NULL);
    gesture_event = selection_press;
  } else if (event->action == DOLLY_POINTER_ACTION_DRAG) {
    gesture_event = selection_drag;
  } else {
    gesture_event = selection_release;
  }
  if (ghostty_selection_gesture_event_set(
          gesture_event, GHOSTTY_SELECTION_GESTURE_EVENT_OPT_REF, &ref) !=
      GHOSTTY_SUCCESS) return -1;
  if (event->action != DOLLY_POINTER_ACTION_RELEASE &&
      ghostty_selection_gesture_event_set(
          gesture_event, GHOSTTY_SELECTION_GESTURE_EVENT_OPT_POSITION,
          &position) != GHOSTTY_SUCCESS) return -1;

  bool rectangle = (event->modifiers & DOLLY_INPUT_MOD_ALT) != 0;
  GhosttySelectionGestureGeometry geometry = {
      .columns = cols,
      .cell_width = cell_width,
      .padding_left = padding_x,
      .screen_height = framebuffer_height,
  };
  if (event->action == DOLLY_POINTER_ACTION_DRAG &&
      (ghostty_selection_gesture_event_set(
           gesture_event, GHOSTTY_SELECTION_GESTURE_EVENT_OPT_RECTANGLE,
           &rectangle) != GHOSTTY_SUCCESS ||
       ghostty_selection_gesture_event_set(
           gesture_event, GHOSTTY_SELECTION_GESTURE_EVENT_OPT_GEOMETRY,
           &geometry) != GHOSTTY_SUCCESS)) return -1;

  GhosttySelection selection = GHOSTTY_INIT_SIZED(GhosttySelection);
  GhosttyResult result = ghostty_selection_gesture_event(
      selection_gesture, terminal, gesture_event,
      event->action == DOLLY_POINTER_ACTION_DRAG ? &selection : NULL);
  if (event->action == DOLLY_POINTER_ACTION_DRAG) {
    if (result != GHOSTTY_SUCCESS ||
        ghostty_terminal_set(terminal, GHOSTTY_TERMINAL_OPT_SELECTION,
                            &selection) != GHOSTTY_SUCCESS) return -1;
  } else if (result != GHOSTTY_NO_VALUE) {
    return -1;
  }
  frame_dirty = true;
  return 0;
}

// A wheel delta in thousandths of its unit becomes thousandths of a row:
// negative toward older output, positive toward the active screen. A program
// that asked for the mouse reads a wheel step for each row, at most a page,
// where the pointer is; otherwise the rows scroll the terminal's viewport.
static int handle_scroll(const dolly_input_event *event) {
  uint16_t page_rows = 1;
  (void)ghostty_terminal_get(terminal, GHOSTTY_TERMINAL_DATA_ROWS, &page_rows);
  int64_t wheel_milli = event->y;
  if (event->action == DOLLY_SCROLL_UNIT_PIXEL) wheel_milli /= cell_height;
  else if (event->action == DOLLY_SCROLL_UNIT_PAGE) wheel_milli *= page_rows;
  else if (event->action != DOLLY_SCROLL_UNIT_LINE) return -1;
  if (wheel_milli > 2000000000) wheel_milli = 2000000000;
  if (wheel_milli < -2000000000) wheel_milli = -2000000000;
  const int32_t delta_milli = (int32_t)wheel_milli;
  if ((delta_milli > 0 && scroll_remainder_milli > INT32_MAX - delta_milli) ||
      (delta_milli < 0 && scroll_remainder_milli < INT32_MIN - delta_milli)) {
    scroll_remainder_milli = 0;
    return -1;
  }
  scroll_remainder_milli += delta_milli;
  const intptr_t rows = scroll_remainder_milli / 1000;
  scroll_remainder_milli %= 1000;
  if (rows == 0) return 0;
  if (mouse_reporting()) {
    const uint32_t column = pointer_position.x > padding_x
        ? ((uint32_t)pointer_position.x - padding_x) / cell_width : 0;
    const uint32_t row = pointer_position.y > padding_y
        ? ((uint32_t)pointer_position.y - padding_y) / cell_height : 0;
    const intptr_t steps = rows < 0 ? -rows : rows;
    for (intptr_t step = 0; step < steps && step < page_rows; ++step) {
      report_mouse(GHOSTTY_MOUSE_ACTION_PRESS,
                   rows < 0 ? GHOSTTY_MOUSE_BUTTON_FOUR : GHOSTTY_MOUSE_BUTTON_FIVE,
                   event->modifiers, column, row);
    }
    return 0;
  }
  const GhosttyTerminalScrollViewport viewport = {
      .tag = GHOSTTY_SCROLL_VIEWPORT_DELTA,
      .value = {.delta = rows},
  };
  ghostty_terminal_scroll_viewport(terminal, viewport);
  frame_dirty = true;
  return 0;
}

static int decode_record(const dolly_input_event *event,
                         unsigned char *output,
                         size_t output_capacity,
                         size_t *output_length) {
  *output_length = 0;
  const size_t total = (size_t)event->key_length + event->code_length +
                       event->text_length;
  if (total > sizeof(event->data)) return -1;
  if (event->type == DOLLY_INPUT_EVENT_POINTER ||
      event->type == DOLLY_INPUT_EVENT_SCROLL) {
    // A terminal that a graphics program covers has no pointer of its own.
    if (suspended) return 0;
    return event->type == DOLLY_INPUT_EVENT_POINTER ? handle_pointer(event)
                                                    : handle_scroll(event);
  }
  if (event->type == DOLLY_INPUT_EVENT_TEXT) {
    if (event->text_length > output_capacity) return -1;
    memcpy(output, event->data, event->text_length);
    *output_length = event->text_length;
    return 0;
  }
  if (event->type != DOLLY_INPUT_EVENT_KEY) return 0;

  char key[DOLLY_INPUT_EVENT_DATA_SIZE + 1];
  char code[DOLLY_INPUT_EVENT_DATA_SIZE + 1];
  memcpy(key, event->data, event->key_length);
  key[event->key_length] = '\0';
  memcpy(code, event->data + event->key_length, event->code_length);
  code[event->code_length] = '\0';

  if (event->action != DOLLY_KEY_ACTION_RELEASE &&
      (event->modifiers & DOLLY_INPUT_MOD_CONTROL) != 0 &&
      (strcmp(code, "Equal") == 0 || strcmp(code, "NumpadAdd") == 0 ||
       strcmp(code, "Minus") == 0 || strcmp(code, "NumpadSubtract") == 0)) {
    const bool increase = strcmp(code, "Equal") == 0 ||
                          strcmp(code, "NumpadAdd") == 0;
    font_chosen = true;
    font_size_milli = clamp_u32(
        increase ? font_size_milli + 1000 : font_size_milli - 1000,
        MIN_FONT_MILLI, MAX_FONT_MILLI);
    if (set_layout(viewport_width_css, viewport_height_css,
                   device_scale_milli) == 0) render_frame();
    return 0;
  }

  ghostty_key_event_set_action(key_event, (GhosttyKeyAction)event->action);
  ghostty_key_event_set_key(key_event, map_key(code));
  const GhosttyMods mods = ghostty_mods(event->modifiers);
  ghostty_key_event_set_mods(key_event, mods);
  const bool printable = printable_key(key, event->key_length);
  // KeyboardEvent.key already contains the text produced by Shift (e.g. ':').
  ghostty_key_event_set_consumed_mods(key_event,
      printable ? mods & GHOSTTY_MODS_SHIFT : 0);
  ghostty_key_event_set_composing(
      key_event, (event->flags & DOLLY_INPUT_FLAG_COMPOSING) != 0);
  if (printable) {
    ghostty_key_event_set_utf8(key_event, key, event->key_length);
  } else {
    ghostty_key_event_set_utf8(key_event, NULL, 0);
  }
  ghostty_key_event_set_unshifted_codepoint(key_event,
                                            unshifted_codepoint(code));
  ghostty_key_encoder_setopt_from_terminal(key_encoder, terminal);
  size_t written = 0;
  GhosttyResult result = ghostty_key_encoder_encode(
      key_encoder, key_event, (char *)output, output_capacity, &written);
  if (result != GHOSTTY_SUCCESS) return -1;
  *output_length = written;
  return 0;
}

static const dolly_input_decoder decoder = {
    .record = decode_record,
    .paste = decode_paste,
};

static const dolly_display_driver_v5 driver = {
    .abi_version = DRIVER_ABI_VERSION,
    .struct_size = sizeof(dolly_display_driver_v5),
    .initialize = initialize,
    .write = write_terminal,
    .read = read_replies,
    .resize = resize,
    .present = present,
    .set_suspended = set_suspended,
};

__attribute__((export_name("dolly_display_driver_get_v5")))
const dolly_display_driver_v5 *dolly_display_driver_export(void) {
  return &driver;
}
