You are on page 1of 13

BasicTheXWindowSystem

Programming

2006
SwapnilKamble

FergussonCollege
SYBCS

Introduction:
TheXWindowSystemisthemostwidelyavailablewindowingsystemcapable
ofrunningonUNIXorUNIXlikesystems,includingFreeBSD.TheX.orgFoundation
administersthe.XProtocolstandardThecurrentreleaseofthespecificationis11.6,soyouwill
oftenseereferencesshortenedtoX11R6orevenjustX11.
ThistutorialismadetointroducethestudentsaboutXWindowSystem.For
morehigherlevelXprogrammingprogrammerusuallyusesamuchhigherlevelof
abstraction,suchasusingMotif(oritsfreeversion,lesstiff),GTK,QTandsimilarlibraries.
However,weneedtostartsomewhere.Morethanthis,knowinghowthingsworkdownbelow
isneverabadidea.
Afterreadingthistutorial,onewouldbeabletowriteverysimplegraphicalprograms,butnot
programswithadescentuserinterface.Forsuchprograms,oneofthepreviouslymentioned
librarieswouldbeused.

XSystemConceptsandDefinitions
:

Xrequiresasystemthatconsistsofworkstationscapableofbitmappedgraphics.Thesecanbe
colourormonochrome.
Adisplayisdefinedasaworkstationconsistingofakeyboard,apointingdevice(usuallya
mousealthoughitcouldbeatrackballorgraphicstablet,forinstance)andoneormore
screens.

TheClientAndServerModelOfTheXWindowSystem
Xisnetworkorientedandapplicationsneednotberunningonthesamesystemastheone
supportingthedisplay.ThiscansometimesbequitecomplicatedforasystemsuchasXto
manageandsotheconceptofclientsandserverswasintroduced.buttheXwindowsystem
wasdevelopedwithonemajorgoalflexibility.Theideawasthatthewaythingslookisone
thing,butthewaythingsworkisanothermatter.Thus,thelowerlevelsprovidethetools
requiredtodrawwindows,handleuserinput,allowdrawinggraphicsusingcolors(orblack
andwhitescreens),etc.Tothispoint,adecisionwasmadetoseparatethesystemintotwo
parts.Aclientthatdecideswhattodo,andaserverthatactuallydrawsonthescreenand
readsuserinputinordertosendittotheclientforprocessing.
Youneednotworrytoomuchaboutthepracticalityofthis,asnormallyXmakesthis
transparenttotheuserespeciallyifwerunprogramsonasingleworkstation.However,in
ordertofullyunderstandtheworkingsofX,somenotionoftheseconceptsisrequired.This
modelisthecompleteoppositeofwhatoneisusedtowhendealingwithclientsandservers.
Inourcase,theuserseatsnearthemachinecontrolledbytheserver,whiletheclientmightbe
runningonaremotemachine.Theservercontrolsthescreen,mouseandkeyboard.Aclient
mayconnecttotheserver,requestthatitdrawsawindow(orseveralwindows),andaskthe
servertosenditanyinputtheusersendstothesewindows.Thus,severalclientsmayconnect
toasingleXserveronemightberunninganemailsoftware,onerunningaWWWbrowser,
etc.Wheninputitsentbytheusertosomewindow,theserversendsamessagetotheclient
controllingthiswindowforprocessing.Theclientdecideswhattodowiththisinput,and
sendstheserverrequestsfordrawinginthewindow.
ThewholesessioniscarriedoutusingtheXmessageprotocol.Thisprotocolwas
originallycarriedovertheTCP/IPprotocolsuite,allowingtheclienttorunonanymachine
connectedtothesamenetworkthattheserveris.LaterontheXserverswereextendedto
allowclientsrunningonthelocalmachinemoreoptimizedaccesstotheserver(notethatanX
protocolmessagemaybeseveralhundredsofKBinsize),suchasusingsharedmemory,or
usingUnixdomainsockets.
Theprogramthatcontrolseachdisplayisknownastheserver.Thisterminologymayseema
littleoddaswemaybeusedtotheserverassomethingacrossthenetworksuchasafile
server.Here,theserverisalocalprogramthatcontrolsourdisplay.Alsoourdisplaymaybe
availabletoothersystemsacrossthenetwork.Inthiscaseoursystemdoesactasatruedisplay
server.
Theserveractsasagobetweenbetweenuserprograms,calledclientsorapplicationsandthe
resourcesofthelocalsystem.Theserunoneitherlocalorremotesystems.
Taskstheserverperformsinclude:

