# Widget Instantiation

A hierarchy of widget instances constitutes a widget tree. The shell widget returned by is the root of the widget tree instance. The widgets with one or more children are the intermediate nodes of that tree, and the widgets with no children of any kind are the leaves of the widget tree. With the exception of pop-up children (see ), this widget tree instance defines the associated X Window tree.

Widgets can be either composite or primitive. Both kinds of widgets can contain children, but the Intrinsics provide a set of management mechanisms for constructing and interfacing between composite widgets, their children, and other clients.

Composite widgets, that is, members of the class `compositeWidgetClass`, are containers for an arbitrary, but widget implementation-defined, collection of children, which may be instantiated by the composite widget itself, by other clients, or by a combination of the two. Composite widgets also contain methods for managing the geometry (layout) of any child widget. Under unusual circumstances, a composite widget may have zero children, but it usually has at least one. By contrast, primitive widgets that contain children typically instantiate specific children of known classes themselves and do not expect external clients to do so. Primitive widgets also do not have general geometry management methods.

In addition, the Intrinsics recursively perform many operations (for example, realization and destruction) on composite widgets and all their children. Primitive widgets that have children must be prepared to perform the recursive operations themselves on behalf of their children.

A widget tree is manipulated by several Intrinsics functions. For example, traverses the tree downward and recursively realizes all pop-up widgets and children of composite widgets. traverses the tree downward and destroys all pop-up widgets and children of composite widgets. The functions that fetch and modify resources traverse the tree upward and determine the inheritance of resources from a widget's ancestors. traverses the tree up one level and calls the geometry manager that is responsible for a widget child's geometry.

To facilitate upward traversal of the widget tree, each widget has a pointer to its parent widget. The Shell widget that returns has a parent pointer of NULL.

To facilitate downward traversal of the widget tree, the children field of each composite widget is a pointer to an array of child widgets, which includes all normal children created, not just the subset of children that are managed by the composite widget's geometry manager. Primitive widgets that instantiate children are entirely responsible for all operations that require downward traversal below themselves. In addition, every widget has a pointer to an array of pop-up children.

## Initializing the X Toolkit

Before an application can call any Intrinsics function other than `XtSetLanguageProc` and , it must initialize the Intrinsics by using

- , which initializes the Intrinsics internals

- , which initializes the per-application state

- or , which initializes the per-display state

- , which creates the root of a widget tree

Or an application can call the convenience procedure , which combines the functions of the preceding procedures. An application wishing to use the ANSI C locale mechanism should call `XtSetLanguageProc` prior to calling , , , or .

Multiple instances of X Toolkit applications may be implemented in a single address space. Each instance needs to be able to read input and dispatch events independently of any other instance. Further, an application instance may need multiple display connections to have widgets on multiple displays. From the application's point of view, multiple display connections usually are treated together as a single unit for purposes of event dispatching. To accommodate both requirements, the Intrinsics define application contexts, each of which provides the information needed to distinguish one application instance from another. The major component of an application context is a list of one or more X `Display` pointers for that application. The Intrinsics handle all display connections within a single application context simultaneously, handling input in a round-robin fashion. The application context type `XtAppContext` is opaque to clients.

To initialize the Intrinsics internals, use .

      void XtToolkitInitialize

If was previously called, it returns immediately. When is called before , the latter is protected against simultaneous activation by multiple threads.

To create an application context, use .

      XtAppContext XtCreateApplicationContext

The function returns an application context, which is an opaque type. Every application must have at least one application context.

To destroy an application context and close any remaining display connections in it, use .

      void XtDestroyApplicationContext
      XtAppContext app_context

app_context

  Specifies the application context.

The function destroys the specified application context. If called from within an event dispatch (for example, in a callback procedure), does not destroy the application context until the dispatch is complete.

To get the application context in which a given widget was created, use .

      XtAppContext XtWidgetToApplicationContext
      Widget w

w

  Specifies the widget for which you want the application context. Must be of class Object or any subclass thereof.

The function returns the application context for the specified widget.

To initialize a display and add it to an application context, use .

      void  XtDisplayInitialize
          XtAppContext app_context
          Display * display
          String application_name
          String application_class
          XrmOptionDescRec * options
          Cardinal num_options
          int * argc
          String * argv

app_context

  Specifies the application context.

display

  Specifies a previously opened display connection. Note that a single display connection can be in at most one application context.

application_name

  Specifies the name of the application instance.

application_class

  Specifies the class name of this application, which is usually the generic name for all instances of this application.

options

  Specifies how to parse the command line for any application-specific resources. The options argument is passed as a parameter to `XrmParseCommand`. For further information, see Parsing Command Line Options in Xlib — C Language X Interface and of this specification.

num_options

  Specifies the number of entries in the options list.

argc

  Specifies a pointer to the number of command line parameters.

argv

  Specifies the list of command line parameters.

The function retrieves the language string to be used for the specified display (see ), calls the language procedure (if set) with that language string, builds the resource database for the default screen, calls the Xlib `XrmParseCommand` function to parse the command line, and performs other per-display initialization. After `XrmParseCommand` has been called, argc and argv contain only those parameters that were not in the standard option table or in the table specified by the options argument. If the modified argc is not zero, most applications simply print out the modified argv along with a message listing the allowable options. On POSIX-based systems, the application name is usually the final component of argv[0]. If the synchronous resource is `True`, calls the Xlib `XSynchronize` function to put Xlib into synchronous mode for this display connection and any others currently open in the application context. See and for details on the application_name, application_class, options, and num_options arguments.

calls `XrmSetDatabase` to associate the resource database of the default screen with the display before returning.

To open a display, initialize it, and then add it to an application context, use .

      Display *XtOpenDisplay
           XtAppContext app_context
           String display_string
           String application_name
           String application_class
           XrmOptionDescRec * options
           Cardinal num_options
           int * argc
           String * argv

app_context

  Specifies the application context.

display_string

  Specifies the display string, or NULL.

application_name

  Specifies the name of the application instance, or NULL.

application_class

  Specifies the class name of this application, which is usually the generic name for all instances of this application.

options

  Specifies how to parse the command line for any application-specific resources. The options argument is passed as a parameter to `XrmParseCommand`.

num_options

  Specifies the number of entries in the options list.

argc

  Specifies a pointer to the number of command line parameters.

argv

  Specifies the list of command line parameters.

The function calls `XOpenDisplay` with the specified display_string. If display_string is NULL, uses the current value of the \-display option specified in argv. If no display is specified in argv, the user's default display is retrieved from the environment. On POSIX-based systems, this is the value of the DISPLAY environment variable.

If this succeeds, then calls and passes it the opened display and the value of the \-name option specified in argv as the application name. If no \-name option is specified and application_name is non-NULL, application_name is passed to . If application_name is NULL and if the environment variable RESOURCE_NAME is set, the value of RESOURCE_NAME is used. Otherwise, the application name is the name used to invoke the program. On implementations that conform to ANSI C Hosted Environment support, the application name will be argv[0] less any directory and file type components, that is, the final component of argv[0], if specified. If argv[0] does not exist or is the empty string, the application name is ``main''. returns the newly opened display or NULL if it failed.

See for information regarding the use of in multiple threads.

To close a display and remove it from an application context, use .

      void XtCloseDisplay
           Display * display

display

  Specifies the display.

The function calls `XCloseDisplay` with the specified display as soon as it is safe to do so. If called from within an event dispatch (for example, a callback procedure), does not close the display until the dispatch is complete. Note that applications need only call if they are to continue executing after closing the display; otherwise, they should call .

