diff options
author | marha <marha@users.sourceforge.net> | 2011-09-12 11:27:51 +0200 |
---|---|---|
committer | marha <marha@users.sourceforge.net> | 2011-09-12 11:27:51 +0200 |
commit | dafebc5bb70303f0b5baf0b087cf4d9a64b5c7f0 (patch) | |
tree | bdf833cc6a4fc9035411779e10dd9e8478201885 /xorg-server/hw/xfree86/common | |
parent | 0b40f5f4b54453a77f4b09c431f8efc6875da61f (diff) | |
download | vcxsrv-dafebc5bb70303f0b5baf0b087cf4d9a64b5c7f0.tar.gz vcxsrv-dafebc5bb70303f0b5baf0b087cf4d9a64b5c7f0.tar.bz2 vcxsrv-dafebc5bb70303f0b5baf0b087cf4d9a64b5c7f0.zip |
Synchronised line endinge with release branch
Diffstat (limited to 'xorg-server/hw/xfree86/common')
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Config.c | 5068 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Configure.c | 1510 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Events.c | 1502 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Helper.c | 3898 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Init.c | 3040 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Module.h | 424 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Option.c | 1832 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Priv.h | 308 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86RandR.c | 970 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Xinput.c | 2802 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86sbusBus.c | 1428 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86xv.c | 4380 |
12 files changed, 13581 insertions, 13581 deletions
diff --git a/xorg-server/hw/xfree86/common/xf86Config.c b/xorg-server/hw/xfree86/common/xf86Config.c index 19af91509..58b30dd68 100644 --- a/xorg-server/hw/xfree86/common/xf86Config.c +++ b/xorg-server/hw/xfree86/common/xf86Config.c @@ -1,2534 +1,2534 @@ -/*
- * Loosely based on code bearing the following copyright:
- *
- * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
- */
-
-/*
- * Copyright 1992-2003 by The XFree86 Project, Inc.
- * Copyright 1997 by Metro Link, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/*
- *
- * Authors:
- * Dirk Hohndel <hohndel@XFree86.Org>
- * David Dawes <dawes@XFree86.Org>
- * Marc La France <tsi@XFree86.Org>
- * Egbert Eich <eich@XFree86.Org>
- * ... and others
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#ifdef XF86DRI
-#include <sys/types.h>
-#include <grp.h>
-#endif
-
-#include "xf86.h"
-#include "xf86Parser.h"
-#include "xf86tokens.h"
-#include "xf86Config.h"
-#include "xf86Priv.h"
-#include "xf86_OSlib.h"
-#include "configProcs.h"
-#include "globals.h"
-#include "extension.h"
-#include "xf86pciBus.h"
-
-#include "xf86Xinput.h"
-
-#include "xkbsrv.h"
-
-#include "picture.h"
-
-/*
- * These paths define the way the config file search is done. The escape
- * sequences are documented in parser/scan.c.
- */
-#ifndef ROOT_CONFIGPATH
-#define ROOT_CONFIGPATH "%A," "%R," \
- "/etc/X11/%R," "%P/etc/X11/%R," \
- "%E," "%F," \
- "/etc/X11/%F," "%P/etc/X11/%F," \
- "/etc/X11/%X," "/etc/%X," \
- "%P/etc/X11/%X.%H," \
- "%P/etc/X11/%X," \
- "%P/lib/X11/%X.%H," \
- "%P/lib/X11/%X"
-#endif
-#ifndef USER_CONFIGPATH
-#define USER_CONFIGPATH "/etc/X11/%S," "%P/etc/X11/%S," \
- "/etc/X11/%G," "%P/etc/X11/%G," \
- "/etc/X11/%X," "/etc/%X," \
- "%P/etc/X11/%X.%H," \
- "%P/etc/X11/%X," \
- "%P/lib/X11/%X.%H," \
- "%P/lib/X11/%X"
-#endif
-#ifndef ROOT_CONFIGDIRPATH
-#define ROOT_CONFIGDIRPATH "%A," "%R," \
- "/etc/X11/%R," "%C/X11/%R," \
- "/etc/X11/%X," "%C/X11/%X"
-#endif
-#ifndef USER_CONFIGDIRPATH
-#define USER_CONFIGDIRPATH "/etc/X11/%R," "%C/X11/%R," \
- "/etc/X11/%X," "%C/X11/%X"
-#endif
-#ifndef SYS_CONFIGDIRPATH
-#define SYS_CONFIGDIRPATH "/usr/share/X11/%X," "%D/X11/%X"
-#endif
-#ifndef PROJECTROOT
-#define PROJECTROOT "/usr/X11R6"
-#endif
-
-static ModuleDefault ModuleDefaults[] = {
- {.name = "extmod", .toLoad = TRUE, .load_opt=NULL},
-#ifdef DBE
- {.name = "dbe", .toLoad = TRUE, .load_opt=NULL},
-#endif
-#ifdef GLXEXT
- {.name = "glx", .toLoad = TRUE, .load_opt=NULL},
-#endif
-#ifdef XRECORD
- {.name = "record", .toLoad = TRUE, .load_opt=NULL},
-#endif
-#ifdef XF86DRI
- {.name = "dri", .toLoad = TRUE, .load_opt=NULL},
-#endif
-#ifdef DRI2
- {.name = "dri2", .toLoad = TRUE, .load_opt=NULL},
-#endif
- {.name = NULL, .toLoad = FALSE, .load_opt=NULL}
-};
-
-
-/* Forward declarations */
-static Bool configScreen(confScreenPtr screenp, XF86ConfScreenPtr conf_screen,
- int scrnum, MessageType from);
-static Bool configMonitor(MonPtr monitorp, XF86ConfMonitorPtr conf_monitor);
-static Bool configDevice(GDevPtr devicep, XF86ConfDevicePtr conf_device,
- Bool active);
-static Bool configInput(InputInfoPtr pInfo, XF86ConfInputPtr conf_input,
- MessageType from);
-static Bool configDisplay(DispPtr displayp, XF86ConfDisplayPtr conf_display);
-static Bool addDefaultModes(MonPtr monitorp);
-#ifdef XF86DRI
-static void configDRI(XF86ConfDRIPtr drip);
-#endif
-static void configExtensions(XF86ConfExtensionsPtr conf_ext);
-
-/*
- * xf86GetPathElem --
- * Extract a single element from the font path string starting at
- * pnt. The font path element will be returned, and pnt will be
- * updated to point to the start of the next element, or set to
- * NULL if there are no more.
- */
-static char *
-xf86GetPathElem(char **pnt)
-{
- char *p1;
-
- p1 = *pnt;
- *pnt = index(*pnt, ',');
- if (*pnt != NULL) {
- **pnt = '\0';
- *pnt += 1;
- }
- return p1;
-}
-
-/*
- * xf86ValidateFontPath --
- * Validates the user-specified font path. Each element that
- * begins with a '/' is checked to make sure the directory exists.
- * If the directory exists, the existence of a file named 'fonts.dir'
- * is checked. If either check fails, an error is printed and the
- * element is removed from the font path.
- */
-
-#define DIR_FILE "/fonts.dir"
-static char *
-xf86ValidateFontPath(char *path)
-{
- char *tmp_path, *out_pnt, *path_elem, *next, *p1, *dir_elem;
- struct stat stat_buf;
- int flag;
- int dirlen;
-
- tmp_path = calloc(1,strlen(path)+1);
- out_pnt = tmp_path;
- path_elem = NULL;
- next = path;
- while (next != NULL) {
- path_elem = xf86GetPathElem(&next);
- if (*path_elem == '/') {
- dir_elem = xnfcalloc(1, strlen(path_elem) + 1);
- if ((p1 = strchr(path_elem, ':')) != 0)
- dirlen = p1 - path_elem;
- else
- dirlen = strlen(path_elem);
- strncpy(dir_elem, path_elem, dirlen);
- dir_elem[dirlen] = '\0';
- flag = stat(dir_elem, &stat_buf);
- if (flag == 0)
- if (!S_ISDIR(stat_buf.st_mode))
- flag = -1;
- if (flag != 0) {
- xf86Msg(X_WARNING, "The directory \"%s\" does not exist.\n", dir_elem);
- xf86ErrorF("\tEntry deleted from font path.\n");
- free(dir_elem);
- continue;
- }
- else {
- XNFasprintf(&p1, "%s%s", dir_elem, DIR_FILE);
- flag = stat(p1, &stat_buf);
- if (flag == 0)
- if (!S_ISREG(stat_buf.st_mode))
- flag = -1;
- free(p1);
- if (flag != 0) {
- xf86Msg(X_WARNING,
- "`fonts.dir' not found (or not valid) in \"%s\".\n",
- dir_elem);
- xf86ErrorF("\tEntry deleted from font path.\n");
- xf86ErrorF("\t(Run 'mkfontdir' on \"%s\").\n", dir_elem);
- free(dir_elem);
- continue;
- }
- }
- free(dir_elem);
- }
-
- /*
- * Either an OK directory, or a font server name. So add it to
- * the path.
- */
- if (out_pnt != tmp_path)
- *out_pnt++ = ',';
- strcat(out_pnt, path_elem);
- out_pnt += strlen(path_elem);
- }
- return tmp_path;
-}
-
-
-/*
- * use the datastructure that the parser provides and pick out the parts
- * that we need at this point
- */
-char **
-xf86ModulelistFromConfig(pointer **optlist)
-{
- int count = 0, i = 0;
- char **modulearray;
- char *ignore[] = { "GLcore", "speedo", "bitmap", "drm",
- "freetype", "type1",
- NULL };
- pointer *optarray;
- XF86LoadPtr modp;
- Bool found;
-
- /*
- * make sure the config file has been parsed and that we have a
- * ModulePath set; if no ModulePath was given, use the default
- * ModulePath
- */
- if (xf86configptr == NULL) {
- xf86Msg(X_ERROR, "Cannot access global config data structure\n");
- return NULL;
- }
-
- if (xf86configptr->conf_modules) {
- /* Walk the disable list and let people know what we've parsed to
- * not be loaded
- */
- modp = xf86configptr->conf_modules->mod_disable_lst;
- while (modp) {
- xf86Msg(X_WARNING, "\"%s\" will not be loaded unless you've specified it to be loaded elsewhere.\n", modp->load_name);
- modp = (XF86LoadPtr) modp->list.next;
- }
- /*
- * Walk the default settings table. For each module listed to be
- * loaded, make sure it's in the mod_load_lst. If it's not, make
- * sure it's not in the mod_no_load_lst. If it's not disabled,
- * append it to mod_load_lst
- */
- for (i=0 ; ModuleDefaults[i].name != NULL ; i++) {
- if (ModuleDefaults[i].toLoad == FALSE) {
- xf86Msg(X_WARNING, "\"%s\" is not to be loaded by default. Skipping.\n", ModuleDefaults[i].name);
- continue;
- }
- found = FALSE;
- modp = xf86configptr->conf_modules->mod_load_lst;
- while (modp) {
- if (strcmp(modp->load_name, ModuleDefaults[i].name) == 0) {
- xf86Msg(X_INFO, "\"%s\" will be loaded. This was enabled by default and also specified in the config file.\n", ModuleDefaults[i].name);
- found = TRUE;
- break;
- }
- modp = (XF86LoadPtr) modp->list.next;
- }
- if (found == FALSE) {
- modp = xf86configptr->conf_modules->mod_disable_lst;
- while (modp) {
- if (strcmp(modp->load_name, ModuleDefaults[i].name) == 0) {
- xf86Msg(X_INFO, "\"%s\" will be loaded even though the default is to disable it.\n", ModuleDefaults[i].name);
- found = TRUE;
- break;
- }
- modp = (XF86LoadPtr) modp->list.next;
- }
- }
- if (found == FALSE) {
- XF86LoadPtr ptr = (XF86LoadPtr)xf86configptr->conf_modules;
- xf86addNewLoadDirective(ptr, ModuleDefaults[i].name, XF86_LOAD_MODULE, ModuleDefaults[i].load_opt);
- xf86Msg(X_INFO, "\"%s\" will be loaded by default.\n", ModuleDefaults[i].name);
- }
- }
- } else {
- xf86configptr->conf_modules = xnfcalloc(1, sizeof(XF86ConfModuleRec));
- for (i=0 ; ModuleDefaults[i].name != NULL ; i++) {
- if (ModuleDefaults[i].toLoad == TRUE) {
- XF86LoadPtr ptr = (XF86LoadPtr)xf86configptr->conf_modules;
- xf86addNewLoadDirective(ptr, ModuleDefaults[i].name, XF86_LOAD_MODULE, ModuleDefaults[i].load_opt);
- }
- }
- }
-
- /*
- * Walk the list of modules in the "Module" section to determine how
- * many we have.
- */
- modp = xf86configptr->conf_modules->mod_load_lst;
- while (modp) {
- for (i = 0; ignore[i]; i++) {
- if (strcmp(modp->load_name, ignore[i]) == 0)
- modp->ignore = 1;
- }
- if (!modp->ignore)
- count++;
- modp = (XF86LoadPtr) modp->list.next;
- }
-
- /*
- * allocate the memory and walk the list again to fill in the pointers
- */
- modulearray = xnfalloc((count + 1) * sizeof(char*));
- optarray = xnfalloc((count + 1) * sizeof(pointer));
- count = 0;
- if (xf86configptr->conf_modules) {
- modp = xf86configptr->conf_modules->mod_load_lst;
- while (modp) {
- if (!modp->ignore) {
- modulearray[count] = modp->load_name;
- optarray[count] = modp->load_opt;
- count++;
- }
- modp = (XF86LoadPtr) modp->list.next;
- }
- }
- modulearray[count] = NULL;
- optarray[count] = NULL;
- if (optlist)
- *optlist = optarray;
- else
- free(optarray);
- return modulearray;
-}
-
-
-char **
-xf86DriverlistFromConfig(void)
-{
- int count = 0;
- int j;
- char **modulearray;
- screenLayoutPtr slp;
-
- /*
- * make sure the config file has been parsed and that we have a
- * ModulePath set; if no ModulePath was given, use the default
- * ModulePath
- */
- if (xf86configptr == NULL) {
- xf86Msg(X_ERROR, "Cannot access global config data structure\n");
- return NULL;
- }
-
- /*
- * Walk the list of driver lines in active "Device" sections to
- * determine now many implicitly loaded modules there are.
- *
- */
- if (xf86ConfigLayout.screens) {
- slp = xf86ConfigLayout.screens;
- while ((slp++)->screen) {
- count++;
- }
- }
-
- /*
- * Handle the set of inactive "Device" sections.
- */
- j = 0;
- while (xf86ConfigLayout.inactives[j++].identifier)
- count++;
-
- if (count == 0)
- return NULL;
-
- /*
- * allocate the memory and walk the list again to fill in the pointers
- */
- modulearray = xnfalloc((count + 1) * sizeof(char*));
- count = 0;
- slp = xf86ConfigLayout.screens;
- while (slp->screen) {
- modulearray[count] = slp->screen->device->driver;
- count++;
- slp++;
- }
-
- j = 0;
-
- while (xf86ConfigLayout.inactives[j].identifier)
- modulearray[count++] = xf86ConfigLayout.inactives[j++].driver;
-
- modulearray[count] = NULL;
-
- /* Remove duplicates */
- for (count = 0; modulearray[count] != NULL; count++) {
- int i;
-
- for (i = 0; i < count; i++)
- if (xf86NameCmp(modulearray[i], modulearray[count]) == 0) {
- modulearray[count] = "";
- break;
- }
- }
- return modulearray;
-}
-
-char **
-xf86InputDriverlistFromConfig(void)
-{
- int count = 0;
- char **modulearray;
- InputInfoPtr *idp;
-
- /*
- * make sure the config file has been parsed and that we have a
- * ModulePath set; if no ModulePath was given, use the default
- * ModulePath
- */
- if (xf86configptr == NULL) {
- xf86Msg(X_ERROR, "Cannot access global config data structure\n");
- return NULL;
- }
-
- /*
- * Walk the list of driver lines in active "InputDevice" sections to
- * determine now many implicitly loaded modules there are.
- */
- if (xf86ConfigLayout.inputs) {
- idp = xf86ConfigLayout.inputs;
- while (*idp) {
- count++;
- idp++;
- }
- }
-
- if (count == 0)
- return NULL;
-
- /*
- * allocate the memory and walk the list again to fill in the pointers
- */
- modulearray = xnfalloc((count + 1) * sizeof(char*));
- count = 0;
- idp = xf86ConfigLayout.inputs;
- while (idp && *idp) {
- modulearray[count] = (*idp)->driver;
- count++;
- idp++;
- }
- modulearray[count] = NULL;
-
- /* Remove duplicates */
- for (count = 0; modulearray[count] != NULL; count++) {
- int i;
-
- for (i = 0; i < count; i++)
- if (xf86NameCmp(modulearray[i], modulearray[count]) == 0) {
- modulearray[count] = "";
- break;
- }
- }
- return modulearray;
-}
-
-static void
-fixup_video_driver_list(char **drivers)
-{
- static const char *fallback[4] = { "vesa", "fbdev", "wsfb", NULL };
- char **end, **drv;
- char *x;
- int i;
-
- /* walk to the end of the list */
- for (end = drivers; *end && **end; end++) ;
- end--;
-
- /*
- * for each of the fallback drivers, if we find it in the list,
- * swap it with the last available non-fallback driver.
- */
- for (i = 0; fallback[i]; i++) {
- for (drv = drivers; drv != end; drv++) {
- if (strstr(*drv, fallback[i])) {
- x = *drv; *drv = *end; *end = x;
- end--;
- break;
- }
- }
- }
-}
-
-static char **
-GenerateDriverlist(char * dirname)
-{
- char **ret;
- const char *subdirs[] = { dirname, NULL };
- static const char *patlist[] = {"(.*)_drv\\.so", NULL};
- ret = LoaderListDirs(subdirs, patlist);
-
- /* fix up the probe order for video drivers */
- if (strstr(dirname, "drivers") && ret != NULL)
- fixup_video_driver_list(ret);
-
- return ret;
-}
-
-char **
-xf86DriverlistFromCompile(void)
-{
- static char **driverlist = NULL;
-
- if (!driverlist)
- driverlist = GenerateDriverlist("drivers");
-
- return driverlist;
-}
-
-/*
- * xf86ConfigError --
- * Print a READABLE ErrorMessage!!! All information that is
- * available is printed.
- */
-static void
-xf86ConfigError(char *msg, ...)
-{
- va_list ap;
-
- ErrorF("\nConfig Error:\n");
- va_start(ap, msg);
- VErrorF(msg, ap);
- va_end(ap);
- ErrorF("\n");
- return;
-}
-
-static void
-configFiles(XF86ConfFilesPtr fileconf)
-{
- MessageType pathFrom;
- Bool must_copy;
- int size, countDirs;
- char *temp_path, *log_buf, *start, *end;
-
- /* FontPath */
- must_copy = TRUE;
-
- temp_path = defaultFontPath ? defaultFontPath : "";
- if (xf86fpFlag)
- pathFrom = X_CMDLINE;
- else if (fileconf && fileconf->file_fontpath) {
- pathFrom = X_CONFIG;
- if (xf86Info.useDefaultFontPath) {
- if (asprintf(&defaultFontPath, "%s%s%s", fileconf->file_fontpath,
- *temp_path ? "," : "", temp_path) == -1)
- defaultFontPath = NULL;
- else
- must_copy = FALSE;
- }
- else
- defaultFontPath = fileconf->file_fontpath;
- }
- else
- pathFrom = X_DEFAULT;
- temp_path = defaultFontPath ? defaultFontPath : "";
-
- /* xf86ValidateFontPath modifies its argument, but returns a copy of it. */
- temp_path = must_copy ? xnfstrdup(defaultFontPath) : defaultFontPath;
- defaultFontPath = xf86ValidateFontPath(temp_path);
- free(temp_path);
-
- /* make fontpath more readable in the logfiles */
- countDirs = 1;
- temp_path = defaultFontPath;
- while ((temp_path = index(temp_path, ',')) != NULL) {
- countDirs++;
- temp_path++;
- }
-
- log_buf = xnfalloc(strlen(defaultFontPath) + (2 * countDirs) + 1);
- temp_path = log_buf;
- start = defaultFontPath;
- while((end = index(start, ',')) != NULL) {
- size = (end - start) + 1;
- *(temp_path++) = '\t';
- strncpy(temp_path, start, size);
- temp_path += size;
- *(temp_path++) = '\n';
- start += size;
- }
- /* copy last entry */
- *(temp_path++) = '\t';
- strcpy(temp_path, start);
- xf86Msg(pathFrom, "FontPath set to:\n%s\n", log_buf);
- free(log_buf);
-
- /* ModulePath */
-
- if (fileconf) {
- if (xf86ModPathFrom != X_CMDLINE && fileconf->file_modulepath) {
- xf86ModulePath = fileconf->file_modulepath;
- xf86ModPathFrom = X_CONFIG;
- }
- }
-
- xf86Msg(xf86ModPathFrom, "ModulePath set to \"%s\"\n", xf86ModulePath);
-
- if (!xf86xkbdirFlag && fileconf && fileconf->file_xkbdir) {
- XkbBaseDirectory = fileconf->file_xkbdir;
- xf86Msg(X_CONFIG, "XKB base directory set to \"%s\"\n",
- XkbBaseDirectory);
- }
-#if 0
- /* LogFile */
- /*
- * XXX The problem with this is that the log file is already open.
- * One option might be to copy the exiting contents to the new location.
- * and re-open it. The down side is that the default location would
- * already have been overwritten. Another option would be to start with
- * unique temporary location, then copy it once the correct name is known.
- * A problem with this is what happens if the server exits before that
- * happens.
- */
- if (xf86LogFileFrom == X_DEFAULT && fileconf->file_logfile) {
- xf86LogFile = fileconf->file_logfile;
- xf86LogFileFrom = X_CONFIG;
- }
-#endif
-
- return;
-}
-
-typedef enum {
- FLAG_NOTRAPSIGNALS,
- FLAG_DONTVTSWITCH,
- FLAG_DONTZAP,
- FLAG_DONTZOOM,
- FLAG_DISABLEVIDMODE,
- FLAG_ALLOWNONLOCAL,
- FLAG_ALLOWMOUSEOPENFAIL,
- FLAG_VTSYSREQ,
- FLAG_SAVER_BLANKTIME,
- FLAG_DPMS_STANDBYTIME,
- FLAG_DPMS_SUSPENDTIME,
- FLAG_DPMS_OFFTIME,
- FLAG_PIXMAP,
- FLAG_PC98,
- FLAG_NOPM,
- FLAG_XINERAMA,
- FLAG_LOG,
- FLAG_RENDER_COLORMAP_MODE,
- FLAG_RANDR,
- FLAG_AIGLX,
- FLAG_IGNORE_ABI,
- FLAG_ALLOW_EMPTY_INPUT,
- FLAG_USE_DEFAULT_FONT_PATH,
- FLAG_AUTO_ADD_DEVICES,
- FLAG_AUTO_ENABLE_DEVICES,
- FLAG_GLX_VISUALS,
- FLAG_DRI2,
- FLAG_USE_SIGIO
-} FlagValues;
-
-/**
- * NOTE: the last value for each entry is NOT the default. It is set to TRUE
- * if the parser found the option in the config file.
- */
-static OptionInfoRec FlagOptions[] = {
- { FLAG_NOTRAPSIGNALS, "NoTrapSignals", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_DONTVTSWITCH, "DontVTSwitch", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_DONTZAP, "DontZap", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_DONTZOOM, "DontZoom", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_DISABLEVIDMODE, "DisableVidModeExtension", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_ALLOWNONLOCAL, "AllowNonLocalXvidtune", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_ALLOWMOUSEOPENFAIL, "AllowMouseOpenFail", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_VTSYSREQ, "VTSysReq", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_SAVER_BLANKTIME, "BlankTime" , OPTV_INTEGER,
- {0}, FALSE },
- { FLAG_DPMS_STANDBYTIME, "StandbyTime", OPTV_INTEGER,
- {0}, FALSE },
- { FLAG_DPMS_SUSPENDTIME, "SuspendTime", OPTV_INTEGER,
- {0}, FALSE },
- { FLAG_DPMS_OFFTIME, "OffTime", OPTV_INTEGER,
- {0}, FALSE },
- { FLAG_PIXMAP, "Pixmap", OPTV_INTEGER,
- {0}, FALSE },
- { FLAG_PC98, "PC98", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_NOPM, "NoPM", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_XINERAMA, "Xinerama", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_LOG, "Log", OPTV_STRING,
- {0}, FALSE },
- { FLAG_RENDER_COLORMAP_MODE, "RenderColormapMode", OPTV_STRING,
- {0}, FALSE },
- { FLAG_RANDR, "RandR", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_AIGLX, "AIGLX", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_IGNORE_ABI, "IgnoreABI", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_USE_DEFAULT_FONT_PATH, "UseDefaultFontPath", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_AUTO_ADD_DEVICES, "AutoAddDevices", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_AUTO_ENABLE_DEVICES, "AutoEnableDevices", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_GLX_VISUALS, "GlxVisuals", OPTV_STRING,
- {0}, FALSE },
- { FLAG_DRI2, "DRI2", OPTV_BOOLEAN,
- {0}, FALSE },
- { FLAG_USE_SIGIO, "UseSIGIO", OPTV_BOOLEAN,
- {0}, FALSE },
- { -1, NULL, OPTV_NONE,
- {0}, FALSE },
-};
-
-#ifdef SUPPORT_PC98
-static Bool
-detectPC98(void)
-{
- unsigned char buf[2];
-
- if (xf86ReadBIOS(0xf8000, 0xe80, buf, 2) != 2)
- return FALSE;
- if ((buf[0] == 0x98) && (buf[1] == 0x21))
- return TRUE;
- else
- return FALSE;
-}
-#endif
-
-static Bool
-configServerFlags(XF86ConfFlagsPtr flagsconf, XF86OptionPtr layoutopts)
-{
- XF86OptionPtr optp, tmp;
- int i;
- Pix24Flags pix24 = Pix24DontCare;
- Bool value;
- MessageType from;
- const char *s;
- XkbRMLVOSet set;
- /* Default options. */
- set.rules = "base";
- set.model = "pc105";
- set.layout = "us";
- set.variant = NULL;
- set.options = NULL;
-
- /*
- * Merge the ServerLayout and ServerFlags options. The former have
- * precedence over the latter.
- */
- optp = NULL;
- if (flagsconf && flagsconf->flg_option_lst)
- optp = xf86optionListDup(flagsconf->flg_option_lst);
- if (layoutopts) {
- tmp = xf86optionListDup(layoutopts);
- if (optp)
- optp = xf86optionListMerge(optp, tmp);
- else
- optp = tmp;
- }
-
- xf86ProcessOptions(-1, optp, FlagOptions);
-
- xf86GetOptValBool(FlagOptions, FLAG_NOTRAPSIGNALS, &xf86Info.notrapSignals);
- xf86GetOptValBool(FlagOptions, FLAG_DONTVTSWITCH, &xf86Info.dontVTSwitch);
- xf86GetOptValBool(FlagOptions, FLAG_DONTZAP, &xf86Info.dontZap);
- xf86GetOptValBool(FlagOptions, FLAG_DONTZOOM, &xf86Info.dontZoom);
-
- xf86GetOptValBool(FlagOptions, FLAG_IGNORE_ABI, &xf86Info.ignoreABI);
- if (xf86Info.ignoreABI) {
- xf86Msg(X_CONFIG, "Ignoring ABI Version\n");
- }
-
- if (xf86SIGIOSupported()) {
- xf86Info.useSIGIO = xf86ReturnOptValBool(FlagOptions, FLAG_USE_SIGIO, USE_SIGIO_BY_DEFAULT);
- if (xf86IsOptionSet(FlagOptions, FLAG_USE_SIGIO)) {
- from = X_CONFIG;
- } else {
- from = X_DEFAULT;
- }
- if (!xf86Info.useSIGIO) {
- xf86Msg(from, "Disabling SIGIO handlers for input devices\n");
- } else if (from == X_CONFIG) {
- xf86Msg(from, "Enabling SIGIO handlers for input devices\n");
- }
- } else {
- xf86Info.useSIGIO = FALSE;
- }
-
- if (xf86IsOptionSet(FlagOptions, FLAG_AUTO_ADD_DEVICES)) {
- xf86GetOptValBool(FlagOptions, FLAG_AUTO_ADD_DEVICES,
- &xf86Info.autoAddDevices);
- from = X_CONFIG;
- }
- else {
- from = X_DEFAULT;
- }
- xf86Msg(from, "%sutomatically adding devices\n",
- xf86Info.autoAddDevices ? "A" : "Not a");
-
- if (xf86IsOptionSet(FlagOptions, FLAG_AUTO_ENABLE_DEVICES)) {
- xf86GetOptValBool(FlagOptions, FLAG_AUTO_ENABLE_DEVICES,
- &xf86Info.autoEnableDevices);
- from = X_CONFIG;
- }
- else {
- from = X_DEFAULT;
- }
- xf86Msg(from, "%sutomatically enabling devices\n",
- xf86Info.autoEnableDevices ? "A" : "Not a");
-
- /*
- * Set things up based on the config file information. Some of these
- * settings may be overridden later when the command line options are
- * checked.
- */
-#ifdef XF86VIDMODE
- if (xf86GetOptValBool(FlagOptions, FLAG_DISABLEVIDMODE, &value))
- xf86Info.vidModeEnabled = !value;
- if (xf86GetOptValBool(FlagOptions, FLAG_ALLOWNONLOCAL, &value))
- xf86Info.vidModeAllowNonLocal = value;
-#endif
-
- if (xf86GetOptValBool(FlagOptions, FLAG_ALLOWMOUSEOPENFAIL, &value))
- xf86Info.allowMouseOpenFail = value;
-
- if (xf86GetOptValBool(FlagOptions, FLAG_VTSYSREQ, &value)) {
-#ifdef USE_VT_SYSREQ
- xf86Info.vtSysreq = value;
- xf86Msg(X_CONFIG, "VTSysReq %s\n", value ? "enabled" : "disabled");
-#else
- if (value)
- xf86Msg(X_WARNING, "VTSysReq is not supported on this OS\n");
-#endif
- }
-
- xf86Info.pmFlag = TRUE;
- if (xf86GetOptValBool(FlagOptions, FLAG_NOPM, &value))
- xf86Info.pmFlag = !value;
- {
- if ((s = xf86GetOptValString(FlagOptions, FLAG_LOG))) {
- if (!xf86NameCmp(s,"flush")) {
- xf86Msg(X_CONFIG, "Flushing logfile enabled\n");
- xf86Info.log = LogFlush;
- LogSetParameter(XLOG_FLUSH, TRUE);
- } else if (!xf86NameCmp(s,"sync")) {
- xf86Msg(X_CONFIG, "Syncing logfile enabled\n");
- xf86Info.log = LogSync;
- LogSetParameter(XLOG_FLUSH, TRUE);
- LogSetParameter(XLOG_SYNC, TRUE);
- } else {
- xf86Msg(X_WARNING,"Unknown Log option\n");
- }
- }
- }
-
- {
- if ((s = xf86GetOptValString(FlagOptions, FLAG_RENDER_COLORMAP_MODE))){
- int policy = PictureParseCmapPolicy (s);
- if (policy == PictureCmapPolicyInvalid)
- xf86Msg(X_WARNING, "Unknown colormap policy \"%s\"\n", s);
- else
- {
- xf86Msg(X_CONFIG, "Render colormap policy set to %s\n", s);
- PictureCmapPolicy = policy;
- }
- }
- }
-
-#ifdef RANDR
- xf86Info.disableRandR = FALSE;
- xf86Info.randRFrom = X_DEFAULT;
- if (xf86GetOptValBool(FlagOptions, FLAG_RANDR, &value)) {
- xf86Info.disableRandR = !value;
- xf86Info.randRFrom = X_CONFIG;
- }
-#endif
-
- xf86Info.aiglx = TRUE;
- xf86Info.aiglxFrom = X_DEFAULT;
- if (xf86GetOptValBool(FlagOptions, FLAG_AIGLX, &value)) {
- xf86Info.aiglx = value;
- xf86Info.aiglxFrom = X_CONFIG;
- }
-
-#ifdef GLXEXT
- xf86Info.glxVisuals = XF86_GlxVisualsTypical;
- xf86Info.glxVisualsFrom = X_DEFAULT;
- if ((s = xf86GetOptValString(FlagOptions, FLAG_GLX_VISUALS))) {
- if (!xf86NameCmp(s, "minimal")) {
- xf86Info.glxVisuals = XF86_GlxVisualsMinimal;
- } else if (!xf86NameCmp(s, "typical")) {
- xf86Info.glxVisuals = XF86_GlxVisualsTypical;
- } else if (!xf86NameCmp(s, "all")) {
- xf86Info.glxVisuals = XF86_GlxVisualsAll;
- } else {
- xf86Msg(X_WARNING,"Unknown GlxVisuals option\n");
- }
- }
-
- if (xf86GetOptValBool(FlagOptions, FLAG_AIGLX, &value)) {
- xf86Info.aiglx = value;
- xf86Info.aiglxFrom = X_CONFIG;
- }
-#endif
-
- /* if we're not hotplugging, force some input devices to exist */
- xf86Info.forceInputDevices = !(xf86Info.autoAddDevices && xf86Info.autoEnableDevices);
-
- /* when forcing input devices, we use kbd. otherwise evdev, so use the
- * evdev rules set. */
-#if defined(linux)
- if (!xf86Info.forceInputDevices)
- set.rules = "evdev";
-#endif
- XkbSetRulesDflts(&set);
-
- xf86Info.useDefaultFontPath = TRUE;
- xf86Info.useDefaultFontPathFrom = X_DEFAULT;
- if (xf86GetOptValBool(FlagOptions, FLAG_USE_DEFAULT_FONT_PATH, &value)) {
- xf86Info.useDefaultFontPath = value;
- xf86Info.useDefaultFontPathFrom = X_CONFIG;
- }
-
-/* Make sure that timers don't overflow CARD32's after multiplying */
-#define MAX_TIME_IN_MIN (0x7fffffff / MILLI_PER_MIN)
-
- i = -1;
- xf86GetOptValInteger(FlagOptions, FLAG_SAVER_BLANKTIME, &i);
- if ((i >= 0) && (i < MAX_TIME_IN_MIN))
- ScreenSaverTime = defaultScreenSaverTime = i * MILLI_PER_MIN;
- else if (i != -1)
- xf86ConfigError("BlankTime value %d outside legal range of 0 - %d minutes",
- i, MAX_TIME_IN_MIN);
-
-#ifdef DPMSExtension
- i = -1;
- xf86GetOptValInteger(FlagOptions, FLAG_DPMS_STANDBYTIME, &i);
- if ((i >= 0) && (i < MAX_TIME_IN_MIN))
- DPMSStandbyTime = i * MILLI_PER_MIN;
- else if (i != -1)
- xf86ConfigError("StandbyTime value %d outside legal range of 0 - %d minutes",
- i, MAX_TIME_IN_MIN);
- i = -1;
- xf86GetOptValInteger(FlagOptions, FLAG_DPMS_SUSPENDTIME, &i);
- if ((i >= 0) && (i < MAX_TIME_IN_MIN))
- DPMSSuspendTime = i * MILLI_PER_MIN;
- else if (i != -1)
- xf86ConfigError("SuspendTime value %d outside legal range of 0 - %d minutes",
- i, MAX_TIME_IN_MIN);
- i = -1;
- xf86GetOptValInteger(FlagOptions, FLAG_DPMS_OFFTIME, &i);
- if ((i >= 0) && (i < MAX_TIME_IN_MIN))
- DPMSOffTime = i * MILLI_PER_MIN;
- else if (i != -1)
- xf86ConfigError("OffTime value %d outside legal range of 0 - %d minutes",
- i, MAX_TIME_IN_MIN);
-#endif
-
- i = -1;
- xf86GetOptValInteger(FlagOptions, FLAG_PIXMAP, &i);
- switch (i) {
- case 24:
- pix24 = Pix24Use24;
- break;
- case 32:
- pix24 = Pix24Use32;
- break;
- case -1:
- break;
- default:
- xf86ConfigError("Pixmap option's value (%d) must be 24 or 32\n", i);
- return FALSE;
- }
- if (xf86Pix24 != Pix24DontCare) {
- xf86Info.pixmap24 = xf86Pix24;
- xf86Info.pix24From = X_CMDLINE;
- } else if (pix24 != Pix24DontCare) {
- xf86Info.pixmap24 = pix24;
- xf86Info.pix24From = X_CONFIG;
- } else {
- xf86Info.pixmap24 = Pix24DontCare;
- xf86Info.pix24From = X_DEFAULT;
- }
-#ifdef SUPPORT_PC98
- if (xf86GetOptValBool(FlagOptions, FLAG_PC98, &value)) {
- xf86Info.pc98 = value;
- if (value) {
- xf86Msg(X_CONFIG, "Japanese PC98 architecture\n");
- }
- } else
- if (detectPC98()) {
- xf86Info.pc98 = TRUE;
- xf86Msg(X_PROBED, "Japanese PC98 architecture\n");
- }
-#endif
-
-#ifdef PANORAMIX
- from = X_DEFAULT;
- if (!noPanoramiXExtension)
- from = X_CMDLINE;
- else if (xf86GetOptValBool(FlagOptions, FLAG_XINERAMA, &value)) {
- noPanoramiXExtension = !value;
- from = X_CONFIG;
- }
- if (!noPanoramiXExtension)
- xf86Msg(from, "Xinerama: enabled\n");
-#endif
-
-#ifdef DRI2
- xf86Info.dri2 = FALSE;
- xf86Info.dri2From = X_DEFAULT;
- if (xf86GetOptValBool(FlagOptions, FLAG_DRI2, &value)) {
- xf86Info.dri2 = value;
- xf86Info.dri2From = X_CONFIG;
- }
-#endif
-
- return TRUE;
-}
-
-Bool xf86DRI2Enabled(void)
-{
- return xf86Info.dri2;
-}
-
-/*
- * Locate the core input devices. These can be specified/located in
- * the following ways, in order of priority:
- *
- * 1. The InputDevices named by the -pointer and -keyboard command line
- * options.
- * 2. The "CorePointer" and "CoreKeyboard" InputDevices referred to by
- * the active ServerLayout.
- * 3. The first InputDevices marked as "CorePointer" and "CoreKeyboard".
- * 4. The first InputDevices that use 'keyboard' or 'kbd' and a valid mouse
- * driver (mouse, synaptics, evdev, vmmouse, void)
- * 5. Default devices with an empty (default) configuration. These defaults
- * will reference the 'mouse' and 'keyboard' drivers.
- */
-
-static Bool
-checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout)
-{
- InputInfoPtr corePointer = NULL, coreKeyboard = NULL;
- Bool foundPointer = FALSE, foundKeyboard = FALSE;
- const char *pointerMsg = NULL, *keyboardMsg = NULL;
- InputInfoPtr *devs, /* iterator */
- indp;
- InputInfoRec Pointer = {}, Keyboard = {};
- XF86ConfInputPtr confInput;
- XF86ConfInputRec defPtr, defKbd;
- int count = 0;
- MessageType from = X_DEFAULT;
- int found = 0;
- const char *mousedrivers[] = { "mouse", "synaptics", "evdev", "vmmouse",
- "void", NULL };
-
- /*
- * First check if a core pointer or core keyboard have been specified
- * in the active ServerLayout. If more than one is specified for either,
- * remove the core attribute from the later ones.
- */
- for (devs = servlayoutp->inputs; devs && *devs; devs++) {
- indp = *devs;
- if (indp->options &&
- xf86CheckBoolOption(indp->options, "CorePointer", FALSE)) {
- if (!corePointer) {
- corePointer = indp;
- } else {
- xf86ReplaceBoolOption(indp->options, "CorePointer", FALSE);
- xf86Msg(X_WARNING, "Duplicate core pointer devices. "
- "Removing core pointer attribute from \"%s\"\n",
- indp->name);
- }
- }
- if (indp->options &&
- xf86CheckBoolOption(indp->options, "CoreKeyboard", FALSE)) {
- if (!coreKeyboard) {
- coreKeyboard = indp;
- } else {
- xf86ReplaceBoolOption(indp->options, "CoreKeyboard", FALSE);
- xf86Msg(X_WARNING, "Duplicate core keyboard devices. "
- "Removing core keyboard attribute from \"%s\"\n",
- indp->name);
- }
- }
- count++;
- }
-
- confInput = NULL;
-
- /* 1. Check for the -pointer command line option. */
- if (xf86PointerName) {
- confInput = xf86findInput(xf86PointerName,
- xf86configptr->conf_input_lst);
- if (!confInput) {
- xf86Msg(X_ERROR, "No InputDevice section called \"%s\"\n",
- xf86PointerName);
- return FALSE;
- }
- from = X_CMDLINE;
- /*
- * If one was already specified in the ServerLayout, it needs to be
- * removed.
- */
- if (corePointer) {
- for (devs = servlayoutp->inputs; devs && *devs; devs++)
- if (*devs == corePointer)
- {
- free(*devs);
- *devs = (InputInfoPtr)0x1; /* ensure we dont skip next loop*/
- break;
- }
- for (; devs && *devs; devs++)
- devs[0] = devs[1];
- count--;
- }
- corePointer = NULL;
- foundPointer = TRUE;
- }
-
- /* 2. ServerLayout-specified core pointer. */
- if (corePointer) {
- foundPointer = TRUE;
- from = X_CONFIG;
- }
-
- /* 3. First core pointer device. */
- if (!foundPointer && (xf86Info.forceInputDevices || implicitLayout)) {
- XF86ConfInputPtr p;
-
- for (p = xf86configptr->conf_input_lst; p; p = p->list.next) {
- if (p->inp_option_lst &&
- xf86CheckBoolOption(p->inp_option_lst, "CorePointer", FALSE)) {
- confInput = p;
- foundPointer = TRUE;
- from = X_DEFAULT;
- pointerMsg = "first core pointer device";
- break;
- }
- }
- }
-
- /* 4. First pointer with an allowed mouse driver. */
- if (!foundPointer && xf86Info.forceInputDevices) {
- const char **driver = mousedrivers;
- confInput = xf86findInput(CONF_IMPLICIT_POINTER,
- xf86configptr->conf_input_lst);
- while (*driver && !confInput) {
- confInput = xf86findInputByDriver(*driver,
- xf86configptr->conf_input_lst);
- driver++;
- }
- if (confInput) {
- foundPointer = TRUE;
- from = X_DEFAULT;
- pointerMsg = "first mouse device";
- }
- }
-
- /* 5. Built-in default. */
- if (!foundPointer && xf86Info.forceInputDevices) {
- memset(&defPtr, 0, sizeof(defPtr));
- defPtr.inp_identifier = strdup("<default pointer>");
- defPtr.inp_driver = strdup("mouse");
- confInput = &defPtr;
- foundPointer = TRUE;
- from = X_DEFAULT;
- pointerMsg = "default mouse configuration";
- }
-
- /* Add the core pointer device to the layout, and set it to Core. */
- if (foundPointer && confInput) {
- foundPointer = configInput(&Pointer, confInput, from);
- if (foundPointer) {
- count++;
- 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,
- xnfstrdup("CorePointer"), NULL);
- devs[count] = NULL;
- servlayoutp->inputs = devs;
- }
- }
-
- if (!foundPointer && xf86Info.forceInputDevices) {
- /* This shouldn't happen. */
- xf86Msg(X_ERROR, "Cannot locate a core pointer device.\n");
- return FALSE;
- }
-
- /*
- * always synthesize a 'mouse' section configured to send core
- * events, unless a 'void' section is found, in which case the user
- * probably wants to run footless.
- *
- * If you're using an evdev keyboard and expect a default mouse
- * section ... deal.
- */
- for (devs = servlayoutp->inputs; devs && *devs; devs++) {
- const char **driver = mousedrivers;
- while(*driver) {
- if (!strcmp((*devs)->driver, *driver)) {
- found = 1;
- break;
- }
- driver++;
- }
- }
- if (!found && xf86Info.forceInputDevices) {
- xf86Msg(X_INFO, "No default mouse found, adding one\n");
- memset(&defPtr, 0, sizeof(defPtr));
- defPtr.inp_identifier = strdup("<default pointer>");
- defPtr.inp_driver = strdup("mouse");
- confInput = &defPtr;
- foundPointer = configInput(&Pointer, confInput, from);
- if (foundPointer) {
- count++;
- 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);
- devs[count] = NULL;
- servlayoutp->inputs = devs;
- }
- }
-
- confInput = NULL;
-
- /* 1. Check for the -keyboard command line option. */
- if (xf86KeyboardName) {
- confInput = xf86findInput(xf86KeyboardName,
- xf86configptr->conf_input_lst);
- if (!confInput) {
- xf86Msg(X_ERROR, "No InputDevice section called \"%s\"\n",
- xf86KeyboardName);
- return FALSE;
- }
- from = X_CMDLINE;
- /*
- * If one was already specified in the ServerLayout, it needs to be
- * removed.
- */
- if (coreKeyboard) {
- for (devs = servlayoutp->inputs; devs && *devs; devs++)
- if (*devs == coreKeyboard)
- {
- free(*devs);
- *devs = (InputInfoPtr)0x1; /* ensure we dont skip next loop */
- break;
- }
- for (; devs && *devs; devs++)
- devs[0] = devs[1];
- count--;
- }
- coreKeyboard = NULL;
- foundKeyboard = TRUE;
- }
-
- /* 2. ServerLayout-specified core keyboard. */
- if (coreKeyboard) {
- foundKeyboard = TRUE;
- from = X_CONFIG;
- }
-
- /* 3. First core keyboard device. */
- if (!foundKeyboard && (xf86Info.forceInputDevices || implicitLayout)) {
- XF86ConfInputPtr p;
-
- for (p = xf86configptr->conf_input_lst; p; p = p->list.next) {
- if (p->inp_option_lst &&
- xf86CheckBoolOption(p->inp_option_lst, "CoreKeyboard", FALSE)) {
- confInput = p;
- foundKeyboard = TRUE;
- from = X_DEFAULT;
- keyboardMsg = "first core keyboard device";
- break;
- }
- }
- }
-
- /* 4. First keyboard with 'keyboard' or 'kbd' as the driver. */
- if (!foundKeyboard && xf86Info.forceInputDevices) {
- confInput = xf86findInput(CONF_IMPLICIT_KEYBOARD,
- xf86configptr->conf_input_lst);
- if (!confInput) {
- confInput = xf86findInputByDriver("kbd",
- xf86configptr->conf_input_lst);
- }
- if (confInput) {
- foundKeyboard = TRUE;
- from = X_DEFAULT;
- keyboardMsg = "first keyboard device";
- }
- }
-
- /* 5. Built-in default. */
- if (!foundKeyboard && xf86Info.forceInputDevices) {
- memset(&defKbd, 0, sizeof(defKbd));
- defKbd.inp_identifier = strdup("<default keyboard>");
- defKbd.inp_driver = strdup("kbd");
- confInput = &defKbd;
- foundKeyboard = TRUE;
- keyboardMsg = "default keyboard configuration";
- from = X_DEFAULT;
- }
-
- /* Add the core keyboard device to the layout, and set it to Core. */
- if (foundKeyboard && confInput) {
- foundKeyboard = configInput(&Keyboard, confInput, from);
- if (foundKeyboard) {
- count++;
- 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,
- xnfstrdup("CoreKeyboard"), NULL);
- devs[count] = NULL;
- servlayoutp->inputs = devs;
- }
- }
-
- if (!foundKeyboard && xf86Info.forceInputDevices) {
- /* This shouldn't happen. */
- xf86Msg(X_ERROR, "Cannot locate a core keyboard device.\n");
- return FALSE;
- }
-
- if (pointerMsg) {
- if (implicitLayout)
- xf86Msg(X_DEFAULT, "No Layout section. Using the %s.\n",
- pointerMsg);
- else
- xf86Msg(X_DEFAULT, "The core pointer device wasn't specified "
- "explicitly in the layout.\n"
- "\tUsing the %s.\n", pointerMsg);
- }
-
- if (keyboardMsg) {
- if (implicitLayout)
- xf86Msg(X_DEFAULT, "No Layout section. Using the %s.\n",
- keyboardMsg);
- else
- xf86Msg(X_DEFAULT, "The core keyboard device wasn't specified "
- "explicitly in the layout.\n"
- "\tUsing the %s.\n", keyboardMsg);
- }
-
- if (!xf86Info.forceInputDevices && !(foundPointer && foundKeyboard)) {
-#if defined(CONFIG_HAL) || defined(CONFIG_UDEV)
- const char *config_backend;
-#if defined(CONFIG_HAL)
- config_backend = "HAL";
-#else
- config_backend = "udev";
-#endif
- xf86Msg(X_INFO, "The server relies on %s to provide the list of "
- "input devices.\n\tIf no devices become available, "
- "reconfigure %s or disable AutoAddDevices.\n",
- config_backend, config_backend);
-#else
- xf86Msg(X_WARNING, "Hotplugging requested but the server was "
- "compiled without a config backend. "
- "No input devices were configured, the server "
- "will start without any input devices.\n");
-#endif
- }
-
- return TRUE;
-}
-
-typedef enum {
- LAYOUT_ISOLATEDEVICE,
- LAYOUT_SINGLECARD
-} LayoutValues;
-
-static OptionInfoRec LayoutOptions[] = {
- { LAYOUT_ISOLATEDEVICE, "IsolateDevice", OPTV_STRING,
- {0}, FALSE },
- { LAYOUT_SINGLECARD, "SingleCard", OPTV_BOOLEAN,
- {0}, FALSE },
- { -1, NULL, OPTV_NONE,
- {0}, FALSE },
-};
-
-static Bool
-configInputDevices(XF86ConfLayoutPtr layout, serverLayoutPtr servlayoutp)
-{
- XF86ConfInputrefPtr irp;
- InputInfoPtr *indp;
- int count = 0;
-
- /*
- * Count the number of input devices.
- */
- irp = layout->lay_input_lst;
- while (irp) {
- count++;
- irp = (XF86ConfInputrefPtr)irp->list.next;
- }
- DebugF("Found %d input devices in the layout section %s\n",
- count, layout->lay_identifier);
- indp = xnfcalloc((count + 1), sizeof(InputInfoPtr));
- indp[count] = NULL;
- irp = layout->lay_input_lst;
- count = 0;
- while (irp) {
- indp[count] = xf86AllocateInput();
- if (!configInput(indp[count], irp->iref_inputdev, X_CONFIG)) {
- do {
- free(indp[count]);
- } while(count--);
- free(indp);
- return FALSE;
- }
- indp[count]->options = xf86OptionListMerge(indp[count]->options,
- irp->iref_option_lst);
- count++;
- irp = (XF86ConfInputrefPtr)irp->list.next;
- }
- servlayoutp->inputs = indp;
-
- return TRUE;
-}
-
-
-/*
- * figure out which layout is active, which screens are used in that layout,
- * which drivers and monitors are used in these screens
- */
-static Bool
-configLayout(serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout,
- char *default_layout)
-{
- XF86ConfAdjacencyPtr adjp;
- XF86ConfInactivePtr idp;
- int saved_count, count = 0;
- int scrnum;
- XF86ConfLayoutPtr l;
- MessageType from;
- screenLayoutPtr slp;
- GDevPtr gdp;
- int i = 0, j;
-
- if (!servlayoutp)
- return FALSE;
-
- /*
- * which layout section is the active one?
- *
- * If there is a -layout command line option, use that one, otherwise
- * pick the first one.
- */
- from = X_DEFAULT;
- if (xf86LayoutName != NULL)
- from = X_CMDLINE;
- else if (default_layout) {
- xf86LayoutName = default_layout;
- from = X_CONFIG;
- }
- if (xf86LayoutName != NULL) {
- if ((l = xf86findLayout(xf86LayoutName, conf_layout)) == NULL) {
- xf86Msg(X_ERROR, "No ServerLayout section called \"%s\"\n",
- xf86LayoutName);
- return FALSE;
- }
- conf_layout = l;
- }
- xf86Msg(from, "ServerLayout \"%s\"\n", conf_layout->lay_identifier);
- adjp = conf_layout->lay_adjacency_lst;
-
- /*
- * we know that each screen is referenced exactly once on the left side
- * of a layout statement in the Layout section. So to allocate the right
- * size for the array we do a quick walk of the list to figure out how
- * many sections we have
- */
- while (adjp) {
- count++;
- adjp = (XF86ConfAdjacencyPtr)adjp->list.next;
- }
-
- DebugF("Found %d screens in the layout section %s",
- count, conf_layout->lay_identifier);
- if (!count) /* alloc enough storage even if no screen is specified */
- count = 1;
-
- slp = xnfcalloc(1, (count + 1) * sizeof(screenLayoutRec));
- slp[count].screen = NULL;
- /*
- * now that we have storage, loop over the list again and fill in our
- * data structure; at this point we do not fill in the adjacency
- * information as it is not clear if we need it at all
- */
- adjp = conf_layout->lay_adjacency_lst;
- count = 0;
- while (adjp) {
- slp[count].screen = xnfcalloc(1, sizeof(confScreenRec));
- if (adjp->adj_scrnum < 0)
- scrnum = count;
- else
- scrnum = adjp->adj_scrnum;
- if (!configScreen(slp[count].screen, adjp->adj_screen, scrnum,
- X_CONFIG)) {
- do {
- free(slp[count].screen);
- } while(count--);
- free(slp);
- return FALSE;
- }
- slp[count].x = adjp->adj_x;
- slp[count].y = adjp->adj_y;
- slp[count].refname = adjp->adj_refscreen;
- switch (adjp->adj_where) {
- case CONF_ADJ_OBSOLETE:
- slp[count].where = PosObsolete;
- slp[count].topname = adjp->adj_top_str;
- slp[count].bottomname = adjp->adj_bottom_str;
- slp[count].leftname = adjp->adj_left_str;
- slp[count].rightname = adjp->adj_right_str;
- break;
- case CONF_ADJ_ABSOLUTE:
- slp[count].where = PosAbsolute;
- break;
- case CONF_ADJ_RIGHTOF:
- slp[count].where = PosRightOf;
- break;
- case CONF_ADJ_LEFTOF:
- slp[count].where = PosLeftOf;
- break;
- case CONF_ADJ_ABOVE:
- slp[count].where = PosAbove;
- break;
- case CONF_ADJ_BELOW:
- slp[count].where = PosBelow;
- break;
- case CONF_ADJ_RELATIVE:
- slp[count].where = PosRelative;
- break;
- }
- count++;
- adjp = (XF86ConfAdjacencyPtr)adjp->list.next;
- }
-
- /* No screen was specified in the layout. take the first one from the
- * config file, or - if it is NULL - configScreen autogenerates one for
- * us */
- if (!count)
- {
- slp[0].screen = xnfcalloc(1, sizeof(confScreenRec));
- if (!configScreen(slp[0].screen, xf86configptr->conf_screen_lst,
- 0, X_CONFIG)) {
- free(slp[0].screen);
- free(slp);
- return FALSE;
- }
- }
-
- /* XXX Need to tie down the upper left screen. */
-
- /* Fill in the refscreen and top/bottom/left/right values */
- for (i = 0; i < count; i++) {
- for (j = 0; j < count; j++) {
- if (slp[i].refname &&
- strcmp(slp[i].refname, slp[j].screen->id) == 0) {
- slp[i].refscreen = slp[j].screen;
- }
- if (slp[i].topname &&
- strcmp(slp[i].topname, slp[j].screen->id) == 0) {
- slp[i].top = slp[j].screen;
- }
- if (slp[i].bottomname &&
- strcmp(slp[i].bottomname, slp[j].screen->id) == 0) {
- slp[i].bottom = slp[j].screen;
- }
- if (slp[i].leftname &&
- strcmp(slp[i].leftname, slp[j].screen->id) == 0) {
- slp[i].left = slp[j].screen;
- }
- if (slp[i].rightname &&
- strcmp(slp[i].rightname, slp[j].screen->id) == 0) {
- slp[i].right = slp[j].screen;
- }
- }
- if (slp[i].where != PosObsolete
- && slp[i].where != PosAbsolute
- && !slp[i].refscreen) {
- xf86Msg(X_ERROR,"Screen %s doesn't exist: deleting placement\n",
- slp[i].refname);
- slp[i].where = PosAbsolute;
- slp[i].x = 0;
- slp[i].y = 0;
- }
- }
-
- if (!count)
- saved_count = 1;
- else
- saved_count = count;
- /*
- * Count the number of inactive devices.
- */
- count = 0;
- idp = conf_layout->lay_inactive_lst;
- while (idp) {
- count++;
- idp = (XF86ConfInactivePtr)idp->list.next;
- }
- DebugF("Found %d inactive devices in the layout section %s\n",
- count, conf_layout->lay_identifier);
- gdp = xnfalloc((count + 1) * sizeof(GDevRec));
- gdp[count].identifier = NULL;
- idp = conf_layout->lay_inactive_lst;
- count = 0;
- while (idp) {
- if (!configDevice(&gdp[count], idp->inactive_device, FALSE))
- goto bail;
- count++;
- idp = (XF86ConfInactivePtr)idp->list.next;
- }
-
- if (!configInputDevices(conf_layout, servlayoutp))
- goto bail;
-
- servlayoutp->id = conf_layout->lay_identifier;
- servlayoutp->screens = slp;
- servlayoutp->inactives = gdp;
- servlayoutp->options = conf_layout->lay_option_lst;
- from = X_DEFAULT;
-
- return TRUE;
-
-bail:
- do {
- free(slp[saved_count].screen);
- } while(saved_count--);
- free(slp);
- free(gdp);
- return FALSE;
-}
-
-/*
- * No layout section, so find the first Screen section and set that up as
- * the only active screen.
- */
-static Bool
-configImpliedLayout(serverLayoutPtr servlayoutp, XF86ConfScreenPtr conf_screen,
- XF86ConfigPtr xf86configptr)
-{
- MessageType from;
- XF86ConfScreenPtr s;
- screenLayoutPtr slp;
- InputInfoPtr *indp;
- XF86ConfLayoutRec layout;
-
- if (!servlayoutp)
- return FALSE;
-
- /*
- * which screen section is the active one?
- *
- * If there is a -screen option, use that one, otherwise use the first
- * one.
- */
-
- from = X_CONFIG;
- if (xf86ScreenName != NULL) {
- if ((s = xf86findScreen(xf86ScreenName, conf_screen)) == NULL) {
- xf86Msg(X_ERROR, "No Screen section called \"%s\"\n",
- xf86ScreenName);
- return FALSE;
- }
- conf_screen = s;
- from = X_CMDLINE;
- }
-
- /* We have exactly one screen */
-
- slp = xnfcalloc(1, 2 * sizeof(screenLayoutRec));
- slp[0].screen = xnfcalloc(1, sizeof(confScreenRec));
- slp[1].screen = NULL;
- if (!configScreen(slp[0].screen, conf_screen, 0, from)) {
- free(slp);
- return FALSE;
- }
- servlayoutp->id = "(implicit)";
- servlayoutp->screens = slp;
- servlayoutp->inactives = xnfcalloc(1, sizeof(GDevRec));
- servlayoutp->options = NULL;
-
- memset(&layout, 0, sizeof(layout));
- layout.lay_identifier = servlayoutp->id;
- if (xf86layoutAddInputDevices(xf86configptr, &layout) > 0) {
- if (!configInputDevices(&layout, servlayoutp))
- return FALSE;
- from = X_DEFAULT;
- } else {
- /* Set up an empty input device list, then look for some core devices. */
- indp = xnfalloc(sizeof(InputInfoPtr));
- *indp = NULL;
- servlayoutp->inputs = indp;
- }
-
- return TRUE;
-}
-
-static Bool
-configXvAdaptor(confXvAdaptorPtr adaptor, XF86ConfVideoAdaptorPtr conf_adaptor)
-{
- int count = 0;
- XF86ConfVideoPortPtr conf_port;
-
- xf86Msg(X_CONFIG, "| |-->VideoAdaptor \"%s\"\n",
- conf_adaptor->va_identifier);
- adaptor->identifier = conf_adaptor->va_identifier;
- adaptor->options = conf_adaptor->va_option_lst;
- if (conf_adaptor->va_busid || conf_adaptor->va_driver) {
- xf86Msg(X_CONFIG, "| | Unsupported device type, skipping entry\n");
- return FALSE;
- }
-
- /*
- * figure out how many videoport subsections there are and fill them in
- */
- conf_port = conf_adaptor->va_port_lst;
- while(conf_port) {
- count++;
- conf_port = (XF86ConfVideoPortPtr)conf_port->list.next;
- }
- adaptor->ports = xnfalloc((count) * sizeof(confXvPortRec));
- adaptor->numports = count;
- count = 0;
- conf_port = conf_adaptor->va_port_lst;
- while(conf_port) {
- adaptor->ports[count].identifier = conf_port->vp_identifier;
- adaptor->ports[count].options = conf_port->vp_option_lst;
- count++;
- conf_port = (XF86ConfVideoPortPtr)conf_port->list.next;
- }
-
- return TRUE;
-}
-
-static Bool
-configScreen(confScreenPtr screenp, XF86ConfScreenPtr conf_screen, int scrnum,
- MessageType from)
-{
- int count = 0;
- XF86ConfDisplayPtr dispptr;
- XF86ConfAdaptorLinkPtr conf_adaptor;
- Bool defaultMonitor = FALSE;
- XF86ConfScreenRec local_conf_screen;
-
- if (!conf_screen) {
- memset(&local_conf_screen, 0, sizeof(local_conf_screen));
- conf_screen = &local_conf_screen;
- conf_screen->scrn_identifier = "Default Screen Section";
- xf86Msg(X_DEFAULT, "No screen section available. Using defaults.\n");
- }
-
- xf86Msg(from, "|-->Screen \"%s\" (%d)\n", conf_screen->scrn_identifier,
- scrnum);
- /*
- * now we fill in the elements of the screen
- */
- screenp->id = conf_screen->scrn_identifier;
- screenp->screennum = scrnum;
- screenp->defaultdepth = conf_screen->scrn_defaultdepth;
- screenp->defaultbpp = conf_screen->scrn_defaultbpp;
- screenp->defaultfbbpp = conf_screen->scrn_defaultfbbpp;
- screenp->monitor = xnfcalloc(1, sizeof(MonRec));
- /* If no monitor is specified, create a default one. */
- if (!conf_screen->scrn_monitor) {
- XF86ConfMonitorRec defMon;
-
- memset(&defMon, 0, sizeof(defMon));
- defMon.mon_identifier = "<default monitor>";
- if (!configMonitor(screenp->monitor, &defMon))
- return FALSE;
- defaultMonitor = TRUE;
- } else {
- if (!configMonitor(screenp->monitor,conf_screen->scrn_monitor))
- return FALSE;
- }
- /* Configure the device. If there isn't one configured, attach to the
- * first inactive one that we can configure. If there's none that work,
- * set it to NULL so that the section can be autoconfigured later */
- screenp->device = xnfcalloc(1, sizeof(GDevRec));
- if ((!conf_screen->scrn_device) && (xf86configptr->conf_device_lst)) {
- conf_screen->scrn_device = xf86configptr->conf_device_lst;
- xf86Msg(X_DEFAULT, "No device specified for screen \"%s\".\n"
- "\tUsing the first device section listed.\n", screenp->id);
- }
- if (configDevice(screenp->device,conf_screen->scrn_device, TRUE)) {
- screenp->device->myScreenSection = screenp;
- } else {
- screenp->device = NULL;
- }
- screenp->options = conf_screen->scrn_option_lst;
-
- /*
- * figure out how many display subsections there are and fill them in
- */
- dispptr = conf_screen->scrn_display_lst;
- while(dispptr) {
- count++;
- dispptr = (XF86ConfDisplayPtr)dispptr->list.next;
- }
- screenp->displays = xnfalloc((count) * sizeof(DispRec));
- screenp->numdisplays = count;
-
- /* Fill in the default Virtual size, if any */
- if (conf_screen->scrn_virtualX && conf_screen->scrn_virtualY) {
- for (count = 0, dispptr = conf_screen->scrn_display_lst;
- dispptr;
- dispptr = (XF86ConfDisplayPtr)dispptr->list.next, count++) {
- screenp->displays[count].virtualX = conf_screen->scrn_virtualX;
- screenp->displays[count].virtualY = conf_screen->scrn_virtualY;
- }
- }
-
- /* Now do the per-Display Virtual sizes */
- count = 0;
- dispptr = conf_screen->scrn_display_lst;
- while(dispptr) {
- configDisplay(&(screenp->displays[count]),dispptr);
- count++;
- dispptr = (XF86ConfDisplayPtr)dispptr->list.next;
- }
-
- /*
- * figure out how many videoadaptor references there are and fill them in
- */
- conf_adaptor = conf_screen->scrn_adaptor_lst;
- while(conf_adaptor) {
- count++;
- conf_adaptor = (XF86ConfAdaptorLinkPtr)conf_adaptor->list.next;
- }
- screenp->xvadaptors = xnfalloc((count) * sizeof(confXvAdaptorRec));
- screenp->numxvadaptors = 0;
- conf_adaptor = conf_screen->scrn_adaptor_lst;
- while(conf_adaptor) {
- if (configXvAdaptor(&(screenp->xvadaptors[screenp->numxvadaptors]),
- conf_adaptor->al_adaptor))
- screenp->numxvadaptors++;
- conf_adaptor = (XF86ConfAdaptorLinkPtr)conf_adaptor->list.next;
- }
-
- if (defaultMonitor) {
- xf86Msg(X_DEFAULT, "No monitor specified for screen \"%s\".\n"
- "\tUsing a default monitor configuration.\n", screenp->id);
- }
- return TRUE;
-}
-
-typedef enum {
- MON_REDUCEDBLANKING,
- MON_MAX_PIX_CLOCK,
-} MonitorValues;
-
-static OptionInfoRec MonitorOptions[] = {
- { MON_REDUCEDBLANKING, "ReducedBlanking", OPTV_BOOLEAN,
- {0}, FALSE },
- { MON_MAX_PIX_CLOCK, "MaxPixClock", OPTV_FREQ,
- {0}, FALSE },
- { -1, NULL, OPTV_NONE,
- {0}, FALSE },
-};
-
-static Bool
-configMonitor(MonPtr monitorp, XF86ConfMonitorPtr conf_monitor)
-{
- int count;
- DisplayModePtr mode,last = NULL;
- XF86ConfModeLinePtr cmodep;
- XF86ConfModesPtr modes;
- XF86ConfModesLinkPtr modeslnk = conf_monitor->mon_modes_sect_lst;
- Gamma zeros = {0.0, 0.0, 0.0};
- float badgamma = 0.0;
- double maxPixClock;
-
- xf86Msg(X_CONFIG, "| |-->Monitor \"%s\"\n",
- conf_monitor->mon_identifier);
- monitorp->id = conf_monitor->mon_identifier;
- monitorp->vendor = conf_monitor->mon_vendor;
- monitorp->model = conf_monitor->mon_modelname;
- monitorp->Modes = NULL;
- monitorp->Last = NULL;
- monitorp->gamma = zeros;
- monitorp->widthmm = conf_monitor->mon_width;
- monitorp->heightmm = conf_monitor->mon_height;
- monitorp->reducedblanking = FALSE;
- monitorp->maxPixClock = 0;
- monitorp->options = conf_monitor->mon_option_lst;
-
- /*
- * fill in the monitor structure
- */
- for( count = 0 ;
- count < conf_monitor->mon_n_hsync && count < MAX_HSYNC;
- count++) {
- monitorp->hsync[count].hi = conf_monitor->mon_hsync[count].hi;
- monitorp->hsync[count].lo = conf_monitor->mon_hsync[count].lo;
- }
- monitorp->nHsync = count;
- for( count = 0 ;
- count < conf_monitor->mon_n_vrefresh && count < MAX_VREFRESH;
- count++) {
- monitorp->vrefresh[count].hi = conf_monitor->mon_vrefresh[count].hi;
- monitorp->vrefresh[count].lo = conf_monitor->mon_vrefresh[count].lo;
- }
- monitorp->nVrefresh = count;
-
- /*
- * first we collect the mode lines from the UseModes directive
- */
- while(modeslnk)
- {
- modes = xf86findModes (modeslnk->ml_modes_str,
- xf86configptr->conf_modes_lst);
- modeslnk->ml_modes = modes;
-
-
- /* now add the modes found in the modes
- section to the list of modes for this
- monitor unless it has been added before
- because we are reusing the same section
- for another screen */
- if (xf86itemNotSublist(
- (GenericListPtr)conf_monitor->mon_modeline_lst,
- (GenericListPtr)modes->mon_modeline_lst)) {
- conf_monitor->mon_modeline_lst = (XF86ConfModeLinePtr)
- xf86addListItem(
- (GenericListPtr)conf_monitor->mon_modeline_lst,
- (GenericListPtr)modes->mon_modeline_lst);
- }
- modeslnk = modeslnk->list.next;
- }
-
- /*
- * we need to hook in the mode lines now
- * here both data structures use lists, only our internal one
- * is double linked
- */
- cmodep = conf_monitor->mon_modeline_lst;
- while( cmodep ) {
- mode = xnfcalloc(1, sizeof(DisplayModeRec));
- mode->type = 0;
- mode->Clock = cmodep->ml_clock;
- mode->HDisplay = cmodep->ml_hdisplay;
- mode->HSyncStart = cmodep->ml_hsyncstart;
- mode->HSyncEnd = cmodep->ml_hsyncend;
- mode->HTotal = cmodep->ml_htotal;
- mode->VDisplay = cmodep->ml_vdisplay;
- mode->VSyncStart = cmodep->ml_vsyncstart;
- mode->VSyncEnd = cmodep->ml_vsyncend;
- mode->VTotal = cmodep->ml_vtotal;
- mode->Flags = cmodep->ml_flags;
- mode->HSkew = cmodep->ml_hskew;
- mode->VScan = cmodep->ml_vscan;
- mode->name = xnfstrdup(cmodep->ml_identifier);
- if( last ) {
- mode->prev = last;
- last->next = mode;
- }
- else {
- /*
- * this is the first mode
- */
- monitorp->Modes = mode;
- mode->prev = NULL;
- }
- last = mode;
- cmodep = (XF86ConfModeLinePtr)cmodep->list.next;
- }
- if(last){
- last->next = NULL;
- }
- monitorp->Last = last;
-
- /* add the (VESA) default modes */
- if (! addDefaultModes(monitorp) )
- return FALSE;
-
- if (conf_monitor->mon_gamma_red > GAMMA_ZERO)
- monitorp->gamma.red = conf_monitor->mon_gamma_red;
- if (conf_monitor->mon_gamma_green > GAMMA_ZERO)
- monitorp->gamma.green = conf_monitor->mon_gamma_green;
- if (conf_monitor->mon_gamma_blue > GAMMA_ZERO)
- monitorp->gamma.blue = conf_monitor->mon_gamma_blue;
-
- /* Check that the gamma values are within range */
- if (monitorp->gamma.red > GAMMA_ZERO &&
- (monitorp->gamma.red < GAMMA_MIN ||
- monitorp->gamma.red > GAMMA_MAX)) {
- badgamma = monitorp->gamma.red;
- } else if (monitorp->gamma.green > GAMMA_ZERO &&
- (monitorp->gamma.green < GAMMA_MIN ||
- monitorp->gamma.green > GAMMA_MAX)) {
- badgamma = monitorp->gamma.green;
- } else if (monitorp->gamma.blue > GAMMA_ZERO &&
- (monitorp->gamma.blue < GAMMA_MIN ||
- monitorp->gamma.blue > GAMMA_MAX)) {
- badgamma = monitorp->gamma.blue;
- }
- if (badgamma > GAMMA_ZERO) {
- xf86ConfigError("Gamma value %.f is out of range (%.2f - %.1f)\n",
- badgamma, GAMMA_MIN, GAMMA_MAX);
- return FALSE;
- }
-
- xf86ProcessOptions(-1, monitorp->options, MonitorOptions);
- xf86GetOptValBool(MonitorOptions, MON_REDUCEDBLANKING,
- &monitorp->reducedblanking);
- if (xf86GetOptValFreq(MonitorOptions, MON_MAX_PIX_CLOCK, OPTUNITS_KHZ,
- &maxPixClock) == TRUE) {
- monitorp->maxPixClock = (int) maxPixClock;
- }
-
- return TRUE;
-}
-
-static int
-lookupVisual(const char *visname)
-{
- int i;
-
- if (!visname || !*visname)
- return -1;
-
- for (i = 0; i <= DirectColor; i++) {
- if (!xf86nameCompare(visname, xf86VisualNames[i]))
- break;
- }
-
- if (i <= DirectColor)
- return i;
-
- return -1;
-}
-
-
-static Bool
-configDisplay(DispPtr displayp, XF86ConfDisplayPtr conf_display)
-{
- int count = 0;
- XF86ModePtr modep;
-
- displayp->frameX0 = conf_display->disp_frameX0;
- displayp->frameY0 = conf_display->disp_frameY0;
- displayp->virtualX = conf_display->disp_virtualX;
- displayp->virtualY = conf_display->disp_virtualY;
- displayp->depth = conf_display->disp_depth;
- displayp->fbbpp = conf_display->disp_bpp;
- displayp->weight.red = conf_display->disp_weight.red;
- displayp->weight.green = conf_display->disp_weight.green;
- displayp->weight.blue = conf_display->disp_weight.blue;
- displayp->blackColour.red = conf_display->disp_black.red;
- displayp->blackColour.green = conf_display->disp_black.green;
- displayp->blackColour.blue = conf_display->disp_black.blue;
- displayp->whiteColour.red = conf_display->disp_white.red;
- displayp->whiteColour.green = conf_display->disp_white.green;
- displayp->whiteColour.blue = conf_display->disp_white.blue;
- displayp->options = conf_display->disp_option_lst;
- if (conf_display->disp_visual) {
- displayp->defaultVisual = lookupVisual(conf_display->disp_visual);
- if (displayp->defaultVisual == -1) {
- xf86ConfigError("Invalid visual name: \"%s\"",
- conf_display->disp_visual);
- return FALSE;
- }
- } else {
- displayp->defaultVisual = -1;
- }
-
- /*
- * now hook in the modes
- */
- modep = conf_display->disp_mode_lst;
- while(modep) {
- count++;
- modep = (XF86ModePtr)modep->list.next;
- }
- displayp->modes = xnfalloc((count+1) * sizeof(char*));
- modep = conf_display->disp_mode_lst;
- count = 0;
- while(modep) {
- displayp->modes[count] = modep->mode_name;
- count++;
- modep = (XF86ModePtr)modep->list.next;
- }
- displayp->modes[count] = NULL;
-
- return TRUE;
-}
-
-static Bool
-configDevice(GDevPtr devicep, XF86ConfDevicePtr conf_device, Bool active)
-{
- int i;
-
- if (!conf_device) {
- return FALSE;
- }
-
- if (active)
- xf86Msg(X_CONFIG, "| |-->Device \"%s\"\n",
- conf_device->dev_identifier);
- else
- xf86Msg(X_CONFIG, "|-->Inactive Device \"%s\"\n",
- conf_device->dev_identifier);
-
- devicep->identifier = conf_device->dev_identifier;
- devicep->vendor = conf_device->dev_vendor;
- devicep->board = conf_device->dev_board;
- devicep->chipset = conf_device->dev_chipset;
- devicep->ramdac = conf_device->dev_ramdac;
- devicep->driver = conf_device->dev_driver;
- devicep->active = active;
- devicep->videoRam = conf_device->dev_videoram;
- devicep->BiosBase = conf_device->dev_bios_base;
- devicep->MemBase = conf_device->dev_mem_base;
- devicep->IOBase = conf_device->dev_io_base;
- devicep->clockchip = conf_device->dev_clockchip;
- devicep->busID = conf_device->dev_busid;
- devicep->textClockFreq = conf_device->dev_textclockfreq;
- devicep->chipID = conf_device->dev_chipid;
- devicep->chipRev = conf_device->dev_chiprev;
- devicep->options = conf_device->dev_option_lst;
- devicep->irq = conf_device->dev_irq;
- devicep->screen = conf_device->dev_screen;
-
- for (i = 0; i < MAXDACSPEEDS; i++) {
- if (i < CONF_MAXDACSPEEDS)
- devicep->dacSpeeds[i] = conf_device->dev_dacSpeeds[i];
- else
- devicep->dacSpeeds[i] = 0;
- }
- devicep->numclocks = conf_device->dev_clocks;
- if (devicep->numclocks > MAXCLOCKS)
- devicep->numclocks = MAXCLOCKS;
- for (i = 0; i < devicep->numclocks; i++) {
- devicep->clock[i] = conf_device->dev_clock[i];
- }
- devicep->claimed = FALSE;
-
- return TRUE;
-}
-
-#ifdef XF86DRI
-static void
-configDRI(XF86ConfDRIPtr drip)
-{
- struct group *grp;
-
- xf86ConfigDRI.group = -1;
- xf86ConfigDRI.mode = 0;
-
- if (drip) {
- if (drip->dri_group_name) {
- if ((grp = getgrnam(drip->dri_group_name)))
- xf86ConfigDRI.group = grp->gr_gid;
- } else {
- if (drip->dri_group >= 0)
- xf86ConfigDRI.group = drip->dri_group;
- }
- xf86ConfigDRI.mode = drip->dri_mode;
- }
-}
-#endif
-
-static void
-configExtensions(XF86ConfExtensionsPtr conf_ext)
-{
- XF86OptionPtr o;
-
- if (conf_ext && conf_ext->ext_option_lst) {
- for (o = conf_ext->ext_option_lst; o; o = xf86NextOption(o)) {
- char *name = xf86OptionName(o);
- char *val = xf86OptionValue(o);
- char *n;
- Bool enable = TRUE;
-
- /* Handle "No<ExtensionName>" */
- n = xf86NormalizeName(name);
- if (strncmp(n, "no", 2) == 0) {
- name += 2;
- enable = FALSE;
- }
-
- if (!val ||
- xf86NameCmp(val, "enable") == 0 ||
- xf86NameCmp(val, "enabled") == 0 ||
- xf86NameCmp(val, "on") == 0 ||
- xf86NameCmp(val, "1") == 0 ||
- xf86NameCmp(val, "yes") == 0 ||
- xf86NameCmp(val, "true") == 0) {
- /* NOTHING NEEDED -- enabling is handled below */
- } else if (xf86NameCmp(val, "disable") == 0 ||
- xf86NameCmp(val, "disabled") == 0 ||
- xf86NameCmp(val, "off") == 0 ||
- xf86NameCmp(val, "0") == 0 ||
- xf86NameCmp(val, "no") == 0 ||
- xf86NameCmp(val, "false") == 0) {
- enable = !enable;
- } else {
- xf86Msg(X_WARNING, "Ignoring unrecognized value \"%s\"\n", val);
- free(n);
- continue;
- }
-
- if (EnableDisableExtension(name, enable)) {
- xf86Msg(X_CONFIG, "Extension \"%s\" is %s\n",
- name, enable ? "enabled" : "disabled");
- } else {
- xf86Msg(X_WARNING, "Ignoring unrecognized extension \"%s\"\n",
- name);
- }
- free(n);
- }
- }
-}
-
-static Bool
-configInput(InputInfoPtr inputp, XF86ConfInputPtr conf_input, MessageType from)
-{
- xf86Msg(from, "|-->Input Device \"%s\"\n", conf_input->inp_identifier);
- inputp->name = conf_input->inp_identifier;
- inputp->driver = conf_input->inp_driver;
- inputp->options = conf_input->inp_option_lst;
- inputp->attrs = NULL;
-
- return TRUE;
-}
-
-static Bool
-modeIsPresent(DisplayModePtr mode, MonPtr monitorp)
-{
- DisplayModePtr knownmodes = monitorp->Modes;
-
- /* all I can think of is a linear search... */
- while(knownmodes != NULL)
- {
- if(!strcmp(mode->name, knownmodes->name) &&
- !(knownmodes->type & M_T_DEFAULT))
- return TRUE;
- knownmodes = knownmodes->next;
- }
- return FALSE;
-}
-
-static Bool
-addDefaultModes(MonPtr monitorp)
-{
- DisplayModePtr mode;
- DisplayModePtr last = monitorp->Last;
- int i = 0;
-
- for (i = 0; i < xf86NumDefaultModes; i++)
- {
- mode = xf86DuplicateMode(&xf86DefaultModes[i]);
- if (!modeIsPresent(mode, monitorp))
- {
- monitorp->Modes = xf86ModesAdd(monitorp->Modes, mode);
- last = mode;
- } else {
- free(mode);
- }
- }
- monitorp->Last = last;
-
- return TRUE;
-}
-
-static void
-checkInput(serverLayoutPtr layout, Bool implicit_layout) {
- checkCoreInputDevices(layout, implicit_layout);
-
- /* Unless we're forcing input devices, disable mouse/kbd devices in the
- * config. Otherwise the same physical device is added multiple times,
- * leading to duplicate events.
- */
- if (!xf86Info.forceInputDevices && layout->inputs)
- {
- InputInfoPtr *dev = layout->inputs;
- BOOL warned = FALSE;
-
- while(*dev)
- {
- if (strcmp((*dev)->driver, "kbd") == 0 ||
- strcmp((*dev)->driver, "mouse") == 0 ||
- strcmp((*dev)->driver, "vmmouse") == 0)
- {
- InputInfoPtr *current;
- if (!warned)
- {
- xf86Msg(X_WARNING, "Hotplugging is on, devices using "
- "drivers 'kbd', 'mouse' or 'vmmouse' will be disabled.\n");
- warned = TRUE;
- }
-
- xf86Msg(X_WARNING, "Disabling %s\n", (*dev)->name);
-
- current = dev;
- free(*dev);
-
- do {
- *current = *(current + 1);
- current++;
- } while(*current);
- } else
- dev++;
- }
- }
-}
-
-/*
- * load the config file and fill the global data structure
- */
-ConfigStatus
-xf86HandleConfigFile(Bool autoconfig)
-{
- const char *filename, *dirname, *sysdirname;
- char *filesearch, *dirsearch;
- MessageType filefrom = X_DEFAULT;
- MessageType dirfrom = X_DEFAULT;
- char *scanptr;
- Bool singlecard = 0;
- Bool implicit_layout = FALSE;
-
- if (!autoconfig) {
- if (getuid() == 0) {
- filesearch = ROOT_CONFIGPATH;
- dirsearch = ROOT_CONFIGDIRPATH;
- } else {
- filesearch = USER_CONFIGPATH;
- dirsearch = USER_CONFIGDIRPATH;
- }
-
- if (xf86ConfigFile)
- filefrom = X_CMDLINE;
- if (xf86ConfigDir)
- dirfrom = X_CMDLINE;
-
- xf86initConfigFiles();
- sysdirname = xf86openConfigDirFiles(SYS_CONFIGDIRPATH, NULL,
- PROJECTROOT);
- dirname = xf86openConfigDirFiles(dirsearch, xf86ConfigDir, PROJECTROOT);
- filename = xf86openConfigFile(filesearch, xf86ConfigFile, PROJECTROOT);
- if (filename) {
- xf86MsgVerb(filefrom, 0, "Using config file: \"%s\"\n", filename);
- xf86ConfigFile = xnfstrdup(filename);
- } else {
- if (xf86ConfigFile)
- xf86Msg(X_ERROR, "Unable to locate/open config file: \"%s\"\n",
- xf86ConfigFile);
- }
- if (dirname) {
- xf86MsgVerb(dirfrom, 0, "Using config directory: \"%s\"\n",
- dirname);
- xf86ConfigDir = xnfstrdup(dirname);
- } else {
- if (xf86ConfigDir)
- xf86Msg(X_ERROR,
- "Unable to locate/open config directory: \"%s\"\n",
- xf86ConfigDir);
- }
- if (sysdirname)
- xf86MsgVerb(X_DEFAULT, 0, "Using system config directory \"%s\"\n",
- sysdirname);
- if (!filename && !dirname && !sysdirname)
- return CONFIG_NOFILE;
- }
-
- if ((xf86configptr = xf86readConfigFile ()) == NULL) {
- xf86Msg(X_ERROR, "Problem parsing the config file\n");
- return CONFIG_PARSE_ERROR;
- }
- xf86closeConfigFile ();
-
- /* Initialise a few things. */
-
- /*
- * now we convert part of the information contained in the parser
- * structures into our own structures.
- * The important part here is to figure out which Screen Sections
- * in the XF86Config file are active so that we can piece together
- * the modes that we need later down the road.
- * And while we are at it, we'll decode the rest of the stuff as well
- */
-
- /* First check if a layout section is present, and if it is valid. */
-
- if (xf86configptr->conf_layout_lst == NULL || xf86ScreenName != NULL) {
- if (xf86ScreenName == NULL) {
- xf86Msg(X_DEFAULT,
- "No Layout section. Using the first Screen section.\n");
- }
- if (!configImpliedLayout(&xf86ConfigLayout,
- xf86configptr->conf_screen_lst,
- xf86configptr)) {
- xf86Msg(X_ERROR, "Unable to determine the screen layout\n");
- return CONFIG_PARSE_ERROR;
- }
- implicit_layout = TRUE;
- } else {
- if (xf86configptr->conf_flags != NULL) {
- char *dfltlayout = NULL;
- pointer optlist = xf86configptr->conf_flags->flg_option_lst;
-
- if (optlist && xf86FindOption(optlist, "defaultserverlayout"))
- dfltlayout = xf86SetStrOption(optlist, "defaultserverlayout", NULL);
- if (!configLayout(&xf86ConfigLayout, xf86configptr->conf_layout_lst,
- dfltlayout)) {
- xf86Msg(X_ERROR, "Unable to determine the screen layout\n");
- return CONFIG_PARSE_ERROR;
- }
- } else {
- if (!configLayout(&xf86ConfigLayout, xf86configptr->conf_layout_lst,
- NULL)) {
- xf86Msg(X_ERROR, "Unable to determine the screen layout\n");
- return CONFIG_PARSE_ERROR;
- }
- }
- }
-
- xf86ProcessOptions(-1, xf86ConfigLayout.options, LayoutOptions);
-
- if ((scanptr = xf86GetOptValString(LayoutOptions, LAYOUT_ISOLATEDEVICE))) {
- ; /* IsolateDevice specified; overrides SingleCard */
- } else {
- xf86GetOptValBool(LayoutOptions, LAYOUT_SINGLECARD, &singlecard);
- if (singlecard)
- scanptr = xf86ConfigLayout.screens->screen->device->busID;
- }
- if (scanptr) {
- if (strncmp(scanptr, "PCI:", 4) != 0) {
- xf86Msg(X_WARNING, "Bus types other than PCI not yet isolable.\n"
- "\tIgnoring IsolateDevice option.\n");
- } else
- xf86PciIsolateDevice(scanptr);
- }
-
- /* Now process everything else */
- if (!configServerFlags(xf86configptr->conf_flags,xf86ConfigLayout.options)){
- ErrorF ("Problem when converting the config data structures\n");
- return CONFIG_PARSE_ERROR;
- }
-
- configFiles(xf86configptr->conf_files);
- configExtensions(xf86configptr->conf_extensions);
-#ifdef XF86DRI
- configDRI(xf86configptr->conf_dri);
-#endif
-
- checkInput(&xf86ConfigLayout, implicit_layout);
-
- /*
- * Handle some command line options that can override some of the
- * ServerFlags settings.
- */
-#ifdef XF86VIDMODE
- if (xf86VidModeDisabled)
- xf86Info.vidModeEnabled = FALSE;
- if (xf86VidModeAllowNonLocal)
- xf86Info.vidModeAllowNonLocal = TRUE;
-#endif
-
- if (xf86AllowMouseOpenFail)
- xf86Info.allowMouseOpenFail = TRUE;
-
- return CONFIG_OK;
-}
-
-Bool
-xf86PathIsSafe(const char *path)
-{
- return (xf86pathIsSafe(path) != 0);
-}
+/* + * Loosely based on code bearing the following copyright: + * + * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany. + */ + +/* + * Copyright 1992-2003 by The XFree86 Project, Inc. + * Copyright 1997 by Metro Link, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* + * + * Authors: + * Dirk Hohndel <hohndel@XFree86.Org> + * David Dawes <dawes@XFree86.Org> + * Marc La France <tsi@XFree86.Org> + * Egbert Eich <eich@XFree86.Org> + * ... and others + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#ifdef XF86DRI +#include <sys/types.h> +#include <grp.h> +#endif + +#include "xf86.h" +#include "xf86Parser.h" +#include "xf86tokens.h" +#include "xf86Config.h" +#include "xf86Priv.h" +#include "xf86_OSlib.h" +#include "configProcs.h" +#include "globals.h" +#include "extension.h" +#include "xf86pciBus.h" + +#include "xf86Xinput.h" + +#include "xkbsrv.h" + +#include "picture.h" + +/* + * These paths define the way the config file search is done. The escape + * sequences are documented in parser/scan.c. + */ +#ifndef ROOT_CONFIGPATH +#define ROOT_CONFIGPATH "%A," "%R," \ + "/etc/X11/%R," "%P/etc/X11/%R," \ + "%E," "%F," \ + "/etc/X11/%F," "%P/etc/X11/%F," \ + "/etc/X11/%X," "/etc/%X," \ + "%P/etc/X11/%X.%H," \ + "%P/etc/X11/%X," \ + "%P/lib/X11/%X.%H," \ + "%P/lib/X11/%X" +#endif +#ifndef USER_CONFIGPATH +#define USER_CONFIGPATH "/etc/X11/%S," "%P/etc/X11/%S," \ + "/etc/X11/%G," "%P/etc/X11/%G," \ + "/etc/X11/%X," "/etc/%X," \ + "%P/etc/X11/%X.%H," \ + "%P/etc/X11/%X," \ + "%P/lib/X11/%X.%H," \ + "%P/lib/X11/%X" +#endif +#ifndef ROOT_CONFIGDIRPATH +#define ROOT_CONFIGDIRPATH "%A," "%R," \ + "/etc/X11/%R," "%C/X11/%R," \ + "/etc/X11/%X," "%C/X11/%X" +#endif +#ifndef USER_CONFIGDIRPATH +#define USER_CONFIGDIRPATH "/etc/X11/%R," "%C/X11/%R," \ + "/etc/X11/%X," "%C/X11/%X" +#endif +#ifndef SYS_CONFIGDIRPATH +#define SYS_CONFIGDIRPATH "/usr/share/X11/%X," "%D/X11/%X" +#endif +#ifndef PROJECTROOT +#define PROJECTROOT "/usr/X11R6" +#endif + +static ModuleDefault ModuleDefaults[] = { + {.name = "extmod", .toLoad = TRUE, .load_opt=NULL}, +#ifdef DBE + {.name = "dbe", .toLoad = TRUE, .load_opt=NULL}, +#endif +#ifdef GLXEXT + {.name = "glx", .toLoad = TRUE, .load_opt=NULL}, +#endif +#ifdef XRECORD + {.name = "record", .toLoad = TRUE, .load_opt=NULL}, +#endif +#ifdef XF86DRI + {.name = "dri", .toLoad = TRUE, .load_opt=NULL}, +#endif +#ifdef DRI2 + {.name = "dri2", .toLoad = TRUE, .load_opt=NULL}, +#endif + {.name = NULL, .toLoad = FALSE, .load_opt=NULL} +}; + + +/* Forward declarations */ +static Bool configScreen(confScreenPtr screenp, XF86ConfScreenPtr conf_screen, + int scrnum, MessageType from); +static Bool configMonitor(MonPtr monitorp, XF86ConfMonitorPtr conf_monitor); +static Bool configDevice(GDevPtr devicep, XF86ConfDevicePtr conf_device, + Bool active); +static Bool configInput(InputInfoPtr pInfo, XF86ConfInputPtr conf_input, + MessageType from); +static Bool configDisplay(DispPtr displayp, XF86ConfDisplayPtr conf_display); +static Bool addDefaultModes(MonPtr monitorp); +#ifdef XF86DRI +static void configDRI(XF86ConfDRIPtr drip); +#endif +static void configExtensions(XF86ConfExtensionsPtr conf_ext); + +/* + * xf86GetPathElem -- + * Extract a single element from the font path string starting at + * pnt. The font path element will be returned, and pnt will be + * updated to point to the start of the next element, or set to + * NULL if there are no more. + */ +static char * +xf86GetPathElem(char **pnt) +{ + char *p1; + + p1 = *pnt; + *pnt = index(*pnt, ','); + if (*pnt != NULL) { + **pnt = '\0'; + *pnt += 1; + } + return p1; +} + +/* + * xf86ValidateFontPath -- + * Validates the user-specified font path. Each element that + * begins with a '/' is checked to make sure the directory exists. + * If the directory exists, the existence of a file named 'fonts.dir' + * is checked. If either check fails, an error is printed and the + * element is removed from the font path. + */ + +#define DIR_FILE "/fonts.dir" +static char * +xf86ValidateFontPath(char *path) +{ + char *tmp_path, *out_pnt, *path_elem, *next, *p1, *dir_elem; + struct stat stat_buf; + int flag; + int dirlen; + + tmp_path = calloc(1,strlen(path)+1); + out_pnt = tmp_path; + path_elem = NULL; + next = path; + while (next != NULL) { + path_elem = xf86GetPathElem(&next); + if (*path_elem == '/') { + dir_elem = xnfcalloc(1, strlen(path_elem) + 1); + if ((p1 = strchr(path_elem, ':')) != 0) + dirlen = p1 - path_elem; + else + dirlen = strlen(path_elem); + strncpy(dir_elem, path_elem, dirlen); + dir_elem[dirlen] = '\0'; + flag = stat(dir_elem, &stat_buf); + if (flag == 0) + if (!S_ISDIR(stat_buf.st_mode)) + flag = -1; + if (flag != 0) { + xf86Msg(X_WARNING, "The directory \"%s\" does not exist.\n", dir_elem); + xf86ErrorF("\tEntry deleted from font path.\n"); + free(dir_elem); + continue; + } + else { + XNFasprintf(&p1, "%s%s", dir_elem, DIR_FILE); + flag = stat(p1, &stat_buf); + if (flag == 0) + if (!S_ISREG(stat_buf.st_mode)) + flag = -1; + free(p1); + if (flag != 0) { + xf86Msg(X_WARNING, + "`fonts.dir' not found (or not valid) in \"%s\".\n", + dir_elem); + xf86ErrorF("\tEntry deleted from font path.\n"); + xf86ErrorF("\t(Run 'mkfontdir' on \"%s\").\n", dir_elem); + free(dir_elem); + continue; + } + } + free(dir_elem); + } + + /* + * Either an OK directory, or a font server name. So add it to + * the path. + */ + if (out_pnt != tmp_path) + *out_pnt++ = ','; + strcat(out_pnt, path_elem); + out_pnt += strlen(path_elem); + } + return tmp_path; +} + + +/* + * use the datastructure that the parser provides and pick out the parts + * that we need at this point + */ +char ** +xf86ModulelistFromConfig(pointer **optlist) +{ + int count = 0, i = 0; + char **modulearray; + char *ignore[] = { "GLcore", "speedo", "bitmap", "drm", + "freetype", "type1", + NULL }; + pointer *optarray; + XF86LoadPtr modp; + Bool found; + + /* + * make sure the config file has been parsed and that we have a + * ModulePath set; if no ModulePath was given, use the default + * ModulePath + */ + if (xf86configptr == NULL) { + xf86Msg(X_ERROR, "Cannot access global config data structure\n"); + return NULL; + } + + if (xf86configptr->conf_modules) { + /* Walk the disable list and let people know what we've parsed to + * not be loaded + */ + modp = xf86configptr->conf_modules->mod_disable_lst; + while (modp) { + xf86Msg(X_WARNING, "\"%s\" will not be loaded unless you've specified it to be loaded elsewhere.\n", modp->load_name); + modp = (XF86LoadPtr) modp->list.next; + } + /* + * Walk the default settings table. For each module listed to be + * loaded, make sure it's in the mod_load_lst. If it's not, make + * sure it's not in the mod_no_load_lst. If it's not disabled, + * append it to mod_load_lst + */ + for (i=0 ; ModuleDefaults[i].name != NULL ; i++) { + if (ModuleDefaults[i].toLoad == FALSE) { + xf86Msg(X_WARNING, "\"%s\" is not to be loaded by default. Skipping.\n", ModuleDefaults[i].name); + continue; + } + found = FALSE; + modp = xf86configptr->conf_modules->mod_load_lst; + while (modp) { + if (strcmp(modp->load_name, ModuleDefaults[i].name) == 0) { + xf86Msg(X_INFO, "\"%s\" will be loaded. This was enabled by default and also specified in the config file.\n", ModuleDefaults[i].name); + found = TRUE; + break; + } + modp = (XF86LoadPtr) modp->list.next; + } + if (found == FALSE) { + modp = xf86configptr->conf_modules->mod_disable_lst; + while (modp) { + if (strcmp(modp->load_name, ModuleDefaults[i].name) == 0) { + xf86Msg(X_INFO, "\"%s\" will be loaded even though the default is to disable it.\n", ModuleDefaults[i].name); + found = TRUE; + break; + } + modp = (XF86LoadPtr) modp->list.next; + } + } + if (found == FALSE) { + XF86LoadPtr ptr = (XF86LoadPtr)xf86configptr->conf_modules; + xf86addNewLoadDirective(ptr, ModuleDefaults[i].name, XF86_LOAD_MODULE, ModuleDefaults[i].load_opt); + xf86Msg(X_INFO, "\"%s\" will be loaded by default.\n", ModuleDefaults[i].name); + } + } + } else { + xf86configptr->conf_modules = xnfcalloc(1, sizeof(XF86ConfModuleRec)); + for (i=0 ; ModuleDefaults[i].name != NULL ; i++) { + if (ModuleDefaults[i].toLoad == TRUE) { + XF86LoadPtr ptr = (XF86LoadPtr)xf86configptr->conf_modules; + xf86addNewLoadDirective(ptr, ModuleDefaults[i].name, XF86_LOAD_MODULE, ModuleDefaults[i].load_opt); + } + } + } + + /* + * Walk the list of modules in the "Module" section to determine how + * many we have. + */ + modp = xf86configptr->conf_modules->mod_load_lst; + while (modp) { + for (i = 0; ignore[i]; i++) { + if (strcmp(modp->load_name, ignore[i]) == 0) + modp->ignore = 1; + } + if (!modp->ignore) + count++; + modp = (XF86LoadPtr) modp->list.next; + } + + /* + * allocate the memory and walk the list again to fill in the pointers + */ + modulearray = xnfalloc((count + 1) * sizeof(char*)); + optarray = xnfalloc((count + 1) * sizeof(pointer)); + count = 0; + if (xf86configptr->conf_modules) { + modp = xf86configptr->conf_modules->mod_load_lst; + while (modp) { + if (!modp->ignore) { + modulearray[count] = modp->load_name; + optarray[count] = modp->load_opt; + count++; + } + modp = (XF86LoadPtr) modp->list.next; + } + } + modulearray[count] = NULL; + optarray[count] = NULL; + if (optlist) + *optlist = optarray; + else + free(optarray); + return modulearray; +} + + +char ** +xf86DriverlistFromConfig(void) +{ + int count = 0; + int j; + char **modulearray; + screenLayoutPtr slp; + + /* + * make sure the config file has been parsed and that we have a + * ModulePath set; if no ModulePath was given, use the default + * ModulePath + */ + if (xf86configptr == NULL) { + xf86Msg(X_ERROR, "Cannot access global config data structure\n"); + return NULL; + } + + /* + * Walk the list of driver lines in active "Device" sections to + * determine now many implicitly loaded modules there are. + * + */ + if (xf86ConfigLayout.screens) { + slp = xf86ConfigLayout.screens; + while ((slp++)->screen) { + count++; + } + } + + /* + * Handle the set of inactive "Device" sections. + */ + j = 0; + while (xf86ConfigLayout.inactives[j++].identifier) + count++; + + if (count == 0) + return NULL; + + /* + * allocate the memory and walk the list again to fill in the pointers + */ + modulearray = xnfalloc((count + 1) * sizeof(char*)); + count = 0; + slp = xf86ConfigLayout.screens; + while (slp->screen) { + modulearray[count] = slp->screen->device->driver; + count++; + slp++; + } + + j = 0; + + while (xf86ConfigLayout.inactives[j].identifier) + modulearray[count++] = xf86ConfigLayout.inactives[j++].driver; + + modulearray[count] = NULL; + + /* Remove duplicates */ + for (count = 0; modulearray[count] != NULL; count++) { + int i; + + for (i = 0; i < count; i++) + if (xf86NameCmp(modulearray[i], modulearray[count]) == 0) { + modulearray[count] = ""; + break; + } + } + return modulearray; +} + +char ** +xf86InputDriverlistFromConfig(void) +{ + int count = 0; + char **modulearray; + InputInfoPtr *idp; + + /* + * make sure the config file has been parsed and that we have a + * ModulePath set; if no ModulePath was given, use the default + * ModulePath + */ + if (xf86configptr == NULL) { + xf86Msg(X_ERROR, "Cannot access global config data structure\n"); + return NULL; + } + + /* + * Walk the list of driver lines in active "InputDevice" sections to + * determine now many implicitly loaded modules there are. + */ + if (xf86ConfigLayout.inputs) { + idp = xf86ConfigLayout.inputs; + while (*idp) { + count++; + idp++; + } + } + + if (count == 0) + return NULL; + + /* + * allocate the memory and walk the list again to fill in the pointers + */ + modulearray = xnfalloc((count + 1) * sizeof(char*)); + count = 0; + idp = xf86ConfigLayout.inputs; + while (idp && *idp) { + modulearray[count] = (*idp)->driver; + count++; + idp++; + } + modulearray[count] = NULL; + + /* Remove duplicates */ + for (count = 0; modulearray[count] != NULL; count++) { + int i; + + for (i = 0; i < count; i++) + if (xf86NameCmp(modulearray[i], modulearray[count]) == 0) { + modulearray[count] = ""; + break; + } + } + return modulearray; +} + +static void +fixup_video_driver_list(char **drivers) +{ + static const char *fallback[4] = { "vesa", "fbdev", "wsfb", NULL }; + char **end, **drv; + char *x; + int i; + + /* walk to the end of the list */ + for (end = drivers; *end && **end; end++) ; + end--; + + /* + * for each of the fallback drivers, if we find it in the list, + * swap it with the last available non-fallback driver. + */ + for (i = 0; fallback[i]; i++) { + for (drv = drivers; drv != end; drv++) { + if (strstr(*drv, fallback[i])) { + x = *drv; *drv = *end; *end = x; + end--; + break; + } + } + } +} + +static char ** +GenerateDriverlist(char * dirname) +{ + char **ret; + const char *subdirs[] = { dirname, NULL }; + static const char *patlist[] = {"(.*)_drv\\.so", NULL}; + ret = LoaderListDirs(subdirs, patlist); + + /* fix up the probe order for video drivers */ + if (strstr(dirname, "drivers") && ret != NULL) + fixup_video_driver_list(ret); + + return ret; +} + +char ** +xf86DriverlistFromCompile(void) +{ + static char **driverlist = NULL; + + if (!driverlist) + driverlist = GenerateDriverlist("drivers"); + + return driverlist; +} + +/* + * xf86ConfigError -- + * Print a READABLE ErrorMessage!!! All information that is + * available is printed. + */ +static void +xf86ConfigError(char *msg, ...) +{ + va_list ap; + + ErrorF("\nConfig Error:\n"); + va_start(ap, msg); + VErrorF(msg, ap); + va_end(ap); + ErrorF("\n"); + return; +} + +static void +configFiles(XF86ConfFilesPtr fileconf) +{ + MessageType pathFrom; + Bool must_copy; + int size, countDirs; + char *temp_path, *log_buf, *start, *end; + + /* FontPath */ + must_copy = TRUE; + + temp_path = defaultFontPath ? defaultFontPath : ""; + if (xf86fpFlag) + pathFrom = X_CMDLINE; + else if (fileconf && fileconf->file_fontpath) { + pathFrom = X_CONFIG; + if (xf86Info.useDefaultFontPath) { + if (asprintf(&defaultFontPath, "%s%s%s", fileconf->file_fontpath, + *temp_path ? "," : "", temp_path) == -1) + defaultFontPath = NULL; + else + must_copy = FALSE; + } + else + defaultFontPath = fileconf->file_fontpath; + } + else + pathFrom = X_DEFAULT; + temp_path = defaultFontPath ? defaultFontPath : ""; + + /* xf86ValidateFontPath modifies its argument, but returns a copy of it. */ + temp_path = must_copy ? xnfstrdup(defaultFontPath) : defaultFontPath; + defaultFontPath = xf86ValidateFontPath(temp_path); + free(temp_path); + + /* make fontpath more readable in the logfiles */ + countDirs = 1; + temp_path = defaultFontPath; + while ((temp_path = index(temp_path, ',')) != NULL) { + countDirs++; + temp_path++; + } + + log_buf = xnfalloc(strlen(defaultFontPath) + (2 * countDirs) + 1); + temp_path = log_buf; + start = defaultFontPath; + while((end = index(start, ',')) != NULL) { + size = (end - start) + 1; + *(temp_path++) = '\t'; + strncpy(temp_path, start, size); + temp_path += size; + *(temp_path++) = '\n'; + start += size; + } + /* copy last entry */ + *(temp_path++) = '\t'; + strcpy(temp_path, start); + xf86Msg(pathFrom, "FontPath set to:\n%s\n", log_buf); + free(log_buf); + + /* ModulePath */ + + if (fileconf) { + if (xf86ModPathFrom != X_CMDLINE && fileconf->file_modulepath) { + xf86ModulePath = fileconf->file_modulepath; + xf86ModPathFrom = X_CONFIG; + } + } + + xf86Msg(xf86ModPathFrom, "ModulePath set to \"%s\"\n", xf86ModulePath); + + if (!xf86xkbdirFlag && fileconf && fileconf->file_xkbdir) { + XkbBaseDirectory = fileconf->file_xkbdir; + xf86Msg(X_CONFIG, "XKB base directory set to \"%s\"\n", + XkbBaseDirectory); + } +#if 0 + /* LogFile */ + /* + * XXX The problem with this is that the log file is already open. + * One option might be to copy the exiting contents to the new location. + * and re-open it. The down side is that the default location would + * already have been overwritten. Another option would be to start with + * unique temporary location, then copy it once the correct name is known. + * A problem with this is what happens if the server exits before that + * happens. + */ + if (xf86LogFileFrom == X_DEFAULT && fileconf->file_logfile) { + xf86LogFile = fileconf->file_logfile; + xf86LogFileFrom = X_CONFIG; + } +#endif + + return; +} + +typedef enum { + FLAG_NOTRAPSIGNALS, + FLAG_DONTVTSWITCH, + FLAG_DONTZAP, + FLAG_DONTZOOM, + FLAG_DISABLEVIDMODE, + FLAG_ALLOWNONLOCAL, + FLAG_ALLOWMOUSEOPENFAIL, + FLAG_VTSYSREQ, + FLAG_SAVER_BLANKTIME, + FLAG_DPMS_STANDBYTIME, + FLAG_DPMS_SUSPENDTIME, + FLAG_DPMS_OFFTIME, + FLAG_PIXMAP, + FLAG_PC98, + FLAG_NOPM, + FLAG_XINERAMA, + FLAG_LOG, + FLAG_RENDER_COLORMAP_MODE, + FLAG_RANDR, + FLAG_AIGLX, + FLAG_IGNORE_ABI, + FLAG_ALLOW_EMPTY_INPUT, + FLAG_USE_DEFAULT_FONT_PATH, + FLAG_AUTO_ADD_DEVICES, + FLAG_AUTO_ENABLE_DEVICES, + FLAG_GLX_VISUALS, + FLAG_DRI2, + FLAG_USE_SIGIO +} FlagValues; + +/** + * NOTE: the last value for each entry is NOT the default. It is set to TRUE + * if the parser found the option in the config file. + */ +static OptionInfoRec FlagOptions[] = { + { FLAG_NOTRAPSIGNALS, "NoTrapSignals", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_DONTVTSWITCH, "DontVTSwitch", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_DONTZAP, "DontZap", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_DONTZOOM, "DontZoom", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_DISABLEVIDMODE, "DisableVidModeExtension", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_ALLOWNONLOCAL, "AllowNonLocalXvidtune", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_ALLOWMOUSEOPENFAIL, "AllowMouseOpenFail", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_VTSYSREQ, "VTSysReq", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_SAVER_BLANKTIME, "BlankTime" , OPTV_INTEGER, + {0}, FALSE }, + { FLAG_DPMS_STANDBYTIME, "StandbyTime", OPTV_INTEGER, + {0}, FALSE }, + { FLAG_DPMS_SUSPENDTIME, "SuspendTime", OPTV_INTEGER, + {0}, FALSE }, + { FLAG_DPMS_OFFTIME, "OffTime", OPTV_INTEGER, + {0}, FALSE }, + { FLAG_PIXMAP, "Pixmap", OPTV_INTEGER, + {0}, FALSE }, + { FLAG_PC98, "PC98", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_NOPM, "NoPM", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_XINERAMA, "Xinerama", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_LOG, "Log", OPTV_STRING, + {0}, FALSE }, + { FLAG_RENDER_COLORMAP_MODE, "RenderColormapMode", OPTV_STRING, + {0}, FALSE }, + { FLAG_RANDR, "RandR", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_AIGLX, "AIGLX", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_IGNORE_ABI, "IgnoreABI", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_USE_DEFAULT_FONT_PATH, "UseDefaultFontPath", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_AUTO_ADD_DEVICES, "AutoAddDevices", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_AUTO_ENABLE_DEVICES, "AutoEnableDevices", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_GLX_VISUALS, "GlxVisuals", OPTV_STRING, + {0}, FALSE }, + { FLAG_DRI2, "DRI2", OPTV_BOOLEAN, + {0}, FALSE }, + { FLAG_USE_SIGIO, "UseSIGIO", OPTV_BOOLEAN, + {0}, FALSE }, + { -1, NULL, OPTV_NONE, + {0}, FALSE }, +}; + +#ifdef SUPPORT_PC98 +static Bool +detectPC98(void) +{ + unsigned char buf[2]; + + if (xf86ReadBIOS(0xf8000, 0xe80, buf, 2) != 2) + return FALSE; + if ((buf[0] == 0x98) && (buf[1] == 0x21)) + return TRUE; + else + return FALSE; +} +#endif + +static Bool +configServerFlags(XF86ConfFlagsPtr flagsconf, XF86OptionPtr layoutopts) +{ + XF86OptionPtr optp, tmp; + int i; + Pix24Flags pix24 = Pix24DontCare; + Bool value; + MessageType from; + const char *s; + XkbRMLVOSet set; + /* Default options. */ + set.rules = "base"; + set.model = "pc105"; + set.layout = "us"; + set.variant = NULL; + set.options = NULL; + + /* + * Merge the ServerLayout and ServerFlags options. The former have + * precedence over the latter. + */ + optp = NULL; + if (flagsconf && flagsconf->flg_option_lst) + optp = xf86optionListDup(flagsconf->flg_option_lst); + if (layoutopts) { + tmp = xf86optionListDup(layoutopts); + if (optp) + optp = xf86optionListMerge(optp, tmp); + else + optp = tmp; + } + + xf86ProcessOptions(-1, optp, FlagOptions); + + xf86GetOptValBool(FlagOptions, FLAG_NOTRAPSIGNALS, &xf86Info.notrapSignals); + xf86GetOptValBool(FlagOptions, FLAG_DONTVTSWITCH, &xf86Info.dontVTSwitch); + xf86GetOptValBool(FlagOptions, FLAG_DONTZAP, &xf86Info.dontZap); + xf86GetOptValBool(FlagOptions, FLAG_DONTZOOM, &xf86Info.dontZoom); + + xf86GetOptValBool(FlagOptions, FLAG_IGNORE_ABI, &xf86Info.ignoreABI); + if (xf86Info.ignoreABI) { + xf86Msg(X_CONFIG, "Ignoring ABI Version\n"); + } + + if (xf86SIGIOSupported()) { + xf86Info.useSIGIO = xf86ReturnOptValBool(FlagOptions, FLAG_USE_SIGIO, USE_SIGIO_BY_DEFAULT); + if (xf86IsOptionSet(FlagOptions, FLAG_USE_SIGIO)) { + from = X_CONFIG; + } else { + from = X_DEFAULT; + } + if (!xf86Info.useSIGIO) { + xf86Msg(from, "Disabling SIGIO handlers for input devices\n"); + } else if (from == X_CONFIG) { + xf86Msg(from, "Enabling SIGIO handlers for input devices\n"); + } + } else { + xf86Info.useSIGIO = FALSE; + } + + if (xf86IsOptionSet(FlagOptions, FLAG_AUTO_ADD_DEVICES)) { + xf86GetOptValBool(FlagOptions, FLAG_AUTO_ADD_DEVICES, + &xf86Info.autoAddDevices); + from = X_CONFIG; + } + else { + from = X_DEFAULT; + } + xf86Msg(from, "%sutomatically adding devices\n", + xf86Info.autoAddDevices ? "A" : "Not a"); + + if (xf86IsOptionSet(FlagOptions, FLAG_AUTO_ENABLE_DEVICES)) { + xf86GetOptValBool(FlagOptions, FLAG_AUTO_ENABLE_DEVICES, + &xf86Info.autoEnableDevices); + from = X_CONFIG; + } + else { + from = X_DEFAULT; + } + xf86Msg(from, "%sutomatically enabling devices\n", + xf86Info.autoEnableDevices ? "A" : "Not a"); + + /* + * Set things up based on the config file information. Some of these + * settings may be overridden later when the command line options are + * checked. + */ +#ifdef XF86VIDMODE + if (xf86GetOptValBool(FlagOptions, FLAG_DISABLEVIDMODE, &value)) + xf86Info.vidModeEnabled = !value; + if (xf86GetOptValBool(FlagOptions, FLAG_ALLOWNONLOCAL, &value)) + xf86Info.vidModeAllowNonLocal = value; +#endif + + if (xf86GetOptValBool(FlagOptions, FLAG_ALLOWMOUSEOPENFAIL, &value)) + xf86Info.allowMouseOpenFail = value; + + if (xf86GetOptValBool(FlagOptions, FLAG_VTSYSREQ, &value)) { +#ifdef USE_VT_SYSREQ + xf86Info.vtSysreq = value; + xf86Msg(X_CONFIG, "VTSysReq %s\n", value ? "enabled" : "disabled"); +#else + if (value) + xf86Msg(X_WARNING, "VTSysReq is not supported on this OS\n"); +#endif + } + + xf86Info.pmFlag = TRUE; + if (xf86GetOptValBool(FlagOptions, FLAG_NOPM, &value)) + xf86Info.pmFlag = !value; + { + if ((s = xf86GetOptValString(FlagOptions, FLAG_LOG))) { + if (!xf86NameCmp(s,"flush")) { + xf86Msg(X_CONFIG, "Flushing logfile enabled\n"); + xf86Info.log = LogFlush; + LogSetParameter(XLOG_FLUSH, TRUE); + } else if (!xf86NameCmp(s,"sync")) { + xf86Msg(X_CONFIG, "Syncing logfile enabled\n"); + xf86Info.log = LogSync; + LogSetParameter(XLOG_FLUSH, TRUE); + LogSetParameter(XLOG_SYNC, TRUE); + } else { + xf86Msg(X_WARNING,"Unknown Log option\n"); + } + } + } + + { + if ((s = xf86GetOptValString(FlagOptions, FLAG_RENDER_COLORMAP_MODE))){ + int policy = PictureParseCmapPolicy (s); + if (policy == PictureCmapPolicyInvalid) + xf86Msg(X_WARNING, "Unknown colormap policy \"%s\"\n", s); + else + { + xf86Msg(X_CONFIG, "Render colormap policy set to %s\n", s); + PictureCmapPolicy = policy; + } + } + } + +#ifdef RANDR + xf86Info.disableRandR = FALSE; + xf86Info.randRFrom = X_DEFAULT; + if (xf86GetOptValBool(FlagOptions, FLAG_RANDR, &value)) { + xf86Info.disableRandR = !value; + xf86Info.randRFrom = X_CONFIG; + } +#endif + + xf86Info.aiglx = TRUE; + xf86Info.aiglxFrom = X_DEFAULT; + if (xf86GetOptValBool(FlagOptions, FLAG_AIGLX, &value)) { + xf86Info.aiglx = value; + xf86Info.aiglxFrom = X_CONFIG; + } + +#ifdef GLXEXT + xf86Info.glxVisuals = XF86_GlxVisualsTypical; + xf86Info.glxVisualsFrom = X_DEFAULT; + if ((s = xf86GetOptValString(FlagOptions, FLAG_GLX_VISUALS))) { + if (!xf86NameCmp(s, "minimal")) { + xf86Info.glxVisuals = XF86_GlxVisualsMinimal; + } else if (!xf86NameCmp(s, "typical")) { + xf86Info.glxVisuals = XF86_GlxVisualsTypical; + } else if (!xf86NameCmp(s, "all")) { + xf86Info.glxVisuals = XF86_GlxVisualsAll; + } else { + xf86Msg(X_WARNING,"Unknown GlxVisuals option\n"); + } + } + + if (xf86GetOptValBool(FlagOptions, FLAG_AIGLX, &value)) { + xf86Info.aiglx = value; + xf86Info.aiglxFrom = X_CONFIG; + } +#endif + + /* if we're not hotplugging, force some input devices to exist */ + xf86Info.forceInputDevices = !(xf86Info.autoAddDevices && xf86Info.autoEnableDevices); + + /* when forcing input devices, we use kbd. otherwise evdev, so use the + * evdev rules set. */ +#if defined(linux) + if (!xf86Info.forceInputDevices) + set.rules = "evdev"; +#endif + XkbSetRulesDflts(&set); + + xf86Info.useDefaultFontPath = TRUE; + xf86Info.useDefaultFontPathFrom = X_DEFAULT; + if (xf86GetOptValBool(FlagOptions, FLAG_USE_DEFAULT_FONT_PATH, &value)) { + xf86Info.useDefaultFontPath = value; + xf86Info.useDefaultFontPathFrom = X_CONFIG; + } + +/* Make sure that timers don't overflow CARD32's after multiplying */ +#define MAX_TIME_IN_MIN (0x7fffffff / MILLI_PER_MIN) + + i = -1; + xf86GetOptValInteger(FlagOptions, FLAG_SAVER_BLANKTIME, &i); + if ((i >= 0) && (i < MAX_TIME_IN_MIN)) + ScreenSaverTime = defaultScreenSaverTime = i * MILLI_PER_MIN; + else if (i != -1) + xf86ConfigError("BlankTime value %d outside legal range of 0 - %d minutes", + i, MAX_TIME_IN_MIN); + +#ifdef DPMSExtension + i = -1; + xf86GetOptValInteger(FlagOptions, FLAG_DPMS_STANDBYTIME, &i); + if ((i >= 0) && (i < MAX_TIME_IN_MIN)) + DPMSStandbyTime = i * MILLI_PER_MIN; + else if (i != -1) + xf86ConfigError("StandbyTime value %d outside legal range of 0 - %d minutes", + i, MAX_TIME_IN_MIN); + i = -1; + xf86GetOptValInteger(FlagOptions, FLAG_DPMS_SUSPENDTIME, &i); + if ((i >= 0) && (i < MAX_TIME_IN_MIN)) + DPMSSuspendTime = i * MILLI_PER_MIN; + else if (i != -1) + xf86ConfigError("SuspendTime value %d outside legal range of 0 - %d minutes", + i, MAX_TIME_IN_MIN); + i = -1; + xf86GetOptValInteger(FlagOptions, FLAG_DPMS_OFFTIME, &i); + if ((i >= 0) && (i < MAX_TIME_IN_MIN)) + DPMSOffTime = i * MILLI_PER_MIN; + else if (i != -1) + xf86ConfigError("OffTime value %d outside legal range of 0 - %d minutes", + i, MAX_TIME_IN_MIN); +#endif + + i = -1; + xf86GetOptValInteger(FlagOptions, FLAG_PIXMAP, &i); + switch (i) { + case 24: + pix24 = Pix24Use24; + break; + case 32: + pix24 = Pix24Use32; + break; + case -1: + break; + default: + xf86ConfigError("Pixmap option's value (%d) must be 24 or 32\n", i); + return FALSE; + } + if (xf86Pix24 != Pix24DontCare) { + xf86Info.pixmap24 = xf86Pix24; + xf86Info.pix24From = X_CMDLINE; + } else if (pix24 != Pix24DontCare) { + xf86Info.pixmap24 = pix24; + xf86Info.pix24From = X_CONFIG; + } else { + xf86Info.pixmap24 = Pix24DontCare; + xf86Info.pix24From = X_DEFAULT; + } +#ifdef SUPPORT_PC98 + if (xf86GetOptValBool(FlagOptions, FLAG_PC98, &value)) { + xf86Info.pc98 = value; + if (value) { + xf86Msg(X_CONFIG, "Japanese PC98 architecture\n"); + } + } else + if (detectPC98()) { + xf86Info.pc98 = TRUE; + xf86Msg(X_PROBED, "Japanese PC98 architecture\n"); + } +#endif + +#ifdef PANORAMIX + from = X_DEFAULT; + if (!noPanoramiXExtension) + from = X_CMDLINE; + else if (xf86GetOptValBool(FlagOptions, FLAG_XINERAMA, &value)) { + noPanoramiXExtension = !value; + from = X_CONFIG; + } + if (!noPanoramiXExtension) + xf86Msg(from, "Xinerama: enabled\n"); +#endif + +#ifdef DRI2 + xf86Info.dri2 = FALSE; + xf86Info.dri2From = X_DEFAULT; + if (xf86GetOptValBool(FlagOptions, FLAG_DRI2, &value)) { + xf86Info.dri2 = value; + xf86Info.dri2From = X_CONFIG; + } +#endif + + return TRUE; +} + +Bool xf86DRI2Enabled(void) +{ + return xf86Info.dri2; +} + +/* + * Locate the core input devices. These can be specified/located in + * the following ways, in order of priority: + * + * 1. The InputDevices named by the -pointer and -keyboard command line + * options. + * 2. The "CorePointer" and "CoreKeyboard" InputDevices referred to by + * the active ServerLayout. + * 3. The first InputDevices marked as "CorePointer" and "CoreKeyboard". + * 4. The first InputDevices that use 'keyboard' or 'kbd' and a valid mouse + * driver (mouse, synaptics, evdev, vmmouse, void) + * 5. Default devices with an empty (default) configuration. These defaults + * will reference the 'mouse' and 'keyboard' drivers. + */ + +static Bool +checkCoreInputDevices(serverLayoutPtr servlayoutp, Bool implicitLayout) +{ + InputInfoPtr corePointer = NULL, coreKeyboard = NULL; + Bool foundPointer = FALSE, foundKeyboard = FALSE; + const char *pointerMsg = NULL, *keyboardMsg = NULL; + InputInfoPtr *devs, /* iterator */ + indp; + InputInfoRec Pointer = {}, Keyboard = {}; + XF86ConfInputPtr confInput; + XF86ConfInputRec defPtr, defKbd; + int count = 0; + MessageType from = X_DEFAULT; + int found = 0; + const char *mousedrivers[] = { "mouse", "synaptics", "evdev", "vmmouse", + "void", NULL }; + + /* + * First check if a core pointer or core keyboard have been specified + * in the active ServerLayout. If more than one is specified for either, + * remove the core attribute from the later ones. + */ + for (devs = servlayoutp->inputs; devs && *devs; devs++) { + indp = *devs; + if (indp->options && + xf86CheckBoolOption(indp->options, "CorePointer", FALSE)) { + if (!corePointer) { + corePointer = indp; + } else { + xf86ReplaceBoolOption(indp->options, "CorePointer", FALSE); + xf86Msg(X_WARNING, "Duplicate core pointer devices. " + "Removing core pointer attribute from \"%s\"\n", + indp->name); + } + } + if (indp->options && + xf86CheckBoolOption(indp->options, "CoreKeyboard", FALSE)) { + if (!coreKeyboard) { + coreKeyboard = indp; + } else { + xf86ReplaceBoolOption(indp->options, "CoreKeyboard", FALSE); + xf86Msg(X_WARNING, "Duplicate core keyboard devices. " + "Removing core keyboard attribute from \"%s\"\n", + indp->name); + } + } + count++; + } + + confInput = NULL; + + /* 1. Check for the -pointer command line option. */ + if (xf86PointerName) { + confInput = xf86findInput(xf86PointerName, + xf86configptr->conf_input_lst); + if (!confInput) { + xf86Msg(X_ERROR, "No InputDevice section called \"%s\"\n", + xf86PointerName); + return FALSE; + } + from = X_CMDLINE; + /* + * If one was already specified in the ServerLayout, it needs to be + * removed. + */ + if (corePointer) { + for (devs = servlayoutp->inputs; devs && *devs; devs++) + if (*devs == corePointer) + { + free(*devs); + *devs = (InputInfoPtr)0x1; /* ensure we dont skip next loop*/ + break; + } + for (; devs && *devs; devs++) + devs[0] = devs[1]; + count--; + } + corePointer = NULL; + foundPointer = TRUE; + } + + /* 2. ServerLayout-specified core pointer. */ + if (corePointer) { + foundPointer = TRUE; + from = X_CONFIG; + } + + /* 3. First core pointer device. */ + if (!foundPointer && (xf86Info.forceInputDevices || implicitLayout)) { + XF86ConfInputPtr p; + + for (p = xf86configptr->conf_input_lst; p; p = p->list.next) { + if (p->inp_option_lst && + xf86CheckBoolOption(p->inp_option_lst, "CorePointer", FALSE)) { + confInput = p; + foundPointer = TRUE; + from = X_DEFAULT; + pointerMsg = "first core pointer device"; + break; + } + } + } + + /* 4. First pointer with an allowed mouse driver. */ + if (!foundPointer && xf86Info.forceInputDevices) { + const char **driver = mousedrivers; + confInput = xf86findInput(CONF_IMPLICIT_POINTER, + xf86configptr->conf_input_lst); + while (*driver && !confInput) { + confInput = xf86findInputByDriver(*driver, + xf86configptr->conf_input_lst); + driver++; + } + if (confInput) { + foundPointer = TRUE; + from = X_DEFAULT; + pointerMsg = "first mouse device"; + } + } + + /* 5. Built-in default. */ + if (!foundPointer && xf86Info.forceInputDevices) { + memset(&defPtr, 0, sizeof(defPtr)); + defPtr.inp_identifier = strdup("<default pointer>"); + defPtr.inp_driver = strdup("mouse"); + confInput = &defPtr; + foundPointer = TRUE; + from = X_DEFAULT; + pointerMsg = "default mouse configuration"; + } + + /* Add the core pointer device to the layout, and set it to Core. */ + if (foundPointer && confInput) { + foundPointer = configInput(&Pointer, confInput, from); + if (foundPointer) { + count++; + 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, + xnfstrdup("CorePointer"), NULL); + devs[count] = NULL; + servlayoutp->inputs = devs; + } + } + + if (!foundPointer && xf86Info.forceInputDevices) { + /* This shouldn't happen. */ + xf86Msg(X_ERROR, "Cannot locate a core pointer device.\n"); + return FALSE; + } + + /* + * always synthesize a 'mouse' section configured to send core + * events, unless a 'void' section is found, in which case the user + * probably wants to run footless. + * + * If you're using an evdev keyboard and expect a default mouse + * section ... deal. + */ + for (devs = servlayoutp->inputs; devs && *devs; devs++) { + const char **driver = mousedrivers; + while(*driver) { + if (!strcmp((*devs)->driver, *driver)) { + found = 1; + break; + } + driver++; + } + } + if (!found && xf86Info.forceInputDevices) { + xf86Msg(X_INFO, "No default mouse found, adding one\n"); + memset(&defPtr, 0, sizeof(defPtr)); + defPtr.inp_identifier = strdup("<default pointer>"); + defPtr.inp_driver = strdup("mouse"); + confInput = &defPtr; + foundPointer = configInput(&Pointer, confInput, from); + if (foundPointer) { + count++; + 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); + devs[count] = NULL; + servlayoutp->inputs = devs; + } + } + + confInput = NULL; + + /* 1. Check for the -keyboard command line option. */ + if (xf86KeyboardName) { + confInput = xf86findInput(xf86KeyboardName, + xf86configptr->conf_input_lst); + if (!confInput) { + xf86Msg(X_ERROR, "No InputDevice section called \"%s\"\n", + xf86KeyboardName); + return FALSE; + } + from = X_CMDLINE; + /* + * If one was already specified in the ServerLayout, it needs to be + * removed. + */ + if (coreKeyboard) { + for (devs = servlayoutp->inputs; devs && *devs; devs++) + if (*devs == coreKeyboard) + { + free(*devs); + *devs = (InputInfoPtr)0x1; /* ensure we dont skip next loop */ + break; + } + for (; devs && *devs; devs++) + devs[0] = devs[1]; + count--; + } + coreKeyboard = NULL; + foundKeyboard = TRUE; + } + + /* 2. ServerLayout-specified core keyboard. */ + if (coreKeyboard) { + foundKeyboard = TRUE; + from = X_CONFIG; + } + + /* 3. First core keyboard device. */ + if (!foundKeyboard && (xf86Info.forceInputDevices || implicitLayout)) { + XF86ConfInputPtr p; + + for (p = xf86configptr->conf_input_lst; p; p = p->list.next) { + if (p->inp_option_lst && + xf86CheckBoolOption(p->inp_option_lst, "CoreKeyboard", FALSE)) { + confInput = p; + foundKeyboard = TRUE; + from = X_DEFAULT; + keyboardMsg = "first core keyboard device"; + break; + } + } + } + + /* 4. First keyboard with 'keyboard' or 'kbd' as the driver. */ + if (!foundKeyboard && xf86Info.forceInputDevices) { + confInput = xf86findInput(CONF_IMPLICIT_KEYBOARD, + xf86configptr->conf_input_lst); + if (!confInput) { + confInput = xf86findInputByDriver("kbd", + xf86configptr->conf_input_lst); + } + if (confInput) { + foundKeyboard = TRUE; + from = X_DEFAULT; + keyboardMsg = "first keyboard device"; + } + } + + /* 5. Built-in default. */ + if (!foundKeyboard && xf86Info.forceInputDevices) { + memset(&defKbd, 0, sizeof(defKbd)); + defKbd.inp_identifier = strdup("<default keyboard>"); + defKbd.inp_driver = strdup("kbd"); + confInput = &defKbd; + foundKeyboard = TRUE; + keyboardMsg = "default keyboard configuration"; + from = X_DEFAULT; + } + + /* Add the core keyboard device to the layout, and set it to Core. */ + if (foundKeyboard && confInput) { + foundKeyboard = configInput(&Keyboard, confInput, from); + if (foundKeyboard) { + count++; + 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, + xnfstrdup("CoreKeyboard"), NULL); + devs[count] = NULL; + servlayoutp->inputs = devs; + } + } + + if (!foundKeyboard && xf86Info.forceInputDevices) { + /* This shouldn't happen. */ + xf86Msg(X_ERROR, "Cannot locate a core keyboard device.\n"); + return FALSE; + } + + if (pointerMsg) { + if (implicitLayout) + xf86Msg(X_DEFAULT, "No Layout section. Using the %s.\n", + pointerMsg); + else + xf86Msg(X_DEFAULT, "The core pointer device wasn't specified " + "explicitly in the layout.\n" + "\tUsing the %s.\n", pointerMsg); + } + + if (keyboardMsg) { + if (implicitLayout) + xf86Msg(X_DEFAULT, "No Layout section. Using the %s.\n", + keyboardMsg); + else + xf86Msg(X_DEFAULT, "The core keyboard device wasn't specified " + "explicitly in the layout.\n" + "\tUsing the %s.\n", keyboardMsg); + } + + if (!xf86Info.forceInputDevices && !(foundPointer && foundKeyboard)) { +#if defined(CONFIG_HAL) || defined(CONFIG_UDEV) + const char *config_backend; +#if defined(CONFIG_HAL) + config_backend = "HAL"; +#else + config_backend = "udev"; +#endif + xf86Msg(X_INFO, "The server relies on %s to provide the list of " + "input devices.\n\tIf no devices become available, " + "reconfigure %s or disable AutoAddDevices.\n", + config_backend, config_backend); +#else + xf86Msg(X_WARNING, "Hotplugging requested but the server was " + "compiled without a config backend. " + "No input devices were configured, the server " + "will start without any input devices.\n"); +#endif + } + + return TRUE; +} + +typedef enum { + LAYOUT_ISOLATEDEVICE, + LAYOUT_SINGLECARD +} LayoutValues; + +static OptionInfoRec LayoutOptions[] = { + { LAYOUT_ISOLATEDEVICE, "IsolateDevice", OPTV_STRING, + {0}, FALSE }, + { LAYOUT_SINGLECARD, "SingleCard", OPTV_BOOLEAN, + {0}, FALSE }, + { -1, NULL, OPTV_NONE, + {0}, FALSE }, +}; + +static Bool +configInputDevices(XF86ConfLayoutPtr layout, serverLayoutPtr servlayoutp) +{ + XF86ConfInputrefPtr irp; + InputInfoPtr *indp; + int count = 0; + + /* + * Count the number of input devices. + */ + irp = layout->lay_input_lst; + while (irp) { + count++; + irp = (XF86ConfInputrefPtr)irp->list.next; + } + DebugF("Found %d input devices in the layout section %s\n", + count, layout->lay_identifier); + indp = xnfcalloc((count + 1), sizeof(InputInfoPtr)); + indp[count] = NULL; + irp = layout->lay_input_lst; + count = 0; + while (irp) { + indp[count] = xf86AllocateInput(); + if (!configInput(indp[count], irp->iref_inputdev, X_CONFIG)) { + do { + free(indp[count]); + } while(count--); + free(indp); + return FALSE; + } + indp[count]->options = xf86OptionListMerge(indp[count]->options, + irp->iref_option_lst); + count++; + irp = (XF86ConfInputrefPtr)irp->list.next; + } + servlayoutp->inputs = indp; + + return TRUE; +} + + +/* + * figure out which layout is active, which screens are used in that layout, + * which drivers and monitors are used in these screens + */ +static Bool +configLayout(serverLayoutPtr servlayoutp, XF86ConfLayoutPtr conf_layout, + char *default_layout) +{ + XF86ConfAdjacencyPtr adjp; + XF86ConfInactivePtr idp; + int saved_count, count = 0; + int scrnum; + XF86ConfLayoutPtr l; + MessageType from; + screenLayoutPtr slp; + GDevPtr gdp; + int i = 0, j; + + if (!servlayoutp) + return FALSE; + + /* + * which layout section is the active one? + * + * If there is a -layout command line option, use that one, otherwise + * pick the first one. + */ + from = X_DEFAULT; + if (xf86LayoutName != NULL) + from = X_CMDLINE; + else if (default_layout) { + xf86LayoutName = default_layout; + from = X_CONFIG; + } + if (xf86LayoutName != NULL) { + if ((l = xf86findLayout(xf86LayoutName, conf_layout)) == NULL) { + xf86Msg(X_ERROR, "No ServerLayout section called \"%s\"\n", + xf86LayoutName); + return FALSE; + } + conf_layout = l; + } + xf86Msg(from, "ServerLayout \"%s\"\n", conf_layout->lay_identifier); + adjp = conf_layout->lay_adjacency_lst; + + /* + * we know that each screen is referenced exactly once on the left side + * of a layout statement in the Layout section. So to allocate the right + * size for the array we do a quick walk of the list to figure out how + * many sections we have + */ + while (adjp) { + count++; + adjp = (XF86ConfAdjacencyPtr)adjp->list.next; + } + + DebugF("Found %d screens in the layout section %s", + count, conf_layout->lay_identifier); + if (!count) /* alloc enough storage even if no screen is specified */ + count = 1; + + slp = xnfcalloc(1, (count + 1) * sizeof(screenLayoutRec)); + slp[count].screen = NULL; + /* + * now that we have storage, loop over the list again and fill in our + * data structure; at this point we do not fill in the adjacency + * information as it is not clear if we need it at all + */ + adjp = conf_layout->lay_adjacency_lst; + count = 0; + while (adjp) { + slp[count].screen = xnfcalloc(1, sizeof(confScreenRec)); + if (adjp->adj_scrnum < 0) + scrnum = count; + else + scrnum = adjp->adj_scrnum; + if (!configScreen(slp[count].screen, adjp->adj_screen, scrnum, + X_CONFIG)) { + do { + free(slp[count].screen); + } while(count--); + free(slp); + return FALSE; + } + slp[count].x = adjp->adj_x; + slp[count].y = adjp->adj_y; + slp[count].refname = adjp->adj_refscreen; + switch (adjp->adj_where) { + case CONF_ADJ_OBSOLETE: + slp[count].where = PosObsolete; + slp[count].topname = adjp->adj_top_str; + slp[count].bottomname = adjp->adj_bottom_str; + slp[count].leftname = adjp->adj_left_str; + slp[count].rightname = adjp->adj_right_str; + break; + case CONF_ADJ_ABSOLUTE: + slp[count].where = PosAbsolute; + break; + case CONF_ADJ_RIGHTOF: + slp[count].where = PosRightOf; + break; + case CONF_ADJ_LEFTOF: + slp[count].where = PosLeftOf; + break; + case CONF_ADJ_ABOVE: + slp[count].where = PosAbove; + break; + case CONF_ADJ_BELOW: + slp[count].where = PosBelow; + break; + case CONF_ADJ_RELATIVE: + slp[count].where = PosRelative; + break; + } + count++; + adjp = (XF86ConfAdjacencyPtr)adjp->list.next; + } + + /* No screen was specified in the layout. take the first one from the + * config file, or - if it is NULL - configScreen autogenerates one for + * us */ + if (!count) + { + slp[0].screen = xnfcalloc(1, sizeof(confScreenRec)); + if (!configScreen(slp[0].screen, xf86configptr->conf_screen_lst, + 0, X_CONFIG)) { + free(slp[0].screen); + free(slp); + return FALSE; + } + } + + /* XXX Need to tie down the upper left screen. */ + + /* Fill in the refscreen and top/bottom/left/right values */ + for (i = 0; i < count; i++) { + for (j = 0; j < count; j++) { + if (slp[i].refname && + strcmp(slp[i].refname, slp[j].screen->id) == 0) { + slp[i].refscreen = slp[j].screen; + } + if (slp[i].topname && + strcmp(slp[i].topname, slp[j].screen->id) == 0) { + slp[i].top = slp[j].screen; + } + if (slp[i].bottomname && + strcmp(slp[i].bottomname, slp[j].screen->id) == 0) { + slp[i].bottom = slp[j].screen; + } + if (slp[i].leftname && + strcmp(slp[i].leftname, slp[j].screen->id) == 0) { + slp[i].left = slp[j].screen; + } + if (slp[i].rightname && + strcmp(slp[i].rightname, slp[j].screen->id) == 0) { + slp[i].right = slp[j].screen; + } + } + if (slp[i].where != PosObsolete + && slp[i].where != PosAbsolute + && !slp[i].refscreen) { + xf86Msg(X_ERROR,"Screen %s doesn't exist: deleting placement\n", + slp[i].refname); + slp[i].where = PosAbsolute; + slp[i].x = 0; + slp[i].y = 0; + } + } + + if (!count) + saved_count = 1; + else + saved_count = count; + /* + * Count the number of inactive devices. + */ + count = 0; + idp = conf_layout->lay_inactive_lst; + while (idp) { + count++; + idp = (XF86ConfInactivePtr)idp->list.next; + } + DebugF("Found %d inactive devices in the layout section %s\n", + count, conf_layout->lay_identifier); + gdp = xnfalloc((count + 1) * sizeof(GDevRec)); + gdp[count].identifier = NULL; + idp = conf_layout->lay_inactive_lst; + count = 0; + while (idp) { + if (!configDevice(&gdp[count], idp->inactive_device, FALSE)) + goto bail; + count++; + idp = (XF86ConfInactivePtr)idp->list.next; + } + + if (!configInputDevices(conf_layout, servlayoutp)) + goto bail; + + servlayoutp->id = conf_layout->lay_identifier; + servlayoutp->screens = slp; + servlayoutp->inactives = gdp; + servlayoutp->options = conf_layout->lay_option_lst; + from = X_DEFAULT; + + return TRUE; + +bail: + do { + free(slp[saved_count].screen); + } while(saved_count--); + free(slp); + free(gdp); + return FALSE; +} + +/* + * No layout section, so find the first Screen section and set that up as + * the only active screen. + */ +static Bool +configImpliedLayout(serverLayoutPtr servlayoutp, XF86ConfScreenPtr conf_screen, + XF86ConfigPtr xf86configptr) +{ + MessageType from; + XF86ConfScreenPtr s; + screenLayoutPtr slp; + InputInfoPtr *indp; + XF86ConfLayoutRec layout; + + if (!servlayoutp) + return FALSE; + + /* + * which screen section is the active one? + * + * If there is a -screen option, use that one, otherwise use the first + * one. + */ + + from = X_CONFIG; + if (xf86ScreenName != NULL) { + if ((s = xf86findScreen(xf86ScreenName, conf_screen)) == NULL) { + xf86Msg(X_ERROR, "No Screen section called \"%s\"\n", + xf86ScreenName); + return FALSE; + } + conf_screen = s; + from = X_CMDLINE; + } + + /* We have exactly one screen */ + + slp = xnfcalloc(1, 2 * sizeof(screenLayoutRec)); + slp[0].screen = xnfcalloc(1, sizeof(confScreenRec)); + slp[1].screen = NULL; + if (!configScreen(slp[0].screen, conf_screen, 0, from)) { + free(slp); + return FALSE; + } + servlayoutp->id = "(implicit)"; + servlayoutp->screens = slp; + servlayoutp->inactives = xnfcalloc(1, sizeof(GDevRec)); + servlayoutp->options = NULL; + + memset(&layout, 0, sizeof(layout)); + layout.lay_identifier = servlayoutp->id; + if (xf86layoutAddInputDevices(xf86configptr, &layout) > 0) { + if (!configInputDevices(&layout, servlayoutp)) + return FALSE; + from = X_DEFAULT; + } else { + /* Set up an empty input device list, then look for some core devices. */ + indp = xnfalloc(sizeof(InputInfoPtr)); + *indp = NULL; + servlayoutp->inputs = indp; + } + + return TRUE; +} + +static Bool +configXvAdaptor(confXvAdaptorPtr adaptor, XF86ConfVideoAdaptorPtr conf_adaptor) +{ + int count = 0; + XF86ConfVideoPortPtr conf_port; + + xf86Msg(X_CONFIG, "| |-->VideoAdaptor \"%s\"\n", + conf_adaptor->va_identifier); + adaptor->identifier = conf_adaptor->va_identifier; + adaptor->options = conf_adaptor->va_option_lst; + if (conf_adaptor->va_busid || conf_adaptor->va_driver) { + xf86Msg(X_CONFIG, "| | Unsupported device type, skipping entry\n"); + return FALSE; + } + + /* + * figure out how many videoport subsections there are and fill them in + */ + conf_port = conf_adaptor->va_port_lst; + while(conf_port) { + count++; + conf_port = (XF86ConfVideoPortPtr)conf_port->list.next; + } + adaptor->ports = xnfalloc((count) * sizeof(confXvPortRec)); + adaptor->numports = count; + count = 0; + conf_port = conf_adaptor->va_port_lst; + while(conf_port) { + adaptor->ports[count].identifier = conf_port->vp_identifier; + adaptor->ports[count].options = conf_port->vp_option_lst; + count++; + conf_port = (XF86ConfVideoPortPtr)conf_port->list.next; + } + + return TRUE; +} + +static Bool +configScreen(confScreenPtr screenp, XF86ConfScreenPtr conf_screen, int scrnum, + MessageType from) +{ + int count = 0; + XF86ConfDisplayPtr dispptr; + XF86ConfAdaptorLinkPtr conf_adaptor; + Bool defaultMonitor = FALSE; + XF86ConfScreenRec local_conf_screen; + + if (!conf_screen) { + memset(&local_conf_screen, 0, sizeof(local_conf_screen)); + conf_screen = &local_conf_screen; + conf_screen->scrn_identifier = "Default Screen Section"; + xf86Msg(X_DEFAULT, "No screen section available. Using defaults.\n"); + } + + xf86Msg(from, "|-->Screen \"%s\" (%d)\n", conf_screen->scrn_identifier, + scrnum); + /* + * now we fill in the elements of the screen + */ + screenp->id = conf_screen->scrn_identifier; + screenp->screennum = scrnum; + screenp->defaultdepth = conf_screen->scrn_defaultdepth; + screenp->defaultbpp = conf_screen->scrn_defaultbpp; + screenp->defaultfbbpp = conf_screen->scrn_defaultfbbpp; + screenp->monitor = xnfcalloc(1, sizeof(MonRec)); + /* If no monitor is specified, create a default one. */ + if (!conf_screen->scrn_monitor) { + XF86ConfMonitorRec defMon; + + memset(&defMon, 0, sizeof(defMon)); + defMon.mon_identifier = "<default monitor>"; + if (!configMonitor(screenp->monitor, &defMon)) + return FALSE; + defaultMonitor = TRUE; + } else { + if (!configMonitor(screenp->monitor,conf_screen->scrn_monitor)) + return FALSE; + } + /* Configure the device. If there isn't one configured, attach to the + * first inactive one that we can configure. If there's none that work, + * set it to NULL so that the section can be autoconfigured later */ + screenp->device = xnfcalloc(1, sizeof(GDevRec)); + if ((!conf_screen->scrn_device) && (xf86configptr->conf_device_lst)) { + conf_screen->scrn_device = xf86configptr->conf_device_lst; + xf86Msg(X_DEFAULT, "No device specified for screen \"%s\".\n" + "\tUsing the first device section listed.\n", screenp->id); + } + if (configDevice(screenp->device,conf_screen->scrn_device, TRUE)) { + screenp->device->myScreenSection = screenp; + } else { + screenp->device = NULL; + } + screenp->options = conf_screen->scrn_option_lst; + + /* + * figure out how many display subsections there are and fill them in + */ + dispptr = conf_screen->scrn_display_lst; + while(dispptr) { + count++; + dispptr = (XF86ConfDisplayPtr)dispptr->list.next; + } + screenp->displays = xnfalloc((count) * sizeof(DispRec)); + screenp->numdisplays = count; + + /* Fill in the default Virtual size, if any */ + if (conf_screen->scrn_virtualX && conf_screen->scrn_virtualY) { + for (count = 0, dispptr = conf_screen->scrn_display_lst; + dispptr; + dispptr = (XF86ConfDisplayPtr)dispptr->list.next, count++) { + screenp->displays[count].virtualX = conf_screen->scrn_virtualX; + screenp->displays[count].virtualY = conf_screen->scrn_virtualY; + } + } + + /* Now do the per-Display Virtual sizes */ + count = 0; + dispptr = conf_screen->scrn_display_lst; + while(dispptr) { + configDisplay(&(screenp->displays[count]),dispptr); + count++; + dispptr = (XF86ConfDisplayPtr)dispptr->list.next; + } + + /* + * figure out how many videoadaptor references there are and fill them in + */ + conf_adaptor = conf_screen->scrn_adaptor_lst; + while(conf_adaptor) { + count++; + conf_adaptor = (XF86ConfAdaptorLinkPtr)conf_adaptor->list.next; + } + screenp->xvadaptors = xnfalloc((count) * sizeof(confXvAdaptorRec)); + screenp->numxvadaptors = 0; + conf_adaptor = conf_screen->scrn_adaptor_lst; + while(conf_adaptor) { + if (configXvAdaptor(&(screenp->xvadaptors[screenp->numxvadaptors]), + conf_adaptor->al_adaptor)) + screenp->numxvadaptors++; + conf_adaptor = (XF86ConfAdaptorLinkPtr)conf_adaptor->list.next; + } + + if (defaultMonitor) { + xf86Msg(X_DEFAULT, "No monitor specified for screen \"%s\".\n" + "\tUsing a default monitor configuration.\n", screenp->id); + } + return TRUE; +} + +typedef enum { + MON_REDUCEDBLANKING, + MON_MAX_PIX_CLOCK, +} MonitorValues; + +static OptionInfoRec MonitorOptions[] = { + { MON_REDUCEDBLANKING, "ReducedBlanking", OPTV_BOOLEAN, + {0}, FALSE }, + { MON_MAX_PIX_CLOCK, "MaxPixClock", OPTV_FREQ, + {0}, FALSE }, + { -1, NULL, OPTV_NONE, + {0}, FALSE }, +}; + +static Bool +configMonitor(MonPtr monitorp, XF86ConfMonitorPtr conf_monitor) +{ + int count; + DisplayModePtr mode,last = NULL; + XF86ConfModeLinePtr cmodep; + XF86ConfModesPtr modes; + XF86ConfModesLinkPtr modeslnk = conf_monitor->mon_modes_sect_lst; + Gamma zeros = {0.0, 0.0, 0.0}; + float badgamma = 0.0; + double maxPixClock; + + xf86Msg(X_CONFIG, "| |-->Monitor \"%s\"\n", + conf_monitor->mon_identifier); + monitorp->id = conf_monitor->mon_identifier; + monitorp->vendor = conf_monitor->mon_vendor; + monitorp->model = conf_monitor->mon_modelname; + monitorp->Modes = NULL; + monitorp->Last = NULL; + monitorp->gamma = zeros; + monitorp->widthmm = conf_monitor->mon_width; + monitorp->heightmm = conf_monitor->mon_height; + monitorp->reducedblanking = FALSE; + monitorp->maxPixClock = 0; + monitorp->options = conf_monitor->mon_option_lst; + + /* + * fill in the monitor structure + */ + for( count = 0 ; + count < conf_monitor->mon_n_hsync && count < MAX_HSYNC; + count++) { + monitorp->hsync[count].hi = conf_monitor->mon_hsync[count].hi; + monitorp->hsync[count].lo = conf_monitor->mon_hsync[count].lo; + } + monitorp->nHsync = count; + for( count = 0 ; + count < conf_monitor->mon_n_vrefresh && count < MAX_VREFRESH; + count++) { + monitorp->vrefresh[count].hi = conf_monitor->mon_vrefresh[count].hi; + monitorp->vrefresh[count].lo = conf_monitor->mon_vrefresh[count].lo; + } + monitorp->nVrefresh = count; + + /* + * first we collect the mode lines from the UseModes directive + */ + while(modeslnk) + { + modes = xf86findModes (modeslnk->ml_modes_str, + xf86configptr->conf_modes_lst); + modeslnk->ml_modes = modes; + + + /* now add the modes found in the modes + section to the list of modes for this + monitor unless it has been added before + because we are reusing the same section + for another screen */ + if (xf86itemNotSublist( + (GenericListPtr)conf_monitor->mon_modeline_lst, + (GenericListPtr)modes->mon_modeline_lst)) { + conf_monitor->mon_modeline_lst = (XF86ConfModeLinePtr) + xf86addListItem( + (GenericListPtr)conf_monitor->mon_modeline_lst, + (GenericListPtr)modes->mon_modeline_lst); + } + modeslnk = modeslnk->list.next; + } + + /* + * we need to hook in the mode lines now + * here both data structures use lists, only our internal one + * is double linked + */ + cmodep = conf_monitor->mon_modeline_lst; + while( cmodep ) { + mode = xnfcalloc(1, sizeof(DisplayModeRec)); + mode->type = 0; + mode->Clock = cmodep->ml_clock; + mode->HDisplay = cmodep->ml_hdisplay; + mode->HSyncStart = cmodep->ml_hsyncstart; + mode->HSyncEnd = cmodep->ml_hsyncend; + mode->HTotal = cmodep->ml_htotal; + mode->VDisplay = cmodep->ml_vdisplay; + mode->VSyncStart = cmodep->ml_vsyncstart; + mode->VSyncEnd = cmodep->ml_vsyncend; + mode->VTotal = cmodep->ml_vtotal; + mode->Flags = cmodep->ml_flags; + mode->HSkew = cmodep->ml_hskew; + mode->VScan = cmodep->ml_vscan; + mode->name = xnfstrdup(cmodep->ml_identifier); + if( last ) { + mode->prev = last; + last->next = mode; + } + else { + /* + * this is the first mode + */ + monitorp->Modes = mode; + mode->prev = NULL; + } + last = mode; + cmodep = (XF86ConfModeLinePtr)cmodep->list.next; + } + if(last){ + last->next = NULL; + } + monitorp->Last = last; + + /* add the (VESA) default modes */ + if (! addDefaultModes(monitorp) ) + return FALSE; + + if (conf_monitor->mon_gamma_red > GAMMA_ZERO) + monitorp->gamma.red = conf_monitor->mon_gamma_red; + if (conf_monitor->mon_gamma_green > GAMMA_ZERO) + monitorp->gamma.green = conf_monitor->mon_gamma_green; + if (conf_monitor->mon_gamma_blue > GAMMA_ZERO) + monitorp->gamma.blue = conf_monitor->mon_gamma_blue; + + /* Check that the gamma values are within range */ + if (monitorp->gamma.red > GAMMA_ZERO && + (monitorp->gamma.red < GAMMA_MIN || + monitorp->gamma.red > GAMMA_MAX)) { + badgamma = monitorp->gamma.red; + } else if (monitorp->gamma.green > GAMMA_ZERO && + (monitorp->gamma.green < GAMMA_MIN || + monitorp->gamma.green > GAMMA_MAX)) { + badgamma = monitorp->gamma.green; + } else if (monitorp->gamma.blue > GAMMA_ZERO && + (monitorp->gamma.blue < GAMMA_MIN || + monitorp->gamma.blue > GAMMA_MAX)) { + badgamma = monitorp->gamma.blue; + } + if (badgamma > GAMMA_ZERO) { + xf86ConfigError("Gamma value %.f is out of range (%.2f - %.1f)\n", + badgamma, GAMMA_MIN, GAMMA_MAX); + return FALSE; + } + + xf86ProcessOptions(-1, monitorp->options, MonitorOptions); + xf86GetOptValBool(MonitorOptions, MON_REDUCEDBLANKING, + &monitorp->reducedblanking); + if (xf86GetOptValFreq(MonitorOptions, MON_MAX_PIX_CLOCK, OPTUNITS_KHZ, + &maxPixClock) == TRUE) { + monitorp->maxPixClock = (int) maxPixClock; + } + + return TRUE; +} + +static int +lookupVisual(const char *visname) +{ + int i; + + if (!visname || !*visname) + return -1; + + for (i = 0; i <= DirectColor; i++) { + if (!xf86nameCompare(visname, xf86VisualNames[i])) + break; + } + + if (i <= DirectColor) + return i; + + return -1; +} + + +static Bool +configDisplay(DispPtr displayp, XF86ConfDisplayPtr conf_display) +{ + int count = 0; + XF86ModePtr modep; + + displayp->frameX0 = conf_display->disp_frameX0; + displayp->frameY0 = conf_display->disp_frameY0; + displayp->virtualX = conf_display->disp_virtualX; + displayp->virtualY = conf_display->disp_virtualY; + displayp->depth = conf_display->disp_depth; + displayp->fbbpp = conf_display->disp_bpp; + displayp->weight.red = conf_display->disp_weight.red; + displayp->weight.green = conf_display->disp_weight.green; + displayp->weight.blue = conf_display->disp_weight.blue; + displayp->blackColour.red = conf_display->disp_black.red; + displayp->blackColour.green = conf_display->disp_black.green; + displayp->blackColour.blue = conf_display->disp_black.blue; + displayp->whiteColour.red = conf_display->disp_white.red; + displayp->whiteColour.green = conf_display->disp_white.green; + displayp->whiteColour.blue = conf_display->disp_white.blue; + displayp->options = conf_display->disp_option_lst; + if (conf_display->disp_visual) { + displayp->defaultVisual = lookupVisual(conf_display->disp_visual); + if (displayp->defaultVisual == -1) { + xf86ConfigError("Invalid visual name: \"%s\"", + conf_display->disp_visual); + return FALSE; + } + } else { + displayp->defaultVisual = -1; + } + + /* + * now hook in the modes + */ + modep = conf_display->disp_mode_lst; + while(modep) { + count++; + modep = (XF86ModePtr)modep->list.next; + } + displayp->modes = xnfalloc((count+1) * sizeof(char*)); + modep = conf_display->disp_mode_lst; + count = 0; + while(modep) { + displayp->modes[count] = modep->mode_name; + count++; + modep = (XF86ModePtr)modep->list.next; + } + displayp->modes[count] = NULL; + + return TRUE; +} + +static Bool +configDevice(GDevPtr devicep, XF86ConfDevicePtr conf_device, Bool active) +{ + int i; + + if (!conf_device) { + return FALSE; + } + + if (active) + xf86Msg(X_CONFIG, "| |-->Device \"%s\"\n", + conf_device->dev_identifier); + else + xf86Msg(X_CONFIG, "|-->Inactive Device \"%s\"\n", + conf_device->dev_identifier); + + devicep->identifier = conf_device->dev_identifier; + devicep->vendor = conf_device->dev_vendor; + devicep->board = conf_device->dev_board; + devicep->chipset = conf_device->dev_chipset; + devicep->ramdac = conf_device->dev_ramdac; + devicep->driver = conf_device->dev_driver; + devicep->active = active; + devicep->videoRam = conf_device->dev_videoram; + devicep->BiosBase = conf_device->dev_bios_base; + devicep->MemBase = conf_device->dev_mem_base; + devicep->IOBase = conf_device->dev_io_base; + devicep->clockchip = conf_device->dev_clockchip; + devicep->busID = conf_device->dev_busid; + devicep->textClockFreq = conf_device->dev_textclockfreq; + devicep->chipID = conf_device->dev_chipid; + devicep->chipRev = conf_device->dev_chiprev; + devicep->options = conf_device->dev_option_lst; + devicep->irq = conf_device->dev_irq; + devicep->screen = conf_device->dev_screen; + + for (i = 0; i < MAXDACSPEEDS; i++) { + if (i < CONF_MAXDACSPEEDS) + devicep->dacSpeeds[i] = conf_device->dev_dacSpeeds[i]; + else + devicep->dacSpeeds[i] = 0; + } + devicep->numclocks = conf_device->dev_clocks; + if (devicep->numclocks > MAXCLOCKS) + devicep->numclocks = MAXCLOCKS; + for (i = 0; i < devicep->numclocks; i++) { + devicep->clock[i] = conf_device->dev_clock[i]; + } + devicep->claimed = FALSE; + + return TRUE; +} + +#ifdef XF86DRI +static void +configDRI(XF86ConfDRIPtr drip) +{ + struct group *grp; + + xf86ConfigDRI.group = -1; + xf86ConfigDRI.mode = 0; + + if (drip) { + if (drip->dri_group_name) { + if ((grp = getgrnam(drip->dri_group_name))) + xf86ConfigDRI.group = grp->gr_gid; + } else { + if (drip->dri_group >= 0) + xf86ConfigDRI.group = drip->dri_group; + } + xf86ConfigDRI.mode = drip->dri_mode; + } +} +#endif + +static void +configExtensions(XF86ConfExtensionsPtr conf_ext) +{ + XF86OptionPtr o; + + if (conf_ext && conf_ext->ext_option_lst) { + for (o = conf_ext->ext_option_lst; o; o = xf86NextOption(o)) { + char *name = xf86OptionName(o); + char *val = xf86OptionValue(o); + char *n; + Bool enable = TRUE; + + /* Handle "No<ExtensionName>" */ + n = xf86NormalizeName(name); + if (strncmp(n, "no", 2) == 0) { + name += 2; + enable = FALSE; + } + + if (!val || + xf86NameCmp(val, "enable") == 0 || + xf86NameCmp(val, "enabled") == 0 || + xf86NameCmp(val, "on") == 0 || + xf86NameCmp(val, "1") == 0 || + xf86NameCmp(val, "yes") == 0 || + xf86NameCmp(val, "true") == 0) { + /* NOTHING NEEDED -- enabling is handled below */ + } else if (xf86NameCmp(val, "disable") == 0 || + xf86NameCmp(val, "disabled") == 0 || + xf86NameCmp(val, "off") == 0 || + xf86NameCmp(val, "0") == 0 || + xf86NameCmp(val, "no") == 0 || + xf86NameCmp(val, "false") == 0) { + enable = !enable; + } else { + xf86Msg(X_WARNING, "Ignoring unrecognized value \"%s\"\n", val); + free(n); + continue; + } + + if (EnableDisableExtension(name, enable)) { + xf86Msg(X_CONFIG, "Extension \"%s\" is %s\n", + name, enable ? "enabled" : "disabled"); + } else { + xf86Msg(X_WARNING, "Ignoring unrecognized extension \"%s\"\n", + name); + } + free(n); + } + } +} + +static Bool +configInput(InputInfoPtr inputp, XF86ConfInputPtr conf_input, MessageType from) +{ + xf86Msg(from, "|-->Input Device \"%s\"\n", conf_input->inp_identifier); + inputp->name = conf_input->inp_identifier; + inputp->driver = conf_input->inp_driver; + inputp->options = conf_input->inp_option_lst; + inputp->attrs = NULL; + + return TRUE; +} + +static Bool +modeIsPresent(DisplayModePtr mode, MonPtr monitorp) +{ + DisplayModePtr knownmodes = monitorp->Modes; + + /* all I can think of is a linear search... */ + while(knownmodes != NULL) + { + if(!strcmp(mode->name, knownmodes->name) && + !(knownmodes->type & M_T_DEFAULT)) + return TRUE; + knownmodes = knownmodes->next; + } + return FALSE; +} + +static Bool +addDefaultModes(MonPtr monitorp) +{ + DisplayModePtr mode; + DisplayModePtr last = monitorp->Last; + int i = 0; + + for (i = 0; i < xf86NumDefaultModes; i++) + { + mode = xf86DuplicateMode(&xf86DefaultModes[i]); + if (!modeIsPresent(mode, monitorp)) + { + monitorp->Modes = xf86ModesAdd(monitorp->Modes, mode); + last = mode; + } else { + free(mode); + } + } + monitorp->Last = last; + + return TRUE; +} + +static void +checkInput(serverLayoutPtr layout, Bool implicit_layout) { + checkCoreInputDevices(layout, implicit_layout); + + /* Unless we're forcing input devices, disable mouse/kbd devices in the + * config. Otherwise the same physical device is added multiple times, + * leading to duplicate events. + */ + if (!xf86Info.forceInputDevices && layout->inputs) + { + InputInfoPtr *dev = layout->inputs; + BOOL warned = FALSE; + + while(*dev) + { + if (strcmp((*dev)->driver, "kbd") == 0 || + strcmp((*dev)->driver, "mouse") == 0 || + strcmp((*dev)->driver, "vmmouse") == 0) + { + InputInfoPtr *current; + if (!warned) + { + xf86Msg(X_WARNING, "Hotplugging is on, devices using " + "drivers 'kbd', 'mouse' or 'vmmouse' will be disabled.\n"); + warned = TRUE; + } + + xf86Msg(X_WARNING, "Disabling %s\n", (*dev)->name); + + current = dev; + free(*dev); + + do { + *current = *(current + 1); + current++; + } while(*current); + } else + dev++; + } + } +} + +/* + * load the config file and fill the global data structure + */ +ConfigStatus +xf86HandleConfigFile(Bool autoconfig) +{ + const char *filename, *dirname, *sysdirname; + char *filesearch, *dirsearch; + MessageType filefrom = X_DEFAULT; + MessageType dirfrom = X_DEFAULT; + char *scanptr; + Bool singlecard = 0; + Bool implicit_layout = FALSE; + + if (!autoconfig) { + if (getuid() == 0) { + filesearch = ROOT_CONFIGPATH; + dirsearch = ROOT_CONFIGDIRPATH; + } else { + filesearch = USER_CONFIGPATH; + dirsearch = USER_CONFIGDIRPATH; + } + + if (xf86ConfigFile) + filefrom = X_CMDLINE; + if (xf86ConfigDir) + dirfrom = X_CMDLINE; + + xf86initConfigFiles(); + sysdirname = xf86openConfigDirFiles(SYS_CONFIGDIRPATH, NULL, + PROJECTROOT); + dirname = xf86openConfigDirFiles(dirsearch, xf86ConfigDir, PROJECTROOT); + filename = xf86openConfigFile(filesearch, xf86ConfigFile, PROJECTROOT); + if (filename) { + xf86MsgVerb(filefrom, 0, "Using config file: \"%s\"\n", filename); + xf86ConfigFile = xnfstrdup(filename); + } else { + if (xf86ConfigFile) + xf86Msg(X_ERROR, "Unable to locate/open config file: \"%s\"\n", + xf86ConfigFile); + } + if (dirname) { + xf86MsgVerb(dirfrom, 0, "Using config directory: \"%s\"\n", + dirname); + xf86ConfigDir = xnfstrdup(dirname); + } else { + if (xf86ConfigDir) + xf86Msg(X_ERROR, + "Unable to locate/open config directory: \"%s\"\n", + xf86ConfigDir); + } + if (sysdirname) + xf86MsgVerb(X_DEFAULT, 0, "Using system config directory \"%s\"\n", + sysdirname); + if (!filename && !dirname && !sysdirname) + return CONFIG_NOFILE; + } + + if ((xf86configptr = xf86readConfigFile ()) == NULL) { + xf86Msg(X_ERROR, "Problem parsing the config file\n"); + return CONFIG_PARSE_ERROR; + } + xf86closeConfigFile (); + + /* Initialise a few things. */ + + /* + * now we convert part of the information contained in the parser + * structures into our own structures. + * The important part here is to figure out which Screen Sections + * in the XF86Config file are active so that we can piece together + * the modes that we need later down the road. + * And while we are at it, we'll decode the rest of the stuff as well + */ + + /* First check if a layout section is present, and if it is valid. */ + + if (xf86configptr->conf_layout_lst == NULL || xf86ScreenName != NULL) { + if (xf86ScreenName == NULL) { + xf86Msg(X_DEFAULT, + "No Layout section. Using the first Screen section.\n"); + } + if (!configImpliedLayout(&xf86ConfigLayout, + xf86configptr->conf_screen_lst, + xf86configptr)) { + xf86Msg(X_ERROR, "Unable to determine the screen layout\n"); + return CONFIG_PARSE_ERROR; + } + implicit_layout = TRUE; + } else { + if (xf86configptr->conf_flags != NULL) { + char *dfltlayout = NULL; + pointer optlist = xf86configptr->conf_flags->flg_option_lst; + + if (optlist && xf86FindOption(optlist, "defaultserverlayout")) + dfltlayout = xf86SetStrOption(optlist, "defaultserverlayout", NULL); + if (!configLayout(&xf86ConfigLayout, xf86configptr->conf_layout_lst, + dfltlayout)) { + xf86Msg(X_ERROR, "Unable to determine the screen layout\n"); + return CONFIG_PARSE_ERROR; + } + } else { + if (!configLayout(&xf86ConfigLayout, xf86configptr->conf_layout_lst, + NULL)) { + xf86Msg(X_ERROR, "Unable to determine the screen layout\n"); + return CONFIG_PARSE_ERROR; + } + } + } + + xf86ProcessOptions(-1, xf86ConfigLayout.options, LayoutOptions); + + if ((scanptr = xf86GetOptValString(LayoutOptions, LAYOUT_ISOLATEDEVICE))) { + ; /* IsolateDevice specified; overrides SingleCard */ + } else { + xf86GetOptValBool(LayoutOptions, LAYOUT_SINGLECARD, &singlecard); + if (singlecard) + scanptr = xf86ConfigLayout.screens->screen->device->busID; + } + if (scanptr) { + if (strncmp(scanptr, "PCI:", 4) != 0) { + xf86Msg(X_WARNING, "Bus types other than PCI not yet isolable.\n" + "\tIgnoring IsolateDevice option.\n"); + } else + xf86PciIsolateDevice(scanptr); + } + + /* Now process everything else */ + if (!configServerFlags(xf86configptr->conf_flags,xf86ConfigLayout.options)){ + ErrorF ("Problem when converting the config data structures\n"); + return CONFIG_PARSE_ERROR; + } + + configFiles(xf86configptr->conf_files); + configExtensions(xf86configptr->conf_extensions); +#ifdef XF86DRI + configDRI(xf86configptr->conf_dri); +#endif + + checkInput(&xf86ConfigLayout, implicit_layout); + + /* + * Handle some command line options that can override some of the + * ServerFlags settings. + */ +#ifdef XF86VIDMODE + if (xf86VidModeDisabled) + xf86Info.vidModeEnabled = FALSE; + if (xf86VidModeAllowNonLocal) + xf86Info.vidModeAllowNonLocal = TRUE; +#endif + + if (xf86AllowMouseOpenFail) + xf86Info.allowMouseOpenFail = TRUE; + + return CONFIG_OK; +} + +Bool +xf86PathIsSafe(const char *path) +{ + return (xf86pathIsSafe(path) != 0); +} diff --git a/xorg-server/hw/xfree86/common/xf86Configure.c b/xorg-server/hw/xfree86/common/xf86Configure.c index aabb8e11b..ab0751507 100644 --- a/xorg-server/hw/xfree86/common/xf86Configure.c +++ b/xorg-server/hw/xfree86/common/xf86Configure.c @@ -1,755 +1,755 @@ -/*
- * 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: Alan Hourihane, alanh@fairlite.demon.co.uk
- *
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86.h"
-#include "xf86Config.h"
-#include "xf86_OSlib.h"
-#include "xf86Priv.h"
-#define IN_XSERVER
-#include "Configint.h"
-#include "xf86DDC.h"
-#include "xf86pciBus.h"
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
-#include "xf86Bus.h"
-#include "xf86Sbus.h"
-#endif
-#include "misc.h"
-
-typedef struct _DevToConfig {
- GDevRec GDev;
- struct pci_device * pVideo;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- sbusDevicePtr sVideo;
-#endif
- int iDriver;
-} DevToConfigRec, *DevToConfigPtr;
-
-static DevToConfigPtr DevToConfig = NULL;
-static int nDevToConfig = 0, CurrentDriver;
-
-xf86MonPtr ConfiguredMonitor;
-Bool xf86DoConfigurePass1 = TRUE;
-static Bool foundMouse = FALSE;
-
-#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
-static char *DFLT_MOUSE_DEV = "/dev/sysmouse";
-static char *DFLT_MOUSE_PROTO = "auto";
-#elif defined(linux)
-static char DFLT_MOUSE_DEV[] = "/dev/input/mice";
-static char DFLT_MOUSE_PROTO[] = "auto";
-#elif defined(WSCONS_SUPPORT)
-static char *DFLT_MOUSE_DEV = "/dev/wsmouse";
-static char *DFLT_MOUSE_PROTO = "wsmouse";
-#else
-static char *DFLT_MOUSE_DEV = "/dev/mouse";
-static char *DFLT_MOUSE_PROTO = "auto";
-#endif
-
-/*
- * This is called by the driver, either through xf86Match???Instances() or
- * directly. We allocate a GDevRec and fill it in as much as we can, letting
- * the caller fill in the rest and/or change it as it sees fit.
- */
-GDevPtr
-xf86AddBusDeviceToConfigure(const char *driver, BusType bus, void *busData, int chipset)
-{
- int ret, i, j;
-
- if (!xf86DoConfigure || !xf86DoConfigurePass1)
- return NULL;
-
- /* Check for duplicates */
- for (i = 0; i < nDevToConfig; i++) {
- switch (bus) {
- case BUS_PCI:
- ret = xf86PciConfigure(busData, DevToConfig[i].pVideo);
- break;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- case BUS_SBUS:
- ret = xf86SbusConfigure(busData, DevToConfig[i].sVideo);
- break;
-#endif
- default:
- return NULL;
- }
- if (ret == 0)
- goto out;
- }
-
- /* Allocate new structure occurrence */
- i = nDevToConfig++;
- DevToConfig =
- xnfrealloc(DevToConfig, nDevToConfig * sizeof(DevToConfigRec));
- memset(DevToConfig + i, 0, sizeof(DevToConfigRec));
-
- DevToConfig[i].GDev.chipID =
- DevToConfig[i].GDev.chipRev = DevToConfig[i].GDev.irq = -1;
-
- DevToConfig[i].iDriver = CurrentDriver;
-
- /* Fill in what we know, converting the driver name to lower case */
- DevToConfig[i].GDev.driver = xnfalloc(strlen(driver) + 1);
- for (j = 0; (DevToConfig[i].GDev.driver[j] = tolower(driver[j])); j++);
-
- switch (bus) {
- case BUS_PCI:
- xf86PciConfigureNewDev(busData, DevToConfig[i].pVideo,
- &DevToConfig[i].GDev, &chipset);
- break;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- case BUS_SBUS:
- xf86SbusConfigureNewDev(busData, DevToConfig[i].sVideo,
- &DevToConfig[i].GDev);
- break;
-#endif
- default:
- break;
- }
-
- /* Get driver's available options */
- if (xf86DriverList[CurrentDriver]->AvailableOptions)
- DevToConfig[i].GDev.options = (OptionInfoPtr)
- (*xf86DriverList[CurrentDriver]->AvailableOptions)(chipset,
- bus);
-
- return &DevToConfig[i].GDev;
-
-out:
- return NULL;
-}
-
-static XF86ConfInputPtr
-configureInputSection (void)
-{
- XF86ConfInputPtr mouse = NULL;
- parsePrologue (XF86ConfInputPtr, XF86ConfInputRec)
-
- ptr->inp_identifier = "Keyboard0";
- ptr->inp_driver = "kbd";
- ptr->list.next = NULL;
-
- /* Crude mechanism to auto-detect mouse (os dependent) */
- {
- int fd;
-
- fd = open(DFLT_MOUSE_DEV, 0);
- if (fd != -1) {
- foundMouse = TRUE;
- close(fd);
- }
- }
-
- mouse = calloc(1, sizeof(XF86ConfInputRec));
- mouse->inp_identifier = "Mouse0";
- mouse->inp_driver = "mouse";
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("Protocol"),
- strdup(DFLT_MOUSE_PROTO));
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("Device"),
- strdup(DFLT_MOUSE_DEV));
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("ZAxisMapping"),
- strdup("4 5 6 7"));
- ptr = (XF86ConfInputPtr)xf86addListItem((glp)ptr, (glp)mouse);
- return ptr;
-}
-
-static XF86ConfScreenPtr
-configureScreenSection (int screennum)
-{
- int i;
- int depths[] = { 1, 4, 8, 15, 16, 24/*, 32*/ };
- parsePrologue (XF86ConfScreenPtr, XF86ConfScreenRec)
-
- XNFasprintf(&ptr->scrn_identifier, "Screen%d", screennum);
- XNFasprintf(&ptr->scrn_monitor_str, "Monitor%d", screennum);
- XNFasprintf(&ptr->scrn_device_str, "Card%d", screennum);
-
- for (i=0; i<sizeof(depths)/sizeof(depths[0]); i++)
- {
- XF86ConfDisplayPtr display;
-
- display = calloc(1, sizeof(XF86ConfDisplayRec));
- display->disp_depth = depths[i];
- display->disp_black.red = display->disp_white.red = -1;
- display->disp_black.green = display->disp_white.green = -1;
- display->disp_black.blue = display->disp_white.blue = -1;
- ptr->scrn_display_lst = (XF86ConfDisplayPtr)xf86addListItem(
- (glp)ptr->scrn_display_lst, (glp)display);
- }
-
- return ptr;
-}
-
-static const char*
-optionTypeToString(OptionValueType type)
-{
- switch (type) {
- case OPTV_NONE:
- return "";
- case OPTV_INTEGER:
- return "<i>";
- case OPTV_STRING:
- return "<str>";
- case OPTV_ANYSTR:
- return "[<str>]";
- case OPTV_REAL:
- return "<f>";
- case OPTV_BOOLEAN:
- return "[<bool>]";
- case OPTV_FREQ:
- return "<freq>";
- case OPTV_PERCENT:
- return "<percent>";
- default:
- return "";
- }
-}
-
-static XF86ConfDevicePtr
-configureDeviceSection (int screennum)
-{
- OptionInfoPtr p;
- int i = 0;
- parsePrologue (XF86ConfDevicePtr, XF86ConfDeviceRec)
-
- /* Move device info to parser structure */
- if (asprintf(&ptr->dev_identifier, "Card%d", screennum) == -1)
- ptr->dev_identifier = NULL;
- ptr->dev_chipset = DevToConfig[screennum].GDev.chipset;
- ptr->dev_busid = DevToConfig[screennum].GDev.busID;
- ptr->dev_driver = DevToConfig[screennum].GDev.driver;
- ptr->dev_ramdac = DevToConfig[screennum].GDev.ramdac;
- for (i = 0; (i < MAXDACSPEEDS) && (i < CONF_MAXDACSPEEDS); i++)
- ptr->dev_dacSpeeds[i] = DevToConfig[screennum].GDev.dacSpeeds[i];
- ptr->dev_videoram = DevToConfig[screennum].GDev.videoRam;
- ptr->dev_textclockfreq = DevToConfig[screennum].GDev.textClockFreq;
- ptr->dev_bios_base = DevToConfig[screennum].GDev.BiosBase;
- ptr->dev_mem_base = DevToConfig[screennum].GDev.MemBase;
- ptr->dev_io_base = DevToConfig[screennum].GDev.IOBase;
- ptr->dev_clockchip = DevToConfig[screennum].GDev.clockchip;
- for (i = 0; (i < MAXCLOCKS) && (i < DevToConfig[screennum].GDev.numclocks); i++)
- ptr->dev_clock[i] = DevToConfig[screennum].GDev.clock[i];
- ptr->dev_clocks = i;
- ptr->dev_chipid = DevToConfig[screennum].GDev.chipID;
- ptr->dev_chiprev = DevToConfig[screennum].GDev.chipRev;
- ptr->dev_irq = DevToConfig[screennum].GDev.irq;
-
- /* Make sure older drivers don't segv */
- if (DevToConfig[screennum].GDev.options) {
- /* Fill in the available driver options for people to use */
- const char *descrip =
- " ### Available Driver options are:-\n"
- " ### Values: <i>: integer, <f>: float, "
- "<bool>: \"True\"/\"False\",\n"
- " ### <string>: \"String\", <freq>: \"<f> Hz/kHz/MHz\",\n"
- " ### <percent>: \"<f>%\"\n"
- " ### [arg]: arg optional\n";
- ptr->dev_comment = strdup(descrip);
- if (ptr->dev_comment) {
- for (p = DevToConfig[screennum].GDev.options;
- p->name != NULL; p++) {
- char *p_e;
- const char *prefix = " #Option ";
- const char *middle = " \t# ";
- const char *suffix = "\n";
- const char *opttype = optionTypeToString(p->type);
- char *optname;
- int len = strlen(ptr->dev_comment) + strlen(prefix) +
- strlen(middle) + strlen(suffix) + 1;
-
- if (asprintf(&optname, "\"%s\"", p->name) == -1)
- break;
-
- len += max(20, strlen(optname));
- len += strlen(opttype);
-
- ptr->dev_comment = realloc(ptr->dev_comment, len);
- if (!ptr->dev_comment)
- break;
- p_e = ptr->dev_comment + strlen(ptr->dev_comment);
- sprintf(p_e, "%s%-20s%s%s%s", prefix, optname, middle,
- opttype, suffix);
- free(optname);
- }
- }
- }
-
- return ptr;
-}
-
-static XF86ConfLayoutPtr
-configureLayoutSection (void)
-{
- int scrnum = 0;
- parsePrologue (XF86ConfLayoutPtr, XF86ConfLayoutRec)
-
- ptr->lay_identifier = "X.org Configured";
-
- {
- XF86ConfInputrefPtr iptr;
-
- iptr = malloc (sizeof (XF86ConfInputrefRec));
- iptr->list.next = NULL;
- iptr->iref_option_lst = NULL;
- iptr->iref_inputdev_str = "Mouse0";
- iptr->iref_option_lst =
- xf86addNewOption (iptr->iref_option_lst, strdup("CorePointer"), NULL);
- ptr->lay_input_lst = (XF86ConfInputrefPtr)
- xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr);
- }
-
- {
- XF86ConfInputrefPtr iptr;
-
- iptr = malloc (sizeof (XF86ConfInputrefRec));
- iptr->list.next = NULL;
- iptr->iref_option_lst = NULL;
- iptr->iref_inputdev_str = "Keyboard0";
- iptr->iref_option_lst =
- xf86addNewOption (iptr->iref_option_lst, strdup("CoreKeyboard"), NULL);
- ptr->lay_input_lst = (XF86ConfInputrefPtr)
- xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr);
- }
-
- for (scrnum = 0; scrnum < nDevToConfig; scrnum++) {
- XF86ConfAdjacencyPtr aptr;
-
- aptr = malloc (sizeof (XF86ConfAdjacencyRec));
- aptr->list.next = NULL;
- aptr->adj_x = 0;
- aptr->adj_y = 0;
- aptr->adj_scrnum = scrnum;
- XNFasprintf(&aptr->adj_screen_str, "Screen%d", scrnum);
- if (scrnum == 0) {
- aptr->adj_where = CONF_ADJ_ABSOLUTE;
- aptr->adj_refscreen = NULL;
- }
- else {
- aptr->adj_where = CONF_ADJ_RIGHTOF;
- XNFasprintf(&aptr->adj_refscreen, "Screen%d", scrnum - 1);
- }
- ptr->lay_adjacency_lst =
- (XF86ConfAdjacencyPtr)xf86addListItem((glp)ptr->lay_adjacency_lst,
- (glp)aptr);
- }
-
- return ptr;
-}
-
-static XF86ConfFlagsPtr
-configureFlagsSection (void)
-{
- parsePrologue (XF86ConfFlagsPtr, XF86ConfFlagsRec)
-
- return ptr;
-}
-
-static XF86ConfModulePtr
-configureModuleSection (void)
-{
- char **elist, **el;
- /* Find the list of extension & font modules. */
- const char *esubdirs[] = {
- "extensions",
- "fonts",
- NULL
- };
- parsePrologue (XF86ConfModulePtr, XF86ConfModuleRec)
-
- elist = LoaderListDirs(esubdirs, NULL);
- if (elist) {
- for (el = elist; *el; el++) {
- XF86LoadPtr module;
-
- module = calloc(1, sizeof(XF86LoadRec));
- module->load_name = *el;
- ptr->mod_load_lst = (XF86LoadPtr)xf86addListItem(
- (glp)ptr->mod_load_lst, (glp)module);
- }
- free(elist);
- }
-
- return ptr;
-}
-
-static XF86ConfFilesPtr
-configureFilesSection (void)
-{
- parsePrologue (XF86ConfFilesPtr, XF86ConfFilesRec)
-
- if (xf86ModulePath)
- ptr->file_modulepath = strdup(xf86ModulePath);
- if (defaultFontPath)
- ptr->file_fontpath = strdup(defaultFontPath);
-
- return ptr;
-}
-
-static XF86ConfMonitorPtr
-configureMonitorSection (int screennum)
-{
- parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec)
-
- XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum);
- ptr->mon_vendor = strdup("Monitor Vendor");
- ptr->mon_modelname = strdup("Monitor Model");
-
- return ptr;
-}
-
-/* Initialize Configure Monitor from Detailed Timing Block */
-static void handle_detailed_input(struct detailed_monitor_section *det_mon,
- void *data)
-{
- XF86ConfMonitorPtr ptr = (XF86ConfMonitorPtr) data;
-
- switch (det_mon->type) {
- case DS_NAME:
- ptr->mon_modelname = realloc(ptr->mon_modelname,
- strlen((char*)(det_mon->section.name)) +
- 1);
- strcpy(ptr->mon_modelname,
- (char*)(det_mon->section.name));
- break;
- case DS_RANGES:
- ptr->mon_hsync[ptr->mon_n_hsync].lo =
- det_mon->section.ranges.min_h;
- ptr->mon_hsync[ptr->mon_n_hsync].hi =
- det_mon->section.ranges.max_h;
- ptr->mon_n_vrefresh = 1;
- ptr->mon_vrefresh[ptr->mon_n_hsync].lo =
- det_mon->section.ranges.min_v;
- ptr->mon_vrefresh[ptr->mon_n_hsync].hi =
- det_mon->section.ranges.max_v;
- ptr->mon_n_hsync++;
- default:
- break;
- }
-}
-
-static XF86ConfMonitorPtr
-configureDDCMonitorSection (int screennum)
-{
- int len, mon_width, mon_height;
-#define displaySizeMaxLen 80
- char displaySize_string[displaySizeMaxLen];
- int displaySizeLen;
-
- parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec)
-
- XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum);
- ptr->mon_vendor = strdup(ConfiguredMonitor->vendor.name);
- XNFasprintf(&ptr->mon_modelname, "%x", ConfiguredMonitor->vendor.prod_id);
-
- /* features in centimetres, we want millimetres */
- mon_width = 10 * ConfiguredMonitor->features.hsize ;
- mon_height = 10 * ConfiguredMonitor->features.vsize ;
-
-#ifdef CONFIGURE_DISPLAYSIZE
- ptr->mon_width = mon_width;
- ptr->mon_height = mon_height;
-#else
- if (mon_width && mon_height) {
- /* when values available add DisplaySize option AS A COMMENT */
-
- displaySizeLen = snprintf(displaySize_string, displaySizeMaxLen,
- "\t#DisplaySize\t%5d %5d\t# mm\n",
- mon_width, mon_height);
-
- if (displaySizeLen>0 && displaySizeLen<displaySizeMaxLen) {
- if (ptr->mon_comment) {
- len = strlen(ptr->mon_comment);
- } else {
- len = 0;
- }
- if ((ptr->mon_comment =
- realloc(ptr->mon_comment, len + strlen(displaySize_string) + 1))) {
- strcpy(ptr->mon_comment + len, displaySize_string);
- }
- }
- }
-#endif /* def CONFIGURE_DISPLAYSIZE */
-
- xf86ForEachDetailedBlock(ConfiguredMonitor, handle_detailed_input,
- ptr);
-
- if (ConfiguredMonitor->features.dpms) {
- ptr->mon_option_lst = xf86addNewOption(ptr->mon_option_lst, strdup("DPMS"), NULL);
- }
-
- return ptr;
-}
-
-void
-DoConfigure(void)
-{
- int i,j, screennum = -1;
- char *home = NULL;
- char filename[PATH_MAX];
- char *addslash = "";
- XF86ConfigPtr xf86config = NULL;
- char **vlist, **vl;
- int *dev2screen;
-
- vlist = xf86DriverlistFromCompile();
-
- if (!vlist) {
- ErrorF("Missing output drivers. Configuration failed.\n");
- goto bail;
- }
-
- ErrorF("List of video drivers:\n");
- for (vl = vlist; *vl; vl++)
- ErrorF("\t%s\n", *vl);
-
- /* Load all the drivers that were found. */
- xf86LoadModules(vlist, NULL);
-
- free(vlist);
-
- for (i = 0; i < xf86NumDrivers; i++) {
- xorgHWFlags flags;
- if (!xf86DriverList[i]->driverFunc
- || !xf86DriverList[i]->driverFunc(NULL,
- GET_REQUIRED_HW_INTERFACES,
- &flags)
- || NEED_IO_ENABLED(flags)) {
- xorgHWAccess = TRUE;
- break;
- }
- }
- /* Enable full I/O access */
- if (xorgHWAccess) {
- if(!xf86EnableIO())
- /* oops, we have failed */
- xorgHWAccess = FALSE;
- }
-
- /* Create XF86Config file structure */
- xf86config = calloc(1, sizeof(XF86ConfigRec));
-
- /* Call all of the probe functions, reporting the results. */
- for (CurrentDriver = 0; CurrentDriver < xf86NumDrivers; CurrentDriver++) {
- xorgHWFlags flags;
- Bool found_screen;
- DriverRec * const drv = xf86DriverList[CurrentDriver];
-
- if (!xorgHWAccess) {
- if (!drv->driverFunc
- || !drv->driverFunc( NULL, GET_REQUIRED_HW_INTERFACES, &flags )
- || NEED_IO_ENABLED(flags))
- continue;
- }
-
- found_screen = xf86CallDriverProbe( drv, TRUE );
- if ( found_screen && drv->Identify ) {
- (*drv->Identify)(0);
- }
- }
-
- if (nDevToConfig <= 0) {
- ErrorF("No devices to configure. Configuration failed.\n");
- goto bail;
- }
-
- /* Add device, monitor and screen sections for detected devices */
- for (screennum = 0; screennum < nDevToConfig; screennum++) {
- XF86ConfDevicePtr DevicePtr;
- XF86ConfMonitorPtr MonitorPtr;
- XF86ConfScreenPtr ScreenPtr;
-
- DevicePtr = configureDeviceSection(screennum);
- xf86config->conf_device_lst = (XF86ConfDevicePtr)xf86addListItem(
- (glp)xf86config->conf_device_lst, (glp)DevicePtr);
- MonitorPtr = configureMonitorSection(screennum);
- xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem(
- (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr);
- ScreenPtr = configureScreenSection(screennum);
- xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem(
- (glp)xf86config->conf_screen_lst, (glp)ScreenPtr);
- }
-
- xf86config->conf_files = configureFilesSection();
- xf86config->conf_modules = configureModuleSection();
- xf86config->conf_flags = configureFlagsSection();
- xf86config->conf_videoadaptor_lst = NULL;
- xf86config->conf_modes_lst = NULL;
- xf86config->conf_vendor_lst = NULL;
- xf86config->conf_dri = NULL;
- xf86config->conf_input_lst = configureInputSection();
- xf86config->conf_layout_lst = configureLayoutSection();
-
- home = getenv("HOME");
- if ((home == NULL) || (home[0] == '\0')) {
- home = "/";
- } else {
- /* Determine if trailing slash is present or needed */
- int l = strlen(home);
-
- if (home[l-1] != '/') {
- addslash = "/";
- }
- }
-
- snprintf(filename, sizeof(filename), "%s%s" XF86CONFIGFILE ".new",
- home, addslash);
-
- if (xf86writeConfigFile(filename, xf86config) == 0) {
- xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n",
- filename, strerror(errno));
- goto bail;
- }
-
- xf86DoConfigurePass1 = FALSE;
- /* Try to get DDC information filled in */
- xf86ConfigFile = filename;
- if (xf86HandleConfigFile(FALSE) != CONFIG_OK) {
- goto bail;
- }
-
- xf86DoConfigurePass1 = FALSE;
-
- dev2screen = xnfcalloc(1,xf86NumDrivers*sizeof(int));
-
- {
- Bool *driverProbed = xnfcalloc(1,xf86NumDrivers*sizeof(Bool));
- for (screennum = 0; screennum < nDevToConfig; screennum++) {
- int k,l,n,oldNumScreens;
-
- i = DevToConfig[screennum].iDriver;
-
- if (driverProbed[i]) continue;
- driverProbed[i] = TRUE;
-
- oldNumScreens = xf86NumScreens;
-
- xf86CallDriverProbe( xf86DriverList[i], FALSE );
-
- /* reorder */
- k = screennum > 0 ? screennum : 1;
- for (l = oldNumScreens; l < xf86NumScreens; l++) {
- /* is screen primary? */
- Bool primary = FALSE;
- for (n = 0; n<xf86Screens[l]->numEntities; n++) {
- if (xf86IsEntityPrimary(xf86Screens[l]->entityList[n])) {
- dev2screen[0] = l;
- primary = TRUE;
- break;
- }
- }
- if (primary) continue;
- /* not primary: assign it to next device of same driver */
- /*
- * NOTE: we assume that devices in DevToConfig
- * and xf86Screens[] have the same order except
- * for the primary device which always comes first.
- */
- for (; k < nDevToConfig; k++) {
- if (DevToConfig[k].iDriver == i) {
- dev2screen[k++] = l;
- break;
- }
- }
- }
- }
- free(driverProbed);
- }
-
-
- if (nDevToConfig != xf86NumScreens) {
- ErrorF("Number of created screens does not match number of detected"
- " devices.\n Configuration failed.\n");
- goto bail;
- }
-
- xf86PostProbe();
-
- for (j = 0; j < xf86NumScreens; j++) {
- xf86Screens[j]->scrnIndex = j;
- }
-
- xf86freeMonitorList(xf86config->conf_monitor_lst);
- xf86config->conf_monitor_lst = NULL;
- xf86freeScreenList(xf86config->conf_screen_lst);
- xf86config->conf_screen_lst = NULL;
- for (j = 0; j < xf86NumScreens; j++) {
- XF86ConfMonitorPtr MonitorPtr;
- XF86ConfScreenPtr ScreenPtr;
-
- ConfiguredMonitor = NULL;
-
- if ((*xf86Screens[dev2screen[j]]->PreInit)(xf86Screens[dev2screen[j]],
- PROBE_DETECT) &&
- ConfiguredMonitor) {
- MonitorPtr = configureDDCMonitorSection(j);
- } else {
- MonitorPtr = configureMonitorSection(j);
- }
- ScreenPtr = configureScreenSection(j);
- xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem(
- (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr);
- xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem(
- (glp)xf86config->conf_screen_lst, (glp)ScreenPtr);
- }
-
- if (xf86writeConfigFile(filename, xf86config) == 0) {
- xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n",
- filename, strerror(errno));
- goto bail;
- }
-
- ErrorF("\n");
-
- if (!foundMouse) {
- ErrorF("\n"__XSERVERNAME__" is not able to detect your mouse.\n"
- "Edit the file and correct the Device.\n");
- } else {
- ErrorF("\n"__XSERVERNAME__" detected your mouse at device %s.\n"
- "Please check your config if the mouse is still not\n"
- "operational, as by default "__XSERVERNAME__
- " tries to autodetect\n"
- "the protocol.\n",DFLT_MOUSE_DEV);
- }
-
- if (xf86NumScreens > 1) {
- ErrorF("\n"__XSERVERNAME__
- " has configured a multihead system, please check your config.\n");
- }
-
- ErrorF("\nYour %s file is %s\n\n", XF86CONFIGFILE ,filename);
- ErrorF("To test the server, run 'X -config %s'\n\n", filename);
-
-bail:
- OsCleanup(TRUE);
- AbortDDX(EXIT_ERR_CONFIGURE);
- fflush(stderr);
- exit(0);
-}
+/* + * 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: Alan Hourihane, alanh@fairlite.demon.co.uk + * + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include "xf86.h" +#include "xf86Config.h" +#include "xf86_OSlib.h" +#include "xf86Priv.h" +#define IN_XSERVER +#include "Configint.h" +#include "xf86DDC.h" +#include "xf86pciBus.h" +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) +#include "xf86Bus.h" +#include "xf86Sbus.h" +#endif +#include "misc.h" + +typedef struct _DevToConfig { + GDevRec GDev; + struct pci_device * pVideo; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + sbusDevicePtr sVideo; +#endif + int iDriver; +} DevToConfigRec, *DevToConfigPtr; + +static DevToConfigPtr DevToConfig = NULL; +static int nDevToConfig = 0, CurrentDriver; + +xf86MonPtr ConfiguredMonitor; +Bool xf86DoConfigurePass1 = TRUE; +static Bool foundMouse = FALSE; + +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +static char *DFLT_MOUSE_DEV = "/dev/sysmouse"; +static char *DFLT_MOUSE_PROTO = "auto"; +#elif defined(linux) +static char DFLT_MOUSE_DEV[] = "/dev/input/mice"; +static char DFLT_MOUSE_PROTO[] = "auto"; +#elif defined(WSCONS_SUPPORT) +static char *DFLT_MOUSE_DEV = "/dev/wsmouse"; +static char *DFLT_MOUSE_PROTO = "wsmouse"; +#else +static char *DFLT_MOUSE_DEV = "/dev/mouse"; +static char *DFLT_MOUSE_PROTO = "auto"; +#endif + +/* + * This is called by the driver, either through xf86Match???Instances() or + * directly. We allocate a GDevRec and fill it in as much as we can, letting + * the caller fill in the rest and/or change it as it sees fit. + */ +GDevPtr +xf86AddBusDeviceToConfigure(const char *driver, BusType bus, void *busData, int chipset) +{ + int ret, i, j; + + if (!xf86DoConfigure || !xf86DoConfigurePass1) + return NULL; + + /* Check for duplicates */ + for (i = 0; i < nDevToConfig; i++) { + switch (bus) { + case BUS_PCI: + ret = xf86PciConfigure(busData, DevToConfig[i].pVideo); + break; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + case BUS_SBUS: + ret = xf86SbusConfigure(busData, DevToConfig[i].sVideo); + break; +#endif + default: + return NULL; + } + if (ret == 0) + goto out; + } + + /* Allocate new structure occurrence */ + i = nDevToConfig++; + DevToConfig = + xnfrealloc(DevToConfig, nDevToConfig * sizeof(DevToConfigRec)); + memset(DevToConfig + i, 0, sizeof(DevToConfigRec)); + + DevToConfig[i].GDev.chipID = + DevToConfig[i].GDev.chipRev = DevToConfig[i].GDev.irq = -1; + + DevToConfig[i].iDriver = CurrentDriver; + + /* Fill in what we know, converting the driver name to lower case */ + DevToConfig[i].GDev.driver = xnfalloc(strlen(driver) + 1); + for (j = 0; (DevToConfig[i].GDev.driver[j] = tolower(driver[j])); j++); + + switch (bus) { + case BUS_PCI: + xf86PciConfigureNewDev(busData, DevToConfig[i].pVideo, + &DevToConfig[i].GDev, &chipset); + break; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + case BUS_SBUS: + xf86SbusConfigureNewDev(busData, DevToConfig[i].sVideo, + &DevToConfig[i].GDev); + break; +#endif + default: + break; + } + + /* Get driver's available options */ + if (xf86DriverList[CurrentDriver]->AvailableOptions) + DevToConfig[i].GDev.options = (OptionInfoPtr) + (*xf86DriverList[CurrentDriver]->AvailableOptions)(chipset, + bus); + + return &DevToConfig[i].GDev; + +out: + return NULL; +} + +static XF86ConfInputPtr +configureInputSection (void) +{ + XF86ConfInputPtr mouse = NULL; + parsePrologue (XF86ConfInputPtr, XF86ConfInputRec) + + ptr->inp_identifier = "Keyboard0"; + ptr->inp_driver = "kbd"; + ptr->list.next = NULL; + + /* Crude mechanism to auto-detect mouse (os dependent) */ + { + int fd; + + fd = open(DFLT_MOUSE_DEV, 0); + if (fd != -1) { + foundMouse = TRUE; + close(fd); + } + } + + mouse = calloc(1, sizeof(XF86ConfInputRec)); + mouse->inp_identifier = "Mouse0"; + mouse->inp_driver = "mouse"; + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("Protocol"), + strdup(DFLT_MOUSE_PROTO)); + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("Device"), + strdup(DFLT_MOUSE_DEV)); + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("ZAxisMapping"), + strdup("4 5 6 7")); + ptr = (XF86ConfInputPtr)xf86addListItem((glp)ptr, (glp)mouse); + return ptr; +} + +static XF86ConfScreenPtr +configureScreenSection (int screennum) +{ + int i; + int depths[] = { 1, 4, 8, 15, 16, 24/*, 32*/ }; + parsePrologue (XF86ConfScreenPtr, XF86ConfScreenRec) + + XNFasprintf(&ptr->scrn_identifier, "Screen%d", screennum); + XNFasprintf(&ptr->scrn_monitor_str, "Monitor%d", screennum); + XNFasprintf(&ptr->scrn_device_str, "Card%d", screennum); + + for (i=0; i<sizeof(depths)/sizeof(depths[0]); i++) + { + XF86ConfDisplayPtr display; + + display = calloc(1, sizeof(XF86ConfDisplayRec)); + display->disp_depth = depths[i]; + display->disp_black.red = display->disp_white.red = -1; + display->disp_black.green = display->disp_white.green = -1; + display->disp_black.blue = display->disp_white.blue = -1; + ptr->scrn_display_lst = (XF86ConfDisplayPtr)xf86addListItem( + (glp)ptr->scrn_display_lst, (glp)display); + } + + return ptr; +} + +static const char* +optionTypeToString(OptionValueType type) +{ + switch (type) { + case OPTV_NONE: + return ""; + case OPTV_INTEGER: + return "<i>"; + case OPTV_STRING: + return "<str>"; + case OPTV_ANYSTR: + return "[<str>]"; + case OPTV_REAL: + return "<f>"; + case OPTV_BOOLEAN: + return "[<bool>]"; + case OPTV_FREQ: + return "<freq>"; + case OPTV_PERCENT: + return "<percent>"; + default: + return ""; + } +} + +static XF86ConfDevicePtr +configureDeviceSection (int screennum) +{ + OptionInfoPtr p; + int i = 0; + parsePrologue (XF86ConfDevicePtr, XF86ConfDeviceRec) + + /* Move device info to parser structure */ + if (asprintf(&ptr->dev_identifier, "Card%d", screennum) == -1) + ptr->dev_identifier = NULL; + ptr->dev_chipset = DevToConfig[screennum].GDev.chipset; + ptr->dev_busid = DevToConfig[screennum].GDev.busID; + ptr->dev_driver = DevToConfig[screennum].GDev.driver; + ptr->dev_ramdac = DevToConfig[screennum].GDev.ramdac; + for (i = 0; (i < MAXDACSPEEDS) && (i < CONF_MAXDACSPEEDS); i++) + ptr->dev_dacSpeeds[i] = DevToConfig[screennum].GDev.dacSpeeds[i]; + ptr->dev_videoram = DevToConfig[screennum].GDev.videoRam; + ptr->dev_textclockfreq = DevToConfig[screennum].GDev.textClockFreq; + ptr->dev_bios_base = DevToConfig[screennum].GDev.BiosBase; + ptr->dev_mem_base = DevToConfig[screennum].GDev.MemBase; + ptr->dev_io_base = DevToConfig[screennum].GDev.IOBase; + ptr->dev_clockchip = DevToConfig[screennum].GDev.clockchip; + for (i = 0; (i < MAXCLOCKS) && (i < DevToConfig[screennum].GDev.numclocks); i++) + ptr->dev_clock[i] = DevToConfig[screennum].GDev.clock[i]; + ptr->dev_clocks = i; + ptr->dev_chipid = DevToConfig[screennum].GDev.chipID; + ptr->dev_chiprev = DevToConfig[screennum].GDev.chipRev; + ptr->dev_irq = DevToConfig[screennum].GDev.irq; + + /* Make sure older drivers don't segv */ + if (DevToConfig[screennum].GDev.options) { + /* Fill in the available driver options for people to use */ + const char *descrip = + " ### Available Driver options are:-\n" + " ### Values: <i>: integer, <f>: float, " + "<bool>: \"True\"/\"False\",\n" + " ### <string>: \"String\", <freq>: \"<f> Hz/kHz/MHz\",\n" + " ### <percent>: \"<f>%\"\n" + " ### [arg]: arg optional\n"; + ptr->dev_comment = strdup(descrip); + if (ptr->dev_comment) { + for (p = DevToConfig[screennum].GDev.options; + p->name != NULL; p++) { + char *p_e; + const char *prefix = " #Option "; + const char *middle = " \t# "; + const char *suffix = "\n"; + const char *opttype = optionTypeToString(p->type); + char *optname; + int len = strlen(ptr->dev_comment) + strlen(prefix) + + strlen(middle) + strlen(suffix) + 1; + + if (asprintf(&optname, "\"%s\"", p->name) == -1) + break; + + len += max(20, strlen(optname)); + len += strlen(opttype); + + ptr->dev_comment = realloc(ptr->dev_comment, len); + if (!ptr->dev_comment) + break; + p_e = ptr->dev_comment + strlen(ptr->dev_comment); + sprintf(p_e, "%s%-20s%s%s%s", prefix, optname, middle, + opttype, suffix); + free(optname); + } + } + } + + return ptr; +} + +static XF86ConfLayoutPtr +configureLayoutSection (void) +{ + int scrnum = 0; + parsePrologue (XF86ConfLayoutPtr, XF86ConfLayoutRec) + + ptr->lay_identifier = "X.org Configured"; + + { + XF86ConfInputrefPtr iptr; + + iptr = malloc (sizeof (XF86ConfInputrefRec)); + iptr->list.next = NULL; + iptr->iref_option_lst = NULL; + iptr->iref_inputdev_str = "Mouse0"; + iptr->iref_option_lst = + xf86addNewOption (iptr->iref_option_lst, strdup("CorePointer"), NULL); + ptr->lay_input_lst = (XF86ConfInputrefPtr) + xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr); + } + + { + XF86ConfInputrefPtr iptr; + + iptr = malloc (sizeof (XF86ConfInputrefRec)); + iptr->list.next = NULL; + iptr->iref_option_lst = NULL; + iptr->iref_inputdev_str = "Keyboard0"; + iptr->iref_option_lst = + xf86addNewOption (iptr->iref_option_lst, strdup("CoreKeyboard"), NULL); + ptr->lay_input_lst = (XF86ConfInputrefPtr) + xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr); + } + + for (scrnum = 0; scrnum < nDevToConfig; scrnum++) { + XF86ConfAdjacencyPtr aptr; + + aptr = malloc (sizeof (XF86ConfAdjacencyRec)); + aptr->list.next = NULL; + aptr->adj_x = 0; + aptr->adj_y = 0; + aptr->adj_scrnum = scrnum; + XNFasprintf(&aptr->adj_screen_str, "Screen%d", scrnum); + if (scrnum == 0) { + aptr->adj_where = CONF_ADJ_ABSOLUTE; + aptr->adj_refscreen = NULL; + } + else { + aptr->adj_where = CONF_ADJ_RIGHTOF; + XNFasprintf(&aptr->adj_refscreen, "Screen%d", scrnum - 1); + } + ptr->lay_adjacency_lst = + (XF86ConfAdjacencyPtr)xf86addListItem((glp)ptr->lay_adjacency_lst, + (glp)aptr); + } + + return ptr; +} + +static XF86ConfFlagsPtr +configureFlagsSection (void) +{ + parsePrologue (XF86ConfFlagsPtr, XF86ConfFlagsRec) + + return ptr; +} + +static XF86ConfModulePtr +configureModuleSection (void) +{ + char **elist, **el; + /* Find the list of extension & font modules. */ + const char *esubdirs[] = { + "extensions", + "fonts", + NULL + }; + parsePrologue (XF86ConfModulePtr, XF86ConfModuleRec) + + elist = LoaderListDirs(esubdirs, NULL); + if (elist) { + for (el = elist; *el; el++) { + XF86LoadPtr module; + + module = calloc(1, sizeof(XF86LoadRec)); + module->load_name = *el; + ptr->mod_load_lst = (XF86LoadPtr)xf86addListItem( + (glp)ptr->mod_load_lst, (glp)module); + } + free(elist); + } + + return ptr; +} + +static XF86ConfFilesPtr +configureFilesSection (void) +{ + parsePrologue (XF86ConfFilesPtr, XF86ConfFilesRec) + + if (xf86ModulePath) + ptr->file_modulepath = strdup(xf86ModulePath); + if (defaultFontPath) + ptr->file_fontpath = strdup(defaultFontPath); + + return ptr; +} + +static XF86ConfMonitorPtr +configureMonitorSection (int screennum) +{ + parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec) + + XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum); + ptr->mon_vendor = strdup("Monitor Vendor"); + ptr->mon_modelname = strdup("Monitor Model"); + + return ptr; +} + +/* Initialize Configure Monitor from Detailed Timing Block */ +static void handle_detailed_input(struct detailed_monitor_section *det_mon, + void *data) +{ + XF86ConfMonitorPtr ptr = (XF86ConfMonitorPtr) data; + + switch (det_mon->type) { + case DS_NAME: + ptr->mon_modelname = realloc(ptr->mon_modelname, + strlen((char*)(det_mon->section.name)) + + 1); + strcpy(ptr->mon_modelname, + (char*)(det_mon->section.name)); + break; + case DS_RANGES: + ptr->mon_hsync[ptr->mon_n_hsync].lo = + det_mon->section.ranges.min_h; + ptr->mon_hsync[ptr->mon_n_hsync].hi = + det_mon->section.ranges.max_h; + ptr->mon_n_vrefresh = 1; + ptr->mon_vrefresh[ptr->mon_n_hsync].lo = + det_mon->section.ranges.min_v; + ptr->mon_vrefresh[ptr->mon_n_hsync].hi = + det_mon->section.ranges.max_v; + ptr->mon_n_hsync++; + default: + break; + } +} + +static XF86ConfMonitorPtr +configureDDCMonitorSection (int screennum) +{ + int len, mon_width, mon_height; +#define displaySizeMaxLen 80 + char displaySize_string[displaySizeMaxLen]; + int displaySizeLen; + + parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec) + + XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum); + ptr->mon_vendor = strdup(ConfiguredMonitor->vendor.name); + XNFasprintf(&ptr->mon_modelname, "%x", ConfiguredMonitor->vendor.prod_id); + + /* features in centimetres, we want millimetres */ + mon_width = 10 * ConfiguredMonitor->features.hsize ; + mon_height = 10 * ConfiguredMonitor->features.vsize ; + +#ifdef CONFIGURE_DISPLAYSIZE + ptr->mon_width = mon_width; + ptr->mon_height = mon_height; +#else + if (mon_width && mon_height) { + /* when values available add DisplaySize option AS A COMMENT */ + + displaySizeLen = snprintf(displaySize_string, displaySizeMaxLen, + "\t#DisplaySize\t%5d %5d\t# mm\n", + mon_width, mon_height); + + if (displaySizeLen>0 && displaySizeLen<displaySizeMaxLen) { + if (ptr->mon_comment) { + len = strlen(ptr->mon_comment); + } else { + len = 0; + } + if ((ptr->mon_comment = + realloc(ptr->mon_comment, len + strlen(displaySize_string) + 1))) { + strcpy(ptr->mon_comment + len, displaySize_string); + } + } + } +#endif /* def CONFIGURE_DISPLAYSIZE */ + + xf86ForEachDetailedBlock(ConfiguredMonitor, handle_detailed_input, + ptr); + + if (ConfiguredMonitor->features.dpms) { + ptr->mon_option_lst = xf86addNewOption(ptr->mon_option_lst, strdup("DPMS"), NULL); + } + + return ptr; +} + +void +DoConfigure(void) +{ + int i,j, screennum = -1; + char *home = NULL; + char filename[PATH_MAX]; + char *addslash = ""; + XF86ConfigPtr xf86config = NULL; + char **vlist, **vl; + int *dev2screen; + + vlist = xf86DriverlistFromCompile(); + + if (!vlist) { + ErrorF("Missing output drivers. Configuration failed.\n"); + goto bail; + } + + ErrorF("List of video drivers:\n"); + for (vl = vlist; *vl; vl++) + ErrorF("\t%s\n", *vl); + + /* Load all the drivers that were found. */ + xf86LoadModules(vlist, NULL); + + free(vlist); + + for (i = 0; i < xf86NumDrivers; i++) { + xorgHWFlags flags; + if (!xf86DriverList[i]->driverFunc + || !xf86DriverList[i]->driverFunc(NULL, + GET_REQUIRED_HW_INTERFACES, + &flags) + || NEED_IO_ENABLED(flags)) { + xorgHWAccess = TRUE; + break; + } + } + /* Enable full I/O access */ + if (xorgHWAccess) { + if(!xf86EnableIO()) + /* oops, we have failed */ + xorgHWAccess = FALSE; + } + + /* Create XF86Config file structure */ + xf86config = calloc(1, sizeof(XF86ConfigRec)); + + /* Call all of the probe functions, reporting the results. */ + for (CurrentDriver = 0; CurrentDriver < xf86NumDrivers; CurrentDriver++) { + xorgHWFlags flags; + Bool found_screen; + DriverRec * const drv = xf86DriverList[CurrentDriver]; + + if (!xorgHWAccess) { + if (!drv->driverFunc + || !drv->driverFunc( NULL, GET_REQUIRED_HW_INTERFACES, &flags ) + || NEED_IO_ENABLED(flags)) + continue; + } + + found_screen = xf86CallDriverProbe( drv, TRUE ); + if ( found_screen && drv->Identify ) { + (*drv->Identify)(0); + } + } + + if (nDevToConfig <= 0) { + ErrorF("No devices to configure. Configuration failed.\n"); + goto bail; + } + + /* Add device, monitor and screen sections for detected devices */ + for (screennum = 0; screennum < nDevToConfig; screennum++) { + XF86ConfDevicePtr DevicePtr; + XF86ConfMonitorPtr MonitorPtr; + XF86ConfScreenPtr ScreenPtr; + + DevicePtr = configureDeviceSection(screennum); + xf86config->conf_device_lst = (XF86ConfDevicePtr)xf86addListItem( + (glp)xf86config->conf_device_lst, (glp)DevicePtr); + MonitorPtr = configureMonitorSection(screennum); + xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem( + (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr); + ScreenPtr = configureScreenSection(screennum); + xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem( + (glp)xf86config->conf_screen_lst, (glp)ScreenPtr); + } + + xf86config->conf_files = configureFilesSection(); + xf86config->conf_modules = configureModuleSection(); + xf86config->conf_flags = configureFlagsSection(); + xf86config->conf_videoadaptor_lst = NULL; + xf86config->conf_modes_lst = NULL; + xf86config->conf_vendor_lst = NULL; + xf86config->conf_dri = NULL; + xf86config->conf_input_lst = configureInputSection(); + xf86config->conf_layout_lst = configureLayoutSection(); + + home = getenv("HOME"); + if ((home == NULL) || (home[0] == '\0')) { + home = "/"; + } else { + /* Determine if trailing slash is present or needed */ + int l = strlen(home); + + if (home[l-1] != '/') { + addslash = "/"; + } + } + + snprintf(filename, sizeof(filename), "%s%s" XF86CONFIGFILE ".new", + home, addslash); + + if (xf86writeConfigFile(filename, xf86config) == 0) { + xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n", + filename, strerror(errno)); + goto bail; + } + + xf86DoConfigurePass1 = FALSE; + /* Try to get DDC information filled in */ + xf86ConfigFile = filename; + if (xf86HandleConfigFile(FALSE) != CONFIG_OK) { + goto bail; + } + + xf86DoConfigurePass1 = FALSE; + + dev2screen = xnfcalloc(1,xf86NumDrivers*sizeof(int)); + + { + Bool *driverProbed = xnfcalloc(1,xf86NumDrivers*sizeof(Bool)); + for (screennum = 0; screennum < nDevToConfig; screennum++) { + int k,l,n,oldNumScreens; + + i = DevToConfig[screennum].iDriver; + + if (driverProbed[i]) continue; + driverProbed[i] = TRUE; + + oldNumScreens = xf86NumScreens; + + xf86CallDriverProbe( xf86DriverList[i], FALSE ); + + /* reorder */ + k = screennum > 0 ? screennum : 1; + for (l = oldNumScreens; l < xf86NumScreens; l++) { + /* is screen primary? */ + Bool primary = FALSE; + for (n = 0; n<xf86Screens[l]->numEntities; n++) { + if (xf86IsEntityPrimary(xf86Screens[l]->entityList[n])) { + dev2screen[0] = l; + primary = TRUE; + break; + } + } + if (primary) continue; + /* not primary: assign it to next device of same driver */ + /* + * NOTE: we assume that devices in DevToConfig + * and xf86Screens[] have the same order except + * for the primary device which always comes first. + */ + for (; k < nDevToConfig; k++) { + if (DevToConfig[k].iDriver == i) { + dev2screen[k++] = l; + break; + } + } + } + } + free(driverProbed); + } + + + if (nDevToConfig != xf86NumScreens) { + ErrorF("Number of created screens does not match number of detected" + " devices.\n Configuration failed.\n"); + goto bail; + } + + xf86PostProbe(); + + for (j = 0; j < xf86NumScreens; j++) { + xf86Screens[j]->scrnIndex = j; + } + + xf86freeMonitorList(xf86config->conf_monitor_lst); + xf86config->conf_monitor_lst = NULL; + xf86freeScreenList(xf86config->conf_screen_lst); + xf86config->conf_screen_lst = NULL; + for (j = 0; j < xf86NumScreens; j++) { + XF86ConfMonitorPtr MonitorPtr; + XF86ConfScreenPtr ScreenPtr; + + ConfiguredMonitor = NULL; + + if ((*xf86Screens[dev2screen[j]]->PreInit)(xf86Screens[dev2screen[j]], + PROBE_DETECT) && + ConfiguredMonitor) { + MonitorPtr = configureDDCMonitorSection(j); + } else { + MonitorPtr = configureMonitorSection(j); + } + ScreenPtr = configureScreenSection(j); + xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem( + (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr); + xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem( + (glp)xf86config->conf_screen_lst, (glp)ScreenPtr); + } + + if (xf86writeConfigFile(filename, xf86config) == 0) { + xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n", + filename, strerror(errno)); + goto bail; + } + + ErrorF("\n"); + + if (!foundMouse) { + ErrorF("\n"__XSERVERNAME__" is not able to detect your mouse.\n" + "Edit the file and correct the Device.\n"); + } else { + ErrorF("\n"__XSERVERNAME__" detected your mouse at device %s.\n" + "Please check your config if the mouse is still not\n" + "operational, as by default "__XSERVERNAME__ + " tries to autodetect\n" + "the protocol.\n",DFLT_MOUSE_DEV); + } + + if (xf86NumScreens > 1) { + ErrorF("\n"__XSERVERNAME__ + " has configured a multihead system, please check your config.\n"); + } + + ErrorF("\nYour %s file is %s\n\n", XF86CONFIGFILE ,filename); + ErrorF("To test the server, run 'X -config %s'\n\n", filename); + +bail: + OsCleanup(TRUE); + AbortDDX(EXIT_ERR_CONFIGURE); + fflush(stderr); + exit(0); +} diff --git a/xorg-server/hw/xfree86/common/xf86Events.c b/xorg-server/hw/xfree86/common/xf86Events.c index 72e969e6d..c4a4db9be 100644 --- a/xorg-server/hw/xfree86/common/xf86Events.c +++ b/xorg-server/hw/xfree86/common/xf86Events.c @@ -1,751 +1,751 @@ -/*
- * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
- *
- * 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 Thomas Roell not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission. Thomas Roell makes no representations
- * about the suitability of this software for any purpose. It is provided
- * "as is" without express or implied warranty.
- *
- * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL THOMAS ROELL 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.
- *
- */
-/*
- * Copyright (c) 1994-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/* [JCH-96/01/21] Extended std reverse map to four buttons. */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xpoll.h>
-#include <X11/Xproto.h>
-#include "misc.h"
-#include "compiler.h"
-#include "xf86.h"
-#include "xf86Priv.h"
-#define XF86_OS_PRIVS
-#include "xf86_OSlib.h"
-#include <X11/keysym.h>
-
-#ifdef XFreeXDGA
-#include "dgaproc.h"
-#endif
-
-#include <X11/extensions/XI.h>
-#include <X11/extensions/XIproto.h>
-#include "inputstr.h"
-#include "xf86Xinput.h"
-
-#include "mi.h"
-#include "mipointer.h"
-
-#include "xkbsrv.h"
-#include "xkbstr.h"
-
-#ifdef DPMSExtension
-#include <X11/extensions/dpmsconst.h>
-#include "dpmsproc.h"
-#endif
-
-/*
- * This is a toggling variable:
- * FALSE = No VT switching keys have been pressed last time around
- * TRUE = Possible VT switch Pending
- * (DWH - 12/2/93)
- *
- * This has been generalised to work with Linux and *BSD+syscons (DHD)
- */
-
-Bool VTSwitchEnabled = TRUE; /* Allows run-time disabling for
- *BSD and for avoiding VT
- switches when using the DRI
- automatic full screen mode.*/
-
-extern fd_set EnabledDevices;
-
-#ifdef XF86PM
-extern void (*xf86OSPMClose)(void);
-#endif
-
-static void xf86VTSwitch(void);
-
-/*
- * Allow arbitrary drivers or other XFree86 code to register with our main
- * Wakeup handler.
- */
-typedef struct x_IHRec {
- int fd;
- InputHandlerProc ihproc;
- pointer data;
- Bool enabled;
- struct x_IHRec * next;
-} IHRec, *IHPtr;
-
-static IHPtr InputHandlers = NULL;
-
-
-Bool
-LegalModifier(unsigned int key, DeviceIntPtr pDev)
-{
- return TRUE;
-}
-
-/*
- * TimeSinceLastInputEvent --
- * Function used for screensaver purposes by the os module. Returns the
- * time in milliseconds since there last was any input.
- */
-int
-TimeSinceLastInputEvent(void)
-{
- if (xf86Info.lastEventTime == 0) {
- xf86Info.lastEventTime = GetTimeInMillis();
- }
- return GetTimeInMillis() - xf86Info.lastEventTime;
-}
-
-/*
- * SetTimeSinceLastInputEvent --
- * Set the lastEventTime to now.
- */
-void
-SetTimeSinceLastInputEvent(void)
-{
- xf86Info.lastEventTime = GetTimeInMillis();
-}
-
-/*
- * ProcessInputEvents --
- * Retrieve all waiting input events and pass them to DIX in their
- * correct chronological order. Only reads from the system pointer
- * and keyboard.
- */
-void
-ProcessInputEvents (void)
-{
- int x, y;
-
- mieqProcessInputEvents();
-
- /* FIXME: This is a problem if we have multiple pointers */
- miPointerGetPosition(inputInfo.pointer, &x, &y);
- xf86SetViewport(xf86Info.currentScreen, x, y);
-}
-
-/*
- * Handle keyboard events that cause some kind of "action"
- * (i.e., server termination, video mode changes, VT switches, etc.)
- */
-void
-xf86ProcessActionEvent(ActionEvent action, void *arg)
-{
- DebugF("ProcessActionEvent(%d,%x)\n", (int) action, arg);
- switch (action) {
- case ACTION_TERMINATE:
- if (!xf86Info.dontZap) {
-#ifdef XFreeXDGA
- DGAShutdown();
-#endif
- GiveUp(0);
- }
- break;
- case ACTION_NEXT_MODE:
- if (!xf86Info.dontZoom)
- xf86ZoomViewport(xf86Info.currentScreen, 1);
- break;
- case ACTION_PREV_MODE:
- if (!xf86Info.dontZoom)
- xf86ZoomViewport(xf86Info.currentScreen, -1);
- break;
- case ACTION_SWITCHSCREEN:
- if (VTSwitchEnabled && !xf86Info.dontVTSwitch && arg) {
- int vtno = *((int *) arg);
-
- if (vtno != xf86Info.vtno) {
- if (!xf86VTActivate(vtno)) {
- ErrorF("Failed to switch from vt%02d to vt%02d: %s\n",
- xf86Info.vtno, vtno, strerror(errno));
- }
- }
- }
- break;
- case ACTION_SWITCHSCREEN_NEXT:
- if (VTSwitchEnabled && !xf86Info.dontVTSwitch) {
- if (!xf86VTActivate(xf86Info.vtno + 1)) {
- /* If first try failed, assume this is the last VT and
- * try wrapping around to the first vt.
- */
- if (!xf86VTActivate(1)) {
- ErrorF("Failed to switch from vt%02d to next vt: %s\n",
- xf86Info.vtno, strerror(errno));
- }
- }
- }
- break;
- case ACTION_SWITCHSCREEN_PREV:
- if (VTSwitchEnabled && !xf86Info.dontVTSwitch && xf86Info.vtno > 0) {
- if (!xf86VTActivate(xf86Info.vtno - 1)) {
- /* Don't know what the maximum VT is, so can't wrap around */
- ErrorF("Failed to switch from vt%02d to previous vt: %s\n",
- xf86Info.vtno, strerror(errno));
- }
- }
- break;
- default:
- break;
- }
-}
-
-/*
- * xf86Wakeup --
- * Os wakeup handler.
- */
-
-/* ARGSUSED */
-void
-xf86Wakeup(pointer blockData, int err, pointer pReadmask)
-{
- fd_set* LastSelectMask = (fd_set*)pReadmask;
- fd_set devicesWithInput;
- InputInfoPtr pInfo;
-
- if (err >= 0) {
-
- XFD_ANDSET(&devicesWithInput, LastSelectMask, &EnabledDevices);
- if (XFD_ANYSET(&devicesWithInput)) {
- pInfo = xf86InputDevs;
- while (pInfo) {
- if (pInfo->read_input && pInfo->fd >= 0 &&
- (FD_ISSET(pInfo->fd, &devicesWithInput) != 0)) {
- int sigstate = xf86BlockSIGIO();
-
- /*
- * Remove the descriptior from the set because more than one
- * device may share the same file descriptor.
- */
- FD_CLR(pInfo->fd, &devicesWithInput);
-
- pInfo->read_input(pInfo);
- xf86UnblockSIGIO(sigstate);
- }
- pInfo = pInfo->next;
- }
- }
- }
-
- if (err >= 0) { /* we don't want the handlers called if select() */
- IHPtr ih; /* returned with an error condition, do we? */
-
- for (ih = InputHandlers; ih; ih = ih->next) {
- if (ih->enabled && ih->fd >= 0 && ih->ihproc &&
- (FD_ISSET(ih->fd, ((fd_set *)pReadmask)) != 0)) {
- ih->ihproc(ih->fd, ih->data);
- }
- }
- }
-
- if (xf86VTSwitchPending()) xf86VTSwitch();
-}
-
-
-/*
- * xf86SigioReadInput --
- * signal handler for the SIGIO signal.
- */
-static void
-xf86SigioReadInput(int fd, void *closure)
-{
- int errno_save = errno;
- InputInfoPtr pInfo = closure;
-
- pInfo->read_input(pInfo);
-
- errno = errno_save;
-}
-
-/*
- * xf86AddEnabledDevice --
- *
- */
-void
-xf86AddEnabledDevice(InputInfoPtr pInfo)
-{
- if (!xf86InstallSIGIOHandler (pInfo->fd, xf86SigioReadInput, pInfo)) {
- AddEnabledDevice(pInfo->fd);
- }
-}
-
-/*
- * xf86RemoveEnabledDevice --
- *
- */
-void
-xf86RemoveEnabledDevice(InputInfoPtr pInfo)
-{
- if (!xf86RemoveSIGIOHandler (pInfo->fd)) {
- RemoveEnabledDevice(pInfo->fd);
- }
-}
-
-static int *xf86SignalIntercept = NULL;
-
-void
-xf86InterceptSignals(int *signo)
-{
- if ((xf86SignalIntercept = signo))
- *signo = -1;
-}
-
-static void (*xf86SigIllHandler)(void) = NULL;
-
-void
-xf86InterceptSigIll(void (*sigillhandler)(void))
-{
- xf86SigIllHandler = sigillhandler;
-}
-
-/*
- * xf86SigWrapper --
- * Catch unexpected signals and exit or continue cleanly.
- */
-int
-xf86SigWrapper(int signo)
-{
- if ((signo == SIGILL) && xf86SigIllHandler) {
- (*xf86SigIllHandler)();
- return 0; /* continue */
- }
-
- if (xf86SignalIntercept && (*xf86SignalIntercept < 0)) {
- *xf86SignalIntercept = signo;
- return 0; /* continue */
- }
-
- xf86Info.caughtSignal = TRUE;
- return 1; /* abort */
-}
-
-/*
- * xf86PrintBacktrace --
- * Print a stack backtrace for debugging purposes.
- */
-void
-xf86PrintBacktrace(void)
-{
- xorg_backtrace();
-}
-
-static void
-xf86ReleaseKeys(DeviceIntPtr pDev)
-{
- KeyClassPtr keyc;
- int i, sigstate;
-
- if (!pDev || !pDev->key)
- return;
-
- keyc = pDev->key;
-
- /*
- * Hmm... here is the biggest hack of every time !
- * It may be possible that a switch-vt procedure has finished BEFORE
- * you released all keys neccessary to do this. That peculiar behavior
- * can fool the X-server pretty much, cause it assumes that some keys
- * were not released. TWM may stuck alsmost completly....
- * OK, what we are doing here is after returning from the vt-switch
- * exeplicitely unrelease all keyboard keys before the input-devices
- * are reenabled.
- */
-
- for (i = keyc->xkbInfo->desc->min_key_code;
- i < keyc->xkbInfo->desc->max_key_code;
- i++) {
- if (key_is_down(pDev, i, KEY_POSTED)) {
- sigstate = xf86BlockSIGIO ();
- QueueKeyboardEvents(pDev, KeyRelease, i, NULL);
- xf86UnblockSIGIO(sigstate);
- }
- }
-}
-
-/*
- * xf86VTSwitch --
- * Handle requests for switching the vt.
- */
-static void
-xf86VTSwitch(void)
-{
- int i;
- static int prevSIGIO;
- InputInfoPtr pInfo;
- IHPtr ih;
-
- DebugF("xf86VTSwitch()\n");
-
-#ifdef XFreeXDGA
- if(!DGAVTSwitch())
- return;
-#endif
-
- /*
- * Since all screens are currently all in the same state it is sufficient
- * check the first. This might change in future.
- */
- if (xf86Screens[0]->vtSema) {
-
- DebugF("xf86VTSwitch: Leaving, xf86Exiting is %s\n",
- BOOLTOSTRING((dispatchException & DE_TERMINATE) ? TRUE : FALSE));
-#ifdef DPMSExtension
- if (DPMSPowerLevel != DPMSModeOn)
- DPMSSet(serverClient, DPMSModeOn);
-#endif
- for (i = 0; i < xf86NumScreens; i++) {
- if (!(dispatchException & DE_TERMINATE))
- if (xf86Screens[i]->EnableDisableFBAccess)
- (*xf86Screens[i]->EnableDisableFBAccess) (i, FALSE);
- }
-
- /*
- * Keep the order: Disable Device > LeaveVT
- * EnterVT > EnableDevice
- */
- for (ih = InputHandlers; ih; ih = ih->next)
- xf86DisableInputHandler(ih);
- for (pInfo = xf86InputDevs; pInfo; pInfo = pInfo->next) {
- if (pInfo->dev) {
- xf86ReleaseKeys(pInfo->dev);
- ProcessInputEvents();
- DisableDevice(pInfo->dev, TRUE);
- }
- }
-
- prevSIGIO = xf86BlockSIGIO();
- for (i = 0; i < xf86NumScreens; i++)
- xf86Screens[i]->LeaveVT(i, 0);
-
- xf86AccessLeave(); /* We need this here, otherwise */
-
- if (!xf86VTSwitchAway()) {
- /*
- * switch failed
- */
-
- DebugF("xf86VTSwitch: Leave failed\n");
- xf86AccessEnter();
- for (i = 0; i < xf86NumScreens; i++) {
- if (!xf86Screens[i]->EnterVT(i, 0))
- FatalError("EnterVT failed for screen %d\n", i);
- }
- if (!(dispatchException & DE_TERMINATE)) {
- for (i = 0; i < xf86NumScreens; i++) {
- if (xf86Screens[i]->EnableDisableFBAccess)
- (*xf86Screens[i]->EnableDisableFBAccess) (i, TRUE);
- }
- }
- dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset);
-
- pInfo = xf86InputDevs;
- while (pInfo) {
- if (pInfo->dev)
- EnableDevice(pInfo->dev, TRUE);
- pInfo = pInfo->next;
- }
- for (ih = InputHandlers; ih; ih = ih->next)
- xf86EnableInputHandler(ih);
-
- xf86UnblockSIGIO(prevSIGIO);
-
- } else {
-#ifdef XF86PM
- if (xf86OSPMClose)
- xf86OSPMClose();
- xf86OSPMClose = NULL;
-#endif
-
- for (i = 0; i < xf86NumScreens; i++) {
- /*
- * zero all access functions to
- * trap calls when switched away.
- */
- xf86Screens[i]->vtSema = FALSE;
- }
- if (xorgHWAccess)
- xf86DisableIO();
- }
- } else {
- DebugF("xf86VTSwitch: Entering\n");
- if (!xf86VTSwitchTo()) return;
-
-#ifdef XF86PM
- xf86OSPMClose = xf86OSPMOpen();
-#endif
-
- if (xorgHWAccess)
- xf86EnableIO();
- xf86AccessEnter();
- for (i = 0; i < xf86NumScreens; i++) {
- xf86Screens[i]->vtSema = TRUE;
- if (!xf86Screens[i]->EnterVT(i, 0))
- FatalError("EnterVT failed for screen %d\n", i);
- }
- for (i = 0; i < xf86NumScreens; i++) {
- if (xf86Screens[i]->EnableDisableFBAccess)
- (*xf86Screens[i]->EnableDisableFBAccess)(i, TRUE);
- }
-
- /* Turn screen saver off when switching back */
- dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset);
-
- pInfo = xf86InputDevs;
- while (pInfo) {
- if (pInfo->dev)
- EnableDevice(pInfo->dev, TRUE);
- pInfo = pInfo->next;
- }
-
- for (ih = InputHandlers; ih; ih = ih->next)
- xf86EnableInputHandler(ih);
-
- xf86UnblockSIGIO(prevSIGIO);
- }
-}
-
-
-/* Input handler registration */
-
-static pointer
-addInputHandler(int fd, InputHandlerProc proc, pointer data)
-{
- IHPtr ih;
-
- if (fd < 0 || !proc)
- return NULL;
-
- ih = calloc(sizeof(*ih), 1);
- if (!ih)
- return NULL;
-
- ih->fd = fd;
- ih->ihproc = proc;
- ih->data = data;
- ih->enabled = TRUE;
-
- ih->next = InputHandlers;
- InputHandlers = ih;
-
- return ih;
-}
-
-pointer
-xf86AddInputHandler(int fd, InputHandlerProc proc, pointer data)
-{
- IHPtr ih = addInputHandler(fd, proc, data);
-
- if (ih)
- AddEnabledDevice(fd);
- return ih;
-}
-
-pointer
-xf86AddGeneralHandler(int fd, InputHandlerProc proc, pointer data)
-{
- IHPtr ih = addInputHandler(fd, proc, data);
-
- if (ih)
- AddGeneralSocket(fd);
- return ih;
-}
-
-/**
- * Set the handler for the console's fd. Replaces (and returns) the previous
- * handler or NULL, whichever appropriate.
- * proc may be NULL if the server should not handle events on the console.
- */
-InputHandlerProc
-xf86SetConsoleHandler(InputHandlerProc proc, pointer data)
-{
- static InputHandlerProc handler = NULL;
- InputHandlerProc old_handler = handler;
-
- if (old_handler)
- xf86RemoveGeneralHandler(old_handler);
-
- xf86AddGeneralHandler(xf86Info.consoleFd, proc, data);
- handler = proc;
-
- return old_handler;
-}
-
-static void
-removeInputHandler(IHPtr ih)
-{
- IHPtr p;
-
- if (ih == InputHandlers)
- InputHandlers = ih->next;
- else {
- p = InputHandlers;
- while (p && p->next != ih)
- p = p->next;
- if (ih)
- p->next = ih->next;
- }
- free(ih);
-}
-
-int
-xf86RemoveInputHandler(pointer handler)
-{
- IHPtr ih;
- int fd;
-
- if (!handler)
- return -1;
-
- ih = handler;
- fd = ih->fd;
-
- if (ih->fd >= 0)
- RemoveEnabledDevice(ih->fd);
- removeInputHandler(ih);
-
- return fd;
-}
-
-int
-xf86RemoveGeneralHandler(pointer handler)
-{
- IHPtr ih;
- int fd;
-
- if (!handler)
- return -1;
-
- ih = handler;
- fd = ih->fd;
-
- if (ih->fd >= 0)
- RemoveGeneralSocket(ih->fd);
- removeInputHandler(ih);
-
- return fd;
-}
-
-void
-xf86DisableInputHandler(pointer handler)
-{
- IHPtr ih;
-
- if (!handler)
- return;
-
- ih = handler;
- ih->enabled = FALSE;
- if (ih->fd >= 0)
- RemoveEnabledDevice(ih->fd);
-}
-
-void
-xf86DisableGeneralHandler(pointer handler)
-{
- IHPtr ih;
-
- if (!handler)
- return;
-
- ih = handler;
- ih->enabled = FALSE;
- if (ih->fd >= 0)
- RemoveGeneralSocket(ih->fd);
-}
-
-void
-xf86EnableInputHandler(pointer handler)
-{
- IHPtr ih;
-
- if (!handler)
- return;
-
- ih = handler;
- ih->enabled = TRUE;
- if (ih->fd >= 0)
- AddEnabledDevice(ih->fd);
-}
-
-void
-xf86EnableGeneralHandler(pointer handler)
-{
- IHPtr ih;
-
- if (!handler)
- return;
-
- ih = handler;
- ih->enabled = TRUE;
- if (ih->fd >= 0)
- AddGeneralSocket(ih->fd);
-}
-
-/*
- * As used currently by the DRI, the return value is ignored.
- */
-Bool
-xf86EnableVTSwitch(Bool new)
-{
- static Bool def = TRUE;
- Bool old;
-
- old = VTSwitchEnabled;
- if (!new) {
- /* Disable VT switching */
- def = VTSwitchEnabled;
- VTSwitchEnabled = FALSE;
- } else {
- /* Restore VT switching to default */
- VTSwitchEnabled = def;
- }
- return old;
-}
-
-void
-DDXRingBell(int volume, int pitch, int duration) {
- xf86OSRingBell(volume, pitch, duration);
-}
+/* + * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany. + * + * 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 Thomas Roell not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Thomas Roell makes no representations + * about the suitability of this software for any purpose. It is provided + * "as is" without express or implied warranty. + * + * THOMAS ROELL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL THOMAS ROELL 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. + * + */ +/* + * Copyright (c) 1994-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* [JCH-96/01/21] Extended std reverse map to four buttons. */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <X11/X.h> +#include <X11/Xpoll.h> +#include <X11/Xproto.h> +#include "misc.h" +#include "compiler.h" +#include "xf86.h" +#include "xf86Priv.h" +#define XF86_OS_PRIVS +#include "xf86_OSlib.h" +#include <X11/keysym.h> + +#ifdef XFreeXDGA +#include "dgaproc.h" +#endif + +#include <X11/extensions/XI.h> +#include <X11/extensions/XIproto.h> +#include "inputstr.h" +#include "xf86Xinput.h" + +#include "mi.h" +#include "mipointer.h" + +#include "xkbsrv.h" +#include "xkbstr.h" + +#ifdef DPMSExtension +#include <X11/extensions/dpmsconst.h> +#include "dpmsproc.h" +#endif + +/* + * This is a toggling variable: + * FALSE = No VT switching keys have been pressed last time around + * TRUE = Possible VT switch Pending + * (DWH - 12/2/93) + * + * This has been generalised to work with Linux and *BSD+syscons (DHD) + */ + +Bool VTSwitchEnabled = TRUE; /* Allows run-time disabling for + *BSD and for avoiding VT + switches when using the DRI + automatic full screen mode.*/ + +extern fd_set EnabledDevices; + +#ifdef XF86PM +extern void (*xf86OSPMClose)(void); +#endif + +static void xf86VTSwitch(void); + +/* + * Allow arbitrary drivers or other XFree86 code to register with our main + * Wakeup handler. + */ +typedef struct x_IHRec { + int fd; + InputHandlerProc ihproc; + pointer data; + Bool enabled; + struct x_IHRec * next; +} IHRec, *IHPtr; + +static IHPtr InputHandlers = NULL; + + +Bool +LegalModifier(unsigned int key, DeviceIntPtr pDev) +{ + return TRUE; +} + +/* + * TimeSinceLastInputEvent -- + * Function used for screensaver purposes by the os module. Returns the + * time in milliseconds since there last was any input. + */ +int +TimeSinceLastInputEvent(void) +{ + if (xf86Info.lastEventTime == 0) { + xf86Info.lastEventTime = GetTimeInMillis(); + } + return GetTimeInMillis() - xf86Info.lastEventTime; +} + +/* + * SetTimeSinceLastInputEvent -- + * Set the lastEventTime to now. + */ +void +SetTimeSinceLastInputEvent(void) +{ + xf86Info.lastEventTime = GetTimeInMillis(); +} + +/* + * ProcessInputEvents -- + * Retrieve all waiting input events and pass them to DIX in their + * correct chronological order. Only reads from the system pointer + * and keyboard. + */ +void +ProcessInputEvents (void) +{ + int x, y; + + mieqProcessInputEvents(); + + /* FIXME: This is a problem if we have multiple pointers */ + miPointerGetPosition(inputInfo.pointer, &x, &y); + xf86SetViewport(xf86Info.currentScreen, x, y); +} + +/* + * Handle keyboard events that cause some kind of "action" + * (i.e., server termination, video mode changes, VT switches, etc.) + */ +void +xf86ProcessActionEvent(ActionEvent action, void *arg) +{ + DebugF("ProcessActionEvent(%d,%x)\n", (int) action, arg); + switch (action) { + case ACTION_TERMINATE: + if (!xf86Info.dontZap) { +#ifdef XFreeXDGA + DGAShutdown(); +#endif + GiveUp(0); + } + break; + case ACTION_NEXT_MODE: + if (!xf86Info.dontZoom) + xf86ZoomViewport(xf86Info.currentScreen, 1); + break; + case ACTION_PREV_MODE: + if (!xf86Info.dontZoom) + xf86ZoomViewport(xf86Info.currentScreen, -1); + break; + case ACTION_SWITCHSCREEN: + if (VTSwitchEnabled && !xf86Info.dontVTSwitch && arg) { + int vtno = *((int *) arg); + + if (vtno != xf86Info.vtno) { + if (!xf86VTActivate(vtno)) { + ErrorF("Failed to switch from vt%02d to vt%02d: %s\n", + xf86Info.vtno, vtno, strerror(errno)); + } + } + } + break; + case ACTION_SWITCHSCREEN_NEXT: + if (VTSwitchEnabled && !xf86Info.dontVTSwitch) { + if (!xf86VTActivate(xf86Info.vtno + 1)) { + /* If first try failed, assume this is the last VT and + * try wrapping around to the first vt. + */ + if (!xf86VTActivate(1)) { + ErrorF("Failed to switch from vt%02d to next vt: %s\n", + xf86Info.vtno, strerror(errno)); + } + } + } + break; + case ACTION_SWITCHSCREEN_PREV: + if (VTSwitchEnabled && !xf86Info.dontVTSwitch && xf86Info.vtno > 0) { + if (!xf86VTActivate(xf86Info.vtno - 1)) { + /* Don't know what the maximum VT is, so can't wrap around */ + ErrorF("Failed to switch from vt%02d to previous vt: %s\n", + xf86Info.vtno, strerror(errno)); + } + } + break; + default: + break; + } +} + +/* + * xf86Wakeup -- + * Os wakeup handler. + */ + +/* ARGSUSED */ +void +xf86Wakeup(pointer blockData, int err, pointer pReadmask) +{ + fd_set* LastSelectMask = (fd_set*)pReadmask; + fd_set devicesWithInput; + InputInfoPtr pInfo; + + if (err >= 0) { + + XFD_ANDSET(&devicesWithInput, LastSelectMask, &EnabledDevices); + if (XFD_ANYSET(&devicesWithInput)) { + pInfo = xf86InputDevs; + while (pInfo) { + if (pInfo->read_input && pInfo->fd >= 0 && + (FD_ISSET(pInfo->fd, &devicesWithInput) != 0)) { + int sigstate = xf86BlockSIGIO(); + + /* + * Remove the descriptior from the set because more than one + * device may share the same file descriptor. + */ + FD_CLR(pInfo->fd, &devicesWithInput); + + pInfo->read_input(pInfo); + xf86UnblockSIGIO(sigstate); + } + pInfo = pInfo->next; + } + } + } + + if (err >= 0) { /* we don't want the handlers called if select() */ + IHPtr ih; /* returned with an error condition, do we? */ + + for (ih = InputHandlers; ih; ih = ih->next) { + if (ih->enabled && ih->fd >= 0 && ih->ihproc && + (FD_ISSET(ih->fd, ((fd_set *)pReadmask)) != 0)) { + ih->ihproc(ih->fd, ih->data); + } + } + } + + if (xf86VTSwitchPending()) xf86VTSwitch(); +} + + +/* + * xf86SigioReadInput -- + * signal handler for the SIGIO signal. + */ +static void +xf86SigioReadInput(int fd, void *closure) +{ + int errno_save = errno; + InputInfoPtr pInfo = closure; + + pInfo->read_input(pInfo); + + errno = errno_save; +} + +/* + * xf86AddEnabledDevice -- + * + */ +void +xf86AddEnabledDevice(InputInfoPtr pInfo) +{ + if (!xf86InstallSIGIOHandler (pInfo->fd, xf86SigioReadInput, pInfo)) { + AddEnabledDevice(pInfo->fd); + } +} + +/* + * xf86RemoveEnabledDevice -- + * + */ +void +xf86RemoveEnabledDevice(InputInfoPtr pInfo) +{ + if (!xf86RemoveSIGIOHandler (pInfo->fd)) { + RemoveEnabledDevice(pInfo->fd); + } +} + +static int *xf86SignalIntercept = NULL; + +void +xf86InterceptSignals(int *signo) +{ + if ((xf86SignalIntercept = signo)) + *signo = -1; +} + +static void (*xf86SigIllHandler)(void) = NULL; + +void +xf86InterceptSigIll(void (*sigillhandler)(void)) +{ + xf86SigIllHandler = sigillhandler; +} + +/* + * xf86SigWrapper -- + * Catch unexpected signals and exit or continue cleanly. + */ +int +xf86SigWrapper(int signo) +{ + if ((signo == SIGILL) && xf86SigIllHandler) { + (*xf86SigIllHandler)(); + return 0; /* continue */ + } + + if (xf86SignalIntercept && (*xf86SignalIntercept < 0)) { + *xf86SignalIntercept = signo; + return 0; /* continue */ + } + + xf86Info.caughtSignal = TRUE; + return 1; /* abort */ +} + +/* + * xf86PrintBacktrace -- + * Print a stack backtrace for debugging purposes. + */ +void +xf86PrintBacktrace(void) +{ + xorg_backtrace(); +} + +static void +xf86ReleaseKeys(DeviceIntPtr pDev) +{ + KeyClassPtr keyc; + int i, sigstate; + + if (!pDev || !pDev->key) + return; + + keyc = pDev->key; + + /* + * Hmm... here is the biggest hack of every time ! + * It may be possible that a switch-vt procedure has finished BEFORE + * you released all keys neccessary to do this. That peculiar behavior + * can fool the X-server pretty much, cause it assumes that some keys + * were not released. TWM may stuck alsmost completly.... + * OK, what we are doing here is after returning from the vt-switch + * exeplicitely unrelease all keyboard keys before the input-devices + * are reenabled. + */ + + for (i = keyc->xkbInfo->desc->min_key_code; + i < keyc->xkbInfo->desc->max_key_code; + i++) { + if (key_is_down(pDev, i, KEY_POSTED)) { + sigstate = xf86BlockSIGIO (); + QueueKeyboardEvents(pDev, KeyRelease, i, NULL); + xf86UnblockSIGIO(sigstate); + } + } +} + +/* + * xf86VTSwitch -- + * Handle requests for switching the vt. + */ +static void +xf86VTSwitch(void) +{ + int i; + static int prevSIGIO; + InputInfoPtr pInfo; + IHPtr ih; + + DebugF("xf86VTSwitch()\n"); + +#ifdef XFreeXDGA + if(!DGAVTSwitch()) + return; +#endif + + /* + * Since all screens are currently all in the same state it is sufficient + * check the first. This might change in future. + */ + if (xf86Screens[0]->vtSema) { + + DebugF("xf86VTSwitch: Leaving, xf86Exiting is %s\n", + BOOLTOSTRING((dispatchException & DE_TERMINATE) ? TRUE : FALSE)); +#ifdef DPMSExtension + if (DPMSPowerLevel != DPMSModeOn) + DPMSSet(serverClient, DPMSModeOn); +#endif + for (i = 0; i < xf86NumScreens; i++) { + if (!(dispatchException & DE_TERMINATE)) + if (xf86Screens[i]->EnableDisableFBAccess) + (*xf86Screens[i]->EnableDisableFBAccess) (i, FALSE); + } + + /* + * Keep the order: Disable Device > LeaveVT + * EnterVT > EnableDevice + */ + for (ih = InputHandlers; ih; ih = ih->next) + xf86DisableInputHandler(ih); + for (pInfo = xf86InputDevs; pInfo; pInfo = pInfo->next) { + if (pInfo->dev) { + xf86ReleaseKeys(pInfo->dev); + ProcessInputEvents(); + DisableDevice(pInfo->dev, TRUE); + } + } + + prevSIGIO = xf86BlockSIGIO(); + for (i = 0; i < xf86NumScreens; i++) + xf86Screens[i]->LeaveVT(i, 0); + + xf86AccessLeave(); /* We need this here, otherwise */ + + if (!xf86VTSwitchAway()) { + /* + * switch failed + */ + + DebugF("xf86VTSwitch: Leave failed\n"); + xf86AccessEnter(); + for (i = 0; i < xf86NumScreens; i++) { + if (!xf86Screens[i]->EnterVT(i, 0)) + FatalError("EnterVT failed for screen %d\n", i); + } + if (!(dispatchException & DE_TERMINATE)) { + for (i = 0; i < xf86NumScreens; i++) { + if (xf86Screens[i]->EnableDisableFBAccess) + (*xf86Screens[i]->EnableDisableFBAccess) (i, TRUE); + } + } + dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset); + + pInfo = xf86InputDevs; + while (pInfo) { + if (pInfo->dev) + EnableDevice(pInfo->dev, TRUE); + pInfo = pInfo->next; + } + for (ih = InputHandlers; ih; ih = ih->next) + xf86EnableInputHandler(ih); + + xf86UnblockSIGIO(prevSIGIO); + + } else { +#ifdef XF86PM + if (xf86OSPMClose) + xf86OSPMClose(); + xf86OSPMClose = NULL; +#endif + + for (i = 0; i < xf86NumScreens; i++) { + /* + * zero all access functions to + * trap calls when switched away. + */ + xf86Screens[i]->vtSema = FALSE; + } + if (xorgHWAccess) + xf86DisableIO(); + } + } else { + DebugF("xf86VTSwitch: Entering\n"); + if (!xf86VTSwitchTo()) return; + +#ifdef XF86PM + xf86OSPMClose = xf86OSPMOpen(); +#endif + + if (xorgHWAccess) + xf86EnableIO(); + xf86AccessEnter(); + for (i = 0; i < xf86NumScreens; i++) { + xf86Screens[i]->vtSema = TRUE; + if (!xf86Screens[i]->EnterVT(i, 0)) + FatalError("EnterVT failed for screen %d\n", i); + } + for (i = 0; i < xf86NumScreens; i++) { + if (xf86Screens[i]->EnableDisableFBAccess) + (*xf86Screens[i]->EnableDisableFBAccess)(i, TRUE); + } + + /* Turn screen saver off when switching back */ + dixSaveScreens(serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset); + + pInfo = xf86InputDevs; + while (pInfo) { + if (pInfo->dev) + EnableDevice(pInfo->dev, TRUE); + pInfo = pInfo->next; + } + + for (ih = InputHandlers; ih; ih = ih->next) + xf86EnableInputHandler(ih); + + xf86UnblockSIGIO(prevSIGIO); + } +} + + +/* Input handler registration */ + +static pointer +addInputHandler(int fd, InputHandlerProc proc, pointer data) +{ + IHPtr ih; + + if (fd < 0 || !proc) + return NULL; + + ih = calloc(sizeof(*ih), 1); + if (!ih) + return NULL; + + ih->fd = fd; + ih->ihproc = proc; + ih->data = data; + ih->enabled = TRUE; + + ih->next = InputHandlers; + InputHandlers = ih; + + return ih; +} + +pointer +xf86AddInputHandler(int fd, InputHandlerProc proc, pointer data) +{ + IHPtr ih = addInputHandler(fd, proc, data); + + if (ih) + AddEnabledDevice(fd); + return ih; +} + +pointer +xf86AddGeneralHandler(int fd, InputHandlerProc proc, pointer data) +{ + IHPtr ih = addInputHandler(fd, proc, data); + + if (ih) + AddGeneralSocket(fd); + return ih; +} + +/** + * Set the handler for the console's fd. Replaces (and returns) the previous + * handler or NULL, whichever appropriate. + * proc may be NULL if the server should not handle events on the console. + */ +InputHandlerProc +xf86SetConsoleHandler(InputHandlerProc proc, pointer data) +{ + static InputHandlerProc handler = NULL; + InputHandlerProc old_handler = handler; + + if (old_handler) + xf86RemoveGeneralHandler(old_handler); + + xf86AddGeneralHandler(xf86Info.consoleFd, proc, data); + handler = proc; + + return old_handler; +} + +static void +removeInputHandler(IHPtr ih) +{ + IHPtr p; + + if (ih == InputHandlers) + InputHandlers = ih->next; + else { + p = InputHandlers; + while (p && p->next != ih) + p = p->next; + if (ih) + p->next = ih->next; + } + free(ih); +} + +int +xf86RemoveInputHandler(pointer handler) +{ + IHPtr ih; + int fd; + + if (!handler) + return -1; + + ih = handler; + fd = ih->fd; + + if (ih->fd >= 0) + RemoveEnabledDevice(ih->fd); + removeInputHandler(ih); + + return fd; +} + +int +xf86RemoveGeneralHandler(pointer handler) +{ + IHPtr ih; + int fd; + + if (!handler) + return -1; + + ih = handler; + fd = ih->fd; + + if (ih->fd >= 0) + RemoveGeneralSocket(ih->fd); + removeInputHandler(ih); + + return fd; +} + +void +xf86DisableInputHandler(pointer handler) +{ + IHPtr ih; + + if (!handler) + return; + + ih = handler; + ih->enabled = FALSE; + if (ih->fd >= 0) + RemoveEnabledDevice(ih->fd); +} + +void +xf86DisableGeneralHandler(pointer handler) +{ + IHPtr ih; + + if (!handler) + return; + + ih = handler; + ih->enabled = FALSE; + if (ih->fd >= 0) + RemoveGeneralSocket(ih->fd); +} + +void +xf86EnableInputHandler(pointer handler) +{ + IHPtr ih; + + if (!handler) + return; + + ih = handler; + ih->enabled = TRUE; + if (ih->fd >= 0) + AddEnabledDevice(ih->fd); +} + +void +xf86EnableGeneralHandler(pointer handler) +{ + IHPtr ih; + + if (!handler) + return; + + ih = handler; + ih->enabled = TRUE; + if (ih->fd >= 0) + AddGeneralSocket(ih->fd); +} + +/* + * As used currently by the DRI, the return value is ignored. + */ +Bool +xf86EnableVTSwitch(Bool new) +{ + static Bool def = TRUE; + Bool old; + + old = VTSwitchEnabled; + if (!new) { + /* Disable VT switching */ + def = VTSwitchEnabled; + VTSwitchEnabled = FALSE; + } else { + /* Restore VT switching to default */ + VTSwitchEnabled = def; + } + return old; +} + +void +DDXRingBell(int volume, int pitch, int duration) { + xf86OSRingBell(volume, pitch, duration); +} diff --git a/xorg-server/hw/xfree86/common/xf86Helper.c b/xorg-server/hw/xfree86/common/xf86Helper.c index a210df042..f8e6c8b41 100644 --- a/xorg-server/hw/xfree86/common/xf86Helper.c +++ b/xorg-server/hw/xfree86/common/xf86Helper.c @@ -1,1949 +1,1949 @@ -/*
- * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/*
- * Authors: Dirk Hohndel <hohndel@XFree86.Org>
- * David Dawes <dawes@XFree86.Org>
- * ... and others
- *
- * This file includes the helper functions that the server provides for
- * different drivers.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include "os.h"
-#include "servermd.h"
-#include "pixmapstr.h"
-#include "windowstr.h"
-#include "propertyst.h"
-#include "gcstruct.h"
-#include "loaderProcs.h"
-#include "xf86.h"
-#include "xf86Priv.h"
-#include "xf86_OSlib.h"
-#include "micmap.h"
-#include "xf86DDC.h"
-#include "xf86Xinput.h"
-#include "xf86InPriv.h"
-#include "mivalidate.h"
-#include "xf86Crtc.h"
-
-/* For xf86GetClocks */
-#if defined(CSRG_BASED) || defined(__GNU__)
-#define HAS_SETPRIORITY
-#include <sys/resource.h>
-#endif
-
-static int xf86ScrnInfoPrivateCount = 0;
-
-
-/* Add a pointer to a new DriverRec to xf86DriverList */
-
-void
-xf86AddDriver(DriverPtr driver, pointer module, int flags)
-{
- /* Don't add null entries */
- if (!driver)
- return;
-
- if (xf86DriverList == NULL)
- xf86NumDrivers = 0;
-
- xf86NumDrivers++;
- xf86DriverList = xnfrealloc(xf86DriverList,
- xf86NumDrivers * sizeof(DriverPtr));
- xf86DriverList[xf86NumDrivers - 1] = xnfalloc(sizeof(DriverRec));
- if (flags & HaveDriverFuncs)
- *xf86DriverList[xf86NumDrivers - 1] = *driver;
- else {
- (void) memset( xf86DriverList[xf86NumDrivers - 1], 0,
- sizeof( DriverRec ) );
- (void) memcpy( xf86DriverList[xf86NumDrivers - 1], driver,
- sizeof(DriverRec1));
-
- }
- xf86DriverList[xf86NumDrivers - 1]->module = module;
- xf86DriverList[xf86NumDrivers - 1]->refCount = 0;
-}
-
-void
-xf86DeleteDriver(int drvIndex)
-{
- if (xf86DriverList[drvIndex]
- && (!xf86DriverHasEntities(xf86DriverList[drvIndex]))) {
- if (xf86DriverList[drvIndex]->module)
- UnloadModule(xf86DriverList[drvIndex]->module);
- free(xf86DriverList[drvIndex]);
- xf86DriverList[drvIndex] = NULL;
- }
-}
-
-/* Add a pointer to a new InputDriverRec to xf86InputDriverList */
-
-void
-xf86AddInputDriver(InputDriverPtr driver, pointer module, int flags)
-{
- /* Don't add null entries */
- if (!driver)
- return;
-
- if (xf86InputDriverList == NULL)
- xf86NumInputDrivers = 0;
-
- xf86NumInputDrivers++;
- xf86InputDriverList = xnfrealloc(xf86InputDriverList,
- xf86NumInputDrivers * sizeof(InputDriverPtr));
- xf86InputDriverList[xf86NumInputDrivers - 1] =
- xnfalloc(sizeof(InputDriverRec));
- *xf86InputDriverList[xf86NumInputDrivers - 1] = *driver;
- xf86InputDriverList[xf86NumInputDrivers - 1]->module = module;
-}
-
-void
-xf86DeleteInputDriver(int drvIndex)
-{
- if (xf86InputDriverList[drvIndex] && xf86InputDriverList[drvIndex]->module)
- UnloadModule(xf86InputDriverList[drvIndex]->module);
- free(xf86InputDriverList[drvIndex]);
- xf86InputDriverList[drvIndex] = NULL;
-}
-
-InputDriverPtr
-xf86LookupInputDriver(const char *name)
-{
- int i;
-
- for (i = 0; i < xf86NumInputDrivers; i++) {
- if (xf86InputDriverList[i] && xf86InputDriverList[i]->driverName &&
- xf86NameCmp(name, xf86InputDriverList[i]->driverName) == 0)
- return xf86InputDriverList[i];
- }
- return NULL;
-}
-
-InputInfoPtr
-xf86LookupInput(const char *name)
-{
- InputInfoPtr p;
-
- for (p = xf86InputDevs; p != NULL; p = p->next) {
- if (strcmp(name, p->name) == 0)
- return p;
- }
-
- return NULL;
-}
-
-/* Allocate a new ScrnInfoRec in xf86Screens */
-
-ScrnInfoPtr
-xf86AllocateScreen(DriverPtr drv, int flags)
-{
- int i;
-
- if (xf86Screens == NULL)
- xf86NumScreens = 0;
-
- i = xf86NumScreens++;
- xf86Screens = xnfrealloc(xf86Screens, xf86NumScreens * sizeof(ScrnInfoPtr));
- xf86Screens[i] = xnfcalloc(sizeof(ScrnInfoRec), 1);
- xf86Screens[i]->scrnIndex = i; /* Changes when a screen is removed */
- xf86Screens[i]->origIndex = i; /* This never changes */
- xf86Screens[i]->privates = xnfcalloc(sizeof(DevUnion),
- xf86ScrnInfoPrivateCount);
- /*
- * EnableDisableFBAccess now gets initialized in InitOutput()
- * xf86Screens[i]->EnableDisableFBAccess = xf86EnableDisableFBAccess;
- */
-
- xf86Screens[i]->drv = drv;
- drv->refCount++;
- xf86Screens[i]->module = DuplicateModule(drv->module, NULL);
-
- xf86Screens[i]->DriverFunc = drv->driverFunc;
-
- return xf86Screens[i];
-}
-
-
-/*
- * Remove an entry from xf86Screens. Ideally it should free all allocated
- * data. To do this properly may require a driver hook.
- */
-
-void
-xf86DeleteScreen(int scrnIndex, int flags)
-{
- ScrnInfoPtr pScrn;
- int i;
-
- /* First check if the screen is valid */
- if (xf86NumScreens == 0 || xf86Screens == NULL)
- return;
-
- if (scrnIndex > xf86NumScreens - 1)
- return;
-
- if (!(pScrn = xf86Screens[scrnIndex]))
- return;
-
- /* If a FreeScreen function is defined, call it here */
- if (pScrn->FreeScreen != NULL)
- pScrn->FreeScreen(scrnIndex, 0);
-
- while (pScrn->modes)
- xf86DeleteMode(&pScrn->modes, pScrn->modes);
-
- while (pScrn->modePool)
- xf86DeleteMode(&pScrn->modePool, pScrn->modePool);
-
- xf86OptionListFree(pScrn->options);
-
- if (pScrn->module)
- UnloadModule(pScrn->module);
-
- if (pScrn->drv)
- pScrn->drv->refCount--;
-
- free(pScrn->privates);
-
- xf86ClearEntityListForScreen(scrnIndex);
-
- free(pScrn);
-
- /* Move the other entries down, updating their scrnIndex fields */
-
- xf86NumScreens--;
-
- for (i = scrnIndex; i < xf86NumScreens; i++) {
- xf86Screens[i] = xf86Screens[i + 1];
- xf86Screens[i]->scrnIndex = i;
- /* Also need to take care of the screen layout settings */
- }
-}
-
-/*
- * Allocate a private in ScrnInfoRec.
- */
-
-int
-xf86AllocateScrnInfoPrivateIndex(void)
-{
- int idx, i;
- ScrnInfoPtr pScr;
- DevUnion *nprivs;
-
- idx = xf86ScrnInfoPrivateCount++;
- for (i = 0; i < xf86NumScreens; i++) {
- pScr = xf86Screens[i];
- nprivs = xnfrealloc(pScr->privates,
- xf86ScrnInfoPrivateCount * sizeof(DevUnion));
- /* Zero the new private */
- memset(&nprivs[idx], 0, sizeof(DevUnion));
- pScr->privates = nprivs;
- }
- return idx;
-}
-
-Bool
-xf86AddPixFormat(ScrnInfoPtr pScrn, int depth, int bpp, int pad)
-{
- int i;
-
- if (pScrn->numFormats >= MAXFORMATS)
- return FALSE;
-
- if (bpp <= 0) {
- if (depth == 1)
- bpp = 1;
- else if (depth <= 8)
- bpp = 8;
- else if (depth <= 16)
- bpp = 16;
- else if (depth <= 32)
- bpp = 32;
- else
- return FALSE;
- }
- if (pad <= 0)
- pad = BITMAP_SCANLINE_PAD;
-
- i = pScrn->numFormats++;
- pScrn->formats[i].depth = depth;
- pScrn->formats[i].bitsPerPixel = bpp;
- pScrn->formats[i].scanlinePad = pad;
- return TRUE;
-}
-
-/*
- * Set the depth we are using based on (in the following order of preference):
- * - values given on the command line
- * - values given in the config file
- * - values provided by the driver
- * - an overall default when nothing else is given
- *
- * Also find a Display subsection matching the depth/bpp found.
- *
- * Sets the following ScrnInfoRec fields:
- * bitsPerPixel, pixmap24, depth, display, imageByteOrder,
- * bitmapScanlinePad, bitmapScanlineUnit, bitmapBitOrder, numFormats,
- * formats, fbFormat.
- */
-
-/* Can the screen handle 24 bpp pixmaps */
-#define DO_PIX24(f) ((f & Support24bppFb) || \
- ((f & Support32bppFb) && (f & SupportConvert24to32)))
-
-/* Can the screen handle 32 bpp pixmaps */
-#define DO_PIX32(f) ((f & Support32bppFb) || \
- ((f & Support24bppFb) && (f & SupportConvert32to24)))
-
-/* Does the screen prefer 32bpp fb for 24bpp pixmaps */
-#define CHOOSE32FOR24(f) ((f & Support32bppFb) && (f & SupportConvert24to32) \
- && (f & PreferConvert24to32))
-
-/* Does the screen prefer 24bpp fb for 32bpp pixmaps */
-#define CHOOSE24FOR32(f) ((f & Support24bppFb) && (f & SupportConvert32to24) \
- && (f & PreferConvert32to24))
-
-/* Can the screen handle 32bpp pixmaps for 24bpp fb */
-#define DO_PIX32FOR24(f) ((f & Support24bppFb) && (f & SupportConvert32to24))
-
-/* Can the screen handle 24bpp pixmaps for 32bpp fb */
-#define DO_PIX24FOR32(f) ((f & Support32bppFb) && (f & SupportConvert24to32))
-
-#ifndef GLOBAL_DEFAULT_DEPTH
-#define GLOBAL_DEFAULT_DEPTH 24
-#endif
-
-Bool
-xf86SetDepthBpp(ScrnInfoPtr scrp, int depth, int dummy, int fbbpp,
- int depth24flags)
-{
- int i;
- DispPtr disp;
- Pix24Flags pix24 = xf86Info.pixmap24;
- Bool nomatch = FALSE;
-
- scrp->bitsPerPixel = -1;
- scrp->depth = -1;
- scrp->pixmap24 = Pix24DontCare;
- scrp->bitsPerPixelFrom = X_DEFAULT;
- scrp->depthFrom = X_DEFAULT;
-
- if (xf86FbBpp > 0) {
- scrp->bitsPerPixel = xf86FbBpp;
- scrp->bitsPerPixelFrom = X_CMDLINE;
- }
-
- if (xf86Depth > 0) {
- scrp->depth = xf86Depth;
- scrp->depthFrom = X_CMDLINE;
- }
-
- if (xf86FbBpp < 0 && xf86Depth < 0) {
- if (scrp->confScreen->defaultfbbpp > 0) {
- scrp->bitsPerPixel = scrp->confScreen->defaultfbbpp;
- scrp->bitsPerPixelFrom = X_CONFIG;
- }
- if (scrp->confScreen->defaultdepth > 0) {
- scrp->depth = scrp->confScreen->defaultdepth;
- scrp->depthFrom = X_CONFIG;
- }
-
- if (scrp->confScreen->defaultfbbpp <= 0 &&
- scrp->confScreen->defaultdepth <= 0) {
- /*
- * Check for DefaultDepth and DefaultFbBpp options in the
- * Device sections.
- */
- int i;
- GDevPtr device;
- Bool found = FALSE;
-
- for (i = 0; i < scrp->numEntities; i++) {
- device = xf86GetDevFromEntity(scrp->entityList[i],
- scrp->entityInstanceList[i]);
- if (device && device->options) {
- if (xf86FindOption(device->options, "DefaultDepth")) {
- scrp->depth = xf86SetIntOption(device->options,
- "DefaultDepth", -1);
- scrp->depthFrom = X_CONFIG;
- found = TRUE;
- }
- if (xf86FindOption(device->options, "DefaultFbBpp")) {
- scrp->bitsPerPixel = xf86SetIntOption(device->options,
- "DefaultFbBpp",
- -1);
- scrp->bitsPerPixelFrom = X_CONFIG;
- found = TRUE;
- }
- }
- if (found)
- break;
- }
- }
- }
-
- /* If none of these is set, pick a default */
- if (scrp->bitsPerPixel < 0 && scrp->depth < 0) {
- if (fbbpp > 0 || depth > 0) {
- if (fbbpp > 0)
- scrp->bitsPerPixel = fbbpp;
- if (depth > 0)
- scrp->depth = depth;
- } else {
- scrp->depth = GLOBAL_DEFAULT_DEPTH;
- }
- }
-
- /* If any are not given, determine a default for the others */
-
- if (scrp->bitsPerPixel < 0) {
- /* The depth must be set */
- if (scrp->depth > -1) {
- if (scrp->depth == 1)
- scrp->bitsPerPixel = 1;
- else if (scrp->depth <= 4)
- scrp->bitsPerPixel = 4;
- else if (scrp->depth <= 8)
- scrp->bitsPerPixel = 8;
- else if (scrp->depth <= 16)
- scrp->bitsPerPixel = 16;
- else if (scrp->depth <= 24) {
- /*
- * Figure out if a choice is possible based on the depth24
- * and pix24 flags.
- */
- /* Check pix24 first */
- if (pix24 != Pix24DontCare) {
- if (pix24 == Pix24Use32) {
- if (DO_PIX32(depth24flags)) {
- if (CHOOSE24FOR32(depth24flags))
- scrp->bitsPerPixel = 24;
- else
- scrp->bitsPerPixel = 32;
- } else {
- nomatch = TRUE;
- }
- } else if (pix24 == Pix24Use24) {
- if (DO_PIX24(depth24flags)) {
- if (CHOOSE32FOR24(depth24flags))
- scrp->bitsPerPixel = 32;
- else
- scrp->bitsPerPixel = 24;
- } else {
- nomatch = TRUE;
- }
- }
- } else {
- if (DO_PIX32(depth24flags)) {
- if (CHOOSE24FOR32(depth24flags))
- scrp->bitsPerPixel = 24;
- else
- scrp->bitsPerPixel = 32;
- } else if (DO_PIX24(depth24flags)) {
- if (CHOOSE32FOR24(depth24flags))
- scrp->bitsPerPixel = 32;
- else
- scrp->bitsPerPixel = 24;
- }
- }
- } else if (scrp->depth <= 32)
- scrp->bitsPerPixel = 32;
- else {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Specified depth (%d) is greater than 32\n",
- scrp->depth);
- return FALSE;
- }
- } else {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "xf86SetDepthBpp: internal error: depth and fbbpp"
- " are both not set\n");
- return FALSE;
- }
- if (scrp->bitsPerPixel < 0) {
- if (nomatch)
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Driver can't support depth 24 pixmap format (%d)\n",
- PIX24TOBPP(pix24));
- else if ((depth24flags & (Support24bppFb | Support32bppFb)) ==
- NoDepth24Support)
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Driver can't support depth 24\n");
- else
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Can't find fbbpp for depth 24\n");
- return FALSE;
- }
- scrp->bitsPerPixelFrom = X_PROBED;
- }
-
- if (scrp->depth <= 0) {
- /* bitsPerPixel is already set */
- switch (scrp->bitsPerPixel) {
- case 32:
- scrp->depth = 24;
- break;
- default:
- /* 1, 4, 8, 16 and 24 */
- scrp->depth = scrp->bitsPerPixel;
- break;
- }
- scrp->depthFrom = X_PROBED;
- }
-
- /* Sanity checks */
- if (scrp->depth < 1 || scrp->depth > 32) {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Specified depth (%d) is not in the range 1-32\n",
- scrp->depth);
- return FALSE;
- }
- switch (scrp->bitsPerPixel) {
- case 1:
- case 4:
- case 8:
- case 16:
- case 24:
- case 32:
- break;
- default:
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Specified fbbpp (%d) is not a permitted value\n",
- scrp->bitsPerPixel);
- return FALSE;
- }
- if (scrp->depth > scrp->bitsPerPixel) {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Specified depth (%d) is greater than the fbbpp (%d)\n",
- scrp->depth, scrp->bitsPerPixel);
- return FALSE;
- }
-
- /* set scrp->pixmap24 if the driver isn't flexible */
- if (scrp->bitsPerPixel == 24 && !DO_PIX32FOR24(depth24flags)) {
- scrp->pixmap24 = Pix24Use24;
- }
- if (scrp->bitsPerPixel == 32 && !DO_PIX24FOR32(depth24flags)) {
- scrp->pixmap24 = Pix24Use32;
- }
-
- /*
- * Find the Display subsection matching the depth/fbbpp and initialise
- * scrp->display with it.
- */
- for (i = 0, disp = scrp->confScreen->displays;
- i < scrp->confScreen->numdisplays; i++, disp++) {
- if ((disp->depth == scrp->depth && disp->fbbpp == scrp->bitsPerPixel)
- || (disp->depth == scrp->depth && disp->fbbpp <= 0)
- || (disp->fbbpp == scrp->bitsPerPixel && disp->depth <= 0)) {
- scrp->display = disp;
- break;
- }
- }
-
- /*
- * If an exact match can't be found, see if there is one with no
- * depth or fbbpp specified.
- */
- if (i == scrp->confScreen->numdisplays) {
- for (i = 0, disp = scrp->confScreen->displays;
- i < scrp->confScreen->numdisplays; i++, disp++) {
- if (disp->depth <= 0 && disp->fbbpp <= 0) {
- scrp->display = disp;
- break;
- }
- }
- }
-
- /*
- * If all else fails, create a default one.
- */
- if (i == scrp->confScreen->numdisplays) {
- scrp->confScreen->numdisplays++;
- scrp->confScreen->displays =
- xnfrealloc(scrp->confScreen->displays,
- scrp->confScreen->numdisplays * sizeof(DispRec));
- xf86DrvMsg(scrp->scrnIndex, X_INFO,
- "Creating default Display subsection in Screen section\n"
- "\t\"%s\" for depth/fbbpp %d/%d\n",
- scrp->confScreen->id, scrp->depth, scrp->bitsPerPixel);
- memset(&scrp->confScreen->displays[i], 0, sizeof(DispRec));
- scrp->confScreen->displays[i].blackColour.red = -1;
- scrp->confScreen->displays[i].blackColour.green = -1;
- scrp->confScreen->displays[i].blackColour.blue = -1;
- scrp->confScreen->displays[i].whiteColour.red = -1;
- scrp->confScreen->displays[i].whiteColour.green = -1;
- scrp->confScreen->displays[i].whiteColour.blue = -1;
- scrp->confScreen->displays[i].defaultVisual = -1;
- scrp->confScreen->displays[i].modes = xnfalloc(sizeof(char *));
- scrp->confScreen->displays[i].modes[0] = NULL;
- scrp->confScreen->displays[i].depth = depth;
- scrp->confScreen->displays[i].fbbpp = fbbpp;
- scrp->display = &scrp->confScreen->displays[i];
- }
-
- /*
- * Setup defaults for the display-wide attributes the framebuffer will
- * need. These defaults should eventually be set globally, and not
- * dependent on the screens.
- */
- scrp->imageByteOrder = IMAGE_BYTE_ORDER;
- scrp->bitmapScanlinePad = BITMAP_SCANLINE_PAD;
- if (scrp->depth < 8) {
- /* Planar modes need these settings */
- scrp->bitmapScanlineUnit = 8;
- scrp->bitmapBitOrder = MSBFirst;
- } else {
- scrp->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT;
- scrp->bitmapBitOrder = BITMAP_BIT_ORDER;
- }
-
- /*
- * If an unusual depth is required, add it to scrp->formats. The formats
- * for the common depths are handled globally in InitOutput
- */
- switch (scrp->depth) {
- case 1:
- case 4:
- case 8:
- case 15:
- case 16:
- case 24:
- /* Common depths. Nothing to do for them */
- break;
- default:
- if (!xf86AddPixFormat(scrp, scrp->depth, 0, 0)) {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Can't add pixmap format for depth %d\n", scrp->depth);
- return FALSE;
- }
- }
-
- /* Initialise the framebuffer format for this screen */
- scrp->fbFormat.depth = scrp->depth;
- scrp->fbFormat.bitsPerPixel = scrp->bitsPerPixel;
- scrp->fbFormat.scanlinePad = BITMAP_SCANLINE_PAD;
-
- return TRUE;
-}
-
-/*
- * Print out the selected depth and bpp.
- */
-void
-xf86PrintDepthBpp(ScrnInfoPtr scrp)
-{
- xf86DrvMsg(scrp->scrnIndex, scrp->depthFrom, "Depth %d, ", scrp->depth);
- xf86Msg(scrp->bitsPerPixelFrom, "framebuffer bpp %d\n", scrp->bitsPerPixel);
-}
-
-/*
- * xf86SetWeight sets scrp->weight, scrp->mask, scrp->offset, and for depths
- * greater than MAX_PSEUDO_DEPTH also scrp->rgbBits.
- */
-Bool
-xf86SetWeight(ScrnInfoPtr scrp, rgb weight, rgb mask)
-{
- MessageType weightFrom = X_DEFAULT;
-
- scrp->weight.red = 0;
- scrp->weight.green = 0;
- scrp->weight.blue = 0;
-
- if (xf86Weight.red > 0 && xf86Weight.green > 0 && xf86Weight.blue > 0) {
- scrp->weight = xf86Weight;
- weightFrom = X_CMDLINE;
- } else if (scrp->display->weight.red > 0 && scrp->display->weight.green > 0
- && scrp->display->weight.blue > 0) {
- scrp->weight = scrp->display->weight;
- weightFrom = X_CONFIG;
- } else if (weight.red > 0 && weight.green > 0 && weight.blue > 0) {
- scrp->weight = weight;
- } else {
- switch (scrp->depth) {
- case 1:
- case 4:
- case 8:
- scrp->weight.red = scrp->weight.green =
- scrp->weight.blue = scrp->rgbBits;
- break;
- case 15:
- scrp->weight.red = scrp->weight.green = scrp->weight.blue = 5;
- break;
- case 16:
- scrp->weight.red = scrp->weight.blue = 5;
- scrp->weight.green = 6;
- break;
- case 18:
- scrp->weight.red = scrp->weight.green = scrp->weight.blue = 6;
- break;
- case 24:
- scrp->weight.red = scrp->weight.green = scrp->weight.blue = 8;
- break;
- case 30:
- scrp->weight.red = scrp->weight.green = scrp->weight.blue = 10;
- break;
- }
- }
-
- if (scrp->weight.red)
- xf86DrvMsg(scrp->scrnIndex, weightFrom, "RGB weight %d%d%d\n",
- (int)scrp->weight.red, (int)scrp->weight.green,
- (int)scrp->weight.blue);
-
- if (scrp->depth > MAX_PSEUDO_DEPTH &&
- (scrp->depth != scrp->weight.red + scrp->weight.green +
- scrp->weight.blue)) {
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Weight given (%d%d%d) is inconsistent with the "
- "depth (%d)\n",
- (int)scrp->weight.red, (int)scrp->weight.green,
- (int)scrp->weight.blue, scrp->depth);
- return FALSE;
- }
- if (scrp->depth > MAX_PSEUDO_DEPTH && scrp->weight.red) {
- /*
- * XXX Does this even mean anything for TrueColor visuals?
- * If not, we shouldn't even be setting it here. However, this
- * matches the behaviour of 3.x versions of XFree86.
- */
- scrp->rgbBits = scrp->weight.red;
- if (scrp->weight.green > scrp->rgbBits)
- scrp->rgbBits = scrp->weight.green;
- if (scrp->weight.blue > scrp->rgbBits)
- scrp->rgbBits = scrp->weight.blue;
- }
-
- /* Set the mask and offsets */
- if (mask.red == 0 || mask.green == 0 || mask.blue == 0) {
- /* Default to a setting common to PC hardware */
- scrp->offset.red = scrp->weight.green + scrp->weight.blue;
- scrp->offset.green = scrp->weight.blue;
- scrp->offset.blue = 0;
- scrp->mask.red = ((1 << scrp->weight.red) - 1) << scrp->offset.red;
- scrp->mask.green = ((1 << scrp->weight.green) - 1)
- << scrp->offset.green;
- scrp->mask.blue = (1 << scrp->weight.blue) - 1;
- } else {
- /* Initialise to the values passed */
- scrp->mask.red = mask.red;
- scrp->mask.green = mask.green;
- scrp->mask.blue = mask.blue;
- scrp->offset.red = ffs(mask.red);
- scrp->offset.green = ffs(mask.green);
- scrp->offset.blue = ffs(mask.blue);
- }
- return TRUE;
-}
-
-Bool
-xf86SetDefaultVisual(ScrnInfoPtr scrp, int visual)
-{
- MessageType visualFrom = X_DEFAULT;
-
- if (defaultColorVisualClass >= 0) {
- scrp->defaultVisual = defaultColorVisualClass;
- visualFrom = X_CMDLINE;
- } else if (scrp->display->defaultVisual >= 0) {
- scrp->defaultVisual = scrp->display->defaultVisual;
- visualFrom = X_CONFIG;
- } else if (visual >= 0) {
- scrp->defaultVisual = visual;
- } else {
- if (scrp->depth == 1)
- scrp->defaultVisual = StaticGray;
- else if (scrp->depth == 4)
- scrp->defaultVisual = StaticColor;
- else if (scrp->depth <= MAX_PSEUDO_DEPTH)
- scrp->defaultVisual = PseudoColor;
- else
- scrp->defaultVisual = TrueColor;
- }
- switch (scrp->defaultVisual) {
- case StaticGray:
- case GrayScale:
- case StaticColor:
- case PseudoColor:
- case TrueColor:
- case DirectColor:
- xf86DrvMsg(scrp->scrnIndex, visualFrom, "Default visual is %s\n",
- xf86VisualNames[scrp->defaultVisual]);
- return TRUE;
- default:
-
- xf86DrvMsg(scrp->scrnIndex, X_ERROR,
- "Invalid default visual class (%d)\n", scrp->defaultVisual);
- return FALSE;
- }
-}
-
-#define TEST_GAMMA(g) \
- (g).red > GAMMA_ZERO || (g).green > GAMMA_ZERO || (g).blue > GAMMA_ZERO
-
-#define SET_GAMMA(g) \
- (g) > GAMMA_ZERO ? (g) : 1.0
-
-Bool
-xf86SetGamma(ScrnInfoPtr scrp, Gamma gamma)
-{
- MessageType from = X_DEFAULT;
-#if 0
- xf86MonPtr DDC = (xf86MonPtr)(scrp->monitor->DDC);
-#endif
- if (TEST_GAMMA(xf86Gamma)) {
- from = X_CMDLINE;
- scrp->gamma.red = SET_GAMMA(xf86Gamma.red);
- scrp->gamma.green = SET_GAMMA(xf86Gamma.green);
- scrp->gamma.blue = SET_GAMMA(xf86Gamma.blue);
- } else if (TEST_GAMMA(scrp->monitor->gamma)) {
- from = X_CONFIG;
- scrp->gamma.red = SET_GAMMA(scrp->monitor->gamma.red);
- scrp->gamma.green = SET_GAMMA(scrp->monitor->gamma.green);
- scrp->gamma.blue = SET_GAMMA(scrp->monitor->gamma.blue);
-#if 0
- } else if ( DDC && DDC->features.gamma > GAMMA_ZERO ) {
- from = X_PROBED;
- scrp->gamma.red = SET_GAMMA(DDC->features.gamma);
- scrp->gamma.green = SET_GAMMA(DDC->features.gamma);
- scrp->gamma.blue = SET_GAMMA(DDC->features.gamma);
- /* EDID structure version 2 gives optional seperate red, green & blue gamma values
- * in bytes 0x57-0x59 */
-#endif
- } else if (TEST_GAMMA(gamma)) {
- scrp->gamma.red = SET_GAMMA(gamma.red);
- scrp->gamma.green = SET_GAMMA(gamma.green);
- scrp->gamma.blue = SET_GAMMA(gamma.blue);
- } else {
- scrp->gamma.red = 1.0;
- scrp->gamma.green = 1.0;
- scrp->gamma.blue = 1.0;
- }
- /* Pretend we succeeded if we support better a gamma system.
- * This avoids a confusing message.
- */
- if (xf86_crtc_supports_gamma(scrp))
- return TRUE;
- xf86DrvMsg(scrp->scrnIndex, from,
- "Using gamma correction (%.1f, %.1f, %.1f)\n",
- scrp->gamma.red, scrp->gamma.green, scrp->gamma.blue);
-
- return TRUE;
-}
-
-#undef TEST_GAMMA
-#undef SET_GAMMA
-
-
-/*
- * Set the DPI from the command line option. XXX should allow it to be
- * calculated from the widthmm/heightmm values.
- */
-
-#undef MMPERINCH
-#define MMPERINCH 25.4
-
-void
-xf86SetDpi(ScrnInfoPtr pScrn, int x, int y)
-{
- MessageType from = X_DEFAULT;
- xf86MonPtr DDC = (xf86MonPtr)(pScrn->monitor->DDC);
- int ddcWidthmm, ddcHeightmm;
- int widthErr, heightErr;
-
- /* XXX Maybe there is no need for widthmm/heightmm in ScrnInfoRec */
- pScrn->widthmm = pScrn->monitor->widthmm;
- pScrn->heightmm = pScrn->monitor->heightmm;
-
- if (DDC && (DDC->features.hsize > 0 && DDC->features.vsize > 0) ) {
- /* DDC gives display size in mm for individual modes,
- * but cm for monitor
- */
- ddcWidthmm = DDC->features.hsize * 10; /* 10mm in 1cm */
- ddcHeightmm = DDC->features.vsize * 10; /* 10mm in 1cm */
- } else {
- ddcWidthmm = ddcHeightmm = 0;
- }
-
- if (monitorResolution > 0) {
- pScrn->xDpi = monitorResolution;
- pScrn->yDpi = monitorResolution;
- from = X_CMDLINE;
- } else if (pScrn->widthmm > 0 || pScrn->heightmm > 0) {
- from = X_CONFIG;
- if (pScrn->widthmm > 0) {
- pScrn->xDpi =
- (int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm);
- }
- if (pScrn->heightmm > 0) {
- pScrn->yDpi =
- (int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm);
- }
- if (pScrn->xDpi > 0 && pScrn->yDpi <= 0)
- pScrn->yDpi = pScrn->xDpi;
- if (pScrn->yDpi > 0 && pScrn->xDpi <= 0)
- pScrn->xDpi = pScrn->yDpi;
- xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n",
- pScrn->widthmm, pScrn->heightmm);
-
- /* Warn if config and probe disagree about display size */
- if ( ddcWidthmm && ddcHeightmm ) {
- if (pScrn->widthmm > 0) {
- widthErr = abs(ddcWidthmm - pScrn->widthmm);
- } else {
- widthErr = 0;
- }
- if (pScrn->heightmm > 0) {
- heightErr = abs(ddcHeightmm - pScrn->heightmm);
- } else {
- heightErr = 0;
- }
- if (widthErr>10 || heightErr>10) {
- /* Should include config file name for monitor here */
- xf86DrvMsg(pScrn->scrnIndex, X_WARNING,
- "Probed monitor is %dx%d mm, using Displaysize %dx%d mm\n",
- ddcWidthmm,ddcHeightmm, pScrn->widthmm,pScrn->heightmm);
- }
- }
- } else if ( ddcWidthmm && ddcHeightmm ) {
- from = X_PROBED;
- xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n",
- ddcWidthmm, ddcHeightmm );
- pScrn->widthmm = ddcWidthmm;
- pScrn->heightmm = ddcHeightmm;
- if (pScrn->widthmm > 0) {
- pScrn->xDpi =
- (int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm);
- }
- if (pScrn->heightmm > 0) {
- pScrn->yDpi =
- (int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm);
- }
- if (pScrn->xDpi > 0 && pScrn->yDpi <= 0)
- pScrn->yDpi = pScrn->xDpi;
- if (pScrn->yDpi > 0 && pScrn->xDpi <= 0)
- pScrn->xDpi = pScrn->yDpi;
- } else {
- if (x > 0)
- pScrn->xDpi = x;
- else
- pScrn->xDpi = DEFAULT_DPI;
- if (y > 0)
- pScrn->yDpi = y;
- else
- pScrn->yDpi = DEFAULT_DPI;
- }
- xf86DrvMsg(pScrn->scrnIndex, from, "DPI set to (%d, %d)\n",
- pScrn->xDpi, pScrn->yDpi);
-}
-
-#undef MMPERINCH
-
-
-void
-xf86SetBlackWhitePixels(ScreenPtr pScreen)
-{
- if (xf86FlipPixels) {
- pScreen->whitePixel = 0;
- pScreen->blackPixel = 1;
- } else {
- pScreen->whitePixel = 1;
- pScreen->blackPixel = 0;
- }
-}
-
-/*
- * Function to enable/disable access to the frame buffer
- *
- * This is used when VT switching and when entering/leaving DGA direct mode.
- *
- * This has been rewritten again to eliminate the saved pixmap. The
- * devPrivate field in the screen pixmap is set to NULL to catch code
- * accidentally referencing the frame buffer while the X server is not
- * supposed to touch it.
- *
- * Here, we exchange the pixmap private data, rather than the pixmaps
- * themselves to avoid having to find and change any references to the screen
- * pixmap such as GC's, window privates etc. This also means that this code
- * does not need to know exactly how the pixmap pixels are accessed. Further,
- * this exchange is >not< done through the screen's ModifyPixmapHeader()
- * vector. This means the called frame buffer code layers can determine
- * whether they are switched in or out by keeping track of the root pixmap's
- * private data, and therefore don't need to access pScrnInfo->vtSema.
- */
-void
-xf86EnableDisableFBAccess(int scrnIndex, Bool enable)
-{
- ScrnInfoPtr pScrnInfo = xf86Screens[scrnIndex];
- ScreenPtr pScreen = pScrnInfo->pScreen;
- PixmapPtr pspix;
-
- pspix = (*pScreen->GetScreenPixmap) (pScreen);
- if (enable)
- {
- /*
- * Restore all of the clip lists on the screen
- */
- if (!xf86Resetting)
- SetRootClip (pScreen, TRUE);
-
- }
- else
- {
- /*
- * Empty all of the clip lists on the screen
- */
- SetRootClip (pScreen, FALSE);
- }
-}
-
-/* Print driver messages in the standard format */
-
-#undef PREFIX_SIZE
-#define PREFIX_SIZE 14
-
-void
-xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format,
- va_list args)
-{
- char *tmpFormat;
-
- /* Prefix the scrnIndex name to the format string. */
- if (scrnIndex >= 0 && scrnIndex < xf86NumScreens &&
- xf86Screens[scrnIndex]->name) {
- tmpFormat = malloc(strlen(format) +
- strlen(xf86Screens[scrnIndex]->name) +
- PREFIX_SIZE + 1);
- if (!tmpFormat)
- return;
-
- snprintf(tmpFormat, PREFIX_SIZE + 1, "%s(%d): ",
- xf86Screens[scrnIndex]->name, scrnIndex);
-
- strcat(tmpFormat, format);
- LogVMessageVerb(type, verb, tmpFormat, args);
- free(tmpFormat);
- } else
- LogVMessageVerb(type, verb, format, args);
-}
-#undef PREFIX_SIZE
-
-/* Print driver messages, with verbose level specified directly */
-void
-xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format,
- ...)
-{
- va_list ap;
-
- va_start(ap, format);
- xf86VDrvMsgVerb(scrnIndex, type, verb, format, ap);
- va_end(ap);
-}
-
-/* Print driver messages, with verbose level of 1 (default) */
-void
-xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- xf86VDrvMsgVerb(scrnIndex, type, 1, format, ap);
- va_end(ap);
-}
-
-/* Print input driver messages in the standard format of
- <driver>: <device name>: <message> */
-void
-xf86VIDrvMsgVerb(InputInfoPtr dev, MessageType type, int verb, const char *format,
- va_list args)
-{
- char *msg;
-
- if (asprintf(&msg, "%s: %s: %s", dev->drv->driverName, dev->name, format)
- == -1) {
- LogVMessageVerb(type, verb, "%s", args);
- } else {
- LogVMessageVerb(type, verb, msg, args);
- free(msg);
- }
-}
-
-/* Print input driver message, with verbose level specified directly */
-void
-xf86IDrvMsgVerb(InputInfoPtr dev, MessageType type, int verb, const char *format,
- ...)
-{
- va_list ap;
-
- va_start(ap, format);
- xf86VIDrvMsgVerb(dev, type, verb, format, ap);
- va_end(ap);
-}
-
-/* Print input driver messages, with verbose level of 1 (default) */
-void
-xf86IDrvMsg(InputInfoPtr dev, MessageType type, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- xf86VIDrvMsgVerb(dev, type, 1, format, ap);
- va_end(ap);
-}
-
-
-/* Print non-driver messages with verbose level specified directly */
-void
-xf86MsgVerb(MessageType type, int verb, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, verb, format, ap);
- va_end(ap);
-}
-
-/* Print non-driver messages with verbose level of 1 (default) */
-void
-xf86Msg(MessageType type, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- LogVMessageVerb(type, 1, format, ap);
- va_end(ap);
-}
-
-/* Just like ErrorF, but with the verbose level checked */
-void
-xf86ErrorFVerb(int verb, const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- if (xf86Verbose >= verb || xf86LogVerbose >= verb)
- LogVWrite(verb, format, ap);
- va_end(ap);
-}
-
-/* Like xf86ErrorFVerb, but with an implied verbose level of 1 */
-void
-xf86ErrorF(const char *format, ...)
-{
- va_list ap;
-
- va_start(ap, format);
- if (xf86Verbose >= 1 || xf86LogVerbose >= 1)
- LogVWrite(1, format, ap);
- va_end(ap);
-}
-
-
-void
-xf86LogInit(void)
-{
- char *lf = NULL;
-
-#define LOGSUFFIX ".log"
-#define LOGOLDSUFFIX ".old"
-
- /* Get the log file name */
- if (xf86LogFileFrom == X_DEFAULT) {
- /* Append the display number and ".log" */
- if (asprintf(&lf, "%s%%s" LOGSUFFIX, xf86LogFile) == -1)
- FatalError("Cannot allocate space for the log file name\n");
- xf86LogFile = lf;
- }
-
- xf86LogFile = LogInit(xf86LogFile, LOGOLDSUFFIX);
- xf86LogFileWasOpened = TRUE;
-
- xf86SetVerbosity(xf86Verbose);
- xf86SetLogVerbosity(xf86LogVerbose);
-
-#undef LOGSUFFIX
-#undef LOGOLDSUFFIX
-
- free(lf);
-}
-
-void
-xf86CloseLog(enum ExitCode error)
-{
- LogClose(error);
-}
-
-
-/*
- * Drivers can use these for using their own SymTabRecs.
- */
-
-const char *
-xf86TokenToString(SymTabPtr table, int token)
-{
- int i;
-
- for (i = 0; table[i].token >= 0 && table[i].token != token; i++)
- ;
-
- if (table[i].token < 0)
- return NULL;
- else
- return table[i].name;
-}
-
-int
-xf86StringToToken(SymTabPtr table, const char *string)
-{
- int i;
-
- if (string == NULL)
- return -1;
-
- for (i = 0; table[i].token >= 0 && xf86NameCmp(string, table[i].name); i++)
- ;
-
- return table[i].token;
-}
-
-/*
- * helper to display the clocks found on a card
- */
-void
-xf86ShowClocks(ScrnInfoPtr scrp, MessageType from)
-{
- int j;
-
- xf86DrvMsg(scrp->scrnIndex, from, "Pixel clocks available:");
- for (j=0; j < scrp->numClocks; j++) {
- if ((j % 4) == 0) {
- xf86ErrorF("\n");
- xf86DrvMsg(scrp->scrnIndex, from, "pixel clocks:");
- }
- xf86ErrorF(" %7.3f", (double)scrp->clock[j] / 1000.0);
- }
- xf86ErrorF("\n");
-}
-
-
-/*
- * This prints out the driver identify message, including the names of
- * the supported chipsets.
- *
- * XXX This makes assumptions about the line width, etc. Maybe we could
- * use a more general "pretty print" function for messages.
- */
-void
-xf86PrintChipsets(const char *drvname, const char *drvmsg, SymTabPtr chips)
-{
- int len, i;
-
- len = 6 + strlen(drvname) + 2 + strlen(drvmsg) + 2;
- xf86Msg(X_INFO, "%s: %s:", drvname, drvmsg);
- for (i = 0; chips[i].name != NULL; i++) {
- if (i != 0) {
- xf86ErrorF(",");
- len++;
- }
- if (len + 2 + strlen(chips[i].name) < 78) {
- xf86ErrorF(" ");
- len++;
- } else {
- xf86ErrorF("\n\t");
- len = 8;
- }
- xf86ErrorF("%s", chips[i].name);
- len += strlen(chips[i].name);
- }
- xf86ErrorF("\n");
-}
-
-
-int
-xf86MatchDevice(const char *drivername, GDevPtr **sectlist)
-{
- GDevPtr gdp, *pgdp = NULL;
- confScreenPtr screensecptr;
- int i,j;
-
- if (sectlist)
- *sectlist = NULL;
-
- /*
- * This can happen when running Xorg -showopts and a module like ati
- * or vmware tries to load its submodules when xf86ConfigLayout is empty
- */
- if (!xf86ConfigLayout.screens)
- return 0;
-
- /*
- * This is a very important function that matches the device sections
- * as they show up in the config file with the drivers that the server
- * loads at run time.
- *
- * ChipProbe can call
- * int xf86MatchDevice(char * drivername, GDevPtr ** sectlist)
- * with its driver name. The function allocates an array of GDevPtr and
- * returns this via sectlist and returns the number of elements in
- * this list as return value. 0 means none found, -1 means fatal error.
- *
- * It can figure out which of the Device sections to use for which card
- * (using things like the Card statement, etc). For single headed servers
- * there will of course be just one such Device section.
- */
- i = 0;
-
- /*
- * first we need to loop over all the Screens sections to get to all
- * 'active' device sections
- */
- for (j=0; xf86ConfigLayout.screens[j].screen != NULL; j++) {
- screensecptr = xf86ConfigLayout.screens[j].screen;
- if ((screensecptr->device->driver != NULL)
- && (xf86NameCmp( screensecptr->device->driver,drivername) == 0)
- && (! screensecptr->device->claimed)) {
- /*
- * we have a matching driver that wasn't claimed, yet
- */
- pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr));
- pgdp[i++] = screensecptr->device;
- }
- }
-
- /* Then handle the inactive devices */
- j = 0;
- while (xf86ConfigLayout.inactives[j].identifier) {
- gdp = &xf86ConfigLayout.inactives[j];
- if (gdp->driver && !gdp->claimed &&
- !xf86NameCmp(gdp->driver,drivername)) {
- /* we have a matching driver that wasn't claimed yet */
- pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr));
- pgdp[i++] = gdp;
- }
- j++;
- }
-
- /*
- * make the array NULL terminated and return its address
- */
- if (i)
- pgdp[i] = NULL;
-
- if (sectlist)
- *sectlist = pgdp;
- else
- free(pgdp);
- return i;
-}
-
-/*
- * xf86GetClocks -- get the dot-clocks via a BIG BAD hack ...
- */
-void
-xf86GetClocks(ScrnInfoPtr pScrn, int num, Bool (*ClockFunc)(ScrnInfoPtr, int),
- void (*ProtectRegs)(ScrnInfoPtr, Bool),
- void (*BlankScreen)(ScrnInfoPtr, Bool), IOADDRESS vertsyncreg,
- int maskval, int knownclkindex, int knownclkvalue)
-{
- register int status = vertsyncreg;
- unsigned long i, cnt, rcnt, sync;
-
- /* First save registers that get written on */
- (*ClockFunc)(pScrn, CLK_REG_SAVE);
-
- if (num > MAXCLOCKS)
- num = MAXCLOCKS;
-
- for (i = 0; i < num; i++)
- {
- if (ProtectRegs)
- (*ProtectRegs)(pScrn, TRUE);
- if (!(*ClockFunc)(pScrn, i))
- {
- pScrn->clock[i] = -1;
- continue;
- }
- if (ProtectRegs)
- (*ProtectRegs)(pScrn, FALSE);
- if (BlankScreen)
- (*BlankScreen)(pScrn, FALSE);
-
- usleep(50000); /* let VCO stabilise */
-
- cnt = 0;
- sync = 200000;
-
- while ((inb(status) & maskval) == 0x00)
- if (sync-- == 0) goto finish;
- /* Something appears to be happening, so reset sync count */
- sync = 200000;
- while ((inb(status) & maskval) == maskval)
- if (sync-- == 0) goto finish;
- /* Something appears to be happening, so reset sync count */
- sync = 200000;
- while ((inb(status) & maskval) == 0x00)
- if (sync-- == 0) goto finish;
-
- for (rcnt = 0; rcnt < 5; rcnt++)
- {
- while (!(inb(status) & maskval))
- cnt++;
- while ((inb(status) & maskval))
- cnt++;
- }
-
-finish:
- pScrn->clock[i] = cnt ? cnt : -1;
- if (BlankScreen)
- (*BlankScreen)(pScrn, TRUE);
- }
-
- for (i = 0; i < num; i++)
- {
- if (i != knownclkindex)
- {
- if (pScrn->clock[i] == -1)
- {
- pScrn->clock[i] = 0;
- }
- else
- {
- pScrn->clock[i] = (int)(0.5 +
- (((float)knownclkvalue) * pScrn->clock[knownclkindex]) /
- (pScrn->clock[i]));
- /* Round to nearest 10KHz */
- pScrn->clock[i] += 5;
- pScrn->clock[i] /= 10;
- pScrn->clock[i] *= 10;
- }
- }
- }
-
- pScrn->clock[knownclkindex] = knownclkvalue;
- pScrn->numClocks = num;
-
- /* Restore registers that were written on */
- (*ClockFunc)(pScrn, CLK_REG_RESTORE);
-}
-
-const char *
-xf86GetVisualName(int visual)
-{
- if (visual < 0 || visual > DirectColor)
- return NULL;
-
- return xf86VisualNames[visual];
-}
-
-
-int
-xf86GetVerbosity(void)
-{
- return max(xf86Verbose, xf86LogVerbose);
-}
-
-Pix24Flags
-xf86GetPix24(void)
-{
- return xf86Info.pixmap24;
-}
-
-
-int
-xf86GetDepth(void)
-{
- return xf86Depth;
-}
-
-
-rgb
-xf86GetWeight(void)
-{
- return xf86Weight;
-}
-
-
-Gamma
-xf86GetGamma(void)
-{
- return xf86Gamma;
-}
-
-
-Bool
-xf86GetFlipPixels(void)
-{
- return xf86FlipPixels;
-}
-
-
-const char *
-xf86GetServerName(void)
-{
- return xf86ServerName;
-}
-
-
-Bool
-xf86ServerIsExiting(void)
-{
- return (dispatchException & DE_TERMINATE) == DE_TERMINATE;
-}
-
-
-Bool
-xf86ServerIsResetting(void)
-{
- return xf86Resetting;
-}
-
-
-Bool
-xf86ServerIsInitialising(void)
-{
- return xf86Initialising;
-}
-
-
-Bool
-xf86ServerIsOnlyDetecting(void)
-{
- return xf86DoConfigure;
-}
-
-
-Bool
-xf86CaughtSignal(void)
-{
- return xf86Info.caughtSignal;
-}
-
-
-Bool
-xf86GetVidModeAllowNonLocal(void)
-{
- return xf86Info.vidModeAllowNonLocal;
-}
-
-
-Bool
-xf86GetVidModeEnabled(void)
-{
- return xf86Info.vidModeEnabled;
-}
-
-Bool
-xf86GetModInDevAllowNonLocal(void)
-{
- return xf86Info.miscModInDevAllowNonLocal;
-}
-
-
-Bool
-xf86GetModInDevEnabled(void)
-{
- return xf86Info.miscModInDevEnabled;
-}
-
-
-Bool
-xf86GetAllowMouseOpenFail(void)
-{
- return xf86Info.allowMouseOpenFail;
-}
-
-
-Bool
-xf86IsPc98(void)
-{
-#if SUPPORT_PC98
- return xf86Info.pc98;
-#else
- return FALSE;
-#endif
-}
-
-void
-xf86DisableRandR(void)
-{
- xf86Info.disableRandR = TRUE;
- xf86Info.randRFrom = X_PROBED;
-}
-
-CARD32
-xf86GetModuleVersion(pointer module)
-{
- return (CARD32)LoaderGetModuleVersion(module);
-}
-
-pointer
-xf86LoadDrvSubModule(DriverPtr drv, const char *name)
-{
- pointer ret;
- int errmaj = 0, errmin = 0;
-
- ret = LoadSubModule(drv->module, name, NULL, NULL, NULL, NULL,
- &errmaj, &errmin);
- if (!ret)
- LoaderErrorMsg(NULL, name, errmaj, errmin);
- return ret;
-}
-
-pointer
-xf86LoadSubModule(ScrnInfoPtr pScrn, const char *name)
-{
- pointer ret;
- int errmaj = 0, errmin = 0;
-
- ret = LoadSubModule(pScrn->module, name, NULL, NULL, NULL, NULL,
- &errmaj, &errmin);
- if (!ret)
- LoaderErrorMsg(pScrn->name, name, errmaj, errmin);
- return ret;
-}
-
-/*
- * xf86LoadOneModule loads a single module.
- */
-pointer
-xf86LoadOneModule(char *name, pointer opt)
-{
- int errmaj, errmin;
- char *Name;
- pointer mod;
-
- if (!name)
- return NULL;
-
- /* Normalise the module name */
- Name = xf86NormalizeName(name);
-
- /* Skip empty names */
- if (Name == NULL)
- return NULL;
- if (*Name == '\0') {
- free(Name);
- return NULL;
- }
-
- mod = LoadModule(Name, NULL, NULL, NULL, opt, NULL, &errmaj, &errmin);
- if (!mod)
- LoaderErrorMsg(NULL, Name, errmaj, errmin);
- free(Name);
- return mod;
-}
-
-void
-xf86UnloadSubModule(pointer mod)
-{
- /*
- * This is disabled for now. The loader isn't smart enough yet to undo
- * relocations.
- */
-#if 0
- UnloadSubModule(mod);
-#endif
-}
-
-Bool
-xf86LoaderCheckSymbol(const char *name)
-{
- return LoaderSymbol(name) != NULL;
-}
-
-typedef enum {
- OPTION_BACKING_STORE
-} BSOpts;
-
-static const OptionInfoRec BSOptions[] = {
- { OPTION_BACKING_STORE, "BackingStore", OPTV_BOOLEAN, {0}, FALSE },
- { -1, NULL, OPTV_NONE, {0}, FALSE }
-};
-
-void
-xf86SetBackingStore(ScreenPtr pScreen)
-{
- Bool useBS = FALSE;
- MessageType from = X_DEFAULT;
- ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
- OptionInfoPtr options;
-
- options = xnfalloc(sizeof(BSOptions));
- (void)memcpy(options, BSOptions, sizeof(BSOptions));
- xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);
-
- /* check for commandline option here */
- if (xf86bsEnableFlag) {
- from = X_CMDLINE;
- useBS = TRUE;
- } else if (xf86bsDisableFlag) {
- from = X_CMDLINE;
- useBS = FALSE;
- } else {
- if (xf86GetOptValBool(options, OPTION_BACKING_STORE, &useBS))
- from = X_CONFIG;
- }
- free(options);
- pScreen->backingStoreSupport = useBS ? Always : NotUseful;
- if (serverGeneration == 1)
- xf86DrvMsg(pScreen->myNum, from, "Backing store %s\n",
- useBS ? "enabled" : "disabled");
-}
-
-
-typedef enum {
- OPTION_SILKEN_MOUSE
-} SMOpts;
-
-static const OptionInfoRec SMOptions[] = {
- { OPTION_SILKEN_MOUSE, "SilkenMouse", OPTV_BOOLEAN, {0}, FALSE },
- { -1, NULL, OPTV_NONE, {0}, FALSE }
-};
-
-void
-xf86SetSilkenMouse (ScreenPtr pScreen)
-{
- Bool useSM = TRUE;
- MessageType from = X_DEFAULT;
- ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
- OptionInfoPtr options;
-
- options = xnfalloc(sizeof(SMOptions));
- (void)memcpy(options, SMOptions, sizeof(SMOptions));
- xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options);
-
- /* check for commandline option here */
- /* disable if screen shares resources */
- /* TODO VGA arb disable silken mouse */
- if (xf86silkenMouseDisableFlag) {
- from = X_CMDLINE;
- useSM = FALSE;
- } else {
- if (xf86GetOptValBool(options, OPTION_SILKEN_MOUSE, &useSM))
- from = X_CONFIG;
- }
- free(options);
- /*
- * XXX quick hack to report correctly for OSs that can't do SilkenMouse
- * yet. Should handle this differently so that alternate async methods
- * work correctly with this too.
- */
- pScrn->silkenMouse = useSM && xf86Info.useSIGIO && xf86SIGIOSupported();
- if (serverGeneration == 1)
- xf86DrvMsg(pScreen->myNum, from, "Silken mouse %s\n",
- pScrn->silkenMouse ? "enabled" : "disabled");
-}
-
-/* Wrote this function for the PM2 Xv driver, preliminary. */
-
-pointer
-xf86FindXvOptions(int scrnIndex, int adaptor_index, char *port_name,
- char **adaptor_name, pointer *adaptor_options)
-{
- ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
- confXvAdaptorPtr adaptor;
- int i;
-
- if (adaptor_index >= pScrn->confScreen->numxvadaptors) {
- if (adaptor_name) *adaptor_name = NULL;
- if (adaptor_options) *adaptor_options = NULL;
- return NULL;
- }
-
- adaptor = &pScrn->confScreen->xvadaptors[adaptor_index];
- if (adaptor_name) *adaptor_name = adaptor->identifier;
- if (adaptor_options) *adaptor_options = adaptor->options;
-
- for (i = 0; i < adaptor->numports; i++)
- if (!xf86NameCmp(adaptor->ports[i].identifier, port_name))
- return adaptor->ports[i].options;
-
- return NULL;
-}
-
-/* Rather than duplicate loader's get OS function, just include it directly */
-#define LoaderGetOS xf86GetOS
-#include "loader/os.c"
-
-static void
-xf86ConfigFbEntityInactive(EntityInfoPtr pEnt, EntityProc init,
- EntityProc enter, EntityProc leave, pointer private)
-{
- ScrnInfoPtr pScrn;
-
- if ((pScrn = xf86FindScreenForEntity(pEnt->index)))
- xf86RemoveEntityFromScreen(pScrn,pEnt->index);
- xf86SetEntityFuncs(pEnt->index,init,enter,leave,private);
-}
-
-ScrnInfoPtr
-xf86ConfigFbEntity(ScrnInfoPtr pScrn, int scrnFlag, int entityIndex,
- EntityProc init, EntityProc enter, EntityProc leave,
- pointer private)
-{
- EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex);
- if (!pEnt) return pScrn;
-
- if (!(pEnt->location.type == BUS_NONE)) {
- free(pEnt);
- return pScrn;
- }
-
- if (!pEnt->active) {
- xf86ConfigFbEntityInactive(pEnt, init, enter, leave, private);
- free(pEnt);
- return pScrn;
- }
-
- if (!pScrn)
- pScrn = xf86AllocateScreen(pEnt->driver,scrnFlag);
- xf86AddEntityToScreen(pScrn,entityIndex);
-
- xf86SetEntityFuncs(entityIndex,init,enter,leave,private);
-
- free(pEnt);
- return pScrn;
-}
-
-Bool
-xf86IsScreenPrimary(int scrnIndex)
-{
- ScrnInfoPtr pScrn = xf86Screens[scrnIndex];
- int i;
-
- for (i=0 ; i < pScrn->numEntities; i++) {
- if (xf86IsEntityPrimary(i))
- return TRUE;
- }
- return FALSE;
-}
-
-int
-xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type,
- int format, unsigned long len, pointer value )
-{
- RootWinPropPtr pNewProp = NULL, pRegProp;
- int i;
- Bool existing = FALSE;
-
- DebugF("xf86RegisterRootWindowProperty(%d, %ld, %ld, %d, %ld, %p)\n",
- ScrnIndex, property, type, format, len, value);
-
- if (ScrnIndex<0 || ScrnIndex>=xf86NumScreens) {
- return BadMatch;
- }
-
- if (xf86RegisteredPropertiesTable &&
- xf86RegisteredPropertiesTable[ScrnIndex]) {
- for (pNewProp = xf86RegisteredPropertiesTable[ScrnIndex];
- pNewProp; pNewProp = pNewProp->next) {
- if (strcmp(pNewProp->name, NameForAtom(property)) == 0)
- break;
- }
- }
-
- if (!pNewProp) {
- if ((pNewProp = (RootWinPropPtr)malloc(sizeof(RootWinProp))) == NULL) {
- return BadAlloc;
- }
- /*
- * We will put this property at the end of the list so that
- * the changes are made in the order they were requested.
- */
- pNewProp->next = NULL;
- } else {
- free(pNewProp->name);
- existing = TRUE;
- }
-
- pNewProp->name = xnfstrdup(NameForAtom(property));
- pNewProp->type = type;
- pNewProp->format = format;
- pNewProp->size = len;
- pNewProp->data = value;
-
- DebugF("new property filled\n");
-
- if (NULL==xf86RegisteredPropertiesTable) {
- DebugF("creating xf86RegisteredPropertiesTable[] size %d\n",
- xf86NumScreens);
- if ( NULL==(xf86RegisteredPropertiesTable=(RootWinPropPtr*)xnfcalloc(sizeof(RootWinProp),xf86NumScreens) )) {
- return BadAlloc;
- }
- for (i=0; i<xf86NumScreens; i++) {
- xf86RegisteredPropertiesTable[i] = NULL;
- }
- }
-
- DebugF("xf86RegisteredPropertiesTable %p\n",
- (void *)xf86RegisteredPropertiesTable);
- DebugF("xf86RegisteredPropertiesTable[%d] %p\n",
- ScrnIndex, (void *)xf86RegisteredPropertiesTable[ScrnIndex]);
-
- if (!existing) {
- if ( xf86RegisteredPropertiesTable[ScrnIndex] == NULL) {
- xf86RegisteredPropertiesTable[ScrnIndex] = pNewProp;
- } else {
- pRegProp = xf86RegisteredPropertiesTable[ScrnIndex];
- while (pRegProp->next != NULL) {
- DebugF("- next %p\n", (void *)pRegProp);
- pRegProp = pRegProp->next;
- }
- pRegProp->next = pNewProp;
- }
- }
- DebugF("xf86RegisterRootWindowProperty succeeded\n");
- return Success;
-}
-
-Bool
-xf86IsUnblank(int mode)
-{
- switch(mode) {
- case SCREEN_SAVER_OFF:
- case SCREEN_SAVER_FORCER:
- return TRUE;
- case SCREEN_SAVER_ON:
- case SCREEN_SAVER_CYCLE:
- return FALSE;
- default:
- xf86MsgVerb(X_WARNING, 0, "Unexpected save screen mode: %d\n", mode);
- return TRUE;
- }
-}
-
-void
-xf86MotionHistoryAllocate(InputInfoPtr pInfo)
-{
- AllocateMotionHistory(pInfo->dev);
-}
+/* + * Copyright (c) 1997-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* + * Authors: Dirk Hohndel <hohndel@XFree86.Org> + * David Dawes <dawes@XFree86.Org> + * ... and others + * + * This file includes the helper functions that the server provides for + * different drivers. + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <X11/X.h> +#include "os.h" +#include "servermd.h" +#include "pixmapstr.h" +#include "windowstr.h" +#include "propertyst.h" +#include "gcstruct.h" +#include "loaderProcs.h" +#include "xf86.h" +#include "xf86Priv.h" +#include "xf86_OSlib.h" +#include "micmap.h" +#include "xf86DDC.h" +#include "xf86Xinput.h" +#include "xf86InPriv.h" +#include "mivalidate.h" +#include "xf86Crtc.h" + +/* For xf86GetClocks */ +#if defined(CSRG_BASED) || defined(__GNU__) +#define HAS_SETPRIORITY +#include <sys/resource.h> +#endif + +static int xf86ScrnInfoPrivateCount = 0; + + +/* Add a pointer to a new DriverRec to xf86DriverList */ + +void +xf86AddDriver(DriverPtr driver, pointer module, int flags) +{ + /* Don't add null entries */ + if (!driver) + return; + + if (xf86DriverList == NULL) + xf86NumDrivers = 0; + + xf86NumDrivers++; + xf86DriverList = xnfrealloc(xf86DriverList, + xf86NumDrivers * sizeof(DriverPtr)); + xf86DriverList[xf86NumDrivers - 1] = xnfalloc(sizeof(DriverRec)); + if (flags & HaveDriverFuncs) + *xf86DriverList[xf86NumDrivers - 1] = *driver; + else { + (void) memset( xf86DriverList[xf86NumDrivers - 1], 0, + sizeof( DriverRec ) ); + (void) memcpy( xf86DriverList[xf86NumDrivers - 1], driver, + sizeof(DriverRec1)); + + } + xf86DriverList[xf86NumDrivers - 1]->module = module; + xf86DriverList[xf86NumDrivers - 1]->refCount = 0; +} + +void +xf86DeleteDriver(int drvIndex) +{ + if (xf86DriverList[drvIndex] + && (!xf86DriverHasEntities(xf86DriverList[drvIndex]))) { + if (xf86DriverList[drvIndex]->module) + UnloadModule(xf86DriverList[drvIndex]->module); + free(xf86DriverList[drvIndex]); + xf86DriverList[drvIndex] = NULL; + } +} + +/* Add a pointer to a new InputDriverRec to xf86InputDriverList */ + +void +xf86AddInputDriver(InputDriverPtr driver, pointer module, int flags) +{ + /* Don't add null entries */ + if (!driver) + return; + + if (xf86InputDriverList == NULL) + xf86NumInputDrivers = 0; + + xf86NumInputDrivers++; + xf86InputDriverList = xnfrealloc(xf86InputDriverList, + xf86NumInputDrivers * sizeof(InputDriverPtr)); + xf86InputDriverList[xf86NumInputDrivers - 1] = + xnfalloc(sizeof(InputDriverRec)); + *xf86InputDriverList[xf86NumInputDrivers - 1] = *driver; + xf86InputDriverList[xf86NumInputDrivers - 1]->module = module; +} + +void +xf86DeleteInputDriver(int drvIndex) +{ + if (xf86InputDriverList[drvIndex] && xf86InputDriverList[drvIndex]->module) + UnloadModule(xf86InputDriverList[drvIndex]->module); + free(xf86InputDriverList[drvIndex]); + xf86InputDriverList[drvIndex] = NULL; +} + +InputDriverPtr +xf86LookupInputDriver(const char *name) +{ + int i; + + for (i = 0; i < xf86NumInputDrivers; i++) { + if (xf86InputDriverList[i] && xf86InputDriverList[i]->driverName && + xf86NameCmp(name, xf86InputDriverList[i]->driverName) == 0) + return xf86InputDriverList[i]; + } + return NULL; +} + +InputInfoPtr +xf86LookupInput(const char *name) +{ + InputInfoPtr p; + + for (p = xf86InputDevs; p != NULL; p = p->next) { + if (strcmp(name, p->name) == 0) + return p; + } + + return NULL; +} + +/* Allocate a new ScrnInfoRec in xf86Screens */ + +ScrnInfoPtr +xf86AllocateScreen(DriverPtr drv, int flags) +{ + int i; + + if (xf86Screens == NULL) + xf86NumScreens = 0; + + i = xf86NumScreens++; + xf86Screens = xnfrealloc(xf86Screens, xf86NumScreens * sizeof(ScrnInfoPtr)); + xf86Screens[i] = xnfcalloc(sizeof(ScrnInfoRec), 1); + xf86Screens[i]->scrnIndex = i; /* Changes when a screen is removed */ + xf86Screens[i]->origIndex = i; /* This never changes */ + xf86Screens[i]->privates = xnfcalloc(sizeof(DevUnion), + xf86ScrnInfoPrivateCount); + /* + * EnableDisableFBAccess now gets initialized in InitOutput() + * xf86Screens[i]->EnableDisableFBAccess = xf86EnableDisableFBAccess; + */ + + xf86Screens[i]->drv = drv; + drv->refCount++; + xf86Screens[i]->module = DuplicateModule(drv->module, NULL); + + xf86Screens[i]->DriverFunc = drv->driverFunc; + + return xf86Screens[i]; +} + + +/* + * Remove an entry from xf86Screens. Ideally it should free all allocated + * data. To do this properly may require a driver hook. + */ + +void +xf86DeleteScreen(int scrnIndex, int flags) +{ + ScrnInfoPtr pScrn; + int i; + + /* First check if the screen is valid */ + if (xf86NumScreens == 0 || xf86Screens == NULL) + return; + + if (scrnIndex > xf86NumScreens - 1) + return; + + if (!(pScrn = xf86Screens[scrnIndex])) + return; + + /* If a FreeScreen function is defined, call it here */ + if (pScrn->FreeScreen != NULL) + pScrn->FreeScreen(scrnIndex, 0); + + while (pScrn->modes) + xf86DeleteMode(&pScrn->modes, pScrn->modes); + + while (pScrn->modePool) + xf86DeleteMode(&pScrn->modePool, pScrn->modePool); + + xf86OptionListFree(pScrn->options); + + if (pScrn->module) + UnloadModule(pScrn->module); + + if (pScrn->drv) + pScrn->drv->refCount--; + + free(pScrn->privates); + + xf86ClearEntityListForScreen(scrnIndex); + + free(pScrn); + + /* Move the other entries down, updating their scrnIndex fields */ + + xf86NumScreens--; + + for (i = scrnIndex; i < xf86NumScreens; i++) { + xf86Screens[i] = xf86Screens[i + 1]; + xf86Screens[i]->scrnIndex = i; + /* Also need to take care of the screen layout settings */ + } +} + +/* + * Allocate a private in ScrnInfoRec. + */ + +int +xf86AllocateScrnInfoPrivateIndex(void) +{ + int idx, i; + ScrnInfoPtr pScr; + DevUnion *nprivs; + + idx = xf86ScrnInfoPrivateCount++; + for (i = 0; i < xf86NumScreens; i++) { + pScr = xf86Screens[i]; + nprivs = xnfrealloc(pScr->privates, + xf86ScrnInfoPrivateCount * sizeof(DevUnion)); + /* Zero the new private */ + memset(&nprivs[idx], 0, sizeof(DevUnion)); + pScr->privates = nprivs; + } + return idx; +} + +Bool +xf86AddPixFormat(ScrnInfoPtr pScrn, int depth, int bpp, int pad) +{ + int i; + + if (pScrn->numFormats >= MAXFORMATS) + return FALSE; + + if (bpp <= 0) { + if (depth == 1) + bpp = 1; + else if (depth <= 8) + bpp = 8; + else if (depth <= 16) + bpp = 16; + else if (depth <= 32) + bpp = 32; + else + return FALSE; + } + if (pad <= 0) + pad = BITMAP_SCANLINE_PAD; + + i = pScrn->numFormats++; + pScrn->formats[i].depth = depth; + pScrn->formats[i].bitsPerPixel = bpp; + pScrn->formats[i].scanlinePad = pad; + return TRUE; +} + +/* + * Set the depth we are using based on (in the following order of preference): + * - values given on the command line + * - values given in the config file + * - values provided by the driver + * - an overall default when nothing else is given + * + * Also find a Display subsection matching the depth/bpp found. + * + * Sets the following ScrnInfoRec fields: + * bitsPerPixel, pixmap24, depth, display, imageByteOrder, + * bitmapScanlinePad, bitmapScanlineUnit, bitmapBitOrder, numFormats, + * formats, fbFormat. + */ + +/* Can the screen handle 24 bpp pixmaps */ +#define DO_PIX24(f) ((f & Support24bppFb) || \ + ((f & Support32bppFb) && (f & SupportConvert24to32))) + +/* Can the screen handle 32 bpp pixmaps */ +#define DO_PIX32(f) ((f & Support32bppFb) || \ + ((f & Support24bppFb) && (f & SupportConvert32to24))) + +/* Does the screen prefer 32bpp fb for 24bpp pixmaps */ +#define CHOOSE32FOR24(f) ((f & Support32bppFb) && (f & SupportConvert24to32) \ + && (f & PreferConvert24to32)) + +/* Does the screen prefer 24bpp fb for 32bpp pixmaps */ +#define CHOOSE24FOR32(f) ((f & Support24bppFb) && (f & SupportConvert32to24) \ + && (f & PreferConvert32to24)) + +/* Can the screen handle 32bpp pixmaps for 24bpp fb */ +#define DO_PIX32FOR24(f) ((f & Support24bppFb) && (f & SupportConvert32to24)) + +/* Can the screen handle 24bpp pixmaps for 32bpp fb */ +#define DO_PIX24FOR32(f) ((f & Support32bppFb) && (f & SupportConvert24to32)) + +#ifndef GLOBAL_DEFAULT_DEPTH +#define GLOBAL_DEFAULT_DEPTH 24 +#endif + +Bool +xf86SetDepthBpp(ScrnInfoPtr scrp, int depth, int dummy, int fbbpp, + int depth24flags) +{ + int i; + DispPtr disp; + Pix24Flags pix24 = xf86Info.pixmap24; + Bool nomatch = FALSE; + + scrp->bitsPerPixel = -1; + scrp->depth = -1; + scrp->pixmap24 = Pix24DontCare; + scrp->bitsPerPixelFrom = X_DEFAULT; + scrp->depthFrom = X_DEFAULT; + + if (xf86FbBpp > 0) { + scrp->bitsPerPixel = xf86FbBpp; + scrp->bitsPerPixelFrom = X_CMDLINE; + } + + if (xf86Depth > 0) { + scrp->depth = xf86Depth; + scrp->depthFrom = X_CMDLINE; + } + + if (xf86FbBpp < 0 && xf86Depth < 0) { + if (scrp->confScreen->defaultfbbpp > 0) { + scrp->bitsPerPixel = scrp->confScreen->defaultfbbpp; + scrp->bitsPerPixelFrom = X_CONFIG; + } + if (scrp->confScreen->defaultdepth > 0) { + scrp->depth = scrp->confScreen->defaultdepth; + scrp->depthFrom = X_CONFIG; + } + + if (scrp->confScreen->defaultfbbpp <= 0 && + scrp->confScreen->defaultdepth <= 0) { + /* + * Check for DefaultDepth and DefaultFbBpp options in the + * Device sections. + */ + int i; + GDevPtr device; + Bool found = FALSE; + + for (i = 0; i < scrp->numEntities; i++) { + device = xf86GetDevFromEntity(scrp->entityList[i], + scrp->entityInstanceList[i]); + if (device && device->options) { + if (xf86FindOption(device->options, "DefaultDepth")) { + scrp->depth = xf86SetIntOption(device->options, + "DefaultDepth", -1); + scrp->depthFrom = X_CONFIG; + found = TRUE; + } + if (xf86FindOption(device->options, "DefaultFbBpp")) { + scrp->bitsPerPixel = xf86SetIntOption(device->options, + "DefaultFbBpp", + -1); + scrp->bitsPerPixelFrom = X_CONFIG; + found = TRUE; + } + } + if (found) + break; + } + } + } + + /* If none of these is set, pick a default */ + if (scrp->bitsPerPixel < 0 && scrp->depth < 0) { + if (fbbpp > 0 || depth > 0) { + if (fbbpp > 0) + scrp->bitsPerPixel = fbbpp; + if (depth > 0) + scrp->depth = depth; + } else { + scrp->depth = GLOBAL_DEFAULT_DEPTH; + } + } + + /* If any are not given, determine a default for the others */ + + if (scrp->bitsPerPixel < 0) { + /* The depth must be set */ + if (scrp->depth > -1) { + if (scrp->depth == 1) + scrp->bitsPerPixel = 1; + else if (scrp->depth <= 4) + scrp->bitsPerPixel = 4; + else if (scrp->depth <= 8) + scrp->bitsPerPixel = 8; + else if (scrp->depth <= 16) + scrp->bitsPerPixel = 16; + else if (scrp->depth <= 24) { + /* + * Figure out if a choice is possible based on the depth24 + * and pix24 flags. + */ + /* Check pix24 first */ + if (pix24 != Pix24DontCare) { + if (pix24 == Pix24Use32) { + if (DO_PIX32(depth24flags)) { + if (CHOOSE24FOR32(depth24flags)) + scrp->bitsPerPixel = 24; + else + scrp->bitsPerPixel = 32; + } else { + nomatch = TRUE; + } + } else if (pix24 == Pix24Use24) { + if (DO_PIX24(depth24flags)) { + if (CHOOSE32FOR24(depth24flags)) + scrp->bitsPerPixel = 32; + else + scrp->bitsPerPixel = 24; + } else { + nomatch = TRUE; + } + } + } else { + if (DO_PIX32(depth24flags)) { + if (CHOOSE24FOR32(depth24flags)) + scrp->bitsPerPixel = 24; + else + scrp->bitsPerPixel = 32; + } else if (DO_PIX24(depth24flags)) { + if (CHOOSE32FOR24(depth24flags)) + scrp->bitsPerPixel = 32; + else + scrp->bitsPerPixel = 24; + } + } + } else if (scrp->depth <= 32) + scrp->bitsPerPixel = 32; + else { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Specified depth (%d) is greater than 32\n", + scrp->depth); + return FALSE; + } + } else { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "xf86SetDepthBpp: internal error: depth and fbbpp" + " are both not set\n"); + return FALSE; + } + if (scrp->bitsPerPixel < 0) { + if (nomatch) + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Driver can't support depth 24 pixmap format (%d)\n", + PIX24TOBPP(pix24)); + else if ((depth24flags & (Support24bppFb | Support32bppFb)) == + NoDepth24Support) + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Driver can't support depth 24\n"); + else + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Can't find fbbpp for depth 24\n"); + return FALSE; + } + scrp->bitsPerPixelFrom = X_PROBED; + } + + if (scrp->depth <= 0) { + /* bitsPerPixel is already set */ + switch (scrp->bitsPerPixel) { + case 32: + scrp->depth = 24; + break; + default: + /* 1, 4, 8, 16 and 24 */ + scrp->depth = scrp->bitsPerPixel; + break; + } + scrp->depthFrom = X_PROBED; + } + + /* Sanity checks */ + if (scrp->depth < 1 || scrp->depth > 32) { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Specified depth (%d) is not in the range 1-32\n", + scrp->depth); + return FALSE; + } + switch (scrp->bitsPerPixel) { + case 1: + case 4: + case 8: + case 16: + case 24: + case 32: + break; + default: + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Specified fbbpp (%d) is not a permitted value\n", + scrp->bitsPerPixel); + return FALSE; + } + if (scrp->depth > scrp->bitsPerPixel) { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Specified depth (%d) is greater than the fbbpp (%d)\n", + scrp->depth, scrp->bitsPerPixel); + return FALSE; + } + + /* set scrp->pixmap24 if the driver isn't flexible */ + if (scrp->bitsPerPixel == 24 && !DO_PIX32FOR24(depth24flags)) { + scrp->pixmap24 = Pix24Use24; + } + if (scrp->bitsPerPixel == 32 && !DO_PIX24FOR32(depth24flags)) { + scrp->pixmap24 = Pix24Use32; + } + + /* + * Find the Display subsection matching the depth/fbbpp and initialise + * scrp->display with it. + */ + for (i = 0, disp = scrp->confScreen->displays; + i < scrp->confScreen->numdisplays; i++, disp++) { + if ((disp->depth == scrp->depth && disp->fbbpp == scrp->bitsPerPixel) + || (disp->depth == scrp->depth && disp->fbbpp <= 0) + || (disp->fbbpp == scrp->bitsPerPixel && disp->depth <= 0)) { + scrp->display = disp; + break; + } + } + + /* + * If an exact match can't be found, see if there is one with no + * depth or fbbpp specified. + */ + if (i == scrp->confScreen->numdisplays) { + for (i = 0, disp = scrp->confScreen->displays; + i < scrp->confScreen->numdisplays; i++, disp++) { + if (disp->depth <= 0 && disp->fbbpp <= 0) { + scrp->display = disp; + break; + } + } + } + + /* + * If all else fails, create a default one. + */ + if (i == scrp->confScreen->numdisplays) { + scrp->confScreen->numdisplays++; + scrp->confScreen->displays = + xnfrealloc(scrp->confScreen->displays, + scrp->confScreen->numdisplays * sizeof(DispRec)); + xf86DrvMsg(scrp->scrnIndex, X_INFO, + "Creating default Display subsection in Screen section\n" + "\t\"%s\" for depth/fbbpp %d/%d\n", + scrp->confScreen->id, scrp->depth, scrp->bitsPerPixel); + memset(&scrp->confScreen->displays[i], 0, sizeof(DispRec)); + scrp->confScreen->displays[i].blackColour.red = -1; + scrp->confScreen->displays[i].blackColour.green = -1; + scrp->confScreen->displays[i].blackColour.blue = -1; + scrp->confScreen->displays[i].whiteColour.red = -1; + scrp->confScreen->displays[i].whiteColour.green = -1; + scrp->confScreen->displays[i].whiteColour.blue = -1; + scrp->confScreen->displays[i].defaultVisual = -1; + scrp->confScreen->displays[i].modes = xnfalloc(sizeof(char *)); + scrp->confScreen->displays[i].modes[0] = NULL; + scrp->confScreen->displays[i].depth = depth; + scrp->confScreen->displays[i].fbbpp = fbbpp; + scrp->display = &scrp->confScreen->displays[i]; + } + + /* + * Setup defaults for the display-wide attributes the framebuffer will + * need. These defaults should eventually be set globally, and not + * dependent on the screens. + */ + scrp->imageByteOrder = IMAGE_BYTE_ORDER; + scrp->bitmapScanlinePad = BITMAP_SCANLINE_PAD; + if (scrp->depth < 8) { + /* Planar modes need these settings */ + scrp->bitmapScanlineUnit = 8; + scrp->bitmapBitOrder = MSBFirst; + } else { + scrp->bitmapScanlineUnit = BITMAP_SCANLINE_UNIT; + scrp->bitmapBitOrder = BITMAP_BIT_ORDER; + } + + /* + * If an unusual depth is required, add it to scrp->formats. The formats + * for the common depths are handled globally in InitOutput + */ + switch (scrp->depth) { + case 1: + case 4: + case 8: + case 15: + case 16: + case 24: + /* Common depths. Nothing to do for them */ + break; + default: + if (!xf86AddPixFormat(scrp, scrp->depth, 0, 0)) { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Can't add pixmap format for depth %d\n", scrp->depth); + return FALSE; + } + } + + /* Initialise the framebuffer format for this screen */ + scrp->fbFormat.depth = scrp->depth; + scrp->fbFormat.bitsPerPixel = scrp->bitsPerPixel; + scrp->fbFormat.scanlinePad = BITMAP_SCANLINE_PAD; + + return TRUE; +} + +/* + * Print out the selected depth and bpp. + */ +void +xf86PrintDepthBpp(ScrnInfoPtr scrp) +{ + xf86DrvMsg(scrp->scrnIndex, scrp->depthFrom, "Depth %d, ", scrp->depth); + xf86Msg(scrp->bitsPerPixelFrom, "framebuffer bpp %d\n", scrp->bitsPerPixel); +} + +/* + * xf86SetWeight sets scrp->weight, scrp->mask, scrp->offset, and for depths + * greater than MAX_PSEUDO_DEPTH also scrp->rgbBits. + */ +Bool +xf86SetWeight(ScrnInfoPtr scrp, rgb weight, rgb mask) +{ + MessageType weightFrom = X_DEFAULT; + + scrp->weight.red = 0; + scrp->weight.green = 0; + scrp->weight.blue = 0; + + if (xf86Weight.red > 0 && xf86Weight.green > 0 && xf86Weight.blue > 0) { + scrp->weight = xf86Weight; + weightFrom = X_CMDLINE; + } else if (scrp->display->weight.red > 0 && scrp->display->weight.green > 0 + && scrp->display->weight.blue > 0) { + scrp->weight = scrp->display->weight; + weightFrom = X_CONFIG; + } else if (weight.red > 0 && weight.green > 0 && weight.blue > 0) { + scrp->weight = weight; + } else { + switch (scrp->depth) { + case 1: + case 4: + case 8: + scrp->weight.red = scrp->weight.green = + scrp->weight.blue = scrp->rgbBits; + break; + case 15: + scrp->weight.red = scrp->weight.green = scrp->weight.blue = 5; + break; + case 16: + scrp->weight.red = scrp->weight.blue = 5; + scrp->weight.green = 6; + break; + case 18: + scrp->weight.red = scrp->weight.green = scrp->weight.blue = 6; + break; + case 24: + scrp->weight.red = scrp->weight.green = scrp->weight.blue = 8; + break; + case 30: + scrp->weight.red = scrp->weight.green = scrp->weight.blue = 10; + break; + } + } + + if (scrp->weight.red) + xf86DrvMsg(scrp->scrnIndex, weightFrom, "RGB weight %d%d%d\n", + (int)scrp->weight.red, (int)scrp->weight.green, + (int)scrp->weight.blue); + + if (scrp->depth > MAX_PSEUDO_DEPTH && + (scrp->depth != scrp->weight.red + scrp->weight.green + + scrp->weight.blue)) { + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Weight given (%d%d%d) is inconsistent with the " + "depth (%d)\n", + (int)scrp->weight.red, (int)scrp->weight.green, + (int)scrp->weight.blue, scrp->depth); + return FALSE; + } + if (scrp->depth > MAX_PSEUDO_DEPTH && scrp->weight.red) { + /* + * XXX Does this even mean anything for TrueColor visuals? + * If not, we shouldn't even be setting it here. However, this + * matches the behaviour of 3.x versions of XFree86. + */ + scrp->rgbBits = scrp->weight.red; + if (scrp->weight.green > scrp->rgbBits) + scrp->rgbBits = scrp->weight.green; + if (scrp->weight.blue > scrp->rgbBits) + scrp->rgbBits = scrp->weight.blue; + } + + /* Set the mask and offsets */ + if (mask.red == 0 || mask.green == 0 || mask.blue == 0) { + /* Default to a setting common to PC hardware */ + scrp->offset.red = scrp->weight.green + scrp->weight.blue; + scrp->offset.green = scrp->weight.blue; + scrp->offset.blue = 0; + scrp->mask.red = ((1 << scrp->weight.red) - 1) << scrp->offset.red; + scrp->mask.green = ((1 << scrp->weight.green) - 1) + << scrp->offset.green; + scrp->mask.blue = (1 << scrp->weight.blue) - 1; + } else { + /* Initialise to the values passed */ + scrp->mask.red = mask.red; + scrp->mask.green = mask.green; + scrp->mask.blue = mask.blue; + scrp->offset.red = ffs(mask.red); + scrp->offset.green = ffs(mask.green); + scrp->offset.blue = ffs(mask.blue); + } + return TRUE; +} + +Bool +xf86SetDefaultVisual(ScrnInfoPtr scrp, int visual) +{ + MessageType visualFrom = X_DEFAULT; + + if (defaultColorVisualClass >= 0) { + scrp->defaultVisual = defaultColorVisualClass; + visualFrom = X_CMDLINE; + } else if (scrp->display->defaultVisual >= 0) { + scrp->defaultVisual = scrp->display->defaultVisual; + visualFrom = X_CONFIG; + } else if (visual >= 0) { + scrp->defaultVisual = visual; + } else { + if (scrp->depth == 1) + scrp->defaultVisual = StaticGray; + else if (scrp->depth == 4) + scrp->defaultVisual = StaticColor; + else if (scrp->depth <= MAX_PSEUDO_DEPTH) + scrp->defaultVisual = PseudoColor; + else + scrp->defaultVisual = TrueColor; + } + switch (scrp->defaultVisual) { + case StaticGray: + case GrayScale: + case StaticColor: + case PseudoColor: + case TrueColor: + case DirectColor: + xf86DrvMsg(scrp->scrnIndex, visualFrom, "Default visual is %s\n", + xf86VisualNames[scrp->defaultVisual]); + return TRUE; + default: + + xf86DrvMsg(scrp->scrnIndex, X_ERROR, + "Invalid default visual class (%d)\n", scrp->defaultVisual); + return FALSE; + } +} + +#define TEST_GAMMA(g) \ + (g).red > GAMMA_ZERO || (g).green > GAMMA_ZERO || (g).blue > GAMMA_ZERO + +#define SET_GAMMA(g) \ + (g) > GAMMA_ZERO ? (g) : 1.0 + +Bool +xf86SetGamma(ScrnInfoPtr scrp, Gamma gamma) +{ + MessageType from = X_DEFAULT; +#if 0 + xf86MonPtr DDC = (xf86MonPtr)(scrp->monitor->DDC); +#endif + if (TEST_GAMMA(xf86Gamma)) { + from = X_CMDLINE; + scrp->gamma.red = SET_GAMMA(xf86Gamma.red); + scrp->gamma.green = SET_GAMMA(xf86Gamma.green); + scrp->gamma.blue = SET_GAMMA(xf86Gamma.blue); + } else if (TEST_GAMMA(scrp->monitor->gamma)) { + from = X_CONFIG; + scrp->gamma.red = SET_GAMMA(scrp->monitor->gamma.red); + scrp->gamma.green = SET_GAMMA(scrp->monitor->gamma.green); + scrp->gamma.blue = SET_GAMMA(scrp->monitor->gamma.blue); +#if 0 + } else if ( DDC && DDC->features.gamma > GAMMA_ZERO ) { + from = X_PROBED; + scrp->gamma.red = SET_GAMMA(DDC->features.gamma); + scrp->gamma.green = SET_GAMMA(DDC->features.gamma); + scrp->gamma.blue = SET_GAMMA(DDC->features.gamma); + /* EDID structure version 2 gives optional seperate red, green & blue gamma values + * in bytes 0x57-0x59 */ +#endif + } else if (TEST_GAMMA(gamma)) { + scrp->gamma.red = SET_GAMMA(gamma.red); + scrp->gamma.green = SET_GAMMA(gamma.green); + scrp->gamma.blue = SET_GAMMA(gamma.blue); + } else { + scrp->gamma.red = 1.0; + scrp->gamma.green = 1.0; + scrp->gamma.blue = 1.0; + } + /* Pretend we succeeded if we support better a gamma system. + * This avoids a confusing message. + */ + if (xf86_crtc_supports_gamma(scrp)) + return TRUE; + xf86DrvMsg(scrp->scrnIndex, from, + "Using gamma correction (%.1f, %.1f, %.1f)\n", + scrp->gamma.red, scrp->gamma.green, scrp->gamma.blue); + + return TRUE; +} + +#undef TEST_GAMMA +#undef SET_GAMMA + + +/* + * Set the DPI from the command line option. XXX should allow it to be + * calculated from the widthmm/heightmm values. + */ + +#undef MMPERINCH +#define MMPERINCH 25.4 + +void +xf86SetDpi(ScrnInfoPtr pScrn, int x, int y) +{ + MessageType from = X_DEFAULT; + xf86MonPtr DDC = (xf86MonPtr)(pScrn->monitor->DDC); + int ddcWidthmm, ddcHeightmm; + int widthErr, heightErr; + + /* XXX Maybe there is no need for widthmm/heightmm in ScrnInfoRec */ + pScrn->widthmm = pScrn->monitor->widthmm; + pScrn->heightmm = pScrn->monitor->heightmm; + + if (DDC && (DDC->features.hsize > 0 && DDC->features.vsize > 0) ) { + /* DDC gives display size in mm for individual modes, + * but cm for monitor + */ + ddcWidthmm = DDC->features.hsize * 10; /* 10mm in 1cm */ + ddcHeightmm = DDC->features.vsize * 10; /* 10mm in 1cm */ + } else { + ddcWidthmm = ddcHeightmm = 0; + } + + if (monitorResolution > 0) { + pScrn->xDpi = monitorResolution; + pScrn->yDpi = monitorResolution; + from = X_CMDLINE; + } else if (pScrn->widthmm > 0 || pScrn->heightmm > 0) { + from = X_CONFIG; + if (pScrn->widthmm > 0) { + pScrn->xDpi = + (int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm); + } + if (pScrn->heightmm > 0) { + pScrn->yDpi = + (int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm); + } + if (pScrn->xDpi > 0 && pScrn->yDpi <= 0) + pScrn->yDpi = pScrn->xDpi; + if (pScrn->yDpi > 0 && pScrn->xDpi <= 0) + pScrn->xDpi = pScrn->yDpi; + xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n", + pScrn->widthmm, pScrn->heightmm); + + /* Warn if config and probe disagree about display size */ + if ( ddcWidthmm && ddcHeightmm ) { + if (pScrn->widthmm > 0) { + widthErr = abs(ddcWidthmm - pScrn->widthmm); + } else { + widthErr = 0; + } + if (pScrn->heightmm > 0) { + heightErr = abs(ddcHeightmm - pScrn->heightmm); + } else { + heightErr = 0; + } + if (widthErr>10 || heightErr>10) { + /* Should include config file name for monitor here */ + xf86DrvMsg(pScrn->scrnIndex, X_WARNING, + "Probed monitor is %dx%d mm, using Displaysize %dx%d mm\n", + ddcWidthmm,ddcHeightmm, pScrn->widthmm,pScrn->heightmm); + } + } + } else if ( ddcWidthmm && ddcHeightmm ) { + from = X_PROBED; + xf86DrvMsg(pScrn->scrnIndex, from, "Display dimensions: (%d, %d) mm\n", + ddcWidthmm, ddcHeightmm ); + pScrn->widthmm = ddcWidthmm; + pScrn->heightmm = ddcHeightmm; + if (pScrn->widthmm > 0) { + pScrn->xDpi = + (int)((double)pScrn->virtualX * MMPERINCH / pScrn->widthmm); + } + if (pScrn->heightmm > 0) { + pScrn->yDpi = + (int)((double)pScrn->virtualY * MMPERINCH / pScrn->heightmm); + } + if (pScrn->xDpi > 0 && pScrn->yDpi <= 0) + pScrn->yDpi = pScrn->xDpi; + if (pScrn->yDpi > 0 && pScrn->xDpi <= 0) + pScrn->xDpi = pScrn->yDpi; + } else { + if (x > 0) + pScrn->xDpi = x; + else + pScrn->xDpi = DEFAULT_DPI; + if (y > 0) + pScrn->yDpi = y; + else + pScrn->yDpi = DEFAULT_DPI; + } + xf86DrvMsg(pScrn->scrnIndex, from, "DPI set to (%d, %d)\n", + pScrn->xDpi, pScrn->yDpi); +} + +#undef MMPERINCH + + +void +xf86SetBlackWhitePixels(ScreenPtr pScreen) +{ + if (xf86FlipPixels) { + pScreen->whitePixel = 0; + pScreen->blackPixel = 1; + } else { + pScreen->whitePixel = 1; + pScreen->blackPixel = 0; + } +} + +/* + * Function to enable/disable access to the frame buffer + * + * This is used when VT switching and when entering/leaving DGA direct mode. + * + * This has been rewritten again to eliminate the saved pixmap. The + * devPrivate field in the screen pixmap is set to NULL to catch code + * accidentally referencing the frame buffer while the X server is not + * supposed to touch it. + * + * Here, we exchange the pixmap private data, rather than the pixmaps + * themselves to avoid having to find and change any references to the screen + * pixmap such as GC's, window privates etc. This also means that this code + * does not need to know exactly how the pixmap pixels are accessed. Further, + * this exchange is >not< done through the screen's ModifyPixmapHeader() + * vector. This means the called frame buffer code layers can determine + * whether they are switched in or out by keeping track of the root pixmap's + * private data, and therefore don't need to access pScrnInfo->vtSema. + */ +void +xf86EnableDisableFBAccess(int scrnIndex, Bool enable) +{ + ScrnInfoPtr pScrnInfo = xf86Screens[scrnIndex]; + ScreenPtr pScreen = pScrnInfo->pScreen; + PixmapPtr pspix; + + pspix = (*pScreen->GetScreenPixmap) (pScreen); + if (enable) + { + /* + * Restore all of the clip lists on the screen + */ + if (!xf86Resetting) + SetRootClip (pScreen, TRUE); + + } + else + { + /* + * Empty all of the clip lists on the screen + */ + SetRootClip (pScreen, FALSE); + } +} + +/* Print driver messages in the standard format */ + +#undef PREFIX_SIZE +#define PREFIX_SIZE 14 + +void +xf86VDrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format, + va_list args) +{ + char *tmpFormat; + + /* Prefix the scrnIndex name to the format string. */ + if (scrnIndex >= 0 && scrnIndex < xf86NumScreens && + xf86Screens[scrnIndex]->name) { + tmpFormat = malloc(strlen(format) + + strlen(xf86Screens[scrnIndex]->name) + + PREFIX_SIZE + 1); + if (!tmpFormat) + return; + + snprintf(tmpFormat, PREFIX_SIZE + 1, "%s(%d): ", + xf86Screens[scrnIndex]->name, scrnIndex); + + strcat(tmpFormat, format); + LogVMessageVerb(type, verb, tmpFormat, args); + free(tmpFormat); + } else + LogVMessageVerb(type, verb, format, args); +} +#undef PREFIX_SIZE + +/* Print driver messages, with verbose level specified directly */ +void +xf86DrvMsgVerb(int scrnIndex, MessageType type, int verb, const char *format, + ...) +{ + va_list ap; + + va_start(ap, format); + xf86VDrvMsgVerb(scrnIndex, type, verb, format, ap); + va_end(ap); +} + +/* Print driver messages, with verbose level of 1 (default) */ +void +xf86DrvMsg(int scrnIndex, MessageType type, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + xf86VDrvMsgVerb(scrnIndex, type, 1, format, ap); + va_end(ap); +} + +/* Print input driver messages in the standard format of + <driver>: <device name>: <message> */ +void +xf86VIDrvMsgVerb(InputInfoPtr dev, MessageType type, int verb, const char *format, + va_list args) +{ + char *msg; + + if (asprintf(&msg, "%s: %s: %s", dev->drv->driverName, dev->name, format) + == -1) { + LogVMessageVerb(type, verb, "%s", args); + } else { + LogVMessageVerb(type, verb, msg, args); + free(msg); + } +} + +/* Print input driver message, with verbose level specified directly */ +void +xf86IDrvMsgVerb(InputInfoPtr dev, MessageType type, int verb, const char *format, + ...) +{ + va_list ap; + + va_start(ap, format); + xf86VIDrvMsgVerb(dev, type, verb, format, ap); + va_end(ap); +} + +/* Print input driver messages, with verbose level of 1 (default) */ +void +xf86IDrvMsg(InputInfoPtr dev, MessageType type, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + xf86VIDrvMsgVerb(dev, type, 1, format, ap); + va_end(ap); +} + + +/* Print non-driver messages with verbose level specified directly */ +void +xf86MsgVerb(MessageType type, int verb, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + LogVMessageVerb(type, verb, format, ap); + va_end(ap); +} + +/* Print non-driver messages with verbose level of 1 (default) */ +void +xf86Msg(MessageType type, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + LogVMessageVerb(type, 1, format, ap); + va_end(ap); +} + +/* Just like ErrorF, but with the verbose level checked */ +void +xf86ErrorFVerb(int verb, const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + if (xf86Verbose >= verb || xf86LogVerbose >= verb) + LogVWrite(verb, format, ap); + va_end(ap); +} + +/* Like xf86ErrorFVerb, but with an implied verbose level of 1 */ +void +xf86ErrorF(const char *format, ...) +{ + va_list ap; + + va_start(ap, format); + if (xf86Verbose >= 1 || xf86LogVerbose >= 1) + LogVWrite(1, format, ap); + va_end(ap); +} + + +void +xf86LogInit(void) +{ + char *lf = NULL; + +#define LOGSUFFIX ".log" +#define LOGOLDSUFFIX ".old" + + /* Get the log file name */ + if (xf86LogFileFrom == X_DEFAULT) { + /* Append the display number and ".log" */ + if (asprintf(&lf, "%s%%s" LOGSUFFIX, xf86LogFile) == -1) + FatalError("Cannot allocate space for the log file name\n"); + xf86LogFile = lf; + } + + xf86LogFile = LogInit(xf86LogFile, LOGOLDSUFFIX); + xf86LogFileWasOpened = TRUE; + + xf86SetVerbosity(xf86Verbose); + xf86SetLogVerbosity(xf86LogVerbose); + +#undef LOGSUFFIX +#undef LOGOLDSUFFIX + + free(lf); +} + +void +xf86CloseLog(enum ExitCode error) +{ + LogClose(error); +} + + +/* + * Drivers can use these for using their own SymTabRecs. + */ + +const char * +xf86TokenToString(SymTabPtr table, int token) +{ + int i; + + for (i = 0; table[i].token >= 0 && table[i].token != token; i++) + ; + + if (table[i].token < 0) + return NULL; + else + return table[i].name; +} + +int +xf86StringToToken(SymTabPtr table, const char *string) +{ + int i; + + if (string == NULL) + return -1; + + for (i = 0; table[i].token >= 0 && xf86NameCmp(string, table[i].name); i++) + ; + + return table[i].token; +} + +/* + * helper to display the clocks found on a card + */ +void +xf86ShowClocks(ScrnInfoPtr scrp, MessageType from) +{ + int j; + + xf86DrvMsg(scrp->scrnIndex, from, "Pixel clocks available:"); + for (j=0; j < scrp->numClocks; j++) { + if ((j % 4) == 0) { + xf86ErrorF("\n"); + xf86DrvMsg(scrp->scrnIndex, from, "pixel clocks:"); + } + xf86ErrorF(" %7.3f", (double)scrp->clock[j] / 1000.0); + } + xf86ErrorF("\n"); +} + + +/* + * This prints out the driver identify message, including the names of + * the supported chipsets. + * + * XXX This makes assumptions about the line width, etc. Maybe we could + * use a more general "pretty print" function for messages. + */ +void +xf86PrintChipsets(const char *drvname, const char *drvmsg, SymTabPtr chips) +{ + int len, i; + + len = 6 + strlen(drvname) + 2 + strlen(drvmsg) + 2; + xf86Msg(X_INFO, "%s: %s:", drvname, drvmsg); + for (i = 0; chips[i].name != NULL; i++) { + if (i != 0) { + xf86ErrorF(","); + len++; + } + if (len + 2 + strlen(chips[i].name) < 78) { + xf86ErrorF(" "); + len++; + } else { + xf86ErrorF("\n\t"); + len = 8; + } + xf86ErrorF("%s", chips[i].name); + len += strlen(chips[i].name); + } + xf86ErrorF("\n"); +} + + +int +xf86MatchDevice(const char *drivername, GDevPtr **sectlist) +{ + GDevPtr gdp, *pgdp = NULL; + confScreenPtr screensecptr; + int i,j; + + if (sectlist) + *sectlist = NULL; + + /* + * This can happen when running Xorg -showopts and a module like ati + * or vmware tries to load its submodules when xf86ConfigLayout is empty + */ + if (!xf86ConfigLayout.screens) + return 0; + + /* + * This is a very important function that matches the device sections + * as they show up in the config file with the drivers that the server + * loads at run time. + * + * ChipProbe can call + * int xf86MatchDevice(char * drivername, GDevPtr ** sectlist) + * with its driver name. The function allocates an array of GDevPtr and + * returns this via sectlist and returns the number of elements in + * this list as return value. 0 means none found, -1 means fatal error. + * + * It can figure out which of the Device sections to use for which card + * (using things like the Card statement, etc). For single headed servers + * there will of course be just one such Device section. + */ + i = 0; + + /* + * first we need to loop over all the Screens sections to get to all + * 'active' device sections + */ + for (j=0; xf86ConfigLayout.screens[j].screen != NULL; j++) { + screensecptr = xf86ConfigLayout.screens[j].screen; + if ((screensecptr->device->driver != NULL) + && (xf86NameCmp( screensecptr->device->driver,drivername) == 0) + && (! screensecptr->device->claimed)) { + /* + * we have a matching driver that wasn't claimed, yet + */ + pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr)); + pgdp[i++] = screensecptr->device; + } + } + + /* Then handle the inactive devices */ + j = 0; + while (xf86ConfigLayout.inactives[j].identifier) { + gdp = &xf86ConfigLayout.inactives[j]; + if (gdp->driver && !gdp->claimed && + !xf86NameCmp(gdp->driver,drivername)) { + /* we have a matching driver that wasn't claimed yet */ + pgdp = xnfrealloc(pgdp, (i + 2) * sizeof(GDevPtr)); + pgdp[i++] = gdp; + } + j++; + } + + /* + * make the array NULL terminated and return its address + */ + if (i) + pgdp[i] = NULL; + + if (sectlist) + *sectlist = pgdp; + else + free(pgdp); + return i; +} + +/* + * xf86GetClocks -- get the dot-clocks via a BIG BAD hack ... + */ +void +xf86GetClocks(ScrnInfoPtr pScrn, int num, Bool (*ClockFunc)(ScrnInfoPtr, int), + void (*ProtectRegs)(ScrnInfoPtr, Bool), + void (*BlankScreen)(ScrnInfoPtr, Bool), IOADDRESS vertsyncreg, + int maskval, int knownclkindex, int knownclkvalue) +{ + register int status = vertsyncreg; + unsigned long i, cnt, rcnt, sync; + + /* First save registers that get written on */ + (*ClockFunc)(pScrn, CLK_REG_SAVE); + + if (num > MAXCLOCKS) + num = MAXCLOCKS; + + for (i = 0; i < num; i++) + { + if (ProtectRegs) + (*ProtectRegs)(pScrn, TRUE); + if (!(*ClockFunc)(pScrn, i)) + { + pScrn->clock[i] = -1; + continue; + } + if (ProtectRegs) + (*ProtectRegs)(pScrn, FALSE); + if (BlankScreen) + (*BlankScreen)(pScrn, FALSE); + + usleep(50000); /* let VCO stabilise */ + + cnt = 0; + sync = 200000; + + while ((inb(status) & maskval) == 0x00) + if (sync-- == 0) goto finish; + /* Something appears to be happening, so reset sync count */ + sync = 200000; + while ((inb(status) & maskval) == maskval) + if (sync-- == 0) goto finish; + /* Something appears to be happening, so reset sync count */ + sync = 200000; + while ((inb(status) & maskval) == 0x00) + if (sync-- == 0) goto finish; + + for (rcnt = 0; rcnt < 5; rcnt++) + { + while (!(inb(status) & maskval)) + cnt++; + while ((inb(status) & maskval)) + cnt++; + } + +finish: + pScrn->clock[i] = cnt ? cnt : -1; + if (BlankScreen) + (*BlankScreen)(pScrn, TRUE); + } + + for (i = 0; i < num; i++) + { + if (i != knownclkindex) + { + if (pScrn->clock[i] == -1) + { + pScrn->clock[i] = 0; + } + else + { + pScrn->clock[i] = (int)(0.5 + + (((float)knownclkvalue) * pScrn->clock[knownclkindex]) / + (pScrn->clock[i])); + /* Round to nearest 10KHz */ + pScrn->clock[i] += 5; + pScrn->clock[i] /= 10; + pScrn->clock[i] *= 10; + } + } + } + + pScrn->clock[knownclkindex] = knownclkvalue; + pScrn->numClocks = num; + + /* Restore registers that were written on */ + (*ClockFunc)(pScrn, CLK_REG_RESTORE); +} + +const char * +xf86GetVisualName(int visual) +{ + if (visual < 0 || visual > DirectColor) + return NULL; + + return xf86VisualNames[visual]; +} + + +int +xf86GetVerbosity(void) +{ + return max(xf86Verbose, xf86LogVerbose); +} + +Pix24Flags +xf86GetPix24(void) +{ + return xf86Info.pixmap24; +} + + +int +xf86GetDepth(void) +{ + return xf86Depth; +} + + +rgb +xf86GetWeight(void) +{ + return xf86Weight; +} + + +Gamma +xf86GetGamma(void) +{ + return xf86Gamma; +} + + +Bool +xf86GetFlipPixels(void) +{ + return xf86FlipPixels; +} + + +const char * +xf86GetServerName(void) +{ + return xf86ServerName; +} + + +Bool +xf86ServerIsExiting(void) +{ + return (dispatchException & DE_TERMINATE) == DE_TERMINATE; +} + + +Bool +xf86ServerIsResetting(void) +{ + return xf86Resetting; +} + + +Bool +xf86ServerIsInitialising(void) +{ + return xf86Initialising; +} + + +Bool +xf86ServerIsOnlyDetecting(void) +{ + return xf86DoConfigure; +} + + +Bool +xf86CaughtSignal(void) +{ + return xf86Info.caughtSignal; +} + + +Bool +xf86GetVidModeAllowNonLocal(void) +{ + return xf86Info.vidModeAllowNonLocal; +} + + +Bool +xf86GetVidModeEnabled(void) +{ + return xf86Info.vidModeEnabled; +} + +Bool +xf86GetModInDevAllowNonLocal(void) +{ + return xf86Info.miscModInDevAllowNonLocal; +} + + +Bool +xf86GetModInDevEnabled(void) +{ + return xf86Info.miscModInDevEnabled; +} + + +Bool +xf86GetAllowMouseOpenFail(void) +{ + return xf86Info.allowMouseOpenFail; +} + + +Bool +xf86IsPc98(void) +{ +#if SUPPORT_PC98 + return xf86Info.pc98; +#else + return FALSE; +#endif +} + +void +xf86DisableRandR(void) +{ + xf86Info.disableRandR = TRUE; + xf86Info.randRFrom = X_PROBED; +} + +CARD32 +xf86GetModuleVersion(pointer module) +{ + return (CARD32)LoaderGetModuleVersion(module); +} + +pointer +xf86LoadDrvSubModule(DriverPtr drv, const char *name) +{ + pointer ret; + int errmaj = 0, errmin = 0; + + ret = LoadSubModule(drv->module, name, NULL, NULL, NULL, NULL, + &errmaj, &errmin); + if (!ret) + LoaderErrorMsg(NULL, name, errmaj, errmin); + return ret; +} + +pointer +xf86LoadSubModule(ScrnInfoPtr pScrn, const char *name) +{ + pointer ret; + int errmaj = 0, errmin = 0; + + ret = LoadSubModule(pScrn->module, name, NULL, NULL, NULL, NULL, + &errmaj, &errmin); + if (!ret) + LoaderErrorMsg(pScrn->name, name, errmaj, errmin); + return ret; +} + +/* + * xf86LoadOneModule loads a single module. + */ +pointer +xf86LoadOneModule(char *name, pointer opt) +{ + int errmaj, errmin; + char *Name; + pointer mod; + + if (!name) + return NULL; + + /* Normalise the module name */ + Name = xf86NormalizeName(name); + + /* Skip empty names */ + if (Name == NULL) + return NULL; + if (*Name == '\0') { + free(Name); + return NULL; + } + + mod = LoadModule(Name, NULL, NULL, NULL, opt, NULL, &errmaj, &errmin); + if (!mod) + LoaderErrorMsg(NULL, Name, errmaj, errmin); + free(Name); + return mod; +} + +void +xf86UnloadSubModule(pointer mod) +{ + /* + * This is disabled for now. The loader isn't smart enough yet to undo + * relocations. + */ +#if 0 + UnloadSubModule(mod); +#endif +} + +Bool +xf86LoaderCheckSymbol(const char *name) +{ + return LoaderSymbol(name) != NULL; +} + +typedef enum { + OPTION_BACKING_STORE +} BSOpts; + +static const OptionInfoRec BSOptions[] = { + { OPTION_BACKING_STORE, "BackingStore", OPTV_BOOLEAN, {0}, FALSE }, + { -1, NULL, OPTV_NONE, {0}, FALSE } +}; + +void +xf86SetBackingStore(ScreenPtr pScreen) +{ + Bool useBS = FALSE; + MessageType from = X_DEFAULT; + ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; + OptionInfoPtr options; + + options = xnfalloc(sizeof(BSOptions)); + (void)memcpy(options, BSOptions, sizeof(BSOptions)); + xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options); + + /* check for commandline option here */ + if (xf86bsEnableFlag) { + from = X_CMDLINE; + useBS = TRUE; + } else if (xf86bsDisableFlag) { + from = X_CMDLINE; + useBS = FALSE; + } else { + if (xf86GetOptValBool(options, OPTION_BACKING_STORE, &useBS)) + from = X_CONFIG; + } + free(options); + pScreen->backingStoreSupport = useBS ? Always : NotUseful; + if (serverGeneration == 1) + xf86DrvMsg(pScreen->myNum, from, "Backing store %s\n", + useBS ? "enabled" : "disabled"); +} + + +typedef enum { + OPTION_SILKEN_MOUSE +} SMOpts; + +static const OptionInfoRec SMOptions[] = { + { OPTION_SILKEN_MOUSE, "SilkenMouse", OPTV_BOOLEAN, {0}, FALSE }, + { -1, NULL, OPTV_NONE, {0}, FALSE } +}; + +void +xf86SetSilkenMouse (ScreenPtr pScreen) +{ + Bool useSM = TRUE; + MessageType from = X_DEFAULT; + ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; + OptionInfoPtr options; + + options = xnfalloc(sizeof(SMOptions)); + (void)memcpy(options, SMOptions, sizeof(SMOptions)); + xf86ProcessOptions(pScrn->scrnIndex, pScrn->options, options); + + /* check for commandline option here */ + /* disable if screen shares resources */ + /* TODO VGA arb disable silken mouse */ + if (xf86silkenMouseDisableFlag) { + from = X_CMDLINE; + useSM = FALSE; + } else { + if (xf86GetOptValBool(options, OPTION_SILKEN_MOUSE, &useSM)) + from = X_CONFIG; + } + free(options); + /* + * XXX quick hack to report correctly for OSs that can't do SilkenMouse + * yet. Should handle this differently so that alternate async methods + * work correctly with this too. + */ + pScrn->silkenMouse = useSM && xf86Info.useSIGIO && xf86SIGIOSupported(); + if (serverGeneration == 1) + xf86DrvMsg(pScreen->myNum, from, "Silken mouse %s\n", + pScrn->silkenMouse ? "enabled" : "disabled"); +} + +/* Wrote this function for the PM2 Xv driver, preliminary. */ + +pointer +xf86FindXvOptions(int scrnIndex, int adaptor_index, char *port_name, + char **adaptor_name, pointer *adaptor_options) +{ + ScrnInfoPtr pScrn = xf86Screens[scrnIndex]; + confXvAdaptorPtr adaptor; + int i; + + if (adaptor_index >= pScrn->confScreen->numxvadaptors) { + if (adaptor_name) *adaptor_name = NULL; + if (adaptor_options) *adaptor_options = NULL; + return NULL; + } + + adaptor = &pScrn->confScreen->xvadaptors[adaptor_index]; + if (adaptor_name) *adaptor_name = adaptor->identifier; + if (adaptor_options) *adaptor_options = adaptor->options; + + for (i = 0; i < adaptor->numports; i++) + if (!xf86NameCmp(adaptor->ports[i].identifier, port_name)) + return adaptor->ports[i].options; + + return NULL; +} + +/* Rather than duplicate loader's get OS function, just include it directly */ +#define LoaderGetOS xf86GetOS +#include "loader/os.c" + +static void +xf86ConfigFbEntityInactive(EntityInfoPtr pEnt, EntityProc init, + EntityProc enter, EntityProc leave, pointer private) +{ + ScrnInfoPtr pScrn; + + if ((pScrn = xf86FindScreenForEntity(pEnt->index))) + xf86RemoveEntityFromScreen(pScrn,pEnt->index); + xf86SetEntityFuncs(pEnt->index,init,enter,leave,private); +} + +ScrnInfoPtr +xf86ConfigFbEntity(ScrnInfoPtr pScrn, int scrnFlag, int entityIndex, + EntityProc init, EntityProc enter, EntityProc leave, + pointer private) +{ + EntityInfoPtr pEnt = xf86GetEntityInfo(entityIndex); + if (!pEnt) return pScrn; + + if (!(pEnt->location.type == BUS_NONE)) { + free(pEnt); + return pScrn; + } + + if (!pEnt->active) { + xf86ConfigFbEntityInactive(pEnt, init, enter, leave, private); + free(pEnt); + return pScrn; + } + + if (!pScrn) + pScrn = xf86AllocateScreen(pEnt->driver,scrnFlag); + xf86AddEntityToScreen(pScrn,entityIndex); + + xf86SetEntityFuncs(entityIndex,init,enter,leave,private); + + free(pEnt); + return pScrn; +} + +Bool +xf86IsScreenPrimary(int scrnIndex) +{ + ScrnInfoPtr pScrn = xf86Screens[scrnIndex]; + int i; + + for (i=0 ; i < pScrn->numEntities; i++) { + if (xf86IsEntityPrimary(i)) + return TRUE; + } + return FALSE; +} + +int +xf86RegisterRootWindowProperty(int ScrnIndex, Atom property, Atom type, + int format, unsigned long len, pointer value ) +{ + RootWinPropPtr pNewProp = NULL, pRegProp; + int i; + Bool existing = FALSE; + + DebugF("xf86RegisterRootWindowProperty(%d, %ld, %ld, %d, %ld, %p)\n", + ScrnIndex, property, type, format, len, value); + + if (ScrnIndex<0 || ScrnIndex>=xf86NumScreens) { + return BadMatch; + } + + if (xf86RegisteredPropertiesTable && + xf86RegisteredPropertiesTable[ScrnIndex]) { + for (pNewProp = xf86RegisteredPropertiesTable[ScrnIndex]; + pNewProp; pNewProp = pNewProp->next) { + if (strcmp(pNewProp->name, NameForAtom(property)) == 0) + break; + } + } + + if (!pNewProp) { + if ((pNewProp = (RootWinPropPtr)malloc(sizeof(RootWinProp))) == NULL) { + return BadAlloc; + } + /* + * We will put this property at the end of the list so that + * the changes are made in the order they were requested. + */ + pNewProp->next = NULL; + } else { + free(pNewProp->name); + existing = TRUE; + } + + pNewProp->name = xnfstrdup(NameForAtom(property)); + pNewProp->type = type; + pNewProp->format = format; + pNewProp->size = len; + pNewProp->data = value; + + DebugF("new property filled\n"); + + if (NULL==xf86RegisteredPropertiesTable) { + DebugF("creating xf86RegisteredPropertiesTable[] size %d\n", + xf86NumScreens); + if ( NULL==(xf86RegisteredPropertiesTable=(RootWinPropPtr*)xnfcalloc(sizeof(RootWinProp),xf86NumScreens) )) { + return BadAlloc; + } + for (i=0; i<xf86NumScreens; i++) { + xf86RegisteredPropertiesTable[i] = NULL; + } + } + + DebugF("xf86RegisteredPropertiesTable %p\n", + (void *)xf86RegisteredPropertiesTable); + DebugF("xf86RegisteredPropertiesTable[%d] %p\n", + ScrnIndex, (void *)xf86RegisteredPropertiesTable[ScrnIndex]); + + if (!existing) { + if ( xf86RegisteredPropertiesTable[ScrnIndex] == NULL) { + xf86RegisteredPropertiesTable[ScrnIndex] = pNewProp; + } else { + pRegProp = xf86RegisteredPropertiesTable[ScrnIndex]; + while (pRegProp->next != NULL) { + DebugF("- next %p\n", (void *)pRegProp); + pRegProp = pRegProp->next; + } + pRegProp->next = pNewProp; + } + } + DebugF("xf86RegisterRootWindowProperty succeeded\n"); + return Success; +} + +Bool +xf86IsUnblank(int mode) +{ + switch(mode) { + case SCREEN_SAVER_OFF: + case SCREEN_SAVER_FORCER: + return TRUE; + case SCREEN_SAVER_ON: + case SCREEN_SAVER_CYCLE: + return FALSE; + default: + xf86MsgVerb(X_WARNING, 0, "Unexpected save screen mode: %d\n", mode); + return TRUE; + } +} + +void +xf86MotionHistoryAllocate(InputInfoPtr pInfo) +{ + AllocateMotionHistory(pInfo->dev); +} diff --git a/xorg-server/hw/xfree86/common/xf86Init.c b/xorg-server/hw/xfree86/common/xf86Init.c index 94e1a5dbd..71926f8e7 100644 --- a/xorg-server/hw/xfree86/common/xf86Init.c +++ b/xorg-server/hw/xfree86/common/xf86Init.c @@ -1,1520 +1,1520 @@ -/*
- * Loosely based on code bearing the following copyright:
- *
- * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany.
- */
-/*
- * Copyright (c) 1992-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-#include <errno.h>
-
-#undef HAS_UTSNAME
-#if !defined(WIN32)
-#define HAS_UTSNAME 1
-#include <sys/utsname.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-#include <X11/Xproto.h>
-#include <X11/Xatom.h>
-#include "input.h"
-#include "servermd.h"
-#include "windowstr.h"
-#include "scrnintstr.h"
-#include "site.h"
-#include "mi.h"
-
-#include "compiler.h"
-
-#include "loaderProcs.h"
-#ifdef XFreeXDGA
-#include "dgaproc.h"
-#endif
-
-#define XF86_OS_PRIVS
-#include "xf86.h"
-#include "xf86Priv.h"
-#include "xf86Config.h"
-#include "xf86_OSlib.h"
-#include "xf86cmap.h"
-#include "xorgVersion.h"
-#include "xf86Build.h"
-#include "mipointer.h"
-#include <X11/extensions/XI.h>
-#include <X11/extensions/XIproto.h>
-#include "xf86DDC.h"
-#include "xf86Xinput.h"
-#include "xf86InPriv.h"
-#include "picturestr.h"
-
-#include "xf86Bus.h"
-#include "xf86VGAarbiter.h"
-#include "globals.h"
-
-#ifdef DPMSExtension
-#include <X11/extensions/dpmsconst.h>
-#include "dpmsproc.h"
-#endif
-#include <hotplug.h>
-
-
-#ifdef XF86PM
-void (*xf86OSPMClose)(void) = NULL;
-#endif
-static Bool xorgHWOpenConsole = FALSE;
-
-/* Common pixmap formats */
-
-static PixmapFormatRec formats[MAXFORMATS] = {
- { 1, 1, BITMAP_SCANLINE_PAD },
- { 4, 8, BITMAP_SCANLINE_PAD },
- { 8, 8, BITMAP_SCANLINE_PAD },
- { 15, 16, BITMAP_SCANLINE_PAD },
- { 16, 16, BITMAP_SCANLINE_PAD },
- { 24, 32, BITMAP_SCANLINE_PAD },
- { 32, 32, BITMAP_SCANLINE_PAD },
-};
-static int numFormats = 7;
-static Bool formatsDone = FALSE;
-
-#ifndef OSNAME
-#define OSNAME " unknown"
-#endif
-#ifndef OSVENDOR
-#define OSVENDOR ""
-#endif
-#ifndef PRE_RELEASE
-#define PRE_RELEASE XORG_VERSION_SNAP
-#endif
-
-static void
-xf86PrintBanner(void)
-{
-#if PRE_RELEASE
- xf86ErrorFVerb(0, "\n"
- "This is a pre-release version of the X server from " XVENDORNAME ".\n"
- "It is not supported in any way.\n"
- "Bugs may be filed in the bugzilla at http://bugs.freedesktop.org/.\n"
- "Select the \"xorg\" product for bugs you find in this release.\n"
- "Before reporting bugs in pre-release versions please check the\n"
- "latest version in the X.Org Foundation git repository.\n"
- "See http://wiki.x.org/wiki/GitPage for git access instructions.\n");
-#endif
- xf86ErrorFVerb(0, "\nX.Org X Server %d.%d.%d",
- XORG_VERSION_MAJOR,
- XORG_VERSION_MINOR,
- XORG_VERSION_PATCH);
-#if XORG_VERSION_SNAP > 0
- xf86ErrorFVerb(0, ".%d", XORG_VERSION_SNAP);
-#endif
-
-#if XORG_VERSION_SNAP >= 900
- /* When the minor number is 99, that signifies that the we are making
- * a release candidate for a major version. (X.0.0)
- * When the patch number is 99, that signifies that the we are making
- * a release candidate for a minor version. (X.Y.0)
- * When the patch number is < 99, then we are making a release
- * candidate for the next point release. (X.Y.Z)
- */
-#if XORG_VERSION_MINOR >= 99
- xf86ErrorFVerb(0, " (%d.0.0 RC %d)", XORG_VERSION_MAJOR+1,
- XORG_VERSION_SNAP - 900);
-#elif XORG_VERSION_PATCH == 99
- xf86ErrorFVerb(0, " (%d.%d.0 RC %d)", XORG_VERSION_MAJOR,
- XORG_VERSION_MINOR + 1, XORG_VERSION_SNAP - 900);
-#else
- xf86ErrorFVerb(0, " (%d.%d.%d RC %d)", XORG_VERSION_MAJOR,
- XORG_VERSION_MINOR, XORG_VERSION_PATCH + 1,
- XORG_VERSION_SNAP - 900);
-#endif
-#endif
-
-#ifdef XORG_CUSTOM_VERSION
- xf86ErrorFVerb(0, " (%s)", XORG_CUSTOM_VERSION);
-#endif
-#ifndef XORG_DATE
-# define XORG_DATE "Unknown"
-#endif
- xf86ErrorFVerb(0, "\nRelease Date: %s\n", XORG_DATE);
- xf86ErrorFVerb(0, "X Protocol Version %d, Revision %d\n",
- X_PROTOCOL, X_PROTOCOL_REVISION);
- xf86ErrorFVerb(0, "Build Operating System: %s %s\n", OSNAME, OSVENDOR);
-#ifdef HAS_UTSNAME
- {
- struct utsname name;
-
- /* Linux & BSD state that 0 is success, SysV (including Solaris, HP-UX,
- and Irix) and Single Unix Spec 3 just say that non-negative is success.
- All agree that failure is represented by a negative number.
- */
- if (uname(&name) >= 0) {
- xf86ErrorFVerb(0, "Current Operating System: %s %s %s %s %s\n",
- name.sysname, name.nodename, name.release, name.version, name.machine);
-#ifdef linux
- do {
- char buf[80];
- int fd = open("/proc/cmdline", O_RDONLY);
- if (fd != -1) {
- xf86ErrorFVerb(0, "Kernel command line: ");
- memset(buf, 0, 80);
- while (read(fd, buf, 80) > 0) {
- xf86ErrorFVerb(0, "%.80s", buf);
- memset(buf, 0, 80);
- }
- close(fd);
- }
- } while (0);
-#endif
- }
- }
-#endif
-#if defined(BUILD_DATE) && (BUILD_DATE > 19000000)
- {
- struct tm t;
- char buf[100];
-
- memset(&t, 0, sizeof(t));
- memset(buf, 0, sizeof(buf));
- t.tm_mday = BUILD_DATE % 100;
- t.tm_mon = (BUILD_DATE / 100) % 100 - 1;
- t.tm_year = BUILD_DATE / 10000 - 1900;
-#if defined(BUILD_TIME)
- t.tm_sec = BUILD_TIME % 100;
- t.tm_min = (BUILD_TIME / 100) % 100;
- t.tm_hour = (BUILD_TIME / 10000) % 100;
- if (strftime(buf, sizeof(buf), "%d %B %Y %I:%M:%S%p", &t))
- xf86ErrorFVerb(0, "Build Date: %s\n", buf);
-#else
- if (strftime(buf, sizeof(buf), "%d %B %Y", &t))
- xf86ErrorFVerb(0, "Build Date: %s\n", buf);
-#endif
- }
-#endif
-#if defined(BUILDERSTRING)
- xf86ErrorFVerb(0, "%s \n", BUILDERSTRING);
-#endif
- xf86ErrorFVerb(0, "Current version of pixman: %s\n",
- pixman_version_string());
- xf86ErrorFVerb(0, "\tBefore reporting problems, check "
- ""__VENDORDWEBSUPPORT__"\n"
- "\tto make sure that you have the latest version.\n");
-}
-
-static void
-xf86PrintMarkers(void)
-{
- LogPrintMarkers();
-}
-
-static Bool
-xf86CreateRootWindow(WindowPtr pWin)
-{
- int ret = TRUE;
- int err = Success;
- ScreenPtr pScreen = pWin->drawable.pScreen;
- RootWinPropPtr pProp;
- CreateWindowProcPtr CreateWindow = (CreateWindowProcPtr)
- dixLookupPrivate(&pScreen->devPrivates, xf86CreateRootWindowKey);
-
- DebugF("xf86CreateRootWindow(%p)\n", pWin);
-
- if ( pScreen->CreateWindow != xf86CreateRootWindow ) {
- /* Can't find hook we are hung on */
- xf86DrvMsg(pScreen->myNum, X_WARNING /* X_ERROR */,
- "xf86CreateRootWindow %p called when not in pScreen->CreateWindow %p n",
- (void *)xf86CreateRootWindow,
- (void *)pScreen->CreateWindow );
- }
-
- /* Unhook this function ... */
- pScreen->CreateWindow = CreateWindow;
- dixSetPrivate(&pScreen->devPrivates, xf86CreateRootWindowKey, NULL);
-
- /* ... and call the previous CreateWindow fuction, if any */
- if (NULL!=pScreen->CreateWindow) {
- ret = (*pScreen->CreateWindow)(pWin);
- }
-
- /* Now do our stuff */
- if (xf86RegisteredPropertiesTable != NULL) {
- if (pWin->parent == NULL && xf86RegisteredPropertiesTable != NULL) {
- for (pProp = xf86RegisteredPropertiesTable[pScreen->myNum];
- pProp != NULL && err==Success;
- pProp = pProp->next )
- {
- Atom prop;
-
- prop = MakeAtom(pProp->name, strlen(pProp->name), TRUE);
- err = dixChangeWindowProperty(serverClient, pWin,
- prop, pProp->type,
- pProp->format, PropModeReplace,
- pProp->size, pProp->data,
- FALSE);
- }
-
- /* Look at err */
- ret &= (err==Success);
-
- } else {
- xf86Msg(X_ERROR, "xf86CreateRootWindow unexpectedly called with "
- "non-root window %p (parent %p)\n",
- (void *)pWin, (void *)pWin->parent);
- ret = FALSE;
- }
- }
-
- DebugF("xf86CreateRootWindow() returns %d\n", ret);
- return ret;
-}
-
-
-static void
-InstallSignalHandlers(void)
-{
- /*
- * Install signal handler for unexpected signals
- */
- xf86Info.caughtSignal=FALSE;
- if (!xf86Info.notrapSignals) {
- OsRegisterSigWrapper(xf86SigWrapper);
- } else {
- signal(SIGSEGV, SIG_DFL);
- signal(SIGILL, SIG_DFL);
-#ifdef SIGEMT
- signal(SIGEMT, SIG_DFL);
-#endif
- signal(SIGFPE, SIG_DFL);
- signal(SIGBUS, SIG_DFL);
- signal(SIGSYS, SIG_DFL);
- signal(SIGXCPU, SIG_DFL);
- signal(SIGXFSZ, SIG_DFL);
- }
-}
-
-/*
- * InitOutput --
- * Initialize screenInfo for all actually accessible framebuffers.
- * That includes vt-manager setup, querying all possible devices and
- * collecting the pixmap formats.
- */
-void
-InitOutput(ScreenInfo *pScreenInfo, int argc, char **argv)
-{
- int i, j, k, scr_index, was_blocked = 0;
- char **modulelist;
- pointer *optionlist;
- Pix24Flags screenpix24, pix24;
- MessageType pix24From = X_DEFAULT;
- Bool pix24Fail = FALSE;
- Bool autoconfig = FALSE;
- GDevPtr configured_device;
-
- xf86Initialising = TRUE;
-
- if (serverGeneration == 1) {
- if ((xf86ServerName = strrchr(argv[0], '/')) != 0)
- xf86ServerName++;
- else
- xf86ServerName = argv[0];
-
- xf86PrintBanner();
- xf86PrintMarkers();
- if (xf86LogFile) {
- time_t t;
- const char *ct;
- t = time(NULL);
- ct = ctime(&t);
- xf86MsgVerb(xf86LogFileFrom, 0, "Log file: \"%s\", Time: %s",
- xf86LogFile, ct);
- }
-
- /* Read and parse the config file */
- if (!xf86DoConfigure && !xf86DoShowOptions) {
- switch (xf86HandleConfigFile(FALSE)) {
- case CONFIG_OK:
- break;
- case CONFIG_PARSE_ERROR:
- xf86Msg(X_ERROR, "Error parsing the config file\n");
- return;
- case CONFIG_NOFILE:
- autoconfig = TRUE;
- break;
- }
- }
-
- InstallSignalHandlers();
-
- /* Initialise the loader */
- LoaderInit();
-
- /* Tell the loader the default module search path */
- LoaderSetPath(xf86ModulePath);
-
- if (xf86Info.ignoreABI) {
- LoaderSetOptions(LDR_OPT_ABI_MISMATCH_NONFATAL);
- }
-
- if (xf86DoShowOptions)
- DoShowOptions();
-
- /* Do a general bus probe. This will be a PCI probe for x86 platforms */
- xf86BusProbe();
-
- if (xf86DoConfigure)
- DoConfigure();
-
- if (autoconfig) {
- if (!xf86AutoConfig()) {
- xf86Msg(X_ERROR, "Auto configuration failed\n");
- return;
- }
- }
-
-#ifdef XF86PM
- xf86OSPMClose = xf86OSPMOpen();
-#endif
-
- /* Load all modules specified explicitly in the config file */
- if ((modulelist = xf86ModulelistFromConfig(&optionlist))) {
- xf86LoadModules(modulelist, optionlist);
- free(modulelist);
- free(optionlist);
- }
-
- /* Load all driver modules specified in the config file */
- /* If there aren't any specified in the config file, autoconfig them */
- /* FIXME: Does not handle multiple active screen sections, but I'm not
- * sure if we really want to handle that case*/
- configured_device = xf86ConfigLayout.screens->screen->device;
- if ((!configured_device) || (!configured_device->driver)) {
- if (!autoConfigDevice(configured_device)) {
- xf86Msg(X_ERROR, "Automatic driver configuration failed\n");
- return ;
- }
- }
- if ((modulelist = xf86DriverlistFromConfig())) {
- xf86LoadModules(modulelist, NULL);
- free(modulelist);
- }
-
- /* Load all input driver modules specified in the config file. */
- if ((modulelist = xf86InputDriverlistFromConfig())) {
- xf86LoadModules(modulelist, NULL);
- free(modulelist);
- }
-
- /*
- * It is expected that xf86AddDriver()/xf86AddInputDriver will be
- * called for each driver as it is loaded. Those functions save the
- * module pointers for drivers.
- * XXX Nothing keeps track of them for other modules.
- */
- /* XXX What do we do if not all of these could be loaded? */
-
- /*
- * At this point, xf86DriverList[] is all filled in with entries for
- * each of the drivers to try and xf86NumDrivers has the number of
- * drivers. If there are none, return now.
- */
-
- if (xf86NumDrivers == 0) {
- xf86Msg(X_ERROR, "No drivers available.\n");
- return;
- }
-
- /*
- * Call each of the Identify functions and call the driverFunc to check
- * if HW access is required. The Identify functions print out some
- * identifying information, and anything else that might be
- * needed at this early stage.
- */
-
- for (i = 0; i < xf86NumDrivers; i++) {
- if (xf86DriverList[i]->Identify != NULL)
- xf86DriverList[i]->Identify(0);
-
- if (!xorgHWAccess || !xorgHWOpenConsole) {
- xorgHWFlags flags;
- if(!xf86DriverList[i]->driverFunc
- || !xf86DriverList[i]->driverFunc(NULL,
- GET_REQUIRED_HW_INTERFACES,
- &flags))
- flags = HW_IO;
-
- if(NEED_IO_ENABLED(flags))
- xorgHWAccess = TRUE;
- if(!(flags & HW_SKIP_CONSOLE))
- xorgHWOpenConsole = TRUE;
- }
- }
-
- if (xorgHWOpenConsole)
- xf86OpenConsole();
- else
- xf86Info.dontVTSwitch = TRUE;
-
- if (xf86BusConfig() == FALSE)
- return;
-
- xf86PostProbe();
-
- /*
- * Sort the drivers to match the requested ording. Using a slow
- * bubble sort.
- */
- for (j = 0; j < xf86NumScreens - 1; j++) {
- for (i = 0; i < xf86NumScreens - j - 1; i++) {
- if (xf86Screens[i + 1]->confScreen->screennum <
- xf86Screens[i]->confScreen->screennum) {
- ScrnInfoPtr tmpScrn = xf86Screens[i + 1];
- xf86Screens[i + 1] = xf86Screens[i];
- xf86Screens[i] = tmpScrn;
- }
- }
- }
- /* Fix up the indexes */
- for (i = 0; i < xf86NumScreens; i++) {
- xf86Screens[i]->scrnIndex = i;
- }
-
- /*
- * Call the driver's PreInit()'s to complete initialisation for the first
- * generation.
- */
-
- for (i = 0; i < xf86NumScreens; i++) {
- xf86VGAarbiterScrnInit(xf86Screens[i]);
- xf86VGAarbiterLock(xf86Screens[i]);
- if (xf86Screens[i]->PreInit &&
- xf86Screens[i]->PreInit(xf86Screens[i], 0))
- xf86Screens[i]->configured = TRUE;
- xf86VGAarbiterUnlock(xf86Screens[i]);
- }
- for (i = 0; i < xf86NumScreens; i++)
- if (!xf86Screens[i]->configured)
- xf86DeleteScreen(i--, 0);
-
- /*
- * If no screens left, return now.
- */
-
- if (xf86NumScreens == 0) {
- xf86Msg(X_ERROR,
- "Screen(s) found, but none have a usable configuration.\n");
- return;
- }
-
- for (i = 0; i < xf86NumScreens; i++) {
- if (xf86Screens[i]->name == NULL) {
- XNFasprintf(&xf86Screens[i]->name, "screen%d", i);
- xf86MsgVerb(X_WARNING, 0,
- "Screen driver %d has no name set, using `%s'.\n",
- i, xf86Screens[i]->name);
- }
- }
-
- /* Remove (unload) drivers that are not required */
- for (i = 0; i < xf86NumDrivers; i++)
- if (xf86DriverList[i] && xf86DriverList[i]->refCount <= 0)
- xf86DeleteDriver(i);
-
- /*
- * At this stage we know how many screens there are.
- */
-
- for (i = 0; i < xf86NumScreens; i++)
- xf86InitViewport(xf86Screens[i]);
-
- /*
- * Collect all pixmap formats and check for conflicts at the display
- * level. Should we die here? Or just delete the offending screens?
- */
- screenpix24 = Pix24DontCare;
- for (i = 0; i < xf86NumScreens; i++) {
- if (xf86Screens[i]->imageByteOrder !=
- xf86Screens[0]->imageByteOrder)
- FatalError("Inconsistent display bitmapBitOrder. Exiting\n");
- if (xf86Screens[i]->bitmapScanlinePad !=
- xf86Screens[0]->bitmapScanlinePad)
- FatalError("Inconsistent display bitmapScanlinePad. Exiting\n");
- if (xf86Screens[i]->bitmapScanlineUnit !=
- xf86Screens[0]->bitmapScanlineUnit)
- FatalError("Inconsistent display bitmapScanlineUnit. Exiting\n");
- if (xf86Screens[i]->bitmapBitOrder !=
- xf86Screens[0]->bitmapBitOrder)
- FatalError("Inconsistent display bitmapBitOrder. Exiting\n");
-
- /* Determine the depth 24 pixmap format the screens would like */
- if (xf86Screens[i]->pixmap24 != Pix24DontCare) {
- if (screenpix24 == Pix24DontCare)
- screenpix24 = xf86Screens[i]->pixmap24;
- else if (screenpix24 != xf86Screens[i]->pixmap24)
- FatalError("Inconsistent depth 24 pixmap format. Exiting\n");
- }
- }
- /* check if screenpix24 is consistent with the config/cmdline */
- if (xf86Info.pixmap24 != Pix24DontCare) {
- pix24 = xf86Info.pixmap24;
- pix24From = xf86Info.pix24From;
- if (screenpix24 != Pix24DontCare && screenpix24 != xf86Info.pixmap24)
- pix24Fail = TRUE;
- } else if (screenpix24 != Pix24DontCare) {
- pix24 = screenpix24;
- pix24From = X_PROBED;
- } else
- pix24 = Pix24Use32;
-
- if (pix24Fail)
- FatalError("Screen(s) can't use the required depth 24 pixmap format"
- " (%d). Exiting\n", PIX24TOBPP(pix24));
-
- /* Initialise the depth 24 format */
- for (j = 0; j < numFormats && formats[j].depth != 24; j++)
- ;
- formats[j].bitsPerPixel = PIX24TOBPP(pix24);
-
- /* Collect additional formats */
- for (i = 0; i < xf86NumScreens; i++) {
- for (j = 0; j < xf86Screens[i]->numFormats; j++) {
- for (k = 0; ; k++) {
- if (k >= numFormats) {
- if (k >= MAXFORMATS)
- FatalError("Too many pixmap formats! Exiting\n");
- formats[k] = xf86Screens[i]->formats[j];
- numFormats++;
- break;
- }
- if (formats[k].depth == xf86Screens[i]->formats[j].depth) {
- if ((formats[k].bitsPerPixel ==
- xf86Screens[i]->formats[j].bitsPerPixel) &&
- (formats[k].scanlinePad ==
- xf86Screens[i]->formats[j].scanlinePad))
- break;
- FatalError("Inconsistent pixmap format for depth %d."
- " Exiting\n", formats[k].depth);
- }
- }
- }
- }
- formatsDone = TRUE;
-
- if (xf86Info.vtno >= 0 ) {
-#define VT_ATOM_NAME "XFree86_VT"
- Atom VTAtom=-1;
- CARD32 *VT = NULL;
- int ret;
-
- /* This memory needs to stay available until the screen has been
- initialized, and we can create the property for real.
- */
- if ( (VT = malloc(sizeof(CARD32)))==NULL ) {
- FatalError("Unable to make VT property - out of memory. Exiting...\n");
- }
- *VT = xf86Info.vtno;
-
- VTAtom = MakeAtom(VT_ATOM_NAME, sizeof(VT_ATOM_NAME) - 1, TRUE);
-
- for (i = 0, ret = Success; i < xf86NumScreens && ret == Success; i++) {
- ret = xf86RegisterRootWindowProperty(xf86Screens[i]->scrnIndex,
- VTAtom, XA_INTEGER, 32,
- 1, VT );
- if (ret != Success)
- xf86DrvMsg(xf86Screens[i]->scrnIndex, X_WARNING,
- "Failed to register VT property\n");
- }
- }
-
- /* If a screen uses depth 24, show what the pixmap format is */
- for (i = 0; i < xf86NumScreens; i++) {
- if (xf86Screens[i]->depth == 24) {
- xf86Msg(pix24From, "Depth 24 pixmap format is %d bpp\n",
- PIX24TOBPP(pix24));
- break;
- }
- }
- } else {
- /*
- * serverGeneration != 1; some OSs have to do things here, too.
- */
- if (xorgHWOpenConsole)
- xf86OpenConsole();
-
-#ifdef XF86PM
- /*
- should we reopen it here? We need to deal with an already opened
- device. We could leave this to the OS layer. For now we simply
- close it here
- */
- if (xf86OSPMClose)
- xf86OSPMClose();
- if ((xf86OSPMClose = xf86OSPMOpen()) != NULL)
- xf86MsgVerb(X_INFO, 3, "APM registered successfully\n");
-#endif
-
- /* Make sure full I/O access is enabled */
- if (xorgHWAccess)
- xf86EnableIO();
- }
-
- /*
- * Use the previously collected parts to setup pScreenInfo
- */
-
- pScreenInfo->imageByteOrder = xf86Screens[0]->imageByteOrder;
- pScreenInfo->bitmapScanlinePad = xf86Screens[0]->bitmapScanlinePad;
- pScreenInfo->bitmapScanlineUnit = xf86Screens[0]->bitmapScanlineUnit;
- pScreenInfo->bitmapBitOrder = xf86Screens[0]->bitmapBitOrder;
- pScreenInfo->numPixmapFormats = numFormats;
- for (i = 0; i < numFormats; i++)
- pScreenInfo->formats[i] = formats[i];
-
- /* Make sure the server's VT is active */
-
- if (serverGeneration != 1) {
- xf86Resetting = TRUE;
- /* All screens are in the same state, so just check the first */
- if (!xf86Screens[0]->vtSema) {
-#ifdef HAS_USL_VTS
- ioctl(xf86Info.consoleFd, VT_RELDISP, VT_ACKACQ);
-#endif
- xf86AccessEnter();
- was_blocked = xf86BlockSIGIO();
- }
- }
-
- for (i = 0; i < xf86NumScreens; i++)
- if (!xf86ColormapAllocatePrivates(xf86Screens[i]))
- FatalError("Cannot register DDX private keys");
-
- if (!dixRegisterPrivateKey(&xf86ScreenKeyRec, PRIVATE_SCREEN, 0) ||
- !dixRegisterPrivateKey(&xf86CreateRootWindowKeyRec, PRIVATE_SCREEN, 0))
- FatalError("Cannot register DDX private keys");
-
- for (i = 0; i < xf86NumScreens; i++) {
- xf86VGAarbiterLock(xf86Screens[i]);
- /*
- * Almost everything uses these defaults, and many of those that
- * don't, will wrap them.
- */
- xf86Screens[i]->EnableDisableFBAccess = xf86EnableDisableFBAccess;
-#ifdef XFreeXDGA
- xf86Screens[i]->SetDGAMode = xf86SetDGAMode;
-#endif
- xf86Screens[i]->DPMSSet = NULL;
- xf86Screens[i]->LoadPalette = NULL;
- xf86Screens[i]->SetOverscan = NULL;
- xf86Screens[i]->DriverFunc = NULL;
- xf86Screens[i]->pScreen = NULL;
- scr_index = AddScreen(xf86Screens[i]->ScreenInit, argc, argv);
- xf86VGAarbiterUnlock(xf86Screens[i]);
- if (scr_index == i) {
- /*
- * Hook in our ScrnInfoRec, and initialise some other pScreen
- * fields.
- */
- dixSetPrivate(&screenInfo.screens[scr_index]->devPrivates,
- xf86ScreenKey, xf86Screens[i]);
- xf86Screens[i]->pScreen = screenInfo.screens[scr_index];
- /* The driver should set this, but make sure it is set anyway */
- xf86Screens[i]->vtSema = TRUE;
- } else {
- /* This shouldn't normally happen */
- FatalError("AddScreen/ScreenInit failed for driver %d\n", i);
- }
-
- DebugF("InitOutput - xf86Screens[%d]->pScreen = %p\n",
- i, xf86Screens[i]->pScreen );
- DebugF("xf86Screens[%d]->pScreen->CreateWindow = %p\n",
- i, xf86Screens[i]->pScreen->CreateWindow );
-
- dixSetPrivate(&screenInfo.screens[scr_index]->devPrivates,
- xf86CreateRootWindowKey,
- xf86Screens[i]->pScreen->CreateWindow);
- xf86Screens[i]->pScreen->CreateWindow = xf86CreateRootWindow;
-
- if (PictureGetSubpixelOrder (xf86Screens[i]->pScreen) == SubPixelUnknown)
- {
- xf86MonPtr DDC = (xf86MonPtr)(xf86Screens[i]->monitor->DDC);
- PictureSetSubpixelOrder (xf86Screens[i]->pScreen,
- DDC ?
- (DDC->features.input_type ?
- SubPixelHorizontalRGB : SubPixelNone) :
- SubPixelUnknown);
- }
-#ifdef RANDR
- if (!xf86Info.disableRandR)
- xf86RandRInit (screenInfo.screens[scr_index]);
- xf86Msg(xf86Info.randRFrom, "RandR %s\n",
- xf86Info.disableRandR ? "disabled" : "enabled");
-#endif
- }
-
- xf86VGAarbiterWrapFunctions();
- xf86UnblockSIGIO(was_blocked);
-
- xf86InitOrigins();
-
- xf86Resetting = FALSE;
- xf86Initialising = FALSE;
-
- RegisterBlockAndWakeupHandlers((BlockHandlerProcPtr)NoopDDA, xf86Wakeup,
- 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.
- */
-
-void
-InitInput(int argc, char **argv)
-{
- InputInfoPtr* pInfo;
- DeviceIntPtr dev;
-
- xf86Info.vtRequestsPending = FALSE;
-
- mieqInit();
-
- /* Initialize all configured input devices */
- for (pInfo = xf86ConfigLayout.inputs; pInfo && *pInfo; pInfo++) {
- InputInfoPtr dup;
- /* Replace obsolete keyboard driver with 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(dup, &dev, TRUE) == BadAlloc)
- break;
- }
-
- config_init();
-}
-
-void
-CloseInput (void)
-{
- config_fini();
- mieqFini();
-}
-
-/*
- * OsVendorInit --
- * OS/Vendor-specific initialisations. Called from OsInit(), which
- * is called by dix before establishing the well known sockets.
- */
-
-void
-OsVendorInit(void)
-{
- static Bool beenHere = FALSE;
-
- signal(SIGCHLD, SIG_DFL); /* Need to wait for child processes */
-
- if (!beenHere) {
- umask(022);
- xf86LogInit();
- }
-
- /* Set stderr to non-blocking. */
-#ifndef O_NONBLOCK
-#if defined(FNDELAY)
-#define O_NONBLOCK FNDELAY
-#elif defined(O_NDELAY)
-#define O_NONBLOCK O_NDELAY
-#endif
-
-#ifdef O_NONBLOCK
- if (!beenHere) {
- if (geteuid() == 0 && getuid() != geteuid())
- {
- int status;
-
- status = fcntl(fileno(stderr), F_GETFL, 0);
- if (status != -1) {
- fcntl(fileno(stderr), F_SETFL, status | O_NONBLOCK);
- }
- }
- }
-#endif
-#endif
-
- beenHere = TRUE;
-}
-
-/*
- * ddxGiveUp --
- * Device dependent cleanup. Called by by dix before normal server death.
- * For SYSV386 we must switch the terminal back to normal mode. No error-
- * checking here, since there should be restored as much as possible.
- */
-
-void
-ddxGiveUp(enum ExitCode error)
-{
- int i;
-
- xf86VGAarbiterFini();
-
-#ifdef XF86PM
- if (xf86OSPMClose)
- xf86OSPMClose();
- xf86OSPMClose = NULL;
-#endif
-
- for (i = 0; i < xf86NumScreens; i++) {
- /*
- * zero all access functions to
- * trap calls when switched away.
- */
- xf86Screens[i]->vtSema = FALSE;
- }
-
-#ifdef XFreeXDGA
- DGAShutdown();
-#endif
-
- if (xorgHWOpenConsole)
- xf86CloseConsole();
-
- xf86CloseLog(error);
-
- /* If an unexpected signal was caught, dump a core for debugging */
- if (xf86Info.caughtSignal)
- OsAbort();
-}
-
-
-
-/*
- * AbortDDX --
- * DDX - specific abort routine. Called by AbortServer(). The attempt is
- * made to restore all original setting of the displays. Also all devices
- * are closed.
- */
-
-void
-AbortDDX(enum ExitCode error)
-{
- int i;
-
- xf86BlockSIGIO();
-
- /*
- * try to restore the original video state
- */
-#ifdef DPMSExtension /* Turn screens back on */
- if (DPMSPowerLevel != DPMSModeOn)
- DPMSSet(serverClient, DPMSModeOn);
-#endif
- if (xf86Screens) {
- for (i = 0; i < xf86NumScreens; i++)
- if (xf86Screens[i]->vtSema) {
- /*
- * if we are aborting before ScreenInit() has finished
- * we might not have been wrapped yet. Therefore enable
- * screen explicitely.
- */
- xf86VGAarbiterLock(xf86Screens[i]);
- (xf86Screens[i]->LeaveVT)(i, 0);
- xf86VGAarbiterUnlock(xf86Screens[i]);
- }
- }
-
- xf86AccessLeave();
-
- /*
- * 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(error);
-}
-
-void
-OsVendorFatalError(void)
-{
-#ifdef VENDORSUPPORT
- ErrorF("\nPlease refer to your Operating System Vendor support pages\n"
- "at %s for support on this crash.\n",VENDORSUPPORT);
-#else
- ErrorF("\nPlease consult the "XVENDORNAME" support \n"
- "\t at "__VENDORDWEBSUPPORT__"\n for help. \n");
-#endif
- if (xf86LogFile && xf86LogFileWasOpened)
- ErrorF("Please also check the log file at \"%s\" for additional "
- "information.\n", xf86LogFile);
- ErrorF("\n");
-}
-
-int
-xf86SetVerbosity(int verb)
-{
- int save = xf86Verbose;
-
- xf86Verbose = verb;
- LogSetParameter(XLOG_VERBOSITY, verb);
- return save;
-}
-
-int
-xf86SetLogVerbosity(int verb)
-{
- int save = xf86LogVerbose;
-
- xf86LogVerbose = verb;
- LogSetParameter(XLOG_FILE_VERBOSITY, verb);
- return save;
-}
-
-static void
-xf86PrintDefaultModulePath(void)
-{
- ErrorF("%s\n", DEFAULT_MODULE_PATH);
-}
-
-static void
-xf86PrintDefaultLibraryPath(void)
-{
- ErrorF("%s\n", DEFAULT_LIBRARY_PATH);
-}
-
-/*
- * ddxProcessArgument --
- * Process device-dependent command line args. Returns 0 if argument is
- * not device dependent, otherwise Count of number of elements of argv
- * that are part of a device dependent commandline option.
- *
- */
-
-/* ARGSUSED */
-int
-ddxProcessArgument(int argc, char **argv, int i)
-{
-#define CHECK_FOR_REQUIRED_ARGUMENT() \
- if (((i + 1) >= argc) || (!argv[i + 1])) { \
- ErrorF("Required argument to %s not specified\n", argv[i]); \
- UseMsg(); \
- FatalError("Required argument to %s not specified\n", argv[i]); \
- }
-
- /* First the options that are only allowed for root */
- if (!strcmp(argv[i], "-modulepath") || !strcmp(argv[i], "-logfile")) {
- if ( (geteuid() == 0) && (getuid() != 0) ) {
- FatalError("The '%s' option can only be used by root.\n", argv[i]);
- }
- else if (!strcmp(argv[i], "-modulepath"))
- {
- char *mp;
- CHECK_FOR_REQUIRED_ARGUMENT();
- mp = strdup(argv[i + 1]);
- if (!mp)
- FatalError("Can't allocate memory for ModulePath\n");
- xf86ModulePath = mp;
- xf86ModPathFrom = X_CMDLINE;
- return 2;
- }
- else if (!strcmp(argv[i], "-logfile"))
- {
- char *lf;
- CHECK_FOR_REQUIRED_ARGUMENT();
- lf = strdup(argv[i + 1]);
- if (!lf)
- FatalError("Can't allocate memory for LogFile\n");
- xf86LogFile = lf;
- xf86LogFileFrom = X_CMDLINE;
- return 2;
- }
- }
- if (!strcmp(argv[i], "-config") || !strcmp(argv[i], "-xf86config"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) {
- FatalError("\nInvalid argument for %s\n"
- "\tFor non-root users, the file specified with %s must be\n"
- "\ta relative path and must not contain any \"..\" elements.\n"
- "\tUsing default "__XCONFIGFILE__" search path.\n\n",
- argv[i], argv[i]);
- }
- xf86ConfigFile = argv[i + 1];
- return 2;
- }
- if (!strcmp(argv[i], "-configdir"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) {
- FatalError("\nInvalid argument for %s\n"
- "\tFor non-root users, the file specified with %s must be\n"
- "\ta relative path and must not contain any \"..\" elements.\n"
- "\tUsing default "__XCONFIGDIR__" search path.\n\n",
- argv[i], argv[i]);
- }
- xf86ConfigDir = argv[i + 1];
- return 2;
- }
- if (!strcmp(argv[i],"-flipPixels"))
- {
- xf86FlipPixels = TRUE;
- return 1;
- }
-#ifdef XF86VIDMODE
- if (!strcmp(argv[i],"-disableVidMode"))
- {
- xf86VidModeDisabled = TRUE;
- return 1;
- }
- if (!strcmp(argv[i],"-allowNonLocalXvidtune"))
- {
- xf86VidModeAllowNonLocal = TRUE;
- return 1;
- }
-#endif
- if (!strcmp(argv[i],"-allowMouseOpenFail"))
- {
- xf86AllowMouseOpenFail = TRUE;
- return 1;
- }
- if (!strcmp(argv[i],"-ignoreABI"))
- {
- LoaderSetOptions(LDR_OPT_ABI_MISMATCH_NONFATAL);
- return 1;
- }
- if (!strcmp(argv[i],"-verbose"))
- {
- if (++i < argc && argv[i])
- {
- char *end;
- long val;
- val = strtol(argv[i], &end, 0);
- if (*end == '\0')
- {
- xf86SetVerbosity(val);
- return 2;
- }
- }
- xf86SetVerbosity(++xf86Verbose);
- return 1;
- }
- if (!strcmp(argv[i],"-logverbose"))
- {
- if (++i < argc && argv[i])
- {
- char *end;
- long val;
- val = strtol(argv[i], &end, 0);
- if (*end == '\0')
- {
- xf86SetLogVerbosity(val);
- return 2;
- }
- }
- xf86SetLogVerbosity(++xf86LogVerbose);
- return 1;
- }
- if (!strcmp(argv[i],"-quiet"))
- {
- xf86SetVerbosity(-1);
- return 1;
- }
- if (!strcmp(argv[i],"-showconfig") || !strcmp(argv[i],"-version"))
- {
- xf86PrintBanner();
- exit(0);
- }
- if (!strcmp(argv[i],"-showDefaultModulePath"))
- {
- xf86PrintDefaultModulePath();
- exit(0);
- }
- if (!strcmp(argv[i],"-showDefaultLibPath"))
- {
- xf86PrintDefaultLibraryPath();
- exit(0);
- }
- /* Notice the -fp flag, but allow it to pass to the dix layer */
- if (!strcmp(argv[i], "-fp"))
- {
- xf86fpFlag = TRUE;
- return 0;
- }
- /* Notice the -bs flag, but allow it to pass to the dix layer */
- if (!strcmp(argv[i], "-bs"))
- {
- xf86bsDisableFlag = TRUE;
- return 0;
- }
- /* Notice the +bs flag, but allow it to pass to the dix layer */
- if (!strcmp(argv[i], "+bs"))
- {
- xf86bsEnableFlag = TRUE;
- return 0;
- }
- /* Notice the -s flag, but allow it to pass to the dix layer */
- if (!strcmp(argv[i], "-s"))
- {
- xf86sFlag = TRUE;
- return 0;
- }
- if (!strcmp(argv[i], "-pixmap24"))
- {
- xf86Pix24 = Pix24Use24;
- return 1;
- }
- if (!strcmp(argv[i], "-pixmap32"))
- {
- xf86Pix24 = Pix24Use32;
- return 1;
- }
- if (!strcmp(argv[i], "-fbbpp"))
- {
- int bpp;
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (sscanf(argv[++i], "%d", &bpp) == 1)
- {
- xf86FbBpp = bpp;
- return 2;
- }
- else
- {
- ErrorF("Invalid fbbpp\n");
- return 0;
- }
- }
- if (!strcmp(argv[i], "-depth"))
- {
- int depth;
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (sscanf(argv[++i], "%d", &depth) == 1)
- {
- xf86Depth = depth;
- return 2;
- }
- else
- {
- ErrorF("Invalid depth\n");
- return 0;
- }
- }
- if (!strcmp(argv[i], "-weight"))
- {
- int red, green, blue;
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (sscanf(argv[++i], "%1d%1d%1d", &red, &green, &blue) == 3)
- {
- xf86Weight.red = red;
- xf86Weight.green = green;
- xf86Weight.blue = blue;
- return 2;
- }
- else
- {
- ErrorF("Invalid weighting\n");
- return 0;
- }
- }
- if (!strcmp(argv[i], "-gamma") || !strcmp(argv[i], "-rgamma") ||
- !strcmp(argv[i], "-ggamma") || !strcmp(argv[i], "-bgamma"))
- {
- double gamma;
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (sscanf(argv[++i], "%lf", &gamma) == 1) {
- if (gamma < GAMMA_MIN || gamma > GAMMA_MAX) {
- ErrorF("gamma out of range, only %.2f <= gamma_value <= %.1f"
- " is valid\n", GAMMA_MIN, GAMMA_MAX);
- return 0;
- }
- if (!strcmp(argv[i-1], "-gamma"))
- xf86Gamma.red = xf86Gamma.green = xf86Gamma.blue = gamma;
- else if (!strcmp(argv[i-1], "-rgamma")) xf86Gamma.red = gamma;
- else if (!strcmp(argv[i-1], "-ggamma")) xf86Gamma.green = gamma;
- else if (!strcmp(argv[i-1], "-bgamma")) xf86Gamma.blue = gamma;
- return 2;
- }
- }
- if (!strcmp(argv[i], "-layout"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- xf86LayoutName = argv[++i];
- return 2;
- }
- if (!strcmp(argv[i], "-screen"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- xf86ScreenName = argv[++i];
- return 2;
- }
- if (!strcmp(argv[i], "-pointer"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- xf86PointerName = argv[++i];
- return 2;
- }
- if (!strcmp(argv[i], "-keyboard"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- xf86KeyboardName = argv[++i];
- return 2;
- }
- if (!strcmp(argv[i], "-nosilk"))
- {
- xf86silkenMouseDisableFlag = TRUE;
- return 1;
- }
-#ifdef HAVE_ACPI
- if (!strcmp(argv[i], "-noacpi"))
- {
- xf86acpiDisableFlag = TRUE;
- return 1;
- }
-#endif
- if (!strcmp(argv[i], "-configure"))
- {
- if (getuid() != 0 && geteuid() == 0) {
- ErrorF("The '-configure' option can only be used by root.\n");
- exit(1);
- }
- xf86DoConfigure = TRUE;
- xf86AllowMouseOpenFail = TRUE;
- return 1;
- }
- if (!strcmp(argv[i], "-showopts"))
- {
- if (getuid() != 0 && geteuid() == 0) {
- ErrorF("The '-showopts' option can only be used by root.\n");
- exit(1);
- }
- xf86DoShowOptions = TRUE;
- return 1;
- }
- if (!strcmp(argv[i], "-isolateDevice"))
- {
- CHECK_FOR_REQUIRED_ARGUMENT();
- if (strncmp(argv[++i], "PCI:", 4)) {
- FatalError("Bus types other than PCI not yet isolable\n");
- }
- xf86PciIsolateDevice(argv[i]);
- return 2;
- }
- /* Notice cmdline xkbdir, but pass to dix as well */
- if (!strcmp(argv[i], "-xkbdir"))
- {
- xf86xkbdirFlag = TRUE;
- return 0;
- }
-
- /* OS-specific processing */
- return xf86ProcessArgument(argc, argv, i);
-}
-
-/*
- * ddxUseMsg --
- * Print out correct use of device dependent commandline options.
- * Maybe the user now knows what really to do ...
- */
-
-void
-ddxUseMsg(void)
-{
- ErrorF("\n");
- ErrorF("\n");
- ErrorF("Device Dependent Usage\n");
- if (getuid() == 0 || geteuid() != 0)
- {
- ErrorF("-modulepath paths specify the module search path\n");
- ErrorF("-logfile file specify a log file name\n");
- ErrorF("-configure probe for devices and write an "__XCONFIGFILE__"\n");
- ErrorF("-showopts print available options for all installed drivers\n");
- }
- ErrorF("-config file specify a configuration file, relative to the\n");
- ErrorF(" "__XCONFIGFILE__" search path, only root can use absolute\n");
- ErrorF("-configdir dir specify a configuration directory, relative to the\n");
- ErrorF(" "__XCONFIGDIR__" search path, only root can use absolute\n");
- ErrorF("-verbose [n] verbose startup messages\n");
- ErrorF("-logverbose [n] verbose log messages\n");
- ErrorF("-quiet minimal startup messages\n");
- ErrorF("-pixmap24 use 24bpp pixmaps for depth 24\n");
- ErrorF("-pixmap32 use 32bpp pixmaps for depth 24\n");
- ErrorF("-fbbpp n set bpp for the framebuffer. Default: 8\n");
- ErrorF("-depth n set colour depth. Default: 8\n");
- ErrorF("-gamma f set gamma value (0.1 < f < 10.0) Default: 1.0\n");
- ErrorF("-rgamma f set gamma value for red phase\n");
- ErrorF("-ggamma f set gamma value for green phase\n");
- ErrorF("-bgamma f set gamma value for blue phase\n");
- ErrorF("-weight nnn set RGB weighting at 16 bpp. Default: 565\n");
- ErrorF("-layout name specify the ServerLayout section name\n");
- ErrorF("-screen name specify the Screen section name\n");
- ErrorF("-keyboard name specify the core keyboard InputDevice name\n");
- ErrorF("-pointer name specify the core pointer InputDevice name\n");
- ErrorF("-nosilk disable Silken Mouse\n");
- ErrorF("-flipPixels swap default black/white Pixel values\n");
-#ifdef XF86VIDMODE
- ErrorF("-disableVidMode disable mode adjustments with xvidtune\n");
- ErrorF("-allowNonLocalXvidtune allow xvidtune to be run as a non-local client\n");
-#endif
- ErrorF("-allowMouseOpenFail start server even if the mouse can't be initialized\n");
- ErrorF("-ignoreABI make module ABI mismatches non-fatal\n");
- ErrorF("-isolateDevice bus_id restrict device resets to bus_id (PCI only)\n");
- ErrorF("-version show the server version\n");
- ErrorF("-showDefaultModulePath show the server default module path\n");
- ErrorF("-showDefaultLibPath show the server default library path\n");
- /* OS-specific usage */
- xf86UseMsg();
- ErrorF("\n");
-}
-
-
-/*
- * xf86LoadModules iterates over a list that is being passed in.
- */
-Bool
-xf86LoadModules(char **list, pointer *optlist)
-{
- int errmaj, errmin;
- pointer opt;
- int i;
- char *name;
- Bool failed = FALSE;
-
- if (!list)
- return TRUE;
-
- for (i = 0; list[i] != NULL; i++) {
-
- /* Normalise the module name */
- name = xf86NormalizeName(list[i]);
-
- /* Skip empty names */
- if (name == NULL || *name == '\0') {
- free(name);
- continue;
- }
-
- /* Replace obsolete keyboard driver with kbd */
- if (!xf86NameCmp(name, "keyboard")) {
- strcpy(name, "kbd");
- }
-
- if (optlist)
- opt = optlist[i];
- else
- opt = NULL;
-
- if (!LoadModule(name, NULL, NULL, NULL, opt, NULL, &errmaj, &errmin)) {
- LoaderErrorMsg(NULL, name, errmaj, errmin);
- failed = TRUE;
- }
- free(name);
- }
- return !failed;
-}
-
-/* Pixmap format stuff */
-
-PixmapFormatPtr
-xf86GetPixFormat(ScrnInfoPtr pScrn, int depth)
-{
- int i;
- static PixmapFormatRec format; /* XXX not reentrant */
-
- /*
- * When the formats[] list initialisation isn't complete, check the
- * depth 24 pixmap config/cmdline options and screen-specified formats.
- */
-
- if (!formatsDone) {
- if (depth == 24) {
- Pix24Flags pix24 = Pix24DontCare;
-
- format.depth = 24;
- format.scanlinePad = BITMAP_SCANLINE_PAD;
- if (xf86Info.pixmap24 != Pix24DontCare)
- pix24 = xf86Info.pixmap24;
- else if (pScrn->pixmap24 != Pix24DontCare)
- pix24 = pScrn->pixmap24;
- if (pix24 == Pix24Use24)
- format.bitsPerPixel = 24;
- else
- format.bitsPerPixel = 32;
- return &format;
- }
- }
-
- for (i = 0; i < numFormats; i++)
- if (formats[i].depth == depth)
- break;
- if (i != numFormats)
- return &formats[i];
- else if (!formatsDone) {
- /* Check for screen-specified formats */
- for (i = 0; i < pScrn->numFormats; i++)
- if (pScrn->formats[i].depth == depth)
- break;
- if (i != pScrn->numFormats)
- return &pScrn->formats[i];
- }
- return NULL;
-}
-
-int
-xf86GetBppFromDepth(ScrnInfoPtr pScrn, int depth)
-{
- PixmapFormatPtr format;
-
-
- format = xf86GetPixFormat(pScrn, depth);
- if (format)
- return format->bitsPerPixel;
- else
- return 0;
-}
+/* + * Loosely based on code bearing the following copyright: + * + * Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany. + */ +/* + * Copyright (c) 1992-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <stdlib.h> +#include <errno.h> + +#undef HAS_UTSNAME +#if !defined(WIN32) +#define HAS_UTSNAME 1 +#include <sys/utsname.h> +#endif + +#include <X11/X.h> +#include <X11/Xmd.h> +#include <X11/Xproto.h> +#include <X11/Xatom.h> +#include "input.h" +#include "servermd.h" +#include "windowstr.h" +#include "scrnintstr.h" +#include "site.h" +#include "mi.h" + +#include "compiler.h" + +#include "loaderProcs.h" +#ifdef XFreeXDGA +#include "dgaproc.h" +#endif + +#define XF86_OS_PRIVS +#include "xf86.h" +#include "xf86Priv.h" +#include "xf86Config.h" +#include "xf86_OSlib.h" +#include "xf86cmap.h" +#include "xorgVersion.h" +#include "xf86Build.h" +#include "mipointer.h" +#include <X11/extensions/XI.h> +#include <X11/extensions/XIproto.h> +#include "xf86DDC.h" +#include "xf86Xinput.h" +#include "xf86InPriv.h" +#include "picturestr.h" + +#include "xf86Bus.h" +#include "xf86VGAarbiter.h" +#include "globals.h" + +#ifdef DPMSExtension +#include <X11/extensions/dpmsconst.h> +#include "dpmsproc.h" +#endif +#include <hotplug.h> + + +#ifdef XF86PM +void (*xf86OSPMClose)(void) = NULL; +#endif +static Bool xorgHWOpenConsole = FALSE; + +/* Common pixmap formats */ + +static PixmapFormatRec formats[MAXFORMATS] = { + { 1, 1, BITMAP_SCANLINE_PAD }, + { 4, 8, BITMAP_SCANLINE_PAD }, + { 8, 8, BITMAP_SCANLINE_PAD }, + { 15, 16, BITMAP_SCANLINE_PAD }, + { 16, 16, BITMAP_SCANLINE_PAD }, + { 24, 32, BITMAP_SCANLINE_PAD }, + { 32, 32, BITMAP_SCANLINE_PAD }, +}; +static int numFormats = 7; +static Bool formatsDone = FALSE; + +#ifndef OSNAME +#define OSNAME " unknown" +#endif +#ifndef OSVENDOR +#define OSVENDOR "" +#endif +#ifndef PRE_RELEASE +#define PRE_RELEASE XORG_VERSION_SNAP +#endif + +static void +xf86PrintBanner(void) +{ +#if PRE_RELEASE + xf86ErrorFVerb(0, "\n" + "This is a pre-release version of the X server from " XVENDORNAME ".\n" + "It is not supported in any way.\n" + "Bugs may be filed in the bugzilla at http://bugs.freedesktop.org/.\n" + "Select the \"xorg\" product for bugs you find in this release.\n" + "Before reporting bugs in pre-release versions please check the\n" + "latest version in the X.Org Foundation git repository.\n" + "See http://wiki.x.org/wiki/GitPage for git access instructions.\n"); +#endif + xf86ErrorFVerb(0, "\nX.Org X Server %d.%d.%d", + XORG_VERSION_MAJOR, + XORG_VERSION_MINOR, + XORG_VERSION_PATCH); +#if XORG_VERSION_SNAP > 0 + xf86ErrorFVerb(0, ".%d", XORG_VERSION_SNAP); +#endif + +#if XORG_VERSION_SNAP >= 900 + /* When the minor number is 99, that signifies that the we are making + * a release candidate for a major version. (X.0.0) + * When the patch number is 99, that signifies that the we are making + * a release candidate for a minor version. (X.Y.0) + * When the patch number is < 99, then we are making a release + * candidate for the next point release. (X.Y.Z) + */ +#if XORG_VERSION_MINOR >= 99 + xf86ErrorFVerb(0, " (%d.0.0 RC %d)", XORG_VERSION_MAJOR+1, + XORG_VERSION_SNAP - 900); +#elif XORG_VERSION_PATCH == 99 + xf86ErrorFVerb(0, " (%d.%d.0 RC %d)", XORG_VERSION_MAJOR, + XORG_VERSION_MINOR + 1, XORG_VERSION_SNAP - 900); +#else + xf86ErrorFVerb(0, " (%d.%d.%d RC %d)", XORG_VERSION_MAJOR, + XORG_VERSION_MINOR, XORG_VERSION_PATCH + 1, + XORG_VERSION_SNAP - 900); +#endif +#endif + +#ifdef XORG_CUSTOM_VERSION + xf86ErrorFVerb(0, " (%s)", XORG_CUSTOM_VERSION); +#endif +#ifndef XORG_DATE +# define XORG_DATE "Unknown" +#endif + xf86ErrorFVerb(0, "\nRelease Date: %s\n", XORG_DATE); + xf86ErrorFVerb(0, "X Protocol Version %d, Revision %d\n", + X_PROTOCOL, X_PROTOCOL_REVISION); + xf86ErrorFVerb(0, "Build Operating System: %s %s\n", OSNAME, OSVENDOR); +#ifdef HAS_UTSNAME + { + struct utsname name; + + /* Linux & BSD state that 0 is success, SysV (including Solaris, HP-UX, + and Irix) and Single Unix Spec 3 just say that non-negative is success. + All agree that failure is represented by a negative number. + */ + if (uname(&name) >= 0) { + xf86ErrorFVerb(0, "Current Operating System: %s %s %s %s %s\n", + name.sysname, name.nodename, name.release, name.version, name.machine); +#ifdef linux + do { + char buf[80]; + int fd = open("/proc/cmdline", O_RDONLY); + if (fd != -1) { + xf86ErrorFVerb(0, "Kernel command line: "); + memset(buf, 0, 80); + while (read(fd, buf, 80) > 0) { + xf86ErrorFVerb(0, "%.80s", buf); + memset(buf, 0, 80); + } + close(fd); + } + } while (0); +#endif + } + } +#endif +#if defined(BUILD_DATE) && (BUILD_DATE > 19000000) + { + struct tm t; + char buf[100]; + + memset(&t, 0, sizeof(t)); + memset(buf, 0, sizeof(buf)); + t.tm_mday = BUILD_DATE % 100; + t.tm_mon = (BUILD_DATE / 100) % 100 - 1; + t.tm_year = BUILD_DATE / 10000 - 1900; +#if defined(BUILD_TIME) + t.tm_sec = BUILD_TIME % 100; + t.tm_min = (BUILD_TIME / 100) % 100; + t.tm_hour = (BUILD_TIME / 10000) % 100; + if (strftime(buf, sizeof(buf), "%d %B %Y %I:%M:%S%p", &t)) + xf86ErrorFVerb(0, "Build Date: %s\n", buf); +#else + if (strftime(buf, sizeof(buf), "%d %B %Y", &t)) + xf86ErrorFVerb(0, "Build Date: %s\n", buf); +#endif + } +#endif +#if defined(BUILDERSTRING) + xf86ErrorFVerb(0, "%s \n", BUILDERSTRING); +#endif + xf86ErrorFVerb(0, "Current version of pixman: %s\n", + pixman_version_string()); + xf86ErrorFVerb(0, "\tBefore reporting problems, check " + ""__VENDORDWEBSUPPORT__"\n" + "\tto make sure that you have the latest version.\n"); +} + +static void +xf86PrintMarkers(void) +{ + LogPrintMarkers(); +} + +static Bool +xf86CreateRootWindow(WindowPtr pWin) +{ + int ret = TRUE; + int err = Success; + ScreenPtr pScreen = pWin->drawable.pScreen; + RootWinPropPtr pProp; + CreateWindowProcPtr CreateWindow = (CreateWindowProcPtr) + dixLookupPrivate(&pScreen->devPrivates, xf86CreateRootWindowKey); + + DebugF("xf86CreateRootWindow(%p)\n", pWin); + + if ( pScreen->CreateWindow != xf86CreateRootWindow ) { + /* Can't find hook we are hung on */ + xf86DrvMsg(pScreen->myNum, X_WARNING /* X_ERROR */, + "xf86CreateRootWindow %p called when not in pScreen->CreateWindow %p n", + (void *)xf86CreateRootWindow, + (void *)pScreen->CreateWindow ); + } + + /* Unhook this function ... */ + pScreen->CreateWindow = CreateWindow; + dixSetPrivate(&pScreen->devPrivates, xf86CreateRootWindowKey, NULL); + + /* ... and call the previous CreateWindow fuction, if any */ + if (NULL!=pScreen->CreateWindow) { + ret = (*pScreen->CreateWindow)(pWin); + } + + /* Now do our stuff */ + if (xf86RegisteredPropertiesTable != NULL) { + if (pWin->parent == NULL && xf86RegisteredPropertiesTable != NULL) { + for (pProp = xf86RegisteredPropertiesTable[pScreen->myNum]; + pProp != NULL && err==Success; + pProp = pProp->next ) + { + Atom prop; + + prop = MakeAtom(pProp->name, strlen(pProp->name), TRUE); + err = dixChangeWindowProperty(serverClient, pWin, + prop, pProp->type, + pProp->format, PropModeReplace, + pProp->size, pProp->data, + FALSE); + } + + /* Look at err */ + ret &= (err==Success); + + } else { + xf86Msg(X_ERROR, "xf86CreateRootWindow unexpectedly called with " + "non-root window %p (parent %p)\n", + (void *)pWin, (void *)pWin->parent); + ret = FALSE; + } + } + + DebugF("xf86CreateRootWindow() returns %d\n", ret); + return ret; +} + + +static void +InstallSignalHandlers(void) +{ + /* + * Install signal handler for unexpected signals + */ + xf86Info.caughtSignal=FALSE; + if (!xf86Info.notrapSignals) { + OsRegisterSigWrapper(xf86SigWrapper); + } else { + signal(SIGSEGV, SIG_DFL); + signal(SIGILL, SIG_DFL); +#ifdef SIGEMT + signal(SIGEMT, SIG_DFL); +#endif + signal(SIGFPE, SIG_DFL); + signal(SIGBUS, SIG_DFL); + signal(SIGSYS, SIG_DFL); + signal(SIGXCPU, SIG_DFL); + signal(SIGXFSZ, SIG_DFL); + } +} + +/* + * InitOutput -- + * Initialize screenInfo for all actually accessible framebuffers. + * That includes vt-manager setup, querying all possible devices and + * collecting the pixmap formats. + */ +void +InitOutput(ScreenInfo *pScreenInfo, int argc, char **argv) +{ + int i, j, k, scr_index, was_blocked = 0; + char **modulelist; + pointer *optionlist; + Pix24Flags screenpix24, pix24; + MessageType pix24From = X_DEFAULT; + Bool pix24Fail = FALSE; + Bool autoconfig = FALSE; + GDevPtr configured_device; + + xf86Initialising = TRUE; + + if (serverGeneration == 1) { + if ((xf86ServerName = strrchr(argv[0], '/')) != 0) + xf86ServerName++; + else + xf86ServerName = argv[0]; + + xf86PrintBanner(); + xf86PrintMarkers(); + if (xf86LogFile) { + time_t t; + const char *ct; + t = time(NULL); + ct = ctime(&t); + xf86MsgVerb(xf86LogFileFrom, 0, "Log file: \"%s\", Time: %s", + xf86LogFile, ct); + } + + /* Read and parse the config file */ + if (!xf86DoConfigure && !xf86DoShowOptions) { + switch (xf86HandleConfigFile(FALSE)) { + case CONFIG_OK: + break; + case CONFIG_PARSE_ERROR: + xf86Msg(X_ERROR, "Error parsing the config file\n"); + return; + case CONFIG_NOFILE: + autoconfig = TRUE; + break; + } + } + + InstallSignalHandlers(); + + /* Initialise the loader */ + LoaderInit(); + + /* Tell the loader the default module search path */ + LoaderSetPath(xf86ModulePath); + + if (xf86Info.ignoreABI) { + LoaderSetOptions(LDR_OPT_ABI_MISMATCH_NONFATAL); + } + + if (xf86DoShowOptions) + DoShowOptions(); + + /* Do a general bus probe. This will be a PCI probe for x86 platforms */ + xf86BusProbe(); + + if (xf86DoConfigure) + DoConfigure(); + + if (autoconfig) { + if (!xf86AutoConfig()) { + xf86Msg(X_ERROR, "Auto configuration failed\n"); + return; + } + } + +#ifdef XF86PM + xf86OSPMClose = xf86OSPMOpen(); +#endif + + /* Load all modules specified explicitly in the config file */ + if ((modulelist = xf86ModulelistFromConfig(&optionlist))) { + xf86LoadModules(modulelist, optionlist); + free(modulelist); + free(optionlist); + } + + /* Load all driver modules specified in the config file */ + /* If there aren't any specified in the config file, autoconfig them */ + /* FIXME: Does not handle multiple active screen sections, but I'm not + * sure if we really want to handle that case*/ + configured_device = xf86ConfigLayout.screens->screen->device; + if ((!configured_device) || (!configured_device->driver)) { + if (!autoConfigDevice(configured_device)) { + xf86Msg(X_ERROR, "Automatic driver configuration failed\n"); + return ; + } + } + if ((modulelist = xf86DriverlistFromConfig())) { + xf86LoadModules(modulelist, NULL); + free(modulelist); + } + + /* Load all input driver modules specified in the config file. */ + if ((modulelist = xf86InputDriverlistFromConfig())) { + xf86LoadModules(modulelist, NULL); + free(modulelist); + } + + /* + * It is expected that xf86AddDriver()/xf86AddInputDriver will be + * called for each driver as it is loaded. Those functions save the + * module pointers for drivers. + * XXX Nothing keeps track of them for other modules. + */ + /* XXX What do we do if not all of these could be loaded? */ + + /* + * At this point, xf86DriverList[] is all filled in with entries for + * each of the drivers to try and xf86NumDrivers has the number of + * drivers. If there are none, return now. + */ + + if (xf86NumDrivers == 0) { + xf86Msg(X_ERROR, "No drivers available.\n"); + return; + } + + /* + * Call each of the Identify functions and call the driverFunc to check + * if HW access is required. The Identify functions print out some + * identifying information, and anything else that might be + * needed at this early stage. + */ + + for (i = 0; i < xf86NumDrivers; i++) { + if (xf86DriverList[i]->Identify != NULL) + xf86DriverList[i]->Identify(0); + + if (!xorgHWAccess || !xorgHWOpenConsole) { + xorgHWFlags flags; + if(!xf86DriverList[i]->driverFunc + || !xf86DriverList[i]->driverFunc(NULL, + GET_REQUIRED_HW_INTERFACES, + &flags)) + flags = HW_IO; + + if(NEED_IO_ENABLED(flags)) + xorgHWAccess = TRUE; + if(!(flags & HW_SKIP_CONSOLE)) + xorgHWOpenConsole = TRUE; + } + } + + if (xorgHWOpenConsole) + xf86OpenConsole(); + else + xf86Info.dontVTSwitch = TRUE; + + if (xf86BusConfig() == FALSE) + return; + + xf86PostProbe(); + + /* + * Sort the drivers to match the requested ording. Using a slow + * bubble sort. + */ + for (j = 0; j < xf86NumScreens - 1; j++) { + for (i = 0; i < xf86NumScreens - j - 1; i++) { + if (xf86Screens[i + 1]->confScreen->screennum < + xf86Screens[i]->confScreen->screennum) { + ScrnInfoPtr tmpScrn = xf86Screens[i + 1]; + xf86Screens[i + 1] = xf86Screens[i]; + xf86Screens[i] = tmpScrn; + } + } + } + /* Fix up the indexes */ + for (i = 0; i < xf86NumScreens; i++) { + xf86Screens[i]->scrnIndex = i; + } + + /* + * Call the driver's PreInit()'s to complete initialisation for the first + * generation. + */ + + for (i = 0; i < xf86NumScreens; i++) { + xf86VGAarbiterScrnInit(xf86Screens[i]); + xf86VGAarbiterLock(xf86Screens[i]); + if (xf86Screens[i]->PreInit && + xf86Screens[i]->PreInit(xf86Screens[i], 0)) + xf86Screens[i]->configured = TRUE; + xf86VGAarbiterUnlock(xf86Screens[i]); + } + for (i = 0; i < xf86NumScreens; i++) + if (!xf86Screens[i]->configured) + xf86DeleteScreen(i--, 0); + + /* + * If no screens left, return now. + */ + + if (xf86NumScreens == 0) { + xf86Msg(X_ERROR, + "Screen(s) found, but none have a usable configuration.\n"); + return; + } + + for (i = 0; i < xf86NumScreens; i++) { + if (xf86Screens[i]->name == NULL) { + XNFasprintf(&xf86Screens[i]->name, "screen%d", i); + xf86MsgVerb(X_WARNING, 0, + "Screen driver %d has no name set, using `%s'.\n", + i, xf86Screens[i]->name); + } + } + + /* Remove (unload) drivers that are not required */ + for (i = 0; i < xf86NumDrivers; i++) + if (xf86DriverList[i] && xf86DriverList[i]->refCount <= 0) + xf86DeleteDriver(i); + + /* + * At this stage we know how many screens there are. + */ + + for (i = 0; i < xf86NumScreens; i++) + xf86InitViewport(xf86Screens[i]); + + /* + * Collect all pixmap formats and check for conflicts at the display + * level. Should we die here? Or just delete the offending screens? + */ + screenpix24 = Pix24DontCare; + for (i = 0; i < xf86NumScreens; i++) { + if (xf86Screens[i]->imageByteOrder != + xf86Screens[0]->imageByteOrder) + FatalError("Inconsistent display bitmapBitOrder. Exiting\n"); + if (xf86Screens[i]->bitmapScanlinePad != + xf86Screens[0]->bitmapScanlinePad) + FatalError("Inconsistent display bitmapScanlinePad. Exiting\n"); + if (xf86Screens[i]->bitmapScanlineUnit != + xf86Screens[0]->bitmapScanlineUnit) + FatalError("Inconsistent display bitmapScanlineUnit. Exiting\n"); + if (xf86Screens[i]->bitmapBitOrder != + xf86Screens[0]->bitmapBitOrder) + FatalError("Inconsistent display bitmapBitOrder. Exiting\n"); + + /* Determine the depth 24 pixmap format the screens would like */ + if (xf86Screens[i]->pixmap24 != Pix24DontCare) { + if (screenpix24 == Pix24DontCare) + screenpix24 = xf86Screens[i]->pixmap24; + else if (screenpix24 != xf86Screens[i]->pixmap24) + FatalError("Inconsistent depth 24 pixmap format. Exiting\n"); + } + } + /* check if screenpix24 is consistent with the config/cmdline */ + if (xf86Info.pixmap24 != Pix24DontCare) { + pix24 = xf86Info.pixmap24; + pix24From = xf86Info.pix24From; + if (screenpix24 != Pix24DontCare && screenpix24 != xf86Info.pixmap24) + pix24Fail = TRUE; + } else if (screenpix24 != Pix24DontCare) { + pix24 = screenpix24; + pix24From = X_PROBED; + } else + pix24 = Pix24Use32; + + if (pix24Fail) + FatalError("Screen(s) can't use the required depth 24 pixmap format" + " (%d). Exiting\n", PIX24TOBPP(pix24)); + + /* Initialise the depth 24 format */ + for (j = 0; j < numFormats && formats[j].depth != 24; j++) + ; + formats[j].bitsPerPixel = PIX24TOBPP(pix24); + + /* Collect additional formats */ + for (i = 0; i < xf86NumScreens; i++) { + for (j = 0; j < xf86Screens[i]->numFormats; j++) { + for (k = 0; ; k++) { + if (k >= numFormats) { + if (k >= MAXFORMATS) + FatalError("Too many pixmap formats! Exiting\n"); + formats[k] = xf86Screens[i]->formats[j]; + numFormats++; + break; + } + if (formats[k].depth == xf86Screens[i]->formats[j].depth) { + if ((formats[k].bitsPerPixel == + xf86Screens[i]->formats[j].bitsPerPixel) && + (formats[k].scanlinePad == + xf86Screens[i]->formats[j].scanlinePad)) + break; + FatalError("Inconsistent pixmap format for depth %d." + " Exiting\n", formats[k].depth); + } + } + } + } + formatsDone = TRUE; + + if (xf86Info.vtno >= 0 ) { +#define VT_ATOM_NAME "XFree86_VT" + Atom VTAtom=-1; + CARD32 *VT = NULL; + int ret; + + /* This memory needs to stay available until the screen has been + initialized, and we can create the property for real. + */ + if ( (VT = malloc(sizeof(CARD32)))==NULL ) { + FatalError("Unable to make VT property - out of memory. Exiting...\n"); + } + *VT = xf86Info.vtno; + + VTAtom = MakeAtom(VT_ATOM_NAME, sizeof(VT_ATOM_NAME) - 1, TRUE); + + for (i = 0, ret = Success; i < xf86NumScreens && ret == Success; i++) { + ret = xf86RegisterRootWindowProperty(xf86Screens[i]->scrnIndex, + VTAtom, XA_INTEGER, 32, + 1, VT ); + if (ret != Success) + xf86DrvMsg(xf86Screens[i]->scrnIndex, X_WARNING, + "Failed to register VT property\n"); + } + } + + /* If a screen uses depth 24, show what the pixmap format is */ + for (i = 0; i < xf86NumScreens; i++) { + if (xf86Screens[i]->depth == 24) { + xf86Msg(pix24From, "Depth 24 pixmap format is %d bpp\n", + PIX24TOBPP(pix24)); + break; + } + } + } else { + /* + * serverGeneration != 1; some OSs have to do things here, too. + */ + if (xorgHWOpenConsole) + xf86OpenConsole(); + +#ifdef XF86PM + /* + should we reopen it here? We need to deal with an already opened + device. We could leave this to the OS layer. For now we simply + close it here + */ + if (xf86OSPMClose) + xf86OSPMClose(); + if ((xf86OSPMClose = xf86OSPMOpen()) != NULL) + xf86MsgVerb(X_INFO, 3, "APM registered successfully\n"); +#endif + + /* Make sure full I/O access is enabled */ + if (xorgHWAccess) + xf86EnableIO(); + } + + /* + * Use the previously collected parts to setup pScreenInfo + */ + + pScreenInfo->imageByteOrder = xf86Screens[0]->imageByteOrder; + pScreenInfo->bitmapScanlinePad = xf86Screens[0]->bitmapScanlinePad; + pScreenInfo->bitmapScanlineUnit = xf86Screens[0]->bitmapScanlineUnit; + pScreenInfo->bitmapBitOrder = xf86Screens[0]->bitmapBitOrder; + pScreenInfo->numPixmapFormats = numFormats; + for (i = 0; i < numFormats; i++) + pScreenInfo->formats[i] = formats[i]; + + /* Make sure the server's VT is active */ + + if (serverGeneration != 1) { + xf86Resetting = TRUE; + /* All screens are in the same state, so just check the first */ + if (!xf86Screens[0]->vtSema) { +#ifdef HAS_USL_VTS + ioctl(xf86Info.consoleFd, VT_RELDISP, VT_ACKACQ); +#endif + xf86AccessEnter(); + was_blocked = xf86BlockSIGIO(); + } + } + + for (i = 0; i < xf86NumScreens; i++) + if (!xf86ColormapAllocatePrivates(xf86Screens[i])) + FatalError("Cannot register DDX private keys"); + + if (!dixRegisterPrivateKey(&xf86ScreenKeyRec, PRIVATE_SCREEN, 0) || + !dixRegisterPrivateKey(&xf86CreateRootWindowKeyRec, PRIVATE_SCREEN, 0)) + FatalError("Cannot register DDX private keys"); + + for (i = 0; i < xf86NumScreens; i++) { + xf86VGAarbiterLock(xf86Screens[i]); + /* + * Almost everything uses these defaults, and many of those that + * don't, will wrap them. + */ + xf86Screens[i]->EnableDisableFBAccess = xf86EnableDisableFBAccess; +#ifdef XFreeXDGA + xf86Screens[i]->SetDGAMode = xf86SetDGAMode; +#endif + xf86Screens[i]->DPMSSet = NULL; + xf86Screens[i]->LoadPalette = NULL; + xf86Screens[i]->SetOverscan = NULL; + xf86Screens[i]->DriverFunc = NULL; + xf86Screens[i]->pScreen = NULL; + scr_index = AddScreen(xf86Screens[i]->ScreenInit, argc, argv); + xf86VGAarbiterUnlock(xf86Screens[i]); + if (scr_index == i) { + /* + * Hook in our ScrnInfoRec, and initialise some other pScreen + * fields. + */ + dixSetPrivate(&screenInfo.screens[scr_index]->devPrivates, + xf86ScreenKey, xf86Screens[i]); + xf86Screens[i]->pScreen = screenInfo.screens[scr_index]; + /* The driver should set this, but make sure it is set anyway */ + xf86Screens[i]->vtSema = TRUE; + } else { + /* This shouldn't normally happen */ + FatalError("AddScreen/ScreenInit failed for driver %d\n", i); + } + + DebugF("InitOutput - xf86Screens[%d]->pScreen = %p\n", + i, xf86Screens[i]->pScreen ); + DebugF("xf86Screens[%d]->pScreen->CreateWindow = %p\n", + i, xf86Screens[i]->pScreen->CreateWindow ); + + dixSetPrivate(&screenInfo.screens[scr_index]->devPrivates, + xf86CreateRootWindowKey, + xf86Screens[i]->pScreen->CreateWindow); + xf86Screens[i]->pScreen->CreateWindow = xf86CreateRootWindow; + + if (PictureGetSubpixelOrder (xf86Screens[i]->pScreen) == SubPixelUnknown) + { + xf86MonPtr DDC = (xf86MonPtr)(xf86Screens[i]->monitor->DDC); + PictureSetSubpixelOrder (xf86Screens[i]->pScreen, + DDC ? + (DDC->features.input_type ? + SubPixelHorizontalRGB : SubPixelNone) : + SubPixelUnknown); + } +#ifdef RANDR + if (!xf86Info.disableRandR) + xf86RandRInit (screenInfo.screens[scr_index]); + xf86Msg(xf86Info.randRFrom, "RandR %s\n", + xf86Info.disableRandR ? "disabled" : "enabled"); +#endif + } + + xf86VGAarbiterWrapFunctions(); + xf86UnblockSIGIO(was_blocked); + + xf86InitOrigins(); + + xf86Resetting = FALSE; + xf86Initialising = FALSE; + + RegisterBlockAndWakeupHandlers((BlockHandlerProcPtr)NoopDDA, xf86Wakeup, + 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. + */ + +void +InitInput(int argc, char **argv) +{ + InputInfoPtr* pInfo; + DeviceIntPtr dev; + + xf86Info.vtRequestsPending = FALSE; + + mieqInit(); + + /* Initialize all configured input devices */ + for (pInfo = xf86ConfigLayout.inputs; pInfo && *pInfo; pInfo++) { + InputInfoPtr dup; + /* Replace obsolete keyboard driver with 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(dup, &dev, TRUE) == BadAlloc) + break; + } + + config_init(); +} + +void +CloseInput (void) +{ + config_fini(); + mieqFini(); +} + +/* + * OsVendorInit -- + * OS/Vendor-specific initialisations. Called from OsInit(), which + * is called by dix before establishing the well known sockets. + */ + +void +OsVendorInit(void) +{ + static Bool beenHere = FALSE; + + signal(SIGCHLD, SIG_DFL); /* Need to wait for child processes */ + + if (!beenHere) { + umask(022); + xf86LogInit(); + } + + /* Set stderr to non-blocking. */ +#ifndef O_NONBLOCK +#if defined(FNDELAY) +#define O_NONBLOCK FNDELAY +#elif defined(O_NDELAY) +#define O_NONBLOCK O_NDELAY +#endif + +#ifdef O_NONBLOCK + if (!beenHere) { + if (geteuid() == 0 && getuid() != geteuid()) + { + int status; + + status = fcntl(fileno(stderr), F_GETFL, 0); + if (status != -1) { + fcntl(fileno(stderr), F_SETFL, status | O_NONBLOCK); + } + } + } +#endif +#endif + + beenHere = TRUE; +} + +/* + * ddxGiveUp -- + * Device dependent cleanup. Called by by dix before normal server death. + * For SYSV386 we must switch the terminal back to normal mode. No error- + * checking here, since there should be restored as much as possible. + */ + +void +ddxGiveUp(enum ExitCode error) +{ + int i; + + xf86VGAarbiterFini(); + +#ifdef XF86PM + if (xf86OSPMClose) + xf86OSPMClose(); + xf86OSPMClose = NULL; +#endif + + for (i = 0; i < xf86NumScreens; i++) { + /* + * zero all access functions to + * trap calls when switched away. + */ + xf86Screens[i]->vtSema = FALSE; + } + +#ifdef XFreeXDGA + DGAShutdown(); +#endif + + if (xorgHWOpenConsole) + xf86CloseConsole(); + + xf86CloseLog(error); + + /* If an unexpected signal was caught, dump a core for debugging */ + if (xf86Info.caughtSignal) + OsAbort(); +} + + + +/* + * AbortDDX -- + * DDX - specific abort routine. Called by AbortServer(). The attempt is + * made to restore all original setting of the displays. Also all devices + * are closed. + */ + +void +AbortDDX(enum ExitCode error) +{ + int i; + + xf86BlockSIGIO(); + + /* + * try to restore the original video state + */ +#ifdef DPMSExtension /* Turn screens back on */ + if (DPMSPowerLevel != DPMSModeOn) + DPMSSet(serverClient, DPMSModeOn); +#endif + if (xf86Screens) { + for (i = 0; i < xf86NumScreens; i++) + if (xf86Screens[i]->vtSema) { + /* + * if we are aborting before ScreenInit() has finished + * we might not have been wrapped yet. Therefore enable + * screen explicitely. + */ + xf86VGAarbiterLock(xf86Screens[i]); + (xf86Screens[i]->LeaveVT)(i, 0); + xf86VGAarbiterUnlock(xf86Screens[i]); + } + } + + xf86AccessLeave(); + + /* + * 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(error); +} + +void +OsVendorFatalError(void) +{ +#ifdef VENDORSUPPORT + ErrorF("\nPlease refer to your Operating System Vendor support pages\n" + "at %s for support on this crash.\n",VENDORSUPPORT); +#else + ErrorF("\nPlease consult the "XVENDORNAME" support \n" + "\t at "__VENDORDWEBSUPPORT__"\n for help. \n"); +#endif + if (xf86LogFile && xf86LogFileWasOpened) + ErrorF("Please also check the log file at \"%s\" for additional " + "information.\n", xf86LogFile); + ErrorF("\n"); +} + +int +xf86SetVerbosity(int verb) +{ + int save = xf86Verbose; + + xf86Verbose = verb; + LogSetParameter(XLOG_VERBOSITY, verb); + return save; +} + +int +xf86SetLogVerbosity(int verb) +{ + int save = xf86LogVerbose; + + xf86LogVerbose = verb; + LogSetParameter(XLOG_FILE_VERBOSITY, verb); + return save; +} + +static void +xf86PrintDefaultModulePath(void) +{ + ErrorF("%s\n", DEFAULT_MODULE_PATH); +} + +static void +xf86PrintDefaultLibraryPath(void) +{ + ErrorF("%s\n", DEFAULT_LIBRARY_PATH); +} + +/* + * ddxProcessArgument -- + * Process device-dependent command line args. Returns 0 if argument is + * not device dependent, otherwise Count of number of elements of argv + * that are part of a device dependent commandline option. + * + */ + +/* ARGSUSED */ +int +ddxProcessArgument(int argc, char **argv, int i) +{ +#define CHECK_FOR_REQUIRED_ARGUMENT() \ + if (((i + 1) >= argc) || (!argv[i + 1])) { \ + ErrorF("Required argument to %s not specified\n", argv[i]); \ + UseMsg(); \ + FatalError("Required argument to %s not specified\n", argv[i]); \ + } + + /* First the options that are only allowed for root */ + if (!strcmp(argv[i], "-modulepath") || !strcmp(argv[i], "-logfile")) { + if ( (geteuid() == 0) && (getuid() != 0) ) { + FatalError("The '%s' option can only be used by root.\n", argv[i]); + } + else if (!strcmp(argv[i], "-modulepath")) + { + char *mp; + CHECK_FOR_REQUIRED_ARGUMENT(); + mp = strdup(argv[i + 1]); + if (!mp) + FatalError("Can't allocate memory for ModulePath\n"); + xf86ModulePath = mp; + xf86ModPathFrom = X_CMDLINE; + return 2; + } + else if (!strcmp(argv[i], "-logfile")) + { + char *lf; + CHECK_FOR_REQUIRED_ARGUMENT(); + lf = strdup(argv[i + 1]); + if (!lf) + FatalError("Can't allocate memory for LogFile\n"); + xf86LogFile = lf; + xf86LogFileFrom = X_CMDLINE; + return 2; + } + } + if (!strcmp(argv[i], "-config") || !strcmp(argv[i], "-xf86config")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) { + FatalError("\nInvalid argument for %s\n" + "\tFor non-root users, the file specified with %s must be\n" + "\ta relative path and must not contain any \"..\" elements.\n" + "\tUsing default "__XCONFIGFILE__" search path.\n\n", + argv[i], argv[i]); + } + xf86ConfigFile = argv[i + 1]; + return 2; + } + if (!strcmp(argv[i], "-configdir")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + if (getuid() != 0 && !xf86PathIsSafe(argv[i + 1])) { + FatalError("\nInvalid argument for %s\n" + "\tFor non-root users, the file specified with %s must be\n" + "\ta relative path and must not contain any \"..\" elements.\n" + "\tUsing default "__XCONFIGDIR__" search path.\n\n", + argv[i], argv[i]); + } + xf86ConfigDir = argv[i + 1]; + return 2; + } + if (!strcmp(argv[i],"-flipPixels")) + { + xf86FlipPixels = TRUE; + return 1; + } +#ifdef XF86VIDMODE + if (!strcmp(argv[i],"-disableVidMode")) + { + xf86VidModeDisabled = TRUE; + return 1; + } + if (!strcmp(argv[i],"-allowNonLocalXvidtune")) + { + xf86VidModeAllowNonLocal = TRUE; + return 1; + } +#endif + if (!strcmp(argv[i],"-allowMouseOpenFail")) + { + xf86AllowMouseOpenFail = TRUE; + return 1; + } + if (!strcmp(argv[i],"-ignoreABI")) + { + LoaderSetOptions(LDR_OPT_ABI_MISMATCH_NONFATAL); + return 1; + } + if (!strcmp(argv[i],"-verbose")) + { + if (++i < argc && argv[i]) + { + char *end; + long val; + val = strtol(argv[i], &end, 0); + if (*end == '\0') + { + xf86SetVerbosity(val); + return 2; + } + } + xf86SetVerbosity(++xf86Verbose); + return 1; + } + if (!strcmp(argv[i],"-logverbose")) + { + if (++i < argc && argv[i]) + { + char *end; + long val; + val = strtol(argv[i], &end, 0); + if (*end == '\0') + { + xf86SetLogVerbosity(val); + return 2; + } + } + xf86SetLogVerbosity(++xf86LogVerbose); + return 1; + } + if (!strcmp(argv[i],"-quiet")) + { + xf86SetVerbosity(-1); + return 1; + } + if (!strcmp(argv[i],"-showconfig") || !strcmp(argv[i],"-version")) + { + xf86PrintBanner(); + exit(0); + } + if (!strcmp(argv[i],"-showDefaultModulePath")) + { + xf86PrintDefaultModulePath(); + exit(0); + } + if (!strcmp(argv[i],"-showDefaultLibPath")) + { + xf86PrintDefaultLibraryPath(); + exit(0); + } + /* Notice the -fp flag, but allow it to pass to the dix layer */ + if (!strcmp(argv[i], "-fp")) + { + xf86fpFlag = TRUE; + return 0; + } + /* Notice the -bs flag, but allow it to pass to the dix layer */ + if (!strcmp(argv[i], "-bs")) + { + xf86bsDisableFlag = TRUE; + return 0; + } + /* Notice the +bs flag, but allow it to pass to the dix layer */ + if (!strcmp(argv[i], "+bs")) + { + xf86bsEnableFlag = TRUE; + return 0; + } + /* Notice the -s flag, but allow it to pass to the dix layer */ + if (!strcmp(argv[i], "-s")) + { + xf86sFlag = TRUE; + return 0; + } + if (!strcmp(argv[i], "-pixmap24")) + { + xf86Pix24 = Pix24Use24; + return 1; + } + if (!strcmp(argv[i], "-pixmap32")) + { + xf86Pix24 = Pix24Use32; + return 1; + } + if (!strcmp(argv[i], "-fbbpp")) + { + int bpp; + CHECK_FOR_REQUIRED_ARGUMENT(); + if (sscanf(argv[++i], "%d", &bpp) == 1) + { + xf86FbBpp = bpp; + return 2; + } + else + { + ErrorF("Invalid fbbpp\n"); + return 0; + } + } + if (!strcmp(argv[i], "-depth")) + { + int depth; + CHECK_FOR_REQUIRED_ARGUMENT(); + if (sscanf(argv[++i], "%d", &depth) == 1) + { + xf86Depth = depth; + return 2; + } + else + { + ErrorF("Invalid depth\n"); + return 0; + } + } + if (!strcmp(argv[i], "-weight")) + { + int red, green, blue; + CHECK_FOR_REQUIRED_ARGUMENT(); + if (sscanf(argv[++i], "%1d%1d%1d", &red, &green, &blue) == 3) + { + xf86Weight.red = red; + xf86Weight.green = green; + xf86Weight.blue = blue; + return 2; + } + else + { + ErrorF("Invalid weighting\n"); + return 0; + } + } + if (!strcmp(argv[i], "-gamma") || !strcmp(argv[i], "-rgamma") || + !strcmp(argv[i], "-ggamma") || !strcmp(argv[i], "-bgamma")) + { + double gamma; + CHECK_FOR_REQUIRED_ARGUMENT(); + if (sscanf(argv[++i], "%lf", &gamma) == 1) { + if (gamma < GAMMA_MIN || gamma > GAMMA_MAX) { + ErrorF("gamma out of range, only %.2f <= gamma_value <= %.1f" + " is valid\n", GAMMA_MIN, GAMMA_MAX); + return 0; + } + if (!strcmp(argv[i-1], "-gamma")) + xf86Gamma.red = xf86Gamma.green = xf86Gamma.blue = gamma; + else if (!strcmp(argv[i-1], "-rgamma")) xf86Gamma.red = gamma; + else if (!strcmp(argv[i-1], "-ggamma")) xf86Gamma.green = gamma; + else if (!strcmp(argv[i-1], "-bgamma")) xf86Gamma.blue = gamma; + return 2; + } + } + if (!strcmp(argv[i], "-layout")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + xf86LayoutName = argv[++i]; + return 2; + } + if (!strcmp(argv[i], "-screen")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + xf86ScreenName = argv[++i]; + return 2; + } + if (!strcmp(argv[i], "-pointer")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + xf86PointerName = argv[++i]; + return 2; + } + if (!strcmp(argv[i], "-keyboard")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + xf86KeyboardName = argv[++i]; + return 2; + } + if (!strcmp(argv[i], "-nosilk")) + { + xf86silkenMouseDisableFlag = TRUE; + return 1; + } +#ifdef HAVE_ACPI + if (!strcmp(argv[i], "-noacpi")) + { + xf86acpiDisableFlag = TRUE; + return 1; + } +#endif + if (!strcmp(argv[i], "-configure")) + { + if (getuid() != 0 && geteuid() == 0) { + ErrorF("The '-configure' option can only be used by root.\n"); + exit(1); + } + xf86DoConfigure = TRUE; + xf86AllowMouseOpenFail = TRUE; + return 1; + } + if (!strcmp(argv[i], "-showopts")) + { + if (getuid() != 0 && geteuid() == 0) { + ErrorF("The '-showopts' option can only be used by root.\n"); + exit(1); + } + xf86DoShowOptions = TRUE; + return 1; + } + if (!strcmp(argv[i], "-isolateDevice")) + { + CHECK_FOR_REQUIRED_ARGUMENT(); + if (strncmp(argv[++i], "PCI:", 4)) { + FatalError("Bus types other than PCI not yet isolable\n"); + } + xf86PciIsolateDevice(argv[i]); + return 2; + } + /* Notice cmdline xkbdir, but pass to dix as well */ + if (!strcmp(argv[i], "-xkbdir")) + { + xf86xkbdirFlag = TRUE; + return 0; + } + + /* OS-specific processing */ + return xf86ProcessArgument(argc, argv, i); +} + +/* + * ddxUseMsg -- + * Print out correct use of device dependent commandline options. + * Maybe the user now knows what really to do ... + */ + +void +ddxUseMsg(void) +{ + ErrorF("\n"); + ErrorF("\n"); + ErrorF("Device Dependent Usage\n"); + if (getuid() == 0 || geteuid() != 0) + { + ErrorF("-modulepath paths specify the module search path\n"); + ErrorF("-logfile file specify a log file name\n"); + ErrorF("-configure probe for devices and write an "__XCONFIGFILE__"\n"); + ErrorF("-showopts print available options for all installed drivers\n"); + } + ErrorF("-config file specify a configuration file, relative to the\n"); + ErrorF(" "__XCONFIGFILE__" search path, only root can use absolute\n"); + ErrorF("-configdir dir specify a configuration directory, relative to the\n"); + ErrorF(" "__XCONFIGDIR__" search path, only root can use absolute\n"); + ErrorF("-verbose [n] verbose startup messages\n"); + ErrorF("-logverbose [n] verbose log messages\n"); + ErrorF("-quiet minimal startup messages\n"); + ErrorF("-pixmap24 use 24bpp pixmaps for depth 24\n"); + ErrorF("-pixmap32 use 32bpp pixmaps for depth 24\n"); + ErrorF("-fbbpp n set bpp for the framebuffer. Default: 8\n"); + ErrorF("-depth n set colour depth. Default: 8\n"); + ErrorF("-gamma f set gamma value (0.1 < f < 10.0) Default: 1.0\n"); + ErrorF("-rgamma f set gamma value for red phase\n"); + ErrorF("-ggamma f set gamma value for green phase\n"); + ErrorF("-bgamma f set gamma value for blue phase\n"); + ErrorF("-weight nnn set RGB weighting at 16 bpp. Default: 565\n"); + ErrorF("-layout name specify the ServerLayout section name\n"); + ErrorF("-screen name specify the Screen section name\n"); + ErrorF("-keyboard name specify the core keyboard InputDevice name\n"); + ErrorF("-pointer name specify the core pointer InputDevice name\n"); + ErrorF("-nosilk disable Silken Mouse\n"); + ErrorF("-flipPixels swap default black/white Pixel values\n"); +#ifdef XF86VIDMODE + ErrorF("-disableVidMode disable mode adjustments with xvidtune\n"); + ErrorF("-allowNonLocalXvidtune allow xvidtune to be run as a non-local client\n"); +#endif + ErrorF("-allowMouseOpenFail start server even if the mouse can't be initialized\n"); + ErrorF("-ignoreABI make module ABI mismatches non-fatal\n"); + ErrorF("-isolateDevice bus_id restrict device resets to bus_id (PCI only)\n"); + ErrorF("-version show the server version\n"); + ErrorF("-showDefaultModulePath show the server default module path\n"); + ErrorF("-showDefaultLibPath show the server default library path\n"); + /* OS-specific usage */ + xf86UseMsg(); + ErrorF("\n"); +} + + +/* + * xf86LoadModules iterates over a list that is being passed in. + */ +Bool +xf86LoadModules(char **list, pointer *optlist) +{ + int errmaj, errmin; + pointer opt; + int i; + char *name; + Bool failed = FALSE; + + if (!list) + return TRUE; + + for (i = 0; list[i] != NULL; i++) { + + /* Normalise the module name */ + name = xf86NormalizeName(list[i]); + + /* Skip empty names */ + if (name == NULL || *name == '\0') { + free(name); + continue; + } + + /* Replace obsolete keyboard driver with kbd */ + if (!xf86NameCmp(name, "keyboard")) { + strcpy(name, "kbd"); + } + + if (optlist) + opt = optlist[i]; + else + opt = NULL; + + if (!LoadModule(name, NULL, NULL, NULL, opt, NULL, &errmaj, &errmin)) { + LoaderErrorMsg(NULL, name, errmaj, errmin); + failed = TRUE; + } + free(name); + } + return !failed; +} + +/* Pixmap format stuff */ + +PixmapFormatPtr +xf86GetPixFormat(ScrnInfoPtr pScrn, int depth) +{ + int i; + static PixmapFormatRec format; /* XXX not reentrant */ + + /* + * When the formats[] list initialisation isn't complete, check the + * depth 24 pixmap config/cmdline options and screen-specified formats. + */ + + if (!formatsDone) { + if (depth == 24) { + Pix24Flags pix24 = Pix24DontCare; + + format.depth = 24; + format.scanlinePad = BITMAP_SCANLINE_PAD; + if (xf86Info.pixmap24 != Pix24DontCare) + pix24 = xf86Info.pixmap24; + else if (pScrn->pixmap24 != Pix24DontCare) + pix24 = pScrn->pixmap24; + if (pix24 == Pix24Use24) + format.bitsPerPixel = 24; + else + format.bitsPerPixel = 32; + return &format; + } + } + + for (i = 0; i < numFormats; i++) + if (formats[i].depth == depth) + break; + if (i != numFormats) + return &formats[i]; + else if (!formatsDone) { + /* Check for screen-specified formats */ + for (i = 0; i < pScrn->numFormats; i++) + if (pScrn->formats[i].depth == depth) + break; + if (i != pScrn->numFormats) + return &pScrn->formats[i]; + } + return NULL; +} + +int +xf86GetBppFromDepth(ScrnInfoPtr pScrn, int depth) +{ + PixmapFormatPtr format; + + + format = xf86GetPixFormat(pScrn, depth); + if (format) + return format->bitsPerPixel; + else + return 0; +} diff --git a/xorg-server/hw/xfree86/common/xf86Module.h b/xorg-server/hw/xfree86/common/xf86Module.h index f5f182b25..2a5c805c4 100644 --- a/xorg-server/hw/xfree86/common/xf86Module.h +++ b/xorg-server/hw/xfree86/common/xf86Module.h @@ -1,212 +1,212 @@ -/*
- * Copyright (c) 1997-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/*
- * This file contains the parts of the loader interface that are visible
- * to modules. This is the only loader-related header that modules should
- * include.
- *
- * It should include a bare minimum of other headers.
- *
- * Longer term, the module/loader code should probably live directly under
- * Xserver/.
- *
- * XXX This file arguably belongs in xfree86/loader/.
- */
-
-#ifndef _XF86MODULE_H
-#define _XF86MODULE_H
-
-#include "misc.h"
-#ifndef NULL
-#define NULL ((void *)0)
-#endif
-
-typedef enum {
- LD_RESOLV_IFDONE = 0, /* only check if no more
- delays pending */
- LD_RESOLV_NOW = 1, /* finish one delay step */
- LD_RESOLV_FORCE = 2 /* force checking... */
-} LoaderResolveOptions;
-
-#define DEFAULT_LIST ((char *)-1)
-
-/* This indicates a special module that doesn't have the usual entry point */
-#define EXTERN_MODULE ((pointer)-1)
-
-/* Built-in ABI classes. These definitions must not be changed. */
-#define ABI_CLASS_NONE NULL
-#define ABI_CLASS_ANSIC "X.Org ANSI C Emulation"
-#define ABI_CLASS_VIDEODRV "X.Org Video Driver"
-#define ABI_CLASS_XINPUT "X.Org XInput driver"
-#define ABI_CLASS_EXTENSION "X.Org Server Extension"
-#define ABI_CLASS_FONT "X.Org Font Renderer"
-
-#define ABI_MINOR_MASK 0x0000FFFF
-#define ABI_MAJOR_MASK 0xFFFF0000
-#define GET_ABI_MINOR(v) ((v) & ABI_MINOR_MASK)
-#define GET_ABI_MAJOR(v) (((v) & ABI_MAJOR_MASK) >> 16)
-#define SET_ABI_VERSION(maj, min) \
- ((((maj) << 16) & ABI_MAJOR_MASK) | ((min) & ABI_MINOR_MASK))
-
-/*
- * ABI versions. Each version has a major and minor revision. Modules
- * using lower minor revisions must work with servers of a higher minor
- * revision. There is no compatibility between different major revisions.
- * Whenever the ABI_ANSIC_VERSION is changed, the others must also be
- * changed. The minor revision mask is 0x0000FFFF and the major revision
- * mask is 0xFFFF0000.
- */
-#define ABI_ANSIC_VERSION SET_ABI_VERSION(0, 4)
-#define ABI_VIDEODRV_VERSION SET_ABI_VERSION(11, 0)
-#define ABI_XINPUT_VERSION SET_ABI_VERSION(13, 0)
-#define ABI_EXTENSION_VERSION SET_ABI_VERSION(5, 0)
-#define ABI_FONT_VERSION SET_ABI_VERSION(0, 6)
-
-#define MODINFOSTRING1 0xef23fdc5
-#define MODINFOSTRING2 0x10dc023a
-
-#ifndef MODULEVENDORSTRING
-#define MODULEVENDORSTRING "X.Org Foundation"
-#endif
-
-/* Error return codes for errmaj. New codes must only be added at the end. */
-typedef enum {
- LDR_NOERROR = 0,
- LDR_NOMEM, /* memory allocation failed */
- LDR_NOENT, /* Module file does not exist */
- LDR_NOSUBENT, /* pre-requsite file to be sub-loaded does not exist */
- LDR_NOSPACE, /* internal module array full */
- LDR_NOMODOPEN, /* module file could not be opened (check errmin) */
- LDR_UNKTYPE, /* file is not a recognized module type */
- LDR_NOLOAD, /* type specific loader failed */
- LDR_ONCEONLY, /* Module should only be loaded once (not an error) */
- LDR_NOPORTOPEN, /* could not open port (check errmin) */
- LDR_NOHARDWARE, /* could not query/initialize the hardware device */
- LDR_MISMATCH, /* the module didn't match the spec'd requirments */
- LDR_BADUSAGE, /* LoadModule is called with bad arguments */
- LDR_INVALID, /* The module doesn't have a valid ModuleData object */
- LDR_BADOS, /* The module doesn't support the OS */
- LDR_MODSPECIFIC /* A module-specific error in the SetupProc */
-} LoaderErrorCode;
-
-/*
- * Some common module classes. The moduleclass can be used to identify
- * that modules loaded are of the correct type. This is a finer
- * classification than the ABI classes even though the default set of
- * classes have the same names. For example, not all modules that require
- * the video driver ABI are themselves video drivers.
- */
-#define MOD_CLASS_NONE NULL
-#define MOD_CLASS_VIDEODRV "X.Org Video Driver"
-#define MOD_CLASS_XINPUT "X.Org XInput Driver"
-#define MOD_CLASS_FONT "X.Org Font Renderer"
-#define MOD_CLASS_EXTENSION "X.Org Server Extension"
-
-/* This structure is expected to be returned by the initfunc */
-typedef struct {
- const char * modname; /* name of module, e.g. "foo" */
- const char * vendor; /* vendor specific string */
- CARD32 _modinfo1_; /* constant MODINFOSTRING1/2 to find */
- CARD32 _modinfo2_; /* infoarea with a binary editor or sign tool */
- CARD32 xf86version; /* contains XF86_VERSION_CURRENT */
- CARD8 majorversion; /* module-specific major version */
- CARD8 minorversion; /* module-specific minor version */
- CARD16 patchlevel; /* module-specific patch level */
- const char * abiclass; /* ABI class that the module uses */
- CARD32 abiversion; /* ABI version */
- const char * moduleclass; /* module class description */
- CARD32 checksum[4]; /* contains a digital signature of the */
- /* version info structure */
-} XF86ModuleVersionInfo;
-
-/*
- * This structure can be used to callers of LoadModule and LoadSubModule to
- * specify version and/or ABI requirements.
- */
-typedef struct {
- CARD8 majorversion; /* module-specific major version */
- CARD8 minorversion; /* moudle-specific minor version */
- CARD16 patchlevel; /* module-specific patch level */
- const char * abiclass; /* ABI class that the module uses */
- CARD32 abiversion; /* ABI version */
- const char * moduleclass; /* module class */
-} XF86ModReqInfo;
-
-/* values to indicate unspecified fields in XF86ModReqInfo. */
-#define MAJOR_UNSPEC 0xFF
-#define MINOR_UNSPEC 0xFF
-#define PATCH_UNSPEC 0xFFFF
-#define ABI_VERS_UNSPEC 0xFFFFFFFF
-
-#define MODULE_VERSION_NUMERIC(maj, min, patch) \
- ((((maj) & 0xFF) << 24) | (((min) & 0xFF) << 16) | (patch & 0xFFFF))
-#define GET_MODULE_MAJOR_VERSION(vers) (((vers) >> 24) & 0xFF)
-#define GET_MODULE_MINOR_VERSION(vers) (((vers) >> 16) & 0xFF)
-#define GET_MODULE_PATCHLEVEL(vers) ((vers) & 0xFFFF)
-
-#define INITARGS void
-
-typedef void (*InitExtension)(INITARGS);
-
-typedef struct {
- InitExtension initFunc;
- const char * name;
- Bool *disablePtr;
- InitExtension setupFunc;
- const char ** initDependencies;
-} ExtensionModule;
-
-extern _X_EXPORT ExtensionModule *ExtensionModuleList;
-
-/* Prototypes for Loader functions that are exported to modules */
-extern _X_EXPORT pointer LoadSubModule(pointer, const char *, const char **,
- const char **, pointer, const XF86ModReqInfo *,
- int *, int *);
-extern _X_EXPORT void UnloadSubModule(pointer);
-extern _X_EXPORT void UnloadModule (pointer);
-extern _X_EXPORT pointer LoaderSymbol(const char *);
-extern _X_EXPORT char **LoaderListDirs(const char **, const char **);
-extern _X_EXPORT void LoaderFreeDirList(char **);
-extern _X_EXPORT void LoaderErrorMsg(const char *, const char *, int, int);
-extern _X_EXPORT void LoadExtension(ExtensionModule *, Bool);
-extern _X_EXPORT void LoaderGetOS(const char **name, int *major, int *minor, int *teeny);
-extern _X_EXPORT Bool LoaderShouldIgnoreABI(void);
-extern _X_EXPORT int LoaderGetABIVersion(const char *abiclass);
-
-typedef pointer (*ModuleSetupProc)(pointer, pointer, int *, int *);
-typedef void (*ModuleTearDownProc)(pointer);
-#define MODULESETUPPROTO(func) pointer func(pointer, pointer, int*, int*)
-#define MODULETEARDOWNPROTO(func) void func(pointer)
-
-typedef struct {
- XF86ModuleVersionInfo * vers;
- ModuleSetupProc setup;
- ModuleTearDownProc teardown;
-} XF86ModuleData;
-
-#endif /* _XF86STR_H */
+/* + * Copyright (c) 1997-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* + * This file contains the parts of the loader interface that are visible + * to modules. This is the only loader-related header that modules should + * include. + * + * It should include a bare minimum of other headers. + * + * Longer term, the module/loader code should probably live directly under + * Xserver/. + * + * XXX This file arguably belongs in xfree86/loader/. + */ + +#ifndef _XF86MODULE_H +#define _XF86MODULE_H + +#include "misc.h" +#ifndef NULL +#define NULL ((void *)0) +#endif + +typedef enum { + LD_RESOLV_IFDONE = 0, /* only check if no more + delays pending */ + LD_RESOLV_NOW = 1, /* finish one delay step */ + LD_RESOLV_FORCE = 2 /* force checking... */ +} LoaderResolveOptions; + +#define DEFAULT_LIST ((char *)-1) + +/* This indicates a special module that doesn't have the usual entry point */ +#define EXTERN_MODULE ((pointer)-1) + +/* Built-in ABI classes. These definitions must not be changed. */ +#define ABI_CLASS_NONE NULL +#define ABI_CLASS_ANSIC "X.Org ANSI C Emulation" +#define ABI_CLASS_VIDEODRV "X.Org Video Driver" +#define ABI_CLASS_XINPUT "X.Org XInput driver" +#define ABI_CLASS_EXTENSION "X.Org Server Extension" +#define ABI_CLASS_FONT "X.Org Font Renderer" + +#define ABI_MINOR_MASK 0x0000FFFF +#define ABI_MAJOR_MASK 0xFFFF0000 +#define GET_ABI_MINOR(v) ((v) & ABI_MINOR_MASK) +#define GET_ABI_MAJOR(v) (((v) & ABI_MAJOR_MASK) >> 16) +#define SET_ABI_VERSION(maj, min) \ + ((((maj) << 16) & ABI_MAJOR_MASK) | ((min) & ABI_MINOR_MASK)) + +/* + * ABI versions. Each version has a major and minor revision. Modules + * using lower minor revisions must work with servers of a higher minor + * revision. There is no compatibility between different major revisions. + * Whenever the ABI_ANSIC_VERSION is changed, the others must also be + * changed. The minor revision mask is 0x0000FFFF and the major revision + * mask is 0xFFFF0000. + */ +#define ABI_ANSIC_VERSION SET_ABI_VERSION(0, 4) +#define ABI_VIDEODRV_VERSION SET_ABI_VERSION(11, 0) +#define ABI_XINPUT_VERSION SET_ABI_VERSION(13, 0) +#define ABI_EXTENSION_VERSION SET_ABI_VERSION(5, 0) +#define ABI_FONT_VERSION SET_ABI_VERSION(0, 6) + +#define MODINFOSTRING1 0xef23fdc5 +#define MODINFOSTRING2 0x10dc023a + +#ifndef MODULEVENDORSTRING +#define MODULEVENDORSTRING "X.Org Foundation" +#endif + +/* Error return codes for errmaj. New codes must only be added at the end. */ +typedef enum { + LDR_NOERROR = 0, + LDR_NOMEM, /* memory allocation failed */ + LDR_NOENT, /* Module file does not exist */ + LDR_NOSUBENT, /* pre-requsite file to be sub-loaded does not exist */ + LDR_NOSPACE, /* internal module array full */ + LDR_NOMODOPEN, /* module file could not be opened (check errmin) */ + LDR_UNKTYPE, /* file is not a recognized module type */ + LDR_NOLOAD, /* type specific loader failed */ + LDR_ONCEONLY, /* Module should only be loaded once (not an error) */ + LDR_NOPORTOPEN, /* could not open port (check errmin) */ + LDR_NOHARDWARE, /* could not query/initialize the hardware device */ + LDR_MISMATCH, /* the module didn't match the spec'd requirments */ + LDR_BADUSAGE, /* LoadModule is called with bad arguments */ + LDR_INVALID, /* The module doesn't have a valid ModuleData object */ + LDR_BADOS, /* The module doesn't support the OS */ + LDR_MODSPECIFIC /* A module-specific error in the SetupProc */ +} LoaderErrorCode; + +/* + * Some common module classes. The moduleclass can be used to identify + * that modules loaded are of the correct type. This is a finer + * classification than the ABI classes even though the default set of + * classes have the same names. For example, not all modules that require + * the video driver ABI are themselves video drivers. + */ +#define MOD_CLASS_NONE NULL +#define MOD_CLASS_VIDEODRV "X.Org Video Driver" +#define MOD_CLASS_XINPUT "X.Org XInput Driver" +#define MOD_CLASS_FONT "X.Org Font Renderer" +#define MOD_CLASS_EXTENSION "X.Org Server Extension" + +/* This structure is expected to be returned by the initfunc */ +typedef struct { + const char * modname; /* name of module, e.g. "foo" */ + const char * vendor; /* vendor specific string */ + CARD32 _modinfo1_; /* constant MODINFOSTRING1/2 to find */ + CARD32 _modinfo2_; /* infoarea with a binary editor or sign tool */ + CARD32 xf86version; /* contains XF86_VERSION_CURRENT */ + CARD8 majorversion; /* module-specific major version */ + CARD8 minorversion; /* module-specific minor version */ + CARD16 patchlevel; /* module-specific patch level */ + const char * abiclass; /* ABI class that the module uses */ + CARD32 abiversion; /* ABI version */ + const char * moduleclass; /* module class description */ + CARD32 checksum[4]; /* contains a digital signature of the */ + /* version info structure */ +} XF86ModuleVersionInfo; + +/* + * This structure can be used to callers of LoadModule and LoadSubModule to + * specify version and/or ABI requirements. + */ +typedef struct { + CARD8 majorversion; /* module-specific major version */ + CARD8 minorversion; /* moudle-specific minor version */ + CARD16 patchlevel; /* module-specific patch level */ + const char * abiclass; /* ABI class that the module uses */ + CARD32 abiversion; /* ABI version */ + const char * moduleclass; /* module class */ +} XF86ModReqInfo; + +/* values to indicate unspecified fields in XF86ModReqInfo. */ +#define MAJOR_UNSPEC 0xFF +#define MINOR_UNSPEC 0xFF +#define PATCH_UNSPEC 0xFFFF +#define ABI_VERS_UNSPEC 0xFFFFFFFF + +#define MODULE_VERSION_NUMERIC(maj, min, patch) \ + ((((maj) & 0xFF) << 24) | (((min) & 0xFF) << 16) | (patch & 0xFFFF)) +#define GET_MODULE_MAJOR_VERSION(vers) (((vers) >> 24) & 0xFF) +#define GET_MODULE_MINOR_VERSION(vers) (((vers) >> 16) & 0xFF) +#define GET_MODULE_PATCHLEVEL(vers) ((vers) & 0xFFFF) + +#define INITARGS void + +typedef void (*InitExtension)(INITARGS); + +typedef struct { + InitExtension initFunc; + const char * name; + Bool *disablePtr; + InitExtension setupFunc; + const char ** initDependencies; +} ExtensionModule; + +extern _X_EXPORT ExtensionModule *ExtensionModuleList; + +/* Prototypes for Loader functions that are exported to modules */ +extern _X_EXPORT pointer LoadSubModule(pointer, const char *, const char **, + const char **, pointer, const XF86ModReqInfo *, + int *, int *); +extern _X_EXPORT void UnloadSubModule(pointer); +extern _X_EXPORT void UnloadModule (pointer); +extern _X_EXPORT pointer LoaderSymbol(const char *); +extern _X_EXPORT char **LoaderListDirs(const char **, const char **); +extern _X_EXPORT void LoaderFreeDirList(char **); +extern _X_EXPORT void LoaderErrorMsg(const char *, const char *, int, int); +extern _X_EXPORT void LoadExtension(ExtensionModule *, Bool); +extern _X_EXPORT void LoaderGetOS(const char **name, int *major, int *minor, int *teeny); +extern _X_EXPORT Bool LoaderShouldIgnoreABI(void); +extern _X_EXPORT int LoaderGetABIVersion(const char *abiclass); + +typedef pointer (*ModuleSetupProc)(pointer, pointer, int *, int *); +typedef void (*ModuleTearDownProc)(pointer); +#define MODULESETUPPROTO(func) pointer func(pointer, pointer, int*, int*) +#define MODULETEARDOWNPROTO(func) void func(pointer) + +typedef struct { + XF86ModuleVersionInfo * vers; + ModuleSetupProc setup; + ModuleTearDownProc teardown; +} XF86ModuleData; + +#endif /* _XF86STR_H */ diff --git a/xorg-server/hw/xfree86/common/xf86Option.c b/xorg-server/hw/xfree86/common/xf86Option.c index 576796d6c..a3a836fc1 100644 --- a/xorg-server/hw/xfree86/common/xf86Option.c +++ b/xorg-server/hw/xfree86/common/xf86Option.c @@ -1,916 +1,916 @@ -/*
- * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/*
- * Author: David Dawes <dawes@xfree86.org>
- *
- * This file includes public option handling functions.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <stdlib.h>
-#include <ctype.h>
-#include <X11/X.h>
-#include "os.h"
-#include "xf86.h"
-#include "xf86Xinput.h"
-#include "xf86Optrec.h"
-#include "xf86Parser.h"
-
-static Bool ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p,
- Bool markUsed);
-
-/*
- * xf86CollectOptions collects the options from each of the config file
- * sections used by the screen and puts the combined list in pScrn->options.
- * This function requires that the following have been initialised:
- *
- * pScrn->confScreen
- * pScrn->Entities[i]->device
- * pScrn->display
- * pScrn->monitor
- *
- * The extraOpts parameter may optionally contain a list of additional options
- * to include.
- *
- * The order of precedence for options is:
- *
- * extraOpts, display, confScreen, monitor, device
- */
-
-void
-xf86CollectOptions(ScrnInfoPtr pScrn, pointer extraOpts)
-{
- XF86OptionPtr tmp;
- XF86OptionPtr extras = (XF86OptionPtr)extraOpts;
- GDevPtr device;
-
- int i;
-
- pScrn->options = NULL;
-
- for (i=pScrn->numEntities - 1; i >= 0; i--) {
- device = xf86GetDevFromEntity(pScrn->entityList[i],
- pScrn->entityInstanceList[i]);
- if (device && device->options) {
- tmp = xf86optionListDup(device->options);
- if (pScrn->options)
- xf86optionListMerge(pScrn->options,tmp);
- else
- pScrn->options = tmp;
- }
- }
- if (pScrn->monitor->options) {
- tmp = xf86optionListDup(pScrn->monitor->options);
- if (pScrn->options)
- pScrn->options = xf86optionListMerge(pScrn->options, tmp);
- else
- pScrn->options = tmp;
- }
- if (pScrn->confScreen->options) {
- tmp = xf86optionListDup(pScrn->confScreen->options);
- if (pScrn->options)
- pScrn->options = xf86optionListMerge(pScrn->options, tmp);
- else
- pScrn->options = tmp;
- }
- if (pScrn->display->options) {
- tmp = xf86optionListDup(pScrn->display->options);
- if (pScrn->options)
- pScrn->options = xf86optionListMerge(pScrn->options, tmp);
- else
- pScrn->options = tmp;
- }
- if (extras) {
- tmp = xf86optionListDup(extras);
- if (pScrn->options)
- pScrn->options = xf86optionListMerge(pScrn->options, tmp);
- else
- pScrn->options = tmp;
- }
-}
-
-/*
- * xf86CollectInputOptions collects extra options for an InputDevice (other
- * than those added by the config backend).
- * The options are merged into the existing ones and thus take precedence
- * over the others.
- */
-
-void
-xf86CollectInputOptions(InputInfoPtr pInfo, const char **defaultOpts)
-{
- if (defaultOpts) {
- XF86OptionPtr tmp =xf86optionListCreate(defaultOpts, -1, 0);
- if (pInfo->options)
- pInfo->options = xf86optionListMerge(tmp, pInfo->options);
- else
- pInfo->options = tmp;
- }
-}
-
-/**
- * Duplicate the option list passed in. The returned pointer will be a newly
- * allocated option list and must be freed by the caller.
- */
-pointer
-xf86OptionListDuplicate(pointer options)
-{
- pointer o = NULL;
-
- while (options)
- {
- o = xf86AddNewOption(o, xf86OptionName(options), xf86OptionValue(options));
- options = xf86nextOption(options);
- }
-
- return o;
-}
-
-
-/* Created for new XInput stuff -- essentially extensions to the parser */
-
-static int
-LookupIntOption(pointer optlist, const char *name, int deflt, Bool markUsed)
-{
- OptionInfoRec o;
-
- o.name = name;
- o.type = OPTV_INTEGER;
- if (ParseOptionValue(-1, optlist, &o, markUsed))
- deflt = o.value.num;
- return deflt;
-}
-
-
-static double
-LookupRealOption(pointer optlist, const char *name, double deflt,
- Bool markUsed)
-{
- OptionInfoRec o;
-
- o.name = name;
- o.type = OPTV_REAL;
- if (ParseOptionValue(-1, optlist, &o, markUsed))
- deflt = o.value.realnum;
- return deflt;
-}
-
-
-static char *
-LookupStrOption(pointer optlist, const char *name, char *deflt, Bool markUsed)
-{
- OptionInfoRec o;
-
- o.name = name;
- o.type = OPTV_STRING;
- if (ParseOptionValue(-1, optlist, &o, markUsed))
- deflt = o.value.str;
- if (deflt)
- return strdup(deflt);
- else
- return NULL;
-}
-
-
-static int
-LookupBoolOption(pointer optlist, const char *name, int deflt, Bool markUsed)
-{
- OptionInfoRec o;
-
- o.name = name;
- o.type = OPTV_BOOLEAN;
- if (ParseOptionValue(-1, optlist, &o, markUsed))
- deflt = o.value.bool;
- return deflt;
-}
-
-static double
-LookupPercentOption(pointer optlist, const char *name, double deflt, Bool markUsed)
-{
- OptionInfoRec o;
-
- o.name = name;
- o.type = OPTV_PERCENT;
- if (ParseOptionValue(-1, optlist, &o, markUsed))
- deflt = o.value.realnum;
- return deflt;
-}
-
-/* These xf86Set* functions are intended for use by non-screen specific code */
-
-int
-xf86SetIntOption(pointer optlist, const char *name, int deflt)
-{
- return LookupIntOption(optlist, name, deflt, TRUE);
-}
-
-
-double
-xf86SetRealOption(pointer optlist, const char *name, double deflt)
-{
- return LookupRealOption(optlist, name, deflt, TRUE);
-}
-
-
-char *
-xf86SetStrOption(pointer optlist, const char *name, char *deflt)
-{
- return LookupStrOption(optlist, name, deflt, TRUE);
-}
-
-
-int
-xf86SetBoolOption(pointer optlist, const char *name, int deflt)
-{
- return LookupBoolOption(optlist, name, deflt, TRUE);
-}
-
-double
-xf86SetPercentOption(pointer optlist, const char *name, double deflt)
-{
- return LookupPercentOption(optlist, name, deflt, TRUE);
-}
-
-/*
- * These are like the Set*Option functions, but they don't mark the options
- * as used.
- */
-int
-xf86CheckIntOption(pointer optlist, const char *name, int deflt)
-{
- return LookupIntOption(optlist, name, deflt, FALSE);
-}
-
-
-double
-xf86CheckRealOption(pointer optlist, const char *name, double deflt)
-{
- return LookupRealOption(optlist, name, deflt, FALSE);
-}
-
-
-char *
-xf86CheckStrOption(pointer optlist, const char *name, char *deflt)
-{
- return LookupStrOption(optlist, name, deflt, FALSE);
-}
-
-
-int
-xf86CheckBoolOption(pointer optlist, const char *name, int deflt)
-{
- return LookupBoolOption(optlist, name, deflt, FALSE);
-}
-
-
-double
-xf86CheckPercentOption(pointer optlist, const char *name, double deflt)
-{
- return LookupPercentOption(optlist, name, deflt, FALSE);
-}
-/*
- * addNewOption() has the required property of replacing the option value
- * if the option is already present.
- */
-pointer
-xf86ReplaceIntOption(pointer optlist, const char *name, const int val)
-{
- char tmp[16];
- sprintf(tmp,"%i",val);
- return xf86AddNewOption(optlist,name,tmp);
-}
-
-pointer
-xf86ReplaceRealOption(pointer optlist, const char *name, const double val)
-{
- char tmp[32];
- snprintf(tmp,32,"%f",val);
- return xf86AddNewOption(optlist,name,tmp);
-}
-
-pointer
-xf86ReplaceBoolOption(pointer optlist, const char *name, const Bool val)
-{
- return xf86AddNewOption(optlist,name,val?"True":"False");
-}
-
-pointer
-xf86ReplacePercentOption(pointer optlist, const char *name, const double val)
-{
- char tmp[16];
- sprintf(tmp, "%lf%%", val);
- return xf86AddNewOption(optlist,name,tmp);
-}
-
-pointer
-xf86ReplaceStrOption(pointer optlist, const char *name, const char* val)
-{
- return xf86AddNewOption(optlist,name,val);
-}
-
-pointer
-xf86AddNewOption(pointer head, const char *name, const char *val)
-{
- /* XXX These should actually be allocated in the parser library. */
- char *tmp = val ? strdup(val) : NULL;
- char *tmp_name = strdup(name);
-
- return xf86addNewOption(head, tmp_name, tmp);
-}
-
-
-pointer
-xf86NewOption(char *name, char *value)
-{
- return xf86newOption(name, value);
-}
-
-
-pointer
-xf86NextOption(pointer list)
-{
- return xf86nextOption(list);
-}
-
-pointer
-xf86OptionListCreate(const char **options, int count, int used)
-{
- return xf86optionListCreate(options, count, used);
-}
-
-pointer
-xf86OptionListMerge(pointer head, pointer tail)
-{
- return xf86optionListMerge(head, tail);
-}
-
-void
-xf86OptionListFree(pointer opt)
-{
- xf86optionListFree(opt);
-}
-
-char *
-xf86OptionName(pointer opt)
-{
- return xf86optionName(opt);
-}
-
-char *
-xf86OptionValue(pointer opt)
-{
- return xf86optionValue(opt);
-}
-
-void
-xf86OptionListReport(pointer parm)
-{
- XF86OptionPtr opts = parm;
-
- while(opts) {
- if (xf86optionValue(opts))
- xf86ErrorFVerb(5, "\tOption \"%s\" \"%s\"\n",
- xf86optionName(opts), xf86optionValue(opts));
- else
- xf86ErrorFVerb( 5, "\tOption \"%s\"\n", xf86optionName(opts));
- opts = xf86nextOption(opts);
- }
-}
-
-/* End of XInput-caused section */
-
-pointer
-xf86FindOption(pointer options, const char *name)
-{
- return xf86findOption(options, name);
-}
-
-
-char *
-xf86FindOptionValue(pointer options, const char *name)
-{
- return xf86findOptionValue(options, name);
-}
-
-
-void
-xf86MarkOptionUsed(pointer option)
-{
- if (option != NULL)
- ((XF86OptionPtr)option)->opt_used = TRUE;
-}
-
-
-void
-xf86MarkOptionUsedByName(pointer options, const char *name)
-{
- XF86OptionPtr opt;
-
- opt = xf86findOption(options, name);
- if (opt != NULL)
- opt->opt_used = TRUE;
-}
-
-Bool
-xf86CheckIfOptionUsed(pointer option)
-{
- if (option != NULL)
- return ((XF86OptionPtr)option)->opt_used;
- else
- return FALSE;
-}
-
-Bool
-xf86CheckIfOptionUsedByName(pointer options, const char *name)
-{
- XF86OptionPtr opt;
-
- opt = xf86findOption(options, name);
- if (opt != NULL)
- return opt->opt_used;
- else
- return FALSE;
-}
-
-void
-xf86ShowUnusedOptions(int scrnIndex, pointer options)
-{
- XF86OptionPtr opt = options;
-
- while (opt) {
- if (opt->opt_name && !opt->opt_used) {
- xf86DrvMsg(scrnIndex, X_WARNING, "Option \"%s\" is not used\n",
- opt->opt_name);
- }
- opt = opt->list.next;
- }
-}
-
-
-static Bool
-GetBoolValue(OptionInfoPtr p, const char *s)
-{
- return xf86getBoolValue(&p->value.bool, s);
-}
-
-static Bool
-ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p,
- Bool markUsed)
-{
- char *s, *end;
- Bool wasUsed = FALSE;
-
- if ((s = xf86findOptionValue(options, p->name)) != NULL) {
- if (markUsed) {
- wasUsed = xf86CheckIfOptionUsedByName(options, p->name);
- xf86MarkOptionUsedByName(options, p->name);
- }
- switch (p->type) {
- case OPTV_INTEGER:
- if (*s == '\0') {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires an integer value\n",
- p->name);
- }
- p->found = FALSE;
- } else {
- p->value.num = strtoul(s, &end, 0);
- if (*end == '\0') {
- p->found = TRUE;
- } else {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires an integer value\n",
- p->name);
- }
- p->found = FALSE;
- }
- }
- break;
- case OPTV_STRING:
- if (*s == '\0') {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires an string value\n",
- p->name);
- }
- p->found = FALSE;
- } else {
- p->value.str = s;
- p->found = TRUE;
- }
- break;
- case OPTV_ANYSTR:
- p->value.str = s;
- p->found = TRUE;
- break;
- case OPTV_REAL:
- if (*s == '\0') {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a floating point "
- "value\n", p->name);
- }
- p->found = FALSE;
- } else {
- p->value.realnum = strtod(s, &end);
- if (*end == '\0') {
- p->found = TRUE;
- } else {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a floating point "
- "value\n", p->name);
- }
- p->found = FALSE;
- }
- }
- break;
- case OPTV_BOOLEAN:
- if (GetBoolValue(p, s)) {
- p->found = TRUE;
- } else {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a boolean value\n",
- p->name);
- }
- p->found = FALSE;
- }
- break;
- case OPTV_PERCENT:
- {
- char tmp = 0;
- /* awkward match, but %% doesn't increase the match counter,
- * hence 100 looks the same as 100% to the caller of sccanf
- */
- if (sscanf(s, "%lf%c", &p->value.realnum, &tmp) != 2 || tmp != '%') {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a percent value\n", p->name);
- }
- p->found = FALSE;
- } else {
- p->found = TRUE;
- }
- }
- break;
- case OPTV_FREQ:
- if (*s == '\0') {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a frequency value\n",
- p->name);
- }
- p->found = FALSE;
- } else {
- double freq = strtod(s, &end);
- int units = 0;
-
- if (end != s) {
- p->found = TRUE;
- if (!xf86NameCmp(end, "Hz"))
- units = 1;
- else if (!xf86NameCmp(end, "kHz") ||
- !xf86NameCmp(end, "k"))
- units = 1000;
- else if (!xf86NameCmp(end, "MHz") ||
- !xf86NameCmp(end, "M"))
- units = 1000000;
- else {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a frequency value\n",
- p->name);
- }
- p->found = FALSE;
- }
- if (p->found)
- freq *= (double)units;
- } else {
- if (markUsed) {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a frequency value\n",
- p->name);
- }
- p->found = FALSE;
- }
- if (p->found) {
- p->value.freq.freq = freq;
- p->value.freq.units = units;
- }
- }
- break;
- case OPTV_NONE:
- /* Should never get here */
- p->found = FALSE;
- break;
- }
- if (p->found && markUsed) {
- int verb = 2;
- if (wasUsed)
- verb = 4;
- xf86DrvMsgVerb(scrnIndex, X_CONFIG, verb, "Option \"%s\"", p->name);
- if (!(p->type == OPTV_BOOLEAN && *s == 0)) {
- xf86ErrorFVerb(verb, " \"%s\"", s);
- }
- xf86ErrorFVerb(verb, "\n");
- }
- } else if (p->type == OPTV_BOOLEAN) {
- /* Look for matches with options with or without a "No" prefix. */
- char *n, *newn;
- OptionInfoRec opt;
-
- n = xf86NormalizeName(p->name);
- if (!n) {
- p->found = FALSE;
- return FALSE;
- }
- if (strncmp(n, "no", 2) == 0) {
- newn = n + 2;
- } else {
- free(n);
- if (asprintf(&n, "No%s", p->name) == -1) {
- p->found = FALSE;
- return FALSE;
- }
- newn = n;
- }
- if ((s = xf86findOptionValue(options, newn)) != NULL) {
- if (markUsed)
- xf86MarkOptionUsedByName(options, newn);
- if (GetBoolValue(&opt, s)) {
- p->value.bool = !opt.value.bool;
- p->found = TRUE;
- } else {
- xf86DrvMsg(scrnIndex, X_WARNING,
- "Option \"%s\" requires a boolean value\n", newn);
- p->found = FALSE;
- }
- } else {
- p->found = FALSE;
- }
- if (p->found && markUsed) {
- xf86DrvMsgVerb(scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn);
- if (*s != 0) {
- xf86ErrorFVerb(2, " \"%s\"", s);
- }
- xf86ErrorFVerb(2, "\n");
- }
- free(n);
- } else {
- p->found = FALSE;
- }
- return p->found;
-}
-
-
-void
-xf86ProcessOptions(int scrnIndex, pointer options, OptionInfoPtr optinfo)
-{
- OptionInfoPtr p;
-
- for (p = optinfo; p->name != NULL; p++) {
- ParseOptionValue(scrnIndex, options, p, TRUE);
- }
-}
-
-
-OptionInfoPtr
-xf86TokenToOptinfo(const OptionInfoRec *table, int token)
-{
- const OptionInfoRec *p, *match = NULL, *set = NULL;
-
- if (!table) {
- ErrorF("xf86TokenToOptinfo: table is NULL\n");
- return NULL;
- }
-
- for (p = table; p->token >= 0; p++) {
- if (p->token == token) {
- match = p;
- if (p->found)
- set = p;
- }
- }
-
- if (set)
- return (OptionInfoPtr)set;
- else if (match)
- return (OptionInfoPtr)match;
- else
- return NULL;
-}
-
-
-const char *
-xf86TokenToOptName(const OptionInfoRec *table, int token)
-{
- const OptionInfoRec *p;
-
- p = xf86TokenToOptinfo(table, token);
- return p->name;
-}
-
-
-Bool
-xf86IsOptionSet(const OptionInfoRec *table, int token)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- return p && p->found;
-}
-
-
-char *
-xf86GetOptValString(const OptionInfoRec *table, int token)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found)
- return p->value.str;
- else
- return NULL;
-}
-
-
-Bool
-xf86GetOptValInteger(const OptionInfoRec *table, int token, int *value)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- *value = p->value.num;
- return TRUE;
- } else
- return FALSE;
-}
-
-
-Bool
-xf86GetOptValULong(const OptionInfoRec *table, int token, unsigned long *value)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- *value = p->value.num;
- return TRUE;
- } else
- return FALSE;
-}
-
-
-Bool
-xf86GetOptValReal(const OptionInfoRec *table, int token, double *value)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- *value = p->value.realnum;
- return TRUE;
- } else
- return FALSE;
-}
-
-
-Bool
-xf86GetOptValFreq(const OptionInfoRec *table, int token,
- OptFreqUnits expectedUnits, double *value)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- if (p->value.freq.units > 0) {
- /* Units give, so the scaling is known. */
- switch (expectedUnits) {
- case OPTUNITS_HZ:
- *value = p->value.freq.freq;
- break;
- case OPTUNITS_KHZ:
- *value = p->value.freq.freq / 1000.0;
- break;
- case OPTUNITS_MHZ:
- *value = p->value.freq.freq / 1000000.0;
- break;
- }
- } else {
- /* No units given, so try to guess the scaling. */
- switch (expectedUnits) {
- case OPTUNITS_HZ:
- *value = p->value.freq.freq;
- break;
- case OPTUNITS_KHZ:
- if (p->value.freq.freq > 1000.0)
- *value = p->value.freq.freq / 1000.0;
- else
- *value = p->value.freq.freq;
- break;
- case OPTUNITS_MHZ:
- if (p->value.freq.freq > 1000000.0)
- *value = p->value.freq.freq / 1000000.0;
- else if (p->value.freq.freq > 1000.0)
- *value = p->value.freq.freq / 1000.0;
- else
- *value = p->value.freq.freq;
- }
- }
- return TRUE;
- } else
- return FALSE;
-}
-
-
-Bool
-xf86GetOptValBool(const OptionInfoRec *table, int token, Bool *value)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- *value = p->value.bool;
- return TRUE;
- } else
- return FALSE;
-}
-
-
-Bool
-xf86ReturnOptValBool(const OptionInfoRec *table, int token, Bool def)
-{
- OptionInfoPtr p;
-
- p = xf86TokenToOptinfo(table, token);
- if (p && p->found) {
- return p->value.bool;
- } else
- return def;
-}
-
-
-int
-xf86NameCmp(const char *s1, const char *s2)
-{
- return xf86nameCompare(s1, s2);
-}
-
-char *
-xf86NormalizeName(const char *s)
-{
- char *ret, *q;
- const char *p;
-
- if (s == NULL)
- return NULL;
-
- ret = malloc(strlen(s) + 1);
- for (p = s, q = ret; *p != 0; p++) {
- switch (*p) {
- case '_':
- case ' ':
- case '\t':
- continue;
- default:
- if (isupper(*p))
- *q++ = tolower(*p);
- else
- *q++ = *p;
- }
- }
- *q = '\0';
- return ret;
-}
+/* + * Copyright (c) 1998-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* + * Author: David Dawes <dawes@xfree86.org> + * + * This file includes public option handling functions. + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <stdlib.h> +#include <ctype.h> +#include <X11/X.h> +#include "os.h" +#include "xf86.h" +#include "xf86Xinput.h" +#include "xf86Optrec.h" +#include "xf86Parser.h" + +static Bool ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p, + Bool markUsed); + +/* + * xf86CollectOptions collects the options from each of the config file + * sections used by the screen and puts the combined list in pScrn->options. + * This function requires that the following have been initialised: + * + * pScrn->confScreen + * pScrn->Entities[i]->device + * pScrn->display + * pScrn->monitor + * + * The extraOpts parameter may optionally contain a list of additional options + * to include. + * + * The order of precedence for options is: + * + * extraOpts, display, confScreen, monitor, device + */ + +void +xf86CollectOptions(ScrnInfoPtr pScrn, pointer extraOpts) +{ + XF86OptionPtr tmp; + XF86OptionPtr extras = (XF86OptionPtr)extraOpts; + GDevPtr device; + + int i; + + pScrn->options = NULL; + + for (i=pScrn->numEntities - 1; i >= 0; i--) { + device = xf86GetDevFromEntity(pScrn->entityList[i], + pScrn->entityInstanceList[i]); + if (device && device->options) { + tmp = xf86optionListDup(device->options); + if (pScrn->options) + xf86optionListMerge(pScrn->options,tmp); + else + pScrn->options = tmp; + } + } + if (pScrn->monitor->options) { + tmp = xf86optionListDup(pScrn->monitor->options); + if (pScrn->options) + pScrn->options = xf86optionListMerge(pScrn->options, tmp); + else + pScrn->options = tmp; + } + if (pScrn->confScreen->options) { + tmp = xf86optionListDup(pScrn->confScreen->options); + if (pScrn->options) + pScrn->options = xf86optionListMerge(pScrn->options, tmp); + else + pScrn->options = tmp; + } + if (pScrn->display->options) { + tmp = xf86optionListDup(pScrn->display->options); + if (pScrn->options) + pScrn->options = xf86optionListMerge(pScrn->options, tmp); + else + pScrn->options = tmp; + } + if (extras) { + tmp = xf86optionListDup(extras); + if (pScrn->options) + pScrn->options = xf86optionListMerge(pScrn->options, tmp); + else + pScrn->options = tmp; + } +} + +/* + * xf86CollectInputOptions collects extra options for an InputDevice (other + * than those added by the config backend). + * The options are merged into the existing ones and thus take precedence + * over the others. + */ + +void +xf86CollectInputOptions(InputInfoPtr pInfo, const char **defaultOpts) +{ + if (defaultOpts) { + XF86OptionPtr tmp =xf86optionListCreate(defaultOpts, -1, 0); + if (pInfo->options) + pInfo->options = xf86optionListMerge(tmp, pInfo->options); + else + pInfo->options = tmp; + } +} + +/** + * Duplicate the option list passed in. The returned pointer will be a newly + * allocated option list and must be freed by the caller. + */ +pointer +xf86OptionListDuplicate(pointer options) +{ + pointer o = NULL; + + while (options) + { + o = xf86AddNewOption(o, xf86OptionName(options), xf86OptionValue(options)); + options = xf86nextOption(options); + } + + return o; +} + + +/* Created for new XInput stuff -- essentially extensions to the parser */ + +static int +LookupIntOption(pointer optlist, const char *name, int deflt, Bool markUsed) +{ + OptionInfoRec o; + + o.name = name; + o.type = OPTV_INTEGER; + if (ParseOptionValue(-1, optlist, &o, markUsed)) + deflt = o.value.num; + return deflt; +} + + +static double +LookupRealOption(pointer optlist, const char *name, double deflt, + Bool markUsed) +{ + OptionInfoRec o; + + o.name = name; + o.type = OPTV_REAL; + if (ParseOptionValue(-1, optlist, &o, markUsed)) + deflt = o.value.realnum; + return deflt; +} + + +static char * +LookupStrOption(pointer optlist, const char *name, char *deflt, Bool markUsed) +{ + OptionInfoRec o; + + o.name = name; + o.type = OPTV_STRING; + if (ParseOptionValue(-1, optlist, &o, markUsed)) + deflt = o.value.str; + if (deflt) + return strdup(deflt); + else + return NULL; +} + + +static int +LookupBoolOption(pointer optlist, const char *name, int deflt, Bool markUsed) +{ + OptionInfoRec o; + + o.name = name; + o.type = OPTV_BOOLEAN; + if (ParseOptionValue(-1, optlist, &o, markUsed)) + deflt = o.value.bool; + return deflt; +} + +static double +LookupPercentOption(pointer optlist, const char *name, double deflt, Bool markUsed) +{ + OptionInfoRec o; + + o.name = name; + o.type = OPTV_PERCENT; + if (ParseOptionValue(-1, optlist, &o, markUsed)) + deflt = o.value.realnum; + return deflt; +} + +/* These xf86Set* functions are intended for use by non-screen specific code */ + +int +xf86SetIntOption(pointer optlist, const char *name, int deflt) +{ + return LookupIntOption(optlist, name, deflt, TRUE); +} + + +double +xf86SetRealOption(pointer optlist, const char *name, double deflt) +{ + return LookupRealOption(optlist, name, deflt, TRUE); +} + + +char * +xf86SetStrOption(pointer optlist, const char *name, char *deflt) +{ + return LookupStrOption(optlist, name, deflt, TRUE); +} + + +int +xf86SetBoolOption(pointer optlist, const char *name, int deflt) +{ + return LookupBoolOption(optlist, name, deflt, TRUE); +} + +double +xf86SetPercentOption(pointer optlist, const char *name, double deflt) +{ + return LookupPercentOption(optlist, name, deflt, TRUE); +} + +/* + * These are like the Set*Option functions, but they don't mark the options + * as used. + */ +int +xf86CheckIntOption(pointer optlist, const char *name, int deflt) +{ + return LookupIntOption(optlist, name, deflt, FALSE); +} + + +double +xf86CheckRealOption(pointer optlist, const char *name, double deflt) +{ + return LookupRealOption(optlist, name, deflt, FALSE); +} + + +char * +xf86CheckStrOption(pointer optlist, const char *name, char *deflt) +{ + return LookupStrOption(optlist, name, deflt, FALSE); +} + + +int +xf86CheckBoolOption(pointer optlist, const char *name, int deflt) +{ + return LookupBoolOption(optlist, name, deflt, FALSE); +} + + +double +xf86CheckPercentOption(pointer optlist, const char *name, double deflt) +{ + return LookupPercentOption(optlist, name, deflt, FALSE); +} +/* + * addNewOption() has the required property of replacing the option value + * if the option is already present. + */ +pointer +xf86ReplaceIntOption(pointer optlist, const char *name, const int val) +{ + char tmp[16]; + sprintf(tmp,"%i",val); + return xf86AddNewOption(optlist,name,tmp); +} + +pointer +xf86ReplaceRealOption(pointer optlist, const char *name, const double val) +{ + char tmp[32]; + snprintf(tmp,32,"%f",val); + return xf86AddNewOption(optlist,name,tmp); +} + +pointer +xf86ReplaceBoolOption(pointer optlist, const char *name, const Bool val) +{ + return xf86AddNewOption(optlist,name,val?"True":"False"); +} + +pointer +xf86ReplacePercentOption(pointer optlist, const char *name, const double val) +{ + char tmp[16]; + sprintf(tmp, "%lf%%", val); + return xf86AddNewOption(optlist,name,tmp); +} + +pointer +xf86ReplaceStrOption(pointer optlist, const char *name, const char* val) +{ + return xf86AddNewOption(optlist,name,val); +} + +pointer +xf86AddNewOption(pointer head, const char *name, const char *val) +{ + /* XXX These should actually be allocated in the parser library. */ + char *tmp = val ? strdup(val) : NULL; + char *tmp_name = strdup(name); + + return xf86addNewOption(head, tmp_name, tmp); +} + + +pointer +xf86NewOption(char *name, char *value) +{ + return xf86newOption(name, value); +} + + +pointer +xf86NextOption(pointer list) +{ + return xf86nextOption(list); +} + +pointer +xf86OptionListCreate(const char **options, int count, int used) +{ + return xf86optionListCreate(options, count, used); +} + +pointer +xf86OptionListMerge(pointer head, pointer tail) +{ + return xf86optionListMerge(head, tail); +} + +void +xf86OptionListFree(pointer opt) +{ + xf86optionListFree(opt); +} + +char * +xf86OptionName(pointer opt) +{ + return xf86optionName(opt); +} + +char * +xf86OptionValue(pointer opt) +{ + return xf86optionValue(opt); +} + +void +xf86OptionListReport(pointer parm) +{ + XF86OptionPtr opts = parm; + + while(opts) { + if (xf86optionValue(opts)) + xf86ErrorFVerb(5, "\tOption \"%s\" \"%s\"\n", + xf86optionName(opts), xf86optionValue(opts)); + else + xf86ErrorFVerb( 5, "\tOption \"%s\"\n", xf86optionName(opts)); + opts = xf86nextOption(opts); + } +} + +/* End of XInput-caused section */ + +pointer +xf86FindOption(pointer options, const char *name) +{ + return xf86findOption(options, name); +} + + +char * +xf86FindOptionValue(pointer options, const char *name) +{ + return xf86findOptionValue(options, name); +} + + +void +xf86MarkOptionUsed(pointer option) +{ + if (option != NULL) + ((XF86OptionPtr)option)->opt_used = TRUE; +} + + +void +xf86MarkOptionUsedByName(pointer options, const char *name) +{ + XF86OptionPtr opt; + + opt = xf86findOption(options, name); + if (opt != NULL) + opt->opt_used = TRUE; +} + +Bool +xf86CheckIfOptionUsed(pointer option) +{ + if (option != NULL) + return ((XF86OptionPtr)option)->opt_used; + else + return FALSE; +} + +Bool +xf86CheckIfOptionUsedByName(pointer options, const char *name) +{ + XF86OptionPtr opt; + + opt = xf86findOption(options, name); + if (opt != NULL) + return opt->opt_used; + else + return FALSE; +} + +void +xf86ShowUnusedOptions(int scrnIndex, pointer options) +{ + XF86OptionPtr opt = options; + + while (opt) { + if (opt->opt_name && !opt->opt_used) { + xf86DrvMsg(scrnIndex, X_WARNING, "Option \"%s\" is not used\n", + opt->opt_name); + } + opt = opt->list.next; + } +} + + +static Bool +GetBoolValue(OptionInfoPtr p, const char *s) +{ + return xf86getBoolValue(&p->value.bool, s); +} + +static Bool +ParseOptionValue(int scrnIndex, pointer options, OptionInfoPtr p, + Bool markUsed) +{ + char *s, *end; + Bool wasUsed = FALSE; + + if ((s = xf86findOptionValue(options, p->name)) != NULL) { + if (markUsed) { + wasUsed = xf86CheckIfOptionUsedByName(options, p->name); + xf86MarkOptionUsedByName(options, p->name); + } + switch (p->type) { + case OPTV_INTEGER: + if (*s == '\0') { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires an integer value\n", + p->name); + } + p->found = FALSE; + } else { + p->value.num = strtoul(s, &end, 0); + if (*end == '\0') { + p->found = TRUE; + } else { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires an integer value\n", + p->name); + } + p->found = FALSE; + } + } + break; + case OPTV_STRING: + if (*s == '\0') { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires an string value\n", + p->name); + } + p->found = FALSE; + } else { + p->value.str = s; + p->found = TRUE; + } + break; + case OPTV_ANYSTR: + p->value.str = s; + p->found = TRUE; + break; + case OPTV_REAL: + if (*s == '\0') { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a floating point " + "value\n", p->name); + } + p->found = FALSE; + } else { + p->value.realnum = strtod(s, &end); + if (*end == '\0') { + p->found = TRUE; + } else { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a floating point " + "value\n", p->name); + } + p->found = FALSE; + } + } + break; + case OPTV_BOOLEAN: + if (GetBoolValue(p, s)) { + p->found = TRUE; + } else { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a boolean value\n", + p->name); + } + p->found = FALSE; + } + break; + case OPTV_PERCENT: + { + char tmp = 0; + /* awkward match, but %% doesn't increase the match counter, + * hence 100 looks the same as 100% to the caller of sccanf + */ + if (sscanf(s, "%lf%c", &p->value.realnum, &tmp) != 2 || tmp != '%') { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a percent value\n", p->name); + } + p->found = FALSE; + } else { + p->found = TRUE; + } + } + break; + case OPTV_FREQ: + if (*s == '\0') { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a frequency value\n", + p->name); + } + p->found = FALSE; + } else { + double freq = strtod(s, &end); + int units = 0; + + if (end != s) { + p->found = TRUE; + if (!xf86NameCmp(end, "Hz")) + units = 1; + else if (!xf86NameCmp(end, "kHz") || + !xf86NameCmp(end, "k")) + units = 1000; + else if (!xf86NameCmp(end, "MHz") || + !xf86NameCmp(end, "M")) + units = 1000000; + else { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a frequency value\n", + p->name); + } + p->found = FALSE; + } + if (p->found) + freq *= (double)units; + } else { + if (markUsed) { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a frequency value\n", + p->name); + } + p->found = FALSE; + } + if (p->found) { + p->value.freq.freq = freq; + p->value.freq.units = units; + } + } + break; + case OPTV_NONE: + /* Should never get here */ + p->found = FALSE; + break; + } + if (p->found && markUsed) { + int verb = 2; + if (wasUsed) + verb = 4; + xf86DrvMsgVerb(scrnIndex, X_CONFIG, verb, "Option \"%s\"", p->name); + if (!(p->type == OPTV_BOOLEAN && *s == 0)) { + xf86ErrorFVerb(verb, " \"%s\"", s); + } + xf86ErrorFVerb(verb, "\n"); + } + } else if (p->type == OPTV_BOOLEAN) { + /* Look for matches with options with or without a "No" prefix. */ + char *n, *newn; + OptionInfoRec opt; + + n = xf86NormalizeName(p->name); + if (!n) { + p->found = FALSE; + return FALSE; + } + if (strncmp(n, "no", 2) == 0) { + newn = n + 2; + } else { + free(n); + if (asprintf(&n, "No%s", p->name) == -1) { + p->found = FALSE; + return FALSE; + } + newn = n; + } + if ((s = xf86findOptionValue(options, newn)) != NULL) { + if (markUsed) + xf86MarkOptionUsedByName(options, newn); + if (GetBoolValue(&opt, s)) { + p->value.bool = !opt.value.bool; + p->found = TRUE; + } else { + xf86DrvMsg(scrnIndex, X_WARNING, + "Option \"%s\" requires a boolean value\n", newn); + p->found = FALSE; + } + } else { + p->found = FALSE; + } + if (p->found && markUsed) { + xf86DrvMsgVerb(scrnIndex, X_CONFIG, 2, "Option \"%s\"", newn); + if (*s != 0) { + xf86ErrorFVerb(2, " \"%s\"", s); + } + xf86ErrorFVerb(2, "\n"); + } + free(n); + } else { + p->found = FALSE; + } + return p->found; +} + + +void +xf86ProcessOptions(int scrnIndex, pointer options, OptionInfoPtr optinfo) +{ + OptionInfoPtr p; + + for (p = optinfo; p->name != NULL; p++) { + ParseOptionValue(scrnIndex, options, p, TRUE); + } +} + + +OptionInfoPtr +xf86TokenToOptinfo(const OptionInfoRec *table, int token) +{ + const OptionInfoRec *p, *match = NULL, *set = NULL; + + if (!table) { + ErrorF("xf86TokenToOptinfo: table is NULL\n"); + return NULL; + } + + for (p = table; p->token >= 0; p++) { + if (p->token == token) { + match = p; + if (p->found) + set = p; + } + } + + if (set) + return (OptionInfoPtr)set; + else if (match) + return (OptionInfoPtr)match; + else + return NULL; +} + + +const char * +xf86TokenToOptName(const OptionInfoRec *table, int token) +{ + const OptionInfoRec *p; + + p = xf86TokenToOptinfo(table, token); + return p->name; +} + + +Bool +xf86IsOptionSet(const OptionInfoRec *table, int token) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + return p && p->found; +} + + +char * +xf86GetOptValString(const OptionInfoRec *table, int token) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) + return p->value.str; + else + return NULL; +} + + +Bool +xf86GetOptValInteger(const OptionInfoRec *table, int token, int *value) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + *value = p->value.num; + return TRUE; + } else + return FALSE; +} + + +Bool +xf86GetOptValULong(const OptionInfoRec *table, int token, unsigned long *value) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + *value = p->value.num; + return TRUE; + } else + return FALSE; +} + + +Bool +xf86GetOptValReal(const OptionInfoRec *table, int token, double *value) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + *value = p->value.realnum; + return TRUE; + } else + return FALSE; +} + + +Bool +xf86GetOptValFreq(const OptionInfoRec *table, int token, + OptFreqUnits expectedUnits, double *value) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + if (p->value.freq.units > 0) { + /* Units give, so the scaling is known. */ + switch (expectedUnits) { + case OPTUNITS_HZ: + *value = p->value.freq.freq; + break; + case OPTUNITS_KHZ: + *value = p->value.freq.freq / 1000.0; + break; + case OPTUNITS_MHZ: + *value = p->value.freq.freq / 1000000.0; + break; + } + } else { + /* No units given, so try to guess the scaling. */ + switch (expectedUnits) { + case OPTUNITS_HZ: + *value = p->value.freq.freq; + break; + case OPTUNITS_KHZ: + if (p->value.freq.freq > 1000.0) + *value = p->value.freq.freq / 1000.0; + else + *value = p->value.freq.freq; + break; + case OPTUNITS_MHZ: + if (p->value.freq.freq > 1000000.0) + *value = p->value.freq.freq / 1000000.0; + else if (p->value.freq.freq > 1000.0) + *value = p->value.freq.freq / 1000.0; + else + *value = p->value.freq.freq; + } + } + return TRUE; + } else + return FALSE; +} + + +Bool +xf86GetOptValBool(const OptionInfoRec *table, int token, Bool *value) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + *value = p->value.bool; + return TRUE; + } else + return FALSE; +} + + +Bool +xf86ReturnOptValBool(const OptionInfoRec *table, int token, Bool def) +{ + OptionInfoPtr p; + + p = xf86TokenToOptinfo(table, token); + if (p && p->found) { + return p->value.bool; + } else + return def; +} + + +int +xf86NameCmp(const char *s1, const char *s2) +{ + return xf86nameCompare(s1, s2); +} + +char * +xf86NormalizeName(const char *s) +{ + char *ret, *q; + const char *p; + + if (s == NULL) + return NULL; + + ret = malloc(strlen(s) + 1); + for (p = s, q = ret; *p != 0; p++) { + switch (*p) { + case '_': + case ' ': + case '\t': + continue; + default: + if (isupper(*p)) + *q++ = tolower(*p); + else + *q++ = *p; + } + } + *q = '\0'; + return ret; +} diff --git a/xorg-server/hw/xfree86/common/xf86Priv.h b/xorg-server/hw/xfree86/common/xf86Priv.h index 436594ba6..1fe3d7e0d 100644 --- a/xorg-server/hw/xfree86/common/xf86Priv.h +++ b/xorg-server/hw/xfree86/common/xf86Priv.h @@ -1,154 +1,154 @@ -/*
- * Copyright (c) 1997-2002 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-/*
- * This file contains declarations for private XFree86 functions and variables,
- * and definitions of private macros.
- *
- * "private" means not available to video drivers.
- */
-
-#ifndef _XF86PRIV_H
-#define _XF86PRIV_H
-
-#include "xf86Privstr.h"
-#include "propertyst.h"
-#include "input.h"
-
-/*
- * Parameters set ONLY from the command line options
- * The global state of these things is held in xf86InfoRec (when appropriate).
- */
-extern _X_EXPORT const char *xf86ConfigFile;
-extern _X_EXPORT const char *xf86ConfigDir;
-extern _X_EXPORT Bool xf86AllowMouseOpenFail;
-#ifdef XF86VIDMODE
-extern _X_EXPORT Bool xf86VidModeDisabled;
-extern _X_EXPORT Bool xf86VidModeAllowNonLocal;
-#endif
-extern _X_EXPORT Bool xf86fpFlag;
-extern _X_EXPORT Bool xf86sFlag;
-extern _X_EXPORT Bool xf86bsEnableFlag;
-extern _X_EXPORT Bool xf86bsDisableFlag;
-extern _X_EXPORT Bool xf86silkenMouseDisableFlag;
-extern _X_EXPORT Bool xf86xkbdirFlag;
-#ifdef HAVE_ACPI
-extern _X_EXPORT Bool xf86acpiDisableFlag;
-#endif
-extern _X_EXPORT char *xf86LayoutName;
-extern _X_EXPORT char *xf86ScreenName;
-extern _X_EXPORT char *xf86PointerName;
-extern _X_EXPORT char *xf86KeyboardName;
-extern _X_EXPORT int xf86FbBpp;
-extern _X_EXPORT int xf86Depth;
-extern _X_EXPORT Pix24Flags xf86Pix24;
-extern _X_EXPORT rgb xf86Weight;
-extern _X_EXPORT Bool xf86FlipPixels;
-extern _X_EXPORT Gamma xf86Gamma;
-extern _X_EXPORT char *xf86ServerName;
-
-/* Other parameters */
-
-extern _X_EXPORT xf86InfoRec xf86Info;
-extern _X_EXPORT const char *xf86ModulePath;
-extern _X_EXPORT MessageType xf86ModPathFrom;
-extern _X_EXPORT const char *xf86LogFile;
-extern _X_EXPORT MessageType xf86LogFileFrom;
-extern _X_EXPORT Bool xf86LogFileWasOpened;
-extern _X_EXPORT serverLayoutRec xf86ConfigLayout;
-
-extern _X_EXPORT DriverPtr *xf86DriverList;
-extern _X_EXPORT int xf86NumDrivers;
-extern _X_EXPORT Bool xf86Resetting;
-extern _X_EXPORT Bool xf86Initialising;
-extern _X_EXPORT int xf86NumScreens;
-extern _X_EXPORT const char *xf86VisualNames[];
-extern _X_EXPORT int xf86Verbose; /* verbosity level */
-extern _X_EXPORT int xf86LogVerbose; /* log file verbosity level */
-extern _X_EXPORT Bool xorgHWAccess;
-
-extern _X_EXPORT RootWinPropPtr *xf86RegisteredPropertiesTable;
-
-#ifndef DEFAULT_VERBOSE
-#define DEFAULT_VERBOSE 0
-#endif
-#ifndef DEFAULT_LOG_VERBOSE
-#define DEFAULT_LOG_VERBOSE 3
-#endif
-#ifndef DEFAULT_DPI
-#define DEFAULT_DPI 96
-#endif
-
-/* Function Prototypes */
-#ifndef _NO_XF86_PROTOTYPES
-
-/* xf86Bus.c */
-extern _X_EXPORT Bool xf86BusConfig(void);
-extern _X_EXPORT void xf86BusProbe(void);
-extern _X_EXPORT void xf86AccessEnter(void);
-extern _X_EXPORT void xf86AccessLeave(void);
-extern _X_EXPORT void xf86PostProbe(void);
-extern _X_EXPORT void xf86ClearEntityListForScreen(int scrnIndex);
-extern _X_EXPORT void xf86AddDevToEntity(int entityIndex, GDevPtr dev);
-
-/* xf86Config.c */
-
-extern _X_EXPORT Bool xf86PathIsSafe(const char *path);
-
-/* xf86DefaultModes */
-
-extern _X_EXPORT const DisplayModeRec xf86DefaultModes[];
-extern _X_EXPORT const int xf86NumDefaultModes;
-
-/* xf86Configure.c */
-extern _X_EXPORT void DoConfigure(void);
-
-/* xf86ShowOpts.c */
-extern _X_EXPORT void DoShowOptions(void);
-
-/* xf86Events.c */
-
-extern _X_EXPORT void xf86Wakeup(pointer blockData, int err, pointer pReadmask);
-extern _X_HIDDEN int xf86SigWrapper(int signo);
-extern _X_EXPORT void xf86HandlePMEvents(int fd, pointer data);
-extern _X_EXPORT int (*xf86PMGetEventFromOs)(int fd,pmEvent *events,int num);
-extern _X_EXPORT pmWait (*xf86PMConfirmEventToOs)(int fd,pmEvent event);
-
-/* xf86Helper.c */
-extern _X_EXPORT void xf86LogInit(void);
-extern _X_EXPORT void xf86CloseLog(enum ExitCode error);
-
-/* xf86Init.c */
-extern _X_EXPORT Bool xf86LoadModules(char **list, pointer *optlist);
-extern _X_EXPORT int xf86SetVerbosity(int verb);
-extern _X_EXPORT int xf86SetLogVerbosity(int verb);
-extern _X_EXPORT Bool xf86CallDriverProbe( struct _DriverRec * drv, Bool detect_only );
-
-#endif /* _NO_XF86_PROTOTYPES */
-
-
-#endif /* _XF86PRIV_H */
+/* + * Copyright (c) 1997-2002 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +/* + * This file contains declarations for private XFree86 functions and variables, + * and definitions of private macros. + * + * "private" means not available to video drivers. + */ + +#ifndef _XF86PRIV_H +#define _XF86PRIV_H + +#include "xf86Privstr.h" +#include "propertyst.h" +#include "input.h" + +/* + * Parameters set ONLY from the command line options + * The global state of these things is held in xf86InfoRec (when appropriate). + */ +extern _X_EXPORT const char *xf86ConfigFile; +extern _X_EXPORT const char *xf86ConfigDir; +extern _X_EXPORT Bool xf86AllowMouseOpenFail; +#ifdef XF86VIDMODE +extern _X_EXPORT Bool xf86VidModeDisabled; +extern _X_EXPORT Bool xf86VidModeAllowNonLocal; +#endif +extern _X_EXPORT Bool xf86fpFlag; +extern _X_EXPORT Bool xf86sFlag; +extern _X_EXPORT Bool xf86bsEnableFlag; +extern _X_EXPORT Bool xf86bsDisableFlag; +extern _X_EXPORT Bool xf86silkenMouseDisableFlag; +extern _X_EXPORT Bool xf86xkbdirFlag; +#ifdef HAVE_ACPI +extern _X_EXPORT Bool xf86acpiDisableFlag; +#endif +extern _X_EXPORT char *xf86LayoutName; +extern _X_EXPORT char *xf86ScreenName; +extern _X_EXPORT char *xf86PointerName; +extern _X_EXPORT char *xf86KeyboardName; +extern _X_EXPORT int xf86FbBpp; +extern _X_EXPORT int xf86Depth; +extern _X_EXPORT Pix24Flags xf86Pix24; +extern _X_EXPORT rgb xf86Weight; +extern _X_EXPORT Bool xf86FlipPixels; +extern _X_EXPORT Gamma xf86Gamma; +extern _X_EXPORT char *xf86ServerName; + +/* Other parameters */ + +extern _X_EXPORT xf86InfoRec xf86Info; +extern _X_EXPORT const char *xf86ModulePath; +extern _X_EXPORT MessageType xf86ModPathFrom; +extern _X_EXPORT const char *xf86LogFile; +extern _X_EXPORT MessageType xf86LogFileFrom; +extern _X_EXPORT Bool xf86LogFileWasOpened; +extern _X_EXPORT serverLayoutRec xf86ConfigLayout; + +extern _X_EXPORT DriverPtr *xf86DriverList; +extern _X_EXPORT int xf86NumDrivers; +extern _X_EXPORT Bool xf86Resetting; +extern _X_EXPORT Bool xf86Initialising; +extern _X_EXPORT int xf86NumScreens; +extern _X_EXPORT const char *xf86VisualNames[]; +extern _X_EXPORT int xf86Verbose; /* verbosity level */ +extern _X_EXPORT int xf86LogVerbose; /* log file verbosity level */ +extern _X_EXPORT Bool xorgHWAccess; + +extern _X_EXPORT RootWinPropPtr *xf86RegisteredPropertiesTable; + +#ifndef DEFAULT_VERBOSE +#define DEFAULT_VERBOSE 0 +#endif +#ifndef DEFAULT_LOG_VERBOSE +#define DEFAULT_LOG_VERBOSE 3 +#endif +#ifndef DEFAULT_DPI +#define DEFAULT_DPI 96 +#endif + +/* Function Prototypes */ +#ifndef _NO_XF86_PROTOTYPES + +/* xf86Bus.c */ +extern _X_EXPORT Bool xf86BusConfig(void); +extern _X_EXPORT void xf86BusProbe(void); +extern _X_EXPORT void xf86AccessEnter(void); +extern _X_EXPORT void xf86AccessLeave(void); +extern _X_EXPORT void xf86PostProbe(void); +extern _X_EXPORT void xf86ClearEntityListForScreen(int scrnIndex); +extern _X_EXPORT void xf86AddDevToEntity(int entityIndex, GDevPtr dev); + +/* xf86Config.c */ + +extern _X_EXPORT Bool xf86PathIsSafe(const char *path); + +/* xf86DefaultModes */ + +extern _X_EXPORT const DisplayModeRec xf86DefaultModes[]; +extern _X_EXPORT const int xf86NumDefaultModes; + +/* xf86Configure.c */ +extern _X_EXPORT void DoConfigure(void); + +/* xf86ShowOpts.c */ +extern _X_EXPORT void DoShowOptions(void); + +/* xf86Events.c */ + +extern _X_EXPORT void xf86Wakeup(pointer blockData, int err, pointer pReadmask); +extern _X_HIDDEN int xf86SigWrapper(int signo); +extern _X_EXPORT void xf86HandlePMEvents(int fd, pointer data); +extern _X_EXPORT int (*xf86PMGetEventFromOs)(int fd,pmEvent *events,int num); +extern _X_EXPORT pmWait (*xf86PMConfirmEventToOs)(int fd,pmEvent event); + +/* xf86Helper.c */ +extern _X_EXPORT void xf86LogInit(void); +extern _X_EXPORT void xf86CloseLog(enum ExitCode error); + +/* xf86Init.c */ +extern _X_EXPORT Bool xf86LoadModules(char **list, pointer *optlist); +extern _X_EXPORT int xf86SetVerbosity(int verb); +extern _X_EXPORT int xf86SetLogVerbosity(int verb); +extern _X_EXPORT Bool xf86CallDriverProbe( struct _DriverRec * drv, Bool detect_only ); + +#endif /* _NO_XF86_PROTOTYPES */ + + +#endif /* _XF86PRIV_H */ diff --git a/xorg-server/hw/xfree86/common/xf86RandR.c b/xorg-server/hw/xfree86/common/xf86RandR.c index e8e5a3696..4663d0366 100644 --- a/xorg-server/hw/xfree86/common/xf86RandR.c +++ b/xorg-server/hw/xfree86/common/xf86RandR.c @@ -1,485 +1,485 @@ -/*
- *
- * Copyright © 2002 Keith Packard, member of The XFree86 Project, Inc.
- *
- * 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 Keith Packard not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission. Keith Packard makes no
- * representations about the suitability of this software for any purpose. It
- * is provided "as is" without express or implied warranty.
- *
- * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL KEITH PACKARD 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.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include "os.h"
-#include "globals.h"
-#include "xf86.h"
-#include "xf86str.h"
-#include "xf86Priv.h"
-#include "xf86DDC.h"
-#include "mipointer.h"
-#include <randrstr.h>
-#include "inputstr.h"
-
-typedef struct _xf86RandRInfo {
- CreateScreenResourcesProcPtr CreateScreenResources;
- CloseScreenProcPtr CloseScreen;
- int virtualX;
- int virtualY;
- int mmWidth;
- int mmHeight;
- Rotation rotation;
-} XF86RandRInfoRec, *XF86RandRInfoPtr;
-
-static DevPrivateKeyRec xf86RandRKeyRec;
-static DevPrivateKey xf86RandRKey;
-
-#define XF86RANDRINFO(p) ((XF86RandRInfoPtr)dixLookupPrivate(&(p)->devPrivates, xf86RandRKey))
-
-static int
-xf86RandRModeRefresh (DisplayModePtr mode)
-{
- if (mode->VRefresh)
- return (int) (mode->VRefresh + 0.5);
- else if (mode->Clock == 0)
- return 0;
- else
- return (int) (mode->Clock * 1000.0 / mode->HTotal / mode->VTotal + 0.5);
-}
-
-static Bool
-xf86RandRGetInfo (ScreenPtr pScreen, Rotation *rotations)
-{
- RRScreenSizePtr pSize;
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
- XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
- DisplayModePtr mode;
- int refresh0 = 60;
- xorgRRModeMM RRModeMM;
-
- *rotations = RR_Rotate_0;
-
- for (mode = scrp->modes; mode != NULL ; mode = mode->next)
- {
- int refresh = xf86RandRModeRefresh (mode);
-
- if (mode == scrp->modes)
- refresh0 = refresh;
-
- RRModeMM.mode = mode;
- RRModeMM.virtX = randrp->virtualX;
- RRModeMM.virtY = randrp->virtualY;
- RRModeMM.mmWidth = randrp->mmWidth;
- RRModeMM.mmHeight = randrp->mmHeight;
-
- if(scrp->DriverFunc) {
- (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM);
- }
-
- pSize = RRRegisterSize (pScreen,
- mode->HDisplay, mode->VDisplay,
- RRModeMM.mmWidth, RRModeMM.mmHeight);
- if (!pSize)
- return FALSE;
- RRRegisterRate (pScreen, pSize, refresh);
- if (mode == scrp->currentMode &&
- mode->HDisplay == scrp->virtualX && mode->VDisplay == scrp->virtualY)
- RRSetCurrentConfig (pScreen, randrp->rotation, refresh, pSize);
- if (mode->next == scrp->modes)
- break;
- }
- if (scrp->currentMode->HDisplay != randrp->virtualX ||
- scrp->currentMode->VDisplay != randrp->virtualY)
- {
- mode = scrp->modes;
-
- RRModeMM.mode = NULL;
- RRModeMM.virtX = randrp->virtualX;
- RRModeMM.virtY = randrp->virtualY;
- RRModeMM.mmWidth = randrp->mmWidth;
- RRModeMM.mmHeight = randrp->mmHeight;
-
- if(scrp->DriverFunc) {
- (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM);
- }
-
- pSize = RRRegisterSize (pScreen,
- randrp->virtualX, randrp->virtualY,
- RRModeMM.mmWidth, RRModeMM.mmHeight);
- if (!pSize)
- return FALSE;
- RRRegisterRate (pScreen, pSize, refresh0);
- if (scrp->virtualX == randrp->virtualX &&
- scrp->virtualY == randrp->virtualY)
- {
- RRSetCurrentConfig (pScreen, randrp->rotation, refresh0, pSize);
- }
- }
-
- /* If there is driver support for randr, let it set our supported rotations */
- if(scrp->DriverFunc) {
- xorgRRRotation RRRotation;
-
- RRRotation.RRRotations = *rotations;
- if (!(*scrp->DriverFunc)(scrp, RR_GET_INFO, &RRRotation))
- return TRUE;
- *rotations = RRRotation.RRRotations;
- }
-
- return TRUE;
-}
-
-static Bool
-xf86RandRSetMode (ScreenPtr pScreen,
- DisplayModePtr mode,
- Bool useVirtual,
- int mmWidth,
- int mmHeight)
-{
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
- XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
- int oldWidth = pScreen->width;
- int oldHeight = pScreen->height;
- int oldmmWidth = pScreen->mmWidth;
- int oldmmHeight = pScreen->mmHeight;
- int oldVirtualX = scrp->virtualX;
- int oldVirtualY = scrp->virtualY;
- WindowPtr pRoot = pScreen->root;
- Bool ret = TRUE;
-
- if (pRoot && scrp->vtSema)
- (*scrp->EnableDisableFBAccess) (pScreen->myNum, FALSE);
- if (useVirtual)
- {
- scrp->virtualX = randrp->virtualX;
- scrp->virtualY = randrp->virtualY;
- }
- else
- {
- scrp->virtualX = mode->HDisplay;
- scrp->virtualY = mode->VDisplay;
- }
-
- /*
- * The DIX forgets the physical dimensions we passed into RRRegisterSize, so
- * reconstruct them if possible.
- */
- if(scrp->DriverFunc) {
- xorgRRModeMM RRModeMM;
-
- RRModeMM.mode = mode;
- RRModeMM.virtX = scrp->virtualX;
- RRModeMM.virtY = scrp->virtualY;
- RRModeMM.mmWidth = mmWidth;
- RRModeMM.mmHeight = mmHeight;
-
- (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM);
-
- mmWidth = RRModeMM.mmWidth;
- mmHeight = RRModeMM.mmHeight;
- }
- if(randrp->rotation & (RR_Rotate_90 | RR_Rotate_270))
- {
- /* If the screen is rotated 90 or 270 degrees, swap the sizes. */
- pScreen->width = scrp->virtualY;
- pScreen->height = scrp->virtualX;
- pScreen->mmWidth = mmHeight;
- pScreen->mmHeight = mmWidth;
- }
- else
- {
- pScreen->width = scrp->virtualX;
- pScreen->height = scrp->virtualY;
- pScreen->mmWidth = mmWidth;
- pScreen->mmHeight = mmHeight;
- }
- if (!xf86SwitchMode (pScreen, mode))
- {
- pScreen->width = oldWidth;
- pScreen->height = oldHeight;
- pScreen->mmWidth = oldmmWidth;
- pScreen->mmHeight = oldmmHeight;
- scrp->virtualX = oldVirtualX;
- scrp->virtualY = oldVirtualY;
- ret = FALSE;
- }
- /*
- * Make sure the layout is correct
- */
- xf86ReconfigureLayout();
-
- /*
- * Make sure the whole screen is visible
- */
- xf86SetViewport (pScreen, pScreen->width, pScreen->height);
- xf86SetViewport (pScreen, 0, 0);
- if (pRoot && scrp->vtSema)
- (*scrp->EnableDisableFBAccess) (pScreen->myNum, TRUE);
- return ret;
-}
-
-static Bool
-xf86RandRSetConfig (ScreenPtr pScreen,
- Rotation rotation,
- int rate,
- RRScreenSizePtr pSize)
-{
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
- XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
- DisplayModePtr mode;
- int pos[MAXDEVICES][2];
- Bool useVirtual = FALSE;
- Rotation oldRotation = randrp->rotation;
- DeviceIntPtr dev;
- Bool view_adjusted = FALSE;
-
- for (dev = inputInfo.devices; dev; dev = dev->next)
- {
- if (!IsMaster(dev) && !IsFloating(dev))
- continue;
-
- miPointerGetPosition(dev, &pos[dev->id][0], &pos[dev->id][1]);
- }
-
- for (mode = scrp->modes; ; mode = mode->next)
- {
- if (mode->HDisplay == pSize->width &&
- mode->VDisplay == pSize->height &&
- (rate == 0 || xf86RandRModeRefresh (mode) == rate))
- break;
- if (mode->next == scrp->modes)
- {
- if (pSize->width == randrp->virtualX &&
- pSize->height == randrp->virtualY)
- {
- mode = scrp->modes;
- useVirtual = TRUE;
- break;
- }
- return FALSE;
- }
- }
-
- if (randrp->rotation != rotation) {
-
- /* Have the driver do its thing. */
- if (scrp->DriverFunc) {
- xorgRRRotation RRRotation;
- RRRotation.RRConfig.rotation = rotation;
- RRRotation.RRConfig.rate = rate;
- RRRotation.RRConfig.width = pSize->width;
- RRRotation.RRConfig.height = pSize->height;
-
- /*
- * Currently we need to rely on HW support for rotation.
- */
- if (!(*scrp->DriverFunc)(scrp, RR_SET_CONFIG, &RRRotation))
- return FALSE;
- } else
- return FALSE;
-
- randrp->rotation = rotation;
- }
-
- if (!xf86RandRSetMode (pScreen, mode, useVirtual, pSize->mmWidth, pSize->mmHeight)) {
- if(randrp->rotation != oldRotation) {
- /* Have the driver undo its thing. */
- if (scrp->DriverFunc) {
- xorgRRRotation RRRotation;
- RRRotation.RRConfig.rotation = oldRotation;
- RRRotation.RRConfig.rate = xf86RandRModeRefresh (scrp->currentMode);
- RRRotation.RRConfig.width = scrp->virtualX;
- RRRotation.RRConfig.height = scrp->virtualY;
- (*scrp->DriverFunc)(scrp, RR_SET_CONFIG, &RRRotation);
- }
-
- randrp->rotation = oldRotation;
- }
- return FALSE;
- }
-
- /*
- * Move the cursor back where it belongs; SwitchMode repositions it
- * FIXME: duplicated code, see modes/xf86RandR12.c
- */
- for (dev = inputInfo.devices; dev; dev = dev->next)
- {
- if (!IsMaster(dev) && !IsFloating(dev))
- continue;
-
- if (pScreen == miPointerGetScreen(dev)) {
- int px = pos[dev->id][0];
- int py = pos[dev->id][1];
-
- px = (px >= pScreen->width ? (pScreen->width - 1) : px);
- py = (py >= pScreen->height ? (pScreen->height - 1) : py);
-
- /* Setting the viewpoint makes only sense on one device */
- if (!view_adjusted && IsMaster(dev)) {
- xf86SetViewport(pScreen, px, py);
- view_adjusted = TRUE;
- }
-
- (*pScreen->SetCursorPosition) (dev, pScreen, px, py, FALSE);
- }
- }
-
- return TRUE;
-}
-
-/*
- * Wait until the screen is initialized before whacking the
- * sizes around; otherwise the screen pixmap will be allocated
- * at the current mode size rather than the maximum size
- */
-static Bool
-xf86RandRCreateScreenResources (ScreenPtr pScreen)
-{
- XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
-#if 0
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
- DisplayModePtr mode;
-#endif
-
- pScreen->CreateScreenResources = randrp->CreateScreenResources;
- if (!(*pScreen->CreateScreenResources) (pScreen))
- return FALSE;
-
-#if 0
- mode = scrp->currentMode;
- if (mode)
- xf86RandRSetMode (pScreen, mode, TRUE);
-#endif
-
- return TRUE;
-}
-
-/*
- * Reset size back to original
- */
-static Bool
-xf86RandRCloseScreen (int index, ScreenPtr pScreen)
-{
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
- XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen);
-
- scrp->virtualX = pScreen->width = randrp->virtualX;
- scrp->virtualY = pScreen->height = randrp->virtualY;
- scrp->currentMode = scrp->modes;
- pScreen->CloseScreen = randrp->CloseScreen;
- free(randrp);
- dixSetPrivate(&pScreen->devPrivates, xf86RandRKey, NULL);
- return (*pScreen->CloseScreen) (index, pScreen);
-}
-
-Rotation
-xf86GetRotation(ScreenPtr pScreen)
-{
- if (xf86RandRKey == NULL)
- return RR_Rotate_0;
-
- return XF86RANDRINFO(pScreen)->rotation;
-}
-
-/* Function to change RandR's idea of the virtual screen size */
-Bool
-xf86RandRSetNewVirtualAndDimensions(ScreenPtr pScreen,
- int newvirtX, int newvirtY, int newmmWidth, int newmmHeight,
- Bool resetMode)
-{
- XF86RandRInfoPtr randrp;
-
- if (xf86RandRKey == NULL)
- return FALSE;
-
- randrp = XF86RANDRINFO(pScreen);
- if (randrp == NULL)
- return FALSE;
-
- if (newvirtX > 0)
- randrp->virtualX = newvirtX;
-
- if (newvirtY > 0)
- randrp->virtualY = newvirtY;
-
- if (newmmWidth > 0)
- randrp->mmWidth = newmmWidth;
-
- if (newmmHeight > 0)
- randrp->mmHeight = newmmHeight;
-
- /* This is only for during server start */
- if (resetMode) {
- return (xf86RandRSetMode(pScreen,
- XF86SCRNINFO(pScreen)->currentMode,
- TRUE,
- pScreen->mmWidth, pScreen->mmHeight));
- }
-
- return TRUE;
-}
-
-Bool
-xf86RandRInit (ScreenPtr pScreen)
-{
- rrScrPrivPtr rp;
- XF86RandRInfoPtr randrp;
- ScrnInfoPtr scrp = XF86SCRNINFO(pScreen);
-
-#ifdef PANORAMIX
- /* XXX disable RandR when using Xinerama */
- if (!noPanoramiXExtension)
- return TRUE;
-#endif
-
- xf86RandRKey = &xf86RandRKeyRec;
-
- if (!dixRegisterPrivateKey(&xf86RandRKeyRec, PRIVATE_SCREEN, 0))
- return FALSE;
-
- randrp = malloc(sizeof (XF86RandRInfoRec));
- if (!randrp)
- return FALSE;
-
- if (!RRScreenInit (pScreen))
- {
- free(randrp);
- return FALSE;
- }
- rp = rrGetScrPriv(pScreen);
- rp->rrGetInfo = xf86RandRGetInfo;
- rp->rrSetConfig = xf86RandRSetConfig;
-
- randrp->virtualX = scrp->virtualX;
- randrp->virtualY = scrp->virtualY;
- randrp->mmWidth = pScreen->mmWidth;
- randrp->mmHeight = pScreen->mmHeight;
-
- randrp->CreateScreenResources = pScreen->CreateScreenResources;
- pScreen->CreateScreenResources = xf86RandRCreateScreenResources;
-
- randrp->CloseScreen = pScreen->CloseScreen;
- pScreen->CloseScreen = xf86RandRCloseScreen;
-
- randrp->rotation = RR_Rotate_0;
-
- dixSetPrivate(&pScreen->devPrivates, xf86RandRKey, randrp);
- return TRUE;
-}
-
-
+/* + * + * Copyright © 2002 Keith Packard, member of The XFree86 Project, Inc. + * + * 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 Keith Packard not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Keith Packard makes no + * representations about the suitability of this software for any purpose. It + * is provided "as is" without express or implied warranty. + * + * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL KEITH PACKARD 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. + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <X11/X.h> +#include "os.h" +#include "globals.h" +#include "xf86.h" +#include "xf86str.h" +#include "xf86Priv.h" +#include "xf86DDC.h" +#include "mipointer.h" +#include <randrstr.h> +#include "inputstr.h" + +typedef struct _xf86RandRInfo { + CreateScreenResourcesProcPtr CreateScreenResources; + CloseScreenProcPtr CloseScreen; + int virtualX; + int virtualY; + int mmWidth; + int mmHeight; + Rotation rotation; +} XF86RandRInfoRec, *XF86RandRInfoPtr; + +static DevPrivateKeyRec xf86RandRKeyRec; +static DevPrivateKey xf86RandRKey; + +#define XF86RANDRINFO(p) ((XF86RandRInfoPtr)dixLookupPrivate(&(p)->devPrivates, xf86RandRKey)) + +static int +xf86RandRModeRefresh (DisplayModePtr mode) +{ + if (mode->VRefresh) + return (int) (mode->VRefresh + 0.5); + else if (mode->Clock == 0) + return 0; + else + return (int) (mode->Clock * 1000.0 / mode->HTotal / mode->VTotal + 0.5); +} + +static Bool +xf86RandRGetInfo (ScreenPtr pScreen, Rotation *rotations) +{ + RRScreenSizePtr pSize; + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen); + DisplayModePtr mode; + int refresh0 = 60; + xorgRRModeMM RRModeMM; + + *rotations = RR_Rotate_0; + + for (mode = scrp->modes; mode != NULL ; mode = mode->next) + { + int refresh = xf86RandRModeRefresh (mode); + + if (mode == scrp->modes) + refresh0 = refresh; + + RRModeMM.mode = mode; + RRModeMM.virtX = randrp->virtualX; + RRModeMM.virtY = randrp->virtualY; + RRModeMM.mmWidth = randrp->mmWidth; + RRModeMM.mmHeight = randrp->mmHeight; + + if(scrp->DriverFunc) { + (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM); + } + + pSize = RRRegisterSize (pScreen, + mode->HDisplay, mode->VDisplay, + RRModeMM.mmWidth, RRModeMM.mmHeight); + if (!pSize) + return FALSE; + RRRegisterRate (pScreen, pSize, refresh); + if (mode == scrp->currentMode && + mode->HDisplay == scrp->virtualX && mode->VDisplay == scrp->virtualY) + RRSetCurrentConfig (pScreen, randrp->rotation, refresh, pSize); + if (mode->next == scrp->modes) + break; + } + if (scrp->currentMode->HDisplay != randrp->virtualX || + scrp->currentMode->VDisplay != randrp->virtualY) + { + mode = scrp->modes; + + RRModeMM.mode = NULL; + RRModeMM.virtX = randrp->virtualX; + RRModeMM.virtY = randrp->virtualY; + RRModeMM.mmWidth = randrp->mmWidth; + RRModeMM.mmHeight = randrp->mmHeight; + + if(scrp->DriverFunc) { + (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM); + } + + pSize = RRRegisterSize (pScreen, + randrp->virtualX, randrp->virtualY, + RRModeMM.mmWidth, RRModeMM.mmHeight); + if (!pSize) + return FALSE; + RRRegisterRate (pScreen, pSize, refresh0); + if (scrp->virtualX == randrp->virtualX && + scrp->virtualY == randrp->virtualY) + { + RRSetCurrentConfig (pScreen, randrp->rotation, refresh0, pSize); + } + } + + /* If there is driver support for randr, let it set our supported rotations */ + if(scrp->DriverFunc) { + xorgRRRotation RRRotation; + + RRRotation.RRRotations = *rotations; + if (!(*scrp->DriverFunc)(scrp, RR_GET_INFO, &RRRotation)) + return TRUE; + *rotations = RRRotation.RRRotations; + } + + return TRUE; +} + +static Bool +xf86RandRSetMode (ScreenPtr pScreen, + DisplayModePtr mode, + Bool useVirtual, + int mmWidth, + int mmHeight) +{ + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen); + int oldWidth = pScreen->width; + int oldHeight = pScreen->height; + int oldmmWidth = pScreen->mmWidth; + int oldmmHeight = pScreen->mmHeight; + int oldVirtualX = scrp->virtualX; + int oldVirtualY = scrp->virtualY; + WindowPtr pRoot = pScreen->root; + Bool ret = TRUE; + + if (pRoot && scrp->vtSema) + (*scrp->EnableDisableFBAccess) (pScreen->myNum, FALSE); + if (useVirtual) + { + scrp->virtualX = randrp->virtualX; + scrp->virtualY = randrp->virtualY; + } + else + { + scrp->virtualX = mode->HDisplay; + scrp->virtualY = mode->VDisplay; + } + + /* + * The DIX forgets the physical dimensions we passed into RRRegisterSize, so + * reconstruct them if possible. + */ + if(scrp->DriverFunc) { + xorgRRModeMM RRModeMM; + + RRModeMM.mode = mode; + RRModeMM.virtX = scrp->virtualX; + RRModeMM.virtY = scrp->virtualY; + RRModeMM.mmWidth = mmWidth; + RRModeMM.mmHeight = mmHeight; + + (*scrp->DriverFunc)(scrp, RR_GET_MODE_MM, &RRModeMM); + + mmWidth = RRModeMM.mmWidth; + mmHeight = RRModeMM.mmHeight; + } + if(randrp->rotation & (RR_Rotate_90 | RR_Rotate_270)) + { + /* If the screen is rotated 90 or 270 degrees, swap the sizes. */ + pScreen->width = scrp->virtualY; + pScreen->height = scrp->virtualX; + pScreen->mmWidth = mmHeight; + pScreen->mmHeight = mmWidth; + } + else + { + pScreen->width = scrp->virtualX; + pScreen->height = scrp->virtualY; + pScreen->mmWidth = mmWidth; + pScreen->mmHeight = mmHeight; + } + if (!xf86SwitchMode (pScreen, mode)) + { + pScreen->width = oldWidth; + pScreen->height = oldHeight; + pScreen->mmWidth = oldmmWidth; + pScreen->mmHeight = oldmmHeight; + scrp->virtualX = oldVirtualX; + scrp->virtualY = oldVirtualY; + ret = FALSE; + } + /* + * Make sure the layout is correct + */ + xf86ReconfigureLayout(); + + /* + * Make sure the whole screen is visible + */ + xf86SetViewport (pScreen, pScreen->width, pScreen->height); + xf86SetViewport (pScreen, 0, 0); + if (pRoot && scrp->vtSema) + (*scrp->EnableDisableFBAccess) (pScreen->myNum, TRUE); + return ret; +} + +static Bool +xf86RandRSetConfig (ScreenPtr pScreen, + Rotation rotation, + int rate, + RRScreenSizePtr pSize) +{ + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen); + DisplayModePtr mode; + int pos[MAXDEVICES][2]; + Bool useVirtual = FALSE; + Rotation oldRotation = randrp->rotation; + DeviceIntPtr dev; + Bool view_adjusted = FALSE; + + for (dev = inputInfo.devices; dev; dev = dev->next) + { + if (!IsMaster(dev) && !IsFloating(dev)) + continue; + + miPointerGetPosition(dev, &pos[dev->id][0], &pos[dev->id][1]); + } + + for (mode = scrp->modes; ; mode = mode->next) + { + if (mode->HDisplay == pSize->width && + mode->VDisplay == pSize->height && + (rate == 0 || xf86RandRModeRefresh (mode) == rate)) + break; + if (mode->next == scrp->modes) + { + if (pSize->width == randrp->virtualX && + pSize->height == randrp->virtualY) + { + mode = scrp->modes; + useVirtual = TRUE; + break; + } + return FALSE; + } + } + + if (randrp->rotation != rotation) { + + /* Have the driver do its thing. */ + if (scrp->DriverFunc) { + xorgRRRotation RRRotation; + RRRotation.RRConfig.rotation = rotation; + RRRotation.RRConfig.rate = rate; + RRRotation.RRConfig.width = pSize->width; + RRRotation.RRConfig.height = pSize->height; + + /* + * Currently we need to rely on HW support for rotation. + */ + if (!(*scrp->DriverFunc)(scrp, RR_SET_CONFIG, &RRRotation)) + return FALSE; + } else + return FALSE; + + randrp->rotation = rotation; + } + + if (!xf86RandRSetMode (pScreen, mode, useVirtual, pSize->mmWidth, pSize->mmHeight)) { + if(randrp->rotation != oldRotation) { + /* Have the driver undo its thing. */ + if (scrp->DriverFunc) { + xorgRRRotation RRRotation; + RRRotation.RRConfig.rotation = oldRotation; + RRRotation.RRConfig.rate = xf86RandRModeRefresh (scrp->currentMode); + RRRotation.RRConfig.width = scrp->virtualX; + RRRotation.RRConfig.height = scrp->virtualY; + (*scrp->DriverFunc)(scrp, RR_SET_CONFIG, &RRRotation); + } + + randrp->rotation = oldRotation; + } + return FALSE; + } + + /* + * Move the cursor back where it belongs; SwitchMode repositions it + * FIXME: duplicated code, see modes/xf86RandR12.c + */ + for (dev = inputInfo.devices; dev; dev = dev->next) + { + if (!IsMaster(dev) && !IsFloating(dev)) + continue; + + if (pScreen == miPointerGetScreen(dev)) { + int px = pos[dev->id][0]; + int py = pos[dev->id][1]; + + px = (px >= pScreen->width ? (pScreen->width - 1) : px); + py = (py >= pScreen->height ? (pScreen->height - 1) : py); + + /* Setting the viewpoint makes only sense on one device */ + if (!view_adjusted && IsMaster(dev)) { + xf86SetViewport(pScreen, px, py); + view_adjusted = TRUE; + } + + (*pScreen->SetCursorPosition) (dev, pScreen, px, py, FALSE); + } + } + + return TRUE; +} + +/* + * Wait until the screen is initialized before whacking the + * sizes around; otherwise the screen pixmap will be allocated + * at the current mode size rather than the maximum size + */ +static Bool +xf86RandRCreateScreenResources (ScreenPtr pScreen) +{ + XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen); +#if 0 + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + DisplayModePtr mode; +#endif + + pScreen->CreateScreenResources = randrp->CreateScreenResources; + if (!(*pScreen->CreateScreenResources) (pScreen)) + return FALSE; + +#if 0 + mode = scrp->currentMode; + if (mode) + xf86RandRSetMode (pScreen, mode, TRUE); +#endif + + return TRUE; +} + +/* + * Reset size back to original + */ +static Bool +xf86RandRCloseScreen (int index, ScreenPtr pScreen) +{ + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + XF86RandRInfoPtr randrp = XF86RANDRINFO(pScreen); + + scrp->virtualX = pScreen->width = randrp->virtualX; + scrp->virtualY = pScreen->height = randrp->virtualY; + scrp->currentMode = scrp->modes; + pScreen->CloseScreen = randrp->CloseScreen; + free(randrp); + dixSetPrivate(&pScreen->devPrivates, xf86RandRKey, NULL); + return (*pScreen->CloseScreen) (index, pScreen); +} + +Rotation +xf86GetRotation(ScreenPtr pScreen) +{ + if (xf86RandRKey == NULL) + return RR_Rotate_0; + + return XF86RANDRINFO(pScreen)->rotation; +} + +/* Function to change RandR's idea of the virtual screen size */ +Bool +xf86RandRSetNewVirtualAndDimensions(ScreenPtr pScreen, + int newvirtX, int newvirtY, int newmmWidth, int newmmHeight, + Bool resetMode) +{ + XF86RandRInfoPtr randrp; + + if (xf86RandRKey == NULL) + return FALSE; + + randrp = XF86RANDRINFO(pScreen); + if (randrp == NULL) + return FALSE; + + if (newvirtX > 0) + randrp->virtualX = newvirtX; + + if (newvirtY > 0) + randrp->virtualY = newvirtY; + + if (newmmWidth > 0) + randrp->mmWidth = newmmWidth; + + if (newmmHeight > 0) + randrp->mmHeight = newmmHeight; + + /* This is only for during server start */ + if (resetMode) { + return (xf86RandRSetMode(pScreen, + XF86SCRNINFO(pScreen)->currentMode, + TRUE, + pScreen->mmWidth, pScreen->mmHeight)); + } + + return TRUE; +} + +Bool +xf86RandRInit (ScreenPtr pScreen) +{ + rrScrPrivPtr rp; + XF86RandRInfoPtr randrp; + ScrnInfoPtr scrp = XF86SCRNINFO(pScreen); + +#ifdef PANORAMIX + /* XXX disable RandR when using Xinerama */ + if (!noPanoramiXExtension) + return TRUE; +#endif + + xf86RandRKey = &xf86RandRKeyRec; + + if (!dixRegisterPrivateKey(&xf86RandRKeyRec, PRIVATE_SCREEN, 0)) + return FALSE; + + randrp = malloc(sizeof (XF86RandRInfoRec)); + if (!randrp) + return FALSE; + + if (!RRScreenInit (pScreen)) + { + free(randrp); + return FALSE; + } + rp = rrGetScrPriv(pScreen); + rp->rrGetInfo = xf86RandRGetInfo; + rp->rrSetConfig = xf86RandRSetConfig; + + randrp->virtualX = scrp->virtualX; + randrp->virtualY = scrp->virtualY; + randrp->mmWidth = pScreen->mmWidth; + randrp->mmHeight = pScreen->mmHeight; + + randrp->CreateScreenResources = pScreen->CreateScreenResources; + pScreen->CreateScreenResources = xf86RandRCreateScreenResources; + + randrp->CloseScreen = pScreen->CloseScreen; + pScreen->CloseScreen = xf86RandRCloseScreen; + + randrp->rotation = RR_Rotate_0; + + dixSetPrivate(&pScreen->devPrivates, xf86RandRKey, randrp); + return TRUE; +} + + diff --git a/xorg-server/hw/xfree86/common/xf86Xinput.c b/xorg-server/hw/xfree86/common/xf86Xinput.c index a53531cc1..d22fdc8b9 100644 --- a/xorg-server/hw/xfree86/common/xf86Xinput.c +++ b/xorg-server/hw/xfree86/common/xf86Xinput.c @@ -1,1401 +1,1401 @@ -/*
- * Copyright 1995-1999 by Frederic Lepied, France. <Lepied@XFree86.org>
- *
- * 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 Frederic Lepied not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission. Frederic Lepied makes no
- * representations about the suitability of this software for any purpose. It
- * is provided "as is" without express or implied warranty.
- *
- * FREDERIC LEPIED DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL FREDERIC LEPIED 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.
- *
- */
-/*
- * Copyright (c) 2000-2002 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
- * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * OTHER DEALINGS IN THE SOFTWARE.
- *
- * Except as contained in this notice, the name of the copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/Xfuncproto.h>
-#include <X11/Xmd.h>
-#include <X11/extensions/XI.h>
-#include <X11/extensions/XIproto.h>
-#include <X11/Xatom.h>
-#include "xf86.h"
-#include "xf86Priv.h"
-#include "xf86Config.h"
-#include "xf86Xinput.h"
-#include "xf86Optrec.h"
-#include "mipointer.h"
-#include "extinit.h"
-#include "loaderProcs.h"
-
-#include "exevents.h" /* AddInputDevice */
-#include "exglobals.h"
-#include "eventstr.h"
-#include "inpututils.h"
-
-#include <string.h> /* InputClassMatches */
-#ifdef HAVE_FNMATCH_H
-#include <fnmatch.h>
-#endif
-#ifdef HAVE_SYS_UTSNAME_H
-#include <sys/utsname.h>
-#endif
-
-#include <stdarg.h>
-#include <stdint.h> /* for int64_t */
-
-#include "mi.h"
-
-#include <ptrveloc.h> /* dix pointer acceleration */
-#include <xserver-properties.h>
-
-#ifdef XFreeXDGA
-#include "dgaproc.h"
-#endif
-
-#include "xkbsrv.h"
-
-/* Valuator verification macro */
-#define XI_VERIFY_VALUATORS(num_valuators) \
- if (num_valuators > MAX_VALUATORS) { \
- xf86Msg(X_ERROR, "%s: num_valuator %d is greater than" \
- " MAX_VALUATORS\n", __FUNCTION__, num_valuators); \
- return; \
- }
-
-static int
-xf86InputDevicePostInit(DeviceIntPtr dev);
-
-/**
- * Eval config and modify DeviceVelocityRec accordingly
- */
-static void
-ProcessVelocityConfiguration(DeviceIntPtr pDev, char* devname, pointer list,
- DeviceVelocityPtr s)
-{
- int tempi;
- float tempf;
- Atom float_prop = XIGetKnownProperty(XATOM_FLOAT);
- Atom prop;
-
- if(!s)
- return;
-
- /* common settings (available via device properties) */
- tempf = xf86SetRealOption(list, "ConstantDeceleration", 1.0);
- if (tempf > 1.0) {
- xf86Msg(X_CONFIG, "%s: (accel) constant deceleration by %.1f\n",
- devname, tempf);
- prop = XIGetKnownProperty(ACCEL_PROP_CONSTANT_DECELERATION);
- XIChangeDeviceProperty(pDev, prop, float_prop, 32,
- PropModeReplace, 1, &tempf, FALSE);
- }
-
- tempf = xf86SetRealOption(list, "AdaptiveDeceleration", 1.0);
- if (tempf > 1.0) {
- xf86Msg(X_CONFIG, "%s: (accel) adaptive deceleration by %.1f\n",
- devname, tempf);
- prop = XIGetKnownProperty(ACCEL_PROP_ADAPTIVE_DECELERATION);
- XIChangeDeviceProperty(pDev, prop, float_prop, 32,
- PropModeReplace, 1, &tempf, FALSE);
- }
-
- /* select profile by number */
- tempi = xf86SetIntOption(list, "AccelerationProfile",
- s->statistics.profile_number);
-
- prop = XIGetKnownProperty(ACCEL_PROP_PROFILE_NUMBER);
- if (XIChangeDeviceProperty(pDev, prop, XA_INTEGER, 32,
- PropModeReplace, 1, &tempi, FALSE) == Success) {
- xf86Msg(X_CONFIG, "%s: (accel) acceleration profile %i\n", devname,
- tempi);
- } else {
- xf86Msg(X_CONFIG, "%s: (accel) acceleration profile %i is unknown\n",
- devname, tempi);
- }
-
- /* set scaling */
- tempf = xf86SetRealOption(list, "ExpectedRate", 0);
- prop = XIGetKnownProperty(ACCEL_PROP_VELOCITY_SCALING);
- if (tempf > 0) {
- tempf = 1000.0 / tempf;
- XIChangeDeviceProperty(pDev, prop, float_prop, 32,
- PropModeReplace, 1, &tempf, FALSE);
- } else {
- tempf = xf86SetRealOption(list, "VelocityScale", s->corr_mul);
- XIChangeDeviceProperty(pDev, prop, float_prop, 32,
- PropModeReplace, 1, &tempf, FALSE);
- }
-
- tempi = xf86SetIntOption(list, "VelocityTrackerCount", -1);
- if (tempi > 1)
- InitTrackers(s, tempi);
-
- s->initial_range = xf86SetIntOption(list, "VelocityInitialRange",
- s->initial_range);
-
- s->max_diff = xf86SetRealOption(list, "VelocityAbsDiff", s->max_diff);
-
- tempf = xf86SetRealOption(list, "VelocityRelDiff", -1);
- if (tempf >= 0) {
- xf86Msg(X_CONFIG, "%s: (accel) max rel. velocity difference: %.1f%%\n",
- devname, tempf*100.0);
- s->max_rel_diff = tempf;
- }
-
- /* Configure softening. If const deceleration is used, this is expected
- * to provide better subpixel information so we enable
- * softening by default only if ConstantDeceleration is not used
- */
- s->use_softening = xf86SetBoolOption(list, "Softening",
- s->const_acceleration == 1.0);
-
- s->average_accel = xf86SetBoolOption(list, "AccelerationProfileAveraging",
- s->average_accel);
-
- s->reset_time = xf86SetIntOption(list, "VelocityReset", s->reset_time);
-}
-
-static void
-ApplyAccelerationSettings(DeviceIntPtr dev){
- int scheme, i;
- DeviceVelocityPtr pVel;
- InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate;
- char* schemeStr;
-
- if (dev->valuator && dev->ptrfeed) {
- schemeStr = xf86SetStrOption(pInfo->options, "AccelerationScheme", "");
-
- scheme = dev->valuator->accelScheme.number;
-
- if (!xf86NameCmp(schemeStr, "predictable"))
- scheme = PtrAccelPredictable;
-
- if (!xf86NameCmp(schemeStr, "lightweight"))
- scheme = PtrAccelLightweight;
-
- if (!xf86NameCmp(schemeStr, "none"))
- scheme = PtrAccelNoOp;
-
- /* reinit scheme if needed */
- if (dev->valuator->accelScheme.number != scheme) {
- if (dev->valuator->accelScheme.AccelCleanupProc) {
- dev->valuator->accelScheme.AccelCleanupProc(dev);
- }
-
- if (InitPointerAccelerationScheme(dev, scheme)) {
- xf86Msg(X_CONFIG, "%s: (accel) selected scheme %s/%i\n",
- pInfo->name, schemeStr, scheme);
- } else {
- xf86Msg(X_CONFIG, "%s: (accel) could not init scheme %s\n",
- pInfo->name, schemeStr);
- scheme = dev->valuator->accelScheme.number;
- }
- } else {
- xf86Msg(X_CONFIG, "%s: (accel) keeping acceleration scheme %i\n",
- pInfo->name, scheme);
- }
-
- free(schemeStr);
-
- /* process special configuration */
- switch (scheme) {
- case PtrAccelPredictable:
- pVel = GetDevicePredictableAccelData(dev);
- ProcessVelocityConfiguration (dev, pInfo->name, pInfo->options,
- pVel);
- break;
- }
-
- i = xf86SetIntOption(pInfo->options, "AccelerationNumerator",
- dev->ptrfeed->ctrl.num);
- if (i >= 0)
- dev->ptrfeed->ctrl.num = i;
-
- i = xf86SetIntOption(pInfo->options, "AccelerationDenominator",
- dev->ptrfeed->ctrl.den);
- if (i > 0)
- dev->ptrfeed->ctrl.den = i;
-
- i = xf86SetIntOption(pInfo->options, "AccelerationThreshold",
- dev->ptrfeed->ctrl.threshold);
- if (i >= 0)
- dev->ptrfeed->ctrl.threshold = i;
-
- xf86Msg(X_CONFIG, "%s: (accel) acceleration factor: %.3f\n",
- pInfo->name, ((float)dev->ptrfeed->ctrl.num)/
- ((float)dev->ptrfeed->ctrl.den));
- xf86Msg(X_CONFIG, "%s: (accel) acceleration threshold: %i\n",
- pInfo->name, dev->ptrfeed->ctrl.threshold);
- }
-}
-
-/***********************************************************************
- *
- * xf86ProcessCommonOptions --
- *
- * Process global options.
- *
- ***********************************************************************
- */
-void
-xf86ProcessCommonOptions(InputInfoPtr pInfo,
- pointer list)
-{
- if (xf86SetBoolOption(list, "Floating", 0) ||
- !xf86SetBoolOption(list, "AlwaysCore", 1) ||
- !xf86SetBoolOption(list, "SendCoreEvents", 1) ||
- !xf86SetBoolOption(list, "CorePointer", 1) ||
- !xf86SetBoolOption(list, "CoreKeyboard", 1)) {
- xf86Msg(X_CONFIG, "%s: doesn't report core events\n", pInfo->name);
- } else {
- pInfo->flags |= XI86_ALWAYS_CORE;
- xf86Msg(X_CONFIG, "%s: always reports core events\n", pInfo->name);
- }
-}
-
-/***********************************************************************
- *
- * xf86ActivateDevice --
- *
- * Initialize an input device.
- *
- * Returns TRUE on success, or FALSE otherwise.
- ***********************************************************************
- */
-static DeviceIntPtr
-xf86ActivateDevice(InputInfoPtr pInfo)
-{
- DeviceIntPtr dev;
- Atom atom;
-
- dev = AddInputDevice(serverClient, pInfo->device_control, TRUE);
-
- if (dev == NULL)
- {
- xf86Msg(X_ERROR, "Too many input devices. Ignoring %s\n",
- pInfo->name);
- pInfo->dev = NULL;
- return NULL;
- }
-
- atom = MakeAtom(pInfo->type_name, strlen(pInfo->type_name), TRUE);
- AssignTypeAndName(dev, atom, pInfo->name);
- dev->public.devicePrivate = pInfo;
- pInfo->dev = dev;
-
- dev->coreEvents = pInfo->flags & XI86_ALWAYS_CORE;
- dev->type = SLAVE;
- dev->spriteInfo->spriteOwner = FALSE;
-
- dev->config_info = xf86SetStrOption(pInfo->options, "config_info", NULL);
-
- if (serverGeneration == 1)
- xf86Msg(X_INFO, "XINPUT: Adding extended input device \"%s\" (type: %s, id %d)\n",
- pInfo->name, pInfo->type_name, dev->id);
-
- return dev;
-}
-
-/****************************************************************************
- *
- * Caller: ProcXSetDeviceMode
- *
- * Change the mode of an extension device.
- * This function is used to change the mode of a device from reporting
- * relative motion to reporting absolute positional information, and
- * vice versa.
- * The default implementation below is that no such devices are supported.
- *
- ***********************************************************************
- */
-
-int
-SetDeviceMode (ClientPtr client, DeviceIntPtr dev, int mode)
-{
- InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate;
-
- if (pInfo->switch_mode) {
- return (*pInfo->switch_mode)(client, dev, mode);
- }
- else
- return BadMatch;
-}
-
-
-/***********************************************************************
- *
- * Caller: ProcXSetDeviceValuators
- *
- * Set the value of valuators on an extension input device.
- * This function is used to set the initial value of valuators on
- * those input devices that are capable of reporting either relative
- * motion or an absolute position, and allow an initial position to be set.
- * The default implementation below is that no such devices are supported.
- *
- ***********************************************************************
- */
-
-int
-SetDeviceValuators (ClientPtr client, DeviceIntPtr dev, int *valuators,
- int first_valuator, int num_valuators)
-{
- InputInfoPtr pInfo = (InputInfoPtr) dev->public.devicePrivate;
-
- if (pInfo->set_device_valuators)
- return (*pInfo->set_device_valuators)(pInfo, valuators, first_valuator,
- num_valuators);
-
- return BadMatch;
-}
-
-
-/***********************************************************************
- *
- * Caller: ProcXChangeDeviceControl
- *
- * Change the specified device controls on an extension input device.
- *
- ***********************************************************************
- */
-
-int
-ChangeDeviceControl (ClientPtr client, DeviceIntPtr dev, xDeviceCtl *control)
-{
- InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate;
-
- if (!pInfo->control_proc) {
- switch (control->control) {
- case DEVICE_CORE:
- case DEVICE_ABS_CALIB:
- case DEVICE_ABS_AREA:
- return BadMatch;
- case DEVICE_RESOLUTION:
- case DEVICE_ENABLE:
- return Success;
- default:
- return BadMatch;
- }
- }
- else {
- return (*pInfo->control_proc)(pInfo, control);
- }
-}
-
-/*
- * Get the operating system name from uname and store it statically to avoid
- * repeating the system call each time MatchOS is checked.
- */
-static const char *
-HostOS(void)
-{
-#ifdef HAVE_SYS_UTSNAME_H
- struct utsname name;
- static char host_os[sizeof(name.sysname)] = "";
-
- if (*host_os == '\0') {
- if (uname(&name) >= 0)
- strcpy(host_os, name.sysname);
- else {
- strncpy(host_os, "unknown", sizeof(host_os));
- host_os[sizeof(host_os)-1] = '\0';
- }
- }
- return host_os;
-#else
- return "";
-#endif
-}
-
-static int
-match_substring(const char *attr, const char *pattern)
-{
- return (strstr(attr, pattern)) ? 0 : -1;
-}
-
-#ifdef HAVE_FNMATCH_H
-static int
-match_pattern(const char *attr, const char *pattern)
-{
- return fnmatch(pattern, attr, 0);
-}
-#else
-#define match_pattern match_substring
-#endif
-
-#ifdef HAVE_FNMATCH_H
-static int
-match_path_pattern(const char *attr, const char *pattern)
-{
- return fnmatch(pattern, attr, FNM_PATHNAME);
-}
-#else
-#define match_path_pattern match_substring
-#endif
-
-/*
- * If no Layout section is found, xf86ServerLayout.id becomes "(implicit)"
- * It is convenient that "" in patterns means "no explicit layout"
- */
-static int
-match_string_implicit(const char *attr, const char *pattern)
-{
- if (strlen(pattern)) {
- return strcmp(attr, pattern);
- } else {
- return strcmp(attr,"(implicit)");
- }
-}
-
-/*
- * Match an attribute against a list of NULL terminated arrays of patterns.
- * If a pattern in each list entry is matched, return TRUE.
- */
-static Bool
-MatchAttrToken(const char *attr, struct list *patterns,
- int (*compare)(const char *attr, const char *pattern))
-{
- const xf86MatchGroup *group;
-
- /* If there are no patterns, accept the match */
- if (list_is_empty(patterns))
- return TRUE;
-
- /* If there are patterns but no attribute, reject the match */
- if (!attr)
- return FALSE;
-
- /*
- * Otherwise, iterate the list of patterns ensuring each entry has a
- * match. Each list entry is a separate Match line of the same type.
- */
- list_for_each_entry(group, patterns, entry) {
- char * const *cur;
- Bool match = FALSE;
-
- for (cur = group->values; *cur; cur++)
- if ((*compare)(attr, *cur) == 0) {
- match = TRUE;
- break;
- }
- if (!match)
- return FALSE;
- }
-
- /* All the entries in the list matched the attribute */
- return TRUE;
-}
-
-/*
- * Classes without any Match statements match all devices. Otherwise, all
- * statements must match.
- */
-static Bool
-InputClassMatches(const XF86ConfInputClassPtr iclass, const InputInfoPtr idev,
- const InputAttributes *attrs)
-{
- /* MatchProduct substring */
- if (!MatchAttrToken(attrs->product, &iclass->match_product, match_substring))
- return FALSE;
-
- /* MatchVendor substring */
- if (!MatchAttrToken(attrs->vendor, &iclass->match_vendor, match_substring))
- return FALSE;
-
- /* MatchDevicePath pattern */
- if (!MatchAttrToken(attrs->device, &iclass->match_device, match_path_pattern))
- return FALSE;
-
- /* MatchOS case-insensitive string */
- if (!MatchAttrToken(HostOS(), &iclass->match_os, strcasecmp))
- return FALSE;
-
- /* MatchPnPID pattern */
- if (!MatchAttrToken(attrs->pnp_id, &iclass->match_pnpid, match_pattern))
- return FALSE;
-
- /* MatchUSBID pattern */
- if (!MatchAttrToken(attrs->usb_id, &iclass->match_usbid, match_pattern))
- return FALSE;
-
- /* MatchDriver string */
- if (!MatchAttrToken(idev->driver, &iclass->match_driver, strcmp))
- return FALSE;
-
- /*
- * MatchTag string
- * See if any of the device's tags match any of the MatchTag tokens.
- */
- if (!list_is_empty(&iclass->match_tag)) {
- char * const *tag;
- Bool match;
-
- if (!attrs->tags)
- return FALSE;
- for (tag = attrs->tags, match = FALSE; *tag; tag++) {
- if (MatchAttrToken(*tag, &iclass->match_tag, strcmp)) {
- match = TRUE;
- break;
- }
- }
- if (!match)
- return FALSE;
- }
-
- /* MatchLayout string */
- if (!list_is_empty(&iclass->match_layout)) {
- if (!MatchAttrToken(xf86ConfigLayout.id,
- &iclass->match_layout, match_string_implicit))
- return FALSE;
- }
-
- /* MatchIs* booleans */
- if (iclass->is_keyboard.set &&
- iclass->is_keyboard.val != !!(attrs->flags & ATTR_KEYBOARD))
- return FALSE;
- if (iclass->is_pointer.set &&
- iclass->is_pointer.val != !!(attrs->flags & ATTR_POINTER))
- return FALSE;
- if (iclass->is_joystick.set &&
- iclass->is_joystick.val != !!(attrs->flags & ATTR_JOYSTICK))
- return FALSE;
- if (iclass->is_tablet.set &&
- iclass->is_tablet.val != !!(attrs->flags & ATTR_TABLET))
- return FALSE;
- if (iclass->is_touchpad.set &&
- iclass->is_touchpad.val != !!(attrs->flags & ATTR_TOUCHPAD))
- return FALSE;
- if (iclass->is_touchscreen.set &&
- iclass->is_touchscreen.val != !!(attrs->flags & ATTR_TOUCHSCREEN))
- return FALSE;
-
- return TRUE;
-}
-
-/*
- * Merge in any InputClass configurations. Options in each InputClass
- * section have more priority than the original device configuration as
- * well as any previous InputClass sections.
- */
-static int
-MergeInputClasses(const InputInfoPtr idev, const InputAttributes *attrs)
-{
- XF86ConfInputClassPtr cl;
- XF86OptionPtr classopts;
-
- for (cl = xf86configptr->conf_inputclass_lst; cl; cl = cl->list.next) {
- if (!InputClassMatches(cl, idev, attrs))
- continue;
-
- /* Collect class options and driver settings */
- classopts = xf86optionListDup(cl->option_lst);
- if (cl->driver) {
- free(idev->driver);
- idev->driver = xstrdup(cl->driver);
- if (!idev->driver) {
- xf86Msg(X_ERROR, "Failed to allocate memory while merging "
- "InputClass configuration");
- return BadAlloc;
- }
- classopts = xf86ReplaceStrOption(classopts, "driver",
- idev->driver);
- }
-
- /* Apply options to device with InputClass settings preferred. */
- xf86Msg(X_CONFIG, "%s: Applying InputClass \"%s\"\n",
- idev->name, cl->identifier);
- idev->options = xf86optionListMerge(idev->options, classopts);
- }
-
- return Success;
-}
-
-/*
- * Iterate the list of classes and look for Option "Ignore". Return the
- * value of the last matching class and holler when returning TRUE.
- */
-static Bool
-IgnoreInputClass(const InputInfoPtr idev, const InputAttributes *attrs)
-{
- XF86ConfInputClassPtr cl;
- Bool ignore = FALSE;
- const char *ignore_class;
-
- for (cl = xf86configptr->conf_inputclass_lst; cl; cl = cl->list.next) {
- if (!InputClassMatches(cl, idev, attrs))
- continue;
- if (xf86findOption(cl->option_lst, "Ignore")) {
- ignore = xf86CheckBoolOption(cl->option_lst, "Ignore", FALSE);
- ignore_class = cl->identifier;
- }
- }
-
- if (ignore)
- xf86Msg(X_CONFIG, "%s: Ignoring device from InputClass \"%s\"\n",
- idev->name, ignore_class);
- return ignore;
-}
-
-InputInfoPtr
-xf86AllocateInput(void)
-{
- InputInfoPtr pInfo;
-
- pInfo = calloc(sizeof(*pInfo), 1);
- if (!pInfo)
- return NULL;
-
- pInfo->fd = -1;
- pInfo->type_name = "UNKNOWN";
-
- return pInfo;
-}
-
-/* Append InputInfoRec to the tail of xf86InputDevs. */
-static void
-xf86AddInput(InputDriverPtr drv, InputInfoPtr pInfo)
-{
- InputInfoPtr *prev = NULL;
-
- pInfo->drv = drv;
- pInfo->module = DuplicateModule(drv->module, NULL);
-
- for (prev = &xf86InputDevs; *prev; prev = &(*prev)->next)
- ;
-
- *prev = pInfo;
- pInfo->next = NULL;
-
- xf86CollectInputOptions(pInfo, (const char**)drv->default_options);
- xf86OptionListReport(pInfo->options);
- xf86ProcessCommonOptions(pInfo, pInfo->options);
-}
-
-/*
- * Remove an entry from xf86InputDevs and free all the device's information.
- */
-void
-xf86DeleteInput(InputInfoPtr pInp, int flags)
-{
- /* First check if the inputdev is valid. */
- if (pInp == NULL)
- return;
-
- if (pInp->module)
- UnloadModule(pInp->module);
-
- /* This should *really* be handled in drv->UnInit(dev) call instead, but
- * if the driver forgets about it make sure we free it or at least crash
- * with flying colors */
- free(pInp->private);
-
- FreeInputAttributes(pInp->attrs);
-
- /* Remove the entry from the list. */
- if (pInp == xf86InputDevs)
- xf86InputDevs = pInp->next;
- else {
- InputInfoPtr p = xf86InputDevs;
- while (p && p->next != pInp)
- p = p->next;
- if (p)
- p->next = pInp->next;
- /* Else the entry wasn't in the xf86InputDevs list (ignore this). */
- }
-
- free(pInp->driver);
- free(pInp->name);
- xf86optionListFree(pInp->options);
- free(pInp);
-}
-
-/*
- * Apply backend-specific initialization. Invoked after ActiveteDevice(),
- * i.e. after the driver successfully completed DEVICE_INIT and the device
- * is advertised.
- * @param dev the device
- * @return Success or an error code
- */
-static int
-xf86InputDevicePostInit(DeviceIntPtr dev) {
- ApplyAccelerationSettings(dev);
- return Success;
-}
-
-/**
- * Create a new input device, activate and enable it.
- *
- * Possible return codes:
- * BadName .. a bad driver name was supplied.
- * BadImplementation ... The driver does not have a PreInit function. This
- * is a driver bug.
- * BadMatch .. device initialization failed.
- * BadAlloc .. too many input devices
- *
- * @param idev The device, already set up with identifier, driver, and the
- * options.
- * @param pdev Pointer to the new device, if Success was reported.
- * @param enable Enable the device after activating it.
- *
- * @return Success or an error code
- */
-_X_INTERNAL int
-xf86NewInputDevice(InputInfoPtr pInfo, DeviceIntPtr *pdev, BOOL enable)
-{
- InputDriverPtr drv = NULL;
- DeviceIntPtr dev = NULL;
- int rval;
-
- /* Memory leak for every attached device if we don't
- * test if the module is already loaded first */
- drv = xf86LookupInputDriver(pInfo->driver);
- if (!drv)
- if (xf86LoadOneModule(pInfo->driver, NULL))
- drv = xf86LookupInputDriver(pInfo->driver);
- if (!drv) {
- xf86Msg(X_ERROR, "No input driver matching `%s'\n", pInfo->driver);
- rval = BadName;
- goto unwind;
- }
-
- xf86Msg(X_INFO, "Using input driver '%s' for '%s'\n", drv->driverName, pInfo->name);
-
- if (!drv->PreInit) {
- xf86Msg(X_ERROR,
- "Input driver `%s' has no PreInit function (ignoring)\n",
- drv->driverName);
- rval = BadImplementation;
- goto unwind;
- }
-
- xf86AddInput(drv, pInfo);
-
- rval = drv->PreInit(drv, pInfo, 0);
-
- if (rval != Success) {
- xf86Msg(X_ERROR, "PreInit returned %d for \"%s\"\n", rval, pInfo->name);
- goto unwind;
- }
-
- if (!(dev = xf86ActivateDevice(pInfo)))
- {
- rval = BadAlloc;
- goto unwind;
- }
-
- rval = ActivateDevice(dev, TRUE);
- if (rval != Success)
- {
- xf86Msg(X_ERROR, "Couldn't init device \"%s\"\n", pInfo->name);
- RemoveDevice(dev, TRUE);
- goto unwind;
- }
-
- rval = xf86InputDevicePostInit(dev);
- if (rval != Success)
- {
- xf86Msg(X_ERROR, "Couldn't post-init device \"%s\"\n", pInfo->name);
- RemoveDevice(dev, TRUE);
- goto unwind;
- }
-
- /* Enable it if it's properly initialised and we're currently in the VT */
- if (enable && dev->inited && dev->startup && xf86Screens[0]->vtSema)
- {
- OsBlockSignals();
- EnableDevice(dev, TRUE);
- if (!dev->enabled)
- {
- OsReleaseSignals();
- xf86Msg(X_ERROR, "Couldn't init device \"%s\"\n", pInfo->name);
- RemoveDevice(dev, TRUE);
- rval = BadMatch;
- goto unwind;
- }
- /* send enter/leave event, update sprite window */
- CheckMotion(NULL, dev);
- OsReleaseSignals();
- }
-
- *pdev = dev;
- return Success;
-
-unwind:
- if(pInfo) {
- if(drv && drv->UnInit)
- drv->UnInit(drv, pInfo, 0);
- else
- xf86DeleteInput(pInfo, 0);
- }
- return rval;
-}
-
-int
-NewInputDeviceRequest (InputOption *options, InputAttributes *attrs,
- DeviceIntPtr *pdev)
-{
- InputInfoPtr pInfo = NULL;
- InputOption *option = NULL;
- int rval = Success;
- int is_auto = 0;
-
- pInfo = xf86AllocateInput();
- if (!pInfo)
- return BadAlloc;
-
- for (option = options; option; option = option->next) {
- if (strcasecmp(option->key, "driver") == 0) {
- if (pInfo->driver) {
- rval = BadRequest;
- goto unwind;
- }
- pInfo->driver = xstrdup(option->value);
- if (!pInfo->driver) {
- rval = BadAlloc;
- goto unwind;
- }
- }
-
- if (strcasecmp(option->key, "name") == 0 ||
- strcasecmp(option->key, "identifier") == 0) {
- if (pInfo->name) {
- rval = BadRequest;
- goto unwind;
- }
- pInfo->name = xstrdup(option->value);
- if (!pInfo->name) {
- rval = BadAlloc;
- goto unwind;
- }
- }
-
- if (strcmp(option->key, "_source") == 0 &&
- (strcmp(option->value, "server/hal") == 0 ||
- strcmp(option->value, "server/udev") == 0)) {
- is_auto = 1;
- if (!xf86Info.autoAddDevices) {
- rval = BadMatch;
- goto unwind;
- }
- }
- }
-
- for (option = options; option; option = option->next) {
- /* Steal option key/value strings from the provided list.
- * We need those strings, the InputOption list doesn't. */
- pInfo->options = xf86addNewOption(pInfo->options,
- option->key, option->value);
- option->key = NULL;
- option->value = NULL;
- }
-
- /* Apply InputClass settings */
- if (attrs) {
- if (IgnoreInputClass(pInfo, attrs)) {
- rval = BadIDChoice;
- goto unwind;
- }
-
- rval = MergeInputClasses(pInfo, attrs);
- if (rval != Success)
- goto unwind;
-
- pInfo->attrs = DuplicateInputAttributes(attrs);
- }
-
- if (!pInfo->driver || !pInfo->name) {
- xf86Msg(X_INFO, "No input driver/identifier specified (ignoring)\n");
- rval = BadRequest;
- goto unwind;
- }
-
- if (!pInfo->name) {
- xf86Msg(X_ERROR, "No device identifier specified (ignoring)\n");
- rval = BadMatch;
- goto unwind;
- }
-
- rval = xf86NewInputDevice(pInfo, pdev,
- (!is_auto || (is_auto && xf86Info.autoEnableDevices)));
-
- return rval;
-
-unwind:
- if (is_auto && !xf86Info.autoAddDevices)
- xf86Msg(X_INFO, "AutoAddDevices is off - not adding device.\n");
- xf86DeleteInput(pInfo, 0);
- return rval;
-}
-
-void
-DeleteInputDeviceRequest(DeviceIntPtr pDev)
-{
- InputInfoPtr pInfo = (InputInfoPtr) pDev->public.devicePrivate;
- InputDriverPtr drv = NULL;
- Bool isMaster = IsMaster(pDev);
-
- if (pInfo) /* need to get these before RemoveDevice */
- drv = pInfo->drv;
-
- OsBlockSignals();
- RemoveDevice(pDev, TRUE);
-
- if (!isMaster && pInfo != NULL)
- {
- if(drv->UnInit)
- drv->UnInit(drv, pInfo, 0);
- else
- xf86DeleteInput(pInfo, 0);
- }
- OsReleaseSignals();
-}
-
-/*
- * convenient functions to post events
- */
-
-void
-xf86PostMotionEvent(DeviceIntPtr device,
- int is_absolute,
- int first_valuator,
- int num_valuators,
- ...)
-{
- va_list var;
- int i = 0;
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_zero(&mask);
- va_start(var, num_valuators);
- for (i = 0; i < num_valuators; i++)
- valuator_mask_set(&mask, first_valuator + i, va_arg(var, int));
- va_end(var);
-
- xf86PostMotionEventM(device, is_absolute, &mask);
-}
-
-void
-xf86PostMotionEventP(DeviceIntPtr device,
- int is_absolute,
- int first_valuator,
- int num_valuators,
- const int *valuators)
-{
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators);
- xf86PostMotionEventM(device, is_absolute, &mask);
-}
-
-void
-xf86PostMotionEventM(DeviceIntPtr device,
- int is_absolute,
- const ValuatorMask *mask)
-{
- int flags = 0;
-
- if (valuator_mask_num_valuators(mask) > 0)
- {
- if (is_absolute)
- flags = POINTER_ABSOLUTE;
- else
- flags = POINTER_RELATIVE | POINTER_ACCELERATE;
- }
-
-#if XFreeXDGA
- /* The evdev driver may not always send all axes across. */
- if (valuator_mask_isset(mask, 0) ||
- valuator_mask_isset(mask, 1))
- if (miPointerGetScreen(device)) {
- int index = miPointerGetScreen(device)->myNum;
- int dx = 0, dy = 0;
-
- if (valuator_mask_isset(mask, 0))
- {
- dx = valuator_mask_get(mask, 0);
- if (is_absolute)
- dx -= device->last.valuators[0];
- }
-
- if (valuator_mask_isset(mask, 1))
- {
- dy = valuator_mask_get(mask, 1);
- if (is_absolute)
- dy -= device->last.valuators[1];
- }
-
- if (DGAStealMotionEvent(device, index, dx, dy))
- return;
- }
-#endif
-
- QueuePointerEvents(device, MotionNotify, 0, flags, mask);
-}
-
-void
-xf86PostProximityEvent(DeviceIntPtr device,
- int is_in,
- int first_valuator,
- int num_valuators,
- ...)
-{
- va_list var;
- int i;
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_zero(&mask);
- va_start(var, num_valuators);
- for (i = 0; i < num_valuators; i++)
- valuator_mask_set(&mask, first_valuator + i, va_arg(var, int));
- va_end(var);
-
- xf86PostProximityEventM(device, is_in, &mask);
-}
-
-void
-xf86PostProximityEventP(DeviceIntPtr device,
- int is_in,
- int first_valuator,
- int num_valuators,
- const int *valuators)
-{
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators);
- xf86PostProximityEventM(device, is_in, &mask);
-}
-
-void
-xf86PostProximityEventM(DeviceIntPtr device,
- int is_in,
- const ValuatorMask *mask)
-{
- QueueProximityEvents(device, is_in ? ProximityIn : ProximityOut, mask);
-}
-
-void
-xf86PostButtonEvent(DeviceIntPtr device,
- int is_absolute,
- int button,
- int is_down,
- int first_valuator,
- int num_valuators,
- ...)
-{
- va_list var;
- ValuatorMask mask;
- int i = 0;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_zero(&mask);
-
- va_start(var, num_valuators);
- for (i = 0; i < num_valuators; i++)
- valuator_mask_set(&mask, first_valuator + i, va_arg(var, int));
- va_end(var);
-
- xf86PostButtonEventM(device, is_absolute, button, is_down, &mask);
-}
-
-void
-xf86PostButtonEventP(DeviceIntPtr device,
- int is_absolute,
- int button,
- int is_down,
- int first_valuator,
- int num_valuators,
- const int *valuators)
-{
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators);
- xf86PostButtonEventM(device, is_absolute, button, is_down, &mask);
-}
-
-void
-xf86PostButtonEventM(DeviceIntPtr device,
- int is_absolute,
- int button,
- int is_down,
- const ValuatorMask *mask)
-{
- int flags = 0;
-
- if (valuator_mask_num_valuators(mask) > 0)
- {
- if (is_absolute)
- flags = POINTER_ABSOLUTE;
- else
- flags = POINTER_RELATIVE | POINTER_ACCELERATE;
- }
-
-#if XFreeXDGA
- if (miPointerGetScreen(device)) {
- int index = miPointerGetScreen(device)->myNum;
-
- if (DGAStealButtonEvent(device, index, button, is_down))
- return;
- }
-#endif
-
- QueuePointerEvents(device,
- is_down ? ButtonPress : ButtonRelease, button,
- flags, mask);
-}
-
-void
-xf86PostKeyEvent(DeviceIntPtr device,
- unsigned int key_code,
- int is_down,
- int is_absolute,
- int first_valuator,
- int num_valuators,
- ...)
-{
- va_list var;
- int i = 0;
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_zero(&mask);
-
- va_start(var, num_valuators);
- for (i = 0; i < num_valuators; i++)
- valuator_mask_set(&mask, first_valuator + i, va_arg(var, int));
- va_end(var);
-
- xf86PostKeyEventM(device, key_code, is_down, is_absolute, &mask);
-}
-
-void
-xf86PostKeyEventP(DeviceIntPtr device,
- unsigned int key_code,
- int is_down,
- int is_absolute,
- int first_valuator,
- int num_valuators,
- const int *valuators)
-{
- ValuatorMask mask;
-
- XI_VERIFY_VALUATORS(num_valuators);
-
- valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators);
- xf86PostKeyEventM(device, key_code, is_down, is_absolute, &mask);
-}
-
-void
-xf86PostKeyEventM(DeviceIntPtr device,
- unsigned int key_code,
- int is_down,
- int is_absolute,
- const ValuatorMask *mask)
-{
-#if XFreeXDGA
- DeviceIntPtr pointer;
-
- /* Some pointers send key events, paired device is wrong then. */
- pointer = IsPointerDevice(device) ? device : GetPairedDevice(device);
- if (miPointerGetScreen(pointer)) {
- int index = miPointerGetScreen(pointer)->myNum;
-
- if (DGAStealKeyEvent(device, index, key_code, is_down))
- return;
- }
-#endif
-
- QueueKeyboardEvents(device,
- is_down ? KeyPress : KeyRelease,
- key_code, mask);
-}
-
-void
-xf86PostKeyboardEvent(DeviceIntPtr device,
- unsigned int key_code,
- int is_down)
-{
- ValuatorMask mask;
-
- valuator_mask_zero(&mask);
- xf86PostKeyEventM(device, key_code, is_down, 0, &mask);
-}
-
-InputInfoPtr
-xf86FirstLocalDevice(void)
-{
- return xf86InputDevs;
-}
-
-/*
- * Cx - raw data from touch screen
- * to_max - scaled highest dimension
- * (remember, this is of rows - 1 because of 0 origin)
- * to_min - scaled lowest dimension
- * from_max - highest raw value from touch screen calibration
- * from_min - lowest raw value from touch screen calibration
- *
- * This function is the same for X or Y coordinates.
- * You may have to reverse the high and low values to compensate for
- * different orgins on the touch screen vs X.
- *
- * e.g. to scale from device coordinates into screen coordinates, call
- * xf86ScaleAxis(x, 0, screen_width, dev_min, dev_max);
- */
-
-int
-xf86ScaleAxis(int Cx,
- int to_max,
- int to_min,
- int from_max,
- int from_min )
-{
- int X;
- int64_t to_width = to_max - to_min;
- int64_t from_width = from_max - from_min;
-
- if (from_width) {
- X = (int)(((to_width * (Cx - from_min)) / from_width) + to_min);
- }
- else {
- X = 0;
- ErrorF ("Divide by Zero in xf86ScaleAxis\n");
- }
-
- if (X > to_max)
- X = to_max;
- if (X < to_min)
- X = to_min;
-
- return X;
-}
-
-/*
- * This function checks the given screen against the current screen and
- * makes changes if appropriate. It should be called from an XInput driver's
- * ReadInput function before any events are posted, if the device is screen
- * specific like a touch screen.
- */
-void
-xf86XInputSetScreen(InputInfoPtr pInfo,
- int screen_number,
- int x,
- int y)
-{
- if (miPointerGetScreen(pInfo->dev) !=
- screenInfo.screens[screen_number]) {
- miPointerSetScreen(pInfo->dev, screen_number, x, y);
- }
-}
-
-
-void
-xf86InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval, int maxval,
- int resolution, int min_res, int max_res, int mode)
-{
- if (!dev || !dev->valuator)
- return;
-
- InitValuatorAxisStruct(dev, axnum, label, minval, maxval, resolution, min_res,
- max_res, mode);
-}
-
-/*
- * Set the valuator values to be in synch with dix/event.c
- * DefineInitialRootWindow().
- */
-void
-xf86InitValuatorDefaults(DeviceIntPtr dev, int axnum)
-{
- if (axnum == 0) {
- dev->valuator->axisVal[0] = screenInfo.screens[0]->width / 2;
- dev->last.valuators[0] = dev->valuator->axisVal[0];
- }
- else if (axnum == 1) {
- dev->valuator->axisVal[1] = screenInfo.screens[0]->height / 2;
- dev->last.valuators[1] = dev->valuator->axisVal[1];
- }
-}
-
-
-/**
- * Deactivate a device. Call this function from the driver if you receive a
- * read error or something else that spoils your day.
- * Device will be moved to the off_devices list, but it will still be there
- * until you really clean up after it.
- * Notifies the client about an inactive device.
- *
- * @param panic True if device is unrecoverable and needs to be removed.
- */
-void
-xf86DisableDevice(DeviceIntPtr dev, Bool panic)
-{
- if(!panic)
- {
- DisableDevice(dev, TRUE);
- } else
- {
- SendDevicePresenceEvent(dev->id, DeviceUnrecoverable);
- DeleteInputDeviceRequest(dev);
- }
-}
-
-/**
- * Reactivate a device. Call this function from the driver if you just found
- * out that the read error wasn't quite that bad after all.
- * Device will be re-activated, and an event sent to the client.
- */
-void
-xf86EnableDevice(DeviceIntPtr dev)
-{
- EnableDevice(dev, TRUE);
-}
-
-/* end of xf86Xinput.c */
+/* + * Copyright 1995-1999 by Frederic Lepied, France. <Lepied@XFree86.org> + * + * 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 Frederic Lepied not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Frederic Lepied makes no + * representations about the suitability of this software for any purpose. It + * is provided "as is" without express or implied warranty. + * + * FREDERIC LEPIED DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL FREDERIC LEPIED 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. + * + */ +/* + * Copyright (c) 2000-2002 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR + * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + * OTHER DEALINGS IN THE SOFTWARE. + * + * Except as contained in this notice, the name of the copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <X11/Xfuncproto.h> +#include <X11/Xmd.h> +#include <X11/extensions/XI.h> +#include <X11/extensions/XIproto.h> +#include <X11/Xatom.h> +#include "xf86.h" +#include "xf86Priv.h" +#include "xf86Config.h" +#include "xf86Xinput.h" +#include "xf86Optrec.h" +#include "mipointer.h" +#include "extinit.h" +#include "loaderProcs.h" + +#include "exevents.h" /* AddInputDevice */ +#include "exglobals.h" +#include "eventstr.h" +#include "inpututils.h" + +#include <string.h> /* InputClassMatches */ +#ifdef HAVE_FNMATCH_H +#include <fnmatch.h> +#endif +#ifdef HAVE_SYS_UTSNAME_H +#include <sys/utsname.h> +#endif + +#include <stdarg.h> +#include <stdint.h> /* for int64_t */ + +#include "mi.h" + +#include <ptrveloc.h> /* dix pointer acceleration */ +#include <xserver-properties.h> + +#ifdef XFreeXDGA +#include "dgaproc.h" +#endif + +#include "xkbsrv.h" + +/* Valuator verification macro */ +#define XI_VERIFY_VALUATORS(num_valuators) \ + if (num_valuators > MAX_VALUATORS) { \ + xf86Msg(X_ERROR, "%s: num_valuator %d is greater than" \ + " MAX_VALUATORS\n", __FUNCTION__, num_valuators); \ + return; \ + } + +static int +xf86InputDevicePostInit(DeviceIntPtr dev); + +/** + * Eval config and modify DeviceVelocityRec accordingly + */ +static void +ProcessVelocityConfiguration(DeviceIntPtr pDev, char* devname, pointer list, + DeviceVelocityPtr s) +{ + int tempi; + float tempf; + Atom float_prop = XIGetKnownProperty(XATOM_FLOAT); + Atom prop; + + if(!s) + return; + + /* common settings (available via device properties) */ + tempf = xf86SetRealOption(list, "ConstantDeceleration", 1.0); + if (tempf > 1.0) { + xf86Msg(X_CONFIG, "%s: (accel) constant deceleration by %.1f\n", + devname, tempf); + prop = XIGetKnownProperty(ACCEL_PROP_CONSTANT_DECELERATION); + XIChangeDeviceProperty(pDev, prop, float_prop, 32, + PropModeReplace, 1, &tempf, FALSE); + } + + tempf = xf86SetRealOption(list, "AdaptiveDeceleration", 1.0); + if (tempf > 1.0) { + xf86Msg(X_CONFIG, "%s: (accel) adaptive deceleration by %.1f\n", + devname, tempf); + prop = XIGetKnownProperty(ACCEL_PROP_ADAPTIVE_DECELERATION); + XIChangeDeviceProperty(pDev, prop, float_prop, 32, + PropModeReplace, 1, &tempf, FALSE); + } + + /* select profile by number */ + tempi = xf86SetIntOption(list, "AccelerationProfile", + s->statistics.profile_number); + + prop = XIGetKnownProperty(ACCEL_PROP_PROFILE_NUMBER); + if (XIChangeDeviceProperty(pDev, prop, XA_INTEGER, 32, + PropModeReplace, 1, &tempi, FALSE) == Success) { + xf86Msg(X_CONFIG, "%s: (accel) acceleration profile %i\n", devname, + tempi); + } else { + xf86Msg(X_CONFIG, "%s: (accel) acceleration profile %i is unknown\n", + devname, tempi); + } + + /* set scaling */ + tempf = xf86SetRealOption(list, "ExpectedRate", 0); + prop = XIGetKnownProperty(ACCEL_PROP_VELOCITY_SCALING); + if (tempf > 0) { + tempf = 1000.0 / tempf; + XIChangeDeviceProperty(pDev, prop, float_prop, 32, + PropModeReplace, 1, &tempf, FALSE); + } else { + tempf = xf86SetRealOption(list, "VelocityScale", s->corr_mul); + XIChangeDeviceProperty(pDev, prop, float_prop, 32, + PropModeReplace, 1, &tempf, FALSE); + } + + tempi = xf86SetIntOption(list, "VelocityTrackerCount", -1); + if (tempi > 1) + InitTrackers(s, tempi); + + s->initial_range = xf86SetIntOption(list, "VelocityInitialRange", + s->initial_range); + + s->max_diff = xf86SetRealOption(list, "VelocityAbsDiff", s->max_diff); + + tempf = xf86SetRealOption(list, "VelocityRelDiff", -1); + if (tempf >= 0) { + xf86Msg(X_CONFIG, "%s: (accel) max rel. velocity difference: %.1f%%\n", + devname, tempf*100.0); + s->max_rel_diff = tempf; + } + + /* Configure softening. If const deceleration is used, this is expected + * to provide better subpixel information so we enable + * softening by default only if ConstantDeceleration is not used + */ + s->use_softening = xf86SetBoolOption(list, "Softening", + s->const_acceleration == 1.0); + + s->average_accel = xf86SetBoolOption(list, "AccelerationProfileAveraging", + s->average_accel); + + s->reset_time = xf86SetIntOption(list, "VelocityReset", s->reset_time); +} + +static void +ApplyAccelerationSettings(DeviceIntPtr dev){ + int scheme, i; + DeviceVelocityPtr pVel; + InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate; + char* schemeStr; + + if (dev->valuator && dev->ptrfeed) { + schemeStr = xf86SetStrOption(pInfo->options, "AccelerationScheme", ""); + + scheme = dev->valuator->accelScheme.number; + + if (!xf86NameCmp(schemeStr, "predictable")) + scheme = PtrAccelPredictable; + + if (!xf86NameCmp(schemeStr, "lightweight")) + scheme = PtrAccelLightweight; + + if (!xf86NameCmp(schemeStr, "none")) + scheme = PtrAccelNoOp; + + /* reinit scheme if needed */ + if (dev->valuator->accelScheme.number != scheme) { + if (dev->valuator->accelScheme.AccelCleanupProc) { + dev->valuator->accelScheme.AccelCleanupProc(dev); + } + + if (InitPointerAccelerationScheme(dev, scheme)) { + xf86Msg(X_CONFIG, "%s: (accel) selected scheme %s/%i\n", + pInfo->name, schemeStr, scheme); + } else { + xf86Msg(X_CONFIG, "%s: (accel) could not init scheme %s\n", + pInfo->name, schemeStr); + scheme = dev->valuator->accelScheme.number; + } + } else { + xf86Msg(X_CONFIG, "%s: (accel) keeping acceleration scheme %i\n", + pInfo->name, scheme); + } + + free(schemeStr); + + /* process special configuration */ + switch (scheme) { + case PtrAccelPredictable: + pVel = GetDevicePredictableAccelData(dev); + ProcessVelocityConfiguration (dev, pInfo->name, pInfo->options, + pVel); + break; + } + + i = xf86SetIntOption(pInfo->options, "AccelerationNumerator", + dev->ptrfeed->ctrl.num); + if (i >= 0) + dev->ptrfeed->ctrl.num = i; + + i = xf86SetIntOption(pInfo->options, "AccelerationDenominator", + dev->ptrfeed->ctrl.den); + if (i > 0) + dev->ptrfeed->ctrl.den = i; + + i = xf86SetIntOption(pInfo->options, "AccelerationThreshold", + dev->ptrfeed->ctrl.threshold); + if (i >= 0) + dev->ptrfeed->ctrl.threshold = i; + + xf86Msg(X_CONFIG, "%s: (accel) acceleration factor: %.3f\n", + pInfo->name, ((float)dev->ptrfeed->ctrl.num)/ + ((float)dev->ptrfeed->ctrl.den)); + xf86Msg(X_CONFIG, "%s: (accel) acceleration threshold: %i\n", + pInfo->name, dev->ptrfeed->ctrl.threshold); + } +} + +/*********************************************************************** + * + * xf86ProcessCommonOptions -- + * + * Process global options. + * + *********************************************************************** + */ +void +xf86ProcessCommonOptions(InputInfoPtr pInfo, + pointer list) +{ + if (xf86SetBoolOption(list, "Floating", 0) || + !xf86SetBoolOption(list, "AlwaysCore", 1) || + !xf86SetBoolOption(list, "SendCoreEvents", 1) || + !xf86SetBoolOption(list, "CorePointer", 1) || + !xf86SetBoolOption(list, "CoreKeyboard", 1)) { + xf86Msg(X_CONFIG, "%s: doesn't report core events\n", pInfo->name); + } else { + pInfo->flags |= XI86_ALWAYS_CORE; + xf86Msg(X_CONFIG, "%s: always reports core events\n", pInfo->name); + } +} + +/*********************************************************************** + * + * xf86ActivateDevice -- + * + * Initialize an input device. + * + * Returns TRUE on success, or FALSE otherwise. + *********************************************************************** + */ +static DeviceIntPtr +xf86ActivateDevice(InputInfoPtr pInfo) +{ + DeviceIntPtr dev; + Atom atom; + + dev = AddInputDevice(serverClient, pInfo->device_control, TRUE); + + if (dev == NULL) + { + xf86Msg(X_ERROR, "Too many input devices. Ignoring %s\n", + pInfo->name); + pInfo->dev = NULL; + return NULL; + } + + atom = MakeAtom(pInfo->type_name, strlen(pInfo->type_name), TRUE); + AssignTypeAndName(dev, atom, pInfo->name); + dev->public.devicePrivate = pInfo; + pInfo->dev = dev; + + dev->coreEvents = pInfo->flags & XI86_ALWAYS_CORE; + dev->type = SLAVE; + dev->spriteInfo->spriteOwner = FALSE; + + dev->config_info = xf86SetStrOption(pInfo->options, "config_info", NULL); + + if (serverGeneration == 1) + xf86Msg(X_INFO, "XINPUT: Adding extended input device \"%s\" (type: %s, id %d)\n", + pInfo->name, pInfo->type_name, dev->id); + + return dev; +} + +/**************************************************************************** + * + * Caller: ProcXSetDeviceMode + * + * Change the mode of an extension device. + * This function is used to change the mode of a device from reporting + * relative motion to reporting absolute positional information, and + * vice versa. + * The default implementation below is that no such devices are supported. + * + *********************************************************************** + */ + +int +SetDeviceMode (ClientPtr client, DeviceIntPtr dev, int mode) +{ + InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate; + + if (pInfo->switch_mode) { + return (*pInfo->switch_mode)(client, dev, mode); + } + else + return BadMatch; +} + + +/*********************************************************************** + * + * Caller: ProcXSetDeviceValuators + * + * Set the value of valuators on an extension input device. + * This function is used to set the initial value of valuators on + * those input devices that are capable of reporting either relative + * motion or an absolute position, and allow an initial position to be set. + * The default implementation below is that no such devices are supported. + * + *********************************************************************** + */ + +int +SetDeviceValuators (ClientPtr client, DeviceIntPtr dev, int *valuators, + int first_valuator, int num_valuators) +{ + InputInfoPtr pInfo = (InputInfoPtr) dev->public.devicePrivate; + + if (pInfo->set_device_valuators) + return (*pInfo->set_device_valuators)(pInfo, valuators, first_valuator, + num_valuators); + + return BadMatch; +} + + +/*********************************************************************** + * + * Caller: ProcXChangeDeviceControl + * + * Change the specified device controls on an extension input device. + * + *********************************************************************** + */ + +int +ChangeDeviceControl (ClientPtr client, DeviceIntPtr dev, xDeviceCtl *control) +{ + InputInfoPtr pInfo = (InputInfoPtr)dev->public.devicePrivate; + + if (!pInfo->control_proc) { + switch (control->control) { + case DEVICE_CORE: + case DEVICE_ABS_CALIB: + case DEVICE_ABS_AREA: + return BadMatch; + case DEVICE_RESOLUTION: + case DEVICE_ENABLE: + return Success; + default: + return BadMatch; + } + } + else { + return (*pInfo->control_proc)(pInfo, control); + } +} + +/* + * Get the operating system name from uname and store it statically to avoid + * repeating the system call each time MatchOS is checked. + */ +static const char * +HostOS(void) +{ +#ifdef HAVE_SYS_UTSNAME_H + struct utsname name; + static char host_os[sizeof(name.sysname)] = ""; + + if (*host_os == '\0') { + if (uname(&name) >= 0) + strcpy(host_os, name.sysname); + else { + strncpy(host_os, "unknown", sizeof(host_os)); + host_os[sizeof(host_os)-1] = '\0'; + } + } + return host_os; +#else + return ""; +#endif +} + +static int +match_substring(const char *attr, const char *pattern) +{ + return (strstr(attr, pattern)) ? 0 : -1; +} + +#ifdef HAVE_FNMATCH_H +static int +match_pattern(const char *attr, const char *pattern) +{ + return fnmatch(pattern, attr, 0); +} +#else +#define match_pattern match_substring +#endif + +#ifdef HAVE_FNMATCH_H +static int +match_path_pattern(const char *attr, const char *pattern) +{ + return fnmatch(pattern, attr, FNM_PATHNAME); +} +#else +#define match_path_pattern match_substring +#endif + +/* + * If no Layout section is found, xf86ServerLayout.id becomes "(implicit)" + * It is convenient that "" in patterns means "no explicit layout" + */ +static int +match_string_implicit(const char *attr, const char *pattern) +{ + if (strlen(pattern)) { + return strcmp(attr, pattern); + } else { + return strcmp(attr,"(implicit)"); + } +} + +/* + * Match an attribute against a list of NULL terminated arrays of patterns. + * If a pattern in each list entry is matched, return TRUE. + */ +static Bool +MatchAttrToken(const char *attr, struct list *patterns, + int (*compare)(const char *attr, const char *pattern)) +{ + const xf86MatchGroup *group; + + /* If there are no patterns, accept the match */ + if (list_is_empty(patterns)) + return TRUE; + + /* If there are patterns but no attribute, reject the match */ + if (!attr) + return FALSE; + + /* + * Otherwise, iterate the list of patterns ensuring each entry has a + * match. Each list entry is a separate Match line of the same type. + */ + list_for_each_entry(group, patterns, entry) { + char * const *cur; + Bool match = FALSE; + + for (cur = group->values; *cur; cur++) + if ((*compare)(attr, *cur) == 0) { + match = TRUE; + break; + } + if (!match) + return FALSE; + } + + /* All the entries in the list matched the attribute */ + return TRUE; +} + +/* + * Classes without any Match statements match all devices. Otherwise, all + * statements must match. + */ +static Bool +InputClassMatches(const XF86ConfInputClassPtr iclass, const InputInfoPtr idev, + const InputAttributes *attrs) +{ + /* MatchProduct substring */ + if (!MatchAttrToken(attrs->product, &iclass->match_product, match_substring)) + return FALSE; + + /* MatchVendor substring */ + if (!MatchAttrToken(attrs->vendor, &iclass->match_vendor, match_substring)) + return FALSE; + + /* MatchDevicePath pattern */ + if (!MatchAttrToken(attrs->device, &iclass->match_device, match_path_pattern)) + return FALSE; + + /* MatchOS case-insensitive string */ + if (!MatchAttrToken(HostOS(), &iclass->match_os, strcasecmp)) + return FALSE; + + /* MatchPnPID pattern */ + if (!MatchAttrToken(attrs->pnp_id, &iclass->match_pnpid, match_pattern)) + return FALSE; + + /* MatchUSBID pattern */ + if (!MatchAttrToken(attrs->usb_id, &iclass->match_usbid, match_pattern)) + return FALSE; + + /* MatchDriver string */ + if (!MatchAttrToken(idev->driver, &iclass->match_driver, strcmp)) + return FALSE; + + /* + * MatchTag string + * See if any of the device's tags match any of the MatchTag tokens. + */ + if (!list_is_empty(&iclass->match_tag)) { + char * const *tag; + Bool match; + + if (!attrs->tags) + return FALSE; + for (tag = attrs->tags, match = FALSE; *tag; tag++) { + if (MatchAttrToken(*tag, &iclass->match_tag, strcmp)) { + match = TRUE; + break; + } + } + if (!match) + return FALSE; + } + + /* MatchLayout string */ + if (!list_is_empty(&iclass->match_layout)) { + if (!MatchAttrToken(xf86ConfigLayout.id, + &iclass->match_layout, match_string_implicit)) + return FALSE; + } + + /* MatchIs* booleans */ + if (iclass->is_keyboard.set && + iclass->is_keyboard.val != !!(attrs->flags & ATTR_KEYBOARD)) + return FALSE; + if (iclass->is_pointer.set && + iclass->is_pointer.val != !!(attrs->flags & ATTR_POINTER)) + return FALSE; + if (iclass->is_joystick.set && + iclass->is_joystick.val != !!(attrs->flags & ATTR_JOYSTICK)) + return FALSE; + if (iclass->is_tablet.set && + iclass->is_tablet.val != !!(attrs->flags & ATTR_TABLET)) + return FALSE; + if (iclass->is_touchpad.set && + iclass->is_touchpad.val != !!(attrs->flags & ATTR_TOUCHPAD)) + return FALSE; + if (iclass->is_touchscreen.set && + iclass->is_touchscreen.val != !!(attrs->flags & ATTR_TOUCHSCREEN)) + return FALSE; + + return TRUE; +} + +/* + * Merge in any InputClass configurations. Options in each InputClass + * section have more priority than the original device configuration as + * well as any previous InputClass sections. + */ +static int +MergeInputClasses(const InputInfoPtr idev, const InputAttributes *attrs) +{ + XF86ConfInputClassPtr cl; + XF86OptionPtr classopts; + + for (cl = xf86configptr->conf_inputclass_lst; cl; cl = cl->list.next) { + if (!InputClassMatches(cl, idev, attrs)) + continue; + + /* Collect class options and driver settings */ + classopts = xf86optionListDup(cl->option_lst); + if (cl->driver) { + free(idev->driver); + idev->driver = xstrdup(cl->driver); + if (!idev->driver) { + xf86Msg(X_ERROR, "Failed to allocate memory while merging " + "InputClass configuration"); + return BadAlloc; + } + classopts = xf86ReplaceStrOption(classopts, "driver", + idev->driver); + } + + /* Apply options to device with InputClass settings preferred. */ + xf86Msg(X_CONFIG, "%s: Applying InputClass \"%s\"\n", + idev->name, cl->identifier); + idev->options = xf86optionListMerge(idev->options, classopts); + } + + return Success; +} + +/* + * Iterate the list of classes and look for Option "Ignore". Return the + * value of the last matching class and holler when returning TRUE. + */ +static Bool +IgnoreInputClass(const InputInfoPtr idev, const InputAttributes *attrs) +{ + XF86ConfInputClassPtr cl; + Bool ignore = FALSE; + const char *ignore_class; + + for (cl = xf86configptr->conf_inputclass_lst; cl; cl = cl->list.next) { + if (!InputClassMatches(cl, idev, attrs)) + continue; + if (xf86findOption(cl->option_lst, "Ignore")) { + ignore = xf86CheckBoolOption(cl->option_lst, "Ignore", FALSE); + ignore_class = cl->identifier; + } + } + + if (ignore) + xf86Msg(X_CONFIG, "%s: Ignoring device from InputClass \"%s\"\n", + idev->name, ignore_class); + return ignore; +} + +InputInfoPtr +xf86AllocateInput(void) +{ + InputInfoPtr pInfo; + + pInfo = calloc(sizeof(*pInfo), 1); + if (!pInfo) + return NULL; + + pInfo->fd = -1; + pInfo->type_name = "UNKNOWN"; + + return pInfo; +} + +/* Append InputInfoRec to the tail of xf86InputDevs. */ +static void +xf86AddInput(InputDriverPtr drv, InputInfoPtr pInfo) +{ + InputInfoPtr *prev = NULL; + + pInfo->drv = drv; + pInfo->module = DuplicateModule(drv->module, NULL); + + for (prev = &xf86InputDevs; *prev; prev = &(*prev)->next) + ; + + *prev = pInfo; + pInfo->next = NULL; + + xf86CollectInputOptions(pInfo, (const char**)drv->default_options); + xf86OptionListReport(pInfo->options); + xf86ProcessCommonOptions(pInfo, pInfo->options); +} + +/* + * Remove an entry from xf86InputDevs and free all the device's information. + */ +void +xf86DeleteInput(InputInfoPtr pInp, int flags) +{ + /* First check if the inputdev is valid. */ + if (pInp == NULL) + return; + + if (pInp->module) + UnloadModule(pInp->module); + + /* This should *really* be handled in drv->UnInit(dev) call instead, but + * if the driver forgets about it make sure we free it or at least crash + * with flying colors */ + free(pInp->private); + + FreeInputAttributes(pInp->attrs); + + /* Remove the entry from the list. */ + if (pInp == xf86InputDevs) + xf86InputDevs = pInp->next; + else { + InputInfoPtr p = xf86InputDevs; + while (p && p->next != pInp) + p = p->next; + if (p) + p->next = pInp->next; + /* Else the entry wasn't in the xf86InputDevs list (ignore this). */ + } + + free(pInp->driver); + free(pInp->name); + xf86optionListFree(pInp->options); + free(pInp); +} + +/* + * Apply backend-specific initialization. Invoked after ActiveteDevice(), + * i.e. after the driver successfully completed DEVICE_INIT and the device + * is advertised. + * @param dev the device + * @return Success or an error code + */ +static int +xf86InputDevicePostInit(DeviceIntPtr dev) { + ApplyAccelerationSettings(dev); + return Success; +} + +/** + * Create a new input device, activate and enable it. + * + * Possible return codes: + * BadName .. a bad driver name was supplied. + * BadImplementation ... The driver does not have a PreInit function. This + * is a driver bug. + * BadMatch .. device initialization failed. + * BadAlloc .. too many input devices + * + * @param idev The device, already set up with identifier, driver, and the + * options. + * @param pdev Pointer to the new device, if Success was reported. + * @param enable Enable the device after activating it. + * + * @return Success or an error code + */ +_X_INTERNAL int +xf86NewInputDevice(InputInfoPtr pInfo, DeviceIntPtr *pdev, BOOL enable) +{ + InputDriverPtr drv = NULL; + DeviceIntPtr dev = NULL; + int rval; + + /* Memory leak for every attached device if we don't + * test if the module is already loaded first */ + drv = xf86LookupInputDriver(pInfo->driver); + if (!drv) + if (xf86LoadOneModule(pInfo->driver, NULL)) + drv = xf86LookupInputDriver(pInfo->driver); + if (!drv) { + xf86Msg(X_ERROR, "No input driver matching `%s'\n", pInfo->driver); + rval = BadName; + goto unwind; + } + + xf86Msg(X_INFO, "Using input driver '%s' for '%s'\n", drv->driverName, pInfo->name); + + if (!drv->PreInit) { + xf86Msg(X_ERROR, + "Input driver `%s' has no PreInit function (ignoring)\n", + drv->driverName); + rval = BadImplementation; + goto unwind; + } + + xf86AddInput(drv, pInfo); + + rval = drv->PreInit(drv, pInfo, 0); + + if (rval != Success) { + xf86Msg(X_ERROR, "PreInit returned %d for \"%s\"\n", rval, pInfo->name); + goto unwind; + } + + if (!(dev = xf86ActivateDevice(pInfo))) + { + rval = BadAlloc; + goto unwind; + } + + rval = ActivateDevice(dev, TRUE); + if (rval != Success) + { + xf86Msg(X_ERROR, "Couldn't init device \"%s\"\n", pInfo->name); + RemoveDevice(dev, TRUE); + goto unwind; + } + + rval = xf86InputDevicePostInit(dev); + if (rval != Success) + { + xf86Msg(X_ERROR, "Couldn't post-init device \"%s\"\n", pInfo->name); + RemoveDevice(dev, TRUE); + goto unwind; + } + + /* Enable it if it's properly initialised and we're currently in the VT */ + if (enable && dev->inited && dev->startup && xf86Screens[0]->vtSema) + { + OsBlockSignals(); + EnableDevice(dev, TRUE); + if (!dev->enabled) + { + OsReleaseSignals(); + xf86Msg(X_ERROR, "Couldn't init device \"%s\"\n", pInfo->name); + RemoveDevice(dev, TRUE); + rval = BadMatch; + goto unwind; + } + /* send enter/leave event, update sprite window */ + CheckMotion(NULL, dev); + OsReleaseSignals(); + } + + *pdev = dev; + return Success; + +unwind: + if(pInfo) { + if(drv && drv->UnInit) + drv->UnInit(drv, pInfo, 0); + else + xf86DeleteInput(pInfo, 0); + } + return rval; +} + +int +NewInputDeviceRequest (InputOption *options, InputAttributes *attrs, + DeviceIntPtr *pdev) +{ + InputInfoPtr pInfo = NULL; + InputOption *option = NULL; + int rval = Success; + int is_auto = 0; + + pInfo = xf86AllocateInput(); + if (!pInfo) + return BadAlloc; + + for (option = options; option; option = option->next) { + if (strcasecmp(option->key, "driver") == 0) { + if (pInfo->driver) { + rval = BadRequest; + goto unwind; + } + pInfo->driver = xstrdup(option->value); + if (!pInfo->driver) { + rval = BadAlloc; + goto unwind; + } + } + + if (strcasecmp(option->key, "name") == 0 || + strcasecmp(option->key, "identifier") == 0) { + if (pInfo->name) { + rval = BadRequest; + goto unwind; + } + pInfo->name = xstrdup(option->value); + if (!pInfo->name) { + rval = BadAlloc; + goto unwind; + } + } + + if (strcmp(option->key, "_source") == 0 && + (strcmp(option->value, "server/hal") == 0 || + strcmp(option->value, "server/udev") == 0)) { + is_auto = 1; + if (!xf86Info.autoAddDevices) { + rval = BadMatch; + goto unwind; + } + } + } + + for (option = options; option; option = option->next) { + /* Steal option key/value strings from the provided list. + * We need those strings, the InputOption list doesn't. */ + pInfo->options = xf86addNewOption(pInfo->options, + option->key, option->value); + option->key = NULL; + option->value = NULL; + } + + /* Apply InputClass settings */ + if (attrs) { + if (IgnoreInputClass(pInfo, attrs)) { + rval = BadIDChoice; + goto unwind; + } + + rval = MergeInputClasses(pInfo, attrs); + if (rval != Success) + goto unwind; + + pInfo->attrs = DuplicateInputAttributes(attrs); + } + + if (!pInfo->driver || !pInfo->name) { + xf86Msg(X_INFO, "No input driver/identifier specified (ignoring)\n"); + rval = BadRequest; + goto unwind; + } + + if (!pInfo->name) { + xf86Msg(X_ERROR, "No device identifier specified (ignoring)\n"); + rval = BadMatch; + goto unwind; + } + + rval = xf86NewInputDevice(pInfo, pdev, + (!is_auto || (is_auto && xf86Info.autoEnableDevices))); + + return rval; + +unwind: + if (is_auto && !xf86Info.autoAddDevices) + xf86Msg(X_INFO, "AutoAddDevices is off - not adding device.\n"); + xf86DeleteInput(pInfo, 0); + return rval; +} + +void +DeleteInputDeviceRequest(DeviceIntPtr pDev) +{ + InputInfoPtr pInfo = (InputInfoPtr) pDev->public.devicePrivate; + InputDriverPtr drv = NULL; + Bool isMaster = IsMaster(pDev); + + if (pInfo) /* need to get these before RemoveDevice */ + drv = pInfo->drv; + + OsBlockSignals(); + RemoveDevice(pDev, TRUE); + + if (!isMaster && pInfo != NULL) + { + if(drv->UnInit) + drv->UnInit(drv, pInfo, 0); + else + xf86DeleteInput(pInfo, 0); + } + OsReleaseSignals(); +} + +/* + * convenient functions to post events + */ + +void +xf86PostMotionEvent(DeviceIntPtr device, + int is_absolute, + int first_valuator, + int num_valuators, + ...) +{ + va_list var; + int i = 0; + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_zero(&mask); + va_start(var, num_valuators); + for (i = 0; i < num_valuators; i++) + valuator_mask_set(&mask, first_valuator + i, va_arg(var, int)); + va_end(var); + + xf86PostMotionEventM(device, is_absolute, &mask); +} + +void +xf86PostMotionEventP(DeviceIntPtr device, + int is_absolute, + int first_valuator, + int num_valuators, + const int *valuators) +{ + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators); + xf86PostMotionEventM(device, is_absolute, &mask); +} + +void +xf86PostMotionEventM(DeviceIntPtr device, + int is_absolute, + const ValuatorMask *mask) +{ + int flags = 0; + + if (valuator_mask_num_valuators(mask) > 0) + { + if (is_absolute) + flags = POINTER_ABSOLUTE; + else + flags = POINTER_RELATIVE | POINTER_ACCELERATE; + } + +#if XFreeXDGA + /* The evdev driver may not always send all axes across. */ + if (valuator_mask_isset(mask, 0) || + valuator_mask_isset(mask, 1)) + if (miPointerGetScreen(device)) { + int index = miPointerGetScreen(device)->myNum; + int dx = 0, dy = 0; + + if (valuator_mask_isset(mask, 0)) + { + dx = valuator_mask_get(mask, 0); + if (is_absolute) + dx -= device->last.valuators[0]; + } + + if (valuator_mask_isset(mask, 1)) + { + dy = valuator_mask_get(mask, 1); + if (is_absolute) + dy -= device->last.valuators[1]; + } + + if (DGAStealMotionEvent(device, index, dx, dy)) + return; + } +#endif + + QueuePointerEvents(device, MotionNotify, 0, flags, mask); +} + +void +xf86PostProximityEvent(DeviceIntPtr device, + int is_in, + int first_valuator, + int num_valuators, + ...) +{ + va_list var; + int i; + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_zero(&mask); + va_start(var, num_valuators); + for (i = 0; i < num_valuators; i++) + valuator_mask_set(&mask, first_valuator + i, va_arg(var, int)); + va_end(var); + + xf86PostProximityEventM(device, is_in, &mask); +} + +void +xf86PostProximityEventP(DeviceIntPtr device, + int is_in, + int first_valuator, + int num_valuators, + const int *valuators) +{ + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators); + xf86PostProximityEventM(device, is_in, &mask); +} + +void +xf86PostProximityEventM(DeviceIntPtr device, + int is_in, + const ValuatorMask *mask) +{ + QueueProximityEvents(device, is_in ? ProximityIn : ProximityOut, mask); +} + +void +xf86PostButtonEvent(DeviceIntPtr device, + int is_absolute, + int button, + int is_down, + int first_valuator, + int num_valuators, + ...) +{ + va_list var; + ValuatorMask mask; + int i = 0; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_zero(&mask); + + va_start(var, num_valuators); + for (i = 0; i < num_valuators; i++) + valuator_mask_set(&mask, first_valuator + i, va_arg(var, int)); + va_end(var); + + xf86PostButtonEventM(device, is_absolute, button, is_down, &mask); +} + +void +xf86PostButtonEventP(DeviceIntPtr device, + int is_absolute, + int button, + int is_down, + int first_valuator, + int num_valuators, + const int *valuators) +{ + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators); + xf86PostButtonEventM(device, is_absolute, button, is_down, &mask); +} + +void +xf86PostButtonEventM(DeviceIntPtr device, + int is_absolute, + int button, + int is_down, + const ValuatorMask *mask) +{ + int flags = 0; + + if (valuator_mask_num_valuators(mask) > 0) + { + if (is_absolute) + flags = POINTER_ABSOLUTE; + else + flags = POINTER_RELATIVE | POINTER_ACCELERATE; + } + +#if XFreeXDGA + if (miPointerGetScreen(device)) { + int index = miPointerGetScreen(device)->myNum; + + if (DGAStealButtonEvent(device, index, button, is_down)) + return; + } +#endif + + QueuePointerEvents(device, + is_down ? ButtonPress : ButtonRelease, button, + flags, mask); +} + +void +xf86PostKeyEvent(DeviceIntPtr device, + unsigned int key_code, + int is_down, + int is_absolute, + int first_valuator, + int num_valuators, + ...) +{ + va_list var; + int i = 0; + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_zero(&mask); + + va_start(var, num_valuators); + for (i = 0; i < num_valuators; i++) + valuator_mask_set(&mask, first_valuator + i, va_arg(var, int)); + va_end(var); + + xf86PostKeyEventM(device, key_code, is_down, is_absolute, &mask); +} + +void +xf86PostKeyEventP(DeviceIntPtr device, + unsigned int key_code, + int is_down, + int is_absolute, + int first_valuator, + int num_valuators, + const int *valuators) +{ + ValuatorMask mask; + + XI_VERIFY_VALUATORS(num_valuators); + + valuator_mask_set_range(&mask, first_valuator, num_valuators, valuators); + xf86PostKeyEventM(device, key_code, is_down, is_absolute, &mask); +} + +void +xf86PostKeyEventM(DeviceIntPtr device, + unsigned int key_code, + int is_down, + int is_absolute, + const ValuatorMask *mask) +{ +#if XFreeXDGA + DeviceIntPtr pointer; + + /* Some pointers send key events, paired device is wrong then. */ + pointer = IsPointerDevice(device) ? device : GetPairedDevice(device); + if (miPointerGetScreen(pointer)) { + int index = miPointerGetScreen(pointer)->myNum; + + if (DGAStealKeyEvent(device, index, key_code, is_down)) + return; + } +#endif + + QueueKeyboardEvents(device, + is_down ? KeyPress : KeyRelease, + key_code, mask); +} + +void +xf86PostKeyboardEvent(DeviceIntPtr device, + unsigned int key_code, + int is_down) +{ + ValuatorMask mask; + + valuator_mask_zero(&mask); + xf86PostKeyEventM(device, key_code, is_down, 0, &mask); +} + +InputInfoPtr +xf86FirstLocalDevice(void) +{ + return xf86InputDevs; +} + +/* + * Cx - raw data from touch screen + * to_max - scaled highest dimension + * (remember, this is of rows - 1 because of 0 origin) + * to_min - scaled lowest dimension + * from_max - highest raw value from touch screen calibration + * from_min - lowest raw value from touch screen calibration + * + * This function is the same for X or Y coordinates. + * You may have to reverse the high and low values to compensate for + * different orgins on the touch screen vs X. + * + * e.g. to scale from device coordinates into screen coordinates, call + * xf86ScaleAxis(x, 0, screen_width, dev_min, dev_max); + */ + +int +xf86ScaleAxis(int Cx, + int to_max, + int to_min, + int from_max, + int from_min ) +{ + int X; + int64_t to_width = to_max - to_min; + int64_t from_width = from_max - from_min; + + if (from_width) { + X = (int)(((to_width * (Cx - from_min)) / from_width) + to_min); + } + else { + X = 0; + ErrorF ("Divide by Zero in xf86ScaleAxis\n"); + } + + if (X > to_max) + X = to_max; + if (X < to_min) + X = to_min; + + return X; +} + +/* + * This function checks the given screen against the current screen and + * makes changes if appropriate. It should be called from an XInput driver's + * ReadInput function before any events are posted, if the device is screen + * specific like a touch screen. + */ +void +xf86XInputSetScreen(InputInfoPtr pInfo, + int screen_number, + int x, + int y) +{ + if (miPointerGetScreen(pInfo->dev) != + screenInfo.screens[screen_number]) { + miPointerSetScreen(pInfo->dev, screen_number, x, y); + } +} + + +void +xf86InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval, int maxval, + int resolution, int min_res, int max_res, int mode) +{ + if (!dev || !dev->valuator) + return; + + InitValuatorAxisStruct(dev, axnum, label, minval, maxval, resolution, min_res, + max_res, mode); +} + +/* + * Set the valuator values to be in synch with dix/event.c + * DefineInitialRootWindow(). + */ +void +xf86InitValuatorDefaults(DeviceIntPtr dev, int axnum) +{ + if (axnum == 0) { + dev->valuator->axisVal[0] = screenInfo.screens[0]->width / 2; + dev->last.valuators[0] = dev->valuator->axisVal[0]; + } + else if (axnum == 1) { + dev->valuator->axisVal[1] = screenInfo.screens[0]->height / 2; + dev->last.valuators[1] = dev->valuator->axisVal[1]; + } +} + + +/** + * Deactivate a device. Call this function from the driver if you receive a + * read error or something else that spoils your day. + * Device will be moved to the off_devices list, but it will still be there + * until you really clean up after it. + * Notifies the client about an inactive device. + * + * @param panic True if device is unrecoverable and needs to be removed. + */ +void +xf86DisableDevice(DeviceIntPtr dev, Bool panic) +{ + if(!panic) + { + DisableDevice(dev, TRUE); + } else + { + SendDevicePresenceEvent(dev->id, DeviceUnrecoverable); + DeleteInputDeviceRequest(dev); + } +} + +/** + * Reactivate a device. Call this function from the driver if you just found + * out that the read error wasn't quite that bad after all. + * Device will be re-activated, and an event sent to the client. + */ +void +xf86EnableDevice(DeviceIntPtr dev) +{ + EnableDevice(dev, TRUE); +} + +/* end of xf86Xinput.c */ diff --git a/xorg-server/hw/xfree86/common/xf86sbusBus.c b/xorg-server/hw/xfree86/common/xf86sbusBus.c index 6e6ab948f..181c6ab00 100644 --- a/xorg-server/hw/xfree86/common/xf86sbusBus.c +++ b/xorg-server/hw/xfree86/common/xf86sbusBus.c @@ -1,714 +1,714 @@ -/*
- * SBUS bus-specific code.
- *
- * Copyright (C) 2000 Jakub Jelinek (jakub@redhat.com)
- *
- * 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
- * JAKUB JELINEK 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.
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <ctype.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <X11/X.h>
-#include "os.h"
-#include "xf86.h"
-#include "xf86Priv.h"
-#include "xf86_OSlib.h"
-#include "xf86cmap.h"
-
-#include "xf86Bus.h"
-
-#include "xf86sbusBus.h"
-#include "xf86Sbus.h"
-
-Bool sbusSlotClaimed = FALSE;
-
-static int xf86nSbusInfo;
-
-static void
-CheckSbusDevice(const char *device, int fbNum)
-{
- int fd, i;
- struct fbgattr fbattr;
- sbusDevicePtr psdp;
-
- fd = open(device, O_RDONLY, 0);
- if (fd < 0)
- return;
- memset(&fbattr, 0, sizeof(fbattr));
- if (ioctl(fd, FBIOGATTR, &fbattr) < 0) {
- if (ioctl(fd, FBIOGTYPE, &fbattr.fbtype) < 0) {
- close(fd);
- return;
- }
- }
- close(fd);
- for (i = 0; sbusDeviceTable[i].devId; i++)
- if (sbusDeviceTable[i].fbType == fbattr.fbtype.fb_type)
- break;
- if (! sbusDeviceTable[i].devId)
- return;
- xf86SbusInfo = xnfrealloc(xf86SbusInfo, sizeof(psdp) * (++xf86nSbusInfo + 1));
- xf86SbusInfo[xf86nSbusInfo] = NULL;
- xf86SbusInfo[xf86nSbusInfo - 1] = psdp = xnfcalloc(sizeof (sbusDevice), 1);
- psdp->devId = sbusDeviceTable[i].devId;
- psdp->fbNum = fbNum;
- psdp->device = xnfstrdup(device);
- psdp->width = fbattr.fbtype.fb_width;
- psdp->height = fbattr.fbtype.fb_height;
- psdp->fd = -1;
-}
-
-void
-xf86SbusProbe(void)
-{
- int i, useProm = 0;
- char fbDevName[32];
- sbusDevicePtr psdp, *psdpp;
-
- xf86SbusInfo = malloc(sizeof(psdp));
- *xf86SbusInfo = NULL;
- for (i = 0; i < 32; i++) {
- sprintf(fbDevName, "/dev/fb%d", i);
- CheckSbusDevice(fbDevName, i);
- }
- if (sparcPromInit() >= 0) {
- useProm = 1;
- sparcPromAssignNodes();
- }
- for (psdpp = xf86SbusInfo; (psdp = *psdpp); psdpp++) {
- for (i = 0; sbusDeviceTable[i].devId; i++)
- if (sbusDeviceTable[i].devId == psdp->devId)
- psdp->descr = sbusDeviceTable[i].descr;
- /*
- * If we can use PROM information and found the PROM node for this
- * device, we can tell more about the card.
- */
- if (useProm && psdp->node.node) {
- char *prop, *promPath;
- int len, chiprev, vmsize;
-
- switch (psdp->devId) {
- case SBUS_DEVICE_MGX:
- prop = sparcPromGetProperty(&psdp->node, "fb_size", &len);
- if (prop && len == 4 && *(int *)prop == 0x400000)
- psdp->descr = "Quantum 3D MGXplus with 4M VRAM";
- break;
- case SBUS_DEVICE_CG6:
- chiprev = 0;
- vmsize = 0;
- prop = sparcPromGetProperty(&psdp->node, "chiprev", &len);
- if (prop && len == 4)
- chiprev = *(int *)prop;
- prop = sparcPromGetProperty(&psdp->node, "vmsize", &len);
- if (prop && len == 4)
- vmsize = *(int *)prop;
- switch (chiprev) {
- case 1:
- case 2:
- case 3:
- case 4:
- psdp->descr = "Sun Double width GX"; break;
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- psdp->descr = "Sun Single width GX"; break;
- case 11:
- switch (vmsize) {
- case 2:
- psdp->descr = "Sun Turbo GX with 1M VSIMM"; break;
- case 4:
- psdp->descr = "Sun Turbo GX Plus"; break;
- default:
- psdp->descr = "Sun Turbo GX"; break;
- }
- }
- break;
- case SBUS_DEVICE_CG14:
- prop = sparcPromGetProperty(&psdp->node, "reg", &len);
- vmsize = 0;
- if (prop && !(len % 12) && len > 0)
- vmsize = *(int *)(prop + len - 4);
- switch (vmsize) {
- case 0x400000:
- psdp->descr = "Sun SX with 4M VSIMM"; break;
- case 0x800000:
- psdp->descr = "Sun SX with 8M VSIMM"; break;
- }
- break;
- case SBUS_DEVICE_LEO:
- prop = sparcPromGetProperty(&psdp->node, "model", &len);
- if (prop && len > 0 && !strstr(prop, "501-2503"))
- psdp->descr = "Sun Turbo ZX";
- break;
- case SBUS_DEVICE_TCX:
- if (sparcPromGetBool(&psdp->node, "tcx-8-bit"))
- psdp->descr = "Sun TCX (8bit)";
- else
- psdp->descr = "Sun TCX (S24)";
- break;
- case SBUS_DEVICE_FFB:
- prop = sparcPromGetProperty(&psdp->node, "name", &len);
- chiprev = 0;
- prop = sparcPromGetProperty(&psdp->node, "board_type", &len);
- if (prop && len == 4)
- chiprev = *(int *)prop;
- if (strstr (prop, "afb")) {
- if (chiprev == 3)
- psdp->descr = "Sun|Elite3D-M6 Horizontal";
- } else {
- switch (chiprev) {
- case 0x08:
- psdp->descr = "Sun FFB 67MHz Creator"; break;
- case 0x0b:
- psdp->descr = "Sun FFB 67MHz Creator 3D"; break;
- case 0x1b:
- psdp->descr = "Sun FFB 75MHz Creator 3D"; break;
- case 0x20:
- case 0x28:
- psdp->descr = "Sun FFB2 Vertical Creator"; break;
- case 0x23:
- case 0x2b:
- psdp->descr = "Sun FFB2 Vertical Creator 3D"; break;
- case 0x30:
- psdp->descr = "Sun FFB2+ Vertical Creator"; break;
- case 0x33:
- psdp->descr = "Sun FFB2+ Vertical Creator 3D"; break;
- case 0x40:
- case 0x48:
- psdp->descr = "Sun FFB2 Horizontal Creator"; break;
- case 0x43:
- case 0x4b:
- psdp->descr = "Sun FFB2 Horizontal Creator 3D"; break;
- }
- }
- break;
- }
-
- xf86Msg(X_PROBED, "SBUS:(0x%08x) %s", psdp->node.node, psdp->descr);
- promPath = sparcPromNode2Pathname (&psdp->node);
- if (promPath) {
- xf86ErrorF(" at %s", promPath);
- free(promPath);
- }
- } else
- xf86Msg(X_PROBED, "SBUS: %s", psdp->descr);
- xf86ErrorF("\n");
- }
- if (useProm)
- sparcPromClose();
-}
-
-/*
- * Parse a BUS ID string, and return the SBUS bus parameters if it was
- * in the correct format for a SBUS bus id.
- */
-
-Bool
-xf86ParseSbusBusString(const char *busID, int *fbNum)
-{
- /*
- * The format is assumed to be one of:
- * "fbN", e.g. "fb1", which means the device corresponding to /dev/fbN
- * "nameN", e.g. "cgsix0", which means Nth instance of card NAME
- * "/prompath", e.g. "/sbus@0,10001000/cgsix@3,0" which is PROM pathname
- * to the device.
- */
-
- const char *id;
- int i, len;
-
- if (StringToBusType(busID, &id) != BUS_SBUS)
- return FALSE;
-
- if (*id != '/') {
- if (!strncmp (id, "fb", 2)) {
- if (!isdigit(id[2]))
- return FALSE;
- *fbNum = atoi(id + 2);
- return TRUE;
- } else {
- sbusDevicePtr *psdpp;
- int devId;
-
- for (i = 0, len = 0; sbusDeviceTable[i].devId; i++) {
- len = strlen(sbusDeviceTable[i].promName);
- if (!strncmp (sbusDeviceTable[i].promName, id, len)
- && isdigit(id[len]))
- break;
- }
- devId = sbusDeviceTable[i].devId;
- if (!devId) return FALSE;
- i = atoi(id + len);
- for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) {
- if ((*psdpp)->devId != devId)
- continue;
- if (!i) {
- *fbNum = (*psdpp)->fbNum;
- return TRUE;
- }
- i--;
- }
- }
- return FALSE;
- }
-
- if (sparcPromInit() >= 0) {
- i = sparcPromPathname2Node(id);
- sparcPromClose();
- if (i) {
- sbusDevicePtr *psdpp;
- for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) {
- if ((*psdpp)->node.node == i) {
- *fbNum = (*psdpp)->fbNum;
- return TRUE;
- }
- }
- }
- }
- return FALSE;
-}
-
-/*
- * Compare a BUS ID string with a SBUS bus id. Return TRUE if they match.
- */
-
-Bool
-xf86CompareSbusBusString(const char *busID, int fbNum)
-{
- int iFbNum;
-
- if (xf86ParseSbusBusString(busID, &iFbNum)) {
- return fbNum == iFbNum;
- } else {
- return FALSE;
- }
-}
-
-/*
- * Check if the slot requested is free. If it is already in use, return FALSE.
- */
-
-Bool
-xf86CheckSbusSlot(int fbNum)
-{
- int i;
- EntityPtr p;
-
- for (i = 0; i < xf86NumEntities; i++) {
- p = xf86Entities[i];
- /* Check if this SBUS slot is taken */
- if (p->bus.type == BUS_SBUS && p->bus.id.sbus.fbNum == fbNum)
- return FALSE;
- }
-
- return TRUE;
-}
-
-/*
- * If the slot requested is already in use, return -1.
- * Otherwise, claim the slot for the screen requesting it.
- */
-
-int
-xf86ClaimSbusSlot(sbusDevicePtr psdp, DriverPtr drvp,
- GDevPtr dev, Bool active)
-{
- EntityPtr p = NULL;
-
- int num;
-
- if (xf86CheckSbusSlot(psdp->fbNum)) {
- num = xf86AllocateEntity();
- p = xf86Entities[num];
- p->driver = drvp;
- p->chipset = -1;
- p->bus.type = BUS_SBUS;
- xf86AddDevToEntity(num, dev);
- p->bus.id.sbus.fbNum = psdp->fbNum;
- p->active = active;
- p->inUse = FALSE;
- sbusSlotClaimed = TRUE;
- return num;
- } else
- return -1;
-}
-
-int
-xf86MatchSbusInstances(const char *driverName, int sbusDevId,
- GDevPtr *devList, int numDevs, DriverPtr drvp,
- int **foundEntities)
-{
- int i,j;
- sbusDevicePtr psdp, *psdpp;
- int numClaimedInstances = 0;
- int allocatedInstances = 0;
- int numFound = 0;
- GDevPtr devBus = NULL;
- GDevPtr dev = NULL;
- int *retEntities = NULL;
- int useProm = 0;
-
- struct Inst {
- sbusDevicePtr sbus;
- GDevPtr dev;
- Bool claimed; /* BusID matches with a device section */
- } *instances = NULL;
-
- *foundEntities = NULL;
- for (psdpp = xf86SbusInfo, psdp = *psdpp; psdp; psdp = *++psdpp) {
- if (psdp->devId != sbusDevId)
- continue;
- if (psdp->fd == -2)
- continue;
- ++allocatedInstances;
- instances = xnfrealloc(instances,
- allocatedInstances * sizeof(struct Inst));
- instances[allocatedInstances - 1].sbus = psdp;
- instances[allocatedInstances - 1].dev = NULL;
- instances[allocatedInstances - 1].claimed = FALSE;
- numFound++;
- }
-
- /*
- * This may be debatable, but if no SBUS devices with a matching vendor
- * type is found, return zero now. It is probably not desirable to
- * allow the config file to override this.
- */
- if (allocatedInstances <= 0) {
- free(instances);
- return 0;
- }
-
- if (sparcPromInit() >= 0)
- useProm = 1;
-
- if (xf86DoConfigure && xf86DoConfigurePass1) {
- GDevPtr pGDev;
- int actualcards = 0;
- for (i = 0; i < allocatedInstances; i++) {
- actualcards++;
- pGDev = xf86AddBusDeviceToConfigure(drvp->driverName, BUS_SBUS,
- instances[i].sbus, -1);
- if (pGDev) {
- /*
- * XF86Match???Instances() treat chipID and chipRev as
- * overrides, so clobber them here.
- */
- pGDev->chipID = pGDev->chipRev = -1;
- }
- }
- free(instances);
- if (useProm)
- sparcPromClose();
- return actualcards;
- }
-
- DebugF("%s instances found: %d\n", driverName, allocatedInstances);
-
- for (i = 0; i < allocatedInstances; i++) {
- char *promPath = NULL;
-
- psdp = instances[i].sbus;
- devBus = NULL;
- dev = NULL;
- if (useProm && psdp->node.node)
- promPath = sparcPromNode2Pathname(&psdp->node);
-
- for (j = 0; j < numDevs; j++) {
- if (devList[j]->busID && *devList[j]->busID) {
- if (xf86CompareSbusBusString(devList[j]->busID, psdp->fbNum)) {
- if (devBus)
- xf86MsgVerb(X_WARNING,0,
- "%s: More than one matching Device section for "
- "instance (BusID: %s) found: %s\n",
- driverName,devList[j]->identifier,
- devList[j]->busID);
- else
- devBus = devList[j];
- }
- } else {
- if (!dev && !devBus) {
- if (promPath)
- xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:%s\n",
- promPath);
- else
- xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:fb%d\n",
- psdp->fbNum);
- dev = devList[j];
- } else
- xf86MsgVerb(X_WARNING, 0,
- "%s: More than one matching Device section "
- "found: %s\n", driverName, devList[j]->identifier);
- }
- }
- if (devBus) dev = devBus; /* busID preferred */
- if (!dev && psdp->fd != -2) {
- if (promPath) {
- xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section "
- "for instance (BusID SBUS:%s) found\n",
- driverName, promPath);
- } else
- xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section "
- "for instance (BusID SBUS:fb%d) found\n",
- driverName, psdp->fbNum);
- } else if (dev) {
- numClaimedInstances++;
- instances[i].claimed = TRUE;
- instances[i].dev = dev;
- }
- free(promPath);
- }
-
- DebugF("%s instances found: %d\n", driverName, numClaimedInstances);
-
- /*
- * Of the claimed instances, check that another driver hasn't already
- * claimed its slot.
- */
- numFound = 0;
- for (i = 0; i < allocatedInstances && numClaimedInstances > 0; i++) {
- if (!instances[i].claimed)
- continue;
- psdp = instances[i].sbus;
- if (!xf86CheckSbusSlot(psdp->fbNum))
- continue;
-
- DebugF("%s: card at fb%d %08x is claimed by a Device section\n",
- driverName, psdp->fbNum, psdp->node.node);
-
- /* Allocate an entry in the lists to be returned */
- numFound++;
- retEntities = xnfrealloc(retEntities, numFound * sizeof(int));
- retEntities[numFound - 1]
- = xf86ClaimSbusSlot(psdp, drvp, instances[i].dev,instances[i].dev->active ?
- TRUE : FALSE);
- }
- free(instances);
- if (numFound > 0) {
- *foundEntities = retEntities;
- }
-
- if (useProm)
- sparcPromClose();
-
- return numFound;
-}
-
-/*
- * xf86GetSbusInfoForEntity() -- Get the sbusDevicePtr of entity.
- */
-sbusDevicePtr
-xf86GetSbusInfoForEntity(int entityIndex)
-{
- sbusDevicePtr *psdpp;
- EntityPtr p = xf86Entities[entityIndex];
-
- if (entityIndex >= xf86NumEntities
- || p->bus.type != BUS_SBUS) return NULL;
-
- for (psdpp = xf86SbusInfo; *psdpp != NULL; psdpp++) {
- if (p->bus.id.sbus.fbNum == (*psdpp)->fbNum)
- return *psdpp;
- }
- return NULL;
-}
-
-int
-xf86GetEntityForSbusInfo(sbusDevicePtr psdp)
-{
- int i;
-
- for (i = 0; i < xf86NumEntities; i++) {
- EntityPtr p = xf86Entities[i];
- if (p->bus.type != BUS_SBUS) continue;
-
- if (p->bus.id.sbus.fbNum == psdp->fbNum)
- return i;
- }
- return -1;
-}
-
-void
-xf86SbusUseBuiltinMode(ScrnInfoPtr pScrn, sbusDevicePtr psdp)
-{
- DisplayModePtr mode;
-
- mode = xnfcalloc(sizeof(DisplayModeRec), 1);
- mode->name = "current";
- mode->next = mode;
- mode->prev = mode;
- mode->type = M_T_BUILTIN;
- mode->Clock = 100000000;
- mode->HDisplay = psdp->width;
- mode->HSyncStart = psdp->width;
- mode->HSyncEnd = psdp->width;
- mode->HTotal = psdp->width;
- mode->VDisplay = psdp->height;
- mode->VSyncStart = psdp->height;
- mode->VSyncEnd = psdp->height;
- mode->VTotal = psdp->height;
- mode->SynthClock = mode->Clock;
- mode->CrtcHDisplay = mode->HDisplay;
- mode->CrtcHSyncStart = mode->HSyncStart;
- mode->CrtcHSyncEnd = mode->HSyncEnd;
- mode->CrtcHTotal = mode->HTotal;
- mode->CrtcVDisplay = mode->VDisplay;
- mode->CrtcVSyncStart = mode->VSyncStart;
- mode->CrtcVSyncEnd = mode->VSyncEnd;
- mode->CrtcVTotal = mode->VTotal;
- mode->CrtcHAdjusted = FALSE;
- mode->CrtcVAdjusted = FALSE;
- pScrn->modes = mode;
- pScrn->virtualX = psdp->width;
- pScrn->virtualY = psdp->height;
-}
-
-static sbusPaletteKeyIndex;
-static DevPrivateKey sbusPaletteKey = &sbusPaletteKeyIndex;
-typedef struct _sbusCmap {
- sbusDevicePtr psdp;
- CloseScreenProcPtr CloseScreen;
- Bool origCmapValid;
- unsigned char origRed[16];
- unsigned char origGreen[16];
- unsigned char origBlue[16];
-} sbusCmapRec, *sbusCmapPtr;
-
-#define SBUSCMAPPTR(pScreen) ((sbusCmapPtr) \
- dixLookupPrivate(&(pScreen)->devPrivates, sbusPaletteKey))
-
-static void
-xf86SbusCmapLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices,
- LOCO *colors, VisualPtr pVisual)
-{
- int i, index;
- sbusCmapPtr cmap;
- struct fbcmap fbcmap;
- unsigned char *data = malloc(numColors*3);
-
- cmap = SBUSCMAPPTR(pScrn->pScreen);
- if (!cmap) return;
- fbcmap.count = 0;
- fbcmap.index = indices[0];
- fbcmap.red = data;
- fbcmap.green = data + numColors;
- fbcmap.blue = fbcmap.green + numColors;
- for (i = 0; i < numColors; i++) {
- index = indices[i];
- if (fbcmap.count && index != fbcmap.index + fbcmap.count) {
- ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
- fbcmap.count = 0;
- fbcmap.index = index;
- }
- fbcmap.red[fbcmap.count] = colors[index].red;
- fbcmap.green[fbcmap.count] = colors[index].green;
- fbcmap.blue[fbcmap.count++] = colors[index].blue;
- }
- ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
- free(data);
-}
-
-static Bool
-xf86SbusCmapCloseScreen(int i, ScreenPtr pScreen)
-{
- sbusCmapPtr cmap;
- struct fbcmap fbcmap;
-
- cmap = SBUSCMAPPTR(pScreen);
- if (cmap->origCmapValid) {
- fbcmap.index = 0;
- fbcmap.count = 16;
- fbcmap.red = cmap->origRed;
- fbcmap.green = cmap->origGreen;
- fbcmap.blue = cmap->origBlue;
- ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap);
- }
- pScreen->CloseScreen = cmap->CloseScreen;
- free(cmap);
- return (*pScreen->CloseScreen) (i, pScreen);
-}
-
-Bool
-xf86SbusHandleColormaps(ScreenPtr pScreen, sbusDevicePtr psdp)
-{
- sbusCmapPtr cmap;
- struct fbcmap fbcmap;
- unsigned char data[2];
-
- cmap = xnfcalloc(1, sizeof(sbusCmapRec));
- dixSetPrivate(&pScreen->devPrivates, sbusPaletteKey, cmap);
- cmap->psdp = psdp;
- fbcmap.index = 0;
- fbcmap.count = 16;
- fbcmap.red = cmap->origRed;
- fbcmap.green = cmap->origGreen;
- fbcmap.blue = cmap->origBlue;
- if (ioctl (psdp->fd, FBIOGETCMAP, &fbcmap) >= 0)
- cmap->origCmapValid = TRUE;
- fbcmap.index = 0;
- fbcmap.count = 2;
- fbcmap.red = data;
- fbcmap.green = data;
- fbcmap.blue = data;
- if (pScreen->whitePixel == 0) {
- data[0] = 255;
- data[1] = 0;
- } else {
- data[0] = 0;
- data[1] = 255;
- }
- ioctl (psdp->fd, FBIOPUTCMAP, &fbcmap);
- cmap->CloseScreen = pScreen->CloseScreen;
- pScreen->CloseScreen = xf86SbusCmapCloseScreen;
- return xf86HandleColormaps(pScreen, 256, 8,
- xf86SbusCmapLoadPalette, NULL, 0);
-}
-
-Bool
-xf86SbusConfigure(void *busData, sbusDevicePtr sBus)
-{
- if (sBus && sBus->fbNum == ((sbusDevicePtr) busData)->fbNum)
- return 0;
- return 1;
-}
-
-void
-xf86SbusConfigureNewDev(void *busData, sbusDevicePtr sBus, GDevRec *GDev)
-{
- char *promPath = NULL;
-
- sBus = (sbusDevicePtr) busData;
- GDev->identifier = sBus->descr;
- if (sparcPromInit() >= 0) {
- promPath = sparcPromNode2Pathname(&sBus->node);
- sparcPromClose();
- }
- if (promPath) {
- XNFasprintf(&GDev->busID, "SBUS:%s", promPath);
- free(promPath);
- } else {
- XNFasprintf(&GDev->busID, "SBUS:fb%d", sBus->fbNum);
- }
-}
+/* + * SBUS bus-specific code. + * + * Copyright (C) 2000 Jakub Jelinek (jakub@redhat.com) + * + * 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 + * JAKUB JELINEK 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. + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <ctype.h> +#include <stdio.h> +#include <unistd.h> +#include <X11/X.h> +#include "os.h" +#include "xf86.h" +#include "xf86Priv.h" +#include "xf86_OSlib.h" +#include "xf86cmap.h" + +#include "xf86Bus.h" + +#include "xf86sbusBus.h" +#include "xf86Sbus.h" + +Bool sbusSlotClaimed = FALSE; + +static int xf86nSbusInfo; + +static void +CheckSbusDevice(const char *device, int fbNum) +{ + int fd, i; + struct fbgattr fbattr; + sbusDevicePtr psdp; + + fd = open(device, O_RDONLY, 0); + if (fd < 0) + return; + memset(&fbattr, 0, sizeof(fbattr)); + if (ioctl(fd, FBIOGATTR, &fbattr) < 0) { + if (ioctl(fd, FBIOGTYPE, &fbattr.fbtype) < 0) { + close(fd); + return; + } + } + close(fd); + for (i = 0; sbusDeviceTable[i].devId; i++) + if (sbusDeviceTable[i].fbType == fbattr.fbtype.fb_type) + break; + if (! sbusDeviceTable[i].devId) + return; + xf86SbusInfo = xnfrealloc(xf86SbusInfo, sizeof(psdp) * (++xf86nSbusInfo + 1)); + xf86SbusInfo[xf86nSbusInfo] = NULL; + xf86SbusInfo[xf86nSbusInfo - 1] = psdp = xnfcalloc(sizeof (sbusDevice), 1); + psdp->devId = sbusDeviceTable[i].devId; + psdp->fbNum = fbNum; + psdp->device = xnfstrdup(device); + psdp->width = fbattr.fbtype.fb_width; + psdp->height = fbattr.fbtype.fb_height; + psdp->fd = -1; +} + +void +xf86SbusProbe(void) +{ + int i, useProm = 0; + char fbDevName[32]; + sbusDevicePtr psdp, *psdpp; + + xf86SbusInfo = malloc(sizeof(psdp)); + *xf86SbusInfo = NULL; + for (i = 0; i < 32; i++) { + sprintf(fbDevName, "/dev/fb%d", i); + CheckSbusDevice(fbDevName, i); + } + if (sparcPromInit() >= 0) { + useProm = 1; + sparcPromAssignNodes(); + } + for (psdpp = xf86SbusInfo; (psdp = *psdpp); psdpp++) { + for (i = 0; sbusDeviceTable[i].devId; i++) + if (sbusDeviceTable[i].devId == psdp->devId) + psdp->descr = sbusDeviceTable[i].descr; + /* + * If we can use PROM information and found the PROM node for this + * device, we can tell more about the card. + */ + if (useProm && psdp->node.node) { + char *prop, *promPath; + int len, chiprev, vmsize; + + switch (psdp->devId) { + case SBUS_DEVICE_MGX: + prop = sparcPromGetProperty(&psdp->node, "fb_size", &len); + if (prop && len == 4 && *(int *)prop == 0x400000) + psdp->descr = "Quantum 3D MGXplus with 4M VRAM"; + break; + case SBUS_DEVICE_CG6: + chiprev = 0; + vmsize = 0; + prop = sparcPromGetProperty(&psdp->node, "chiprev", &len); + if (prop && len == 4) + chiprev = *(int *)prop; + prop = sparcPromGetProperty(&psdp->node, "vmsize", &len); + if (prop && len == 4) + vmsize = *(int *)prop; + switch (chiprev) { + case 1: + case 2: + case 3: + case 4: + psdp->descr = "Sun Double width GX"; break; + case 5: + case 6: + case 7: + case 8: + case 9: + psdp->descr = "Sun Single width GX"; break; + case 11: + switch (vmsize) { + case 2: + psdp->descr = "Sun Turbo GX with 1M VSIMM"; break; + case 4: + psdp->descr = "Sun Turbo GX Plus"; break; + default: + psdp->descr = "Sun Turbo GX"; break; + } + } + break; + case SBUS_DEVICE_CG14: + prop = sparcPromGetProperty(&psdp->node, "reg", &len); + vmsize = 0; + if (prop && !(len % 12) && len > 0) + vmsize = *(int *)(prop + len - 4); + switch (vmsize) { + case 0x400000: + psdp->descr = "Sun SX with 4M VSIMM"; break; + case 0x800000: + psdp->descr = "Sun SX with 8M VSIMM"; break; + } + break; + case SBUS_DEVICE_LEO: + prop = sparcPromGetProperty(&psdp->node, "model", &len); + if (prop && len > 0 && !strstr(prop, "501-2503")) + psdp->descr = "Sun Turbo ZX"; + break; + case SBUS_DEVICE_TCX: + if (sparcPromGetBool(&psdp->node, "tcx-8-bit")) + psdp->descr = "Sun TCX (8bit)"; + else + psdp->descr = "Sun TCX (S24)"; + break; + case SBUS_DEVICE_FFB: + prop = sparcPromGetProperty(&psdp->node, "name", &len); + chiprev = 0; + prop = sparcPromGetProperty(&psdp->node, "board_type", &len); + if (prop && len == 4) + chiprev = *(int *)prop; + if (strstr (prop, "afb")) { + if (chiprev == 3) + psdp->descr = "Sun|Elite3D-M6 Horizontal"; + } else { + switch (chiprev) { + case 0x08: + psdp->descr = "Sun FFB 67MHz Creator"; break; + case 0x0b: + psdp->descr = "Sun FFB 67MHz Creator 3D"; break; + case 0x1b: + psdp->descr = "Sun FFB 75MHz Creator 3D"; break; + case 0x20: + case 0x28: + psdp->descr = "Sun FFB2 Vertical Creator"; break; + case 0x23: + case 0x2b: + psdp->descr = "Sun FFB2 Vertical Creator 3D"; break; + case 0x30: + psdp->descr = "Sun FFB2+ Vertical Creator"; break; + case 0x33: + psdp->descr = "Sun FFB2+ Vertical Creator 3D"; break; + case 0x40: + case 0x48: + psdp->descr = "Sun FFB2 Horizontal Creator"; break; + case 0x43: + case 0x4b: + psdp->descr = "Sun FFB2 Horizontal Creator 3D"; break; + } + } + break; + } + + xf86Msg(X_PROBED, "SBUS:(0x%08x) %s", psdp->node.node, psdp->descr); + promPath = sparcPromNode2Pathname (&psdp->node); + if (promPath) { + xf86ErrorF(" at %s", promPath); + free(promPath); + } + } else + xf86Msg(X_PROBED, "SBUS: %s", psdp->descr); + xf86ErrorF("\n"); + } + if (useProm) + sparcPromClose(); +} + +/* + * Parse a BUS ID string, and return the SBUS bus parameters if it was + * in the correct format for a SBUS bus id. + */ + +Bool +xf86ParseSbusBusString(const char *busID, int *fbNum) +{ + /* + * The format is assumed to be one of: + * "fbN", e.g. "fb1", which means the device corresponding to /dev/fbN + * "nameN", e.g. "cgsix0", which means Nth instance of card NAME + * "/prompath", e.g. "/sbus@0,10001000/cgsix@3,0" which is PROM pathname + * to the device. + */ + + const char *id; + int i, len; + + if (StringToBusType(busID, &id) != BUS_SBUS) + return FALSE; + + if (*id != '/') { + if (!strncmp (id, "fb", 2)) { + if (!isdigit(id[2])) + return FALSE; + *fbNum = atoi(id + 2); + return TRUE; + } else { + sbusDevicePtr *psdpp; + int devId; + + for (i = 0, len = 0; sbusDeviceTable[i].devId; i++) { + len = strlen(sbusDeviceTable[i].promName); + if (!strncmp (sbusDeviceTable[i].promName, id, len) + && isdigit(id[len])) + break; + } + devId = sbusDeviceTable[i].devId; + if (!devId) return FALSE; + i = atoi(id + len); + for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) { + if ((*psdpp)->devId != devId) + continue; + if (!i) { + *fbNum = (*psdpp)->fbNum; + return TRUE; + } + i--; + } + } + return FALSE; + } + + if (sparcPromInit() >= 0) { + i = sparcPromPathname2Node(id); + sparcPromClose(); + if (i) { + sbusDevicePtr *psdpp; + for (psdpp = xf86SbusInfo; *psdpp; ++psdpp) { + if ((*psdpp)->node.node == i) { + *fbNum = (*psdpp)->fbNum; + return TRUE; + } + } + } + } + return FALSE; +} + +/* + * Compare a BUS ID string with a SBUS bus id. Return TRUE if they match. + */ + +Bool +xf86CompareSbusBusString(const char *busID, int fbNum) +{ + int iFbNum; + + if (xf86ParseSbusBusString(busID, &iFbNum)) { + return fbNum == iFbNum; + } else { + return FALSE; + } +} + +/* + * Check if the slot requested is free. If it is already in use, return FALSE. + */ + +Bool +xf86CheckSbusSlot(int fbNum) +{ + int i; + EntityPtr p; + + for (i = 0; i < xf86NumEntities; i++) { + p = xf86Entities[i]; + /* Check if this SBUS slot is taken */ + if (p->bus.type == BUS_SBUS && p->bus.id.sbus.fbNum == fbNum) + return FALSE; + } + + return TRUE; +} + +/* + * If the slot requested is already in use, return -1. + * Otherwise, claim the slot for the screen requesting it. + */ + +int +xf86ClaimSbusSlot(sbusDevicePtr psdp, DriverPtr drvp, + GDevPtr dev, Bool active) +{ + EntityPtr p = NULL; + + int num; + + if (xf86CheckSbusSlot(psdp->fbNum)) { + num = xf86AllocateEntity(); + p = xf86Entities[num]; + p->driver = drvp; + p->chipset = -1; + p->bus.type = BUS_SBUS; + xf86AddDevToEntity(num, dev); + p->bus.id.sbus.fbNum = psdp->fbNum; + p->active = active; + p->inUse = FALSE; + sbusSlotClaimed = TRUE; + return num; + } else + return -1; +} + +int +xf86MatchSbusInstances(const char *driverName, int sbusDevId, + GDevPtr *devList, int numDevs, DriverPtr drvp, + int **foundEntities) +{ + int i,j; + sbusDevicePtr psdp, *psdpp; + int numClaimedInstances = 0; + int allocatedInstances = 0; + int numFound = 0; + GDevPtr devBus = NULL; + GDevPtr dev = NULL; + int *retEntities = NULL; + int useProm = 0; + + struct Inst { + sbusDevicePtr sbus; + GDevPtr dev; + Bool claimed; /* BusID matches with a device section */ + } *instances = NULL; + + *foundEntities = NULL; + for (psdpp = xf86SbusInfo, psdp = *psdpp; psdp; psdp = *++psdpp) { + if (psdp->devId != sbusDevId) + continue; + if (psdp->fd == -2) + continue; + ++allocatedInstances; + instances = xnfrealloc(instances, + allocatedInstances * sizeof(struct Inst)); + instances[allocatedInstances - 1].sbus = psdp; + instances[allocatedInstances - 1].dev = NULL; + instances[allocatedInstances - 1].claimed = FALSE; + numFound++; + } + + /* + * This may be debatable, but if no SBUS devices with a matching vendor + * type is found, return zero now. It is probably not desirable to + * allow the config file to override this. + */ + if (allocatedInstances <= 0) { + free(instances); + return 0; + } + + if (sparcPromInit() >= 0) + useProm = 1; + + if (xf86DoConfigure && xf86DoConfigurePass1) { + GDevPtr pGDev; + int actualcards = 0; + for (i = 0; i < allocatedInstances; i++) { + actualcards++; + pGDev = xf86AddBusDeviceToConfigure(drvp->driverName, BUS_SBUS, + instances[i].sbus, -1); + if (pGDev) { + /* + * XF86Match???Instances() treat chipID and chipRev as + * overrides, so clobber them here. + */ + pGDev->chipID = pGDev->chipRev = -1; + } + } + free(instances); + if (useProm) + sparcPromClose(); + return actualcards; + } + + DebugF("%s instances found: %d\n", driverName, allocatedInstances); + + for (i = 0; i < allocatedInstances; i++) { + char *promPath = NULL; + + psdp = instances[i].sbus; + devBus = NULL; + dev = NULL; + if (useProm && psdp->node.node) + promPath = sparcPromNode2Pathname(&psdp->node); + + for (j = 0; j < numDevs; j++) { + if (devList[j]->busID && *devList[j]->busID) { + if (xf86CompareSbusBusString(devList[j]->busID, psdp->fbNum)) { + if (devBus) + xf86MsgVerb(X_WARNING,0, + "%s: More than one matching Device section for " + "instance (BusID: %s) found: %s\n", + driverName,devList[j]->identifier, + devList[j]->busID); + else + devBus = devList[j]; + } + } else { + if (!dev && !devBus) { + if (promPath) + xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:%s\n", + promPath); + else + xf86Msg(X_PROBED, "Assigning device section with no busID to SBUS:fb%d\n", + psdp->fbNum); + dev = devList[j]; + } else + xf86MsgVerb(X_WARNING, 0, + "%s: More than one matching Device section " + "found: %s\n", driverName, devList[j]->identifier); + } + } + if (devBus) dev = devBus; /* busID preferred */ + if (!dev && psdp->fd != -2) { + if (promPath) { + xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section " + "for instance (BusID SBUS:%s) found\n", + driverName, promPath); + } else + xf86MsgVerb(X_WARNING, 0, "%s: No matching Device section " + "for instance (BusID SBUS:fb%d) found\n", + driverName, psdp->fbNum); + } else if (dev) { + numClaimedInstances++; + instances[i].claimed = TRUE; + instances[i].dev = dev; + } + free(promPath); + } + + DebugF("%s instances found: %d\n", driverName, numClaimedInstances); + + /* + * Of the claimed instances, check that another driver hasn't already + * claimed its slot. + */ + numFound = 0; + for (i = 0; i < allocatedInstances && numClaimedInstances > 0; i++) { + if (!instances[i].claimed) + continue; + psdp = instances[i].sbus; + if (!xf86CheckSbusSlot(psdp->fbNum)) + continue; + + DebugF("%s: card at fb%d %08x is claimed by a Device section\n", + driverName, psdp->fbNum, psdp->node.node); + + /* Allocate an entry in the lists to be returned */ + numFound++; + retEntities = xnfrealloc(retEntities, numFound * sizeof(int)); + retEntities[numFound - 1] + = xf86ClaimSbusSlot(psdp, drvp, instances[i].dev,instances[i].dev->active ? + TRUE : FALSE); + } + free(instances); + if (numFound > 0) { + *foundEntities = retEntities; + } + + if (useProm) + sparcPromClose(); + + return numFound; +} + +/* + * xf86GetSbusInfoForEntity() -- Get the sbusDevicePtr of entity. + */ +sbusDevicePtr +xf86GetSbusInfoForEntity(int entityIndex) +{ + sbusDevicePtr *psdpp; + EntityPtr p = xf86Entities[entityIndex]; + + if (entityIndex >= xf86NumEntities + || p->bus.type != BUS_SBUS) return NULL; + + for (psdpp = xf86SbusInfo; *psdpp != NULL; psdpp++) { + if (p->bus.id.sbus.fbNum == (*psdpp)->fbNum) + return *psdpp; + } + return NULL; +} + +int +xf86GetEntityForSbusInfo(sbusDevicePtr psdp) +{ + int i; + + for (i = 0; i < xf86NumEntities; i++) { + EntityPtr p = xf86Entities[i]; + if (p->bus.type != BUS_SBUS) continue; + + if (p->bus.id.sbus.fbNum == psdp->fbNum) + return i; + } + return -1; +} + +void +xf86SbusUseBuiltinMode(ScrnInfoPtr pScrn, sbusDevicePtr psdp) +{ + DisplayModePtr mode; + + mode = xnfcalloc(sizeof(DisplayModeRec), 1); + mode->name = "current"; + mode->next = mode; + mode->prev = mode; + mode->type = M_T_BUILTIN; + mode->Clock = 100000000; + mode->HDisplay = psdp->width; + mode->HSyncStart = psdp->width; + mode->HSyncEnd = psdp->width; + mode->HTotal = psdp->width; + mode->VDisplay = psdp->height; + mode->VSyncStart = psdp->height; + mode->VSyncEnd = psdp->height; + mode->VTotal = psdp->height; + mode->SynthClock = mode->Clock; + mode->CrtcHDisplay = mode->HDisplay; + mode->CrtcHSyncStart = mode->HSyncStart; + mode->CrtcHSyncEnd = mode->HSyncEnd; + mode->CrtcHTotal = mode->HTotal; + mode->CrtcVDisplay = mode->VDisplay; + mode->CrtcVSyncStart = mode->VSyncStart; + mode->CrtcVSyncEnd = mode->VSyncEnd; + mode->CrtcVTotal = mode->VTotal; + mode->CrtcHAdjusted = FALSE; + mode->CrtcVAdjusted = FALSE; + pScrn->modes = mode; + pScrn->virtualX = psdp->width; + pScrn->virtualY = psdp->height; +} + +static sbusPaletteKeyIndex; +static DevPrivateKey sbusPaletteKey = &sbusPaletteKeyIndex; +typedef struct _sbusCmap { + sbusDevicePtr psdp; + CloseScreenProcPtr CloseScreen; + Bool origCmapValid; + unsigned char origRed[16]; + unsigned char origGreen[16]; + unsigned char origBlue[16]; +} sbusCmapRec, *sbusCmapPtr; + +#define SBUSCMAPPTR(pScreen) ((sbusCmapPtr) \ + dixLookupPrivate(&(pScreen)->devPrivates, sbusPaletteKey)) + +static void +xf86SbusCmapLoadPalette(ScrnInfoPtr pScrn, int numColors, int *indices, + LOCO *colors, VisualPtr pVisual) +{ + int i, index; + sbusCmapPtr cmap; + struct fbcmap fbcmap; + unsigned char *data = malloc(numColors*3); + + cmap = SBUSCMAPPTR(pScrn->pScreen); + if (!cmap) return; + fbcmap.count = 0; + fbcmap.index = indices[0]; + fbcmap.red = data; + fbcmap.green = data + numColors; + fbcmap.blue = fbcmap.green + numColors; + for (i = 0; i < numColors; i++) { + index = indices[i]; + if (fbcmap.count && index != fbcmap.index + fbcmap.count) { + ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap); + fbcmap.count = 0; + fbcmap.index = index; + } + fbcmap.red[fbcmap.count] = colors[index].red; + fbcmap.green[fbcmap.count] = colors[index].green; + fbcmap.blue[fbcmap.count++] = colors[index].blue; + } + ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap); + free(data); +} + +static Bool +xf86SbusCmapCloseScreen(int i, ScreenPtr pScreen) +{ + sbusCmapPtr cmap; + struct fbcmap fbcmap; + + cmap = SBUSCMAPPTR(pScreen); + if (cmap->origCmapValid) { + fbcmap.index = 0; + fbcmap.count = 16; + fbcmap.red = cmap->origRed; + fbcmap.green = cmap->origGreen; + fbcmap.blue = cmap->origBlue; + ioctl (cmap->psdp->fd, FBIOPUTCMAP, &fbcmap); + } + pScreen->CloseScreen = cmap->CloseScreen; + free(cmap); + return (*pScreen->CloseScreen) (i, pScreen); +} + +Bool +xf86SbusHandleColormaps(ScreenPtr pScreen, sbusDevicePtr psdp) +{ + sbusCmapPtr cmap; + struct fbcmap fbcmap; + unsigned char data[2]; + + cmap = xnfcalloc(1, sizeof(sbusCmapRec)); + dixSetPrivate(&pScreen->devPrivates, sbusPaletteKey, cmap); + cmap->psdp = psdp; + fbcmap.index = 0; + fbcmap.count = 16; + fbcmap.red = cmap->origRed; + fbcmap.green = cmap->origGreen; + fbcmap.blue = cmap->origBlue; + if (ioctl (psdp->fd, FBIOGETCMAP, &fbcmap) >= 0) + cmap->origCmapValid = TRUE; + fbcmap.index = 0; + fbcmap.count = 2; + fbcmap.red = data; + fbcmap.green = data; + fbcmap.blue = data; + if (pScreen->whitePixel == 0) { + data[0] = 255; + data[1] = 0; + } else { + data[0] = 0; + data[1] = 255; + } + ioctl (psdp->fd, FBIOPUTCMAP, &fbcmap); + cmap->CloseScreen = pScreen->CloseScreen; + pScreen->CloseScreen = xf86SbusCmapCloseScreen; + return xf86HandleColormaps(pScreen, 256, 8, + xf86SbusCmapLoadPalette, NULL, 0); +} + +Bool +xf86SbusConfigure(void *busData, sbusDevicePtr sBus) +{ + if (sBus && sBus->fbNum == ((sbusDevicePtr) busData)->fbNum) + return 0; + return 1; +} + +void +xf86SbusConfigureNewDev(void *busData, sbusDevicePtr sBus, GDevRec *GDev) +{ + char *promPath = NULL; + + sBus = (sbusDevicePtr) busData; + GDev->identifier = sBus->descr; + if (sparcPromInit() >= 0) { + promPath = sparcPromNode2Pathname(&sBus->node); + sparcPromClose(); + } + if (promPath) { + XNFasprintf(&GDev->busID, "SBUS:%s", promPath); + free(promPath); + } else { + XNFasprintf(&GDev->busID, "SBUS:fb%d", sBus->fbNum); + } +} diff --git a/xorg-server/hw/xfree86/common/xf86xv.c b/xorg-server/hw/xfree86/common/xf86xv.c index 416842473..b46dfefed 100644 --- a/xorg-server/hw/xfree86/common/xf86xv.c +++ b/xorg-server/hw/xfree86/common/xf86xv.c @@ -1,2190 +1,2190 @@ -/*
- * XFree86 Xv DDX written by Mark Vojkovich (markv@valinux.com)
- */
-/*
- * Copyright (c) 1998-2003 by The XFree86 Project, Inc.
- *
- * 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
- * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s)
- * and author(s) 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 copyright holder(s) and author(s).
- */
-
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "misc.h"
-#include "xf86.h"
-#include "xf86_OSproc.h"
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "scrnintstr.h"
-#include "regionstr.h"
-#include "windowstr.h"
-#include "pixmapstr.h"
-#include "mivalidate.h"
-#include "validate.h"
-#include "resource.h"
-#include "gcstruct.h"
-#include "dixstruct.h"
-
-#include <X11/extensions/Xv.h>
-#include <X11/extensions/Xvproto.h>
-#include "xvdix.h"
-#include "xvmodproc.h"
-
-#include "xf86xvpriv.h"
-
-
-/* XvScreenRec fields */
-
-static Bool xf86XVCloseScreen(int, ScreenPtr);
-static int xf86XVQueryAdaptors(ScreenPtr, XvAdaptorPtr *, int *);
-
-/* XvAdaptorRec fields */
-
-static int xf86XVAllocatePort(unsigned long, XvPortPtr, XvPortPtr*);
-static int xf86XVFreePort(XvPortPtr);
-static int xf86XVPutVideo(ClientPtr, DrawablePtr,XvPortPtr, GCPtr,
- INT16, INT16, CARD16, CARD16,
- INT16, INT16, CARD16, CARD16);
-static int xf86XVPutStill(ClientPtr, DrawablePtr,XvPortPtr, GCPtr,
- INT16, INT16, CARD16, CARD16,
- INT16, INT16, CARD16, CARD16);
-static int xf86XVGetVideo(ClientPtr, DrawablePtr,XvPortPtr, GCPtr,
- INT16, INT16, CARD16, CARD16,
- INT16, INT16, CARD16, CARD16);
-static int xf86XVGetStill(ClientPtr, DrawablePtr,XvPortPtr, GCPtr,
- INT16, INT16, CARD16, CARD16,
- INT16, INT16, CARD16, CARD16);
-static int xf86XVStopVideo(ClientPtr, XvPortPtr, DrawablePtr);
-static int xf86XVSetPortAttribute(ClientPtr, XvPortPtr, Atom, INT32);
-static int xf86XVGetPortAttribute(ClientPtr, XvPortPtr, Atom, INT32*);
-static int xf86XVQueryBestSize(ClientPtr, XvPortPtr, CARD8,
- CARD16, CARD16,CARD16, CARD16,
- unsigned int*, unsigned int*);
-static int xf86XVPutImage(ClientPtr, DrawablePtr, XvPortPtr, GCPtr,
- INT16, INT16, CARD16, CARD16,
- INT16, INT16, CARD16, CARD16,
- XvImagePtr, unsigned char*, Bool,
- CARD16, CARD16);
-static int xf86XVQueryImageAttributes(ClientPtr, XvPortPtr, XvImagePtr,
- CARD16*, CARD16*, int*, int*);
-
-
-/* ScreenRec fields */
-
-static Bool xf86XVDestroyWindow(WindowPtr pWin);
-static void xf86XVWindowExposures(WindowPtr pWin, RegionPtr r1, RegionPtr r2);
-static void xf86XVPostValidateTree(WindowPtr pWin, WindowPtr pLayerWin, VTKind kind);
-static void xf86XVClipNotify(WindowPtr pWin, int dx, int dy);
-
-#define PostValidateTreeUndefined ((PostValidateTreeProcPtr)-1)
-
-/* ScrnInfoRec functions */
-
-static Bool xf86XVEnterVT(int, int);
-static void xf86XVLeaveVT(int, int);
-static void xf86XVAdjustFrame(int index, int x, int y, int flags);
-static void xf86XVModeSet(ScrnInfoPtr pScrn);
-
-/* misc */
-
-static Bool xf86XVInitAdaptors(ScreenPtr, XF86VideoAdaptorPtr*, int);
-
-
-static DevPrivateKeyRec XF86XVWindowKeyRec;
-#define XF86XVWindowKey (&XF86XVWindowKeyRec)
-
-DevPrivateKey XF86XvScreenKey;
-
-static unsigned long PortResource = 0;
-
-DevPrivateKey (*XvGetScreenKeyProc)(void) = NULL;
-unsigned long (*XvGetRTPortProc)(void) = NULL;
-int (*XvScreenInitProc)(ScreenPtr) = NULL;
-
-#define GET_XV_SCREEN(pScreen) \
- ((XvScreenPtr)dixLookupPrivate(&(pScreen)->devPrivates, XF86XvScreenKey))
-
-#define GET_XF86XV_SCREEN(pScreen) \
- ((XF86XVScreenPtr)(GET_XV_SCREEN(pScreen)->devPriv.ptr))
-
-#define GET_XF86XV_WINDOW(pWin) \
- ((XF86XVWindowPtr)dixLookupPrivate(&(pWin)->devPrivates, XF86XVWindowKey))
-
-static xf86XVInitGenericAdaptorPtr *GenDrivers = NULL;
-static int NumGenDrivers = 0;
-
-int
-xf86XVRegisterGenericAdaptorDriver(
- xf86XVInitGenericAdaptorPtr InitFunc
-){
- xf86XVInitGenericAdaptorPtr *newdrivers;
-
- newdrivers = realloc(GenDrivers, sizeof(xf86XVInitGenericAdaptorPtr) *
- (1 + NumGenDrivers));
- if (!newdrivers)
- return 0;
- GenDrivers = newdrivers;
-
- GenDrivers[NumGenDrivers++] = InitFunc;
-
- return 1;
-}
-
-int
-xf86XVListGenericAdaptors(
- ScrnInfoPtr pScrn,
- XF86VideoAdaptorPtr **adaptors
-){
- int i,j,n,num;
- XF86VideoAdaptorPtr *DrivAdap,*new;
-
- num = 0;
- *adaptors = NULL;
- /*
- * The v4l driver registers itself first, but can use surfaces registered
- * by other drivers. So, call the v4l driver last.
- */
- for (i = NumGenDrivers; --i >= 0; ) {
- DrivAdap = NULL;
- n = (*GenDrivers[i])(pScrn, &DrivAdap);
- if (0 == n)
- continue;
- new = realloc(*adaptors, sizeof(XF86VideoAdaptorPtr) * (num+n));
- if (NULL == new)
- continue;
- *adaptors = new;
- for (j = 0; j < n; j++, num++)
- (*adaptors)[num] = DrivAdap[j];
- }
- return num;
-}
-
-
-/**************** Offscreen surface stuff *******************/
-
-typedef struct {
- XF86OffscreenImagePtr images;
- int num;
-} OffscreenImageRec;
-
-static DevPrivateKeyRec OffscreenPrivateKeyRec;
-#define OffscreenPrivateKey (&OffscreenPrivateKeyRec)
-#define GetOffscreenImage(pScreen) ((OffscreenImageRec *) dixLookupPrivate(&(pScreen)->devPrivates, OffscreenPrivateKey))
-
-Bool
-xf86XVRegisterOffscreenImages(
- ScreenPtr pScreen,
- XF86OffscreenImagePtr images,
- int num
-){
- OffscreenImageRec *OffscreenImage;
- /* This function may be called before xf86XVScreenInit, so there's
- * no better place than this to call dixRegisterPrivateKey to ensure we
- * have space reserved. After the first call it is a no-op. */
- if(!dixRegisterPrivateKey(OffscreenPrivateKey, PRIVATE_SCREEN, sizeof(OffscreenImageRec)) ||
- !(OffscreenImage = GetOffscreenImage(pScreen)))
- /* Every X.org driver assumes this function always succeeds, so
- * just die on allocation failure. */
- FatalError("Could not allocate private storage for XV offscreen images.\n");
-
- OffscreenImage->num = num;
- OffscreenImage->images = images;
- return TRUE;
-}
-
-XF86OffscreenImagePtr
-xf86XVQueryOffscreenImages(
- ScreenPtr pScreen,
- int *num
-){
- OffscreenImageRec *OffscreenImage = GetOffscreenImage(pScreen);
- *num = OffscreenImage->num;
- return OffscreenImage->images;
-}
-
-
-XF86VideoAdaptorPtr
-xf86XVAllocateVideoAdaptorRec(ScrnInfoPtr pScrn)
-{
- return calloc(1, sizeof(XF86VideoAdaptorRec));
-}
-
-void
-xf86XVFreeVideoAdaptorRec(XF86VideoAdaptorPtr ptr)
-{
- free(ptr);
-}
-
-
-Bool
-xf86XVScreenInit(
- ScreenPtr pScreen,
- XF86VideoAdaptorPtr *adaptors,
- int num
-){
- ScrnInfoPtr pScrn;
- XF86XVScreenPtr ScreenPriv;
- XvScreenPtr pxvs;
-
- if(num <= 0 ||
- !XvGetScreenKeyProc || !XvGetRTPortProc || !XvScreenInitProc)
- return FALSE;
-
- if(Success != (*XvScreenInitProc)(pScreen)) return FALSE;
-
- if (!dixRegisterPrivateKey(&XF86XVWindowKeyRec, PRIVATE_WINDOW, 0))
- return FALSE;
-
- XF86XvScreenKey = (*XvGetScreenKeyProc)();
-
- PortResource = (*XvGetRTPortProc)();
-
- pxvs = GET_XV_SCREEN(pScreen);
-
- /* Anyone initializing the Xv layer must provide these two.
- The Xv di layer calls them without even checking if they exist! */
-
- pxvs->ddCloseScreen = xf86XVCloseScreen;
- pxvs->ddQueryAdaptors = xf86XVQueryAdaptors;
-
- /* The Xv di layer provides us with a private hook so that we don't
- have to allocate our own screen private. They also provide
- a CloseScreen hook so that we don't have to wrap it. I'm not
- sure that I appreciate that. */
-
- ScreenPriv = malloc(sizeof(XF86XVScreenRec));
- pxvs->devPriv.ptr = (pointer)ScreenPriv;
-
- if(!ScreenPriv) return FALSE;
-
- pScrn = xf86Screens[pScreen->myNum];
-
- ScreenPriv->DestroyWindow = pScreen->DestroyWindow;
- ScreenPriv->WindowExposures = pScreen->WindowExposures;
- ScreenPriv->PostValidateTree = PostValidateTreeUndefined;
- ScreenPriv->ClipNotify = pScreen->ClipNotify;
- ScreenPriv->EnterVT = pScrn->EnterVT;
- ScreenPriv->LeaveVT = pScrn->LeaveVT;
- ScreenPriv->AdjustFrame = pScrn->AdjustFrame;
- ScreenPriv->ModeSet = pScrn->ModeSet;
-
- pScreen->DestroyWindow = xf86XVDestroyWindow;
- pScreen->WindowExposures = xf86XVWindowExposures;
- pScreen->ClipNotify = xf86XVClipNotify;
- pScrn->EnterVT = xf86XVEnterVT;
- pScrn->LeaveVT = xf86XVLeaveVT;
- if(pScrn->AdjustFrame)
- pScrn->AdjustFrame = xf86XVAdjustFrame;
- pScrn->ModeSet = xf86XVModeSet;
-
- if(!xf86XVInitAdaptors(pScreen, adaptors, num))
- return FALSE;
-
- return TRUE;
-}
-
-static void
-xf86XVFreeAdaptor(XvAdaptorPtr pAdaptor)
-{
- int i;
-
- free(pAdaptor->name);
- pAdaptor->name = NULL;
-
- if(pAdaptor->pEncodings) {
- XvEncodingPtr pEncode = pAdaptor->pEncodings;
-
- for(i = 0; i < pAdaptor->nEncodings; i++, pEncode++)
- free(pEncode->name);
- free(pAdaptor->pEncodings);
- pAdaptor->pEncodings = NULL;
- }
-
- free(pAdaptor->pFormats);
- pAdaptor->pFormats = NULL;
-
- if(pAdaptor->pPorts) {
- XvPortPtr pPort = pAdaptor->pPorts;
- XvPortRecPrivatePtr pPriv;
-
- for(i = 0; i < pAdaptor->nPorts; i++, pPort++) {
- pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr;
- if(pPriv) {
- if(pPriv->clientClip)
- RegionDestroy(pPriv->clientClip);
- if(pPriv->pCompositeClip && pPriv->FreeCompositeClip)
- RegionDestroy(pPriv->pCompositeClip);
- if (pPriv->ckeyFilled)
- RegionDestroy(pPriv->ckeyFilled);
- free(pPriv);
- }
- }
- free(pAdaptor->pPorts);
- pAdaptor->pPorts = NULL;
- }
-
- if(pAdaptor->pAttributes) {
- XvAttributePtr pAttribute = pAdaptor->pAttributes;
-
- for(i = 0; i < pAdaptor->nAttributes; i++, pAttribute++)
- free(pAttribute->name);
- free(pAdaptor->pAttributes);
- pAdaptor->pAttributes = NULL;
- }
-
- free(pAdaptor->pImages);
- free(pAdaptor->devPriv.ptr);
- pAdaptor->pImages = NULL;
- pAdaptor->devPriv.ptr = NULL;
-}
-
-static Bool
-xf86XVInitAdaptors(
- ScreenPtr pScreen,
- XF86VideoAdaptorPtr *infoPtr,
- int number
-) {
- XvScreenPtr pxvs = GET_XV_SCREEN(pScreen);
- ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
- XF86VideoAdaptorPtr adaptorPtr;
- XvAdaptorPtr pAdaptor, pa;
- XvAdaptorRecPrivatePtr adaptorPriv;
- int na, numAdaptor;
- XvPortRecPrivatePtr portPriv;
- XvPortPtr pPort, pp;
- int numPort;
- XF86AttributePtr attributePtr;
- XvAttributePtr pAttribute, pat;
- XF86VideoFormatPtr formatPtr;
- XvFormatPtr pFormat, pf;
- int numFormat, totFormat;
- XF86VideoEncodingPtr encodingPtr;
- XvEncodingPtr pEncode, pe;
- XF86ImagePtr imagePtr;
- XvImagePtr pImage, pi;
- int numVisuals;
- VisualPtr pVisual;
- int i;
-
- pxvs->nAdaptors = 0;
- pxvs->pAdaptors = NULL;
-
- if(!(pAdaptor = calloc(number, sizeof(XvAdaptorRec))))
- return FALSE;
-
- for(pa = pAdaptor, na = 0, numAdaptor = 0; na < number; na++, adaptorPtr++) {
- adaptorPtr = infoPtr[na];
-
- if(!adaptorPtr->StopVideo || !adaptorPtr->SetPortAttribute ||
- !adaptorPtr->GetPortAttribute || !adaptorPtr->QueryBestSize)
- continue;
-
- /* client libs expect at least one encoding */
- if(!adaptorPtr->nEncodings || !adaptorPtr->pEncodings)
- continue;
-
- pa->type = adaptorPtr->type;
-
- if(!adaptorPtr->PutVideo && !adaptorPtr->GetVideo)
- pa->type &= ~XvVideoMask;
-
- if(!adaptorPtr->PutStill && !adaptorPtr->GetStill)
- pa->type &= ~XvStillMask;
-
- if(!adaptorPtr->PutImage || !adaptorPtr->QueryImageAttributes)
- pa->type &= ~XvImageMask;
-
- if(!adaptorPtr->PutVideo && !adaptorPtr->PutImage &&
- !adaptorPtr->PutStill)
- pa->type &= ~XvInputMask;
-
- if(!adaptorPtr->GetVideo && !adaptorPtr->GetStill)
- pa->type &= ~XvOutputMask;
-
- if(!(adaptorPtr->type & (XvPixmapMask | XvWindowMask)))
- continue;
- if(!(adaptorPtr->type & (XvImageMask | XvVideoMask | XvStillMask)))
- continue;
-
- pa->pScreen = pScreen;
- pa->ddAllocatePort = xf86XVAllocatePort;
- pa->ddFreePort = xf86XVFreePort;
- pa->ddPutVideo = xf86XVPutVideo;
- pa->ddPutStill = xf86XVPutStill;
- pa->ddGetVideo = xf86XVGetVideo;
- pa->ddGetStill = xf86XVGetStill;
- pa->ddStopVideo = xf86XVStopVideo;
- pa->ddPutImage = xf86XVPutImage;
- pa->ddSetPortAttribute = xf86XVSetPortAttribute;
- pa->ddGetPortAttribute = xf86XVGetPortAttribute;
- pa->ddQueryBestSize = xf86XVQueryBestSize;
- pa->ddQueryImageAttributes = xf86XVQueryImageAttributes;
- pa->name = strdup(adaptorPtr->name);
-
- if(adaptorPtr->nEncodings &&
- (pEncode = calloc(adaptorPtr->nEncodings, sizeof(XvEncodingRec)))) {
-
- for(pe = pEncode, encodingPtr = adaptorPtr->pEncodings, i = 0;
- i < adaptorPtr->nEncodings; pe++, i++, encodingPtr++)
- {
- pe->id = encodingPtr->id;
- pe->pScreen = pScreen;
- pe->name = strdup(encodingPtr->name);
- pe->width = encodingPtr->width;
- pe->height = encodingPtr->height;
- pe->rate.numerator = encodingPtr->rate.numerator;
- pe->rate.denominator = encodingPtr->rate.denominator;
- }
- pa->nEncodings = adaptorPtr->nEncodings;
- pa->pEncodings = pEncode;
- }
-
- if(adaptorPtr->nImages &&
- (pImage = calloc(adaptorPtr->nImages, sizeof(XvImageRec)))) {
-
- for(i = 0, pi = pImage, imagePtr = adaptorPtr->pImages;
- i < adaptorPtr->nImages; i++, pi++, imagePtr++)
- {
- pi->id = imagePtr->id;
- pi->type = imagePtr->type;
- pi->byte_order = imagePtr->byte_order;
- memcpy(pi->guid, imagePtr->guid, 16);
- pi->bits_per_pixel = imagePtr->bits_per_pixel;
- pi->format = imagePtr->format;
- pi->num_planes = imagePtr->num_planes;
- pi->depth = imagePtr->depth;
- pi->red_mask = imagePtr->red_mask;
- pi->green_mask = imagePtr->green_mask;
- pi->blue_mask = imagePtr->blue_mask;
- pi->y_sample_bits = imagePtr->y_sample_bits;
- pi->u_sample_bits = imagePtr->u_sample_bits;
- pi->v_sample_bits = imagePtr->v_sample_bits;
- pi->horz_y_period = imagePtr->horz_y_period;
- pi->horz_u_period = imagePtr->horz_u_period;
- pi->horz_v_period = imagePtr->horz_v_period;
- pi->vert_y_period = imagePtr->vert_y_period;
- pi->vert_u_period = imagePtr->vert_u_period;
- pi->vert_v_period = imagePtr->vert_v_period;
- memcpy(pi->component_order, imagePtr->component_order, 32);
- pi->scanline_order = imagePtr->scanline_order;
- }
- pa->nImages = adaptorPtr->nImages;
- pa->pImages = pImage;
- }
-
- if(adaptorPtr->nAttributes &&
- (pAttribute = calloc(adaptorPtr->nAttributes, sizeof(XvAttributeRec))))
- {
- for(pat = pAttribute, attributePtr = adaptorPtr->pAttributes, i = 0;
- i < adaptorPtr->nAttributes; pat++, i++, attributePtr++)
- {
- pat->flags = attributePtr->flags;
- pat->min_value = attributePtr->min_value;
- pat->max_value = attributePtr->max_value;
- pat->name = strdup(attributePtr->name);
- }
- pa->nAttributes = adaptorPtr->nAttributes;
- pa->pAttributes = pAttribute;
- }
-
-
- totFormat = adaptorPtr->nFormats;
-
- if(!(pFormat = calloc(totFormat, sizeof(XvFormatRec)))) {
- xf86XVFreeAdaptor(pa);
- continue;
- }
- for(pf = pFormat, i = 0, numFormat = 0, formatPtr = adaptorPtr->pFormats;
- i < adaptorPtr->nFormats; i++, formatPtr++)
- {
- numVisuals = pScreen->numVisuals;
- pVisual = pScreen->visuals;
-
- while(numVisuals--) {
- if((pVisual->class == formatPtr->class) &&
- (pVisual->nplanes == formatPtr->depth)) {
-
- if(numFormat >= totFormat) {
- void *moreSpace;
- totFormat *= 2;
- moreSpace = realloc(pFormat,
- totFormat * sizeof(XvFormatRec));
- if(!moreSpace) break;
- pFormat = moreSpace;
- pf = pFormat + numFormat;
- }
-
- pf->visual = pVisual->vid;
- pf->depth = formatPtr->depth;
-
- pf++;
- numFormat++;
- }
- pVisual++;
- }
- }
- pa->nFormats = numFormat;
- pa->pFormats = pFormat;
- if(!numFormat) {
- xf86XVFreeAdaptor(pa);
- continue;
- }
-
- if(!(adaptorPriv = calloc(1, sizeof(XvAdaptorRecPrivate)))) {
- xf86XVFreeAdaptor(pa);
- continue;
- }
-
- adaptorPriv->flags = adaptorPtr->flags;
- adaptorPriv->PutVideo = adaptorPtr->PutVideo;
- adaptorPriv->PutStill = adaptorPtr->PutStill;
- adaptorPriv->GetVideo = adaptorPtr->GetVideo;
- adaptorPriv->GetStill = adaptorPtr->GetStill;
- adaptorPriv->StopVideo = adaptorPtr->StopVideo;
- adaptorPriv->SetPortAttribute = adaptorPtr->SetPortAttribute;
- adaptorPriv->GetPortAttribute = adaptorPtr->GetPortAttribute;
- adaptorPriv->QueryBestSize = adaptorPtr->QueryBestSize;
- adaptorPriv->QueryImageAttributes = adaptorPtr->QueryImageAttributes;
- adaptorPriv->PutImage = adaptorPtr->PutImage;
- adaptorPriv->ReputImage = adaptorPtr->ReputImage; /* image/still */
-
- pa->devPriv.ptr = (pointer)adaptorPriv;
-
- if(!(pPort = calloc(adaptorPtr->nPorts, sizeof(XvPortRec)))) {
- xf86XVFreeAdaptor(pa);
- continue;
- }
- for(pp = pPort, i = 0, numPort = 0;
- i < adaptorPtr->nPorts; i++) {
-
- if(!(pp->id = FakeClientID(0)))
- continue;
-
- if(!(portPriv = calloc(1, sizeof(XvPortRecPrivate))))
- continue;
-
- if(!AddResource(pp->id, PortResource, pp)) {
- free(portPriv);
- continue;
- }
-
- pp->pAdaptor = pa;
- pp->pNotify = (XvPortNotifyPtr)NULL;
- pp->pDraw = (DrawablePtr)NULL;
- pp->client = (ClientPtr)NULL;
- pp->grab.client = (ClientPtr)NULL;
- pp->time = currentTime;
- pp->devPriv.ptr = portPriv;
-
- portPriv->pScrn = pScrn;
- portPriv->AdaptorRec = adaptorPriv;
- portPriv->DevPriv.ptr = adaptorPtr->pPortPrivates[i].ptr;
-
- pp++;
- numPort++;
- }
- pa->nPorts = numPort;
- pa->pPorts = pPort;
- if(!numPort) {
- xf86XVFreeAdaptor(pa);
- continue;
- }
-
- pa->base_id = pPort->id;
-
- pa++;
- numAdaptor++;
- }
-
- if(numAdaptor) {
- pxvs->nAdaptors = numAdaptor;
- pxvs->pAdaptors = pAdaptor;
- } else {
- free(pAdaptor);
- return FALSE;
- }
-
- return TRUE;
-}
-
-/* Video should be clipped to the intersection of the window cliplist
- and the client cliplist specified in the GC for which the video was
- initialized. When we need to reclip a window, the GC that started
- the video may not even be around anymore. That's why we save the
- client clip from the GC when the video is initialized. We then
- use xf86XVUpdateCompositeClip to calculate the new composite clip
- when we need it. This is different from what DEC did. They saved
- the GC and used it's clip list when they needed to reclip the window,
- even if the client clip was different from the one the video was
- initialized with. If the original GC was destroyed, they had to stop
- the video. I like the new method better (MArk).
-
- This function only works for windows. Will need to rewrite when
- (if) we support pixmap rendering.
-*/
-
-static void
-xf86XVUpdateCompositeClip(XvPortRecPrivatePtr portPriv)
-{
- RegionPtr pregWin, pCompositeClip;
- WindowPtr pWin;
- Bool freeCompClip = FALSE;
-
- if(portPriv->pCompositeClip)
- return;
-
- pWin = (WindowPtr)portPriv->pDraw;
-
- /* get window clip list */
- if(portPriv->subWindowMode == IncludeInferiors) {
- pregWin = NotClippedByChildren(pWin);
- freeCompClip = TRUE;
- } else
- pregWin = &pWin->clipList;
-
- if(!portPriv->clientClip) {
- portPriv->pCompositeClip = pregWin;
- portPriv->FreeCompositeClip = freeCompClip;
- return;
- }
-
- pCompositeClip = RegionCreate(NullBox, 1);
- RegionCopy(pCompositeClip, portPriv->clientClip);
- RegionTranslate(pCompositeClip,
- portPriv->pDraw->x, portPriv->pDraw->y);
- RegionIntersect(pCompositeClip, pregWin, pCompositeClip);
-
- portPriv->pCompositeClip = pCompositeClip;
- portPriv->FreeCompositeClip = TRUE;
-
- if(freeCompClip) {
- RegionDestroy(pregWin);
- }
-}
-
-/* Save the current clientClip and update the CompositeClip whenever
- we have a fresh GC */
-
-static void
-xf86XVCopyClip(
- XvPortRecPrivatePtr portPriv,
- GCPtr pGC
-){
- /* copy the new clip if it exists */
- if((pGC->clientClipType == CT_REGION) && pGC->clientClip) {
- if(!portPriv->clientClip)
- portPriv->clientClip = RegionCreate(NullBox, 1);
- /* Note: this is in window coordinates */
- RegionCopy(portPriv->clientClip, pGC->clientClip);
- RegionTranslate(portPriv->clientClip,
- pGC->clipOrg.x, pGC->clipOrg.y);
- } else if(portPriv->clientClip) { /* free the old clientClip */
- RegionDestroy(portPriv->clientClip);
- portPriv->clientClip = NULL;
- }
-
- /* get rid of the old clip list */
- if(portPriv->pCompositeClip && portPriv->FreeCompositeClip) {
- RegionDestroy(portPriv->pCompositeClip);
- }
-
- portPriv->pCompositeClip = pGC->pCompositeClip;
- portPriv->FreeCompositeClip = FALSE;
- portPriv->subWindowMode = pGC->subWindowMode;
-}
-
-static void
-xf86XVCopyCompositeClip(XvPortRecPrivatePtr portPriv,
- GCPtr pGC,
- DrawablePtr pDraw)
-{
- if (!portPriv->clientClip)
- portPriv->clientClip = RegionCreate(NullBox, 1);
- /* Keep the original GC composite clip around for ReputImage */
- RegionCopy(portPriv->clientClip, pGC->pCompositeClip);
- RegionTranslate(portPriv->clientClip,
- -pDraw->x, -pDraw->y);
-
- /* get rid of the old clip list */
- if (portPriv->pCompositeClip && portPriv->FreeCompositeClip)
- RegionDestroy(portPriv->pCompositeClip);
-
- portPriv->pCompositeClip = pGC->pCompositeClip;
- portPriv->FreeCompositeClip = FALSE;
- portPriv->subWindowMode = pGC->subWindowMode;
-}
-
-static int
-xf86XVRegetVideo(XvPortRecPrivatePtr portPriv)
-{
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- xf86XVUpdateCompositeClip(portPriv);
-
- /* translate the video region to the screen */
- WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x;
- WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y;
- WinBox.x2 = WinBox.x1 + portPriv->drw_w;
- WinBox.y2 = WinBox.y1 + portPriv->drw_h;
-
- /* clip to the window composite clip */
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip);
-
- /* that's all if it's totally obscured */
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto CLIP_VIDEO_BAILOUT;
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->GetVideo)(portPriv->pScrn,
- portPriv->vid_x, portPriv->vid_y,
- WinBox.x1, WinBox.y1,
- portPriv->vid_w, portPriv->vid_h,
- portPriv->drw_w, portPriv->drw_h,
- &ClipRegion, portPriv->DevPriv.ptr,
- portPriv->pDraw);
-
- if(ret == Success)
- portPriv->isOn = XV_ON;
-
-CLIP_VIDEO_BAILOUT:
-
- if((clippedAway || (ret != Success)) && portPriv->isOn == XV_ON) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- /* This clip was copied and only good for one shot */
- if(!portPriv->FreeCompositeClip)
- portPriv->pCompositeClip = NULL;
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-
-static int
-xf86XVReputVideo(XvPortRecPrivatePtr portPriv)
-{
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- xf86XVUpdateCompositeClip(portPriv);
-
- /* translate the video region to the screen */
- WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x;
- WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y;
- WinBox.x2 = WinBox.x1 + portPriv->drw_w;
- WinBox.y2 = WinBox.y1 + portPriv->drw_h;
-
- /* clip to the window composite clip */
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip);
-
- /* clip and translate to the viewport */
- if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) {
- RegionRec VPReg;
- BoxRec VPBox;
-
- VPBox.x1 = portPriv->pScrn->frameX0;
- VPBox.y1 = portPriv->pScrn->frameY0;
- VPBox.x2 = portPriv->pScrn->frameX1 + 1;
- VPBox.y2 = portPriv->pScrn->frameY1 + 1;
-
- RegionInit(&VPReg, &VPBox, 1);
- RegionIntersect(&ClipRegion, &ClipRegion, &VPReg);
- RegionUninit(&VPReg);
- }
-
- /* that's all if it's totally obscured */
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto CLIP_VIDEO_BAILOUT;
- }
-
- /* bailout if we have to clip but the hardware doesn't support it */
- if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) {
- BoxPtr clipBox = RegionRects(&ClipRegion);
- if( (RegionNumRects(&ClipRegion) != 1) ||
- (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) ||
- (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2))
- {
- clippedAway = TRUE;
- goto CLIP_VIDEO_BAILOUT;
- }
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->PutVideo)(portPriv->pScrn,
- portPriv->vid_x, portPriv->vid_y,
- WinBox.x1, WinBox.y1,
- portPriv->vid_w, portPriv->vid_h,
- portPriv->drw_w, portPriv->drw_h,
- &ClipRegion, portPriv->DevPriv.ptr,
- portPriv->pDraw);
-
- if(ret == Success) portPriv->isOn = XV_ON;
-
-CLIP_VIDEO_BAILOUT:
-
- if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- /* This clip was copied and only good for one shot */
- if(!portPriv->FreeCompositeClip)
- portPriv->pCompositeClip = NULL;
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-/* Reput image/still */
-static int
-xf86XVReputImage(XvPortRecPrivatePtr portPriv)
-{
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- xf86XVUpdateCompositeClip(portPriv);
-
- /* the clip can get smaller over time */
- RegionCopy(portPriv->clientClip, portPriv->pCompositeClip);
- RegionTranslate(portPriv->clientClip,
- -portPriv->pDraw->x, -portPriv->pDraw->y);
-
- /* translate the video region to the screen */
- WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x;
- WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y;
- WinBox.x2 = WinBox.x1 + portPriv->drw_w;
- WinBox.y2 = WinBox.y1 + portPriv->drw_h;
-
- /* clip to the window composite clip */
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip);
-
- /* clip and translate to the viewport */
- if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) {
- RegionRec VPReg;
- BoxRec VPBox;
-
- VPBox.x1 = portPriv->pScrn->frameX0;
- VPBox.y1 = portPriv->pScrn->frameY0;
- VPBox.x2 = portPriv->pScrn->frameX1 + 1;
- VPBox.y2 = portPriv->pScrn->frameY1 + 1;
-
- RegionInit(&VPReg, &VPBox, 1);
- RegionIntersect(&ClipRegion, &ClipRegion, &VPReg);
- RegionUninit(&VPReg);
- }
-
- /* that's all if it's totally obscured */
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto CLIP_VIDEO_BAILOUT;
- }
-
- /* bailout if we have to clip but the hardware doesn't support it */
- if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) {
- BoxPtr clipBox = RegionRects(&ClipRegion);
- if( (RegionNumRects(&ClipRegion) != 1) ||
- (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) ||
- (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2))
- {
- clippedAway = TRUE;
- goto CLIP_VIDEO_BAILOUT;
- }
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->ReputImage)(portPriv->pScrn,
- portPriv->vid_x, portPriv->vid_y,
- WinBox.x1, WinBox.y1,
- portPriv->vid_w, portPriv->vid_h,
- portPriv->drw_w, portPriv->drw_h,
- &ClipRegion, portPriv->DevPriv.ptr,
- portPriv->pDraw);
-
- portPriv->isOn = (ret == Success) ? XV_ON : XV_OFF;
-
-CLIP_VIDEO_BAILOUT:
-
- if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- /* This clip was copied and only good for one shot */
- if(!portPriv->FreeCompositeClip)
- portPriv->pCompositeClip = NULL;
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-
-static int
-xf86XVReputAllVideo(WindowPtr pWin, pointer data)
-{
- XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin);
-
- while(WinPriv) {
- if(WinPriv->PortRec->type == XvInputMask)
- xf86XVReputVideo(WinPriv->PortRec);
- else
- xf86XVRegetVideo(WinPriv->PortRec);
- WinPriv = WinPriv->next;
- }
-
- return WT_WALKCHILDREN;
-}
-
-static int
-xf86XVEnlistPortInWindow(WindowPtr pWin, XvPortRecPrivatePtr portPriv)
-{
- XF86XVWindowPtr winPriv, PrivRoot;
-
- winPriv = PrivRoot = GET_XF86XV_WINDOW(pWin);
-
- /* Enlist our port in the window private */
- while(winPriv) {
- if(winPriv->PortRec == portPriv) /* we're already listed */
- break;
- winPriv = winPriv->next;
- }
-
- if(!winPriv) {
- winPriv = calloc(1, sizeof(XF86XVWindowRec));
- if(!winPriv) return BadAlloc;
- winPriv->PortRec = portPriv;
- winPriv->next = PrivRoot;
- dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey, winPriv);
- }
-
- portPriv->pDraw = (DrawablePtr)pWin;
-
- return Success;
-}
-
-
-static void
-xf86XVRemovePortFromWindow(WindowPtr pWin, XvPortRecPrivatePtr portPriv)
-{
- XF86XVWindowPtr winPriv, prevPriv = NULL;
- winPriv = GET_XF86XV_WINDOW(pWin);
-
- while(winPriv) {
- if(winPriv->PortRec == portPriv) {
- if(prevPriv)
- prevPriv->next = winPriv->next;
- else
- dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey,
- winPriv->next);
- free(winPriv);
- break;
- }
- prevPriv = winPriv;
- winPriv = winPriv->next;
- }
- portPriv->pDraw = NULL;
- if (portPriv->ckeyFilled) {
- RegionDestroy(portPriv->ckeyFilled);
- portPriv->ckeyFilled = NULL;
- }
- portPriv->clipChanged = FALSE;
-}
-
-static void
-xf86XVReputOrStopPort(XvPortRecPrivatePtr pPriv,
- WindowPtr pWin,
- Bool visible)
-{
- if (!visible) {
- if (pPriv->isOn == XV_ON) {
- (*pPriv->AdaptorRec->StopVideo)(pPriv->pScrn, pPriv->DevPriv.ptr, FALSE);
- pPriv->isOn = XV_PENDING;
- }
-
- if (!pPriv->type) /* overlaid still/image*/
- xf86XVRemovePortFromWindow(pWin, pPriv);
-
- return;
- }
-
- switch (pPriv->type) {
- case XvInputMask:
- xf86XVReputVideo(pPriv);
- break;
- case XvOutputMask:
- xf86XVRegetVideo(pPriv);
- break;
- default: /* overlaid still/image*/
- if (pPriv->AdaptorRec->ReputImage)
- xf86XVReputImage(pPriv);
- break;
- }
-}
-
-static void
-xf86XVReputOrStopAllPorts(ScrnInfoPtr pScrn, Bool onlyChanged)
-{
- ScreenPtr pScreen = pScrn->pScreen;
- XvScreenPtr pxvs = GET_XV_SCREEN(pScreen);
- XvAdaptorPtr pa;
- int c, i;
-
- for (c = pxvs->nAdaptors, pa = pxvs->pAdaptors; c > 0; c--, pa++) {
- XvPortPtr pPort = pa->pPorts;
-
- for (i = pa->nPorts; i > 0; i--, pPort++) {
- XvPortRecPrivatePtr pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr;
- WindowPtr pWin = (WindowPtr)pPriv->pDraw;
- Bool visible;
-
- if (pPriv->isOn == XV_OFF || !pWin)
- continue;
-
- if (onlyChanged && !pPriv->clipChanged)
- continue;
-
- visible = pWin->visibility == VisibilityUnobscured ||
- pWin->visibility == VisibilityPartiallyObscured;
-
- /*
- * Stop and remove still/images if
- * ReputImage isn't supported.
- */
- if (!pPriv->type && !pPriv->AdaptorRec->ReputImage)
- visible = FALSE;
-
- xf86XVReputOrStopPort(pPriv, pWin, visible);
-
- pPriv->clipChanged = FALSE;
- }
- }
-}
-
-/**** ScreenRec fields ****/
-
-static Bool
-xf86XVDestroyWindow(WindowPtr pWin)
-{
- ScreenPtr pScreen = pWin->drawable.pScreen;
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- XF86XVWindowPtr tmp, WinPriv = GET_XF86XV_WINDOW(pWin);
- int ret;
-
- while(WinPriv) {
- XvPortRecPrivatePtr pPriv = WinPriv->PortRec;
-
- if(pPriv->isOn > XV_OFF) {
- (*pPriv->AdaptorRec->StopVideo)(
- pPriv->pScrn, pPriv->DevPriv.ptr, TRUE);
- pPriv->isOn = XV_OFF;
- }
-
- pPriv->pDraw = NULL;
- tmp = WinPriv;
- WinPriv = WinPriv->next;
- free(tmp);
- }
-
- dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey, NULL);
-
- pScreen->DestroyWindow = ScreenPriv->DestroyWindow;
- ret = (*pScreen->DestroyWindow)(pWin);
- pScreen->DestroyWindow = xf86XVDestroyWindow;
-
- return ret;
-}
-
-static void
-xf86XVPostValidateTree(WindowPtr pWin, WindowPtr pLayerWin, VTKind kind)
-{
- ScreenPtr pScreen;
- XF86XVScreenPtr ScreenPriv;
- ScrnInfoPtr pScrn;
-
- if (pWin)
- pScreen = pWin->drawable.pScreen;
- else
- pScreen = pLayerWin->drawable.pScreen;
-
- ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- pScrn = xf86Screens[pScreen->myNum];
-
- xf86XVReputOrStopAllPorts(pScrn, TRUE);
-
- pScreen->PostValidateTree = ScreenPriv->PostValidateTree;
- if (pScreen->PostValidateTree) {
- (*pScreen->PostValidateTree)(pWin, pLayerWin, kind);
- }
- ScreenPriv->PostValidateTree = PostValidateTreeUndefined;
-}
-
-static void
-xf86XVWindowExposures(WindowPtr pWin, RegionPtr reg1, RegionPtr reg2)
-{
- ScreenPtr pScreen = pWin->drawable.pScreen;
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin);
- XvPortRecPrivatePtr pPriv;
- Bool AreasExposed;
-
- AreasExposed = (WinPriv && reg1 && RegionNotEmpty(reg1));
-
- pScreen->WindowExposures = ScreenPriv->WindowExposures;
- (*pScreen->WindowExposures)(pWin, reg1, reg2);
- pScreen->WindowExposures = xf86XVWindowExposures;
-
- /* filter out XClearWindow/Area */
- if (!pWin->valdata) return;
-
- while(WinPriv) {
- Bool visible = TRUE;
-
- pPriv = WinPriv->PortRec;
-
- /*
- * Stop and remove still/images if areas were exposed and
- * ReputImage isn't supported.
- */
- if (!pPriv->type && !pPriv->AdaptorRec->ReputImage)
- visible = !AreasExposed;
-
- /*
- * Subtract exposed areas from overlaid image to match textured video
- * behavior.
- */
- if (!pPriv->type && pPriv->clientClip)
- RegionSubtract(pPriv->clientClip, pPriv->clientClip, reg1);
-
- if (visible && pPriv->ckeyFilled) {
- RegionRec tmp;
- RegionNull(&tmp);
- RegionCopy(&tmp, reg1);
- RegionTranslate(&tmp, pWin->drawable.x, pWin->drawable.y);
- RegionSubtract(pPriv->ckeyFilled, pPriv->ckeyFilled, &tmp);
- }
-
- WinPriv = WinPriv->next;
- xf86XVReputOrStopPort(pPriv, pWin, visible);
-
- pPriv->clipChanged = FALSE;
- }
-}
-
-static void
-xf86XVClipNotify(WindowPtr pWin, int dx, int dy)
-{
- ScreenPtr pScreen = pWin->drawable.pScreen;
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin);
- XvPortRecPrivatePtr pPriv;
-
- while(WinPriv) {
- pPriv = WinPriv->PortRec;
-
- if(pPriv->pCompositeClip && pPriv->FreeCompositeClip)
- RegionDestroy(pPriv->pCompositeClip);
-
- pPriv->pCompositeClip = NULL;
-
- if (pPriv->AdaptorRec->ClipNotify)
- (*pPriv->AdaptorRec->ClipNotify)(pPriv->pScrn, pPriv->DevPriv.ptr,
- pWin, dx, dy);
-
- pPriv->clipChanged = TRUE;
-
- if (ScreenPriv->PostValidateTree == PostValidateTreeUndefined) {
- ScreenPriv->PostValidateTree = pScreen->PostValidateTree;
- pScreen->PostValidateTree = xf86XVPostValidateTree;
- }
-
- WinPriv = WinPriv->next;
- }
-
- if(ScreenPriv->ClipNotify) {
- pScreen->ClipNotify = ScreenPriv->ClipNotify;
- (*pScreen->ClipNotify)(pWin, dx, dy);
- pScreen->ClipNotify = xf86XVClipNotify;
- }
-}
-
-
-
-/**** Required XvScreenRec fields ****/
-
-static Bool
-xf86XVCloseScreen(int i, ScreenPtr pScreen)
-{
- ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
- XvScreenPtr pxvs = GET_XV_SCREEN(pScreen);
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- XvAdaptorPtr pa;
- int c;
-
- if(!ScreenPriv) return TRUE;
-
- pScreen->DestroyWindow = ScreenPriv->DestroyWindow;
- pScreen->WindowExposures = ScreenPriv->WindowExposures;
- pScreen->ClipNotify = ScreenPriv->ClipNotify;
-
- pScrn->EnterVT = ScreenPriv->EnterVT;
- pScrn->LeaveVT = ScreenPriv->LeaveVT;
- pScrn->AdjustFrame = ScreenPriv->AdjustFrame;
- pScrn->ModeSet = ScreenPriv->ModeSet;
-
- for(c = 0, pa = pxvs->pAdaptors; c < pxvs->nAdaptors; c++, pa++) {
- xf86XVFreeAdaptor(pa);
- }
-
- free(pxvs->pAdaptors);
- free(ScreenPriv);
- return TRUE;
-}
-
-
-static int
-xf86XVQueryAdaptors(
- ScreenPtr pScreen,
- XvAdaptorPtr *p_pAdaptors,
- int *p_nAdaptors
-){
- XvScreenPtr pxvs = GET_XV_SCREEN(pScreen);
-
- *p_nAdaptors = pxvs->nAdaptors;
- *p_pAdaptors = pxvs->pAdaptors;
-
- return Success;
-}
-
-
-/**** ScrnInfoRec fields ****/
-
-static Bool
-xf86XVEnterVT(int index, int flags)
-{
- ScrnInfoPtr pScrn = xf86Screens[index];
- ScreenPtr pScreen = screenInfo.screens[index];
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- Bool ret;
-
- pScrn->EnterVT = ScreenPriv->EnterVT;
- ret = (*ScreenPriv->EnterVT)(index, flags);
- ScreenPriv->EnterVT = pScrn->EnterVT;
- pScrn->EnterVT = xf86XVEnterVT;
-
- if(ret) WalkTree(pScreen, xf86XVReputAllVideo, 0);
-
- return ret;
-}
-
-static void
-xf86XVLeaveVT(int index, int flags)
-{
- ScrnInfoPtr pScrn = xf86Screens[index];
- ScreenPtr pScreen = screenInfo.screens[index];
- XvScreenPtr pxvs = GET_XV_SCREEN(pScreen);
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
- XvAdaptorPtr pAdaptor;
- XvPortPtr pPort;
- XvPortRecPrivatePtr pPriv;
- int i, j;
-
- for(i = 0; i < pxvs->nAdaptors; i++) {
- pAdaptor = &pxvs->pAdaptors[i];
- for(j = 0; j < pAdaptor->nPorts; j++) {
- pPort = &pAdaptor->pPorts[j];
- pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr;
- if(pPriv->isOn > XV_OFF) {
-
- (*pPriv->AdaptorRec->StopVideo)(
- pPriv->pScrn, pPriv->DevPriv.ptr, TRUE);
- pPriv->isOn = XV_OFF;
-
- if(pPriv->pCompositeClip && pPriv->FreeCompositeClip)
- RegionDestroy(pPriv->pCompositeClip);
-
- pPriv->pCompositeClip = NULL;
-
- if(!pPriv->type && pPriv->pDraw) { /* still */
- xf86XVRemovePortFromWindow((WindowPtr)pPriv->pDraw, pPriv);
- }
- }
- }
- }
-
- pScrn->LeaveVT = ScreenPriv->LeaveVT;
- (*ScreenPriv->LeaveVT)(index, flags);
- ScreenPriv->LeaveVT = pScrn->LeaveVT;
- pScrn->LeaveVT = xf86XVLeaveVT;
-}
-
-static void
-xf86XVAdjustFrame(int index, int x, int y, int flags)
-{
- ScrnInfoPtr pScrn = xf86Screens[index];
- ScreenPtr pScreen = pScrn->pScreen;
- XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen);
-
- if(ScreenPriv->AdjustFrame) {
- pScrn->AdjustFrame = ScreenPriv->AdjustFrame;
- (*pScrn->AdjustFrame)(index, x, y, flags);
- pScrn->AdjustFrame = xf86XVAdjustFrame;
- }
-
- xf86XVReputOrStopAllPorts(pScrn, FALSE);
-}
-
-static void
-xf86XVModeSet(ScrnInfoPtr pScrn)
-{
- ScreenPtr pScreen = pScrn->pScreen;
- XF86XVScreenPtr ScreenPriv;
-
- /* Can be called before pScrn->pScreen is set */
- if (!pScreen)
- return;
-
- ScreenPriv = GET_XF86XV_SCREEN(pScreen);
-
- if (ScreenPriv->ModeSet) {
- pScrn->ModeSet = ScreenPriv->ModeSet;
- (*pScrn->ModeSet)(pScrn);
- pScrn->ModeSet = xf86XVModeSet;
- }
-
- xf86XVReputOrStopAllPorts(pScrn, FALSE);
-}
-
-/**** XvAdaptorRec fields ****/
-
-static int
-xf86XVAllocatePort(
- unsigned long port,
- XvPortPtr pPort,
- XvPortPtr *ppPort
-){
- *ppPort = pPort;
- return Success;
-}
-
-
-
-static int
-xf86XVFreePort(XvPortPtr pPort)
-{
- return Success;
-}
-
-
-static int
-xf86XVPutVideo(
- ClientPtr client,
- DrawablePtr pDraw,
- XvPortPtr pPort,
- GCPtr pGC,
- INT16 vid_x, INT16 vid_y,
- CARD16 vid_w, CARD16 vid_h,
- INT16 drw_x, INT16 drw_y,
- CARD16 drw_w, CARD16 drw_h
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
- int result;
-
- /* No dumping video to pixmaps... For now anyhow */
- if(pDraw->type != DRAWABLE_WINDOW) {
- pPort->pDraw = (DrawablePtr)NULL;
- return BadAlloc;
- }
-
- /* If we are changing windows, unregister our port in the old window */
- if(portPriv->pDraw && (portPriv->pDraw != pDraw))
- xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv);
-
- /* Register our port with the new window */
- result = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv);
- if(result != Success) return result;
-
- portPriv->type = XvInputMask;
-
- /* save a copy of these parameters */
- portPriv->vid_x = vid_x; portPriv->vid_y = vid_y;
- portPriv->vid_w = vid_w; portPriv->vid_h = vid_h;
- portPriv->drw_x = drw_x; portPriv->drw_y = drw_y;
- portPriv->drw_w = drw_w; portPriv->drw_h = drw_h;
-
- /* make sure we have the most recent copy of the clientClip */
- xf86XVCopyClip(portPriv, pGC);
-
- /* To indicate to the DI layer that we were successful */
- pPort->pDraw = pDraw;
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- return(xf86XVReputVideo(portPriv));
-}
-
-static int
-xf86XVPutStill(
- ClientPtr client,
- DrawablePtr pDraw,
- XvPortPtr pPort,
- GCPtr pGC,
- INT16 vid_x, INT16 vid_y,
- CARD16 vid_w, CARD16 vid_h,
- INT16 drw_x, INT16 drw_y,
- CARD16 drw_w, CARD16 drw_h
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- if (pDraw->type != DRAWABLE_WINDOW)
- return BadAlloc;
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- WinBox.x1 = pDraw->x + drw_x;
- WinBox.y1 = pDraw->y + drw_y;
- WinBox.x2 = WinBox.x1 + drw_w;
- WinBox.y2 = WinBox.y1 + drw_h;
-
- xf86XVCopyCompositeClip(portPriv, pGC, pDraw);
-
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip);
-
- if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) {
- RegionRec VPReg;
- BoxRec VPBox;
-
- VPBox.x1 = portPriv->pScrn->frameX0;
- VPBox.y1 = portPriv->pScrn->frameY0;
- VPBox.x2 = portPriv->pScrn->frameX1 + 1;
- VPBox.y2 = portPriv->pScrn->frameY1 + 1;
-
- RegionInit(&VPReg, &VPBox, 1);
- RegionIntersect(&ClipRegion, &ClipRegion, &VPReg);
- RegionUninit(&VPReg);
- }
-
- if(portPriv->pDraw) {
- xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv);
- }
-
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto PUT_STILL_BAILOUT;
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) {
- BoxPtr clipBox = RegionRects(&ClipRegion);
- if( (RegionNumRects(&ClipRegion) != 1) ||
- (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) ||
- (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2))
- {
- clippedAway = TRUE;
- goto PUT_STILL_BAILOUT;
- }
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->PutStill)(portPriv->pScrn,
- vid_x, vid_y, WinBox.x1, WinBox.y1,
- vid_w, vid_h, drw_w, drw_h,
- &ClipRegion, portPriv->DevPriv.ptr,
- pDraw);
-
- if((ret == Success) &&
- (portPriv->AdaptorRec->flags & VIDEO_OVERLAID_STILLS)) {
-
- xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv);
- portPriv->isOn = XV_ON;
- portPriv->vid_x = vid_x; portPriv->vid_y = vid_y;
- portPriv->vid_w = vid_w; portPriv->vid_h = vid_h;
- portPriv->drw_x = drw_x; portPriv->drw_y = drw_y;
- portPriv->drw_w = drw_w; portPriv->drw_h = drw_h;
- portPriv->type = 0; /* no mask means it's transient and should
- not be reput once it's removed */
- pPort->pDraw = pDraw; /* make sure we can get stop requests */
- }
-
-PUT_STILL_BAILOUT:
-
- if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- /* This clip was copied and only good for one shot */
- if(!portPriv->FreeCompositeClip)
- portPriv->pCompositeClip = NULL;
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-static int
-xf86XVGetVideo(
- ClientPtr client,
- DrawablePtr pDraw,
- XvPortPtr pPort,
- GCPtr pGC,
- INT16 vid_x, INT16 vid_y,
- CARD16 vid_w, CARD16 vid_h,
- INT16 drw_x, INT16 drw_y,
- CARD16 drw_w, CARD16 drw_h
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
- int result;
-
- /* No pixmaps... For now anyhow */
- if(pDraw->type != DRAWABLE_WINDOW) {
- pPort->pDraw = (DrawablePtr)NULL;
- return BadAlloc;
- }
-
- /* If we are changing windows, unregister our port in the old window */
- if(portPriv->pDraw && (portPriv->pDraw != pDraw))
- xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv);
-
- /* Register our port with the new window */
- result = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv);
- if(result != Success) return result;
-
- portPriv->type = XvOutputMask;
-
- /* save a copy of these parameters */
- portPriv->vid_x = vid_x; portPriv->vid_y = vid_y;
- portPriv->vid_w = vid_w; portPriv->vid_h = vid_h;
- portPriv->drw_x = drw_x; portPriv->drw_y = drw_y;
- portPriv->drw_w = drw_w; portPriv->drw_h = drw_h;
-
- /* make sure we have the most recent copy of the clientClip */
- xf86XVCopyClip(portPriv, pGC);
-
- /* To indicate to the DI layer that we were successful */
- pPort->pDraw = pDraw;
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- return(xf86XVRegetVideo(portPriv));
-}
-
-static int
-xf86XVGetStill(
- ClientPtr client,
- DrawablePtr pDraw,
- XvPortPtr pPort,
- GCPtr pGC,
- INT16 vid_x, INT16 vid_y,
- CARD16 vid_w, CARD16 vid_h,
- INT16 drw_x, INT16 drw_y,
- CARD16 drw_w, CARD16 drw_h
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- if (pDraw->type != DRAWABLE_WINDOW)
- return BadAlloc;
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- WinBox.x1 = pDraw->x + drw_x;
- WinBox.y1 = pDraw->y + drw_y;
- WinBox.x2 = WinBox.x1 + drw_w;
- WinBox.y2 = WinBox.y1 + drw_h;
-
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip);
-
- if(portPriv->pDraw) {
- xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv);
- }
-
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto GET_STILL_BAILOUT;
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->GetStill)(portPriv->pScrn,
- vid_x, vid_y, WinBox.x1, WinBox.y1,
- vid_w, vid_h, drw_w, drw_h,
- &ClipRegion, portPriv->DevPriv.ptr,
- pDraw);
-
-GET_STILL_BAILOUT:
-
- if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-
-
-static int
-xf86XVStopVideo(
- ClientPtr client,
- XvPortPtr pPort,
- DrawablePtr pDraw
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
-
- if(pDraw->type != DRAWABLE_WINDOW)
- return BadAlloc;
-
- xf86XVRemovePortFromWindow((WindowPtr)pDraw, portPriv);
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- /* Must free resources. */
-
- if(portPriv->isOn > XV_OFF) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, TRUE);
- portPriv->isOn = XV_OFF;
- }
-
- return Success;
-}
-
-static int
-xf86XVSetPortAttribute(
- ClientPtr client,
- XvPortPtr pPort,
- Atom attribute,
- INT32 value
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
-
- return((*portPriv->AdaptorRec->SetPortAttribute)(portPriv->pScrn,
- attribute, value, portPriv->DevPriv.ptr));
-}
-
-
-static int
-xf86XVGetPortAttribute(
- ClientPtr client,
- XvPortPtr pPort,
- Atom attribute,
- INT32 *p_value
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
-
- return((*portPriv->AdaptorRec->GetPortAttribute)(portPriv->pScrn,
- attribute, p_value, portPriv->DevPriv.ptr));
-}
-
-
-
-static int
-xf86XVQueryBestSize(
- ClientPtr client,
- XvPortPtr pPort,
- CARD8 motion,
- CARD16 vid_w, CARD16 vid_h,
- CARD16 drw_w, CARD16 drw_h,
- unsigned int *p_w, unsigned int *p_h
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
-
- (*portPriv->AdaptorRec->QueryBestSize)(portPriv->pScrn,
- (Bool)motion, vid_w, vid_h, drw_w, drw_h,
- p_w, p_h, portPriv->DevPriv.ptr);
-
- return Success;
-}
-
-
-static int
-xf86XVPutImage(
- ClientPtr client,
- DrawablePtr pDraw,
- XvPortPtr pPort,
- GCPtr pGC,
- INT16 src_x, INT16 src_y,
- CARD16 src_w, CARD16 src_h,
- INT16 drw_x, INT16 drw_y,
- CARD16 drw_w, CARD16 drw_h,
- XvImagePtr format,
- unsigned char* data,
- Bool sync,
- CARD16 width, CARD16 height
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
- RegionRec WinRegion;
- RegionRec ClipRegion;
- BoxRec WinBox;
- int ret = Success;
- Bool clippedAway = FALSE;
-
- if (pDraw->type != DRAWABLE_WINDOW)
- return BadAlloc;
-
- if(!portPriv->pScrn->vtSema) return Success; /* Success ? */
-
- xf86XVCopyCompositeClip(portPriv, pGC, pDraw);
-
- WinBox.x1 = pDraw->x + drw_x;
- WinBox.y1 = pDraw->y + drw_y;
- WinBox.x2 = WinBox.x1 + drw_w;
- WinBox.y2 = WinBox.y1 + drw_h;
-
- RegionInit(&WinRegion, &WinBox, 1);
- RegionNull(&ClipRegion);
- RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip);
-
- if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) {
- RegionRec VPReg;
- BoxRec VPBox;
-
- VPBox.x1 = portPriv->pScrn->frameX0;
- VPBox.y1 = portPriv->pScrn->frameY0;
- VPBox.x2 = portPriv->pScrn->frameX1 + 1;
- VPBox.y2 = portPriv->pScrn->frameY1 + 1;
-
- RegionInit(&VPReg, &VPBox, 1);
- RegionIntersect(&ClipRegion, &ClipRegion, &VPReg);
- RegionUninit(&VPReg);
- }
-
- /* If we are changing windows, unregister our port in the old window */
- if(portPriv->pDraw && (portPriv->pDraw != pDraw))
- xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv);
-
- /* Register our port with the new window */
- ret = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv);
- if(ret != Success) goto PUT_IMAGE_BAILOUT;
-
- if(!RegionNotEmpty(&ClipRegion)) {
- clippedAway = TRUE;
- goto PUT_IMAGE_BAILOUT;
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) {
- BoxPtr clipBox = RegionRects(&ClipRegion);
- if( (RegionNumRects(&ClipRegion) != 1) ||
- (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) ||
- (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2))
- {
- clippedAway = TRUE;
- goto PUT_IMAGE_BAILOUT;
- }
- }
-
- if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) {
- RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion);
- }
-
- ret = (*portPriv->AdaptorRec->PutImage)(portPriv->pScrn,
- src_x, src_y, WinBox.x1, WinBox.y1,
- src_w, src_h, drw_w, drw_h, format->id, data, width, height,
- sync, &ClipRegion, portPriv->DevPriv.ptr,
- pDraw);
-
- if((ret == Success) &&
- (portPriv->AdaptorRec->flags & VIDEO_OVERLAID_IMAGES)) {
-
- portPriv->isOn = XV_ON;
- portPriv->vid_x = src_x; portPriv->vid_y = src_y;
- portPriv->vid_w = src_w; portPriv->vid_h = src_h;
- portPriv->drw_x = drw_x; portPriv->drw_y = drw_y;
- portPriv->drw_w = drw_w; portPriv->drw_h = drw_h;
- portPriv->type = 0; /* no mask means it's transient and should
- not be reput once it's removed */
- pPort->pDraw = pDraw; /* make sure we can get stop requests */
- }
-
-PUT_IMAGE_BAILOUT:
-
- if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) {
- (*portPriv->AdaptorRec->StopVideo)(
- portPriv->pScrn, portPriv->DevPriv.ptr, FALSE);
- portPriv->isOn = XV_PENDING;
- }
-
- /* This clip was copied and only good for one shot */
- if(!portPriv->FreeCompositeClip)
- portPriv->pCompositeClip = NULL;
-
- RegionUninit(&WinRegion);
- RegionUninit(&ClipRegion);
-
- return ret;
-}
-
-
-static int
-xf86XVQueryImageAttributes(
- ClientPtr client,
- XvPortPtr pPort,
- XvImagePtr format,
- CARD16 *width,
- CARD16 *height,
- int *pitches,
- int *offsets
-){
- XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr);
-
- return (*portPriv->AdaptorRec->QueryImageAttributes)(portPriv->pScrn,
- format->id, width, height, pitches, offsets);
-}
-
-void
-xf86XVFillKeyHelperDrawable (DrawablePtr pDraw, CARD32 key, RegionPtr fillboxes)
-{
- ScreenPtr pScreen = pDraw->pScreen;
- ChangeGCVal pval[2];
- BoxPtr pbox = RegionRects(fillboxes);
- int i, nbox = RegionNumRects(fillboxes);
- xRectangle *rects;
- GCPtr gc;
-
- if(!xf86Screens[pScreen->myNum]->vtSema) return;
-
- gc = GetScratchGC(pDraw->depth, pScreen);
- pval[0].val = key;
- pval[1].val = IncludeInferiors;
- (void) ChangeGC(NullClient, gc, GCForeground|GCSubwindowMode, pval);
- ValidateGC(pDraw, gc);
-
- rects = malloc(nbox * sizeof(xRectangle));
-
- for(i = 0; i < nbox; i++, pbox++)
- {
- rects[i].x = pbox->x1 - pDraw->x;
- rects[i].y = pbox->y1 - pDraw->y;
- rects[i].width = pbox->x2 - pbox->x1;
- rects[i].height = pbox->y2 - pbox->y1;
- }
-
- (*gc->ops->PolyFillRect)(pDraw, gc, nbox, rects);
-
- free(rects);
- FreeScratchGC (gc);
-}
-
-void
-xf86XVFillKeyHelper (ScreenPtr pScreen, CARD32 key, RegionPtr fillboxes)
-{
- xf86XVFillKeyHelperDrawable (&pScreen->root->drawable, key, fillboxes);
-}
-
-void
-xf86XVFillKeyHelperPort (DrawablePtr pDraw, pointer data, CARD32 key, RegionPtr clipboxes, Bool fillEverything)
-{
- WindowPtr pWin = (WindowPtr)pDraw;
- XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin);
- XvPortRecPrivatePtr portPriv = NULL;
- RegionRec reg;
- RegionPtr fillboxes;
-
- while (WinPriv) {
- XvPortRecPrivatePtr pPriv = WinPriv->PortRec;
-
- if (data == pPriv->DevPriv.ptr) {
- portPriv = pPriv;
- break;
- }
-
- WinPriv = WinPriv->next;
- }
-
- if (!portPriv)
- return;
-
- if (!portPriv->ckeyFilled)
- portPriv->ckeyFilled = RegionCreate(NULL, 0);
-
- if (!fillEverything) {
- RegionNull(®);
- fillboxes = ®
- RegionSubtract(fillboxes, clipboxes, portPriv->ckeyFilled);
-
- if (!RegionNotEmpty(fillboxes))
- goto out;
- } else
- fillboxes = clipboxes;
-
-
- RegionCopy(portPriv->ckeyFilled, clipboxes);
-
- xf86XVFillKeyHelperDrawable(pDraw, key, fillboxes);
-out:
- if (!fillEverything)
- RegionUninit(®);
-}
-
-
-/* xf86XVClipVideoHelper -
-
- Takes the dst box in standard X BoxRec form (top and left
- edges inclusive, bottom and right exclusive). The new dst
- box is returned. The source boundaries are given (x1, y1
- inclusive, x2, y2 exclusive) and returned are the new source
- boundaries in 16.16 fixed point.
-*/
-
-Bool
-xf86XVClipVideoHelper(
- BoxPtr dst,
- INT32 *xa,
- INT32 *xb,
- INT32 *ya,
- INT32 *yb,
- RegionPtr reg,
- INT32 width,
- INT32 height
-){
- double xsw, xdw, ysw, ydw;
- INT32 delta;
- BoxPtr extents = RegionExtents(reg);
- int diff;
-
- xsw = (*xb - *xa) << 16;
- xdw = dst->x2 - dst->x1;
- ysw = (*yb - *ya) << 16;
- ydw = dst->y2 - dst->y1;
-
- *xa <<= 16; *xb <<= 16;
- *ya <<= 16; *yb <<= 16;
-
- diff = extents->x1 - dst->x1;
- if (diff > 0) {
- dst->x1 = extents->x1;
- *xa += (diff * xsw) / xdw;
- }
- diff = dst->x2 - extents->x2;
- if (diff > 0) {
- dst->x2 = extents->x2;
- *xb -= (diff * xsw) / xdw;
- }
- diff = extents->y1 - dst->y1;
- if (diff > 0) {
- dst->y1 = extents->y1;
- *ya += (diff * ysw) / ydw;
- }
- diff = dst->y2 - extents->y2;
- if (diff > 0) {
- dst->y2 = extents->y2;
- *yb -= (diff * ysw) / ydw;
- }
-
- if (*xa < 0) {
- diff = (((-*xa) * xdw) + xsw - 1) / xsw;
- dst->x1 += diff;
- *xa += (diff * xsw) / xdw;
- }
- delta = *xb - (width << 16);
- if (delta > 0) {
- diff = ((delta * xdw) + xsw - 1) / xsw;
- dst->x2 -= diff;
- *xb -= (diff * xsw) / xdw;
- }
- if (*xa >= *xb) return FALSE;
-
- if (*ya < 0) {
- diff = (((-*ya) * ydw) + ysw - 1) / ysw;
- dst->y1 += diff;
- *ya += (diff * ysw) / ydw;
- }
- delta = *yb - (height << 16);
- if (delta > 0) {
- diff = ((delta * ydw) + ysw - 1) / ysw;
- dst->y2 -= diff;
- *yb -= (diff * ysw) / ydw;
- }
- if (*ya >= *yb) return FALSE;
-
- if ((dst->x1 > extents->x1) || (dst->x2 < extents->x2) ||
- (dst->y1 > extents->y1) || (dst->y2 < extents->y2))
- {
- RegionRec clipReg;
- RegionInit(&clipReg, dst, 1);
- RegionIntersect(reg, reg, &clipReg);
- RegionUninit(&clipReg);
- }
- return TRUE;
-}
-
-void
-xf86XVCopyYUV12ToPacked(
- const void *srcy,
- const void *srcv,
- const void *srcu,
- void *dst,
- int srcPitchy,
- int srcPitchuv,
- int dstPitch,
- int h,
- int w
-){
- CARD32 *Dst;
- const CARD8 *Y, *U, *V;
- int i, j;
-
- w >>= 1;
-
- for (j = 0; j < h; j++) {
- Dst = dst;
- Y = srcy; V = srcv; U = srcu;
- i = w;
- while (i >= 4) {
-#if X_BYTE_ORDER == X_LITTLE_ENDIAN
- Dst[0] = Y[0] | (Y[1] << 16) | (U[0] << 8) | (V[0] << 24);
- Dst[1] = Y[2] | (Y[3] << 16) | (U[1] << 8) | (V[1] << 24);
- Dst[2] = Y[4] | (Y[5] << 16) | (U[2] << 8) | (V[2] << 24);
- Dst[3] = Y[6] | (Y[7] << 16) | (U[3] << 8) | (V[3] << 24);
-#else
- /* This assumes a little-endian framebuffer */
- Dst[0] = (Y[0] << 24) | (Y[1] << 8) | (U[0] << 16) | V[0];
- Dst[1] = (Y[2] << 24) | (Y[3] << 8) | (U[1] << 16) | V[1];
- Dst[2] = (Y[4] << 24) | (Y[5] << 8) | (U[2] << 16) | V[2];
- Dst[3] = (Y[6] << 24) | (Y[7] << 8) | (U[3] << 16) | V[3];
-#endif
- Dst += 4; Y += 8; V += 4; U += 4;
- i -= 4;
- }
-
- while (i--) {
-#if X_BYTE_ORDER == X_LITTLE_ENDIAN
- Dst[0] = Y[0] | (Y[1] << 16) | (U[0] << 8) | (V[0] << 24);
-#else
- /* This assumes a little-endian framebuffer */
- Dst[0] = (Y[0] << 24) | (Y[1] << 8) | (U[0] << 16) | V[0];
-#endif
- Dst++; Y += 2; V++; U++;
- }
-
- dst = (CARD8 *)dst + dstPitch;
- srcy = (const CARD8 *)srcy + srcPitchy;
- if (j & 1) {
- srcu = (const CARD8 *)srcu + srcPitchuv;
- srcv = (const CARD8 *)srcv + srcPitchuv;
- }
- }
-}
-
-void
-xf86XVCopyPacked(
- const void *src,
- void *dst,
- int srcPitch,
- int dstPitch,
- int h,
- int w
-){
- const CARD32 *Src;
- CARD32 *Dst;
- int i;
-
- w >>= 1;
- while (--h >= 0) {
- do {
- Dst = dst; Src = src;
- i = w;
- while (i >= 4) {
- Dst[0] = Src[0];
- Dst[1] = Src[1];
- Dst[2] = Src[2];
- Dst[3] = Src[3];
- Dst += 4; Src += 4; i -= 4;
- }
- if (!i) break;
- Dst[0] = Src[0];
- if (i == 1) break;
- Dst[1] = Src[1];
- if (i == 2) break;
- Dst[2] = Src[2];
- } while (0);
-
- src = (const CARD8 *)src + srcPitch;
- dst = (CARD8 *)dst + dstPitch;
- }
-}
+/* + * XFree86 Xv DDX written by Mark Vojkovich (markv@valinux.com) + */ +/* + * Copyright (c) 1998-2003 by The XFree86 Project, Inc. + * + * 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 + * THE COPYRIGHT HOLDER(S) OR AUTHOR(S) 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 copyright holder(s) + * and author(s) 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 copyright holder(s) and author(s). + */ + + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include "misc.h" +#include "xf86.h" +#include "xf86_OSproc.h" + +#include <X11/X.h> +#include <X11/Xproto.h> +#include "scrnintstr.h" +#include "regionstr.h" +#include "windowstr.h" +#include "pixmapstr.h" +#include "mivalidate.h" +#include "validate.h" +#include "resource.h" +#include "gcstruct.h" +#include "dixstruct.h" + +#include <X11/extensions/Xv.h> +#include <X11/extensions/Xvproto.h> +#include "xvdix.h" +#include "xvmodproc.h" + +#include "xf86xvpriv.h" + + +/* XvScreenRec fields */ + +static Bool xf86XVCloseScreen(int, ScreenPtr); +static int xf86XVQueryAdaptors(ScreenPtr, XvAdaptorPtr *, int *); + +/* XvAdaptorRec fields */ + +static int xf86XVAllocatePort(unsigned long, XvPortPtr, XvPortPtr*); +static int xf86XVFreePort(XvPortPtr); +static int xf86XVPutVideo(ClientPtr, DrawablePtr,XvPortPtr, GCPtr, + INT16, INT16, CARD16, CARD16, + INT16, INT16, CARD16, CARD16); +static int xf86XVPutStill(ClientPtr, DrawablePtr,XvPortPtr, GCPtr, + INT16, INT16, CARD16, CARD16, + INT16, INT16, CARD16, CARD16); +static int xf86XVGetVideo(ClientPtr, DrawablePtr,XvPortPtr, GCPtr, + INT16, INT16, CARD16, CARD16, + INT16, INT16, CARD16, CARD16); +static int xf86XVGetStill(ClientPtr, DrawablePtr,XvPortPtr, GCPtr, + INT16, INT16, CARD16, CARD16, + INT16, INT16, CARD16, CARD16); +static int xf86XVStopVideo(ClientPtr, XvPortPtr, DrawablePtr); +static int xf86XVSetPortAttribute(ClientPtr, XvPortPtr, Atom, INT32); +static int xf86XVGetPortAttribute(ClientPtr, XvPortPtr, Atom, INT32*); +static int xf86XVQueryBestSize(ClientPtr, XvPortPtr, CARD8, + CARD16, CARD16,CARD16, CARD16, + unsigned int*, unsigned int*); +static int xf86XVPutImage(ClientPtr, DrawablePtr, XvPortPtr, GCPtr, + INT16, INT16, CARD16, CARD16, + INT16, INT16, CARD16, CARD16, + XvImagePtr, unsigned char*, Bool, + CARD16, CARD16); +static int xf86XVQueryImageAttributes(ClientPtr, XvPortPtr, XvImagePtr, + CARD16*, CARD16*, int*, int*); + + +/* ScreenRec fields */ + +static Bool xf86XVDestroyWindow(WindowPtr pWin); +static void xf86XVWindowExposures(WindowPtr pWin, RegionPtr r1, RegionPtr r2); +static void xf86XVPostValidateTree(WindowPtr pWin, WindowPtr pLayerWin, VTKind kind); +static void xf86XVClipNotify(WindowPtr pWin, int dx, int dy); + +#define PostValidateTreeUndefined ((PostValidateTreeProcPtr)-1) + +/* ScrnInfoRec functions */ + +static Bool xf86XVEnterVT(int, int); +static void xf86XVLeaveVT(int, int); +static void xf86XVAdjustFrame(int index, int x, int y, int flags); +static void xf86XVModeSet(ScrnInfoPtr pScrn); + +/* misc */ + +static Bool xf86XVInitAdaptors(ScreenPtr, XF86VideoAdaptorPtr*, int); + + +static DevPrivateKeyRec XF86XVWindowKeyRec; +#define XF86XVWindowKey (&XF86XVWindowKeyRec) + +DevPrivateKey XF86XvScreenKey; + +static unsigned long PortResource = 0; + +DevPrivateKey (*XvGetScreenKeyProc)(void) = NULL; +unsigned long (*XvGetRTPortProc)(void) = NULL; +int (*XvScreenInitProc)(ScreenPtr) = NULL; + +#define GET_XV_SCREEN(pScreen) \ + ((XvScreenPtr)dixLookupPrivate(&(pScreen)->devPrivates, XF86XvScreenKey)) + +#define GET_XF86XV_SCREEN(pScreen) \ + ((XF86XVScreenPtr)(GET_XV_SCREEN(pScreen)->devPriv.ptr)) + +#define GET_XF86XV_WINDOW(pWin) \ + ((XF86XVWindowPtr)dixLookupPrivate(&(pWin)->devPrivates, XF86XVWindowKey)) + +static xf86XVInitGenericAdaptorPtr *GenDrivers = NULL; +static int NumGenDrivers = 0; + +int +xf86XVRegisterGenericAdaptorDriver( + xf86XVInitGenericAdaptorPtr InitFunc +){ + xf86XVInitGenericAdaptorPtr *newdrivers; + + newdrivers = realloc(GenDrivers, sizeof(xf86XVInitGenericAdaptorPtr) * + (1 + NumGenDrivers)); + if (!newdrivers) + return 0; + GenDrivers = newdrivers; + + GenDrivers[NumGenDrivers++] = InitFunc; + + return 1; +} + +int +xf86XVListGenericAdaptors( + ScrnInfoPtr pScrn, + XF86VideoAdaptorPtr **adaptors +){ + int i,j,n,num; + XF86VideoAdaptorPtr *DrivAdap,*new; + + num = 0; + *adaptors = NULL; + /* + * The v4l driver registers itself first, but can use surfaces registered + * by other drivers. So, call the v4l driver last. + */ + for (i = NumGenDrivers; --i >= 0; ) { + DrivAdap = NULL; + n = (*GenDrivers[i])(pScrn, &DrivAdap); + if (0 == n) + continue; + new = realloc(*adaptors, sizeof(XF86VideoAdaptorPtr) * (num+n)); + if (NULL == new) + continue; + *adaptors = new; + for (j = 0; j < n; j++, num++) + (*adaptors)[num] = DrivAdap[j]; + } + return num; +} + + +/**************** Offscreen surface stuff *******************/ + +typedef struct { + XF86OffscreenImagePtr images; + int num; +} OffscreenImageRec; + +static DevPrivateKeyRec OffscreenPrivateKeyRec; +#define OffscreenPrivateKey (&OffscreenPrivateKeyRec) +#define GetOffscreenImage(pScreen) ((OffscreenImageRec *) dixLookupPrivate(&(pScreen)->devPrivates, OffscreenPrivateKey)) + +Bool +xf86XVRegisterOffscreenImages( + ScreenPtr pScreen, + XF86OffscreenImagePtr images, + int num +){ + OffscreenImageRec *OffscreenImage; + /* This function may be called before xf86XVScreenInit, so there's + * no better place than this to call dixRegisterPrivateKey to ensure we + * have space reserved. After the first call it is a no-op. */ + if(!dixRegisterPrivateKey(OffscreenPrivateKey, PRIVATE_SCREEN, sizeof(OffscreenImageRec)) || + !(OffscreenImage = GetOffscreenImage(pScreen))) + /* Every X.org driver assumes this function always succeeds, so + * just die on allocation failure. */ + FatalError("Could not allocate private storage for XV offscreen images.\n"); + + OffscreenImage->num = num; + OffscreenImage->images = images; + return TRUE; +} + +XF86OffscreenImagePtr +xf86XVQueryOffscreenImages( + ScreenPtr pScreen, + int *num +){ + OffscreenImageRec *OffscreenImage = GetOffscreenImage(pScreen); + *num = OffscreenImage->num; + return OffscreenImage->images; +} + + +XF86VideoAdaptorPtr +xf86XVAllocateVideoAdaptorRec(ScrnInfoPtr pScrn) +{ + return calloc(1, sizeof(XF86VideoAdaptorRec)); +} + +void +xf86XVFreeVideoAdaptorRec(XF86VideoAdaptorPtr ptr) +{ + free(ptr); +} + + +Bool +xf86XVScreenInit( + ScreenPtr pScreen, + XF86VideoAdaptorPtr *adaptors, + int num +){ + ScrnInfoPtr pScrn; + XF86XVScreenPtr ScreenPriv; + XvScreenPtr pxvs; + + if(num <= 0 || + !XvGetScreenKeyProc || !XvGetRTPortProc || !XvScreenInitProc) + return FALSE; + + if(Success != (*XvScreenInitProc)(pScreen)) return FALSE; + + if (!dixRegisterPrivateKey(&XF86XVWindowKeyRec, PRIVATE_WINDOW, 0)) + return FALSE; + + XF86XvScreenKey = (*XvGetScreenKeyProc)(); + + PortResource = (*XvGetRTPortProc)(); + + pxvs = GET_XV_SCREEN(pScreen); + + /* Anyone initializing the Xv layer must provide these two. + The Xv di layer calls them without even checking if they exist! */ + + pxvs->ddCloseScreen = xf86XVCloseScreen; + pxvs->ddQueryAdaptors = xf86XVQueryAdaptors; + + /* The Xv di layer provides us with a private hook so that we don't + have to allocate our own screen private. They also provide + a CloseScreen hook so that we don't have to wrap it. I'm not + sure that I appreciate that. */ + + ScreenPriv = malloc(sizeof(XF86XVScreenRec)); + pxvs->devPriv.ptr = (pointer)ScreenPriv; + + if(!ScreenPriv) return FALSE; + + pScrn = xf86Screens[pScreen->myNum]; + + ScreenPriv->DestroyWindow = pScreen->DestroyWindow; + ScreenPriv->WindowExposures = pScreen->WindowExposures; + ScreenPriv->PostValidateTree = PostValidateTreeUndefined; + ScreenPriv->ClipNotify = pScreen->ClipNotify; + ScreenPriv->EnterVT = pScrn->EnterVT; + ScreenPriv->LeaveVT = pScrn->LeaveVT; + ScreenPriv->AdjustFrame = pScrn->AdjustFrame; + ScreenPriv->ModeSet = pScrn->ModeSet; + + pScreen->DestroyWindow = xf86XVDestroyWindow; + pScreen->WindowExposures = xf86XVWindowExposures; + pScreen->ClipNotify = xf86XVClipNotify; + pScrn->EnterVT = xf86XVEnterVT; + pScrn->LeaveVT = xf86XVLeaveVT; + if(pScrn->AdjustFrame) + pScrn->AdjustFrame = xf86XVAdjustFrame; + pScrn->ModeSet = xf86XVModeSet; + + if(!xf86XVInitAdaptors(pScreen, adaptors, num)) + return FALSE; + + return TRUE; +} + +static void +xf86XVFreeAdaptor(XvAdaptorPtr pAdaptor) +{ + int i; + + free(pAdaptor->name); + pAdaptor->name = NULL; + + if(pAdaptor->pEncodings) { + XvEncodingPtr pEncode = pAdaptor->pEncodings; + + for(i = 0; i < pAdaptor->nEncodings; i++, pEncode++) + free(pEncode->name); + free(pAdaptor->pEncodings); + pAdaptor->pEncodings = NULL; + } + + free(pAdaptor->pFormats); + pAdaptor->pFormats = NULL; + + if(pAdaptor->pPorts) { + XvPortPtr pPort = pAdaptor->pPorts; + XvPortRecPrivatePtr pPriv; + + for(i = 0; i < pAdaptor->nPorts; i++, pPort++) { + pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr; + if(pPriv) { + if(pPriv->clientClip) + RegionDestroy(pPriv->clientClip); + if(pPriv->pCompositeClip && pPriv->FreeCompositeClip) + RegionDestroy(pPriv->pCompositeClip); + if (pPriv->ckeyFilled) + RegionDestroy(pPriv->ckeyFilled); + free(pPriv); + } + } + free(pAdaptor->pPorts); + pAdaptor->pPorts = NULL; + } + + if(pAdaptor->pAttributes) { + XvAttributePtr pAttribute = pAdaptor->pAttributes; + + for(i = 0; i < pAdaptor->nAttributes; i++, pAttribute++) + free(pAttribute->name); + free(pAdaptor->pAttributes); + pAdaptor->pAttributes = NULL; + } + + free(pAdaptor->pImages); + free(pAdaptor->devPriv.ptr); + pAdaptor->pImages = NULL; + pAdaptor->devPriv.ptr = NULL; +} + +static Bool +xf86XVInitAdaptors( + ScreenPtr pScreen, + XF86VideoAdaptorPtr *infoPtr, + int number +) { + XvScreenPtr pxvs = GET_XV_SCREEN(pScreen); + ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; + XF86VideoAdaptorPtr adaptorPtr; + XvAdaptorPtr pAdaptor, pa; + XvAdaptorRecPrivatePtr adaptorPriv; + int na, numAdaptor; + XvPortRecPrivatePtr portPriv; + XvPortPtr pPort, pp; + int numPort; + XF86AttributePtr attributePtr; + XvAttributePtr pAttribute, pat; + XF86VideoFormatPtr formatPtr; + XvFormatPtr pFormat, pf; + int numFormat, totFormat; + XF86VideoEncodingPtr encodingPtr; + XvEncodingPtr pEncode, pe; + XF86ImagePtr imagePtr; + XvImagePtr pImage, pi; + int numVisuals; + VisualPtr pVisual; + int i; + + pxvs->nAdaptors = 0; + pxvs->pAdaptors = NULL; + + if(!(pAdaptor = calloc(number, sizeof(XvAdaptorRec)))) + return FALSE; + + for(pa = pAdaptor, na = 0, numAdaptor = 0; na < number; na++, adaptorPtr++) { + adaptorPtr = infoPtr[na]; + + if(!adaptorPtr->StopVideo || !adaptorPtr->SetPortAttribute || + !adaptorPtr->GetPortAttribute || !adaptorPtr->QueryBestSize) + continue; + + /* client libs expect at least one encoding */ + if(!adaptorPtr->nEncodings || !adaptorPtr->pEncodings) + continue; + + pa->type = adaptorPtr->type; + + if(!adaptorPtr->PutVideo && !adaptorPtr->GetVideo) + pa->type &= ~XvVideoMask; + + if(!adaptorPtr->PutStill && !adaptorPtr->GetStill) + pa->type &= ~XvStillMask; + + if(!adaptorPtr->PutImage || !adaptorPtr->QueryImageAttributes) + pa->type &= ~XvImageMask; + + if(!adaptorPtr->PutVideo && !adaptorPtr->PutImage && + !adaptorPtr->PutStill) + pa->type &= ~XvInputMask; + + if(!adaptorPtr->GetVideo && !adaptorPtr->GetStill) + pa->type &= ~XvOutputMask; + + if(!(adaptorPtr->type & (XvPixmapMask | XvWindowMask))) + continue; + if(!(adaptorPtr->type & (XvImageMask | XvVideoMask | XvStillMask))) + continue; + + pa->pScreen = pScreen; + pa->ddAllocatePort = xf86XVAllocatePort; + pa->ddFreePort = xf86XVFreePort; + pa->ddPutVideo = xf86XVPutVideo; + pa->ddPutStill = xf86XVPutStill; + pa->ddGetVideo = xf86XVGetVideo; + pa->ddGetStill = xf86XVGetStill; + pa->ddStopVideo = xf86XVStopVideo; + pa->ddPutImage = xf86XVPutImage; + pa->ddSetPortAttribute = xf86XVSetPortAttribute; + pa->ddGetPortAttribute = xf86XVGetPortAttribute; + pa->ddQueryBestSize = xf86XVQueryBestSize; + pa->ddQueryImageAttributes = xf86XVQueryImageAttributes; + pa->name = strdup(adaptorPtr->name); + + if(adaptorPtr->nEncodings && + (pEncode = calloc(adaptorPtr->nEncodings, sizeof(XvEncodingRec)))) { + + for(pe = pEncode, encodingPtr = adaptorPtr->pEncodings, i = 0; + i < adaptorPtr->nEncodings; pe++, i++, encodingPtr++) + { + pe->id = encodingPtr->id; + pe->pScreen = pScreen; + pe->name = strdup(encodingPtr->name); + pe->width = encodingPtr->width; + pe->height = encodingPtr->height; + pe->rate.numerator = encodingPtr->rate.numerator; + pe->rate.denominator = encodingPtr->rate.denominator; + } + pa->nEncodings = adaptorPtr->nEncodings; + pa->pEncodings = pEncode; + } + + if(adaptorPtr->nImages && + (pImage = calloc(adaptorPtr->nImages, sizeof(XvImageRec)))) { + + for(i = 0, pi = pImage, imagePtr = adaptorPtr->pImages; + i < adaptorPtr->nImages; i++, pi++, imagePtr++) + { + pi->id = imagePtr->id; + pi->type = imagePtr->type; + pi->byte_order = imagePtr->byte_order; + memcpy(pi->guid, imagePtr->guid, 16); + pi->bits_per_pixel = imagePtr->bits_per_pixel; + pi->format = imagePtr->format; + pi->num_planes = imagePtr->num_planes; + pi->depth = imagePtr->depth; + pi->red_mask = imagePtr->red_mask; + pi->green_mask = imagePtr->green_mask; + pi->blue_mask = imagePtr->blue_mask; + pi->y_sample_bits = imagePtr->y_sample_bits; + pi->u_sample_bits = imagePtr->u_sample_bits; + pi->v_sample_bits = imagePtr->v_sample_bits; + pi->horz_y_period = imagePtr->horz_y_period; + pi->horz_u_period = imagePtr->horz_u_period; + pi->horz_v_period = imagePtr->horz_v_period; + pi->vert_y_period = imagePtr->vert_y_period; + pi->vert_u_period = imagePtr->vert_u_period; + pi->vert_v_period = imagePtr->vert_v_period; + memcpy(pi->component_order, imagePtr->component_order, 32); + pi->scanline_order = imagePtr->scanline_order; + } + pa->nImages = adaptorPtr->nImages; + pa->pImages = pImage; + } + + if(adaptorPtr->nAttributes && + (pAttribute = calloc(adaptorPtr->nAttributes, sizeof(XvAttributeRec)))) + { + for(pat = pAttribute, attributePtr = adaptorPtr->pAttributes, i = 0; + i < adaptorPtr->nAttributes; pat++, i++, attributePtr++) + { + pat->flags = attributePtr->flags; + pat->min_value = attributePtr->min_value; + pat->max_value = attributePtr->max_value; + pat->name = strdup(attributePtr->name); + } + pa->nAttributes = adaptorPtr->nAttributes; + pa->pAttributes = pAttribute; + } + + + totFormat = adaptorPtr->nFormats; + + if(!(pFormat = calloc(totFormat, sizeof(XvFormatRec)))) { + xf86XVFreeAdaptor(pa); + continue; + } + for(pf = pFormat, i = 0, numFormat = 0, formatPtr = adaptorPtr->pFormats; + i < adaptorPtr->nFormats; i++, formatPtr++) + { + numVisuals = pScreen->numVisuals; + pVisual = pScreen->visuals; + + while(numVisuals--) { + if((pVisual->class == formatPtr->class) && + (pVisual->nplanes == formatPtr->depth)) { + + if(numFormat >= totFormat) { + void *moreSpace; + totFormat *= 2; + moreSpace = realloc(pFormat, + totFormat * sizeof(XvFormatRec)); + if(!moreSpace) break; + pFormat = moreSpace; + pf = pFormat + numFormat; + } + + pf->visual = pVisual->vid; + pf->depth = formatPtr->depth; + + pf++; + numFormat++; + } + pVisual++; + } + } + pa->nFormats = numFormat; + pa->pFormats = pFormat; + if(!numFormat) { + xf86XVFreeAdaptor(pa); + continue; + } + + if(!(adaptorPriv = calloc(1, sizeof(XvAdaptorRecPrivate)))) { + xf86XVFreeAdaptor(pa); + continue; + } + + adaptorPriv->flags = adaptorPtr->flags; + adaptorPriv->PutVideo = adaptorPtr->PutVideo; + adaptorPriv->PutStill = adaptorPtr->PutStill; + adaptorPriv->GetVideo = adaptorPtr->GetVideo; + adaptorPriv->GetStill = adaptorPtr->GetStill; + adaptorPriv->StopVideo = adaptorPtr->StopVideo; + adaptorPriv->SetPortAttribute = adaptorPtr->SetPortAttribute; + adaptorPriv->GetPortAttribute = adaptorPtr->GetPortAttribute; + adaptorPriv->QueryBestSize = adaptorPtr->QueryBestSize; + adaptorPriv->QueryImageAttributes = adaptorPtr->QueryImageAttributes; + adaptorPriv->PutImage = adaptorPtr->PutImage; + adaptorPriv->ReputImage = adaptorPtr->ReputImage; /* image/still */ + + pa->devPriv.ptr = (pointer)adaptorPriv; + + if(!(pPort = calloc(adaptorPtr->nPorts, sizeof(XvPortRec)))) { + xf86XVFreeAdaptor(pa); + continue; + } + for(pp = pPort, i = 0, numPort = 0; + i < adaptorPtr->nPorts; i++) { + + if(!(pp->id = FakeClientID(0))) + continue; + + if(!(portPriv = calloc(1, sizeof(XvPortRecPrivate)))) + continue; + + if(!AddResource(pp->id, PortResource, pp)) { + free(portPriv); + continue; + } + + pp->pAdaptor = pa; + pp->pNotify = (XvPortNotifyPtr)NULL; + pp->pDraw = (DrawablePtr)NULL; + pp->client = (ClientPtr)NULL; + pp->grab.client = (ClientPtr)NULL; + pp->time = currentTime; + pp->devPriv.ptr = portPriv; + + portPriv->pScrn = pScrn; + portPriv->AdaptorRec = adaptorPriv; + portPriv->DevPriv.ptr = adaptorPtr->pPortPrivates[i].ptr; + + pp++; + numPort++; + } + pa->nPorts = numPort; + pa->pPorts = pPort; + if(!numPort) { + xf86XVFreeAdaptor(pa); + continue; + } + + pa->base_id = pPort->id; + + pa++; + numAdaptor++; + } + + if(numAdaptor) { + pxvs->nAdaptors = numAdaptor; + pxvs->pAdaptors = pAdaptor; + } else { + free(pAdaptor); + return FALSE; + } + + return TRUE; +} + +/* Video should be clipped to the intersection of the window cliplist + and the client cliplist specified in the GC for which the video was + initialized. When we need to reclip a window, the GC that started + the video may not even be around anymore. That's why we save the + client clip from the GC when the video is initialized. We then + use xf86XVUpdateCompositeClip to calculate the new composite clip + when we need it. This is different from what DEC did. They saved + the GC and used it's clip list when they needed to reclip the window, + even if the client clip was different from the one the video was + initialized with. If the original GC was destroyed, they had to stop + the video. I like the new method better (MArk). + + This function only works for windows. Will need to rewrite when + (if) we support pixmap rendering. +*/ + +static void +xf86XVUpdateCompositeClip(XvPortRecPrivatePtr portPriv) +{ + RegionPtr pregWin, pCompositeClip; + WindowPtr pWin; + Bool freeCompClip = FALSE; + + if(portPriv->pCompositeClip) + return; + + pWin = (WindowPtr)portPriv->pDraw; + + /* get window clip list */ + if(portPriv->subWindowMode == IncludeInferiors) { + pregWin = NotClippedByChildren(pWin); + freeCompClip = TRUE; + } else + pregWin = &pWin->clipList; + + if(!portPriv->clientClip) { + portPriv->pCompositeClip = pregWin; + portPriv->FreeCompositeClip = freeCompClip; + return; + } + + pCompositeClip = RegionCreate(NullBox, 1); + RegionCopy(pCompositeClip, portPriv->clientClip); + RegionTranslate(pCompositeClip, + portPriv->pDraw->x, portPriv->pDraw->y); + RegionIntersect(pCompositeClip, pregWin, pCompositeClip); + + portPriv->pCompositeClip = pCompositeClip; + portPriv->FreeCompositeClip = TRUE; + + if(freeCompClip) { + RegionDestroy(pregWin); + } +} + +/* Save the current clientClip and update the CompositeClip whenever + we have a fresh GC */ + +static void +xf86XVCopyClip( + XvPortRecPrivatePtr portPriv, + GCPtr pGC +){ + /* copy the new clip if it exists */ + if((pGC->clientClipType == CT_REGION) && pGC->clientClip) { + if(!portPriv->clientClip) + portPriv->clientClip = RegionCreate(NullBox, 1); + /* Note: this is in window coordinates */ + RegionCopy(portPriv->clientClip, pGC->clientClip); + RegionTranslate(portPriv->clientClip, + pGC->clipOrg.x, pGC->clipOrg.y); + } else if(portPriv->clientClip) { /* free the old clientClip */ + RegionDestroy(portPriv->clientClip); + portPriv->clientClip = NULL; + } + + /* get rid of the old clip list */ + if(portPriv->pCompositeClip && portPriv->FreeCompositeClip) { + RegionDestroy(portPriv->pCompositeClip); + } + + portPriv->pCompositeClip = pGC->pCompositeClip; + portPriv->FreeCompositeClip = FALSE; + portPriv->subWindowMode = pGC->subWindowMode; +} + +static void +xf86XVCopyCompositeClip(XvPortRecPrivatePtr portPriv, + GCPtr pGC, + DrawablePtr pDraw) +{ + if (!portPriv->clientClip) + portPriv->clientClip = RegionCreate(NullBox, 1); + /* Keep the original GC composite clip around for ReputImage */ + RegionCopy(portPriv->clientClip, pGC->pCompositeClip); + RegionTranslate(portPriv->clientClip, + -pDraw->x, -pDraw->y); + + /* get rid of the old clip list */ + if (portPriv->pCompositeClip && portPriv->FreeCompositeClip) + RegionDestroy(portPriv->pCompositeClip); + + portPriv->pCompositeClip = pGC->pCompositeClip; + portPriv->FreeCompositeClip = FALSE; + portPriv->subWindowMode = pGC->subWindowMode; +} + +static int +xf86XVRegetVideo(XvPortRecPrivatePtr portPriv) +{ + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + xf86XVUpdateCompositeClip(portPriv); + + /* translate the video region to the screen */ + WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x; + WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y; + WinBox.x2 = WinBox.x1 + portPriv->drw_w; + WinBox.y2 = WinBox.y1 + portPriv->drw_h; + + /* clip to the window composite clip */ + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip); + + /* that's all if it's totally obscured */ + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto CLIP_VIDEO_BAILOUT; + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->GetVideo)(portPriv->pScrn, + portPriv->vid_x, portPriv->vid_y, + WinBox.x1, WinBox.y1, + portPriv->vid_w, portPriv->vid_h, + portPriv->drw_w, portPriv->drw_h, + &ClipRegion, portPriv->DevPriv.ptr, + portPriv->pDraw); + + if(ret == Success) + portPriv->isOn = XV_ON; + +CLIP_VIDEO_BAILOUT: + + if((clippedAway || (ret != Success)) && portPriv->isOn == XV_ON) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + /* This clip was copied and only good for one shot */ + if(!portPriv->FreeCompositeClip) + portPriv->pCompositeClip = NULL; + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + + +static int +xf86XVReputVideo(XvPortRecPrivatePtr portPriv) +{ + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + xf86XVUpdateCompositeClip(portPriv); + + /* translate the video region to the screen */ + WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x; + WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y; + WinBox.x2 = WinBox.x1 + portPriv->drw_w; + WinBox.y2 = WinBox.y1 + portPriv->drw_h; + + /* clip to the window composite clip */ + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip); + + /* clip and translate to the viewport */ + if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) { + RegionRec VPReg; + BoxRec VPBox; + + VPBox.x1 = portPriv->pScrn->frameX0; + VPBox.y1 = portPriv->pScrn->frameY0; + VPBox.x2 = portPriv->pScrn->frameX1 + 1; + VPBox.y2 = portPriv->pScrn->frameY1 + 1; + + RegionInit(&VPReg, &VPBox, 1); + RegionIntersect(&ClipRegion, &ClipRegion, &VPReg); + RegionUninit(&VPReg); + } + + /* that's all if it's totally obscured */ + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto CLIP_VIDEO_BAILOUT; + } + + /* bailout if we have to clip but the hardware doesn't support it */ + if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) { + BoxPtr clipBox = RegionRects(&ClipRegion); + if( (RegionNumRects(&ClipRegion) != 1) || + (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) || + (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2)) + { + clippedAway = TRUE; + goto CLIP_VIDEO_BAILOUT; + } + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->PutVideo)(portPriv->pScrn, + portPriv->vid_x, portPriv->vid_y, + WinBox.x1, WinBox.y1, + portPriv->vid_w, portPriv->vid_h, + portPriv->drw_w, portPriv->drw_h, + &ClipRegion, portPriv->DevPriv.ptr, + portPriv->pDraw); + + if(ret == Success) portPriv->isOn = XV_ON; + +CLIP_VIDEO_BAILOUT: + + if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + /* This clip was copied and only good for one shot */ + if(!portPriv->FreeCompositeClip) + portPriv->pCompositeClip = NULL; + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + +/* Reput image/still */ +static int +xf86XVReputImage(XvPortRecPrivatePtr portPriv) +{ + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + xf86XVUpdateCompositeClip(portPriv); + + /* the clip can get smaller over time */ + RegionCopy(portPriv->clientClip, portPriv->pCompositeClip); + RegionTranslate(portPriv->clientClip, + -portPriv->pDraw->x, -portPriv->pDraw->y); + + /* translate the video region to the screen */ + WinBox.x1 = portPriv->pDraw->x + portPriv->drw_x; + WinBox.y1 = portPriv->pDraw->y + portPriv->drw_y; + WinBox.x2 = WinBox.x1 + portPriv->drw_w; + WinBox.y2 = WinBox.y1 + portPriv->drw_h; + + /* clip to the window composite clip */ + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, portPriv->pCompositeClip); + + /* clip and translate to the viewport */ + if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) { + RegionRec VPReg; + BoxRec VPBox; + + VPBox.x1 = portPriv->pScrn->frameX0; + VPBox.y1 = portPriv->pScrn->frameY0; + VPBox.x2 = portPriv->pScrn->frameX1 + 1; + VPBox.y2 = portPriv->pScrn->frameY1 + 1; + + RegionInit(&VPReg, &VPBox, 1); + RegionIntersect(&ClipRegion, &ClipRegion, &VPReg); + RegionUninit(&VPReg); + } + + /* that's all if it's totally obscured */ + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto CLIP_VIDEO_BAILOUT; + } + + /* bailout if we have to clip but the hardware doesn't support it */ + if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) { + BoxPtr clipBox = RegionRects(&ClipRegion); + if( (RegionNumRects(&ClipRegion) != 1) || + (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) || + (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2)) + { + clippedAway = TRUE; + goto CLIP_VIDEO_BAILOUT; + } + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->ReputImage)(portPriv->pScrn, + portPriv->vid_x, portPriv->vid_y, + WinBox.x1, WinBox.y1, + portPriv->vid_w, portPriv->vid_h, + portPriv->drw_w, portPriv->drw_h, + &ClipRegion, portPriv->DevPriv.ptr, + portPriv->pDraw); + + portPriv->isOn = (ret == Success) ? XV_ON : XV_OFF; + +CLIP_VIDEO_BAILOUT: + + if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + /* This clip was copied and only good for one shot */ + if(!portPriv->FreeCompositeClip) + portPriv->pCompositeClip = NULL; + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + + +static int +xf86XVReputAllVideo(WindowPtr pWin, pointer data) +{ + XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin); + + while(WinPriv) { + if(WinPriv->PortRec->type == XvInputMask) + xf86XVReputVideo(WinPriv->PortRec); + else + xf86XVRegetVideo(WinPriv->PortRec); + WinPriv = WinPriv->next; + } + + return WT_WALKCHILDREN; +} + +static int +xf86XVEnlistPortInWindow(WindowPtr pWin, XvPortRecPrivatePtr portPriv) +{ + XF86XVWindowPtr winPriv, PrivRoot; + + winPriv = PrivRoot = GET_XF86XV_WINDOW(pWin); + + /* Enlist our port in the window private */ + while(winPriv) { + if(winPriv->PortRec == portPriv) /* we're already listed */ + break; + winPriv = winPriv->next; + } + + if(!winPriv) { + winPriv = calloc(1, sizeof(XF86XVWindowRec)); + if(!winPriv) return BadAlloc; + winPriv->PortRec = portPriv; + winPriv->next = PrivRoot; + dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey, winPriv); + } + + portPriv->pDraw = (DrawablePtr)pWin; + + return Success; +} + + +static void +xf86XVRemovePortFromWindow(WindowPtr pWin, XvPortRecPrivatePtr portPriv) +{ + XF86XVWindowPtr winPriv, prevPriv = NULL; + winPriv = GET_XF86XV_WINDOW(pWin); + + while(winPriv) { + if(winPriv->PortRec == portPriv) { + if(prevPriv) + prevPriv->next = winPriv->next; + else + dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey, + winPriv->next); + free(winPriv); + break; + } + prevPriv = winPriv; + winPriv = winPriv->next; + } + portPriv->pDraw = NULL; + if (portPriv->ckeyFilled) { + RegionDestroy(portPriv->ckeyFilled); + portPriv->ckeyFilled = NULL; + } + portPriv->clipChanged = FALSE; +} + +static void +xf86XVReputOrStopPort(XvPortRecPrivatePtr pPriv, + WindowPtr pWin, + Bool visible) +{ + if (!visible) { + if (pPriv->isOn == XV_ON) { + (*pPriv->AdaptorRec->StopVideo)(pPriv->pScrn, pPriv->DevPriv.ptr, FALSE); + pPriv->isOn = XV_PENDING; + } + + if (!pPriv->type) /* overlaid still/image*/ + xf86XVRemovePortFromWindow(pWin, pPriv); + + return; + } + + switch (pPriv->type) { + case XvInputMask: + xf86XVReputVideo(pPriv); + break; + case XvOutputMask: + xf86XVRegetVideo(pPriv); + break; + default: /* overlaid still/image*/ + if (pPriv->AdaptorRec->ReputImage) + xf86XVReputImage(pPriv); + break; + } +} + +static void +xf86XVReputOrStopAllPorts(ScrnInfoPtr pScrn, Bool onlyChanged) +{ + ScreenPtr pScreen = pScrn->pScreen; + XvScreenPtr pxvs = GET_XV_SCREEN(pScreen); + XvAdaptorPtr pa; + int c, i; + + for (c = pxvs->nAdaptors, pa = pxvs->pAdaptors; c > 0; c--, pa++) { + XvPortPtr pPort = pa->pPorts; + + for (i = pa->nPorts; i > 0; i--, pPort++) { + XvPortRecPrivatePtr pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr; + WindowPtr pWin = (WindowPtr)pPriv->pDraw; + Bool visible; + + if (pPriv->isOn == XV_OFF || !pWin) + continue; + + if (onlyChanged && !pPriv->clipChanged) + continue; + + visible = pWin->visibility == VisibilityUnobscured || + pWin->visibility == VisibilityPartiallyObscured; + + /* + * Stop and remove still/images if + * ReputImage isn't supported. + */ + if (!pPriv->type && !pPriv->AdaptorRec->ReputImage) + visible = FALSE; + + xf86XVReputOrStopPort(pPriv, pWin, visible); + + pPriv->clipChanged = FALSE; + } + } +} + +/**** ScreenRec fields ****/ + +static Bool +xf86XVDestroyWindow(WindowPtr pWin) +{ + ScreenPtr pScreen = pWin->drawable.pScreen; + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + XF86XVWindowPtr tmp, WinPriv = GET_XF86XV_WINDOW(pWin); + int ret; + + while(WinPriv) { + XvPortRecPrivatePtr pPriv = WinPriv->PortRec; + + if(pPriv->isOn > XV_OFF) { + (*pPriv->AdaptorRec->StopVideo)( + pPriv->pScrn, pPriv->DevPriv.ptr, TRUE); + pPriv->isOn = XV_OFF; + } + + pPriv->pDraw = NULL; + tmp = WinPriv; + WinPriv = WinPriv->next; + free(tmp); + } + + dixSetPrivate(&pWin->devPrivates, XF86XVWindowKey, NULL); + + pScreen->DestroyWindow = ScreenPriv->DestroyWindow; + ret = (*pScreen->DestroyWindow)(pWin); + pScreen->DestroyWindow = xf86XVDestroyWindow; + + return ret; +} + +static void +xf86XVPostValidateTree(WindowPtr pWin, WindowPtr pLayerWin, VTKind kind) +{ + ScreenPtr pScreen; + XF86XVScreenPtr ScreenPriv; + ScrnInfoPtr pScrn; + + if (pWin) + pScreen = pWin->drawable.pScreen; + else + pScreen = pLayerWin->drawable.pScreen; + + ScreenPriv = GET_XF86XV_SCREEN(pScreen); + pScrn = xf86Screens[pScreen->myNum]; + + xf86XVReputOrStopAllPorts(pScrn, TRUE); + + pScreen->PostValidateTree = ScreenPriv->PostValidateTree; + if (pScreen->PostValidateTree) { + (*pScreen->PostValidateTree)(pWin, pLayerWin, kind); + } + ScreenPriv->PostValidateTree = PostValidateTreeUndefined; +} + +static void +xf86XVWindowExposures(WindowPtr pWin, RegionPtr reg1, RegionPtr reg2) +{ + ScreenPtr pScreen = pWin->drawable.pScreen; + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin); + XvPortRecPrivatePtr pPriv; + Bool AreasExposed; + + AreasExposed = (WinPriv && reg1 && RegionNotEmpty(reg1)); + + pScreen->WindowExposures = ScreenPriv->WindowExposures; + (*pScreen->WindowExposures)(pWin, reg1, reg2); + pScreen->WindowExposures = xf86XVWindowExposures; + + /* filter out XClearWindow/Area */ + if (!pWin->valdata) return; + + while(WinPriv) { + Bool visible = TRUE; + + pPriv = WinPriv->PortRec; + + /* + * Stop and remove still/images if areas were exposed and + * ReputImage isn't supported. + */ + if (!pPriv->type && !pPriv->AdaptorRec->ReputImage) + visible = !AreasExposed; + + /* + * Subtract exposed areas from overlaid image to match textured video + * behavior. + */ + if (!pPriv->type && pPriv->clientClip) + RegionSubtract(pPriv->clientClip, pPriv->clientClip, reg1); + + if (visible && pPriv->ckeyFilled) { + RegionRec tmp; + RegionNull(&tmp); + RegionCopy(&tmp, reg1); + RegionTranslate(&tmp, pWin->drawable.x, pWin->drawable.y); + RegionSubtract(pPriv->ckeyFilled, pPriv->ckeyFilled, &tmp); + } + + WinPriv = WinPriv->next; + xf86XVReputOrStopPort(pPriv, pWin, visible); + + pPriv->clipChanged = FALSE; + } +} + +static void +xf86XVClipNotify(WindowPtr pWin, int dx, int dy) +{ + ScreenPtr pScreen = pWin->drawable.pScreen; + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin); + XvPortRecPrivatePtr pPriv; + + while(WinPriv) { + pPriv = WinPriv->PortRec; + + if(pPriv->pCompositeClip && pPriv->FreeCompositeClip) + RegionDestroy(pPriv->pCompositeClip); + + pPriv->pCompositeClip = NULL; + + if (pPriv->AdaptorRec->ClipNotify) + (*pPriv->AdaptorRec->ClipNotify)(pPriv->pScrn, pPriv->DevPriv.ptr, + pWin, dx, dy); + + pPriv->clipChanged = TRUE; + + if (ScreenPriv->PostValidateTree == PostValidateTreeUndefined) { + ScreenPriv->PostValidateTree = pScreen->PostValidateTree; + pScreen->PostValidateTree = xf86XVPostValidateTree; + } + + WinPriv = WinPriv->next; + } + + if(ScreenPriv->ClipNotify) { + pScreen->ClipNotify = ScreenPriv->ClipNotify; + (*pScreen->ClipNotify)(pWin, dx, dy); + pScreen->ClipNotify = xf86XVClipNotify; + } +} + + + +/**** Required XvScreenRec fields ****/ + +static Bool +xf86XVCloseScreen(int i, ScreenPtr pScreen) +{ + ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; + XvScreenPtr pxvs = GET_XV_SCREEN(pScreen); + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + XvAdaptorPtr pa; + int c; + + if(!ScreenPriv) return TRUE; + + pScreen->DestroyWindow = ScreenPriv->DestroyWindow; + pScreen->WindowExposures = ScreenPriv->WindowExposures; + pScreen->ClipNotify = ScreenPriv->ClipNotify; + + pScrn->EnterVT = ScreenPriv->EnterVT; + pScrn->LeaveVT = ScreenPriv->LeaveVT; + pScrn->AdjustFrame = ScreenPriv->AdjustFrame; + pScrn->ModeSet = ScreenPriv->ModeSet; + + for(c = 0, pa = pxvs->pAdaptors; c < pxvs->nAdaptors; c++, pa++) { + xf86XVFreeAdaptor(pa); + } + + free(pxvs->pAdaptors); + free(ScreenPriv); + return TRUE; +} + + +static int +xf86XVQueryAdaptors( + ScreenPtr pScreen, + XvAdaptorPtr *p_pAdaptors, + int *p_nAdaptors +){ + XvScreenPtr pxvs = GET_XV_SCREEN(pScreen); + + *p_nAdaptors = pxvs->nAdaptors; + *p_pAdaptors = pxvs->pAdaptors; + + return Success; +} + + +/**** ScrnInfoRec fields ****/ + +static Bool +xf86XVEnterVT(int index, int flags) +{ + ScrnInfoPtr pScrn = xf86Screens[index]; + ScreenPtr pScreen = screenInfo.screens[index]; + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + Bool ret; + + pScrn->EnterVT = ScreenPriv->EnterVT; + ret = (*ScreenPriv->EnterVT)(index, flags); + ScreenPriv->EnterVT = pScrn->EnterVT; + pScrn->EnterVT = xf86XVEnterVT; + + if(ret) WalkTree(pScreen, xf86XVReputAllVideo, 0); + + return ret; +} + +static void +xf86XVLeaveVT(int index, int flags) +{ + ScrnInfoPtr pScrn = xf86Screens[index]; + ScreenPtr pScreen = screenInfo.screens[index]; + XvScreenPtr pxvs = GET_XV_SCREEN(pScreen); + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + XvAdaptorPtr pAdaptor; + XvPortPtr pPort; + XvPortRecPrivatePtr pPriv; + int i, j; + + for(i = 0; i < pxvs->nAdaptors; i++) { + pAdaptor = &pxvs->pAdaptors[i]; + for(j = 0; j < pAdaptor->nPorts; j++) { + pPort = &pAdaptor->pPorts[j]; + pPriv = (XvPortRecPrivatePtr)pPort->devPriv.ptr; + if(pPriv->isOn > XV_OFF) { + + (*pPriv->AdaptorRec->StopVideo)( + pPriv->pScrn, pPriv->DevPriv.ptr, TRUE); + pPriv->isOn = XV_OFF; + + if(pPriv->pCompositeClip && pPriv->FreeCompositeClip) + RegionDestroy(pPriv->pCompositeClip); + + pPriv->pCompositeClip = NULL; + + if(!pPriv->type && pPriv->pDraw) { /* still */ + xf86XVRemovePortFromWindow((WindowPtr)pPriv->pDraw, pPriv); + } + } + } + } + + pScrn->LeaveVT = ScreenPriv->LeaveVT; + (*ScreenPriv->LeaveVT)(index, flags); + ScreenPriv->LeaveVT = pScrn->LeaveVT; + pScrn->LeaveVT = xf86XVLeaveVT; +} + +static void +xf86XVAdjustFrame(int index, int x, int y, int flags) +{ + ScrnInfoPtr pScrn = xf86Screens[index]; + ScreenPtr pScreen = pScrn->pScreen; + XF86XVScreenPtr ScreenPriv = GET_XF86XV_SCREEN(pScreen); + + if(ScreenPriv->AdjustFrame) { + pScrn->AdjustFrame = ScreenPriv->AdjustFrame; + (*pScrn->AdjustFrame)(index, x, y, flags); + pScrn->AdjustFrame = xf86XVAdjustFrame; + } + + xf86XVReputOrStopAllPorts(pScrn, FALSE); +} + +static void +xf86XVModeSet(ScrnInfoPtr pScrn) +{ + ScreenPtr pScreen = pScrn->pScreen; + XF86XVScreenPtr ScreenPriv; + + /* Can be called before pScrn->pScreen is set */ + if (!pScreen) + return; + + ScreenPriv = GET_XF86XV_SCREEN(pScreen); + + if (ScreenPriv->ModeSet) { + pScrn->ModeSet = ScreenPriv->ModeSet; + (*pScrn->ModeSet)(pScrn); + pScrn->ModeSet = xf86XVModeSet; + } + + xf86XVReputOrStopAllPorts(pScrn, FALSE); +} + +/**** XvAdaptorRec fields ****/ + +static int +xf86XVAllocatePort( + unsigned long port, + XvPortPtr pPort, + XvPortPtr *ppPort +){ + *ppPort = pPort; + return Success; +} + + + +static int +xf86XVFreePort(XvPortPtr pPort) +{ + return Success; +} + + +static int +xf86XVPutVideo( + ClientPtr client, + DrawablePtr pDraw, + XvPortPtr pPort, + GCPtr pGC, + INT16 vid_x, INT16 vid_y, + CARD16 vid_w, CARD16 vid_h, + INT16 drw_x, INT16 drw_y, + CARD16 drw_w, CARD16 drw_h +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + int result; + + /* No dumping video to pixmaps... For now anyhow */ + if(pDraw->type != DRAWABLE_WINDOW) { + pPort->pDraw = (DrawablePtr)NULL; + return BadAlloc; + } + + /* If we are changing windows, unregister our port in the old window */ + if(portPriv->pDraw && (portPriv->pDraw != pDraw)) + xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv); + + /* Register our port with the new window */ + result = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv); + if(result != Success) return result; + + portPriv->type = XvInputMask; + + /* save a copy of these parameters */ + portPriv->vid_x = vid_x; portPriv->vid_y = vid_y; + portPriv->vid_w = vid_w; portPriv->vid_h = vid_h; + portPriv->drw_x = drw_x; portPriv->drw_y = drw_y; + portPriv->drw_w = drw_w; portPriv->drw_h = drw_h; + + /* make sure we have the most recent copy of the clientClip */ + xf86XVCopyClip(portPriv, pGC); + + /* To indicate to the DI layer that we were successful */ + pPort->pDraw = pDraw; + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + return(xf86XVReputVideo(portPriv)); +} + +static int +xf86XVPutStill( + ClientPtr client, + DrawablePtr pDraw, + XvPortPtr pPort, + GCPtr pGC, + INT16 vid_x, INT16 vid_y, + CARD16 vid_w, CARD16 vid_h, + INT16 drw_x, INT16 drw_y, + CARD16 drw_w, CARD16 drw_h +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + if (pDraw->type != DRAWABLE_WINDOW) + return BadAlloc; + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + WinBox.x1 = pDraw->x + drw_x; + WinBox.y1 = pDraw->y + drw_y; + WinBox.x2 = WinBox.x1 + drw_w; + WinBox.y2 = WinBox.y1 + drw_h; + + xf86XVCopyCompositeClip(portPriv, pGC, pDraw); + + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip); + + if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) { + RegionRec VPReg; + BoxRec VPBox; + + VPBox.x1 = portPriv->pScrn->frameX0; + VPBox.y1 = portPriv->pScrn->frameY0; + VPBox.x2 = portPriv->pScrn->frameX1 + 1; + VPBox.y2 = portPriv->pScrn->frameY1 + 1; + + RegionInit(&VPReg, &VPBox, 1); + RegionIntersect(&ClipRegion, &ClipRegion, &VPReg); + RegionUninit(&VPReg); + } + + if(portPriv->pDraw) { + xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv); + } + + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto PUT_STILL_BAILOUT; + } + + if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) { + BoxPtr clipBox = RegionRects(&ClipRegion); + if( (RegionNumRects(&ClipRegion) != 1) || + (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) || + (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2)) + { + clippedAway = TRUE; + goto PUT_STILL_BAILOUT; + } + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->PutStill)(portPriv->pScrn, + vid_x, vid_y, WinBox.x1, WinBox.y1, + vid_w, vid_h, drw_w, drw_h, + &ClipRegion, portPriv->DevPriv.ptr, + pDraw); + + if((ret == Success) && + (portPriv->AdaptorRec->flags & VIDEO_OVERLAID_STILLS)) { + + xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv); + portPriv->isOn = XV_ON; + portPriv->vid_x = vid_x; portPriv->vid_y = vid_y; + portPriv->vid_w = vid_w; portPriv->vid_h = vid_h; + portPriv->drw_x = drw_x; portPriv->drw_y = drw_y; + portPriv->drw_w = drw_w; portPriv->drw_h = drw_h; + portPriv->type = 0; /* no mask means it's transient and should + not be reput once it's removed */ + pPort->pDraw = pDraw; /* make sure we can get stop requests */ + } + +PUT_STILL_BAILOUT: + + if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + /* This clip was copied and only good for one shot */ + if(!portPriv->FreeCompositeClip) + portPriv->pCompositeClip = NULL; + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + +static int +xf86XVGetVideo( + ClientPtr client, + DrawablePtr pDraw, + XvPortPtr pPort, + GCPtr pGC, + INT16 vid_x, INT16 vid_y, + CARD16 vid_w, CARD16 vid_h, + INT16 drw_x, INT16 drw_y, + CARD16 drw_w, CARD16 drw_h +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + int result; + + /* No pixmaps... For now anyhow */ + if(pDraw->type != DRAWABLE_WINDOW) { + pPort->pDraw = (DrawablePtr)NULL; + return BadAlloc; + } + + /* If we are changing windows, unregister our port in the old window */ + if(portPriv->pDraw && (portPriv->pDraw != pDraw)) + xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv); + + /* Register our port with the new window */ + result = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv); + if(result != Success) return result; + + portPriv->type = XvOutputMask; + + /* save a copy of these parameters */ + portPriv->vid_x = vid_x; portPriv->vid_y = vid_y; + portPriv->vid_w = vid_w; portPriv->vid_h = vid_h; + portPriv->drw_x = drw_x; portPriv->drw_y = drw_y; + portPriv->drw_w = drw_w; portPriv->drw_h = drw_h; + + /* make sure we have the most recent copy of the clientClip */ + xf86XVCopyClip(portPriv, pGC); + + /* To indicate to the DI layer that we were successful */ + pPort->pDraw = pDraw; + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + return(xf86XVRegetVideo(portPriv)); +} + +static int +xf86XVGetStill( + ClientPtr client, + DrawablePtr pDraw, + XvPortPtr pPort, + GCPtr pGC, + INT16 vid_x, INT16 vid_y, + CARD16 vid_w, CARD16 vid_h, + INT16 drw_x, INT16 drw_y, + CARD16 drw_w, CARD16 drw_h +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + if (pDraw->type != DRAWABLE_WINDOW) + return BadAlloc; + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + WinBox.x1 = pDraw->x + drw_x; + WinBox.y1 = pDraw->y + drw_y; + WinBox.x2 = WinBox.x1 + drw_w; + WinBox.y2 = WinBox.y1 + drw_h; + + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip); + + if(portPriv->pDraw) { + xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv); + } + + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto GET_STILL_BAILOUT; + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->GetStill)(portPriv->pScrn, + vid_x, vid_y, WinBox.x1, WinBox.y1, + vid_w, vid_h, drw_w, drw_h, + &ClipRegion, portPriv->DevPriv.ptr, + pDraw); + +GET_STILL_BAILOUT: + + if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + + + +static int +xf86XVStopVideo( + ClientPtr client, + XvPortPtr pPort, + DrawablePtr pDraw +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + + if(pDraw->type != DRAWABLE_WINDOW) + return BadAlloc; + + xf86XVRemovePortFromWindow((WindowPtr)pDraw, portPriv); + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + /* Must free resources. */ + + if(portPriv->isOn > XV_OFF) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, TRUE); + portPriv->isOn = XV_OFF; + } + + return Success; +} + +static int +xf86XVSetPortAttribute( + ClientPtr client, + XvPortPtr pPort, + Atom attribute, + INT32 value +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + + return((*portPriv->AdaptorRec->SetPortAttribute)(portPriv->pScrn, + attribute, value, portPriv->DevPriv.ptr)); +} + + +static int +xf86XVGetPortAttribute( + ClientPtr client, + XvPortPtr pPort, + Atom attribute, + INT32 *p_value +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + + return((*portPriv->AdaptorRec->GetPortAttribute)(portPriv->pScrn, + attribute, p_value, portPriv->DevPriv.ptr)); +} + + + +static int +xf86XVQueryBestSize( + ClientPtr client, + XvPortPtr pPort, + CARD8 motion, + CARD16 vid_w, CARD16 vid_h, + CARD16 drw_w, CARD16 drw_h, + unsigned int *p_w, unsigned int *p_h +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + + (*portPriv->AdaptorRec->QueryBestSize)(portPriv->pScrn, + (Bool)motion, vid_w, vid_h, drw_w, drw_h, + p_w, p_h, portPriv->DevPriv.ptr); + + return Success; +} + + +static int +xf86XVPutImage( + ClientPtr client, + DrawablePtr pDraw, + XvPortPtr pPort, + GCPtr pGC, + INT16 src_x, INT16 src_y, + CARD16 src_w, CARD16 src_h, + INT16 drw_x, INT16 drw_y, + CARD16 drw_w, CARD16 drw_h, + XvImagePtr format, + unsigned char* data, + Bool sync, + CARD16 width, CARD16 height +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + RegionRec WinRegion; + RegionRec ClipRegion; + BoxRec WinBox; + int ret = Success; + Bool clippedAway = FALSE; + + if (pDraw->type != DRAWABLE_WINDOW) + return BadAlloc; + + if(!portPriv->pScrn->vtSema) return Success; /* Success ? */ + + xf86XVCopyCompositeClip(portPriv, pGC, pDraw); + + WinBox.x1 = pDraw->x + drw_x; + WinBox.y1 = pDraw->y + drw_y; + WinBox.x2 = WinBox.x1 + drw_w; + WinBox.y2 = WinBox.y1 + drw_h; + + RegionInit(&WinRegion, &WinBox, 1); + RegionNull(&ClipRegion); + RegionIntersect(&ClipRegion, &WinRegion, pGC->pCompositeClip); + + if(portPriv->AdaptorRec->flags & VIDEO_CLIP_TO_VIEWPORT) { + RegionRec VPReg; + BoxRec VPBox; + + VPBox.x1 = portPriv->pScrn->frameX0; + VPBox.y1 = portPriv->pScrn->frameY0; + VPBox.x2 = portPriv->pScrn->frameX1 + 1; + VPBox.y2 = portPriv->pScrn->frameY1 + 1; + + RegionInit(&VPReg, &VPBox, 1); + RegionIntersect(&ClipRegion, &ClipRegion, &VPReg); + RegionUninit(&VPReg); + } + + /* If we are changing windows, unregister our port in the old window */ + if(portPriv->pDraw && (portPriv->pDraw != pDraw)) + xf86XVRemovePortFromWindow((WindowPtr)(portPriv->pDraw), portPriv); + + /* Register our port with the new window */ + ret = xf86XVEnlistPortInWindow((WindowPtr)pDraw, portPriv); + if(ret != Success) goto PUT_IMAGE_BAILOUT; + + if(!RegionNotEmpty(&ClipRegion)) { + clippedAway = TRUE; + goto PUT_IMAGE_BAILOUT; + } + + if(portPriv->AdaptorRec->flags & VIDEO_NO_CLIPPING) { + BoxPtr clipBox = RegionRects(&ClipRegion); + if( (RegionNumRects(&ClipRegion) != 1) || + (clipBox->x1 != WinBox.x1) || (clipBox->x2 != WinBox.x2) || + (clipBox->y1 != WinBox.y1) || (clipBox->y2 != WinBox.y2)) + { + clippedAway = TRUE; + goto PUT_IMAGE_BAILOUT; + } + } + + if(portPriv->AdaptorRec->flags & VIDEO_INVERT_CLIPLIST) { + RegionSubtract(&ClipRegion, &WinRegion, &ClipRegion); + } + + ret = (*portPriv->AdaptorRec->PutImage)(portPriv->pScrn, + src_x, src_y, WinBox.x1, WinBox.y1, + src_w, src_h, drw_w, drw_h, format->id, data, width, height, + sync, &ClipRegion, portPriv->DevPriv.ptr, + pDraw); + + if((ret == Success) && + (portPriv->AdaptorRec->flags & VIDEO_OVERLAID_IMAGES)) { + + portPriv->isOn = XV_ON; + portPriv->vid_x = src_x; portPriv->vid_y = src_y; + portPriv->vid_w = src_w; portPriv->vid_h = src_h; + portPriv->drw_x = drw_x; portPriv->drw_y = drw_y; + portPriv->drw_w = drw_w; portPriv->drw_h = drw_h; + portPriv->type = 0; /* no mask means it's transient and should + not be reput once it's removed */ + pPort->pDraw = pDraw; /* make sure we can get stop requests */ + } + +PUT_IMAGE_BAILOUT: + + if((clippedAway || (ret != Success)) && (portPriv->isOn == XV_ON)) { + (*portPriv->AdaptorRec->StopVideo)( + portPriv->pScrn, portPriv->DevPriv.ptr, FALSE); + portPriv->isOn = XV_PENDING; + } + + /* This clip was copied and only good for one shot */ + if(!portPriv->FreeCompositeClip) + portPriv->pCompositeClip = NULL; + + RegionUninit(&WinRegion); + RegionUninit(&ClipRegion); + + return ret; +} + + +static int +xf86XVQueryImageAttributes( + ClientPtr client, + XvPortPtr pPort, + XvImagePtr format, + CARD16 *width, + CARD16 *height, + int *pitches, + int *offsets +){ + XvPortRecPrivatePtr portPriv = (XvPortRecPrivatePtr)(pPort->devPriv.ptr); + + return (*portPriv->AdaptorRec->QueryImageAttributes)(portPriv->pScrn, + format->id, width, height, pitches, offsets); +} + +void +xf86XVFillKeyHelperDrawable (DrawablePtr pDraw, CARD32 key, RegionPtr fillboxes) +{ + ScreenPtr pScreen = pDraw->pScreen; + ChangeGCVal pval[2]; + BoxPtr pbox = RegionRects(fillboxes); + int i, nbox = RegionNumRects(fillboxes); + xRectangle *rects; + GCPtr gc; + + if(!xf86Screens[pScreen->myNum]->vtSema) return; + + gc = GetScratchGC(pDraw->depth, pScreen); + pval[0].val = key; + pval[1].val = IncludeInferiors; + (void) ChangeGC(NullClient, gc, GCForeground|GCSubwindowMode, pval); + ValidateGC(pDraw, gc); + + rects = malloc(nbox * sizeof(xRectangle)); + + for(i = 0; i < nbox; i++, pbox++) + { + rects[i].x = pbox->x1 - pDraw->x; + rects[i].y = pbox->y1 - pDraw->y; + rects[i].width = pbox->x2 - pbox->x1; + rects[i].height = pbox->y2 - pbox->y1; + } + + (*gc->ops->PolyFillRect)(pDraw, gc, nbox, rects); + + free(rects); + FreeScratchGC (gc); +} + +void +xf86XVFillKeyHelper (ScreenPtr pScreen, CARD32 key, RegionPtr fillboxes) +{ + xf86XVFillKeyHelperDrawable (&pScreen->root->drawable, key, fillboxes); +} + +void +xf86XVFillKeyHelperPort (DrawablePtr pDraw, pointer data, CARD32 key, RegionPtr clipboxes, Bool fillEverything) +{ + WindowPtr pWin = (WindowPtr)pDraw; + XF86XVWindowPtr WinPriv = GET_XF86XV_WINDOW(pWin); + XvPortRecPrivatePtr portPriv = NULL; + RegionRec reg; + RegionPtr fillboxes; + + while (WinPriv) { + XvPortRecPrivatePtr pPriv = WinPriv->PortRec; + + if (data == pPriv->DevPriv.ptr) { + portPriv = pPriv; + break; + } + + WinPriv = WinPriv->next; + } + + if (!portPriv) + return; + + if (!portPriv->ckeyFilled) + portPriv->ckeyFilled = RegionCreate(NULL, 0); + + if (!fillEverything) { + RegionNull(®); + fillboxes = ® + RegionSubtract(fillboxes, clipboxes, portPriv->ckeyFilled); + + if (!RegionNotEmpty(fillboxes)) + goto out; + } else + fillboxes = clipboxes; + + + RegionCopy(portPriv->ckeyFilled, clipboxes); + + xf86XVFillKeyHelperDrawable(pDraw, key, fillboxes); +out: + if (!fillEverything) + RegionUninit(®); +} + + +/* xf86XVClipVideoHelper - + + Takes the dst box in standard X BoxRec form (top and left + edges inclusive, bottom and right exclusive). The new dst + box is returned. The source boundaries are given (x1, y1 + inclusive, x2, y2 exclusive) and returned are the new source + boundaries in 16.16 fixed point. +*/ + +Bool +xf86XVClipVideoHelper( + BoxPtr dst, + INT32 *xa, + INT32 *xb, + INT32 *ya, + INT32 *yb, + RegionPtr reg, + INT32 width, + INT32 height +){ + double xsw, xdw, ysw, ydw; + INT32 delta; + BoxPtr extents = RegionExtents(reg); + int diff; + + xsw = (*xb - *xa) << 16; + xdw = dst->x2 - dst->x1; + ysw = (*yb - *ya) << 16; + ydw = dst->y2 - dst->y1; + + *xa <<= 16; *xb <<= 16; + *ya <<= 16; *yb <<= 16; + + diff = extents->x1 - dst->x1; + if (diff > 0) { + dst->x1 = extents->x1; + *xa += (diff * xsw) / xdw; + } + diff = dst->x2 - extents->x2; + if (diff > 0) { + dst->x2 = extents->x2; + *xb -= (diff * xsw) / xdw; + } + diff = extents->y1 - dst->y1; + if (diff > 0) { + dst->y1 = extents->y1; + *ya += (diff * ysw) / ydw; + } + diff = dst->y2 - extents->y2; + if (diff > 0) { + dst->y2 = extents->y2; + *yb -= (diff * ysw) / ydw; + } + + if (*xa < 0) { + diff = (((-*xa) * xdw) + xsw - 1) / xsw; + dst->x1 += diff; + *xa += (diff * xsw) / xdw; + } + delta = *xb - (width << 16); + if (delta > 0) { + diff = ((delta * xdw) + xsw - 1) / xsw; + dst->x2 -= diff; + *xb -= (diff * xsw) / xdw; + } + if (*xa >= *xb) return FALSE; + + if (*ya < 0) { + diff = (((-*ya) * ydw) + ysw - 1) / ysw; + dst->y1 += diff; + *ya += (diff * ysw) / ydw; + } + delta = *yb - (height << 16); + if (delta > 0) { + diff = ((delta * ydw) + ysw - 1) / ysw; + dst->y2 -= diff; + *yb -= (diff * ysw) / ydw; + } + if (*ya >= *yb) return FALSE; + + if ((dst->x1 > extents->x1) || (dst->x2 < extents->x2) || + (dst->y1 > extents->y1) || (dst->y2 < extents->y2)) + { + RegionRec clipReg; + RegionInit(&clipReg, dst, 1); + RegionIntersect(reg, reg, &clipReg); + RegionUninit(&clipReg); + } + return TRUE; +} + +void +xf86XVCopyYUV12ToPacked( + const void *srcy, + const void *srcv, + const void *srcu, + void *dst, + int srcPitchy, + int srcPitchuv, + int dstPitch, + int h, + int w +){ + CARD32 *Dst; + const CARD8 *Y, *U, *V; + int i, j; + + w >>= 1; + + for (j = 0; j < h; j++) { + Dst = dst; + Y = srcy; V = srcv; U = srcu; + i = w; + while (i >= 4) { +#if X_BYTE_ORDER == X_LITTLE_ENDIAN + Dst[0] = Y[0] | (Y[1] << 16) | (U[0] << 8) | (V[0] << 24); + Dst[1] = Y[2] | (Y[3] << 16) | (U[1] << 8) | (V[1] << 24); + Dst[2] = Y[4] | (Y[5] << 16) | (U[2] << 8) | (V[2] << 24); + Dst[3] = Y[6] | (Y[7] << 16) | (U[3] << 8) | (V[3] << 24); +#else + /* This assumes a little-endian framebuffer */ + Dst[0] = (Y[0] << 24) | (Y[1] << 8) | (U[0] << 16) | V[0]; + Dst[1] = (Y[2] << 24) | (Y[3] << 8) | (U[1] << 16) | V[1]; + Dst[2] = (Y[4] << 24) | (Y[5] << 8) | (U[2] << 16) | V[2]; + Dst[3] = (Y[6] << 24) | (Y[7] << 8) | (U[3] << 16) | V[3]; +#endif + Dst += 4; Y += 8; V += 4; U += 4; + i -= 4; + } + + while (i--) { +#if X_BYTE_ORDER == X_LITTLE_ENDIAN + Dst[0] = Y[0] | (Y[1] << 16) | (U[0] << 8) | (V[0] << 24); +#else + /* This assumes a little-endian framebuffer */ + Dst[0] = (Y[0] << 24) | (Y[1] << 8) | (U[0] << 16) | V[0]; +#endif + Dst++; Y += 2; V++; U++; + } + + dst = (CARD8 *)dst + dstPitch; + srcy = (const CARD8 *)srcy + srcPitchy; + if (j & 1) { + srcu = (const CARD8 *)srcu + srcPitchuv; + srcv = (const CARD8 *)srcv + srcPitchuv; + } + } +} + +void +xf86XVCopyPacked( + const void *src, + void *dst, + int srcPitch, + int dstPitch, + int h, + int w +){ + const CARD32 *Src; + CARD32 *Dst; + int i; + + w >>= 1; + while (--h >= 0) { + do { + Dst = dst; Src = src; + i = w; + while (i >= 4) { + Dst[0] = Src[0]; + Dst[1] = Src[1]; + Dst[2] = Src[2]; + Dst[3] = Src[3]; + Dst += 4; Src += 4; i -= 4; + } + if (!i) break; + Dst[0] = Src[0]; + if (i == 1) break; + Dst[1] = Src[1]; + if (i == 2) break; + Dst[2] = Src[2]; + } while (0); + + src = (const CARD8 *)src + srcPitch; + dst = (CARD8 *)dst + dstPitch; + } +} |