Text and font C reference

These interfaces are private. See Text layout and document fonts for ownership and lifetime.

Layout measurement

TextLayout *Rbc_GetTextLayout(const char *string, TextStyle *stylePtr)

Allocate an unrotated multiline layout using a borrowed style and font.

Fragment text pointers borrow the input string; keep it alive and unchanged until the layout is no longer used. NULL is treated as an empty string. The caller frees the single allocation with ckfree. Counts are UTF byte counts, not character counts. Rotation and anchoring are drawing operations.

Parameters:
  • string – [in] NUL-terminated Tcl UTF text borrowed by fragments until the layout is freed; NULL is treated as empty.

  • stylePtr – [in] Borrowed style with live font, padding, justification, leader and shadow offset used for measurement.

void Rbc_GetTextExtents(TextStyle *tsPtr, const char *string, int *widthPtr, int *heightPtr)

Measure unrotated text without allocating a fragment array.

Borrow the style and font. NULL returns zero dimensions, ignoring padding. The height includes leader spacing for every line; unlike GetTextLayout it does not remove the final leader. Do not substitute it blindly for layout dimensions when nonzero leader spacing is used.

Parameters:
  • tsPtr – [in] Borrowed measurement style and live font; ignored when string is NULL.

  • string – [in] NUL-terminated Tcl UTF text, or NULL to return zero dimensions.

  • widthPtr – [out] Required destination for the nonnegative unrotated width in pixels.

  • heightPtr – [out] Required destination for the nonnegative unrotated height in pixels, including final leader spacing.

Style initialization and GC ownership

void Rbc_InitTextStyle(TextStyle *stylePtr)

Initialize style defaults without acquiring or releasing resources.

This is not a full memset: gc, border, width and height are not initialized. A caller using those fields must initialize them separately. In particular, set gc to NULL or a valid owned Tk GC before ResetTextStyle or FreeTextStyle.

Parameters:
  • stylePtr – [inout] Caller-owned record receiving selected defaults; existing resources are not released.

void Rbc_ResetTextStyle(Tk_Window tkwin, TextStyle *stylePtr)

Replace the style GC using its current font and optional foreground.

Requires a live window, valid font, and gc either NULL or an owned Tk GC. Acquires the replacement before releasing the old GC. Font and colors are borrowed; their ownership is unchanged.

Parameters:
  • tkwin – [in] Live Tk window supplying the display and drawing resources; borrowed for the call.

  • stylePtr – [inout] Style with a valid borrowed font, optional color and NULL or owned Tk GC; receives the new owned GC.

void Rbc_FreeTextStyle(Display *display, TextStyle *stylePtr)

Release a non-NULL style GC with Tk_FreeGC.

Does not release font, colors, border or the style record, and does not clear the gc field. Do not call twice without resetting that field or installing another owned GC. A borrowed GC must not be released through this helper.

Parameters:
  • display – [in] Display owning the style GC.

  • stylePtr – [inout] Style whose non-NULL owned Tk GC is released; gc remains stale until the caller resets it.

Document font cache

Rbc_ExportFont *Rbc_FirstExportFont(Rbc_ExportContext *token)

Return the borrowed head of the document font list, or NULL.

Follow next pointers only while the document font cache remains alive. This does not initialize a cache or transfer ownership.

Parameters:
  • token – [in] Live export context; an absent font cache yields NULL.

int Rbc_ExportFontCharacter(Rbc_ExportContext *token, Tk_Font tkfont, Tcl_UniChar ch, Rbc_ExportFont **fontPtr, int *cidPtr, double *sizePtr, double *advancePtr)

Resolve a Unicode scalar into a document-local font and character ID.

Borrow token and tkfont. Requires a live Tk window and interpreter. May call the global Tcl font command to resolve Tk’s per-character fallback face; this helper does not itself preserve graph lifetime. On TCL_OK, return a borrowed font, a one-based character ID, pixel size and horizontal advance. The ID is not a native glyph index. Outputs are valid only on success; the font remains owned by token until ExportFontsFree. On TCL_ERROR, retain the first static export diagnostic. Partial cache allocations remain valid for cleanup; do not continue serialization.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • tkfont – [in] Borrowed Tk font, kept valid throughout the export cache lifetime.

  • ch – [in] Unicode scalar to resolve, not a native glyph index or PDF character code.

  • fontPtr – [out] Receives a borrowed document-owned font only on success; invalidated by Rbc_ExportFontsFree.

  • cidPtr – [out] Receives a one-based character ID within that font only on success.

  • sizePtr – [out] Receives resolved font size in display pixels only on success.

  • advancePtr – [out] Receives horizontal advance in display pixels only on success.

void Rbc_ExportFontsFree(Rbc_ExportContext *token)

