API Reference

class uharfbuzz.Blob

Bases: object

Binary data containers.

Blobs wrap a chunk of binary data to handle lifecycle management of data while it is passed between client and HarfBuzz. Blobs are primarily used to create font faces, but also to access font face tables, as well as pass around other binary data.

Parameters:

data – The binary data to wrap. If None or empty, the empty blob is returned.

Wraps hb_blob_t.

data

Fetches the data from a blob.

Type:

bytes

Wraps hb_blob_get_data().

classmethod from_file_path(filename: str | Path) Blob

Creates a new blob containing the data from the specified file.

The filename is passed directly to the system on all platforms, except on Windows, where the filename is interpreted as UTF-8. Only if the filename is not valid UTF-8, it will be interpreted according to the system codepage.

Parameters:

filename – A filename.

Returns:

A new Blob with the content of the file.

Raises:

HarfBuzzError – If the file cannot be opened or read.

Wraps hb_blob_create_from_file_or_fail().

class uharfbuzz.Buffer

Bases: object

Input and output buffers.

Buffers serve a dual role in HarfBuzz; before shaping, they hold the input characters that are passed to shape(), and after shaping they hold the output glyphs.

The input buffer is a sequence of Unicode codepoints, with associated attributes such as direction and script. The output buffer is a sequence of glyphs, with associated attributes such as position and cluster.

DEFAULT_REPLACEMENT_CODEPOINT = 0xFFFD

The default code point for replacing invalid characters in a given encoding. Set to U+FFFD REPLACEMENT CHARACTER.

Wraps HB_BUFFER_REPLACEMENT_CODEPOINT_DEFAULT.

Wraps hb_buffer_t.

add_codepoints(codepoints: List[int], item_offset: int = 0, item_length: int = -1)

Appends characters from codepoints to the buffer.

The item_offset is the position of the first character from codepoints that will be appended, and item_length is the number of characters. When shaping part of a larger text (e.g. a run of text from a paragraph), instead of passing just the substring corresponding to the run, it is preferable to pass the whole paragraph and specify the run start and length as item_offset and item_length, respectively, to give HarfBuzz the full context to be able, for example, to do cross-run Arabic shaping or properly handle combining marks at start of run.

This method does not check the validity of codepoints, it is up to the caller to ensure it contains valid Unicode scalar values. In contrast, add_utf8() and add_str() perform sanity-check on the input.

Parameters:
  • codepoints – A sequence of Unicode code points to append.

  • item_offset – The offset of the first code point to add to the buffer.

  • item_length – The number of code points to add to the buffer, or -1 to add the rest of codepoints.

Raises:

MemoryError – If memory allocation fails.

Wraps hb_buffer_add_codepoints().

add_str(text: str, item_offset: int = 0, item_length: int = -1)

Appends text to the buffer.

Replaces invalid characters with the buffer replacement code point, see replacement_codepoint.

Parameters:
  • text – Text to append.

  • item_offset – The offset of the first character to add to the buffer.

  • item_length – The number of characters to add to the buffer, or -1 to add the rest of text.

Raises:

MemoryError – If memory allocation fails.

Wraps hb_buffer_add_utf32().

add_utf8(text: bytes, item_offset: int = 0, item_length: int = -1)

Appends UTF-8 text to the buffer.

Replaces invalid UTF-8 characters with the buffer replacement code point, see replacement_codepoint.

Parameters:
  • text – UTF-8 encoded text to append.

  • item_offset – The offset of the first character to add to the buffer.

  • item_length – The number of characters to add to the buffer, or -1 to add the rest of text.

Raises:

MemoryError – If memory allocation fails.

Wraps hb_buffer_add_utf8().

clear_contents()

Similar to reset(), but does not clear the Unicode functions and the replacement code point.

Wraps hb_buffer_clear_contents().

cluster_level

The cluster level of the buffer. The BufferClusterLevel dictates one aspect of how HarfBuzz will treat non-base characters during shaping.

Type:

BufferClusterLevel

Wraps hb_buffer_get_cluster_level() / hb_buffer_set_cluster_level().

content_type

The type of buffer contents. Buffers are either empty, contain characters (before shaping), or contain glyphs (the result of shaping).

Type:

BufferContentType

Wraps hb_buffer_get_content_type() / hb_buffer_set_content_type().

classmethod create() Buffer

Deprecated since version 0.10.0.

Use Buffer() instead.

direction

The text flow direction of the buffer. No shaping can happen without setting buffer direction, and it controls the visual direction for the output glyphs; for RTL direction the glyphs will be reversed. Many layout features depend on the proper setting of the direction, for example, reversing RTL text before shaping, then shaping with LTR direction is not the same as keeping the text in logical order and shaping with RTL direction.

Wraps hb_buffer_get_direction() / hb_buffer_set_direction().

flags

The BufferFlags of the buffer.

Type:

BufferFlags

Wraps hb_buffer_get_flags() / hb_buffer_set_flags().

glyph_infos

The buffer glyph information array. The value is valid as long as the buffer has not been modified.

Type:

list[GlyphInfo]

Wraps hb_buffer_get_glyph_infos().

glyph_positions

The buffer glyph position array. The value is valid as long as the buffer has not been modified.

If the buffer did not have positions before, the positions will be initialized to zeros, unless this property is accessed from within a buffer message callback (see set_message_func()), in which case None is returned.

Type:

list[GlyphPosition] | None

Wraps hb_buffer_get_glyph_positions().

guess_segment_properties()

Sets unset buffer segment properties based on buffer Unicode contents. If the buffer is not empty, it must have content type BufferContentType.UNICODE.

If the buffer script is not set, it will be set to the Unicode script of the first character in the buffer that has a script other than COMMON, INHERITED, and UNKNOWN.

Next, if the buffer direction is not set, it will be set to the natural horizontal direction of the buffer script.

Finally, if the buffer language is not set, it will be set to the process’s default language.

Wraps hb_buffer_guess_segment_properties().

invisible_glyph

The codepoint that replaces invisible characters in the shaping result. If set to zero (default), the glyph for the U+0020 SPACE character is used. Otherwise, this value is used verbatim.

Wraps hb_buffer_get_invisible_glyph() / hb_buffer_set_invisible_glyph().

language

The language of the buffer, as a BCP 47 language tag.

Languages are crucial for selecting which OpenType feature to apply to the buffer which can result in applying language-specific behaviour. Languages are orthogonal to the scripts, and though they are related, they are different concepts and should not be confused with each other.

Wraps hb_buffer_get_language() / hb_buffer_set_language().

not_found_glyph

The codepoint that replaces characters not found in the font during shaping.

The not-found glyph defaults to zero, sometimes known as the .notdef glyph. This API allows for differentiating the two.

Wraps hb_buffer_get_not_found_glyph() / hb_buffer_set_not_found_glyph().

replacement_codepoint

The codepoint that replaces invalid entries for a given encoding when adding text to the buffer.

Default is DEFAULT_REPLACEMENT_CODEPOINT.

Wraps hb_buffer_get_replacement_codepoint() / hb_buffer_set_replacement_codepoint().

reset()

Resets the buffer to its initial status, as if it was just newly created.

Wraps hb_buffer_reset().

script

The script of the buffer, as an ISO 15924 script tag.

Script is crucial for choosing the proper shaping behaviour for scripts that require it (e.g. Arabic) and the which OpenType features defined in the font to be applied.

Wraps hb_buffer_get_script() / hb_buffer_set_script().

serialize(font: Font, format: BufferSerializeFormat = BufferSerializeFormat.TEXT, flags: BufferSerializeFlags = <BufferSerializeFlags.DEFAULT: 0>) str

Serializes the buffer into a textual representation of its content, whether Unicode codepoints or glyph identifiers and positioning information. This is useful for showing the contents of the buffer, for example during debugging.

Parameters:
  • font – The Font used to shape this buffer, needed to read glyph names and extents.

  • format – The BufferSerializeFormat to use for formatting the output.

  • flags – The BufferSerializeFlags that control what glyph properties to serialize.

Returns:

The serialized buffer contents.

Wraps hb_buffer_serialize().

set_language_from_ot_tag(value: str)

Sets the language of the buffer from an OpenType language tag.

Wraps hb_ot_tag_to_language() + hb_buffer_set_language().

set_message_func(callback: Callable[str])

Sets the implementation function for the buffer’s message callback.

The callback is called with a message describing what step of the shaping process will be performed. Returning False from this callback will skip this shaping step and move to the next one.

Wraps hb_buffer_set_message_func().

set_script_from_ot_tag(value: str)

Sets the script of the buffer from an OpenType script tag.

Wraps hb_ot_tag_to_script() + hb_buffer_set_script().

class uharfbuzz.BufferClusterLevel(*values)

Bases: IntEnum

Data type for holding HarfBuzz’s clustering behavior options. The cluster level dictates one aspect of how HarfBuzz will treat non-base characters during shaping.

MONOTONE_GRAPHEMES is the default, because it maintains backward compatibility with older versions of HarfBuzz. New client programs that do not need to maintain such backward compatibility are recommended to use MONOTONE_CHARACTERS instead of the default.

MONOTONE_GRAPHEMES = 0

Return cluster values grouped by graphemes into monotone order. Non-base characters are merged into the cluster of the base character that precedes them. There is also cluster merging every time the clusters will otherwise become non-monotone.

MONOTONE_CHARACTERS = 1

Return cluster values grouped into monotone order. Non-base characters are initially assigned their own cluster values, which are not merged into preceding base clusters. This allows HarfBuzz to perform additional operations like reorder sequences of adjacent marks. The output is still monotone, but the cluster values are more granular.

CHARACTERS = 2

Don’t group cluster values. Non-base characters are assigned their own cluster values, which are not merged into preceding base clusters. Moreover, the cluster values are not merged into monotone order. This is the most granular cluster level, and it is useful for clients that need to know the exact cluster values of each character, but is harder to use for clients, since clusters might appear in any order.

GRAPHEMES = 3

Only group clusters, but don’t enforce monotone order. Non-base characters are merged into the cluster of the base character that precedes them. This is similar to the Unicode Grapheme Cluster algorithm, but it is not exactly the same. The output is not forced to be monotone. This is useful for clients that want to use HarfBuzz as a cheap implementation of the Unicode Grapheme Cluster algorithm.

DEFAULT = MONOTONE_GRAPHEMES

Default cluster level, equal to MONOTONE_GRAPHEMES.

Wraps hb_buffer_cluster_level_t.

class uharfbuzz.BufferContentType(*values)

Bases: IntEnum

The type of Buffer contents.

INVALID = 0

Initial value for new buffer.

UNICODE = 1

The buffer contains input characters (before shaping).

GLYPHS = 2

The buffer contains output glyphs (after shaping).

Wraps hb_buffer_content_type_t.

class uharfbuzz.BufferFlags(*values)

Bases: IntFlag

Flags for Buffer.

DEFAULT = 0x00

The default buffer flag.

BOT = 0x01

Flag indicating that special handling of the beginning of text paragraph can be applied to this buffer. Should usually be set, unless you are passing to the buffer only part of the text without the full context.

EOT = 0x02

Flag indicating that special handling of the end of text paragraph can be applied to this buffer, similar to BOT.

PRESERVE_DEFAULT_IGNORABLES = 0x04

Flag indication that character with Default_Ignorable Unicode property should use the corresponding glyph from the font, instead of hiding them (done by replacing them with the space glyph and zeroing the advance width.) This flag takes precedence over REMOVE_DEFAULT_IGNORABLES.

REMOVE_DEFAULT_IGNORABLES = 0x08

Flag indication that character with Default_Ignorable Unicode property should be removed from glyph string instead of hiding them (done by replacing them with the space glyph and zeroing the advance width.) PRESERVE_DEFAULT_IGNORABLES takes precedence over this flag.

DO_NOT_INSERT_DOTTED_CIRCLE = 0x10

Flag indicating that a dotted circle should not be inserted in the rendering of incorrect character sequences (such at <0905 093E>).

VERIFY = 0x20

Flag indicating that the shape() call and its variants should perform various verification processes on the results of the shaping operation on the buffer. If the verification fails, then either a buffer message is sent, if a message handler is installed on the buffer, or a message is written to standard error. In either case, the shaping result might be modified to show the failed output.