allowingaccessbymultipleclients,
interpretingnetworkmessagesfromclients,
twodimensionalgraphicsdisplay,
maintainlocalresourcessuchaswindows,cursors,fontsandgraphics.

TheXProgrammingModel
Theclientandserverareconnectedbyacommunicationpathcalled(surprise,surprise)the
connector.ThisisperformedbyalowlevelClanguageinterfaceknownasXlib.Xlibisthe
lowestleveloftheXsystemsoftwarehierarchyorarchitecture.Manyapplicationscanbe
writtenusingXlibalone.However,ingeneral,itwillbedifficultandtimeconsumingtowrite
complexGUIprogramsonlyinXlib.Unlikeconventionalcomputerprograms,thatcarrysome
serialnature,aGUIprogramusuallyusesanasynchronousprogrammingmodel,alsoknown
as"eventdrivenprogramming".Thismeansthatthatprogrammostlysitsidle,waitingfor
eventssentbytheXserver,andthenactsupontheseevents.Aneventmaysay"Theuser
pressedthe1stbuttonmouseinspotx,y",or"thewindowyoucontrolneedstoberedrawn".In
orderfortheprogramtoberesponsivetotheuserinput,aswellastorefreshrequests,itneeds
tohandleeacheventinarathershortperiodoftime(e.g.lessthan200milliseconds,asarule
ofthumb).Thisalsoimpliesthattheprogrammaynotperformoperationsthatmighttakea
longtimewhilehandlinganevent(suchasopeninganetworkconnectiontosomeremote
server,orconnectingtoadatabaseserver,orevenperformingalongfilecopyoperation).
Instead,itneedstoperformalltheseoperationsinanasynchronousmanner.Thismaybedone
byusingvariousasynchronousmodelstoperformthelongishoperations,orbyperforming
theminadifferentprocessorthread.
Manyhigherlevelsubroutinelibraries,calledtoolkits,havebeendevelopedtoremedythis
problem.
Note:Xisnotrestrictedtoasinglelanguage,operatingsystemoruserinterface.Itisrelatively
straightforwardtolinkcallstoXfrommostprogramminglanguages.AnXapplicationmust
onlybeabletogenerateandreceivemessagesinaspecialform,calledXprotocolmessages.
However,theprotocolmessagesareeasilyaccessibleasClibrariesinXlib(andothers).
ThereareusuallytwolevelsoftoolkitsaboveXlib

XToolkit(Xt)Intrinsicsarepartsofthetoolkitthatallowprogrammerstobuildnew
widgets.
ThirdPartyToolkitssuchaMotif

AnapplicationprograminXwillusuallyconsistoftwoparts.Thegraphicaluserinterface
writteninoneormoreofXlib,XtorMotifandthealgorithmicorfunctionalpartofthe
applicationwheretheinputfromtheinterfaceandotherprocessingtasksaredefined.Fig.
illustratestherelationshipsbetweentheapplicationprogramandthevariouspartsoftheX
System.
Themainconcernofthistextistointroduceconceptsinbuildingthegraphicaluser
interfaceinXandMotifinparticular.Wenowbrieflydescribethemaintasksofthethreelevels
oftheXprogrammingmodelbeforeembarkingonwritingMotifprograms.
SothewayaGUIprogramlooksissomethinglikethat:
1. Performinitializationroutines.
2. ConnecttotheXserver.
3. PerformXrelatedinitialization.

