Page:1234567891011

Chapter 2


Using Widgets

Widgets serve as the primary tools for building a user interface or application environment. The Athena widget set consists of primitive widgets that contain no children (for example, a command button) and composite widgets which may contain one or more widget children (for example, a Box widget).
The remaining chapters explain the widgets that are provided by the Athena widget set. These user-interface components serve as an interface for application programmers who do not want to implement their own widgets. In addition, they serve as a starting point for those widget programmers who, using the Intrinsics mechanisms, want to implement alternative application programming interfaces.
This chapter is a brief introduction to widget programming. The examples provided use the Athena widgets, though most of the concepts will apply to all widget sets. Although there are several programming interfaces to the X Toolkit, only one is described here. A full description of the programming interface is provided in the document X Toolkit Intrinsics-C Language Interface.

Home


2.1. Setting the Locale

If it is desirable that the application take advantage of internationalization (il8n), you must establish locale with XtSetLanguageProc before XtDisplayInitialize or XtAppInitialize is called. For full details, please refer to the document X Toolkit Intrinsics-C Language Interface, section 2.2. However, the following simplest-case call is sufficient in many or most applications.

XtSetLanguageProc(NULL, NULL, NULL);

Most notably, this will affect the Standard C locale, determine which resource files will be loaded, and what fonts will be required of FontSet specifications. In many cases, the addition of this line is the only source change required to internationalize Xaw programs, and will not disturb the function of programs in the default "C" locale.

Home


2.2. Initializing the Toolkit

You must call a toolkit initialization function before invoking any other toolkit routines (besides locale setting, above). XtAppInitialize opens the X server connection, parses the command line, and creates an initial widget that will serve as the root of a tree of widgets created by this application.