PRODUCE_UNSAFE_TO_CONCAT = 0x40

Flag indicating that the GlyphFlags.UNSAFE_TO_CONCAT glyph-flag should be produced by the shaper. By default it will not be produced since it incurs a cost.

PRODUCE_SAFE_TO_INSERT_TATWEEL = 0x80

Flag indicating that the GlyphFlags.SAFE_TO_INSERT_TATWEEL glyph-flag should be produced by the shaper. By default it will not be produced.

Wraps hb_buffer_flags_t.

class uharfbuzz.BufferSerializeFlags(*values)

Bases: IntFlag

Flags that control what glyph information are serialized in Buffer.serialize().

DEFAULT = 0x00

Serialize glyph names, clusters and positions.

NO_CLUSTERS = 0x01

Do not serialize glyph cluster.

NO_POSITIONS = 0x02

Do not serialize glyph position information.

NO_GLYPH_NAMES = 0x04

Do not serialize glyph name.

GLYPH_EXTENTS = 0x08

Serialize glyph extents.

GLYPH_FLAGS = 0x10

Serialize glyph flags.

NO_ADVANCES = 0x20

Do not serialize glyph advances, glyph offsets will reflect absolute glyph positions.

Note: when this flag is used with a partial range of the buffer (i.e. start is not 0), calculating the absolute positions has a cost proportional to start. If the buffer is serialized in many small chunks, this can lead to quadratic behavior. It is recommended to use a larger buf_size to minimize this cost.

Wraps hb_buffer_serialize_flags_t.

class uharfbuzz.BufferSerializeFormat(*values)

Bases: IntEnum

The buffer serialization and de-serialization format used in Buffer.serialize().

TEXT

A human-readable, plain text format.

JSON

A machine-readable JSON format.

INVALID

Invalid format.

Wraps hb_buffer_serialize_format_t.

class uharfbuzz.Color(red: int, green: int, blue: int, alpha: int)

Bases: NamedTuple

A color value. Colors are eight bits per channel RGB plus alpha transparency.

Wraps hb_color_t.

alpha: int

Alpha channel value.

blue: int

Blue channel value.

static from_int(value: int) Color

Construct a Color from an integer representation.

green: int

Green channel value.

red: int

Red channel value.

to_int() int

Returns an int representation of this Color.

class uharfbuzz.ColorLine

Bases: object

A struct containing color information for a gradient.

Wraps hb_color_line_t.

color_stops

Fetches a list of color stops from this color line.

Note that due to variations being applied, the returned color stops may be out of order. It is the caller’s responsibility to ensure that color stops are sorted by their offset before they are used.

Type:

Sequence[ColorStop]

Wraps hb_color_line_get_color_stops().

extend

Fetches the extend mode of this color line.

Type:

PaintExtend

Wraps hb_color_line_get_extend().

class uharfbuzz.ColorStop(offset: float, is_foreground: bool, color: Color)

Bases: NamedTuple

Information about a color stop on a color line.

Color lines typically have offsets ranging between 0 and 1, but that is not required.

The is_foreground and color fields have the same semantics as in the color callback set by PaintFuncs.set_color_func().

Note: despite color being unpremultiplied here, interpolation in gradients shall happen in premultiplied space. See the OpenType spec COLR section for details.

Wraps hb_color_stop_t.

color: Color

The color, unpremultiplied.

is_foreground: bool

Whether the color is the foreground.

offset: float

The offset of the color stop.

class uharfbuzz.DrawFuncs

Bases: object

draw_glyph(font: Font, gid: int, draw_data: object = None)

Deprecated since version 0.34.0.

Use Font.draw_glyph() instead.

get_glyph_shape(font: Font, gid: int)

Deprecated since version 0.34.0.

Use Font.draw_glyph() instead.

set_close_path_func(func: Callable[[object], None], user_data: object = None)
set_cubic_to_func(func: Callable[[float, float, float, float, float, float, object], None], user_data: object = None)
set_line_to_func(func: Callable[[float, float, object], None], user_data: object = None)
set_move_to_func(func: Callable[[float, float, object], None], user_data: object = None)
set_quadratic_to_func(func: Callable[[float, float, float, float, object], None], user_data: object = None)
class uharfbuzz.Face

Bases: object

Font face objects.

A font face is an object that represents a single face from within a font family. More precisely, a font face represents a single face in a binary font file. Font faces are typically built from a binary blob and a face index. Font faces are used to create fonts.

The face index is used for blobs of file formats such as TTC and DFont that can contain more than one face. Face indices within such collections are zero-based.

Parameters:
  • blob – A Blob or bytes containing the font data. If None, the empty face is returned.

  • index – The index of the face within the blob.

Wraps hb_face_t.

axis_infos

A list of all variation axes in the face.

Type:

list[OTVarAxisInfo]

Wraps hb_ot_var_get_axis_infos().

blob

A Blob containing the binary data of the face.

If referencing the face data is not possible, this property creates a blob out of individual table blobs if table_tags works with this face, otherwise it returns an empty blob.

Type:

Blob

Wraps hb_face_reference_blob().

color_palette_color_get_name_id(color_index: int) int | None

Fetches the name table Name ID that provides display names for the specified color in the face’s CPAL color palette.

Parameters:

color_index – The index of the color.

Returns:

The Name ID, or None if the color is not named.

Wraps hb_ot_color_palette_color_get_name_id().

color_palettes

The face’s color palettes.

Type:

list[OTColorPalette]

Wraps hb_ot_color_palette_get_count().

count

The number of faces in the blob.

Wraps hb_face_count().

classmethod create(blob: bytes, index: int = 0) Face

Deprecated since version 0.10.0.

Use Face() instead.

classmethod create_for_tables(func: Callable[[Face, str, object], bytes], user_data: object) Face

Variant of the normal constructor, built for those cases where it is more convenient to provide data for individual tables instead of the whole font data. With the caveat that table_tags would not work with faces created this way. You can address that by calling the set_get_table_tags_func() method and setting the appropriate callback.

Creates a new face object from the specified user_data and func.

Parameters:
  • func – A callback that takes the Face, a table tag, and the user_data and returns the table data as bytes.

  • user_data – User data passed to func on each call.

Wraps hb_face_create_for_tables().

get_color_palette(palette_index: int) OTColorPalette

Fetches the color palette at the specified index.

Parameters:

palette_index – The index of the color palette.

Returns:

An OTColorPalette with the colors, name ID, and flags of the palette.

Wraps hb_ot_color_palette_get_colors(), hb_ot_color_palette_get_name_id(), and hb_ot_color_palette_get_flags().

get_glyph_color_layers(glyph: int) List[OTColorLayer]

Fetches a list of all color layers for the specified glyph index in the face.

Parameters:

glyph – The glyph index to query.

Returns:

The array of layers found.

Wraps hb_ot_color_glyph_get_layers().

get_glyph_color_svg(glyph: int) Blob

Fetches the SVG document for a glyph. The blob may be either plain text or gzip-encoded.

If the glyph has no SVG document, the singleton empty blob is returned.

Parameters:

glyph – An SVG glyph index.

Returns:

A Blob with the content of the SVG document.

Wraps hb_ot_color_glyph_reference_svg().

get_language_feature_tags(tag: str, script_index: int = 0, language_index: int = 65535) List[str]

Fetches a list of all features in the face’s GSUB or GPOS table.

Parameters:
  • tag"GSUB" or "GPOS".

  • script_index – The index of the requested script tag.

  • language_index – The index of the requested language tag.

Returns:

The array of feature tags found for the query.

Wraps hb_ot_layout_language_get_feature_tags().

get_layout_glyph_class(glyph: int) OTLayoutGlyphClass

Fetches the GDEF class of the requested glyph.

Parameters:

glyph – The glyph code point to query.

Returns:

The OTLayoutGlyphClass glyph class of the given code point in the GDEF table of the face.

Wraps hb_ot_layout_get_glyph_class().

get_lookup_glyph_alternates(lookup_index: int, glyph: int) List[int]

Fetches alternates of a glyph from a given GSUB lookup index.

Parameters:
  • lookup_index – Index of the feature lookup to query.

  • glyph – A glyph id.

Returns:

Alternate glyphs associated with the glyph id.

Wraps hb_ot_layout_lookup_get_glyph_alternates().

get_name(name_id: OTNameIdPredefined | int, language: str | None = None) str | None

Fetches a font name from the OpenType name table.

Parameters:
  • name_id – The OpenType name identifier to fetch.

  • language – The BCP 47 language tag to fetch the name for. If None, English ("en") is assumed.

Returns:

The name as a str, or None if not found.

Wraps hb_ot_name_get_utf8().

get_script_language_tags(tag: str, script_index: int = 0) List[str]

Fetches a list of language tags in the face’s GSUB or GPOS table, underneath the specified script index.

Parameters:
  • tag"GSUB" or "GPOS".

  • script_index – The index of the requested script tag.

Returns:

Array of language tags found in the table.

Wraps hb_ot_layout_script_get_language_tags().

get_table_script_tags(tag: str) List[str]

Fetches a list of all scripts enumerated in the specified face’s GSUB or GPOS table.

Parameters:

tag"GSUB" or "GPOS".

Returns:

The array of script tags found for the query.

Wraps hb_ot_layout_table_get_script_tags().

glyph_count

The glyph-count value of the face.

Wraps hb_face_get_glyph_count() / hb_face_set_glyph_count().

glyph_has_color_paint(glyph: int) bool

Tests whether the face includes COLRv1 paint data for glyph.

Parameters:

glyph – The glyph index to query.

Returns:

True if data is found, False otherwise.

Wraps hb_ot_color_glyph_has_paint().

has_color_layers

Whether the face includes a COLR table with data according to COLRv0.

Wraps hb_ot_color_has_layers().

has_color_paint

Whether the face includes a COLR table with data according to COLRv1.

Wraps hb_ot_color_has_paint().

has_color_palettes

Whether the face includes a CPAL color-palette table.

Wraps hb_ot_color_has_palettes().

has_color_png

Whether the face has PNG glyph images (either in CBDT or sbix tables).

Wraps hb_ot_color_has_png().

has_color_svg

Whether the face includes any SVG glyph images.

Wraps hb_ot_color_has_svg().

has_layout_glyph_classes

Whether the face has any glyph classes defined in its GDEF table.

Wraps hb_ot_layout_has_glyph_classes().

has_layout_positioning

Whether the face includes any GPOS positioning.

Wraps hb_ot_layout_has_positioning().

has_layout_substitution

Whether the face includes any GSUB substitutions.

Wraps hb_ot_layout_has_substitution().

has_math_data

Whether the face has a MATH table.

Wraps hb_ot_math_has_data().

has_var_data

Whether the face includes any OpenType variation data in the fvar table.

Wraps hb_ot_var_has_data().

index

The face-index of this face.

Face indices within a collection are zero-based. Changing the index has no effect on the face itself, only on the value returned by this property.

Wraps hb_face_get_index() / hb_face_set_index().

is_glyph_extended_math_shape(glyph: int) bool

Tests whether the given glyph index is an extended shape in the face.

Parameters:

glyph – The glyph index to test.

Returns:

True if the glyph is an extended shape, False otherwise.

Wraps hb_ot_math_is_glyph_extended_shape().

list_names() List[OTNameEntry]

Enumerates all available name IDs and language combinations.

Returns:

Array of available name entries.

Wraps hb_ot_name_list_names().

named_instances

The named instances defined in the face’s fvar table.

Type:

list[OTVarNamedInstance]

Wraps hb_ot_var_get_named_instance_count(), hb_ot_var_named_instance_get_subfamily_name_id(), hb_ot_var_named_instance_get_postscript_name_id(), and hb_ot_var_named_instance_get_design_coords().

reference_table(tag: str) Blob

Fetches a reference to the specified table within the face.

Parameters:

tag – The four-character tag of the table to query.

Returns:

A Blob with the table data, or an empty blob if referencing table data is not possible.

Wraps hb_face_reference_table().

set_get_table_tags_func(func: Callable[[Face, object], List[str]], user_data: object = None)

Sets the implementation function for retrieving the table tags of the face.

