diff options
31 files changed, 8356 insertions, 8316 deletions
diff --git a/mesalib/src/glsl/ast_function.cpp b/mesalib/src/glsl/ast_function.cpp index fad069135..463db9499 100644 --- a/mesalib/src/glsl/ast_function.cpp +++ b/mesalib/src/glsl/ast_function.cpp @@ -442,13 +442,21 @@ process_array_constructor(exec_list *instructions, ir_rvalue *ir = (ir_rvalue *) n;
ir_rvalue *result = ir;
- /* Apply implicit conversions (not the scalar constructor rules!) */
+ /* Apply implicit conversions (not the scalar constructor rules!). See
+ * the spec quote above. */
if (constructor_type->element_type()->is_float()) {
const glsl_type *desired_type =
glsl_type::get_instance(GLSL_TYPE_FLOAT,
ir->type->vector_elements,
ir->type->matrix_columns);
- result = convert_component(ir, desired_type);
+ if (result->type->can_implicitly_convert_to(desired_type)) {
+ /* Even though convert_component() implements the constructor
+ * conversion rules (not the implicit conversion rules), its safe
+ * to use it here because we already checked that the implicit
+ * conversion is legal.
+ */
+ result = convert_component(ir, desired_type);
+ }
}
if (result->type != constructor_type->element_type()) {
diff --git a/mesalib/src/glsl/glsl_types.cpp b/mesalib/src/glsl/glsl_types.cpp index 978e9a398..758fcf756 100644 --- a/mesalib/src/glsl/glsl_types.cpp +++ b/mesalib/src/glsl/glsl_types.cpp @@ -523,3 +523,19 @@ glsl_type::component_slots() const return 0;
}
}
+
+bool
+glsl_type::can_implicitly_convert_to(const glsl_type *desired) const
+{
+ if (this == desired)
+ return true;
+
+ /* There is no conversion among matrix types. */
+ if (this->matrix_columns > 1 || desired->matrix_columns > 1)
+ return false;
+
+ /* int and uint can be converted to float. */
+ return desired->is_float()
+ && this->is_integer()
+ && this->vector_elements == desired->vector_elements;
+}
diff --git a/mesalib/src/glsl/glsl_types.h b/mesalib/src/glsl/glsl_types.h index 87f57e7c7..048696693 100644 --- a/mesalib/src/glsl/glsl_types.h +++ b/mesalib/src/glsl/glsl_types.h @@ -224,6 +224,41 @@ struct glsl_type { */ unsigned component_slots() const; + /** + * \brief Can this type be implicitly converted to another? + * + * \return True if the types are identical or if this type can be converted + * to \c desired according to Section 4.1.10 of the GLSL spec. + * + * \verbatim + * From page 25 (31 of the pdf) of the GLSL 1.50 spec, Section 4.1.10 + * Implicit Conversions: + * + * In some situations, an expression and its type will be implicitly + * converted to a different type. The following table shows all allowed + * implicit conversions: + * + * Type of expression | Can be implicitly converted to + * -------------------------------------------------- + * int float + * uint + * + * ivec2 vec2 + * uvec2 + * + * ivec3 vec3 + * uvec3 + * + * ivec4 vec4 + * uvec4 + * + * There are no implicit array or structure conversions. For example, + * an array of int cannot be implicitly converted to an array of float. + * There are no implicit conversions between signed and unsigned + * integers. + * \endverbatim + */ + bool can_implicitly_convert_to(const glsl_type *desired) const; /** * Query whether or not a type is a scalar (non-vector and non-matrix). diff --git a/mesalib/src/glsl/ir_function.cpp b/mesalib/src/glsl/ir_function.cpp index 0f2f1a0ee..6cfc32cc2 100644 --- a/mesalib/src/glsl/ir_function.cpp +++ b/mesalib/src/glsl/ir_function.cpp @@ -24,73 +24,36 @@ #include "glsl_types.h" #include "ir.h" -int -type_compare(const glsl_type *a, const glsl_type *b) -{ - /* If the types are the same, they trivially match. - */ - if (a == b) - return 0; - - switch (a->base_type) { - case GLSL_TYPE_UINT: - case GLSL_TYPE_INT: - case GLSL_TYPE_BOOL: - /* There is no implicit conversion to or from integer types or bool. - */ - if ((a->is_integer() != b->is_integer()) - || (a->is_boolean() != b->is_boolean())) - return -1; - - /* FALLTHROUGH */ - - case GLSL_TYPE_FLOAT: - if ((a->vector_elements != b->vector_elements) - || (a->matrix_columns != b->matrix_columns)) - return -1; - - return 1; - - case GLSL_TYPE_SAMPLER: - case GLSL_TYPE_STRUCT: - /* Samplers and structures must match exactly. - */ - return -1; - - case GLSL_TYPE_ARRAY: - if ((b->base_type != GLSL_TYPE_ARRAY) - || (a->length != b->length)) - return -1; - - /* From GLSL 1.50 spec, page 27 (page 33 of the PDF): - * "There are no implicit array or structure conversions." - * - * If the comparison of the array element types detects that a conversion - * would be required, the array types do not match. - */ - return (type_compare(a->fields.array, b->fields.array) == 0) ? 0 : -1; - - case GLSL_TYPE_VOID: - case GLSL_TYPE_ERROR: - default: - /* These are all error conditions. It is invalid for a parameter to - * a function to be declared as error, void, or a function. - */ - return -1; - } - - /* This point should be unreachable. - */ - assert(0); -} - +typedef enum { + PARAMETER_LIST_NO_MATCH, + PARAMETER_LIST_EXACT_MATCH, + PARAMETER_LIST_INEXACT_MATCH, /*< Match requires implicit conversion. */ +} parameter_list_match_t; + +/** + * \brief Check if two parameter lists match. + * + * \param list_a Parameters of the function definition. + * \param list_b Actual parameters passed to the function. + * \see matching_signature() + */ -static int +/** + * \brief Check if two parameter lists match. + * + * \param list_a Parameters of the function definition. + * \param list_b Actual parameters passed to the function. + * \see matching_signature() + */ +static parameter_list_match_t parameter_lists_match(const exec_list *list_a, const exec_list *list_b) { const exec_node *node_a = list_a->head; const exec_node *node_b = list_b->head; - int total_score = 0; + + /* This is set to true if there is an inexact match requiring an implicit + * conversion. */ + bool inexact_match = false; for (/* empty */ ; !node_a->is_tail_sentinel() @@ -100,18 +63,17 @@ parameter_lists_match(const exec_list *list_a, const exec_list *list_b) * do not match. */ if (node_b->is_tail_sentinel()) - return -1; + return PARAMETER_LIST_NO_MATCH; const ir_variable *const param = (ir_variable *) node_a; const ir_instruction *const actual = (ir_instruction *) node_b; - /* Determine whether or not the types match. If the types are an - * exact match, the match score is zero. If the types don't match - * but the actual parameter can be coerced to the type of the declared - * parameter, the match score is one. - */ - int score; + if (param->type == actual->type) + continue; + + /* Try to find an implicit conversion from actual to param. */ + inexact_match = true; switch ((enum ir_variable_mode)(param->mode)) { case ir_var_auto: case ir_var_uniform: @@ -121,15 +83,17 @@ parameter_lists_match(const exec_list *list_a, const exec_list *list_b) * as uniform. */ assert(0); - return -1; + return PARAMETER_LIST_NO_MATCH; case ir_var_const_in: case ir_var_in: - score = type_compare(param->type, actual->type); + if (!actual->type->can_implicitly_convert_to(param->type)) + return PARAMETER_LIST_NO_MATCH; break; case ir_var_out: - score = type_compare(actual->type, param->type); + if (!param->type->can_implicitly_convert_to(actual->type)) + return PARAMETER_LIST_NO_MATCH; break; case ir_var_inout: @@ -137,17 +101,12 @@ parameter_lists_match(const exec_list *list_a, const exec_list *list_b) * there is int -> float but no float -> int), inout parameters must * be exact matches. */ - score = (type_compare(actual->type, param->type) == 0) ? 0 : -1; - break; + return PARAMETER_LIST_NO_MATCH; default: assert(false); + return PARAMETER_LIST_NO_MATCH; } - - if (score < 0) - return -1; - - total_score += score; } /* If all of the parameters from the other parameter list have been @@ -155,9 +114,12 @@ parameter_lists_match(const exec_list *list_a, const exec_list *list_b) * match. */ if (!node_b->is_tail_sentinel()) - return -1; + return PARAMETER_LIST_NO_MATCH; - return total_score; + if (inexact_match) + return PARAMETER_LIST_INEXACT_MATCH; + else + return PARAMETER_LIST_EXACT_MATCH; } @@ -181,18 +143,20 @@ ir_function::matching_signature(const exec_list *actual_parameters) ir_function_signature *const sig = (ir_function_signature *) iter.get(); - const int score = parameter_lists_match(& sig->parameters, - actual_parameters); - - /* If we found an exact match, simply return it */ - if (score == 0) + switch (parameter_lists_match(& sig->parameters, actual_parameters)) { + case PARAMETER_LIST_EXACT_MATCH: return sig; - - if (score > 0) { + case PARAMETER_LIST_INEXACT_MATCH: if (match == NULL) match = sig; else multiple_inexact_matches = true; + continue; + case PARAMETER_LIST_NO_MATCH: + continue; + default: + assert(false); + return NULL; } } diff --git a/mesalib/src/mesa/main/teximage.c b/mesalib/src/mesa/main/teximage.c index 7141efba1..1cca7d90e 100644 --- a/mesalib/src/mesa/main/teximage.c +++ b/mesalib/src/mesa/main/teximage.c @@ -1,6 +1,5 @@ /*
- * mesa 3-D graphics library
- * Version: 7.6
+ * Mesa 3-D graphics library
*
* Copyright (C) 1999-2008 Brian Paul All Rights Reserved.
* Copyright (C) 2009 VMware, Inc. All Rights Reserved.
@@ -556,8 +555,6 @@ _mesa_tex_target_to_face(GLenum target) * \param target texture target.
* \param level image level.
* \param texImage texture image.
- *
- * This was basically prompted by the introduction of cube maps.
*/
void
_mesa_set_tex_image(struct gl_texture_object *tObj,
@@ -709,15 +706,13 @@ get_proxy_target(GLenum target) /**
* Get the texture object that corresponds to the target of the given
- * texture unit.
+ * texture unit. The target should have already been checked for validity.
*
* \param ctx GL context.
* \param texUnit texture unit.
* \param target texture target.
*
* \return pointer to the texture object on success, or NULL on failure.
- *
- * \sa gl_texture_unit.
*/
struct gl_texture_object *
_mesa_select_tex_object(struct gl_context *ctx,
diff --git a/mesalib/src/mesa/main/texparam.c b/mesalib/src/mesa/main/texparam.c index 1e51782d7..1bb5b6e78 100644 --- a/mesalib/src/mesa/main/texparam.c +++ b/mesalib/src/mesa/main/texparam.c @@ -1266,12 +1266,13 @@ _mesa_GetTexParameterfv( GLenum target, GLenum pname, GLfloat *params ) break;
case GL_TEXTURE_CUBE_MAP_SEAMLESS:
- if (ctx->Extensions.AMD_seamless_cubemap_per_texture) {
- *params = (GLfloat) obj->Sampler.CubeMapSeamless;
- }
- else {
- error = GL_TRUE;
- }
+ if (ctx->Extensions.AMD_seamless_cubemap_per_texture) {
+ *params = (GLfloat) obj->Sampler.CubeMapSeamless;
+ }
+ else {
+ error = GL_TRUE;
+ }
+ break;
default:
error = GL_TRUE;
@@ -1441,6 +1442,7 @@ _mesa_GetTexParameteriv( GLenum target, GLenum pname, GLint *params ) else {
error = GL_TRUE;
}
+ break;
default:
; /* silence warnings */
diff --git a/pixman/pixman/pixman-radial-gradient.c b/pixman/pixman/pixman-radial-gradient.c index ecbca6f63..b6dd6b2c7 100644 --- a/pixman/pixman/pixman-radial-gradient.c +++ b/pixman/pixman/pixman-radial-gradient.c @@ -126,7 +126,7 @@ radial_compute_color (double a, t1 = (b - sqrtdiscr) * inva; /* - * The root that must be used if the biggest one that belongs + * The root that must be used is the biggest one that belongs * to the valid range ([0,1] for PIXMAN_REPEAT_NONE, any * solution that results in a positive radius otherwise). * @@ -162,7 +162,7 @@ radial_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) * Implementation of radial gradients following the PDF specification. * See section 8.7.4.5.4 Type 3 (Radial) Shadings of the PDF Reference * Manual (PDF 32000-1:2008 at the time of this writing). - * + * * In the radial gradient problem we are given two circles (c₁,r₁) and * (c₂,r₂) that define the gradient itself. * @@ -179,7 +179,7 @@ radial_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) * * The graphical result is the same as drawing the valid (radius > 0) * circles with increasing t in [-inf, +inf] (or in [0,1] if the gradient - * is not repeated) using SOURCE operatior composition. + * is not repeated) using SOURCE operator composition. * * It looks like a cone pointing towards the viewer if the ending circle * is smaller than the starting one, a cone pointing inside the page if @@ -190,14 +190,14 @@ radial_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) * in, compute the t values for that point, solving for t in: * * length((1-t)·c₁ + t·(c₂) - p) = (1-t)·r₁ + t·r₂ - * + * * Let's rewrite it in a simpler way, by defining some auxiliary * variables: * * cd = c₂ - c₁ * pd = p - c₁ * dr = r₂ - r₁ - * lenght(t·cd - pd) = r₁ + t·dr + * length(t·cd - pd) = r₁ + t·dr * * which actually means * @@ -223,7 +223,7 @@ radial_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) * B = pdx·cdx + pdy·cdy + r₁·dr * C = pdx² + pdy² - r₁² * At² - 2Bt + C = 0 - * + * * The solutions (unless the equation degenerates because of A = 0) are: * * t = (B ± ⎷(B² - A·C)) / A @@ -262,7 +262,7 @@ radial_get_scanline_narrow (pixman_iter_t *iter, const uint32_t *mask) { if (!pixman_transform_point_3d (image->common.transform, &v)) return iter->buffer; - + unit.vector[0] = image->common.transform->matrix[0][0]; unit.vector[1] = image->common.transform->matrix[1][0]; unit.vector[2] = image->common.transform->matrix[2][0]; @@ -468,4 +468,3 @@ pixman_image_create_radial_gradient (pixman_point_fixed_t * inner, return image; } - diff --git a/xorg-server/config/udev.c b/xorg-server/config/udev.c index c810b6b5e..63eb83605 100644 --- a/xorg-server/config/udev.c +++ b/xorg-server/config/udev.c @@ -251,14 +251,12 @@ wakeup_handler(pointer data, int err, pointer read_mask) return;
action = udev_device_get_action(udev_device);
if (action) {
- if (!strcmp(action, "add"))
- device_added(udev_device);
- else if (!strcmp(action, "remove"))
- device_removed(udev_device);
- else if (!strcmp(action, "change")) {
+ if (!strcmp(action, "add") || !strcmp(action, "change")) {
device_removed(udev_device);
device_added(udev_device);
}
+ else if (!strcmp(action, "remove"))
+ device_removed(udev_device);
}
udev_device_unref(udev_device);
}
@@ -283,6 +281,9 @@ config_udev_init(void) if (!udev_monitor)
return 0;
+ udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "input", NULL);
+ udev_monitor_filter_add_match_subsystem_devtype(udev_monitor, "tty", NULL); /* For Wacom serial devices */
+
if (udev_monitor_enable_receiving(udev_monitor)) {
ErrorF("config/udev: failed to bind the udev monitor\n");
return 0;
@@ -291,11 +292,20 @@ config_udev_init(void) enumerate = udev_enumerate_new(udev);
if (!enumerate)
return 0;
+
+ udev_enumerate_add_match_subsystem(enumerate, "input");
+ udev_enumerate_add_match_subsystem(enumerate, "tty");
+
udev_enumerate_scan_devices(enumerate);
devices = udev_enumerate_get_list_entry(enumerate);
udev_list_entry_foreach(device, devices) {
const char *syspath = udev_list_entry_get_name(device);
struct udev_device *udev_device = udev_device_new_from_syspath(udev, syspath);
+
+ /* Device might be gone by the time we try to open it */
+ if (!udev_device)
+ continue;
+
device_added(udev_device);
udev_device_unref(udev_device);
}
diff --git a/xorg-server/configure.ac b/xorg-server/configure.ac index 8422f565e..b91971498 100644 --- a/xorg-server/configure.ac +++ b/xorg-server/configure.ac @@ -1187,11 +1187,7 @@ if test "x$XKB_DFLT_RULES" = x; then case $host_os in
linux*)
dnl doesn't take AutoAddDevices into account, but whatever.
- if test "x$CONFIG_HAL" = xyes; then
- XKB_DFLT_RULES="evdev"
- else
- XKB_DFLT_RULES="base"
- fi
+ XKB_DFLT_RULES="evdev"
;;
*)
XKB_DFLT_RULES="base"
diff --git a/xorg-server/dix/main.c b/xorg-server/dix/main.c index b7cc4e497..2fc39b5f0 100644 --- a/xorg-server/dix/main.c +++ b/xorg-server/dix/main.c @@ -396,7 +396,7 @@ int main(int argc, char *argv[], char *envp[]) if (dispatchException & DE_TERMINATE)
{
- ddxGiveUp();
+ ddxGiveUp(EXIT_NO_ERROR);
break;
}
diff --git a/xorg-server/doc/Xserver-spec.xml b/xorg-server/doc/Xserver-spec.xml index a48e88754..b14e4897e 100644 --- a/xorg-server/doc/Xserver-spec.xml +++ b/xorg-server/doc/Xserver-spec.xml @@ -1,5102 +1,5102 @@ -<?xml version="1.0" encoding="ISO-8859-1"?>
-<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN"
- "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" [
- <!ENTITY % defs SYSTEM "/xserver/doc/xml/xserver.ent"> %defs;
-]>
-
-<article>
- <articleinfo>
- <author>
- <firstname>Susan</firstname><surname>Angebranndt</surname>
- <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
- </author>
- <author>
- <firstname>Raymond</firstname><surname>Drewry</surname>
- <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
- </author>
- <author>
- <firstname>Philip</firstname><surname>Karlton</surname>
- <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
- </author>
- <author>
- <firstname>Todd</firstname><surname>Newman</surname>
- <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation>
- </author>
- <author>
- <firstname>Bob</firstname><surname>Scheifler</surname>
- <affiliation><orgname>Massachusetts Institute of Technology</orgname></affiliation>
- </author>
- <author>
- <firstname>Keith</firstname><surname>Packard</surname>
- <affiliation><orgname>MIT X Consortium</orgname></affiliation>
- </author>
- <author>
- <firstname>David</firstname><othername>P.</othername><surname>Wiggins</surname>
- <affiliation><orgname>X Consortium</orgname></affiliation>
- </author>
- <author>
- <firstname>Jim</firstname><surname>Gettys</surname>
- <affiliation><orgname>X.org Foundation and Hewlett Packard</orgname></affiliation>
- </author>
- <publisher><publishername>The X.Org Foundation</publishername></publisher>
- <pubdate>&xserver.reldate;</pubdate>
- <releaseinfo>X server version &xserver.version;</releaseinfo>
- <title>Definition of the Porting Layer for the X v11 Sample Server</title>
- <titleabbrev>X Porting Layer</titleabbrev>
- <revhistory>
- <revision>
- <revnumber>1.0</revnumber>
- <date>27 Oct 2004</date>
- <authorinitials>sa</authorinitials>
- <revremark>Initial Version</revremark>
- </revision>
- <revision>
- <revnumber>1.1</revnumber>
- <date>27 Oct 2004</date>
- <authorinitials>bs</authorinitials>
- <revremark>Minor Revisions</revremark>
- </revision>
- <revision>
- <revnumber>2.0</revnumber>
- <date>27 Oct 2004</date>
- <authorinitials>kp</authorinitials>
- <revremark>Revised for Release 4 and 5</revremark>
- </revision>
- <revision>
- <revnumber>3.0</revnumber>
- <date>27 Oct 2004</date>
- <authorinitials>dpw</authorinitials>
- <revremark>Revised for Release 6</revremark>
- </revision>
- <revision>
- <revnumber>3.1</revnumber>
- <date>27 Oct 2004</date>
- <authorinitials>jg</authorinitials>
- <revremark>Revised for Release 6.8.2</revremark>
- </revision>
- <revision>
- <revnumber>3.2</revnumber>
- <date>17 Dec 2006</date>
- <authorinitials>efw</authorinitials>
- <revremark>DocBook conversion</revremark>
- </revision>
- <revision>
- <revnumber>3.3</revnumber>
- <date>17 Feb 2008</date>
- <authorinitials>aj</authorinitials>
- <revremark>Revised for backing store changes</revremark>
- </revision>
- <revision>
- <revnumber>3.4</revnumber>
- <date>31 Mar 2008</date>
- <authorinitials>efw</authorinitials>
- <revremark>Revised for devPrivates changes</revremark>
- </revision>
- <revision>
- <revnumber>3.5</revnumber>
- <date>July 2010</date>
- <authorinitials>ac</authorinitials>
- <revremark>Revised for Xorg 1.9 devPrivates changes
- and 1.8 CreateNewResourceType changes</revremark>
- </revision>
- </revhistory>
- <legalnotice>
- <para>Copyright © 1994 X Consortium, Inc., 2004 X.org Foundation, Inc.</para>
- <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>
- <para>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</para>
- <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>
- <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>
- </legalnotice>
- <abstract>
- <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:
- <orderedlist>
- <listitem><para>Read the first section of the "Strategies for Porting" document (Overview of Porting Process).</para></listitem>
- <listitem><para>Skim over this document (the Definition document).</para></listitem>
- <listitem><para>Skim over the remainder of the Strategies document.</para></listitem>
- <listitem><para>Start planning and working, referring to the Strategies and Definition documents.</para></listitem>
- </orderedlist>
- You may also want to look at the following documents:
- <itemizedlist>
- <listitem><para>"The X Window System" for an overview of X.</para></listitem>
- <listitem><para>"Xlib - C Language X Interface" for a view of what the client programmer sees.</para></listitem>
- <listitem><para>"X Window System Protocol" for a terse description of the byte stream protocol between the client and server.</para></listitem>
- </itemizedlist>
- </para>
- <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>
- <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>
- <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>
- </abstract>
- </articleinfo>
-
-<!-- Original authorship information:
-
-.OF 'Porting Layer Definition'- % -'October 27, 2004'
-Definition of the Porting Layer
-for the X v11 Sample Server
-Susan Angebranndt
-Raymond Drewry
-Philip Karlton
-Todd Newman
-Digital Equipment Corporation
-
-minor revisions by
-Bob Scheifler
-Massachusetts Institute of Technology
-
-Revised for Release 4 and Release 5 by
-Keith Packard
-MIT X Consortium
-
-Revised for Release 6 by
-David P. Wiggins
-X Consortium
-
-Minor Revisions for Release 6.8.2 by
-Jim Gettys
-X.org Foundation and Hewlett Packard
--->
-
-<section>
- <title>The X Window System</title>
-<para>
-The X Window System, or simply "X," is a
-windowing system that provides high-performance, high-level,
-device-independent graphics.
-</para>
-<para>
-X is a windowing system designed for bitmapped graphic displays.
-The display can have a
-simple, monochrome display or it can have a color display with up to 32 bits
-per pixel with a special graphics processor doing the work. (In this
-document, monochrome means a black and white display with one bit per pixel.
-Even though the usual meaning of monochrome is more general, this special
-case is so common that we decided to reserve the word for this purpose.)
-In practice, monochrome displays are now almost unheard of, with 4 bit
-gray scale displays being the low end.
-</para>
-<para>
-X is designed for a networking environment where
-users can run applications on machines other than their own workstations.
-Sometimes, the connection is over an Ethernet network with a protocol such as TCP/IP;
-but, any "reliable" byte stream is allowable.
-A high-bandwidth byte stream is preferable; RS-232 at
-9600 baud would be slow without compression techniques.
-</para>
-<para>
-X by itself allows great freedom of design.
-For instance, it does not include any user interface standard.
-Its intent is to "provide mechanism, not policy."
-By making it general, it can be the foundation for a wide
-variety of interactive software.
-</para>
-<para>
-For a more detailed overview, see the document "The X Window System."
-For details on the byte stream protocol, see "X Window System protocol."
-</para>
-</section>
-<section>
-<title>Overview of the Server</title>
-<para>
-The display server
-manages windows and simple graphics requests
-for the user on behalf of different client applications.
-The client applications can be running on any machine on the network.
-The server mainly does three things:
-<itemizedlist>
- <listitem><para>Responds to protocol requests from existing clients (mostly graphic and text drawing commands)</para></listitem>
- <listitem><para>Sends device input (keystrokes and mouse actions) and other events to existing clients</para></listitem>
- <listitem><para>Maintains client connections</para></listitem>
-</itemizedlist>
-</para>
-<para>
-The server code is organized into four major pieces:
-<itemizedlist>
- <listitem><para>Device Independent (DIX) layer - code shared among all implementations</para></listitem>
- <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>
- <listitem><para>Device Dependent (DDX) layer - code that is (potentially) different for each combination of operating system and graphic device</para></listitem>
- <listitem><para>Extension Interface - a standard way to add features to the X server</para></listitem>
-</itemizedlist>
-</para>
-<para>
-The "porting layer" consists of the OS and DDX layers; these are
-actually parallel and neither one is on top of the other.
-The DIX layer is intended to be portable
-without change to target systems and is not
-detailed here, although several routines
-in DIX that are called by DDX are
-documented.
-Extensions incorporate new functionality into the server; and require
-additional functionality over a simple DDX.
-</para>
-<para>
-The following sections outline the functions of the layers.
-Section 3 briefly tells what you need to know about the DIX layer.
-The OS layer is explained in Section 4.
-Section 5 gives the theory of operation and procedural interface for the
-DDX layer.
-Section 6 describes the functions which exist for the extension writer.
-</para>
-</section>
-
-<section>
- <title>DIX Layer</title>
-<para>
-The DIX layer is the machine and device independent part of X.
-The source should be common to all operating systems and devices.
-The port process should not include changes to this part, therefore internal interfaces to DIX
-modules are not discussed, except for public interfaces to the DDX and the OS layers.
-The functions described in this section are available for extension writers to use.
-</para>
-<para>
-In the process of getting your server to work, if
-you think that DIX must be modified for purposes other than bug fixes,
-you may be doing something wrong.
-Keep looking for a more compatible solution.
-When the next release of the X server code is available,
-you should be able to just drop in the new DIX code and compile it.
-If you change DIX,
-you will have to remember what changes you made and will have
-to change the new sources before you can update to the new version.
-</para>
-<para>
-The heart of the DIX code is a loop called the dispatch loop.
-Each time the processor goes around the loop, it sends off accumulated input events
-from the input devices to the clients, and it processes requests from the clients.
-This loop is the most organized way for the server to
-process the asynchronous requests that
-it needs to process.
-Most of these operations are performed by OS and DDX routines that you must supply.
-</para>
-<section>
- <title>Server Resource System</title>
-<para>
-X resources are C structs inside the server.
-Client applications create and manipulate these objects
-according to the rules of the X byte stream protocol.
-Client applications refer to resources with resource IDs,
-which are 32-bit integers that are sent over the network.
-Within the server, of course, they are just C structs, and we refer to them
-by pointers.
-</para>
-<section>
- <title>Pre-Defined Resource Types</title>
-<para>
-The DDX layer has several kinds of resources:
-<itemizedlist>
-<listitem><para>Window</para></listitem>
-<listitem><para>Pixmap</para></listitem>
-<listitem><para>Screen</para></listitem>
-<listitem><para>Device</para></listitem>
-<listitem><para>Colormap</para></listitem>
-<listitem><para>Font</para></listitem>
-<listitem><para>Cursor</para></listitem>
-<listitem><para>Graphics Contexts</para></listitem>
-</itemizedlist>
-</para>
-<para>
-The type names of the more
-important server
-structs usually end in "Rec," such as "DeviceRec;"
-the pointer types usually end in "Ptr," such as "DevicePtr."
-</para>
-<para>
-The structs and
-important defined constants are declared
-in .h files that have names that suggest the name of the object.
-For instance, there are two .h files for windows,
-window.h and windowstr.h.
-window.h defines only what needs to be defined in order to use windows
-without peeking inside of them;
-windowstr.h defines the structs with all of their components in great detail
-for those who need it.
-</para>
-<para>
-Three kinds of fields are in these structs:
-<itemizedlist>
-<listitem><para>Attribute fields - struct fields that contain values like normal structs</para></listitem>
-<listitem><para>Pointers to procedures, or structures of procedures, that operate on the object</para></listitem>
-<listitem><para>A single private field or a devPrivates list (see <xref linkend="wrappers_and_privates"/>)
-used by your DDX code to store private data.</para></listitem>
-</itemizedlist>
-</para>
-<para>
-DIX calls through
-the struct's procedure pointers to do its tasks.
-These procedures are set either directly or indirectly by DDX procedures.
-Most of
-the procedures described in the remainder of this
-document are accessed through one of these structs.
-For example, the procedure to create a pixmap
-is attached to a ScreenRec and might be called by using the expression
-</para>
-<para>
-<blockquote>
-<programlisting>(* pScreen->CreatePixmap)(pScreen, width, height, depth).</programlisting>
-</blockquote>
-</para>
-<para>
-All procedure pointers must be set to some routine unless noted otherwise;
-a null pointer will have unfortunate consequences.
-</para>
-<para>
-Procedure routines will be indicated in the documentation by this convention:
-<blockquote>
-<programlisting>void pScreen->MyScreenRoutine(arg, arg, ...)</programlisting>
-</blockquote>
-as opposed to a free routine, not in a data structure:
-<blockquote>
-<programlisting>void MyFreeRoutine(arg, arg, ...)</programlisting>
-</blockquote>
-</para>
-<para>
-The attribute fields are mostly set by DIX; DDX should not modify them
-unless noted otherwise.
-</para>
-</section>
-<section>
- <title>Creating Resources and Resource Types</title>
-<para>
-These functions should also be called from your extensionInitProc to
-allocate all of the various resource classes and types required for
-the extension. Each time the server resets, these types must be reallocated
-as the old allocations will have been discarded.
-Resource types are integer values starting at 1. Get
-a resource type by calling
-<blockquote><programlisting>
-
- RESTYPE CreateNewResourceType(deleteFunc, char *name)
-
-</programlisting></blockquote>
-deleteFunc will be called to destroy all resources with this
-type. name will be used to identify this type of resource
-to clients using the X-Resource extension, to security
-extensions such as SELinux, and to tracing frameworks such as DTrace.
-[The name argument was added in xorg-server 1.8.]
-</para>
-<para>
-Resource classes are masks starting at 1 << 31 which can
-be or'ed with any resource type to provide attributes for the
-type. To allocate a new class bit, call
-<blockquote><programlisting>
-
- RESTYPE CreateNewResourceClass()
-
-</programlisting></blockquote>
-</para>
-<para>
-There are two ways of looking up resources, by type or
-by class. Classes are non-exclusive subsets of the space of
-all resources, so you can lookup the union of multiple classes.
-(RC_ANY is the union of all classes).</para>
-<para>
-Note that the appropriate class bits must be or'ed into the value returned
-by CreateNewResourceType when calling resource lookup functions.</para>
-<para>
-If you need to create a ``private'' resource ID for internal use, you
-can call FakeClientID.
-<blockquote><programlisting>
-
- XID FakeClientID(client)
- int client;
-
-</programlisting></blockquote>
-This allocates from ID space reserved for the server.</para>
-<para>
-To associate a resource value with an ID, use AddResource.
-<blockquote><programlisting>
-
- Bool AddResource(id, type, value)
- XID id;
- RESTYPE type;
- pointer value;
-
-</programlisting></blockquote>
-The type should be the full type of the resource, including any class
-bits. If AddResource fails to allocate memory to store the resource,
-it will call the deleteFunc for the type, and then return False.</para>
-<para>
-To free a resource, use one of the following.
-<blockquote><programlisting>
-
- void FreeResource(id, skipDeleteFuncType)
- XID id;
- RESTYPE skipDeleteFuncType;
-
- void FreeResourceByType(id, type, skipFree)
- XID id;
- RESTYPE type;
- Bool skipFree;
-
-</programlisting></blockquote>
-FreeResource frees all resources matching the given id, regardless of
-type; the type's deleteFunc will be called on each matching resource,
-except that skipDeleteFuncType can be set to a single type for which
-the deleteFunc should not be called (otherwise pass RT_NONE).
-FreeResourceByType frees a specific resource matching a given id
-and type; if skipFree is true, then the deleteFunc is not called.
-</para>
-</section>
-<section>
- <title>Looking Up Resources</title>
-<para>
-To look up a resource, use one of the following.
-<blockquote><programlisting>
-
- int dixLookupResourceByType(
- pointer *result,
- XID id,
- RESTYPE rtype,
- ClientPtr client,
- Mask access_mode);
-
- int dixLookupResourceByClass(
- pointer *result,
- XID id,
- RESTYPE rclass,
- ClientPtr client,
- Mask access_mode);
-
-</programlisting></blockquote>
-dixLookupResourceByType finds a resource with the given id and exact type.
-dixLookupResourceByClass finds a resource with the given id whose type is
-included in any one of the specified classes.
-The client and access_mode must be provided to allow security extensions to
-check if the client has the right privileges for the requested access.
-The bitmask values defined in the dixaccess.h header are or'ed together
-to define the requested access_mode.
-</para>
-</section>
-</section>
-<section>
- <title>Callback Manager</title>
-<para>
-To satisfy a growing number of requests for the introduction of ad hoc
-notification style hooks in the server, a generic callback manager was
-introduced in R6. A callback list object can be introduced for each
-new hook that is desired, and other modules in the server can register
-interest in the new callback list. The following functions support
-these operations.</para>
-<para>
-Before getting bogged down in the interface details, an typical usage
-example should establish the framework. Let's look at the
-ClientStateCallback in dix/dispatch.c. The purpose of this particular
-callback is to notify interested parties when a client's state
-(initial, running, gone) changes. The callback is "created" in this
-case by simply declaring a variable:
-<blockquote><programlisting>
- CallbackListPtr ClientStateCallback;
-</programlisting></blockquote>
-</para>
-<para>
-Whenever the client's state changes, the following code appears, which notifies
-all interested parties of the change:
-<blockquote><programlisting>
- if (ClientStateCallback) CallCallbacks(&ClientStateCallback, (pointer)client);
-</programlisting></blockquote>
-</para>
-<para>
-Interested parties subscribe to the ClientStateCallback list by saying:
-<blockquote><programlisting>
- AddCallback(&ClientStateCallback, func, data);
-</programlisting></blockquote>
-</para>
-<para>
-When CallCallbacks is invoked on the list, func will be called thusly:
-<blockquote><programlisting>
- (*func)(&ClientStateCallback, data, client)
-</programlisting></blockquote>
-</para>
-<para>
-Now for the details.
-<blockquote><programlisting>
-
- Bool AddCallback(pcbl, callback, subscriber_data)
- CallbackListPtr *pcbl;
- CallbackProcPtr callback;
- pointer subscriber_data;
-
-</programlisting></blockquote>
-Adds the (callback, subscriber_data) pair to the given callback list. Creates the callback
-list if it doesn't exist. Returns TRUE if successful.</para>
-<para>
-<blockquote><programlisting>
-
- Bool DeleteCallback(pcbl, callback, subscriber_data)
- CallbackListPtr *pcbl;
- CallbackProcPtr callback;
- pointer subscriber_data;
-
-</programlisting></blockquote>
-Removes the (callback, data) pair to the given callback list if present.
-Returns TRUE if (callback, data) was found.</para>
-<para>
-<blockquote><programlisting>
-
- void CallCallbacks(pcbl, call_data)
- CallbackListPtr *pcbl;
- pointer call_data;
-
-</programlisting></blockquote>
-For each callback currently registered on the given callback list, call
-it as follows:
-<blockquote><programlisting>
-
- (*callback)(pcbl, subscriber_data, call_data);
-</programlisting></blockquote>
-</para>
-<para>
-<blockquote><programlisting>
- void DeleteCallbackList(pcbl)
- CallbackListPtr *pcbl;
-
-</programlisting></blockquote>
-Destroys the given callback list.</para>
-</section>
-<section>
- <title>Extension Interfaces</title>
-<para>
-This function should be called from your extensionInitProc which
-should be called by InitExtensions.
-<blockquote><programlisting>
-
- ExtensionEntry *AddExtension(name, NumEvents,NumErrors,
- MainProc, SwappedMainProc, CloseDownProc, MinorOpcodeProc)
-
- char *name; /*Null terminate string; case matters*/
- int NumEvents;
- int NumErrors;
- int (* MainProc)(ClientPtr);/*Called if client matches server order*/
- int (* SwappedMainProc)(ClientPtr);/*Called if client differs from server*/
- void (* CloseDownProc)(ExtensionEntry *);
- unsigned short (*MinorOpcodeProc)(ClientPtr);
-
-</programlisting></blockquote>
-name is the name used by clients to refer to the extension. NumEvents is the
-number of event types used by the extension, NumErrors is the number of
-error codes needed by the extension. MainProc is called whenever a client
-accesses the major opcode assigned to the extension. SwappedMainProc is
-identical, except the client using the extension has reversed byte-sex.
-CloseDownProc is called at server reset time to deallocate any private
-storage used by the extension. MinorOpcodeProc is used by DIX to place the
-appropriate value into errors. The DIX routine StandardMinorOpcode can be
-used here which takes the minor opcode from the normal place in the request
-(i.e. just after the major opcode).</para>
-</section>
-<section>
- <title>Macros and Other Helpers</title>
-<para>
-There are a number of macros in Xserver/include/dix.h which
-are useful to the extension writer. Ones of particular interest
-are: REQUEST, REQUEST_SIZE_MATCH, REQUEST_AT_LEAST_SIZE,
-REQUEST_FIXED_SIZE, LEGAL_NEW_RESOURCE, and
-VALIDATE_DRAWABLE_AND_GC. Useful byte swapping macros can be found
-in Xserver/include/dix.h: WriteReplyToClient and WriteSwappedDataToClient; and
-in Xserver/include/misc.h: lswapl, lswaps, LengthRestB, LengthRestS,
-LengthRestL, SwapRestS, SwapRestL, swapl, swaps, cpswapl, and cpswaps.</para>
-</section>
-</section>
-
-<section>
- <title>OS Layer</title>
-<para>
-This part of the source consists of a few routines that you have to rewrite
-for each operating system.
-These OS functions maintain the client connections and schedule work
-to be done for clients.
-They also provide an interface to font files,
-font name to file name translation, and
-low level memory management.
-<blockquote>
-<programlisting>void OsInit()</programlisting>
-</blockquote>
-OsInit initializes your OS code, performing whatever tasks need to be done.
-Frequently there is not much to be done.
-The sample server implementation is in Xserver/os/osinit.c.
-</para>
-<section>
- <title>Scheduling and Request Delivery</title>
-<para>
-The main dispatch loop in DIX creates the illusion of multitasking between
-different windows, while the server is itself but a single process.
-The dispatch loop breaks up the work for each client into small digestible parts.
-Some parts are requests from a client, such as individual graphic commands.
-Some parts are events delivered to the client, such as keystrokes from the user.
-The processing of events and requests for different
-clients can be interleaved with one another so true multitasking
-is not needed in the server.
-</para>
-<para>
-You must supply some of the pieces for proper scheduling between clients.
-<blockquote>
-<programlisting>
- int WaitForSomething(pClientReady)
- int *pClientReady;
-</programlisting>
-</blockquote>
-</para>
-<para>
-WaitForSomething is the scheduler procedure you must write that will
-suspend your server process until something needs to be done.
-This call should
-make the server suspend until one or more of the following occurs:
-<itemizedlist>
-<listitem><para>There is an input event from the user or hardware (see SetInputCheck())</para></listitem>
-<listitem><para>There are requests waiting from known clients, in which case you should return a count of clients stored in pClientReady</para></listitem>
-<listitem><para>A new client tries to connect, in which case you should create the client and then continue waiting</para></listitem>
-</itemizedlist>
-</para>
-<para>
-Before WaitForSomething() computes the masks to pass to select, poll or
-similar operating system interface, it needs to
-see if there is anything to do on the work queue; if so, it must call a DIX
-routine called ProcessWorkQueue.
-<blockquote>
-<programlisting>
- extern WorkQueuePtr workQueue;
-
- if (workQueue)
- ProcessWorkQueue ();
-</programlisting>
-</blockquote>
-</para>
-<para>
-If WaitForSomething() decides it is about to do something that might block
-(in the sample server, before it calls select() or poll) it must call a DIX
-routine called BlockHandler().
-<blockquote>
-<programlisting>
- void BlockHandler(pTimeout, pReadmask)
- pointer pTimeout;
- pointer pReadmask;
-</programlisting>
-</blockquote>
-The types of the arguments are for agreement between the OS and DDX
-implementations, but the pTimeout is a pointer to the information
-determining how long the block is allowed to last, and the
-pReadmask is a pointer to the information describing the descriptors
-that will be waited on.
-</para>
-<para>
-In the sample server, pTimeout is a struct timeval **, and pReadmask is
-the address of the select() mask for reading.
-</para>
-<para>
-The DIX BlockHandler() iterates through the Screens, for each one calling
-its BlockHandler. A BlockHandler is declared thus:
-<blockquote>
-<programlisting>
- void xxxBlockHandler(nscreen, pbdata, pptv, pReadmask)
- int nscreen;
- pointer pbdata;
- struct timeval ** pptv;
- pointer pReadmask;
-</programlisting>
-</blockquote>
-The arguments are the index of the Screen, the blockData field
-of the Screen, and the arguments to the DIX BlockHandler().
-</para>
-<para>
-Immediately after WaitForSomething returns from the
-block, even if it didn't actually block, it must call the DIX routine
-WakeupHandler().
-<blockquote>
-<programlisting>
- void WakeupHandler(result, pReadmask)
- int result;
- pointer pReadmask;
-</programlisting>
-</blockquote>
-Once again, the types are not specified by DIX. The result is the
-success indicator for the thing that (may have) blocked,
-and the pReadmask is a mask of the descriptors that came active.
-In the sample server, result is the result from select() (or equivalent
-operating system function), and pReadmask is
-the address of the select() mask for reading.
-</para>
-<para>
-The DIX WakeupHandler() calls each Screen's
-WakeupHandler. A WakeupHandler is declared thus:
-<blockquote>
-<programlisting>
- void xxxWakeupHandler(nscreen, pbdata, err, pReadmask)
- int nscreen;
- pointer pbdata;
- unsigned long result;
- pointer pReadmask;
-</programlisting>
-</blockquote>
-The arguments are the index of the Screen, the blockData field
-of the Screen, and the arguments to the DIX WakeupHandler().
-</para>
-<para>
-In addition to the per-screen BlockHandlers, any module may register
-block and wakeup handlers (only together) using:
-<blockquote>
-<programlisting>
- Bool RegisterBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData)
- BlockHandlerProcPtr blockHandler;
- WakeupHandlerProcPtr wakeupHandler;
- pointer blockData;
-</programlisting>
-</blockquote>
-A FALSE return code indicates that the registration failed for lack of
-memory. To remove a registered Block handler at other than server reset time
-(when they are all removed automatically), use:
-<blockquote>
-<programlisting>
- RemoveBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData)
- BlockHandlerProcPtr blockHandler;
- WakeupHandlerProcPtr wakeupHandler;
- pointer blockData;
-</programlisting>
-</blockquote>
-All three arguments must match the values passed to
-RegisterBlockAndWakeupHandlers.
-</para>
-<para>
-These registered block handlers are called after the per-screen handlers:
-<blockquote>
-<programlisting>
- void (*BlockHandler) (blockData, pptv, pReadmask)
- pointer blockData;
- OsTimerPtr pptv;
- pointer pReadmask;
-</programlisting>
-</blockquote>
-</para>
-<para>
-Sometimes block handlers need to adjust the time in a OSTimePtr structure,
-which on UNIX family systems is generally represented by a struct timeval
-consisting of seconds and microseconds in 32 bit values.
-As a convenience to reduce error prone struct timeval computations which
-require modulus arithmetic and correct overflow behavior in the face of
-millisecond wrapping through 32 bits,
-<blockquote><programlisting>
-
- void AdjustWaitForDelay(pointer /*waitTime*, unsigned long /* newdelay */)
-
-</programlisting></blockquote>
-has been provided.
-</para>
-<para>
-Any wakeup handlers registered with RegisterBlockAndWakeupHandlers will
-be called before the Screen handlers:
-<blockquote><programlisting>
-
- void (*WakeupHandler) (blockData, err, pReadmask)
- pointer blockData;
- int err;
- pointer pReadmask;
-</programlisting></blockquote>
-</para>
-<para>
-The WaitForSomething on the sample server also has a built
-in screen saver that darkens the screen if no input happens for a period of time.
-The sample server implementation is in Xserver/os/WaitFor.c.
-</para>
-<para>
-Note that WaitForSomething() may be called when you already have several
-outstanding things (events, requests, or new clients) queued up.
-For instance, your server may have just done a large graphics request,
-and it may have been a long time since WaitForSomething() was last called.
-If many clients have lots of requests queued up, DIX will only service
-some of them for a given client
-before going on to the next client (see isItTimeToYield, below).
-Therefore, WaitForSomething() will have to report that these same clients
-still have requests queued up the next time around.
-</para>
-<para>
-An implementation should return information on as
-many outstanding things as it can.
-For instance, if your implementation always checks for client data first and does not
-report any input events until there is no client data left,
-your mouse and keyboard might get locked out by an application that constantly
-barrages the server with graphics drawing requests.
-Therefore, as a general rule, input devices should always have priority over graphics
-devices.
-</para>
-<para>
-A list of indexes (client->index) for clients with data ready to be read or
-processed should be returned in pClientReady, and the count of indexes
-returned as the result value of the call.
-These are not clients that have full requests ready, but any clients who have
-any data ready to be read or processed.
-The DIX dispatcher
-will process requests from each client in turn by calling
-ReadRequestFromClient(), below.
-</para>
-<para>
-WaitForSomething() must create new clients as they are requested (by
-whatever mechanism at the transport level). A new client is created
-by calling the DIX routine:
-<blockquote><programlisting>
-
- ClientPtr NextAvailableClient(ospriv)
- pointer ospriv;
-</programlisting></blockquote>
-This routine returns NULL if a new client cannot be allocated (e.g. maximum
-number of clients reached). The ospriv argument will be stored into the OS
-private field (pClient->osPrivate), to store OS private information about the
-client. In the sample server, the osPrivate field contains the
-number of the socket for this client. See also "New Client Connections."
-NextAvailableClient() will call InsertFakeRequest(), so you must be
-prepared for this.
-</para>
-<para>
-If there are outstanding input events,
-you should make sure that the two SetInputCheck() locations are unequal.
-The DIX dispatcher will call your implementation of ProcessInputEvents()
-until the SetInputCheck() locations are equal.
-</para>
-<para>
-The sample server contains an implementation of WaitForSomething().
-The
-following two routines indicate to WaitForSomething() what devices should
-be waited for. fd is an OS dependent type; in the sample server
-it is an open file descriptor.
-<blockquote><programlisting>
-
- int AddEnabledDevice(fd)
- int fd;
-
- int RemoveEnabledDevice(fd)
- int fd;
-</programlisting></blockquote>
-These two routines are
-usually called by DDX from the initialize cases of the
-Input Procedures that are stored in the DeviceRec (the
-routine passed to AddInputDevice()).
-The sample server implementation of AddEnabledDevice
-and RemoveEnabledDevice are in Xserver/os/connection.c.
-</para>
-<section>
- <title>Timer Facilities</title>
-<para>
-Similarly, the X server or an extension may need to wait for some timeout.
-Early X releases implemented this functionality using block and wakeup handlers,
-but this has been rewritten to use a general timer facilty, and the
-internal screen saver facilities reimplemented to use Timers.
-These functions are TimerInit, TimerForce, TimerSet, TimerCheck, TimerCancel,
-and TimerFree, as defined in Xserver/include/os.h. A callback function will be called
-when the timer fires, along with the current time, and a user provided argument.
-<blockquote><programlisting>
- typedef struct _OsTimerRec *OsTimerPtr;
-
- typedef CARD32 (*OsTimerCallback)(
- OsTimerPtr /* timer */,
- CARD32 /* time */,
- pointer /* arg */);
-
- OsTimerPtr TimerSet( OsTimerPtr /* timer */,
- int /* flags */,
- CARD32 /* millis */,
- OsTimerCallback /* func */,
- pointer /* arg */);
-
-</programlisting></blockquote>
-</para>
-<para>
-TimerSet returns a pointer to a timer structure and sets a timer to the specified time
-with the specified argument. The flags can be TimerAbsolute and TimerForceOld.
-The TimerSetOld flag controls whether if the timer is reset and the timer is pending, the
-whether the callback function will get called.
-The TimerAbsolute flag sets the callback time to an absolute time in the future rather
-than a time relative to when TimerSet is called.
-TimerFree should be called to free the memory allocated
-for the timer entry.
-<blockquote><programlisting>
- void TimerInit(void)
-
- Bool TimerForce(OsTimerPtr /* pTimer */)
-
- void TimerCheck(void);
-
- void TimerCancel(OsTimerPtr /* pTimer */)
-
- void TimerFree(OsTimerPtr /* pTimer */)
-</programlisting></blockquote>
-</para>
-<para>
-TimerInit frees any existing timer entries. TimerForce forces a call to the timer's
-callback function and returns true if the timer entry existed, else it returns false and
-does not call the callback function. TimerCancel will cancel the specified timer.
-TimerFree calls TimerCancel and frees the specified timer.
-Calling TimerCheck will force the server to see if any timer callbacks should be called.
-</para>
-</section>
-</section>
-<section>
- <title>New Client Connections</title>
-<para>
-The process whereby a new client-server connection starts up is
-very dependent upon what your byte stream mechanism.
-This section describes byte stream initiation using examples from the TCP/IP
-implementation on the sample server.
-</para>
-<para>
-The first thing that happens is a client initiates a connection with the server.
-How a client knows to do this depends upon your network facilities and the
-Xlib implementation.
-In a typical scenario, a user named Fred
-on his X workstation is logged onto a Cray
-supercomputer running a command shell in an X window. Fred can type shell
-commands and have the Cray respond as though the X server were a dumb terminal.
-Fred types in a command to run an X client application that was linked with Xlib.
-Xlib looks at the shell environment variable DISPLAY, which has the
-value "fredsbittube:0.0."
-The host name of Fred's workstation is "fredsbittube," and the 0s are
-for multiple screens and multiple X server processes.
-(Precisely what
-happens on your system depends upon how X and Xlib are implemented.)
-</para>
-<para>
-The client application calls a TCP routine on the
-Cray to open a TCP connection for X
-to communicate with the network node "fredsbittube."
-The TCP software on the Cray does this by looking up the TCP
-address of "fredsbittube" and sending an open request to TCP port 6000
-on fredsbittube.
-</para>
-<para>
-All X servers on TCP listen for new clients on port 6000 by default;
-this is known as a "well-known port" in IP terminology.
-</para>
-<para>
-The server receives this request from its port 6000
-and checks where it came from to see if it is on the server's list
-of "trustworthy" hosts to talk to.
-Then, it opens another port for communications with the client.
-This is the byte stream that all X communications will go over.
-</para>
-<para>
-Actually, it is a bit more complicated than that.
-Each X server process running on the host machine is called a "display."
-Each display can have more than one screen that it manages.
-"corporatehydra:3.2" represents screen 2 on display 3 on
-the multi-screened network node corporatehydra.
-The open request would be sent on well-known port number 6003.
-</para>
-<para>
-Once the byte stream is set up, what goes on does not depend very much
-upon whether or not it is TCP.
-The client sends an xConnClientPrefix struct (see Xproto.h) that has the
-version numbers for the version of Xlib it is running, some byte-ordering information,
-and two character strings used for authorization.
-If the server does not like the authorization strings
-or the version numbers do not match within the rules,
-or if anything else is wrong, it sends a failure
-response with a reason string.
-</para>
-<para>
-If the information never comes, or comes much too slowly, the connection
-should be broken off. You must implement the connection timeout. The
-sample server implements this by keeping a timestamp for each still-connecting
-client and, each time just before it attempts to accept new connections, it
-closes any connection that are too old.
-The connection timeout can be set from the command line.
-</para>
-<para>
-You must implement whatever authorization schemes you want to support.
-The sample server on the distribution tape supports a simple authorization
-scheme. The only interface seen by DIX is:
-<blockquote><programlisting>
-
- char *
- ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string)
- ClientPtr client;
- unsigned int proto_n;
- char *auth_proto;
- unsigned int string_n;
- char *auth_string;
-</programlisting></blockquote>
-DIX will only call this once per client, once it has read the full initial
-connection data from the client. If the connection should be
-accepted ClientAuthorized() should return NULL, and otherwise should
-return an error message string.
-</para>
-<para>
-Accepting new connections happens internally to WaitForSomething().
-WaitForSomething() must call the DIX routine NextAvailableClient()
-to create a client object.
-Processing of the initial connection data will be handled by DIX.
-Your OS layer must be able to map from a client
-to whatever information your OS code needs to communicate
-on the given byte stream to the client.
-DIX uses this ClientPtr to refer to
-the client from now on. The sample server uses the osPrivate field in
-the ClientPtr to store the file descriptor for the socket, the
-input and output buffers, and authorization information.
-</para>
-<para>
-To initialize the methods you choose to allow clients to connect to
-your server, main() calls the routine
-<blockquote><programlisting>
-
- void CreateWellKnownSockets()
-</programlisting></blockquote>
-This routine is called only once, and not called when the server
-is reset. To recreate any sockets during server resets, the following
-routine is called from the main loop:
-<blockquote><programlisting>
-
- void ResetWellKnownSockets()
-</programlisting></blockquote>
-Sample implementations of both of these routines are found in
-Xserver/os/connection.c.
-</para>
-<para>
-For more details, see the section called "Connection Setup" in the X protocol specification.
-</para>
-</section>
-<section>
- <title>Reading Data from Clients</title>
-<para>
-Requests from the client are read in as a byte stream by the OS layer.
-They may be in the form of several blocks of bytes delivered in sequence; requests may
-be broken up over block boundaries or there may be many requests per block.
-Each request carries with it length information.
-It is the responsibility of the following routine to break it up into request blocks.
-<blockquote><programlisting>
-
- int ReadRequestFromClient(who)
- ClientPtr who;
-</programlisting></blockquote>
-</para>
-<para>
-You must write
-the routine ReadRequestFromClient() to get one request from the byte stream
-belonging to client "who."
-You must swap the third and fourth bytes (the second 16-bit word) according to the
-byte-swap rules of
-the protocol to determine the length of the
-request.
-This length is measured in 32-bit words, not in bytes. Therefore, the
-theoretical maximum request is 256K.
-(However, the maximum length allowed is dependent upon the server's input
-buffer. This size is sent to the client upon connection. The maximum
-size is the constant MAX_REQUEST_SIZE in Xserver/include/os.h)
-The rest of the request you return is
-assumed NOT to be correctly swapped for internal
-use, because that is the responsibility of DIX.
-</para>
-<para>
-The 'who' argument is the ClientPtr returned from WaitForSomething.
-The return value indicating status should be set to the (positive) byte count if the read is successful,
-0 if the read was blocked, or a negative error code if an error happened.
-</para>
-<para>
-You must then store a pointer to
-the bytes of the request in the client request buffer field;
-who->requestBuffer. This can simply be a pointer into your buffer;
-DIX may modify it in place but will not otherwise cause damage.
-Of course, the request must be contiguous; you must
-shuffle it around in your buffers if not.
-</para>
-<para>
-The sample server implementation is in Xserver/os/io.c.
-</para>
-<section><title>Inserting Data for Clients</title>
-<para>
-DIX can insert data into the client stream, and can cause a "replay" of
-the current request.
-<blockquote><programlisting>
-
- Bool InsertFakeRequest(client, data, count)
- ClientPtr client;
- char *data;
- int count;
-
- int ResetCurrentRequest(client)
- ClientPtr client;
-</programlisting></blockquote>
-</para>
-<para>
-InsertFakeRequest() must insert the specified number of bytes of data
-into the head of the input buffer for the client. This may be a
-complete request, or it might be a partial request. For example,
-NextAvailableCient() will insert a partial request in order to read
-the initial connection data sent by the client. The routine returns FALSE
-if memory could not be allocated. ResetCurrentRequest()
-should "back up" the input buffer so that the currently executing request
-will be reexecuted. DIX may have altered some values (e.g. the overall
-request length), so you must recheck to see if you still have a complete
-request. ResetCurrentRequest() should always cause a yield (isItTimeToYield).
-</para>
-</section>
-</section>
-
-<section>
- <title>Sending Events, Errors And Replies To Clients</title>
-<para>
-<blockquote><programlisting>
-
- int WriteToClient(who, n, buf)
- ClientPtr who;
- int n;
- char *buf;
-</programlisting></blockquote>
-WriteToClient should write n bytes starting at buf to the
-ClientPtr "who".
-It returns the number of bytes written, but for simplicity,
-the number returned must be either the same value as the number
-requested, or -1, signaling an error.
-The sample server implementation is in Xserver/os/io.c.
-</para>
-<para>
-<blockquote><programlisting>
- void SendErrorToClient(client, majorCode, minorCode, resId, errorCode)
- ClientPtr client;
- unsigned int majorCode;
- unsigned int minorCode;
- XID resId;
- int errorCode;
-</programlisting></blockquote>
-SendErrorToClient can be used to send errors back to clients,
-although in most cases your request function should simply return
-the error code, having set client->errorValue to the appropriate
-error value to return to the client, and DIX will call this
-function with the correct opcodes for you.
-</para>
-<para>
-<blockquote><programlisting>
-
- void FlushAllOutput()
-
- void FlushIfCriticalOutputPending()
-
- void SetCriticalOutputPending()
-</programlisting></blockquote>
-These three routines may be implemented to support buffered or delayed
-writes to clients, but at the very least, the stubs must exist.
-FlushAllOutput() unconditionally flushes all output to clients;
-FlushIfCriticalOutputPending() flushes output only if
-SetCriticalOutputPending() has be called since the last time output
-was flushed.
-The sample server implementation is in Xserver/os/io.c and
-actually ignores requests to flush output on a per-client basis
-if it knows that there
-are requests in that client's input queue.
-</para>
-</section>
-<section>
- <title>Font Support</title>
-<para>
-In the sample server, fonts are encoded in disk files or fetched from the
-font server. The two fonts required by the server, <quote>fixed</quote>
-and <quote>cursor</quote> are commonly compiled into the font library.
-For disk fonts, there is one file per font, with a file name like
-"fixed.pcf". Font server fonts are read over the network using the
-X Font Server Protocol. The disk directories containing disk fonts and
-the names of the font servers are listed together in the current "font path."
-</para>
-<para>
-In principle, you can put all your fonts in ROM or in RAM in your server.
-You can put them all in one library file on disk.
-You could generate them on the fly from stroke descriptions. By placing the
-appropriate code in the Font Library, you will automatically export fonts in
-that format both through the X server and the Font server.
-</para>
-<para>
-The code for processing fonts in different formats, as well as handling the
-metadata files for them on disk (such as <filename>fonts.dir</filename>) is
-located in the libXfont library, which is provided as a separately compiled
-module. These routines are
-shared between the X server and the Font server, so instead of this document
-specifying what you must implement, simply refer to the font
-library interface specification for the details. All of the interface code to the Font
-library is contained in dix/dixfonts.c
-</para>
-</section>
-<section>
- <title>Memory Management</title>
-<para>
-Memory management is based on functions in the C runtime library.
-Xalloc(), Xrealloc(), and Xfree() are deprecated aliases for malloc(),
-realloc(), and free(), and you should simply call the C library functions
-directly. Consult a C runtime library reference
-manual for more details.
-</para>
-<para>
-Treat memory allocation carefully in your implementation. Memory
-leaks can be very hard to find and are frustrating to a user. An X
-server could be running for days or weeks without being reset, just
-like a regular terminal. If you leak a few dozen k per day, that will
-add up and will cause problems for users that leave their workstations
-on.
-</para>
-</section>
-<section>
- <title>Client Scheduling</title>
-<para>
-The X server
-has the ability to schedule clients much like an operating system would,
-suspending and restarting them without regard for the state of their input
-buffers. This functionality allows the X server to suspend one client and
-continue processing requests from other clients while waiting for a
-long-term network activity (like loading a font) before continuing with the
-first client.
-<blockquote><programlisting>
- Bool isItTimeToYield;
-</programlisting></blockquote>
-isItTimeToYield is a global variable you can set
-if you want to tell
-DIX to end the client's "time slice" and start paying attention to the next client.
-After the current request is finished, DIX will move to the next client.
-</para>
-<para>
-In the sample
-server, ReadRequestFromClient() sets isItTimeToYield after
-10 requests packets in a row are read from the same client.
-</para>
-<para>
-This scheduling algorithm can have a serious effect upon performance when two
-clients are drawing into their windows simultaneously.
-If it allows one client to run until its request
-queue is empty by ignoring isItTimeToYield, the client's queue may
-in fact never empty and other clients will be blocked out.
-On the other hand, if it switchs between different clients too quickly,
-performance may suffer due to too much switching between contexts.
-For example, if a graphics processor needs to be set up with drawing modes
-before drawing, and two different clients are drawing with
-different modes into two different windows, you may
-switch your graphics processor modes so often that performance is impacted.
-</para>
-<para>
-See the Strategies document for
-heuristics on setting isItTimeToYield.
-</para>
-<para>
-The following functions provide the ability to suspend request
-processing on a particular client, resuming it at some later time:
-<blockquote><programlisting>
-
- int IgnoreClient (who)
- ClientPtr who;
-
- int AttendClient (who)
- ClientPtr who;
-</programlisting></blockquote>
-Ignore client is responsible for pretending that the given client doesn't
-exist. WaitForSomething should not return this client as ready for reading
-and should not return if only this client is ready. AttendClient undoes
-whatever IgnoreClient did, setting it up for input again.
-</para>
-<para>
-Three functions support "process control" for X clients:
-<blockquote><programlisting>
-
- Bool ClientSleep (client, function, closure)
- ClientPtr client;
- Bool (*function)();
- pointer closure;
-
-</programlisting></blockquote>
-This suspends the current client (the calling routine is responsible for
-making its way back to Dispatch()). No more X requests will be processed
-for this client until ClientWakeup is called.
-<blockquote><programlisting>
-
- Bool ClientSignal (client)
- ClientPtr client;
-
-</programlisting></blockquote>
-This function causes a call to the (*function) parameter passed to
-ClientSleep to be queued on the work queue. This does not automatically
-"wakeup" the client, but the function called is free to do so by calling:
-<blockquote><programlisting>
-
- ClientWakeup (client)
- ClientPtr client;
-
-</programlisting></blockquote>
-This re-enables X request processing for the specified client.
-</para>
-</section>
-<section>
- <title>Other OS Functions</title>
-<para>
-<blockquote><programlisting>
- void
- ErrorF(char *f, ...)
-
- void
- FatalError(char *f, ...)
-
- void
- Error(str)
- char *str;
-</programlisting></blockquote>
-You should write these three routines to provide for diagnostic output
-from the dix and ddx layers, although implementing them to produce no
-output will not affect the correctness of your server. ErrorF() and
-FatalError() take a printf() type of format specification in the first
-argument and an implementation-dependent number of arguments following
-that. Normally, the formats passed to ErrorF() and FatalError()
-should be terminated with a newline. Error() provides an os interface
-for printing out the string passed as an argument followed by a
-meaningful explanation of the last system error. Normally the string
-does not contain a newline, and it is only called by the ddx layer.
-In the sample implementation, Error() uses the perror() function.
-</para>
-<para>
-After printing the message arguments, FatalError() must be implemented
-such that the server will call AbortDDX() to give the ddx layer
-a chance to reset the hardware, and then
-terminate the server; it must not return.
-</para>
-<para>
-The sample server implementation for these routines
-is in Xserver/os/log.c along with other routines for logging messages.
-</para>
-</section>
-</section>
-
-<section>
- <title>DDX Layer</title>
-<para>
-This section describes the
-interface between DIX and DDX.
-While there may be an OS-dependent driver interface between DDX
-and the physical device, that interface is left to the DDX
-implementor and is not specified here.
-</para>
-<para>
-The DDX layer does most of its work through procedures that are
-pointed to by different structs.
-As previously described, the behavior of these resources is largely determined by
-these procedure pointers.
-Most of these routines are for graphic display on the screen or support functions thereof.
-The rest are for user input from input devices.
-</para>
-<section>
- <title>Input</title>
-<para>
-In this document "input" refers to input from the user,
-such as mouse, keyboard, and
-bar code readers.
-X input devices are of several types: keyboard, pointing device, and
-many others. The core server has support for extension devices as
-described by the X Input Extension document; the interfaces used by
-that extension are described elsewhere. The core devices are actually
-implemented as two collections of devices, the mouse is a ButtonDevice,
-a ValuatorDevice and a PtrFeedbackDevice while the keyboard is a KeyDevice,
-a FocusDevice and a KbdFeedbackDevice. Each part implements a portion of
-the functionality of the device. This abstraction is hidden from view for
-core devices by DIX.
-</para>
-<para>
-You, the DDX programmer, are
-responsible for some of the routines in this section.
-Others are DIX routines that you should call to do the things you need to do in these DDX routines.
-Pay attention to which is which.
-</para>
-<section>
- <title>Input Device Data Structures</title>
-<para>
-DIX keeps a global directory of devices in a central data structure
-called InputInfo.
-For each device there is a device structure called a DeviceRec.
-DIX can locate any DeviceRec through InputInfo.
-In addition, it has a special pointer to identify the main pointing device
-and a special pointer to identify the main keyboard.
-</para>
-<para>
-The DeviceRec (Xserver/include/input.h) is a device-independent
-structure that contains the state of an input device.
-A DevicePtr is simply a pointer to a DeviceRec.
-</para>
-<para>
-An xEvent describes an event the server reports to a client.
-Defined in Xproto.h, it is a huge struct of union of structs that have fields for
-all kinds of events.
-All of the variants overlap, so that the struct is actually very small in memory.
-</para>
-</section>
-<section>
- <title>Processing Events</title>
-<para>
-The main DDX input interface is the following routine:
-<blockquote><programlisting>
-
- void ProcessInputEvents()
-</programlisting></blockquote>
-You must write this routine to deliver input events from the user.
-DIX calls it when input is pending (see next section), and possibly
-even when it is not.
-You should write it to get events from each device and deliver
-the events to DIX.
-To deliver the events to DIX, DDX should call the following
-routine:
-<blockquote><programlisting>
-
- void DevicePtr->processInputProc(pEvent, device, count)
- xEventPtr events;
- DeviceIntPtr device;
- int count;
-</programlisting></blockquote>
-This is the "input proc" for the device, a DIX procedure.
-DIX will fill in this procedure pointer to one of its own routines by
-the time ProcessInputEvents() is called the first time.
-Call this input proc routine as many times as needed to
-deliver as many events as should be delivered.
-DIX will buffer them up and send them out as needed. Count is set
-to the number of event records which make up one atomic device event and
-is always 1 for the core devices (see the X Input Extension for descriptions
-of devices which may use count > 1).
-</para>
-<para>
-For example, your ProcessInputEvents() routine might check the mouse and the
-keyboard.
-If the keyboard had several keystrokes queued up, it could just call
-the keyboard's processInputProc as many times as needed to flush its internal queue.
-</para>
-<para>
-event is an xEvent struct you pass to the input proc.
-When the input proc returns, it is finished with the event rec, and you can fill
-in new values and call the input proc again with it.
-</para>
-<para>
-You should deliver the events in the same order that they were generated.
-</para>
-<para>
-For keyboard and pointing devices the xEvent variant should be keyButtonPointer.
-Fill in the following fields in the xEvent record:
-<itemizedlist>
-
-<listitem><para>type - is one of the following: KeyPress, KeyRelease, ButtonPress,
- ButtonRelease, or MotionNotify</para></listitem>
-<listitem><para>detail - for KeyPress or KeyRelease fields, this should be the
- key number (not the ASCII code); otherwise unused</para></listitem>
-<listitem><para>time - is the time that the event happened (32-bits, in milliseconds, arbitrary origin)</para></listitem>
-<listitem><para>rootX - is the x coordinate of cursor</para></listitem>
-<listitem><para>rootY - is the y coordinate of cursor</para></listitem>
-
-</itemizedlist>
-The rest of the fields are filled in by DIX.
-</para>
-<para>
-The time stamp is maintained by your code in the DDX layer, and it is your responsibility to
-stamp all events correctly.
-</para>
-<para>
-The x and y coordinates of the pointing device and the time must be filled in for all event types
-including keyboard events.
-</para>
-<para>
-The pointing device must report all button press and release events.
-In addition, it should report a MotionNotify event every time it gets called
-if the pointing device has moved since the last notify.
-Intermediate pointing device moves are stored in a special GetMotionEvents buffer,
-because most client programs are not interested in them.
-</para>
-<para>
-There are quite a collection of sample implementations of this routine,
-one for each supported device.
-</para>
-</section>
-<section>
-<title>Telling DIX When Input is Pending</title>
-<para>
-In the server's dispatch loop, DIX checks to see
-if there is any device input pending whenever WaitForSomething() returns.
-If the check says that input is pending, DIX calls the
-DDX routine ProcessInputEvents().
-</para>
-<para>
-This check for pending input must be very quick; a procedure call
-is too slow.
-The code that does the check is a hardwired IF
-statement in DIX code that simply compares the values
-pointed to by two pointers.
-If the values are different, then it assumes that input is pending and
-ProcessInputEvents() is called by DIX.
-</para>
-<para>
-You must pass pointers to DIX to tell it what values to compare.
-The following procedure
-is used to set these pointers:
-<blockquote><programlisting>
-
- void SetInputCheck(p1, p2)
- long *p1, *p2;
-</programlisting></blockquote>
-You should call it sometime during initialization to indicate to DIX the
-correct locations to check.
-You should
-pay special attention to the size of what they actually point to,
-because the locations are assumed to be longs.
-</para>
-<para>
-These two pointers are initialized by DIX
-to point to arbitrary values that
-are different.
-In other words, if you forget to call this routine during initialization,
-the worst thing that will happen is that
-ProcessInputEvents will be called when
-there are no events to process.
-</para>
-<para>
-p1 and p2 might
-point at the head and tail of some shared
-memory queue.
-Another use would be to have one point at a constant 0, with the
-other pointing at some mask containing 1s
-for each input device that has
-something pending.
-</para>
-<para>
-The DDX layer of the sample server calls SetInputCheck()
-once when the
-server's private internal queue is initialized.
-It passes pointers to the queue's head and tail. See Xserver/mi/mieq.c.
-</para>
-<para>
-<blockquote><programlisting>
- int TimeSinceLastInputEvent()
-</programlisting></blockquote>
-DDX must time stamp all hardware input
-events. But DIX sometimes needs to know the
-time and the OS layer needs to know the time since the last hardware
-input event in
-order for the screen saver to work. TimeSinceLastInputEvent() returns
-the this time in milliseconds.
-</para>
-</section>
-<section>
- <title>Controlling Input Devices</title>
-<para>
-You must write four routines to do various device-specific
-things with the keyboard and pointing device.
-They can have any name you wish because
-you pass the procedure pointers to DIX routines.
-</para>
-<para>
-<blockquote><programlisting>
-
- int pInternalDevice->valuator->GetMotionProc(pdevice, coords, start, stop, pScreen)
- DeviceIntPtr pdevice;
- xTimecoord * coords;
- unsigned long start;
- unsigned long stop;
- ScreenPtr pScreen;
-</programlisting></blockquote>
-You write this DDX routine to fill in coords with all the motion
-events that have times (32-bit count of milliseconds) between time
-start and time stop. It should return the number of motion events
-returned. If there is no motion events support, this routine should
-do nothing and return zero. The maximum number of coords to return is
-set in InitPointerDeviceStruct(), below.
-</para>
-<para>
-When the user drags the pointing device, the cursor position
-theoretically sweeps through an infinite number of points. Normally,
-a client that is concerned with points other than the starting and
-ending points will receive a pointer-move event only as often as the
-server generates them. (Move events do not queue up; each new one
-replaces the last in the queue.) A server, if desired, can implement
-a scheme to save these intermediate events in a motion buffer. A
-client application, like a paint program, may then request that these
-events be delivered to it through the GetMotionProc routine.
-</para>
-<para>
-<blockquote><programlisting>
-
- void pInternalDevice->bell->BellProc(percent, pDevice, ctrl, unknown)
- int percent;
- DeviceIntPtr pDevice;
- pointer ctrl;
- int class;
-</programlisting></blockquote>
-You need to write this routine to ring the bell on the keyboard.
-loud is a number from 0 to 100, with 100 being the loudest.
-Class is either BellFeedbackClass or KbdFeedbackClass (from XI.h).
-</para>
-<para>
-<blockquote><programlisting>
-
- void pInternalDevice->somedevice->CtrlProc(device, ctrl)
- DevicePtr device;
- SomethingCtrl *ctrl;
-
-</programlisting></blockquote>
-You write two versions of this procedure, one for the keyboard and one for the pointing device.
-DIX calls it to inform DDX when a client has requested changes in the current
-settings for the particular device.
-For a keyboard, this might be the repeat threshold and rate.
-For a pointing device, this might be a scaling factor (coarse or fine) for position reporting.
-See input.h for the ctrl structures.
-</para>
-</section>
-<section>
- <title>Input Initialization</title>
-<para>
-Input initialization is a bit complicated.
-It all starts with InitInput(), a routine that you write to call
-AddInputDevice() twice
-(once for pointing device and once for keyboard.)
-</para>
-<para>
-When you Add the devices, a routine you supply for each device
-gets called to initialize them.
-Your individual initialize routines must call InitKeyboardDeviceStruct()
-or InitPointerDeviceStruct(), depending upon which it is.
-In other words, you indicate twice that the keyboard is the keyboard and
-the pointer is the pointer.
-</para>
-<para>
-<blockquote><programlisting>
-
- void InitInput(argc, argv)
- int argc;
- char **argv;
-</programlisting></blockquote>
-InitInput is a DDX routine you must write to initialize the
-input subsystem in DDX.
-It must call AddInputDevice() for each device that might generate events.
-</para>
-<para>
-<blockquote><programlisting>
-
- DevicePtr AddInputDevice(deviceProc, autoStart)
- DeviceProc deviceProc;
- Bool autoStart;
-</programlisting></blockquote>
-AddInputDevice is a DIX routine you call to create a device object.
-deviceProc is a DDX routine that is called by DIX to do various operations.
-AutoStart should be TRUE for devices that need to be turned on at
-initialization time with a special call, as opposed to waiting for some
-client application to
-turn them on.
-This routine returns NULL if sufficient memory cannot be allocated to
-install the device.
-</para>
-<para>
-Note also that except for the main keyboard and pointing device,
-an extension is needed to provide for a client interface to a device.
-</para>
-<para>
-The following DIX
-procedures return the specified DevicePtr. They may or may not be useful
-to DDX implementors.
-</para>
-<para>
-<blockquote><programlisting>
-
- DevicePtr LookupKeyboardDevice()
-</programlisting></blockquote>
-LookupKeyboardDevice returns pointer for current main keyboard device.
-</para>
-<para>
-<blockquote><programlisting>
-
- DevicePtr LookupPointerDevice()
-</programlisting></blockquote>
-LookupPointerDevice returns pointer for current main pointing device.
-</para>
-<para>
-A DeviceProc (the kind passed to AddInputDevice()) in the following form:
-<blockquote><programlisting>
-
- Bool pInternalDevice->DeviceProc(device, action);
- DeviceIntPtr device;
- int action;
-</programlisting></blockquote>
-You must write a DeviceProc for each device.
-device points to the device record.
-action tells what action to take;
-it will be one of these defined constants (defined in input.h):
-<itemizedlist>
-<listitem><para>
-DEVICE_INIT -
-At DEVICE_INIT time, the device should initialize itself by calling
-InitPointerDeviceStruct(), InitKeyboardDeviceStruct(), or a similar
-routine (see below)
-and "opening" the device if necessary.
-If you return a non-zero (i.e., != Success) value from the DEVICE_INIT
-call, that device will be considered unavailable. If either the main keyboard
-or main pointing device cannot be initialized, the DIX code will refuse
-to continue booting up.</para></listitem>
-<listitem><para>
-DEVICE_ON - If the DeviceProc is called with DEVICE_ON, then it is
-allowed to start
-putting events into the client stream by calling through the ProcessInputProc
-in the device.</para></listitem>
-<listitem><para>
-DEVICE_OFF - If the DeviceProc is called with DEVICE_OFF, no further
-events from that
-device should be given to the DIX layer.
-The device will appear to be dead to the user.</para></listitem>
-<listitem><para>
-DEVICE_CLOSE - At DEVICE_CLOSE (terminate or reset) time, the device should
-be totally closed down.</para></listitem>
-</itemizedlist>
-</para>
-<para>
-<blockquote><programlisting>
-
- void InitPointerDeviceStruct(device, map, mapLength,
- GetMotionEvents, ControlProc, numMotionEvents)
- DevicePtr device;
- CARD8 *map;
- int mapLength;
- ValuatorMotionProcPtr ControlProc;
- PtrCtrlProcPtr GetMotionEvents;
- int numMotionEvents;
-</programlisting></blockquote>
-InitPointerDeviceStruct is a DIX routine you call at DEVICE_INIT time to declare
-some operating routines and data structures for a pointing device.
-map and mapLength are as described in the X Window
-System protocol specification.
-ControlProc and GetMotionEvents are DDX routines, see above.
-</para>
-<para>
-numMotionEvents is for the motion-buffer-size for the GetMotionEvents
-request.
-A typical length for a motion buffer would be 100 events.
-A server that does not implement this capability should set
-numMotionEvents to zero.
-</para>
-<para>
-<blockquote><programlisting>
-
- void InitKeyboardDeviceStruct(device, pKeySyms, pModifiers, Bell, ControlProc)
- DevicePtr device;
- KeySymsPtr pKeySyms;
- CARD8 *pModifiers;
- BellProcPtr Bell;
- KbdCtrlProcPtr ControlProc;
-
-</programlisting></blockquote>
-You call this DIX routine when a keyboard device is initialized and
-its device procedure is called with
-DEVICE_INIT.
-The formats of the keysyms and modifier maps are defined in
-Xserver/include/input.h.
-They describe the layout of keys on the keyboards, and the glyphs
-associated with them. ( See the next section for information on
-setting up the modifier map and the keysym map.)
-ControlProc and Bell are DDX routines, see above.
-</para>
-</section>
-<section>
- <title>Keyboard Mapping and Keycodes</title>
-<para>
-When you send a keyboard event, you send a report that a given key has
-either been pressed or has been released. There must be a keycode for
-each key that identifies the key; the keycode-to-key mapping can be
-any mapping you desire, because you specify the mapping in a table you
-set up for DIX. However, you are restricted by the protocol
-specification to keycode values in the range 8 to 255 inclusive.
-</para>
-<para>
-The keycode mapping information that you set up consists of the following:
-<itemizedlist>
-<listitem><para>
-A minimum and maximum keycode number</para></listitem>
-<listitem><para>
-An array of sets of keysyms for each key, that is of length
-maxkeycode - minkeycode + 1.
-Each element of this array is a list of codes for symbols that are on that key.
-There is no limit to the number of symbols that can be on a key.</para></listitem>
-</itemizedlist>
-Once the map is set up, DIX keeps and
-maintains the client's changes to it.
-</para>
-<para>
-The X protocol defines standard names to indicate the symbol(s)
-printed on each keycap. (See X11/keysym.h)
-</para>
-<para>
-Legal modifier keys must generate both up and down transitions. When
-a client tries to change a modifier key (for instance, to make "A" the
-"Control" key), DIX calls the following routine, which should return
-TRUE if the key can be used as a modifier on the given device:
-<blockquote><programlisting>
-
- Bool LegalModifier(key, pDev)
- unsigned int key;
- DevicePtr pDev;
-</programlisting></blockquote>
-</para>
-</section>
-</section>
-<section>
-<title>Screens</title>
-<para>
-Different computer graphics
-displays have different capabilities.
-Some are simple monochrome
-frame buffers that are just lying
-there in memory, waiting to be written into.
-Others are color displays with many bits per pixel using some color lookup table.
-Still others have high-speed graphic processors that prefer to do all of the work
-themselves,
-including maintaining their own high-level, graphic data structures.
-</para>
-<section>
- <title>Screen Hardware Requirements</title>
-<para>
-The only requirement on screens is that you be able to both read
-and write locations in the frame buffer.
-All screens must have a depth of 32 or less (unless you use
-an X extension to allow a greater depth).
-All screens must fit into one of the classes listed in the section
-in this document on Visuals and Depths.
-</para>
-<para>
-X uses the pixel as its fundamental unit of distance on the screen.
-Therefore, most programs will measure everything in pixels.</para>
-<para>
-The sample server assumes square pixels.
-Serious WYSIWYG (what you see is what you get) applications for
-publishing and drawing programs will adjust for
-different screen resolutions automatically.
-Considerable work
-is involved in compensating for non-square pixels (a bit in the DDX
-code for the sample server but quite a bit in the client applications).</para>
-</section>
-<section>
- <title>Data Structures</title>
-<para>
-X supports multiple screens that are connected to the same
-server. Therefore, all the per-screen information is bundled into one data
-structure of attributes and procedures, which is the ScreenRec (see
-Xserver/include/scrnintstr.h).
-The procedure entry points in a ScreenRec operate on
-regions, colormaps, cursors, and fonts, because these resources
-can differ in format from one screen to another.</para>
-<para>
-Windows are areas on the screen that can be drawn into by graphic
-routines. "Pixmaps" are off-screen graphic areas that can be drawn
-into. They are both considered drawables and are described in the
-section on Drawables. All graphic operations work on drawables, and
-operations are available to copy patches from one drawable to another.</para>
-<para>
-The pixel image data in all drawables is in a format that is private
-to DDX. In fact, each instance of a drawable is associated with a
-given screen. Presumably, the pixel image data for pixmaps is chosen
-to be conveniently understood by the hardware. All screens in a
-single server must be able to handle all pixmaps depths declared in
-the connection setup information.</para>
-<para>
-Pixmap images are transferred to the server in one of two ways:
-XYPixmap or ZPimap. XYPixmaps are a series of bitmaps, one for each
-bit plane of the image, using the bitmap padding rules from the
-connection setup. ZPixmaps are a series of bits, nibbles, bytes or
-words, one for each pixel, using the format rules (padding and so on)
-for the appropriate depth.</para>
-<para>
-All screens in a given server must agree on a set of pixmap image
-formats (PixmapFormat) to support (depth, number of bits per pixel,
-etc.).</para>
-<para>
-There is no color interpretation of bits in the pixmap. Pixmaps
-do not contain pixel values. The interpretation is made only when
-the bits are transferred onto the screen.</para>
-<para>
-The screenInfo structure (in scrnintstr.h) is a global data structure
-that has a pointer to an array of ScreenRecs, one for each screen on
-the server. (These constitute the one and only description of each
-screen in the server.) Each screen has an identifying index (0, 1, 2, ...).
-In addition, the screenInfo struct contains global server-wide
-details, such as the bit- and byte- order in all bit images, and the
-list of pixmap image formats that are supported. The X protocol
-insists that these must be the same for all screens on the server.</para>
-</section>
-<section>
- <title>Output Initialization</title>
-<para>
-<blockquote><programlisting>
-
- InitOutput(pScreenInfo, argc, argv)
- ScreenInfo *pScreenInfo;
- int argc;
- char **argv;
-</programlisting></blockquote>
-Upon initialization, your DDX routine InitOutput() is called by DIX.
-It is passed a pointer to screenInfo to initialize. It is also passed
-the argc and argv from main() for your server for the command-line
-arguments. These arguments may indicate what or how many screen
-device(s) to use or in what way to use them. For instance, your
-server command line may allow a "-D" flag followed by the name of the
-screen device to use.</para>
-<para>
-Your InitOutput() routine should initialize each screen you wish to
-use by calling AddScreen(), and then it should initialize the pixmap
-formats that you support by storing values directly into the
-screenInfo data structure. You should also set certain
-implementation-dependent numbers and procedures in your screenInfo,
-which determines the pixmap and scanline padding rules for all screens
-in the server.</para>
-<para>
-<blockquote><programlisting>
-
- int AddScreen(scrInitProc, argc, argv)
- Bool (*scrInitProc)();
- int argc;
- char **argv;
-</programlisting></blockquote>
-You should call AddScreen(), a DIX procedure, in InitOutput() once for
-each screen to add it to the screenInfo database. The first argument
-is an initialization procedure for the screen that you supply. The
-second and third are the argc and argv from main(). It returns the
-screen number of the screen installed, or -1 if there is either
-insufficient memory to add the screen, or (*scrInitProc) returned
-FALSE.</para>
-<para>
-The scrInitProc should be of the following form:
-<blockquote><programlisting>
-
- Bool scrInitProc(iScreen, pScreen, argc, argv)
- int iScreen;
- ScreenPtr pScreen;
- int argc;
- char **argv;
-</programlisting></blockquote>
-iScreen is the index for this screen; 0 for the first one initialized,
-1 for the second, etc. pScreen is the pointer to the screen's new
-ScreenRec. argc and argv are as before. Your screen initialize
-procedure should return TRUE upon success or FALSE if the screen
-cannot be initialized (for instance, if the screen hardware does not
-exist on this machine).</para>
-<para>
-This procedure must determine what actual device it is supposed to initialize.
-If you have a different procedure for each screen, then it is no problem.
-If you have the same procedure for multiple screens, it may have trouble
-figuring out which screen to initialize each time around, especially if
-InitOutput() does not initialize all of the screens.
-It is probably easiest to have one procedure for each screen.</para>
-<para>
-The initialization procedure should fill in all the screen procedures
-for that screen (windowing functions, region functions, etc.) and certain
-screen attributes for that screen.</para>
-</section>
-<section>
- <title>Region Routines in the ScreenRec</title>
-<para>
-A region is a dynamically allocated data structure that describes an
-irregularly shaped piece of real estate in XY pixel space. You can
-think of it as a set of pixels on the screen to be operated upon with
-set operations such as AND and OR.</para>
-<para>
-A region is frequently implemented as a list of rectangles or bitmaps
-that enclose the selected pixels. Region operators control the
-"clipping policy," or the operations that work on regions. (The
-sample server uses YX-banded rectangles. Unless you have something
-already implemented for your graphics system, you should keep that
-implementation.) The procedure pointers to the region operators are
-located in the ScreenRec data structure. The definition of a region
-can be found in the file Xserver/include/regionstr.h. The region code
-is found in Xserver/mi/miregion.c. DDX implementations using other
-region formats will need to supply different versions of the region
-operators.</para>
-<para>
-Since the list of rectangles is unbounded in size, part of the region
-data structure is usually a large, dynamically allocated chunk of
-memory. As your region operators calculate logical combinations of
-regions, these blocks may need to be reallocated by your region
-software. For instance, in the sample server, a RegionRec has some
-header information and a pointer to a dynamically allocated rectangle
-list. Periodically, the rectangle list needs to be expanded with
-Xrealloc(), whereupon the new pointer is remembered in the RegionRec.</para>
-<para>
-Most of the region operations come in two forms: a function pointer in
-the Screen structure, and a macro. The server can be compiled so that
-the macros make direct calls to the appropriate functions (instead of
-indirecting through a screen function pointer), or it can be compiled
-so that the macros are identical to the function pointer forms.
-Making direct calls is faster on many architectures.</para>
-<para>
-<blockquote><programlisting>
-
- RegionPtr pScreen->RegionCreate( rect, size)
- BoxPtr rect;
- int size;
-
- macro: RegionPtr RegionCreate(rect, size)
-
-</programlisting></blockquote>
-RegionCreate creates a region that describes ONE rectangle. The
-caller can avoid unnecessary reallocation and copying by declaring the
-probable maximum number of rectangles that this region will need to
-describe itself. Your region routines, though, cannot fail just
-because the region grows beyond this size. The caller of this routine
-can pass almost anything as the size; the value is merely a good guess
-as to the maximum size until it is proven wrong by subsequent use.
-Your region procedures are then on their own in estimating how big the
-region will get. Your implementation might ignore size, if
-applicable.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RegionInit (pRegion, rect, size)
- RegionPtr pRegion;
- BoxPtr rect;
- int size;
-
- macro: RegionInit(pRegion, rect, size)
-
-</programlisting></blockquote>
-Given an existing raw region structure (such as an local variable), this
-routine fills in the appropriate fields to make this region as usable as
-one returned from RegionCreate. This avoids the additional dynamic memory
-allocation overhead for the region structure itself.
-</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->RegionCopy(dstrgn, srcrgn)
- RegionPtr dstrgn, srcrgn;
-
- macro: Bool RegionCopy(dstrgn, srcrgn)
-
-</programlisting></blockquote>
-RegionCopy copies the description of one region, srcrgn, to another
-already-created region,
-dstrgn; returning TRUE if the copy succeeded, and FALSE otherwise.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RegionDestroy( pRegion)
- RegionPtr pRegion;
-
- macro: RegionDestroy(pRegion)
-
-</programlisting></blockquote>
-RegionDestroy destroys a region and frees all allocated memory.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RegionUninit (pRegion)
- RegionPtr pRegion;
-
- macro: RegionUninit(pRegion)
-
-</programlisting></blockquote>
-Frees everything except the region structure itself, useful when the
-region was originally passed to RegionInit instead of received from
-RegionCreate. When this call returns, pRegion must not be reused until
-it has been RegionInit'ed again.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->Intersect(newReg, reg1, reg2)
- RegionPtr newReg, reg1, reg2;
-
- macro: Bool RegionIntersect(newReg, reg1, reg2)
-
- Bool pScreen->Union(newReg, reg1, reg2)
- RegionPtr newReg, reg1, reg2;
-
- macro: Bool RegionUnion(newReg, reg1, reg2)
-
- Bool pScreen->Subtract(newReg, regMinuend, regSubtrahend)
- RegionPtr newReg, regMinuend, regSubtrahend;
-
- macro: Bool RegionUnion(newReg, regMinuend, regSubtrahend)
-
- Bool pScreen->Inverse(newReg, pReg, pBox)
- RegionPtr newReg, pReg;
- BoxPtr pBox;
-
- macro: Bool RegionInverse(newReg, pReg, pBox)
-
-</programlisting></blockquote>
-The above four calls all do basic logical operations on regions. They
-set the new region (which already exists) to describe the logical
-intersection, union, set difference, or inverse of the region(s) that
-were passed in. Your routines must be able to handle a situation
-where the newReg is the same region as one of the other region
-arguments.</para>
-<para>
-The subtract function removes the Subtrahend from the Minuend and
-puts the result in newReg.</para>
-<para>
-The inverse function returns a region that is the pBox minus the
-region passed in. (A true "inverse" would make a region that extends
-to infinity in all directions but has holes in the middle.) It is
-undefined for situations where the region extends beyond the box.</para>
-<para>
-Each routine must return the value TRUE for success.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RegionReset(pRegion, pBox)
- RegionPtr pRegion;
- BoxPtr pBox;
-
- macro: RegionReset(pRegion, pBox)
-
-</programlisting></blockquote>
-RegionReset sets the region to describe
-one rectangle and reallocates it to a size of one rectangle, if applicable.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->TranslateRegion(pRegion, x, y)
- RegionPtr pRegion;
- int x, y;
-
- macro: RegionTranslate(pRegion, x, y)
-
-</programlisting></blockquote>
-TranslateRegion simply moves a region +x in the x direction and +y in the y
-direction.</para>
-<para>
-<blockquote><programlisting>
-
- int pScreen->RectIn(pRegion, pBox)
- RegionPtr pRegion;
- BoxPtr pBox;
-
- macro: int RegionContainsRect(pRegion, pBox)
-
-</programlisting></blockquote>
-RectIn returns one of the defined constants rgnIN, rgnOUT, or rgnPART,
-depending upon whether the box is entirely inside the region, entirely
-outside of the region, or partly in and partly out of the region.
-These constants are defined in Xserver/include/region.h.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->PointInRegion(pRegion, x, y, pBox)
- RegionPtr pRegion;
- int x, y;
- BoxPtr pBox;
-
- macro: Bool RegionContainsPoint(pRegion, x, y, pBox)
-
-</programlisting></blockquote>
-PointInRegion returns true if the point x, y is in the region. In
-addition, it fills the rectangle pBox with coordinates of a rectangle
-that is entirely inside of pRegion and encloses the point. In the mi
-implementation, it is the largest such rectangle. (Due to the sample
-server implementation, this comes cheaply.)</para>
-<para>
-This routine used by DIX when tracking the pointing device and
-deciding whether to report mouse events or change the cursor. For
-instance, DIX needs to change the cursor when it moves from one window
-to another. Due to overlapping windows, the shape to check may be
-irregular. A PointInRegion() call for every pointing device movement
-may be too expensive. The pBox is a kind of wake-up box; DIX need not
-call PointInRegion() again until the cursor wanders outside of the
-returned box.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->RegionNotEmpty(pRegion)
- RegionPtr pRegion;
-
- macro: Bool RegionNotEmpty(pRegion)
-
-</programlisting></blockquote>
-RegionNotEmpty is a boolean function that returns
-true or false depending upon whether the region encloses any pixels.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RegionEmpty(pRegion)
- RegionPtr pRegion;
-
- macro: RegionEmpty(pRegion)
-
-</programlisting></blockquote>
-RegionEmpty sets the region to be empty.</para>
-<para>
-<blockquote><programlisting>
-
- BoxPtr pScreen->RegionExtents(pRegion)
- RegionPtr pRegion;
-
- macro: RegionExtents(pRegion)
-
-</programlisting></blockquote>
-RegionExtents returns a rectangle that is the smallest
-possible superset of the entire region.
-The caller will not modify this rectangle, so it can be the one
-in your region struct.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->RegionAppend (pDstRgn, pRegion)
- RegionPtr pDstRgn;
- RegionPtr pRegion;
-
- macro: Bool RegionAppend(pDstRgn, pRegion)
-
- Bool pScreen->RegionValidate (pRegion, pOverlap)
- RegionPtr pRegion;
- Bool *pOverlap;
-
- macro: Bool RegionValidate(pRegion, pOverlap)
-
-</programlisting></blockquote>
-These functions provide an optimization for clip list generation and
-must be used in conjunction. The combined effect is to produce the
-union of a collection of regions, by using RegionAppend several times,
-and finally calling RegionValidate which takes the intermediate
-representation (which needn't be a valid region) and produces the
-desired union. pOverlap is set to TRUE if any of the original
-regions overlap; FALSE otherwise.</para>
-<para>
-<blockquote><programlisting>
-
- RegionPtr pScreen->BitmapToRegion (pPixmap)
- PixmapPtr pPixmap;
-
- macro: RegionPtr BitmapToRegion(pScreen, pPixmap)
-
-</programlisting></blockquote>
-Given a depth-1 pixmap, this routine must create a valid region which
-includes all the areas of the pixmap filled with 1's and excludes the
-areas filled with 0's. This routine returns NULL if out of memory.</para>
-<para>
-<blockquote><programlisting>
-
- RegionPtr pScreen->RectsToRegion (nrects, pRects, ordering)
- int nrects;
- xRectangle *pRects;
- int ordering;
-
- macro: RegionPtr RegionFromRects(nrects, pRects, ordering)
-
-</programlisting></blockquote>
-Given a client-supplied list of rectangles, produces a region which includes
-the union of all the rectangles. Ordering may be used as a hint which
-describes how the rectangles are sorted. As the hint is provided by a
-client, it must not be required to be correct, but the results when it is
-not correct are not defined (core dump is not an option here).</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->SendGraphicsExpose(client,pRegion,drawable,major,minor)
- ClientPtr client;
- RegionPtr pRegion;
- XID drawable;
- int major;
- int minor;
-
-</programlisting></blockquote>
-SendGraphicsExpose dispatches a list of GraphicsExposure events which
-span the region to the specified client. If the region is empty, or
-a NULL pointer, a NoExpose event is sent instead.</para>
-</section>
-<section>
- <title>Cursor Routines for a Screen</title>
-<para>
-A cursor is the visual form tied to the pointing device. The default
-cursor is an "X" shape, but the cursor can have any shape. When a
-client creates a window, it declares what shape the cursor will be
-when it strays into that window on the screen.</para>
-<para>
-For each possible shape the cursor assumes, there is a CursorRec data
-structure. This data structure contains a pointer to a CursorBits
-data structure which contains a bitmap for the image of the cursor and
-a bitmap for a mask behind the cursor, in addition, the CursorRec data
-structure contains foreground and background colors for the cursor.
-The CursorBits data structure is shared among multiple CursorRec
-structures which use the same font and glyph to describe both source
-and mask. The cursor image is applied to the screen by applying the
-mask first, clearing 1 bits in its form to the background color, and
-then overwriting on the source image, in the foreground color. (One
-bits of the source image that fall on top of zero bits of the mask
-image are undefined.) This way, a cursor can have transparent parts,
-and opaque parts in two colors. X allows any cursor size, but some
-hardware cursor schemes allow a maximum of N pixels by M pixels.
-Therefore, you are allowed to transform the cursor to a smaller size,
-but be sure to include the hot-spot.</para>
-<para>
-CursorBits in Xserver/include/cursorstr.h is a device-independent
-structure containing a device-independent representation of the bits
-for the source and mask. (This is possible because the bitmap
-representation is the same for all screens.)</para>
-<para>
-When a cursor is created, it is "realized" for each screen. At
-realization time, each screen has the chance to convert the bits into
-some other representation that may be more convenient (for instance,
-putting the cursor into off-screen memory) and set up its
-device-private area in either the CursorRec data structure or
-CursorBits data structure as appropriate to possibly point to whatever
-data structures are needed. It is more memory-conservative to share
-realizations by using the CursorBits private field, but this makes the
-assumption that the realization is independent of the colors used
-(which is typically true). For instance, the following are the device
-private entries for a particular screen and cursor:
-<blockquote><programlisting>
-
- pCursor->devPriv[pScreen->myNum]
- pCursor->bits->devPriv[pScreen->myNum]
-
-</programlisting></blockquote>
-This is done because the change from one cursor shape to another must
-be fast and responsive; the cursor image should be able to flutter as
-fast as the user moves it across the screen.</para>
-<para>
-You must implement the following routines for your hardware:
-<blockquote><programlisting>
-
- Bool pScreen->RealizeCursor( pScr, pCurs)
- ScreenPtr pScr;
- CursorPtr pCurs;
-
- Bool pScreen->UnrealizeCursor( pScr, pCurs)
- ScreenPtr pScr;
- CursorPtr pCurs;
-
-</programlisting></blockquote>
-</para>
-<para>
-RealizeCursor and UnrealizeCursor should realize (allocate and
-calculate all data needed) and unrealize (free the dynamically
-allocated data) a given cursor when DIX needs them. They are called
-whenever a device-independent cursor is created or destroyed. The
-source and mask bits pointed to by fields in pCurs are undefined for
-bits beyond the right edge of the cursor. This is so because the bits
-are in Bitmap format, which may have pad bits on the right edge. You
-should inhibit UnrealizeCursor() if the cursor is currently in use;
-this happens when the system is reset.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->DisplayCursor( pScr, pCurs)
- ScreenPtr pScr;
- CursorPtr pCurs;
-
-</programlisting></blockquote>
-DisplayCursor should change the cursor on the given screen to the one
-passed in. It is called by DIX when the user moves the pointing
-device into a different window with a different cursor. The hotspot
-in the cursor should be aligned with the current cursor position.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->RecolorCursor( pScr, pCurs, displayed)
- ScreenPtr pScr;
- CursorPtr pCurs;
- Bool displayed;
-</programlisting></blockquote>
-RecolorCursor notifies DDX that the colors in pCurs have changed and
-indicates whether this is the cursor currently being displayed. If it
-is, the cursor hardware state may have to be updated. Whether
-displayed or not, state created at RealizeCursor time may have to be
-updated. A generic version, miRecolorCursor, may be used that
-does an unrealize, a realize, and possibly a display (in micursor.c);
-however this constrains UnrealizeCursor and RealizeCursor to always return
-TRUE as no error indication is returned here.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ConstrainCursor( pScr, pBox)
- ScreenPtr pScr;
- BoxPtr pBox;
-
-</programlisting></blockquote>
-ConstrainCursor should cause the cursor to restrict its motion to the
-rectangle pBox. DIX code is capable of enforcing this constraint by
-forcefully moving the cursor if it strays out of the rectangle, but
-ConstrainCursor offers a way to send a hint to the driver or hardware
-if such support is available. This can prevent the cursor from
-wandering out of the box, then jumping back, as DIX forces it back.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->PointerNonInterestBox( pScr, pBox)
- ScreenPtr pScr;
- BoxPtr pBox;
-
-</programlisting></blockquote>
-PointerNonInterestBox is DIX's way of telling the pointing device code
-not to report motion events while the cursor is inside a given
-rectangle on the given screen. It is optional and, if not
-implemented, it should do nothing. This routine is called only when
-the client has declared that it is not interested in motion events in
-a given window. The rectangle you get may be a subset of that window.
-It saves DIX code the time required to discard uninteresting mouse
-motion events. This is only a hint, which may speed performance.
-Nothing in DIX currently calls PointerNonInterestBox.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->CursorLimits( pScr, pCurs, pHotBox, pTopLeftBox)
- ScreenPtr pScr;
- CursorPtr pCurs;
- BoxPtr pHotBox;
- BoxPtr pTopLeftBox; /* return value */
-
-</programlisting></blockquote>
-CursorLimits should calculate the box that the cursor hot spot is
-physically capable of moving within, as a function of the screen pScr,
-the device-independent cursor pCurs, and a box that DIX hypothetically
-would want the hot spot confined within, pHotBox. This routine is for
-informing DIX only; it alters no state within DDX.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->SetCursorPosition( pScr, newx, newy, generateEvent)
- ScreenPtr pScr;
- int newx;
- int newy;
- Bool generateEvent;
-
-</programlisting></blockquote>
-SetCursorPosition should artificially move the cursor as though the
-user had jerked the pointing device very quickly. This is called in
-response to the WarpPointer request from the client, and at other
-times. If generateEvent is True, the device should decide whether or
-not to call ProcessInputEvents() and then it must call
-DevicePtr->processInputProc. Its effects are, of course, limited in
-value for absolute pointing devices such as a tablet.</para>
-<para>
-<blockquote><programlisting>
-
- void NewCurrentScreen(newScreen, x, y)
- ScreenPtr newScreen;
- int x,y;
-
-</programlisting></blockquote>
-If your ddx provides some mechanism for the user to magically move the
-pointer between multiple screens, you need to inform DIX when this
-occurs. You should call NewCurrentScreen to accomplish this, specifying
-the new screen and the new x and y coordinates of the pointer on that screen.</para>
-</section>
-<section>
- <title>Visuals, Depths and Pixmap Formats for Screens</title>
-<para>
-The "depth" of a image is the number of bits that are used per pixel to display it.</para>
-<para>
-The "bits per pixel" of a pixmap image that is sent over the client
-byte stream is a number that is either 4, 8, 16, 24 or 32. It is the
-number of bits used per pixel in Z format. For instance, a pixmap
-image that has a depth of six is best sent in Z format as 8 bits per
-pixel.</para>
-<para>
-A "pixmap image format" or a "pixmap format" is a description of the
-format of a pixmap image as it is sent over the byte stream. For each
-depth available on a server, there is one and only one pixmap format.
-This pixmap image format gives the bits per pixel and the scanline
-padding unit. (For instance, are pixel rows padded to bytes, 16-bit
-words, or 32-bit words?)</para>
-<para>
-For each screen, you must decide upon what depth(s) it supports. You
-should only count the number of bits used for the actual image. Some
-displays store additional bits to indicate what window this pixel is
-in, how close this object is to a viewer, transparency, and other
-data; do not count these bits.</para>
-<para>
-A "display class" tells whether the display is monochrome or color,
-whether there is a lookup table, and how the lookup table works.</para>
-<para>
-A "visual" is a combination of depth, display class, and a description
-of how the pixel values result in a color on the screen. Each visual
-has a set of masks and offsets that are used to separate a pixel value
-into its red, green, and blue components and a count of the number of
-colormap entries. Some of these fields are only meaningful when the
-class dictates so. Each visual also has a screen ID telling which
-screen it is usable on. Note that the depth does not imply the number
-of map_entries; for instance, a display can have 8 bits per pixel but
-only 254 colormap entries for use by applications (the other two being
-reserved by hardware for the cursor).</para>
-<para>
-Each visual is identified by a 32-bit visual ID which the client uses
-to choose what visual is desired on a given window. Clients can be
-using more than one visual on the same screen at the same time.</para>
-<para>
-The class of a display describes how this translation takes place.
-There are three ways to do the translation.
-<itemizedlist>
-<listitem><para>
-Pseudo - The pixel value, as a whole, is looked up
-in a table of length map_entries to
-determine the color to display.</para></listitem>
-<listitem><para>
-True - The
-pixel value is broken up into red, green, and blue fields, each of which
-are looked up in separate red, green, and blue lookup tables,
-each of length map_entries.</para></listitem>
-<listitem><para>
-Gray - The pixel value is looked up in a table of length map_entries to
-determine a gray level to display.</para></listitem>
-</itemizedlist>
-</para>
-<para>
-In addition, the lookup table can be static (resulting colors are fixed for each
-pixel value)
-or dynamic (lookup entries are under control of the client program).
-This leads to a total of six classes:
-<itemizedlist>
-<listitem><para>
-Static Gray - The pixel value (of however many bits) determines directly the
-level of gray
-that the pixel assumes.</para></listitem>
-<listitem><para>
-Gray Scale - The pixel value is fed through a lookup table to arrive at the level
-of gray to display
-for the given pixel.</para></listitem>
-<listitem><para>
-Static Color - The pixel value is fed through a fixed lookup table that yields the
-color to display
-for that pixel.</para></listitem>
-<listitem><para>
-PseudoColor - The whole pixel value is fed through a programmable lookup
-table that has one
-color (including red, green, and blue intensities) for each possible pixel value,
-and that color is displayed.</para></listitem>
-<listitem><para>
-True Color - Each pixel value consists of one or more bits
-that directly determine each primary color intensity after being fed through
-a fixed table.</para></listitem>
-<listitem><para>
-Direct Color - Each pixel value consists of one or more bits for each primary color.
-Each primary color value is individually looked up in a table for that primary
-color, yielding
-an intensity for that primary color.
-For each pixel, the red value is looked up in the
-red table, the green value in the green table, and
-the blue value in the blue table.</para></listitem>
-</itemizedlist>
-</para>
-<para>
-Here are some examples:
-<itemizedlist>
-<listitem><para>
-A simple monochrome 1 bit per pixel display is Static Gray.</para></listitem>
-<listitem><para>
-A display that has 2 bits per pixel for a choice
-between the colors of black, white, green and violet is Static Color.</para></listitem>
-<listitem><para>
-A display that has three bits per pixel, where
-each bit turns on or off one of the red, green or
-blue guns, is in the True Color class.</para></listitem>
-<listitem><para>
-If you take the last example and scramble the
-correspondence between pixel values and colors
-it becomes a Static Color display.</para></listitem>
-</itemizedlist></para>
-<para>
-A display has 8 bits per pixel. The 8 bits select one entry out of 256 entries
-in a lookup table, each entry consisting of 24 bits (8bits each for red, green,
-and blue).
-The display can show any 256 of 16 million colors on the screen at once.
-This is a pseudocolor display.
-The client application gets to fill the lookup table in this class of display.</para>
-<para>
-Imagine the same hardware from the last example.
-Your server software allows the user, on the
-command line that starts up the server
-program,
-to fill the lookup table to his liking once and for all.
-From then on, the server software would not change the lookup table
-until it exits.
-For instance, the default might be a lookup table with a reasonable sample of
-colors from throughout the color space.
-But the user could specify that the table be filled with 256 steps of gray scale
-because he knew ahead of time he would be manipulating a lot of black-and-white
-scanned photographs
-and not very many color things.
-Clients would be presented with this unchangeable lookup table.
-Although the hardware qualifies as a PseudoColor display,
-the facade presented to the X client is that this is a Static Color display.</para>
-<para>
-You have to decide what kind of display you have or want
-to pretend you have.
-When you initialize the screen(s), this class value must be set in the
-VisualRec data structure along with other display characteristics like the
-depth and other numbers.</para>
-<para>
-The allowable DepthRec's and VisualRec's are pointed to by fields in the ScreenRec.
-These are set up when InitOutput() is called; you should Xalloc() appropriate blocks
-or use static variables initialized to the correct values.</para>
-</section>
-<section>
-<title>Colormaps for Screens</title>
-<para>
-A colormap is a device-independent
-mapping between pixel values and colors displayed on the screen.</para>
-<para>
-Different windows on the same screen can have different
-colormaps at the same time.
-At any given time, the most recently installed
-colormap(s) will be in use in the server
-so that its (their) windows' colors will be guaranteed to be correct.
-Other windows may be off-color.
-Although this may seem to be chaotic, in practice most clients
-use the default colormap for the screen.</para>
-<para>
-The default colormap for a screen is initialized when the screen is initialized.
-It always remains in existence and is not owned by any regular client. It
-is owned by client 0 (the server itself).
-Many clients will simply use this default colormap for their drawing.
-Depending upon the class of the screen, the entries in this colormap may
-be modifiable by client applications.</para>
-</section>
-<section>
- <title>Colormap Routines</title>
-<para>
-You need to implement the following routines to handle the device-dependent
-aspects of color maps. You will end up placing pointers to these procedures
-in your ScreenRec data structure(s). The sample server implementations of
-many of these routines are in fbcmap.c.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->CreateColormap(pColormap)
- ColormapPtr pColormap;
-
-</programlisting></blockquote>
-This routine is called by the DIX CreateColormap routine after it has allocated
-all the data for the new colormap and just before it returns to the dispatcher.
-It is the DDX layer's chance to initialize the colormap, particularly if it is
-a static map. See the following
-section for more details on initializing colormaps.
-The routine returns FALSE if creation failed, such as due to memory
-limitations.
-Notice that the colormap has a devPriv field from which you can hang any
-colormap specific storage you need. Since each colormap might need special
-information, we attached the field to the colormap and not the visual.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->DestroyColormap(pColormap)
- ColormapPtr pColormap;
-
-</programlisting></blockquote>
-This routine is called by the DIX FreeColormap routine after it has uninstalled
-the colormap and notified all interested parties, and before it has freed
-any of the colormap storage.
-It is the DDX layer's chance to free any data it added to the colormap.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->InstallColormap(pColormap)
- ColormapPtr pColormap;
-
-</programlisting></blockquote>
-InstallColormap should
-fill a lookup table on the screen with which the colormap is associated with
-the colors in pColormap.
-If there is only one hardware lookup table for the screen, then all colors on
-the screen may change simultaneously.</para>
-<para>
-In the more general case of multiple hardware lookup tables,
-this may cause some other colormap to be
-uninstalled, meaning that windows that subscribed to the colormap
-that was uninstalled may end up being off-color.
-See the note, below, about uninstalling maps.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->UninstallColormap(pColormap)
- ColormapPtr pColormap;
-
-</programlisting></blockquote>
-UninstallColormap should
-remove pColormap from screen pColormap->pScreen.
-Some other map, such as the default map if possible,
-should be installed in place of pColormap if applicable.
-If
-pColormap is the default map, do nothing.
-If any client has requested ColormapNotify events, the DDX layer must notify the client.
-(The routine WalkTree() is
-be used to find such windows. The DIX routines TellNoMap(),
-TellNewMap() and TellGainedMap() are provided to be used as
-the procedure parameter to WalkTree. These procedures are in
-Xserver/dix/colormap.c.)</para>
-<para>
-<blockquote><programlisting>
-
- int pScreen->ListInstalledColormaps(pScreen, pCmapList)
- ScreenPtr pScreen;
- XID *pCmapList;
-
-
-</programlisting></blockquote>
-ListInstalledColormaps fills the pCmapList in with the resource ids
-of the installed maps and returns a count of installed maps.
-pCmapList will point to an array of size MaxInstalledMaps that was allocated
-by the caller.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->StoreColors (pmap, ndef, pdefs)
- ColormapPtr pmap;
- int ndef;
- xColorItem *pdefs;
-
-</programlisting></blockquote>
-StoreColors changes some of the entries in the colormap pmap.
-The number of entries to change are ndef, and pdefs points to the information
-describing what to change.
-Note that partial changes of entries in the colormap are allowed.
-Only the colors
-indicated in the flags field of each xColorItem need to be changed.
-However, all three color fields will be sent with the proper value for the
-benefit of screens that may not be able to set part of a colormap value.
-If the screen is a static class, this routine does nothing.
-The structure of colormap entries is nontrivial; see colormapst.h
-and the definition of xColorItem in Xproto.h for
-more details.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ResolveColor(pRed, pGreen, pBlue, pVisual)
- unsigned short *pRed, *pGreen, *pBlue;
- VisualPtr pVisual;
-
-
-</programlisting></blockquote>
-Given a requested color, ResolveColor returns the nearest color that this hardware is
-capable of displaying on this visual.
-In other words, this rounds off each value, in place, to the number of bits
-per primary color that your screen can use.
-Remember that each screen has one of these routines.
-The level of roundoff should be what you would expect from the value
-you put in the bits_per_rgb field of the pVisual.</para>
-<para>
-Each value is an unsigned value ranging from 0 to 65535.
-The bits least likely to be used are the lowest ones.</para>
-<para>
-For example, if you had a pseudocolor display
-with any number of bits per pixel
-that had a lookup table supplying 6 bits for each color gun
-(a total of 256K different colors), you would
-round off each value to 6 bits. Please don't simply truncate these values
-to the upper 6 bits, scale the result so that the maximum value seen
-by the client will be 65535 for each primary. This makes color values
-more portable between different depth displays (a 6-bit truncated white
-will not look white on an 8-bit display).</para>
-<section>
-<title>Initializing a Colormap</title>
-<para>
-When a client requests a new colormap and when the server creates the default
-colormap, the procedure CreateColormap in the DIX layer is invoked.
-That procedure allocates memory for the colormap and related storage such as
-the lists of which client owns which pixels.
-It then sets a bit, BeingCreated, in the flags field of the ColormapRec
-and calls the DDX layer's CreateColormap routine.
-This is your chance to initialize the colormap.
-If the colormap is static, which you can tell by looking at the class field,
-you will want to fill in each color cell to match the hardwares notion of the
-color for that pixel.
-If the colormap is the default for the screen, which you can tell by looking
-at the IsDefault bit in the flags field, you should allocate BlackPixel
-and WhitePixel to match the values you set in the pScreen structure.
-(Of course, you picked those values to begin with.)</para>
-<para>
-You can also wait and use AllocColor() to allocate blackPixel
-and whitePixel after the default colormap has been created.
-If the default colormap is static and you initialized it in
-pScreen->CreateColormap, then use can use AllocColor afterwards
-to choose pixel values with the closest rgb values to those
-desired for blackPixel and whitePixel.
-If the default colormap is dynamic and uninitialized, then
-the rgb values you request will be obeyed, and AllocColor will
-again choose pixel values for you.
-These pixel values can then be stored into the screen.</para>
-<para>
-There are two ways to fill in the colormap.
-The simplest way is to use the DIX function AllocColor.
-<blockquote><programlisting>
-
-int AllocColor (pmap, pred, pgreen, pblue, pPix, client)
- ColormapPtr pmap;
- unsigned short *pred, *pgreen, *pblue;
- Pixel *pPix;
- int client;
-
-</programlisting></blockquote>
-This takes three pointers to 16 bit color values and a pointer to a suggested
-pixel value. The pixel value is either an index into one colormap or a
-combination of three indices depending on the type of pmap.
-If your colormap starts out empty, and you don't deliberately pick the same
-value twice, you will always get your suggested pixel.
-The truly nervous could check that the value returned in *pPix is the one
-AllocColor was called with.
-If you don't care which pixel is used, or would like them sequentially
-allocated from entry 0, set *pPix to 0. This will find the first free
-pixel and use that.</para>
-<para>
-AllocColor will take care of all the bookkeeping and will
-call StoreColors to get the colormap rgb values initialized.
-The hardware colormap will be changed whenever this colormap
-is installed.</para>
-<para>
-If for some reason AllocColor doesn't do what you want, you can do your
-own bookkeeping and call StoreColors yourself. This is much more difficult
-and shouldn't be necessary for most devices.</para>
-</section>
-</section>
-<section>
- <title>Fonts for Screens</title>
-<para>
-A font is a set of bitmaps that depict the symbols in a character set.
-Each font is for only one typeface in a given size, in other words,
-just one bitmap for each character. Parallel fonts may be available
-in a variety of sizes and variations, including "bold" and "italic."
-X supports fonts for 8-bit and 16-bit character codes (for oriental
-languages that have more than 256 characters in the font). Glyphs are
-bitmaps for individual characters.</para>
-<para>
-The source comes with some useful font files in an ASCII, plain-text
-format that should be comprehensible on a wide variety of operating
-systems. The text format, referred to as BDF, is a slight extension
-of the current Adobe 2.1 Bitmap Distribution Format (Adobe Systems,
-Inc.).</para>
-<para>
-A short paper in PostScript format is included with the sample server
-that defines BDF. It includes helpful pictures, which is why it is
-done in PostScript and is not included in this document.</para>
-<para>
-Your implementation should include some sort of font compiler to read
-these files and generate binary files that are directly usable by your
-server implementation. The sample server comes with the source for a
-font compiler.</para>
-<para>
-It is important the font properties contained in the BDF files are
-preserved across any font compilation. In particular, copyright
-information cannot be casually tossed aside without legal
-ramifications. Other properties will be important to some
-sophisticated applications.</para>
-<para>
-All clients get font information from the server. Therefore, your
-server can support any fonts it wants to. It should probably support
-at least the fonts supplied with the X11 tape. In principle, you can
-convert fonts from other sources or dream up your own fonts for use on
-your server.</para>
-<section>
-<title>Portable Compiled Format</title>
-<para>
-A font compiler is supplied with the sample server. It has
-compile-time switches to convert the BDF files into a portable binary
-form, called Portable Compiled Format or PCF. This allows for an
-arbitrary data format inside the file, and by describing the details
-of the format in the header of the file, any PCF file can be read by
-any PCF reading client. By selecting the format which matches the
-required internal format for your renderer, the PCF reader can avoid
-reformatting the data each time it is read in. The font compiler
-should be quite portable.</para>
-<para>
-The fonts included with the tape are stored in fonts/bdf. The
-font compiler is found in fonts/tools/bdftopcf.</para>
-</section>
-<section>
- <title>Font Realization</title>
-<para>
-Each screen configured into the server
-has an opportunity at font-load time
-to "realize" a font into some internal format if necessary.
-This happens every time the font is loaded into memory.</para>
-<para>
-A font (FontRec in Xserver/include/dixfontstr.h) is
-a device-independent structure containing a device-independent
-representation of the font. When a font is created, it is "realized"
-for each screen. At this point, the screen has the chance to convert
-the font into some other format. The DDX layer can also put information
-in the devPrivate storage.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->RealizeFont(pScr, pFont)
- ScreenPtr pScr;
- FontPtr pFont;
-
- Bool pScreen->UnrealizeFont(pScr, pFont)
- ScreenPtr pScr;
- FontPtr pFont;
-
-</programlisting></blockquote>
-RealizeFont and UnrealizeFont should calculate and allocate these extra data structures and
-dispose of them when no longer needed.
-These are called in response to OpenFont and CloseFont requests from
-the client.
-The sample server implementation is in fbscreen.c (which does very little).</para>
-</section>
-</section>
-<section>
- <title>Other Screen Routines</title>
-<para>
-You must supply several other screen-specific routines for
-your X server implementation.
-Some of these are described in other sections:
-<itemizedlist>
-<listitem><para>
-GetImage() is described in the Drawing Primitives section.</para></listitem>
-<listitem><para>
-GetSpans() is described in the Pixblit routine section.</para></listitem>
-<listitem><para>
-Several window and pixmap manipulation procedures are
-described in the Window section under Drawables.</para></listitem>
-<listitem><para>
-The CreateGC() routine is described under Graphics Contexts.</para></listitem>
-</itemizedlist>
-</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->QueryBestSize(kind, pWidth, pHeight)
- int kind;
- unsigned short *pWidth, *pHeight;
- ScreenPtr pScreen;
-
-</programlisting></blockquote>
-QueryBestSize() returns the best sizes for cursors, tiles, and stipples
-in response to client requests.
-kind is one of the defined constants CursorShape, TileShape, or StippleShape
-(defined in X.h).
-For CursorShape, return the maximum width and
-height for cursors that you can handle.
-For TileShape and StippleShape, start with the suggested values in pWidth
-and pHeight and modify them in place to be optimal values that are
-greater than or equal to the suggested values.
-The sample server implementation is in Xserver/fb/fbscreen.c.</para>
-<para>
-<blockquote><programlisting>
-
- pScreen->SourceValidate(pDrawable, x, y, width, height)
- DrawablePtr pDrawable;
- int x, y, width, height;
- unsigned int subWindowMode;
-
-</programlisting></blockquote>
-SourceValidate should be called by CopyArea/CopyPlane primitives when
-the SourceValidate function pointer in the screen is non-null. If you know that
-you will never need SourceValidate, you can avoid this check. Currently,
-SourceValidate is used by the mi software cursor code to remove the cursor
-from the screen when the source rectangle overlaps the cursor position.
-x,y,width,height describe the source rectangle (source relative, that is)
-for the copy operation. subWindowMode comes from the GC or source Picture.
-</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->SaveScreen(pScreen, on)
- ScreenPtr pScreen;
- int on;
-
-</programlisting></blockquote>
-SaveScreen() is used for Screen Saver support (see WaitForSomething()).
-pScreen is the screen to save.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->CloseScreen(pScreen)
- ScreenPtr pScreen;
-
-</programlisting></blockquote>
-When the server is reset, it calls this routine for each screen.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->CreateScreenResources(pScreen)
- ScreenPtr pScreen;
-
-</programlisting></blockquote>
-If this routine is not NULL, it will be called once per screen per
-server initialization/reset after all modules have had a chance to
-request private space on all structures that support them (see
-<xref linkend="wrappers_and_privates"/> below). You may create resources
-in this function instead of in the
-screen init function passed to AddScreen in order to guarantee that
-all pre-allocated space requests have been registered first. With the
-new devPrivates mechanism, this is not strictly necessary, however.
-This routine returns TRUE if successful.</para>
-</section>
-</section>
-<section>
-<title>Drawables</title>
-<para>
-A drawable is a descriptor of a surface that graphics are drawn into, either
-a window on the screen or a pixmap in memory.</para>
-<para>
-Each drawable has a type, class,
-ScreenPtr for the screen it is associated with, depth, position, size,
-and serial number.
-The type is one of the defined constants DRAWABLE_PIXMAP,
-DRAWABLE_WINDOW and UNDRAWABLE_WINDOW.
-(An undrawable window is used for window class InputOnly.)
-The serial number is guaranteed to be unique across drawables, and
-is used in determining
-the validity of the clipping information in a GC.
-The screen selects the set of procedures used to manipulate and draw into the
-drawable. Position is used (currently) only by windows; pixmaps must
-set these fields to 0,0 as this reduces the amount of conditional code
-executed throughout the mi code. Size indicates the actual client-specified
-size of the drawable.
-There are, in fact, no other fields that a window drawable and pixmap
-drawable have in common besides those mentioned here.</para>
-<para>
-Both PixmapRecs and WindowRecs are structs that start with a drawable
-and continue on with more fields. Pixmaps have a single pointer field
-named devPrivate which usually points to the pixmap data but could conceivably be
-used for anything that DDX wants. Both windows and pixmaps also have a
-devPrivates field which can be used for DDX specific data (see <xref linkend="wrappers_and_privates"/>
-below). This is done because different graphics hardware has
-different requirements for management; if the graphics is always
-handled by a processor with an independent address space, there is no
-point having a pointer to the bit image itself.</para>
-<para>
-The definition of a drawable and a pixmap can be found in the file
-Xserver/include/pixmapstr.h.
-The definition of a window can be found in the file Xserver/include/windowstr.h.</para>
-<section>
- <title>Pixmaps</title>
-<para>
-A pixmap is a three-dimensional array of bits stored somewhere offscreen,
-rather than in the visible portion of the screen's display frame buffer. It
-can be used as a source or destination in graphics operations. There is no
-implied interpretation of the pixel values in a pixmap, because it has no
-associated visual or colormap. There is only a depth that indicates the
-number of significant bits per pixel. Also, there is no implied physical
-size for each pixel; all graphic units are in numbers of pixels. Therefore,
-a pixmap alone does not constitute a complete image; it represents only a
-rectangular array of pixel values.</para>
-<para>
-Note that the pixmap data structure is reference-counted.</para>
-<para>
-The server implementation is free to put the pixmap data
-anywhere it sees fit, according to its graphics hardware setup. Many
-implementations will simply have the data dynamically allocated in the
-server's address space. More sophisticated implementations may put the
-data in undisplayed framebuffer storage.</para>
-<para>
-In addition to dynamic devPrivates (see <xref linkend="wrappers_and_privates"/>
-below), the pixmap data structure has two fields that are private to
-the device. Although you can use them for anything you want, they
-have intended purposes. devKind is intended to be a device specific
-indication of the pixmap location (host memory, off-screen, etc.). In
-the sample server, since all pixmaps are in memory, devKind stores the
-width of the pixmap in bitmap scanline units. devPrivate is usually
-a pointer to the bits in the pixmap.</para>
-<para>
-A bitmap is a pixmap that is one bit deep.</para>
-<para>
-<blockquote><programlisting>
-
- PixmapPtr pScreen->CreatePixmap(pScreen, width, height, depth)
- ScreenPtr pScreen;
- int width, height, depth;
-
-</programlisting></blockquote>
-This ScreenRec procedure must create a pixmap of the size
-requested.
-It must allocate a PixmapRec and fill in all of the fields.
-The reference count field must be set to 1.
-If width or height are zero, no space should be allocated
-for the pixmap data, and if the implementation is using the
-devPrivate field as a pointer to the pixmap data, it should be
-set to NULL.
-If successful, it returns a pointer to the new pixmap; if not, it returns NULL.
-See Xserver/fb/fbpixmap.c for the sample server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->DestroyPixmap(pPixmap)
- PixmapPtr pPixmap;
-
-</programlisting></blockquote>
-This ScreenRec procedure must "destroy" a pixmap.
-It should decrement the reference count and, if zero, it
-must deallocate the PixmapRec and all attached devPrivate blocks.
-If successful, it returns TRUE.
-See Xserver/fb/fbpixmap.c for the sample server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- Bool
- pScreen->ModifyPixmapHeader(pPixmap, width, height, depth, bitsPerPixel, devKind, pPixData)
- PixmapPtr pPixmap;
- int width;
- int height;
- int depth;
- int bitsPerPixel;
- int devKind;
- pointer pPixData;
-
-</programlisting></blockquote>
-This routine takes a pixmap header and initializes the fields of the PixmapRec to the
-parameters of the same name. pPixmap must have been created via
-pScreen->CreatePixmap with a zero width or height to avoid
-allocating space for the pixmap data. pPixData is assumed to be the
-pixmap data; it will be stored in an implementation-dependent place
-(usually pPixmap->devPrivate.ptr). This routine returns
-TRUE if successful. See Xserver/mi/miscrinit.c for the sample
-server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- PixmapPtr
- GetScratchPixmapHeader(pScreen, width, height, depth, bitsPerPixel, devKind, pPixData)
- ScreenPtr pScreen;
- int width;
- int height;
- int depth;
- int bitsPerPixel;
- int devKind;
- pointer pPixData;
-
- void FreeScratchPixmapHeader(pPixmap)
- PixmapPtr pPixmap;
-
-</programlisting></blockquote>
-DDX should use these two DIX routines when it has a buffer of raw
-image data that it wants to manipulate as a pixmap temporarily,
-usually so that some other part of the server can be leveraged to
-perform some operation on the data. The data should be passed in
-pPixData, and will be stored in an implementation-dependent place
-(usually pPixmap->devPrivate.ptr). The other
-fields go into the corresponding PixmapRec fields.
-If successful, GetScratchPixmapHeader returns a valid PixmapPtr which can
-be used anywhere the server expects a pixmap, else
-it returns NULL. The pixmap should be released when no longer needed
-(usually within the same function that allocated it)
-with FreeScratchPixmapHeader.</para>
-</section>
-<section>
- <title>Windows</title>
-<para>
-A window is a visible, or potentially visible, rectangle on the screen.
-DIX windowing functions maintain an internal n-ary tree data structure, which
-represents the current relationships of the mapped windows.
-Windows that are contained in another window are children of that window and
-are clipped to the boundaries of the parent.
-The root window in the tree is the window for the entire screen.
-Sibling windows constitute a doubly-linked list; the parent window has a pointer
-to the head and tail of this list.
-Each child also has a pointer to its parent.</para>
-<para>
-The border of a window is drawn by a DDX procedure when DIX requests that it
-be drawn. The contents of the window is drawn by the client through
-requests to the server.</para>
-<para>
-Window painting is orchestrated through an expose event system.
-When a region is exposed,
-DIX generates an expose event, telling the client to repaint the window and
-passing the region that is the minimal area needed to be repainted.</para>
-<para>
-As a favor to clients, the server may retain
-the output to the hidden parts of windows
-in off-screen memory; this is called "backing store".
-When a part of such a window becomes exposed, it
-can quickly move pixels into place instead of
-triggering an expose event and waiting for a client on the other
-end of the network to respond.
-Even if the network response is insignificant, the time to
-intelligently paint a section of a window is usually more than
-the time to just copy already-painted sections.
-At best, the repainting involves blanking out the area to a background color,
-which will take about the
-same amount of time.
-In this way, backing store can dramatically increase the
-performance of window moves.</para>
-<para>
-On the other hand, backing store can be quite complex, because
-all graphics drawn to hidden areas must be intercepted and redirected
-to the off-screen window sections.
-Not only can this be complicated for the server programmer,
-but it can also impact window painting performance.
-The backing store implementation can choose, at any time, to
-forget pieces of backing that are written into, relying instead upon
-expose events to repaint for simplicity.</para>
-<para>
-In X, the decision to use the backing-store scheme is made
-by you, the server implementor. The sample server implements
-backing store "for free" by reusing the infrastructure for the Composite
-extension. As a side effect, it treats the WhenMapped and Always hints
-as equivalent. However, it will never forget pixel contents when the
-window is mapped.</para>
-<para>
-When a window operation is requested by the client,
-such as a window being created or moved,
-a new state is computed.
-During this transition, DIX informs DDX what rectangles in what windows are about to
-become obscured and what rectangles in what windows have become exposed.
-This provides a hook for the implementation of backing store.
-If DDX is unable to restore exposed regions, DIX generates expose
-events to the client.
-It is then the client's responsibility to paint the
-window parts that were exposed but not restored.</para>
-<para>
-If a window is resized, pixels sometimes need to be
-moved, depending upon
-the application.
-The client can request "Gravity" so that
-certain blocks of the window are
-moved as a result of a resize.
-For instance, if the window has controls or other items
-that always hang on the edge of the
-window, and that edge is moved as a result of the resize,
-then those pixels should be moved
-to avoid having the client repaint it.
-If the client needs to repaint it anyway, such an operation takes
-time, so it is desirable
-for the server to approximate the appearance of the window as best
-it can while waiting for the client
-to do it perfectly.
-Gravity is used for that, also.</para>
-<para>
-The window has several fields used in drawing
-operations:
-<itemizedlist>
-<listitem><para>
-clipList - This region, in conjunction with
-the client clip region in the gc, is used to clip output.
-clipList has the window's children subtracted from it, in addition to pieces of sibling windows
-that overlap this window. To get the list with the
-children included (subwindow-mode is IncludeInferiors),
-the routine NotClippedByChildren(pWin) returns the unclipped region.</para></listitem>
-<listitem><para>
-borderClip is the region used by CopyWindow and
-includes the area of the window, its children, and the border, but with the
-overlapping areas of sibling children removed.</para></listitem>
-</itemizedlist>
-Most of the other fields are for DIX use only.</para>
-<section>
-<title>Window Procedures in the ScreenRec</title>
-<para>
-You should implement
-all of the following procedures and store pointers to them in the screen record.</para>
-<para>
-The device-independent portion of the server "owns" the window tree.
-However, clever hardware might want to know the relationship of
-mapped windows. There are pointers to procedures
-in the ScreenRec data structure that are called to give the hardware
-a chance to update its internal state. These are helpers and
-hints to DDX only;
-they do not change the window tree, which is only changed by DIX.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->CreateWindow(pWin)
- WindowPtr pWin;
-
-</programlisting></blockquote>
-This routine is a hook for when DIX creates a window.
-It should fill in the "Window Procedures in the WindowRec" below
-and also allocate the devPrivate block for it.</para>
-<para>
-See Xserver/fb/fbwindow.c for the sample server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->DestroyWindow(pWin);
- WindowPtr pWin;
-
-</programlisting></blockquote>
-This routine is a hook for when DIX destroys a window.
-It should deallocate the devPrivate block for it and any other blocks that need
-to be freed, besides doing other cleanup actions.</para>
-<para>
-See Xserver/fb/fbwindow.c for the sample server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->PositionWindow(pWin, x, y);
- WindowPtr pWin;
- int x, y;
-
-</programlisting></blockquote>
-This routine is a hook for when DIX moves or resizes a window.
-It should do whatever private operations need to be done when a window is moved or resized.
-For instance, if DDX keeps a pixmap tile used for drawing the background
-or border, and it keeps the tile rotated such that it is longword
-aligned to longword locations in the frame buffer, then you should rotate your tiles here.
-The actual graphics involved in moving the pixels on the screen and drawing the
-border are handled by CopyWindow(), below.</para>
-<para>
-See Xserver/fb/fbwindow.c for the sample server implementation.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->RealizeWindow(pWin);
- WindowPtr pWin;
-
- Bool pScreen->UnrealizeWindow(pWin);
- WindowPtr pWin;
-
-</programlisting></blockquote>
-These routines are hooks for when DIX maps (makes visible) and unmaps
-(makes invisible) a window. It should do whatever private operations
-need to be done when these happen, such as allocating or deallocating
-structures that are only needed for visible windows. RealizeWindow
-does NOT draw the window border, background or contents;
-UnrealizeWindow does NOT erase the window or generate exposure events
-for underlying windows; this is taken care of by DIX. DIX does,
-however, call PaintWindowBackground() and PaintWindowBorder() to
-perform some of these.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->ChangeWindowAttributes(pWin, vmask)
- WindowPtr pWin;
- unsigned long vmask;
-
-</programlisting></blockquote>
-ChangeWindowAttributes is called whenever DIX changes window
-attributes, such as the size, front-to-back ordering, title, or
-anything of lesser severity that affects the window itself. The
-sample server implements this routine. It computes accelerators for
-quickly putting up background and border tiles. (See description of
-the set of routines stored in the WindowRec.)</para>
-<para>
-<blockquote><programlisting>
-
- int pScreen->ValidateTree(pParent, pChild, kind)
- WindowPtr pParent, pChild;
- VTKind kind;
-
-</programlisting></blockquote>
-ValidateTree calculates the clipping region for the parent window and
-all of its children. This routine must be provided. The sample server
-has a machine-independent version in Xserver/mi/mivaltree.c. This is
-a very difficult routine to replace.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->PostValidateTree(pParent, pChild, kind)
- WindowPtr pParent, pChild;
- VTKind kind;
-
-</programlisting></blockquote>
-If this routine is not NULL, DIX calls it shortly after calling
-ValidateTree, passing it the same arguments. This is useful for
-managing multi-layered framebuffers.
-The sample server sets this to NULL.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->WindowExposures(pWin, pRegion, pBSRegion)
- WindowPtr pWin;
- RegionPtr pRegion;
- RegionPtr pBSRegion;
-
-</programlisting></blockquote>
-The WindowExposures() routine
-paints the border and generates exposure events for the window.
-pRegion is an unoccluded region of the window, and pBSRegion is an
-occluded region that has backing store.
-Since exposure events include a rectangle describing what was exposed,
-this routine may have to send back a series of exposure events, one for
-each rectangle of the region.
-The count field in the expose event is a hint to the
-client as to the number of
-regions that are after this one.
-This routine must be provided. The sample
-server has a machine-independent version in Xserver/mi/miexpose.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ClipNotify (pWin, dx, dy)
- WindowPtr pWin;
- int dx, dy;
-
-</programlisting></blockquote>
-Whenever the cliplist for a window is changed, this function is called to
-perform whatever hardware manipulations might be necessary. When called,
-the clip list and border clip regions in the window are set to the new
-values. dx,dy are the distance that the window has been moved (if at all).</para>
-</section>
-<section>
- <title>Window Painting Procedures</title>
-<para>
-In addition to the procedures listed above, there are two routines which
-manipulate the actual window image directly.
-In the sample server, mi implementations will work for
-most purposes and fb routines speed up situations, such
-as solid backgrounds/borders or tiles that are 8, 16 or 32 pixels square.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ClearToBackground(pWin, x, y, w, h, generateExposures);
- WindowPtr pWin;
- int x, y, w, h;
- Bool generateExposures;
-
-</programlisting></blockquote>
-This routine is called on a window in response to a ClearToBackground request
-from the client.
-This request has two different but related functions, depending upon generateExposures.</para>
-<para>
-If generateExposures is true, the client is declaring that the given rectangle
-on the window is incorrectly painted and needs to be repainted.
-The sample server implementation calculates the exposure region
-and hands it to the DIX procedure HandleExposures(), which
-calls the WindowExposures() routine, below, for the window
-and all of its child windows.</para>
-<para>
-If generateExposures is false, the client is trying to simply erase part
-of the window to the background fill style.
-ClearToBackground should write the background color or tile to the
-rectangle in question (probably using PaintWindowBackground).
-If w or h is zero, it clears all the way to the right or lower edge of the window.</para>
-<para>
-The sample server implementation is in Xserver/mi/miwindow.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->CopyWindow(pWin, oldpt, oldRegion);
- WindowPtr pWin;
- DDXPointRec oldpt;
- RegionPtr oldRegion;
-
-</programlisting></blockquote>
-CopyWindow is called when a window is moved, and graphically moves to
-pixels of a window on the screen. It should not change any other
-state within DDX (see PositionWindow(), above).</para>
-<para>
-oldpt is the old location of the upper-left corner. oldRegion is the
-old region it is coming from. The new location and new region is
-stored in the WindowRec. oldRegion might modified in place by this
-routine (the sample implementation does this).</para>
-<para>
-CopyArea could be used, except that this operation has more
-complications. First of all, you do not want to copy a rectangle onto
-a rectangle. The original window may be obscured by other windows,
-and the new window location may be similarly obscured. Second, some
-hardware supports multiple windows with multiple depths, and your
-routine needs to take care of that.</para>
-<para>
-The pixels in oldRegion (with reference point oldpt) are copied to the
-window's new region (pWin->borderClip). pWin->borderClip is gotten
-directly from the window, rather than passing it as a parameter.</para>
-<para>
-The sample server implementation is in Xserver/fb/fbwindow.c.</para>
-</section>
-<section>
-<title>Screen Operations for Multi-Layered Framebuffers</title>
-<para>
-The following screen functions are useful if you have a framebuffer with
-multiple sets of independent bit planes, e.g. overlays or underlays in
-addition to the "main" planes. If you have a simple single-layer
-framebuffer, you should probably use the mi versions of these routines
-in mi/miwindow.c. This can be easily accomplished by calling miScreenInit.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->MarkWindow(pWin)
- WindowPtr pWin;
-
-</programlisting></blockquote>
-This formerly dix function MarkWindow has moved to ddx and is accessed
-via this screen function. This function should store something,
-usually a pointer to a device-dependent structure, in pWin->valdata so
-that ValidateTree has the information it needs to validate the window.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->MarkOverlappedWindows(parent, firstChild, ppLayerWin)
- WindowPtr parent;
- WindowPtr firstChild;
- WindowPtr * ppLayerWin;
-
-</programlisting></blockquote>
-This formerly dix function MarkWindow has moved to ddx and is accessed
-via this screen function. In the process, it has grown another
-parameter: ppLayerWin, which is filled in with a pointer to the window
-at which save under marking and ValidateTree should begin. In the
-single-layered framebuffer case, pLayerWin == pWin.</para>
-<para>
-<blockquote><programlisting>
-
- Bool pScreen->ChangeSaveUnder(pLayerWin, firstChild)
- WindowPtr pLayerWin;
- WindowPtr firstChild;
-
-</programlisting></blockquote>
-The dix functions ChangeSaveUnder and CheckSaveUnder have moved to ddx and
-are accessed via this screen function. pLayerWin should be the window
-returned in the ppLayerWin parameter of MarkOverlappedWindows. The function
-may turn on backing store for windows that might be covered, and may partially
-turn off backing store for windows. It returns TRUE if PostChangeSaveUnder
-needs to be called to finish turning off backing store.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->PostChangeSaveUnder(pLayerWin, firstChild)
- WindowPtr pLayerWin;
- WindowPtr firstChild;
-
-</programlisting></blockquote>
-The dix function DoChangeSaveUnder has moved to ddx and is accessed via
-this screen function. This function completes the job of turning off
-backing store that was started by ChangeSaveUnder.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->MoveWindow(pWin, x, y, pSib, kind)
- WindowPtr pWin;
- int x;
- int y;
- WindowPtr pSib;
- VTKind kind;
-
-</programlisting></blockquote>
-The formerly dix function MoveWindow has moved to ddx and is accessed via
-this screen function. The new position of the window is given by
-x,y. kind is VTMove if the window is only moving, or VTOther if
-the border is also changing.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ResizeWindow(pWin, x, y, w, h, pSib)
- WindowPtr pWin;
- int x;
- int y;
- unsigned int w;
- unsigned int h;
- WindowPtr pSib;
-
-</programlisting></blockquote>
-The formerly dix function SlideAndSizeWindow has moved to ddx and is accessed via
-this screen function. The new position is given by x,y. The new size
-is given by w,h.</para>
-<para>
-<blockquote><programlisting>
-
- WindowPtr pScreen->GetLayerWindow(pWin)
- WindowPtr pWin
-
-</programlisting></blockquote>
-This is a new function which returns a child of the layer parent of pWin.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->HandleExposures(pWin)
- WindowPtr pWin;
-
-</programlisting></blockquote>
-The formerly dix function HandleExposures has moved to ddx and is accessed via
-this screen function. This function is called after ValidateTree and
-uses the information contained in valdata to send exposures to windows.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ReparentWindow(pWin, pPriorParent)
- WindowPtr pWin;
- WindowPtr pPriorParent;
-
-</programlisting></blockquote>
-This function will be called when a window is reparented. At the time of
-the call, pWin will already be spliced into its new position in the
-window tree, and pPriorParent is its previous parent. This function
-can be NULL.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->SetShape(pWin)
- WindowPtr pWin;
-
-</programlisting></blockquote>
-The formerly dix function SetShape has moved to ddx and is accessed via
-this screen function. The window's new shape will have already been
-stored in the window when this function is called.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->ChangeBorderWidth(pWin, width)
- WindowPtr pWin;
- unsigned int width;
-
-</programlisting></blockquote>
-The formerly dix function ChangeBorderWidth has moved to ddx and is accessed via
-this screen function. The new border width is given by width.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->MarkUnrealizedWindow(pChild, pWin, fromConfigure)
- WindowPtr pChild;
- WindowPtr pWin;
- Bool fromConfigure;
-
-</programlisting></blockquote>
-This function is called for windows that are being unrealized as part of
-an UnrealizeTree. pChild is the window being unrealized, pWin is an
-ancestor, and the fromConfigure value is simply propagated from UnrealizeTree.</para>
-</section>
-</section>
-</section>
-<section>
-<title>Graphics Contexts and Validation</title>
-<para>
-This graphics context (GC) contains state variables such as foreground and
-background pixel value (color), the current line style and width,
-the current tile or stipple for pattern generation, the current font for text
-generation, and other similar attributes.</para>
-<para>
-In many graphics systems, the equivalent of the graphics context and the
-drawable are combined as one entity.
-The main distinction between the two kinds of status is that a drawable
-describes a writing surface and the writings that may have already been done
-on it, whereas a graphics context describes the drawing process.
-A drawable is like a chalkboard.
-A GC is like a piece of chalk.</para>
-<para>
-Unlike many similar systems, there is no "current pen location."
-Every graphic operation is accompanied by the coordinates where it is to happen.</para>
-<para>
-The GC also includes two vectors of procedure pointers, the first
-operate on the GC itself and are called GC funcs. The second, called
-GC ops,
-contains the functions that carry out the fundamental graphic operations
-such as drawing lines, polygons, arcs, text, and copying bitmaps.
-The DDX graphic software can, if it
-wants to be smart, change these two vectors of procedure pointers
-to take advantage of hardware/firmware in the server machine, which can do
-a better job under certain circumstances. To reduce the amount of memory
-consumed by each GC, it is wise to create a few "boilerplate" GC ops vectors
-which can be shared by every GC which matches the constraints for that set.
-Also, it is usually reasonable to have every GC created by a particular
-module to share a common set of GC funcs. Samples of this sort of
-sharing can be seen in fb/fbgc.c.</para>
-<para>
-The DDX software is notified any time the client (or DIX) uses a changed GC.
-For instance, if the hardware has special support for drawing fixed-width
-fonts, DDX can intercept changes to the current font in a GC just before
-drawing is done. It can plug into either a fixed-width procedure that makes
-the hardware draw characters, or a variable-width procedure that carefully
-lays out glyphs by hand in software, depending upon the new font that is
-selected.</para>
-<para>
-A definition of these structures can be found in the file
-Xserver/include/gcstruct.h.</para>
-<para>
-Also included in each GC is support for dynamic devPrivates, which the
-DDX can use for any purpose (see <xref linkend="wrappers_and_privates"/> below).</para>
-<para>
-The DIX routines available for manipulating GCs are
-CreateGC, ChangeGC, ChangeGCXIDs, CopyGC, SetClipRects, SetDashes, and FreeGC.
-<blockquote><programlisting>
-
- GCPtr CreateGC(pDrawable, mask, pval, pStatus)
- DrawablePtr pDrawable;
- BITS32 mask;
- XID *pval;
- int *pStatus;
-
- int ChangeGC(client, pGC, mask, pUnion)
- ClientPtr client;
- GCPtr pGC;
- BITS32 mask;
- ChangeGCValPtr pUnion;
-
- int ChangeGCXIDs(client, pGC, mask, pC32)
- ClientPtr client;
- GCPtr pGC;
- BITS32 mask;
- CARD32 *pC32;
-
- int CopyGC(pgcSrc, pgcDst, mask)
- GCPtr pgcSrc;
- GCPtr pgcDst;
- BITS32 mask;
-
- int SetClipRects(pGC, xOrigin, yOrigin, nrects, prects, ordering)
- GCPtr pGC;
- int xOrigin, yOrigin;
- int nrects;
- xRectangle *prects;
- int ordering;
-
- SetDashes(pGC, offset, ndash, pdash)
- GCPtr pGC;
- unsigned offset;
- unsigned ndash;
- unsigned char *pdash;
-
- int FreeGC(pGC, gid)
- GCPtr pGC;
- GContext gid;
-
-</programlisting></blockquote>
-</para>
-<para>
-As a convenience, each Screen structure contains an array of
-GCs that are preallocated, one at each depth the screen supports.
-These are particularly useful in the mi code. Two DIX routines
-must be used to get these GCs:
-<blockquote><programlisting>
-
- GCPtr GetScratchGC(depth, pScreen)
- int depth;
- ScreenPtr pScreen;
-
- FreeScratchGC(pGC)
- GCPtr pGC;
-
-</programlisting></blockquote>
-Always use these two routines, don't try to extract the scratch
-GC yourself -- someone else might be using it, so a new one must
-be created on the fly.</para>
-<para>
-If you need a GC for a very long time, say until the server is restarted,
-you should not take one from the pool used by GetScratchGC, but should
-get your own using CreateGC or CreateScratchGC.
-This leaves the ones in the pool free for routines that only need it for
-a little while and don't want to pay a heavy cost to get it.
-<blockquote><programlisting>
-
- GCPtr CreateScratchGC(pScreen, depth)
- ScreenPtr pScreen;
- int depth;
-
-</programlisting></blockquote>
-NULL is returned if the GC cannot be created.
-The GC returned can be freed with FreeScratchGC.</para>
-<section>
- <title>Details of Operation</title>
-<para>
-At screen initialization, a screen must supply a GC creation procedure.
-At GC creation, the screen must fill in GC funcs and GC ops vectors
-(Xserver/include/gcstruct.h). For any particular GC, the func vector
-must remain constant, while the op vector may vary. This invariant is to
-ensure that Wrappers work correctly.</para>
-<para>
-When a client request is processed that results in a change
-to the GC, the device-independent state of the GC is updated.
-This includes a record of the state that changed.
-Then the ChangeGC GC func is called.
-This is useful for graphics subsystems that are able to process
-state changes in parallel with the server CPU.
-DDX may opt not to take any action at GC-modify time.
-This is more efficient if multiple GC-modify requests occur
-between draws using a given GC.</para>
-<para>
-Validation occurs at the first draw operation that specifies the GC after
-that GC was modified. DIX calls then the ValidateGC GC func. DDX should
-then update its internal state. DDX internal state may be stored as one or
-more of the following: 1) device private block on the GC; 2) hardware
-state; 3) changes to the GC ops.</para>
-<para>
-The GC contains a serial number, which is loaded with a number fetched from
-the window that was drawn into the last time the GC was used. The serial
-number in the drawable is changed when the drawable's
-clipList or absCorner changes. Thus, by
-comparing the GC serial number with the drawable serial number, DIX can
-force a validate if the drawable has been changed since the last time it
-was used with this GC.</para>
-<para>
-In addition, the drawable serial number is always guaranteed to have the
-most significant bit set to 0. Thus, the DDX layer can set the most
-significant bit of the serial number to 1 in a GC to force a validate the next time
-the GC is used. DIX also uses this technique to indicate that a change has
-been made to the GC by way of a SetGC, a SetDashes or a SetClip request.</para>
-</section>
-<section>
- <title>GC Handling Routines</title>
-<para>
-The ScreenRec data structure has a pointer for
-CreateGC().
-<blockquote><programlisting>
-
- Bool pScreen->CreateGC(pGC)
- GCPtr pGC;
-</programlisting></blockquote>
-This routine must fill in the fields of
-a dynamically allocated GC that is passed in.
-It does NOT allocate the GC record itself or fill
-in the defaults; DIX does that.</para>
-<para>
-This must fill in both the GC funcs and ops; none of the drawing
-functions will be called before the GC has been validated,
-but the others (dealing with allocating of clip regions,
-changing and destroying the GC, etc.) might be.</para>
-<para>
-The GC funcs vector contains pointers to 7
-routines and a devPrivate field:
-<blockquote><programlisting>
-
- pGC->funcs->ChangeGC(pGC, changes)
- GCPtr pGC;
- unsigned long changes;
-
-</programlisting></blockquote>
-This GC func is called immediately after a field in the GC is changed.
-changes is a bit mask indicating the changed fields of the GC in this
-request.</para>
-<para>
-The ChangeGC routine is useful if you have a system where
-state-changes to the GC can be swallowed immediately by your graphics
-system, and a validate is not necessary.</para>
-<para>
-<blockquote><programlisting>
-
- pGC->funcs->ValidateGC(pGC, changes, pDraw)
- GCPtr pGC;
- unsigned long changes;
- DrawablePtr pDraw;
-
-</programlisting></blockquote>
-ValidateGC is called by DIX just before the GC will be used when one
-of many possible changes to the GC or the graphics system has
-happened. It can modify devPrivates data attached to the GC,
-change the op vector, or change hardware according to the
-values in the GC. It may not change the device-independent portion of
-the GC itself.</para>
-<para>
-In almost all cases, your ValidateGC() procedure should take the
-regions that drawing needs to be clipped to and combine them into a
-composite clip region, which you keep a pointer to in the private part
-of the GC. In this way, your drawing primitive routines (and whatever
-is below them) can easily determine what to clip and where. You
-should combine the regions clientClip (the region that the client
-desires to clip output to) and the region returned by
-NotClippedByChildren(), in DIX. An example is in Xserver/fb/fbgc.c.</para>
-<para>
-Some kinds of extension software may cause this routine to be called
-more than originally intended; you should not rely on algorithms that
-will break under such circumstances.</para>
-<para>
-See the Strategies document for more information on creatively using
-this routine.</para>
-<para>
-<blockquote><programlisting>
-
- pGC->funcs->CopyGC(pGCSrc, mask, pGCDst)
- GCPtr pGCSrc;
- unsigned long mask;
- GCPtr pGCDst;
-
-</programlisting></blockquote>
-This routine is called by DIX when a GC is being copied to another GC.
-This is for situations where dynamically allocated chunks of memory
-are stored in the GC's dynamic devPrivates and need to be transferred to
-the destination GC.</para>
-<para>
-<blockquote><programlisting>
-
- pGC->funcs->DestroyGC(pGC)
- GCPtr pGC;
-
-</programlisting></blockquote>
-This routine is called before the GC is destroyed for the
-entity interested in this GC to clean up after itself.
-This routine is responsible for freeing any auxiliary storage allocated.</para>
-</section>
-<section>
- <title>GC Clip Region Routines</title>
-<para>
-The GC clientClip field requires three procedures to manage it. These
-procedures are in the GC funcs vector. The underlying principle is that dix
-knows nothing about the internals of the clipping information, (except when
-it has come from the client), and so calls ddX whenever it needs to copy,
-set, or destroy such information. It could have been possible for dix not
-to allow ddX to touch the field in the GC, and require it to keep its own
-copy in devPriv, but since clip masks can be very large, this seems like a
-bad idea. Thus, the server allows ddX to do whatever it wants to the
-clientClip field of the GC, but requires it to do all manipulation itself.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->funcs->ChangeClip(pGC, type, pValue, nrects)
- GCPtr pGC;
- int type;
- char *pValue;
- int nrects;
-
-</programlisting></blockquote>
-This routine is called whenever the client changes the client clip
-region. The pGC points to the GC involved, the type tells what form
-the region has been sent in. If type is CT_NONE, then there is no
-client clip. If type is CT_UNSORTED, CT_YBANDED or CT_YXBANDED, then
-pValue pointer to a list of rectangles, nrects long. If type is
-CT_REGION, then pValue pointer to a RegionRec from the mi region code.
-If type is CT_PIXMAP pValue is a pointer to a pixmap. (The defines
-for CT_NONE, etc. are in Xserver/include/gc.h.) This routine is
-responsible for incrementing any necessary reference counts (e.g. for
-a pixmap clip mask) for the new clipmask and freeing anything that
-used to be in the GC's clipMask field. The lists of rectangles passed
-in can be freed with Xfree(), the regions can be destroyed with the
-RegionDestroy field in the screen, and pixmaps can be destroyed by
-calling the screen's DestroyPixmap function. DIX and MI code expect
-what they pass in to this to be freed or otherwise inaccessible, and
-will never look inside what's been put in the GC. This is a good
-place to be wary of storage leaks.</para>
-<para>
-In the sample server, this routine transforms either the bitmap or the
-rectangle list into a region, so that future routines will have a more
-predictable starting point to work from. (The validate routine must
-take this client clip region and merge it with other regions to arrive
-at a composite clip region before any drawing is done.)</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->funcs->DestroyClip(pGC)
- GCPtr pGC;
-
-</programlisting></blockquote>
-This routine is called whenever the client clip region must be destroyed.
-The pGC points to the GC involved. This call should set the clipType
-field of the GC to CT_NONE.
-In the sample server, the pointer to the client clip region is set to NULL
-by this routine after destroying the region, so that other software
-(including ChangeClip() above) will recognize that there is no client clip region.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->funcs->CopyClip(pgcDst, pgcSrc)
- GCPtr pgcDst, pgcSrc;
-
-</programlisting></blockquote>
-This routine makes a copy of the clipMask and clipType from pgcSrc
-into pgcDst. It is responsible for destroying any previous clipMask
-in pgcDst. The clip mask in the source can be the same as the
-clip mask in the dst (clients do the strangest things), so care must
-be taken when destroying things. This call is required because dix
-does not know how to copy the clip mask from pgcSrc.</para>
-</section>
-</section>
-<section>
- <title>Drawing Primitives</title>
-<para>
-The X protocol (rules for the byte stream that goes between client and server)
-does all graphics using primitive
-operations, which are called Drawing Primitives.
-These include line drawing, area filling, arcs, and text drawing.
-Your implementation must supply 16 routines
-to perform these on your hardware.
-(The number 16 is arbitrary.)</para>
-<para>
-More specifically, 16 procedure pointers are in each
-GC op vector.
-At any given time, ALL of them MUST point to a valid procedure that
-attempts to do the operation assigned, although
-the procedure pointers may change and may
-point to different procedures to carry out the same operation.
-A simple server will leave them all pointing to the same 16 routines, while
-a more optimized implementation will switch each from one
-procedure to another, depending upon what is most optimal
-for the current GC and drawable.</para>
-<para>
-The sample server contains a considerable chunk of code called the
-mi (machine independent)
-routines, which serve as drawing primitive routines.
-Many server implementations will be able to use these as-is,
-because they work for arbitrary depths.
-They make no assumptions about the formats of pixmaps
-and frame buffers, since they call a set of routines
-known as the "Pixblit Routines" (see next section).
-They do assume that the way to draw is
-through these low-level routines that apply pixel values rows at a time.
-If your hardware or firmware gives more performance when
-things are done differently, you will want to take this fact into account
-and rewrite some or all of the drawing primitives to fit your needs.</para>
-<section>
- <title>GC Components</title>
-<para>
-This section describes the fields in the GC that affect each drawing primitive.
-The only primitive that is not affected is GetImage, which does not use a GC
-because its destination is a protocol-style bit image.
-Since each drawing primitive mirrors exactly the X protocol request of the
-same name, you should refer to the X protocol specification document
-for more details.</para>
-<para>
-ALL of these routines MUST CLIP to the
-appropriate regions in the drawable.
-Since there are many regions to clip to simultaneously,
-your ValidateGC routine should combine these into a unified
-clip region to which your drawing routines can quickly refer.
-This is exactly what the fb routines supplied with the sample server
-do.
-The mi implementation passes responsibility for clipping while drawing
-down to the Pixblit routines.</para>
-<para>
-Also, all of them must adhere to the current plane mask.
-The plane mask has one bit for every bit plane in the drawable;
-only planes with 1 bits in the mask are affected by any drawing operation.</para>
-<para>
-All functions except for ImageText calls must obey the alu function.
-This is usually Copy, but could be any of the allowable 16 raster-ops.</para>
-<para>
-All of the functions, except for CopyArea, might use the current
-foreground and background pixel values.
-Each pixel value is 32 bits.
-These correspond to foreground and background colors, but you have
-to run them through the colormap to find out what color the pixel values
-represent. Do not worry about the color, just apply the pixel value.</para>
-<para>
-The routines that draw lines (PolyLine, PolySegment, PolyRect, and PolyArc)
-use the line width, line style, cap style, and join style.
-Line width is in pixels.
-The line style specifies whether it is solid or dashed, and what kind of dash.
-The cap style specifies whether Rounded, Butt, etc.
-The join style specifies whether joins between joined lines are Miter, Round or Beveled.
-When lines cross as part of the same polyline, they are assumed to be drawn once.
-(See the X protocol specification for more details.)</para>
-<para>
-Zero-width lines are NOT meant to be really zero width; this is the client's way
-of telling you that you can optimize line drawing with little regard to
-the end caps and joins.
-They are called "thin" lines and are meant to be one pixel wide.
-These are frequently done in hardware or in a streamlined assembly language
-routine.</para>
-<para>
-Lines with widths greater than zero, though, must all be drawn with the same
-algorithm, because client software assumes that every jag on every
-line at an angle will come at the same place.
-Two lines that should have
-one pixel in the space between them
-(because of their distance apart and their widths) should have such a one-pixel line
-of space between them if drawn, regardless of angle.</para>
-<para>
-The solid area fill routines (FillPolygon, PolyFillRect, PolyFillArc)
-all use the fill rule, which specifies subtle interpretations of
-what points are inside and what are outside of a given polygon.
-The PolyFillArc routine also uses the arc mode, which specifies
-whether to fill pie segments or single-edge slices of an ellipse.</para>
-<para>
-The line drawing, area fill, and PolyText routines must all
-apply the correct "fill style."
-This can be either a solid foreground color, a transparent stipple,
-an opaque stipple, or a tile.
-Stipples are bitmaps where the 1 bits represent that the foreground color is written,
-and 0 bits represent that either the pixel is left alone (transparent) or that
-the background color is written (opaque).
-A tile is a pixmap of the full depth of the GC that is applied in its full glory to all areas.
-The stipple and tile patterns can be any rectangular size, although some implementations
-will be faster for certain sizes such as 8x8 or 32x32.
-The mi implementation passes this responsibility down to the Pixblit routines.</para>
-<para>
-See the X protocol document for full details.
-The description of the CreateGC request has a very good, detailed description of these
-attributes.</para>
-</section>
-<section>
-<title>The Primitives</title>
-<para>
-The Drawing Primitives are as follows:
-
-<blockquote><programlisting>
-
- RegionPtr pGC->ops->CopyArea(src, dst, pGC, srcx, srcy, w, h, dstx, dsty)
- DrawablePtr dst, src;
- GCPtr pGC;
- int srcx, srcy, w, h, dstx, dsty;
-
-</programlisting></blockquote>
-CopyArea copies a rectangle of pixels from one drawable to another of
-the same depth. To effect scrolling, this must be able to copy from
-any drawable to itself, overlapped. No squeezing or stretching is done
-because the source and destination are the same size. However,
-everything is still clipped to the clip regions of the destination
-drawable.</para>
-<para>
-If pGC->graphicsExposures is True, any portions of the destination which
-were not valid in the source (either occluded by covering windows, or
-outside the bounds of the drawable) should be collected together and
-returned as a region (if this resultant region is empty, NULL can be
-returned instead). Furthermore, the invalid bits of the source are
-not copied to the destination and (when the destination is a window)
-are filled with the background tile. The sample routine
-miHandleExposures generates the appropriate return value and fills the
-invalid area using pScreen->PaintWindowBackground.</para>
-<para>
-For instance, imagine a window that is partially obscured by other
-windows in front of it. As text is scrolled on your window, the pixels
-that are scrolled out from under obscuring windows will not be
-available on the screen to copy to the right places, and so an exposure
-event must be sent for the client to correctly repaint them. Of
-course, if you implement backing store, you could do this without resorting
-to exposure events.</para>
-<para>
-An example implementation is fbCopyArea() in Xserver/fb/fbcopy.c.</para>
-<para>
-<blockquote><programlisting>
-
- RegionPtr pGC->ops->CopyPlane(src, dst, pGC, srcx, srcy, w, h, dstx, dsty, plane)
- DrawablePtr dst, src;
- GCPtr pGC;
- int srcx, srcy, w, h, dstx, dsty;
- unsigned long plane;
-
-</programlisting></blockquote>
-CopyPlane must copy one plane of a rectangle from the source drawable
-onto the destination drawable. Because this routine only copies one
-bit out of each pixel, it can copy between drawables of different
-depths. This is the only way of copying between drawables of
-different depths, except for copying bitmaps to pixmaps and applying
-foreground and background colors to it. All other conditions of
-CopyArea apply to CopyPlane too.</para>
-<para>
-An example implementation is fbCopyPlane() in
-Xserver/fb/fbcopy.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyPoint(dst, pGC, mode, n, pPoint)
- DrawablePtr dst;
- GCPtr pGC;
- int mode;
- int n;
- DDXPointPtr pPoint;
-
-</programlisting></blockquote>
-PolyPoint draws a set of one-pixel dots (foreground color)
-at the locations given in the array.
-mode is one of the defined constants Origin (absolute coordinates) or Previous
-(each coordinate is relative to the last).
-Note that this does not use the background color or any tiles or stipples.</para>
-<para>
-Example implementations are fbPolyPoint() in Xserver/fb/fbpoint.c and
-miPolyPoint in Xserver/mi/mipolypnt.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->Polylines(dst, pGC, mode, n, pPoint)
- DrawablePtr dst;
- GCPtr pGC;
- int mode;
- int n;
- DDXPointPtr pPoint;
-
-</programlisting></blockquote>
-Similar to PolyPoint, Polylines draws lines between the locations given in the array.
-Zero-width lines are NOT meant to be really zero width; this is the client's way of
-telling you that you can maximally optimize line drawing with little regard to
-the end caps and joins.
-mode is one of the defined constants Previous or Origin, depending upon
-whether the points are each relative to the last or are absolute.</para>
-<para>
-Example implementations are miWideLine() and miWideDash() in
-mi/miwideline.c and miZeroLine() in mi/mizerline.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolySegment(dst, pGC, n, pPoint)
- DrawablePtr dst;
- GCPtr pGC;
- int n;
- xSegment *pSegments;
-
-</programlisting></blockquote>
-PolySegments draws unconnected
-lines between pairs of points in the array; the array must be of
-even size; no interconnecting lines are drawn.</para>
-<para>
-An example implementation is miPolySegment() in mipolyseg.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyRectangle(dst, pGC, n, pRect)
- DrawablePtr dst;
- GCPtr pGC;
- int n;
- xRectangle *pRect;
-
-</programlisting></blockquote>
-PolyRectangle draws outlines of rectangles for each rectangle in the array.</para>
-<para>
-An example implementation is miPolyRectangle() in Xserver/mi/mipolyrect.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyArc(dst, pGC, n, pArc)
- DrawablePtr dst;
- GCPtr pGC;
- int n;
- xArc*pArc;
-
-</programlisting></blockquote>
-PolyArc draws connected conic arcs according to the descriptions in the array.
-See the protocol specification for more details.</para>
-<para>
-Example implementations are miZeroPolyArc in Xserver/mi/mizerarc. and
-miPolyArc() in Xserver/mi/miarc.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->FillPolygon(dst, pGC, shape, mode, count, pPoint)
- DrawablePtr dst;
- GCPtr pGC;
- int shape;
- int mode;
- int count;
- DDXPointPtr pPoint;
-
-</programlisting></blockquote>
-FillPolygon fills a polygon specified by the points in the array
-with the appropriate fill style.
-If necessary, an extra border line is assumed between the starting and ending lines.
-The shape can be used as a hint
-to optimize filling; it indicates whether it is convex (all interior angles
-less than 180), nonconvex (some interior angles greater than 180 but
-border does not cross itself), or complex (border crosses itself).
-You can choose appropriate algorithms or hardware based upon mode.
-mode is one of the defined constants Previous or Origin, depending upon
-whether the points are each relative to the last or are absolute.</para>
-<para>
-An example implementation is miFillPolygon() in Xserver/mi/mipoly.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyFillRect(dst, pGC, n, pRect)
- DrawablePtr dst;
- GCPtr pGC;
- int n;
- xRectangle *pRect;
-
-</programlisting></blockquote>
-PolyFillRect fills multiple rectangles.</para>
-<para>
-Example implementations are fbPolyFillRect() in Xserver/fb/fbfillrect.c and
-miPolyFillRect() in Xserver/mi/mifillrct.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyFillArc(dst, pGC, n, pArc)
- DrawablePtr dst;
- GCPtr pGC;
- int n;
- xArc *pArc;
-
-</programlisting></blockquote>
-PolyFillArc fills a shape for each arc in the
-list that is bounded by the arc and one or two
-line segments with the current fill style.</para>
-<para>
-An example implementation is miPolyFillArc() in Xserver/mi/mifillarc.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PutImage(dst, pGC, depth, x, y, w, h, leftPad, format, pBinImage)
- DrawablePtr dst;
- GCPtr pGC;
- int x, y, w, h;
- int format;
- char *pBinImage;
-
-</programlisting></blockquote>
-PutImage copies a pixmap image into the drawable. The pixmap image
-must be in X protocol format (either Bitmap, XYPixmap, or ZPixmap),
-and format tells the format. (See the X protocol specification for
-details on these formats). You must be able to accept all three
-formats, because the client gets to decide which format to send.
-Either the drawable and the pixmap image have the same depth, or the
-source pixmap image must be a Bitmap. If a Bitmap, the foreground and
-background colors will be applied to the destination.</para>
-<para>
-An example implementation is fbPutImage() in Xserver/fb/fbimage.c.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->GetImage(src, x, y, w, h, format, planeMask, pBinImage)
- DrawablePtr src;
- int x, y, w, h;
- unsigned int format;
- unsigned long planeMask;
- char *pBinImage;
-
-</programlisting></blockquote>
-GetImage copies the bits from the source drawable into
-the destination pointer. The bits are written into the buffer
-according to the server-defined pixmap padding rules.
-pBinImage is guaranteed to be big enough to hold all
-the bits that must be written.</para>
-<para>
-This routine does not correspond exactly to the X protocol GetImage
-request, since DIX has to break the reply up into buffers of a size
-requested by the transport layer. If format is ZPixmap, the bits are
-written in the ZFormat for the depth of the drawable; if there is a 0
-bit in the planeMask for a particular plane, all pixels must have the
-bit in that plane equal to 0. If format is XYPixmap, planemask is
-guaranteed to have a single bit set; the bits should be written in
-Bitmap format, which is the format for a single plane of an XYPixmap.</para>
-<para>
-An example implementation is miGetImage() in Xserver/mi/mibitblt.c.
-<blockquote><programlisting>
-
- void pGC->ops->ImageText8(pDraw, pGC, x, y, count, chars)
- DrawablePtr pDraw;
- GCPtr pGC;
- int x, y;
- int count;
- char *chars;
-
-</programlisting></blockquote>
-ImageText8 draws text. The text is drawn in the foreground color; the
-background color fills the remainder of the character rectangles. The
-coordinates specify the baseline and start of the text.</para>
-<para>
-An example implementation is miImageText8() in Xserver/mi/mipolytext.c.</para>
-<para>
-<blockquote><programlisting>
-
- int pGC->ops->PolyText8(pDraw, pGC, x, y, count, chars)
- DrawablePtr pDraw;
- GCPtr pGC;
- int x, y;
- int count;
- char *chars;
-
-</programlisting></blockquote>
-PolyText8 works like ImageText8, except it draws with
-the current fill style for special effects such as
-shaded text.
-See the X protocol specification for more details.</para>
-<para>
-An example implementation is miPolyText8() in Xserver/mi/mipolytext.c.</para>
-<para>
-<blockquote><programlisting>
-
- int pGC->ops->PolyText16(pDraw, pGC, x, y, count, chars)
- DrawablePtr pDraw;
- GCPtr pGC;
- int x, y;
- int count;
- unsigned short *chars;
-
- void pGC->ops->ImageText16(pDraw, pGC, x, y, count, chars)
- DrawablePtr pDraw;
- GCPtr pGC;
- int x, y;
- int count;
- unsigned short *chars;
-
-</programlisting></blockquote>
-These two routines are the same as the "8" versions,
-except that they are for 16-bit character codes (useful
-for oriental writing systems).</para>
-<para>
-The primary difference is in the way the character information is
-looked up. The 8-bit and the 16-bit versions obviously have different
-kinds of character values to look up; the main goal of the lookup is
-to provide a pointer to the CharInfo structs for the characters to
-draw and to pass these pointers to the Glyph routines. Given a
-CharInfo struct, lower-level software can draw the glyph desired with
-little concern for other characteristics of the font.</para>
-<para>
-16-bit character fonts have a row-and-column scheme, where the 2bytes
-of the character code constitute the row and column in a square matrix
-of CharInfo structs. Each font has row and column minimum and maximum
-values; the CharInfo structures form a two-dimensional matrix.</para>
-<para>
-Example implementations are miPolyText16() and
-miImageText16() in Xserver/mi/mipolytext.c.</para>
-<para>
-See the X protocol specification for more details on these graphic operations.</para>
-<para>
-There is a hook in the GC ops, called LineHelper, that used to be used in the
-sample implementation by the code for wide lines. It no longer servers any
-purpose in the sample servers, but still exists, #ifdef'ed by NEED_LINEHELPER,
-in case someone needs it.</para>
-</section>
-</section>
-<section>
- <title>Pixblit Procedures</title>
-<para>
-The Drawing Primitive functions must be defined for your server.
-One possible way to do this is to use the mi routines from the sample server.
-If you choose to use the mi routines (even part of them!) you must implement
-these Pixblit routines.
-These routines read and write pixel values
-and deal directly with the image data.</para>
-<para>
-The Pixblit routines for the sample server are part of the "fb"
-routines. As with the mi routines, the fb routines are
-portable but are not as portable as the mi routines.</para>
-<para>
-The fb subsystem is a depth-independent framebuffer core, capable of
-operating at any depth from 1 to 32, based on the depth of the window
-or pixmap it is currently operating on. In particular, this means it
-can support pixmaps of multiple depths on the same screen. It supplies
-both Pixblit routines and higher-level optimized implementations of the
-Drawing Primitive routines. It does make the assumption that the pixel
-data it touches is available in the server's address space.</para>
-<para>
-In other words, if you have a "normal" frame buffer type display, you
-can probably use the fb code, and the mi code. If you
-have a stranger hardware, you will have to supply your own Pixblit
-routines, but you can use the mi routines on top of them. If you have
-better ways of doing some of the Drawing Primitive functions, then you
-may want to supply some of your own Drawing Primitive routines. (Even
-people who write their own Drawing Primitives save at least some of
-the mi code for certain special cases that their hardware or library
-or fancy algorithm does not handle.)</para>
-<para>
-The client, DIX, and the machine-independent routines do not carry the
-final responsibility of clipping. They all depend upon the Pixblit
-routines to do their clipping for them. The rule is, if you touch the
-frame buffer, you clip.</para>
-<para>
-(The higher level routines may decide to clip at a high level, but
-this is only for increased performance and cannot substitute for
-bottom-level clipping. For instance, the mi routines, DIX, or the
-client may decide to check all character strings to be drawn and chop
-off all characters that would not be displayed. If so, it must retain
-the character on the edge that is partly displayed so that the Pixblit
-routines can clip off precisely at the right place.)</para>
-<para>
-To make this easier, all of the reasons to clip can be combined into
-one region in your ValidateGC procedure. You take this composite clip
-region with you into the Pixblit routines. (The sample server does
-this.)</para>
-<para>
-Also, FillSpans() has to apply tile and stipple patterns. The
-patterns are all aligned to the window origin so that when two people
-write patches that are contiguous, they will merge nicely. (Really,
-they are aligned to the patOrg point in the GC. This defaults to (0,
-0) but can be set by the client to anything.)</para>
-<para>
-However, the mi routines can translate (relocate) the points from
-window-relative to screen-relative if desired. If you set the
-miTranslate field in the GC (set it in the CreateGC or ValidateGC
-routine), then the mi output routines will translate all coordinates.
-If it is false, then the coordinates will be passed window-relative.
-Screens with no hardware translation will probably set miTranslate to
-TRUE, so that geometry (e.g. polygons, rectangles) can be translated,
-rather than having the resulting list of scanlines translated; this is
-good because the list vertices in a drawing request will generally be
-much smaller than the list of scanlines it produces. Similarly,
-hardware that does translation can set miTranslate to FALSE, and avoid
-the extra addition per vertex, which can be (but is not always)
-important for getting the highest possible performance. (Contrast the
-behavior of GetSpans, which is not expected to be called as often, and
-so has different constraints.) The miTranslate field is settable in
-each GC, if , for example, you are mixing several kinds of
-destinations (offscreen pixmaps, main memory pixmaps, backing store,
-and windows), all of which have different requirements, on one screen.</para>
-<para>
-As with other drawing routines, there are fields in the GC to direct
-higher code to the correct routine to execute for each function. In
-this way, you can optimize for special cases, for example, drawing
-solids versus drawing stipples.</para>
-<para>
-The Pixblit routines are broken up into three sets. The Span routines
-simply fill in rows of pixels. The Glyph routines fill in character
-glyphs. The PushPixels routine is a three-input bitblt for more
-sophisticated image creation.</para>
-<para>
-It turns out that the Glyph and PushPixels routines actually have a
-machine-independent implementation that depends upon the Span
-routines. If you are really pressed for time, you can use these
-versions, although they are quite slow.</para>
-<section>
-<title>Span Routines</title>
-<para>
-For these routines, all graphic operations have been reduced to "spans."
-A span is a horizontal row of pixels.
-If you can design these routines which write into and read from
-rows of pixels at a time, you can use the mi routines.</para>
-<para>
-Each routine takes
-a destination drawable to draw into, a GC to use while drawing,
-the number of spans to do, and two pointers to arrays that indicate the list
-of starting points and the list of widths of spans.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->FillSpans(dst, pGC, nSpans, pPoints, pWidths, sorted)
- DrawablePtr dst;
- GCPtr pGC;
- int nSpans;
- DDXPointPtr pPoints;
- int *pWidths;
- int sorted;
-
-</programlisting></blockquote>
-FillSpans should fill horizontal rows of pixels with
-the appropriate patterns, stipples, etc.,
-based on the values in the GC.
-The starting points are in the array at pPoints; the widths are in pWidths.
-If sorted is true, the scan lines are in increasing y order, in which case
-you may be able to make assumptions and optimizations.</para>
-<para>
-GC components: alu, clipOrg, clientClip, and fillStyle.</para>
-<para>
-GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
-(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
-and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->SetSpans(pDrawable, pGC, pSrc, ppt, pWidths, nSpans, sorted)
- DrawablePtr pDrawable;
- GCPtr pGC;
- char *pSrc;
- DDXPointPtr pPoints;
- int *pWidths;
- int nSpans;
- int sorted;
-
-</programlisting></blockquote>
-For each span, this routine should copy pWidths bits from pSrc to
-pDrawable at pPoints using the raster-op from the GC.
-If sorted is true, the scan lines are in increasing y order.
-The pixels in pSrc are
-padded according to the screen's padding rules.
-These
-can be used to support
-interesting extension libraries, for example, shaded primitives. It does not
-use the tile and stipple.</para>
-<para>
-GC components: alu, clipOrg, and clientClip</para>
-<para>
-The above functions are expected to handle all modifiers in the current
-GC. Therefore, it is expedient to have
-different routines to quickly handle common special cases
-and reload the procedure pointers
-at validate time, as with the other output functions.</para>
-<para>
-<blockquote><programlisting>
-
- void pScreen->GetSpans(pDrawable, wMax, pPoints, pWidths, nSpans)
- DrawablePtr pDrawable;
- int wMax;
- DDXPointPtr pPoints;
- int *pWidths;
- int nSpans;
- char *pDst;
-
-</programlisting></blockquote>
-For each span, GetSpans gets bits from the drawable starting at pPoints
-and continuing for pWidths bits.
-Each scanline returned will be server-scanline padded.
-The routine can return NULL if memory cannot be allocated to hold the
-result.</para>
-<para>
-GetSpans never translates -- for a window, the coordinates are already
-screen-relative. Consider the case of hardware that doesn't do
-translation: the mi code that calls ddX will translate each shape
-(rectangle, polygon,. etc.) before scan-converting it, which requires
-many fewer additions that having GetSpans translate each span does.
-Conversely, consider hardware that does translate: it can set its
-translation point to (0, 0) and get each span, and the only penalty is
-the small number of additions required to translate each shape being
-scan-converted by the calling code. Contrast the behavior of
-FillSpans and SetSpans (discussed above under miTranslate), which are
-expected to be used more often.</para>
-<para>
-Thus, the penalty to hardware that does hardware translation is
-negligible, and code that wants to call GetSpans() is greatly
-simplified, both for extensions and the machine-independent core
-implementation.</para>
-<section>
- <title>Glyph Routines</title>
-<para>
-The Glyph routines draw individual character glyphs for text drawing requests.</para>
-<para>
-You have a choice in implementing these routines. You can use the mi
-versions; they depend ultimately upon the span routines. Although
-text drawing will work, it will be very slow.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PolyGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
- DrawablePtr pDrawable;
- GCPtr pGC;
- int x , y;
- unsigned int nglyph;
- CharInfoRec **ppci; /* array of character info */
- pointer unused; /* unused since R5 */
-
-</programlisting></blockquote>
-GC components: alu, clipOrg, clientClip, font, and fillStyle.</para>
-<para>
-GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
-(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
-and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->ImageGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase)
- DrawablePtr pDrawable;
- GCPtr pGC;
- int x , y;
- unsigned int nglyph;
- CharInfoRec **ppci; /* array of character info */
- pointer unused; /* unused since R5 */
-
-</programlisting></blockquote>
-GC components: clipOrg, clientClip, font, fgPixel, bgPixel</para>
-<para>
-These routines must copy the glyphs defined by the bitmaps in
-pglyphBase and the font metrics in ppci to the DrawablePtr, pDrawable.
-The poly routine follows all fill, stipple, and tile rules. The image
-routine simply blasts the glyph onto the glyph's rectangle, in
-foreground and background colors.</para>
-<para>
-More precisely, the Image routine fills the character rectangle with
-the background color, and then the glyph is applied in the foreground
-color. The glyph can extend outside of the character rectangle.
-ImageGlyph() is used for terminal emulators and informal text purposes
-such as button labels.</para>
-<para>
-The exact specification for the Poly routine is that the glyph is
-painted with the current fill style. The character rectangle is
-irrelevant for this operation. PolyText, at a higher level, includes
-facilities for font changes within strings and such; it is to be used
-for WYSIWYG word processing and similar systems.</para>
-<para>
-Both of these routines must clip themselves to the overall clipping region.</para>
-<para>
-Example implementations in mi are miPolyGlyphBlt() and
-miImageGlyphBlt() in Xserver/mi/miglblt.c.</para>
-</section>
-<section>
-<title>PushPixels routine</title>
-<para>
-The PushPixels routine writes the current fill style onto the drawable
-in a certain shape defined by a bitmap. PushPixels is equivalent to
-using a second stipple. You can thing of it as pushing the fillStyle
-through a stencil. PushPixels is not used by any of the mi rendering code,
-but is used by the mi software cursor code.
-<blockquote><para>
- Suppose the stencil is: 00111100
- and the stipple is: 10101010
- PushPixels result: 00101000
-</para></blockquote>
-</para>
-<para>
-You have a choice in implementing this routine.
-You can use the mi version which depends ultimately upon FillSpans().
-Although it will work, it will be slow.</para>
-<para>
-<blockquote><programlisting>
-
- void pGC->ops->PushPixels(pGC, pBitMap, pDrawable, dx, dy, xOrg, yOrg)
- GCPtr pGC;
- PixmapPtr pBitMap;
- DrawablePtr pDrawable;
- int dx, dy, xOrg, yOrg;
-
-</programlisting></blockquote>
-GC components: alu, clipOrg, clientClip, and fillStyle.</para>
-<para>
-GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg
-(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple);
-and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para>
-<para>
-PushPixels applys the foreground color, tile, or stipple from the pGC
-through a stencil onto pDrawable. pBitMap points to a stencil (of
-which we use an area dx wide by dy high), which is oriented over the
-drawable at xOrg, yOrg. Where there is a 1 bit in the bitmap, the
-destination is set according to the current fill style. Where there
-is a 0 bit in the bitmap, the destination is left the way it is.</para>
-<para>
-This routine must clip to the overall clipping region.</para>
-<para>
-An Example implementation is miPushPixels() in Xserver/mi/mipushpxl.c.</para>
-</section>
-</section>
-</section>
-<section>
- <title>Shutdown Procedures</title>
-<para>
-<blockquote><programlisting>
- void AbortDDX()
- void ddxGiveUp()
-</programlisting></blockquote>
-Some hardware may require special work to be done before the server
-exits so that it is not left in an intermediate state. As explained
-in the OS layer, FatalError() will call AbortDDX() just before
-terminating the server. In addition, ddxGiveUp() will be called just
-before terminating the server on a "clean" death. What AbortDDX() and
-ddxGiveUP do is left unspecified, only that stubs must exist in the
-ddx layer. It is up to local implementors as to what they should
-accomplish before termination.</para>
-<section>
- <title>Command Line Procedures</title>
-<para>
-<blockquote><programlisting>
- int ddxProcessArgument(argc, argv, i)
- int argc;
- char *argv[];
- int i;
-
- void
- ddxUseMsg()
-
-</programlisting></blockquote>
-You should write these routines to deal with device-dependent command line
-arguments. The routine ddxProcessArgument() is called with the command line,
-and the current index into argv; you should return zero if the argument
-is not a device-dependent one, and otherwise return a count of the number
-of elements of argv that are part of this one argument. For a typical
-option (e.g., "-realtime"), you should return the value one. This
-routine gets called before checks are made against device-independent
-arguments, so it is possible to peek at all arguments or to override
-device-independent argument processing. You can document the
-device-dependent arguments in ddxUseMsg(), which will be
-called from UseMsg() after printing out the device-independent arguments.</para>
-</section>
-</section>
-<section id="wrappers_and_privates">
- <title>Wrappers and Privates</title>
-<para>
-Two new extensibility concepts have been developed for release 4, Wrappers
-and devPrivates. These replace the R3 GCInterest queues, which were not a
-general enough mechanism for many extensions and only provided hooks into a
-single data structure. devPrivates have been revised substantially for
-X.Org X server release 1.5, and updated again for the 1.9 release.</para>
-<section>
- <title>devPrivates</title>
-<para>
-devPrivates provides a way to attach arbitrary private data to various server structures.
-Any structure which contains a <structfield>devPrivates</structfield> field of
-type <type>PrivateRec</type> supports this mechanism. Some structures allow
-allocating space for private data after some objects have been created, others
-require all space allocations be registered before any objects of that type
-are created. <filename class="headerfile">Xserver/include/privates.h</filename>
-lists which of these cases applies to each structure containing
-<structfield>devPrivates</structfield>.</para>
-
-<para>
-To request private space, use
-<blockquote><programlisting>
- Bool dixRegisterPrivateKey(DevPrivateKey key, DevPrivateType type, unsigned size);
-</programlisting></blockquote>
-The first argument is a pointer to a <type>DevPrivateKeyRec</type> which
-will serve as the unique identifier for the private data. Typically this is
-the address of a static <type>DevPrivateKeyRec</type> in your code.
-The second argument is the class of objects for which this key will apply.
-The third argument is the size of the space being requested, or
-<constant>0</constant> to only allocate a pointer that the caller will manage.
-If space is requested, this space will be automatically freed when the object
-is destroyed. Note that a call to <function>dixSetPrivate</function>
-that changes the pointer value may cause the space to be unreachable by the caller, however it will still be automatically freed.
-The function returns <literal>TRUE</literal> unless memory allocation fails.
-If the function is called more than once on the same key, all calls must use
-the same value for <type>size</type> or the server will abort.</para>
-
-<para>
-To request per-screen private space in an object, use
-<blockquote><programlisting>
- Bool dixRegisterScreenPrivateKey(DevScreenPrivateKey key, ScreenPtr pScreen, DevPrivateType type, unsigned size);
-</programlisting></blockquote>
-The <parameter>type</parameter> and <parameter>size</parameter> arguments are
-the same as those to <function>dixRegisterPrivateKey</function> but this
-function ensures the given <parameter>key</parameter> exists on objects of
-the specified type with distinct storage for the given
-<parameter>pScreen</parameter>. The key is usable on ScreenPrivate variants
-that are otherwise equivalent to the following Private functions.</para>
-
-<para>
-To attach a piece of private data to an object, use:
-<blockquote><programlisting>
- void dixSetPrivate(PrivateRec **privates, const DevPrivateKey key, pointer val)
-</programlisting></blockquote>
-The first argument is the address of the <structfield>devPrivates</structfield>
-field in the target structure. This field is managed privately by the DIX
-layer and should not be directly modified. The second argument is a pointer
-to the <type>DevPrivateKeyRec</type> which you registered with
-<function>dixRegisterPrivateKey</function> or allocated with
-<function>dixCreatePrivateKey</function>. Only one
-piece of data with a given key can be attached to an object, and in most cases
-each key is specific to the type of object it was registered for. (An
-exception is the PRIVATE_XSELINUX class which applies to multiple object types.)
-The third argument is the value to store.</para>
-<para>
-If private data with the given key is already associated with the object,
-<function>dixSetPrivate</function> will overwrite the old value with the
-new one.</para>
-
-<para>
-To look up a piece of private data, use one of:
-<blockquote><programlisting>
- pointer dixLookupPrivate(PrivateRec **privates, const DevPrivateKey key)
- pointer *dixLookupPrivateAddr(PrivateRec **privates, const DevPrivateKey key)
-</programlisting></blockquote>
-The first argument is the address of the <structfield>devPrivates</structfield> field
-in the target structure. The second argument is the key to look up.
-If a non-zero size was given when the key was registered, or if private data
-with the given key is already associated with the object, then
-<function>dixLookupPrivate</function> will return the pointer value
-while <function>dixLookupPrivateAddr</function>
-will return the address of the pointer.</para>
-
-<para>
-When implementing new server resource objects that support devPrivates, there
-are four steps to perform:
-Add a type value to the <type>DevPrivateType</type> enum in
-<filename class="headerfile">Xserver/include/privates.h</filename>,
-declare a field of type <type>PrivateRec *</type> in your structure;
-initialize this field to <literal>NULL</literal> when creating any objects; and
-when freeing any objects call the <function>dixFreePrivates</function> or
-<function>dixFreeObjectWithPrivates</function> function.</para>
-</section>
-<section>
- <title>Wrappers</title>
-<para>
-Wrappers are not a body of code, nor an interface spec. They are, instead,
-a technique for hooking a new module into an existing calling sequence.
-There are limitations on other portions of the server implementation which
-make using wrappers possible; limits on when specific fields of data
-structures may be modified. They are intended as a replacement for
-GCInterest queues, which were not general enough to support existing
-modules; in particular software cursors needed more
-control over the activity. The general mechanism for using wrappers is:
-<blockquote><programlisting>
-privateWrapperFunction (object, ...)
- ObjectPtr object;
-{
- pre-wrapped-function-stuff ...
-
- object->functionVector = dixLookupPrivate(&object->devPrivates, privateKey);
- (*object->functionVector) (object, ...);
- /*
- * this next line is occasionally required by the rules governing
- * wrapper functions. Always using it will not cause problems.
- * Not using it when necessary can cause severe troubles.
- */
- dixSetPrivate(&object->devPrivates, privateKey, object->functionVector);
- object->functionVector = privateWrapperFunction;
-
- post-wrapped-function-stuff ...
-}
-
-privateInitialize (object)
- ObjectPtr object;
-{
- dixSetPrivate(&object->devPrivates, privateKey, object->functionVector);
- object->functionVector = privateWrapperFunction;
-}
-</programlisting></blockquote>
-</para>
-<para>
-Thus the privateWrapperFunction provides hooks for performing work both
-before and after the wrapped function has been called; the process of
-resetting the functionVector is called "unwrapping" while the process of
-fetching the wrapped function and replacing it with the wrapping function
-is called "wrapping". It should be clear that GCInterest queues could
-be emulated using wrappers. In general, any function vectors contained in
-objects can be wrapped, but only vectors in GCs and Screens have been tested.</para>
-<para>
-Wrapping screen functions is quite easy; each vector is individually
-wrapped. Screen functions are not supposed to change after initialization,
-so rewrapping is technically not necessary, but causes no problems.</para>
-<para>
-Wrapping GC functions is a bit more complicated. GC's have two tables of
-function vectors, one hanging from gc->ops and the other from gc->funcs, which
-should be initially wrapped from a CreateGC wrapper. Wrappers should modify
-only table pointers, not the contents of the tables, as they
-may be shared by more than one GC (and, in the case of funcs, are probably
-shared by all gcs). Your func wrappers may change the GC funcs or ops
-pointers, and op wrappers may change the GC op pointers but not the funcs.</para>
-<para>
-Thus, the rule for GC wrappings is: wrap the funcs from CreateGC and, in each
-func wrapper, unwrap the ops and funcs, call down, and re-wrap. In each op
-wrapper, unwrap the ops, call down, and rewrap afterwards. Note that in
-re-wrapping you must save out the pointer you're replacing again. This way the
-chain will be maintained when wrappers adjust the funcs/ops tables they use.</para>
-</section>
-</section>
-<section>
- <title>Work Queue</title>
-<para>
-To queue work for execution when all clients are in a stable state (i.e.
-just before calling select() in WaitForSomething), call:
-<blockquote><programlisting>
- Bool QueueWorkProc(function,client,closure)
- Bool (*function)();
- ClientPtr client;
- pointer closure;
-</programlisting></blockquote>
-</para>
-<para>
-When the server is about to suspend itself, the given function will be
-executed:
-<blockquote><programlisting>
- (*function) (client, closure)
-</programlisting></blockquote>
-</para>
-<para>
-Neither client nor closure are actually used inside the work queue routines.</para>
-</section>
-</section>
-<section>
- <title>Summary of Routines</title>
-<para>
-This is a summary of the routines discussed in this document.
-The procedure names are in alphabetical order.
-The Struct is the structure it is attached to; if blank, this
-procedure is not attached to a struct and must be named as shown.
-The sample server provides implementations in the following
-categories. Notice that many of the graphics routines have both
-mi and fb implementations.</para>
-<para>
-<itemizedlist>
-<listitem><para>dix portable to all systems; do not attempt to rewrite (Xserver/dix)</para></listitem>
-<listitem><para>os routine provided in Xserver/os or Xserver/include/os.h</para></listitem>
-<listitem><para>ddx frame buffer dependent (examples in Xserver/fb)</para></listitem>
-<listitem><para>mi routine provided in Xserver/mi</para></listitem>
-<listitem><para>hd hardware dependent (examples in many Xserver/hw directories)</para></listitem>
-<listitem><para>none not implemented in sample implementation</para></listitem>
-</itemizedlist>
-</para>
- <table frame="all" id="routines-1">
- <title>Server Routines (Page 1)</title>
- <tgroup cols='3' align='left' colsep='1' rowsep='1'>
- <thead>
- <row>
- <entry>Procedure</entry>
- <entry>Port</entry>
- <entry>Struct</entry>
- </row>
- </thead>
- <tbody>
-<row><entry><function>ALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AbortDDX</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AddCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AddEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AddInputDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AddScreen</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>AdjustWaitForDelay</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>Bell</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row>
-<row><entry><function>ChangeClip</function></entry><entry><literal>mi</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>ChangeGC</function></entry><entry><literal></literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>ChangeWindowAttributes</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>ClearToBackground</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row>
-<row><entry><function>ClientAuthorized</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ClientSignal</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ClientSleep</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ClientWakeup</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ClipNotify</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CloseScreen</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ConstrainCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CopyArea</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>CopyGCDest</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>CopyGCSource</function></entry><entry><literal>none</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>CopyPlane</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>CopyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row>
-<row><entry><function>CreateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CreateCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>CreatePixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CreateScreenResources</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CreateWellKnowSockets</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>CreateWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>CursorLimits</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>DEALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>DeleteCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>DeleteCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>DestroyClip</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>DestroyGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>DestroyPixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>DestroyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>DisplayCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>Error</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ErrorF</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>FatalError</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>FillPolygon</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>FillSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>FlushAllOutput</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>FlushIfCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>FreeScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>GetImage</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>GetMotionEvents</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row>
-<row><entry><function>GetScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>GetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>GetStaticColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
- </tbody>
- </tgroup>
- </table>
-
- <table frame="all" id="routines-2">
- <title>Server Routines (Page 2)</title>
- <tgroup cols='3' align='left' colsep='1' rowsep='1'>
- <thead>
- <row>
- <entry>Procedure</entry>
- <entry>Port</entry>
- <entry>Struct</entry>
- </row>
- </thead>
- <tbody>
-<row><entry><function>ImageGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>ImageText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>ImageText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>InitInput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>InitKeyboardDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>InitOutput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>InitPointerDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>InsertFakeRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>InstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>Intersect</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>Inverse</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>LegalModifier</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>LineHelper</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>ListInstalledColormaps</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>LookupKeyboardDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>LookupPointerDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ModifyPixmapHeader</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>NextAvailableClient</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>OsInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>PaintWindowBackground</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
-<row><entry><function>PaintWindowBorder</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
-<row><entry><function>PointerNonInterestBox</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>PointInRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>PolyArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyFillArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyFillRect</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>Polylines</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyPoint</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyRectangle</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolySegment</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PolyText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PositionWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>ProcessInputEvents</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>PushPixels</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>PutImage</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>QueryBestSize</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>ReadRequestFromClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>RealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RecolorCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RectIn</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionCopy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionCreate</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionDestroy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionExtents</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionNotEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>RegionReset</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>ResolveColor</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
- </tbody>
- </tgroup>
- </table>
-
- <table frame="all" id="routines-3">
- <title>Server Routines (Page 3)</title>
- <tgroup cols='3' align='left' colsep='1' rowsep='1'>
- <thead>
- <row>
- <entry>Procedure</entry>
- <entry>Port</entry>
- <entry>Struct</entry>
- </row>
- </thead>
- <tbody>
-<row><entry><function>RemoveEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>ResetCurrentRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>SaveScreen</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>SetCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>SetCursorPosition</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>SetInputCheck</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row>
-<row><entry><function>SetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row>
-<row><entry><function>StoreColors</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>Subtract</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>TimerCancel</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimerCheck</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimerForce</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimerFree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimerInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimerSet</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TimeSinceLastInputEvent</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row>
-<row><entry><function>TranslateRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>UninstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>Union</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>UnrealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>UnrealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>UnrealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>ValidateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row>
-<row><entry><function>ValidateTree</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row>
-<row><entry><function>WaitForSomething</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>WindowExposures</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row>
-<row><entry><function>WriteToClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>Xalloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>Xfree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
-<row><entry><function>Xrealloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row>
- </tbody>
- </tgroup>
- </table>
-</section>
-</article>
+<?xml version="1.0" encoding="ISO-8859-1"?> +<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.3//EN" + "http://www.oasis-open.org/docbook/xml/4.3/docbookx.dtd" [ + <!ENTITY % defs SYSTEM "/xserver/doc/xml/xserver.ent"> %defs; +]> + +<article> + <articleinfo> + <author> + <firstname>Susan</firstname><surname>Angebranndt</surname> + <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation> + </author> + <author> + <firstname>Raymond</firstname><surname>Drewry</surname> + <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation> + </author> + <author> + <firstname>Philip</firstname><surname>Karlton</surname> + <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation> + </author> + <author> + <firstname>Todd</firstname><surname>Newman</surname> + <affiliation><orgname>Digital Equipment Corporation</orgname></affiliation> + </author> + <author> + <firstname>Bob</firstname><surname>Scheifler</surname> + <affiliation><orgname>Massachusetts Institute of Technology</orgname></affiliation> + </author> + <author> + <firstname>Keith</firstname><surname>Packard</surname> + <affiliation><orgname>MIT X Consortium</orgname></affiliation> + </author> + <author> + <firstname>David</firstname><othername>P.</othername><surname>Wiggins</surname> + <affiliation><orgname>X Consortium</orgname></affiliation> + </author> + <author> + <firstname>Jim</firstname><surname>Gettys</surname> + <affiliation><orgname>X.org Foundation and Hewlett Packard</orgname></affiliation> + </author> + <publisher><publishername>The X.Org Foundation</publishername></publisher> + <pubdate>&xserver.reldate;</pubdate> + <releaseinfo>X server version &xserver.version;</releaseinfo> + <title>Definition of the Porting Layer for the X v11 Sample Server</title> + <titleabbrev>X Porting Layer</titleabbrev> + <revhistory> + <revision> + <revnumber>1.0</revnumber> + <date>27 Oct 2004</date> + <authorinitials>sa</authorinitials> + <revremark>Initial Version</revremark> + </revision> + <revision> + <revnumber>1.1</revnumber> + <date>27 Oct 2004</date> + <authorinitials>bs</authorinitials> + <revremark>Minor Revisions</revremark> + </revision> + <revision> + <revnumber>2.0</revnumber> + <date>27 Oct 2004</date> + <authorinitials>kp</authorinitials> + <revremark>Revised for Release 4 and 5</revremark> + </revision> + <revision> + <revnumber>3.0</revnumber> + <date>27 Oct 2004</date> + <authorinitials>dpw</authorinitials> + <revremark>Revised for Release 6</revremark> + </revision> + <revision> + <revnumber>3.1</revnumber> + <date>27 Oct 2004</date> + <authorinitials>jg</authorinitials> + <revremark>Revised for Release 6.8.2</revremark> + </revision> + <revision> + <revnumber>3.2</revnumber> + <date>17 Dec 2006</date> + <authorinitials>efw</authorinitials> + <revremark>DocBook conversion</revremark> + </revision> + <revision> + <revnumber>3.3</revnumber> + <date>17 Feb 2008</date> + <authorinitials>aj</authorinitials> + <revremark>Revised for backing store changes</revremark> + </revision> + <revision> + <revnumber>3.4</revnumber> + <date>31 Mar 2008</date> + <authorinitials>efw</authorinitials> + <revremark>Revised for devPrivates changes</revremark> + </revision> + <revision> + <revnumber>3.5</revnumber> + <date>July 2010</date> + <authorinitials>ac</authorinitials> + <revremark>Revised for Xorg 1.9 devPrivates changes + and 1.8 CreateNewResourceType changes</revremark> + </revision> + </revhistory> + <legalnotice> + <para>Copyright © 1994 X Consortium, Inc., 2004 X.org Foundation, Inc.</para> + <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> + <para>The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.</para> + <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> + <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> + </legalnotice> + <abstract> + <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: + <orderedlist> + <listitem><para>Read the first section of the "Strategies for Porting" document (Overview of Porting Process).</para></listitem> + <listitem><para>Skim over this document (the Definition document).</para></listitem> + <listitem><para>Skim over the remainder of the Strategies document.</para></listitem> + <listitem><para>Start planning and working, referring to the Strategies and Definition documents.</para></listitem> + </orderedlist> + You may also want to look at the following documents: + <itemizedlist> + <listitem><para>"The X Window System" for an overview of X.</para></listitem> + <listitem><para>"Xlib - C Language X Interface" for a view of what the client programmer sees.</para></listitem> + <listitem><para>"X Window System Protocol" for a terse description of the byte stream protocol between the client and server.</para></listitem> + </itemizedlist> + </para> + <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> + <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> + <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> + </abstract> + </articleinfo> + +<!-- Original authorship information: + +.OF 'Porting Layer Definition'- % -'October 27, 2004' +Definition of the Porting Layer +for the X v11 Sample Server +Susan Angebranndt +Raymond Drewry +Philip Karlton +Todd Newman +Digital Equipment Corporation + +minor revisions by +Bob Scheifler +Massachusetts Institute of Technology + +Revised for Release 4 and Release 5 by +Keith Packard +MIT X Consortium + +Revised for Release 6 by +David P. Wiggins +X Consortium + +Minor Revisions for Release 6.8.2 by +Jim Gettys +X.org Foundation and Hewlett Packard +--> + +<section> + <title>The X Window System</title> +<para> +The X Window System, or simply "X," is a +windowing system that provides high-performance, high-level, +device-independent graphics. +</para> +<para> +X is a windowing system designed for bitmapped graphic displays. +The display can have a +simple, monochrome display or it can have a color display with up to 32 bits +per pixel with a special graphics processor doing the work. (In this +document, monochrome means a black and white display with one bit per pixel. +Even though the usual meaning of monochrome is more general, this special +case is so common that we decided to reserve the word for this purpose.) +In practice, monochrome displays are now almost unheard of, with 4 bit +gray scale displays being the low end. +</para> +<para> +X is designed for a networking environment where +users can run applications on machines other than their own workstations. +Sometimes, the connection is over an Ethernet network with a protocol such as TCP/IP; +but, any "reliable" byte stream is allowable. +A high-bandwidth byte stream is preferable; RS-232 at +9600 baud would be slow without compression techniques. +</para> +<para> +X by itself allows great freedom of design. +For instance, it does not include any user interface standard. +Its intent is to "provide mechanism, not policy." +By making it general, it can be the foundation for a wide +variety of interactive software. +</para> +<para> +For a more detailed overview, see the document "The X Window System." +For details on the byte stream protocol, see "X Window System protocol." +</para> +</section> +<section> +<title>Overview of the Server</title> +<para> +The display server +manages windows and simple graphics requests +for the user on behalf of different client applications. +The client applications can be running on any machine on the network. +The server mainly does three things: +<itemizedlist> + <listitem><para>Responds to protocol requests from existing clients (mostly graphic and text drawing commands)</para></listitem> + <listitem><para>Sends device input (keystrokes and mouse actions) and other events to existing clients</para></listitem> + <listitem><para>Maintains client connections</para></listitem> +</itemizedlist> +</para> +<para> +The server code is organized into four major pieces: +<itemizedlist> + <listitem><para>Device Independent (DIX) layer - code shared among all implementations</para></listitem> + <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> + <listitem><para>Device Dependent (DDX) layer - code that is (potentially) different for each combination of operating system and graphic device</para></listitem> + <listitem><para>Extension Interface - a standard way to add features to the X server</para></listitem> +</itemizedlist> +</para> +<para> +The "porting layer" consists of the OS and DDX layers; these are +actually parallel and neither one is on top of the other. +The DIX layer is intended to be portable +without change to target systems and is not +detailed here, although several routines +in DIX that are called by DDX are +documented. +Extensions incorporate new functionality into the server; and require +additional functionality over a simple DDX. +</para> +<para> +The following sections outline the functions of the layers. +Section 3 briefly tells what you need to know about the DIX layer. +The OS layer is explained in Section 4. +Section 5 gives the theory of operation and procedural interface for the +DDX layer. +Section 6 describes the functions which exist for the extension writer. +</para> +</section> + +<section> + <title>DIX Layer</title> +<para> +The DIX layer is the machine and device independent part of X. +The source should be common to all operating systems and devices. +The port process should not include changes to this part, therefore internal interfaces to DIX +modules are not discussed, except for public interfaces to the DDX and the OS layers. +The functions described in this section are available for extension writers to use. +</para> +<para> +In the process of getting your server to work, if +you think that DIX must be modified for purposes other than bug fixes, +you may be doing something wrong. +Keep looking for a more compatible solution. +When the next release of the X server code is available, +you should be able to just drop in the new DIX code and compile it. +If you change DIX, +you will have to remember what changes you made and will have +to change the new sources before you can update to the new version. +</para> +<para> +The heart of the DIX code is a loop called the dispatch loop. +Each time the processor goes around the loop, it sends off accumulated input events +from the input devices to the clients, and it processes requests from the clients. +This loop is the most organized way for the server to +process the asynchronous requests that +it needs to process. +Most of these operations are performed by OS and DDX routines that you must supply. +</para> +<section> + <title>Server Resource System</title> +<para> +X resources are C structs inside the server. +Client applications create and manipulate these objects +according to the rules of the X byte stream protocol. +Client applications refer to resources with resource IDs, +which are 32-bit integers that are sent over the network. +Within the server, of course, they are just C structs, and we refer to them +by pointers. +</para> +<section> + <title>Pre-Defined Resource Types</title> +<para> +The DDX layer has several kinds of resources: +<itemizedlist> +<listitem><para>Window</para></listitem> +<listitem><para>Pixmap</para></listitem> +<listitem><para>Screen</para></listitem> +<listitem><para>Device</para></listitem> +<listitem><para>Colormap</para></listitem> +<listitem><para>Font</para></listitem> +<listitem><para>Cursor</para></listitem> +<listitem><para>Graphics Contexts</para></listitem> +</itemizedlist> +</para> +<para> +The type names of the more +important server +structs usually end in "Rec," such as "DeviceRec;" +the pointer types usually end in "Ptr," such as "DevicePtr." +</para> +<para> +The structs and +important defined constants are declared +in .h files that have names that suggest the name of the object. +For instance, there are two .h files for windows, +window.h and windowstr.h. +window.h defines only what needs to be defined in order to use windows +without peeking inside of them; +windowstr.h defines the structs with all of their components in great detail +for those who need it. +</para> +<para> +Three kinds of fields are in these structs: +<itemizedlist> +<listitem><para>Attribute fields - struct fields that contain values like normal structs</para></listitem> +<listitem><para>Pointers to procedures, or structures of procedures, that operate on the object</para></listitem> +<listitem><para>A single private field or a devPrivates list (see <xref linkend="wrappers_and_privates"/>) +used by your DDX code to store private data.</para></listitem> +</itemizedlist> +</para> +<para> +DIX calls through +the struct's procedure pointers to do its tasks. +These procedures are set either directly or indirectly by DDX procedures. +Most of +the procedures described in the remainder of this +document are accessed through one of these structs. +For example, the procedure to create a pixmap +is attached to a ScreenRec and might be called by using the expression +</para> +<para> +<blockquote> +<programlisting>(* pScreen->CreatePixmap)(pScreen, width, height, depth).</programlisting> +</blockquote> +</para> +<para> +All procedure pointers must be set to some routine unless noted otherwise; +a null pointer will have unfortunate consequences. +</para> +<para> +Procedure routines will be indicated in the documentation by this convention: +<blockquote> +<programlisting>void pScreen->MyScreenRoutine(arg, arg, ...)</programlisting> +</blockquote> +as opposed to a free routine, not in a data structure: +<blockquote> +<programlisting>void MyFreeRoutine(arg, arg, ...)</programlisting> +</blockquote> +</para> +<para> +The attribute fields are mostly set by DIX; DDX should not modify them +unless noted otherwise. +</para> +</section> +<section> + <title>Creating Resources and Resource Types</title> +<para> +These functions should also be called from your extensionInitProc to +allocate all of the various resource classes and types required for +the extension. Each time the server resets, these types must be reallocated +as the old allocations will have been discarded. +Resource types are integer values starting at 1. Get +a resource type by calling +<blockquote><programlisting> + + RESTYPE CreateNewResourceType(deleteFunc, char *name) + +</programlisting></blockquote> +deleteFunc will be called to destroy all resources with this +type. name will be used to identify this type of resource +to clients using the X-Resource extension, to security +extensions such as SELinux, and to tracing frameworks such as DTrace. +[The name argument was added in xorg-server 1.8.] +</para> +<para> +Resource classes are masks starting at 1 << 31 which can +be or'ed with any resource type to provide attributes for the +type. To allocate a new class bit, call +<blockquote><programlisting> + + RESTYPE CreateNewResourceClass() + +</programlisting></blockquote> +</para> +<para> +There are two ways of looking up resources, by type or +by class. Classes are non-exclusive subsets of the space of +all resources, so you can lookup the union of multiple classes. +(RC_ANY is the union of all classes).</para> +<para> +Note that the appropriate class bits must be or'ed into the value returned +by CreateNewResourceType when calling resource lookup functions.</para> +<para> +If you need to create a ``private'' resource ID for internal use, you +can call FakeClientID. +<blockquote><programlisting> + + XID FakeClientID(client) + int client; + +</programlisting></blockquote> +This allocates from ID space reserved for the server.</para> +<para> +To associate a resource value with an ID, use AddResource. +<blockquote><programlisting> + + Bool AddResource(id, type, value) + XID id; + RESTYPE type; + pointer value; + +</programlisting></blockquote> +The type should be the full type of the resource, including any class +bits. If AddResource fails to allocate memory to store the resource, +it will call the deleteFunc for the type, and then return False.</para> +<para> +To free a resource, use one of the following. +<blockquote><programlisting> + + void FreeResource(id, skipDeleteFuncType) + XID id; + RESTYPE skipDeleteFuncType; + + void FreeResourceByType(id, type, skipFree) + XID id; + RESTYPE type; + Bool skipFree; + +</programlisting></blockquote> +FreeResource frees all resources matching the given id, regardless of +type; the type's deleteFunc will be called on each matching resource, +except that skipDeleteFuncType can be set to a single type for which +the deleteFunc should not be called (otherwise pass RT_NONE). +FreeResourceByType frees a specific resource matching a given id +and type; if skipFree is true, then the deleteFunc is not called. +</para> +</section> +<section> + <title>Looking Up Resources</title> +<para> +To look up a resource, use one of the following. +<blockquote><programlisting> + + int dixLookupResourceByType( + pointer *result, + XID id, + RESTYPE rtype, + ClientPtr client, + Mask access_mode); + + int dixLookupResourceByClass( + pointer *result, + XID id, + RESTYPE rclass, + ClientPtr client, + Mask access_mode); + +</programlisting></blockquote> +dixLookupResourceByType finds a resource with the given id and exact type. +dixLookupResourceByClass finds a resource with the given id whose type is +included in any one of the specified classes. +The client and access_mode must be provided to allow security extensions to +check if the client has the right privileges for the requested access. +The bitmask values defined in the dixaccess.h header are or'ed together +to define the requested access_mode. +</para> +</section> +</section> +<section> + <title>Callback Manager</title> +<para> +To satisfy a growing number of requests for the introduction of ad hoc +notification style hooks in the server, a generic callback manager was +introduced in R6. A callback list object can be introduced for each +new hook that is desired, and other modules in the server can register +interest in the new callback list. The following functions support +these operations.</para> +<para> +Before getting bogged down in the interface details, an typical usage +example should establish the framework. Let's look at the +ClientStateCallback in dix/dispatch.c. The purpose of this particular +callback is to notify interested parties when a client's state +(initial, running, gone) changes. The callback is "created" in this +case by simply declaring a variable: +<blockquote><programlisting> + CallbackListPtr ClientStateCallback; +</programlisting></blockquote> +</para> +<para> +Whenever the client's state changes, the following code appears, which notifies +all interested parties of the change: +<blockquote><programlisting> + if (ClientStateCallback) CallCallbacks(&ClientStateCallback, (pointer)client); +</programlisting></blockquote> +</para> +<para> +Interested parties subscribe to the ClientStateCallback list by saying: +<blockquote><programlisting> + AddCallback(&ClientStateCallback, func, data); +</programlisting></blockquote> +</para> +<para> +When CallCallbacks is invoked on the list, func will be called thusly: +<blockquote><programlisting> + (*func)(&ClientStateCallback, data, client) +</programlisting></blockquote> +</para> +<para> +Now for the details. +<blockquote><programlisting> + + Bool AddCallback(pcbl, callback, subscriber_data) + CallbackListPtr *pcbl; + CallbackProcPtr callback; + pointer subscriber_data; + +</programlisting></blockquote> +Adds the (callback, subscriber_data) pair to the given callback list. Creates the callback +list if it doesn't exist. Returns TRUE if successful.</para> +<para> +<blockquote><programlisting> + + Bool DeleteCallback(pcbl, callback, subscriber_data) + CallbackListPtr *pcbl; + CallbackProcPtr callback; + pointer subscriber_data; + +</programlisting></blockquote> +Removes the (callback, data) pair to the given callback list if present. +Returns TRUE if (callback, data) was found.</para> +<para> +<blockquote><programlisting> + + void CallCallbacks(pcbl, call_data) + CallbackListPtr *pcbl; + pointer call_data; + +</programlisting></blockquote> +For each callback currently registered on the given callback list, call +it as follows: +<blockquote><programlisting> + + (*callback)(pcbl, subscriber_data, call_data); +</programlisting></blockquote> +</para> +<para> +<blockquote><programlisting> + void DeleteCallbackList(pcbl) + CallbackListPtr *pcbl; + +</programlisting></blockquote> +Destroys the given callback list.</para> +</section> +<section> + <title>Extension Interfaces</title> +<para> +This function should be called from your extensionInitProc which +should be called by InitExtensions. +<blockquote><programlisting> + + ExtensionEntry *AddExtension(name, NumEvents,NumErrors, + MainProc, SwappedMainProc, CloseDownProc, MinorOpcodeProc) + + char *name; /*Null terminate string; case matters*/ + int NumEvents; + int NumErrors; + int (* MainProc)(ClientPtr);/*Called if client matches server order*/ + int (* SwappedMainProc)(ClientPtr);/*Called if client differs from server*/ + void (* CloseDownProc)(ExtensionEntry *); + unsigned short (*MinorOpcodeProc)(ClientPtr); + +</programlisting></blockquote> +name is the name used by clients to refer to the extension. NumEvents is the +number of event types used by the extension, NumErrors is the number of +error codes needed by the extension. MainProc is called whenever a client +accesses the major opcode assigned to the extension. SwappedMainProc is +identical, except the client using the extension has reversed byte-sex. +CloseDownProc is called at server reset time to deallocate any private +storage used by the extension. MinorOpcodeProc is used by DIX to place the +appropriate value into errors. The DIX routine StandardMinorOpcode can be +used here which takes the minor opcode from the normal place in the request +(i.e. just after the major opcode).</para> +</section> +<section> + <title>Macros and Other Helpers</title> +<para> +There are a number of macros in Xserver/include/dix.h which +are useful to the extension writer. Ones of particular interest +are: REQUEST, REQUEST_SIZE_MATCH, REQUEST_AT_LEAST_SIZE, +REQUEST_FIXED_SIZE, LEGAL_NEW_RESOURCE, and +VALIDATE_DRAWABLE_AND_GC. Useful byte swapping macros can be found +in Xserver/include/dix.h: WriteReplyToClient and WriteSwappedDataToClient; and +in Xserver/include/misc.h: lswapl, lswaps, LengthRestB, LengthRestS, +LengthRestL, SwapRestS, SwapRestL, swapl, swaps, cpswapl, and cpswaps.</para> +</section> +</section> + +<section> + <title>OS Layer</title> +<para> +This part of the source consists of a few routines that you have to rewrite +for each operating system. +These OS functions maintain the client connections and schedule work +to be done for clients. +They also provide an interface to font files, +font name to file name translation, and +low level memory management. +<blockquote> +<programlisting>void OsInit()</programlisting> +</blockquote> +OsInit initializes your OS code, performing whatever tasks need to be done. +Frequently there is not much to be done. +The sample server implementation is in Xserver/os/osinit.c. +</para> +<section> + <title>Scheduling and Request Delivery</title> +<para> +The main dispatch loop in DIX creates the illusion of multitasking between +different windows, while the server is itself but a single process. +The dispatch loop breaks up the work for each client into small digestible parts. +Some parts are requests from a client, such as individual graphic commands. +Some parts are events delivered to the client, such as keystrokes from the user. +The processing of events and requests for different +clients can be interleaved with one another so true multitasking +is not needed in the server. +</para> +<para> +You must supply some of the pieces for proper scheduling between clients. +<blockquote> +<programlisting> + int WaitForSomething(pClientReady) + int *pClientReady; +</programlisting> +</blockquote> +</para> +<para> +WaitForSomething is the scheduler procedure you must write that will +suspend your server process until something needs to be done. +This call should +make the server suspend until one or more of the following occurs: +<itemizedlist> +<listitem><para>There is an input event from the user or hardware (see SetInputCheck())</para></listitem> +<listitem><para>There are requests waiting from known clients, in which case you should return a count of clients stored in pClientReady</para></listitem> +<listitem><para>A new client tries to connect, in which case you should create the client and then continue waiting</para></listitem> +</itemizedlist> +</para> +<para> +Before WaitForSomething() computes the masks to pass to select, poll or +similar operating system interface, it needs to +see if there is anything to do on the work queue; if so, it must call a DIX +routine called ProcessWorkQueue. +<blockquote> +<programlisting> + extern WorkQueuePtr workQueue; + + if (workQueue) + ProcessWorkQueue (); +</programlisting> +</blockquote> +</para> +<para> +If WaitForSomething() decides it is about to do something that might block +(in the sample server, before it calls select() or poll) it must call a DIX +routine called BlockHandler(). +<blockquote> +<programlisting> + void BlockHandler(pTimeout, pReadmask) + pointer pTimeout; + pointer pReadmask; +</programlisting> +</blockquote> +The types of the arguments are for agreement between the OS and DDX +implementations, but the pTimeout is a pointer to the information +determining how long the block is allowed to last, and the +pReadmask is a pointer to the information describing the descriptors +that will be waited on. +</para> +<para> +In the sample server, pTimeout is a struct timeval **, and pReadmask is +the address of the select() mask for reading. +</para> +<para> +The DIX BlockHandler() iterates through the Screens, for each one calling +its BlockHandler. A BlockHandler is declared thus: +<blockquote> +<programlisting> + void xxxBlockHandler(nscreen, pbdata, pptv, pReadmask) + int nscreen; + pointer pbdata; + struct timeval ** pptv; + pointer pReadmask; +</programlisting> +</blockquote> +The arguments are the index of the Screen, the blockData field +of the Screen, and the arguments to the DIX BlockHandler(). +</para> +<para> +Immediately after WaitForSomething returns from the +block, even if it didn't actually block, it must call the DIX routine +WakeupHandler(). +<blockquote> +<programlisting> + void WakeupHandler(result, pReadmask) + int result; + pointer pReadmask; +</programlisting> +</blockquote> +Once again, the types are not specified by DIX. The result is the +success indicator for the thing that (may have) blocked, +and the pReadmask is a mask of the descriptors that came active. +In the sample server, result is the result from select() (or equivalent +operating system function), and pReadmask is +the address of the select() mask for reading. +</para> +<para> +The DIX WakeupHandler() calls each Screen's +WakeupHandler. A WakeupHandler is declared thus: +<blockquote> +<programlisting> + void xxxWakeupHandler(nscreen, pbdata, err, pReadmask) + int nscreen; + pointer pbdata; + unsigned long result; + pointer pReadmask; +</programlisting> +</blockquote> +The arguments are the index of the Screen, the blockData field +of the Screen, and the arguments to the DIX WakeupHandler(). +</para> +<para> +In addition to the per-screen BlockHandlers, any module may register +block and wakeup handlers (only together) using: +<blockquote> +<programlisting> + Bool RegisterBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData) + BlockHandlerProcPtr blockHandler; + WakeupHandlerProcPtr wakeupHandler; + pointer blockData; +</programlisting> +</blockquote> +A FALSE return code indicates that the registration failed for lack of +memory. To remove a registered Block handler at other than server reset time +(when they are all removed automatically), use: +<blockquote> +<programlisting> + RemoveBlockAndWakeupHandlers (blockHandler, wakeupHandler, blockData) + BlockHandlerProcPtr blockHandler; + WakeupHandlerProcPtr wakeupHandler; + pointer blockData; +</programlisting> +</blockquote> +All three arguments must match the values passed to +RegisterBlockAndWakeupHandlers. +</para> +<para> +These registered block handlers are called after the per-screen handlers: +<blockquote> +<programlisting> + void (*BlockHandler) (blockData, pptv, pReadmask) + pointer blockData; + OsTimerPtr pptv; + pointer pReadmask; +</programlisting> +</blockquote> +</para> +<para> +Sometimes block handlers need to adjust the time in a OSTimePtr structure, +which on UNIX family systems is generally represented by a struct timeval +consisting of seconds and microseconds in 32 bit values. +As a convenience to reduce error prone struct timeval computations which +require modulus arithmetic and correct overflow behavior in the face of +millisecond wrapping through 32 bits, +<blockquote><programlisting> + + void AdjustWaitForDelay(pointer /*waitTime*, unsigned long /* newdelay */) + +</programlisting></blockquote> +has been provided. +</para> +<para> +Any wakeup handlers registered with RegisterBlockAndWakeupHandlers will +be called before the Screen handlers: +<blockquote><programlisting> + + void (*WakeupHandler) (blockData, err, pReadmask) + pointer blockData; + int err; + pointer pReadmask; +</programlisting></blockquote> +</para> +<para> +The WaitForSomething on the sample server also has a built +in screen saver that darkens the screen if no input happens for a period of time. +The sample server implementation is in Xserver/os/WaitFor.c. +</para> +<para> +Note that WaitForSomething() may be called when you already have several +outstanding things (events, requests, or new clients) queued up. +For instance, your server may have just done a large graphics request, +and it may have been a long time since WaitForSomething() was last called. +If many clients have lots of requests queued up, DIX will only service +some of them for a given client +before going on to the next client (see isItTimeToYield, below). +Therefore, WaitForSomething() will have to report that these same clients +still have requests queued up the next time around. +</para> +<para> +An implementation should return information on as +many outstanding things as it can. +For instance, if your implementation always checks for client data first and does not +report any input events until there is no client data left, +your mouse and keyboard might get locked out by an application that constantly +barrages the server with graphics drawing requests. +Therefore, as a general rule, input devices should always have priority over graphics +devices. +</para> +<para> +A list of indexes (client->index) for clients with data ready to be read or +processed should be returned in pClientReady, and the count of indexes +returned as the result value of the call. +These are not clients that have full requests ready, but any clients who have +any data ready to be read or processed. +The DIX dispatcher +will process requests from each client in turn by calling +ReadRequestFromClient(), below. +</para> +<para> +WaitForSomething() must create new clients as they are requested (by +whatever mechanism at the transport level). A new client is created +by calling the DIX routine: +<blockquote><programlisting> + + ClientPtr NextAvailableClient(ospriv) + pointer ospriv; +</programlisting></blockquote> +This routine returns NULL if a new client cannot be allocated (e.g. maximum +number of clients reached). The ospriv argument will be stored into the OS +private field (pClient->osPrivate), to store OS private information about the +client. In the sample server, the osPrivate field contains the +number of the socket for this client. See also "New Client Connections." +NextAvailableClient() will call InsertFakeRequest(), so you must be +prepared for this. +</para> +<para> +If there are outstanding input events, +you should make sure that the two SetInputCheck() locations are unequal. +The DIX dispatcher will call your implementation of ProcessInputEvents() +until the SetInputCheck() locations are equal. +</para> +<para> +The sample server contains an implementation of WaitForSomething(). +The +following two routines indicate to WaitForSomething() what devices should +be waited for. fd is an OS dependent type; in the sample server +it is an open file descriptor. +<blockquote><programlisting> + + int AddEnabledDevice(fd) + int fd; + + int RemoveEnabledDevice(fd) + int fd; +</programlisting></blockquote> +These two routines are +usually called by DDX from the initialize cases of the +Input Procedures that are stored in the DeviceRec (the +routine passed to AddInputDevice()). +The sample server implementation of AddEnabledDevice +and RemoveEnabledDevice are in Xserver/os/connection.c. +</para> +<section> + <title>Timer Facilities</title> +<para> +Similarly, the X server or an extension may need to wait for some timeout. +Early X releases implemented this functionality using block and wakeup handlers, +but this has been rewritten to use a general timer facilty, and the +internal screen saver facilities reimplemented to use Timers. +These functions are TimerInit, TimerForce, TimerSet, TimerCheck, TimerCancel, +and TimerFree, as defined in Xserver/include/os.h. A callback function will be called +when the timer fires, along with the current time, and a user provided argument. +<blockquote><programlisting> + typedef struct _OsTimerRec *OsTimerPtr; + + typedef CARD32 (*OsTimerCallback)( + OsTimerPtr /* timer */, + CARD32 /* time */, + pointer /* arg */); + + OsTimerPtr TimerSet( OsTimerPtr /* timer */, + int /* flags */, + CARD32 /* millis */, + OsTimerCallback /* func */, + pointer /* arg */); + +</programlisting></blockquote> +</para> +<para> +TimerSet returns a pointer to a timer structure and sets a timer to the specified time +with the specified argument. The flags can be TimerAbsolute and TimerForceOld. +The TimerSetOld flag controls whether if the timer is reset and the timer is pending, the +whether the callback function will get called. +The TimerAbsolute flag sets the callback time to an absolute time in the future rather +than a time relative to when TimerSet is called. +TimerFree should be called to free the memory allocated +for the timer entry. +<blockquote><programlisting> + void TimerInit(void) + + Bool TimerForce(OsTimerPtr /* pTimer */) + + void TimerCheck(void); + + void TimerCancel(OsTimerPtr /* pTimer */) + + void TimerFree(OsTimerPtr /* pTimer */) +</programlisting></blockquote> +</para> +<para> +TimerInit frees any existing timer entries. TimerForce forces a call to the timer's +callback function and returns true if the timer entry existed, else it returns false and +does not call the callback function. TimerCancel will cancel the specified timer. +TimerFree calls TimerCancel and frees the specified timer. +Calling TimerCheck will force the server to see if any timer callbacks should be called. +</para> +</section> +</section> +<section> + <title>New Client Connections</title> +<para> +The process whereby a new client-server connection starts up is +very dependent upon what your byte stream mechanism. +This section describes byte stream initiation using examples from the TCP/IP +implementation on the sample server. +</para> +<para> +The first thing that happens is a client initiates a connection with the server. +How a client knows to do this depends upon your network facilities and the +Xlib implementation. +In a typical scenario, a user named Fred +on his X workstation is logged onto a Cray +supercomputer running a command shell in an X window. Fred can type shell +commands and have the Cray respond as though the X server were a dumb terminal. +Fred types in a command to run an X client application that was linked with Xlib. +Xlib looks at the shell environment variable DISPLAY, which has the +value "fredsbittube:0.0." +The host name of Fred's workstation is "fredsbittube," and the 0s are +for multiple screens and multiple X server processes. +(Precisely what +happens on your system depends upon how X and Xlib are implemented.) +</para> +<para> +The client application calls a TCP routine on the +Cray to open a TCP connection for X +to communicate with the network node "fredsbittube." +The TCP software on the Cray does this by looking up the TCP +address of "fredsbittube" and sending an open request to TCP port 6000 +on fredsbittube. +</para> +<para> +All X servers on TCP listen for new clients on port 6000 by default; +this is known as a "well-known port" in IP terminology. +</para> +<para> +The server receives this request from its port 6000 +and checks where it came from to see if it is on the server's list +of "trustworthy" hosts to talk to. +Then, it opens another port for communications with the client. +This is the byte stream that all X communications will go over. +</para> +<para> +Actually, it is a bit more complicated than that. +Each X server process running on the host machine is called a "display." +Each display can have more than one screen that it manages. +"corporatehydra:3.2" represents screen 2 on display 3 on +the multi-screened network node corporatehydra. +The open request would be sent on well-known port number 6003. +</para> +<para> +Once the byte stream is set up, what goes on does not depend very much +upon whether or not it is TCP. +The client sends an xConnClientPrefix struct (see Xproto.h) that has the +version numbers for the version of Xlib it is running, some byte-ordering information, +and two character strings used for authorization. +If the server does not like the authorization strings +or the version numbers do not match within the rules, +or if anything else is wrong, it sends a failure +response with a reason string. +</para> +<para> +If the information never comes, or comes much too slowly, the connection +should be broken off. You must implement the connection timeout. The +sample server implements this by keeping a timestamp for each still-connecting +client and, each time just before it attempts to accept new connections, it +closes any connection that are too old. +The connection timeout can be set from the command line. +</para> +<para> +You must implement whatever authorization schemes you want to support. +The sample server on the distribution tape supports a simple authorization +scheme. The only interface seen by DIX is: +<blockquote><programlisting> + + char * + ClientAuthorized(client, proto_n, auth_proto, string_n, auth_string) + ClientPtr client; + unsigned int proto_n; + char *auth_proto; + unsigned int string_n; + char *auth_string; +</programlisting></blockquote> +DIX will only call this once per client, once it has read the full initial +connection data from the client. If the connection should be +accepted ClientAuthorized() should return NULL, and otherwise should +return an error message string. +</para> +<para> +Accepting new connections happens internally to WaitForSomething(). +WaitForSomething() must call the DIX routine NextAvailableClient() +to create a client object. +Processing of the initial connection data will be handled by DIX. +Your OS layer must be able to map from a client +to whatever information your OS code needs to communicate +on the given byte stream to the client. +DIX uses this ClientPtr to refer to +the client from now on. The sample server uses the osPrivate field in +the ClientPtr to store the file descriptor for the socket, the +input and output buffers, and authorization information. +</para> +<para> +To initialize the methods you choose to allow clients to connect to +your server, main() calls the routine +<blockquote><programlisting> + + void CreateWellKnownSockets() +</programlisting></blockquote> +This routine is called only once, and not called when the server +is reset. To recreate any sockets during server resets, the following +routine is called from the main loop: +<blockquote><programlisting> + + void ResetWellKnownSockets() +</programlisting></blockquote> +Sample implementations of both of these routines are found in +Xserver/os/connection.c. +</para> +<para> +For more details, see the section called "Connection Setup" in the X protocol specification. +</para> +</section> +<section> + <title>Reading Data from Clients</title> +<para> +Requests from the client are read in as a byte stream by the OS layer. +They may be in the form of several blocks of bytes delivered in sequence; requests may +be broken up over block boundaries or there may be many requests per block. +Each request carries with it length information. +It is the responsibility of the following routine to break it up into request blocks. +<blockquote><programlisting> + + int ReadRequestFromClient(who) + ClientPtr who; +</programlisting></blockquote> +</para> +<para> +You must write +the routine ReadRequestFromClient() to get one request from the byte stream +belonging to client "who." +You must swap the third and fourth bytes (the second 16-bit word) according to the +byte-swap rules of +the protocol to determine the length of the +request. +This length is measured in 32-bit words, not in bytes. Therefore, the +theoretical maximum request is 256K. +(However, the maximum length allowed is dependent upon the server's input +buffer. This size is sent to the client upon connection. The maximum +size is the constant MAX_REQUEST_SIZE in Xserver/include/os.h) +The rest of the request you return is +assumed NOT to be correctly swapped for internal +use, because that is the responsibility of DIX. +</para> +<para> +The 'who' argument is the ClientPtr returned from WaitForSomething. +The return value indicating status should be set to the (positive) byte count if the read is successful, +0 if the read was blocked, or a negative error code if an error happened. +</para> +<para> +You must then store a pointer to +the bytes of the request in the client request buffer field; +who->requestBuffer. This can simply be a pointer into your buffer; +DIX may modify it in place but will not otherwise cause damage. +Of course, the request must be contiguous; you must +shuffle it around in your buffers if not. +</para> +<para> +The sample server implementation is in Xserver/os/io.c. +</para> +<section><title>Inserting Data for Clients</title> +<para> +DIX can insert data into the client stream, and can cause a "replay" of +the current request. +<blockquote><programlisting> + + Bool InsertFakeRequest(client, data, count) + ClientPtr client; + char *data; + int count; + + int ResetCurrentRequest(client) + ClientPtr client; +</programlisting></blockquote> +</para> +<para> +InsertFakeRequest() must insert the specified number of bytes of data +into the head of the input buffer for the client. This may be a +complete request, or it might be a partial request. For example, +NextAvailableCient() will insert a partial request in order to read +the initial connection data sent by the client. The routine returns FALSE +if memory could not be allocated. ResetCurrentRequest() +should "back up" the input buffer so that the currently executing request +will be reexecuted. DIX may have altered some values (e.g. the overall +request length), so you must recheck to see if you still have a complete +request. ResetCurrentRequest() should always cause a yield (isItTimeToYield). +</para> +</section> +</section> + +<section> + <title>Sending Events, Errors And Replies To Clients</title> +<para> +<blockquote><programlisting> + + int WriteToClient(who, n, buf) + ClientPtr who; + int n; + char *buf; +</programlisting></blockquote> +WriteToClient should write n bytes starting at buf to the +ClientPtr "who". +It returns the number of bytes written, but for simplicity, +the number returned must be either the same value as the number +requested, or -1, signaling an error. +The sample server implementation is in Xserver/os/io.c. +</para> +<para> +<blockquote><programlisting> + void SendErrorToClient(client, majorCode, minorCode, resId, errorCode) + ClientPtr client; + unsigned int majorCode; + unsigned int minorCode; + XID resId; + int errorCode; +</programlisting></blockquote> +SendErrorToClient can be used to send errors back to clients, +although in most cases your request function should simply return +the error code, having set client->errorValue to the appropriate +error value to return to the client, and DIX will call this +function with the correct opcodes for you. +</para> +<para> +<blockquote><programlisting> + + void FlushAllOutput() + + void FlushIfCriticalOutputPending() + + void SetCriticalOutputPending() +</programlisting></blockquote> +These three routines may be implemented to support buffered or delayed +writes to clients, but at the very least, the stubs must exist. +FlushAllOutput() unconditionally flushes all output to clients; +FlushIfCriticalOutputPending() flushes output only if +SetCriticalOutputPending() has be called since the last time output +was flushed. +The sample server implementation is in Xserver/os/io.c and +actually ignores requests to flush output on a per-client basis +if it knows that there +are requests in that client's input queue. +</para> +</section> +<section> + <title>Font Support</title> +<para> +In the sample server, fonts are encoded in disk files or fetched from the +font server. The two fonts required by the server, <quote>fixed</quote> +and <quote>cursor</quote> are commonly compiled into the font library. +For disk fonts, there is one file per font, with a file name like +"fixed.pcf". Font server fonts are read over the network using the +X Font Server Protocol. The disk directories containing disk fonts and +the names of the font servers are listed together in the current "font path." +</para> +<para> +In principle, you can put all your fonts in ROM or in RAM in your server. +You can put them all in one library file on disk. +You could generate them on the fly from stroke descriptions. By placing the +appropriate code in the Font Library, you will automatically export fonts in +that format both through the X server and the Font server. +</para> +<para> +The code for processing fonts in different formats, as well as handling the +metadata files for them on disk (such as <filename>fonts.dir</filename>) is +located in the libXfont library, which is provided as a separately compiled +module. These routines are +shared between the X server and the Font server, so instead of this document +specifying what you must implement, simply refer to the font +library interface specification for the details. All of the interface code to the Font +library is contained in dix/dixfonts.c +</para> +</section> +<section> + <title>Memory Management</title> +<para> +Memory management is based on functions in the C runtime library. +Xalloc(), Xrealloc(), and Xfree() are deprecated aliases for malloc(), +realloc(), and free(), and you should simply call the C library functions +directly. Consult a C runtime library reference +manual for more details. +</para> +<para> +Treat memory allocation carefully in your implementation. Memory +leaks can be very hard to find and are frustrating to a user. An X +server could be running for days or weeks without being reset, just +like a regular terminal. If you leak a few dozen k per day, that will +add up and will cause problems for users that leave their workstations +on. +</para> +</section> +<section> + <title>Client Scheduling</title> +<para> +The X server +has the ability to schedule clients much like an operating system would, +suspending and restarting them without regard for the state of their input +buffers. This functionality allows the X server to suspend one client and +continue processing requests from other clients while waiting for a +long-term network activity (like loading a font) before continuing with the +first client. +<blockquote><programlisting> + Bool isItTimeToYield; +</programlisting></blockquote> +isItTimeToYield is a global variable you can set +if you want to tell +DIX to end the client's "time slice" and start paying attention to the next client. +After the current request is finished, DIX will move to the next client. +</para> +<para> +In the sample +server, ReadRequestFromClient() sets isItTimeToYield after +10 requests packets in a row are read from the same client. +</para> +<para> +This scheduling algorithm can have a serious effect upon performance when two +clients are drawing into their windows simultaneously. +If it allows one client to run until its request +queue is empty by ignoring isItTimeToYield, the client's queue may +in fact never empty and other clients will be blocked out. +On the other hand, if it switchs between different clients too quickly, +performance may suffer due to too much switching between contexts. +For example, if a graphics processor needs to be set up with drawing modes +before drawing, and two different clients are drawing with +different modes into two different windows, you may +switch your graphics processor modes so often that performance is impacted. +</para> +<para> +See the Strategies document for +heuristics on setting isItTimeToYield. +</para> +<para> +The following functions provide the ability to suspend request +processing on a particular client, resuming it at some later time: +<blockquote><programlisting> + + int IgnoreClient (who) + ClientPtr who; + + int AttendClient (who) + ClientPtr who; +</programlisting></blockquote> +Ignore client is responsible for pretending that the given client doesn't +exist. WaitForSomething should not return this client as ready for reading +and should not return if only this client is ready. AttendClient undoes +whatever IgnoreClient did, setting it up for input again. +</para> +<para> +Three functions support "process control" for X clients: +<blockquote><programlisting> + + Bool ClientSleep (client, function, closure) + ClientPtr client; + Bool (*function)(); + pointer closure; + +</programlisting></blockquote> +This suspends the current client (the calling routine is responsible for +making its way back to Dispatch()). No more X requests will be processed +for this client until ClientWakeup is called. +<blockquote><programlisting> + + Bool ClientSignal (client) + ClientPtr client; + +</programlisting></blockquote> +This function causes a call to the (*function) parameter passed to +ClientSleep to be queued on the work queue. This does not automatically +"wakeup" the client, but the function called is free to do so by calling: +<blockquote><programlisting> + + ClientWakeup (client) + ClientPtr client; + +</programlisting></blockquote> +This re-enables X request processing for the specified client. +</para> +</section> +<section> + <title>Other OS Functions</title> +<para> +<blockquote><programlisting> + void + ErrorF(char *f, ...) + + void + FatalError(char *f, ...) + + void + Error(str) + char *str; +</programlisting></blockquote> +You should write these three routines to provide for diagnostic output +from the dix and ddx layers, although implementing them to produce no +output will not affect the correctness of your server. ErrorF() and +FatalError() take a printf() type of format specification in the first +argument and an implementation-dependent number of arguments following +that. Normally, the formats passed to ErrorF() and FatalError() +should be terminated with a newline. Error() provides an os interface +for printing out the string passed as an argument followed by a +meaningful explanation of the last system error. Normally the string +does not contain a newline, and it is only called by the ddx layer. +In the sample implementation, Error() uses the perror() function. +</para> +<para> +After printing the message arguments, FatalError() must be implemented +such that the server will call AbortDDX() to give the ddx layer +a chance to reset the hardware, and then +terminate the server; it must not return. +</para> +<para> +The sample server implementation for these routines +is in Xserver/os/log.c along with other routines for logging messages. +</para> +</section> +</section> + +<section> + <title>DDX Layer</title> +<para> +This section describes the +interface between DIX and DDX. +While there may be an OS-dependent driver interface between DDX +and the physical device, that interface is left to the DDX +implementor and is not specified here. +</para> +<para> +The DDX layer does most of its work through procedures that are +pointed to by different structs. +As previously described, the behavior of these resources is largely determined by +these procedure pointers. +Most of these routines are for graphic display on the screen or support functions thereof. +The rest are for user input from input devices. +</para> +<section> + <title>Input</title> +<para> +In this document "input" refers to input from the user, +such as mouse, keyboard, and +bar code readers. +X input devices are of several types: keyboard, pointing device, and +many others. The core server has support for extension devices as +described by the X Input Extension document; the interfaces used by +that extension are described elsewhere. The core devices are actually +implemented as two collections of devices, the mouse is a ButtonDevice, +a ValuatorDevice and a PtrFeedbackDevice while the keyboard is a KeyDevice, +a FocusDevice and a KbdFeedbackDevice. Each part implements a portion of +the functionality of the device. This abstraction is hidden from view for +core devices by DIX. +</para> +<para> +You, the DDX programmer, are +responsible for some of the routines in this section. +Others are DIX routines that you should call to do the things you need to do in these DDX routines. +Pay attention to which is which. +</para> +<section> + <title>Input Device Data Structures</title> +<para> +DIX keeps a global directory of devices in a central data structure +called InputInfo. +For each device there is a device structure called a DeviceRec. +DIX can locate any DeviceRec through InputInfo. +In addition, it has a special pointer to identify the main pointing device +and a special pointer to identify the main keyboard. +</para> +<para> +The DeviceRec (Xserver/include/input.h) is a device-independent +structure that contains the state of an input device. +A DevicePtr is simply a pointer to a DeviceRec. +</para> +<para> +An xEvent describes an event the server reports to a client. +Defined in Xproto.h, it is a huge struct of union of structs that have fields for +all kinds of events. +All of the variants overlap, so that the struct is actually very small in memory. +</para> +</section> +<section> + <title>Processing Events</title> +<para> +The main DDX input interface is the following routine: +<blockquote><programlisting> + + void ProcessInputEvents() +</programlisting></blockquote> +You must write this routine to deliver input events from the user. +DIX calls it when input is pending (see next section), and possibly +even when it is not. +You should write it to get events from each device and deliver +the events to DIX. +To deliver the events to DIX, DDX should call the following +routine: +<blockquote><programlisting> + + void DevicePtr->processInputProc(pEvent, device, count) + xEventPtr events; + DeviceIntPtr device; + int count; +</programlisting></blockquote> +This is the "input proc" for the device, a DIX procedure. +DIX will fill in this procedure pointer to one of its own routines by +the time ProcessInputEvents() is called the first time. +Call this input proc routine as many times as needed to +deliver as many events as should be delivered. +DIX will buffer them up and send them out as needed. Count is set +to the number of event records which make up one atomic device event and +is always 1 for the core devices (see the X Input Extension for descriptions +of devices which may use count > 1). +</para> +<para> +For example, your ProcessInputEvents() routine might check the mouse and the +keyboard. +If the keyboard had several keystrokes queued up, it could just call +the keyboard's processInputProc as many times as needed to flush its internal queue. +</para> +<para> +event is an xEvent struct you pass to the input proc. +When the input proc returns, it is finished with the event rec, and you can fill +in new values and call the input proc again with it. +</para> +<para> +You should deliver the events in the same order that they were generated. +</para> +<para> +For keyboard and pointing devices the xEvent variant should be keyButtonPointer. +Fill in the following fields in the xEvent record: +<itemizedlist> + +<listitem><para>type - is one of the following: KeyPress, KeyRelease, ButtonPress, + ButtonRelease, or MotionNotify</para></listitem> +<listitem><para>detail - for KeyPress or KeyRelease fields, this should be the + key number (not the ASCII code); otherwise unused</para></listitem> +<listitem><para>time - is the time that the event happened (32-bits, in milliseconds, arbitrary origin)</para></listitem> +<listitem><para>rootX - is the x coordinate of cursor</para></listitem> +<listitem><para>rootY - is the y coordinate of cursor</para></listitem> + +</itemizedlist> +The rest of the fields are filled in by DIX. +</para> +<para> +The time stamp is maintained by your code in the DDX layer, and it is your responsibility to +stamp all events correctly. +</para> +<para> +The x and y coordinates of the pointing device and the time must be filled in for all event types +including keyboard events. +</para> +<para> +The pointing device must report all button press and release events. +In addition, it should report a MotionNotify event every time it gets called +if the pointing device has moved since the last notify. +Intermediate pointing device moves are stored in a special GetMotionEvents buffer, +because most client programs are not interested in them. +</para> +<para> +There are quite a collection of sample implementations of this routine, +one for each supported device. +</para> +</section> +<section> +<title>Telling DIX When Input is Pending</title> +<para> +In the server's dispatch loop, DIX checks to see +if there is any device input pending whenever WaitForSomething() returns. +If the check says that input is pending, DIX calls the +DDX routine ProcessInputEvents(). +</para> +<para> +This check for pending input must be very quick; a procedure call +is too slow. +The code that does the check is a hardwired IF +statement in DIX code that simply compares the values +pointed to by two pointers. +If the values are different, then it assumes that input is pending and +ProcessInputEvents() is called by DIX. +</para> +<para> +You must pass pointers to DIX to tell it what values to compare. +The following procedure +is used to set these pointers: +<blockquote><programlisting> + + void SetInputCheck(p1, p2) + long *p1, *p2; +</programlisting></blockquote> +You should call it sometime during initialization to indicate to DIX the +correct locations to check. +You should +pay special attention to the size of what they actually point to, +because the locations are assumed to be longs. +</para> +<para> +These two pointers are initialized by DIX +to point to arbitrary values that +are different. +In other words, if you forget to call this routine during initialization, +the worst thing that will happen is that +ProcessInputEvents will be called when +there are no events to process. +</para> +<para> +p1 and p2 might +point at the head and tail of some shared +memory queue. +Another use would be to have one point at a constant 0, with the +other pointing at some mask containing 1s +for each input device that has +something pending. +</para> +<para> +The DDX layer of the sample server calls SetInputCheck() +once when the +server's private internal queue is initialized. +It passes pointers to the queue's head and tail. See Xserver/mi/mieq.c. +</para> +<para> +<blockquote><programlisting> + int TimeSinceLastInputEvent() +</programlisting></blockquote> +DDX must time stamp all hardware input +events. But DIX sometimes needs to know the +time and the OS layer needs to know the time since the last hardware +input event in +order for the screen saver to work. TimeSinceLastInputEvent() returns +the this time in milliseconds. +</para> +</section> +<section> + <title>Controlling Input Devices</title> +<para> +You must write four routines to do various device-specific +things with the keyboard and pointing device. +They can have any name you wish because +you pass the procedure pointers to DIX routines. +</para> +<para> +<blockquote><programlisting> + + int pInternalDevice->valuator->GetMotionProc(pdevice, coords, start, stop, pScreen) + DeviceIntPtr pdevice; + xTimecoord * coords; + unsigned long start; + unsigned long stop; + ScreenPtr pScreen; +</programlisting></blockquote> +You write this DDX routine to fill in coords with all the motion +events that have times (32-bit count of milliseconds) between time +start and time stop. It should return the number of motion events +returned. If there is no motion events support, this routine should +do nothing and return zero. The maximum number of coords to return is +set in InitPointerDeviceStruct(), below. +</para> +<para> +When the user drags the pointing device, the cursor position +theoretically sweeps through an infinite number of points. Normally, +a client that is concerned with points other than the starting and +ending points will receive a pointer-move event only as often as the +server generates them. (Move events do not queue up; each new one +replaces the last in the queue.) A server, if desired, can implement +a scheme to save these intermediate events in a motion buffer. A +client application, like a paint program, may then request that these +events be delivered to it through the GetMotionProc routine. +</para> +<para> +<blockquote><programlisting> + + void pInternalDevice->bell->BellProc(percent, pDevice, ctrl, unknown) + int percent; + DeviceIntPtr pDevice; + pointer ctrl; + int class; +</programlisting></blockquote> +You need to write this routine to ring the bell on the keyboard. +loud is a number from 0 to 100, with 100 being the loudest. +Class is either BellFeedbackClass or KbdFeedbackClass (from XI.h). +</para> +<para> +<blockquote><programlisting> + + void pInternalDevice->somedevice->CtrlProc(device, ctrl) + DevicePtr device; + SomethingCtrl *ctrl; + +</programlisting></blockquote> +You write two versions of this procedure, one for the keyboard and one for the pointing device. +DIX calls it to inform DDX when a client has requested changes in the current +settings for the particular device. +For a keyboard, this might be the repeat threshold and rate. +For a pointing device, this might be a scaling factor (coarse or fine) for position reporting. +See input.h for the ctrl structures. +</para> +</section> +<section> + <title>Input Initialization</title> +<para> +Input initialization is a bit complicated. +It all starts with InitInput(), a routine that you write to call +AddInputDevice() twice +(once for pointing device and once for keyboard.) +</para> +<para> +When you Add the devices, a routine you supply for each device +gets called to initialize them. +Your individual initialize routines must call InitKeyboardDeviceStruct() +or InitPointerDeviceStruct(), depending upon which it is. +In other words, you indicate twice that the keyboard is the keyboard and +the pointer is the pointer. +</para> +<para> +<blockquote><programlisting> + + void InitInput(argc, argv) + int argc; + char **argv; +</programlisting></blockquote> +InitInput is a DDX routine you must write to initialize the +input subsystem in DDX. +It must call AddInputDevice() for each device that might generate events. +</para> +<para> +<blockquote><programlisting> + + DevicePtr AddInputDevice(deviceProc, autoStart) + DeviceProc deviceProc; + Bool autoStart; +</programlisting></blockquote> +AddInputDevice is a DIX routine you call to create a device object. +deviceProc is a DDX routine that is called by DIX to do various operations. +AutoStart should be TRUE for devices that need to be turned on at +initialization time with a special call, as opposed to waiting for some +client application to +turn them on. +This routine returns NULL if sufficient memory cannot be allocated to +install the device. +</para> +<para> +Note also that except for the main keyboard and pointing device, +an extension is needed to provide for a client interface to a device. +</para> +<para> +The following DIX +procedures return the specified DevicePtr. They may or may not be useful +to DDX implementors. +</para> +<para> +<blockquote><programlisting> + + DevicePtr LookupKeyboardDevice() +</programlisting></blockquote> +LookupKeyboardDevice returns pointer for current main keyboard device. +</para> +<para> +<blockquote><programlisting> + + DevicePtr LookupPointerDevice() +</programlisting></blockquote> +LookupPointerDevice returns pointer for current main pointing device. +</para> +<para> +A DeviceProc (the kind passed to AddInputDevice()) in the following form: +<blockquote><programlisting> + + Bool pInternalDevice->DeviceProc(device, action); + DeviceIntPtr device; + int action; +</programlisting></blockquote> +You must write a DeviceProc for each device. +device points to the device record. +action tells what action to take; +it will be one of these defined constants (defined in input.h): +<itemizedlist> +<listitem><para> +DEVICE_INIT - +At DEVICE_INIT time, the device should initialize itself by calling +InitPointerDeviceStruct(), InitKeyboardDeviceStruct(), or a similar +routine (see below) +and "opening" the device if necessary. +If you return a non-zero (i.e., != Success) value from the DEVICE_INIT +call, that device will be considered unavailable. If either the main keyboard +or main pointing device cannot be initialized, the DIX code will refuse +to continue booting up.</para></listitem> +<listitem><para> +DEVICE_ON - If the DeviceProc is called with DEVICE_ON, then it is +allowed to start +putting events into the client stream by calling through the ProcessInputProc +in the device.</para></listitem> +<listitem><para> +DEVICE_OFF - If the DeviceProc is called with DEVICE_OFF, no further +events from that +device should be given to the DIX layer. +The device will appear to be dead to the user.</para></listitem> +<listitem><para> +DEVICE_CLOSE - At DEVICE_CLOSE (terminate or reset) time, the device should +be totally closed down.</para></listitem> +</itemizedlist> +</para> +<para> +<blockquote><programlisting> + + void InitPointerDeviceStruct(device, map, mapLength, + GetMotionEvents, ControlProc, numMotionEvents) + DevicePtr device; + CARD8 *map; + int mapLength; + ValuatorMotionProcPtr ControlProc; + PtrCtrlProcPtr GetMotionEvents; + int numMotionEvents; +</programlisting></blockquote> +InitPointerDeviceStruct is a DIX routine you call at DEVICE_INIT time to declare +some operating routines and data structures for a pointing device. +map and mapLength are as described in the X Window +System protocol specification. +ControlProc and GetMotionEvents are DDX routines, see above. +</para> +<para> +numMotionEvents is for the motion-buffer-size for the GetMotionEvents +request. +A typical length for a motion buffer would be 100 events. +A server that does not implement this capability should set +numMotionEvents to zero. +</para> +<para> +<blockquote><programlisting> + + void InitKeyboardDeviceStruct(device, pKeySyms, pModifiers, Bell, ControlProc) + DevicePtr device; + KeySymsPtr pKeySyms; + CARD8 *pModifiers; + BellProcPtr Bell; + KbdCtrlProcPtr ControlProc; + +</programlisting></blockquote> +You call this DIX routine when a keyboard device is initialized and +its device procedure is called with +DEVICE_INIT. +The formats of the keysyms and modifier maps are defined in +Xserver/include/input.h. +They describe the layout of keys on the keyboards, and the glyphs +associated with them. ( See the next section for information on +setting up the modifier map and the keysym map.) +ControlProc and Bell are DDX routines, see above. +</para> +</section> +<section> + <title>Keyboard Mapping and Keycodes</title> +<para> +When you send a keyboard event, you send a report that a given key has +either been pressed or has been released. There must be a keycode for +each key that identifies the key; the keycode-to-key mapping can be +any mapping you desire, because you specify the mapping in a table you +set up for DIX. However, you are restricted by the protocol +specification to keycode values in the range 8 to 255 inclusive. +</para> +<para> +The keycode mapping information that you set up consists of the following: +<itemizedlist> +<listitem><para> +A minimum and maximum keycode number</para></listitem> +<listitem><para> +An array of sets of keysyms for each key, that is of length +maxkeycode - minkeycode + 1. +Each element of this array is a list of codes for symbols that are on that key. +There is no limit to the number of symbols that can be on a key.</para></listitem> +</itemizedlist> +Once the map is set up, DIX keeps and +maintains the client's changes to it. +</para> +<para> +The X protocol defines standard names to indicate the symbol(s) +printed on each keycap. (See X11/keysym.h) +</para> +<para> +Legal modifier keys must generate both up and down transitions. When +a client tries to change a modifier key (for instance, to make "A" the +"Control" key), DIX calls the following routine, which should return +TRUE if the key can be used as a modifier on the given device: +<blockquote><programlisting> + + Bool LegalModifier(key, pDev) + unsigned int key; + DevicePtr pDev; +</programlisting></blockquote> +</para> +</section> +</section> +<section> +<title>Screens</title> +<para> +Different computer graphics +displays have different capabilities. +Some are simple monochrome +frame buffers that are just lying +there in memory, waiting to be written into. +Others are color displays with many bits per pixel using some color lookup table. +Still others have high-speed graphic processors that prefer to do all of the work +themselves, +including maintaining their own high-level, graphic data structures. +</para> +<section> + <title>Screen Hardware Requirements</title> +<para> +The only requirement on screens is that you be able to both read +and write locations in the frame buffer. +All screens must have a depth of 32 or less (unless you use +an X extension to allow a greater depth). +All screens must fit into one of the classes listed in the section +in this document on Visuals and Depths. +</para> +<para> +X uses the pixel as its fundamental unit of distance on the screen. +Therefore, most programs will measure everything in pixels.</para> +<para> +The sample server assumes square pixels. +Serious WYSIWYG (what you see is what you get) applications for +publishing and drawing programs will adjust for +different screen resolutions automatically. +Considerable work +is involved in compensating for non-square pixels (a bit in the DDX +code for the sample server but quite a bit in the client applications).</para> +</section> +<section> + <title>Data Structures</title> +<para> +X supports multiple screens that are connected to the same +server. Therefore, all the per-screen information is bundled into one data +structure of attributes and procedures, which is the ScreenRec (see +Xserver/include/scrnintstr.h). +The procedure entry points in a ScreenRec operate on +regions, colormaps, cursors, and fonts, because these resources +can differ in format from one screen to another.</para> +<para> +Windows are areas on the screen that can be drawn into by graphic +routines. "Pixmaps" are off-screen graphic areas that can be drawn +into. They are both considered drawables and are described in the +section on Drawables. All graphic operations work on drawables, and +operations are available to copy patches from one drawable to another.</para> +<para> +The pixel image data in all drawables is in a format that is private +to DDX. In fact, each instance of a drawable is associated with a +given screen. Presumably, the pixel image data for pixmaps is chosen +to be conveniently understood by the hardware. All screens in a +single server must be able to handle all pixmaps depths declared in +the connection setup information.</para> +<para> +Pixmap images are transferred to the server in one of two ways: +XYPixmap or ZPimap. XYPixmaps are a series of bitmaps, one for each +bit plane of the image, using the bitmap padding rules from the +connection setup. ZPixmaps are a series of bits, nibbles, bytes or +words, one for each pixel, using the format rules (padding and so on) +for the appropriate depth.</para> +<para> +All screens in a given server must agree on a set of pixmap image +formats (PixmapFormat) to support (depth, number of bits per pixel, +etc.).</para> +<para> +There is no color interpretation of bits in the pixmap. Pixmaps +do not contain pixel values. The interpretation is made only when +the bits are transferred onto the screen.</para> +<para> +The screenInfo structure (in scrnintstr.h) is a global data structure +that has a pointer to an array of ScreenRecs, one for each screen on +the server. (These constitute the one and only description of each +screen in the server.) Each screen has an identifying index (0, 1, 2, ...). +In addition, the screenInfo struct contains global server-wide +details, such as the bit- and byte- order in all bit images, and the +list of pixmap image formats that are supported. The X protocol +insists that these must be the same for all screens on the server.</para> +</section> +<section> + <title>Output Initialization</title> +<para> +<blockquote><programlisting> + + InitOutput(pScreenInfo, argc, argv) + ScreenInfo *pScreenInfo; + int argc; + char **argv; +</programlisting></blockquote> +Upon initialization, your DDX routine InitOutput() is called by DIX. +It is passed a pointer to screenInfo to initialize. It is also passed +the argc and argv from main() for your server for the command-line +arguments. These arguments may indicate what or how many screen +device(s) to use or in what way to use them. For instance, your +server command line may allow a "-D" flag followed by the name of the +screen device to use.</para> +<para> +Your InitOutput() routine should initialize each screen you wish to +use by calling AddScreen(), and then it should initialize the pixmap +formats that you support by storing values directly into the +screenInfo data structure. You should also set certain +implementation-dependent numbers and procedures in your screenInfo, +which determines the pixmap and scanline padding rules for all screens +in the server.</para> +<para> +<blockquote><programlisting> + + int AddScreen(scrInitProc, argc, argv) + Bool (*scrInitProc)(); + int argc; + char **argv; +</programlisting></blockquote> +You should call AddScreen(), a DIX procedure, in InitOutput() once for +each screen to add it to the screenInfo database. The first argument +is an initialization procedure for the screen that you supply. The +second and third are the argc and argv from main(). It returns the +screen number of the screen installed, or -1 if there is either +insufficient memory to add the screen, or (*scrInitProc) returned +FALSE.</para> +<para> +The scrInitProc should be of the following form: +<blockquote><programlisting> + + Bool scrInitProc(iScreen, pScreen, argc, argv) + int iScreen; + ScreenPtr pScreen; + int argc; + char **argv; +</programlisting></blockquote> +iScreen is the index for this screen; 0 for the first one initialized, +1 for the second, etc. pScreen is the pointer to the screen's new +ScreenRec. argc and argv are as before. Your screen initialize +procedure should return TRUE upon success or FALSE if the screen +cannot be initialized (for instance, if the screen hardware does not +exist on this machine).</para> +<para> +This procedure must determine what actual device it is supposed to initialize. +If you have a different procedure for each screen, then it is no problem. +If you have the same procedure for multiple screens, it may have trouble +figuring out which screen to initialize each time around, especially if +InitOutput() does not initialize all of the screens. +It is probably easiest to have one procedure for each screen.</para> +<para> +The initialization procedure should fill in all the screen procedures +for that screen (windowing functions, region functions, etc.) and certain +screen attributes for that screen.</para> +</section> +<section> + <title>Region Routines in the ScreenRec</title> +<para> +A region is a dynamically allocated data structure that describes an +irregularly shaped piece of real estate in XY pixel space. You can +think of it as a set of pixels on the screen to be operated upon with +set operations such as AND and OR.</para> +<para> +A region is frequently implemented as a list of rectangles or bitmaps +that enclose the selected pixels. Region operators control the +"clipping policy," or the operations that work on regions. (The +sample server uses YX-banded rectangles. Unless you have something +already implemented for your graphics system, you should keep that +implementation.) The procedure pointers to the region operators are +located in the ScreenRec data structure. The definition of a region +can be found in the file Xserver/include/regionstr.h. The region code +is found in Xserver/mi/miregion.c. DDX implementations using other +region formats will need to supply different versions of the region +operators.</para> +<para> +Since the list of rectangles is unbounded in size, part of the region +data structure is usually a large, dynamically allocated chunk of +memory. As your region operators calculate logical combinations of +regions, these blocks may need to be reallocated by your region +software. For instance, in the sample server, a RegionRec has some +header information and a pointer to a dynamically allocated rectangle +list. Periodically, the rectangle list needs to be expanded with +Xrealloc(), whereupon the new pointer is remembered in the RegionRec.</para> +<para> +Most of the region operations come in two forms: a function pointer in +the Screen structure, and a macro. The server can be compiled so that +the macros make direct calls to the appropriate functions (instead of +indirecting through a screen function pointer), or it can be compiled +so that the macros are identical to the function pointer forms. +Making direct calls is faster on many architectures.</para> +<para> +<blockquote><programlisting> + + RegionPtr pScreen->RegionCreate( rect, size) + BoxPtr rect; + int size; + + macro: RegionPtr RegionCreate(rect, size) + +</programlisting></blockquote> +RegionCreate creates a region that describes ONE rectangle. The +caller can avoid unnecessary reallocation and copying by declaring the +probable maximum number of rectangles that this region will need to +describe itself. Your region routines, though, cannot fail just +because the region grows beyond this size. The caller of this routine +can pass almost anything as the size; the value is merely a good guess +as to the maximum size until it is proven wrong by subsequent use. +Your region procedures are then on their own in estimating how big the +region will get. Your implementation might ignore size, if +applicable.</para> +<para> +<blockquote><programlisting> + + void pScreen->RegionInit (pRegion, rect, size) + RegionPtr pRegion; + BoxPtr rect; + int size; + + macro: RegionInit(pRegion, rect, size) + +</programlisting></blockquote> +Given an existing raw region structure (such as an local variable), this +routine fills in the appropriate fields to make this region as usable as +one returned from RegionCreate. This avoids the additional dynamic memory +allocation overhead for the region structure itself. +</para> +<para> +<blockquote><programlisting> + + Bool pScreen->RegionCopy(dstrgn, srcrgn) + RegionPtr dstrgn, srcrgn; + + macro: Bool RegionCopy(dstrgn, srcrgn) + +</programlisting></blockquote> +RegionCopy copies the description of one region, srcrgn, to another +already-created region, +dstrgn; returning TRUE if the copy succeeded, and FALSE otherwise.</para> +<para> +<blockquote><programlisting> + + void pScreen->RegionDestroy( pRegion) + RegionPtr pRegion; + + macro: RegionDestroy(pRegion) + +</programlisting></blockquote> +RegionDestroy destroys a region and frees all allocated memory.</para> +<para> +<blockquote><programlisting> + + void pScreen->RegionUninit (pRegion) + RegionPtr pRegion; + + macro: RegionUninit(pRegion) + +</programlisting></blockquote> +Frees everything except the region structure itself, useful when the +region was originally passed to RegionInit instead of received from +RegionCreate. When this call returns, pRegion must not be reused until +it has been RegionInit'ed again.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->Intersect(newReg, reg1, reg2) + RegionPtr newReg, reg1, reg2; + + macro: Bool RegionIntersect(newReg, reg1, reg2) + + Bool pScreen->Union(newReg, reg1, reg2) + RegionPtr newReg, reg1, reg2; + + macro: Bool RegionUnion(newReg, reg1, reg2) + + Bool pScreen->Subtract(newReg, regMinuend, regSubtrahend) + RegionPtr newReg, regMinuend, regSubtrahend; + + macro: Bool RegionUnion(newReg, regMinuend, regSubtrahend) + + Bool pScreen->Inverse(newReg, pReg, pBox) + RegionPtr newReg, pReg; + BoxPtr pBox; + + macro: Bool RegionInverse(newReg, pReg, pBox) + +</programlisting></blockquote> +The above four calls all do basic logical operations on regions. They +set the new region (which already exists) to describe the logical +intersection, union, set difference, or inverse of the region(s) that +were passed in. Your routines must be able to handle a situation +where the newReg is the same region as one of the other region +arguments.</para> +<para> +The subtract function removes the Subtrahend from the Minuend and +puts the result in newReg.</para> +<para> +The inverse function returns a region that is the pBox minus the +region passed in. (A true "inverse" would make a region that extends +to infinity in all directions but has holes in the middle.) It is +undefined for situations where the region extends beyond the box.</para> +<para> +Each routine must return the value TRUE for success.</para> +<para> +<blockquote><programlisting> + + void pScreen->RegionReset(pRegion, pBox) + RegionPtr pRegion; + BoxPtr pBox; + + macro: RegionReset(pRegion, pBox) + +</programlisting></blockquote> +RegionReset sets the region to describe +one rectangle and reallocates it to a size of one rectangle, if applicable.</para> +<para> +<blockquote><programlisting> + + void pScreen->TranslateRegion(pRegion, x, y) + RegionPtr pRegion; + int x, y; + + macro: RegionTranslate(pRegion, x, y) + +</programlisting></blockquote> +TranslateRegion simply moves a region +x in the x direction and +y in the y +direction.</para> +<para> +<blockquote><programlisting> + + int pScreen->RectIn(pRegion, pBox) + RegionPtr pRegion; + BoxPtr pBox; + + macro: int RegionContainsRect(pRegion, pBox) + +</programlisting></blockquote> +RectIn returns one of the defined constants rgnIN, rgnOUT, or rgnPART, +depending upon whether the box is entirely inside the region, entirely +outside of the region, or partly in and partly out of the region. +These constants are defined in Xserver/include/region.h.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->PointInRegion(pRegion, x, y, pBox) + RegionPtr pRegion; + int x, y; + BoxPtr pBox; + + macro: Bool RegionContainsPoint(pRegion, x, y, pBox) + +</programlisting></blockquote> +PointInRegion returns true if the point x, y is in the region. In +addition, it fills the rectangle pBox with coordinates of a rectangle +that is entirely inside of pRegion and encloses the point. In the mi +implementation, it is the largest such rectangle. (Due to the sample +server implementation, this comes cheaply.)</para> +<para> +This routine used by DIX when tracking the pointing device and +deciding whether to report mouse events or change the cursor. For +instance, DIX needs to change the cursor when it moves from one window +to another. Due to overlapping windows, the shape to check may be +irregular. A PointInRegion() call for every pointing device movement +may be too expensive. The pBox is a kind of wake-up box; DIX need not +call PointInRegion() again until the cursor wanders outside of the +returned box.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->RegionNotEmpty(pRegion) + RegionPtr pRegion; + + macro: Bool RegionNotEmpty(pRegion) + +</programlisting></blockquote> +RegionNotEmpty is a boolean function that returns +true or false depending upon whether the region encloses any pixels.</para> +<para> +<blockquote><programlisting> + + void pScreen->RegionEmpty(pRegion) + RegionPtr pRegion; + + macro: RegionEmpty(pRegion) + +</programlisting></blockquote> +RegionEmpty sets the region to be empty.</para> +<para> +<blockquote><programlisting> + + BoxPtr pScreen->RegionExtents(pRegion) + RegionPtr pRegion; + + macro: RegionExtents(pRegion) + +</programlisting></blockquote> +RegionExtents returns a rectangle that is the smallest +possible superset of the entire region. +The caller will not modify this rectangle, so it can be the one +in your region struct.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->RegionAppend (pDstRgn, pRegion) + RegionPtr pDstRgn; + RegionPtr pRegion; + + macro: Bool RegionAppend(pDstRgn, pRegion) + + Bool pScreen->RegionValidate (pRegion, pOverlap) + RegionPtr pRegion; + Bool *pOverlap; + + macro: Bool RegionValidate(pRegion, pOverlap) + +</programlisting></blockquote> +These functions provide an optimization for clip list generation and +must be used in conjunction. The combined effect is to produce the +union of a collection of regions, by using RegionAppend several times, +and finally calling RegionValidate which takes the intermediate +representation (which needn't be a valid region) and produces the +desired union. pOverlap is set to TRUE if any of the original +regions overlap; FALSE otherwise.</para> +<para> +<blockquote><programlisting> + + RegionPtr pScreen->BitmapToRegion (pPixmap) + PixmapPtr pPixmap; + + macro: RegionPtr BitmapToRegion(pScreen, pPixmap) + +</programlisting></blockquote> +Given a depth-1 pixmap, this routine must create a valid region which +includes all the areas of the pixmap filled with 1's and excludes the +areas filled with 0's. This routine returns NULL if out of memory.</para> +<para> +<blockquote><programlisting> + + RegionPtr pScreen->RectsToRegion (nrects, pRects, ordering) + int nrects; + xRectangle *pRects; + int ordering; + + macro: RegionPtr RegionFromRects(nrects, pRects, ordering) + +</programlisting></blockquote> +Given a client-supplied list of rectangles, produces a region which includes +the union of all the rectangles. Ordering may be used as a hint which +describes how the rectangles are sorted. As the hint is provided by a +client, it must not be required to be correct, but the results when it is +not correct are not defined (core dump is not an option here).</para> +<para> +<blockquote><programlisting> + + void pScreen->SendGraphicsExpose(client,pRegion,drawable,major,minor) + ClientPtr client; + RegionPtr pRegion; + XID drawable; + int major; + int minor; + +</programlisting></blockquote> +SendGraphicsExpose dispatches a list of GraphicsExposure events which +span the region to the specified client. If the region is empty, or +a NULL pointer, a NoExpose event is sent instead.</para> +</section> +<section> + <title>Cursor Routines for a Screen</title> +<para> +A cursor is the visual form tied to the pointing device. The default +cursor is an "X" shape, but the cursor can have any shape. When a +client creates a window, it declares what shape the cursor will be +when it strays into that window on the screen.</para> +<para> +For each possible shape the cursor assumes, there is a CursorRec data +structure. This data structure contains a pointer to a CursorBits +data structure which contains a bitmap for the image of the cursor and +a bitmap for a mask behind the cursor, in addition, the CursorRec data +structure contains foreground and background colors for the cursor. +The CursorBits data structure is shared among multiple CursorRec +structures which use the same font and glyph to describe both source +and mask. The cursor image is applied to the screen by applying the +mask first, clearing 1 bits in its form to the background color, and +then overwriting on the source image, in the foreground color. (One +bits of the source image that fall on top of zero bits of the mask +image are undefined.) This way, a cursor can have transparent parts, +and opaque parts in two colors. X allows any cursor size, but some +hardware cursor schemes allow a maximum of N pixels by M pixels. +Therefore, you are allowed to transform the cursor to a smaller size, +but be sure to include the hot-spot.</para> +<para> +CursorBits in Xserver/include/cursorstr.h is a device-independent +structure containing a device-independent representation of the bits +for the source and mask. (This is possible because the bitmap +representation is the same for all screens.)</para> +<para> +When a cursor is created, it is "realized" for each screen. At +realization time, each screen has the chance to convert the bits into +some other representation that may be more convenient (for instance, +putting the cursor into off-screen memory) and set up its +device-private area in either the CursorRec data structure or +CursorBits data structure as appropriate to possibly point to whatever +data structures are needed. It is more memory-conservative to share +realizations by using the CursorBits private field, but this makes the +assumption that the realization is independent of the colors used +(which is typically true). For instance, the following are the device +private entries for a particular screen and cursor: +<blockquote><programlisting> + + pCursor->devPriv[pScreen->myNum] + pCursor->bits->devPriv[pScreen->myNum] + +</programlisting></blockquote> +This is done because the change from one cursor shape to another must +be fast and responsive; the cursor image should be able to flutter as +fast as the user moves it across the screen.</para> +<para> +You must implement the following routines for your hardware: +<blockquote><programlisting> + + Bool pScreen->RealizeCursor( pScr, pCurs) + ScreenPtr pScr; + CursorPtr pCurs; + + Bool pScreen->UnrealizeCursor( pScr, pCurs) + ScreenPtr pScr; + CursorPtr pCurs; + +</programlisting></blockquote> +</para> +<para> +RealizeCursor and UnrealizeCursor should realize (allocate and +calculate all data needed) and unrealize (free the dynamically +allocated data) a given cursor when DIX needs them. They are called +whenever a device-independent cursor is created or destroyed. The +source and mask bits pointed to by fields in pCurs are undefined for +bits beyond the right edge of the cursor. This is so because the bits +are in Bitmap format, which may have pad bits on the right edge. You +should inhibit UnrealizeCursor() if the cursor is currently in use; +this happens when the system is reset.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->DisplayCursor( pScr, pCurs) + ScreenPtr pScr; + CursorPtr pCurs; + +</programlisting></blockquote> +DisplayCursor should change the cursor on the given screen to the one +passed in. It is called by DIX when the user moves the pointing +device into a different window with a different cursor. The hotspot +in the cursor should be aligned with the current cursor position.</para> +<para> +<blockquote><programlisting> + + void pScreen->RecolorCursor( pScr, pCurs, displayed) + ScreenPtr pScr; + CursorPtr pCurs; + Bool displayed; +</programlisting></blockquote> +RecolorCursor notifies DDX that the colors in pCurs have changed and +indicates whether this is the cursor currently being displayed. If it +is, the cursor hardware state may have to be updated. Whether +displayed or not, state created at RealizeCursor time may have to be +updated. A generic version, miRecolorCursor, may be used that +does an unrealize, a realize, and possibly a display (in micursor.c); +however this constrains UnrealizeCursor and RealizeCursor to always return +TRUE as no error indication is returned here.</para> +<para> +<blockquote><programlisting> + + void pScreen->ConstrainCursor( pScr, pBox) + ScreenPtr pScr; + BoxPtr pBox; + +</programlisting></blockquote> +ConstrainCursor should cause the cursor to restrict its motion to the +rectangle pBox. DIX code is capable of enforcing this constraint by +forcefully moving the cursor if it strays out of the rectangle, but +ConstrainCursor offers a way to send a hint to the driver or hardware +if such support is available. This can prevent the cursor from +wandering out of the box, then jumping back, as DIX forces it back.</para> +<para> +<blockquote><programlisting> + + void pScreen->PointerNonInterestBox( pScr, pBox) + ScreenPtr pScr; + BoxPtr pBox; + +</programlisting></blockquote> +PointerNonInterestBox is DIX's way of telling the pointing device code +not to report motion events while the cursor is inside a given +rectangle on the given screen. It is optional and, if not +implemented, it should do nothing. This routine is called only when +the client has declared that it is not interested in motion events in +a given window. The rectangle you get may be a subset of that window. +It saves DIX code the time required to discard uninteresting mouse +motion events. This is only a hint, which may speed performance. +Nothing in DIX currently calls PointerNonInterestBox.</para> +<para> +<blockquote><programlisting> + + void pScreen->CursorLimits( pScr, pCurs, pHotBox, pTopLeftBox) + ScreenPtr pScr; + CursorPtr pCurs; + BoxPtr pHotBox; + BoxPtr pTopLeftBox; /* return value */ + +</programlisting></blockquote> +CursorLimits should calculate the box that the cursor hot spot is +physically capable of moving within, as a function of the screen pScr, +the device-independent cursor pCurs, and a box that DIX hypothetically +would want the hot spot confined within, pHotBox. This routine is for +informing DIX only; it alters no state within DDX.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->SetCursorPosition( pScr, newx, newy, generateEvent) + ScreenPtr pScr; + int newx; + int newy; + Bool generateEvent; + +</programlisting></blockquote> +SetCursorPosition should artificially move the cursor as though the +user had jerked the pointing device very quickly. This is called in +response to the WarpPointer request from the client, and at other +times. If generateEvent is True, the device should decide whether or +not to call ProcessInputEvents() and then it must call +DevicePtr->processInputProc. Its effects are, of course, limited in +value for absolute pointing devices such as a tablet.</para> +<para> +<blockquote><programlisting> + + void NewCurrentScreen(newScreen, x, y) + ScreenPtr newScreen; + int x,y; + +</programlisting></blockquote> +If your ddx provides some mechanism for the user to magically move the +pointer between multiple screens, you need to inform DIX when this +occurs. You should call NewCurrentScreen to accomplish this, specifying +the new screen and the new x and y coordinates of the pointer on that screen.</para> +</section> +<section> + <title>Visuals, Depths and Pixmap Formats for Screens</title> +<para> +The "depth" of a image is the number of bits that are used per pixel to display it.</para> +<para> +The "bits per pixel" of a pixmap image that is sent over the client +byte stream is a number that is either 4, 8, 16, 24 or 32. It is the +number of bits used per pixel in Z format. For instance, a pixmap +image that has a depth of six is best sent in Z format as 8 bits per +pixel.</para> +<para> +A "pixmap image format" or a "pixmap format" is a description of the +format of a pixmap image as it is sent over the byte stream. For each +depth available on a server, there is one and only one pixmap format. +This pixmap image format gives the bits per pixel and the scanline +padding unit. (For instance, are pixel rows padded to bytes, 16-bit +words, or 32-bit words?)</para> +<para> +For each screen, you must decide upon what depth(s) it supports. You +should only count the number of bits used for the actual image. Some +displays store additional bits to indicate what window this pixel is +in, how close this object is to a viewer, transparency, and other +data; do not count these bits.</para> +<para> +A "display class" tells whether the display is monochrome or color, +whether there is a lookup table, and how the lookup table works.</para> +<para> +A "visual" is a combination of depth, display class, and a description +of how the pixel values result in a color on the screen. Each visual +has a set of masks and offsets that are used to separate a pixel value +into its red, green, and blue components and a count of the number of +colormap entries. Some of these fields are only meaningful when the +class dictates so. Each visual also has a screen ID telling which +screen it is usable on. Note that the depth does not imply the number +of map_entries; for instance, a display can have 8 bits per pixel but +only 254 colormap entries for use by applications (the other two being +reserved by hardware for the cursor).</para> +<para> +Each visual is identified by a 32-bit visual ID which the client uses +to choose what visual is desired on a given window. Clients can be +using more than one visual on the same screen at the same time.</para> +<para> +The class of a display describes how this translation takes place. +There are three ways to do the translation. +<itemizedlist> +<listitem><para> +Pseudo - The pixel value, as a whole, is looked up +in a table of length map_entries to +determine the color to display.</para></listitem> +<listitem><para> +True - The +pixel value is broken up into red, green, and blue fields, each of which +are looked up in separate red, green, and blue lookup tables, +each of length map_entries.</para></listitem> +<listitem><para> +Gray - The pixel value is looked up in a table of length map_entries to +determine a gray level to display.</para></listitem> +</itemizedlist> +</para> +<para> +In addition, the lookup table can be static (resulting colors are fixed for each +pixel value) +or dynamic (lookup entries are under control of the client program). +This leads to a total of six classes: +<itemizedlist> +<listitem><para> +Static Gray - The pixel value (of however many bits) determines directly the +level of gray +that the pixel assumes.</para></listitem> +<listitem><para> +Gray Scale - The pixel value is fed through a lookup table to arrive at the level +of gray to display +for the given pixel.</para></listitem> +<listitem><para> +Static Color - The pixel value is fed through a fixed lookup table that yields the +color to display +for that pixel.</para></listitem> +<listitem><para> +PseudoColor - The whole pixel value is fed through a programmable lookup +table that has one +color (including red, green, and blue intensities) for each possible pixel value, +and that color is displayed.</para></listitem> +<listitem><para> +True Color - Each pixel value consists of one or more bits +that directly determine each primary color intensity after being fed through +a fixed table.</para></listitem> +<listitem><para> +Direct Color - Each pixel value consists of one or more bits for each primary color. +Each primary color value is individually looked up in a table for that primary +color, yielding +an intensity for that primary color. +For each pixel, the red value is looked up in the +red table, the green value in the green table, and +the blue value in the blue table.</para></listitem> +</itemizedlist> +</para> +<para> +Here are some examples: +<itemizedlist> +<listitem><para> +A simple monochrome 1 bit per pixel display is Static Gray.</para></listitem> +<listitem><para> +A display that has 2 bits per pixel for a choice +between the colors of black, white, green and violet is Static Color.</para></listitem> +<listitem><para> +A display that has three bits per pixel, where +each bit turns on or off one of the red, green or +blue guns, is in the True Color class.</para></listitem> +<listitem><para> +If you take the last example and scramble the +correspondence between pixel values and colors +it becomes a Static Color display.</para></listitem> +</itemizedlist></para> +<para> +A display has 8 bits per pixel. The 8 bits select one entry out of 256 entries +in a lookup table, each entry consisting of 24 bits (8bits each for red, green, +and blue). +The display can show any 256 of 16 million colors on the screen at once. +This is a pseudocolor display. +The client application gets to fill the lookup table in this class of display.</para> +<para> +Imagine the same hardware from the last example. +Your server software allows the user, on the +command line that starts up the server +program, +to fill the lookup table to his liking once and for all. +From then on, the server software would not change the lookup table +until it exits. +For instance, the default might be a lookup table with a reasonable sample of +colors from throughout the color space. +But the user could specify that the table be filled with 256 steps of gray scale +because he knew ahead of time he would be manipulating a lot of black-and-white +scanned photographs +and not very many color things. +Clients would be presented with this unchangeable lookup table. +Although the hardware qualifies as a PseudoColor display, +the facade presented to the X client is that this is a Static Color display.</para> +<para> +You have to decide what kind of display you have or want +to pretend you have. +When you initialize the screen(s), this class value must be set in the +VisualRec data structure along with other display characteristics like the +depth and other numbers.</para> +<para> +The allowable DepthRec's and VisualRec's are pointed to by fields in the ScreenRec. +These are set up when InitOutput() is called; you should Xalloc() appropriate blocks +or use static variables initialized to the correct values.</para> +</section> +<section> +<title>Colormaps for Screens</title> +<para> +A colormap is a device-independent +mapping between pixel values and colors displayed on the screen.</para> +<para> +Different windows on the same screen can have different +colormaps at the same time. +At any given time, the most recently installed +colormap(s) will be in use in the server +so that its (their) windows' colors will be guaranteed to be correct. +Other windows may be off-color. +Although this may seem to be chaotic, in practice most clients +use the default colormap for the screen.</para> +<para> +The default colormap for a screen is initialized when the screen is initialized. +It always remains in existence and is not owned by any regular client. It +is owned by client 0 (the server itself). +Many clients will simply use this default colormap for their drawing. +Depending upon the class of the screen, the entries in this colormap may +be modifiable by client applications.</para> +</section> +<section> + <title>Colormap Routines</title> +<para> +You need to implement the following routines to handle the device-dependent +aspects of color maps. You will end up placing pointers to these procedures +in your ScreenRec data structure(s). The sample server implementations of +many of these routines are in fbcmap.c.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->CreateColormap(pColormap) + ColormapPtr pColormap; + +</programlisting></blockquote> +This routine is called by the DIX CreateColormap routine after it has allocated +all the data for the new colormap and just before it returns to the dispatcher. +It is the DDX layer's chance to initialize the colormap, particularly if it is +a static map. See the following +section for more details on initializing colormaps. +The routine returns FALSE if creation failed, such as due to memory +limitations. +Notice that the colormap has a devPriv field from which you can hang any +colormap specific storage you need. Since each colormap might need special +information, we attached the field to the colormap and not the visual.</para> +<para> +<blockquote><programlisting> + + void pScreen->DestroyColormap(pColormap) + ColormapPtr pColormap; + +</programlisting></blockquote> +This routine is called by the DIX FreeColormap routine after it has uninstalled +the colormap and notified all interested parties, and before it has freed +any of the colormap storage. +It is the DDX layer's chance to free any data it added to the colormap.</para> +<para> +<blockquote><programlisting> + + void pScreen->InstallColormap(pColormap) + ColormapPtr pColormap; + +</programlisting></blockquote> +InstallColormap should +fill a lookup table on the screen with which the colormap is associated with +the colors in pColormap. +If there is only one hardware lookup table for the screen, then all colors on +the screen may change simultaneously.</para> +<para> +In the more general case of multiple hardware lookup tables, +this may cause some other colormap to be +uninstalled, meaning that windows that subscribed to the colormap +that was uninstalled may end up being off-color. +See the note, below, about uninstalling maps.</para> +<para> +<blockquote><programlisting> + + void pScreen->UninstallColormap(pColormap) + ColormapPtr pColormap; + +</programlisting></blockquote> +UninstallColormap should +remove pColormap from screen pColormap->pScreen. +Some other map, such as the default map if possible, +should be installed in place of pColormap if applicable. +If +pColormap is the default map, do nothing. +If any client has requested ColormapNotify events, the DDX layer must notify the client. +(The routine WalkTree() is +be used to find such windows. The DIX routines TellNoMap(), +TellNewMap() and TellGainedMap() are provided to be used as +the procedure parameter to WalkTree. These procedures are in +Xserver/dix/colormap.c.)</para> +<para> +<blockquote><programlisting> + + int pScreen->ListInstalledColormaps(pScreen, pCmapList) + ScreenPtr pScreen; + XID *pCmapList; + + +</programlisting></blockquote> +ListInstalledColormaps fills the pCmapList in with the resource ids +of the installed maps and returns a count of installed maps. +pCmapList will point to an array of size MaxInstalledMaps that was allocated +by the caller.</para> +<para> +<blockquote><programlisting> + + void pScreen->StoreColors (pmap, ndef, pdefs) + ColormapPtr pmap; + int ndef; + xColorItem *pdefs; + +</programlisting></blockquote> +StoreColors changes some of the entries in the colormap pmap. +The number of entries to change are ndef, and pdefs points to the information +describing what to change. +Note that partial changes of entries in the colormap are allowed. +Only the colors +indicated in the flags field of each xColorItem need to be changed. +However, all three color fields will be sent with the proper value for the +benefit of screens that may not be able to set part of a colormap value. +If the screen is a static class, this routine does nothing. +The structure of colormap entries is nontrivial; see colormapst.h +and the definition of xColorItem in Xproto.h for +more details.</para> +<para> +<blockquote><programlisting> + + void pScreen->ResolveColor(pRed, pGreen, pBlue, pVisual) + unsigned short *pRed, *pGreen, *pBlue; + VisualPtr pVisual; + + +</programlisting></blockquote> +Given a requested color, ResolveColor returns the nearest color that this hardware is +capable of displaying on this visual. +In other words, this rounds off each value, in place, to the number of bits +per primary color that your screen can use. +Remember that each screen has one of these routines. +The level of roundoff should be what you would expect from the value +you put in the bits_per_rgb field of the pVisual.</para> +<para> +Each value is an unsigned value ranging from 0 to 65535. +The bits least likely to be used are the lowest ones.</para> +<para> +For example, if you had a pseudocolor display +with any number of bits per pixel +that had a lookup table supplying 6 bits for each color gun +(a total of 256K different colors), you would +round off each value to 6 bits. Please don't simply truncate these values +to the upper 6 bits, scale the result so that the maximum value seen +by the client will be 65535 for each primary. This makes color values +more portable between different depth displays (a 6-bit truncated white +will not look white on an 8-bit display).</para> +<section> +<title>Initializing a Colormap</title> +<para> +When a client requests a new colormap and when the server creates the default +colormap, the procedure CreateColormap in the DIX layer is invoked. +That procedure allocates memory for the colormap and related storage such as +the lists of which client owns which pixels. +It then sets a bit, BeingCreated, in the flags field of the ColormapRec +and calls the DDX layer's CreateColormap routine. +This is your chance to initialize the colormap. +If the colormap is static, which you can tell by looking at the class field, +you will want to fill in each color cell to match the hardwares notion of the +color for that pixel. +If the colormap is the default for the screen, which you can tell by looking +at the IsDefault bit in the flags field, you should allocate BlackPixel +and WhitePixel to match the values you set in the pScreen structure. +(Of course, you picked those values to begin with.)</para> +<para> +You can also wait and use AllocColor() to allocate blackPixel +and whitePixel after the default colormap has been created. +If the default colormap is static and you initialized it in +pScreen->CreateColormap, then use can use AllocColor afterwards +to choose pixel values with the closest rgb values to those +desired for blackPixel and whitePixel. +If the default colormap is dynamic and uninitialized, then +the rgb values you request will be obeyed, and AllocColor will +again choose pixel values for you. +These pixel values can then be stored into the screen.</para> +<para> +There are two ways to fill in the colormap. +The simplest way is to use the DIX function AllocColor. +<blockquote><programlisting> + +int AllocColor (pmap, pred, pgreen, pblue, pPix, client) + ColormapPtr pmap; + unsigned short *pred, *pgreen, *pblue; + Pixel *pPix; + int client; + +</programlisting></blockquote> +This takes three pointers to 16 bit color values and a pointer to a suggested +pixel value. The pixel value is either an index into one colormap or a +combination of three indices depending on the type of pmap. +If your colormap starts out empty, and you don't deliberately pick the same +value twice, you will always get your suggested pixel. +The truly nervous could check that the value returned in *pPix is the one +AllocColor was called with. +If you don't care which pixel is used, or would like them sequentially +allocated from entry 0, set *pPix to 0. This will find the first free +pixel and use that.</para> +<para> +AllocColor will take care of all the bookkeeping and will +call StoreColors to get the colormap rgb values initialized. +The hardware colormap will be changed whenever this colormap +is installed.</para> +<para> +If for some reason AllocColor doesn't do what you want, you can do your +own bookkeeping and call StoreColors yourself. This is much more difficult +and shouldn't be necessary for most devices.</para> +</section> +</section> +<section> + <title>Fonts for Screens</title> +<para> +A font is a set of bitmaps that depict the symbols in a character set. +Each font is for only one typeface in a given size, in other words, +just one bitmap for each character. Parallel fonts may be available +in a variety of sizes and variations, including "bold" and "italic." +X supports fonts for 8-bit and 16-bit character codes (for oriental +languages that have more than 256 characters in the font). Glyphs are +bitmaps for individual characters.</para> +<para> +The source comes with some useful font files in an ASCII, plain-text +format that should be comprehensible on a wide variety of operating +systems. The text format, referred to as BDF, is a slight extension +of the current Adobe 2.1 Bitmap Distribution Format (Adobe Systems, +Inc.).</para> +<para> +A short paper in PostScript format is included with the sample server +that defines BDF. It includes helpful pictures, which is why it is +done in PostScript and is not included in this document.</para> +<para> +Your implementation should include some sort of font compiler to read +these files and generate binary files that are directly usable by your +server implementation. The sample server comes with the source for a +font compiler.</para> +<para> +It is important the font properties contained in the BDF files are +preserved across any font compilation. In particular, copyright +information cannot be casually tossed aside without legal +ramifications. Other properties will be important to some +sophisticated applications.</para> +<para> +All clients get font information from the server. Therefore, your +server can support any fonts it wants to. It should probably support +at least the fonts supplied with the X11 tape. In principle, you can +convert fonts from other sources or dream up your own fonts for use on +your server.</para> +<section> +<title>Portable Compiled Format</title> +<para> +A font compiler is supplied with the sample server. It has +compile-time switches to convert the BDF files into a portable binary +form, called Portable Compiled Format or PCF. This allows for an +arbitrary data format inside the file, and by describing the details +of the format in the header of the file, any PCF file can be read by +any PCF reading client. By selecting the format which matches the +required internal format for your renderer, the PCF reader can avoid +reformatting the data each time it is read in. The font compiler +should be quite portable.</para> +<para> +The fonts included with the tape are stored in fonts/bdf. The +font compiler is found in fonts/tools/bdftopcf.</para> +</section> +<section> + <title>Font Realization</title> +<para> +Each screen configured into the server +has an opportunity at font-load time +to "realize" a font into some internal format if necessary. +This happens every time the font is loaded into memory.</para> +<para> +A font (FontRec in Xserver/include/dixfontstr.h) is +a device-independent structure containing a device-independent +representation of the font. When a font is created, it is "realized" +for each screen. At this point, the screen has the chance to convert +the font into some other format. The DDX layer can also put information +in the devPrivate storage.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->RealizeFont(pScr, pFont) + ScreenPtr pScr; + FontPtr pFont; + + Bool pScreen->UnrealizeFont(pScr, pFont) + ScreenPtr pScr; + FontPtr pFont; + +</programlisting></blockquote> +RealizeFont and UnrealizeFont should calculate and allocate these extra data structures and +dispose of them when no longer needed. +These are called in response to OpenFont and CloseFont requests from +the client. +The sample server implementation is in fbscreen.c (which does very little).</para> +</section> +</section> +<section> + <title>Other Screen Routines</title> +<para> +You must supply several other screen-specific routines for +your X server implementation. +Some of these are described in other sections: +<itemizedlist> +<listitem><para> +GetImage() is described in the Drawing Primitives section.</para></listitem> +<listitem><para> +GetSpans() is described in the Pixblit routine section.</para></listitem> +<listitem><para> +Several window and pixmap manipulation procedures are +described in the Window section under Drawables.</para></listitem> +<listitem><para> +The CreateGC() routine is described under Graphics Contexts.</para></listitem> +</itemizedlist> +</para> +<para> +<blockquote><programlisting> + + void pScreen->QueryBestSize(kind, pWidth, pHeight) + int kind; + unsigned short *pWidth, *pHeight; + ScreenPtr pScreen; + +</programlisting></blockquote> +QueryBestSize() returns the best sizes for cursors, tiles, and stipples +in response to client requests. +kind is one of the defined constants CursorShape, TileShape, or StippleShape +(defined in X.h). +For CursorShape, return the maximum width and +height for cursors that you can handle. +For TileShape and StippleShape, start with the suggested values in pWidth +and pHeight and modify them in place to be optimal values that are +greater than or equal to the suggested values. +The sample server implementation is in Xserver/fb/fbscreen.c.</para> +<para> +<blockquote><programlisting> + + pScreen->SourceValidate(pDrawable, x, y, width, height) + DrawablePtr pDrawable; + int x, y, width, height; + unsigned int subWindowMode; + +</programlisting></blockquote> +SourceValidate should be called by CopyArea/CopyPlane primitives when +the SourceValidate function pointer in the screen is non-null. If you know that +you will never need SourceValidate, you can avoid this check. Currently, +SourceValidate is used by the mi software cursor code to remove the cursor +from the screen when the source rectangle overlaps the cursor position. +x,y,width,height describe the source rectangle (source relative, that is) +for the copy operation. subWindowMode comes from the GC or source Picture. +</para> +<para> +<blockquote><programlisting> + + Bool pScreen->SaveScreen(pScreen, on) + ScreenPtr pScreen; + int on; + +</programlisting></blockquote> +SaveScreen() is used for Screen Saver support (see WaitForSomething()). +pScreen is the screen to save.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->CloseScreen(pScreen) + ScreenPtr pScreen; + +</programlisting></blockquote> +When the server is reset, it calls this routine for each screen.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->CreateScreenResources(pScreen) + ScreenPtr pScreen; + +</programlisting></blockquote> +If this routine is not NULL, it will be called once per screen per +server initialization/reset after all modules have had a chance to +request private space on all structures that support them (see +<xref linkend="wrappers_and_privates"/> below). You may create resources +in this function instead of in the +screen init function passed to AddScreen in order to guarantee that +all pre-allocated space requests have been registered first. With the +new devPrivates mechanism, this is not strictly necessary, however. +This routine returns TRUE if successful.</para> +</section> +</section> +<section> +<title>Drawables</title> +<para> +A drawable is a descriptor of a surface that graphics are drawn into, either +a window on the screen or a pixmap in memory.</para> +<para> +Each drawable has a type, class, +ScreenPtr for the screen it is associated with, depth, position, size, +and serial number. +The type is one of the defined constants DRAWABLE_PIXMAP, +DRAWABLE_WINDOW and UNDRAWABLE_WINDOW. +(An undrawable window is used for window class InputOnly.) +The serial number is guaranteed to be unique across drawables, and +is used in determining +the validity of the clipping information in a GC. +The screen selects the set of procedures used to manipulate and draw into the +drawable. Position is used (currently) only by windows; pixmaps must +set these fields to 0,0 as this reduces the amount of conditional code +executed throughout the mi code. Size indicates the actual client-specified +size of the drawable. +There are, in fact, no other fields that a window drawable and pixmap +drawable have in common besides those mentioned here.</para> +<para> +Both PixmapRecs and WindowRecs are structs that start with a drawable +and continue on with more fields. Pixmaps have a single pointer field +named devPrivate which usually points to the pixmap data but could conceivably be +used for anything that DDX wants. Both windows and pixmaps also have a +devPrivates field which can be used for DDX specific data (see <xref linkend="wrappers_and_privates"/> +below). This is done because different graphics hardware has +different requirements for management; if the graphics is always +handled by a processor with an independent address space, there is no +point having a pointer to the bit image itself.</para> +<para> +The definition of a drawable and a pixmap can be found in the file +Xserver/include/pixmapstr.h. +The definition of a window can be found in the file Xserver/include/windowstr.h.</para> +<section> + <title>Pixmaps</title> +<para> +A pixmap is a three-dimensional array of bits stored somewhere offscreen, +rather than in the visible portion of the screen's display frame buffer. It +can be used as a source or destination in graphics operations. There is no +implied interpretation of the pixel values in a pixmap, because it has no +associated visual or colormap. There is only a depth that indicates the +number of significant bits per pixel. Also, there is no implied physical +size for each pixel; all graphic units are in numbers of pixels. Therefore, +a pixmap alone does not constitute a complete image; it represents only a +rectangular array of pixel values.</para> +<para> +Note that the pixmap data structure is reference-counted.</para> +<para> +The server implementation is free to put the pixmap data +anywhere it sees fit, according to its graphics hardware setup. Many +implementations will simply have the data dynamically allocated in the +server's address space. More sophisticated implementations may put the +data in undisplayed framebuffer storage.</para> +<para> +In addition to dynamic devPrivates (see <xref linkend="wrappers_and_privates"/> +below), the pixmap data structure has two fields that are private to +the device. Although you can use them for anything you want, they +have intended purposes. devKind is intended to be a device specific +indication of the pixmap location (host memory, off-screen, etc.). In +the sample server, since all pixmaps are in memory, devKind stores the +width of the pixmap in bitmap scanline units. devPrivate is usually +a pointer to the bits in the pixmap.</para> +<para> +A bitmap is a pixmap that is one bit deep.</para> +<para> +<blockquote><programlisting> + + PixmapPtr pScreen->CreatePixmap(pScreen, width, height, depth) + ScreenPtr pScreen; + int width, height, depth; + +</programlisting></blockquote> +This ScreenRec procedure must create a pixmap of the size +requested. +It must allocate a PixmapRec and fill in all of the fields. +The reference count field must be set to 1. +If width or height are zero, no space should be allocated +for the pixmap data, and if the implementation is using the +devPrivate field as a pointer to the pixmap data, it should be +set to NULL. +If successful, it returns a pointer to the new pixmap; if not, it returns NULL. +See Xserver/fb/fbpixmap.c for the sample server implementation.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->DestroyPixmap(pPixmap) + PixmapPtr pPixmap; + +</programlisting></blockquote> +This ScreenRec procedure must "destroy" a pixmap. +It should decrement the reference count and, if zero, it +must deallocate the PixmapRec and all attached devPrivate blocks. +If successful, it returns TRUE. +See Xserver/fb/fbpixmap.c for the sample server implementation.</para> +<para> +<blockquote><programlisting> + + Bool + pScreen->ModifyPixmapHeader(pPixmap, width, height, depth, bitsPerPixel, devKind, pPixData) + PixmapPtr pPixmap; + int width; + int height; + int depth; + int bitsPerPixel; + int devKind; + pointer pPixData; + +</programlisting></blockquote> +This routine takes a pixmap header and initializes the fields of the PixmapRec to the +parameters of the same name. pPixmap must have been created via +pScreen->CreatePixmap with a zero width or height to avoid +allocating space for the pixmap data. pPixData is assumed to be the +pixmap data; it will be stored in an implementation-dependent place +(usually pPixmap->devPrivate.ptr). This routine returns +TRUE if successful. See Xserver/mi/miscrinit.c for the sample +server implementation.</para> +<para> +<blockquote><programlisting> + + PixmapPtr + GetScratchPixmapHeader(pScreen, width, height, depth, bitsPerPixel, devKind, pPixData) + ScreenPtr pScreen; + int width; + int height; + int depth; + int bitsPerPixel; + int devKind; + pointer pPixData; + + void FreeScratchPixmapHeader(pPixmap) + PixmapPtr pPixmap; + +</programlisting></blockquote> +DDX should use these two DIX routines when it has a buffer of raw +image data that it wants to manipulate as a pixmap temporarily, +usually so that some other part of the server can be leveraged to +perform some operation on the data. The data should be passed in +pPixData, and will be stored in an implementation-dependent place +(usually pPixmap->devPrivate.ptr). The other +fields go into the corresponding PixmapRec fields. +If successful, GetScratchPixmapHeader returns a valid PixmapPtr which can +be used anywhere the server expects a pixmap, else +it returns NULL. The pixmap should be released when no longer needed +(usually within the same function that allocated it) +with FreeScratchPixmapHeader.</para> +</section> +<section> + <title>Windows</title> +<para> +A window is a visible, or potentially visible, rectangle on the screen. +DIX windowing functions maintain an internal n-ary tree data structure, which +represents the current relationships of the mapped windows. +Windows that are contained in another window are children of that window and +are clipped to the boundaries of the parent. +The root window in the tree is the window for the entire screen. +Sibling windows constitute a doubly-linked list; the parent window has a pointer +to the head and tail of this list. +Each child also has a pointer to its parent.</para> +<para> +The border of a window is drawn by a DDX procedure when DIX requests that it +be drawn. The contents of the window is drawn by the client through +requests to the server.</para> +<para> +Window painting is orchestrated through an expose event system. +When a region is exposed, +DIX generates an expose event, telling the client to repaint the window and +passing the region that is the minimal area needed to be repainted.</para> +<para> +As a favor to clients, the server may retain +the output to the hidden parts of windows +in off-screen memory; this is called "backing store". +When a part of such a window becomes exposed, it +can quickly move pixels into place instead of +triggering an expose event and waiting for a client on the other +end of the network to respond. +Even if the network response is insignificant, the time to +intelligently paint a section of a window is usually more than +the time to just copy already-painted sections. +At best, the repainting involves blanking out the area to a background color, +which will take about the +same amount of time. +In this way, backing store can dramatically increase the +performance of window moves.</para> +<para> +On the other hand, backing store can be quite complex, because +all graphics drawn to hidden areas must be intercepted and redirected +to the off-screen window sections. +Not only can this be complicated for the server programmer, +but it can also impact window painting performance. +The backing store implementation can choose, at any time, to +forget pieces of backing that are written into, relying instead upon +expose events to repaint for simplicity.</para> +<para> +In X, the decision to use the backing-store scheme is made +by you, the server implementor. The sample server implements +backing store "for free" by reusing the infrastructure for the Composite +extension. As a side effect, it treats the WhenMapped and Always hints +as equivalent. However, it will never forget pixel contents when the +window is mapped.</para> +<para> +When a window operation is requested by the client, +such as a window being created or moved, +a new state is computed. +During this transition, DIX informs DDX what rectangles in what windows are about to +become obscured and what rectangles in what windows have become exposed. +This provides a hook for the implementation of backing store. +If DDX is unable to restore exposed regions, DIX generates expose +events to the client. +It is then the client's responsibility to paint the +window parts that were exposed but not restored.</para> +<para> +If a window is resized, pixels sometimes need to be +moved, depending upon +the application. +The client can request "Gravity" so that +certain blocks of the window are +moved as a result of a resize. +For instance, if the window has controls or other items +that always hang on the edge of the +window, and that edge is moved as a result of the resize, +then those pixels should be moved +to avoid having the client repaint it. +If the client needs to repaint it anyway, such an operation takes +time, so it is desirable +for the server to approximate the appearance of the window as best +it can while waiting for the client +to do it perfectly. +Gravity is used for that, also.</para> +<para> +The window has several fields used in drawing +operations: +<itemizedlist> +<listitem><para> +clipList - This region, in conjunction with +the client clip region in the gc, is used to clip output. +clipList has the window's children subtracted from it, in addition to pieces of sibling windows +that overlap this window. To get the list with the +children included (subwindow-mode is IncludeInferiors), +the routine NotClippedByChildren(pWin) returns the unclipped region.</para></listitem> +<listitem><para> +borderClip is the region used by CopyWindow and +includes the area of the window, its children, and the border, but with the +overlapping areas of sibling children removed.</para></listitem> +</itemizedlist> +Most of the other fields are for DIX use only.</para> +<section> +<title>Window Procedures in the ScreenRec</title> +<para> +You should implement +all of the following procedures and store pointers to them in the screen record.</para> +<para> +The device-independent portion of the server "owns" the window tree. +However, clever hardware might want to know the relationship of +mapped windows. There are pointers to procedures +in the ScreenRec data structure that are called to give the hardware +a chance to update its internal state. These are helpers and +hints to DDX only; +they do not change the window tree, which is only changed by DIX.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->CreateWindow(pWin) + WindowPtr pWin; + +</programlisting></blockquote> +This routine is a hook for when DIX creates a window. +It should fill in the "Window Procedures in the WindowRec" below +and also allocate the devPrivate block for it.</para> +<para> +See Xserver/fb/fbwindow.c for the sample server implementation.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->DestroyWindow(pWin); + WindowPtr pWin; + +</programlisting></blockquote> +This routine is a hook for when DIX destroys a window. +It should deallocate the devPrivate block for it and any other blocks that need +to be freed, besides doing other cleanup actions.</para> +<para> +See Xserver/fb/fbwindow.c for the sample server implementation.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->PositionWindow(pWin, x, y); + WindowPtr pWin; + int x, y; + +</programlisting></blockquote> +This routine is a hook for when DIX moves or resizes a window. +It should do whatever private operations need to be done when a window is moved or resized. +For instance, if DDX keeps a pixmap tile used for drawing the background +or border, and it keeps the tile rotated such that it is longword +aligned to longword locations in the frame buffer, then you should rotate your tiles here. +The actual graphics involved in moving the pixels on the screen and drawing the +border are handled by CopyWindow(), below.</para> +<para> +See Xserver/fb/fbwindow.c for the sample server implementation.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->RealizeWindow(pWin); + WindowPtr pWin; + + Bool pScreen->UnrealizeWindow(pWin); + WindowPtr pWin; + +</programlisting></blockquote> +These routines are hooks for when DIX maps (makes visible) and unmaps +(makes invisible) a window. It should do whatever private operations +need to be done when these happen, such as allocating or deallocating +structures that are only needed for visible windows. RealizeWindow +does NOT draw the window border, background or contents; +UnrealizeWindow does NOT erase the window or generate exposure events +for underlying windows; this is taken care of by DIX. DIX does, +however, call PaintWindowBackground() and PaintWindowBorder() to +perform some of these.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->ChangeWindowAttributes(pWin, vmask) + WindowPtr pWin; + unsigned long vmask; + +</programlisting></blockquote> +ChangeWindowAttributes is called whenever DIX changes window +attributes, such as the size, front-to-back ordering, title, or +anything of lesser severity that affects the window itself. The +sample server implements this routine. It computes accelerators for +quickly putting up background and border tiles. (See description of +the set of routines stored in the WindowRec.)</para> +<para> +<blockquote><programlisting> + + int pScreen->ValidateTree(pParent, pChild, kind) + WindowPtr pParent, pChild; + VTKind kind; + +</programlisting></blockquote> +ValidateTree calculates the clipping region for the parent window and +all of its children. This routine must be provided. The sample server +has a machine-independent version in Xserver/mi/mivaltree.c. This is +a very difficult routine to replace.</para> +<para> +<blockquote><programlisting> + + void pScreen->PostValidateTree(pParent, pChild, kind) + WindowPtr pParent, pChild; + VTKind kind; + +</programlisting></blockquote> +If this routine is not NULL, DIX calls it shortly after calling +ValidateTree, passing it the same arguments. This is useful for +managing multi-layered framebuffers. +The sample server sets this to NULL.</para> +<para> +<blockquote><programlisting> + + void pScreen->WindowExposures(pWin, pRegion, pBSRegion) + WindowPtr pWin; + RegionPtr pRegion; + RegionPtr pBSRegion; + +</programlisting></blockquote> +The WindowExposures() routine +paints the border and generates exposure events for the window. +pRegion is an unoccluded region of the window, and pBSRegion is an +occluded region that has backing store. +Since exposure events include a rectangle describing what was exposed, +this routine may have to send back a series of exposure events, one for +each rectangle of the region. +The count field in the expose event is a hint to the +client as to the number of +regions that are after this one. +This routine must be provided. The sample +server has a machine-independent version in Xserver/mi/miexpose.c.</para> +<para> +<blockquote><programlisting> + + void pScreen->ClipNotify (pWin, dx, dy) + WindowPtr pWin; + int dx, dy; + +</programlisting></blockquote> +Whenever the cliplist for a window is changed, this function is called to +perform whatever hardware manipulations might be necessary. When called, +the clip list and border clip regions in the window are set to the new +values. dx,dy are the distance that the window has been moved (if at all).</para> +</section> +<section> + <title>Window Painting Procedures</title> +<para> +In addition to the procedures listed above, there are two routines which +manipulate the actual window image directly. +In the sample server, mi implementations will work for +most purposes and fb routines speed up situations, such +as solid backgrounds/borders or tiles that are 8, 16 or 32 pixels square.</para> +<para> +<blockquote><programlisting> + + void pScreen->ClearToBackground(pWin, x, y, w, h, generateExposures); + WindowPtr pWin; + int x, y, w, h; + Bool generateExposures; + +</programlisting></blockquote> +This routine is called on a window in response to a ClearToBackground request +from the client. +This request has two different but related functions, depending upon generateExposures.</para> +<para> +If generateExposures is true, the client is declaring that the given rectangle +on the window is incorrectly painted and needs to be repainted. +The sample server implementation calculates the exposure region +and hands it to the DIX procedure HandleExposures(), which +calls the WindowExposures() routine, below, for the window +and all of its child windows.</para> +<para> +If generateExposures is false, the client is trying to simply erase part +of the window to the background fill style. +ClearToBackground should write the background color or tile to the +rectangle in question (probably using PaintWindowBackground). +If w or h is zero, it clears all the way to the right or lower edge of the window.</para> +<para> +The sample server implementation is in Xserver/mi/miwindow.c.</para> +<para> +<blockquote><programlisting> + + void pScreen->CopyWindow(pWin, oldpt, oldRegion); + WindowPtr pWin; + DDXPointRec oldpt; + RegionPtr oldRegion; + +</programlisting></blockquote> +CopyWindow is called when a window is moved, and graphically moves to +pixels of a window on the screen. It should not change any other +state within DDX (see PositionWindow(), above).</para> +<para> +oldpt is the old location of the upper-left corner. oldRegion is the +old region it is coming from. The new location and new region is +stored in the WindowRec. oldRegion might modified in place by this +routine (the sample implementation does this).</para> +<para> +CopyArea could be used, except that this operation has more +complications. First of all, you do not want to copy a rectangle onto +a rectangle. The original window may be obscured by other windows, +and the new window location may be similarly obscured. Second, some +hardware supports multiple windows with multiple depths, and your +routine needs to take care of that.</para> +<para> +The pixels in oldRegion (with reference point oldpt) are copied to the +window's new region (pWin->borderClip). pWin->borderClip is gotten +directly from the window, rather than passing it as a parameter.</para> +<para> +The sample server implementation is in Xserver/fb/fbwindow.c.</para> +</section> +<section> +<title>Screen Operations for Multi-Layered Framebuffers</title> +<para> +The following screen functions are useful if you have a framebuffer with +multiple sets of independent bit planes, e.g. overlays or underlays in +addition to the "main" planes. If you have a simple single-layer +framebuffer, you should probably use the mi versions of these routines +in mi/miwindow.c. This can be easily accomplished by calling miScreenInit.</para> +<para> +<blockquote><programlisting> + + void pScreen->MarkWindow(pWin) + WindowPtr pWin; + +</programlisting></blockquote> +This formerly dix function MarkWindow has moved to ddx and is accessed +via this screen function. This function should store something, +usually a pointer to a device-dependent structure, in pWin->valdata so +that ValidateTree has the information it needs to validate the window.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->MarkOverlappedWindows(parent, firstChild, ppLayerWin) + WindowPtr parent; + WindowPtr firstChild; + WindowPtr * ppLayerWin; + +</programlisting></blockquote> +This formerly dix function MarkWindow has moved to ddx and is accessed +via this screen function. In the process, it has grown another +parameter: ppLayerWin, which is filled in with a pointer to the window +at which save under marking and ValidateTree should begin. In the +single-layered framebuffer case, pLayerWin == pWin.</para> +<para> +<blockquote><programlisting> + + Bool pScreen->ChangeSaveUnder(pLayerWin, firstChild) + WindowPtr pLayerWin; + WindowPtr firstChild; + +</programlisting></blockquote> +The dix functions ChangeSaveUnder and CheckSaveUnder have moved to ddx and +are accessed via this screen function. pLayerWin should be the window +returned in the ppLayerWin parameter of MarkOverlappedWindows. The function +may turn on backing store for windows that might be covered, and may partially +turn off backing store for windows. It returns TRUE if PostChangeSaveUnder +needs to be called to finish turning off backing store.</para> +<para> +<blockquote><programlisting> + + void pScreen->PostChangeSaveUnder(pLayerWin, firstChild) + WindowPtr pLayerWin; + WindowPtr firstChild; + +</programlisting></blockquote> +The dix function DoChangeSaveUnder has moved to ddx and is accessed via +this screen function. This function completes the job of turning off +backing store that was started by ChangeSaveUnder.</para> +<para> +<blockquote><programlisting> + + void pScreen->MoveWindow(pWin, x, y, pSib, kind) + WindowPtr pWin; + int x; + int y; + WindowPtr pSib; + VTKind kind; + +</programlisting></blockquote> +The formerly dix function MoveWindow has moved to ddx and is accessed via +this screen function. The new position of the window is given by +x,y. kind is VTMove if the window is only moving, or VTOther if +the border is also changing.</para> +<para> +<blockquote><programlisting> + + void pScreen->ResizeWindow(pWin, x, y, w, h, pSib) + WindowPtr pWin; + int x; + int y; + unsigned int w; + unsigned int h; + WindowPtr pSib; + +</programlisting></blockquote> +The formerly dix function SlideAndSizeWindow has moved to ddx and is accessed via +this screen function. The new position is given by x,y. The new size +is given by w,h.</para> +<para> +<blockquote><programlisting> + + WindowPtr pScreen->GetLayerWindow(pWin) + WindowPtr pWin + +</programlisting></blockquote> +This is a new function which returns a child of the layer parent of pWin.</para> +<para> +<blockquote><programlisting> + + void pScreen->HandleExposures(pWin) + WindowPtr pWin; + +</programlisting></blockquote> +The formerly dix function HandleExposures has moved to ddx and is accessed via +this screen function. This function is called after ValidateTree and +uses the information contained in valdata to send exposures to windows.</para> +<para> +<blockquote><programlisting> + + void pScreen->ReparentWindow(pWin, pPriorParent) + WindowPtr pWin; + WindowPtr pPriorParent; + +</programlisting></blockquote> +This function will be called when a window is reparented. At the time of +the call, pWin will already be spliced into its new position in the +window tree, and pPriorParent is its previous parent. This function +can be NULL.</para> +<para> +<blockquote><programlisting> + + void pScreen->SetShape(pWin) + WindowPtr pWin; + +</programlisting></blockquote> +The formerly dix function SetShape has moved to ddx and is accessed via +this screen function. The window's new shape will have already been +stored in the window when this function is called.</para> +<para> +<blockquote><programlisting> + + void pScreen->ChangeBorderWidth(pWin, width) + WindowPtr pWin; + unsigned int width; + +</programlisting></blockquote> +The formerly dix function ChangeBorderWidth has moved to ddx and is accessed via +this screen function. The new border width is given by width.</para> +<para> +<blockquote><programlisting> + + void pScreen->MarkUnrealizedWindow(pChild, pWin, fromConfigure) + WindowPtr pChild; + WindowPtr pWin; + Bool fromConfigure; + +</programlisting></blockquote> +This function is called for windows that are being unrealized as part of +an UnrealizeTree. pChild is the window being unrealized, pWin is an +ancestor, and the fromConfigure value is simply propagated from UnrealizeTree.</para> +</section> +</section> +</section> +<section> +<title>Graphics Contexts and Validation</title> +<para> +This graphics context (GC) contains state variables such as foreground and +background pixel value (color), the current line style and width, +the current tile or stipple for pattern generation, the current font for text +generation, and other similar attributes.</para> +<para> +In many graphics systems, the equivalent of the graphics context and the +drawable are combined as one entity. +The main distinction between the two kinds of status is that a drawable +describes a writing surface and the writings that may have already been done +on it, whereas a graphics context describes the drawing process. +A drawable is like a chalkboard. +A GC is like a piece of chalk.</para> +<para> +Unlike many similar systems, there is no "current pen location." +Every graphic operation is accompanied by the coordinates where it is to happen.</para> +<para> +The GC also includes two vectors of procedure pointers, the first +operate on the GC itself and are called GC funcs. The second, called +GC ops, +contains the functions that carry out the fundamental graphic operations +such as drawing lines, polygons, arcs, text, and copying bitmaps. +The DDX graphic software can, if it +wants to be smart, change these two vectors of procedure pointers +to take advantage of hardware/firmware in the server machine, which can do +a better job under certain circumstances. To reduce the amount of memory +consumed by each GC, it is wise to create a few "boilerplate" GC ops vectors +which can be shared by every GC which matches the constraints for that set. +Also, it is usually reasonable to have every GC created by a particular +module to share a common set of GC funcs. Samples of this sort of +sharing can be seen in fb/fbgc.c.</para> +<para> +The DDX software is notified any time the client (or DIX) uses a changed GC. +For instance, if the hardware has special support for drawing fixed-width +fonts, DDX can intercept changes to the current font in a GC just before +drawing is done. It can plug into either a fixed-width procedure that makes +the hardware draw characters, or a variable-width procedure that carefully +lays out glyphs by hand in software, depending upon the new font that is +selected.</para> +<para> +A definition of these structures can be found in the file +Xserver/include/gcstruct.h.</para> +<para> +Also included in each GC is support for dynamic devPrivates, which the +DDX can use for any purpose (see <xref linkend="wrappers_and_privates"/> below).</para> +<para> +The DIX routines available for manipulating GCs are +CreateGC, ChangeGC, ChangeGCXIDs, CopyGC, SetClipRects, SetDashes, and FreeGC. +<blockquote><programlisting> + + GCPtr CreateGC(pDrawable, mask, pval, pStatus) + DrawablePtr pDrawable; + BITS32 mask; + XID *pval; + int *pStatus; + + int ChangeGC(client, pGC, mask, pUnion) + ClientPtr client; + GCPtr pGC; + BITS32 mask; + ChangeGCValPtr pUnion; + + int ChangeGCXIDs(client, pGC, mask, pC32) + ClientPtr client; + GCPtr pGC; + BITS32 mask; + CARD32 *pC32; + + int CopyGC(pgcSrc, pgcDst, mask) + GCPtr pgcSrc; + GCPtr pgcDst; + BITS32 mask; + + int SetClipRects(pGC, xOrigin, yOrigin, nrects, prects, ordering) + GCPtr pGC; + int xOrigin, yOrigin; + int nrects; + xRectangle *prects; + int ordering; + + SetDashes(pGC, offset, ndash, pdash) + GCPtr pGC; + unsigned offset; + unsigned ndash; + unsigned char *pdash; + + int FreeGC(pGC, gid) + GCPtr pGC; + GContext gid; + +</programlisting></blockquote> +</para> +<para> +As a convenience, each Screen structure contains an array of +GCs that are preallocated, one at each depth the screen supports. +These are particularly useful in the mi code. Two DIX routines +must be used to get these GCs: +<blockquote><programlisting> + + GCPtr GetScratchGC(depth, pScreen) + int depth; + ScreenPtr pScreen; + + FreeScratchGC(pGC) + GCPtr pGC; + +</programlisting></blockquote> +Always use these two routines, don't try to extract the scratch +GC yourself -- someone else might be using it, so a new one must +be created on the fly.</para> +<para> +If you need a GC for a very long time, say until the server is restarted, +you should not take one from the pool used by GetScratchGC, but should +get your own using CreateGC or CreateScratchGC. +This leaves the ones in the pool free for routines that only need it for +a little while and don't want to pay a heavy cost to get it. +<blockquote><programlisting> + + GCPtr CreateScratchGC(pScreen, depth) + ScreenPtr pScreen; + int depth; + +</programlisting></blockquote> +NULL is returned if the GC cannot be created. +The GC returned can be freed with FreeScratchGC.</para> +<section> + <title>Details of Operation</title> +<para> +At screen initialization, a screen must supply a GC creation procedure. +At GC creation, the screen must fill in GC funcs and GC ops vectors +(Xserver/include/gcstruct.h). For any particular GC, the func vector +must remain constant, while the op vector may vary. This invariant is to +ensure that Wrappers work correctly.</para> +<para> +When a client request is processed that results in a change +to the GC, the device-independent state of the GC is updated. +This includes a record of the state that changed. +Then the ChangeGC GC func is called. +This is useful for graphics subsystems that are able to process +state changes in parallel with the server CPU. +DDX may opt not to take any action at GC-modify time. +This is more efficient if multiple GC-modify requests occur +between draws using a given GC.</para> +<para> +Validation occurs at the first draw operation that specifies the GC after +that GC was modified. DIX calls then the ValidateGC GC func. DDX should +then update its internal state. DDX internal state may be stored as one or +more of the following: 1) device private block on the GC; 2) hardware +state; 3) changes to the GC ops.</para> +<para> +The GC contains a serial number, which is loaded with a number fetched from +the window that was drawn into the last time the GC was used. The serial +number in the drawable is changed when the drawable's +clipList or absCorner changes. Thus, by +comparing the GC serial number with the drawable serial number, DIX can +force a validate if the drawable has been changed since the last time it +was used with this GC.</para> +<para> +In addition, the drawable serial number is always guaranteed to have the +most significant bit set to 0. Thus, the DDX layer can set the most +significant bit of the serial number to 1 in a GC to force a validate the next time +the GC is used. DIX also uses this technique to indicate that a change has +been made to the GC by way of a SetGC, a SetDashes or a SetClip request.</para> +</section> +<section> + <title>GC Handling Routines</title> +<para> +The ScreenRec data structure has a pointer for +CreateGC(). +<blockquote><programlisting> + + Bool pScreen->CreateGC(pGC) + GCPtr pGC; +</programlisting></blockquote> +This routine must fill in the fields of +a dynamically allocated GC that is passed in. +It does NOT allocate the GC record itself or fill +in the defaults; DIX does that.</para> +<para> +This must fill in both the GC funcs and ops; none of the drawing +functions will be called before the GC has been validated, +but the others (dealing with allocating of clip regions, +changing and destroying the GC, etc.) might be.</para> +<para> +The GC funcs vector contains pointers to 7 +routines and a devPrivate field: +<blockquote><programlisting> + + pGC->funcs->ChangeGC(pGC, changes) + GCPtr pGC; + unsigned long changes; + +</programlisting></blockquote> +This GC func is called immediately after a field in the GC is changed. +changes is a bit mask indicating the changed fields of the GC in this +request.</para> +<para> +The ChangeGC routine is useful if you have a system where +state-changes to the GC can be swallowed immediately by your graphics +system, and a validate is not necessary.</para> +<para> +<blockquote><programlisting> + + pGC->funcs->ValidateGC(pGC, changes, pDraw) + GCPtr pGC; + unsigned long changes; + DrawablePtr pDraw; + +</programlisting></blockquote> +ValidateGC is called by DIX just before the GC will be used when one +of many possible changes to the GC or the graphics system has +happened. It can modify devPrivates data attached to the GC, +change the op vector, or change hardware according to the +values in the GC. It may not change the device-independent portion of +the GC itself.</para> +<para> +In almost all cases, your ValidateGC() procedure should take the +regions that drawing needs to be clipped to and combine them into a +composite clip region, which you keep a pointer to in the private part +of the GC. In this way, your drawing primitive routines (and whatever +is below them) can easily determine what to clip and where. You +should combine the regions clientClip (the region that the client +desires to clip output to) and the region returned by +NotClippedByChildren(), in DIX. An example is in Xserver/fb/fbgc.c.</para> +<para> +Some kinds of extension software may cause this routine to be called +more than originally intended; you should not rely on algorithms that +will break under such circumstances.</para> +<para> +See the Strategies document for more information on creatively using +this routine.</para> +<para> +<blockquote><programlisting> + + pGC->funcs->CopyGC(pGCSrc, mask, pGCDst) + GCPtr pGCSrc; + unsigned long mask; + GCPtr pGCDst; + +</programlisting></blockquote> +This routine is called by DIX when a GC is being copied to another GC. +This is for situations where dynamically allocated chunks of memory +are stored in the GC's dynamic devPrivates and need to be transferred to +the destination GC.</para> +<para> +<blockquote><programlisting> + + pGC->funcs->DestroyGC(pGC) + GCPtr pGC; + +</programlisting></blockquote> +This routine is called before the GC is destroyed for the +entity interested in this GC to clean up after itself. +This routine is responsible for freeing any auxiliary storage allocated.</para> +</section> +<section> + <title>GC Clip Region Routines</title> +<para> +The GC clientClip field requires three procedures to manage it. These +procedures are in the GC funcs vector. The underlying principle is that dix +knows nothing about the internals of the clipping information, (except when +it has come from the client), and so calls ddX whenever it needs to copy, +set, or destroy such information. It could have been possible for dix not +to allow ddX to touch the field in the GC, and require it to keep its own +copy in devPriv, but since clip masks can be very large, this seems like a +bad idea. Thus, the server allows ddX to do whatever it wants to the +clientClip field of the GC, but requires it to do all manipulation itself.</para> +<para> +<blockquote><programlisting> + + void pGC->funcs->ChangeClip(pGC, type, pValue, nrects) + GCPtr pGC; + int type; + char *pValue; + int nrects; + +</programlisting></blockquote> +This routine is called whenever the client changes the client clip +region. The pGC points to the GC involved, the type tells what form +the region has been sent in. If type is CT_NONE, then there is no +client clip. If type is CT_UNSORTED, CT_YBANDED or CT_YXBANDED, then +pValue pointer to a list of rectangles, nrects long. If type is +CT_REGION, then pValue pointer to a RegionRec from the mi region code. +If type is CT_PIXMAP pValue is a pointer to a pixmap. (The defines +for CT_NONE, etc. are in Xserver/include/gc.h.) This routine is +responsible for incrementing any necessary reference counts (e.g. for +a pixmap clip mask) for the new clipmask and freeing anything that +used to be in the GC's clipMask field. The lists of rectangles passed +in can be freed with Xfree(), the regions can be destroyed with the +RegionDestroy field in the screen, and pixmaps can be destroyed by +calling the screen's DestroyPixmap function. DIX and MI code expect +what they pass in to this to be freed or otherwise inaccessible, and +will never look inside what's been put in the GC. This is a good +place to be wary of storage leaks.</para> +<para> +In the sample server, this routine transforms either the bitmap or the +rectangle list into a region, so that future routines will have a more +predictable starting point to work from. (The validate routine must +take this client clip region and merge it with other regions to arrive +at a composite clip region before any drawing is done.)</para> +<para> +<blockquote><programlisting> + + void pGC->funcs->DestroyClip(pGC) + GCPtr pGC; + +</programlisting></blockquote> +This routine is called whenever the client clip region must be destroyed. +The pGC points to the GC involved. This call should set the clipType +field of the GC to CT_NONE. +In the sample server, the pointer to the client clip region is set to NULL +by this routine after destroying the region, so that other software +(including ChangeClip() above) will recognize that there is no client clip region.</para> +<para> +<blockquote><programlisting> + + void pGC->funcs->CopyClip(pgcDst, pgcSrc) + GCPtr pgcDst, pgcSrc; + +</programlisting></blockquote> +This routine makes a copy of the clipMask and clipType from pgcSrc +into pgcDst. It is responsible for destroying any previous clipMask +in pgcDst. The clip mask in the source can be the same as the +clip mask in the dst (clients do the strangest things), so care must +be taken when destroying things. This call is required because dix +does not know how to copy the clip mask from pgcSrc.</para> +</section> +</section> +<section> + <title>Drawing Primitives</title> +<para> +The X protocol (rules for the byte stream that goes between client and server) +does all graphics using primitive +operations, which are called Drawing Primitives. +These include line drawing, area filling, arcs, and text drawing. +Your implementation must supply 16 routines +to perform these on your hardware. +(The number 16 is arbitrary.)</para> +<para> +More specifically, 16 procedure pointers are in each +GC op vector. +At any given time, ALL of them MUST point to a valid procedure that +attempts to do the operation assigned, although +the procedure pointers may change and may +point to different procedures to carry out the same operation. +A simple server will leave them all pointing to the same 16 routines, while +a more optimized implementation will switch each from one +procedure to another, depending upon what is most optimal +for the current GC and drawable.</para> +<para> +The sample server contains a considerable chunk of code called the +mi (machine independent) +routines, which serve as drawing primitive routines. +Many server implementations will be able to use these as-is, +because they work for arbitrary depths. +They make no assumptions about the formats of pixmaps +and frame buffers, since they call a set of routines +known as the "Pixblit Routines" (see next section). +They do assume that the way to draw is +through these low-level routines that apply pixel values rows at a time. +If your hardware or firmware gives more performance when +things are done differently, you will want to take this fact into account +and rewrite some or all of the drawing primitives to fit your needs.</para> +<section> + <title>GC Components</title> +<para> +This section describes the fields in the GC that affect each drawing primitive. +The only primitive that is not affected is GetImage, which does not use a GC +because its destination is a protocol-style bit image. +Since each drawing primitive mirrors exactly the X protocol request of the +same name, you should refer to the X protocol specification document +for more details.</para> +<para> +ALL of these routines MUST CLIP to the +appropriate regions in the drawable. +Since there are many regions to clip to simultaneously, +your ValidateGC routine should combine these into a unified +clip region to which your drawing routines can quickly refer. +This is exactly what the fb routines supplied with the sample server +do. +The mi implementation passes responsibility for clipping while drawing +down to the Pixblit routines.</para> +<para> +Also, all of them must adhere to the current plane mask. +The plane mask has one bit for every bit plane in the drawable; +only planes with 1 bits in the mask are affected by any drawing operation.</para> +<para> +All functions except for ImageText calls must obey the alu function. +This is usually Copy, but could be any of the allowable 16 raster-ops.</para> +<para> +All of the functions, except for CopyArea, might use the current +foreground and background pixel values. +Each pixel value is 32 bits. +These correspond to foreground and background colors, but you have +to run them through the colormap to find out what color the pixel values +represent. Do not worry about the color, just apply the pixel value.</para> +<para> +The routines that draw lines (PolyLine, PolySegment, PolyRect, and PolyArc) +use the line width, line style, cap style, and join style. +Line width is in pixels. +The line style specifies whether it is solid or dashed, and what kind of dash. +The cap style specifies whether Rounded, Butt, etc. +The join style specifies whether joins between joined lines are Miter, Round or Beveled. +When lines cross as part of the same polyline, they are assumed to be drawn once. +(See the X protocol specification for more details.)</para> +<para> +Zero-width lines are NOT meant to be really zero width; this is the client's way +of telling you that you can optimize line drawing with little regard to +the end caps and joins. +They are called "thin" lines and are meant to be one pixel wide. +These are frequently done in hardware or in a streamlined assembly language +routine.</para> +<para> +Lines with widths greater than zero, though, must all be drawn with the same +algorithm, because client software assumes that every jag on every +line at an angle will come at the same place. +Two lines that should have +one pixel in the space between them +(because of their distance apart and their widths) should have such a one-pixel line +of space between them if drawn, regardless of angle.</para> +<para> +The solid area fill routines (FillPolygon, PolyFillRect, PolyFillArc) +all use the fill rule, which specifies subtle interpretations of +what points are inside and what are outside of a given polygon. +The PolyFillArc routine also uses the arc mode, which specifies +whether to fill pie segments or single-edge slices of an ellipse.</para> +<para> +The line drawing, area fill, and PolyText routines must all +apply the correct "fill style." +This can be either a solid foreground color, a transparent stipple, +an opaque stipple, or a tile. +Stipples are bitmaps where the 1 bits represent that the foreground color is written, +and 0 bits represent that either the pixel is left alone (transparent) or that +the background color is written (opaque). +A tile is a pixmap of the full depth of the GC that is applied in its full glory to all areas. +The stipple and tile patterns can be any rectangular size, although some implementations +will be faster for certain sizes such as 8x8 or 32x32. +The mi implementation passes this responsibility down to the Pixblit routines.</para> +<para> +See the X protocol document for full details. +The description of the CreateGC request has a very good, detailed description of these +attributes.</para> +</section> +<section> +<title>The Primitives</title> +<para> +The Drawing Primitives are as follows: + +<blockquote><programlisting> + + RegionPtr pGC->ops->CopyArea(src, dst, pGC, srcx, srcy, w, h, dstx, dsty) + DrawablePtr dst, src; + GCPtr pGC; + int srcx, srcy, w, h, dstx, dsty; + +</programlisting></blockquote> +CopyArea copies a rectangle of pixels from one drawable to another of +the same depth. To effect scrolling, this must be able to copy from +any drawable to itself, overlapped. No squeezing or stretching is done +because the source and destination are the same size. However, +everything is still clipped to the clip regions of the destination +drawable.</para> +<para> +If pGC->graphicsExposures is True, any portions of the destination which +were not valid in the source (either occluded by covering windows, or +outside the bounds of the drawable) should be collected together and +returned as a region (if this resultant region is empty, NULL can be +returned instead). Furthermore, the invalid bits of the source are +not copied to the destination and (when the destination is a window) +are filled with the background tile. The sample routine +miHandleExposures generates the appropriate return value and fills the +invalid area using pScreen->PaintWindowBackground.</para> +<para> +For instance, imagine a window that is partially obscured by other +windows in front of it. As text is scrolled on your window, the pixels +that are scrolled out from under obscuring windows will not be +available on the screen to copy to the right places, and so an exposure +event must be sent for the client to correctly repaint them. Of +course, if you implement backing store, you could do this without resorting +to exposure events.</para> +<para> +An example implementation is fbCopyArea() in Xserver/fb/fbcopy.c.</para> +<para> +<blockquote><programlisting> + + RegionPtr pGC->ops->CopyPlane(src, dst, pGC, srcx, srcy, w, h, dstx, dsty, plane) + DrawablePtr dst, src; + GCPtr pGC; + int srcx, srcy, w, h, dstx, dsty; + unsigned long plane; + +</programlisting></blockquote> +CopyPlane must copy one plane of a rectangle from the source drawable +onto the destination drawable. Because this routine only copies one +bit out of each pixel, it can copy between drawables of different +depths. This is the only way of copying between drawables of +different depths, except for copying bitmaps to pixmaps and applying +foreground and background colors to it. All other conditions of +CopyArea apply to CopyPlane too.</para> +<para> +An example implementation is fbCopyPlane() in +Xserver/fb/fbcopy.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyPoint(dst, pGC, mode, n, pPoint) + DrawablePtr dst; + GCPtr pGC; + int mode; + int n; + DDXPointPtr pPoint; + +</programlisting></blockquote> +PolyPoint draws a set of one-pixel dots (foreground color) +at the locations given in the array. +mode is one of the defined constants Origin (absolute coordinates) or Previous +(each coordinate is relative to the last). +Note that this does not use the background color or any tiles or stipples.</para> +<para> +Example implementations are fbPolyPoint() in Xserver/fb/fbpoint.c and +miPolyPoint in Xserver/mi/mipolypnt.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->Polylines(dst, pGC, mode, n, pPoint) + DrawablePtr dst; + GCPtr pGC; + int mode; + int n; + DDXPointPtr pPoint; + +</programlisting></blockquote> +Similar to PolyPoint, Polylines draws lines between the locations given in the array. +Zero-width lines are NOT meant to be really zero width; this is the client's way of +telling you that you can maximally optimize line drawing with little regard to +the end caps and joins. +mode is one of the defined constants Previous or Origin, depending upon +whether the points are each relative to the last or are absolute.</para> +<para> +Example implementations are miWideLine() and miWideDash() in +mi/miwideline.c and miZeroLine() in mi/mizerline.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolySegment(dst, pGC, n, pPoint) + DrawablePtr dst; + GCPtr pGC; + int n; + xSegment *pSegments; + +</programlisting></blockquote> +PolySegments draws unconnected +lines between pairs of points in the array; the array must be of +even size; no interconnecting lines are drawn.</para> +<para> +An example implementation is miPolySegment() in mipolyseg.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyRectangle(dst, pGC, n, pRect) + DrawablePtr dst; + GCPtr pGC; + int n; + xRectangle *pRect; + +</programlisting></blockquote> +PolyRectangle draws outlines of rectangles for each rectangle in the array.</para> +<para> +An example implementation is miPolyRectangle() in Xserver/mi/mipolyrect.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyArc(dst, pGC, n, pArc) + DrawablePtr dst; + GCPtr pGC; + int n; + xArc*pArc; + +</programlisting></blockquote> +PolyArc draws connected conic arcs according to the descriptions in the array. +See the protocol specification for more details.</para> +<para> +Example implementations are miZeroPolyArc in Xserver/mi/mizerarc. and +miPolyArc() in Xserver/mi/miarc.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->FillPolygon(dst, pGC, shape, mode, count, pPoint) + DrawablePtr dst; + GCPtr pGC; + int shape; + int mode; + int count; + DDXPointPtr pPoint; + +</programlisting></blockquote> +FillPolygon fills a polygon specified by the points in the array +with the appropriate fill style. +If necessary, an extra border line is assumed between the starting and ending lines. +The shape can be used as a hint +to optimize filling; it indicates whether it is convex (all interior angles +less than 180), nonconvex (some interior angles greater than 180 but +border does not cross itself), or complex (border crosses itself). +You can choose appropriate algorithms or hardware based upon mode. +mode is one of the defined constants Previous or Origin, depending upon +whether the points are each relative to the last or are absolute.</para> +<para> +An example implementation is miFillPolygon() in Xserver/mi/mipoly.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyFillRect(dst, pGC, n, pRect) + DrawablePtr dst; + GCPtr pGC; + int n; + xRectangle *pRect; + +</programlisting></blockquote> +PolyFillRect fills multiple rectangles.</para> +<para> +Example implementations are fbPolyFillRect() in Xserver/fb/fbfillrect.c and +miPolyFillRect() in Xserver/mi/mifillrct.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyFillArc(dst, pGC, n, pArc) + DrawablePtr dst; + GCPtr pGC; + int n; + xArc *pArc; + +</programlisting></blockquote> +PolyFillArc fills a shape for each arc in the +list that is bounded by the arc and one or two +line segments with the current fill style.</para> +<para> +An example implementation is miPolyFillArc() in Xserver/mi/mifillarc.c.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PutImage(dst, pGC, depth, x, y, w, h, leftPad, format, pBinImage) + DrawablePtr dst; + GCPtr pGC; + int x, y, w, h; + int format; + char *pBinImage; + +</programlisting></blockquote> +PutImage copies a pixmap image into the drawable. The pixmap image +must be in X protocol format (either Bitmap, XYPixmap, or ZPixmap), +and format tells the format. (See the X protocol specification for +details on these formats). You must be able to accept all three +formats, because the client gets to decide which format to send. +Either the drawable and the pixmap image have the same depth, or the +source pixmap image must be a Bitmap. If a Bitmap, the foreground and +background colors will be applied to the destination.</para> +<para> +An example implementation is fbPutImage() in Xserver/fb/fbimage.c.</para> +<para> +<blockquote><programlisting> + + void pScreen->GetImage(src, x, y, w, h, format, planeMask, pBinImage) + DrawablePtr src; + int x, y, w, h; + unsigned int format; + unsigned long planeMask; + char *pBinImage; + +</programlisting></blockquote> +GetImage copies the bits from the source drawable into +the destination pointer. The bits are written into the buffer +according to the server-defined pixmap padding rules. +pBinImage is guaranteed to be big enough to hold all +the bits that must be written.</para> +<para> +This routine does not correspond exactly to the X protocol GetImage +request, since DIX has to break the reply up into buffers of a size +requested by the transport layer. If format is ZPixmap, the bits are +written in the ZFormat for the depth of the drawable; if there is a 0 +bit in the planeMask for a particular plane, all pixels must have the +bit in that plane equal to 0. If format is XYPixmap, planemask is +guaranteed to have a single bit set; the bits should be written in +Bitmap format, which is the format for a single plane of an XYPixmap.</para> +<para> +An example implementation is miGetImage() in Xserver/mi/mibitblt.c. +<blockquote><programlisting> + + void pGC->ops->ImageText8(pDraw, pGC, x, y, count, chars) + DrawablePtr pDraw; + GCPtr pGC; + int x, y; + int count; + char *chars; + +</programlisting></blockquote> +ImageText8 draws text. The text is drawn in the foreground color; the +background color fills the remainder of the character rectangles. The +coordinates specify the baseline and start of the text.</para> +<para> +An example implementation is miImageText8() in Xserver/mi/mipolytext.c.</para> +<para> +<blockquote><programlisting> + + int pGC->ops->PolyText8(pDraw, pGC, x, y, count, chars) + DrawablePtr pDraw; + GCPtr pGC; + int x, y; + int count; + char *chars; + +</programlisting></blockquote> +PolyText8 works like ImageText8, except it draws with +the current fill style for special effects such as +shaded text. +See the X protocol specification for more details.</para> +<para> +An example implementation is miPolyText8() in Xserver/mi/mipolytext.c.</para> +<para> +<blockquote><programlisting> + + int pGC->ops->PolyText16(pDraw, pGC, x, y, count, chars) + DrawablePtr pDraw; + GCPtr pGC; + int x, y; + int count; + unsigned short *chars; + + void pGC->ops->ImageText16(pDraw, pGC, x, y, count, chars) + DrawablePtr pDraw; + GCPtr pGC; + int x, y; + int count; + unsigned short *chars; + +</programlisting></blockquote> +These two routines are the same as the "8" versions, +except that they are for 16-bit character codes (useful +for oriental writing systems).</para> +<para> +The primary difference is in the way the character information is +looked up. The 8-bit and the 16-bit versions obviously have different +kinds of character values to look up; the main goal of the lookup is +to provide a pointer to the CharInfo structs for the characters to +draw and to pass these pointers to the Glyph routines. Given a +CharInfo struct, lower-level software can draw the glyph desired with +little concern for other characteristics of the font.</para> +<para> +16-bit character fonts have a row-and-column scheme, where the 2bytes +of the character code constitute the row and column in a square matrix +of CharInfo structs. Each font has row and column minimum and maximum +values; the CharInfo structures form a two-dimensional matrix.</para> +<para> +Example implementations are miPolyText16() and +miImageText16() in Xserver/mi/mipolytext.c.</para> +<para> +See the X protocol specification for more details on these graphic operations.</para> +<para> +There is a hook in the GC ops, called LineHelper, that used to be used in the +sample implementation by the code for wide lines. It no longer servers any +purpose in the sample servers, but still exists, #ifdef'ed by NEED_LINEHELPER, +in case someone needs it.</para> +</section> +</section> +<section> + <title>Pixblit Procedures</title> +<para> +The Drawing Primitive functions must be defined for your server. +One possible way to do this is to use the mi routines from the sample server. +If you choose to use the mi routines (even part of them!) you must implement +these Pixblit routines. +These routines read and write pixel values +and deal directly with the image data.</para> +<para> +The Pixblit routines for the sample server are part of the "fb" +routines. As with the mi routines, the fb routines are +portable but are not as portable as the mi routines.</para> +<para> +The fb subsystem is a depth-independent framebuffer core, capable of +operating at any depth from 1 to 32, based on the depth of the window +or pixmap it is currently operating on. In particular, this means it +can support pixmaps of multiple depths on the same screen. It supplies +both Pixblit routines and higher-level optimized implementations of the +Drawing Primitive routines. It does make the assumption that the pixel +data it touches is available in the server's address space.</para> +<para> +In other words, if you have a "normal" frame buffer type display, you +can probably use the fb code, and the mi code. If you +have a stranger hardware, you will have to supply your own Pixblit +routines, but you can use the mi routines on top of them. If you have +better ways of doing some of the Drawing Primitive functions, then you +may want to supply some of your own Drawing Primitive routines. (Even +people who write their own Drawing Primitives save at least some of +the mi code for certain special cases that their hardware or library +or fancy algorithm does not handle.)</para> +<para> +The client, DIX, and the machine-independent routines do not carry the +final responsibility of clipping. They all depend upon the Pixblit +routines to do their clipping for them. The rule is, if you touch the +frame buffer, you clip.</para> +<para> +(The higher level routines may decide to clip at a high level, but +this is only for increased performance and cannot substitute for +bottom-level clipping. For instance, the mi routines, DIX, or the +client may decide to check all character strings to be drawn and chop +off all characters that would not be displayed. If so, it must retain +the character on the edge that is partly displayed so that the Pixblit +routines can clip off precisely at the right place.)</para> +<para> +To make this easier, all of the reasons to clip can be combined into +one region in your ValidateGC procedure. You take this composite clip +region with you into the Pixblit routines. (The sample server does +this.)</para> +<para> +Also, FillSpans() has to apply tile and stipple patterns. The +patterns are all aligned to the window origin so that when two people +write patches that are contiguous, they will merge nicely. (Really, +they are aligned to the patOrg point in the GC. This defaults to (0, +0) but can be set by the client to anything.)</para> +<para> +However, the mi routines can translate (relocate) the points from +window-relative to screen-relative if desired. If you set the +miTranslate field in the GC (set it in the CreateGC or ValidateGC +routine), then the mi output routines will translate all coordinates. +If it is false, then the coordinates will be passed window-relative. +Screens with no hardware translation will probably set miTranslate to +TRUE, so that geometry (e.g. polygons, rectangles) can be translated, +rather than having the resulting list of scanlines translated; this is +good because the list vertices in a drawing request will generally be +much smaller than the list of scanlines it produces. Similarly, +hardware that does translation can set miTranslate to FALSE, and avoid +the extra addition per vertex, which can be (but is not always) +important for getting the highest possible performance. (Contrast the +behavior of GetSpans, which is not expected to be called as often, and +so has different constraints.) The miTranslate field is settable in +each GC, if , for example, you are mixing several kinds of +destinations (offscreen pixmaps, main memory pixmaps, backing store, +and windows), all of which have different requirements, on one screen.</para> +<para> +As with other drawing routines, there are fields in the GC to direct +higher code to the correct routine to execute for each function. In +this way, you can optimize for special cases, for example, drawing +solids versus drawing stipples.</para> +<para> +The Pixblit routines are broken up into three sets. The Span routines +simply fill in rows of pixels. The Glyph routines fill in character +glyphs. The PushPixels routine is a three-input bitblt for more +sophisticated image creation.</para> +<para> +It turns out that the Glyph and PushPixels routines actually have a +machine-independent implementation that depends upon the Span +routines. If you are really pressed for time, you can use these +versions, although they are quite slow.</para> +<section> +<title>Span Routines</title> +<para> +For these routines, all graphic operations have been reduced to "spans." +A span is a horizontal row of pixels. +If you can design these routines which write into and read from +rows of pixels at a time, you can use the mi routines.</para> +<para> +Each routine takes +a destination drawable to draw into, a GC to use while drawing, +the number of spans to do, and two pointers to arrays that indicate the list +of starting points and the list of widths of spans.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->FillSpans(dst, pGC, nSpans, pPoints, pWidths, sorted) + DrawablePtr dst; + GCPtr pGC; + int nSpans; + DDXPointPtr pPoints; + int *pWidths; + int sorted; + +</programlisting></blockquote> +FillSpans should fill horizontal rows of pixels with +the appropriate patterns, stipples, etc., +based on the values in the GC. +The starting points are in the array at pPoints; the widths are in pWidths. +If sorted is true, the scan lines are in increasing y order, in which case +you may be able to make assumptions and optimizations.</para> +<para> +GC components: alu, clipOrg, clientClip, and fillStyle.</para> +<para> +GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg +(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple); +and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para> +<para> +<blockquote><programlisting> + + void pGC->ops->SetSpans(pDrawable, pGC, pSrc, ppt, pWidths, nSpans, sorted) + DrawablePtr pDrawable; + GCPtr pGC; + char *pSrc; + DDXPointPtr pPoints; + int *pWidths; + int nSpans; + int sorted; + +</programlisting></blockquote> +For each span, this routine should copy pWidths bits from pSrc to +pDrawable at pPoints using the raster-op from the GC. +If sorted is true, the scan lines are in increasing y order. +The pixels in pSrc are +padded according to the screen's padding rules. +These +can be used to support +interesting extension libraries, for example, shaded primitives. It does not +use the tile and stipple.</para> +<para> +GC components: alu, clipOrg, and clientClip</para> +<para> +The above functions are expected to handle all modifiers in the current +GC. Therefore, it is expedient to have +different routines to quickly handle common special cases +and reload the procedure pointers +at validate time, as with the other output functions.</para> +<para> +<blockquote><programlisting> + + void pScreen->GetSpans(pDrawable, wMax, pPoints, pWidths, nSpans) + DrawablePtr pDrawable; + int wMax; + DDXPointPtr pPoints; + int *pWidths; + int nSpans; + char *pDst; + +</programlisting></blockquote> +For each span, GetSpans gets bits from the drawable starting at pPoints +and continuing for pWidths bits. +Each scanline returned will be server-scanline padded. +The routine can return NULL if memory cannot be allocated to hold the +result.</para> +<para> +GetSpans never translates -- for a window, the coordinates are already +screen-relative. Consider the case of hardware that doesn't do +translation: the mi code that calls ddX will translate each shape +(rectangle, polygon,. etc.) before scan-converting it, which requires +many fewer additions that having GetSpans translate each span does. +Conversely, consider hardware that does translate: it can set its +translation point to (0, 0) and get each span, and the only penalty is +the small number of additions required to translate each shape being +scan-converted by the calling code. Contrast the behavior of +FillSpans and SetSpans (discussed above under miTranslate), which are +expected to be used more often.</para> +<para> +Thus, the penalty to hardware that does hardware translation is +negligible, and code that wants to call GetSpans() is greatly +simplified, both for extensions and the machine-independent core +implementation.</para> +<section> + <title>Glyph Routines</title> +<para> +The Glyph routines draw individual character glyphs for text drawing requests.</para> +<para> +You have a choice in implementing these routines. You can use the mi +versions; they depend ultimately upon the span routines. Although +text drawing will work, it will be very slow.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PolyGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase) + DrawablePtr pDrawable; + GCPtr pGC; + int x , y; + unsigned int nglyph; + CharInfoRec **ppci; /* array of character info */ + pointer unused; /* unused since R5 */ + +</programlisting></blockquote> +GC components: alu, clipOrg, clientClip, font, and fillStyle.</para> +<para> +GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg +(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple); +and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para> +<para> +<blockquote><programlisting> + + void pGC->ops->ImageGlyphBlt(pDrawable, pGC, x, y, nglyph, ppci, pglyphBase) + DrawablePtr pDrawable; + GCPtr pGC; + int x , y; + unsigned int nglyph; + CharInfoRec **ppci; /* array of character info */ + pointer unused; /* unused since R5 */ + +</programlisting></blockquote> +GC components: clipOrg, clientClip, font, fgPixel, bgPixel</para> +<para> +These routines must copy the glyphs defined by the bitmaps in +pglyphBase and the font metrics in ppci to the DrawablePtr, pDrawable. +The poly routine follows all fill, stipple, and tile rules. The image +routine simply blasts the glyph onto the glyph's rectangle, in +foreground and background colors.</para> +<para> +More precisely, the Image routine fills the character rectangle with +the background color, and then the glyph is applied in the foreground +color. The glyph can extend outside of the character rectangle. +ImageGlyph() is used for terminal emulators and informal text purposes +such as button labels.</para> +<para> +The exact specification for the Poly routine is that the glyph is +painted with the current fill style. The character rectangle is +irrelevant for this operation. PolyText, at a higher level, includes +facilities for font changes within strings and such; it is to be used +for WYSIWYG word processing and similar systems.</para> +<para> +Both of these routines must clip themselves to the overall clipping region.</para> +<para> +Example implementations in mi are miPolyGlyphBlt() and +miImageGlyphBlt() in Xserver/mi/miglblt.c.</para> +</section> +<section> +<title>PushPixels routine</title> +<para> +The PushPixels routine writes the current fill style onto the drawable +in a certain shape defined by a bitmap. PushPixels is equivalent to +using a second stipple. You can thing of it as pushing the fillStyle +through a stencil. PushPixels is not used by any of the mi rendering code, +but is used by the mi software cursor code. +<blockquote><para> + Suppose the stencil is: 00111100 + and the stipple is: 10101010 + PushPixels result: 00101000 +</para></blockquote> +</para> +<para> +You have a choice in implementing this routine. +You can use the mi version which depends ultimately upon FillSpans(). +Although it will work, it will be slow.</para> +<para> +<blockquote><programlisting> + + void pGC->ops->PushPixels(pGC, pBitMap, pDrawable, dx, dy, xOrg, yOrg) + GCPtr pGC; + PixmapPtr pBitMap; + DrawablePtr pDrawable; + int dx, dy, xOrg, yOrg; + +</programlisting></blockquote> +GC components: alu, clipOrg, clientClip, and fillStyle.</para> +<para> +GC mode-dependent components: fgPixel (for fillStyle Solid); tile, patOrg +(for fillStyle Tile); stipple, patOrg, fgPixel (for fillStyle Stipple); +and stipple, patOrg, fgPixel and bgPixel (for fillStyle OpaqueStipple).</para> +<para> +PushPixels applys the foreground color, tile, or stipple from the pGC +through a stencil onto pDrawable. pBitMap points to a stencil (of +which we use an area dx wide by dy high), which is oriented over the +drawable at xOrg, yOrg. Where there is a 1 bit in the bitmap, the +destination is set according to the current fill style. Where there +is a 0 bit in the bitmap, the destination is left the way it is.</para> +<para> +This routine must clip to the overall clipping region.</para> +<para> +An Example implementation is miPushPixels() in Xserver/mi/mipushpxl.c.</para> +</section> +</section> +</section> +<section> + <title>Shutdown Procedures</title> +<para> +<blockquote><programlisting> + void AbortDDX(enum ExitCode error) + void ddxGiveUp(enum ExitCode error) +</programlisting></blockquote> +Some hardware may require special work to be done before the server +exits so that it is not left in an intermediate state. As explained +in the OS layer, FatalError() will call AbortDDX() just before +terminating the server. In addition, ddxGiveUp() will be called just +before terminating the server on a "clean" death. What AbortDDX() and +ddxGiveUP do is left unspecified, only that stubs must exist in the +ddx layer. It is up to local implementors as to what they should +accomplish before termination.</para> +<section> + <title>Command Line Procedures</title> +<para> +<blockquote><programlisting> + int ddxProcessArgument(argc, argv, i) + int argc; + char *argv[]; + int i; + + void + ddxUseMsg() + +</programlisting></blockquote> +You should write these routines to deal with device-dependent command line +arguments. The routine ddxProcessArgument() is called with the command line, +and the current index into argv; you should return zero if the argument +is not a device-dependent one, and otherwise return a count of the number +of elements of argv that are part of this one argument. For a typical +option (e.g., "-realtime"), you should return the value one. This +routine gets called before checks are made against device-independent +arguments, so it is possible to peek at all arguments or to override +device-independent argument processing. You can document the +device-dependent arguments in ddxUseMsg(), which will be +called from UseMsg() after printing out the device-independent arguments.</para> +</section> +</section> +<section id="wrappers_and_privates"> + <title>Wrappers and Privates</title> +<para> +Two new extensibility concepts have been developed for release 4, Wrappers +and devPrivates. These replace the R3 GCInterest queues, which were not a +general enough mechanism for many extensions and only provided hooks into a +single data structure. devPrivates have been revised substantially for +X.Org X server release 1.5, and updated again for the 1.9 release.</para> +<section> + <title>devPrivates</title> +<para> +devPrivates provides a way to attach arbitrary private data to various server structures. +Any structure which contains a <structfield>devPrivates</structfield> field of +type <type>PrivateRec</type> supports this mechanism. Some structures allow +allocating space for private data after some objects have been created, others +require all space allocations be registered before any objects of that type +are created. <filename class="headerfile">Xserver/include/privates.h</filename> +lists which of these cases applies to each structure containing +<structfield>devPrivates</structfield>.</para> + +<para> +To request private space, use +<blockquote><programlisting> + Bool dixRegisterPrivateKey(DevPrivateKey key, DevPrivateType type, unsigned size); +</programlisting></blockquote> +The first argument is a pointer to a <type>DevPrivateKeyRec</type> which +will serve as the unique identifier for the private data. Typically this is +the address of a static <type>DevPrivateKeyRec</type> in your code. +The second argument is the class of objects for which this key will apply. +The third argument is the size of the space being requested, or +<constant>0</constant> to only allocate a pointer that the caller will manage. +If space is requested, this space will be automatically freed when the object +is destroyed. Note that a call to <function>dixSetPrivate</function> +that changes the pointer value may cause the space to be unreachable by the caller, however it will still be automatically freed. +The function returns <literal>TRUE</literal> unless memory allocation fails. +If the function is called more than once on the same key, all calls must use +the same value for <type>size</type> or the server will abort.</para> + +<para> +To request per-screen private space in an object, use +<blockquote><programlisting> + Bool dixRegisterScreenPrivateKey(DevScreenPrivateKey key, ScreenPtr pScreen, DevPrivateType type, unsigned size); +</programlisting></blockquote> +The <parameter>type</parameter> and <parameter>size</parameter> arguments are +the same as those to <function>dixRegisterPrivateKey</function> but this +function ensures the given <parameter>key</parameter> exists on objects of +the specified type with distinct storage for the given +<parameter>pScreen</parameter>. The key is usable on ScreenPrivate variants +that are otherwise equivalent to the following Private functions.</para> + +<para> +To attach a piece of private data to an object, use: +<blockquote><programlisting> + void dixSetPrivate(PrivateRec **privates, const DevPrivateKey key, pointer val) +</programlisting></blockquote> +The first argument is the address of the <structfield>devPrivates</structfield> +field in the target structure. This field is managed privately by the DIX +layer and should not be directly modified. The second argument is a pointer +to the <type>DevPrivateKeyRec</type> which you registered with +<function>dixRegisterPrivateKey</function> or allocated with +<function>dixCreatePrivateKey</function>. Only one +piece of data with a given key can be attached to an object, and in most cases +each key is specific to the type of object it was registered for. (An +exception is the PRIVATE_XSELINUX class which applies to multiple object types.) +The third argument is the value to store.</para> +<para> +If private data with the given key is already associated with the object, +<function>dixSetPrivate</function> will overwrite the old value with the +new one.</para> + +<para> +To look up a piece of private data, use one of: +<blockquote><programlisting> + pointer dixLookupPrivate(PrivateRec **privates, const DevPrivateKey key) + pointer *dixLookupPrivateAddr(PrivateRec **privates, const DevPrivateKey key) +</programlisting></blockquote> +The first argument is the address of the <structfield>devPrivates</structfield> field +in the target structure. The second argument is the key to look up. +If a non-zero size was given when the key was registered, or if private data +with the given key is already associated with the object, then +<function>dixLookupPrivate</function> will return the pointer value +while <function>dixLookupPrivateAddr</function> +will return the address of the pointer.</para> + +<para> +When implementing new server resource objects that support devPrivates, there +are four steps to perform: +Add a type value to the <type>DevPrivateType</type> enum in +<filename class="headerfile">Xserver/include/privates.h</filename>, +declare a field of type <type>PrivateRec *</type> in your structure; +initialize this field to <literal>NULL</literal> when creating any objects; and +when freeing any objects call the <function>dixFreePrivates</function> or +<function>dixFreeObjectWithPrivates</function> function.</para> +</section> +<section> + <title>Wrappers</title> +<para> +Wrappers are not a body of code, nor an interface spec. They are, instead, +a technique for hooking a new module into an existing calling sequence. +There are limitations on other portions of the server implementation which +make using wrappers possible; limits on when specific fields of data +structures may be modified. They are intended as a replacement for +GCInterest queues, which were not general enough to support existing +modules; in particular software cursors needed more +control over the activity. The general mechanism for using wrappers is: +<blockquote><programlisting> +privateWrapperFunction (object, ...) + ObjectPtr object; +{ + pre-wrapped-function-stuff ... + + object->functionVector = dixLookupPrivate(&object->devPrivates, privateKey); + (*object->functionVector) (object, ...); + /* + * this next line is occasionally required by the rules governing + * wrapper functions. Always using it will not cause problems. + * Not using it when necessary can cause severe troubles. + */ + dixSetPrivate(&object->devPrivates, privateKey, object->functionVector); + object->functionVector = privateWrapperFunction; + + post-wrapped-function-stuff ... +} + +privateInitialize (object) + ObjectPtr object; +{ + dixSetPrivate(&object->devPrivates, privateKey, object->functionVector); + object->functionVector = privateWrapperFunction; +} +</programlisting></blockquote> +</para> +<para> +Thus the privateWrapperFunction provides hooks for performing work both +before and after the wrapped function has been called; the process of +resetting the functionVector is called "unwrapping" while the process of +fetching the wrapped function and replacing it with the wrapping function +is called "wrapping". It should be clear that GCInterest queues could +be emulated using wrappers. In general, any function vectors contained in +objects can be wrapped, but only vectors in GCs and Screens have been tested.</para> +<para> +Wrapping screen functions is quite easy; each vector is individually +wrapped. Screen functions are not supposed to change after initialization, +so rewrapping is technically not necessary, but causes no problems.</para> +<para> +Wrapping GC functions is a bit more complicated. GC's have two tables of +function vectors, one hanging from gc->ops and the other from gc->funcs, which +should be initially wrapped from a CreateGC wrapper. Wrappers should modify +only table pointers, not the contents of the tables, as they +may be shared by more than one GC (and, in the case of funcs, are probably +shared by all gcs). Your func wrappers may change the GC funcs or ops +pointers, and op wrappers may change the GC op pointers but not the funcs.</para> +<para> +Thus, the rule for GC wrappings is: wrap the funcs from CreateGC and, in each +func wrapper, unwrap the ops and funcs, call down, and re-wrap. In each op +wrapper, unwrap the ops, call down, and rewrap afterwards. Note that in +re-wrapping you must save out the pointer you're replacing again. This way the +chain will be maintained when wrappers adjust the funcs/ops tables they use.</para> +</section> +</section> +<section> + <title>Work Queue</title> +<para> +To queue work for execution when all clients are in a stable state (i.e. +just before calling select() in WaitForSomething), call: +<blockquote><programlisting> + Bool QueueWorkProc(function,client,closure) + Bool (*function)(); + ClientPtr client; + pointer closure; +</programlisting></blockquote> +</para> +<para> +When the server is about to suspend itself, the given function will be +executed: +<blockquote><programlisting> + (*function) (client, closure) +</programlisting></blockquote> +</para> +<para> +Neither client nor closure are actually used inside the work queue routines.</para> +</section> +</section> +<section> + <title>Summary of Routines</title> +<para> +This is a summary of the routines discussed in this document. +The procedure names are in alphabetical order. +The Struct is the structure it is attached to; if blank, this +procedure is not attached to a struct and must be named as shown. +The sample server provides implementations in the following +categories. Notice that many of the graphics routines have both +mi and fb implementations.</para> +<para> +<itemizedlist> +<listitem><para>dix portable to all systems; do not attempt to rewrite (Xserver/dix)</para></listitem> +<listitem><para>os routine provided in Xserver/os or Xserver/include/os.h</para></listitem> +<listitem><para>ddx frame buffer dependent (examples in Xserver/fb)</para></listitem> +<listitem><para>mi routine provided in Xserver/mi</para></listitem> +<listitem><para>hd hardware dependent (examples in many Xserver/hw directories)</para></listitem> +<listitem><para>none not implemented in sample implementation</para></listitem> +</itemizedlist> +</para> + <table frame="all" id="routines-1"> + <title>Server Routines (Page 1)</title> + <tgroup cols='3' align='left' colsep='1' rowsep='1'> + <thead> + <row> + <entry>Procedure</entry> + <entry>Port</entry> + <entry>Struct</entry> + </row> + </thead> + <tbody> +<row><entry><function>ALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>AbortDDX</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>AddCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>AddEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>AddInputDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>AddScreen</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>AdjustWaitForDelay</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>Bell</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row> +<row><entry><function>ChangeClip</function></entry><entry><literal>mi</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>ChangeGC</function></entry><entry><literal></literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>ChangeWindowAttributes</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>ClearToBackground</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row> +<row><entry><function>ClientAuthorized</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>ClientSignal</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>ClientSleep</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>ClientWakeup</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>ClipNotify</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CloseScreen</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>ConstrainCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CopyArea</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>CopyGCDest</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>CopyGCSource</function></entry><entry><literal>none</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>CopyPlane</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>CopyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Window</para></entry></row> +<row><entry><function>CreateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CreateCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>CreatePixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CreateScreenResources</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CreateWellKnowSockets</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>CreateWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>CursorLimits</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>DEALLOCATE_LOCAL</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>DeleteCallback</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>DeleteCallbackList</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>DestroyClip</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>DestroyGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>DestroyPixmap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>DestroyWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>DisplayCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>Error</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>ErrorF</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>FatalError</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>FillPolygon</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>FillSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>FlushAllOutput</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>FlushIfCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>FreeScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>GetImage</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>GetMotionEvents</function></entry><entry><literal>hd</literal></entry><entry><para>Device</para></entry></row> +<row><entry><function>GetScratchPixmapHeader</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>GetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>GetStaticColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> + </tbody> + </tgroup> + </table> + + <table frame="all" id="routines-2"> + <title>Server Routines (Page 2)</title> + <tgroup cols='3' align='left' colsep='1' rowsep='1'> + <thead> + <row> + <entry>Procedure</entry> + <entry>Port</entry> + <entry>Struct</entry> + </row> + </thead> + <tbody> +<row><entry><function>ImageGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>ImageText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>ImageText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>InitInput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>InitKeyboardDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>InitOutput</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>InitPointerDeviceStruct</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>InsertFakeRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>InstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>Intersect</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>Inverse</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>LegalModifier</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>LineHelper</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>ListInstalledColormaps</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>LookupKeyboardDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>LookupPointerDevice</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>ModifyPixmapHeader</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>NextAvailableClient</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>OsInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>PaintWindowBackground</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row> +<row><entry><function>PaintWindowBorder</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row> +<row><entry><function>PointerNonInterestBox</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>PointInRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>PolyArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyFillArc</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyFillRect</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyGlyphBlt</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>Polylines</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyPoint</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyRectangle</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolySegment</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyText16</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PolyText8</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PositionWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>ProcessInputEvents</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>PushPixels</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>PutImage</function></entry><entry><literal>mi</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>QueryBestSize</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>ReadRequestFromClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>RealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RecolorCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RectIn</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionCopy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionCreate</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionDestroy</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionExtents</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionNotEmpty</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>RegionReset</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>ResolveColor</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> + </tbody> + </tgroup> + </table> + + <table frame="all" id="routines-3"> + <title>Server Routines (Page 3)</title> + <tgroup cols='3' align='left' colsep='1' rowsep='1'> + <thead> + <row> + <entry>Procedure</entry> + <entry>Port</entry> + <entry>Struct</entry> + </row> + </thead> + <tbody> +<row><entry><function>RemoveEnabledDevice</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>ResetCurrentRequest</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>SaveScreen</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>SetCriticalOutputPending</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>SetCursorPosition</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>SetInputCheck</function></entry><entry><literal>dix</literal></entry><entry><para></para></entry></row> +<row><entry><function>SetSpans</function></entry><entry><literal>ddx</literal></entry><entry><para>GC op</para></entry></row> +<row><entry><function>StoreColors</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>Subtract</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>TimerCancel</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimerCheck</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimerForce</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimerFree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimerInit</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimerSet</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>TimeSinceLastInputEvent</function></entry><entry><literal>hd</literal></entry><entry><para></para></entry></row> +<row><entry><function>TranslateRegion</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>UninstallColormap</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>Union</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>UnrealizeCursor</function></entry><entry><literal>hd</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>UnrealizeFont</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>UnrealizeWindow</function></entry><entry><literal>ddx</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>ValidateGC</function></entry><entry><literal>ddx</literal></entry><entry><para>GC func</para></entry></row> +<row><entry><function>ValidateTree</function></entry><entry><literal>mi</literal></entry><entry><para>Screen</para></entry></row> +<row><entry><function>WaitForSomething</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>WindowExposures</function></entry><entry><literal>mi</literal></entry><entry><para>Window</para></entry></row> +<row><entry><function>WriteToClient</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>Xalloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>Xfree</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> +<row><entry><function>Xrealloc</function></entry><entry><literal>os</literal></entry><entry><para></para></entry></row> + </tbody> + </tgroup> + </table> +</section> +</article> diff --git a/xorg-server/hw/dmx/dmxinit.c b/xorg-server/hw/dmx/dmxinit.c index 5dce93028..a8399bc75 100644 --- a/xorg-server/hw/dmx/dmxinit.c +++ b/xorg-server/hw/dmx/dmxinit.c @@ -1,1029 +1,1029 @@ -/*
- * Copyright 2001-2004 Red Hat Inc., Durham, North Carolina.
- *
- * All Rights Reserved.
- *
- * 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 on 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:
- *
- * The above copyright notice and this permission notice (including the
- * next paragraph) shall be included in all copies or substantial
- * portions of the Software.
- *
- * 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
- * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS
- * 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.
- */
-
-/*
- * Authors:
- * Kevin E. Martin <kem@redhat.com>
- * David H. Dawes <dawes@xfree86.org>
- * Rickard E. (Rik) Faith <faith@redhat.com>
- *
- */
-
-/** \file
- * Provide expected functions for initialization from the ddx layer and
- * global variables for the DMX server. */
-
-#ifdef HAVE_DMX_CONFIG_H
-#include <dmx-config.h>
-#endif
-
-#include "dmx.h"
-#include "dmxinit.h"
-#include "dmxsync.h"
-#include "dmxlog.h"
-#include "dmxinput.h"
-#include "dmxscrinit.h"
-#include "dmxcursor.h"
-#include "dmxfont.h"
-#include "config/dmxconfig.h"
-#include "dmxcb.h"
-#include "dmxprop.h"
-#include "dmxstat.h"
-#include "dmxpict.h"
-
-#include <X11/Xos.h> /* For gettimeofday */
-#include "dixstruct.h"
-#ifdef PANORAMIX
-#include "panoramiXsrv.h"
-#endif
-
-#include <signal.h> /* For SIGQUIT */
-
-#ifdef GLXEXT
-#include <GL/glx.h>
-#include <GL/glxint.h>
-#include "dmx_glxvisuals.h"
-#include <X11/extensions/Xext.h>
-#include <X11/extensions/extutil.h>
-#endif /* GLXEXT */
-
-/* Global variables available to all Xserver/hw/dmx routines. */
-int dmxNumScreens;
-DMXScreenInfo *dmxScreens;
-
-int dmxNumInputs;
-DMXInputInfo *dmxInputs;
-
-int dmxShadowFB = FALSE;
-
-XErrorEvent dmxLastErrorEvent;
-Bool dmxErrorOccurred = FALSE;
-
-char *dmxFontPath = NULL;
-
-Bool dmxOffScreenOpt = TRUE;
-
-Bool dmxSubdividePrimitives = TRUE;
-
-Bool dmxLazyWindowCreation = TRUE;
-
-Bool dmxUseXKB = TRUE;
-
-int dmxDepth = 0;
-
-#ifndef GLXEXT
-static Bool dmxGLXProxy = FALSE;
-#else
-Bool dmxGLXProxy = TRUE;
-
-Bool dmxGLXSwapGroupSupport = TRUE;
-
-Bool dmxGLXSyncSwap = FALSE;
-
-Bool dmxGLXFinishSwap = FALSE;
-#endif
-
-Bool dmxIgnoreBadFontPaths = FALSE;
-
-Bool dmxAddRemoveScreens = FALSE;
-
-/* dmxErrorHandler catches errors that occur when calling one of the
- * back-end servers. Some of this code is based on _XPrintDefaultError
- * in xc/lib/X11/XlibInt.c */
-static int dmxErrorHandler(Display *dpy, XErrorEvent *ev)
-{
-#define DMX_ERROR_BUF_SIZE 256
- /* RATS: these buffers are only used in
- * length-limited calls. */
- char buf[DMX_ERROR_BUF_SIZE];
- char request[DMX_ERROR_BUF_SIZE];
- _XExtension *ext = NULL;
-
- dmxErrorOccurred = TRUE;
- dmxLastErrorEvent = *ev;
-
- XGetErrorText(dpy, ev->error_code, buf, sizeof(buf));
- dmxLog(dmxWarning, "dmxErrorHandler: %s\n", buf);
-
- /* Find major opcode name */
- if (ev->request_code < 128) {
- XmuSnprintf(request, sizeof(request), "%d", ev->request_code);
- XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf));
- } else {
- for (ext = dpy->ext_procs;
- ext && ext->codes.major_opcode != ev->request_code;
- ext = ext->next);
- if (ext) strncpy(buf, ext->name, sizeof(buf));
- else buf[0] = '\0';
- }
- dmxLog(dmxWarning, " Major opcode: %d (%s)\n",
- ev->request_code, buf);
-
- /* Find minor opcode name */
- if (ev->request_code >= 128 && ext) {
- XmuSnprintf(request, sizeof(request), "%d", ev->request_code);
- XmuSnprintf(request, sizeof(request), "%s.%d",
- ext->name, ev->minor_code);
- XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf));
- dmxLog(dmxWarning, " Minor opcode: %d (%s)\n",
- ev->minor_code, buf);
- }
-
- /* Provide value information */
- switch (ev->error_code) {
- case BadValue:
- dmxLog(dmxWarning, " Value: 0x%x\n",
- ev->resourceid);
- break;
- case BadAtom:
- dmxLog(dmxWarning, " AtomID: 0x%x\n",
- ev->resourceid);
- break;
- default:
- dmxLog(dmxWarning, " ResourceID: 0x%x\n",
- ev->resourceid);
- break;
- }
-
- /* Provide serial number information */
- dmxLog(dmxWarning, " Failed serial number: %d\n",
- ev->serial);
- dmxLog(dmxWarning, " Current serial number: %d\n",
- dpy->request);
- return 0;
-}
-
-#ifdef GLXEXT
-static int dmxNOPErrorHandler(Display *dpy, XErrorEvent *ev)
-{
- return 0;
-}
-#endif
-
-Bool dmxOpenDisplay(DMXScreenInfo *dmxScreen)
-{
- if (!(dmxScreen->beDisplay = XOpenDisplay(dmxScreen->name)))
- return FALSE;
-
- dmxPropertyDisplay(dmxScreen);
- return TRUE;
-}
-
-void dmxSetErrorHandler(DMXScreenInfo *dmxScreen)
-{
- XSetErrorHandler(dmxErrorHandler);
-}
-
-static void dmxPrintScreenInfo(DMXScreenInfo *dmxScreen)
-{
- XWindowAttributes attribs;
- int ndepths = 0, *depths = NULL;
- int i;
- Display *dpy = dmxScreen->beDisplay;
- Screen *s = DefaultScreenOfDisplay(dpy);
- int scr = DefaultScreen(dpy);
-
- XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs);
- if (!(depths = XListDepths(dpy, scr, &ndepths))) ndepths = 0;
-
- dmxLogOutput(dmxScreen, "Name of display: %s\n", DisplayString(dpy));
- dmxLogOutput(dmxScreen, "Version number: %d.%d\n",
- ProtocolVersion(dpy), ProtocolRevision(dpy));
- dmxLogOutput(dmxScreen, "Vendor string: %s\n", ServerVendor(dpy));
- if (!strstr(ServerVendor(dpy), "XFree86")) {
- dmxLogOutput(dmxScreen, "Vendor release: %d\n", VendorRelease(dpy));
- } else {
- /* This code based on xdpyinfo.c */
- int v = VendorRelease(dpy);
- int major = -1, minor = -1, patch = -1, subpatch = -1;
-
- if (v < 336)
- major = v / 100, minor = (v / 10) % 10, patch = v % 10;
- else if (v < 3900) {
- major = v / 1000;
- minor = (v / 100) % 10;
- if (((v / 10) % 10) || (v % 10)) {
- patch = (v / 10) % 10;
- if (v % 10) subpatch = v % 10;
- }
- } else if (v < 40000000) {
- major = v / 1000;
- minor = (v / 10) % 10;
- if (v % 10) patch = v % 10;
- } else {
- major = v / 10000000;
- minor = (v / 100000) % 100;
- patch = (v / 1000) % 100;
- if (v % 1000) subpatch = v % 1000;
- }
- dmxLogOutput(dmxScreen, "Vendor release: %d (XFree86 version: %d.%d",
- v, major, minor);
- if (patch > 0) dmxLogOutputCont(dmxScreen, ".%d", patch);
- if (subpatch > 0) dmxLogOutputCont(dmxScreen, ".%d", subpatch);
- dmxLogOutputCont(dmxScreen, ")\n");
- }
-
-
- dmxLogOutput(dmxScreen, "Dimensions: %dx%d pixels\n",
- attribs.width, attribs.height);
- dmxLogOutput(dmxScreen, "%d depths on screen %d: ", ndepths, scr);
- for (i = 0; i < ndepths; i++)
- dmxLogOutputCont(dmxScreen, "%c%d", i ? ',' : ' ', depths[i]);
- dmxLogOutputCont(dmxScreen, "\n");
- dmxLogOutput(dmxScreen, "Depth of root window: %d plane%s (%d)\n",
- attribs.depth, attribs.depth == 1 ? "" : "s",
- DisplayPlanes(dpy, scr));
- dmxLogOutput(dmxScreen, "Number of colormaps: %d min, %d max\n",
- MinCmapsOfScreen(s), MaxCmapsOfScreen(s));
- dmxLogOutput(dmxScreen, "Options: backing-store %s, save-unders %s\n",
- (DoesBackingStore (s) == NotUseful) ? "no" :
- ((DoesBackingStore (s) == Always) ? "yes" : "when mapped"),
- DoesSaveUnders (s) ? "yes" : "no");
- dmxLogOutput(dmxScreen, "Window Manager running: %s\n",
- (dmxScreen->WMRunningOnBE) ? "yes" : "no");
-
- if (dmxScreen->WMRunningOnBE) {
- dmxLogOutputWarning(dmxScreen,
- "Window manager running "
- "-- colormaps not supported\n");
- }
- XFree(depths);
-}
-
-void dmxGetScreenAttribs(DMXScreenInfo *dmxScreen)
-{
- XWindowAttributes attribs;
- Display *dpy = dmxScreen->beDisplay;
-#ifdef GLXEXT
- int dummy;
-#endif
-
- XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs);
-
- dmxScreen->beWidth = attribs.width;
- dmxScreen->beHeight = attribs.height;
-
- /* Fill in missing geometry information */
- if (dmxScreen->scrnXSign < 0) {
- if (dmxScreen->scrnWidth) {
- dmxScreen->scrnX = (attribs.width - dmxScreen->scrnWidth
- - dmxScreen->scrnX);
- } else {
- dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX;
- dmxScreen->scrnX = 0;
- }
- }
- if (dmxScreen->scrnYSign < 0) {
- if (dmxScreen->scrnHeight) {
- dmxScreen->scrnY = (attribs.height - dmxScreen->scrnHeight
- - dmxScreen->scrnY);
- } else {
- dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY;
- dmxScreen->scrnY = 0;
- }
- }
- if (!dmxScreen->scrnWidth)
- dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX;
- if (!dmxScreen->scrnHeight)
- dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY;
-
- if (!dmxScreen->rootWidth) dmxScreen->rootWidth = dmxScreen->scrnWidth;
- if (!dmxScreen->rootHeight) dmxScreen->rootHeight = dmxScreen->scrnHeight;
- if (dmxScreen->rootWidth + dmxScreen->rootX > dmxScreen->scrnWidth)
- dmxScreen->rootWidth = dmxScreen->scrnWidth - dmxScreen->rootX;
- if (dmxScreen->rootHeight + dmxScreen->rootY > dmxScreen->scrnHeight)
- dmxScreen->rootHeight = dmxScreen->scrnHeight - dmxScreen->rootY;
-
- /* FIXME: Get these from the back-end server */
- dmxScreen->beXDPI = 75;
- dmxScreen->beYDPI = 75;
-
- dmxScreen->beDepth = attribs.depth; /* FIXME: verify that this
- * works always. In
- * particular, this will work
- * well for depth=16, will fail
- * because of colormap issues
- * at depth 8. More work needs
- * to be done here. */
-
- if (dmxScreen->beDepth <= 8) dmxScreen->beBPP = 8;
- else if (dmxScreen->beDepth <= 16) dmxScreen->beBPP = 16;
- else dmxScreen->beBPP = 32;
-
-#ifdef GLXEXT
- /* get the majorOpcode for the back-end GLX extension */
- XQueryExtension(dpy, "GLX", &dmxScreen->glxMajorOpcode,
- &dummy, &dmxScreen->glxErrorBase);
-#endif
-
- dmxPrintScreenInfo(dmxScreen);
- dmxLogOutput(dmxScreen, "%dx%d+%d+%d on %dx%d at depth=%d, bpp=%d\n",
- dmxScreen->scrnWidth, dmxScreen->scrnHeight,
- dmxScreen->scrnX, dmxScreen->scrnY,
- dmxScreen->beWidth, dmxScreen->beHeight,
- dmxScreen->beDepth, dmxScreen->beBPP);
- if (dmxScreen->beDepth == 8)
- dmxLogOutputWarning(dmxScreen,
- "Support for depth == 8 is not complete\n");
-}
-
-Bool dmxGetVisualInfo(DMXScreenInfo *dmxScreen)
-{
- int i;
- XVisualInfo visinfo;
-
- visinfo.screen = DefaultScreen(dmxScreen->beDisplay);
- dmxScreen->beVisuals = XGetVisualInfo(dmxScreen->beDisplay,
- VisualScreenMask,
- &visinfo,
- &dmxScreen->beNumVisuals);
-
- dmxScreen->beDefVisualIndex = -1;
-
- if (defaultColorVisualClass >= 0 || dmxDepth > 0) {
- for (i = 0; i < dmxScreen->beNumVisuals; i++)
- if (defaultColorVisualClass >= 0) {
- if (dmxScreen->beVisuals[i].class == defaultColorVisualClass) {
- if (dmxDepth > 0) {
- if (dmxScreen->beVisuals[i].depth == dmxDepth) {
- dmxScreen->beDefVisualIndex = i;
- break;
- }
- } else {
- dmxScreen->beDefVisualIndex = i;
- break;
- }
- }
- } else if (dmxScreen->beVisuals[i].depth == dmxDepth) {
- dmxScreen->beDefVisualIndex = i;
- break;
- }
- } else {
- visinfo.visualid =
- XVisualIDFromVisual(DefaultVisual(dmxScreen->beDisplay,
- visinfo.screen));
-
- for (i = 0; i < dmxScreen->beNumVisuals; i++)
- if (visinfo.visualid == dmxScreen->beVisuals[i].visualid) {
- dmxScreen->beDefVisualIndex = i;
- break;
- }
- }
-
- for (i = 0; i < dmxScreen->beNumVisuals; i++)
- dmxLogVisual(dmxScreen, &dmxScreen->beVisuals[i],
- (i == dmxScreen->beDefVisualIndex));
-
- return dmxScreen->beDefVisualIndex >= 0;
-}
-
-void dmxGetColormaps(DMXScreenInfo *dmxScreen)
-{
- int i;
-
- dmxScreen->beNumDefColormaps = dmxScreen->beNumVisuals;
- dmxScreen->beDefColormaps = malloc(dmxScreen->beNumDefColormaps *
- sizeof(*dmxScreen->beDefColormaps));
-
- for (i = 0; i < dmxScreen->beNumDefColormaps; i++)
- dmxScreen->beDefColormaps[i] =
- XCreateColormap(dmxScreen->beDisplay,
- DefaultRootWindow(dmxScreen->beDisplay),
- dmxScreen->beVisuals[i].visual,
- AllocNone);
-
- dmxScreen->beBlackPixel = BlackPixel(dmxScreen->beDisplay,
- DefaultScreen(dmxScreen->beDisplay));
- dmxScreen->beWhitePixel = WhitePixel(dmxScreen->beDisplay,
- DefaultScreen(dmxScreen->beDisplay));
-}
-
-void dmxGetPixmapFormats(DMXScreenInfo *dmxScreen)
-{
- dmxScreen->beDepths =
- XListDepths(dmxScreen->beDisplay, DefaultScreen(dmxScreen->beDisplay),
- &dmxScreen->beNumDepths);
-
- dmxScreen->bePixmapFormats =
- XListPixmapFormats(dmxScreen->beDisplay,
- &dmxScreen->beNumPixmapFormats);
-}
-
-static Bool dmxSetPixmapFormats(ScreenInfo *pScreenInfo,
- DMXScreenInfo *dmxScreen)
-{
- XPixmapFormatValues *bePixmapFormat;
- PixmapFormatRec *format;
- int i, j;
-
- pScreenInfo->imageByteOrder = ImageByteOrder(dmxScreen->beDisplay);
- pScreenInfo->bitmapScanlineUnit = BitmapUnit(dmxScreen->beDisplay);
- pScreenInfo->bitmapScanlinePad = BitmapPad(dmxScreen->beDisplay);
- pScreenInfo->bitmapBitOrder = BitmapBitOrder(dmxScreen->beDisplay);
-
- pScreenInfo->numPixmapFormats = 0;
- for (i = 0; i < dmxScreen->beNumPixmapFormats; i++) {
- bePixmapFormat = &dmxScreen->bePixmapFormats[i];
- for (j = 0; j < dmxScreen->beNumDepths; j++)
- if ((bePixmapFormat->depth == 1) ||
- (bePixmapFormat->depth == dmxScreen->beDepths[j])) {
- format = &pScreenInfo->formats[pScreenInfo->numPixmapFormats];
-
- format->depth = bePixmapFormat->depth;
- format->bitsPerPixel = bePixmapFormat->bits_per_pixel;
- format->scanlinePad = bePixmapFormat->scanline_pad;
-
- pScreenInfo->numPixmapFormats++;
- break;
- }
- }
-
- return TRUE;
-}
-
-void dmxCheckForWM(DMXScreenInfo *dmxScreen)
-{
- Status status;
- XWindowAttributes xwa;
-
- status = XGetWindowAttributes(dmxScreen->beDisplay,
- DefaultRootWindow(dmxScreen->beDisplay),
- &xwa);
- dmxScreen->WMRunningOnBE =
- (status &&
- ((xwa.all_event_masks & SubstructureRedirectMask) ||
- (xwa.all_event_masks & SubstructureNotifyMask)));
-}
-
-/** Initialize the display and collect relevant information about the
- * display properties */
-static void dmxDisplayInit(DMXScreenInfo *dmxScreen)
-{
- if (!dmxOpenDisplay(dmxScreen))
- dmxLog(dmxFatal,
- "dmxOpenDisplay: Unable to open display %s\n",
- dmxScreen->name);
-
- dmxSetErrorHandler(dmxScreen);
- dmxCheckForWM(dmxScreen);
- dmxGetScreenAttribs(dmxScreen);
-
- if (!dmxGetVisualInfo(dmxScreen))
- dmxLog(dmxFatal, "dmxGetVisualInfo: No matching visuals found\n");
-
- dmxGetColormaps(dmxScreen);
- dmxGetPixmapFormats(dmxScreen);
-}
-
-/* If this doesn't compile, just add || defined(yoursystem) to the line
- * below. This information is to help with bug reports and is not
- * critical. */
-#if !defined(_POSIX_SOURCE)
-static const char *dmxExecOS(void) { return ""; }
-#else
-#include <sys/utsname.h>
-static const char *dmxExecOS(void)
-{
- static char buffer[128];
- static int initialized = 0;
- struct utsname u;
-
- if (!initialized++) {
- memset(buffer, 0, sizeof(buffer));
- uname(&u);
- XmuSnprintf(buffer, sizeof(buffer)-1, "%s %s %s",
- u.sysname, u.release, u.version);
- }
- return buffer;
-}
-#endif
-
-static const char *dmxBuildCompiler(void)
-{
- static char buffer[128];
- static int initialized = 0;
-
- if (!initialized++) {
- memset(buffer, 0, sizeof(buffer));
-#if defined(__GNUC__) && defined(__GNUC_MINOR__) &&defined(__GNUC_PATCHLEVEL__)
- XmuSnprintf(buffer, sizeof(buffer)-1, "gcc %d.%d.%d",
- __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
-#endif
- }
- return buffer;
-}
-
-static const char *dmxExecHost(void)
-{
- static char buffer[128];
- static int initialized = 0;
-
- if (!initialized++) {
- memset(buffer, 0, sizeof(buffer));
- XmuGetHostname(buffer, sizeof(buffer) - 1);
- }
- return buffer;
-}
-
-/** This routine is called in Xserver/dix/main.c from \a main(). */
-void InitOutput(ScreenInfo *pScreenInfo, int argc, char *argv[])
-{
- int i;
- static unsigned long dmxGeneration = 0;
-#ifdef GLXEXT
- Bool glxSupported = TRUE;
-#endif
-
- if (dmxGeneration != serverGeneration) {
- int vendrel = VENDOR_RELEASE;
- int major, minor, year, month, day;
-
- dmxGeneration = serverGeneration;
-
- major = vendrel / 100000000;
- vendrel -= major * 100000000;
- minor = vendrel / 1000000;
- vendrel -= minor * 1000000;
- year = vendrel / 10000;
- vendrel -= year * 10000;
- month = vendrel / 100;
- vendrel -= month * 100;
- day = vendrel;
-
- /* Add other epoch tests here */
- if (major > 0 && minor > 0) year += 2000;
-
- dmxLog(dmxInfo, "Generation: %d\n", dmxGeneration);
- dmxLog(dmxInfo, "DMX version: %d.%d.%02d%02d%02d (%s)\n",
- major, minor, year, month, day, VENDOR_STRING);
-
- SetVendorRelease(VENDOR_RELEASE);
- SetVendorString(VENDOR_STRING);
-
- if (dmxGeneration == 1) {
- dmxLog(dmxInfo, "DMX Build OS: %s (%s)\n", OSNAME, OSVENDOR);
- dmxLog(dmxInfo, "DMX Build Compiler: %s\n", dmxBuildCompiler());
- dmxLog(dmxInfo, "DMX Execution OS: %s\n", dmxExecOS());
- dmxLog(dmxInfo, "DMX Execution Host: %s\n", dmxExecHost());
- }
- dmxLog(dmxInfo, "MAXSCREENS: %d\n", MAXSCREENS);
-
- for (i = 0; i < dmxNumScreens; i++) {
- if (dmxScreens[i].beDisplay)
- dmxLog(dmxWarning, "Display \"%s\" still open\n",
- dmxScreens[i].name);
- dmxStatFree(dmxScreens[i].stat);
- dmxScreens[i].stat = NULL;
- }
- for (i = 0; i < dmxNumInputs; i++) dmxInputFree(&dmxInputs[i]);
- free(dmxScreens);
- free(dmxInputs);
- dmxScreens = NULL;
- dmxInputs = NULL;
- dmxNumScreens = 0;
- dmxNumInputs = 0;
- }
-
- /* Make sure that the command-line arguments are sane. */
- if (dmxAddRemoveScreens && dmxGLXProxy) {
- /* Currently it is not possible to support GLX and Render
- * extensions with dynamic screen addition/removal due to the
- * state that each extension keeps, which cannot be restored. */
- dmxLog(dmxWarning,
- "GLX Proxy and Render extensions do not yet support dynamic\n");
- dmxLog(dmxWarning,
- "screen addition and removal. Please specify -noglxproxy\n");
- dmxLog(dmxWarning,
- "and -norender on the command line or in the configuration\n");
- dmxLog(dmxWarning,
- "file to disable these two extensions if you wish to use\n");
- dmxLog(dmxWarning,
- "the dynamic addition and removal of screens support.\n");
- dmxLog(dmxFatal,
- "Dynamic screen addition/removal error (see above).\n");
- }
-
- /* ddxProcessArgument has been called at this point, but any data
- * from the configuration file has not been applied. Do so, and be
- * sure we have at least one back-end display. */
- dmxConfigConfigure();
- if (!dmxNumScreens)
- dmxLog(dmxFatal, "InitOutput: no back-end displays found\n");
- if (!dmxNumInputs)
- dmxLog(dmxInfo, "InitOutput: no inputs found\n");
-
- /* Disable lazy window creation optimization if offscreen
- * optimization is disabled */
- if (!dmxOffScreenOpt && dmxLazyWindowCreation) {
- dmxLog(dmxInfo,
- "InitOutput: Disabling lazy window creation optimization\n");
- dmxLog(dmxInfo,
- " since it requires the offscreen optimization\n");
- dmxLog(dmxInfo,
- " to function properly.\n");
- dmxLazyWindowCreation = FALSE;
- }
-
- /* Open each display and gather information about it. */
- for (i = 0; i < dmxNumScreens; i++)
- dmxDisplayInit(&dmxScreens[i]);
-
-#if PANORAMIX
- /* Register a Xinerama callback which will run from within
- * PanoramiXCreateConnectionBlock. We can use the callback to
- * determine if Xinerama is loaded and to check the visuals
- * determined by PanoramiXConsolidate. */
- XineramaRegisterConnectionBlockCallback(dmxConnectionBlockCallback);
-#endif
-
- /* Since we only have a single screen thus far, we only need to set
- the pixmap formats to match that screen. FIXME: this isn't true.*/
- if (!dmxSetPixmapFormats(pScreenInfo, &dmxScreens[0])) return;
-
- /* Might want to install a signal handler to allow cleaning up after
- * unexpected signals. The DIX/OS layer already handles SIGINT and
- * SIGTERM, so everything is OK for expected signals. --DD
- *
- * SIGHUP, SIGINT, and SIGTERM are trapped in os/connection.c
- * SIGQUIT is another common signal that is sent from the keyboard.
- * Trap it here, to ensure that the keyboard modifier map and other
- * state for the input devices are restored. (This makes the
- * behavior of SIGQUIT somewhat unexpected, since it will be the
- * same as the behavior of SIGINT. However, leaving the modifier
- * map of the input devices empty is even more unexpected.) --RF
- */
- OsSignal(SIGQUIT, GiveUp);
-
-#ifdef GLXEXT
- /* Check if GLX extension exists on all back-end servers */
- for (i = 0; i < dmxNumScreens; i++)
- glxSupported &= (dmxScreens[i].glxMajorOpcode > 0);
-#endif
-
- /* Tell dix layer about the backend displays */
- for (i = 0; i < dmxNumScreens; i++) {
-
-#ifdef GLXEXT
- if (glxSupported) {
- /*
- * Builds GLX configurations from the list of visuals
- * supported by the back-end server, and give that
- * configuration list to the glx layer - so that he will
- * build the visuals accordingly.
- */
-
- DMXScreenInfo *dmxScreen = &dmxScreens[i];
- __GLXvisualConfig *configs = NULL;
- dmxGlxVisualPrivate **configprivs = NULL;
- int nconfigs = 0;
- int (*oldErrorHandler)(Display *, XErrorEvent *);
- int i;
-
- /* Catch errors if when using an older GLX w/o FBconfigs */
- oldErrorHandler = XSetErrorHandler(dmxNOPErrorHandler);
-
- /* Get FBConfigs of the back-end server */
- dmxScreen->fbconfigs = GetGLXFBConfigs(dmxScreen->beDisplay,
- dmxScreen->glxMajorOpcode,
- &dmxScreen->numFBConfigs);
-
- XSetErrorHandler(oldErrorHandler);
-
- dmxScreen->glxVisuals =
- GetGLXVisualConfigs(dmxScreen->beDisplay,
- DefaultScreen(dmxScreen->beDisplay),
- &dmxScreen->numGlxVisuals);
-
- if (dmxScreen->fbconfigs) {
- configs =
- GetGLXVisualConfigsFromFBConfigs(dmxScreen->fbconfigs,
- dmxScreen->numFBConfigs,
- dmxScreen->beVisuals,
- dmxScreen->beNumVisuals,
- dmxScreen->glxVisuals,
- dmxScreen->numGlxVisuals,
- &nconfigs);
- } else {
- configs = dmxScreen->glxVisuals;
- nconfigs = dmxScreen->numGlxVisuals;
- }
-
- configprivs = malloc(nconfigs * sizeof(dmxGlxVisualPrivate*));
-
- if (configs != NULL && configprivs != NULL) {
-
- /* Initialize our private info for each visual
- * (currently only x_visual_depth and x_visual_class)
- */
- for (i = 0; i < nconfigs; i++) {
-
- configprivs[i] = (dmxGlxVisualPrivate *)
- malloc(sizeof(dmxGlxVisualPrivate));
- configprivs[i]->x_visual_depth = 0;
- configprivs[i]->x_visual_class = 0;
-
- /* Find the visual depth */
- if (configs[i].vid > 0) {
- int j;
- for (j = 0; j < dmxScreen->beNumVisuals; j++) {
- if (dmxScreen->beVisuals[j].visualid ==
- configs[i].vid) {
- configprivs[i]->x_visual_depth =
- dmxScreen->beVisuals[j].depth;
- configprivs[i]->x_visual_class =
- dmxScreen->beVisuals[j].class;
- break;
- }
- }
- }
- }
-
- XFlush(dmxScreen->beDisplay);
- }
- }
-#endif /* GLXEXT */
-
- AddScreen(dmxScreenInit, argc, argv);
- }
-
- /* Compute origin information. */
- dmxInitOrigins();
-
- /* Compute overlap information. */
- dmxInitOverlap();
-
- /* Make sure there is a global width/height available */
- dmxComputeWidthHeight(DMX_NO_RECOMPUTE_BOUNDING_BOX);
-
- /* FIXME: The following is temporarily placed here. When the DMX
- * extension is available, it will be move there.
- */
- dmxInitFonts();
-
- /* Initialize the render extension */
- if (!noRenderExtension)
- dmxInitRender();
-
- /* Initialized things that need timer hooks */
- dmxStatInit();
- dmxSyncInit(); /* Calls RegisterBlockAndWakeupHandlers */
-
- dmxLog(dmxInfo, "Shadow framebuffer support %s\n",
- dmxShadowFB ? "enabled" : "disabled");
-}
-
-/* RATS: Assuming the fp string (which comes from the command-line argv
- vector) is NULL-terminated, the buffer is large enough for the
- strcpy. */
-static void dmxSetDefaultFontPath(char *fp)
-{
- int fplen = strlen(fp) + 1;
-
- if (dmxFontPath) {
- int len;
-
- len = strlen(dmxFontPath);
- dmxFontPath = realloc(dmxFontPath, len+fplen+1);
- dmxFontPath[len] = ',';
- strncpy(&dmxFontPath[len+1], fp, fplen);
- } else {
- dmxFontPath = malloc(fplen);
- strncpy(dmxFontPath, fp, fplen);
- }
-
- defaultFontPath = dmxFontPath;
-}
-
-/** This function is called in Xserver/os/utils.c from \a AbortServer().
- * We must ensure that backend and console state is restored in the
- * event the server shutdown wasn't clean. */
-void AbortDDX(void)
-{
- int i;
-
- for (i=0; i < dmxNumScreens; i++) {
- DMXScreenInfo *dmxScreen = &dmxScreens[i];
-
- if (dmxScreen->beDisplay) XCloseDisplay(dmxScreen->beDisplay);
- dmxScreen->beDisplay = NULL;
- }
-}
-
-#ifdef DDXBEFORERESET
-/* This function is called in Xserver/dix/dispatch.c */
-void ddxBeforeReset(void)
-{
-}
-#endif
-
-/** This function is called in Xserver/dix/main.c from \a main() when
- * dispatchException & DE_TERMINATE (which is the only way to exit the
- * main loop without an interruption. */
-void ddxGiveUp(void)
-{
- AbortDDX();
-}
-
-/** This function is called in Xserver/os/osinit.c from \a OsInit(). */
-void OsVendorInit(void)
-{
-}
-
-/** This function is called in Xserver/os/utils.c from \a FatalError()
- * and \a VFatalError(). (Note that setting the function pointer \a
- * OsVendorVErrorFProc will cause \a VErrorF() (which is called by the
- * two routines mentioned here, as well as by others) to use the
- * referenced routine instead of \a vfprintf().) */
-void OsVendorFatalError(void)
-{
-}
-
-/** Process our command line arguments. */
-int ddxProcessArgument(int argc, char *argv[], int i)
-{
- int retval = 0;
-
- if (!strcmp(argv[i], "-display")) {
- if (++i < argc) dmxConfigStoreDisplay(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-inputfrom") || !strcmp(argv[i], "-input")) {
- if (++i < argc) dmxConfigStoreInput(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-xinputfrom") || !strcmp(argv[i],"-xinput")) {
- if (++i < argc) dmxConfigStoreXInput(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-noshadowfb")) {
- dmxLog(dmxWarning,
- "-noshadowfb has been deprecated "
- "since it is now the default\n");
- dmxShadowFB = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-nomulticursor")) {
- dmxCursorNoMulti();
- retval = 1;
- } else if (!strcmp(argv[i], "-shadowfb")) {
- dmxShadowFB = TRUE;
- retval = 1;
- } else if (!strcmp(argv[i], "-configfile")) {
- if (++i < argc) dmxConfigStoreFile(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-config")) {
- if (++i < argc) dmxConfigStoreConfig(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-fontpath")) {
- if (++i < argc) dmxSetDefaultFontPath(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-stat")) {
- if ((i += 2) < argc) dmxStatActivate(argv[i-1], argv[i]);
- retval = 3;
- } else if (!strcmp(argv[i], "-syncbatch")) {
- if (++i < argc) dmxSyncActivate(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-nooffscreenopt")) {
- dmxOffScreenOpt = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-nosubdivprims")) {
- dmxSubdividePrimitives = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-nowindowopt")) {
- dmxLazyWindowCreation = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-noxkb")) {
- dmxUseXKB = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-depth")) {
- if (++i < argc) dmxDepth = atoi(argv[i]);
- retval = 2;
- } else if (!strcmp(argv[i], "-norender")) {
- noRenderExtension = TRUE;
- retval = 1;
-#ifdef GLXEXT
- } else if (!strcmp(argv[i], "-noglxproxy")) {
- dmxGLXProxy = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-noglxswapgroup")) {
- dmxGLXSwapGroupSupport = FALSE;
- retval = 1;
- } else if (!strcmp(argv[i], "-glxsyncswap")) {
- dmxGLXSyncSwap = TRUE;
- retval = 1;
- } else if (!strcmp(argv[i], "-glxfinishswap")) {
- dmxGLXFinishSwap = TRUE;
- retval = 1;
-#endif
- } else if (!strcmp(argv[i], "-ignorebadfontpaths")) {
- dmxIgnoreBadFontPaths = TRUE;
- retval = 1;
- } else if (!strcmp(argv[i], "-addremovescreens")) {
- dmxAddRemoveScreens = TRUE;
- retval = 1;
- } else if (!strcmp(argv[i], "-param")) {
- if ((i += 2) < argc) {
- if (!strcasecmp(argv[i-1], "xkbrules"))
- dmxConfigSetXkbRules(argv[i]);
- else if (!strcasecmp(argv[i-1], "xkbmodel"))
- dmxConfigSetXkbModel(argv[i]);
- else if (!strcasecmp(argv[i-1], "xkblayout"))
- dmxConfigSetXkbLayout(argv[i]);
- else if (!strcasecmp(argv[i-1], "xkbvariant"))
- dmxConfigSetXkbVariant(argv[i]);
- else if (!strcasecmp(argv[i-1], "xkboptions"))
- dmxConfigSetXkbOptions(argv[i]);
- else
- dmxLog(dmxWarning,
- "-param requires: XkbRules, XkbModel, XkbLayout,"
- " XkbVariant, or XkbOptions\n");
- }
- retval = 3;
- }
- if (!serverGeneration) dmxConfigSetMaxScreens();
- return retval;
-}
-
-/** Provide succinct usage information for the DMX server. */
-void ddxUseMsg(void)
-{
- ErrorF("\n\nDevice Dependent Usage:\n");
- ErrorF("-display string Specify the back-end display(s)\n");
- ErrorF("-input string Specify input source for core device\n");
- ErrorF("-xinput string Specify input source for XInput device\n");
- ErrorF("-shadowfb Enable shadow frame buffer\n");
- ErrorF("-configfile file Read from a configuration file\n");
- ErrorF("-config config Select a specific configuration\n");
- ErrorF("-nomulticursor Turn of multiple cursor support\n");
- ErrorF("-fontpath Sets the default font path\n");
- ErrorF("-stat inter scrns Print out performance statistics\n");
- ErrorF("-syncbatch inter Set interval for XSync batching\n");
- ErrorF("-nooffscreenopt Disable offscreen optimization\n");
- ErrorF("-nosubdivprims Disable primitive subdivision\n");
- ErrorF(" optimization\n");
- ErrorF("-nowindowopt Disable lazy window creation optimization\n");
- ErrorF("-noxkb Disable use of the XKB extension with\n");
- ErrorF(" backend displays (cf. -kb).\n");
- ErrorF("-depth Specify the default root window depth\n");
- ErrorF("-norender Disable RENDER extension support\n");
-#ifdef GLXEXT
- ErrorF("-noglxproxy Disable GLX Proxy\n");
- ErrorF("-noglxswapgroup Disable swap group and swap barrier\n");
- ErrorF(" extensions in GLX proxy\n");
- ErrorF("-glxsyncswap Force XSync after swap buffers\n");
- ErrorF("-glxfinishswap Force glFinish after swap buffers\n");
-#endif
- ErrorF("-ignorebadfontpaths Ignore bad font paths during initialization\n");
- ErrorF("-addremovescreens Enable dynamic screen addition/removal\n");
- ErrorF("-param ... Specify configuration parameters (e.g.,\n");
- ErrorF(" XkbRules, XkbModel, XkbLayout, etc.)\n");
- ErrorF("\n");
- ErrorF(" If the -input string matches a -display string, then input\n"
- " is taken from that backend display. (XInput cannot be taken\n"
- " from a backend display.) Placing \",console\" after the\n"
- " display name will force a console window to be opened on\n"
- " that display in addition to the backend input. This is\n"
- " useful if the backend window does not cover the whole\n"
- " physical display.\n\n");
-
- ErrorF(" Otherwise, if the -input or -xinput string specifies another\n"
- " X display, then a console window will be created on that\n"
- " display. Placing \",windows\" or \",nowindows\" after the\n"
- " display name will control the display of window outlines in\n"
- " the console.\n\n");
-
- ErrorF(" -input or -xinput dummy specifies no input.\n");
- ErrorF(" -input or -xinput local specifies the use of a raw keyboard,\n"
- " mouse, or other (extension) device:\n"
- " -input local,kbd,ps2 will use a ps2 mouse\n"
- " -input local,kbd,ms will use a serial mouse\n"
- " -input local,usb-kbd,usb-mou will use USB devices \n"
- " -xinput local,usb-oth will use a non-mouse and\n"
- " non-keyboard USB device with XInput\n\n");
-
- ErrorF(" Special Keys:\n");
- ErrorF(" Ctrl-Alt-g Server grab/ungrab (console only)\n");
- ErrorF(" Ctrl-Alt-f Fine (1-pixel) mouse mode (console only)\n");
- ErrorF(" Ctrl-Alt-q Quit (core devices only)\n");
- ErrorF(" Ctrl-Alt-F* Switch to VC (local only)\n");
-}
+/* + * Copyright 2001-2004 Red Hat Inc., Durham, North Carolina. + * + * All Rights Reserved. + * + * 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 on 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: + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial + * portions of the Software. + * + * 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 + * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS + * 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. + */ + +/* + * Authors: + * Kevin E. Martin <kem@redhat.com> + * David H. Dawes <dawes@xfree86.org> + * Rickard E. (Rik) Faith <faith@redhat.com> + * + */ + +/** \file + * Provide expected functions for initialization from the ddx layer and + * global variables for the DMX server. */ + +#ifdef HAVE_DMX_CONFIG_H +#include <dmx-config.h> +#endif + +#include "dmx.h" +#include "dmxinit.h" +#include "dmxsync.h" +#include "dmxlog.h" +#include "dmxinput.h" +#include "dmxscrinit.h" +#include "dmxcursor.h" +#include "dmxfont.h" +#include "config/dmxconfig.h" +#include "dmxcb.h" +#include "dmxprop.h" +#include "dmxstat.h" +#include "dmxpict.h" + +#include <X11/Xos.h> /* For gettimeofday */ +#include "dixstruct.h" +#ifdef PANORAMIX +#include "panoramiXsrv.h" +#endif + +#include <signal.h> /* For SIGQUIT */ + +#ifdef GLXEXT +#include <GL/glx.h> +#include <GL/glxint.h> +#include "dmx_glxvisuals.h" +#include <X11/extensions/Xext.h> +#include <X11/extensions/extutil.h> +#endif /* GLXEXT */ + +/* Global variables available to all Xserver/hw/dmx routines. */ +int dmxNumScreens; +DMXScreenInfo *dmxScreens; + +int dmxNumInputs; +DMXInputInfo *dmxInputs; + +int dmxShadowFB = FALSE; + +XErrorEvent dmxLastErrorEvent; +Bool dmxErrorOccurred = FALSE; + +char *dmxFontPath = NULL; + +Bool dmxOffScreenOpt = TRUE; + +Bool dmxSubdividePrimitives = TRUE; + +Bool dmxLazyWindowCreation = TRUE; + +Bool dmxUseXKB = TRUE; + +int dmxDepth = 0; + +#ifndef GLXEXT +static Bool dmxGLXProxy = FALSE; +#else +Bool dmxGLXProxy = TRUE; + +Bool dmxGLXSwapGroupSupport = TRUE; + +Bool dmxGLXSyncSwap = FALSE; + +Bool dmxGLXFinishSwap = FALSE; +#endif + +Bool dmxIgnoreBadFontPaths = FALSE; + +Bool dmxAddRemoveScreens = FALSE; + +/* dmxErrorHandler catches errors that occur when calling one of the + * back-end servers. Some of this code is based on _XPrintDefaultError + * in xc/lib/X11/XlibInt.c */ +static int dmxErrorHandler(Display *dpy, XErrorEvent *ev) +{ +#define DMX_ERROR_BUF_SIZE 256 + /* RATS: these buffers are only used in + * length-limited calls. */ + char buf[DMX_ERROR_BUF_SIZE]; + char request[DMX_ERROR_BUF_SIZE]; + _XExtension *ext = NULL; + + dmxErrorOccurred = TRUE; + dmxLastErrorEvent = *ev; + + XGetErrorText(dpy, ev->error_code, buf, sizeof(buf)); + dmxLog(dmxWarning, "dmxErrorHandler: %s\n", buf); + + /* Find major opcode name */ + if (ev->request_code < 128) { + XmuSnprintf(request, sizeof(request), "%d", ev->request_code); + XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf)); + } else { + for (ext = dpy->ext_procs; + ext && ext->codes.major_opcode != ev->request_code; + ext = ext->next); + if (ext) strncpy(buf, ext->name, sizeof(buf)); + else buf[0] = '\0'; + } + dmxLog(dmxWarning, " Major opcode: %d (%s)\n", + ev->request_code, buf); + + /* Find minor opcode name */ + if (ev->request_code >= 128 && ext) { + XmuSnprintf(request, sizeof(request), "%d", ev->request_code); + XmuSnprintf(request, sizeof(request), "%s.%d", + ext->name, ev->minor_code); + XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf)); + dmxLog(dmxWarning, " Minor opcode: %d (%s)\n", + ev->minor_code, buf); + } + + /* Provide value information */ + switch (ev->error_code) { + case BadValue: + dmxLog(dmxWarning, " Value: 0x%x\n", + ev->resourceid); + break; + case BadAtom: + dmxLog(dmxWarning, " AtomID: 0x%x\n", + ev->resourceid); + break; + default: + dmxLog(dmxWarning, " ResourceID: 0x%x\n", + ev->resourceid); + break; + } + + /* Provide serial number information */ + dmxLog(dmxWarning, " Failed serial number: %d\n", + ev->serial); + dmxLog(dmxWarning, " Current serial number: %d\n", + dpy->request); + return 0; +} + +#ifdef GLXEXT +static int dmxNOPErrorHandler(Display *dpy, XErrorEvent *ev) +{ + return 0; +} +#endif + +Bool dmxOpenDisplay(DMXScreenInfo *dmxScreen) +{ + if (!(dmxScreen->beDisplay = XOpenDisplay(dmxScreen->name))) + return FALSE; + + dmxPropertyDisplay(dmxScreen); + return TRUE; +} + +void dmxSetErrorHandler(DMXScreenInfo *dmxScreen) +{ + XSetErrorHandler(dmxErrorHandler); +} + +static void dmxPrintScreenInfo(DMXScreenInfo *dmxScreen) +{ + XWindowAttributes attribs; + int ndepths = 0, *depths = NULL; + int i; + Display *dpy = dmxScreen->beDisplay; + Screen *s = DefaultScreenOfDisplay(dpy); + int scr = DefaultScreen(dpy); + + XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs); + if (!(depths = XListDepths(dpy, scr, &ndepths))) ndepths = 0; + + dmxLogOutput(dmxScreen, "Name of display: %s\n", DisplayString(dpy)); + dmxLogOutput(dmxScreen, "Version number: %d.%d\n", + ProtocolVersion(dpy), ProtocolRevision(dpy)); + dmxLogOutput(dmxScreen, "Vendor string: %s\n", ServerVendor(dpy)); + if (!strstr(ServerVendor(dpy), "XFree86")) { + dmxLogOutput(dmxScreen, "Vendor release: %d\n", VendorRelease(dpy)); + } else { + /* This code based on xdpyinfo.c */ + int v = VendorRelease(dpy); + int major = -1, minor = -1, patch = -1, subpatch = -1; + + if (v < 336) + major = v / 100, minor = (v / 10) % 10, patch = v % 10; + else if (v < 3900) { + major = v / 1000; + minor = (v / 100) % 10; + if (((v / 10) % 10) || (v % 10)) { + patch = (v / 10) % 10; + if (v % 10) subpatch = v % 10; + } + } else if (v < 40000000) { + major = v / 1000; + minor = (v / 10) % 10; + if (v % 10) patch = v % 10; + } else { + major = v / 10000000; + minor = (v / 100000) % 100; + patch = (v / 1000) % 100; + if (v % 1000) subpatch = v % 1000; + } + dmxLogOutput(dmxScreen, "Vendor release: %d (XFree86 version: %d.%d", + v, major, minor); + if (patch > 0) dmxLogOutputCont(dmxScreen, ".%d", patch); + if (subpatch > 0) dmxLogOutputCont(dmxScreen, ".%d", subpatch); + dmxLogOutputCont(dmxScreen, ")\n"); + } + + + dmxLogOutput(dmxScreen, "Dimensions: %dx%d pixels\n", + attribs.width, attribs.height); + dmxLogOutput(dmxScreen, "%d depths on screen %d: ", ndepths, scr); + for (i = 0; i < ndepths; i++) + dmxLogOutputCont(dmxScreen, "%c%d", i ? ',' : ' ', depths[i]); + dmxLogOutputCont(dmxScreen, "\n"); + dmxLogOutput(dmxScreen, "Depth of root window: %d plane%s (%d)\n", + attribs.depth, attribs.depth == 1 ? "" : "s", + DisplayPlanes(dpy, scr)); + dmxLogOutput(dmxScreen, "Number of colormaps: %d min, %d max\n", + MinCmapsOfScreen(s), MaxCmapsOfScreen(s)); + dmxLogOutput(dmxScreen, "Options: backing-store %s, save-unders %s\n", + (DoesBackingStore (s) == NotUseful) ? "no" : + ((DoesBackingStore (s) == Always) ? "yes" : "when mapped"), + DoesSaveUnders (s) ? "yes" : "no"); + dmxLogOutput(dmxScreen, "Window Manager running: %s\n", + (dmxScreen->WMRunningOnBE) ? "yes" : "no"); + + if (dmxScreen->WMRunningOnBE) { + dmxLogOutputWarning(dmxScreen, + "Window manager running " + "-- colormaps not supported\n"); + } + XFree(depths); +} + +void dmxGetScreenAttribs(DMXScreenInfo *dmxScreen) +{ + XWindowAttributes attribs; + Display *dpy = dmxScreen->beDisplay; +#ifdef GLXEXT + int dummy; +#endif + + XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs); + + dmxScreen->beWidth = attribs.width; + dmxScreen->beHeight = attribs.height; + + /* Fill in missing geometry information */ + if (dmxScreen->scrnXSign < 0) { + if (dmxScreen->scrnWidth) { + dmxScreen->scrnX = (attribs.width - dmxScreen->scrnWidth + - dmxScreen->scrnX); + } else { + dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX; + dmxScreen->scrnX = 0; + } + } + if (dmxScreen->scrnYSign < 0) { + if (dmxScreen->scrnHeight) { + dmxScreen->scrnY = (attribs.height - dmxScreen->scrnHeight + - dmxScreen->scrnY); + } else { + dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY; + dmxScreen->scrnY = 0; + } + } + if (!dmxScreen->scrnWidth) + dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX; + if (!dmxScreen->scrnHeight) + dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY; + + if (!dmxScreen->rootWidth) dmxScreen->rootWidth = dmxScreen->scrnWidth; + if (!dmxScreen->rootHeight) dmxScreen->rootHeight = dmxScreen->scrnHeight; + if (dmxScreen->rootWidth + dmxScreen->rootX > dmxScreen->scrnWidth) + dmxScreen->rootWidth = dmxScreen->scrnWidth - dmxScreen->rootX; + if (dmxScreen->rootHeight + dmxScreen->rootY > dmxScreen->scrnHeight) + dmxScreen->rootHeight = dmxScreen->scrnHeight - dmxScreen->rootY; + + /* FIXME: Get these from the back-end server */ + dmxScreen->beXDPI = 75; + dmxScreen->beYDPI = 75; + + dmxScreen->beDepth = attribs.depth; /* FIXME: verify that this + * works always. In + * particular, this will work + * well for depth=16, will fail + * because of colormap issues + * at depth 8. More work needs + * to be done here. */ + + if (dmxScreen->beDepth <= 8) dmxScreen->beBPP = 8; + else if (dmxScreen->beDepth <= 16) dmxScreen->beBPP = 16; + else dmxScreen->beBPP = 32; + +#ifdef GLXEXT + /* get the majorOpcode for the back-end GLX extension */ + XQueryExtension(dpy, "GLX", &dmxScreen->glxMajorOpcode, + &dummy, &dmxScreen->glxErrorBase); +#endif + + dmxPrintScreenInfo(dmxScreen); + dmxLogOutput(dmxScreen, "%dx%d+%d+%d on %dx%d at depth=%d, bpp=%d\n", + dmxScreen->scrnWidth, dmxScreen->scrnHeight, + dmxScreen->scrnX, dmxScreen->scrnY, + dmxScreen->beWidth, dmxScreen->beHeight, + dmxScreen->beDepth, dmxScreen->beBPP); + if (dmxScreen->beDepth == 8) + dmxLogOutputWarning(dmxScreen, + "Support for depth == 8 is not complete\n"); +} + +Bool dmxGetVisualInfo(DMXScreenInfo *dmxScreen) +{ + int i; + XVisualInfo visinfo; + + visinfo.screen = DefaultScreen(dmxScreen->beDisplay); + dmxScreen->beVisuals = XGetVisualInfo(dmxScreen->beDisplay, + VisualScreenMask, + &visinfo, + &dmxScreen->beNumVisuals); + + dmxScreen->beDefVisualIndex = -1; + + if (defaultColorVisualClass >= 0 || dmxDepth > 0) { + for (i = 0; i < dmxScreen->beNumVisuals; i++) + if (defaultColorVisualClass >= 0) { + if (dmxScreen->beVisuals[i].class == defaultColorVisualClass) { + if (dmxDepth > 0) { + if (dmxScreen->beVisuals[i].depth == dmxDepth) { + dmxScreen->beDefVisualIndex = i; + break; + } + } else { + dmxScreen->beDefVisualIndex = i; + break; + } + } + } else if (dmxScreen->beVisuals[i].depth == dmxDepth) { + dmxScreen->beDefVisualIndex = i; + break; + } + } else { + visinfo.visualid = + XVisualIDFromVisual(DefaultVisual(dmxScreen->beDisplay, + visinfo.screen)); + + for (i = 0; i < dmxScreen->beNumVisuals; i++) + if (visinfo.visualid == dmxScreen->beVisuals[i].visualid) { + dmxScreen->beDefVisualIndex = i; + break; + } + } + + for (i = 0; i < dmxScreen->beNumVisuals; i++) + dmxLogVisual(dmxScreen, &dmxScreen->beVisuals[i], + (i == dmxScreen->beDefVisualIndex)); + + return dmxScreen->beDefVisualIndex >= 0; +} + +void dmxGetColormaps(DMXScreenInfo *dmxScreen) +{ + int i; + + dmxScreen->beNumDefColormaps = dmxScreen->beNumVisuals; + dmxScreen->beDefColormaps = malloc(dmxScreen->beNumDefColormaps * + sizeof(*dmxScreen->beDefColormaps)); + + for (i = 0; i < dmxScreen->beNumDefColormaps; i++) + dmxScreen->beDefColormaps[i] = + XCreateColormap(dmxScreen->beDisplay, + DefaultRootWindow(dmxScreen->beDisplay), + dmxScreen->beVisuals[i].visual, + AllocNone); + + dmxScreen->beBlackPixel = BlackPixel(dmxScreen->beDisplay, + DefaultScreen(dmxScreen->beDisplay)); + dmxScreen->beWhitePixel = WhitePixel(dmxScreen->beDisplay, + DefaultScreen(dmxScreen->beDisplay)); +} + +void dmxGetPixmapFormats(DMXScreenInfo *dmxScreen) +{ + dmxScreen->beDepths = + XListDepths(dmxScreen->beDisplay, DefaultScreen(dmxScreen->beDisplay), + &dmxScreen->beNumDepths); + + dmxScreen->bePixmapFormats = + XListPixmapFormats(dmxScreen->beDisplay, + &dmxScreen->beNumPixmapFormats); +} + +static Bool dmxSetPixmapFormats(ScreenInfo *pScreenInfo, + DMXScreenInfo *dmxScreen) +{ + XPixmapFormatValues *bePixmapFormat; + PixmapFormatRec *format; + int i, j; + + pScreenInfo->imageByteOrder = ImageByteOrder(dmxScreen->beDisplay); + pScreenInfo->bitmapScanlineUnit = BitmapUnit(dmxScreen->beDisplay); + pScreenInfo->bitmapScanlinePad = BitmapPad(dmxScreen->beDisplay); + pScreenInfo->bitmapBitOrder = BitmapBitOrder(dmxScreen->beDisplay); + + pScreenInfo->numPixmapFormats = 0; + for (i = 0; i < dmxScreen->beNumPixmapFormats; i++) { + bePixmapFormat = &dmxScreen->bePixmapFormats[i]; + for (j = 0; j < dmxScreen->beNumDepths; j++) + if ((bePixmapFormat->depth == 1) || + (bePixmapFormat->depth == dmxScreen->beDepths[j])) { + format = &pScreenInfo->formats[pScreenInfo->numPixmapFormats]; + + format->depth = bePixmapFormat->depth; + format->bitsPerPixel = bePixmapFormat->bits_per_pixel; + format->scanlinePad = bePixmapFormat->scanline_pad; + + pScreenInfo->numPixmapFormats++; + break; + } + } + + return TRUE; +} + +void dmxCheckForWM(DMXScreenInfo *dmxScreen) +{ + Status status; + XWindowAttributes xwa; + + status = XGetWindowAttributes(dmxScreen->beDisplay, + DefaultRootWindow(dmxScreen->beDisplay), + &xwa); + dmxScreen->WMRunningOnBE = + (status && + ((xwa.all_event_masks & SubstructureRedirectMask) || + (xwa.all_event_masks & SubstructureNotifyMask))); +} + +/** Initialize the display and collect relevant information about the + * display properties */ +static void dmxDisplayInit(DMXScreenInfo *dmxScreen) +{ + if (!dmxOpenDisplay(dmxScreen)) + dmxLog(dmxFatal, + "dmxOpenDisplay: Unable to open display %s\n", + dmxScreen->name); + + dmxSetErrorHandler(dmxScreen); + dmxCheckForWM(dmxScreen); + dmxGetScreenAttribs(dmxScreen); + + if (!dmxGetVisualInfo(dmxScreen)) + dmxLog(dmxFatal, "dmxGetVisualInfo: No matching visuals found\n"); + + dmxGetColormaps(dmxScreen); + dmxGetPixmapFormats(dmxScreen); +} + +/* If this doesn't compile, just add || defined(yoursystem) to the line + * below. This information is to help with bug reports and is not + * critical. */ +#if !defined(_POSIX_SOURCE) +static const char *dmxExecOS(void) { return ""; } +#else +#include <sys/utsname.h> +static const char *dmxExecOS(void) +{ + static char buffer[128]; + static int initialized = 0; + struct utsname u; + + if (!initialized++) { + memset(buffer, 0, sizeof(buffer)); + uname(&u); + XmuSnprintf(buffer, sizeof(buffer)-1, "%s %s %s", + u.sysname, u.release, u.version); + } + return buffer; +} +#endif + +static const char *dmxBuildCompiler(void) +{ + static char buffer[128]; + static int initialized = 0; + + if (!initialized++) { + memset(buffer, 0, sizeof(buffer)); +#if defined(__GNUC__) && defined(__GNUC_MINOR__) &&defined(__GNUC_PATCHLEVEL__) + XmuSnprintf(buffer, sizeof(buffer)-1, "gcc %d.%d.%d", + __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); +#endif + } + return buffer; +} + +static const char *dmxExecHost(void) +{ + static char buffer[128]; + static int initialized = 0; + + if (!initialized++) { + memset(buffer, 0, sizeof(buffer)); + XmuGetHostname(buffer, sizeof(buffer) - 1); + } + return buffer; +} + +/** This routine is called in Xserver/dix/main.c from \a main(). */ +void InitOutput(ScreenInfo *pScreenInfo, int argc, char *argv[]) +{ + int i; + static unsigned long dmxGeneration = 0; +#ifdef GLXEXT + Bool glxSupported = TRUE; +#endif + + if (dmxGeneration != serverGeneration) { + int vendrel = VENDOR_RELEASE; + int major, minor, year, month, day; + + dmxGeneration = serverGeneration; + + major = vendrel / 100000000; + vendrel -= major * 100000000; + minor = vendrel / 1000000; + vendrel -= minor * 1000000; + year = vendrel / 10000; + vendrel -= year * 10000; + month = vendrel / 100; + vendrel -= month * 100; + day = vendrel; + + /* Add other epoch tests here */ + if (major > 0 && minor > 0) year += 2000; + + dmxLog(dmxInfo, "Generation: %d\n", dmxGeneration); + dmxLog(dmxInfo, "DMX version: %d.%d.%02d%02d%02d (%s)\n", + major, minor, year, month, day, VENDOR_STRING); + + SetVendorRelease(VENDOR_RELEASE); + SetVendorString(VENDOR_STRING); + + if (dmxGeneration == 1) { + dmxLog(dmxInfo, "DMX Build OS: %s (%s)\n", OSNAME, OSVENDOR); + dmxLog(dmxInfo, "DMX Build Compiler: %s\n", dmxBuildCompiler()); + dmxLog(dmxInfo, "DMX Execution OS: %s\n", dmxExecOS()); + dmxLog(dmxInfo, "DMX Execution Host: %s\n", dmxExecHost()); + } + dmxLog(dmxInfo, "MAXSCREENS: %d\n", MAXSCREENS); + + for (i = 0; i < dmxNumScreens; i++) { + if (dmxScreens[i].beDisplay) + dmxLog(dmxWarning, "Display \"%s\" still open\n", + dmxScreens[i].name); + dmxStatFree(dmxScreens[i].stat); + dmxScreens[i].stat = NULL; + } + for (i = 0; i < dmxNumInputs; i++) dmxInputFree(&dmxInputs[i]); + free(dmxScreens); + free(dmxInputs); + dmxScreens = NULL; + dmxInputs = NULL; + dmxNumScreens = 0; + dmxNumInputs = 0; + } + + /* Make sure that the command-line arguments are sane. */ + if (dmxAddRemoveScreens && dmxGLXProxy) { + /* Currently it is not possible to support GLX and Render + * extensions with dynamic screen addition/removal due to the + * state that each extension keeps, which cannot be restored. */ + dmxLog(dmxWarning, + "GLX Proxy and Render extensions do not yet support dynamic\n"); + dmxLog(dmxWarning, + "screen addition and removal. Please specify -noglxproxy\n"); + dmxLog(dmxWarning, + "and -norender on the command line or in the configuration\n"); + dmxLog(dmxWarning, + "file to disable these two extensions if you wish to use\n"); + dmxLog(dmxWarning, + "the dynamic addition and removal of screens support.\n"); + dmxLog(dmxFatal, + "Dynamic screen addition/removal error (see above).\n"); + } + + /* ddxProcessArgument has been called at this point, but any data + * from the configuration file has not been applied. Do so, and be + * sure we have at least one back-end display. */ + dmxConfigConfigure(); + if (!dmxNumScreens) + dmxLog(dmxFatal, "InitOutput: no back-end displays found\n"); + if (!dmxNumInputs) + dmxLog(dmxInfo, "InitOutput: no inputs found\n"); + + /* Disable lazy window creation optimization if offscreen + * optimization is disabled */ + if (!dmxOffScreenOpt && dmxLazyWindowCreation) { + dmxLog(dmxInfo, + "InitOutput: Disabling lazy window creation optimization\n"); + dmxLog(dmxInfo, + " since it requires the offscreen optimization\n"); + dmxLog(dmxInfo, + " to function properly.\n"); + dmxLazyWindowCreation = FALSE; + } + + /* Open each display and gather information about it. */ + for (i = 0; i < dmxNumScreens; i++) + dmxDisplayInit(&dmxScreens[i]); + +#if PANORAMIX + /* Register a Xinerama callback which will run from within + * PanoramiXCreateConnectionBlock. We can use the callback to + * determine if Xinerama is loaded and to check the visuals + * determined by PanoramiXConsolidate. */ + XineramaRegisterConnectionBlockCallback(dmxConnectionBlockCallback); +#endif + + /* Since we only have a single screen thus far, we only need to set + the pixmap formats to match that screen. FIXME: this isn't true.*/ + if (!dmxSetPixmapFormats(pScreenInfo, &dmxScreens[0])) return; + + /* Might want to install a signal handler to allow cleaning up after + * unexpected signals. The DIX/OS layer already handles SIGINT and + * SIGTERM, so everything is OK for expected signals. --DD + * + * SIGHUP, SIGINT, and SIGTERM are trapped in os/connection.c + * SIGQUIT is another common signal that is sent from the keyboard. + * Trap it here, to ensure that the keyboard modifier map and other + * state for the input devices are restored. (This makes the + * behavior of SIGQUIT somewhat unexpected, since it will be the + * same as the behavior of SIGINT. However, leaving the modifier + * map of the input devices empty is even more unexpected.) --RF + */ + OsSignal(SIGQUIT, GiveUp); + +#ifdef GLXEXT + /* Check if GLX extension exists on all back-end servers */ + for (i = 0; i < dmxNumScreens; i++) + glxSupported &= (dmxScreens[i].glxMajorOpcode > 0); +#endif + + /* Tell dix layer about the backend displays */ + for (i = 0; i < dmxNumScreens; i++) { + +#ifdef GLXEXT + if (glxSupported) { + /* + * Builds GLX configurations from the list of visuals + * supported by the back-end server, and give that + * configuration list to the glx layer - so that he will + * build the visuals accordingly. + */ + + DMXScreenInfo *dmxScreen = &dmxScreens[i]; + __GLXvisualConfig *configs = NULL; + dmxGlxVisualPrivate **configprivs = NULL; + int nconfigs = 0; + int (*oldErrorHandler)(Display *, XErrorEvent *); + int i; + + /* Catch errors if when using an older GLX w/o FBconfigs */ + oldErrorHandler = XSetErrorHandler(dmxNOPErrorHandler); + + /* Get FBConfigs of the back-end server */ + dmxScreen->fbconfigs = GetGLXFBConfigs(dmxScreen->beDisplay, + dmxScreen->glxMajorOpcode, + &dmxScreen->numFBConfigs); + + XSetErrorHandler(oldErrorHandler); + + dmxScreen->glxVisuals = + GetGLXVisualConfigs(dmxScreen->beDisplay, + DefaultScreen(dmxScreen->beDisplay), + &dmxScreen->numGlxVisuals); + + if (dmxScreen->fbconfigs) { + configs = + GetGLXVisualConfigsFromFBConfigs(dmxScreen->fbconfigs, + dmxScreen->numFBConfigs, + dmxScreen->beVisuals, + dmxScreen->beNumVisuals, + dmxScreen->glxVisuals, + dmxScreen->numGlxVisuals, + &nconfigs); + } else { + configs = dmxScreen->glxVisuals; + nconfigs = dmxScreen->numGlxVisuals; + } + + configprivs = malloc(nconfigs * sizeof(dmxGlxVisualPrivate*)); + + if (configs != NULL && configprivs != NULL) { + + /* Initialize our private info for each visual + * (currently only x_visual_depth and x_visual_class) + */ + for (i = 0; i < nconfigs; i++) { + + configprivs[i] = (dmxGlxVisualPrivate *) + malloc(sizeof(dmxGlxVisualPrivate)); + configprivs[i]->x_visual_depth = 0; + configprivs[i]->x_visual_class = 0; + + /* Find the visual depth */ + if (configs[i].vid > 0) { + int j; + for (j = 0; j < dmxScreen->beNumVisuals; j++) { + if (dmxScreen->beVisuals[j].visualid == + configs[i].vid) { + configprivs[i]->x_visual_depth = + dmxScreen->beVisuals[j].depth; + configprivs[i]->x_visual_class = + dmxScreen->beVisuals[j].class; + break; + } + } + } + } + + XFlush(dmxScreen->beDisplay); + } + } +#endif /* GLXEXT */ + + AddScreen(dmxScreenInit, argc, argv); + } + + /* Compute origin information. */ + dmxInitOrigins(); + + /* Compute overlap information. */ + dmxInitOverlap(); + + /* Make sure there is a global width/height available */ + dmxComputeWidthHeight(DMX_NO_RECOMPUTE_BOUNDING_BOX); + + /* FIXME: The following is temporarily placed here. When the DMX + * extension is available, it will be move there. + */ + dmxInitFonts(); + + /* Initialize the render extension */ + if (!noRenderExtension) + dmxInitRender(); + + /* Initialized things that need timer hooks */ + dmxStatInit(); + dmxSyncInit(); /* Calls RegisterBlockAndWakeupHandlers */ + + dmxLog(dmxInfo, "Shadow framebuffer support %s\n", + dmxShadowFB ? "enabled" : "disabled"); +} + +/* RATS: Assuming the fp string (which comes from the command-line argv + vector) is NULL-terminated, the buffer is large enough for the + strcpy. */ +static void dmxSetDefaultFontPath(char *fp) +{ + int fplen = strlen(fp) + 1; + + if (dmxFontPath) { + int len; + + len = strlen(dmxFontPath); + dmxFontPath = realloc(dmxFontPath, len+fplen+1); + dmxFontPath[len] = ','; + strncpy(&dmxFontPath[len+1], fp, fplen); + } else { + dmxFontPath = malloc(fplen); + strncpy(dmxFontPath, fp, fplen); + } + + defaultFontPath = dmxFontPath; +} + +/** This function is called in Xserver/os/utils.c from \a AbortServer(). + * We must ensure that backend and console state is restored in the + * event the server shutdown wasn't clean. */ +void AbortDDX(enum ExitCode error) +{ + int i; + + for (i=0; i < dmxNumScreens; i++) { + DMXScreenInfo *dmxScreen = &dmxScreens[i]; + + if (dmxScreen->beDisplay) XCloseDisplay(dmxScreen->beDisplay); + dmxScreen->beDisplay = NULL; + } +} + +#ifdef DDXBEFORERESET +/* This function is called in Xserver/dix/dispatch.c */ +void ddxBeforeReset(void) +{ +} +#endif + +/** This function is called in Xserver/dix/main.c from \a main() when + * dispatchException & DE_TERMINATE (which is the only way to exit the + * main loop without an interruption. */ +void ddxGiveUp(enum ExitCode error) +{ + AbortDDX(error); +} + +/** This function is called in Xserver/os/osinit.c from \a OsInit(). */ +void OsVendorInit(void) +{ +} + +/** This function is called in Xserver/os/utils.c from \a FatalError() + * and \a VFatalError(). (Note that setting the function pointer \a + * OsVendorVErrorFProc will cause \a VErrorF() (which is called by the + * two routines mentioned here, as well as by others) to use the + * referenced routine instead of \a vfprintf().) */ +void OsVendorFatalError(void) +{ +} + +/** Process our command line arguments. */ +int ddxProcessArgument(int argc, char *argv[], int i) +{ + int retval = 0; + + if (!strcmp(argv[i], "-display")) { + if (++i < argc) dmxConfigStoreDisplay(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-inputfrom") || !strcmp(argv[i], "-input")) { + if (++i < argc) dmxConfigStoreInput(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-xinputfrom") || !strcmp(argv[i],"-xinput")) { + if (++i < argc) dmxConfigStoreXInput(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-noshadowfb")) { + dmxLog(dmxWarning, + "-noshadowfb has been deprecated " + "since it is now the default\n"); + dmxShadowFB = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-nomulticursor")) { + dmxCursorNoMulti(); + retval = 1; + } else if (!strcmp(argv[i], "-shadowfb")) { + dmxShadowFB = TRUE; + retval = 1; + } else if (!strcmp(argv[i], "-configfile")) { + if (++i < argc) dmxConfigStoreFile(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-config")) { + if (++i < argc) dmxConfigStoreConfig(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-fontpath")) { + if (++i < argc) dmxSetDefaultFontPath(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-stat")) { + if ((i += 2) < argc) dmxStatActivate(argv[i-1], argv[i]); + retval = 3; + } else if (!strcmp(argv[i], "-syncbatch")) { + if (++i < argc) dmxSyncActivate(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-nooffscreenopt")) { + dmxOffScreenOpt = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-nosubdivprims")) { + dmxSubdividePrimitives = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-nowindowopt")) { + dmxLazyWindowCreation = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-noxkb")) { + dmxUseXKB = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-depth")) { + if (++i < argc) dmxDepth = atoi(argv[i]); + retval = 2; + } else if (!strcmp(argv[i], "-norender")) { + noRenderExtension = TRUE; + retval = 1; +#ifdef GLXEXT + } else if (!strcmp(argv[i], "-noglxproxy")) { + dmxGLXProxy = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-noglxswapgroup")) { + dmxGLXSwapGroupSupport = FALSE; + retval = 1; + } else if (!strcmp(argv[i], "-glxsyncswap")) { + dmxGLXSyncSwap = TRUE; + retval = 1; + } else if (!strcmp(argv[i], "-glxfinishswap")) { + dmxGLXFinishSwap = TRUE; + retval = 1; +#endif + } else if (!strcmp(argv[i], "-ignorebadfontpaths")) { + dmxIgnoreBadFontPaths = TRUE; + retval = 1; + } else if (!strcmp(argv[i], "-addremovescreens")) { + dmxAddRemoveScreens = TRUE; + retval = 1; + } else if (!strcmp(argv[i], "-param")) { + if ((i += 2) < argc) { + if (!strcasecmp(argv[i-1], "xkbrules")) + dmxConfigSetXkbRules(argv[i]); + else if (!strcasecmp(argv[i-1], "xkbmodel")) + dmxConfigSetXkbModel(argv[i]); + else if (!strcasecmp(argv[i-1], "xkblayout")) + dmxConfigSetXkbLayout(argv[i]); + else if (!strcasecmp(argv[i-1], "xkbvariant")) + dmxConfigSetXkbVariant(argv[i]); + else if (!strcasecmp(argv[i-1], "xkboptions")) + dmxConfigSetXkbOptions(argv[i]); + else + dmxLog(dmxWarning, + "-param requires: XkbRules, XkbModel, XkbLayout," + " XkbVariant, or XkbOptions\n"); + } + retval = 3; + } + if (!serverGeneration) dmxConfigSetMaxScreens(); + return retval; +} + +/** Provide succinct usage information for the DMX server. */ +void ddxUseMsg(void) +{ + ErrorF("\n\nDevice Dependent Usage:\n"); + ErrorF("-display string Specify the back-end display(s)\n"); + ErrorF("-input string Specify input source for core device\n"); + ErrorF("-xinput string Specify input source for XInput device\n"); + ErrorF("-shadowfb Enable shadow frame buffer\n"); + ErrorF("-configfile file Read from a configuration file\n"); + ErrorF("-config config Select a specific configuration\n"); + ErrorF("-nomulticursor Turn of multiple cursor support\n"); + ErrorF("-fontpath Sets the default font path\n"); + ErrorF("-stat inter scrns Print out performance statistics\n"); + ErrorF("-syncbatch inter Set interval for XSync batching\n"); + ErrorF("-nooffscreenopt Disable offscreen optimization\n"); + ErrorF("-nosubdivprims Disable primitive subdivision\n"); + ErrorF(" optimization\n"); + ErrorF("-nowindowopt Disable lazy window creation optimization\n"); + ErrorF("-noxkb Disable use of the XKB extension with\n"); + ErrorF(" backend displays (cf. -kb).\n"); + ErrorF("-depth Specify the default root window depth\n"); + ErrorF("-norender Disable RENDER extension support\n"); +#ifdef GLXEXT + ErrorF("-noglxproxy Disable GLX Proxy\n"); + ErrorF("-noglxswapgroup Disable swap group and swap barrier\n"); + ErrorF(" extensions in GLX proxy\n"); + ErrorF("-glxsyncswap Force XSync after swap buffers\n"); + ErrorF("-glxfinishswap Force glFinish after swap buffers\n"); +#endif + ErrorF("-ignorebadfontpaths Ignore bad font paths during initialization\n"); + ErrorF("-addremovescreens Enable dynamic screen addition/removal\n"); + ErrorF("-param ... Specify configuration parameters (e.g.,\n"); + ErrorF(" XkbRules, XkbModel, XkbLayout, etc.)\n"); + ErrorF("\n"); + ErrorF(" If the -input string matches a -display string, then input\n" + " is taken from that backend display. (XInput cannot be taken\n" + " from a backend display.) Placing \",console\" after the\n" + " display name will force a console window to be opened on\n" + " that display in addition to the backend input. This is\n" + " useful if the backend window does not cover the whole\n" + " physical display.\n\n"); + + ErrorF(" Otherwise, if the -input or -xinput string specifies another\n" + " X display, then a console window will be created on that\n" + " display. Placing \",windows\" or \",nowindows\" after the\n" + " display name will control the display of window outlines in\n" + " the console.\n\n"); + + ErrorF(" -input or -xinput dummy specifies no input.\n"); + ErrorF(" -input or -xinput local specifies the use of a raw keyboard,\n" + " mouse, or other (extension) device:\n" + " -input local,kbd,ps2 will use a ps2 mouse\n" + " -input local,kbd,ms will use a serial mouse\n" + " -input local,usb-kbd,usb-mou will use USB devices \n" + " -xinput local,usb-oth will use a non-mouse and\n" + " non-keyboard USB device with XInput\n\n"); + + ErrorF(" Special Keys:\n"); + ErrorF(" Ctrl-Alt-g Server grab/ungrab (console only)\n"); + ErrorF(" Ctrl-Alt-f Fine (1-pixel) mouse mode (console only)\n"); + ErrorF(" Ctrl-Alt-q Quit (core devices only)\n"); + ErrorF(" Ctrl-Alt-F* Switch to VC (local only)\n"); +} diff --git a/xorg-server/hw/kdrive/src/kdrive.c b/xorg-server/hw/kdrive/src/kdrive.c index 7d424dbcc..85fe190fc 100644 --- a/xorg-server/hw/kdrive/src/kdrive.c +++ b/xorg-server/hw/kdrive/src/kdrive.c @@ -233,7 +233,7 @@ KdProcessSwitch (void) #ifndef _MSC_VER
void
-AbortDDX(void)
+AbortDDX(enum ExitCode error)
{
KdDisableScreens ();
if (kdOsFuncs)
@@ -250,9 +250,9 @@ AbortDDX(void) }
void
-ddxGiveUp (void)
+ddxGiveUp (enum ExitCode error)
{
- AbortDDX ();
+ AbortDDX (error);
}
#endif
diff --git a/xorg-server/hw/vfb/InitOutput.c b/xorg-server/hw/vfb/InitOutput.c index 04253dc5a..31ed50533 100644 --- a/xorg-server/hw/vfb/InitOutput.c +++ b/xorg-server/hw/vfb/InitOutput.c @@ -1,969 +1,969 @@ -/*
-
-Copyright 1993, 1998 The Open Group
-
-Permission to use, copy, modify, distribute, and sell this software and its
-documentation for any purpose is hereby granted without fee, provided that
-the above copyright notice appear in all copies and that both that
-copyright notice and this permission notice appear in supporting
-documentation.
-
-The above copyright notice and this permission notice shall be included
-in all copies or substantial portions of the Software.
-
-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 OPEN GROUP 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.
-
-Except as contained in this notice, the name of The Open Group shall
-not be used in advertising or otherwise to promote the sale, use or
-other dealings in this Software without prior written authorization
-from The Open Group.
-
-*/
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#if defined(WIN32)
-#include <X11/Xwinsock.h>
-#endif
-#include <stdio.h>
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include <X11/Xos.h>
-#include "scrnintstr.h"
-#include "servermd.h"
-#define PSZ 8
-#include "fb.h"
-#include "mibstore.h"
-#include "colormapst.h"
-#include "gcstruct.h"
-#include "input.h"
-#include "mipointer.h"
-#include "micmap.h"
-#include <sys/types.h>
-#ifdef HAS_MMAP
-#include <sys/mman.h>
-#ifndef MAP_FILE
-#define MAP_FILE 0
-#endif
-#endif /* HAS_MMAP */
-#include <sys/stat.h>
-#include <errno.h>
-#ifndef WIN32
-#include <sys/param.h>
-#endif
-#include <X11/XWDFile.h>
-#ifdef HAS_SHM
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#endif /* HAS_SHM */
-#include "dix.h"
-#include "miline.h"
-
-#define VFB_DEFAULT_WIDTH 1280
-#define VFB_DEFAULT_HEIGHT 1024
-#define VFB_DEFAULT_DEPTH 8
-#define VFB_DEFAULT_WHITEPIXEL 1
-#define VFB_DEFAULT_BLACKPIXEL 0
-#define VFB_DEFAULT_LINEBIAS 0
-#define XWD_WINDOW_NAME_LEN 60
-
-typedef struct
-{
- int width;
- int paddedBytesWidth;
- int paddedWidth;
- int height;
- int depth;
- int bitsPerPixel;
- int sizeInBytes;
- int ncolors;
- char *pfbMemory;
- XWDColor *pXWDCmap;
- XWDFileHeader *pXWDHeader;
- Pixel blackPixel;
- Pixel whitePixel;
- unsigned int lineBias;
- CloseScreenProcPtr closeScreen;
-
-#ifdef HAS_MMAP
- int mmap_fd;
- char mmap_file[MAXPATHLEN];
-#endif
-
-#ifdef HAS_SHM
- int shmid;
-#endif
-} vfbScreenInfo, *vfbScreenInfoPtr;
-
-static int vfbNumScreens;
-static vfbScreenInfo *vfbScreens;
-static vfbScreenInfo defaultScreenInfo = {
- .width = VFB_DEFAULT_WIDTH,
- .height = VFB_DEFAULT_HEIGHT,
- .depth = VFB_DEFAULT_DEPTH,
- .blackPixel = VFB_DEFAULT_BLACKPIXEL,
- .whitePixel = VFB_DEFAULT_WHITEPIXEL,
- .lineBias = VFB_DEFAULT_LINEBIAS,
-};
-static Bool vfbPixmapDepths[33];
-#ifdef HAS_MMAP
-static char *pfbdir = NULL;
-#endif
-typedef enum { NORMAL_MEMORY_FB, SHARED_MEMORY_FB, MMAPPED_FILE_FB } fbMemType;
-static fbMemType fbmemtype = NORMAL_MEMORY_FB;
-static char needswap = 0;
-static Bool Render = TRUE;
-
-#define swapcopy16(_dst, _src) \
- if (needswap) { CARD16 _s = _src; cpswaps(_s, _dst); } \
- else _dst = _src;
-
-#define swapcopy32(_dst, _src) \
- if (needswap) { CARD32 _s = _src; cpswapl(_s, _dst); } \
- else _dst = _src;
-
-
-static void
-vfbInitializePixmapDepths(void)
-{
- int i;
- vfbPixmapDepths[1] = TRUE; /* always need bitmaps */
- for (i = 2; i <= 32; i++)
- vfbPixmapDepths[i] = FALSE;
-}
-
-static int
-vfbBitsPerPixel(int depth)
-{
- if (depth == 1) return 1;
- else if (depth <= 8) return 8;
- else if (depth <= 16) return 16;
- else return 32;
-}
-
-void
-ddxGiveUp(void)
-{
- int i;
-
- /* clean up the framebuffers */
-
- switch (fbmemtype)
- {
-#ifdef HAS_MMAP
- case MMAPPED_FILE_FB:
- for (i = 0; i < vfbNumScreens; i++)
- {
- if (-1 == unlink(vfbScreens[i].mmap_file))
- {
- perror("unlink");
- ErrorF("unlink %s failed, %s",
- vfbScreens[i].mmap_file, strerror(errno));
- }
- }
- break;
-#else /* HAS_MMAP */
- case MMAPPED_FILE_FB:
- break;
-#endif /* HAS_MMAP */
-
-#ifdef HAS_SHM
- case SHARED_MEMORY_FB:
- for (i = 0; i < vfbNumScreens; i++)
- {
- if (-1 == shmdt((char *)vfbScreens[i].pXWDHeader))
- {
- perror("shmdt");
- ErrorF("shmdt failed, %s", strerror(errno));
- }
- }
- break;
-#else /* HAS_SHM */
- case SHARED_MEMORY_FB:
- break;
-#endif /* HAS_SHM */
-
- case NORMAL_MEMORY_FB:
- for (i = 0; i < vfbNumScreens; i++)
- {
- free(vfbScreens[i].pXWDHeader);
- }
- break;
- }
-}
-
-void
-AbortDDX(void)
-{
- ddxGiveUp();
-}
-
-#ifdef __APPLE__
-void
-DarwinHandleGUI(int argc, char *argv[])
-{
-}
-#endif
-
-void
-OsVendorInit(void)
-{
-}
-
-void
-OsVendorFatalError(void)
-{
-}
-
-#if defined(DDXBEFORERESET)
-void ddxBeforeReset(void)
-{
- return;
-}
-#endif
-
-void
-ddxUseMsg(void)
-{
- ErrorF("-screen scrn WxHxD set screen's width, height, depth\n");
- ErrorF("-pixdepths list-of-int support given pixmap depths\n");
- ErrorF("+/-render turn on/off RENDER extension support"
- "(default on)\n");
- ErrorF("-linebias n adjust thin line pixelization\n");
- ErrorF("-blackpixel n pixel value for black\n");
- ErrorF("-whitepixel n pixel value for white\n");
-
-#ifdef HAS_MMAP
- ErrorF("-fbdir directory put framebuffers in mmap'ed files in directory\n");
-#endif
-
-#ifdef HAS_SHM
- ErrorF("-shmem put framebuffers in shared memory\n");
-#endif
-}
-
-int
-ddxProcessArgument(int argc, char *argv[], int i)
-{
- static Bool firstTime = TRUE;
- static int lastScreen = -1;
- vfbScreenInfo *currentScreen;
-
- if (firstTime)
- {
- vfbInitializePixmapDepths();
- firstTime = FALSE;
- }
-
- if (lastScreen == -1)
- currentScreen = &defaultScreenInfo;
- else
- currentScreen = &vfbScreens[lastScreen];
-
-#define CHECK_FOR_REQUIRED_ARGUMENTS(num) \
- if (((i + num) >= argc) || (!argv[i + num])) { \
- ErrorF("Required argument to %s not specified\n", argv[i]); \
- UseMsg(); \
- FatalError("Required argument to %s not specified\n", argv[i]); \
- }
-
- if (strcmp (argv[i], "-screen") == 0) /* -screen n WxHxD */
- {
- int screenNum;
- CHECK_FOR_REQUIRED_ARGUMENTS(2);
- screenNum = atoi(argv[i+1]);
- if (screenNum < 0)
- {
- ErrorF("Invalid screen number %d\n", screenNum);
- UseMsg();
- FatalError("Invalid screen number %d passed to -screen\n",
- screenNum);
- }
-
- if (vfbNumScreens <= screenNum)
- {
- vfbScreens = realloc(vfbScreens, sizeof(*vfbScreens) * (screenNum + 1));
- if (!vfbScreens)
- FatalError("Not enough memory for screen %d\n", screenNum);
- for (; vfbNumScreens <= screenNum; ++vfbNumScreens)
- vfbScreens[vfbNumScreens] = defaultScreenInfo;
- }
-
- if (3 != sscanf(argv[i+2], "%dx%dx%d",
- &vfbScreens[screenNum].width,
- &vfbScreens[screenNum].height,
- &vfbScreens[screenNum].depth))
- {
- ErrorF("Invalid screen configuration %s\n", argv[i+2]);
- UseMsg();
- FatalError("Invalid screen configuration %s for -screen %d\n",
- argv[i+2], screenNum);
- }
-
- lastScreen = screenNum;
- return 3;
- }
-
- if (strcmp (argv[i], "-pixdepths") == 0) /* -pixdepths list-of-depth */
- {
- int depth, ret = 1;
-
- CHECK_FOR_REQUIRED_ARGUMENTS(1);
- while ((++i < argc) && (depth = atoi(argv[i])) != 0)
- {
- if (depth < 0 || depth > 32)
- {
- ErrorF("Invalid pixmap depth %d\n", depth);
- UseMsg();
- FatalError("Invalid pixmap depth %d passed to -pixdepths\n",
- depth);
- }
- vfbPixmapDepths[depth] = TRUE;
- ret++;
- }
- return ret;
- }
-
- if (strcmp (argv[i], "+render") == 0) /* +render */
- {
- Render = TRUE;
- return 1;
- }
-
- if (strcmp (argv[i], "-render") == 0) /* -render */
- {
- Render = FALSE;
-#ifdef COMPOSITE
- noCompositeExtension = TRUE;
-#endif
- return 1;
- }
-
- if (strcmp (argv[i], "-blackpixel") == 0) /* -blackpixel n */
- {
- CHECK_FOR_REQUIRED_ARGUMENTS(1);
- currentScreen->blackPixel = atoi(argv[++i]);
- return 2;
- }
-
- if (strcmp (argv[i], "-whitepixel") == 0) /* -whitepixel n */
- {
- CHECK_FOR_REQUIRED_ARGUMENTS(1);
- currentScreen->whitePixel = atoi(argv[++i]);
- return 2;
- }
-
- if (strcmp (argv[i], "-linebias") == 0) /* -linebias n */
- {
- CHECK_FOR_REQUIRED_ARGUMENTS(1);
- currentScreen->lineBias = atoi(argv[++i]);
- return 2;
- }
-
-#ifdef HAS_MMAP
- if (strcmp (argv[i], "-fbdir") == 0) /* -fbdir directory */
- {
- CHECK_FOR_REQUIRED_ARGUMENTS(1);
- pfbdir = argv[++i];
- fbmemtype = MMAPPED_FILE_FB;
- return 2;
- }
-#endif /* HAS_MMAP */
-
-#ifdef HAS_SHM
- if (strcmp (argv[i], "-shmem") == 0) /* -shmem */
- {
- fbmemtype = SHARED_MEMORY_FB;
- return 1;
- }
-#endif
-
- return 0;
-}
-
-static DevPrivateKeyRec cmapScrPrivateKeyRec;
-#define cmapScrPrivateKey (&cmapScrPrivateKeyRec)
-
-#define GetInstalledColormap(s) ((ColormapPtr) dixLookupPrivate(&(s)->devPrivates, cmapScrPrivateKey))
-#define SetInstalledColormap(s,c) (dixSetPrivate(&(s)->devPrivates, cmapScrPrivateKey, c))
-
-static int
-vfbListInstalledColormaps(ScreenPtr pScreen, Colormap *pmaps)
-{
- /* By the time we are processing requests, we can guarantee that there
- * is always a colormap installed */
- *pmaps = GetInstalledColormap(pScreen)->mid;
- return 1;
-}
-
-
-static void
-vfbInstallColormap(ColormapPtr pmap)
-{
- ColormapPtr oldpmap = GetInstalledColormap(pmap->pScreen);
-
- if (pmap != oldpmap)
- {
- int entries;
- XWDFileHeader *pXWDHeader;
- XWDColor *pXWDCmap;
- VisualPtr pVisual;
- Pixel * ppix;
- xrgb * prgb;
- xColorItem *defs;
- int i;
-
- if(oldpmap != (ColormapPtr)None)
- WalkTree(pmap->pScreen, TellLostMap, (char *)&oldpmap->mid);
- /* Install pmap */
- SetInstalledColormap(pmap->pScreen, pmap);
- WalkTree(pmap->pScreen, TellGainedMap, (char *)&pmap->mid);
-
- entries = pmap->pVisual->ColormapEntries;
- pXWDHeader = vfbScreens[pmap->pScreen->myNum].pXWDHeader;
- pXWDCmap = vfbScreens[pmap->pScreen->myNum].pXWDCmap;
- pVisual = pmap->pVisual;
-
- swapcopy32(pXWDHeader->visual_class, pVisual->class);
- swapcopy32(pXWDHeader->red_mask, pVisual->redMask);
- swapcopy32(pXWDHeader->green_mask, pVisual->greenMask);
- swapcopy32(pXWDHeader->blue_mask, pVisual->blueMask);
- swapcopy32(pXWDHeader->bits_per_rgb, pVisual->bitsPerRGBValue);
- swapcopy32(pXWDHeader->colormap_entries, pVisual->ColormapEntries);
-
- ppix = (Pixel *)malloc(entries * sizeof(Pixel));
- prgb = (xrgb *)malloc(entries * sizeof(xrgb));
- defs = (xColorItem *)malloc(entries * sizeof(xColorItem));
-
- for (i = 0; i < entries; i++) ppix[i] = i;
- /* XXX truecolor */
- QueryColors(pmap, entries, ppix, prgb, serverClient);
-
- for (i = 0; i < entries; i++) { /* convert xrgbs to xColorItems */
- defs[i].pixel = ppix[i] & 0xff; /* change pixel to index */
- defs[i].red = prgb[i].red;
- defs[i].green = prgb[i].green;
- defs[i].blue = prgb[i].blue;
- defs[i].flags = DoRed|DoGreen|DoBlue;
- }
- (*pmap->pScreen->StoreColors)(pmap, entries, defs);
-
- free(ppix);
- free(prgb);
- free(defs);
- }
-}
-
-static void
-vfbUninstallColormap(ColormapPtr pmap)
-{
- ColormapPtr curpmap = GetInstalledColormap(pmap->pScreen);
-
- if(pmap == curpmap)
- {
- if (pmap->mid != pmap->pScreen->defColormap)
- {
- dixLookupResourceByType((pointer *)&curpmap,
- pmap->pScreen->defColormap,
- RT_COLORMAP, serverClient,
- DixInstallAccess);
- (*pmap->pScreen->InstallColormap)(curpmap);
- }
- }
-}
-
-static void
-vfbStoreColors(ColormapPtr pmap, int ndef, xColorItem *pdefs)
-{
- XWDColor *pXWDCmap;
- int i;
-
- if (pmap != GetInstalledColormap(pmap->pScreen))
- {
- return;
- }
-
- pXWDCmap = vfbScreens[pmap->pScreen->myNum].pXWDCmap;
-
- if ((pmap->pVisual->class | DynamicClass) == DirectColor)
- {
- return;
- }
-
- for (i = 0; i < ndef; i++)
- {
- if (pdefs[i].flags & DoRed)
- {
- swapcopy16(pXWDCmap[pdefs[i].pixel].red, pdefs[i].red);
- }
- if (pdefs[i].flags & DoGreen)
- {
- swapcopy16(pXWDCmap[pdefs[i].pixel].green, pdefs[i].green);
- }
- if (pdefs[i].flags & DoBlue)
- {
- swapcopy16(pXWDCmap[pdefs[i].pixel].blue, pdefs[i].blue);
- }
- }
-}
-
-static Bool
-vfbSaveScreen(ScreenPtr pScreen, int on)
-{
- return TRUE;
-}
-
-#ifdef HAS_MMAP
-
-/* this flushes any changes to the screens out to the mmapped file */
-static void
-vfbBlockHandler(pointer blockData, OSTimePtr pTimeout, pointer pReadmask)
-{
- int i;
-
- for (i = 0; i < vfbNumScreens; i++)
- {
-#ifdef MS_ASYNC
- if (-1 == msync((caddr_t)vfbScreens[i].pXWDHeader,
- (size_t)vfbScreens[i].sizeInBytes, MS_ASYNC))
-#else
- /* silly NetBSD and who else? */
- if (-1 == msync((caddr_t)vfbScreens[i].pXWDHeader,
- (size_t)vfbScreens[i].sizeInBytes))
-#endif
- {
- perror("msync");
- ErrorF("msync failed, %s", strerror(errno));
- }
- }
-}
-
-
-static void
-vfbWakeupHandler(pointer blockData, int result, pointer pReadmask)
-{
-}
-
-
-static void
-vfbAllocateMmappedFramebuffer(vfbScreenInfoPtr pvfb)
-{
-#define DUMMY_BUFFER_SIZE 65536
- char dummyBuffer[DUMMY_BUFFER_SIZE];
- int currentFileSize, writeThisTime;
-
- sprintf(pvfb->mmap_file, "%s/Xvfb_screen%d", pfbdir, (int) (pvfb - vfbScreens));
- if (-1 == (pvfb->mmap_fd = open(pvfb->mmap_file, O_CREAT|O_RDWR, 0666)))
- {
- perror("open");
- ErrorF("open %s failed, %s", pvfb->mmap_file, strerror(errno));
- return;
- }
-
- /* Extend the file to be the proper size */
-
- memset(dummyBuffer, 0, DUMMY_BUFFER_SIZE);
- for (currentFileSize = 0;
- currentFileSize < pvfb->sizeInBytes;
- currentFileSize += writeThisTime)
- {
- writeThisTime = min(DUMMY_BUFFER_SIZE,
- pvfb->sizeInBytes - currentFileSize);
- if (-1 == write(pvfb->mmap_fd, dummyBuffer, writeThisTime))
- {
- perror("write");
- ErrorF("write %s failed, %s", pvfb->mmap_file, strerror(errno));
- return;
- }
- }
-
- /* try to mmap the file */
-
- pvfb->pXWDHeader = (XWDFileHeader *)mmap((caddr_t)NULL, pvfb->sizeInBytes,
- PROT_READ|PROT_WRITE,
- MAP_FILE|MAP_SHARED,
- pvfb->mmap_fd, 0);
- if (-1 == (long)pvfb->pXWDHeader)
- {
- perror("mmap");
- ErrorF("mmap %s failed, %s", pvfb->mmap_file, strerror(errno));
- pvfb->pXWDHeader = NULL;
- return;
- }
-
- if (!RegisterBlockAndWakeupHandlers(vfbBlockHandler, vfbWakeupHandler,
- NULL))
- {
- pvfb->pXWDHeader = NULL;
- }
-}
-#endif /* HAS_MMAP */
-
-
-#ifdef HAS_SHM
-static void
-vfbAllocateSharedMemoryFramebuffer(vfbScreenInfoPtr pvfb)
-{
- /* create the shared memory segment */
-
- pvfb->shmid = shmget(IPC_PRIVATE, pvfb->sizeInBytes, IPC_CREAT|0777);
- if (pvfb->shmid < 0)
- {
- perror("shmget");
- ErrorF("shmget %d bytes failed, %s", pvfb->sizeInBytes, strerror(errno));
- return;
- }
-
- /* try to attach it */
-
- pvfb->pXWDHeader = (XWDFileHeader *)shmat(pvfb->shmid, 0, 0);
- if (-1 == (long)pvfb->pXWDHeader)
- {
- perror("shmat");
- ErrorF("shmat failed, %s", strerror(errno));
- pvfb->pXWDHeader = NULL;
- return;
- }
-
- ErrorF("screen %d shmid %d\n", (int) (pvfb - vfbScreens), pvfb->shmid);
-}
-#endif /* HAS_SHM */
-
-static char *
-vfbAllocateFramebufferMemory(vfbScreenInfoPtr pvfb)
-{
- if (pvfb->pfbMemory) return pvfb->pfbMemory; /* already done */
-
- pvfb->sizeInBytes = pvfb->paddedBytesWidth * pvfb->height;
-
- /* Calculate how many entries in colormap. This is rather bogus, because
- * the visuals haven't even been set up yet, but we need to know because we
- * have to allocate space in the file for the colormap. The number 10
- * below comes from the MAX_PSEUDO_DEPTH define in cfbcmap.c.
- */
-
- if (pvfb->depth <= 10)
- { /* single index colormaps */
- pvfb->ncolors = 1 << pvfb->depth;
- }
- else
- { /* decomposed colormaps */
- int nplanes_per_color_component = pvfb->depth / 3;
- if (pvfb->depth % 3) nplanes_per_color_component++;
- pvfb->ncolors = 1 << nplanes_per_color_component;
- }
-
- /* add extra bytes for XWDFileHeader, window name, and colormap */
-
- pvfb->sizeInBytes += SIZEOF(XWDheader) + XWD_WINDOW_NAME_LEN +
- pvfb->ncolors * SIZEOF(XWDColor);
-
- pvfb->pXWDHeader = NULL;
- switch (fbmemtype)
- {
-#ifdef HAS_MMAP
- case MMAPPED_FILE_FB: vfbAllocateMmappedFramebuffer(pvfb); break;
-#else
- case MMAPPED_FILE_FB: break;
-#endif
-
-#ifdef HAS_SHM
- case SHARED_MEMORY_FB: vfbAllocateSharedMemoryFramebuffer(pvfb); break;
-#else
- case SHARED_MEMORY_FB: break;
-#endif
-
- case NORMAL_MEMORY_FB:
- pvfb->pXWDHeader = (XWDFileHeader *)malloc(pvfb->sizeInBytes);
- break;
- }
-
- if (pvfb->pXWDHeader)
- {
- pvfb->pXWDCmap = (XWDColor *)((char *)pvfb->pXWDHeader
- + SIZEOF(XWDheader) + XWD_WINDOW_NAME_LEN);
- pvfb->pfbMemory = (char *)(pvfb->pXWDCmap + pvfb->ncolors);
-
- return pvfb->pfbMemory;
- }
- else
- return NULL;
-}
-
-
-static void
-vfbWriteXWDFileHeader(ScreenPtr pScreen)
-{
- vfbScreenInfoPtr pvfb = &vfbScreens[pScreen->myNum];
- XWDFileHeader *pXWDHeader = pvfb->pXWDHeader;
- char hostname[XWD_WINDOW_NAME_LEN];
- unsigned long swaptest = 1;
- int i;
-
- needswap = *(char *) &swaptest;
-
- pXWDHeader->header_size = (char *)pvfb->pXWDCmap - (char *)pvfb->pXWDHeader;
- pXWDHeader->file_version = XWD_FILE_VERSION;
-
- pXWDHeader->pixmap_format = ZPixmap;
- pXWDHeader->pixmap_depth = pvfb->depth;
- pXWDHeader->pixmap_height = pXWDHeader->window_height = pvfb->height;
- pXWDHeader->xoffset = 0;
- pXWDHeader->byte_order = IMAGE_BYTE_ORDER;
- pXWDHeader->bitmap_bit_order = BITMAP_BIT_ORDER;
-#ifndef INTERNAL_VS_EXTERNAL_PADDING
- pXWDHeader->pixmap_width = pXWDHeader->window_width = pvfb->width;
- pXWDHeader->bitmap_unit = BITMAP_SCANLINE_UNIT;
- pXWDHeader->bitmap_pad = BITMAP_SCANLINE_PAD;
-#else
- pXWDHeader->pixmap_width = pXWDHeader->window_width = pvfb->paddedWidth;
- pXWDHeader->bitmap_unit = BITMAP_SCANLINE_UNIT_PROTO;
- pXWDHeader->bitmap_pad = BITMAP_SCANLINE_PAD_PROTO;
-#endif
- pXWDHeader->bits_per_pixel = pvfb->bitsPerPixel;
- pXWDHeader->bytes_per_line = pvfb->paddedBytesWidth;
- pXWDHeader->ncolors = pvfb->ncolors;
-
- /* visual related fields are written when colormap is installed */
-
- pXWDHeader->window_x = pXWDHeader->window_y = 0;
- pXWDHeader->window_bdrwidth = 0;
-
- /* write xwd "window" name: Xvfb hostname:server.screen */
-
- if (-1 == gethostname(hostname, sizeof(hostname)))
- hostname[0] = 0;
- else
- hostname[XWD_WINDOW_NAME_LEN-1] = 0;
- sprintf((char *)(pXWDHeader+1), "Xvfb %s:%s.%d", hostname, display,
- pScreen->myNum);
-
- /* write colormap pixel slot values */
-
- for (i = 0; i < pvfb->ncolors; i++)
- {
- pvfb->pXWDCmap[i].pixel = i;
- }
-
- /* byte swap to most significant byte first */
-
- if (needswap)
- {
- SwapLongs((CARD32 *)pXWDHeader, SIZEOF(XWDheader)/4);
- for (i = 0; i < pvfb->ncolors; i++)
- {
- register char n;
- swapl(&pvfb->pXWDCmap[i].pixel, n);
- }
- }
-}
-
-
-static Bool
-vfbCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y)
-{
- return FALSE;
-}
-
-static void
-vfbCrossScreen (ScreenPtr pScreen, Bool entering)
-{
-}
-
-static miPointerScreenFuncRec vfbPointerCursorFuncs =
-{
- vfbCursorOffScreen,
- vfbCrossScreen,
- miPointerWarpCursor
-};
-
-static Bool
-vfbCloseScreen(int index, ScreenPtr pScreen)
-{
- vfbScreenInfoPtr pvfb = &vfbScreens[index];
- int i;
-
- pScreen->CloseScreen = pvfb->closeScreen;
-
- /*
- * XXX probably lots of stuff to clean. For now,
- * clear installed colormaps so that server reset works correctly.
- */
- for (i = 0; i < screenInfo.numScreens; i++)
- SetInstalledColormap(screenInfo.screens[i], NULL);
-
- return pScreen->CloseScreen(index, pScreen);
-}
-
-static Bool
-vfbScreenInit(int index, ScreenPtr pScreen, int argc, char **argv)
-{
- vfbScreenInfoPtr pvfb = &vfbScreens[index];
- int dpix = monitorResolution, dpiy = monitorResolution;
- int ret;
- char *pbits;
-
- if (!dixRegisterPrivateKey(&cmapScrPrivateKeyRec, PRIVATE_SCREEN, 0))
- return FALSE;
-
- if (dpix == 0)
- dpix = 100;
-
- if (dpiy == 0)
- dpiy = 100;
-
- pvfb->paddedBytesWidth = PixmapBytePad(pvfb->width, pvfb->depth);
- pvfb->bitsPerPixel = vfbBitsPerPixel(pvfb->depth);
- if (pvfb->bitsPerPixel >= 8 )
- pvfb->paddedWidth = pvfb->paddedBytesWidth / (pvfb->bitsPerPixel / 8);
- else
- pvfb->paddedWidth = pvfb->paddedBytesWidth * 8;
- pbits = vfbAllocateFramebufferMemory(pvfb);
- if (!pbits) return FALSE;
-
- switch (pvfb->depth) {
- case 8:
- miSetVisualTypesAndMasks (8,
- ((1 << StaticGray) |
- (1 << GrayScale) |
- (1 << StaticColor) |
- (1 << PseudoColor) |
- (1 << TrueColor) |
- (1 << DirectColor)),
- 8, PseudoColor, 0, 0, 0);
- break;
- case 15:
- miSetVisualTypesAndMasks (15,
- ((1 << TrueColor) |
- (1 << DirectColor)),
- 8, TrueColor, 0x7c00, 0x03e0, 0x001f);
- break;
- case 16:
- miSetVisualTypesAndMasks (16,
- ((1 << TrueColor) |
- (1 << DirectColor)),
- 8, TrueColor, 0xf800, 0x07e0, 0x001f);
- break;
- case 24:
- miSetVisualTypesAndMasks (24,
- ((1 << TrueColor) |
- (1 << DirectColor)),
- 8, TrueColor, 0xff0000, 0x00ff00, 0x0000ff);
- break;
- case 30:
- miSetVisualTypesAndMasks (30,
- ((1 << TrueColor) |
- (1 << DirectColor)),
- 10, TrueColor, 0x3ff00000, 0x000ffc00, 0x000003ff);
- break;
- }
-
- miSetPixmapDepths ();
-
- ret = fbScreenInit(pScreen, pbits, pvfb->width, pvfb->height,
- dpix, dpiy, pvfb->paddedWidth,pvfb->bitsPerPixel);
- if (ret && Render)
- fbPictureInit (pScreen, 0, 0);
-
- if (!ret) return FALSE;
-
- pScreen->InstallColormap = vfbInstallColormap;
- pScreen->UninstallColormap = vfbUninstallColormap;
- pScreen->ListInstalledColormaps = vfbListInstalledColormaps;
-
- pScreen->SaveScreen = vfbSaveScreen;
- pScreen->StoreColors = vfbStoreColors;
-
- miDCInitialize(pScreen, &vfbPointerCursorFuncs);
-
- vfbWriteXWDFileHeader(pScreen);
-
- pScreen->blackPixel = pvfb->blackPixel;
- pScreen->whitePixel = pvfb->whitePixel;
-
- ret = fbCreateDefColormap(pScreen);
-
- miSetZeroLineBias(pScreen, pvfb->lineBias);
-
- pvfb->closeScreen = pScreen->CloseScreen;
- pScreen->CloseScreen = vfbCloseScreen;
-
- return ret;
-
-} /* end vfbScreenInit */
-
-
-void
-InitOutput(ScreenInfo *screenInfo, int argc, char **argv)
-{
- int i;
- int NumFormats = 0;
-
- /* initialize pixmap formats */
-
- /* must have a pixmap depth to match every screen depth */
- for (i = 0; i < vfbNumScreens; i++)
- {
- vfbPixmapDepths[vfbScreens[i].depth] = TRUE;
- }
-
- /* RENDER needs a good set of pixmaps. */
- if (Render) {
- vfbPixmapDepths[1] = TRUE;
- vfbPixmapDepths[4] = TRUE;
- vfbPixmapDepths[8] = TRUE;
-#if 0
- vfbPixmapDepths[12] = TRUE;
-#endif
-/* vfbPixmapDepths[15] = TRUE; */
- vfbPixmapDepths[16] = TRUE;
- vfbPixmapDepths[24] = TRUE;
-#if 0
- vfbPixmapDepths[30] = TRUE;
-#endif
- vfbPixmapDepths[32] = TRUE;
- }
-
- for (i = 1; i <= 32; i++)
- {
- if (vfbPixmapDepths[i])
- {
- if (NumFormats >= MAXFORMATS)
- FatalError ("MAXFORMATS is too small for this server\n");
- screenInfo->formats[NumFormats].depth = i;
- screenInfo->formats[NumFormats].bitsPerPixel = vfbBitsPerPixel(i);
- screenInfo->formats[NumFormats].scanlinePad = BITMAP_SCANLINE_PAD;
- NumFormats++;
- }
- }
-
- screenInfo->imageByteOrder = IMAGE_BYTE_ORDER;
- screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
- screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
- screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER;
- screenInfo->numPixmapFormats = NumFormats;
-
- /* initialize screens */
-
- if (vfbNumScreens < 1)
- {
- vfbScreens = &defaultScreenInfo;
- vfbNumScreens = 1;
- }
- for (i = 0; i < vfbNumScreens; i++)
- {
- if (-1 == AddScreen(vfbScreenInit, argc, argv))
- {
- FatalError("Couldn't add screen %d", i);
- }
- }
-
-} /* end InitOutput */
+/* + +Copyright 1993, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +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 OPEN GROUP 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. + +Except as contained in this notice, the name of The Open Group shall +not be used in advertising or otherwise to promote the sale, use or +other dealings in this Software without prior written authorization +from The Open Group. + +*/ + +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#endif + +#if defined(WIN32) +#include <X11/Xwinsock.h> +#endif +#include <stdio.h> +#include <X11/X.h> +#include <X11/Xproto.h> +#include <X11/Xos.h> +#include "scrnintstr.h" +#include "servermd.h" +#define PSZ 8 +#include "fb.h" +#include "mibstore.h" +#include "colormapst.h" +#include "gcstruct.h" +#include "input.h" +#include "mipointer.h" +#include "micmap.h" +#include <sys/types.h> +#ifdef HAS_MMAP +#include <sys/mman.h> +#ifndef MAP_FILE +#define MAP_FILE 0 +#endif +#endif /* HAS_MMAP */ +#include <sys/stat.h> +#include <errno.h> +#ifndef WIN32 +#include <sys/param.h> +#endif +#include <X11/XWDFile.h> +#ifdef HAS_SHM +#include <sys/ipc.h> +#include <sys/shm.h> +#endif /* HAS_SHM */ +#include "dix.h" +#include "miline.h" + +#define VFB_DEFAULT_WIDTH 1280 +#define VFB_DEFAULT_HEIGHT 1024 +#define VFB_DEFAULT_DEPTH 8 +#define VFB_DEFAULT_WHITEPIXEL 1 +#define VFB_DEFAULT_BLACKPIXEL 0 +#define VFB_DEFAULT_LINEBIAS 0 +#define XWD_WINDOW_NAME_LEN 60 + +typedef struct +{ + int width; + int paddedBytesWidth; + int paddedWidth; + int height; + int depth; + int bitsPerPixel; + int sizeInBytes; + int ncolors; + char *pfbMemory; + XWDColor *pXWDCmap; + XWDFileHeader *pXWDHeader; + Pixel blackPixel; + Pixel whitePixel; + unsigned int lineBias; + CloseScreenProcPtr closeScreen; + +#ifdef HAS_MMAP + int mmap_fd; + char mmap_file[MAXPATHLEN]; +#endif + +#ifdef HAS_SHM + int shmid; +#endif +} vfbScreenInfo, *vfbScreenInfoPtr; + +static int vfbNumScreens; +static vfbScreenInfo *vfbScreens; +static vfbScreenInfo defaultScreenInfo = { + .width = VFB_DEFAULT_WIDTH, + .height = VFB_DEFAULT_HEIGHT, + .depth = VFB_DEFAULT_DEPTH, + .blackPixel = VFB_DEFAULT_BLACKPIXEL, + .whitePixel = VFB_DEFAULT_WHITEPIXEL, + .lineBias = VFB_DEFAULT_LINEBIAS, +}; +static Bool vfbPixmapDepths[33]; +#ifdef HAS_MMAP +static char *pfbdir = NULL; +#endif +typedef enum { NORMAL_MEMORY_FB, SHARED_MEMORY_FB, MMAPPED_FILE_FB } fbMemType; +static fbMemType fbmemtype = NORMAL_MEMORY_FB; +static char needswap = 0; +static Bool Render = TRUE; + +#define swapcopy16(_dst, _src) \ + if (needswap) { CARD16 _s = _src; cpswaps(_s, _dst); } \ + else _dst = _src; + +#define swapcopy32(_dst, _src) \ + if (needswap) { CARD32 _s = _src; cpswapl(_s, _dst); } \ + else _dst = _src; + + +static void +vfbInitializePixmapDepths(void) +{ + int i; + vfbPixmapDepths[1] = TRUE; /* always need bitmaps */ + for (i = 2; i <= 32; i++) + vfbPixmapDepths[i] = FALSE; +} + +static int +vfbBitsPerPixel(int depth) +{ + if (depth == 1) return 1; + else if (depth <= 8) return 8; + else if (depth <= 16) return 16; + else return 32; +} + +void +ddxGiveUp(enum ExitCode error) +{ + int i; + + /* clean up the framebuffers */ + + switch (fbmemtype) + { +#ifdef HAS_MMAP + case MMAPPED_FILE_FB: + for (i = 0; i < vfbNumScreens; i++) + { + if (-1 == unlink(vfbScreens[i].mmap_file)) + { + perror("unlink"); + ErrorF("unlink %s failed, %s", + vfbScreens[i].mmap_file, strerror(errno)); + } + } + break; +#else /* HAS_MMAP */ + case MMAPPED_FILE_FB: + break; +#endif /* HAS_MMAP */ + +#ifdef HAS_SHM + case SHARED_MEMORY_FB: + for (i = 0; i < vfbNumScreens; i++) + { + if (-1 == shmdt((char *)vfbScreens[i].pXWDHeader)) + { + perror("shmdt"); + ErrorF("shmdt failed, %s", strerror(errno)); + } + } + break; +#else /* HAS_SHM */ + case SHARED_MEMORY_FB: + break; +#endif /* HAS_SHM */ + + case NORMAL_MEMORY_FB: + for (i = 0; i < vfbNumScreens; i++) + { + free(vfbScreens[i].pXWDHeader); + } + break; + } +} + +void +AbortDDX(enum ExitCode error) +{ + ddxGiveUp(error); +} + +#ifdef __APPLE__ +void +DarwinHandleGUI(int argc, char *argv[]) +{ +} +#endif + +void +OsVendorInit(void) +{ +} + +void +OsVendorFatalError(void) +{ +} + +#if defined(DDXBEFORERESET) +void ddxBeforeReset(void) +{ + return; +} +#endif + +void +ddxUseMsg(void) +{ + ErrorF("-screen scrn WxHxD set screen's width, height, depth\n"); + ErrorF("-pixdepths list-of-int support given pixmap depths\n"); + ErrorF("+/-render turn on/off RENDER extension support" + "(default on)\n"); + ErrorF("-linebias n adjust thin line pixelization\n"); + ErrorF("-blackpixel n pixel value for black\n"); + ErrorF("-whitepixel n pixel value for white\n"); + +#ifdef HAS_MMAP + ErrorF("-fbdir directory put framebuffers in mmap'ed files in directory\n"); +#endif + +#ifdef HAS_SHM + ErrorF("-shmem put framebuffers in shared memory\n"); +#endif +} + +int +ddxProcessArgument(int argc, char *argv[], int i) +{ + static Bool firstTime = TRUE; + static int lastScreen = -1; + vfbScreenInfo *currentScreen; + + if (firstTime) + { + vfbInitializePixmapDepths(); + firstTime = FALSE; + } + + if (lastScreen == -1) + currentScreen = &defaultScreenInfo; + else + currentScreen = &vfbScreens[lastScreen]; + +#define CHECK_FOR_REQUIRED_ARGUMENTS(num) \ + if (((i + num) >= argc) || (!argv[i + num])) { \ + ErrorF("Required argument to %s not specified\n", argv[i]); \ + UseMsg(); \ + FatalError("Required argument to %s not specified\n", argv[i]); \ + } + + if (strcmp (argv[i], "-screen") == 0) /* -screen n WxHxD */ + { + int screenNum; + CHECK_FOR_REQUIRED_ARGUMENTS(2); + screenNum = atoi(argv[i+1]); + if (screenNum < 0) + { + ErrorF("Invalid screen number %d\n", screenNum); + UseMsg(); + FatalError("Invalid screen number %d passed to -screen\n", + screenNum); + } + + if (vfbNumScreens <= screenNum) + { + vfbScreens = realloc(vfbScreens, sizeof(*vfbScreens) * (screenNum + 1)); + if (!vfbScreens) + FatalError("Not enough memory for screen %d\n", screenNum); + for (; vfbNumScreens <= screenNum; ++vfbNumScreens) + vfbScreens[vfbNumScreens] = defaultScreenInfo; + } + + if (3 != sscanf(argv[i+2], "%dx%dx%d", + &vfbScreens[screenNum].width, + &vfbScreens[screenNum].height, + &vfbScreens[screenNum].depth)) + { + ErrorF("Invalid screen configuration %s\n", argv[i+2]); + UseMsg(); + FatalError("Invalid screen configuration %s for -screen %d\n", + argv[i+2], screenNum); + } + + lastScreen = screenNum; + return 3; + } + + if (strcmp (argv[i], "-pixdepths") == 0) /* -pixdepths list-of-depth */ + { + int depth, ret = 1; + + CHECK_FOR_REQUIRED_ARGUMENTS(1); + while ((++i < argc) && (depth = atoi(argv[i])) != 0) + { + if (depth < 0 || depth > 32) + { + ErrorF("Invalid pixmap depth %d\n", depth); + UseMsg(); + FatalError("Invalid pixmap depth %d passed to -pixdepths\n", + depth); + } + vfbPixmapDepths[depth] = TRUE; + ret++; + } + return ret; + } + + if (strcmp (argv[i], "+render") == 0) /* +render */ + { + Render = TRUE; + return 1; + } + + if (strcmp (argv[i], "-render") == 0) /* -render */ + { + Render = FALSE; +#ifdef COMPOSITE + noCompositeExtension = TRUE; +#endif + return 1; + } + + if (strcmp (argv[i], "-blackpixel") == 0) /* -blackpixel n */ + { + CHECK_FOR_REQUIRED_ARGUMENTS(1); + currentScreen->blackPixel = atoi(argv[++i]); + return 2; + } + + if (strcmp (argv[i], "-whitepixel") == 0) /* -whitepixel n */ + { + CHECK_FOR_REQUIRED_ARGUMENTS(1); + currentScreen->whitePixel = atoi(argv[++i]); + return 2; + } + + if (strcmp (argv[i], "-linebias") == 0) /* -linebias n */ + { + CHECK_FOR_REQUIRED_ARGUMENTS(1); + currentScreen->lineBias = atoi(argv[++i]); + return 2; + } + +#ifdef HAS_MMAP + if (strcmp (argv[i], "-fbdir") == 0) /* -fbdir directory */ + { + CHECK_FOR_REQUIRED_ARGUMENTS(1); + pfbdir = argv[++i]; + fbmemtype = MMAPPED_FILE_FB; + return 2; + } +#endif /* HAS_MMAP */ + +#ifdef HAS_SHM + if (strcmp (argv[i], "-shmem") == 0) /* -shmem */ + { + fbmemtype = SHARED_MEMORY_FB; + return 1; + } +#endif + + return 0; +} + +static DevPrivateKeyRec cmapScrPrivateKeyRec; +#define cmapScrPrivateKey (&cmapScrPrivateKeyRec) + +#define GetInstalledColormap(s) ((ColormapPtr) dixLookupPrivate(&(s)->devPrivates, cmapScrPrivateKey)) +#define SetInstalledColormap(s,c) (dixSetPrivate(&(s)->devPrivates, cmapScrPrivateKey, c)) + +static int +vfbListInstalledColormaps(ScreenPtr pScreen, Colormap *pmaps) +{ + /* By the time we are processing requests, we can guarantee that there + * is always a colormap installed */ + *pmaps = GetInstalledColormap(pScreen)->mid; + return 1; +} + + +static void +vfbInstallColormap(ColormapPtr pmap) +{ + ColormapPtr oldpmap = GetInstalledColormap(pmap->pScreen); + + if (pmap != oldpmap) + { + int entries; + XWDFileHeader *pXWDHeader; + XWDColor *pXWDCmap; + VisualPtr pVisual; + Pixel * ppix; + xrgb * prgb; + xColorItem *defs; + int i; + + if(oldpmap != (ColormapPtr)None) + WalkTree(pmap->pScreen, TellLostMap, (char *)&oldpmap->mid); + /* Install pmap */ + SetInstalledColormap(pmap->pScreen, pmap); + WalkTree(pmap->pScreen, TellGainedMap, (char *)&pmap->mid); + + entries = pmap->pVisual->ColormapEntries; + pXWDHeader = vfbScreens[pmap->pScreen->myNum].pXWDHeader; + pXWDCmap = vfbScreens[pmap->pScreen->myNum].pXWDCmap; + pVisual = pmap->pVisual; + + swapcopy32(pXWDHeader->visual_class, pVisual->class); + swapcopy32(pXWDHeader->red_mask, pVisual->redMask); + swapcopy32(pXWDHeader->green_mask, pVisual->greenMask); + swapcopy32(pXWDHeader->blue_mask, pVisual->blueMask); + swapcopy32(pXWDHeader->bits_per_rgb, pVisual->bitsPerRGBValue); + swapcopy32(pXWDHeader->colormap_entries, pVisual->ColormapEntries); + + ppix = (Pixel *)malloc(entries * sizeof(Pixel)); + prgb = (xrgb *)malloc(entries * sizeof(xrgb)); + defs = (xColorItem *)malloc(entries * sizeof(xColorItem)); + + for (i = 0; i < entries; i++) ppix[i] = i; + /* XXX truecolor */ + QueryColors(pmap, entries, ppix, prgb, serverClient); + + for (i = 0; i < entries; i++) { /* convert xrgbs to xColorItems */ + defs[i].pixel = ppix[i] & 0xff; /* change pixel to index */ + defs[i].red = prgb[i].red; + defs[i].green = prgb[i].green; + defs[i].blue = prgb[i].blue; + defs[i].flags = DoRed|DoGreen|DoBlue; + } + (*pmap->pScreen->StoreColors)(pmap, entries, defs); + + free(ppix); + free(prgb); + free(defs); + } +} + +static void +vfbUninstallColormap(ColormapPtr pmap) +{ + ColormapPtr curpmap = GetInstalledColormap(pmap->pScreen); + + if(pmap == curpmap) + { + if (pmap->mid != pmap->pScreen->defColormap) + { + dixLookupResourceByType((pointer *)&curpmap, + pmap->pScreen->defColormap, + RT_COLORMAP, serverClient, + DixInstallAccess); + (*pmap->pScreen->InstallColormap)(curpmap); + } + } +} + +static void +vfbStoreColors(ColormapPtr pmap, int ndef, xColorItem *pdefs) +{ + XWDColor *pXWDCmap; + int i; + + if (pmap != GetInstalledColormap(pmap->pScreen)) + { + return; + } + + pXWDCmap = vfbScreens[pmap->pScreen->myNum].pXWDCmap; + + if ((pmap->pVisual->class | DynamicClass) == DirectColor) + { + return; + } + + for (i = 0; i < ndef; i++) + { + if (pdefs[i].flags & DoRed) + { + swapcopy16(pXWDCmap[pdefs[i].pixel].red, pdefs[i].red); + } + if (pdefs[i].flags & DoGreen) + { + swapcopy16(pXWDCmap[pdefs[i].pixel].green, pdefs[i].green); + } + if (pdefs[i].flags & DoBlue) + { + swapcopy16(pXWDCmap[pdefs[i].pixel].blue, pdefs[i].blue); + } + } +} + +static Bool +vfbSaveScreen(ScreenPtr pScreen, int on) +{ + return TRUE; +} + +#ifdef HAS_MMAP + +/* this flushes any changes to the screens out to the mmapped file */ +static void +vfbBlockHandler(pointer blockData, OSTimePtr pTimeout, pointer pReadmask) +{ + int i; + + for (i = 0; i < vfbNumScreens; i++) + { +#ifdef MS_ASYNC + if (-1 == msync((caddr_t)vfbScreens[i].pXWDHeader, + (size_t)vfbScreens[i].sizeInBytes, MS_ASYNC)) +#else + /* silly NetBSD and who else? */ + if (-1 == msync((caddr_t)vfbScreens[i].pXWDHeader, + (size_t)vfbScreens[i].sizeInBytes)) +#endif + { + perror("msync"); + ErrorF("msync failed, %s", strerror(errno)); + } + } +} + + +static void +vfbWakeupHandler(pointer blockData, int result, pointer pReadmask) +{ +} + + +static void +vfbAllocateMmappedFramebuffer(vfbScreenInfoPtr pvfb) +{ +#define DUMMY_BUFFER_SIZE 65536 + char dummyBuffer[DUMMY_BUFFER_SIZE]; + int currentFileSize, writeThisTime; + + sprintf(pvfb->mmap_file, "%s/Xvfb_screen%d", pfbdir, (int) (pvfb - vfbScreens)); + if (-1 == (pvfb->mmap_fd = open(pvfb->mmap_file, O_CREAT|O_RDWR, 0666))) + { + perror("open"); + ErrorF("open %s failed, %s", pvfb->mmap_file, strerror(errno)); + return; + } + + /* Extend the file to be the proper size */ + + memset(dummyBuffer, 0, DUMMY_BUFFER_SIZE); + for (currentFileSize = 0; + currentFileSize < pvfb->sizeInBytes; + currentFileSize += writeThisTime) + { + writeThisTime = min(DUMMY_BUFFER_SIZE, + pvfb->sizeInBytes - currentFileSize); + if (-1 == write(pvfb->mmap_fd, dummyBuffer, writeThisTime)) + { + perror("write"); + ErrorF("write %s failed, %s", pvfb->mmap_file, strerror(errno)); + return; + } + } + + /* try to mmap the file */ + + pvfb->pXWDHeader = (XWDFileHeader *)mmap((caddr_t)NULL, pvfb->sizeInBytes, + PROT_READ|PROT_WRITE, + MAP_FILE|MAP_SHARED, + pvfb->mmap_fd, 0); + if (-1 == (long)pvfb->pXWDHeader) + { + perror("mmap"); + ErrorF("mmap %s failed, %s", pvfb->mmap_file, strerror(errno)); + pvfb->pXWDHeader = NULL; + return; + } + + if (!RegisterBlockAndWakeupHandlers(vfbBlockHandler, vfbWakeupHandler, + NULL)) + { + pvfb->pXWDHeader = NULL; + } +} +#endif /* HAS_MMAP */ + + +#ifdef HAS_SHM +static void +vfbAllocateSharedMemoryFramebuffer(vfbScreenInfoPtr pvfb) +{ + /* create the shared memory segment */ + + pvfb->shmid = shmget(IPC_PRIVATE, pvfb->sizeInBytes, IPC_CREAT|0777); + if (pvfb->shmid < 0) + { + perror("shmget"); + ErrorF("shmget %d bytes failed, %s", pvfb->sizeInBytes, strerror(errno)); + return; + } + + /* try to attach it */ + + pvfb->pXWDHeader = (XWDFileHeader *)shmat(pvfb->shmid, 0, 0); + if (-1 == (long)pvfb->pXWDHeader) + { + perror("shmat"); + ErrorF("shmat failed, %s", strerror(errno)); + pvfb->pXWDHeader = NULL; + return; + } + + ErrorF("screen %d shmid %d\n", (int) (pvfb - vfbScreens), pvfb->shmid); +} +#endif /* HAS_SHM */ + +static char * +vfbAllocateFramebufferMemory(vfbScreenInfoPtr pvfb) +{ + if (pvfb->pfbMemory) return pvfb->pfbMemory; /* already done */ + + pvfb->sizeInBytes = pvfb->paddedBytesWidth * pvfb->height; + + /* Calculate how many entries in colormap. This is rather bogus, because + * the visuals haven't even been set up yet, but we need to know because we + * have to allocate space in the file for the colormap. The number 10 + * below comes from the MAX_PSEUDO_DEPTH define in cfbcmap.c. + */ + + if (pvfb->depth <= 10) + { /* single index colormaps */ + pvfb->ncolors = 1 << pvfb->depth; + } + else + { /* decomposed colormaps */ + int nplanes_per_color_component = pvfb->depth / 3; + if (pvfb->depth % 3) nplanes_per_color_component++; + pvfb->ncolors = 1 << nplanes_per_color_component; + } + + /* add extra bytes for XWDFileHeader, window name, and colormap */ + + pvfb->sizeInBytes += SIZEOF(XWDheader) + XWD_WINDOW_NAME_LEN + + pvfb->ncolors * SIZEOF(XWDColor); + + pvfb->pXWDHeader = NULL; + switch (fbmemtype) + { +#ifdef HAS_MMAP + case MMAPPED_FILE_FB: vfbAllocateMmappedFramebuffer(pvfb); break; +#else + case MMAPPED_FILE_FB: break; +#endif + +#ifdef HAS_SHM + case SHARED_MEMORY_FB: vfbAllocateSharedMemoryFramebuffer(pvfb); break; +#else + case SHARED_MEMORY_FB: break; +#endif + + case NORMAL_MEMORY_FB: + pvfb->pXWDHeader = (XWDFileHeader *)malloc(pvfb->sizeInBytes); + break; + } + + if (pvfb->pXWDHeader) + { + pvfb->pXWDCmap = (XWDColor *)((char *)pvfb->pXWDHeader + + SIZEOF(XWDheader) + XWD_WINDOW_NAME_LEN); + pvfb->pfbMemory = (char *)(pvfb->pXWDCmap + pvfb->ncolors); + + return pvfb->pfbMemory; + } + else + return NULL; +} + + +static void +vfbWriteXWDFileHeader(ScreenPtr pScreen) +{ + vfbScreenInfoPtr pvfb = &vfbScreens[pScreen->myNum]; + XWDFileHeader *pXWDHeader = pvfb->pXWDHeader; + char hostname[XWD_WINDOW_NAME_LEN]; + unsigned long swaptest = 1; + int i; + + needswap = *(char *) &swaptest; + + pXWDHeader->header_size = (char *)pvfb->pXWDCmap - (char *)pvfb->pXWDHeader; + pXWDHeader->file_version = XWD_FILE_VERSION; + + pXWDHeader->pixmap_format = ZPixmap; + pXWDHeader->pixmap_depth = pvfb->depth; + pXWDHeader->pixmap_height = pXWDHeader->window_height = pvfb->height; + pXWDHeader->xoffset = 0; + pXWDHeader->byte_order = IMAGE_BYTE_ORDER; + pXWDHeader->bitmap_bit_order = BITMAP_BIT_ORDER; +#ifndef INTERNAL_VS_EXTERNAL_PADDING + pXWDHeader->pixmap_width = pXWDHeader->window_width = pvfb->width; + pXWDHeader->bitmap_unit = BITMAP_SCANLINE_UNIT; + pXWDHeader->bitmap_pad = BITMAP_SCANLINE_PAD; +#else + pXWDHeader->pixmap_width = pXWDHeader->window_width = pvfb->paddedWidth; + pXWDHeader->bitmap_unit = BITMAP_SCANLINE_UNIT_PROTO; + pXWDHeader->bitmap_pad = BITMAP_SCANLINE_PAD_PROTO; +#endif + pXWDHeader->bits_per_pixel = pvfb->bitsPerPixel; + pXWDHeader->bytes_per_line = pvfb->paddedBytesWidth; + pXWDHeader->ncolors = pvfb->ncolors; + + /* visual related fields are written when colormap is installed */ + + pXWDHeader->window_x = pXWDHeader->window_y = 0; + pXWDHeader->window_bdrwidth = 0; + + /* write xwd "window" name: Xvfb hostname:server.screen */ + + if (-1 == gethostname(hostname, sizeof(hostname))) + hostname[0] = 0; + else + hostname[XWD_WINDOW_NAME_LEN-1] = 0; + sprintf((char *)(pXWDHeader+1), "Xvfb %s:%s.%d", hostname, display, + pScreen->myNum); + + /* write colormap pixel slot values */ + + for (i = 0; i < pvfb->ncolors; i++) + { + pvfb->pXWDCmap[i].pixel = i; + } + + /* byte swap to most significant byte first */ + + if (needswap) + { + SwapLongs((CARD32 *)pXWDHeader, SIZEOF(XWDheader)/4); + for (i = 0; i < pvfb->ncolors; i++) + { + register char n; + swapl(&pvfb->pXWDCmap[i].pixel, n); + } + } +} + + +static Bool +vfbCursorOffScreen (ScreenPtr *ppScreen, int *x, int *y) +{ + return FALSE; +} + +static void +vfbCrossScreen (ScreenPtr pScreen, Bool entering) +{ +} + +static miPointerScreenFuncRec vfbPointerCursorFuncs = +{ + vfbCursorOffScreen, + vfbCrossScreen, + miPointerWarpCursor +}; + +static Bool +vfbCloseScreen(int index, ScreenPtr pScreen) +{ + vfbScreenInfoPtr pvfb = &vfbScreens[index]; + int i; + + pScreen->CloseScreen = pvfb->closeScreen; + + /* + * XXX probably lots of stuff to clean. For now, + * clear installed colormaps so that server reset works correctly. + */ + for (i = 0; i < screenInfo.numScreens; i++) + SetInstalledColormap(screenInfo.screens[i], NULL); + + return pScreen->CloseScreen(index, pScreen); +} + +static Bool +vfbScreenInit(int index, ScreenPtr pScreen, int argc, char **argv) +{ + vfbScreenInfoPtr pvfb = &vfbScreens[index]; + int dpix = monitorResolution, dpiy = monitorResolution; + int ret; + char *pbits; + + if (!dixRegisterPrivateKey(&cmapScrPrivateKeyRec, PRIVATE_SCREEN, 0)) + return FALSE; + + if (dpix == 0) + dpix = 100; + + if (dpiy == 0) + dpiy = 100; + + pvfb->paddedBytesWidth = PixmapBytePad(pvfb->width, pvfb->depth); + pvfb->bitsPerPixel = vfbBitsPerPixel(pvfb->depth); + if (pvfb->bitsPerPixel >= 8 ) + pvfb->paddedWidth = pvfb->paddedBytesWidth / (pvfb->bitsPerPixel / 8); + else + pvfb->paddedWidth = pvfb->paddedBytesWidth * 8; + pbits = vfbAllocateFramebufferMemory(pvfb); + if (!pbits) return FALSE; + + switch (pvfb->depth) { + case 8: + miSetVisualTypesAndMasks (8, + ((1 << StaticGray) | + (1 << GrayScale) | + (1 << StaticColor) | + (1 << PseudoColor) | + (1 << TrueColor) | + (1 << DirectColor)), + 8, PseudoColor, 0, 0, 0); + break; + case 15: + miSetVisualTypesAndMasks (15, + ((1 << TrueColor) | + (1 << DirectColor)), + 8, TrueColor, 0x7c00, 0x03e0, 0x001f); + break; + case 16: + miSetVisualTypesAndMasks (16, + ((1 << TrueColor) | + (1 << DirectColor)), + 8, TrueColor, 0xf800, 0x07e0, 0x001f); + break; + case 24: + miSetVisualTypesAndMasks (24, + ((1 << TrueColor) | + (1 << DirectColor)), + 8, TrueColor, 0xff0000, 0x00ff00, 0x0000ff); + break; + case 30: + miSetVisualTypesAndMasks (30, + ((1 << TrueColor) | + (1 << DirectColor)), + 10, TrueColor, 0x3ff00000, 0x000ffc00, 0x000003ff); + break; + } + + miSetPixmapDepths (); + + ret = fbScreenInit(pScreen, pbits, pvfb->width, pvfb->height, + dpix, dpiy, pvfb->paddedWidth,pvfb->bitsPerPixel); + if (ret && Render) + fbPictureInit (pScreen, 0, 0); + + if (!ret) return FALSE; + + pScreen->InstallColormap = vfbInstallColormap; + pScreen->UninstallColormap = vfbUninstallColormap; + pScreen->ListInstalledColormaps = vfbListInstalledColormaps; + + pScreen->SaveScreen = vfbSaveScreen; + pScreen->StoreColors = vfbStoreColors; + + miDCInitialize(pScreen, &vfbPointerCursorFuncs); + + vfbWriteXWDFileHeader(pScreen); + + pScreen->blackPixel = pvfb->blackPixel; + pScreen->whitePixel = pvfb->whitePixel; + + ret = fbCreateDefColormap(pScreen); + + miSetZeroLineBias(pScreen, pvfb->lineBias); + + pvfb->closeScreen = pScreen->CloseScreen; + pScreen->CloseScreen = vfbCloseScreen; + + return ret; + +} /* end vfbScreenInit */ + + +void +InitOutput(ScreenInfo *screenInfo, int argc, char **argv) +{ + int i; + int NumFormats = 0; + + /* initialize pixmap formats */ + + /* must have a pixmap depth to match every screen depth */ + for (i = 0; i < vfbNumScreens; i++) + { + vfbPixmapDepths[vfbScreens[i].depth] = TRUE; + } + + /* RENDER needs a good set of pixmaps. */ + if (Render) { + vfbPixmapDepths[1] = TRUE; + vfbPixmapDepths[4] = TRUE; + vfbPixmapDepths[8] = TRUE; +#if 0 + vfbPixmapDepths[12] = TRUE; +#endif +/* vfbPixmapDepths[15] = TRUE; */ + vfbPixmapDepths[16] = TRUE; + vfbPixmapDepths[24] = TRUE; +#if 0 + vfbPixmapDepths[30] = TRUE; +#endif + vfbPixmapDepths[32] = TRUE; + } + + for (i = 1; i <= 32; i++) + { + if (vfbPixmapDepths[i]) + { + if (NumFormats >= MAXFORMATS) + FatalError ("MAXFORMATS is too small for this server\n"); + screenInfo->formats[NumFormats].depth = i; + screenInfo->formats[NumFormats].bitsPerPixel = vfbBitsPerPixel(i); + screenInfo->formats[NumFormats].scanlinePad = BITMAP_SCANLINE_PAD; + NumFormats++; + } + } + + screenInfo->imageByteOrder = IMAGE_BYTE_ORDER; + screenInfo->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT; + screenInfo->bitmapScanlinePad = BITMAP_SCANLINE_PAD; + screenInfo->bitmapBitOrder = BITMAP_BIT_ORDER; + screenInfo->numPixmapFormats = NumFormats; + + /* initialize screens */ + + if (vfbNumScreens < 1) + { + vfbScreens = &defaultScreenInfo; + vfbNumScreens = 1; + } + for (i = 0; i < vfbNumScreens; i++) + { + if (-1 == AddScreen(vfbScreenInit, argc, argv)) + { + FatalError("Couldn't add screen %d", i); + } + } + +} /* end InitOutput */ diff --git a/xorg-server/hw/xfree86/common/xf86Config.c b/xorg-server/hw/xfree86/common/xf86Config.c index 4047350c4..19af91509 100644 --- a/xorg-server/hw/xfree86/common/xf86Config.c +++ b/xorg-server/hw/xfree86/common/xf86Config.c @@ -1222,6 +1222,7 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout) devs = xnfrealloc(servlayoutp->inputs,
(count + 1) * sizeof(InputInfoPtr));
devs[count - 1] = xnfalloc(sizeof(InputInfoRec));
+ Pointer.fd = -1;
*devs[count - 1] = Pointer;
devs[count - 1]->options =
xf86addNewOption(devs[count -1]->options,
@@ -1267,6 +1268,7 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout) devs = xnfrealloc(servlayoutp->inputs,
(count + 1) * sizeof(InputInfoPtr));
devs[count - 1] = xnfalloc(sizeof(InputInfoRec));
+ Pointer.fd = -1;
*devs[count - 1] = Pointer;
devs[count - 1]->options =
xf86addNewOption(NULL, xnfstrdup("AlwaysCore"), NULL);
@@ -1363,6 +1365,7 @@ checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout) devs = xnfrealloc(servlayoutp->inputs,
(count + 1) * sizeof(InputInfoPtr));
devs[count - 1] = xnfalloc(sizeof(InputInfoRec));
+ Keyboard.fd = -1;
*devs[count - 1] = Keyboard;
devs[count - 1]->options =
xf86addNewOption(devs[count - 1]->options,
diff --git a/xorg-server/hw/xfree86/common/xf86Configure.c b/xorg-server/hw/xfree86/common/xf86Configure.c index ba0628ffd..aabb8e11b 100644 --- a/xorg-server/hw/xfree86/common/xf86Configure.c +++ b/xorg-server/hw/xfree86/common/xf86Configure.c @@ -749,7 +749,7 @@ DoConfigure(void) bail:
OsCleanup(TRUE);
- AbortDDX();
+ AbortDDX(EXIT_ERR_CONFIGURE);
fflush(stderr);
exit(0);
}
diff --git a/xorg-server/hw/xfree86/common/xf86Helper.c b/xorg-server/hw/xfree86/common/xf86Helper.c index da15b0503..a210df042 100644 --- a/xorg-server/hw/xfree86/common/xf86Helper.c +++ b/xorg-server/hw/xfree86/common/xf86Helper.c @@ -1198,9 +1198,9 @@ xf86LogInit(void) }
void
-xf86CloseLog(void)
+xf86CloseLog(enum ExitCode error)
{
- LogClose();
+ LogClose(error);
}
diff --git a/xorg-server/hw/xfree86/common/xf86Init.c b/xorg-server/hw/xfree86/common/xf86Init.c index 44071996c..94e1a5dbd 100644 --- a/xorg-server/hw/xfree86/common/xf86Init.c +++ b/xorg-server/hw/xfree86/common/xf86Init.c @@ -791,6 +791,21 @@ InitOutput(ScreenInfo *pScreenInfo, int argc, char **argv) NULL);
}
+static InputInfoPtr
+duplicateDevice(InputInfoPtr pInfo)
+{
+ InputInfoPtr dup = calloc(1, sizeof(InputInfoRec));
+ if (dup) {
+ dup->name = strdup(pInfo->name);
+ dup->driver = strdup(pInfo->driver);
+ dup->options = xf86OptionListDuplicate(pInfo->options);
+ /* type_name is a const string */
+ dup->type_name = pInfo->type_name;
+ dup->fd = -1;
+ }
+ return dup;
+}
+
/*
* InitInput --
* Initialize all supported input devices.
@@ -799,7 +814,7 @@ InitOutput(ScreenInfo *pScreenInfo, int argc, char **argv) void
InitInput(int argc, char **argv)
{
- InputInfoPtr* pDev;
+ InputInfoPtr* pInfo;
DeviceIntPtr dev;
xf86Info.vtRequestsPending = FALSE;
@@ -807,14 +822,21 @@ InitInput(int argc, char **argv) mieqInit();
/* Initialize all configured input devices */
- for (pDev = xf86ConfigLayout.inputs; pDev && *pDev; pDev++) {
+ for (pInfo = xf86ConfigLayout.inputs; pInfo && *pInfo; pInfo++) {
+ InputInfoPtr dup;
/* Replace obsolete keyboard driver with kbd */
- if (!xf86NameCmp((*pDev)->driver, "keyboard")) {
- strcpy((*pDev)->driver, "kbd");
+ if (!xf86NameCmp((*pInfo)->driver, "keyboard")) {
+ strcpy((*pInfo)->driver, "kbd");
}
+ /* Data passed into xf86NewInputDevice will be freed on shutdown.
+ * Duplicate from xf86ConfigLayout.inputs, otherwise we don't have any
+ * xorg.conf input devices in the second generation
+ */
+ dup = duplicateDevice(*pInfo);
+
/* If one fails, the others will too */
- if (xf86NewInputDevice(*pDev, &dev, TRUE) == BadAlloc)
+ if (xf86NewInputDevice(dup, &dev, TRUE) == BadAlloc)
break;
}
@@ -880,7 +902,7 @@ OsVendorInit(void) */
void
-ddxGiveUp(void)
+ddxGiveUp(enum ExitCode error)
{
int i;
@@ -907,7 +929,7 @@ ddxGiveUp(void) if (xorgHWOpenConsole)
xf86CloseConsole();
- xf86CloseLog();
+ xf86CloseLog(error);
/* If an unexpected signal was caught, dump a core for debugging */
if (xf86Info.caughtSignal)
@@ -924,7 +946,7 @@ ddxGiveUp(void) */
void
-AbortDDX(void)
+AbortDDX(enum ExitCode error)
{
int i;
@@ -957,7 +979,7 @@ AbortDDX(void) * This is needed for an abnormal server exit, since the normal exit stuff
* MUST also be performed (i.e. the vt must be left in a defined state)
*/
- ddxGiveUp();
+ ddxGiveUp(error);
}
void
diff --git a/xorg-server/hw/xfree86/common/xf86Option.c b/xorg-server/hw/xfree86/common/xf86Option.c index 08f143347..576796d6c 100644 --- a/xorg-server/hw/xfree86/common/xf86Option.c +++ b/xorg-server/hw/xfree86/common/xf86Option.c @@ -340,7 +340,7 @@ pointer xf86AddNewOption(pointer head, const char *name, const char *val)
{
/* XXX These should actually be allocated in the parser library. */
- char *tmp = strdup(val);
+ char *tmp = val ? strdup(val) : NULL;
char *tmp_name = strdup(name);
return xf86addNewOption(head, tmp_name, tmp);
diff --git a/xorg-server/hw/xfree86/common/xf86Priv.h b/xorg-server/hw/xfree86/common/xf86Priv.h index a77d38fd3..436594ba6 100644 --- a/xorg-server/hw/xfree86/common/xf86Priv.h +++ b/xorg-server/hw/xfree86/common/xf86Priv.h @@ -140,7 +140,7 @@ extern _X_EXPORT pmWait (*xf86PMConfirmEventToOs)(int fd,pmEvent event); /* xf86Helper.c */
extern _X_EXPORT void xf86LogInit(void);
-extern _X_EXPORT void xf86CloseLog(void);
+extern _X_EXPORT void xf86CloseLog(enum ExitCode error);
/* xf86Init.c */
extern _X_EXPORT Bool xf86LoadModules(char **list, pointer *optlist);
diff --git a/xorg-server/hw/xfree86/common/xf86ShowOpts.c b/xorg-server/hw/xfree86/common/xf86ShowOpts.c index 7aa79eb6a..a8059168d 100644 --- a/xorg-server/hw/xfree86/common/xf86ShowOpts.c +++ b/xorg-server/hw/xfree86/common/xf86ShowOpts.c @@ -1,130 +1,130 @@ -/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86ShopwOpts.c,v 3.80 2003/10/08 14:58:27 dawes Exp $ */
-/*
- * Copyright 2000-2002 by Alan Hourihane, Flint Mountain, North Wales.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Alan Hourihane not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission. Alan Hourihane makes no representations
- * about the suitability of this software for any purpose. It is provided
- * "as is" without express or implied warranty.
- *
- * ALAN HOURIHANE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL ALAN HOURIHANE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- *
- * Author: Marcus Schaefer, ms@suse.de
- *
- */
-
-#include <ctype.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include "os.h"
-#ifdef XFree86LOADER
-#include "loaderProcs.h"
-#endif
-#include "xf86.h"
-#include "xf86Config.h"
-#include "xf86_OSlib.h"
-#include "xf86Priv.h"
-/* #include "xf86PciData.h" */
-#define IN_XSERVER
-#include "xf86Parser.h"
-#include "xf86tokens.h"
-#include "Configint.h"
-#include "xf86DDC.h"
-#if defined(__sparc__) && !defined(__OpenBSD__)
-#include "xf86Bus.h"
-#include "xf86Sbus.h"
-#endif
-#include "globals.h"
-
-static const char*
-optionTypeToSting(OptionValueType type)
-{
- switch (type) {
- case OPTV_NONE:
- return "";
- case OPTV_INTEGER:
- return "<int>";
- case OPTV_STRING:
- return "<str>";
- case OPTV_ANYSTR:
- return "<str>";
- case OPTV_REAL:
- return "<real>";
- case OPTV_BOOLEAN:
- return "<bool>";
- case OPTV_FREQ:
- return "<freq>";
- case OPTV_PERCENT:
- return "<percent>";
- default:
- return "<undef>";
- }
-}
-
-void DoShowOptions (void) {
- int i = 0;
- char **vlist = 0;
- char *pSymbol = 0;
- XF86ModuleData *initData = 0;
- if (! (vlist = xf86DriverlistFromCompile())) {
- ErrorF("Missing output drivers\n");
- goto bail;
- }
- xf86LoadModules (vlist,0);
- free(vlist);
- for (i = 0; i < xf86NumDrivers; i++) {
- if (xf86DriverList[i]->AvailableOptions) {
- OptionInfoPtr pOption = (OptionInfoPtr)(*xf86DriverList[i]->AvailableOptions)(0,0);
- if (! pOption) {
- ErrorF ("(EE) Couldn't read option table for %s driver\n",
- xf86DriverList[i]->driverName
- );
- continue;
- }
- XNFasprintf(&pSymbol, "%sModuleData",
- xf86DriverList[i]->driverName);
- initData = LoaderSymbol (pSymbol);
- if (initData) {
- XF86ModuleVersionInfo *vers = initData->vers;
- OptionInfoPtr p;
- ErrorF ("Driver[%d]:%s[%s] {\n",
- i,xf86DriverList[i]->driverName,vers->vendor
- );
- for (p = pOption; p->name != NULL; p++) {
- const char *opttype = optionTypeToSting(p->type);
- /* XXX: Why overallocate by 2 bytes?
- * Otherwise, this would be strdup()
- */
- char *optname = malloc(strlen(p->name) + 2 + 1);
- if (!optname) {
- continue;
- }
- sprintf(optname, "%s", p->name);
- ErrorF ("\t%s:%s\n", optname,opttype);
- }
- ErrorF ("}\n");
- }
- }
- }
- bail:
- OsCleanup (TRUE);
- AbortDDX ();
- fflush (stderr);
- exit (0);
-}
+/* $XFree86: xc/programs/Xserver/hw/xfree86/common/xf86ShopwOpts.c,v 3.80 2003/10/08 14:58:27 dawes Exp $ */ +/* + * Copyright 2000-2002 by Alan Hourihane, Flint Mountain, North Wales. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Alan Hourihane not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Alan Hourihane makes no representations + * about the suitability of this software for any purpose. It is provided + * "as is" without express or implied warranty. + * + * ALAN HOURIHANE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL ALAN HOURIHANE BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + * + * Author: Marcus Schaefer, ms@suse.de + * + */ + +#include <ctype.h> +#include <stdlib.h> +#include <unistd.h> +#include <sys/types.h> +#include <sys/stat.h> +#include <fcntl.h> +#include <X11/X.h> +#include <X11/Xmd.h> +#include "os.h" +#ifdef XFree86LOADER +#include "loaderProcs.h" +#endif +#include "xf86.h" +#include "xf86Config.h" +#include "xf86_OSlib.h" +#include "xf86Priv.h" +/* #include "xf86PciData.h" */ +#define IN_XSERVER +#include "xf86Parser.h" +#include "xf86tokens.h" +#include "Configint.h" +#include "xf86DDC.h" +#if defined(__sparc__) && !defined(__OpenBSD__) +#include "xf86Bus.h" +#include "xf86Sbus.h" +#endif +#include "globals.h" + +static const char* +optionTypeToSting(OptionValueType type) +{ + switch (type) { + case OPTV_NONE: + return ""; + case OPTV_INTEGER: + return "<int>"; + case OPTV_STRING: + return "<str>"; + case OPTV_ANYSTR: + return "<str>"; + case OPTV_REAL: + return "<real>"; + case OPTV_BOOLEAN: + return "<bool>"; + case OPTV_FREQ: + return "<freq>"; + case OPTV_PERCENT: + return "<percent>"; + default: + return "<undef>"; + } +} + +void DoShowOptions (void) { + int i = 0; + char **vlist = 0; + char *pSymbol = 0; + XF86ModuleData *initData = 0; + if (! (vlist = xf86DriverlistFromCompile())) { + ErrorF("Missing output drivers\n"); + goto bail; + } + xf86LoadModules (vlist,0); + free(vlist); + for (i = 0; i < xf86NumDrivers; i++) { + if (xf86DriverList[i]->AvailableOptions) { + OptionInfoPtr pOption = (OptionInfoPtr)(*xf86DriverList[i]->AvailableOptions)(0,0); + if (! pOption) { + ErrorF ("(EE) Couldn't read option table for %s driver\n", + xf86DriverList[i]->driverName + ); + continue; + } + XNFasprintf(&pSymbol, "%sModuleData", + xf86DriverList[i]->driverName); + initData = LoaderSymbol (pSymbol); + if (initData) { + XF86ModuleVersionInfo *vers = initData->vers; + OptionInfoPtr p; + ErrorF ("Driver[%d]:%s[%s] {\n", + i,xf86DriverList[i]->driverName,vers->vendor + ); + for (p = pOption; p->name != NULL; p++) { + const char *opttype = optionTypeToSting(p->type); + /* XXX: Why overallocate by 2 bytes? + * Otherwise, this would be strdup() + */ + char *optname = malloc(strlen(p->name) + 2 + 1); + if (!optname) { + continue; + } + sprintf(optname, "%s", p->name); + ErrorF ("\t%s:%s\n", optname,opttype); + } + ErrorF ("}\n"); + } + } + } + bail: + OsCleanup (TRUE); + AbortDDX (EXIT_ERR_DRIVERS); + fflush (stderr); + exit (0); +} diff --git a/xorg-server/hw/xfree86/common/xf86Xinput.c b/xorg-server/hw/xfree86/common/xf86Xinput.c index afef0994d..a53531cc1 100644 --- a/xorg-server/hw/xfree86/common/xf86Xinput.c +++ b/xorg-server/hw/xfree86/common/xf86Xinput.c @@ -844,6 +844,7 @@ xf86NewInputDevice(InputInfoPtr pInfo, DeviceIntPtr *pdev, BOOL enable) {
OsReleaseSignals();
xf86Msg(X_ERROR, "Couldn't init device \"%s\"\n", pInfo->name);
+ RemoveDevice(dev, TRUE);
rval = BadMatch;
goto unwind;
}
diff --git a/xorg-server/hw/xnest/Init.c b/xorg-server/hw/xnest/Init.c index 5f330c970..263565977 100644 --- a/xorg-server/hw/xnest/Init.c +++ b/xorg-server/hw/xnest/Init.c @@ -114,16 +114,16 @@ CloseInput(void) /*
* DDX - specific abort routine. Called by AbortServer().
*/
-void AbortDDX(void)
+void AbortDDX(enum ExitCode error)
{
xnestDoFullGeneration = True;
xnestCloseDisplay();
}
/* Called by GiveUp(). */
-void ddxGiveUp(void)
+void ddxGiveUp(enum ExitCode error)
{
- AbortDDX();
+ AbortDDX(error);
}
#ifdef __APPLE__
diff --git a/xorg-server/hw/xquartz/darwin.c b/xorg-server/hw/xquartz/darwin.c index 0b2f12fa7..8250f064a 100644 --- a/xorg-server/hw/xquartz/darwin.c +++ b/xorg-server/hw/xquartz/darwin.c @@ -766,9 +766,9 @@ void ddxUseMsg( void ) * ddxGiveUp --
* Device dependent cleanup. Called by dix before normal server death.
*/
-void ddxGiveUp( void )
+void ddxGiveUp( enum ExitCode error )
{
- ErrorF( "Quitting Xquartz\n" );
+ LogClose(error);
}
@@ -779,7 +779,7 @@ void ddxGiveUp( void ) * are closed.
*/
_X_NORETURN
-void AbortDDX( void ) {
+void AbortDDX( enum ExitCode error ) {
ErrorF( " AbortDDX\n" );
OsAbort();
}
diff --git a/xorg-server/hw/xwin/InitOutput.c b/xorg-server/hw/xwin/InitOutput.c index ae56c51fa..f79132c42 100644 --- a/xorg-server/hw/xwin/InitOutput.c +++ b/xorg-server/hw/xwin/InitOutput.c @@ -177,7 +177,7 @@ ddxBeforeReset (void) /* See Porting Layer Definition - p. 57 */
void
-ddxGiveUp (void)
+ddxGiveUp (enum ExitCode error)
{
int i;
@@ -212,7 +212,7 @@ ddxGiveUp (void) g_pszLogFile = LogInit (g_pszLogFile, NULL);
g_fLogInited = TRUE;
}
- LogClose ();
+ LogClose (error);
/*
* At this point we aren't creating any new screens, so
@@ -242,10 +242,10 @@ ddxGiveUp (void) /* See Porting Layer Definition - p. 57 */
void
-AbortDDX (void)
+AbortDDX (enum ExitCode error)
{
winDebug ("AbortDDX\n");
- ddxGiveUp ();
+ ddxGiveUp (error);
}
#ifdef __CYGWIN__
@@ -906,7 +906,7 @@ ddxUseMsg(void) g_pszLogFile = LogInit (g_pszLogFile, NULL);
g_fLogInited = TRUE;
}
- LogClose ();
+ LogClose (EXIT_NO_ERROR);
/* Notify user where UseMsg text can be found.*/
if (!g_fNoHelpMessageBox)
diff --git a/xorg-server/hw/xwin/Makefile.am b/xorg-server/hw/xwin/Makefile.am index 0afd81883..70f6cf7a6 100644 --- a/xorg-server/hw/xwin/Makefile.am +++ b/xorg-server/hw/xwin/Makefile.am @@ -176,27 +176,7 @@ install-exec-hook: EXTRA_DIST = \ $(xwinconfig_DATA) \ X.ico \ - XWin.rc \ - xlaunch/config.cc \ - xlaunch/COPYING \ - xlaunch/main.cc \ - xlaunch/resources/dialog.rc \ - xlaunch/resources/fullscreen.bmp \ - xlaunch/resources/images.rc \ - xlaunch/resources/multiwindow.bmp \ - xlaunch/resources/nodecoration.bmp \ - xlaunch/resources/resources.h \ - xlaunch/resources/resources.rc \ - xlaunch/resources/strings.rc \ - xlaunch/resources/windowed.bmp \ - xlaunch/window/dialog.cc \ - xlaunch/window/dialog.h \ - xlaunch/window/util.cc \ - xlaunch/window/util.h \ - xlaunch/window/window.cc \ - xlaunch/window/window.h \ - xlaunch/window/wizard.cc \ - xlaunch/window/wizard.h + XWin.rc relink: $(AM_V_at)rm -f XWin$(EXEEXT) && $(MAKE) XWin$(EXEEXT) diff --git a/xorg-server/hw/xwin/winerror.c b/xorg-server/hw/xwin/winerror.c index 47e1bd86f..e95be3f4c 100644 --- a/xorg-server/hw/xwin/winerror.c +++ b/xorg-server/hw/xwin/winerror.c @@ -1,167 +1,167 @@ -/*
- *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved.
- *
- *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:
- *
- *The above copyright notice and this permission notice shall be
- *included in all copies or substantial portions of the Software.
- *
- *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 HAROLD L HUNT II 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.
- *
- *Except as contained in this notice, the name of Harold L Hunt II
- *shall not be used in advertising or otherwise to promote the sale, use
- *or other dealings in this Software without prior written authorization
- *from Harold L Hunt II.
- *
- * Authors: Harold L Hunt II
- */
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-
-#include <../xfree86/common/xorgVersion.h>
-#include "win.h"
-
-extern Bool g_fSilentDupError;
-#ifdef DDXOSVERRORF
-/* Prototype */
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args);
-
-void
-OsVendorVErrorF (const char *pszFormat, va_list va_args)
-{
-#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
- /* make sure the clipboard and multiwindow threads do not interfere the
- * main thread */
- static pthread_mutex_t s_pmPrinting = PTHREAD_MUTEX_INITIALIZER;
-
- /* Lock the printing mutex */
- pthread_mutex_lock (&s_pmPrinting);
-#endif
-
- /*
- If we want to silence it,
- detect if we are going to abort due to duplication error
- */
- if (g_fSilentDupError)
- {
- if ((strcmp(pszFormat,
- "InitOutput - Duplicate invocation on display "
- "number: %s. Exiting.\n") == 0)
- || (strcmp(pszFormat,
- "Server is already active for display %s\n%s %s\n%s\n") == 0)
- || (strcmp(pszFormat,
- "MakeAllCOTSServerListeners: server already running\n") == 0))
- {
- g_fSilentFatalError = TRUE;
- }
- }
-
- /* Print the error message to a log file, could be stderr */
- LogVWrite (0, pszFormat, va_args);
-
-#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW)
- /* Unlock the printing mutex */
- pthread_mutex_unlock (&s_pmPrinting);
-#endif
-}
-#endif
-
-
-/*
- * os/util.c/FatalError () calls our vendor ErrorF, so the message
- * from a FatalError will be logged. Thus, the message for the
- * fatal error is not passed to this function.
- *
- * Attempt to do last-ditch, safe, important cleanup here.
- */
-char g_FatalErrorMessage[1024];
-void
-OsVendorFatalError (void)
-{
- /* Don't give duplicate warning if UseMsg was called */
- if (g_fSilentFatalError)
- return;
-
- if (!g_fLogInited) {
- g_fLogInited = TRUE;
- g_pszLogFile = LogInit (g_pszLogFile, NULL);
- }
- LogClose ();
-
- winMessageBoxF (
- "A fatal error has occurred and " PROJECT_NAME " will now exit.\n" \
- "%s\n"
- "Please open %s for more information.\n",
- MB_ICONERROR, g_FatalErrorMessage, (g_pszLogFile?g_pszLogFile:"the logfile"));
-}
-
-
-/*
- * winMessageBoxF - Print a formatted error message in a useful
- * message box.
- */
-
-void
-winMessageBoxF (const char *pszError, UINT uType, ...)
-{
- char * pszErrorF = NULL;
- char * pszMsgBox = NULL;
- va_list args;
- int size;
-
- va_start(args, uType);
- size = vasprintf (&pszErrorF, pszError, args);
- va_end(args);
- if (size == -1) {
- pszErrorF = NULL;
- goto winMessageBoxF_Cleanup;
- }
-
-#define MESSAGEBOXF \
- "%s\n" \
- "Vendor: %s\n" \
- "Release: %d.%d.%d.%d\n" \
- "Contact: %s\n" \
- "%s\n\n" \
- "XWin was started with the following command-line:\n\n" \
- "%s\n"
-
- size = asprintf (&pszMsgBox, MESSAGEBOXF,
- pszErrorF, XVENDORNAME,
- XORG_VERSION_MAJOR, XORG_VERSION_MINOR, XORG_VERSION_PATCH,
- XORG_VERSION_SNAP,
- BUILDERADDR,
- BUILDERSTRING,
- g_pszCommandLine);
-
- if (size == -1) {
- pszMsgBox = NULL;
- goto winMessageBoxF_Cleanup;
- }
-
- /* Display the message box string */
- MessageBox (NULL,
- pszMsgBox,
- PROJECT_NAME,
- MB_OK | uType);
-
- winMessageBoxF_Cleanup:
- free(pszErrorF);
- free(pszMsgBox);
-#undef MESSAGEBOXF
-}
+/* + *Copyright (C) 2001-2004 Harold L Hunt II All Rights Reserved. + * + *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: + * + *The above copyright notice and this permission notice shall be + *included in all copies or substantial portions of the Software. + * + *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 HAROLD L HUNT II 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. + * + *Except as contained in this notice, the name of Harold L Hunt II + *shall not be used in advertising or otherwise to promote the sale, use + *or other dealings in this Software without prior written authorization + *from Harold L Hunt II. + * + * Authors: Harold L Hunt II + */ + +#ifdef HAVE_XWIN_CONFIG_H +#include <xwin-config.h> +#endif + +#include <../xfree86/common/xorgVersion.h> +#include "win.h" + +extern Bool g_fSilentDupError; +#ifdef DDXOSVERRORF +/* Prototype */ +void +OsVendorVErrorF (const char *pszFormat, va_list va_args); + +void +OsVendorVErrorF (const char *pszFormat, va_list va_args) +{ +#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW) + /* make sure the clipboard and multiwindow threads do not interfere the + * main thread */ + static pthread_mutex_t s_pmPrinting = PTHREAD_MUTEX_INITIALIZER; + + /* Lock the printing mutex */ + pthread_mutex_lock (&s_pmPrinting); +#endif + + /* + If we want to silence it, + detect if we are going to abort due to duplication error + */ + if (g_fSilentDupError) + { + if ((strcmp(pszFormat, + "InitOutput - Duplicate invocation on display " + "number: %s. Exiting.\n") == 0) + || (strcmp(pszFormat, + "Server is already active for display %s\n%s %s\n%s\n") == 0) + || (strcmp(pszFormat, + "MakeAllCOTSServerListeners: server already running\n") == 0)) + { + g_fSilentFatalError = TRUE; + } + } + + /* Print the error message to a log file, could be stderr */ + LogVWrite (0, pszFormat, va_args); + +#if defined(XWIN_CLIPBOARD) || defined (XWIN_MULTIWINDOW) + /* Unlock the printing mutex */ + pthread_mutex_unlock (&s_pmPrinting); +#endif +} +#endif + + +/* + * os/util.c/FatalError () calls our vendor ErrorF, so the message + * from a FatalError will be logged. Thus, the message for the + * fatal error is not passed to this function. + * + * Attempt to do last-ditch, safe, important cleanup here. + */ +char g_FatalErrorMessage[1024]; +void +OsVendorFatalError (void) +{ + /* Don't give duplicate warning if UseMsg was called */ + if (g_fSilentFatalError) + return; + + if (!g_fLogInited) { + g_fLogInited = TRUE; + g_pszLogFile = LogInit (g_pszLogFile, NULL); + } + LogClose (EXIT_ERR_ABORT); + + winMessageBoxF ( + "A fatal error has occurred and " PROJECT_NAME " will now exit.\n" \ + "%s\n" + "Please open %s for more information.\n", + MB_ICONERROR, g_FatalErrorMessage, (g_pszLogFile?g_pszLogFile:"the logfile")); +} + + +/* + * winMessageBoxF - Print a formatted error message in a useful + * message box. + */ + +void +winMessageBoxF (const char *pszError, UINT uType, ...) +{ + char * pszErrorF = NULL; + char * pszMsgBox = NULL; + va_list args; + int size; + + va_start(args, uType); + size = vasprintf (&pszErrorF, pszError, args); + va_end(args); + if (size == -1) { + pszErrorF = NULL; + goto winMessageBoxF_Cleanup; + } + +#define MESSAGEBOXF \ + "%s\n" \ + "Vendor: %s\n" \ + "Release: %d.%d.%d.%d\n" \ + "Contact: %s\n" \ + "%s\n\n" \ + "XWin was started with the following command-line:\n\n" \ + "%s\n" + + size = asprintf (&pszMsgBox, MESSAGEBOXF, + pszErrorF, XVENDORNAME, + XORG_VERSION_MAJOR, XORG_VERSION_MINOR, XORG_VERSION_PATCH, + XORG_VERSION_SNAP, + BUILDERADDR, + BUILDERSTRING, + g_pszCommandLine); + + if (size == -1) { + pszMsgBox = NULL; + goto winMessageBoxF_Cleanup; + } + + /* Display the message box string */ + MessageBox (NULL, + pszMsgBox, + PROJECT_NAME, + MB_OK | uType); + + winMessageBoxF_Cleanup: + free(pszErrorF); + free(pszMsgBox); +#undef MESSAGEBOXF +} diff --git a/xorg-server/include/os.h b/xorg-server/include/os.h index b7cf76db5..6800d4369 100644 --- a/xorg-server/include/os.h +++ b/xorg-server/include/os.h @@ -461,8 +461,15 @@ typedef struct { /* stuff for FlushCallback */
extern _X_EXPORT CallbackListPtr FlushCallback;
-extern _X_EXPORT void AbortDDX(void);
-extern _X_EXPORT void ddxGiveUp(void);
+enum ExitCode {
+ EXIT_NO_ERROR = 0,
+ EXIT_ERR_ABORT = 1,
+ EXIT_ERR_CONFIGURE = 2,
+ EXIT_ERR_DRIVERS = 3,
+};
+
+extern _X_EXPORT void AbortDDX(enum ExitCode error);
+extern _X_EXPORT void ddxGiveUp(enum ExitCode error);
extern _X_EXPORT int TimeSinceLastInputEvent(void);
/* strcasecmp.c */
@@ -510,7 +517,7 @@ typedef enum { } MessageType;
extern _X_EXPORT const char *LogInit(const char *fname, const char *backup);
-extern _X_EXPORT void LogClose(void);
+extern _X_EXPORT void LogClose(enum ExitCode error);
extern _X_EXPORT Bool LogSetParameter(LogParameter param, int value);
extern _X_EXPORT void LogVWrite(int verb, const char *f, va_list args) _X_ATTRIBUTE_PRINTF(2,0);
extern _X_EXPORT void LogWrite(int verb, const char *f, ...) _X_ATTRIBUTE_PRINTF(2,3);
diff --git a/xorg-server/os/log.c b/xorg-server/os/log.c index 7640c9e07..abf0cb86f 100644 --- a/xorg-server/os/log.c +++ b/xorg-server/os/log.c @@ -237,9 +237,11 @@ LogInit(const char *fname, const char *backup) }
void
-LogClose(void)
+LogClose(enum ExitCode error)
{
if (logFile) {
+ ErrorF("Server terminated %s (%d). Closing log file.\n",
+ (error == EXIT_NO_ERROR) ? "successfully" : "with error", error);
fclose(logFile);
logFile = NULL;
}
@@ -418,7 +420,7 @@ AbortServer(void) CloseWellKnownConnections();
OsCleanup(TRUE);
CloseDownDevices();
- AbortDDX();
+ AbortDDX(EXIT_ERR_ABORT);
fflush(stderr);
if (CoreDump)
OsAbort();
diff --git a/xorg-server/randr/rrproperty.c b/xorg-server/randr/rrproperty.c index dd0caa0b3..61e7bb45a 100644 --- a/xorg-server/randr/rrproperty.c +++ b/xorg-server/randr/rrproperty.c @@ -1,736 +1,736 @@ -/*
- * Copyright © 2006 Keith Packard
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that copyright
- * notice and this permission notice appear in supporting documentation, and
- * that the name of the copyright holders not be used in advertising or
- * publicity pertaining to distribution of the software without specific,
- * written prior permission. The copyright holders make no representations
- * about the suitability of this software for any purpose. It is provided "as
- * is" without express or implied warranty.
- *
- * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
- * OF THIS SOFTWARE.
- */
-
-#include "randrstr.h"
-#include "propertyst.h"
-#include "swaprep.h"
-
-static int
-DeliverPropertyEvent(WindowPtr pWin, void *value)
-{
- xRROutputPropertyNotifyEvent *event = value;
- RREventPtr *pHead, pRREvent;
-
- dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id,
- RREventType, serverClient, DixReadAccess);
- if (!pHead)
- return WT_WALKCHILDREN;
-
- for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next)
- {
- if (!(pRREvent->mask & RROutputPropertyNotifyMask))
- continue;
-
- event->window = pRREvent->window->drawable.id;
- WriteEventsToClient(pRREvent->client, 1, (xEvent *)event);
- }
-
- return WT_WALKCHILDREN;
-}
-
-static void RRDeliverPropertyEvent(ScreenPtr pScreen, xEvent *event)
-{
- if (!(dispatchException & (DE_RESET | DE_TERMINATE)))
- WalkTree(pScreen, DeliverPropertyEvent, event);
-}
-
-static void
-RRDestroyOutputProperty (RRPropertyPtr prop)
-{
- free(prop->valid_values);
- free(prop->current.data);
- free(prop->pending.data);
- free(prop);
-}
-
-static void
-RRDeleteProperty(RROutputRec *output, RRPropertyRec *prop)
-{
- xRROutputPropertyNotifyEvent event;
- event.type = RREventBase + RRNotify;
- event.subCode = RRNotify_OutputProperty;
- event.output = output->id;
- event.state = PropertyDelete;
- event.atom = prop->propertyName;
- event.timestamp = currentTime.milliseconds;
-
- RRDeliverPropertyEvent(output->pScreen, (xEvent *)&event);
-
- RRDestroyOutputProperty(prop);
-}
-
-void
-RRDeleteAllOutputProperties(RROutputPtr output)
-{
- RRPropertyPtr prop, next;
-
- for (prop = output->properties; prop; prop = next) {
- next = prop->next;
- RRDeleteProperty(output, prop);
- }
-}
-
-static void
-RRInitOutputPropertyValue (RRPropertyValuePtr property_value)
-{
- property_value->type = None;
- property_value->format = 0;
- property_value->size = 0;
- property_value->data = NULL;
-}
-
-static RRPropertyPtr
-RRCreateOutputProperty (Atom property)
-{
- RRPropertyPtr prop;
-
- prop = (RRPropertyPtr)malloc(sizeof(RRPropertyRec));
- if (!prop)
- return NULL;
- prop->next = NULL;
- prop->propertyName = property;
- prop->is_pending = FALSE;
- prop->range = FALSE;
- prop->immutable = FALSE;
- prop->num_valid = 0;
- prop->valid_values = NULL;
- RRInitOutputPropertyValue (&prop->current);
- RRInitOutputPropertyValue (&prop->pending);
- return prop;
-}
-
-void
-RRDeleteOutputProperty(RROutputPtr output, Atom property)
-{
- RRPropertyRec *prop, **prev;
-
- for (prev = &output->properties; (prop = *prev); prev = &(prop->next))
- if (prop->propertyName == property) {
- *prev = prop->next;
- RRDeleteProperty(output, prop);
- return;
- }
-}
-
-int
-RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type,
- int format, int mode, unsigned long len,
- pointer value, Bool sendevent, Bool pending)
-{
- RRPropertyPtr prop;
- xRROutputPropertyNotifyEvent event;
- rrScrPrivPtr pScrPriv = rrGetScrPriv(output->pScreen);
- int size_in_bytes;
- int total_size;
- unsigned long total_len;
- RRPropertyValuePtr prop_value;
- RRPropertyValueRec new_value;
- Bool add = FALSE;
-
- size_in_bytes = format >> 3;
-
- /* first see if property already exists */
- prop = RRQueryOutputProperty (output, property);
- if (!prop) /* just add to list */
- {
- prop = RRCreateOutputProperty (property);
- if (!prop)
- return BadAlloc;
- add = TRUE;
- mode = PropModeReplace;
- }
- if (pending && prop->is_pending)
- prop_value = &prop->pending;
- else
- prop_value = &prop->current;
-
- /* To append or prepend to a property the request format and type
- must match those of the already defined property. The
- existing format and type are irrelevant when using the mode
- "PropModeReplace" since they will be written over. */
-
- if ((format != prop_value->format) && (mode != PropModeReplace))
- return BadMatch;
- if ((prop_value->type != type) && (mode != PropModeReplace))
- return BadMatch;
- new_value = *prop_value;
- if (mode == PropModeReplace)
- total_len = len;
- else
- total_len = prop_value->size + len;
-
- if (mode == PropModeReplace || len > 0)
- {
- pointer new_data = NULL, old_data = NULL;
-
- total_size = total_len * size_in_bytes;
- new_value.data = (pointer)malloc(total_size);
- if (!new_value.data && total_size)
- {
- if (add)
- RRDestroyOutputProperty (prop);
- return BadAlloc;
- }
- new_value.size = len;
- new_value.type = type;
- new_value.format = format;
-
- switch (mode) {
- case PropModeReplace:
- new_data = new_value.data;
- old_data = NULL;
- break;
- case PropModeAppend:
- new_data = (pointer) (((char *) new_value.data) +
- (prop_value->size * size_in_bytes));
- old_data = new_value.data;
- break;
- case PropModePrepend:
- new_data = new_value.data;
- old_data = (pointer) (((char *) new_value.data) +
- (prop_value->size * size_in_bytes));
- break;
- }
- if (new_data)
- memcpy ((char *) new_data, (char *) value, len * size_in_bytes);
- if (old_data)
- memcpy ((char *) old_data, (char *) prop_value->data,
- prop_value->size * size_in_bytes);
-
- if (pending && pScrPriv->rrOutputSetProperty &&
- !pScrPriv->rrOutputSetProperty(output->pScreen, output,
- prop->propertyName, &new_value))
- {
- free(new_value.data);
- return BadValue;
- }
- free(prop_value->data);
- *prop_value = new_value;
- }
-
- else if (len == 0)
- {
- /* do nothing */
- }
-
- if (add)
- {
- prop->next = output->properties;
- output->properties = prop;
- }
-
- if (pending && prop->is_pending)
- output->pendingProperties = TRUE;
-
- if (sendevent)
- {
- event.type = RREventBase + RRNotify;
- event.subCode = RRNotify_OutputProperty;
- event.output = output->id;
- event.state = PropertyNewValue;
- event.atom = prop->propertyName;
- event.timestamp = currentTime.milliseconds;
- RRDeliverPropertyEvent (output->pScreen, (xEvent *)&event);
- }
- return Success;
-}
-
-Bool
-RRPostPendingProperties (RROutputPtr output)
-{
- RRPropertyValuePtr pending_value;
- RRPropertyValuePtr current_value;
- RRPropertyPtr property;
- Bool ret = TRUE;
-
- if (!output->pendingProperties)
- return TRUE;
-
- output->pendingProperties = FALSE;
- for (property = output->properties; property; property = property->next)
- {
- /* Skip non-pending properties */
- if (!property->is_pending)
- continue;
-
- pending_value = &property->pending;
- current_value = &property->current;
-
- /*
- * If the pending and current values are equal, don't mark it
- * as changed (which would deliver an event)
- */
- if (pending_value->type == current_value->type &&
- pending_value->format == current_value->format &&
- pending_value->size == current_value->size &&
- !memcmp (pending_value->data, current_value->data,
- pending_value->size))
- continue;
-
- if (RRChangeOutputProperty (output, property->propertyName,
- pending_value->type, pending_value->format,
- PropModeReplace, pending_value->size,
- pending_value->data, TRUE,
- FALSE) != Success)
- ret = FALSE;
- }
- return ret;
-}
-
-RRPropertyPtr
-RRQueryOutputProperty (RROutputPtr output, Atom property)
-{
- RRPropertyPtr prop;
-
- for (prop = output->properties; prop; prop = prop->next)
- if (prop->propertyName == property)
- return prop;
- return NULL;
-}
-
-RRPropertyValuePtr
-RRGetOutputProperty (RROutputPtr output, Atom property, Bool pending)
-{
- RRPropertyPtr prop = RRQueryOutputProperty (output, property);
- rrScrPrivPtr pScrPriv = rrGetScrPriv(output->pScreen);
-
- if (!prop)
- return NULL;
- if (pending && prop->is_pending)
- return &prop->pending;
- else {
-#if RANDR_13_INTERFACE
- /* If we can, try to update the property value first */
- if (pScrPriv->rrOutputGetProperty)
- pScrPriv->rrOutputGetProperty(output->pScreen, output,
- prop->propertyName);
-#endif
- return &prop->current;
- }
-}
-
-int
-RRConfigureOutputProperty (RROutputPtr output, Atom property,
- Bool pending, Bool range, Bool immutable,
- int num_values, INT32 *values)
-{
- RRPropertyPtr prop = RRQueryOutputProperty (output, property);
- Bool add = FALSE;
- INT32 *new_values;
-
- if (!prop)
- {
- prop = RRCreateOutputProperty (property);
- if (!prop)
- return BadAlloc;
- add = TRUE;
- } else if (prop->immutable && !immutable)
- return BadAccess;
-
- /*
- * ranges must have even number of values
- */
- if (range && (num_values & 1))
- return BadMatch;
-
- new_values = malloc(num_values * sizeof (INT32));
- if (!new_values && num_values)
- return BadAlloc;
- if (num_values)
- memcpy (new_values, values, num_values * sizeof (INT32));
-
- /*
- * Property moving from pending to non-pending
- * loses any pending values
- */
- if (prop->is_pending && !pending)
- {
- free(prop->pending.data);
- RRInitOutputPropertyValue (&prop->pending);
- }
-
- prop->is_pending = pending;
- prop->range = range;
- prop->immutable = immutable;
- prop->num_valid = num_values;
- free(prop->valid_values);
- prop->valid_values = new_values;
-
- if (add) {
- prop->next = output->properties;
- output->properties = prop;
- }
-
- return Success;
-}
-
-int
-ProcRRListOutputProperties (ClientPtr client)
-{
- REQUEST(xRRListOutputPropertiesReq);
- Atom *pAtoms = NULL, *temppAtoms;
- xRRListOutputPropertiesReply rep;
- int numProps = 0;
- RROutputPtr output;
- RRPropertyPtr prop;
-
- REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq);
-
- VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess);
-
- for (prop = output->properties; prop; prop = prop->next)
- numProps++;
- if (numProps)
- if(!(pAtoms = (Atom *)malloc(numProps * sizeof(Atom))))
- return BadAlloc;
-
- rep.type = X_Reply;
- rep.length = bytes_to_int32(numProps * sizeof(Atom));
- rep.sequenceNumber = client->sequence;
- rep.nAtoms = numProps;
- if (client->swapped)
- {
- int n;
- swaps (&rep.sequenceNumber, n);
- swapl (&rep.length, n);
- swaps (&rep.nAtoms, n);
- }
- temppAtoms = pAtoms;
- for (prop = output->properties; prop; prop = prop->next)
- *temppAtoms++ = prop->propertyName;
-
- WriteToClient(client, sizeof(xRRListOutputPropertiesReply), (char*)&rep);
- if (numProps)
- {
- client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write;
- WriteSwappedDataToClient(client, numProps * sizeof(Atom), pAtoms);
- free(pAtoms);
- }
- return Success;
-}
-
-int
-ProcRRQueryOutputProperty (ClientPtr client)
-{
- REQUEST(xRRQueryOutputPropertyReq);
- xRRQueryOutputPropertyReply rep;
- RROutputPtr output;
- RRPropertyPtr prop;
- char *extra = NULL;
-
- REQUEST_SIZE_MATCH(xRRQueryOutputPropertyReq);
-
- VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess);
-
- prop = RRQueryOutputProperty (output, stuff->property);
- if (!prop)
- return BadName;
-
- if (prop->num_valid) {
- extra = malloc(prop->num_valid * sizeof(INT32));
- if (!extra)
- return BadAlloc;
- }
- rep.type = X_Reply;
- rep.length = prop->num_valid;
- rep.sequenceNumber = client->sequence;
- rep.pending = prop->is_pending;
- rep.range = prop->range;
- rep.immutable = prop->immutable;
- if (client->swapped)
- {
- int n;
- swaps (&rep.sequenceNumber, n);
- swapl (&rep.length, n);
- }
- WriteToClient (client, sizeof (xRRQueryOutputPropertyReply), (char*)&rep);
- if (prop->num_valid)
- {
- memcpy(extra, prop->valid_values, prop->num_valid * sizeof(INT32));
- client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write;
- WriteSwappedDataToClient(client, prop->num_valid * sizeof(INT32),
- extra);
- free(extra);
- }
- return Success;
-}
-
-int
-ProcRRConfigureOutputProperty (ClientPtr client)
-{
- REQUEST(xRRConfigureOutputPropertyReq);
- RROutputPtr output;
- int num_valid;
-
- REQUEST_AT_LEAST_SIZE(xRRConfigureOutputPropertyReq);
-
- VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess);
-
- num_valid = stuff->length - bytes_to_int32(sizeof (xRRConfigureOutputPropertyReq));
- return RRConfigureOutputProperty (output, stuff->property,
- stuff->pending, stuff->range,
- FALSE, num_valid,
- (INT32 *) (stuff + 1));
-}
-
-int
-ProcRRChangeOutputProperty (ClientPtr client)
-{
- REQUEST(xRRChangeOutputPropertyReq);
- RROutputPtr output;
- char format, mode;
- unsigned long len;
- int sizeInBytes;
- int totalSize;
- int err;
-
- REQUEST_AT_LEAST_SIZE(xRRChangeOutputPropertyReq);
- UpdateCurrentTime();
- format = stuff->format;
- mode = stuff->mode;
- if ((mode != PropModeReplace) && (mode != PropModeAppend) &&
- (mode != PropModePrepend))
- {
- client->errorValue = mode;
- return BadValue;
- }
- if ((format != 8) && (format != 16) && (format != 32))
- {
- client->errorValue = format;
- return BadValue;
- }
- len = stuff->nUnits;
- if (len > bytes_to_int32((0xffffffff - sizeof(xChangePropertyReq))))
- return BadLength;
- sizeInBytes = format>>3;
- totalSize = len * sizeInBytes;
- REQUEST_FIXED_SIZE(xRRChangeOutputPropertyReq, totalSize);
-
- VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess);
-
- if (!ValidAtom(stuff->property))
- {
- client->errorValue = stuff->property;
- return BadAtom;
- }
- if (!ValidAtom(stuff->type))
- {
- client->errorValue = stuff->type;
- return BadAtom;
- }
-
- err = RRChangeOutputProperty(output, stuff->property,
- stuff->type, (int)format,
- (int)mode, len, (pointer)&stuff[1], TRUE, TRUE);
- if (err != Success)
- return err;
- else
- return Success;
-}
-
-int
-ProcRRDeleteOutputProperty (ClientPtr client)
-{
- REQUEST(xRRDeleteOutputPropertyReq);
- RROutputPtr output;
-
- REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq);
- UpdateCurrentTime();
- VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess);
-
- if (!ValidAtom(stuff->property))
- {
- client->errorValue = stuff->property;
- return BadAtom;
- }
-
-
- RRDeleteOutputProperty(output, stuff->property);
- return Success;
-}
-
-int
-ProcRRGetOutputProperty (ClientPtr client)
-{
- REQUEST(xRRGetOutputPropertyReq);
- RRPropertyPtr prop, *prev;
- RRPropertyValuePtr prop_value;
- unsigned long n, len, ind;
- RROutputPtr output;
- xRRGetOutputPropertyReply reply;
- char *extra = NULL;
-
- REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq);
- if (stuff->delete)
- UpdateCurrentTime();
- VERIFY_RR_OUTPUT(stuff->output, output,
- stuff->delete ? DixWriteAccess : DixReadAccess);
-
- if (!ValidAtom(stuff->property))
- {
- client->errorValue = stuff->property;
- return BadAtom;
- }
- if ((stuff->delete != xTrue) && (stuff->delete != xFalse))
- {
- client->errorValue = stuff->delete;
- return BadValue;
- }
- if ((stuff->type != AnyPropertyType) && !ValidAtom(stuff->type))
- {
- client->errorValue = stuff->type;
- return BadAtom;
- }
-
- for (prev = &output->properties; (prop = *prev); prev = &prop->next)
- if (prop->propertyName == stuff->property)
- break;
-
- reply.type = X_Reply;
- reply.sequenceNumber = client->sequence;
- if (!prop)
- {
- reply.nItems = 0;
- reply.length = 0;
- reply.bytesAfter = 0;
- reply.propertyType = None;
- reply.format = 0;
- if (client->swapped) {
- int n;
-
- swaps(&reply.sequenceNumber, n);
- swapl(&reply.length, n);
- swapl(&reply.propertyType, n);
- swapl(&reply.bytesAfter, n);
- swapl(&reply.nItems, n);
- }
- WriteToClient(client, sizeof(xRRGetOutputPropertyReply), &reply);
- return Success;
- }
-
- if (prop->immutable && stuff->delete)
- return BadAccess;
-
- prop_value = RRGetOutputProperty(output, stuff->property, stuff->pending);
- if (!prop_value)
- return BadAtom;
-
- /* If the request type and actual type don't match. Return the
- property information, but not the data. */
-
- if (((stuff->type != prop_value->type) &&
- (stuff->type != AnyPropertyType))
- )
- {
- reply.bytesAfter = prop_value->size;
- reply.format = prop_value->format;
- reply.length = 0;
- reply.nItems = 0;
- reply.propertyType = prop_value->type;
- if (client->swapped) {
- int n;
-
- swaps(&reply.sequenceNumber, n);
- swapl(&reply.length, n);
- swapl(&reply.propertyType, n);
- swapl(&reply.bytesAfter, n);
- swapl(&reply.nItems, n);
- }
- WriteToClient(client, sizeof(xRRGetOutputPropertyReply), &reply);
- return Success;
- }
-
-/*
- * Return type, format, value to client
- */
- n = (prop_value->format/8) * prop_value->size; /* size (bytes) of prop */
- ind = stuff->longOffset << 2;
-
- /* If longOffset is invalid such that it causes "len" to
- be negative, it's a value error. */
-
- if (n < ind)
- {
- client->errorValue = stuff->longOffset;
- return BadValue;
- }
-
- len = min(n - ind, 4 * stuff->longLength);
-
- if (len) {
- extra = malloc(len);
- if (!extra)
- return BadAlloc;
- }
- reply.bytesAfter = n - (ind + len);
- reply.format = prop_value->format;
- reply.length = bytes_to_int32(len);
- if (prop_value->format)
- reply.nItems = len / (prop_value->format / 8);
- else
- reply.nItems = 0;
- reply.propertyType = prop_value->type;
-
- if (stuff->delete && (reply.bytesAfter == 0))
- {
- xRROutputPropertyNotifyEvent event;
-
- event.type = RREventBase + RRNotify;
- event.subCode = RRNotify_OutputProperty;
- event.output = output->id;
- event.state = PropertyDelete;
- event.atom = prop->propertyName;
- event.timestamp = currentTime.milliseconds;
- RRDeliverPropertyEvent (output->pScreen, (xEvent *)&event);
- }
-
- if (client->swapped) {
- int n;
-
- swaps(&reply.sequenceNumber, n);
- swapl(&reply.length, n);
- swapl(&reply.propertyType, n);
- swapl(&reply.bytesAfter, n);
- swapl(&reply.nItems, n);
- }
- WriteToClient(client, sizeof(xGenericReply), &reply);
- if (len)
- {
- memcpy(extra, (char *)prop_value->data + ind, len);
- switch (reply.format) {
- case 32: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap32Write; break;
- case 16: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap16Write; break;
- default: client->pSwapReplyFunc = (ReplySwapPtr)WriteToClient; break;
- }
- WriteSwappedDataToClient(client, len,
- extra);
- free(extra);
- }
-
- if (stuff->delete && (reply.bytesAfter == 0))
- { /* delete the Property */
- *prev = prop->next;
- RRDestroyOutputProperty (prop);
- }
- return Success;
-}
-
+/* + * Copyright © 2006 Keith Packard + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that copyright + * notice and this permission notice appear in supporting documentation, and + * that the name of the copyright holders not be used in advertising or + * publicity pertaining to distribution of the software without specific, + * written prior permission. The copyright holders make no representations + * about the suitability of this software for any purpose. It is provided "as + * is" without express or implied warranty. + * + * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "randrstr.h" +#include "propertyst.h" +#include "swaprep.h" + +static int +DeliverPropertyEvent(WindowPtr pWin, void *value) +{ + xRROutputPropertyNotifyEvent *event = value; + RREventPtr *pHead, pRREvent; + + dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, + RREventType, serverClient, DixReadAccess); + if (!pHead) + return WT_WALKCHILDREN; + + for (pRREvent = *pHead; pRREvent; pRREvent = pRREvent->next) + { + if (!(pRREvent->mask & RROutputPropertyNotifyMask)) + continue; + + event->window = pRREvent->window->drawable.id; + WriteEventsToClient(pRREvent->client, 1, (xEvent *)event); + } + + return WT_WALKCHILDREN; +} + +static void RRDeliverPropertyEvent(ScreenPtr pScreen, xEvent *event) +{ + if (!(dispatchException & (DE_RESET | DE_TERMINATE))) + WalkTree(pScreen, DeliverPropertyEvent, event); +} + +static void +RRDestroyOutputProperty (RRPropertyPtr prop) +{ + free(prop->valid_values); + free(prop->current.data); + free(prop->pending.data); + free(prop); +} + +static void +RRDeleteProperty(RROutputRec *output, RRPropertyRec *prop) +{ + xRROutputPropertyNotifyEvent event; + event.type = RREventBase + RRNotify; + event.subCode = RRNotify_OutputProperty; + event.output = output->id; + event.state = PropertyDelete; + event.atom = prop->propertyName; + event.timestamp = currentTime.milliseconds; + + RRDeliverPropertyEvent(output->pScreen, (xEvent *)&event); + + RRDestroyOutputProperty(prop); +} + +void +RRDeleteAllOutputProperties(RROutputPtr output) +{ + RRPropertyPtr prop, next; + + for (prop = output->properties; prop; prop = next) { + next = prop->next; + RRDeleteProperty(output, prop); + } +} + +static void +RRInitOutputPropertyValue (RRPropertyValuePtr property_value) +{ + property_value->type = None; + property_value->format = 0; + property_value->size = 0; + property_value->data = NULL; +} + +static RRPropertyPtr +RRCreateOutputProperty (Atom property) +{ + RRPropertyPtr prop; + + prop = (RRPropertyPtr)malloc(sizeof(RRPropertyRec)); + if (!prop) + return NULL; + prop->next = NULL; + prop->propertyName = property; + prop->is_pending = FALSE; + prop->range = FALSE; + prop->immutable = FALSE; + prop->num_valid = 0; + prop->valid_values = NULL; + RRInitOutputPropertyValue (&prop->current); + RRInitOutputPropertyValue (&prop->pending); + return prop; +} + +void +RRDeleteOutputProperty(RROutputPtr output, Atom property) +{ + RRPropertyRec *prop, **prev; + + for (prev = &output->properties; (prop = *prev); prev = &(prop->next)) + if (prop->propertyName == property) { + *prev = prop->next; + RRDeleteProperty(output, prop); + return; + } +} + +int +RRChangeOutputProperty (RROutputPtr output, Atom property, Atom type, + int format, int mode, unsigned long len, + pointer value, Bool sendevent, Bool pending) +{ + RRPropertyPtr prop; + xRROutputPropertyNotifyEvent event; + rrScrPrivPtr pScrPriv = rrGetScrPriv(output->pScreen); + int size_in_bytes; + int total_size; + unsigned long total_len; + RRPropertyValuePtr prop_value; + RRPropertyValueRec new_value; + Bool add = FALSE; + + size_in_bytes = format >> 3; + + /* first see if property already exists */ + prop = RRQueryOutputProperty (output, property); + if (!prop) /* just add to list */ + { + prop = RRCreateOutputProperty (property); + if (!prop) + return BadAlloc; + add = TRUE; + mode = PropModeReplace; + } + if (pending && prop->is_pending) + prop_value = &prop->pending; + else + prop_value = &prop->current; + + /* To append or prepend to a property the request format and type + must match those of the already defined property. The + existing format and type are irrelevant when using the mode + "PropModeReplace" since they will be written over. */ + + if ((format != prop_value->format) && (mode != PropModeReplace)) + return BadMatch; + if ((prop_value->type != type) && (mode != PropModeReplace)) + return BadMatch; + new_value = *prop_value; + if (mode == PropModeReplace) + total_len = len; + else + total_len = prop_value->size + len; + + if (mode == PropModeReplace || len > 0) + { + pointer new_data = NULL, old_data = NULL; + + total_size = total_len * size_in_bytes; + new_value.data = (pointer)malloc(total_size); + if (!new_value.data && total_size) + { + if (add) + RRDestroyOutputProperty (prop); + return BadAlloc; + } + new_value.size = len; + new_value.type = type; + new_value.format = format; + + switch (mode) { + case PropModeReplace: + new_data = new_value.data; + old_data = NULL; + break; + case PropModeAppend: + new_data = (pointer) (((char *) new_value.data) + + (prop_value->size * size_in_bytes)); + old_data = new_value.data; + break; + case PropModePrepend: + new_data = new_value.data; + old_data = (pointer) (((char *) new_value.data) + + (prop_value->size * size_in_bytes)); + break; + } + if (new_data) + memcpy ((char *) new_data, (char *) value, len * size_in_bytes); + if (old_data) + memcpy ((char *) old_data, (char *) prop_value->data, + prop_value->size * size_in_bytes); + + if (pending && pScrPriv->rrOutputSetProperty && + !pScrPriv->rrOutputSetProperty(output->pScreen, output, + prop->propertyName, &new_value)) + { + free(new_value.data); + return BadValue; + } + free(prop_value->data); + *prop_value = new_value; + } + + else if (len == 0) + { + /* do nothing */ + } + + if (add) + { + prop->next = output->properties; + output->properties = prop; + } + + if (pending && prop->is_pending) + output->pendingProperties = TRUE; + + if (sendevent) + { + event.type = RREventBase + RRNotify; + event.subCode = RRNotify_OutputProperty; + event.output = output->id; + event.state = PropertyNewValue; + event.atom = prop->propertyName; + event.timestamp = currentTime.milliseconds; + RRDeliverPropertyEvent (output->pScreen, (xEvent *)&event); + } + return Success; +} + +Bool +RRPostPendingProperties (RROutputPtr output) +{ + RRPropertyValuePtr pending_value; + RRPropertyValuePtr current_value; + RRPropertyPtr property; + Bool ret = TRUE; + + if (!output->pendingProperties) + return TRUE; + + output->pendingProperties = FALSE; + for (property = output->properties; property; property = property->next) + { + /* Skip non-pending properties */ + if (!property->is_pending) + continue; + + pending_value = &property->pending; + current_value = &property->current; + + /* + * If the pending and current values are equal, don't mark it + * as changed (which would deliver an event) + */ + if (pending_value->type == current_value->type && + pending_value->format == current_value->format && + pending_value->size == current_value->size && + !memcmp (pending_value->data, current_value->data, + pending_value->size * (pending_value->format / 8))) + continue; + + if (RRChangeOutputProperty (output, property->propertyName, + pending_value->type, pending_value->format, + PropModeReplace, pending_value->size, + pending_value->data, TRUE, + FALSE) != Success) + ret = FALSE; + } + return ret; +} + +RRPropertyPtr +RRQueryOutputProperty (RROutputPtr output, Atom property) +{ + RRPropertyPtr prop; + + for (prop = output->properties; prop; prop = prop->next) + if (prop->propertyName == property) + return prop; + return NULL; +} + +RRPropertyValuePtr +RRGetOutputProperty (RROutputPtr output, Atom property, Bool pending) +{ + RRPropertyPtr prop = RRQueryOutputProperty (output, property); + rrScrPrivPtr pScrPriv = rrGetScrPriv(output->pScreen); + + if (!prop) + return NULL; + if (pending && prop->is_pending) + return &prop->pending; + else { +#if RANDR_13_INTERFACE + /* If we can, try to update the property value first */ + if (pScrPriv->rrOutputGetProperty) + pScrPriv->rrOutputGetProperty(output->pScreen, output, + prop->propertyName); +#endif + return &prop->current; + } +} + +int +RRConfigureOutputProperty (RROutputPtr output, Atom property, + Bool pending, Bool range, Bool immutable, + int num_values, INT32 *values) +{ + RRPropertyPtr prop = RRQueryOutputProperty (output, property); + Bool add = FALSE; + INT32 *new_values; + + if (!prop) + { + prop = RRCreateOutputProperty (property); + if (!prop) + return BadAlloc; + add = TRUE; + } else if (prop->immutable && !immutable) + return BadAccess; + + /* + * ranges must have even number of values + */ + if (range && (num_values & 1)) + return BadMatch; + + new_values = malloc(num_values * sizeof (INT32)); + if (!new_values && num_values) + return BadAlloc; + if (num_values) + memcpy (new_values, values, num_values * sizeof (INT32)); + + /* + * Property moving from pending to non-pending + * loses any pending values + */ + if (prop->is_pending && !pending) + { + free(prop->pending.data); + RRInitOutputPropertyValue (&prop->pending); + } + + prop->is_pending = pending; + prop->range = range; + prop->immutable = immutable; + prop->num_valid = num_values; + free(prop->valid_values); + prop->valid_values = new_values; + + if (add) { + prop->next = output->properties; + output->properties = prop; + } + + return Success; +} + +int +ProcRRListOutputProperties (ClientPtr client) +{ + REQUEST(xRRListOutputPropertiesReq); + Atom *pAtoms = NULL, *temppAtoms; + xRRListOutputPropertiesReply rep; + int numProps = 0; + RROutputPtr output; + RRPropertyPtr prop; + + REQUEST_SIZE_MATCH(xRRListOutputPropertiesReq); + + VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess); + + for (prop = output->properties; prop; prop = prop->next) + numProps++; + if (numProps) + if(!(pAtoms = (Atom *)malloc(numProps * sizeof(Atom)))) + return BadAlloc; + + rep.type = X_Reply; + rep.length = bytes_to_int32(numProps * sizeof(Atom)); + rep.sequenceNumber = client->sequence; + rep.nAtoms = numProps; + if (client->swapped) + { + int n; + swaps (&rep.sequenceNumber, n); + swapl (&rep.length, n); + swaps (&rep.nAtoms, n); + } + temppAtoms = pAtoms; + for (prop = output->properties; prop; prop = prop->next) + *temppAtoms++ = prop->propertyName; + + WriteToClient(client, sizeof(xRRListOutputPropertiesReply), (char*)&rep); + if (numProps) + { + client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write; + WriteSwappedDataToClient(client, numProps * sizeof(Atom), pAtoms); + free(pAtoms); + } + return Success; +} + +int +ProcRRQueryOutputProperty (ClientPtr client) +{ + REQUEST(xRRQueryOutputPropertyReq); + xRRQueryOutputPropertyReply rep; + RROutputPtr output; + RRPropertyPtr prop; + char *extra = NULL; + + REQUEST_SIZE_MATCH(xRRQueryOutputPropertyReq); + + VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess); + + prop = RRQueryOutputProperty (output, stuff->property); + if (!prop) + return BadName; + + if (prop->num_valid) { + extra = malloc(prop->num_valid * sizeof(INT32)); + if (!extra) + return BadAlloc; + } + rep.type = X_Reply; + rep.length = prop->num_valid; + rep.sequenceNumber = client->sequence; + rep.pending = prop->is_pending; + rep.range = prop->range; + rep.immutable = prop->immutable; + if (client->swapped) + { + int n; + swaps (&rep.sequenceNumber, n); + swapl (&rep.length, n); + } + WriteToClient (client, sizeof (xRRQueryOutputPropertyReply), (char*)&rep); + if (prop->num_valid) + { + memcpy(extra, prop->valid_values, prop->num_valid * sizeof(INT32)); + client->pSwapReplyFunc = (ReplySwapPtr)Swap32Write; + WriteSwappedDataToClient(client, prop->num_valid * sizeof(INT32), + extra); + free(extra); + } + return Success; +} + +int +ProcRRConfigureOutputProperty (ClientPtr client) +{ + REQUEST(xRRConfigureOutputPropertyReq); + RROutputPtr output; + int num_valid; + + REQUEST_AT_LEAST_SIZE(xRRConfigureOutputPropertyReq); + + VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess); + + num_valid = stuff->length - bytes_to_int32(sizeof (xRRConfigureOutputPropertyReq)); + return RRConfigureOutputProperty (output, stuff->property, + stuff->pending, stuff->range, + FALSE, num_valid, + (INT32 *) (stuff + 1)); +} + +int +ProcRRChangeOutputProperty (ClientPtr client) +{ + REQUEST(xRRChangeOutputPropertyReq); + RROutputPtr output; + char format, mode; + unsigned long len; + int sizeInBytes; + int totalSize; + int err; + + REQUEST_AT_LEAST_SIZE(xRRChangeOutputPropertyReq); + UpdateCurrentTime(); + format = stuff->format; + mode = stuff->mode; + if ((mode != PropModeReplace) && (mode != PropModeAppend) && + (mode != PropModePrepend)) + { + client->errorValue = mode; + return BadValue; + } + if ((format != 8) && (format != 16) && (format != 32)) + { + client->errorValue = format; + return BadValue; + } + len = stuff->nUnits; + if (len > bytes_to_int32((0xffffffff - sizeof(xChangePropertyReq)))) + return BadLength; + sizeInBytes = format>>3; + totalSize = len * sizeInBytes; + REQUEST_FIXED_SIZE(xRRChangeOutputPropertyReq, totalSize); + + VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess); + + if (!ValidAtom(stuff->property)) + { + client->errorValue = stuff->property; + return BadAtom; + } + if (!ValidAtom(stuff->type)) + { + client->errorValue = stuff->type; + return BadAtom; + } + + err = RRChangeOutputProperty(output, stuff->property, + stuff->type, (int)format, + (int)mode, len, (pointer)&stuff[1], TRUE, TRUE); + if (err != Success) + return err; + else + return Success; +} + +int +ProcRRDeleteOutputProperty (ClientPtr client) +{ + REQUEST(xRRDeleteOutputPropertyReq); + RROutputPtr output; + + REQUEST_SIZE_MATCH(xRRDeleteOutputPropertyReq); + UpdateCurrentTime(); + VERIFY_RR_OUTPUT(stuff->output, output, DixReadAccess); + + if (!ValidAtom(stuff->property)) + { + client->errorValue = stuff->property; + return BadAtom; + } + + + RRDeleteOutputProperty(output, stuff->property); + return Success; +} + +int +ProcRRGetOutputProperty (ClientPtr client) +{ + REQUEST(xRRGetOutputPropertyReq); + RRPropertyPtr prop, *prev; + RRPropertyValuePtr prop_value; + unsigned long n, len, ind; + RROutputPtr output; + xRRGetOutputPropertyReply reply; + char *extra = NULL; + + REQUEST_SIZE_MATCH(xRRGetOutputPropertyReq); + if (stuff->delete) + UpdateCurrentTime(); + VERIFY_RR_OUTPUT(stuff->output, output, + stuff->delete ? DixWriteAccess : DixReadAccess); + + if (!ValidAtom(stuff->property)) + { + client->errorValue = stuff->property; + return BadAtom; + } + if ((stuff->delete != xTrue) && (stuff->delete != xFalse)) + { + client->errorValue = stuff->delete; + return BadValue; + } + if ((stuff->type != AnyPropertyType) && !ValidAtom(stuff->type)) + { + client->errorValue = stuff->type; + return BadAtom; + } + + for (prev = &output->properties; (prop = *prev); prev = &prop->next) + if (prop->propertyName == stuff->property) + break; + + reply.type = X_Reply; + reply.sequenceNumber = client->sequence; + if (!prop) + { + reply.nItems = 0; + reply.length = 0; + reply.bytesAfter = 0; + reply.propertyType = None; + reply.format = 0; + if (client->swapped) { + int n; + + swaps(&reply.sequenceNumber, n); + swapl(&reply.length, n); + swapl(&reply.propertyType, n); + swapl(&reply.bytesAfter, n); + swapl(&reply.nItems, n); + } + WriteToClient(client, sizeof(xRRGetOutputPropertyReply), &reply); + return Success; + } + + if (prop->immutable && stuff->delete) + return BadAccess; + + prop_value = RRGetOutputProperty(output, stuff->property, stuff->pending); + if (!prop_value) + return BadAtom; + + /* If the request type and actual type don't match. Return the + property information, but not the data. */ + + if (((stuff->type != prop_value->type) && + (stuff->type != AnyPropertyType)) + ) + { + reply.bytesAfter = prop_value->size; + reply.format = prop_value->format; + reply.length = 0; + reply.nItems = 0; + reply.propertyType = prop_value->type; + if (client->swapped) { + int n; + + swaps(&reply.sequenceNumber, n); + swapl(&reply.length, n); + swapl(&reply.propertyType, n); + swapl(&reply.bytesAfter, n); + swapl(&reply.nItems, n); + } + WriteToClient(client, sizeof(xRRGetOutputPropertyReply), &reply); + return Success; + } + +/* + * Return type, format, value to client + */ + n = (prop_value->format/8) * prop_value->size; /* size (bytes) of prop */ + ind = stuff->longOffset << 2; + + /* If longOffset is invalid such that it causes "len" to + be negative, it's a value error. */ + + if (n < ind) + { + client->errorValue = stuff->longOffset; + return BadValue; + } + + len = min(n - ind, 4 * stuff->longLength); + + if (len) { + extra = malloc(len); + if (!extra) + return BadAlloc; + } + reply.bytesAfter = n - (ind + len); + reply.format = prop_value->format; + reply.length = bytes_to_int32(len); + if (prop_value->format) + reply.nItems = len / (prop_value->format / 8); + else + reply.nItems = 0; + reply.propertyType = prop_value->type; + + if (stuff->delete && (reply.bytesAfter == 0)) + { + xRROutputPropertyNotifyEvent event; + + event.type = RREventBase + RRNotify; + event.subCode = RRNotify_OutputProperty; + event.output = output->id; + event.state = PropertyDelete; + event.atom = prop->propertyName; + event.timestamp = currentTime.milliseconds; + RRDeliverPropertyEvent (output->pScreen, (xEvent *)&event); + } + + if (client->swapped) { + int n; + + swaps(&reply.sequenceNumber, n); + swapl(&reply.length, n); + swapl(&reply.propertyType, n); + swapl(&reply.bytesAfter, n); + swapl(&reply.nItems, n); + } + WriteToClient(client, sizeof(xGenericReply), &reply); + if (len) + { + memcpy(extra, (char *)prop_value->data + ind, len); + switch (reply.format) { + case 32: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap32Write; break; + case 16: client->pSwapReplyFunc = (ReplySwapPtr)CopySwap16Write; break; + default: client->pSwapReplyFunc = (ReplySwapPtr)WriteToClient; break; + } + WriteSwappedDataToClient(client, len, + extra); + free(extra); + } + + if (stuff->delete && (reply.bytesAfter == 0)) + { /* delete the Property */ + *prev = prop->next; + RRDestroyOutputProperty (prop); + } + return Success; +} + diff --git a/xorg-server/xkeyboard-config/symbols/lv b/xorg-server/xkeyboard-config/symbols/lv index 532c49749..34bb65aae 100644 --- a/xorg-server/xkeyboard-config/symbols/lv +++ b/xorg-server/xkeyboard-config/symbols/lv @@ -299,18 +299,18 @@ xkb_symbols "modern" { key <AC08> {[ i, I, i, I ]};
key <AC09> {[ t, T, t, T ]};
key <AC10> {[ r, R, rcedilla, Rcedilla ]};
- key <AC11> {[ m, M, bar, M ]};
- key <AC12> {[ slash, question, backslash, U263A ]};
+ key <AC11> {[ m, M, m, M ]};
+ key <BKSL> {[ slash, question, backslash, bar ]};
key <LSGT> {[ q, Q, q, Q ]};
key <AB01> {[ x, X, q, Q ]};
key <AB02> {[ z, Z, zcaron, Zcaron ]};
key <AB03> {[ c, C, ccaron, Ccaron ]};
- key <AB04> {[ v, V, v, V ]};
- key <AB05> {[ w, W, w, W ]};
- key <AB06> {[ f, F, f, F ]};
- key <AB07> {[ y, Y, y, Y ]};
- key <AB08> {[ h, H, h, H ]};
+ key <AB04> {[ v, V, period, V ]};
+ key <AB05> {[ w, W, slash, W ]};
+ key <AB06> {[ f, F, bar, F ]};
+ key <AB07> {[ y, Y, backslash, Y ]};
+ key <AB08> {[ h, H, U263A, U2639 ]};
key <AB09> {[ comma, semicolon, less, multiply ]};
key <AB10> {[ period, colon, greater, division ]};
key <SPCE> {[ space, space, apostrophe ]};
|