Widget XtAppInitialize(app_context_return, application_class, options, num_options, argc_in_out, argv_in_out, fa,
XtAppContext *app_context_return;
String application_class;
XrmOptionDescRec options[];
Cardinal num_options;
int *argc_in_our;
String *argv_in_out[];
String *fallback_resources;
ArgList args;
Cardinal nurn_args;

app_con_returnReturns the application context of this application, if non-NULL.
application_classSpecifies the class name of this application, which is usually the generic name for all instances of this application. A useful convention is to form the class name by capitalizing the first letter of the application name. For example, the application named "xman" has a class name of "Xman".
optionsSpecifies 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 Xlib-C Language X Interface.
num_optionsSpecifies the number of entries in the options list.
argc_in_outSpecifies a pointer to the number of command line parameters.
argv_in_outSpecifies the command line parameters.
fallback_resourcesSpecifies resource values to be used if the site-wide application class defaults file cannot be opened, or NULL.
argsSpecifies the argument list to use when creating the Application shell.
num_argsSpecifies the number of arguments in args.

This function will remove the command line arguments that the toolkit reads from argc in out, and argv in out. It will then attempt to open the display. If the display cannot be opened, an error message is issued and XtAppInitialize terminates the application. Once the display is opened, all resources are read from the locations specified by the Intrinsics. This function returns an ApplicationShell widget to be used as the root of the application's widget tree.

Home


2.3. Creating a Widget

Creating a widget is a three-step process. First, the widget instance is allocated, and various instance-specific attributes are set by using XtCreateWidget. Second, the widget's parent is informed of the new child by using XtManageChild. Finally, X windows are created for the parent and all its children by using XtRealizeWidget and specifying the top-most widget. The first two steps can be combined by using XtCreateManagedWidget. In addition, XtRealizeWidget is automatically called when the child becomes managed if the parent is already realized.
To allocate, initialize, and manage a widget, use XtCreateManagedWidget.
Widget XtCreateManagedWidget(name, widget_class, parent, args, num_args)
String name;
WidgetClass widget_class;
Widget parent;
ArgList args;
Cardinal num_args;

nameSpecifies the instance name for the created widget that is used for retrieving widget resources.
widget_classSpecifies the widget class pointer for the created widget.
parentSpecifies the parent widget ID.
argsSpecifies the argument list. The argument list is a variable-length list composed of name and value pairs that contain information pertaining to the specific widget instance being created.
num_argsSpecifies the number of arguments in the argument list. If the num_args is zero, the argument list is never referenced.

When a widget instance is successfully created, the widget identifier is returned to the application. If an error is encountered, the XtError routine is invoked to inform the user of the error. For further information, see X Toolkit Intrinsics-C Language Interface.

Home


2.4. Common Resources

Although a widget can have unique arguments that it understands, all widgets have common arguments that provide some regularity of operation. The common arguments allow arbitrary widgets to be managed by higher-level components without regard for the individual widget type. Widgets will ignore any argument that they do not understand.

The following resources are retrieved from the argument list or from the resource database by all of the Athena widgets:

NameClassType Default Value
acceleratorsAccelerators AcceleratoTableNULL
ancestorSensitiveAncestorSensitive BooleanTrue
backgroundBackground PixelXtDefaultBackground
backgroundPixmapPixmap PixmapXtUnspecifiedPixmap
borderColorBorderColor PixelXtDefaultForeground
borderPixmapPixmap PixmapXtUnspecifiedPixrnap
borderWidthBorderWidth Dimension1
colormapColormapColormap Parent's Colormap
depthDepthint Parent's Depth
destroyCallbackCallback XtCallbackListNULL
heightHeightDimension widget dependent
mappedWhenManagedMappedWhenManaged BooleanTrue
screenScreenScreen Parent's Screen
sensitiveSensitiveBoolean True
translationsTranslations TranslationTablewidget dependent
widthWidthDimension widget dependent
xPositionPosition 0
yPositionPosition 0

The following additional resources are retrieved from the argument list or from the resource database by many of the Athena widgets:

NameClassType Default Value
callbackCallbackXtCallbackList NULL
cursorCursorCursor widget dependent
foregroundForeground PixelXtDefaultForeground
insensitiveBorderInsensitive PixmapGreyPixmap

Home


2.5. Resource Conversions

Most resources in the Athena widget set have a converter registered that will translate the string in a resource file to the correct internal representation. While some are obvious (string to integer, for example), others need specific mention of the allowable values. Three general converters are described here:

Many widgets have defined special converters that apply only to that widget. When these occur, the documentation section for that widget will describe the converter.

2.5.1. Cursor Conversion

The value for the cursorName resource is specified in the resource database as a string, and is of the following forms:

2.5.2. Pixel Conversion

The string-to-pixel converter takes any name that is acceptable to XParseColor (see Xlib-C Language X Interface). In addition this routine understands the special toolkit symbols 'XtDefaultForeground' and 'XtDefaultBackground', described in X Toolkit Intrinsics-C Language Interface. In short the acceptable pixel names are:

2.5.3. Bitmap Conversion

The string-to-bitmap converter attempts to locate a file containing bitmap data whose name is specified by the input string. If the file name is relative (i.e. does not begin with / or ./), the directories to be searched are specified in the bitmapFilePath resource-class BitmapFilePath. This resource specifies a colon (:) separated list of directories that will be searched for the named bitmap or cursor glyph. The bitmapFilePath resource is global to the application, and may not be specified differently for each widget that wishes to convert a cursor to bitmap. In addition to the directories specified in the bitmapFilePath resource a default directory is searched. When using POSIX the default directory is /usr/include/X11/bitmaps.

Home


2.6. Realizing a Widget

The XtRealizeWidget function performs two tasks:

void XtRealizeWidget(w)
Widget w;

wSpecifies the widget.

For further information about this function, see the X Toolkit Intrinsics-C Language Interface.

Home


2.7. Processing Events

Now that the application has created, managed and realized its widgets, it is ready to process the events that will be delivered by the X Server to this client. A function call that will process the events is XtAppMainLoop.

voidXtAppMainLoop(app_context)
XtAppContext app_contexr;

app_contextSpecifies the application context of this application. The value is normally returned by XtAppInitialize.

This function never returns: it is an infinite loop that processes the X events. User input can be handled through callback procedures and application defined action routines. More details are provided in X Toolkit Intrinsics-C Language Interface.

Home


2.8. Standard Widget Manipulation Functions

After a widget has been created, a client can interact with that widget by calling one of the standard widget manipulation routines provided by the Intrinsics, or a widget class-specific manipulation routine.

The Intrinsics provide generic routines to give the application programmer access to a set of standard widget functions. The common widget routines let an application or composite widget perform the following operations on widgets without requiring explicit knowledge of the widget type.

2.8.1. Mapping Widgets

By default, widget windows are mapped (made viewable) automatically by XtRealizeWidget. This behavior can be disabled by using XtSetMappedWhenManaged, making the client responsible for calling XtMapWidget to make the widget viewable.
void XtSetMappedWhenManaged(w, map_when_managed)
Widget w;
Boolean map_when_managed;
wSpecifies the widget.
map_when_managedSpecifies the new value. If map_when_managed is True, the widget is mapped automatically when it is realized. If map_when_managed is False, the client must call XtMapWidget or make a second call to XtSetMappedWhenManaged to cause the child window to be mapped.

The definition for XtMapWidget is:

void XtMapWidget(w)
Widget w;

wSpecifies the widget.

When you are creating several children in sequence for a previously realized common parent it is generally more efficient to construct a list of children as they are created (using XtCreateWidget) and then use XtManageChildren to request that their parent managed them all at once. By managing a list of children at one time, the parent can avoid wasteful duplication of geometry processing and the associated "screen flash".

void XtManageChildren(children, num_children)
WidgetList children;
Cardinal num_children;

childrenSpecifies a list of children to add.
num_childrenSpecifies the number of children to add.

If the parent is already visible on the screen, it is especially important to batch updates so that the minimum amount of visible window reconfiguration is performed.

For further information about these functions, see the X Toolkit Intrinsics-C Language Interface.

2.8.2. Destroying Widgets

To destroy a widget instance of any type, use XtDestroyWidget.

void XtDestroyWidget(w)
Widget w;

wSpecifies the widget.

XtDestroyWidget destroys the widget and recursively destroys any children that it may have, including the windows created by its children. After calling XtDestroyWidget, no further references should be made to the widget or any children that the destroyed widget may have had.

2.8.3. Retrieving Widget Resource Values

To retrieve the current value of a resource attribute associated with a widget instance, use XtGetValues.

void XtGetValues(w, args, num_args)
Widget w;
ArgList args;
Cardinal num_args;

wSpecifies the widget.
argsSpecifies a variable-length argument list of name and address pairs that contain the resource name and the address into which the resource value is stored.
num_argsSpecifies the number of arguments in the argument list.

The arguments and values passed in the argument list are dependent on the widget. Note that the caller is responsible for providing space into which the returned resource value is copied; the ArgList contains a pointer to this storage (e.g. x and y must be allocated as Position). For further information, see the X Toolkit Intrinsics-C Language Interface.

2.8.4. Modifying Widget Resource Values

To modify the current value of a resource attribute associated with a widget instance, use XtSetValues.

void XtSetValues(w, args, num_args)
Widget w;
ArgList args;
Cardinal num_args;

wSpecifies the widget.
argsSpecifies an array of name and value pairs that contain the arguments to be modified and their new values.
num_argsSpecifies the number of arguments in the argument list.

The arguments and values that are passed will depend on the widget being modified. Some widgets may not allow certain resources to be modified after the widget instance has been created or realized. No notification is given if any part of a XtSetValues request is ignored.

For further information about these functions, see the X Toolkit Intrinsics-C Language Interface.

NOTE
The argument list entry for XtGetValues specifies the address to which the caller wants the value copied. The argument list entry for XtSetValues, however, contains the new value itself, if the size of value is less than sizeof(XtArgVal) (architecture dependent, but at least sizeof(long)); otherwise, it is a pointer to the value. String resources are always passed as pointers, regardless of the length of the string.

Home


2.9. Using the Client Callback Interface

Widgets can communicate changes in their state to their clients by means of a callback facility. The format for a client's callback handler is:

void CallbackProc(w, client_data, call_data)
Widget w;
XtPointer client_data;
XtPointer call_data;

wSpecifies widget for which the callback is registered.
client_dataSpecifies arbitrary client-supplied data that the widget should pass back to the client when the widget executes the client's callback procedure. This is a way for the client registering the callback to also register client-specific data: a pointer to additional information about the widget, a reason for invoking the callback, and so on. If no additional information is necessary, NULL may be passed as this argument. This field is also frequently known as the closure.
call_dataSpecifies any callback-specific data the widget wants to pass to the client. For example, when Scrollbar executes its jumpProc callback list, it passes the current position of the thumb in call_data.

Callbacks can be registered either by creating an argument containing the callback list described below or by using the special convenience routines XtAddCallback and XtAddCallbacks. When the widget is created, a pointer to a list of callback procedure and data pairs can be passed in the argument list to XtCreateWidget. The list is of type XtCallbackList:

typedef struct {
        XtCallbackProc callback;
        XtPointer closure;
} XtCallbackRec, *XtCallbackList;
The callback list must be allocated and initialized before calling XtCreateWidget. The end of the list is identified by an entry containing NULL in call back and closure. Once the widget is created, the client can change or de-allocate this list; the widget itself makes no further reference to it. The closure field contains the client_data passed to the callback when the callback list is executed.

The second method for registering callbacks is to use XtAddCallback after the widget has been created.

void XtAddCallback(w, callback_name, callback, client_data)
Widget w;
String callback_name;
XtCallbackProc callback;
XtPointer client_data;

wSpecifies the widget to add the callback to.
callback_nameSpecifies the callback list within the widget to append to.
callbackSpecifies the callback procedure to add.
client_dataSpecifies the data to be passed to the callback when it is invoked.

XtAddCallback adds the specified callback to the list for the named widget.

All widgets provide a callback list named destroyCallback where clients can register procedures that are to be executed when the widget is destroyed. The destroy callbacks are executed when the widget or an ancestor is destroyed. The call data argument is unused for destroy callbacks.

Home


2.10. Programming Considerations

This section provides some guidelines on how to set up an application program that uses the X Toolkit.

2.10.1. Writing Applications

When writing an application that uses the X Toolkit, you should make sure that your application performs the following:

  1. Include <X11/Intrinsic.h> in your application programs. This header file automatically includes <X11/Xlib.h>, so all Xlib functions also are defined. It may also be necessary to include < X11/StringDefs.h> when setting up argument lists, as many of the XtNsomething definitions are only defined in this file.

  2. Include the widget-specific header files for each widget type that you need to use. For example, <X11/Xaw/Label.h> and <X11/Xaw/Command.h>.

  3. Call the XtAppInitialize function before invoking any other toolkit or Xlib functions. For further information, see Section 2.1 and the X Toolkit Intrinsics-C Language Interface.

  4. To pass attributes to the widget creation routines that will override any site or user customizations, set up argument lists. In this document, a list of valid argument names is provided in the discussion of each widget. The names each have a global symbol defined that begins with XtN to help catch spelling errors. For example, XtNlabel is defined for the label resource of many widgets.

    For further information, see Section 2.10.2.2.

  5. When the argument list is set up, create the widget with the XtCreateManagedWidget function. For further information, see Section 2.2 and the X Toolkit Intrinsics-C Language Interface.

  6. If the widget has any callback routines, set by the XtNcallback argument or the XtAddCallback function, declare these routines within the application.

  7. After creating the initial widget hierarchy, windows must be created for each widget by calling XtRealizeWidget on the top level widget.

  8. Most applications now sit in a loop processing events using XtAppMainLoop, for example:

    XtCreateManagedWidget(name, class, parent, args, num_args);
    XtRealizeWidget(shell);
    XtAppMainLoop(app_conrext);

    For information about this function, see the X Toolkit Intrinsics-C Language Interface.

  9. Link your application with libXaw (the Athena widgets), libXmu (miscellaneous utilities), libXt (the X Toolkit Intrinsics), libSM (Session Management), libICE (Inter-Client Exchange), libXext (the extension library needed for the shape extension code which allows rounded Command buttons), and libX11 (the core X library). The following provides a sample command line:

    cc -o application application.c -1Xaw -1Xmu -1Xt -1SM -1ICE -1Xext -1X11

2.10.2. Changing Resource Values

The Intrinsics support two methods of changing the default resource values; the resource manager, and an argument list passed into XtCreateWidget. While resources values will get updated no matter which method you use, the two methods provide slightly different functionality.

Resource
This method picks up resource definitions described in Xlib-C Language X Interface from many different locations at run time. The locations most important to the application programmer are the fallback resources and the app-defaults file, (see X Toolkit Intrinsics-C Language Interface for the complete list). Since these resource are loaded at run time, they can be overridden by the user, allowing an application to be customized to fit the particular needs of each individual user. These values can also be modified without the need to rebuild the application, allowing rapid prototyping of user interfaces. Application programmers should use resources in preference to hard-coded values whenever possible.

Argument
The values passed into the widget at creation time via an argument list cannot be modified by the user, and allow no opportunity for customization. It is used to set resources that cannot be specified as strings (e.g. callback lists) or resources that should not be overridden (e.g. window depth) by the user.

2.10.2.1. Specifying Resources

It is important for all X Toolkit application programmers to understand how to use the X Resource Manager to specify resources for widgets in an X application. This section will describe the most common methods used to specify these resources, and how to use the X Resource manager.

XrdbThe xrdb utility may be used to load a file containing resources into the X server. Once the resources are loaded, the resources will affect any new applications started on the display that they were loaded onto.
Application DefaultsThe application defaults (app-defaults) file (normally in /usr/lib/X11/app-defaults/classname) for an application is loaded whenever the application is started.

The resource specification has two colon-separated parts, a name, and a value. The value is a string whose format is dependent on the resource specified by name. Name is constructed by appending a resource name to a full widget name.

The full widget name is a list of the name of every ancestor of the desired widget separated by periods (.). Each widget also has a class associated with it. A class is a type of widget (e.g. Label or Scrollbar or Box). Notice that class names, by convention, begin with capital letters and instance names begin with lower case letters. The class of any widget may be used in place of its name in a resource specification. Here are a few examples:

xman.form.button1This is a fully specified resource name, and will affect only widgets called buttonl that are children of widgets called form that are children of applications named xman. (Note that while typically two widgets that are siblings will have different names, it is not prohibited.)
Xman.Form.CommandThis will match any Command widget that is a child of a Form widget that is itself a child of an application of class Xman.
Xman.Form.button1This is a mixed resource name with both widget names and classes specified.

This syntax allows an application programmer to specify any widget in the widget tree. To match more than one widget (for example a user may want to make all Command buttons blue), use an asterisk (*) instead of a period. When an asterisk is used, any number of widgets (including zero) may exist between the two widget names. For example:

Xman*CommandThis matches all Command widgets in the Xman application.
Foo*button1This matches any widget in the Foo application that is named buttonl.

The root of all application widget trees is the widget returned by XtAppInitialize. Even though this is actually an ApplicationShell widget, the toolkit replaces its widget class with the class name of the application. The name of this widget is either the name used to invoke the application (argv[0]) or the name of the application specified using the standard -name command line option supported by the Intrinsics.

The last step in constructing the resource name is to append the name of the resource with either a period or asterisk to the full or partial widget name already constructed.

*foreground:BlueSpecifies that all widgets in all applications will have a fore ground color of blue.
Xman*borderWidth:10Specifies that all widgets in an application whose class is Xman will have a border width of 10 (pixels).
xman.form.button1.label:TestingSpecifies that a particular widget in the xman application will have a label named Testing.

An exclamation point (!) in the first column of a line indicates that the rest of the line should be treated as a comment.

Final Words
The Resource manager is a powerful tool that can be used very effectively to customize X Toolkit applications at run time by either the application programmer or the user. Some final points to note:

For a complete explanation of the rules of precedence, and other specific topics see X Toolkit Intrinsics-C Language Interface and Xlib-C Language X Interface.

2.10.2.2. Creating Argument Lists

To set up an argument list for the inline specification of widget attributes, you may use any of the four approaches discussed in this section. Each resource name has a global symbol associated with it. This global symbol has the form XtNresource name. For example, the symbol for "foreground" is XtNforeground. For further information, see the X Toolkit Intrinsics-C Language Interface.

Argument are specified by using the following structure:

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

The first approach is to statically initialize the argument list. For example:

static Arg arglist[] = {
        {XtNwidth, (XtArgVal) 400},
        {XtNheight. (XtArgVal) 300},
};

This approach is convenient for lists that do not need to be computed at runtime and makes adding or deleting new elements easy. The XtNumber macro is used to compute the number of elements in the argument list, preventing simple programming errors:

XtCreateWidget(name, class, parent, arglist, XtNumber(arglist));

The second approach is to use the XtSetArg macro. For example:

Arg arglist[10];
XtSetArg(arglist[1], XtNwidth, 400);
XtSetArg(arglist[2], XtNheight, 300);

To make it easier to insert and delete entries, you also can use a variable index:

Arg arglist[10];
Cardinal i=0;
XtSetArg(arglist[i],XtNwidth, 400);i++;
XtSetArg(arglist[i], XtNheight, 300);i++;

The i variable can then be used as the argument list count in the widget create function. In this example, XtNumber would return 10, not 2, and therefore is not useful.

NOTE
You should not use auto-increment or auto-decrement within the first argument to XtSetArg. As it is currently implemented, XtSetArg is a macro that dereferences the first argument twice.

The third approach is to individually set the elements of the argument list array:

Arg arglist[10];
arglist[0].name = XtNwidth;
arglist[0].value = (XtArgVal) 400;
arglist[1].name =XtNheight;
arglist[1].value = (XtArgVal) 300;

Note that in this example, as in the previous example, XtNumber would return 10, not 2, and therefore would not be useful.

The fourth approach is to use a mixture of the first and third approaches: you can statically define the argument list but modify some entries at runtime. For example:

Static Arg arglist[] = {
         {XtNwidth, (XtArgVal) 400},
         {XtNheight, (XtArgVal) NULL},
};
arglist[1].value = (XtArgVal) 300;

In this example, XtNumber can be used, as in the first approach, for easier code maintenance.

Home


2.11. Example Programs

The best way to understand how to use any programming library is by trying some simple examples. A collection of example programs that introduces each of the widgets in that Athena widget set, as well as many important toolkit programming concepts, is available in the X11R6 release as distributed by the X Consortium. It can be found in the distribution directory contrib/examples/mit/Xaw, but see your site administrator for the exact location of these files on your system. See the README file from that directory for a guide to the examples.

Home

Contents Previous Chapter Next Chapter