See for information regarding the use of in multiple threads.

## Establishing the Locale

Resource databases are specified to be created in the current process locale. During display initialization prior to creating the per-screen resource database, the Intrinsics will call out to a specified application procedure to set the locale according to options found on the command line or in the per-display resource specifications.

The callout procedure provided by the application is of type `XtLanguageProc`.

      typedef String (*XtLanguageProc)
      Display display
      String language
      XtPointer client_data

display

  Passes the display.

language

  Passes the initial language value obtained from the command line or server per-display resource specifications.

client_data

  Passes the additional client data specified in the call to `XtSetLanguageProc`.

The language procedure allows an application to set the locale to the value of the language resource determined by . The function returns a new language string that will be subsequently used by to establish the path for loading resource files. The returned string will be copied by the Intrinsics into new memory.

Initially, no language procedure is set by the Intrinsics. To set the language procedure for use by , use `XtSetLanguageProc`.

      XtLanguageProc XtSetLanguageProc
      XtAppContext app_context
      XtLanguageProc proc
      XtPointer client_data

app_context

  Specifies the application context in which the language procedure is to be used, or NULL.

proc

  Specifies the language procedure.

client_data

  Specifies additional client data to be passed to the language procedure when it is called.

`XtSetLanguageProc` sets the language procedure that will be called from for all subsequent Displays initialized in the specified application context. If app_context is NULL, the specified language procedure is registered in all application contexts created by the calling process, including any future application contexts that may be created. If proc is NULL, a default language procedure is registered. `XtSetLanguageProc` returns the previously registered language procedure. If a language procedure has not yet been registered, the return value is unspecified, but if this return value is used in a subsequent call to `XtSetLanguageProc`, it will cause the default language procedure to be registered.

The default language procedure does the following:

- Sets the locale according to the environment. On ANSI C-based systems this is done by calling `setlocale`( `LC_ALL`, language ). If an error is encountered, a warning message is issued with .

- Calls `XSupportsLocale` to verify that the current locale is supported. If the locale is not supported, a warning message is issued with and the locale is set to ``C''.

- Calls `XSetLocaleModifiers` specifying the empty string.

- Returns the value of the current locale. On ANSI C-based systems this is the return value from a final call to `setlocale`( `LC_ALL`, NULL ).

A client wishing to use this mechanism to establish locale can do so by calling `XtSetLanguageProc` prior to , as in the following example.

    	Widget top;
    	XtSetLanguageProc(NULL, NULL, NULL);
    	top = XtOpenApplication(...);
    	...

## Loading the Resource Database

The function first determines the language string to be used for the specified display. It then creates a resource database for the default screen of the display by combining the following sources in order, with the entries in the first named source having highest precedence:

- Application command line (argc, argv).

- Per-host user environment resource file on the local host.

- Per-screen resource specifications from the server.

- Per-display resource specifications from the server or from the user preference file on the local host.

- Application-specific user resource file on the local host.

- Application-specific class resource file on the local host.

When the resource database for a particular screen on the display is needed (either internally, or when is called), it is created in the following manner using the sources listed above in the same order:

- A temporary database, the ``server resource database'', is created from the string returned by `XResourceManagerString` or, if `XResourceManagerString` returns NULL, the contents of a resource file in the user's home directory. On POSIX-based systems, the usual name for this user preference resource file is $HOME/`.Xdefaults`.

- If a language procedure has been set, first searches the command line for the option ``-xnlLanguage'', or for a -xrm option that specifies the xnlLanguage/XnlLanguage resource, as specified by Section 2.4. If such a resource is found, the value is assumed to be entirely in XPCS, the X Portable Character Set. If neither option is specified on the command line, queries the server resource database (which is assumed to be entirely in XPCS) for the resource name`.xnlLanguage`, class Class`.XnlLanguage` where name and Class are the application_name and application_class specified to . The language procedure is then invoked with the resource value if found, else the empty string. The string returned from the language procedure is saved for all future references in the Intrinsics that require the per-display language string.

- The screen resource database is initialized by parsing the command line in the manner specified by Section 2.4.

- If a language procedure has not been set, the initial database is then queried for the resource name`.xnlLanguage`, class Class`.XnlLanguage` as specified above. If this database query fails, the server resource database is queried; if this query also fails, the language is determined from the environment; on POSIX-based systems, this is done by retrieving the value of the LANG environment variable. If no language string is found, the empty string is used. This language string is saved for all future references in the Intrinsics that require the per-display language string.

- After determining the language string, the user's environment resource file is then merged into the initial resource database if the file exists. This file is user-, host-, and process-specific and is expected to contain user preferences that are to override those specifications in the per-display and per-screen resources. On POSIX-based systems, the user's environment resource file name is specified by the value of the XENVIRONMENT environment variable. If this environment variable does not exist, the user's home directory is searched for a file named `.Xdefaults-`host, where host is the host name of the machine on which the application is running.

- The per-screen resource specifications are then merged into the screen resource database, if they exist. These specifications are the string returned by `XScreenResourceString` for the respective screen and are owned entirely by the user.

- Next, the server resource database created earlier is merged into the screen resource database. The server property, and corresponding user preference file, are owned and constructed entirely by the user.

- The application-specific user resource file from the local host is then merged into the screen resource database. This file contains user customizations and is stored in a directory owned by the user. Either the user or the application or both can store resource specifications in the file. Each should be prepared to find and respect entries made by the other. The file name is found by calling `XrmSetDatabase` with the current screen resource database, after preserving the original display-associated database, then calling with the parameters (display, NULL, NULL, NULL, path, NULL, 0, NULL), where path is defined in an operating-system-specific way. On POSIX-based systems, path is defined to be the value of the environment variable XUSERFILESEARCHPATH if this is defined. If XUSERFILESEARCHPATH is not defined, an implementation-dependent default value is used. This default value is constrained in the following manner:

- - If the environment variable XAPPLRESDIR is not defined, the default XUSERFILESEARCHPATH must contain at least six entries. These entries must contain $HOME as the directory prefix, plus the following substitutions:

              1.	%C, %N, %L	or	%C, %N, %l, %t, %c
              2.	%C, %N, %l
              3.	%C, %N
              4.	%N, %L	or	%N, %l, %t, %c
              5.	%N, %l
              6.	%N

    The order of these six entries within the path must be as given above. The order and use of substitutions within a given entry are implementation-dependent.

  - If XAPPLRESDIR is defined, the default XUSERFILESEARCHPATH must contain at least seven entries. These entries must contain the following directory prefixes and substitutions:

              1.	$XAPPLRESDIR	with	%C, %N, %L	or	%C, %N, %l, %t, %c
              2.	$XAPPLRESDIR	with	%C, %N, %l
              3.	$XAPPLRESDIR	with	%C, %N
              4.	$XAPPLRESDIR	with	%N, %L	or	%N, %l, %t, %c
              5.	$XAPPLRESDIR	with	%N, %l
              6.	$XAPPLRESDIR	with	%N
              7.	$HOME	with	%N

    The order of these seven entries within the path must be as given above. The order and use of substitutions within a given entry are implementation-dependent.

