Freetype Library

  1. How To Install Freetype Library
  2. Freetype Library Not Found

Keith Packard
XFree86 Core Team, SuSE Inc.
keithp@keithp.com

  1. FreeType is a software font engine that is designed to be small, efficient, highly customizable and portable while capable of producing high-quality output (glyph images). It can be used in graphics libraries, display servers, font conversion tools, text image generation tools, and many other products as well.
  2. Note that unlike other FreeType objects, the library doesn't keep a list of all allocated glyph objects. This means you have to destroy them yourself instead of relying on FTDoneFreeType doing all the clean-up. Transforming & copying the glyph image.
  3. Creating a new instance of the FreeType 2 library and setting the handle library to it, and loading each module that FreeType knows about in the library. Among others, your new library object is able to handle TrueType, Type 1, CID-keyed & OpenType/CFF fonts gracefully.

Abstract:

The X Render Extension provides a new glyph rendering architecture based onclient-side glyph and font management. While this resolves many toughtechnical issues relating to the extension design, it places the burden ofrasterizing, configuring and customizing font usage on every X client. Acute email ids production engine crack.

Freetype Library

Many times when WINE complains about missing libraries it's because it's looking for the 32-bit libraries, e.g.

The Xft library was written to provide X applications a convenient interfaceto the FreeType font rasterizer and the Render extension. As FreeTypeprovides for no configuration or customization, Xft also performs thistask. Xft provides new font naming conventions, sophisticated font matchingand selection mechanisms and sufficient abstrations to permit commonapplications to benefit from Render extension based text output whilestill working on X servers without support for this extension.

The X Render Extension[Pac01] moves font access and glyph imagegeneration from the X server to the X client. Client-side glyph managementprovides several advantages for X applications: access to every detail ofthe font-file, application-specific fonts, incremental rasterization and theability to share known fonts with other parts of the environment, such asprinters.Additionally, as the underlying rendering mechanism refers only to imagesand not glyphs, the glyph rasterization technology and even the font fileformat itself no longer depends on the capabilities of the X server.Integrating new font technologies can now move at the rapid speed ofindividual application development rather than the glacial speed of thegeneral availabilty of new X server enhancements.

With the X server no longer in charge of managing font file access andrasterization, a new library was needed to perform this task on the clientside of the wire. As the Render extension was designed to supportanti-aliased graphics, this new library needed to provide support forhigh-quality anti-aliased glyph rasterization.

The FreeType project[TT00] has developed a complete fontrasterization engine for most outline font formats along with standard X PCFbitmap fonts. The Render extension takes glyph images and presents them onthe screen. All that was needed was a thin layer of glue code to fitbetween FreeType and the Render extension to enable applications to presenthigh-quality text on the screen.

For X servers not supporting the Render extension, the library should provideaccess to ``core' fonts (fonts accessed through the original core Xprotocol). This permits applications to move to the new library withoutleaving legacy X server support behind.

The FreeType library shies from specifying how font files are located;instead it requires that applications provide file names from which fontsare loaded. This places the burden of configuring and customizing the setof available fonts outside of the FreeType library. This new ``glue' layerwould have to provide some configuration to be usable in a desktopenvironment.

The X Render extension provides a couple of simple abstractions forapplication management of glyphs. Each Glyph contains an ``alpha' mask (arectangular image of opacity values) covering the glyph shape, an offsetfrom the origin of the alpha mask to the nominal glyph origin and a defaultescapement (with both horizontal and vertical offsets) to the next glyph. Acollection of Glyphs are contained in a GlyphSet and are numbered by theapplication with arbitrary 32-bit indices.

Applications draw text by sending a GlyphSet identifier and a list ofindices in that set. The server sets each glyph by rendering the alphamask at the specified drawing location adjusted by the glyph offset.Successive glyphs are positioned by adding the escapement vector to thecurrent origin. Just as with the core PolyText requests, sequences ofglyphs can be alternated in the same request with position adjustments andGlyphSet changes. This allows a complex string to be rendered ina single operation.

As the required set of operating system language and locale support expandsto cover more of the world's peoples, the number of glyphs included in mostfonts also increases. Popular outline fonts contain thousands of glyphstoday. Where incrementally rendering glyphs was considered a reasonableoptimization ten years ago, it is now an essential part of any fontmechanism to minimize the memory usage of each font and reduce the timetaken when accessing a new font. The Render extension provides for suchincremental rasterization by allowing Glyphs to be added when needed to anexisting GlyphSet. No information flows from the X server to the clientwhen adding new Glyphs which makes the process entirely asynchronous. Thisasychrony permits reasonable performance even in the face of high networklatency.