Release all document-local font programs and character cache entries.

Clears token->fontData; an empty cache is harmless. Invalidates all borrowed font records and table views. Does not free backend PDF resources, the document buffer, the export context or any borrowed Tk font.

Parameters:
  • token – [inout] Context whose entire font cache is released and fontData cleared; backend resources are separate.

int Rbc_FontUnicodeProgram(Rbc_ExportContext *token, Rbc_ExportFont *font, Tcl_DString *program)

Append an SVG font program with Unicode mappings for used characters.

Borrow token and a populated export font. The caller initializes program and owns its DString storage. Rebuilds a temporary sfnt with replacement cmap; retains outlines rather than subsetting them, and leaves font unchanged. Returns TCL_OK after appending, or TCL_ERROR with an export diagnostic. Temporary program allocations are released on both paths.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • font – [in] Borrowed font record with validated program bytes and table metadata.

  • program – [inout] Caller-initialized DString receiving appended binary sfnt bytes on success; unchanged on failure.

Shared text drawing implementation

group Text geometry and native drawing

Private helpers; layouts borrow strings and styles borrow Tk resources.

Functions

static int TextLayoutInt(Tcl_WideInt value)

Saturate a wide signed coordinate to the native int range.

No allocation or interpreter error is involved; negative coordinates remain valid.

Parameters:
  • value – [in] Wide signed pixel coordinate, saturated to the native int range.

static int TextLayoutSize(Tcl_WideInt value)

Clamp a wide size to the nonnegative int range.

Nonpositive inputs become zero; values above INT_MAX become INT_MAX.

Parameters:
  • value – [in] Wide pixel extent, clamped to zero through INT_MAX.

static size_t GetTextLayoutByteCount(Tcl_Size nFrags)

Compute allocation bytes for a variable-length fragment array.

Uses offsetof(TextLayout, fragArr), including for zero fragments. Negative counts or size_t overflow cause Tcl_Panic rather than a recoverable error.

Parameters:
  • nFrags – [in] Nonnegative number of TextFragment records; zero requires only the layout header.

static int TextRotatedSize(double value)

Round a rotated extent into bounded nonnegative integer geometry.

Nonfinite or nonpositive values become zero; large finite values saturate at INT_MAX. Remaining values use the existing ROUND convention.

Parameters:
  • value – [in] Floating pixel extent; nonfinite or nonpositive values become zero.

static int TextLayoutCoordinate(double value)

Round a floating coordinate with finite checks and int saturation.

Nonfinite values become zero; finite out-of-range values saturate at the corresponding int endpoint. Remaining values use ROUND.

Parameters:
  • value – [in] Floating signed pixel coordinate; nonfinite values become zero.

static void DrawTextLayout(Display *display, Drawable drawable, GC gc, Tk_Font font, int x, int y, TextLayout *textPtr, double theta)

Draw borrowed fragments relative to an already anchored box origin.

For zero theta, add fragment baselines with saturated integer arithmetic and call Tk_DrawChars. Otherwise rotate each baseline about the unrotated box center, translate to the rounded rotated box, and call TkDrawAngledChars. theta is in degrees and must satisfy the bounding-box helper preconditions. The caller supplies a live drawable, compatible GC and font. This helper neither selects foreground colors nor retains or frees layout resources.

Parameters:
  • display – [in] Display owning the destination and drawing resources.

  • drawable – [in] Live destination drawable compatible with the supplied font and GC.

  • gc – [in] Borrowed compatible GC with foreground already selected.

  • font – [in] Borrowed Tk font used to draw the measured fragments.

  • x – [in] Upper-left X coordinate of the rotated bounding box, already anchored.

  • y – [in] Upper-left Y coordinate of the rotated bounding box, already anchored.

  • textPtr – [in] Borrowed unrotated layout whose fragment strings remain alive and unchanged.

  • theta – [in] Finite normalized rotation in degrees, in [0, 360).

void Rbc_GetBoundingBox(int width, int height, double theta, double *rotWidthPtr, double *rotHeightPtr, Point2D *bbox)

Compute the centered bounding box of a rotated rectangle.

width and height describe the unrotated rectangle. theta is in degrees; callers supply a finite, normalized angle in [0, 360). Both dimension outputs are required; bbox may be NULL or point to four Point2D entries. Corners retain the original NW, NE, SE, SW indexing around the origin. Positive angles rotate visually counterclockwise in screen coordinates. Exact quadrants avoid trigonometric rounding. Other angles rotate each corner and double the maximum positive coordinates. No resources are owned.