4. Whilenotfinished:
1. ReceivethenexteventfromtheXserver.
2. handletheevent,possiblysendingvariousdrawingrequeststotheXserver.
3. Iftheeventwasaquitmessage,exittheloop.
5. ClosedowntheconnectiontotheXserver.
6. Performcleanupoperations.

Xlib
ThemaintaskofXlibistotranslateCdatastructuresandproceduresintothespecialformofX
protocolmessageswhicharethensentoff.Obviouslytheconverseofreceivingmessagesand
convertingthemtoCstructuresisperformedaswell.Xlibhandlestheinterfacebetweenclient
(application)andthenetwork.
BasicXlibNotions
InordertoeliminatetheneedsofprogramstoactuallyimplementtheXprotocollayer,a
librarycalled'Xlib'wascreated.ThislibrarygivesaprogramaverylowlevelaccesstoanyX
server.Sincetheprotocolisstandardized,AclientusinganyimplementationofXlibmaytalk
withanyXserver.Thismightlooktrivialthesedays,butbackatthedaysofusingcharacter
modeterminalsandproprietarymethodsofdrawinggraphicsonscreens,thislookedlikea
majorbreakthrough.Infact,you'llnoticethebighypegoingaroundthinclients,windows
terminalservers,etc.TheyareimplementingtodaywhattheXprotocolenabledinthelate
80's.Ontheotherhand,theXuniverseisplayingacatchupgameregardingCUA(common
useraccess,anotionmadebyIBMtorefertotheusageofacommonlookandfeelforall
programsinordertoeasethelivesoftheusers).Nothavingacommonlookandfeelwasa
philosophyofthecreatorsoftheXwindowsystem.Obviously,ithadsomedrawbacksthatare
evidenttoday.
TheXDisplay
ThemajornotionofusingXlibistheXdisplay.Thisisastructurerepresentingtheconnection
wehaveopenwithagivenXserver.Ithidesaqueueofmessagescomingfromtheserver,and
aqueueofpendingrequeststhatourclientintendstosendtotheserver.InXlib,thisstructure
isnamed'Display'.WhenweopenaconnectiontoanXserver,thelibraryreturnsapointerto
suchastructure.Later,wesupplythispointertoanyXlibfunctionthatshouldsendmessages
totheXserverorreceivemessagesfromthisserver.
TheGCGraphicsContext
Whenweperformvariousdrawingoperations(graphics,text,etc),wemayspecifyvarious
optionsforcontrollinghowthedatawillbedrawnwhatforegroundandbackgroundcolors
touse,howlineedgeswillbeconnected,whatfonttousewhendrawingsometext,etc).In
ordertoavoidtheneedtosupplyzillionsofparameterstoeachdrawingfunction,agraphical