Parameters:
  • func – A callback that takes the Face and the user_data and returns the list of table tags as str.

  • user_data – User data passed to func on each call.

Wraps hb_face_set_get_table_tags_func().

table_tags

A list of all table tags for the face, if possible.

Type:

list[str]

Wraps hb_face_get_table_tags().

unicodes

All Unicode characters covered by the face.

Type:

Set

Wraps hb_face_collect_unicodes().

upem

The units-per-em (UPEM) value of the face.

Typical UPEM values for fonts are 1000, or 2048, but any value in between 16 and 16,384 is allowed for OpenType fonts.

Wraps hb_face_get_upem() / hb_face_set_upem().

variation_selectors

All Unicode “Variation Selector” characters covered by the face.

Type:

Set

Wraps hb_face_collect_variation_selectors().

variation_unicodes(variation_selector: int) Set[int]

All Unicode characters for variation_selector covered by the face.

Parameters:

variation_selector – The Variation Selector to query.

Returns:

The Set of Unicode characters.

Wraps hb_face_collect_variation_unicodes().

class uharfbuzz.Font

Bases: object

Font objects.

A font object represents a font face at a specific size and with certain other parameters (pixels-per-em, points-per-em, variation settings) specified. Font objects are created from font face objects, and are used as input to shape(), among other things.

Client programs can optionally pass in their own functions that implement the basic, lower-level queries of font objects. This set of font functions is defined by the virtual methods in FontFuncs.

Parameters:

face_or_font – A Face to create a font from, or another Font to create a sub-font from. If None, the empty font is returned.

Wraps hb_font_t.

classmethod create(face: Face) Font

Deprecated since version 0.10.0.

Use Font() instead.

draw_glyph(gid: int, draw_funcs: DrawFuncs, draw_state: object = None)

Draws the outline that corresponds to a glyph in the font.

The outline is returned by way of calls to the callbacks of the draw_funcs object, with draw_state passed to them.

Parameters:
  • gid – The glyph ID.

  • draw_funcs – The DrawFuncs to draw to.

  • draw_state – User data to pass to the draw callbacks.

Wraps hb_font_draw_glyph().

draw_glyph_with_pen(gid: int, pen)

Draws the outline of a glyph using a fontTools-style pen.

Parameters:
  • gid – The glyph ID.

  • pen – An object with moveTo, lineTo, curveTo, qCurveTo, and closePath methods.

face

The Face associated with this font.

Type:

Face

Wraps hb_font_get_face().

funcs

The font-functions structure attached to this font.

Assigning to this property replaces the font-functions structure attached to the font.

Type:

FontFuncs

Wraps hb_font_set_funcs().

get_font_extents(direction: str) FontExtents

Fetches the extents for a font in a text segment of the specified direction.

Calls the appropriate direction-specific variant (horizontal or vertical) depending on the value of direction.

Parameters:

direction – The direction of the text segment.

Returns:

The FontExtents retrieved.

Wraps hb_font_get_extents_for_direction().

get_glyph_color_png(glyph: int) Blob

Fetches the PNG image for a glyph. This function takes a font object, not a face object, as input. To get an optimally sized PNG blob, the PPEM values must be set on the font object. If PPEM is unset, the blob returned will be the largest PNG available.

If the glyph has no PNG image, the singleton empty blob is returned.

Wraps hb_ot_color_glyph_reference_png().

get_glyph_extents(gid: int) GlyphExtents

Fetches the GlyphExtents data for a glyph ID.

Parameters:

gid – The glyph ID to query.

Returns:

The GlyphExtents retrieved, or None if not found.

Wraps hb_font_get_glyph_extents().

get_glyph_from_name(name: str) int | None

Fetches the glyph ID that corresponds to a name string in the font.

Parameters:

name – The name to query.

Returns:

The glyph ID retrieved, or None if not found.

Wraps hb_font_get_glyph_from_name().

get_glyph_h_advance(gid: int) int

Fetches the advance for a glyph ID, for horizontal text segments.

Wraps hb_font_get_glyph_h_advance().

get_glyph_h_origin(gid: int) Tuple[int, int] | None

Fetches the (X, Y) coordinates of the origin for a glyph ID, for horizontal text segments.

Returns:

The (X, Y) coordinates of the origin, or None if not found.

Wraps hb_font_get_glyph_h_origin().

get_glyph_name(gid: int) str | None

Fetches the glyph-name string for a glyph ID in the font.

According to the OpenType specification, glyph names are limited to 63 characters and can only contain (a subset of) ASCII.

Parameters:

gid – The glyph ID to query.

Returns:

Name string retrieved for the glyph ID, or None if not found.

Wraps hb_font_get_glyph_name().

get_glyph_v_advance(gid: int) int

Fetches the advance for a glyph ID, for vertical text segments.

Wraps hb_font_get_glyph_v_advance().

get_glyph_v_origin(gid: int) Tuple[int, int] | None

Fetches the (X, Y) coordinates of the origin for a glyph ID, for vertical text segments.

Returns:

The (X, Y) coordinates of the origin, or None if not found.

Wraps hb_font_get_glyph_v_origin().

get_layout_baseline(baseline_tag: str, direction: str, script_tag: str, language_tag: str) int

Fetches a baseline value from the font.

Parameters:
  • baseline_tag – A baseline tag.

  • direction – Text direction.

  • script_tag – Script tag.

  • language_tag – Language tag, currently unused.

Returns:

The baseline value if found, or None otherwise.

Raises:

ValueError – If baseline_tag is not recognized.

Wraps hb_ot_layout_get_baseline().

get_math_constant(constant: OTMathConstant) int

Fetches the specified math constant.

For most constants, the value returned is a position. However, if the requested constant is OTMathConstant.SCRIPT_PERCENT_SCALE_DOWN, OTMathConstant.SCRIPT_SCRIPT_PERCENT_SCALE_DOWN or OTMathConstant.RADICAL_DEGREE_BOTTOM_RAISE_PERCENT, then the return value is an integer between 0 and 100 representing that percentage.

Raises:

ValueError – If constant is not a valid OTMathConstant.

Wraps hb_ot_math_get_constant().

get_math_glyph_assembly(glyph: int, direction: str) Tuple[List[OTMathGlyphPart], int]

Fetches the GlyphAssembly for the specified font, glyph index, and direction.

Returns:

A tuple (parts, italics_correction) of the glyph parts returned and the italics correction of the glyph assembly.

Wraps hb_ot_math_get_glyph_assembly().

get_math_glyph_italics_correction(glyph: int) int

Fetches an italics-correction value (if one exists) for the specified glyph index.

Wraps hb_ot_math_get_glyph_italics_correction().

get_math_glyph_kerning(glyph: int, kern: OTMathKern, correction_height: int) int

Fetches the math kerning (cut-ins) value for the specified font, glyph index, and kern.

Raises:

ValueError – If kern is not a valid OTMathKern.

Wraps hb_ot_math_get_glyph_kerning().

get_math_glyph_kernings(glyph: int, kern: OTMathKern) List[OTMathKernEntry]

Fetches the raw MathKern (cut-in) data for the specified font, glyph index, and kern.

Raises:

ValueError – If kern is not a valid OTMathKern.

Wraps hb_ot_math_get_glyph_kernings().

get_math_glyph_top_accent_attachment(glyph: int) int

Fetches a top-accent-attachment value (if one exists) for the specified glyph index.

Wraps hb_ot_math_get_glyph_top_accent_attachment().

get_math_glyph_variants(glyph: int, direction: str) List[OTMathGlyphVariant]

Fetches the MathGlyphConstruction for the specified font, glyph index, and direction.

Wraps hb_ot_math_get_glyph_variants().

get_math_min_connector_overlap(direction: str) int

Fetches the MathVariants table for the font and returns the minimum overlap of connecting glyphs that are required to draw a glyph assembly in the specified direction.

Wraps hb_ot_math_get_min_connector_overlap().

get_metric_position(tag: OTMetricsTag) int | None

Fetches metrics value corresponding to tag from the font.

Returns:

The metrics value from the font, or None if not found.

Wraps hb_ot_metrics_get_position().

get_metric_position_with_fallback(tag: OTMetricsTag) int

Fetches metrics value corresponding to tag from the font, and synthesizes a value if the value is missing in the font.

Wraps hb_ot_metrics_get_position_with_fallback().

get_metric_variation(tag: OTMetricsTag) float

Fetches metrics value corresponding to tag from the font with the current font variation settings applied.

Wraps hb_ot_metrics_get_variation().

get_metric_x_variation(tag: OTMetricsTag) int

Fetches horizontal metrics value corresponding to tag from the font with the current font variation settings applied.

Wraps hb_ot_metrics_get_x_variation().

get_metric_y_variation(tag: OTMetricsTag) int

Fetches vertical metrics value corresponding to tag from the font with the current font variation settings applied.

Wraps hb_ot_metrics_get_y_variation().

get_nominal_glyph(unicode: int) int | None

Fetches the nominal glyph ID for a Unicode code point.

Returns:

The glyph ID retrieved, or None if not found.

Wraps hb_font_get_nominal_glyph().

get_style_value(tag: StyleTag) float

Searches variation axes of the font for a specific axis first; if not set, first tries to get default style values in the STAT table, then tries to polyfill from different tables of the font.

Returns:

Corresponding axis or default value to a style tag.

Wraps hb_style_get_value().

get_var_coords_design()

Fetches the list of variation coordinates (in design-space units) currently set on the font.

Wraps hb_font_get_var_coords_design().

get_var_coords_normalized() List[float]

Fetches the list of normalized variation coordinates currently set on the font.

Returns:

The coordinates array.

Wraps hb_font_get_var_coords_normalized().

get_variation_glyph(unicode: int, variation_selector: int) int | None

Fetches the glyph ID for a Unicode code point when followed by the specified variation-selector code point.

Returns:

The glyph ID retrieved, or None if not found.

Wraps hb_font_get_variation_glyph().

glyph_from_string(string: str) int

Fetches the glyph ID that matches the specified string.

Strings of the format gidDDD or uniUUUU are parsed automatically.

Returns:

The glyph ID corresponding to the string requested, or None if not found.

Wraps hb_font_glyph_from_string().

glyph_to_string(gid: int) str

Fetches the name of the specified glyph ID.

If the glyph ID has no name, a string of the form gidDDD is generated, with DDD being the glyph ID.

Wraps hb_font_glyph_to_string().

paint_glyph(gid: int, paint_funcs: PaintFuncs, paint_state: object = None, palette_index: int = 0, foreground: Color | None = None)

Paints the glyph. If painting a color glyph failed, it will fall back to painting an outline monochrome glyph.

The painting instructions are returned by way of calls to the callbacks of the paint_funcs object, with paint_state passed to them.

Parameters:
  • gid – The glyph ID.

  • paint_funcs – The PaintFuncs to paint with.

  • paint_state – User data to pass to the paint callbacks.

  • palette_index – The index of the font’s color palette to use.

  • foreground – The foreground color, unpremultiplied.

Wraps hb_font_paint_glyph().

ppem

The horizontal and vertical pixels-per-em (PPEM) of the font, as a (x_ppem, y_ppem) tuple.

These values are used for pixel-size-specific adjustment to shaping and draw results, though for the most part they are unused and can be left unset.

Wraps hb_font_get_ppem() / hb_font_set_ppem().

ptem

The “point size” of the font. Set to zero to unset. Used in CoreText to implement optical sizing.

Note: there are 72 points in an inch.

Wraps hb_font_get_ptem() / hb_font_set_ptem().

scale

The horizontal and vertical scale of the font, as a (x_scale, y_scale) tuple.

The font scale is a number related to, but not the same as, font size. Typically the client establishes a scale factor to be used between the two. For example, 64, or 256, which would be the fractional-precision part of the font scale. This is necessary because position values are integer types and you need to leave room for fractional values in there.

For example, to set the font size to 20, with 64 levels of fractional precision you would call font.scale = (20 * 64, 20 * 64).

In the example above, even what font size 20 means is up to you. It might be 20 pixels, or 20 points, or 20 millimeters. HarfBuzz does not care about that. You can set the point size of the font using ptem, and the pixel size using ppem.

