twn_text.c: dont segfault on font not found

This commit is contained in:
veclavtalica 2025-02-17 12:32:01 +03:00
parent 4c1a8e087a
commit a1f4599efd

View File

@ -108,11 +108,8 @@ static char *string_arena_alloc(StringArena *arena, size_t size) {
static FontData *text_load_font_data(const char *path, int height_px) {
FontData *font_data = ccalloc(1, sizeof *font_data);
font_data->file_path = path;
font_data->height_px = height_px;
unsigned char* bitmap = ccalloc(ctx.font_texture_size * ctx.font_texture_size, 1);
FontData *font_data;
unsigned char* bitmap;
{
unsigned char *buf = NULL;
@ -125,10 +122,21 @@ static FontData *text_load_font_data(const char *path, int height_px) {
buf_len = font_file_ptr->value.len;
} else {
buf_len = file_to_bytes(path, &buf);
if (buf_len == -1) {
/* TODO: have a fallback default font */
log_warn("Font %s not found", path);
return NULL;
}
FontFileBuffer buffer = { buf_len, buf };
shput(font_file_cache_hash, path, buffer);
}
font_data = ccalloc(1, sizeof *font_data);
font_data->file_path = path;
font_data->height_px = height_px;
bitmap = ccalloc(ctx.font_texture_size * ctx.font_texture_size, 1);
stbtt_InitFont(&font_data->info, buf, stbtt_GetFontOffsetForIndex(buf, 0));
/* might as well get these now, for later */
@ -224,7 +232,7 @@ static void text_draw_with(FontData* font_data, char* text, Vec2 position, Color
}
static void ensure_font_cache(const char *font_path, int height_px) {
static bool ensure_font_cache(const char *font_path, int height_px) {
/* HACK: don't */
bool is_cached = false;
for (size_t i = 0; i < arrlenu(ctx.text_cache.data); ++i) {
@ -236,8 +244,11 @@ static void ensure_font_cache(const char *font_path, int height_px) {
}
if (!is_cached) {
FontData *new_font_data = text_load_font_data(font_path, height_px);
if (new_font_data == NULL)
return false;
arrput(ctx.text_cache.data, new_font_data);
}
return true;
}
@ -294,7 +305,8 @@ void draw_text(const char *string, Vec2 position, float height, Color color, con
return;
}
ensure_font_cache(font, (int)height);
if (!ensure_font_cache(font, (int)height))
return;
/* the original string might not be around by the time it's used, so copy it */
size_t str_length = SDL_strlen(string) + 1;
@ -322,7 +334,9 @@ void draw_text(const char *string, Vec2 position, float height, Color color, con
float draw_text_width(const char *string, float height, const char *font) {
ensure_font_cache(font, (int)height);
if (!ensure_font_cache(font, (int)height))
return 0;
FontData *font_data = get_font_data(font, (int)height);
int length = 0;