contextstructure,oftype'GC'isused.Wesetthevariousdrawingoptionsinthisstructure,and
thenpassapointertothisstructuretoanydrawingroutines.Thisisratherhandy,asweoften
needstoperformseveraldrawingrequestswiththesameoptions.Thus,wewouldinitializea
graphicalcontext,setthedesiredoptions,andpassthisGCstructuretoalldrawingfunctions.
ObjectHandles
WhenvariousobjectsarecreatedforusbytheXserversuchaswindows,drawingareasand
cursorstherelevantfunctionreturnsahandle.Thisissomeidentifierfortheobjectthat
actuallyresidesintheXserver'smemorynotinourapplication'smemory.Wecanlater
manipulatethisobjectbysupplyingthishandletovariousXlibfunctions.Theserverkeepsa
mappingbetweenthesehandlesandtheactualobjectsitmanages.Xlibprovidesvarioustype
definitionsfortheseobjects(Window,Cursor,Colormapandsoon),whicharealleventually
mappedtosimpleintegers.Weshouldstillusethesetypenameswhendefiningvariablesthat
holdhandlesforportabilityreasons.
MemoryAllocationForXlibStructures
VariousstructuretypesareusedinXlib'sinterface.Someofthemareallocateddirectlybythe
user.OthersareallocatedusingspecificXlibfunctions.Thisallowsthelibrarytoinitialize
properlythesestructures.Thisisveryhandy,sincethesestructurestendtocontainalotof
variables,makingitrathertediousforthepoorprogrammertoinitialize.RememberXlibtries
tobeasflexibleaspossible,andthismeansitisalsoascomplexasitcanget.Havingdefault
valueswillenableabeginnerXprogrammertousethelibrary,withoutinterferingwiththe
abilityofamoreexperiencedprogrammertotweakwiththesezillionsofoptions.
Asforfreeingmemory,thisisdoneinoneoftwoways.Incaseswhereweallocatedthe
memorywefreeitinthesamemanner(i.e.usefree()tofreememoryallocatedusing
malloc()).IncaseweusedsomeXlibfunctiontoallocateit,orweusedsomeXlibquery
methodthatreturnsdynamicallyallocatedmemorywewillusetheXFree()functiontofree
thismemoryblock.
Events
Astructureoftype'XEvent'isusedtopasseventsreceivedfromtheXserver.Xlibsupportsa
largeamountofeventtypes.TheXEventstructurecontainsthetypeofeventreceived,aswell
asthedataassociatedwiththeevent(e.g.positiononthescreenwheretheeventwas
generated,mousebuttonassociatedwiththeevent,regionofscreenassociatedwitha'redraw'
event,etc).Thewaytoreadtheevent'sdatadependsontheeventtype.Thus,anXEvent
structurecontainsaClanguageunionofallpossibleeventtypes(ifyou'renotsurewhatC
unionsare,itistimetocheckyourprofferedClanguagemanual...).Thus,wecouldhavean
XExposeevent,anXButtonevent,anXMotionevent,etc.

CompilingXlibBasedPrograms
%ccprog.coprogL/usr/X11/liblX11

orperhapsthis(forasystemwithrelease6ofX11):
%ccprog.coprogL/usr/X11R6/liblX1

HowtouseXinaCprogram
Fromtheprogrammer'spointofviewXconsistsofalibraryofsubroutineswhichhemaycall
inordertoperformspecificfunctionsonthedisplay.Thesefunctionsarecontainedinalibrary,
/usr/lib/libX11.a,(or/usr/lib/X11R5/libX11.slon)whichmustbelinkedintotheprogramby
theloaderwhentheexecutableversionoftheprogramisgenerated.Thiscanusuallybedone
byaddinglX11totheendofthecompilationcommandand,on,L/usr/lib/X11R5tothe
start.TheXlibheaderfileX11/Xlib.h(or/usr/include/X11R5/Xlib.hon)mustalsobeincluded
atthetopofeveryprogramfilewhichusestheXlibrary.OnthethisrequirestheadditionofI
/usr/include/X11R5
ThecoordinatesystemforXwindowshasitsoriginatthetoplefthandcornerofanygiven
window.Thexcoordinateincreasesfromlefttorightacrossthepageandtheycoordinate
increasesfromtoptobottom.Theglobalcoordinatesystemiseffectivelythatofthe
RootWindowwhichcoversthewholeofthescreen.ThescalingofcoordinatesonanXdisplay
isneverchanged,howeveroperationsineachwindowareperformedrelativetothatwindow's
origin.
XfunctionswhicharedescribedasreturningStatusproduceanonzerovalueiftheyhave
executedsuccessfullyandreturnzeroiftheyhavefailed.OthHowtouseXinaCprogram
Fromtheprogrammer'spointofviewXconsistsofalibraryofsubroutineswhichhemaycall
inordertoperformspecificfunctionsonthedisplay.Thesefunctionsarecontainedinalibrary,
/usr/lib/libX11.a,(or/usr/lib/X11R5/libX11.so)whichmustbelinkedintotheprogramby
theloaderwhentheexecutableversionoftheprogramisgenerated.Thiscanusuallybedone
byaddinglX11totheendofthecompilationcommandand,on,L/usr/lib/X11R6tothe
start.TheXlibheaderfileX11/Xlib.h(or/usr/include/X11R5/Xlib.h)mustalsobeincludedat
thetopofeveryprogramfilewhichusestheXlibrary.OnthethisrequirestheadditionofI
/usr/include/X11R6
ThecoordinatesystemforXwindowshasitsoriginatthetoplefthandcornerofanygiven
window.Thexcoordinateincreasesfromlefttorightacrossthepageandtheycoordinate
increasesfromtoptobottom.Theglobalcoordinatesystemiseffectivelythatofthe
RootWindowwhichcoversthewholeofthescreen.ThescalingofcoordinatesonanXdisplay
isneverchanged,howeveroperationsineachwindowareperformedrelativetothatwindow's
origin.
XfunctionswhicharedescribedasreturningStatusproduceanonzerovalueiftheyhave
executedsuccessfullyandreturnzeroiftheyhavefailed.Otherroutineswhichreturnapointer
tosomethingonsuccessusuallyreturntheNULLpointeronfailure.