The choice of scale is yours but needs to be consistent between what you set here, and what you expect out of position values as well has draw / paint API output values.

Fonts default to a scale equal to the UPEM value of their face. A font with this setting is sometimes called an “unscaled” font.

Wraps hb_font_get_scale() / hb_font_set_scale().

set_var_coords_design(coords: List[float])

Applies a list of variation coordinates (in design-space units) to the font.

Note that this overrides all existing variations set on the font. Axes not included in coords will be effectively set to their default values.

Wraps hb_font_set_var_coords_design().

set_var_coords_normalized(coords: List[float])

Applies a list of variation coordinates (in normalized units) to the font.

Note that this overrides all existing variations set on the font. Axes not included in coords will be effectively set to their default values.

Wraps hb_font_set_var_coords_normalized().

set_variation(name: str, value: float)

Change the value of one variation axis on the font.

Note: this method is expensive to be called repeatedly. If you want to set multiple variation axes at the same time, use set_variations() instead.

Parameters:
  • name – The axis tag.

  • value – The value of the variation axis.

Wraps hb_font_set_variation().

set_variations(variations: Dict[str, float])

Applies a list of font-variation settings to the font.

Note that this overrides all existing variations set on the font. Axes not included in variations will be effectively set to their default values.

Parameters:

variations – A mapping of axis-tag string to value.

Wraps hb_font_set_variations().

synthetic_bold

The “synthetic boldness” of the font, as a tuple (x_embolden, y_embolden, in_place).

Positive values for x_embolden / y_embolden make a font bolder, negative values thinner. Typical values are in the 0.01 to 0.05 range. The default value is zero.

If in_place is False, then glyph advance-widths are also adjusted, otherwise they are not. The in-place mode is useful for simulating font grading.

The setter accepts a float (applied to both axes, in_place=False), a 1-tuple, a 2-tuple, or a 3-tuple.

Wraps hb_font_get_synthetic_bold() / hb_font_set_synthetic_bold().

synthetic_slant

The “synthetic slant” of the font. By default is zero. Synthetic slant is the graphical skew applied to the font at rendering time.

HarfBuzz needs to know this value to adjust shaping results, metrics, and style values to match the slanted rendering.

The slant value is a ratio. For example, a 20% slant would be represented as a 0.2 value.

Wraps hb_font_get_synthetic_slant() / hb_font_set_synthetic_slant().

var_named_instance

The currently-set named-instance index of the font.

Wraps hb_font_get_var_named_instance() / hb_font_set_var_named_instance().

class uharfbuzz.FontExtents(ascender: int, descender: int, line_gap: int)

Bases: NamedTuple

Font-wide extent values, measured in scaled units.

Note that typically ascender is positive and descender negative, in coordinate systems that grow up.

Wraps hb_font_extents_t.

ascender: int

The height of typographic ascenders.

descender: int

The depth of typographic descenders.

line_gap: int

The suggested line-spacing gap.

class uharfbuzz.FontFuncs

Bases: object

The virtual methods that define the font functions used by a Font for the basic, lower-level queries against a font object.

Wraps hb_font_funcs_t.

classmethod create() FontFuncs

Deprecated since version 0.10.0.

Use FontFuncs() instead.

set_font_h_extents_func(func: Callable[[Font, object], FontExtents], user_data: object = None)

Sets the implementation function for the horizontal-font-extents callback.

Wraps hb_font_funcs_set_font_h_extents_func().

set_font_v_extents_func(func: Callable[[Font, object], FontExtents], user_data: object = None)

Sets the implementation function for the vertical-font-extents callback.

Wraps hb_font_funcs_set_font_v_extents_func().

set_glyph_h_advance_func(func: Callable[[Font, int, object], int], user_data: object = None)

Sets the implementation function for the horizontal-glyph-advance callback.

Wraps hb_font_funcs_set_glyph_h_advance_func().

set_glyph_name_func(func: Callable[[Font, int, object], str], user_data: object = None)

Sets the implementation function for the glyph-name callback.

Wraps hb_font_funcs_set_glyph_name_func().

set_glyph_v_advance_func(func: Callable[[Font, int, object], int], user_data: object = None)

Sets the implementation function for the vertical-glyph-advance callback.

Wraps hb_font_funcs_set_glyph_v_advance_func().

set_glyph_v_origin_func(func: Callable[[Font, int, object], int, int, int], user_data: object = None)

Sets the implementation function for the vertical-glyph-origin callback. The callback must return a (success, x, y) tuple.

Wraps hb_font_funcs_set_glyph_v_origin_func().

set_nominal_glyph_func(func: Callable[[Font, int, object], int], user_data: object = None)

Sets the implementation function for the nominal-glyph callback.

Wraps hb_font_funcs_set_nominal_glyph_func().

set_variation_glyph_func(func: Callable[[Font, int, int, object], int], user_data: object = None)

Sets the implementation function for the variation-glyph callback.

Wraps hb_font_funcs_set_variation_glyph_func().

class uharfbuzz.GlyphExtents(x_bearing: int, y_bearing: int, width: int, height: int)

Bases: NamedTuple

Glyph extent values, measured in font units.

Note that height is negative, in coordinate systems that grow up.

Wraps hb_glyph_extents_t.

height: int

Distance from the top extremum of the glyph to the bottom extremum.

width: int

Distance from the left extremum of the glyph to the right extremum.

x_bearing: int

Distance from the x-origin to the left extremum of the glyph.

y_bearing: int

Distance from the top extremum of the glyph to the y-origin.

class uharfbuzz.GlyphFlags(*values)

Bases: IntFlag

Flags for GlyphInfo.

UNSAFE_TO_BREAK = 0x01

Indicates that if input text is broken at the beginning of the cluster this glyph is part of, then both sides need to be re-shaped, as the result might be different. On the flip side, it means that when this flag is not present, then it is safe to break the glyph-run at the beginning of this cluster, and the two sides will represent the exact same result one would get if breaking input text at the beginning of this cluster and shaping the two sides separately. This can be used to optimize paragraph layout, by avoiding re-shaping of each line after line-breaking.

UNSAFE_TO_CONCAT = 0x02

Indicates that if input text is changed on one side of the beginning of the cluster this glyph is part of, then the shaping results for the other side might change. Note that the absence of this flag will NOT by itself mean that it IS safe to concat text. Only two pieces of text both of which clear of this flag can be concatenated safely. This can be used to optimize paragraph layout, by avoiding re-shaping of each line after line-breaking, by limiting the reshaping to a small piece around the breaking position only, even if the breaking position carries the UNSAFE_TO_BREAK or when hyphenation or other text transformation happens at line-break position, in the following way: 1. Iterate back from the line-break position until the first cluster start position that is NOT unsafe-to-concat, 2. shape the segment from there till the end of line, 3. check whether the resulting glyph-run also is clear of the unsafe-to-concat at its start-of-text position; if it is, just splice it into place and the line is shaped; If not, move on to a position further back that is clear of unsafe-to-concat and retry from there, and repeat. At the start of next line a similar algorithm can be implemented. That is: 1. Iterate forward from the line-break position until the first cluster start position that is NOT unsafe-to-concat, 2. shape the segment from beginning of the line to that position, 3. check whether the resulting glyph-run also is clear of the unsafe-to-concat at its end-of-text position; if it is, just splice it into place and the beginning is shaped; If not, move on to a position further forward that is clear of unsafe-to-concat and retry up to there, and repeat. A slight complication will arise in the implementation of the algorithm above, because while our buffer API has a way to return flags for position corresponding to start-of-text, there is currently no position corresponding to end-of-text. This limitation can be alleviated by shaping more text than needed and looking for unsafe-to-concat flag within text clusters. The UNSAFE_TO_BREAK flag will always imply this flag. To use this flag, you must enable the buffer flag BufferFlags.PRODUCE_UNSAFE_TO_CONCAT during shaping, otherwise the buffer flag will not be reliably produced.

SAFE_TO_INSERT_TATWEEL = 0x04

In scripts that use elongation (Arabic, Mongolian, Syriac, etc.), this flag signifies that it is safe to insert a U+0640 TATWEEL character before this cluster for elongation. This flag does not determine the script-specific elongation places, but only when it is safe to do the elongation without interrupting text shaping.

Wraps hb_glyph_flags_t.

class uharfbuzz.GlyphInfo

Bases: object

The structure that holds information about the glyphs and their relation to input text.

Wraps hb_glyph_info_t.

cluster

The index of the character in the original text that corresponds to this GlyphInfo, or whatever the client passes to Buffer.add_codepoints(). More than one GlyphInfo can have the same cluster value, if they resulted from the same character (e.g. one to many glyph substitution), and when more than one character gets merged in the same glyph (e.g. many to one glyph substitution) the GlyphInfo will have the smallest cluster value of them. By default some characters are merged into the same cluster (e.g. combining marks have the same cluster as their bases) even if they are separate glyphs, Buffer.cluster_level allows selecting more fine-grained cluster handling.

codepoint

Either a Unicode code point (before shaping) or a glyph index (after shaping).

flags

Glyph flags encoded within a GlyphInfo.

Type:

GlyphFlags

Wraps hb_glyph_info_get_glyph_flags().

class uharfbuzz.GlyphPosition

Bases: object

The structure that holds the positions of the glyph in both horizontal and vertical directions. All positions in GlyphPosition are relative to the current point.

Wraps hb_glyph_position_t.

position

A tuple of (x_offset, y_offset, x_advance, y_advance).

x_advance

How much the line advances after drawing this glyph when setting text in horizontal direction.

x_offset

How much the glyph moves on the X-axis before drawing it, this should not affect how much the line advances.

y_advance

How much the line advances after drawing this glyph when setting text in vertical direction.

y_offset

How much the glyph moves on the Y-axis before drawing it, this should not affect how much the line advances.

class uharfbuzz.HBObject

Bases: object

Represents an array of objects in the object graph to be serialized. Used internally by serialize() and serialize_with_tag().

Wraps hb_subset_serialize_object_t.

exception uharfbuzz.HarfBuzzError

Bases: Exception

class uharfbuzz.Map

Bases: object

Data type for holding integer-to-integer hash maps.

INVALID_VALUE

Unset map value.

Wraps HB_MAP_VALUE_INVALID.

Wraps hb_map_t.

clear()

Clears out the contents of this map.

Wraps hb_map_clear().

copy() Map

Allocate a copy of this map.

Returns:

Newly-allocated map.

Wraps hb_map_copy().

get(k: int)

Fetches the value stored for k in this map.

Parameters:

k – The key to query.

Returns:

The value stored for k, or None if k is not in the map.

Wraps hb_map_get().

items()

Returns an iterator over (key, value) pairs in this map.

The order in which the pairs are returned is undefined.

keys()

Returns an iterator over the keys in this map.

The order in which the keys are returned is undefined.

update(other)

Add the contents of other to this map.

Parameters:

other – Another Map, or any mapping of integer keys to integer values.

Wraps hb_map_update().

values()

Returns an iterator over the values in this map.

The order in which the values are returned is undefined.

class uharfbuzz.MapIter

Bases: object

Iterator over (key, value) pairs in a Map.

Wraps hb_map_next().

class uharfbuzz.OTColor(red: int, green: int, blue: int, alpha: int)

Bases: Color

A Color from a font’s color palette, together with its name ID.

name_id: int | None
class uharfbuzz.OTColorLayer(glyph: int, color_index: int)

Bases: NamedTuple

A pair of glyph and color index.

A color index of 0xFFFF does not refer to a palette color, but indicates that the foreground color should be used.

Wraps hb_ot_color_layer_t.

color_index: int

The palette color index of the layer.

glyph: int

The glyph ID of the layer.

class uharfbuzz.OTColorPalette(colors: List[OTColor], name_id: int | None, flags: OTColorPaletteFlags)

Bases: NamedTuple

A color palette from a font’s CPAL table.

colors: List[OTColor]

The colors that make up the palette.

flags: OTColorPaletteFlags

The OTColorPaletteFlags flags for the palette.

name_id: int | None

The name table Name ID that provides display names for the palette, or None if no name is associated.

class uharfbuzz.OTColorPaletteFlags(*values)

Bases: IntFlag

Flags that describe the properties of a color palette.

