Commit Graph
955 Commits
Author SHA1 Message Date
Sai Asish Y cce964cb4f [ot-tag] guard against NULL language in hb_ot_tags_to_script_and_language (#6085)
hb_ot_tag_to_language returns NULL for HB_OT_TAG_DEFAULT_LANGUAGE, and hb_language_to_string returns NULL for it, so the script-suffix path called strlen on a NULL pointer whenever the primary script tag did not match the input. Skip the suffix construction when there is no base language string and leave the default (NULL) language in place.

Signed-off-by: Sai Asish Y <say.apm35@gmail.com>
2026-07-21 18:47:36 -06:00
nussaibah shaikh 53900fd388 [gpu] bound clip depth in push_clip_path_end (#6073)
push_clip_path_end wrote clip_stack[clip_depth] without the
HB_GPU_PAINT_MAX_CLIP_DEPTH check that push_clip_glyph and
push_clip_path_start both apply. clip_depth can be pushed past
the fixed 3-entry clip_stack, so closing a clip path while the
stack is full writes a pending_clip_t past the array. Guard it
like the sibling clip pushes.
2026-07-21 18:45:53 -06:00
nussaibah shaikh 387ab23f7f [raster] Reject non-finite texel coords in hb_raster_paint_image (#6082)
The range test guarding the bilinear sampler is comparison-based, so NaN
coordinates pass it and reach (int) floorf() in
hb_raster_sample_bilinear_premul, where only x1/y1 are clamped.  The
determinant guard has the same shape, so a transform that overflows to
infinity is accepted and 1/inf turns inf * 0 into NaN.
2026-07-21 18:40:41 -06:00
Nussu06 9de7e9d563 [paint] pass color_glyph its own user_data
The dispatch wrapper handed the callback user_data->push_clip_glyph
instead of user_data->color_glyph, so a client registering both
callbacks with different contexts got the wrong pointer on every
COLR glyph.
2026-07-17 11:43:34 -06:00
Garret Rieger d7861576ae More fixes for review comments. 2026-07-14 16:26:49 -06:00
Garret Rieger 2725565dab Address review comments. 2026-07-14 16:26:49 -06:00
Garret Rieger 99380f0e44 Add new hb_subset_input_to_command_line_or_fail().
This generates an equivalent hb-subset command line string for a given subset input.

Assisted by gemini.
2026-07-14 16:26:49 -06:00
Behdad Esfahbod 4fbbe7ae4f [ot-font] Invalidate vertical origin cache on scale change
The vertical-origin cache stores scaled y-origin values, but it was
validated against serial_coords. Changing only the font scale leaves
serial_coords unchanged, so hb_font_set_scale() could keep serving stale
vertical origins.

Validate scale-dependent OT font caches against the full font serial and
check that serial before using the batched vertical-origin callback. Add
an API regression that changes y_scale on one font and verifies the
vertical origin is recomputed.

Testing:
meson compile -C build test/api/test-ot-face
meson test -C build test-ot-face --print-errorlogs
meson test -C build --suite api --print-errorlogs

Fixes: https://github.com/harfbuzz/harfbuzz/issues/6066
Assisted-by: OpenAI Codex
2026-07-14 14:02:38 -06:00
Khaled Hosny e2588968ae [COLR] Emit fill_glyph for glyph clips with a solid paint
Detect the fill-glyph pattern in the COLRv1 graph: a PaintGlyph whose
child is a (Var)PaintSolid, and emit a single fill_glyph instead of
push_clip_glyph + color + pop_clip.
2026-07-12 22:20:21 +03:00
Khaled Hosny b4ed968183 [test/paint] Test the fill_path callback 2026-07-12 19:36:15 +03:00
Behdad Esfahbod d287ee3ee2 [ft] Fix get_table_tags returning no tags on streaming faces
_hb_ft_get_table_tags() (used for FT faces created over a custom stream,
i.e. when ft_face->stream->read is set) did

    if (!table_count) return population;
    else *table_count = 0;
    ...
    end_offset = hb_min (start_offset + *table_count, population);

zeroing *table_count before using it as the requested buffer size, so
end_offset collapsed to start_offset, the copy loop never ran, and
hb_face_get_table_tags() always reported zero tags (and wrote none).

Restructure to match the CoreText / face-builder / default backends: keep
the caller's *table_count, check the start_offset + *table_count sum for
overflow, clamp to the table population, then copy.  Also guard the copy
on table_tags so a NULL output array (count-only query) is handled.

The existing FT test used FT_New_Memory_Face, whose in-memory face routes
through the default blob table-tags path and never exercised this
callback.  Add a streaming-face variant (FT_Open_Face with a read stream)
that does; it failed (count 0 vs 3) before this fix.

Assisted-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 01:08:45 -06:00
Behdad Esfahbod 706a2ba8d3 [ot] Guard remaining list-getter output arrays against NULL
Following GHSA-v5mv-8hhw-vff8, sweep the rest of the public "list getter"
APIs for the same defect: a NULL output array passed with a non-NULL count
on a populated table wrote through the NULL pointer and crashed (SIGSEGV).
These output params are not all annotated nullable, but the crash is
reachable from public C APIs and is a straightforward DoS, so guard the
write on the output pointer consistently (matching hb_color_line_get_color_stops
and the fixes in the previous two commits).  When the output is NULL the
getter now just returns the total count.

Getters hardened:

  - MathKern::get_entries              (hb_ot_math_get_glyph_kernings)
  - MathGlyphAssembly::get_parts       (hb_ot_math_get_glyph_assembly)
  - MathGlyphConstruction::get_variants (hb_ot_math_get_glyph_variants)
  - IndexArray::get_indexes            (hb_ot_layout_language_get_feature_indexes,
                                        hb_ot_layout_feature_get_lookups, ...)
  - RecordListOf::get_tags             (hb_ot_layout_table_get_script_tags,
                                        _get_feature_tags, _get_language_tags, ...)
  - AttachList::get_attach_points      (hb_ot_layout_get_attach_points)
  - LigGlyph::get_lig_carets           (hb_ot_layout_get_ligature_carets)
  - fvar get_axis_infos / get_axes_deprecated / get_instance_coords
                                        (hb_ot_var_get_axis_infos, hb_ot_var_get_axes,
                                        hb_ot_var_named_instance_get_design_coords)
  - OpenTypeOffsetTable / CoreText / face-builder get_table_tags
                                        (hb_face_get_table_tags)

Extend test/api/test-ot-nullable-output.c with table-tags, fvar axis-info
and MATH kerning cases; each crashed before this change.

Assisted-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 00:53:56 -06:00
Behdad EsfahbodandClaude Opus 4.8 d75c58a2e4 [ot] Fix NULL-deref when nullable output arrays are passed to list getters
Several public "list getter" APIs document their output array as nullable
(pass NULL to just query the total count without storing anything), but
their implementations gated the copy only on the count pointer:

    if (count)
    {
      + source.sub_array (start_offset, count)
      | hb_sink (hb_array (out, *count));   // writes through out even if NULL
    }

Passing a non-NULL count with a NULL output array on a populated table
therefore wrote through the NULL pointer and crashed (SIGSEGV).

Gate each copy on the output pointer as well (the same idiom already used
by hb_color_line_get_color_stops: "if (count && out)").  This is a no-op
when the output array is non-NULL and restores the documented behaviour of
returning the total count when it is NULL.  Affected getters:

  - hb_ot_color_palette_get_colors            (CPAL)
  - hb_ot_color_glyph_get_layers              (COLR v0)
  - hb_ot_meta_get_entry_tags                 (meta)
  - hb_aat_layout_get_feature_types           (AAT feat)
  - hb_aat_layout_feature_type_get_selector_infos (AAT feat)
  - hb_ot_layout_feature_get_characters       (GSUB cvXX)
  - hb_ot_layout_lookup_get_glyph_alternates  (GSUB aalt)

Add test/api/test-ot-nullable-output.c exercising each route with a NULL
output array; every case crashed before this change.

Fixes: GHSA-v5mv-8hhw-vff8
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 00:28:35 -06:00
Behdad Esfahbod 6a0bcf4318 [VARC] Fix test fonts glyphDataFormat (#6046) 2026-07-02 14:01:19 -06:00
Garret Rieger 22d6df2a19 Fix missing addition of idDelta when collecting cmap4 unicodes and mappings. (#6038)
From the spec: The value c is the character code in question, and i is the segment index in which c appears. If the value obtained from the indexing operation is not 0 (which indicates missingGlyph), idDelta[i] is added to it to get the glyph index. The idDelta arithmetic is modulo 65536.
2026-06-24 03:00:52 -06:00
Fuqiao Xue 6dda1a083c Add HB_SCRIPT_KATAKANA_OR_HIRAGANA (#5995)
* Add HB_SCRIPT_KATAKANA_OR_HIRAGANA

Fix #1473.

* Refactor HB_SCRIPT_KATAKANA_OR_HIRAGANA
2026-06-02 02:33:52 -06:00
Behdad EsfahbodandClaude Opus 4.8 d639197ed5 [COLR] Fix glyph extents for .notdef in COLRv1 fonts (#6012)
get_base_glyph_paintrecord() looked up the BaseGlyphList with the
reference-returning bsearch(), which yields the all-zero Null object
when the glyph is absent, and then rejected non-matches by comparing
record->glyphId against the requested gid. For glyph 0 the Null
object's glyphId (0) equals the requested gid, so the sentinel was
taken for a real record. .notdef then resolved to a bogus empty paint,
and COLR::get_extents() returned success with 0,0,0,0 instead of
letting hb_ot_get_glyph_extents() fall back to the glyf outline.

Use bfind(), which reports presence directly, so a missing glyph
(including glyph 0) returns nullptr and extents fall back correctly.

This surfaced as a mark-positioning difference: fallback mark
positioning centers a mark using the base and mark glyph extents, so a
.notdef mark over a space was positioned differently from shapers that
report the real outline extents (e.g. fontations/HarfRust).

Testing:
- test/api/test-extents.c: glyph 0 (.notdef, has an outline) now
  reports its outline extents; updated the expectation accordingly.
- b/util/hb-shape Noto-COLRv1.ttf -u 0020,0650 now matches
  --font-funcs=fontations.
- meson test -C build  (246 passed, 1 skipped)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-01 03:23:05 -06:00
Behdad EsfahbodandChad Brokaw 77abf89986 [harfrust] Honor hb font funcs during shaping (#6002)
Wire the HarfRust shaper through the active hb_font_t callback
surface so custom hb_font_funcs_t are respected during shaping.
Add a harfrust-specific test-shape invocation to cover that path.

Tested: meson test -C build test-shape-harfrust
Tested: HB_SHAPER_LIST=harfrust meson test -C build harfbuzz:shape_threads
Tested: HB_SHAPER_LIST=harfrust meson test -C build test-shape
Assisted-by: OpenAI Codex

---------

Co-authored-by: Chad Brokaw <cbrokaw@gmail.com>
2026-05-28 13:33:21 -04:00
Behdad Esfahbod 719a1d3c10 [paint] Round COLRv1 alpha consistently
Round COLRv1 alpha values when packing them into 8-bit colors in the
native OpenType and FreeType paint paths.

This removes the old downward truncation bias and aligns native output
with the backend behavior expected by the updated paint fixtures.

Update the affected test-paint fixtures for the rounded alpha values.

Testing:
CCACHE_DISABLE=1 meson test -C build --print-errorlogs

Assisted-by: OpenAI Codex
2026-05-27 12:42:55 +02:00
Behdad Esfahbod 788706d568 [test] Normalize linear paint transcripts
Reduce linear gradient anchors and normalize color lines before
printing them in test-paint. This makes the transcript reflect the
renderer-facing gradient geometry instead of backend-specific raw
COLRv1 anchors and stop ranges.

Also normalize signed zero in transform output so the fixtures stay
stable across backends.

Testing:
CCACHE_DISABLE=1 meson test -C build test-paint --print-errorlogs

Assisted-by: OpenAI Codex
2026-05-27 12:40:44 +02:00
Behdad Esfahbod 56ac9c925f [paint] Push COLRv1 root clip under font transform
Make the native COLRv1 paint paths report the root clip in font
units under the font transform. This matches the order used by
fontations and removes the need to pre-scale the HB-OT clip extents.

For the FreeType path, add a helper to convert FT_ClipBox values
back to font units before pushing them under the font transform, and
share that conversion with nested COLR glyph clip boxes.

Update paint and vector expectations for the new transform/clip stack.

Testing:
CCACHE_DISABLE=1 meson test -C build --print-errorlogs

Assisted-by: OpenAI Codex
2026-05-27 10:48:19 +02:00
Behdad Esfahbod 202202b349 [test] Disable stale beyond-64k API checks
The disabled assertions cover behavior from an older beyond-64k proposal.
That proposal has since changed, and current backends should not be
required to implement the stale loca-derived glyph count and metrics rules.

Keep the checks visible as disabled reminders until the library code is
adapted to the updated design.

Tested with:
CCACHE_DISABLE=1 HB_FONT_FUNCS=fontations meson test -C build test-be-glyph-advance test-be-num-glyphs

Assisted-by: OpenAI Codex
2026-05-27 09:38:31 +02:00
parasol-aserandjeffhuang da577bc545 test: strengthen buffer and map API coverage (#5979)
Add focused API tests for hb_buffer_create_similar() and buffer
configuration persistence across clear/reset. Also exercise public hb_map
copy, equality, hash, update, iteration, keys, and values paths with
order-independent assertions.

Validation:
meson test -C build-tgl-precheck --print-errorlogs --suite api test-buffer
meson test -C build-tgl-precheck --print-errorlogs --suite api test-map
meson test -C build-tgl-precheck --print-errorlogs --suite api test-buffer test-map

Assisted-by: OpenAI Codex <codex@openai.com>

Co-authored-by: jeffhuang <jeff@docker.xydrsucermoubd24xgo33yhsgd.bx.internal.cloudapp.net>
2026-05-06 17:27:10 -06:00
parasol-aserandjeffhuang 1ea68a9f57 [fontations] Fix OOB write on glyph-name callback with size == 0 (#5946) (#5947)
* [fontations] Fix OOB write on glyph-name callback with size == 0

The Rust `_hb_fontations_glyph_name()` callback computed
`glyph_name.len().min(size as usize - 1)`. When a caller passed
`size == 0`, `size as usize - 1` underflowed a `usize` to
`usize::MAX`, the `min()` clamp collapsed to `glyph_name.len()`,
and the subsequent `copy_nonoverlapping` / trailing NUL wrote
`glyph_name.len() + 1` bytes into a zero-capacity caller buffer.
This is an out-of-bounds write reachable from the public API
whenever the build was configured with `-Dfontations=enabled`
and the application had called `hb_fontations_font_set_funcs()`.

Short-circuit the `size == 0` case before the subtraction.
Return `true` in that case to match the existing post and CFF1
backends (`hb-ot-post-table.hh`, `hb-ot-cff1-table.hh`), which
both early-out with `return true` on `!buf_len` — the glyph
does have a name; we simply had no buffer to write it into.

Regression tests added in `test/api/test-glyph-names.c` cover
the zero-size path on post and CFF1 backends, a sub-font, a
NULL buffer, and `size == 1` / small-buffer / exact-fit cases
so the truncation path does not silently regress.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/5946
Assisted-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* [font] Reject glyph-name lookups with size == 0 at the wrapper

`hb_font_t::get_glyph_name()` previously pre-wrote the trailing
NUL only when `size != 0` but still dispatched to the backend
callback with `size == 0`. Every current glyph-name backend has
to re-validate that argument: `post` and `cff1` short-circuit
with `return true`, the new Rust `fontations` callback now
short-circuits too (prior commit), and the CoreText callback in
`hb-coretext-font.cc` has a structurally similar `(CFIndex)size
- 1` pattern.

Normalize this at the wrapper layer: return `false` immediately
on `size == 0`, before any backend dispatch and before the
`*name = '\0'` write. This makes the zero-size case a single,
auditable no-op for every glyph-name provider (native or Rust,
current or future) and removes the CoreText underflow from the
reachable surface through the same chokepoint.

Observable change: callers that invoked
`hb_font_get_glyph_name(font, gid, buf, 0)` on post/cff1 backed
fonts used to get `true` back; they now get `false`. `size == 0`
queries carry no useful information for the caller, so this is
considered a safe hardening rather than a contract break.

Assisted-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

* [font] Preserve glyph-name zero-size probe semantics

Keep `hb_font_get_glyph_name(..., NULL, 0)` as a valid
return-value-only probe instead of rejecting `size == 0` in the
wrapper.

Fix the remaining backend-specific zero-size paths in hb-ft and
hb-coretext-font so they answer the probe without dereferencing the
caller buffer, and update the API tests to assert the preserved
behavior.

Testing: CCACHE_DISABLE=1 meson test -C build test-glyph-names
Testing: CCACHE_DISABLE=1 meson test -C build test-ft
Assisted-by: OpenAI Codex <codex@openai.com>

---------

Co-authored-by: jeffhuang <jeff@docker.xydrsucermoubd24xgo33yhsgd.bx.internal.cloudapp.net>
2026-04-18 19:54:54 -06:00
Behdad EsfahbodandClaude Opus 4.6 591748f1e1 [draw][paint] Make get_funcs instance-aware; add get_format
The six public draw / paint funcs getters across raster,
vector, and gpu used to be singletons:

  hb_raster_draw_get_funcs (void)
  hb_raster_paint_get_funcs (void)
  hb_vector_draw_get_funcs (void)
  hb_vector_paint_get_funcs (void)
  hb_gpu_draw_get_funcs (void)
  hb_gpu_paint_get_funcs (void)

That works fine for raster and gpu, where there's a single
backend per type, but breaks for the vector backend where
SVG and PDF have separate funcs sets — callers using the
public getter always got SVG funcs and silently produced
SVG markup inside PDF output streams when invoking the new
arbitrary-path clip API on a PDF context.

Make all six take a const-pointer to the relevant context
instance.  vector_paint dispatches on paint->format; the
other five just use the instance for symmetry today (room
for future format-style dispatch later).

Also expose hb_vector_draw_get_format / hb_vector_paint_
get_format public getters so callers (or third parties)
can ask a vector context for its format without poking at
internals.

Also: hb_vector_paint_push_clip_path_end now wraps the
emitted SVG clipPath's path in transform="scale(1,-1)" so
free-form arbitrary clips at base body level land in the
same coord system the per-glyph <use scale(_,-sy)>
wrappers establish.  Without this, free-form clip-path
arbitrary outlines emitted between paint_glyph calls came
out mirrored across the X axis.

Updates internal callers (hb_vector_paint_glyph,
hb_pdf_emit_glyph_path, hb_raster_paint_push_clip_path_
start, hb_gpu_paint_push_clip_path_start, the GPU pen
adapter), util sites (raster-output.hh, vector-output.hh,
gpu/demo-font.cc), API tests (test-raster.cc, test-gpu.cc),
and the docs section index.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:21:49 -06:00
Behdad EsfahbodandClaude Opus 4.6 98470a3e02 [draw] Rename hb_draw_rect to hb_draw_rectangle
API rename for the not-yet-released stroked/filled
rectangle helper added to hb-draw — full names
(hb_draw_line, hb_draw_circle, hb_draw_rectangle) read
better than mixed full/abbreviated.

Updates the public header, impl, the gpu doc reference,
the GPU API test, the GPU demo's extents overlay, the
extents-overlay paint helper, and the docs section
listing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:18:20 -06:00
Behdad EsfahbodandClaude Opus 4.6 f3c36ef3d6 [test] Add API tests for push_clip_path_start/_end
Folded into the existing test-paint binary.  Two tests,
both font-independent (registered ahead of the glyph-based
flavor setup so they run even on builds without the test
COLRv1 font):

* test_push_clip_path_nil_returns_null: an unset paint-funcs
  table returns NULL from push_clip_path_start and clears
  the out-param draw_data, and push_clip_path_end is safe
  to call on the nil stub.

* test_push_clip_path_round_trip: registered start/end fire
  in order, the returned draw-funcs + draw-data round-trip
  through the public entry points, and every hb_draw_*()
  call reaches the sink accumulator.  Asserts the count
  includes hb_draw_close_path's synthetic back-to-start
  line_to so the contract is documented by the test.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:18:20 -06:00
Behdad Esfahbod 98f3a42ee2 [vector/raster/gpu] Add *_glyph_or_fail() variants across all three
Consolidate the {vector,raster,gpu}_{draw,paint}_glyph APIs
to match the hb_font_{draw,paint}_glyph / _or_fail pattern:

  * Each existing *_glyph() public function now returns void.
    For the draw variants this is purely a return-value drop.
    For the paint variants the void entry additionally gains a
    synthesize fallback for non-color glyphs (calls
    hb_font_paint_glyph instead of _or_fail) so a mono glyph
    still produces output via a foreground-colored outline.

  * New *_glyph_or_fail() variants return hb_bool_t, reporting
    exactly what hb_font_{draw,paint}_glyph_or_fail() would.
    Callers that care about distinguishing color paint from
    synthesized outline now have a clean boolean signal.

Refactors the internal impls behind a shared static helper
parameterised by a `fallible` flag; the two public entries
delegate, passing true (for _or_fail) or false (for the void
alias).

For GPU specifically, paint_glyph_or_fail no longer folds the
encoder's unsupported flag into its return -- that state was
always better reported from hb_gpu_paint_encode() (which
returns NULL), and conflating the two prevented callers from
telling "font has no paint data" from "encoder hit a limit".

While in there, remove a dead branch at the end of
hb_vector_paint_glyph's SVG case (both inner blocks had
already returned; the tail was unreachable).

Updates docs/harfbuzz-sections.txt with the six new symbols
and the NEWS note with the Changed API callouts.  Updates
in-tree callers (hb-vector-svg-all, hb-raster-all, test-gpu,
util/vector-output.hh) to the _or_fail variants where they
previously read the return value.

Fixes: https://github.com/harfbuzz/harfbuzz/issues/5926

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 00:36:37 -06:00
Behdad Esfahbod fd2a6968ab [draw] hb_draw_line: add cap parameter (butt / square)
Add hb_draw_line_cap_t enum with HB_DRAW_LINE_CAP_BUTT (the
existing default behavior) and HB_DRAW_LINE_CAP_SQUARE, which
extends each endpoint along the line direction by half its
local stroke width.

Square caps let four hb_draw_line() calls form a closed
rectangle without gaps at the corners -- a meaningfully
cheaper alternative to hb_draw_rect() for thin outlined
rectangles, since each line's bbox is just stroke_width tall
instead of covering the full rectangle interior.

Round caps not implemented yet; can be added as a third enum
value when a use case shows up.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 02:35:10 -06:00
Behdad Esfahbod e731c38975 [draw] Promote shape helpers from hb-gpu-draw to hb-draw
Three shape-emitting helpers (line, rect, circle) operate on
any hb_draw_funcs_t, not specifically the GPU backend.  Move
them out of the GPU-only API surface into the core hb-draw
API so any pen (raster, vector, gpu, user-supplied) gets
them.

API rename / move:

  hb_gpu_draw_line   -> hb_draw_line   (in src/hb-draw.h)
  hb_gpu_draw_rect   -> hb_draw_rect
  hb_gpu_draw_circle -> hb_draw_circle

Signatures gain a (dfuncs, draw_data, st) prefix to match the
existing hb_draw_move_to / line_to / cubic_to / close_path
shape -- the helpers are thin wrappers over those.

Callers in test/api/test-gpu.cc and util/gpu/demo-font.cc
updated to call hb_draw_* with hb_gpu_draw_get_funcs() and a
local hb_draw_state_t.

Updated harfbuzz-sections.txt with the new entries; removed
hb_gpu_draw_line / _rect / _circle from hb-gpu.h.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 02:27:43 -06:00
Behdad Esfahbod cfdcea6c79 [gpu] Add hb_gpu_draw_line / _rect / _circle shape helpers
The GPU draw encoder already consumes arbitrary curves via the
hb_draw_funcs_t machinery -- that's how glyph outlines feed in.
Expose three convenience helpers so callers can emit common
shapes (tapered line, rectangle, circle) without having to
hand-roll the curve math:

    hb_gpu_draw_line   (draw, x0,y0,w0, x1,y1,w1);
    hb_gpu_draw_rect   (draw, x,y,w,h, stroke_width);
    hb_gpu_draw_circle (draw, cx,cy,r, stroke_width);

stroke_width = NaN means "filled".  A finite positive value
produces a stroked outline by emitting an outer contour CCW
and an inner contour CW so the fill rule carves a hole.

For shapes beyond these three helpers, callers can feed any
outline through hb_draw_move_to / _line_to / _quadratic_to /
_cubic_to / _close_path with the funcs from
hb_gpu_draw_get_funcs() and the hb_gpu_draw_t as data -- the
helpers are thin wrappers over that path.

Useful for game UI: health bars, progress rings, custom
line-art decorations, rendered through the same slug shader
as text.

Assisted-by: Claude <noreply@anthropic.com>
2026-04-15 01:54:08 -06:00
Behdad Esfahbod a01bd008ad [gpu] paint_encode: empty-blob singleton for "no ink" (match draw)
hb_gpu_draw_encode already returns the empty-blob singleton (not
NULL) when the encoder has accumulated no curves -- the convention
is "NULL = encoder failed, empty blob = nothing to render".

Make hb_gpu_paint_encode follow the same shape:
  - NULL  -> hard failure (paint_glyph hit an unsupported feature
             or allocation failed).
  - empty -> no ink (e.g. space glyph or paint tree that produced
             no layer ops).

Document on both encode functions, and update the tests to expect
empty (not NULL) for the no-ink path.

The demo already short-circuits on length 0 (no atlas upload) and
_hb_gpu_blob_recycle drops the empty singleton instead of stashing
it, so nothing downstream needs to change.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:50:16 -06:00
Behdad Esfahbod b38c5189df [gpu] Detect paint-encoder limits, fail rather than misrender
Paint encoder used to push past several limits and produce a blob
that wraps an int16, overflows the shader's group stack, or skips
unsupported callbacks entirely.  Detect each:

- num_ops > 32767 (the i16 blob header field's range): set
  paint->unsupported in every emit path.
- group depth > HB_GPU_PAINT_MAX_GROUP_DEPTH (4 -- matches the
  fragment shader's HB_GPU_PAINT_GROUP_DEPTH): set unsupported
  in push_group; mirror the symmetric pop guard.
- PaintImage: register an `image` callback that sets unsupported
  (the slug+gradient encoder can't represent raster images).

push_clip_rectangle is intentionally NOT trapped -- the encoder
silently ignores it; rendered output is wider than the rectangle
asks but doesn't fail.

Nested PaintGlyph clips still silently override the outer clip
(only depth 1 is faithfully stored); follow-up commit will lift
this to depth 2.

Document all of the above in NEWS, and relax the COLR test to
tolerate a font where every glyph trips one of these limits.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 18:45:35 -06:00
Behdad Esfahbod d235a23b45 [test/api] Silence cast-align in test-gpu blob accessors
Casting hb_blob_get_data()'s const char* to a struct pointer
trips clang's -Wcast-align (1-byte to 2-byte short).  In practice
the blob's underlying buffer is malloc'd and so suitably aligned
for any standard type; suppress the warning around the cast with
the same #pragma GCC diagnostic ignored "-Wcast-align" pattern
used elsewhere in the codebase (hb-bit-set.hh, hb-machinery.hh).

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:26:01 -06:00
Behdad Esfahbod 157e5111b3 [gpu] Add tests + benchmark for hb_gpu_paint, NEWS draft
test/api/test-gpu: extends the existing draw test suite with
paint counterparts -- create/destroy, get_funcs singleton,
shader_source for all four langs, empty encode returns nullptr,
encode of a monochrome glyph (synthesized single-layer fallback),
encode of a real COLRv1 glyph (test_glyphs-glyf_colr_1.ttf,
scanning for a glyph our encoder fully supports), auto-clear on
encode, reset wipes config, recycle_blob roundtrip.

perf/benchmark-gpu: add BM_GpuPaintEncode parallel to
BM_GpuDrawEncode (renamed from BM_GpuEncode for symmetry) so the
two paths can be compared on the same fonts.

NEWS: draft entry under "leading to NEXT (REPLACEME)" listing the
new hb_gpu_paint_* API surface and the recent GPU library changes
(--draw / --paint flags, gradient inverse-transform).  Release
manager will fold this into the actual release section.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 16:00:51 -06:00
Behdad Esfahbod f587af3ec3 [gpu] Extract shared shader helpers into hb_gpu_shader_source() (#5921)
The draw-renderer fragment shaders defined utilities
(HB_GPU_UNITS_PER_EM, the hb_gpu_atlas uniform, hb_gpu_fetch) that
any future GPU renderer will also need.  The draw-renderer vertex
shader likewise contained only the generic hb_gpu_dilate helper.
If a paint renderer were added today and a caller linked both
fragment sources together, hb_gpu_fetch would be defined twice.

Move these shared helpers into a new family of sources and expose
them via a new public entry point:

  hb_gpu_shader_source (stage, lang);

The existing hb_gpu_draw_shader_source() now returns only the
draw-specific fragment code; it returns an empty string for the
vertex stage because all current vertex logic is shared.  Callers
concatenate the shared source first, then the draw-specific
source, then their own main():

  [#version, hb_gpu_shader_source (...), hb_gpu_draw_shader_source
  (...), main]

Additions:
 - src/hb-gpu-fragment.{glsl,msl,wgsl,hlsl} — shared fragment
 - src/hb-gpu-vertex.{glsl,msl,wgsl,hlsl}   — shared vertex,
   renamed from hb-gpu-draw-vertex.*
 - src/hb-gpu-shaders.cc — hb_gpu_shader_source() dispatcher

Removals:
 - src/hb-gpu-draw-vertex.{glsl,msl,wgsl,hlsl} — moved to common

Shared sources are Behdad-only copyright; the Eric Lengyel / Slug
attribution stays on the draw-specific fragment sources where the
Slug algorithm actually lives.

Updates: test/api/test-gpu.cc, the Metal/D3D11/WebGPU/GL demo
shaders, the hb-gpu SECTION documentation, meson.build,
CMakeLists.txt, gen-gpu-shader-artifacts.py decl_map,
harfbuzz-world.cc, and docs/harfbuzz-sections.txt.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 12:10:23 -06:00
Behdad Esfahbod eeec9bd9fa [gpu] Unify shader source getters; rename for draw/paint split
Replace the two separate getters

  hb_gpu_shader_fragment_source (lang)
  hb_gpu_shader_vertex_source   (lang)

with a single

  hb_gpu_draw_shader_source (stage, lang)

where stage is the new hb_gpu_shader_stage_t enum (VERTEX or
FRAGMENT).  Parameter order is stage-first because "the vertex
shader in GLSL" reads more naturally than the reverse, and stage
is the primary axis (it determines which shader object the source
is compiled into).

The `_draw_` in the new name makes room for the incoming
hb_gpu_paint_shader_source() once the COLRv1 encoder lands —
that family will have its own (likely different) shader sources
per stage and language.

Updated the four in-tree callers: test/api/test-gpu.cc, and the
GPU demos under util/gpu/.  ABI break on a 14.0-only API; the
gpu library is still young enough that this is acceptable.

Marked new API with XSince: REPLACEME.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:26:21 -06:00
Behdad Esfahbod 4650398a07 [gpu] encode() returns extents + auto-clears; drop get_extents() (#5910)
Bring hb_gpu_draw_encode into line with the rest of the render APIs:
auto-clear on success, and return the computed glyph extents to the
caller via a new out-parameter (nullable).

  HB_EXTERN hb_blob_t *
  hb_gpu_draw_encode (hb_gpu_draw_t      *draw,
                      hb_glyph_extents_t *extents);

Consumers typically need both the encoded blob and the glyph's
extents to size the quad they'll draw into in the vertex shader;
returning them together removes a redundant trip through the draw
state and lets encode() auto-clear like hb_vector_*_render() and
hb_raster_*_render() do.

Drop hb_gpu_draw_get_extents() from the public API — its only
role was reading extents out of the draw state post-encode, which
the new encode() signature makes redundant.  The computation
stays (moved to a static _hb_gpu_draw_get_extents helper) so
encode() can call it before auto-clear wipes the state.

ABI break for anyone who had already wired up against the 14.0.0
hb_gpu_draw_encode signature or hb_gpu_draw_get_extents, but the
library is new/experimental and the two in-tree consumers
(test/api/test-gpu.cc, util/gpu/demo-font.cc, util/hb-gpu-encode-all.cc,
test/fuzzing/hb-gpu-fuzzer.cc) are updated here.

All 240 tests pass.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 00:15:54 -06:00
Behdad Esfahbod 5e6ae10f62 [raster][vector] Remove SVG-font glyph source rendering
Remove support for rendering glyphs whose source is the OpenType
SVG table, in both hb-raster and hb-vector.  SVG is a large format
and our in-tree parser/renderer was half-finished; the complexity
was not justified by the partial coverage.

This is source-side only: hb-vector's SVG *output* backend (used
to serialize outline / COLR glyphs to SVG) is unaffected.  Fonts
that have an SVG table will still load; glyphs served only by that
table will not render from these libraries.

hb-raster:
  - Delete the hb-raster-svg-* file cluster (11 .cc/.hh files plus
    hb-raster-svg.hh: parse, base, bbox, clip, color, defs,
    defs-scan, fill, gradient, parse, render, use, context).
  - Drop svg_glyph/svg_font/svg_palette state from
    hb_raster_paint_t and the HB_PAINT_IMAGE_FORMAT_SVG branch in
    the image callback.
  - Drop hb_raster_paint_push_clip_path + hb_raster_svg_path_func_t
    (only used from the SVG renderer).
  - Drop zlib dependency (gzip decompression was only used for the
    SVG table reader; libpng brings its own zlib linkage for PNGs).

hb-vector:
  - Delete hb-vector-svg-subset.{cc,hh} (extracted font-SVG glyph
    for embedding in SVG output).
  - Remove the HB_TAG('s','v','g',' ') branch from the image paint
    callback; PNG embedding remains.
  - Drop svg_image tracking state from hb_vector_paint_t
    (current_color_glyph_has_svg_image, current_svg_image_glyph,
    current_face, svg_image_counter, subset_body_scratch).
  - Simplify the color-glyph cache to store just def_id instead of
    packed (def_id, image_like).
  - Drop hb_svg_append_image_instance_translate.

Build wiring: src/meson.build, CMakeLists.txt, harfbuzz-world.cc
updated to match.  Test suite: remove SVG-specific cases from
test/api/test-raster.cc and the handwriting-{svg,picosvg} vector
tests + expected fixtures.

~5700 LOC deleted, ~10 LOC added.  Full test suite (240 tests)
passes.

Assisted-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 22:46:35 -06:00
Behdad Esfahbod b5287cb3fb [gpu] Clamp exported draw extents
hb_gpu_draw_get_extents() cast rounded bounds to hb_position_t
before subtracting them. A fuzzed glyph outline with an extreme
negative bound could therefore overflow signed int arithmetic while
forming width or height.

Compute the rounded bounds in double, reject non-finite values, and
clamp the exported extents to hb_position_t before returning them.
Add an API regression that covers the OSS-Fuzz testcase through the
public GPU draw API.

Fixes: https://oss-fuzz.com/testcase-detail/5918954634936320
Tested: meson test -C build --print-errorlogs
Assisted-by: OpenAI Codex
2026-04-09 23:15:34 -06:00
💀 f4600f3c87 test: add hb-ft load-flag preservation regression 2026-04-09 14:57:29 -06:00
Behdad Esfahbod 3b7ee09f0e [gpu] Fix draw encode blob ownership leaks
hb_gpu_draw_encode() could allocate a fresh output buffer and then
return NULL before transferring ownership to a blob, leaking that
temporary buffer on late encode failures.

The recycled-blob growth path also tried hb_realloc() first and fell
back to hb_malloc() when that failed. Once the new buffer was committed
to the recycled blob, the old recycled buffer could be orphaned.

Free temporary buffers on the remaining late-failure exits and keep
the old recycled buffer alive until a replacement has been committed.
Tighten the GPU API recycle test to encode a larger second outline so
that reused-buffer growth stays covered.

Tested:
- meson test -C build

Assisted-by: OpenAI Codex <codex@openai.com>
2026-04-04 19:44:54 -06:00
Behdad EsfahbodandOpenAI Codex a4aff49856 [gpu] Fix contour breaks and bounds quantization in encode (#5892)
Encode used adjacent endpoint equality to infer contour breaks, which
fails when two contours touch at the same point. Track contour starts
explicitly during accumulation instead, and use that flag when packing
shared endpoints.

Encode also rounded blob bounds to the nearest quarter unit. That can
shrink the encoded extents and clip coverage at glyph edges. Quantize
mins downward and maxes upward so the blob header always encloses the
actual geometry.

Add focused API tests for both regressions.

Testing:
- meson test -C build

Co-authored-by: OpenAI Codex <codex@openai.com>
2026-04-03 12:09:02 -06:00
Behdad EsfahbodandClaude Opus 4.6 d46f8e3444 [gpu] Rename HB_GPU_SHADER_GLSL_330 to HB_GPU_SHADER_LANG_GLSL
The shader source is compatible with both GLSL 3.30 and
GLSL ES 3.00.  Rename the enum value to reflect this and
match the type name convention.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 00:40:11 -06:00
Behdad EsfahbodandClaude Opus 4.6 0582846c08 [gpu] Simplify shader API: return single string per language
Change hb_gpu_shader_{fragment,vertex}_sources() (array + count)
to hb_gpu_shader_{fragment,vertex}_source() returning a single
const char *.  Each language variant is one complete string.

Simplifies the demo shader compilation and documentation.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 17:10:04 -06:00
Behdad EsfahbodandClaude Opus 4.6 971e607319 [gpu] Add API test and google-benchmark encode benchmark
test-gpu: 7 subtests covering create/destroy, empty encode,
glyph encode, reset, draw funcs singleton, shader sources,
and recycle_blob.

benchmark-gpu: benchmarks draw, encode, and draw+encode
per-glyph across several fonts using google-benchmark.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 22:27:40 -06:00
Behdad Esfahbod 6e45962326 [raster] Guard direct SVG paint callbacks
The raster SVG image callback assumes hb_raster_paint_glyph()
seeded svg_font/svg_glyph state before the paint protocol
reaches HB_PAINT_IMAGE_FORMAT_SVG. Clients can also call
hb_font_paint_glyph_or_fail() directly with
hb_raster_paint_get_funcs(), which leaves svg_font unset and
crashes in hb_raster_svg_render().

Return false when the callback is reached without that
wrapper-only state, and cover the direct API path with a
regression test.

Testing: CCACHE_DISABLE=1 meson test -C build
Fixes https://github.com/harfbuzz/harfbuzz/security/advisories/GHSA-ggh9-cgg2-r4vr
Assisted-by: OpenAI Codex <codex@openai.com>
2026-03-26 14:41:14 -06:00
Khaled Hosny b327f0c672 [tests] Fix warning when building without zlib
../test/api/test-raster.cc:67:1: warning: unused function 'render_svg_glyph' [-Wunused-function]
   67 | render_svg_glyph (hb_face_t      *face,
      | ^~~~~~~~~~~~~~~~
1 warning generated.
2026-03-12 17:36:39 +02:00
Behdad Esfahbod b7e4f5fd62 [raster] Support gzip-compressed SVG documents
The raster SVG path treated hb_ot_color_glyph_reference_svg()
blobs as plain XML, even though SVG table documents may
legally be gzip encoded. That caused hb-raster to reject
fonts that store compressed SVG documents.

Detect gzip payloads in the raster SVG renderer, reject
documents whose advertised uncompressed size exceeds
HB_SVG_MAX_DOCUMENT_SIZE, and inflate the rest through
zlib while keeping the same size cap enforced during
decompression. Plain SVG documents are also bounded by the
same 16 MiB limit.

Add a raster API regression that renders the existing
plain and compressed noto_handwriting SVG fixtures and
verifies identical output.

Testing:
- meson test -C build

Assisted-by: OpenAI Codex
2026-03-11 14:18:31 -03:00
Behdad Esfahbod cfd9a52c9d [svg] Gate SVG table processing under HB_NO_SVG (#5814)
Skip the SVG table accelerator and do not define the public
SVG color APIs when HB_NO_SVG is set. Guard internal
callers so SVG-table-dependent code compiles out cleanly,
and add HB_NO_SVG to the HB_TINY profile.

Tested: meson setup build-nosvg -Dc_args=-DHB_NO_SVG -Dcpp_args=-DHB_NO_SVG
Tested: meson compile -C build-nosvg hb-shape hb-info hb-vector main
Tested: meson compile -C build-nosvg (libharfbuzz/libharfbuzz-raster/libharfbuzz-vector linked; full tree stopped on unrelated missing chafa.h in util/hb-raster.cc)
Tested: nm -gU build-nosvg/src/libharfbuzz.0.dylib | grep -E "hb_ot_color_.*svg" (no matches)

Assisted-by: OpenAI Codex
2026-03-10 00:19:39 -06:00