As applications transmit images of each glyph they display, the X serverconserves memory by sharing identical glyphs wherever possible. Thiseliminates duplicate glyphs both when sent by separate applications and evenwithin each application. While the Render extension also provides theability for applications to share the job of rasterizing glyphs, this hasn'tyet been exploited and offers the possibility of future performanceenhancements.

Setapp crack mac. The FreeType project was originally formed to build a freely availablerasterizer for TrueType fonts. The first version of the FreeType libraryprovided a high-quality TrueType rasterizer essentially matching existingsystems.

The second version of the FreeType library generalizes the rasterizerinternals to provide support for many more formats--Type-1, OpenType and CIDoutline formats are now supported along with the current standard X``Portable Compiled Format' used for bitmap fonts.

FreeType provides interfaces for measuring and rasterizing glyphs as well asmechanisms to access tables within the font file for kerning and glyphsubstitution of various forms. Rosary in latin. This provides applications with the dataneeded to position glyphs for a variety of locales, as long as theunderlying font includes the necessary tables.

As the FreeType project was clearly building a general font library, theburden of developing a new library within XFree86 was significantly reduced byadopting this existing system and providing ``glue code' to adapt theFreeType data structures to those needed by the Render extension. This doesexpose applications to changes in the FreeType library, but as FreeType is amature project, such changes are likely to be less severe than would berequired from any new library developed by XFree86.

Font naming and configuration are not a part of the FreeType library. Thisparticular chore is left to the application. As FreeType is used in manyenvironments, some of which don't even have a file system, this designserves to ensure that FreeType remains free of system policy while providingfor the widest possible use. Providing such support turned out to be thehardest part of Xft, and the part which will likely be replaced in the nearfuture.

How To Install Freetype Library

The core protocol provides for unstructured string font names. The X LogicalFont Description[SG92] (XLFD) was designed to place some structure on theformat of these string names. As outline fonts for desktop computing was arelative novelty when X was developed, the core protocol and the XLFD wereboth designed based on bitmapped fonts. The semantics and syntaxsurrounding scalable names was added after a significant period ofXLFD-based development had already occurred.

The intent of the font name syntax in the XLFD was to provideapplications sufficient information about the font from the name alonepermitting font selection and font list presentation to be performed withoutreference to the underlying font data itself.

The XLFD also provide a standard policy for opening fonts using namescontaining `?' and `*'. For such names, the font selected is that whichwould have been returned first in response to a request to list fonts usingthe same pattern. Unfortunately, this doesn't ensure that `*' is areasonable default value as the server keeps font names internally sortedwithin each font directory for efficient searching. For example, whenattempting to use `*' for the font weight the server will list `bold' before`normal'.

Where this policy really failed was in the mapping of point sizes to pixelsizes. XLFD provides pixel size, point size and resolution in both axes inthe font name. The standard X fonts are segregated by resolution, separate`75dpi' and `100dpi' directories contain fonts at various point sizesfor those resolutions. Additional directories of fonts are generallyrasterized for 75dpi screens.

The protocol directs the X server to search the font directories in theorder presented by the font path. This makes the font path dictate whichresolution is preferred. If the 100dpi directory is listed first,applications specifying `*' for the resolution fields will use 100dpi fontswhere they exist and 75dpi fonts otherwise.

Applications specifying only point size and using `*' for resolution end upwith a collection of random sized fonts--those found in the 100dpidirectory will be rasterized for a 100dpi screen, the remainder of the fontsare generally rasterized for a 75dpi screen and appear smaller as a result.

The end result is that XLFD font matching is fraught with peril;applications attempting it often resort to listing available fonts andthen presenting fully qualified XLFD names back to the server.

One further issue with the XLFD is that it includes the average width of theglyphs as a part of the name. While this is a useful piece of informationfor applications interested in selecting among various setwidths, and iseasily computed for bitmapped fonts, outline fonts can't generally computethis without rasterizing all glyphs at the desired size. Simply listing thefonts available at a particular size involves rasterizing every glyphfor every font.

XLFD provides useful information about the available fonts, and except forthe average width field, this information is easily computed and deliveredback to applications. Applications using XLFD names should avoid usingserver-side font matching and instead manage XLFD names locally, generatingappropriate fully qualified names using information gleaned from listing theavailable fonts.

As XLFD names don't provide for reasonable matching semantics, a new schemewas required to permit the underlying font system to locate a suitable fontgiven a set of constraints provided by the application. Such a systemneeded to be flexible enough to encompass unimagined new font propertieswhile not requiring that applications fully specify every aspect of the font.

Xft interacts with its environment in three areas; with applications througha programming interface, with the system through configuration files andwith users as they provide font names. While these three areas interactwithin the library, they are separable from the design perspective.

Application Interface Design