DEFAULT = 0x00

Default indicating that there is nothing special to note about a color palette.

USABLE_WITH_LIGHT_BACKGROUND = 0x01

Flag indicating that the color palette is appropriate to use when displaying the font on a light background such as white.

USABLE_WITH_DARK_BACKGROUND = 0x02

Flag indicating that the color palette is appropriate to use when displaying the font on a dark background such as black.

Wraps hb_ot_color_palette_flags_t.

class uharfbuzz.OTLayoutGlyphClass(*values)

Bases: IntEnum

The GDEF classes defined for glyphs.

UNCLASSIFIED = 0

Glyphs not matching the other classifications.

BASE_GLYPH = 1

Spacing, single characters, capable of accepting marks.

LIGATURE = 2

Glyphs that represent ligation of multiple characters.

MARK = 3

Non-spacing, combining glyphs that represent marks.

COMPONENT = 4

Spacing glyphs that represent part of a single character.

Wraps hb_ot_layout_glyph_class_t.

class uharfbuzz.OTMathConstant(*values)

Bases: IntEnum

Math constants from the OpenType MATH table.

Wraps hb_ot_math_constant_t.

ACCENT_BASE_HEIGHT = 6
AXIS_HEIGHT = 5
DELIMITED_SUB_FORMULA_MIN_HEIGHT = 2
DISPLAY_OPERATOR_MIN_HEIGHT = 3
FLATTENED_ACCENT_BASE_HEIGHT = 7
FRACTION_DENOMINATOR_DISPLAY_STYLE_SHIFT_DOWN = 35
FRACTION_DENOMINATOR_GAP_MIN = 39
FRACTION_DENOMINATOR_SHIFT_DOWN = 34
FRACTION_DENOM_DISPLAY_STYLE_GAP_MIN = 40
FRACTION_NUMERATOR_DISPLAY_STYLE_SHIFT_UP = 33
FRACTION_NUMERATOR_GAP_MIN = 36
FRACTION_NUMERATOR_SHIFT_UP = 32
FRACTION_NUM_DISPLAY_STYLE_GAP_MIN = 37
FRACTION_RULE_THICKNESS = 38
LOWER_LIMIT_BASELINE_DROP_MIN = 21
LOWER_LIMIT_GAP_MIN = 20
MATH_LEADING = 4
OVERBAR_EXTRA_ASCENDER = 45
OVERBAR_RULE_THICKNESS = 44
OVERBAR_VERTICAL_GAP = 43
RADICAL_DEGREE_BOTTOM_RAISE_PERCENT = 55
RADICAL_DISPLAY_STYLE_VERTICAL_GAP = 50
RADICAL_EXTRA_ASCENDER = 52
RADICAL_KERN_AFTER_DEGREE = 54
RADICAL_KERN_BEFORE_DEGREE = 53
RADICAL_RULE_THICKNESS = 51
RADICAL_VERTICAL_GAP = 49
SCRIPT_PERCENT_SCALE_DOWN = 0
SCRIPT_SCRIPT_PERCENT_SCALE_DOWN = 1
SKEWED_FRACTION_HORIZONTAL_GAP = 41
SKEWED_FRACTION_VERTICAL_GAP = 42
SPACE_AFTER_SCRIPT = 17
STACK_BOTTOM_DISPLAY_STYLE_SHIFT_DOWN = 25
STACK_BOTTOM_SHIFT_DOWN = 24
STACK_DISPLAY_STYLE_GAP_MIN = 27
STACK_GAP_MIN = 26
STACK_TOP_DISPLAY_STYLE_SHIFT_UP = 23
STACK_TOP_SHIFT_UP = 22
STRETCH_STACK_BOTTOM_SHIFT_DOWN = 29
STRETCH_STACK_GAP_ABOVE_MIN = 30
STRETCH_STACK_GAP_BELOW_MIN = 31
STRETCH_STACK_TOP_SHIFT_UP = 28
SUBSCRIPT_BASELINE_DROP_MIN = 10
SUBSCRIPT_SHIFT_DOWN = 8
SUBSCRIPT_TOP_MAX = 9
SUB_SUPERSCRIPT_GAP_MIN = 15
SUPERSCRIPT_BASELINE_DROP_MAX = 14
SUPERSCRIPT_BOTTOM_MAX_WITH_SUBSCRIPT = 16
SUPERSCRIPT_BOTTOM_MIN = 13
SUPERSCRIPT_SHIFT_UP = 11
SUPERSCRIPT_SHIFT_UP_CRAMPED = 12
UNDERBAR_EXTRA_DESCENDER = 48
UNDERBAR_RULE_THICKNESS = 47
UNDERBAR_VERTICAL_GAP = 46
UPPER_LIMIT_BASELINE_RISE_MIN = 19
UPPER_LIMIT_GAP_MIN = 18
class uharfbuzz.OTMathGlyphPart(glyph: int, start_connector_length: int, end_connector_length: int, full_advance: int, flags: OTMathGlyphPartFlags)

Bases: NamedTuple

Information for a “part” component of a math-variant glyph. Large variants for stretchable math glyphs (such as parentheses) can be constructed on the fly from parts.

Wraps hb_ot_math_glyph_part_t.

end_connector_length: int

The length of the connector on the ending side of the variant part.

flags: OTMathGlyphPartFlags

OTMathGlyphPartFlags flags for the part.

full_advance: int

The total advance of the part.

glyph: int

The glyph index of the variant part.

start_connector_length: int

The length of the connector on the starting side of the variant part.

class uharfbuzz.OTMathGlyphPartFlags(*values)

Bases: IntFlag

Flags for math glyph parts.

EXTENDER = 0x01

This is an extender glyph part that can be repeated to reach the desired length.

Wraps hb_ot_math_glyph_part_flags_t.

class uharfbuzz.OTMathGlyphVariant(glyph: int, advance: int)

Bases: NamedTuple

Math-variant information for a glyph.

Wraps hb_ot_math_glyph_variant_t.

advance: int

The advance width of the variant.

glyph: int

The glyph index of the variant.

class uharfbuzz.OTMathKern(*values)

Bases: IntEnum

The math kerning-table types defined for the four corners of a glyph.

TOP_RIGHT = 0

The top right corner of the glyph.

TOP_LEFT = 1

The top left corner of the glyph.

BOTTOM_RIGHT = 2

The bottom right corner of the glyph.

BOTTOM_LEFT = 3

The bottom left corner of the glyph.

Wraps hb_ot_math_kern_t.

class uharfbuzz.OTMathKernEntry(max_correction_height: int, kern_value: int)

Bases: NamedTuple

Math kerning (cut-in) information for a glyph.

Wraps hb_ot_math_kern_entry_t.

kern_value: int

The kern value of the entry.

max_correction_height: int

The maximum height at which this entry should be used.

class uharfbuzz.OTMetricsTag(*values)

Bases: IntEnum

Metric tags corresponding to MVAR Value Tags.

Wraps hb_ot_metrics_tag_t.

class uharfbuzz.OTNameEntry(name_id: OTNameIdPredefined | int, language: str | None)

Bases: NamedTuple

Structure representing a name ID in a particular language.

Wraps hb_ot_name_entry_t.

language: str | None

The BCP 47 language tag, or None if the language cannot be determined.

name_id: OTNameIdPredefined | int

The name ID, as an OTNameIdPredefined value or a raw int if it does not match any of the predefined ones.

class uharfbuzz.OTNameIdPredefined(*values)

Bases: IntEnum

Predefined values for the OpenType name table Name ID.

COPYRIGHT

Copyright notice.

FONT_FAMILY

Font Family name.

FONT_SUBFAMILY

Font Subfamily name.

UNIQUE_ID

Unique font identifier.

FULL_NAME

Full font name that reflects all family and relevant subfamily descriptors.

VERSION_STRING

Version string.

POSTSCRIPT_NAME

PostScript name for the font.

TRADEMARK

Trademark.

MANUFACTURER

Manufacturer name.

DESIGNER

Designer.

DESCRIPTION

Description.

VENDOR_URL

URL of font vendor.

DESIGNER_URL

URL of typeface designer.

LICENSE

License description.

LICENSE_URL

License information URL.

TYPOGRAPHIC_FAMILY

Typographic family name.

TYPOGRAPHIC_SUBFAMILY

Typographic subfamily name.

MAC_FULL_NAME

Compatible full name (Macintosh only).

SAMPLE_TEXT

Sample text.

CID_FINDFONT_NAME

PostScript CID findfont name.

WWS_FAMILY

WWS family name.

WWS_SUBFAMILY

WWS subfamily name.

LIGHT_BACKGROUND

Light background palette.

DARK_BACKGROUND

Dark background palette.

VARIATIONS_PS_PREFIX

Variations PostScript name prefix.

INVALID

Value to represent a nonexistent name ID.

Wraps hb_ot_name_id_predefined_t.

class uharfbuzz.OTVarAxisFlags(*values)

Bases: IntFlag

Flags for OTVarAxisInfo.

HIDDEN = 0x01

The axis should not be exposed directly in user interfaces.

Wraps hb_ot_var_axis_flags_t.

class uharfbuzz.OTVarAxisInfo(axis_index: int, tag: str, name_id: int, flags: OTVarAxisFlags, min_value: float, default_value: float, max_value: float)

Bases: NamedTuple

Data type for holding variation-axis values.

Wraps hb_ot_var_axis_info_t.

axis_index: int

Index of the axis in the variation-axis array.

default_value: float

The position on the variation axis corresponding to the font’s defaults.

flags: OTVarAxisFlags

The OTVarAxisFlags flags for the axis.

max_value: float

The maximum value on the variation axis that the font covers.

min_value: float

The minimum value on the variation axis that the font covers.

name_id: int

The name table Name ID that provides display names for the axis.

tag: str

The tag identifying the design variation of the axis.

class uharfbuzz.OTVarNamedInstance(subfamily_name_id: int, postscript_name_id: int, design_coords: List[float])

Bases: NamedTuple

A named instance defined in the font’s fvar table.

design_coords: List[float]

The design-space coordinates corresponding to the named instance.

postscript_name_id: int

The name table Name ID that provides display names for the “PostScript name” defined for the given named instance.

subfamily_name_id: int

The name table Name ID that provides display names for the “Subfamily name” defined for the given named instance.

class uharfbuzz.PaintCompositeMode(*values)

Bases: IntEnum

The values of this enumeration describe the compositing modes that can be used when combining temporary redirected drawing with the backdrop.

See the OpenType spec COLR section for details.

CLEAR

Clear destination layer (bounded).

SRC

Replace destination layer (bounded).

DEST

Ignore the source.

SRC_OVER

Draw source layer on top of destination layer (bounded).

DEST_OVER

Draw destination on top of source.

SRC_IN

Draw source where there was destination content (unbounded).

DEST_IN

Leave destination only where there was source content (unbounded).

SRC_OUT

Draw source where there was no destination content (unbounded).

DEST_OUT

Leave destination only where there was no source content.

SRC_ATOP

Draw source on top of destination content and only there.

DEST_ATOP

Leave destination on top of source content and only there (unbounded).

XOR

Source and destination are shown where there is only one of them.

PLUS

Source and destination layers are accumulated.

SCREEN

Source and destination are complemented and multiplied. This causes the result to be at least as light as the lighter inputs.

OVERLAY

Multiplies or screens, depending on the lightness of the destination color.

DARKEN

Replaces the destination with the source if it is darker, otherwise keeps the source.

LIGHTEN

Replaces the destination with the source if it is lighter, otherwise keeps the source.

COLOR_DODGE

Brightens the destination color to reflect the source color.

COLOR_BURN

Darkens the destination color to reflect the source color.

HARD_LIGHT

Multiplies or screens, dependent on source color.

SOFT_LIGHT

Darkens or lightens, dependent on source color.

DIFFERENCE

Takes the difference of the source and destination color.

EXCLUSION

Produces an effect similar to difference, but with lower contrast.

MULTIPLY

Source and destination layers are multiplied. This causes the result to be at least as dark as the darker inputs.

HSL_HUE

Creates a color with the hue of the source and the saturation and luminosity of the target.

HSL_SATURATION