- Last, the application-specific class resource file from the local host is merged into the screen resource database. This file is owned by the application and is usually installed in a system directory when the application is installed. It may contain sitewide customizations specified by the system manager. The name of the application class resource file is found by calling with the parameters (display, ``app-defaults'', NULL, NULL, NULL, NULL, 0, NULL). This file is expected to be provided by the developer of the application and may be required for the application to function properly. A simple application that wants to be assured of having a minimal set of resources in the absence of its class resource file can declare fallback resource specifications with . Note that the customization substitution string is retrieved dynamically by so that the resolved file name of the application class resource file can be affected by any of the earlier sources for the screen resource database, even though the contents of the class resource file have lowest precedence. After calling , the original display-associated database is restored.

To obtain the resource database for a particular screen, use .

      XrmDatabase XtScreenDatabase
          Screen * screen

screen

  Specifies the screen whose resource database is to be returned.

The function returns the fully merged resource database as specified above, associated with the specified screen. If the specified screen does not belong to a `Display` initialized by , the results are undefined.

To obtain the default resource database associated with a particular display, use .

      XrmDatabase XtDatabase
          Display * display

display

  Specifies the display.

The function is equivalent to `XrmGetDatabase`. It returns the database associated with the specified display, or NULL if a database has not been set.

To specify a default set of resource values that will be used to initialize the resource database if no application-specific class resource file is found (the last of the six sources listed above), use .

      void XtAppSetFallbackResources
          XtAppContext * app_context
          String * specification_list

app_context

  Specifies the application context in which the fallback specifications will be used.

specification_list

  Specifies a NULL-terminated list of resource specifications to preload the database, or NULL.

Each entry in specification_list points to a string in the format of `XrmPutLineResource`. Following a call to , when a resource database is being created for a particular screen and the Intrinsics are not able to find or read an application-specific class resource file according to the rules given above and if specification_list is not NULL, the resource specifications in specification_list will be merged into the screen resource database in place of the application-specific class resource file. is not required to copy specification_list; the caller must ensure that the contents of the list and of the strings addressed by the list remain valid until all displays are initialized or until is called again. The value NULL for specification_list removes any previous fallback resource specification for the application context. The intended use for fallback resources is to provide a minimal number of resources that will make the application usable (or at least terminate with helpful diagnostic messages) when some problem exists in finding and loading the application defaults file.

## Parsing the Command Line

The function first parses the command line for the following options:

-display

  Specifies the display name for `XOpenDisplay`.

-name

  Sets the resource name prefix, which overrides the application name passed to .

-xnllanguage

  Specifies the initial language string for establishing locale and for finding application class resource files.

has a table of standard command line options that are passed to `XrmParseCommand` for adding resources to the resource database, and it takes as a parameter additional application-specific resource abbreviations. The format of this table is described in Section 15.9 in Xlib — C Language X Interface.

    typedef enum {
            XrmoptionNoArg,	/* Value is specified in OptionDescRec.value */
            XrmoptionIsArg,	/* Value is the option string itself */
            XrmoptionStickyArg,	/* Value is characters immediately following option */
            XrmoptionSepArg,	/* Value is next argument in argv */
            XrmoptionResArg,	/* Use the next argument as input to XrmPutLineResource*/
            XrmoptionSkipArg,	/* Ignore this option and the next argument in argv */
            XrmoptionSkipNArgs,	/* Ignore this option and the next */
                                    /* OptionDescRec.value arguments in argv */
            XrmoptionSkipLine	/* Ignore this option and the rest of argv */
    } XrmOptionKind;
    typedef struct {
            char *option;	/* Option name in argv */
            char *specifier;	/* Resource name (without application name) */
            XrmOptionKind argKind;	/* Location of the resource value */
            XPointer value;	/* Value to provide if XrmoptionNoArg */
    } XrmOptionDescRec, *XrmOptionDescList;

The standard table contains the following entries:

Option String | Resource Name | Argument Kind | Resource Value
--- | --- | --- | ---
−background | *background | SepArg | next argument
−bd | *borderColor | SepArg | next argument
−bg | *background | SepArg | next argument
−borderwidth | .borderWidth | SepArg | next argument
−bordercolor | *borderColor | SepArg | next argument
−bw | .borderWidth | SepArg | next argument
−display | .display | SepArg | next argument
−fg | *foreground | SepArg | next argument
−fn | *font | SepArg | next argument
−font | *font | SepArg | next argument
−foreground | *foreground | SepArg | next argument
−geometry | .geometry | SepArg | next argument
−iconic | .iconic | NoArg | "true"
−name | .name | SepArg | next argument
−reverse | .reverseVideo | NoArg | "on"
−rv | .reverseVideo | NoArg | "on"
+rv | .reverseVideo | NoArg | "off"
−selectionTimeout | .selectionTimeout | SepArg | next argument
−synchronous | .synchronous | NoArg | "on"
+synchronous | .synchronous | NoArg | "off"
−title | .title | SepArg | next argument
−xnllanguage | .xnlLanguage | SepArg | next argument
−xrm | next argument | ResArg | next argument
−xtsessionID | .sessionID | SepArg | next argument

Note that any unique abbreviation for an option name in the standard table or in the application table is accepted.

If reverseVideo is `True`, the values of `XtDefaultForeground` and `XtDefaultBackground` are exchanged for all screens on the Display.

The value of the synchronous resource specifies whether or not Xlib is put into synchronous mode. If a value is found in the resource database during display initialization, makes a call to `XSynchronize` for all display connections currently open in the application context. Therefore, when multiple displays are initialized in the same application context, the most recent value specified for the synchronous resource is used for all displays in the application context.

The value of the selectionTimeout resource applies to all displays opened in the same application context. When multiple displays are initialized in the same application context, the most recent value specified is used for all displays in the application context.

The -xrm option provides a method of setting any resource in an application. The next argument should be a quoted string identical in format to a line in the user resource file. For example, to give a red background to all command buttons in an application named `xmh`, you can start it up as

    xmh -xrm 'xmh*Command.background: red'

When it parses the command line, merges the application option table with the standard option table before calling the Xlib `XrmParseCommand` function. An entry in the application table with the same name as an entry in the standard table overrides the standard table entry. If an option name is a prefix of another option name, both names are kept in the merged table. The Intrinsics reserve all option names beginning with the characters ``-xt'' for future standard uses.

## Creating Widgets

The creation of widget instances is a three-phase process:

1. The widgets are allocated and initialized with resources and are optionally added to the managed subset of their parent.

2. All composite widgets are notified of their managed children in a bottom-up traversal of the widget tree.

3. The widgets create X windows, which then are mapped.

To start the first phase, the application calls for all its widgets and adds some (usually, most or all) of its widgets to their respective parents' managed set by calling . To avoid an O(n2) creation process where each composite widget lays itself out each time a widget is created and managed, parent widgets are not notified of changes in their managed set during this phase.

After all widgets have been created, the application calls with the top-level widget to execute the second and third phases. first recursively traverses the widget tree in a postorder (bottom-up) traversal and then notifies each composite widget with one or more managed children by means of its change_managed procedure.

Notifying a parent about its managed set involves geometry layout and possibly geometry negotiation. A parent deals with constraints on its size imposed from above (for example, when a user specifies the application window size) and suggestions made from below (for example, when a primitive child computes its preferred size). One difference between the two can cause geometry changes to ripple in both directions through the widget tree. The parent may force some of its children to change size and position and may issue geometry requests to its own parent in order to better accommodate all its children. You cannot predict where anything will go on the screen until this process finishes.

Consequently, in the first and second phases, no X windows are actually created, because it is likely that they will get moved around after creation. This avoids unnecessary requests to the X server.

Finally, starts the third phase by making a preorder (top-down) traversal of the widget tree, allocates an X window to each widget by means of its realize procedure, and finally maps the widgets that are managed.