Parameters:
  • width – [in] Nonnegative unrotated width in pixels.

  • height – [in] Nonnegative unrotated height in pixels.

  • theta – [in] Finite normalized rotation in degrees, in [0, 360).

  • rotWidthPtr – [out] Required destination for the floating axis-aligned rotated width.

  • rotHeightPtr – [out] Required destination for the floating axis-aligned rotated height.

  • bbox – [out] Optional array of four rotated corners centered at the origin, in original NW, NE, SE, SW order.

void Rbc_TranslateAnchor(int x, int y, int width, int height, Tk_Anchor anchor, int *transXPtr, int *transYPtr)

Translate an integer anchor position to the box upper-left corner.

Both output pointers are required. NULL and NW anchors leave the position unchanged. Center offsets use integer division; subtraction is performed in Tcl_WideInt and saturated to int. No drawing or allocation occurs.

Parameters:
  • x – [in] Horizontal anchor position in drawable pixels.

  • y – [in] Vertical anchor position in drawable pixels.

  • width – [in] Nonnegative box width in pixels.

  • height – [in] Nonnegative box height in pixels.

  • anchor – [in] Tk anchor locating the rotated box relative to the requested position.

  • transXPtr – [out] Required destination for the saturated upper-left X coordinate.

  • transYPtr – [out] Required destination for the saturated upper-left Y coordinate.

Point2D Rbc_TranslatePoint(Point2D *pointPtr, int width, int height, Tk_Anchor anchor)

Return a floating upper-left position from a borrowed anchor point.

Does not modify pointPtr. Center offsets retain half-pixel fractions, unlike Rbc_TranslateAnchor; no integer saturation is applied. NULL and NW anchors return the original position.

Parameters:
  • pointPtr – [in] Required borrowed anchor point, left unchanged.

  • width – [in] Nonnegative box width in pixels.

  • height – [in] Nonnegative box height in pixels.

  • anchor – [in] Tk anchor locating the rotated box relative to the requested position.

void Rbc_SetDrawTextStyle(TextStyle *tsPtr, Tk_Font font, GC gc, XColor *normalColor, XColor *activeColor, XColor *shadowColor, double theta, Tk_Anchor anchor, Tk_Justify justify, int leader, int shadowOffset)

Set drawing attributes using borrowed font, colors and GC.

Applies Rbc_InitTextStyle defaults, then installs supplied attributes. No resource is acquired or released, including a previously installed GC. border, width and height remain untouched. A supplied borrowed GC must not subsequently be released through Rbc_FreeTextStyle.

Parameters:
  • tsPtr – [inout] Caller-owned style receiving defaults and borrowed attributes; existing resources are not released.

  • font – [in] Tk font borrowed for subsequent measurement and drawing.

  • gc – [in] GC borrowed for drawing; no reference is acquired.

  • normalColor – [in] Borrowed normal color, required by drawing paths that restore foreground.

  • activeColor – [in] Borrowed active color, required when STATE_ACTIVE is used.

  • shadowColor – [in] Borrowed shadow color, or NULL to disable the shadow pass.

  • theta – [in] Rotation in degrees; supply a finite value with quotient by 360 representable as int before drawing.

  • anchor – [in] Tk anchor locating the rotated box relative to the requested position.

  • justify – [in] Horizontal justification of fragments within the unrotated layout.

  • leader – [in] Extra interline spacing in display pixels.

  • shadowOffset – [in] Shadow displacement in pixels; positive values enable a pass when a shadow color is present.

void Rbc_SetPrintTextStyle(TextStyle *tsPtr, Tk_Font font, XColor *fgColor, XColor *activeColor, XColor *shadowColor, double theta, Tk_Anchor anchor, Tk_Justify justify, int leader, int shadowOffset)

Set print attributes without acquiring native drawing resources.

Applies Rbc_InitTextStyle defaults, then borrows the supplied font and colors. gc, border, width and height remain untouched; this does not prepare an uninitialized style for native drawing or GC cleanup.

Parameters:
  • tsPtr – [inout] Caller-owned style receiving print attributes; gc, border and extents remain untouched.

  • font – [in] Borrowed Tk font supplying measurement and export attributes.

  • fgColor – [in] Borrowed foreground color; validity requirements belong to the chosen exporter.

  • activeColor – [in] Borrowed active foreground color; this is not a background color.

  • shadowColor – [in] Borrowed shadow color, or NULL for no shadow color.

  • theta – [in] Rotation in degrees; supply a finite value with quotient by 360 representable as int before drawing.

  • anchor – [in] Tk anchor locating the rotated box relative to the requested position.

  • justify – [in] Horizontal justification of fragments within the unrotated layout.

  • leader – [in] Extra interline spacing in display pixels.

  • shadowOffset – [in] Shadow displacement in pixels; positive values enable a pass when a shadow color is present.