Creates a color with the saturation of the source and the hue and luminosity of the target. Painting with this mode onto a gray area produces no change.

HSL_COLOR

Creates a color with the hue and saturation of the source and the luminosity of the target. This preserves the gray levels of the target and is useful for coloring monochrome images or tinting color images.

HSL_LUMINOSITY

Creates a color with the luminosity of the source and the hue and saturation of the target. This produces an inverse effect to HSL_COLOR.

Wraps hb_paint_composite_mode_t.

class uharfbuzz.PaintExtend(*values)

Bases: IntEnum

The values of this enumeration determine how color values outside the minimum and maximum defined offset on a ColorLine are determined.

See the OpenType spec COLR section for details.

PAD

Outside the defined interval, the color of the closest color stop is used.

REPEAT

The color line is repeated over repeated multiples of the defined interval.

REFLECT

The color line is repeated over repeated intervals, as for the repeat mode. However, in each repeated interval, the ordering of color stops is the reverse of the adjacent interval.

Wraps hb_paint_extend_t.

class uharfbuzz.PaintFuncs

Bases: object

Glyph paint callbacks.

The callbacks assume that the caller maintains a stack of current transforms, clips and intermediate surfaces, as evidenced by the pairs of push/pop callbacks. The push/pop calls will be properly nested, so it is fine to store the different kinds of object on a single stack.

Not all callbacks are required for all kinds of glyphs. For rendering COLRv0 or non-color outline glyphs, the gradient callbacks are not needed, and the composite callback only needs to handle simple alpha compositing (PaintCompositeMode.SRC_OVER).

The paint-image callback is only needed for glyphs with image blobs in the CBDT, sbix or SVG tables.

The custom-palette-color callback is only necessary if you want to override colors from the font palette with custom colors.

Wraps hb_paint_funcs_t.

set_color_func(func: Callable[[Color, bool, object], None])

Sets the color callback on this PaintFuncs.

The callback paints a color everywhere within the current clip. is_foreground indicates whether the color is the foreground. color is the color to use, unpremultiplied.

Wraps hb_paint_funcs_set_color_func().

set_color_glyph_func(func: Callable[[int, object], bool])

Sets the color-glyph callback on this PaintFuncs.

The callback renders a color glyph by glyph index. It should return True if the glyph was painted, False otherwise.

Wraps hb_paint_funcs_set_color_glyph_func().

set_custom_palette_color_func(func: Callable[[int, object], Color])

Sets the custom-palette-color callback on this PaintFuncs.

The callback fetches a custom palette override color for color_index. Custom palette colors override colors from the font’s selected color palette. It is not necessary to override all palette entries; return None for entries that should be taken from the font palette.

Wraps hb_paint_funcs_set_custom_palette_color_func().

set_image_func(func: Callable[[Blob, int, int, str, float, GlyphExtents, object], bool])

Sets the paint-image callback on this PaintFuncs.

The callback paints a glyph image. It is called for glyphs with image blobs in the CBDT, sbix or SVG tables. The format argument identifies the kind of data that is contained in image. The image dimensions and glyph extents are provided if available, and should be used to size and position the image. The callback should return whether the operation was successful.

Wraps hb_paint_funcs_set_image_func().

set_linear_gradient_func(func: Callable[[ColorLine, float, float, float, float, float, float, object], None])

Sets the linear-gradient callback on this PaintFuncs.

The callback paints a linear gradient everywhere within the current clip. The color_line object contains information about the colors of the gradient; it is only valid for the duration of the callback, you cannot keep it around. The coordinates of the points are interpreted according to the current transform.

Wraps hb_paint_funcs_set_linear_gradient_func().

set_pop_clip_func(func: Callable[[object], None])

Sets the pop-clip callback on this PaintFuncs.

The callback undoes the effect of a prior call to the push-clip-glyph or push-clip-rectangle callback.

Wraps hb_paint_funcs_set_pop_clip_func().

set_pop_group_func(func: Callable[[PaintCompositeMode, object], None])

Sets the pop-group callback on this PaintFuncs.

The callback undoes the effect of a prior call to the push-group callback. It stops the redirection to the intermediate surface, and then composites it on the previous surface, using the compositing mode passed to the callback.

Wraps hb_paint_funcs_set_pop_group_func().

set_pop_transform_func(func: Callable[[object], None])

Sets the pop-transform callback on this PaintFuncs.

The callback undoes the effect of a prior call to the push-transform callback.

Wraps hb_paint_funcs_set_pop_transform_func().

set_push_clip_glyph_func(func: Callable[[int, object], None])

Sets the push-clip-glyph callback on this PaintFuncs.

The callback clips subsequent paint calls to the outline of a glyph.

This clip is applied in addition to the current clip, and remains in effect until a matching call to the pop-clip callback.

Wraps hb_paint_funcs_set_push_clip_glyph_func().

set_push_clip_rectangle_func(func: Callable[[float, float, float, float, object], None])

Sets the push-clip-rectangle callback on this PaintFuncs.

The callback clips subsequent paint calls to a rectangle. The coordinates of the rectangle are interpreted according to the current transform.

This clip is applied in addition to the current clip, and remains in effect until a matching call to the pop-clip callback.

Wraps hb_paint_funcs_set_push_clip_rectangle_func().

set_push_group_func(func: Callable[[object], None])

Sets the push-group callback on this PaintFuncs.

The callback uses an intermediate surface for subsequent paint calls. The drawing will be redirected to an intermediate surface until a matching call to the pop-group callback.

Wraps hb_paint_funcs_set_push_group_func().

set_push_transform_func(func: Callable[[float, float, float, float, float, float, object], None])

Sets the push-transform callback on this PaintFuncs.

The callback applies a transform to subsequent paint calls. This transform is applied after the current transform, and remains in effect until a matching call to the pop-transform callback.

Wraps hb_paint_funcs_set_push_transform_func().

set_radial_gradient_func(func: Callable[[ColorLine, float, float, float, float, float, float, object], None])

Sets the radial-gradient callback on this PaintFuncs.

The callback paints a radial gradient everywhere within the current clip. The color_line object contains information about the colors of the gradient; it is only valid for the duration of the callback, you cannot keep it around. The coordinates of the points are interpreted according to the current transform.

Wraps hb_paint_funcs_set_radial_gradient_func().

set_sweep_gradient_func(func: Callable[[ColorLine, float, float, float, float, object], None])

Sets the sweep-gradient callback on this PaintFuncs.

The callback paints a sweep gradient everywhere within the current clip. The color_line object contains information about the colors of the gradient; it is only valid for the duration of the callback, you cannot keep it around. The coordinates of the points are interpreted according to the current transform.

Wraps hb_paint_funcs_set_sweep_gradient_func().

class uharfbuzz.RasterDraw

Bases: object

An opaque outline rasterizer object. Accumulates glyph outlines via DrawFuncs callbacks, then produces a RasterImage with render().

Wraps hb_raster_draw_t.

clear()

Discards accumulated geometry and extents so this rasterizer can be reused for another render. User configuration (transform, scale factors) is preserved. Call reset() to also reset user configuration to defaults.

Wraps hb_raster_draw_clear().

draw_glyph(font: Font, glyph: int)

Draws one glyph into this rasterizer using the current transform. Equivalent to draw_glyph_or_fail() with the return value ignored.

Wraps hb_raster_draw_glyph().

draw_glyph_or_fail(font: Font, glyph: int) bool

Convenience to draw one glyph.

Returns:

True if the glyph was drawn, False if the font has no outlines for glyph.

Wraps hb_raster_draw_glyph_or_fail().

extents

The output image extents. When set, render() uses the given extents instead of auto-computing them from the accumulated geometry. None if no extents are configured.

Type:

RasterExtents | None

Wraps hb_raster_draw_get_extents() and hb_raster_draw_set_extents().

render() RasterImage | None

Rasterizes the accumulated outline geometry into a new RasterImage. After rendering, the accumulated edges are cleared so the rasterizer can be reused. Output format is always RasterFormat.A8.

Returns:

A rendered RasterImage. Returns None on allocation/configuration failure. If no geometry was accumulated, returns an empty image.

Wraps hb_raster_draw_render().

reset()

Resets this rasterizer to its initial state, clearing all accumulated geometry, the transform, and fixed extents. The object can then be reused for a new glyph.

Wraps hb_raster_draw_reset().

scale_factor

Post-transform minification factors applied during rasterization. Factors larger than 1 shrink the output in pixels. The default is 1.

Type:

tuple of (x_scale_factor, y_scale_factor)

Wraps hb_raster_draw_get_scale_factor() and hb_raster_draw_set_scale_factor().

set_glyph_extents(extents: GlyphExtents) bool

Transforms extents with the rasterizer’s current transform and sets the resulting pixel extents for the next render.

This is equivalent to computing a transformed bounding box in pixel space and assigning it to extents.

Returns:

True if transformed extents are non-empty and set; False otherwise.

Wraps hb_raster_draw_set_glyph_extents().

transform

A 2×3 affine transform applied to all incoming draw coordinates before rasterization. The default is the identity.

Type:

tuple of (xx, yx, xy, yy, dx, dy)

Wraps hb_raster_draw_get_transform() and hb_raster_draw_set_transform().

class uharfbuzz.RasterExtents(x_origin: int = 0, y_origin: int = 0, width: int = 0, height: int = 0, stride: int = 0)

Bases: NamedTuple

Pixel-buffer extents for raster operations.

Wraps hb_raster_extents_t.

height: int

Height in pixels.

stride: int

Bytes per row; 0 means auto-calculate on input, filled on output.

width: int

Width in pixels.

x_origin: int

X coordinate of the left edge of the image in glyph space.

y_origin: int

Y coordinate of the bottom edge of the image in glyph space.

class uharfbuzz.RasterFormat(*values)

Bases: IntEnum

Pixel format for raster images.

A8

8-bit alpha-only coverage.

BGRA32

32-bit BGRA color.

Wraps hb_raster_format_t.

class uharfbuzz.RasterImage

Bases: object

An opaque raster image object holding a pixel buffer produced by RasterDraw.render(). Use buffer and extents to access the pixels.

Wraps hb_raster_image_t.

buffer

Fetches the raw pixel buffer of this image. The buffer layout is described by extents and format. Rows are stored bottom-to-top.

Type:

bytes

Wraps hb_raster_image_get_buffer().

clear()

Clears this image’s pixels to zero while keeping current extents and format.

Wraps hb_raster_image_clear().

configure(format: RasterFormat, extents: RasterExtents | None = None) bool

Configures this image’s format and extents together, resizing backing storage at most once. This function does not clear pixel contents.

Passing None for extents clears extents and releases the backing allocation.

Returns:

True if configuration succeeds, False on allocation failure.

Wraps hb_raster_image_configure().

extents

Fetches the pixel-buffer extents of this image.

Type:

RasterExtents

Wraps hb_raster_image_get_extents().

format

Fetches the pixel format of this image.

Type:

RasterFormat

Wraps hb_raster_image_get_format().

class uharfbuzz.RasterPaint

Bases: object

An opaque color-glyph paint context. Implements PaintFuncs callbacks that render COLRv0/v1 color glyphs into a RasterFormat.BGRA32 RasterImage.

Wraps hb_raster_paint_t.

background

The background color. If set to a non-transparent value, the rendered image is pre-filled with this color before glyph content is composited on top. Default is transparent.

Type:

Color

Wraps hb_raster_paint_get_background() and hb_raster_paint_set_background().

clear()

Discards accumulated paint output so this paint context can be reused for another render. User configuration (base transform, scale factors, foreground, custom palette colors) is preserved. Call reset() to also reset user configuration to defaults.

Wraps hb_raster_paint_clear().

clear_custom_palette_colors()

Clears all custom palette color overrides previously set on this paint context.

After this call, palette lookups use the selected font palette without custom override entries.

Wraps hb_raster_paint_clear_custom_palette_colors().

extents

The output image extents (pixel rectangle). Must be set before painting; otherwise render() returns None. None if no extents are configured.

Type:

RasterExtents | None

Wraps hb_raster_paint_get_extents() and hb_raster_paint_set_extents().

foreground

The foreground color used when paint callbacks request it (e.g. is_foreground in color stops or solid fills). Defaults to opaque black if none was set.