### Creating and Merging Argument Lists

Many Intrinsics functions may be passed pairs of resource names and values. These are passed as an arglist, a pointer to an array of `Arg` structures, which contains

    typedef struct {
    	String name;
    	XtArgVal value;
    } Arg, *ArgList;

where `XtArgVal` is as defined in Section 1.5.

If the size of the resource is less than or equal to the size of an `XtArgVal`, the resource value is stored directly in value; otherwise, a pointer to it is stored in value.

To set values in an `ArgList`, use .

      void XtSetArg
      Arg arg
      String name
      XtArgVal value

arg

  Specifies the name/value pair to set.

name

  Specifies the name of the resource.

value

  Specifies the value of the resource if it will fit in an `XtArgVal`, else the address.

The function is usually used in a highly stylized manner to minimize the probability of making a mistake; for example:

    Arg args[20];
    int n;
    n = 0;
    XtSetArg(args[n], XtNheight, 100);	n++;
    XtSetArg(args[n], XtNwidth, 200);	n++;
    XtSetValues(widget, args, n);

Alternatively, an application can statically declare the argument list and use :

    static Args args[] = {
    	{XtNheight, (XtArgVal) 100},
    	{XtNwidth, (XtArgVal) 200},
    };
    XtSetValues(Widget, args, XtNumber(args));

Note that you should not use expressions with side effects such as auto-increment or auto-decrement within the first argument to . can be implemented as a macro that evaluates the first argument twice.

To merge two arglist arrays, use .

      ArgList XtMergeArgLists
         ArgList args1
         Cardinal num_args1
         ArgList args2
         Cardinal num_args2

args1

  Specifies the first argument list.

num_args1

  Specifies the number of entries in the first argument list.

args2

  Specifies the second argument list.

num_args2

  Specifies the number of entries in the second argument list.

The function allocates enough storage to hold the combined arglist arrays and copies them into it. Note that it does not check for duplicate entries. The length of the returned list is the sum of the lengths of the specified lists. When it is no longer needed, free the returned storage by using .

All Intrinsics interfaces that require `ArgList` arguments have analogs conforming to the ANSI C variable argument list (traditionally called ``varargs'') calling convention. The name of the analog is formed by prefixing ``Va'' to the name of the corresponding `ArgList` procedure; e.g., . Each procedure named `XtVa` something takes as its last arguments, in place of the corresponding `ArgList`/ `Cardinal` parameters, a variable parameter list of resource name and value pairs where each name is of type `String` and each value is of type `XtArgVal`. The end of the list is identified by a name entry containing NULL. Developers writing in the C language wishing to pass resource name and value pairs to any of these interfaces may use the `ArgList` and varargs forms interchangeably.

Two special names are defined for use only in varargs lists: `XtVaTypedArg` and `XtVaNestedList`.

    #define XtVaTypedArg "XtVaTypedArg"

If the name `XtVaTypedArg` is specified in place of a resource name, then the following four arguments are interpreted as a name/type/value/size tuple where name is of type `String`, type is of type `String`, value is of type `XtArgVal`, and size is of type int. When a varargs list containing `XtVaTypedArg` is processed, a resource type conversion (see ) is performed if necessary to convert the value into the format required by the associated resource. If type is XtRString, then value contains a pointer to the string and size contains the number of bytes allocated, including the trailing null byte. If type is not XtRString, then if size is less than or equal to `sizeof`(`XtArgVal`), the value should be the data cast to the type `XtArgVal`, otherwise value is a pointer to the data. If the type conversion fails for any reason, a warning message is issued and the list entry is skipped.

    #define XtVaNestedList  "XtVaNestedList"

If the name `XtVaNestedList` is specified in place of a resource name, then the following argument is interpreted as an `XtVarArgsList` value, which specifies another varargs list that is logically inserted into the original list at the point of declaration. The end of the nested list is identified with a name entry containing NULL. Varargs lists may nest to any depth.

To dynamically allocate a varargs list for use with `XtVaNestedList` in multiple calls, use .

    typedef XtPointer XtVarArgsList;

      XtVarArgsList XtVaCreateArgsList
         XtPointer unused
          ...

unused

  This argument is not currently used and must be specified as NULL.

...

  Specifies a variable parameter list of resource name and value pairs.

The function allocates memory and copies its arguments into a single list pointer, which may be used with `XtVaNestedList`. The end of both lists is identified by a name entry containing NULL. Any entries of type `XtVaTypedArg` are copied as specified without applying conversions. Data passed by reference (including Strings) are not copied, only the pointers themselves; the caller must ensure that the data remain valid for the lifetime of the created varargs list. The list should be freed using when no longer needed.

Use of resource files and of the resource database is generally encouraged over lengthy arglist or varargs lists whenever possible in order to permit modification without recompilation.

### Creating a Widget Instance

To create an instance of a widget, use .

      Widget XtCreateWidget
          String name
          WidgetClass object_class
          Widget parent
          ArgList args
          Cardinal num_args

name

  Specifies the resource instance name for the created widget, which is used for retrieving resources and, for that reason, should not be the same as any other widget that is a child of the same parent.

object_class

  Specifies the widget class pointer for the created object. Must be objectClass or any subclass thereof.

parent

  Specifies the parent widget. Must be of class Object or any subclass thereof.

args

  Specifies the argument list to override any other resource specifications.

num_args

  Specifies the number of entries in the argument list.

The function performs all the boilerplate operations of widget creation, doing the following in order:

- Checks to see if the class_initialize procedure has been called for this class and for all superclasses and, if not, calls those necessary in a superclass-to-subclass order.

- If the specified class is not `coreWidgetClass` or a subclass thereof, and the parent's class is a subclass of `compositeWidgetClass` and either no extension record in the parent's composite class part extension field exists with the record_type NULLQUARK or the accepts_objects field in the extension record is `False`, issues a fatal error; see and .

- If the specified class contains an extension record in the object class part extension field with record_type NULLQUARK and the allocate field is not NULL, the procedure is invoked to allocate memory for the widget instance. If the parent is a member of the class `constraintWidgetClass`, the procedure also allocates memory for the parent's constraints and stores the address of this memory into the constraints field. If no allocate procedure is found, the Intrinsics allocate memory for the widget and, when applicable, the constraints, and initializes the constraints field.

- Initializes the Core nonresource data fields self, parent, widget_class, being_destroyed, name, managed, window, visible, popup_list, and num_popups.

- Initializes the resource fields (for example, background_pixel) by using the `CoreClassPart` resource lists specified for this class and all superclasses.

- If the parent is a member of the class `constraintWidgetClass`, initializes the resource fields of the constraints record by using the `ConstraintClassPart` resource lists specified for the parent's class and all superclasses up to `constraintWidgetClass`.

- Calls the initialize procedures for the widget starting at the Object initialize procedure on down to the widget's initialize procedure.

- If the parent is a member of the class `constraintWidgetClass`, calls the `ConstraintClassPart` initialize procedures, starting at `constraintWidgetClass` on down to the parent's `ConstraintClassPart` initialize procedure.

- If the parent is a member of the class `compositeWidgetClass`, puts the widget into its parent's children list by calling its parent's insert_child procedure. For further information, see .

To create an instance of a widget using varargs lists, use .

      Widget XtVaCreateWidget
          String name
          WidgetClass object_class
          Widget parent
           ...

name

  Specifies the resource name for the created widget.

object_class

  Specifies the widget class pointer for the created object. Must be objectClass or any subclass thereof.

