Blender V5.3
blf_font.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2009 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
12
13#include <algorithm>
14#include <cstdio>
15#include <cstdlib>
16#include <cstring>
17
18#include <ft2build.h>
19
20#include FT_FREETYPE_H
21#include FT_CACHE_H /* FreeType Cache. */
22#include FT_GLYPH_H
23#include FT_MULTIPLE_MASTERS_H /* Variable font support. */
24#include FT_TRUETYPE_IDS_H /* Code-point coverage constants. */
25#include FT_TRUETYPE_TABLES_H /* For TT_OS2 */
26
27#include "MEM_guardedalloc.h"
28
29#include "DNA_vec_types.h"
30
31#include "BLI_math_bits.hh"
33#include "BLI_math_matrix_c.hh"
34#include "BLI_mutex.hh"
35#include "BLI_path_utils.hh"
36#include "BLI_rect.hh"
37#include "BLI_string.hh"
39#include "BLI_string_utf8.hh"
40#include "BLI_vector.hh"
41
42#include "BLF_api.hh"
43
44#include "GPU_batch.hh"
45#include "GPU_matrix.hh"
46#include "GPU_state.hh"
47
48#include "blf_internal.hh"
49#include "blf_internal_types.hh"
50
51#include "BLI_strict_flags.hh" /* IWYU pragma: keep. Keep last. */
52
53namespace blender {
54
55#ifdef WIN32
56# define FT_New_Face FT_New_Face__win32_compat
57#endif
58
59/* Batching buffer for drawing. */
60
62
63/* `freetype2` handle ONLY for this file! */
64static FT_Library ft_lib = nullptr;
65static FTC_Manager ftc_manager = nullptr;
66static FTC_CMapCache ftc_charmap_cache = nullptr;
67
68/* Mutex around face creation and deletion. */
70
71/* Lock around places that query free type caching system, and use the
72 * calculated ft_size result. `FTC_Manager_LookupSize` can remove
73 * ft_size of a completely different font instance, when the cache
74 * is full! */
76
77/* May be set to #widgetbase_draw_cache_flush. */
78static void (*blf_draw_cache_flush)() = nullptr;
79
82
83/* -------------------------------------------------------------------- */
86
87static bool blf_setup_face(FontBLF *font);
88
92static void blf_face_finalizer(void *object)
93{
94 FT_Face face = static_cast<FT_Face>(object);
95 FontBLF *font = static_cast<FontBLF *>(face->generic.data);
96 font->face = nullptr;
97}
98
104static FT_Error blf_cache_face_requester(FTC_FaceID faceID,
105 FT_Library lib,
106 FT_Pointer /*req_data*/,
107 FT_Face *face)
108{
109 FontBLF *font = static_cast<FontBLF *>(faceID);
110 int err = FT_Err_Cannot_Open_Resource;
111
112 std::scoped_lock lock(ft_face_load_mutex);
113 if (font->filepath) {
114 err = FT_New_Face(lib, font->filepath, 0, face);
115 }
116 else if (font->mem) {
117 err = FT_New_Memory_Face(
118 lib, static_cast<const FT_Byte *>(font->mem), FT_Long(font->mem_size), 0, face);
119 }
120
121 if (err == FT_Err_Ok) {
122 font->face = *face;
123 font->face->generic.data = font;
124 font->face->generic.finalizer = blf_face_finalizer;
125
126 /* More FontBLF setup now that we have a face. */
127 if (!blf_setup_face(font)) {
128 err = FT_Err_Cannot_Open_Resource;
129 }
130 }
131 else {
132 /* Clear this on error to avoid exception in FTC_Manager_LookupFace. */
133 *face = nullptr;
134 }
135
136 return err;
137}
138
142static void blf_size_finalizer(void *object)
143{
144 FT_Size size = static_cast<FT_Size>(object);
145 FontBLF *font = static_cast<FontBLF *>(size->generic.data);
146 font->ft_size = nullptr;
147}
148
150
151/* -------------------------------------------------------------------- */
154
155uint blf_get_char_index(FontBLF *font, const uint charcode)
156{
157 return FTC_CMapCache_Lookup(ftc_charmap_cache, font, -1, charcode);
158}
159
160/* Convert a FreeType 26.6 value representing an unscaled design size to fractional pixels. */
161static ft_pix blf_unscaled_F26Dot6_to_pixels(FontBLF *font, const FT_Pos value)
162{
163 std::lock_guard lock(ft_cache_size_mutex);
164 blf_ensure_size(font);
165
166 /* Scale value by font size using integer-optimized multiplication. */
167 FT_Long scaled = FT_MulFix(value, font->ft_size->metrics.x_scale);
168
169 /* Copied from FreeType's FT_Get_Kerning (with FT_KERNING_DEFAULT), scaling down. */
170 /* Kerning distances at small PPEM values so that they don't become too big. */
171 if (font->ft_size->metrics.x_ppem < 25) {
172 scaled = FT_MulDiv(scaled, font->ft_size->metrics.x_ppem, 25);
173 }
174
175 return ft_pix(scaled);
176}
177
179
180/* -------------------------------------------------------------------- */
183
191{
193 sizeof(g_batch.glyph_data), nullptr, GPU_USAGE_STREAM, __func__);
194 g_batch.glyph_len = 0;
195 /* We render a quad as a triangle strip and instance it for each glyph. */
197}
198
206
208{
209 if (g_batch.batch == nullptr) {
211 }
212
213 const bool font_changed = (g_batch.font != font);
214 const bool simple_shader = ((font->flags & (BLF_ROTATION | BLF_ASPECT)) == 0);
215 const bool shader_changed = (simple_shader != g_batch.simple_shader);
216
217 g_batch.active = g_batch.enabled && simple_shader;
218
219 if (simple_shader) {
220 /* Offset is applied to each glyph. */
221 g_batch.ofs[0] = font->pos[0];
222 g_batch.ofs[1] = font->pos[1];
223 }
224 else {
225 /* Offset is baked in model-view matrix. */
227 }
228
229 if (g_batch.active) {
230 float gpumat[4][4];
232
233 bool mat_changed = equals_m4m4(gpumat, g_batch.mat) == false;
234
235 if (mat_changed) {
236 /* Model view matrix is no longer the same.
237 * Flush cache but with the previous matrix. */
240 }
241
242 /* Flush cache if configuration is not the same. */
243 if (mat_changed || font_changed || shader_changed) {
245 g_batch.simple_shader = simple_shader;
246 g_batch.font = font;
247 }
248 else {
249 /* Nothing changed continue batching. */
250 return;
251 }
252
253 if (mat_changed) {
255 /* Save for next `memcmp`. */
256 memcpy(g_batch.mat, gpumat, sizeof(g_batch.mat));
257 }
258 }
259 else {
260 /* Flush cache. */
262 g_batch.font = font;
263 g_batch.simple_shader = simple_shader;
264 }
265}
266
268{
270 BLI_assert(gc);
271 BLI_assert(gc->bitmap_len > 0);
272
273 if (gc->bitmap_len > gc->bitmap_len_landed) {
274 const int tex_width = GPU_texture_width(gc->texture);
275
276 int bitmap_len_landed = gc->bitmap_len_landed;
277 int remain = gc->bitmap_len - bitmap_len_landed;
278 int offset_x = bitmap_len_landed % tex_width;
279 int offset_y = bitmap_len_landed / tex_width;
280
281 /* TODO(@germano): Update more than one row in a single call. */
282 while (remain) {
283 int remain_row = tex_width - offset_x;
284 int width = remain > remain_row ? remain_row : remain;
287 &gc->bitmap_result[bitmap_len_landed],
288 offset_x,
289 offset_y,
290 0,
291 width,
292 1,
293 0);
294
295 bitmap_len_landed += width;
296 remain -= width;
297 offset_x = 0;
298 offset_y += 1;
299 }
300
301 gc->bitmap_len_landed = bitmap_len_landed;
302 }
303
304 return gc->texture;
305}
306
308{
309 if (g_batch.glyph_len == 0) {
310 return;
311 }
312
314
315 /* We need to flush widget base first to ensure correct ordering. */
316 if (blf_draw_cache_flush != nullptr) {
318 }
319
324
327 /* Setup texture width mask and shift, so that shader can avoid costly divisions. */
328 int tex_width = GPU_texture_width(texture);
329 BLI_assert_msg(is_power_of_2_i(tex_width), "Font texture width must be power of two");
330 int width_shift = 31 - bitscan_reverse_i(tex_width);
331 GPU_batch_uniform_1i(g_batch.batch, "glyph_tex_width_mask", tex_width - 1);
332 GPU_batch_uniform_1i(g_batch.batch, "glyph_tex_width_shift", width_shift);
334
336
338 g_batch.glyph_len = 0;
339}
340
342{
343 if (!g_batch.active) {
345 }
346}
347
356
358
359/* -------------------------------------------------------------------- */
362
363BLI_INLINE ft_pix blf_kerning(FontBLF *font, const GlyphBLF *g_prev, const GlyphBLF *g)
364{
365 ft_pix adjustment = 0;
366
367 /* Small adjust if there is hinting. */
368 adjustment += g->lsb_delta - ((g_prev) ? g_prev->rsb_delta : 0);
369
370 if (FT_HAS_KERNING(font) && g_prev) {
371 FT_Vector delta = {KERNING_ENTRY_UNSET};
372
373 /* Get unscaled kerning value from our cache if ASCII. */
374 if ((g_prev->c < KERNING_CACHE_TABLE_SIZE) && (g->c < KERNING_CACHE_TABLE_SIZE)) {
375 delta.x = font->kerning_cache->ascii_table[g->c][g_prev->c];
376 }
377
378 /* If not ASCII or not found in cache, ask FreeType for kerning. */
379 if (font->face && delta.x == KERNING_ENTRY_UNSET) [[unlikely]] {
380 /* Note that this function sets delta values to zero on any error. */
381 FT_Get_Kerning(font->face, g_prev->idx, g->idx, FT_KERNING_UNSCALED, &delta);
382 }
383
384 /* If ASCII we save this value to our cache for quicker access next time. */
385 if ((g_prev->c < KERNING_CACHE_TABLE_SIZE) && (g->c < KERNING_CACHE_TABLE_SIZE)) {
386 font->kerning_cache->ascii_table[g->c][g_prev->c] = int(delta.x);
387 }
388
389 if (delta.x != 0) {
390 /* Convert unscaled design units to pixels and move pen. */
391 adjustment += blf_unscaled_F26Dot6_to_pixels(font, delta.x);
392 }
393 }
394
395 return adjustment;
396}
397
399 GlyphCacheBLF *gc,
400 const GlyphBLF *g_prev,
401 const char *str,
402 const size_t str_len,
403 size_t *i_p,
404 int32_t *pen_x)
405{
406 uint charcode = BLI_str_utf8_as_unicode_step_safe(str, str_len, i_p);
407 /* Invalid unicode sequences return the byte value, stepping forward one.
408 * This allows `latin1` to display (which is sometimes used for file-paths). */
409 BLI_assert(charcode != BLI_UTF8_ERR);
410 GlyphBLF *g = blf_glyph_ensure(font, gc, charcode);
411 if (g && pen_x && !(font->flags & BLF_MONOSPACED)) {
412 *pen_x += blf_kerning(font, g_prev, g);
413
414#ifdef BLF_SUBPIXEL_POSITION
415 if (!(font->flags & BLF_RENDER_SUBPIXELAA)) {
416 *pen_x = FT_PIX_ROUND(*pen_x);
417 }
418#else
419 *pen_x = FT_PIX_ROUND(*pen_x);
420#endif
421
422#ifdef BLF_SUBPIXEL_AA
423 g = blf_glyph_ensure_subpixel(font, gc, g, *pen_x);
424#endif
425 }
426 return g;
427}
428
436{
437 return flag_is_set(g->flags, GlyphFlagBLF::Combining);
438}
439
464
470 FontBLF *font, GlyphCacheBLF *gc, GlyphStepData &step, const char *str, const size_t str_len)
471{
472 const ft_pix pen_x_prev = step.pen_x_right;
474 font, gc, step.g_kerning, str, str_len, &step.i, &step.pen_x_right);
475 if (step.g != nullptr) {
477 /* Common case, advancing to the next character. */
478 step.pen_x_base = step.pen_x_right;
479 step.pen_x = step.pen_x_right;
480 step.pen_x_right += step.g->advance_x;
481 step.g_kerning = step.g;
482 step.offset_y = 0;
483 step.base_ymax_accum = step.g->box_ymax;
484 step.base_ymin_accum = step.g->box_ymin;
485 }
486 else {
487 /* Combining character: center the mark over the previous base character.
488 *
489 * Without GPOS data (which requires a shaping engine such as HarfBuzz),
490 * combining glyphs have no base-relative positioning. We follow the
491 * fallback algorithm used by HarfBuzz when GPOS tables are absent
492 * (see `hb-ot-shape-fallback.cc`, `position_mark`):
493 *
494 * - X: center the mark bitmap over the base character's advance width.
495 * - Y: place the mark at the accumulated top (above) or bottom (below)
496 * of the base, with a small gap. Successive marks stack.
497 * If the offset would push the mark the wrong direction, dampen it.
498 *
499 * Above/below is determined from glyph bounding boxes: the mark's
500 * vertical center vs the base glyph's vertical midpoint. */
501 step.pen_x_right = pen_x_prev;
502
503 /* Horizontal: center align (matches HarfBuzz ABOVE / BELOW default). */
504 const int base_center = (ft_pix_to_int(step.pen_x_base) + ft_pix_to_int(pen_x_prev)) / 2;
505 const int mark_center_offset = step.g->pos[0] + step.g->dims[0] / 2;
506 step.pen_x = ft_pix_from_int(base_center - mark_center_offset);
507
508 /* Vertical: reposition above/below marks (follows HarfBuzz `position_mark`). */
509 step.offset_y = 0;
510 if (step.g_kerning) {
511 const ft_pix mark_ymin = step.g->box_ymin;
512 const ft_pix mark_ymax = step.g->box_ymax;
513 const ft_pix mark_height = mark_ymax - mark_ymin;
514 const ft_pix base_mid = (step.g_kerning->box_ymin + step.g_kerning->box_ymax) / 2;
515 const ft_pix mark_mid = (mark_ymin + mark_ymax) / 2;
516 /* Gap matches HarfBuzz `y_gap = font->y_scale / 16`. */
517 const ft_pix y_gap = ft_pix_from_float(gc->size) / 16;
518
519 if (mark_mid > base_mid) {
520 /* Above mark. */
521 step.base_ymax_accum += y_gap;
522 step.offset_y = step.base_ymax_accum - mark_ymin;
523 /* Don't shift down "above" marks too much (HarfBuzz dampening). */
524 if ((y_gap > 0) != (step.offset_y > 0)) {
525 const ft_pix correction = -step.offset_y / 2;
526 step.base_ymax_accum += correction;
527 step.offset_y += correction;
528 }
529 step.base_ymax_accum += mark_height;
530 }
531 else {
532 /* Below mark. */
533 step.base_ymin_accum -= y_gap;
534 step.offset_y = step.base_ymin_accum - mark_ymax;
535 /* Never shift up "below" marks (HarfBuzz dampening). */
536 if ((y_gap > 0) == (step.offset_y > 0)) {
537 step.base_ymin_accum -= step.offset_y;
538 step.offset_y = 0;
539 }
540 step.base_ymin_accum -= mark_height;
541 }
542 }
543 }
544 return true;
545 }
546 return false;
547}
548
554{
555 step.g = nullptr;
556 step.g_kerning = nullptr;
557 step.pen_x = 0;
558 step.pen_x_right = 0;
559 step.pen_x_base = 0;
560 step.offset_y = 0;
561 step.base_ymax_accum = 0;
562 step.base_ymin_accum = 0;
563}
564
566
567/* -------------------------------------------------------------------- */
570
574[[maybe_unused]] static int blf_str_is_utf8_valid_lazy_init(const char *str,
575 const size_t str_len,
576 int &is_utf8_valid)
577{
578 if (is_utf8_valid == -1) {
579 is_utf8_valid = BLI_str_utf8_invalid_byte(str, str_len) == -1;
580 }
581 return is_utf8_valid;
582}
583
585
586/* -------------------------------------------------------------------- */
589
590static void blf_font_draw_ex(FontBLF *font,
591 GlyphCacheBLF *gc,
592 const char *str,
593 const size_t str_len,
594 ResultBLF *r_info,
595 const ft_pix pen_y)
596{
597 if (str_len == 0) {
598 /* Early exit, don't do any immediate-mode GPU operations. */
599 return;
600 }
601
602 GlyphStepData step = {};
603
605
606 while ((step.i < str_len) && str[step.i]) {
607 if (!blf_glyph_step(font, gc, step, str, str_len)) {
608 continue;
609 }
610 /* Do not return this loop if clipped, we want every character tested. */
611 blf_glyph_draw(font,
612 gc,
613 step.g,
615 ft_pix_to_int_floor(pen_y + step.offset_y));
616 }
617
619
620 if (r_info) {
621 r_info->lines = 1;
622 r_info->width = ft_pix_to_int(step.pen_x_right);
623 }
624}
625void blf_font_draw(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
626{
628 blf_font_draw_ex(font, gc, str, str_len, r_info, 0);
630}
631
633 const char *str,
634 const size_t str_len,
635 const int char_width,
636 const int tab_columns)
637{
638 GlyphBLF *g;
639 int columns = 0;
640 ft_pix pen_x = 0, pen_y = 0;
641 ft_pix char_width_fpx = ft_pix_from_int(char_width);
642
643 size_t i = 0;
644
646
648
649 while ((i < str_len) && str[i]) {
650 g = blf_glyph_from_utf8_and_step(font, gc, nullptr, str, str_len, &i, nullptr);
651
652 if (g == nullptr) [[unlikely]] {
653 continue;
654 }
655 /* Do not return this loop if clipped, we want every character tested. */
656 blf_glyph_draw(font, gc, g, ft_pix_to_int_floor(pen_x), ft_pix_to_int_floor(pen_y));
657
658 const int col = UNLIKELY(g->c == '\t') ? (tab_columns - (columns % tab_columns)) :
659 BLI_wcwidth_safe(char32_t(g->c));
660 columns += col;
661 pen_x += char_width_fpx * col;
662 }
663
665
667 return columns;
668}
669
670#ifndef WITH_HEADLESS
672 const uint icon_id,
673 const float size,
674 const float color[4],
675 const float outline_alpha,
676 const bool multicolor,
677 FunctionRef<void(std::string &)> edit_source_cb)
678{
679 BLI_assert(outline_alpha <= 1.0f); /* Higher values overflow, caller must ensure. */
680 blf_font_size(font, size);
681
682 if (color != nullptr) {
684 }
685
686 if (outline_alpha > 0.0f) {
687 font->flags |= BLF_SHADOW;
689 font->shadow_x = 0;
690 font->shadow_y = 0;
691 font->shadow_color[0] = 0;
692 font->shadow_color[1] = 0;
693 font->shadow_color[2] = 0;
694 font->shadow_color[3] = char(outline_alpha * 255.0f);
695 }
696
699
700 GlyphBLF *g = blf_glyph_ensure_icon(gc, icon_id, multicolor, edit_source_cb);
701 if (g) {
702 blf_glyph_draw(font, gc, g, 0, 0);
703 }
704
705 if (outline_alpha > 0) {
706 font->flags &= ~BLF_SHADOW;
707 }
708
711}
712
714 const uint icon_id,
715 const float size,
716 int *r_width,
717 int *r_height,
718 const bool multicolor,
719 FunctionRef<void(std::string &)> edit_source_cb)
720{
721 blf_font_size(font, size);
723 GlyphBLF *g = blf_glyph_ensure_icon(gc, icon_id, multicolor, edit_source_cb);
724
725 if (!g) {
727 *r_width = 0;
728 *r_height = 0;
729 return {};
730 }
731
732 *r_width = g->dims[0];
733 *r_height = g->dims[1];
734 Array<uchar> bitmap(g->dims[0] * g->dims[1] * 4);
735
736 if (g->num_channels == 4) {
737 memcpy(bitmap.data(), g->bitmap, size_t(bitmap.size()));
738 }
739 else if (g->num_channels == 1) {
740 for (int64_t y = 0; y < int64_t(g->dims[1]); y++) {
741 for (int64_t x = 0; x < int64_t(g->dims[0]); x++) {
742 int64_t offs_in = (y * int64_t(g->pitch)) + x;
743 bitmap[int64_t(offs_in * 4)] = g->bitmap[offs_in];
744 bitmap[int64_t(offs_in * 4 + 1)] = g->bitmap[offs_in];
745 bitmap[int64_t(offs_in * 4 + 2)] = g->bitmap[offs_in];
746 bitmap[int64_t(offs_in * 4 + 3)] = g->bitmap[offs_in];
747 }
748 }
749 }
751 return bitmap;
752}
753#endif /* WITH_HEADLESS */
754
756
757/* -------------------------------------------------------------------- */
760
765 GlyphBLF *g,
766 const ft_pix pen_x,
767 const ft_pix pen_y_basis)
768{
769 /* Match the GPU path: floor pen_x then add pos[0] in integer space. */
770 const int chx = ft_pix_to_int_floor(pen_x) + g->pos[0];
771
772 /* Match the GPU path's Y calculation: baseline + pos[1] gives the top of the glyph
773 * (in bottom-up coordinates). The bitmap rows start from pen_y upward. */
774 const int glyph_y = ft_pix_to_int_floor(pen_y_basis) + g->pos[1] - g->dims[1];
775 const int chy = glyph_y + g->dims[1];
776
777 ft_pix pen_y = ft_pix_from_int(glyph_y);
778
779 if ((chx + g->dims[0]) < 0 || /* Out of bounds: left. */
780 chx >= buf_info->dims[0] || /* Out of bounds: right. */
781 (ft_pix_to_int(pen_y) + g->dims[1]) < 0 || /* Out of bounds: bottom. */
782 ft_pix_to_int(pen_y) >= buf_info->dims[1] /* Out of bounds: top. */
783 )
784 {
785 return;
786 }
787
788 /* Don't draw beyond the buffer bounds. */
789 int width_clip = g->dims[0];
790 int height_clip = g->dims[1];
791 int yb_start = g->pitch < 0 ? 0 : g->dims[1] - 1;
792
793 if (width_clip + chx > buf_info->dims[0]) {
794 width_clip -= chx + width_clip - buf_info->dims[0];
795 }
796 if (height_clip + ft_pix_to_int(pen_y) > buf_info->dims[1]) {
797 height_clip -= ft_pix_to_int(pen_y) + height_clip - buf_info->dims[1];
798 }
799
800 /* Clip drawing below the image. */
801 if (pen_y < 0) {
802 yb_start += (g->pitch < 0) ? -ft_pix_to_int(pen_y) : ft_pix_to_int(pen_y);
803 height_clip += ft_pix_to_int(pen_y);
804 pen_y = 0;
805 }
806
807 /* Avoid conversions in the pixel writing loop. */
808 const int pen_y_px = ft_pix_to_int(pen_y);
809
810 const float *b_col_float = buf_info->col_float;
811 const uchar *b_col_char = buf_info->col_char;
812
813 if (buf_info->fbuf) {
814 int yb = yb_start;
815 for (int y = ((chy >= 0) ? 0 : -chy); y < height_clip; y++) {
816 const int x_start = (chx >= 0) ? 0 : -chx;
817 const uchar *a_ptr = g->bitmap + x_start + (yb * g->pitch);
818 const int64_t buf_ofs = (int64_t(buf_info->dims[0]) * (pen_y_px + y) + (chx + x_start)) *
819 buf_info->channel_count;
820 float *fbuf = buf_info->fbuf + buf_ofs;
821 if (buf_info->channel_count == 4) {
822 for (int x = x_start; x < width_clip; x++, a_ptr++, fbuf += 4) {
823 const char a_byte = *a_ptr;
824 if (a_byte) {
825 const float a = (a_byte / 255.0f) * b_col_float[3];
826
827 float font_pixel[4];
828 font_pixel[0] = b_col_float[0] * a;
829 font_pixel[1] = b_col_float[1] * a;
830 font_pixel[2] = b_col_float[2] * a;
831 font_pixel[3] = a;
832 blend_color_mix_float(fbuf, fbuf, font_pixel);
833 }
834 }
835 }
836 else {
837 for (int x = x_start; x < width_clip; x++, a_ptr++, fbuf++) {
838 const char a_byte = *a_ptr;
839 if (a_byte) {
840 *fbuf = (a_byte / 255.0f) * b_col_float[0];
841 }
842 }
843 }
844
845 if (g->pitch < 0) {
846 yb++;
847 }
848 else {
849 yb--;
850 }
851 }
852 }
853
854 if (buf_info->cbuf) {
855 int yb = yb_start;
856 for (int y = ((chy >= 0) ? 0 : -chy); y < height_clip; y++) {
857 const int x_start = (chx >= 0) ? 0 : -chx;
858 const uchar *a_ptr = g->bitmap + x_start + (yb * g->pitch);
859 const int64_t buf_ofs = (int64_t(buf_info->dims[0]) * (pen_y_px + y) + (chx + x_start)) *
860 buf_info->channel_count;
861 uchar *cbuf = buf_info->cbuf + buf_ofs;
862 if (buf_info->channel_count == 4) {
863 for (int x = x_start; x < width_clip; x++, a_ptr++, cbuf += 4) {
864 const char a_byte = *a_ptr;
865
866 if (a_byte) {
867 const float a = (a_byte / 255.0f) * b_col_float[3];
868
869 uchar font_pixel[4];
870 font_pixel[0] = b_col_char[0];
871 font_pixel[1] = b_col_char[1];
872 font_pixel[2] = b_col_char[2];
873 font_pixel[3] = unit_float_to_uchar_clamp(a);
874 blend_color_mix_byte(cbuf, cbuf, font_pixel);
875 }
876 }
877 }
878 else {
879 for (int x = x_start; x < width_clip; x++, a_ptr++, cbuf++) {
880 const char a_byte = *a_ptr;
881 if (a_byte) {
882 const float a = (a_byte / 255.0f) * b_col_float[0];
883 *cbuf = unit_float_to_uchar_clamp(a);
884 }
885 }
886 }
887
888 if (g->pitch < 0) {
889 yb++;
890 }
891 else {
892 yb--;
893 }
894 }
895 }
896}
897
898/* Sanity checks are done by BLF_draw_buffer() */
900 GlyphCacheBLF *gc,
901 const char *str,
902 const size_t str_len,
903 const ft_pix pen_y,
904 ResultBLF *r_info)
905{
906 GlyphStepData step = {};
907
908 /* Keep step coordinates in the same space as the GPU path (origin at 0).
909 * Apply font->pos as an offset when drawing, matching how the GPU path
910 * applies it via a matrix translation. */
911 const ft_pix pos_x = ft_pix_from_int(font->pos[0]);
912 ft_pix pen_y_basis = ft_pix_from_int(font->pos[1]) + pen_y;
913 FontBufInfoBLF *buf_info = &font->buf_info;
914
915 /* Another buffer specific call for color conversion. */
916
917 while ((step.i < str_len) && str[step.i]) {
918 if (!blf_glyph_step(font, gc, step, str, str_len)) {
919 continue;
920 }
921 blf_glyph_draw_buffer(buf_info, step.g, step.pen_x + pos_x, pen_y_basis + step.offset_y);
922 }
923
924 if (r_info) {
925 r_info->lines = 1;
926 r_info->width = ft_pix_to_int(step.pen_x_right);
927 }
928}
929
930void blf_font_draw_buffer(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
931{
933 blf_font_draw_buffer_ex(font, gc, str, str_len, 0, r_info);
935}
936
938
939/* -------------------------------------------------------------------- */
946
948 GlyphCacheBLF *gc,
949 const GlyphBLF *g_prev,
950 GlyphBLF *g,
951 ft_pix *pen_x,
952 const int width_i)
953{
954 if (g == nullptr) [[unlikely]] {
955 /* Continue the calling loop. */
956 return false;
957 }
958
959 if (!(font->flags & BLF_MONOSPACED)) {
960 *pen_x += blf_kerning(font, g_prev, g);
961
962#ifdef BLF_SUBPIXEL_POSITION
963 if (!(font->flags & BLF_RENDER_SUBPIXELAA)) {
964 *pen_x = FT_PIX_ROUND(*pen_x);
965 }
966#else
967 *pen_x = FT_PIX_ROUND(*pen_x);
968#endif
969
970#ifdef BLF_SUBPIXEL_AA
971 g = blf_glyph_ensure_subpixel(font, gc, g, *pen_x);
972#endif
973 }
974
975 *pen_x += g->advance_x;
976
977 /* When true, break the calling loop. */
978 return (ft_pix_to_int(*pen_x) >= width_i);
979}
980
982 FontBLF *font, const char *str, const size_t str_len, int width, int *r_width)
983{
984 GlyphStepData step = {};
985 size_t i_prev = 0;
986 ft_pix width_new = 0;
987
989 const int width_i = width;
990
991 while ((step.i < str_len) && str[step.i]) {
992 if (!blf_glyph_step(font, gc, step, str, str_len)) {
993 continue;
994 }
995 if (ft_pix_to_int(step.pen_x_right) >= width_i) {
996 break;
997 }
998 i_prev = step.i;
999 width_new = step.pen_x_right;
1000 }
1001
1002 if (r_width) {
1003 *r_width = ft_pix_to_int(width_new);
1004 }
1005
1007 return i_prev;
1008}
1009
1011 FontBLF *font, const char *str, const size_t str_len, int width, int *r_width)
1012{
1013 GlyphBLF *g, *g_prev;
1014 ft_pix pen_x, width_new;
1015 size_t i, i_prev, i_tmp;
1016 std::optional<size_t> i_next = {};
1017 const char *s, *s_prev;
1018
1020#ifndef NDEBUG
1021 int is_utf8_valid = -1;
1022#endif
1023
1024 i = BLI_strnlen(str, str_len);
1026 i = size_t(s - str);
1027 s_prev = BLI_str_find_prev_char_utf8(s, str);
1028 i_prev = size_t(s_prev - str);
1029
1030 i_tmp = i;
1031 g = blf_glyph_from_utf8_and_step(font, gc, nullptr, str, str_len, &i_tmp, nullptr);
1032 for (width_new = pen_x = 0; (s != nullptr && i > 0);
1033 i_next = i, i = i_prev, s = s_prev, g = g_prev, g_prev = nullptr, width_new = pen_x)
1034 {
1035 s_prev = BLI_str_find_prev_char_utf8(s, str);
1036 i_prev = size_t(s_prev - str);
1037
1038 i_tmp = i_prev;
1039 g_prev = blf_glyph_from_utf8_and_step(font, gc, nullptr, str, str_len, &i_tmp, nullptr);
1040 BLI_assert(i_tmp == i ||
1041 /* TODO: proper handling of non UTF8 strings. */
1042 (blf_str_is_utf8_valid_lazy_init(str, str_len, is_utf8_valid) == 0));
1043
1044 /* Skip kerning when the left-neighbor is a combining character. */
1045 const GlyphBLF *g_prev_kerning = (g_prev && !blf_glyph_is_combining(g_prev)) ? g_prev :
1046 nullptr;
1047 if (blf_font_width_to_strlen_glyph_process(font, gc, g_prev_kerning, g, &pen_x, width)) {
1048 break;
1049 }
1050 }
1051
1052 if (r_width) {
1053 *r_width = ft_pix_to_int(width_new);
1054 }
1055
1057 return i_next ? *i_next : i;
1058}
1059
1061
1062/* -------------------------------------------------------------------- */
1065
1067 GlyphCacheBLF *gc,
1068 const char *str,
1069 const size_t str_len,
1070 rcti *r_box,
1071 ResultBLF *r_info,
1072 ft_pix pen_y)
1073{
1074 GlyphStepData step = {};
1075
1076 ft_pix box_xmin = ft_pix_from_int(32000);
1077 ft_pix box_xmax = ft_pix_from_int(-32000);
1078 ft_pix box_ymin = ft_pix_from_int(32000);
1079 ft_pix box_ymax = ft_pix_from_int(-32000);
1080
1081 while ((step.i < str_len) && str[step.i]) {
1082 if (!blf_glyph_step(font, gc, step, str, str_len)) {
1083 continue;
1084 }
1085
1086 const ft_pix gbox_xmin = std::min(step.pen_x, step.pen_x + step.g->box_xmin);
1087 /* Mono-spaced characters should only use advance. See #130385. */
1088 const ft_pix gbox_xmax = (font->flags & BLF_MONOSPACED) ?
1089 step.pen_x_right :
1090 std::max(step.pen_x_right, step.pen_x + step.g->box_xmax);
1091 const ft_pix gbox_ymin = step.g->box_ymin + pen_y + step.offset_y;
1092 const ft_pix gbox_ymax = step.g->box_ymax + pen_y + step.offset_y;
1093
1094 box_xmin = std::min(gbox_xmin, box_xmin);
1095 box_ymin = std::min(gbox_ymin, box_ymin);
1096
1097 box_xmax = std::max(gbox_xmax, box_xmax);
1098 box_ymax = std::max(gbox_ymax, box_ymax);
1099 }
1100
1101 if (box_xmin > box_xmax) {
1102 box_xmin = 0;
1103 box_ymin = 0;
1104 box_xmax = 0;
1105 box_ymax = 0;
1106 }
1107
1108 r_box->xmin = ft_pix_to_int_floor(box_xmin);
1109 r_box->xmax = ft_pix_to_int_ceil(box_xmax);
1110 r_box->ymin = ft_pix_to_int_floor(box_ymin);
1111 r_box->ymax = ft_pix_to_int_ceil(box_ymax);
1112
1113 if (r_info) {
1114 r_info->lines = 1;
1115 r_info->width = ft_pix_to_int(step.pen_x_right);
1116 }
1117}
1119 FontBLF *font, const char *str, const size_t str_len, rcti *r_box, ResultBLF *r_info)
1120{
1122 blf_font_boundbox_ex(font, gc, str, str_len, r_box, r_info, 0);
1124}
1125
1127 const char *str,
1128 const size_t str_len,
1129 float *r_width,
1130 float *r_height,
1131 ResultBLF *r_info)
1132{
1133 float xa, ya;
1134 rcti box;
1135
1136 if (font->flags & BLF_ASPECT) {
1137 xa = font->aspect[0];
1138 ya = font->aspect[1];
1139 }
1140 else {
1141 xa = 1.0f;
1142 ya = 1.0f;
1143 }
1144
1145 if (font->flags & BLF_WORD_WRAP) {
1146 blf_font_boundbox__wrap(font, str, str_len, &box, r_info);
1147 }
1148 else {
1149 blf_font_boundbox(font, str, str_len, &box, r_info);
1150 }
1151 *r_width = (float(BLI_rcti_size_x(&box)) * xa);
1152 *r_height = (float(BLI_rcti_size_y(&box)) * ya);
1153}
1154
1155float blf_font_width(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
1156{
1157 float xa;
1158 rcti box;
1159
1160 if (font->flags & BLF_ASPECT) {
1161 xa = font->aspect[0];
1162 }
1163 else {
1164 xa = 1.0f;
1165 }
1166
1167 if (font->flags & BLF_WORD_WRAP) {
1168 blf_font_boundbox__wrap(font, str, str_len, &box, r_info);
1169 }
1170 else {
1171 blf_font_boundbox(font, str, str_len, &box, r_info);
1172 }
1173 return float(BLI_rcti_size_x(&box)) * xa;
1174}
1175
1176float blf_font_height(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
1177{
1178 float ya;
1179 rcti box;
1180
1181 if (font->flags & BLF_ASPECT) {
1182 ya = font->aspect[1];
1183 }
1184 else {
1185 ya = 1.0f;
1186 }
1187
1188 if (font->flags & BLF_WORD_WRAP) {
1189 blf_font_boundbox__wrap(font, str, str_len, &box, r_info);
1190 }
1191 else {
1192 blf_font_boundbox(font, str, str_len, &box, r_info);
1193 }
1194 return float(BLI_rcti_size_y(&box)) * ya;
1195}
1196
1198{
1199 const GlyphCacheBLF *gc = blf_glyph_cache_acquire(font);
1200 float width = (gc) ? float(gc->fixed_width) : font->size / 2.0f;
1202 return width;
1203}
1204
1205int blf_font_glyph_advance(FontBLF *font, const char *str)
1206{
1208 const uint charcode = BLI_str_utf8_as_unicode_safe(str);
1209 const GlyphBLF *g = blf_glyph_ensure(font, gc, charcode);
1210
1211 if (g == nullptr) [[unlikely]] {
1213 return 0;
1214 }
1215
1216 const int glyph_advance = ft_pix_to_int(g->advance_x);
1217
1219 return glyph_advance;
1220}
1221
1223 const char *str,
1224 const size_t str_len,
1225 BLF_GlyphBoundsFn user_fn,
1226 void *user_data)
1227{
1228 if (str_len == 0 || str[0] == 0) {
1229 /* Early exit. */
1230 return;
1231 }
1232
1233 GlyphStepData step = {};
1234
1236
1237 while ((step.i < str_len) && str[step.i]) {
1238 const size_t i_curr = step.i;
1239 if (!blf_glyph_step(font, gc, step, str, str_len)) {
1240 continue;
1241 }
1242 if (blf_glyph_is_combining(step.g)) [[unlikely]] {
1243 /* Ignore combining characters like diacritical marks. */
1244 continue;
1245 }
1246 rcti bounds;
1247 bounds.xmin = ft_pix_to_int_floor(step.pen_x) + ft_pix_to_int_floor(step.g->box_xmin);
1248 bounds.xmax = ft_pix_to_int_floor(step.pen_x) + ft_pix_to_int_ceil(step.g->box_xmax);
1249 bounds.ymin = ft_pix_to_int_floor(step.g->box_ymin);
1250 bounds.ymax = ft_pix_to_int_ceil(step.g->box_ymax);
1251
1252 if (user_fn(str, i_curr, &bounds, user_data) == false) {
1253 break;
1254 }
1255 }
1256
1258}
1259
1261 FontBLF *font,
1262 const char *str,
1263 size_t str_len,
1264 FunctionRef<void(int index, size_t byte_offset, int byte_len, int advance_x)> callback)
1265{
1267
1268 size_t byte_offset = 0;
1269 int index = 0;
1270 while (byte_offset <= str_len) {
1271 const int char_byte_len = BLI_str_utf8_size_safe(str);
1272 const uint charcode = BLI_str_utf8_as_unicode_safe(str);
1273 const GlyphBLF *g = blf_glyph_ensure(font, gc, charcode);
1274 const int advance_x = g ? ft_pix_to_int(g->advance_x) : 0;
1275
1276 callback(index, byte_offset, char_byte_len, advance_x);
1277
1278 index++;
1279 byte_offset += size_t(char_byte_len);
1280 str += char_byte_len;
1281 }
1282
1284}
1285
1292
1293static bool blf_cursor_position_foreach_glyph(const char * /*str*/,
1294 const size_t str_step_ofs,
1295 const rcti *bounds,
1296 void *user_data)
1297{
1299 user_data);
1300 if (data->location_x < (bounds->xmin + bounds->xmax) / 2) {
1301 data->r_offset = str_step_ofs;
1302 return false;
1303 }
1304 return true;
1305}
1306
1308 const char *str,
1309 size_t str_len,
1310 int location_x)
1311{
1312 /* Do not early exit if location_x <= 0, as this can result in an incorrect
1313 * offset for RTL text. Instead of offset of character responsible for first
1314 * glyph you'd get offset of first character, which could be the last glyph. */
1315 if (!str || !str[0] || !str_len) {
1316 return 0;
1317 }
1318
1320 data.location_x = location_x;
1321 data.r_offset = size_t(-1);
1322
1324
1325 if (data.r_offset == size_t(-1)) {
1326 /* We are to the right of the string, so return position of null terminator. */
1327 data.r_offset = BLI_strnlen(str, str_len);
1328 }
1329 else if (BLI_str_utf8_char_width_or_error(&str[data.r_offset]) == 0) {
1330 /* This is a combining character, so move to previous visible valid char. */
1331 int offset = int(data.r_offset);
1332 BLI_str_cursor_step_prev_utf8(str, int(str_len), &offset);
1333 data.r_offset = size_t(offset);
1334 }
1335
1336 return data.r_offset;
1337}
1338
1343
1344static bool blf_str_offset_foreach_glyph(const char * /*str*/,
1345 const size_t str_step_ofs,
1346 const rcti *bounds,
1347 void *user_data)
1348{
1350 if (data->str_offset == str_step_ofs) {
1351 data->bounds = *bounds;
1352 return false;
1353 }
1354 return true;
1355}
1356
1358 const char *str,
1359 size_t str_offset,
1360 rcti *r_glyph_bounds)
1361{
1363 data.str_offset = str_offset;
1364 data.bounds = {0};
1365
1367 *r_glyph_bounds = data.bounds;
1368}
1369
1371 const char *str,
1372 const size_t str_len,
1373 const size_t str_offset,
1374 const int cursor_width)
1375{
1376 if (!str || !str[0]) {
1377 return 0;
1378 }
1379
1380 /* Right edge of the previous character, if available. */
1381 rcti prev = {0};
1382 if (str_offset > 0) {
1383 blf_str_offset_to_glyph_bounds(font, str, str_offset - 1, &prev);
1384 }
1385
1386 /* Left edge of the next character, if available. */
1387 rcti next = {0};
1388 if (str_offset < strlen(str)) {
1389 blf_str_offset_to_glyph_bounds(font, str, str_offset, &next);
1390 }
1391
1392 if ((prev.xmax == prev.xmin) && next.xmax) {
1393 /* Nothing (or a space) to the left, so align to right character. */
1394 return next.xmin - (cursor_width / 2);
1395 }
1396 if ((prev.xmax != prev.xmin) && !next.xmax) {
1397 /* End of string, so align to last character. */
1398 return prev.xmax - (cursor_width / 2);
1399 }
1400 if (prev.xmax && next.xmax) {
1401 /* Between two characters, so use the center. */
1402 if (next.xmin >= prev.xmax || next.xmin == next.xmax) {
1403 return ((prev.xmax + next.xmin) - cursor_width) / 2;
1404 }
1405 /* A nicer center if reversed order - RTL. */
1406 return ((next.xmax + prev.xmin) - cursor_width) / 2;
1407 }
1408 if (!str_offset) {
1409 /* Start of string. */
1410 return 0 - cursor_width;
1411 }
1412 return int(blf_font_width(font, str, str_len, nullptr));
1413}
1414
1416 FontBLF *font, const char *str, size_t str_len, size_t sel_start, size_t sel_length)
1417{
1418 Vector<Bounds<int>> boxes;
1419 const int start = blf_str_offset_to_cursor(font, str, str_len, sel_start, 0);
1420 const int end = blf_str_offset_to_cursor(font, str, str_len, sel_start + sel_length, 0);
1421 boxes.append(Bounds(start, end));
1422 return boxes;
1423}
1424
1426
1427/* -------------------------------------------------------------------- */
1430
1441 const char *str,
1442 const size_t str_len,
1443 const int max_pixel_width,
1444 BLFWrapMode mode,
1445 ResultBLF *r_info,
1446 void (*callback)(FontBLF *font,
1447 GlyphCacheBLF *gc,
1448 const char *str,
1449 const size_t str_len,
1450 ft_pix pen_y,
1451 void *userdata),
1452 void *userdata)
1453{
1454 GlyphStepData step = {};
1455 const GlyphBLF *g_prev = nullptr;
1456 ft_pix pen_y = 0;
1457 ft_pix line_width = 0;
1458 int lines = 0;
1459
1460 /* Size of characters not shown at the end of the wrapped line. */
1461 size_t clip_bytes = 0;
1462
1463 ft_pix line_height = blf_font_height_max_ft_pix(font);
1464
1466
1467 struct WordWrapVars {
1468 ft_pix wrap_width;
1469 size_t start, last[2];
1470 } wrap = {max_pixel_width != -1 ? ft_pix_from_int(max_pixel_width) : INT_MAX, 0, {0, 0}};
1471
1472 // printf("%s wrapping (%d, %d) `%s`:\n", __func__, str_len, strlen(str), str);
1473 while ((step.i < str_len) && str[step.i]) {
1474
1475 /* Wrap variables. */
1476 const size_t i_curr = step.i;
1477 bool do_draw = false;
1478
1479 /* Step through even when the glyph is null (e.g. line feed), since control characters
1480 * like `\n` still drive wrapping. `step.i` is always advanced by `blf_glyph_step`. */
1481 blf_glyph_step(font, gc, step, str, str_len);
1482
1483 const uint codepoint = BLI_str_utf8_as_unicode_safe(&str[i_curr]);
1484 const uint codepoint_prev = g_prev ? g_prev->c : 0;
1485
1494 /* Ensure at least one character in the wrapped line.
1495 * Null glyphs (control characters) contribute no width so cannot cause overflow. */
1496 const bool overflows = (step.g != nullptr) && step.pen_x_right >= wrap.wrap_width &&
1497 step.pen_x != 0;
1498
1499 if (overflows && (wrap.start != wrap.last[0])) [[unlikely]] {
1500 do_draw = true;
1501 }
1502 else if (bool(mode & BLFWrapMode::HardLimit) && overflows && !blf_glyph_is_combining(step.g))
1503 [[unlikely]]
1504 {
1505 wrap.last[0] = i_curr;
1506 wrap.last[1] = i_curr;
1507 do_draw = true;
1508 clip_bytes = 0;
1509 }
1510 else if (((step.i < str_len) && str[step.i]) == 0) [[unlikely]] {
1511 /* Need check here for trailing newline, else we draw it. */
1512 wrap.last[0] = step.i + ((codepoint != '\n') ? 1 : 0);
1513 wrap.last[1] = step.i;
1514 do_draw = true;
1515 clip_bytes = 0;
1516 }
1517 else if (codepoint == '\n') [[unlikely]] {
1518 wrap.last[0] = i_curr + 1;
1519 wrap.last[1] = step.i;
1520 do_draw = true;
1521 clip_bytes = 1;
1522 }
1523 else if (codepoint != ' ' && (g_prev ? g_prev->c == ' ' : false)) [[unlikely]] {
1524 wrap.last[0] = i_curr;
1525 wrap.last[1] = i_curr;
1526 clip_bytes = 1;
1527 }
1528 else if (bool(mode & BLFWrapMode::Path)) [[unlikely]] {
1529 if (ELEM(codepoint, SEP, ' ', '?', '&', '=')) {
1530 /* Break and leave at the end of line. */
1531 wrap.last[0] = step.i;
1532 wrap.last[1] = step.i;
1533 clip_bytes = 0;
1534 }
1535 else if (ELEM(codepoint, '-', '_', '.', '%')) {
1536 /* Break and move to the next line. */
1537 wrap.last[0] = i_curr;
1538 wrap.last[1] = i_curr;
1539 clip_bytes = 0;
1540 }
1541 }
1542 else if (bool(mode & BLFWrapMode::Typographical) &&
1544 BLI_str_utf32_char_is_breaking_space(codepoint_prev)) [[unlikely]]
1545 {
1546 /* Optional break after space, removing it. */
1547 wrap.last[0] = i_curr;
1548 wrap.last[1] = i_curr;
1549 clip_bytes = BLI_str_utf8_from_unicode_len(codepoint_prev);
1550 }
1551 else if (bool(mode & BLFWrapMode::Typographical) &&
1552 BLI_str_utf32_char_is_optional_break_after(codepoint, codepoint_prev)) [[unlikely]]
1553 {
1554 /* Optional break after various characters, keeping it. */
1555 wrap.last[0] = step.i;
1556 wrap.last[1] = step.i;
1557 clip_bytes = 0;
1558 }
1559 else if (bool(mode & BLFWrapMode::Typographical) &&
1560 BLI_str_utf32_char_is_optional_break_before(codepoint, codepoint_prev)) [[unlikely]]
1561 {
1562 /* Optional break before various characters. */
1563 wrap.last[0] = i_curr;
1564 wrap.last[1] = i_curr;
1565 clip_bytes = 0;
1566 }
1567
1568 if (do_draw) [[unlikely]] {
1569#if 0
1570 printf("(%03d..%03d) `%.*s`\n",
1571 wrap.start,
1572 wrap.last[0],
1573 (wrap.last[0] - wrap.start) - 1,
1574 &str[wrap.start]);
1575#endif
1576
1577 callback(font,
1578 gc,
1579 &str[wrap.start],
1580 std::min(wrap.last[0] - wrap.start - clip_bytes, str_len - wrap.start),
1581 pen_y,
1582 userdata);
1583 line_width = step.pen_x_right;
1584 wrap.start = wrap.last[0];
1586 step.i = wrap.last[1];
1587 pen_y -= line_height;
1588 g_prev = nullptr;
1589 lines += 1;
1590 continue;
1591 }
1592
1593 g_prev = step.g;
1594 }
1595
1596 // printf("done! lines: %d, width, %d\n", lines, step.pen_x_right);
1597
1598 if (r_info) {
1599 r_info->lines = lines;
1600 /* Width of last line only (with wrapped lines). */
1601 r_info->width = ft_pix_to_int(line_width);
1602 }
1603
1605}
1606
1609 GlyphCacheBLF *gc,
1610 const char *str,
1611 const size_t str_len,
1612 ft_pix pen_y,
1613 void * /*userdata*/)
1614{
1615 blf_font_draw_ex(font, gc, str, str_len, nullptr, pen_y);
1616}
1617void blf_font_draw__wrap(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
1618{
1620 str,
1621 str_len,
1622 font->wrap_width,
1623 font->wrap_mode,
1624 r_info,
1626 nullptr);
1627}
1628
1631 GlyphCacheBLF *gc,
1632 const char *str,
1633 const size_t str_len,
1634 ft_pix pen_y,
1635 void *userdata)
1636{
1637 rcti *box = static_cast<rcti *>(userdata);
1638 rcti box_single;
1639
1640 blf_font_boundbox_ex(font, gc, str, str_len, &box_single, nullptr, pen_y);
1641 BLI_rcti_union(box, &box_single);
1642}
1644 FontBLF *font, const char *str, const size_t str_len, rcti *r_box, ResultBLF *r_info)
1645{
1646 r_box->xmin = 32000;
1647 r_box->xmax = -32000;
1648 r_box->ymin = 32000;
1649 r_box->ymax = -32000;
1650
1652 str,
1653 str_len,
1654 font->wrap_width,
1655 font->wrap_mode,
1656 r_info,
1658 r_box);
1659
1660 if (r_box->xmin > r_box->xmax) {
1661 r_box->xmin = 0;
1662 r_box->ymin = 0;
1663 r_box->xmax = 0;
1664 r_box->ymax = 0;
1665 }
1666}
1667
1670 GlyphCacheBLF *gc,
1671 const char *str,
1672 const size_t str_len,
1673 const ft_pix pen_y,
1674 void * /*userdata*/)
1675{
1676 blf_font_draw_buffer_ex(font, gc, str, str_len, pen_y, nullptr);
1677}
1679 const char *str,
1680 const size_t str_len,
1681 ResultBLF *r_info)
1682{
1684 str,
1685 str_len,
1686 font->wrap_width,
1687 font->wrap_mode,
1688 r_info,
1690 nullptr);
1691}
1692
1694static void blf_font_string_wrap_cb(FontBLF * /*font*/,
1695 GlyphCacheBLF * /*gc*/,
1696 const char *str,
1697 const size_t str_len,
1698 const ft_pix /*pen_y*/,
1699 void *str_list_ptr)
1700{
1701 Vector<StringRef> *list = static_cast<Vector<StringRef> *>(str_list_ptr);
1702 StringRef line(str, str + str_len);
1703 list->append(line);
1704}
1705
1707 StringRef str,
1708 int max_pixel_width,
1709 BLFWrapMode mode)
1710{
1713 str.data(),
1714 size_t(str.size()),
1715 max_pixel_width,
1716 mode,
1717 nullptr,
1719 &list);
1720 return list;
1721}
1722
1724
1725/* -------------------------------------------------------------------- */
1728
1730{
1731 std::lock_guard lock(ft_cache_size_mutex);
1732 blf_ensure_size(font);
1733 /* #Metrics::height is rounded to pixel. Force minimum of one pixel. */
1734 return std::max(ft_pix(font->ft_size->metrics.height), ft_pix_from_int(1));
1735}
1736
1738{
1740}
1741
1743{
1744 std::lock_guard lock(ft_cache_size_mutex);
1745 blf_ensure_size(font);
1746 /* #Metrics::max_advance is rounded to pixel. Force minimum of one pixel. */
1747 return std::max(ft_pix(font->ft_size->metrics.max_advance), ft_pix_from_int(1));
1748}
1749
1751{
1753}
1754
1756{
1757 std::lock_guard lock(ft_cache_size_mutex);
1758 blf_ensure_size(font);
1759 return ft_pix_to_int(ft_pix(font->ft_size->metrics.descender));
1760}
1761
1763{
1764 std::lock_guard lock(ft_cache_size_mutex);
1765 blf_ensure_size(font);
1766 return ft_pix_to_int(ft_pix(font->ft_size->metrics.ascender));
1767}
1768
1769bool blf_font_bounds_max(FontBLF *font, rctf *r_bounds)
1770{
1771 if (!blf_ensure_face(font)) {
1772 return false;
1773 }
1774
1775 r_bounds->xmin = float(font->face->bbox.xMin) / float(font->face->units_per_EM) * font->size;
1776 r_bounds->xmax = float(font->face->bbox.xMax) / float(font->face->units_per_EM) * font->size;
1777 r_bounds->ymin = float(font->face->bbox.yMin) / float(font->face->units_per_EM) * font->size;
1778 r_bounds->ymax = float(font->face->bbox.yMax) / float(font->face->units_per_EM) * font->size;
1779 return true;
1780}
1781
1783{
1784 if (!blf_ensure_face(font) || !font->face->family_name) {
1785 return nullptr;
1786 }
1787 return BLI_sprintfN("%s %s", font->face->family_name, font->face->style_name);
1788}
1789
1791
1792/* -------------------------------------------------------------------- */
1795
1797{
1798 memset(&g_batch, 0, sizeof(g_batch));
1799 int err = FT_Init_FreeType(&ft_lib);
1800 if (err == FT_Err_Ok) {
1801 /* Create a FreeType cache manager. */
1802 err = FTC_Manager_New(ft_lib,
1807 nullptr,
1808 &ftc_manager);
1809 if (err == FT_Err_Ok) {
1810 /* Create a character-map cache to speed up glyph index lookups. */
1811 err = FTC_CMapCache_New(ftc_manager, &ftc_charmap_cache);
1812 }
1813 }
1814 return err;
1815}
1816
1818{
1819 if (ftc_manager) {
1820 FTC_Manager_Done(ftc_manager);
1821 }
1822 if (ft_lib) {
1823 FT_Done_FreeType(ft_lib);
1824 }
1826}
1827
1828void BLF_cache_flush_set_fn(void (*cache_flush_fn)())
1829{
1830 blf_draw_cache_flush = cache_flush_fn;
1831}
1832
1834
1835/* -------------------------------------------------------------------- */
1838
1839static void blf_font_fill(FontBLF *font)
1840{
1841 font->aspect[0] = 1.0f;
1842 font->aspect[1] = 1.0f;
1843 font->aspect[2] = 1.0f;
1844 font->pos[0] = 0;
1845 font->pos[1] = 0;
1846 font->angle = 0.0f;
1847
1848 /* Use an easily identifiable bright color (yellow)
1849 * so its clear when #BLF_color calls are missing. */
1850 font->color[0] = 255;
1851 font->color[1] = 255;
1852 font->color[2] = 0;
1853 font->color[3] = 255;
1854
1855 font->clip_rec.xmin = 0;
1856 font->clip_rec.xmax = 0;
1857 font->clip_rec.ymin = 0;
1858 font->clip_rec.ymax = 0;
1859 font->flags = BLF_NONE;
1860 font->size = 0;
1861 font->char_weight = 400;
1862 font->char_slant = 0.0f;
1863 font->char_width = 1.0f;
1864 font->char_spacing = 0.0f;
1865
1866 font->kerning_cache = nullptr;
1867 font->tex_size_max = -1;
1868
1869 font->buf_info.fbuf = nullptr;
1870 font->buf_info.cbuf = nullptr;
1871 font->buf_info.dims[0] = 0;
1872 font->buf_info.dims[1] = 0;
1873 font->buf_info.channel_count = 4;
1874 font->buf_info.col_init[0] = 0;
1875 font->buf_info.col_init[1] = 0;
1876 font->buf_info.col_init[2] = 0;
1877 font->buf_info.col_init[3] = 0;
1878}
1879
1884static void blf_font_metrics(FT_Face face, FontMetrics *metrics)
1885{
1886 /* Members with non-zero defaults. */
1887 metrics->weight = 400;
1888 metrics->width = 1.0f;
1889
1890 const TT_OS2 *os2_table = static_cast<const TT_OS2 *>(FT_Get_Sfnt_Table(face, FT_SFNT_OS2));
1891 if (os2_table) {
1892 /* The default (resting) font weight. */
1893 if (os2_table->usWeightClass >= 1 && os2_table->usWeightClass <= 1000) {
1894 metrics->weight = short(os2_table->usWeightClass);
1895 }
1896
1897 /* Width value is one of integers 1-9 with known values. */
1898 if (os2_table->usWidthClass >= 1 && os2_table->usWidthClass <= 9) {
1899 switch (os2_table->usWidthClass) {
1900 case 1:
1901 metrics->width = 0.5f;
1902 break;
1903 case 2:
1904 metrics->width = 0.625f;
1905 break;
1906 case 3:
1907 metrics->width = 0.75f;
1908 break;
1909 case 4:
1910 metrics->width = 0.875f;
1911 break;
1912 case 5:
1913 metrics->width = 1.0f;
1914 break;
1915 case 6:
1916 metrics->width = 1.125f;
1917 break;
1918 case 7:
1919 metrics->width = 1.25f;
1920 break;
1921 case 8:
1922 metrics->width = 1.5f;
1923 break;
1924 case 9:
1925 metrics->width = 2.0f;
1926 break;
1927 }
1928 }
1929
1930 metrics->strikeout_position = short(os2_table->yStrikeoutPosition);
1931 metrics->strikeout_thickness = short(os2_table->yStrikeoutSize);
1932 metrics->subscript_size = short(os2_table->ySubscriptYSize);
1933 metrics->subscript_xoffset = short(os2_table->ySubscriptXOffset);
1934 metrics->subscript_yoffset = short(os2_table->ySubscriptYOffset);
1935 metrics->superscript_size = short(os2_table->ySuperscriptYSize);
1936 metrics->superscript_xoffset = short(os2_table->ySuperscriptXOffset);
1937 metrics->superscript_yoffset = short(os2_table->ySuperscriptYOffset);
1938 metrics->family_class = short(os2_table->sFamilyClass);
1939 metrics->selection_flags = short(os2_table->fsSelection);
1940 metrics->first_charindex = short(os2_table->usFirstCharIndex);
1941 metrics->last_charindex = short(os2_table->usLastCharIndex);
1942 if (os2_table->version > 1) {
1943 metrics->cap_height = short(os2_table->sCapHeight);
1944 metrics->x_height = short(os2_table->sxHeight);
1945 }
1946 }
1947
1948 /* The Post table usually contains a slant value, but in counter-clockwise degrees. */
1949 const TT_Postscript *post_table = static_cast<const TT_Postscript *>(
1950 FT_Get_Sfnt_Table(face, FT_SFNT_POST));
1951 if (post_table) {
1952 if (post_table->italicAngle != 0) {
1953 metrics->slant = float(post_table->italicAngle) / -65536.0f;
1954 }
1955 }
1956
1957 /* Metrics copied from those gathered by FreeType. */
1958 metrics->units_per_EM = short(face->units_per_EM);
1959 metrics->ascender = short(face->ascender);
1960 metrics->descender = short(face->descender);
1961 metrics->line_height = short(face->height);
1962 metrics->max_advance_width = short(face->max_advance_width);
1963 metrics->max_advance_height = short(face->max_advance_height);
1964 metrics->underline_position = short(face->underline_position);
1965 metrics->underline_thickness = short(face->underline_thickness);
1966 metrics->num_glyphs = int(face->num_glyphs);
1967
1968 if (metrics->cap_height == 0) {
1969 /* Calculate or guess cap height if it is not set in the font. */
1970 FT_UInt gi = FT_Get_Char_Index(face, uint('H'));
1971 if (gi && FT_Load_Glyph(face, gi, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP) == FT_Err_Ok) {
1972 metrics->cap_height = short(face->glyph->metrics.height);
1973 }
1974 else {
1975 metrics->cap_height = short(float(metrics->units_per_EM) * 0.7f);
1976 }
1977 }
1978
1979 if (metrics->x_height == 0) {
1980 /* Calculate or guess x-height if it is not set in the font. */
1981 FT_UInt gi = FT_Get_Char_Index(face, uint('x'));
1982 if (gi && FT_Load_Glyph(face, gi, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP) == FT_Err_Ok) {
1983 metrics->x_height = short(face->glyph->metrics.height);
1984 }
1985 else {
1986 metrics->x_height = short(float(metrics->units_per_EM) * 0.5f);
1987 }
1988 }
1989
1990 FT_UInt gi = FT_Get_Char_Index(face, uint('o'));
1991 if (gi && FT_Load_Glyph(face, gi, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP) == FT_Err_Ok) {
1992 metrics->o_proportion = float(face->glyph->metrics.width) / float(face->glyph->metrics.height);
1993 }
1994
1995 if (metrics->ascender == 0) {
1996 /* Set a sane value for ascender if not set in the font. */
1997 metrics->ascender = short(float(metrics->units_per_EM) * 0.8f);
1998 }
1999
2000 if (metrics->descender == 0) {
2001 /* Set a sane value for descender if not set in the font. */
2002 metrics->descender = metrics->ascender - metrics->units_per_EM;
2003 }
2004
2005 if (metrics->weight == 400 && face->style_flags & FT_STYLE_FLAG_BOLD) {
2006 /* Normal weight yet this is an bold font, so set a sane weight value. */
2007 metrics->weight = 700;
2008 }
2009
2010 if (metrics->slant == 0.0f && face->style_flags & FT_STYLE_FLAG_ITALIC) {
2011 /* No slant yet this is an italic font, so set a sane slant value. */
2012 metrics->slant = 8.0f;
2013 }
2014
2015 if (metrics->underline_position == 0) {
2016 metrics->underline_position = short(float(metrics->units_per_EM) * -0.2f);
2017 }
2018
2019 if (metrics->underline_thickness == 0) {
2020 metrics->underline_thickness = short(float(metrics->units_per_EM) * 0.07f);
2021 }
2022
2023 if (metrics->strikeout_position == 0) {
2024 metrics->strikeout_position = short(float(metrics->x_height) * 0.6f);
2025 }
2026
2027 if (metrics->strikeout_thickness == 0) {
2028 metrics->strikeout_thickness = metrics->underline_thickness;
2029 }
2030
2031 if (metrics->subscript_size == 0) {
2032 metrics->subscript_size = short(float(metrics->units_per_EM) * 0.6f);
2033 }
2034
2035 if (metrics->subscript_yoffset == 0) {
2036 metrics->subscript_yoffset = short(float(metrics->units_per_EM) * 0.075f);
2037 }
2038
2039 if (metrics->superscript_size == 0) {
2040 metrics->superscript_size = short(float(metrics->units_per_EM) * 0.6f);
2041 }
2042
2043 if (metrics->superscript_yoffset == 0) {
2044 metrics->superscript_yoffset = short(float(metrics->units_per_EM) * 0.35f);
2045 }
2046
2047 metrics->valid = true;
2048}
2049
2054static bool blf_setup_face(FontBLF *font)
2055{
2056 font->face_flags = font->face->face_flags;
2057
2058 if (FT_HAS_MULTIPLE_MASTERS(font) && !font->variations) {
2059 FT_Get_MM_Var(font->face, &(font->variations));
2060 }
2061
2062 if (!font->metrics.valid) {
2063 blf_font_metrics(font->face, &font->metrics);
2064 font->char_weight = font->metrics.weight;
2065 font->char_slant = font->metrics.slant;
2066 font->char_width = font->metrics.width;
2067 font->char_spacing = font->metrics.spacing;
2068 }
2069
2070 if (FT_IS_FIXED_WIDTH(font)) {
2071 font->flags |= BLF_MONOSPACED;
2072 }
2073
2074 if (FT_HAS_KERNING(font) && !font->kerning_cache) {
2075 /* Create kerning cache table and fill with value indicating "unset". */
2077 for (uint i = 0; i < KERNING_CACHE_TABLE_SIZE; i++) {
2078 for (uint j = 0; j < KERNING_CACHE_TABLE_SIZE; j++) {
2080 }
2081 }
2082 }
2083
2084 return true;
2085}
2086
2088{
2089 if (font->face) {
2090 return true;
2091 }
2092
2093 if (font->flags & BLF_BAD_FONT) {
2094 return false;
2095 }
2096
2097 FT_Error err = FTC_Manager_LookupFace(ftc_manager, font, &font->face);
2098
2099 if (err) {
2100 if (ELEM(err, FT_Err_Unknown_File_Format, FT_Err_Unimplemented_Feature)) {
2101 printf("Format of this font file is not supported\n");
2102 }
2103 else {
2104 printf("Error encountered while opening font file\n");
2105 }
2106 font->flags |= BLF_BAD_FONT;
2107 return false;
2108 }
2109
2110 if (font->face && !(font->face->face_flags & FT_FACE_FLAG_SCALABLE)) {
2111 printf("Font is not scalable\n");
2112 return false;
2113 }
2114
2115 err = FT_Select_Charmap(font->face, FT_ENCODING_UNICODE);
2116 if (err) {
2117 err = FT_Select_Charmap(font->face, FT_ENCODING_APPLE_ROMAN);
2118 }
2119 if (err && font->face->num_charmaps > 0) {
2120 err = FT_Select_Charmap(font->face, font->face->charmaps[0]->encoding);
2121 }
2122 if (err) {
2123 printf("Can't set a character map!\n");
2124 font->flags |= BLF_BAD_FONT;
2125 return false;
2126 }
2127
2128 if (font->filepath) {
2129 char *mfile = blf_dir_metrics_search(font->filepath);
2130 if (mfile) {
2131 err = FT_Attach_File(font->face, mfile);
2132 if (err) {
2133 fprintf(stderr,
2134 "FT_Attach_File failed to load '%s' with error %d\n",
2135 font->filepath,
2136 int(err));
2137 }
2138 MEM_delete(mfile);
2139 }
2140 }
2141
2142 /* Setup Font details that require having a Face. */
2143 return blf_setup_face(font);
2144}
2145
2153
2154/* Details about the fallback fonts we ship, so that we can load only when needed. */
2156 {"Noto Sans CJK Regular.woff2",
2157 TT_UCR_HANGUL_JAMO,
2158 TT_UCR_CJK_SYMBOLS | TT_UCR_HIRAGANA | TT_UCR_KATAKANA | TT_UCR_BOPOMOFO | TT_UCR_CJK_MISC |
2159 TT_UCR_ENCLOSED_CJK_LETTERS_MONTHS | TT_UCR_CJK_COMPATIBILITY |
2160 TT_UCR_CJK_UNIFIED_IDEOGRAPHS | TT_UCR_CJK_COMPATIBILITY_IDEOGRAPHS |
2161 TT_UCR_HANGUL_COMPATIBILITY_JAMO | TT_UCR_HANGUL,
2162 TT_UCR_CJK_COMPATIBILITY_FORMS | TT_UCR_HALFWIDTH_FULLWIDTH_FORMS,
2163 0},
2164 {"NotoEmoji-VariableFont_wght.woff2", 0x80000003L, 0x241E4ACL, 0x14000000L, 0x4000000L},
2165 {"NotoSansArabic-VariableFont_wdth,wght.woff2",
2166 TT_UCR_ARABIC,
2167 uint(TT_UCR_ARABIC_PRESENTATION_FORMS_A),
2168 TT_UCR_ARABIC_PRESENTATION_FORMS_B,
2169 0},
2170 {"NotoSansArmenian-VariableFont_wdth,wght.woff2", TT_UCR_ARMENIAN, 0, 0, 0},
2171 {"NotoSansBengali-VariableFont_wdth,wght.woff2", TT_UCR_BENGALI, 0, 0, 0},
2172 {"NotoSansDevanagari-Regular.woff2", TT_UCR_DEVANAGARI, 0, 0, 0},
2173 {"NotoSansEthiopic-Regular.woff2", 0, 0, TT_UCR_ETHIOPIC, 0},
2174 {"NotoSansGeorgian-VariableFont_wdth,wght.woff2", TT_UCR_GEORGIAN, 0, 0, 0},
2175 {"NotoSansGujarati-Regular.woff2", TT_UCR_GUJARATI, 0, 0, 0},
2176 {"NotoSansGurmukhi-VariableFont_wdth,wght.woff2", TT_UCR_GURMUKHI, 0, 0, 0},
2177 {"NotoSansHebrew-Regular.woff2", TT_UCR_HEBREW, 0, 0, 0},
2178 {"NotoSansJavanese-Regular.woff2", 0x80000003L, 0x2000L, 0, 0},
2179 {"NotoSansKannada-VariableFont_wdth,wght.woff2", TT_UCR_KANNADA, 0, 0, 0},
2180 {"NotoSansKhmer-VariableFont_wdth,wght.woff2", 0, 0, TT_UCR_KHMER, 0},
2181 {"NotoSansMalayalam-VariableFont_wdth,wght.woff2", TT_UCR_MALAYALAM, 0, 0, 0},
2182 {"NotoSansMath-Regular.woff2", 0, TT_UCR_MATHEMATICAL_OPERATORS, 0, 0},
2183 {"NotoSansMyanmar-Regular.woff2", 0, 0, TT_UCR_MYANMAR, 0},
2184 {"NotoSansSymbols-VariableFont_wght.woff2", 0x3L, 0x200E4B4L, 0, 0},
2185 {"NotoSansSymbols2-Regular.woff2", 0x80000003L, 0x200E3E4L, 0x40020L, 0x580A048L},
2186 {"NotoSansTamil-VariableFont_wdth,wght.woff2", TT_UCR_TAMIL, 0, 0, 0},
2187 {"NotoSansTelugu-VariableFont_wdth,wght.woff2", TT_UCR_TELUGU, 0, 0, 0},
2188 {"NotoSansThai-VariableFont_wdth,wght.woff2", TT_UCR_THAI, 0, 0, 0},
2189};
2190
2194static FontBLF *blf_font_new_impl(const char *filepath,
2195 const char *mem_name,
2196 const uchar *mem,
2197 const size_t mem_size)
2198{
2199 FontBLF *font = MEM_new<FontBLF>(__func__);
2200
2201 font->mem_name = mem_name ? BLI_strdup(mem_name) : nullptr;
2202 font->filepath = filepath ? BLI_strdup(filepath) : nullptr;
2203 if (mem) {
2204 font->mem = mem;
2205 font->mem_size = mem_size;
2206 }
2207 blf_font_fill(font);
2208 font->ft_lib = ft_lib;
2209
2210 /* If we have static details about this font file, we don't have to load the Face yet. */
2211 bool face_needed = true;
2212
2213 if (font->filepath) {
2214 const char *filename = BLI_path_basename(font->filepath);
2215 for (int i = 0; i < int(ARRAY_SIZE(static_face_details)); i++) {
2217 const FaceDetails *static_details = &static_face_details[i];
2218 font->unicode_ranges[0] = static_details->coverage1;
2219 font->unicode_ranges[1] = static_details->coverage2;
2220 font->unicode_ranges[2] = static_details->coverage3;
2221 font->unicode_ranges[3] = static_details->coverage4;
2222 face_needed = false;
2223 break;
2224 }
2225 }
2226 }
2227
2228 if (face_needed) {
2229 if (!blf_ensure_face(font)) {
2230 blf_font_free(font);
2231 return nullptr;
2232 }
2233
2234 /* Save TrueType table with bits to quickly test most unicode block coverage. */
2235 const TT_OS2 *os2_table = static_cast<const TT_OS2 *>(
2236 FT_Get_Sfnt_Table(font->face, FT_SFNT_OS2));
2237 if (os2_table) {
2238 font->unicode_ranges[0] = uint(os2_table->ulUnicodeRange1);
2239 font->unicode_ranges[1] = uint(os2_table->ulUnicodeRange2);
2240 font->unicode_ranges[2] = uint(os2_table->ulUnicodeRange3);
2241 font->unicode_ranges[3] = uint(os2_table->ulUnicodeRange4);
2242 }
2243 }
2244
2245 /* Detect "Last resort" fonts. They have everything. Usually except last 5 bits. */
2246 if (font->unicode_ranges[0] == 0xffffffffU && font->unicode_ranges[1] == 0xffffffffU &&
2247 font->unicode_ranges[2] == 0xffffffffU && font->unicode_ranges[3] >= 0x7FFFFFFU)
2248 {
2249 font->flags |= BLF_LAST_RESORT;
2250 }
2251
2252 return font;
2253}
2254
2256{
2257 return blf_font_new_impl(filepath, nullptr, nullptr, 0);
2258}
2259
2260FontBLF *blf_font_new_from_mem(const char *mem_name, const uchar *mem, const size_t mem_size)
2261{
2262 return blf_font_new_impl(nullptr, mem_name, mem, mem_size);
2263}
2264
2265void blf_font_attach_from_mem(FontBLF *font, const uchar *mem, const size_t mem_size)
2266{
2267 FT_Open_Args open;
2268
2269 open.flags = FT_OPEN_MEMORY;
2270 open.memory_base = static_cast<const FT_Byte *>(mem);
2271 open.memory_size = FT_Long(mem_size);
2272 if (blf_ensure_face(font)) {
2273 FT_Attach_Stream(font->face, &open);
2274 }
2275}
2276
2278{
2280
2281 if (font->kerning_cache) {
2282 MEM_delete(font->kerning_cache);
2283 }
2284
2285 if (font->variations) {
2286 FT_Done_MM_Var(font->ft_lib, font->variations);
2287 }
2288
2289 if (font->face) {
2290 std::scoped_lock lock(ft_face_load_mutex);
2291 FTC_Manager_RemoveFaceID(ftc_manager, font);
2292 font->face = nullptr;
2293 }
2294 if (font->filepath) {
2295 MEM_delete(font->filepath);
2296 }
2297 if (font->mem_name) {
2298 MEM_delete(font->mem_name);
2299 }
2300
2301 MEM_delete(font);
2302}
2303
2305
2306/* -------------------------------------------------------------------- */
2309
2311{
2312 if (font->ft_size) {
2313 return;
2314 }
2315
2316 FTC_ScalerRec scaler = {nullptr};
2317 scaler.face_id = font;
2318 scaler.width = 0;
2319 scaler.height = round_fl_to_uint(font->size * 64.0f);
2320 scaler.pixel = 0;
2321 scaler.x_res = BLF_DPI;
2322 scaler.y_res = BLF_DPI;
2323 if (FTC_Manager_LookupSize(ftc_manager, &scaler, &font->ft_size) == FT_Err_Ok) {
2324 font->ft_size->generic.data = static_cast<void *>(font);
2325 font->ft_size->generic.finalizer = blf_size_finalizer;
2326 return;
2327 }
2328
2330}
2331
2332bool blf_font_size(FontBLF *font, float size)
2333{
2334 if (!blf_ensure_face(font)) {
2335 return false;
2336 }
2337
2338 /* FreeType uses fixed-point integers in 64ths. */
2339 FT_UInt ft_size = round_fl_to_uint(size * 64.0f);
2340 /* Adjust our new size to be on even 64ths. */
2341 size = float(ft_size) / 64.0f;
2342
2343 if (font->size != size) {
2344 std::lock_guard lock(ft_cache_size_mutex);
2345 FTC_ScalerRec scaler = {nullptr};
2346 scaler.face_id = font;
2347 scaler.width = 0;
2348 scaler.height = ft_size;
2349 scaler.pixel = 0;
2350 scaler.x_res = BLF_DPI;
2351 scaler.y_res = BLF_DPI;
2352 if (FTC_Manager_LookupSize(ftc_manager, &scaler, &font->ft_size) != FT_Err_Ok) {
2353 return false;
2354 }
2355 font->ft_size->generic.data = static_cast<void *>(font);
2356 font->ft_size->generic.finalizer = blf_size_finalizer;
2357 }
2358
2359 font->size = size;
2360 return true;
2361}
2362
2364
2365} // namespace blender
#define BLI_path_cmp
#define BLI_UTF8_ERR
#define GPU_batch_texture_bind(batch, name, tex)
Definition GPU_batch.hh:284
#define GPU_BATCH_DISCARD_SAFE(batch)
Definition GPU_batch.hh:199
#define GPU_batch_uniform_1i(batch, name, x)
Definition GPU_batch.hh:265
Read Blender memory allocation and freeing.
volatile int lock
#define BLI_assert_unreachable()
#define BLI_INLINE
#define UNLIKELY(x)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define BLF_CACHE_BYTES
#define BLF_CACHE_MAX_FACES
#define BLF_CACHE_MAX_SIZES
#define BLF_DPI
#define FT_PIX_ROUND(x)
#define KERNING_CACHE_TABLE_SIZE
#define KERNING_ENTRY_UNSET
btMatrix3x3 scaled(const btVector3 &s) const
Create a scaled copy of the matrix.
int64_t size() const
Definition BLI_array.hh:267
const T * data() const
Definition BLI_array.hh:323
void append(const T &value)
#define str(s)
#define INT_MAX
VecBase< float, D > step(VecOp< float, D >, VecOp< float, D >) RET
TEX_TEMPLATE DataVec texture(T, FltCoord, float=0.0f) RET
std::string filename(const std::string_view &str, size_t pos)
BLI_INLINE Texture * wrap(MTLTexture *texture)
BMesh Iterators.
void * MEM_new_uninitialized(size_t len, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1) ATTR_NONNULL(2)
int blf_font_height_max(FontBLF *font)
Definition blf_font.cc:1737
MINLINE unsigned int round_fl_to_uint(float a)
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
void GPU_storagebuf_update(gpu::StorageBuf *ssbo, const void *data)
static void blf_font_fill(FontBLF *font)
Definition blf_font.cc:1839
__int64 int64_t
Definition BKE_text.h:90
gpu::Batch * GPU_batch_create_procedural(GPUPrimType primitive_type, int32_t vertex_count)
Definition gpu_batch.cc:85
void blf_font_width_and_height(FontBLF *font, const char *str, const size_t str_len, float *r_width, float *r_height, ResultBLF *r_info)
Definition blf_font.cc:1126
MINLINE unsigned char unit_float_to_uchar_clamp(float val)
bool BLI_str_utf32_char_is_breaking_space(char32_t codepoint)
ptrdiff_t BLI_str_utf8_invalid_byte(const char *str, size_t str_len) ATTR_NONNULL(1)
static Mutex ft_face_load_mutex
Definition blf_font.cc:69
bool blf_ensure_face(FontBLF *font)
Definition blf_font.cc:2087
ft_pix ft_pix_from_int(int v)
unsigned int uint
Definition BKE_text.h:55
MINLINE void blend_color_mix_float(float dst[4], const float src1[4], const float src2[4])
static gpu::Texture * blf_batch_cache_texture_load()
Definition blf_font.cc:267
void blf_glyph_cache_release(FontBLF *font)
Definition blf_glyph.cc:145
BLI_INLINE bool blf_glyph_is_combining(const GlyphBLF *g)
Definition blf_font.cc:435
void blf_font_draw_buffer__wrap(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:1678
char * blf_dir_metrics_search(const char *filepath)
Definition blf_dir.cc:28
gpu::StorageBuf * GPU_storagebuf_create_ex(size_t size, const void *data, GPUUsageType usage, const char *name)
unsigned int BLI_str_utf8_as_unicode_safe(const char *p) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
uint blf_get_char_index(FontBLF *font, const uint charcode)
Definition blf_font.cc:155
static void blf_batch_draw_init()
Definition blf_font.cc:190
int blf_font_draw_mono(FontBLF *font, const char *str, const size_t str_len, const int char_width, const int tab_columns)
Definition blf_font.cc:632
float blf_font_fixed_width(FontBLF *font)
Definition blf_font.cc:1197
void blf_ensure_size(FontBLF *font)
Definition blf_font.cc:2310
MINLINE void blend_color_mix_byte(unsigned char dst[4], const unsigned char src1[4], const unsigned char src2[4])
BatchBLF g_batch
Definition blf_font.cc:61
Vector< Bounds< int > > blf_str_selection_boxes(FontBLF *font, const char *str, size_t str_len, size_t sel_start, size_t sel_length)
Definition blf_font.cc:1415
char * BLI_sprintfN(const char *__restrict format,...) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC ATTR_PRINTF_FORMAT(1
static void blf_font_boundbox_wrap_cb(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, ft_pix pen_y, void *userdata)
Definition blf_font.cc:1630
void blf_font_free(FontBLF *font)
Definition blf_font.cc:2277
static bool blf_cursor_position_foreach_glyph(const char *, const size_t str_step_ofs, const rcti *bounds, void *user_data)
Definition blf_font.cc:1293
void GPU_storagebuf_usage_size_set(gpu::StorageBuf *ssbo, size_t size)
@ GPU_PRIM_TRI_STRIP
static void blf_font_wrap_apply(FontBLF *font, const char *str, const size_t str_len, const int max_pixel_width, BLFWrapMode mode, ResultBLF *r_info, void(*callback)(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, ft_pix pen_y, void *userdata), void *userdata)
Definition blf_font.cc:1440
void blf_glyph_draw(FontBLF *font, GlyphCacheBLF *gc, GlyphBLF *g, const int x, const int y)
void blf_font_boundbox(FontBLF *font, const char *str, const size_t str_len, rcti *r_box, ResultBLF *r_info)
Definition blf_font.cc:1118
static FTC_Manager ftc_manager
Definition blf_font.cc:65
static bool blf_setup_face(FontBLF *font)
Definition blf_font.cc:2054
void blf_font_boundbox__wrap(FontBLF *font, const char *str, const size_t str_len, rcti *r_box, ResultBLF *r_info)
Definition blf_font.cc:1643
static FontBLF * blf_font_new_impl(const char *filepath, const char *mem_name, const uchar *mem, const size_t mem_size)
Definition blf_font.cc:2194
static void blf_font_metrics(FT_Face face, FontMetrics *metrics)
Definition blf_font.cc:1884
void BLF_cache_flush_set_fn(void(*cache_flush_fn)())
Definition blf_font.cc:1828
unsigned int BLI_str_utf8_as_unicode_step_safe(const char *__restrict p, size_t p_len, size_t *__restrict index) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
static ft_pix blf_font_width_max_ft_pix(FontBLF *font)
Definition blf_font.cc:1742
static void blf_font_draw_buffer_ex(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, const ft_pix pen_y, ResultBLF *r_info)
Definition blf_font.cc:899
BLI_INLINE ft_pix blf_kerning(FontBLF *font, const GlyphBLF *g_prev, const GlyphBLF *g)
Definition blf_font.cc:363
@ GPU_BLEND_NONE
Definition GPU_state.hh:88
@ GPU_BLEND_ALPHA
Definition GPU_state.hh:90
float blf_font_height(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:1176
void blf_font_info_foreach_glyph(FontBLF *font, const char *str, size_t str_len, FunctionRef< void(int index, size_t byte_offset, int byte_len, int advance_x)> callback)
Definition blf_font.cc:1260
void blf_str_offset_to_glyph_bounds(FontBLF *font, const char *str, size_t str_offset, rcti *r_glyph_bounds)
Definition blf_font.cc:1357
Vector< StringRef > blf_font_string_wrap(FontBLF *font, StringRef str, int max_pixel_width, BLFWrapMode mode)
Definition blf_font.cc:1706
static ft_pix blf_font_height_max_ft_pix(FontBLF *font)
Definition blf_font.cc:1729
static FT_Library ft_lib
Definition blf_font.cc:64
size_t blf_font_width_to_strlen(FontBLF *font, const char *str, const size_t str_len, int width, int *r_width)
Definition blf_font.cc:981
void GPU_texture_update_sub(gpu::Texture *texture, eGPUDataFormat data_format, const void *pixels, int offset_x, int offset_y, int offset_z, int width, int height, int depth, uint unpack_row_length=0)
static bool blf_str_offset_foreach_glyph(const char *, const size_t str_step_ofs, const rcti *bounds, void *user_data)
Definition blf_font.cc:1344
void void void const char * BLI_path_basename(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
static FTC_CMapCache ftc_charmap_cache
Definition blf_font.cc:66
void blf_font_draw_buffer(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:930
BLI_INLINE int BLI_rcti_size_y(const struct rcti *rct)
Definition BLI_rect.hh:207
FontBLF * blf_font_new_from_mem(const char *mem_name, const uchar *mem, const size_t mem_size)
Definition blf_font.cc:2260
GlyphCacheBLF * blf_glyph_cache_acquire(FontBLF *font)
Definition blf_glyph.cc:132
unsigned char uchar
Definition BKE_text.h:58
int blf_font_descender(FontBLF *font)
Definition blf_font.cc:1755
bool blf_font_bounds_max(FontBLF *font, rctf *r_bounds)
Definition blf_font.cc:1769
BMesh const char void * data
int blf_font_glyph_advance(FontBLF *font, const char *str)
Definition blf_font.cc:1205
int blf_str_offset_to_cursor(FontBLF *font, const char *str, const size_t str_len, const size_t str_offset, const int cursor_width)
Definition blf_font.cc:1370
bool BLI_str_utf32_char_is_optional_break_after(char32_t codepoint, char32_t codepoint_prev)
bool BLI_str_utf32_char_is_optional_break_before(char32_t codepoint, char32_t codepoint_prev)
BLI_INLINE GlyphBLF * blf_glyph_from_utf8_and_step(FontBLF *font, GlyphCacheBLF *gc, const GlyphBLF *g_prev, const char *str, const size_t str_len, size_t *i_p, int32_t *pen_x)
Definition blf_font.cc:398
FontBLF * blf_font_new_from_filepath(const char *filepath)
Definition blf_font.cc:2255
BLI_INLINE bool blf_glyph_step(FontBLF *font, GlyphCacheBLF *gc, GlyphStepData &step, const char *str, const size_t str_len)
Definition blf_font.cc:469
int BLI_str_utf8_char_width_or_error(const char *p) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
void BLI_rcti_union(struct rcti *rct_a, const struct rcti *rct_b)
int GPU_texture_width(const gpu::Texture *texture)
bool(*)(const char *str, size_t str_step_ofs, const rcti *bounds, void *user_dataconst) BLF_GlyphBoundsFn
Definition BLF_api.hh:211
static void blf_size_finalizer(void *object)
Definition blf_font.cc:142
void blf_font_draw__wrap(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:1617
constexpr size_t ARRAY_SIZE(const T(&arg)[N]) noexcept
static bool blf_font_width_to_strlen_glyph_process(FontBLF *font, GlyphCacheBLF *gc, const GlyphBLF *g_prev, GlyphBLF *g, ft_pix *pen_x, const int width_i)
Definition blf_font.cc:947
int char char int int int int size_t BLI_strnlen(const char *str, size_t maxlen) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
bool equals_m4m4(const float mat1[4][4], const float mat2[4][4])
bool BLI_str_cursor_step_prev_utf8(const char *str, int str_maxlen, int *pos)
static Mutex ft_cache_size_mutex
Definition blf_font.cc:75
int BLI_str_utf8_size_safe(const char *p) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1)
void GPU_storagebuf_bind(gpu::StorageBuf *ssbo, int slot)
int blf_font_init()
Definition blf_font.cc:1796
GlyphBLF * blf_glyph_ensure(FontBLF *font, GlyphCacheBLF *gc, const uint charcode, uint8_t subpixel)
BLI_INLINE int BLI_rcti_size_x(const struct rcti *rct)
Definition BLI_rect.hh:203
GlyphBLF * blf_glyph_ensure_icon(GlyphCacheBLF *gc, const uint icon_id, bool color, FunctionRef< void(std::string &)> edit_source_cb)
void blf_font_draw(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:625
void GPU_batch_program_set_builtin(gpu::Batch *batch, GPUBuiltinShader shader_id)
void blf_font_boundbox_foreach_glyph(FontBLF *font, const char *str, const size_t str_len, BLF_GlyphBoundsFn user_fn, void *user_data)
Definition blf_font.cc:1222
static void blf_glyph_draw_buffer(FontBufInfoBLF *buf_info, GlyphBLF *g, const ft_pix pen_x, const ft_pix pen_y_basis)
Definition blf_font.cc:764
int ft_pix_to_int_ceil(ft_pix v)
size_t blf_str_offset_from_cursor_position(FontBLF *font, const char *str, size_t str_len, int location_x)
Definition blf_font.cc:1307
ft_pix ft_pix_from_float(float v)
static void blf_font_draw_buffer__wrap_cb(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, const ft_pix pen_y, void *)
Definition blf_font.cc:1669
int blf_font_width_max(FontBLF *font)
Definition blf_font.cc:1750
static ft_pix blf_unscaled_F26Dot6_to_pixels(FontBLF *font, const FT_Pos value)
Definition blf_font.cc:161
static void blf_font_draw__wrap_cb(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, ft_pix pen_y, void *)
Definition blf_font.cc:1608
const char * BLI_str_find_prev_char_utf8(const char *p, const char *str_start) ATTR_WARN_UNUSED_RESULT ATTR_RETURNS_NONNULL ATTR_NONNULL(1
MINLINE void zero_v2_int(int r[2])
static void blf_font_string_wrap_cb(FontBLF *, GlyphCacheBLF *, const char *str, const size_t str_len, const ft_pix, void *str_list_ptr)
Definition blf_font.cc:1694
char * BLI_strdup(const char *str) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1) ATTR_MALLOC
static FT_Error blf_cache_face_requester(FTC_FaceID faceID, FT_Library lib, FT_Pointer, FT_Face *face)
Definition blf_font.cc:104
static void blf_font_boundbox_ex(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, rcti *r_box, ResultBLF *r_info, ft_pix pen_y)
Definition blf_font.cc:1066
std::mutex Mutex
Definition BLI_mutex.hh:51
void blf_draw_svg_icon(FontBLF *font, const uint icon_id, const float size, const float color[4], const float outline_alpha, const bool multicolor, FunctionRef< void(std::string &)> edit_source_cb)
Definition blf_font.cc:671
int BLI_wcwidth_safe(char32_t ucs) ATTR_WARN_UNUSED_RESULT
signed int int32_t
Definition BKE_text.h:78
Array< uchar > blf_svg_icon_bitmap(FontBLF *font, const uint icon_id, const float size, int *r_width, int *r_height, const bool multicolor, FunctionRef< void(std::string &)> edit_source_cb)
Definition blf_font.cc:713
unsigned int unsigned int size_t BLI_str_utf8_from_unicode_len(unsigned int c) ATTR_WARN_UNUSED_RESULT
size_t blf_font_width_to_rstrlen(FontBLF *font, const char *str, const size_t str_len, int width, int *r_width)
Definition blf_font.cc:1010
void GPU_batch_draw_advanced(gpu::Batch *batch, int vertex_first, int vertex_count, int instance_first, int instance_count)
void GPU_texture_unbind(gpu::Texture *texture)
int ft_pix_to_int(ft_pix v)
void GPU_blend(GPUBlend blend)
Definition gpu_state.cc:44
void blf_batch_draw_begin(FontBLF *font)
Definition blf_font.cc:207
bool blf_font_size(FontBLF *font, float size)
Definition blf_font.cc:2332
MINLINE int is_power_of_2_i(int n)
MINLINE int bitscan_reverse_i(int a)
static void blf_font_draw_ex(FontBLF *font, GlyphCacheBLF *gc, const char *str, const size_t str_len, ResultBLF *r_info, const ft_pix pen_y)
Definition blf_font.cc:590
constexpr char SEP
void GPU_storagebuf_free(gpu::StorageBuf *ssbo)
void blf_glyph_cache_clear(FontBLF *font)
Definition blf_glyph.cc:161
void GPU_matrix_pop()
static void blf_batch_draw_exit()
Definition blf_font.cc:199
float blf_font_width(FontBLF *font, const char *str, const size_t str_len, ResultBLF *r_info)
Definition blf_font.cc:1155
static void blf_face_finalizer(void *object)
Definition blf_font.cc:92
void blf_font_attach_from_mem(FontBLF *font, const uchar *mem, const size_t mem_size)
Definition blf_font.cc:2265
void GPU_matrix_set(const float m[4][4])
static const FaceDetails static_face_details[]
Definition blf_font.cc:2155
void blf_batch_draw()
Definition blf_font.cc:307
int ft_pix_to_int_floor(ft_pix v)
GlyphBLF * blf_glyph_ensure_subpixel(FontBLF *font, GlyphCacheBLF *gc, GlyphBLF *g, int32_t pen_x)
static void blf_batch_draw_end()
Definition blf_font.cc:341
@ BLF_RENDER_SUBPIXELAA
Definition BLF_enums.hh:63
@ BLF_SHADOW
Definition BLF_enums.hh:38
@ BLF_ASPECT
Definition BLF_enums.hh:41
@ BLF_LAST_RESORT
Definition BLF_enums.hh:55
@ BLF_ROTATION
Definition BLF_enums.hh:36
@ BLF_BAD_FONT
Definition BLF_enums.hh:57
@ BLF_WORD_WRAP
Definition BLF_enums.hh:42
@ BLF_MONOSPACED
Definition BLF_enums.hh:51
void BLF_batch_discard()
Definition blf_font.cc:348
void GPU_matrix_push()
void blf_font_exit()
Definition blf_font.cc:1817
static int blf_str_is_utf8_valid_lazy_init(const char *str, const size_t str_len, int &is_utf8_valid)
Definition blf_font.cc:574
MINLINE void rgba_float_to_uchar(unsigned char r_col[4], const float col_f[4])
static void(*) blf_draw_cache_flush()
Definition blf_font.cc:78
BLI_INLINE void blf_glyph_step_reset_for_newline(GlyphStepData &step)
Definition blf_font.cc:553
int blf_font_ascender(FontBLF *font)
Definition blf_font.cc:1762
char * blf_display_name(FontBLF *font)
Definition blf_font.cc:1782
const float(* GPU_matrix_model_view_get(float m[4][4]))[4]
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
GlyphCacheBLF * glyph_cache
GlyphQuad glyph_data[BLF_BATCH_DRAW_LEN_MAX]
gpu::StorageBuf * glyph_buf
Bounds()=default
unsigned char shadow_color[4]
FontBufInfoBLF buf_info
unsigned char color[4]
KerningCacheBLF * kerning_cache
const GlyphBLF * g_kerning
Definition blf_font.cc:448
int ascii_table[KERNING_CACHE_TABLE_SIZE][KERNING_CACHE_TABLE_SIZE]