Type:

Color

Wraps hb_raster_paint_get_foreground() and hb_raster_paint_set_foreground().

paint_glyph(font: Font, glyph: int)

Paints one glyph into this paint context. Unlike paint_glyph_or_fail(), glyphs with no color paint data fall back to a synthesized foreground-colored outline, so any glyph with an outline or bitmap image produces output.

Wraps hb_raster_paint_glyph().

paint_glyph_or_fail(font: Font, glyph: int) bool

Convenience to paint one color glyph.

Returns:

True if painting succeeded, False otherwise.

Wraps hb_raster_paint_glyph_or_fail().

palette

Selects which font palette is used when paint callbacks look up indexed colors. Default is palette 0.

Type:

int

Wraps hb_raster_paint_get_palette() and hb_raster_paint_set_palette().

render() RasterImage | None

Extracts the rendered image after painting has completed. The paint context’s surface stack is consumed and the result returned as a new RasterImage. Output format is always RasterFormat.BGRA32.

extents or set_glyph_extents() must be called before painting; otherwise this function returns None. Internal drawing state is cleared here so the same object can be reused without client-side clearing.

Returns:

A rendered RasterImage. Returns None if extents were not set or if allocation/configuration fails. If extents were set but nothing was painted, returns an empty image.

Wraps hb_raster_paint_render().

reset()

Resets this paint context to its initial state, clearing all configuration while preserving internal image caches.

Wraps hb_raster_paint_reset().

scale_factor

Post-transform minification factors applied during painting. Factors larger than 1 shrink the output in pixels. The default is 1.

Type:

tuple of (x_scale_factor, y_scale_factor)

Wraps hb_raster_paint_get_scale_factor() and hb_raster_paint_set_scale_factor().

set_custom_palette_color(color_index: int, color: Color) bool

Overrides one font palette color entry for subsequent paint operations. Overrides are keyed by color_index and persist on this paint context until cleared (or replaced for the same index).

These overrides are consulted by paint operations that resolve CPAL entries.

Returns:

True if the override was set; False on allocation failure.

Wraps hb_raster_paint_set_custom_palette_color().

set_glyph_extents(extents: GlyphExtents) bool

Transforms extents with the paint context’s base transform and sets the resulting output image extents.

This is equivalent to computing a transformed bounding box in pixel space and assigning it to extents.

Returns:

True if transformed extents are non-empty and set; False otherwise.

Wraps hb_raster_paint_set_glyph_extents().

transform

The base 2×3 affine transform that maps from glyph-space coordinates to pixel-space coordinates.

Type:

tuple of (xx, yx, xy, yy, dx, dy)

Wraps hb_raster_paint_get_transform() and hb_raster_paint_set_transform().

exception uharfbuzz.RepackerError

Bases: SerializerError

exception uharfbuzz.SerializerError

Bases: Exception

class uharfbuzz.Set

Bases: object

Data type for holding a set of integers. Set is used to gather and contain glyph IDs, Unicode code points, and various other collections of discrete values.

INVALID_VALUE

Unset set value.

Wraps HB_SET_VALUE_INVALID.

Wraps hb_set_t.

add(c: int)

Adds c to this set.

Wraps hb_set_add().

add_range(first: int, last: int)

Adds all of the elements from first to last (inclusive) to this set.

Wraps hb_set_add_range().

clear()

Clears out the contents of this set.

Wraps hb_set_clear().

copy() Set

Allocate a copy of this set.

Returns:

Newly-allocated set.

Wraps hb_set_copy().

del_range(first: int, last: int)

Removes all of the elements from first to last (inclusive) from this set.

If last is INVALID_VALUE, then all values greater than or equal to first are removed.

Wraps hb_set_del_range().

difference_update(other: Set)

Subtracts the contents of other from this set.

Wraps hb_set_subtract().

discard(c: int)

Removes c from this set if it is present.

Wraps hb_set_del().

intersection_update(other: Set)

Makes this set the intersection of itself and other.

Wraps hb_set_intersect().

invert()

Inverts the contents of this set.

Wraps hb_set_invert().

is_inverted() bool

Returns whether the set is inverted.

Returns:

True if the set is inverted, False otherwise.

Wraps hb_set_is_inverted().

issubset(larger_set: Set) bool

Tests whether this set is a subset of larger_set.

Returns:

True if this set is a subset of (or equal to) larger_set, False otherwise.

Wraps hb_set_is_subset().

issuperset(smaller_set: Set) bool

Tests whether smaller_set is a subset of this set.

Returns:

True if smaller_set is a subset of (or equal to) this set, False otherwise.

Wraps hb_set_is_subset().

max

The largest element in the set, or INVALID_VALUE if the set is empty.

Type:

int

Wraps hb_set_get_max().

min

The smallest element in the set, or INVALID_VALUE if the set is empty.

Type:

int

Wraps hb_set_get_min().

remove(c: int)

Removes c from this set, raising KeyError if c is not in the set.

Wraps hb_set_del().

set(other)

Makes the contents of this set equal to the contents of other.

Parameters:

other – Another Set, or any iterable of integers.

Wraps hb_set_set().

symmetric_difference_update(other: Set)

Makes this set the symmetric difference of itself and other.

Wraps hb_set_symmetric_difference().

update(other)

Makes this set the union of itself and other.

Parameters:

other – Another Set, or any iterable of integers.

Wraps hb_set_union().

class uharfbuzz.SetIter

Bases: object

Iterator over the elements of a Set in increasing order.

Wraps hb_set_next().

class uharfbuzz.StyleTag(*values)

Bases: IntEnum

Style tags defined by OpenType Design-Variation Axis Tag Registry.

ITALIC

Used to vary between non-italic and italic. A value of 0 can be interpreted as “Roman” (non-italic); a value of 1 can be interpreted as (fully) italic.

OPTICAL_SIZE

Used to vary design to suit different text sizes. Non-zero. Values can be interpreted as text size, in points.

SLANT_ANGLE

Used to vary between upright and slanted text. Values must be greater than -90 and less than +90. Values can be interpreted as the angle, in counter-clockwise degrees, of oblique slant from whatever the designer considers to be upright for that font design. Typical right-leaning Italic fonts have a negative slant angle (typically around -12).

SLANT_RATIO

Same as SLANT_ANGLE expressed as a ratio. Typical right-leaning Italic fonts have a positive slant ratio (typically around 0.2).

WIDTH

Used to vary width of text from narrower to wider. Non-zero. Values can be interpreted as a percentage of whatever the font designer considers “normal width” for that font design.

WEIGHT

Used to vary stroke thicknesses or other design details to give variation from lighter to blacker. Values can be interpreted in direct comparison to values for usWeightClass in the OS/2 table, or the CSS font-weight property.

Wraps hb_style_tag_t.

class uharfbuzz.SubsetFlags(*values)

Bases: IntFlag

List of boolean properties that can be configured on the subset input.

DEFAULT

All flags at their default value of false.

NO_HINTING

If set hinting instructions will be dropped in the produced subset. Otherwise hinting instructions will be retained.

RETAIN_GIDS

If set glyph indices will not be modified in the produced subset. If glyphs are dropped their indices will be retained as an empty glyph.

DESUBROUTINIZE

If set and subsetting a CFF font the subsetter will attempt to remove subroutines from the CFF glyphs.

NAME_LEGACY

If set non-unicode name records will be retained in the subset.

SET_OVERLAPS_FLAG

If set the subsetter will set the OVERLAP_SIMPLE flag on each simple glyph.

PASSTHROUGH_UNRECOGNIZED

If set the subsetter will not drop unrecognized tables and instead pass them through untouched.

NOTDEF_OUTLINE

If set the notdef glyph outline will be retained in the final subset.

GLYPH_NAMES

If set the PS glyph names will be retained in the final subset.

NO_PRUNE_UNICODE_RANGES

If set then the unicode ranges in OS/2 will not be recalculated.

NO_LAYOUT_CLOSURE

If set do not perform glyph closure on layout substitution rules (GSUB).

Wraps hb_subset_flags_t.

class uharfbuzz.SubsetInput

Bases: object

Things that change based on the input. Characters to keep, etc.

Wraps hb_subset_input_t.

drop_table_tag_set

Shortcut for sets(SubsetInputSets.DROP_TABLE_TAG).

Type:

Set

flags

All of the subsetting flags in the input object.

Type:

SubsetFlags

Wraps hb_subset_input_get_flags() and hb_subset_input_set_flags().

get_axis_range(tag: str) Tuple[float | None, float | None, float | None] | None

Gets the axis range assigned by previous calls to set_axis_range().

Parameters:

tag – Tag of the axis.

Returns:

(min, max, default) triple if a range has been set for this axis tag, None otherwise. Each component is None only if it was previously set to None (NaN) via set_axis_range().

Wraps hb_subset_input_get_axis_range().

glyph_set

The set of glyph IDs to retain. The caller should modify the set as needed.

Type:

Set

Wraps hb_subset_input_glyph_set().

keep_everything()

Configure input object to keep everything in the font face. That is, all Unicodes, glyphs, names, layout items, glyph names, etc.

The input can be tailored afterwards by the caller.

Wraps hb_subset_input_keep_everything().

layout_feature_tag_set

Shortcut for sets(SubsetInputSets.LAYOUT_FEATURE_TAG).

Type:

Set

layout_script_tag_set

Shortcut for sets(SubsetInputSets.LAYOUT_SCRIPT_TAG).

Type:

Set

name_id_set

Shortcut for sets(SubsetInputSets.NAME_ID).

Type:

Set

name_lang_id_set

Shortcut for sets(SubsetInputSets.NAME_LANG_ID).

Type:

Set

no_subset_table_tag_set

Shortcut for sets(SubsetInputSets.NO_SUBSET_TABLE_TAG).

Type:

Set

pin_all_axes_to_default(face: Face) bool

Pin all axes to default locations in this subset input object.

All axes in a font must be pinned. Additionally, CFF2 table, if present, will be de-subroutinized.

Returns:

True if success, False otherwise.

Wraps hb_subset_input_pin_all_axes_to_default().

pin_axis_location(face: Face, tag: str, value: float) bool

Pin an axis to a fixed location in this subset input object.

All axes in a font must be pinned. Additionally, CFF2 table, if present, will be de-subroutinized.

Parameters:
  • tag – Tag of the axis to be pinned.

  • value – Location on the axis to be pinned at.

Returns:

True if success, False otherwise.

Wraps hb_subset_input_pin_axis_location().

pin_axis_to_default(face: Face, tag: str) bool

Pin an axis to its default location in this subset input object.

All axes in a font must be pinned. Additionally, CFF2 table, if present, will be de-subroutinized.

Parameters:

tag – Tag of the axis to be pinned.

Returns:

True if success, False otherwise.

Wraps hb_subset_input_pin_axis_to_default().

set_axis_range(face: Face, tag: str, min_value: float | None = None, max_value: float | None = None, def_value: float | None = None) bool

Restricting the range of variation on an axis in this subset input object. New min/default/max values will be clamped if they’re not within the fvar axis range.

If the fvar axis default value is not within the new range, the new default value will be changed to the new min or max value, whichever is closer to the fvar axis default.

Note: input min value can not be bigger than input max value. If the input default value is not within the new min/max range, it’ll be clamped.

Parameters:
  • tag – Tag of the axis.

  • min_value – Minimum value of the axis variation range to set, if None the existing min will be used.

  • max_value – Maximum value of the axis variation range to set, if None the existing max will be used.

  • def_value – Default value of the axis variation range to set, if None the existing default will be used.

Returns:

True if success, False otherwise.

Wraps hb_subset_input_set_axis_range().

sets(set_type: SubsetInputSets) Set

Gets the set of the specified type.

Wraps hb_subset_input_set().

subset(source: Face) Face

Subsets source according to this input. Equivalent to calling subset() with source and this input.

unicode_set

The set of Unicode code points to retain. The caller should modify the set as needed.

Type:

Set

Wraps hb_subset_input_unicode_set().

class uharfbuzz.SubsetInputSets(*values)

Bases: IntEnum

List of sets that can be configured on the subset input.

GLYPH_INDEX

The set of glyph indexes to retain in the subset.

