Skip to content
Myr

render.c

This file

Path

render.c

2,298 lines · 74.2 KiB · C

Last changed by

wayland: implement text-input-unstable-v3 for IME supportMark Stosbergbefore adoption43caf1d

History of this file

Take it

1#include "render.h"23#include <limits.h>4#include <pthread.h>5#include <semaphore.h>6#include <signal.h>7#include <stdio.h>8#include <stdlib.h>9#include <string.h>10#include <threads.h>11#include <uchar.h>12#include <sys/time.h>1314#include "column.h"15#include "macros.h"16#include "timing.h"1718#if HAS_INCLUDE(<pthread_np.h>)19#include <pthread_np.h>20#define pthread_setname_np(thread, name) (pthread_set_name_np(thread, name), 0)21#elif defined(__NetBSD__)22#define pthread_setname_np(thread, name) pthread_setname_np(thread, "%s", (void *)name)23#endif2425#if defined(FUZZEL_ENABLE_CAIRO)26#include <cairo.h>27#else28#define cairo_t void29#endif3031#include <fcft/fcft.h>3233#if defined(FUZZEL_ENABLE_SVG_NANOSVG)34 #include <nanosvg/nanosvgrast.h>35#endif3637#if defined(FUZZEL_ENABLE_SVG_RESVG)38 #include <resvg.h>39#endif4041#define LOG_MODULE "render"42#define LOG_ENABLE_DBG 043#include "log.h"44#include "char32.h"45#include "icon.h"46#include "srgb.h"47#include "stride.h"48#include "xmalloc.h"49#include "xsnprintf.h"5051#define min(x, y) ((x) < (y) ? (x) : (y))52#define max(x, y) ((x) > (y) ? (x) : (y))5354struct render;55struct thread_context {56    struct render *render;57    int my_id;58};5960struct render {61    const struct config *conf;62    struct fcft_font *font;63    struct fcft_font *font_bold;64    enum fcft_subpixel subpixel;6566    /* Cached fcft text runs */67    struct fcft_text_run *prompt_text_run;68    struct fcft_text_run *message_text_run;69    struct fcft_text_run *placeholder_text_run;7071    /* Cached selection corners */72    pixman_image_t *selection_corners;7374    float scale;75    float dpi;76    bool size_font_by_dpi;7778    bool gamma_correct;79    pixman_color_t pix_background_color;80    pixman_color_t pix_border_color;81    pixman_color_t pix_text_color;82    pixman_color_t pix_message_color;83    pixman_color_t pix_prompt_color;84    pixman_color_t pix_input_color;85    pixman_color_t pix_match_color;86    pixman_color_t pix_selection_color;87    pixman_color_t pix_selection_text_color;88    pixman_color_t pix_selection_match_color;89    pixman_color_t pix_counter_color;90    pixman_color_t pix_placeholder_color;9192    unsigned x_margin;93    unsigned y_margin;94    unsigned inner_pad;95    unsigned border_size;96    unsigned border_radius;97    unsigned selection_border_radius;98    unsigned row_height;99    unsigned icon_height;100    unsigned message_height;101102    unsigned input_glyph_offset; /* At which glyph to start rendering input */103104    /* Set during render_prompt; used by IME for cursor rectangle */105    struct {106        int x, y, w, h;  /* buffer pixel coordinates */107    } cursor_rect;108109    struct {110        uint16_t count;111        sem_t start;112        sem_t done;113        mtx_t lock;114        tll(int) queue;115        thrd_t *threads;116117        const struct matches *matches;118        struct buffer *buf;119        bool render_icons;120    } workers;121122    mtx_t *icon_lock;123};124125static pixman_color_t126rgba2pixman(bool gamma_correct, struct rgba rgba)127{128    pixman_color_t pix_color = {129        .alpha = rgba.a * 65535. + 0.5,130        .red = gamma_correct ? srgb_decode_8_to_16(rgba.r * 255 + 0.5) : rgba.r * 65535. + 0.5,131        .green = gamma_correct ? srgb_decode_8_to_16(rgba.g * 255 + 0.5) : rgba.g * 65535. + 0.5,132        .blue = gamma_correct ? srgb_decode_8_to_16(rgba.b * 255 + 0.5) : rgba.b * 65535. + 0.5,133    };134135    pix_color.red = (uint32_t)pix_color.red * pix_color.alpha / 0xffff;136    pix_color.green = (uint32_t)pix_color.green * pix_color.alpha / 0xffff;137    pix_color.blue = (uint32_t)pix_color.blue * pix_color.alpha / 0xffff;138139    return pix_color;140}141142static int143pt_or_px_as_pixels(const struct render *render, const struct pt_or_px *pt_or_px)144{145    double scale = !render->size_font_by_dpi ? render->scale : 1.;146    double dpi = render->size_font_by_dpi  ? render->dpi : 96.;147148    return pt_or_px->px == 0149        ? round(pt_or_px->pt * scale * dpi / 72.)150        : pt_or_px->px;151}152153static pixman_region32_t154rounded_rectangle_region(uint16_t x, uint16_t y, uint16_t width, uint16_t height, uint16_t radius)155{156157    int rect_count = ( radius + radius ) + 1;158    pixman_box32_t rects[rect_count];159160    for (int i = 0; i <= radius; i++) {161        uint16_t ydist = radius - i;162        uint16_t curve = sqrt(radius * radius - ydist * ydist);163164        rects[i] = (pixman_box32_t) {165            x + radius - curve,166            y + i,167            x + width - radius + curve,168            y + i + 1169        };170171        rects[radius + i] = (pixman_box32_t) {172            x + radius - curve,173            y + height - i,174            x + width - radius + curve,175            y + height - i + 1176        };177    }178179    rects[(radius * 2)] = (pixman_box32_t){180        x,181        y + radius,182        x + width,183        y + height + 1 - radius184    };185186    pixman_region32_t region;187    pixman_region32_init_rects(&region, rects, rect_count);188    return region;189}190191static inline void192fill_region32(pixman_op_t op, pixman_image_t* dest,193                       const pixman_color_t* color, pixman_region32_t* region)194{195    int rectc;196    pixman_box32_t *rects = pixman_region32_rectangles(region, &rectc);197    pixman_image_fill_boxes(op, dest, color, rectc, rects);198199}200201static inline void202fill_rounded_rectangle(pixman_op_t op, pixman_image_t* dest,203                       const pixman_color_t* color, int16_t x, int16_t y,204                       uint16_t width, uint16_t height, uint16_t radius)205{206    pixman_region32_t region = rounded_rectangle_region(x, y, width, height, radius);207    fill_region32(op, dest, color, &region);208    pixman_region32_fini(&region);209}210211static void212render_rounded_rectangle(pixman_image_t* dest, pixman_color_t* background,213                         pixman_color_t* border, unsigned int radius, unsigned bw,214                         int16_t x, int16_t y, uint16_t width, uint16_t height)215{216    if (radius == 0) {217        pixman_image_fill_rectangles(218            PIXMAN_OP_SRC, dest, background,219            1, &(pixman_rectangle16_t){220            x + bw, y + bw, width - 2 * bw, height - 2 * bw});221222        pixman_image_fill_rectangles(223            PIXMAN_OP_SRC, dest, border,224            4, (pixman_rectangle16_t[]){225                {x, y, width, bw},                              /* top */226                {x, y + bw, bw, height - 2 * bw},               /* left */227                {x + width - bw, y + bw, bw, height - 2 * bw},  /* right */228                {x, y + height - bw, width, bw}                 /* bottom */229            });230    } else {231        const int msaa_scale = 2;232        const double brd_sz_scaled = bw * msaa_scale;233        const double brd_rad_scaled = radius * msaa_scale;234        int w = width * msaa_scale;235        int h = height * msaa_scale;236        int bg_rad = brd_rad_scaled * (1.0 - (float)brd_sz_scaled / (float)brd_rad_scaled);237238        pixman_image_t *bg_img;239        if (msaa_scale != 1) {240            bg_img = pixman_image_create_bits(241                pixman_image_get_format(dest), w, h, NULL, w*4);242        } else {243            bg_img = dest;244        }245246        /* Border */247        fill_rounded_rectangle(248            PIXMAN_OP_SRC, bg_img, border, 0, 0, w, h, brd_rad_scaled);249250        /* Background */251        fill_rounded_rectangle(252            PIXMAN_OP_SRC, bg_img, background, brd_sz_scaled, brd_sz_scaled,253            w-(brd_sz_scaled*2),254            h-(brd_sz_scaled*2),255            bg_rad);256257        if (msaa_scale != 1) {258            pixman_f_transform_t ftrans;259            pixman_transform_t trans;260            pixman_f_transform_init_scale(&ftrans, msaa_scale, msaa_scale);261            pixman_transform_from_pixman_f_transform(&trans, &ftrans);262            pixman_image_set_transform(bg_img, &trans);263            pixman_image_set_filter(bg_img, PIXMAN_FILTER_BILINEAR, NULL, 0);264265            pixman_image_composite32(266                PIXMAN_OP_SRC, bg_img, NULL, dest, 0, 0, 0, 0, x, y,267                width, height);268            pixman_image_unref(bg_img);269        }270    }271}272273void274render_background(const struct render *render, struct buffer *buf)275{276    unsigned bw = render->border_size;277278    pixman_color_t bg = render->pix_background_color;279    pixman_color_t border_color = render->pix_border_color;280281    if (buf->age == 0) {282        /* Each sub-part of the window erases itself */283        return;284    }285286    /* Limit radius if the margins are very small, to prevent e.g. the287       selection "box" from overlapping the corners */288    const unsigned int radius =289        min(render->border_radius,290            max(render->x_margin,291                render->y_margin));292293    render_rounded_rectangle(buf->pix[0], &bg, &border_color, radius, bw,294                             0, 0, buf->width, buf->height);295}296297static void298render_glyph(pixman_image_t *pix, const struct fcft_glyph *glyph, int x, int y,299             const pixman_color_t *color)300{301    if (pixman_image_get_format(glyph->pix) == PIXMAN_a8r8g8b8) {302        /* Glyph surface is a pre-rendered image (typically a color emoji...) */303        pixman_image_composite32(304            PIXMAN_OP_OVER, glyph->pix, NULL, pix, 0, 0, 0, 0,305            x + glyph->x, y - glyph->y,306            glyph->width, glyph->height);307    } else {308        /* Glyph surface is an alpha mask */309        pixman_image_t *src = pixman_image_create_solid_fill(color);310        pixman_image_composite32(311            PIXMAN_OP_OVER, src, glyph->pix, pix, 0, 0, 0, 0,312            x + glyph->x, y - glyph->y,313            glyph->width, glyph->height);314        pixman_image_unref(src);315    }316}317318static int319render_baseline(const struct render *render)320{321    const struct fcft_font *font = render->font;322    const int line_height = render->row_height;323    const int font_height = font->ascent + font->descent;324325    /*326     * Center glyph on the line *if* using a custom line height,327     * otherwise the baseline is simply 'descent' pixels above the328     * bottom of the cell329     */330    const int glyph_top_y =331        render->conf->line_height.px >= 0 && line_height >= font_height332            ? round((line_height - font_height) / 2.)333            : 0;334335    return line_height - glyph_top_y - font->descent;336}337338static int339render_match_count(const struct render *render, struct buffer *buf,340                   const struct prompt *prompt, const struct matches *matches)341{342    struct fcft_font *font = render->font;343    assert(font != NULL);344345    const struct config *conf = render->conf;346347    const enum fcft_subpixel subpixel =348        conf->colors.background.a == 1. && conf->colors.selection.a == 1.349            ? render->subpixel350            : FCFT_SUBPIXEL_NONE;351352    size_t total_count = matches_get_application_visible_count(matches);353    size_t match_count = matches_get_total_count(matches);354    const char32_t *ptext = prompt_text(prompt);355356    char text[64];357    size_t count = (ptext[0] == U'\0') ? total_count : match_count;358    size_t chars = xsnprintf(text, sizeof(text), "%zu/%zu", count, total_count);359360    /* fcft wants UTF-32. Since we only use ASCII... */361    uint32_t wtext[64];362    for (size_t i = 0; i < chars; i++)363        wtext[i] = (uint32_t)(unsigned char)text[i];364365    int width = -1;366    int x = buf->width - render->border_size - render->x_margin;367    int y = render->border_size + render->y_margin +368            (render->row_height + font->height) / 2 - font->descent;369370    if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING) {371        struct fcft_text_run *run = fcft_rasterize_text_run_utf32(372            font, chars, wtext, subpixel);373374        if (run != NULL) {375            width = 0;376377            for (size_t i = 0; i < run->count; i++) {378                const struct fcft_glyph *glyph = run->glyphs[i];379                width += glyph->advance.x;380            }381382            x -= width;383            for (size_t i = 0; i < run->count; i++) {384                const struct fcft_glyph *glyph = run->glyphs[i];385                render_glyph(buf->pix[0], glyph, x, y, &render->pix_counter_color);386                x += glyph->advance.x;387            }388389            fcft_text_run_destroy(run);390            return width;391        }392    }393394    const struct fcft_glyph **glyphs = xmalloc(chars * sizeof(glyphs[0]));395    long *x_kern = xmalloc(chars * sizeof(x_kern[0]));396    char32_t prev = 0;397398    width = 0;399    for (size_t i = 0; i < (size_t)chars; i++) {400        x_kern[i] = 0;401402        const struct fcft_glyph *glyph =403            fcft_rasterize_char_utf32(font, wtext[i], subpixel);404        glyphs[i] = glyph;405406        if (glyph == NULL)407            continue;408409        if (i > 0) {410            if (fcft_kerning(font, prev, wtext[i], &x_kern[i], NULL))411                width += x_kern[i];412        }413        width += glyph->advance.x;414        prev = wtext[i];415    }416417    x -= width;418419    for (size_t i = 0; i < (size_t)chars; i++) {420        const struct fcft_glyph *glyph = glyphs[i];421        if (glyph == NULL)422            continue;423424        x += x_kern[i];425        render_glyph(buf->pix[0], glyph, x, y, &render->pix_counter_color);426        x += glyph->advance.x;427        prev = wtext[i];428    }429430    free(x_kern);431    free(glyphs);432    return width;433}434435static void436render_cursor(const struct render *render, int x, int baseline, pixman_image_t *pix)437{438    struct fcft_font *font = render->font;439440    if (true) {441        /* Bar cursor */442        const int height = min(font->ascent + font->descent, render->row_height);443444        pixman_image_fill_rectangles(445            PIXMAN_OP_SRC, pix, &render->pix_input_color,446            1, &(pixman_rectangle16_t){447                x,448                baseline + render->font->descent - height,449                font->underline.thickness,450                height});451    } else {452        /* TODO: future: underline cursor */453        pixman_image_fill_rectangles(454            PIXMAN_OP_SRC, pix, &render->pix_input_color,455            1, &(pixman_rectangle16_t){456                x, baseline - font->underline.position,457                font->max_advance.x,458                font->underline.thickness});459    }460}461462static void463adjust_input_glyph_offset(struct render *render, const struct prompt *prompt,464                          size_t count,465                          const struct fcft_glyph *glyphs[static count],466                          long kerning[static count],467                          int start_x, int max_x)468{469    struct fcft_font *font = render->font;470    const size_t cursor_location = prompt_cursor(prompt);471472    if (cursor_location == 0)473        render->input_glyph_offset = 0;474475    /* Clamp to input string's length */476    render->input_glyph_offset = min(render->input_glyph_offset, count - 1);477478    /* If cursor position is before the current offset, adjust the479       offset backward */480    for (size_t i = 0; i < render->input_glyph_offset; i++) {481        if (cursor_location == i + 1) {482            render->input_glyph_offset = i + 1;483            break;484        }485    }486487    /* If cursor position is after the current visible portion, adjust the offset forward */488    int pos = start_x;489490    for (size_t i = render->input_glyph_offset; i < count; i++) {491492        const struct fcft_glyph *glyph = glyphs[i];493        if (glyph == NULL)494            continue;495496        const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);497498        /* Cursor is after this glyph? */499        if (cursor_location == i + 1) {500            /* If current glyph doesn't fit, adjust offset so that it does */501            if (pos + kerning[i] + pixels_needed > max_x) {502                int needed = (pos + kerning[i] + pixels_needed) - max_x;503504                /* Font may be variable width, meaning we may have to scroll multiple characters */505                while (needed > 0 && render->input_glyph_offset + 1 < count) {506                    long scrolled_kerning;507                    fcft_kerning(508                        font,509                        glyphs[render->input_glyph_offset]->cp,510                        glyphs[render->input_glyph_offset + 1]->cp,511                        &scrolled_kerning, NULL);512513                    const int gained =514                        scrolled_kerning +515                        glyphs[render->input_glyph_offset]->advance.x;516517                    needed -= gained;518                    pos -= gained;519                    render->input_glyph_offset++;520                }521            }522        }523524        pos += kerning[i] + glyph->advance.x;525    }526527    /* Pull in glyphs from the left, if there's space left */528    while (render->input_glyph_offset > 0 && max_x > pos) {529        int total_width = start_x;530531        for (size_t i = render->input_glyph_offset; i < count; i++) {532            const struct fcft_glyph *g = glyphs[i];533            if (g == NULL)534                continue;535536            const int w = max(g->width, g->advance.x);537538            if (total_width + kerning[i] + w > max_x) {539                break;540            }541542            total_width += kerning[i] + (i + 1 == count ? w : g->advance.x);543        }544545        const struct fcft_glyph *glyph = glyphs[render->input_glyph_offset - 1];546        const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);547548        assert(render->input_glyph_offset > 0);549        assert(render->input_glyph_offset < count);550551        const long kern = kerning[render->input_glyph_offset];552        const int available = max_x - total_width;553        if (kern + pixels_needed > available)554            break;555556        render->input_glyph_offset--;557        pos += kern + glyph->advance.x;558    }559}560561static void562current_line_boundaries(char32_t* remaining_message, const struct config *conf,563                        char32_t** current_line_end, char32_t** next_line_start)564{565    char32_t* next_linebreak = c32chr(remaining_message, U'\n');566    // Unless word wrapping, the current line boundaries are the whole line567    // If the line is shorter than the configured width, we can also immediately return568    if (conf->message_mode != MESSAGE_MODE_WRAP569        || (next_linebreak != NULL && next_linebreak - remaining_message <= conf->chars)570        || (next_linebreak == NULL && c32len(remaining_message) <= conf->chars)571    ) {572        if (next_linebreak) {573            *current_line_end = next_linebreak-1;574            // Do not skip leading spaces after a linebreak,575            // as intentional spaces likely exist for formatting purposes.576            *next_line_start = next_linebreak+1;577        } else {578            *current_line_end = remaining_message + c32len(remaining_message) - 1;579            *next_line_start = NULL;580        }581        goto strip_trailing_spaces;582    }583584    // Wrapping logic585    char32_t* last_space = NULL;586    *current_line_end = remaining_message;587    while (*current_line_end - remaining_message < conf->chars) {588        if (**current_line_end == U' ') {589            last_space = *current_line_end;590        }591        (*current_line_end)++;592    }593594    // If there is no space in the line, all we can really do (without595    // changing the string) is stop at the end character and move to596    // the next line.597    // Might be nice to have a configurable "wrapping character" option598    // later.599    // current_line_end is already conf->chars characters after remaining_message600    // here due to the space-searching loop601    if (last_space == NULL) {602        // Bumped one beyond conf->chars before the loop ends603        (*current_line_end)--;604        *next_line_start = *current_line_end + 1;605        // Consistency. Should never happen here, but good to check.606        goto strip_leading_spaces;607    }608609610    // If there is a space in the line, break on it.611    *current_line_end = last_space-1;612    *next_line_start = last_space+1;613614strip_leading_spaces:615    while (*next_line_start != NULL && c32len(*next_line_start) > 0 && **next_line_start == U' ')616        (*next_line_start)++;617    if (c32len(*next_line_start) == 0)618        *next_line_start = NULL;619620strip_trailing_spaces:621    while (622        *current_line_end != NULL623        && *current_line_end > remaining_message624        && **current_line_end == U' ')625    {626        (*current_line_end)--;627    }628629}630631/*632 * Returns the x-coordinate of the left edge of the row background area.633 * The background extends slightly past the text content edge (border + x_margin)634 * by sel_margin (= x_margin / 3) on each side, so the selection highlight635 * has a small gap from the window border while bleeding into the margin.636 */637static int638row_bg_x(const struct render *render)639{640    const int sel_margin = render->x_margin / 3;641    return render->border_size + render->x_margin - sel_margin;642}643644void645render_message(struct render *render, struct buffer *buf)646{647    if (!render->conf->message) return;648649    struct fcft_font *font = render->font;650    assert(font != NULL);651652    const char32_t *message = render->conf->message;653    size_t message_len = c32len(message);654655    const enum fcft_subpixel subpixel =656        (render->conf->colors.background.a == 1. &&657         render->conf->colors.message.a == 1.)658        ? render->subpixel : FCFT_SUBPIXEL_NONE;659660661    int x = render->border_size + render->x_margin;662    int y = render->border_size + render->y_margin + render_baseline(render);663664    /* Erase background */665    pixman_color_t bg = render->pix_background_color;666    //pixman_color_t bg = (pixman_color_t){0xffff, 0, 0, 0xffff};667    pixman_image_fill_rectangles(668        PIXMAN_OP_SRC, buf->pix[0], &bg, 1,669        &(pixman_rectangle16_t){670            row_bg_x(render),671            render->border_size + render->y_margin,672            buf->width - 2 * row_bg_x(render),673            render->message_height});674675    struct fcft_text_run *message_run = render->message_text_run;676677    if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING && message_run == NULL) {678        message_run = fcft_rasterize_text_run_utf32(679            font, message_len, message, subpixel);680    }681682    char32_t* current_pos = render->conf->message;683    char32_t* current_line_end = NULL;684    char32_t* next_line_start = NULL;685    while (current_pos != NULL) {686        current_line_boundaries(current_pos, render->conf,687                                &current_line_end, &next_line_start);688689        if (message_run != NULL) {690            for (; current_pos <= current_line_end; current_pos++) {691                int i = current_pos - render->conf->message;692                const struct fcft_glyph *glyph = NULL;693694                for (size_t j = 0; j < message_run->count; j++) {695                    if (message_run->cluster[j] == i) {696                        glyph = message_run->glyphs[j];697                        break;698                    }699                }700701                if (glyph == NULL)702                    continue;703704                render_glyph(buf->pix[0], glyph, x, y, &render->pix_message_color);705                x += glyph->advance.x;706            }707        } else {708            char32_t prev = 0;709            for (; current_pos <= current_line_end; current_pos++) {710                int i = current_pos - render->conf->message;711                const char32_t wc = message[i];712                if (wc == U'\n') {713                    x = render->border_size + render->x_margin;714                    y += render->row_height;715                    continue;716                }717718                const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(font, wc, subpixel);719720                if (glyph == NULL) {721                    prev = wc;722                    continue;723                }724725                long x_kern;726                fcft_kerning(font, prev, wc, &x_kern, NULL);727728                x += x_kern;729730                render_glyph(731                    buf->pix[0], glyph, x, y, &render->pix_message_color);732                x += glyph->advance.x;733                x += pt_or_px_as_pixels(render, &render->conf->letter_spacing);734735                prev = wc;736            }737        }738739        current_pos = next_line_start;740        x = render->border_size + render->x_margin;741        y += render->row_height;742    }743744745    if (render->message_text_run == NULL)746        render->message_text_run = message_run;747    else if (message_run != render->message_text_run)748        fcft_text_run_destroy(message_run);749}750751static void752update_cursor_rect(struct render *render, int x, int y)753{754    struct fcft_font *font = render->font;755    const int height = min(font->ascent + font->descent, render->row_height);756    render->cursor_rect.x = x;757    render->cursor_rect.y = y + font->descent - height;758    render->cursor_rect.w = font->underline.thickness;759    render->cursor_rect.h = height;760}761762/*763 * Render preedit text at the cursor position, following foot's approach:764 * - All preedit glyphs are rendered with an underline.765 * - A bar cursor is placed at the glyph index given by preedit_cursor766 *   (-1 means the cursor is hidden).767 * Returns the new x position after all preedit glyphs.768 */769static int770render_preedit_at_cursor(const struct render *render, struct buffer *buf,771                         int x, int y, int max_x,772                         const char32_t *preedit, size_t preedit_len,773                         int32_t preedit_cursor,774                         enum fcft_subpixel subpixel)775{776    struct fcft_font *font = render->font;777    const int ul_y = y - font->underline.position;778    const int ul_h = font->underline.thickness;779780    char32_t prev = 0;781782    for (size_t i = 0; i < preedit_len; i++) {783        /* Cursor bar before this glyph */784        if (preedit_cursor >= 0 && (int32_t)i == preedit_cursor)785            render_cursor(render, x, y, buf->pix[0]);786787        const struct fcft_glyph *glyph =788            fcft_rasterize_char_utf32(font, preedit[i], subpixel);789790        if (glyph == NULL) {791            prev = 0;792            continue;793        }794795        long x_kern = 0;796        if (prev != 0)797            fcft_kerning(font, prev, preedit[i], &x_kern, NULL);798        x += x_kern;799800        const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);801        if (x + pixels_needed > max_x)802            break;803804        const int glyph_start_x = x;805806        render_glyph(buf->pix[0], glyph, x, y, &render->pix_input_color);807        x += glyph->advance.x;808        x += pt_or_px_as_pixels(render, &render->conf->letter_spacing);809810        /* Underline below the preedit glyph */811        pixman_image_fill_rectangles(812            PIXMAN_OP_SRC, buf->pix[0], &render->pix_input_color,813            1, &(pixman_rectangle16_t){814                glyph_start_x,815                ul_y,816                x - glyph_start_x,817                ul_h});818819        prev = preedit[i];820    }821822    /* Cursor bar after all preedit glyphs */823    if (preedit_cursor < 0 || preedit_cursor >= (int32_t)preedit_len)824        render_cursor(render, x, y, buf->pix[0]);825826    return x;827}828829void830render_prompt(struct render *render, struct buffer *buf,831              const struct prompt *prompt, const struct matches *matches,832              const char32_t *preedit, int32_t preedit_cursor)833{834    struct fcft_font *font = render->font;835    assert(font != NULL);836837    const struct config *conf = render->conf;838839    const char32_t *pprompt = prompt_prompt(prompt);840    size_t prompt_len = c32len(pprompt);841    const size_t cursor_location = prompt_cursor(prompt);842843    const char32_t *ptext = prompt_text(prompt);844    size_t text_len = c32len(ptext);845    /* Suppress placeholder while IME preedit is active */846    const bool have_preedit = preedit != NULL && preedit[0] != U'\0';847    bool use_placeholder = text_len == 0 && !have_preedit;848849    const enum fcft_subpixel subpixel =850        (render->conf->colors.background.a == 1. &&851         render->conf->colors.selection.a == 1.)852        ? render->subpixel : FCFT_SUBPIXEL_NONE;853854    const struct fcft_glyph *input_glyphs[text_len];855    long input_kerning[text_len];856857    {858        const bool use_password = conf->password_mode.enabled && !use_placeholder;859860        for (size_t i = 0; i < text_len; i++) {861            char32_t wc = use_password ? conf->password_mode.character : ptext[i];862            input_glyphs[i] = fcft_rasterize_char_utf32(font, wc, subpixel);863            if (i == 0 || use_password)864                input_kerning[i] = 0;865            else866                fcft_kerning(font, ptext[i - 1], ptext[i], &input_kerning[i], NULL);867        }868    }869870    if (use_placeholder) {871        ptext = prompt_placeholder(prompt);872        text_len = c32len(ptext);873    }874875    int x = render->border_size + render->x_margin;876    int y = render->border_size + render->y_margin + render_baseline(render) + render->message_height;877878    /* Erase background */879    pixman_color_t bg = render->pix_background_color;880    //pixman_color_t bg = (pixman_color_t){0xffff, 0, 0, 0xffff};881    pixman_image_fill_rectangles(882        PIXMAN_OP_SRC, buf->pix[0], &bg, 1,883        &(pixman_rectangle16_t){884            row_bg_x(render),885            render->border_size + render->y_margin + render->message_height,886            buf->width - 2 * row_bg_x(render),887            render->row_height});888889#if 0890    bg = (pixman_color_t){0, 0xffff, 0, 0xffff};891    pixman_image_fill_rectangles(892        PIXMAN_OP_SRC, buf->pix[0], &bg, 1,893        &(pixman_rectangle16_t){894            render->border_size + render->x_margin,895            render->border_size + render->y_margin,896            buf->width - 2 * (render->border_size + render->x_margin),897            render->row_height});898#endif899900    int stats_width = conf->match_counter901        ? render_match_count(render, buf, prompt, matches)902        : 0;903904    const int max_x =905        buf->width - render->border_size - render->x_margin - stats_width;906907    struct fcft_text_run *prompt_run = render->prompt_text_run;908    struct fcft_text_run *input_run =909        use_placeholder ? render->placeholder_text_run : NULL;910911    if (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING) {912        if (prompt_run == NULL) {913            prompt_run = fcft_rasterize_text_run_utf32(914                font, prompt_len, pprompt, subpixel);915        }916        if (input_run == NULL && use_placeholder) {917            input_run = fcft_rasterize_text_run_utf32(918                font, text_len, ptext, subpixel);919        }920    }921922    if (prompt_run != NULL) {923        for (size_t i = 0; i < prompt_run->count; i++) {924            const struct fcft_glyph *glyph = prompt_run->glyphs[i];925            const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);926927            if (x + pixels_needed > max_x)928                goto out;929930            render_glyph(buf->pix[0], glyph, x, y, &render->pix_prompt_color);931            x += glyph->advance.x;932        }933    } else {934        char32_t prev = 0;935        for (size_t i = 0; i < prompt_len; i++) {936            const char32_t wc = pprompt[i];937            const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(font, wc, subpixel);938939            if (glyph == NULL) {940                prev = wc;941                continue;942            }943944            long x_kern;945            fcft_kerning(font, prev, wc, &x_kern, NULL);946947            x += x_kern;948949            const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);950            if (x + pixels_needed > max_x)951                goto out;952953            render_glyph(954                buf->pix[0], glyph, x, y, &render->pix_prompt_color);955            x += glyph->advance.x;956            x += pt_or_px_as_pixels(render, &render->conf->letter_spacing);957958            prev = wc;959        }960    }961962    /*963     * Adjust glyph offset (i.e. where in the input string we start964     * rendering), to ensure the portion containing the cursor is965     * always visible.966     */967    adjust_input_glyph_offset(968        render, prompt, !use_placeholder ? text_len : 0,969        input_glyphs, input_kerning, x, max_x);970971    /* Cursor, if right after the prompt. In all other cases, the972     * cursor will be rendered by the loop below */973    const bool is_hidden_pwd =974        conf->password_mode.enabled && conf->password_mode.character == U'\0';975    if (cursor_location == render->input_glyph_offset || is_hidden_pwd) {976        update_cursor_rect(render, x, y);977        if (have_preedit && !is_hidden_pwd) {978            x = render_preedit_at_cursor(979                render, buf, x, y, max_x,980                preedit, c32len(preedit), preedit_cursor, subpixel);981        } else {982            render_cursor(render, x, y, buf->pix[0]);983        }984    }985986    if (input_run != NULL && !(conf->password_mode.enabled && !use_placeholder)) {987        /* We only shape the placeholder string */988        assert(use_placeholder);989990        for (size_t i = render->input_glyph_offset; i < input_run->count; i++) {991            const struct fcft_glyph *glyph = input_run->glyphs[i];992            const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);993994            if (x + pixels_needed > max_x) {995                goto out;996            }997998            render_glyph(buf->pix[0], glyph, x, y,999                         use_placeholder1000                             ? &render->pix_placeholder_color1001                             : &render->pix_input_color);1002            x += glyph->advance.x;10031004            /* Cursor */1005            const int cur_cluster = input_run->cluster[i];1006            const int next_cluster = i + 1 < input_run->count1007                ? input_run->cluster[i + 1] : INT_MAX;10081009            if (cursor_location > cur_cluster &&1010                cursor_location <= next_cluster)1011            {1012                render_cursor(render, x, y, buf->pix[0]);1013            }1014        }1015    } else {1016        char32_t prev = 0;10171018        for (size_t i = render->input_glyph_offset; i < text_len; i++) {1019            if (conf->password_mode.enabled &&1020                conf->password_mode.character == U'\0' &&1021                !use_placeholder)1022            {1023                continue;1024            }10251026            const struct fcft_glyph *glyph = input_glyphs[i];10271028            if (glyph == NULL) {1029                prev = 0;1030                continue;1031            }10321033            long x_kern;1034            fcft_kerning(font, prev, glyph->cp, &x_kern, NULL);10351036            x += x_kern;10371038            const int pixels_needed = max(glyph->x + glyph->width, glyph->advance.x);10391040            if (x + pixels_needed > max_x)1041                goto out;10421043            render_glyph(1044                buf->pix[0], glyph, x, y,1045                use_placeholder1046                    ? &render->pix_placeholder_color1047                    : &render->pix_input_color);1048            x += glyph->advance.x;1049            x += pt_or_px_as_pixels(render, &render->conf->letter_spacing);10501051            /* Cursor */1052            if (cursor_location > 0 && cursor_location - 1 == i) {1053                update_cursor_rect(render, x, y);1054                if (have_preedit) {1055                    x = render_preedit_at_cursor(1056                        render, buf, x, y, max_x,1057                        preedit, c32len(preedit), preedit_cursor, subpixel);1058                } else {1059                    render_cursor(render, x, y, buf->pix[0]);1060                }1061            }10621063            prev = glyph->cp;1064        }1065    }10661067out:1068    if (render->prompt_text_run == NULL)1069        render->prompt_text_run = prompt_run;1070    else if (prompt_run != render->prompt_text_run)1071        fcft_text_run_destroy(prompt_run);1072    if (use_placeholder && render->placeholder_text_run == NULL)1073        render->placeholder_text_run = input_run;1074    else if (!use_placeholder || input_run != render->placeholder_text_run)1075        fcft_text_run_destroy(input_run);1076}10771078static void1079render_match_text(pixman_image_t *pix, double *_x, double _y, double max_x,1080                  const char32_t *text, size_t match_count,1081                  const struct match_substring matches[static match_count],1082                  struct fcft_font *font, enum fcft_subpixel subpixel,1083                  int letter_spacing, int tabs,1084                  pixman_color_t regular_color, pixman_color_t match_color,1085                  struct fcft_text_run **run)1086{1087    int x = *_x;1088    int y = _y;10891090    const struct fcft_glyph **glyphs = NULL;1091    int *clusters = NULL;1092    long *kern = NULL;1093    size_t count = 0;10941095    if (*run == NULL &&1096        (fcft_capabilities() & FCFT_CAPABILITY_TEXT_RUN_SHAPING))1097    {1098        *run = fcft_rasterize_text_run_utf32(1099            font, c32len(text), text, subpixel);1100    }11011102    if (*run != NULL) {1103        glyphs = (*run)->glyphs;1104        clusters = (*run)->cluster;1105        count = (*run)->count;1106    } else {1107        count = c32len(text);1108        glyphs = xmalloc(count * sizeof(glyphs[0]));1109        clusters = xmalloc(count * sizeof(clusters[0]));1110        kern = xmalloc(count * sizeof(kern[0]));11111112        for (size_t i = 0; i < count; i++) {1113            const struct fcft_glyph *glyph = fcft_rasterize_char_utf32(1114                font, text[i], subpixel);1115            if (glyph == NULL) {1116                glyphs[i] = NULL;1117                continue;1118            }11191120            if (i > 0)1121                fcft_kerning(font, text[i - 1], text[i], &kern[i], NULL);1122            else1123                kern[i] = 0;11241125            glyphs[i] = glyph;1126            clusters[i] = i;1127        }1128    }11291130    for (size_t i = 0; i < count; i++) {1131        if (text[clusters[i]] == U'\t') {1132            const struct fcft_glyph *space =1133                fcft_rasterize_char_utf32(font, U' ', subpixel);11341135            if (space != NULL) {1136                const size_t chars_to_next_tab_stop = tabs == 01137                    ? 01138                    : tabs - (clusters[i] % tabs);1139                x += chars_to_next_tab_stop * space->advance.x;1140            }11411142            continue;1143        }11441145        bool is_match = false;1146        for (size_t j = 0; j < match_count; j++) {1147            const struct match_substring *match = &matches[j];1148            assert(match->start >= 0);11491150            if (clusters[i] >= match->start &&1151                clusters[i] < match->start + match->len)1152            {1153                is_match = true;1154                break;1155            }1156        }11571158        if (x + (kern != NULL ? kern[i] : 0) + glyphs[i]->advance.x > max_x) {1159            const struct fcft_glyph *ellipses =1160                fcft_rasterize_char_utf32(font, U'…', subpixel);11611162            if (ellipses != NULL)1163                render_glyph(pix, ellipses, x, y, &regular_color);11641165            break;1166        }11671168        x += kern != NULL ? kern[i] : 0;1169        render_glyph(pix, glyphs[i], x, y, is_match ? &match_color : &regular_color);1170        x += glyphs[i]->advance.x + letter_spacing;1171        y += glyphs[i]->advance.y;1172    }11731174    if (*run == NULL) {1175        free(kern);1176        free(clusters);1177        free(glyphs);1178    }11791180    *_x = x;1181}11821183#if defined(FUZZEL_ENABLE_SVG_LIBRSVG)1184static void1185render_svg_librsvg(const struct icon *icon, int x, int y, int size,1186                   cairo_t *cairo)1187{1188    RsvgHandle *svg = icon->svg;11891190    cairo_save(cairo);1191    cairo_set_operator(cairo, CAIRO_OPERATOR_ATOP);11921193 #if LIBRSVG_CHECK_VERSION(2, 46, 0)1194    if (cairo_status(cairo) == CAIRO_STATUS_SUCCESS) {1195        const RsvgRectangle viewport = {1196            .x = x,1197            .y = y,1198            .width = size,1199            .height = size,1200        };12011202        cairo_rectangle(cairo, x, y, size, size);1203        cairo_clip(cairo);12041205        rsvg_handle_render_document(svg, cairo, &viewport, NULL);1206    }1207 #else1208    RsvgDimensionData dim;1209    rsvg_handle_get_dimensions(svg, &dim);12101211    const double scale_x = size / dim.width;1212    const double scale_y = size / dim.height;1213    const double scale = scale_x < scale_y ? scale_x : scale_y;12141215    const double height = dim.height * scale;1216    const double width = dim.width * scale;12171218    cairo_rectangle(cairo, x, y, height, width);1219    cairo_clip(cairo);12201221    /* Translate + scale. Note: order matters! */1222    cairo_translate(cairo, x, y);1223    cairo_scale(cairo, scale, scale);12241225    if (cairo_status(cairo) == CAIRO_STATUS_SUCCESS)1226        rsvg_handle_render_cairo(svg, cairo);1227 #endif1228    cairo_restore(cairo);1229}1230#endif /* FUZZEL_ENABLE_SVG_LIBRSVG */12311232#if defined(FUZZEL_ENABLE_SVG_NANOSVG)1233static void1234render_svg_nanosvg(struct icon *icon, int x, int y, int size,1235                   pixman_image_t *pix, cairo_t *cairo, bool gamma_correct)1236{1237#if defined(FUZZEL_ENABLE_CAIRO)1238    cairo_surface_flush(cairo_get_target(cairo));1239#endif12401241    pixman_image_t *img = NULL;12421243    /* Look for a cached image, at the correct size */1244    tll_foreach(icon->rasterized, it) {1245        if (it->item.size == size) {1246            img = it->item.pix;1247            break;1248        }1249    }12501251    if (img == NULL) {1252        NSVGimage *svg = icon->svg;1253        struct NSVGrasterizer *rast = nsvgCreateRasterizer();12541255        if (rast == NULL)1256            return;12571258        float scale = svg->width > svg->height ? size / svg->width : size / svg->height;12591260        const int width = roundf(svg->width * scale);1261        const int height = roundf(svg->height * scale);12621263        uint8_t *data_8bit = xmalloc(width * height * 4);1264        uint8_t *data_16bit = NULL;1265        uint64_t *abgr16 = NULL;12661267        nsvgRasterize(rast, svg, 0, 0, scale, data_8bit, width, height, width * 4);12681269        if (gamma_correct) {1270            /* For gamma-correct blending, create 16-bit buffer and image */1271            data_16bit = xmalloc(width * height * 8);1272            abgr16 = (uint64_t *)data_16bit;12731274            img = pixman_image_create_bits_no_clear(1275                PIXMAN_a16b16g16r16, width, height, (uint32_t *)data_16bit,1276                width * 8);1277        } else {1278            img = pixman_image_create_bits_no_clear(1279                PIXMAN_a8b8g8r8, width, height, (uint32_t *)data_8bit, width * 4);1280        }12811282        /* Nanosvg produces non-premultiplied ABGR, while pixman expects1283         * premultiplied */12841285        for (uint32_t *abgr = (uint32_t *)data_8bit;1286             abgr < (uint32_t *)(data_8bit + width * height * 4);1287             abgr++)1288        {1289            uint16_t alpha = (*abgr >> 24) & 0xff;1290            uint16_t blue = (*abgr >> 16) & 0xff;1291            uint16_t green = (*abgr >> 8) & 0xff;1292            uint16_t red = (*abgr >> 0) & 0xff;12931294            /*1295             * TODO: decode sRGB -> linear here1296             *1297             * We should decode to 16-bit, meaning we have to prepare1298             * a 16-bit buffer before looping the pixels.1299             */13001301            if (gamma_correct) {1302                if (alpha == 0x00)1303                    blue = green = red = 0x00;1304                else {1305                    alpha |= alpha << 8;  /* Alpha already linear, expand to 16-bit */1306                    blue = srgb_decode_8_to_16(blue);1307                    green = srgb_decode_8_to_16(green);1308                    red = srgb_decode_8_to_16(red);13091310                    blue = blue * alpha / 0xffff;1311                    green = green * alpha / 0xffff;1312                    red = red * alpha / 0xffff;1313                }13141315                *abgr16 = (uint64_t)alpha << 48 | (uint64_t)blue << 32 | (uint64_t)green << 16 | (uint64_t)red;1316                abgr16++;1317            } else {1318                if (alpha == 0x00)1319                    blue = green = red = 0x00;1320                else {1321                    blue = (uint8_t)(blue * alpha / 0xff);1322                    green = (uint8_t)(green * alpha / 0xff);1323                    red = (uint8_t)(red * alpha / 0xff);1324                }13251326                *abgr = (uint32_t)alpha << 24 | blue << 16 | green << 8 | red;1327            }1328        }13291330        if (gamma_correct) {1331            /* Free the 8-bit buffer as we've converted everything to 16-bit */1332            free(data_8bit);1333        }13341335        nsvgDeleteRasterizer(rast);13361337        tll_push_back(icon->rasterized, ((struct rasterized){img, size}));1338    }13391340    const int w = pixman_image_get_width(img);1341    const int h = pixman_image_get_height(img);13421343    pixman_image_composite32(1344        PIXMAN_OP_OVER, img, NULL, pix, 0, 0, 0, 0,1345        x + (size - w) / 2,1346        y + (size - h) / 2,1347        w, h);13481349#if defined(FUZZEL_ENABLE_CAIRO)1350    cairo_surface_mark_dirty(cairo_get_target(cairo));1351#endif1352}1353#endif /* FUZZEL_ENABLE_SVG_NANOSVG */13541355#if defined(FUZZEL_ENABLE_SVG_RESVG)1356static void1357render_svg_resvg(struct icon *icon, int x, int y, int size,1358                 pixman_image_t *pix, cairo_t *cairo, bool gamma_correct)1359{1360#if defined(FUZZEL_ENABLE_CAIRO)1361    cairo_surface_flush(cairo_get_target(cairo));1362#endif13631364    pixman_image_t *img = NULL;13651366    /* Look for a cached image, at the correct size */1367    tll_foreach(icon->rasterized, it) {1368        if (it->item.size == size) {1369            img = it->item.pix;1370            break;1371        }1372    }13731374    if (img == NULL) {1375        resvg_render_tree *tree = icon->svg;1376        resvg_size svg_size = resvg_get_image_size(tree);13771378        if (svg_size.width == 0 || svg_size.height == 0)1379            return;13801381        float scale = svg_size.width > svg_size.height ? size / svg_size.width : size / svg_size.height;13821383        const int width = roundf(svg_size.width * scale);1384        const int height = roundf(svg_size.height * scale);13851386        uint8_t *data_8bit = xmalloc(width * height * 4);1387        memset(data_8bit, 0, width * height * 4);13881389        /* resvg renders to RGBA8888 premultiplied */1390        resvg_transform transform = resvg_transform_identity();1391        transform.a = scale;1392        transform.d = scale;1393        resvg_render(tree, transform, width, height, (char *)data_8bit);13941395        if (gamma_correct) {1396            /* For gamma-correct blending, create 16-bit buffer and image */1397            uint8_t *data_16bit = xmalloc(width * height * 8);1398            uint64_t *abgr16 = (uint64_t *)data_16bit;13991400            /* resvg produces premultiplied RGBA, need to convert to ABGR16 for pixman */1401            for (uint32_t *rgba = (uint32_t *)data_8bit;1402                 rgba < (uint32_t *)(data_8bit + width * height * 4);1403                 rgba++)1404            {1405                uint16_t red = (*rgba >> 0) & 0xff;1406                uint16_t green = (*rgba >> 8) & 0xff;1407                uint16_t blue = (*rgba >> 16) & 0xff;1408                uint16_t alpha = (*rgba >> 24) & 0xff;14091410                /* Decode sRGB to linear for gamma-correct blending */1411                if (alpha == 0x00) {1412                    blue = green = red = 0x00;1413                } else {1414                    /* First, un-premultiply */1415                    blue = (uint16_t)(blue * 0xff / alpha);1416                    green = (uint16_t)(green * 0xff / alpha);1417                    red = (uint16_t)(red * 0xff / alpha);14181419                    /* Convert to linear 16-bit */1420                    alpha |= alpha << 8;  /* Alpha already linear, expand to 16-bit */1421                    blue = srgb_decode_8_to_16(blue);1422                    green = srgb_decode_8_to_16(green);1423                    red = srgb_decode_8_to_16(red);14241425                    /* Re-premultiply in 16-bit linear space */1426                    blue = blue * alpha / 0xffff;1427                    green = green * alpha / 0xffff;1428                    red = red * alpha / 0xffff;1429                }14301431                *abgr16 = (uint64_t)alpha << 48 | (uint64_t)blue << 32 | (uint64_t)green << 16 | (uint64_t)red;1432                abgr16++;1433            }14341435            /* Free the 8-bit buffer as we've converted everything to 16-bit */1436            free(data_8bit);14371438            /* Create 16-bit pixman image */1439            img = pixman_image_create_bits_no_clear(1440                PIXMAN_a16b16g16r16, width, height, (uint32_t *)data_16bit,1441                width * 8);1442        } else {1443            /* Create 8-bit pixman image */1444            img = pixman_image_create_bits_no_clear(1445                PIXMAN_a8b8g8r8, width, height, (uint32_t *)data_8bit, width * 4);1446        }14471448        tll_push_back(icon->rasterized, ((struct rasterized){img, size}));1449    }14501451    const int w = pixman_image_get_width(img);1452    const int h = pixman_image_get_height(img);14531454    pixman_image_composite32(1455        PIXMAN_OP_OVER, img, NULL, pix, 0, 0, 0, 0,1456        x + (size - w) / 2,1457        y + (size - h) / 2,1458        w, h);14591460#if defined(FUZZEL_ENABLE_CAIRO)1461    cairo_surface_mark_dirty(cairo_get_target(cairo));1462#endif1463}1464#endif /* FUZZEL_ENABLE_SVG_RESVG */14651466static void1467render_svg(struct icon *icon, int x, int y, int size,1468           pixman_image_t *pix, cairo_t *cairo, bool gamma_correct,1469           bool print_timing_info)1470{1471    assert(icon->type == ICON_SVG);14721473    if (icon->svg == NULL) {1474        struct timespec *start_load = time_begin();14751476        if (!icon_from_svg(icon, icon->path)) {1477            free(start_load);1478            return;1479        }14801481        time_finish(start_load, NULL, "%s loaded", icon->path);1482        LOG_DBG("%s", icon->path);1483    }14841485    struct timespec *render_start = time_begin();14861487#if defined(FUZZEL_ENABLE_SVG_LIBRSVG)1488    render_svg_librsvg(icon, x, y, size, cairo);1489#elif defined(FUZZEL_ENABLE_SVG_NANOSVG)1490    render_svg_nanosvg(icon, x, y, size, pix, cairo, gamma_correct);1491#elif defined(FUZZEL_ENABLE_SVG_RESVG)1492    render_svg_resvg(icon, x, y, size, pix, cairo, gamma_correct);1493#endif14941495    time_finish(render_start, NULL, "%s rendered", icon->path);1496}14971498#if defined(FUZZEL_ENABLE_PNG_LIBPNG)1499static void1500render_png_libpng(struct icon *icon, int x, int y, int size,1501                  pixman_image_t *pix, cairo_t *cairo,1502                  enum scaling_filter scaling_filter)1503{1504#if defined(FUZZEL_ENABLE_CAIRO)1505    cairo_surface_flush(cairo_get_target(cairo));1506#endif15071508    pixman_image_t *png = icon->png;1509    pixman_format_code_t fmt = pixman_image_get_format(png);1510    int height = pixman_image_get_height(png);1511    int width = pixman_image_get_width(png);15121513    if (height > size || width > size) {1514        double scale = (double)size / (height > width ? height : width);15151516        pixman_f_transform_t _scale_transform;1517        pixman_f_transform_init_scale(&_scale_transform, 1. / scale, 1. / scale);15181519        pixman_transform_t scale_transform;1520        pixman_transform_from_pixman_f_transform(1521            &scale_transform, &_scale_transform);1522        pixman_image_set_transform(png, &scale_transform);15231524        const int largest_side = max(width, height);15251526        if (largest_side >= 1024) {1527            if (!icon->png_size_warned) {1528                LOG_WARN(1529                    "%s: PNG is too large (%dx%d); "1530                    "downscaling using a less precise filter (fast)",1531                    icon->path, width, height);1532                icon->png_size_warned = true;1533            }15341535            pixman_image_set_filter(png, PIXMAN_FILTER_FAST, NULL, 0);1536        }15371538        else {15391540            bool slow_scaling_filter = false;15411542            switch (scaling_filter) {1543            case SCALING_FILTER_NONE:1544            case SCALING_FILTER_NEAREST:1545            case SCALING_FILTER_BILINEAR:1546            case SCALING_FILTER_BOX:1547                slow_scaling_filter = false;1548                break;15491550            case SCALING_FILTER_CUBIC:1551            case SCALING_FILTER_LANCZOS3:1552            case SCALING_FILTER_LINEAR:1553            case SCALING_FILTER_LANCZOS2:1554            case SCALING_FILTER_LANCZOS3_STRETCHED:1555                slow_scaling_filter = true;1556                break;1557            }15581559            if (slow_scaling_filter && largest_side >= 256) {1560                if (!icon->png_size_warned) {1561                    LOG_WARN(1562                        "%s: PNG is too large (%dx%d); "1563                        "downscaling using a less precise filter (box)",1564                        icon->path, width, height);1565                    icon->png_size_warned = true;1566                }15671568                scaling_filter = SCALING_FILTER_BOX;1569            }15701571            switch (scaling_filter) {1572            case SCALING_FILTER_NONE:1573                break;15741575            /*1576             * "simple" filters1577             */15781579            case SCALING_FILTER_NEAREST:1580                pixman_image_set_filter(png, PIXMAN_FILTER_NEAREST, NULL, 0);1581                break;15821583            case SCALING_FILTER_BILINEAR:1584                pixman_image_set_filter(png, PIXMAN_FILTER_BILINEAR, NULL, 0);1585                break;15861587            /*1588             * Separable convolution filters1589             */1590            case SCALING_FILTER_CUBIC:1591            case SCALING_FILTER_LANCZOS3:1592            case SCALING_FILTER_BOX:1593            case SCALING_FILTER_LINEAR:1594            case SCALING_FILTER_LANCZOS2:1595            case SCALING_FILTER_LANCZOS3_STRETCHED: {15961597                pixman_kernel_t kernel;15981599                switch (scaling_filter) {1600                case SCALING_FILTER_CUBIC: kernel = PIXMAN_KERNEL_CUBIC; break;1601                case SCALING_FILTER_LANCZOS3: kernel = PIXMAN_KERNEL_LANCZOS3; break;1602                case SCALING_FILTER_BOX: kernel = PIXMAN_KERNEL_BOX; break;1603                case SCALING_FILTER_LINEAR: kernel = PIXMAN_KERNEL_LINEAR; break;1604                case SCALING_FILTER_LANCZOS2: kernel = PIXMAN_KERNEL_LANCZOS2; break;1605                case SCALING_FILTER_LANCZOS3_STRETCHED: kernel = PIXMAN_KERNEL_LANCZOS3_STRETCHED; break;1606                default: assert(false); kernel = PIXMAN_KERNEL_CUBIC; break;1607                }16081609                int param_count = 0;1610                pixman_fixed_t *params = pixman_filter_create_separable_convolution(1611                    &param_count,1612                    pixman_double_to_fixed(1. / scale),1613                    pixman_double_to_fixed(1. / scale),1614                    kernel, kernel,1615                    kernel, kernel,1616                    1, 1);16171618                if (params != NULL || param_count == 0) {1619                    pixman_image_set_filter(1620                        png, PIXMAN_FILTER_SEPARABLE_CONVOLUTION,1621                        params, param_count);1622                }16231624                free(params);1625                break;1626            }1627            }1628        }16291630        width *= scale;1631        height *= scale;16321633        int stride = stride_for_format_and_width(fmt, width);1634        uint8_t *data = xmalloc(height * stride);1635        pixman_image_t *scaled_png = pixman_image_create_bits_no_clear(1636            fmt, width, height, (uint32_t *)data, stride);1637        pixman_image_composite32(1638            PIXMAN_OP_SRC, png, NULL, scaled_png, 0, 0, 0, 0, 0, 0, width, height);16391640        free(pixman_image_get_data(png));1641        pixman_image_unref(png);16421643        png = scaled_png;1644        icon->png = png;1645    }16461647    pixman_image_composite32(1648        PIXMAN_OP_OVER, png, NULL, pix, 0, 0, 0, 0,1649        x + (size - width) / 2,1650        y + (size - height) / 2,1651        width, height);16521653#if defined(FUZZEL_ENABLE_CAIRO)1654    cairo_surface_mark_dirty(cairo_get_target(cairo));1655#endif1656}1657#endif /* FUZZEL_ENABLE_PNG_LIBPNG */16581659static void1660render_png(struct icon *icon, int x, int y, int size, pixman_image_t *pix,1661           cairo_t *cairo, bool gamma_correct, bool print_timing_info,1662           enum scaling_filter scaling_filter)1663{1664    assert(icon->type == ICON_PNG);16651666    if (icon->png == NULL) {1667        struct timespec *start_load = time_begin();16681669        if (!icon_from_png(icon, icon->path, gamma_correct)) {1670            free(start_load);1671            return;1672        }16731674        time_finish(start_load, NULL, "%s loaded", icon->path);1675        LOG_DBG("%s", icon->path);1676    }16771678    struct timespec *start_render = time_begin();16791680#if defined(FUZZEL_ENABLE_PNG_LIBPNG)1681    render_png_libpng(icon, x, y, size, pix, cairo, scaling_filter);1682#endif16831684    time_finish(start_render, NULL, "%s rendered", icon->path);1685}16861687static int1688first_row_y(const struct render *render)1689{1690    return (render->border_size +1691            render->y_margin +1692            (render->conf->hide_prompt ? 0 : render->row_height) +1693            (render->conf->hide_prompt ? 0 : render->inner_pad) +1694            render->message_height);1695}16961697static void1698render_match_entry_background(const struct render *render,1699                              int idx, int row_count,1700                              pixman_image_t *pix, int width)1701{1702    pixman_color_t bg = render->pix_background_color;17031704    const int x = row_bg_x(render);1705    const int y = first_row_y(render) + idx * render->row_height;1706    const int w = width - 2 * row_bg_x(render);1707    const int h = row_count * render->row_height;17081709    pixman_image_fill_rectangles(1710        PIXMAN_OP_SRC, pix, &bg, 1, &(pixman_rectangle16_t){x, y, w, h});1711}17121713static void1714render_selected_match_entry_background(struct render *render,1715                                       int idx, pixman_image_t *pix, int width)1716{1717    pixman_color_t bg = render->pix_selection_color;17181719    const int x = row_bg_x(render);1720    const int y = first_row_y(render) + idx * render->row_height;1721    const int w = width - 2 * row_bg_x(render);1722    const int h = 1 * render->row_height;17231724    // limit radius to half of height, any larger and it causes weird shapes1725    // also limit it when horizontal padding is small, to prevent icon pop out1726    const unsigned int radius = min(1727        min(render->selection_border_radius, h / 2), render->x_margin);17281729    if (render->selection_corners == NULL) {1730        render->selection_corners = pixman_image_create_bits(1731            pixman_image_get_format(pix), w, h, NULL, w * 4);1732        render_rounded_rectangle(render->selection_corners, &bg, &bg, radius, 0, 0, 0, w, h);1733    }1734    pixman_image_composite(1735        PIXMAN_OP_OVER, render->selection_corners, NULL, pix,1736        0, 0, 0, 0, x, y, w, h);1737}17381739static void1740render_one_match_entry(struct render *render, const struct matches *matches,1741                       const struct match *match, bool render_icons,1742                       int idx, bool is_selected, int width, int height,1743                       pixman_image_t *pix, cairo_t *cairo)1744{1745    const enum fcft_subpixel subpixel =1746        (render->conf->colors.background.a == 1. &&1747         render->conf->colors.selection.a == 1.)1748            ? render->subpixel : FCFT_SUBPIXEL_NONE;17491750    struct fcft_font *font =1751        is_selected ? render->font_bold : render->font;1752    const struct fcft_glyph *ellipses =1753        fcft_rasterize_char_utf32(font, U'…', subpixel);17541755    const int first_row = first_row_y(render);1756    double cur_x = render->border_size + render->x_margin;1757    double max_x = width - render->border_size - render->x_margin;17581759    render_match_entry_background(render, idx, 1, pix, width);17601761    if (is_selected) {1762        render_selected_match_entry_background(render, idx, pix, width);17631764        /* If currently selected item has a scalable icon, and if1765         * there's "enough" free space, render a large representation1766         * of the icon */17671768        const double ratio = render->conf->image_size_ratio;1769        const double size = min(height * ratio, width * ratio);1770        const double img_x = (width - size) / 2.;1771        const double img_y_bottom = max(height - first_row, 0.);1772        const double img_y = max(img_y_bottom - size, 0.);1773        const size_t match_count = matches_get_count(matches);1774        const double list_end = first_row + match_count * render->row_height;17751776        LOG_DBG("img_y=%f, list_end=%f", img_y, list_end);17771778        if (render_icons &&1779            size > 0 &&1780            match->application->icon.type == ICON_SVG &&1781            img_y > list_end + render->row_height)1782        {1783            render_svg(&match->application->icon, img_x, img_y, size, pix, cairo,1784                       render->gamma_correct, render->conf->print_timing_info);1785        }1786    }17871788    if (render_icons) {1789        struct icon *icon = &match->application->icon;1790        const int size = render->icon_height;1791        const int img_x = cur_x;1792        const int img_y = first_row + idx * render->row_height + (render->row_height - size) / 2;17931794        switch (icon->type) {1795        case ICON_NONE:1796            break;17971798        case ICON_PNG:1799            render_png(icon, img_x, img_y, size, pix, cairo,1800                       render->gamma_correct, render->conf->print_timing_info,1801                       render->conf->png_scaling_filter);1802            break;18031804        case ICON_SVG:1805            render_svg(icon, img_x, img_y, size, pix, cairo,1806                       render->gamma_correct, render->conf->print_timing_info);1807            break;1808        }1809    }18101811    const struct fcft_glyph *space =1812        fcft_rasterize_char_utf32(render->font, U' ', subpixel);18131814    cur_x +=1815        (render->conf->icons_enabled && matches_have_icons(matches)1816            ? (render->row_height +1817               (space != NULL ? space->advance.x : render->font->max_advance.x))1818            : 0) +1819        pt_or_px_as_pixels(render, &render->conf->letter_spacing);18201821    /* Replace newlines in title, with spaces (basic support for1822     * multiline entries) */1823    if (match->application->render_title == NULL) {1824        char32_t *newline = c32chr(match->application->title, U'\n');18251826        if (newline != NULL) {1827            char32_t *render_title = xc32dup(match->application->title);18281829            newline = render_title + (newline - match->application->title);1830            *newline = U' ';18311832            while ((newline = c32chr(newline, U'\n')) != NULL)1833                *newline = U' ';18341835            match->application->render_title = render_title;1836        } else {1837            /* No newlines, use title as-is */1838            match->application->render_title = match->application->title;1839        }1840    }18411842    const int y = first_row + render_baseline(render) + idx * render->row_height;18431844    /* Application title */1845    render_match_text(1846        pix, &cur_x, y, max_x - (ellipses != NULL ? ellipses->width : 0),1847        match->application->render_title, match->pos_count, match->pos,1848        font, subpixel,1849        pt_or_px_as_pixels(render, &render->conf->letter_spacing),1850        render->conf->tabs,1851        (is_selected1852            ? render->pix_selection_text_color1853            : render->pix_text_color),1854        (is_selected1855            ? render->pix_selection_match_color1856            : render->pix_match_color),1857        (is_selected1858            ? &match->application->shaped_bold1859            : &match->application->shaped));1860}18611862void1863render_match_list(struct render *render, struct buffer *buf,1864                  const struct prompt *prompt, const struct matches *matches)1865{1866    const size_t match_count = matches_get_count(matches);1867    const size_t selected = matches_get_match_index(matches);18681869    assert(match_count == 0 || selected < match_count);18701871    bool render_icons = mtx_trylock(render->icon_lock) == thrd_success;18721873    if (render->workers.count > 0) {1874        mtx_lock(&render->workers.lock);1875        render->workers.matches = matches;1876        render->workers.buf = buf;1877        render->workers.render_icons= render_icons;18781879        for (size_t i = 0; i < render->workers.count; i++)1880            sem_post(&render->workers.start);18811882        assert(tll_length(render->workers.queue) == 0);1883    }18841885    /* Erase background of the "empty" area, after the last match */1886    const size_t effective_lines = matches_max_matches_per_page(matches);1887    render_match_entry_background(1888        render, match_count, effective_lines - match_count,1889        buf->pix[0], buf->width);18901891    for (size_t i = 0; i < match_count; i++) {1892        if (render->workers.count == 0) {1893            const struct match *match = matches_get(matches, i);1894            render_one_match_entry(1895                render, matches, match, render_icons, i, i == selected,1896                buf->width, buf->height, buf->pix[0],1897#if defined(FUZZEL_ENABLE_CAIRO)1898                buf->cairo[0]1899#else1900                NULL1901#endif1902                );1903        } else {1904            tll_push_back(render->workers.queue, i);1905        }1906    }19071908    if (render->workers.count > 0) {1909        for (size_t i = 0; i < render->workers.count; i++)1910            tll_push_back(render->workers.queue, -1);1911        mtx_unlock(&render->workers.lock);19121913        for (size_t i = 0; i < render->workers.count; i++)1914            sem_wait(&render->workers.done);19151916        render->workers.matches = NULL;1917        render->workers.buf = NULL;1918        render->workers.render_icons = false;1919    }19201921    if (render_icons)1922        mtx_unlock(render->icon_lock);1923}19241925/* THREAD */1926static int1927render_worker_thread(void *_ctx)1928{1929    struct thread_context *ctx = _ctx;1930    struct render *render = ctx->render;1931    const int my_id = ctx->my_id;1932    free(ctx);19331934    sigset_t mask;1935    sigfillset(&mask);1936    pthread_sigmask(SIG_SETMASK, &mask, NULL);19371938    char proc_title[16];1939    xsnprintf(proc_title, sizeof(proc_title), "fuzzel:rend:%d", my_id);19401941    if (pthread_setname_np(pthread_self(), proc_title) < 0)1942        LOG_ERRNO("render worker %d: failed to set process title", my_id);19431944    sem_t *start = &render->workers.start;1945    sem_t *done = &render->workers.done;1946    mtx_t *lock = &render->workers.lock;19471948    while (true) {1949        sem_wait(start);19501951        const struct matches *matches = render->workers.matches;1952        struct buffer *buf = render->workers.buf;1953        const bool render_icons = render->workers.render_icons;1954        const size_t selected = matches != NULL1955            ? matches_get_match_index(matches)1956            : 0;19571958        bool frame_done = false;19591960        while (!frame_done) {1961            mtx_lock(lock);1962            assert(tll_length(render->workers.queue) > 0);19631964            int row_no = tll_pop_front(render->workers.queue);1965            mtx_unlock(lock);19661967            switch (row_no) {1968            default: {1969                assert(buf != NULL);19701971                const struct match *match = matches_get(matches, row_no);1972                render_one_match_entry(1973                    render, matches, match, render_icons,1974                    row_no, row_no == selected, buf->width, buf->height,1975                    buf->pix[my_id],1976#if defined(FUZZEL_ENABLE_CAIRO)1977                    buf->cairo[my_id]1978#else1979                    NULL1980#endif1981                    );19821983                break;1984            }19851986            case -1:1987                frame_done = true;1988                sem_post(done);1989                break;19901991            case -2:1992                return 0;1993            }1994        }1995    }19961997    return -1;1998}19992000struct render *

The first 2,000 of 2,298 lines.