Conventions Used in this Manual
1.1. IntrinsicsThe Intrinsics provide the base mechanism necessary to builda wide variety of interoperating widget sets and applicationenvironments. The Intrinsics are a layer on top of Xlib,the C Library X Interface. They extend the fundamentalabstractions provided by the X Window System while stillremaining independent of any particular user interfacepolicy or style.The Intrinsics use object-oriented programming techniques tosupply a consistent architecture for constructing andcomposing user interface components, known as widgets. Thisallows programmers to extend a widget set in new ways,either by deriving new widgets from existing ones(subclassing) or by writing entirely new widgets followingthe established conventions.When the Intrinsics were first conceived, the root of theobject hierarchy was a widget class named Core. In Release4 of the Intrinsics, three nonwidget superclasses were addedabove Core. These superclasses are described in Chapter 12.The name of the class now at the root of the Intrinsicsclass hierarchy is Object. The remainder of thisspecification refers uniformly to widgets and Core as ifthey were the base class for all Intrinsics operations. Theargument descriptions for each Intrinsics procedure andChapter 12 describe which operations are defined for thenonwidget superclasses of Core. The reader may determine bycontext whether a specific reference to widget actuallymeans ‘‘widget’’ or ‘‘object.’’1.2. LanguagesThe Intrinsics are intended to be used for two programmingpurposes. Programmers writing widgets will be using most ofthe facilities provided by the Intrinsics to construct userinterface components from the simple, such as buttons andscrollbars, to the complex, such as control panels andproperty sheets. Application programmers will use a muchsmaller subset of the Intrinsics procedures in combinationwith one or more sets of widgets to construct and presentcomplete user interfaces on an X display. The Intrinsicsprogramming interfaces primarily intended for applicationuse are designed to be callable from most proceduralprogramming languages. Therefore, most arguments are passedby reference rather than by value. The interfaces primarilyintended for widget programmers are expected to be usedprincipally from the C language. In these cases, the usualC programming conventions apply. In this specification, theterm client refers to any module, widget, or applicationthat calls an Intrinsics procedure.Applications that use the Intrinsics mechanisms must includethe header files <X11/Intrinsic.h> and <X11/StringDefs.h>,or their equivalent, and they may also include<X11/Xatoms.h> and <X11/Shell.h>. In addition, widgetimplementations should include <X11/IntrinsicP.h> instead of<X11/Intrinsic.h>.The applications must also include the additional headerfiles for each widget class that they are to use (forexample, <X11/Xaw/Label.h> or <X11/Xaw/Scrollbar.h>). On aPOSIX-based system, the Intrinsics object library file isnamed libXt.a and is usually referenced as −lXt when linkingthe application.1.3. Procedures and Macros
1.4. Widgets
1.4.1. Core WidgetsThe Core widget class contains the definitions of fieldscommon to all widgets. All widgets classes are subclassesof the Core class, which is defined by the CoreClassPart andCorePart structures.1.4.1.1. CoreClassPart StructureAll widget classes contain the fields defined in theCoreClassPart structure.__│ typedef struct {WidgetClass superclass; See Section 1.6String class_name; See Chapter 9Cardinal widget_size; See Section 1.6XtProc class_initialize; See Section 1.6XtWidgetClassProc class_part_initialize;See Section 1.6XtEnum class_inited; See Section 1.6XtInitProc initialize; See Section 2.5XtArgsProc initialize_hook; See Section 2.5XtRealizeProc realize; See Section 2.6XtActionList actions; See Chapter 10Cardinal num_actions; See Chapter 10XtResourceList resources; See Chapter 9Cardinal num_resources; See Chapter 9XrmClass xrm_class; Private to resource managerBoolean compress_motion; See Section 7.9XtEnum compress_exposure; See Section 7.9Boolean compress_enterleave; See Section 7.9Boolean visible_interest; See Section 7.10XtWidgetProc destroy; See Section 2.8XtWidgetProc resize; See Chapter 6XtExposeProc expose; See Section 7.10XtSetValuesFunc set_values; See Section 9.7XtArgsFunc set_values_hook; See Section 9.7XtAlmostProc set_values_almost;See Section 9.7XtArgsProc get_values_hook; See Section 9.7XtAcceptFocusProc accept_focus;See Section 7.3XtVersionType version; See Section 1.6XtPointer callback_private; Private to callbacksString tm_table; See Chapter 10XtGeometryHandler query_geometry;See Chapter 6XtStringProc display_accelerator;See Chapter 10XtPointer extension; See Section 1.6} CoreClassPart;│__ All widget classes have the Core class fields as their firstcomponent. The prototypical WidgetClass and CoreWidgetClassare defined with only this set of fields.__│ typedef struct {CoreClassPart core_class;} WidgetClassRec, *WidgetClass, CoreClassRec, *CoreWidgetClass;│__ Various routines can cast widget class pointers, as needed,to specific widget class types.The single occurrences of the class record and pointer forcreating instances of Core areIn IntrinsicP.h:__│ extern WidgetClassRec widgetClassRec;#define coreClassRec widgetClassRec│__ In Intrinsic.h:__│ extern WidgetClass widgetClass, coreWidgetClass;│__ The opaque types Widget and WidgetClass and the opaquevariable widgetClass are defined for generic actions onwidgets. In order to make these types opaque and ensurethat the compiler does not allow applications to accessprivate data, the Intrinsics use incomplete structuredefinitions in Intrinsic.h:__│ typedef struct _WidgetClassRec *WidgetClass, *CoreWidgetClass;│__ 1.4.1.2. CorePart StructureAll widget instances contain the fields defined in theCorePart structure.__│ typedef struct _CorePart {Widget self; Described belowWidgetClass widget_class;See Section 1.6Widget parent; See Section 2.5Boolean being_destroyed; See Section 2.8XtCallbackList destroy_callbacks;See Section 2.8XtPointer constraints; See Section 3.6Position x; See Chapter 6Position y; See Chapter 6Dimension width; See Chapter 6Dimension height; See Chapter 6Dimension border_width; See Chapter 6Boolean managed; See Chapter 3Boolean sensitive; See Section 7.7Boolean ancestor_sensitive;See Section 7.7XtTranslations accelerators;See Chapter 10Pixel border_pixel; See Section 2.6Pixmap border_pixmap; See Section 2.6WidgetList popup_list; See Chapter 5Cardinal num_popups; See Chapter 5String name; See Chapter 9Screen *screen; See Section 2.6Colormap colormap; See Section 2.6Window window; See Section 2.6Cardinal depth; See Section 2.6Pixel background_pixel; See Section 2.6Pixmap background_pixmap;See Section 2.6Boolean visible; See Section 7.10Boolean mapped_when_managed;See Chapter 3} CorePart;│__ All widget instances have the Core fields as their firstcomponent. The prototypical type Widget is defined withonly this set of fields.__│ typedef struct {CorePart core;} WidgetRec, *Widget, CoreRec, *CoreWidget;│__ Various routines can cast widget pointers, as needed, tospecific widget types.In order to make these types opaque and ensure that thecompiler does not allow applications to access private data,the Intrinsics use incomplete structure definitions inIntrinsic.h.__│ typedef struct _WidgetRec *Widget, *CoreWidget;│__ 1.4.1.3. Core Resources
1.4.1.4. CorePart Default ValuesThe default values for the Core fields, which are filled inby the Intrinsics, from the resource lists, and by theinitialize procedures, areXtUnspecifiedPixmap is a symbolic constant guaranteed to beunequal to any valid Pixmap id, None, and ParentRelative.1.4.2. Composite WidgetsThe Composite widget class is a subclass of the Core widgetclass (see Chapter 3). Composite widgets are intended to becontainers for other widgets. The additional data used bycomposite widgets are defined by the CompositeClassPart andCompositePart structures.1.4.2.1. CompositeClassPart StructureIn addition to the Core class fields, widgets of theComposite class have the following class fields.__│ typedef struct {XtGeometryHandler geometry_manager;See Chapter 6XtWidgetProc change_managed; See Chapter 3XtWidgetProc insert_child; See Chapter 3XtWidgetProc delete_child; See Chapter 3XtPointer extension; See Section 1.6} CompositeClassPart;│__ The extension record defined for CompositeClassPart withrecord_type equal to NULLQUARK isCompositeClassExtensionRec.__│ typedef struct {XtPointer next_extension; See Section 1.6.12XrmQuark record_type; See Section 1.6.12long version; See Section 1.6.12Cardinal record_size; See Section 1.6.12Boolean accepts_objects; See Section 2.5.2Boolean allows_change_managed_set;See Section 3.4.3} CompositeClassExtensionRec, *CompositeClassExtension;│__ Composite classes have the Composite class fieldsimmediately following the Core class fields.__│ typedef struct {CoreClassPart core_class;CompositeClassPart composite_class;} CompositeClassRec, *CompositeWidgetClass;│__ The single occurrences of the class record and pointer forcreating instances of Composite areIn IntrinsicP.h:__│ extern CompositeClassRec compositeClassRec;│__ In Intrinsic.h:__│ extern WidgetClass compositeWidgetClass;│__ The opaque types CompositeWidget and CompositeWidgetClassand the opaque variable compositeWidgetClass are defined forgeneric operations on widgets whose class is Composite or asubclass of Composite. The symbolic constant for theCompositeClassExtension version identifier isXtCompositeExtensionVersion (see Section 1.6.12).Intrinsic.h uses an incomplete structure definition toensure that the compiler catches attempts to access privatedata.__│ typedef struct _CompositeClassRec *CompositeWidgetClass;│__ 1.4.2.2. CompositePart StructureIn addition to the Core instance fields, widgets of theComposite class have the following instance fields definedin the CompositePart structure.__│ typedef struct {WidgetList children; See Chapter 3Cardinal num_children; See Chapter 3Cardinal num_slots; See Chapter 3XtOrderProc insert_position;See Section 3.2} CompositePart;│__ Composite widgets have the Composite instance fieldsimmediately following the Core instance fields.__│ typedef struct {CorePart core;CompositePart composite;} CompositeRec, *CompositeWidget;│__ Intrinsic.h uses an incomplete structure definition toensure that the compiler catches attempts to access privatedata.__│ typedef struct _CompositeRec *CompositeWidget;│__ 1.4.2.3. Composite ResourcesThe resource names, classes, and representation types thatare specified in the compositeClassRec resource list are1.4.2.4. CompositePart Default ValuesThe default values for the Composite fields, which arefilled in from the Composite resource list and by theComposite initialize procedure, areThe children, num_children, and insert_position fields aredeclared as resources; XtNinsertPosition is a settableresource, XtNchildren and XtNnumChildren may be read by anyclient but should only be modified by the composite widgetclass procedures.1.4.3. Constraint WidgetsThe Constraint widget class is a subclass of the Compositewidget class (see Section 3.6). Constraint widgets maintainadditional state data for each child; for example,client-defined constraints on the child’s geometry. Theadditional data used by constraint widgets are defined bythe ConstraintClassPart and ConstraintPart structures.1.4.3.1. ConstraintClassPart StructureIn addition to the Core and Composite class fields, widgetsof the Constraint class have the following class fields.__│ typedef struct {XtResourceList resources;See Chapter 9Cardinal num_resources; See Chapter 9Cardinal constraint_size;See Section 3.6XtInitProc initialize; See Section 3.6XtWidgetProc destroy; See Section 3.6XtSetValuesFunc set_values;See Section 9.7.2XtPointer extension; See Section 1.6} ConstraintClassPart;│__ The extension record defined for ConstraintClassPart withrecord_type equal to NULLQUARK isConstraintClassExtensionRec.__│ typedef struct {XtPointer next_extension;See Section 1.6.12XrmQuark record_type; See Section 1.6.12long version; See Section 1.6.12Cardinal record_size; See Section 1.6.12XtArgsProc get_values_hook;See Section 9.7.1} ConstraintClassExtensionRec, *ConstraintClassExtension;│__ Constraint classes have the Constraint class fieldsimmediately following the Composite class fields.__│ typedef struct _ConstraintClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ConstraintClassPart constraint_class;} ConstraintClassRec, *ConstraintWidgetClass;│__ The single occurrences of the class record and pointer forcreating instances of Constraint areIn IntrinsicP.h:__│ extern ConstraintClassRec constraintClassRec;│__ In Intrinsic.h:__│ extern WidgetClass constraintWidgetClass;│__ The opaque types ConstraintWidget and ConstraintWidgetClassand the opaque variable constraintWidgetClass are definedfor generic operations on widgets whose class is Constraintor a subclass of Constraint. The symbolic constant for theConstraintClassExtension version identifier isXtConstraintExtensionVersion (see Section 1.6.12).Intrinsic.h uses an incomplete structure definition toensure that the compiler catches attempts to access privatedata.__│ typedef struct _ConstraintClassRec *ConstraintWidgetClass;│__ 1.4.3.2. ConstraintPart StructureIn addition to the Core and Composite instance fields,widgets of the Constraint class have the following unusedinstance fields defined in the ConstraintPart structure__│ typedef struct {int empty;} ConstraintPart;│__ Constraint widgets have the Constraint instance fieldsimmediately following the Composite instance fields.__│ typedef struct {CorePart core;CompositePart composite;ConstraintPart constraint;} ConstraintRec, *ConstraintWidget;│__ Intrinsic.h uses an incomplete structure definition toensure that the compiler catches attempts to access privatedata.__│ typedef struct _ConstraintRec *ConstraintWidget;│__ 1.4.3.3. Constraint ResourcesThe constraintClassRec core_class and constraint_classresources fields are NULL, and the num_resources fields arezero; no additional resources beyond those declared by thesuperclasses are defined for Constraint.1.5. Implementation-Specific TypesTo increase the portability of widget and application sourcecode between different system environments, the Intrinsicsdefine several types whose precise representation isexplicitly dependent upon, and chosen by, each individualimplementation of the Intrinsics.These implementation-defined types areBoolean A datum that contains a zero or nonzero value.Unless explicitly stated, clients should notassume that the nonzero value is equal to thesymbolic value True.Cardinal An unsigned integer datum with a minimum range of[0..2^16-1].Dimension An unsigned integer datum with a minimum range of[0..2^16-1].Position A signed integer datum with a minimum range of[-2^15..2^15-1].XtPointer A datum large enough to contain the largest of achar*, int*, function pointer, structure pointer,or long value. A pointer to any type orfunction, or a long value may be converted to anXtPointer and back again and the result willcompare equal to the original value. In ANSI Cenvironments it is expected that XtPointer willbe defined as void*.XtArgVal A datum large enough to contain an XtPointer,Cardinal, Dimension, or Position value.XtEnum An integer datum large enough to encode at least128 distinct values, two of which are thesymbolic values True and False. The symbolicvalues TRUE and FALSE are also defined to beequal to True and False, respectively.In addition to these specific types, the precise order ofthe fields within the structure declarations for any of theinstance part records ObjectPart, RectObjPart, CorePart,CompositePart, ShellPart, WMShellPart, TopLevelShellPart,and ApplicationShellPart is implementation-defined. Thesestructures may also have additional private fields internalto the implementation. The ObjectPart, RectObjPart, andCorePart structures must be defined so that any member withthe same name appears at the same offset in ObjectRec,RectObjRec, and CoreRec (WidgetRec). No other relationsbetween the offsets of any two fields may be assumed.1.6. Widget Classing
1.6.1. Widget Naming ConventionsThe Intrinsics provide a vehicle by which programmers cancreate new widgets and organize a collection of widgets intoan application. To ensure that applications need not dealwith as many styles of capitalization and spelling as thenumber of widget classes it uses, the following guidelinesshould be followed when writing new widgets:• Use the X library naming conventions that areapplicable. For example, a record component name isall lowercase and uses underscores (_) for compoundwords (for example, background_pixmap). Type andprocedure names start with uppercase and usecapitalization for compound words (for example, ArgListor XtSetValues).• A resource name is spelled identically to the fieldname except that compound names use capitalizationrather than underscore. To let the compiler catchspelling errors, each resource name should have asymbolic identifier prefixed with ‘‘XtN’’. Forexample, the background_pixmap field has thecorresponding identifier XtNbackgroundPixmap, which isdefined as the string ‘‘backgroundPixmap’’. Manypredefined names are listed in <X11/StringDefs.h>.Before you invent a new name, you should make surethere is not already a name that you can use.• A resource class string starts with a capital letterand uses capitalization for compound names (forexample,‘‘BorderWidth’’). Each resource class stringshould have a symbolic identifier prefixed with ‘‘XtC’’(for example, XtCBorderWidth). Many predefined classesare listed in <X11/StringDefs.h>.• A resource representation string is spelled identicallyto the type name (for example, ‘‘TranslationTable’’).Each representation string should have a symbolicidentifier prefixed with ‘‘XtR’’ (for example,XtRTranslationTable). Many predefined representationtypes are listed in <X11/StringDefs.h>.• New widget classes start with a capital and useuppercase for compound words. Given a new class nameAbcXyz, you should derive several names:− Additional widget instance structure part nameAbcXyzPart.− Complete widget instance structure names AbcXyzRecand _AbcXyzRec.− Widget instance structure pointer type nameAbcXyzWidget.− Additional class structure part nameAbcXyzClassPart.− Complete class structure names AbcXyzClassRec and_AbcXyzClassRec.− Class structure pointer type nameAbcXyzWidgetClass.− Class structure variable abcXyzClassRec.− Class structure pointer variableabcXyzWidgetClass.• Action procedures available to translationspecifications should follow the same namingconventions as procedures. That is, they start with acapital letter, and compound names use uppercase (forexample, ‘‘Highlight’’ and ‘‘NotifyClient’’).The symbolic identifiers XtN..., XtC..., and XtR... may beimplemented as macros, as global symbols, or as a mixture ofthe two. The (implicit) type of the identifier is String.The pointer value itself is not significant; clients mustnot assume that inequality of two identifiers impliesinequality of the resource name, class, or representationstring. Clients should also note that although globalsymbols permit savings in literal storage in someenvironments, they also introduce the possibility ofmultiple definition conflicts when applications attempt touse independently developed widgets simultaneously.1.6.2. Widget Subclassing in Public .h FilesThe public .h file for a widget class is imported by clientsand contains• A reference to the public .h file for the superclass.• Symbolic identifiers for the names and classes of thenew resources that this widget adds to its superclass.The definitions should have a single space between thedefinition name and the value and no trailing space orcomment in order to reduce the possibility of compilerwarnings from similar declarations in multiple classes.• Type declarations for any new resource data typesdefined by the class.• The class record pointer variable used to create widgetinstances.• The C type that corresponds to widget instances of thisclass.• Entry points for new class methods.For example, the following is the public .h file for apossible implementation of a Label widget:#ifndef LABEL_H#define LABEL_H/* New resources */#define XtNjustify "justify"#define XtNforeground "foreground"#define XtNlabel "label"#define XtNfont "font"#define XtNinternalWidth "internalWidth"#define XtNinternalHeight "internalHeight"/* Class record pointer */extern WidgetClass labelWidgetClass;/* C Widget type definition */typedef struct _LabelRec *LabelWidget;/* New class method entry points */extern void LabelSetText();/* Widget w *//* String text */extern String LabelGetText();/* Widget w */#endif LABEL_HThe conditional inclusion of the text allows the applicationto include header files for different widgets without beingconcerned that they already may be included as a superclassof another widget.To accommodate operating systems with file name lengthrestrictions, the name of the public .h file is the firstten characters of the widget class. For example, the public.h file for the Constraint widget class is Constraint.h.1.6.3. Widget Subclassing in Private .h FilesThe private .h file for a widget is imported by widgetclasses that are subclasses of the widget and contains• A reference to the public .h file for the class.• A reference to the private .h file for the superclass.• Symbolic identifiers for any new resourcerepresentation types defined by the class. Thedefinitions should have a single space between thedefinition name and the value and no trailing space orcomment.• A structure part definition for the new fields that thewidget instance adds to its superclass’s widgetstructure.• The complete widget instance structure definition forthis widget.• A structure part definition for the new fields thatthis widget class adds to its superclass’s constraintstructure if the widget class is a subclass ofConstraint.• The complete constraint structure definition if thewidget class is a subclass of Constraint.• Type definitions for any new procedure types used byclass methods declared in the widget class part.• A structure part definition for the new fields thatthis widget class adds to its superclass’s widget classstructure.• The complete widget class structure definition for thiswidget.• The complete widget class extension structuredefinition for this widget, if any.• The symbolic constant identifying the class extensionversion, if any.• The name of the global class structure variablecontaining the generic class structure for this class.• An inherit constant for each new procedure in thewidget class part structure.For example, the following is the private .h file for apossible Label widget:#ifndef LABELP_H#define LABELP_H#include <X11/Label.h>/* New representation types used by the Label widget */#define XtRJustify "Justify"/* New fields for the Label widget record */typedef struct {/* Settable resources */Pixel foreground;XFontStruct *font;String label; /* text to display */XtJustify justify;Dimension internal_width;/* # pixels horizontal border */Dimension internal_height;/* # pixels vertical border *//* Data derived from resources */GC normal_GC;GC gray_GC;Pixmap gray_pixmap;Position label_x;Position label_y;Dimension label_width;Dimension label_height;Cardinal label_len;Boolean display_sensitive;} LabelPart;/* Full instance record declaration */typedef struct _LabelRec {CorePart core;LabelPart label;} LabelRec;/* Types for Label class methods */typedef void (*LabelSetTextProc)();/* Widget w *//* String text */typedef String (*LabelGetTextProc)();/* Widget w *//* New fields for the Label widget class record */typedef struct {LabelSetTextProc set_text;LabelGetTextProc get_text;XtPointer extension;} LabelClassPart;/* Full class record declaration */typedef struct _LabelClassRec {CoreClassPart core_class;LabelClassPart label_class;} LabelClassRec;/* Class record variable */extern LabelClassRec labelClassRec;#define LabelInheritSetText((LabelSetTextProc)_XtInherit)#define LabelInheritGetText((LabelGetTextProc)_XtInherit)#endif LABELP_HTo accommodate operating systems with file name lengthrestrictions, the name of the private .h file is the firstnine characters of the widget class followed by a capital P.For example, the private .h file for the Constraint widgetclass is ConstrainP.h.1.6.4. Widget Subclassing in .c FilesThe .c file for a widget contains the structure initializerfor the class record variable, which contains the followingparts:• Class information (for example, superclass, class_name,widget_size, class_initialize, and class_inited).• Data constants (for example, resources andnum_resources, actions and num_actions,visible_interest, compress_motion, compress_exposure,and version).• Widget operations (for example, initialize, realize,destroy, resize, expose, set_values, accept_focus, andany new operations specific to the widget).The superclass field points to the superclass global classrecord, declared in the superclass private .h file. Fordirect subclasses of the generic core widget, superclassshould be initialized to the address of the widgetClassRecstructure. The superclass is used for class chainingoperations and for inheriting or enveloping a superclass’soperations (see Sections 1.6.7, 1.6.9, and 1.6.10).The class_name field contains the text name for this class,which is used by the resource manager. For example, theLabel widget has the string ‘‘Label’’. More than one widgetclass can share the same text class name. This string mustbe permanently allocated prior to or during the execution ofthe class initialization procedure and must not besubsequently deallocated.The widget_size field is the size of the correspondingwidget instance structure (not the size of the classstructure).The version field indicates the toolkit implementationversion number and is used for runtime consistency checkingof the X Toolkit and widgets in an application. Widgetwriters must set it to the implementation-defined symbolicvalue XtVersion in the widget class structureinitialization. Those widget writers who believe that theirwidget binaries are compatible with other implementations ofthe Intrinsics can put the special value XtVersionDontCheckin the version field to disable version checking for thosewidgets. If a widget needs to compile alternative code fordifferent revisions of the Intrinsics interface definition,it may use the symbol XtSpecificationRelease, as describedin Chapter 13. Use of XtVersion allows the Intrinsicsimplementation to recognize widget binaries that werecompiled with older implementations.The extension field is for future upward compatibility. Ifthe widget programmer adds fields to class parts, allsubclass structure layouts change, requiring completerecompilation. To allow clients to avoid recompilation, anextension field at the end of each class part can point to arecord that contains any additional class informationrequired.All other fields are described in their respective sections.The .c file also contains the declaration of the globalclass structure pointer variable used to create instances ofthe class. The following is an abbreviated version of the.c file for a Label widget. The resources table isdescribed in Chapter 9./* Resources specific to Label */static XtResource resources[] = {{XtNforeground, XtCForeground, XtRPixel, sizeof(Pixel),XtOffset(LabelWidget, label.foreground), XtRString,XtDefaultForeground},{XtNfont, XtCFont, XtRFontStruct, sizeof(XFontStruct *),XtOffset(LabelWidget, label.font),XtRString,XtDefaultFont},{XtNlabel, XtCLabel, XtRString, sizeof(String),XtOffset(LabelWidget, label.label), XtRString, NULL},...}/* Forward declarations of procedures */static void ClassInitialize();static void Initialize();static void Realize();static void SetText();static void GetText();.../* Class record constant */LabelClassRec labelClassRec = {{ /* core_class fields *//* superclass */ (WidgetClass)&coreClassRec,/* class_name */ "Label",/* widget_size */ sizeof(LabelRec),/* class_initialize */ClassInitialize,/* class_part_initialize */NULL,/* class_inited */False,/* initialize */ Initialize,/* initialize_hook */NULL,/* realize */ Realize,/* actions */ NULL,/* num_actions */ 0,/* resources */ resources,/* num_resources */XtNumber(resources),/* xrm_class */ NULLQUARK,/* compress_motion */True,/* compress_exposure */True,/* compress_enterleave */True,/* visible_interest */False,/* destroy */ NULL,/* resize */ Resize,/* expose */ Redisplay,/* set_values */ SetValues,/* set_values_hook */NULL,/* set_values_almost */XtInheritSetValuesAlmost,/* get_values_hook */NULL,/* accept_focus */NULL,/* version */ XtVersion,/* callback_offsets */NULL,/* tm_table */ NULL,/* query_geometry */XtInheritQueryGeometry,/* display_accelerator */NULL,/* extension */ NULL},{ /* Label_class fields *//* get_text */ GetText,/* set_text */ SetText,/* extension */ NULL}};/* Class record pointer */WidgetClass labelWidgetClass = (WidgetClass) &labelClassRec;/* New method access routines */void LabelSetText(w, text)Widget w;String text;{ Label WidgetClass lwc = (Label WidgetClass)XtClass(w);XtCheckSubclass(w, labelWidgetClass, NULL);*(lwc->label_class.set_text)(w, text)}/* Private procedures */...1.6.5. Widget Class and Superclass Look UpTo obtain the class of a widget, use XtClass.__│ WidgetClass XtClass(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ The XtClass function returns a pointer to the widget’s classstructure.To obtain the superclass of a widget, use XtSuperclass.__│ WidgetClass XtSuperclass(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ The XtSuperclass function returns a pointer to the widget’ssuperclass class structure.1.6.6. Widget Subclass VerificationTo check the subclass to which a widget belongs, useXtIsSubclass.__│ Boolean XtIsSubclass(w, widget_class)Widget w;WidgetClass widget_class;w Specifies the widget or object instance whoseclass is to be checked. Must be of class Objector any subclass thereof.widget_classSpecifies the widget class for which to test. Mustbe objectClass or any subclass thereof.│__ The XtIsSubclass function returns True if the class of thespecified widget is equal to or is a subclass of thespecified class. The widget’s class can be any number ofsubclasses down the chain and need not be an immediatesubclass of the specified class. Composite widgets thatneed to restrict the class of the items they contain can useXtIsSubclass to find out if a widget belongs to the desiredclass of objects.To test if a given widget belongs to a subclass of anIntrinsics-defined class, the Intrinsics define macros orfunctions equivalent to XtIsSubclass for each of thebuilt-in classes. These procedures are XtIsObject,XtIsRectObj, XtIsWidget, XtIsComposite, XtIsConstraint,XtIsShell, XtIsOverrideShell, XtIsWMShell, XtIsVendorShell,XtIsTransientShell, XtIsTopLevelShell, XtIsApplicationShell,and XtIsSessionShell.All these macros and functions have the same argumentdescription.__│ Boolean XtIs<class> (w)Widget w;w Specifies the widget or object instance whoseclass is to be checked. Must be of class Objector any subclass thereof.│__ These procedures may be faster than calling XtIsSubclassdirectly for the built-in classes.To check a widget’s class and to generate a debugging errormessage, use XtCheckSubclass, defined in <X11/IntrinsicP.h>:__│ void XtCheckSubclass(w, widget_class, message)Widget w;WidgetClass widget_class;String message;w Specifies the widget or object whose class is tobe checked. Must be of class Object or anysubclass thereof.widget_classSpecifies the widget class for which to test.Must be objectClass or any subclass thereof.message Specifies the message to be used.│__ The XtCheckSubclass macro determines if the class of thespecified widget is equal to or is a subclass of thespecified class. The widget’s class can be any number ofsubclasses down the chain and need not be an immediatesubclass of the specified class. If the specified widget’sclass is not a subclass, XtCheckSubclass constructs an errormessage from the supplied message, the widget’s actualclass, and the expected class and calls XtErrorMsg.XtCheckSubclass should be used at the entry point ofexported routines to ensure that the client has passed in avalid widget class for the exported operation.XtCheckSubclass is only executed when the module has beencompiled with the compiler symbol DEBUG defined; otherwise,it is defined as the empty string and generates no code.1.6.7. Superclass ChainingWhile most fields in a widget class structure areself-contained, some fields are linked to theircorresponding fields in their superclass structures. With alinked field, the Intrinsics access the field’s value onlyafter accessing its corresponding superclass value (calleddownward superclass chaining) or before accessing itscorresponding superclass value (called upward superclasschaining). The self-contained fields areIn all widget classes:class_nameclass_initializewidget_sizerealizevisible_interestresizeexposeaccept_focuscompress_motioncompress_exposurecompress_enterleaveset_values_almosttm_tableversionallocatedeallocateIn Composite widget classes:geometry_managerchange_managedinsert_childdelete_childaccepts_objectsallows_change_managed_setIn Constraint widget classes:constraint_sizeIn Shell widget classes:root_geometry_managerWith downward superclass chaining, the invocation of anoperation first accesses the field from the Object, RectObj,and Core class structures, then from the subclass structure,and so on down the class chain to that widget’s classstructure. These superclass-to-subclass fields areclass_part_initializeget_values_hookinitializeinitialize_hookset_valuesset_values_hookresourcesIn addition, for subclasses of Constraint, the followingfields of the ConstraintClassPart andConstraintClassExtensionRec structures are chained from theConstraint class down to the subclass:resourcesinitializeset_valuesget_values_hookWith upward superclass chaining, the invocation of anoperation first accesses the field from the widget classstructure, then from the superclass structure, and so on upthe class chain to the Core, RectObj, and Object classstructures. The subclass-to-superclass fields aredestroyactionsFor subclasses of Constraint, the following field ofConstraintClassPart is chained from the subclass up to theConstraint class:destroy1.6.8. Class Initialization: class_initialize andclass_part_initialize ProceduresMany class records can be initialized completely at compileor link time. In some cases, however, a class may need toregister type converters or perform other sorts of once-onlyruntime initialization.Because the C language does not have initializationprocedures that are invoked automatically when a programstarts up, a widget class can declare a class_initializeprocedure that will be automatically called exactly once bythe Intrinsics. A class initialization procedure pointer isof type XtProc:__│ typedef void (*XtProc)(void);│__ A widget class indicates that it has no class initializationprocedure by specifying NULL in the class_initialize field.In addition to the class initialization that is done exactlyonce, some classes perform initialization for fields intheir parts of the class record. These are performed notjust for the particular class, but for subclasses as well,and are done in the class’s class part initializationprocedure, a pointer to which is stored in theclass_part_initialize field. The class_part_initializeprocedure pointer is of type XtWidgetClassProc.__│ typedef void (*XtWidgetClassProc)(WidgetClass);WidgetClass widget_class;widget_classPoints to the class structure for the class beinginitialized.│__ During class initialization, the class part initializationprocedures for the class and all its superclasses are calledin superclass-to-subclass order on the class record. Theseprocedures have the responsibility of doing any dynamicinitializations necessary to their class’s part of therecord. The most common is the resolution of any inheritedmethods defined in the class. For example, if a widgetclass C has superclasses Core, Composite, A, and B, theclass record for C first is passed to Core ’sclass_part_initialize procedure. This resolves anyinherited Core methods and compiles the textualrepresentations of the resource list and action table thatare defined in the class record. Next, Composite’sclass_part_initialize procedure is called to initialize thecomposite part of C’s class record. Finally, theclass_part_initialize procedures for A, B, and C, in thatorder, are called. For further information, see Section1.6.9. Classes that do not define any new class fields orthat need no extra processing for them can specify NULL inthe class_part_initialize field.All widget classes, whether they have a class initializationprocedure or not, must start with their class_inited fieldFalse.The first time a widget of a class is created,XtCreateWidget ensures that the widget class and allsuperclasses are initialized, in superclass-to-subclassorder, by checking each class_inited field and, if it isFalse, by calling the class_initialize and theclass_part_initialize procedures for the class and all itssuperclasses. The Intrinsics then set the class_initedfield to a nonzero value. After the one-timeinitialization, a class structure is constant.The following example provides the class initializationprocedure for a Label class.static void ClassInitialize(){ XtSetTypeConverter(XtRString, XtRJustify, CvtStringToJustify,NULL, 0, XtCacheNone, NULL);}1.6.9. Initializing a Widget ClassA class is initialized when the first widget of that classor any subclass is created. To initialize a widget classwithout creating any widgets, use XtInitializeWidgetClass.__│ void XtInitializeWidgetClass(object_class)WidgetClass object_class;object_classSpecifies the object class to initialize. May beobjectClass or any subclass thereof.│__ If the specified widget class is already initialized,XtInitializeWidgetClass returns immediately.If the class initialization procedure registers typeconverters, these type converters are not available untilthe first object of the class or subclass is created orXtInitializeWidgetClass is called (see Section 9.6).1.6.10. Inheritance of Superclass OperationsA widget class is free to use any of its superclass’sself-contained operations rather than implementing its owncode. The most frequently inherited operations areexposerealizeinsert_childdelete_childgeometry_managerset_values_almostTo inherit an operation xyz, specify the constantXtInheritXyz in your class record.Every class that declares a new procedure in its widgetclass part must provide for inheriting the procedure in itsclass_part_initialize procedure. The chained operationsdeclared in Core and Constraint records are never inherited.Widget classes that do nothing beyond what their superclassdoes specify NULL for chained procedures in their classrecords.Inheriting works by comparing the value of the field with aknown, special value and by copying in the superclass’svalue for that field if a match occurs. This special value,called the inheritance constant, is usually the Intrinsicsinternal value _XtInherit cast to the appropriate type._XtInherit is a procedure that issues an error message if itis actually called.For example, CompositeP.h contains these definitions:#define XtInheritGeometryManager ((XtGeometryHandler) _XtInherit)#define XtInheritChangeManaged ((XtWidgetProc) _XtInherit)#define XtInheritInsertChild ((XtArgsProc) _XtInherit)#define XtInheritDeleteChild ((XtWidgetProc) _XtInherit)Composite’s class_part_initialize procedure begins asfollows:static void CompositeClassPartInitialize(widgetClass)WidgetClass widgetClass;{ CompositeWidgetClass wc = (CompositeWidgetClass)widgetClass;CompositeWidgetClass super = (CompositeWidgetClass)wc->core_class.superclass;if (wc->composite_class.geometry_manager == XtInheritGeometryManager) {wc->composite_class.geometry_manager = super->composite_class.geometry_manager;}if (wc->composite_class.change_managed == XtInheritChangeManaged) {wc->composite_class.change_managed = super->composite_class.change_managed;}...Nonprocedure fields may be inherited in the same manner asprocedure fields. The class may declare any reserved valueit wishes for the inheritance constant for its new fields.The following inheritance constants are defined:For Object:XtInheritAllocateXtInheritDeallocateFor Core:XtInheritRealizeXtInheritResizeXtInheritExposeXtInheritSetValuesAlmostXtInheritAcceptFocusXtInheritQueryGeometryXtInheritTranslationsXtInheritDisplayAcceleratorFor Composite:XtInheritGeometryManagerXtInheritChangeManagedXtInheritInsertChildXtInheritDeleteChildFor Shell:XtInheritRootGeometryManager1.6.11. Invocation of Superclass OperationsA widget sometimes needs to call a superclass operation thatis not chained. For example, a widget’s expose proceduremight call its superclass’s expose and then perform a littlemore work on its own. For example, a Composite class withpredefined managed children can implement insert_child byfirst calling its superclass’s insert_child and then callingXtManageChild to add the child to the managed set.NoteA class method should not use XtSuperclass butshould instead call the class method of its ownspecific superclass directly through thesuperclass record. That is, it should use its ownclass pointers only, not the widget’s classpointers, as the widget’s class may be a subclassof the class whose implementation is beingreferenced.This technique is referred to as enveloping the superclass’soperation.1.6.12. Class Extension RecordsIt may be necessary at times to add new fields to alreadyexisting widget class structures. To permit this to be donewithout requiring recompilation of all subclasses, the lastfield in a class part structure should be an extensionpointer. If no extension fields for a class have yet beendefined, subclasses should initialize the value of theextension pointer to NULL.If extension fields exist, as is the case with theComposite, Constraint, and Shell classes, subclasses canprovide values for these fields by setting the extensionpointer for the appropriate part in their class structure topoint to a statically declared extension record containingthe additional fields. Setting the extension field is nevermandatory; code that uses fields in the extension recordmust always check the extension field and take someappropriate default action if it is NULL.In order to permit multiple subclasses and libraries tochain extension records from a single extension field,extension records should be declared as a linked list, andeach extension record definition should contain thefollowing four fields at the beginning of the structuredeclaration:__│ struct {XtPointer next_extension;XrmQuark record_type;long version;Cardinal record_size;};next_extensionSpecifies the next record in the list, or NULL.record_type Specifies the particular structure declarationto which each extension record instanceconforms.version Specifies a version id symbolic constantsupplied by the definer of the structure.record_size Specifies the total number of bytes allocatedfor the extension record.│__ The record_type field identifies the contents of theextension record and is used by the definer of the record tolocate its particular extension record in the list. Therecord_type field is normally assigned the result ofXrmStringToQuark for a registered string constant. TheIntrinsics reserve all record type strings beginning withthe two characters ‘‘XT’’ for future standard uses. Thevalue NULLQUARK may also be used by the class part owner inextension records attached to its own class part extensionfield to identify the extension record unique to thatparticular class.The version field is an owner-defined constant that may beused to identify binary files that have been compiled withalternate definitions of the remainder of the extensionrecord data structure. The private header file for a widgetclass should provide a symbolic constant for subclasses touse to initialize this field. The record_size field valueincludes the four common header fields and should normallybe initialized with sizeof().Any value stored in the class part extension fields ofCompositeClassPart, ConstraintClassPart, or ShellClassPartmust point to an extension record conforming to thisdefinition.The Intrinsics provide a utility function for widget writersto locate a particular class extension record in a linkedlist, given a widget class and the offset of the extensionfield in the class record.To locate a class extension record, use XtGetClassExtension.__│ XtPointer XtGetClassExtension(object_class, byte_offset, type, version, record_size)WidgetClass object_class;Cardinal byte_offset;XrmQuark type;long version;Cardinal record_size;object_classSpecifies the object class containing theextension list to be searched.byte_offsetSpecifies the offset in bytes from the base of theclass record of the extension field to besearched.type Specifies the record_type of the class extensionto be located.version Specifies the minimum acceptable version of theclass extension required for a match.record_sizeSpecifies the minimum acceptable length of theclass extension record required for a match, or 0.│__ The list of extension records at the specified offset in thespecified object class will be searched for a match on thespecified type, a version greater than or equal to thespecified version, and a record size greater than or equalthe specified record_size if it is nonzero.XtGetClassExtension returns a pointer to a matchingextension record or NULL if no match is found. The returnedextension record must not be modified or freed by the callerif the caller is not the extension owner.1
2.1. Initializing the X ToolkitBefore an application can call any Intrinsics function otherthan XtSetLanguageProc and XtToolkitThreadInitialize, itmust initialize the Intrinsics by using• XtToolkitInitialize, which initializes the Intrinsicsinternals• XtCreateApplicationContext, which initializes theper-application state• XtDisplayInitialize or XtOpenDisplay, which initializesthe per-display state• XtAppCreateShell, which creates the root of a widgettreeOr an application can call the convenience procedureXtOpenApplication, which combines the functions of thepreceding procedures. An application wishing to use theANSI C locale mechanism should call XtSetLanguageProc priorto calling XtDisplayInitialize, XtOpenDisplay,XtOpenApplication, or XtAppInitialize.Multiple instances of X Toolkit applications may beimplemented in a single address space. Each instance needsto be able to read input and dispatch events independentlyof any other instance. Further, an application instance mayneed multiple display connections to have widgets onmultiple displays. From the application’s point of view,multiple display connections usually are treated together asa single unit for purposes of event dispatching. Toaccommodate both requirements, the Intrinsics defineapplication contexts, each of which provides the informationneeded to distinguish one application instance from another.The major component of an application context is a list ofone or more X Display pointers for that application. TheIntrinsics handle all display connections within a singleapplication context simultaneously, handling input in around-robin fashion. The application context typeXtAppContext is opaque to clients.To initialize the Intrinsics internals, useXtToolkitInitialize.__│ void XtToolkitInitialize()│__ If XtToolkitInitialize was previously called, it returnsimmediately. When XtToolkitThreadInitialize is calledbefore XtToolkitInitialize, the latter is protected againstsimultaneous activation by multiple threads.To create an application context, useXtCreateApplicationContext.__│ XtAppContext XtCreateApplicationContext()│__ The XtCreateApplicationContext function returns anapplication context, which is an opaque type. Everyapplication must have at least one application context.To destroy an application context and close any remainingdisplay connections in it, use XtDestroyApplicationContext.__│ void XtDestroyApplicationContext(app_context)XtAppContext app_context;app_contextSpecifies the application context.│__ The XtDestroyApplicationContext function destroys thespecified application context. If called from within anevent dispatch (for example, in a callback procedure),XtDestroyApplicationContext does not destroy the applicationcontext until the dispatch is complete.To get the application context in which a given widget wascreated, use XtWidgetToApplicationContext.__│ XtAppContext XtWidgetToApplicationContext(w)Widget w;w Specifies the widget for which you want theapplication context. Must be of class Object orany subclass thereof.│__ The XtWidgetToApplicationContext function returns theapplication context for the specified widget.To initialize a display and add it to an applicationcontext, use XtDisplayInitialize.__│ void XtDisplayInitialize(app_context, display, application_name, application_class,options, num_options, argc, argv)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 displayconnection. Note that a single displayconnection can be in at most one applicationcontext.application_nameSpecifies the name of the applicationinstance.application_classSpecifies the class name of this application,which is usually the generic name for allinstances of this application.options Specifies how to parse the command line forany application-specific resources. Theoptions argument is passed as a parameter toXrmParseCommand. For further information, seeSection 15.9 in Xlib — C Language X Interfaceand Section 2.4 of this specification.num_options Specifies the number of entries in the optionslist.argc Specifies a pointer to the number of commandline parameters.argv Specifies the list of command line parameters.│__ The XtDisplayInitialize function retrieves the languagestring to be used for the specified display (see Section11.11), calls the language procedure (if set) with thatlanguage string, builds the resource database for thedefault screen, calls the Xlib XrmParseCommand function toparse the command line, and performs other per-displayinitialization. After XrmParseCommand has been called, argcand argv contain only those parameters that were not in thestandard option table or in the table specified by theoptions argument. If the modified argc is not zero, mostapplications simply print out the modified argv along with amessage listing the allowable options. On POSIX-basedsystems, the application name is usually the final componentof argv[0]. If the synchronous resource is True,XtDisplayInitialize calls the Xlib XSynchronize function toput Xlib into synchronous mode for this display connectionand any others currently open in the application context.See Sections 2.3 and 2.4 for details on theapplication_name, application_class, options, andnum_options arguments.XtDisplayInitialize calls XrmSetDatabase to associate theresource database of the default screen with the displaybefore returning.To open a display, initialize it, and then add it to anapplication context, use XtOpenDisplay.__│ Display *XtOpenDisplay(app_context, display_string, application_name, application_class,options, num_options, argc, argv)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_stringSpecifies the display string, or NULL.application_nameSpecifies the name of the applicationinstance, or NULL.application_classSpecifies the class name of this application,which is usually the generic name for allinstances of this application.options Specifies how to parse the command line forany application-specific resources. Theoptions argument is passed as a parameter toXrmParseCommand.num_options Specifies the number of entries in the optionslist.argc Specifies a pointer to the number of commandline parameters.argv Specifies the list of command line parameters.│__ The XtOpenDisplay function calls XOpenDisplay with thespecified display_string. If display_string is NULL,XtOpenDisplay uses the current value of the −display optionspecified in argv. If no display is specified in argv, theuser’s default display is retrieved from the environment.On POSIX-based systems, this is the value of the DISPLAYenvironment variable.If this succeeds, XtOpenDisplay then callsXtDisplayInitialize and passes it the opened display and thevalue of the −name option specified in argv as theapplication name. If no −name option is specified andapplication_name is non-NULL, application_name is passed toXtDisplayInitialize. If application_name is NULL and if theenvironment variable RESOURCE_NAME is set, the value ofRESOURCE_NAME is used. Otherwise, the application name isthe name used to invoke the program. On implementationsthat conform to ANSI C Hosted Environment support, theapplication name will be argv[0] less any directory and filetype components, that is, the final component of argv[0], ifspecified. If argv[0] does not exist or is the emptystring, the application name is ‘‘main’’. XtOpenDisplayreturns the newly opened display or NULL if it failed.See Section 7.12 for information regarding the use ofXtOpenDisplay in multiple threads.To close a display and remove it from an applicationcontext, use XtCloseDisplay.__│ void XtCloseDisplay(display)Display *display;display Specifies the display.│__ The XtCloseDisplay function calls XCloseDisplay with thespecified display as soon as it is safe to do so. If calledfrom within an event dispatch (for example, a callbackprocedure), XtCloseDisplay does not close the display untilthe dispatch is complete. Note that applications need onlycall XtCloseDisplay if they are to continue executing afterclosing the display; otherwise, they should callXtDestroyApplicationContext.See Section 7.12 for information regarding the use ofXtCloseDisplay in multiple threads.2.2. Establishing the LocaleResource databases are specified to be created in thecurrent process locale. During display initialization priorto creating the per-screen resource database, the Intrinsicswill call out to a specified application procedure to setthe locale according to options found on the command line orin the per-display resource specifications.The callout procedure provided by the application is of typeXtLanguageProc.__│ typedef String (*XtLanguageProc)(Display*, String, XtPointer);Display *display;String language;XtPointer client_data;display Passes the display.language Passes the initial language value obtained fromthe command line or server per-display resourcespecifications.client_dataPasses the additional client data specified in thecall to XtSetLanguageProc.│__ The language procedure allows an application to set thelocale to the value of the language resource determined byXtDisplayInitialize. The function returns a new languagestring that will be subsequently used by XtDisplayInitializeto establish the path for loading resource files. Thereturned string will be copied by the Intrinsics into newmemory.Initially, no language procedure is set by the Intrinsics.To set the language procedure for use byXtDisplayInitialize, use XtSetLanguageProc.__│ XtLanguageProc XtSetLanguageProc(app_context, proc, client_data)XtAppContext app_context;XtLanguageProc proc;XtPointer client_data;app_contextSpecifies the application context in which thelanguage procedure is to be used, or NULL.proc Specifies the language procedure.client_dataSpecifies additional client data to be passed tothe language procedure when it is called.│__ XtSetLanguageProc sets the language procedure that will becalled from XtDisplayInitialize for all subsequent Displaysinitialized in the specified application context. Ifapp_context is NULL, the specified language procedure isregistered in all application contexts created by thecalling process, including any future application contextsthat may be created. If proc is NULL, a default languageprocedure is registered. XtSetLanguageProc returns thepreviously registered language procedure. If a languageprocedure has not yet been registered, the return value isunspecified, but if this return value is used in asubsequent call to XtSetLanguageProc, it will cause thedefault language procedure to be registered.The default language procedure does the following:• Sets the locale according to the environment. On ANSIC-based systems this is done by calling setlocale(LC_ALL, language ). If an error is encountered, awarning message is issued with XtWarning.• Calls XSupportsLocale to verify that the current localeis supported. If the locale is not supported, awarning message is issued with XtWarning and the localeis set to ‘‘C’’.• Calls XSetLocaleModifiers specifying the empty string.• Returns the value of the current locale. On ANSIC-based systems this is the return value from a finalcall to setlocale( LC_ALL, NULL ).A client wishing to use this mechanism to establish localecan do so by calling XtSetLanguageProc prior toXtDisplayInitialize, as in the following example.Widget top;XtSetLanguageProc(NULL, NULL, NULL);top = XtOpenApplication(...);...2.3. Loading the Resource DatabaseThe XtDisplayInitialize function first determines thelanguage string to be used for the specified display. Itthen creates a resource database for the default screen ofthe display by combining the following sources in order,with the entries in the first named source having highestprecedence:• Application command line (argc, argv).• Per-host user environment resource file on the localhost.• Per-screen resource specifications from the server.• Per-display resource specifications from the server orfromthe user preference file on the local host.• Application-specific user resource file on the localhost.• Application-specific class resource file on the localhost.When the resource database for a particular screen on thedisplay is needed (either internally, or whenXtScreenDatabase is called), it is created in the followingmanner using the sources listed above in the same order:• A temporary database, the ‘‘server resource database’’,is created from the string returned byXResourceManagerString or, if XResourceManagerStringreturns NULL, the contents of a resource file in theuser’s home directory. On POSIX-based systems, theusual name for this user preference resource file is$HOME/.Xdefaults.• If a language procedure has been set,XtDisplayInitialize first searches the command line forthe option ‘‘-xnlLanguage’’, or for a -xrm option thatspecifies the xnlLanguage/XnlLanguage resource, asspecified by Section 2.4. If such a resource is found,the value is assumed to be entirely in XPCS, the XPortable Character Set. If neither option is specifiedon the command line, XtDisplayInitialize queries theserver resource database (which is assumed to beentirely in XPCS) for the resource name.xnlLanguage,class Class.XnlLanguage where name and Class are theapplication_name and application_class specified toXtDisplayInitialize. The language procedure is theninvoked with the resource value if found, else theempty string. The string returned from the languageprocedure is saved for all future references in theIntrinsics that require the per-display languagestring.• The screen resource database is initialized by parsingthe command line in the manner specified by Section2.4.• If a language procedure has not been set, the initialdatabase is then queried for the resourcename.xnlLanguage, class Class.XnlLanguage as specifiedabove. If this database query fails, the serverresource database is queried; if this query also fails,the language is determined from the environment; onPOSIX-based systems, this is done by retrieving thevalue of the LANG environment variable. If no languagestring is found, the empty string is used. Thislanguage string is saved for all future references inthe Intrinsics that require the per-display languagestring.• After determining the language string, the user’senvironment resource file is then merged into theinitial resource database if the file exists. Thisfile is user-, host-, and process-specific and isexpected to contain user preferences that are tooverride those specifications in the per-display andper-screen resources. On POSIX-based systems, theuser’s environment resource file name is specified bythe value of the XENVIRONMENT environment variable. Ifthis environment variable does not exist, the user’shome directory is searched for a file named.Xdefaults-host, where host is the host name of themachine on which the application is running.• The per-screen resource specifications are then mergedinto the screen resource database, if they exist.These specifications are the string returned byXScreenResourceString for the respective screen and areowned entirely by the user.• Next, the server resource database created earlier ismerged into the screen resource database. The serverproperty, and corresponding user preference file, areowned and constructed entirely by the user.• The application-specific user resource file from thelocal host is then merged into the screen resourcedatabase. This file contains user customizations andis stored in a directory owned by the user. Either theuser or the application or both can store resourcespecifications in the file. Each should be prepared tofind and respect entries made by the other. The filename is found by calling XrmSetDatabase with thecurrent screen resource database, after preserving theoriginal display-associated database, then callingXtResolvePathname with the parameters (display, NULL,NULL, NULL, path, NULL, 0, NULL), where path is definedin an operating-system-specific way. On POSIX-basedsystems, path is defined to be the value of theenvironment variable XUSERFILESEARCHPATH if this isdefined. If XUSERFILESEARCHPATH is not defined, animplementation-dependent default value is used. Thisdefault value is constrained in the following manner:− If the environment variable XAPPLRESDIR is notdefined, the default XUSERFILESEARCHPATH mustcontain at least six entries. These entries mustcontain $HOME as the directory prefix, plus thefollowing substitutions:1. %C, %N, %L or %C, %N, %l, %t, %c2. %C, %N, %l3. %C, %N4. %N, %L or %N, %l, %t, %c5. %N, %l6. %NThe order of these six entries within the path mustbe as given above. The order and use ofsubstitutions within a given entry areimplementation-dependent.− If XAPPLRESDIR is defined, the defaultXUSERFILESEARCHPATH must contain at least sevenentries. These entries must contain the followingdirectory prefixes and substitutions:1. $XAPPLRESDIR with %C, %N, %L or %C, %N, %l, %t, %c2. $XAPPLRESDIR with %C, %N, %l3. $XAPPLRESDIR with %C, %N4. $XAPPLRESDIR with %N, %L or %N, %l, %t, %c5. $XAPPLRESDIR with %N, %l6. $XAPPLRESDIR with %N7. $HOME with %NThe order of these seven entries within the pathmust be as given above. The order and use ofsubstitutions within a given entry areimplementation-dependent.• Last, the application-specific class resource file fromthe local host is merged into the screen resourcedatabase. This file is owned by the application and isusually installed in a system directory when theapplication is installed. It may contain sitewidecustomizations specified by the system manager. Thename of the application class resource file is found bycalling XtResolvePathname with the parameters (display,‘‘app-defaults’’, NULL, NULL, NULL, NULL, 0, NULL).This file is expected to be provided by the developerof the application and may be required for theapplication to function properly. A simple applicationthat wants to be assured of having a minimal set ofresources in the absence of its class resource file candeclare fallback resource specifications withXtAppSetFallbackResources. Note that the customizationsubstitution string is retrieved dynamically byXtResolvePathname so that the resolved file name of theapplication class resource file can be affected by anyof the earlier sources for the screen resourcedatabase, even though the contents of the classresource file have lowest precedence. After callingXtResolvePathname, the original display-associateddatabase is restored.To obtain the resource database for a particular screen, useXtScreenDatabase.__│ XrmDatabase XtScreenDatabase(screen)Screen *screen;screen Specifies the screen whose resource database is tobe returned.│__ The XtScreenDatabase function returns the fully mergedresource database as specified above, associated with thespecified screen. If the specified screen does not belongto a Display initialized by XtDisplayInitialize, the resultsare undefined.To obtain the default resource database associated with aparticular display, use XtDatabase.__│ XrmDatabase XtDatabase(display)Display *display;display Specifies the display.│__ The XtDatabase function is equivalent to XrmGetDatabase. Itreturns 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 beused to initialize the resource database if noapplication-specific class resource file is found (the lastof the six sources listed above), useXtAppSetFallbackResources.__│ void XtAppSetFallbackResources(app_context, specification_list)XtAppContext app_context;String *specification_list;app_context Specifies the application context in which thefallback specifications will be used.specification_listSpecifies a NULL-terminated list of resourcespecifications to preload the database, or NULL.│__ Each entry in specification_list points to a string in theformat of XrmPutLineResource. Following a call toXtAppSetFallbackResources, when a resource database is beingcreated for a particular screen and the Intrinsics are notable to find or read an application-specific class resourcefile according to the rules given above and ifspecification_list is not NULL, the resource specificationsin specification_list will be merged into the screenresource database in place of the application-specific classresource file. XtAppSetFallbackResources is not required tocopy specification_list; the caller must ensure that thecontents of the list and of the strings addressed by thelist remain valid until all displays are initialized oruntil XtAppSetFallbackResources is called again. The valueNULL for specification_list removes any previous fallbackresource specification for the application context. Theintended use for fallback resources is to provide a minimalnumber of resources that will make the application usable(or at least terminate with helpful diagnostic messages)when some problem exists in finding and loading theapplication defaults file.2.4. Parsing the Command LineThe XtOpenDisplay function first parses the command line forthe following options:−display Specifies the display name for XOpenDisplay.−name Sets the resource name prefix, which overrides theapplication name passed to XtOpenDisplay.−xnllanguageSpecifies the initial language string forestablishing locale and for finding applicationclass resource files.XtDisplayInitialize has a table of standard command lineoptions that are passed to XrmParseCommand for addingresources to the resource database, and it takes as aparameter additional application-specific resourceabbreviations. The format of this table is described inSection 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:Note that any unique abbreviation for an option name in thestandard table or in the application table is accepted.If reverseVideo is True, the values of XtDefaultForegroundand XtDefaultBackground are exchanged for all screens on theDisplay.The value of the synchronous resource specifies whether ornot Xlib is put into synchronous mode. If a value is foundin the resource database during display initialization,XtDisplayInitialize makes a call to XSynchronize for alldisplay connections currently open in the applicationcontext. Therefore, when multiple displays are initializedin the same application context, the most recent valuespecified for the synchronous resource is used for alldisplays in the application context.The value of the selectionTimeout resource applies to alldisplays opened in the same application context. Whenmultiple displays are initialized in the same applicationcontext, the most recent value specified is used for alldisplays in the application context.The −xrm option provides a method of setting any resource inan application. The next argument should be a quoted stringidentical in format to a line in the user resource file.For example, to give a red background to all command buttonsin an application named xmh, you can start it up asxmh −xrm ’xmh*Command.background: red’When it parses the command line, XtDisplayInitialize mergesthe application option table with the standard option tablebefore calling the Xlib XrmParseCommand function. An entryin the application table with the same name as an entry inthe standard table overrides the standard table entry. Ifan option name is a prefix of another option name, bothnames are kept in the merged table. The Intrinsics reserveall option names beginning with the characters ‘‘-xt’’ forfuture standard uses.2.5. Creating WidgetsThe creation of widget instances is a three-phase process:1. The widgets are allocated and initialized withresources and are optionally added to the managedsubset of their parent.2. All composite widgets are notified of their managedchildren 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 callsXtCreateWidgetfor all its widgets and adds some (usually, most or all) of its widgetsto their respective parents’ managed set by callingXtManageChild.To avoid an O(n2) creation process where each composite widgetlays itself out each time a widget is created and managed,parent widgets are not notified of changes in their managed setduring this phase.After all widgets have been created, the application callsXtRealizeWidget with the top-level widget to execute thesecond and third phases. XtRealizeWidget first recursivelytraverses the widget tree in a postorder (bottom-up)traversal and then notifies each composite widget with oneor more managed children by means of its change_managedprocedure.Notifying a parent about its managed set involves geometrylayout and possibly geometry negotiation. A parent dealswith constraints on its size imposed from above (forexample, when a user specifies the application window size)and suggestions made from below (for example, when aprimitive child computes its preferred size). Onedifference between the two can cause geometry changes toripple in both directions through the widget tree. Theparent may force some of its children to change size andposition and may issue geometry requests to its own parentin order to better accommodate all its children. You cannotpredict where anything will go on the screen until thisprocess finishes.Consequently, in the first and second phases, no X windowsare actually created, because it is likely that they willget moved around after creation. This avoids unnecessaryrequests to the X server.Finally, XtRealizeWidget starts the third phase by making apreorder (top-down) traversal of the widget tree, allocatesan X window to each widget by means of its realizeprocedure, and finally maps the widgets that are managed.2.5.1. Creating and Merging Argument ListsMany Intrinsics functions may be passed pairs of resourcenames and values. These are passed as an arglist, a pointerto 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 thesize of an XtArgVal, the resource value is stored directlyin value; otherwise, a pointer to it is stored in value.To set values in an ArgList, use XtSetArg.__│ void XtSetArg(arg, name, value)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 fitin an XtArgVal, else the address.│__ The XtSetArg function is usually used in a highly stylizedmanner to minimize the probability of making a mistake; forexample: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 theargument list and use XtNumber:static Args args[] = {{XtNheight, (XtArgVal) 100},{XtNwidth, (XtArgVal) 200},};XtSetValues(Widget, args, XtNumber(args));Note that you should not use expressions with side effectssuch as auto-increment or auto-decrement within the firstargument to XtSetArg. XtSetArg can be implemented as amacro that evaluates the first argument twice.To merge two arglist arrays, use XtMergeArgLists.__│ ArgList XtMergeArgLists(args1, num_args1, args2, num_args2)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 firstargument list.args2 Specifies the second argument list.num_args2 Specifies the number of entries in the secondargument list.│__ The XtMergeArgLists function allocates enough storage tohold the combined arglist arrays and copies them into it.Note that it does not check for duplicate entries. Thelength of the returned list is the sum of the lengths of thespecified lists. When it is no longer needed, free thereturned storage by using XtFree.All Intrinsics interfaces that require ArgList argumentshave analogs conforming to the ANSI C variable argument list(traditionally called ‘‘varargs’’) calling convention. Thename of the analog is formed by prefixing ‘‘Va’’ to the nameof the corresponding ArgList procedure; e.g.,XtVaCreateWidget. Each procedure named XtVasomething takesas its last arguments, in place of the correspondingArgList/ Cardinal parameters, a variable parameter list ofresource name and value pairs where each name is of typeString and each value is of type XtArgVal. The end of thelist is identified by a name entry containing NULL.Developers writing in the C language wishing to passresource name and value pairs to any of these interfaces mayuse 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 resourcename, then the following four arguments are interpreted as aname/type/value/size tuple where name is of type String,type is of type String, value is of type XtArgVal, and sizeis of type int. When a varargs list containing XtVaTypedArgis processed, a resource type conversion (see Section 9.6)is performed if necessary to convert the value into theformat required by the associated resource. If type isXtRString, then value contains a pointer to the string andsize contains the number of bytes allocated, including thetrailing null byte. If type is not XtRString, then if sizeis less than or equal to sizeof(XtArgVal), the value shouldbe the data cast to the type XtArgVal, otherwise value is apointer to the data. If the type conversion fails for anyreason, a warning message is issued and the list entry isskipped.__│ #define XtVaNestedList "XtVaNestedList"│__ If the name XtVaNestedList is specified in place of aresource name, then the following argument is interpreted asan XtVarArgsList value, which specifies another varargs listthat is logically inserted into the original list at thepoint of declaration. The end of the nested list isidentified with a name entry containing NULL. Varargs listsmay nest to any depth.To dynamically allocate a varargs list for use withXtVaNestedList in multiple calls, use XtVaCreateArgsList.__│ typedef XtPointer XtVarArgsList;XtVarArgsList XtVaCreateArgsList(unused, ...)XtPointer unused;unused This argument is not currently used and must bespecified as NULL.... Specifies a variable parameter list of resourcename and value pairs.│__ The XtVaCreateArgsList function allocates memory and copiesits arguments into a single list pointer, which may be usedwith XtVaNestedList. The end of both lists is identified bya name entry containing NULL. Any entries of typeXtVaTypedArg are copied as specified without applyingconversions. Data passed by reference (including Strings)are not copied, only the pointers themselves; the callermust ensure that the data remain valid for the lifetime ofthe created varargs list. The list should be freed usingXtFree when no longer needed.Use of resource files and of the resource database isgenerally encouraged over lengthy arglist or varargs listswhenever possible in order to permit modification withoutrecompilation.2.5.2. Creating a Widget InstanceTo create an instance of a widget, use XtCreateWidget.__│ Widget XtCreateWidget(name, object_class, parent, args, num_args)String name;WidgetClass object_class;Widget parent;ArgList args;Cardinal num_args;name Specifies the resource instance name for thecreated widget, which is used for retrievingresources and, for that reason, should not be thesame as any other widget that is a child of thesame parent.object_classSpecifies the widget class pointer for the createdobject. Must be objectClass or any subclassthereof.parent Specifies the parent widget. Must be of classObject or any subclass thereof.args Specifies the argument list to override any otherresource specifications.num_args Specifies the number of entries in the argumentlist.│__ The XtCreateWidget function performs all the boilerplateoperations of widget creation, doing the following in order:• Checks to see if the class_initialize procedure hasbeen called for this class and for all superclassesand, if not, calls those necessary in asuperclass-to-subclass order.• If the specified class is not coreWidgetClass or asubclass thereof, and the parent’s class is a subclassof compositeWidgetClass and either no extension recordin the parent’s composite class part extension fieldexists with the record_type NULLQUARK or theaccepts_objects field in the extension record is False,XtCreateWidget issues a fatal error; see Section 3.1and Chapter 12.• If the specified class contains an extension record inthe object class part extension field with record_typeNULLQUARK and the allocate field is not NULL, theprocedure is invoked to allocate memory for the widgetinstance. If the parent is a member of the classconstraintWidgetClass, the procedure also allocatesmemory for the parent’s constraints and stores theaddress of this memory into the constraints field. Ifno allocate procedure is found, the Intrinsics allocatememory for the widget and, when applicable, theconstraints, 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 resourcelists specified for this class and all superclasses.• If the parent is a member of the classconstraintWidgetClass, initializes the resource fieldsof the constraints record by using theConstraintClassPart resource lists specified for theparent’s class and all superclasses up toconstraintWidgetClass.• Calls the initialize procedures for the widget startingat the Object initialize procedure on down to thewidget’s initialize procedure.• If the parent is a member of the classconstraintWidgetClass, calls the ConstraintClassPartinitialize procedures, starting atconstraintWidgetClass on down to the parent’sConstraintClassPart initialize procedure.• If the parent is a member of the classcompositeWidgetClass, puts the widget into its parent’schildren list by calling its parent’s insert_childprocedure. For further information, see Section 3.1.To create an instance of a widget using varargs lists, useXtVaCreateWidget.__│ Widget XtVaCreateWidget(name, object_class, parent, ...)String name;WidgetClass object_class;Widget parent;name Specifies the resource name for the createdwidget.object_classSpecifies the widget class pointer for the createdobject. Must be objectClass or any subclassthereof.parent Specifies the parent widget. Must be of classObject or any subclass thereof.... Specifies the variable argument list to overrideany other resource specifications.│__ The XtVaCreateWidget procedure is identical in function toXtCreateWidget with the args and num_args parametersreplaced by a varargs list, as described in Section 2.5.1.2.5.3. Creating an Application Shell InstanceAn application can have multiple top-level widgets, each ofwhich specifies a unique widget tree that can potentially beon different screens or displays. An application usesXtAppCreateShell to create independent widget trees.__│ Widget XtAppCreateShell(name, application_class, widget_class, display, args, num_args)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 toXtDisplayInitialize is used.application_classSpecifies the resource class string to be usedin place of the widget class_name string whenwidget_class is applicationShellWidgetClass or asubclass thereof.widget_classSpecifies the widget class for the top-levelwidget (e.g., applicationShellWidgetClass).display Specifies the display for the default screen andfor the resource database used to retrieve theshell widget resources.args Specifies the argument list to override anyother resource specifications.num_args Specifies the number of entries in the argumentlist.│__ The XtAppCreateShell function creates a new shell widgetinstance as the root of a widget tree. The screen resourcefor this widget is determined by first scanning args for theXtNscreen argument. If no XtNscreen argument is found, theresource database associated with the default screen of thespecified display is queried for the resource name.screen,class Class.Screen where Class is the specifiedapplication_class if widget_class isapplicationShellWidgetClass or a subclass thereof. Ifwidget_class is not applicationShellWidgetClass or asubclass, Class is the class_name field from theCoreClassPart of the specified widget_class. If this queryfails, the default screen of the specified display is used.Once the screen is determined, the resource databaseassociated with that screen is used to retrieve allremaining resources for the shell widget not specified inargs. The widget name and Class as determined above areused as the leftmost (i.e., root) components in all fullyqualified resource names for objects within this widgettree.If the specified widget class is a subclass of WMShell, thename and Class as determined above will be stored into theWM_CLASS property on the widget’s window when it becomesrealized. If the specified widget_class isapplicationShellWidgetClass or a subclass thereof, theWM_COMMAND property will also be set from the values of theXtNargv 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 andcreate the others as pop-up children of it by usingXtCreatePopupShell.• Have all shells as pop-up children of an unrealizedtop-level shell.The first method, which is best used when there is a clearchoice for what is the main window, leads to resourcespecifications 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 widgettree using varargs lists, use XtVaAppCreateShell.__│ Widget XtVaAppCreateShell(name, application_class, widget_class, display, ...)String name;String application_class;WidgetClass widget_class;Display *display;name Specifies the instance name of the shellwidget. If name is NULL, the applicationname passed to XtDisplayInitialize is used.application_classSpecifies the resource class string to beused in place of the widget class_name stringwhen widget_class isapplicationShellWidgetClass or a subclassthereof.widget_class Specifies the widget class for the top-levelwidget.display Specifies the display for the default screenand for the resource database used toretrieve the shell widget resources.... Specifies the variable argument list tooverride any other resource specifications.│__ The XtVaAppCreateShell procedure is identical in function toXtAppCreateShell with the args and num_args parametersreplaced by a varargs list, as described in Section 2.5.1.2.5.4. Convenience Procedure to Initialize an ApplicationTo initialize the Intrinsics internals, create anapplication context, open and initialize a display, andcreate the initial root shell instance, an application mayuse XtOpenApplication or XtVaOpenApplication.__│ Widget XtOpenApplication(app_context_return, application_class, options, num_options,argc_in_out, argv_in_out, fallback_resources, widget_class, args, num_args)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_returnReturns the application context, if non-NULL.application_classSpecifies 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 commandline arguments.argv_in_out Specifies a pointer to the command linearguments.fallback_resourcesSpecifies resource values to be used if theapplication class resource file cannot beopened or read, or NULL.widget_class Specifies the class of the widget to becreated. Must be shellWidgetClass or asubclass.args Specifies the argument list to override anyother resource specifications for the createdshell widget.num_args Specifies the number of entries in theargument list.│__ The XtOpenApplication function calls XtToolkitInitializefollowed by XtCreateApplicationContext, then callsXtOpenDisplay with display_string NULL and application_nameNULL, and finally calls XtAppCreateShell with name NULL, thespecified widget_class, an argument list and count, andreturns the created shell. The recommended widget_class issessionShellWidgetClass. The argument list and count arecreated by merging the specified args and num_args with alist containing the specified argc and argv. The modifiedargc and argv returned by XtDisplayInitialize are returnedin argc_in_out and argv_in_out. If app_context_return isnot NULL, the created application context is also returned.If the display specified by the command line cannot beopened, an error message is issued and XtOpenApplicationterminates the application. If fallback_resources isnon-NULL, XtAppSetFallbackResources is called with the valueprior to calling XtOpenDisplay.__│ Widget XtVaOpenApplication(app_context_return, application_class, options, num_options,argc_in_out, argv_in_out, fallback_resources, widget_class, ...)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_returnReturns the application context, if non-NULL.application_classSpecifies 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 commandline arguments.argv_in_out Specifies the command line arguments array.fallback_resourcesSpecifies resource values to be used if theapplication class resource file cannot beopened, or NULL.widget_class Specifies the class of the widget to becreated. Must be shellWidgetClass or asubclass.... Specifies the variable argument list tooverride any other resource specificationsfor the created shell.│__ The XtVaOpenApplication procedure is identical in functionto XtOpenApplication with the args and num_args parametersreplaced by a varargs list, as described in Section 2.5.1.2.5.5. Widget Instance Allocation: The allocate ProcedureA widget class may optionally provide an instance allocationprocedure in the ObjectClassExtension record.When the call to create a widget includes a varargs listcontaining XtVaTypedArg, these arguments will be passed tothe allocation procedure in an XtTypedArgList.__│ typedef struct {String name;String type;XtArgVal value;int size;} XtTypedArg, *XtTypedArgList;│__ The allocate procedure pointer in the ObjectClassExtensionrecord is of type XtAllocateProc.__│ typedef void (*XtAllocateProc)(WidgetClass, Cardinal*, Cardinal*, ArgList, Cardinal*,XtTypedArgList, Cardinal*, Widget*, XtPointer*);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 toallocate.constraint_sizeSpecifies the size of the constraint recordto allocate, or 0.more_bytes Specifies the number of auxiliary bytes ofmemory to allocate.args Specifies the argument list as given in thecall to create the widget.num_args Specifies the number of arguments.typed_args Specifies the list of typed arguments givenin the call to create the widget.num_typed_args Specifies the number of typed arguments.new_return Returns a pointer to the newly allocatedinstance, or NULL in case of error.more_bytes_returnReturns the auxiliary memory if it wasrequested, or NULL if requested and an erroroccurred; otherwise, unchanged.│__ At widget allocation time, if an extension record withrecord_type equal to NULLQUARK is located through the objectclass part extension field and the allocate field is notNULL, the XtAllocateProc will be invoked to allocate memoryfor the widget. If no ObjectClassPart extension record isdeclared with record_type equal to NULLQUARK, thenXtInheritAllocate and XtInheritDeallocate are assumed. Ifno XtAllocateProc is found, the Intrinsics will allocatememory for the widget.An XtAllocateProc must perform the following:• Allocate memory for the widget instance and return itin new_return. The memory must be at leastwc->core_class.widget_size bytes in length, double-wordaligned.• Initialize the core.constraints field in the instancerecord to NULL or to point to a constraint record. Ifconstraint_size is not 0, the procedure must allocatememory for the constraint record. The memory must bedouble-word aligned.• If more_bytes is not 0, then the address of a block ofmemory at least more_bytes in size, double-wordaligned, must be returned in the more_bytes_returnparameter, or NULL to indicate an error.A class allocation procedure that envelops the allocationprocedure of a superclass must rely on the envelopedprocedure to perform the instance and constraint allocation.Allocation procedures should refrain from initializingfields in the widget record except to store pointers tonewly allocated additional memory. Under no circumstancesshould an allocation procedure that envelopes its superclassallocation procedure modify fields in the instance part ofany superclass.2.5.6. Widget Instance Initialization: The initializeProcedureThe initialize procedure pointer in a widget class is oftype XtInitProc.__│ typedef void (*XtInitProc)(Widget, Widget, ArgList, Cardinal*);Widget request;Widget new;ArgList args;Cardinal *num_args;request Specifies a copy of the widget with resourcevalues as requested by the argument list, theresource database, and the widget defaults.new Specifies the widget with the new values, bothresource and nonresource, that are actuallyallowed.args Specifies the argument list passed by the client,for computing derived resource values. If theclient created the widget using a varargs form,any resources specified via XtVaTypedArg areconverted to the widget representation and thelist is transformed into the ArgList format.num_args Specifies the number of entries in the argumentlist.│__ An initialization procedure performs the following:• Allocates space for and copies any resources referencedby address that the client is allowed to free or modifyafter the widget has been created. For example, if awidget has a field that is a String, it may choose notto depend on the characters at that address remainingconstant but dynamically allocate space for the stringand copy it to the new space. Widgets that do not copyone or more resources referenced by address shouldclearly so state in their user documentation.NoteIt is not necessary to allocate space for orto copy callback lists.• Computes values for unspecified resource fields. Forexample, if width and height are zero, the widgetshould compute an appropriate width and height based onits other resources. NoteA widget may directly assign only its ownwidth and height within the initialize,initialize_hook, set_values, andset_values_hook procedures; see Chapter 6.• Computes values for uninitialized nonresource fieldsthat are derived from resource fields. For example,graphics contexts (GCs) that the widget uses arederived from resources like background, foreground, andfont.An initialization procedure also can check certain fieldsfor internal consistency. For example, it makes no sense tospecify a colormap for a depth that does not support thatcolormap.Initialization procedures are called insuperclass-to-subclass order after all fields specified inthe resource lists have been initialized. The initializeprocedure does not need to examine args and num_args if allpublic resources are declared in the resource list. Most ofthe initialization code for a specific widget class dealswith fields defined in that class and not with fieldsdefined in its superclasses.If a subclass does not need an initialization procedurebecause it does not need to perform any of the aboveoperations, it can specify NULL for the initialize field inthe class record.Sometimes a subclass may want to overwrite values filled inby its superclass. In particular, size calculations of asuperclass often are incorrect for a subclass, and in thiscase, the subclass must modify or recalculate fieldsdeclared and computed by its superclass.As an example, a subclass can visually surround itssuperclass display. In this case, the width and heightcalculated by the superclass initialize procedure are toosmall and need to be incremented by the size of thesurround. The subclass needs to know if its superclass’ssize was calculated by the superclass or was specifiedexplicitly. All widgets must place themselves into whateversize is explicitly given, but they should compute areasonable size if no size is requested.The request and new arguments provide the necessaryinformation for a subclass to determine the differencebetween an explicitly specified field and a field computedby a superclass. The request widget is a copy of the widgetas initialized by the arglist and resource database. Thenew widget starts with the values in the request, but it hasbeen updated by all superclass initialization procedurescalled so far. A subclass initialize procedure can comparethese two to resolve any potential conflicts.In the above example, the subclass with the visual surroundcan see if the width and height in the request widget arezero. If so, it adds its surround size to the width andheight fields in the new widget. If not, it must make dowith the size originally specified.The new widget will become the actual widget instancerecord. Therefore, the initialization procedure should doall its work on the new widget; the request widget shouldnever be modified. If the initialize procedure needs tocall any routines that operate on a widget, it shouldspecify new as the widget instance.2.5.7. Constraint Instance Initialization: TheConstraintClassPart initialize ProcedureThe constraint initialization procedure pointer, found inthe ConstraintClassPart initialize field of the widget classrecord, is of type XtInitProc. The values passed to theparent constraint initialization procedures are the same asthose passed to the child’s class widget initializationprocedures.The constraints field of the request widget points to a copyof the constraints record as initialized by the arglist andresource database.The constraint initialization procedure should compute anyconstraint fields derived from constraint resources. It canmake further changes to the new widget to make the widgetand any other constraint fields conform to the specifiedconstraints, for example, changing the widget’s size orposition.If a constraint class does not need a constraintinitialization procedure, it can specify NULL for theinitialize field of the ConstraintClassPart in the classrecord.2.5.8. Nonwidget Data Initialization: The initialize_hookProcedure NoteThe initialize_hook procedure is obsolete, as thesame information is now available to theinitialize procedure. The procedure has beenretained for those widgets that used it inprevious releases.The initialize_hook procedure pointer is of type XtArgsProc:__│ typedef void (*XtArgsProc)(Widget, ArgList, Cardinal*);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 varargsform, any resources specified via XtVaTypedArg areconverted to the widget representation and thelist is transformed into the ArgList format.num_args Specifies the number of entries in the argumentlist.│__ If this procedure is not NULL, it is called immediatelyafter the corresponding initialize procedure or in its placeif the initialize field is NULL.The initialize_hook procedure allows a widget instance toinitialize nonresource data using information from thespecified argument list as if it were a resource.2.6. Realizing WidgetsTo realize a widget instance, use XtRealizeWidget.__│ void XtRealizeWidget(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__If the widget is already realized, XtRealizeWidget simplyreturns. Otherwise it performs the following:• Binds all action names in the widget’s translationtable to procedures (see Section 10.1.2).• Makes a postorder traversal of the widget tree rootedat the specified widget and calls each non-NULLchange_managed procedure of all composite widgets thathave one or more managed children.• Constructs an XSetWindowAttributes structure filled inwith information derived from the Core widget fieldsand calls the realize procedure for the widget, whichadds any widget-specific attributes and creates the Xwindow.• If the widget is not a subclass ofcompositeWidgetClass, XtRealizeWidget returns;otherwise it continues and performs the following:− Descends recursively to each of the widget’smanaged children and calls the realize procedures.Primitive widgets that instantiate children areresponsible for realizing those childrenthemselves.− Maps all of the managed children windows that havemapped_when_managed True. If a widget is managedbut mapped_when_managed is False, the widget isallocated visual space but is not displayed.If the widget is a top-level shell widget (that is, it hasno parent), and mapped_when_managed is True, XtRealizeWidgetmaps the widget window.XtCreateWidget, XtVaCreateWidget, XtRealizeWidget,XtManageChildren, XtUnmanageChildren, XtUnrealizeWidget,XtSetMappedWhenManaged, and XtDestroyWidget maintain thefollowing invariants:• If a composite widget is realized, then all its managedchildren are realized.• If a composite widget is realized, then all its managedchildren that have mapped_when_managed True are mapped.All Intrinsics functions and all widget routines shouldaccept either realized or unrealized widgets. When callingthe realize or change_managed procedures for children of acomposite widget, XtRealizeWidget calls the procedures inreverse order of appearance in the CompositePart childrenlist. By default, this ordering of the realize procedureswill result in the stacking order of any newly createdsubwindows being top-to-bottom in the order of appearance onthe list, and the most recently created child will be at thebottom.To check whether or not a widget has been realized, useXtIsRealized.__│ Boolean XtIsRealized(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ The XtIsRealized function returns True if the widget hasbeen realized, that is, if the widget has a nonzero windowID. If the specified object is not a widget, the state ofthe nearest widget ancestor is returned.Some widget procedures (for example, set_values) might wishto operate differently after the widget has been realized.2.6.1. Widget Instance Window Creation: The realizeProcedureThe realize procedure pointer in a widget class is of typeXtRealizeProc.__│ typedef void (*XtRealizeProc)(Widget, XtValueMask*, XSetWindowAttributes*);Widget w;XtValueMask *value_mask;XSetWindowAttributes *attributes;w Specifies the widget.value_maskSpecifies which fields in the attributes structureare used.attributesSpecifies the window attributes to use in theXCreateWindow call.│__ The realize procedure must create the widget’s window.Before calling the class realize procedure, the genericXtRealizeWidget function fills in a mask and a correspondingXSetWindowAttributes structure. It sets the followingfields in attributes and corresponding bits in value_maskbased on information in the widget core structure:• The background_pixmap (or background_pixel ifbackground_pixmap is XtUnspecifiedPixmap) is filled infrom the corresponding field.• The border_pixmap (or border_pixel if border_pixmap isXtUnspecifiedPixmap) is filled in from thecorresponding field.• The colormap is filled in from the corresponding field.• The event_mask is filled in based on the event handlersregistered, the event translations specified, whetherthe expose field is non-NULL, and whethervisible_interest is True.• The bit_gravity is set to NorthWestGravity if theexpose field is NULL.These or any other fields in attributes and thecorresponding bits in value_mask can be set by the realizeprocedure.Note that because realize is not a chained operation, thewidget class realize procedure must update theXSetWindowAttributes structure with all the appropriatefields from non-Core superclasses.A widget class can inherit its realize procedure from itssuperclass during class initialization. The realizeprocedure defined for coreWidgetClass calls XtCreateWindowwith the passed value_mask and attributes and withwindow_class and visual set to CopyFromParent. BothcompositeWidgetClass and constraintWidgetClass inherit thisrealize procedure, and most new widget subclasses can do thesame (see Section 1.6.10).The most common noninherited realize procedures setbit_gravity in the mask and attributes to the appropriatevalue and then create the window. For example, depending onits justification, Label might set bit_gravity toWestGravity, CenterGravity, or EastGravity. Consequently,shrinking it would just move the bits appropriately, and noexposure event is needed for repainting.If a composite widget’s children should be realized in anorder other than that specified (to control the stackingorder, for example), it should call XtRealizeWidget on itschildren itself in the appropriate order from within its ownrealize procedure.Widgets that have children and whose class is not a subclassof compositeWidgetClass are responsible for callingXtRealizeWidget on their children, usually from within therealize procedure.Realize procedures cannot manage or unmanage theirdescendants.2.6.2. Window Creation Convenience RoutineRather than call the Xlib XCreateWindow function explicitly,a realize procedure should normally call the Intrinsicsanalog XtCreateWindow, which simplifies the creation ofwindows for widgets.__│ void XtCreateWindow(w, window_class, visual, value_mask, attributes)Widget w;unsigned int window_class;Visual *visual;XtValueMask value_mask;XSetWindowAttributes *attributes;w Specifies the widget that defines the additionalwindow attributed. Must be of class Core or anysubclass thereof.window_classSpecifies the Xlib window class (for example,InputOutput, InputOnly, or CopyFromParent).visual Specifies the visual type (usuallyCopyFromParent).value_maskSpecifies which fields in the attributes structureare used.attributesSpecifies the window attributes to use in theXCreateWindow call.│__ The XtCreateWindow function calls the Xlib XCreateWindowfunction with values from the widget structure and thepassed parameters. Then, it assigns the created window tothe widget’s window field.XtCreateWindow evaluates the following fields of the widgetcore structure: depth, screen, parent->core.window, x, y,width, height, and border_width.2.7. Obtaining Window Information from a WidgetThe Core widget class definition contains the screen andwindow ids. The window field may be NULL for a while (seeSections 2.5 and 2.6).The display pointer, the parent widget, screen pointer, andwindow of a widget are available to the widget writer bymeans of macros and to the application writer by means offunctions.__│ Display *XtDisplay(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ XtDisplay returns the display pointer for the specifiedwidget.__│ Widget XtParent(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ XtParent returns the parent object for the specified widget.The returned object will be of class Object or a subclass.__│ Screen *XtScreen(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ XtScreen returns the screen pointer for the specifiedwidget.__│ Window XtWindow(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ XtWindow returns the window of the specified widget.The display pointer, screen pointer, and window of a widgetor of the closest widget ancestor of a nonwidget object areavailable by means of XtDisplayOfObject, XtScreenOfObject,and XtWindowOfObject.__│ Display *XtDisplayOfObject(object)Widget object;object Specifies the object. Must be of class Object orany subclass thereof.│__ XtDisplayOfObject is identical in function to XtDisplay ifthe object is a widget; otherwise XtDisplayOfObject returnsthe display pointer for the nearest ancestor of object thatis of class Widget or a subclass thereof.__│ Screen *XtScreenOfObject(object)Widget object;object Specifies the object. Must be of class Object orany subclass thereof.│__ XtScreenOfObject is identical in function to XtScreen if theobject is a widget; otherwise XtScreenOfObject returns thescreen pointer for the nearest ancestor of object that is ofclass Widget or a subclass thereof.__│ Window XtWindowOfObject(object)Widget object;object Specifies the object. Must be of class Object orany subclass thereof.│__ XtWindowOfObject is identical in function to XtWindow if theobject is a widget; otherwise XtWindowOfObject returns thewindow for the nearest ancestor of object that is of classWidget or a subclass thereof.To retrieve the instance name of an object, use XtName.__│ String XtName(object)Widget object;object Specifies the object whose name is desired. Mustbe of class Object or any subclass thereof.│__ XtName returns a pointer to the instance name of thespecified object. The storage is owned by the Intrinsicsand must not be modified. The name is not qualified by thenames of any of the object’s ancestors.Several window attributes are locally cached in the widgetinstance. Thus, they can be set by the resource manager andXtSetValues as well as used by routines that derivestructures from these values (for example, depth forderiving pixmaps, background_pixel for deriving GCs, and soon) or in the XtCreateWindow call.The x, y, width, height, and border_width window attributesare available to geometry managers. These fields aremaintained synchronously inside the Intrinsics. When anXConfigureWindow is issued by the Intrinsics on the widget’swindow (on request of its parent), these values are updatedimmediately rather than some time later when the servergenerates a ConfigureNotify event. (In fact, most widgetsdo not select SubstructureNotify events.) This ensures thatall geometry calculations are based on the internallyconsistent toolkit world rather than on either aninconsistent world updated by asynchronous ConfigureNotifyevents or a consistent, but slow, world in which geometrymanagers ask the server for window sizes whenever they needto lay out their managed children (see Chapter 6).2.7.1. Unrealizing WidgetsTo destroy the windows associated with a widget and itsnon-pop-up descendants, use XtUnrealizeWidget.__│ void XtUnrealizeWidget(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ If the widget is currently unrealized, XtUnrealizeWidgetsimply returns. Otherwise it performs the following:• Unmanages the widget if the widget is managed.• Makes a postorder (child-to-parent) traversal of thewidget tree rooted at the specified widget and, foreach widget that has declared a callback list resourcenamed ‘‘unrealizeCallback’’, executes the procedures onthe XtNunrealizeCallback list.• Destroys the widget’s window and any subwindows bycalling XDestroyWindow with the specified widget’swindow field.Any events in the queue or which arrive following a call toXtUnrealizeWidget will be dispatched as if the window(s) ofthe unrealized widget(s) had never existed.2.8. Destroying WidgetsThe Intrinsics provide support• To destroy all the pop-up children of the widget beingdestroyed and destroy all children of compositewidgets.• To remove (and unmap) the widget from its parent.• To call the callback procedures that have beenregistered to trigger when the widget is destroyed.• To minimize the number of things a widget has todeallocate when destroyed.• To minimize the number of XDestroyWindow calls whendestroying a widget tree.To destroy a widget instance, use XtDestroyWidget.__│ void XtDestroyWidget(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ The XtDestroyWidget function provides the only method ofdestroying a widget, including widgets that need to destroythemselves. It can be called at any time, including from anapplication callback routine of the widget being destroyed.This requires a two-phase destroy process in order to avoiddangling references to destroyed widgets.In phase 1, XtDestroyWidget performs the following:• If the being_destroyed field of the widget is True, itreturns immediately.• Recursively descends the widget tree and sets thebeing_destroyed field to True for the widget and allnormal 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 w2occurs after w1 on the destroy list, then w2 is not adescendent, either normal or pop-up, of w1.Phase 2 occurs when all procedures that should execute as aresult of the current event have been called, including allprocedures registered with the event and translationmanagers, that is, when the current invocation ofXtDispatchEvent is about to return, or immediately if not inXtDispatchEvent.In phase 2, XtDestroyWidget performs the following on eachentry in the destroy list in the order specified:• If the widget is not a pop-up child and the widget’sparent is a subclass of compositeWidgetClass, and ifthe parent is not being destroyed, it callsXtUnmanageChild on the widget and then calls thewidget’s parent’s delete_child procedure (see Section3.3).• Calls the destroy callback procedures registered on thewidget and all normal and pop-up descendants inpostorder (it calls child callbacks before parentcallbacks).The XtDestroyWidget function then makes second traversal ofthe widget and all normal and pop-up descendants to performthe following three items on each widget in postorder:• If the widget is not a pop-up child and the widget’sparent is a subclass of constraintWidgetClass, it callsthe ConstraintClassPart destroy procedure for theparent, then for the parent’s superclass, until finallyit calls the ConstraintClassPart destroy procedure forconstraintWidgetClass.• Calls the CoreClassPart destroy procedure declared inthe widget class, then the destroy procedure declaredin its superclass, until finally it calls the destroyprocedure declared in the Object class record.Callback lists are deallocated.• If the widget class object class part contains anObjectClassExtension record with the record_typeNULLQUARK and the deallocate field is not NULL, callsthe deallocate procedure to deallocate the instance andif one exists, the constraint record. Otherwise, theIntrinsics will deallocate the widget instance recordand if one exists, the constraint record.• Calls XDestroyWindow if the specified widget isrealized (that is, has an X window). The serverrecursively destroys all normal descendant windows.(Windows of realized pop-up Shell children, and theirdescendants, are destroyed by a shell class destroyprocedure.)2.8.1. Adding and Removing Destroy CallbacksWhen an application needs to perform additional processingduring the destruction of a widget, it should register adestroy callback procedure for the widget. The destroycallback procedures use the mechanism described in Chapter8. The destroy callback list is identified by the resourcename XtNdestroyCallback.For example, the following adds an application-supplieddestroy callback procedure ClientDestroy with client data toa widget by calling XtAddCallback.XtAddCallback(w, XtNdestroyCallback, ClientDestroy, client_data)Similarly, the following removes the application-supplieddestroy callback procedure ClientDestroy by callingXtRemoveCallback.XtRemoveCallback(w, XtNdestroyCallback, ClientDestroy, client_data)The ClientDestroy argument is of type XtCallbackProc; seeSection 8.1.2.8.2. Dynamic Data Deallocation: The destroy ProcedureThe destroy procedure pointers in the ObjectClassPart,RectObjClassPart, and CoreClassPart structures are of typeXtWidgetProc.__│ typedef void (*XtWidgetProc)(Widget);Widget w;w Specifies the widget being destroyed.│__ The destroy procedures are called in subclass-to-superclassorder. Therefore, a widget’s destroy procedure shoulddeallocate only storage that is specific to the subclass andshould ignore the storage allocated by any of itssuperclasses. The destroy procedure should deallocate onlyresources that have been explicitly created by the subclass.Any resource that was obtained from the resource database orpassed in an argument list was not created by the widget andtherefore should not be destroyed by it. If a widget doesnot need to deallocate any storage, the destroy procedureentry in its class record can be NULL.Deallocating storage includes, but is not limited to, thefollowing steps:• Calling XtFree on dynamic storage allocated withXtMalloc, XtCalloc, and so on.• Calling XFreePixmap on pixmaps created with direct Xcalls.• Calling XtReleaseGC on GCs allocated with XtGetGC.• Calling XFreeGC on GCs allocated with direct X calls.• Calling XtRemoveEventHandler on event handlers added toother widgets.• Calling XtRemoveTimeOut on timers created withXtAppAddTimeOut.• Calling XtDestroyWidget for each child if the widgethas children and is not a subclass ofcompositeWidgetClass.During destroy phase 2 for each widget, the Intrinsicsremove the widget from the modal cascade, unregister allevent handlers, remove all key, keyboard, button, andpointer grabs and remove all callback procedures registeredon the widget. Any outstanding selection transfers willtime out.2.8.3. Dynamic Constraint Data Deallocation: TheConstraintClassPart destroy ProcedureThe constraint destroy procedure identified in theConstraintClassPart structure is called for a widget whoseparent is a subclass of constraintWidgetClass. Thisconstraint destroy procedure pointer is of typeXtWidgetProc. The constraint destroy procedures are calledin subclass-to-superclass order, starting at the class ofthe widget’s parent and ending at constraintWidgetClass.Therefore, a parent’s constraint destroy procedure shoulddeallocate only storage that is specific to the constraintsubclass and not storage allocated by any of itssuperclasses.If a parent does not need to deallocate any constraintstorage, the constraint destroy procedure entry in its classrecord can be NULL.2.8.4. Widget Instance Deallocation: The deallocateProcedureThe deallocate procedure pointer in the ObjectClassExtensionrecord is of type XtDeallocateProc.__│ typedef void (*XtDeallocateProc)(Widget, XtPointer);Widget widget;XtPointer more_bytes;widget Specifies the widget being destroyed.more_bytesSpecifies the auxiliary memory received from thecorresponding allocator along with the widget, orNULL.│__ When a widget is destroyed, if an ObjectClassExtensionrecord exists in the object class part extension field withrecord_type NULLQUARK and the deallocate field is not NULL,the XtDeallocateProc will be called. If no ObjectClassPartextension record is declared with record_type equal toNULLQUARK, then XtInheritAllocate and XtInheritDeallocateare assumed. The responsibilities of the deallocateprocedure are to deallocate the memory specified bymore_bytes if it is not NULL, to deallocate the constraintsrecord as specified by the widget’s core.constraints fieldif it is not NULL, and to deallocate the widget instanceitself.If no XtDeallocateProc is found, it is assumed that theIntrinsics originally allocated the memory and isresponsible for freeing it.2.9. Exiting from an ApplicationAll X Toolkit applications should terminate by callingXtDestroyApplicationContext and then exiting using thestandard method for their operating system (typically, bycalling exit for POSIX-based systems). The quickest way tomake the windows disappear while exiting is to callXtUnmapWidget on each top-level shell widget. TheIntrinsics have no resources beyond those in the programimage, and the X server will free its resources when itsconnection to the application is broken.Depending upon the widget set in use, it may be necessary toexplicitly destroy individual widgets or widget trees withXtDestroyWidget before calling XtDestroyApplicationContextin order to ensure that any required widget cleanup isproperly executed. The application developer must refer tothe widget documentation to learn if a widget needs toperform cleanup beyond that performed automatically by theoperating system. If the client is a session participant(see Section 4.2), then the client may wish to resign fromthe session before exiting. See Section 4.2.4 for details.2
3.1. Addition of Children to a Composite Widget: Theinsert_child ProcedureTo add a child to the parent’s list of children, theXtCreateWidget function calls the parent’s class routineinsert_child. The insert_child procedure pointer in acomposite widget is of type XtWidgetProc.__│ typedef void (*XtWidgetProc)(Widget);Widget w;w Passes the newly created child.│__ Most composite widgets inherit their superclass’s operation.The insert_child routine in CompositeWidgetClasscalls andinserts the child at the specified position in the childrenlist, expanding it if necessary.Some composite widgets define their own insert_child routineso that they can order their children in some convenientway, create companion controller widgets for a new widget,or limit the number or class of their child widgets. Acomposite widget class that wishes to allow nonwidgetchildren (see Chapter 12) must specify aCompositeClassExtension extension record as described inSection 1.4.2.1 and set the accepts_objects field in thisrecord to True. If the CompositeClassExtension record isnot specified or the accepts_objects field is False, thecomposite widget can assume that all its children are of asubclass of Core without an explicit subclass test in theinsert_child procedure.If there is not enough room to insert a new child in thechildren array (that is, num_children is equal tonum_slots), the insert_child procedure must first reallocatethe array and update num_slots. The insert_child procedurethen places the child at the appropriate position in thearray and increments the num_children field.3.2. Insertion Order of Children: The insert_positionProcedureInstances of composite widgets sometimes need to specifymore about the order in which their children are kept. Forexample, an application may want a set of command buttons insome logical order grouped by function, and it may wantbuttons that represent file names to be kept in alphabeticalorder without constraining the order in which the buttonsare created.An application controls the presentation order of a set ofchildren by supplying an XtNinsertPosition resource. Theinsert_position procedure pointer in a composite widgetinstance is of type XtOrderProc.__│ typedef Cardinal (*XtOrderProc)(Widget);Widget w;w Passes the newly created widget.│__ Composite widgets that allow clients to order their children(usually homogeneous boxes) can call their widget instance’sinsert_position procedure from the class’s insert_childprocedure to determine where a new child should go in itschildren array. Thus, a client using a composite class canapply different sorting criteria to widget instances of theclass, passing in a different insert_position procedureresource when it creates each composite widget instance.The return value of the insert_position procedure indicateshow many children should go before the widget. Returningzero indicates that the widget should go before all otherchildren, and returning num_children indicates that itshould go after all other children. The defaultinsert_position function returns num_children and can beoverridden by a specific composite widget’s resource list orby the argument list provided when the composite widget iscreated.3.3. Deletion of Children: The delete_child ProcedureTo remove the child from the parent’s children list, theXtDestroyWidget function eventually causes a call to theComposite parent’s class delete_child procedure. Thedelete_child procedure pointer is of type XtWidgetProc.__│ typedef void (*XtWidgetProc)(Widget);Widget w;w Passes the child being deleted.│__ Most widgets inherit the delete_child procedure from theirsuperclass. Composite widgets that create companion widgetsdefine their own delete_child procedure to remove thesecompanion widgets.3.4. Adding and Removing Children from the Managed SetThe Intrinsics provide a set of generic routines to permitthe addition of widgets to or the removal of widgets from acomposite widget’s managed set. These generic routineseventually call the composite widget’s change_managedprocedure if the procedure pointer is non-NULL. Thechange_managed procedure pointer is of type XtWidgetProc.The widget argument specifies the composite widget whosemanaged child set has been modified.3.4.1. Managing ChildrenTo add a list of widgets to the geometry-managed (and hencedisplayable) subset of their Composite parent, useXtManageChildren.__│ typedef Widget *WidgetList;void XtManageChildren(children, num_children)WidgetList children;Cardinal num_children;children Specifies a list of child widgets. Each childmust be of class RectObj or any subclass thereof.num_childrenSpecifies the number of children in the list.│__ The XtManageChildren function performs the following:• Issues an error if the children do not all have thesame parent or if the parent’s class is not a subclassof compositeWidgetClass.• Returns immediately if the common parent is beingdestroyed; otherwise, for each unique child on thelist, XtManageChildren ignores the child if it alreadyis managed or is being destroyed, and marks it if not.• If the parent is realized and after all children havebeen marked, it makes some of the newly managedchildren viewable:− Calls the change_managed routine of the widgets’parent.− Calls XtRealizeWidget on each previously unmanagedchild that is unrealized.− Maps each previously unmanaged child that hasmap_when_managed True.Managing children is independent of the ordering of childrenand independent of creating and deleting children. Thelayout routine of the parent should consider children whosemanaged field is True and should ignore all other children.Note that some composite widgets, especially fixed boxes,call XtManageChild from their insert_child procedure.If the parent widget is realized, its change_managedprocedure is called to notify it that its set of managedchildren has changed. The parent can reposition and resizeany of its children. It moves each child as needed bycalling XtMoveWidget, which first updates the x and y fieldsand which then calls XMoveWindow.If the composite widget wishes to change the size or borderwidth of any of its children, it calls XtResizeWidget, whichfirst updates the width, height, and border_width fields andthen calls XConfigureWindow. Simultaneous repositioning andresizing may be done with XtConfigureWidget; see Section6.6.To add a single child to its parent widget’s set of managedchildren, use XtManageChild.__│ void XtManageChild(child)Widget child;child Specifies the child. Must be of class RectObj orany subclass thereof.│__ The XtManageChild function constructs a WidgetList of length1 and calls XtManageChildren.To create and manage a child widget in a single procedure,use XtCreateManagedWidget or XtVaCreateManagedWidget.__│ Widget XtCreateManagedWidget(name, widget_class, parent, args, num_args)String name;WidgetClass widget_class;Widget parent;ArgList args;Cardinal num_args;name Specifies the resource instance name for thecreated widget.widget_classSpecifies the widget class pointer for the createdwidget. Must be rectObjClass or any subclassthereof.parent Specifies the parent widget. Must be of classComposite or any subclass thereof.args Specifies the argument list to override any otherresource specifications.num_args Specifies the number of entries in the argumentlist.│__ The XtCreateManagedWidget function is a convenience routinethat calls XtCreateWidget and XtManageChild.__│ Widget XtVaCreateManagedWidget(name, widget_class, parent, ...)String name;WidgetClass widget_class;Widget parent;name Specifies the resource instance name for thecreated widget.widget_classSpecifies the widget class pointer for the createdwidget. Must be rectObjClass or any subclassthereof.parent Specifies the parent widget. Must be of classComposite or any subclass thereof.... Specifies the variable argument list to overrideany other resource specifications.│__ XtVaCreateManagedWidget is identical in function toXtCreateManagedWidget with the args and num_args parametersreplaced by a varargs list, as described in Section 2.5.1.3.4.2. Unmanaging ChildrenTo remove a list of children from a parent widget’s managedlist, use XtUnmanageChildren.__│ void XtUnmanageChildren(children, num_children)WidgetList children;Cardinal num_children;children Specifies a list of child widgets. Each childmust be of class RectObj or any subclass thereof.num_childrenSpecifies the number of children.│__ The XtUnmanageChildren function performs the following:• Returns immediately if the common parent is beingdestroyed.• Issues an error if the children do not all have thesame parent or if the parent is not a subclass ofcompositeWidgetClass.• For each unique child on the list, XtUnmanageChildrenignores the child if it is unmanaged; otherwise itperforms the following:− Marks the child as unmanaged.− If the child is realized and the map_when_managedfield is True, it is unmapped.• If the parent is realized and if any children havebecome unmanaged, calls the change_managed routine ofthe widgets’ parent.XtUnmanageChildren does not destroy the child widgets.Removing widgets from a parent’s managed set is often atemporary banishment, and some time later the client maymanage the children again. To destroy widgets entirely,XtDestroyWidget should be called instead; see Section 2.9.To remove a single child from its parent widget’s managedset, use XtUnmanageChild.__│ void XtUnmanageChild(child)Widget child;child Specifies the child. Must be of class RectObj orany subclass thereof.│__ The XtUnmanageChild function constructs a widget list oflength 1 and calls XtUnmanageChildren.These functions are low-level routines that are used bygeneric composite widget building routines. In addition,composite widgets can provide widget-specific, high-levelconvenience procedures.3.4.3. Bundling Changes to the Managed SetA client may simultaneously unmanage and manage childrenwith a single call to the Intrinsics. In this same call theclient may provide a callback procedure that can modify thegeometries of one or more children. The composite widgetclass defines whether this single client call results inseparate invocations of the change_managed method, one tounmanage and the other to manage, or in just a singleinvocation.To simultaneously remove from and add to thegeometry-managed set of children of a composite parent, useXtChangeManagedSet.__│ void XtChangeManagedSet(unmanage_children, num_unmanage_children,do_change_proc, client_data,manage_children, num_manage_children)WidgetList unmanage_children;Cardinal num_unmanage_children;XtDoChangeProc do_change_proc;XtPointer client_data;WidgetList manage_children;Cardinal num_manage_children;unmanage_children Specifies the list of widget children toinitially remove from the managed set.num_unmanage_childrenSpecifies the number of entries in theunmanage_children list.do_change_proc Specifies a procedure to invoke betweenunmanaging and managing the children, orNULL.client_data Specifies client data to be passed to thedo_change_proc.manage_children Specifies the list of widget children tofinally add to the managed set.num_manage_childrenSpecifies the number of entries in themanage_children list.│__ The XtChangeManagedSet function performs the following:• Returns immediately if num_unmanage_children andnum_manage_children are both 0.• Issues a warning and returns if the widgets specifiedin the manage_children and the unmanage_children listsdo not all have the same parent or if that parent isnot a subclass of compositeWidgetClass.• Returns immediately if the common parent is beingdestroyed.• If do_change_proc is not NULL and the parent’sCompositeClassExtension allows_change_managed_set fieldis False, then XtChangeManagedSet performs thefollowing:− Calls XtUnmanageChildren (unmanage_children,num_unmanage_children).− Calls the do_change_proc.− Calls XtManageChildren (manage_children,num_manage_children).• Otherwise, the following is performed:− For each child on the unmanage_children list; ifthe child is already unmanaged it is ignored,otherwise it is marked as unmanaged, and if it isrealized and its map_when_managed field is True,it is unmapped.− If do_change_proc is non-NULL, the procedure isinvoked.− For each child on the manage_children list; if thechild is already managed or is being destroyed, itis ignored; otherwise it is marked as managed.− If the parent is realized and after all childrenhave been marked, the change_managed method of theparent is invoked, and subsequently some of thenewly managed children are made viewable bycalling XtRealizeWidget on each previouslyunmanaged child that is unrealized and mappingeach previously unmanaged child that hasmap_when_managed True.If no CompositeClassExtension record is found in theparent’s composite class part extension field with recordtype NULLQUARK and version greater than 1, and ifXtInheritChangeManaged was specified in the parent’s classrecord during class initialization, the value of theallows_change_managed_set field is inherited from thesuperclass. The value inherited from compositeWidgetClassfor the allows_change_managed_set field is False.It is not an error to include a child in both theunmanage_children and the manage_children lists. The effectof such a call is that the child remains managed followingthe call, but the do_change_proc is able to affect the childwhile it is in an unmanaged state.The do_change_proc is of type XtDoChangeProc.__│ typedef void (*XtDoChangeProc)(Widget, WidgetList, Cardinal*, WidgetList, Cardinal*, XtPointer);Widget composite_parent;WidgetList unmange_children;Cardinal *num_unmanage_children;WidgetList manage_children;Cardinal *num_manage_children;XtPointer client_data;composite_parent Passes the composite parent whose managedset is being altered.unmanage_children Passes the list of children just removedfrom the managed set.num_unmanage_childrenPasses the number of entries in theunmanage_children list.manage_children Passes the list of children about to beadded to the managed set.num_manage_childrenPasses the number of entries in themanage_children list.client_data Passes the client data passed toXtChangeManagedSet.│__ The do_change_proc procedure is used by the caller ofXtChangeManagedSet to make changes to one or more childrenat the point when the managed set contains the fewestentries. These changes may involve geometry requests, andin this case the caller of XtChangeManagedSet may takeadvantage of the fact that the Intrinsics internally grantgeometry requests made by unmanaged children withoutinvoking the parent’s geometry manager. To achieve thisadvantage, if the do_change_proc procedure changes thegeometry of a child or of a descendant of a child, then thatchild should be included in the unmanage_children andmanage_children lists.3.4.4. Determining if a Widget Is ManagedTo determine the managed state of a given child widget, useXtIsManaged.__│ Boolean XtIsManaged(w)Widget w;w Specifies the widget. Must be of class Object orany subclass thereof.│__ The XtIsManaged function returns True if the specifiedwidget is of class RectObj or any subclass thereof and ismanaged, or False otherwise.3.5. Controlling When Widgets Get MappedA widget is normally mapped if it is managed. However, thisbehavior can be overridden by setting theXtNmappedWhenManaged resource for the widget when it iscreated or by setting the map_when_managed field to False.To change the value of a given widget’s map_when_managedfield, use XtSetMappedWhenManaged.__│ void XtSetMappedWhenManaged(w, map_when_managed)Widget w;Boolean map_when_managed;w Specifies the widget. Must be of class Core orany subclass thereof.map_when_managedSpecifies a Boolean value that indicates the newvalue that is stored into the widget’smap_when_managed field.│__ If the widget is realized and managed, and ifmap_when_managed is True, XtSetMappedWhenManaged maps thewindow. If the widget is realized and managed, and ifmap_when_managed is False, it unmaps the window.XtSetMappedWhenManaged is a convenience function that isequivalent to (but slightly faster than) calling XtSetValuesand setting the new value for the XtNmappedWhenManagedresource then mapping the widget as appropriate. As analternative to using XtSetMappedWhenManaged to controlmapping, a client may set mapped_when_managed to False anduse XtMapWidget and XtUnmapWidget explicitly.To map a widget explicitly, use XtMapWidget.__│ XtMapWidget(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ To unmap a widget explicitly, use XtUnmapWidget.__│ XtUnmapWidget(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ 3.6. Constrained Composite WidgetsThe Constraint widget class is a subclass ofcompositeWidgetClass. The name is derived from the factthat constraint widgets may manage the geometry of theirchildren based on constraints associated with each child.These constraints can be as simple as the maximum width andheight the parent will allow the child to occupy or can beas complicated as how other children should change if thischild is moved or resized. Constraint widgets let a parentdefine constraints as resources that are supplied for theirchildren. For example, if the Constraint parent defines themaximum sizes for its children, these new size resources areretrieved for each child as if they were resources that weredefined by the child widget’s class. Accordingly,constraint resources may be included in the argument list orresource file just like any other resource for the child.Constraint widgets have all the responsibilities of normalcomposite widgets and, in addition, must process and actupon the constraint information associated with each oftheir children.To make it easy for widgets and the Intrinsics to keep trackof the constraints associated with a child, every widget hasa constraints field, which is the address of aparent-specific structure that contains constraintinformation about the child. If a child’s parent does notbelong to a subclass of constraintWidgetClass, then thechild’s constraints field is NULL.Subclasses of Constraint can add constraint data to theconstraint record defined by their superclass. To allowthis, widget writers should define the constraint records intheir private .h file by using the same conventions as usedfor widget records. For example, a widget class that needsto maintain a maximum width and height for each child mightdefine its constraint record as follows:typedef struct {Dimension max_width, max_height;} MaxConstraintPart;typedef struct {MaxConstraintPart max;} MaxConstraintRecord, *MaxConstraint;A subclass of this widget class that also needs to maintaina minimum size would define its constraint record asfollows:typedef struct {Dimension min_width, min_height;} MinConstraintPart;typedef struct {MaxConstraintPart max;MinConstraintPart min;} MaxMinConstraintRecord, *MaxMinConstraint;Constraints are allocated, initialized, deallocated, andotherwise maintained insofar as possible by the Intrinsics.The Constraint class record part has several entries thatfacilitate this. All entries in ConstraintClassPart arefields and procedures that are defined and implemented bythe parent, but they are called whenever actions areperformed on the parent’s children.The XtCreateWidget function uses the constraint_size fieldin the parent’s class record to allocate a constraint recordwhen a child is created. XtCreateWidget also uses theconstraint resources to fill in resource fields in theconstraint record associated with a child. It then callsthe constraint initialize procedure so that the parent cancompute constraint fields that are derived from constraintresources and can possibly move or resize the child toconform to the given constraints.When the XtGetValues and XtSetValues functions are executedon a child, they use the constraint resources to get thevalues or set the values of constraints associated with thatchild. XtSetValues then calls the constraint set_valuesprocedures so that the parent can recompute derivedconstraint fields and move or resize the child asappropriate. If a Constraint widget class or any of itssuperclasses have declared a ConstraintClassExtension recordin the ConstraintClassPart extension fields with a recordtype of NULLQUARK and the get_values_hook field in theextension record is non-NULL, XtGetValues calls theget_values_hook procedure(s) to allow the parent to returnderived constraint fields.The XtDestroyWidget function calls the constraint destroyprocedure to deallocate any dynamic storage associated witha constraint record. The constraint record itself must notbe deallocated by the constraint destroy procedure;XtDestroyWidget does this automatically.3
4.1. Shell Widget DefinitionsWidgets negotiate their size and position with their parentwidget, that is, the widget that directly contains them.Widgets at the top of the hierarchy do not have parentwidgets. Instead, they must deal with the outside world.To provide for this, each top-level widget is encapsulatedin a special widget, called a shell widget.Shell widgets, whose class is a subclass of the Compositeclass, encapsulate other widgets and can allow a widget toavoid the geometry clipping imposed by the parent-childwindow relationship. They also can provide a layer ofcommunication with the window manager.The eight different types of shells are:Note that the classes Shell, WMShell, and VendorShell areinternal and should not be instantiated or subclassed. OnlyOverrrideShell, TransientShell, TopLevelShell,ApplicationShell, and SessionShell are intended for publicuse.4.1.1. ShellClassPart DefinitionsOnly the Shell class has additional class fields, which areall contained in the ShellClassExtensionRec. None of theother Shell classes have any additional class fields:__│ typedef struct {XtPointer extension;} ShellClassPart, OverrideShellClassPart,WMShellClassPart, VendorShellClassPart, TransientShellClassPart,TopLevelShellClassPart, ApplicationShellClassPart, SessionShellClassPart;│__ The full Shell class record definitions are:__│ typedef struct _ShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;} ShellClassRec;typedef struct {XtPointer next_extension; See Section 1.6.12XrmQuark record_type; See Section 1.6.12long version; See Section 1.6.12Cardinal record_size; See Section 1.6.12XtGeometryHandler root_geometry_manager;See below} ShellClassExtensionRec, *ShellClassExtension;typedef struct _OverrideShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;OverrideShellClassPart override_shell_class;} OverrideShellClassRec;typedef struct _WMShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;} WMShellClassRec;typedef struct _VendorShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;VendorShellClassPart vendor_shell_class;} VendorShellClassRec;typedef struct _TransientShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;VendorShellClassPart vendor_shell_class;TransientShellClassPart transient_shell_class;} TransientShellClassRec;typedef struct _TopLevelShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;VendorShellClassPart vendor_shell_class;TopLevelShellClassPart top_level_shell_class;} TopLevelShellClassRec;typedef struct _ApplicationShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;VendorShellClassPart vendor_shell_class;TopLevelShellClassPart top_level_shell_class;ApplicationShellClassPart application_shell_class;} ApplicationShellClassRec;typedef struct _SessionShellClassRec {CoreClassPart core_class;CompositeClassPart composite_class;ShellClassPart shell_class;WMShellClassPart wm_shell_class;VendorShellClassPart vendor_shell_class;TopLevelShellClassPart top_level_shell_class;ApplicationShellClassPart application_shell_class;SessionShellClassPart session_shell_class;} SessionShellClassRec;│__ The single occurrences of the class records and pointers forcreating instances of shells are:__│ extern ShellClassRec shellClassRec;extern OverrideShellClassRec overrideShellClassRec;extern WMShellClassRec wmShellClassRec;extern VendorShellClassRec vendorShellClassRec;extern TransientShellClassRec transientShellClassRec;extern TopLevelShellClassRec topLevelShellClassRec;extern ApplicationShellClassRec applicationShellClassRec;extern SessionShellClassRec sessionShellClassRec;extern WidgetClass shellWidgetClass;extern WidgetClass overrideShellWidgetClass;extern WidgetClass wmShellWidgetClass;extern WidgetClass vendorShellWidgetClass;extern WidgetClass transientShellWidgetClass;extern WidgetClass topLevelShellWidgetClass;extern WidgetClass applicationShellWidgetClass;extern WidgetClass sessionShellWidgetClass;│__ The following opaque types and opaque variables are definedfor generic operations on widgets whose class is a subclassof Shell.The declarations for all Intrinsics-defined shells exceptVendorShell appear in Shell.h and ShellP.h. VendorShell hasseparate public and private .h files which are included byShell.h and ShellP.h.Shell.h uses incomplete structure definitions to ensure thatthe compiler catches attempts to access private data in anyof the Shell instance or class data structures.The symbolic constant for the ShellClassExtension versionidentifier is XtShellExtensionVersion (see Section 1.6.12).The root_geometry_manager procedure acts as the parentgeometry manager for geometry requests made by shellwidgets. When a shell widget calls eitherXtMakeGeometryRequest or XtMakeResizeRequest, theroot_geometry_manager procedure is invoked to negotiate thenew geometry with the window manager. If the window managerpermits the new geometry, the root_geometry_managerprocedure should return XtGeometryYes; if the window managerdenies the geometry request or does not change the windowgeometry within some timeout interval (equal to wm_timeoutin the case of WMShells), the root_geometry_managerprocedure should return XtGeometryNo. If the window managermakes some alternative geometry change, theroot_geometry_manager procedure may return eitherXtGeometryNo and handle the new geometry as a resize orXtGeometryAlmost in anticipation that the shell will acceptthe compromise. If the compromise is not accepted, the newsize must then be handled as a resize. Subclasses of Shellthat wish to provide their own root_geometry_managerprocedures are strongly encouraged to use enveloping toinvoke their superclass’s root_geometry_manager procedureunder most situations, as the window manager interaction maybe very complex.If no ShellClassPart extension record is declared withrecord_type equal to NULLQUARK, thenXtInheritRootGeometryManager is assumed.4.1.2. ShellPart DefinitionThe various shell widgets have the following additionalinstance fields defined in their widget records:__│ typedef struct {String geometry;XtCreatePopupChildProc create_popup_child_proc;XtGrabKind grab_kind;Boolean spring_loaded;Boolean popped_up;Boolean allow_shell_resize;Boolean client_specified;Boolean save_under;Boolean override_redirect;XtCallbackList popup_callback;XtCallbackList popdown_callback;Visual * visual;} ShellPart;typedef struct {int empty;} OverrideShellPart;typedef struct {String title;int wm_timeout;Boolean wait_for_wm;Boolean transient;Boolean urgency;Widget client_leader;String window_role;struct _OldXSizeHints {long flags;int x, y;int width, height;int min_width, min_height;int max_width, max_height;int width_inc, height_inc;struct {int x;int y;} min_aspect, max_aspect;} size_hints;XWMHints wm_hints;int base_width, base_height, win_gravity;Atom title_encoding;} WMShellPart;typedef struct {int vendor_specific;} VendorShellPart;typedef struct {Widget transient_for;} TransientShellPart;typedef struct {String icon_name;Boolean iconic;Atom icon_name_encoding;} TopLevelShellPart;typedef struct {char * class;XrmClass xrm_class;int argc;char ** argv;} ApplicationShellPart;typedef struct {SmcConn connection;String session_id;String * restart_command;String * clone_command;String * discard_command;String * resign_command;String * shutdown_command;String * environment;String current_dir;String program_path;unsigned char restart_style;Boolean join_session;XtCallbackList save_callbacks;XtCallbackList interact_callbacks;XtCallbackList cancel_callbacks;XtCallbackList save_complete_callbacks;XtCallbackList die_callbacks;XtCallbackList error_callbacks;} SessionShellPart;│__ The full shell widget instance record definitions are:__│ typedef struct {CorePart core;CompositePart composite;ShellPart shell;} ShellRec, *ShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;OverrideShellPart override;} OverrideShellRec, *OverrideShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;} WMShellRec, *WMShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;VendorShellPart vendor;} VendorShellRec, *VendorShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;VendorShellPart vendor;TransientShellPart transient;} TransientShellRec, *TransientShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;VendorShellPart vendor;TopLevelShellPart topLevel;} TopLevelShellRec, *TopLevelShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;VendorShellPart vendor;TopLevelShellPart topLevel;ApplicationShellPart application;} ApplicationShellRec, *ApplicationShellWidget;typedef struct {CorePart core;CompositePart composite;ShellPart shell;WMShellPart wm;VendorShellPart vendor;TopLevelShellPart topLevel;ApplicationShellPart application;SessionShellPart session;} SessionShellRec, *SessionShellWidget;│__ 4.1.3. Shell ResourcesThe resource names, classes, and representation typesspecified in the shellClassRec resource list are:OverrideShell declares no additional resources beyond thosedefined by Shell.The resource names, classes, and representation typesspecified in the wmShellClassRec resource list are:The class resource list for VendorShell isimplementation-defined.The resource names, classes, and representation types thatare specified in the transientShellClassRec resource listare:The resource names, classes, and representation types thatare specified in the topLevelShellClassRec resource listare:The resource names, classes, and representation types thatare specified in the applicationShellClassRec resource listare:The resource names, classes, and representation types thatare specified in the sessionShellClassRec resource list are:4.1.4. ShellPart Default ValuesThe default values for fields common to all classes ofpublic shells (filled in by the Shell resource lists and theShell initialize procedures) are:The geometry field specifies the size and position and isusually given only on a command line or in a defaults file.If the geometry field is non-NULL when a widget of classWMShell is realized, the geometry specification is parsedusing XWMGeometry with a default geometry string constructedfrom the values of x, y, width, height, width_inc, andheight_inc and the size and position flags in the windowmanager size hints are set. If the geometry specifies an xor y position, then USPosition is set. If the geometryspecifies a width or height, then USSize is set. Any fieldsin the geometry specification override the correspondingvalues in the Core x, y, width, and height fields. Ifgeometry is NULL or contains only a partial specification,then the Core x, y, width, and height fields are used andPPosition and PSize are set as appropriate. The geometrystring is not copied by any of the Intrinsics Shell classes;a client specifying the string in an arglist or varargs listmust ensure that the value remains valid until the shellwidget is realized. For further information on the geometrystring, see Section 16.4 in Xlib — C Language X Interface.The create_popup_child_proc procedure is called by theXtPopup procedure and may remain NULL. The grab_kind,spring_loaded, and popped_up fields maintain widget stateinformation as described under XtPopup, XtMenuPopup,XtPopdown, and XtMenuPopdown. The allow_shell_resize fieldcontrols whether the widget contained by the shell isallowed to try to resize itself. If allow_shell_resize isFalse, any geometry requests made by the child will alwaysreturn XtGeometryNo without interacting with the windowmanager. Setting save_under True instructs the server toattempt to save the contents of windows obscured by theshell when it is mapped and to restore those contentsautomatically when the shell is unmapped. It is useful forpop-up menus. Setting override_redirect True determineswhether the window manager can intercede when the shellwindow is mapped. For further information onoverride_redirect, see Section 3.2 in Xlib — C Language XInterface and Sections 4.1.10 and 4.2.2 in the Inter-ClientCommunication Conventions Manual. The pop-up and pop-downcallbacks are called during XtPopup and XtPopdown. Thedefault value of the visual resource is the symbolic valueCopyFromParent. The Intrinsics do not need to query theparent’s visual type when the default value is used; if aclient using XtGetValues to examine the visual type receivesthe value CopyFromParent, it must then useXGetWindowAttributes if it needs the actual visual type.The default values for Shell fields in WMShell and itssubclasses are:The title and title_encoding fields are stored in theWM_NAME property on the shell’s window by the WMShellrealize procedure. If the title_encoding field is None, thetitle string is assumed to be in the encoding of the currentlocale and the encoding of the WM_NAME property is set toXStdICCTextStyle. If a language procedure has not been setthe default value of title_encoding is XA_STRING, otherwisethe default value is None. The wm_timeout field specifies,in milliseconds, the amount of time a shell is to wait forconfirmation of a geometry request to the window manager.If none comes back within that time, the shell assumes thewindow manager is not functioning properly and setswait_for_wm to False (later events may reset this value).When wait_for_wm is False, the shell does not wait for aresponse, but relies on asynchronous notification. Iftransient is True, the WM_TRANSIENT_FOR property will bestored on the shell window with a value as specified below.The interpretation of this property is specific to thewindow manager under which the application is run; see theInter-Client Communication Conventions Manual for moredetails.The realize and set_values procedures of WMShell store theWM_CLIENT_LEADER property on the shell window. Whenclient_leader is not NULL and the client leader widget isrealized, the property will be created with the value of thewindow of the client leader widget. When client_leader isNULL and the shell widget has a NULL parent, the widget’swindow is used as the value of the property. Whenclient_leader is NULL and the shell widget has a non-NULLparent, a search is made for the closest shell ancestor witha non-NULL client_leader, and if none is found the shellancestor with a NULL parent is the result. If the resultingwidget is realized, the property is created with the valueof the widget’s window.When the value of window_role is not NULL, the realize andset_values procedures store the WM_WINDOW_ROLE property onthe shell’s window with the value of the resource.All other resources specify fields in the window managerhints and the window manager size hints. The realize andset_values procedures of WMShell set the corresponding flagbits in the hints if any of the fields contain nondefaultvalues. In addition, if a flag bit is set that refers to afield with the value XtUnspecifiedShellInt, the value of thefield is modified as follows:If the shell widget has a non-NULL parent, then the realizeand set_values procedures replace the valueXtUnspecifiedWindow in the window_group field with thewindow id of the root widget of the widget tree if the rootwidget is realized. The symbolic constantXtUnspecifiedWindowGroup may be used to indicate that thewindow_group hint flag bit is not to be set. If transientis True, the shell’s class is not a subclass ofTransientShell, and window_group is notXtUnspecifiedWindowGroup, the WMShell realize and set_valuesprocedures then store the WM_TRANSIENT_FOR property with thevalue of window_group.Transient shells have the following additional resource:The realize and set_values procedures of TransientShellstore the WM_TRANSIENT_FOR property on the shell window iftransient is True. If transient_for is non-NULL and thewidget specified by transient_for is realized, then itswindow is used as the value of the WM_TRANSIENT_FORproperty; otherwise, the value of window_group is used.TopLevel shells have the the following additional resources:The icon_name and icon_name_encoding fields are stored inthe WM_ICON_NAME property on the shell’s window by theTopLevelShell realize procedure. If the icon_name_encodingfield is None, the icon_name string is assumed to be in theencoding of the current locale and the encoding of theWM_ICON_NAME property is set to XStdICCTextStyle. If alanguage procedure has not been set, the default value oficon_name_encoding is XA_STRING, otherwise the default valueis None. The iconic field may be used by a client torequest that the window manager iconify or deiconify theshell; the TopLevelShell set_values procedure will send theappropriate WM_CHANGE_STATE message (as specified by theInter-Client Communication Conventions Manual) if thisresource is changed from False to True and will call XtPopupspecifying grab_kind as XtGrabNone if iconic is changed fromTrue to False. The XtNiconic resource is also analternative way to set the XtNinitialState resource toindicate that a shell should be initially displayed as anicon; the TopLevelShell initialize procedure will setinitial_state to IconicState if iconic is True.Application shells have the following additional resources:The argc and argv fields are used to initialize the standardproperty WM_COMMAND. See the Inter-Client CommunicationConventions Manual for more information.The default values for the SessionShell instance fields,which are filled in from the resource lists and by theinitialize procedure, areThe connection field contains the session connection objector NULL if a session connection is not being managed by thiswidget.The session_id is an identification assigned to the sessionparticipant by the session manager. The session_id will bepassed to the session manager as the client identifier ofthe previous session. When a connection is established withthe session manager, the client id assigned by the sessionmanager is stored in the session_id field. When not NULL,the session_id of the Session shell widget that is at theroot of the widget tree of the client leader widget will beused to create the SM_CLIENT_ID property on the clientleader’s window.If join_session is False, the widget will not attempt toestablish a connection to the session manager at shellcreation time. See Sections 4.2.1 and 4.2.4 for moreinformation on the functionality of this resource.The restart_command, clone_command, discard_command,resign_command, shutdown_command, environment, current_dir,program_path, and restart_style fields contain standardsession properties.When a session connection is established or newly managed bythe shell, the shell initialize and set_values methods checkthe values of the restart_command, clone_command, andprogram_path resources. At that time, if restart_command isNULL, the value of the argv resource will be copied torestart_command. Whether or not restart_command was NULL,if "-xtsessionID" "<session id>" does not already appear inthe restart_command, it will be added by the initialize andset_values methods at the beginning of the commandarguments; if the "-xtsessionID" argument already appearswith an incorrect session id in the following argument, thatargument will be replaced with the current session id.After this, the shell initialize and set_values procedurescheck the clone_command. If clone_command is NULL,restart_command will be copied to clone_command, except the"-xtsessionID" and following argument will not be copied.Finally, the shell initialize and set_values procedurescheck the program_path. If program_path is NULL, the firstelement of restart_command is copied to program_path.The possible values of restart_style are SmRestartIfRunning,SmRestartAnyway, SmRestartImmediately, and SmRestartNever.A resource converter is registered for this resource; forthe strings that it recognizes, see Section 9.6.1.The resource type EnvironmentArray is a NULL-terminatedarray of pointers to strings; each string has the format"name=value". The ‘=’ character may not appear in the name,and the string is terminated by a null character.4.2. Session ParticipationApplications can participate in a user’s session, exchangingmessages with the session manager as described in the XSession Management Protocol and the X Session ManagementLibrary.When a widget of sessionShellWidgetClass or a subclass iscreated, the widget provides support for the application asa session participant and continues to provide support untilthe widget is destroyed.4.2.1. Joining a SessionWhen a Session shell is created, if connection is NULL, andif join_session is True, and if argv or restart_command isnot NULL, and if in POSIX environments the SESSION_MANAGERenvironment variable is defined, the shell will attempt toestablish a new connection with the session manager.To transfer management of an existing session connectionfrom an application to the shell at widget creation time,pass the existing session connection ID as the connectionresource value when creating the Session shell, and if theother creation-time conditions on session participation aremet, the widget will maintain the connection with thesession manager. The application must ensure that only oneSession shell manages the connection.In the Session shell set_values procedure, if join_sessionchanges from False to True and connection is NULL and whenin POSIX environments the SESSION_MANAGER environmentvariable is defined, the shell will attempt to open aconnection to the session manager. If connection changesfrom NULL to non-NULL, the Session shell will take overmanagement of that session connection and will setjoin_session to True. If join_session changes from False toTrue and connection is not NULL, the Session shell will takeover management of the session connection.When a successful connection has been established,connection contains the session connection ID for thesession participant. When the shell begins to manage theconnection, it will call XtAppAddInput to register thehandler which watches for protocol messages from the sessionmanager. When the attempt to connect fails, a warningmessage is issued and connection is set to NULL.While the connection is being managed, if a SaveYourself,SaveYourselfPhase2, Interact, ShutdownCancelled,SaveComplete, or Die message is received from the sessionmanager, the Session shell will call out to applicationcallback procedures registered on the respective callbacklist of the Session shell and will sendSaveYourselfPhase2Request, InteractRequest, InteractDone,SaveYourselfDone, and ConnectionClosed messages asappropriate. Initially, all of the client’s sessionproperties are undefined. When any of the session propertyresource values are defined or change, the Session shellinitialize and set_values procedures will update theclient’s session property value by a SetProperties or aDeleteProperties message, as appropriate. The sessionProcessID and UserID properties are always set by the shellwhen it is possible to determine the value of theseproperties.4.2.2. Saving Application StateThe session manager instigates an application checkpoint bysending a SaveYourself request. Applications areresponsible for saving their state in response to therequest.When the SaveYourself request arrives, the proceduresregistered on the Session shell’s save callback list arecalled. If the application does not register any savecallback procedures on the save callback list, the shellwill report to the session manager that the applicationfailed to save its state. Each procedure on the savecallback list receives a token in the call_data parameter.The checkpoint token in the call_data parameter is of typeXtCheckpointToken.__│ typedef struct {int save_type;int interact_style;Boolean shutdown;Boolean fast;Boolean cancel_shutdownint phase;int interact_dialog_type;/* return */Boolean request_cancel; /* return */Boolean request_next_phase; /* return */Boolean save_success; /* return */} XtCheckpointTokenRec, *XtCheckpointToken;│__ The save_type, interact_style, shutdown, and fast fields ofthe token contain the parameters of the SaveYourselfmessage. The possible values of save_type are SmSaveLocal,SmSaveGlobal, and SmSaveBoth; these indicate the type ofinformation to be saved. The possible values ofinteract_style are SmInteractStyleNone,SmInteractStyleErrors, and SmInteractStyleAny; theseindicate whether user interaction would be permitted and, ifso, what kind of interaction. If shutdown is True, thecheckpoint is being performed in preparation for the end ofthe session. If fast is True, the client should perform thecheckpoint as quickly as possible. If cancel_shutdown isTrue, a ShutdownCancelled message has been received for thecurrent save operation. (See Section 4.4.4.) The phase isused by manager clients, such as a window manager, todistinguish between the first and second phase of a saveoperation. The phase will be either 1 or 2. The remainingfields in the checkpoint token structure are provided forthe application to communicate with the shell.Upon entry to the first application save callback procedure,the return fields in the token have the following initialvalues: interact_dialog_type is SmDialogNormal;request_cancel is False; request_next_phase is False; andsave_success is True. When a token is returned with any ofthe four return fields containing a noninitial value, andwhen the field is applicable, subsequent tokens passed tothe application during the current save operation willalways contain the noninitial value.The purpose of the token’s save_success field is to indicatethe outcome of the entire operation to the session managerand ultimately, to the user. Returning False indicates someportion of the application state could not be successfullysaved. If any token is returned to the shell withsave_success False, tokens subsequently received by theapplication for the current save operation will showsave_success as False. When the shell sends the finalstatus of the checkpoint to the session manager, it willindicate failure to save application state if any token wasreturned with save_success False.Session participants that manage and save the state of otherclients should structure their save or interact callbacks toset request_next_phase to True when phase is 1, which willcause the shell to send the SaveYourselfPhase2Request whenthe first phase is complete. When the SaveYourselfPhase2message is received, the shell will invoke the savecallbacks a second time with phase equal to 2. Managerclients should save the state of other clients when thecallbacks are invoked the second time and phase equal to 2.The application may request additional tokens while acheckpoint is under way, and these additional tokens must bereturned by an explicit call.To request an additional token for a save callback responsethat has a deferred outcome, use XtSessionGetToken.__│ XtCheckpointToken XtSessionGetToken(widget)Widget widget;widget Specifies the Session shell widget which managessession participation.│__ The XtSessionGetToken function will return NULL if nocheckpoint operation is currently under way.To indicate the completion of checkpoint processingincluding user interaction, the application must signal theSession shell by returning all tokens. (See Sections4.2.2.2 and 4.2.2.4). To return a token, useXtSessionReturnToken.__│ void XtSessionReturnToken(token)XtCheckpointToken token;token Specifies a token that was received as thecall_data by a procedure on the interact callbacklist or a token that was received by a call toXtSessionGetToken.│__ Tokens passed as call_data to save callbacks are implicitlyreturned when the save callback procedure returns. A savecallback procedure should not call XtSessionReturnToken onthe token passed in its call_data.4.2.2.1. Requesting InteractionWhen the token interact_style allows user interaction, theapplication may interact with the user during thecheckpoint, but must wait for permission to interact.Applications request permission to interact with the userduring the checkpointing operation by registering aprocedure on the Session shell’s interact callback list.When all save callback procedures have returned, and eachtime a token that was granted by a call to XtSessionGetTokenis returned, the Session shell examines the interactcallback list. If interaction is permitted and the interactcallback list is not empty, the shell will send anInteractRequest to the session manager when an interactrequest is not already outstanding for the application.The type of interaction dialog that will be requested isspecified by the interact_dialog_type field in thecheckpoint token. The possible values forinteract_dialog_type are SmDialogError and SmDialogNormal.If a token is returned with interact_dialog_type containingSmDialogError, the interact request and any subsequentinteract requests will be for an error dialog; otherwise,the request will be for a normal dialog with the user.When a token is returned with save_success False orinteract_dialog_type SmDialogError, tokens subsequentlypassed to callbacks during the same active SaveYourselfresponse will reflect these changed values, indicating thatan error condition has occurred during the checkpoint.The request_cancel field is a return value for interactcallbacks only. Upon return from a procedure on the savecallback list, the value of the token’s request_cancel fieldis not examined by the shell. This is also true of tokensreceived through a call to XtSessionGetToken.4.2.2.2. Interacting with the User during a CheckpointWhen the session manager grants the application’s requestfor user interaction, the Session shell receives an Interactmessage. The procedures registered on the interact callbacklist are executed, but not as if executing a typicalcallback list. These procedures are individually executedin sequence, with a checkpoint token functioning as thesequencing mechanism. Each step in the sequence begins byremoving a procedure from the interact callback list andexecuting it with a token passed in the call_data. Theinteract callback will typically pop up a dialog box andreturn. When the user interaction and associatedapplication checkpointing has completed, the applicationmust return the token by calling XtSessionReturnToken.Returning the token completes the current step and triggersthe next step in the sequence.During interaction the client may request cancellation of ashutdown. When a token passed as call_data to an interactprocedure is returned, if shutdown is True andcancel_shutdown is False, request_cancel indicates whetherthe application requests that the pending shutdown becancelled. If request_cancel is True, the field will alsobe True in any tokens subsequently granted during thecheckpoint operation. When a token is returned requestingcancellation of the session shutdown, pending interactprocedures will still be called by the Session shell. Whenall interact procedures have been removed from the interactcallback list, executed, and the final interact tokenreturned to the shell, an InteractDone message is sent tothe session manager, indicating whether a pending sessionshutdown is requested to be cancelled.4.2.2.3. Responding to a Shutdown CancellationCallbacks registered on the cancel callback list are invokedwhen the Session shell processes a ShutdownCancelled messagefrom the session manager. This may occur during theprocessing of save callbacks, while waiting for interactpermission, during user interaction, or after the saveoperation is complete and the application is expecting aSaveComplete or a Die message. The call_data for thesecallbacks is NULL.When the shell notices that a pending shutdown has beencancelled, the token cancel_shutdown field will be True intokens subsequently given to the application.Receiving notice of a shutdown cancellation does not cancelthe pending execution of save callbacks or interactcallbacks. After the cancel callbacks execute, ifinteract_style is not SmInteractStyleNone and the interactlist is not empty, the procedures on the interact callbacklist will be executed and passed a token with interact_styleSmInteractStyleNone. The application should not interactwith the user, and the Session shell will not send anInteractDone message.4.2.2.4. Completing a SaveWhen there is no user interaction, the shell regards theapplication as having finished saving state when allcallback procedures on the save callback list have returned,and any additional tokens passed out by XtSessionGetTokenhave been returned by corresponding calls toXtSessionReturnToken. If the save operation involved userinteraction, the above completion conditions apply, and inaddition, all requests for interaction have been granted orcancelled, and all tokens passed to interact callbacks havebeen returned through calls to XtSessionReturnToken. If thesave operation involved a manager client that requested thesecond phase, the above conditions apply to both the firstand second phase of the save operation.When the application has finished saving state, the Sessionshell will report the result to the session manager bysending the SaveYourselfDone message. If the session iscontinuing, the shell will receive the SaveComplete messagewhen all applications have completed saving state. Thismessage indicates that applications may again allow changesto their state. The shell will execute the save_completecallbacks. The call_data for these callbacks is NULL.4.2.3. Responding to a ShutdownCallbacks registered on the die callback list are invokedwhen the session manager sends a Die message. The callbackson this list should do whatever is appropriate to quit theapplication. Before executing procedures on the diecallback list, the Session shell will close the connectionto the session manager and will remove the handler thatwatches for protocol messages. The call_data for thesecallbacks is NULL.4.2.4. Resigning from a SessionWhen the Session shell widget is destroyed, the destroymethod will close the connection to the session manager bysending a ConnectionClosed protocol message and will removethe input callback that was watching for session protocolmessages.When XtSetValues is used to set join_session to False, theset_values method of the Session shell will close theconnection to the session manager if one exists by sending aConnectionClosed message, and connection will be set toNULL.Applications that exit in response to user actions and thatdo not wait for phase 2 destroy to complete on the Sessionshell should set join_session to False before exiting.When XtSetValues is used to set connection to NULL, theSession shell will stop managing the connection, if oneexists. However, that session connection will not beclosed.Applications that wish to ensure continuation of a sessionconnection beyond the destruction of the shell should firstretrieve the connection resource value, then set theconnection resource to NULL, and then they may safelydestroy the widget without losing control of the sessionconnection.The error callback list will be called if an unrecoverablecommunications error occurs while the shell is managing theconnection. The shell will close the connection, setconnection to NULL, remove the input callback, and call theprocedures registered on the error callback list. Thecall_data for these callbacks is NULL.4
5.1. Pop-Up Widget Types
5.2. Creating a Pop-Up ShellFor a widget to be popped up, it must be the child of apop-up shell widget. None of the Intrinsics-supplied shellswill simultaneously manage more than one child. Both theshell and child taken together are referred to as thepop-up. When you need to use a pop-up, you always refer tothe pop-up by the pop-up shell, not the child.To create a pop-up shell, use XtCreatePopupShell.__│ Widget XtCreatePopupShell(name, widget_class, parent, args, num_args)String name;WidgetClass widget_class;Widget parent;ArgList args;Cardinal num_args;name Specifies the instance name for the created shellwidget.widget_classSpecifies the widget class pointer for the createdshell widget.parent Specifies the parent widget. Must be of classCore or any subclass thereof.args Specifies the argument list to override any otherresource specifications.num_args Specifies the number of entries in the argumentlist.│__ The XtCreatePopupShell function ensures that the specifiedclass is a subclass of Shell and, rather than usinginsert_child to attach the widget to the parent’s childrenlist, attaches the shell to the parent’s popup_listdirectly.The screen resource for this widget is determined by firstscanning args for the XtNscreen argument. If no XtNscreenargument is found, the resource database associated with theparent’s screen is queried for the resource name.screen,class Class.Screen where Class is the class_name field fromthe CoreClassPart of the specified widget_class. If thisquery fails, the parent’s screen is used. Once the screenis determined, the resource database associated with thatscreen is used to retrieve all remaining resources for thewidget not specified in args.A spring-loaded pop-up invoked from a translation table viaXtMenuPopup must already exist at the time that thetranslation is invoked, so the translation manager can findthe shell by name. Pop-ups invoked in other ways can becreated when the pop-up actually is needed. This delayedcreation of the shell is particularly useful when you pop upan unspecified number of pop-ups. You can look to see if anappropriate unused shell (that is, not currently popped up)exists and create a new shell if needed.To create a pop-up shell using varargs lists, useXtVaCreatePopupShell.__│ Widget XtVaCreatePopupShell(name, widget_class, parent, ...)String name;WidgetClass widget_class;Widget parent;name Specifies the instance name for the created shellwidget.widget_classSpecifies the widget class pointer for the createdshell widget.parent Specifies the parent widget. Must be of classCore or any subclass thereof.... Specifies the variable argument list to overrideany other resource specifications.│__ XtVaCreatePopupShell is identical in function toXtCreatePopupShell with the args and num_args parametersreplaced by a varargs list as described in Section 2.5.1.5.3. Creating Pop-Up ChildrenOnce a pop-up shell is created, the single child of thepop-up shell can be created either statically ordynamically.At startup, an application can create the child of thepop-up shell, which is appropriate for pop-up childrencomposed of a fixed set of widgets. The application canchange the state of the subparts of the pop-up child as theapplication state changes. For example, if an applicationcreates a static menu, it can call XtSetSensitive (or, ingeneral, XtSetValues) on any of the buttons that make up themenu. Creating the pop-up child early means that pop-uptime is minimized, especially if the application callsXtRealizeWidget on the pop-up shell at startup. When themenu is needed, all the widgets that make up the menualready exist and need only be mapped. The menu should popup as quickly as the X server can respond.Alternatively, an application can postpone the creation ofthe child until it is needed, which minimizes applicationstartup time and allows the pop-up child to reconfigureitself each time it is popped up. In this case, the pop-upchild creation routine might poll the application to findout if it should change the sensitivity of any of itssubparts.Pop-up child creation does not map the pop-up, even if youcreate the child and call XtRealizeWidget on the pop-upshell.All shells have pop-up and pop-down callbacks, which providethe opportunity either to make last-minute changes to apop-up child before it is popped up or to change it after itis popped down. Note that excessive use of pop-up callbackscan make popping up occur more slowly.5.4. Mapping a Pop-Up WidgetPop-ups can be popped up through several mechanisms:• A call to XtPopup or XtPopupSpringLoaded.• One of the supplied callback procedures XtCallbackNone,XtCallbackNonexclusive, or XtCallbackExclusive.• The standard translation action XtMenuPopup.Some of these routines take an argument of type XtGrabKind,which is defined as__│ typedef enum {XtGrabNone, XtGrabNonexclusive, XtGrabExclusive} XtGrabKind;│__ The create_popup_child_proc procedure pointer in the shellwidget instance record is of type XtCreatePopupChildProc.__│ typedef void (*XtCreatePopupChildProc)(Widget);Widget w;w Specifies the shell widget being popped up.│__ To map a pop-up from within an application, use XtPopup.__│ void XtPopup(popup_shell, grab_kind)Widget popup_shell;XtGrabKind grab_kind;popup_shellSpecifies the shell widget.grab_kind Specifies the way in which user events should beconstrained.│__ The XtPopup function performs the following:• Calls XtCheckSubclass to ensure popup_shell’s class isa subclass of shellWidgetClass.• Raises the window and returns if the shell’s popped_upfield is already True.• Calls the callback procedures on the shell’spopup_callback list, specifying a pointer to the valueof grab_kind as the call_data argument.• Sets the shell popped_up field to True, the shellspring_loaded field to False, and the shell grab_kindfield from grab_kind.• If the shell’s create_popup_child_proc field isnon-NULL, XtPopup calls it with popup_shell as theparameter.• If grab_kind is either XtGrabNonexclusive orXtGrabExclusive, it callsXtAddGrab(popup_shell, (grab_kind == XtGrabExclusive), False)• Calls XtRealizeWidget with popup_shell specified.• Calls XMapRaised with the window of popup_shell.To map a spring-loaded pop-up from within an application,use XtPopupSpringLoaded.__│ void XtPopupSpringLoaded(popup_shell)Widget popup_shell;popup_shellSpecifies the shell widget to be popped up.│__ The XtPopupSpringLoaded function performs exactly as XtPopupexcept that it sets the shell spring_loaded field to Trueand always calls XtAddGrab with exclusive True andspring-loaded True.To map a pop-up from a given widget’s callback list, youalso can register one of the XtCallbackNone,XtCallbackNonexclusive, or XtCallbackExclusive convenienceroutines as callbacks, using the pop-up shell widget as theclient data.__│ void XtCallbackNone(w, client_data, call_data)Widget w;XtPointer client_data;XtPointer call_data;w Specifies the widget.client_dataSpecifies the pop-up shell.call_data Specifies the callback data argument, which is notused by this procedure.void XtCallbackNonexclusive(w, client_data, call_data)Widget w;XtPointer client_data;XtPointer call_data;w Specifies the widget.client_dataSpecifies the pop-up shell.call_data Specifies the callback data argument, which is notused by this procedure.void XtCallbackExclusive(w, client_data, call_data)Widget w;XtPointer client_data;XtPointer call_data;w Specifies the widget.client_dataSpecifies the pop-up shell.call_data Specifies the callback data argument, which is notused by this procedure.│__ The XtCallbackNone, XtCallbackNonexclusive, andXtCallbackExclusive functions call XtPopup with the shellspecified by the client_data argument and grab_kind set asthe name specifies. XtCallbackNone, XtCallbackNonexclusive,and XtCallbackExclusive specify XtGrabNone,XtGrabNonexclusive, and XtGrabExclusive, respectively. Eachfunction then sets the widget that executed the callbacklist to be insensitive by calling XtSetSensitive. Usingthese functions in callbacks is not required. Inparticular, an application must provide customized code forcallbacks that create pop-up shells dynamically or that mustdo more than desensitizing the button.Within a translation table, to pop up a menu when a key orpointer button is pressed or when the pointer is moved intoa widget, use XtMenuPopup, or its synonym, MenuPopup. Froma translation writer’s point of view, the definition forthis translation action is__│ void XtMenuPopup(shell_name)String shell_name;shell_nameSpecifies the name of the shell widget to pop up.│__ XtMenuPopup is known to the translation manager, whichregisters the corresponding built-in action procedureXtMenuPopupAction using XtRegisterGrabAction specifyingowner_events True, event_mask ButtonPressMask |ButtonReleaseMask, and pointer_mode and keyboard_modeGrabModeAsync.If XtMenuPopup is invoked on ButtonPress, it callsXtPopupSpringLoaded on the specified shell widget. IfXtMenuPopup is invoked on KeyPress or EnterWindow, it callsXtPopup on the specified shell widget with grab_kind set toXtGrabNonexclusive. Otherwise, the translation managergenerates a warning message and ignores the action.XtMenuPopup tries to find the shell by searching the widgettree starting at the widget in which it is invoked. If itfinds a shell with the specified name in the pop-up childrenof that widget, it pops up the shell with the appropriateparameters. Otherwise, it moves up the parent chain to finda pop-up child with the specified name. If XtMenuPopup getsto the application top-level shell widget and has not founda matching shell, it generates a warning and returnsimmediately.5.5. Unmapping a Pop-Up WidgetPop-ups can be popped down through several mechanisms:• A call to XtPopdown• The supplied callback procedure XtCallbackPopdown• The standard translation action XtMenuPopdownTo unmap a pop-up from within an application, use XtPopdown.__│ void XtPopdown(popup_shell)Widget popup_shell;popup_shellSpecifies the shell widget to pop down.│__ The XtPopdown function performs the following:• Calls XtCheckSubclass to ensure popup_shell’s class isa subclass of shellWidgetClass.• Checks that the popped_up field of popup_shell is True;otherwise, it returns immediately.• Unmaps popup_shell’s window and, if override_redirectis False, sends a synthetic UnmapNotify event asspecified by the Inter-Client Communication ConventionsManual.• If popup_shell’s grab_kind is either XtGrabNonexclusiveor XtGrabExclusive, it calls XtRemoveGrab.• Sets popup_shell’s popped_up field to False.• Calls the callback procedures on the shell’spopdown_callback list, specifying a pointer to thevalue of the shell’s grab_kind field as the call_dataargument.To pop down a pop-up from a callback list, you may use thecallback XtCallbackPopdown.__│ void XtCallbackPopdown(w, client_data, call_data)Widget w;XtPointer client_data;XtPointer call_data;w Specifies the widget.client_dataSpecifies a pointer to the XtPopdownID structure.call_data Specifies the callback data argument, which is notused by this procedure.│__ The XtCallbackPopdown function casts the client_dataparameter to a pointer of type XtPopdownID.__│ typedef struct {Widget shell_widget;Widget enable_widget;} XtPopdownIDRec, *XtPopdownID;│__ The shell_widget is the pop-up shell to pop down, and theenable_widget is usually the widget that was used to pop itup in one of the pop-up callback convenience procedures.XtCallbackPopdown calls XtPopdown with the specifiedshell_widget and then calls XtSetSensitive to resensitizeenable_widget.Within a translation table, to pop down a spring-loaded menuwhen a key or pointer button is released or when the pointeris moved into a widget, use XtMenuPopdown or its synonym,MenuPopdown. From a translation writer’s point of view, thedefinition for this translation action is__│ void XtMenuPopdown(shell_name)String shell_name;shell_nameSpecifies the name of the shell widget to popdown.│__ If a shell name is not given, XtMenuPopdown calls XtPopdownwith the widget for which the translation is specified. Ifshell_name is specified in the translation table,XtMenuPopdown tries to find the shell by looking up thewidget tree starting at the widget in which it is invoked.If it finds a shell with the specified name in the pop-upchildren of that widget, it pops down the shell; otherwise,it moves up the parent chain to find a pop-up child with thespecified name. If XtMenuPopdown gets to the applicationtop-level shell widget and cannot find a matching shell, itgenerates a warning and returns immediately.5
6.1. Initiating Geometry Changes
6.2. General Geometry Manager RequestsWhen making a geometry request, the child specifies anXtWidgetGeometry structure.__│ typedef unsigned long XtGeometryMask;typedef struct {XtGeometryMask request_mode;Position x, y;Dimension width, height;Dimension border_width;Widget sibling;int stack_mode;} XtWidgetGeometry;│__ To make a general geometry manager request from a widget,use XtMakeGeometryRequest.__│ XtGeometryResult XtMakeGeometryRequest(w, request, reply_return)Widget w;XtWidgetGeometry *request;XtWidgetGeometry *reply_return;w Specifies the widget making the request. Must beof class RectObj or any subclass thereof.request Specifies the desired widget geometry (size,position, border width, and stacking order).reply_returnReturns the allowed widget size, or may be NULL ifthe requesting widget is not interested inhandling XtGeometryAlmost.│__ Depending on the condition, XtMakeGeometryRequest performsthe following:• If the widget is unmanaged or the widget’s parent isnot realized, it makes the changes and returnsXtGeometryYes.• If the parent’s class is not a subclass ofcompositeWidgetClass or the parent’s geometry_managerfield is NULL, it issues an error.• If the widget’s being_destroyed field is True, itreturns XtGeometryNo.• If the widget x, y, width, height, and border_widthfields are all equal to the requested values, itreturns XtGeometryYes; otherwise, it calls the parent’sgeometry_manager procedure with the given parameters.• If the parent’s geometry manager returns XtGeometryYesand if XtCWQueryOnly is not set inrequest->request_mode and if the widget is realized,XtMakeGeometryRequest calls the XConfigureWindow Xlibfunction to reconfigure the widget’s window (set itssize, location, and stacking order as appropriate).• If the geometry manager returns XtGeometryDone, thechange has been approved and actually has been done.In this case, XtMakeGeometryRequest does no configuringand returns XtGeometryYes. XtMakeGeometryRequest neverreturns XtGeometryDone.• Otherwise, XtMakeGeometryRequest just returns theresulting value from the parent’s geometry manager.Children of primitive widgets are always unmanaged;therefore, XtMakeGeometryRequest always returnsXtGeometryYes when called by a child of a primitive widget.The return codes from geometry managers are__│ typedef enum {XtGeometryYes,XtGeometryNo,XtGeometryAlmost,XtGeometryDone} XtGeometryResult;│__ The request_mode definitions are from <X11/X.h>.__││__ The Intrinsics also support the following value.__││__ XtCWQueryOnly indicates that the corresponding geometryrequest is only a query as to what would happen if thisgeometry request were made and that no widgets shouldactually be changed.XtMakeGeometryRequest, like the XConfigureWindow Xlibfunction, uses request_mode to determine which fields in theXtWidgetGeometry structure the caller wants to specify.The stack_mode definitions are from <X11/X.h>:__││__ The Intrinsics also support the following value.__││__ For definition and behavior of Above, Below, TopIf,BottomIf, and Opposite, see Section 3.7 in Xlib — C LanguageX Interface. XtSMDontChange indicates that the widget wantsits current stacking order preserved.6.3. Resize RequestsTo make a simple resize request from a widget, you can useXtMakeResizeRequest as an alternative toXtMakeGeometryRequest.__│ XtGeometryResult XtMakeResizeRequest(w, width, height, width_return, height_return)Widget w;Dimension width, height;Dimension *width_return, *height_return;w Specifies the widget making the request. Must beof class RectObj or any subclass thereof.width Specify the desired widget width and height.heightwidth_returnReturn the allowed widget width and height.height_return│__ The XtMakeResizeRequest function, a simple interface toXtMakeGeometryRequest, creates an XtWidgetGeometry structureand specifies that width and height should change by settingrequest_mode to CWWidth | CWHeight. The geometry manager isfree to modify any of the other window attributes (positionor stacking order) to satisfy the resize request. If thereturn value is XtGeometryAlmost, width_return andheight_return contain a compromise width and height. Ifthese are acceptable, the widget should immediately callXtMakeResizeRequest again and request that the compromisewidth and height be applied. If the widget is notinterested in XtGeometryAlmost replies, it can pass NULL forwidth_return and height_return.6.4. Potential Geometry ChangesSometimes a geometry manager cannot respond to a geometryrequest from a child without first making a geometry requestto the widget’s own parent (the original requestor’sgrandparent). If the request to the grandparent would allowthe parent to satisfy the original request, the geometrymanager can make the intermediate geometry request as if itwere the originator. On the other hand, if the geometrymanager already has determined that the original requestcannot be completely satisfied (for example, if it alwaysdenies position changes), it needs to tell the grandparentto respond to the intermediate request without actuallychanging the geometry because it does not know if the childwill accept the compromise. To accomplish this, thegeometry manager uses XtCWQueryOnly in the intermediaterequest.When XtCWQueryOnly is used, the geometry manager needs tocache enough information to exactly reconstruct theintermediate request. If the grandparent’s response to theintermediate query was XtGeometryAlmost, the geometrymanager needs to cache the entire reply geometry in theevent the child accepts the parent’s compromise.If the grandparent’s response was XtGeometryAlmost, it mayalso be necessary to cache the entire reply geometry fromthe grandparent when XtCWQueryOnly is not used. If thegeometry manager is still able to satisfy the originalrequest, it may immediately accept the grandparent’scompromise and then act on the child’s request. If thegrandparent’s compromise geometry is insufficient to allowthe child’s request and if the geometry manager is willingto offer a different compromise to the child, thegrandparent’s compromise should not be accepted until thechild has accepted the new compromise.Note that a compromise geometry returned withXtGeometryAlmost is guaranteed only for the next call to thesame widget; therefore, a cache of size 1 is sufficient.6.5. Child Geometry Management: The geometry_managerProcedureThe geometry_manager procedure pointer in a composite widgetclass is of type XtGeometryHandler.__│ typedef XtGeometryResult (*XtGeometryHandler)(Widget, XtWidgetGeometry*, XtWidgetGeometry*);Widget w;XtWidgetGeometry *request;XtWidgetGeometry *geometry_return;w Passes the widget making the request.request Passes the new geometry the child desires.geometry_returnPasses a geometry structure in which thegeometry manager may store a compromise.│__ A class can inherit its superclass’s geometry manager duringclass initialization.A bit set to zero in the request’s request_mode field meansthat the child widget does not care about the value of thecorresponding field, so the geometry manager can change thisfield as it wishes. A bit set to 1 means that the childwants that geometry element set to the value in thecorresponding field.If the geometry manager can satisfy all changes requestedand if XtCWQueryOnly is not specified, it updates thewidget’s x, y, width, height, and border_width fieldsappropriately. Then, it returns XtGeometryYes, and thevalues pointed to by the geometry_return argument areundefined. The widget’s window is moved and resizedautomatically by XtMakeGeometryRequest.Homogeneous composite widgets often find it convenient totreat the widget making the request the same as any otherwidget, including reconfiguring it using XtConfigureWidgetor XtResizeWidget as part of its layout process, unlessXtCWQueryOnly is specified. If it does this, it shouldreturn XtGeometryDone to inform XtMakeGeometryRequest thatit does not need to do the configuration itself.NoteTo remain compatible with layout techniques usedin older widgets (before XtGeometryDone was addedto the Intrinsics), a geometry manager shouldavoid using XtResizeWidget or XtConfigureWidget onthe child making the request because the layoutprocess of the child may be in an intermediatestate in which it is not prepared to handle a callto its resize procedure. A self-contained widgetset may choose this alternative geometrymanagement scheme, however, provided that itclearly warns widget developers of thecompatibility consequences.Although XtMakeGeometryRequest resizes the widget’s window(if the geometry manager returns XtGeometryYes), it does notcall the widget class’s resize procedure. The requestingwidget must perform whatever resizing calculations areneeded explicitly.If the geometry manager disallows the request, the widgetcannot change its geometry. The values pointed to bygeometry_return are undefined, and the geometry managerreturns XtGeometryNo.Sometimes the geometry manager cannot satisfy the requestexactly but may be able to satisfy a similar request. Thatis, it could satisfy only a subset of the requests (forexample, size but not position) or a lesser request (forexample, it cannot make the child as big as the request butit can make the child bigger than its current size). Insuch cases, the geometry manager fills in the structurepointed to by geometry_return with the actual changes it iswilling to make, including an appropriate request_mode mask,and returns XtGeometryAlmost. If a bit ingeometry_return->request_mode is zero, the geometry manageragrees not to change the corresponding value ifgeometry_return is used immediately in a new request. If abit is 1, the geometry manager does change that element tothe corresponding value in geometry_return. More bits maybe set in geometry_return->request_mode than in the originalrequest if the geometry manager intends to change otherfields should the child accept the compromise.When XtGeometryAlmost is returned, the widget must decide ifthe compromise suggested in geometry_return is acceptable.If it is, the widget must not change its geometry directly;rather, it must make another call to XtMakeGeometryRequest.If the next geometry request from this child uses thegeometry_return values filled in by the geometry managerwith an XtGeometryAlmost return and if there have been nointervening geometry requests on either its parent or any ofits other children, the geometry manager must grant therequest, if possible. That is, if the child asksimmediately with the returned geometry, it should get ananswer of XtGeometryYes. However, dynamic behavior in theuser’s window manager may affect the final outcome.To return XtGeometryYes, the geometry manager frequentlyrearranges the position of other managed children by callingXtMoveWidget. However, a few geometry managers maysometimes change the size of other managed children bycalling XtResizeWidget or XtConfigureWidget. IfXtCWQueryOnly is specified, the geometry manager must returndata describing how it would react to this geometry requestwithout actually moving or resizing any widgets.Geometry managers must not assume that the request andgeometry_return arguments point to independent storage. Thecaller is permitted to use the same field for both, and thegeometry manager must allocate its own temporary storage, ifnecessary.6.6. Widget Placement and SizingTo move a sibling widget of the child making the geometryrequest, the parent uses XtMoveWidget.__│ void XtMoveWidget(w, x, y)Widget w;Position x;Position y;w Specifies the widget. Must be of class RectObj orany subclass thereof.xy Specify the new widget x and y coordinates.│__ The XtMoveWidget function returns immediately if thespecified geometry fields are the same as the old values.Otherwise, XtMoveWidget writes the new x and y values intothe object and, if the object is a widget and is realized,issues an Xlib XMoveWindow call on the widget’s window.To resize a sibling widget of the child making the geometryrequest, the parent uses XtResizeWidget.__│ void XtResizeWidget(w, width, height, border_width)Widget w;Dimension width;Dimension height;Dimension border_width;w Specifies the widget. Must be of class RectObj orany subclass thereof.widthheightborder_widthSpecify the new widget size.│__ The XtResizeWidget function returns immediately if thespecified geometry fields are the same as the old values.Otherwise, XtResizeWidget writes the new width, height, andborder_width values into the object and, if the object is awidget and is realized, issues an XConfigureWindow call onthe widget’s window.If the new width or height is different from the old values,XtResizeWidget calls the object’s resize procedure to notifyit of the size change.To move and resize the sibling widget of the child makingthe geometry request, the parent uses XtConfigureWidget.__│ void XtConfigureWidget(w, x, y, width, height, border_width)Widget w;Position x;Position y;Dimension width;Dimension height;Dimension border_width;w Specifies the widget. Must be of class RectObj orany subclass thereof.xy Specify the new widget x and y coordinates.widthheightborder_widthSpecify the new widget size.│__ The XtConfigureWidget function returns immediately if thespecified new geometry fields are all equal to the currentvalues. Otherwise, XtConfigureWidget writes the new x, y,width, height, and border_width values into the object and,if the object is a widget and is realized, makes an XlibXConfigureWindow call on the widget’s window.If the new width or height is different from its old value,XtConfigureWidget calls the object’s resize procedure tonotify it of the size change; otherwise, it simply returns.To resize a child widget that already has the new values ofits width, height, and border width, the parent usesXtResizeWindow.__│ void XtResizeWindow(w)Widget w;w Specifies the widget. Must be of class Core orany subclass thereof.│__ The XtResizeWindow function calls the XConfigureWindow Xlibfunction to make the window of the specified widget matchits width, height, and border width. This request is doneunconditionally because there is no inexpensive way to tellif these values match the current values. Note that thewidget’s resize procedure is not called.There are very few times to use XtResizeWindow; instead, theparent should use XtResizeWidget.6.7. Preferred GeometrySome parents may be willing to adjust their layouts toaccommodate the preferred geometries of their children.They can use XtQueryGeometry to obtain the preferredgeometry and, as they see fit, can use or ignore any portionof the response.To query a child widget’s preferred geometry, useXtQueryGeometry.__│ XtGeometryResult XtQueryGeometry(w, intended, preferred_return)Widget w;XtWidgetGeometry *intended;XtWidgetGeometry *preferred_return;w Specifies the widget. Must be of class RectObjor any subclass thereof.intended Specifies the new geometry the parent plans togive to the child, or NULL.preferred_returnReturns the child widget’s preferred geometry.│__ To discover a child’s preferred geometry, the child’s parentstores the new geometry in the corresponding fields of theintended structure, sets the corresponding bits inintended.request_mode, and calls XtQueryGeometry. Theparent should set only those fields that are important to itso that the child can determine whether it may be able toattempt changes to other fields.XtQueryGeometry clears all bits in thepreferred_return->request_mode field and checks thequery_geometry field of the specified widget’s class record.If query_geometry is not NULL, XtQueryGeometry calls thequery_geometry procedure and passes as arguments thespecified widget, intended, and preferred_return structures.If the intended argument is NULL, XtQueryGeometry replacesit with a pointer to an XtWidgetGeometry structure withrequest_mode equal to zero before calling the query_geometryprocedure. NoteIf XtQueryGeometry is called from within ageometry_manager procedure for the widget thatissued XtMakeGeometryRequest orXtMakeResizeRequest, the results are notguaranteed to be consistent with the requestedchanges. The change request passed to thegeometry manager takes precedence over thepreferred geometry.The query_geometry procedure pointer is of typeXtGeometryHandler.__│ typedef XtGeometryResult (*XtGeometryHandler)(Widget, XtWidgetGeometry*, XtWidgetGeometry*);Widget w;XtWidgetGeometry *request;XtWidgetGeometry *preferred_return;w Passes the child widget whose preferred geometryis required.request Passes the geometry changes that the parentplans to make.preferred_returnPasses a structure in which the child returnsits preferred geometry.│__ The query_geometry procedure is expected to examine the bitsset in request->request_mode, evaluate the preferredgeometry of the widget, and store the result inpreferred_return (setting the bits inpreferred_return->request_mode corresponding to thosegeometry fields that it cares about). If the proposedgeometry change is acceptable without modification, thequery_geometry procedure should return XtGeometryYes. If atleast one field in preferred_return with a bit set inpreferred_return->request_mode is different from thecorresponding field in request or if a bit was set inpreferred_return->request_mode that was not set in therequest, the query_geometry procedure should returnXtGeometryAlmost. If the preferred geometry is identical tothe current geometry, the query_geometry procedure shouldreturn XtGeometryNo. NoteThe query_geometry procedure may assume that noXtMakeResizeRequest or XtMakeGeometryRequest is inprogress for the specified widget; that is, it isnot required to construct a reply consistent withthe requested geometry if such a request wereactually outstanding.After calling the query_geometry procedure or if thequery_geometry field is NULL, XtQueryGeometry examines allthe unset bits in preferred_return->request_mode and setsthe corresponding fields in preferred_return to the currentvalues from the widget instance. If CWStackMode is not set,the stack_mode field is set to XtSMDontChange.XtQueryGeometry returns the value returned by thequery_geometry procedure or XtGeometryYes if thequery_geometry field is NULL.Therefore, the caller can interpret a return ofXtGeometryYes as not needing to evaluate the contents of thereply and, more important, not needing to modify its layoutplans. A return of XtGeometryAlmost means either that boththe parent and the child expressed interest in at least onecommon field and the child’s preference does not match theparent’s intentions or that the child expressed interest ina field that the parent might need to consider. A returnvalue of XtGeometryNo means that both the parent and thechild expressed interest in a field and that the childsuggests that the field’s current value in the widgetinstance is its preferred value. In addition, whether ornot the caller ignores the return value or the reply mask,it is guaranteed that the preferred_return structurecontains complete geometry information for the child.Parents are expected to call XtQueryGeometry in their layoutroutine and wherever else the information is significantafter change_managed has been called. The first time it isinvoked, the changed_managed procedure may assume that thechild’s current geometry is its preferred geometry. Thus,the child is still responsible for storing values into itsown geometry during its initialize procedure.6.8. Size Change Management: The resize ProcedureA child can be resized by its parent at any time. Widgetsusually need to know when they have changed size so thatthey can lay out their displayed data again to match the newsize. When a parent resizes a child, it callsXtResizeWidget, which updates the geometry fields in thewidget, configures the window if the widget is realized, andcalls the child’s resize procedure to notify the child. Theresize procedure pointer is of type XtWidgetProc.If a class need not recalculate anything when a widget isresized, it can specify NULL for the resize field in itsclass record. This is an unusual case and should occur onlyfor widgets with very trivial display semantics. The resizeprocedure takes a widget as its only argument. The x, y,width, height, and border_width fields of the widget containthe new values. The resize procedure should recalculate thelayout of internal data as needed. (For example, a centeredLabel in a window that changes size should recalculate thestarting position of the text.) The widget must obey resizeas a command and must not treat it as a request. A widgetmust not issue an XtMakeGeometryRequest orXtMakeResizeRequest call from its resize procedure.6
7.1. Adding and Deleting Additional Event SourcesWhile most applications are driven only by X events, someapplications need to incorporate other sources of input intothe Intrinsics event-handling mechanism. The event managerprovides routines to integrate notification of timer eventsand file data pending into this mechanism.The next section describes functions that provide inputgathering from files. The application registers the fileswith the Intrinsics read routine. When input is pending onone of the files, the registered callback procedures areinvoked.7.1.1. Adding and Removing Input SourcesTo register a new file as an input source for a givenapplication context, use XtAppAddInput.__│ XtInputId XtAppAddInput(app_context, source, condition, proc, client_data)XtAppContext app_context;int source;XtPointer condition;XtInputCallbackProc proc;XtPointer client_data;app_contextSpecifies the application context that identifiesthe application.source Specifies the source file descriptor on aPOSIX-based system or otheroperating-system-dependent device specification.condition Specifies the mask that indicates a read, write,or exception condition or some otheroperating-system-dependent condition.proc Specifies the procedure to be called when thecondition is found.client_dataSpecifies an argument passed to the specifiedprocedure when it is called.│__ The XtAppAddInput function registers with the Intrinsicsread routine a new source of events, which is usually fileinput but can also be file output. Note that file should beloosely interpreted to mean any sink or source of data.XtAppAddInput also specifies the conditions under which thesource can generate events. When an event is pending onthis source, the callback procedure is called.The legal values for the condition argument areoperating-system-dependent. On a POSIX-based system, sourceis a file number and the condition is some union of thefollowing:XtInputReadMaskSpecifies that proc is to be called whensource has data to be read.XtInputWriteMaskSpecifies that proc is to be called whensource is ready for writing.XtInputExceptMaskSpecifies that proc is to be called whensource has exception data.Callback procedure pointers used to handle file events areof type XtInputCallbackProc.__│ typedef void (*XtInputCallbackProc)(XtPointer, int*, XtInputId*);XtPointer client_data;int *source;XtInputId *id;client_dataPasses the client data argument that wasregistered for this procedure in XtAppAddInput.source Passes the source file descriptor generating theevent.id Passes the id returned from the correspondingXtAppAddInput call.│__ See Section 7.12 for information regarding the use ofXtAppAddInput in multiple threads.To discontinue a source of input, use XtRemoveInput.__│ void XtRemoveInput(id)XtInputId id;id Specifies the id returned from the correspondingXtAppAddInput call.│__ The XtRemoveInput function causes the Intrinsics readroutine to stop watching for events from the file sourcespecified by id.See Section 7.12 for information regarding the use ofXtRemoveInput in multiple threads.7.1.2. Adding and Removing Blocking NotificationsOccasionally it is desirable for an application to receivenotification when the Intrinsics event manager detects nopending input from file sources and no pending input from Xserver event sources and is about to block in an operatingsystem call.To register a hook that is called immediately prior to eventblocking, use XtAppAddBlockHook.__│ XtBlockHookId XtAppAddBlockHook(app_context, proc, client_data)XtAppContext app_context;XtBlockHookProc proc;XtPointer client_data;app_contextSpecifies the application context that identifiesthe application.proc Specifies the procedure to be called beforeblocking.client_dataSpecifies an argument passed to the specifiedprocedure when it is called.│__ The XtAppAddBlockHook function registers the specifiedprocedure and returns an identifier for it. The hookprocedure proc is called at any time in the future when theIntrinsics are about to block pending some input.The procedure pointers used to provide notification of eventblocking are of type XtBlockHookProc.__│ typedef void (*XtBlockHookProc)(XtPointer);XtPointer client_data;client_dataPasses the client data argument that wasregistered for this procedure in XtApp-AddBlockHook.│__ To discontinue the use of a procedure for blockingnotification, use XtRemoveBlockHook.__│ void XtRemoveBlockHook(id)XtBlockHookId id;id Specifies the identifier returned from thecorresponding call to XtAppAddBlockHook.│__ The XtRemoveBlockHook function removes the specifiedprocedure from the list of procedures that are called by theIntrinsics read routine before blocking on event sources.7.1.3. Adding and Removing TimeoutsThe timeout facility notifies the application or the widgetthrough a callback procedure that a specified time intervalhas elapsed. Timeout values are uniquely identified by aninterval id.To register a timeout callback, use XtAppAddTimeOut.__│ XtIntervalId XtAppAddTimeOut(app_context, interval, proc, client_data)XtAppContext app_context;unsigned long interval;XtTimerCallbackProc proc;XtPointer client_data;app_contextSpecifies the application context for which thetimer is to be set.interval Specifies the time interval in milliseconds.proc Specifies the procedure to be called when the timeexpires.client_dataSpecifies an argument passed to the specifiedprocedure when it is called.│__ The XtAppAddTimeOut function creates a timeout and returnsan identifier for it. The timeout value is set to interval.The callback procedure proc is called when XtAppNextEvent orXtAppProcessEvent is next called after the time intervalelapses, and then the timeout is removed.Callback procedure pointers used with timeouts are of typeXtTimerCallbackProc.__│ typedef void (*XtTimerCallbackProc)(XtPointer, XtIntervalId*);XtPointer client_data;XtIntervalId *timer;client_dataPasses the client data argument that wasregistered for this procedure in XtAppAddTimeOut.timer Passes the id returned from the correspondingXtAppAddTimeOut call.│__ See Section 7.12 for information regarding the use ofXtAppAddTimeOut in multiple threads.To clear a timeout value, use XtRemoveTimeOut.__│ void XtRemoveTimeOut(timer)XtIntervalId timer;timer Specifies the id for the timeout request to becleared.│__ The XtRemoveTimeOut function removes the pending timeout.Note that timeouts are automatically removed once theytrigger.Please refer to Section 7.12 for information regarding theuse of XtRemoveTimeOut in multiple threads.7.1.4. Adding and Removing Signal CallbacksThe signal facility notifies the application or the widgetthrough a callback procedure that a signal or other externalasynchronous event has occurred. The registered callbackprocedures are uniquely identified by a signal id.Prior to establishing a signal handler, the application orwidget should call XtAppAddSignal and store the resultingidentifier in a place accessible to the signal handler.When a signal arrives, the signal handler should callXtNoticeSignal to notify the Intrinsics that a signal hasoccured. To register a signal callback use XtAppAddSignal.__│ XtSignalId XtAppAddSignal(app_context, proc, client_data)XtAppContext app_context;XtSignalCallbackProc proc;XtPointer client_data;app_contextSpecifies the application context that identifiesthe application.proc Specifies the procedure to be called when thesignal is noticed.client_dataSpecifies an argument passed to the specifiedprocedure when it is called.│__ The callback procedure pointers used to handle signal eventsare of type XtSignalCallbackProc.__│ typedef void (*XtSignalCallbackProc)(XtPointer, XtSignalId*);XtPointer client_data;XtSignalId *id;client_dataPasses the client data argument that wasregistered for this procedure in XtAppAddSignal.id Passes the id returned from the correspondingXtAppAddSignal call.│__ To notify the Intrinsics that a signal has occured, useXtNoticeSignal.__│ void XtNoticeSignal(id)XtSignalId id;id Specifies the id returned from the correspondingXtAppAddSignal call.│__ On a POSIX-based system, XtNoticeSignal is the onlyIntrinsics function that can safely be called from a signalhandler. If XtNoticeSignal is invoked multiple times beforethe Intrinsics are able to invoke the registered callback,the callback is only called once. Logically, the Intrinsicsmaintain ‘‘pending’’ flag for each registered callback.This flag is initially False and is set to True byXtNoticeSignal. When XtAppNextEvent or XtAppProcessEvent(with a mask including XtIMSignal) is called, all registeredcallbacks with ‘‘pending’’ True are invoked and the flagsare reset to False.If the signal handler wants to track how many times thesignal has been raised, it can keep its own private counter.Typically the handler would not do any other work; thecallback does the actual processing for the signal. TheIntrinsics never block signals from being raised, so if agiven signal can be raised multiple times before theIntrinsics can invoke the callback for that signal, thecallback must be designed to deal with this. In anothercase, a signal might be raised just after the Intrinsicssets the pending flag to False but before the callback canget control, in which case the pending flag will still beTrue after the callback returns, and the Intrinsics willinvoke the callback again, even though all of the signalraises have been handled. The callback must also beprepared to handle this case.To remove a registered signal callback, call XtRemoveSignal.__│ void XtRemoveSignal(id)XtSignalId id;id Specifies the id returned by the correspondingcall to XtAppAddSignal.│__ The client should typically disable the source of the signalbefore calling XtRemoveSignal. If the signal could havebeen raised again before the source was disabled and theclient wants to process it, then after disabling the sourcebut before calling XtRemoveSignal the client can test forsignals with XtAppPending and process them by callingXtAppProcessEvent with the mask XtIMSignal.7.2. Constraining Events to a Cascade of WidgetsModal widgets are widgets that, except for the inputdirected to them, lock out user input to the application.When a modal menu or modal dialog box is popped up usingXtPopup, user events (keyboard and pointer events) thatoccur outside the modal widget should be delivered to themodal widget or ignored. In no case will user events bedelivered to a widget outside the modal widget.Menus can pop up submenus, and dialog boxes can pop upfurther dialog boxes to create a pop-up cascade. In thiscase, user events may be delivered to one of several modalwidgets in the cascade.Display-related events should be delivered outside the modalcascade so that exposure events and the like keep theapplication’s display up-to-date. Any event that occurswithin the cascade is delivered as usual. The user eventsdelivered to the most recent spring-loaded shell in thecascade when they occur outside the cascade are called remapevents and are KeyPress, KeyRelease, ButtonPress, andButtonRelease. The user events ignored when they occuroutside the cascade are MotionNotify and EnterNotify. Allother events are delivered normally. In particular, notethat this is one way in which widgets can receiveLeaveNotify events without first receiving EnterNotifyevents; they should be prepared to deal with this, typicallyby ignoring any unmatched LeaveNotify events.XtPopup uses the XtAddGrab and XtRemoveGrab functions toconstrain user events to a modal cascade and subsequently toremove a grab when the modal widget is popped down.To constrain or redirect user input to a modal widget, useXtAddGrab.__│ void XtAddGrab(w, exclusive, spring_loaded)Widget w;Boolean exclusive;Boolean spring_loaded;w Specifies the widget to add to the modal cascade.Must be of class Core or any subclass thereof.exclusive Specifies whether user events should be dispatchedexclusively to this widget or also to previouswidgets in the cascade.spring_loadedSpecifies whether this widget was popped upbecause the user pressed a pointer button.│__ The XtAddGrab function appends the widget to the modalcascade and checks that exclusive is True if spring_loadedis True. If this condition is not met, XtAddGrab generatesa warning message.The modal cascade is used by XtDispatchEvent when it triesto dispatch a user event. When at least one modal widget isin the widget cascade, XtDispatchEvent first determines ifthe event should be delivered. It starts at the most recentcascade entry and follows the cascade up to and includingthe most recent cascade entry added with the exclusiveparameter True.This subset of the modal cascade along with all descendantsof these widgets comprise the active subset. User eventsthat occur outside the widgets in this subset are ignored orremapped. Modal menus with submenus generally add a submenuwidget to the cascade with exclusive False. Modal dialogboxes that need to restrict user input to the most deeplynested dialog box add a subdialog widget to the cascade withexclusive True. User events that occur within the activesubset are delivered to the appropriate widget, which isusually a child or further descendant of the modal widget.Regardless of where in the application they occur, remapevents are always delivered to the most recent widget in theactive subset of the cascade registered with spring_loadedTrue, if any such widget exists. If the event occurred inthe active subset of the cascade but outside thespring-loaded widget, it is delivered normally before beingdelivered also to the spring-loaded widget. Regardless ofwhere it is dispatched, the Intrinsics do not modify thecontents of the event.To remove the redirection of user input to a modal widget,use XtRemoveGrab.__│ void XtRemoveGrab(w)Widget w;w Specifies the widget to remove from the modalcascade.│__ The XtRemoveGrab function removes widgets from the modalcascade starting at the most recent widget up to andincluding the specified widget. It issues a warning if thespecified widget is not on the modal cascade.7.2.1. Requesting Key and Button GrabsThe Intrinsics provide a set of key and button grabinterfaces that are parallel to those provided by Xlib andthat allow the Intrinsics to modify event dispatching whennecessary. X Toolkit applications and widgets that need topassively grab keys or buttons or actively grab the keyboardor pointer should use the following Intrinsics routinesrather than the corresponding Xlib routines.To passively grab a single key of the keyboard, useXtGrabKey.__│ void XtGrabKey(widget, keycode, modifiers, owner_events, pointer_mode, keyboard_mode)Widget widget;KeyCode keycode;Modifiers modifiers;Boolean owner_events;int pointer_mode, keyboard_mode;widget Specifies the widget in whose window the key is tobe grabbed. Must be of class Core or any subclassthereof.keycodemodifiersowner_eventspointer_modekeyboard_modeSpecify arguments to XGrabKey; see Section 12.2 inXlib — C Language X Interface.│__ XtGrabKey calls XGrabKey specifying the widget’s window asthe grab window if the widget is realized. The remainingarguments are exactly as for XGrabKey. If the widget is notrealized, or is later unrealized, the call to XGrabKey isperformed (again) when the widget is realized and its windowbecomes mapped. In the future, if XtDispatchEvent is calledwith a KeyPress event matching the specified keycode andmodifiers (which may be AnyKey or AnyModifier, respectively)for the widget’s window, the Intrinsics will callXtUngrabKeyboard with the timestamp from the KeyPress eventif either of the following conditions is true:• There is a modal cascade and the widget is not in theactive subset of the cascade and the keyboard was notpreviously grabbed, or• XFilterEvent returns True.To cancel a passive key grab, use XtUngrabKey.__│ void XtUngrabKey(widget, keycode, modifiers)Widget widget;KeyCode keycode;Modifiers modifiers;widget Specifies the widget in whose window the key wasgrabbed.keycodemodifiers Specify arguments to XUngrabKey; see Section 12.2in Xlib — C Language X Interface.│__ The XtUngrabKey procedure calls XUngrabKey specifying thewidget’s window as the ungrab window if the widget isrealized. The remaining arguments are exactly as forXUngrabKey. If the widget is not realized, XtUngrabKeyremoves a deferred XtGrabKey request, if any, for thespecified widget, keycode, and modifiers.To actively grab the keyboard, use XtGrabKeyboard.__│ int XtGrabKeyboard(widget, owner_events, pointer_mode, keyboard_mode, time)Widget widget;Boolean owner_events;int pointer_mode, keyboard_mode;Time time;widget Specifies the widget for whose window the keyboardis to be grabbed. Must be of class Core or anysubclass thereof.owner_eventspointer_modekeyboard_modetime Specify arguments to XGrabKeyboard; see Section12.2 in Xlib — C Language X Interface.│__ If the specified widget is realized, XtGrabKeyboard callsXGrabKeyboard specifying the widget’s window as the grabwindow. The remaining arguments and return value areexactly as for XGrabKeyboard. If the widget is notrealized, XtGrabKeyboard immediately returnsGrabNotViewable. No future automatic ungrab is implied by