UNICODE

The set of unicode codepoints to retain in the subset.

NO_SUBSET_TABLE_TAG

The set of table tags which specifies tables that should not be subsetted.

DROP_TABLE_TAG

The set of table tags which specifies tables which will be dropped in the subset.

NAME_ID

The set of name ids that will be retained.

NAME_LANG_ID

The set of name lang ids that will be retained.

LAYOUT_FEATURE_TAG

The set of layout feature tags that will be retained in the subset.

LAYOUT_SCRIPT_TAG

The set of layout script tags that will be retained in the subset. Defaults to all tags.

Wraps hb_subset_sets_t.

NAME_ID = 4
class uharfbuzz.SubsetPlan

Bases: object

Contains information about how the subset operation will be executed. Such as mappings from the old glyph ids to the new ones in the subset.

Constructing a SubsetPlan computes a plan for subsetting the supplied face according to the provided input. The plan describes which tables and glyphs should be retained.

Wraps hb_subset_plan_t.

execute() Face

Executes this subsetting plan.

Returns:

A new Face containing the generated font subset.

Raises:

RuntimeError – If the subsetting operation fails.

Wraps hb_subset_plan_execute_or_fail().

new_to_old_glyph_mapping

The mapping between glyphs in the subset that will be produced by this plan and the glyph in the original font.

Type:

Map

Wraps hb_subset_plan_new_to_old_glyph_mapping().

old_to_new_glyph_mapping

The mapping between glyphs in the original font to glyphs in the subset that will be produced by this plan.

Type:

Map

Wraps hb_subset_plan_old_to_new_glyph_mapping().

unicode_to_old_glyph_mapping

The mapping between codepoints in the original font and the associated glyph id in the original font.

Type:

Map

Wraps hb_subset_plan_unicode_to_old_glyph_mapping().

uharfbuzz.ot_color_glyph_get_layers(face: Face, glyph: int) List[OTColorLayer]

Deprecated since version 0.40.0.

Use Face.get_glyph_color_layers() instead.

uharfbuzz.ot_color_glyph_get_png(font: Font, glyph: int) Blob

Deprecated since version 0.40.0.

Use Font.get_glyph_color_png() instead.

uharfbuzz.ot_color_glyph_get_svg(face: Face, glyph: int) Blob

Deprecated since version 0.40.0.

Use Face.get_glyph_color_svg() instead.

uharfbuzz.ot_color_glyph_has_paint(face: Face, glyph: int) bool

Deprecated since version 0.40.0.

Use Face.glyph_has_color_paint() instead.

uharfbuzz.ot_color_has_layers(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_color_layers instead.

uharfbuzz.ot_color_has_paint(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_color_paint instead.

uharfbuzz.ot_color_has_palettes(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_color_palettes instead.

uharfbuzz.ot_color_has_png(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_color_png instead.

uharfbuzz.ot_color_has_svg(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_color_svg instead.

uharfbuzz.ot_color_palette_color_get_name_id(face: Face, color_index: int) int | None

Deprecated since version 0.40.0.

Use Face.color_palette_color_get_name_id() instead.

uharfbuzz.ot_color_palette_get_colors(face: Face, palette_index: int) List[Color]

Deprecated since version 0.40.0.

Use Face.get_color_palette() instead.

uharfbuzz.ot_color_palette_get_count(face: Face) int

Deprecated since version 0.40.0.

Use Face.color_palettes instead.

uharfbuzz.ot_color_palette_get_flags(face: Face, palette_index: int) OTColorPaletteFlags

Deprecated since version 0.40.0.

Use Face.get_color_palette() instead.

uharfbuzz.ot_color_palette_get_name_id(face: Face, palette_index: int) int | None

Deprecated since version 0.40.0.

Use Face.get_color_palette() instead.

uharfbuzz.ot_font_set_funcs(font: Font)

Sets the font functions to use when working with font to the HarfBuzz’s native implementation. This is the default for fonts newly created.

Wraps hb_ot_font_set_funcs().

uharfbuzz.ot_layout_get_baseline(font: Font, baseline_tag: str, direction: str, script_tag: str, language_tag: str) int

Deprecated since version 0.40.0.

Use Face.get_layout_baseline() instead.

uharfbuzz.ot_layout_get_glyph_class(face: Face, glyph: int) OTLayoutGlyphClass

Deprecated since version 0.40.0.

Use Face.get_layout_glyph_class() instead.

uharfbuzz.ot_layout_has_glyph_classes(face: Face) bool

Deprecated since version 0.40.0.

Use Face.face.has_layout_glyph_classes instead.

uharfbuzz.ot_layout_has_positioning(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_layout_positioning instead.

uharfbuzz.ot_layout_has_substitution(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_layout_substitution instead.

uharfbuzz.ot_layout_language_get_feature_tags(face: Face, tag: str, script_index: int = 0, language_index: int = 65535) List[str]

Deprecated since version 0.40.0.

Use Face.get_language_feature_tags() instead.

uharfbuzz.ot_layout_lookup_get_glyph_alternates(face: Face, lookup_index: int, glyph: hb_codepoint_t) List[int]

Deprecated since version 0.40.0.

Use Face.get_lookup_glyph_alternates() instead.

uharfbuzz.ot_layout_script_get_language_tags(face: Face, tag: str, script_index: int = 0) List[str]

Deprecated since version 0.40.0.

Use Face.get_script_language_tags() instead.

uharfbuzz.ot_layout_table_get_script_tags(face: Face, tag: str) List[str]

Deprecated since version 0.40.0.

Use Face.get_table_script_tags() instead.

uharfbuzz.ot_math_get_constant(font: Font, constant: OTMathConstant) int

Deprecated since version 0.40.0.

Use Font.get_math_constant() instead.

uharfbuzz.ot_math_get_glyph_assembly(font: Font, glyph: int, direction: str) Tuple[List[OTMathGlyphPart], int]

Deprecated since version 0.40.0.

Use Font.get_math_glyph_assembly() instead.

uharfbuzz.ot_math_get_glyph_italics_correction(font: Font, glyph: int) int

Deprecated since version 0.40.0.

Use Font.get_math_glyph_italics_correction() instead.

uharfbuzz.ot_math_get_glyph_kerning(font: Font, glyph: int, kern: OTMathKern, correction_height) int

Deprecated since version 0.40.0.

Use Font.get_math_glyph_kerning() instead.

uharfbuzz.ot_math_get_glyph_kernings(font: Font, glyph: int, kern: OTMathKern) List[OTMathKernEntry]

Deprecated since version 0.40.0.

Use Font.get_math_glyph_kernings() instead.

uharfbuzz.ot_math_get_glyph_top_accent_attachment(font: Font, glyph: int) int

Deprecated since version 0.40.0.

Use Font.get_math_glyph_top_accent_attachment() instead.

uharfbuzz.ot_math_get_glyph_variants(font: Font, glyph: int, direction: str) List[OTMathGlyphVariant]

Deprecated since version 0.40.0.

Use Font.get_math_glyph_variants() instead.

uharfbuzz.ot_math_get_min_connector_overlap(font: Font, direction: str) int

Deprecated since version 0.40.0.

Use Font.get_math_min_connector_overlap() instead.

uharfbuzz.ot_math_has_data(face: Face) bool

Deprecated since version 0.40.0.

Use Face.has_math_data instead.

uharfbuzz.ot_math_is_glyph_extended_shape(face: Face, glyph: int) bool

Deprecated since version 0.40.0.

Use Face.is_glyph_extended_math_shape() instead.

uharfbuzz.ot_tag_to_language(tag: str) str

Converts a language tag to a language.

Parameters:

tag – A language tag.

Returns:

The language corresponding to tag, or None.

Wraps hb_ot_tag_to_language().

uharfbuzz.ot_tag_to_script(tag: str) str

Converts a script tag to a script.

Parameters:

tag – A script tag.

Returns:

The script corresponding to tag.

Wraps hb_ot_tag_to_script().

uharfbuzz.repack(subtables, graphnodes)

Deprecated since version 0.45.0.

Use serialize() instead.

uharfbuzz.repack_with_tag(tag, subtables, graphnodes)

Deprecated since version 0.45.0.

Use serialize_with_tag() instead.

uharfbuzz.serialize(subtables: List[bytes], graphnodes: List[Tuple[List[Tuple[int, int, int]], List[Tuple[int, int, int]]]]) bytes

Same as serialize_with_tag() with an empty tag, which disables table specific optimizations.

uharfbuzz.serialize_with_tag(tag: str, subtables: List[bytes], graphnodes: List[Tuple[List[Tuple[int, int, int]], List[Tuple[int, int, int]]]]) bytes

Given the input object graph info, repack a table to eliminate offset overflows and serialize it into a continuous array of bytes. Table specific optimizations (e.g. extension promotion in GSUB and GPOS) may be performed. Passing an empty tag will disable table specific optimizations.

The whole table is represented as a Graph and the input graphnodes is a flat list of subtables with each node(subtable) represented by a tuple of 2 list: real_link list and virtual_link list.

A link(egde) is an offset link between parent table and child table. It’s represented in the format of a tuple: (posiiton: int, width: int, objidx: int):

  • position: means relative position of the offset field in bytes from the beginning of the subtable’s C struct. e.g: a GSUB header struct in C looks like below:

    uint16 majorVersion uint16 minorVersion offset16 scriptListOffset offset16 featureListOffset offset16 lookupListOffset And the position for scriptListOffset is 4 which is calculated from (16+16)/8

  • width: size of the offset: e.g 2 for offset16 and 4 for offset32

  • objidx: objidx is the index of the subtable in graph/tree generated by postorder traversal

There’re 2 types of links:

  • real_link represents an real offset field in the parent table

  • virtual_link is not real offset link, it specifies an ordering constraint that harfbuzz packing must follow. A virtual link would have 0 width, 0 position, and a real objidx. e.g: if Node A has a virtual link with objidx b(corresponding Node is B), then that means Node B is always packed after Node A in the final serialized order

Parameters:
  • tag – Tag of the table being packed, needed to allow table specific optimizations.

  • subtables – List of subtable byte buffers, one per object in the object graph.

  • graphnodes – List of (real_links, virtual_links) tuples, one per object.

Returns:

The serialized table as bytes.

Raises:

RepackerError – If serialization fails.

Wraps hb_subset_serialize_or_fail().

uharfbuzz.shape(font: Font, buffer: Buffer, features: Dict[str, int | bool | Sequence[Tuple[int, int, int | bool]]] | None = None, shapers: List[str] | None = None)

Shapes buffer using font turning its Unicode characters content to positioned glyphs. If features is not None, it will be used to control the features applied during shaping. If two features have the same tag but overlapping ranges the value of the feature with the higher index takes precedence.

If shapers is not None, the specified shapers will be used in the given order, otherwise the default shapers list will be used.

Parameters:
  • font – A Font to use for shaping.

  • buffer – A Buffer to shape.

  • features – A mapping whose keys are feature tags (or feature strings as accepted by hb_feature_from_string when the value is an int/bool), and whose values are either an int/bool applied globally, or a sequence of (start, end, value) triples applying the feature to a specific cluster range.

  • shapers – Ordered list of shaper names to try, or None for the default list.

Raises:
  • RuntimeError – If all shapers failed (only when shapers is provided).

  • MemoryError – If memory allocation fails.

Wraps hb_shape() or hb_shape_full() when shapers is given.

uharfbuzz.subset(face: Face, input: SubsetInput) Face

Subsets a font according to provided input.

Raises:

RuntimeError – If the subset operation fails or the face has no glyphs.

Wraps hb_subset_or_fail().

uharfbuzz.subset_preprocess(face: Face) Face

Preprocesses the face and attaches data that will be needed by the subsetter. Future subsetting operations can then use the precomputed data to speed up the subsetting operation.

See subset-preprocessing for more information.

Note: the preprocessed face may contain sub-blobs that reference the memory backing the source Face. Therefore in the case that this memory is not owned by the source face you will need to ensure that memory lives as long as the returned Face.

Returns:

a new Face.

Wraps hb_subset_preprocess().

uharfbuzz.version_string() str

Returns library version as a string with three components.

Returns:

Library version string.

Wraps hb_version_string().