Tosavespace,wehaveonlydeclaredargumentswhosetypeoruseisnotselfevident.Most
particularly,thefollowingvariablesarenotdeclared:
Display*display;
Windoww;
Drawabled;/*eitherawindowyoucandrawintoor
offscreenmemory(apixmap)*/
GCgc;/*aGraphicsContext,wherecurrentfont,

OpeningAndClosingTheConnectionToAnXServer
AnXprogramfirstneedstoopentheconnectiontotheXserver.Whenwedothat,weneedto
specifytheaddressofthehostrunningtheXserver,aswellasthedisplaynumber.TheX
windowsystemcansupportseveraldisplaysallconnectedtothesamemachine.However,
usuallythereisonlyonesuchdisplay,whichisdisplaynumber'0'.Ifwewantedtoconnectto
thelocaldisplay(i.e.thedisplayofthemachineonwhichourclientprogramruns),wecould
specifythedisplayas":0".Toconnecttothefirstdisplayofamachinewhoseaddressis
"simey",wecouldusetheaddress"conn".Hereishowtheconnectionisopened:
#include<X11/Xlib.h>/*definescommonXlibfunctionsandstructs.*/
.
.
/*thisvariablewillcontainthepointertotheDisplaystructure*/
/*returnedwhenopeningaconnection.*/
Display*display;
/*opentheconnectiontothedisplay"conn".*/
display=XOpenDisplay("conn");
if(display==NULL){
fprintf(stderr,"CannotconnecttoXserver%s\n","conn");
exit(1);
}

NotethatiscommonforXprogramstocheckiftheenvironmentvariable'DISPLAY'isdefined,
andifitis,useitscontentsastheparametertotheXOpenDisplay()function.
WhentheprogramfinisheditsbusinessandneedstoclosetheconnectiontheXserver,itdoes
somethinglikethis:
XCloseDisplay(display);

Thiswouldcauseallwindowscreatedbytheprogram(ifanyareleft)tobeautomatically
closedbytheserver,andanyresourcesstoredontheserveronbehalfoftheclientstobe
freed.Notethatthisdoesnotcauseourclientprogramtoterminatewecouldusethenormal
exit()functiontodothat.