void Rbc_DrawTextLayout(Tk_Window tkwin, Drawable drawable, TextLayout *textPtr, TextStyle *tsPtr, int x, int y)

Draw a borrowed layout with anchor, rotation and style-state effects.

Requires a valid font and drawable-compatible GC. Normal color is needed by color-restoration paths, activeColor for active text, and border for disabled or emphasis text. Normalizes theta in place; callers must supply a finite angle whose quotient by 360 is representable as int. Disabled/emphasis rendering takes precedence over shadow and active text, drawing two border-colored passes one pixel apart. Otherwise an optional shadow precedes the normal or active pass. Changed foreground is reset to the normal color, not the GC foreground on entry. The GC must permit this mutation. Rotation uses Tk angled text, not a temporary bitmap. The layout and style resources remain owned by the caller.

Parameters:
  • tkwin – [in] Live Tk window supplying the display and drawing resources; borrowed for the call.

  • drawable – [in] Live destination drawable compatible with the supplied font and GC.

  • textPtr – [in] Borrowed measured layout and live fragment strings; not freed or modified.

  • tsPtr – [inout] Borrowed style with valid font, mutable GC and colors required by its state; theta is normalized in place.

  • x – [in] Horizontal anchor position in drawable pixels.

  • y – [in] Vertical anchor position in drawable pixels.

void Rbc_DrawText2(Tk_Window tkwin, Drawable drawable, const char *string, TextStyle *tsPtr, int x, int y, Dim2D *areaPtr)

Draw a temporary layout and optionally return its rotated dimensions.

NULL or empty text draws nothing and sets a supplied areaPtr to zero. Nonempty text uses Rbc_DrawTextLayout, inheriting its style requirements and theta mutation. areaPtr may be NULL; dimensions use rounded rotated extents and exclude anchor position. Frees only the temporary layout.

Parameters:
  • tkwin – [in] Live Tk window supplying the display and drawing resources; borrowed for the call.

  • drawable – [in] Live destination drawable compatible with the supplied font and GC.

  • string – [in] Borrowed NUL-terminated Tcl UTF text; NULL or empty text draws nothing.

  • tsPtr – [inout] Borrowed style with valid font, mutable GC and colors required by its state; theta is normalized in place.

  • x – [in] Horizontal anchor position in drawable pixels.

  • y – [in] Vertical anchor position in drawable pixels.

  • areaPtr – [out] Optional rotated bounding dimensions in pixels; initialized to zero even when no text is drawn.

void Rbc_DrawText(Tk_Window tkwin, Drawable drawable, const char *string, TextStyle *tsPtr, int x, int y)

Draw nonempty text using a temporary borrowed-string layout.

NULL or empty text is a no-op. Otherwise delegates to Rbc_DrawTextLayout and frees the layout, retaining the caller-owned string, font and colors. Inherits the drawing helper requirements and theta/GC side effects.

Parameters:
  • tkwin – [in] Live Tk window supplying the display and drawing resources; borrowed for the call.

  • drawable – [in] Live destination drawable compatible with the supplied font and GC.

  • string – [in] Borrowed NUL-terminated Tcl UTF text; NULL or empty text draws nothing.

  • tsPtr – [inout] Borrowed style with valid font, mutable GC and colors required by its state; theta is normalized in place.

  • x – [in] Horizontal anchor position in drawable pixels.

  • y – [in] Vertical anchor position in drawable pixels.

GC Rbc_GetBitmapGC(Tk_Window tkwin)

Borrow a cached depth-one GC keyed by Display pointer.

Creates the GC from a temporary one-pixel bitmap on the first request for a display, initially with foreground and background zero. Later calls return the same mutable GC without resetting its attributes. Callers must not free it and must establish all state needed for their operation. The process-static table has no cleanup or synchronization here; it is not a per-window, per-screen or per-interpreter ownership mechanism.

Parameters:
  • tkwin – [in] Window selecting the display cache key and, on first use, the screen for GC creation.

Native font acquisition and parsing

group Shared export font internals

Private readers and builders.

Table views borrow their owning font program; bounds-checked metadata parsing is not a complete font-file sanitizer.

Functions

unsigned int Rbc_FontU16(const unsigned char *p)

Read an unsigned big-endian 16-bit field.

Requires two readable bytes; performs no bounds check or allocation.

Parameters:
  • p – [in] Start of at least two readable bytes; no alignment requirement.

uint32_t Rbc_FontU32(const unsigned char *p)

Read an unsigned big-endian 32-bit field.

Requires four readable bytes; performs no alignment-dependent loads or bounds check.

Parameters:
  • p – [in] Start of at least four readable bytes; no alignment requirement.

int Rbc_FontS16(const unsigned char *p)

Read a signed big-endian 16-bit field.