The primary goal of Xft was to connect the output of the FreeType rasterizerwith the Render extension. However, to gain some acceptance of Xft asa replacement for the existing Xlib text output routines, a secondary goalwas to also support core X fonts, albeit with some compromise on applicationfunctionality.

Because FreeType doesn't provide for font selection, a portion of Xftprovides for font matching. Adopting the existing XLFD mechanism would havesignificantly restricted the capabilities for font matching, so Xft providesa new format. This selection mechanism is designed to always match somefont, permiting applications to assume that suitable fonts exist andavoiding fallback mechanisms at every level.

Another requirement is that the library provide reasonable matches, such assubstituting oblique fonts when italic is requested and using medium weightfonts when no weight is specified. This permits applications to specifyfonts without all of their characteristics and expect reasonable results.In cases where the application request contains conflicting requirements,policy about which characteristics are most important provides resolution.

To simplify text encoding options at the library level, all text outputroutines accept only Unicode-encoded data. Other encodings are converted bythe application, either at the boundary with the operating system or betweenthe application and Xft. As existing fonts generally provide a Unicodeencoding, or one easily converted to Unicode, this dramatically simplifiesthe internals of the library while exposing a consistent view to theapplication.

Another important goal was to minimize the exposure of internal datastructures to applications. As the Render extension permits incrementaldownloads of new glyphs, Xft is designed to rasterize new glyphs on demand.This requires that metric information be requested through a function ratherthan directly accessed from the data structures as is done in Xlib.

Finally, as Xft is not designed as a complete font access library, theunderlying FreeType data types are exposed for applications to use directlywith FreeType itself. This reduces the complexity of Xft while stillallowing applications full access to the available font information.

Font Naming Design

The design of font names for Xft started with the notion that font namesrepresent properties of the font, either properties desired by anapplication or properties presented by the font itself. As the requirementsof an application are not fixed, and the characteristics of fonts continue tobe enhanced, an idea emerged of representing a font name as a variable listof named properties, each with an associated set of values. Allowing morethan one value for each property provides the ability to specify alternativeacceptable values for aspects of the font like family names or styles.

This design unifies the representation of application font requests andavailable fonts. An ``XftPattern' is a collection of named properties;each property holds one or more values. Each available font is described asan XftPattern providing characteristics of the font. Applications buildXftPatterns describing their requirements which are then matched against theXftPatterns describing all of the available fonts. The available font mostclosely matching the application specification is selected. Thisnearest-matching mechanism ensures that every application font request willbe matched by a font, although the precise characteristics of that font maydiffer from the application's request.

Finally, a textual representation for XftPatterns was designed. This permitsapplications to be configured much as they are today by using a string toselect a font.

XftPatterns provide a simple and extensible mechanism for communicatingrequirements and capabilities between the application and the fonts ituses. Their usage is described in Section 6.

Font Listing Design

The core protocol provides primitive support for querying the set ofavailable fonts; a simple shell-style pattern is passed to the X server andthe set of font names matching that pattern is returned. There is no way ofdiscovering the set of available font families without getting a list whichincludes essentially all of the fonts in the system. Applications areresponsible for extracting the information they need from this mass of data.

What was needed, instead, was the ability to ask the system for specificrelevant information and to have it discard redundant data. Applicationscould then focus on examining and manipulating the information, rather thanexpend significant effort parsing XLFD strings.

Xft splits the information needed to return data about available fonts intotwo pieces. The first is a pattern which is used to select from theavailable fonts. The second is a set of property names used to determinewhat information the application is interested in receiving. The list ofmatching fonts would be pared to eliminate entries with duplicate values inthe selected properties.

Finally, the notion of ``best match' isn't useful in listing fonts;applications use font lists to generate dialogs for the user or to discovercapabilities of a family of fonts. Instead of measuring the distance fromthe requested pattern to the available fonts, an exact match is required forall elements of the pattern.

Configuration Design

To avoid the possible proliferation of incompatible font configuration andcustomization mechanisms, a standard was needed. As no existing standardexisted, adding configuration to Xft at least ensured that X applicationscould share fonts and name them in the same way.

An essential customization requirement is to allow one font to stand-in foranother. These ``aliases' help maintain the general appearance of text byselecting faces with similar characteristics to unavailable faces. Anotheruseful role is in supporting generic `mono', `sans' and `serif' faces whichapplications can use to follow the users preference in each of these commoncases.

Another goal was to make adding fonts as easy as possible. The core X fontconfiguration mechanism uses the X server font path to list the set ofdirectories in which to find fonts. In each of these directories, twoseparate configuration files must be generated which map font names to filenames. If these files are missing or corrupted, font selection will notwork properly. By eliminating such configuration files, the overall systemwould be more robust.

