1 <!DOCTYPE html public "-//W3C//DTD HTML 4.01 Transitional//EN"
2 "http://www.w3.org/TR/html4/loose.dtd">
7 <title>Basic Graphics Programming With The XCB Library</title>
8 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
9 <link href="xcb.css" rel="stylesheet" type="text/css">
14 Basic Graphics Programming With The XCB Library
18 <li><a class="section" href="#intro">Introduction</a>
19 <li><a class="section" href="#Xmodel">The client and server model of the X window system</a>
20 <li><a class="section" href="#asynch">GUI programming: the asynchronous model</a>
21 <li><a class="section" href="#notions">Basic XCB notions</a>
23 <li><a class="subsection" href="#conn">The X Connection</a>
24 <li><a class="subsection" href="#requestsreplies">Requests and replies: the Xlib killers</a>
25 <li><a class="subsection" href="#gc">The Graphics Context</a>
27 <li>Memory allocation for XCB structures
28 <li><a class="subsection" href="#events">Events</a>
30 <li><a class="section" href="#use">Using XCB-based programs</a>
32 <li><a class="subsection" href="#inst">Installation of XCB</a>
33 <li><a class="subsection" href="#comp">Compiling XCB-based programs</a>
35 <li><a class="section" href="#openconn">Opening and closing the connection to an X server</a>
36 <li><a class="section" href="#screen">Checking basic information about a connection</a>
37 <li><a class="section" href="#helloworld">Creating a basic window - the "hello world" program</a>
38 <li><a class="section" href="#drawing">Drawing in a window</a>
40 <li><a class="subsection" href="#allocgc">Allocating a Graphics Context</a>
41 <li><a class="subsection" href="#changegc">Changing the attributes of a Graphics Context</a>
42 <li><a class="subsection" href="#drawingprim">Drawing primitives: point, line, box, circle,...</a>
44 <li><a class="section" href="#xevents">X Events</a>
46 <li><a class="subsection" href="#register">Registering for event types using event masks</a>
47 <li><a class="subsection" href="#loop">Receiving events: writing the events loop</a>
48 <li><a class="subsection" href="#expose">Expose events</a>
49 <li><a class="subsection" href="#userinput">Getting user input</a>
51 <li><a class="subsubsection" href="#mousepressrelease">Mouse button press and release events</a>
52 <li><a class="subsubsection" href="#mousemvnt">Mouse movement events</a>
53 <li><a class="subsubsection" href="#mouseenter">Mouse pointer enter and leave events</a>
54 <li><a class="subsubsection" href="#focus">The keyboard focus</a>
55 <li><a class="subsubsection" href="#keypress">Keyboard press and release events</a>
57 <li><a class="subsection" href="#eventex">X events: a complete example</a>
59 <li><a class="section" href="#font">Handling text and fonts</a>
61 <li><a class="subsection" href="#fontstruct">The Font structure</a>
63 <li>Assigning a Font to a Graphic Context
64 <li>Drawing text in a window
68 <li>Root, parent and child windows
69 <li>Events propagation
71 <li><a class="section" href="#wm">Interacting with the window manager</a>
73 <li><a class="subsection" href="#wmprop">Window properties</a>
74 <li><a class="subsection" href="#wmname">Setting the window name and icon name</a>
75 <li>Setting preferred window size(s)
76 <li>Setting miscellaneous window manager hints
77 <li>Setting an application's icon
78 <li>Obeying the delete-window protocol
80 <li><a class="section" href="#winop">Simple window operations</a>
82 <li><a class="subsection" href="#winmap">Mapping and unmapping a window</a>
83 <li><a class="subsection" href="#winconf">Configuring a window</a>
84 <li><a class="subsection" href="#winmove">Moving a window around the screen</a>
85 <li><a class="subsection" href="#winsize">Resizing a window</a>
86 <li><a class="subsection" href="#winstack">Changing windows stacking order: raise and lower</a>
87 <li>Iconifying and de-iconifying a window
88 <li><a class="subsection" href="#wingetinfo">Getting informations about a window</a>
90 <li><a class="section" href="#usecolor">Using colors to paint the rainbow</a>
92 <li><a class="subsection" href="#colormap">Color maps</a>
93 <li><a class="subsection" href="#colormapalloc">Allocating and freeing Color Maps</a>
94 <li><a class="subsection" href="#alloccolor">Allocating and freeing a color entry</a>
95 <li>Drawing with a color
97 <li><a class="section" href="#pixmaps">X Bitmaps and Pixmaps</a>
99 <li><a class="subsection" href="#pixmapswhat">What is a X Bitmap ? An X Pixmap ?</a>
100 <li>Loading a bitmap from a file
101 <li>Drawing a bitmap in a window
102 <li><a class="subsection" href="#pixmapscreate">Creating a pixmap</a>
103 <li><a class="subsection" href="#pixmapsdraw">Drawing a pixmap in a window</a>
104 <li><a class="subsection" href="#pixmapsfree">Freeing a pixmap</a>
106 <li>Messing with the mouse cursor
108 <li>Creating and destroying a mouse cursor
109 <li>Setting a window's mouse cursor
111 <li><a class="subsection" href="#translation">Translation of basic Xlib functions and macros</a>
113 <li><a class="subsection" href="#displaystructure">Members of the Display structure</a>
115 <li><a class="subsection" href="#ConnectionNumber">ConnectionNumber</a>
116 <li><a class="subsection" href="#DefaultScreen">DefaultScreen</a>
117 <li><a class="subsection" href="#QLength">QLength</a>
118 <li><a class="subsection" href="#ScreenCount">ScreenCount</a>
119 <li><a class="subsection" href="#ServerVendor">ServerVendor</a>
120 <li><a class="subsection" href="#ProtocolVersion">ProtocolVersion</a>
121 <li><a class="subsection" href="#ProtocolRevision">ProtocolRevision</a>
122 <li><a class="subsection" href="#VendorRelease">VendorRelease</a>
123 <li><a class="subsection" href="#DisplayString">DisplayString</a>
124 <li><a class="subsection" href="#BitmapUnit">BitmapUnit</a>
125 <li><a class="subsection" href="#BitmapBitOrder">BitmapBitOrder</a>
126 <li><a class="subsection" href="#BitmapPad">BitmapPad</a>
127 <li><a class="subsection" href="#ImageByteOrder">ImageByteOrder</a>
129 <li><a class="subsection" href="#screenofdisplay">ScreenOfDisplay related functions</a>
131 <li><a class="subsection" href="#ScreenOfDisplay">ScreenOfDisplay</a>
132 <li><a class="subsection" href="#DefaultScreenOfDisplay">DefaultScreenOfDisplay</a>
133 <li><a class="subsection" href="#RootWindow">RootWindow / RootWindowOfScreen</a>
134 <li><a class="subsection" href="#DefaultRootWindow">DefaultRootWindow</a>
135 <li><a class="subsection" href="#DefaultVisual">DefaultVisual / DefaultVisualOfScreen</a>
136 <li><a class="subsection" href="#DefaultGC">DefaultGC / DefaultGCOfScreen</a>
137 <li><a class="subsection" href="#BlackPixel">BlackPixel / BlackPixelOfScreen</a>
138 <li><a class="subsection" href="#WhitePixel">WhitePixel / WhitePixelOfScreen</a>
139 <li><a class="subsection" href="#DisplayWidth">DisplayWidth / WidthOfScreen</a>
140 <li><a class="subsection" href="#DisplayHeight">DisplayHeight / HeightOfScreen</a>
141 <li><a class="subsection" href="#DisplayWidthMM">DisplayWidthMM / WidthMMOfScreen</a>
142 <li><a class="subsection" href="#DisplayHeightMM">DisplayHeightMM / HeightMMOfScreen</a>
143 <li><a class="subsection" href="#DisplayPlanes">DisplayPlanes / DefaultDepth / DefaultDepthOfScreen / PlanesOfScreen</a>
144 <li><a class="subsection" href="#DefaultColormap">DefaultColormap / DefaultColormapOfScreen</a>
145 <li><a class="subsection" href="#MinCmapsOfScreen">MinCmapsOfScreen</a>
146 <li><a class="subsection" href="#MaxCmapsOfScreen">MaxCmapsOfScreen</a>
147 <li><a class="subsection" href="#DoesSaveUnders">DoesSaveUnders</a>
148 <li><a class="subsection" href="#DoesBackingStore">DoesBackingStore</a>
149 <li><a class="subsection" href="#EventMaskOfScreen">EventMaskOfScreen</a>
151 <li><a class="subsection" href="#misc">Miscellaneaous macros</a>
153 <li><a class="subsection" href="#DisplayOfScreen">DisplayOfScreen</a>
154 <li><a class="subsection" href="#DisplayCells">DisplayCells / CellsOfScreen</a>
159 <div class="section">
161 <li class="title"><a name="intro">Introduction</a>
163 This tutorial is based on the
164 <a href="http://users.actcom.co.il/~choo/lupg/tutorials/xlib-programming/xlib-programming.html">Xlib Tutorial</a>
165 written by <a href="mailto:choor@atcom.co.il">Guy Keren</a>. The
166 author allowed me to take some parts of his text, mainly the text which
167 deals with the X Windows generality.
170 This tutorial is intended for people who want to start to program
171 with the <a href="http://xcb.freedesktop.org">XCB</a>
172 library. keep in mind that XCB, like the
173 <a href="http://tronche.com/gui/x/xlib/introduction">Xlib</a>
174 library, isn't what post programmers wanting to write X
175 applications are looking for. They should use a much higher
176 level GUI toolkit like Motif,
177 <a href="http://www.lesstif.org">LessTiff</a>,
178 <a href="http://www.gtk.org">GTK</a>,
179 <a href="http://www.trolltech.com">QT</a> or
180 <a href="http://www.enlightenment.org">EWL</a>, or use
181 <a href="http://cairographics.org">Cairo</a>.
183 we need to start somewhere. More than this, knowing how things
184 work down below is never a bad idea.
187 After reading this tutorial, one should be able to write very
188 simple graphical programs, but not programs with decent user
189 interfaces. For such programs, one of the previously mentioned
190 libraries should be used.
193 But what is XCB? Xlib has been
194 the standard C binding for the <a href="http://www.x.org">X
195 Window System</a> protocol for many years now. It is an
196 excellent piece of work, but there are applications for which it
197 is not ideal, for example:
200 <li><b>Small platforms</b>: Xlib is a large piece of code, and
201 it's difficult to make it smaller
202 <li><b>Latency hiding</b>: Xlib requests requiring a reply are
203 effectively synchronous: they block until the reply appears,
204 whether the result is needed immediately or not.
205 <li><b>Direct access to the protocol</b>: Xlib does quite a
206 bit of caching, layering, and similar optimizations. While this
207 is normally a feature, it makes it difficult to simply emit
208 specified X protocol requests and process specific
210 <li><b>Threaded applications</b>: While Xlib does attempt to
211 support multithreading, the API makes this difficult and
213 <li><b>New extensions</b>: The Xlib infrastructure provides
214 limited support for the new creation of X extension client side
218 For these reasons, among others, XCB, an X C binding, has been
219 designed to solve the above problems and thus provide a base for
222 <li>Toolkit implementation.
223 <li>Direct protocol-level programming.
224 <li>Lightweight emulation of commonly used portions of the
228 <li class="title"><a name="Xmodel">The client and server model of the X window system</a>
230 The X Window System was developed with one major goal:
231 flexibility. The idea was that the way things look is one thing,
232 but the way things work is another matter. Thus, the lower
233 levels provide the tools required to draw windows, handle user
234 input, allow drawing graphics using colors (or black and white
235 screens), etc. To this point, a decision was made to separate
236 the system into two parts. A client that decides what to do, and
237 a server that actually draws on the screen and reads user input
238 in order to send it to the client for processing.
241 This model is the complete opposite of what is used to when
242 dealing with clients and servers. In our case, the user sits
243 near the machine controlled by the server, while the client
244 might be running on a remote machine. The server controls the
245 screens, mouse and keyboard. A client may connect to the server,
246 request that it draws a window (or several windows), and ask the
247 server to send it any input the user sends to these
248 windows. Thus, several clients may connect to a single X server
249 (one might be running mail software, one running a WWW
250 browser, etc). When input is sent by the user to some window,
251 the server sends a message to the client controlling this window
252 for processing. The client decides what to do with this input,
253 and sends the server requests for drawing in the window.
256 The whole session is carried out using the X message
257 protocol. This protocol was originally carried over the TCP/IP
258 protocol suite, allowing the client to run on any machine
259 connected to the same network that the server is. Later on, the
260 X servers were extended to allow clients running on the local
261 machine with more optimized access to the server (note that an X
262 protocol message may be several hundreds of KB in size), such as
263 using shared memory, or using Unix domain sockets (a method for
264 creating a logical channel on a Unix system between two processes).
266 <li class="title"><a name="asynch">GUI programming: the asynchronous model</a>
268 Unlike conventional computer programs, that carry some serial
269 nature, a GUI program usually uses an asynchronous programming
270 model, also known as "event-driven programming". This means that
271 that program mostly sits idle, waiting for events sent by the X
272 server, and then acts upon these events. An event may say "The
273 user pressed the 1st button mouse in spot (x,y)", or "The window
274 you control needs to be redrawn". In order for the program to be
275 responsive to the user input, as well as to refresh requests, it
276 needs to handle each event in a rather short period of time
277 (e.g. less that 200 milliseconds, as a rule of thumb).
280 This also implies that the program may not perform operations
281 that might take a long time while handling an event (such as
282 opening a network connection to some remote server, or
283 connecting to a database server, or even performing a long file
284 copy operation). Instead, it needs to perform all these
285 operations in an asynchronous manner. This may be done by using
286 various asynchronous models to perform the longish operations,
287 or by performing them in a different process or thread.
290 So the way a GUI program looks is something like that:
293 <li>Perform initialization routines.
294 <li>Connect to the X server.
295 <li>Perform X-related initialization.
296 <li>While not finished:
298 <li>Receive the next event from the X server.
299 <li>Handle the event, possibly sending various drawing
300 requests to the X server.
301 <li>If the event was a quit message, exit the loop.
303 <li>Close down the connection to the X server.
304 <li>Perform cleanup operations.
307 <li class="title"><a name="notions">Basic XCB notions</a>
309 XCB has been created to eliminate the need for
310 programs to actually implement the X protocol layer. This
311 library gives a program a very low-level access to any X
312 server. Since the protocol is standardized, a client using any
313 implementation of XCB may talk with any X server (the same
314 occurs for Xlib, of course). We now give a brief description of
315 the basic XCB notions. They will be detailed later.
318 <li class="subtitle"><a name="conn">The X Connection</a>
320 The major notion of using XCB is the X Connection. This is a
321 structure representing the connection we have open with a
322 given X server. It hides a queue of messages coming from the
323 server, and a queue of pending requests that our client
324 intends to send to the server. In XCB, this structure is named
325 'XCBConnection'. It is analogous to the Xlib Display.
326 When we open a connection to an X server, the
327 library returns a pointer to such a structure. Later, we
328 supply this pointer to any XCB function that should send
329 messages to the X server or receive messages from this server.
331 <li class="subtitle"><a name="requestsreplies">Requests and
332 replies: the Xlib killers</a>
334 To ask for information from the X server, we have to make a request
335 and ask for a reply. With Xlib, these two tasks are
336 automatically done: Xlib locks the system, sends a request,
337 waits for a reply from the X server and unlocks. This is
338 annoying, especially if one makes a lot of requests to the X
339 server. Indeed, Xlib has to wait for the end of a reply
340 before asking for the next request (because of the locks that
341 Xlib sends). For example, here is a time-line of N=4
342 requests/replies with Xlib, with a round-trip latency
343 <b>T_round_trip</b> that is 5 times long as the time required
344 to write or read a request/reply (<b>T_write/T_read</b>):
347 W-----RW-----RW-----RW-----R
350 <li>W: Writing request
351 <li>-: Stalled, waiting for data
355 The total time is N * (T_write + T_round_trip + T_read).
358 With XCB, we can suppress most of the round-trips as the
359 requests and the replies are not locked. We usually send a
360 request, then XCB returns to us a <b>cookie</b>, which is an
361 identifier. Then, later, we ask for a reply using this
362 <b>cookie</b> and XCB returns a
363 pointer to that reply. Hence, with XCB, we can send a lot of
364 requests, and later in the program, ask for all the replies
365 when we need them. Here is the time-line for 4
366 requests/replies when we use this property of XCB:
372 The total time is N * T_write + max (0, T_round_trip - (N-1) *
373 T_write) + N * T_read. Which can be considerably faster than
374 all those Xlib round-trips.
377 Here is a program that computes the time to create 500 atoms
378 with Xlib and XCB. It shows the Xlib way, the bad XCB way
379 (which is similar to Xlib) and the good XCB way. On my
380 computer, XCB is 25 times faster than Xlib.
383 #include <stdlib.h>
384 #include <stdio.h>
385 #include <string.h>
386 #include <sys/time.h>
388 #include <X11/XCB/xcb.h>
390 #include <X11/Xlib.h>
395 struct timeval timev;
397 gettimeofday(&timev, NULL);
399 return (double)timev.tv_sec + (((double)timev.tv_usec) / 1000000);
407 XCBInternAtomCookie *cs;
420 c = XCBConnect (NULL, NULL);
423 atoms = (XCBATOM *)malloc (count * sizeof (atoms));
424 names = (char **)malloc (count * sizeof (char *));
427 for (i = 0; i < count; ++i)
431 sprintf (buf, "NAME%d", i);
432 names[i] = strdup (buf);
438 for (i = 0; i < count; ++i)
439 atoms[i] = XCBInternAtomReply (c,
448 printf ("bad use time : %f\n", diff);
453 cs = (XCBInternAtomCookie *) malloc (count * sizeof(XCBInternAtomCookie));
454 for(i = 0; i < count; ++i)
455 cs[i] = XCBInternAtom (c, 0, strlen(names[i]), names[i]);
457 for(i = 0; i < count; ++i)
461 r = XCBInternAtomReply(c, cs[i], 0);
468 printf ("good use time : %f\n", end - start);
469 printf ("ratio : %f\n", diff / (end - start));
473 for (i = 0; i < count; ++i)
483 disp = XOpenDisplay (getenv("DISPLAY"));
485 atoms_x = (Atom *)malloc (count * sizeof (atoms_x));
489 for (i = 0; i < count; ++i)
490 atoms_x[i] = XInternAtom(disp, names[i], 0);
493 diff_x = end - start;
494 printf ("Xlib use time : %f\n", diff_x);
495 printf ("ratio : %f\n", diff_x / diff);
500 XCloseDisplay (disp);
505 <li class="subtitle"><a name="gc">The Graphic Context</a>
507 When we perform various drawing operations (graphics, text,
508 etc), we may specify various options for controlling how the
509 data will be drawn (what foreground and background colors to
510 use, how line edges will be connected, what font to use when
511 drawing some text, etc). In order to avoid the need to supply
512 hundreds of parameters to each drawing function, a graphical
513 context structure is used. We set the various drawing options
514 in this structure, and then we pass a pointer to this
515 structure to any drawing routines. This is rather handy, as we
516 often need to perform several drawing requests with the same
517 options. Thus, we would initialize a graphical context, set
518 the desired options, and pass this structure to all drawing
522 Note that graphic contexts have no client-side structure in
523 XCB, they're just XIDs. Xlib has a client-side structure
524 because it caches the GC contents so it can avoid making
525 redundant requests, but of course XCB doesn't do that.
527 <li class="subtitle"><a name="events">Events</a>
529 A structure is used to pass events received from the X
530 server. XCB supports exactly the events specified in the
531 protocol (33 events). This structure contains the type
532 of event received (including a bit for whether it came
533 from the server or another client), as well as the data associated with the
534 event (e.g. position on the screen where the event was
535 generated, mouse button associated with the event, region of
536 the screen associated with a "redraw" event, etc). The way to
537 read the event's data depends on the event type.
541 <li class="title"><a name="use">Using XCB-based programs</a>
544 <li class="subtitle"><a name="inst">Installation of XCB</a>
546 <b>TODO:</b> These instructions are out of date.
547 Just reference the <a href="http://xcb.freedesktop.org/">main XCB page</a>
548 so we don't have to maintain these instructions in more than
552 To build XCB from source, you need to have installed at
559 <li><a href="http://www.check.org">check</a>
560 <li><a href="http://xmlsoft.org/XSLT/">xsltproc</a>
563 You have to checkout in CVS the following modules:
566 <li>Xproto from xlibs
572 Note that Xproto and xcb-proto exist only to install header
573 files, so typing 'make' or 'make all' will produce the message
574 "Nothing to be done for 'all'". That's normal.
576 <li class="subtitle"><a name="comp">Compiling XCB-based programs</a>
578 Compiling XCB-based programs requires linking them with the XCB
579 library. This is easily done thanks to pkgconfig:
582 gcc -Wall prog.c -o prog `pkg-config --cflags --libs xcb`
585 <li class="title"><a name="openconn">Opening and closing the connection to an X server</a>
587 An X program first needs to open the connection to the X
588 server. There is a function that opens a connection. It requires
589 the display name, or NULL. In the latter case, the display name
590 will be the one in the environment variable DISPLAY.
593 XCBConnection *XCBConnect (const char *displayname,
597 The second parameter returns the screen number used for the
598 connection. The returned structure describes an XCB connection
599 and is opaque. Here is how the connection can be opened:
602 #include <X11/XCB/xcb.h>
605 main (int argc, char *argv[])
609 /* Open the connection to the X server. Use the DISPLAY environment variable as the default display name */
610 c = XCBConnect (NULL, NULL);
616 To close a connection, it suffices to use:
619 void XCBDisconnect (XCBConnection *c);
648 <li class="title"><a name="screen">Checking basic information about a connection</a>
650 Once we have opened a connection to an X server, we should check some
651 basic information about it: what screens it has, what is the
652 size (width and height) of the screen, how many colors it
653 supports (black and white ? grey scale ?, 256 colors ? more ?),
654 and so on. We get such information from the XCBSCREEN
660 XCBCOLORMAP default_colormap;
663 CARD32 current_input_masks;
664 CARD16 width_in_pixels;
665 CARD16 height_in_pixels;
666 CARD16 width_in_millimeters;
667 CARD16 height_in_millimeters;
668 CARD16 min_installed_maps;
669 CARD16 max_installed_maps;
670 XCBVISUALID root_visual;
674 CARD8 allowed_depths_len;
678 We could retrieve the first screen of the connection by using the
682 XCBSCREENIter XCBSetupRootsIter (XCBSetup *R);
685 Here is a small program that shows how to use this function:
688 #include <stdio.h>
690 #include <X11/XCB/xcb.h>
693 main (int argc, char *argv[])
700 /* Open the connection to the X server. Use the DISPLAY environment variable */
701 c = XCBConnect (NULL, &screen_nbr);
703 /* Get the screen #screen_nbr */
704 iter = XCBSetupRootsIter (XCBGetSetup (c));
705 for (; iter.rem; --screen_nbr, XCBSCREENNext (&iter))
713 printf ("Informations of screen %ld:\n", screen->root.xid);
714 printf (" width.........: %d\n", screen->width_in_pixels);
715 printf (" height........: %d\n", screen->height_in_pixels);
716 printf (" white pixel...: %ld\n", screen->white_pixel);
717 printf (" black pixel...: %ld\n", screen->black_pixel);
723 <li class="title"><a name="helloworld">Creating a basic window - the "hello world" program</a>
725 After we got some basic information about our screen, we can
726 create our first window. In the X Window System, a window is
727 characterized by an Id. So, in XCB, a window is of type:
735 We first ask for a new Id for our window, with this function:
738 XCBWINDOW XCBWINDOWNew(XCBConnection *c);
741 Then, XCB supplies the following function to create new windows:
744 XCBVoidCookie XCBCreateWindow (XCBConnection *c, /* Pointer to the XCBConnection structure */
745 CARD8 depth, /* Depth of the screen */
746 XCBWINDOW wid, /* Id of the window */
747 XCBWINDOW parent, /* Id of an existing window that should be the parent of the new window */
748 INT16 x, /* X position of the top-left corner of the window (in pixels) */
749 INT16 y, /* Y position of the top-left corner of the window (in pixels) */
750 CARD16 width, /* Width of the window (in pixels) */
751 CARD16 height, /* Height of the window (in pixels) */
752 CARD16 border_width, /* Width of the window's border (in pixels) */
756 const CARD32 *value_list);
759 The fact that we created the window does not mean that it will
760 be drawn on screen. By default, newly created windows are not
761 mapped on the screen (they are invisible). In order to make our
762 window visible, we use the function <span class="code">XCBMapWindow()</span>, whose
766 XCBVoidCookie XCBMapWindow (XCBConnection *c, XCBWINDOW window);
769 Finally, here is a small program to create a window of size
770 150x150 pixels, positioned at the top-left corner of the screen:
773 #include <unistd.h> /* pause() */
775 #include <X11/XCB/xcb.h>
778 main (int argc, char *argv[])
784 /* Open the connection to the X server */
785 c = XCBConnect (NULL, NULL);
787 /* Get the first screen */
788 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
790 /* Ask for our window's Id */
791 win.window = XCBWINDOWNew(c);
793 /* Create the window */
794 XCBCreateWindow (c, /* Connection */
795 XCBCopyFromParent, /* depth (same as root)*/
796 win.window, /* window Id */
797 screen->root, /* parent window */
799 150, 150, /* width, height */
800 10, /* border_width */
801 XCBWindowClassInputOutput,/* class */
802 screen->root_visual, /* visual */
803 0, NULL); /* masks, not used yet */
805 /* Map the window on the screen */
806 XCBMapWindow (c, win.window);
808 /* Make sure commands are sent before we pause, so window is shown */
811 pause (); /* hold client until Ctrl-C */
817 In this code, you see one more function - <span class="code">XCBFlush()</span>, not explained
818 yet. It is used to flush all the pending requests. More
819 precisely, there are 2 functions that do such things. The first
820 one is <span class="code">XCBFlush()</span>:
823 int XCBFlush (XCBConnection *c);
826 This function flushes all pending requests to the X server (much
827 like the <span class="code">fflush()</span> function is used to
828 flush standard output). The second function is
829 <span class="code">XCBSync()</span>:
832 int XCBSync(XCBConnection *c, XCBGenericError **e);
835 This functions also flushes all pending requests to the X
836 server, and then waits until the X server finishing processing
837 these requests. In a normal program, this will not be necessary
838 (we'll see why when we get to write a normal X program), but for
839 now, we put it there.
842 The window that is created by the above code has a default
843 background (gray). This one can be set to a specific color,
844 thanks to the two last parameters of
845 <span class="code">XCBCreateWindow()</span>, which are not
846 described yet. See the subsections
847 <a href="#winconf">Configuring a window</a> or
848 <a href="#winconf">Registering for event types using event masks</a>
849 for examples on how to use these parameters. In addition, as no
850 events are handled, you have to make a Ctrl-C to interrupt the
854 <b>TODO</b>: one should tell what these functions return and
855 about the generic error
869 <li>XCBCreateWindow ()
874 <li class="title"><a name="drawing">Drawing in a window</a>
876 Drawing in a window can be done using various graphical
877 functions (drawing pixels, lines, rectangles, etc). In order to
878 draw in a window, we first need to define various general
879 drawing parameters (what line width to use, which color to draw
880 with, etc). This is done using a graphical context.
883 <li class="subtitle"><a name="allocgc">Allocating a Graphics Context</a>
885 As we said, a graphical context defines several attributes to
886 be used with the various drawing functions. For this, we
887 define a graphical context. We can use more than one graphical
888 context with a single window, in order to draw in multiple
889 styles (different colors, different line widths, etc). In XCB,
890 a Graphics Context is, as a window, characterized by an Id:
898 We first ask the X server to attribute an Id to our graphic
899 context with this function:
902 XCBGCONTEXT XCBGCONTEXTNew (XCBConnection *c);
905 Then, we set the attributes of the graphic context with this function:
908 XCBVoidCookie XCBCreateGC (XCBConnection *c,
910 XCBDRAWABLE drawable,
912 const CARD32 *value_list);
915 We give now an example on how to allocate a graphic context
916 that specifies that each drawing function that uses it will
917 draw in foreground with a black color.
920 #include <X11/XCB/xcb.h>
923 main (int argc, char *argv[])
932 /* Open the connection to the X server and get the first screen */
933 c = XCBConnect (NULL, NULL);
934 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
936 /* Create a black graphic context for drawing in the foreground */
937 win.window = screen->root;
938 black = XCBGCONTEXTNew (c);
939 mask = XCBGCForeground;
940 value[0] = screen->black_pixel;
941 XCBCreateGC (c, black, win, mask, value);
947 Note should be taken regarding the role of "value_mask" and
948 "value_list" in the prototype of <span class="code">XCBCreateGC()</span>. Since a
949 graphic context has many attributes, and since we often just
950 want to define a few of them, we need to be able to tell the
951 <span class="code">XCBCreateGC()</span> which attributes we
952 want to set. This is what the "value_mask" parameter is
953 for. We then use the "value_list" parameter to specify actual
954 values for the attribute we defined in "value_mask". Thus, for
955 each constant used in "value_list", we will use the matching
956 constant in "value_mask". In this case, we define a graphic
957 context with one attribute: when drawing (a point, a line,
958 etc), the foreground color will be black. The rest of the
959 attributes of this graphic context will be set to their
963 See the next Subsection for more details.
976 <li>XCBGCONTEXTNew ()
982 <li class="subtitle"><a name="changegc">Changing the attributes of a Graphics Context</a>
984 Once we have allocated a Graphic Context, we may need to
985 change its attributes (for example, changing the foreground
986 color we use to draw a line, or changing the attributes of the
987 font we use to display strings. See Subsections Drawing with a
988 color and Assigning a Font to a Graphic Context). This is done
989 by using this function:
992 XCBVoidCookie XCBChangeGC (XCBConnection *c, /* The XCB Connection */
993 XCBGCONTEXT gc, /* The Graphic Context */
994 CARD32 value_mask, /* Components of the Graphic Context that have to be set */
995 const CARD32 *value_list); /* Value as specified by value_mask */
998 The <span class="code">value_mask</span> parameter could take
999 any combination of these masks from the XCBGC enumeration:
1014 <li>XCBGCTileStippleOriginX
1015 <li>XCBGCTileStippleOriginY
1017 <li>XCBGCSubwindowMode
1018 <li>XCBGCGraphicsExposures
1019 <li>XCBGCClipOriginX
1020 <li>XCBGCClipOriginY
1027 It is possible to set several attributes at the same
1028 time (for example setting the attributes of a font and the
1029 color which will be used to display a string), by OR'ing these
1030 values in <span class="code">value_mask</span>. Then
1031 <span class="code">value_list</span> has to be an array which
1032 lists the value for the respective attributes. <b>These values
1033 must be in the same order as masks listed above.</b> See Subsection
1034 Drawing with a color to have an example.
1037 <b>TODO</b>: set the links of the 3 subsections, once they will
1041 <b>TODO</b>: give an example which sets several attributes.
1043 <li class="subtitle"><a name="drawingprim">Drawing primitives: point, line, box, circle,...</a>
1045 After we have created a Graphic Context, we can draw on a
1046 window using this Graphic Context, with a set of XCB
1047 functions, collectively called "drawing primitives". Let see
1051 To draw a point, or several points, we use
1054 XCBVoidCookie XCBPolyPoint (XCBConnection *c, /* The connection to the X server */
1055 BYTE coordinate_mode, /* Coordinate mode, usually set to XCBCoordModeOrigin */
1056 XCBDRAWABLE drawable, /* The drawable on which we want to draw the point(s) */
1057 XCBGCONTEXT gc, /* The Graphic Context we use to draw the point(s) */
1058 CARD32 points_len, /* The number of points */
1059 const XCBPOINT *points); /* An array of points */
1062 The <span class="code">coordinate_mode</span> parameter
1063 specifies the coordinate mode. Available values are
1066 <li><span class="code">XCBCoordModeOrigin</span>
1067 <li><span class="code">XCBCoordModePrevious</span>
1070 If XCBCoordModePrevious is used, then all points but the first one
1071 are relative to the immediately previous point.
1074 The <span class="code">XCBPOINT</span> type is just a
1075 structure with two fields (the coordinates of the point):
1084 You could see an example in xpoints.c. <b>TODO</b> Set the link.
1087 To draw a line, or a polygonal line, we use
1090 XCBVoidCookie XCBPolyLine (XCBConnection *c, /* The connection to the X server */
1091 BYTE coordinate_mode, /* Coordinate mode, usually set to XCBCoordModeOrigin */
1092 XCBDRAWABLE drawable, /* The drawable on which we want to draw the line(s) */
1093 XCBGCONTEXT gc, /* The Graphic Context we use to draw the line(s) */
1094 CARD32 points_len, /* The number of points in the polygonal line */
1095 const XCBPOINT *points); /* An array of points */
1098 This function will draw the line between the first and the
1099 second points, then the line between the second and the third
1103 To draw a segment, or several segments, we use
1106 XCBVoidCookie XCBPolySegment (XCBConnection *c, /* The connection to the X server */
1107 XCBDRAWABLE drawable, /* The drawable on which we want to draw the segment(s) */
1108 XCBGCONTEXT gc, /* The Graphic Context we use to draw the segment(s) */
1109 CARD32 segments_len, /* The number of segments */
1110 const XCBSEGMENT *segments); /* An array of segments */
1113 The <span class="code">XCBSEGMENT</span> type is just a
1114 structure with four fields (the coordinates of the two points
1115 that define the segment):
1126 To draw a rectangle, or several rectangles, we use
1129 XCBVoidCookie XCBPolyRectangle (XCBConnection *c, /* The connection to the X server */
1130 XCBDRAWABLE drawable, /* The drawable on which we want to draw the rectangle(s) */
1131 XCBGCONTEXT gc, /* The Graphic Context we use to draw the rectangle(s) */
1132 CARD32 rectangles_len, /* The number of rectangles */
1133 const XCBRECTANGLE *rectangles); /* An array of rectangles */
1136 The <span class="code">XCBRECTANGLE</span> type is just a
1137 structure with four fields (the coordinates of the top-left
1138 corner of the rectangle, and its width and height):
1148 <!-- There's no coordinate_mode. Is it normal? -->
1149 <!-- [iano] Yes, it's not in the protocol. -->
1151 To draw an elliptical arc, or several elliptical arcs, we use
1154 XCBVoidCookie XCBPolyArc (XCBConnection *c, /* The connection to the X server */
1155 XCBDRAWABLE drawable, /* The drawable on which we want to draw the arc(s) */
1156 XCBGCONTEXT gc, /* The Graphic Context we use to draw the arc(s) */
1157 CARD32 arcs_len, /* The number of arcs */
1158 const XCBARC *arcs); /* An array of arcs */
1161 The <span class="code">XCBARC</span> type is a structure with
1166 INT16 x; /* Top left x coordinate of the rectangle surrounding the ellipse */
1167 INT16 y; /* Top left y coordinate of the rectangle surrounding the ellipse */
1168 CARD16 width; /* Width of the rectangle surrounding the ellipse */
1169 CARD16 height; /* Height of the rectangle surrounding the ellipse */
1170 INT16 angle1; /* Angle at which the arc begins */
1171 INT16 angle2; /* Angle at which the arc ends */
1176 Note: the angles are expressed in units of 1/64 of a degree,
1177 so to have an angle of 90 degrees, starting at 0,
1178 <span class="code">angle1 = 0</span> and
1179 <span class="code">angle2 = 90 << 6</span>. Positive angles
1180 indicate counterclockwise motion, while negative angles
1181 indicate clockwise motion.
1184 <!-- I think that (x,y) should be the center of the
1185 ellipse, and (width, height) the radius. It's more logical. -->
1186 <!-- iano: Yes, and I bet some toolkits do that.
1187 But the protocol (and many other graphics APIs) define arcs
1188 by bounding rectangles. -->
1190 The corresponding function which fill inside the geometrical
1191 object are listed below, without further explanation, as they
1192 are used as the above functions.
1195 To Fill a polygon defined by the points given as arguments ,
1199 XCBVoidCookie XCBFillPoly (XCBConnection *c,
1200 XCBDRAWABLE drawable,
1203 CARD8 coordinate_mode,
1205 const XCBPOINT *points);
1208 The <span class="code">shape</span> parameter specifies a
1209 shape that helps the server to improve performance. Available
1213 <li><span class="code">XCBPolyShapeComplex</span>
1214 <li><span class="code">XCBPolyShapeNonconvex</span>
1215 <li><span class="code">XCBPolyShapeConvex</span>
1218 To fill one or several rectangles, we use
1221 XCBVoidCookie XCBPolyFillRectangle (XCBConnection *c,
1222 XCBDRAWABLE drawable,
1224 CARD32 rectangles_len,
1225 const XCBRECTANGLE *rectangles);
1228 To fill one or several arcs, we use
1231 XCBVoidCookie XCBPolyFillArc (XCBConnection *c,
1232 XCBDRAWABLE drawable,
1235 const XCBARC *arcs);
1238 <a name="points.c"></a>
1240 To illustrate these functions, here is an example that draws
1241 four points, a polygonal line, two segments, two rectangles
1242 and two arcs. Remark that we use events for the first time, as
1243 an introduction to the next section.
1246 <b>TODO:</b> Use screen->root_depth for depth parameter.
1249 <b>TODO:</b> Remove get_depth(). It isn't used!
1252 #include <stdlib.h>
1253 #include <stdio.h>
1255 #include <X11/XCB/xcb.h>
1257 /* Get the depth of the screen. Needed in order to draw something */
1259 get_depth(XCBConnection *c,
1262 XCBDRAWABLE drawable;
1263 XCBGetGeometryRep *geom;
1266 drawable.window = root->root;
1267 geom = XCBGetGeometryReply (c, XCBGetGeometry(c, drawable), 0);
1271 perror ("GetGeometry(root) failed");
1275 depth = geom->depth;
1282 main (int argc, char *argv[])
1287 XCBGCONTEXT foreground;
1292 /* geometric objects */
1293 XCBPOINT points[] = {
1299 XCBPOINT polyline[] = {
1301 { 5, 20}, /* rest of points are relative */
1305 XCBSEGMENT segments[] = {
1307 {110, 25, 130, 60}};
1309 XCBRECTANGLE rectangles[] = {
1314 {10, 100, 60, 40, 0, 90 << 6},
1315 {90, 100, 55, 40, 0, 270 << 6}};
1317 /* Open the connection to the X server */
1318 c = XCBConnect (NULL, NULL);
1320 /* Get the first screen */
1321 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
1323 /* Create black (foreground) graphic context */
1324 win.window = screen->root;
1326 foreground = XCBGCONTEXTNew (c);
1327 mask = XCBGCForeground | XCBGCGraphicsExposures;
1328 values[0] = screen->black_pixel;
1330 XCBCreateGC (c, foreground, win, mask, values);
1332 /* Ask for our window's Id */
1333 win.window = XCBWINDOWNew(c);
1335 /* Create the window */
1336 mask = XCBCWBackPixel | XCBCWEventMask;
1337 values[0] = screen->white_pixel;
1338 values[1] = XCBEventMaskExposure;
1339 XCBCreateWindow (c, /* Connection */
1340 XCBCopyFromParent, /* depth */
1341 win.window, /* window Id */
1342 screen->root, /* parent window */
1344 150, 150, /* width, height */
1345 10, /* border_width */
1346 XCBWindowClassInputOutput,/* class */
1347 screen->root_visual, /* visual */
1348 mask, values); /* masks */
1350 /* Map the window on the screen */
1351 XCBMapWindow (c, win.window);
1354 /* We flush the request */
1357 while ((e = XCBWaitForEvent (c)))
1359 switch (e->response_type & ~0x80)
1363 /* We draw the points */
1364 XCBPolyPoint (c, XCBCoordModeOrigin, win, foreground, 4, points);
1366 /* We draw the polygonal line */
1367 XCBPolyLine (c, XCBCoordModePrevious, win, foreground, 4, polyline);
1369 /* We draw the segements */
1370 XCBPolySegment (c, win, foreground, 2, segments);
1372 /* We draw the rectangles */
1373 XCBPolyRectangle (c, win, foreground, 2, rectangles);
1375 /* We draw the arcs */
1376 XCBPolyArc (c, win, foreground, 2, arcs);
1378 /* We flush the request */
1385 /* Unknown event type, ignore it */
1389 /* Free the Generic Event */
1397 <li class="title"><a name="xevents">X Events</a>
1399 In an X program, everything is driven by events. Event painting
1400 on the screen is sometimes done as a response to an event (an
1401 <span class="code">Expose</span> event). If part of a program's
1402 window that was hidden, gets exposed (e.g. the window was raised
1403 above other widows), the X server will send an "expose" event to
1404 let the program know it should repaint that part of the
1405 window. User input (key presses, mouse movement, etc) is also
1406 received as a set of events.
1409 <li class="subtitle"><a name="register">Registering for event types using event masks</a>
1411 During the creation of a window, you should give it what kind
1412 of events it wishes to receive. Thus, you may register for
1413 various mouse (also called pointer) events, keyboard events,
1414 expose events, and so on. This is done for optimizing the
1415 server-to-client connection (i.e. why send a program (that
1416 might even be running at the other side of the globe) an event
1417 it is not interested in ?)
1420 In XCB, you use the "value_mask" and "value_list" data in the
1421 <span class="code">XCBCreateWindow()</span> function to
1422 register for events. Here is how we register for
1423 <span class="code">Expose</span> event when creating a window:
1426 mask = XCBCWEventMask;
1427 valwin[0] = XCBEventMaskExposure;
1428 win.window = XCBWINDOWNew (c);
1429 XCBCreateWindow (c, depth, win.window, root->root,
1431 XCBWindowClassInputOutput, root->root_visual,
1435 <span class="code">XCBEventMaskExposure</span> is a constant defined
1436 in the XCBEventMask enumeration in the "xproto.h" header file. If we wanted to register for several
1437 event types, we can logically "or" them, as follows:
1440 mask = XCBCWEventMask;
1441 valwin[0] = XCBEventMaskExposure | XCBEventMaskButtonPress;
1442 win.window = XCBWINDOWNew (c);
1443 XCBCreateWindow (c, depth, win.window, root->root,
1445 XCBWindowClassInputOutput, root->root_visual,
1449 This registers for <span class="code">Expose</span> events as
1450 well as for mouse button presses inside the created
1451 window. You should note that a mask may represent several
1455 The values that a mask could take are given
1456 by the <span class="code">XCBCW</span> enumeration:
1460 XCBCWBackPixmap = 1L<<0,
1461 XCBCWBackPixel = 1L<<1,
1462 XCBCWBorderPixmap = 1L<<2,
1463 XCBCWBorderPixel = 1L<<3,
1464 XCBCWBitGravity = 1L<<4,
1465 XCBCWWinGravity = 1L<<5,
1466 XCBCWBackingStore = 1L<<6,
1467 XCBCWBackingPlanes = 1L<<7,
1468 XCBCWBackingPixel = 1L<<8,
1469 XCBCWOverrideRedirect = 1L<<9,
1470 XCBCWSaveUnder = 1L<<10,
1471 XCBCWEventMask = 1L<<11,
1472 XCBCWDontPropagate = 1L<<12,
1473 XCBCWColormap = 1L<<13,
1474 XCBCWCursor = 1L<<14
1478 <p>Note: we must be careful when setting the values of the valwin
1479 parameter, as they have to follow the order the
1480 <span class="code">XCBCW</span> enumeration. Here is an
1485 mask = XCBCWEventMask | XCBCWBackPixmap;
1486 valwin[0] = XCBNone; /* for XCBCWBackPixmap (whose value is 1) */
1487 valwin[1] = XCBEventMaskExposure | XCBEventMaskButtonPress; /* for XCBCWEventMask, whose value (2048) */
1488 /* is greater than the one of XCBCWBackPixmap */
1491 If the window has already been created, we can use the
1492 <span class="code">XCBConfigureWindow()</span> function to set
1493 the events that the window will receive. The subsection
1494 <a href="#winconf">Configuring a window</a> shows its
1495 prototype. As an example, here is a piece of code that
1496 configures the window to receive the
1497 <span class="code">Expose</span> and
1498 <span class="code">ButtonPress</span> events:
1501 const static CARD32 values[] = { XCBEventMaskExposure | XCBEventMaskButtonPress };
1503 /* The connection c and the window win are supposed to be defined */
1505 XCBConfigureWindow (c, win, XCBCWEventMask, values);
1509 Note: A common bug programmers do is adding code to handle new
1510 event types in their program, while forgetting to add the
1511 masks for these events in the creation of the window. Such a
1512 programmer then should sit down for hours debugging his
1513 program, wondering "Why doesn't my program notice that I
1514 released the button?", only to find that they registered for
1515 button press events but not for button release events.
1518 <li class="subtitle"><a name="loop">Receiving events: writing the events loop</a>
1520 After we have registered for the event types we are interested
1521 in, we need to enter a loop of receiving events and handling
1522 them. There are two ways to receive events: a blocking way and
1527 <span class="code">XCBWaitForEvent (XCBConnection *c)</span>
1528 is the blocking way. It waits (so blocks...) until an event is
1529 queued in the X server. Then it retrieves it into a newly
1530 allocated structure (it dequeues it from the queue) and returns
1531 it. This structure has to be freed. The function returns
1532 <span class="code">NULL</span> if an error occurs.
1536 <span class="code">XCBPollForEvent (XCBConnection *c, int
1537 *error)</span> is the non-blocking way. It looks at the event
1538 queue and returns (and dequeues too) an existing event into
1539 a newly allocated structure. This structure has to be
1540 freed. It returns <span class="code">NULL</span> if there is
1541 no event. If an error occurs, the parameter <span
1542 class="code">error</span> will be filled with the error
1546 There are various ways to write such a loop. We present two
1547 ways to write such a loop, with the two functions above. The
1548 first one uses <span class="code">XCBWaitForEvent</span>, which
1549 is similar to an event Xlib loop using only <span
1550 class="code">XNextEvent</span>:
1555 while ((e = XCBWaitForEvent (c)))
1557 switch (e->response_type & ~0x80)
1561 /* Handle the Expose event type */
1562 XCBExposeEvent *ev = (XCBExposeEvent *)e;
1568 case XCBButtonPress:
1570 /* Handle the ButtonPress event type */
1571 XCBButtonPressEvent *ev = (XCBButtonPressEvent *)e;
1579 /* Unknown event type, ignore it */
1583 /* Free the Generic Event */
1588 You will certainly want to use <span
1589 class="code">XCBPollForEvent(XCBConnection *c, int
1590 *error)</span> if, in Xlib, you use <span
1591 class="code">XPending</span> or
1592 <span class="code">XCheckMaskEvent</span>:
1595 while (XPending (display))
1599 XNextEvent(d, &ev);
1601 /* Manage your event */
1605 Such a loop in XCB looks like:
1608 XCBGenericEvent *ev;
1610 while ((ev = XCBPollForEvent (conn, 0)))
1612 /* Manage your event */
1616 The events are managed in the same way as with <span
1617 class="code">XCBWaitForEvent</span>.
1618 Obviously, we will need to give the user some way of
1619 terminating the program. This is usually done by handling a
1620 special "quit" event, as we will soon see.
1633 <li>XCBWaitForEvent ()
1638 <li>XPending ()</li>
1639 <li>XCheckMaskEvent ()</li>
1644 <li>XCBPollForEvent ()
1649 <li class="subtitle"><a name="expose">Expose events</a>
1651 The <span class="code">Expose</span> event is one of the most
1652 basic (and most used) events an application may receive. It
1653 will be sent to us in one of several cases:
1656 <li>A window that covered part of our window has moved
1657 away, exposing part (or all) of our window.
1658 <li>Our window was raised above other windows.
1659 <li>Our window mapped for the first time.
1660 <li>Our window was de-iconified.
1663 You should note the implicit assumption hidden here: the
1664 contents of our window is lost when it is being obscured
1665 (covered) by either windows. One may wonder why the X server
1666 does not save this contents. The answer is: to save
1667 memory. After all, the number of windows on a display at a
1668 given time may be very large, and storing the contents of all
1669 of them might require a lot of memory. Actually, there is a
1670 way to tell the X server to store the contents of a window in
1671 special cases, as we will see later.
1674 When we get an <span class="code">Expose</span> event, we
1675 should take the event's data from the members of the following
1680 BYTE response_type; /* The type of the event, here it is XCBExpose */
1683 XCBWINDOW window; /* The Id of the window that receives the event (in case */
1684 /* our application registered for events on several windows */
1685 CARD16 x; /* The x coordinate of the top-left part of the window that needs to be redrawn */
1686 CARD16 y; /* The y coordinate of the top-left part of the window that needs to be redrawn */
1687 CARD16 width; /* The width of the part of the window that needs to be redrawn */
1688 CARD16 height; /* The height of the part of the window that needs to be redrawn */
1692 <li class="subtitle"><a name="userinput">Getting user input</a>
1694 User input traditionally comes from two sources: the mouse
1695 and the keyboard. Various event types exist to notify us of
1696 user input (a key being presses on the keyboard, a key being
1697 released on the keyboard, the mouse moving over our window,
1698 the mouse entering (or leaving) our window, and so on.
1701 <li class="subsubtitle"><a name="mousepressrelease">Mouse button press and release events</a>
1703 The first event type we will deal with is a mouse
1704 button-press (or button-release) event in our window. In
1705 order to register to such an event type, we should add one
1706 (or more) of the following masks when we create our window:
1709 <li><span class="code">XCBEventMaskButtonPress</span>: notify us
1710 of any button that was pressed in one of our windows.
1711 <li><span class="code">XCBEventMaskButtonRelease</span>: notify us
1712 of any button that was released in one of our windows.
1715 The structure to be checked for in our events loop is the
1716 same for these two events, and is the following:
1720 BYTE response_type; /* The type of the event, here it is XCBButtonPressEvent or XCBButtonReleaseEvent */
1723 XCBTIMESTAMP time; /* Time, in milliseconds the event took place in */
1729 INT16 event_x; /* The x coordinate where the mouse has been pressed in the window */
1730 INT16 event_y; /* The y coordinate where the mouse has been pressed in the window */
1731 CARD16 state; /* A mask of the buttons (or keys) during the event */
1733 } XCBButtonPressEvent;
1735 typedef XCBButtonPressEvent XCBButtonReleaseEvent;
1738 The <span class="code">time</span> field may be used to calculate "double-click"
1739 situations by an application (e.g. if the mouse button was
1740 clicked two times in a duration shorter than a given amount
1741 of time, assume this was a double click).
1744 The <span class="code">state</span> field is a mask of the buttons held down during
1745 the event. It is a bitwise OR of any of the following (from the XCBButtonMask and
1746 XCBModMask enumerations):
1749 <li><span class="code">XCBButtonMask1</span>
1750 <li><span class="code">XCBButtonMask2</span>
1751 <li><span class="code">XCBButtonMask3</span>
1752 <li><span class="code">XCBButtonMask4</span>
1753 <li><span class="code">XCBButtonMask5</span>
1754 <li><span class="code">XCBModMaskShift</span>
1755 <li><span class="code">XCBModMaskLock</span>
1756 <li><span class="code">XCBModMaskControl</span>
1757 <li><span class="code">XCBModMask1</span>
1758 <li><span class="code">XCBModMask2</span>
1759 <li><span class="code">XCBModMask3</span>
1760 <li><span class="code">XCBModMask4</span>
1761 <li><span class="code">XCBModMask5</span>
1764 Their names are self explanatory, where the first 5 refer to
1765 the mouse buttons that are being pressed, while the rest
1766 refer to various "special keys" that are being pressed (Mod1
1767 is usually the 'Alt' key or the 'Meta' key).
1770 <b>TODO:</b> Problem: it seems that the state does not
1771 change when clicking with various buttons.
1773 <li class="subsubtitle"><a name="mousemvnt">Mouse movement events</a>
1775 Similar to mouse button press and release events, we also
1776 can be notified of various mouse movement events. These can
1777 be split into two families. One is of mouse pointer
1778 movement while no buttons are pressed, and the second is a
1779 mouse pointer motion while one (or more) of the buttons are
1780 pressed (this is sometimes called "a mouse drag operation",
1781 or just "dragging"). The following event masks may be added
1782 during the creation of our window:
1785 <li><span class="code">XCBEventMaskPointerMotion</span>: events of
1786 the pointer moving in one of the windows controlled by our
1787 application, while no mouse button is held pressed.
1788 <li><span class="code">XCBEventMaskButtonMotion</span>: Events of
1789 the pointer moving while one or more of the mouse buttons
1791 <li><span class="code">XCBEventMaskButton1Motion</span>: same as
1792 <span class="code">XCBEventMaskButtonMotion</span>, but only when
1793 the 1st mouse button is held pressed.
1794 <li><span class="code">XCBEventMaskButton2Motion</span>,
1795 <span class="code">XCBEventMaskButton3Motion</span>,
1796 <span class="code">XCBEventMaskButton4Motion</span>,
1797 <span class="code">XCBEventMaskButton5Motion</span>: same as
1798 <span class="code">XCBEventMaskButton1Motion</span>, but
1799 respectively for 2nd, 3rd, 4th and 5th mouse button.
1802 The structure to be checked for in our events loop is the
1803 same for these events, and is the following:
1807 BYTE response_type; /* The type of the event */
1810 XCBTIMESTAMP time; /* Time, in milliseconds the event took place in */
1816 INT16 event_x; /* The x coordinate of the mouse when the event was generated */
1817 INT16 event_y; /* The y coordinate of the mouse when the event was generated */
1818 CARD16 state; /* A mask of the buttons (or keys) during the event */
1820 } XCBMotionNotifyEvent;
1822 <li class="subsubtitle"><a name="mouseenter">Mouse pointer enter and leave events</a>
1824 Another type of event that applications might be interested
1825 in, is a mouse pointer entering a window the program
1826 controls, or leaving such a window. Some programs use these
1827 events to show the user that the application is now in
1828 focus. In order to register for such an event type, we
1829 should add one (or more) of the following masks when we
1833 <li><span class="code">XCBEventEnterWindow</span>: notify us
1834 when the mouse pointer enters any of our controlled
1836 <li><span class="code">XCBEventLeaveWindow</span>: notify us
1837 when the mouse pointer leaves any of our controlled
1841 The structure to be checked for in our events loop is the
1842 same for these two events, and is the following:
1846 BYTE response_type; /* The type of the event */
1849 XCBTIMESTAMP time; /* Time, in milliseconds the event took place in */
1855 INT16 event_x; /* The x coordinate of the mouse when the event was generated */
1856 INT16 event_y; /* The y coordinate of the mouse when the event was generated */
1857 CARD16 state; /* A mask of the buttons (or keys) during the event */
1858 BYTE mode; /* The number of mouse button that was clicked */
1859 BYTE same_screen_focus;
1860 } XCBEnterNotifyEvent;
1862 typedef XCBEnterNotifyEvent XCBLeaveNotifyEvent;
1864 <li class="subsubtitle"><a name="focus">The keyboard focus</a>
1866 There may be many windows on a screen, but only a single
1867 keyboard attached to them. How does the X server then know
1868 which window should be sent a given keyboard input ? This is
1869 done using the keyboard focus. Only a single window on the
1870 screen may have the keyboard focus at a given time. There
1871 is a XCB function that allows a program to set the keyboard
1872 focus to a given window. The user can usually set the
1873 keyboard focus using the window manager (often by clicking
1874 on the title bar of the desired window). Once our window
1875 has the keyboard focus, every key press or key release will
1876 cause an event to be sent to our program (if it regsitered
1877 for these event types...).
1879 <li class="subsubtitle"><a name="keypress">Keyboard press and release events</a>
1881 If a window controlled by our program currently holds the
1882 keyboard focus, it can receive key press and key release
1883 events. So, we should add one (or more) of the following
1884 masks when we create our window:
1887 <li><span class="code">XCBEventMaskKeyPress</span>: notify us when
1888 a key was pressed while any of our controlled windows had
1890 <li><span class="code">XCBEventMaskKeyRelease</span>: notify us
1891 when a key was released while any of our controlled
1892 windows had the keyboard focus.
1895 The structure to be checked for in our events loop is the
1896 same for these two events, and is the following:
1900 BYTE response_type; /* The type of the event */
1903 XCBTIMESTAMP time; /* Time, in milliseconds the event took place in */
1915 typedef XCBKeyPressEvent XCBKeyReleaseEvent;
1918 The <span class="code">detail</span> field refers to the
1919 physical key on the keyboard.
1922 <b>TODO:</b> Talk about getting the ASCII code from the key code.
1925 <li class="subtitle"><a name="eventex">X events: a complete example</a>
1927 As an example for handling events, we show a program that
1928 creates a window, enters an events loop and checks for all the
1929 events described above, and writes on the terminal the relevant
1930 characteristics of the event. With this code, it should be
1931 easy to add drawing operations, like those which have been
1935 #include <stdlib.h>
1936 #include <stdio.h>
1938 #include <X11/XCB/xcb.h>
1941 print_modifiers(CARD32 mask)
1943 const char **mod, *mods[] = {
1944 "Shift", "Lock", "Ctrl", "Alt",
1945 "Mod2", "Mod3", "Mod4", "Mod5",
1946 "Button1", "Button2", "Button3", "Button4", "Button5"
1948 printf("Modifier mask: ");
1949 for (mod = mods ; mask; mask >>= 1, mod++)
1956 main (int argc, char *argv[])
1965 /* Open the connection to the X server */
1966 c = XCBConnect (NULL, NULL);
1968 /* Get the first screen */
1969 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
1971 /* Ask for our window's Id */
1972 win.window = XCBWINDOWNew(c);
1974 /* Create the window */
1975 mask = XCBCWBackPixel | XCBCWEventMask;
1976 values[0] = screen->white_pixel;
1977 values[1] = XCBEventMaskExposure | XCBEventMaskButtonPress
1978 | XCBEventMaskButtonRelease | XCBEventMaskPointerMotion
1979 | XCBEventMaskEnterWindow | XCBEventMaskLeaveWindow
1980 | XCBEventMaskKeyPress | XCBEventMaskKeyRelease;
1981 XCBCreateWindow (c, /* Connection */
1983 win.window, /* window Id */
1984 screen->root, /* parent window */
1986 150, 150, /* width, height */
1987 10, /* border_width */
1988 XCBWindowClassInputOutput,/* class */
1989 screen->root_visual, /* visual */
1990 mask, values); /* masks */
1992 /* Map the window on the screen */
1993 XCBMapWindow (c, win.window);
1997 while ((e = XCBWaitForEvent (c)))
1999 switch (e->response_type & ~0x80)
2003 XCBExposeEvent *ev = (XCBExposeEvent *)e;
2005 printf ("Window %ld exposed. Region to be redrawn at location (%d,%d), with dimension (%d,%d)\n",
2006 ev->window.xid, ev->x, ev->y, ev->width, ev->height);
2009 case XCBButtonPress:
2011 XCBButtonPressEvent *ev = (XCBButtonPressEvent *)e;
2012 print_modifiers(ev->state);
2014 switch (ev->detail.id)
2018 printf ("Wheel Button up in window %ld, at coordinates (%d,%d)\n",
2019 ev->event.xid, ev->event_x, ev->event_y);
2024 printf ("Wheel Button down in window %ld, at coordinates (%d,%d)\n",
2025 ev->event.xid, ev->event_x, ev->event_y);
2029 printf ("Button %d pressed in window %ld, at coordinates (%d,%d)\n",
2030 ev->detail.id, ev->event.xid, ev->event_x, ev->event_y);
2034 case XCBButtonRelease:
2036 XCBButtonReleaseEvent *ev = (XCBButtonReleaseEvent *)e;
2037 print_modifiers(ev->state);
2039 printf ("Button %d released in window %ld, at coordinates (%d,%d)\n",
2040 ev->detail.id, ev->event.xid, ev->event_x, ev->event_y);
2043 case XCBMotionNotify:
2045 XCBMotionNotifyEvent *ev = (XCBMotionNotifyEvent *)e;
2047 printf ("Mouse moved in window %ld, at coordinates (%d,%d)\n",
2048 ev->event.xid, ev->event_x, ev->event_y);
2051 case XCBEnterNotify:
2053 XCBEnterNotifyEvent *ev = (XCBEnterNotifyEvent *)e;
2055 printf ("Mouse entered window %ld, at coordinates (%d,%d)\n",
2056 ev->event.xid, ev->event_x, ev->event_y);
2059 case XCBLeaveNotify:
2061 XCBLeaveNotifyEvent *ev = (XCBLeaveNotifyEvent *)e;
2063 printf ("Mouse left window %ld, at coordinates (%d,%d)\n",
2064 ev->event.xid, ev->event_x, ev->event_y);
2069 XCBKeyPressEvent *ev = (XCBKeyPressEvent *)e;
2070 print_modifiers(ev->state);
2072 printf ("Key pressed in window %ld\n",
2078 XCBKeyReleaseEvent *ev = (XCBKeyReleaseEvent *)e;
2079 print_modifiers(ev->state);
2081 printf ("Key released in window %ld\n",
2087 /* Unknown event type, ignore it */
2088 printf("Unknown event: %d\n", e->response_type);
2092 /* Free the Generic Event */
2100 <li class="title"><a name="font">Handling text and fonts</a>
2102 Besides drawing graphics on a window, we often want to draw
2103 text. Text strings have two major properties: the characters to
2104 be drawn and the font with which they are drawn. In order to
2105 draw text, we need to first request the X server to load a
2106 font. We then assign a font to a Graphic Context, and finally, we
2107 draw the text in a window, using the Graphic Context.
2110 <li class="subtitle"><a name="fontstruct">The Font structure</a>
2112 In order to support flexible fonts, a font structure is
2113 defined. You know what ? It's an Id:
2121 It is used to contain information about a font, and is passed
2122 to several functions that handle fonts selection and text drawing.
2125 <b>TODO:</b> example for picking a font and displaying some text.
2126 Even better, also demonstrate translating keypresses to text.
2129 <li class="title"><a name="wm">Interacting with the window manager</a>
2131 After we have seen how to create windows and draw on them, we
2132 take one step back, and look at how our windows are interacting
2133 with their environment (the full screen and the other
2134 windows). First of all, our application needs to interact with
2135 the window manager. The window manager is responsible to
2136 decorating drawn windows (i.e. adding a frame, an iconify
2137 button, a system menu, a title bar, etc), as well as handling
2138 icons shown when windows are being iconified. It also handles
2139 ordering of windows on the screen, and other administrative
2140 tasks. We need to give it various hints as to how we want it to
2141 treat our application's windows.
2144 <li class="subtitle"><a name="wmprop">Window properties</a>
2146 Many of the parameters communicated to the window manager are
2147 passed using data called "properties". These properties are
2148 attached by the X server to different windows, and are stored
2149 in a format that makes it possible to read them from different
2150 machines that may use different architectures (remember that
2151 an X client program may run on a remote machine).
2154 The property and its type (a string, an integer, etc) are
2155 Id. Their type are <span class="code">XCBATOM</span>:
2163 To change the property of a window, we use the following
2167 XCBVoidCookie XCBChangeProperty (XCBConnection *c, /* Connection to the X server */
2168 CARD8 mode, /* Property mode */
2169 XCBWINDOW window, /* Window */
2170 XCBATOM property, /* Property to change */
2171 XCBATOM type, /* Type of the property */
2172 CARD8 format, /* Format of the property (8, 16, 32) */
2173 CARD32 data_len, /* Length of the data parameter */
2174 const void *data); /* Data */
2177 The <span class="code">mode</span> parameter coud be one of
2178 the following values (defined in enumeration XCBPropMode in
2179 the xproto.h header file):
2182 <li>XCBPropModeReplace
2183 <li>XCBPropModePrepend
2184 <li>XCBPropModeAppend
2187 <li class="subtitle"><a name="wmname">Setting the window name and icon name</a>
2189 The first thing we want to do would be to set the name for our
2190 window. This is done using the
2191 <span class="code">XCBChangeProperty()</span> function. This
2192 name may be used by the window manager as the title of the
2193 window (in the title bar), in a task list, etc. The property
2194 atom to use to set the name of a window is
2195 <span class="code">WM_NAME</span> (and
2196 <span class="code">WM_ICON_NAME</span> for the iconified
2197 window) and its type is <span class="code">STRING</span>. Here
2198 is an example of utilization:
2201 #include <string.h>
2203 #include <X11/XCB/xcb.h>
2204 #include <X11/XCB/xcb_atom.h>
2207 main (int argc, char *argv[])
2212 char *title = "Hello World !";
2213 char *title_icon = "Hello World ! (iconified)";
2217 /* Open the connection to the X server */
2218 c = XCBConnect (NULL, NULL);
2220 /* Get the first screen */
2221 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
2223 /* Ask for our window's Id */
2224 win.window = XCBWINDOWNew(c);
2226 /* Create the window */
2227 XCBCreateWindow (c, /* Connection */
2229 win.window, /* window Id */
2230 screen->root, /* parent window */
2232 250, 150, /* width, height */
2233 10, /* border_width */
2234 XCBWindowClassInputOutput,/* class */
2235 screen->root_visual, /* visual */
2236 0, NULL); /* masks, not used */
2238 /* Set the title of the window */
2239 XCBChangeProperty(c, XCBPropModeReplace, win.window,
2241 strlen(title), title);
2243 /* Set the title of the window icon */
2244 XCBChangeProperty(c, XCBPropModeReplace, win.window,
2245 WM_ICON_NAME, STRING, 8,
2246 strlen(title_icon), title_icon);
2248 /* Map the window on the screen */
2249 XCBMapWindow (c, win.window);
2259 <p>Note: the use of the atoms needs our program to be compiled
2260 and linked against xcb_atom, so that we have to use
2264 gcc prog.c -o prog `pkg-config --cflags --libs xcb_atom`
2268 for the program to compile fine.
2272 <li class="title"><a name="winop">Simple window operations</a>
2274 One more thing we can do to our window is manipulate them on the
2275 screen (resize them, move them, raise or lower them, iconify
2276 them, and so on). Some window operations functions are supplied
2277 by XCB for this purpose.
2280 <li class="subtitle"><a name="winmap">Mapping and un-mapping a window</a>
2282 The first pair of operations we can apply on a window is
2283 mapping it, or un-mapping it. Mapping a window causes the
2284 window to appear on the screen, as we have seen in our simple
2285 window program example. Un-mapping it causes it to be removed
2286 from the screen (although the window as a logical entity still
2287 exists). This gives the effect of making a window hidden
2288 (unmapped) and shown again (mapped). For example, if we have a
2289 dialog box window in our program, instead of creating it every
2290 time the user asks to open it, we can create the window once,
2291 in an un-mapped mode, and when the user asks to open it, we
2292 simply map the window on the screen. When the user clicked the
2293 'OK' or 'Cancel' button, we simply un-map the window. This is
2294 much faster than creating and destroying the window, however,
2295 the cost is wasted resources, both on the client side, and on
2299 To map a window, you use the following function:
2302 XCBVoidCookie XCBMapWindow(XCBConnection *c, XCBWINDOW window);
2305 To have a simple example, see the <a href="#helloworld">example</a>
2306 above. The mapping operation will cause an
2307 <span class="code">Expose</span> event to be sent to our
2308 application, unless the window is completely covered by other
2312 Un-mapping a window is also simple. You use the function
2315 XCBVoidCookie XCBUnmapWindow(XCBConnection *c, XCBWINDOW window);
2318 The utilization of this function is the same as
2319 <span class="code">XCBMapWindow()</span>.
2321 <li class="subtitle"><a name="winconf">Configuring a window</a>
2323 As we have seen when we have created our first window, in the
2324 X Events subsection, we can set some attributes for the window
2325 (that is, the position, the size, the events the window will
2326 receive, etc). If we want to modify them, but the window is
2327 already created, we can change them by using the following
2331 XCBVoidCookie XCBConfigureWindow (XCBConnection *c, /* The connection to the X server*/
2332 XCBWINDOW window, /* The window to configure */
2333 CARD16 value_mask, /* The mask */
2334 const CARD32 *value_list); /* The values to set */
2337 We set the <span class="code">value_mask</span> to one or
2338 several mask values that are in the XCBConfigWindow enumeration in the xproto.h header:
2341 <li><span class="code">XCBConfigWindowX</span>: new x coordinate of the window's top left corner
2342 <li><span class="code">XCBConfigWindowY</span>: new y coordinate of the window's top left corner
2343 <li><span class="code">XCBConfigWindowWidth</span>: new width of the window
2344 <li><span class="code">XCBConfigWindowHeight</span>: new height of the window
2345 <li><span class="code">XCBConfigWindowBorderWidth</span>: new width of the border of the window
2346 <li><span class="code">XCBConfigWindowSibling</span>
2347 <li><span class="code">XCBConfigWindowStackMode</span>: the new stacking order
2350 We then give to <span class="code">value_mask</span> the new
2351 value. We now describe how to use
2352 <span class="code">XCBConfigureWindow</span> in some useful
2355 <li class="subtitle"><a name="winmove">Moving a window around the screen</a>
2357 An operation we might want to do with windows is to move them
2358 to a different location. This can be done like this:
2361 const static CARD32 values[] = { 10, 20 };
2363 /* The connection c and the window win are supposed to be defined */
2365 /* Move the window to coordinates x = 10 and y = 20 */
2366 XCBConfigureWindow (c, win, XCBConfigWindowX | XCBConfigWindowY, values);
2369 Note that when the window is moved, it might get partially
2370 exposed or partially hidden by other windows, and thus we
2371 might get <span class="code">Expose</span> events due to this
2374 <li class="subtitle"><a name="winsize">Resizing a window</a>
2376 Yet another operation we can do is to change the size of a
2377 window. This is done using the following code:
2380 const static CARD32 values[] = { 200, 300 };
2382 /* The connection c and the window win are supposed to be defined */
2384 /* Resize the window to width = 10 and height = 20 */
2385 XCBConfigureWindow (c, win, XCBConfigWindowWidth | XCBConfigWindowHeight, values);
2388 We can also combine the move and resize operations using one
2389 single call to <span class="code">XCBConfigureWindow</span>:
2392 const static CARD32 values[] = { 10, 20, 200, 300 };
2394 /* The connection c and the window win are supposed to be defined */
2396 /* Move the window to coordinates x = 10 and y = 20 */
2397 /* and resize the window to width = 10 and height = 20 */
2398 XCBConfigureWindow (c, win, XCBConfigWindowX | XCBConfigWindowY | XCBConfigWindowWidth | XCBConfigWindowHeight, values);
2400 <li class="subtitle"><a name="winstack">Changing windows stacking order: raise and lower</a>
2402 Until now, we changed properties of a single window. We'll see
2403 that there are properties that relate to the window and other
2404 windows. One of them is the stacking order. That is, the order
2405 in which the windows are layered on top of each other. The
2406 front-most window is said to be on the top of the stack, while
2407 the back-most window is at the bottom of the stack. Here is
2408 how to manipulate our windows stack order:
2411 const static CARD32 values[] = { XCBStackModeAbove };
2413 /* The connection c and the window win are supposed to be defined */
2415 /* Move the window on the top of the stack */
2416 XCBConfigureWindow (c, win, XCBConfigWindowStackMode, values);
2419 const static CARD32 values[] = { XCBStackModeBelow };
2421 /* The connection c and the window win are supposed to be defined */
2423 /* Move the window on the bottom of the stack */
2424 XCBConfigureWindow (c, win, XCBConfigWindowStackMode, values);
2426 <li class="subtitle"><a name="wingetinfo">Getting information about a window</a>
2428 Just like we can set various attributes of our windows, we can
2429 also ask the X server supply the current values of these
2430 attributes. For example, we can check where a window is
2431 located on the screen, what is its current size, whether it is
2432 mapped or not, etc. The structure that contains some of this
2438 CARD8 depth; /* depth of the window */
2441 XCBWINDOW root; /* Id of the root window *>
2442 INT16 x; /* X coordinate of the window's location */
2443 INT16 y; /* Y coordinate of the window's location */
2444 CARD16 width; /* Width of the window */
2445 CARD16 height; /* Height of the window */
2446 CARD16 border_width; /* Width of the window's border */
2447 } XCBGetGeometryRep;
2450 XCB fill this structure with two functions:
2453 XCBGetGeometryCookie XCBGetGeometry (XCBConnection *c,
2454 XCBDRAWABLE drawable);
2455 XCBGetGeometryRep *XCBGetGeometryReply (XCBConnection *c,
2456 XCBGetGeometryCookie cookie,
2457 XCBGenericError **e);
2460 You use them as follows:
2465 XCBGetGeometryRep *geom;
2467 /* You initialize c and win */
2469 geom = XCBGetGeometryReply (c, XCBGetGeometry (c, win), 0);
2471 /* Do something with the fields of geom */
2476 Remark that you have to free the structure, as
2477 <span class="code">XCBGetGeometryReply</span> allocates a
2481 One problem is that the returned location of the window is
2482 relative to its parent window. This makes these coordinates
2483 rather useless for any window manipulation functions, like
2484 moving it on the screen. In order to overcome this problem, we
2485 need to take a two-step operation. First, we find out the Id
2486 of the parent window of our window. We then translate the
2487 above relative coordinates to the screen coordinates.
2490 To get the Id of the parent window, we need this structure:
2499 XCBWINDOW parent; /* Id of the parent window */
2500 CARD16 children_len;
2505 To fill this structure, we use these two functions:
2508 XCBQueryTreeCookie XCBQueryTree (XCBConnection *c,
2510 XCBQueryTreeRep *XCBQueryTreeReply (XCBConnection *c,
2511 XCBQueryTreeCookie cookie,
2512 XCBGenericError **e);
2515 The translated coordinates will be found in this structure:
2524 CARD16 dst_x; /* Translated x coordinate */
2525 CARD16 dst_y; /* Translated y coordinate */
2526 } XCBTranslateCoordinatesRep;
2529 As usual, we need two functions to fill this structure:
2532 XCBTranslateCoordinatesCookie XCBTranslateCoordinates (XCBConnection *c,
2533 XCBWINDOW src_window,
2534 XCBWINDOW dst_window,
2537 XCBTranslateCoordinatesRep *XCBTranslateCoordinatesReply (XCBConnection *c,
2538 XCBTranslateCoordinatesCookie cookie,
2539 XCBGenericError **e);
2542 We use them as follows:
2547 XCBGetGeometryRep *geom;
2548 XCBQueryTreeRep *tree;
2549 XCBTranslateCoordinatesRep *trans;
2551 /* You initialize c and win */
2553 geom = XCBGetGeometryReply (c, XCBGetGeometry (c, win), 0);
2557 tree = XCBQueryTreeReply (c, XCBQueryTree (c, win), 0);
2561 trans = XCBTranslateCoordinatesReply (c,
2562 XCBTranslateCoordinates (c,
2565 geom->x, geom->y),
2570 /* the translated coordinates are in trans->dst_x and trans->dst_y */
2577 Of course, as for <span class="code">geom</span>,
2578 <span class="code">tree</span> and
2579 <span class="code">trans</span> have to be freed.
2582 The work is a bit hard, but XCB is a very low-level library.
2585 <b>TODO:</b> the utilization of these functions should be a
2586 prog, which displays the coordinates of the window.
2589 There is another structure that gives informations about our window:
2594 CARD8 backing_store;
2597 XCBVISUALID visual; /* Visual of the window */
2601 CARD32 backing_planes;
2602 CARD32 backing_pixel;
2604 BOOL map_is_installed;
2605 CARD8 map_state; /* Map state of the window */
2606 BOOL override_redirect;
2607 XCBCOLORMAP colormap; /* Colormap of the window */
2608 CARD32 all_event_masks;
2609 CARD32 your_event_mask;
2610 CARD16 do_not_propagate_mask;
2611 } XCBGetWindowAttributesRep;
2614 XCB supplies these two functions to fill it:
2617 XCBGetWindowAttributesCookie XCBGetWindowAttributes (XCBConnection *c,
2619 XCBGetWindowAttributesRep *XCBGetWindowAttributesReply (XCBConnection *c,
2620 XCBGetWindowAttributesCookie cookie,
2621 XCBGenericError **e);
2624 You use them as follows:
2629 XCBGetWindowAttributesRep *attr;
2631 /* You initialize c and win */
2633 attr = XCBGetWindowAttributesReply (c, XCBGetWindowAttributes (c, win), 0);
2638 /* Do something with the fields of attr */
2643 As for <span class="code">geom</span>,
2644 <span class="code">attr</span> has to be freed.
2647 <li class="title"><a name="usecolor">Using colors to paint the rainbow</a>
2649 Up until now, all our painting operation were done using black
2650 and white. We will (finally) see now how to draw using colors.
2653 <li class="subtitle"><a name="colormap">Color maps</a>
2655 In the beginning, there were not enough colors. Screen
2656 controllers could only support a limited number of colors
2657 simultaneously (initially 2, then 4, 16 and 256). Because of
2658 this, an application could not just ask to draw in a "light
2659 purple-red" color, and expect that color to be available. Each
2660 application allocated the colors it needed, and when all the
2661 color entries (4, 16, 256 colors) were in use, the next color
2662 allocation would fail.
2665 Thus, the notion of "a color map" was introduced. A color map
2666 is a table whose size is the same as the number of
2667 simultaneous colors a given screen controller. Each entry
2668 contained the RGB (Red, Green and Blue) values of a different
2669 color (all colors can be drawn using some combination of red,
2670 green and blue). When an application wants to draw on the
2671 screen, it does not specify which color to use. Rather, it
2672 specifies which color entry of some color map to be used
2673 during this drawing. Change the value in this color map entry
2674 and the drawing will use a different color.
2677 In order to be able to draw using colors that got something to
2678 do with what the programmer intended, color map allocation
2679 functions are supplied. You could ask to allocate entry for a
2680 color with a set of RGB values. If one already existed, you
2681 would get its index in the table. If none existed, and the
2682 table was not full, a new cell would be allocated to contain
2683 the given RGB values, and its index returned. If the table was
2684 full, the procedure would fail. You could then ask to get a
2685 color map entry with a color that is closest to the one you
2686 were asking for. This would mean that the actual drawing on
2687 the screen would be done using colors similar to what you
2688 wanted, but not the same.
2691 On today's more modern screens where one runs an X server with
2692 support for 16 million colors, this limitation looks a little
2693 silly, but remember that there are still older computers with
2694 older graphics cards out there. Using color map, support for
2695 these screen becomes transparent to you. On a display
2696 supporting 16 million colors, any color entry allocation
2697 request would succeed. On a display supporting a limited
2698 number of colors, some color allocation requests would return
2699 similar colors. It won't look as good, but your application
2702 <li class="subtitle"><a name="colormapalloc">Allocating and freeing Color Maps</a>
2704 When you draw using XCB, you can choose to use the standard
2705 color map of the screen your window is displayed on, or you
2706 can allocate a new color map and apply it to a window. In the
2707 latter case, each time the mouse moves onto your window, the
2708 screen color map will be replaced by your window's color map,
2709 and you'll see all the other windows on screen change their
2710 colors into something quite bizzare. In fact, this is the
2711 effect you get with X applications that use the "-install"
2712 command line option.
2715 In XCB, a color map is (as often in X) an Id:
2723 In order to access the screen's default color map, you just
2724 have to retrieve the <span class="code">default_colormap</span>
2725 field of the <span class="code">XCBSCREEN</span> structure
2727 <a href="#screen">Checking basic information about a connection</a>):
2730 #include <stdio.h>
2732 #include <X11/XCB/xcb.h>
2735 main (int argc, char *argv[])
2739 XCBCOLORMAP colormap;
2741 /* Open the connection to the X server and get the first screen */
2742 c = XCBConnect (NULL, NULL);
2743 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
2745 colormap = screen->default_colormap;
2751 This will return the color map used by default on the first
2752 screen (again, remember that an X server may support several
2753 different screens, each of which might have its own resources).
2756 The other option, that of allocating a new colormap, works as
2757 follows. We first ask the X server to give an Id to our color
2758 map, with this function:
2761 XCBCOLORMAP XCBCOLORMAPNew (XCBConnection *c);
2764 Then, we create the color map with
2767 XCBVoidCookie XCBCreateColormap (XCBConnection *c, /* Pointer to the XCBConnection structure */
2768 BYTE alloc, /* Colormap entries to be allocated (AllocNone or AllocAll) */
2769 XCBCOLORMAP mid, /* Id of the color map */
2770 XCBWINDOW window, /* Window on whose screen the colormap will be created */
2771 XCBVISUALID visual); /* Id of the visual supported by the screen */
2774 Here is an example of creation of a new color map:
2777 #include <X11/XCB/xcb.h>
2780 main (int argc, char *argv[])
2787 /* Open the connection to the X server and get the first screen */
2788 c = XCBConnect (NULL, NULL);
2789 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
2791 /* We create the window win here*/
2793 cmap = XCBCOLORMAPNew (c);
2794 XCBCreateColormap (c, XCBColormapAllocNone, cmap, win, screen->root_visual);
2800 Note that the window parameter is only used to allow the X
2801 server to create the color map for the given screen. We can
2802 then use this color map for any window drawn on the same screen.
2805 To free a color map, it suffices to use this function:
2808 XCBVoidCookie XCBFreeColormap (XCBConnection *c, /* The connection */
2809 XCBCOLORMAP cmap); /* The color map */
2817 <li>XCreateColormap ()
2822 <li>XCBCOLORMAPNew ()
2823 <li>XCBCreateColormap ()
2828 <li>XFreeColormap ()
2833 <li>XCBFreeColormap ()
2838 <li class="subtitle"><a name="alloccolor">Allocating and freeing a color entry</a>
2840 Once we got access to some color map, we can start allocating
2841 colors. The informations related to a color are stored in the
2842 following structure:
2850 CARD16 red; /* The red component */
2851 CARD16 green; /* The green component */
2852 CARD16 blue; /* The blue component */
2854 CARD32 pixel; /* The entry in the color map, supplied by the X server */
2858 XCB supplies these two functions to fill it:
2861 XCBAllocColorCookie XCBAllocColor (XCBConnection *c,
2866 XCBAllocColorRep *XCBAllocColorReply (XCBConnection *c,
2867 XCBAllocColorCookie cookie,
2868 XCBGenericError **e);
2871 The fuction <span class="code">XCBAllocColor()</span> takes the
2872 3 RGB components as parameters (red, green and blue). Here is an
2873 example of using these functions:
2876 #include <malloc.h>
2878 #include <X11/XCB/xcb.h>
2881 main (int argc, char *argv[])
2887 XCBAllocColorRep *rep;
2889 /* Open the connection to the X server and get the first screen */
2890 c = XCBConnect (NULL, NULL);
2891 screen = XCBSetupRootsIter (XCBGetSetup (c)).data;
2893 /* We create the window win here*/
2895 cmap = XCBCOLORMAPNew (c);
2896 XCBCreateColormap (c, XCBColormapAllocNone, cmap, win, screen->root_visual);
2898 rep = XCBAllocColorReply (c, XCBAllocColor (c, cmap, 65535, 0, 0), 0);
2903 /* Do something with r->pixel or the components */
2911 As <span class="code">XCBAllocColorReply()</span> allocates
2912 memory, you have to free <span class="code">rep</span>.
2915 <b>TODO</b>: Talk about freeing colors.
2918 <li class="title"><a name="pixmaps">X Bitmaps and Pixmaps</a>
2920 One thing many so-called "Multi-Media" applications need to do,
2921 is display images. In the X world, this is done using bitmaps
2922 and pixmaps. We have already seen some usage of them when
2923 setting an icon for our application. Lets study them further,
2924 and see how to draw these images inside a window, along side the
2925 simple graphics and text we have seen so far.
2928 One thing to note before delving further, is that XCB (nor Xlib)
2929 supplies no means of manipulating popular image formats, such as
2930 gif, png, jpeg or tiff. It is up to the programmer (or to higher
2931 level graphics libraries) to translate these image formats into
2932 formats that the X server is familiar with (x bitmaps and x
2936 <li class="subtitle"><a name="pixmapswhat">What is a X Bitmap? An X Pixmap?</a>
2938 An X bitmap is a two-color image stored in a format specific
2939 to the X window system. When stored in a file, the bitmap data
2940 looks like a C source file. It contains variables defining the
2941 width and the height of the bitmap, an array containing the
2942 bit values of the bitmap (the size of the array is
2943 (width+7)/8*height and the bit and byte order are LSB), and
2944 an optional hot-spot location (that will
2945 be explained later, when discussing mouse cursors).
2948 An X pixmap is a format used to stored images in the memory of
2949 an X server. This format can store both black and white images
2950 (such as x bitmaps) as well as color images. It is the only
2951 image format supported by the X protocol, and any image to be
2952 drawn on screen, should be first translated into this format.
2955 In actuality, an X pixmap can be thought of as a window that
2956 does not appear on the screen. Many graphics operations that
2957 work on windows, will also work on pixmaps. Indeed, the type
2958 of X pixmap in XCB is an Id like a window:
2966 In order to make the difference between a window and a pixmap,
2967 XCB introduces a drawable type, which is a <b>union</b>
2976 in order to avoid confusion between a window and a pixmap. The
2977 operations that will work the same on a window or a pixmap
2978 will require a <span class="code">XCBDRAWABLE</span>
2982 Remark: In Xlib, there is no specific difference between a
2983 <span class="code">Drawable</span>, a
2984 <span class="code">Pixmap</span> or a
2985 <span class="code">Window</span>: all are 32 bit long
2986 integer. XCB wraps all these different IDs in structures to
2987 provide some measure of type-safety.
2990 <li class="subtitle"><a name="pixmapscreate">Creating a pixmap</a>
2992 Sometimes we want to create an un-initialized pixmap, so we
2993 can later draw into it. This is useful for image drawing
2994 programs (creating a new empty canvas will cause the creation
2995 of a new pixmap on which the drawing can be stored). It is
2996 also useful when reading various image formats: we load the
2997 image data into memory, create a pixmap on the server, and
2998 then draw the decoded image data onto that pixmap.
3001 To create a new pixmap, we first ask the X server to give an
3002 Id to our pixmap, with this function:
3005 XCBPIXMAP XCBPIXMAPNew (XCBConnection *c);
3008 Then, XCB supplies the following function to create new pixmaps:
3011 XCBVoidCookie XCBCreatePixmap (XCBConnection *c, /* Pointer to the XCBConnection structure */
3012 CARD8 depth, /* Depth of the screen */
3013 XCBPIXMAP pid, /* Id of the pixmap */
3014 XCBDRAWABLE drawable,
3015 CARD16 width, /* Width of the window (in pixels) */
3016 CARD16 height); /* Height of the window (in pixels) */
3019 <b>TODO</b>: Explain the drawable parameter, and give an
3020 example (like <a href="xpoints.c">xpoints.c</a>)
3022 <li class="subtitle"><a name="pixmapsdraw"></a>Drawing a pixmap in a window
3024 Once we got a handle to a pixmap, we can draw it on some
3025 window, using the following function:
3028 XCBVoidCookie XCBCopyArea (XCBConnection *c, /* Pointer to the XCBConnection structure */
3029 XCBDRAWABLE src_drawable, /* The Drawable we want to paste */
3030 XCBDRAWABLE dst_drawable, /* The Drawable on which we copy the previous Drawable */
3031 XCBGCONTEXT gc, /* A Graphic Context */
3032 INT16 src_x, /* Top left x coordinate of the region we want to copy */
3033 INT16 src_y, /* Top left y coordinate of the region we want to copy */
3034 INT16 dst_x, /* Top left x coordinate of the region where we want to copy */
3035 INT16 dst_y, /* Top left y coordinate of the region where we want to copy */
3036 CARD16 width, /* Width of the region we want to copy */
3037 CARD16 height); /* Height of the region we want to copy */
3040 As you can see, we could copy the whole pixmap, as well as
3041 only a given rectangle of the pixmap. This is useful to
3042 optimize the drawing speed: we could copy only what we have
3043 modified in the pixmap.
3046 <b>One important note should be made</b>: it is possible to
3047 create pixmaps with different depths on the same screen. When
3048 we perform copy operations (a pixmap onto a window, etc), we
3049 should make sure that both source and target have the same
3050 depth. If they have a different depth, the operation would
3051 fail. The exception to this is if we copy a specific bit plane
3052 of the source pixmap using the
3053 <span class="code">XCBCopyPlane</span> function. In such an
3054 event, we can copy a specific plane to the target window (in
3055 actuality, setting a specific bit in the color of each pixel
3056 copied). This can be used to generate strange graphic effects
3057 in a window, but that is beyond the scope of this tutorial.
3059 <li class="subtitle"><a name="pixmapsfree"></a>Freeing a pixmap
3061 Finally, when we are done using a given pixmap, we should free
3062 it, in order to free resources of the X server. This is done
3063 using this function:
3066 XCBVoidCookie XCBFreePixmap (XCBConnection *c, /* Pointer to the XCBConnection structure */
3067 XCBPIXMAP pixmap); /* A given pixmap */
3070 Of course, after having freed it, we must not try accessing
3074 <b>TODO</b>: Give an example, or a link to xpoints.c
3077 <li class="title"><a name="translation">Translation of basic Xlib functions and macros</a>
3079 The problem when you want to port an Xlib program to XCB is that
3080 you don't know if the Xlib function that you want to "translate"
3081 is a X Window one or an Xlib macro. In that section, we describe
3082 a way to translate the usual functions or macros that Xlib
3083 provides. It's usually just a member of a structure.
3086 <li class="subtitle"><a name="displaystructure">Members of the Display structure</a>
3087 In this section, we look at how to translate the macros that
3088 return some members of the <span class="code">Display</span>
3089 structure. They are obtained by using a function that requires a
3090 <span class="code">XCBConnection *</span> or a member of the
3091 <span class="code">XCBSetup</span> structure
3092 (via the function <span class="code">XCBGetSetup</span>), or
3093 a function that requires that structure.
3095 <li class="subtitle"><a name="ConnectionNumber">ConnectionNumber</a>
3097 This number is the file descriptor that connects the client
3098 to the server. You just have to use that function:
3101 int XCBGetFileDescriptor(XCBConnection *c);
3103 <li class="subtitle"><a name="DefaultScreen"></a>DefaultScreen
3105 That number is not stored by XCB. It is returned in the
3106 second parameter of the function <span class="code"><a href="#openconn">XCBConnect</a></span>.
3107 Hence, you have to store it yourself if you want to use
3108 it. Then, to get the <span class="code">XCBSCREEN</span>
3109 structure, you have to iterate on the screens.
3110 The equivalent function of the Xlib's
3111 <span class="code">ScreenOfDisplay</span> function can be
3112 found <a href="#ScreenOfDisplay">below</a>. This is also provided in the
3113 XCBAux library as <span class="code">XCBAuxGetScreen()</span>. OK, here is the
3114 small piece of code to get that number:
3118 int screen_default_nbr;
3120 /* you pass the name of the display you want to XCBConnect */
3122 c = XCBConnect (display_name, &screen_default_nbr);
3124 /* screen_default_nbr contains now the number of the default screen */
3126 <li class="subtitle"><a name="QLength"></a>QLength
3131 However, this points out a basic difference in philosophy between
3132 Xlib and XCB. Xlib has several functions for filtering and
3133 manipulating the incoming and outgoing X message queues. XCB
3134 wishes to hide this as much as possible from the user, which
3135 allows for more freedom in implementation strategies.
3137 <li class="subtitle"><a name="ScreenCount"></a>ScreenCount
3139 You get the count of screens with the functions
3140 <span class="code">XCBGetSetup</span>
3142 <span class="code">XCBSetupRootsIter</span>
3143 (if you need to iterate):
3149 /* you init the connection */
3151 screen_count = XCBSetupRootsIter (XCBGetSetup (c)).rem;
3153 /* screen_count contains now the count of screens */
3156 If you don't want to iterate over the screens, a better way
3157 to get that number is to use
3158 <span class="code">XCBSetupRootsLength</span>:
3164 /* you init the connection */
3166 screen_count = XCBSetupRootsLength (XCBGetSetup (c));
3168 /* screen_count contains now the count of screens */
3170 <li class="subtitle"><a name="ServerVendor"></a>ServerVendor
3172 You get the name of the vendor of the server hardware with
3173 the functions <span class="code">XCBGetSetup</span>
3176 class="code">XCBSetupVendor</span>. Beware
3177 that, unlike Xlib, the string returned by XCB is not
3178 necessarily null-terminaled:
3182 char *vendor = NULL;
3185 /* you init the connection */
3186 length = XCBSetupVendorLength (XCBGetSetup (c));
3187 vendor = (char *)malloc (length + 1);
3189 memcpy (vendor, XCBSetupVendor (XCBGetSetup (c)), length);
3190 vendor[length] = '\0';
3192 /* vendor contains now the name of the vendor. Must be freed when not used anymore */
3194 <li class="subtitle"><a name="ProtocolVersion"></a>ProtocolVersion
3196 You get the major version of the protocol in the
3197 <span class="code">XCBSetup</span>
3198 structure, with the function <span class="code">XCBGetSetup</span>:
3202 CARD16 protocol_major_version;
3204 /* you init the connection */
3206 protocol_major_version = XCBGetSetup (c)->protocol_major_version;
3208 /* protocol_major_version contains now the major version of the protocol */
3210 <li class="subtitle"><a name="ProtocolRevision"></a>ProtocolRevision
3212 You get the minor version of the protocol in the
3213 <span class="code">XCBSetup</span>
3214 structure, with the function <span class="code">XCBGetSetup</span>:
3218 CARD16 protocol_minor_version;
3220 /* you init the connection */
3222 protocol_minor_version = XCBGetSetup (c)->protocol_minor_version;
3224 /* protocol_minor_version contains now the minor version of the protocol */
3226 <li class="subtitle"><a name="VendorRelease"></a>VendorRelease
3228 You get the number of the release of the server hardware in the
3229 <span class="code">XCBSetup</span>
3230 structure, with the function <span class="code">XCBGetSetup</span>:
3234 CARD32 release_number;
3236 /* you init the connection */
3238 release_number = XCBGetSetup (c)->release_number;
3240 /* release_number contains now the number of the release of the server hardware */
3242 <li class="subtitle"><a name="DisplayString"></a>DisplayString
3244 The name of the display is not stored in XCB. You have to
3245 store it by yourself.
3247 <li class="subtitle"><a name="BitmapUnit"></a>BitmapUnit
3249 You get the bitmap scanline unit in the
3250 <span class="code">XCBSetup</span>
3251 structure, with the function <span class="code">XCBGetSetup</span>:
3255 CARD8 bitmap_format_scanline_unit;
3257 /* you init the connection */
3259 bitmap_format_scanline_unit = XCBGetSetup (c)->bitmap_format_scanline_unit;
3261 /* bitmap_format_scanline_unit contains now the bitmap scanline unit */
3263 <li class="subtitle"><a name="BitmapBitOrder"></a>BitmapBitOrder
3265 You get the bitmap bit order in the
3266 <span class="code">XCBSetup</span>
3267 structure, with the function <span class="code">XCBGetSetup</span>:
3271 CARD8 bitmap_format_bit_order;
3273 /* you init the connection */
3275 bitmap_format_bit_order = XCBGetSetup (c)->bitmap_format_bit_order;
3277 /* bitmap_format_bit_order contains now the bitmap bit order */
3279 <li class="subtitle"><a name="BitmapPad"></a>BitmapPad
3281 You get the bitmap scanline pad in the
3282 <span class="code">XCBSetup</span>
3283 structure, with the function <span class="code">XCBGetSetup</span>:
3287 CARD8 bitmap_format_scanline_pad;
3289 /* you init the connection */
3291 bitmap_format_scanline_pad = XCBGetSetup (c)->bitmap_format_scanline_pad;
3293 /* bitmap_format_scanline_pad contains now the bitmap scanline pad */
3295 <li class="subtitle"><a name="ImageByteOrder"></a>ImageByteOrder
3297 You get the image byte order in the
3298 <span class="code">XCBSetup</span>
3299 structure, with the function <span class="code">XCBGetSetup</span>:
3303 CARD8 image_byte_order;
3305 /* you init the connection */
3307 image_byte_order = XCBGetSetup (c)->image_byte_order;
3309 /* image_byte_order contains now the image byte order */
3312 <li class="subtitle"><a name="screenofdisplay">ScreenOfDisplay related functions</a>
3314 in Xlib, <span class="code">ScreenOfDisplay</span> returns a
3315 <span class="code">Screen</span> structure that contains
3316 several characteristics of your screen. XCB has a similar
3317 structure (<span class="code">XCBSCREEN</span>),
3318 but the way to obtain it is a bit different. With
3319 Xlib, you just provide the number of the screen and you grab it
3320 from an array. With XCB, you iterate over all the screens to
3321 obtain the one you want. The complexity of this operation is
3322 O(n). So the best is to store this structure if you use
3323 it often. See <a href="#ScreenOfDisplay">ScreenOfDisplay</a> just below.
3326 Xlib provides generally two functions to obtain the characteristics
3327 related to the screen. One with the display and the number of
3328 the screen, which calls <span class="code">ScreenOfDisplay</span>,
3329 and the other that uses the <span class="code">Screen</span> structure.
3330 This might be a bit confusing. As mentioned above, with XCB, it
3331 is better to store the <span class="code">XCBSCREEN</span>
3332 structure. Then, you have to read the members of this
3333 structure. That's why the Xlib functions are put by pairs (or
3334 more) as, with XCB, you will use the same code.
3337 <li class="subtitle"><a name="ScreenOfDisplay">ScreenOfDisplay</a>
3339 This function returns the Xlib <span class="code">Screen</span>
3340 structure. With XCB, you iterate over all the screens and
3341 once you get the one you want, you return it:
3343 <pre class="code"><a name="ScreenOfDisplay"></a>
3344 XCBSCREEN *ScreenOfDisplay (XCBConnection *c,
3349 iter = XCBSetupRootsIter (XCBGetSetup (c));
3350 for (; iter.rem; --screen, XCBSCREENNext (&iter))
3358 As mentioned above, you might want to store the value
3359 returned by this function.
3362 All the functions below will use the result of that
3363 function, as they just grab a specific member of the
3364 <span class="code">XCBSCREEN</span> structure.
3366 <li class="subtitle"><a name="DefaultScreenOfDisplay"></a>DefaultScreenOfDisplay
3368 It is the default screen that you obtain when you connect to
3369 the X server. It suffices to call the <a href="#ScreenOfDisplay">ScreenOfDisplay</a>
3370 function above with the connection and the number of the
3375 int screen_default_nbr;
3376 XCBSCREEN *default_screen; /* the returned default screen */
3378 /* you pass the name of the display you want to XCBConnect */
3380 c = XCBConnect (display_name, &screen_default_nbr);
3381 default_screen = ScreenOfDisplay (c, screen_default_nbr);
3383 /* default_screen contains now the default root window, or a NULL window if no screen is found */
3385 <li class="subtitle"><a name="RootWindow">RootWindow / RootWindowOfScreen</a>
3392 XCBWINDOW root_window = { 0 }; /* the returned window */
3394 /* you init the connection and screen_nbr */
3396 screen = ScreenOfDisplay (c, screen_nbr);
3398 root_window = screen->root;
3400 /* root_window contains now the root window, or a NULL window if no screen is found */
3402 <li class="subtitle"><a name="DefaultRootWindow">DefaultRootWindow</a>
3404 It is the root window of the default screen. So, you call
3405 <a name="ScreenOfDisplay">ScreenOfDisplay</a> with the
3406 default screen number and you get the
3407 <a href="#RootWindow">root window</a> as above:
3412 int screen_default_nbr;
3413 XCBWINDOW root_window = { 0 }; /* the returned root window */
3415 /* you pass the name of the display you want to XCBConnect */
3417 c = XCBConnect (display_name, &screen_default_nbr);
3418 screen = ScreenOfDisplay (c, screen_default_nbr);
3420 root_window = screen->root;
3422 /* root_window contains now the default root window, or a NULL window if no screen is found */
3424 <li class="subtitle"><a name="DefaultVisual">DefaultVisual / DefaultVisualOfScreen</a>
3426 While a Visual is, in Xlib, a structure, in XCB, there are
3427 two types: <span class="code">XCBVISUALID</span>, which is
3428 the Id of the visual, and <span class="code">XCBVISUALTYPE</span>,
3429 which corresponds to the Xlib Visual. To get the Id of the
3430 visual of a screen, just get the
3431 <span class="code">root_visual</span>
3432 member of a <span class="code">XCBSCREEN</span>:
3438 XCBVISUALID root_visual = { 0 }; /* the returned visual Id */
3440 /* you init the connection and screen_nbr */
3442 screen = ScreenOfDisplay (c, screen_nbr);
3444 root_visual = screen->root_visual;
3446 /* root_visual contains now the value of the Id of the visual, or a NULL visual if no screen is found */
3449 To get the <span class="code">XCBVISUALTYPE</span>
3450 structure, it's a bit less easy. You have to get the
3451 <span class="code">XCBSCREEN</span> structure that you want,
3452 get its <span class="code">root_visual</span> member,
3453 then iterate over the <span class="code">XCBDEPTH</span>s
3454 and the <span class="code">XCBVISUALTYPE</span>s, and compare
3455 the <span class="code">XCBVISUALID</span> of these <span class="code">XCBVISUALTYPE</span>s:
3456 with <span class="code">root_visual</span>:
3462 XCBVISUALID root_visual = { 0 };
3463 XCBVISUALTYPE *visual_type = NULL; /* the returned visual type */
3465 /* you init the connection and screen_nbr */
3467 screen = ScreenOfDisplay (c, screen_nbr);
3470 XCBDEPTHIter depth_iter;
3472 depth_iter = XCBSCREENAllowedDepthsIter (screen);
3473 for (; depth_iter.rem; XCBDEPTHNext (&depth_iter))
3475 XCBVISUALTYPEIter visual_iter;
3477 visual_iter = XCBDEPTHVisualsIter (depth_iter.data);
3478 for (; visual_iter.rem; XCBVISUALTYPENext (&visual_iter))
3480 if (screen->root_visual.id == visual_iter.data->visual_id.id)
3482 visual_type = visual_iter.data;
3489 /* visual_type contains now the visual structure, or a NULL visual structure if no screen is found */
3491 <li class="subtitle"><a name="DefaultGC">DefaultGC / DefaultGCOfScreen</a>
3493 This default Graphic Context is just a newly created Graphic
3494 Context, associated to the root window of a
3495 <span class="code">XCBSCREEN</span>,
3496 using the black white pixels of that screen:
3502 XCBGCONTEXT gc = { 0 }; /* the returned default graphic context */
3504 /* you init the connection and screen_nbr */
3506 screen = ScreenOfDisplay (c, screen_nbr);
3513 gc = XCBGCONTEXTNew (c);
3514 draw.window = screen->root;
3515 mask = XCBGCForeground | XCBGCBackground;
3516 values[0] = screen->black_pixel;
3517 values[1] = screen->white_pixel;
3518 XCBCreateGC (c, gc, draw, mask, values);
3521 /* gc contains now the default graphic context */
3523 <li class="subtitle"><a name="BlackPixel">BlackPixel / BlackPixelOfScreen</a>
3525 It is the Id of the black pixel, which is in the structure
3526 of an <span class="code">XCBSCREEN</span>.
3532 CARD32 black_pixel = 0; /* the returned black pixel */
3534 /* you init the connection and screen_nbr */
3536 screen = ScreenOfDisplay (c, screen_nbr);
3538 black_pixel = screen->black_pixel;
3540 /* black_pixel contains now the value of the black pixel, or 0 if no screen is found */
3542 <li class="subtitle"><a name="WhitePixel">WhitePixel / WhitePixelOfScreen</a>
3544 It is the Id of the white pixel, which is in the structure
3545 of an <span class="code">XCBSCREEN</span>.
3551 CARD32 white_pixel = 0; /* the returned white pixel */
3553 /* you init the connection and screen_nbr */
3555 screen = ScreenOfDisplay (c, screen_nbr);
3557 white_pixel = screen->white_pixel;
3559 /* white_pixel contains now the value of the white pixel, or 0 if no screen is found */
3561 <li class="subtitle"><a name="DisplayWidth">DisplayWidth / WidthOfScreen</a>
3563 It is the width in pixels of the screen that you want, and
3564 which is in the structure of the corresponding
3565 <span class="code">XCBSCREEN</span>.
3571 CARD32 width_in_pixels = 0; /* the returned width in pixels */
3573 /* you init the connection and screen_nbr */
3575 screen = ScreenOfDisplay (c, screen_nbr);
3577 width_in_pixels = screen->width_in_pixels;
3579 /* width_in_pixels contains now the width in pixels, or 0 if no screen is found */
3581 <li class="subtitle"><a name="DisplayHeight">DisplayHeight / HeightOfScreen</a>
3583 It is the height in pixels of the screen that you want, and
3584 which is in the structure of the corresponding
3585 <span class="code">XCBSCREEN</span>.
3591 CARD32 height_in_pixels = 0; /* the returned height in pixels */
3593 /* you init the connection and screen_nbr */
3595 screen = ScreenOfDisplay (c, screen_nbr);
3597 height_in_pixels = screen->height_in_pixels;
3599 /* height_in_pixels contains now the height in pixels, or 0 if no screen is found */
3601 <li class="subtitle"><a name="DisplayWidthMM">DisplayWidthMM / WidthMMOfScreen</a>
3603 It is the width in millimeters of the screen that you want, and
3604 which is in the structure of the corresponding
3605 <span class="code">XCBSCREEN</span>.
3611 CARD32 width_in_millimeters = 0; /* the returned width in millimeters */
3613 /* you init the connection and screen_nbr */
3615 screen = ScreenOfDisplay (c, screen_nbr);
3617 width_in_millimeters = screen->width_in_millimeters;
3619 /* width_in_millimeters contains now the width in millimeters, or 0 if no screen is found */
3621 <li class="subtitle"><a name="DisplayHeightMM">DisplayHeightMM / HeightMMOfScreen</a>
3623 It is the height in millimeters of the screen that you want, and
3624 which is in the structure of the corresponding
3625 <span class="code">XCBSCREEN</span>.
3631 CARD32 height_in_millimeters = 0; /* the returned height in millimeters */
3633 /* you init the connection and screen_nbr */
3635 screen = ScreenOfDisplay (c, screen_nbr);
3637 height_in_millimeters = screen->height_in_millimeters;
3639 /* height_in_millimeters contains now the height in millimeters, or 0 if no screen is found */
3641 <li class="subtitle"><a name="DisplayPlanes">DisplayPlanes / DefaultDepth / DefaultDepthOfScreen / PlanesOfScreen</a>
3643 It is the depth (in bits) of the root window of the
3644 screen. You get it from the <span class="code">XCBSCREEN</span> structure.
3650 CARD8 root_depth = 0; /* the returned depth of the root window */
3652 /* you init the connection and screen_nbr */
3654 screen = ScreenOfDisplay (c, screen_nbr);
3656 root_depth = screen->root_depth;
3658 /* root_depth contains now the depth of the root window, or 0 if no screen is found */
3660 <li class="subtitle"><a name="DefaultColormap">DefaultColormap / DefaultColormapOfScreen</a>
3662 This is the default colormap of the screen (and not the
3663 (default) colormap of the default screen !). As usual, you
3664 get it from the <span class="code">XCBSCREEN</span> structure:
3670 XCBCOLORMAP default_colormap = { 0 }; /* the returned default colormap */
3672 /* you init the connection and screen_nbr */
3674 screen = ScreenOfDisplay (c, screen_nbr);
3676 default_colormap = screen->default_colormap;
3678 /* default_colormap contains now the default colormap, or a NULL colormap if no screen is found */
3680 <li class="subtitle"><a name="MinCmapsOfScreen"></a>MinCmapsOfScreen
3682 You get the minimum installed colormaps in the <span class="code">XCBSCREEN</span> structure:
3688 CARD16 min_installed_maps = 0; /* the returned minimum installed colormaps */
3690 /* you init the connection and screen_nbr */
3692 screen = ScreenOfDisplay (c, screen_nbr);
3694 min_installed_maps = screen->min_installed_maps;
3696 /* min_installed_maps contains now the minimum installed colormaps, or 0 if no screen is found */
3698 <li class="subtitle"><a name="MaxCmapsOfScreen"></a>MaxCmapsOfScreen
3700 You get the maximum installed colormaps in the <span class="code">XCBSCREEN</span> structure:
3706 CARD16 max_installed_maps = 0; /* the returned maximum installed colormaps */
3708 /* you init the connection and screen_nbr */
3710 screen = ScreenOfDisplay (c, screen_nbr);
3712 max_installed_maps = screen->max_installed_maps;
3714 /* max_installed_maps contains now the maximum installed colormaps, or 0 if no screen is found */
3716 <li class="subtitle"><a name="DoesSaveUnders"></a>DoesSaveUnders
3718 You know if <span class="code">save_unders</span> is set,
3719 by looking in the <span class="code">XCBSCREEN</span> structure:
3725 BOOL save_unders = 0; /* the returned value of save_unders */
3727 /* you init the connection and screen_nbr */
3729 screen = ScreenOfDisplay (c, screen_nbr);
3731 save_unders = screen->save_unders;
3733 /* save_unders contains now the value of save_unders, or FALSE if no screen is found */
3735 <li class="subtitle"><a name="DoesBackingStore"></a>DoesBackingStore
3737 You know the value of <span class="code">backing_stores</span>,
3738 by looking in the <span class="code">XCBSCREEN</span> structure:
3744 BYTE backing_stores = 0; /* the returned value of backing_stores */
3746 /* you init the connection and screen_nbr */
3748 screen = ScreenOfDisplay (c, screen_nbr);
3750 backing_stores = screen->backing_stores;
3752 /* backing_stores contains now the value of backing_stores, or FALSE if no screen is found */
3754 <li class="subtitle"><a name="EventMaskOfScreen"></a>EventMaskOfScreen
3756 To get the current input masks,
3757 you look in the <span class="code">XCBSCREEN</span> structure:
3763 CARD32 current_input_masks = 0; /* the returned value of current input masks */
3765 /* you init the connection and screen_nbr */
3767 screen = ScreenOfDisplay (c, screen_nbr);
3769 current_input_masks = screen->current_input_masks;
3771 /* current_input_masks contains now the value of the current input masks, or FALSE if no screen is found */
3774 <li class="subtitle"><a name="misc">Miscellaneous macros</a>
3776 <li class="subtitle"><a name="DisplayOfScreen"></a>DisplayOfScreen
3778 in Xlib, the <span class="code">Screen</span> structure
3779 stores its associated <span class="code">Display</span>
3780 structure. This is not the case in the X Window protocol,
3781 hence, it's also not the case in XCB. So you have to store
3784 <li class="subtitle"><a name="DisplayCells"></a>DisplayCells / CellsOfScreen
3786 To get the colormap entries,
3787 you look in the <span class="code">XCBVISUALTYPE</span>
3788 structure, that you grab like <a class="subsection" href="#DefaultVisual">here</a>:
3792 XCBVISUALTYPE *visual_type;
3793 CARD16 colormap_entries = 0; /* the returned value of the colormap entries */
3795 /* you init the connection and visual_type */
3798 colormap_entries = visual_type->colormap_entries;
3800 /* colormap_entries contains now the value of the colormap entries, or FALSE if no screen is found */