CheckingBasicInformationAboutADisplay
OnceweopenedaconnectiontoanXserver,weshouldchecksomebasicinformationaboutit:
whatscreensithas,whatisthesize(widthandheight)ofthescreen,howmanycolorsit
supports(blackandwhite?greyscale?256colors?more?),andsoon.Wewillshowacode
snippetthatmakesfewofthesechecks,withcommentsexplainingeachfunctionasitisbeing
used.Weassumethat'display'isapointertoa'Display'structure,asreturnedbyaprevious
calltoXOpenDisplay().
/*thisvariablewillbeusedtostorethe"default"screenofthe*/
/*Xserver.usuallyanXserverhasonlyonescreen,sowe'reonly*/
/*interestedinthatscreen.*/
intscreen_num;
/*thesevariableswillstorethesizeofthescreen,inpixels.*/
intscreen_width;
intscreen_height;
/*thisvariablewillbeusedtostoretheIDoftherootwindowofour*/
/*screen.Eachscreenalwayshasarootwindowthatcoversthewhole*/
/*screen,andalwaysexists.*/
Windowroot_window;
/*thesevariableswillbeusedtostoretheIDsoftheblackandwhite*/
/*colorsofthegivenscreen.Moreonthiswillbeexplainedlater.*/
unsignedlongwhite_pixel;
unsignedlongblack_pixel;
/*checkthenumberofthedefaultscreenforourXserver.*/
screen_num=DefaultScreen(display);
/*findthewidthofthedefaultscreenofourXserver,inpixels.*/
screen_width=DisplayWidth(display,screen_num);
/*findtheheightofthedefaultscreenofourXserver,inpixels.*/
screen_height=DisplayHeight(display,screen_num);
/*findtheIDoftherootwindowofthescreen.*/
root_window=RootWindow(display,screen_num);
/*findthevalueofawhitepixelonthisscreen.*/
white_pixel=WhitePixel(display,screen_num);
/*findthevalueofablackpixelonthisscreen.*/
black_pixel=BlackPixel(display,screen_num);

Therearevariousothermacrostogetmoreinformationaboutthescreen,thatyoucanfindin
anyXlibreference.Therearealsofunctionequivalentsforsomeofthesemacros(e.g.
XWhitePixel,whichdoesthesameasWhitePixel)

CreatingABasicWindowOur"helloworld"Program
Afterwegotsomebasicinformationaboutourscreen,wecangettocreatingourfirstwindow.
Xlibsuppliesseveralfunctionsforcreatingnewwindows,oneofwhichis
XCreateSimpleWindow().Thisfunctiongetsquiteafewparametersdeterminingthewindow's
size,itsposition,andsoon.Hereisacompletelistoftheseparameters:
Display*display
PointertotheDisplaystructure.
Windowparent
TheIDofanexistingwindowthatshouldbetheparentofthenewwindow.
intx
XPositionofthetopleftcornerofthewindow(givenasnumberofpixelsfromtheleftof
thescreen).
inty
YPositionofthetopleftcornerofthewindow(givenasnumberofpixelsfromthetopof
thescreen).
unsignedintwidth
Widthofthenewwindow,inpixels.
unsignedintheight
Heightofthenewwindow,inpixels.
unsignedintborder_width
Widthofthewindow'sborder,inpixels.
unsignedlongborder
Colortobeusedtopaintthewindow'sborder.
unsignedlongbackground
Colortobeusedtopaintthewindow'sbackground.
Letscreateasimplewindow,whosewidthis1/3ofthescreen'swidth,heightis1/3ofthe
screen'sheight,backgroundcoloriswhite,bordercolorisblack,andborderwidthis2pixels.
Thewindowwillbeplacedatthetopleftcornerofthescreen.
/*thisvariablewillstoretheIDofthenewlycreatedwindow.*/
Windowwin;
/*thesevariableswillstorethewindow'swidthandheight.*/
intwin_width;
intwin_height;
/*thesevariableswillstorethewindow'slocation.*/
intwin_x;
intwin_y;
/*calculatethewindow'swidthandheight.*/
win_width=DisplayWidth(display,screen_num)/3;
win_height=DisplayHeight(display,screen_num)/3;