Finally, users and administrators need to customize the rasterization ofspecific fonts. Some users wish to avoid anti-aliased text at a range ofsizes, or for specific faces. Others need to adjust the size or spacing ofcertain fonts.

As it turns out, Xft is not quite the right place for all suchconfiguration--X applications aren't the only ones interested in accessingfonts and font information. Moving this configuration mechanism out of Xftand into a library usable by non-X applications will be a focus ofdevelopment in the near future.

Font names in Xft are represented as a list of named properties, each ofwhich carries a list of typed values. This collection of properties isstored in an XftPattern data structure. There are routines to createXftPatterns, edit them and perform matching operations against the list ofavailable fonts. Xft has a list of properties, shown inTable 1, which it supports internally;there is no restriction that applications use only these, Xft willignore those it doesn't understand.

Table 1:Xft Font Name Properties.
NameTypeC Name
familyStringXFT_FAMILY
styleStringXFT_STYLE
slantIntXFT_SLANT
weightIntXFT_WEIGHT
sizeDoubleXFT_SIZE
pixelsizeDoubleXFT_PIXEL_SIZE
encodingStringXFT_ENCODING
spacingIntXFT_SPACING
foundryStringXFT_FOUNDRY
coreBoolXFT_CORE
antialiasBoolXFT_ANTIALIAS
xlfdStringXFT_XLFD
fileStringXFT_FILE
indexIntXFT_INDEX
rasterizerStringXFT_RASTERIZER
outlineBoolXFT_OUTLINE
scalableBoolXFT_SCALABLE
rgbaIntXFT_RGBA
scaleDoubleXFT_SCALE
renderBoolXFT_RENDER
minspaceBoolXFT_MINSPACE
dpiDoubleXFT_DPI
charwidthIntXFT_CHAR_WIDTH
charheightIntXFT_CHAR_HEIGHT
matrixMatrixXFT_MATRIX

To permit XftPatterns to be transmitted and stored, a string representationexists which can capture the structure of a pattern. The formatof these strings is shown in Figure 1.

Each of the supported names has an implicit type which is used to parse theassociated values. This reduces the need for quoting or other lexicalmechanisms to distinguish amongst the various types. As is shown, namedconstants can take the place of either values or complete name=value pairs.As the constants uniquely determine their associated property name, there isno need to supply that as well. Refer to Table 2 for alist of the available constants.
Table 2:Xft Font Name Constants.
NameConstantValue
weightlight0
medium100
demibold180
bold200
black210
slantroman0
italic100
oblique110
spacingproportional0
mono100
charcell110
rgbargb1
bgr2
vrgb3
vbgr4

Each of these constants is represented internally by a numeric value; thispermits similar matches by comparing the value from the available fonts withthe value requested by the application. An application requesting `demibold'will select `bold' instead of `medium'. This helps ensure that the intentof the application is fulfilled, even when the available fonts don't matchthose present during development and testing.

Additionally, while XLFD names are not ideal, they are common in existing Xapplications and do represent a set of desired font characteristics. Xftcan convert an XLFD name into an XftPattern which can then be used to selecta font using Xft matching rules rather than the XLFD matching rulesdescribed in Section 4.

Xft font names are designed to be extensible so that existing applicationswill continue to to operate correctly even while the Xft/FreeType2 interfacecontinues to grow and provide pattern elements for newer systems.

Using the core protocol, all applications are ensured of having access toall of the available fonts as it is the X servers responsibility to locatethem. With font management now moving to the client side, locating fontsbecomes the responsibility of the application. Without a central sharedconfiguration mechanism, the set of available fonts for each application maywell be different. Installing and selecting fonts would be problematic anderror prone.

The main job, then, of the Xft configuration file is to specify the locationof available font files. Secondary to this is the role of adjusting fontselection and customizing rasterization parameters.

By default, the Xft configuration file `XftConfig' is found in/usr/X11R6/lib/X11. This can be overridden by specifying an alternatefilename in the XFT_CONFIG environment variable.

Comments can be placed anywhere in the file with the `#' character andextend to the end of the line. The remaining syntax will be exposed insubsequent sections.


Font Directories

Xft takes a simplistic view in configuring where fonts are to be found. Alist of directories are specified and Xft searches those for font files, allof the font files it finds are added to the list of available fonts formatching. The order within the directories is irrelevant; Xft alwayssearches for the best match among all of the fonts. Directories arespecified in the config file with a line of the form:

No special configuration of the directory is required, Xft scans thedirectory looking for font files automatically.

Nested Configuration Files

To split the configuration file into manageable parts, and to allow forper-user customization of the library, the Xft configuration file allows forlines of the form:

The only difference is that the first form will cause Xft to emit a warningmessage when the referred file can't be found. The `~' characterrefers to the user's home directory; as the Xft configuration file is parsedby the user's applications themselves, this permits per-user customizationwithout referring to the X display.


