1<?xml version="1.0" encoding="ISO-8859-1"?>
2<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
3 "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" [
4 <!ENTITY % defs SYSTEM "/xserver/doc/xml/xserver.ent"> %defs;
5]>
6
7<article>
8  <articleinfo>
9    <author>
10      <firstname>Susan</firstname><surname>Angebranndt</surname>
11      <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
12    </author>
13    <author>
14      <firstname>Raymond</firstname><surname>Drewry</surname>
15      <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
16    </author>
17    <author>
18      <firstname>Philip</firstname><surname>Karlton</surname>
19      <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
20    </author>
21    <author>
22      <firstname>Todd</firstname><surname>Newman</surname>
23      <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
24    </author>
25    <author>
26      <firstname>Bob</firstname><surname>Scheifler</surname>
27      <affiliation><orgname>Massachusetts Institute of Technology</orgname></affiliation>
28    </author>
29    <author>
30      <firstname>Keith</firstname><surname>Packard</surname>
31      <affiliation><orgname>MIT X Consortium</orgname></affiliation>
32    </author>
33    <author>
34      <firstname>David</firstname><othername>P.</othername><surname>Wiggins</surname>
35      <affiliation><orgname>X Consortium</orgname></affiliation>
36    </author>
37    <author>
38      <firstname>Jim</firstname><surname>Gettys</surname>
39      <affiliation><orgname>X.org Foundation and Hewlett Packard</orgname></affiliation>
40    </author>
41    <publisher><publishername>The X.Org Foundation</publishername></publisher>
42    <pubdate>&xserver.reldate;</pubdate>
43    <releaseinfo>X server version &xserver.version;</releaseinfo>
44    <title>Definition of the Porting Layer for the X v11 Sample Server</title>
45    <titleabbrev>X Porting Layer</titleabbrev>
46    <revhistory>
47      <revision>
48	<revnumber>1.0</revnumber>
49	<date>27 Oct 2004</date>
50	<authorinitials>sa</authorinitials>
51	<revremark>Initial Version</revremark>
52      </revision>
53      <revision>
54	<revnumber>1.1</revnumber>
55	<date>27 Oct 2004</date>
56	<authorinitials>bs</authorinitials>
57	<revremark>Minor Revisions</revremark>
58      </revision>
59      <revision>
60	<revnumber>2.0</revnumber>
61	<date>27 Oct 2004</date>
62	<authorinitials>kp</authorinitials>
63	<revremark>Revised for Release 4 and 5</revremark>
64      </revision>
65      <revision>
66	<revnumber>3.0</revnumber>
67	<date>27 Oct 2004</date>
68	<authorinitials>dpw</authorinitials>
69	<revremark>Revised for Release 6</revremark>
70      </revision>
71      <revision>
72	<revnumber>3.1</revnumber>
73	<date>27 Oct 2004</date>
74	<authorinitials>jg</authorinitials>
75	<revremark>Revised for Release 6.8.2</revremark>
76      </revision>
77      <revision>
78	<revnumber>3.2</revnumber>
79	<date>17 Dec 2006</date>
80	<authorinitials>efw</authorinitials>
81	<revremark>DocBook conversion</revremark>
82      </revision>
83      <revision>
84	<revnumber>3.3</revnumber>
85	<date>17 Feb 2008</date>
86	<authorinitials>aj</authorinitials>
87	<revremark>Revised for backing store changes</revremark>
88      </revision>
89      <revision>
90	<revnumber>3.4</revnumber>
91	<date>31 Mar 2008</date>
92	<authorinitials>efw</authorinitials>
93	<revremark>Revised for devPrivates changes</revremark>
94      </revision>
95      <revision>
96	<revnumber>3.5</revnumber>
97	<date>July 2010</date>
98	<authorinitials>ac</authorinitials>
99	<revremark>Revised for Xorg 1.9 devPrivates changes
100	  and 1.8 CreateNewResourceType changes</revremark>
101      </revision>
102    </revhistory>
103    <legalnotice>
104      <para>Copyright &#xA9; 1994 X Consortium, Inc., 2004 X.org Foundation, Inc.</para>
105      <para>Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ``Software''), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:</para>
106      <para>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</para>
107      <para>THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</para>
108      <para>LK201 and DEC are trademarks of Digital Equipment Corporation.  Macintosh and Apple are trademarks of Apple Computer, Inc.  PostScript is a trademark of Adobe Systems, Inc.  Ethernet is a trademark of Xerox Corporation.  X Window System is a trademark of the X.org Foundation, Inc.  Cray is a trademark of Cray Research, Inc.</para>
109    </legalnotice>
110    <abstract>
111      <para>The following document explains the structure of the X Window System display server and the interfaces among the larger pieces.  It is intended as a reference for programmers who are implementing an X Display Server on their workstation hardware.  It is included with the X Window System source tape, along with the document "Strategies for Porting the X v11 Sample Server."  The order in which you should read these documents is:
112      <orderedlist>
113	<listitem><para>Read the first section of the "Strategies for Porting" document (Overview of Porting Process).</para></listitem>
114	<listitem><para>Skim over this document (the Definition document).</para></listitem>
115	<listitem><para>Skim over the remainder of the Strategies document.</para></listitem>
116	<listitem><para>Start planning and working, referring to the Strategies and Definition documents.</para></listitem>
117      </orderedlist>
118      You may also want to look at the following documents:
119      <itemizedlist>
120	<listitem><para>"The X Window System" for an overview of X.</para></listitem>
121	<listitem><para>"Xlib - C Language X Interface" for a view of what the client programmer sees.</para></listitem>
122	<listitem><para>"X Window System Protocol" for a terse description of the byte stream protocol between the client and server.</para></listitem>
123      </itemizedlist>
124      </para>
125      <para>To understand this document and the accompanying source code, you should know the C language.  You should be familiar with 2D graphics and windowing concepts such as clipping, bitmaps, fonts, etc.  You should have a general knowledge of the X Window System.  To implement the server code on your hardware, you need to know a lot about your hardware, its graphic display device(s), and (possibly) its networking and multitasking facilities.  This document depends a lot on the source code, so you should have a listing of the code handy.</para>
126      <para>Some source in the distribution is directly compilable on your machine.  Some of it will require modification.  Other parts may have to be completely written from scratch.  The distribution also includes source for a sample implementation of a display server which runs on a very wide variety of color and monochrome displays on Linux and *BSD which you will find useful for implementing any type of X server.</para>
127      <para>Note to the 2008 edition: at this time this document must be considered incomplete, though improved over the 2004 edition.  In particular, the new Render extension is still lacking good documentation, and has become vital to high performance X implementations.  Modern applications and desktop environments are now much more sensitive to good implementation of the Render extension than in most operations of the old X graphics model.  The shadow frame buffer implementation is also very useful in many circumstances, and also needs documentation.  We hope to rectify these shortcomings in our documentation in the future.  Help would be greatly appreciated.</para>
128    </abstract>
129  </articleinfo>
130
131<!-- Original authorship information:
132
133.OF 'Porting Layer Definition'- % -'October 27, 2004'
134Definition of the Porting Layer
135for the X v11 Sample Server
136Susan Angebranndt
137Raymond Drewry
138Philip Karlton
139Todd Newman
140Digital Equipment Corporation
141
142minor revisions by
143Bob Scheifler
144Massachusetts Institute of Technology
145
146Revised for Release 4 and Release 5 by
147Keith Packard
148MIT X Consortium
149
150Revised for Release 6 by
151David P. Wiggins
152X Consortium
153
154Minor Revisions for Release 6.8.2 by
155Jim Gettys
156X.org Foundation and Hewlett Packard
157-->
158
159<section>
160  <title>The X Window System</title>
161<para>
162The X Window System, or simply "X," is a
163windowing system that provides high-performance, high-level,
164device-independent graphics.
165</para>
166<para>
167X is a windowing system designed for bitmapped graphic displays.
168The display can have a
169simple, monochrome display or it can have a color display with up to 32 bits
170per pixel with a special graphics processor doing the work.  (In this
171document, monochrome means a black and white display with one bit per pixel.
172Even though the usual meaning of monochrome is more general, this special
173case is so common that we decided to reserve the word for this purpose.)
174In practice, monochrome displays are now almost unheard of, with 4 bit
175gray scale displays being the low end.
176</para>
177<para>
178X is designed for a networking environment where
179users can run applications on machines other than their own workstations.
180Sometimes, the connection is over an Ethernet network with a protocol such as TCP/IP;
181but, any "reliable" byte stream is allowable.
182A high-bandwidth byte stream is preferable; RS-232 at
1839600 baud would be slow without compression techniques.
184</para>
185<para>
186X by itself allows great freedom of design.
187For instance, it does not include any user interface standard.
188Its intent is to "provide mechanism, not policy."
189By making it general, it can be the foundation for a wide
190variety of interactive software.
191</para>
192<para>
193For a more detailed overview, see the document "The X Window System."
194For details on the byte stream protocol, see "X Window System protocol."
195</para>
196</section>
197<section>
198<title>Overview of the Server</title>
199<para>
200The display server
201manages windows and simple graphics requests
202for the user on behalf of different client applications.
203The client applications can be running on any machine on the network.
204The server mainly does three things:
205<itemizedlist>
206  <listitem><para>Responds to protocol requests from existing clients (mostly graphic and text drawing commands)</para></listitem>
207  <listitem><para>Sends device input (keystrokes and mouse actions) and other events to existing clients</para></listitem>
208  <listitem><para>Maintains client connections</para></listitem>
209</itemizedlist>
210</para>
211<para>
212The server code is organized into four major pieces:
213<itemizedlist>
214  <listitem><para>Device Independent (DIX) layer - code shared among all implementations</para></listitem>
215  <listitem><para>Operating System (OS) layer - code that is different for each operating system but is shared among all graphic devices for this operating system</para></listitem>
216  <listitem><para>Device Dependent (DDX) layer - code that is (potentially) different for each combination of operating system and graphic device</para></listitem>
217  <listitem><para>Extension Interface - a standard way to add features to the X server</para></listitem>
218</itemizedlist>
219</para>
220<para>
221The "porting layer" consists of the OS and DDX layers; these are
222actually parallel and neither one is on top of the other.
223The DIX layer is intended to be portable
224without change to target systems and is not
225detailed here, although several routines
226in DIX that are called by DDX are
227documented.
228Extensions incorporate new functionality into the server; and require
229additional functionality over a simple DDX.
230</para>
231<para>
232The following sections outline the functions of the layers.
233Section 3 briefly tells what you need to know about the DIX layer.
234The OS layer is explained in Section 4.
235Section 5 gives the theory of operation and procedural interface for the
236DDX layer.
237Section 6 describes the functions which exist for the extension writer.
238</para>
239</section>
240
241<section>
242  <title>DIX Layer</title>
243<para>
244The DIX layer is the machine and device independent part of X.
245The source should be common to all operating systems and devices.
246The port process should not include changes to this part, therefore internal interfaces to DIX
247modules are not discussed, except for public interfaces to the DDX and the OS layers.
248The functions described in this section are available for extension writers to use.
249</para>
250<para>
251In the process of getting your server to work, if
252you think that DIX must be modified for purposes other than bug fixes,
253you may be doing something wrong.
254Keep looking for a more compatible solution.
255When the next release of the X server code is available,
256you should be able to just drop in the new DIX code and compile it.
257If you change DIX,
258you will have to remember what changes you made and will have
259to change the new sources before you can update to the new version.
260</para>
261<para>
262The heart of the DIX code is a loop called the dispatch loop.
263Each time the processor goes around the loop, it sends off accumulated input events
264from the input devices to the clients, and it processes requests from the clients.
265This loop is the most organized way for the server to
266process the asynchronous requests that
267it needs to process.
268Most of these operations are performed by OS and DDX routines that you must supply.
269</para>
270<section>
271  <title>Server Resource System</title>
272<para>
273X resources are C structs inside the server.
274Client applications create and manipulate these objects
275according to the rules of the X byte stream protocol.
276Client applications refer to resources with resource IDs,
277which are 32-bit integers that are sent over the network.
278Within the server, of course, they are just C structs, and we refer to them
279by pointers.
280</para>
281<section>
282  <title>Pre-Defined Resource Types</title>
283<para>
284The DDX layer has several kinds of resources:
285<itemizedlist>
286<listitem><para>Window</para></listitem>
287<listitem><para>Pixmap</para></listitem>
288<listitem><para>Screen</para></listitem>
289<listitem><para>Device</para></listitem>
290<listitem><para>Colormap</para></listitem>
291<listitem><para>Font</para></listitem>
292<listitem><para>Cursor</para></listitem>
293<listitem><para>Graphics Contexts</para></listitem>
294</itemizedlist>
295</para>
296<para>
297The type names of the more
298important server
299structs usually end in "Rec," such as "DeviceRec;"
300the pointer types usually end in "Ptr," such as "DevicePtr."
301</para>
302<para>
303The structs and
304important defined constants are declared
305in .h files that have names that suggest the name of the object.
306For instance, there are two .h files for windows,
307window.h and windowstr.h.
308window.h defines only what needs to be defined in order to use windows
309without peeking inside of them;
310windowstr.h defines the structs with all of their components in great detail
311for those who need it.
312</para>
313<para>
314Three kinds of fields are in these structs:
315<itemizedlist>
316<listitem><para>Attribute fields - struct fields that contain values like normal structs</para></listitem>
317<listitem><para>Pointers to procedures, or structures of procedures, that operate on the object</para></listitem>
318<listitem><para>A single private field or a devPrivates list (see <xref linkend="wrappers_and_privates"/>)
319used by your DDX code to store private data.</para></listitem>
320</itemizedlist>
321</para>
322<para>
323DIX calls through
324the struct's procedure pointers to do its tasks.
325These procedures are set either directly or indirectly by DDX procedures.
326Most of
327the procedures described in the remainder of this
328document are accessed through one of these structs.
329For example, the procedure to create a pixmap
330is attached to a ScreenRec and might be called by using the expression
331</para>
332<para>
333<blockquote>
334<programlisting>(* pScreen->CreatePixmap)(pScreen, width, height, depth).</programlisting>
335</blockquote>
336</para>
337<para>
338All procedure pointers must be set to some routine unless noted otherwise;
339a null pointer will have unfortunate consequences.
340</para>
341<para>
342Procedure routines will be indicated in the documentation by this convention:
343<blockquote>
344<programlisting>void pScreen->MyScreenRoutine(arg, arg, ...)</programlisting>
345</blockquote>
346as opposed to a free routine, not in a data structure:
347<blockquote>
348<programlisting>void MyFreeRoutine(arg, arg, ...)</programlisting>
349</blockquote>
350</para>
351<para>
352The attribute fields are mostly set by DIX; DDX should not modify them
353unless noted otherwise.
354</para>
355</section>
356<section>
357  <title>Creating Resources and Resource Types</title>
358<para>
359These functions should also be called from your extensionInitProc to
360allocate all of the various resource classes and types required for
361the extension.  Each time the server resets, these types must be reallocated
362as the old allocations will have been discarded.
363Resource types are integer values starting at 1.  Get
364a resource type by calling
365<blockquote><programlisting>
366
367    RESTYPE CreateNewResourceType(deleteFunc, char *name)
368
369</programlisting></blockquote>
370deleteFunc will be called to destroy all resources with this
371type.   name will be used to identify this type of resource
372to clients using the X-Resource extension, to security
373extensions such as SELinux, and to tracing frameworks such as DTrace.
374[The name argument was added in xorg-server 1.8.]
375</para>
376<para>
377Resource classes are masks starting at 1 &lt;&lt; 31 which can
378be or'ed with any resource type to provide attributes for the
379type.  To allocate a new class bit, call
380<blockquote><programlisting>
381
382    RESTYPE CreateNewResourceClass()
383
384</programlisting></blockquote>
385</para>
386<para>
387There are two ways of looking up resources, by type or
388by class.  Classes are non-exclusive subsets of the space of
389all resources, so you can lookup the union of multiple classes.
390(RC_ANY is the union of all classes).</para>
391<para>
392Note that the appropriate class bits must be or'ed into the value returned
393by CreateNewResourceType when calling resource lookup functions.</para>
394<para>
395If you need to create a ``private'' resource ID for internal use, you
396can call FakeClientID.
397<blockquote><programlisting>
398
399	XID FakeClientID(client)
400	    int client;
401
402</programlisting></blockquote>
403This allocates from ID space reserved for the server.</para>
404<para>
405To associate a resource value with an ID, use AddResource.
406<blockquote><programlisting>
407
408	Bool AddResource(id, type, value)
409	    XID id;
410	    RESTYPE type;
411	    pointer value;
412
413</programlisting></blockquote>
414The type should be the full type of the resource, including any class
415bits.  If AddResource fails to allocate memory to store the resource,
416it will call the deleteFunc for the type, and then return False.</para>
417<para>
418To free a resource, use one of the following.
419<blockquote><programlisting>
420
421	void FreeResource(id, skipDeleteFuncType)
422	    XID id;
423	    RESTYPE skipDeleteFuncType;
424
425	void FreeResourceByType(id, type, skipFree)
426	    XID id;
427	    RESTYPE type;
428	    Bool    skipFree;
429
430</programlisting></blockquote>
431FreeResource frees all resources matching the given id, regardless of
432type; the type's deleteFunc will be called on each matching resource,
433except that skipDeleteFuncType can be set to a single type for which
434the deleteFunc should not be called (otherwise pass RT_NONE).
435FreeResourceByType frees a specific resource matching a given id
436and type; if skipFree is true, then the deleteFunc is not called.
437</para>
438</section>
439<section>
440  <title>Looking Up Resources</title>
441<para>
442To look up a resource, use one of the following.
443<blockquote><programlisting>
444
445	int dixLookupResourceByType(
446	    pointer *result,
447	    XID id,
448	    RESTYPE rtype,
449	    ClientPtr client,
450	    Mask access_mode);
451
452	int dixLookupResourceByClass(
453	    pointer *result,
454	    XID id,
455	    RESTYPE rclass,
456	    ClientPtr client,
457	    Mask access_mode);
458
459</programlisting></blockquote>
460dixLookupResourceByType finds a resource with the given id and exact type.
461dixLookupResourceByClass finds a resource with the given id whose type is
462included in any one of the specified classes.
463The client and access_mode must be provided to allow security extensions to
464check if the client has the right privileges for the requested access.
465The bitmask values defined in the dixaccess.h header are or'ed together
466to define the requested access_mode.
467</para>
468</section>
469</section>
470<section>
471  <title>Callback Manager</title>
472<para>
473To satisfy a growing number of requests for the introduction of ad hoc
474notification style hooks in the server, a generic callback manager was
475introduced in R6.  A callback list object can be introduced for each
476new hook that is desired, and other modules in the server can register
477interest in the new callback list.  The following functions support
478these operations.</para>
479<para>
480Before getting bogged down in the interface details, an typical usage
481example should establish the framework.  Let's look at the
482ClientStateCallback in dix/dispatch.c.  The purpose of this particular
483callback is to notify interested parties when a client's state
484(initial, running, gone) changes.  The callback is "created" in this
485case by simply declaring a variable:
486<blockquote><programlisting>
487	CallbackListPtr ClientStateCallback;
488</programlisting></blockquote>
489</para>
490<para>
491Whenever the client's state changes, the following code appears, which notifies
492all interested parties of the change:
493<blockquote><programlisting>
494	if (ClientStateCallback) CallCallbacks(&amp;ClientStateCallback, (pointer)client);
495</programlisting></blockquote>
496</para>
497<para>
498Interested parties subscribe to the ClientStateCallback list by saying:
499<blockquote><programlisting>
500	AddCallback(&amp;ClientStateCallback, func, data);
501</programlisting></blockquote>
502</para>
503<para>
504When CallCallbacks is invoked on the list, func will be called thusly:
505<blockquote><programlisting>
506	(*func)(&amp;ClientStateCallback, data, client)
507</programlisting></blockquote>
508</para>
509<para>
510Now for the details.
511<blockquote><programlisting>
512
513	Bool AddCallback(pcbl, callback, subscriber_data)
514	    CallbackListPtr *pcbl;
515	    CallbackProcPtr callback;
516	    pointer         subscriber_data;
517
518</programlisting></blockquote>
519Adds the (callback, subscriber_data) pair to the given callback list.  Creates the callback
520list if it doesn't exist.  Returns TRUE if successful.</para>
521<para>
522<blockquote><programlisting>
523
524	Bool DeleteCallback(pcbl, callback, subscriber_data)
525	    CallbackListPtr *pcbl;
526	    CallbackProcPtr callback;
527	    pointer         subscriber_data;
528
529</programlisting></blockquote>
530Removes the (callback, data) pair to the given callback list if present.
531Returns TRUE if (callback, data) was found.</para>
532<para>
533<blockquote><programlisting>
534
535	void CallCallbacks(pcbl, call_data)
536	    CallbackListPtr    *pcbl;
537	    pointer	    call_data;
538
539</programlisting></blockquote>
540For each callback currently registered on the given callback list, call
541it as follows:
542<blockquote><programlisting>
543
544	(*callback)(pcbl, subscriber_data, call_data);
545</programlisting></blockquote>
546</para>
547<para>
548<blockquote><programlisting>
549	void DeleteCallbackList(pcbl)
550	    CallbackListPtr    *pcbl;
551
552</programlisting></blockquote>
553Destroys the given callback list.</para>
554</section>
555<section>
556  <title>Extension Interfaces</title>
557<para>
558This function should be called from your extensionInitProc which
559should be called by InitExtensions.
560<blockquote><programlisting>
561
562	ExtensionEntry *AddExtension(name, NumEvents,NumErrors,
563		MainProc, SwappedMainProc, CloseDownProc, MinorOpcodeProc)
564
565		char *name;  /*Null terminate string; case matters*/
566		int NumEvents;
567		int NumErrors;
568		int (* MainProc)(ClientPtr);/*Called if client matches server order*/
569		int (* SwappedMainProc)(ClientPtr);/*Called if client differs from server*/
570		void (* CloseDownProc)(ExtensionEntry *);
571		unsigned short (*MinorOpcodeProc)(ClientPtr);
572
573</programlisting></blockquote>
574name is the name used by clients to refer to the extension.  NumEvents is the
575number of event types used by the extension, NumErrors is the number of
576error codes needed by the extension.  MainProc is called whenever a client
577accesses the major opcode assigned to the extension.  SwappedMainProc is
578identical, except the client using the extension has reversed byte-sex.
579CloseDownProc is called at server reset time to deallocate any private
580storage used by the extension.  MinorOpcodeProc is used by DIX to place the
581appropriate value into errors.  The DIX routine StandardMinorOpcode can be
582used here which takes the minor opcode from the normal place in the request
583(i.e. just after the major opcode).</para>
584</section>
585<section>
586  <title>Macros and Other Helpers</title>
587<para>
588There are a number of macros in Xserver/include/dix.h which
589are useful to the extension writer.  Ones of particular interest
590are: REQUEST, REQUEST_SIZE_MATCH, REQUEST_AT_LEAST_SIZE,
591REQUEST_FIXED_SIZE, LEGAL_NEW_RESOURCE, and
592VALIDATE_DRAWABLE_AND_GC. Useful byte swapping macros can be found
593in Xserver/include/dix.h: WriteReplyToClient and WriteSwappedDataToClient; and
594in Xserver/include/misc.h: lswapl, lswaps, LengthRestB, LengthRestS,
595LengthRestL, SwapRestS, SwapRestL, swapl, swaps, cpswapl, and cpswaps.</para>
596</section>
597</section>
598
599<section>
600  <title>OS Layer</title>
601<para>
602This part of the source consists of a few routines that you have to rewrite
603for each operating system.
604These OS functions maintain the client connections and schedule work
605to be done for clients.
606They also provide an interface to font files,
607font name to file name translation, and
608low level memory management.
609<blockquote>
610<programlisting>void OsInit()</programlisting>
611</blockquote>
612OsInit initializes your OS code, performing whatever tasks need to be done.
613Frequently there is not much to be done.
614The sample server implementation is in Xserver/os/osinit.c.
615</para>
616<section>
617  <title>Scheduling and Request Delivery</title>
618<para>
619The main dispatch loop in DIX creates the illusion of multitasking between
620different windows, while the server is itself but a single process.
621The dispatch loop breaks up the work for each client into small digestible parts.
622Some parts are requests from a client, such as individual graphic commands.
623Some parts are events delivered to the client, such as keystrokes from the user.
624The processing of events and requests for different
625clients can be interleaved with one another so true multitasking
626is not needed in the server.
627</para>
628<para>
629You must supply some of the pieces for proper scheduling between clients.
630<blockquote>
631<programlisting>
632	int WaitForSomething(pClientReady)
633		int *pClientReady;
634</programlisting>
635</blockquote>
636</para>
637<para>
638WaitForSomething is the scheduler procedure you must write that will
639suspend your server process until something needs to be done.
640This call should
641make the server suspend until one or more of the following occurs:
642<itemizedlist>
643<listitem><para>There is an input event from the user or hardware (see SetInputCheck())</para></listitem>
644<listitem><para>There are requests waiting from known clients, in which case you should return a count of clients stored in pClientReady</para></listitem>
645<listitem><para>A new client tries to connect, in which case you should create the client and then continue waiting</para></listitem>
646</itemizedlist>
647</para>
648<para>
649Before WaitForSomething() computes the masks to pass to select, poll or
650similar operating system interface, it needs to
651see if there is anything to do on the work queue; if so, it must call a DIX
652routine called ProcessWorkQueue.
653<blockquote>
654<programlisting>
655	extern WorkQueuePtr	workQueue;
656
657	if (workQueue)
658		ProcessWorkQueue ();
659</programlisting>
660</blockquote>
661</para>
662<para>
663If WaitForSomething() decides it is about to do something that might block
664(in the sample server,  before it calls select() or poll) it must call a DIX
665routine called BlockHandler().
666<blockquote>
667<programlisting>
668	void BlockHandler(pTimeout, pReadmask)
669		pointer pTimeout;
670		pointer pReadmask;
671</programlisting>
672</blockquote>
673The types of the arguments are for agreement between the OS and DDX
674implementations,  but the pTimeout is a pointer to the information
675determining how long the block is allowed to last,  and the
676pReadmask is a pointer to the information describing the descriptors
677that will be waited on.
678</para>
679<para>
680In the sample server,  pTimeout is a struct timeval **,  and pReadmask is
681the address of the select() mask for reading.
682</para>
683<para>
684The DIX BlockHandler() iterates through the Screens,  for each one calling
685its BlockHandler.  A BlockHandler is declared thus:
686<blockquote>
687<programlisting>
688	void xxxBlockHandler(nscreen, pbdata, pptv, pReadmask)
689		int nscreen;
690		pointer pbdata;
691		struct timeval ** pptv;
692		pointer pReadmask;
693</programlisting>
694</blockquote>
695The arguments are the index of the Screen,  the blockData field
696of the Screen,  and the arguments to the DIX BlockHandler().
697</para>
698<para>
699Immediately after WaitForSomething returns from the
700block,  even if it didn't actually block,  it must call the DIX routine
701WakeupHandler().
702<blockquote>
703<programlisting>
704	void WakeupHandler(result, pReadmask)
705		int result;
706		pointer pReadmask;
707</programlisting>
708</blockquote>
709Once again,  the types are not specified by DIX.  The result is the
710success indicator for the thing that (may have) blocked,
711and the pReadmask is a mask of the descriptors that came active.
712In the sample server,  result is the result from select() (or equivalent
713operating system function),  and pReadmask is
714the address of the select() mask for reading.
715</para>
716<para>
717The DIX WakeupHandler() calls each Screen's
718WakeupHandler.  A WakeupHandler is declared thus:
719<blockquote>
720<programlisting>
721	void xxxWakeupHandler(nscreen, pbdata, err, pReadmask)
722		int nscreen;
723		pointer pbdata;
724		unsigned long result;
725		pointer pReadmask;
726</programlisting>
727</blockquote>
728The arguments are the index of the Screen,  the blockData field
729of the Screen,  and the arguments to the DIX WakeupHandler().
730</para>
731<para>
732In addition to the per-screen BlockHandlers, any module may register
733block and wakeup handlers (only together) using:
734<blockquote>
735<programlisting>
736	Bool RegisterBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData)
737		BlockHandlerProcPtr    blockHandler;
738		WakeupHandlerProcPtr   wakeupHandler;
739		pointer blockData;
740</programlisting>
741</blockquote>
742A FALSE return code indicates that the registration failed for lack of
743memory.  To remove a registered Block handler at other than server reset time
744(when they are all removed automatically), use:
745<blockquote>
746<programlisting>
747	RemoveBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData)
748		BlockHandlerProcPtr   blockHandler;
749		WakeupHandlerProcPtr  wakeupHandler;
750		pointer blockData;
751</programlisting>
752</blockquote>
753All three arguments must match the values passed to
754RegisterBlockAndWakeupHandlers.
755</para>
756<para>
757These registered block handlers are called after the per-screen handlers:
758<blockquote>
759<programlisting>
760	void (*BlockHandler) (blockData, pptv, pReadmask)
761		pointer	blockData;
762		OsTimerPtr pptv;
763		pointer	pReadmask;
764</programlisting>
765</blockquote>
766</para>
767<para>
768Sometimes block handlers need to adjust the time in a OSTimePtr structure,
769which on UNIX family systems is generally represented by a struct timeval
770consisting of seconds and microseconds in 32 bit values.
771As a convenience to reduce error prone struct timeval computations which
772require modulus arithmetic and correct overflow behavior in the face of
773millisecond wrapping through 32 bits,
774<blockquote><programlisting>
775
776	void AdjustWaitForDelay(pointer /*waitTime*, unsigned long /* newdelay */)
777
778</programlisting></blockquote>
779has been provided.
780</para>
781<para>
782Any wakeup handlers registered with RegisterBlockAndWakeupHandlers will
783be called before the Screen handlers:
784<blockquote><programlisting>
785
786	void (*WakeupHandler) (blockData, err, pReadmask)
787		pointer	blockData;
788		int err;
789		pointer pReadmask;
790</programlisting></blockquote>
791</para>
792<para>
793The WaitForSomething on the sample server also has a built
794in screen saver that darkens the screen if no input happens for a period of time.
795The sample server implementation is in Xserver/os/WaitFor.c.
796</para>
797<para>
798Note that WaitForSomething() may be called when you already have several
799outstanding things (events, requests, or new clients) queued up.
800For instance, your server may have just done a large graphics request,
801and it may have been a long time since WaitForSomething() was last called.
802If many clients have lots of requests queued up, DIX will only service
803some of them for a given client
804before going on to the next client (see isItTimeToYield, below).
805Therefore, WaitForSomething() will have to report that these same clients
806still have requests queued up the next time around.
807</para>
808<para>
809An implementation should return information on as
810many outstanding things as it can.
811For instance, if your implementation always checks for client data first and does not
812report any input events until there is no client data left,
813your mouse and keyboard might get locked out by an application that constantly
814barrages the server with graphics drawing requests.
815Therefore, as a general rule, input devices should always have priority over graphics
816devices.
817</para>
818<para>
819A list of indexes (client->index) for clients with data ready to be read or
820processed should be returned in pClientReady, and the count of indexes
821returned as the result value of the call.
822These are not clients that have full requests ready, but any clients who have
823any data ready to be read or processed.
824The DIX dispatcher
825will process requests from each client in turn by calling
826ReadRequestFromClient(), below.
827</para>
828<para>
829WaitForSomething() must create new clients as they are requested (by
830whatever mechanism at the transport level).  A new client is created
831by calling the DIX routine:
832<blockquote><programlisting>
833
834	ClientPtr NextAvailableClient(ospriv)
835		pointer ospriv;
836</programlisting></blockquote>
837This routine returns NULL if a new client cannot be allocated (e.g. maximum
838number of clients reached).  The ospriv argument will be stored into the OS
839private field (pClient->osPrivate), to store OS private information about the
840client.  In the sample server, the osPrivate field contains the
841number of the socket for this client. See also "New Client Connections."
842NextAvailableClient() will call InsertFakeRequest(), so you must be
843prepared for this.
844</para>
845<para>
846If there are outstanding input events,
847you should make sure that the two SetInputCheck() locations are unequal.
848The DIX dispatcher will call your implementation of ProcessInputEvents()
849until the SetInputCheck() locations are equal.
850</para>
851<para>
852The sample server contains an implementation of WaitForSomething().
853The
854following two routines indicate to WaitForSomething() what devices should
855be waited for.   fd is an OS dependent type; in the sample server
856it is an open file descriptor.
857<blockquote><programlisting>
858
859	int AddEnabledDevice(fd)
860		int fd;
861
862	int RemoveEnabledDevice(fd)
863		int fd;
864</programlisting></blockquote>
865These two routines are
866usually called by DDX from the initialize cases of the
867Input Procedures that are stored in the DeviceRec (the
868routine passed to AddInputDevice()).
869The sample server implementation of AddEnabledDevice
870and RemoveEnabledDevice are in Xserver/os/connection.c.
871</para>
872<section>
873  <title>Timer Facilities</title>
874<para>
875Similarly, the X server or an extension may need to wait for some timeout.
876Early X releases implemented this functionality using block and wakeup handlers,
877but this has been rewritten to use a general timer facilty, and the
878internal screen saver facilities reimplemented to use Timers.
879These functions are TimerInit, TimerForce, TimerSet, TimerCheck, TimerCancel,
880and TimerFree, as defined in Xserver/include/os.h. A callback function will be called
881when the timer fires, along with the current time, and a user provided argument.
882<blockquote><programlisting>
883	typedef	struct _OsTimerRec *OsTimerPtr;
884
885	typedef CARD32 (*OsTimerCallback)(
886		OsTimerPtr /* timer */,
887		CARD32 /* time */,
888		pointer /* arg */);
889
890	 OsTimerPtr TimerSet( OsTimerPtr /* timer */,
891		int /* flags */,
892		CARD32 /* millis */,
893		OsTimerCallback /* func */,
894		pointer /* arg */);
895
896</programlisting></blockquote>
897</para>
898<para>
899TimerSet returns a pointer to a timer structure and sets a timer to the specified time
900with the specified argument.  The flags can be TimerAbsolute and TimerForceOld.
901The TimerSetOld flag controls whether if the timer is reset and the timer is pending, the
902whether the callback function will get called.
903The TimerAbsolute flag sets the callback time to an absolute time in the future rather
904than a time relative to when TimerSet is called.
905TimerFree should be called to free the memory allocated
906for the timer entry.
907<blockquote><programlisting>
908	void TimerInit(void)
909
910	Bool TimerForce(OsTimerPtr /* pTimer */)
911
912	void TimerCheck(void);
913
914	void TimerCancel(OsTimerPtr /* pTimer */)
915
916	void TimerFree(OsTimerPtr /* pTimer */)
917</programlisting></blockquote>
918</para>
919<para>
920TimerInit frees any existing timer entries. TimerForce forces a call to the timer's
921callback function and returns true if the timer entry existed, else it returns false and
922does not call the callback function. TimerCancel will cancel the specified timer.
923TimerFree calls TimerCancel and frees the specified timer.
924Calling TimerCheck will force the server to see if any timer callbacks should be called.
925</para>
926</section>
927</section>
928<section>
929  <title>New Client Connections</title>
930<para>
931The process whereby a new client-server connection starts up is
932very dependent upon what your byte stream mechanism.
933This section describes byte stream initiation using examples from the TCP/IP
934implementation on the sample server.
935</para>
936<para>
937The first thing that happens is a client initiates a connection with the server.
938How a client knows to do this depends upon your network facilities and the
939Xlib implementation.
940In a typical scenario, a user named Fred
941on his X workstation is logged onto a Cray
942supercomputer running a command shell in an X window.  Fred can type shell
943commands and have the Cray respond as though the X server were a dumb terminal.
944Fred types in a command to run an X client application that was linked with Xlib.
945Xlib looks at the shell environment variable DISPLAY, which has the
946value "fredsbittube:0.0."
947The host name of Fred's workstation is "fredsbittube," and the 0s are
948for multiple screens and multiple X server processes.
949(Precisely what
950happens on your system depends upon how X and Xlib are implemented.)
951</para>
952<para>
953The client application calls a TCP routine on the
954Cray to open a TCP connection for X
955to communicate with the network node "fredsbittube."
956The TCP software on the Cray does this by looking up the TCP
957address of "fredsbittube" and sending an open request to TCP port 6000
958on fredsbittube.
959</para>
960<para>
961All X servers on TCP listen for new clients on port 6000 by default;
962this is known as a "well-known port" in IP terminology.
963</para>
964<para>
965The server receives this request from its port 6000
966and checks where it came from to see if it is on the server's list
967of "trustworthy" hosts to talk to.
968Then, it opens another port for communications with the client.
969This is the byte stream that all X communications will go over.
970</para>
971<para>
972Actually, it is a bit more complicated than that.
973Each X server process running on the host machine is called a "display."
974Each display can have more than one screen that it manages.
975"corporatehydra:3.2" represents screen 2 on display 3 on
976the multi-screened network node corporatehydra.
977The open request would be sent on well-known port number 6003.
978</para>
979<para>
980Once the byte stream is set up, what goes on does not depend very much
981upon whether or not it is TCP.
982The client sends an xConnClientPrefix struct (see Xproto.h) that has the
983version numbers for the version of Xlib it is running, some byte-ordering information,
984and two character strings used for authorization.
985If the server does not like the authorization strings
986or the version numbers do not match within the rules,
987or if anything else is wrong, it sends a failure
988response with a reason string.
989</para>
990<para>
991If the information never comes, or comes much too slowly, the connection
992should be broken off.  You must implement the connection timeout.  The
993sample server implements this by keeping a timestamp for each still-connecting
994client and, each time just before it attempts to accept new connections, it
995closes any connection that are too old.
996The connection timeout can be set from the command line.
997</para>
998<para>
999You must implement whatever authorization schemes you want to support.
1000The sample server on the distribution tape supports a simple authorization
1001scheme.  The only interface seen by DIX is:
1002<blockquote><programlisting>
1003
1004	char *
1005	ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
1006	    ClientPtr client;
1007	    unsigned int proto_n;
1008	    char *auth_proto;
1009	    unsigned int string_n;
1010	    char *auth_string;
1011</programlisting></blockquote>
1012DIX will only call this once per client, once it has read the full initial
1013connection data from the client.  If the connection should be
1014accepted ClientAuthorized() should return NULL, and otherwise should
1015return an error message string.
1016</para>
1017<para>
1018Accepting new connections happens internally to WaitForSomething().
1019WaitForSomething() must call the DIX routine NextAvailableClient()
1020to create a client object.
1021Processing of the initial connection data will be handled by DIX.
1022Your OS layer must be able to map from a client
1023to whatever information your OS code needs to communicate
1024on the given byte stream to the client.
1025DIX uses this ClientPtr to refer to
1026the client from now on.   The sample server uses the osPrivate field in
1027the ClientPtr to store the file descriptor for the socket, the
1028input and output buffers, and authorization information.
1029</para>
1030<para>
1031To initialize the methods you choose to allow clients to connect to
1032your server, main() calls the routine
1033<blockquote><programlisting>
1034
1035	void CreateWellKnownSockets()
1036</programlisting></blockquote>
1037This routine is called only once, and not called when the server
1038is reset.  To recreate any sockets during server resets, the following
1039routine is called from the main loop:
1040<blockquote><programlisting>
1041
1042	void ResetWellKnownSockets()
1043</programlisting></blockquote>
1044Sample implementations of both of these routines are found in
1045Xserver/os/connection.c.
1046</para>
1047<para>
1048For more details, see the section called "Connection Setup" in the X protocol specification.
1049</para>
1050</section>
1051<section>
1052  <title>Reading Data from Clients</title>
1053<para>
1054Requests from the client are read in as a byte stream by the OS layer.
1055They may be in the form of several blocks of bytes delivered in sequence; requests may
1056be broken up over block boundaries or there may be many requests per block.
1057Each request carries with it length information.
1058It is the responsibility of the following routine to break it up into request blocks.
1059<blockquote><programlisting>
1060
1061	int ReadRequestFromClient(who)
1062		ClientPtr who;
1063</programlisting></blockquote>
1064</para>
1065<para>
1066You must write
1067the routine ReadRequestFromClient() to get one request from the byte stream
1068belonging to client "who."
1069You must swap the third and fourth bytes (the second 16-bit word) according to the
1070byte-swap rules of
1071the protocol to determine the length of the
1072request.
1073This length is measured in 32-bit words, not in bytes.  Therefore, the
1074theoretical maximum request is 256K.
1075(However, the maximum length allowed is dependent upon the server's input
1076buffer.  This size is sent to the client upon connection.  The maximum
1077size is the constant MAX_REQUEST_SIZE in Xserver/include/os.h)
1078The rest of the request you return is
1079assumed NOT to be correctly swapped for internal
1080use, because that is the responsibility of DIX.
1081</para>
1082<para>
1083The 'who' argument is the ClientPtr returned from WaitForSomething.
1084The return value indicating status should be set to the (positive) byte count if the read is successful,
10850 if the read was blocked, or a negative error code if an error happened.
1086</para>
1087<para>
1088You must then store a pointer to
1089the bytes of the request in the client request buffer field;
1090who->requestBuffer.  This can simply be a pointer into your buffer;
1091DIX may modify it in place but will not otherwise cause damage.
1092Of course, the request must be contiguous; you must
1093shuffle it around in your buffers if not.
1094</para>
1095<para>
1096The sample server implementation is in Xserver/os/io.c.
1097</para>
1098<section><title>Inserting Data for Clients</title>
1099<para>
1100DIX can insert data into the client stream, and can cause a "replay" of
1101the current request.
1102<blockquote><programlisting>
1103
1104	Bool InsertFakeRequest(client, data, count)
1105	    ClientPtr client;
1106	    char *data;
1107	    int count;
1108
1109	int ResetCurrentRequest(client)
1110	    ClientPtr client;
1111</programlisting></blockquote>
1112</para>
1113<para>
1114InsertFakeRequest() must insert the specified number of bytes of data
1115into the head of the input buffer for the client.  This may be a
1116complete request, or it might be a partial request.  For example,
1117NextAvailableCient() will insert a partial request in order to read
1118the initial connection data sent by the client.  The routine returns FALSE
1119if memory could not be allocated.  ResetCurrentRequest()
1120should "back up" the input buffer so that the currently executing request
1121will be reexecuted.  DIX may have altered some values (e.g. the overall
1122request length), so you must recheck to see if you still have a complete
1123request.  ResetCurrentRequest() should always cause a yield (isItTimeToYield).
1124</para>
1125</section>
1126</section>
1127
1128<section>
1129  <title>Sending Events, Errors And Replies To Clients</title>
1130<para>
1131<blockquote><programlisting>
1132
1133	int WriteToClient(who, n, buf)
1134		ClientPtr who;
1135		int n;
1136		char *buf;
1137</programlisting></blockquote>
1138WriteToClient should write n bytes starting at buf to the
1139ClientPtr "who".
1140It returns the number of bytes written, but for simplicity,
1141the number returned must be either the same value as the number
1142requested, or -1, signaling an error.
1143The sample server implementation is in Xserver/os/io.c.
1144</para>
1145<para>
1146<blockquote><programlisting>
1147	void SendErrorToClient(client, majorCode, minorCode, resId, errorCode)
1148	    ClientPtr client;
1149	    unsigned int majorCode;
1150	    unsigned int minorCode;
1151	    XID resId;
1152	    int errorCode;
1153</programlisting></blockquote>
1154SendErrorToClient can be used to send errors back to clients,
1155although in most cases your request function should simply return
1156the error code, having set client->errorValue to the appropriate
1157error value to return to the client, and DIX will call this
1158function with the correct opcodes for you.
1159</para>
1160<para>
1161<blockquote><programlisting>
1162
1163	void FlushAllOutput()
1164
1165	void FlushIfCriticalOutputPending()
1166
1167	void SetCriticalOutputPending()
1168</programlisting></blockquote>
1169These three routines may be implemented to support buffered or delayed
1170writes to clients, but at the very least, the stubs must exist.
1171FlushAllOutput() unconditionally flushes all output to clients;
1172FlushIfCriticalOutputPending() flushes output only if
1173SetCriticalOutputPending() has be called since the last time output
1174was flushed.
1175The sample server implementation is in Xserver/os/io.c and
1176actually ignores requests to flush output on a per-client basis
1177if it knows that there
1178are requests in that client's input queue.
1179</para>
1180</section>
1181<section>
1182  <title>Font Support</title>
1183<para>
1184In the sample server, fonts are encoded in disk files or fetched from the
1185font server.   The two fonts required by the server, <quote>fixed</quote>
1186and <quote>cursor</quote> are commonly compiled into the font library.
1187For disk fonts, there is one file per font, with a file name like
1188"fixed.pcf".  Font server fonts are read over the network using the
1189X Font Server Protocol.  The disk directories containing disk fonts and
1190the names of the font servers are listed together in the current "font path."
1191</para>
1192<para>
1193In principle, you can put all your fonts in ROM or in RAM in your server.
1194You can put them all in one library file on disk.
1195You could generate them on the fly from stroke descriptions.  By placing the
1196appropriate code in the Font Library, you will automatically export fonts in
1197that format both through the X server and the Font server.
1198</para>
1199<para>
1200The code for processing fonts in different formats, as well as handling the
1201metadata files for them on disk (such as <filename>fonts.dir</filename>) is
1202located in the libXfont library, which is provided as a separately compiled
1203module.  These routines are
1204shared between the X server and the Font server, so instead of this document
1205specifying what you must implement, simply refer to the font
1206library interface specification for the details.  All of the interface code to the Font
1207library is contained in dix/dixfonts.c
1208</para>
1209</section>
1210<section>
1211  <title>Memory Management</title>
1212<para>
1213Memory management is based on functions in the C runtime library.
1214Xalloc(), Xrealloc(), and Xfree() are deprecated aliases for malloc(),
1215realloc(), and free(), and you should simply call the C library functions
1216directly.  Consult a C runtime library reference
1217manual for more details.
1218</para>
1219<para>
1220Treat memory allocation carefully in your implementation.  Memory
1221leaks can be very hard to find and are frustrating to a user.  An X
1222server could be running for days or weeks without being reset, just
1223like a regular terminal.  If you leak a few dozen k per day, that will
1224add up and will cause problems for users that leave their workstations
1225on.
1226</para>
1227</section>
1228<section>
1229  <title>Client Scheduling</title>
1230<para>
1231The X server
1232has the ability to schedule clients much like an operating system would,
1233suspending and restarting them without regard for the state of their input
1234buffers.  This functionality allows the X server to suspend one client and
1235continue processing requests from other clients while waiting for a
1236long-term network activity (like loading a font) before continuing with the
1237first client.
1238<blockquote><programlisting>
1239	Bool isItTimeToYield;
1240</programlisting></blockquote>
1241isItTimeToYield is a global variable you can set
1242if you want to tell
1243DIX to end the client's "time slice" and start paying attention to the next client.
1244After the current request is finished, DIX will move to the next client.
1245</para>
1246<para>
1247In the sample
1248server, ReadRequestFromClient() sets isItTimeToYield after
124910 requests packets in a row are read from the same client.
1250</para>
1251<para>
1252This scheduling algorithm can have a serious effect upon performance when two
1253clients are drawing into their windows simultaneously.
1254If it allows one client to run until its request
1255queue is empty by ignoring isItTimeToYield, the client's queue may
1256in fact never empty and other clients will be blocked out.
1257On the other hand, if it switchs between different clients too quickly,
1258performance may suffer due to too much switching between contexts.
1259For example, if a graphics processor needs to be set up with drawing modes
1260before drawing, and two different clients are drawing with
1261different modes into two different windows, you may
1262switch your graphics processor modes so often that performance is impacted.
1263</para>
1264<para>
1265See the Strategies document for
1266heuristics on setting isItTimeToYield.
1267</para>
1268<para>
1269The following functions provide the ability to suspend request
1270processing on a particular client, resuming it at some later time:
1271<blockquote><programlisting>
1272
1273	int IgnoreClient (who)
1274		ClientPtr who;
1275
1276	int AttendClient (who)
1277		ClientPtr who;
1278</programlisting></blockquote>
1279Ignore client is responsible for pretending that the given client doesn't
1280exist.  WaitForSomething should not return this client as ready for reading
1281and should not return if only this client is ready.  AttendClient undoes
1282whatever IgnoreClient did, setting it up for input again.
1283</para>
1284<para>
1285Three functions support "process control" for X clients:
1286<blockquote><programlisting>
1287
1288	Bool ClientSleep (client, function, closure)
1289		ClientPtr	client;
1290		Bool		(*function)();
1291		pointer		closure;
1292
1293</programlisting></blockquote>
1294This suspends the current client (the calling routine is responsible for
1295making its way back to Dispatch()).  No more X requests will be processed
1296for this client until ClientWakeup is called.
1297<blockquote><programlisting>
1298
1299	Bool ClientSignal (client)
1300		ClientPtr	client;
1301
1302</programlisting></blockquote>
1303This function causes a call to the (*function) parameter passed to
1304ClientSleep to be queued on the work queue.  This does not automatically
1305"wakeup" the client, but the function called is free to do so by calling:
1306<blockquote><programlisting>
1307
1308	ClientWakeup (client)
1309		ClientPtr	client;
1310
1311</programlisting></blockquote>
1312This re-enables X request processing for the specified client.
1313</para>
1314</section>
1315<section>
1316  <title>Other OS Functions</title>
1317<para>
1318<blockquote><programlisting>
1319	void
1320	ErrorF(char *f, ...)
1321
1322	void
1323	FatalError(char *f, ...)
1324
1325	void
1326	Error(str)
1327	    char *str;
1328</programlisting></blockquote>
1329You should write these three routines to provide for diagnostic output
1330from the dix and ddx layers, although implementing them to produce no
1331output will not affect the correctness of your server.  ErrorF() and
1332FatalError() take a printf() type of format specification in the first
1333argument and an implementation-dependent number of arguments following
1334that.  Normally, the formats passed to ErrorF() and FatalError()
1335should be terminated with a newline.  Error() provides an os interface
1336for printing out the string passed as an argument followed by a
1337meaningful explanation of the last system error.  Normally the string
1338does not contain a newline, and it is only called by the ddx layer.
1339In the sample implementation, Error() uses the perror() function.
1340</para>
1341<para>
1342After printing the message arguments, FatalError() must be implemented
1343such that the server will call AbortDDX() to give the ddx layer
1344a chance to reset the hardware, and then
1345terminate the server; it must not return.
1346</para>
1347<para>
1348The sample server implementation for these routines
1349is in Xserver/os/log.c along with other routines for logging messages.
1350</para>
1351</section>
1352</section>
1353
1354<section>
1355  <title>DDX Layer</title>
1356<para>
1357This section describes the
1358interface between DIX and DDX.
1359While there may be an OS-dependent driver interface between DDX
1360and the physical device, that interface is left to the DDX
1361implementor and is not specified here.
1362</para>
1363<para>
1364The DDX layer does most of its work through procedures that are
1365pointed to by different structs.
1366As previously described, the behavior of these resources is largely determined by
1367these procedure pointers.
1368Most of these routines are for graphic display on the screen or support functions thereof.
1369The rest are for user input from input devices.
1370</para>
1371<section>
1372  <title>Input</title>
1373<para>
1374In this document "input" refers to input from the user,
1375such as mouse, keyboard, and
1376bar code readers.
1377X input devices are of several types: keyboard, pointing device, and
1378many others.  The core server has support for extension devices as
1379described by the X Input Extension document; the interfaces used by
1380that extension are described elsewhere.  The core devices are actually
1381implemented as two collections of devices, the mouse is a ButtonDevice,
1382a ValuatorDevice and a PtrFeedbackDevice while the keyboard is a KeyDevice,
1383a FocusDevice and a KbdFeedbackDevice.  Each part implements a portion of
1384the functionality of the device.  This abstraction is hidden from view for
1385core devices by DIX.
1386</para>
1387<para>
1388You, the DDX programmer, are
1389responsible for some of the routines in this section.
1390Others are DIX routines that you should call to do the things you need to do in these DDX routines.
1391Pay attention to which is which.
1392</para>
1393<section>
1394  <title>Input Device Data Structures</title>
1395<para>
1396DIX keeps a global directory of devices in a central data structure
1397called InputInfo.
1398For each device there is a device structure called a DeviceRec.
1399DIX can locate any DeviceRec through InputInfo.
1400In addition, it has a special pointer to identify the main pointing device
1401and a special pointer to identify the main keyboard.
1402</para>
1403<para>
1404The DeviceRec (Xserver/include/input.h) is a device-independent
1405structure that contains the state of an input device.
1406A DevicePtr is simply a pointer to a DeviceRec.
1407</para>
1408<para>
1409An xEvent describes an event the server reports to a client.
1410Defined in Xproto.h, it is a huge struct of union of structs that have fields for
1411all kinds of events.
1412All of the variants overlap, so that the struct is actually very small in memory.
1413</para>
1414</section>
1415<section>
1416  <title>Processing Events</title>
1417<para>
1418The main DDX input interface is the following routine:
1419<blockquote><programlisting>
1420
1421	void ProcessInputEvents()
1422</programlisting></blockquote>
1423You must write this routine to deliver input events from the user.
1424DIX calls it when input is pending (see next section), and possibly
1425even when it is not.
1426You should write it to get events from each device and deliver
1427the events to DIX.
1428To deliver the events to DIX, DDX should call the following
1429routine:
1430<blockquote><programlisting>
1431
1432	void DevicePtr->processInputProc(pEvent, device, count)
1433		    xEventPtr events;
1434		    DeviceIntPtr device;
1435		    int count;
1436</programlisting></blockquote>
1437This is the "input proc" for the device, a DIX procedure.
1438DIX will fill in this procedure pointer to one of its own routines by
1439the time ProcessInputEvents() is called the first time.
1440Call this input proc routine as many times as needed to
1441deliver as many events as should be delivered.
1442DIX will buffer them up and send them out as needed.  Count is set
1443to the number of event records which make up one atomic device event and
1444is always 1 for the core devices (see the X Input Extension for descriptions
1445of devices which may use count &#x3E; 1).
1446</para>
1447<para>
1448For example, your ProcessInputEvents() routine might check the mouse and the
1449keyboard.
1450If the keyboard had several keystrokes queued up, it could just call
1451the keyboard's processInputProc as many times as needed to flush its internal queue.
1452</para>
1453<para>
1454event is an xEvent struct you pass to the input proc.
1455When the input proc returns, it is finished with the event rec, and you can fill
1456in new values and call the input proc again with it.
1457</para>
1458<para>
1459You should deliver the events in the same order that they were generated.
1460</para>
1461<para>
1462For keyboard and pointing devices the xEvent variant should be keyButtonPointer.
1463Fill in the following fields in the xEvent record:
1464<itemizedlist>
1465
1466<listitem><para>type - is one of the following: KeyPress, KeyRelease, ButtonPress,
1467					ButtonRelease, or MotionNotify</para></listitem>
1468<listitem><para>detail - for KeyPress or KeyRelease fields, this should be the
1469					key number (not the ASCII code); otherwise unused</para></listitem>
1470<listitem><para>time - is the time that the event happened (32-bits, in milliseconds, arbitrary origin)</para></listitem>
1471<listitem><para>rootX - is the x coordinate of cursor</para></listitem>
1472<listitem><para>rootY - is the y coordinate of cursor</para></listitem>
1473
1474</itemizedlist>
1475The rest of the fields are filled in by DIX.
1476</para>
1477<para>
1478The time stamp is maintained by your code in the DDX layer, and it is your responsibility to
1479stamp all events correctly.
1480</para>
1481<para>
1482The x and y coordinates of the pointing device and the time must be filled in for all event types
1483including keyboard events.
1484</para>
1485<para>
1486The pointing device must report all button press and release events.
1487In addition, it should report a MotionNotify event every time it gets called
1488if the pointing device has moved since the last notify.
1489Intermediate pointing device moves are stored in a special GetMotionEvents buffer,
1490because most client programs are not interested in them.
1491</para>
1492<para>
1493There are quite a collection of sample implementations of this routine,
1494one for each supported device.
1495</para>
1496</section>
1497<section>
1498<title>Telling DIX When Input is Pending</title>
1499<para>
1500In the server's dispatch loop, DIX checks to see
1501if there is any device input pending whenever WaitForSomething() returns.
1502If the check says that input is pending, DIX calls the
1503DDX routine ProcessInputEvents().
1504</para>
1505<para>
1506This check for pending input must be very quick; a procedure call
1507is too slow.
1508The code that does the check is a hardwired IF
1509statement in DIX code that simply compares the values
1510pointed to by two pointers.
1511If the values are different, then it assumes that input is pending and
1512ProcessInputEvents() is called by DIX.
1513</para>
1514<para>
1515You must pass pointers to DIX to tell it what values to compare.
1516The following procedure
1517is used to set these pointers:
1518<blockquote><programlisting>
1519
1520	void SetInputCheck(p1, p2)
1521		long *p1, *p2;
1522</programlisting></blockquote>
1523You should call it sometime during initialization to indicate to DIX the
1524correct locations to check.
1525You should
1526pay special attention to the size of what they actually point to,
1527because the locations are assumed to be longs.
1528</para>
1529<para>
1530These two pointers are initialized by DIX
1531to point to arbitrary values that
1532are different.
1533In other words, if you forget to call this routine during initialization,
1534the worst thing that will happen is that
1535ProcessInputEvents will be called when
1536there are no events to process.
1537</para>
1538<para>
1539p1 and p2 might
1540point at the head and tail of some shared
1541memory queue.
1542Another use would be to have one point at a constant 0, with the
1543other pointing at some mask containing 1s
1544for each input device that has
1545something pending.
1546</para>
1547<para>
1548The DDX layer of the sample server calls SetInputCheck()
1549once when the
1550server's private internal queue is initialized.
1551It passes pointers to the queue's head and tail.  See Xserver/mi/mieq.c.
1552</para>
1553<para>
1554<blockquote><programlisting>
1555	int TimeSinceLastInputEvent()
1556</programlisting></blockquote>
1557DDX must time stamp all hardware input
1558events.  But DIX sometimes needs to know the
1559time and the OS layer needs to know the time since the last hardware
1560input event in
1561order for the screen saver to work.   TimeSinceLastInputEvent() returns
1562the this time in milliseconds.
1563</para>
1564</section>
1565<section>
1566  <title>Controlling Input Devices</title>
1567<para>
1568You must write four routines to do various device-specific
1569things with the keyboard and pointing device.
1570They can have any name you wish because
1571you pass the procedure pointers to DIX routines.
1572</para>
1573<para>
1574<blockquote><programlisting>
1575
1576	int pInternalDevice->valuator->GetMotionProc(pdevice, coords, start, stop, pScreen)
1577		DeviceIntPtr pdevice;
1578		xTimecoord * coords;
1579		unsigned long start;
1580		unsigned long stop;
1581		ScreenPtr pScreen;
1582</programlisting></blockquote>
1583You write this DDX routine to fill in coords with all the motion
1584events that have times (32-bit count of milliseconds) between time
1585start and time stop.  It should return the number of motion events
1586returned.  If there is no motion events support, this routine should
1587do nothing and return zero.  The maximum number of coords to return is
1588set in InitPointerDeviceStruct(), below.
1589</para>
1590<para>
1591When the user drags the pointing device, the cursor position
1592theoretically sweeps through an infinite number of points.  Normally,
1593a client that is concerned with points other than the starting and
1594ending points will receive a pointer-move event only as often as the
1595server generates them. (Move events do not queue up; each new one
1596replaces the last in the queue.)  A server, if desired, can implement
1597a scheme to save these intermediate events in a motion buffer.  A
1598client application, like a paint program, may then request that these
1599events be delivered to it through the GetMotionProc routine.
1600</para>
1601<para>
1602<blockquote><programlisting>
1603
1604	void pInternalDevice->bell->BellProc(percent, pDevice, ctrl, unknown)
1605		int percent;
1606		DeviceIntPtr pDevice;
1607		pointer ctrl;
1608		int class;
1609</programlisting></blockquote>
1610You need to write this routine to ring the bell on the keyboard.
1611loud is a number from 0 to 100, with 100 being the loudest.
1612Class is either BellFeedbackClass or KbdFeedbackClass (from XI.h).
1613</para>
1614<para>
1615<blockquote><programlisting>
1616
1617	void pInternalDevice->somedevice->CtrlProc(device, ctrl)
1618		DevicePtr device;
1619		SomethingCtrl *ctrl;
1620
1621</programlisting></blockquote>
1622You write two versions of this procedure, one for the keyboard and one for the pointing device.
1623DIX calls it to inform DDX when a client has requested changes in the current
1624settings for the particular device.
1625For a keyboard, this might be the repeat threshold and rate.
1626For a pointing device, this might be a scaling factor (coarse or fine) for position reporting.
1627See input.h for the ctrl structures.
1628</para>
1629</section>
1630<section>
1631  <title>Input Initialization</title>
1632<para>
1633Input initialization is a bit complicated.
1634It all starts with InitInput(), a routine that you write to call
1635AddInputDevice() twice
1636(once for pointing device and once for keyboard.)
1637</para>
1638<para>
1639When you Add the devices, a routine you supply for each device
1640gets called to initialize them.
1641Your individual initialize routines must call InitKeyboardDeviceStruct()
1642or InitPointerDeviceStruct(), depending upon which it is.
1643In other words, you indicate twice that the keyboard is the keyboard and
1644the pointer is the pointer.
1645</para>
1646<para>
1647<blockquote><programlisting>
1648
1649	void InitInput(argc, argv)
1650	    int argc;
1651	    char **argv;
1652</programlisting></blockquote>
1653InitInput is a DDX routine you must write to initialize the
1654input subsystem in DDX.
1655It must call AddInputDevice() for each device that might generate events.
1656</para>
1657<para>
1658<blockquote><programlisting>
1659
1660	DevicePtr AddInputDevice(deviceProc, autoStart)
1661		DeviceProc deviceProc;
1662		Bool autoStart;
1663</programlisting></blockquote>
1664AddInputDevice is a DIX routine you call to create a device object.
1665deviceProc is a DDX routine that is called by DIX to do various operations.
1666AutoStart should be TRUE for devices that need to be turned on at
1667initialization time with a special call, as opposed to waiting for some
1668client application to
1669turn them on.
1670This routine returns NULL if sufficient memory cannot be allocated to
1671install the device.
1672</para>
1673<para>
1674Note also that except for the main keyboard and pointing device,
1675an extension is needed to provide for a client interface to a device.
1676</para>
1677<para>
1678The following DIX
1679procedures return the specified DevicePtr. They may or may not be useful
1680to DDX implementors.
1681</para>
1682<para>
1683<blockquote><programlisting>
1684
1685	DevicePtr LookupKeyboardDevice()
1686</programlisting></blockquote>
1687LookupKeyboardDevice returns pointer for current main keyboard device.
1688</para>
1689<para>
1690<blockquote><programlisting>
1691
1692	DevicePtr LookupPointerDevice()
1693</programlisting></blockquote>
1694LookupPointerDevice returns pointer for current main pointing device.
1695</para>
1696<para>
1697A DeviceProc (the kind passed to AddInputDevice()) in the following form:
1698<blockquote><programlisting>
1699
1700	Bool pInternalDevice->DeviceProc(device, action);
1701		DeviceIntPtr device;
1702		int action;
1703</programlisting></blockquote>
1704You must write a DeviceProc for each device.
1705device points to the device record.
1706action tells what action to take;
1707it will be one of  these defined constants  (defined in input.h):
1708<itemizedlist>
1709<listitem><para>
1710DEVICE_INIT -
1711At DEVICE_INIT time, the device should initialize itself by calling
1712InitPointerDeviceStruct(), InitKeyboardDeviceStruct(), or a similar
1713routine (see below)
1714and "opening" the device if necessary.
1715If you return a non-zero (i.e., != Success) value from the DEVICE_INIT
1716call, that device will be considered unavailable. If either the main keyboard
1717or main pointing device cannot be initialized, the DIX code will refuse
1718to continue booting up.</para></listitem>
1719<listitem><para>
1720DEVICE_ON - If the DeviceProc is called with DEVICE_ON, then it is
1721allowed to start
1722putting events into the client stream by calling through the ProcessInputProc
1723in the device.</para></listitem>
1724<listitem><para>
1725DEVICE_OFF - If the DeviceProc is called with DEVICE_OFF, no further
1726events from that
1727device should be given to the DIX layer.
1728The device will appear to be dead to the user.</para></listitem>
1729<listitem><para>
1730DEVICE_CLOSE - At DEVICE_CLOSE (terminate or reset) time, the device should
1731be totally closed down.</para></listitem>
1732</itemizedlist>
1733</para>
1734<para>
1735<blockquote><programlisting>
1736
1737	void InitPointerDeviceStruct(device, map, mapLength,
1738			GetMotionEvents, ControlProc, numMotionEvents)
1739		DevicePtr device;
1740		CARD8 *map;
1741		int mapLength;
1742		ValuatorMotionProcPtr ControlProc;
1743		PtrCtrlProcPtr GetMotionEvents;
1744		int numMotionEvents;
1745</programlisting></blockquote>
1746InitPointerDeviceStruct is a DIX routine you call at DEVICE_INIT time to declare
1747some operating routines and data structures for a pointing device.
1748map and mapLength are as described in the X Window
1749System protocol specification.
1750ControlProc and GetMotionEvents are DDX routines, see above.
1751</para>
1752<para>
1753numMotionEvents is for the motion-buffer-size for the GetMotionEvents
1754request.
1755A typical length for a motion buffer would be 100 events.
1756A server that does not implement this capability should set
1757numMotionEvents to zero.
1758</para>
1759<para>
1760<blockquote><programlisting>
1761
1762	void InitKeyboardDeviceStruct(device, pKeySyms, pModifiers, Bell, ControlProc)
1763		DevicePtr device;
1764		KeySymsPtr pKeySyms;
1765		CARD8 *pModifiers;
1766		BellProcPtr Bell;
1767		KbdCtrlProcPtr ControlProc;
1768
1769</programlisting></blockquote>
1770You call this DIX routine when a keyboard device is initialized and
1771its device procedure is called with
1772DEVICE_INIT.
1773The formats of the keysyms and modifier maps are defined in
1774Xserver/include/input.h.
1775They describe the layout of keys on the keyboards, and the glyphs
1776associated with them.  ( See the next section for information on
1777setting up the modifier map and the keysym map.)
1778ControlProc and Bell are DDX routines, see above.
1779</para>
1780</section>
1781<section>
1782  <title>Keyboard Mapping and Keycodes</title>
1783<para>
1784When you send a keyboard event, you send a report that a given key has
1785either been pressed or has been released.  There must be a keycode for
1786each key that identifies the key; the keycode-to-key mapping can be
1787any mapping you desire, because you specify the mapping in a table you
1788set up for DIX.  However, you are restricted by the protocol
1789specification to keycode values in the range 8 to 255 inclusive.
1790</para>
1791<para>
1792The keycode mapping information that you set up consists of the following:
1793<itemizedlist>
1794<listitem><para>
1795A minimum and maximum keycode number</para></listitem>
1796<listitem><para>
1797An array of sets of keysyms for each key, that is of length
1798maxkeycode - minkeycode + 1.
1799Each element of this array is a list of codes for symbols that are on that key.
1800There is no limit to the number of symbols that can be on a key.</para></listitem>
1801</itemizedlist>
1802Once the map is set up, DIX keeps and
1803maintains the client's changes to it.
1804</para>
1805<para>
1806The X protocol defines standard names to indicate the symbol(s)
1807printed on each keycap. (See X11/keysym.h)
1808</para>
1809<para>
1810Legal modifier keys must generate both up and down transitions.  When
1811a client tries to change a modifier key (for instance, to make "A" the
1812"Control" key), DIX calls the following routine, which should return
1813TRUE if the key can be used as a modifier on the given device:
1814<blockquote><programlisting>
1815
1816	Bool LegalModifier(key, pDev)
1817	    unsigned int key;
1818	    DevicePtr pDev;
1819</programlisting></blockquote>
1820</para>
1821</section>
1822</section>
1823<section>
1824<title>Screens</title>
1825<para>
1826Different computer graphics
1827displays have different capabilities.
1828Some are simple monochrome
1829frame buffers that are just lying
1830there in memory, waiting to be written into.
1831Others are color displays with many bits per pixel using some color lookup table.
1832Still others have high-speed graphic processors that prefer to do all of the work
1833themselves,
1834including maintaining their own high-level, graphic data structures.
1835</para>
1836<section>
1837  <title>Screen Hardware Requirements</title>
1838<para>
1839The only requirement on screens is that you be able to both read
1840and write locations in the frame buffer.
1841All screens must have a depth of 32 or less (unless you use
1842an X extension to allow a greater depth).
1843All screens must fit into one of the classes listed in the section
1844in this document on Visuals and Depths.
1845</para>
1846<para>
1847X uses the pixel as its fundamental unit of distance on the screen.
1848Therefore, most programs will measure everything in pixels.</para>
1849<para>
1850The sample server assumes square pixels.
1851Serious WYSIWYG (what you see is what you get) applications for
1852publishing and drawing programs will adjust for
1853different screen resolutions automatically.
1854Considerable work
1855is involved in compensating for non-square pixels (a bit in the DDX
1856code for the sample server but quite a bit in the client applications).</para>
1857</section>
1858<section>
1859  <title>Data Structures</title>
1860<para>
1861X supports multiple screens that are connected to the same
1862server.  Therefore, all the per-screen information is bundled into one data
1863structure of attributes and procedures, which is the ScreenRec (see
1864Xserver/include/scrnintstr.h).
1865The procedure entry points in a ScreenRec operate on
1866regions, colormaps, cursors, and fonts, because these resources
1867can differ in format from one screen to another.</para>
1868<para>
1869Windows are areas on the screen that can be drawn into by graphic
1870routines.  "Pixmaps" are off-screen graphic areas that can be drawn
1871into.  They are both considered drawables and are described in the
1872section on Drawables.  All graphic operations work on drawables, and
1873operations are available to copy patches from one drawable to another.</para>
1874<para>
1875The pixel image data in all drawables is in a format that is private
1876to DDX.  In fact, each instance of a drawable is associated with a
1877given screen.  Presumably, the pixel image data for pixmaps is chosen
1878to be conveniently understood by the hardware.  All screens in a
1879single server must be able to handle all pixmaps depths declared in
1880the connection setup information.</para>
1881<para>
1882Pixmap images are transferred to the server in one of two ways:
1883XYPixmap or ZPimap.  XYPixmaps are a series of bitmaps, one for each
1884bit plane of the image, using the bitmap padding rules from the
1885connection setup.  ZPixmaps are a series of bits, nibbles, bytes or
1886words, one for each pixel, using the format rules (padding and so on)
1887for the appropriate depth.</para>
1888<para>
1889All screens in a given server must agree on a set of pixmap image
1890formats (PixmapFormat) to support (depth, number of bits per pixel,
1891etc.).</para>
1892<para>
1893There is no color interpretation of bits in the pixmap.  Pixmaps
1894do not contain pixel values.  The interpretation is made only when
1895the bits are transferred onto the screen.</para>
1896<para>
1897The screenInfo structure (in scrnintstr.h) is a global data structure
1898that has a pointer to an array of ScreenRecs, one for each screen on
1899the server.  (These constitute the one and only description of each
1900screen in the server.)  Each screen has an identifying index (0, 1, 2, ...).
1901In addition, the screenInfo struct contains global server-wide
1902details, such as the bit- and byte- order in all bit images, and the
1903list of pixmap image formats that are supported.  The X protocol
1904insists that these must be the same for all screens on the server.</para>
1905</section>
1906<section>
1907  <title>Output Initialization</title>
1908<para>
1909<blockquote><programlisting>
1910
1911	InitOutput(pScreenInfo, argc, argv)
1912		ScreenInfo *pScreenInfo;
1913		int argc;
1914		char **argv;
1915</programlisting></blockquote>
1916Upon initialization, your DDX routine InitOutput() is called by DIX.
1917It is passed a pointer to screenInfo to initialize.  It is also passed
1918the argc and argv from main() for your server for the command-line
1919arguments.  These arguments may indicate what or how many screen
1920device(s) to use or in what way to use them.  For instance, your
1921server command line may allow a "-D" flag followed by the name of the
1922screen device to use.</para>
1923<para>
1924Your InitOutput() routine should initialize each screen you wish to
1925use by calling AddScreen(), and then it should initialize the pixmap
1926formats that you support by storing values directly into the
1927screenInfo data structure.  You should also set certain
1928implementation-dependent numbers and procedures in your screenInfo,
1929which determines the pixmap and scanline padding rules for all screens
1930in the server.</para>
1931<para>
1932<blockquote><programlisting>
1933
1934	int AddScreen(scrInitProc, argc, argv)
1935		Bool (*scrInitProc)();
1936		int argc;
1937		char **argv;
1938</programlisting></blockquote>
1939You should call AddScreen(), a DIX procedure, in InitOutput() once for
1940each screen to add it to the screenInfo database.  The first argument
1941is an initialization procedure for the screen that you supply.  The
1942second and third are the argc and argv from main().  It returns the
1943screen number of the screen installed, or -1 if there is either
1944insufficient memory to add the screen, or (*scrInitProc) returned
1945FALSE.</para>
1946<para>
1947The scrInitProc should be of the following form:
1948<blockquote><programlisting>
1949
1950	Bool scrInitProc(iScreen, pScreen, argc, argv)
1951		int iScreen;
1952		ScreenPtr pScreen;
1953		int argc;
1954		char **argv;
1955</programlisting></blockquote>
1956iScreen is the index for this screen; 0 for the first one initialized,
19571 for the second, etc.  pScreen is the pointer to the screen's new
1958ScreenRec.  argc and argv are as before.  Your screen initialize
1959procedure should return TRUE upon success or FALSE if the screen
1960cannot be initialized (for instance, if the screen hardware does not
1961exist on this machine).</para>
1962<para>
1963This procedure must determine what actual device it is supposed to initialize.
1964If you have a different procedure for each screen, then it is no problem.
1965If you have the same procedure for multiple screens, it may have trouble
1966figuring out which screen to initialize each time around, especially if
1967InitOutput() does not initialize all of the screens.
1968It is probably easiest to have one procedure for each screen.</para>
1969<para>
1970The initialization procedure should fill in all the screen procedures
1971for that screen (windowing functions, region functions, etc.) and certain
1972screen attributes for that screen.</para>
1973</section>
1974<section>
1975  <title>Region Routines in the ScreenRec</title>
1976<para>
1977A region is a dynamically allocated data structure that describes an
1978irregularly shaped piece of real estate in XY pixel space.  You can
1979think of it as a set of pixels on the screen to be operated upon with
1980set operations such as AND and OR.</para>
1981<para>
1982A region is frequently implemented as a list of rectangles or bitmaps
1983that enclose the selected pixels.  Region operators control the
1984"clipping policy," or the operations that work on regions.  (The
1985sample server uses YX-banded rectangles.  Unless you have something
1986already implemented for your graphics system, you should keep that
1987implementation.)  The procedure pointers to the region operators are
1988located in the ScreenRec data structure.  The definition of a region
1989can be found in the file Xserver/include/regionstr.h.  The region code
1990is found in Xserver/mi/miregion.c.  DDX implementations using other
1991region formats will need to supply different versions of the region
1992operators.</para>
1993<para>
1994Since the list of rectangles is unbounded in size, part of the region
1995data structure is usually a large, dynamically allocated chunk of
1996memory.  As your region operators calculate logical combinations of
1997regions, these blocks may need to be reallocated by your region
1998software.  For instance, in the sample server, a RegionRec has some
1999header information and a pointer to a dynamically allocated rectangle
2000list.  Periodically, the rectangle list needs to be expanded with
2001Xrealloc(), whereupon the new pointer is remembered in the RegionRec.</para>
2002<para>
2003Most of the region operations come in two forms: a function pointer in
2004the Screen structure, and a macro.  The server can be compiled so that
2005the macros make direct calls to the appropriate functions (instead of
2006indirecting through a screen function pointer), or it can be compiled
2007so that the macros are identical to the function pointer forms.
2008Making direct calls is faster on many architectures.</para>
2009<para>
2010<blockquote><programlisting>
2011
2012	RegionPtr pScreen->RegionCreate( rect, size)
2013		BoxPtr rect;
2014		int size;
2015
2016	macro: RegionPtr RegionCreate(rect, size)
2017
2018</programlisting></blockquote>
2019RegionCreate creates a region that describes ONE rectangle.  The
2020caller can avoid unnecessary reallocation and copying by declaring the
2021probable maximum number of rectangles that this region will need to
2022describe itself.  Your region routines, though, cannot fail just
2023because the region grows beyond this size.  The caller of this routine
2024can pass almost anything as the size; the value is merely a good guess
2025as to the maximum size until it is proven wrong by subsequent use.
2026Your region procedures are then on their own in estimating how big the
2027region will get.  Your implementation might ignore size, if
2028applicable.</para>
2029<para>
2030<blockquote><programlisting>
2031
2032	void pScreen->RegionInit (pRegion, rect, size)
2033		RegionPtr	pRegion;
2034		BoxPtr		rect;
2035		int		size;
2036
2037	macro: RegionInit(pRegion, rect, size)
2038
2039</programlisting></blockquote>
2040Given an existing raw region structure (such as an local variable), this
2041routine fills in the appropriate fields to make this region as usable as
2042one returned from RegionCreate.  This avoids the additional dynamic memory
2043allocation overhead for the region structure itself.
2044</para>
2045<para>
2046<blockquote><programlisting>
2047
2048	Bool pScreen->RegionCopy(dstrgn, srcrgn)
2049		RegionPtr dstrgn, srcrgn;
2050
2051	macro: Bool RegionCopy(dstrgn, srcrgn)
2052
2053</programlisting></blockquote>
2054RegionCopy copies the description of one region, srcrgn, to another
2055already-created region,
2056dstrgn; returning TRUE if the copy succeeded, and FALSE otherwise.</para>
2057<para>
2058<blockquote><programlisting>
2059
2060	void pScreen->RegionDestroy( pRegion)
2061		RegionPtr pRegion;
2062
2063	macro: RegionDestroy(pRegion)
2064
2065</programlisting></blockquote>
2066RegionDestroy destroys a region and frees all allocated memory.</para>
2067<para>
2068<blockquote><programlisting>
2069
2070	void pScreen->RegionUninit (pRegion)
2071		RegionPtr pRegion;
2072
2073	macro: RegionUninit(pRegion)
2074
2075</programlisting></blockquote>
2076Frees everything except the region structure itself, useful when the
2077region was originally passed to RegionInit instead of received from
2078RegionCreate.  When this call returns, pRegion must not be reused until
2079it has been RegionInit'ed again.</para>
2080<para>
2081<blockquote><programlisting>
2082
2083	Bool pScreen->Intersect(newReg, reg1, reg2)
2084		RegionPtr newReg, reg1, reg2;
2085
2086	macro: Bool RegionIntersect(newReg, reg1, reg2)
2087
2088	Bool  pScreen->Union(newReg, reg1, reg2)
2089		RegionPtr newReg, reg1, reg2;
2090
2091	macro: Bool RegionUnion(newReg, reg1, reg2)
2092
2093	Bool  pScreen->Subtract(newReg, regMinuend, regSubtrahend)
2094		RegionPtr newReg, regMinuend, regSubtrahend;
2095
2096	macro: Bool RegionUnion(newReg, regMinuend, regSubtrahend)
2097
2098	Bool pScreen->Inverse(newReg, pReg,  pBox)
2099		RegionPtr newReg, pReg;
2100		BoxPtr pBox;
2101
2102	macro: Bool RegionInverse(newReg, pReg,  pBox)
2103
2104</programlisting></blockquote>
2105The above four calls all do basic logical operations on regions.  They
2106set the new region (which already exists) to describe the logical
2107intersection, union, set difference, or inverse of the region(s) that
2108were passed in.  Your routines must be able to handle a situation
2109where the newReg is the same region as one of the other region
2110arguments.</para>
2111<para>
2112The subtract function removes the Subtrahend from the Minuend and
2113puts the result in newReg.</para>
2114<para>
2115The inverse function returns a region that is the pBox minus the
2116region passed in.  (A true "inverse" would make a region that extends
2117to infinity in all directions but has holes in the middle.)  It is
2118undefined for situations where the region extends beyond the box.</para>
2119<para>
2120Each routine must return the value TRUE for success.</para>
2121<para>
2122<blockquote><programlisting>
2123
2124	void pScreen->RegionReset(pRegion, pBox)
2125		RegionPtr pRegion;
2126		BoxPtr pBox;
2127
2128	macro: RegionReset(pRegion, pBox)
2129
2130</programlisting></blockquote>
2131RegionReset sets the region to describe
2132one rectangle and reallocates it to a size of one rectangle, if applicable.</para>
2133<para>
2134<blockquote><programlisting>
2135
2136	void  pScreen->TranslateRegion(pRegion, x, y)
2137		RegionPtr pRegion;
2138		int x, y;
2139
2140	macro: RegionTranslate(pRegion, x, y)
2141
2142</programlisting></blockquote>
2143TranslateRegion simply moves a region +x in the x direction and +y in the y
2144direction.</para>
2145<para>
2146<blockquote><programlisting>
2147
2148	int  pScreen->RectIn(pRegion, pBox)
2149		RegionPtr pRegion;
2150		BoxPtr pBox;
2151
2152	macro: int RegionContainsRect(pRegion, pBox)
2153
2154</programlisting></blockquote>
2155RectIn returns one of the defined constants rgnIN, rgnOUT, or rgnPART,
2156depending upon whether the box is entirely inside the region, entirely
2157outside of the region, or partly in and partly out of the region.
2158These constants are defined in Xserver/include/region.h.</para>
2159<para>
2160<blockquote><programlisting>
2161
2162	Bool pScreen->PointInRegion(pRegion, x, y, pBox)
2163		RegionPtr pRegion;
2164		int x, y;
2165		BoxPtr pBox;
2166
2167	macro: Bool RegionContainsPoint(pRegion, x, y, pBox)
2168
2169</programlisting></blockquote>
2170PointInRegion returns true if the point x, y is in the region.  In
2171addition, it fills the rectangle pBox with coordinates of a rectangle
2172that is entirely inside of pRegion and encloses the point.  In the mi
2173implementation, it is the largest such rectangle.  (Due to the sample
2174server implementation, this comes cheaply.)</para>
2175<para>
2176This routine used by DIX when tracking the pointing device and
2177deciding whether to report mouse events or change the cursor.  For
2178instance, DIX needs to change the cursor when it moves from one window
2179to another.  Due to overlapping windows, the shape to check may be
2180irregular.  A PointInRegion() call for every pointing device movement
2181may be too expensive.  The pBox is a kind of wake-up box; DIX need not
2182call PointInRegion() again until the cursor wanders outside of the
2183returned box.</para>
2184<para>
2185<blockquote><programlisting>
2186
2187	Bool pScreen->RegionNotEmpty(pRegion)
2188		RegionPtr pRegion;
2189
2190	macro: Bool RegionNotEmpty(pRegion)
2191
2192</programlisting></blockquote>
2193RegionNotEmpty is a boolean function that returns
2194true or false depending upon whether the region encloses any pixels.</para>
2195<para>
2196<blockquote><programlisting>
2197
2198	void pScreen->RegionEmpty(pRegion)
2199		RegionPtr pRegion;
2200
2201	macro: RegionEmpty(pRegion)
2202
2203</programlisting></blockquote>
2204RegionEmpty sets the region to be empty.</para>
2205<para>
2206<blockquote><programlisting>
2207
2208	BoxPtr pScreen->RegionExtents(pRegion)
2209		RegionPtr pRegion;
2210
2211	macro: RegionExtents(pRegion)
2212
2213</programlisting></blockquote>
2214RegionExtents returns a rectangle that is the smallest
2215possible superset of the entire region.
2216The caller will not modify this rectangle, so it can be the one
2217in your region struct.</para>
2218<para>
2219<blockquote><programlisting>
2220
2221	Bool pScreen->RegionAppend (pDstRgn, pRegion)
2222		RegionPtr pDstRgn;
2223		RegionPtr pRegion;
2224
2225	macro: Bool RegionAppend(pDstRgn, pRegion)
2226
2227	Bool pScreen->RegionValidate (pRegion, pOverlap)
2228		RegionPtr pRegion;
2229		Bool *pOverlap;
2230
2231	macro: Bool RegionValidate(pRegion, pOverlap)
2232
2233</programlisting></blockquote>
2234These functions provide an optimization for clip list generation and
2235must be used in conjunction.  The combined effect is to produce the
2236union of a collection of regions, by using RegionAppend several times,
2237and finally calling RegionValidate which takes the intermediate
2238representation (which needn't be a valid region) and produces the
2239desired union.  pOverlap is set to TRUE if any of the original
2240regions overlap; FALSE otherwise.</para>
2241<para>
2242<blockquote><programlisting>
2243
2244	RegionPtr pScreen->BitmapToRegion (pPixmap)
2245		PixmapPtr pPixmap;
2246
2247	macro: RegionPtr BitmapToRegion(pScreen, pPixmap)
2248
2249</programlisting></blockquote>
2250Given a depth-1 pixmap, this routine must create a valid region which
2251includes all the areas of the pixmap filled with 1's and excludes the
2252areas filled with 0's.  This routine returns NULL if out of memory.</para>
2253<para>
2254<blockquote><programlisting>
2255
2256	RegionPtr pScreen->RectsToRegion (nrects, pRects, ordering)
2257		int nrects;
2258		xRectangle *pRects;
2259		int ordering;
2260
2261	macro: RegionPtr RegionFromRects(nrects, pRects, ordering)
2262
2263</programlisting></blockquote>
2264Given a client-supplied list of rectangles, produces a region which includes
2265the union of all the rectangles.  Ordering may be used as a hint which
2266describes how the rectangles are sorted.  As the hint is provided by a
2267client, it must not be required to be correct, but the results when it is
2268not correct are not defined (core dump is not an option here).</para>
2269<para>
2270<blockquote><programlisting>
2271
2272	void pScreen->SendGraphicsExpose(client,pRegion,drawable,major,minor)
2273		ClientPtr client;
2274		RegionPtr pRegion;
2275		XID drawable;
2276		int major;
2277		int minor;
2278
2279</programlisting></blockquote>
2280SendGraphicsExpose dispatches a list of GraphicsExposure events which
2281span the region to the specified client.  If the region is empty, or
2282a NULL pointer, a NoExpose event is sent instead.</para>
2283</section>
2284<section>
2285  <title>Cursor Routines for a Screen</title>
2286<para>
2287A cursor is the visual form tied to the pointing device.  The default
2288cursor is an "X" shape, but the cursor can have any shape.  When a
2289client creates a window, it declares what shape the cursor will be
2290when it strays into that window on the screen.</para>
2291<para>
2292For each possible shape the cursor assumes, there is a CursorRec data
2293structure.  This data structure contains a pointer to a CursorBits
2294data structure which contains a bitmap for the image of the cursor and
2295a bitmap for a mask behind the cursor, in addition, the CursorRec data
2296structure contains foreground and background colors for the cursor.
2297The CursorBits data structure is shared among multiple CursorRec
2298structures which use the same font and glyph to describe both source
2299and mask.  The cursor image is applied to the screen by applying the
2300mask first, clearing 1 bits in its form to the background color, and
2301then overwriting on the source image, in the foreground color.  (One
2302bits of the source image that fall on top of zero bits of the mask
2303image are undefined.)  This way, a cursor can have transparent parts,
2304and opaque parts in two colors.  X allows any cursor size, but some
2305hardware cursor schemes allow a maximum of N pixels by M pixels.
2306Therefore, you are allowed to transform the cursor to a smaller size,
2307but be sure to include the hot-spot.</para>
2308<para>
2309CursorBits in Xserver/include/cursorstr.h is a device-independent
2310structure containing a device-independent representation of the bits
2311for the source and mask.  (This is possible because the bitmap
2312representation is the same for all screens.)</para>
2313<para>
2314When a cursor is created, it is "realized" for each screen.  At
2315realization time, each screen has the chance to convert the bits into
2316some other representation that may be more convenient (for instance,
2317putting the cursor into off-screen memory) and set up its
2318device-private area in either the CursorRec data structure or
2319CursorBits data structure as appropriate to possibly point to whatever
2320data structures are needed.  It is more memory-conservative to share
2321realizations by using the CursorBits private field, but this makes the
2322assumption that the realization is independent of the colors used
2323(which is typically true).  For instance, the following are the device
2324private entries for a particular screen and cursor:
2325<blockquote><programlisting>
2326
2327	pCursor->devPriv[pScreen->myNum]
2328	pCursor->bits->devPriv[pScreen->myNum]
2329
2330</programlisting></blockquote>
2331This is done because the change from one cursor shape to another must
2332be fast and responsive; the cursor image should be able to flutter as
2333fast as the user moves it across the screen.</para>
2334<para>
2335You must implement the following routines for your hardware:
2336<blockquote><programlisting>
2337
2338	Bool pScreen->RealizeCursor( pScr, pCurs)
2339		ScreenPtr pScr;
2340		CursorPtr pCurs;
2341
2342	Bool pScreen->UnrealizeCursor( pScr, pCurs)
2343		ScreenPtr pScr;
2344		CursorPtr pCurs;
2345
2346</programlisting></blockquote>
2347</para>
2348<para>
2349RealizeCursor and UnrealizeCursor should realize (allocate and
2350calculate all data needed) and unrealize (free the dynamically
2351allocated data) a given cursor when DIX needs them.  They are called
2352whenever a device-independent cursor is created or destroyed.  The
2353source and mask bits pointed to by fields in pCurs are undefined for
2354bits beyond the right edge of the cursor.  This is so because the bits
2355are in Bitmap format, which may have pad bits on the right edge.  You
2356should inhibit UnrealizeCursor() if the cursor is currently in use;
2357this happens when the system is reset.</para>
2358<para>
2359<blockquote><programlisting>
2360
2361	Bool pScreen->DisplayCursor( pScr, pCurs)
2362		ScreenPtr pScr;
2363		CursorPtr pCurs;
2364
2365</programlisting></blockquote>
2366DisplayCursor should change the cursor on the given screen to the one
2367passed in.  It is called by DIX when the user moves the pointing
2368device into a different window with a different cursor.  The hotspot
2369in the cursor should be aligned with the current cursor position.</para>
2370<para>
2371<blockquote><programlisting>
2372
2373	void pScreen->RecolorCursor( pScr, pCurs, displayed)
2374		ScreenPtr pScr;
2375		CursorPtr pCurs;
2376		Bool displayed;
2377</programlisting></blockquote>
2378RecolorCursor notifies DDX that the colors in pCurs have changed and
2379indicates whether this is the cursor currently being displayed.  If it
2380is, the cursor hardware state may have to be updated.  Whether
2381displayed or not, state created at RealizeCursor time may have to be
2382updated.  A generic version, miRecolorCursor, may be used that
2383does an unrealize, a realize, and possibly a display (in micursor.c);
2384however this constrains UnrealizeCursor and RealizeCursor to always return
2385TRUE as no error indication is returned here.</para>
2386<para>
2387<blockquote><programlisting>
2388
2389	void pScreen->ConstrainCursor( pScr, pBox)
2390		ScreenPtr pScr;
2391		BoxPtr pBox;
2392
2393</programlisting></blockquote>
2394ConstrainCursor should cause the cursor to restrict its motion to the
2395rectangle pBox.  DIX code is capable of enforcing this constraint by
2396forcefully moving the cursor if it strays out of the rectangle, but
2397ConstrainCursor offers a way to send a hint to the driver or hardware
2398if such support is available.  This can prevent the cursor from
2399wandering out of the box, then jumping back, as DIX forces it back.</para>
2400<para>
2401<blockquote><programlisting>
2402
2403	void pScreen->PointerNonInterestBox( pScr, pBox)
2404		ScreenPtr pScr;
2405		BoxPtr pBox;
2406
2407</programlisting></blockquote>
2408PointerNonInterestBox is DIX's way of telling the pointing device code
2409not to report motion events while the cursor is inside a given
2410rectangle on the given screen.  It is optional and, if not
2411implemented, it should do nothing.  This routine is called only when
2412the client has declared that it is not interested in motion events in
2413a given window.  The rectangle you get may be a subset of that window.
2414It saves DIX code the time required to discard uninteresting mouse
2415motion events.  This is only a hint, which may speed performance.
2416Nothing in DIX currently calls PointerNonInterestBox.</para>
2417<para>
2418<blockquote><programlisting>
2419
2420	void pScreen->CursorLimits( pScr, pCurs, pHotBox, pTopLeftBox)
2421		ScreenPtr pScr;
2422		CursorPtr pCurs;
2423		BoxPtr pHotBox;
2424		BoxPtr pTopLeftBox;	/* return value */
2425
2426</programlisting></blockquote>
2427CursorLimits should calculate the box that the cursor hot spot is
2428physically capable of moving within, as a function of the screen pScr,
2429the device-independent cursor pCurs, and a box that DIX hypothetically
2430would want the hot spot confined within, pHotBox.  This routine is for
2431informing DIX only; it alters no state within DDX.</para>
2432<para>
2433<blockquote><programlisting>
2434
2435	Bool pScreen->SetCursorPosition( pScr, newx, newy, generateEvent)
2436		ScreenPtr pScr;
2437		int newx;
2438		int newy;
2439		Bool generateEvent;
2440
2441</programlisting></blockquote>
2442SetCursorPosition should artificially move the cursor as though the
2443user had jerked the pointing device very quickly.  This is called in
2444response to the WarpPointer request from the client, and at other
2445times.  If generateEvent is True, the device should decide whether or
2446not to call ProcessInputEvents() and then it must call
2447DevicePtr->processInputProc.  Its effects are, of course, limited in
2448value for absolute pointing devices such as a tablet.</para>
2449<para>
2450<blockquote><programlisting>
2451
2452	void NewCurrentScreen(newScreen, x, y)
2453	    ScreenPtr newScreen;
2454	    int x,y;
2455
2456</programlisting></blockquote>
2457If your ddx provides some mechanism for the user to magically move the
2458pointer between multiple screens, you need to inform DIX when this
2459occurs.  You should call NewCurrentScreen to accomplish this, specifying
2460the new screen and the new x and y coordinates of the pointer on that screen.</para>
2461</section>
2462<section>
2463  <title>Visuals, Depths and Pixmap Formats for Screens</title>
2464<para>
2465The "depth" of a image is the number of bits that are used per pixel to display it.</para>
2466<para>
2467The "bits per pixel" of a pixmap image that is sent over the client
2468byte stream is a number that is either 4, 8, 16, 24 or 32.  It is the
2469number of bits used per pixel in Z format.  For instance, a pixmap
2470image that has a depth of six is best sent in Z format as 8 bits per
2471pixel.</para>
2472<para>
2473A "pixmap image format" or a "pixmap format" is a description of the
2474format of a pixmap image as it is sent over the byte stream.  For each
2475depth available on a server, there is one and only one pixmap format.
2476This pixmap image format gives the bits per pixel and the scanline
2477padding unit. (For instance, are pixel rows padded to bytes, 16-bit
2478words, or 32-bit words?)</para>
2479<para>
2480For each screen, you must decide upon what depth(s) it supports.  You
2481should only count the number of bits used for the actual image.  Some
2482displays store additional bits to indicate what window this pixel is
2483in, how close this object is to a viewer, transparency, and other
2484data; do not count these bits.</para>
2485<para>
2486A "display class" tells whether the display is monochrome or color,
2487whether there is a lookup table, and how the lookup table works.</para>
2488<para>
2489A "visual" is a combination of depth, display class, and a description
2490of how the pixel values result in a color on the screen.  Each visual
2491has a set of masks and offsets that are used to separate a pixel value
2492into its red, green, and blue components and a count of the number of
2493colormap entries.  Some of these fields are only meaningful when the
2494class dictates so.  Each visual also has a screen ID telling which
2495screen it is usable on.  Note that the depth does not imply the number
2496of map_entries; for instance, a display can have 8 bits per pixel but
2497only 254 colormap entries for use by applications (the other two being
2498reserved by hardware for the cursor).</para>
2499<para>
2500Each visual is identified by a 32-bit visual ID which the client uses
2501to choose what visual is desired on a given window.  Clients can be
2502using more than one visual on the same screen at the same time.</para>
2503<para>
2504The class of a display describes how this translation takes place.
2505There are three ways to do the translation.
2506<itemizedlist>
2507<listitem><para>
2508Pseudo - The pixel value, as a whole, is looked up
2509in a table of length map_entries to
2510determine the color to display.</para></listitem>
2511<listitem><para>
2512True - The
2513pixel value is broken up into red, green, and blue fields, each of which
2514are looked up in separate red, green, and blue lookup tables,
2515each of length map_entries.</para></listitem>
2516<listitem><para>
2517Gray - The pixel value is looked up in a table of length map_entries to
2518determine a gray level to display.</para></listitem>
2519</itemizedlist>
2520</para>
2521<para>
2522In addition, the lookup table can be static (resulting colors are fixed for each
2523pixel value)
2524or dynamic (lookup entries are under control of the client program).
2525This leads to a total of six classes:
2526<itemizedlist>
2527<listitem><para>
2528Static Gray - The pixel value (of however many bits) determines directly the
2529level of gray
2530that the pixel assumes.</para></listitem>
2531<listitem><para>
2532Gray Scale - The pixel value is fed through a lookup table to arrive at the level
2533of gray to display
2534for the given pixel.</para></listitem>
2535<listitem><para>
2536Static Color - The pixel value is fed through a fixed lookup table that yields the
2537color to display
2538for that pixel.</para></listitem>
2539<listitem><para>
2540PseudoColor - The whole pixel value is fed through a programmable lookup
2541table that has one
2542color (including red, green, and blue intensities) for each possible pixel value,
2543and that color is displayed.</para></listitem>
2544<listitem><para>
2545True Color - Each pixel value consists of one or more bits
2546that directly determine each primary color intensity after being fed through
2547a fixed table.</para></listitem>
2548<listitem><para>
2549Direct Color - Each pixel value consists of one or more bits for each primary color.
2550Each primary color value is individually looked up in a table for that primary
2551color, yielding
2552an intensity for that primary color.
2553For each pixel, the red value is looked up in the
2554red table, the green value in the green table, and
2555the blue value in the blue table.</para></listitem>
2556</itemizedlist>
2557</para>
2558<para>
2559Here are some examples:
2560<itemizedlist>
2561<listitem><para>
2562A simple monochrome 1 bit per pixel display is Static Gray.</para></listitem>
2563<listitem><para>
2564A display that has 2 bits per pixel for a choice
2565between the colors of black, white, green and violet is Static Color.</para></listitem>
2566<listitem><para>
2567A display that has three bits per pixel, where
2568each bit turns on or off one of the red, green or
2569blue guns, is in the True Color class.</para></listitem>
2570<listitem><para>
2571If you take the last example and scramble the
2572correspondence between pixel values and colors
2573it becomes a Static Color display.</para></listitem>
2574</itemizedlist></para>
2575<para>
2576A display has 8 bits per pixel.  The 8 bits select one entry out of 256 entries
2577in a lookup table, each entry consisting of 24 bits (8bits each for red, green,
2578and blue).
2579The display can show any 256 of 16 million colors on the screen at once.
2580This is a pseudocolor display.
2581The client application gets to fill the lookup table in this class of display.</para>
2582<para>
2583Imagine the same hardware from the last example.
2584Your server software allows the user, on the
2585command line that starts up the server
2586program,
2587to fill the lookup table to his liking once and for all.
2588From then on, the server software would not change the lookup table
2589until it exits.
2590For instance, the default might be a lookup table with a reasonable sample of
2591colors from throughout the color space.
2592But the user could specify that the table be filled with 256 steps of gray scale
2593because he knew ahead of time he would be manipulating a lot of black-and-white
2594scanned photographs
2595and not very many color things.
2596Clients would be presented with this unchangeable lookup table.
2597Although the hardware qualifies as a PseudoColor display,
2598the facade presented to the X client is that this is a Static Color display.</para>
2599<para>
2600You have to decide what kind of display you have or want
2601to pretend you have.
2602When you initialize the screen(s), this class value must be set in the
2603VisualRec data structure along with other display characteristics like the
2604depth and other numbers.</para>
2605<para>
2606The allowable DepthRec's and VisualRec's are pointed to by fields in the ScreenRec.
2607These are set up when InitOutput() is called; you should Xalloc() appropriate blocks
2608or use static variables initialized to the correct values.</para>
2609</section>
2610<section>
2611<title>Colormaps for Screens</title>
2612<para>
2613A colormap is a device-independent
2614mapping between pixel values and colors displayed on the screen.</para>
2615<para>
2616Different windows on the same screen can have different
2617colormaps at the same time.
2618At any given time, the most recently installed
2619colormap(s) will be in use in the server
2620so that its (their) windows' colors will be guaranteed to be correct.
2621Other windows may be off-color.
2622Although this may seem to be chaotic, in practice most clients
2623use the default colormap for the screen.</para>
2624<para>
2625The default colormap for a screen is initialized when the screen is initialized.
2626It always remains in existence and is not owned by any regular client.  It
2627is owned by client 0 (the server itself).
2628Many clients will simply use this default colormap for their drawing.
2629Depending upon the class of the screen, the entries in this colormap may
2630be modifiable by client applications.</para>
2631</section>
2632<section>
2633  <title>Colormap Routines</title>
2634<para>
2635You need to implement the following routines to handle the device-dependent
2636aspects of color maps.  You will end up placing pointers to these procedures
2637in your ScreenRec data structure(s).  The sample server implementations of
2638many of these routines are in fbcmap.c.</para>
2639<para>
2640<blockquote><programlisting>
2641
2642	Bool pScreen->CreateColormap(pColormap)
2643		ColormapPtr pColormap;
2644
2645</programlisting></blockquote>
2646This routine is called by the DIX CreateColormap routine after it has allocated
2647all the data for the new colormap and just before it returns to the dispatcher.
2648It is the DDX layer's chance to initialize the colormap, particularly if it is
2649a static map.  See the following
2650section for more details on initializing colormaps.
2651The routine returns FALSE if creation failed, such as due to memory
2652limitations.
2653Notice that the colormap has a devPriv field from which you can hang any
2654colormap specific storage you need.  Since each colormap might need special
2655information, we attached the field to the colormap and not the visual.</para>
2656<para>
2657<blockquote><programlisting>
2658
2659	void pScreen->DestroyColormap(pColormap)
2660		ColormapPtr pColormap;
2661
2662</programlisting></blockquote>
2663This routine is called by the DIX FreeColormap routine after it has uninstalled
2664the colormap and notified all interested parties, and before it has freed
2665any of the colormap storage.
2666It is the DDX layer's chance to free any data it added to the colormap.</para>
2667<para>
2668<blockquote><programlisting>
2669
2670	void pScreen->InstallColormap(pColormap)
2671		ColormapPtr pColormap;
2672
2673</programlisting></blockquote>
2674InstallColormap should
2675fill a lookup table on the screen with which the colormap is associated with
2676the colors in pColormap.
2677If there is only one hardware lookup table for the screen, then all colors on
2678the screen may change simultaneously.</para>
2679<para>
2680In the more general case of multiple hardware lookup tables,
2681this may cause some other colormap to be
2682uninstalled, meaning that windows that subscribed to the colormap
2683that was uninstalled may end up being off-color.
2684See the note, below, about uninstalling maps.</para>
2685<para>
2686<blockquote><programlisting>
2687
2688	void pScreen->UninstallColormap(pColormap)
2689		ColormapPtr pColormap;
2690
2691</programlisting></blockquote>
2692UninstallColormap should
2693remove pColormap from screen pColormap->pScreen.
2694Some other map, such as the default map if possible,
2695should be installed in place of pColormap if applicable.
2696If
2697pColormap is the default map, do nothing.
2698If any client has requested ColormapNotify events, the DDX layer must notify the client.
2699(The routine WalkTree() is
2700be used to find such windows.  The DIX routines TellNoMap(),
2701TellNewMap()  and TellGainedMap() are provided to be used as
2702the procedure parameter to WalkTree.  These procedures are in
2703Xserver/dix/colormap.c.)</para>
2704<para>
2705<blockquote><programlisting>
2706
2707	int pScreen->ListInstalledColormaps(pScreen, pCmapList)
2708		ScreenPtr pScreen;
2709		XID *pCmapList;
2710
2711
2712</programlisting></blockquote>
2713ListInstalledColormaps fills the pCmapList in with the resource ids
2714of the installed maps and returns a count of installed maps.
2715pCmapList will point to an array of size MaxInstalledMaps that was allocated
2716by the caller.</para>
2717<para>
2718<blockquote><programlisting>
2719
2720	void pScreen->StoreColors (pmap, ndef, pdefs)
2721		ColormapPtr pmap;
2722		int ndef;
2723		xColorItem *pdefs;
2724
2725</programlisting></blockquote>
2726StoreColors changes some of the entries in the colormap pmap.
2727The number of entries to change are ndef, and pdefs points to the information
2728describing what to change.
2729Note that partial changes of entries in the colormap are allowed.
2730Only the colors
2731indicated in the flags field of each xColorItem need to be changed.
2732However, all three color fields will be sent with the proper value for the
2733benefit of screens that may not be able to set part of a colormap value.
2734If the screen is a static class, this routine does nothing.
2735The structure of colormap entries is nontrivial; see colormapst.h
2736and the definition of xColorItem in Xproto.h for
2737more details.</para>
2738<para>
2739<blockquote><programlisting>
2740
2741	void pScreen->ResolveColor(pRed, pGreen, pBlue, pVisual)
2742		unsigned short *pRed, *pGreen, *pBlue;
2743		VisualPtr pVisual;
2744
2745
2746</programlisting></blockquote>
2747Given a requested color, ResolveColor returns the nearest color that this hardware is
2748capable of displaying on this visual.
2749In other words, this rounds off each value, in place, to the number of bits
2750per primary color that your screen can use.
2751Remember that each screen has one of these routines.
2752The level of roundoff should be what you would expect from the value
2753you put in the bits_per_rgb field of the pVisual.</para>
2754<para>
2755Each value is an unsigned value ranging from 0 to 65535.
2756The bits least likely to be used are the lowest ones.</para>
2757<para>
2758For example, if you had a pseudocolor display
2759with any number of bits per pixel
2760that had a lookup table supplying 6 bits for each color gun
2761(a total of 256K different colors), you would
2762round off each value to 6 bits.  Please don't simply truncate these values
2763to the upper 6 bits, scale the result so that the maximum value seen
2764by the client will be 65535 for each primary.  This makes color values
2765more portable between different depth displays (a 6-bit truncated white
2766will not look white on an 8-bit display).</para>
2767<section>
2768<title>Initializing a Colormap</title>
2769<para>
2770When a client requests a new colormap and when the server creates the default
2771colormap, the procedure CreateColormap in the DIX layer is invoked.
2772That procedure allocates memory for the colormap and related storage such as
2773the lists of which client owns which pixels.
2774It then sets a bit, BeingCreated, in the flags field of the ColormapRec
2775and calls the DDX layer's CreateColormap routine.
2776This is your chance to initialize the colormap.
2777If the colormap is static, which you can tell by looking at the class field,
2778you will want to fill in each color cell to match the hardwares notion of the
2779color for that pixel.
2780If the colormap is the default for the screen, which you can tell by looking
2781at the IsDefault bit in the flags field, you should allocate BlackPixel
2782and WhitePixel to match the values you set in the pScreen structure.
2783(Of course, you picked those values to begin with.)</para>
2784<para>
2785You can also wait and use AllocColor() to allocate blackPixel
2786and whitePixel after the default colormap has been created.
2787If the default colormap is static and you initialized it in
2788pScreen->CreateColormap, then use can use AllocColor afterwards
2789to choose pixel values with the closest rgb values to those
2790desired for blackPixel and whitePixel.
2791If the default colormap is dynamic and uninitialized, then
2792the rgb values you request will be obeyed, and AllocColor will
2793again choose pixel values for you.
2794These pixel values can then be stored into the screen.</para>
2795<para>
2796There are two ways to fill in the colormap.
2797The simplest way is to use the DIX function AllocColor.
2798<blockquote><programlisting>
2799
2800int AllocColor (pmap, pred, pgreen, pblue, pPix, client)
2801    ColormapPtr         pmap;
2802    unsigned short      *pred, *pgreen, *pblue;
2803    Pixel               *pPix;
2804    int                 client;
2805
2806</programlisting></blockquote>
2807This takes three pointers to 16 bit color values and a pointer to a suggested
2808pixel value.  The pixel value is either an index into one colormap or a
2809combination of three indices depending on the type of pmap.
2810If your colormap starts out empty, and you don't deliberately pick the same
2811value twice, you will always get your suggested pixel.
2812The truly nervous could check that the value returned in *pPix is the one
2813AllocColor was called with.
2814If you don't care which pixel is used, or would like them sequentially
2815allocated from entry 0, set *pPix to 0.  This will find the first free
2816pixel and use that.</para>
2817<para>
2818AllocColor will take care of all the  bookkeeping  and  will
2819call StoreColors to get the colormap rgb values initialized.
2820The hardware colormap will be changed whenever this colormap
2821is installed.</para>
2822<para>
2823If for some reason AllocColor doesn't do what you want, you can do your
2824own bookkeeping and call StoreColors yourself.  This is much more difficult
2825and shouldn't be necessary for most devices.</para>
2826</section>
2827</section>
2828<section>
2829  <title>Fonts for Screens</title>
2830<para>
2831A font is a set of bitmaps that depict the symbols in a character set.
2832Each font is for only one typeface in a given size, in other words,
2833just one bitmap for each character.  Parallel fonts may be available
2834in a variety of sizes and variations, including "bold" and "italic."
2835X supports fonts for 8-bit and 16-bit character codes (for oriental
2836languages that have more than 256 characters in the font).  Glyphs are
2837bitmaps for individual characters.</para>
2838<para>
2839The source comes with some useful font files in an ASCII, plain-text
2840format that should be comprehensible on a wide variety of operating
2841systems.  The text format, referred to as BDF, is a slight extension
2842of the current Adobe 2.1 Bitmap Distribution Format (Adobe Systems,
2843Inc.).</para>
2844<para>
2845A short paper in PostScript format is included with the sample server
2846that defines BDF.  It includes helpful pictures, which is why it is
2847done in PostScript and is not included in this document.</para>
2848<para>
2849Your implementation should include some sort of font compiler to read
2850these files and generate binary files that are directly usable by your
2851server implementation.  The sample server comes with the source for a
2852font compiler.</para>
2853<para>
2854It is important the font properties contained in the BDF files are
2855preserved across any font compilation. In particular, copyright
2856information cannot be casually tossed aside without legal
2857ramifications. Other properties will be important to some
2858sophisticated applications.</para>
2859<para>
2860All clients get font information from the server.  Therefore, your
2861server can support any fonts it wants to.  It should probably support
2862at least the fonts supplied with the X11 tape.  In principle, you can
2863convert fonts from other sources or dream up your own fonts for use on
2864your server.</para>
2865<section>
2866<title>Portable Compiled Format</title>
2867<para>
2868A font compiler is supplied with the sample server.  It has
2869compile-time switches to convert the BDF files into a portable binary
2870form, called Portable Compiled Format or PCF.  This allows for an
2871arbitrary data format inside the file, and by describing the details
2872of the format in the header of the file, any PCF file can be read by
2873any PCF reading client.  By selecting the format which matches the
2874required internal format for your renderer, the PCF reader can avoid
2875reformatting the data each time it is read in.  The font compiler
2876should be quite portable.</para>
2877<para>
2878The fonts included with the tape are stored in fonts/bdf.  The
2879font compiler is found in fonts/tools/bdftopcf.</para>
2880</section>
2881<section>
2882  <title>Font Realization</title>
2883<para>
2884Each screen configured into the server
2885has an opportunity at font-load time
2886to "realize" a font into some internal format if necessary.
2887This happens every time the font is loaded into memory.</para>
2888<para>
2889A font (FontRec in Xserver/include/dixfontstr.h) is
2890a device-independent structure containing a device-independent
2891representation of the font.  When a font is created, it is "realized"
2892for each screen.  At this point, the screen has the chance to convert
2893the font into some other format.  The DDX layer can also put information
2894in the devPrivate storage.</para>
2895<para>
2896<blockquote><programlisting>
2897
2898	Bool pScreen->RealizeFont(pScr, pFont)
2899		ScreenPtr pScr;
2900		FontPtr pFont;
2901
2902	Bool pScreen->UnrealizeFont(pScr, pFont)
2903		ScreenPtr pScr;
2904		FontPtr pFont;
2905
2906</programlisting></blockquote>
2907RealizeFont and UnrealizeFont should calculate and allocate these extra data structures and
2908dispose of them when no longer needed.
2909These are called in response to OpenFont and CloseFont requests from
2910the client.
2911The sample server implementation is in fbscreen.c (which does very little).</para>
2912</section>
2913</section>
2914<section>
2915  <title>Other Screen Routines</title>
2916<para>
2917You must supply several other screen-specific routines for
2918your X server implementation.
2919Some of these are described in other sections:
2920<itemizedlist>
2921<listitem><para>
2922GetImage() is described in the Drawing Primitives section.</para></listitem>
2923<listitem><para>
2924GetSpans() is described in the Pixblit routine section.</para></listitem>
2925<listitem><para>
2926Several window and pixmap manipulation procedures are
2927described in the Window section under Drawables.</para></listitem>
2928<listitem><para>
2929The CreateGC() routine is described under Graphics Contexts.</para></listitem>
2930</itemizedlist>
2931</para>
2932<para>
2933<blockquote><programlisting>
2934
2935	void pScreen->QueryBestSize(kind, pWidth, pHeight)
2936		int kind;
2937		unsigned short *pWidth, *pHeight;
2938		ScreenPtr pScreen;
2939
2940</programlisting></blockquote>
2941QueryBestSize() returns the best sizes for cursors, tiles, and stipples
2942in response to client requests.
2943kind is one of the defined constants CursorShape, TileShape, or StippleShape
2944(defined in X.h).
2945For CursorShape, return the maximum width and
2946height for cursors that you can handle.
2947For TileShape and StippleShape, start with the suggested values in pWidth
2948and pHeight and modify them in place to be optimal values that are
2949greater than or equal to the suggested values.
2950The sample server implementation is in Xserver/fb/fbscreen.c.</para>
2951<para>
2952<blockquote><programlisting>
2953
2954	pScreen->SourceValidate(pDrawable, x, y, width, height)
2955		DrawablePtr pDrawable;
2956		int x, y, width, height;
2957		unsigned int subWindowMode;
2958
2959</programlisting></blockquote>
2960SourceValidate should be called by CopyArea/CopyPlane primitives when
2961the SourceValidate function pointer in the screen is non-null.  If you know that
2962you will never need SourceValidate, you can avoid this check.  Currently,
2963SourceValidate is used by the mi software cursor code to remove the cursor
2964from the screen when the source rectangle overlaps the cursor position.
2965x,y,width,height describe the source rectangle (source relative, that is)
2966for the copy operation.  subWindowMode comes from the GC or source Picture.
2967</para>
2968<para>
2969<blockquote><programlisting>
2970
2971	Bool pScreen->SaveScreen(pScreen, on)
2972		ScreenPtr pScreen;
2973		int on;
2974
2975</programlisting></blockquote>
2976SaveScreen() is used for Screen Saver support (see WaitForSomething()).
2977pScreen is the screen to save.</para>
2978<para>
2979<blockquote><programlisting>
2980
2981	Bool pScreen->CloseScreen(pScreen)
2982	    ScreenPtr pScreen;
2983
2984</programlisting></blockquote>
2985When the server is reset, it calls this routine for each screen.</para>
2986<para>
2987<blockquote><programlisting>
2988
2989	Bool pScreen->CreateScreenResources(pScreen)
2990	    ScreenPtr pScreen;
2991
2992</programlisting></blockquote>
2993If this routine is not NULL, it will be called once per screen per
2994server initialization/reset after all modules have had a chance to
2995request private space on all structures that support them (see
2996<xref linkend="wrappers_and_privates"/> below).  You may create resources
2997in this function instead of in the
2998screen init function passed to AddScreen in order to guarantee that
2999all pre-allocated space requests have been registered first.  With the
3000new devPrivates mechanism, this is not strictly necessary, however.
3001This routine returns TRUE if successful.</para>
3002</section>
3003</section>
3004<section>
3005<title>Drawables</title>
3006<para>
3007A drawable is a descriptor of a surface that graphics are drawn into, either
3008a window on the screen or a pixmap in memory.</para>
3009<para>
3010Each drawable has a type, class,
3011ScreenPtr for the screen it is associated with, depth, position, size,
3012and serial number.
3013The type is one of the defined constants DRAWABLE_PIXMAP,
3014DRAWABLE_WINDOW and UNDRAWABLE_WINDOW.
3015(An undrawable window is used for window class InputOnly.)
3016The serial number is guaranteed to be unique across drawables, and
3017is used in determining
3018the validity of the clipping information in a GC.
3019The screen selects the set of procedures used to manipulate and draw into the
3020drawable.  Position is used (currently) only by windows; pixmaps must
3021set these fields to 0,0 as this reduces the amount of conditional code
3022executed throughout the mi code.  Size indicates the actual client-specified
3023size of the drawable.
3024There are, in fact, no other fields that a window drawable and pixmap
3025drawable have in common besides those mentioned here.</para>
3026<para>
3027Both PixmapRecs and WindowRecs are structs that start with a drawable
3028and continue on with more fields.  Pixmaps have a single pointer field
3029named devPrivate which usually points to the pixmap data but could conceivably be
3030used for anything that DDX wants.  Both windows and pixmaps also have a
3031devPrivates field which can be used for DDX specific data (see <xref linkend="wrappers_and_privates"/>
3032below).  This is done because different graphics hardware has
3033different requirements for management; if the graphics is always
3034handled by a processor with an independent address space, there is no
3035point having a pointer to the bit image itself.</para>
3036<para>
3037The definition of a drawable and a pixmap can be found in the file
3038Xserver/include/pixmapstr.h.
3039The definition of a window can be found in the file Xserver/include/windowstr.h.</para>
3040<section>
3041  <title>Pixmaps</title>
3042<para>
3043A pixmap is a three-dimensional array of bits stored somewhere offscreen,
3044rather than in the visible portion of the screen's display frame buffer.  It
3045can be used as a source or destination in graphics operations.  There is no
3046implied interpretation of the pixel values in a pixmap, because it has no
3047associated visual or colormap.  There is only a depth that indicates the
3048number of significant bits per pixel.  Also, there is no implied physical
3049size for each pixel; all graphic units are in numbers of pixels.  Therefore,
3050a pixmap alone does not constitute a complete image; it represents only a
3051rectangular array of pixel values.</para>
3052<para>
3053Note that the pixmap data structure is reference-counted.</para>
3054<para>
3055The server implementation is free to put the pixmap data
3056anywhere it sees fit, according to its graphics hardware setup.  Many
3057implementations will simply have the data dynamically allocated in the
3058server's address space.  More sophisticated implementations may put the
3059data in undisplayed framebuffer storage.</para>
3060<para>
3061In addition to dynamic devPrivates (see <xref linkend="wrappers_and_privates"/>
3062below), the pixmap data structure has two fields that are private to
3063the device.  Although you can use them for anything you want, they
3064have intended purposes.  devKind is intended to be a device specific
3065indication of the pixmap location (host memory, off-screen, etc.).  In
3066the sample server, since all pixmaps are in memory, devKind stores the
3067width of the pixmap in bitmap scanline units.  devPrivate is usually
3068a pointer to the bits in the pixmap.</para>
3069<para>
3070A bitmap is a pixmap that is one bit deep.</para>
3071<para>
3072<blockquote><programlisting>
3073
3074	PixmapPtr pScreen->CreatePixmap(pScreen, width, height, depth)
3075		ScreenPtr pScreen;
3076		int width, height, depth;
3077
3078</programlisting></blockquote>
3079This ScreenRec procedure must create a pixmap of the size
3080requested.
3081It must allocate a PixmapRec and fill in all of the fields.
3082The reference count field must be set to 1.
3083If width or height are zero, no space should be allocated
3084for the pixmap data, and if the implementation is using the
3085devPrivate field as a pointer to the pixmap data, it should be
3086set to NULL.
3087If successful, it returns a pointer to the new pixmap; if not, it returns NULL.
3088See Xserver/fb/fbpixmap.c for the sample server implementation.</para>
3089<para>
3090<blockquote><programlisting>
3091
3092	Bool pScreen->DestroyPixmap(pPixmap)
3093		PixmapPtr pPixmap;
3094
3095</programlisting></blockquote>
3096This ScreenRec procedure must "destroy" a pixmap.
3097It should decrement the reference count and, if zero, it
3098must deallocate the PixmapRec and all attached devPrivate blocks.
3099If successful, it returns TRUE.
3100See Xserver/fb/fbpixmap.c for the sample server implementation.</para>
3101<para>
3102<blockquote><programlisting>
3103
3104	Bool
3105	pScreen->ModifyPixmapHeader(pPixmap, width, height, depth, bitsPerPixel, devKind, pPixData)
3106		PixmapPtr   pPixmap;
3107		int	    width;
3108		int	    height;
3109		int	    depth;
3110		int	    bitsPerPixel;
3111		int	    devKind;
3112		pointer     pPixData;
3113
3114</programlisting></blockquote>
3115This routine takes a pixmap header and initializes the fields of the PixmapRec to the
3116parameters of the same name.  pPixmap must have been created via
3117pScreen->CreatePixmap with a zero width or height to avoid
3118allocating space for the pixmap data.  pPixData is assumed to be the
3119pixmap data; it will be stored in an implementation-dependent place
3120(usually pPixmap->devPrivate.ptr).  This routine returns
3121TRUE if successful.  See Xserver/mi/miscrinit.c for the sample
3122server implementation.</para>
3123<para>
3124<blockquote><programlisting>
3125
3126	PixmapPtr
3127	GetScratchPixmapHeader(pScreen, width, height, depth, bitsPerPixel, devKind, pPixData)
3128		ScreenPtr   pScreen;
3129		int	    width;
3130		int	    height;
3131		int	    depth;
3132		int	    bitsPerPixel;
3133		int	    devKind;
3134		pointer     pPixData;
3135
3136	void FreeScratchPixmapHeader(pPixmap)
3137		PixmapPtr pPixmap;
3138
3139</programlisting></blockquote>
3140DDX should use these two DIX routines when it has a buffer of raw
3141image data that it wants to manipulate as a pixmap temporarily,
3142usually so that some other part of the server can be leveraged to
3143perform some operation on the data.  The data should be passed in
3144pPixData, and will be stored in an implementation-dependent place
3145(usually pPixmap->devPrivate.ptr). The other
3146fields go into the corresponding PixmapRec fields.
3147If successful, GetScratchPixmapHeader returns a valid PixmapPtr which can
3148be used anywhere the server expects a pixmap, else
3149it returns NULL.  The pixmap should be released when no longer needed
3150(usually within the same function that allocated it)
3151with FreeScratchPixmapHeader.</para>
3152</section>
3153<section>
3154  <title>Windows</title>
3155<para>
3156A window is a visible, or potentially visible, rectangle on the screen.
3157DIX windowing functions maintain an internal n-ary tree data structure, which
3158represents the current relationships of the mapped windows.
3159Windows that are contained in another window are children of that window and
3160are clipped to the boundaries of the parent.
3161The root window in the tree is the window for the entire screen.
3162Sibling windows constitute a doubly-linked list; the parent window has a pointer
3163to the head and tail of this list.
3164Each child also has a pointer to its parent.</para>
3165<para>
3166The border of a window is drawn by a DDX procedure when DIX requests that it
3167be drawn.  The contents of the window is drawn by the client through
3168requests to the server.</para>
3169<para>
3170Window painting is orchestrated through an expose event system.
3171When a region is exposed,
3172DIX generates an expose event, telling the client to repaint the window and
3173passing the region that is the minimal area needed to be repainted.</para>
3174<para>
3175As a favor to clients, the server may retain
3176the output to the hidden parts of windows
3177in off-screen memory; this is called "backing store".
3178When a part of such a window becomes exposed, it
3179can quickly move pixels into place instead of
3180triggering an expose event and waiting for a client on the other
3181end of the network to respond.
3182Even if the network response is insignificant, the time to
3183intelligently paint a section of a window is usually more than
3184the time to just copy already-painted sections.
3185At best, the repainting involves blanking out the area to a background color,
3186which will take about the
3187same amount of time.
3188In this way, backing store can dramatically increase the
3189performance of window moves.</para>
3190<para>
3191On the other hand, backing store can be quite complex, because
3192all graphics drawn to hidden areas must be intercepted and redirected
3193to the off-screen window sections.
3194Not only can this be complicated for the server programmer,
3195but it can also impact window painting performance.
3196The backing store implementation can choose, at any time, to
3197forget pieces of backing that are written into, relying instead upon
3198expose events to repaint for simplicity.</para>
3199<para>
3200In X, the decision to use the backing-store scheme is made
3201by you, the server implementor.  The sample server implements
3202backing store "for free" by reusing the infrastructure for the Composite
3203extension.  As a side effect, it treats the WhenMapped and Always hints
3204as equivalent.  However, it will never forget pixel contents when the
3205window is mapped.</para>
3206<para>
3207When a window operation is requested by the client,
3208such as a window being created or moved,
3209a new state is computed.
3210During this transition, DIX informs DDX what rectangles in what windows are about to
3211become obscured and what rectangles in what windows have become exposed.
3212This provides a hook for the implementation of backing store.
3213If DDX is unable to restore exposed regions, DIX generates expose
3214events to the client.
3215It is then the client's responsibility to paint the
3216window parts that were exposed but not restored.</para>
3217<para>
3218If a window is resized, pixels sometimes need to be
3219moved, depending upon
3220the application.
3221The client can request "Gravity" so that
3222certain blocks of the window are
3223moved as a result of a resize.
3224For instance, if the window has controls or other items
3225that always hang on the edge of the
3226window, and that edge is moved as a result of the resize,
3227then those pixels should be moved
3228to avoid having the client repaint it.
3229If the client needs to repaint it anyway, such an operation takes
3230time, so it is desirable
3231for the server to approximate the appearance of the window as best
3232it can while waiting for the client
3233to do it perfectly.
3234Gravity is used for that, also.</para>
3235<para>
3236The window has several fields used in drawing
3237operations:
3238<itemizedlist>
3239<listitem><para>
3240clipList - This region, in conjunction with
3241the client clip region in the gc, is used to clip output.
3242clipList has the window's children subtracted from it, in addition to pieces of sibling windows
3243that overlap this window.  To get the list with the
3244children included (subwindow-mode is IncludeInferiors),
3245the routine NotClippedByChildren(pWin) returns the unclipped region.</para></listitem>
3246<listitem><para>
3247borderClip is the region used by CopyWindow and
3248includes the area of the window, its children, and the border, but with the
3249overlapping areas of sibling children removed.</para></listitem>
3250</itemizedlist>
3251Most of the other fields are for DIX use only.</para>
3252<section>
3253<title>Window Procedures in the ScreenRec</title>
3254<para>
3255You should implement
3256all of the following procedures and store pointers to them in the screen record.</para>
3257<para>
3258The device-independent portion of the server "owns" the window tree.
3259However, clever hardware might want to know the relationship of
3260mapped windows.  There are pointers to procedures
3261in the ScreenRec data structure that are called to give the hardware
3262a chance to update its internal state.  These are helpers and
3263hints to DDX only;
3264they do not change the window tree, which is only changed by DIX.</para>
3265<para>
3266<blockquote><programlisting>
3267
3268	Bool pScreen->CreateWindow(pWin)
3269		WindowPtr pWin;
3270
3271</programlisting></blockquote>
3272This routine is a hook for when DIX creates a window.
3273It should fill in the "Window Procedures in the WindowRec" below
3274and also allocate the devPrivate block for it.</para>
3275<para>
3276See Xserver/fb/fbwindow.c for the sample server implementation.</para>
3277<para>
3278<blockquote><programlisting>
3279
3280	Bool pScreen->DestroyWindow(pWin);
3281		WindowPtr pWin;
3282
3283</programlisting></blockquote>
3284This routine is a hook for when DIX destroys a window.
3285It should deallocate the devPrivate block for it and any other blocks that need
3286to be freed, besides doing other cleanup actions.</para>
3287<para>
3288See Xserver/fb/fbwindow.c for the sample server implementation.</para>
3289<para>
3290<blockquote><programlisting>
3291
3292	Bool pScreen->PositionWindow(pWin, x, y);
3293		WindowPtr pWin;
3294		int x, y;
3295
3296</programlisting></blockquote>
3297This routine is a hook for when DIX moves or resizes a window.
3298It should do whatever private operations need to be done when a window is moved or resized.
3299For instance, if DDX keeps a pixmap tile used for drawing the background
3300or border, and it keeps the tile rotated such that it is longword
3301aligned to longword locations in the frame buffer, then you should rotate your tiles here.
3302The actual graphics involved in moving the pixels on the screen and drawing the
3303border are handled by CopyWindow(), below.</para>
3304<para>
3305See Xserver/fb/fbwindow.c for the sample server implementation.</para>
3306<para>
3307<blockquote><programlisting>
3308
3309	Bool pScreen->RealizeWindow(pWin);
3310		WindowPtr pWin;
3311
3312	Bool  pScreen->UnrealizeWindow(pWin);
3313		WindowPtr pWin;
3314
3315</programlisting></blockquote>
3316These routines are hooks for when DIX maps (makes visible) and unmaps
3317(makes invisible) a window.  It should do whatever private operations
3318need to be done when these happen, such as allocating or deallocating
3319structures that are only needed for visible windows.  RealizeWindow
3320does NOT draw the window border, background or contents;
3321UnrealizeWindow does NOT erase the window or generate exposure events
3322for underlying windows; this is taken care of by DIX.  DIX does,
3323however, call PaintWindowBackground() and PaintWindowBorder() to
3324perform some of these.</para>
3325<para>
3326<blockquote><programlisting>
3327
3328	Bool pScreen->ChangeWindowAttributes(pWin, vmask)
3329		WindowPtr pWin;
3330		unsigned long vmask;
3331
3332</programlisting></blockquote>
3333ChangeWindowAttributes is called whenever DIX changes window
3334attributes, such as the size, front-to-back ordering, title, or
3335anything of lesser severity that affects the window itself.  The
3336sample server implements this routine.  It computes accelerators for
3337quickly putting up background and border tiles.  (See description of
3338the set of routines stored in the WindowRec.)</para>
3339<para>
3340<blockquote><programlisting>
3341
3342	int pScreen->ValidateTree(pParent,  pChild, kind)
3343		WindowPtr pParent, pChild;
3344		VTKind kind;
3345
3346</programlisting></blockquote>
3347ValidateTree calculates the clipping region for the parent window and
3348all of its children.  This routine must be provided. The sample server
3349has a machine-independent version in Xserver/mi/mivaltree.c.  This is
3350a very difficult routine to replace.</para>
3351<para>
3352<blockquote><programlisting>
3353
3354	void pScreen->PostValidateTree(pParent,  pChild, kind)
3355		WindowPtr pParent, pChild;
3356		VTKind kind;
3357
3358</programlisting></blockquote>
3359If this routine is not NULL, DIX calls it shortly after calling
3360ValidateTree, passing it the same arguments.  This is useful for
3361managing multi-layered framebuffers.
3362The sample server sets this to NULL.</para>
3363<para>
3364<blockquote><programlisting>
3365
3366	void pScreen->WindowExposures(pWin, pRegion, pBSRegion)
3367		WindowPtr pWin;
3368		RegionPtr pRegion;
3369		RegionPtr pBSRegion;
3370
3371</programlisting></blockquote>
3372The WindowExposures() routine
3373paints the border and generates exposure events for the window.
3374pRegion is an unoccluded region of the window, and pBSRegion is an
3375occluded region that has backing store.
3376Since exposure events include a rectangle describing what was exposed,
3377this routine may have to send back a series of exposure events, one for
3378each rectangle of the region.
3379The count field in the expose event is a hint to the
3380client as to the number of
3381regions that are after this one.
3382This routine must be provided. The sample
3383server has a machine-independent version in Xserver/mi/miexpose.c.</para>
3384<para>
3385<blockquote><programlisting>
3386
3387	void pScreen->ClipNotify (pWin, dx, dy)
3388		WindowPtr pWin;
3389		int dx, dy;
3390
3391</programlisting></blockquote>
3392Whenever the cliplist for a window is changed, this function is called to
3393perform whatever hardware manipulations might be necessary.  When called,
3394the clip list and border clip regions in the window are set to the new
3395values.  dx,dy are the distance that the window has been moved (if at all).</para>
3396</section>
3397<section>
3398  <title>Window Painting Procedures</title>
3399<para>
3400In addition to the procedures listed above, there are two routines which
3401manipulate the actual window image directly.
3402In the sample server, mi implementations will work for
3403most purposes and fb routines speed up situations, such
3404as solid backgrounds/borders or tiles that are 8, 16 or 32 pixels square.</para>
3405<para>
3406<blockquote><programlisting>
3407
3408	void pScreen->ClearToBackground(pWin, x, y, w, h, generateExposures);
3409		WindowPtr pWin;
3410		int x, y, w, h;
3411		Bool generateExposures;
3412
3413</programlisting></blockquote>
3414This routine is called on a window in response to a ClearToBackground request
3415from the client.
3416This request has two different but related functions, depending upon generateExposures.</para>
3417<para>
3418If generateExposures is true, the client is declaring that the given rectangle
3419on the window is incorrectly painted and needs to be repainted.
3420The sample server implementation calculates the exposure region
3421and hands it to the DIX procedure HandleExposures(), which
3422calls the WindowExposures() routine, below, for the window
3423and all of its child windows.</para>
3424<para>
3425If generateExposures is false, the client is trying to simply erase part
3426of the window to the background fill style.
3427ClearToBackground should write the background color or tile to the
3428rectangle in question (probably using PaintWindowBackground).
3429If w or h is zero, it clears all the way to the right or lower edge of the window.</para>
3430<para>
3431The sample server implementation is in Xserver/mi/miwindow.c.</para>
3432<para>
3433<blockquote><programlisting>
3434
3435	void pScreen->CopyWindow(pWin, oldpt, oldRegion);
3436		WindowPtr pWin;
3437		DDXPointRec oldpt;
3438		RegionPtr oldRegion;
3439
3440</programlisting></blockquote>
3441CopyWindow is called when a window is moved, and graphically moves to
3442pixels of a window on the screen.  It should not change any other
3443state within DDX (see PositionWindow(), above).</para>
3444<para>
3445oldpt is the old location of the upper-left corner.  oldRegion is the
3446old region it is coming from.  The new location and new region is
3447stored in the WindowRec.  oldRegion might modified in place by this
3448routine (the sample implementation does this).</para>
3449<para>
3450CopyArea could be used, except that this operation has more
3451complications.  First of all, you do not want to copy a rectangle onto
3452a rectangle.  The original window may be obscured by other windows,
3453and the new window location may be similarly obscured.  Second, some
3454hardware supports multiple windows with multiple depths, and your
3455routine needs to take care of that.</para>
3456<para>
3457The pixels in oldRegion (with reference point oldpt) are copied to the
3458window's new region (pWin->borderClip).  pWin->borderClip is gotten
3459directly from the window, rather than passing it as a parameter.</para>
3460<para>
3461The sample server implementation is in Xserver/fb/fbwindow.c.</para>
3462</section>
3463<section>
3464<title>Screen Operations for Multi-Layered Framebuffers</title>
3465<para>
3466The following screen functions are useful if you have a framebuffer with
3467multiple sets of independent bit planes, e.g. overlays or underlays in
3468addition to the "main" planes.  If you have a simple single-layer
3469framebuffer, you should probably use the mi versions of these routines
3470in mi/miwindow.c.  This can be easily accomplished by calling miScreenInit.</para>
3471<para>
3472<blockquote><programlisting>
3473
3474    void pScreen->MarkWindow(pWin)
3475	WindowPtr pWin;
3476
3477</programlisting></blockquote>
3478This formerly dix function MarkWindow has moved to ddx and is accessed
3479via this screen function.  This function should store something,
3480usually a pointer to a device-dependent structure, in pWin->valdata so
3481that ValidateTree has the information it needs to validate the window.</para>
3482<para>
3483<blockquote><programlisting>
3484
3485    Bool pScreen->MarkOverlappedWindows(parent, firstChild, ppLayerWin)
3486	WindowPtr parent;
3487	WindowPtr firstChild;
3488	WindowPtr * ppLayerWin;
3489
3490</programlisting></blockquote>
3491This formerly dix function MarkWindow has moved to ddx and is accessed
3492via this screen function.  In the process, it has grown another
3493parameter: ppLayerWin, which is filled in with a pointer to the window
3494at which save under marking and ValidateTree should begin.  In the
3495single-layered framebuffer case, pLayerWin == pWin.</para>
3496<para>
3497<blockquote><programlisting>
3498
3499    Bool pScreen->ChangeSaveUnder(pLayerWin, firstChild)
3500	WindowPtr pLayerWin;
3501	WindowPtr firstChild;
3502
3503</programlisting></blockquote>
3504The dix functions ChangeSaveUnder and CheckSaveUnder have moved to ddx and
3505are accessed via this screen function.  pLayerWin should be the window
3506returned in the ppLayerWin parameter of MarkOverlappedWindows.  The function
3507may turn on backing store for windows that might be covered, and may partially
3508turn off backing store for windows.  It returns TRUE if PostChangeSaveUnder
3509needs to be called to finish turning off backing store.</para>
3510<para>
3511<blockquote><programlisting>
3512
3513    void pScreen->PostChangeSaveUnder(pLayerWin, firstChild)
3514	WindowPtr pLayerWin;
3515	WindowPtr firstChild;
3516
3517</programlisting></blockquote>
3518The dix function DoChangeSaveUnder has moved to ddx and is accessed via
3519this screen function.  This function completes the job of turning off
3520backing store that was started by ChangeSaveUnder.</para>
3521<para>
3522<blockquote><programlisting>
3523
3524    void pScreen->MoveWindow(pWin, x, y, pSib, kind)
3525	WindowPtr pWin;
3526	int x;
3527	int y;
3528	WindowPtr pSib;
3529	VTKind kind;
3530
3531</programlisting></blockquote>
3532The formerly dix function MoveWindow has moved to ddx and is accessed via
3533this screen function.  The new position of the window is given by
3534x,y.  kind is VTMove if the window is only moving, or VTOther if
3535the border is also changing.</para>
3536<para>
3537<blockquote><programlisting>
3538
3539    void pScreen->ResizeWindow(pWin, x, y, w, h, pSib)
3540	WindowPtr pWin;
3541	int x;
3542	int y;
3543	unsigned int w;
3544	unsigned int h;
3545	WindowPtr pSib;
3546
3547</programlisting></blockquote>
3548The formerly dix function SlideAndSizeWindow has moved to ddx and is accessed via
3549this screen function.  The new position is given by x,y.  The new size
3550is given by w,h.</para>
3551<para>
3552<blockquote><programlisting>
3553
3554    WindowPtr pScreen->GetLayerWindow(pWin)
3555	WindowPtr pWin
3556
3557</programlisting></blockquote>
3558This is a new function which returns a child of the layer parent of pWin.</para>
3559<para>
3560<blockquote><programlisting>
3561
3562    void pScreen->HandleExposures(pWin)
3563	WindowPtr pWin;
3564
3565</programlisting></blockquote>
3566The formerly dix function HandleExposures has moved to ddx and is accessed via
3567this screen function.  This function is called after ValidateTree and
3568uses the information contained in valdata to send exposures to windows.</para>
3569<para>
3570<blockquote><programlisting>
3571
3572    void pScreen->ReparentWindow(pWin, pPriorParent)
3573	WindowPtr pWin;
3574	WindowPtr pPriorParent;
3575
3576</programlisting></blockquote>
3577This function will be called when a window is reparented.  At the time of
3578the call, pWin will already be spliced into its new position in the
3579window tree, and pPriorParent is its previous parent.  This function
3580can be NULL.</para>
3581<para>
3582<blockquote><programlisting>
3583
3584    void pScreen->SetShape(pWin)
3585	WindowPtr pWin;
3586
3587</programlisting></blockquote>
3588The formerly dix function SetShape has moved to ddx and is accessed via
3589this screen function.  The window's new shape will have already been
3590stored in the window when this function is called.</para>
3591<para>
3592<blockquote><programlisting>
3593
3594    void pScreen->ChangeBorderWidth(pWin, width)
3595	WindowPtr pWin;
3596	unsigned int width;
3597
3598</programlisting></blockquote>
3599The formerly dix function ChangeBorderWidth has moved to ddx and is accessed via
3600this screen function.  The new border width is given by width.</para>
3601<para>
3602<blockquote><programlisting>
3603
3604    void pScreen->MarkUnrealizedWindow(pChild, pWin, fromConfigure)
3605	WindowPtr pChild;
3606	WindowPtr pWin;
3607	Bool fromConfigure;
3608
3609</programlisting></blockquote>
3610This function is called for windows that are being unrealized as part of
3611an UnrealizeTree.  pChild is the window being unrealized, pWin is an
3612ancestor, and the fromConfigure value is simply propagated from UnrealizeTree.</para>
3613</section>
3614</section>
3615</section>
3616<section>
3617<title>Graphics Contexts and Validation</title>
3618<para>
3619This graphics context (GC) contains state variables such as foreground and
3620background pixel value (color), the current line style and width,
3621the current tile or stipple for pattern generation, the current font for text
3622generation, and other similar attributes.</para>
3623<para>
3624In many graphics systems, the equivalent of the graphics context and the
3625drawable are combined as one entity.
3626The main distinction between the two kinds of status is that a drawable
3627describes a writing surface and the writings that may have already been done
3628on it, whereas a graphics context describes the drawing process.
3629A drawable is like a chalkboard.
3630A GC is like a piece of chalk.</para>
3631<para>
3632Unlike many similar systems, there is no "current pen location."
3633Every graphic operation is accompanied by the coordinates where it is to happen.</para>
3634<para>
3635The GC also includes two vectors of procedure pointers, the first
3636operate on the GC itself and are called GC funcs.  The second, called
3637GC ops,
3638contains the functions that carry out the fundamental graphic operations
3639such as drawing lines, polygons, arcs, text, and copying bitmaps.
3640The DDX graphic software can, if it
3641wants to be smart, change these two vectors of procedure pointers
3642to take advantage of hardware/firmware in the server machine, which can do
3643a better job under certain circumstances.  To reduce the amount of memory
3644consumed by each GC, it is wise to create a few "boilerplate" GC ops vectors
3645which can be shared by every GC which matches the constraints for that set.
3646Also, it is usually reasonable to have every GC created by a particular
3647module to share a common set of GC funcs.  Samples of this sort of
3648sharing can be seen in fb/fbgc.c.</para>
3649<para>
3650The DDX software is notified any time the client (or DIX) uses a changed GC.
3651For instance, if the hardware has special support for drawing fixed-width
3652fonts, DDX can intercept changes to the current font in a GC just before
3653drawing is done.  It can plug into either a fixed-width procedure that makes
3654the hardware draw characters, or a variable-width procedure that carefully
3655lays out glyphs by hand in software, depending upon the new font that is
3656selected.</para>
3657<para>
3658A definition of these structures can be found in the file
3659Xserver/include/gcstruct.h.</para>
3660<para>
3661Also included in each GC is support for dynamic devPrivates, which the
3662DDX can use for any purpose (see <xref linkend="wrappers_and_privates"/> below).</para>
3663<para>
3664The DIX routines available for manipulating GCs are
3665CreateGC, ChangeGC, ChangeGCXIDs, CopyGC, SetClipRects, SetDashes, and FreeGC.
3666<blockquote><programlisting>
3667
3668	GCPtr CreateGC(pDrawable, mask, pval, pStatus)
3669	    DrawablePtr pDrawable;
3670	    BITS32 mask;
3671	    XID *pval;
3672	    int *pStatus;
3673
3674	int ChangeGC(client, pGC, mask, pUnion)
3675	    ClientPtr client;
3676	    GCPtr pGC;
3677	    BITS32 mask;
3678	    ChangeGCValPtr pUnion;
3679
3680	int ChangeGCXIDs(client, pGC, mask, pC32)
3681	    ClientPtr client;
3682	    GCPtr pGC;
3683	    BITS32 mask;
3684	    CARD32 *pC32;
3685
3686	int CopyGC(pgcSrc, pgcDst, mask)
3687	    GCPtr pgcSrc;
3688	    GCPtr pgcDst;
3689	    BITS32 mask;
3690
3691	int SetClipRects(pGC, xOrigin, yOrigin, nrects, prects, ordering)
3692	    GCPtr pGC;
3693	    int xOrigin, yOrigin;
3694	    int nrects;
3695	    xRectangle *prects;
3696	    int ordering;
3697
3698	SetDashes(pGC, offset, ndash, pdash)
3699	    GCPtr pGC;
3700	    unsigned offset;
3701	    unsigned ndash;
3702	    unsigned char *pdash;
3703
3704	int FreeGC(pGC, gid)
3705	    GCPtr pGC;
3706	    GContext gid;
3707
3708</programlisting></blockquote>
3709</para>
3710<para>
3711As a convenience, each Screen structure contains an array of
3712GCs that are preallocated, one at each depth the screen supports.
3713These are particularly useful in the mi code.  Two DIX routines
3714must be used to get these GCs:
3715<blockquote><programlisting>
3716
3717	GCPtr GetScratchGC(depth, pScreen)
3718	    int depth;
3719	    ScreenPtr pScreen;
3720
3721	FreeScratchGC(pGC)
3722	    GCPtr pGC;
3723
3724</programlisting></blockquote>
3725Always use these two routines, don't try to extract the scratch
3726GC yourself -- someone else might be using it, so a new one must
3727be created on the fly.</para>
3728<para>
3729If you need a GC for a very long time, say until the server is restarted,
3730you should not take one from the pool used by GetScratchGC, but should
3731get your own using CreateGC or CreateScratchGC.
3732This leaves the ones in the pool free for routines that only need it for
3733a little while and don't want to pay a heavy cost to get it.
3734<blockquote><programlisting>
3735
3736	GCPtr CreateScratchGC(pScreen, depth)
3737	    ScreenPtr pScreen;
3738	    int depth;
3739
3740</programlisting></blockquote>
3741NULL is returned if the GC cannot be created.
3742The GC returned can be freed with FreeScratchGC.</para>
3743<section>
3744  <title>Details of Operation</title>
3745<para>
3746At screen initialization, a screen must supply a GC creation procedure.
3747At GC creation, the screen must fill in GC funcs and GC ops vectors
3748(Xserver/include/gcstruct.h).  For any particular GC, the func vector
3749must remain constant, while the op vector may vary.  This invariant is to
3750ensure that Wrappers work correctly.</para>
3751<para>
3752When a client request is processed that results in a change
3753to the GC, the device-independent state of the GC is updated.
3754This includes a record of the state that changed.
3755Then the ChangeGC GC func is called.
3756This is useful for graphics subsystems that are able to process
3757state changes in parallel with the server CPU.
3758DDX may opt not to take any action at GC-modify time.
3759This is more efficient if multiple GC-modify requests occur
3760between draws using a given GC.</para>
3761<para>
3762Validation occurs at the first draw operation that specifies the GC after
3763that GC was modified.  DIX calls then the ValidateGC GC func.  DDX should
3764then update its internal state.  DDX internal state may be stored as one or
3765more of the following:  1) device private block on the GC; 2) hardware
3766state; 3) changes to the GC ops.</para>
3767<para>
3768The GC contains a serial number, which is loaded with a number fetched from
3769the window that was drawn into the last time the GC was used.  The serial
3770number in the drawable is changed when the drawable's
3771clipList or absCorner changes.  Thus, by
3772comparing the GC serial number with the drawable serial number, DIX can
3773force a validate if the drawable has been changed since the last time it
3774was used with this GC.</para>
3775<para>
3776In addition, the drawable serial number is always guaranteed to have the
3777most significant bit set to 0.  Thus, the DDX layer can set the most
3778significant bit of the serial number to 1 in a GC to force a validate the next time
3779the GC is used.  DIX also uses this technique to indicate that a change has
3780been made to the GC by way of a SetGC, a SetDashes or a SetClip request.</para>
3781</section>
3782<section>
3783  <title>GC Handling Routines</title>
3784<para>
3785The ScreenRec data structure has a pointer for
3786CreateGC().
3787<blockquote><programlisting>
3788
3789	Bool pScreen->CreateGC(pGC)
3790		GCPtr pGC;
3791</programlisting></blockquote>
3792This routine must fill in the fields of
3793a dynamically allocated GC that is passed in.
3794It does NOT allocate the GC record itself or fill
3795in the defaults; DIX does that.</para>
3796<para>
3797This must fill in both the GC funcs and ops; none of the drawing
3798functions will be called before the GC has been validated,
3799but the others (dealing with allocating of clip regions,
3800changing and destroying the GC, etc.) might be.</para>
3801<para>
3802The GC funcs vector contains pointers to 7
3803routines and a devPrivate field:
3804<blockquote><programlisting>
3805
3806	pGC->funcs->ChangeGC(pGC, changes)
3807		GCPtr pGC;
3808		unsigned long changes;
3809
3810</programlisting></blockquote>
3811This GC func is called immediately after a field in the GC is changed.
3812changes is a bit mask indicating the changed fields of the GC in this
3813request.</para>
3814<para>
3815The ChangeGC routine is useful if you have a system where
3816state-changes to the GC can be swallowed immediately by your graphics
3817system, and a validate is not necessary.</para>
3818<para>
3819<blockquote><programlisting>
3820
3821	pGC->funcs->ValidateGC(pGC, changes, pDraw)
3822		GCPtr pGC;
3823		unsigned long changes;
3824		DrawablePtr pDraw;
3825
3826</programlisting></blockquote>
3827ValidateGC is called by DIX just before the GC will be used when one
3828of many possible changes to the GC or the graphics system has
3829happened.  It can modify devPrivates data attached to the GC,
3830change the op vector, or change hardware according to the
3831values in the GC.  It may not change the device-independent portion of
3832the GC itself.</para>
3833<para>
3834In almost all cases, your ValidateGC() procedure should take the
3835regions that drawing needs to be clipped to and combine them into a
3836composite clip region, which you keep a pointer to in the private part
3837of the GC.  In this way, your drawing primitive routines (and whatever
3838is below them) can easily determine what to clip and where.  You
3839should combine the regions clientClip (the region that the client
3840desires to clip output to) and the region returned by
3841NotClippedByChildren(), in DIX.  An example is in Xserver/fb/fbgc.c.</para>
3842<para>
3843Some kinds of extension software may cause this routine to be called
3844more than originally intended; you should not rely on algorithms that
3845will break under such circumstances.</para>
3846<para>
3847See the Strategies document for more information on creatively using
3848this routine.</para>
3849<para>
3850<blockquote><programlisting>
3851
3852	pGC->funcs->CopyGC(pGCSrc, mask, pGCDst)
3853		GCPtr pGCSrc;
3854		unsigned long mask;
3855		GCPtr pGCDst;
3856
3857</programlisting></blockquote>
3858This routine is called by DIX when a GC is being copied to another GC.
3859This is for situations where dynamically allocated chunks of memory
3860are stored in the GC's dynamic devPrivates and need to be transferred to
3861the destination GC.</para>
3862<para>
3863<blockquote><programlisting>
3864
3865	pGC->funcs->DestroyGC(pGC)
3866		GCPtr pGC;
3867
3868</programlisting></blockquote>
3869This routine is called before the GC is destroyed for the
3870entity interested in this GC to clean up after itself.
3871This routine is responsible for freeing any auxiliary storage allocated.</para>
3872</section>
3873<section>
3874  <title>GC Clip Region Routines</title>
3875<para>
3876The GC clientClip field requires three procedures to manage it.  These
3877procedures are in the GC funcs vector.  The underlying principle is that dix
3878knows nothing about the internals of the clipping information, (except when
3879it has come from the client), and so calls ddX whenever it needs to copy,
3880set, or destroy such information.  It could have been possible for dix not
3881to allow ddX to touch the field in the GC, and require it to keep its own
3882copy in devPriv, but since clip masks can be very large, this seems like a
3883bad idea.  Thus, the server allows ddX to do whatever it wants to the
3884clientClip field of the GC, but requires it to do all manipulation itself.</para>
3885<para>
3886<blockquote><programlisting>
3887
3888	void pGC->funcs->ChangeClip(pGC, type, pValue, nrects)
3889		GCPtr pGC;
3890		int type;
3891		char *pValue;
3892		int nrects;
3893
3894</programlisting></blockquote>
3895This routine is called whenever the client changes the client clip
3896region.  The pGC points to the GC involved, the type tells what form
3897the region has been sent in.  If type is CT_NONE, then there is no
3898client clip.  If type is CT_UNSORTED, CT_YBANDED or CT_YXBANDED, then
3899pValue pointer to a list of rectangles, nrects long.  If type is
3900CT_REGION, then pValue pointer to a RegionRec from the mi region code.
3901If type is CT_PIXMAP pValue is a pointer to a pixmap.  (The defines
3902for CT_NONE, etc. are in Xserver/include/gc.h.)  This routine is
3903responsible for incrementing any necessary reference counts (e.g. for
3904a pixmap clip mask) for the new clipmask and freeing anything that
3905used to be in the GC's clipMask field.  The lists of rectangles passed
3906in can be freed with Xfree(), the regions can be destroyed with the
3907RegionDestroy field in the screen, and pixmaps can be destroyed by
3908calling the screen's DestroyPixmap function.  DIX and MI code expect
3909what they pass in to this to be freed or otherwise inaccessible, and
3910will never look inside what's been put in the GC.  This is a good
3911place to be wary of storage leaks.</para>
3912<para>
3913In the sample server, this routine transforms either the bitmap or the
3914rectangle list into a region, so that future routines will have a more
3915predictable starting point to work from.  (The validate routine must
3916take this client clip region and merge it with other regions to arrive
3917at a composite clip region before any drawing is done.)</para>
3918<para>
3919<blockquote><programlisting>
3920
3921	void pGC->funcs->DestroyClip(pGC)
3922		GCPtr pGC;
3923
3924</programlisting></blockquote>
3925This routine is called whenever the client clip region must be destroyed.
3926The pGC points to the GC involved.  This call should set the clipType
3927field of the GC to CT_NONE.
3928In the sample server, the pointer to the client clip region is set to NULL
3929by this routine after destroying the region, so that other software
3930(including ChangeClip() above) will recognize that there is no client clip region.</para>
3931<para>
3932<blockquote><programlisting>
3933
3934	void pGC->funcs->CopyClip(pgcDst, pgcSrc)
3935		GCPtr pgcDst, pgcSrc;
3936
3937</programlisting></blockquote>
3938This routine makes a copy of the clipMask and clipType from pgcSrc
3939into pgcDst.  It is responsible for destroying any previous clipMask
3940in pgcDst.  The clip mask in the source can be the same as the
3941clip mask in the dst (clients do the strangest things), so care must
3942be taken when destroying things.  This call is required because dix
3943does not know how to copy the clip mask from pgcSrc.</para>
3944</section>
3945</section>
3946<section>
3947  <title>Drawing Primitives</title>
3948<para>
3949The X protocol (rules for the byte stream that goes between client and server)
3950does all graphics using primitive
3951operations, which are called Drawing Primitives.
3952These include line drawing, area filling, arcs, and text drawing.
3953Your implementation must supply 16 routines
3954to perform these on your hardware.
3955(The number 16 is arbitrary.)</para>
3956<para>
3957More specifically, 16 procedure pointers are in each
3958GC op vector.
3959At any given time, ALL of them MUST point to a valid procedure that
3960attempts to do the operation assigned, although
3961the procedure pointers may change and may
3962point to different procedures to carry out the same operation.
3963A simple server will leave them all pointing to the same 16 routines, while
3964a more optimized implementation will switch each from one
3965procedure to another, depending upon what is most optimal
3966for the current GC and drawable.</para>
3967<para>
3968The sample server contains a considerable chunk of code called the
3969mi (machine independent)
3970routines, which serve as drawing primitive routines.
3971Many server implementations will be able to use these as-is,
3972because they work for arbitrary depths.
3973They make no assumptions about the formats of pixmaps
3974and frame buffers, since they call a set of routines
3975known as the "Pixblit Routines" (see next section).
3976They do assume that the way to draw is
3977through these low-level routines that apply pixel values rows at a time.
3978If your hardware or firmware gives more performance when
3979things are done differently, you will want to take this fact into account
3980and rewrite some or all of the drawing primitives to fit your needs.</para>
3981<section>
3982  <title>GC Components</title>
3983<para>
3984This section describes the fields in the GC that affect each drawing primitive.
3985The only primitive that is not affected is GetImage, which does not use a GC
3986because its destination is a protocol-style bit image.
3987Since each drawing primitive mirrors exactly the X protocol request of the
3988same name, you should refer to the X protocol specification document
3989for more details.</para>
3990<para>
3991ALL of these routines MUST CLIP to the
3992appropriate regions in the drawable.
3993Since there are many regions to clip to simultaneously,
3994your ValidateGC routine should combine these into a unified
3995clip region to which your drawing routines can quickly refer.
3996This is exactly what the fb routines supplied with the sample server
3997do.
3998The mi implementation passes responsibility for clipping while drawing
3999down to the Pixblit routines.</para>
4000<para>
4001Also, all of them must adhere to the current plane mask.
4002The plane mask has one bit for every bit plane in the drawable;
4003only planes with 1 bits in the mask are affected by any drawing operation.</para>
4004<para>
4005All functions except for ImageText calls must obey the alu function.
4006This is usually Copy, but could be any of the allowable 16 raster-ops.</para>
4007<para>
4008All of the functions, except for CopyArea, might use the current
4009foreground and background pixel values.
4010Each pixel value is 32 bits.
4011These correspond to foreground and background colors, but you have
4012to run them through the colormap to find out what color the pixel values
4013represent.  Do not worry about the color, just apply the pixel value.</para>
4014<para>
4015The routines that draw lines (PolyLine, PolySegment, PolyRect, and PolyArc)
4016use the line width, line style, cap style, and join style.
4017Line width is in pixels.
4018The line style specifies whether it is solid or dashed, and what kind of dash.
4019The cap style specifies whether Rounded, Butt, etc.
4020The join style specifies whether joins between joined lines are Miter, Round or Beveled.
4021When lines cross as part of the same polyline, they are assumed to be drawn once.
4022(See the X protocol specification for more details.)</para>
4023<para>
4024Zero-width lines are NOT meant to be really zero width; this is the client's way
4025of telling you that you can optimize line drawing with little regard to
4026the end caps and joins.
4027They are called "thin" lines and are meant to be one pixel wide.
4028These are frequently done in hardware or in a streamlined assembly language
4029routine.</para>
4030<para>
4031Lines with widths greater than zero, though, must all be drawn with the same
4032algorithm, because client software assumes that every jag on every
4033line at an angle will come at the same place.
4034Two lines that should have
4035one pixel in the space between them
4036(because of their distance apart and their widths) should have such a one-pixel line
4037of space between them if drawn, regardless of angle.</para>
4038<para>
4039The solid area fill routines (FillPolygon, PolyFillRect, PolyFillArc)
4040all use the fill rule, which specifies subtle interpretations of
4041what points are inside and what are outside of a given polygon.
4042The PolyFillArc routine also uses the arc mode, which specifies
4043whether to fill pie segments or single-edge slices of an ellipse.</para>
4044<para>
4045The line drawing, area fill, and PolyText routines must all
4046apply the correct "fill style."
4047This can be either a solid foreground color, a transparent stipple,
4048an opaque stipple, or a tile.
4049Stipples are bitmaps where the 1 bits represent that the foreground color is written,
4050and 0 bits represent that either the pixel is left alone (transparent) or that
4051the background color is written (opaque).
4052A tile is a pixmap of the full depth of the GC that is applied in its full glory to all areas.
4053The stipple and tile patterns can be any rectangular size, although some implementations
4054will be faster for certain sizes such as 8x8 or 32x32.
4055The mi implementation passes this responsibility down to the Pixblit routines.</para>
4056<para>
4057See the X protocol document for full details.
4058The description of the CreateGC request has a very good, detailed description of these
4059attributes.</para>
4060</section>
4061<section>
4062<title>The Primitives</title>
4063<para>
4064The Drawing Primitives are as follows:
4065
4066<blockquote><programlisting>
4067
4068	RegionPtr pGC->ops->CopyArea(src, dst, pGC, srcx, srcy, w, h, dstx, dsty)
4069		DrawablePtr dst, src;
4070		GCPtr pGC;
4071		int srcx, srcy, w, h, dstx, dsty;
4072
4073</programlisting></blockquote>
4074CopyArea copies a rectangle of pixels from one drawable to another of
4075the same depth.  To effect scrolling, this must be able to copy from
4076any drawable to itself, overlapped.  No squeezing or stretching is done
4077because the source and destination are the same size.  However,
4078everything is still clipped to the clip regions of the destination
4079drawable.</para>
4080<para>
4081If pGC->graphicsExposures is True, any portions of the destination which
4082were not valid in the source (either occluded by covering windows, or
4083outside the bounds of the drawable) should be collected together and
4084returned as a region (if this resultant region is empty, NULL can be
4085returned instead).  Furthermore, the invalid bits of the source are
4086not copied to the destination and (when the destination is a window)
4087are filled with the background tile.  The sample routine
4088miHandleExposures generates the appropriate return value and fills the
4089invalid area using pScreen->PaintWindowBackground.</para>
4090<para>
4091For instance, imagine a window that is partially obscured by other
4092windows in front of it.  As text is scrolled on your window, the pixels
4093that are scrolled out from under obscuring windows will not be
4094available on the screen to copy to the right places, and so an exposure
4095event must be sent for the client to correctly repaint them.  Of
4096course, if you implement backing store, you could do this without resorting
4097to exposure events.</para>
4098<para>
4099An example implementation is fbCopyArea() in Xserver/fb/fbcopy.c.</para>
4100<para>
4101<blockquote><programlisting>
4102
4103	RegionPtr pGC->ops->CopyPlane(src, dst, pGC, srcx, srcy, w, h, dstx, dsty, plane)
4104		DrawablePtr dst, src;
4105		GCPtr pGC;
4106		int srcx, srcy, w, h, dstx, dsty;
4107		unsigned long plane;
4108
4109</programlisting></blockquote>
4110CopyPlane must copy one plane of a rectangle from the source drawable
4111onto the destination drawable.  Because this routine only copies one
4112bit out of each pixel, it can copy between drawables of different
4113depths.  This is the only way of copying between drawables of
4114different depths, except for copying bitmaps to pixmaps and applying
4115foreground and background colors to it.  All other conditions of
4116CopyArea apply to CopyPlane too.</para>
4117<para>
4118An example implementation is fbCopyPlane() in
4119Xserver/fb/fbcopy.c.</para>
4120<para>
4121<blockquote><programlisting>
4122
4123	void pGC->ops->PolyPoint(dst, pGC, mode, n, pPoint)
4124		DrawablePtr dst;
4125		GCPtr pGC;
4126		int mode;
4127		int n;
4128		DDXPointPtr pPoint;
4129
4130</programlisting></blockquote>
4131PolyPoint draws a set of one-pixel dots (foreground color)
4132at the locations given in the array.
4133mode is one of the defined constants Origin (absolute coordinates) or Previous
4134(each coordinate is relative to the last).
4135Note that this does not use the background color or any tiles or stipples.</para>
4136<para>
4137Example implementations are fbPolyPoint() in Xserver/fb/fbpoint.c and
4138miPolyPoint in Xserver/mi/mipolypnt.c.</para>
4139<para>
4140<blockquote><programlisting>
4141
4142	void pGC->ops->Polylines(dst, pGC, mode, n, pPoint)
4143		DrawablePtr dst;
4144		GCPtr pGC;
4145		int mode;
4146		int n;
4147		DDXPointPtr pPoint;
4148
4149</programlisting></blockquote>
4150Similar to PolyPoint, Polylines draws lines between the locations given in the array.
4151Zero-width lines are NOT meant to be really zero width; this is the client's way of
4152telling you that you can maximally optimize line drawing with little regard to
4153the end caps and joins.
4154mode is one of the defined constants Previous or Origin, depending upon
4155whether the points are each relative to the last or are absolute.</para>
4156<para>
4157Example implementations are miWideLine() and miWideDash() in
4158mi/miwideline.c and miZeroLine() in mi/mizerline.c.</para>
4159<para>
4160<blockquote><programlisting>
4161
4162	void pGC->ops->PolySegment(dst, pGC, n, pPoint)
4163		DrawablePtr dst;
4164		GCPtr pGC;
4165		int n;
4166		xSegment *pSegments;
4167
4168</programlisting></blockquote>
4169PolySegments draws unconnected
4170lines between pairs of points in the array; the array must be of
4171even size; no interconnecting lines are drawn.</para>
4172<para>
4173An example implementation is miPolySegment() in mipolyseg.c.</para>
4174<para>
4175<blockquote><programlisting>
4176
4177	void pGC->ops->PolyRectangle(dst, pGC, n, pRect)
4178		DrawablePtr dst;
4179		GCPtr pGC;
4180		int n;
4181		xRectangle *pRect;
4182
4183</programlisting></blockquote>
4184PolyRectangle draws outlines of rectangles for each rectangle in the array.</para>
4185<para>
4186An example implementation is miPolyRectangle() in Xserver/mi/mipolyrect.c.</para>
4187<para>
4188<blockquote><programlisting>
4189
4190	void pGC->ops->PolyArc(dst, pGC, n, pArc)
4191		DrawablePtr dst;
4192		GCPtr pGC;
4193		int n;
4194		xArc*pArc;
4195
4196</programlisting></blockquote>
4197PolyArc draws connected conic arcs according to the descriptions in the array.
4198See the protocol specification for more details.</para>
4199<para>
4200Example implementations are miZeroPolyArc in Xserver/mi/mizerarc. and
4201miPolyArc() in Xserver/mi/miarc.c.</para>
4202<para>
4203<blockquote><programlisting>
4204
4205	void pGC->ops->FillPolygon(dst, pGC, shape, mode, count, pPoint)
4206		DrawablePtr dst;
4207		GCPtr pGC;
4208		int shape;
4209		int mode;
4210		int count;
4211		DDXPointPtr pPoint;
4212
4213</programlisting></blockquote>
4214FillPolygon fills a polygon specified by the points in the array
4215with the appropriate fill style.
4216If necessary, an extra border line is assumed between the starting and ending lines.
4217The shape can be used as a hint
4218to optimize filling; it indicates whether it is convex (all interior angles
4219less than 180), nonconvex (some interior angles greater than 180 but
4220border does not cross itself), or complex (border crosses itself).
4221You can choose appropriate algorithms or hardware based upon mode.
4222mode is one of the defined constants Previous or Origin, depending upon
4223whether the points are each relative to the last or are absolute.</para>
4224<para>
4225An example implementation is miFillPolygon() in Xserver/mi/mipoly.c.</para>
4226<para>
4227<blockquote><programlisting>
4228
4229	void pGC->ops->PolyFillRect(dst, pGC, n, pRect)
4230		DrawablePtr dst;
4231		GCPtr pGC;
4232		int n;
4233		xRectangle *pRect;
4234
4235</programlisting></blockquote>
4236PolyFillRect fills multiple rectangles.</para>
4237<para>
4238Example implementations are fbPolyFillRect() in Xserver/fb/fbfillrect.c and
4239miPolyFillRect() in Xserver/mi/mifillrct.c.</para>
4240<para>
4241<blockquote><programlisting>
4242
4243	void pGC->ops->PolyFillArc(dst, pGC, n, pArc)
4244		DrawablePtr dst;
4245		GCPtr pGC;
4246		int n;
4247		xArc *pArc;
4248
4249</programlisting></blockquote>
4250PolyFillArc fills a shape for each arc in the
4251list that is bounded by the arc and one or two
4252line segments with the current fill style.</para>
4253<para>
4254An example implementation is miPolyFillArc() in Xserver/mi/mifillarc.c.</para>
4255<para>
4256<blockquote><programlisting>
4257
4258	void pGC->ops->PutImage(dst, pGC, depth, x, y, w, h, leftPad, format, pBinImage)
4259		DrawablePtr dst;
4260		GCPtr pGC;
4261		int x, y, w, h;
4262		int format;
4263		char *pBinImage;
4264
4265</programlisting></blockquote>
4266PutImage copies a pixmap image into the drawable.  The pixmap image
4267must be in X protocol format (either Bitmap, XYPixmap, or ZPixmap),
4268and format tells the format.  (See the X protocol specification for
4269details on these formats).  You must be able to accept all three
4270formats, because the client gets to decide which format to send.
4271Either the drawable and the pixmap image have the same depth, or the
4272source pixmap image must be a Bitmap.  If a Bitmap, the foreground and
4273background colors will be applied to the destination.</para>
4274<para>
4275An example implementation is fbPutImage() in Xserver/fb/fbimage.c.</para>
4276<para>
4277<blockquote><programlisting>
4278
4279	void pScreen->GetImage(src, x, y, w, h, format, planeMask, pBinImage)
4280		 DrawablePtr src;
4281		 int x, y, w, h;
4282		 unsigned int format;
4283		 unsigned long planeMask;
4284		 char *pBinImage;
4285
4286</programlisting></blockquote>
4287GetImage copies the bits from the source drawable into
4288the destination pointer.  The bits are written into the buffer
4289according to the server-defined pixmap padding rules.
4290pBinImage is guaranteed to be big enough to hold all
4291the bits that must be written.</para>
4292<para>
4293This routine does not correspond exactly to the X protocol GetImage
4294request, since DIX has to break the reply up into buffers of a size
4295requested by the transport layer.  If format is ZPixmap, the bits are
4296written in the ZFormat for the depth of the drawable; if there is a 0
4297bit in the planeMask for a particular plane, all pixels must have the
4298bit in that plane equal to 0.  If format is XYPixmap, planemask is
4299guaranteed to have a single bit set; the bits should be written in
4300Bitmap format, which is the format for a single plane of an XYPixmap.</para>
4301<para>
4302An example implementation is miGetImage() in Xserver/mi/mibitblt.c.
4303<blockquote><programlisting>
4304
4305	void pGC->ops->ImageText8(pDraw, pGC, x, y, count, chars)
4306		DrawablePtr pDraw;
4307		GCPtr pGC;
4308		int x, y;
4309		int count;
4310		char *chars;
4311
4312</programlisting></blockquote>
4313ImageText8 draws text.  The text is drawn in the foreground color; the
4314background color fills the remainder of the character rectangles.  The
4315coordinates specify the baseline and start of the text.</para>
4316<para>
4317An example implementation is miImageText8() in Xserver/mi/mipolytext.c.</para>
4318<para>
4319<blockquote><programlisting>
4320
4321	int pGC->ops->PolyText8(pDraw, pGC, x, y, count, chars)
4322		DrawablePtr pDraw;
4323		GCPtr pGC;
4324		int x, y;
4325		int count;
4326		char *chars;
4327
4328</programlisting></blockquote>
4329PolyText8 works like ImageText8, except it draws with
4330the current fill style for special effects such as
4331shaded text.
4332See the X protocol specification for more details.</para>
4333<para>
4334An example implementation is miPolyText8() in Xserver/mi/mipolytext.c.</para>
4335<para>
4336<blockquote><programlisting>
4337
4338	int pGC->ops->PolyText16(pDraw, pGC, x, y, count, chars)
4339		DrawablePtr pDraw;
4340		GCPtr pGC;
4341		int x, y;
4342		int count;
4343		unsigned short *chars;
4344
4345	void pGC->ops->ImageText16(pDraw, pGC, x, y, count, chars)
4346		DrawablePtr pDraw;
4347		GCPtr pGC;
4348		int x, y;
4349		int count;
4350		unsigned short *chars;
4351
4352</programlisting></blockquote>
4353These two routines are the same as the "8" versions,
4354except that they are for 16-bit character codes (useful
4355for oriental writing systems).</para>
4356<para>
4357The primary difference is in the way the character information is
4358looked up.  The 8-bit and the 16-bit versions obviously have different
4359kinds of character values to look up; the main goal of the lookup is
4360to provide a pointer to the CharInfo structs for the characters to
4361draw and to pass these pointers to the Glyph routines.  Given a
4362CharInfo struct, lower-level software can draw the glyph desired with
4363little concern for other characteristics of the font.</para>
4364<para>
436516-bit character fonts have a row-and-column scheme, where the 2bytes
4366of the character code constitute the row and column in a square matrix
4367of CharInfo structs.  Each font has row and column minimum and maximum
4368values; the CharInfo structures form a two-dimensional matrix.</para>
4369<para>
4370Example implementations are miPolyText16() and
4371miImageText16() in Xserver/mi/mipolytext.c.</para>
4372<para>
4373See the X protocol specification for more details on these graphic operations.</para>
4374<para>
4375There is a hook in the GC ops, called LineHelper, that used to be used in the
4376sample implementation by the code for wide lines.  It no longer servers any
4377purpose in the sample servers, but still exists, #ifdef'ed by NEED_LINEHELPER,
4378in case someone needs it.</para>
4379</section>
4380</section>
4381<section>
4382  <title>Pixblit Procedures</title>
4383<para>
4384The Drawing Primitive functions must be defined for your server.
4385One possible way to do this is to use the mi routines from the sample server.
4386If you choose to use the mi routines (even part of them!) you must implement
4387these Pixblit routines.
4388These routines read and write pixel values
4389and deal directly with the image data.</para>
4390<para>
4391The Pixblit routines for the sample server are part of the "fb"
4392routines.  As with the mi routines, the fb routines are
4393portable but are not as portable as the mi routines.</para>
4394<para>
4395The fb subsystem is a depth-independent framebuffer core, capable of
4396operating at any depth from 1 to 32, based on the depth of the window
4397or pixmap it is currently operating on.  In particular, this means it
4398can support pixmaps of multiple depths on the same screen.  It supplies
4399both Pixblit routines and higher-level optimized implementations of the
4400Drawing Primitive routines.  It does make the assumption that the pixel
4401data it touches is available in the server's address space.</para>
4402<para>
4403In other words, if you have a "normal" frame buffer type display, you
4404can probably use the fb code, and the mi code.  If you
4405have a stranger hardware, you will have to supply your own Pixblit
4406routines, but you can use the mi routines on top of them.  If you have
4407better ways of doing some of the Drawing Primitive functions, then you
4408may want to supply some of your own Drawing Primitive routines.  (Even
4409people who write their own Drawing Primitives save at least some of
4410the mi code for certain special cases that their hardware or library
4411or fancy algorithm does not handle.)</para>
4412<para>
4413The client, DIX, and the machine-independent routines do not carry the
4414final responsibility of clipping.  They all depend upon the Pixblit
4415routines to do their clipping for them.  The rule is, if you touch the
4416frame buffer, you clip.</para>
4417<para>
4418(The higher level routines may decide to clip at a high level, but
4419this is only for increased performance and cannot substitute for
4420bottom-level clipping.  For instance, the mi routines, DIX, or the
4421client may decide to check all character strings to be drawn and chop
4422off all characters that would not be displayed.  If so, it must retain
4423the character on the edge that is partly displayed so that the Pixblit
4424routines can clip off precisely at the right place.)</para>
4425<para>
4426To make this easier, all of the reasons to clip can be combined into
4427one region in your ValidateGC procedure.  You take this composite clip
4428region with you into the Pixblit routines.  (The sample server does
4429this.)</para>
4430<para>
4431Also, FillSpans() has to apply tile and stipple patterns.  The
4432patterns are all aligned to the window origin so that when two people
4433write patches that are contiguous, they will merge nicely.  (Really,
4434they are aligned to the patOrg point in the GC.  This defaults to (0,
44350) but can be set by the client to anything.)</para>
4436<para>
4437However, the mi routines can translate (relocate) the points from
4438window-relative to screen-relative if desired.  If you set the
4439miTranslate field in the GC (set it in the CreateGC or ValidateGC
4440routine), then the mi output routines will translate all coordinates.
4441If it is false, then the coordinates will be passed window-relative.
4442Screens with no hardware translation will probably set miTranslate to
4443TRUE, so that geometry (e.g. polygons, rectangles) can be translated,
4444rather than having the resulting list of scanlines translated; this is
4445good because the list vertices in a drawing request will generally be
4446much smaller than the list of scanlines it produces.  Similarly,
4447hardware that does translation can set miTranslate to FALSE, and avoid
4448the extra addition per vertex, which can be (but is not always)
4449important for getting the highest possible performance.  (Contrast the
4450behavior of GetSpans, which is not expected to be called as often, and
4451so has different constraints.)  The miTranslate field is settable in
4452each GC, if , for example, you are mixing several kinds of
4453destinations (offscreen pixmaps, main memory pixmaps, backing store,
4454and windows), all of which have different requirements, on one screen.</para>
4455<para>
4456As with other drawing routines, there are fields in the GC to direct
4457higher code to the correct routine to execute for each function.  In
4458this way, you can optimize for special cases, for example, drawing
4459solids versus drawing stipples.</para>
4460<para>
4461The Pixblit routines are broken up into three sets.  The Span routines
4462simply fill in rows of pixels.  The Glyph routines fill in character
4463glyphs.  The PushPixels routine is a three-input bitblt for more
4464sophisticated image creation.</para>
4465<para>
4466It turns out that the Glyph and PushPixels routines actually have a
4467machine-independent implementation that depends upon the Span
4468routines.  If you are really pressed for time, you can use these
4469versions, although they are quite slow.</para>
4470<section>
4471<title>Span Routines</title>
4472<para>
4473For these routines, all graphic operations have been reduced to "spans."
4474A span is a horizontal row of pixels.
4475If you can design these routines which write into and read from
4476rows of pixels at a time, you can use the mi routines.</para>
4477<para>
4478Each routine takes
4479a destination drawable to draw into, a GC to use while drawing,
4480the number of spans to do, and two pointers to arrays that indicate the list
4481of starting points and the list of widths of spans.</para>
4482<para>
4483<blockquote><programlisting>
4484
4485	void pGC->ops->FillSpans(dst, pGC, nSpans, pPoints, pWidths, sorted)
4486		DrawablePtr dst;
4487		GCPtr pGC;
4488		int nSpans;
4489		DDXPointPtr pPoints;
4490		int *pWidths;
4491		int sorted;
4492
4493</programlisting></blockquote>
4494FillSpans should fill horizontal rows of pixels with
4495the appropriate patterns, stipples, etc.,
4496based on the values in the GC.
4497The starting points are in the array at pPoints; the widths are in pWidths.
4498If sorted is true, the scan lines are in increasing y order, in which case
4499you may be able to make assumptions and optimizations.</para>
4500<para>
4501GC components: alu, clipOrg, clientClip, and fillStyle.</para>
4502<para>
4503GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
4504(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
4505and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
4506<para>
4507<blockquote><programlisting>
4508
4509	void pGC->ops->SetSpans(pDrawable, pGC, pSrc, ppt, pWidths, nSpans, sorted)
4510		DrawablePtr pDrawable;
4511		GCPtr pGC;
4512		char *pSrc;
4513		DDXPointPtr pPoints;
4514		int *pWidths;
4515		int nSpans;
4516		int sorted;
4517
4518</programlisting></blockquote>
4519For each span, this routine should copy pWidths bits from pSrc to
4520pDrawable at pPoints using the raster-op from the GC.
4521If sorted is true, the scan lines are in increasing y order.
4522The pixels in pSrc are
4523padded according to the screen's padding rules.
4524These
4525can be used to support
4526interesting extension libraries, for example, shaded primitives.   It does not
4527use the tile and stipple.</para>
4528<para>
4529GC components: alu, clipOrg, and clientClip</para>
4530<para>
4531The above functions are expected to handle all modifiers in the current
4532GC.  Therefore, it is expedient to have
4533different routines to quickly handle common special cases
4534and reload the procedure pointers
4535at validate time, as with the other output functions.</para>
4536<para>
4537<blockquote><programlisting>
4538
4539	void pScreen->GetSpans(pDrawable, wMax, pPoints, pWidths, nSpans)
4540		DrawablePtr pDrawable;
4541		int wMax;
4542		DDXPointPtr pPoints;
4543		int *pWidths;
4544		int nSpans;
4545		char *pDst;
4546
4547</programlisting></blockquote>
4548For each span, GetSpans gets bits from the drawable starting at pPoints
4549and continuing for pWidths bits.
4550Each scanline returned will be server-scanline padded.
4551The routine can return NULL if memory cannot be allocated to hold the
4552result.</para>
4553<para>
4554GetSpans never translates -- for a window, the coordinates are already
4555screen-relative.  Consider the case of hardware that doesn't do
4556translation: the mi code that calls ddX will translate each shape
4557(rectangle, polygon,. etc.) before scan-converting it, which requires
4558many fewer additions that having GetSpans translate each span does.
4559Conversely, consider hardware that does translate: it can set its
4560translation point to (0, 0) and get each span, and the only penalty is
4561the small number of additions required to translate each shape being
4562scan-converted by the calling code.  Contrast the behavior of
4563FillSpans and SetSpans (discussed above under miTranslate), which are
4564expected to be used more often.</para>
4565<para>
4566Thus, the penalty to hardware that does hardware translation is
4567negligible, and code that wants to call GetSpans() is greatly
4568simplified, both for extensions and the machine-independent core
4569implementation.</para>
4570<section>
4571  <title>Glyph Routines</title>
4572<para>
4573The Glyph routines draw individual character glyphs for text drawing requests.</para>
4574<para>
4575You have a choice in implementing these routines.  You can use the mi
4576versions; they depend ultimately upon the span routines.  Although
4577text drawing will work, it will be very slow.</para>
4578<para>
4579<blockquote><programlisting>
4580
4581	void pGC->ops->PolyGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
4582		DrawablePtr pDrawable;
4583		GCPtr pGC;
4584		int x , y;
4585		unsigned int nglyph;
4586		CharInfoRec **ppci;		/* array of character info */
4587		pointer unused;			/* unused since R5 */
4588
4589</programlisting></blockquote>
4590GC components: alu, clipOrg, clientClip, font, and fillStyle.</para>
4591<para>
4592GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
4593(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
4594and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
4595<para>
4596<blockquote><programlisting>
4597
4598	void pGC->ops->ImageGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
4599		DrawablePtr pDrawable;
4600		GCPtr pGC;
4601		int x , y;
4602		unsigned int nglyph;
4603		CharInfoRec **ppci;	/* array of character info */
4604		pointer unused;		/* unused since R5 */
4605
4606</programlisting></blockquote>
4607GC components: clipOrg, clientClip, font, fgPixel, bgPixel</para>
4608<para>
4609These routines must copy the glyphs defined by the bitmaps in
4610pglyphBase and the font metrics in ppci to the DrawablePtr, pDrawable.
4611The poly routine follows all fill, stipple, and tile rules.  The image
4612routine simply blasts the glyph onto the glyph's rectangle, in
4613foreground and background colors.</para>
4614<para>
4615More precisely, the Image routine fills the character rectangle with
4616the background color, and then the glyph is applied in the foreground
4617color.  The glyph can extend outside of the character rectangle.
4618ImageGlyph() is used for terminal emulators and informal text purposes
4619such as button labels.</para>
4620<para>
4621The exact specification for the Poly routine is that the glyph is
4622painted with the current fill style.  The character rectangle is
4623irrelevant for this operation.  PolyText, at a higher level, includes
4624facilities for font changes within strings and such; it is to be used
4625for WYSIWYG word processing and similar systems.</para>
4626<para>
4627Both of these routines must clip themselves to the overall clipping region.</para>
4628<para>
4629Example implementations in mi are miPolyGlyphBlt() and
4630miImageGlyphBlt() in Xserver/mi/miglblt.c.</para>
4631</section>
4632<section>
4633<title>PushPixels routine</title>
4634<para>
4635The PushPixels routine writes the current fill style onto the drawable
4636in a certain shape defined by a bitmap.  PushPixels is equivalent to
4637using a second stipple.  You can thing of it as pushing the fillStyle
4638through a stencil.  PushPixels is not used by any of the mi rendering code,
4639but is used by the mi software cursor code.
4640<blockquote><para>
4641	Suppose the stencil is:	00111100
4642	and the stipple is:	10101010
4643	PushPixels result:	00101000
4644</para></blockquote>
4645</para>
4646<para>
4647You have a choice in implementing this routine.
4648You can use the mi version which depends ultimately upon FillSpans().
4649Although it will work, it will be slow.</para>
4650<para>
4651<blockquote><programlisting>
4652
4653	void pGC->ops->PushPixels(pGC, pBitMap, pDrawable, dx, dy, xOrg, yOrg)
4654		GCPtr pGC;
4655		PixmapPtr pBitMap;
4656		DrawablePtr pDrawable;
4657		int dx, dy, xOrg, yOrg;
4658
4659</programlisting></blockquote>
4660GC components: alu, clipOrg, clientClip, and fillStyle.</para>
4661<para>
4662GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
4663(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
4664and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
4665<para>
4666PushPixels applys the foreground color, tile, or stipple from the pGC
4667through a stencil onto pDrawable.  pBitMap points to a stencil (of
4668which we use an area dx wide by dy high), which is oriented over the
4669drawable at xOrg, yOrg.  Where there is a 1 bit in the bitmap, the
4670destination is set according to the current fill style.  Where there
4671is a 0 bit in the bitmap, the destination is left the way it is.</para>
4672<para>
4673This routine must clip to the overall clipping region.</para>
4674<para>
4675An Example implementation is miPushPixels() in Xserver/mi/mipushpxl.c.</para>
4676</section>
4677</section>
4678</section>
4679<section>
4680  <title>Shutdown Procedures</title>
4681<para>
4682<blockquote><programlisting>
4683	void AbortDDX()
4684	void ddxGiveUp()
4685</programlisting></blockquote>
4686Some hardware may require special work to be done before the server
4687exits so that it is not left in an intermediate state.  As explained
4688in the OS layer, FatalError() will call AbortDDX() just before
4689terminating the server.  In addition, ddxGiveUp() will be called just
4690before terminating the server on a "clean" death.  What AbortDDX() and
4691ddxGiveUP do is left unspecified, only that stubs must exist in the
4692ddx layer.  It is up to local implementors as to what they should
4693accomplish before termination.</para>
4694<section>
4695  <title>Command Line Procedures</title>
4696<para>
4697<blockquote><programlisting>
4698	int ddxProcessArgument(argc, argv, i)
4699	    int argc;
4700	    char *argv[];
4701	    int i;
4702
4703	void
4704	ddxUseMsg()
4705
4706</programlisting></blockquote>
4707You should write these routines to deal with device-dependent command line
4708arguments.  The routine ddxProcessArgument() is called with the command line,
4709and the current index into argv; you should return zero if the argument
4710is not a device-dependent one, and otherwise return a count of the number
4711of elements of argv that are part of this one argument.  For a typical
4712option (e.g., "-realtime"), you should return the value one.  This
4713routine gets called before checks are made against device-independent
4714arguments, so it is possible to peek at all arguments or to override
4715device-independent argument processing.  You can document the
4716device-dependent arguments in ddxUseMsg(), which will be
4717called from UseMsg() after printing out the device-independent arguments.</para>
4718</section>
4719</section>
4720<section id="wrappers_and_privates">
4721  <title>Wrappers and Privates</title>
4722<para>
4723Two new extensibility concepts have been developed for release 4, Wrappers
4724and devPrivates.  These replace the R3 GCInterest queues, which were not a
4725general enough mechanism for many extensions and only provided hooks into a
4726single data structure.  devPrivates have been revised substantially for
4727X.Org X server release 1.5, and updated again for the 1.9 release.</para>
4728<section>
4729  <title>devPrivates</title>
4730<para>
4731devPrivates provides a way to attach arbitrary private data to various server structures.
4732Any structure which contains a <structfield>devPrivates</structfield> field of
4733type <type>PrivateRec</type> supports this mechanism.  Some structures allow
4734allocating space for private data after some objects have been created, others
4735require all space allocations be registered before any objects of that type
4736are created.  <filename class="headerfile">Xserver/include/privates.h</filename>
4737lists which of these cases applies to each structure containing
4738<structfield>devPrivates</structfield>.</para>
4739
4740<para>
4741To request private space, use
4742<blockquote><programlisting>
4743	Bool dixRegisterPrivateKey(DevPrivateKey key, DevPrivateType type, unsigned size);
4744</programlisting></blockquote>
4745The first argument is a pointer to a <type>DevPrivateKeyRec</type> which
4746will serve as the unique identifier for the private data.  Typically this is
4747the address of a static <type>DevPrivateKeyRec</type> in your code.
4748The second argument is the class of objects for which this key will apply.
4749The third argument is the size of the space being requested, or
4750<constant>0</constant> to only allocate a pointer that the caller will manage.
4751If space is requested, this space will be automatically freed when the object
4752is destroyed.  Note that a call to <function>dixSetPrivate</function>
4753that changes the pointer value may cause the space to be unreachable by the caller, however it will still be automatically freed.
4754The function returns <literal>TRUE</literal> unless memory allocation fails.
4755If the function is called more than once on the same key, all calls must use
4756the same value for <type>size</type> or the server will abort.</para>
4757
4758<para>
4759To request per-screen private space in an object, use
4760<blockquote><programlisting>
4761	Bool dixRegisterScreenPrivateKey(DevScreenPrivateKey key, ScreenPtr pScreen, DevPrivateType type, unsigned size);
4762</programlisting></blockquote>
4763The <parameter>type</parameter> and <parameter>size</parameter> arguments are
4764the same as those to <function>dixRegisterPrivateKey</function> but this
4765function ensures the given <parameter>key</parameter> exists on objects of
4766the specified type with distinct storage for the given
4767<parameter>pScreen</parameter>. The key is usable on ScreenPrivate variants
4768that are otherwise equivalent to the following Private functions.</para>
4769
4770<para>
4771To attach a piece of private data to an object, use:
4772<blockquote><programlisting>
4773	void dixSetPrivate(PrivateRec **privates, const DevPrivateKey key, pointer val)
4774</programlisting></blockquote>
4775The first argument is the address of the <structfield>devPrivates</structfield>
4776field in the target structure.  This field is managed privately by the DIX
4777layer and should not be directly modified.  The second argument is a pointer
4778to the <type>DevPrivateKeyRec</type> which you registered with
4779<function>dixRegisterPrivateKey</function> or allocated with
4780<function>dixCreatePrivateKey</function>.  Only one
4781piece of data with a given key can be attached to an object, and in most cases
4782each key is specific to the type of object it was registered for.   (An
4783exception is the PRIVATE_XSELINUX class which applies to multiple object types.)
4784The third argument is the value to store.</para>
4785<para>
4786If private data with the given key is already associated with the object,
4787<function>dixSetPrivate</function> will overwrite the old value with the
4788new one.</para>
4789
4790<para>
4791To look up a piece of private data, use one of:
4792<blockquote><programlisting>
4793	pointer dixLookupPrivate(PrivateRec **privates, const DevPrivateKey key)
4794	pointer *dixLookupPrivateAddr(PrivateRec **privates, const DevPrivateKey key)
4795</programlisting></blockquote>
4796The first argument is the address of the <structfield>devPrivates</structfield> field
4797in the target structure.  The second argument is the key to look up.
4798If a non-zero size was given when the key was registered, or if private data
4799with the given key is already associated with the object, then
4800<function>dixLookupPrivate</function> will return the pointer value
4801while <function>dixLookupPrivateAddr</function>
4802will return the address of the pointer.</para>
4803
4804<para>
4805When implementing new server resource objects that support devPrivates, there
4806are four steps to perform:
4807Add a type value to the <type>DevPrivateType</type> enum in
4808<filename class="headerfile">Xserver/include/privates.h</filename>,
4809declare a field of type <type>PrivateRec *</type> in your structure;
4810initialize this field to <literal>NULL</literal> when creating any objects; and
4811when freeing any objects call the <function>dixFreePrivates</function> or
4812<function>dixFreeObjectWithPrivates</function> function.</para>
4813</section>
4814<section>
4815  <title>Wrappers</title>
4816<para>
4817Wrappers are not a body of code, nor an interface spec.  They are, instead,
4818a technique for hooking a new module into an existing calling sequence.
4819There are limitations on other portions of the server implementation which
4820make using wrappers possible; limits on when specific fields of data
4821structures may be modified.  They are intended as a replacement for
4822GCInterest queues, which were not general enough to support existing
4823modules; in particular software cursors needed more
4824control over the activity.  The general mechanism for using wrappers is:
4825<blockquote><programlisting>
4826privateWrapperFunction (object, ...)
4827	ObjectPtr	object;
4828{
4829	pre-wrapped-function-stuff ...
4830
4831	object->functionVector = dixLookupPrivate(&amp;object->devPrivates, privateKey);
4832	(*object->functionVector) (object, ...);
4833	/*
4834	 * this next line is occasionally required by the rules governing
4835	 * wrapper functions.  Always using it will not cause problems.
4836	 * Not using it when necessary can cause severe troubles.
4837	 */
4838	dixSetPrivate(&amp;object->devPrivates, privateKey, object->functionVector);
4839	object->functionVector = privateWrapperFunction;
4840
4841	post-wrapped-function-stuff ...
4842}
4843
4844privateInitialize (object)
4845	ObjectPtr	object;
4846{
4847	dixSetPrivate(&amp;object->devPrivates, privateKey, object->functionVector);
4848	object->functionVector = privateWrapperFunction;
4849}
4850</programlisting></blockquote>
4851</para>
4852<para>
4853Thus the privateWrapperFunction provides hooks for performing work both
4854before and after the wrapped function has been called; the process of
4855resetting the functionVector is called "unwrapping" while the process of
4856fetching the wrapped function and replacing it with the wrapping function
4857is called "wrapping".  It should be clear that GCInterest queues could
4858be emulated using wrappers.  In general, any function vectors contained in
4859objects can be wrapped, but only vectors in GCs and Screens have been tested.</para>
4860<para>
4861Wrapping screen functions is quite easy; each vector is individually
4862wrapped.  Screen functions are not supposed to change after initialization,
4863so rewrapping is technically not necessary, but causes no problems.</para>
4864<para>
4865Wrapping GC functions is a bit more complicated.  GC's have two tables of
4866function vectors, one hanging from gc->ops and the other from gc->funcs, which
4867should be initially wrapped from a CreateGC wrapper.  Wrappers should modify
4868only table pointers, not the contents of the tables, as they
4869may be shared by more than one GC (and, in the case of funcs, are probably
4870shared by all gcs).  Your func wrappers may change the GC funcs or ops
4871pointers, and op wrappers may change the GC op pointers but not the funcs.</para>
4872<para>
4873Thus, the rule for GC wrappings is: wrap the funcs from CreateGC and, in each
4874func wrapper, unwrap the ops and funcs, call down, and re-wrap.  In each op
4875wrapper, unwrap the ops, call down, and rewrap afterwards.  Note that in
4876re-wrapping you must save out the pointer you're replacing again.  This way the
4877chain will be maintained when wrappers adjust the funcs/ops tables they use.</para>
4878</section>
4879</section>
4880<section>
4881    <title>Work Queue</title>
4882<para>
4883To queue work for execution when all clients are in a stable state (i.e.
4884just before calling select() in WaitForSomething), call:
4885<blockquote><programlisting>
4886	Bool QueueWorkProc(function,client,closure)
4887		Bool		(*function)();
4888		ClientPtr	client;
4889		pointer		closure;
4890</programlisting></blockquote>
4891</para>
4892<para>
4893When the server is about to suspend itself, the given function will be
4894executed:
4895<blockquote><programlisting>
4896	(*function) (client, closure)
4897</programlisting></blockquote>
4898</para>
4899<para>
4900Neither client nor closure are actually used inside the work queue routines.</para>
4901</section>
4902</section>
4903<section>
4904  <title>Summary of Routines</title>
4905<para>
4906This is a summary of the routines discussed in this document.
4907The procedure names are in alphabetical order.
4908The Struct is the structure it is attached to; if blank, this
4909procedure is not attached to a struct and must be named as shown.
4910The sample server provides implementations in the following
4911categories.  Notice that many of the graphics routines have both
4912mi and fb implementations.</para>
4913<para>
4914<itemizedlist>
4915<listitem><para>dix	portable to all systems; do not attempt to rewrite (Xserver/dix)</para></listitem>
4916<listitem><para>os	routine provided in Xserver/os or Xserver/include/os.h</para></listitem>
4917<listitem><para>ddx	frame buffer dependent (examples in Xserver/fb)</para></listitem>
4918<listitem><para>mi	routine provided in Xserver/mi</para></listitem>
4919<listitem><para>hd	hardware dependent (examples in many Xserver/hw directories)</para></listitem>
4920<listitem><para>none	not implemented in sample implementation</para></listitem>
4921</itemizedlist>
4922</para>
4923	<table frame="all" id="routines-1">
4924	  <title>Server Routines (Page 1)</title>
4925	  <tgroup cols='3' align='left' colsep='1' rowsep='1'>
4926	    <thead>
4927	      <row>
4928		<entry>Procedure</entry>
4929		<entry>Port</entry>
4930		<entry>Struct</entry>
4931	      </row>
4932	    </thead>
4933	    <tbody>
4934<row><entry><function>ALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4935<row><entry><function>AbortDDX</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
4936<row><entry><function>AddCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4937<row><entry><function>AddEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4938<row><entry><function>AddInputDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4939<row><entry><function>AddScreen</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4940<row><entry><function>AdjustWaitForDelay</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4941<row><entry><function>Bell</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row>
4942<row><entry><function>ChangeClip</function></entry><entry><literal>mi</literal></entry><entry><para>GC func</para></entry></row>
4943<row><entry><function>ChangeGC</function></entry><entry><literal></literal></entry><entry><para>GC func</para></entry></row>
4944<row><entry><function>ChangeWindowAttributes</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4945<row><entry><function>ClearToBackground</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row>
4946<row><entry><function>ClientAuthorized</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4947<row><entry><function>ClientSignal</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4948<row><entry><function>ClientSleep</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4949<row><entry><function>ClientWakeup</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4950<row><entry><function>ClipNotify</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4951<row><entry><function>CloseScreen</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
4952<row><entry><function>ConstrainCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
4953<row><entry><function>CopyArea</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
4954<row><entry><function>CopyGCDest</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
4955<row><entry><function>CopyGCSource</function></entry><entry><literal>none</literal></entry><entry><para>GC func</para></entry></row>
4956<row><entry><function>CopyPlane</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
4957<row><entry><function>CopyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row>
4958<row><entry><function>CreateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4959<row><entry><function>CreateCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4960<row><entry><function>CreatePixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4961<row><entry><function>CreateScreenResources</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4962<row><entry><function>CreateWellKnowSockets</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4963<row><entry><function>CreateWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4964<row><entry><function>CursorLimits</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
4965<row><entry><function>DEALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4966<row><entry><function>DeleteCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4967<row><entry><function>DeleteCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4968<row><entry><function>DestroyClip</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
4969<row><entry><function>DestroyGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
4970<row><entry><function>DestroyPixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4971<row><entry><function>DestroyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4972<row><entry><function>DisplayCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
4973<row><entry><function>Error</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4974<row><entry><function>ErrorF</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4975<row><entry><function>FatalError</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4976<row><entry><function>FillPolygon</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
4977<row><entry><function>FillSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row>
4978<row><entry><function>FlushAllOutput</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4979<row><entry><function>FlushIfCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
4980<row><entry><function>FreeScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4981<row><entry><function>GetImage</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
4982<row><entry><function>GetMotionEvents</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row>
4983<row><entry><function>GetScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
4984<row><entry><function>GetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4985<row><entry><function>GetStaticColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
4986	    </tbody>
4987	  </tgroup>
4988	</table>
4989
4990	<table frame="all" id="routines-2">
4991	  <title>Server Routines (Page 2)</title>
4992	  <tgroup cols='3' align='left' colsep='1' rowsep='1'>
4993	    <thead>
4994	      <row>
4995		<entry>Procedure</entry>
4996		<entry>Port</entry>
4997		<entry>Struct</entry>
4998	      </row>
4999	    </thead>
5000	    <tbody>
5001<row><entry><function>ImageGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5002<row><entry><function>ImageText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5003<row><entry><function>ImageText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5004<row><entry><function>InitInput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
5005<row><entry><function>InitKeyboardDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5006<row><entry><function>InitOutput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
5007<row><entry><function>InitPointerDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5008<row><entry><function>InsertFakeRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5009<row><entry><function>InstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5010<row><entry><function>Intersect</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5011<row><entry><function>Inverse</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5012<row><entry><function>LegalModifier</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
5013<row><entry><function>LineHelper</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5014<row><entry><function>ListInstalledColormaps</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5015<row><entry><function>LookupKeyboardDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5016<row><entry><function>LookupPointerDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5017<row><entry><function>ModifyPixmapHeader</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5018<row><entry><function>NextAvailableClient</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5019<row><entry><function>OsInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5020<row><entry><function>PaintWindowBackground</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
5021<row><entry><function>PaintWindowBorder</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
5022<row><entry><function>PointerNonInterestBox</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5023<row><entry><function>PointInRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5024<row><entry><function>PolyArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5025<row><entry><function>PolyFillArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5026<row><entry><function>PolyFillRect</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5027<row><entry><function>PolyGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5028<row><entry><function>Polylines</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5029<row><entry><function>PolyPoint</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5030<row><entry><function>PolyRectangle</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5031<row><entry><function>PolySegment</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5032<row><entry><function>PolyText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5033<row><entry><function>PolyText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5034<row><entry><function>PositionWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5035<row><entry><function>ProcessInputEvents</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
5036<row><entry><function>PushPixels</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5037<row><entry><function>PutImage</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
5038<row><entry><function>QueryBestSize</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5039<row><entry><function>ReadRequestFromClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5040<row><entry><function>RealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5041<row><entry><function>RealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5042<row><entry><function>RealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5043<row><entry><function>RecolorCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5044<row><entry><function>RectIn</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5045<row><entry><function>RegionCopy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5046<row><entry><function>RegionCreate</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5047<row><entry><function>RegionDestroy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5048<row><entry><function>RegionEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5049<row><entry><function>RegionExtents</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5050<row><entry><function>RegionNotEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5051<row><entry><function>RegionReset</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5052<row><entry><function>ResolveColor</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5053	    </tbody>
5054	  </tgroup>
5055	</table>
5056
5057	<table frame="all" id="routines-3">
5058	  <title>Server Routines (Page 3)</title>
5059	  <tgroup cols='3' align='left' colsep='1' rowsep='1'>
5060	    <thead>
5061	      <row>
5062		<entry>Procedure</entry>
5063		<entry>Port</entry>
5064		<entry>Struct</entry>
5065	      </row>
5066	    </thead>
5067	    <tbody>
5068<row><entry><function>RemoveEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5069<row><entry><function>ResetCurrentRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5070<row><entry><function>SaveScreen</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5071<row><entry><function>SetCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5072<row><entry><function>SetCursorPosition</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5073<row><entry><function>SetInputCheck</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
5074<row><entry><function>SetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row>
5075<row><entry><function>StoreColors</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5076<row><entry><function>Subtract</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5077<row><entry><function>TimerCancel</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5078<row><entry><function>TimerCheck</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5079<row><entry><function>TimerForce</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5080<row><entry><function>TimerFree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5081<row><entry><function>TimerInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5082<row><entry><function>TimerSet</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5083<row><entry><function>TimeSinceLastInputEvent</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
5084<row><entry><function>TranslateRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5085<row><entry><function>UninstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5086<row><entry><function>Union</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5087<row><entry><function>UnrealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
5088<row><entry><function>UnrealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5089<row><entry><function>UnrealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
5090<row><entry><function>ValidateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
5091<row><entry><function>ValidateTree</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
5092<row><entry><function>WaitForSomething</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5093<row><entry><function>WindowExposures</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
5094<row><entry><function>WriteToClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5095<row><entry><function>Xalloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5096<row><entry><function>Xfree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5097<row><entry><function>Xrealloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
5098	    </tbody>
5099	  </tgroup>
5100	</table>
5101</section>
5102</article>
5103