parent

  Specifies the parent widget. Must be of class Object or any subclass thereof.

...

  Specifies the variable argument list to override any other resource specifications.

The procedure is identical in function to with the args and num_args parameters replaced by a varargs list, as described in Section 2.5.1.

### Creating an Application Shell Instance

An application can have multiple top-level widgets, each of which specifies a unique widget tree that can potentially be on different screens or displays. An application uses to create independent widget trees.

      Widget XtAppCreateShell
          String name
          String application_class
          WidgetClass widget_class
          Display * display
          ArgList args
          Cardinal num_args

name

  Specifies the instance name of the shell widget. If name is NULL, the application name passed to is used.

application_class

  Specifies the resource class string to be used in place of the widget class_name string when widget_class is `applicationShellWidgetClass` or a subclass thereof.

widget_class

  Specifies the widget class for the top-level widget (e.g., `applicationShellWidgetClass ).`

display

  Specifies the display for the default screen and for the resource database used to retrieve the shell widget resources.

args

  Specifies the argument list to override any other resource specifications.

num_args

  Specifies the number of entries in the argument list.

The function creates a new shell widget instance as the root of a widget tree. The screen resource for this widget is determined by first scanning args for the XtNscreen argument. If no XtNscreen argument is found, the resource database associated with the default screen of the specified display is queried for the resource name.screen, class Class.Screen where Class is the specified application_class if widget_class is `applicationShellWidgetClass` or a subclass thereof. If widget_class is not `application\%Shell\%Widget\%Class` or a subclass, Class is the class_name field from the `CoreClassPart` of the specified widget_class. If this query fails, the default screen of the specified display is used. Once the screen is determined, the resource database associated with that screen is used to retrieve all remaining resources for the shell widget not specified in args. The widget name and Class as determined above are used as the leftmost (i.e., root) components in all fully qualified resource names for objects within this widget tree.

If the specified widget class is a subclass of WMShell, the name and Class as determined above will be stored into the WM_CLASS property on the widget's window when it becomes realized. If the specified widget_class is `applicationShellWidgetClass` or a subclass thereof, the WM_COMMAND property will also be set from the values of the XtNargv and XtNargc resources.

To create multiple top-level shells within a single (logical) application, you can use one of two methods:

- Designate one shell as the real top-level shell and create the others as pop-up children of it by using .

- Have all shells as pop-up children of an unrealized top-level shell.

The first method, which is best used when there is a clear choice for what is the main window, leads to resource specifications like the following:

    xmail.geometry:...	(the main window)
    xmail.read.geometry:...	(the read window)
    xmail.compose.geometry:...	(the compose window)

The second method, which is best if there is no main window, leads to resource specifications like the following:

    xmail.headers.geometry:...	(the headers window)
    xmail.read.geometry:...	(the read window)
    xmail.compose.geometry:...	(the compose window)

To create a top-level widget that is the root of a widget tree using varargs lists, use .

      Widget XtVaAppCreateShell
          String name
          String application_class
          WidgetClass widget_class
          Display * display

name

  Specifies the instance name of the shell widget. If name is NULL, the application name passed to is used.

application_class

  Specifies the resource class string to be used in place of the widget class_name string when widget_class is `applicationShellWidgetClass` or a subclass thereof.

widget_class

  Specifies the widget class for the top-level widget.

display

  Specifies the display for the default screen and for the resource database used to retrieve the shell widget resources.

...

  Specifies the variable argument list to override any other resource specifications.

The procedure is identical in function to with the args and num_args parameters replaced by a varargs list, as described in Section 2.5.1.

### Convenience Procedure to Initialize an Application

To initialize the Intrinsics internals, create an application context, open and initialize a display, and create the initial root shell instance, an application may use or .

      Widget XtOpenApplication
          XtAppContext * app_context_return
          String application_class
          XrmOptionDescList options
          Cardinal num_options
          int * argc_in_out
          String * argv_in_out
          String * fallback_resources
          WidgetClass widget_class
          ArgList args
          Cardinal num_args

app_context_return

  Returns the application context, if non-NULL.

application_class

  Specifies the class name of the application.

options

  Specifies the command line options table.

num_options

  Specifies the number of entries in options.

argc_in_out

  Specifies a pointer to the number of command line arguments.

argv_in_out

  Specifies a pointer to the command line arguments.

fallback_resources

  Specifies resource values to be used if the application class resource file cannot be opened or read, or NULL.

widget_class

  Specifies the class of the widget to be created. Must be shellWidgetClass or a subclass.

args

  Specifies the argument list to override any other resource specifications for the created shell widget.

num_args

  Specifies the number of entries in the argument list.

The function calls followed by , then calls with display_string NULL and application_name NULL, and finally calls with name NULL, the specified widget_class, an argument list and count, and returns the created shell. The recommended widget_class is `sessionShellWidgetClass`. The argument list and count are created by merging the specified args and num_args with a list containing the specified argc and argv. The modified argc and argv returned by are returned in argc_in_out and argv_in_out. If app_context_return is not NULL, the created application context is also returned. If the display specified by the command line cannot be opened, an error message is issued and terminates the application. If fallback_resources is non-NULL, is called with the value prior to calling .

      Widget XtVaOpenApplication
          XtAppContext * app_context_return
          String application_class
          XrmOptionDescList options
          Cardinal num_options
          int * argc_in_out
          String * argv_in_out
          String * fallback_resources
          WidgetClass widget_class

app_context_return

  Returns the application context, if non-NULL.

application_class

  Specifies the class name of the application.

options

  Specifies the command line options table.

num_options

  Specifies the number of entries in options.

argc_in_out

  Specifies a pointer to the number of command line arguments.

argv_in_out

  Specifies the command line arguments array.

fallback_resources

  Specifies resource values to be used if the application class resource file cannot be opened, or NULL.

widget_class

  Specifies the class of the widget to be created. Must be shellWidgetClass or a subclass.

...

  Specifies the variable argument list to override any other resource specifications for the created shell.

The procedure is identical in function to with the args and num_args parameters replaced by a varargs list, as described in Section 2.5.1.

### Widget Instance Allocation: The allocate Procedure

A widget class may optionally provide an instance allocation procedure in the `ObjectClassExtension` record.

When the call to create a widget includes a varargs list containing `XtVaTypedArg`, these arguments will be passed to the allocation procedure in an `XtTypedArgList`.

    typedef struct {
    	String name;
    	String type;
    	XtArgVal value;
    	int size;
    } XtTypedArg, *XtTypedArgList;

The allocate procedure pointer in the `ObjectClassExtension` record is of type .

      typedef void (*AllocateProc)
          WidgetClass widget_class
          Cardinal* constraint_size
          Cardinal* more_bytes
          ArgList args
          Cardinal* num_args
          XtTypedArgList typed_args
          Cardinal* num_typed_args
          Widget* new_return
          XtPointer* more_bytes_return

widget_class

  Specifies the widget class of the instance to allocate.

constraint_size

  Specifies the size of the constraint record to allocate, or 0.

more_bytes

  Specifies the number of auxiliary bytes of memory to allocate.

args

  Specifies the argument list as given in the call to create the widget.

num_args

  Specifies the number of arguments.

typed_args

  Specifies the list of typed arguments given in the call to create the widget.

num_typed_args

  Specifies the number of typed arguments.

new_return

  Returns a pointer to the newly allocated instance, or NULL in case of error.

more_bytes_return

  Returns the auxiliary memory if it was requested, or NULL if requested and an error occurred; otherwise, unchanged.

At widget allocation time, if an extension record with record_type equal to NULLQUARK is located through the object class part extension field and the allocate field is not NULL, the will be invoked to allocate memory for the widget. If no ObjectClassPart extension record is declared with record_type equal to NULLQUARK, then `XtInheritAllocate` and `XtInheritDeallocate` are assumed. If no is found, the Intrinsics will allocate memory for the widget.

An must perform the following:

- Allocate memory for the widget instance and return it in new_return. The memory must be at least wc->core_class.widget_size bytes in length, double-word aligned.

- Initialize the core.constraints field in the instance record to NULL or to point to a constraint record. If constraint_size is not 0, the procedure must allocate memory for the constraint record. The memory must be double-word aligned.

- If more_bytes is not 0, then the address of a block of memory at least more_bytes in size, double-word aligned, must be returned in the more_bytes_return parameter, or NULL to indicate an error.

A class allocation procedure that envelops the allocation procedure of a superclass must rely on the enveloped procedure to perform the instance and constraint allocation. Allocation procedures should refrain from initializing fields in the widget record except to store pointers to newly allocated additional memory. Under no circumstances should an allocation procedure that envelopes its superclass allocation procedure modify fields in the instance part of any superclass.

### Widget Instance Initialization: The initialize Procedure

The initialize procedure pointer in a widget class is of type .

      typedef void (*XtInitProc)
      Widget request
      Widget new
      ArgList args
      Cardinal * num_args

request

  Specifies a copy of the widget with resource values as requested by the argument list, the resource database, and the widget defaults.

new

  Specifies the widget with the new values, both resource and nonresource, that are actually allowed.

args

  Specifies the argument list passed by the client, for computing derived resource values. If the client created the widget using a varargs form, any resources specified via `XtVaTypedArg` are converted to the widget representation and the list is transformed into the `ArgList` format.

num_args

  Specifies the number of entries in the argument list.

An initialization procedure performs the following:

- Allocates space for and copies any resources referenced by address that the client is allowed to free or modify after the widget has been created. For example, if a widget has a field that is a `String`, it may choose not to depend on the characters at that address remaining constant but dynamically allocate space for the string and copy it to the new space. Widgets that do not copy one or more resources referenced by address should clearly so state in their user documentation.

  It is not necessary to allocate space for or to copy callback lists.

- Computes values for unspecified resource fields. For example, if width and height are zero, the widget should compute an appropriate width and height based on its other resources.

  A widget may directly assign only its own width and height within the initialize, initialize_hook, set_values, and set_values_hook procedures; see .

- Computes values for uninitialized nonresource fields that are derived from resource fields. For example, graphics contexts (GCs) that the widget uses are derived from resources like background, foreground, and font.

An initialization procedure also can check certain fields for internal consistency. For example, it makes no sense to specify a colormap for a depth that does not support that colormap.

Initialization procedures are called in superclass-to-subclass order after all fields specified in the resource lists have been initialized. The initialize procedure does not need to examine args and num_args if all public resources are declared in the resource list. Most of the initialization code for a specific widget class deals with fields defined in that class and not with fields defined in its superclasses.

If a subclass does not need an initialization procedure because it does not need to perform any of the above operations, it can specify NULL for the initialize field in the class record.

Sometimes a subclass may want to overwrite values filled in by its superclass. In particular, size calculations of a superclass often are incorrect for a subclass, and in this case, the subclass must modify or recalculate fields declared and computed by its superclass.

As an example, a subclass can visually surround its superclass display. In this case, the width and height calculated by the superclass initialize procedure are too small and need to be incremented by the size of the surround. The subclass needs to know if its superclass's size was calculated by the superclass or was specified explicitly. All widgets must place themselves into whatever size is explicitly given, but they should compute a reasonable size if no size is requested.

The request and new arguments provide the necessary information for a subclass to determine the difference between an explicitly specified field and a field computed by a superclass. The request widget is a copy of the widget as initialized by the arglist and resource database. The new widget starts with the values in the request, but it has been updated by all superclass initialization procedures called so far. A subclass initialize procedure can compare these two to resolve any potential conflicts.

In the above example, the subclass with the visual surround can see if the width and height in the request widget are zero. If so, it adds its surround size to the width and height fields in the new widget. If not, it must make do with the size originally specified.

The new widget will become the actual widget instance record. Therefore, the initialization procedure should do all its work on the new widget; the request widget should never be modified. If the initialize procedure needs to call any routines that operate on a widget, it should specify new as the widget instance.

### Constraint Instance Initialization: The ConstraintClassPart initialize Procedure

The constraint initialization procedure pointer, found in the `ConstraintClassPart` initialize field of the widget class record, is of type . The values passed to the parent constraint initialization procedures are the same as those passed to the child's class widget initialization procedures.

The constraints field of the request widget points to a copy of the constraints record as initialized by the arglist and resource database.

The constraint initialization procedure should compute any constraint fields derived from constraint resources. It can make further changes to the new widget to make the widget and any other constraint fields conform to the specified constraints, for example, changing the widget's size or position.

If a constraint class does not need a constraint initialization procedure, it can specify NULL for the initialize field of the `ConstraintClassPart` in the class record.

### Nonwidget Data Initialization: The initialize_hook Procedure

The initialize_hook procedure is obsolete, as the same information is now available to the initialize procedure. The procedure has been retained for those widgets that used it in previous releases.

The initialize_hook procedure pointer is of type :

      typedef void(*XtArgsProc)
      Widget w
      ArgList args
      Cardinal * num_args

w

  Specifies the widget.

args

  Specifies the argument list passed by the client. If the client created the widget using a varargs form, any resources specified via `XtVaTypedArg` are converted to the widget representation and the list is transformed into the `ArgList` format.

num_args

  Specifies the number of entries in the argument list.

If this procedure is not NULL, it is called immediately after the corresponding initialize procedure or in its place if the initialize field is NULL.

The initialize_hook procedure allows a widget instance to initialize nonresource data using information from the specified argument list as if it were a resource.

## Realizing Widgets

To realize a widget instance, use .

      void XtRealizeWidget
      Widget w

w

  Specifies the widget. Must be of class Core or any subclass thereof.

If the widget is already realized, simply returns. Otherwise it performs the following:

- Binds all action names in the widget's translation table to procedures (see ).

- Makes a postorder traversal of the widget tree rooted at the specified widget and calls each non-NULL change_managed procedure of all composite widgets that have one or more managed children.

- Constructs an `XSetWindowAttributes` structure filled in with information derived from the Core widget fields and calls the realize procedure for the widget, which adds any widget-specific attributes and creates the X window.

- If the widget is not a subclass of `compositeWidgetClass`, returns; otherwise it continues and performs the following:

- - Descends recursively to each of the widget's managed children and calls the realize procedures. Primitive widgets that instantiate children are responsible for realizing those children themselves.

  - Maps all of the managed children windows that have mapped_when_managed `True`. If a widget is managed but mapped_when_managed is `False`, the widget is allocated visual space but is not displayed.

If the widget is a top-level shell widget (that is, it has no parent), and mapped_when_managed is `True`, maps the widget window.

, , , , `XtUnmanage\%Children`, , , and `XtDestroy\%Widget` maintain the following invariants:

- If a composite widget is realized, then all its managed children are realized.

- If a composite widget is realized, then all its managed children that have mapped_when_managed `True` are mapped.

All Intrinsics functions and all widget routines should accept either realized or unrealized widgets. When calling the realize or change_managed procedures for children of a composite widget, calls the procedures in reverse order of appearance in the `CompositePart` children list. By default, this ordering of the realize procedures will result in the stacking order of any newly created subwindows being top-to-bottom in the order of appearance on the list, and the most recently created child will be at the bottom.

To check whether or not a widget has been realized, use .

      Boolean XtIsRealized
      Widget w

w

  Specifies the widget. Must be of class Object or any subclass thereof.

The function returns `True` if the widget has been realized, that is, if the widget has a nonzero window ID. If the specified object is not a widget, the state of the nearest widget ancestor is returned.

Some widget procedures (for example, set_values) might wish to operate differently after the widget has been realized.

### Widget Instance Window Creation: The realize Procedure

The realize procedure pointer in a widget class is of type .

      typedef void (*XtRealizeProc)
      Widget w
      XtValueMask value_mask
      XSetWindowAttributes attributes

w

  Specifies the widget.

value_mask

  Specifies which fields in the attributes structure are used.

attributes

  Specifies the window attributes to use in the `XCreateWindow` call.

The realize procedure must create the widget's window.

Before calling the class realize procedure, the generic function fills in a mask and a corresponding `XSetWindowAttributes` structure. It sets the following fields in attributes and corresponding bits in value_mask based on information in the widget core structure:

- The background_pixmap (or background_pixel if background_pixmap is `XtUnspecifiedPixmap`) is filled in from the corresponding field.

- The border_pixmap (or border_pixel if border_pixmap is `XtUnspecifiedPixmap`) is filled in from the corresponding field.

- The colormap is filled in from the corresponding field.

- The event_mask is filled in based on the event handlers registered, the event translations specified, whether the expose field is non-NULL, and whether visible_interest is `True`.

- The bit_gravity is set to `NorthWestGravity` if the expose field is NULL.

These or any other fields in attributes and the corresponding bits in value_mask can be set by the realize procedure.

Note that because realize is not a chained operation, the widget class realize procedure must update the `XSetWindowAttributes` structure with all the appropriate fields from non-Core superclasses.

A widget class can inherit its realize procedure from its superclass during class initialization. The realize procedure defined for `coreWidgetClass` calls with the passed value_mask and attributes and with window_class and visual set to `CopyFromParent`. Both `compositeWidgetClass` and `constraintWidgetClass` inherit this realize procedure, and most new widget subclasses can do the same (see ).

The most common noninherited realize procedures set bit_gravity in the mask and attributes to the appropriate value and then create the window. For example, depending on its justification, Label might set bit_gravity to `WestGravity`, `CenterGravity`, or `EastGravity`. Consequently, shrinking it would just move the bits appropriately, and no exposure event is needed for repainting.

If a composite widget's children should be realized in an order other than that specified (to control the stacking order, for example), it should call on its children itself in the appropriate order from within its own realize procedure.

Widgets that have children and whose class is not a subclass of `compositeWidgetClass` are responsible for calling on their children, usually from within the realize procedure.

Realize procedures cannot manage or unmanage their descendants.

### Window Creation Convenience Routine

Rather than call the Xlib `XCreateWindow` function explicitly, a realize procedure should normally call the Intrinsics analog , which simplifies the creation of windows for widgets.

      void XtCreateWindow
      Widget w
      unsigned int window_class
      Visual * visual
      XtValueMask value_mask
      XSetWindowAttributes attributes

w

  Specifies the widget that defines the additional window attributed. Must be of class Core or any subclass thereof.

window_class

  Specifies the Xlib window class (for example, `InputOutput`, `InputOnly`, or `CopyFromParent ).`

visual

  Specifies the visual type (usually `CopyFromParent ).`

value_mask

  Specifies which fields in the attributes structure are used.

attributes

  Specifies the window attributes to use in the `XCreateWindow` call.

The function calls the Xlib `XCreateWindow` function with values from the widget structure and the passed parameters. Then, it assigns the created window to the widget's window field.

evaluates the following fields of the widget core structure: depth, screen, parent->core.window, x, y, width, height, and border_width.

## Obtaining Window Information from a Widget

The Core widget class definition contains the screen and window ids. The window field may be NULL for a while (see and ).

The display pointer, the parent widget, screen pointer, and window of a widget are available to the widget writer by means of macros and to the application writer by means of functions.

      Display XtDisplay
      Widget w

w

  Specifies the widget. Must be of class Core or any subclass thereof.

`XtDisplay` returns the display pointer for the specified widget.

      Widget XtParent
      Widget w

w

  Specifies the widget. Must be of class Object or any subclass thereof.

`XtParent` returns the parent object for the specified widget. The returned object will be of class Object or a subclass.

      Screen *XtScreen
      Widget w

w

  Specifies the widget. Must be of class Core or any subclass thereof.

returns the screen pointer for the specified widget.

      Window XtWindow
      Widget w

w

  Specifies the widget. Must be of class Core or any subclass thereof.

returns the window of the specified widget.

The display pointer, screen pointer, and window of a widget or of the closest widget ancestor of a nonwidget object are available by means of , , and .

      Display *XtDisplayOfObject
      Widget w

object

  Specifies the object. Must be of class Object or any subclass thereof.

is identical in function to `XtDisplay` if the object is a widget; otherwise returns the display pointer for the nearest ancestor of object that is of class Widget or a subclass thereof.

      Screen *XtScreenOfObject
      Widget object

object

  Specifies the object. Must be of class Object or any subclass thereof.

is identical in function to if the object is a widget; otherwise returns the screen pointer for the nearest ancestor of object that is of class Widget or a subclass thereof.

      Window XtWindowOfObject
      Widget object

object

  Specifies the object. Must be of class Object or any subclass thereof.

is identical in function to if the object is a widget; otherwise returns the window for the nearest ancestor of object that is of class Widget or a subclass thereof.

To retrieve the instance name of an object, use .

      String XtName
      Widget object

object

  Specifies the object whose name is desired. Must be of class Object or any subclass thereof.

returns a pointer to the instance name of the specified object. The storage is owned by the Intrinsics and must not be modified. The name is not qualified by the names of any of the object's ancestors.

Several window attributes are locally cached in the widget instance. Thus, they can be set by the resource manager and as well as used by routines that derive structures from these values (for example, depth for deriving pixmaps, background_pixel for deriving GCs, and so on) or in the call.

The x, y, width, height, and border_width window attributes are available to geometry managers. These fields are maintained synchronously inside the Intrinsics. When an `XConfigureWindow` is issued by the Intrinsics on the widget's window (on request of its parent), these values are updated immediately rather than some time later when the server generates a `ConfigureNotify` event. (In fact, most widgets do not select `SubstructureNotify` events.) This ensures that all geometry calculations are based on the internally consistent toolkit world rather than on either an inconsistent world updated by asynchronous `ConfigureNotify` events or a consistent, but slow, world in which geometry managers ask the server for window sizes whenever they need to lay out their managed children (see ).

### Unrealizing Widgets

To destroy the windows associated with a widget and its non-pop-up descendants, use .

      void XtUnrealizeWidget
      Widget w

w

  Specifies the widget. Must be of class Core or any subclass thereof.

If the widget is currently unrealized, simply returns. Otherwise it performs the following:

- Unmanages the widget if the widget is managed.

- Makes a postorder (child-to-parent) traversal of the widget tree rooted at the specified widget and, for each widget that has declared a callback list resource named ``unrealizeCallback'', executes the procedures on the XtNunrealizeCallback list.

- Destroys the widget's window and any subwindows by calling `XDestroyWindow` with the specified widget's window field.

Any events in the queue or which arrive following a call to will be dispatched as if the window(s) of the unrealized widget(s) had never existed.

## Destroying Widgets

The Intrinsics provide support

- To destroy all the pop-up children of the widget being destroyed and destroy all children of composite widgets.

- To remove (and unmap) the widget from its parent.

- To call the callback procedures that have been registered to trigger when the widget is destroyed.

- To minimize the number of things a widget has to deallocate when destroyed.

- To minimize the number of `XDestroyWindow` calls when destroying a widget tree.

To destroy a widget instance, use .

      void XtDestroyWidget
      Widget w

w

  Specifies the widget. Must be of class Object or any subclass thereof.

The function provides the only method of destroying a widget, including widgets that need to destroy themselves. It can be called at any time, including from an application callback routine of the widget being destroyed. This requires a two-phase destroy process in order to avoid dangling references to destroyed widgets.

In phase 1, performs the following:

- If the being_destroyed field of the widget is `True`, it returns immediately.

- Recursively descends the widget tree and sets the being_destroyed field to `True` for the widget and all normal and pop-up children.

- Adds the widget to a list of widgets (the destroy list) that should be destroyed when it is safe to do so.

Entries on the destroy list satisfy the invariant that if w2 occurs after w1 on the destroy list, then w2 is not a descendent, either normal or pop-up, of w1.

Phase 2 occurs when all procedures that should execute as a result of the current event have been called, including all procedures registered with the event and translation managers, that is, when the current invocation of is about to return, or immediately if not in .

In phase 2, performs the following on each entry in the destroy list in the order specified:

- If the widget is not a pop-up child and the widget's parent is a subclass of `composite\%WidgetClass`, and if the parent is not being destroyed, it calls on the widget and then calls the widget's parent's delete_child procedure (see ).

- Calls the destroy callback procedures registered on the widget and all normal and pop-up descendants in postorder (it calls child callbacks before parent callbacks).

The function then makes second traversal of the widget and all normal and pop-up descendants to perform the following three items on each widget in postorder:

- If the widget is not a pop-up child and the widget's parent is a subclass of `constraint\%WidgetClass`, it calls the `ConstraintClassPart` destroy procedure for the parent, then for the parent's superclass, until finally it calls the `ConstraintClassPart` destroy procedure for `constraintWidgetClass`.

- Calls the `CoreClassPart` destroy procedure declared in the widget class, then the destroy procedure declared in its superclass, until finally it calls the destroy procedure declared in the Object class record. Callback lists are deallocated.

- If the widget class object class part contains an `ObjectClassExtension` record with the record_type NULLQUARK and the deallocate field is not NULL, calls the deallocate procedure to deallocate the instance and if one exists, the constraint record. Otherwise, the Intrinsics will deallocate the widget instance record and if one exists, the constraint record.

- Calls `XDestroyWindow` if the specified widget is realized (that is, has an X window). The server recursively destroys all normal descendant windows. (Windows of realized pop-up Shell children, and their descendants, are destroyed by a shell class destroy procedure.)

### Adding and Removing Destroy Callbacks

When an application needs to perform additional processing during the destruction of a widget, it should register a destroy callback procedure for the widget. The destroy callback procedures use the mechanism described in . The destroy callback list is identified by the resource name XtNdestroyCallback.

For example, the following adds an application-supplied destroy callback procedure ClientDestroy with client data to a widget by calling .

    XtAddCallback(w, XtNdestroyCallback, ClientDestroy, client_data)

Similarly, the following removes the application-supplied destroy callback procedure ClientDestroy by calling .

    XtRemoveCallback(w, XtNdestroyCallback, ClientDestroy, client_data)

The ClientDestroy argument is of type ; see .

### Dynamic Data Deallocation: The destroy Procedure

The destroy procedure pointers in the `ObjectClassPart`, `RectObjClassPart`, and `CoreClassPart` structures are of type .

      typedef void XtWidgetProc
      Widget w

w

  Specifies the widget being destroyed.

The destroy procedures are called in subclass-to-superclass order. Therefore, a widget's destroy procedure should deallocate only storage that is specific to the subclass and should ignore the storage allocated by any of its superclasses. The destroy procedure should deallocate only resources that have been explicitly created by the subclass. Any resource that was obtained from the resource database or passed in an argument list was not created by the widget and therefore should not be destroyed by it. If a widget does not need to deallocate any storage, the destroy procedure entry in its class record can be NULL.

Deallocating storage includes, but is not limited to, the following steps:

- Calling on dynamic storage allocated with , , and so on.

- Calling `XFreePixmap` on pixmaps created with direct X calls.

- Calling on GCs allocated with .

- Calling `XFreeGC` on GCs allocated with direct X calls.

- Calling on event handlers added to other widgets.

- Calling on timers created with .

- Calling for each child if the widget has children and is not a subclass of `compositeWidgetClass`.

During destroy phase 2 for each widget, the Intrinsics remove the widget from the modal cascade, unregister all event handlers, remove all key, keyboard, button, and pointer grabs and remove all callback procedures registered on the widget. Any outstanding selection transfers will time out.

### Dynamic Constraint Data Deallocation: The ConstraintClassPart destroy Procedure

The constraint destroy procedure identified in the `ConstraintClassPart` `constraintWidgetClass`. This constraint destroy procedure pointer is of type . The constraint destroy procedures are called in subclass-to-superclass order, starting at the class of the widget's parent and ending at `constraint\%WidgetClass`. Therefore, a parent's constraint destroy procedure should deallocate only storage that is specific to the constraint subclass and not storage allocated by any of its superclasses.

If a parent does not need to deallocate any constraint storage, the constraint destroy procedure entry in its class record can be NULL.

### Widget Instance Deallocation: The deallocate Procedure

The deallocate procedure pointer in the `ObjectClassExtension` record is of type `XtDeallocateProc`.

      typedef void (*XtDeallocateProc)
      Widget widget
      XtPointer more_bytes

widget

  Specifies the widget being destroyed.

more_bytes

  Specifies the auxiliary memory received from the corresponding allocator along with the widget, or NULL.

When a widget is destroyed, if an `ObjectClassExtension` record exists in the object class part extension field with record_type NULLQUARK and the deallocate field is not NULL, the `XtDeallocateProc` will be called. If no ObjectClassPart extension record is declared with record_type equal to NULLQUARK, then `XtInheritAllocate` and `XtInheritDeallocate` are assumed. The responsibilities of the deallocate procedure are to deallocate the memory specified by more_bytes if it is not NULL, to deallocate the constraints record as specified by the widget's core.constraints field if it is not NULL, and to deallocate the widget instance itself.

If no `XtDeallocateProc` is found, it is assumed that the Intrinsics originally allocated the memory and is responsible for freeing it.

## Exiting from an Application

All X Toolkit applications should terminate by calling and then exiting using the standard method for their operating system (typically, by calling `exit` for POSIX-based systems). The quickest way to make the windows disappear while exiting is to call on each top-level shell widget. The Intrinsics have no resources beyond those in the program image, and the X server will free its resources when its connection to the application is broken.

Depending upon the widget set in use, it may be necessary to explicitly destroy individual widgets or widget trees with before calling in order to ensure that any required widget cleanup is properly executed. The application developer must refer to the widget documentation to learn if a widget needs to perform cleanup beyond that performed automatically by the operating system. If the client is a session participant (see ), then the client may wish to resign from the session before exiting. See for details.