Font Pattern Editing

To provide for font substitution and other adjustments in the font matchingprocess along with allowing for the configuration of the rasterizationprocess, the Xft configuration file can contain operations which modify theXftPattern before the matching process is done. These operations are called``editing commands' and operate by matching the incoming pattern andmodifying it. Each command is executed in the order it appears in theconfiguration file. The syntax for these commands is found inFigure 2.

The match clauses select which patterns are selected for editing; all mustbe true for the edit to be performed. Matches prefixed with `any' aretrue if any of the values associated with the named field satisfy thecondition. Matches prefixed with `all' are true only when all of thevalues satisfy the condition.

The edit clauses operate on the fields of the pattern and can either replaceor amend the values found for the associated field. If the match clausecontains a reference to the same element of the pattern, the matching valueis marked.

Edits using the `+=' operator will insert their value before the markedvalue. Edits using the `=+' operator will insert their value after themarked value. Edits using the `=' operator will replace the marked valuewith their value. If no value is marked, the `+=' and `=+' operatorsprepend/append their associated value to the list of values while the `='operator replaces all existing values with its associated value.

The operators within the expressions operate in the obvious manner,one possibly unexpected operation is that the `+' operator can operate onstrings and will concatenate them. Fields within the font may be referredto within an expression; the first value associated with the field is used.

After using this mechanism for several months, it has become clear that itis very complex and yet incapable of performing expected tasks. Onedeficiency is that the edits affect only the incoming pattern and do notoperate on the matched font. This makes the example of disablinganti-aliasing for LuciduxSerif fonts produce unexpected results whenpresented with a name of the form:

Times,LuciduxSerif,serif-10
The `match' clause will succeed with this pattern, causing this Times fontto be displayed without anti-aliasing.

Another issue is that font aliases are difficult to specify and still don'tprovide precisely the desired semantics. There are two possible semanticsdesired for font aliases; the first is that certain faces shouldalways be substituted for others, the second is that certain facesmay be substituted for others when those are not found. An explicitstatement of this kind would both clarify the file format while improvingthe font matching semantics.

The goal for font matching in Xft is to accept a collection ofcharacteristics from the application and return the best font fromall of those available. The application provides a font specification inthe form of an XftPattern to the XftFontMatch function. The pattern isedited as described in Section 7.3. X resources are then usedto modify the pattern as shown in Table 3.

Table 3:Adjusting Xft values with X Resources.
X ResourceTypeEffectDefault
Xft.renderBoolDirects Xft to use client-side fontsHasRender
Xft.coreBoolDirects Xft to use server-side fonts!HasRender
Xft.antialiasBoolSelects whether glyphs are anti-aliasedTrue
Xft.rgbaNumberSpecifies sub-pixel order on LCD screens0
Xft.minspaceBoolEliminates extra leading between linesFalse
Xft.scaleNumberScales point size of all fonts1.0
Xft.dpiNumberUsed to convert point size into pixel sizeVertical screen dpi

If a pixel size was not specified by the application, it is computed bytaking the specified point size (if specified, else 12.0), multiplying thatby the scale factor and then converting it from points to pixels using thespecified dpi value. The other X resources are used as default values forthe associated pattern elements.

The fully specified pattern is then compared with all available fonts. Onlythe fields shown in table 4 are used in thiscomparison.

Table 4:Matching Order of Xft Field Comparisons.
OrderNameType
1foundryString
2encodingString
3antialiasBool
4familyString
5spacingNumber
6pixelsizeNumber
7styleString
8slantNumber
9weightNumber
10rasterizerString
11outlineBool

The order of fields in this table is significant; any mismatch in elementsearlier in the table override all matches in later elements. Missing elementsin a pattern or font are tacitly matched. Numbers are measured by themagnitude of their difference. This is how `oblique' selects `italic'instead of `roman'.

Field with multiple values are biased to prefer fonts which match earlier inthe list; this way the name

Times,LuciduxSerif,serif-10
will prefer to match `Times' over `LuciduxSerif'.

Once a font has been selected, an XftPattern is built which describes thatfont precisely allowing the application to discover what font was actuallyselected. This pattern includes information about the underlying font fileitself allowing applications direct access to any information unavailablethrough FreeType. Fields found in the pattern that don't occur inthe font are added; this allows applications to communicate information infont patterns, both to rasterizers and also within the application itself.

While the main goal of Xft is to provide client-side font support usingFreeType and the Render extension, it seemed reasonable to also provide someapplication compatibility by using core X fonts where the Render extensionwas unavailable. This, by necessity, restricts the capabilities of thelibrary, but even so, many applications can use Xft functions with eithercore or Render fonts without change. Others need only minor adjustments tonotice when FreeType functions cannot be used.