/*positionofthewindowistopleftcorner0,0.*/
win_x=win_y=0;
/*createthewindow,asspecifiedearlier.*/
win=XCreateSimpleWindow(display,
RootWindow(display,screen_num),
win_x,win_y,
win_width,win_height,
win_border_width,BlackPixel(display,screen_num),
WhitePixel(display,screen_num));

Thefactthatwecreatedthewindowdoesnotmeanitwillbedrawnonscreen.Bydefault,
newlycreatedwindowsarenotmappedonthescreentheyareinvisible.Inordertomakeour
windowvisible,weusetheXMapWindow()function,asfollows:
XMapWindow(display,win);

Toseeallthecodewehavegatheredsofar,takealookatthesimplewindow.cprogram.You'll
seetwomorefunctionnotexplainedsofarXFlush()andXSync().TheXFlush()function
flushesallpendingrequeststotheXservermuchlikethefflush()functionisusedtoflash
standardoutput.TheXSync()functionalsoflushesallpendingrequeststotheXserver,and
thenwaitsuntiltheXserverfinishesprocessingtheserequests.Inanormalprogramthiswill
notbenecessary(you'llseewhywhenwegettowriteanormalXprogram),butfornowwe
putitthere.Trycompilingtheprogrameitherwithorwithoutthesefunctioncallstoseethe
differenceinitsbehavior.

DrawingInAWindow
Drawinginawindowcanbedoneusingvariousgraphicalfunctionsdrawingpixels,lines,
circles,rectangles,etc.Inordertodrawinawindow,wefirstneedtodefinevariousgeneral
drawingparameterswhatlinewidthtouse,whichcolortodrawwith,etc.Thisisdoneusing
agraphicalcontext(GC).
AllocatingAGraphicsContext(GC)
Aswesaid,agraphicalcontextdefinesseveralattributestobeusedwiththevariousdrawing
functions.Forthis,wedefineagraphicalcontext.Wecanusemorethanonegraphicalcontext
withasinglewindow,inordertodrawinmultiplestyles(differentcolors,differentline
widths,etc.).AllocatinganewGCisdoneusingtheXCreateGC()function,asfollows(inthis
codefragment,weassume"display"isapointertoaDisplaystructure,and"win"istheIDofa
previouslycreatedwindow):
/*thisvariablewillcontainthehandletothereturnedgraphicscontext.*/
GCgc;
/*thesevariablesareusedtospecifyvariousattributesfortheGC.*/

/*initialvaluesfortheGC.*/
XGCValuesvalues=CapButt|JoinBevel;
/*whichvaluesin'values'tocheckwhencreatingtheGC.*/
unsignedlongvaluemask=GCCapStyle|GCJoinStyle;
/*createanewgraphicalcontext.*/
gc=XCreateGC(display,win,valuemask,&values);
if(gc<0){
fprintf(stderr,"XCreateGC:\n");
}

Noteshouldbetakenregardingtherolesof"valuemask"and"values".Sinceagraphicscontext
haszillionsofattributes,andsinceoftenwedon'twanttodefinefewofthem,weneedtobe
abletotelltheXCreateGC()whichattributeswewanttoset.Thisiswhatthe"valuemask"
variableisfor.Wethenusethe"values"variabletospecifyactualvaluesfortheattributeswe
definedinthe"valuesmask".Thus,foreachconstantusedin"values",we'llusethematching
constantin"valuesmask".Inthiscase,wedefinedagraphicscontextwithtwoattributes:
1. Whendrawingamultiplepartline,thelinesshouldbejoinedina'Bevelian'style.
2. Aline'sendpointwillbedrawnstraight(asopposedtoendingthelineinaround
shape,ifitswidthismorethan1pixelwide).
TherestoftheattributesofthisGCwillbesettotheirdefaultvalues.