Requires two readable bytes; explicitly sign-extends the unsigned value.

Parameters:
  • p – [in] Start of at least two readable bytes; no alignment requirement.

void Rbc_FontPut16(unsigned char *p, unsigned int n)

Write the low 16 bits in big-endian order.

Requires two writable bytes. Values outside the field width are truncated, not rejected.

Parameters:
  • p – [out] Start of at least two writable bytes.

  • n – [in] Value whose low 16 bits are stored; higher bits are discarded.

static void FontPut32(unsigned char *p, uint32_t n)

Write a big-endian 32-bit field.

Requires four writable bytes. Used for rebuilt directories, checksums and cmap fields.

Parameters:
  • p – [out] Start of at least four writable bytes.

  • n – [in] 32-bit value written most significant byte first.

static void FontSourceFree(FontSource *source)

Release a partially or fully initialized native font source.

Requires a zero-initialized source before acquisition. Frees byte storage and, on Windows, restores the selected font before releasing the DC and created font. Does not free the source record or clear fields; do not call twice.

Parameters:
  • source – [inout] Zero-initialized or partially acquired source whose owned resources are released once; fields are not cleared.

static int FontSourceOpen(Rbc_ExportContext *token, const char *family, int bold, int italic, double size, Tcl_UniChar ch, FontSource *source)

Acquire a native scalable face for a selected family, style and character.

Caller supplies a zeroed FontSource and must call FontSourceFree on success and failure. Windows creates a GDI font/DC and reads the sfnt directory; individual tables remain available through that DC. X11 matches character coverage through Fontconfig, reads at most 64 MiB through Tcl channels and selects a collection face. Returns TCL_ERROR with an export diagnostic on failure; partial source ownership remains with the caller. Does not build the independent export program or validate all its tables.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • family – [in] Borrowed NUL-terminated UTF-8 family selected by Tk.

  • bold – [in] Nonzero requests bold physical style.

  • italic – [in] Nonzero requests italic physical style.

  • size – [in] Validated positive pixel size, representable as the rounded GDI height; ignored on X11.

  • ch – [in] Character coverage required by Fontconfig; Windows relies on the already selected family.

  • source – [inout] Caller-owned zeroed source; caller releases partial resources on both success and failure.

static int FontProgram(Rbc_ExportContext *token, FontSource *source, Rbc_ExportFont *font)

Rebuild an independent sfnt with fresh offsets and checksums.

Borrows an acquired FontSource; requires a fresh destination font record. Drops DSIG, rejects fvar, bounds directory and table sizes and copies full tables into a zero-padded allocation. Windows reads tables by GDI tag; other sources use checked file-relative offsets. Installs bytes/length before all validation finishes, so the caller must free the partial font on TCL_ERROR. Recomputes table checksums and head adjustment, but does not validate every outline instruction, table relationship or semantic field.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • source – [in] Acquired source directory and platform resources; remains caller-owned.

  • font – [inout] Fresh destination receiving owned bytes and length, possibly before a later validation failure.

Rbc_FontTable Rbc_FontGetTable(Rbc_ExportFont *font, const char *tag)

Find a borrowed table slice in a rebuilt export font.

Requires a FontProgram-validated directory and a readable four-byte tag. Returns {NULL,0} when absent. Does not revalidate bounds or retain the owning font; the returned view expires when its program storage is released.

Parameters:
  • font – [in] Font whose directory and table extents were validated by FontProgram.

  • tag – [in] Four readable tag bytes; a terminating NUL is not required.

static uint32_t CffOffset(const unsigned char *p, unsigned int width)

Decode a big-endian variable-width CFF offset.

Caller validates width (one through four) and the corresponding readable bytes. Returns the unsigned offset without adjusting its one-based origin.

Parameters:
  • p – [in] At least width readable bytes.

  • width – [in] Validated offset width from one through four bytes.

static int CffIndex(Rbc_FontTable table, size_t *position, Rbc_FontTable *index)

Validate a CFF INDEX and advance a caller-owned cursor.

Checks count, offset width, one-based initial offset, monotonic offsets and final data bounds. Empty INDEX records occupy two bytes. On success returns one and a borrowed complete INDEX slice, advancing position past it. On failure returns zero without advancing position; the output slice may be partially written and must not be used. Does not validate item contents.

Parameters:
  • table – [in] Borrowed readable CFF table slice with its byte length.

  • position – [inout] Zero-based byte cursor, advanced only on success.

  • index – [out] Borrowed complete INDEX slice on success; may be partially written on failure and must then be ignored.

static Rbc_FontTable CffItem(Rbc_FontTable index, unsigned int item)

Borrow one item from an already validated CFF INDEX.

