# Locales and Internationalized Text Functions

An internationalized application is one that is adaptable to the requirements of different native languages, local customs, and character string encodings. The process of adapting the operation to a particular native language, local custom, or string encoding is called localization. A goal of internationalization is to permit localization without program source modifications or recompilation.

As one of the localization mechanisms, Xlib provides an X Input Method (XIM) functional interface for internationalized text input and an X Output Method (XOM) functional interface for internationalized text output.

Internationalization in X is based on the concept of a locale. A locale defines the localized behavior of a program at run time. Locales affect Xlib in its:

- Encoding and processing of input method text

- Encoding of resource files and values

- Encoding and imaging of text strings

- Encoding and decoding for inter-client text communication

• Encoding and decoding for inter-client text communication Characters from various languages are represented in a computer using an encoding. Different languages have different encodings, and there are even different encodings for the same characters in the same language.

This chapter defines support for localized text imaging and text input and describes the locale mechanism that controls all locale-dependent Xlib functions. Sets of functions are provided for multibyte (char *) text as well as wide character (wchar_t) text in the form supported by the host C language environment. The multibyte and wide character functions are equivalent except for the form of the text argument.

The Xlib internationalization functions are not meant to provide support for multilingual applications (mixing multiple languages within a single piece of text), but they make it possible to implement applications that work in limited fashion with more than one language in independent contexts.

The remainder of this chapter discusses:

- X locale management

- Locale and modifier dependencies

- Variable argument lists

- Output methods

- Input methods

- String constants

## X Locale Management

X supports one or more of the locales defined by the host environment. On implementations that conform to the ANSI C library, the locale announcement method is `setlocale`. This function configures the locale operation of both the host C library and Xlib. The operation of Xlib is governed by the LC_CTYPE category; this is called the current locale. An implementation is permitted to provide implementation-dependent mechanisms for announcing the locale in addition to `setlocale`.

On implementations that do not conform to the ANSI C library, the locale announcement method is Xlib implementation-dependent.

The mechanism by which the semantic operation of Xlib is defined for a specific locale is implementation-dependent.

X is not required to support all the locales supported by the host. To determine if the current locale is supported by X, use `XSupportsLocale`.

Bool XSupportsLocale()

The `XSupportsLocale` function returns True if Xlib functions are capable of operating under the current locale. If it returns False, Xlib locale-dependent functions for which the XLocaleNotSupported return status is defined will return XLocaleNotSupported. Other Xlib locale-dependent routines will operate in the ``C'' locale.

The client is responsible for selecting its locale and X modifiers. Clients should provide a means for the user to override the clients' locale selection at client invocation. Most single-display X clients operate in a single locale for both X and the host processing environment. They will configure the locale by calling three functions: the host locale configuration function, `XSupportsLocale`, and .

The semantics of certain categories of X internationalization capabilities can be configured by setting modifiers. Modifiers are named by implementation-dependent and locale-specific strings. The only standard use for this capability at present is selecting one of several styles of keyboard input method.

To configure Xlib locale modifiers for the current locale, use .

      char *XSetLocaleModifiers
      char *modifier_list

modifier_list

  Specifies the modifiers.

The function sets the X modifiers for the current locale setting. The modifier_list argument is a null-terminated string of the form ``{@category=value}'', that is, having zero or more concatenated ``@category=value'' entries, where category is a category name and value is the (possibly empty) setting for that category. The values are encoded in the current locale. Category names are restricted to the POSIX Portable Filename Character Set.

The local host X locale modifiers announcer (on POSIX-compliant systems, the XMODIFIERS environment variable) is appended to the modifier_list to provide default values on the local host. If a given category appears more than once in the list, the first setting in the list is used. If a given category is not included in the full modifier list, the category is set to an implementation-dependent default for the current locale. An empty value for a category explicitly specifies the implementation-dependent default.

If the function is successful, it returns a pointer to a string. The contents of the string are such that a subsequent call with that string (in the same locale) will restore the modifiers to the same settings. If modifier_list is a NULL pointer, also returns a pointer to such a string, and the current locale modifiers are not changed.

If invalid values are given for one or more modifier categories supported by the locale, a NULL pointer is returned, and none of the current modifiers are changed.

At program startup, the modifiers that are in effect are unspecified until the first successful call to set them. Whenever the locale is changed, the modifiers that are in effect become unspecified until the next successful call to set them. Clients should always call with a non-NULL modifier_list after setting the locale before they call any locale-dependent Xlib routine.

The only standard modifier category currently defined is ``im'', which identifies the desired input method. The values for input method are not standardized. A single locale may use multiple input methods, switching input method under user control. The modifier may specify the initial input method in effect or an ordered list of input methods. Multiple input methods may be specified in a single im value string in an implementation-dependent manner.

The returned modifiers string is owned by Xlib and should not be modified or freed by the client. It may be freed by Xlib after the current locale or modifiers are changed. Until freed, it will not be modified by Xlib.

The recommended procedure for clients initializing their locale and modifiers is to obtain locale and modifier announcers separately from one of the following prioritized sources:

- A command line option

- A resource

- The empty string ("")

The first of these that is defined should be used. Note that when a locale command line option or locale resource is defined, the effect should be to set all categories to the specified locale, overriding any category-specific settings in the local host environment.

## Locale and Modifier Dependencies

The internationalized Xlib functions operate in the current locale configured by the host environment and X locale modifiers set by or in the locale and modifiers configured at the time some object supplied to the function was created. For each locale-dependent function, the following table describes the locale (and modifiers) dependency:

Locale from | Affects the Function | In
--- | --- | ---
Locale Query/Configuration:
`setlocale` | `XSupportsLocale` | Locale queried
| Locale modified
Resources:
`setlocale` |  | Locale of XrmDatabase
XrmDatabase |  | Locale of XrmDatabase
Setting Standard Properties:
`setlocale` |  | Encoding of supplied/returned text (some WM_ property text in environment locale)
`setlocale` |  | Encoding of supplied/returned text
Text Input:
`setlocale` |  | XIM input method selection
| XIM selection
| XIM selection
XIM |  | XIC input method configuration
, and so on | Queried locale
XIC |  | Keyboard layout
| Encoding of returned text
Text Drawing:
`setlocale` |  | XOM output method selection
| Charsets of fonts in XFontSet
XOM |  | XOC output method configuration
, and so on | Queried locale
XFontSet | , | Locale of supplied text
, and so on | Locale of supplied text
, and so on , `XwcTextExtents`, and so on | Locale-dependent metrics
Xlib Errors:
`setlocale` | , , and so on | Locale of error message

Clients may assume that a locale-encoded text string returned by an X function can be passed to a C library routine, or vice versa, if the locale is the same at the two calls.

All text strings processed by internationalized Xlib functions are assumed to begin in the initial state of the encoding of the locale, if the encoding is state-dependent.

All Xlib functions behave as if they do not change the current locale or X modifier setting. (This means that if they do change locale or call with a non-NULL argument, they must save and restore the current state on entry and exit.) Also, Xlib functions on implementations that conform to the ANSI C library do not alter the global state associated with the ANSI C functions `mblen`, `mbtowc`, `wctomb`, and `strtok`.

## Variable Argument Lists

Various functions in this chapter have arguments that conform to the ANSI C variable argument list calling convention. Each function denoted with an argument of the form ``...'' takes a variable-length list of name and value pairs, where each name is a string and each value is of type XPointer. A name argument that is NULL identifies the end of the list.

A variable-length argument list may contain a nested list. If the name XNVaNestedList is specified in place of an argument name, then the following value is interpreted as an XVaNestedList value that specifies a list of values logically inserted into the original list at the point of declaration. A NULL identifies the end of a nested list.

To allocate a nested variable argument list dynamically, use .

      XVaNestedList XVaCreateNestedList
      int dummy

dummy

  Specifies an unused argument (required by ANSI C).