Core font handling takes two pieces; selection of fonts and rendering. Theselection of fonts is done by listing the available X fonts and convertingthose into XftPattern data structures and then accepting application patternsfor matching. As the matching is based on a ``nearness' metric instead ofsimple shell pattern matching, the resulting matching is generally moreuseful than that specified by the XLFD. This can simplify applicationswhich before had significant mechanism devoted to core X font matching.

Library

Once a core font is selected, rendering becomes a simple matter of havingthe Xft routines call the standard Xlib text drawing routines. The onlydifficulty is in mapping the Unicode glyphs provided by the application intothe encoding supported by the font.

One effect of this merging is that the general Xft rendering routines expose nocapabilities not provided by both Render and core fonts. Applications mayspecify a translucent color value for drawing, but it will be ignored whenusing core fonts. Similarly, there's no provision for selecting a rasteroperation or compositing operator as each is supported by only oneunderlying renderer.

The result is a new way of using the core fonts which is in many wayseasier to use and more powerful than the Xlib equivalents.

The Xft programming interface can be easily separated into three distinctareas: those dealing with XftPatterns and matching fonts, those dealing withdrawing glyphs on the screen and a small section providing an interface tothe underlying FreeType library.

How to install freetype library

Xft Data Structures

XftValue
An XftValue holds one value for an element of an XftPattern. It shouldbe treated as a tagged union; set and check the `type' field before usingthe union elements. Storage for the string and matrix elements isseparate. Xft always copies the data from these pointers when receivingXftValue structures from the application, this leaves applications free touse static or stack-based storage as appropriate.
XftPattern
An XftPattern is an opaque structure holding a list of named elements, eachof which holds a list of XftValues. Xft provides interfaces to build andquery these patterns.
XftFont
The XftFont data structure is returned when opening fonts and is used indrawing glyphs. The visible members provide a modicum of information aboutthe font. The `core' value will be True if the underlying font is a coreX font, in which case the u.core.font field will point at an XFontStruct.Otherwise, the underlying font is a FreeType font and the u.ft.font fieldrefers to an XftFontStruct.
XftFontStruct
This structure should probably become opaque with suitable accessorfunctions to reach the appropriate internal fields. The most useful memberis likely to be the `face' which refers to the underlying FreeTypeobject, however, as keeping that object resident in memory is ratherexpensive, it may be that this needs to become cached and loaded on demand.Applications wanting to use this field are wise to prepare for its eventualdisappearance by wrapping access in a macro. An audit of which other fieldsof this structure should be visible is needed.
XftDraw
An XftDraw encapsulates the state needed to render glyphs to an X drawable.For the Render extension, a Picture is needed while for core X, a GC andassociated pixel values are required.
XftColor
The Render extension needs RGBA while core X requires a pixel value. AnXftColor holds both, and routines exist to initialize and free anyassociated resources. For TrueColor visuals, the allocation routine avoidsa round trip by computing the pixel value locally, so there's no performancepenalty in that case. When it is know that the Render extension will beused, the `color' member can be initialized manually leaving the `pixel'value unset.
XftObjectSet
The font listing mechanism within Xft uses an XftObjectSet to restrict theamount of data returned to the application. An XftObjectSet holds a list offield names.
XftFontSet
XftFontSets reference a set of patterns and are used as the return valuefrom the font listing functions.
XftResult
Functions that return a search result use this data type to present theirfindings. XftResultMatch indicates that the object was found,XftResultNoMatch says that no matching object was found.XftResultTypeMismatch says that an object was found, but it was of the wrongtype while XftResultNoId says that an object was found, but that there werefewer values than requested.

Font Pattern Manipulation

Many Xft operations involve XftPattern objects. As those should not bedirectly accessed by the application, a set of routines exist to manipulatethem.
XftPatternCreate
This creates an empty pattern.
XftPatternDuplicate
A new pattern is created which contains all of the values from `p'.Values referring to other memory (strings and matrices) are copied to newlyallocated storage as well.
XftPatternDestroy
All referenced storage, including any strings and matrices referred to byvalues within the pattern, is freed.
XftPatternAdd
`value' is added to the list of values for the field `object'. If`append' is True, the value is added to the end of the list, otherwise itis insert at the head. If `value' refers to a string or matrix,XftPatternAdd will allocate new storage and copy the object into it.XftPatternAdd returns False only when allocating space for this operationfails. This function forms the basis for the remaining XftPatternAddfunctions.