Requires the complete slice returned by successful CffIndex, even for an empty INDEX. Out-of-range item indices return {NULL,0}; an in-range item may have zero length. No allocation, ownership transfer or repeated validation.

Parameters:
  • index – [in] Complete INDEX slice already validated by CffIndex.

  • item – [in] Zero-based item number; an out-of-range number returns an empty NULL slice.

Rbc_FontTable Rbc_FontGlyphName(Rbc_ExportFont *font, int glyph)

Resolve a validated name-keyed CFF glyph to its name bytes.

Requires an in-range glyph and initialized SID array. Standard SIDs borrow static names; custom SIDs borrow the validated String INDEX. The returned slice is not necessarily NUL-terminated. FontCffInit validates name lengths before consumers serialize them; this helper does not validate glyph bounds.

Parameters:
  • font – [in] Name-keyed CFF font with validated SIDs and String INDEX.

  • glyph – [in] Valid zero-based native glyph index into the SID array; not a document character ID.

static int FontCffInit(Rbc_ExportContext *token, Rbc_ExportFont *font)

Initialize glyph-name SIDs for a name-keyed CFF 1 font.

Requires a validated sfnt font, CFF table and positive glyph count. Parses Name/Top DICT/String INDEX data, relevant charset and CharStrings offsets, and predefined or explicit charset forms. Rejects CID-keyed CFF and malformed metadata. Allocates font->sids, retained for FontFree even on later failure. Only the metadata required by export is interpreted; charstring programs and unused DICT operands are not a complete CFF validation target.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • font – [inout] Rebuilt font with validated CFF table and positive glyph count; owns any allocated SID array even on failure.

static int FontTables(Rbc_ExportContext *token, Rbc_ExportFont *font)

Validate and cache the table views needed by document text export.

Requires a rebuilt sfnt. Checks metrics, cmap directory bounds, outline type, color-table exclusions and embedding permission bits. Derives a safe export name or falls back to RBCFont plus the serial ID. Cached views borrow font bytes; no table is copied. Returns TCL_ERROR through the export context; partial metadata remains attached for cleanup. CFF charset initialization and per-character cmap lookup are separate stages.

Parameters:
  • token – [inout] Live export context receiving the first error diagnostic and any document-local cache changes.

  • font – [inout] Rebuilt sfnt receiving borrowed table views, metrics and a safe export name; partial metadata remains on failure.

static int FontGlyph(Rbc_ExportFont *font, Tcl_UniChar ch)

Resolve a Unicode scalar to a native glyph index.

Requires FontTables-validated metadata. Tries Unicode format 12, Unicode format 4, then Windows Symbol format 4 with F000 and legacy byte mappings. Uses the retained named Tcl encoding when available. Subtable bounds and resulting glyph indices are checked; malformed/unsupported candidates are skipped. Returns zero for no usable nonzero glyph. Format-12 binary search assumes sorted groups; this is not a complete cmap conformance validator.

Parameters:
  • font – [in] Borrowed font record with validated program bytes and table metadata.

  • ch – [in] Unicode scalar to resolve, not a native glyph index or PDF character code.

static void FontFree(Rbc_ExportFont *font)

Release one export font record and all its owned allocations.

Requires initialized codes hash storage, including for failed acquisition. Releases program bytes, key, glyph/character/SID arrays and optional Tcl encoding, then the record. Does not unlink it or free following list nodes. All borrowed table/name views become invalid; Tk_Font handles are not owned.

Parameters:
  • font – [in] Owned non-NULL record with initialized codes hash; caller unlinks it before release if necessary.

static Tcl_Obj *FontActual(Rbc_ExportContext *token, Tk_Font font, Tcl_UniChar ch)

Query Tk 9 for the actual per-character font attributes.

Evaluates global ::font actual with display window and the Unicode character. Returns a retained result object on success; caller decrements it. Restores interpreter state on both paths and records an export error on failure. Requires live Tk font/window/interpreter. This Tcl boundary does not itself preserve graph resources or guard reentrant replacement of the font command.

Parameters:
  • token – [inout] Export context with a live interpreter/window; interpreter state is restored after the Tcl query.

  • font – [in] Borrowed Tk font whose actual per-character attributes are queried.

  • ch – [in] Unicode scalar to resolve, not a native glyph index or PDF character code.

static Tcl_Obj *FontAttribute(Tcl_Obj *attributes, const char *name)

Borrow a named attribute from a dictionary-like Tcl result.

Creates and releases a temporary key. Returns NULL for a missing key or failed dictionary lookup; returned values remain owned by attributes. No interpreter diagnostic is produced.

Parameters:
  • attributes – [in] Borrowed Tcl dictionary-like result, kept alive while the returned value is used.

  • name – [in] Borrowed NUL-terminated attribute key, such as -family.