XEvents
InanXlibprogram,everythingisdrivenbyevents.Eventpaintingonthescreenissometimes
doneasaresponsetoaneventan"expose"event.Ifpartofaprogram'swindowthatwas
hidden,getsexposed(e.g.thewindowwasraisedaboveotherwindows),theXserverwill
sendan"expose"eventtolettheprogramknowitshouldrepaintthatpartofthewindow.User
input(keypresses,mousemovement,etc.)isalsoreceivedasasetofevents.
RegisteringForEventTypesUsingEventMasks
Afteraprogramcreatesawindow(orseveralwindows),itshouldtelltheXserverwhattypes
ofeventsitwishestoreceiveforthiswindow.Bydefault,noeventsaresenttotheprogram.It
mayregisterforvariousmouse(alsocalled"pointer")events,keyboardevents,exposeevents
andsoon.Thisisdoneforoptimizingtheservertoclientconnection(i.e.whysendaprogram
(thatmightevenberunningattheothersideoftheglobe)aneventitisnotinterestedin?).
InXlib,weusetheXSelectInput()functiontoregisterforevents.Thisfunctionaccepts3
parametersthedisplaystructure,anIDofawindow,andamaskoftheeventtypesitwishes
toget.ThewindowIDparameterallowsustoregisterforreceivingdifferenttypesofevents
fordifferentwindows.Hereishowweregisterfor"expose"eventsforawindowwhoseIDis
'win':
XSelectInput(display,win,ExposureMask);

ExposureMaskisaconstantdefinedinthe"X.h"headerfile.Ifwewantedtoregistertoseveral
eventtypes,wecanlogically"or"them,asfollows:
XSelectInput(display,win,ExposureMask|ButtonPressMask);

Thisregistersfor"expose"eventsaswellasformousebuttonpressesinsidethegivenwindow.
Youshouldnotethatamaskmayrepresentseveraleventsubtypes.
Note:Acommonbugprogrammersdoisaddingcodetohandleneweventtypesintheirprogram,
whileforgettingtoaddthemasksfortheseeventsinthecalltoXSelectInput().Sucha
programmerthencouldsitdownforhoursdebugginghisprogram,wondering"whydoesn'tmy
programnoticethatireleasedthebutton??",onlytofindthattheyregisteredforbuttonpress
events,butnotforbuttonreleaseevents.
ReceivingEventsWritingTheEventsLoop
Afterwehaveregisteredfortheeventtypesweareinterestedin,weneedtoenteraloopof
receivingeventsandhandlingthem.Therearevariouswaystowritesuchaloop,butthebasic
looplookslikethis:
/*thisstructurewillcontaintheevent'sdata,oncereceived.*/
XEventan_event;
/*enteran"endless"loopofhandlingevents.*/
while(1){
XNextEvent(display,&an_event);
switch(an_event.type){
caseExpose:
/*handlethiseventtype...*/
.
.
break;
default:/*unknowneventtypeignoreit.*/
break;
}
}

TheXNextEvent()functionfetchesthenexteventcomingfromtheXserver.Ifnoeventis
waiting,itblocksuntiloneisreceived.Whenitreturns,theevent'sdataisplacedintheXEvent
variablegiventothefunctionasthesecondparameter.Afterthat,the"type"fieldofthis
variablespecifieswhattypeofeventwegot.Exposeistheeventtypethattellsusthereisa
partofthewindowthatneedstoberedrawn.Afterwehandlethisevent,wegobackandwait
forthenexteventtoprocess.Obviously,wewillneedtogivetheusersomewayofterminating
theprogram.Thisisusuallydonebyhandlingaspecial"quit"event,aswe'llsoonsee.
AndmessingwithmousethatIwillwriteasandwhenIgetresponsefromthis
article,ifatallanyoneisinterested.Sendmeyourreplyandkeeponinformingmeabout
yourXWindowSystemProgramming.Pleasekindlyignorethemistakesinthearticle.Any

kindofsuggestionaboutthisarticlearemostwelcome.
...Swapnil
swap.kamble@yahoo.com

You might also like