Each of these functions createsa temporary XftValue with the appropriate type and value and passes it toXftPatternAdd with the `append' value set to True.

XftPatternGet
XftPatternGet searches the indicated pattern for an element whose namematches `object'. It then searches along the list of values for that namefor the `id'th element (starting at zero) and stores the resulting valuein v. It does not allocate new storage for strings or matrices, soapplications must ensure that the returned value not be referenced beyondthe life of the XftPattern itself. This function forms the basis for theremaining XftPatternGet functions.

Each of these convenience functions calls XftPatternGet. If the datatype ofthe resulting value doesn't match the type of the function, these functionsreturn XftResultTypeMismatch, otherwise they return the same thing asXftPatternGet.

XftPatternBuild
The arguments after `orig' form a list of pattern names, types and valuesto add to the specified pattern. If `orig' is null, a new pattern isallocated. The pattern arguments are of the form:The list is terminated with a NULL object. Here's an example:This function is a convenience function encapsulating several calls toXftPatternAdd in one statement, the semantics are identical to making theequivalent set of XftPatternAdd calls.This takes the a varargs list of arguments in the same format asXftPatternBuild, yielding identical results.


Font Selection

Xft exposes several levels of font selection functions. The patternsinvolved can either be implicitly generated using a simple font name string,or they can be explicitly managed by the application and manipulated beforebeing presented to the underlying interface for matching. Starting with themost primitive level, Xft provides:
XftFontMatch
This function takes the application-generated XftPattern, performs theconfig file edits and X resource substitutions and then matches the resultagainst the set of available fonts. The closest matching font name isreturned as another XftPattern which contains enough information to openthe font with the next function, XftFontOpenPattern. In case of failure,the return value is 0 and an indication of the error is placed in result.
XftFontOpenPattern
XftFontOpenPattern accepts a matched font pattern and creates an XftFontstructure for the font. The returned XftFont contains a reference to thepassed pattern, this pattern will be destroyed when the XftFont is passed toXftFontClose.
XftFontOpen
Arguments after `screen' form an implicit XftPattern as seen in thedescription of XftPatternBuild in Section 10.2.Here's an example:A pattern is created from the arguments and passed to XftFontMatch, theresult of that is passed to XftFontOpenPattern which produces the returnvalue for this function.
XftFontOpenName
Similar to XftFontOpen, the `name' argument forms an implicit XftPattern,XftFontMatcn and XftFontOpenPattern are used in the same fashion to producea matching XftFont.
XftFontOpenXlfd
This functions precisely as XftFontOpenName except that the XftPattern isgenerated by parsing the XLFD name `xlfd'.
XftFontClose
The underlying core or FreeType font object is closed and the patternreferenced by the font is destroyed.

XftDraw Manipulation

Xft provides an abstraction that masks the differences between core Xand Render extension rendering. The XftDraw object provides thetarget for either mode, wrapping suitable information for either renderingmodel.

XftDrawCreate
This routine creates an XftDraw object referencing mentioned drawable alongwith its associated visual and colormap. The visual argument is requiredeven for pixmap rendering as it specifies the eventual format for the pixelvalues.
XftDrawCreateBitmap
When the rendering target is a 1-bit bitmap, this function is used in placeof XftDrawCreate.
XftDrawChange
This function switches the underlying rendering target without affecting anyother properties of the XftDraw object. Applications are responsible forensuring that the drawable uses the same visual as the original drawable.
XftDrawDisplay,XftDrawDrawable,

XftDrawColormap,XftDrawVisual
These functions simply return the associated value from the opaque XftDrawstructure.
XftDrawDestroy
This destroys the XftDraw object and any private data allocated therein.The X drawable referenced is not destroyed.

Glyph Rendering

With an XftFont and an XftDraw in hand, the next step is to use themtogether and present some text on the screen. This is relatively simple asthe encoding is always Unicode and the only thing that changes is how thoseglyphs are stored. This section also documents a few other conveniencefunctions for applications wanting to use similar data structures for otheroperations.
XftTextExtents
These functions measure the extents of the specified string and returns themetrics in the `extents' structure.
XftDrawString
Each of these functions displays a single string. For Render text, thestring is painted using the Over operator. For core text, it ispainted with GXcopy and a full planemask.
XftDrawRect
This simple function paints a single rectangle in the specified color.
XftDrawSetClip
The clip list for the specified XftDraw is set from the specified region.Alternative functions taking lists of rectangles should probably be added.

Font Listing

Xft provides a relatively complex mechanism for listing available fonts.This allows the same mechanism to list available faces as well as availablestyles for a particular face without returning extraneous data. This isaccomplished by having the application declare which fields of the fontpatterns are important and separately provide a pattern to select matchingfonts. For each matching font, an entry for the returned list is generatedby extracting only those fields selected by the XftObjectList provided by theapplication. A unique set of such entries is returned to the application.