static int FontUnicodeCompare(const void *a, const void *b)

Order temporary Unicode-to-glyph pairs by scalar value.

qsort comparator for FontUnicodePair records; ignores glyph values and uses relational comparisons rather than subtraction that could overflow.

Parameters:

PDF font resource encoding

group PDF font resources

Private document-owned resources.

Character collection precedes finalization.

Functions

static int PdfStandardCharacter(Rbc_ExportContext *token, Tk_Font font, Tcl_UniChar ch, int *idPtr, int *codePtr, double *sizePtr)

Map a nonembedded character to a standard PDF font and WinAnsi code.

Accepts printable ASCII, Latin-1 and the defined Windows-1252 extension characters. Unsupported text sets an export error. Derives Courier/Times/ Helvetica style from Tk PostScript naming, reserves a deduplicated Type1 resource and returns pixel size/code/id. Borrows the Tk font; no native font program is acquired. Outputs are only usable on TCL_OK.

Parameters:
  • token – [inout] Live PDF export context with initialized builder and a valid current buffer.

  • font – [in] Borrowed Tk font supplying standard-family/style selection and point size.

  • ch – [in] Unicode scalar to resolve, not a native glyph index or PDF character code.

  • idPtr – [out] Receives the document font resource object number on success.

  • codePtr – [out] Receives the one-byte WinAnsi character code on success.

  • sizePtr – [out] Receives font size converted to display pixels on success.

int Rbc_PdfFontCharacter(Rbc_ExportContext *token, Tk_Font tkfont, Tcl_UniChar ch, int *idPtr, int *cidPtr, double *sizePtr, int *digitsPtr, double *advancePtr)

Resolve a character and reserve its PDF font resource.

With embedding disabled uses WinAnsi and two hex digits. Otherwise borrows the shared font cache and its native advance; TrueType uses four-digit CIDs, CFF uses two-digit codes in 255-character blocks. Resource placeholders are replaced by Rbc_PdfFontsFinish. Requires initialized PDF export state; caller must not serialize the document before successful finalization. Returns TCL_ERROR for existing or newly recorded export errors.

Parameters:
  • token – [inout] Live PDF export context with initialized builder and a valid current buffer.

  • tkfont – [in] Borrowed Tk font used for standard-font mapping or shared native resolution.

  • ch – [in] Unicode scalar to resolve, not a native glyph index or PDF character code.

  • idPtr – [out] PDF font resource object number; consume only on TCL_OK.

  • cidPtr – [out] Code for that resource: WinAnsi byte, TrueType CID or CFF block-local code; consume only on TCL_OK.

  • sizePtr – [out] Resolved font size in display pixels; consume only on TCL_OK.

  • digitsPtr – [out] Hexadecimal code width (two or four digits); may be written before a later failure.

  • advancePtr – [out] Native horizontal advance in pixels, or zero in nonembedded mode; may be written before a later failure.

static void FontCffResources(Rbc_ExportContext *token, Rbc_ExportFont *font, int descriptor)

Finalize simple Type1C resources in blocks of 255 characters.

Requires a collected name-keyed CFF font, reserved block IDs and a shared descriptor object. Builds per-block widths, escaped glyph-name Differences and ToUnicode maps, sharing the embedded CFF program through the descriptor. Temporarily redirects token->buffer and restores it before releasing local DString storage. Does not release the font or serialize the final PDF file.

Parameters:
  • token – [inout] Live PDF export context with initialized builder and a valid current buffer.

  • font – [in] Collected name-keyed CFF font with reserved fontIds for every used 255-character block.

  • descriptor – [in] Existing PDF font-descriptor object number in the same document; shared by all blocks.

int Rbc_PdfFontsFinish(Rbc_ExportContext *token)

Replace collected font placeholders with complete PDF font dictionaries.

Requires completed character collection and initialized PDF resources. Embeds full TrueType programs or CFF tables, descriptors, widths and Unicode maps. TrueType adds CIDToGIDMap and Identity-H descendant resources; CFF delegates block encodings to FontCffResources. Borrows all cached fonts and restores token->buffer after temporary serialization. Returns TCL_ERROR for a pre-existing export error. Finalize once before document serialization; this operation does not freeze the cache or enforce one-shot use.

Parameters:
  • token – [inout] Live PDF export context with initialized builder and a valid current buffer.

Data records and member contracts

These records describe stored state and resource ownership. Their presence in the reference does not make private layouts part of the installed C API.

struct ExportCharacter

Cached resolved character within a document font.

Public Members

Rbc_ExportFont *font

Borrowed document-owned font.

int cid

One-based document character ID, not a native glyph index.

double size

Resolved font size in display pixels.

