comp windows x intrinsics frequently asked questions faq archive name xt faq version id faq xt v ware exp the x toolkit intrinsics f a q a monthly posting this article contains the answers to some frequently asked questions faq from comp windows x about the x toolkit intrinsics to submit questions preferably with an answer send email to ware cis ohio state edu many faqs including this one are available on the archive site rtfm mit edu in the directory pub usenet news answers the name under which a faq is archived appears in the archive name line at the top of the article this faq is archived as xt faq all code fragments are public domain contents xt glossary software versions related faq s why does my application core dump when i use signals alarms cthreads how do i use a different visual than the default which visual should an application use why do only shell widgets have a visual which visual depth and colormap do shells inherit i ve done all the above and i still get a badmatch error why why doesn t my widget get destroyed when i call xtdestroywidget how do i exit but still execute the destroycallbacks how do i resize a shell widget why can t xtappaddinput handle files what good books and magazines are there on xt what widgets are available what alternatives to the intrinsics are there how do i pass a float value to xtsetvalues how do i write a resource converter how do i open multiple displays what changed from r to r to r where are the resources loaded from what order are callbacks executed in how do i know if a widget is visible how do i reparent a widget in xt i e xtreparentwidget why use xtmalloc xtfree etc how to debug an xt application why don t xtaddinput xtaddtimeout and xtaddworkproc work what is and how can i implement drag and drop xt glossary o the xt intrinsics implement an object oriented interface to c code to allow useful graphical components to be created included with this are classes that provide the base functionality object rectobj core composite constraint shell overrideshell wmshell etc the terms xt and intrinsics are used interchangeably however they are used very precisely to mean a specific library of the x window system in particular it does not include the athena motif olit or any other widget set without further widgets the intrinsics are not especially useful o a widget refers to a user interface abstraction created via xt the precise use is any object that is a subclass of the core class it is used loosely to refer to anything that is a subclass of the object class although these are more accurately called windowless widgets or gadgets o xlib is the c interface to the x protocol it is one layer below the xt intrinsics typically a widget uses relatively few xlib functions because xt provides most such services although an understanding of xlib helps with problems software versions the following are the latest versions of xt based software software version released next expected x r patch none x r patch athena widgets see x r motif olit xtra xw x r none xcu x r none fwf related faq s david b lewis uunet craft faq maintains the faq on x it is posted monthly on comp windows x and located on export in contrib faq liam r e quin lee sq sq com posts an faq list on open look to comp windows x jan newmarch jan pandonia canberra edu au posts an faq list on motif to comp windows x motif peter ware ware cis ohio state edu posts an faq list for comp windows x intrinsics it is on export in contrib faq xt why does my application core dump when i use signals alarms cthreads in brief xlib xt and most widget sets have no mutual exclusion for critical sections any interrupt handler is likely to leave one of the above libraries in an inconsistent state such as all the appropriate flags not yet set dangling pointers in the middle of a list traversal etc note that the ansi c standard points out that behavior of a signal handler is undefined if the signal handler calls any function other than signal itself so this is not a problem specific to xlib and xt the posix specification mentions other functions which may be called safely but it may not be assumed that these functions are called by xlib or xt functions the only safe way to deal with signals is to set a flag in the interrupt handler this flag later needs to be checked either by a work procedure or a timeout callback it is incorrect to add either of these in the interrupt handler as another note it is dangerous to add a work procedure that never finishes this effectively preempts any work procedures previously added and so they will never be called another option is to open a pipe tell the event loop about the read end using xtappaddinput and then the signal handler can write a byte to the write end of the pipe for each signal however this could deadlock your process if the pipe fills up why don t the intrinsics deal with this problem primarily because it is supposed to be a portable layer to any hardware and operating system is that a good enough reason i don t think so note the article in the x journal and the example in o reilly volume are in error how do i use a different visual than the default this requires a more complicated answer than it should a window has three things that are visual specific the visual colormap and border pixmap all widgets have their own colormap and borderpixmap resource only shell widgets have visual resources another questions deals with why shells have a visual the default value of these resources is copyfromparent which does exactly what it says in the shell widget copyfromparent gets evalulated as defaultvisualofscreen and defaultcolormapofscreen when any one of the three resources is not properly set a badmatch error occurs when the window is created they are not properly set because each of the values depends on the visual being used how to get this to work there are two parts to the answer the first is if you want an application to start with a particular visual and the second is if you want a particular shell within an application to start with a different visual the second is actually easier because the basic information you need is available the first is a little harder because you ll need to initialize much of the toolkit yourself in order to determine the needed information some sample code to start up an application using something other than the default visual to compile cc g visual c o visual lxaw lxmu lxt lxext lx lm to run visual geometry x depth visual staticcolor fg blue bg yellow you need to move the mouse to get the particular visuals colormap to install include x intrinsic h include x stringdefs h include x shell h typedef struct visual visual int depth optionsrec optionsrec options xtresource resources visual visual xtrvisual sizeof visual xtoffsetof optionsrec visual xtrimmediate null depth depth xtrint sizeof int xtoffsetof optionsrec depth xtrimmediate null xrmoptiondescrec desc visual visual xrmoptionseparg null depth depth xrmoptionseparg null int main argc argv int argc char argv xtappcontext app the application context widget top toplevel widget display dpy display char xargv saved argument vector int xargc saved argument count colormap colormap created colormap xvisualinfo vinfo template for find visual xvisualinfo vinfo list returned list of visuals int count number of matchs only arg args cardinal cnt char name test char class test save the command line arguments xargc argc xargv char xtmalloc argc sizeof char bcopy char argv char xargv argc sizeof char the following creates a dummy toplevel widget so we can retrieve the appropriate visual resource cnt top xtappinitialize app class desc xtnumber desc argc argv string null args cnt dpy xtdisplay top cnt xtgetapplicationresources top options resources xtnumber resources args cnt cnt if options visual options visual defaultvisualofscreen xtscreen top xtsetarg args cnt xtnvisual options visual cnt now we create an appropriate colormap we could use a default colormap based on the class of the visual we could examine some property on the rootwindow to find the right colormap we could do all sorts of things colormap xcreatecolormap dpy rootwindowofscreen xtscreen top options visual allocnone xtsetarg args cnt xtncolormap colormap cnt now find some information about the visual vinfo visualid xvisualidfromvisual options visual vinfo list xgetvisualinfo dpy visualidmask vinfo count if vinfo list count xtsetarg args cnt xtndepth vinfo list depth cnt xfree xpointer vinfo list xtdestroywidget top now create the real toplevel widget xtsetarg args cnt xtnargv xargv cnt xtsetarg args cnt xtnargc xargc cnt top xtappcreateshell char null class applicationshellwidgetclass dpy args cnt display the application and loop handling all events xtrealizewidget top xtappmainloop app return which visual should an application use this is a point that can be argued about but one opinion is there is no way for an application to know the appropriate visual it has to be specified by the user if you disagree with this then your application probably falls into the category of always using the default visual or it is hardware specific and expects some particular visual such as bit truecolor with an overlayplane extension or some such why no application runs in isolation depending on the way a server allocates resources i may not always want your application to run in truecolor mode if it is going to mess up my other applications i may be very upset if it chooses to run in greyscale instead of psuedocolor or just monochrome as an example on a low end color sun server there are many different possible visuals monochrome entry colormap static gray static color and a truecolor the sgi iris s offer all the above plus bit truecolor bit truecolor an overlay plane why do only shell widgets have a visual this is strictly by convention it makes it possible for an arbitrary widget to know that the visual it uses can be found by looking for the shell widget that is its ancestor and obtaining the visual of that shell a widget can have its own visual resource if it does it must have its own realize method to use the visual when it calls xcreatewindow you should also make this a resource that can be obtained with xtgetvalues so other widgets can find it a reasonable value is probably xtnvisual which visual depth and colormap do shells inherit the default value for these resources are set to copyfromparent this is interpreted as the defaultcolormapofscreen defaultdepthofscreen and the default visual of the screen if the widget has no parent i e it is an applicationshellwidgetclass and the root of your widget tree if the parent of the widget is not null then the shell copies colormap and depth from its parent and uses copyfromparent as the visual i ve done all the above and i still get a badmatch error why some resource converters improperly cache references this was especially true of x r and earlier versions of motif why doesn t my widget get destroyed when i call xtdestroywidget see section of the xt specification it eventually does get destroyed just not immediately the intrinsics destroy a widget in a two phase process first it and all of its children have a flag set that indicate it is being destroyed it is then put on a list of widgets to be destroyed this way any pending x events or further references to that widget can be cleaned up before the memory is actually freed the second phase is then performed after all callbacks event handlers and actions have completed before checking for the next x event at this point the list is traversed and each widget s memory is actually free d among other things as some further caveats trivia the widgets may be destroyed if the intrinsics determine that they have no further references to the widgets on the list if so then the phase destruction occurs immediately also if nested event loops are used widgets placed on the destroy list before entering the inner event loop are not destroyed until returning to the outer event loop how do i exit but still execute the destroycallbacks the problem is if a simple and entirely reasonable approach to exiting an application is used such as calling exit directly then a widget may not have a chance to clean up any external state such as open sockets temporary files allocated x resources etc this code for simplicity reasons assumes only a single toplevel widget widget toplevelget gw widget gw widget to find toplevel widget top for top gw xtparent top top xtparent top empty return top void exitcallback gw closure call data widget gw widget xtpointer closure data the app specified xtpointer call data widget specific data widget toplevel toplevel toplevelget gw xtunmapwidget toplevel make it disappear quickly xtdestroywidget toplevel exit one can see that the above code exit s immediately after destroying the toplevel widget the trouble is the phase destruction may never occur this works for most widgets and most applications but will not work for those widgets that have any external state you might think that since it works now it will always work but remember that part of the reason an object oriented approach is used is so one can be ignorant of the implementation details for each widget which means that the widget may change and someday require that some external state is cleaned up by the destroy callbacks one alternative is to modify exitcallback to set a global flag and then test for that flag in a private event loop however private event loops are frowned upon because it tends to encourage sloppy and difficult to maintain practices try the following code instead include x intrinsic h extern widget toplevelget if needfunctionprototypes widget gw endif extern boolean exitworkproc if needfunctionprototypes xtpointer closure endif extern void exitcallback if needfunctionprototypes widget gw xtpointer closure xtpointer call data endif widget toplevelget gw widget gw widget to find toplevel widget top for top gw xtparent top top xtparent top empty return top void exitcallback gw closure call data widget gw widget xtpointer closure data the app specified xtpointer call data widget specific data widget toplevel toplevel toplevelget gw xtunmapwidget toplevel make it disappear quickly xtdestroywidget toplevel xtappaddworkproc xtwidgettoapplicationcontext gw exitworkproc xtpointer null boolean exitworkproc closure xtpointer closure exit notreached exitcallback adds a work procedure that will get called when the application is next idle which happens after all the events are processed and the destroy callbacks are executed how do i resize a shell widget after it is realized one doesn t resize a shell widget the proper thing is to resize the currently managed child of the shell widget using xtsetvalues the geometry change is then propagated to the shell which asks the window manager which may or may not allow the request however the shell must have the resource xtnallowshellresize set to true otherwise it will not even ask the window manager to grant the request and the shell will not resize to change the position of a shell use xtsetvalues on the shell not the child and within the limits of the window manager it should be granted why can t xtappaddinput handle files it does however unix semantics for when i o is ready for a file does not fit most peoples intuitive model in unix terms a file descriptor is ready for reading whenever the read call would not block ignoring the setting of optional flags that indicate not to block this works as expected for terminals sockets and pipes for a file the read will always return but the return indicates an eof i e no more data the result is the code in the intrinsics always calls the input handler because it always thinks something is about to be read the culprit is the select system call or on sysv based os s it is the poll system call how to get around this on a unix system the best approach is to use another process to check for available input on the file use a pipe to connect the application with this other process and pass the file descriptor from the pipe to xtappaddinput a suitable program on bsd systems is tail f filename it s rumored that select on some systems is not completely reliable in particular ibm aix this is one where it would work for a while several thousand times and then stop until some other event woke it up this seemed to be the result of a race condition in the kernel ibm claims to have a fix for this pyramid doesn t work at all ultrix and possibly others where pipes are implemented as sockets wasn t completely broken but although the writing side wrote in byte blocks the reading side received it all broken up as if it was being put into the pipe a byte at a time you can waste a lot of time by reading small blocks get raound it by detecting the situation and having select ignore the pipe for mseconds by then it had been given the whole block note that all the above descriptions used unix terminology such as read file descriptor pipes etc this is an os dependent area and may not be identical on all systems however the intrinsic designers felt it was a common enough operation that it should be included with part of the toolkit why they didn t also deal with signals at this point i don t know what good books and magazines are there on xt i have a favorite that is the definitive reference to my perspective it offers a reasonable introduction but also goes into the full details of the intrinsics when i started using it i was already familiar with xt and the concepts behind it so newcomers may or may not find it useful i ve always found it accurate and complete which means its a pages asente paul j and swick ralph r x window system toolkit the complete programmer s guide and specification digital press isbn order number ey e e dp and by prentice hall isbn also available through dec direct at digital the other book i commonly recomend to novices is young doug the x window system applications and programming with xt motif version prentice hall isbn isbn and of course o reilly has an entire series of manuals on x and xt o reilly ordering is in particular volume is an xt reference done in manual page style the rd edition is extensively overhauled and goes far beyond the mit manual pages i m finding it very useful in particular the permutted index and references to other manual pages help a great deal in chasing down related information i read two periodicals the x resource and the the x journal these are the only two dealing specifically with x the x resource is published quarterly by o reilly with one of the issues being the mit x consortium technical conference proceedings there is no advertising i ve found it informative with pretty good depth for orders call or email cathyr ora com for editorial matters email adrian ora com table of contents are posted at math utah edu in ftp pub tex bib in tex form and on ftp uu net in ftp published oreilly xresource in ascii form the x journal is a bimonthly trade rag with lots of advertising the articles are informative and oriented toward a less technical audience i read it more to see what s going on then with an expectation of learning a great deal but remember i represent a fairly small percentage of people also they have a pretty good collection of people on the advisory board and as columnists call what widgets are available there are three popular widget sets athena the set provided with x this is sufficient for most purposes but is on the ugly side recently a d look is available for ftp on export lcs mit edu contrib xaw d tar z motif from osf available for a license fee and commonly shipped on many workstation vendors platforms almost everyone but sun it looks good and works well but personally i think it is poorly implemented olit the open look intrinsics toolkit is a set of widgets implementing sun s open look specification developed by at t i ve never used it so can t comment on its quality i ve heard rumours that it is a pain to actually get in addition the following collection of widgets are also available xtra a library of widgets for sale from graphical software technology it includes bar graph stacked bar graph line graph pie chart xy plot hypertext help spreadsheet and data entry form widgets i ve never seen them so i can t comment fwf the free widget foundation is attempting to collect a set of freely available widgets included are a pixmap editor filedialog and a few others the current set of widgets can be obtained via anonymous ftp from the machine a cs uiuc edu in the file pub fwf shar z xcu the cornell university widgets from gene dykes one of the early widget sets released provides a nice appearance for buttons and has a mini command language probably not so widely used xs the sony widget set this was around during r days but seemed to disappear it looked like it had promise xw the hp widgets the precursor to motif originally written for r there exists diffs to get it to work under r r again a pretty good widget set but has more or less died the precursor to this was the xray toolkit which was originally implemented for x r and apparently provided much experience for the designers of xt xo a widget set i m working on it s still primitive but you can give it a try in archive cis ohio state edu pub xo the following specialized widgets are also available tbl implements a tabular layout of widgets supports motif widgets as children part of wcl plots the athena plotting widgets not the athena widgets contact gnb bby oz au or joe athena mit edu what alternatives to the intrinsics are there name language vendor xview c sun oi c parcplace interviews c stanford tcl tk c sprite berkeley edu however much i like c and admire the skill in both designing and implementing the intrinsics hopefully some alternative will develop in the next years that uses an object oriented language keep your eyes open and expect some change about the same time a language other than c starts gaining acceptance how do i pass a float value to xtsetvalues first what is going wrong is the structure for an arg is essentially typdef struct string name long value arg and the code arg arg xtsetarg arg name expands to arg arg arg name name arg value you can see that with normal c type conversions the arg value gets the integer instead of the floating point value when the value is copied into the widget resource the bit pattern is wildly different than that required for a floating point value so how to get around this the following macro is from the athena widgets document and i am now recomending it over the previous suggestions define xtsetfloatarg arg n d if sizeof float sizeof xtargval xtsetarg arg n d else xtargval ld xtargval d xtsetarg arg n ld how do i write a resource converter courtesy of rich thomson rthomson dsd es com the following discussion of resource converters assumes r or r intrinsics resource converters changed between r and r to allow for destructors and caching of converted values there are several main types of resource converters string to data type data type to string data type to data type i string to data type usually a string to data type converter has a fixed set of strings that will be converted to data type values this is most often used to map enumerated names to enumerated values name value true false in this case the string to data type converter needs to compare the resource value to the list of fixed strings this is most readily accomplished by the use of the quark mechanism of the resource manager the resource value is turned into a quark which is a unique representation of the string that fits into a single word then the resource quark is compared against the quarks for the fixed strings representing the enumerated values if there are many enumerated strings in the converter or many converters each with a small number of enumeration strings then a global initialization routine might be used to turn all the resource strings into quarks that way the first time one of these converters is used the strings will be turned into quarks and held in static variables for use in the next invocation of one of the converters ii data type to string this type of converter is slightly easier than the string to data type converters since the use of quarks isn t necessary instead the data type value is simply converted to a string value probably by the use of sprintf data type to string converters are useful for applications that wish to convert an internal data type value into a string so that they can write out a valid resource specification to a file this mechanism can be used to provide a snapshot of application state into a file this snapshot can be used to restore the program to a known state via the usual x resource database mechanisms if you are taking the trouble to write a string to data type converter it isn t much extra effort to write the data type to string converter writing both at the same time helps to ensure that they are consistent iii data type to data type this type of converter is used to convert an existing data type value to another data type for instance an x pixel value can be converted to an rgb data type that contains separate fields for red green and blue the type signature for a resource converter is as follows typedef boolean xttypeconverter display xrmvalueptr cardinal xrmvalueptr xrmvalueptr xtpointer display dpy xrmvalueptr args cardinal num args xrmvalueptr fromval xrmvalueptr toval xtpointer converter data when the converter is invoked the fromval argument points to the source x resource manager value and the toval argument points to the destination x resource manager value the converter data argument is an opaque pointer to some converter specific data that is specified when the converter is registered the args and num args arguments allow extra information to be passed to the converter when it is invoked for instance the pixel to rgb structure converter discussed above would need colormap and visual arguments in which to lookup the pixel to obtain the rgb values corresponding to that pixel care must be taken with the toval argument an xrmvalue has the following type definition and specifies a size and location for a converted value typedef struct unsigned int size caddr t addr xrmvalue xrmvalueptr when the converter is invoked the address may point to a location of the given size for the converted value or the location can be null in the former case the converter should ensure that the size of the destination area is large enough to handle the converted value if the destination area is not large enough then the converter should set the size to the amount of space needed and return false the caller can then ensure that enough space is allocated and reinvoke the converter if the size is large enough then the converter can simply copy the converted value into the space given and return true if the location is null then the converter can assign the location to the address of a static variable containing the converted value and return true when writing a group of converters this code is often repeated and it becomes convenient to define a macro define done var type if toval addr if toval size sizeof type toval size sizeof type return false else type toval addr var else toval addr caddr t var toval size sizeof type return true define donestr str if toval addr toval size sizeof string toval size sizeof string return false else toval addr caddr t str toval size sizeof string return true inside the converter it is a good idea to perform a little safety checking on the num args and args arguments to ensure that your converter is being called properly once you have written your converter you need to register it with the intrinsics the intrinsics invokes resource converters when creating widgets and fetching their resource values from the resource database to register a converter with a single application context use xtappsettypeconverter void xtappsettypeconverter context from to converter args num args cache destructor xtappcontext context string from string to xttypeconverter converter xtconvertarglist args cardinal num args xtcachetype cache xtdestructor destructor to register a converter with all application contexts use xtsettypeconverter void xtsettypeconverter from to converter args num args cache destructor string from string to xttypeconverter converter xtconvertarglist args cardinal num args xtcachetype cache xtdestructor destructor in the r intrinsics there were the routines xtappaddconverter and xtaddconverter these have been superseded by xtappsettypeconverter and xtsettypeconverter whenever possible the newer routines should be used when a converter is registered with the intrinsics a cache argument specifies how converted resource values are to be cached xtcachenone don t cache any converted values xtcacheall cache all converted values xtcachebydisplay cache converted values on a per display basis caching converted values that require a round trip to the server is a good idea for instance string to pixel conversions the destructor argument is a routine that is invoked then the resource is destroyed either because its cached reference count has been decremented to zero or because the widget owning the value is being destroyed xtdestructor has the following type definition typedef void xtdestructor xtappcontext xrmvalueptr xtpointer xrmvalueptr cardinal xtappcontext context xrmvalueptr to xtpointer converter data xrmvalueptr args cardinal num args the destructor is invoked to free any auxiliary storage associated with the to argument but does not actually free the storage pointed to by the to argument itself to addr the destructor is passed the extra arguments that were passed to the converter when the conversion was performed for instance colormap and visual arguments for the string to pixel converter since the destructor would need to free the allocated pixel from the colormap as well as the private data passed in when the converter was registered sample converter code can be found in the following files in the mit r distribution mit lib xt converters c contrib lib pext converters c contrib lib pext converters h how do i open multiple displays see multi user application software using xt the x resource issue summer by oliver jones for a complete coverage of the issues involved most of this answer is based on that article in a nutshell one uses xtopendisplay to add each display to a single application context and then xtclosedisplay to shutdown each display and remove it from the application context the real problems occur when trying to close down a display this can happen ways user selects a quit button on one of the displays user has window manager send a wm delete window message server disconnect possibly from a killclient message server shutdown crash or network failure i ll assume you can deal gracefully with since it is merely a problem of translating a widget to a display and removing that display if not then read the oliver jones article the third one is difficult to handle the following is based on the oliver jones article and i include it here because it is a difficult problem the difficulty arises because the xlib design presumed that an i o error is always unrecoverable and so fatal this is essentially true for a single display x based application but not true for a multiple display program or an application that does things other than display information on an x server when an x i o error occurs the i o error handler is called and if it returns then an exit happens the only way around this is to use setjmp longjmp to avoid returning to the i o error handler the following code fragment demonstrates this include setjmp h jmp buf xiorecover void xiohandler dpy display dpy destroydisplay dpy longjmp xiorecover main if setjmp xiorecover xsetioerrorhandler xiohandler xtappmainloop app context the destroydisplay is something that given a display pointer can go back to the application specific data and perform any necessary cleanup it should also call xtclosedisplay for those of you unfamiliar with setjmp longjmp when setjmp is first called it returns a and save s enough information in the jmp buf that a latter execution of longjmp can return the program to the same state as if the setjmp was just executed the return value of this second setjmp is the value of the second argument to longjmp there are several caveats about using these but for this purpose it is adequate some other problems you might run into are resource converters that improperly cache resources the most likely symptoms are xlib errors such as badcolor badatom or badfont there may be problems with the total number of displays you can open since typically only a limited number of file descriptors are available with being a typical value you may also run into authorization problems when trying to connect to a display there was much discussion in comp windows x about this topic in november of robert scheifler posted an article which basically said this is the way it will be and xlib will not change what changed from r to r to r this addresses only changes in the intrinsics first the general changes for each release are described then a certainly incomplete list of new functions added and others that are now deprecated are listed brevity is a primary goal much of the following information is retrieved from chapter of the mit xt intrinsics manual and from o reilly volume rd edition from r to r addition of gadgets windowless widgets new resource type converter interface to handle cacheing and additional data variable argument list interface define xtspecificationrelease added with this release wmshellpart toplevelshellpart transientshellpart changed incompatibly core initialize core set values added arglist and count parameters event handlers had continue to dispatch parameter added core set values almost specification changed core compress exposure changed to an enumerated data type from boolean core class inited changed to enumerated data type from boolean constraint get values hook added to extension record core initialize hook obsolete as info is passed to core initialize shell root geometry manager added to extension record core set values hook obsolete as info is passed to core set values calling xtquerygeometry must store complete geometry added unrealizecallback xttranslatecoords actually works under r from r to r psuedo resource basetranslation added searching for app default and other files made more flexible customization resource added per screen resource database support permanently allocated strings permanetly allocated strings required for several class fields the args argument to xtappinitialize xtvaappinitialize xtopendisplay xtdisplayinitialize and xtinitialize were changed from cardinal to int many performance improvements this is summarized from the article xt performance improvements in release by gabe beged dov in the x resource issue xrmstringtoquark augmented with xrmpermstringtoquark to avoid string copies several fields in the class record are indicated as needing permanent strings using an array of strings for resources callback lists redesigned to use less memory translation manager redesigned and rewritten so it takes less memory translation tables merges are faster cache of action bindings keycode to keysyms are cached better sharing of gc s with modifiable fields window to widget translation uses less space and faster does not malloc space for widget name since quark is available widget space is allocated to include the constraints over several example programs about a reduction in memory usage functions new with r xtallocategc sharable gc with modifiable fields xtgetactionlist get the action table of a class xtscreendatabase return resource database for a screen xtsetlanguageproc register language procedure called to set locale functions new with r xtappaddactionhook procedure to call before every action xtappinitialize lots of initialization work xtappreleasecacherefs decrement cache reference count for converter xtappsetfallbackresources specify default resources xtappsettypeconverter register a new style converter xtcallcallbacklist directly execute a callback list xtcallconverter invoke a new style converter xtcallbackreleasecacheref release a cached resource value xtcallbackreleasecachereflist release a list of cached resource values xtconvertandstore find and call a resource converter xtdirectconvert invoke old style converter xtdisplayofobject return the display xtdisplaystringconversionwarning issue a warning about conversion xtfindfile find a file xtgetactionkeysym retrieve keysym modifies for this action xtgetapplicationnameandclass return name and class xtgetconstraintresourcelist get constraints for a widget xtgetkeysymtable return keycode to keysym mapping table xtgetmulticlicktime read the multi click time xtgetselectionrequest retrieve the selectionrequest event xtgetselectionvalueincremental obtain the selection value incrementally xtgetselectionvaluesincremental obtain the selection value incrementally xtinitializewidgetclass initialize a widget class manually xtinserteventhanlder register event handler before after others xtinsertraweventhandler register event handler without modify input mask xtisobject test if subclass of object xtisrectobj test if subclass of rectobj xtkeysymtokeycodelist return list of keycodes xtlasttimestampprocessed retrieve most recent event time xtmenupopdown action for popping down a widget xtmenupopup action for popping up a widget xtoffsetof macro for structure offsets xtownselectionincremental make selection data availabe incrementally xtpoupspringloaded map a spring loaded popup xtregistergrabaction indicate action procedure needs a passive grab xtremoveactiohhook remove function called after every action xtresolvepathname find a file xtscreenofobject return screen of object xtsetmulticlicktime set the multi click time xtsetwmcolormapwindows set wm colormap windows for custom colormaps xtungrabbutton cancel a passive button grab xtungrabkey cancel a passive key grab xtungrabkeybard release an active keyboard grab xtungrabpointer release an active pointer grab xtva varags interfaces to a bunch of functions xtwindowofobject return window of nearest widget ancestor deprecated replacement when xtaddactions xtappaddactions r xtaddconverter xtappaddconverter r xtaddinput xtappaddinput r xtaddtimeout xtappaddtimeout r xtaddworkproc xtappaddworkproc r xtconvert xtconvertandstore r xtcreateapplicationshell xtappcreateshell r xtdestroygc xtreleasegc r xterror xtapperror r xtgeterrordatabase xtappgeterrordatabase r xtgeterrordatabasetext xtappgeterrordatabasetext r xtgetselectiontimeout xtappgetselectiontimeout r xtinitialize xtappinitialize r xtmainloop xtappmainloop r menupopdown action xtmenupopdown action r menupopup action xtmenupopup action r xtnextevent xtappnextevent r xtpeekevent xtapppeekevent r xtpending xtapppending r xtseterrorhandler xtappseterrorhandler r xtseterrormsghandler xtappseterrormsghandler r xtsetselectiontimeout xtappsetselectiontimeout r xtsetwarninghandler xtappsetwarninghandler r xtsetwarningmsghandler xtappsetwarningmsghandler r xtwarning xtappwarning r xtwarningmsg xtappwarningmsg r where are the resources loaded from the resources of a widget are filled in from the following places from highest priority to lowest priority args passed at creation time command line arguments user s per host defaults file user s defaults file user s per application default file system wide per application default file note that are read only once on application startup the result of steps is a single resource database used for further queries the per host defaults file contains customizations for all applications executing on a specific computer this file is either specified with the xenvironment environment variable or if that is not set then the file home xdefaults host is used the user defaults file is either obtained from the resource manager property on the root window of the display or if that is not set then the file home xdefaults is used typically the program xrdb is used to set the resource manager property please note that this should be kept relatively small as each client that connects to the display must transfer the property a size of around kbyte is reasonable some toolkits may track changes to the resource manager but most do not a user may have many per application default files containing customizations specific to each application the intrinsics are quite flexible on how this file is found read the next part that describes the various environment variables and how they effect where this file is found the system wide per application default files are typically found in usr lib x app defaults if such a file is not found then the fallback resources are used the intrinsics are quite flexible on how this file is found read the next part that describes the various environment variables and how they effect where this file is found thanks to oliver jones oj pictel com for the following you can use several environment variables to control how resources are loaded for your xt based programs xfilesearchpath xuserfilesearchpath and xapplresdir these environment variables control where xt looks for application defaults files as an application is initializing xt loads at most one app defaults file from the path defined in xfilesearchpath and another from the path defined in xuserfilesearchpath set xfilesearchpath if software is installed on your system in such a way that app defaults files appear in several different directory hierarchies suppose for example that you are running sun s open windows and you also have some r x applications installed in usr lib x app defaults you could set a value like this for xfilesearchpath and it would cause xt to look up app defaults files in both usr lib x and usr openwin lib or wherever your openwinhome is located setenv xfilesearchpath usr lib x t n openwinhome lib t n the value of this environment variable is a colon separated list of pathnames the pathnames contain replacement characters as follows see xtresolvepathname n the value of the filename parameter or the application s class name t the value of the file type in this case the literal string app defaults c customization resource r only s suffix none for app defaults l language locale and codeset e g ja jp euc l language part of l e g ja t the territory part of the display s language string c the codeset part of the display s language string let s take apart the example suppose the application s class name is myterm also suppose open windows is installed in usr openwin notice the example omits locale specific lookup usr lib x t n means usr lib x app defaults myterm openwinhome lib t n means usr openwin lib app defaults myterm as the application initializes xt tries to open both of the above app defaults files in the order shown as soon as it finds one it reads it and uses it and stops looking for others the effect of this path is to search first in usr lib x then in usr openwin let s consider another example this time let s set xuserfilesearchpath so it looks for the file myterm ad in the current working directory then for myterm in the directory app defaults setenv xuserfilesearchpath n ad home app defaults n the first path in the list expands to myterm ad the second expands to home app defaults myterm this is a convenient setting for debugging because it follows the imake convention of naming the app defaults file myterm ad in the application s source directory so you can run the application from the directory in which you are working and still have the resources loaded properly note when looking for app default files with xuserfilesearchpath for some bizarre reason neither the type nor file suffix is defined so t and s are useless with r there s another twist you may specify a customization resource value for example you might run the myterm application like this myterm xrm customization color if one of your pathname specifications had the value usr lib x app defaults n c then the expanded pathname would be usr lib x app defaults myterm color because the c substitution character takes on the value of the customization resource the default xfilesearchpath compiled into xt is usr lib x l t n c r usr lib x l t n c r usr lib x t n c r usr lib x l t n usr lib x l t n usr lib x t n note some sites replace usr lib x with a projectroot in this batch of default settings the default xuserfilesearchpath also compiled into xt is root l n c r root l n c r root n c r root l n root l n root n root is either the value of xapplresdir or the user s home directory if xapplresdir is not set if you set xuserfilesearchpath to some value other than the default xt ignores xapplresdir altogether notice that the quick and dirty way of making your application find your app defaults file in your current working directory is to set xapplresdir to a single dot in r all this machinery worked differently for r compatibilty many people set their xapplresdir value to a dot followed by a slash what order are callbacks executed in courtesy of donna converse converse expo lcs mit edu the intrinsics library do not guarantee an order this is because both the widget writer and the application writer have the ability to modify the entire contents of the callback list neither one currently knows what the other is doing and so the intrinsics cannot guarantee the order of execution the application programmer cannot rely on the widget writer the widget writer is not required to document when the widget will add and remove callbacks from the list or what effect this will have therefore the functionality contained in a callback should be independent of the functionality contained in other callbacks on the list even though the xt standard in the definition of xtaddcallback says callback name specifies the callback list to which the procedure is to be appended you may not infer from the word appended that the callback routines are called in the same order as they have been added to the callback list how do i know if a widget is visible courtesy of donna converse converse expo lcs mit edu i am building a widget needs to know if it is visible i set the visible interest field in core and if my window is completely obscured the core visible flag goes false however if my window is iconified the flag stays set to true right everything is implemented correctly this demonstrates a deficiency in the x protocol and the core widget is reflecting the capabilities of the protocol the deficiency is that the information is available in one way in this case an inconvenient way the xt specification is accurate in the second and third paragraphs of section so read this section carefully the visible field will not change in response to iconification a visibilitynotify event will not be received when the window goes from viewable to unviewable that is when the widget or an ancestor is unmapped that is when iconification occurs this is the protocol deficiency visibility state and viewable state have specific meanings in the x protocol see the glossary in your xlib and x protocol reference manual is this a problem with mwm or is there something else which needs to be done you ll see this with any window manager with no window manager if the problem is mwm what is the fastest way to determine if a window is iconified as an application writer keep track with a global boolean in an action routine with translations for mapnotify and unmapnotify on the shell widget which contains your custom widget as the custom widget writer see the map state field returned by a call to xgetwindowattributes these are suggestions how do i reparent a widget in xt i e xtreparentwidget you can t why use xtmalloc xtfree etc unfortunately most code that calls malloc realloc or calloc tends to ignore the possibility of returning null at best it is handled something like ptr type malloc sizeof type if ptr perror malloc in xyzzy exit to handle this common case the intrinsics define the functions xtmalloc xtcalloc xtnew xtnewstring and xtrealloc which all use the standard c language functions malloc calloc and realloc but execute xterrormsg if a null value is returned xt error handlers are not supposed to return so this effectively exits in addition if xtrealloc is called with a null pointer it uses xtmalloc to get the initial space this allows code like if ptr ptr type malloc sizeof type else ptr type realloc ptr sizeof type count count to be written as ptr xtrealloc ptr sizeof ptr count also xtfree accepts a null pointer as an argument generally i ve found the xt functions conveniant to use however anytime i m allocating anything potentially large i use the standard functions so i can fully recover from not enough memory errors xtnew and xtnewstring are conveniant macros for allocating a structure or copying a string struct abc xyzzy char ptr char str abcdef xyzzy xtnew struct abc takes care of type casting ptr xtnewstring str a strict interpretation of the intrinsics reference manual allow an implementation to provide functions that are not exchangable with malloc and free i e code such as char ptr ptr xtmalloc free ptr may not work personally i d call any implementation that did this broken and complain to the vendor a common error for motif programmers is to use xtfree on a string when they should really be using xmstringfree how to debug an xt application first i d recomend getting purify from pure software this is a great package for tracing memory problems on sun s it s a bit pricey at but i d still recomend it excuse the marketing blurb contact support pure com for more info purify inserts additional checking instructions directly into the object code produced by existing compilers these instructions check every memory read and write performed by the program under test and detect several types of access errors such as reading unitialized memory writing past malloc d bounds or writing to freed memory purify inserts checking logic into all of the code in a program including third party and vendor object code libraries and verifies system call interfaces in addition purify tracks memory usage and identifies individual memory leaks using a novel adaption of garbage collection techniques purify s nearly comprehensive memory access checking slows the target program down typically by a factor of two to five an alternative package that isn t as pricey for a sun runs on many unix s and has pretty similar features is the sentinel debugging environment this replaces malloc and several other c library functions to add additional checks contact cpcahil virtech vti com for more info next if you are getting any sort of xlib error you ll need to run in synchronous mode easily accomplished with the sync command line argument or by setting the variable xdebug to with your debugger then set a break point in exit this will let you trace back to the original xlib function being called if you don t run in synchronous mode then the actual error may have occured any number of calls to xlib previously since the xlib calls are buffered and replies from the server are asynchronous next if you are having trouble with window layout you can use the undocumented resource xtidentifywindows or the class resource xtdebug to cause the widget name to be identified with each window for example example xload xrm xtdebug true example xwininfo tree click in new xload window will give the normal information but the widget name and class of each window is included this can help for checking the location and size of errant widgets next if you are having trouble with geometry managers or you want to test the way a widget manages it s children you can try export lcs mit edu contrib libxtgeo tar z this acts as a filter between any children and a geometry manager and checks the behaviour of both it s a very clever idea the most unfortunate problem is debugging a callback while the application is executing a grab of the keyboard or mouse such as from a pulldown menu the server effectively locks up and you ll need to go to another machine and kill the debugger manually the server locks up because the application being debugged has said no one else can have access to the keyboard but the application is not stopped waiting because the debugger is waiting for your commands unfortunately you can t give them because all the input is going to your application which is stopped the best way to debug this kind of problem is with two machines on your desk running the program under a debugger or other environment on one machine and running the application on the other possibly using a command sequence like this othermachine xhost thismachine thismachine setenv display othermachine thismachine gdb application your favorite debugger or this othermachine xhost thismachine thismachine gdb application gdb set environment display othermachine gdb run i believe codecenter a c interpreter graphical debugger has a method of dealing with this by explicitely calling the xlib functions to release any grabs during breakpoints debugging widget problems requires pretty good debugging skills and knowledge of how widgets work you can go a long way without knowing the internals of a particular widget but not very far without understanding how a widget works judicious use of conditional breakpoints and adding print statements with the debugger help a great deal why don t xtaddinput xtaddtimeout and xtaddworkproc work i have got a delicate problem with the three routines xtaddinput xtaddtimeout and xtaddworkproc the problem i have is that when i use them in my application they seem not to be registred properly i have made a handy little testprogram where everything works perfect but in my real application nothing happens the introduction in r of the xtapp functions obsoleted those routines see q for other changes in r r and r what happens is they use a default application context different then the one you may have created since events and timeouts are distributed on a per application context basis and you are using two application contexts you won t get those events for example cnt toplevel xtappinitialize app class desc xtnumber desc argc argv fallback args cnt xtaddtimeout xtaddworkproc xtappmainloop app would never invoke the timeout what is and how can i implement drag and drop courtesy of roger reynolds rogerr netcom com feb drag n drop is a buzzword for moving data between clients in an intuitive fashion motif version supports drag n drop capabilities openlook has supported d n d all along the two protocols are not compatable with each other and so far as i know they are not published i wrote a package called rdd which is designed to be a flexible public protocol for doing drag n drop operations between clients my intention was to provide a tool which would make it easy for people to support a standard drag n drop protocol in the programs they develop and contribute or sell regardless of what widget set is used as long as it is based on xt the implementation is based upon my understanding of the icccm conventions for more details read the code i have heard from dozens of people using rdd who like it and feel that it works a whole lot better than motif stuff also there seem to be many who think that it is neat but are constrained to use motif anyway the latest rdd and some other stuff is available for ftp from netcom com in pub rogerr a possibly older version is also available on export lcs mit edu in contrib pete ware ware cis ohio state edu cis dept ohio state university w bolz hall neil ave h columbus oh