...

  Specifies the variable length argument list(Al.

The function allocates memory and copies its arguments into a single list pointer, which may be used as a value for arguments requiring a list value. Any entries are copied as specified. Data passed by reference is not copied; the caller must ensure data remains valid for the lifetime of the nested list. The list should be freed using when it is no longer needed.

## Output Methods

This section provides discussions of the following X Output Method (XOM) topics:

- Output method overview

- Output method functions

- Output method values

- Output context functions

- Output context values

- Creating and freeing a font set

- Obtaining font set metrics

- Drawing text using font sets

### Output Method Overview

Locale-dependent text may include one or more text components, each of which may require different fonts and character set encodings. In some languages, each component might have a different drawing direction, and some components might contain context-dependent characters that change shape based on relationships with neighboring characters.

When drawing such locale-dependent text, some locale-specific knowledge is required; for example, what fonts are required to draw the text, how the text can be separated into components, and which fonts are selected to draw each component. Further, when bidirectional text must be drawn, the internal representation order of the text must be changed into the visual representation order to be drawn.

An X Output Method provides a functional interface so that clients do not have to deal directly with such locale-dependent details. Output methods provide the following capabilities:

- Creating a set of fonts required to draw locale-dependent text.

- Drawing locale-dependent text with a font set without the caller needing to be aware of locale dependencies.

- Obtaining the escapement and extents in pixels of locale-dependent text.

- Determining if bidirectional or context-dependent drawing is required in a specific locale with a specific font set.

Two different abstractions are used in the representation of the output method for clients.

The abstraction used to communicate with an output method is an opaque data structure represented by the XOM data type. The abstraction for representing the state of a particular output thread is called an output context. The Xlib representation of an output context is an XOC, which is compatible with XFontSet in terms of its functional interface, but is a broader, more generalized abstraction.

### Output Method Functions

To open an output method, use .

      XOM XOpenOM
      Display *display
      XrmDatabase db
      char *res_name
      char *res_class

display

  Specifies the connection to the X server.

db

  Specifies a pointer to the resource database.

res_name

  Specifies the full resource name of the application.

res_class

  Specifies the full class name of the application.

The function opens an output method matching the current locale and modifiers specification. The current locale and modifiers are bound to the output method when is called. The locale associated with an output method cannot be changed.

The specific output method to which this call will be routed is identified on the basis of the current locale and modifiers. will identify a default output method corresponding to the current locale. That default can be modified using to set the output method modifier.

The db argument is the resource database to be used by the output method for looking up resources that are private to the output method. It is not intended that this database be used to look up values that can be set as OC values in an output context. If db is NULL, no database is passed to the output method.

The res_name and res_class arguments specify the resource name and class of the application. They are intended to be used as prefixes by the output method when looking up resources that are common to all output contexts that may be created for this output method. The characters used for resource names and classes must be in the X Portable Character Set. The resources looked up are not fully specified if res_name or res_class is NULL.

The res_name and res_class arguments are not assumed to exist beyond the call to . The specified resource database is assumed to exist for the lifetime of the output method.

returns NULL if no output method could be opened.

To close an output method, use .

      Status XCloseOM
      XOM om

om

  Specifies the output method.

The function closes the specified output method.

To set output method attributes, use .

      char *XSetOMValues
      XOM om

om

  Specifies the output method.

...

  Specifies the variable-length argument list to set XOM values.

The function presents a variable argument list programming interface for setting properties or features of the specified output method. This function returns NULL if it succeeds; otherwise, it returns the name of the first argument that could not be obtained.

No standard arguments are currently defined by Xlib.

To query an output method, use .

      char *XGetOMValues
      XOM om

om

  Specifies the output method.

...

  Specifies the variable-length argument list to get XOM values.

The function presents a variable argument list programming interface for querying properties or features of the specified output method. This function returns NULL if it succeeds; otherwise, it returns the name of the first argument that could not be obtained.

To obtain the display associated with an output method, use .

      Display *XDisplayOfOM
      XOM om

om

  Specifies the output method.

The function returns the display associated with the specified output method.

To get the locale associated with an output method, use .

      char *XLocaleOfOM
      XOM om

om

  Specifies the output method.

The returns the locale associated with the specified output method.

### X Output Method Values

The following table describes how XOM values are interpreted by an output method. The first column lists the XOM values. The second column indicates how each of the XOM values are treated by a particular output style.

The following key applies to this table.

Key | Explanation
--- | ---
G | This value may be read using .

XOM Value | Key
--- | ---
XNRequiredCharSet | G
XNQueryOrientation | G
XNDirectionalDependentDrawing | G
XNContextualDrawing | G

#### Required Char Set

The XNRequiredCharSet argument returns the list of charsets that are required for loading the fonts needed for the locale. The value of the argument is a pointer to a structure of type XOMCharSetList.

The XOMCharSetList structure is defined as follows:

    typedef struct {
         int    charset_count;
         char   **charset_list;
    } XOMCharSetList;

The charset_list member is a list of one or more null-terminated charset names, and the charset_count member is the number of charset names.

The required charset list is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XOM. Until freed, its contents will not be modified by Xlib.

#### Query Orientation

The XNQueryOrientation argument returns the global orientation of text when drawn. Other than `XOMOrientation_LTR_TTB`, the set of orientations supported is locale-dependent. The value of the argument is a pointer to a structure of type XOMOrientation. Clients are responsible for freeing the XOMOrientation structure by using ; this also frees the contents of the structure.

    typedef struct {
         int          num_orientation;
         XOrientation *orientation;     /* Input Text description */
    } XOMOrientation;

    typedef enum {
         XOMOrientation_LTR_TTB,
         XOMOrientation_RTL_TTB,
         XOMOrientation_TTB_LTR,
         XOMOrientation_TTB_RTL,
         XOMOrientation_Context
    } XOrientation;

The possible value for XOrientation may be:

- `XOMOrientation_LTR_TTB` left-to-right, top-to-bottom global orientation

- `XOMOrientation_RTL_TTB` right-to-left, top-to-bottom global orientation

- `XOMOrientation_TTB_LTR` top-to-bottom, left-to-right global orientation

- `XOMOrientation_TTB_RTL` top-to-bottom, right-to-left global orientation

- `XOMOrientation_Context` contextual global orientation

#### Directional Dependent Drawing

The XNDirectionalDependentDrawing argument indicates whether the text rendering functions implement implicit handling of directional text. If this value is True, the output method has knowledge of directional dependencies and reorders text as necessary when rendering text. If this value is False, the output method does not implement any directional text handling, and all character directions are assumed to be left-to-right.

Regardless of the rendering order of characters, the origins of all characters are on the primary draw direction side of the drawing origin.

This OM value presents functionality identical to the function.

#### Context Dependent Drawing

The XNContextualDrawing argument indicates whether the text rendering functions implement implicit context-dependent drawing. If this value is True, the output method has knowledge of context dependencies and performs character shape editing, combining glyphs to present a single character as necessary. The actual shape editing is dependent on the locale implementation and the font set used.

This OM value presents functionality identical to the function.

### Output Context Functions

An output context is an abstraction that contains both the data required by an output method and the information required to display that data. There can be multiple output contexts for one output method. The programming interfaces for creating, reading, or modifying an output context use a variable argument list. The name elements of the argument lists are referred to as XOC values. It is intended that output methods be controlled by these XOC values. As new XOC values are created, they should be registered with the X Consortium. An XOC can be used anywhere an XFontSet can be used, and vice versa; XFontSet is retained for compatibility with previous releases. The concepts of output methods and output contexts include broader, more generalized abstraction than font set, supporting complex and more intelligent text display, and dealing not only with multiple fonts but also with context dependencies. However, XFontSet is widely used in several interfaces, so XOC is defined as an upward compatible type of XFontSet.

To create an output context, use .

      XOC XCreateOC
      XOM om

om

  Specifies the output method.

...

  Specifies the variable-length argument list to set XOC values.

The function creates an output context within the specified output method.

The base font names argument is mandatory at creation time, and the output context will not be created unless it is provided. All other output context values can be set later.

returns NULL if no output context could be created. NULL can be returned for any of the following reasons:

- A required argument was not set.

- A read-only argument was set.

- An argument name is not recognized.

- The output method encountered an output method implementation-dependent error.

can generate a BadAtom error.

To destroy an output context, use .

      void XDestroyOC
      XOC oc

oc

  Specifies the output context.

The function destroys the specified output context.

To get the output method associated with an output context, use .

      XOM XOMOfOC
      XOC oc

oc

  Specifies the output context.

The function returns the output method associated with the specified output context.

Xlib provides two functions for setting and reading output context values, respectively, and . Both functions have a variable-length argument list. In that argument list, any XOC value's name must be denoted with a character string using the X Portable Character Set.

To set XOC values, use .

      char *XSetOCValues
      XOC oc

oc

  Specifies the output context.

...

  Specifies the variable-length argument list to set XOC values.

The function returns NULL if no error occurred; otherwise, it returns the name of the first argument that could not be set. An argument might not be set for any of the following reasons:

- The argument is read-only.

- The argument name is not recognized.

- An implementation-dependent error occurs.

Each value to be set must be an appropriate datum, matching the data type imposed by the semantics of the argument.

can generate a BadAtom error.

To obtain XOC values, use .

      char *XGetOCValues
      XOC oc

oc

  Specifies the output context.

...

  Specifies the variable-length argument list to get XOC values.

The function returns NULL if no error occurred; otherwise, it returns the name of the first argument that could not be obtained. An argument might not be obtained for any of the following reasons:

- The argument name is not recognized.

- An implementation-dependent error occurs.

Each argument value following a name must point to a location where the value is to be stored.

### Output Context Values

The following table describes how XOC values are interpreted by an output method. The first column lists the XOC values. The second column indicates the alternative interfaces that function identically and are provided for compatibility with previous releases. The third column indicates how each of the XOC values is treated.

The following keys apply to this table.

Key | Explanation
--- | ---
C | This value must be set with .
D | This value may be set using . If it is not set,a default is provided.
G | This value may be read using .
S | This value must be set using .

XOC Value | Alternative Interface | Key
--- | --- | ---
BaseFontName |  | C-G
MissingCharSet |  | G
DefaultString |  | G
Orientation | - | D-S-G
ResourceName | - | S-G
ResourceClass | - | S-G
FontInfo |  | G
OMAutomatic | - | G

#### Base Font Name

The XNBaseFontName argument is a list of base font names that Xlib uses to load the fonts needed for the locale. The base font names are a comma-separated list. The string is null-terminated and is assumed to be in the Host Portable Character Encoding; otherwise, the result is implementation-dependent. White space immediately on either side of a separating comma is ignored.

Use of XLFD font names permits Xlib to obtain the fonts needed for a variety of locales from a single locale-independent base font name. The single base font name should name a family of fonts whose members are encoded in the various charsets needed by the locales of interest.

An XLFD base font name can explicitly name a charset needed for the locale. This allows the user to specify an exact font for use with a charset required by a locale, fully controlling the font selection.

If a base font name is not an XLFD name, Xlib will attempt to obtain an XLFD name from the font properties for the font. If Xlib is successful, the function will return this XLFD name instead of the client-supplied name.

This argument must be set at creation time and cannot be changed. If no fonts exist for any of the required charsets, or if the locale definition in Xlib requires that a font exist for a particular charset and a font is not found for that charset, returns NULL.

When querying for the XNBaseFontName XOC value, returns a null-terminated string identifying the base font names that Xlib used to load the fonts needed for the locale. This string is owned by Xlib and should not be modified or freed by the client. The string will be freed by a call to with the associated XOC. Until freed, the string contents will not be modified by Xlib.

#### Missing CharSet

The XNMissingCharSet argument returns the list of required charsets that are missing from the font set. The value of the argument is a pointer to a structure of type XOMCharSetList.

If fonts exist for all of the charsets required by the current locale, charset_list is set to NULL and charset_count is set to zero. If no fonts exist for one or more of the required charsets, charset_list is set to a list of one or more null-terminated charset names for which no fonts exist, and charset_count is set to the number of missing charsets. The charsets are from the list of the required charsets for the encoding of the locale and do not include any charsets to which Xlib may be able to remap a required charset.

The missing charset list is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XOC. Until freed, its contents will not be modified by Xlib.

#### Default String

When a drawing or measuring function is called with an XOC that has missing charsets, some characters in the locale will not be drawable. The XNDefaultString argument returns a pointer to a string that represents the glyphs that are drawn with this XOC when the charsets of the available fonts do not include all glyphs required to draw a character. The string does not necessarily consist of valid characters in the current locale and is not necessarily drawn with the fonts loaded for the font set, but the client can draw or measure the default glyphs by including this string in a string being drawn or measured with the XOC.

If the XNDefaultString argument returned the empty string (""), no glyphs are drawn and the escapement is zero. The returned string is null-terminated. It is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XOC. Until freed, its contents will not be modified by Xlib.

#### Orientation

The XNOrientation argument specifies the current orientation of text when drawn. The value of this argument is one of the values returned by the function with the XNQueryOrientation argument specified in the XOrientation list. The value of the argument is of type XOrientation. When XNOrientation is queried, the value specifies the current orientation. When XNOrientation is set, a value is used to set the current orientation.

When `XOMOrientation_Context` is set, the text orientation of the text is determined according to an implementation-defined method (for example, ISO 6429 control sequences), and the initial text orientation for locale-dependent Xlib functions is assumed to be `XOMOrientation_LTR_TTB`.

The XNOrientation value does not change the prime drawing direction for Xlib drawing functions.

#### Resource Name and Class

The XNResourceName and XNResourceClass arguments are strings that specify the full name and class used by the client to obtain resources for the display of the output context. These values should be used as prefixes for name and class when looking up resources that may vary according to the output context. If these values are not set, the resources will not be fully specified.

It is not intended that values that can be set as XOM values be set as resources.

When querying for the XNResourceName or XNResourceClass XOC value, returns a null-terminated string. This string is owned by Xlib and should not be modified or freed by the client. The string will be freed by a call to with the associated XOC or when the associated value is changed via . Until freed, the string contents will not be modified by Xlib.

#### Font Info

The XNFontInfo argument specifies a list of one or more XFontStruct structures and font names for the fonts used for drawing by the given output context. The value of the argument is a pointer to a structure of type XOMFontInfo.

    typedef struct {
         int         num_font;
         XFontStruct **font_struct_list;
         char        **font_name_list;
    } XOMFontInfo;

A list of pointers to the XFontStruct structures is returned to font_struct_list. A list of pointers to null-terminated, fully-specified font name strings in the locale of the output context is returned to font_name_list. The font_name_list order corresponds to the font_struct_list order. The number of XFontStruct structures and font names is returned to num_font.

Because it is not guaranteed that a given character will be imaged using a single font glyph, there is no provision for mapping a character or default string to the font properties, font ID, or direction hint for the font for the character. The client may access the XFontStruct list to obtain these values for all the fonts currently in use.

Xlib does not guarantee that fonts are loaded from the server at the creation of an XOC. Xlib may choose to cache font data, loading it only as needed to draw text or compute text dimensions. Therefore, existence of the per_char metrics in the XFontStruct structures in the XFontStructSet is undefined. Also, note that all properties in the XFontStruct structures are in the STRING encoding.

The client must not free the XOMFontInfo struct itself; it will be freed when the XOC is closed.

#### OM Automatic

The XNOMAutomatic argument returns whether the associated output context was created by or not. Because the function not only destroys the output context but also closes the implicit output method associated with it, should be used with any output context created by . However, it is possible that a client does not know how the output context was created. Before a client destroys the output context, it can query whether XNOMAutomatic is set to determine whether or should be used to destroy the output context.

### Creating and Freeing a Font Set

Xlib international text drawing is done using a set of one or more fonts, as needed for the locale of the text. Fonts are loaded according to a list of base font names supplied by the client and the charsets required by the locale. The XFontSet is an opaque type representing the state of a particular output thread and is equivalent to the type XOC.

The function is a convenience function for creating an output context using only default values. The returned XFontSet has an implicitly created XOM. This XOM has an OM value XNOMAutomatic automatically set to True so that the output context self indicates whether it was created by or .

      XFontSet XCreateFontSet
      Display *display
      char *base_font_name_list
      char ***missing_charset_list_return
      int *missing_charset_count_return
      char **def_string_return

display

  Specifies the connection to the X server.

base_font_name_list

  Specifies the base font names.

missing_charset_list_return

  Returns the missing charsets.

missing_charset_count_return

  Returns the number of missing charsets.

def_string_return

  Returns the string drawn for missing charsets.

The function creates a font set for the specified display. The font set is bound to the current locale when is called. The font set may be used in subsequent calls to obtain font and character information and to image text in the locale of the font set.

The base_font_name_list argument is a list of base font names that Xlib uses to load the fonts needed for the locale. The base font names are a comma-separated list. The string is null-terminated and is assumed to be in the Host Portable Character Encoding; otherwise, the result is implementation-dependent. White space immediately on either side of a separating comma is ignored.

Use of XLFD font names permits Xlib to obtain the fonts needed for a variety of locales from a single locale-independent base font name. The single base font name should name a family of fonts whose members are encoded in the various charsets needed by the locales of interest.

An XLFD base font name can explicitly name a charset needed for the locale. This allows the user to specify an exact font for use with a charset required by a locale, fully controlling the font selection.

If a base font name is not an XLFD name, Xlib will attempt to obtain an XLFD name from the font properties for the font. If this action is successful in obtaining an XLFD name, the function will return this XLFD name instead of the client-supplied name.

Xlib uses the following algorithm to select the fonts that will be used to display text with the XFontSet.

For each font charset required by the locale, the base font name list is searched for the first appearance of one of the following cases that names a set of fonts that exist at the server:

- The first XLFD-conforming base font name that specifies the required charset or a superset of the required charset in its CharSetRegistry and CharSetEncoding fields. The implementation may use a base font name whose specified charset is a superset of the required charset, for example, an ISO8859-1 font for an ASCII charset.

- The first set of one or more XLFD-conforming base font names that specify one or more charsets that can be remapped to support the required charset. The Xlib implementation may recognize various mappings from a required charset to one or more other charsets and use the fonts for those charsets. For example, JIS Roman is ASCII with tilde and backslash replaced by yen and overbar; Xlib may load an ISO8859-1 font to support this character set if a JIS Roman font is not available.

- The first XLFD-conforming font name or the first non-XLFD font name for which an XLFD font name can be obtained, combined with the required charset (replacing the CharSetRegistry and CharSetEncoding fields in the XLFD font name). As in case 1, the implementation may use a charset that is a superset of the required charset.

- The first font name that can be mapped in some implementation-dependent manner to one or more fonts that support imaging text in the charset.

For example, assume that a locale required the charsets:

    ISO8859-1
    JISX0208.1983
    JISX0201.1976
    GB2312-1980.0

The user could supply a base_font_name_list that explicitly specifies the charsets, ensuring that specific fonts are used if they exist. For example:

    "-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-240-JISX0208.1983-0,\\
    -JIS-Fixed-Medium-R-Normal--26-180-100-100-C-120-JISX0201.1976-0,\\
    -GB-Fixed-Medium-R-Normal--26-180-100-100-C-240-GB2312-1980.0,\\
    -Adobe-Courier-Bold-R-Normal--25-180-75-75-M-150-ISO8859-1"

Alternatively, the user could supply a base_font_name_list that omits the charsets, letting Xlib select font charsets required for the locale. For example:

    "-JIS-Fixed-Medium-R-Normal--26-180-100-100-C-240,\\
    -JIS-Fixed-Medium-R-Normal--26-180-100-100-C-120,\\
    -GB-Fixed-Medium-R-Normal--26-180-100-100-C-240,\\
    -Adobe-Courier-Bold-R-Normal--25-180-100-100-M-150"

Alternatively, the user could simply supply a single base font name that allows Xlib to select from all available fonts that meet certain minimum XLFD property requirements. For example:

    "-*-*-*-R-Normal--*-180-100-100-*-*"

If is unable to create the font set, either because there is insufficient memory or because the current locale is not supported, returns NULL, missing_charset_list_return is set to NULL, and missing_charset_count_return is set to zero. If fonts exist for all of the charsets required by the current locale, returns a valid XFontSet, missing_charset_list_return is set to NULL, and missing_charset_count_return is set to zero.

If no font exists for one or more of the required charsets, sets missing_charset_list_return to a list of one or more null-terminated charset names for which no font exists and sets missing_charset_count_return to the number of missing fonts. The charsets are from the list of the required charsets for the encoding of the locale and do not include any charsets to which Xlib may be able to remap a required charset.

If no font exists for any of the required charsets or if the locale definition in Xlib requires that a font exist for a particular charset and a font is not found for that charset, returns NULL. Otherwise, returns a valid XFontSet to font_set.

When an Xmb/wc drawing or measuring function is called with an XFontSet that has missing charsets, some characters in the locale will not be drawable. If def_string_return is non-NULL, returns a pointer to a string that represents the glyphs that are drawn with this XFontSet when the charsets of the available fonts do not include all font glyphs required to draw a codepoint. The string does not necessarily consist of valid characters in the current locale and is not necessarily drawn with the fonts loaded for the font set, but the client can draw and measure the default glyphs by including this string in a string being drawn or measured with the XFontSet.

If the string returned to def_string_return is the empty string (""), no glyphs are drawn, and the escapement is zero. The returned string is null-terminated. It is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XFontSet. Until freed, its contents will not be modified by Xlib.

The client is responsible for constructing an error message from the missing charset and default string information and may choose to continue operation in the case that some fonts did not exist.

The returned XFontSet and missing charset list should be freed with and , respectively. The client-supplied base_font_name_list may be freed by the client after calling .

To obtain a list of XFontStruct structures and full font names given an XFontSet, use .

      int XFontsOfFontSet
      XFontSet font_set
      XFontStruct ***font_struct_list_return
      char ***font_name_list_return

font_set

  Specifies the font set.

font_struct_list_return

  Returns the list of font structs.

font_name_list_return

  Returns the list of font names.

The function returns a list of one or more XFontStructs and font names for the fonts used by the Xmb and Xwc layers for the given font set. A list of pointers to the XFontStruct structures is returned to font_struct_list_return. A list of pointers to null-terminated, fully specified font name strings in the locale of the font set is returned to font_name_list_return. The font_name_list order corresponds to the font_struct_list order. The number of XFontStruct structures and font names is returned as the value of the function.

Because it is not guaranteed that a given character will be imaged using a single font glyph, there is no provision for mapping a character or default string to the font properties, font ID, or direction hint for the font for the character. The client may access the XFontStruct list to obtain these values for all the fonts currently in use.

Xlib does not guarantee that fonts are loaded from the server at the creation of an XFontSet. Xlib may choose to cache font data, loading it only as needed to draw text or compute text dimensions. Therefore, existence of the per_char metrics in the XFontStruct structures in the XFontStructSet is undefined. Also, note that all properties in the XFontStruct structures are in the STRING encoding.

The XFontStruct and font name lists are owned by Xlib and should not be modified or freed by the client. They will be freed by a call to with the associated XFontSet. Until freed, their contents will not be modified by Xlib.

To obtain the base font name list and the selected font name list given an XFontSet, use .

      char *XBaseFontNameListOfFontSet
      XFontSet font_set

font_set

  Specifies the font set.

The function returns the original base font name list supplied by the client when the XFontSet was created. A null-terminated string containing a list of comma-separated font names is returned as the value of the function. White space may appear immediately on either side of separating commas.

If obtained an XLFD name from the font properties for the font specified by a non-XLFD base name, the function will return the XLFD name instead of the non-XLFD base name.

The base font name list is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XFontSet. Until freed, its contents will not be modified by Xlib.

To obtain the locale name given an XFontSet, use .

      char *XLocaleOfFontSet
      XFontSet font_set

font_set

  Specifies the font set.

The function returns the name of the locale bound to the specified XFontSet, as a null-terminated string.

The returned locale name string is owned by Xlib and should not be modified or freed by the client. It may be freed by a call to with the associated XFontSet. Until freed, it will not be modified by Xlib.

The function is a convenience function for freeing an output context. also frees its associated XOM if the output context was created by .

      void XFreeFontSet
      Display *display
      XFontSet font_set

display

  Specifies the connection to the X server.

font_set

  Specifies the font set.

The function frees the specified font set. The associated base font name list, font name list, XFontStruct list, and XFontSetExtents, if any, are freed.

### Obtaining Font Set Metrics

Metrics for the internationalized text drawing functions are defined in terms of a primary draw direction, which is the default direction in which the character origin advances for each succeeding character in the string. The Xlib interface is currently defined to support only a left-to-right primary draw direction. The drawing origin is the position passed to the drawing function when the text is drawn. The baseline is a line drawn through the drawing origin parallel to the primary draw direction. Character ink is the pixels painted in the foreground color and does not include interline or intercharacter spacing or image text background pixels.

The drawing functions are allowed to implement implicit text directionality control, reversing the order in which characters are rendered along the primary draw direction in response to locale-specific lexical analysis of the string.

Regardless of the character rendering order, the origins of all characters are on the primary draw direction side of the drawing origin. The screen location of a particular character image may be determined with or .

The drawing functions are allowed to implement context-dependent rendering, where the glyphs drawn for a string are not simply a concatenation of the glyphs that represent each individual character. A string of two characters drawn with may render differently than if the two characters were drawn with separate calls to . If the client appends or inserts a character in a previously drawn string, the client may need to redraw some adjacent characters to obtain proper rendering.

To find out about direction-dependent rendering, use .

      Bool XDirectionalDependentDrawing
      XFontSet font_set

font_set

  Specifies the font set.

The function returns True if the drawing functions implement implicit text directionality; otherwise, it returns False.

To find out about context-dependent rendering, use .

      Bool XContextualDrawing
      XFontSet font_set

font_set

  Specifies the font set.

The function returns True if text drawn with the font set might include context-dependent drawing; otherwise, it returns False.

To find out about context-dependent or direction-dependent rendering, use .

      Bool XContextDependentDrawing
      XFontSet font_set

font_set

  Specifies the font set.

The function returns True if the drawing functions implement implicit text directionality or if text drawn with the font_set might include context-dependent drawing; otherwise, it returns False.

The drawing functions do not interpret newline, tab, or other control characters. The behavior when nonprinting characters other than space are drawn is implementation-dependent. It is the client's responsibility to interpret control characters in a text stream.

The maximum character extents for the fonts that are used by the text drawing layers can be accessed by the XFontSetExtents structure:

    typedef struct {
         XRectangle max_ink_extent;     /* over all drawable characters */
         XRectangle max_logical_extent; /* over all drawable characters */
    } XFontSetExtents;

The XRectangle structures used to return font set metrics are the usual Xlib screen-oriented rectangles with x, y giving the upper left corner, and width and height always positive.

The max_ink_extent member gives the maximum extent, over all drawable characters, of the rectangles that bound the character glyph image drawn in the foreground color, relative to a constant origin. See and `XwcTextExtents` for detailed semantics.

The max_logical_extent member gives the maximum extent, over all drawable characters, of the rectangles that specify minimum spacing to other graphical features, relative to a constant origin. Other graphical features drawn by the client, for example, a border surrounding the text, should not intersect this rectangle. The max_logical_extent member should be used to compute minimum interline spacing and the minimum area that must be allowed in a text field to draw a given number of arbitrary characters.

Due to context-dependent rendering, appending a given character to a string may change the string's extent by an amount other than that character's individual extent.

The rectangles for a given character in a string can be obtained from or .

To obtain the maximum extents structure given an XFontSet, use .

      XFontSetExtents *XExtentsOfFontSet
      XFontSet font_set

font_set

  Specifies the font set.

The function returns an XFontSetExtents structure for the fonts used by the Xmb and Xwc layers for the given font set.

The XFontSetExtents structure is owned by Xlib and should not be modified or freed by the client. It will be freed by a call to with the associated XFontSet. Until freed, its contents will not be modified by Xlib.

To obtain the escapement in pixels of the specified text as a value, use or .

      int XmbTextEscapement
      XFontSet font_set
      char *string
      int num_bytes

      int XwcTextEscapement
      XFontSet font_set
      wchar_t *string
      int num_wchars

font_set

  Specifies the font set.

string

  Specifies the character string.

num_bytes

  Specifies the number of bytes in the string argument.

num_wchars

  Specifies the number of characters in the string argument.

The and functions return the escapement in pixels of the specified string as a value, using the fonts loaded for the specified font set. The escapement is the distance in pixels in the primary draw direction from the drawing origin to the origin of the next character to be drawn, assuming that the rendering of the next character is not dependent on the supplied string.

Regardless of the character rendering order, the escapement is always positive.

To obtain the overall_ink_return and overall_logical_return arguments, the overall bounding box of the string's image, and a logical bounding box, use or `XwcTextExtents`.

      int XmbTextExtents
      XFontSet font_set
      char *string
      int num_bytes
      XRectangle *overall_ink_return
      XRectangle *overall_logical_return

      int XwcTextExtents
      XFontSet font_set
      wchar_t *string
      int num_wchars
      XRectangle *overall_ink_return
      XRectangle *overall_logical_return

font_set

  Specifies the font set.

string

  Specifies the character string.

num_bytes

  Specifies the number of bytes in the string argument.

num_wchars

  Specifies the number of characters in the string argument.

overall_ink_return

  Returns the overall ink dimensions.

overall_logical_return

  Returns the overall logical dimensions.

The and `XwcTextExtents` functions set the components of the specified overall_ink_return and overall_logical_return arguments to the overall bounding box of the string's image and a logical bounding box for spacing purposes, respectively. They return the value returned by or . These metrics are relative to the drawing origin of the string, using the fonts loaded for the specified font set.

If the overall_ink_return argument is non-NULL, it is set to the bounding box of the string's character ink. The overall_ink_return for a nondescending, horizontally drawn Latin character is conventionally entirely above the baseline; that is, overall_ink_return.height <= -overall_ink_return.y. The overall_ink_return for a nonkerned character is entirely at, and to the right of, the origin; that is, overall_ink_return.x >= 0. A character consisting of a single pixel at the origin would set overall_ink_return fields y = 0, x = 0, width = 1, and height = 1.

If the overall_logical_return argument is non-NULL, it is set to the bounding box that provides minimum spacing to other graphical features for the string. Other graphical features, for example, a border surrounding the text, should not intersect this rectangle.

When the XFontSet has missing charsets, metrics for each unavailable character are taken from the default string returned by so that the metrics represent the text as it will actually be drawn. The behavior for an invalid codepoint is undefined.

To determine the effective drawing origin for a character in a drawn string, the client should call on the entire string, then on the character, and subtract the x values of the returned rectangles for the character. This is useful to redraw portions of a line of text or to justify words, but for context-dependent rendering, the client should not assume that it can redraw the character by itself and get the same rendering.

To obtain per-character information for a text string, use or .

      Status XmbTextPerCharExtents
      XFontSet font_set
      char *string
      int num_bytes
      XRectangle *ink_array_return
      XRectangle *logical_array_return
      int array_size
      int *num_chars_return
      XRectangle *overall_ink_return
      XRectangle *overall_logical_return

      Status XwcTextPerCharExtents
      XFontSet font_set
      wchar_t *string
      int num_wchars
      XRectangle *ink_array_return
      XRectangle *logical_array_return
      int array_size
      int *num_chars_return
      XRectangle *overall_ink_return
      XRectangle *overall_logical_return

font_set

  Specifies the font set.

string

  Specifies the character string.

num_bytes

  Specifies the number of bytes in the string argument.

num_wchars

  Specifies the number of characters in the string argument.

ink_array_return

  Returns the ink dimensions for each character.

logical_array_return

  Returns the logical dimensions for each character.

array_size

  Specifies the size of ink_array_return and logical_array_return. The caller must pass in arrays of this size.

num_chars_return

  Returns the number of characters in the string argument.

overall_ink_return

  Returns the overall ink dimensions.

overall_logical_return

  Returns the overall logical dimensions.

The and functions return the text dimensions of each character of the specified text, using the fonts loaded for the specified font set. Each successive element of ink_array_return and logical_array_return is set to the successive character's drawn metrics, relative to the drawing origin of the string and one rectangle for each character in the supplied text string. The number of elements of ink_array_return and logical_array_return that have been set is returned to num_chars_return.

Each element of ink_array_return is set to the bounding box of the corresponding character's drawn foreground color. Each element of logical_array_return is set to the bounding box that provides minimum spacing to other graphical features for the corresponding character. Other graphical features should not intersect any of the logical_array_return rectangles.

Note that an XRectangle represents the effective drawing dimensions of the character, regardless of the number of font glyphs that are used to draw the character or the direction in which the character is drawn. If multiple characters map to a single character glyph, the dimensions of all the XRectangles of those characters are the same.

When the XFontSet has missing charsets, metrics for each unavailable character are taken from the default string returned by so that the metrics represent the text as it will actually be drawn. The behavior for an invalid codepoint is undefined.

If the array_size is too small for the number of characters in the supplied text, the functions return zero and num_chars_return is set to the number of rectangles required. Otherwise, the functions return a nonzero value.

If the overall_ink_return or overall_logical_return argument is non-NULL, and return the maximum extent of the string's metrics to overall_ink_return or overall_logical_return, as returned by or `XwcTextExtents`.

### Drawing Text Using Font Sets

The functions defined in this section draw text at a specified location in a drawable. They are similar to the functions , , and except that they work with font sets instead of single fonts and interpret the text based on the locale of the font set instead of treating the bytes of the string as direct font indexes. See section 8.6 for details of the use of Graphics Contexts (GCs) and possible protocol errors. If a BadFont error is generated, characters prior to the offending character may have been drawn.

The text is drawn using the fonts loaded for the specified font set; the font in the GC is ignored and may be modified by the functions. No validation that all fonts conform to some width rule is performed.

The text functions and use the following structures:

    typedef struct {
         char     *chars;    /* pointer to string */
         int      nchars;    /* number of bytes */
         int      delta;     /* pixel delta between strings */
         XFontSet font_set;  /* fonts, None means don't change */
    } XmbTextItem;

    typedef struct {
         wchar_t *chars;     /* pointer to wide char string */
         int nchars;     /* number of wide characters */
         int delta;     /* pixel delta between strings */
         XFontSet font_set;     /* fonts, None means don't change */
    } XwcTextItem;

To draw text using multiple font sets in a given drawable, use or .

      void XmbDrawText
      Display *display
      Drawable d
      GC gc
      intx, y
      XmbTextItem *items
      int nitems

      void XwcDrawText
      Display *display
      Drawable d
      GC gc
      intx, y
      XwcTextItem *items
      int nitems

display

  Specifies the connection to the X server.

d

  Specifies the drawable.

gc

  Specifies the GC.

x

y

  Specify the x and y coordinates of the position in the new parent window.

items

  Specifies an array of text items.

nitems

  Specifies the number of text items in the array.

The and functions allow complex spacing and font set shifts between text strings. Each text item is processed in turn, with the origin of a text element advanced in the primary draw direction by the escapement of the previous text item. A text item delta specifies an additional escapement of the text item drawing origin in the primary draw direction. A font_set member other than None in an item causes the font set to be used for this and subsequent text items in the text_items list. Leading text items with a font_set member set to None will not be drawn.

and do not perform any context-dependent rendering between text segments. Clients may compute the drawing metrics by passing each text segment to and `XwcTextExtents` or and . When the XFontSet has missing charsets, each unavailable character is drawn with the default string returned by . The behavior for an invalid codepoint is undefined.

To draw text using a single font set in a given drawable, use or .

      void XmbDrawString
      Display *display
      Drawable d
      XFontSet font_set
      GC gc
      intx, y
      char *string
      int num_bytes

      void XwcDrawString
      Display *display
      Drawable d
      XFontSet font_set
      GC gc
      intx, y
      wchar_t *string
      int num_wchars

display

  Specifies the connection to the X server.

d

  Specifies the drawable.

font_set

  Specifies the font set.

gc

  Specifies the GC.

x

y

  Specify the x and y coordinates of the position in the new parent window.

string

  Specifies the character string.

num_bytes

  Specifies the number of bytes in the string argument.

num_wchars

  Specifies the number of characters in the string argument.

The and functions draw the specified text with the foreground pixel. When the XFontSet has missing charsets, each unavailable character is drawn with the default string returned by . The behavior for an invalid codepoint is undefined.

To draw image text using a single font set in a given drawable, use or .

      void XmbDrawImageString
      Display *display
      Drawable d
      XFontSet font_set
      GC gc
      intx, y
      char *string
      int num_bytes

      void XwcDrawImageString
      Display *display
      Drawable d
      XFontSet font_set
      GC gc
      intx, y
      wchar_t *string
      int num_wchars

display

  Specifies the connection to the X server.

d

  Specifies the drawable.

font_set

  Specifies the font set.

gc

  Specifies the GC.

x

y

  Specify the x and y coordinates of the position in the new parent window.

string

  Specifies the character string.

num_bytes

  Specifies the number of bytes in the string argument.

num_wchars

  Specifies the number of characters in the string argument.

The and functions fill a destination rectangle with the background pixel defined in the GC and then paint the text with the foreground pixel. The filled rectangle is the rectangle returned to overall_logical_return by or `XwcTextExtents` for the same text and XFontSet.

When the XFontSet has missing charsets, each unavailable character is drawn with the default string returned by . The behavior for an invalid codepoint is undefined.

## Input Methods

This section provides discussions of the following X Input Method (XIM) topics:

- Input method overview

- Input method management

- Input method functions

- Input method values

- Input context functions

- Input context values

- Input method callback semantics

- Event filtering

- Getting keyboard input

- Input method conventions

### Input Method Overview

This section provides definitions for terms and concepts used for internationalized text input and a brief overview of the intended use of the mechanisms provided by Xlib.

A large number of languages in the world use alphabets consisting of a small set of symbols (letters) to form words. To enter text into a computer in an alphabetic language, a user usually has a keyboard on which there exist key symbols corresponding to the alphabet. Sometimes, a few characters of an alphabetic language are missing on the keyboard. Many computer users who speak a Latin-alphabet-based language only have an English-based keyboard. They need to hit a combination of keystrokes to enter a character that does not exist directly on the keyboard. A number of algorithms have been developed for entering such characters. These are known as European input methods, compose input methods, or dead-key input methods.

Japanese is an example of a language with a phonetic symbol set, where each symbol represents a specific sound. There are two phonetic symbol sets in Japanese: Katakana and Hiragana. In general, Katakana is used for words that are of foreign origin, and Hiragana is used for writing native Japanese words. Collectively, the two systems are called Kana. Each set consists of 48 characters.

Korean also has a phonetic symbol set, called Hangul. Each of the 24 basic phonetic symbols (14 consonants and 10 vowels) represents a specific sound. A syllable is composed of two or three parts: the initial consonants, the vowels, and the optional last consonants. With Hangul, syllables can be treated as the basic units on which text processing is done. For example, a delete operation may work on a phonetic symbol or a syllable. Korean code sets include several thousands of these syllables. A user types the phonetic symbols that make up the syllables of the words to be entered. The display may change as each phonetic symbol is entered. For example, when the second phonetic symbol of a syllable is entered, the first phonetic symbol may change its shape and size. Likewise, when the third phonetic symbol is entered, the first two phonetic symbols may change their shape and size.

Not all languages rely solely on alphabetic or phonetic systems. Some languages, including Japanese and Korean, employ an ideographic writing system. In an ideographic system, rather than taking a small set of symbols and combining them in different ways to create words, each word consists of one unique symbol (or, occasionally, several symbols). The number of symbols can be very large: approximately 50,000 have been identified in Hanzi, the Chinese ideographic system.

Two major aspects of ideographic systems impact their use with computers. First, the standard computer character sets in Japan, China, and Korea include roughly 8,000 characters, while sets in Taiwan have between 15,000 and 30,000 characters. This makes it necessary to use more than one byte to represent a character. Second, it obviously is impractical to have a keyboard that includes all of a given language's ideographic symbols. Therefore, a mechanism is required for entering characters so that a keyboard with a reasonable number of keys can be used. Those input methods are usually based on phonetics, but there also exist methods based on the graphical properties of characters.

In Japan, both Kana and the ideographic system Kanji are used. In Korea, Hangul and sometimes the ideographic system Hanja are used. Now consider entering ideographs in Japan, Korea, China, and Taiwan.

In Japan, either Kana or English characters are typed and then a region is selected (sometimes automatically) for conversion to Kanji. Several Kanji characters may have the same phonetic representation. If that is the case with the string entered, a menu of characters is presented and the user must choose the appropriate one. If no choice is necessary or a preference has been established, the input method does the substitution directly. When Latin characters are converted to Kana or Kanji, it is called a romaji conversion.

In Korea, it is usually acceptable to keep Korean text in Hangul form, but some people may choose to write Hanja-originated words in Hanja rather than in Hangul. To change Hangul to Hanja, the user selects a region for conversion and then follows the same basic method as that described for Japanese.

Probably because there are well-accepted phonetic writing systems for Japanese and Korean, computer input methods in these countries for entering ideographs are fairly standard. Keyboard keys have both English characters and phonetic symbols engraved on them, and the user can switch between the two sets.

The situation is different for Chinese. While there is a phonetic system called Pinyin promoted by authorities, there is no consensus for entering Chinese text. Some vendors use a phonetic decomposition (Pinyin or another), others use ideographic decomposition of Chinese words, with various implementations and keyboard layouts. There are about 16 known methods, none of which is a clear standard.

Also, there are actually two ideographic sets used: Traditional Chinese (the original written Chinese) and Simplified Chinese. Several years ago, the People's Republic of China launched a campaign to simplify some ideographic characters and eliminate redundancies altogether. Under the plan, characters would be streamlined every five years. Characters have been revised several times now, resulting in the smaller, simpler set that makes up Simplified Chinese.

#### Input Method Architecture

As shown in the previous section, there are many different input methods in use today, each varying with language, culture, and history. A common feature of many input methods is that the user may type multiple keystrokes to compose a single character (or set of characters). The process of composing characters from keystrokes is called preediting. It may require complex algorithms and large dictionaries involving substantial computer resources.

Input methods may require one or more areas in which to show the feedback of the actual keystrokes, to propose disambiguation to the user, to list dictionaries, and so on. The input method areas of concern are as follows:

- The status area is a logical extension of the LEDs that exist on the physical keyboard. It is a window that is intended to present the internal state of the input method that is critical to the user. The status area may consist of text data and bitmaps or some combination.

- The preedit area displays the intermediate text for those languages that are composing prior to the client handling the data.

- The auxiliary area is used for pop-up menus and customizing dialogs that may be required for an input method. There may be multiple auxiliary areas for an input method. Auxiliary areas are managed by the input method independent of the client. Auxiliary areas are assumed to be separate dialogs, which are maintained by the input method.

There are various user interaction styles used for preediting. The ones supported by Xlib are as follows:

- For on-the-spot input methods, preediting data will be displayed directly in the application window. Application data is moved to allow preedit data to appear at the point of insertion.

- Over-the-spot preediting means that the data is displayed in a preedit window that is placed over the point of insertion.

- Off-the-spot preediting means that the preedit window is inside the application window but not at the point of insertion. Often, this type of window is placed at the bottom of the application window.

- Root-window preediting refers to input methods that use a preedit window that is the child of `RootWindow`.

It would require a lot of computing resources if portable applications had to include input methods for all the languages in the world. To avoid this, a goal of the Xlib design is to allow an application to communicate with an input method placed in a separate process. Such a process is called an input server. The server to which the application should connect is dependent on the environment when the application is started up, that is, the user language and the actual encoding to be used for it. The input method connection is said to be locale-dependent. It is also user-dependent. For a given language, the user can choose, to some extent, the user interface style of input method (if choice is possible among several).

Using an input server implies communication overhead, but applications can be migrated without relinking. Input methods can be implemented either as a stub communicating to an input server or as a local library.

An input method may be based on a front-end or a back-end architecture. In a front-end architecture, there are two separate connections to the X server: keystrokes go directly from the X server to the input method on one connection and other events to the regular client connection. The input method is then acting as a filter and sends composed strings to the client. A front-end architecture requires synchronization between the two connections to avoid lost key events or locking issues.

In a back-end architecture, a single X server connection is used. A dispatching mechanism must decide on this channel to delegate appropriate keystrokes to the input method. For instance, it may retain a Help keystroke for its own purpose. In the case where the input method is a separate process (that is, a server), there must be a special communication protocol between the back-end client and the input server.

A front-end architecture introduces synchronization issues and a filtering mechanism for noncharacter keystrokes (Function keys, Help, and so on). A back-end architecture sometimes implies more communication overhead and more process switching. If all three processes (X server, input server, client) are running on a single workstation, there are two process switches for each keystroke in a back-end architecture, but there is only one in a front-end architecture.

The abstraction used by a client to communicate with an input method is an opaque data structure represented by the XIM data type. This data structure is returned by the function, which opens an input method on a given display. Subsequent operations on this data structure encapsulate all communication between client and input method. There is no need for an X client to use any networking library or natural language package to use an input method.

A single input server may be used for one or more languages, supporting one or more encoding schemes. But the strings returned from an input method will always be encoded in the (single) locale associated with the XIM object.

#### Input Contexts

Xlib provides the ability to manage a multi-threaded state for text input. A client may be using multiple windows, each window with multiple text entry areas, and the user possibly switching among them at any time. The abstraction for representing the state of a particular input thread is called an input context. The Xlib representation of an input context is an XIC.

An input context is the abstraction retaining the state, properties, and semantics of communication between a client and an input method. An input context is a combination of an input method, a locale specifying the encoding of the character strings to be returned, a client window, internal state information, and various layout or appearance characteristics. The input context concept somewhat matches for input the graphics context abstraction defined for graphics output.

One input context belongs to exactly one input method. Different input contexts may be associated with the same input method, possibly with the same client window. An XIC is created with the function, providing an XIM argument and affiliating the input context to the input method for its lifetime. When an input method is closed with , all of its affiliated input contexts should not be used any more (and should preferably be destroyed before closing the input method).

Considering the example of a client window with multiple text entry areas, the application programmer could, for example, choose to implement as follows:

- As many input contexts are created as text entry areas, and the client will get the input accumulated on each context each time it looks up in that context.

- A single context is created for a top-level window in the application. If such a window contains several text entry areas, each time the user moves to another text entry area, the client has to indicate changes in the context.

A range of choices can be made by application designers to use either a single or multiple input contexts, according to the needs of their application.

#### Getting Keyboard Input

To obtain characters from an input method, a client must call the function or with an input context created from that input method. Both a locale and display are bound to an input method when it is opened, and an input context inherits this locale and display. Any strings returned by or will be encoded in that locale.

#### Focus Management

For each text entry area in which the or functions are used, there will be an associated input context.

When the application focus moves to a text entry area, the application must set the input context focus to the input context associated with that area. The input context focus is set by calling with the appropriate input context.

Also, when the application focus moves out of a text entry area, the application should unset the focus for the associated input context by calling . As an optimization, if is called successively on two different input contexts, setting the focus on the second will automatically unset the focus on the first.

To set and unset the input context focus correctly, it is necessary to track application-level focus changes. Such focus changes do not necessarily correspond to X server focus changes.

If a single input context is being used to do input for multiple text entry areas, it will also be necessary to set the focus window of the input context whenever the focus window changes (see section 13.5.6.3).

#### Geometry Management

In most input method architectures (on-the-spot being the notable exception), the input method will perform the display of its own data. To provide better visual locality, it is often desirable to have the input method areas embedded within a client. To do this, the client may need to allocate space for an input method. Xlib provides support that allows the size and position of input method areas to be provided by a client. The input method areas that are supported for geometry management are the status area and the preedit area.

The fundamental concept on which geometry management for input method windows is based is the proper division of responsibilities between the client (or toolkit) and the input method. The division of responsibilities is as follows:

- The client is responsible for the geometry of the input method window.

- The input method is responsible for the contents of the input method window.

An input method is able to suggest a size to the client, but it cannot suggest a placement. Also the input method can only suggest a size. It does not determine the size, and it must accept the size it is given.

Before a client provides geometry management for an input method, it must determine if geometry management is needed. The input method indicates the need for geometry management by setting XIMPreeditArea or XIMStatusArea in its XIMStyles value returned by . When a client has decided that it will provide geometry management for an input method, it indicates that decision by setting the XNInputStyle value in the XIC.

After a client has established with the input method that it will do geometry management, the client must negotiate the geometry with the input method. The geometry is negotiated by the following steps:

- The client suggests an area to the input method by setting the XNAreaNeeded value for that area. If the client has no constraints for the input method, it either will not suggest an area or will set the width and height to zero. Otherwise, it will set one of the values.

- The client will get the XIC value XNAreaNeeded. The input method will return its suggested size in this value. The input method should pay attention to any constraints suggested by the client.

- The client sets the XIC value XNArea to inform the input method of the geometry of its window. The client should try to honor the geometry requested by the input method. The input method must accept this geometry.

Clients doing geometry management must be aware that setting other XIC values may affect the geometry desired by an input method. For example, XNFontSet and XNLineSpace may change the geometry desired by the input method.

The table of XIC values (see section 13.5.6) indicates the values that can cause the desired geometry to change when they are set. It is the responsibility of the client to renegotiate the geometry of the input method window when it is needed.

In addition, a geometry management callback is provided by which an input method can initiate a geometry change.

#### Event Filtering

A filtering mechanism is provided to allow input methods to capture X events transparently to clients. It is expected that toolkits (or clients) using or will call this filter at some point in the event processing mechanism to make sure that events needed by an input method can be filtered by that input method.

If there were no filter, a client could receive and discard events that are necessary for the proper functioning of an input method. The following provides a few examples of such events:

- Expose events on preedit window in local mode.

- Events may be used by an input method to communicate with an input server. Such input server protocol-related events have to be intercepted if one does not want to disturb client code.

- Key events can be sent to a filter before they are bound to translations such as those the X Toolkit Intrinsics library provides.

Clients are expected to get the XIC value XNFilterEvents and augment the event mask for the client window with that event mask. This mask may be zero.

#### Callbacks

When an on-the-spot input method is implemented, only the client can insert or delete preedit data in place and possibly scroll existing text. This means that the echo of the keystrokes has to be achieved by the client itself, tightly coupled with the input method logic.

When the user enters a keystroke, the client calls or . At this point, in the on-the-spot case, the echo of the keystroke in the preedit has not yet been done. Before returning to the client logic that handles the input characters, the look-up function must call the echoing logic to insert the new keystroke. If the keystrokes entered so far make up a character, the keystrokes entered need to be deleted, and the composed character will be returned. Hence, what happens is that, while being called by client code, the input method logic has to call back to the client before it returns. The client code, that is, a callback procedure, is called from the input method logic.

There are a number of cases where the input method logic has to call back the client. Each of those cases is associated with a well-defined callback action. It is possible for the client to specify, for each input context, what callback is to be called for each action.

There are also callbacks provided for feedback of status information and a callback to initiate a geometry request for an input method.

#### Visible Position Feedback Masks

In the on-the-spot input style, there is a problem when attempting to draw preedit strings that are longer than the available space. Once the display area is exceeded, it is not clear how best to display the preedit string. The visible position feedback masks of XIMText help resolve this problem by allowing the input method to specify hints that indicate the essential portions of the preedit string. For example, such hints can help developers implement scrolling of a long preedit string within a short preedit display area.

#### Preedit String Management

As highlighted before, the input method architecture provides preediting, which supports a type of preprocessor input composition. In this case, composition consists of interpreting a sequence of key events and returning a committed string via or . This provides the basics for input methods.

In addition to preediting based on key events, a general framework is provided to give a client that desires it more advanced preediting based on the text within the client. This framework is called string conversion and is provided using XIC values. The fundamental concept of string conversion is to allow the input method to manipulate the client's text independent of any user preediting operation.

The need for string conversion is based on language needs and input method capabilities. The following are some examples of string conversion:

- Transliteration conversion provides language-specific conversions within the input method. In the case of Korean input, users wish to convert a Hangul string into a Hanja string while in preediting, after preediting, or in other situations (for example, on a selected string). The conversion is triggered when the user presses a Hangul-to-Hanja key sequence (which may be input method specific). Sometimes the user may want to invoke the conversion after finishing preediting or on a user-selected string. Thus, the string to be converted is in an application buffer, not in the preedit area of the input method. The string conversion services allow the client to request this transliteration conversion from the input method. There are many other transliteration conversions defined for various languages, for example, Kana-to-Kanji conversion in Japanese. The key to remember is that transliteration conversions are triggered at the request of the user and returned to the client immediately without affecting the preedit area of the input method.

- Reconversion of a previously committed string or a selected string is supported by many input methods as a convenience to the user. For example, a user tends to mistype the commit key while preediting. In that case, some input methods provide a special key sequence to request a ``reconvert'' operation on the committed string, similiar to the undo facility provided by most text editors. Another example is where the user is proofreading a document that has some misconversions from preediting and wants to correct the misconverted text. Such reconversion is again triggered by the user invoking some special action, but reconversions should not affect the state of the preedit area.

- Context-sensitive conversion is required for some languages and input methods that need to retrieve text that surrounds the current spot location (cursor position) of the client's buffer. Such text is needed when the preediting operation depends on some surrounding characters (usually preceding the spot location). For example, in Thai language input, certain character sequences may be invalid and the input method may want to check whether characters constitute a valid word. Input methods that do such context-dependent checking need to retrieve the characters surrounding the current cursor position to obtain complete words. Unlike other conversions, this conversion is not explicitly requested by the user. Input methods that provide such context-sensitive conversion continuously need to request context from the client, and any change in the context of the spot location may affect such conversions. The client's context would be needed if the user moves the cursor and starts editing again. For this reason, an input method supporting this type of conversion should take notice of when the client calls or , which is usually an indication of a context change.

Context-sensitive conversions just need a copy of the client's text, while other conversions replace the client's text with new text to achieve the reconversion or transliteration. Yet in all cases the result of a conversion, either immediately or via preediting, is returned by the and functions.

String conversion support is dependent on the availability of the XNStringConversion or XNStringConversionCallback XIC values. Because the input method may not support string conversions, clients have to query the availability of string conversion operations by checking the supported XIC values list by calling with the XNQueryICValuesList IM value.

The difference between these two values is whether the conversion is invoked by the client or the input method. The XNStringConversion XIC value is used by clients to request a string conversion from the input method. The client is responsible for determining which events are used to trigger the string conversion and whether the string to be converted should be copied or deleted. The type of conversion is determined by the input method; the client can only pass the string to be converted. The client is guaranteed that no XNStringConversionCallback will be issued when this value is set; thus, the client need only set one of these values.

The XNStringConversionCallback XIC value is used by the client to notify the input method that it will accept requests from the input method for string conversion. If this value is set, it is the input method's responsibility to determine which events are used to trigger the string conversion. When such events occur, the input method issues a call to the client-supplied procedure to retrieve the string to be converted. The client's callback procedure is notified whether to copy or delete the string and is provided with hints as to the amount of text needed. The XIMStringConversionCallbackStruct specifies which text should be passed back to the input method.

Finally, the input method may call the client's XNStringConversionCallback procedure multiple times if the string returned from the callback is not sufficient to perform a successful conversion. The arguments to the client's procedure allow the input method to define a position (in character units) relative to the client's cursor position and the size of the text needed. By varying the position and size of the desired text in subsequent callbacks, the input method can retrieve additional text.

### Input Method Management

The interface to input methods might appear to be simply creating an input method () and freeing an input method (). However, input methods may require complex communication with input method servers (IM servers), for example:

- If the X server, IM server, and X clients are started asynchronously, some clients may attempt to connect to the IM server before it is fully operational, and fail. Therefore, some mechanism is needed to allow clients to detect when an IM server has started.

It is up to clients to decide what should be done when an IM server is not available (for example, wait, or use some other IM server).

- Some input methods may allow the underlying IM server to be switched. Such customization may be desired without restarting the entire client.

To support management of input methods in these cases, the following functions are provided:

| This function allows clients to register a callback procedure to be called when Xlib detects that an IM server is up and available.
| A client calls this function as a result of the callback procedure being called.

,

These functions use the XIM and XIC values, XNDestroyCallback, to allow a client to register a callback procedure to be called when Xlib detects that an IM server that was associated with an opened input method is no longer available. In addition, this function can be used to switch IM servers for those input methods that support such functionality. The IM value for switching IM servers is implementation-dependent; see the description below about switching IM servers.

| This function removes a callback procedure registered by the client.

Input methods that support switching of IM servers may exhibit some side-effects:

- The input method will ensure that any new IM server supports any of the input styles being used by input contexts already associated with the input method. However, the list of supported input styles may be different.

- Geometry management requests on previously created input contexts may be initiated by the new IM server.

#### Hot Keys

Some clients need to guarantee which keys can be used to escape from the input method, regardless of the input method state; for example, the client-specific Help key or the keys to move the input focus. The HotKey mechanism allows clients to specify a set of keys for this purpose. However, the input method might not allow clients to specify hot keys. Therefore, clients have to query support of hot keys by checking the supported XIC values list by calling with the XNQueryICValuesList IM value. When the hot keys specified conflict with the key bindings of the input method, hot keys take precedence over the key bindings of the input method.

#### Preedit State Operation

An input method may have several internal states, depending on its implementation and the locale. However, one state that is independent of locale and implementation is whether the input method is currently performing a preediting operation. Xlib provides the ability for an application to manage the preedit state programmatically. Two methods are provided for retrieving the preedit state of an input context. One method is to query the state by calling with the XNPreeditState XIC value. Another method is to receive notification whenever the preedit state is changed. To receive such notification, an application needs to register a callback by calling with the XNPreeditStateNotifyCallback XIC value. In order to change the preedit state programmatically, an application needs to call with XNPreeditState.

Availability of the preedit state is input method dependent. The input method may not provide the ability to set the state or to retrieve the state programmatically. Therefore, clients have to query availability of preedit state operations by checking the supported XIC values list by calling with the XNQueryICValuesList IM value.

### Input Method Functions

To open a connection, use .

      XIM XOpenIM
      Display *display
      XrmDatabase db
      char *res_name
      char *res_class

display

  Specifies the connection to the X server.

db

  Specifies a pointer to the resource database.

res_name

  Specifies the full resource name of the application.

res_class

  Specifies the full class name of the application.

The function opens an input method, matching the current locale and modifiers specification. Current locale and modifiers are bound to the input method at opening time. The locale associated with an input method cannot be changed dynamically. This implies that the strings returned by or , for any input context affiliated with a given input method, will be encoded in the locale current at the time the input method is opened.

The specific input method to which this call will be routed is identified on the basis of the current locale. will identify a default input method corresponding to the current locale. That default can be modified using for the input method modifier.

The db argument is the resource database to be used by the input method for looking up resources that are private to the input method. It is not intended that this database be used to look up values that can be set as IC values in an input context. If db is NULL, no database is passed to the input method.

The res_name and res_class arguments specify the resource name and class of the application. They are intended to be used as prefixes by the input method when looking up resources that are common to all input contexts that may be created for this input method. The characters used for resource names and classes must be in the X Portable Character Set. The resources looked up are not fully specified if res_name or res_class is NULL.

The res_name and res_class arguments are not assumed to exist beyond the call to . The specified resource database is assumed to exist for the lifetime of the input method.

returns NULL if no input method could be opened.

To close a connection, use .

      Status XCloseIM
      XIM im

im

  Specifies the input method.

The function closes the specified input method.

To set input method attributes, use .

      char *XSetIMValues
      XIM im

im

  Specifies the input method.

...

  Specifies the variable-length argument list to set XIM values.

The function presents a variable argument list programming interface for setting attributes of the specified input method. It returns NULL if it succeeds; otherwise, it returns the name of the first argument that could not be set. Xlib does not attempt to set arguments from the supplied list that follow the failed argument; all arguments in the list preceding the failed argument have been set correctly.

To query an input method, use .

      char *XGetIMValues
      XIM im

im

  Specifies the input method.

...

  Specifies the variable length argument list to get XIM values.

The function presents a variable argument list programming interface for querying properties or features of the specified input method. This function returns NULL if it succeeds; otherwise, it returns the name of the first argument that could not be obtained.

Each XIM value argument (following a name) must point to a location where the XIM value is to be stored. That is, if the XIM value is of type T, the argument must be of type T*. If T itself is a pointer type, then allocates memory to store the actual data, and the client is responsible for freeing this data by calling with the returned pointer.

To obtain the display associated with an input method, use .

      Display *XDisplayOfIM
      XIM im

im

  Specifies the input method.

The function returns the display associated with the specified input method.

To get the locale associated with an input method, use .

      char *XLocaleOfIM
      XIM im

im

  Specifies the input method.

The function returns the locale associated with the specified input method.

To register an input method instantiate callback, use .

      Bool XRegisterIMInstantiateCallback
      Display *display
      XrmDatabase db
      char *res_name
      char *res_class
      XIMProc callback
      XPointer *client_data

display

  Specifies the connection to the X server.

db

  Specifies a pointer to the resource database.

res_name

  Specifies the full resource name of the application.

res_class

  Specifies the full class name of the application.

callback

  Specifies a pointer to the input method instantiate callback.

client_data

  Specifies the additional client data.

The function registers a callback to be invoked whenever a new input method becomes available for the specified display that matches the current locale and modifiers.

The function returns True if it succeeds; otherwise, it returns False.

The generic prototype is as follows:

      void IMInstantiateCallback
      Display *display
      XPointer client_data
      XPointer call_data

display

  Specifies the connection to the X server.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

To unregister an input method instantiation callback, use .

      Bool XUnregisterIMInstantiateCallback
      Display *display
      XrmDatabase db
      char *res_name
      char *res_class
      XIMProc callback
      XPointer *client_data

display

  Specifies the connection to the X server.

db

  Specifies a pointer to the resource database.

res_name

  Specifies the full resource name of the application.

res_class

  Specifies the full class name of the application.

callback

  Specifies a pointer to the input method instantiate callback.

client_data

  Specifies the additional client data.

The function removes an input method instantiation callback previously registered. The function returns True if it succeeds; otherwise, it returns False.

### Input Method Values

The following table describes how XIM values are interpreted by an input method. The first column lists the XIM values. The second column indicates how each of the XIM values are treated by that input style.

The following keys apply to this table.

Key | Explanation
--- | ---
D | This value may be set using . If it is not set, a default is provided.
S | This value may be set using .
G | This value may be read using .

XIM Value | Key
--- | ---
XNQueryInputStyle | G
XNResourceName | D-S-G
XNResourceClass | D-S-G
XNDestroyCallback | D-S-G
XNQueryIMValuesList | G
XNQueryICValuesList | G
XNVisiblePosition | G
XNR6PreeditCallback | D-S-G

XNR6PreeditCallback is obsolete and its use is not recommended (see section 13.5.4.6).

#### Query Input Style

A client should always query the input method to determine which input styles are supported. The client should then find an input style it is capable of supporting.

If the client cannot find an input style that it can support, it should negotiate with the user the continuation of the program (exit, choose another input method, and so on).

The argument value must be a pointer to a location where the returned value will be stored. The returned value is a pointer to a structure of type XIMStyles. Clients are responsible for freeing the XIMStyles structure. To do so, use .

The XIMStyles structure is defined as follows:

    typedef unsigned long XIMStyle;

    #define     XIMPreeditArea             0x0001L
    #define     XIMPreeditCallbacks        0x0002L
    #define     XIMPreeditPosition         0x0004L
    #define     XIMPreeditNothing          0x0008L
    #define     XIMPreeditNone             0x0010L

    #define     XIMStatusArea              0x0100L
    #define     XIMStatusCallbacks         0x0200L
    #define     XIMStatusNothing           0x0400L
    #define     XIMStatusNone              0x0800L

    typedef struct {
          unsigned short count_styles;
          XIMStyle * supported_styles;
    } XIMStyles;

An XIMStyles structure contains the number of input styles supported in its count_styles field. This is also the size of the supported_styles array.

The supported styles is a list of bitmask combinations, which indicate the combination of styles for each of the areas supported. These areas are described later. Each element in the list should select one of the bitmask values for each area. The list describes the complete set of combinations supported. Only these combinations are supported by the input method.

The preedit category defines what type of support is provided by the input method for preedit information.

XIMPreeditArea | If chosen, the input method would require the client to provide some area values for it to do its preediting. Refer to XIC values XNArea and XNAreaNeeded.
XIMPreeditPosition | If chosen, the input method would require the client to provide positional values. Refer to XIC values XNSpotLocation and XNFocusWindow.
XIMPreeditCallbacks | If chosen, the input method would require the client to define the set of preedit callbacks. Refer to XIC values XNPreeditStartCallback, XNPreeditDoneCallback, XNPreeditDrawCallback, and XNPreeditCaretCallback.
XIMPreeditNothing | If chosen, the input method can function without any preedit values.
XIMPreeditNone | The input method does not provide any preedit feedback. Any preedit value is ignored. This style is mutually exclusive with the other preedit styles.

The status category defines what type of support is provided by the input method for status information.

XIMStatusArea | The input method requires the client to provide some area values for it to do its status feedback. See XNArea and XNAreaNeeded.
XIMStatusCallbacks | The input method requires the client to define the set of status callbacks, XNStatusStartCallback, XNStatusDoneCallback, and XNStatusDrawCallback.
XIMStatusNothing | The input method can function without any status values.
XIMStatusNone | The input method does not provide any status feedback. If chosen, any status value is ignored. This style is mutually exclusive with the other status styles.

#### Resource Name and Class

The XNResourceName and XNResourceClass arguments are strings that specify the full name and class used by the input method. These values should be used as prefixes for the name and class when looking up resources that may vary according to the input method. If these values are not set, the resources will not be fully specified.

It is not intended that values that can be set as XIM values be set as resources.

#### Destroy Callback

The XNDestroyCallback argument is a pointer to a structure of type XIMCallback. XNDestroyCallback is triggered when an input method stops its service for any reason. After the callback is invoked, the input method is closed and the associated input context(s) are destroyed by Xlib. Therefore, the client should not call or .

The generic prototype of this callback function is as follows:

      void DestroyCallback
      XIM im
      XPointer client_data
      XPointer call_data

im

  Specifies the input method.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

A DestroyCallback is always called with a NULL call_data argument.

#### Query IM/IC Values List

XNQueryIMValuesList and XNQueryICValuesList are used to query about XIM and XIC values supported by the input method.

The argument value must be a pointer to a location where the returned value will be stored. The returned value is a pointer to a structure of type XIMValuesList. Clients are responsible for freeing the XIMValuesList structure. To do so, use .

The XIMValuesList structure is defined as follows:

    typedef struct {
         unsigned short count_values;
         char **supported_values;
    } XIMValuesList;

#### Visible Position

The XNVisiblePosition argument indicates whether the visible position masks of XIMFeedback in XIMText are available.

The argument value must be a pointer to a location where the returned value will be stored. The returned value is of type Bool. If the returned value is True, the input method uses the visible position masks of XIMFeedback in XIMText; otherwise, the input method does not use the masks.

Because this XIM value is optional, a client should call with argument XNQueryIMValuesList before using this argument. If the XNVisiblePosition does not exist in the IM values list returned from XNQueryIMValuesList, the visible position masks of XIMFeedback in XIMText are not used to indicate the visible position.

#### Preedit Callback Behavior

The XNR6PreeditCallback argument originally included in the X11R6 specification has been deprecated.\(dg During formulation of the X11R6 specification, the behavior of the R6 PreeditDrawCallbacks was going to differ significantly from that of the R5 callbacks. Late changes to the specification converged the R5 and R6 behaviors, eliminating the need for XNR6PreeditCallback. Unfortunately, this argument was not removed from the R6 specification before it was published.

The XNR6PreeditCallback argument indicates whether the behavior of preedit callbacks regarding XIMPreeditDrawCallbackStruct values follows Release 5 or Release 6 semantics.

The value is of type Bool. When querying for XNR6PreeditCallback, if the returned value is True, the input method uses the Release 6 behavior; otherwise, it uses the Release 5 behavior. The default value is False. In order to use Release 6 semantics, the value of XNR6PreeditCallback must be set to True.

Because this XIM value is optional, a client should call with argument XNQueryIMValuesList before using this argument. If the XNR6PreeditCallback does not exist in the IM values list returned from XNQueryIMValuesList, the PreeditCallback behavior is Release 5 semantics.

### Input Context Functions

An input context is an abstraction that is used to contain both the data required (if any) by an input method and the information required to display that data. There may be multiple input contexts for one input method. The programming interfaces for creating, reading, or modifying an input context use a variable argument list. The name elements of the argument lists are referred to as XIC values. It is intended that input methods be controlled by these XIC values. As new XIC values are created, they should be registered with the X Consortium.

To create an input context, use .

      XIC XCreateIC
      XIM im

im

  Specifies the input method.

...

  Specifies the variable length argument list to set XIC values.

The function creates a context within the specified input method.

Some of the arguments are mandatory at creation time, and the input context will not be created if those arguments are not provided. The mandatory arguments are the input style and the set of text callbacks (if the input style selected requires callbacks). All other input context values can be set later.

returns a NULL value if no input context could be created. A NULL value could be returned for any of the following reasons:

- A required argument was not set.

- A read-only argument was set (for example, XNFilterEvents).

- The argument name is not recognized.

- The input method encountered an input method implementation-dependent error.

can generate BadAtom, BadColor, BadPixmap, and BadWindow errors.

To destroy an input context, use .

      void XDestroyIC
      XIC ic

ic

  Specifies the input context.

destroys the specified input context.

To communicate to and synchronize with input method for any changes in keyboard focus from the client side, use and .

      void XSetICFocus
      XIC ic

ic

  Specifies the input context.

The function allows a client to notify an input method that the focus window attached to the specified input context has received keyboard focus. The input method should take action to provide appropriate feedback. Complete feedback specification is a matter of user interface policy.

Calling does not affect the focus window value.

      void XUnsetICFocus
      XIC ic

ic

  Specifies the input context.

The function allows a client to notify an input method that the specified input context has lost the keyboard focus and that no more input is expected on the focus window attached to that input context. The input method should take action to provide appropriate feedback. Complete feedback specification is a matter of user interface policy.

Calling does not affect the focus window value; the client may still receive events from the input method that are directed to the focus window.

To reset the state of an input context to its initial state, use or .

      char *XmbResetIC
      XIC ic

      wchar_t *XwcResetIC
      XIC ic

ic

  Specifies the input context.

When XNResetState is set to XIMInitialState, and reset an input context to its initial state; when XNResetState is set to XIMPreserveState, the current input context state is preserved. In both cases, any input pending on that context is deleted. The input method is required to clear the preedit area, if any, and update the status accordingly. Calling or does not change the focus.

The return value of is its current preedit string as a multibyte string. If there is any preedit text drawn or visible to the user, then these procedures must return a non-NULL string. If there is no visible preedit text, then it is input method implementation-dependent whether these procedures return a non-NULL string or NULL.

The client should free the returned string by calling .

To get the input method associated with an input context, use .

      XIM XIMOfIC
      XIC ic

ic

  Specifies the input context.

The function returns the input method associated with the specified input context.

Xlib provides two functions for setting and reading XIC values, respectively, and . Both functions have a variable-length argument list. In that argument list, any XIC value's name must be denoted with a character string using the X Portable Character Set.

To set XIC values, use .

      char *XSetICValues
      XIC ic

ic

  Specifies the input context.

...

  Specifies the variable length argument list to set XIC values.

The function returns NULL if no error occurred; otherwise, it returns the name of the first argument that could not be set. An argument might not be set for any of the following reasons:

- The argument is read-only (for example, XNFilterEvents).

- The argument name is not recognized.

- An implementation-dependent error occurs.

Each value to be set must be an appropriate datum, matching the data type imposed by the semantics of the argument.

can generate BadAtom, BadColor, BadCursor, BadPixmap, and BadWindow errors.

To obtain XIC values, use .

      char *XGetICValues
      XIC ic

ic

  Specifies the input context.

...

  Specifies the variable length argument list to get XIC values.

The function returns NULL if no error occurred; otherwise, it returns the name of the first argument that could not be obtained. An argument could not be obtained for any of the following reasons:

- The argument name is not recognized.

- The input method encountered an implementation-dependent error.

Each IC attribute value argument (following a name) must point to a location where the IC value is to be stored. That is, if the IC value is of type T, the argument must be of type T*. If T itself is a pointer type, then allocates memory to store the actual data, and the client is responsible for freeing this data by calling with the returned pointer. The exception to this rule is for an IC value of type XVaNestedList (for preedit and status attributes). In this case, the argument must also be of type XVaNestedList. Then, the rule of changing type T to T* and freeing the allocated data applies to each element of the nested list.

### Input Context Values

The following tables describe how XIC values are interpreted by an input method depending on the input style chosen by the user.

The first column lists the XIC values. The second column indicates which values are involved in affecting, negotiating, and setting the geometry of the input method windows. The subentries under the third column indicate the different input styles that are supported. Each of these columns indicates how each of the XIC values are treated by that input style.

The following keys apply to these tables.

Key | Explanation
--- | ---
C | This value must be set with .
D | This value may be set using .> If it is not set,> a default is provided.
G | This value may be read using .
GN | This value may cause geometry negotiation when its value is set by means of or .
GR | This value will be the response of the input method when any GN value is changed.
GS | This value will cause the geometry of the input method window to be set.
O | This value must be set once and only once. It need not be set at create time.
S | This value may be set with .
Ignored | This value is ignored by the input method for the given input style.

XIC Value | Geometry Mangement | Preedit Callback | Preedit Position | Input Style Preedit Area | Preedit Nothing | Preedit None
--- | --- | --- | --- | --- | --- | ---
Input Style |  | C-G | C-G | C-G | C-G | C-G
Client Window |  | O-G | O-G | O-G | O-G | Ignored
Focus Window | GN | D-S-G | D-S-G | D-S-G | D-S-G | Ignored
Resource Name |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Resource Class |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Geometry Callback |  | Ignored | Ignored | D-S-G | Ignored | Ignored
Filter Events |  | G | G | G | G | Ignored
Destroy Callback |  | D-S-G | D-S-G | D-S-G | D-S-G | D-S-G
String Conversion Callback |  | S-G | S-G | S-G | S-G | S-G
String Conversion |  | D-S-G | D-S-G | D-S-G | D-S-G | D-S-G
Reset State |  | D-S-G | D-S-G | D-S-G | D-S-G | Ignored
HotKey |  | S-G | S-G | S-G | S-G | Ignored
HotKeyState |  | D-S-G | D-S-G | D-S-G | D-S-G | Ignored
`Preedit`
Area | GS | Ignored | D-S-G | D-S-G | Ignored | Ignored
Area Needed | GN-GR | Ignored | Ignored | S-G | Ignored | Ignored
Spot Location |  | Ignored | D-S-G | Ignored | Ignored | Ignored
Colormap |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Foreground |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Background |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Background Pixmap |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Font Set | GN | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Line Spacing | GN | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Cursor |  | Ignored | D-S-G | D-S-G | D-S-G | Ignored
Preedit State |  | D-S-G | D-S-G | D-S-G | D-S-G | Ignored
Preedit State Notify Callback |  | S-G | S-G | S-G | S-G | Ignored
Preedit Callbacks |  | C-S-G | Ignored | Ignored | Ignored | Ignored

XIC Value | Geomentry Management | Status Callback | Status Area | Status Nothing | Status None
--- | --- | --- | --- | --- | ---
Input Style |  | C-G | C-G | C-G | C-G
Client Window |  | O-G | O-G | O-G | Ignored
Focus Window | GN | D-S-G | D-S-G | D-S-G | Ignored
Resource Name |  | Ignored | D-S-G | D-S-G | Ignored
Resource Class |  | Ignored | D-S-G | D-S-G | Ignored
Geometry Callback |  | Ignored | D-S-G | Ignored | Ignored
Filter Events |  | G | G | G | G
Status
Area | GS | Ignored | D-S-G | Ignored | Ignored
Area Needed | GN-GR | Ignored | S-G | Ignored | Ignored
Colormap |  | Ignored | D-S-G | D-S-G | Ignored
Foreground |  | Ignored | D-S-G | D-S-G | Ignored
Background |  | Ignored | D-S-G | D-S-G | Ignored
Background Pixmap |  | Ignored | D-S-G | D-S-G | Ignored
Font Set | GN | Ignored | D-S-G | D-S-G | Ignored
Line Spacing | GN | Ignored | D-S-G | D-S-G | Ignored
Cursor |  | Ignored | D-S-G | D-S-G | Ignored
Status Callbacks |  | C-S-G | Ignored | Ignored | Ignored

#### Input Style

The XNInputStyle argument specifies the input style to be used. The value of this argument must be one of the values returned by the function with the XNQueryInputStyle argument specified in the supported_styles list.

Note that this argument must be set at creation time and cannot be changed.

#### Client Window

The XNClientWindow argument specifies to the input method the client window in which the input method can display data or create subwindows. Geometry values for input method areas are given with respect to the client window. Dynamic change of client window is not supported. This argument may be set only once and should be set before any input is done using this input context. If it is not set, the input method may not operate correctly.

If an attempt is made to set this value a second time with , the string XNClientWindow will be returned by , and the client window will not be changed.

If the client window is not a valid window ID on the display attached to the input method, a BadWindow error can be generated when this value is used by the input method.

#### Focus Window

The XNFocusWindow argument specifies the focus window. The primary purpose of the XNFocusWindow is to identify the window that will receive the key event when input is composed. In addition, the input method may possibly affect the focus window as follows:

- Select events on it

- Send events to it

- Modify its properties

- Grab the keyboard within that window

The associated value must be of type Window. If the focus window is not a valid window ID on the display attached to the input method, a BadWindow error can be generated when this value is used by the input method.

When this XIC value is left unspecified, the input method will use the client window as the default focus window.

#### Resource Name and Class

The XNResourceName and XNResourceClass arguments are strings that specify the full name and class used by the client to obtain resources for the client window. These values should be used as prefixes for name and class when looking up resources that may vary according to the input context. If these values are not set, the resources will not be fully specified.

It is not intended that values that can be set as XIC values be set as resources.

#### Geometry Callback

The XNGeometryCallback argument is a structure of type XIMCallback (see section 13.5.6.13.12).

The XNGeometryCallback argument specifies the geometry callback that a client can set. This callback is not required for correct operation of either an input method or a client. It can be set for a client whose user interface policy permits an input method to request the dynamic change of that input method's window. An input method that does dynamic change will need to filter any events that it uses to initiate the change.

#### Filter Events

The XNFilterEvents argument returns the event mask that an input method needs to have selected for. The client is expected to augment its own event mask for the client window with this one.

This argument is read-only, is set by the input method at create time, and is never changed.

The type of this argument is unsigned long. Setting this value will cause an error.

#### Destroy Callback

The XNDestroyCallback argument is a pointer to a structure of type XIMCallback (see section 13.5.6.13.12). This callback is triggered when the input method stops its service for any reason; for example, when a connection to an IM server is broken. After the destroy callback is called, the input context is destroyed and the input method is closed. Therefore, the client should not call and .

#### String Conversion Callback

The XNStringConversionCallback argument is a structure of type XIMCallback (see section 13.5.6.13.12).

The XNStringConversionCallback argument specifies a string conversion callback. This callback is not required for correct operation of either the input method or the client. It can be set by a client to support string conversions that may be requested by the input method. An input method that does string conversions will filter any events that it uses to initiate the conversion.

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this argument.

#### String Conversion

The XNStringConversion argument is a structure of type XIMStringConversionText.

The XNStringConversion argument specifies the string to be converted by an input method. This argument is not required for correct operation of either the input method or the client.

String conversion facilitates the manipulation of text independent of preediting. It is essential for some input methods and clients to manipulate text by performing context-sensitive conversion, reconversion, or transliteration conversion on it.

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this argument.

The XIMStringConversionText structure is defined as follows:

    typedef struct _XIMStringConversionText {
         unsigned short              length;
         XIMStringConversionFeedback *feedback;
         Bool                        encoding_is_wchar;
         union {
              char     *mbs;
              wchar_t  *wcs;
         } string;
    } XIMStringConversionText;

    typedef unsigned long XIMStringConversionFeedback;

The feedback member is reserved for future use. The text to be converted is defined by the string and length members. The length is indicated in characters. To prevent the library from freeing memory pointed to by an uninitialized pointer, the client should set the feedback element to NULL.

#### Reset State

The XNResetState argument specifies the state the input context will return to after calling or .

The XIC state may be set to its initial state, as specified by the XNPreeditState value when was called, or it may be set to preserve the current state.

The valid masks for XIMResetState are as follows:

    typedef unsigned long XIMResetState;

    #define XIMInitialState  (1L)
    #define XIMPreserveState (1L<<1)

If XIMInitialState is set, then and will return to the initial XNPreeditState state of the XIC.

If XIMPreserveState is set, then and will preserve the current state of the XIC.

If XNResetState is left unspecified, the default is XIMInitialState.

XIMResetState values other than those specified above will default to XIMInitialState.

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this argument.

#### Hot Keys

The XNHotKey argument specifies the hot key list to the XIC. The hot key list is a pointer to the structure of type XIMHotKeyTriggers, which specifies the key events that must be received without any interruption of the input method. For the hot key list set with this argument to be utilized, the client must also set XNHotKeyState to XIMHotKeyStateON.

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this functionality.

The value of the argument is a pointer to a structure of type XIMHotKeyTriggers.

If an event for a key in the hot key list is found, then the process will receive the event and it will be processed inside the client.

    typedef struct {
         KeySym keysym;
         unsigned int modifier;
         unsigned int modifier_mask;
    } XIMHotKeyTrigger;

    typedef struct {
         int num_hot_key;
         XIMHotKeyTrigger *key;
    } XIMHotKeyTriggers;

The combination of modifier and modifier_mask are used to represent one of three states for each modifier: either the modifier must be on, or the modifier must be off, or the modifier is a ``don't care'' - it may be on or off. When a modifier_mask bit is set to 0, the state of the associated modifier is ignored when evaluating whether the key is hot or not.

Modifier Bit | Mask Bit | Meaning
--- | --- | ---
0 | 1 | The modifier must be off.
1 | 1 | The modifier must be on.
n/a | 0 | Do not care if the modifier is on or off.

#### Hot Key State

The XNHotKeyState argument specifies the hot key state of the input method. This is usually used to switch the input method between hot key operation and normal input processing.

The value of the argument is a pointer to a structure of type XIMHotKeyState .

    typedef unsigned long XIMHotKeyState;

    #define XIMHotKeyStateON            (0x0001L)
    #define XIMHotKeyStateOFF           (0x0002L)

If not specified, the default is XIMHotKeyStateOFF.

#### Preedit and Status Attributes

The XNPreeditAttributes and XNStatusAttributes arguments specify to an input method the attributes to be used for the preedit and status areas, if any. Those attributes are passed to or as a nested variable-length list. The names to be used in these lists are described in the following sections.

##### Area

The value of the XNArea argument must be a pointer to a structure of type XRectangle. The interpretation of the XNArea argument is dependent on the input method style that has been set.

If the input method style is XIMPreeditPosition, XNArea specifies the clipping region within which preediting will take place. If the focus window has been set, the coordinates are assumed to be relative to the focus window. Otherwise, the coordinates are assumed to be relative to the client window. If neither has been set, the results are undefined.

If XNArea is not specified, is set to NULL, or is invalid, the input method will default the clipping region to the geometry of the XNFocusWindow. If the area specified is NULL or invalid, the results are undefined.

If the input style is XIMPreeditArea or XIMStatusArea, XNArea specifies the geometry provided by the client to the input method. The input method may use this area to display its data, either preedit or status depending on the area designated. The input method may create a window as a child of the client window with dimensions that fit the XNArea. The coordinates are relative to the client window. If the client window has not been set yet, the input method should save these values and apply them when the client window is set. If XNArea is not specified, is set to NULL, or is invalid, the results are undefined.

##### Area Needed

When set, the XNAreaNeeded argument specifies the geometry suggested by the client for this area (preedit or status). The value associated with the argument must be a pointer to a structure of type XRectangle. Note that the x, y values are not used and that nonzero values for width or height are the constraints that the client wishes the input method to respect.

When read, the XNAreaNeeded argument specifies the preferred geometry desired by the input method for the area.

This argument is only valid if the input style is XIMPreeditArea or XIMStatusArea. It is used for geometry negotiation between the client and the input method and has no other effect on the input method (see section 13.5.1.5).

##### Spot Location

The XNSpotLocation argument specifies to the input method the coordinates of the spot to be used by an input method executing with XNInputStyle set to XIMPreeditPosition. When specified to any input method other than XIMPreeditPosition, this XIC value is ignored.

The x coordinate specifies the position where the next character would be inserted. The y coordinate is the position of the baseline used by the current text line in the focus window. The x and y coordinates are relative to the focus window, if it has been set; otherwise, they are relative to the client window. If neither the focus window nor the client window has been set, the results are undefined.

The value of the argument is a pointer to a structure of type XPoint.

##### Colormap

Two different arguments can be used to indicate what colormap the input method should use to allocate colors, a colormap ID, or a standard colormap name.

The XNColormap argument is used to specify a colormap ID. The argument value is of type Colormap. An invalid argument may generate a BadColor error when it is used by the input method.

The XNStdColormap argument is used to indicate the name of the standard colormap in which the input method should allocate colors. The argument value is an Atom that should be a valid atom for calling . An invalid argument may generate a BadAtom error when it is used by the input method.

If the colormap is left unspecified, the client window colormap becomes the default.

##### Foreground and Background

The XNForeground and XNBackground arguments specify the foreground and background pixel, respectively. The argument value is of type unsigned long. It must be a valid pixel in the input method colormap.

If these values are left unspecified, the default is determined by the input method.

##### Background Pixmap

The XNBackgroundPixmap argument specifies a background pixmap to be used as the background of the window. The value must be of type Pixmap. An invalid argument may generate a BadPixmap error when it is used by the input method.

If this value is left unspecified, the default is determined by the input method.

##### Font Set

The XNFontSet argument specifies to the input method what font set is to be used. The argument value is of type XFontSet.

If this value is left unspecified, the default is determined by the input method.

##### Line Spacing

The XNLineSpace argument specifies to the input method what line spacing is to be used in the preedit window if more than one line is to be used. This argument is of type int.

If this value is left unspecified, the default is determined by the input method.

##### Cursor

The XNCursor argument specifies to the input method what cursor is to be used in the specified window. This argument is of type Cursor.

An invalid argument may generate a BadCursor error when it is used by the input method. If this value is left unspecified, the default is determined by the input method.

##### Preedit State

The XNPreeditState argument specifies the state of input preediting for the input method. Input preediting can be on or off.

The valid mask names for XNPreeditState are as follows:

    typedef unsigned long XIMPreeditState;

    #define XIMPreeditUnknown    0L
    #define XIMPreeditEnable     1L
    #define XIMPreeditDisable    (1L<<1)

If a value of XIMPreeditEnable is set, then input preediting is turned on by the input method.

If a value of XIMPreeditDisable is set, then input preediting is turned off by the input method.

If XNPreeditState is left unspecified, then the state will be implementation-dependent.

When XNResetState is set to XIMInitialState, the XNPreeditState value specified at the creation time will be reflected as the initial state for and .

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this argument.

##### Preedit State Notify Callback

The preedit state notify callback is triggered by the input method when the preediting state has changed. The value of the XNPreeditStateNotifyCallback argument is a pointer to a structure of type XIMCallback. The generic prototype is as follows:

      void PreeditStateNotifyCallback
      XIC ic
      XPointer client_data
      XIMPreeditStateNotifyCallbackStruct *call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Specifies the current preedit state.

The XIMPreeditStateNotifyCallbackStruct structure is defined as follows:

    typedef struct _XIMPreeditStateNotifyCallbackStruct {
         XIMPreeditState state;
    } XIMPreeditStateNotifyCallbackStruct;

Because this XIC value is optional, a client should call with argument XNQueryICValuesList before using this argument.

##### Preedit and Status Callbacks

A client that wants to support the input style XIMPreeditCallbacks must provide a set of preedit callbacks to the input method. The set of preedit callbacks is as follows:

XNPreeditStartCallback | This is called when the input method starts preedit.
XNPreeditDoneCallback | This is called when the input method stops preedit.
XNPreeditDrawCallback | This is called when a number of preedit keystrokes should be echoed.
XNPreeditCaretCallback | This is called to move the text insertion point within the preedit string.

A client that wants to support the input style XIMStatusCallbacks must provide a set of status callbacks to the input method. The set of status callbacks is as follows:

XNStatusStartCallback | This is called when the input method initializes the status area.
XNStatusDoneCallback | This is called when the input method no longer needs the status area.
XNStatusDrawCallback | This is called when updating of the status area is required.

The value of any status or preedit argument is a pointer to a structure of type XIMCallback.

    typedef void (*XIMProc)();

    typedef struct {
         XPointer client_data;
         XIMProc callback;
    } XIMCallback;

Each callback has some particular semantics and will carry the data that expresses the environment necessary to the client into a specific data structure. This paragraph only describes the arguments to be used to set the callback.

Setting any of these values while doing preedit may cause unexpected results.

### Input Method Callback Semantics

XIM callbacks are procedures defined by clients or text drawing packages that are to be called from the input method when selected events occur. Most clients will use a text editing package or a toolkit and, hence, will not need to define such callbacks. This section defines the callback semantics, when they are triggered, and what their arguments are. This information is mostly useful for X toolkit implementors.

Callbacks are mostly provided so that clients (or text editing packages) can implement on-the-spot preediting in their own window. In that case, the input method needs to communicate and synchronize with the client. The input method needs to communicate changes in the preedit window when it is under control of the client. Those callbacks allow the client to initialize the preedit area, display a new preedit string, move the text insertion point during preedit, terminate preedit, or update the status area.

All callback procedures follow the generic prototype:

      void CallbackPrototype
      XIC ic
      XPointer client_data
      SomeType call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Specifies data specific to the callback.

The call_data argument is a structure that expresses the arguments needed to achieve the semantics; that is, it is a specific data structure appropriate to the callback. In cases where no data is needed in the callback, this call_data argument is NULL. The client_data argument is a closure that has been initially specified by the client when specifying the callback and passed back. It may serve, for example, to inherit application context in the callback.

The following paragraphs describe the programming semantics and specific data structure associated with the different reasons.

#### Geometry Callback

The geometry callback is triggered by the input method to indicate that it wants the client to negotiate geometry. The generic prototype is as follows:

      void GeometryCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

The callback is called with a NULL call_data argument.

#### Destroy Callback

The destroy callback is triggered by the input method when it stops service for any reason. After the callback is invoked, the input context will be freed by Xlib. The generic prototype is as follows:

      void DestroyCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

The callback is called with a NULL call_data argument.

#### String Conversion Callback

The string conversion callback is triggered by the input method to request the client to return the string to be converted. The returned string may be either a multibyte or wide character string, with an encoding matching the locale bound to the input context. The callback prototype is as follows:

      void StringConversionCallback
      XIC ic
      XPointer client_data
      XIMStringConversionCallbackStruct *call_data

ic

  Specifies the input method.

client_data

  Specifies the additional client data.

call_data

  Specifies the amount of the string to be converted.

The callback is passed an XIMStringConversionCallbackStruct structure in the call_data argument. The text member is an XIMStringConversionText structure (see section 13.5.6.9) to be filled in by the client and describes the text to be sent to the input method. The data pointed to by the string and feedback elements of the XIMStringConversionText structure will be freed using by the input method after the callback returns. So the client should not point to internal buffers that are critical to the client. Similarly, because the feedback element is currently reserved for future use, the client should set feedback to NULL to prevent the library from freeing memory at some random location due to an uninitialized pointer.

The XIMStringConversionCallbackStruct structure is defined as follows:

    typedef struct _XIMStringConversionCallbackStruct {
         XIMStringConversionPosition position;
         XIMCaretDirection direction;
         short factor;
         XIMStringConversionOperation operation;
         XIMStringConversionText *text;
    } XIMStringConversionCallbackStruct;

    typedef short XIMStringConversionPosition;

    typedef unsigned short XIMStringConversionOperation;

    #define XIMStringConversionSubstitution       (0x0001)
    #define XIMStringConversionRetrieval          (0x0001)

XIMStringConversionPosition specifies the starting position of the string to be returned in the XIMStringConversionText structure. The value identifies a position, in units of characters, relative to the client's cursor position in the client's buffer.

The ending position of the text buffer is determined by the direction and factor members. Specifically, it is the character position relative to the starting point as defined by the XIMCaretDirection. The factor member of XIMStringConversionCallbackStruct specifies the number of XIMCaretDirection positions to be applied. For example, if the direction specifies `XIMLineEnd` and factor is 1, then all characters from the starting position to the end of the current display line are returned. If the direction specifies `XIMForwardChar` or `XIMBackwardChar`, then the factor specifies a relative position, indicated in characters, from the starting position.

XIMStringConversionOperation specifies whether the string to be converted should be deleted (substitution) or copied (retrieval) from the client's buffer. When the XIMStringConversionOperation is XIMStringConversionSubstitution, the client must delete the string to be converted from its own buffer. When the XIMStringConversionOperation is XIMStringConversionRetrieval, the client must not delete the string to be converted from its buffer. The substitute operation is typically used for reconversion and transliteration conversion, while the retrieval operation is typically used for context-sensitive conversion.

#### Preedit State Callbacks

When the input method turns preediting on or off, a or callback is triggered to let the toolkit do the setup or the cleanup for the preedit region.

      int PreeditStartCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

When preedit starts on the specified input context, the callback is called with a NULL call_data argument. will return the maximum size of the preedit string. A positive number indicates the maximum number of bytes allowed in the preedit string, and a value of -1 indicates there is no limit.

      void PreeditDoneCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

When preedit stops on the specified input context, the callback is called with a NULL call_data argument. The client can release the data allocated by .

should initialize appropriate data needed for displaying preedit information and for handling further calls. Once is called, it will not be called again before has been called.

#### Preedit Draw Callback

This callback is triggered to draw and insert, delete or replace, preedit text in the preedit region. The preedit text may include unconverted input text such as Japanese Kana, converted text such as Japanese Kanji characters, or characters of both kinds. That string is either a multibyte or wide character string, whose encoding matches the locale bound to the input context. The callback prototype is as follows:

      void PreeditDrawCallback
      XIC ic
      XPointer client_data
      XIMPreeditDrawCallbackStruct *call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Specifies the preedit drawing information.

The callback is passed an XIMPreeditDrawCallbackStruct structure in the call_data argument. The text member of this structure contains the text to be drawn. After the string has been drawn, the caret should be moved to the specified location.

The XIMPreeditDrawCallbackStruct structure is defined as follows:

    typedef struct _XIMPreeditDrawCallbackStruct {
         int caret;     /* Cursor offset within preedit string */
         int chg_first;     /* Starting change position */
         int chg_length;     /* Length of the change in character count */
         XIMText *text;
    } XIMPreeditDrawCallbackStruct;

The client must keep updating a buffer of the preedit text and the callback arguments referring to indexes in that buffer. The call_data fields have specific meanings according to the operation, as follows:

- To indicate text deletion, the call_data member specifies a NULL text field. The text to be deleted is then the current text in the buffer from position chg_first (starting at zero) on a character length of chg_length.

- When text is non-NULL, it indicates insertion or replacement of text in the buffer.

- The chg_length member identifies the number of characters in the current preedit buffer that are affected by this call. A positive chg_length indicates that chg_length number of characters, starting at chg_first, must be deleted or must be replaced by text, whose length is specified in the XIMText structure.

- A chg_length value of zero indicates that text must be inserted right at the position specified by chg_first. A value of zero for chg_first specifies the first character in the buffer.

- chg_length and chg_first combine to identify the modification required to the preedit buffer; beginning at chg_first, replace chg_length number of characters with the text in the supplied XIMText structure. For example, suppose the preedit buffer contains the string "ABCDE".

-     Text:      A B C D E
                ^ ^ ^ ^ ^ ^
      CharPos:  0 1 2 3 4 5

  The CharPos in the diagram shows the location of the character position relative to the character.

- If the value of chg_first is 1 and the value of chg_length is 3, this says to replace 3 characters beginning at character position 1 with the string in the XIMText structure. Hence, BCD would be replaced by the value in the structure.

- Though chg_length and chg_first are both signed integers they will never have a negative value.

- The caret member identifies the character position before which the cursor should be placed - after modification to the preedit buffer has been completed. For example, if caret is zero, the cursor is at the beginning of the buffer. If the caret is one, the cursor is between the first and second character.

    typedef struct _XIMText {
         unsigned short length;
         XIMFeedback * feedback;
         Bool encoding_is_wchar;
         union {
              char * multi_byte;
              wchar_t * wide_char;
         } string;
    } XIMText;

The text string passed is actually a structure specifying as follows:

- The length member is the text length in characters.

- The encoding_is_wchar member is a value that indicates if the text string is encoded in wide character or multibyte format. The text string may be passed either as multibyte or as wide character; the input method controls in which form data is passed. The client's callback routine must be able to handle data passed in either form.

- The string member is the text string.

- The feedback member indicates rendering type for each character in the string member. If string is NULL (indicating that only highlighting of the existing preedit buffer should be updated), feedback points to length highlight elements that should be applied to the existing preedit buffer, beginning at chg_first.

The feedback member expresses the types of rendering feedback the callback should apply when drawing text. Rendering of the text to be drawn is specified either in generic ways (for example, primary, secondary) or in specific ways (reverse, underline). When generic indications are given, the client is free to choose the rendering style. It is necessary, however, that primary and secondary be mapped to two distinct rendering styles.

If an input method wants to control display of the preedit string, an input method can indicate the visibility hints using feedbacks in a specific way. The XIMVisibleToForward, XIMVisibleToBackword, and XIMVisibleToCenter masks are exclusively used for these visibility hints. The XIMVisibleToForward mask indicates that the preedit text is preferably displayed in the primary draw direction from the caret position in the preedit area forward. The XIMVisibleToBackword mask indicates that the preedit text is preferably displayed from the caret position in the preedit area backward, relative to the primary draw direction. The XIMVisibleToCenter mask indicates that the preedit text is preferably displayed with the caret position in the preedit area centered.

The insertion point of the preedit string could exist outside of the visible area when visibility hints are used. Only one of the masks is valid for the entire preedit string, and only one character can hold one of these feedbacks for a given input context at one time. This feedback may be OR'ed together with another highlight (such as XIMReverse). Only the most recently set feedback is valid, and any previous feedback is automatically canceled. This is a hint to the client, and the client is free to choose how to display the preedit string.

The feedback member also specifies how rendering of the text argument should be performed. If the feedback is NULL, the callback should apply the same feedback as is used for the surrounding characters in the preedit buffer; if chg_first is at a highlight boundary, the client can choose which of the two highlights to use. If feedback is not NULL, feedback specifies an array defining the rendering for each character of the string, and the length of the array is thus length.

If an input method wants to indicate that it is only updating the feedback of the preedit text without changing the content of it, the XIMText structure will contain a NULL value for the string field, the number of characters affected (relative to chg_first) will be in the length field, and the feedback field will point to an array of XIMFeedback.

Each element in the feedback array is a bitmask represented by a value of type XIMFeedback. The valid mask names are as follows:

    typedef unsigned long XIMFeedback;

    #define     XIMReverse                     1L
    #define     XIMUnderline                   (1L<<1)
    #define     XIMHighlight                   (1L<<2)
    #define     XIMPrimary                     (1L<<5)*
    #define     XIMSecondary                   (1L<<6)*
    #define     XIMTertiary                    (1L<<7)*
    #define     XIMVisibleToForward            (1L<<8)
    #define     XIMVisibleToBackward           (1L<<9)
    #define     XIMVisibleToCenter               (1L<<10)

    *† The values for XIMPrimary, XIMSecondary, and XIMTertiary were incorrectly defined in
    the R5 specification. The X Consortium’s X11R5 implementation correctly
    implemented the values for these highlights. The value of these highlights has
    been corrected in this specification to agree with the values in the
    Consortium’s X11R5 and X11R6 implementations.

Characters drawn with the XIMReverse highlight should be drawn by swapping the foreground and background colors used to draw normal, unhighlighted characters. Characters drawn with the XIMUnderline highlight should be underlined. Characters drawn with the XIMHighlight, XIMPrimary, XIMSecondary, and XIMTertiary highlights should be drawn in some unique manner that must be different from XIMReverse and XIMUnderline. The values for XIMPrimary, XIMSecondary, and XIMTertiary were incorrectly defined in the R5 specification. The X Consortium's X11R5 implementation correctly implemented the values for these highlights. The value of these highlights has been corrected in this specification to agree with the values in the Consortium's X11R5 and X11R6 implementations.

#### Preedit Caret Callback

An input method may have its own navigation keys to allow the user to move the text insertion point in the preedit area (for example, to move backward or forward). Consequently, input method needs to indicate to the client that it should move the text insertion point. It then calls the PreeditCaretCallback.

      void PreeditCaretCallback
      XIC ic
      XPointer client_data
      XIMPreeditCaretCallbackStruct *call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Specifies the preedit caret information.

The input method will trigger PreeditCaretCallback to move the text insertion point during preedit. The call_data argument contains a pointer to an XIMPreeditCaretCallbackStruct structure, which indicates where the caret should be moved. The callback must move the insertion point to its new location and return, in field position, the new offset value from the initial position.

The XIMPreeditCaretCallbackStruct structure is defined as follows:

    typedef struct _XIMPreeditCaretCallbackStruct {
         int position;     /* Caret offset within preedit string */
         XIMCaretDirection direction;     /* Caret moves direction */
         XIMCaretStyle style;     /* Feedback of the caret */
    } XIMPreeditCaretCallbackStruct;

The XIMCaretStyle structure is defined as follows:

    typedef enum {
         XIMIsInvisible,     /* Disable caret feedback */
         XIMIsPrimary,     /* UI defined caret feedback */
         XIMIsSecondary,     /* UI defined caret feedback */
    } XIMCaretStyle;

The XIMCaretDirection structure is defined as follows:

    typedef enum {
         XIMForwardChar, XIMBackwardChar,
         XIMForwardWord, XIMBackwardWord,
         XIMCaretUp, XIMCaretDown,
         XIMNextLine, XIMPreviousLine,
         XIMLineStart, XIMLineEnd,
         XIMAbsolutePosition,
         XIMDontChange,
     } XIMCaretDirection;

These values are defined as follows:

`XIMForwardChar` | Move the caret forward one character position.
`XIMBackwardChar` | Move the caret backward one character position.
`XIMForwardWord` | Move the caret forward one word.
`XIMBackwardWord` | Move the caret backward one word.
`XIMCaretUp` | Move the caret up one line keeping the current horizontal offset.
`XIMCaretDown` | Move the caret down one line keeping the current horizontal offset.
`XIMPreviousLine` | Move the caret to the beginning of the previous line.
`XIMNextLine` | Move the caret to the beginning of the next line.
`XIMLineStart` | Move the caret to the beginning of the current display line that contains the caret.
`XIMLineEnd` | Move the caret to the end of the current display line that contains the caret.
`XIMAbsolutePosition` | The callback must move to the location specified by the position field of the callback data, indicated in characters, starting from the beginning of the preedit text. Hence, a value of zero means move back to the beginning of the preedit text.
`XIMDontChange` | The caret position does not change.

#### Status Callbacks

An input method may communicate changes in the status of an input context (for example, created, destroyed, or focus changes) with three status callbacks: StatusStartCallback, StatusDoneCallback, and StatusDrawCallback.

When the input context is created or gains focus, the input method calls the StatusStartCallback callback.

      void StatusStartCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

The callback should initialize appropriate data for displaying status and for responding to StatusDrawCallback calls. Once StatusStartCallback is called, it will not be called again before StatusDoneCallback has been called.

When an input context is destroyed or when it loses focus, the input method calls StatusDoneCallback.

      void StatusDoneCallback
      XIC ic
      XPointer client_data
      XPointer call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Not used for this callback and always passed as NULL.

The callback may release any data allocated on `StatusStart`.

When an input context status has to be updated, the input method calls StatusDrawCallback.

      void StatusDrawCallback
      XIC ic
      XPointer client_data
      XIMStatusDrawCallbackStruct *call_data

ic

  Specifies the input context.

client_data

  Specifies the additional client data.

call_data

  Specifies the status drawing information.

The callback should update the status area by either drawing a string or imaging a bitmap in the status area.

The XIMStatusDataType and XIMStatusDrawCallbackStruct structures are defined as follows:

    typedef enum {
         XIMTextType,
         XIMBitmapType,
    } XIMStatusDataType;

    typedef struct _XIMStatusDrawCallbackStruct {
         XIMStatusDataType type;
         union {
              XIMText *text;
              Pixmap  bitmap;
         } data;
    } XIMStatusDrawCallbackStruct;

The feedback styles XIMVisibleToForward, XIMVisibleToBackword, and XIMVisibleToCenter are not relevant and will not appear in the XIMFeedback element of the XIMText structure.

### Event Filtering

Xlib provides the ability for an input method to register a filter internal to Xlib. This filter is called by a client (or toolkit) by calling after calling . Any client that uses the XIM interface should call to allow input methods to process their events without knowledge of the client's dispatching mechanism. A client's user interface policy may determine the priority of event filters with respect to other event-handling mechanisms (for example, modal grabs).

Clients may not know how many filters there are, if any, and what they do. They may only know if an event has been filtered on return of . Clients should discard filtered events.

To filter an event, use .

      Bool XFilterEvent
      XEvent *event
      Window w

event

  Specifies the event to filter.

w

  Specifies the window for which the filter is to be applied.

If the window argument is None, applies the filter to the window specified in the XEvent structure. The window argument is provided so that layers above Xlib that do event redirection can indicate to which window an event has been redirected.

If returns True, then some input method has filtered the event, and the client should discard the event. If returns False, then the client should continue processing the event.

If a grab has occurred in the client and returns True, the client should ungrab the keyboard.

### Getting Keyboard Input

To get composed input from an input method, use or .

      int XmbLookupString
      XIC ic
      XKeyPressedEvent *event
      char *buffer_return
      int bytes_buffer
      KeySym *keysym_return
      Status *status_return

      int XwcLookupString
      XIC ic
      XKeyPressedEvent *event
      wchar_t *buffer_return
      int wchars_buffer
      KeySym *keysym_return
      Status *status_return

ic

  Specifies the input context.

event

  Specifies the key event to be used.

buffer_return

  Returns a multibyte string or wide character string (if any) from the input method.

bytes_buffer

wchars_buffer

  Specifies space available in the return buffer.

keysym_return

  Returns the KeySym computed from the event if this argument is not NULL.

status_return

  Returns a value indicating what kind of data is returned.

The and functions return the string from the input method specified in the buffer_return argument. If no string is returned, the buffer_return argument is unchanged.

The KeySym into which the KeyCode from the event was mapped is returned in the keysym_return argument if it is non-NULL and the status_return argument indicates that a KeySym was returned. If both a string and a KeySym are returned, the KeySym value does not necessarily correspond to the string returned.

returns the length of the string in bytes, and returns the length of the string in characters. Both and return text in the encoding of the locale bound to the input method of the specified input context.

Each string returned by and begins in the initial state of the encoding of the locale (if the encoding of the locale is state-dependent).

To insure proper input processing, it is essential that the client pass only KeyPress events to and . Their behavior when a client passes a KeyRelease event is undefined.

Clients should check the status_return argument before using the other returned values. These two functions both return a value to status_return that indicates what has been returned in the other arguments. The possible values returned are:

XBufferOverflow | The input string to be returned is too large for the supplied buffer_return. The required size ( in bytes; in characters) is returned as the value of the function, and the contents of buffer_return and keysym_return are not modified. The client should recall the function with the same event and a buffer of adequate size to obtain the string.
XLookupNone | No consistent input has been composed so far. The contents of buffer_return and keysym_return are not modified, and the function returns zero.
XLookupChars | Some input characters have been composed. They are placed in the buffer_return argument, and the string length is returned as the value of the function. The string is encoded in the locale bound to the input context. The content of the keysym_return argument is not modified.
XLookupKeySym | A KeySym has been returned instead of a string and is returned in keysym_return. The content of the buffer_return argument is not modified, and the function returns zero.
XLookupBoth | Both a KeySym and a string are returned; XLookupChars and XLookupKeySym occur simultaneously.

It does not make any difference if the input context passed as an argument to and is the one currently in possession of the focus or not. Input may have been composed within an input context before it lost the focus, and that input may be returned on subsequent calls to or even though it does not have any more keyboard focus.

### Input Method Conventions

The input method architecture is transparent to the client. However, clients should respect a number of conventions in order to work properly. Clients must also be aware of possible effects of synchronization between input method and library in the case of a remote input server.

#### Client Conventions

A well-behaved client (or toolkit) should first query the input method style. If the client cannot satisfy the requirements of the supported styles (in terms of geometry management or callbacks), it should negotiate with the user continuation of the program or raise an exception or error of some sort.

#### Synchronization Conventions

A KeyPress event with a KeyCode of zero is used exclusively as a signal that an input method has composed input that can be returned by or . No other use is made of a KeyPress event with KeyCode of zero.

Such an event may be generated by either a front-end or a back-end input method in an implementation-dependent manner. Some possible ways to generate this event include:

- A synthetic event sent by an input method server

- An artificial event created by a input method filter and pushed onto a client's event queue

- A KeyPress event whose KeyCode value is modified by an input method filter

When callback support is specified by the client, input methods will not take action unless they explicitly called back the client and obtained no response (the callback is not specified or returned invalid data).

## String Constants

The following symbols for string constants are defined in `<X11/Xlib.h>`. Although they are shown here with particular macro definitions, they may be implemented as macros, as global symbols, or as a mixture of the two. The string pointer value itself is not significant; clients must not assume that inequality of two values implies inequality of the actual string data.

    #define XNVaNestedList                       "XNVaNestedList"
    #define XNSeparatorofNestedList              "separatorofNestedList"
    #define XNQueryInputStyle                    "queryInputStyle"
    #define XNClientWindow                       "clientWindow"
    #define XNInputStyle                         "inputStyle"
    #define XNFocusWindow                        "focusWindow"
    #define XNResourceName                       "resourceName"
    #define XNResourceClass                      "resourceClass"
    #define XNGeometryCallback                   "geometryCallback"
    #define XNDestroyCallback                    "destroyCallback"
    #define XNFilterEvents                       "filterEvents"
    #define XNPreeditStartCallback               "preeditStartCallback"
    #define XNPreeditDoneCallback                "preeditDoneCallback"
    #define XNPreeditDrawCallback                "preeditDrawCallback"
    #define XNPreeditCaretCallback               "preeditCaretCallback"
    #define XNPreeditStateNotifyCallback         "preeditStateNotifyCallback"
    #define XNPreeditAttributes                  "preeditAttributes"
    #define XNStatusStartCallback                "statusStartCallback"
    #define XNStatusDoneCallback                 "statusDoneCallback"
    #define XNStatusDrawCallback                 "statusDrawCallback"
    #define XNStatusAttributes                   "statusAttributes"
    #define XNArea                               "area"
    #define XNAreaNeeded                         "areaNeeded"
    #define XNSpotLocation                       "spotLocation"
    #define XNColormap                           "colorMap"
    #define XNStdColormap                        "stdColorMap"
    #define XNForeground                         "foreground"
    #define XNBackground                         "background"
    #define XNBackgroundPixmap                   "backgroundPixmap"
    #define XNFontSet                            "fontSet"
    #define XNLineSpace                          "lineSpace"
    #define XNCursor                             "cursor"
    #define XNQueryIMValuesList                  "queryIMValuesList"
    #define XNQueryICValuesList                  "queryICValuesList"
    #define XNStringConversionCallback           "stringConversionCallback"
    #define XNStringConversion                   "stringConversion"
    #define XNResetState                         "resetState"
    #define XNHotKey                             "hotkey"
    #define XNHotKeyState                        "hotkeyState"
    #define XNPreeditState                       "preeditState"
    #define XNVisiblePosition                    "visiblePosition"
    #define XNR6PreeditCallbackBehavior          "r6PreeditCallback"
    #define XNRequiredCharSet                    "requiredCharSet"
    #define XNQueryOrientation                   "queryOrientation"
    #define XNDirectionalDependentDrawing        "directionalDependentDrawing"
    #define XNContextualDrawing                  "contextualDrawing"
    #define XNBaseFontName                       "baseFontName"
    #define XNMissingCharSet                     "missingCharSet"
    #define XNDefaultString                      "defaultString"
    #define XNOrientation                        "orientation"
    #define XNFontInfo                           "fontInfo"
    #define XNOMAutomatic                        "omAutomatic"