Because listing fonts is a fundamentally separate process from opening asingle font, the semantics for how patterns match fonts in this process isdifferent than in Section 10.3. Matching in thiscontext requires that each of the elements of the pattern must have onevalue which precisely matches the associated font element.

XftObjectSetCreate
Creates an empty XftObjectSet.
XftObjectSetAdd
Add a single field name to an XftObjectSet. Storage is allocated for thename and it is copied from the argument permitting the application torelease or reuse its own copy.
XftObjectSetDestroy
The XftObjectSet is destroyed along with any other referenced storage.
XftObjectSetBuild, XftObjectSetVaBuild
XftObjectSetBuild creates an XftObjectSet from a list of object namesterminated with NULL. This permits the quick construction of a constant setof names without a long sequence of calls and is semantically equivalent tosuch a sequence of calls. XftObjectSetVaBuild takes an existing varargslist and does the same thing.
XftListFontsPatternObjects
For each font matching `pattern', a new pattern is generatedincluding only those elements specified in `os'. This function thenmerges each new pattern into the return value so that only unique patternsare included.
XftListFonts
The variable arguments include a list of pattern elements as seen in thedescription of XftPatternBuild inSection 10.2 followed by a NULL. Following that, a list offield names as described by XftObjectSetBuild in this section followed byanother null. With the pattern and object set generated, this functioncalls XftListFontPatternObjects and returns the same result.

FreeType Access

Where more complex interactions with the underlying FreeType library orRender extension are required, Xft provides some functions to access those moredirectly.

Freetype Library Not Found

XftFreeTypeGet
This returns the underlying XftFontStruct object for the given font, or NULLif the underlying font is not a FreeType font.
XftRenderString
These four related functions all provide a bit more control over thedrawing of text with the Render extension. In particular, they provide foran arbitrary source picture which can be used to pattern the text.Applications might also be able to perform more efficient caching of thesource Picture data with these routines;

As described in Section 7.1, the library generates the setof available fonts by scanning each of the directories listed in theconfiguration files. Discovering the properties of a font requires that thefont file be opened by FreeType and a significant amount of the fileprocessed. This can take quite some time, especially with a large number offonts.

To improve the performance of this operation, Xft caches the results of thissearch in two places. Each directory may contain a file namedXftCache which contains a list of fonts, one per line with the fontfile name, the index within the file of the font and information about thefont represented as an XftPattern in string form. For any fonts not foundin an XftCache file, Xft generates a .xftcache file in theusers home directory containing the font file name, font index, the filemodification time and the XftPattern.

Freetype

XftCache files are built by the xftcache program, a standard part of theXFree86 release. Users are encouraged to run this on other directoriesadded to the Xft configuration file, and to re-run it whenever the contentsof those directories change. Xft will automatically manage the contents ofeach per-user .xftcache file to save unknown fonts while eliminatinginformation present in an XftCache file.

Xft still scans each directory at startup time, but it first checks theper-directory and per-user caches for the filename before attempting to openit with FreeType. This dramatically reduces applications startup time whileretaining the accuracy provided by querying directory contents.

Xft started as a relatively small effort to bind the X Render extension withthe FreeType rasterizer. It gained new capabilities as needed to providesupport for more applications. All of this new functionality has beennecessary, but some of it has outgrown this X-centric library. Inparticular, the font configuration mechanism must be extracted from Xft andplaced in a separate library to be shared with printer drivers and othernon-X font consumers. This will ensure that fonts can be easily installedand managed for the benefit of all applications, not just those displayinginformation on the screen.

Xft also needs additional capabilities to support internationalization.Right now, the XftFont object refers to a single FreeType font. If thatfont doesn't contain all of the glyphs necessary to render a particulardocument, the missing glyphs will not be displayed correctly. Somemechanism for finding replacement glyphs is needed. The XftFontstructure should be extended to optionally perform automatic glyphsubstitution using multiple underlying FreeType faces.

For applications not wanting automatic substitution, it should be possibleto match fonts based on required subsets of Unicode glyphs; the informationabout glyph coverage is present in each font file, applications should beable to specify the needed range of glyphs and have Xft match fonts based onthose requirements.

The development of Xft has followed a different model from most of Xdevelopment. Early versions of the library were released and integratedinto other projects; other X projects have waited until they wereessentially stable before being reviewed by the community at large.

As use of the library has grown, some major improvements have been addedwithout significantly impacting those other projects. Future enhancementsmay require changes to existing applications, but that should be viewed as apart of this process; much of this library is breaking new ground for theXFree86 community and only through widespread review and use can appropriatearchitecture be developed.

The design and implementation of Xft has progressed rapidly. Even thoughXft was started only one year ago it has already become an essential partof many current X projects.

Bibliography

  • MOST POPULAR ARTICLES