struct ExportFontCache

Document-owned font list and character lookup cache.

Public Members

Rbc_ExportFont *fonts

Owned list of font programs.

int serial

Last allocated document-local font identifier.

Tcl_HashTable characters

Cache of resolved font/character pairs; entries own ExportCharacter records.

struct FontSource

Temporary native font source; cleanup releases bytes and platform handles.

Public Members

unsigned char *bytes

Owned retrieved font-program bytes.

size_t length

Number of retrieved bytes.

size_t offset

Face offset within a font collection.

struct FontUnicodePair

Unicode scalar to source-glyph mapping used to build a cmap.

Public Members

uint32_t character

Unicode scalar.

uint32_t glyph

Native glyph index.

struct Rbc_ExportFont

Document-owned font program, parsed table views and character mapping.

Table views borrow bytes; export-font cleanup releases the program and auxiliary arrays.

Public Members

struct Rbc_ExportFont *next

Next font in the document cache, or NULL.

char *key

Owned native-face cache key.

unsigned char *bytes

Owned sfnt font program.

size_t length

Font program length in bytes.

Rbc_FontTable head

Borrowed font-header table.

Rbc_FontTable hhea

Borrowed horizontal-header table.

Rbc_FontTable hmtx

Borrowed horizontal-metrics table.

Rbc_FontTable cmap

Borrowed character-map table.

Rbc_FontTable maxp

Borrowed maximum-profile table.

int id

Document-local font identifier.

int units

Font design units per em.

int glyphCount

Number of glyphs in the source program.

int metricsCount

Number of long horizontal metrics.

int count

Number of assigned document character IDs.

int capacity

Allocated capacity of character/glyph mapping arrays.

int isCff

Nonzero for CFF outlines instead of TrueType outlines.

int fontIds[258]

Backend resource IDs; zero until the PDF writer reserves them.

Rbc_FontTable cff

Borrowed CFF table.

Rbc_FontTable cffStrings

Borrowed CFF string INDEX.

unsigned short *sids

Owned CFF glyph-name string-ID array.

int *glyphs

Owned native-glyph array indexed by document character ID minus one.

Tcl_UniChar *characters

Owned Unicode array indexed by document character ID minus one.

Tcl_HashTable codes

Unicode-to-document-character-ID cache.

Tcl_Encoding symbolEncoding

Retained Tcl encoding for symbol-font mappings, or NULL.

char name[128]

NUL-terminated export font name.

struct Rbc_FontTable

Borrowed byte view into a font program; invalidated when its owner releases the program.

Public Members

const unsigned char *bytes

First table byte, or NULL for an absent table.

size_t length

Number of available bytes.

struct Shadow

Text shadow color and pixel displacement.

Public Members

XColor *color

Borrowed shadow color, or NULL to omit the shadow.

int offset

Shadow displacement in pixels.

struct TextFragment

One line of a multiline layout.

Text is borrowed from the original string.

Public Members

const char *text

Borrowed UTF byte span; count gives its length and it need not be NUL-terminated.

int x

X-Y offset of the baseline from the upper-left corner of the bounding box.

int y

X-Y offset of the baseline from the upper-left corner of the bounding box.

int sx

Reserved screen-coordinate fields.

int sy

Reserved screen-coordinate fields.

Tcl_Size count

Number of bytes in text.

The actual character count may differ because of multi-byte UTF encodings.

int width

Width of segment in pixels.

This is used to draw PostScript strings at the same width as the screen representation.

struct TextLayout

Single variable-size allocation of measured text fragments.

Public Members

Tcl_Size nFrags

Number of text fragments.

int width

Dimensions of text bounding box.

int height

Dimensions of text bounding box.

TextFragment fragArr[1]

Inline fragment records; allocation extends to nFrags entries.

Fragment strings remain borrowed.

struct TextStyle

Shared text attributes.

Font, colors and border are borrowed; the GC is released by Rbc_FreeTextStyle(). Initialization does not initialize every field.

Public Members

unsigned int state

If non-zero, indicates to draw text in the active color.

int width

Extents of text.

int height

Extents of text.

XColor *color

Normal color.

XColor *activeColor

Active color.

Tk_Font font

Font to use to draw text.

Tk_3DBorder border

Background color of text.

This is also used for drawing disabled text.

Shadow shadow

Drop shadow color and offset.

Tk_Justify justify

Justification of the text string.

This only matters if the text is composed of multiple lines.

GC gc

GC used to draw the text.

double theta

Rotation of text in degrees.

Tk_Anchor anchor

Indicates how the text is anchored around its x and y coordinates.

Rbc_Pad padX

pixels padding of around text region

Rbc_Pad padY

pixels padding of around text region

int leader

pixels spacing between lines of text