diff options
Diffstat (limited to 'xorg-server')
229 files changed, 38449 insertions, 36427 deletions
diff --git a/xorg-server/Xext/Makefile b/xorg-server/Xext/Makefile new file mode 100644 index 000000000..204ffe797 --- /dev/null +++ b/xorg-server/Xext/Makefile @@ -0,0 +1,38 @@ +CSRCS=\ +bigreq.c \ +dpms.c \ +dpmsstubs.c \ +mbuf.c \ +saver.c \ +security.c \ +shape.c \ +sleepuntil.c \ +sync.c \ +xace.c \ +xcmisc.c \ +xres.c \ +xtest.c \ +geext.c \ +panoramiX.c \ +panoramiXprocs.c \ +panoramiXSwap.c + +#shm.c \ +#appgroup.c \ +#fontcache.c \ +#mbufbf.c \ +#mbufpx.c \ +#xcalibrate.c \ +#xf86bigfont.c \ +#xprint.c \ +#xselinux.c \ +#xvdisp.c \ +#xvmain.c \ +#xvmc.c + +LIBRARY=libxext + +INCLUDES += ..\hw\xfree86\dixmods\extmod + + + diff --git a/xorg-server/Xext/dpms.c b/xorg-server/Xext/dpms.c index df63a8bf1..1130fe244 100644 --- a/xorg-server/Xext/dpms.c +++ b/xorg-server/Xext/dpms.c @@ -28,6 +28,8 @@ Equipment Corporation. #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else +#define DPMSExtension #endif #include <X11/X.h> diff --git a/xorg-server/Xext/saver.c b/xorg-server/Xext/saver.c index 04e6497bd..90d18ead5 100644 --- a/xorg-server/Xext/saver.c +++ b/xorg-server/Xext/saver.c @@ -1,1537 +1,1543 @@ -/* - * -Copyright (c) 1992 X Consortium - -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 -X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of the X Consortium 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 X Consortium. - * - * Author: Keith Packard, MIT X Consortium - */ - - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <X11/X.h> -#include <X11/Xproto.h> -#include "misc.h" -#include "os.h" -#include "windowstr.h" -#include "scrnintstr.h" -#include "pixmapstr.h" -#include "extnsionst.h" -#include "dixstruct.h" -#include "resource.h" -#include "opaque.h" -#include <X11/extensions/saverproto.h> -#include "gcstruct.h" -#include "cursorstr.h" -#include "colormapst.h" -#include "xace.h" -#ifdef PANORAMIX -#include "panoramiX.h" -#include "panoramiXsrv.h" -#endif -#ifdef DPMSExtension -#include <X11/extensions/dpmsconst.h> -#endif -#include "protocol-versions.h" - -#include <stdio.h> - -#include "modinit.h" - -static int ScreenSaverEventBase = 0; - -static DISPATCH_PROC(ProcScreenSaverQueryInfo); -static DISPATCH_PROC(ProcScreenSaverDispatch); -static DISPATCH_PROC(ProcScreenSaverQueryVersion); -static DISPATCH_PROC(ProcScreenSaverSelectInput); -static DISPATCH_PROC(ProcScreenSaverSetAttributes); -static DISPATCH_PROC(ProcScreenSaverUnsetAttributes); -static DISPATCH_PROC(ProcScreenSaverSuspend); -static DISPATCH_PROC(SProcScreenSaverDispatch); -static DISPATCH_PROC(SProcScreenSaverQueryInfo); -static DISPATCH_PROC(SProcScreenSaverQueryVersion); -static DISPATCH_PROC(SProcScreenSaverSelectInput); -static DISPATCH_PROC(SProcScreenSaverSetAttributes); -static DISPATCH_PROC(SProcScreenSaverUnsetAttributes); -static DISPATCH_PROC(SProcScreenSaverSuspend); - -static Bool ScreenSaverHandle ( - ScreenPtr /* pScreen */, - int /* xstate */, - Bool /* force */ - ); - -static Bool -CreateSaverWindow ( - ScreenPtr /* pScreen */ - ); - -static Bool -DestroySaverWindow ( - ScreenPtr /* pScreen */ - ); - -static void -UninstallSaverColormap ( - ScreenPtr /* pScreen */ - ); - -static void -CheckScreenPrivate ( - ScreenPtr /* pScreen */ - ); - -static void SScreenSaverNotifyEvent ( - xScreenSaverNotifyEvent * /* from */, - xScreenSaverNotifyEvent * /* to */ - ); - -static RESTYPE SuspendType; /* resource type for suspension records */ - -typedef struct _ScreenSaverSuspension *ScreenSaverSuspensionPtr; - -/* List of clients that are suspending the screensaver. */ -static ScreenSaverSuspensionPtr suspendingClients = NULL; - -/* - * clientResource is a resource ID that's added when the record is - * allocated, so the record is freed and the screensaver resumed when - * the client disconnects. count is the number of times the client has - * requested the screensaver be suspended. - */ -typedef struct _ScreenSaverSuspension -{ - ScreenSaverSuspensionPtr next; - ClientPtr pClient; - XID clientResource; - int count; -} ScreenSaverSuspensionRec; - -static int ScreenSaverFreeSuspend( - pointer /*value */, - XID /* id */ -); - -/* - * each screen has a list of clients requesting - * ScreenSaverNotify events. Each client has a resource - * for each screen it selects ScreenSaverNotify input for, - * this resource is used to delete the ScreenSaverNotifyRec - * entry from the per-screen queue. - */ - -static RESTYPE SaverEventType; /* resource type for event masks */ - -typedef struct _ScreenSaverEvent *ScreenSaverEventPtr; - -typedef struct _ScreenSaverEvent { - ScreenSaverEventPtr next; - ClientPtr client; - ScreenPtr screen; - XID resource; - CARD32 mask; -} ScreenSaverEventRec; - -static int ScreenSaverFreeEvents( - pointer /* value */, - XID /* id */ -); - -static Bool setEventMask ( - ScreenPtr /* pScreen */, - ClientPtr /* client */, - unsigned long /* mask */ -); - -static unsigned long getEventMask ( - ScreenPtr /* pScreen */, - ClientPtr /* client */ -); - -/* - * when a client sets the screen saver attributes, a resource is - * kept to be freed when the client exits - */ - -static RESTYPE AttrType; /* resource type for attributes */ - -typedef struct _ScreenSaverAttr { - ScreenPtr screen; - ClientPtr client; - XID resource; - short x, y; - unsigned short width, height, borderWidth; - unsigned char class; - unsigned char depth; - VisualID visual; - CursorPtr pCursor; - PixmapPtr pBackgroundPixmap; - PixmapPtr pBorderPixmap; - Colormap colormap; - unsigned long mask; /* no pixmaps or cursors */ - unsigned long *values; -} ScreenSaverAttrRec, *ScreenSaverAttrPtr; - -static int ScreenSaverFreeAttr ( - pointer /* value */, - XID /* id */ -); - -static void FreeAttrs ( - ScreenSaverAttrPtr /* pAttr */ -); - -static void FreeScreenAttr ( - ScreenSaverAttrPtr /* pAttr */ -); - -static void -SendScreenSaverNotify ( - ScreenPtr /* pScreen */, - int /* state */, - Bool /* forced */ -); - -typedef struct _ScreenSaverScreenPrivate { - ScreenSaverEventPtr events; - ScreenSaverAttrPtr attr; - Bool hasWindow; - Colormap installedMap; -} ScreenSaverScreenPrivateRec, *ScreenSaverScreenPrivatePtr; - -static ScreenSaverScreenPrivatePtr -MakeScreenPrivate ( - ScreenPtr /* pScreen */ - ); - -static int ScreenPrivateKeyIndex; -static DevPrivateKey ScreenPrivateKey = &ScreenPrivateKeyIndex; - -#define GetScreenPrivate(s) ((ScreenSaverScreenPrivatePtr) \ - dixLookupPrivate(&(s)->devPrivates, ScreenPrivateKey)) -#define SetScreenPrivate(s,v) \ - dixSetPrivate(&(s)->devPrivates, ScreenPrivateKey, v); -#define SetupScreen(s) ScreenSaverScreenPrivatePtr pPriv = (s ? GetScreenPrivate(s) : NULL) - -#define New(t) (xalloc (sizeof (t))) - -/**************** - * ScreenSaverExtensionInit - * - * Called from InitExtensions in main() or from QueryExtension() if the - * extension is dynamically loaded. - * - ****************/ - -void -ScreenSaverExtensionInit(INITARGS) -{ - ExtensionEntry *extEntry; - int i; - ScreenPtr pScreen; - - AttrType = CreateNewResourceType(ScreenSaverFreeAttr); - SaverEventType = CreateNewResourceType(ScreenSaverFreeEvents); - SuspendType = CreateNewResourceType(ScreenSaverFreeSuspend); - - for (i = 0; i < screenInfo.numScreens; i++) - { - pScreen = screenInfo.screens[i]; - SetScreenPrivate (pScreen, NULL); - } - if (AttrType && SaverEventType && SuspendType && - (extEntry = AddExtension(ScreenSaverName, ScreenSaverNumberEvents, 0, - ProcScreenSaverDispatch, SProcScreenSaverDispatch, - NULL, StandardMinorOpcode))) - { - ScreenSaverEventBase = extEntry->eventBase; - EventSwapVector[ScreenSaverEventBase] = (EventSwapPtr) SScreenSaverNotifyEvent; - } -} - -static void -CheckScreenPrivate (ScreenPtr pScreen) -{ - SetupScreen (pScreen); - - if (!pPriv) - return; - if (!pPriv->attr && !pPriv->events && - !pPriv->hasWindow && pPriv->installedMap == None) - { - xfree (pPriv); - SetScreenPrivate (pScreen, NULL); - savedScreenInfo[pScreen->myNum].ExternalScreenSaver = NULL; - } -} - -static ScreenSaverScreenPrivatePtr -MakeScreenPrivate (ScreenPtr pScreen) -{ - SetupScreen (pScreen); - - if (pPriv) - return pPriv; - pPriv = New (ScreenSaverScreenPrivateRec); - if (!pPriv) - return 0; - pPriv->events = 0; - pPriv->attr = 0; - pPriv->hasWindow = FALSE; - pPriv->installedMap = None; - SetScreenPrivate (pScreen, pPriv); - savedScreenInfo[pScreen->myNum].ExternalScreenSaver = ScreenSaverHandle; - return pPriv; -} - -static unsigned long -getEventMask (ScreenPtr pScreen, ClientPtr client) -{ - SetupScreen(pScreen); - ScreenSaverEventPtr pEv; - - if (!pPriv) - return 0; - for (pEv = pPriv->events; pEv; pEv = pEv->next) - if (pEv->client == client) - return pEv->mask; - return 0; -} - -static Bool -setEventMask (ScreenPtr pScreen, ClientPtr client, unsigned long mask) -{ - SetupScreen(pScreen); - ScreenSaverEventPtr pEv, *pPrev; - - if (getEventMask (pScreen, client) == mask) - return TRUE; - if (!pPriv) - { - pPriv = MakeScreenPrivate (pScreen); - if (!pPriv) - return FALSE; - } - for (pPrev = &pPriv->events; (pEv = *pPrev) != 0; pPrev = &pEv->next) - if (pEv->client == client) - break; - if (mask == 0) - { - FreeResource (pEv->resource, SaverEventType); - *pPrev = pEv->next; - xfree (pEv); - CheckScreenPrivate (pScreen); - } - else - { - if (!pEv) - { - pEv = New (ScreenSaverEventRec); - if (!pEv) - { - CheckScreenPrivate (pScreen); - return FALSE; - } - *pPrev = pEv; - pEv->next = NULL; - pEv->client = client; - pEv->screen = pScreen; - pEv->resource = FakeClientID (client->index); - if (!AddResource (pEv->resource, SaverEventType, (pointer) pEv)) - return FALSE; - } - pEv->mask = mask; - } - return TRUE; -} - -static void -FreeAttrs (ScreenSaverAttrPtr pAttr) -{ - PixmapPtr pPixmap; - CursorPtr pCursor; - - if ((pPixmap = pAttr->pBackgroundPixmap) != 0) - (*pPixmap->drawable.pScreen->DestroyPixmap)(pPixmap); - if ((pPixmap = pAttr->pBorderPixmap) != 0) - (*pPixmap->drawable.pScreen->DestroyPixmap)(pPixmap); - if ((pCursor = pAttr->pCursor) != 0) - FreeCursor (pCursor, (Cursor) 0); -} - -static void -FreeScreenAttr (ScreenSaverAttrPtr pAttr) -{ - FreeAttrs (pAttr); - xfree (pAttr->values); - xfree (pAttr); -} - -static int -ScreenSaverFreeEvents (pointer value, XID id) -{ - ScreenSaverEventPtr pOld = (ScreenSaverEventPtr)value; - ScreenPtr pScreen = pOld->screen; - SetupScreen (pScreen); - ScreenSaverEventPtr pEv, *pPrev; - - if (!pPriv) - return TRUE; - for (pPrev = &pPriv->events; (pEv = *pPrev) != 0; pPrev = &pEv->next) - if (pEv == pOld) - break; - if (!pEv) - return TRUE; - *pPrev = pEv->next; - xfree (pEv); - CheckScreenPrivate (pScreen); - return TRUE; -} - -static int -ScreenSaverFreeAttr (pointer value, XID id) -{ - ScreenSaverAttrPtr pOldAttr = (ScreenSaverAttrPtr)value; - ScreenPtr pScreen = pOldAttr->screen; - SetupScreen (pScreen); - - if (!pPriv) - return TRUE; - if (pPriv->attr != pOldAttr) - return TRUE; - FreeScreenAttr (pOldAttr); - pPriv->attr = NULL; - if (pPriv->hasWindow) - { - dixSaveScreens (serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset); - dixSaveScreens (serverClient, SCREEN_SAVER_FORCER, ScreenSaverActive); - } - CheckScreenPrivate (pScreen); - return TRUE; -} - -static int -ScreenSaverFreeSuspend (pointer value, XID id) -{ - ScreenSaverSuspensionPtr data = (ScreenSaverSuspensionPtr) value; - ScreenSaverSuspensionPtr *prev, this; - - /* Unlink and free the suspension record for the client */ - for (prev = &suspendingClients; (this = *prev); prev = &this->next) - { - if (this == data) - { - *prev = this->next; - xfree (this); - break; - } - } - - /* Reenable the screensaver if this was the last client suspending it. */ - if (screenSaverSuspended && suspendingClients == NULL) - { - screenSaverSuspended = FALSE; - - /* The screensaver could be active, since suspending it (by design) - doesn't prevent it from being forceably activated */ -#ifdef DPMSExtension - if (screenIsSaved != SCREEN_SAVER_ON && DPMSPowerLevel == DPMSModeOn) -#else - if (screenIsSaved != SCREEN_SAVER_ON) -#endif - { - UpdateCurrentTimeIf(); - lastDeviceEventTime = currentTime; - SetScreenSaverTimer(); - } - } - - return Success; -} - -static void -SendScreenSaverNotify (ScreenPtr pScreen, int state, Bool forced) -{ - ScreenSaverScreenPrivatePtr pPriv; - ScreenSaverEventPtr pEv; - unsigned long mask; - xScreenSaverNotifyEvent ev; - ClientPtr client; - int kind; - - UpdateCurrentTimeIf (); - mask = ScreenSaverNotifyMask; - if (state == ScreenSaverCycle) - mask = ScreenSaverCycleMask; - pScreen = screenInfo.screens[pScreen->myNum]; - pPriv = GetScreenPrivate(pScreen); - if (!pPriv) - return; - if (pPriv->attr) - kind = ScreenSaverExternal; - else if (ScreenSaverBlanking != DontPreferBlanking) - kind = ScreenSaverBlanked; - else - kind = ScreenSaverInternal; - for (pEv = pPriv->events; pEv; pEv = pEv->next) - { - client = pEv->client; - if (client->clientGone) - continue; - if (!(pEv->mask & mask)) - continue; - ev.type = ScreenSaverNotify + ScreenSaverEventBase; - ev.state = state; - ev.sequenceNumber = client->sequence; - ev.timestamp = currentTime.milliseconds; - ev.root = WindowTable[pScreen->myNum]->drawable.id; - ev.window = savedScreenInfo[pScreen->myNum].wid; - ev.kind = kind; - ev.forced = forced; - WriteEventsToClient (client, 1, (xEvent *) &ev); - } -} - -static void -SScreenSaverNotifyEvent (xScreenSaverNotifyEvent *from, - xScreenSaverNotifyEvent *to) -{ - to->type = from->type; - to->state = from->state; - cpswaps (from->sequenceNumber, to->sequenceNumber); - cpswapl (from->timestamp, to->timestamp); - cpswapl (from->root, to->root); - cpswapl (from->window, to->window); - to->kind = from->kind; - to->forced = from->forced; -} - -static void -UninstallSaverColormap (ScreenPtr pScreen) -{ - SetupScreen(pScreen); - ColormapPtr pCmap; - int rc; - - if (pPriv && pPriv->installedMap != None) - { - rc = dixLookupResourceByType((pointer *)&pCmap, pPriv->installedMap, - RT_COLORMAP, serverClient, - DixUninstallAccess); - if (rc == Success) - (*pCmap->pScreen->UninstallColormap) (pCmap); - pPriv->installedMap = None; - CheckScreenPrivate (pScreen); - } -} - -static Bool -CreateSaverWindow (ScreenPtr pScreen) -{ - SetupScreen (pScreen); - ScreenSaverStuffPtr pSaver; - ScreenSaverAttrPtr pAttr; - WindowPtr pWin; - int result; - unsigned long mask; - Colormap *installedMaps; - int numInstalled; - int i; - Colormap wantMap; - ColormapPtr pCmap; - - pSaver = &savedScreenInfo[pScreen->myNum]; - if (pSaver->pWindow) - { - pSaver->pWindow = NullWindow; - FreeResource (pSaver->wid, RT_NONE); - if (pPriv) - { - UninstallSaverColormap (pScreen); - pPriv->hasWindow = FALSE; - CheckScreenPrivate (pScreen); - } - } - - if (!pPriv || !(pAttr = pPriv->attr)) - return FALSE; - - pPriv->installedMap = None; - - if (GrabInProgress && GrabInProgress != pAttr->client->index) - return FALSE; - - pWin = CreateWindow (pSaver->wid, WindowTable[pScreen->myNum], - pAttr->x, pAttr->y, pAttr->width, pAttr->height, - pAttr->borderWidth, pAttr->class, - pAttr->mask, (XID *)pAttr->values, - pAttr->depth, serverClient, pAttr->visual, - &result); - if (!pWin) - return FALSE; - - if (!AddResource(pWin->drawable.id, RT_WINDOW, pWin)) - return FALSE; - - mask = 0; - if (pAttr->pBackgroundPixmap) - { - pWin->backgroundState = BackgroundPixmap; - pWin->background.pixmap = pAttr->pBackgroundPixmap; - pAttr->pBackgroundPixmap->refcnt++; - mask |= CWBackPixmap; - } - if (pAttr->pBorderPixmap) - { - pWin->borderIsPixel = FALSE; - pWin->border.pixmap = pAttr->pBorderPixmap; - pAttr->pBorderPixmap->refcnt++; - mask |= CWBorderPixmap; - } - if (pAttr->pCursor) - { - if (!pWin->optional) - if (!MakeWindowOptional (pWin)) - { - FreeResource (pWin->drawable.id, RT_NONE); - return FALSE; - } - if (pWin->optional->cursor) - FreeCursor (pWin->optional->cursor, (Cursor)0); - pWin->optional->cursor = pAttr->pCursor; - pAttr->pCursor->refcnt++; - pWin->cursorIsNone = FALSE; - CheckWindowOptionalNeed (pWin); - mask |= CWCursor; - } - if (mask) - (*pScreen->ChangeWindowAttributes) (pWin, mask); - - if (pAttr->colormap != None) - (void) ChangeWindowAttributes (pWin, CWColormap, &pAttr->colormap, - serverClient); - - MapWindow (pWin, serverClient); - - pPriv->hasWindow = TRUE; - pSaver->pWindow = pWin; - - /* check and install our own colormap if it isn't installed now */ - wantMap = wColormap (pWin); - if (wantMap == None) - return TRUE; - installedMaps = xalloc (pScreen->maxInstalledCmaps * sizeof (Colormap)); - numInstalled = (*pWin->drawable.pScreen->ListInstalledColormaps) - (pScreen, installedMaps); - for (i = 0; i < numInstalled; i++) - if (installedMaps[i] == wantMap) - break; - - xfree ((char *) installedMaps); - - if (i < numInstalled) - return TRUE; - - result = dixLookupResourceByType((pointer *)&pCmap, wantMap, RT_COLORMAP, - serverClient, DixInstallAccess); - if (result != Success) - return TRUE; - - pPriv->installedMap = wantMap; - - (*pCmap->pScreen->InstallColormap) (pCmap); - - return TRUE; -} - -static Bool -DestroySaverWindow (ScreenPtr pScreen) -{ - SetupScreen(pScreen); - ScreenSaverStuffPtr pSaver; - - if (!pPriv || !pPriv->hasWindow) - return FALSE; - - pSaver = &savedScreenInfo[pScreen->myNum]; - if (pSaver->pWindow) - { - pSaver->pWindow = NullWindow; - FreeResource (pSaver->wid, RT_NONE); - } - pPriv->hasWindow = FALSE; - CheckScreenPrivate (pScreen); - UninstallSaverColormap (pScreen); - return TRUE; -} - -static Bool -ScreenSaverHandle (ScreenPtr pScreen, int xstate, Bool force) -{ - int state = 0; - Bool ret = FALSE; - ScreenSaverScreenPrivatePtr pPriv; - - switch (xstate) - { - case SCREEN_SAVER_ON: - state = ScreenSaverOn; - ret = CreateSaverWindow (pScreen); - break; - case SCREEN_SAVER_OFF: - state = ScreenSaverOff; - ret = DestroySaverWindow (pScreen); - break; - case SCREEN_SAVER_CYCLE: - state = ScreenSaverCycle; - pPriv = GetScreenPrivate (pScreen); - if (pPriv && pPriv->hasWindow) - ret = TRUE; - - } -#ifdef PANORAMIX - if(noPanoramiXExtension || !pScreen->myNum) -#endif - SendScreenSaverNotify (pScreen, state, force); - return ret; -} - -static int -ProcScreenSaverQueryVersion (ClientPtr client) -{ - xScreenSaverQueryVersionReply rep; - int n; - - REQUEST_SIZE_MATCH (xScreenSaverQueryVersionReq); - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.majorVersion = SERVER_SAVER_MAJOR_VERSION; - rep.minorVersion = SERVER_SAVER_MINOR_VERSION; - if (client->swapped) { - swaps(&rep.sequenceNumber, n); - swapl(&rep.length, n); - } - WriteToClient(client, sizeof (xScreenSaverQueryVersionReply), (char *)&rep); - return (client->noClientException); -} - -static int -ProcScreenSaverQueryInfo (ClientPtr client) -{ - REQUEST(xScreenSaverQueryInfoReq); - xScreenSaverQueryInfoReply rep; - int n, rc; - ScreenSaverStuffPtr pSaver; - DrawablePtr pDraw; - CARD32 lastInput; - ScreenSaverScreenPrivatePtr pPriv; - - REQUEST_SIZE_MATCH (xScreenSaverQueryInfoReq); - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, - DixGetAttrAccess); - if (rc != Success) - return rc; - rc = XaceHook(XACE_SCREENSAVER_ACCESS, client, pDraw->pScreen, - DixGetAttrAccess); - if (rc != Success) - return rc; - - pSaver = &savedScreenInfo[pDraw->pScreen->myNum]; - pPriv = GetScreenPrivate (pDraw->pScreen); - - UpdateCurrentTime (); - lastInput = GetTimeInMillis() - lastDeviceEventTime.milliseconds; - - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.window = pSaver->wid; - if (screenIsSaved != SCREEN_SAVER_OFF) - { - rep.state = ScreenSaverOn; - if (ScreenSaverTime) - rep.tilOrSince = lastInput - ScreenSaverTime; - else - rep.tilOrSince = 0; - } - else - { - if (ScreenSaverTime) - { - rep.state = ScreenSaverOff; - if (ScreenSaverTime < lastInput) - rep.tilOrSince = 0; - else - rep.tilOrSince = ScreenSaverTime - lastInput; - } - else - { - rep.state = ScreenSaverDisabled; - rep.tilOrSince = 0; - } - } - rep.idle = lastInput; - rep.eventMask = getEventMask (pDraw->pScreen, client); - if (pPriv && pPriv->attr) - rep.kind = ScreenSaverExternal; - else if (ScreenSaverBlanking != DontPreferBlanking) - rep.kind = ScreenSaverBlanked; - else - rep.kind = ScreenSaverInternal; - if (client->swapped) - { - swaps (&rep.sequenceNumber, n); - swapl (&rep.length, n); - swapl (&rep.window, n); - swapl (&rep.tilOrSince, n); - swapl (&rep.idle, n); - swapl (&rep.eventMask, n); - } - WriteToClient(client, sizeof (xScreenSaverQueryInfoReply), (char *)&rep); - return (client->noClientException); -} - -static int -ProcScreenSaverSelectInput (ClientPtr client) -{ - REQUEST(xScreenSaverSelectInputReq); - DrawablePtr pDraw; - int rc; - - REQUEST_SIZE_MATCH (xScreenSaverSelectInputReq); - rc = dixLookupDrawable (&pDraw, stuff->drawable, client, 0, - DixGetAttrAccess); - if (rc != Success) - return rc; - - rc = XaceHook(XACE_SCREENSAVER_ACCESS, client, pDraw->pScreen, - DixSetAttrAccess); - if (rc != Success) - return rc; - - if (!setEventMask (pDraw->pScreen, client, stuff->eventMask)) - return BadAlloc; - return Success; -} - -static int -ScreenSaverSetAttributes (ClientPtr client) -{ - REQUEST(xScreenSaverSetAttributesReq); - DrawablePtr pDraw; - WindowPtr pParent; - ScreenPtr pScreen; - ScreenSaverScreenPrivatePtr pPriv = 0; - ScreenSaverAttrPtr pAttr = 0; - int ret, len, class, bw, depth; - unsigned long visual; - int idepth, ivisual; - Bool fOK; - DepthPtr pDepth; - WindowOptPtr ancwopt; - unsigned int *pVlist; - unsigned long *values = 0; - unsigned long tmask, imask; - unsigned long val; - Pixmap pixID; - PixmapPtr pPixmap; - Cursor cursorID; - CursorPtr pCursor; - Colormap cmap; - ColormapPtr pCmap; - - REQUEST_AT_LEAST_SIZE (xScreenSaverSetAttributesReq); - ret = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, - DixGetAttrAccess); - if (ret != Success) - return ret; - pScreen = pDraw->pScreen; - pParent = WindowTable[pScreen->myNum]; - - ret = XaceHook(XACE_SCREENSAVER_ACCESS, client, pScreen, DixSetAttrAccess); - if (ret != Success) - return ret; - - len = stuff->length - bytes_to_int32(sizeof(xScreenSaverSetAttributesReq)); - if (Ones(stuff->mask) != len) - return BadLength; - if (!stuff->width || !stuff->height) - { - client->errorValue = 0; - return BadValue; - } - switch (class = stuff->c_class) - { - case CopyFromParent: - case InputOnly: - case InputOutput: - break; - default: - client->errorValue = class; - return BadValue; - } - bw = stuff->borderWidth; - depth = stuff->depth; - visual = stuff->visualID; - - /* copied directly from CreateWindow */ - - if (class == CopyFromParent) - class = pParent->drawable.class; - - if ((class != InputOutput) && (class != InputOnly)) - { - client->errorValue = class; - return BadValue; - } - - if ((class != InputOnly) && (pParent->drawable.class == InputOnly)) - return BadMatch; - - if ((class == InputOnly) && ((bw != 0) || (depth != 0))) - return BadMatch; - - if ((class == InputOutput) && (depth == 0)) - depth = pParent->drawable.depth; - ancwopt = pParent->optional; - if (!ancwopt) - ancwopt = FindWindowWithOptional(pParent)->optional; - if (visual == CopyFromParent) - visual = ancwopt->visual; - - /* Find out if the depth and visual are acceptable for this Screen */ - if ((visual != ancwopt->visual) || (depth != pParent->drawable.depth)) - { - fOK = FALSE; - for(idepth = 0; idepth < pScreen->numDepths; idepth++) - { - pDepth = (DepthPtr) &pScreen->allowedDepths[idepth]; - if ((depth == pDepth->depth) || (depth == 0)) - { - for (ivisual = 0; ivisual < pDepth->numVids; ivisual++) - { - if (visual == pDepth->vids[ivisual]) - { - fOK = TRUE; - break; - } - } - } - } - if (fOK == FALSE) - return BadMatch; - } - - if (((stuff->mask & (CWBorderPixmap | CWBorderPixel)) == 0) && - (class != InputOnly) && - (depth != pParent->drawable.depth)) - { - return BadMatch; - } - - if (((stuff->mask & CWColormap) == 0) && - (class != InputOnly) && - ((visual != ancwopt->visual) || (ancwopt->colormap == None))) - { - return BadMatch; - } - - /* end of errors from CreateWindow */ - - pPriv = GetScreenPrivate (pScreen); - if (pPriv && pPriv->attr) - { - if (pPriv->attr->client != client) - return BadAccess; - } - if (!pPriv) - { - pPriv = MakeScreenPrivate (pScreen); - if (!pPriv) - return FALSE; - } - pAttr = New (ScreenSaverAttrRec); - if (!pAttr) - { - ret = BadAlloc; - goto bail; - } - /* over allocate for override redirect */ - values = xalloc ((len + 1) * sizeof (unsigned long)); - if (!values) - { - ret = BadAlloc; - goto bail; - } - pAttr->screen = pScreen; - pAttr->client = client; - pAttr->x = stuff->x; - pAttr->y = stuff->y; - pAttr->width = stuff->width; - pAttr->height = stuff->height; - pAttr->borderWidth = stuff->borderWidth; - pAttr->class = stuff->c_class; - pAttr->depth = depth; - pAttr->visual = visual; - pAttr->colormap = None; - pAttr->pCursor = NullCursor; - pAttr->pBackgroundPixmap = NullPixmap; - pAttr->pBorderPixmap = NullPixmap; - pAttr->values = values; - /* - * go through the mask, checking the values, - * looking up pixmaps and cursors and hold a reference - * to them. - */ - pAttr->mask = tmask = stuff->mask | CWOverrideRedirect; - pVlist = (unsigned int *) (stuff + 1); - while (tmask) { - imask = lowbit (tmask); - tmask &= ~imask; - switch (imask) - { - case CWBackPixmap: - pixID = (Pixmap )*pVlist; - if (pixID == None) - { - *values++ = None; - } - else if (pixID == ParentRelative) - { - if (depth != pParent->drawable.depth) - { - ret = BadMatch; - goto PatchUp; - } - *values++ = ParentRelative; - } - else - { - ret = dixLookupResourceByType((pointer *)&pPixmap, pixID, RT_PIXMAP, - client, DixReadAccess); - if (ret == Success) - { - if ((pPixmap->drawable.depth != depth) || - (pPixmap->drawable.pScreen != pScreen)) - { - ret = BadMatch; - goto PatchUp; - } - pAttr->pBackgroundPixmap = pPixmap; - pPixmap->refcnt++; - pAttr->mask &= ~CWBackPixmap; - } - else - { - ret = (ret == BadValue) ? BadPixmap : ret; - client->errorValue = pixID; - goto PatchUp; - } - } - break; - case CWBackPixel: - *values++ = (CARD32) *pVlist; - break; - case CWBorderPixmap: - pixID = (Pixmap ) *pVlist; - if (pixID == CopyFromParent) - { - if (depth != pParent->drawable.depth) - { - ret = BadMatch; - goto PatchUp; - } - *values++ = CopyFromParent; - } - else - { - ret = dixLookupResourceByType((pointer *)&pPixmap, pixID, RT_PIXMAP, - client, DixReadAccess); - if (ret == Success) - { - if ((pPixmap->drawable.depth != depth) || - (pPixmap->drawable.pScreen != pScreen)) - { - ret = BadMatch; - goto PatchUp; - } - pAttr->pBorderPixmap = pPixmap; - pPixmap->refcnt++; - pAttr->mask &= ~CWBorderPixmap; - } - else - { - ret = (ret == BadValue) ? BadPixmap : ret; - client->errorValue = pixID; - goto PatchUp; - } - } - break; - case CWBorderPixel: - *values++ = (CARD32) *pVlist; - break; - case CWBitGravity: - val = (CARD8 )*pVlist; - if (val > StaticGravity) - { - ret = BadValue; - client->errorValue = val; - goto PatchUp; - } - *values++ = val; - break; - case CWWinGravity: - val = (CARD8 )*pVlist; - if (val > StaticGravity) - { - ret = BadValue; - client->errorValue = val; - goto PatchUp; - } - *values++ = val; - break; - case CWBackingStore: - val = (CARD8 )*pVlist; - if ((val != NotUseful) && (val != WhenMapped) && (val != Always)) - { - ret = BadValue; - client->errorValue = val; - goto PatchUp; - } - *values++ = val; - break; - case CWBackingPlanes: - *values++ = (CARD32) *pVlist; - break; - case CWBackingPixel: - *values++ = (CARD32) *pVlist; - break; - case CWSaveUnder: - val = (BOOL) *pVlist; - if ((val != xTrue) && (val != xFalse)) - { - ret = BadValue; - client->errorValue = val; - goto PatchUp; - } - *values++ = val; - break; - case CWEventMask: - *values++ = (CARD32) *pVlist; - break; - case CWDontPropagate: - *values++ = (CARD32) *pVlist; - break; - case CWOverrideRedirect: - if (!(stuff->mask & CWOverrideRedirect)) - pVlist--; - else - { - val = (BOOL ) *pVlist; - if ((val != xTrue) && (val != xFalse)) - { - ret = BadValue; - client->errorValue = val; - goto PatchUp; - } - } - *values++ = xTrue; - break; - case CWColormap: - cmap = (Colormap) *pVlist; - ret = dixLookupResourceByType((pointer *)&pCmap, cmap, RT_COLORMAP, - client, DixUseAccess); - if (ret != Success) - { - ret = (ret == BadValue) ? BadColor : ret; - client->errorValue = cmap; - goto PatchUp; - } - if (pCmap->pVisual->vid != visual || pCmap->pScreen != pScreen) - { - ret = BadMatch; - goto PatchUp; - } - pAttr->colormap = cmap; - pAttr->mask &= ~CWColormap; - break; - case CWCursor: - cursorID = (Cursor ) *pVlist; - if ( cursorID == None) - { - *values++ = None; - } - else - { - ret = dixLookupResourceByType((pointer *)&pCursor, cursorID, - RT_CURSOR, client, DixUseAccess); - if (ret != Success) - { - ret = (ret == BadValue) ? BadCursor : ret; - client->errorValue = cursorID; - goto PatchUp; - } - pCursor->refcnt++; - pAttr->pCursor = pCursor; - pAttr->mask &= ~CWCursor; - } - break; - default: - ret = BadValue; - client->errorValue = stuff->mask; - goto PatchUp; - } - pVlist++; - } - if (pPriv->attr) - FreeScreenAttr (pPriv->attr); - pPriv->attr = pAttr; - pAttr->resource = FakeClientID (client->index); - if (!AddResource (pAttr->resource, AttrType, (pointer) pAttr)) - return BadAlloc; - return Success; -PatchUp: - FreeAttrs (pAttr); -bail: - CheckScreenPrivate (pScreen); - if (pAttr) xfree (pAttr->values); - xfree (pAttr); - return ret; -} - -static int -ScreenSaverUnsetAttributes (ClientPtr client) -{ - REQUEST(xScreenSaverSetAttributesReq); - DrawablePtr pDraw; - ScreenSaverScreenPrivatePtr pPriv; - int rc; - - REQUEST_SIZE_MATCH (xScreenSaverUnsetAttributesReq); - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, - DixGetAttrAccess); - if (rc != Success) - return rc; - pPriv = GetScreenPrivate (pDraw->pScreen); - if (pPriv && pPriv->attr && pPriv->attr->client == client) - { - FreeResource (pPriv->attr->resource, AttrType); - FreeScreenAttr (pPriv->attr); - pPriv->attr = NULL; - CheckScreenPrivate (pDraw->pScreen); - } - return Success; -} - -static int -ProcScreenSaverSetAttributes (ClientPtr client) -{ -#ifdef PANORAMIX - if(!noPanoramiXExtension) { - REQUEST(xScreenSaverSetAttributesReq); - PanoramiXRes *draw; - PanoramiXRes *backPix = NULL; - PanoramiXRes *bordPix = NULL; - PanoramiXRes *cmap = NULL; - int i, status, len; - int pback_offset = 0, pbord_offset = 0, cmap_offset = 0; - XID orig_visual, tmp; - - REQUEST_AT_LEAST_SIZE (xScreenSaverSetAttributesReq); - - status = dixLookupResourceByClass((pointer *)&draw, stuff->drawable, - XRC_DRAWABLE, client, DixWriteAccess); - if (status != Success) - return (status == BadValue) ? BadDrawable : status; - - len = stuff->length - bytes_to_int32(sizeof(xScreenSaverSetAttributesReq)); - if (Ones(stuff->mask) != len) - return BadLength; - - if((Mask)stuff->mask & CWBackPixmap) { - pback_offset = Ones((Mask)stuff->mask & (CWBackPixmap - 1)); - tmp = *((CARD32 *) &stuff[1] + pback_offset); - if ((tmp != None) && (tmp != ParentRelative)) { - status = dixLookupResourceByType((pointer *)&backPix, tmp, - XRT_PIXMAP, client, - DixReadAccess); - if (status != Success) - return (status == BadValue) ? BadPixmap : status; - } - } - - if ((Mask)stuff->mask & CWBorderPixmap) { - pbord_offset = Ones((Mask)stuff->mask & (CWBorderPixmap - 1)); - tmp = *((CARD32 *) &stuff[1] + pbord_offset); - if (tmp != CopyFromParent) { - status = dixLookupResourceByType((pointer *)&bordPix, tmp, - XRT_PIXMAP, client, - DixReadAccess); - if (status != Success) - return (status == BadValue) ? BadPixmap : status; - } - } - - if ((Mask)stuff->mask & CWColormap) { - cmap_offset = Ones((Mask)stuff->mask & (CWColormap - 1)); - tmp = *((CARD32 *) &stuff[1] + cmap_offset); - if ((tmp != CopyFromParent) && (tmp != None)) { - status = dixLookupResourceByType((pointer *)&cmap, tmp, - XRT_COLORMAP, client, - DixReadAccess); - if (status != Success) - return (status == BadValue) ? BadColor : status; - } - } - - orig_visual = stuff->visualID; - - FOR_NSCREENS_BACKWARD(i) { - stuff->drawable = draw->info[i].id; - if (backPix) - *((CARD32 *) &stuff[1] + pback_offset) = backPix->info[i].id; - if (bordPix) - *((CARD32 *) &stuff[1] + pbord_offset) = bordPix->info[i].id; - if (cmap) - *((CARD32 *) &stuff[1] + cmap_offset) = cmap->info[i].id; - - if (orig_visual != CopyFromParent) - stuff->visualID = PanoramiXTranslateVisualID(i, orig_visual); - - status = ScreenSaverSetAttributes(client); - } - - return status; - } -#endif - - return ScreenSaverSetAttributes(client); -} - -static int -ProcScreenSaverUnsetAttributes (ClientPtr client) -{ -#ifdef PANORAMIX - if(!noPanoramiXExtension) { - REQUEST(xScreenSaverUnsetAttributesReq); - PanoramiXRes *draw; - int rc, i; - - rc = dixLookupResourceByClass((pointer *)&draw, stuff->drawable, - XRC_DRAWABLE, client, DixWriteAccess); - if (rc != Success) - return (rc == BadValue) ? BadDrawable : rc; - - for(i = PanoramiXNumScreens - 1; i > 0; i--) { - stuff->drawable = draw->info[i].id; - ScreenSaverUnsetAttributes(client); - } - - stuff->drawable = draw->info[0].id; - } -#endif - - return ScreenSaverUnsetAttributes(client); -} - -static int -ProcScreenSaverSuspend (ClientPtr client) -{ - ScreenSaverSuspensionPtr *prev, this; - - REQUEST(xScreenSaverSuspendReq); - REQUEST_SIZE_MATCH(xScreenSaverSuspendReq); - - /* Check if this client is suspending the screensaver */ - for (prev = &suspendingClients; (this = *prev); prev = &this->next) - if (this->pClient == client) - break; - - if (this) - { - if (stuff->suspend == TRUE) - this->count++; - else if (--this->count == 0) - FreeResource (this->clientResource, RT_NONE); - - return Success; - } - - /* If we get to this point, this client isn't suspending the screensaver */ - if (stuff->suspend == FALSE) - return Success; - - /* - * Allocate a suspension record for the client, and stop the screensaver - * if it isn't already suspended by another client. We attach a resource ID - * to the record, so the screensaver will be reenabled and the record freed - * if the client disconnects without reenabling it first. - */ - this = xalloc (sizeof (ScreenSaverSuspensionRec)); - - if (!this) - return BadAlloc; - - this->next = NULL; - this->pClient = client; - this->count = 1; - this->clientResource = FakeClientID (client->index); - - if (!AddResource (this->clientResource, SuspendType, (pointer) this)) - { - xfree (this); - return BadAlloc; - } - - *prev = this; - if (!screenSaverSuspended) - { - screenSaverSuspended = TRUE; - FreeScreenSaverTimer(); - } - - return (client->noClientException); -} - -static DISPATCH_PROC((*NormalVector[])) = { - ProcScreenSaverQueryVersion, - ProcScreenSaverQueryInfo, - ProcScreenSaverSelectInput, - ProcScreenSaverSetAttributes, - ProcScreenSaverUnsetAttributes, - ProcScreenSaverSuspend, -}; - -#define NUM_REQUESTS ((sizeof NormalVector) / (sizeof NormalVector[0])) - -static int -ProcScreenSaverDispatch (ClientPtr client) -{ - REQUEST(xReq); - - if (stuff->data < NUM_REQUESTS) - return (*NormalVector[stuff->data])(client); - return BadRequest; -} - -static int -SProcScreenSaverQueryVersion (ClientPtr client) -{ - REQUEST(xScreenSaverQueryVersionReq); - int n; - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xScreenSaverQueryVersionReq); - return ProcScreenSaverQueryVersion (client); -} - -static int -SProcScreenSaverQueryInfo (ClientPtr client) -{ - REQUEST(xScreenSaverQueryInfoReq); - int n; - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xScreenSaverQueryInfoReq); - swapl (&stuff->drawable, n); - return ProcScreenSaverQueryInfo (client); -} - -static int -SProcScreenSaverSelectInput (ClientPtr client) -{ - REQUEST(xScreenSaverSelectInputReq); - int n; - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xScreenSaverSelectInputReq); - swapl (&stuff->drawable, n); - swapl (&stuff->eventMask, n); - return ProcScreenSaverSelectInput (client); -} - -static int -SProcScreenSaverSetAttributes (ClientPtr client) -{ - REQUEST(xScreenSaverSetAttributesReq); - int n; - - swaps (&stuff->length, n); - REQUEST_AT_LEAST_SIZE(xScreenSaverSetAttributesReq); - swapl (&stuff->drawable, n); - swaps (&stuff->x, n); - swaps (&stuff->y, n); - swaps (&stuff->width, n); - swaps (&stuff->height, n); - swaps (&stuff->borderWidth, n); - swapl (&stuff->visualID, n); - swapl (&stuff->mask, n); - SwapRestL(stuff); - return ProcScreenSaverSetAttributes (client); -} - -static int -SProcScreenSaverUnsetAttributes (ClientPtr client) -{ - REQUEST(xScreenSaverUnsetAttributesReq); - int n; - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xScreenSaverUnsetAttributesReq); - swapl (&stuff->drawable, n); - return ProcScreenSaverUnsetAttributes (client); -} - -static int -SProcScreenSaverSuspend (ClientPtr client) -{ - int n; - REQUEST(xScreenSaverSuspendReq); - - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xScreenSaverSuspendReq); - swapl(&stuff->suspend, n); - return ProcScreenSaverSuspend (client); -} - -static DISPATCH_PROC((*SwappedVector[])) = { - SProcScreenSaverQueryVersion, - SProcScreenSaverQueryInfo, - SProcScreenSaverSelectInput, - SProcScreenSaverSetAttributes, - SProcScreenSaverUnsetAttributes, - SProcScreenSaverSuspend, -}; - -static int -SProcScreenSaverDispatch (ClientPtr client) -{ - REQUEST(xReq); - - if (stuff->data < NUM_REQUESTS) - return (*SwappedVector[stuff->data])(client); - return BadRequest; -} +/*
+ *
+Copyright (c) 1992 X Consortium
+
+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
+X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of the X Consortium 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 X Consortium.
+ *
+ * Author: Keith Packard, MIT X Consortium
+ */
+
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+#define SCREENSAVER
+#endif
+
+#ifdef CreateWindow
+#undef CreateWindow
+#endif
+
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "misc.h"
+#include "os.h"
+#include "windowstr.h"
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "extnsionst.h"
+#include "dixstruct.h"
+#include "resource.h"
+#include "opaque.h"
+#include <X11/extensions/saverproto.h>
+#include "gcstruct.h"
+#include "cursorstr.h"
+#include "colormapst.h"
+#include "xace.h"
+#ifdef PANORAMIX
+#include "panoramiX.h"
+#include "panoramiXsrv.h"
+#endif
+#ifdef DPMSExtension
+#include <X11/extensions/dpmsconst.h>
+#endif
+#include "protocol-versions.h"
+
+#include <stdio.h>
+
+#include "modinit.h"
+
+static int ScreenSaverEventBase = 0;
+
+static DISPATCH_PROC(ProcScreenSaverQueryInfo);
+static DISPATCH_PROC(ProcScreenSaverDispatch);
+static DISPATCH_PROC(ProcScreenSaverQueryVersion);
+static DISPATCH_PROC(ProcScreenSaverSelectInput);
+static DISPATCH_PROC(ProcScreenSaverSetAttributes);
+static DISPATCH_PROC(ProcScreenSaverUnsetAttributes);
+static DISPATCH_PROC(ProcScreenSaverSuspend);
+static DISPATCH_PROC(SProcScreenSaverDispatch);
+static DISPATCH_PROC(SProcScreenSaverQueryInfo);
+static DISPATCH_PROC(SProcScreenSaverQueryVersion);
+static DISPATCH_PROC(SProcScreenSaverSelectInput);
+static DISPATCH_PROC(SProcScreenSaverSetAttributes);
+static DISPATCH_PROC(SProcScreenSaverUnsetAttributes);
+static DISPATCH_PROC(SProcScreenSaverSuspend);
+
+static Bool ScreenSaverHandle (
+ ScreenPtr /* pScreen */,
+ int /* xstate */,
+ Bool /* force */
+ );
+
+static Bool
+CreateSaverWindow (
+ ScreenPtr /* pScreen */
+ );
+
+static Bool
+DestroySaverWindow (
+ ScreenPtr /* pScreen */
+ );
+
+static void
+UninstallSaverColormap (
+ ScreenPtr /* pScreen */
+ );
+
+static void
+CheckScreenPrivate (
+ ScreenPtr /* pScreen */
+ );
+
+static void SScreenSaverNotifyEvent (
+ xScreenSaverNotifyEvent * /* from */,
+ xScreenSaverNotifyEvent * /* to */
+ );
+
+static RESTYPE SuspendType; /* resource type for suspension records */
+
+typedef struct _ScreenSaverSuspension *ScreenSaverSuspensionPtr;
+
+/* List of clients that are suspending the screensaver. */
+static ScreenSaverSuspensionPtr suspendingClients = NULL;
+
+/*
+ * clientResource is a resource ID that's added when the record is
+ * allocated, so the record is freed and the screensaver resumed when
+ * the client disconnects. count is the number of times the client has
+ * requested the screensaver be suspended.
+ */
+typedef struct _ScreenSaverSuspension
+{
+ ScreenSaverSuspensionPtr next;
+ ClientPtr pClient;
+ XID clientResource;
+ int count;
+} ScreenSaverSuspensionRec;
+
+static int ScreenSaverFreeSuspend(
+ pointer /*value */,
+ XID /* id */
+);
+
+/*
+ * each screen has a list of clients requesting
+ * ScreenSaverNotify events. Each client has a resource
+ * for each screen it selects ScreenSaverNotify input for,
+ * this resource is used to delete the ScreenSaverNotifyRec
+ * entry from the per-screen queue.
+ */
+
+static RESTYPE SaverEventType; /* resource type for event masks */
+
+typedef struct _ScreenSaverEvent *ScreenSaverEventPtr;
+
+typedef struct _ScreenSaverEvent {
+ ScreenSaverEventPtr next;
+ ClientPtr client;
+ ScreenPtr screen;
+ XID resource;
+ CARD32 mask;
+} ScreenSaverEventRec;
+
+static int ScreenSaverFreeEvents(
+ pointer /* value */,
+ XID /* id */
+);
+
+static Bool setEventMask (
+ ScreenPtr /* pScreen */,
+ ClientPtr /* client */,
+ unsigned long /* mask */
+);
+
+static unsigned long getEventMask (
+ ScreenPtr /* pScreen */,
+ ClientPtr /* client */
+);
+
+/*
+ * when a client sets the screen saver attributes, a resource is
+ * kept to be freed when the client exits
+ */
+
+static RESTYPE AttrType; /* resource type for attributes */
+
+typedef struct _ScreenSaverAttr {
+ ScreenPtr screen;
+ ClientPtr client;
+ XID resource;
+ short x, y;
+ unsigned short width, height, borderWidth;
+ unsigned char class;
+ unsigned char depth;
+ VisualID visual;
+ CursorPtr pCursor;
+ PixmapPtr pBackgroundPixmap;
+ PixmapPtr pBorderPixmap;
+ Colormap colormap;
+ unsigned long mask; /* no pixmaps or cursors */
+ unsigned long *values;
+} ScreenSaverAttrRec, *ScreenSaverAttrPtr;
+
+static int ScreenSaverFreeAttr (
+ pointer /* value */,
+ XID /* id */
+);
+
+static void FreeAttrs (
+ ScreenSaverAttrPtr /* pAttr */
+);
+
+static void FreeScreenAttr (
+ ScreenSaverAttrPtr /* pAttr */
+);
+
+static void
+SendScreenSaverNotify (
+ ScreenPtr /* pScreen */,
+ int /* state */,
+ Bool /* forced */
+);
+
+typedef struct _ScreenSaverScreenPrivate {
+ ScreenSaverEventPtr events;
+ ScreenSaverAttrPtr attr;
+ Bool hasWindow;
+ Colormap installedMap;
+} ScreenSaverScreenPrivateRec, *ScreenSaverScreenPrivatePtr;
+
+static ScreenSaverScreenPrivatePtr
+MakeScreenPrivate (
+ ScreenPtr /* pScreen */
+ );
+
+static int ScreenPrivateKeyIndex;
+static DevPrivateKey ScreenPrivateKey = &ScreenPrivateKeyIndex;
+
+#define GetScreenPrivate(s) ((ScreenSaverScreenPrivatePtr) \
+ dixLookupPrivate(&(s)->devPrivates, ScreenPrivateKey))
+#define SetScreenPrivate(s,v) \
+ dixSetPrivate(&(s)->devPrivates, ScreenPrivateKey, v);
+#define SetupScreen(s) ScreenSaverScreenPrivatePtr pPriv = (s ? GetScreenPrivate(s) : NULL)
+
+#define New(t) (xalloc (sizeof (t)))
+
+/****************
+ * ScreenSaverExtensionInit
+ *
+ * Called from InitExtensions in main() or from QueryExtension() if the
+ * extension is dynamically loaded.
+ *
+ ****************/
+
+void
+ScreenSaverExtensionInit(INITARGS)
+{
+ ExtensionEntry *extEntry;
+ int i;
+ ScreenPtr pScreen;
+
+ AttrType = CreateNewResourceType(ScreenSaverFreeAttr);
+ SaverEventType = CreateNewResourceType(ScreenSaverFreeEvents);
+ SuspendType = CreateNewResourceType(ScreenSaverFreeSuspend);
+
+ for (i = 0; i < screenInfo.numScreens; i++)
+ {
+ pScreen = screenInfo.screens[i];
+ SetScreenPrivate (pScreen, NULL);
+ }
+ if (AttrType && SaverEventType && SuspendType &&
+ (extEntry = AddExtension(ScreenSaverName, ScreenSaverNumberEvents, 0,
+ ProcScreenSaverDispatch, SProcScreenSaverDispatch,
+ NULL, StandardMinorOpcode)))
+ {
+ ScreenSaverEventBase = extEntry->eventBase;
+ EventSwapVector[ScreenSaverEventBase] = (EventSwapPtr) SScreenSaverNotifyEvent;
+ }
+}
+
+static void
+CheckScreenPrivate (ScreenPtr pScreen)
+{
+ SetupScreen (pScreen);
+
+ if (!pPriv)
+ return;
+ if (!pPriv->attr && !pPriv->events &&
+ !pPriv->hasWindow && pPriv->installedMap == None)
+ {
+ xfree (pPriv);
+ SetScreenPrivate (pScreen, NULL);
+ savedScreenInfo[pScreen->myNum].ExternalScreenSaver = NULL;
+ }
+}
+
+static ScreenSaverScreenPrivatePtr
+MakeScreenPrivate (ScreenPtr pScreen)
+{
+ SetupScreen (pScreen);
+
+ if (pPriv)
+ return pPriv;
+ pPriv = New (ScreenSaverScreenPrivateRec);
+ if (!pPriv)
+ return 0;
+ pPriv->events = 0;
+ pPriv->attr = 0;
+ pPriv->hasWindow = FALSE;
+ pPriv->installedMap = None;
+ SetScreenPrivate (pScreen, pPriv);
+ savedScreenInfo[pScreen->myNum].ExternalScreenSaver = ScreenSaverHandle;
+ return pPriv;
+}
+
+static unsigned long
+getEventMask (ScreenPtr pScreen, ClientPtr client)
+{
+ SetupScreen(pScreen);
+ ScreenSaverEventPtr pEv;
+
+ if (!pPriv)
+ return 0;
+ for (pEv = pPriv->events; pEv; pEv = pEv->next)
+ if (pEv->client == client)
+ return pEv->mask;
+ return 0;
+}
+
+static Bool
+setEventMask (ScreenPtr pScreen, ClientPtr client, unsigned long mask)
+{
+ SetupScreen(pScreen);
+ ScreenSaverEventPtr pEv, *pPrev;
+
+ if (getEventMask (pScreen, client) == mask)
+ return TRUE;
+ if (!pPriv)
+ {
+ pPriv = MakeScreenPrivate (pScreen);
+ if (!pPriv)
+ return FALSE;
+ }
+ for (pPrev = &pPriv->events; (pEv = *pPrev) != 0; pPrev = &pEv->next)
+ if (pEv->client == client)
+ break;
+ if (mask == 0)
+ {
+ FreeResource (pEv->resource, SaverEventType);
+ *pPrev = pEv->next;
+ xfree (pEv);
+ CheckScreenPrivate (pScreen);
+ }
+ else
+ {
+ if (!pEv)
+ {
+ pEv = New (ScreenSaverEventRec);
+ if (!pEv)
+ {
+ CheckScreenPrivate (pScreen);
+ return FALSE;
+ }
+ *pPrev = pEv;
+ pEv->next = NULL;
+ pEv->client = client;
+ pEv->screen = pScreen;
+ pEv->resource = FakeClientID (client->index);
+ if (!AddResource (pEv->resource, SaverEventType, (pointer) pEv))
+ return FALSE;
+ }
+ pEv->mask = mask;
+ }
+ return TRUE;
+}
+
+static void
+FreeAttrs (ScreenSaverAttrPtr pAttr)
+{
+ PixmapPtr pPixmap;
+ CursorPtr pCursor;
+
+ if ((pPixmap = pAttr->pBackgroundPixmap) != 0)
+ (*pPixmap->drawable.pScreen->DestroyPixmap)(pPixmap);
+ if ((pPixmap = pAttr->pBorderPixmap) != 0)
+ (*pPixmap->drawable.pScreen->DestroyPixmap)(pPixmap);
+ if ((pCursor = pAttr->pCursor) != 0)
+ FreeCursor (pCursor, (Cursor) 0);
+}
+
+static void
+FreeScreenAttr (ScreenSaverAttrPtr pAttr)
+{
+ FreeAttrs (pAttr);
+ xfree (pAttr->values);
+ xfree (pAttr);
+}
+
+static int
+ScreenSaverFreeEvents (pointer value, XID id)
+{
+ ScreenSaverEventPtr pOld = (ScreenSaverEventPtr)value;
+ ScreenPtr pScreen = pOld->screen;
+ SetupScreen (pScreen);
+ ScreenSaverEventPtr pEv, *pPrev;
+
+ if (!pPriv)
+ return TRUE;
+ for (pPrev = &pPriv->events; (pEv = *pPrev) != 0; pPrev = &pEv->next)
+ if (pEv == pOld)
+ break;
+ if (!pEv)
+ return TRUE;
+ *pPrev = pEv->next;
+ xfree (pEv);
+ CheckScreenPrivate (pScreen);
+ return TRUE;
+}
+
+static int
+ScreenSaverFreeAttr (pointer value, XID id)
+{
+ ScreenSaverAttrPtr pOldAttr = (ScreenSaverAttrPtr)value;
+ ScreenPtr pScreen = pOldAttr->screen;
+ SetupScreen (pScreen);
+
+ if (!pPriv)
+ return TRUE;
+ if (pPriv->attr != pOldAttr)
+ return TRUE;
+ FreeScreenAttr (pOldAttr);
+ pPriv->attr = NULL;
+ if (pPriv->hasWindow)
+ {
+ dixSaveScreens (serverClient, SCREEN_SAVER_FORCER, ScreenSaverReset);
+ dixSaveScreens (serverClient, SCREEN_SAVER_FORCER, ScreenSaverActive);
+ }
+ CheckScreenPrivate (pScreen);
+ return TRUE;
+}
+
+static int
+ScreenSaverFreeSuspend (pointer value, XID id)
+{
+ ScreenSaverSuspensionPtr data = (ScreenSaverSuspensionPtr) value;
+ ScreenSaverSuspensionPtr *prev, this;
+
+ /* Unlink and free the suspension record for the client */
+ for (prev = &suspendingClients; (this = *prev); prev = &this->next)
+ {
+ if (this == data)
+ {
+ *prev = this->next;
+ xfree (this);
+ break;
+ }
+ }
+
+ /* Reenable the screensaver if this was the last client suspending it. */
+ if (screenSaverSuspended && suspendingClients == NULL)
+ {
+ screenSaverSuspended = FALSE;
+
+ /* The screensaver could be active, since suspending it (by design)
+ doesn't prevent it from being forceably activated */
+#ifdef DPMSExtension
+ if (screenIsSaved != SCREEN_SAVER_ON && DPMSPowerLevel == DPMSModeOn)
+#else
+ if (screenIsSaved != SCREEN_SAVER_ON)
+#endif
+ {
+ UpdateCurrentTimeIf();
+ lastDeviceEventTime = currentTime;
+ SetScreenSaverTimer();
+ }
+ }
+
+ return Success;
+}
+
+static void
+SendScreenSaverNotify (ScreenPtr pScreen, int state, Bool forced)
+{
+ ScreenSaverScreenPrivatePtr pPriv;
+ ScreenSaverEventPtr pEv;
+ unsigned long mask;
+ xScreenSaverNotifyEvent ev;
+ ClientPtr client;
+ int kind;
+
+ UpdateCurrentTimeIf ();
+ mask = ScreenSaverNotifyMask;
+ if (state == ScreenSaverCycle)
+ mask = ScreenSaverCycleMask;
+ pScreen = screenInfo.screens[pScreen->myNum];
+ pPriv = GetScreenPrivate(pScreen);
+ if (!pPriv)
+ return;
+ if (pPriv->attr)
+ kind = ScreenSaverExternal;
+ else if (ScreenSaverBlanking != DontPreferBlanking)
+ kind = ScreenSaverBlanked;
+ else
+ kind = ScreenSaverInternal;
+ for (pEv = pPriv->events; pEv; pEv = pEv->next)
+ {
+ client = pEv->client;
+ if (client->clientGone)
+ continue;
+ if (!(pEv->mask & mask))
+ continue;
+ ev.type = ScreenSaverNotify + ScreenSaverEventBase;
+ ev.state = state;
+ ev.sequenceNumber = client->sequence;
+ ev.timestamp = currentTime.milliseconds;
+ ev.root = WindowTable[pScreen->myNum]->drawable.id;
+ ev.window = savedScreenInfo[pScreen->myNum].wid;
+ ev.kind = kind;
+ ev.forced = forced;
+ WriteEventsToClient (client, 1, (xEvent *) &ev);
+ }
+}
+
+static void
+SScreenSaverNotifyEvent (xScreenSaverNotifyEvent *from,
+ xScreenSaverNotifyEvent *to)
+{
+ to->type = from->type;
+ to->state = from->state;
+ cpswaps (from->sequenceNumber, to->sequenceNumber);
+ cpswapl (from->timestamp, to->timestamp);
+ cpswapl (from->root, to->root);
+ cpswapl (from->window, to->window);
+ to->kind = from->kind;
+ to->forced = from->forced;
+}
+
+static void
+UninstallSaverColormap (ScreenPtr pScreen)
+{
+ SetupScreen(pScreen);
+ ColormapPtr pCmap;
+ int rc;
+
+ if (pPriv && pPriv->installedMap != None)
+ {
+ rc = dixLookupResourceByType((pointer *)&pCmap, pPriv->installedMap,
+ RT_COLORMAP, serverClient,
+ DixUninstallAccess);
+ if (rc == Success)
+ (*pCmap->pScreen->UninstallColormap) (pCmap);
+ pPriv->installedMap = None;
+ CheckScreenPrivate (pScreen);
+ }
+}
+
+static Bool
+CreateSaverWindow (ScreenPtr pScreen)
+{
+ SetupScreen (pScreen);
+ ScreenSaverStuffPtr pSaver;
+ ScreenSaverAttrPtr pAttr;
+ WindowPtr pWin;
+ int result;
+ unsigned long mask;
+ Colormap *installedMaps;
+ int numInstalled;
+ int i;
+ Colormap wantMap;
+ ColormapPtr pCmap;
+
+ pSaver = &savedScreenInfo[pScreen->myNum];
+ if (pSaver->pWindow)
+ {
+ pSaver->pWindow = NullWindow;
+ FreeResource (pSaver->wid, RT_NONE);
+ if (pPriv)
+ {
+ UninstallSaverColormap (pScreen);
+ pPriv->hasWindow = FALSE;
+ CheckScreenPrivate (pScreen);
+ }
+ }
+
+ if (!pPriv || !(pAttr = pPriv->attr))
+ return FALSE;
+
+ pPriv->installedMap = None;
+
+ if (GrabInProgress && GrabInProgress != pAttr->client->index)
+ return FALSE;
+
+ pWin = CreateWindow (pSaver->wid, WindowTable[pScreen->myNum],
+ pAttr->x, pAttr->y, pAttr->width, pAttr->height,
+ pAttr->borderWidth, pAttr->class,
+ pAttr->mask, (XID *)pAttr->values,
+ pAttr->depth, serverClient, pAttr->visual,
+ &result);
+ if (!pWin)
+ return FALSE;
+
+ if (!AddResource(pWin->drawable.id, RT_WINDOW, pWin))
+ return FALSE;
+
+ mask = 0;
+ if (pAttr->pBackgroundPixmap)
+ {
+ pWin->backgroundState = BackgroundPixmap;
+ pWin->background.pixmap = pAttr->pBackgroundPixmap;
+ pAttr->pBackgroundPixmap->refcnt++;
+ mask |= CWBackPixmap;
+ }
+ if (pAttr->pBorderPixmap)
+ {
+ pWin->borderIsPixel = FALSE;
+ pWin->border.pixmap = pAttr->pBorderPixmap;
+ pAttr->pBorderPixmap->refcnt++;
+ mask |= CWBorderPixmap;
+ }
+ if (pAttr->pCursor)
+ {
+ if (!pWin->optional)
+ if (!MakeWindowOptional (pWin))
+ {
+ FreeResource (pWin->drawable.id, RT_NONE);
+ return FALSE;
+ }
+ if (pWin->optional->cursor)
+ FreeCursor (pWin->optional->cursor, (Cursor)0);
+ pWin->optional->cursor = pAttr->pCursor;
+ pAttr->pCursor->refcnt++;
+ pWin->cursorIsNone = FALSE;
+ CheckWindowOptionalNeed (pWin);
+ mask |= CWCursor;
+ }
+ if (mask)
+ (*pScreen->ChangeWindowAttributes) (pWin, mask);
+
+ if (pAttr->colormap != None)
+ (void) ChangeWindowAttributes (pWin, CWColormap, &pAttr->colormap,
+ serverClient);
+
+ MapWindow (pWin, serverClient);
+
+ pPriv->hasWindow = TRUE;
+ pSaver->pWindow = pWin;
+
+ /* check and install our own colormap if it isn't installed now */
+ wantMap = wColormap (pWin);
+ if (wantMap == None)
+ return TRUE;
+ installedMaps = xalloc (pScreen->maxInstalledCmaps * sizeof (Colormap));
+ numInstalled = (*pWin->drawable.pScreen->ListInstalledColormaps)
+ (pScreen, installedMaps);
+ for (i = 0; i < numInstalled; i++)
+ if (installedMaps[i] == wantMap)
+ break;
+
+ xfree ((char *) installedMaps);
+
+ if (i < numInstalled)
+ return TRUE;
+
+ result = dixLookupResourceByType((pointer *)&pCmap, wantMap, RT_COLORMAP,
+ serverClient, DixInstallAccess);
+ if (result != Success)
+ return TRUE;
+
+ pPriv->installedMap = wantMap;
+
+ (*pCmap->pScreen->InstallColormap) (pCmap);
+
+ return TRUE;
+}
+
+static Bool
+DestroySaverWindow (ScreenPtr pScreen)
+{
+ SetupScreen(pScreen);
+ ScreenSaverStuffPtr pSaver;
+
+ if (!pPriv || !pPriv->hasWindow)
+ return FALSE;
+
+ pSaver = &savedScreenInfo[pScreen->myNum];
+ if (pSaver->pWindow)
+ {
+ pSaver->pWindow = NullWindow;
+ FreeResource (pSaver->wid, RT_NONE);
+ }
+ pPriv->hasWindow = FALSE;
+ CheckScreenPrivate (pScreen);
+ UninstallSaverColormap (pScreen);
+ return TRUE;
+}
+
+static Bool
+ScreenSaverHandle (ScreenPtr pScreen, int xstate, Bool force)
+{
+ int state = 0;
+ Bool ret = FALSE;
+ ScreenSaverScreenPrivatePtr pPriv;
+
+ switch (xstate)
+ {
+ case SCREEN_SAVER_ON:
+ state = ScreenSaverOn;
+ ret = CreateSaverWindow (pScreen);
+ break;
+ case SCREEN_SAVER_OFF:
+ state = ScreenSaverOff;
+ ret = DestroySaverWindow (pScreen);
+ break;
+ case SCREEN_SAVER_CYCLE:
+ state = ScreenSaverCycle;
+ pPriv = GetScreenPrivate (pScreen);
+ if (pPriv && pPriv->hasWindow)
+ ret = TRUE;
+
+ }
+#ifdef PANORAMIX
+ if(noPanoramiXExtension || !pScreen->myNum)
+#endif
+ SendScreenSaverNotify (pScreen, state, force);
+ return ret;
+}
+
+static int
+ProcScreenSaverQueryVersion (ClientPtr client)
+{
+ xScreenSaverQueryVersionReply rep;
+ int n;
+
+ REQUEST_SIZE_MATCH (xScreenSaverQueryVersionReq);
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.majorVersion = SERVER_SAVER_MAJOR_VERSION;
+ rep.minorVersion = SERVER_SAVER_MINOR_VERSION;
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.length, n);
+ }
+ WriteToClient(client, sizeof (xScreenSaverQueryVersionReply), (char *)&rep);
+ return (client->noClientException);
+}
+
+static int
+ProcScreenSaverQueryInfo (ClientPtr client)
+{
+ REQUEST(xScreenSaverQueryInfoReq);
+ xScreenSaverQueryInfoReply rep;
+ int n, rc;
+ ScreenSaverStuffPtr pSaver;
+ DrawablePtr pDraw;
+ CARD32 lastInput;
+ ScreenSaverScreenPrivatePtr pPriv;
+
+ REQUEST_SIZE_MATCH (xScreenSaverQueryInfoReq);
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ rc = XaceHook(XACE_SCREENSAVER_ACCESS, client, pDraw->pScreen,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ pSaver = &savedScreenInfo[pDraw->pScreen->myNum];
+ pPriv = GetScreenPrivate (pDraw->pScreen);
+
+ UpdateCurrentTime ();
+ lastInput = GetTimeInMillis() - lastDeviceEventTime.milliseconds;
+
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.window = pSaver->wid;
+ if (screenIsSaved != SCREEN_SAVER_OFF)
+ {
+ rep.state = ScreenSaverOn;
+ if (ScreenSaverTime)
+ rep.tilOrSince = lastInput - ScreenSaverTime;
+ else
+ rep.tilOrSince = 0;
+ }
+ else
+ {
+ if (ScreenSaverTime)
+ {
+ rep.state = ScreenSaverOff;
+ if (ScreenSaverTime < lastInput)
+ rep.tilOrSince = 0;
+ else
+ rep.tilOrSince = ScreenSaverTime - lastInput;
+ }
+ else
+ {
+ rep.state = ScreenSaverDisabled;
+ rep.tilOrSince = 0;
+ }
+ }
+ rep.idle = lastInput;
+ rep.eventMask = getEventMask (pDraw->pScreen, client);
+ if (pPriv && pPriv->attr)
+ rep.kind = ScreenSaverExternal;
+ else if (ScreenSaverBlanking != DontPreferBlanking)
+ rep.kind = ScreenSaverBlanked;
+ else
+ rep.kind = ScreenSaverInternal;
+ if (client->swapped)
+ {
+ swaps (&rep.sequenceNumber, n);
+ swapl (&rep.length, n);
+ swapl (&rep.window, n);
+ swapl (&rep.tilOrSince, n);
+ swapl (&rep.idle, n);
+ swapl (&rep.eventMask, n);
+ }
+ WriteToClient(client, sizeof (xScreenSaverQueryInfoReply), (char *)&rep);
+ return (client->noClientException);
+}
+
+static int
+ProcScreenSaverSelectInput (ClientPtr client)
+{
+ REQUEST(xScreenSaverSelectInputReq);
+ DrawablePtr pDraw;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xScreenSaverSelectInputReq);
+ rc = dixLookupDrawable (&pDraw, stuff->drawable, client, 0,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ rc = XaceHook(XACE_SCREENSAVER_ACCESS, client, pDraw->pScreen,
+ DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ if (!setEventMask (pDraw->pScreen, client, stuff->eventMask))
+ return BadAlloc;
+ return Success;
+}
+
+static int
+ScreenSaverSetAttributes (ClientPtr client)
+{
+ REQUEST(xScreenSaverSetAttributesReq);
+ DrawablePtr pDraw;
+ WindowPtr pParent;
+ ScreenPtr pScreen;
+ ScreenSaverScreenPrivatePtr pPriv = 0;
+ ScreenSaverAttrPtr pAttr = 0;
+ int ret, len, class, bw, depth;
+ unsigned long visual;
+ int idepth, ivisual;
+ Bool fOK;
+ DepthPtr pDepth;
+ WindowOptPtr ancwopt;
+ unsigned int *pVlist;
+ unsigned long *values = 0;
+ unsigned long tmask, imask;
+ unsigned long val;
+ Pixmap pixID;
+ PixmapPtr pPixmap;
+ Cursor cursorID;
+ CursorPtr pCursor;
+ Colormap cmap;
+ ColormapPtr pCmap;
+
+ REQUEST_AT_LEAST_SIZE (xScreenSaverSetAttributesReq);
+ ret = dixLookupDrawable(&pDraw, stuff->drawable, client, 0,
+ DixGetAttrAccess);
+ if (ret != Success)
+ return ret;
+ pScreen = pDraw->pScreen;
+ pParent = WindowTable[pScreen->myNum];
+
+ ret = XaceHook(XACE_SCREENSAVER_ACCESS, client, pScreen, DixSetAttrAccess);
+ if (ret != Success)
+ return ret;
+
+ len = stuff->length - bytes_to_int32(sizeof(xScreenSaverSetAttributesReq));
+ if (Ones(stuff->mask) != len)
+ return BadLength;
+ if (!stuff->width || !stuff->height)
+ {
+ client->errorValue = 0;
+ return BadValue;
+ }
+ switch (class = stuff->c_class)
+ {
+ case CopyFromParent:
+ case InputOnly:
+ case InputOutput:
+ break;
+ default:
+ client->errorValue = class;
+ return BadValue;
+ }
+ bw = stuff->borderWidth;
+ depth = stuff->depth;
+ visual = stuff->visualID;
+
+ /* copied directly from CreateWindow */
+
+ if (class == CopyFromParent)
+ class = pParent->drawable.class;
+
+ if ((class != InputOutput) && (class != InputOnly))
+ {
+ client->errorValue = class;
+ return BadValue;
+ }
+
+ if ((class != InputOnly) && (pParent->drawable.class == InputOnly))
+ return BadMatch;
+
+ if ((class == InputOnly) && ((bw != 0) || (depth != 0)))
+ return BadMatch;
+
+ if ((class == InputOutput) && (depth == 0))
+ depth = pParent->drawable.depth;
+ ancwopt = pParent->optional;
+ if (!ancwopt)
+ ancwopt = FindWindowWithOptional(pParent)->optional;
+ if (visual == CopyFromParent)
+ visual = ancwopt->visual;
+
+ /* Find out if the depth and visual are acceptable for this Screen */
+ if ((visual != ancwopt->visual) || (depth != pParent->drawable.depth))
+ {
+ fOK = FALSE;
+ for(idepth = 0; idepth < pScreen->numDepths; idepth++)
+ {
+ pDepth = (DepthPtr) &pScreen->allowedDepths[idepth];
+ if ((depth == pDepth->depth) || (depth == 0))
+ {
+ for (ivisual = 0; ivisual < pDepth->numVids; ivisual++)
+ {
+ if (visual == pDepth->vids[ivisual])
+ {
+ fOK = TRUE;
+ break;
+ }
+ }
+ }
+ }
+ if (fOK == FALSE)
+ return BadMatch;
+ }
+
+ if (((stuff->mask & (CWBorderPixmap | CWBorderPixel)) == 0) &&
+ (class != InputOnly) &&
+ (depth != pParent->drawable.depth))
+ {
+ return BadMatch;
+ }
+
+ if (((stuff->mask & CWColormap) == 0) &&
+ (class != InputOnly) &&
+ ((visual != ancwopt->visual) || (ancwopt->colormap == None)))
+ {
+ return BadMatch;
+ }
+
+ /* end of errors from CreateWindow */
+
+ pPriv = GetScreenPrivate (pScreen);
+ if (pPriv && pPriv->attr)
+ {
+ if (pPriv->attr->client != client)
+ return BadAccess;
+ }
+ if (!pPriv)
+ {
+ pPriv = MakeScreenPrivate (pScreen);
+ if (!pPriv)
+ return FALSE;
+ }
+ pAttr = New (ScreenSaverAttrRec);
+ if (!pAttr)
+ {
+ ret = BadAlloc;
+ goto bail;
+ }
+ /* over allocate for override redirect */
+ values = xalloc ((len + 1) * sizeof (unsigned long));
+ if (!values)
+ {
+ ret = BadAlloc;
+ goto bail;
+ }
+ pAttr->screen = pScreen;
+ pAttr->client = client;
+ pAttr->x = stuff->x;
+ pAttr->y = stuff->y;
+ pAttr->width = stuff->width;
+ pAttr->height = stuff->height;
+ pAttr->borderWidth = stuff->borderWidth;
+ pAttr->class = stuff->c_class;
+ pAttr->depth = depth;
+ pAttr->visual = visual;
+ pAttr->colormap = None;
+ pAttr->pCursor = NullCursor;
+ pAttr->pBackgroundPixmap = NullPixmap;
+ pAttr->pBorderPixmap = NullPixmap;
+ pAttr->values = values;
+ /*
+ * go through the mask, checking the values,
+ * looking up pixmaps and cursors and hold a reference
+ * to them.
+ */
+ pAttr->mask = tmask = stuff->mask | CWOverrideRedirect;
+ pVlist = (unsigned int *) (stuff + 1);
+ while (tmask) {
+ imask = lowbit (tmask);
+ tmask &= ~imask;
+ switch (imask)
+ {
+ case CWBackPixmap:
+ pixID = (Pixmap )*pVlist;
+ if (pixID == None)
+ {
+ *values++ = None;
+ }
+ else if (pixID == ParentRelative)
+ {
+ if (depth != pParent->drawable.depth)
+ {
+ ret = BadMatch;
+ goto PatchUp;
+ }
+ *values++ = ParentRelative;
+ }
+ else
+ {
+ ret = dixLookupResourceByType((pointer *)&pPixmap, pixID, RT_PIXMAP,
+ client, DixReadAccess);
+ if (ret == Success)
+ {
+ if ((pPixmap->drawable.depth != depth) ||
+ (pPixmap->drawable.pScreen != pScreen))
+ {
+ ret = BadMatch;
+ goto PatchUp;
+ }
+ pAttr->pBackgroundPixmap = pPixmap;
+ pPixmap->refcnt++;
+ pAttr->mask &= ~CWBackPixmap;
+ }
+ else
+ {
+ ret = (ret == BadValue) ? BadPixmap : ret;
+ client->errorValue = pixID;
+ goto PatchUp;
+ }
+ }
+ break;
+ case CWBackPixel:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWBorderPixmap:
+ pixID = (Pixmap ) *pVlist;
+ if (pixID == CopyFromParent)
+ {
+ if (depth != pParent->drawable.depth)
+ {
+ ret = BadMatch;
+ goto PatchUp;
+ }
+ *values++ = CopyFromParent;
+ }
+ else
+ {
+ ret = dixLookupResourceByType((pointer *)&pPixmap, pixID, RT_PIXMAP,
+ client, DixReadAccess);
+ if (ret == Success)
+ {
+ if ((pPixmap->drawable.depth != depth) ||
+ (pPixmap->drawable.pScreen != pScreen))
+ {
+ ret = BadMatch;
+ goto PatchUp;
+ }
+ pAttr->pBorderPixmap = pPixmap;
+ pPixmap->refcnt++;
+ pAttr->mask &= ~CWBorderPixmap;
+ }
+ else
+ {
+ ret = (ret == BadValue) ? BadPixmap : ret;
+ client->errorValue = pixID;
+ goto PatchUp;
+ }
+ }
+ break;
+ case CWBorderPixel:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWBitGravity:
+ val = (CARD8 )*pVlist;
+ if (val > StaticGravity)
+ {
+ ret = BadValue;
+ client->errorValue = val;
+ goto PatchUp;
+ }
+ *values++ = val;
+ break;
+ case CWWinGravity:
+ val = (CARD8 )*pVlist;
+ if (val > StaticGravity)
+ {
+ ret = BadValue;
+ client->errorValue = val;
+ goto PatchUp;
+ }
+ *values++ = val;
+ break;
+ case CWBackingStore:
+ val = (CARD8 )*pVlist;
+ if ((val != NotUseful) && (val != WhenMapped) && (val != Always))
+ {
+ ret = BadValue;
+ client->errorValue = val;
+ goto PatchUp;
+ }
+ *values++ = val;
+ break;
+ case CWBackingPlanes:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWBackingPixel:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWSaveUnder:
+ val = (BOOL) *pVlist;
+ if ((val != xTrue) && (val != xFalse))
+ {
+ ret = BadValue;
+ client->errorValue = val;
+ goto PatchUp;
+ }
+ *values++ = val;
+ break;
+ case CWEventMask:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWDontPropagate:
+ *values++ = (CARD32) *pVlist;
+ break;
+ case CWOverrideRedirect:
+ if (!(stuff->mask & CWOverrideRedirect))
+ pVlist--;
+ else
+ {
+ val = (BOOL ) *pVlist;
+ if ((val != xTrue) && (val != xFalse))
+ {
+ ret = BadValue;
+ client->errorValue = val;
+ goto PatchUp;
+ }
+ }
+ *values++ = xTrue;
+ break;
+ case CWColormap:
+ cmap = (Colormap) *pVlist;
+ ret = dixLookupResourceByType((pointer *)&pCmap, cmap, RT_COLORMAP,
+ client, DixUseAccess);
+ if (ret != Success)
+ {
+ ret = (ret == BadValue) ? BadColor : ret;
+ client->errorValue = cmap;
+ goto PatchUp;
+ }
+ if (pCmap->pVisual->vid != visual || pCmap->pScreen != pScreen)
+ {
+ ret = BadMatch;
+ goto PatchUp;
+ }
+ pAttr->colormap = cmap;
+ pAttr->mask &= ~CWColormap;
+ break;
+ case CWCursor:
+ cursorID = (Cursor ) *pVlist;
+ if ( cursorID == None)
+ {
+ *values++ = None;
+ }
+ else
+ {
+ ret = dixLookupResourceByType((pointer *)&pCursor, cursorID,
+ RT_CURSOR, client, DixUseAccess);
+ if (ret != Success)
+ {
+ ret = (ret == BadValue) ? BadCursor : ret;
+ client->errorValue = cursorID;
+ goto PatchUp;
+ }
+ pCursor->refcnt++;
+ pAttr->pCursor = pCursor;
+ pAttr->mask &= ~CWCursor;
+ }
+ break;
+ default:
+ ret = BadValue;
+ client->errorValue = stuff->mask;
+ goto PatchUp;
+ }
+ pVlist++;
+ }
+ if (pPriv->attr)
+ FreeScreenAttr (pPriv->attr);
+ pPriv->attr = pAttr;
+ pAttr->resource = FakeClientID (client->index);
+ if (!AddResource (pAttr->resource, AttrType, (pointer) pAttr))
+ return BadAlloc;
+ return Success;
+PatchUp:
+ FreeAttrs (pAttr);
+bail:
+ CheckScreenPrivate (pScreen);
+ if (pAttr) xfree (pAttr->values);
+ xfree (pAttr);
+ return ret;
+}
+
+static int
+ScreenSaverUnsetAttributes (ClientPtr client)
+{
+ REQUEST(xScreenSaverSetAttributesReq);
+ DrawablePtr pDraw;
+ ScreenSaverScreenPrivatePtr pPriv;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xScreenSaverUnsetAttributesReq);
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ pPriv = GetScreenPrivate (pDraw->pScreen);
+ if (pPriv && pPriv->attr && pPriv->attr->client == client)
+ {
+ FreeResource (pPriv->attr->resource, AttrType);
+ FreeScreenAttr (pPriv->attr);
+ pPriv->attr = NULL;
+ CheckScreenPrivate (pDraw->pScreen);
+ }
+ return Success;
+}
+
+static int
+ProcScreenSaverSetAttributes (ClientPtr client)
+{
+#ifdef PANORAMIX
+ if(!noPanoramiXExtension) {
+ REQUEST(xScreenSaverSetAttributesReq);
+ PanoramiXRes *draw;
+ PanoramiXRes *backPix = NULL;
+ PanoramiXRes *bordPix = NULL;
+ PanoramiXRes *cmap = NULL;
+ int i, status, len;
+ int pback_offset = 0, pbord_offset = 0, cmap_offset = 0;
+ XID orig_visual, tmp;
+
+ REQUEST_AT_LEAST_SIZE (xScreenSaverSetAttributesReq);
+
+ status = dixLookupResourceByClass((pointer *)&draw, stuff->drawable,
+ XRC_DRAWABLE, client, DixWriteAccess);
+ if (status != Success)
+ return (status == BadValue) ? BadDrawable : status;
+
+ len = stuff->length - bytes_to_int32(sizeof(xScreenSaverSetAttributesReq));
+ if (Ones(stuff->mask) != len)
+ return BadLength;
+
+ if((Mask)stuff->mask & CWBackPixmap) {
+ pback_offset = Ones((Mask)stuff->mask & (CWBackPixmap - 1));
+ tmp = *((CARD32 *) &stuff[1] + pback_offset);
+ if ((tmp != None) && (tmp != ParentRelative)) {
+ status = dixLookupResourceByType((pointer *)&backPix, tmp,
+ XRT_PIXMAP, client,
+ DixReadAccess);
+ if (status != Success)
+ return (status == BadValue) ? BadPixmap : status;
+ }
+ }
+
+ if ((Mask)stuff->mask & CWBorderPixmap) {
+ pbord_offset = Ones((Mask)stuff->mask & (CWBorderPixmap - 1));
+ tmp = *((CARD32 *) &stuff[1] + pbord_offset);
+ if (tmp != CopyFromParent) {
+ status = dixLookupResourceByType((pointer *)&bordPix, tmp,
+ XRT_PIXMAP, client,
+ DixReadAccess);
+ if (status != Success)
+ return (status == BadValue) ? BadPixmap : status;
+ }
+ }
+
+ if ((Mask)stuff->mask & CWColormap) {
+ cmap_offset = Ones((Mask)stuff->mask & (CWColormap - 1));
+ tmp = *((CARD32 *) &stuff[1] + cmap_offset);
+ if ((tmp != CopyFromParent) && (tmp != None)) {
+ status = dixLookupResourceByType((pointer *)&cmap, tmp,
+ XRT_COLORMAP, client,
+ DixReadAccess);
+ if (status != Success)
+ return (status == BadValue) ? BadColor : status;
+ }
+ }
+
+ orig_visual = stuff->visualID;
+
+ FOR_NSCREENS_BACKWARD(i) {
+ stuff->drawable = draw->info[i].id;
+ if (backPix)
+ *((CARD32 *) &stuff[1] + pback_offset) = backPix->info[i].id;
+ if (bordPix)
+ *((CARD32 *) &stuff[1] + pbord_offset) = bordPix->info[i].id;
+ if (cmap)
+ *((CARD32 *) &stuff[1] + cmap_offset) = cmap->info[i].id;
+
+ if (orig_visual != CopyFromParent)
+ stuff->visualID = PanoramiXTranslateVisualID(i, orig_visual);
+
+ status = ScreenSaverSetAttributes(client);
+ }
+
+ return status;
+ }
+#endif
+
+ return ScreenSaverSetAttributes(client);
+}
+
+static int
+ProcScreenSaverUnsetAttributes (ClientPtr client)
+{
+#ifdef PANORAMIX
+ if(!noPanoramiXExtension) {
+ REQUEST(xScreenSaverUnsetAttributesReq);
+ PanoramiXRes *draw;
+ int rc, i;
+
+ rc = dixLookupResourceByClass((pointer *)&draw, stuff->drawable,
+ XRC_DRAWABLE, client, DixWriteAccess);
+ if (rc != Success)
+ return (rc == BadValue) ? BadDrawable : rc;
+
+ for(i = PanoramiXNumScreens - 1; i > 0; i--) {
+ stuff->drawable = draw->info[i].id;
+ ScreenSaverUnsetAttributes(client);
+ }
+
+ stuff->drawable = draw->info[0].id;
+ }
+#endif
+
+ return ScreenSaverUnsetAttributes(client);
+}
+
+static int
+ProcScreenSaverSuspend (ClientPtr client)
+{
+ ScreenSaverSuspensionPtr *prev, this;
+
+ REQUEST(xScreenSaverSuspendReq);
+ REQUEST_SIZE_MATCH(xScreenSaverSuspendReq);
+
+ /* Check if this client is suspending the screensaver */
+ for (prev = &suspendingClients; (this = *prev); prev = &this->next)
+ if (this->pClient == client)
+ break;
+
+ if (this)
+ {
+ if (stuff->suspend == TRUE)
+ this->count++;
+ else if (--this->count == 0)
+ FreeResource (this->clientResource, RT_NONE);
+
+ return Success;
+ }
+
+ /* If we get to this point, this client isn't suspending the screensaver */
+ if (stuff->suspend == FALSE)
+ return Success;
+
+ /*
+ * Allocate a suspension record for the client, and stop the screensaver
+ * if it isn't already suspended by another client. We attach a resource ID
+ * to the record, so the screensaver will be reenabled and the record freed
+ * if the client disconnects without reenabling it first.
+ */
+ this = xalloc (sizeof (ScreenSaverSuspensionRec));
+
+ if (!this)
+ return BadAlloc;
+
+ this->next = NULL;
+ this->pClient = client;
+ this->count = 1;
+ this->clientResource = FakeClientID (client->index);
+
+ if (!AddResource (this->clientResource, SuspendType, (pointer) this))
+ {
+ xfree (this);
+ return BadAlloc;
+ }
+
+ *prev = this;
+ if (!screenSaverSuspended)
+ {
+ screenSaverSuspended = TRUE;
+ FreeScreenSaverTimer();
+ }
+
+ return (client->noClientException);
+}
+
+static DISPATCH_PROC((*NormalVector[])) = {
+ ProcScreenSaverQueryVersion,
+ ProcScreenSaverQueryInfo,
+ ProcScreenSaverSelectInput,
+ ProcScreenSaverSetAttributes,
+ ProcScreenSaverUnsetAttributes,
+ ProcScreenSaverSuspend,
+};
+
+#define NUM_REQUESTS ((sizeof NormalVector) / (sizeof NormalVector[0]))
+
+static int
+ProcScreenSaverDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+
+ if (stuff->data < NUM_REQUESTS)
+ return (*NormalVector[stuff->data])(client);
+ return BadRequest;
+}
+
+static int
+SProcScreenSaverQueryVersion (ClientPtr client)
+{
+ REQUEST(xScreenSaverQueryVersionReq);
+ int n;
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xScreenSaverQueryVersionReq);
+ return ProcScreenSaverQueryVersion (client);
+}
+
+static int
+SProcScreenSaverQueryInfo (ClientPtr client)
+{
+ REQUEST(xScreenSaverQueryInfoReq);
+ int n;
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xScreenSaverQueryInfoReq);
+ swapl (&stuff->drawable, n);
+ return ProcScreenSaverQueryInfo (client);
+}
+
+static int
+SProcScreenSaverSelectInput (ClientPtr client)
+{
+ REQUEST(xScreenSaverSelectInputReq);
+ int n;
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xScreenSaverSelectInputReq);
+ swapl (&stuff->drawable, n);
+ swapl (&stuff->eventMask, n);
+ return ProcScreenSaverSelectInput (client);
+}
+
+static int
+SProcScreenSaverSetAttributes (ClientPtr client)
+{
+ REQUEST(xScreenSaverSetAttributesReq);
+ int n;
+
+ swaps (&stuff->length, n);
+ REQUEST_AT_LEAST_SIZE(xScreenSaverSetAttributesReq);
+ swapl (&stuff->drawable, n);
+ swaps (&stuff->x, n);
+ swaps (&stuff->y, n);
+ swaps (&stuff->width, n);
+ swaps (&stuff->height, n);
+ swaps (&stuff->borderWidth, n);
+ swapl (&stuff->visualID, n);
+ swapl (&stuff->mask, n);
+ SwapRestL(stuff);
+ return ProcScreenSaverSetAttributes (client);
+}
+
+static int
+SProcScreenSaverUnsetAttributes (ClientPtr client)
+{
+ REQUEST(xScreenSaverUnsetAttributesReq);
+ int n;
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xScreenSaverUnsetAttributesReq);
+ swapl (&stuff->drawable, n);
+ return ProcScreenSaverUnsetAttributes (client);
+}
+
+static int
+SProcScreenSaverSuspend (ClientPtr client)
+{
+ int n;
+ REQUEST(xScreenSaverSuspendReq);
+
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xScreenSaverSuspendReq);
+ swapl(&stuff->suspend, n);
+ return ProcScreenSaverSuspend (client);
+}
+
+static DISPATCH_PROC((*SwappedVector[])) = {
+ SProcScreenSaverQueryVersion,
+ SProcScreenSaverQueryInfo,
+ SProcScreenSaverSelectInput,
+ SProcScreenSaverSetAttributes,
+ SProcScreenSaverUnsetAttributes,
+ SProcScreenSaverSuspend,
+};
+
+static int
+SProcScreenSaverDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+
+ if (stuff->data < NUM_REQUESTS)
+ return (*SwappedVector[stuff->data])(client);
+ return BadRequest;
+}
diff --git a/xorg-server/Xext/security.c b/xorg-server/Xext/security.c index 2cd0e1774..da7d1b9cf 100644 --- a/xorg-server/Xext/security.c +++ b/xorg-server/Xext/security.c @@ -1,1154 +1,1156 @@ -/* - -Copyright 1996, 1998 The Open Group - -Permission to use, copy, modify, distribute, and sell this software and its -documentation for any purpose is hereby granted without fee, provided that -the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation. - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of The Open Group shall not be -used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization from The Open Group. - -*/ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include "scrnintstr.h" -#include "inputstr.h" -#include "windowstr.h" -#include "propertyst.h" -#include "colormapst.h" -#include "privates.h" -#include "registry.h" -#include "xacestr.h" -#include "securitysrv.h" -#include <X11/extensions/securproto.h> -#include "modinit.h" -#include "protocol-versions.h" - -/* Extension stuff */ -static int SecurityErrorBase; /* first Security error number */ -static int SecurityEventBase; /* first Security event number */ - -RESTYPE SecurityAuthorizationResType; /* resource type for authorizations */ -static RESTYPE RTEventClient; - -static CallbackListPtr SecurityValidateGroupCallback = NULL; - -/* Private state record */ -static int stateKeyIndex; -static DevPrivateKey stateKey = &stateKeyIndex; - -/* This is what we store as client security state */ -typedef struct { - int haveState; - unsigned int trustLevel; - XID authId; -} SecurityStateRec; - -/* Extensions that untrusted clients shouldn't have access to */ -static char *SecurityTrustedExtensions[] = { - "XC-MISC", - "BIG-REQUESTS", - "XpExtension", - NULL -}; - -/* - * Access modes that untrusted clients are allowed on trusted objects. - */ -static const Mask SecurityResourceMask = - DixGetAttrAccess | DixReceiveAccess | DixListPropAccess | - DixGetPropAccess | DixListAccess; -static const Mask SecurityWindowExtraMask = DixRemoveAccess; -static const Mask SecurityRootWindowExtraMask = - DixReceiveAccess | DixSendAccess | DixAddAccess | DixRemoveAccess; -static const Mask SecurityDeviceMask = - DixGetAttrAccess | DixReceiveAccess | DixGetFocusAccess | - DixGrabAccess | DixSetAttrAccess | DixUseAccess; -static const Mask SecurityServerMask = DixGetAttrAccess | DixGrabAccess; -static const Mask SecurityClientMask = DixGetAttrAccess; - - -/* SecurityAudit - * - * Arguments: - * format is the formatting string to be used to interpret the - * remaining arguments. - * - * Returns: nothing. - * - * Side Effects: - * Writes the message to the log file if security logging is on. - */ - -static void -SecurityAudit(char *format, ...) -{ - va_list args; - - if (auditTrailLevel < SECURITY_AUDIT_LEVEL) - return; - va_start(args, format); - VAuditF(format, args); - va_end(args); -} /* SecurityAudit */ - -/* - * Performs a Security permission check. - */ -static int -SecurityDoCheck(SecurityStateRec *subj, SecurityStateRec *obj, - Mask requested, Mask allowed) -{ - if (!subj->haveState || !obj->haveState) - return Success; - if (subj->trustLevel == XSecurityClientTrusted) - return Success; - if (obj->trustLevel != XSecurityClientTrusted) - return Success; - if ((requested | allowed) == allowed) - return Success; - - return BadAccess; -} - -/* - * Labels initial server objects. - */ -static void -SecurityLabelInitial(void) -{ - SecurityStateRec *state; - - /* Do the serverClient */ - state = dixLookupPrivate(&serverClient->devPrivates, stateKey); - state->trustLevel = XSecurityClientTrusted; - state->haveState = TRUE; -} - -/* - * Looks up a request name - */ -static _X_INLINE const char * -SecurityLookupRequestName(ClientPtr client) -{ - int major = ((xReq *)client->requestBuffer)->reqType; - int minor = MinorOpcodeOfRequest(client); - return LookupRequestName(major, minor); -} - - -#define rClient(obj) (clients[CLIENT_ID((obj)->resource)]) - -/* SecurityDeleteAuthorization - * - * Arguments: - * value is the authorization to delete. - * id is its resource ID. - * - * Returns: Success. - * - * Side Effects: - * Frees everything associated with the authorization. - */ - -static int -SecurityDeleteAuthorization( - pointer value, - XID id) -{ - SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value; - unsigned short name_len, data_len; - char *name, *data; - int status; - int i; - OtherClientsPtr pEventClient; - - /* Remove the auth using the os layer auth manager */ - - status = AuthorizationFromID(pAuth->id, &name_len, &name, - &data_len, &data); - assert(status); - status = RemoveAuthorization(name_len, name, data_len, data); - assert(status); - (void)status; - - /* free the auth timer if there is one */ - - if (pAuth->timer) TimerFree(pAuth->timer); - - /* send revoke events */ - - while ((pEventClient = pAuth->eventClients)) - { - /* send revocation event event */ - ClientPtr client = rClient(pEventClient); - - if (!client->clientGone) - { - xSecurityAuthorizationRevokedEvent are; - are.type = SecurityEventBase + XSecurityAuthorizationRevoked; - are.sequenceNumber = client->sequence; - are.authId = pAuth->id; - WriteEventsToClient(client, 1, (xEvent *)&are); - } - FreeResource(pEventClient->resource, RT_NONE); - } - - /* kill all clients using this auth */ - - for (i = 1; i<currentMaxClients; i++) - if (clients[i]) { - SecurityStateRec *state; - state = dixLookupPrivate(&clients[i]->devPrivates, stateKey); - if (state->haveState && state->authId == pAuth->id) - CloseDownClient(clients[i]); - } - - SecurityAudit("revoked authorization ID %d\n", pAuth->id); - xfree(pAuth); - return Success; - -} /* SecurityDeleteAuthorization */ - - -/* resource delete function for RTEventClient */ -static int -SecurityDeleteAuthorizationEventClient( - pointer value, - XID id) -{ - OtherClientsPtr pEventClient, prev = NULL; - SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value; - - for (pEventClient = pAuth->eventClients; - pEventClient; - pEventClient = pEventClient->next) - { - if (pEventClient->resource == id) - { - if (prev) - prev->next = pEventClient->next; - else - pAuth->eventClients = pEventClient->next; - xfree(pEventClient); - return(Success); - } - prev = pEventClient; - } - /*NOTREACHED*/ - return -1; /* make compiler happy */ -} /* SecurityDeleteAuthorizationEventClient */ - - -/* SecurityComputeAuthorizationTimeout - * - * Arguments: - * pAuth is the authorization for which we are computing the timeout - * seconds is the number of seconds we want to wait - * - * Returns: - * the number of milliseconds that the auth timer should be set to - * - * Side Effects: - * Sets pAuth->secondsRemaining to any "overflow" amount of time - * that didn't fit in 32 bits worth of milliseconds - */ - -static CARD32 -SecurityComputeAuthorizationTimeout( - SecurityAuthorizationPtr pAuth, - unsigned int seconds) -{ - /* maxSecs is the number of full seconds that can be expressed in - * 32 bits worth of milliseconds - */ - CARD32 maxSecs = (CARD32)(~0) / (CARD32)MILLI_PER_SECOND; - - if (seconds > maxSecs) - { /* only come here if we want to wait more than 49 days */ - pAuth->secondsRemaining = seconds - maxSecs; - return maxSecs * MILLI_PER_SECOND; - } - else - { /* by far the common case */ - pAuth->secondsRemaining = 0; - return seconds * MILLI_PER_SECOND; - } -} /* SecurityStartAuthorizationTimer */ - -/* SecurityAuthorizationExpired - * - * This function is passed as an argument to TimerSet and gets called from - * the timer manager in the os layer when its time is up. - * - * Arguments: - * timer is the timer for this authorization. - * time is the current time. - * pval is the authorization whose time is up. - * - * Returns: - * A new time delay in milliseconds if the timer should wait some - * more, else zero. - * - * Side Effects: - * Frees the authorization resource if the timeout period is really - * over, otherwise recomputes pAuth->secondsRemaining. - */ - -static CARD32 -SecurityAuthorizationExpired( - OsTimerPtr timer, - CARD32 time, - pointer pval) -{ - SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)pval; - - assert(pAuth->timer == timer); - - if (pAuth->secondsRemaining) - { - return SecurityComputeAuthorizationTimeout(pAuth, - pAuth->secondsRemaining); - } - else - { - FreeResource(pAuth->id, RT_NONE); - return 0; - } -} /* SecurityAuthorizationExpired */ - -/* SecurityStartAuthorizationTimer - * - * Arguments: - * pAuth is the authorization whose timer should be started. - * - * Returns: nothing. - * - * Side Effects: - * A timer is started, set to expire after the timeout period for - * this authorization. When it expires, the function - * SecurityAuthorizationExpired will be called. - */ - -static void -SecurityStartAuthorizationTimer( - SecurityAuthorizationPtr pAuth) -{ - pAuth->timer = TimerSet(pAuth->timer, 0, - SecurityComputeAuthorizationTimeout(pAuth, pAuth->timeout), - SecurityAuthorizationExpired, pAuth); -} /* SecurityStartAuthorizationTimer */ - - -/* Proc functions all take a client argument, execute the request in - * client->requestBuffer, and return a protocol error status. - */ - -static int -ProcSecurityQueryVersion( - ClientPtr client) -{ - /* REQUEST(xSecurityQueryVersionReq); */ - xSecurityQueryVersionReply rep; - - REQUEST_SIZE_MATCH(xSecurityQueryVersionReq); - rep.type = X_Reply; - rep.sequenceNumber = client->sequence; - rep.length = 0; - rep.majorVersion = SERVER_SECURITY_MAJOR_VERSION; - rep.minorVersion = SERVER_SECURITY_MINOR_VERSION; - if(client->swapped) - { - char n; - swaps(&rep.sequenceNumber, n); - swaps(&rep.majorVersion, n); - swaps(&rep.minorVersion, n); - } - (void)WriteToClient(client, SIZEOF(xSecurityQueryVersionReply), - (char *)&rep); - return (client->noClientException); -} /* ProcSecurityQueryVersion */ - - -static int -SecurityEventSelectForAuthorization( - SecurityAuthorizationPtr pAuth, - ClientPtr client, - Mask mask) -{ - OtherClients *pEventClient; - - for (pEventClient = pAuth->eventClients; - pEventClient; - pEventClient = pEventClient->next) - { - if (SameClient(pEventClient, client)) - { - if (mask == 0) - FreeResource(pEventClient->resource, RT_NONE); - else - pEventClient->mask = mask; - return Success; - } - } - - pEventClient = xalloc(sizeof(OtherClients)); - if (!pEventClient) - return BadAlloc; - pEventClient->mask = mask; - pEventClient->resource = FakeClientID(client->index); - pEventClient->next = pAuth->eventClients; - if (!AddResource(pEventClient->resource, RTEventClient, - (pointer)pAuth)) - { - xfree(pEventClient); - return BadAlloc; - } - pAuth->eventClients = pEventClient; - - return Success; -} /* SecurityEventSelectForAuthorization */ - - -static int -ProcSecurityGenerateAuthorization( - ClientPtr client) -{ - REQUEST(xSecurityGenerateAuthorizationReq); - int len; /* request length in CARD32s*/ - Bool removeAuth = FALSE; /* if bailout, call RemoveAuthorization? */ - SecurityAuthorizationPtr pAuth = NULL; /* auth we are creating */ - int err; /* error to return from this function */ - XID authId; /* authorization ID assigned by os layer */ - xSecurityGenerateAuthorizationReply rep; /* reply struct */ - unsigned int trustLevel; /* trust level of new auth */ - XID group; /* group of new auth */ - CARD32 timeout; /* timeout of new auth */ - CARD32 *values; /* list of supplied attributes */ - char *protoname; /* auth proto name sent in request */ - char *protodata; /* auth proto data sent in request */ - unsigned int authdata_len; /* # bytes of generated auth data */ - char *pAuthdata; /* generated auth data */ - Mask eventMask; /* what events on this auth does client want */ - - /* check request length */ - - REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq); - len = bytes_to_int32(SIZEOF(xSecurityGenerateAuthorizationReq)); - len += bytes_to_int32(stuff->nbytesAuthProto); - len += bytes_to_int32(stuff->nbytesAuthData); - values = ((CARD32 *)stuff) + len; - len += Ones(stuff->valueMask); - if (client->req_len != len) - return BadLength; - - /* check valuemask */ - if (stuff->valueMask & ~XSecurityAllAuthorizationAttributes) - { - client->errorValue = stuff->valueMask; - return BadValue; - } - - /* check timeout */ - timeout = 60; - if (stuff->valueMask & XSecurityTimeout) - { - timeout = *values++; - } - - /* check trustLevel */ - trustLevel = XSecurityClientUntrusted; - if (stuff->valueMask & XSecurityTrustLevel) - { - trustLevel = *values++; - if (trustLevel != XSecurityClientTrusted && - trustLevel != XSecurityClientUntrusted) - { - client->errorValue = trustLevel; - return BadValue; - } - } - - /* check group */ - group = None; - if (stuff->valueMask & XSecurityGroup) - { - group = *values++; - if (SecurityValidateGroupCallback) - { - SecurityValidateGroupInfoRec vgi; - vgi.group = group; - vgi.valid = FALSE; - CallCallbacks(&SecurityValidateGroupCallback, (pointer)&vgi); - - /* if nobody said they recognized it, it's an error */ - - if (!vgi.valid) - { - client->errorValue = group; - return BadValue; - } - } - } - - /* check event mask */ - eventMask = 0; - if (stuff->valueMask & XSecurityEventMask) - { - eventMask = *values++; - if (eventMask & ~XSecurityAllEventMasks) - { - client->errorValue = eventMask; - return BadValue; - } - } - - protoname = (char *)&stuff[1]; - protodata = protoname + bytes_to_int32(stuff->nbytesAuthProto); - - /* call os layer to generate the authorization */ - - authId = GenerateAuthorization(stuff->nbytesAuthProto, protoname, - stuff->nbytesAuthData, protodata, - &authdata_len, &pAuthdata); - if ((XID) ~0L == authId) - { - err = SecurityErrorBase + XSecurityBadAuthorizationProtocol; - goto bailout; - } - - /* now that we've added the auth, remember to remove it if we have to - * abort the request for some reason (like allocation failure) - */ - removeAuth = TRUE; - - /* associate additional information with this auth ID */ - - pAuth = xalloc(sizeof(SecurityAuthorizationRec)); - if (!pAuth) - { - err = BadAlloc; - goto bailout; - } - - /* fill in the auth fields */ - - pAuth->id = authId; - pAuth->timeout = timeout; - pAuth->group = group; - pAuth->trustLevel = trustLevel; - pAuth->refcnt = 0; /* the auth was just created; nobody's using it yet */ - pAuth->secondsRemaining = 0; - pAuth->timer = NULL; - pAuth->eventClients = NULL; - - /* handle event selection */ - if (eventMask) - { - err = SecurityEventSelectForAuthorization(pAuth, client, eventMask); - if (err != Success) - goto bailout; - } - - if (!AddResource(authId, SecurityAuthorizationResType, pAuth)) - { - err = BadAlloc; - goto bailout; - } - - /* start the timer ticking */ - - if (pAuth->timeout != 0) - SecurityStartAuthorizationTimer(pAuth); - - /* tell client the auth id and data */ - - rep.type = X_Reply; - rep.length = bytes_to_int32(authdata_len); - rep.sequenceNumber = client->sequence; - rep.authId = authId; - rep.dataLength = authdata_len; - - if (client->swapped) - { - char n; - swapl(&rep.length, n); - swaps(&rep.sequenceNumber, n); - swapl(&rep.authId, n); - swaps(&rep.dataLength, n); - } - - WriteToClient(client, SIZEOF(xSecurityGenerateAuthorizationReply), - (char *)&rep); - WriteToClient(client, authdata_len, pAuthdata); - - SecurityAudit("client %d generated authorization %d trust %d timeout %d group %d events %d\n", - client->index, pAuth->id, pAuth->trustLevel, pAuth->timeout, - pAuth->group, eventMask); - - /* the request succeeded; don't call RemoveAuthorization or free pAuth */ - - removeAuth = FALSE; - pAuth = NULL; - err = client->noClientException; - -bailout: - if (removeAuth) - RemoveAuthorization(stuff->nbytesAuthProto, protoname, - authdata_len, pAuthdata); - if (pAuth) xfree(pAuth); - return err; - -} /* ProcSecurityGenerateAuthorization */ - -static int -ProcSecurityRevokeAuthorization( - ClientPtr client) -{ - REQUEST(xSecurityRevokeAuthorizationReq); - SecurityAuthorizationPtr pAuth; - int rc; - - REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq); - - rc = dixLookupResourceByType((pointer *)&pAuth, stuff->authId, - SecurityAuthorizationResType, client, - DixDestroyAccess); - if (rc != Success) - return (rc == BadValue) ? - SecurityErrorBase + XSecurityBadAuthorization : rc; - - FreeResource(stuff->authId, RT_NONE); - return Success; -} /* ProcSecurityRevokeAuthorization */ - - -static int -ProcSecurityDispatch( - ClientPtr client) -{ - REQUEST(xReq); - - switch (stuff->data) - { - case X_SecurityQueryVersion: - return ProcSecurityQueryVersion(client); - case X_SecurityGenerateAuthorization: - return ProcSecurityGenerateAuthorization(client); - case X_SecurityRevokeAuthorization: - return ProcSecurityRevokeAuthorization(client); - default: - return BadRequest; - } -} /* ProcSecurityDispatch */ - -static int -SProcSecurityQueryVersion( - ClientPtr client) -{ - REQUEST(xSecurityQueryVersionReq); - char n; - - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xSecurityQueryVersionReq); - swaps(&stuff->majorVersion, n); - swaps(&stuff->minorVersion,n); - return ProcSecurityQueryVersion(client); -} /* SProcSecurityQueryVersion */ - - -static int -SProcSecurityGenerateAuthorization( - ClientPtr client) -{ - REQUEST(xSecurityGenerateAuthorizationReq); - char n; - CARD32 *values; - unsigned long nvalues; - int values_offset; - - swaps(&stuff->length, n); - REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq); - swaps(&stuff->nbytesAuthProto, n); - swaps(&stuff->nbytesAuthData, n); - swapl(&stuff->valueMask, n); - values_offset = bytes_to_int32(stuff->nbytesAuthProto) + - bytes_to_int32(stuff->nbytesAuthData); - if (values_offset > - stuff->length - bytes_to_int32(sz_xSecurityGenerateAuthorizationReq)) - return BadLength; - values = (CARD32 *)(&stuff[1]) + values_offset; - nvalues = (((CARD32 *)stuff) + stuff->length) - values; - SwapLongs(values, nvalues); - return ProcSecurityGenerateAuthorization(client); -} /* SProcSecurityGenerateAuthorization */ - - -static int -SProcSecurityRevokeAuthorization( - ClientPtr client) -{ - REQUEST(xSecurityRevokeAuthorizationReq); - char n; - - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq); - swapl(&stuff->authId, n); - return ProcSecurityRevokeAuthorization(client); -} /* SProcSecurityRevokeAuthorization */ - - -static int -SProcSecurityDispatch( - ClientPtr client) -{ - REQUEST(xReq); - - switch (stuff->data) - { - case X_SecurityQueryVersion: - return SProcSecurityQueryVersion(client); - case X_SecurityGenerateAuthorization: - return SProcSecurityGenerateAuthorization(client); - case X_SecurityRevokeAuthorization: - return SProcSecurityRevokeAuthorization(client); - default: - return BadRequest; - } -} /* SProcSecurityDispatch */ - -static void -SwapSecurityAuthorizationRevokedEvent( - xSecurityAuthorizationRevokedEvent *from, - xSecurityAuthorizationRevokedEvent *to) -{ - to->type = from->type; - to->detail = from->detail; - cpswaps(from->sequenceNumber, to->sequenceNumber); - cpswapl(from->authId, to->authId); -} - -/* SecurityCheckDeviceAccess - * - * Arguments: - * client is the client attempting to access a device. - * dev is the device being accessed. - * fromRequest is TRUE if the device access is a direct result of - * the client executing some request and FALSE if it is a - * result of the server trying to send an event (e.g. KeymapNotify) - * to the client. - * Returns: - * TRUE if the device access should be allowed, else FALSE. - * - * Side Effects: - * An audit message is generated if access is denied. - */ - -static void -SecurityDevice(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceDeviceAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - Mask requested = rec->access_mode; - Mask allowed = SecurityDeviceMask; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&serverClient->devPrivates, stateKey); - - if (rec->dev != inputInfo.keyboard) - /* this extension only supports the core keyboard */ - allowed = requested; - - if (SecurityDoCheck(subj, obj, requested, allowed) != Success) { - SecurityAudit("Security denied client %d keyboard access on request " - "%s\n", rec->client->index, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; - } -} - -/* SecurityResource - * - * This function gets plugged into client->CheckAccess and is called from - * SecurityLookupIDByType/Class to determine if the client can access the - * resource. - * - * Arguments: - * client is the client doing the resource access. - * id is the resource id. - * rtype is its type or class. - * access_mode represents the intended use of the resource; see - * resource.h. - * res is a pointer to the resource structure for this resource. - * - * Returns: - * If access is granted, the value of rval that was passed in, else FALSE. - * - * Side Effects: - * Disallowed resource accesses are audited. - */ - -static void -SecurityResource(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceResourceAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - int cid = CLIENT_ID(rec->id); - Mask requested = rec->access_mode; - Mask allowed = SecurityResourceMask; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&clients[cid]->devPrivates, stateKey); - - /* disable background None for untrusted windows */ - if ((requested & DixCreateAccess) && (rec->rtype == RT_WINDOW)) - if (subj->haveState && subj->trustLevel != XSecurityClientTrusted) - ((WindowPtr)rec->res)->forcedBG = TRUE; - - /* additional permissions for specific resource types */ - if (rec->rtype == RT_WINDOW) - allowed |= SecurityWindowExtraMask; - - /* special checks for server-owned resources */ - if (cid == 0) { - if (rec->rtype & RC_DRAWABLE) - /* additional operations allowed on root windows */ - allowed |= SecurityRootWindowExtraMask; - - else if (rec->rtype == RT_COLORMAP) - /* allow access to default colormaps */ - allowed = requested; - - else - /* allow read access to other server-owned resources */ - allowed |= DixReadAccess; - } - - if (SecurityDoCheck(subj, obj, requested, allowed) == Success) - return; - - SecurityAudit("Security: denied client %d access %x to resource 0x%x " - "of client %d on request %s\n", rec->client->index, - requested, rec->id, cid, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; /* deny access */ -} - - -static void -SecurityExtension(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceExtAccessRec *rec = calldata; - SecurityStateRec *subj; - int i = 0; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - - if (subj->haveState && subj->trustLevel == XSecurityClientTrusted) - return; - - while (SecurityTrustedExtensions[i]) - if (!strcmp(SecurityTrustedExtensions[i++], rec->ext->name)) - return; - - SecurityAudit("Security: denied client %d access to extension " - "%s on request %s\n", - rec->client->index, rec->ext->name, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; -} - -static void -SecurityServer(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceServerAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - Mask requested = rec->access_mode; - Mask allowed = SecurityServerMask; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&serverClient->devPrivates, stateKey); - - if (SecurityDoCheck(subj, obj, requested, allowed) != Success) { - SecurityAudit("Security: denied client %d access to server " - "configuration request %s\n", rec->client->index, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; - } -} - -static void -SecurityClient(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceClientAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - Mask requested = rec->access_mode; - Mask allowed = SecurityClientMask; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&rec->target->devPrivates, stateKey); - - if (SecurityDoCheck(subj, obj, requested, allowed) != Success) { - SecurityAudit("Security: denied client %d access to client %d on " - "request %s\n", rec->client->index, rec->target->index, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; - } -} - -static void -SecurityProperty(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XacePropertyAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - ATOM name = (*rec->ppProp)->propertyName; - Mask requested = rec->access_mode; - Mask allowed = SecurityResourceMask | DixReadAccess; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey); - - if (SecurityDoCheck(subj, obj, requested, allowed) != Success) { - SecurityAudit("Security: denied client %d access to property %s " - "(atom 0x%x) window 0x%x of client %d on request %s\n", - rec->client->index, NameForAtom(name), name, - rec->pWin->drawable.id, wClient(rec->pWin)->index, - SecurityLookupRequestName(rec->client)); - rec->status = BadAccess; - } -} - -static void -SecuritySend(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceSendAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - - if (rec->client) { - int i; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey); - - if (SecurityDoCheck(subj, obj, DixSendAccess, 0) == Success) - return; - - for (i = 0; i < rec->count; i++) - if (rec->events[i].u.u.type != UnmapNotify && - rec->events[i].u.u.type != ConfigureRequest && - rec->events[i].u.u.type != ClientMessage) { - - SecurityAudit("Security: denied client %d from sending event " - "of type %s to window 0x%x of client %d\n", - rec->client->index, - LookupEventName(rec->events[i].u.u.type), - rec->pWin->drawable.id, - wClient(rec->pWin)->index); - rec->status = BadAccess; - return; - } - } -} - -static void -SecurityReceive(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - XaceReceiveAccessRec *rec = calldata; - SecurityStateRec *subj, *obj; - - subj = dixLookupPrivate(&rec->client->devPrivates, stateKey); - obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey); - - if (SecurityDoCheck(subj, obj, DixReceiveAccess, 0) == Success) - return; - - SecurityAudit("Security: denied client %d from receiving an event " - "sent to window 0x%x of client %d\n", - rec->client->index, rec->pWin->drawable.id, - wClient(rec->pWin)->index); - rec->status = BadAccess; -} - -/* SecurityClientStateCallback - * - * Arguments: - * pcbl is &ClientStateCallback. - * nullata is NULL. - * calldata is a pointer to a NewClientInfoRec (include/dixstruct.h) - * which contains information about client state changes. - * - * Returns: nothing. - * - * Side Effects: - * - * If a new client is connecting, its authorization ID is copied to - * client->authID. If this is a generated authorization, its reference - * count is bumped, its timer is cancelled if it was running, and its - * trustlevel is copied to TRUSTLEVEL(client). - * - * If a client is disconnecting and the client was using a generated - * authorization, the authorization's reference count is decremented, and - * if it is now zero, the timer for this authorization is started. - */ - -static void -SecurityClientState(CallbackListPtr *pcbl, pointer unused, pointer calldata) -{ - NewClientInfoRec *pci = calldata; - SecurityStateRec *state; - SecurityAuthorizationPtr pAuth; - int rc; - - state = dixLookupPrivate(&pci->client->devPrivates, stateKey); - - switch (pci->client->clientState) { - case ClientStateInitial: - state->trustLevel = XSecurityClientTrusted; - state->authId = None; - state->haveState = TRUE; - break; - - case ClientStateRunning: - state->authId = AuthorizationIDOfClient(pci->client); - rc = dixLookupResourceByType((pointer *)&pAuth, state->authId, - SecurityAuthorizationResType, serverClient, - DixGetAttrAccess); - if (rc == Success) { - /* it is a generated authorization */ - pAuth->refcnt++; - if (pAuth->refcnt == 1 && pAuth->timer) - TimerCancel(pAuth->timer); - - state->trustLevel = pAuth->trustLevel; - } - break; - - case ClientStateGone: - case ClientStateRetained: - rc = dixLookupResourceByType((pointer *)&pAuth, state->authId, - SecurityAuthorizationResType, serverClient, - DixGetAttrAccess); - if (rc == Success) { - /* it is a generated authorization */ - pAuth->refcnt--; - if (pAuth->refcnt == 0) - SecurityStartAuthorizationTimer(pAuth); - } - break; - - default: - break; - } -} - -/* SecurityResetProc - * - * Arguments: - * extEntry is the extension information for the security extension. - * - * Returns: nothing. - * - * Side Effects: - * Performs any cleanup needed by Security at server shutdown time. - */ - -static void -SecurityResetProc( - ExtensionEntry *extEntry) -{ - /* Unregister callbacks */ - DeleteCallback(&ClientStateCallback, SecurityClientState, NULL); - - XaceDeleteCallback(XACE_EXT_DISPATCH, SecurityExtension, NULL); - XaceDeleteCallback(XACE_RESOURCE_ACCESS, SecurityResource, NULL); - XaceDeleteCallback(XACE_DEVICE_ACCESS, SecurityDevice, NULL); - XaceDeleteCallback(XACE_PROPERTY_ACCESS, SecurityProperty, NULL); - XaceDeleteCallback(XACE_SEND_ACCESS, SecuritySend, NULL); - XaceDeleteCallback(XACE_RECEIVE_ACCESS, SecurityReceive, NULL); - XaceDeleteCallback(XACE_CLIENT_ACCESS, SecurityClient, NULL); - XaceDeleteCallback(XACE_EXT_ACCESS, SecurityExtension, NULL); - XaceDeleteCallback(XACE_SERVER_ACCESS, SecurityServer, NULL); -} - - -/* SecurityExtensionInit - * - * Arguments: none. - * - * Returns: nothing. - * - * Side Effects: - * Enables the Security extension if possible. - */ - -void -SecurityExtensionInit(INITARGS) -{ - ExtensionEntry *extEntry; - int ret = TRUE; - - SecurityAuthorizationResType = - CreateNewResourceType(SecurityDeleteAuthorization); - - RTEventClient = CreateNewResourceType( - SecurityDeleteAuthorizationEventClient); - - if (!SecurityAuthorizationResType || !RTEventClient) - return; - - RTEventClient |= RC_NEVERRETAIN; - RegisterResourceName(SecurityAuthorizationResType, "SecurityAuthorization"); - RegisterResourceName(RTEventClient, "SecurityEventClient"); - - /* Allocate the private storage */ - if (!dixRequestPrivate(stateKey, sizeof(SecurityStateRec))) - FatalError("SecurityExtensionSetup: Can't allocate client private.\n"); - - /* Register callbacks */ - ret &= AddCallback(&ClientStateCallback, SecurityClientState, NULL); - - ret &= XaceRegisterCallback(XACE_EXT_DISPATCH, SecurityExtension, NULL); - ret &= XaceRegisterCallback(XACE_RESOURCE_ACCESS, SecurityResource, NULL); - ret &= XaceRegisterCallback(XACE_DEVICE_ACCESS, SecurityDevice, NULL); - ret &= XaceRegisterCallback(XACE_PROPERTY_ACCESS, SecurityProperty, NULL); - ret &= XaceRegisterCallback(XACE_SEND_ACCESS, SecuritySend, NULL); - ret &= XaceRegisterCallback(XACE_RECEIVE_ACCESS, SecurityReceive, NULL); - ret &= XaceRegisterCallback(XACE_CLIENT_ACCESS, SecurityClient, NULL); - ret &= XaceRegisterCallback(XACE_EXT_ACCESS, SecurityExtension, NULL); - ret &= XaceRegisterCallback(XACE_SERVER_ACCESS, SecurityServer, NULL); - - if (!ret) - FatalError("SecurityExtensionSetup: Failed to register callbacks\n"); - - /* Add extension to server */ - extEntry = AddExtension(SECURITY_EXTENSION_NAME, - XSecurityNumberEvents, XSecurityNumberErrors, - ProcSecurityDispatch, SProcSecurityDispatch, - SecurityResetProc, StandardMinorOpcode); - - SecurityErrorBase = extEntry->errorBase; - SecurityEventBase = extEntry->eventBase; - - EventSwapVector[SecurityEventBase + XSecurityAuthorizationRevoked] = - (EventSwapPtr)SwapSecurityAuthorizationRevokedEvent; - - /* Label objects that were created before we could register ourself */ - SecurityLabelInitial(); -} +/*
+
+Copyright 1996, 1998 The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+*/
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+#define XACE
+#endif
+
+#include "scrnintstr.h"
+#include "inputstr.h"
+#include "windowstr.h"
+#include "propertyst.h"
+#include "colormapst.h"
+#include "privates.h"
+#include "registry.h"
+#include "xacestr.h"
+#include "securitysrv.h"
+#include <X11/extensions/securproto.h>
+#include "modinit.h"
+#include "protocol-versions.h"
+
+/* Extension stuff */
+static int SecurityErrorBase; /* first Security error number */
+static int SecurityEventBase; /* first Security event number */
+
+RESTYPE SecurityAuthorizationResType; /* resource type for authorizations */
+static RESTYPE RTEventClient;
+
+static CallbackListPtr SecurityValidateGroupCallback = NULL;
+
+/* Private state record */
+static int stateKeyIndex;
+static DevPrivateKey stateKey = &stateKeyIndex;
+
+/* This is what we store as client security state */
+typedef struct {
+ int haveState;
+ unsigned int trustLevel;
+ XID authId;
+} SecurityStateRec;
+
+/* Extensions that untrusted clients shouldn't have access to */
+static char *SecurityTrustedExtensions[] = {
+ "XC-MISC",
+ "BIG-REQUESTS",
+ "XpExtension",
+ NULL
+};
+
+/*
+ * Access modes that untrusted clients are allowed on trusted objects.
+ */
+static const Mask SecurityResourceMask =
+ DixGetAttrAccess | DixReceiveAccess | DixListPropAccess |
+ DixGetPropAccess | DixListAccess;
+static const Mask SecurityWindowExtraMask = DixRemoveAccess;
+static const Mask SecurityRootWindowExtraMask =
+ DixReceiveAccess | DixSendAccess | DixAddAccess | DixRemoveAccess;
+static const Mask SecurityDeviceMask =
+ DixGetAttrAccess | DixReceiveAccess | DixGetFocusAccess |
+ DixGrabAccess | DixSetAttrAccess | DixUseAccess;
+static const Mask SecurityServerMask = DixGetAttrAccess | DixGrabAccess;
+static const Mask SecurityClientMask = DixGetAttrAccess;
+
+
+/* SecurityAudit
+ *
+ * Arguments:
+ * format is the formatting string to be used to interpret the
+ * remaining arguments.
+ *
+ * Returns: nothing.
+ *
+ * Side Effects:
+ * Writes the message to the log file if security logging is on.
+ */
+
+static void
+SecurityAudit(char *format, ...)
+{
+ va_list args;
+
+ if (auditTrailLevel < SECURITY_AUDIT_LEVEL)
+ return;
+ va_start(args, format);
+ VAuditF(format, args);
+ va_end(args);
+} /* SecurityAudit */
+
+/*
+ * Performs a Security permission check.
+ */
+static int
+SecurityDoCheck(SecurityStateRec *subj, SecurityStateRec *obj,
+ Mask requested, Mask allowed)
+{
+ if (!subj->haveState || !obj->haveState)
+ return Success;
+ if (subj->trustLevel == XSecurityClientTrusted)
+ return Success;
+ if (obj->trustLevel != XSecurityClientTrusted)
+ return Success;
+ if ((requested | allowed) == allowed)
+ return Success;
+
+ return BadAccess;
+}
+
+/*
+ * Labels initial server objects.
+ */
+static void
+SecurityLabelInitial(void)
+{
+ SecurityStateRec *state;
+
+ /* Do the serverClient */
+ state = dixLookupPrivate(&serverClient->devPrivates, stateKey);
+ state->trustLevel = XSecurityClientTrusted;
+ state->haveState = TRUE;
+}
+
+/*
+ * Looks up a request name
+ */
+static _X_INLINE const char *
+SecurityLookupRequestName(ClientPtr client)
+{
+ int major = ((xReq *)client->requestBuffer)->reqType;
+ int minor = MinorOpcodeOfRequest(client);
+ return LookupRequestName(major, minor);
+}
+
+
+#define rClient(obj) (clients[CLIENT_ID((obj)->resource)])
+
+/* SecurityDeleteAuthorization
+ *
+ * Arguments:
+ * value is the authorization to delete.
+ * id is its resource ID.
+ *
+ * Returns: Success.
+ *
+ * Side Effects:
+ * Frees everything associated with the authorization.
+ */
+
+static int
+SecurityDeleteAuthorization(
+ pointer value,
+ XID id)
+{
+ SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value;
+ unsigned short name_len, data_len;
+ char *name, *data;
+ int status;
+ int i;
+ OtherClientsPtr pEventClient;
+
+ /* Remove the auth using the os layer auth manager */
+
+ status = AuthorizationFromID(pAuth->id, &name_len, &name,
+ &data_len, &data);
+ assert(status);
+ status = RemoveAuthorization(name_len, name, data_len, data);
+ assert(status);
+ (void)status;
+
+ /* free the auth timer if there is one */
+
+ if (pAuth->timer) TimerFree(pAuth->timer);
+
+ /* send revoke events */
+
+ while ((pEventClient = pAuth->eventClients))
+ {
+ /* send revocation event event */
+ ClientPtr client = rClient(pEventClient);
+
+ if (!client->clientGone)
+ {
+ xSecurityAuthorizationRevokedEvent are;
+ are.type = SecurityEventBase + XSecurityAuthorizationRevoked;
+ are.sequenceNumber = client->sequence;
+ are.authId = pAuth->id;
+ WriteEventsToClient(client, 1, (xEvent *)&are);
+ }
+ FreeResource(pEventClient->resource, RT_NONE);
+ }
+
+ /* kill all clients using this auth */
+
+ for (i = 1; i<currentMaxClients; i++)
+ if (clients[i]) {
+ SecurityStateRec *state;
+ state = dixLookupPrivate(&clients[i]->devPrivates, stateKey);
+ if (state->haveState && state->authId == pAuth->id)
+ CloseDownClient(clients[i]);
+ }
+
+ SecurityAudit("revoked authorization ID %d\n", pAuth->id);
+ xfree(pAuth);
+ return Success;
+
+} /* SecurityDeleteAuthorization */
+
+
+/* resource delete function for RTEventClient */
+static int
+SecurityDeleteAuthorizationEventClient(
+ pointer value,
+ XID id)
+{
+ OtherClientsPtr pEventClient, prev = NULL;
+ SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)value;
+
+ for (pEventClient = pAuth->eventClients;
+ pEventClient;
+ pEventClient = pEventClient->next)
+ {
+ if (pEventClient->resource == id)
+ {
+ if (prev)
+ prev->next = pEventClient->next;
+ else
+ pAuth->eventClients = pEventClient->next;
+ xfree(pEventClient);
+ return(Success);
+ }
+ prev = pEventClient;
+ }
+ /*NOTREACHED*/
+ return -1; /* make compiler happy */
+} /* SecurityDeleteAuthorizationEventClient */
+
+
+/* SecurityComputeAuthorizationTimeout
+ *
+ * Arguments:
+ * pAuth is the authorization for which we are computing the timeout
+ * seconds is the number of seconds we want to wait
+ *
+ * Returns:
+ * the number of milliseconds that the auth timer should be set to
+ *
+ * Side Effects:
+ * Sets pAuth->secondsRemaining to any "overflow" amount of time
+ * that didn't fit in 32 bits worth of milliseconds
+ */
+
+static CARD32
+SecurityComputeAuthorizationTimeout(
+ SecurityAuthorizationPtr pAuth,
+ unsigned int seconds)
+{
+ /* maxSecs is the number of full seconds that can be expressed in
+ * 32 bits worth of milliseconds
+ */
+ CARD32 maxSecs = (CARD32)(~0) / (CARD32)MILLI_PER_SECOND;
+
+ if (seconds > maxSecs)
+ { /* only come here if we want to wait more than 49 days */
+ pAuth->secondsRemaining = seconds - maxSecs;
+ return maxSecs * MILLI_PER_SECOND;
+ }
+ else
+ { /* by far the common case */
+ pAuth->secondsRemaining = 0;
+ return seconds * MILLI_PER_SECOND;
+ }
+} /* SecurityStartAuthorizationTimer */
+
+/* SecurityAuthorizationExpired
+ *
+ * This function is passed as an argument to TimerSet and gets called from
+ * the timer manager in the os layer when its time is up.
+ *
+ * Arguments:
+ * timer is the timer for this authorization.
+ * time is the current time.
+ * pval is the authorization whose time is up.
+ *
+ * Returns:
+ * A new time delay in milliseconds if the timer should wait some
+ * more, else zero.
+ *
+ * Side Effects:
+ * Frees the authorization resource if the timeout period is really
+ * over, otherwise recomputes pAuth->secondsRemaining.
+ */
+
+static CARD32
+SecurityAuthorizationExpired(
+ OsTimerPtr timer,
+ CARD32 time,
+ pointer pval)
+{
+ SecurityAuthorizationPtr pAuth = (SecurityAuthorizationPtr)pval;
+
+ assert(pAuth->timer == timer);
+
+ if (pAuth->secondsRemaining)
+ {
+ return SecurityComputeAuthorizationTimeout(pAuth,
+ pAuth->secondsRemaining);
+ }
+ else
+ {
+ FreeResource(pAuth->id, RT_NONE);
+ return 0;
+ }
+} /* SecurityAuthorizationExpired */
+
+/* SecurityStartAuthorizationTimer
+ *
+ * Arguments:
+ * pAuth is the authorization whose timer should be started.
+ *
+ * Returns: nothing.
+ *
+ * Side Effects:
+ * A timer is started, set to expire after the timeout period for
+ * this authorization. When it expires, the function
+ * SecurityAuthorizationExpired will be called.
+ */
+
+static void
+SecurityStartAuthorizationTimer(
+ SecurityAuthorizationPtr pAuth)
+{
+ pAuth->timer = TimerSet(pAuth->timer, 0,
+ SecurityComputeAuthorizationTimeout(pAuth, pAuth->timeout),
+ SecurityAuthorizationExpired, pAuth);
+} /* SecurityStartAuthorizationTimer */
+
+
+/* Proc functions all take a client argument, execute the request in
+ * client->requestBuffer, and return a protocol error status.
+ */
+
+static int
+ProcSecurityQueryVersion(
+ ClientPtr client)
+{
+ /* REQUEST(xSecurityQueryVersionReq); */
+ xSecurityQueryVersionReply rep;
+
+ REQUEST_SIZE_MATCH(xSecurityQueryVersionReq);
+ rep.type = X_Reply;
+ rep.sequenceNumber = client->sequence;
+ rep.length = 0;
+ rep.majorVersion = SERVER_SECURITY_MAJOR_VERSION;
+ rep.minorVersion = SERVER_SECURITY_MINOR_VERSION;
+ if(client->swapped)
+ {
+ char n;
+ swaps(&rep.sequenceNumber, n);
+ swaps(&rep.majorVersion, n);
+ swaps(&rep.minorVersion, n);
+ }
+ (void)WriteToClient(client, SIZEOF(xSecurityQueryVersionReply),
+ (char *)&rep);
+ return (client->noClientException);
+} /* ProcSecurityQueryVersion */
+
+
+static int
+SecurityEventSelectForAuthorization(
+ SecurityAuthorizationPtr pAuth,
+ ClientPtr client,
+ Mask mask)
+{
+ OtherClients *pEventClient;
+
+ for (pEventClient = pAuth->eventClients;
+ pEventClient;
+ pEventClient = pEventClient->next)
+ {
+ if (SameClient(pEventClient, client))
+ {
+ if (mask == 0)
+ FreeResource(pEventClient->resource, RT_NONE);
+ else
+ pEventClient->mask = mask;
+ return Success;
+ }
+ }
+
+ pEventClient = xalloc(sizeof(OtherClients));
+ if (!pEventClient)
+ return BadAlloc;
+ pEventClient->mask = mask;
+ pEventClient->resource = FakeClientID(client->index);
+ pEventClient->next = pAuth->eventClients;
+ if (!AddResource(pEventClient->resource, RTEventClient,
+ (pointer)pAuth))
+ {
+ xfree(pEventClient);
+ return BadAlloc;
+ }
+ pAuth->eventClients = pEventClient;
+
+ return Success;
+} /* SecurityEventSelectForAuthorization */
+
+
+static int
+ProcSecurityGenerateAuthorization(
+ ClientPtr client)
+{
+ REQUEST(xSecurityGenerateAuthorizationReq);
+ int len; /* request length in CARD32s*/
+ Bool removeAuth = FALSE; /* if bailout, call RemoveAuthorization? */
+ SecurityAuthorizationPtr pAuth = NULL; /* auth we are creating */
+ int err; /* error to return from this function */
+ XID authId; /* authorization ID assigned by os layer */
+ xSecurityGenerateAuthorizationReply rep; /* reply struct */
+ unsigned int trustLevel; /* trust level of new auth */
+ XID group; /* group of new auth */
+ CARD32 timeout; /* timeout of new auth */
+ CARD32 *values; /* list of supplied attributes */
+ char *protoname; /* auth proto name sent in request */
+ char *protodata; /* auth proto data sent in request */
+ unsigned int authdata_len; /* # bytes of generated auth data */
+ char *pAuthdata; /* generated auth data */
+ Mask eventMask; /* what events on this auth does client want */
+
+ /* check request length */
+
+ REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq);
+ len = bytes_to_int32(SIZEOF(xSecurityGenerateAuthorizationReq));
+ len += bytes_to_int32(stuff->nbytesAuthProto);
+ len += bytes_to_int32(stuff->nbytesAuthData);
+ values = ((CARD32 *)stuff) + len;
+ len += Ones(stuff->valueMask);
+ if (client->req_len != len)
+ return BadLength;
+
+ /* check valuemask */
+ if (stuff->valueMask & ~XSecurityAllAuthorizationAttributes)
+ {
+ client->errorValue = stuff->valueMask;
+ return BadValue;
+ }
+
+ /* check timeout */
+ timeout = 60;
+ if (stuff->valueMask & XSecurityTimeout)
+ {
+ timeout = *values++;
+ }
+
+ /* check trustLevel */
+ trustLevel = XSecurityClientUntrusted;
+ if (stuff->valueMask & XSecurityTrustLevel)
+ {
+ trustLevel = *values++;
+ if (trustLevel != XSecurityClientTrusted &&
+ trustLevel != XSecurityClientUntrusted)
+ {
+ client->errorValue = trustLevel;
+ return BadValue;
+ }
+ }
+
+ /* check group */
+ group = None;
+ if (stuff->valueMask & XSecurityGroup)
+ {
+ group = *values++;
+ if (SecurityValidateGroupCallback)
+ {
+ SecurityValidateGroupInfoRec vgi;
+ vgi.group = group;
+ vgi.valid = FALSE;
+ CallCallbacks(&SecurityValidateGroupCallback, (pointer)&vgi);
+
+ /* if nobody said they recognized it, it's an error */
+
+ if (!vgi.valid)
+ {
+ client->errorValue = group;
+ return BadValue;
+ }
+ }
+ }
+
+ /* check event mask */
+ eventMask = 0;
+ if (stuff->valueMask & XSecurityEventMask)
+ {
+ eventMask = *values++;
+ if (eventMask & ~XSecurityAllEventMasks)
+ {
+ client->errorValue = eventMask;
+ return BadValue;
+ }
+ }
+
+ protoname = (char *)&stuff[1];
+ protodata = protoname + bytes_to_int32(stuff->nbytesAuthProto);
+
+ /* call os layer to generate the authorization */
+
+ authId = GenerateAuthorization(stuff->nbytesAuthProto, protoname,
+ stuff->nbytesAuthData, protodata,
+ &authdata_len, &pAuthdata);
+ if ((XID) ~0L == authId)
+ {
+ err = SecurityErrorBase + XSecurityBadAuthorizationProtocol;
+ goto bailout;
+ }
+
+ /* now that we've added the auth, remember to remove it if we have to
+ * abort the request for some reason (like allocation failure)
+ */
+ removeAuth = TRUE;
+
+ /* associate additional information with this auth ID */
+
+ pAuth = xalloc(sizeof(SecurityAuthorizationRec));
+ if (!pAuth)
+ {
+ err = BadAlloc;
+ goto bailout;
+ }
+
+ /* fill in the auth fields */
+
+ pAuth->id = authId;
+ pAuth->timeout = timeout;
+ pAuth->group = group;
+ pAuth->trustLevel = trustLevel;
+ pAuth->refcnt = 0; /* the auth was just created; nobody's using it yet */
+ pAuth->secondsRemaining = 0;
+ pAuth->timer = NULL;
+ pAuth->eventClients = NULL;
+
+ /* handle event selection */
+ if (eventMask)
+ {
+ err = SecurityEventSelectForAuthorization(pAuth, client, eventMask);
+ if (err != Success)
+ goto bailout;
+ }
+
+ if (!AddResource(authId, SecurityAuthorizationResType, pAuth))
+ {
+ err = BadAlloc;
+ goto bailout;
+ }
+
+ /* start the timer ticking */
+
+ if (pAuth->timeout != 0)
+ SecurityStartAuthorizationTimer(pAuth);
+
+ /* tell client the auth id and data */
+
+ rep.type = X_Reply;
+ rep.length = bytes_to_int32(authdata_len);
+ rep.sequenceNumber = client->sequence;
+ rep.authId = authId;
+ rep.dataLength = authdata_len;
+
+ if (client->swapped)
+ {
+ char n;
+ swapl(&rep.length, n);
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.authId, n);
+ swaps(&rep.dataLength, n);
+ }
+
+ WriteToClient(client, SIZEOF(xSecurityGenerateAuthorizationReply),
+ (char *)&rep);
+ WriteToClient(client, authdata_len, pAuthdata);
+
+ SecurityAudit("client %d generated authorization %d trust %d timeout %d group %d events %d\n",
+ client->index, pAuth->id, pAuth->trustLevel, pAuth->timeout,
+ pAuth->group, eventMask);
+
+ /* the request succeeded; don't call RemoveAuthorization or free pAuth */
+
+ removeAuth = FALSE;
+ pAuth = NULL;
+ err = client->noClientException;
+
+bailout:
+ if (removeAuth)
+ RemoveAuthorization(stuff->nbytesAuthProto, protoname,
+ authdata_len, pAuthdata);
+ if (pAuth) xfree(pAuth);
+ return err;
+
+} /* ProcSecurityGenerateAuthorization */
+
+static int
+ProcSecurityRevokeAuthorization(
+ ClientPtr client)
+{
+ REQUEST(xSecurityRevokeAuthorizationReq);
+ SecurityAuthorizationPtr pAuth;
+ int rc;
+
+ REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq);
+
+ rc = dixLookupResourceByType((pointer *)&pAuth, stuff->authId,
+ SecurityAuthorizationResType, client,
+ DixDestroyAccess);
+ if (rc != Success)
+ return (rc == BadValue) ?
+ SecurityErrorBase + XSecurityBadAuthorization : rc;
+
+ FreeResource(stuff->authId, RT_NONE);
+ return Success;
+} /* ProcSecurityRevokeAuthorization */
+
+
+static int
+ProcSecurityDispatch(
+ ClientPtr client)
+{
+ REQUEST(xReq);
+
+ switch (stuff->data)
+ {
+ case X_SecurityQueryVersion:
+ return ProcSecurityQueryVersion(client);
+ case X_SecurityGenerateAuthorization:
+ return ProcSecurityGenerateAuthorization(client);
+ case X_SecurityRevokeAuthorization:
+ return ProcSecurityRevokeAuthorization(client);
+ default:
+ return BadRequest;
+ }
+} /* ProcSecurityDispatch */
+
+static int
+SProcSecurityQueryVersion(
+ ClientPtr client)
+{
+ REQUEST(xSecurityQueryVersionReq);
+ char n;
+
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xSecurityQueryVersionReq);
+ swaps(&stuff->majorVersion, n);
+ swaps(&stuff->minorVersion,n);
+ return ProcSecurityQueryVersion(client);
+} /* SProcSecurityQueryVersion */
+
+
+static int
+SProcSecurityGenerateAuthorization(
+ ClientPtr client)
+{
+ REQUEST(xSecurityGenerateAuthorizationReq);
+ char n;
+ CARD32 *values;
+ unsigned long nvalues;
+ int values_offset;
+
+ swaps(&stuff->length, n);
+ REQUEST_AT_LEAST_SIZE(xSecurityGenerateAuthorizationReq);
+ swaps(&stuff->nbytesAuthProto, n);
+ swaps(&stuff->nbytesAuthData, n);
+ swapl(&stuff->valueMask, n);
+ values_offset = bytes_to_int32(stuff->nbytesAuthProto) +
+ bytes_to_int32(stuff->nbytesAuthData);
+ if (values_offset >
+ stuff->length - bytes_to_int32(sz_xSecurityGenerateAuthorizationReq))
+ return BadLength;
+ values = (CARD32 *)(&stuff[1]) + values_offset;
+ nvalues = (((CARD32 *)stuff) + stuff->length) - values;
+ SwapLongs(values, nvalues);
+ return ProcSecurityGenerateAuthorization(client);
+} /* SProcSecurityGenerateAuthorization */
+
+
+static int
+SProcSecurityRevokeAuthorization(
+ ClientPtr client)
+{
+ REQUEST(xSecurityRevokeAuthorizationReq);
+ char n;
+
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xSecurityRevokeAuthorizationReq);
+ swapl(&stuff->authId, n);
+ return ProcSecurityRevokeAuthorization(client);
+} /* SProcSecurityRevokeAuthorization */
+
+
+static int
+SProcSecurityDispatch(
+ ClientPtr client)
+{
+ REQUEST(xReq);
+
+ switch (stuff->data)
+ {
+ case X_SecurityQueryVersion:
+ return SProcSecurityQueryVersion(client);
+ case X_SecurityGenerateAuthorization:
+ return SProcSecurityGenerateAuthorization(client);
+ case X_SecurityRevokeAuthorization:
+ return SProcSecurityRevokeAuthorization(client);
+ default:
+ return BadRequest;
+ }
+} /* SProcSecurityDispatch */
+
+static void
+SwapSecurityAuthorizationRevokedEvent(
+ xSecurityAuthorizationRevokedEvent *from,
+ xSecurityAuthorizationRevokedEvent *to)
+{
+ to->type = from->type;
+ to->detail = from->detail;
+ cpswaps(from->sequenceNumber, to->sequenceNumber);
+ cpswapl(from->authId, to->authId);
+}
+
+/* SecurityCheckDeviceAccess
+ *
+ * Arguments:
+ * client is the client attempting to access a device.
+ * dev is the device being accessed.
+ * fromRequest is TRUE if the device access is a direct result of
+ * the client executing some request and FALSE if it is a
+ * result of the server trying to send an event (e.g. KeymapNotify)
+ * to the client.
+ * Returns:
+ * TRUE if the device access should be allowed, else FALSE.
+ *
+ * Side Effects:
+ * An audit message is generated if access is denied.
+ */
+
+static void
+SecurityDevice(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceDeviceAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+ Mask requested = rec->access_mode;
+ Mask allowed = SecurityDeviceMask;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&serverClient->devPrivates, stateKey);
+
+ if (rec->dev != inputInfo.keyboard)
+ /* this extension only supports the core keyboard */
+ allowed = requested;
+
+ if (SecurityDoCheck(subj, obj, requested, allowed) != Success) {
+ SecurityAudit("Security denied client %d keyboard access on request "
+ "%s\n", rec->client->index,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess;
+ }
+}
+
+/* SecurityResource
+ *
+ * This function gets plugged into client->CheckAccess and is called from
+ * SecurityLookupIDByType/Class to determine if the client can access the
+ * resource.
+ *
+ * Arguments:
+ * client is the client doing the resource access.
+ * id is the resource id.
+ * rtype is its type or class.
+ * access_mode represents the intended use of the resource; see
+ * resource.h.
+ * res is a pointer to the resource structure for this resource.
+ *
+ * Returns:
+ * If access is granted, the value of rval that was passed in, else FALSE.
+ *
+ * Side Effects:
+ * Disallowed resource accesses are audited.
+ */
+
+static void
+SecurityResource(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceResourceAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+ int cid = CLIENT_ID(rec->id);
+ Mask requested = rec->access_mode;
+ Mask allowed = SecurityResourceMask;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&clients[cid]->devPrivates, stateKey);
+
+ /* disable background None for untrusted windows */
+ if ((requested & DixCreateAccess) && (rec->rtype == RT_WINDOW))
+ if (subj->haveState && subj->trustLevel != XSecurityClientTrusted)
+ ((WindowPtr)rec->res)->forcedBG = TRUE;
+
+ /* additional permissions for specific resource types */
+ if (rec->rtype == RT_WINDOW)
+ allowed |= SecurityWindowExtraMask;
+
+ /* special checks for server-owned resources */
+ if (cid == 0) {
+ if (rec->rtype & RC_DRAWABLE)
+ /* additional operations allowed on root windows */
+ allowed |= SecurityRootWindowExtraMask;
+
+ else if (rec->rtype == RT_COLORMAP)
+ /* allow access to default colormaps */
+ allowed = requested;
+
+ else
+ /* allow read access to other server-owned resources */
+ allowed |= DixReadAccess;
+ }
+
+ if (SecurityDoCheck(subj, obj, requested, allowed) == Success)
+ return;
+
+ SecurityAudit("Security: denied client %d access %x to resource 0x%x "
+ "of client %d on request %s\n", rec->client->index,
+ requested, rec->id, cid,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess; /* deny access */
+}
+
+
+static void
+SecurityExtension(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceExtAccessRec *rec = calldata;
+ SecurityStateRec *subj;
+ int i = 0;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+
+ if (subj->haveState && subj->trustLevel == XSecurityClientTrusted)
+ return;
+
+ while (SecurityTrustedExtensions[i])
+ if (!strcmp(SecurityTrustedExtensions[i++], rec->ext->name))
+ return;
+
+ SecurityAudit("Security: denied client %d access to extension "
+ "%s on request %s\n",
+ rec->client->index, rec->ext->name,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess;
+}
+
+static void
+SecurityServer(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceServerAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+ Mask requested = rec->access_mode;
+ Mask allowed = SecurityServerMask;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&serverClient->devPrivates, stateKey);
+
+ if (SecurityDoCheck(subj, obj, requested, allowed) != Success) {
+ SecurityAudit("Security: denied client %d access to server "
+ "configuration request %s\n", rec->client->index,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess;
+ }
+}
+
+static void
+SecurityClient(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceClientAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+ Mask requested = rec->access_mode;
+ Mask allowed = SecurityClientMask;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&rec->target->devPrivates, stateKey);
+
+ if (SecurityDoCheck(subj, obj, requested, allowed) != Success) {
+ SecurityAudit("Security: denied client %d access to client %d on "
+ "request %s\n", rec->client->index, rec->target->index,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess;
+ }
+}
+
+static void
+SecurityProperty(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XacePropertyAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+ ATOM name = (*rec->ppProp)->propertyName;
+ Mask requested = rec->access_mode;
+ Mask allowed = SecurityResourceMask | DixReadAccess;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey);
+
+ if (SecurityDoCheck(subj, obj, requested, allowed) != Success) {
+ SecurityAudit("Security: denied client %d access to property %s "
+ "(atom 0x%x) window 0x%x of client %d on request %s\n",
+ rec->client->index, NameForAtom(name), name,
+ rec->pWin->drawable.id, wClient(rec->pWin)->index,
+ SecurityLookupRequestName(rec->client));
+ rec->status = BadAccess;
+ }
+}
+
+static void
+SecuritySend(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceSendAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+
+ if (rec->client) {
+ int i;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey);
+
+ if (SecurityDoCheck(subj, obj, DixSendAccess, 0) == Success)
+ return;
+
+ for (i = 0; i < rec->count; i++)
+ if (rec->events[i].u.u.type != UnmapNotify &&
+ rec->events[i].u.u.type != ConfigureRequest &&
+ rec->events[i].u.u.type != ClientMessage) {
+
+ SecurityAudit("Security: denied client %d from sending event "
+ "of type %s to window 0x%x of client %d\n",
+ rec->client->index,
+ LookupEventName(rec->events[i].u.u.type),
+ rec->pWin->drawable.id,
+ wClient(rec->pWin)->index);
+ rec->status = BadAccess;
+ return;
+ }
+ }
+}
+
+static void
+SecurityReceive(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ XaceReceiveAccessRec *rec = calldata;
+ SecurityStateRec *subj, *obj;
+
+ subj = dixLookupPrivate(&rec->client->devPrivates, stateKey);
+ obj = dixLookupPrivate(&wClient(rec->pWin)->devPrivates, stateKey);
+
+ if (SecurityDoCheck(subj, obj, DixReceiveAccess, 0) == Success)
+ return;
+
+ SecurityAudit("Security: denied client %d from receiving an event "
+ "sent to window 0x%x of client %d\n",
+ rec->client->index, rec->pWin->drawable.id,
+ wClient(rec->pWin)->index);
+ rec->status = BadAccess;
+}
+
+/* SecurityClientStateCallback
+ *
+ * Arguments:
+ * pcbl is &ClientStateCallback.
+ * nullata is NULL.
+ * calldata is a pointer to a NewClientInfoRec (include/dixstruct.h)
+ * which contains information about client state changes.
+ *
+ * Returns: nothing.
+ *
+ * Side Effects:
+ *
+ * If a new client is connecting, its authorization ID is copied to
+ * client->authID. If this is a generated authorization, its reference
+ * count is bumped, its timer is cancelled if it was running, and its
+ * trustlevel is copied to TRUSTLEVEL(client).
+ *
+ * If a client is disconnecting and the client was using a generated
+ * authorization, the authorization's reference count is decremented, and
+ * if it is now zero, the timer for this authorization is started.
+ */
+
+static void
+SecurityClientState(CallbackListPtr *pcbl, pointer unused, pointer calldata)
+{
+ NewClientInfoRec *pci = calldata;
+ SecurityStateRec *state;
+ SecurityAuthorizationPtr pAuth;
+ int rc;
+
+ state = dixLookupPrivate(&pci->client->devPrivates, stateKey);
+
+ switch (pci->client->clientState) {
+ case ClientStateInitial:
+ state->trustLevel = XSecurityClientTrusted;
+ state->authId = None;
+ state->haveState = TRUE;
+ break;
+
+ case ClientStateRunning:
+ state->authId = AuthorizationIDOfClient(pci->client);
+ rc = dixLookupResourceByType((pointer *)&pAuth, state->authId,
+ SecurityAuthorizationResType, serverClient,
+ DixGetAttrAccess);
+ if (rc == Success) {
+ /* it is a generated authorization */
+ pAuth->refcnt++;
+ if (pAuth->refcnt == 1 && pAuth->timer)
+ TimerCancel(pAuth->timer);
+
+ state->trustLevel = pAuth->trustLevel;
+ }
+ break;
+
+ case ClientStateGone:
+ case ClientStateRetained:
+ rc = dixLookupResourceByType((pointer *)&pAuth, state->authId,
+ SecurityAuthorizationResType, serverClient,
+ DixGetAttrAccess);
+ if (rc == Success) {
+ /* it is a generated authorization */
+ pAuth->refcnt--;
+ if (pAuth->refcnt == 0)
+ SecurityStartAuthorizationTimer(pAuth);
+ }
+ break;
+
+ default:
+ break;
+ }
+}
+
+/* SecurityResetProc
+ *
+ * Arguments:
+ * extEntry is the extension information for the security extension.
+ *
+ * Returns: nothing.
+ *
+ * Side Effects:
+ * Performs any cleanup needed by Security at server shutdown time.
+ */
+
+static void
+SecurityResetProc(
+ ExtensionEntry *extEntry)
+{
+ /* Unregister callbacks */
+ DeleteCallback(&ClientStateCallback, SecurityClientState, NULL);
+
+ XaceDeleteCallback(XACE_EXT_DISPATCH, SecurityExtension, NULL);
+ XaceDeleteCallback(XACE_RESOURCE_ACCESS, SecurityResource, NULL);
+ XaceDeleteCallback(XACE_DEVICE_ACCESS, SecurityDevice, NULL);
+ XaceDeleteCallback(XACE_PROPERTY_ACCESS, SecurityProperty, NULL);
+ XaceDeleteCallback(XACE_SEND_ACCESS, SecuritySend, NULL);
+ XaceDeleteCallback(XACE_RECEIVE_ACCESS, SecurityReceive, NULL);
+ XaceDeleteCallback(XACE_CLIENT_ACCESS, SecurityClient, NULL);
+ XaceDeleteCallback(XACE_EXT_ACCESS, SecurityExtension, NULL);
+ XaceDeleteCallback(XACE_SERVER_ACCESS, SecurityServer, NULL);
+}
+
+
+/* SecurityExtensionInit
+ *
+ * Arguments: none.
+ *
+ * Returns: nothing.
+ *
+ * Side Effects:
+ * Enables the Security extension if possible.
+ */
+
+void
+SecurityExtensionInit(INITARGS)
+{
+ ExtensionEntry *extEntry;
+ int ret = TRUE;
+
+ SecurityAuthorizationResType =
+ CreateNewResourceType(SecurityDeleteAuthorization);
+
+ RTEventClient = CreateNewResourceType(
+ SecurityDeleteAuthorizationEventClient);
+
+ if (!SecurityAuthorizationResType || !RTEventClient)
+ return;
+
+ RTEventClient |= RC_NEVERRETAIN;
+ RegisterResourceName(SecurityAuthorizationResType, "SecurityAuthorization");
+ RegisterResourceName(RTEventClient, "SecurityEventClient");
+
+ /* Allocate the private storage */
+ if (!dixRequestPrivate(stateKey, sizeof(SecurityStateRec)))
+ FatalError("SecurityExtensionSetup: Can't allocate client private.\n");
+
+ /* Register callbacks */
+ ret &= AddCallback(&ClientStateCallback, SecurityClientState, NULL);
+
+ ret &= XaceRegisterCallback(XACE_EXT_DISPATCH, SecurityExtension, NULL);
+ ret &= XaceRegisterCallback(XACE_RESOURCE_ACCESS, SecurityResource, NULL);
+ ret &= XaceRegisterCallback(XACE_DEVICE_ACCESS, SecurityDevice, NULL);
+ ret &= XaceRegisterCallback(XACE_PROPERTY_ACCESS, SecurityProperty, NULL);
+ ret &= XaceRegisterCallback(XACE_SEND_ACCESS, SecuritySend, NULL);
+ ret &= XaceRegisterCallback(XACE_RECEIVE_ACCESS, SecurityReceive, NULL);
+ ret &= XaceRegisterCallback(XACE_CLIENT_ACCESS, SecurityClient, NULL);
+ ret &= XaceRegisterCallback(XACE_EXT_ACCESS, SecurityExtension, NULL);
+ ret &= XaceRegisterCallback(XACE_SERVER_ACCESS, SecurityServer, NULL);
+
+ if (!ret)
+ FatalError("SecurityExtensionSetup: Failed to register callbacks\n");
+
+ /* Add extension to server */
+ extEntry = AddExtension(SECURITY_EXTENSION_NAME,
+ XSecurityNumberEvents, XSecurityNumberErrors,
+ ProcSecurityDispatch, SProcSecurityDispatch,
+ SecurityResetProc, StandardMinorOpcode);
+
+ SecurityErrorBase = extEntry->errorBase;
+ SecurityEventBase = extEntry->eventBase;
+
+ EventSwapVector[SecurityEventBase + XSecurityAuthorizationRevoked] =
+ (EventSwapPtr)SwapSecurityAuthorizationRevokedEvent;
+
+ /* Label objects that were created before we could register ourself */
+ SecurityLabelInitial();
+}
diff --git a/xorg-server/Xext/shape.c b/xorg-server/Xext/shape.c index 700fe76d1..27f7ae25e 100644 --- a/xorg-server/Xext/shape.c +++ b/xorg-server/Xext/shape.c @@ -1,1293 +1,1295 @@ -/************************************************************ - -Copyright 1989, 1998 The Open Group - -Permission to use, copy, modify, distribute, and sell this software and its -documentation for any purpose is hereby granted without fee, provided that -the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation. - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of The Open Group shall not be -used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization from The Open Group. - -********************************************************/ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <stdlib.h> - -#include <X11/X.h> -#include <X11/Xproto.h> -#include "misc.h" -#include "os.h" -#include "windowstr.h" -#include "scrnintstr.h" -#include "pixmapstr.h" -#include "extnsionst.h" -#include "dixstruct.h" -#include "resource.h" -#include "opaque.h" -#include <X11/extensions/shapeproto.h> -#include "regionstr.h" -#include "gcstruct.h" -#include "modinit.h" -#include "protocol-versions.h" - -typedef RegionPtr (*CreateDftPtr)( - WindowPtr /* pWin */ - ); - -static int ShapeFreeClient( - pointer /* data */, - XID /* id */ - ); -static int ShapeFreeEvents( - pointer /* data */, - XID /* id */ - ); -static void SShapeNotifyEvent( - xShapeNotifyEvent * /* from */, - xShapeNotifyEvent * /* to */ - ); - -/* SendShapeNotify, CreateBoundingShape and CreateClipShape are used - * externally by the Xfixes extension and are now defined in window.h - */ - -static DISPATCH_PROC(ProcShapeCombine); -static DISPATCH_PROC(ProcShapeDispatch); -static DISPATCH_PROC(ProcShapeGetRectangles); -static DISPATCH_PROC(ProcShapeInputSelected); -static DISPATCH_PROC(ProcShapeMask); -static DISPATCH_PROC(ProcShapeOffset); -static DISPATCH_PROC(ProcShapeQueryExtents); -static DISPATCH_PROC(ProcShapeQueryVersion); -static DISPATCH_PROC(ProcShapeRectangles); -static DISPATCH_PROC(ProcShapeSelectInput); -static DISPATCH_PROC(SProcShapeCombine); -static DISPATCH_PROC(SProcShapeDispatch); -static DISPATCH_PROC(SProcShapeGetRectangles); -static DISPATCH_PROC(SProcShapeInputSelected); -static DISPATCH_PROC(SProcShapeMask); -static DISPATCH_PROC(SProcShapeOffset); -static DISPATCH_PROC(SProcShapeQueryExtents); -static DISPATCH_PROC(SProcShapeQueryVersion); -static DISPATCH_PROC(SProcShapeRectangles); -static DISPATCH_PROC(SProcShapeSelectInput); - -#ifdef PANORAMIX -#include "panoramiX.h" -#include "panoramiXsrv.h" -#endif - -static int ShapeEventBase = 0; -static RESTYPE ClientType, ShapeEventType; /* resource types for event masks */ - -/* - * each window has a list of clients requesting - * ShapeNotify events. Each client has a resource - * for each window it selects ShapeNotify input for, - * this resource is used to delete the ShapeNotifyRec - * entry from the per-window queue. - */ - -typedef struct _ShapeEvent *ShapeEventPtr; - -typedef struct _ShapeEvent { - ShapeEventPtr next; - ClientPtr client; - WindowPtr window; - XID clientResource; -} ShapeEventRec; - -/**************** - * ShapeExtensionInit - * - * Called from InitExtensions in main() or from QueryExtension() if the - * extension is dynamically loaded. - * - ****************/ - -void -ShapeExtensionInit(void) -{ - ExtensionEntry *extEntry; - - ClientType = CreateNewResourceType(ShapeFreeClient); - ShapeEventType = CreateNewResourceType(ShapeFreeEvents); - if (ClientType && ShapeEventType && - (extEntry = AddExtension(SHAPENAME, ShapeNumberEvents, 0, - ProcShapeDispatch, SProcShapeDispatch, - NULL, StandardMinorOpcode))) - { - ShapeEventBase = extEntry->eventBase; - EventSwapVector[ShapeEventBase] = (EventSwapPtr) SShapeNotifyEvent; - } -} - -static int -RegionOperate ( - ClientPtr client, - WindowPtr pWin, - int kind, - RegionPtr *destRgnp, - RegionPtr srcRgn, - int op, - int xoff, int yoff, - CreateDftPtr create) -{ - ScreenPtr pScreen = pWin->drawable.pScreen; - - if (srcRgn && (xoff || yoff)) - REGION_TRANSLATE(pScreen, srcRgn, xoff, yoff); - if (!pWin->parent) - { - if (srcRgn) - REGION_DESTROY(pScreen, srcRgn); - return Success; - } - - /* May/30/2001: - * The shape.PS specs say if src is None, existing shape is to be - * removed (and so the op-code has no meaning in such removal); - * see shape.PS, page 3, ShapeMask. - */ - if (srcRgn == NULL) { - if (*destRgnp != NULL) { - REGION_DESTROY (pScreen, *destRgnp); - *destRgnp = 0; - /* go on to remove shape and generate ShapeNotify */ - } - else { - /* May/30/2001: - * The target currently has no shape in effect, so nothing to - * do here. The specs say that ShapeNotify is generated whenever - * the client region is "modified"; since no modification is done - * here, we do not generate that event. The specs does not say - * "it is an error to request removal when there is no shape in - * effect", so we return good status. - */ - return Success; - } - } - else switch (op) { - case ShapeSet: - if (*destRgnp) - REGION_DESTROY(pScreen, *destRgnp); - *destRgnp = srcRgn; - srcRgn = 0; - break; - case ShapeUnion: - if (*destRgnp) - REGION_UNION(pScreen, *destRgnp, *destRgnp, srcRgn); - break; - case ShapeIntersect: - if (*destRgnp) - REGION_INTERSECT(pScreen, *destRgnp, *destRgnp, srcRgn); - else { - *destRgnp = srcRgn; - srcRgn = 0; - } - break; - case ShapeSubtract: - if (!*destRgnp) - *destRgnp = (*create)(pWin); - REGION_SUBTRACT(pScreen, *destRgnp, *destRgnp, srcRgn); - break; - case ShapeInvert: - if (!*destRgnp) - *destRgnp = REGION_CREATE(pScreen, (BoxPtr) 0, 0); - else - REGION_SUBTRACT(pScreen, *destRgnp, srcRgn, *destRgnp); - break; - default: - client->errorValue = op; - return BadValue; - } - if (srcRgn) - REGION_DESTROY(pScreen, srcRgn); - (*pScreen->SetShape) (pWin); - SendShapeNotify (pWin, kind); - return Success; -} - -RegionPtr -CreateBoundingShape (WindowPtr pWin) -{ - BoxRec extents; - - extents.x1 = -wBorderWidth (pWin); - extents.y1 = -wBorderWidth (pWin); - extents.x2 = pWin->drawable.width + wBorderWidth (pWin); - extents.y2 = pWin->drawable.height + wBorderWidth (pWin); - return REGION_CREATE(pWin->drawable.pScreen, &extents, 1); -} - -RegionPtr -CreateClipShape (WindowPtr pWin) -{ - BoxRec extents; - - extents.x1 = 0; - extents.y1 = 0; - extents.x2 = pWin->drawable.width; - extents.y2 = pWin->drawable.height; - return REGION_CREATE(pWin->drawable.pScreen, &extents, 1); -} - -static int -ProcShapeQueryVersion (ClientPtr client) -{ - xShapeQueryVersionReply rep; - int n; - - REQUEST_SIZE_MATCH (xShapeQueryVersionReq); - memset(&rep, 0, sizeof(xShapeQueryVersionReply)); - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.majorVersion = SERVER_SHAPE_MAJOR_VERSION; - rep.minorVersion = SERVER_SHAPE_MINOR_VERSION; - if (client->swapped) { - swaps(&rep.sequenceNumber, n); - swapl(&rep.length, n); - swaps(&rep.majorVersion, n); - swaps(&rep.minorVersion, n); - } - WriteToClient(client, sizeof (xShapeQueryVersionReply), (char *)&rep); - return (client->noClientException); -} - -/***************** - * ProcShapeRectangles - * - *****************/ - -static int -ProcShapeRectangles (ClientPtr client) -{ - WindowPtr pWin; - ScreenPtr pScreen; - REQUEST(xShapeRectanglesReq); - xRectangle *prects; - int nrects, ctype, rc; - RegionPtr srcRgn; - RegionPtr *destRgn; - CreateDftPtr createDefault; - - REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq); - UpdateCurrentTime(); - rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess); - if (rc != Success) - return rc; - switch (stuff->destKind) { - case ShapeBounding: - createDefault = CreateBoundingShape; - break; - case ShapeClip: - createDefault = CreateClipShape; - break; - case ShapeInput: - createDefault = CreateBoundingShape; - break; - default: - client->errorValue = stuff->destKind; - return BadValue; - } - if ((stuff->ordering != Unsorted) && (stuff->ordering != YSorted) && - (stuff->ordering != YXSorted) && (stuff->ordering != YXBanded)) - { - client->errorValue = stuff->ordering; - return BadValue; - } - pScreen = pWin->drawable.pScreen; - nrects = ((stuff->length << 2) - sizeof(xShapeRectanglesReq)); - if (nrects & 4) - return BadLength; - nrects >>= 3; - prects = (xRectangle *) &stuff[1]; - ctype = VerifyRectOrder(nrects, prects, (int)stuff->ordering); - if (ctype < 0) - return BadMatch; - srcRgn = RECTS_TO_REGION(pScreen, nrects, prects, ctype); - - if (!pWin->optional) - MakeWindowOptional (pWin); - switch (stuff->destKind) { - case ShapeBounding: - destRgn = &pWin->optional->boundingShape; - break; - case ShapeClip: - destRgn = &pWin->optional->clipShape; - break; - case ShapeInput: - destRgn = &pWin->optional->inputShape; - break; - default: - return BadValue; - } - - return RegionOperate (client, pWin, (int)stuff->destKind, - destRgn, srcRgn, (int)stuff->op, - stuff->xOff, stuff->yOff, createDefault); -} - -#ifdef PANORAMIX -static int -ProcPanoramiXShapeRectangles( - ClientPtr client) -{ - REQUEST(xShapeRectanglesReq); - PanoramiXRes *win; - int j, result; - - REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq); - - result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW, - client, DixWriteAccess); - if (result != Success) - return (result == BadValue) ? BadWindow : result; - - FOR_NSCREENS(j) { - stuff->dest = win->info[j].id; - result = ProcShapeRectangles (client); - BREAK_IF(result != Success); - } - return (result); -} -#endif - - -/************** - * ProcShapeMask - **************/ - - -static int -ProcShapeMask (ClientPtr client) -{ - WindowPtr pWin; - ScreenPtr pScreen; - REQUEST(xShapeMaskReq); - RegionPtr srcRgn; - RegionPtr *destRgn; - PixmapPtr pPixmap; - CreateDftPtr createDefault; - int rc; - - REQUEST_SIZE_MATCH (xShapeMaskReq); - UpdateCurrentTime(); - rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess); - if (rc != Success) - return rc; - switch (stuff->destKind) { - case ShapeBounding: - createDefault = CreateBoundingShape; - break; - case ShapeClip: - createDefault = CreateClipShape; - break; - case ShapeInput: - createDefault = CreateBoundingShape; - break; - default: - client->errorValue = stuff->destKind; - return BadValue; - } - pScreen = pWin->drawable.pScreen; - if (stuff->src == None) - srcRgn = 0; - else { - rc = dixLookupResourceByType((pointer *)&pPixmap, stuff->src, RT_PIXMAP, - client, DixReadAccess); - if (rc != Success) - return (rc == BadValue) ? BadPixmap : rc; - if (pPixmap->drawable.pScreen != pScreen || - pPixmap->drawable.depth != 1) - return BadMatch; - srcRgn = BITMAP_TO_REGION(pScreen, pPixmap); - if (!srcRgn) - return BadAlloc; - } - - if (!pWin->optional) - MakeWindowOptional (pWin); - switch (stuff->destKind) { - case ShapeBounding: - destRgn = &pWin->optional->boundingShape; - break; - case ShapeClip: - destRgn = &pWin->optional->clipShape; - break; - case ShapeInput: - destRgn = &pWin->optional->inputShape; - break; - default: - return BadValue; - } - - return RegionOperate (client, pWin, (int)stuff->destKind, - destRgn, srcRgn, (int)stuff->op, - stuff->xOff, stuff->yOff, createDefault); -} - -#ifdef PANORAMIX -static int -ProcPanoramiXShapeMask( - ClientPtr client) -{ - REQUEST(xShapeMaskReq); - PanoramiXRes *win, *pmap; - int j, result; - - REQUEST_SIZE_MATCH (xShapeMaskReq); - - result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW, - client, DixWriteAccess); - if (result != Success) - return (result == BadValue) ? BadWindow : result; - - if(stuff->src != None) { - result = dixLookupResourceByType((pointer *)&pmap, stuff->src, - XRT_PIXMAP, client, DixReadAccess); - if (result != Success) - return (result == BadValue) ? BadPixmap : result; - } else - pmap = NULL; - - FOR_NSCREENS(j) { - stuff->dest = win->info[j].id; - if(pmap) - stuff->src = pmap->info[j].id; - result = ProcShapeMask (client); - BREAK_IF(result != Success); - } - return (result); -} -#endif - - -/************ - * ProcShapeCombine - ************/ - -static int -ProcShapeCombine (ClientPtr client) -{ - WindowPtr pSrcWin, pDestWin; - ScreenPtr pScreen; - REQUEST(xShapeCombineReq); - RegionPtr srcRgn; - RegionPtr *destRgn; - CreateDftPtr createDefault; - CreateDftPtr createSrc; - RegionPtr tmp; - int rc; - - REQUEST_SIZE_MATCH (xShapeCombineReq); - UpdateCurrentTime(); - rc = dixLookupWindow(&pDestWin, stuff->dest, client, DixSetAttrAccess); - if (rc != Success) - return rc; - if (!pDestWin->optional) - MakeWindowOptional (pDestWin); - switch (stuff->destKind) { - case ShapeBounding: - createDefault = CreateBoundingShape; - break; - case ShapeClip: - createDefault = CreateClipShape; - break; - case ShapeInput: - createDefault = CreateBoundingShape; - break; - default: - client->errorValue = stuff->destKind; - return BadValue; - } - pScreen = pDestWin->drawable.pScreen; - - rc = dixLookupWindow(&pSrcWin, stuff->src, client, DixGetAttrAccess); - if (rc != Success) - return rc; - switch (stuff->srcKind) { - case ShapeBounding: - srcRgn = wBoundingShape (pSrcWin); - createSrc = CreateBoundingShape; - break; - case ShapeClip: - srcRgn = wClipShape (pSrcWin); - createSrc = CreateClipShape; - break; - case ShapeInput: - srcRgn = wInputShape (pSrcWin); - createSrc = CreateBoundingShape; - break; - default: - client->errorValue = stuff->srcKind; - return BadValue; - } - if (pSrcWin->drawable.pScreen != pScreen) - { - return BadMatch; - } - - if (srcRgn) { - tmp = REGION_CREATE(pScreen, (BoxPtr) 0, 0); - REGION_COPY(pScreen, tmp, srcRgn); - srcRgn = tmp; - } else - srcRgn = (*createSrc) (pSrcWin); - - if (!pDestWin->optional) - MakeWindowOptional (pDestWin); - switch (stuff->destKind) { - case ShapeBounding: - destRgn = &pDestWin->optional->boundingShape; - break; - case ShapeClip: - destRgn = &pDestWin->optional->clipShape; - break; - case ShapeInput: - destRgn = &pDestWin->optional->inputShape; - break; - default: - return BadValue; - } - - return RegionOperate (client, pDestWin, (int)stuff->destKind, - destRgn, srcRgn, (int)stuff->op, - stuff->xOff, stuff->yOff, createDefault); -} - - -#ifdef PANORAMIX -static int -ProcPanoramiXShapeCombine( - ClientPtr client) -{ - REQUEST(xShapeCombineReq); - PanoramiXRes *win, *win2; - int j, result; - - REQUEST_AT_LEAST_SIZE (xShapeCombineReq); - - result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW, - client, DixWriteAccess); - if (result != Success) - return (result == BadValue) ? BadWindow : result; - - result = dixLookupResourceByType((pointer *)&win2, stuff->src, XRT_WINDOW, - client, DixReadAccess); - if (result != Success) - return (result == BadValue) ? BadWindow : result; - - FOR_NSCREENS(j) { - stuff->dest = win->info[j].id; - stuff->src = win2->info[j].id; - result = ProcShapeCombine (client); - BREAK_IF(result != Success); - } - return (result); -} -#endif - -/************* - * ProcShapeOffset - *************/ - -static int -ProcShapeOffset (ClientPtr client) -{ - WindowPtr pWin; - ScreenPtr pScreen; - REQUEST(xShapeOffsetReq); - RegionPtr srcRgn; - int rc; - - REQUEST_SIZE_MATCH (xShapeOffsetReq); - UpdateCurrentTime(); - rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess); - if (rc != Success) - return rc; - switch (stuff->destKind) { - case ShapeBounding: - srcRgn = wBoundingShape (pWin); - break; - case ShapeClip: - srcRgn = wClipShape(pWin); - break; - case ShapeInput: - srcRgn = wInputShape (pWin); - break; - default: - client->errorValue = stuff->destKind; - return BadValue; - } - pScreen = pWin->drawable.pScreen; - if (srcRgn) - { - REGION_TRANSLATE(pScreen, srcRgn, stuff->xOff, stuff->yOff); - (*pScreen->SetShape) (pWin); - } - SendShapeNotify (pWin, (int)stuff->destKind); - return Success; -} - - -#ifdef PANORAMIX -static int -ProcPanoramiXShapeOffset( - ClientPtr client) -{ - REQUEST(xShapeOffsetReq); - PanoramiXRes *win; - int j, result; - - REQUEST_AT_LEAST_SIZE (xShapeOffsetReq); - - result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW, - client, DixWriteAccess); - if (result != Success) - return (result == BadValue) ? BadWindow : result; - - FOR_NSCREENS(j) { - stuff->dest = win->info[j].id; - result = ProcShapeOffset (client); - if(result != Success) break; - } - return (result); -} -#endif - - -static int -ProcShapeQueryExtents (ClientPtr client) -{ - REQUEST(xShapeQueryExtentsReq); - WindowPtr pWin; - xShapeQueryExtentsReply rep; - BoxRec extents, *pExtents; - int n, rc; - RegionPtr region; - - REQUEST_SIZE_MATCH (xShapeQueryExtentsReq); - rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); - if (rc != Success) - return rc; - memset(&rep, 0, sizeof(xShapeQueryExtentsReply)); - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.boundingShaped = (wBoundingShape(pWin) != 0); - rep.clipShaped = (wClipShape(pWin) != 0); - if ((region = wBoundingShape(pWin))) { - /* this is done in two steps because of a compiler bug on SunOS 4.1.3 */ - pExtents = REGION_EXTENTS(pWin->drawable.pScreen, region); - extents = *pExtents; - } else { - extents.x1 = -wBorderWidth (pWin); - extents.y1 = -wBorderWidth (pWin); - extents.x2 = pWin->drawable.width + wBorderWidth (pWin); - extents.y2 = pWin->drawable.height + wBorderWidth (pWin); - } - rep.xBoundingShape = extents.x1; - rep.yBoundingShape = extents.y1; - rep.widthBoundingShape = extents.x2 - extents.x1; - rep.heightBoundingShape = extents.y2 - extents.y1; - if ((region = wClipShape(pWin))) { - /* this is done in two steps because of a compiler bug on SunOS 4.1.3 */ - pExtents = REGION_EXTENTS(pWin->drawable.pScreen, region); - extents = *pExtents; - } else { - extents.x1 = 0; - extents.y1 = 0; - extents.x2 = pWin->drawable.width; - extents.y2 = pWin->drawable.height; - } - rep.xClipShape = extents.x1; - rep.yClipShape = extents.y1; - rep.widthClipShape = extents.x2 - extents.x1; - rep.heightClipShape = extents.y2 - extents.y1; - if (client->swapped) { - swaps(&rep.sequenceNumber, n); - swapl(&rep.length, n); - swaps(&rep.xBoundingShape, n); - swaps(&rep.yBoundingShape, n); - swaps(&rep.widthBoundingShape, n); - swaps(&rep.heightBoundingShape, n); - swaps(&rep.xClipShape, n); - swaps(&rep.yClipShape, n); - swaps(&rep.widthClipShape, n); - swaps(&rep.heightClipShape, n); - } - WriteToClient(client, sizeof (xShapeQueryExtentsReply), (char *)&rep); - return (client->noClientException); -} - -/*ARGSUSED*/ -static int -ShapeFreeClient (pointer data, XID id) -{ - ShapeEventPtr pShapeEvent; - WindowPtr pWin; - ShapeEventPtr *pHead, pCur, pPrev; - int rc; - - pShapeEvent = (ShapeEventPtr) data; - pWin = pShapeEvent->window; - rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, - ShapeEventType, serverClient, DixReadAccess); - if (rc == Success) { - pPrev = 0; - for (pCur = *pHead; pCur && pCur != pShapeEvent; pCur=pCur->next) - pPrev = pCur; - if (pCur) - { - if (pPrev) - pPrev->next = pShapeEvent->next; - else - *pHead = pShapeEvent->next; - } - } - xfree ((pointer) pShapeEvent); - return 1; -} - -/*ARGSUSED*/ -static int -ShapeFreeEvents (pointer data, XID id) -{ - ShapeEventPtr *pHead, pCur, pNext; - - pHead = (ShapeEventPtr *) data; - for (pCur = *pHead; pCur; pCur = pNext) { - pNext = pCur->next; - FreeResource (pCur->clientResource, ClientType); - xfree ((pointer) pCur); - } - xfree ((pointer) pHead); - return 1; -} - -static int -ProcShapeSelectInput (ClientPtr client) -{ - REQUEST(xShapeSelectInputReq); - WindowPtr pWin; - ShapeEventPtr pShapeEvent, pNewShapeEvent, *pHead; - XID clientResource; - int rc; - - REQUEST_SIZE_MATCH (xShapeSelectInputReq); - rc = dixLookupWindow(&pWin, stuff->window, client, DixReceiveAccess); - if (rc != Success) - return rc; - rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, - ShapeEventType, client, DixWriteAccess); - if (rc != Success && rc != BadValue) - return rc; - - switch (stuff->enable) { - case xTrue: - if (pHead) { - - /* check for existing entry. */ - for (pShapeEvent = *pHead; - pShapeEvent; - pShapeEvent = pShapeEvent->next) - { - if (pShapeEvent->client == client) - return Success; - } - } - - /* build the entry */ - pNewShapeEvent = xalloc (sizeof (ShapeEventRec)); - if (!pNewShapeEvent) - return BadAlloc; - pNewShapeEvent->next = 0; - pNewShapeEvent->client = client; - pNewShapeEvent->window = pWin; - /* - * add a resource that will be deleted when - * the client goes away - */ - clientResource = FakeClientID (client->index); - pNewShapeEvent->clientResource = clientResource; - if (!AddResource (clientResource, ClientType, (pointer)pNewShapeEvent)) - return BadAlloc; - /* - * create a resource to contain a pointer to the list - * of clients selecting input. This must be indirect as - * the list may be arbitrarily rearranged which cannot be - * done through the resource database. - */ - if (!pHead) - { - pHead = xalloc (sizeof (ShapeEventPtr)); - if (!pHead || - !AddResource (pWin->drawable.id, ShapeEventType, (pointer)pHead)) - { - FreeResource (clientResource, RT_NONE); - return BadAlloc; - } - *pHead = 0; - } - pNewShapeEvent->next = *pHead; - *pHead = pNewShapeEvent; - break; - case xFalse: - /* delete the interest */ - if (pHead) { - pNewShapeEvent = 0; - for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) { - if (pShapeEvent->client == client) - break; - pNewShapeEvent = pShapeEvent; - } - if (pShapeEvent) { - FreeResource (pShapeEvent->clientResource, ClientType); - if (pNewShapeEvent) - pNewShapeEvent->next = pShapeEvent->next; - else - *pHead = pShapeEvent->next; - xfree (pShapeEvent); - } - } - break; - default: - client->errorValue = stuff->enable; - return BadValue; - } - return Success; -} - -/* - * deliver the event - */ - -void -SendShapeNotify (WindowPtr pWin, int which) -{ - ShapeEventPtr *pHead, pShapeEvent; - ClientPtr client; - xShapeNotifyEvent se; - BoxRec extents; - RegionPtr region; - BYTE shaped; - int rc; - - rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, - ShapeEventType, serverClient, DixReadAccess); - if (rc != Success) - return; - switch (which) { - case ShapeBounding: - region = wBoundingShape(pWin); - if (region) { - extents = *REGION_EXTENTS(pWin->drawable.pScreen, region); - shaped = xTrue; - } else { - extents.x1 = -wBorderWidth (pWin); - extents.y1 = -wBorderWidth (pWin); - extents.x2 = pWin->drawable.width + wBorderWidth (pWin); - extents.y2 = pWin->drawable.height + wBorderWidth (pWin); - shaped = xFalse; - } - break; - case ShapeClip: - region = wClipShape(pWin); - if (region) { - extents = *REGION_EXTENTS(pWin->drawable.pScreen, region); - shaped = xTrue; - } else { - extents.x1 = 0; - extents.y1 = 0; - extents.x2 = pWin->drawable.width; - extents.y2 = pWin->drawable.height; - shaped = xFalse; - } - break; - case ShapeInput: - region = wInputShape(pWin); - if (region) { - extents = *REGION_EXTENTS(pWin->drawable.pScreen, region); - shaped = xTrue; - } else { - extents.x1 = -wBorderWidth (pWin); - extents.y1 = -wBorderWidth (pWin); - extents.x2 = pWin->drawable.width + wBorderWidth (pWin); - extents.y2 = pWin->drawable.height + wBorderWidth (pWin); - shaped = xFalse; - } - break; - default: - return; - } - for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) { - client = pShapeEvent->client; - if (client == serverClient || client->clientGone) - continue; - se.type = ShapeNotify + ShapeEventBase; - se.kind = which; - se.window = pWin->drawable.id; - se.sequenceNumber = client->sequence; - se.x = extents.x1; - se.y = extents.y1; - se.width = extents.x2 - extents.x1; - se.height = extents.y2 - extents.y1; - se.time = currentTime.milliseconds; - se.shaped = shaped; - WriteEventsToClient (client, 1, (xEvent *) &se); - } -} - -static int -ProcShapeInputSelected (ClientPtr client) -{ - REQUEST(xShapeInputSelectedReq); - WindowPtr pWin; - ShapeEventPtr pShapeEvent, *pHead; - int enabled, rc; - xShapeInputSelectedReply rep; - int n; - - REQUEST_SIZE_MATCH (xShapeInputSelectedReq); - rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); - if (rc != Success) - return rc; - rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id, - ShapeEventType, client, DixReadAccess); - if (rc != Success && rc != BadValue) - return rc; - enabled = xFalse; - if (pHead) { - for (pShapeEvent = *pHead; - pShapeEvent; - pShapeEvent = pShapeEvent->next) - { - if (pShapeEvent->client == client) { - enabled = xTrue; - break; - } - } - } - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.enabled = enabled; - if (client->swapped) { - swaps (&rep.sequenceNumber, n); - swapl (&rep.length, n); - } - WriteToClient (client, sizeof (xShapeInputSelectedReply), (char *) &rep); - return (client->noClientException); -} - -static int -ProcShapeGetRectangles (ClientPtr client) -{ - REQUEST(xShapeGetRectanglesReq); - WindowPtr pWin; - xShapeGetRectanglesReply rep; - xRectangle *rects; - int nrects, i, rc; - RegionPtr region; - int n; - - REQUEST_SIZE_MATCH(xShapeGetRectanglesReq); - rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); - if (rc != Success) - return rc; - switch (stuff->kind) { - case ShapeBounding: - region = wBoundingShape(pWin); - break; - case ShapeClip: - region = wClipShape(pWin); - break; - case ShapeInput: - region = wInputShape (pWin); - break; - default: - client->errorValue = stuff->kind; - return BadValue; - } - if (!region) { - nrects = 1; - rects = xalloc (sizeof (xRectangle)); - if (!rects) - return BadAlloc; - switch (stuff->kind) { - case ShapeBounding: - rects->x = - (int) wBorderWidth (pWin); - rects->y = - (int) wBorderWidth (pWin); - rects->width = pWin->drawable.width + wBorderWidth (pWin); - rects->height = pWin->drawable.height + wBorderWidth (pWin); - break; - case ShapeClip: - rects->x = 0; - rects->y = 0; - rects->width = pWin->drawable.width; - rects->height = pWin->drawable.height; - break; - case ShapeInput: - rects->x = - (int) wBorderWidth (pWin); - rects->y = - (int) wBorderWidth (pWin); - rects->width = pWin->drawable.width + wBorderWidth (pWin); - rects->height = pWin->drawable.height + wBorderWidth (pWin); - break; - } - } else { - BoxPtr box; - nrects = REGION_NUM_RECTS(region); - box = REGION_RECTS(region); - rects = xalloc (nrects * sizeof (xRectangle)); - if (!rects && nrects) - return BadAlloc; - for (i = 0; i < nrects; i++, box++) { - rects[i].x = box->x1; - rects[i].y = box->y1; - rects[i].width = box->x2 - box->x1; - rects[i].height = box->y2 - box->y1; - } - } - rep.type = X_Reply; - rep.sequenceNumber = client->sequence; - rep.length = bytes_to_int32(nrects * sizeof (xRectangle)); - rep.ordering = YXBanded; - rep.nrects = nrects; - if (client->swapped) { - swaps (&rep.sequenceNumber, n); - swapl (&rep.length, n); - swapl (&rep.nrects, n); - SwapShorts ((short *)rects, (unsigned long)nrects * 4); - } - WriteToClient (client, sizeof (rep), (char *) &rep); - WriteToClient (client, nrects * sizeof (xRectangle), (char *) rects); - xfree (rects); - return client->noClientException; -} - -static int -ProcShapeDispatch (ClientPtr client) -{ - REQUEST(xReq); - switch (stuff->data) { - case X_ShapeQueryVersion: - return ProcShapeQueryVersion (client); - case X_ShapeRectangles: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShapeRectangles (client); - else -#endif - return ProcShapeRectangles (client); - case X_ShapeMask: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShapeMask (client); - else -#endif - return ProcShapeMask (client); - case X_ShapeCombine: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShapeCombine (client); - else -#endif - return ProcShapeCombine (client); - case X_ShapeOffset: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShapeOffset (client); - else -#endif - return ProcShapeOffset (client); - case X_ShapeQueryExtents: - return ProcShapeQueryExtents (client); - case X_ShapeSelectInput: - return ProcShapeSelectInput (client); - case X_ShapeInputSelected: - return ProcShapeInputSelected (client); - case X_ShapeGetRectangles: - return ProcShapeGetRectangles (client); - default: - return BadRequest; - } -} - -static void -SShapeNotifyEvent(xShapeNotifyEvent *from, xShapeNotifyEvent *to) -{ - to->type = from->type; - to->kind = from->kind; - cpswapl (from->window, to->window); - cpswaps (from->sequenceNumber, to->sequenceNumber); - cpswaps (from->x, to->x); - cpswaps (from->y, to->y); - cpswaps (from->width, to->width); - cpswaps (from->height, to->height); - cpswapl (from->time, to->time); - to->shaped = from->shaped; -} - -static int -SProcShapeQueryVersion (ClientPtr client) -{ - int n; - REQUEST (xShapeQueryVersionReq); - - swaps (&stuff->length, n); - return ProcShapeQueryVersion (client); -} - -static int -SProcShapeRectangles (ClientPtr client) -{ - char n; - REQUEST (xShapeRectanglesReq); - - swaps (&stuff->length, n); - REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq); - swapl (&stuff->dest, n); - swaps (&stuff->xOff, n); - swaps (&stuff->yOff, n); - SwapRestS(stuff); - return ProcShapeRectangles (client); -} - -static int -SProcShapeMask (ClientPtr client) -{ - char n; - REQUEST (xShapeMaskReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeMaskReq); - swapl (&stuff->dest, n); - swaps (&stuff->xOff, n); - swaps (&stuff->yOff, n); - swapl (&stuff->src, n); - return ProcShapeMask (client); -} - -static int -SProcShapeCombine (ClientPtr client) -{ - char n; - REQUEST (xShapeCombineReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeCombineReq); - swapl (&stuff->dest, n); - swaps (&stuff->xOff, n); - swaps (&stuff->yOff, n); - swapl (&stuff->src, n); - return ProcShapeCombine (client); -} - -static int -SProcShapeOffset (ClientPtr client) -{ - char n; - REQUEST (xShapeOffsetReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeOffsetReq); - swapl (&stuff->dest, n); - swaps (&stuff->xOff, n); - swaps (&stuff->yOff, n); - return ProcShapeOffset (client); -} - -static int -SProcShapeQueryExtents (ClientPtr client) -{ - char n; - REQUEST (xShapeQueryExtentsReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeQueryExtentsReq); - swapl (&stuff->window, n); - return ProcShapeQueryExtents (client); -} - -static int -SProcShapeSelectInput (ClientPtr client) -{ - char n; - REQUEST (xShapeSelectInputReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeSelectInputReq); - swapl (&stuff->window, n); - return ProcShapeSelectInput (client); -} - -static int -SProcShapeInputSelected (ClientPtr client) -{ - int n; - REQUEST (xShapeInputSelectedReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xShapeInputSelectedReq); - swapl (&stuff->window, n); - return ProcShapeInputSelected (client); -} - -static int -SProcShapeGetRectangles (ClientPtr client) -{ - REQUEST(xShapeGetRectanglesReq); - char n; - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xShapeGetRectanglesReq); - swapl (&stuff->window, n); - return ProcShapeGetRectangles (client); -} - -static int -SProcShapeDispatch (ClientPtr client) -{ - REQUEST(xReq); - switch (stuff->data) { - case X_ShapeQueryVersion: - return SProcShapeQueryVersion (client); - case X_ShapeRectangles: - return SProcShapeRectangles (client); - case X_ShapeMask: - return SProcShapeMask (client); - case X_ShapeCombine: - return SProcShapeCombine (client); - case X_ShapeOffset: - return SProcShapeOffset (client); - case X_ShapeQueryExtents: - return SProcShapeQueryExtents (client); - case X_ShapeSelectInput: - return SProcShapeSelectInput (client); - case X_ShapeInputSelected: - return SProcShapeInputSelected (client); - case X_ShapeGetRectangles: - return SProcShapeGetRectangles (client); - default: - return BadRequest; - } -} +/************************************************************
+
+Copyright 1989, 1998 The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+********************************************************/
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+#define SHAPE
+#endif
+
+#include <stdlib.h>
+
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "misc.h"
+#include "os.h"
+#include "windowstr.h"
+#include "scrnintstr.h"
+#include "pixmapstr.h"
+#include "extnsionst.h"
+#include "dixstruct.h"
+#include "resource.h"
+#include "opaque.h"
+#include <X11/extensions/shapeproto.h>
+#include "regionstr.h"
+#include "gcstruct.h"
+#include "modinit.h"
+#include "protocol-versions.h"
+
+typedef RegionPtr (*CreateDftPtr)(
+ WindowPtr /* pWin */
+ );
+
+static int ShapeFreeClient(
+ pointer /* data */,
+ XID /* id */
+ );
+static int ShapeFreeEvents(
+ pointer /* data */,
+ XID /* id */
+ );
+static void SShapeNotifyEvent(
+ xShapeNotifyEvent * /* from */,
+ xShapeNotifyEvent * /* to */
+ );
+
+/* SendShapeNotify, CreateBoundingShape and CreateClipShape are used
+ * externally by the Xfixes extension and are now defined in window.h
+ */
+
+static DISPATCH_PROC(ProcShapeCombine);
+static DISPATCH_PROC(ProcShapeDispatch);
+static DISPATCH_PROC(ProcShapeGetRectangles);
+static DISPATCH_PROC(ProcShapeInputSelected);
+static DISPATCH_PROC(ProcShapeMask);
+static DISPATCH_PROC(ProcShapeOffset);
+static DISPATCH_PROC(ProcShapeQueryExtents);
+static DISPATCH_PROC(ProcShapeQueryVersion);
+static DISPATCH_PROC(ProcShapeRectangles);
+static DISPATCH_PROC(ProcShapeSelectInput);
+static DISPATCH_PROC(SProcShapeCombine);
+static DISPATCH_PROC(SProcShapeDispatch);
+static DISPATCH_PROC(SProcShapeGetRectangles);
+static DISPATCH_PROC(SProcShapeInputSelected);
+static DISPATCH_PROC(SProcShapeMask);
+static DISPATCH_PROC(SProcShapeOffset);
+static DISPATCH_PROC(SProcShapeQueryExtents);
+static DISPATCH_PROC(SProcShapeQueryVersion);
+static DISPATCH_PROC(SProcShapeRectangles);
+static DISPATCH_PROC(SProcShapeSelectInput);
+
+#ifdef PANORAMIX
+#include "panoramiX.h"
+#include "panoramiXsrv.h"
+#endif
+
+static int ShapeEventBase = 0;
+static RESTYPE ClientType, ShapeEventType; /* resource types for event masks */
+
+/*
+ * each window has a list of clients requesting
+ * ShapeNotify events. Each client has a resource
+ * for each window it selects ShapeNotify input for,
+ * this resource is used to delete the ShapeNotifyRec
+ * entry from the per-window queue.
+ */
+
+typedef struct _ShapeEvent *ShapeEventPtr;
+
+typedef struct _ShapeEvent {
+ ShapeEventPtr next;
+ ClientPtr client;
+ WindowPtr window;
+ XID clientResource;
+} ShapeEventRec;
+
+/****************
+ * ShapeExtensionInit
+ *
+ * Called from InitExtensions in main() or from QueryExtension() if the
+ * extension is dynamically loaded.
+ *
+ ****************/
+
+void
+ShapeExtensionInit(void)
+{
+ ExtensionEntry *extEntry;
+
+ ClientType = CreateNewResourceType(ShapeFreeClient);
+ ShapeEventType = CreateNewResourceType(ShapeFreeEvents);
+ if (ClientType && ShapeEventType &&
+ (extEntry = AddExtension(SHAPENAME, ShapeNumberEvents, 0,
+ ProcShapeDispatch, SProcShapeDispatch,
+ NULL, StandardMinorOpcode)))
+ {
+ ShapeEventBase = extEntry->eventBase;
+ EventSwapVector[ShapeEventBase] = (EventSwapPtr) SShapeNotifyEvent;
+ }
+}
+
+static int
+RegionOperate (
+ ClientPtr client,
+ WindowPtr pWin,
+ int kind,
+ RegionPtr *destRgnp,
+ RegionPtr srcRgn,
+ int op,
+ int xoff, int yoff,
+ CreateDftPtr create)
+{
+ ScreenPtr pScreen = pWin->drawable.pScreen;
+
+ if (srcRgn && (xoff || yoff))
+ REGION_TRANSLATE(pScreen, srcRgn, xoff, yoff);
+ if (!pWin->parent)
+ {
+ if (srcRgn)
+ REGION_DESTROY(pScreen, srcRgn);
+ return Success;
+ }
+
+ /* May/30/2001:
+ * The shape.PS specs say if src is None, existing shape is to be
+ * removed (and so the op-code has no meaning in such removal);
+ * see shape.PS, page 3, ShapeMask.
+ */
+ if (srcRgn == NULL) {
+ if (*destRgnp != NULL) {
+ REGION_DESTROY (pScreen, *destRgnp);
+ *destRgnp = 0;
+ /* go on to remove shape and generate ShapeNotify */
+ }
+ else {
+ /* May/30/2001:
+ * The target currently has no shape in effect, so nothing to
+ * do here. The specs say that ShapeNotify is generated whenever
+ * the client region is "modified"; since no modification is done
+ * here, we do not generate that event. The specs does not say
+ * "it is an error to request removal when there is no shape in
+ * effect", so we return good status.
+ */
+ return Success;
+ }
+ }
+ else switch (op) {
+ case ShapeSet:
+ if (*destRgnp)
+ REGION_DESTROY(pScreen, *destRgnp);
+ *destRgnp = srcRgn;
+ srcRgn = 0;
+ break;
+ case ShapeUnion:
+ if (*destRgnp)
+ REGION_UNION(pScreen, *destRgnp, *destRgnp, srcRgn);
+ break;
+ case ShapeIntersect:
+ if (*destRgnp)
+ REGION_INTERSECT(pScreen, *destRgnp, *destRgnp, srcRgn);
+ else {
+ *destRgnp = srcRgn;
+ srcRgn = 0;
+ }
+ break;
+ case ShapeSubtract:
+ if (!*destRgnp)
+ *destRgnp = (*create)(pWin);
+ REGION_SUBTRACT(pScreen, *destRgnp, *destRgnp, srcRgn);
+ break;
+ case ShapeInvert:
+ if (!*destRgnp)
+ *destRgnp = REGION_CREATE(pScreen, (BoxPtr) 0, 0);
+ else
+ REGION_SUBTRACT(pScreen, *destRgnp, srcRgn, *destRgnp);
+ break;
+ default:
+ client->errorValue = op;
+ return BadValue;
+ }
+ if (srcRgn)
+ REGION_DESTROY(pScreen, srcRgn);
+ (*pScreen->SetShape) (pWin);
+ SendShapeNotify (pWin, kind);
+ return Success;
+}
+
+RegionPtr
+CreateBoundingShape (WindowPtr pWin)
+{
+ BoxRec extents;
+
+ extents.x1 = -wBorderWidth (pWin);
+ extents.y1 = -wBorderWidth (pWin);
+ extents.x2 = pWin->drawable.width + wBorderWidth (pWin);
+ extents.y2 = pWin->drawable.height + wBorderWidth (pWin);
+ return REGION_CREATE(pWin->drawable.pScreen, &extents, 1);
+}
+
+RegionPtr
+CreateClipShape (WindowPtr pWin)
+{
+ BoxRec extents;
+
+ extents.x1 = 0;
+ extents.y1 = 0;
+ extents.x2 = pWin->drawable.width;
+ extents.y2 = pWin->drawable.height;
+ return REGION_CREATE(pWin->drawable.pScreen, &extents, 1);
+}
+
+static int
+ProcShapeQueryVersion (ClientPtr client)
+{
+ xShapeQueryVersionReply rep;
+ int n;
+
+ REQUEST_SIZE_MATCH (xShapeQueryVersionReq);
+ memset(&rep, 0, sizeof(xShapeQueryVersionReply));
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.majorVersion = SERVER_SHAPE_MAJOR_VERSION;
+ rep.minorVersion = SERVER_SHAPE_MINOR_VERSION;
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.length, n);
+ swaps(&rep.majorVersion, n);
+ swaps(&rep.minorVersion, n);
+ }
+ WriteToClient(client, sizeof (xShapeQueryVersionReply), (char *)&rep);
+ return (client->noClientException);
+}
+
+/*****************
+ * ProcShapeRectangles
+ *
+ *****************/
+
+static int
+ProcShapeRectangles (ClientPtr client)
+{
+ WindowPtr pWin;
+ ScreenPtr pScreen;
+ REQUEST(xShapeRectanglesReq);
+ xRectangle *prects;
+ int nrects, ctype, rc;
+ RegionPtr srcRgn;
+ RegionPtr *destRgn;
+ CreateDftPtr createDefault;
+
+ REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq);
+ UpdateCurrentTime();
+ rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ createDefault = CreateBoundingShape;
+ break;
+ case ShapeClip:
+ createDefault = CreateClipShape;
+ break;
+ case ShapeInput:
+ createDefault = CreateBoundingShape;
+ break;
+ default:
+ client->errorValue = stuff->destKind;
+ return BadValue;
+ }
+ if ((stuff->ordering != Unsorted) && (stuff->ordering != YSorted) &&
+ (stuff->ordering != YXSorted) && (stuff->ordering != YXBanded))
+ {
+ client->errorValue = stuff->ordering;
+ return BadValue;
+ }
+ pScreen = pWin->drawable.pScreen;
+ nrects = ((stuff->length << 2) - sizeof(xShapeRectanglesReq));
+ if (nrects & 4)
+ return BadLength;
+ nrects >>= 3;
+ prects = (xRectangle *) &stuff[1];
+ ctype = VerifyRectOrder(nrects, prects, (int)stuff->ordering);
+ if (ctype < 0)
+ return BadMatch;
+ srcRgn = RECTS_TO_REGION(pScreen, nrects, prects, ctype);
+
+ if (!pWin->optional)
+ MakeWindowOptional (pWin);
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ destRgn = &pWin->optional->boundingShape;
+ break;
+ case ShapeClip:
+ destRgn = &pWin->optional->clipShape;
+ break;
+ case ShapeInput:
+ destRgn = &pWin->optional->inputShape;
+ break;
+ default:
+ return BadValue;
+ }
+
+ return RegionOperate (client, pWin, (int)stuff->destKind,
+ destRgn, srcRgn, (int)stuff->op,
+ stuff->xOff, stuff->yOff, createDefault);
+}
+
+#ifdef PANORAMIX
+static int
+ProcPanoramiXShapeRectangles(
+ ClientPtr client)
+{
+ REQUEST(xShapeRectanglesReq);
+ PanoramiXRes *win;
+ int j, result;
+
+ REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq);
+
+ result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW,
+ client, DixWriteAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadWindow : result;
+
+ FOR_NSCREENS(j) {
+ stuff->dest = win->info[j].id;
+ result = ProcShapeRectangles (client);
+ BREAK_IF(result != Success);
+ }
+ return (result);
+}
+#endif
+
+
+/**************
+ * ProcShapeMask
+ **************/
+
+
+static int
+ProcShapeMask (ClientPtr client)
+{
+ WindowPtr pWin;
+ ScreenPtr pScreen;
+ REQUEST(xShapeMaskReq);
+ RegionPtr srcRgn;
+ RegionPtr *destRgn;
+ PixmapPtr pPixmap;
+ CreateDftPtr createDefault;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xShapeMaskReq);
+ UpdateCurrentTime();
+ rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ createDefault = CreateBoundingShape;
+ break;
+ case ShapeClip:
+ createDefault = CreateClipShape;
+ break;
+ case ShapeInput:
+ createDefault = CreateBoundingShape;
+ break;
+ default:
+ client->errorValue = stuff->destKind;
+ return BadValue;
+ }
+ pScreen = pWin->drawable.pScreen;
+ if (stuff->src == None)
+ srcRgn = 0;
+ else {
+ rc = dixLookupResourceByType((pointer *)&pPixmap, stuff->src, RT_PIXMAP,
+ client, DixReadAccess);
+ if (rc != Success)
+ return (rc == BadValue) ? BadPixmap : rc;
+ if (pPixmap->drawable.pScreen != pScreen ||
+ pPixmap->drawable.depth != 1)
+ return BadMatch;
+ srcRgn = BITMAP_TO_REGION(pScreen, pPixmap);
+ if (!srcRgn)
+ return BadAlloc;
+ }
+
+ if (!pWin->optional)
+ MakeWindowOptional (pWin);
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ destRgn = &pWin->optional->boundingShape;
+ break;
+ case ShapeClip:
+ destRgn = &pWin->optional->clipShape;
+ break;
+ case ShapeInput:
+ destRgn = &pWin->optional->inputShape;
+ break;
+ default:
+ return BadValue;
+ }
+
+ return RegionOperate (client, pWin, (int)stuff->destKind,
+ destRgn, srcRgn, (int)stuff->op,
+ stuff->xOff, stuff->yOff, createDefault);
+}
+
+#ifdef PANORAMIX
+static int
+ProcPanoramiXShapeMask(
+ ClientPtr client)
+{
+ REQUEST(xShapeMaskReq);
+ PanoramiXRes *win, *pmap;
+ int j, result;
+
+ REQUEST_SIZE_MATCH (xShapeMaskReq);
+
+ result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW,
+ client, DixWriteAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadWindow : result;
+
+ if(stuff->src != None) {
+ result = dixLookupResourceByType((pointer *)&pmap, stuff->src,
+ XRT_PIXMAP, client, DixReadAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadPixmap : result;
+ } else
+ pmap = NULL;
+
+ FOR_NSCREENS(j) {
+ stuff->dest = win->info[j].id;
+ if(pmap)
+ stuff->src = pmap->info[j].id;
+ result = ProcShapeMask (client);
+ BREAK_IF(result != Success);
+ }
+ return (result);
+}
+#endif
+
+
+/************
+ * ProcShapeCombine
+ ************/
+
+static int
+ProcShapeCombine (ClientPtr client)
+{
+ WindowPtr pSrcWin, pDestWin;
+ ScreenPtr pScreen;
+ REQUEST(xShapeCombineReq);
+ RegionPtr srcRgn;
+ RegionPtr *destRgn;
+ CreateDftPtr createDefault;
+ CreateDftPtr createSrc;
+ RegionPtr tmp;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xShapeCombineReq);
+ UpdateCurrentTime();
+ rc = dixLookupWindow(&pDestWin, stuff->dest, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ if (!pDestWin->optional)
+ MakeWindowOptional (pDestWin);
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ createDefault = CreateBoundingShape;
+ break;
+ case ShapeClip:
+ createDefault = CreateClipShape;
+ break;
+ case ShapeInput:
+ createDefault = CreateBoundingShape;
+ break;
+ default:
+ client->errorValue = stuff->destKind;
+ return BadValue;
+ }
+ pScreen = pDestWin->drawable.pScreen;
+
+ rc = dixLookupWindow(&pSrcWin, stuff->src, client, DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ switch (stuff->srcKind) {
+ case ShapeBounding:
+ srcRgn = wBoundingShape (pSrcWin);
+ createSrc = CreateBoundingShape;
+ break;
+ case ShapeClip:
+ srcRgn = wClipShape (pSrcWin);
+ createSrc = CreateClipShape;
+ break;
+ case ShapeInput:
+ srcRgn = wInputShape (pSrcWin);
+ createSrc = CreateBoundingShape;
+ break;
+ default:
+ client->errorValue = stuff->srcKind;
+ return BadValue;
+ }
+ if (pSrcWin->drawable.pScreen != pScreen)
+ {
+ return BadMatch;
+ }
+
+ if (srcRgn) {
+ tmp = REGION_CREATE(pScreen, (BoxPtr) 0, 0);
+ REGION_COPY(pScreen, tmp, srcRgn);
+ srcRgn = tmp;
+ } else
+ srcRgn = (*createSrc) (pSrcWin);
+
+ if (!pDestWin->optional)
+ MakeWindowOptional (pDestWin);
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ destRgn = &pDestWin->optional->boundingShape;
+ break;
+ case ShapeClip:
+ destRgn = &pDestWin->optional->clipShape;
+ break;
+ case ShapeInput:
+ destRgn = &pDestWin->optional->inputShape;
+ break;
+ default:
+ return BadValue;
+ }
+
+ return RegionOperate (client, pDestWin, (int)stuff->destKind,
+ destRgn, srcRgn, (int)stuff->op,
+ stuff->xOff, stuff->yOff, createDefault);
+}
+
+
+#ifdef PANORAMIX
+static int
+ProcPanoramiXShapeCombine(
+ ClientPtr client)
+{
+ REQUEST(xShapeCombineReq);
+ PanoramiXRes *win, *win2;
+ int j, result;
+
+ REQUEST_AT_LEAST_SIZE (xShapeCombineReq);
+
+ result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW,
+ client, DixWriteAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadWindow : result;
+
+ result = dixLookupResourceByType((pointer *)&win2, stuff->src, XRT_WINDOW,
+ client, DixReadAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadWindow : result;
+
+ FOR_NSCREENS(j) {
+ stuff->dest = win->info[j].id;
+ stuff->src = win2->info[j].id;
+ result = ProcShapeCombine (client);
+ BREAK_IF(result != Success);
+ }
+ return (result);
+}
+#endif
+
+/*************
+ * ProcShapeOffset
+ *************/
+
+static int
+ProcShapeOffset (ClientPtr client)
+{
+ WindowPtr pWin;
+ ScreenPtr pScreen;
+ REQUEST(xShapeOffsetReq);
+ RegionPtr srcRgn;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xShapeOffsetReq);
+ UpdateCurrentTime();
+ rc = dixLookupWindow(&pWin, stuff->dest, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ switch (stuff->destKind) {
+ case ShapeBounding:
+ srcRgn = wBoundingShape (pWin);
+ break;
+ case ShapeClip:
+ srcRgn = wClipShape(pWin);
+ break;
+ case ShapeInput:
+ srcRgn = wInputShape (pWin);
+ break;
+ default:
+ client->errorValue = stuff->destKind;
+ return BadValue;
+ }
+ pScreen = pWin->drawable.pScreen;
+ if (srcRgn)
+ {
+ REGION_TRANSLATE(pScreen, srcRgn, stuff->xOff, stuff->yOff);
+ (*pScreen->SetShape) (pWin);
+ }
+ SendShapeNotify (pWin, (int)stuff->destKind);
+ return Success;
+}
+
+
+#ifdef PANORAMIX
+static int
+ProcPanoramiXShapeOffset(
+ ClientPtr client)
+{
+ REQUEST(xShapeOffsetReq);
+ PanoramiXRes *win;
+ int j, result;
+
+ REQUEST_AT_LEAST_SIZE (xShapeOffsetReq);
+
+ result = dixLookupResourceByType((pointer *)&win, stuff->dest, XRT_WINDOW,
+ client, DixWriteAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadWindow : result;
+
+ FOR_NSCREENS(j) {
+ stuff->dest = win->info[j].id;
+ result = ProcShapeOffset (client);
+ if(result != Success) break;
+ }
+ return (result);
+}
+#endif
+
+
+static int
+ProcShapeQueryExtents (ClientPtr client)
+{
+ REQUEST(xShapeQueryExtentsReq);
+ WindowPtr pWin;
+ xShapeQueryExtentsReply rep;
+ BoxRec extents, *pExtents;
+ int n, rc;
+ RegionPtr region;
+
+ REQUEST_SIZE_MATCH (xShapeQueryExtentsReq);
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ memset(&rep, 0, sizeof(xShapeQueryExtentsReply));
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.boundingShaped = (wBoundingShape(pWin) != 0);
+ rep.clipShaped = (wClipShape(pWin) != 0);
+ if ((region = wBoundingShape(pWin))) {
+ /* this is done in two steps because of a compiler bug on SunOS 4.1.3 */
+ pExtents = REGION_EXTENTS(pWin->drawable.pScreen, region);
+ extents = *pExtents;
+ } else {
+ extents.x1 = -wBorderWidth (pWin);
+ extents.y1 = -wBorderWidth (pWin);
+ extents.x2 = pWin->drawable.width + wBorderWidth (pWin);
+ extents.y2 = pWin->drawable.height + wBorderWidth (pWin);
+ }
+ rep.xBoundingShape = extents.x1;
+ rep.yBoundingShape = extents.y1;
+ rep.widthBoundingShape = extents.x2 - extents.x1;
+ rep.heightBoundingShape = extents.y2 - extents.y1;
+ if ((region = wClipShape(pWin))) {
+ /* this is done in two steps because of a compiler bug on SunOS 4.1.3 */
+ pExtents = REGION_EXTENTS(pWin->drawable.pScreen, region);
+ extents = *pExtents;
+ } else {
+ extents.x1 = 0;
+ extents.y1 = 0;
+ extents.x2 = pWin->drawable.width;
+ extents.y2 = pWin->drawable.height;
+ }
+ rep.xClipShape = extents.x1;
+ rep.yClipShape = extents.y1;
+ rep.widthClipShape = extents.x2 - extents.x1;
+ rep.heightClipShape = extents.y2 - extents.y1;
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.length, n);
+ swaps(&rep.xBoundingShape, n);
+ swaps(&rep.yBoundingShape, n);
+ swaps(&rep.widthBoundingShape, n);
+ swaps(&rep.heightBoundingShape, n);
+ swaps(&rep.xClipShape, n);
+ swaps(&rep.yClipShape, n);
+ swaps(&rep.widthClipShape, n);
+ swaps(&rep.heightClipShape, n);
+ }
+ WriteToClient(client, sizeof (xShapeQueryExtentsReply), (char *)&rep);
+ return (client->noClientException);
+}
+
+/*ARGSUSED*/
+static int
+ShapeFreeClient (pointer data, XID id)
+{
+ ShapeEventPtr pShapeEvent;
+ WindowPtr pWin;
+ ShapeEventPtr *pHead, pCur, pPrev;
+ int rc;
+
+ pShapeEvent = (ShapeEventPtr) data;
+ pWin = pShapeEvent->window;
+ rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id,
+ ShapeEventType, serverClient, DixReadAccess);
+ if (rc == Success) {
+ pPrev = 0;
+ for (pCur = *pHead; pCur && pCur != pShapeEvent; pCur=pCur->next)
+ pPrev = pCur;
+ if (pCur)
+ {
+ if (pPrev)
+ pPrev->next = pShapeEvent->next;
+ else
+ *pHead = pShapeEvent->next;
+ }
+ }
+ xfree ((pointer) pShapeEvent);
+ return 1;
+}
+
+/*ARGSUSED*/
+static int
+ShapeFreeEvents (pointer data, XID id)
+{
+ ShapeEventPtr *pHead, pCur, pNext;
+
+ pHead = (ShapeEventPtr *) data;
+ for (pCur = *pHead; pCur; pCur = pNext) {
+ pNext = pCur->next;
+ FreeResource (pCur->clientResource, ClientType);
+ xfree ((pointer) pCur);
+ }
+ xfree ((pointer) pHead);
+ return 1;
+}
+
+static int
+ProcShapeSelectInput (ClientPtr client)
+{
+ REQUEST(xShapeSelectInputReq);
+ WindowPtr pWin;
+ ShapeEventPtr pShapeEvent, pNewShapeEvent, *pHead;
+ XID clientResource;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xShapeSelectInputReq);
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixReceiveAccess);
+ if (rc != Success)
+ return rc;
+ rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id,
+ ShapeEventType, client, DixWriteAccess);
+ if (rc != Success && rc != BadValue)
+ return rc;
+
+ switch (stuff->enable) {
+ case xTrue:
+ if (pHead) {
+
+ /* check for existing entry. */
+ for (pShapeEvent = *pHead;
+ pShapeEvent;
+ pShapeEvent = pShapeEvent->next)
+ {
+ if (pShapeEvent->client == client)
+ return Success;
+ }
+ }
+
+ /* build the entry */
+ pNewShapeEvent = xalloc (sizeof (ShapeEventRec));
+ if (!pNewShapeEvent)
+ return BadAlloc;
+ pNewShapeEvent->next = 0;
+ pNewShapeEvent->client = client;
+ pNewShapeEvent->window = pWin;
+ /*
+ * add a resource that will be deleted when
+ * the client goes away
+ */
+ clientResource = FakeClientID (client->index);
+ pNewShapeEvent->clientResource = clientResource;
+ if (!AddResource (clientResource, ClientType, (pointer)pNewShapeEvent))
+ return BadAlloc;
+ /*
+ * create a resource to contain a pointer to the list
+ * of clients selecting input. This must be indirect as
+ * the list may be arbitrarily rearranged which cannot be
+ * done through the resource database.
+ */
+ if (!pHead)
+ {
+ pHead = xalloc (sizeof (ShapeEventPtr));
+ if (!pHead ||
+ !AddResource (pWin->drawable.id, ShapeEventType, (pointer)pHead))
+ {
+ FreeResource (clientResource, RT_NONE);
+ return BadAlloc;
+ }
+ *pHead = 0;
+ }
+ pNewShapeEvent->next = *pHead;
+ *pHead = pNewShapeEvent;
+ break;
+ case xFalse:
+ /* delete the interest */
+ if (pHead) {
+ pNewShapeEvent = 0;
+ for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) {
+ if (pShapeEvent->client == client)
+ break;
+ pNewShapeEvent = pShapeEvent;
+ }
+ if (pShapeEvent) {
+ FreeResource (pShapeEvent->clientResource, ClientType);
+ if (pNewShapeEvent)
+ pNewShapeEvent->next = pShapeEvent->next;
+ else
+ *pHead = pShapeEvent->next;
+ xfree (pShapeEvent);
+ }
+ }
+ break;
+ default:
+ client->errorValue = stuff->enable;
+ return BadValue;
+ }
+ return Success;
+}
+
+/*
+ * deliver the event
+ */
+
+void
+SendShapeNotify (WindowPtr pWin, int which)
+{
+ ShapeEventPtr *pHead, pShapeEvent;
+ ClientPtr client;
+ xShapeNotifyEvent se;
+ BoxRec extents;
+ RegionPtr region;
+ BYTE shaped;
+ int rc;
+
+ rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id,
+ ShapeEventType, serverClient, DixReadAccess);
+ if (rc != Success)
+ return;
+ switch (which) {
+ case ShapeBounding:
+ region = wBoundingShape(pWin);
+ if (region) {
+ extents = *REGION_EXTENTS(pWin->drawable.pScreen, region);
+ shaped = xTrue;
+ } else {
+ extents.x1 = -wBorderWidth (pWin);
+ extents.y1 = -wBorderWidth (pWin);
+ extents.x2 = pWin->drawable.width + wBorderWidth (pWin);
+ extents.y2 = pWin->drawable.height + wBorderWidth (pWin);
+ shaped = xFalse;
+ }
+ break;
+ case ShapeClip:
+ region = wClipShape(pWin);
+ if (region) {
+ extents = *REGION_EXTENTS(pWin->drawable.pScreen, region);
+ shaped = xTrue;
+ } else {
+ extents.x1 = 0;
+ extents.y1 = 0;
+ extents.x2 = pWin->drawable.width;
+ extents.y2 = pWin->drawable.height;
+ shaped = xFalse;
+ }
+ break;
+ case ShapeInput:
+ region = wInputShape(pWin);
+ if (region) {
+ extents = *REGION_EXTENTS(pWin->drawable.pScreen, region);
+ shaped = xTrue;
+ } else {
+ extents.x1 = -wBorderWidth (pWin);
+ extents.y1 = -wBorderWidth (pWin);
+ extents.x2 = pWin->drawable.width + wBorderWidth (pWin);
+ extents.y2 = pWin->drawable.height + wBorderWidth (pWin);
+ shaped = xFalse;
+ }
+ break;
+ default:
+ return;
+ }
+ for (pShapeEvent = *pHead; pShapeEvent; pShapeEvent = pShapeEvent->next) {
+ client = pShapeEvent->client;
+ if (client == serverClient || client->clientGone)
+ continue;
+ se.type = ShapeNotify + ShapeEventBase;
+ se.kind = which;
+ se.window = pWin->drawable.id;
+ se.sequenceNumber = client->sequence;
+ se.x = extents.x1;
+ se.y = extents.y1;
+ se.width = extents.x2 - extents.x1;
+ se.height = extents.y2 - extents.y1;
+ se.time = currentTime.milliseconds;
+ se.shaped = shaped;
+ WriteEventsToClient (client, 1, (xEvent *) &se);
+ }
+}
+
+static int
+ProcShapeInputSelected (ClientPtr client)
+{
+ REQUEST(xShapeInputSelectedReq);
+ WindowPtr pWin;
+ ShapeEventPtr pShapeEvent, *pHead;
+ int enabled, rc;
+ xShapeInputSelectedReply rep;
+ int n;
+
+ REQUEST_SIZE_MATCH (xShapeInputSelectedReq);
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ rc = dixLookupResourceByType((pointer *)&pHead, pWin->drawable.id,
+ ShapeEventType, client, DixReadAccess);
+ if (rc != Success && rc != BadValue)
+ return rc;
+ enabled = xFalse;
+ if (pHead) {
+ for (pShapeEvent = *pHead;
+ pShapeEvent;
+ pShapeEvent = pShapeEvent->next)
+ {
+ if (pShapeEvent->client == client) {
+ enabled = xTrue;
+ break;
+ }
+ }
+ }
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.enabled = enabled;
+ if (client->swapped) {
+ swaps (&rep.sequenceNumber, n);
+ swapl (&rep.length, n);
+ }
+ WriteToClient (client, sizeof (xShapeInputSelectedReply), (char *) &rep);
+ return (client->noClientException);
+}
+
+static int
+ProcShapeGetRectangles (ClientPtr client)
+{
+ REQUEST(xShapeGetRectanglesReq);
+ WindowPtr pWin;
+ xShapeGetRectanglesReply rep;
+ xRectangle *rects;
+ int nrects, i, rc;
+ RegionPtr region;
+ int n;
+
+ REQUEST_SIZE_MATCH(xShapeGetRectanglesReq);
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ switch (stuff->kind) {
+ case ShapeBounding:
+ region = wBoundingShape(pWin);
+ break;
+ case ShapeClip:
+ region = wClipShape(pWin);
+ break;
+ case ShapeInput:
+ region = wInputShape (pWin);
+ break;
+ default:
+ client->errorValue = stuff->kind;
+ return BadValue;
+ }
+ if (!region) {
+ nrects = 1;
+ rects = xalloc (sizeof (xRectangle));
+ if (!rects)
+ return BadAlloc;
+ switch (stuff->kind) {
+ case ShapeBounding:
+ rects->x = - (int) wBorderWidth (pWin);
+ rects->y = - (int) wBorderWidth (pWin);
+ rects->width = pWin->drawable.width + wBorderWidth (pWin);
+ rects->height = pWin->drawable.height + wBorderWidth (pWin);
+ break;
+ case ShapeClip:
+ rects->x = 0;
+ rects->y = 0;
+ rects->width = pWin->drawable.width;
+ rects->height = pWin->drawable.height;
+ break;
+ case ShapeInput:
+ rects->x = - (int) wBorderWidth (pWin);
+ rects->y = - (int) wBorderWidth (pWin);
+ rects->width = pWin->drawable.width + wBorderWidth (pWin);
+ rects->height = pWin->drawable.height + wBorderWidth (pWin);
+ break;
+ }
+ } else {
+ BoxPtr box;
+ nrects = REGION_NUM_RECTS(region);
+ box = REGION_RECTS(region);
+ rects = xalloc (nrects * sizeof (xRectangle));
+ if (!rects && nrects)
+ return BadAlloc;
+ for (i = 0; i < nrects; i++, box++) {
+ rects[i].x = box->x1;
+ rects[i].y = box->y1;
+ rects[i].width = box->x2 - box->x1;
+ rects[i].height = box->y2 - box->y1;
+ }
+ }
+ rep.type = X_Reply;
+ rep.sequenceNumber = client->sequence;
+ rep.length = bytes_to_int32(nrects * sizeof (xRectangle));
+ rep.ordering = YXBanded;
+ rep.nrects = nrects;
+ if (client->swapped) {
+ swaps (&rep.sequenceNumber, n);
+ swapl (&rep.length, n);
+ swapl (&rep.nrects, n);
+ SwapShorts ((short *)rects, (unsigned long)nrects * 4);
+ }
+ WriteToClient (client, sizeof (rep), (char *) &rep);
+ WriteToClient (client, nrects * sizeof (xRectangle), (char *) rects);
+ xfree (rects);
+ return client->noClientException;
+}
+
+static int
+ProcShapeDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+ switch (stuff->data) {
+ case X_ShapeQueryVersion:
+ return ProcShapeQueryVersion (client);
+ case X_ShapeRectangles:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShapeRectangles (client);
+ else
+#endif
+ return ProcShapeRectangles (client);
+ case X_ShapeMask:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShapeMask (client);
+ else
+#endif
+ return ProcShapeMask (client);
+ case X_ShapeCombine:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShapeCombine (client);
+ else
+#endif
+ return ProcShapeCombine (client);
+ case X_ShapeOffset:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShapeOffset (client);
+ else
+#endif
+ return ProcShapeOffset (client);
+ case X_ShapeQueryExtents:
+ return ProcShapeQueryExtents (client);
+ case X_ShapeSelectInput:
+ return ProcShapeSelectInput (client);
+ case X_ShapeInputSelected:
+ return ProcShapeInputSelected (client);
+ case X_ShapeGetRectangles:
+ return ProcShapeGetRectangles (client);
+ default:
+ return BadRequest;
+ }
+}
+
+static void
+SShapeNotifyEvent(xShapeNotifyEvent *from, xShapeNotifyEvent *to)
+{
+ to->type = from->type;
+ to->kind = from->kind;
+ cpswapl (from->window, to->window);
+ cpswaps (from->sequenceNumber, to->sequenceNumber);
+ cpswaps (from->x, to->x);
+ cpswaps (from->y, to->y);
+ cpswaps (from->width, to->width);
+ cpswaps (from->height, to->height);
+ cpswapl (from->time, to->time);
+ to->shaped = from->shaped;
+}
+
+static int
+SProcShapeQueryVersion (ClientPtr client)
+{
+ int n;
+ REQUEST (xShapeQueryVersionReq);
+
+ swaps (&stuff->length, n);
+ return ProcShapeQueryVersion (client);
+}
+
+static int
+SProcShapeRectangles (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeRectanglesReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_AT_LEAST_SIZE (xShapeRectanglesReq);
+ swapl (&stuff->dest, n);
+ swaps (&stuff->xOff, n);
+ swaps (&stuff->yOff, n);
+ SwapRestS(stuff);
+ return ProcShapeRectangles (client);
+}
+
+static int
+SProcShapeMask (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeMaskReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeMaskReq);
+ swapl (&stuff->dest, n);
+ swaps (&stuff->xOff, n);
+ swaps (&stuff->yOff, n);
+ swapl (&stuff->src, n);
+ return ProcShapeMask (client);
+}
+
+static int
+SProcShapeCombine (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeCombineReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeCombineReq);
+ swapl (&stuff->dest, n);
+ swaps (&stuff->xOff, n);
+ swaps (&stuff->yOff, n);
+ swapl (&stuff->src, n);
+ return ProcShapeCombine (client);
+}
+
+static int
+SProcShapeOffset (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeOffsetReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeOffsetReq);
+ swapl (&stuff->dest, n);
+ swaps (&stuff->xOff, n);
+ swaps (&stuff->yOff, n);
+ return ProcShapeOffset (client);
+}
+
+static int
+SProcShapeQueryExtents (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeQueryExtentsReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeQueryExtentsReq);
+ swapl (&stuff->window, n);
+ return ProcShapeQueryExtents (client);
+}
+
+static int
+SProcShapeSelectInput (ClientPtr client)
+{
+ char n;
+ REQUEST (xShapeSelectInputReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeSelectInputReq);
+ swapl (&stuff->window, n);
+ return ProcShapeSelectInput (client);
+}
+
+static int
+SProcShapeInputSelected (ClientPtr client)
+{
+ int n;
+ REQUEST (xShapeInputSelectedReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xShapeInputSelectedReq);
+ swapl (&stuff->window, n);
+ return ProcShapeInputSelected (client);
+}
+
+static int
+SProcShapeGetRectangles (ClientPtr client)
+{
+ REQUEST(xShapeGetRectanglesReq);
+ char n;
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShapeGetRectanglesReq);
+ swapl (&stuff->window, n);
+ return ProcShapeGetRectangles (client);
+}
+
+static int
+SProcShapeDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+ switch (stuff->data) {
+ case X_ShapeQueryVersion:
+ return SProcShapeQueryVersion (client);
+ case X_ShapeRectangles:
+ return SProcShapeRectangles (client);
+ case X_ShapeMask:
+ return SProcShapeMask (client);
+ case X_ShapeCombine:
+ return SProcShapeCombine (client);
+ case X_ShapeOffset:
+ return SProcShapeOffset (client);
+ case X_ShapeQueryExtents:
+ return SProcShapeQueryExtents (client);
+ case X_ShapeSelectInput:
+ return SProcShapeSelectInput (client);
+ case X_ShapeInputSelected:
+ return SProcShapeInputSelected (client);
+ case X_ShapeGetRectangles:
+ return SProcShapeGetRectangles (client);
+ default:
+ return BadRequest;
+ }
+}
diff --git a/xorg-server/Xext/shm.c b/xorg-server/Xext/shm.c index e4f08e2a2..d3393bfed 100644 --- a/xorg-server/Xext/shm.c +++ b/xorg-server/Xext/shm.c @@ -1,1260 +1,1279 @@ -/************************************************************ - -Copyright 1989, 1998 The Open Group - -Permission to use, copy, modify, distribute, and sell this software and its -documentation for any purpose is hereby granted without fee, provided that -the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation. - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of The Open Group shall not be -used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization from The Open Group. - -********************************************************/ - -/* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */ - - -#define SHM - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <sys/types.h> -#include <sys/ipc.h> -#include <sys/shm.h> -#include <unistd.h> -#include <sys/stat.h> -#include <X11/X.h> -#include <X11/Xproto.h> -#include "misc.h" -#include "os.h" -#include "dixstruct.h" -#include "resource.h" -#include "scrnintstr.h" -#include "windowstr.h" -#include "pixmapstr.h" -#include "gcstruct.h" -#include "extnsionst.h" -#include "servermd.h" -#include "shmint.h" -#include "xace.h" -#include <X11/extensions/shmproto.h> -#include <X11/Xfuncproto.h> -#include "protocol-versions.h" - -/* Needed for Solaris cross-zone shared memory extension */ -#ifdef HAVE_SHMCTL64 -#include <sys/ipc_impl.h> -#define SHMSTAT(id, buf) shmctl64(id, IPC_STAT64, buf) -#define SHMSTAT_TYPE struct shmid_ds64 -#define SHMPERM_TYPE struct ipc_perm64 -#define SHM_PERM(buf) buf.shmx_perm -#define SHM_SEGSZ(buf) buf.shmx_segsz -#define SHMPERM_UID(p) p->ipcx_uid -#define SHMPERM_CUID(p) p->ipcx_cuid -#define SHMPERM_GID(p) p->ipcx_gid -#define SHMPERM_CGID(p) p->ipcx_cgid -#define SHMPERM_MODE(p) p->ipcx_mode -#define SHMPERM_ZONEID(p) p->ipcx_zoneid -#else -#define SHMSTAT(id, buf) shmctl(id, IPC_STAT, buf) -#define SHMSTAT_TYPE struct shmid_ds -#define SHMPERM_TYPE struct ipc_perm -#define SHM_PERM(buf) buf.shm_perm -#define SHM_SEGSZ(buf) buf.shm_segsz -#define SHMPERM_UID(p) p->uid -#define SHMPERM_CUID(p) p->cuid -#define SHMPERM_GID(p) p->gid -#define SHMPERM_CGID(p) p->cgid -#define SHMPERM_MODE(p) p->mode -#endif - -#ifdef PANORAMIX -#include "panoramiX.h" -#include "panoramiXsrv.h" -#endif - -#include "modinit.h" - -typedef struct _ShmDesc { - struct _ShmDesc *next; - int shmid; - int refcnt; - char *addr; - Bool writable; - unsigned long size; -} ShmDescRec, *ShmDescPtr; - -static PixmapPtr fbShmCreatePixmap(XSHM_CREATE_PIXMAP_ARGS); -static int ShmDetachSegment( - pointer /* value */, - XID /* shmseg */ - ); -static void ShmResetProc( - ExtensionEntry * /* extEntry */ - ); -static void SShmCompletionEvent( - xShmCompletionEvent * /* from */, - xShmCompletionEvent * /* to */ - ); - -static Bool ShmDestroyPixmap (PixmapPtr pPixmap); - -static DISPATCH_PROC(ProcShmAttach); -static DISPATCH_PROC(ProcShmCreatePixmap); -static DISPATCH_PROC(ProcShmDetach); -static DISPATCH_PROC(ProcShmDispatch); -static DISPATCH_PROC(ProcShmGetImage); -static DISPATCH_PROC(ProcShmPutImage); -static DISPATCH_PROC(ProcShmQueryVersion); -static DISPATCH_PROC(SProcShmAttach); -static DISPATCH_PROC(SProcShmCreatePixmap); -static DISPATCH_PROC(SProcShmDetach); -static DISPATCH_PROC(SProcShmDispatch); -static DISPATCH_PROC(SProcShmGetImage); -static DISPATCH_PROC(SProcShmPutImage); -static DISPATCH_PROC(SProcShmQueryVersion); - -static unsigned char ShmReqCode; -int ShmCompletionCode; -int BadShmSegCode; -RESTYPE ShmSegType; -static ShmDescPtr Shmsegs; -static Bool sharedPixmaps; -static ShmFuncsPtr shmFuncs[MAXSCREENS]; -static DestroyPixmapProcPtr destroyPixmap[MAXSCREENS]; -static int shmPixmapPrivateIndex; -static DevPrivateKey shmPixmapPrivate = &shmPixmapPrivateIndex; -static ShmFuncs miFuncs = {NULL, NULL}; -static ShmFuncs fbFuncs = {fbShmCreatePixmap, NULL}; - -#define VERIFY_SHMSEG(shmseg,shmdesc,client) \ -{ \ - int rc; \ - rc = dixLookupResourceByType((pointer *)&(shmdesc), shmseg, ShmSegType, \ - client, DixReadAccess); \ - if (rc != Success) \ - return (rc == BadValue) ? BadShmSegCode : rc; \ -} - -#define VERIFY_SHMPTR(shmseg,offset,needwrite,shmdesc,client) \ -{ \ - VERIFY_SHMSEG(shmseg, shmdesc, client); \ - if ((offset & 3) || (offset > shmdesc->size)) \ - { \ - client->errorValue = offset; \ - return BadValue; \ - } \ - if (needwrite && !shmdesc->writable) \ - return BadAccess; \ -} - -#define VERIFY_SHMSIZE(shmdesc,offset,len,client) \ -{ \ - if ((offset + len) > shmdesc->size) \ - { \ - return BadAccess; \ - } \ -} - - -#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__CYGWIN__) || defined(__DragonFly__) -#include <sys/signal.h> - -static Bool badSysCall = FALSE; - -static void -SigSysHandler(int signo) -{ - badSysCall = TRUE; -} - -static Bool CheckForShmSyscall(void) -{ - void (*oldHandler)(); - int shmid = -1; - - /* If no SHM support in the kernel, the bad syscall will generate SIGSYS */ - oldHandler = signal(SIGSYS, SigSysHandler); - - badSysCall = FALSE; - shmid = shmget(IPC_PRIVATE, 4096, IPC_CREAT); - - if (shmid != -1) - { - /* Successful allocation - clean up */ - shmctl(shmid, IPC_RMID, NULL); - } - else - { - /* Allocation failed */ - badSysCall = TRUE; - } - signal(SIGSYS, oldHandler); - return(!badSysCall); -} - -#define MUST_CHECK_FOR_SHM_SYSCALL - -#endif - -void -ShmExtensionInit(INITARGS) -{ - ExtensionEntry *extEntry; - int i; - -#ifdef MUST_CHECK_FOR_SHM_SYSCALL - if (!CheckForShmSyscall()) - { - ErrorF("MIT-SHM extension disabled due to lack of kernel support\n"); - return; - } -#endif - - sharedPixmaps = xFalse; - { - sharedPixmaps = xTrue; - for (i = 0; i < screenInfo.numScreens; i++) - { - if (!shmFuncs[i]) - shmFuncs[i] = &miFuncs; - if (!shmFuncs[i]->CreatePixmap) - sharedPixmaps = xFalse; - } - if (sharedPixmaps) - for (i = 0; i < screenInfo.numScreens; i++) - { - destroyPixmap[i] = screenInfo.screens[i]->DestroyPixmap; - screenInfo.screens[i]->DestroyPixmap = ShmDestroyPixmap; - } - } - ShmSegType = CreateNewResourceType(ShmDetachSegment); - if (ShmSegType && - (extEntry = AddExtension(SHMNAME, ShmNumberEvents, ShmNumberErrors, - ProcShmDispatch, SProcShmDispatch, - ShmResetProc, StandardMinorOpcode))) - { - ShmReqCode = (unsigned char)extEntry->base; - ShmCompletionCode = extEntry->eventBase; - BadShmSegCode = extEntry->errorBase; - EventSwapVector[ShmCompletionCode] = (EventSwapPtr) SShmCompletionEvent; - } -} - -/*ARGSUSED*/ -static void -ShmResetProc(ExtensionEntry *extEntry) -{ - int i; - - for (i = 0; i < MAXSCREENS; i++) - { - shmFuncs[i] = NULL; - } -} - -void -ShmRegisterFuncs(ScreenPtr pScreen, ShmFuncsPtr funcs) -{ - shmFuncs[pScreen->myNum] = funcs; -} - -static Bool -ShmDestroyPixmap (PixmapPtr pPixmap) -{ - ScreenPtr pScreen = pPixmap->drawable.pScreen; - Bool ret; - if (pPixmap->refcnt == 1) - { - ShmDescPtr shmdesc; - shmdesc = (ShmDescPtr)dixLookupPrivate(&pPixmap->devPrivates, - shmPixmapPrivate); - if (shmdesc) - ShmDetachSegment ((pointer) shmdesc, pPixmap->drawable.id); - } - - pScreen->DestroyPixmap = destroyPixmap[pScreen->myNum]; - ret = (*pScreen->DestroyPixmap) (pPixmap); - destroyPixmap[pScreen->myNum] = pScreen->DestroyPixmap; - pScreen->DestroyPixmap = ShmDestroyPixmap; - return ret; -} - -void -ShmRegisterFbFuncs(ScreenPtr pScreen) -{ - shmFuncs[pScreen->myNum] = &fbFuncs; -} - -static int -ProcShmQueryVersion(ClientPtr client) -{ - xShmQueryVersionReply rep; - int n; - - REQUEST_SIZE_MATCH(xShmQueryVersionReq); - memset(&rep, 0, sizeof(xShmQueryVersionReply)); - rep.type = X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.sharedPixmaps = sharedPixmaps; - rep.pixmapFormat = sharedPixmaps ? ZPixmap : 0; - rep.majorVersion = SERVER_SHM_MAJOR_VERSION; - rep.minorVersion = SERVER_SHM_MINOR_VERSION; - rep.uid = geteuid(); - rep.gid = getegid(); - if (client->swapped) { - swaps(&rep.sequenceNumber, n); - swapl(&rep.length, n); - swaps(&rep.majorVersion, n); - swaps(&rep.minorVersion, n); - swaps(&rep.uid, n); - swaps(&rep.gid, n); - } - WriteToClient(client, sizeof(xShmQueryVersionReply), (char *)&rep); - return (client->noClientException); -} - -/* - * Simulate the access() system call for a shared memory segement, - * using the credentials from the client if available - */ -static int -shm_access(ClientPtr client, SHMPERM_TYPE *perm, int readonly) -{ - int uid, gid; - mode_t mask; - int uidset = 0, gidset = 0; - LocalClientCredRec *lcc; - - if (GetLocalClientCreds(client, &lcc) != -1) { - - if (lcc->fieldsSet & LCC_UID_SET) { - uid = lcc->euid; - uidset = 1; - } - if (lcc->fieldsSet & LCC_GID_SET) { - gid = lcc->egid; - gidset = 1; - } - -#if defined(HAVE_GETZONEID) && defined(SHMPERM_ZONEID) - if ( ((lcc->fieldsSet & LCC_ZID_SET) == 0) || (lcc->zoneid == -1) - || (lcc->zoneid != SHMPERM_ZONEID(perm))) { - uidset = 0; - gidset = 0; - } -#endif - FreeLocalClientCreds(lcc); - - if (uidset) { - /* User id 0 always gets access */ - if (uid == 0) { - return 0; - } - /* Check the owner */ - if (SHMPERM_UID(perm) == uid || SHMPERM_CUID(perm) == uid) { - mask = S_IRUSR; - if (!readonly) { - mask |= S_IWUSR; - } - return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1; - } - } - - if (gidset) { - /* Check the group */ - if (SHMPERM_GID(perm) == gid || SHMPERM_CGID(perm) == gid) { - mask = S_IRGRP; - if (!readonly) { - mask |= S_IWGRP; - } - return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1; - } - } - } - /* Otherwise, check everyone else */ - mask = S_IROTH; - if (!readonly) { - mask |= S_IWOTH; - } - return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1; -} - -static int -ProcShmAttach(ClientPtr client) -{ - SHMSTAT_TYPE buf; - ShmDescPtr shmdesc; - REQUEST(xShmAttachReq); - - REQUEST_SIZE_MATCH(xShmAttachReq); - LEGAL_NEW_RESOURCE(stuff->shmseg, client); - if ((stuff->readOnly != xTrue) && (stuff->readOnly != xFalse)) - { - client->errorValue = stuff->readOnly; - return(BadValue); - } - for (shmdesc = Shmsegs; - shmdesc && (shmdesc->shmid != stuff->shmid); - shmdesc = shmdesc->next) - ; - if (shmdesc) - { - if (!stuff->readOnly && !shmdesc->writable) - return BadAccess; - shmdesc->refcnt++; - } - else - { - shmdesc = xalloc(sizeof(ShmDescRec)); - if (!shmdesc) - return BadAlloc; - shmdesc->addr = shmat(stuff->shmid, 0, - stuff->readOnly ? SHM_RDONLY : 0); - if ((shmdesc->addr == ((char *)-1)) || - SHMSTAT(stuff->shmid, &buf)) - { - xfree(shmdesc); - return BadAccess; - } - - /* The attach was performed with root privs. We must - * do manual checking of access rights for the credentials - * of the client */ - - if (shm_access(client, &(SHM_PERM(buf)), stuff->readOnly) == -1) { - shmdt(shmdesc->addr); - xfree(shmdesc); - return BadAccess; - } - - shmdesc->shmid = stuff->shmid; - shmdesc->refcnt = 1; - shmdesc->writable = !stuff->readOnly; - shmdesc->size = SHM_SEGSZ(buf); - shmdesc->next = Shmsegs; - Shmsegs = shmdesc; - } - if (!AddResource(stuff->shmseg, ShmSegType, (pointer)shmdesc)) - return BadAlloc; - return(client->noClientException); -} - -/*ARGSUSED*/ -static int -ShmDetachSegment(pointer value, /* must conform to DeleteType */ - XID shmseg) -{ - ShmDescPtr shmdesc = (ShmDescPtr)value; - ShmDescPtr *prev; - - if (--shmdesc->refcnt) - return TRUE; - shmdt(shmdesc->addr); - for (prev = &Shmsegs; *prev != shmdesc; prev = &(*prev)->next) - ; - *prev = shmdesc->next; - xfree(shmdesc); - return Success; -} - -static int -ProcShmDetach(ClientPtr client) -{ - ShmDescPtr shmdesc; - REQUEST(xShmDetachReq); - - REQUEST_SIZE_MATCH(xShmDetachReq); - VERIFY_SHMSEG(stuff->shmseg, shmdesc, client); - FreeResource(stuff->shmseg, RT_NONE); - return(client->noClientException); -} - -/* - * If the given request doesn't exactly match PutImage's constraints, - * wrap the image in a scratch pixmap header and let CopyArea sort it out. - */ -static void -doShmPutImage(DrawablePtr dst, GCPtr pGC, - int depth, unsigned int format, - int w, int h, int sx, int sy, int sw, int sh, int dx, int dy, - char *data) -{ - PixmapPtr pPixmap; - - pPixmap = GetScratchPixmapHeader(dst->pScreen, w, h, depth, - BitsPerPixel(depth), - PixmapBytePad(w, depth), - data); - if (!pPixmap) - return; - pGC->ops->CopyArea((DrawablePtr)pPixmap, dst, pGC, sx, sy, sw, sh, dx, dy); - FreeScratchPixmapHeader(pPixmap); -} - -#ifdef PANORAMIX -static int -ProcPanoramiXShmPutImage(ClientPtr client) -{ - int j, result, orig_x, orig_y; - PanoramiXRes *draw, *gc; - Bool sendEvent, isRoot; - - REQUEST(xShmPutImageReq); - REQUEST_SIZE_MATCH(xShmPutImageReq); - - result = dixLookupResourceByClass((pointer *)&draw, stuff->drawable, - XRC_DRAWABLE, client, DixWriteAccess); - if (result != Success) - return (result == BadValue) ? BadDrawable : result; - - result = dixLookupResourceByType((pointer *)&gc, stuff->gc, - XRT_GC, client, DixReadAccess); - if (result != Success) - return (result == BadValue) ? BadGC : result; - - isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; - - orig_x = stuff->dstX; - orig_y = stuff->dstY; - sendEvent = stuff->sendEvent; - stuff->sendEvent = 0; - FOR_NSCREENS(j) { - if(!j) stuff->sendEvent = sendEvent; - stuff->drawable = draw->info[j].id; - stuff->gc = gc->info[j].id; - if (isRoot) { - stuff->dstX = orig_x - panoramiXdataPtr[j].x; - stuff->dstY = orig_y - panoramiXdataPtr[j].y; - } - result = ProcShmPutImage(client); - if(result != client->noClientException) break; - } - return(result); -} - -static int -ProcPanoramiXShmGetImage(ClientPtr client) -{ - PanoramiXRes *draw; - DrawablePtr drawables[MAXSCREENS]; - DrawablePtr pDraw; - xShmGetImageReply xgi; - ShmDescPtr shmdesc; - int i, x, y, w, h, format, rc; - Mask plane = 0, planemask; - long lenPer = 0, length, widthBytesLine; - Bool isRoot; - - REQUEST(xShmGetImageReq); - - REQUEST_SIZE_MATCH(xShmGetImageReq); - - if ((stuff->format != XYPixmap) && (stuff->format != ZPixmap)) { - client->errorValue = stuff->format; - return(BadValue); - } - - rc = dixLookupResourceByClass((pointer *)&draw, stuff->drawable, - XRC_DRAWABLE, client, DixWriteAccess); - if (rc != Success) - return (rc == BadValue) ? BadDrawable : rc; - - if (draw->type == XRT_PIXMAP) - return ProcShmGetImage(client); - - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, - DixReadAccess); - if (rc != Success) - return rc; - - VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); - - x = stuff->x; - y = stuff->y; - w = stuff->width; - h = stuff->height; - format = stuff->format; - planemask = stuff->planeMask; - - isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root; - - if(isRoot) { - if( /* check for being onscreen */ - x < 0 || x + w > PanoramiXPixWidth || - y < 0 || y + h > PanoramiXPixHeight ) - return(BadMatch); - } else { - if( /* check for being onscreen */ - panoramiXdataPtr[0].x + pDraw->x + x < 0 || - panoramiXdataPtr[0].x + pDraw->x + x + w > PanoramiXPixWidth || - panoramiXdataPtr[0].y + pDraw->y + y < 0 || - panoramiXdataPtr[0].y + pDraw->y + y + h > PanoramiXPixHeight || - /* check for being inside of border */ - x < - wBorderWidth((WindowPtr)pDraw) || - x + w > wBorderWidth((WindowPtr)pDraw) + (int)pDraw->width || - y < -wBorderWidth((WindowPtr)pDraw) || - y + h > wBorderWidth ((WindowPtr)pDraw) + (int)pDraw->height) - return(BadMatch); - } - - drawables[0] = pDraw; - for(i = 1; i < PanoramiXNumScreens; i++) { - rc = dixLookupDrawable(drawables+i, draw->info[i].id, client, 0, - DixReadAccess); - if (rc != Success) - return rc; - } - - xgi.visual = wVisual(((WindowPtr)pDraw)); - xgi.type = X_Reply; - xgi.length = 0; - xgi.sequenceNumber = client->sequence; - xgi.depth = pDraw->depth; - - if(format == ZPixmap) { - widthBytesLine = PixmapBytePad(w, pDraw->depth); - length = widthBytesLine * h; - } else { - widthBytesLine = PixmapBytePad(w, 1); - lenPer = widthBytesLine * h; - plane = ((Mask)1) << (pDraw->depth - 1); - length = lenPer * Ones(planemask & (plane | (plane - 1))); - } - - VERIFY_SHMSIZE(shmdesc, stuff->offset, length, client); - xgi.size = length; - - if (length == 0) {/* nothing to do */ } - else if (format == ZPixmap) { - XineramaGetImageData(drawables, x, y, w, h, format, planemask, - shmdesc->addr + stuff->offset, - widthBytesLine, isRoot); - } else { - - length = stuff->offset; - for (; plane; plane >>= 1) { - if (planemask & plane) { - XineramaGetImageData(drawables, x, y, w, h, - format, plane, shmdesc->addr + length, - widthBytesLine, isRoot); - length += lenPer; - } - } - } - - if (client->swapped) { - int n; - swaps(&xgi.sequenceNumber, n); - swapl(&xgi.length, n); - swapl(&xgi.visual, n); - swapl(&xgi.size, n); - } - WriteToClient(client, sizeof(xShmGetImageReply), (char *)&xgi); - - return(client->noClientException); -} - -static int -ProcPanoramiXShmCreatePixmap(ClientPtr client) -{ - ScreenPtr pScreen = NULL; - PixmapPtr pMap = NULL; - DrawablePtr pDraw; - DepthPtr pDepth; - int i, j, result, rc; - ShmDescPtr shmdesc; - REQUEST(xShmCreatePixmapReq); - unsigned int width, height, depth; - unsigned long size; - PanoramiXRes *newPix; - - REQUEST_SIZE_MATCH(xShmCreatePixmapReq); - client->errorValue = stuff->pid; - if (!sharedPixmaps) - return BadImplementation; - LEGAL_NEW_RESOURCE(stuff->pid, client); - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY, - DixGetAttrAccess); - if (rc != Success) - return rc; - - VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); - - width = stuff->width; - height = stuff->height; - depth = stuff->depth; - if (!width || !height || !depth) - { - client->errorValue = 0; - return BadValue; - } - if (width > 32767 || height > 32767) - return BadAlloc; - - if (stuff->depth != 1) - { - pDepth = pDraw->pScreen->allowedDepths; - for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++) - if (pDepth->depth == stuff->depth) - goto CreatePmap; - client->errorValue = stuff->depth; - return BadValue; - } - -CreatePmap: - size = PixmapBytePad(width, depth) * height; - if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) { - if (size < width * height) - return BadAlloc; - } - /* thankfully, offset is unsigned */ - if (stuff->offset + size < size) - return BadAlloc; - - VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client); - - if(!(newPix = xalloc(sizeof(PanoramiXRes)))) - return BadAlloc; - - newPix->type = XRT_PIXMAP; - newPix->u.pix.shared = TRUE; - newPix->info[0].id = stuff->pid; - for(j = 1; j < PanoramiXNumScreens; j++) - newPix->info[j].id = FakeClientID(client->index); - - result = (client->noClientException); - - FOR_NSCREENS(j) { - pScreen = screenInfo.screens[j]; - - pMap = (*shmFuncs[j]->CreatePixmap)(pScreen, - stuff->width, stuff->height, stuff->depth, - shmdesc->addr + stuff->offset); - - if (pMap) { - dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc); - shmdesc->refcnt++; - pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER; - pMap->drawable.id = newPix->info[j].id; - if (!AddResource(newPix->info[j].id, RT_PIXMAP, (pointer)pMap)) { - (*pScreen->DestroyPixmap)(pMap); - result = BadAlloc; - break; - } - } else { - result = BadAlloc; - break; - } - } - - if(result == BadAlloc) { - while(j--) { - (*pScreen->DestroyPixmap)(pMap); - FreeResource(newPix->info[j].id, RT_NONE); - } - xfree(newPix); - } else - AddResource(stuff->pid, XRT_PIXMAP, newPix); - - return result; -} - -#endif - -static int -ProcShmPutImage(ClientPtr client) -{ - GCPtr pGC; - DrawablePtr pDraw; - long length; - ShmDescPtr shmdesc; - REQUEST(xShmPutImageReq); - - REQUEST_SIZE_MATCH(xShmPutImageReq); - VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess); - VERIFY_SHMPTR(stuff->shmseg, stuff->offset, FALSE, shmdesc, client); - if ((stuff->sendEvent != xTrue) && (stuff->sendEvent != xFalse)) - return BadValue; - if (stuff->format == XYBitmap) - { - if (stuff->depth != 1) - return BadMatch; - length = PixmapBytePad(stuff->totalWidth, 1); - } - else if (stuff->format == XYPixmap) - { - if (pDraw->depth != stuff->depth) - return BadMatch; - length = PixmapBytePad(stuff->totalWidth, 1); - length *= stuff->depth; - } - else if (stuff->format == ZPixmap) - { - if (pDraw->depth != stuff->depth) - return BadMatch; - length = PixmapBytePad(stuff->totalWidth, stuff->depth); - } - else - { - client->errorValue = stuff->format; - return BadValue; - } - - /* - * There's a potential integer overflow in this check: - * VERIFY_SHMSIZE(shmdesc, stuff->offset, length * stuff->totalHeight, - * client); - * the version below ought to avoid it - */ - if (stuff->totalHeight != 0 && - length > (shmdesc->size - stuff->offset)/stuff->totalHeight) { - client->errorValue = stuff->totalWidth; - return BadValue; - } - if (stuff->srcX > stuff->totalWidth) - { - client->errorValue = stuff->srcX; - return BadValue; - } - if (stuff->srcY > stuff->totalHeight) - { - client->errorValue = stuff->srcY; - return BadValue; - } - if ((stuff->srcX + stuff->srcWidth) > stuff->totalWidth) - { - client->errorValue = stuff->srcWidth; - return BadValue; - } - if ((stuff->srcY + stuff->srcHeight) > stuff->totalHeight) - { - client->errorValue = stuff->srcHeight; - return BadValue; - } - - if ((((stuff->format == ZPixmap) && (stuff->srcX == 0)) || - ((stuff->format != ZPixmap) && - (stuff->srcX < screenInfo.bitmapScanlinePad) && - ((stuff->format == XYBitmap) || - ((stuff->srcY == 0) && - (stuff->srcHeight == stuff->totalHeight))))) && - ((stuff->srcX + stuff->srcWidth) == stuff->totalWidth)) - (*pGC->ops->PutImage) (pDraw, pGC, stuff->depth, - stuff->dstX, stuff->dstY, - stuff->totalWidth, stuff->srcHeight, - stuff->srcX, stuff->format, - shmdesc->addr + stuff->offset + - (stuff->srcY * length)); - else - doShmPutImage(pDraw, pGC, stuff->depth, stuff->format, - stuff->totalWidth, stuff->totalHeight, - stuff->srcX, stuff->srcY, - stuff->srcWidth, stuff->srcHeight, - stuff->dstX, stuff->dstY, - shmdesc->addr + stuff->offset); - - if (stuff->sendEvent) - { - xShmCompletionEvent ev; - - ev.type = ShmCompletionCode; - ev.drawable = stuff->drawable; - ev.sequenceNumber = client->sequence; - ev.minorEvent = X_ShmPutImage; - ev.majorEvent = ShmReqCode; - ev.shmseg = stuff->shmseg; - ev.offset = stuff->offset; - WriteEventsToClient(client, 1, (xEvent *) &ev); - } - - return (client->noClientException); -} - - - -static int -ProcShmGetImage(ClientPtr client) -{ - DrawablePtr pDraw; - long lenPer = 0, length; - Mask plane = 0; - xShmGetImageReply xgi; - ShmDescPtr shmdesc; - int n, rc; - - REQUEST(xShmGetImageReq); - - REQUEST_SIZE_MATCH(xShmGetImageReq); - if ((stuff->format != XYPixmap) && (stuff->format != ZPixmap)) - { - client->errorValue = stuff->format; - return(BadValue); - } - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0, - DixReadAccess); - if (rc != Success) - return rc; - VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); - if (pDraw->type == DRAWABLE_WINDOW) - { - if( /* check for being viewable */ - !((WindowPtr) pDraw)->realized || - /* check for being on screen */ - pDraw->x + stuff->x < 0 || - pDraw->x + stuff->x + (int)stuff->width > pDraw->pScreen->width || - pDraw->y + stuff->y < 0 || - pDraw->y + stuff->y + (int)stuff->height > pDraw->pScreen->height || - /* check for being inside of border */ - stuff->x < - wBorderWidth((WindowPtr)pDraw) || - stuff->x + (int)stuff->width > - wBorderWidth((WindowPtr)pDraw) + (int)pDraw->width || - stuff->y < -wBorderWidth((WindowPtr)pDraw) || - stuff->y + (int)stuff->height > - wBorderWidth((WindowPtr)pDraw) + (int)pDraw->height - ) - return(BadMatch); - xgi.visual = wVisual(((WindowPtr)pDraw)); - } - else - { - if (stuff->x < 0 || - stuff->x+(int)stuff->width > pDraw->width || - stuff->y < 0 || - stuff->y+(int)stuff->height > pDraw->height - ) - return(BadMatch); - xgi.visual = None; - } - xgi.type = X_Reply; - xgi.length = 0; - xgi.sequenceNumber = client->sequence; - xgi.depth = pDraw->depth; - if(stuff->format == ZPixmap) - { - length = PixmapBytePad(stuff->width, pDraw->depth) * stuff->height; - } - else - { - lenPer = PixmapBytePad(stuff->width, 1) * stuff->height; - plane = ((Mask)1) << (pDraw->depth - 1); - /* only planes asked for */ - length = lenPer * Ones(stuff->planeMask & (plane | (plane - 1))); - } - - VERIFY_SHMSIZE(shmdesc, stuff->offset, length, client); - xgi.size = length; - - if (length == 0) - { - /* nothing to do */ - } - else if (stuff->format == ZPixmap) - { - (*pDraw->pScreen->GetImage)(pDraw, stuff->x, stuff->y, - stuff->width, stuff->height, - stuff->format, stuff->planeMask, - shmdesc->addr + stuff->offset); - } - else - { - - length = stuff->offset; - for (; plane; plane >>= 1) - { - if (stuff->planeMask & plane) - { - (*pDraw->pScreen->GetImage)(pDraw, - stuff->x, stuff->y, - stuff->width, stuff->height, - stuff->format, plane, - shmdesc->addr + length); - length += lenPer; - } - } - } - - if (client->swapped) { - swaps(&xgi.sequenceNumber, n); - swapl(&xgi.length, n); - swapl(&xgi.visual, n); - swapl(&xgi.size, n); - } - WriteToClient(client, sizeof(xShmGetImageReply), (char *)&xgi); - - return(client->noClientException); -} - -static PixmapPtr -fbShmCreatePixmap (ScreenPtr pScreen, - int width, int height, int depth, char *addr) -{ - PixmapPtr pPixmap; - - pPixmap = (*pScreen->CreatePixmap)(pScreen, 0, 0, pScreen->rootDepth, 0); - if (!pPixmap) - return NullPixmap; - - if (!(*pScreen->ModifyPixmapHeader)(pPixmap, width, height, depth, - BitsPerPixel(depth), PixmapBytePad(width, depth), (pointer)addr)) { - (*pScreen->DestroyPixmap)(pPixmap); - return NullPixmap; - } - return pPixmap; -} - -static int -ProcShmCreatePixmap(ClientPtr client) -{ - PixmapPtr pMap; - DrawablePtr pDraw; - DepthPtr pDepth; - int i, rc; - ShmDescPtr shmdesc; - REQUEST(xShmCreatePixmapReq); - unsigned int width, height, depth; - unsigned long size; - - REQUEST_SIZE_MATCH(xShmCreatePixmapReq); - client->errorValue = stuff->pid; - if (!sharedPixmaps) - return BadImplementation; - LEGAL_NEW_RESOURCE(stuff->pid, client); - rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY, - DixGetAttrAccess); - if (rc != Success) - return rc; - - VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client); - - width = stuff->width; - height = stuff->height; - depth = stuff->depth; - if (!width || !height || !depth) - { - client->errorValue = 0; - return BadValue; - } - if (width > 32767 || height > 32767) - return BadAlloc; - - if (stuff->depth != 1) - { - pDepth = pDraw->pScreen->allowedDepths; - for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++) - if (pDepth->depth == stuff->depth) - goto CreatePmap; - client->errorValue = stuff->depth; - return BadValue; - } - -CreatePmap: - size = PixmapBytePad(width, depth) * height; - if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) { - if (size < width * height) - return BadAlloc; - } - /* thankfully, offset is unsigned */ - if (stuff->offset + size < size) - return BadAlloc; - - VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client); - pMap = (*shmFuncs[pDraw->pScreen->myNum]->CreatePixmap)( - pDraw->pScreen, stuff->width, - stuff->height, stuff->depth, - shmdesc->addr + stuff->offset); - if (pMap) - { - rc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, RT_PIXMAP, - pMap, RT_NONE, NULL, DixCreateAccess); - if (rc != Success) { - pDraw->pScreen->DestroyPixmap(pMap); - return rc; - } - dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc); - shmdesc->refcnt++; - pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER; - pMap->drawable.id = stuff->pid; - if (AddResource(stuff->pid, RT_PIXMAP, (pointer)pMap)) - { - return(client->noClientException); - } - pDraw->pScreen->DestroyPixmap(pMap); - } - return (BadAlloc); -} - -static int -ProcShmDispatch (ClientPtr client) -{ - REQUEST(xReq); - switch (stuff->data) - { - case X_ShmQueryVersion: - return ProcShmQueryVersion(client); - case X_ShmAttach: - return ProcShmAttach(client); - case X_ShmDetach: - return ProcShmDetach(client); - case X_ShmPutImage: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShmPutImage(client); -#endif - return ProcShmPutImage(client); - case X_ShmGetImage: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShmGetImage(client); -#endif - return ProcShmGetImage(client); - case X_ShmCreatePixmap: -#ifdef PANORAMIX - if ( !noPanoramiXExtension ) - return ProcPanoramiXShmCreatePixmap(client); -#endif - return ProcShmCreatePixmap(client); - default: - return BadRequest; - } -} - -static void -SShmCompletionEvent(xShmCompletionEvent *from, xShmCompletionEvent *to) -{ - to->type = from->type; - cpswaps(from->sequenceNumber, to->sequenceNumber); - cpswapl(from->drawable, to->drawable); - cpswaps(from->minorEvent, to->minorEvent); - to->majorEvent = from->majorEvent; - cpswapl(from->shmseg, to->shmseg); - cpswapl(from->offset, to->offset); -} - -static int -SProcShmQueryVersion(ClientPtr client) -{ - int n; - REQUEST(xShmQueryVersionReq); - - swaps(&stuff->length, n); - return ProcShmQueryVersion(client); -} - -static int -SProcShmAttach(ClientPtr client) -{ - int n; - REQUEST(xShmAttachReq); - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xShmAttachReq); - swapl(&stuff->shmseg, n); - swapl(&stuff->shmid, n); - return ProcShmAttach(client); -} - -static int -SProcShmDetach(ClientPtr client) -{ - int n; - REQUEST(xShmDetachReq); - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xShmDetachReq); - swapl(&stuff->shmseg, n); - return ProcShmDetach(client); -} - -static int -SProcShmPutImage(ClientPtr client) -{ - int n; - REQUEST(xShmPutImageReq); - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xShmPutImageReq); - swapl(&stuff->drawable, n); - swapl(&stuff->gc, n); - swaps(&stuff->totalWidth, n); - swaps(&stuff->totalHeight, n); - swaps(&stuff->srcX, n); - swaps(&stuff->srcY, n); - swaps(&stuff->srcWidth, n); - swaps(&stuff->srcHeight, n); - swaps(&stuff->dstX, n); - swaps(&stuff->dstY, n); - swapl(&stuff->shmseg, n); - swapl(&stuff->offset, n); - return ProcShmPutImage(client); -} - -static int -SProcShmGetImage(ClientPtr client) -{ - int n; - REQUEST(xShmGetImageReq); - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xShmGetImageReq); - swapl(&stuff->drawable, n); - swaps(&stuff->x, n); - swaps(&stuff->y, n); - swaps(&stuff->width, n); - swaps(&stuff->height, n); - swapl(&stuff->planeMask, n); - swapl(&stuff->shmseg, n); - swapl(&stuff->offset, n); - return ProcShmGetImage(client); -} - -static int -SProcShmCreatePixmap(ClientPtr client) -{ - int n; - REQUEST(xShmCreatePixmapReq); - swaps(&stuff->length, n); - REQUEST_SIZE_MATCH(xShmCreatePixmapReq); - swapl(&stuff->pid, n); - swapl(&stuff->drawable, n); - swaps(&stuff->width, n); - swaps(&stuff->height, n); - swapl(&stuff->shmseg, n); - swapl(&stuff->offset, n); - return ProcShmCreatePixmap(client); -} - -static int -SProcShmDispatch (ClientPtr client) -{ - REQUEST(xReq); - switch (stuff->data) - { - case X_ShmQueryVersion: - return SProcShmQueryVersion(client); - case X_ShmAttach: - return SProcShmAttach(client); - case X_ShmDetach: - return SProcShmDetach(client); - case X_ShmPutImage: - return SProcShmPutImage(client); - case X_ShmGetImage: - return SProcShmGetImage(client); - case X_ShmCreatePixmap: - return SProcShmCreatePixmap(client); - default: - return BadRequest; - } -} +/************************************************************
+
+Copyright 1989, 1998 The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+********************************************************/
+
+/* THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION */
+
+
+#define SHM
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <sys/types.h>
+#if !defined(_MSC_VER)
+#include <sys/ipc.h>
+#include <sys/shm.h>
+#endif
+#include <unistd.h>
+#include <sys/stat.h>
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "misc.h"
+#include "os.h"
+#include "dixstruct.h"
+#include "resource.h"
+#include "scrnintstr.h"
+#include "windowstr.h"
+#include "pixmapstr.h"
+#include "gcstruct.h"
+#include "extnsionst.h"
+#include "servermd.h"
+#include "shmint.h"
+#include "xace.h"
+#include <X11/extensions/shmproto.h>
+#include <X11/Xfuncproto.h>
+#include "protocol-versions.h"
+
+/* Needed for Solaris cross-zone shared memory extension */
+#ifdef HAVE_SHMCTL64
+#include <sys/ipc_impl.h>
+#define SHMSTAT(id, buf) shmctl64(id, IPC_STAT64, buf)
+#define SHMSTAT_TYPE struct shmid_ds64
+#define SHMPERM_TYPE struct ipc_perm64
+#define SHM_PERM(buf) buf.shmx_perm
+#define SHM_SEGSZ(buf) buf.shmx_segsz
+#define SHMPERM_UID(p) p->ipcx_uid
+#define SHMPERM_CUID(p) p->ipcx_cuid
+#define SHMPERM_GID(p) p->ipcx_gid
+#define SHMPERM_CGID(p) p->ipcx_cgid
+#define SHMPERM_MODE(p) p->ipcx_mode
+#define SHMPERM_ZONEID(p) p->ipcx_zoneid
+#else
+#define SHMSTAT(id, buf) shmctl(id, IPC_STAT, buf)
+#define SHMSTAT_TYPE struct shmid_ds
+#define SHMPERM_TYPE struct ipc_perm
+#define SHM_PERM(buf) buf.shm_perm
+#define SHM_SEGSZ(buf) buf.shm_segsz
+#define SHMPERM_UID(p) p->uid
+#define SHMPERM_CUID(p) p->cuid
+#define SHMPERM_GID(p) p->gid
+#define SHMPERM_CGID(p) p->cgid
+#define SHMPERM_MODE(p) p->mode
+#endif
+
+#ifdef PANORAMIX
+#include "panoramiX.h"
+#include "panoramiXsrv.h"
+#endif
+
+#include "modinit.h"
+
+typedef struct _ShmDesc {
+ struct _ShmDesc *next;
+ int shmid;
+ int refcnt;
+ char *addr;
+ Bool writable;
+ unsigned long size;
+} ShmDescRec, *ShmDescPtr;
+
+static PixmapPtr fbShmCreatePixmap(XSHM_CREATE_PIXMAP_ARGS);
+static int ShmDetachSegment(
+ pointer /* value */,
+ XID /* shmseg */
+ );
+static void ShmResetProc(
+ ExtensionEntry * /* extEntry */
+ );
+static void SShmCompletionEvent(
+ xShmCompletionEvent * /* from */,
+ xShmCompletionEvent * /* to */
+ );
+
+static Bool ShmDestroyPixmap (PixmapPtr pPixmap);
+
+static DISPATCH_PROC(ProcShmAttach);
+static DISPATCH_PROC(ProcShmCreatePixmap);
+static DISPATCH_PROC(ProcShmDetach);
+static DISPATCH_PROC(ProcShmDispatch);
+static DISPATCH_PROC(ProcShmGetImage);
+static DISPATCH_PROC(ProcShmPutImage);
+static DISPATCH_PROC(ProcShmQueryVersion);
+static DISPATCH_PROC(SProcShmAttach);
+static DISPATCH_PROC(SProcShmCreatePixmap);
+static DISPATCH_PROC(SProcShmDetach);
+static DISPATCH_PROC(SProcShmDispatch);
+static DISPATCH_PROC(SProcShmGetImage);
+static DISPATCH_PROC(SProcShmPutImage);
+static DISPATCH_PROC(SProcShmQueryVersion);
+
+static unsigned char ShmReqCode;
+int ShmCompletionCode;
+int BadShmSegCode;
+RESTYPE ShmSegType;
+static ShmDescPtr Shmsegs;
+static Bool sharedPixmaps;
+static ShmFuncsPtr shmFuncs[MAXSCREENS];
+static DestroyPixmapProcPtr destroyPixmap[MAXSCREENS];
+static int shmPixmapPrivateIndex;
+static DevPrivateKey shmPixmapPrivate = &shmPixmapPrivateIndex;
+static ShmFuncs miFuncs = {NULL, NULL};
+static ShmFuncs fbFuncs = {fbShmCreatePixmap, NULL};
+
+#define VERIFY_SHMSEG(shmseg,shmdesc,client) \
+{ \
+ int rc; \
+ rc = dixLookupResourceByType((pointer *)&(shmdesc), shmseg, ShmSegType, \
+ client, DixReadAccess); \
+ if (rc != Success) \
+ return (rc == BadValue) ? BadShmSegCode : rc; \
+}
+
+#define VERIFY_SHMPTR(shmseg,offset,needwrite,shmdesc,client) \
+{ \
+ VERIFY_SHMSEG(shmseg, shmdesc, client); \
+ if ((offset & 3) || (offset > shmdesc->size)) \
+ { \
+ client->errorValue = offset; \
+ return BadValue; \
+ } \
+ if (needwrite && !shmdesc->writable) \
+ return BadAccess; \
+}
+
+#define VERIFY_SHMSIZE(shmdesc,offset,len,client) \
+{ \
+ if ((offset + len) > shmdesc->size) \
+ { \
+ return BadAccess; \
+ } \
+}
+
+
+#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__CYGWIN__) || defined(__DragonFly__)
+#include <sys/signal.h>
+
+static Bool badSysCall = FALSE;
+
+static void
+SigSysHandler(int signo)
+{
+ badSysCall = TRUE;
+}
+
+static Bool CheckForShmSyscall(void)
+{
+ void (*oldHandler)();
+ int shmid = -1;
+
+ /* If no SHM support in the kernel, the bad syscall will generate SIGSYS */
+ oldHandler = signal(SIGSYS, SigSysHandler);
+
+ badSysCall = FALSE;
+ shmid = shmget(IPC_PRIVATE, 4096, IPC_CREAT);
+
+ if (shmid != -1)
+ {
+ /* Successful allocation - clean up */
+ shmctl(shmid, IPC_RMID, NULL);
+ }
+ else
+ {
+ /* Allocation failed */
+ badSysCall = TRUE;
+ }
+ signal(SIGSYS, oldHandler);
+ return(!badSysCall);
+}
+
+#define MUST_CHECK_FOR_SHM_SYSCALL
+
+#endif
+
+void
+ShmExtensionInit(INITARGS)
+{
+ ExtensionEntry *extEntry;
+ int i;
+
+#ifdef MUST_CHECK_FOR_SHM_SYSCALL
+ if (!CheckForShmSyscall())
+ {
+ ErrorF("MIT-SHM extension disabled due to lack of kernel support\n");
+ return;
+ }
+#endif
+
+ sharedPixmaps = xFalse;
+ {
+ sharedPixmaps = xTrue;
+ for (i = 0; i < screenInfo.numScreens; i++)
+ {
+ if (!shmFuncs[i])
+ shmFuncs[i] = &miFuncs;
+ if (!shmFuncs[i]->CreatePixmap)
+ sharedPixmaps = xFalse;
+ }
+ if (sharedPixmaps)
+ for (i = 0; i < screenInfo.numScreens; i++)
+ {
+ destroyPixmap[i] = screenInfo.screens[i]->DestroyPixmap;
+ screenInfo.screens[i]->DestroyPixmap = ShmDestroyPixmap;
+ }
+ }
+ ShmSegType = CreateNewResourceType(ShmDetachSegment);
+ if (ShmSegType &&
+ (extEntry = AddExtension(SHMNAME, ShmNumberEvents, ShmNumberErrors,
+ ProcShmDispatch, SProcShmDispatch,
+ ShmResetProc, StandardMinorOpcode)))
+ {
+ ShmReqCode = (unsigned char)extEntry->base;
+ ShmCompletionCode = extEntry->eventBase;
+ BadShmSegCode = extEntry->errorBase;
+ EventSwapVector[ShmCompletionCode] = (EventSwapPtr) SShmCompletionEvent;
+ }
+}
+
+/*ARGSUSED*/
+static void
+ShmResetProc(ExtensionEntry *extEntry)
+{
+ int i;
+
+ for (i = 0; i < MAXSCREENS; i++)
+ {
+ shmFuncs[i] = NULL;
+ }
+}
+
+void
+ShmRegisterFuncs(ScreenPtr pScreen, ShmFuncsPtr funcs)
+{
+ shmFuncs[pScreen->myNum] = funcs;
+}
+
+static Bool
+ShmDestroyPixmap (PixmapPtr pPixmap)
+{
+ ScreenPtr pScreen = pPixmap->drawable.pScreen;
+ Bool ret;
+ if (pPixmap->refcnt == 1)
+ {
+ ShmDescPtr shmdesc;
+ shmdesc = (ShmDescPtr)dixLookupPrivate(&pPixmap->devPrivates,
+ shmPixmapPrivate);
+ if (shmdesc)
+ ShmDetachSegment ((pointer) shmdesc, pPixmap->drawable.id);
+ }
+
+ pScreen->DestroyPixmap = destroyPixmap[pScreen->myNum];
+ ret = (*pScreen->DestroyPixmap) (pPixmap);
+ destroyPixmap[pScreen->myNum] = pScreen->DestroyPixmap;
+ pScreen->DestroyPixmap = ShmDestroyPixmap;
+ return ret;
+}
+
+void
+ShmRegisterFbFuncs(ScreenPtr pScreen)
+{
+ shmFuncs[pScreen->myNum] = &fbFuncs;
+}
+
+static int
+ProcShmQueryVersion(ClientPtr client)
+{
+ xShmQueryVersionReply rep;
+ int n;
+
+ REQUEST_SIZE_MATCH(xShmQueryVersionReq);
+ memset(&rep, 0, sizeof(xShmQueryVersionReply));
+ rep.type = X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.sharedPixmaps = sharedPixmaps;
+ rep.pixmapFormat = sharedPixmaps ? ZPixmap : 0;
+ rep.majorVersion = SERVER_SHM_MAJOR_VERSION;
+ rep.minorVersion = SERVER_SHM_MINOR_VERSION;
+#ifndef _MSC_VER
+ rep.uid = geteuid();
+ rep.gid = getegid();
+#endif
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.length, n);
+ swaps(&rep.majorVersion, n);
+ swaps(&rep.minorVersion, n);
+ swaps(&rep.uid, n);
+ swaps(&rep.gid, n);
+ }
+ WriteToClient(client, sizeof(xShmQueryVersionReply), (char *)&rep);
+ return (client->noClientException);
+}
+
+/*
+ * Simulate the access() system call for a shared memory segement,
+ * using the credentials from the client if available
+ */
+static int
+shm_access(ClientPtr client, SHMPERM_TYPE *perm, int readonly)
+{
+ int uid, gid;
+ mode_t mask;
+ int uidset = 0, gidset = 0;
+ LocalClientCredRec *lcc;
+
+ if (GetLocalClientCreds(client, &lcc) != -1) {
+
+ if (lcc->fieldsSet & LCC_UID_SET) {
+ uid = lcc->euid;
+ uidset = 1;
+ }
+ if (lcc->fieldsSet & LCC_GID_SET) {
+ gid = lcc->egid;
+ gidset = 1;
+ }
+
+#if defined(HAVE_GETZONEID) && defined(SHMPERM_ZONEID)
+ if ( ((lcc->fieldsSet & LCC_ZID_SET) == 0) || (lcc->zoneid == -1)
+ || (lcc->zoneid != SHMPERM_ZONEID(perm))) {
+ uidset = 0;
+ gidset = 0;
+ }
+#endif
+ FreeLocalClientCreds(lcc);
+
+ if (uidset) {
+ /* User id 0 always gets access */
+ if (uid == 0) {
+ return 0;
+ }
+ #ifdef _MSC_VER
+ __asm int 3;
+ #else
+ /* Check the owner */
+ if (SHMPERM_UID(perm) == uid || SHMPERM_CUID(perm) == uid) {
+ mask = S_IRUSR;
+ if (!readonly) {
+ mask |= S_IWUSR;
+ }
+ return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;
+ }
+ #endif
+ }
+
+ if (gidset) {
+ /* Check the group */
+ #ifdef _MSC_VER
+ __asm int 3;
+ #else
+ if (SHMPERM_GID(perm) == gid || SHMPERM_CGID(perm) == gid) {
+ mask = S_IRGRP;
+ if (!readonly) {
+ mask |= S_IWGRP;
+ }
+ return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;
+ }
+ #endif
+ }
+ }
+ #ifdef _MSC_VER
+ __asm int 3;
+ return -1;
+ #else
+ /* Otherwise, check everyone else */
+ mask = S_IROTH;
+ if (!readonly) {
+ mask |= S_IWOTH;
+ }
+ return (SHMPERM_MODE(perm) & mask) == mask ? 0 : -1;
+ #endif
+}
+
+static int
+ProcShmAttach(ClientPtr client)
+{
+ SHMSTAT_TYPE buf;
+ ShmDescPtr shmdesc;
+ REQUEST(xShmAttachReq);
+
+ REQUEST_SIZE_MATCH(xShmAttachReq);
+ LEGAL_NEW_RESOURCE(stuff->shmseg, client);
+ if ((stuff->readOnly != xTrue) && (stuff->readOnly != xFalse))
+ {
+ client->errorValue = stuff->readOnly;
+ return(BadValue);
+ }
+ for (shmdesc = Shmsegs;
+ shmdesc && (shmdesc->shmid != stuff->shmid);
+ shmdesc = shmdesc->next)
+ ;
+ if (shmdesc)
+ {
+ if (!stuff->readOnly && !shmdesc->writable)
+ return BadAccess;
+ shmdesc->refcnt++;
+ }
+ else
+ {
+ shmdesc = xalloc(sizeof(ShmDescRec));
+ if (!shmdesc)
+ return BadAlloc;
+ shmdesc->addr = shmat(stuff->shmid, 0,
+ stuff->readOnly ? SHM_RDONLY : 0);
+ if ((shmdesc->addr == ((char *)-1)) ||
+ SHMSTAT(stuff->shmid, &buf))
+ {
+ xfree(shmdesc);
+ return BadAccess;
+ }
+
+ /* The attach was performed with root privs. We must
+ * do manual checking of access rights for the credentials
+ * of the client */
+
+ if (shm_access(client, &(SHM_PERM(buf)), stuff->readOnly) == -1) {
+ shmdt(shmdesc->addr);
+ xfree(shmdesc);
+ return BadAccess;
+ }
+
+ shmdesc->shmid = stuff->shmid;
+ shmdesc->refcnt = 1;
+ shmdesc->writable = !stuff->readOnly;
+ shmdesc->size = SHM_SEGSZ(buf);
+ shmdesc->next = Shmsegs;
+ Shmsegs = shmdesc;
+ }
+ if (!AddResource(stuff->shmseg, ShmSegType, (pointer)shmdesc))
+ return BadAlloc;
+ return(client->noClientException);
+}
+
+/*ARGSUSED*/
+static int
+ShmDetachSegment(pointer value, /* must conform to DeleteType */
+ XID shmseg)
+{
+ ShmDescPtr shmdesc = (ShmDescPtr)value;
+ ShmDescPtr *prev;
+
+ if (--shmdesc->refcnt)
+ return TRUE;
+#ifndef _MSC_VER
+ shmdt(shmdesc->addr);
+#endif
+ for (prev = &Shmsegs; *prev != shmdesc; prev = &(*prev)->next)
+ ;
+ *prev = shmdesc->next;
+ xfree(shmdesc);
+ return Success;
+}
+
+static int
+ProcShmDetach(ClientPtr client)
+{
+ ShmDescPtr shmdesc;
+ REQUEST(xShmDetachReq);
+
+ REQUEST_SIZE_MATCH(xShmDetachReq);
+ VERIFY_SHMSEG(stuff->shmseg, shmdesc, client);
+ FreeResource(stuff->shmseg, RT_NONE);
+ return(client->noClientException);
+}
+
+/*
+ * If the given request doesn't exactly match PutImage's constraints,
+ * wrap the image in a scratch pixmap header and let CopyArea sort it out.
+ */
+static void
+doShmPutImage(DrawablePtr dst, GCPtr pGC,
+ int depth, unsigned int format,
+ int w, int h, int sx, int sy, int sw, int sh, int dx, int dy,
+ char *data)
+{
+ PixmapPtr pPixmap;
+
+ pPixmap = GetScratchPixmapHeader(dst->pScreen, w, h, depth,
+ BitsPerPixel(depth),
+ PixmapBytePad(w, depth),
+ data);
+ if (!pPixmap)
+ return;
+ pGC->ops->CopyArea((DrawablePtr)pPixmap, dst, pGC, sx, sy, sw, sh, dx, dy);
+ FreeScratchPixmapHeader(pPixmap);
+}
+
+#ifdef PANORAMIX
+static int
+ProcPanoramiXShmPutImage(ClientPtr client)
+{
+ int j, result, orig_x, orig_y;
+ PanoramiXRes *draw, *gc;
+ Bool sendEvent, isRoot;
+
+ REQUEST(xShmPutImageReq);
+ REQUEST_SIZE_MATCH(xShmPutImageReq);
+
+ result = dixLookupResourceByClass((pointer *)&draw, stuff->drawable,
+ XRC_DRAWABLE, client, DixWriteAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadDrawable : result;
+
+ result = dixLookupResourceByType((pointer *)&gc, stuff->gc,
+ XRT_GC, client, DixReadAccess);
+ if (result != Success)
+ return (result == BadValue) ? BadGC : result;
+
+ isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
+
+ orig_x = stuff->dstX;
+ orig_y = stuff->dstY;
+ sendEvent = stuff->sendEvent;
+ stuff->sendEvent = 0;
+ FOR_NSCREENS(j) {
+ if(!j) stuff->sendEvent = sendEvent;
+ stuff->drawable = draw->info[j].id;
+ stuff->gc = gc->info[j].id;
+ if (isRoot) {
+ stuff->dstX = orig_x - panoramiXdataPtr[j].x;
+ stuff->dstY = orig_y - panoramiXdataPtr[j].y;
+ }
+ result = ProcShmPutImage(client);
+ if(result != client->noClientException) break;
+ }
+ return(result);
+}
+
+static int
+ProcPanoramiXShmGetImage(ClientPtr client)
+{
+ PanoramiXRes *draw;
+ DrawablePtr drawables[MAXSCREENS];
+ DrawablePtr pDraw;
+ xShmGetImageReply xgi;
+ ShmDescPtr shmdesc;
+ int i, x, y, w, h, format, rc;
+ Mask plane = 0, planemask;
+ long lenPer = 0, length, widthBytesLine;
+ Bool isRoot;
+
+ REQUEST(xShmGetImageReq);
+
+ REQUEST_SIZE_MATCH(xShmGetImageReq);
+
+ if ((stuff->format != XYPixmap) && (stuff->format != ZPixmap)) {
+ client->errorValue = stuff->format;
+ return(BadValue);
+ }
+
+ rc = dixLookupResourceByClass((pointer *)&draw, stuff->drawable,
+ XRC_DRAWABLE, client, DixWriteAccess);
+ if (rc != Success)
+ return (rc == BadValue) ? BadDrawable : rc;
+
+ if (draw->type == XRT_PIXMAP)
+ return ProcShmGetImage(client);
+
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0,
+ DixReadAccess);
+ if (rc != Success)
+ return rc;
+
+ VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);
+
+ x = stuff->x;
+ y = stuff->y;
+ w = stuff->width;
+ h = stuff->height;
+ format = stuff->format;
+ planemask = stuff->planeMask;
+
+ isRoot = (draw->type == XRT_WINDOW) && draw->u.win.root;
+
+ if(isRoot) {
+ if( /* check for being onscreen */
+ x < 0 || x + w > PanoramiXPixWidth ||
+ y < 0 || y + h > PanoramiXPixHeight )
+ return(BadMatch);
+ } else {
+ if( /* check for being onscreen */
+ panoramiXdataPtr[0].x + pDraw->x + x < 0 ||
+ panoramiXdataPtr[0].x + pDraw->x + x + w > PanoramiXPixWidth ||
+ panoramiXdataPtr[0].y + pDraw->y + y < 0 ||
+ panoramiXdataPtr[0].y + pDraw->y + y + h > PanoramiXPixHeight ||
+ /* check for being inside of border */
+ x < - wBorderWidth((WindowPtr)pDraw) ||
+ x + w > wBorderWidth((WindowPtr)pDraw) + (int)pDraw->width ||
+ y < -wBorderWidth((WindowPtr)pDraw) ||
+ y + h > wBorderWidth ((WindowPtr)pDraw) + (int)pDraw->height)
+ return(BadMatch);
+ }
+
+ drawables[0] = pDraw;
+ for(i = 1; i < PanoramiXNumScreens; i++) {
+ rc = dixLookupDrawable(drawables+i, draw->info[i].id, client, 0,
+ DixReadAccess);
+ if (rc != Success)
+ return rc;
+ }
+
+ xgi.visual = wVisual(((WindowPtr)pDraw));
+ xgi.type = X_Reply;
+ xgi.length = 0;
+ xgi.sequenceNumber = client->sequence;
+ xgi.depth = pDraw->depth;
+
+ if(format == ZPixmap) {
+ widthBytesLine = PixmapBytePad(w, pDraw->depth);
+ length = widthBytesLine * h;
+ } else {
+ widthBytesLine = PixmapBytePad(w, 1);
+ lenPer = widthBytesLine * h;
+ plane = ((Mask)1) << (pDraw->depth - 1);
+ length = lenPer * Ones(planemask & (plane | (plane - 1)));
+ }
+
+ VERIFY_SHMSIZE(shmdesc, stuff->offset, length, client);
+ xgi.size = length;
+
+ if (length == 0) {/* nothing to do */ }
+ else if (format == ZPixmap) {
+ XineramaGetImageData(drawables, x, y, w, h, format, planemask,
+ shmdesc->addr + stuff->offset,
+ widthBytesLine, isRoot);
+ } else {
+
+ length = stuff->offset;
+ for (; plane; plane >>= 1) {
+ if (planemask & plane) {
+ XineramaGetImageData(drawables, x, y, w, h,
+ format, plane, shmdesc->addr + length,
+ widthBytesLine, isRoot);
+ length += lenPer;
+ }
+ }
+ }
+
+ if (client->swapped) {
+ int n;
+ swaps(&xgi.sequenceNumber, n);
+ swapl(&xgi.length, n);
+ swapl(&xgi.visual, n);
+ swapl(&xgi.size, n);
+ }
+ WriteToClient(client, sizeof(xShmGetImageReply), (char *)&xgi);
+
+ return(client->noClientException);
+}
+
+static int
+ProcPanoramiXShmCreatePixmap(ClientPtr client)
+{
+ ScreenPtr pScreen = NULL;
+ PixmapPtr pMap = NULL;
+ DrawablePtr pDraw;
+ DepthPtr pDepth;
+ int i, j, result, rc;
+ ShmDescPtr shmdesc;
+ REQUEST(xShmCreatePixmapReq);
+ unsigned int width, height, depth;
+ unsigned long size;
+ PanoramiXRes *newPix;
+
+ REQUEST_SIZE_MATCH(xShmCreatePixmapReq);
+ client->errorValue = stuff->pid;
+ if (!sharedPixmaps)
+ return BadImplementation;
+ LEGAL_NEW_RESOURCE(stuff->pid, client);
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);
+
+ width = stuff->width;
+ height = stuff->height;
+ depth = stuff->depth;
+ if (!width || !height || !depth)
+ {
+ client->errorValue = 0;
+ return BadValue;
+ }
+ if (width > 32767 || height > 32767)
+ return BadAlloc;
+
+ if (stuff->depth != 1)
+ {
+ pDepth = pDraw->pScreen->allowedDepths;
+ for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++)
+ if (pDepth->depth == stuff->depth)
+ goto CreatePmap;
+ client->errorValue = stuff->depth;
+ return BadValue;
+ }
+
+CreatePmap:
+ size = PixmapBytePad(width, depth) * height;
+ if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) {
+ if (size < width * height)
+ return BadAlloc;
+ }
+ /* thankfully, offset is unsigned */
+ if (stuff->offset + size < size)
+ return BadAlloc;
+
+ VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client);
+
+ if(!(newPix = xalloc(sizeof(PanoramiXRes))))
+ return BadAlloc;
+
+ newPix->type = XRT_PIXMAP;
+ newPix->u.pix.shared = TRUE;
+ newPix->info[0].id = stuff->pid;
+ for(j = 1; j < PanoramiXNumScreens; j++)
+ newPix->info[j].id = FakeClientID(client->index);
+
+ result = (client->noClientException);
+
+ FOR_NSCREENS(j) {
+ pScreen = screenInfo.screens[j];
+
+ pMap = (*shmFuncs[j]->CreatePixmap)(pScreen,
+ stuff->width, stuff->height, stuff->depth,
+ shmdesc->addr + stuff->offset);
+
+ if (pMap) {
+ dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc);
+ shmdesc->refcnt++;
+ pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
+ pMap->drawable.id = newPix->info[j].id;
+ if (!AddResource(newPix->info[j].id, RT_PIXMAP, (pointer)pMap)) {
+ (*pScreen->DestroyPixmap)(pMap);
+ result = BadAlloc;
+ break;
+ }
+ } else {
+ result = BadAlloc;
+ break;
+ }
+ }
+
+ if(result == BadAlloc) {
+ while(j--) {
+ (*pScreen->DestroyPixmap)(pMap);
+ FreeResource(newPix->info[j].id, RT_NONE);
+ }
+ xfree(newPix);
+ } else
+ AddResource(stuff->pid, XRT_PIXMAP, newPix);
+
+ return result;
+}
+
+#endif
+
+static int
+ProcShmPutImage(ClientPtr client)
+{
+ GCPtr pGC;
+ DrawablePtr pDraw;
+ long length;
+ ShmDescPtr shmdesc;
+ REQUEST(xShmPutImageReq);
+
+ REQUEST_SIZE_MATCH(xShmPutImageReq);
+ VALIDATE_DRAWABLE_AND_GC(stuff->drawable, pDraw, DixWriteAccess);
+ VERIFY_SHMPTR(stuff->shmseg, stuff->offset, FALSE, shmdesc, client);
+ if ((stuff->sendEvent != xTrue) && (stuff->sendEvent != xFalse))
+ return BadValue;
+ if (stuff->format == XYBitmap)
+ {
+ if (stuff->depth != 1)
+ return BadMatch;
+ length = PixmapBytePad(stuff->totalWidth, 1);
+ }
+ else if (stuff->format == XYPixmap)
+ {
+ if (pDraw->depth != stuff->depth)
+ return BadMatch;
+ length = PixmapBytePad(stuff->totalWidth, 1);
+ length *= stuff->depth;
+ }
+ else if (stuff->format == ZPixmap)
+ {
+ if (pDraw->depth != stuff->depth)
+ return BadMatch;
+ length = PixmapBytePad(stuff->totalWidth, stuff->depth);
+ }
+ else
+ {
+ client->errorValue = stuff->format;
+ return BadValue;
+ }
+
+ /*
+ * There's a potential integer overflow in this check:
+ * VERIFY_SHMSIZE(shmdesc, stuff->offset, length * stuff->totalHeight,
+ * client);
+ * the version below ought to avoid it
+ */
+ if (stuff->totalHeight != 0 &&
+ length > (shmdesc->size - stuff->offset)/stuff->totalHeight) {
+ client->errorValue = stuff->totalWidth;
+ return BadValue;
+ }
+ if (stuff->srcX > stuff->totalWidth)
+ {
+ client->errorValue = stuff->srcX;
+ return BadValue;
+ }
+ if (stuff->srcY > stuff->totalHeight)
+ {
+ client->errorValue = stuff->srcY;
+ return BadValue;
+ }
+ if ((stuff->srcX + stuff->srcWidth) > stuff->totalWidth)
+ {
+ client->errorValue = stuff->srcWidth;
+ return BadValue;
+ }
+ if ((stuff->srcY + stuff->srcHeight) > stuff->totalHeight)
+ {
+ client->errorValue = stuff->srcHeight;
+ return BadValue;
+ }
+
+ if ((((stuff->format == ZPixmap) && (stuff->srcX == 0)) ||
+ ((stuff->format != ZPixmap) &&
+ (stuff->srcX < screenInfo.bitmapScanlinePad) &&
+ ((stuff->format == XYBitmap) ||
+ ((stuff->srcY == 0) &&
+ (stuff->srcHeight == stuff->totalHeight))))) &&
+ ((stuff->srcX + stuff->srcWidth) == stuff->totalWidth))
+ (*pGC->ops->PutImage) (pDraw, pGC, stuff->depth,
+ stuff->dstX, stuff->dstY,
+ stuff->totalWidth, stuff->srcHeight,
+ stuff->srcX, stuff->format,
+ shmdesc->addr + stuff->offset +
+ (stuff->srcY * length));
+ else
+ doShmPutImage(pDraw, pGC, stuff->depth, stuff->format,
+ stuff->totalWidth, stuff->totalHeight,
+ stuff->srcX, stuff->srcY,
+ stuff->srcWidth, stuff->srcHeight,
+ stuff->dstX, stuff->dstY,
+ shmdesc->addr + stuff->offset);
+
+ if (stuff->sendEvent)
+ {
+ xShmCompletionEvent ev;
+
+ ev.type = ShmCompletionCode;
+ ev.drawable = stuff->drawable;
+ ev.sequenceNumber = client->sequence;
+ ev.minorEvent = X_ShmPutImage;
+ ev.majorEvent = ShmReqCode;
+ ev.shmseg = stuff->shmseg;
+ ev.offset = stuff->offset;
+ WriteEventsToClient(client, 1, (xEvent *) &ev);
+ }
+
+ return (client->noClientException);
+}
+
+
+
+static int
+ProcShmGetImage(ClientPtr client)
+{
+ DrawablePtr pDraw;
+ long lenPer = 0, length;
+ Mask plane = 0;
+ xShmGetImageReply xgi;
+ ShmDescPtr shmdesc;
+ int n, rc;
+
+ REQUEST(xShmGetImageReq);
+
+ REQUEST_SIZE_MATCH(xShmGetImageReq);
+ if ((stuff->format != XYPixmap) && (stuff->format != ZPixmap))
+ {
+ client->errorValue = stuff->format;
+ return(BadValue);
+ }
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, 0,
+ DixReadAccess);
+ if (rc != Success)
+ return rc;
+ VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);
+ if (pDraw->type == DRAWABLE_WINDOW)
+ {
+ if( /* check for being viewable */
+ !((WindowPtr) pDraw)->realized ||
+ /* check for being on screen */
+ pDraw->x + stuff->x < 0 ||
+ pDraw->x + stuff->x + (int)stuff->width > pDraw->pScreen->width ||
+ pDraw->y + stuff->y < 0 ||
+ pDraw->y + stuff->y + (int)stuff->height > pDraw->pScreen->height ||
+ /* check for being inside of border */
+ stuff->x < - wBorderWidth((WindowPtr)pDraw) ||
+ stuff->x + (int)stuff->width >
+ wBorderWidth((WindowPtr)pDraw) + (int)pDraw->width ||
+ stuff->y < -wBorderWidth((WindowPtr)pDraw) ||
+ stuff->y + (int)stuff->height >
+ wBorderWidth((WindowPtr)pDraw) + (int)pDraw->height
+ )
+ return(BadMatch);
+ xgi.visual = wVisual(((WindowPtr)pDraw));
+ }
+ else
+ {
+ if (stuff->x < 0 ||
+ stuff->x+(int)stuff->width > pDraw->width ||
+ stuff->y < 0 ||
+ stuff->y+(int)stuff->height > pDraw->height
+ )
+ return(BadMatch);
+ xgi.visual = None;
+ }
+ xgi.type = X_Reply;
+ xgi.length = 0;
+ xgi.sequenceNumber = client->sequence;
+ xgi.depth = pDraw->depth;
+ if(stuff->format == ZPixmap)
+ {
+ length = PixmapBytePad(stuff->width, pDraw->depth) * stuff->height;
+ }
+ else
+ {
+ lenPer = PixmapBytePad(stuff->width, 1) * stuff->height;
+ plane = ((Mask)1) << (pDraw->depth - 1);
+ /* only planes asked for */
+ length = lenPer * Ones(stuff->planeMask & (plane | (plane - 1)));
+ }
+
+ VERIFY_SHMSIZE(shmdesc, stuff->offset, length, client);
+ xgi.size = length;
+
+ if (length == 0)
+ {
+ /* nothing to do */
+ }
+ else if (stuff->format == ZPixmap)
+ {
+ (*pDraw->pScreen->GetImage)(pDraw, stuff->x, stuff->y,
+ stuff->width, stuff->height,
+ stuff->format, stuff->planeMask,
+ shmdesc->addr + stuff->offset);
+ }
+ else
+ {
+
+ length = stuff->offset;
+ for (; plane; plane >>= 1)
+ {
+ if (stuff->planeMask & plane)
+ {
+ (*pDraw->pScreen->GetImage)(pDraw,
+ stuff->x, stuff->y,
+ stuff->width, stuff->height,
+ stuff->format, plane,
+ shmdesc->addr + length);
+ length += lenPer;
+ }
+ }
+ }
+
+ if (client->swapped) {
+ swaps(&xgi.sequenceNumber, n);
+ swapl(&xgi.length, n);
+ swapl(&xgi.visual, n);
+ swapl(&xgi.size, n);
+ }
+ WriteToClient(client, sizeof(xShmGetImageReply), (char *)&xgi);
+
+ return(client->noClientException);
+}
+
+static PixmapPtr
+fbShmCreatePixmap (ScreenPtr pScreen,
+ int width, int height, int depth, char *addr)
+{
+ PixmapPtr pPixmap;
+
+ pPixmap = (*pScreen->CreatePixmap)(pScreen, 0, 0, pScreen->rootDepth, 0);
+ if (!pPixmap)
+ return NullPixmap;
+
+ if (!(*pScreen->ModifyPixmapHeader)(pPixmap, width, height, depth,
+ BitsPerPixel(depth), PixmapBytePad(width, depth), (pointer)addr)) {
+ (*pScreen->DestroyPixmap)(pPixmap);
+ return NullPixmap;
+ }
+ return pPixmap;
+}
+
+static int
+ProcShmCreatePixmap(ClientPtr client)
+{
+ PixmapPtr pMap;
+ DrawablePtr pDraw;
+ DepthPtr pDepth;
+ int i, rc;
+ ShmDescPtr shmdesc;
+ REQUEST(xShmCreatePixmapReq);
+ unsigned int width, height, depth;
+ unsigned long size;
+
+ REQUEST_SIZE_MATCH(xShmCreatePixmapReq);
+ client->errorValue = stuff->pid;
+ if (!sharedPixmaps)
+ return BadImplementation;
+ LEGAL_NEW_RESOURCE(stuff->pid, client);
+ rc = dixLookupDrawable(&pDraw, stuff->drawable, client, M_ANY,
+ DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ VERIFY_SHMPTR(stuff->shmseg, stuff->offset, TRUE, shmdesc, client);
+
+ width = stuff->width;
+ height = stuff->height;
+ depth = stuff->depth;
+ if (!width || !height || !depth)
+ {
+ client->errorValue = 0;
+ return BadValue;
+ }
+ if (width > 32767 || height > 32767)
+ return BadAlloc;
+
+ if (stuff->depth != 1)
+ {
+ pDepth = pDraw->pScreen->allowedDepths;
+ for (i=0; i<pDraw->pScreen->numDepths; i++, pDepth++)
+ if (pDepth->depth == stuff->depth)
+ goto CreatePmap;
+ client->errorValue = stuff->depth;
+ return BadValue;
+ }
+
+CreatePmap:
+ size = PixmapBytePad(width, depth) * height;
+ if (sizeof(size) == 4 && BitsPerPixel(depth) > 8) {
+ if (size < width * height)
+ return BadAlloc;
+ }
+ /* thankfully, offset is unsigned */
+ if (stuff->offset + size < size)
+ return BadAlloc;
+
+ VERIFY_SHMSIZE(shmdesc, stuff->offset, size, client);
+ pMap = (*shmFuncs[pDraw->pScreen->myNum]->CreatePixmap)(
+ pDraw->pScreen, stuff->width,
+ stuff->height, stuff->depth,
+ shmdesc->addr + stuff->offset);
+ if (pMap)
+ {
+ rc = XaceHook(XACE_RESOURCE_ACCESS, client, stuff->pid, RT_PIXMAP,
+ pMap, RT_NONE, NULL, DixCreateAccess);
+ if (rc != Success) {
+ pDraw->pScreen->DestroyPixmap(pMap);
+ return rc;
+ }
+ dixSetPrivate(&pMap->devPrivates, shmPixmapPrivate, shmdesc);
+ shmdesc->refcnt++;
+ pMap->drawable.serialNumber = NEXT_SERIAL_NUMBER;
+ pMap->drawable.id = stuff->pid;
+ if (AddResource(stuff->pid, RT_PIXMAP, (pointer)pMap))
+ {
+ return(client->noClientException);
+ }
+ pDraw->pScreen->DestroyPixmap(pMap);
+ }
+ return (BadAlloc);
+}
+
+static int
+ProcShmDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+ switch (stuff->data)
+ {
+ case X_ShmQueryVersion:
+ return ProcShmQueryVersion(client);
+ case X_ShmAttach:
+ return ProcShmAttach(client);
+ case X_ShmDetach:
+ return ProcShmDetach(client);
+ case X_ShmPutImage:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShmPutImage(client);
+#endif
+ return ProcShmPutImage(client);
+ case X_ShmGetImage:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShmGetImage(client);
+#endif
+ return ProcShmGetImage(client);
+ case X_ShmCreatePixmap:
+#ifdef PANORAMIX
+ if ( !noPanoramiXExtension )
+ return ProcPanoramiXShmCreatePixmap(client);
+#endif
+ return ProcShmCreatePixmap(client);
+ default:
+ return BadRequest;
+ }
+}
+
+static void
+SShmCompletionEvent(xShmCompletionEvent *from, xShmCompletionEvent *to)
+{
+ to->type = from->type;
+ cpswaps(from->sequenceNumber, to->sequenceNumber);
+ cpswapl(from->drawable, to->drawable);
+ cpswaps(from->minorEvent, to->minorEvent);
+ to->majorEvent = from->majorEvent;
+ cpswapl(from->shmseg, to->shmseg);
+ cpswapl(from->offset, to->offset);
+}
+
+static int
+SProcShmQueryVersion(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmQueryVersionReq);
+
+ swaps(&stuff->length, n);
+ return ProcShmQueryVersion(client);
+}
+
+static int
+SProcShmAttach(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmAttachReq);
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShmAttachReq);
+ swapl(&stuff->shmseg, n);
+ swapl(&stuff->shmid, n);
+ return ProcShmAttach(client);
+}
+
+static int
+SProcShmDetach(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmDetachReq);
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShmDetachReq);
+ swapl(&stuff->shmseg, n);
+ return ProcShmDetach(client);
+}
+
+static int
+SProcShmPutImage(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmPutImageReq);
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShmPutImageReq);
+ swapl(&stuff->drawable, n);
+ swapl(&stuff->gc, n);
+ swaps(&stuff->totalWidth, n);
+ swaps(&stuff->totalHeight, n);
+ swaps(&stuff->srcX, n);
+ swaps(&stuff->srcY, n);
+ swaps(&stuff->srcWidth, n);
+ swaps(&stuff->srcHeight, n);
+ swaps(&stuff->dstX, n);
+ swaps(&stuff->dstY, n);
+ swapl(&stuff->shmseg, n);
+ swapl(&stuff->offset, n);
+ return ProcShmPutImage(client);
+}
+
+static int
+SProcShmGetImage(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmGetImageReq);
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShmGetImageReq);
+ swapl(&stuff->drawable, n);
+ swaps(&stuff->x, n);
+ swaps(&stuff->y, n);
+ swaps(&stuff->width, n);
+ swaps(&stuff->height, n);
+ swapl(&stuff->planeMask, n);
+ swapl(&stuff->shmseg, n);
+ swapl(&stuff->offset, n);
+ return ProcShmGetImage(client);
+}
+
+static int
+SProcShmCreatePixmap(ClientPtr client)
+{
+ int n;
+ REQUEST(xShmCreatePixmapReq);
+ swaps(&stuff->length, n);
+ REQUEST_SIZE_MATCH(xShmCreatePixmapReq);
+ swapl(&stuff->pid, n);
+ swapl(&stuff->drawable, n);
+ swaps(&stuff->width, n);
+ swaps(&stuff->height, n);
+ swapl(&stuff->shmseg, n);
+ swapl(&stuff->offset, n);
+ return ProcShmCreatePixmap(client);
+}
+
+static int
+SProcShmDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+ switch (stuff->data)
+ {
+ case X_ShmQueryVersion:
+ return SProcShmQueryVersion(client);
+ case X_ShmAttach:
+ return SProcShmAttach(client);
+ case X_ShmDetach:
+ return SProcShmDetach(client);
+ case X_ShmPutImage:
+ return SProcShmPutImage(client);
+ case X_ShmGetImage:
+ return SProcShmGetImage(client);
+ case X_ShmCreatePixmap:
+ return SProcShmCreatePixmap(client);
+ default:
+ return BadRequest;
+ }
+}
diff --git a/xorg-server/Xext/xace.c b/xorg-server/Xext/xace.c index bf0e98fb0..02a0c1ebc 100644 --- a/xorg-server/Xext/xace.c +++ b/xorg-server/Xext/xace.c @@ -19,6 +19,8 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else +#define XACE #endif #include <stdarg.h> diff --git a/xorg-server/Xi/exevents.c b/xorg-server/Xi/exevents.c index b0e0ede6c..8729d129b 100644 --- a/xorg-server/Xi/exevents.c +++ b/xorg-server/Xi/exevents.c @@ -1,2170 +1,2172 @@ -/************************************************************ - -Copyright 1989, 1998 The Open Group - -Permission to use, copy, modify, distribute, and sell this software and its -documentation for any purpose is hereby granted without fee, provided that -the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation. - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of The Open Group shall not be -used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization from The Open Group. - -Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -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 Hewlett-Packard not be -used in advertising or publicity pertaining to distribution of the -software without specific, written prior permission. - -HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING -ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL -HEWLETT-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. - -********************************************************/ - -/******************************************************************** - * - * Routines to register and initialize extension input devices. - * This also contains ProcessOtherEvent, the routine called from DDX - * to route extension events. - * - */ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include "inputstr.h" -#include <X11/X.h> -#include <X11/Xproto.h> -#include <X11/extensions/XI.h> -#include <X11/extensions/XIproto.h> -#include <X11/extensions/XI2proto.h> -#include <X11/extensions/geproto.h> -#include "windowstr.h" -#include "miscstruct.h" -#include "region.h" -#include "exevents.h" -#include "extnsionst.h" -#include "exglobals.h" -#include "dixevents.h" /* DeliverFocusedEvent */ -#include "dixgrabs.h" /* CreateGrab() */ -#include "scrnintstr.h" -#include "listdev.h" /* for CopySwapXXXClass */ -#include "xace.h" -#include "xiquerydevice.h" /* For List*Info */ -#include "eventconvert.h" -#include "eventstr.h" - -#include <X11/extensions/XKBproto.h> -#include "xkbsrv.h" - -#define WID(w) ((w) ? ((w)->drawable.id) : 0) -#define AllModifiersMask ( \ - ShiftMask | LockMask | ControlMask | Mod1Mask | Mod2Mask | \ - Mod3Mask | Mod4Mask | Mod5Mask ) -#define AllButtonsMask ( \ - Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask ) - -Bool ShouldFreeInputMasks(WindowPtr /* pWin */ , - Bool /* ignoreSelectedEvents */ - ); -static Bool MakeInputMasks(WindowPtr /* pWin */ - ); - -/* Used to sture classes currently not in use by an MD */ -extern DevPrivateKey UnusedClassesPrivateKey; - -/* - * Only let the given client know of core events which will affect its - * interpretation of input events, if the client's ClientPointer (or the - * paired keyboard) is the current device. - */ -int -XIShouldNotify(ClientPtr client, DeviceIntPtr dev) -{ - DeviceIntPtr current_ptr = PickPointer(client); - DeviceIntPtr current_kbd = GetPairedDevice(current_ptr); - - if (dev == current_kbd || dev == current_ptr) - return 1; - - return 0; -} - -void -RegisterOtherDevice(DeviceIntPtr device) -{ - device->public.processInputProc = ProcessOtherEvent; - device->public.realInputProc = ProcessOtherEvent; -} - -Bool -IsPointerEvent(InternalEvent* event) -{ - switch(event->any.type) - { - case ET_ButtonPress: - case ET_ButtonRelease: - case ET_Motion: - /* XXX: enter/leave ?? */ - return TRUE; - default: - break; - } - return FALSE; -} - -/** - * @return the device matching the deviceid of the device set in the event, or - * NULL if the event is not an XInput event. - */ -DeviceIntPtr -XIGetDevice(xEvent* xE) -{ - DeviceIntPtr pDev = NULL; - - if (xE->u.u.type == DeviceButtonPress || - xE->u.u.type == DeviceButtonRelease || - xE->u.u.type == DeviceMotionNotify || - xE->u.u.type == ProximityIn || - xE->u.u.type == ProximityOut || - xE->u.u.type == DevicePropertyNotify) - { - int rc; - int id; - - id = ((deviceKeyButtonPointer*)xE)->deviceid & ~MORE_EVENTS; - - rc = dixLookupDevice(&pDev, id, serverClient, DixUnknownAccess); - if (rc != Success) - ErrorF("[dix] XIGetDevice failed on XACE restrictions (%d)\n", rc); - } - return pDev; -} - - -/** - * Copy the device->key into master->key and send a mapping notify to the - * clients if appropriate. - * master->key needs to be allocated by the caller. - * - * Device is the slave device. If it is attached to a master device, we may - * need to send a mapping notify to the client because it causes the MD - * to change state. - * - * Mapping notify needs to be sent in the following cases: - * - different slave device on same master - * - different master - * - * XXX: They way how the code is we also send a map notify if the slave device - * stays the same, but the master changes. This isn't really necessary though. - * - * XXX: this gives you funny behaviour with the ClientPointer. When a - * MappingNotify is sent to the client, the client usually responds with a - * GetKeyboardMapping. This will retrieve the ClientPointer's keyboard - * mapping, regardless of which keyboard sent the last mapping notify request. - * So depending on the CP setting, your keyboard may change layout in each - * app... - * - * This code is basically the old SwitchCoreKeyboard. - */ - -static void -CopyKeyClass(DeviceIntPtr device, DeviceIntPtr master) -{ - KeyClassPtr mk = master->key; - KeyClassPtr dk = device->key; - int i; - - if (device == master) - return; - - mk->sourceid = device->id; - - for (i = 0; i < 8; i++) - mk->modifierKeyCount[i] = dk->modifierKeyCount[i]; - - if (!XkbCopyDeviceKeymap(master, device)) - FatalError("Couldn't pivot keymap from device to core!\n"); -} - -/** - * Copies the feedback classes from device "from" into device "to". Classes - * are duplicated (not just flipping the pointers). All feedback classes are - * linked lists, the full list is duplicated. - */ -static void -DeepCopyFeedbackClasses(DeviceIntPtr from, DeviceIntPtr to) -{ - ClassesPtr classes; - - - if (from->intfeed) - { - IntegerFeedbackPtr *i, it; - - if (!to->intfeed) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->intfeed = classes->intfeed; - } - - i = &to->intfeed; - for (it = from->intfeed; it; it = it->next) - { - if (!(*i)) - { - *i = xcalloc(1, sizeof(IntegerFeedbackClassRec)); - if (!(*i)) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*i)->CtrlProc = it->CtrlProc; - (*i)->ctrl = it->ctrl; - - i = &(*i)->next; - } - } else if (to->intfeed && !from->intfeed) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->intfeed = to->intfeed; - to->intfeed = NULL; - } - - if (from->stringfeed) - { - StringFeedbackPtr *s, it; - - if (!to->stringfeed) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->stringfeed = classes->stringfeed; - } - - s = &to->stringfeed; - for (it = from->stringfeed; it; it = it->next) - { - if (!(*s)) - { - *s = xcalloc(1, sizeof(StringFeedbackClassRec)); - if (!(*s)) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*s)->CtrlProc = it->CtrlProc; - (*s)->ctrl = it->ctrl; - - s = &(*s)->next; - } - } else if (to->stringfeed && !from->stringfeed) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->stringfeed = to->stringfeed; - to->stringfeed = NULL; - } - - if (from->bell) - { - BellFeedbackPtr *b, it; - - if (!to->bell) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->bell = classes->bell; - } - - b = &to->bell; - for (it = from->bell; it; it = it->next) - { - if (!(*b)) - { - *b = xcalloc(1, sizeof(BellFeedbackClassRec)); - if (!(*b)) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*b)->BellProc = it->BellProc; - (*b)->CtrlProc = it->CtrlProc; - (*b)->ctrl = it->ctrl; - - b = &(*b)->next; - } - } else if (to->bell && !from->bell) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->bell = to->bell; - to->bell = NULL; - } - - if (from->leds) - { - LedFeedbackPtr *l, it; - - if (!to->leds) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->leds = classes->leds; - } - - l = &to->leds; - for (it = from->leds; it; it = it->next) - { - if (!(*l)) - { - *l = xcalloc(1, sizeof(LedFeedbackClassRec)); - if (!(*l)) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*l)->CtrlProc = it->CtrlProc; - (*l)->ctrl = it->ctrl; - if ((*l)->xkb_sli) - XkbFreeSrvLedInfo((*l)->xkb_sli); - (*l)->xkb_sli = XkbCopySrvLedInfo(from, it->xkb_sli, NULL, *l); - - l = &(*l)->next; - } - } else if (to->leds && !from->leds) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->leds = to->leds; - to->leds = NULL; - } -} - -static void -DeepCopyKeyboardClasses(DeviceIntPtr from, DeviceIntPtr to) -{ - ClassesPtr classes; - - /* XkbInitDevice (->XkbInitIndicatorMap->XkbFindSrvLedInfo) relies on the - * kbdfeed to be set up properly, so let's do the feedback classes first. - */ - if (from->kbdfeed) - { - KbdFeedbackPtr *k, it; - - if (!to->kbdfeed) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - - to->kbdfeed = classes->kbdfeed; - if (!to->kbdfeed) - InitKeyboardDeviceStruct(to, NULL, NULL, NULL); - } - - k = &to->kbdfeed; - for(it = from->kbdfeed; it; it = it->next) - { - if (!(*k)) - { - *k = xcalloc(1, sizeof(KbdFeedbackClassRec)); - if (!*k) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*k)->BellProc = it->BellProc; - (*k)->CtrlProc = it->CtrlProc; - (*k)->ctrl = it->ctrl; - if ((*k)->xkb_sli) - XkbFreeSrvLedInfo((*k)->xkb_sli); - (*k)->xkb_sli = XkbCopySrvLedInfo(from, it->xkb_sli, *k, NULL); - - k = &(*k)->next; - } - } else if (to->kbdfeed && !from->kbdfeed) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->kbdfeed = to->kbdfeed; - to->kbdfeed = NULL; - } - - if (from->key) - { - if (!to->key) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->key = classes->key; - if (!to->key) - InitKeyboardDeviceStruct(to, NULL, NULL, NULL); - else - classes->key = NULL; - } - - CopyKeyClass(from, to); - } else if (to->key && !from->key) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->key = to->key; - to->key = NULL; - } - - /* We can't just copy over the focus class. When an app sets the focus, - * it'll do so on the master device. Copying the SDs focus means losing - * the focus. - * So we only copy the focus class if the device didn't have one, - * otherwise we leave it as it is. - */ - if (from->focus) - { - if (!to->focus) - { - WindowPtr *oldTrace; - - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->focus = classes->focus; - if (!to->focus) - { - to->focus = xcalloc(1, sizeof(FocusClassRec)); - if (!to->focus) - FatalError("[Xi] no memory for class shift.\n"); - } else - classes->focus = NULL; - - oldTrace = to->focus->trace; - memcpy(to->focus, from->focus, sizeof(FocusClassRec)); - to->focus->trace = xrealloc(oldTrace, - to->focus->traceSize * sizeof(WindowPtr)); - if (!to->focus->trace && to->focus->traceSize) - FatalError("[Xi] no memory for trace.\n"); - memcpy(to->focus->trace, from->focus->trace, - from->focus->traceSize * sizeof(WindowPtr)); - to->focus->sourceid = from->id; - } - } else if (to->focus) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->focus = to->focus; - to->focus = NULL; - } - -} - -static void -DeepCopyPointerClasses(DeviceIntPtr from, DeviceIntPtr to) -{ - ClassesPtr classes; - - /* Feedback classes must be copied first */ - if (from->ptrfeed) - { - PtrFeedbackPtr *p, it; - if (!to->ptrfeed) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->ptrfeed = classes->ptrfeed; - } - - p = &to->ptrfeed; - for (it = from->ptrfeed; it; it = it->next) - { - if (!(*p)) - { - *p = xcalloc(1, sizeof(PtrFeedbackClassRec)); - if (!*p) - { - ErrorF("[Xi] Cannot alloc memory for class copy."); - return; - } - } - (*p)->CtrlProc = it->CtrlProc; - (*p)->ctrl = it->ctrl; - - p = &(*p)->next; - } - } else if (to->ptrfeed && !from->ptrfeed) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->ptrfeed = to->ptrfeed; - to->ptrfeed = NULL; - } - - if (from->valuator) - { - ValuatorClassPtr v; - if (!to->valuator) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->valuator = classes->valuator; - if (to->valuator) - classes->valuator = NULL; - } - - to->valuator = xrealloc(to->valuator, sizeof(ValuatorClassRec) + - from->valuator->numAxes * sizeof(AxisInfo) + - from->valuator->numAxes * sizeof(double)); - v = to->valuator; - if (!v) - FatalError("[Xi] no memory for class shift.\n"); - - v->numAxes = from->valuator->numAxes; - v->axes = (AxisInfoPtr)&v[1]; - memcpy(v->axes, from->valuator->axes, v->numAxes * sizeof(AxisInfo)); - - v->axisVal = (double*)(v->axes + from->valuator->numAxes); - v->sourceid = from->id; - v->mode = from->valuator->mode; - } else if (to->valuator && !from->valuator) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->valuator = to->valuator; - to->valuator = NULL; - } - - if (from->button) - { - if (!to->button) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->button = classes->button; - if (!to->button) - { - to->button = xcalloc(1, sizeof(ButtonClassRec)); - if (!to->button) - FatalError("[Xi] no memory for class shift.\n"); - } else - classes->button = NULL; - } - - if (from->button->xkb_acts) - { - if (!to->button->xkb_acts) - { - to->button->xkb_acts = xcalloc(1, sizeof(XkbAction)); - if (!to->button->xkb_acts) - FatalError("[Xi] not enough memory for xkb_acts.\n"); - } - memcpy(to->button->xkb_acts, from->button->xkb_acts, - sizeof(XkbAction)); - } else - xfree(to->button->xkb_acts); - - memcpy(to->button->labels, from->button->labels, - from->button->numButtons * sizeof(Atom)); - to->button->sourceid = from->id; - } else if (to->button && !from->button) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->button = to->button; - to->button = NULL; - } - - if (from->proximity) - { - if (!to->proximity) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->proximity = classes->proximity; - if (!to->proximity) - { - to->proximity = xcalloc(1, sizeof(ProximityClassRec)); - if (!to->proximity) - FatalError("[Xi] no memory for class shift.\n"); - } else - classes->proximity = NULL; - } - memcpy(to->proximity, from->proximity, sizeof(ProximityClassRec)); - to->proximity->sourceid = from->id; - } else if (to->proximity) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->proximity = to->proximity; - to->proximity = NULL; - } - - if (from->absolute) - { - if (!to->absolute) - { - classes = dixLookupPrivate(&to->devPrivates, - UnusedClassesPrivateKey); - to->absolute = classes->absolute; - if (!to->absolute) - { - to->absolute = xcalloc(1, sizeof(AbsoluteClassRec)); - if (!to->absolute) - FatalError("[Xi] no memory for class shift.\n"); - } else - classes->absolute = NULL; - } - memcpy(to->absolute, from->absolute, sizeof(AbsoluteClassRec)); - to->absolute->sourceid = from->id; - } else if (to->absolute) - { - ClassesPtr classes; - classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey); - classes->absolute = to->absolute; - to->absolute = NULL; - } -} - -/** - * Copies the CONTENT of the classes of device from into the classes in device - * to. From and to are identical after finishing. - * - * If to does not have classes from currenly has, the classes are stored in - * to's devPrivates system. Later, we recover it again from there if needed. - * Saves a few memory allocations. - */ -void -DeepCopyDeviceClasses(DeviceIntPtr from, DeviceIntPtr to, DeviceChangedEvent *dce) -{ - /* generic feedback classes, not tied to pointer and/or keyboard */ - DeepCopyFeedbackClasses(from, to); - - if ((dce->flags & DEVCHANGE_KEYBOARD_EVENT)) - DeepCopyKeyboardClasses(from, to); - if ((dce->flags & DEVCHANGE_POINTER_EVENT)) - DeepCopyPointerClasses(from, to); -} - - -/** - * Send an XI2 DeviceChangedEvent to all interested clients. - */ -void -XISendDeviceChangedEvent(DeviceIntPtr device, DeviceIntPtr master, DeviceChangedEvent *dce) -{ - xXIDeviceChangedEvent *dcce; - int rc; - - rc = EventToXI2((InternalEvent*)dce, (xEvent**)&dcce); - if (rc != Success) - { - ErrorF("[Xi] event conversion from DCE failed with code %d\n", rc); - return; - } - - /* we don't actually swap if there's a NullClient, swapping is done - * later when event is delivered. */ - SendEventToAllWindows(master, XI_DeviceChangedMask, (xEvent*)dcce, 1); - xfree(dcce); -} - -static void -ChangeMasterDeviceClasses(DeviceIntPtr device, DeviceChangedEvent *dce) -{ - DeviceIntPtr slave; - int rc; - - /* For now, we don't have devices that change physically. */ - if (!IsMaster(device)) - return; - - rc = dixLookupDevice(&slave, dce->sourceid, serverClient, DixReadAccess); - - if (rc != Success) - return; /* Device has disappeared */ - - if (!slave->u.master) - return; /* set floating since the event */ - - if (slave->u.master->id != dce->masterid) - return; /* not our slave anymore, don't care */ - - /* FIXME: we probably need to send a DCE for the new slave now */ - - device->public.devicePrivate = slave->public.devicePrivate; - - /* FIXME: the classes may have changed since we generated the event. */ - DeepCopyDeviceClasses(slave, device, dce); - XISendDeviceChangedEvent(slave, device, dce); -} - -/** - * Update the device state according to the data in the event. - * - * return values are - * DEFAULT ... process as normal - * DONT_PROCESS ... return immediately from caller - */ -#define DEFAULT 0 -#define DONT_PROCESS 1 -int -UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event) -{ - int i; - int key = 0, - bit = 0, - last_valuator; - - KeyClassPtr k = NULL; - ButtonClassPtr b = NULL; - ValuatorClassPtr v = NULL; - BYTE *kptr = NULL; - - /* This event is always the first we get, before the actual events with - * the data. However, the way how the DDX is set up, "device" will - * actually be the slave device that caused the event. - */ - switch(event->type) - { - case ET_DeviceChanged: - ChangeMasterDeviceClasses(device, (DeviceChangedEvent*)event); - return DONT_PROCESS; /* event has been sent already */ - case ET_Motion: - case ET_ButtonPress: - case ET_ButtonRelease: - case ET_KeyPress: - case ET_KeyRelease: - case ET_ProximityIn: - case ET_ProximityOut: - break; - default: - /* other events don't update the device */ - return DEFAULT; - } - - k = device->key; - v = device->valuator; - b = device->button; - - key = event->detail.key; - bit = 1 << (key & 7); - - /* Update device axis */ - /* Check valuators first */ - last_valuator = -1; - for (i = 0; i < MAX_VALUATORS; i++) - { - if (BitIsOn(&event->valuators.mask, i)) - { - if (!v) - { - ErrorF("[Xi] Valuators reported for non-valuator device '%s'. " - "Ignoring event.\n", device->name); - return DONT_PROCESS; - } else if (v->numAxes < i) - { - ErrorF("[Xi] Too many valuators reported for device '%s'. " - "Ignoring event.\n", device->name); - return DONT_PROCESS; - } - last_valuator = i; - } - } - - for (i = 0; i <= last_valuator && i < v->numAxes; i++) - { - if (BitIsOn(&event->valuators.mask, i)) - { - /* XXX: Relative/Absolute mode */ - v->axisVal[i] = event->valuators.data[i]; - v->axisVal[i] += event->valuators.data_frac[i]; - } - } - - if (event->type == ET_KeyPress) { - if (!k) - return DONT_PROCESS; - - kptr = &k->down[key >> 3]; - /* don't allow ddx to generate multiple downs, but repeats are okay */ - if ((*kptr & bit) && !event->key_repeat) - return DONT_PROCESS; - if (device->valuator) - device->valuator->motionHintWindow = NullWindow; - *kptr |= bit; - } else if (event->type == ET_KeyRelease) { - if (!k) - return DONT_PROCESS; - - kptr = &k->down[key >> 3]; - if (!(*kptr & bit)) /* guard against duplicates */ - return DONT_PROCESS; - if (device->valuator) - device->valuator->motionHintWindow = NullWindow; - *kptr &= ~bit; - } else if (event->type == ET_ButtonPress) { - Mask mask; - if (!b) - return DONT_PROCESS; - - kptr = &b->down[key >> 3]; - if ((*kptr & bit) != 0) - return DONT_PROCESS; - *kptr |= bit; - if (device->valuator) - device->valuator->motionHintWindow = NullWindow; - if (!b->map[key]) - return DONT_PROCESS; - b->buttonsDown++; - b->motionMask = DeviceButtonMotionMask; - if (b->map[key] <= 5) - b->state |= (Button1Mask >> 1) << b->map[key]; - - /* Add state and motionMask to the filter for this event */ - mask = DevicePointerMotionMask | b->state | b->motionMask; - SetMaskForEvent(device->id, mask, DeviceMotionNotify); - mask = PointerMotionMask | b->state | b->motionMask; - SetMaskForEvent(device->id, mask, MotionNotify); - } else if (event->type == ET_ButtonRelease) { - Mask mask; - if (!b) - return DONT_PROCESS; - - kptr = &b->down[key>>3]; - if (!(*kptr & bit)) - return DONT_PROCESS; - if (IsMaster(device)) { - DeviceIntPtr sd; - - /* - * Leave the button down if any slave has the - * button still down. Note that this depends on the - * event being delivered through the slave first - */ - for (sd = inputInfo.devices; sd; sd = sd->next) { - if (IsMaster(sd) || sd->u.master != device) - continue; - if (!sd->button) - continue; - if ((sd->button->down[key>>3] & bit) != 0) - return DONT_PROCESS; - } - } - *kptr &= ~bit; - if (device->valuator) - device->valuator->motionHintWindow = NullWindow; - if (!b->map[key]) - return DONT_PROCESS; - if (b->buttonsDown >= 1 && !--b->buttonsDown) - b->motionMask = 0; - if (b->map[key] <= 5) - b->state &= ~((Button1Mask >> 1) << b->map[key]); - - /* Add state and motionMask to the filter for this event */ - mask = DevicePointerMotionMask | b->state | b->motionMask; - SetMaskForEvent(device->id, mask, DeviceMotionNotify); - mask = PointerMotionMask | b->state | b->motionMask; - SetMaskForEvent(device->id, mask, MotionNotify); - } else if (event->type == ET_ProximityIn) - device->valuator->mode &= ~OutOfProximity; - else if (event->type == ET_ProximityOut) - device->valuator->mode |= OutOfProximity; - - return DEFAULT; -} - -static void -ProcessRawEvent(RawDeviceEvent *ev, DeviceIntPtr device) -{ - GrabPtr grab = device->deviceGrab.grab; - - if (grab) - DeliverGrabbedEvent((InternalEvent*)ev, device, FALSE); - else { /* deliver to all root windows */ - xEvent *xi; - int i; - - i = EventToXI2((InternalEvent*)ev, (xEvent**)&xi); - if (i != Success) - { - ErrorF("[Xi] %s: XI2 conversion failed in ProcessRawEvent (%d)\n", - device->name, i); - return; - } - - for (i = 0; i < screenInfo.numScreens; i++) - DeliverEventsToWindow(device, WindowTable[i], xi, 1, - GetEventFilter(device, xi), NULL); - xfree(xi); - } -} - -/** - * Main device event processing function. - * Called from when processing the events from the event queue. - * - */ -void -ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device) -{ - GrabPtr grab; - Bool deactivateDeviceGrab = FALSE; - int key = 0, rootX, rootY; - ButtonClassPtr b; - KeyClassPtr k; - ValuatorClassPtr v; - int ret = 0; - int state, i; - DeviceIntPtr mouse = NULL, kbd = NULL; - DeviceEvent *event = &ev->device_event; - - CHECKEVENT(ev); - - if (ev->any.type == ET_RawKeyPress || - ev->any.type == ET_RawKeyRelease || - ev->any.type == ET_RawButtonPress || - ev->any.type == ET_RawButtonRelease || - ev->any.type == ET_RawMotion) - { - ProcessRawEvent(&ev->raw_event, device); - return; - } - - if (IsPointerDevice(device)) - { - kbd = GetPairedDevice(device); - mouse = device; - if (!kbd->key) /* can happen with floating SDs */ - kbd = NULL; - } else - { - mouse = GetPairedDevice(device); - kbd = device; - if (!mouse->valuator || !mouse->button) /* may be float. SDs */ - mouse = NULL; - } - - /* State needs to be assembled BEFORE the device is updated. */ - state = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0; - state |= (mouse && mouse->button) ? (mouse->button->state) : 0; - - for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++) - if (BitIsOn(mouse->button->down, i)) - SetBit(event->buttons, i); - - if (kbd && kbd->key) - { - XkbStatePtr state; - /* we need the state before the event happens */ - if (event->type == ET_KeyPress || event->type == ET_KeyRelease) - state = &kbd->key->xkbInfo->prev_state; - else - state = &kbd->key->xkbInfo->state; - - event->mods.base = state->base_mods; - event->mods.latched = state->latched_mods; - event->mods.locked = state->locked_mods; - event->mods.effective = state->mods; - - event->group.base = state->base_group; - event->group.latched = state->latched_group; - event->group.locked = state->locked_group; - event->group.effective = state->group; - } - - ret = UpdateDeviceState(device, event); - if (ret == DONT_PROCESS) - return; - - v = device->valuator; - b = device->button; - k = device->key; - - if (IsMaster(device) || !device->u.master) - CheckMotion(event, device); - - switch (event->type) - { - case ET_Motion: - case ET_ButtonPress: - case ET_ButtonRelease: - case ET_KeyPress: - case ET_KeyRelease: - case ET_ProximityIn: - case ET_ProximityOut: - GetSpritePosition(device, &rootX, &rootY); - event->root_x = rootX; - event->root_y = rootY; - NoticeEventTime((InternalEvent*)event); - event->corestate = state; - key = event->detail.key; - break; - default: - break; - } - -#if 0 - /* FIXME: I'm broken. Please fix me. Thanks */ - if (DeviceEventCallback) { - DeviceEventInfoRec eventinfo; - - eventinfo.events = (xEventPtr) xE; - eventinfo.count = count; - CallCallbacks(&DeviceEventCallback, (pointer) & eventinfo); - } -#endif - grab = device->deviceGrab.grab; - - switch(event->type) - { - case ET_KeyPress: - if (!grab && CheckDeviceGrabs(device, event, 0)) { - device->deviceGrab.activatingKey = key; - return; - } - break; - case ET_KeyRelease: - if (grab && device->deviceGrab.fromPassiveGrab && - (key == device->deviceGrab.activatingKey) && - (device->deviceGrab.grab->type == KeyPress || - device->deviceGrab.grab->type == DeviceKeyPress || - device->deviceGrab.grab->type == XI_KeyPress)) - deactivateDeviceGrab = TRUE; - break; - case ET_ButtonPress: - event->detail.button = b->map[key]; - if (!event->detail.button) { /* there's no button 0 */ - event->detail.button = key; - return; - } - if (!grab && CheckDeviceGrabs(device, event, 0)) - { - /* if a passive grab was activated, the event has been sent - * already */ - return; - } - break; - case ET_ButtonRelease: - event->detail.button = b->map[key]; - if (!event->detail.button) { /* there's no button 0 */ - event->detail.button = key; - return; - } - if (grab && !b->buttonsDown && - device->deviceGrab.fromPassiveGrab && - (device->deviceGrab.grab->type == ButtonPress || - device->deviceGrab.grab->type == DeviceButtonPress || - device->deviceGrab.grab->type == XI_ButtonPress)) - deactivateDeviceGrab = TRUE; - default: - break; - } - - - if (grab) - DeliverGrabbedEvent((InternalEvent*)event, device, deactivateDeviceGrab); - else if (device->focus && !IsPointerEvent((InternalEvent*)ev)) - DeliverFocusedEvent(device, (InternalEvent*)event, - GetSpriteWindow(device)); - else - DeliverDeviceEvents(GetSpriteWindow(device), (InternalEvent*)event, - NullGrab, NullWindow, device); - - if (deactivateDeviceGrab == TRUE) - (*device->deviceGrab.DeactivateGrab) (device); - event->detail.key = key; -} - -int -InitProximityClassDeviceStruct(DeviceIntPtr dev) -{ - ProximityClassPtr proxc; - - proxc = (ProximityClassPtr) xalloc(sizeof(ProximityClassRec)); - if (!proxc) - return FALSE; - proxc->sourceid = dev->id; - dev->proximity = proxc; - return TRUE; -} - -/** - * Initialise the device's valuators. The memory must already be allocated, - * this function merely inits the matching axis (specified through axnum) to - * sane values. - * - * It is a condition that (minval < maxval). - * - * @see InitValuatorClassDeviceStruct - */ -void -InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval, int maxval, - int resolution, int min_res, int max_res) -{ - AxisInfoPtr ax; - - if (!dev || !dev->valuator || minval > maxval) - return; - if (axnum >= dev->valuator->numAxes) - return; - - ax = dev->valuator->axes + axnum; - - ax->min_value = minval; - ax->max_value = maxval; - ax->resolution = resolution; - ax->min_resolution = min_res; - ax->max_resolution = max_res; - ax->label = label; -} - -static void -FixDeviceStateNotify(DeviceIntPtr dev, deviceStateNotify * ev, KeyClassPtr k, - ButtonClassPtr b, ValuatorClassPtr v, int first) -{ - ev->type = DeviceStateNotify; - ev->deviceid = dev->id; - ev->time = currentTime.milliseconds; - ev->classes_reported = 0; - ev->num_keys = 0; - ev->num_buttons = 0; - ev->num_valuators = 0; - - if (b) { - ev->classes_reported |= (1 << ButtonClass); - ev->num_buttons = b->numButtons; - memcpy((char*)ev->buttons, (char*)b->down, 4); - } else if (k) { - ev->classes_reported |= (1 << KeyClass); - ev->num_keys = k->xkbInfo->desc->max_key_code - - k->xkbInfo->desc->min_key_code; - memmove((char *)&ev->keys[0], (char *)k->down, 4); - } - if (v) { - int nval = v->numAxes - first; - - ev->classes_reported |= (1 << ValuatorClass); - ev->classes_reported |= (dev->valuator->mode << ModeBitsShift); - ev->num_valuators = nval < 3 ? nval : 3; - switch (ev->num_valuators) { - case 3: - ev->valuator2 = v->axisVal[first + 2]; - case 2: - ev->valuator1 = v->axisVal[first + 1]; - case 1: - ev->valuator0 = v->axisVal[first]; - break; - } - } -} - -static void -FixDeviceValuator(DeviceIntPtr dev, deviceValuator * ev, ValuatorClassPtr v, - int first) -{ - int nval = v->numAxes - first; - - ev->type = DeviceValuator; - ev->deviceid = dev->id; - ev->num_valuators = nval < 3 ? nval : 3; - ev->first_valuator = first; - switch (ev->num_valuators) { - case 3: - ev->valuator2 = v->axisVal[first + 2]; - case 2: - ev->valuator1 = v->axisVal[first + 1]; - case 1: - ev->valuator0 = v->axisVal[first]; - break; - } - first += ev->num_valuators; -} - -void -DeviceFocusEvent(DeviceIntPtr dev, int type, int mode, int detail, - WindowPtr pWin) -{ - deviceFocus event; - xXIFocusInEvent *xi2event; - DeviceIntPtr mouse; - int btlen, len, i; - - mouse = (IsMaster(dev) || dev->u.master) ? GetMaster(dev, MASTER_POINTER) : dev; - - /* XI 2 event */ - btlen = (mouse->button) ? bits_to_bytes(mouse->button->numButtons) : 0; - btlen = bytes_to_int32(btlen); - len = sizeof(xXIFocusInEvent) + btlen * 4; - - xi2event = xcalloc(1, len); - xi2event->type = GenericEvent; - xi2event->extension = IReqCode; - xi2event->evtype = type; - xi2event->length = bytes_to_int32(len - sizeof(xEvent)); - xi2event->buttons_len = btlen; - xi2event->detail = detail; - xi2event->time = currentTime.milliseconds; - xi2event->deviceid = dev->id; - xi2event->sourceid = dev->id; /* a device doesn't change focus by itself */ - xi2event->mode = mode; - xi2event->root_x = FP1616(mouse->spriteInfo->sprite->hot.x, 0); - xi2event->root_y = FP1616(mouse->spriteInfo->sprite->hot.y, 0); - - for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++) - if (BitIsOn(mouse->button->down, i)) - SetBit(&xi2event[1], i); - - if (dev->key) - { - xi2event->mods.base_mods = dev->key->xkbInfo->state.base_mods; - xi2event->mods.latched_mods = dev->key->xkbInfo->state.latched_mods; - xi2event->mods.locked_mods = dev->key->xkbInfo->state.locked_mods; - xi2event->mods.effective_mods = dev->key->xkbInfo->state.mods; - - xi2event->group.base_group = dev->key->xkbInfo->state.base_group; - xi2event->group.latched_group = dev->key->xkbInfo->state.latched_group; - xi2event->group.locked_group = dev->key->xkbInfo->state.locked_group; - xi2event->group.effective_group = dev->key->xkbInfo->state.group; - } - - FixUpEventFromWindow(dev, (xEvent*)xi2event, pWin, None, FALSE); - - DeliverEventsToWindow(dev, pWin, (xEvent*)xi2event, 1, - GetEventFilter(dev, (xEvent*)xi2event), NullGrab); - - xfree(xi2event); - - /* XI 1.x event */ - event.deviceid = dev->id; - event.mode = mode; - event.type = (type == XI_FocusIn) ? DeviceFocusIn : DeviceFocusOut; - event.detail = detail; - event.window = pWin->drawable.id; - event.time = currentTime.milliseconds; - - DeliverEventsToWindow(dev, pWin, (xEvent *) & event, 1, - DeviceFocusChangeMask, NullGrab); - - if ((type == DeviceFocusIn) && - (wOtherInputMasks(pWin)) && - (wOtherInputMasks(pWin)->inputEvents[dev->id] & DeviceStateNotifyMask)) - { - int evcount = 1; - deviceStateNotify *ev, *sev; - deviceKeyStateNotify *kev; - deviceButtonStateNotify *bev; - - KeyClassPtr k; - ButtonClassPtr b; - ValuatorClassPtr v; - int nval = 0, nkeys = 0, nbuttons = 0, first = 0; - - if ((b = dev->button) != NULL) { - nbuttons = b->numButtons; - if (nbuttons > 32) - evcount++; - } - if ((k = dev->key) != NULL) { - nkeys = k->xkbInfo->desc->max_key_code - - k->xkbInfo->desc->min_key_code; - if (nkeys > 32) - evcount++; - if (nbuttons > 0) { - evcount++; - } - } - if ((v = dev->valuator) != NULL) { - nval = v->numAxes; - - if (nval > 3) - evcount++; - if (nval > 6) { - if (!(k && b)) - evcount++; - if (nval > 9) - evcount += ((nval - 7) / 3); - } - } - - sev = ev = (deviceStateNotify *) xalloc(evcount * sizeof(xEvent)); - FixDeviceStateNotify(dev, ev, NULL, NULL, NULL, first); - - if (b != NULL) { - FixDeviceStateNotify(dev, ev++, NULL, b, v, first); - first += 3; - nval -= 3; - if (nbuttons > 32) { - (ev - 1)->deviceid |= MORE_EVENTS; - bev = (deviceButtonStateNotify *) ev++; - bev->type = DeviceButtonStateNotify; - bev->deviceid = dev->id; - memcpy((char*)&bev->buttons[4], (char*)&b->down[4], DOWN_LENGTH - 4); - } - if (nval > 0) { - (ev - 1)->deviceid |= MORE_EVENTS; - FixDeviceValuator(dev, (deviceValuator *) ev++, v, first); - first += 3; - nval -= 3; - } - } - - if (k != NULL) { - FixDeviceStateNotify(dev, ev++, k, NULL, v, first); - first += 3; - nval -= 3; - if (nkeys > 32) { - (ev - 1)->deviceid |= MORE_EVENTS; - kev = (deviceKeyStateNotify *) ev++; - kev->type = DeviceKeyStateNotify; - kev->deviceid = dev->id; - memmove((char *)&kev->keys[0], (char *)&k->down[4], 28); - } - if (nval > 0) { - (ev - 1)->deviceid |= MORE_EVENTS; - FixDeviceValuator(dev, (deviceValuator *) ev++, v, first); - first += 3; - nval -= 3; - } - } - - while (nval > 0) { - FixDeviceStateNotify(dev, ev++, NULL, NULL, v, first); - first += 3; - nval -= 3; - if (nval > 0) { - (ev - 1)->deviceid |= MORE_EVENTS; - FixDeviceValuator(dev, (deviceValuator *) ev++, v, first); - first += 3; - nval -= 3; - } - } - - DeliverEventsToWindow(dev, pWin, (xEvent *) sev, evcount, - DeviceStateNotifyMask, NullGrab); - xfree(sev); - } -} - -int -CheckGrabValues(ClientPtr client, GrabParameters* param) -{ - if (param->grabtype != GRABTYPE_CORE && - param->grabtype != GRABTYPE_XI && - param->grabtype != GRABTYPE_XI2) - { - ErrorF("[Xi] grabtype is invalid. This is a bug.\n"); - return BadImplementation; - } - - if ((param->this_device_mode != GrabModeSync) && - (param->this_device_mode != GrabModeAsync)) { - client->errorValue = param->this_device_mode; - return BadValue; - } - if ((param->other_devices_mode != GrabModeSync) && - (param->other_devices_mode != GrabModeAsync)) { - client->errorValue = param->other_devices_mode; - return BadValue; - } - - if (param->grabtype != GRABTYPE_XI2 && (param->modifiers != AnyModifier) && - (param->modifiers & ~AllModifiersMask)) { - client->errorValue = param->modifiers; - return BadValue; - } - - if ((param->ownerEvents != xFalse) && (param->ownerEvents != xTrue)) { - client->errorValue = param->ownerEvents; - return BadValue; - } - return Success; -} - -int -GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device, - int button, GrabParameters *param, GrabType grabtype, - GrabMask *mask) -{ - WindowPtr pWin, confineTo; - CursorPtr cursor; - GrabPtr grab; - int rc, type = -1; - Mask access_mode = DixGrabAccess; - - rc = CheckGrabValues(client, param); - if (rc != Success) - return rc; - if (param->confineTo == None) - confineTo = NullWindow; - else { - rc = dixLookupWindow(&confineTo, param->confineTo, client, DixSetAttrAccess); - if (rc != Success) - return rc; - } - if (param->cursor == None) - cursor = NullCursor; - else { - rc = dixLookupResourceByType((pointer *)&cursor, param->cursor, - RT_CURSOR, client, DixUseAccess); - if (rc != Success) - { - client->errorValue = param->cursor; - return (rc == BadValue) ? BadCursor : rc; - } - access_mode |= DixForceAccess; - } - if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync) - access_mode |= DixFreezeAccess; - rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode); - if (rc != Success) - return rc; - rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess); - if (rc != Success) - return rc; - - if (grabtype == GRABTYPE_XI) - type = DeviceButtonPress; - else if (grabtype == GRABTYPE_XI2) - type = XI_ButtonPress; - - grab = CreateGrab(client->index, dev, modifier_device, pWin, grabtype, - mask, param, type, button, confineTo, cursor); - if (!grab) - return BadAlloc; - return AddPassiveGrabToList(client, grab); -} - -/** - * Grab the given key. If grabtype is GRABTYPE_XI, the key is a keycode. If - * grabtype is GRABTYPE_XI2, the key is a keysym. - */ -int -GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device, - int key, GrabParameters *param, GrabType grabtype, GrabMask *mask) -{ - WindowPtr pWin; - GrabPtr grab; - KeyClassPtr k = dev->key; - Mask access_mode = DixGrabAccess; - int rc, type = -1; - - rc = CheckGrabValues(client, param); - if (rc != Success) - return rc; - if (k == NULL) - return BadMatch; - if (grabtype == GRABTYPE_XI) - { - if ((key > k->xkbInfo->desc->max_key_code || - key < k->xkbInfo->desc->min_key_code) - && (key != AnyKey)) { - client->errorValue = key; - return BadValue; - } - type = DeviceKeyPress; - } else if (grabtype == GRABTYPE_XI2) - type = XI_KeyPress; - - rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess); - if (rc != Success) - return rc; - if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync) - access_mode |= DixFreezeAccess; - rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode); - if (rc != Success) - return rc; - - grab = CreateGrab(client->index, dev, modifier_device, pWin, grabtype, - mask, param, type, key, NULL, NULL); - if (!grab) - return BadAlloc; - return AddPassiveGrabToList(client, grab); -} - -/* Enter/FocusIn grab */ -int -GrabWindow(ClientPtr client, DeviceIntPtr dev, int type, - GrabParameters *param, GrabMask *mask) -{ - WindowPtr pWin; - CursorPtr cursor; - GrabPtr grab; - Mask access_mode = DixGrabAccess; - int rc; - - rc = CheckGrabValues(client, param); - if (rc != Success) - return rc; - - rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess); - if (rc != Success) - return rc; - if (param->cursor == None) - cursor = NullCursor; - else { - rc = dixLookupResourceByType((pointer *)&cursor, param->cursor, - RT_CURSOR, client, DixUseAccess); - if (rc != Success) - { - client->errorValue = param->cursor; - return (rc == BadValue) ? BadCursor : rc; - } - access_mode |= DixForceAccess; - } - if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync) - access_mode |= DixFreezeAccess; - rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode); - if (rc != Success) - return rc; - - grab = CreateGrab(client->index, dev, dev, pWin, GRABTYPE_XI2, - mask, param, (type == XIGrabtypeEnter) ? XI_Enter : XI_FocusIn, - 0, NULL, cursor); - - if (!grab) - return BadAlloc; - - return AddPassiveGrabToList(client, grab); -} - -int -SelectForWindow(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client, - Mask mask, Mask exclusivemasks) -{ - int mskidx = dev->id; - int i, ret; - Mask check; - InputClientsPtr others; - - check = (mask & exclusivemasks); - if (wOtherInputMasks(pWin)) { - if (check & wOtherInputMasks(pWin)->inputEvents[mskidx]) { /* It is illegal for two different - * clients to select on any of the - * events for maskcheck. However, - * it is OK, for some client to - * continue selecting on one of those - * events. */ - for (others = wOtherInputMasks(pWin)->inputClients; others; - others = others->next) { - if (!SameClient(others, client) && (check & - others->mask[mskidx])) - return BadAccess; - } - } - for (others = wOtherInputMasks(pWin)->inputClients; others; - others = others->next) { - if (SameClient(others, client)) { - check = others->mask[mskidx]; - others->mask[mskidx] = mask; - if (mask == 0) { - for (i = 0; i < EMASKSIZE; i++) - if (i != mskidx && others->mask[i] != 0) - break; - if (i == EMASKSIZE) { - RecalculateDeviceDeliverableEvents(pWin); - if (ShouldFreeInputMasks(pWin, FALSE)) - FreeResource(others->resource, RT_NONE); - return Success; - } - } - goto maskSet; - } - } - } - check = 0; - if ((ret = AddExtensionClient(pWin, client, mask, mskidx)) != Success) - return ret; - maskSet: - if (dev->valuator) - if ((dev->valuator->motionHintWindow == pWin) && - (mask & DevicePointerMotionHintMask) && - !(check & DevicePointerMotionHintMask) && !dev->deviceGrab.grab) - dev->valuator->motionHintWindow = NullWindow; - RecalculateDeviceDeliverableEvents(pWin); - return Success; -} - -int -AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx) -{ - InputClientsPtr others; - - if (!pWin->optional && !MakeWindowOptional(pWin)) - return BadAlloc; - others = xcalloc(1, sizeof(InputClients)); - if (!others) - return BadAlloc; - if (!pWin->optional->inputMasks && !MakeInputMasks(pWin)) - return BadAlloc; - others->mask[mskidx] = mask; - others->resource = FakeClientID(client->index); - others->next = pWin->optional->inputMasks->inputClients; - pWin->optional->inputMasks->inputClients = others; - if (!AddResource(others->resource, RT_INPUTCLIENT, (pointer) pWin)) - return BadAlloc; - return Success; -} - -static Bool -MakeInputMasks(WindowPtr pWin) -{ - struct _OtherInputMasks *imasks; - - imasks = xcalloc(1, sizeof(struct _OtherInputMasks)); - if (!imasks) - return FALSE; - pWin->optional->inputMasks = imasks; - return TRUE; -} - -void -RecalculateDeviceDeliverableEvents(WindowPtr pWin) -{ - InputClientsPtr others; - struct _OtherInputMasks *inputMasks; /* default: NULL */ - WindowPtr pChild, tmp; - int i, j; - - pChild = pWin; - while (1) { - if ((inputMasks = wOtherInputMasks(pChild)) != 0) { - for (i = 0; i < EMASKSIZE; i++) - memset(inputMasks->xi2mask[i], 0, sizeof(inputMasks->xi2mask[i])); - for (others = inputMasks->inputClients; others; - others = others->next) { - for (i = 0; i < EMASKSIZE; i++) - inputMasks->inputEvents[i] |= others->mask[i]; - for (i = 0; i < EMASKSIZE; i++) - for (j = 0; j < XI2MASKSIZE; j++) - inputMasks->xi2mask[i][j] |= others->xi2mask[i][j]; - } - for (i = 0; i < EMASKSIZE; i++) - inputMasks->deliverableEvents[i] = inputMasks->inputEvents[i]; - for (tmp = pChild->parent; tmp; tmp = tmp->parent) - if (wOtherInputMasks(tmp)) - for (i = 0; i < EMASKSIZE; i++) - inputMasks->deliverableEvents[i] |= - (wOtherInputMasks(tmp)->deliverableEvents[i] - & ~inputMasks-> - dontPropagateMask[i] & PropagateMask[i]); - } - if (pChild->firstChild) { - pChild = pChild->firstChild; - continue; - } - while (!pChild->nextSib && (pChild != pWin)) - pChild = pChild->parent; - if (pChild == pWin) - break; - pChild = pChild->nextSib; - } -} - -int -InputClientGone(WindowPtr pWin, XID id) -{ - InputClientsPtr other, prev; - - if (!wOtherInputMasks(pWin)) - return (Success); - prev = 0; - for (other = wOtherInputMasks(pWin)->inputClients; other; - other = other->next) { - if (other->resource == id) { - if (prev) { - prev->next = other->next; - xfree(other); - } else if (!(other->next)) { - if (ShouldFreeInputMasks(pWin, TRUE)) { - wOtherInputMasks(pWin)->inputClients = other->next; - xfree(wOtherInputMasks(pWin)); - pWin->optional->inputMasks = (OtherInputMasks *) NULL; - CheckWindowOptionalNeed(pWin); - xfree(other); - } else { - other->resource = FakeClientID(0); - if (!AddResource(other->resource, RT_INPUTCLIENT, - (pointer) pWin)) - return BadAlloc; - } - } else { - wOtherInputMasks(pWin)->inputClients = other->next; - xfree(other); - } - RecalculateDeviceDeliverableEvents(pWin); - return (Success); - } - prev = other; - } - FatalError("client not on device event list"); -} - -int -SendEvent(ClientPtr client, DeviceIntPtr d, Window dest, Bool propagate, - xEvent * ev, Mask mask, int count) -{ - WindowPtr pWin; - WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */ - WindowPtr spriteWin = GetSpriteWindow(d); - - if (dest == PointerWindow) - pWin = spriteWin; - else if (dest == InputFocus) { - WindowPtr inputFocus; - - if (!d->focus) - inputFocus = spriteWin; - else - inputFocus = d->focus->win; - - if (inputFocus == FollowKeyboardWin) - inputFocus = inputInfo.keyboard->focus->win; - - if (inputFocus == NoneWin) - return Success; - - /* If the input focus is PointerRootWin, send the event to where - * the pointer is if possible, then perhaps propogate up to root. */ - if (inputFocus == PointerRootWin) - inputFocus = GetCurrentRootWindow(d); - - if (IsParent(inputFocus, spriteWin)) { - effectiveFocus = inputFocus; - pWin = spriteWin; - } else - effectiveFocus = pWin = inputFocus; - } else - dixLookupWindow(&pWin, dest, client, DixSendAccess); - if (!pWin) - return BadWindow; - if ((propagate != xFalse) && (propagate != xTrue)) { - client->errorValue = propagate; - return BadValue; - } - ev->u.u.type |= 0x80; - if (propagate) { - for (; pWin; pWin = pWin->parent) { - if (DeliverEventsToWindow(d, pWin, ev, count, mask, NullGrab)) - return Success; - if (pWin == effectiveFocus) - return Success; - if (wOtherInputMasks(pWin)) - mask &= ~wOtherInputMasks(pWin)->dontPropagateMask[d->id]; - if (!mask) - break; - } - } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, ev, count)) - DeliverEventsToWindow(d, pWin, ev, count, mask, NullGrab); - return Success; -} - -int -SetButtonMapping(ClientPtr client, DeviceIntPtr dev, int nElts, BYTE * map) -{ - int i; - ButtonClassPtr b = dev->button; - - if (b == NULL) - return BadMatch; - - if (nElts != b->numButtons) { - client->errorValue = nElts; - return BadValue; - } - if (BadDeviceMap(&map[0], nElts, 1, 255, &client->errorValue)) - return BadValue; - for (i = 0; i < nElts; i++) - if ((b->map[i + 1] != map[i]) && BitIsOn(b->down, i + 1)) - return MappingBusy; - for (i = 0; i < nElts; i++) - b->map[i + 1] = map[i]; - return Success; -} - -int -ChangeKeyMapping(ClientPtr client, - DeviceIntPtr dev, - unsigned len, - int type, - KeyCode firstKeyCode, - CARD8 keyCodes, CARD8 keySymsPerKeyCode, KeySym * map) -{ - KeySymsRec keysyms; - KeyClassPtr k = dev->key; - - if (k == NULL) - return (BadMatch); - - if (len != (keyCodes * keySymsPerKeyCode)) - return BadLength; - - if ((firstKeyCode < k->xkbInfo->desc->min_key_code) || - (firstKeyCode + keyCodes - 1 > k->xkbInfo->desc->max_key_code)) { - client->errorValue = firstKeyCode; - return BadValue; - } - if (keySymsPerKeyCode == 0) { - client->errorValue = 0; - return BadValue; - } - keysyms.minKeyCode = firstKeyCode; - keysyms.maxKeyCode = firstKeyCode + keyCodes - 1; - keysyms.mapWidth = keySymsPerKeyCode; - keysyms.map = map; - - XkbApplyMappingChange(dev, &keysyms, firstKeyCode, keyCodes, NULL, - serverClient); - - return client->noClientException; -} - -static void -DeleteDeviceFromAnyExtEvents(WindowPtr pWin, DeviceIntPtr dev) -{ - WindowPtr parent; - - /* Deactivate any grabs performed on this window, before making - * any input focus changes. - * Deactivating a device grab should cause focus events. */ - - if (dev->deviceGrab.grab && (dev->deviceGrab.grab->window == pWin)) - (*dev->deviceGrab.DeactivateGrab) (dev); - - /* If the focus window is a root window (ie. has no parent) - * then don't delete the focus from it. */ - - if (dev->focus && (pWin == dev->focus->win) && (pWin->parent != NullWindow)) { - int focusEventMode = NotifyNormal; - - /* If a grab is in progress, then alter the mode of focus events. */ - - if (dev->deviceGrab.grab) - focusEventMode = NotifyWhileGrabbed; - - switch (dev->focus->revert) { - case RevertToNone: - if (!ActivateFocusInGrab(dev, pWin, NoneWin)) - DoFocusEvents(dev, pWin, NoneWin, focusEventMode); - dev->focus->win = NoneWin; - dev->focus->traceGood = 0; - break; - case RevertToParent: - parent = pWin; - do { - parent = parent->parent; - dev->focus->traceGood--; - } - while (!parent->realized); - if (!ActivateFocusInGrab(dev, pWin, parent)) - DoFocusEvents(dev, pWin, parent, focusEventMode); - dev->focus->win = parent; - dev->focus->revert = RevertToNone; - break; - case RevertToPointerRoot: - if (!ActivateFocusInGrab(dev, pWin, PointerRootWin)) - DoFocusEvents(dev, pWin, PointerRootWin, focusEventMode); - dev->focus->win = PointerRootWin; - dev->focus->traceGood = 0; - break; - case RevertToFollowKeyboard: - { - DeviceIntPtr kbd = GetMaster(dev, MASTER_KEYBOARD); - if (!kbd || (kbd == dev && kbd != inputInfo.keyboard)) - kbd = inputInfo.keyboard; - if (kbd->focus->win) { - if (!ActivateFocusInGrab(dev, pWin, kbd->focus->win)) - DoFocusEvents(dev, pWin, kbd->focus->win, focusEventMode); - dev->focus->win = FollowKeyboardWin; - dev->focus->traceGood = 0; - } else { - if (!ActivateFocusInGrab(dev, pWin, NoneWin)) - DoFocusEvents(dev, pWin, NoneWin, focusEventMode); - dev->focus->win = NoneWin; - dev->focus->traceGood = 0; - } - } - break; - } - } - - if (dev->valuator) - if (dev->valuator->motionHintWindow == pWin) - dev->valuator->motionHintWindow = NullWindow; -} - -void -DeleteWindowFromAnyExtEvents(WindowPtr pWin, Bool freeResources) -{ - int i; - DeviceIntPtr dev; - InputClientsPtr ic; - struct _OtherInputMasks *inputMasks; - - for (dev = inputInfo.devices; dev; dev = dev->next) { - DeleteDeviceFromAnyExtEvents(pWin, dev); - } - - for (dev = inputInfo.off_devices; dev; dev = dev->next) - DeleteDeviceFromAnyExtEvents(pWin, dev); - - if (freeResources) - while ((inputMasks = wOtherInputMasks(pWin)) != 0) { - ic = inputMasks->inputClients; - for (i = 0; i < EMASKSIZE; i++) - inputMasks->dontPropagateMask[i] = 0; - FreeResource(ic->resource, RT_NONE); - } -} - -int -MaybeSendDeviceMotionNotifyHint(deviceKeyButtonPointer * pEvents, Mask mask) -{ - DeviceIntPtr dev; - - dixLookupDevice(&dev, pEvents->deviceid & DEVICE_BITS, serverClient, - DixReadAccess); - if (!dev) - return 0; - - if (pEvents->type == DeviceMotionNotify) { - if (mask & DevicePointerMotionHintMask) { - if (WID(dev->valuator->motionHintWindow) == pEvents->event) { - return 1; /* don't send, but pretend we did */ - } - pEvents->detail = NotifyHint; - } else { - pEvents->detail = NotifyNormal; - } - } - return (0); -} - -void -CheckDeviceGrabAndHintWindow(WindowPtr pWin, int type, - deviceKeyButtonPointer * xE, GrabPtr grab, - ClientPtr client, Mask deliveryMask) -{ - DeviceIntPtr dev; - - dixLookupDevice(&dev, xE->deviceid & DEVICE_BITS, serverClient, - DixGrabAccess); - if (!dev) - return; - - if (type == DeviceMotionNotify) - dev->valuator->motionHintWindow = pWin; - else if ((type == DeviceButtonPress) && (!grab) && - (deliveryMask & DeviceButtonGrabMask)) { - GrabRec tempGrab; - - tempGrab.device = dev; - tempGrab.resource = client->clientAsMask; - tempGrab.window = pWin; - tempGrab.ownerEvents = - (deliveryMask & DeviceOwnerGrabButtonMask) ? TRUE : FALSE; - tempGrab.eventMask = deliveryMask; - tempGrab.keyboardMode = GrabModeAsync; - tempGrab.pointerMode = GrabModeAsync; - tempGrab.confineTo = NullWindow; - tempGrab.cursor = NullCursor; - tempGrab.next = NULL; - (*dev->deviceGrab.ActivateGrab) (dev, &tempGrab, currentTime, TRUE); - } -} - -static Mask -DeviceEventMaskForClient(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client) -{ - InputClientsPtr other; - - if (!wOtherInputMasks(pWin)) - return 0; - for (other = wOtherInputMasks(pWin)->inputClients; other; - other = other->next) { - if (SameClient(other, client)) - return other->mask[dev->id]; - } - return 0; -} - -void -MaybeStopDeviceHint(DeviceIntPtr dev, ClientPtr client) -{ - WindowPtr pWin; - GrabPtr grab = dev->deviceGrab.grab; - - pWin = dev->valuator->motionHintWindow; - - if ((grab && SameClient(grab, client) && - ((grab->eventMask & DevicePointerMotionHintMask) || - (grab->ownerEvents && - (DeviceEventMaskForClient(dev, pWin, client) & - DevicePointerMotionHintMask)))) || - (!grab && - (DeviceEventMaskForClient(dev, pWin, client) & - DevicePointerMotionHintMask))) - dev->valuator->motionHintWindow = NullWindow; -} - -int -DeviceEventSuppressForWindow(WindowPtr pWin, ClientPtr client, Mask mask, - int maskndx) -{ - struct _OtherInputMasks *inputMasks = wOtherInputMasks(pWin); - - if (mask & ~PropagateMask[maskndx]) { - client->errorValue = mask; - return BadValue; - } - - if (mask == 0) { - if (inputMasks) - inputMasks->dontPropagateMask[maskndx] = mask; - } else { - if (!inputMasks) - AddExtensionClient(pWin, client, 0, 0); - inputMasks = wOtherInputMasks(pWin); - inputMasks->dontPropagateMask[maskndx] = mask; - } - RecalculateDeviceDeliverableEvents(pWin); - if (ShouldFreeInputMasks(pWin, FALSE)) - FreeResource(inputMasks->inputClients->resource, RT_NONE); - return Success; -} - -Bool -ShouldFreeInputMasks(WindowPtr pWin, Bool ignoreSelectedEvents) -{ - int i; - Mask allInputEventMasks = 0; - struct _OtherInputMasks *inputMasks = wOtherInputMasks(pWin); - - for (i = 0; i < EMASKSIZE; i++) - allInputEventMasks |= inputMasks->dontPropagateMask[i]; - if (!ignoreSelectedEvents) - for (i = 0; i < EMASKSIZE; i++) - allInputEventMasks |= inputMasks->inputEvents[i]; - if (allInputEventMasks == 0) - return TRUE; - else - return FALSE; -} - -/*********************************************************************** - * - * Walk through the window tree, finding all clients that want to know - * about the Event. - * - */ - -static void -FindInterestedChildren(DeviceIntPtr dev, WindowPtr p1, Mask mask, - xEvent * ev, int count) -{ - WindowPtr p2; - - while (p1) { - p2 = p1->firstChild; - DeliverEventsToWindow(dev, p1, ev, count, mask, NullGrab); - FindInterestedChildren(dev, p2, mask, ev, count); - p1 = p1->nextSib; - } -} - -/*********************************************************************** - * - * Send an event to interested clients in all windows on all screens. - * - */ - -void -SendEventToAllWindows(DeviceIntPtr dev, Mask mask, xEvent * ev, int count) -{ - int i; - WindowPtr pWin, p1; - - for (i = 0; i < screenInfo.numScreens; i++) { - pWin = WindowTable[i]; - if (!pWin) - continue; - DeliverEventsToWindow(dev, pWin, ev, count, mask, NullGrab); - p1 = pWin->firstChild; - FindInterestedChildren(dev, p1, mask, ev, count); - } -} - -/** - * Set the XI2 mask for the given client on the given window. - * @param dev The device to set the mask for. - * @param win The window to set the mask on. - * @param client The client setting the mask. - * @param len Number of bytes in mask. - * @param mask Event mask in the form of (1 << eventtype) - */ -int -XISetEventMask(DeviceIntPtr dev, WindowPtr win, ClientPtr client, - unsigned int len, unsigned char* mask) -{ - OtherInputMasks *masks; - InputClientsPtr others = NULL; - - masks = wOtherInputMasks(win); - if (masks) - { - for (others = wOtherInputMasks(win)->inputClients; others; - others = others->next) { - if (SameClient(others, client)) { - memset(others->xi2mask[dev->id], 0, - sizeof(others->xi2mask[dev->id])); - break; - } - } - } - - len = min(len, sizeof(others->xi2mask[dev->id])); - - if (len && !others) - { - if (AddExtensionClient(win, client, 0, 0) != Success) - return BadAlloc; - others= wOtherInputMasks(win)->inputClients; - } - - if (others) - memset(others->xi2mask[dev->id], 0, sizeof(others->xi2mask[dev->id])); - - if (len) - memcpy(others->xi2mask[dev->id], mask, len); - - RecalculateDeviceDeliverableEvents(win); - - return Success; -} +/************************************************************
+
+Copyright 1989, 1998 The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+Copyright 1989 by Hewlett-Packard Company, Palo Alto, California.
+
+ All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+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 Hewlett-Packard not be
+used in advertising or publicity pertaining to distribution of the
+software without specific, written prior permission.
+
+HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
+ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
+HEWLETT-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.
+
+********************************************************/
+
+/********************************************************************
+ *
+ * Routines to register and initialize extension input devices.
+ * This also contains ProcessOtherEvent, the routine called from DDX
+ * to route extension events.
+ *
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+#define XINPUT
+#endif
+
+#include "inputstr.h"
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include <X11/extensions/XI.h>
+#include <X11/extensions/XIproto.h>
+#include <X11/extensions/XI2proto.h>
+#include <X11/extensions/geproto.h>
+#include "windowstr.h"
+#include "miscstruct.h"
+#include "region.h"
+#include "exevents.h"
+#include "extnsionst.h"
+#include "exglobals.h"
+#include "dixevents.h" /* DeliverFocusedEvent */
+#include "dixgrabs.h" /* CreateGrab() */
+#include "scrnintstr.h"
+#include "listdev.h" /* for CopySwapXXXClass */
+#include "xace.h"
+#include "xiquerydevice.h" /* For List*Info */
+#include "eventconvert.h"
+#include "eventstr.h"
+
+#include <X11/extensions/XKBproto.h>
+#include "xkbsrv.h"
+
+#define WID(w) ((w) ? ((w)->drawable.id) : 0)
+#define AllModifiersMask ( \
+ ShiftMask | LockMask | ControlMask | Mod1Mask | Mod2Mask | \
+ Mod3Mask | Mod4Mask | Mod5Mask )
+#define AllButtonsMask ( \
+ Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask )
+
+Bool ShouldFreeInputMasks(WindowPtr /* pWin */ ,
+ Bool /* ignoreSelectedEvents */
+ );
+static Bool MakeInputMasks(WindowPtr /* pWin */
+ );
+
+/* Used to sture classes currently not in use by an MD */
+extern DevPrivateKey UnusedClassesPrivateKey;
+
+/*
+ * Only let the given client know of core events which will affect its
+ * interpretation of input events, if the client's ClientPointer (or the
+ * paired keyboard) is the current device.
+ */
+int
+XIShouldNotify(ClientPtr client, DeviceIntPtr dev)
+{
+ DeviceIntPtr current_ptr = PickPointer(client);
+ DeviceIntPtr current_kbd = GetPairedDevice(current_ptr);
+
+ if (dev == current_kbd || dev == current_ptr)
+ return 1;
+
+ return 0;
+}
+
+void
+RegisterOtherDevice(DeviceIntPtr device)
+{
+ device->public.processInputProc = ProcessOtherEvent;
+ device->public.realInputProc = ProcessOtherEvent;
+}
+
+Bool
+IsPointerEvent(InternalEvent* event)
+{
+ switch(event->any.type)
+ {
+ case ET_ButtonPress:
+ case ET_ButtonRelease:
+ case ET_Motion:
+ /* XXX: enter/leave ?? */
+ return TRUE;
+ default:
+ break;
+ }
+ return FALSE;
+}
+
+/**
+ * @return the device matching the deviceid of the device set in the event, or
+ * NULL if the event is not an XInput event.
+ */
+DeviceIntPtr
+XIGetDevice(xEvent* xE)
+{
+ DeviceIntPtr pDev = NULL;
+
+ if (xE->u.u.type == DeviceButtonPress ||
+ xE->u.u.type == DeviceButtonRelease ||
+ xE->u.u.type == DeviceMotionNotify ||
+ xE->u.u.type == ProximityIn ||
+ xE->u.u.type == ProximityOut ||
+ xE->u.u.type == DevicePropertyNotify)
+ {
+ int rc;
+ int id;
+
+ id = ((deviceKeyButtonPointer*)xE)->deviceid & ~MORE_EVENTS;
+
+ rc = dixLookupDevice(&pDev, id, serverClient, DixUnknownAccess);
+ if (rc != Success)
+ ErrorF("[dix] XIGetDevice failed on XACE restrictions (%d)\n", rc);
+ }
+ return pDev;
+}
+
+
+/**
+ * Copy the device->key into master->key and send a mapping notify to the
+ * clients if appropriate.
+ * master->key needs to be allocated by the caller.
+ *
+ * Device is the slave device. If it is attached to a master device, we may
+ * need to send a mapping notify to the client because it causes the MD
+ * to change state.
+ *
+ * Mapping notify needs to be sent in the following cases:
+ * - different slave device on same master
+ * - different master
+ *
+ * XXX: They way how the code is we also send a map notify if the slave device
+ * stays the same, but the master changes. This isn't really necessary though.
+ *
+ * XXX: this gives you funny behaviour with the ClientPointer. When a
+ * MappingNotify is sent to the client, the client usually responds with a
+ * GetKeyboardMapping. This will retrieve the ClientPointer's keyboard
+ * mapping, regardless of which keyboard sent the last mapping notify request.
+ * So depending on the CP setting, your keyboard may change layout in each
+ * app...
+ *
+ * This code is basically the old SwitchCoreKeyboard.
+ */
+
+static void
+CopyKeyClass(DeviceIntPtr device, DeviceIntPtr master)
+{
+ KeyClassPtr mk = master->key;
+ KeyClassPtr dk = device->key;
+ int i;
+
+ if (device == master)
+ return;
+
+ mk->sourceid = device->id;
+
+ for (i = 0; i < 8; i++)
+ mk->modifierKeyCount[i] = dk->modifierKeyCount[i];
+
+ if (!XkbCopyDeviceKeymap(master, device))
+ FatalError("Couldn't pivot keymap from device to core!\n");
+}
+
+/**
+ * Copies the feedback classes from device "from" into device "to". Classes
+ * are duplicated (not just flipping the pointers). All feedback classes are
+ * linked lists, the full list is duplicated.
+ */
+static void
+DeepCopyFeedbackClasses(DeviceIntPtr from, DeviceIntPtr to)
+{
+ ClassesPtr classes;
+
+
+ if (from->intfeed)
+ {
+ IntegerFeedbackPtr *i, it;
+
+ if (!to->intfeed)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->intfeed = classes->intfeed;
+ }
+
+ i = &to->intfeed;
+ for (it = from->intfeed; it; it = it->next)
+ {
+ if (!(*i))
+ {
+ *i = xcalloc(1, sizeof(IntegerFeedbackClassRec));
+ if (!(*i))
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*i)->CtrlProc = it->CtrlProc;
+ (*i)->ctrl = it->ctrl;
+
+ i = &(*i)->next;
+ }
+ } else if (to->intfeed && !from->intfeed)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->intfeed = to->intfeed;
+ to->intfeed = NULL;
+ }
+
+ if (from->stringfeed)
+ {
+ StringFeedbackPtr *s, it;
+
+ if (!to->stringfeed)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->stringfeed = classes->stringfeed;
+ }
+
+ s = &to->stringfeed;
+ for (it = from->stringfeed; it; it = it->next)
+ {
+ if (!(*s))
+ {
+ *s = xcalloc(1, sizeof(StringFeedbackClassRec));
+ if (!(*s))
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*s)->CtrlProc = it->CtrlProc;
+ (*s)->ctrl = it->ctrl;
+
+ s = &(*s)->next;
+ }
+ } else if (to->stringfeed && !from->stringfeed)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->stringfeed = to->stringfeed;
+ to->stringfeed = NULL;
+ }
+
+ if (from->bell)
+ {
+ BellFeedbackPtr *b, it;
+
+ if (!to->bell)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->bell = classes->bell;
+ }
+
+ b = &to->bell;
+ for (it = from->bell; it; it = it->next)
+ {
+ if (!(*b))
+ {
+ *b = xcalloc(1, sizeof(BellFeedbackClassRec));
+ if (!(*b))
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*b)->BellProc = it->BellProc;
+ (*b)->CtrlProc = it->CtrlProc;
+ (*b)->ctrl = it->ctrl;
+
+ b = &(*b)->next;
+ }
+ } else if (to->bell && !from->bell)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->bell = to->bell;
+ to->bell = NULL;
+ }
+
+ if (from->leds)
+ {
+ LedFeedbackPtr *l, it;
+
+ if (!to->leds)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->leds = classes->leds;
+ }
+
+ l = &to->leds;
+ for (it = from->leds; it; it = it->next)
+ {
+ if (!(*l))
+ {
+ *l = xcalloc(1, sizeof(LedFeedbackClassRec));
+ if (!(*l))
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*l)->CtrlProc = it->CtrlProc;
+ (*l)->ctrl = it->ctrl;
+ if ((*l)->xkb_sli)
+ XkbFreeSrvLedInfo((*l)->xkb_sli);
+ (*l)->xkb_sli = XkbCopySrvLedInfo(from, it->xkb_sli, NULL, *l);
+
+ l = &(*l)->next;
+ }
+ } else if (to->leds && !from->leds)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->leds = to->leds;
+ to->leds = NULL;
+ }
+}
+
+static void
+DeepCopyKeyboardClasses(DeviceIntPtr from, DeviceIntPtr to)
+{
+ ClassesPtr classes;
+
+ /* XkbInitDevice (->XkbInitIndicatorMap->XkbFindSrvLedInfo) relies on the
+ * kbdfeed to be set up properly, so let's do the feedback classes first.
+ */
+ if (from->kbdfeed)
+ {
+ KbdFeedbackPtr *k, it;
+
+ if (!to->kbdfeed)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+
+ to->kbdfeed = classes->kbdfeed;
+ if (!to->kbdfeed)
+ InitKeyboardDeviceStruct(to, NULL, NULL, NULL);
+ }
+
+ k = &to->kbdfeed;
+ for(it = from->kbdfeed; it; it = it->next)
+ {
+ if (!(*k))
+ {
+ *k = xcalloc(1, sizeof(KbdFeedbackClassRec));
+ if (!*k)
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*k)->BellProc = it->BellProc;
+ (*k)->CtrlProc = it->CtrlProc;
+ (*k)->ctrl = it->ctrl;
+ if ((*k)->xkb_sli)
+ XkbFreeSrvLedInfo((*k)->xkb_sli);
+ (*k)->xkb_sli = XkbCopySrvLedInfo(from, it->xkb_sli, *k, NULL);
+
+ k = &(*k)->next;
+ }
+ } else if (to->kbdfeed && !from->kbdfeed)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->kbdfeed = to->kbdfeed;
+ to->kbdfeed = NULL;
+ }
+
+ if (from->key)
+ {
+ if (!to->key)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->key = classes->key;
+ if (!to->key)
+ InitKeyboardDeviceStruct(to, NULL, NULL, NULL);
+ else
+ classes->key = NULL;
+ }
+
+ CopyKeyClass(from, to);
+ } else if (to->key && !from->key)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->key = to->key;
+ to->key = NULL;
+ }
+
+ /* We can't just copy over the focus class. When an app sets the focus,
+ * it'll do so on the master device. Copying the SDs focus means losing
+ * the focus.
+ * So we only copy the focus class if the device didn't have one,
+ * otherwise we leave it as it is.
+ */
+ if (from->focus)
+ {
+ if (!to->focus)
+ {
+ WindowPtr *oldTrace;
+
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->focus = classes->focus;
+ if (!to->focus)
+ {
+ to->focus = xcalloc(1, sizeof(FocusClassRec));
+ if (!to->focus)
+ FatalError("[Xi] no memory for class shift.\n");
+ } else
+ classes->focus = NULL;
+
+ oldTrace = to->focus->trace;
+ memcpy(to->focus, from->focus, sizeof(FocusClassRec));
+ to->focus->trace = xrealloc(oldTrace,
+ to->focus->traceSize * sizeof(WindowPtr));
+ if (!to->focus->trace && to->focus->traceSize)
+ FatalError("[Xi] no memory for trace.\n");
+ memcpy(to->focus->trace, from->focus->trace,
+ from->focus->traceSize * sizeof(WindowPtr));
+ to->focus->sourceid = from->id;
+ }
+ } else if (to->focus)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->focus = to->focus;
+ to->focus = NULL;
+ }
+
+}
+
+static void
+DeepCopyPointerClasses(DeviceIntPtr from, DeviceIntPtr to)
+{
+ ClassesPtr classes;
+
+ /* Feedback classes must be copied first */
+ if (from->ptrfeed)
+ {
+ PtrFeedbackPtr *p, it;
+ if (!to->ptrfeed)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->ptrfeed = classes->ptrfeed;
+ }
+
+ p = &to->ptrfeed;
+ for (it = from->ptrfeed; it; it = it->next)
+ {
+ if (!(*p))
+ {
+ *p = xcalloc(1, sizeof(PtrFeedbackClassRec));
+ if (!*p)
+ {
+ ErrorF("[Xi] Cannot alloc memory for class copy.");
+ return;
+ }
+ }
+ (*p)->CtrlProc = it->CtrlProc;
+ (*p)->ctrl = it->ctrl;
+
+ p = &(*p)->next;
+ }
+ } else if (to->ptrfeed && !from->ptrfeed)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->ptrfeed = to->ptrfeed;
+ to->ptrfeed = NULL;
+ }
+
+ if (from->valuator)
+ {
+ ValuatorClassPtr v;
+ if (!to->valuator)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->valuator = classes->valuator;
+ if (to->valuator)
+ classes->valuator = NULL;
+ }
+
+ to->valuator = xrealloc(to->valuator, sizeof(ValuatorClassRec) +
+ from->valuator->numAxes * sizeof(AxisInfo) +
+ from->valuator->numAxes * sizeof(double));
+ v = to->valuator;
+ if (!v)
+ FatalError("[Xi] no memory for class shift.\n");
+
+ v->numAxes = from->valuator->numAxes;
+ v->axes = (AxisInfoPtr)&v[1];
+ memcpy(v->axes, from->valuator->axes, v->numAxes * sizeof(AxisInfo));
+
+ v->axisVal = (double*)(v->axes + from->valuator->numAxes);
+ v->sourceid = from->id;
+ v->mode = from->valuator->mode;
+ } else if (to->valuator && !from->valuator)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->valuator = to->valuator;
+ to->valuator = NULL;
+ }
+
+ if (from->button)
+ {
+ if (!to->button)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->button = classes->button;
+ if (!to->button)
+ {
+ to->button = xcalloc(1, sizeof(ButtonClassRec));
+ if (!to->button)
+ FatalError("[Xi] no memory for class shift.\n");
+ } else
+ classes->button = NULL;
+ }
+
+ if (from->button->xkb_acts)
+ {
+ if (!to->button->xkb_acts)
+ {
+ to->button->xkb_acts = xcalloc(1, sizeof(XkbAction));
+ if (!to->button->xkb_acts)
+ FatalError("[Xi] not enough memory for xkb_acts.\n");
+ }
+ memcpy(to->button->xkb_acts, from->button->xkb_acts,
+ sizeof(XkbAction));
+ } else
+ xfree(to->button->xkb_acts);
+
+ memcpy(to->button->labels, from->button->labels,
+ from->button->numButtons * sizeof(Atom));
+ to->button->sourceid = from->id;
+ } else if (to->button && !from->button)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->button = to->button;
+ to->button = NULL;
+ }
+
+ if (from->proximity)
+ {
+ if (!to->proximity)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->proximity = classes->proximity;
+ if (!to->proximity)
+ {
+ to->proximity = xcalloc(1, sizeof(ProximityClassRec));
+ if (!to->proximity)
+ FatalError("[Xi] no memory for class shift.\n");
+ } else
+ classes->proximity = NULL;
+ }
+ memcpy(to->proximity, from->proximity, sizeof(ProximityClassRec));
+ to->proximity->sourceid = from->id;
+ } else if (to->proximity)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->proximity = to->proximity;
+ to->proximity = NULL;
+ }
+
+ if (from->absolute)
+ {
+ if (!to->absolute)
+ {
+ classes = dixLookupPrivate(&to->devPrivates,
+ UnusedClassesPrivateKey);
+ to->absolute = classes->absolute;
+ if (!to->absolute)
+ {
+ to->absolute = xcalloc(1, sizeof(AbsoluteClassRec));
+ if (!to->absolute)
+ FatalError("[Xi] no memory for class shift.\n");
+ } else
+ classes->absolute = NULL;
+ }
+ memcpy(to->absolute, from->absolute, sizeof(AbsoluteClassRec));
+ to->absolute->sourceid = from->id;
+ } else if (to->absolute)
+ {
+ ClassesPtr classes;
+ classes = dixLookupPrivate(&to->devPrivates, UnusedClassesPrivateKey);
+ classes->absolute = to->absolute;
+ to->absolute = NULL;
+ }
+}
+
+/**
+ * Copies the CONTENT of the classes of device from into the classes in device
+ * to. From and to are identical after finishing.
+ *
+ * If to does not have classes from currenly has, the classes are stored in
+ * to's devPrivates system. Later, we recover it again from there if needed.
+ * Saves a few memory allocations.
+ */
+void
+DeepCopyDeviceClasses(DeviceIntPtr from, DeviceIntPtr to, DeviceChangedEvent *dce)
+{
+ /* generic feedback classes, not tied to pointer and/or keyboard */
+ DeepCopyFeedbackClasses(from, to);
+
+ if ((dce->flags & DEVCHANGE_KEYBOARD_EVENT))
+ DeepCopyKeyboardClasses(from, to);
+ if ((dce->flags & DEVCHANGE_POINTER_EVENT))
+ DeepCopyPointerClasses(from, to);
+}
+
+
+/**
+ * Send an XI2 DeviceChangedEvent to all interested clients.
+ */
+void
+XISendDeviceChangedEvent(DeviceIntPtr device, DeviceIntPtr master, DeviceChangedEvent *dce)
+{
+ xXIDeviceChangedEvent *dcce;
+ int rc;
+
+ rc = EventToXI2((InternalEvent*)dce, (xEvent**)&dcce);
+ if (rc != Success)
+ {
+ ErrorF("[Xi] event conversion from DCE failed with code %d\n", rc);
+ return;
+ }
+
+ /* we don't actually swap if there's a NullClient, swapping is done
+ * later when event is delivered. */
+ SendEventToAllWindows(master, XI_DeviceChangedMask, (xEvent*)dcce, 1);
+ xfree(dcce);
+}
+
+static void
+ChangeMasterDeviceClasses(DeviceIntPtr device, DeviceChangedEvent *dce)
+{
+ DeviceIntPtr slave;
+ int rc;
+
+ /* For now, we don't have devices that change physically. */
+ if (!IsMaster(device))
+ return;
+
+ rc = dixLookupDevice(&slave, dce->sourceid, serverClient, DixReadAccess);
+
+ if (rc != Success)
+ return; /* Device has disappeared */
+
+ if (!slave->u.master)
+ return; /* set floating since the event */
+
+ if (slave->u.master->id != dce->masterid)
+ return; /* not our slave anymore, don't care */
+
+ /* FIXME: we probably need to send a DCE for the new slave now */
+
+ device->public.devicePrivate = slave->public.devicePrivate;
+
+ /* FIXME: the classes may have changed since we generated the event. */
+ DeepCopyDeviceClasses(slave, device, dce);
+ XISendDeviceChangedEvent(slave, device, dce);
+}
+
+/**
+ * Update the device state according to the data in the event.
+ *
+ * return values are
+ * DEFAULT ... process as normal
+ * DONT_PROCESS ... return immediately from caller
+ */
+#define DEFAULT 0
+#define DONT_PROCESS 1
+int
+UpdateDeviceState(DeviceIntPtr device, DeviceEvent* event)
+{
+ int i;
+ int key = 0,
+ bit = 0,
+ last_valuator;
+
+ KeyClassPtr k = NULL;
+ ButtonClassPtr b = NULL;
+ ValuatorClassPtr v = NULL;
+ BYTE *kptr = NULL;
+
+ /* This event is always the first we get, before the actual events with
+ * the data. However, the way how the DDX is set up, "device" will
+ * actually be the slave device that caused the event.
+ */
+ switch(event->type)
+ {
+ case ET_DeviceChanged:
+ ChangeMasterDeviceClasses(device, (DeviceChangedEvent*)event);
+ return DONT_PROCESS; /* event has been sent already */
+ case ET_Motion:
+ case ET_ButtonPress:
+ case ET_ButtonRelease:
+ case ET_KeyPress:
+ case ET_KeyRelease:
+ case ET_ProximityIn:
+ case ET_ProximityOut:
+ break;
+ default:
+ /* other events don't update the device */
+ return DEFAULT;
+ }
+
+ k = device->key;
+ v = device->valuator;
+ b = device->button;
+
+ key = event->detail.key;
+ bit = 1 << (key & 7);
+
+ /* Update device axis */
+ /* Check valuators first */
+ last_valuator = -1;
+ for (i = 0; i < MAX_VALUATORS; i++)
+ {
+ if (BitIsOn(&event->valuators.mask, i))
+ {
+ if (!v)
+ {
+ ErrorF("[Xi] Valuators reported for non-valuator device '%s'. "
+ "Ignoring event.\n", device->name);
+ return DONT_PROCESS;
+ } else if (v->numAxes < i)
+ {
+ ErrorF("[Xi] Too many valuators reported for device '%s'. "
+ "Ignoring event.\n", device->name);
+ return DONT_PROCESS;
+ }
+ last_valuator = i;
+ }
+ }
+
+ for (i = 0; i <= last_valuator && i < v->numAxes; i++)
+ {
+ if (BitIsOn(&event->valuators.mask, i))
+ {
+ /* XXX: Relative/Absolute mode */
+ v->axisVal[i] = event->valuators.data[i];
+ v->axisVal[i] += event->valuators.data_frac[i];
+ }
+ }
+
+ if (event->type == ET_KeyPress) {
+ if (!k)
+ return DONT_PROCESS;
+
+ kptr = &k->down[key >> 3];
+ /* don't allow ddx to generate multiple downs, but repeats are okay */
+ if ((*kptr & bit) && !event->key_repeat)
+ return DONT_PROCESS;
+ if (device->valuator)
+ device->valuator->motionHintWindow = NullWindow;
+ *kptr |= bit;
+ } else if (event->type == ET_KeyRelease) {
+ if (!k)
+ return DONT_PROCESS;
+
+ kptr = &k->down[key >> 3];
+ if (!(*kptr & bit)) /* guard against duplicates */
+ return DONT_PROCESS;
+ if (device->valuator)
+ device->valuator->motionHintWindow = NullWindow;
+ *kptr &= ~bit;
+ } else if (event->type == ET_ButtonPress) {
+ Mask mask;
+ if (!b)
+ return DONT_PROCESS;
+
+ kptr = &b->down[key >> 3];
+ if ((*kptr & bit) != 0)
+ return DONT_PROCESS;
+ *kptr |= bit;
+ if (device->valuator)
+ device->valuator->motionHintWindow = NullWindow;
+ if (!b->map[key])
+ return DONT_PROCESS;
+ b->buttonsDown++;
+ b->motionMask = DeviceButtonMotionMask;
+ if (b->map[key] <= 5)
+ b->state |= (Button1Mask >> 1) << b->map[key];
+
+ /* Add state and motionMask to the filter for this event */
+ mask = DevicePointerMotionMask | b->state | b->motionMask;
+ SetMaskForEvent(device->id, mask, DeviceMotionNotify);
+ mask = PointerMotionMask | b->state | b->motionMask;
+ SetMaskForEvent(device->id, mask, MotionNotify);
+ } else if (event->type == ET_ButtonRelease) {
+ Mask mask;
+ if (!b)
+ return DONT_PROCESS;
+
+ kptr = &b->down[key>>3];
+ if (!(*kptr & bit))
+ return DONT_PROCESS;
+ if (IsMaster(device)) {
+ DeviceIntPtr sd;
+
+ /*
+ * Leave the button down if any slave has the
+ * button still down. Note that this depends on the
+ * event being delivered through the slave first
+ */
+ for (sd = inputInfo.devices; sd; sd = sd->next) {
+ if (IsMaster(sd) || sd->u.master != device)
+ continue;
+ if (!sd->button)
+ continue;
+ if ((sd->button->down[key>>3] & bit) != 0)
+ return DONT_PROCESS;
+ }
+ }
+ *kptr &= ~bit;
+ if (device->valuator)
+ device->valuator->motionHintWindow = NullWindow;
+ if (!b->map[key])
+ return DONT_PROCESS;
+ if (b->buttonsDown >= 1 && !--b->buttonsDown)
+ b->motionMask = 0;
+ if (b->map[key] <= 5)
+ b->state &= ~((Button1Mask >> 1) << b->map[key]);
+
+ /* Add state and motionMask to the filter for this event */
+ mask = DevicePointerMotionMask | b->state | b->motionMask;
+ SetMaskForEvent(device->id, mask, DeviceMotionNotify);
+ mask = PointerMotionMask | b->state | b->motionMask;
+ SetMaskForEvent(device->id, mask, MotionNotify);
+ } else if (event->type == ET_ProximityIn)
+ device->valuator->mode &= ~OutOfProximity;
+ else if (event->type == ET_ProximityOut)
+ device->valuator->mode |= OutOfProximity;
+
+ return DEFAULT;
+}
+
+static void
+ProcessRawEvent(RawDeviceEvent *ev, DeviceIntPtr device)
+{
+ GrabPtr grab = device->deviceGrab.grab;
+
+ if (grab)
+ DeliverGrabbedEvent((InternalEvent*)ev, device, FALSE);
+ else { /* deliver to all root windows */
+ xEvent *xi;
+ int i;
+
+ i = EventToXI2((InternalEvent*)ev, (xEvent**)&xi);
+ if (i != Success)
+ {
+ ErrorF("[Xi] %s: XI2 conversion failed in ProcessRawEvent (%d)\n",
+ device->name, i);
+ return;
+ }
+
+ for (i = 0; i < screenInfo.numScreens; i++)
+ DeliverEventsToWindow(device, WindowTable[i], xi, 1,
+ GetEventFilter(device, xi), NULL);
+ xfree(xi);
+ }
+}
+
+/**
+ * Main device event processing function.
+ * Called from when processing the events from the event queue.
+ *
+ */
+void
+ProcessOtherEvent(InternalEvent *ev, DeviceIntPtr device)
+{
+ GrabPtr grab;
+ Bool deactivateDeviceGrab = FALSE;
+ int key = 0, rootX, rootY;
+ ButtonClassPtr b;
+ KeyClassPtr k;
+ ValuatorClassPtr v;
+ int ret = 0;
+ int state, i;
+ DeviceIntPtr mouse = NULL, kbd = NULL;
+ DeviceEvent *event = &ev->device_event;
+
+ CHECKEVENT(ev);
+
+ if (ev->any.type == ET_RawKeyPress ||
+ ev->any.type == ET_RawKeyRelease ||
+ ev->any.type == ET_RawButtonPress ||
+ ev->any.type == ET_RawButtonRelease ||
+ ev->any.type == ET_RawMotion)
+ {
+ ProcessRawEvent(&ev->raw_event, device);
+ return;
+ }
+
+ if (IsPointerDevice(device))
+ {
+ kbd = GetPairedDevice(device);
+ mouse = device;
+ if (!kbd->key) /* can happen with floating SDs */
+ kbd = NULL;
+ } else
+ {
+ mouse = GetPairedDevice(device);
+ kbd = device;
+ if (!mouse->valuator || !mouse->button) /* may be float. SDs */
+ mouse = NULL;
+ }
+
+ /* State needs to be assembled BEFORE the device is updated. */
+ state = (kbd && kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->state) : 0;
+ state |= (mouse && mouse->button) ? (mouse->button->state) : 0;
+
+ for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
+ if (BitIsOn(mouse->button->down, i))
+ SetBit(event->buttons, i);
+
+ if (kbd && kbd->key)
+ {
+ XkbStatePtr state;
+ /* we need the state before the event happens */
+ if (event->type == ET_KeyPress || event->type == ET_KeyRelease)
+ state = &kbd->key->xkbInfo->prev_state;
+ else
+ state = &kbd->key->xkbInfo->state;
+
+ event->mods.base = state->base_mods;
+ event->mods.latched = state->latched_mods;
+ event->mods.locked = state->locked_mods;
+ event->mods.effective = state->mods;
+
+ event->group.base = state->base_group;
+ event->group.latched = state->latched_group;
+ event->group.locked = state->locked_group;
+ event->group.effective = state->group;
+ }
+
+ ret = UpdateDeviceState(device, event);
+ if (ret == DONT_PROCESS)
+ return;
+
+ v = device->valuator;
+ b = device->button;
+ k = device->key;
+
+ if (IsMaster(device) || !device->u.master)
+ CheckMotion(event, device);
+
+ switch (event->type)
+ {
+ case ET_Motion:
+ case ET_ButtonPress:
+ case ET_ButtonRelease:
+ case ET_KeyPress:
+ case ET_KeyRelease:
+ case ET_ProximityIn:
+ case ET_ProximityOut:
+ GetSpritePosition(device, &rootX, &rootY);
+ event->root_x = rootX;
+ event->root_y = rootY;
+ NoticeEventTime((InternalEvent*)event);
+ event->corestate = state;
+ key = event->detail.key;
+ break;
+ default:
+ break;
+ }
+
+#if 0
+ /* FIXME: I'm broken. Please fix me. Thanks */
+ if (DeviceEventCallback) {
+ DeviceEventInfoRec eventinfo;
+
+ eventinfo.events = (xEventPtr) xE;
+ eventinfo.count = count;
+ CallCallbacks(&DeviceEventCallback, (pointer) & eventinfo);
+ }
+#endif
+ grab = device->deviceGrab.grab;
+
+ switch(event->type)
+ {
+ case ET_KeyPress:
+ if (!grab && CheckDeviceGrabs(device, event, 0)) {
+ device->deviceGrab.activatingKey = key;
+ return;
+ }
+ break;
+ case ET_KeyRelease:
+ if (grab && device->deviceGrab.fromPassiveGrab &&
+ (key == device->deviceGrab.activatingKey) &&
+ (device->deviceGrab.grab->type == KeyPress ||
+ device->deviceGrab.grab->type == DeviceKeyPress ||
+ device->deviceGrab.grab->type == XI_KeyPress))
+ deactivateDeviceGrab = TRUE;
+ break;
+ case ET_ButtonPress:
+ event->detail.button = b->map[key];
+ if (!event->detail.button) { /* there's no button 0 */
+ event->detail.button = key;
+ return;
+ }
+ if (!grab && CheckDeviceGrabs(device, event, 0))
+ {
+ /* if a passive grab was activated, the event has been sent
+ * already */
+ return;
+ }
+ break;
+ case ET_ButtonRelease:
+ event->detail.button = b->map[key];
+ if (!event->detail.button) { /* there's no button 0 */
+ event->detail.button = key;
+ return;
+ }
+ if (grab && !b->buttonsDown &&
+ device->deviceGrab.fromPassiveGrab &&
+ (device->deviceGrab.grab->type == ButtonPress ||
+ device->deviceGrab.grab->type == DeviceButtonPress ||
+ device->deviceGrab.grab->type == XI_ButtonPress))
+ deactivateDeviceGrab = TRUE;
+ default:
+ break;
+ }
+
+
+ if (grab)
+ DeliverGrabbedEvent((InternalEvent*)event, device, deactivateDeviceGrab);
+ else if (device->focus && !IsPointerEvent((InternalEvent*)ev))
+ DeliverFocusedEvent(device, (InternalEvent*)event,
+ GetSpriteWindow(device));
+ else
+ DeliverDeviceEvents(GetSpriteWindow(device), (InternalEvent*)event,
+ NullGrab, NullWindow, device);
+
+ if (deactivateDeviceGrab == TRUE)
+ (*device->deviceGrab.DeactivateGrab) (device);
+ event->detail.key = key;
+}
+
+int
+InitProximityClassDeviceStruct(DeviceIntPtr dev)
+{
+ ProximityClassPtr proxc;
+
+ proxc = (ProximityClassPtr) xalloc(sizeof(ProximityClassRec));
+ if (!proxc)
+ return FALSE;
+ proxc->sourceid = dev->id;
+ dev->proximity = proxc;
+ return TRUE;
+}
+
+/**
+ * Initialise the device's valuators. The memory must already be allocated,
+ * this function merely inits the matching axis (specified through axnum) to
+ * sane values.
+ *
+ * It is a condition that (minval < maxval).
+ *
+ * @see InitValuatorClassDeviceStruct
+ */
+void
+InitValuatorAxisStruct(DeviceIntPtr dev, int axnum, Atom label, int minval, int maxval,
+ int resolution, int min_res, int max_res)
+{
+ AxisInfoPtr ax;
+
+ if (!dev || !dev->valuator || minval > maxval)
+ return;
+ if (axnum >= dev->valuator->numAxes)
+ return;
+
+ ax = dev->valuator->axes + axnum;
+
+ ax->min_value = minval;
+ ax->max_value = maxval;
+ ax->resolution = resolution;
+ ax->min_resolution = min_res;
+ ax->max_resolution = max_res;
+ ax->label = label;
+}
+
+static void
+FixDeviceStateNotify(DeviceIntPtr dev, deviceStateNotify * ev, KeyClassPtr k,
+ ButtonClassPtr b, ValuatorClassPtr v, int first)
+{
+ ev->type = DeviceStateNotify;
+ ev->deviceid = dev->id;
+ ev->time = currentTime.milliseconds;
+ ev->classes_reported = 0;
+ ev->num_keys = 0;
+ ev->num_buttons = 0;
+ ev->num_valuators = 0;
+
+ if (b) {
+ ev->classes_reported |= (1 << ButtonClass);
+ ev->num_buttons = b->numButtons;
+ memcpy((char*)ev->buttons, (char*)b->down, 4);
+ } else if (k) {
+ ev->classes_reported |= (1 << KeyClass);
+ ev->num_keys = k->xkbInfo->desc->max_key_code -
+ k->xkbInfo->desc->min_key_code;
+ memmove((char *)&ev->keys[0], (char *)k->down, 4);
+ }
+ if (v) {
+ int nval = v->numAxes - first;
+
+ ev->classes_reported |= (1 << ValuatorClass);
+ ev->classes_reported |= (dev->valuator->mode << ModeBitsShift);
+ ev->num_valuators = nval < 3 ? nval : 3;
+ switch (ev->num_valuators) {
+ case 3:
+ ev->valuator2 = v->axisVal[first + 2];
+ case 2:
+ ev->valuator1 = v->axisVal[first + 1];
+ case 1:
+ ev->valuator0 = v->axisVal[first];
+ break;
+ }
+ }
+}
+
+static void
+FixDeviceValuator(DeviceIntPtr dev, deviceValuator * ev, ValuatorClassPtr v,
+ int first)
+{
+ int nval = v->numAxes - first;
+
+ ev->type = DeviceValuator;
+ ev->deviceid = dev->id;
+ ev->num_valuators = nval < 3 ? nval : 3;
+ ev->first_valuator = first;
+ switch (ev->num_valuators) {
+ case 3:
+ ev->valuator2 = v->axisVal[first + 2];
+ case 2:
+ ev->valuator1 = v->axisVal[first + 1];
+ case 1:
+ ev->valuator0 = v->axisVal[first];
+ break;
+ }
+ first += ev->num_valuators;
+}
+
+void
+DeviceFocusEvent(DeviceIntPtr dev, int type, int mode, int detail,
+ WindowPtr pWin)
+{
+ deviceFocus event;
+ xXIFocusInEvent *xi2event;
+ DeviceIntPtr mouse;
+ int btlen, len, i;
+
+ mouse = (IsMaster(dev) || dev->u.master) ? GetMaster(dev, MASTER_POINTER) : dev;
+
+ /* XI 2 event */
+ btlen = (mouse->button) ? bits_to_bytes(mouse->button->numButtons) : 0;
+ btlen = bytes_to_int32(btlen);
+ len = sizeof(xXIFocusInEvent) + btlen * 4;
+
+ xi2event = xcalloc(1, len);
+ xi2event->type = GenericEvent;
+ xi2event->extension = IReqCode;
+ xi2event->evtype = type;
+ xi2event->length = bytes_to_int32(len - sizeof(xEvent));
+ xi2event->buttons_len = btlen;
+ xi2event->detail = detail;
+ xi2event->time = currentTime.milliseconds;
+ xi2event->deviceid = dev->id;
+ xi2event->sourceid = dev->id; /* a device doesn't change focus by itself */
+ xi2event->mode = mode;
+ xi2event->root_x = FP1616(mouse->spriteInfo->sprite->hot.x, 0);
+ xi2event->root_y = FP1616(mouse->spriteInfo->sprite->hot.y, 0);
+
+ for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
+ if (BitIsOn(mouse->button->down, i))
+ SetBit(&xi2event[1], i);
+
+ if (dev->key)
+ {
+ xi2event->mods.base_mods = dev->key->xkbInfo->state.base_mods;
+ xi2event->mods.latched_mods = dev->key->xkbInfo->state.latched_mods;
+ xi2event->mods.locked_mods = dev->key->xkbInfo->state.locked_mods;
+ xi2event->mods.effective_mods = dev->key->xkbInfo->state.mods;
+
+ xi2event->group.base_group = dev->key->xkbInfo->state.base_group;
+ xi2event->group.latched_group = dev->key->xkbInfo->state.latched_group;
+ xi2event->group.locked_group = dev->key->xkbInfo->state.locked_group;
+ xi2event->group.effective_group = dev->key->xkbInfo->state.group;
+ }
+
+ FixUpEventFromWindow(dev, (xEvent*)xi2event, pWin, None, FALSE);
+
+ DeliverEventsToWindow(dev, pWin, (xEvent*)xi2event, 1,
+ GetEventFilter(dev, (xEvent*)xi2event), NullGrab);
+
+ xfree(xi2event);
+
+ /* XI 1.x event */
+ event.deviceid = dev->id;
+ event.mode = mode;
+ event.type = (type == XI_FocusIn) ? DeviceFocusIn : DeviceFocusOut;
+ event.detail = detail;
+ event.window = pWin->drawable.id;
+ event.time = currentTime.milliseconds;
+
+ DeliverEventsToWindow(dev, pWin, (xEvent *) & event, 1,
+ DeviceFocusChangeMask, NullGrab);
+
+ if ((type == DeviceFocusIn) &&
+ (wOtherInputMasks(pWin)) &&
+ (wOtherInputMasks(pWin)->inputEvents[dev->id] & DeviceStateNotifyMask))
+ {
+ int evcount = 1;
+ deviceStateNotify *ev, *sev;
+ deviceKeyStateNotify *kev;
+ deviceButtonStateNotify *bev;
+
+ KeyClassPtr k;
+ ButtonClassPtr b;
+ ValuatorClassPtr v;
+ int nval = 0, nkeys = 0, nbuttons = 0, first = 0;
+
+ if ((b = dev->button) != NULL) {
+ nbuttons = b->numButtons;
+ if (nbuttons > 32)
+ evcount++;
+ }
+ if ((k = dev->key) != NULL) {
+ nkeys = k->xkbInfo->desc->max_key_code -
+ k->xkbInfo->desc->min_key_code;
+ if (nkeys > 32)
+ evcount++;
+ if (nbuttons > 0) {
+ evcount++;
+ }
+ }
+ if ((v = dev->valuator) != NULL) {
+ nval = v->numAxes;
+
+ if (nval > 3)
+ evcount++;
+ if (nval > 6) {
+ if (!(k && b))
+ evcount++;
+ if (nval > 9)
+ evcount += ((nval - 7) / 3);
+ }
+ }
+
+ sev = ev = (deviceStateNotify *) xalloc(evcount * sizeof(xEvent));
+ FixDeviceStateNotify(dev, ev, NULL, NULL, NULL, first);
+
+ if (b != NULL) {
+ FixDeviceStateNotify(dev, ev++, NULL, b, v, first);
+ first += 3;
+ nval -= 3;
+ if (nbuttons > 32) {
+ (ev - 1)->deviceid |= MORE_EVENTS;
+ bev = (deviceButtonStateNotify *) ev++;
+ bev->type = DeviceButtonStateNotify;
+ bev->deviceid = dev->id;
+ memcpy((char*)&bev->buttons[4], (char*)&b->down[4], DOWN_LENGTH - 4);
+ }
+ if (nval > 0) {
+ (ev - 1)->deviceid |= MORE_EVENTS;
+ FixDeviceValuator(dev, (deviceValuator *) ev++, v, first);
+ first += 3;
+ nval -= 3;
+ }
+ }
+
+ if (k != NULL) {
+ FixDeviceStateNotify(dev, ev++, k, NULL, v, first);
+ first += 3;
+ nval -= 3;
+ if (nkeys > 32) {
+ (ev - 1)->deviceid |= MORE_EVENTS;
+ kev = (deviceKeyStateNotify *) ev++;
+ kev->type = DeviceKeyStateNotify;
+ kev->deviceid = dev->id;
+ memmove((char *)&kev->keys[0], (char *)&k->down[4], 28);
+ }
+ if (nval > 0) {
+ (ev - 1)->deviceid |= MORE_EVENTS;
+ FixDeviceValuator(dev, (deviceValuator *) ev++, v, first);
+ first += 3;
+ nval -= 3;
+ }
+ }
+
+ while (nval > 0) {
+ FixDeviceStateNotify(dev, ev++, NULL, NULL, v, first);
+ first += 3;
+ nval -= 3;
+ if (nval > 0) {
+ (ev - 1)->deviceid |= MORE_EVENTS;
+ FixDeviceValuator(dev, (deviceValuator *) ev++, v, first);
+ first += 3;
+ nval -= 3;
+ }
+ }
+
+ DeliverEventsToWindow(dev, pWin, (xEvent *) sev, evcount,
+ DeviceStateNotifyMask, NullGrab);
+ xfree(sev);
+ }
+}
+
+int
+CheckGrabValues(ClientPtr client, GrabParameters* param)
+{
+ if (param->grabtype != GRABTYPE_CORE &&
+ param->grabtype != GRABTYPE_XI &&
+ param->grabtype != GRABTYPE_XI2)
+ {
+ ErrorF("[Xi] grabtype is invalid. This is a bug.\n");
+ return BadImplementation;
+ }
+
+ if ((param->this_device_mode != GrabModeSync) &&
+ (param->this_device_mode != GrabModeAsync)) {
+ client->errorValue = param->this_device_mode;
+ return BadValue;
+ }
+ if ((param->other_devices_mode != GrabModeSync) &&
+ (param->other_devices_mode != GrabModeAsync)) {
+ client->errorValue = param->other_devices_mode;
+ return BadValue;
+ }
+
+ if (param->grabtype != GRABTYPE_XI2 && (param->modifiers != AnyModifier) &&
+ (param->modifiers & ~AllModifiersMask)) {
+ client->errorValue = param->modifiers;
+ return BadValue;
+ }
+
+ if ((param->ownerEvents != xFalse) && (param->ownerEvents != xTrue)) {
+ client->errorValue = param->ownerEvents;
+ return BadValue;
+ }
+ return Success;
+}
+
+int
+GrabButton(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
+ int button, GrabParameters *param, GrabType grabtype,
+ GrabMask *mask)
+{
+ WindowPtr pWin, confineTo;
+ CursorPtr cursor;
+ GrabPtr grab;
+ int rc, type = -1;
+ Mask access_mode = DixGrabAccess;
+
+ rc = CheckGrabValues(client, param);
+ if (rc != Success)
+ return rc;
+ if (param->confineTo == None)
+ confineTo = NullWindow;
+ else {
+ rc = dixLookupWindow(&confineTo, param->confineTo, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ }
+ if (param->cursor == None)
+ cursor = NullCursor;
+ else {
+ rc = dixLookupResourceByType((pointer *)&cursor, param->cursor,
+ RT_CURSOR, client, DixUseAccess);
+ if (rc != Success)
+ {
+ client->errorValue = param->cursor;
+ return (rc == BadValue) ? BadCursor : rc;
+ }
+ access_mode |= DixForceAccess;
+ }
+ if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync)
+ access_mode |= DixFreezeAccess;
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode);
+ if (rc != Success)
+ return rc;
+ rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+
+ if (grabtype == GRABTYPE_XI)
+ type = DeviceButtonPress;
+ else if (grabtype == GRABTYPE_XI2)
+ type = XI_ButtonPress;
+
+ grab = CreateGrab(client->index, dev, modifier_device, pWin, grabtype,
+ mask, param, type, button, confineTo, cursor);
+ if (!grab)
+ return BadAlloc;
+ return AddPassiveGrabToList(client, grab);
+}
+
+/**
+ * Grab the given key. If grabtype is GRABTYPE_XI, the key is a keycode. If
+ * grabtype is GRABTYPE_XI2, the key is a keysym.
+ */
+int
+GrabKey(ClientPtr client, DeviceIntPtr dev, DeviceIntPtr modifier_device,
+ int key, GrabParameters *param, GrabType grabtype, GrabMask *mask)
+{
+ WindowPtr pWin;
+ GrabPtr grab;
+ KeyClassPtr k = dev->key;
+ Mask access_mode = DixGrabAccess;
+ int rc, type = -1;
+
+ rc = CheckGrabValues(client, param);
+ if (rc != Success)
+ return rc;
+ if (k == NULL)
+ return BadMatch;
+ if (grabtype == GRABTYPE_XI)
+ {
+ if ((key > k->xkbInfo->desc->max_key_code ||
+ key < k->xkbInfo->desc->min_key_code)
+ && (key != AnyKey)) {
+ client->errorValue = key;
+ return BadValue;
+ }
+ type = DeviceKeyPress;
+ } else if (grabtype == GRABTYPE_XI2)
+ type = XI_KeyPress;
+
+ rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync)
+ access_mode |= DixFreezeAccess;
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode);
+ if (rc != Success)
+ return rc;
+
+ grab = CreateGrab(client->index, dev, modifier_device, pWin, grabtype,
+ mask, param, type, key, NULL, NULL);
+ if (!grab)
+ return BadAlloc;
+ return AddPassiveGrabToList(client, grab);
+}
+
+/* Enter/FocusIn grab */
+int
+GrabWindow(ClientPtr client, DeviceIntPtr dev, int type,
+ GrabParameters *param, GrabMask *mask)
+{
+ WindowPtr pWin;
+ CursorPtr cursor;
+ GrabPtr grab;
+ Mask access_mode = DixGrabAccess;
+ int rc;
+
+ rc = CheckGrabValues(client, param);
+ if (rc != Success)
+ return rc;
+
+ rc = dixLookupWindow(&pWin, param->grabWindow, client, DixSetAttrAccess);
+ if (rc != Success)
+ return rc;
+ if (param->cursor == None)
+ cursor = NullCursor;
+ else {
+ rc = dixLookupResourceByType((pointer *)&cursor, param->cursor,
+ RT_CURSOR, client, DixUseAccess);
+ if (rc != Success)
+ {
+ client->errorValue = param->cursor;
+ return (rc == BadValue) ? BadCursor : rc;
+ }
+ access_mode |= DixForceAccess;
+ }
+ if (param->this_device_mode == GrabModeSync || param->other_devices_mode == GrabModeSync)
+ access_mode |= DixFreezeAccess;
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, dev, access_mode);
+ if (rc != Success)
+ return rc;
+
+ grab = CreateGrab(client->index, dev, dev, pWin, GRABTYPE_XI2,
+ mask, param, (type == XIGrabtypeEnter) ? XI_Enter : XI_FocusIn,
+ 0, NULL, cursor);
+
+ if (!grab)
+ return BadAlloc;
+
+ return AddPassiveGrabToList(client, grab);
+}
+
+int
+SelectForWindow(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client,
+ Mask mask, Mask exclusivemasks)
+{
+ int mskidx = dev->id;
+ int i, ret;
+ Mask check;
+ InputClientsPtr others;
+
+ check = (mask & exclusivemasks);
+ if (wOtherInputMasks(pWin)) {
+ if (check & wOtherInputMasks(pWin)->inputEvents[mskidx]) { /* It is illegal for two different
+ * clients to select on any of the
+ * events for maskcheck. However,
+ * it is OK, for some client to
+ * continue selecting on one of those
+ * events. */
+ for (others = wOtherInputMasks(pWin)->inputClients; others;
+ others = others->next) {
+ if (!SameClient(others, client) && (check &
+ others->mask[mskidx]))
+ return BadAccess;
+ }
+ }
+ for (others = wOtherInputMasks(pWin)->inputClients; others;
+ others = others->next) {
+ if (SameClient(others, client)) {
+ check = others->mask[mskidx];
+ others->mask[mskidx] = mask;
+ if (mask == 0) {
+ for (i = 0; i < EMASKSIZE; i++)
+ if (i != mskidx && others->mask[i] != 0)
+ break;
+ if (i == EMASKSIZE) {
+ RecalculateDeviceDeliverableEvents(pWin);
+ if (ShouldFreeInputMasks(pWin, FALSE))
+ FreeResource(others->resource, RT_NONE);
+ return Success;
+ }
+ }
+ goto maskSet;
+ }
+ }
+ }
+ check = 0;
+ if ((ret = AddExtensionClient(pWin, client, mask, mskidx)) != Success)
+ return ret;
+ maskSet:
+ if (dev->valuator)
+ if ((dev->valuator->motionHintWindow == pWin) &&
+ (mask & DevicePointerMotionHintMask) &&
+ !(check & DevicePointerMotionHintMask) && !dev->deviceGrab.grab)
+ dev->valuator->motionHintWindow = NullWindow;
+ RecalculateDeviceDeliverableEvents(pWin);
+ return Success;
+}
+
+int
+AddExtensionClient(WindowPtr pWin, ClientPtr client, Mask mask, int mskidx)
+{
+ InputClientsPtr others;
+
+ if (!pWin->optional && !MakeWindowOptional(pWin))
+ return BadAlloc;
+ others = xcalloc(1, sizeof(InputClients));
+ if (!others)
+ return BadAlloc;
+ if (!pWin->optional->inputMasks && !MakeInputMasks(pWin))
+ return BadAlloc;
+ others->mask[mskidx] = mask;
+ others->resource = FakeClientID(client->index);
+ others->next = pWin->optional->inputMasks->inputClients;
+ pWin->optional->inputMasks->inputClients = others;
+ if (!AddResource(others->resource, RT_INPUTCLIENT, (pointer) pWin))
+ return BadAlloc;
+ return Success;
+}
+
+static Bool
+MakeInputMasks(WindowPtr pWin)
+{
+ struct _OtherInputMasks *imasks;
+
+ imasks = xcalloc(1, sizeof(struct _OtherInputMasks));
+ if (!imasks)
+ return FALSE;
+ pWin->optional->inputMasks = imasks;
+ return TRUE;
+}
+
+void
+RecalculateDeviceDeliverableEvents(WindowPtr pWin)
+{
+ InputClientsPtr others;
+ struct _OtherInputMasks *inputMasks; /* default: NULL */
+ WindowPtr pChild, tmp;
+ int i, j;
+
+ pChild = pWin;
+ while (1) {
+ if ((inputMasks = wOtherInputMasks(pChild)) != 0) {
+ for (i = 0; i < EMASKSIZE; i++)
+ memset(inputMasks->xi2mask[i], 0, sizeof(inputMasks->xi2mask[i]));
+ for (others = inputMasks->inputClients; others;
+ others = others->next) {
+ for (i = 0; i < EMASKSIZE; i++)
+ inputMasks->inputEvents[i] |= others->mask[i];
+ for (i = 0; i < EMASKSIZE; i++)
+ for (j = 0; j < XI2MASKSIZE; j++)
+ inputMasks->xi2mask[i][j] |= others->xi2mask[i][j];
+ }
+ for (i = 0; i < EMASKSIZE; i++)
+ inputMasks->deliverableEvents[i] = inputMasks->inputEvents[i];
+ for (tmp = pChild->parent; tmp; tmp = tmp->parent)
+ if (wOtherInputMasks(tmp))
+ for (i = 0; i < EMASKSIZE; i++)
+ inputMasks->deliverableEvents[i] |=
+ (wOtherInputMasks(tmp)->deliverableEvents[i]
+ & ~inputMasks->
+ dontPropagateMask[i] & PropagateMask[i]);
+ }
+ if (pChild->firstChild) {
+ pChild = pChild->firstChild;
+ continue;
+ }
+ while (!pChild->nextSib && (pChild != pWin))
+ pChild = pChild->parent;
+ if (pChild == pWin)
+ break;
+ pChild = pChild->nextSib;
+ }
+}
+
+int
+InputClientGone(WindowPtr pWin, XID id)
+{
+ InputClientsPtr other, prev;
+
+ if (!wOtherInputMasks(pWin))
+ return (Success);
+ prev = 0;
+ for (other = wOtherInputMasks(pWin)->inputClients; other;
+ other = other->next) {
+ if (other->resource == id) {
+ if (prev) {
+ prev->next = other->next;
+ xfree(other);
+ } else if (!(other->next)) {
+ if (ShouldFreeInputMasks(pWin, TRUE)) {
+ wOtherInputMasks(pWin)->inputClients = other->next;
+ xfree(wOtherInputMasks(pWin));
+ pWin->optional->inputMasks = (OtherInputMasks *) NULL;
+ CheckWindowOptionalNeed(pWin);
+ xfree(other);
+ } else {
+ other->resource = FakeClientID(0);
+ if (!AddResource(other->resource, RT_INPUTCLIENT,
+ (pointer) pWin))
+ return BadAlloc;
+ }
+ } else {
+ wOtherInputMasks(pWin)->inputClients = other->next;
+ xfree(other);
+ }
+ RecalculateDeviceDeliverableEvents(pWin);
+ return (Success);
+ }
+ prev = other;
+ }
+ FatalError("client not on device event list");
+}
+
+int
+SendEvent(ClientPtr client, DeviceIntPtr d, Window dest, Bool propagate,
+ xEvent * ev, Mask mask, int count)
+{
+ WindowPtr pWin;
+ WindowPtr effectiveFocus = NullWindow; /* only set if dest==InputFocus */
+ WindowPtr spriteWin = GetSpriteWindow(d);
+
+ if (dest == PointerWindow)
+ pWin = spriteWin;
+ else if (dest == InputFocus) {
+ WindowPtr inputFocus;
+
+ if (!d->focus)
+ inputFocus = spriteWin;
+ else
+ inputFocus = d->focus->win;
+
+ if (inputFocus == FollowKeyboardWin)
+ inputFocus = inputInfo.keyboard->focus->win;
+
+ if (inputFocus == NoneWin)
+ return Success;
+
+ /* If the input focus is PointerRootWin, send the event to where
+ * the pointer is if possible, then perhaps propogate up to root. */
+ if (inputFocus == PointerRootWin)
+ inputFocus = GetCurrentRootWindow(d);
+
+ if (IsParent(inputFocus, spriteWin)) {
+ effectiveFocus = inputFocus;
+ pWin = spriteWin;
+ } else
+ effectiveFocus = pWin = inputFocus;
+ } else
+ dixLookupWindow(&pWin, dest, client, DixSendAccess);
+ if (!pWin)
+ return BadWindow;
+ if ((propagate != xFalse) && (propagate != xTrue)) {
+ client->errorValue = propagate;
+ return BadValue;
+ }
+ ev->u.u.type |= 0x80;
+ if (propagate) {
+ for (; pWin; pWin = pWin->parent) {
+ if (DeliverEventsToWindow(d, pWin, ev, count, mask, NullGrab))
+ return Success;
+ if (pWin == effectiveFocus)
+ return Success;
+ if (wOtherInputMasks(pWin))
+ mask &= ~wOtherInputMasks(pWin)->dontPropagateMask[d->id];
+ if (!mask)
+ break;
+ }
+ } else if (!XaceHook(XACE_SEND_ACCESS, client, NULL, pWin, ev, count))
+ DeliverEventsToWindow(d, pWin, ev, count, mask, NullGrab);
+ return Success;
+}
+
+int
+SetButtonMapping(ClientPtr client, DeviceIntPtr dev, int nElts, BYTE * map)
+{
+ int i;
+ ButtonClassPtr b = dev->button;
+
+ if (b == NULL)
+ return BadMatch;
+
+ if (nElts != b->numButtons) {
+ client->errorValue = nElts;
+ return BadValue;
+ }
+ if (BadDeviceMap(&map[0], nElts, 1, 255, &client->errorValue))
+ return BadValue;
+ for (i = 0; i < nElts; i++)
+ if ((b->map[i + 1] != map[i]) && BitIsOn(b->down, i + 1))
+ return MappingBusy;
+ for (i = 0; i < nElts; i++)
+ b->map[i + 1] = map[i];
+ return Success;
+}
+
+int
+ChangeKeyMapping(ClientPtr client,
+ DeviceIntPtr dev,
+ unsigned len,
+ int type,
+ KeyCode firstKeyCode,
+ CARD8 keyCodes, CARD8 keySymsPerKeyCode, KeySym * map)
+{
+ KeySymsRec keysyms;
+ KeyClassPtr k = dev->key;
+
+ if (k == NULL)
+ return (BadMatch);
+
+ if (len != (keyCodes * keySymsPerKeyCode))
+ return BadLength;
+
+ if ((firstKeyCode < k->xkbInfo->desc->min_key_code) ||
+ (firstKeyCode + keyCodes - 1 > k->xkbInfo->desc->max_key_code)) {
+ client->errorValue = firstKeyCode;
+ return BadValue;
+ }
+ if (keySymsPerKeyCode == 0) {
+ client->errorValue = 0;
+ return BadValue;
+ }
+ keysyms.minKeyCode = firstKeyCode;
+ keysyms.maxKeyCode = firstKeyCode + keyCodes - 1;
+ keysyms.mapWidth = keySymsPerKeyCode;
+ keysyms.map = map;
+
+ XkbApplyMappingChange(dev, &keysyms, firstKeyCode, keyCodes, NULL,
+ serverClient);
+
+ return client->noClientException;
+}
+
+static void
+DeleteDeviceFromAnyExtEvents(WindowPtr pWin, DeviceIntPtr dev)
+{
+ WindowPtr parent;
+
+ /* Deactivate any grabs performed on this window, before making
+ * any input focus changes.
+ * Deactivating a device grab should cause focus events. */
+
+ if (dev->deviceGrab.grab && (dev->deviceGrab.grab->window == pWin))
+ (*dev->deviceGrab.DeactivateGrab) (dev);
+
+ /* If the focus window is a root window (ie. has no parent)
+ * then don't delete the focus from it. */
+
+ if (dev->focus && (pWin == dev->focus->win) && (pWin->parent != NullWindow)) {
+ int focusEventMode = NotifyNormal;
+
+ /* If a grab is in progress, then alter the mode of focus events. */
+
+ if (dev->deviceGrab.grab)
+ focusEventMode = NotifyWhileGrabbed;
+
+ switch (dev->focus->revert) {
+ case RevertToNone:
+ if (!ActivateFocusInGrab(dev, pWin, NoneWin))
+ DoFocusEvents(dev, pWin, NoneWin, focusEventMode);
+ dev->focus->win = NoneWin;
+ dev->focus->traceGood = 0;
+ break;
+ case RevertToParent:
+ parent = pWin;
+ do {
+ parent = parent->parent;
+ dev->focus->traceGood--;
+ }
+ while (!parent->realized);
+ if (!ActivateFocusInGrab(dev, pWin, parent))
+ DoFocusEvents(dev, pWin, parent, focusEventMode);
+ dev->focus->win = parent;
+ dev->focus->revert = RevertToNone;
+ break;
+ case RevertToPointerRoot:
+ if (!ActivateFocusInGrab(dev, pWin, PointerRootWin))
+ DoFocusEvents(dev, pWin, PointerRootWin, focusEventMode);
+ dev->focus->win = PointerRootWin;
+ dev->focus->traceGood = 0;
+ break;
+ case RevertToFollowKeyboard:
+ {
+ DeviceIntPtr kbd = GetMaster(dev, MASTER_KEYBOARD);
+ if (!kbd || (kbd == dev && kbd != inputInfo.keyboard))
+ kbd = inputInfo.keyboard;
+ if (kbd->focus->win) {
+ if (!ActivateFocusInGrab(dev, pWin, kbd->focus->win))
+ DoFocusEvents(dev, pWin, kbd->focus->win, focusEventMode);
+ dev->focus->win = FollowKeyboardWin;
+ dev->focus->traceGood = 0;
+ } else {
+ if (!ActivateFocusInGrab(dev, pWin, NoneWin))
+ DoFocusEvents(dev, pWin, NoneWin, focusEventMode);
+ dev->focus->win = NoneWin;
+ dev->focus->traceGood = 0;
+ }
+ }
+ break;
+ }
+ }
+
+ if (dev->valuator)
+ if (dev->valuator->motionHintWindow == pWin)
+ dev->valuator->motionHintWindow = NullWindow;
+}
+
+void
+DeleteWindowFromAnyExtEvents(WindowPtr pWin, Bool freeResources)
+{
+ int i;
+ DeviceIntPtr dev;
+ InputClientsPtr ic;
+ struct _OtherInputMasks *inputMasks;
+
+ for (dev = inputInfo.devices; dev; dev = dev->next) {
+ DeleteDeviceFromAnyExtEvents(pWin, dev);
+ }
+
+ for (dev = inputInfo.off_devices; dev; dev = dev->next)
+ DeleteDeviceFromAnyExtEvents(pWin, dev);
+
+ if (freeResources)
+ while ((inputMasks = wOtherInputMasks(pWin)) != 0) {
+ ic = inputMasks->inputClients;
+ for (i = 0; i < EMASKSIZE; i++)
+ inputMasks->dontPropagateMask[i] = 0;
+ FreeResource(ic->resource, RT_NONE);
+ }
+}
+
+int
+MaybeSendDeviceMotionNotifyHint(deviceKeyButtonPointer * pEvents, Mask mask)
+{
+ DeviceIntPtr dev;
+
+ dixLookupDevice(&dev, pEvents->deviceid & DEVICE_BITS, serverClient,
+ DixReadAccess);
+ if (!dev)
+ return 0;
+
+ if (pEvents->type == DeviceMotionNotify) {
+ if (mask & DevicePointerMotionHintMask) {
+ if (WID(dev->valuator->motionHintWindow) == pEvents->event) {
+ return 1; /* don't send, but pretend we did */
+ }
+ pEvents->detail = NotifyHint;
+ } else {
+ pEvents->detail = NotifyNormal;
+ }
+ }
+ return (0);
+}
+
+void
+CheckDeviceGrabAndHintWindow(WindowPtr pWin, int type,
+ deviceKeyButtonPointer * xE, GrabPtr grab,
+ ClientPtr client, Mask deliveryMask)
+{
+ DeviceIntPtr dev;
+
+ dixLookupDevice(&dev, xE->deviceid & DEVICE_BITS, serverClient,
+ DixGrabAccess);
+ if (!dev)
+ return;
+
+ if (type == DeviceMotionNotify)
+ dev->valuator->motionHintWindow = pWin;
+ else if ((type == DeviceButtonPress) && (!grab) &&
+ (deliveryMask & DeviceButtonGrabMask)) {
+ GrabRec tempGrab;
+
+ tempGrab.device = dev;
+ tempGrab.resource = client->clientAsMask;
+ tempGrab.window = pWin;
+ tempGrab.ownerEvents =
+ (deliveryMask & DeviceOwnerGrabButtonMask) ? TRUE : FALSE;
+ tempGrab.eventMask = deliveryMask;
+ tempGrab.keyboardMode = GrabModeAsync;
+ tempGrab.pointerMode = GrabModeAsync;
+ tempGrab.confineTo = NullWindow;
+ tempGrab.cursor = NullCursor;
+ tempGrab.next = NULL;
+ (*dev->deviceGrab.ActivateGrab) (dev, &tempGrab, currentTime, TRUE);
+ }
+}
+
+static Mask
+DeviceEventMaskForClient(DeviceIntPtr dev, WindowPtr pWin, ClientPtr client)
+{
+ InputClientsPtr other;
+
+ if (!wOtherInputMasks(pWin))
+ return 0;
+ for (other = wOtherInputMasks(pWin)->inputClients; other;
+ other = other->next) {
+ if (SameClient(other, client))
+ return other->mask[dev->id];
+ }
+ return 0;
+}
+
+void
+MaybeStopDeviceHint(DeviceIntPtr dev, ClientPtr client)
+{
+ WindowPtr pWin;
+ GrabPtr grab = dev->deviceGrab.grab;
+
+ pWin = dev->valuator->motionHintWindow;
+
+ if ((grab && SameClient(grab, client) &&
+ ((grab->eventMask & DevicePointerMotionHintMask) ||
+ (grab->ownerEvents &&
+ (DeviceEventMaskForClient(dev, pWin, client) &
+ DevicePointerMotionHintMask)))) ||
+ (!grab &&
+ (DeviceEventMaskForClient(dev, pWin, client) &
+ DevicePointerMotionHintMask)))
+ dev->valuator->motionHintWindow = NullWindow;
+}
+
+int
+DeviceEventSuppressForWindow(WindowPtr pWin, ClientPtr client, Mask mask,
+ int maskndx)
+{
+ struct _OtherInputMasks *inputMasks = wOtherInputMasks(pWin);
+
+ if (mask & ~PropagateMask[maskndx]) {
+ client->errorValue = mask;
+ return BadValue;
+ }
+
+ if (mask == 0) {
+ if (inputMasks)
+ inputMasks->dontPropagateMask[maskndx] = mask;
+ } else {
+ if (!inputMasks)
+ AddExtensionClient(pWin, client, 0, 0);
+ inputMasks = wOtherInputMasks(pWin);
+ inputMasks->dontPropagateMask[maskndx] = mask;
+ }
+ RecalculateDeviceDeliverableEvents(pWin);
+ if (ShouldFreeInputMasks(pWin, FALSE))
+ FreeResource(inputMasks->inputClients->resource, RT_NONE);
+ return Success;
+}
+
+Bool
+ShouldFreeInputMasks(WindowPtr pWin, Bool ignoreSelectedEvents)
+{
+ int i;
+ Mask allInputEventMasks = 0;
+ struct _OtherInputMasks *inputMasks = wOtherInputMasks(pWin);
+
+ for (i = 0; i < EMASKSIZE; i++)
+ allInputEventMasks |= inputMasks->dontPropagateMask[i];
+ if (!ignoreSelectedEvents)
+ for (i = 0; i < EMASKSIZE; i++)
+ allInputEventMasks |= inputMasks->inputEvents[i];
+ if (allInputEventMasks == 0)
+ return TRUE;
+ else
+ return FALSE;
+}
+
+/***********************************************************************
+ *
+ * Walk through the window tree, finding all clients that want to know
+ * about the Event.
+ *
+ */
+
+static void
+FindInterestedChildren(DeviceIntPtr dev, WindowPtr p1, Mask mask,
+ xEvent * ev, int count)
+{
+ WindowPtr p2;
+
+ while (p1) {
+ p2 = p1->firstChild;
+ DeliverEventsToWindow(dev, p1, ev, count, mask, NullGrab);
+ FindInterestedChildren(dev, p2, mask, ev, count);
+ p1 = p1->nextSib;
+ }
+}
+
+/***********************************************************************
+ *
+ * Send an event to interested clients in all windows on all screens.
+ *
+ */
+
+void
+SendEventToAllWindows(DeviceIntPtr dev, Mask mask, xEvent * ev, int count)
+{
+ int i;
+ WindowPtr pWin, p1;
+
+ for (i = 0; i < screenInfo.numScreens; i++) {
+ pWin = WindowTable[i];
+ if (!pWin)
+ continue;
+ DeliverEventsToWindow(dev, pWin, ev, count, mask, NullGrab);
+ p1 = pWin->firstChild;
+ FindInterestedChildren(dev, p1, mask, ev, count);
+ }
+}
+
+/**
+ * Set the XI2 mask for the given client on the given window.
+ * @param dev The device to set the mask for.
+ * @param win The window to set the mask on.
+ * @param client The client setting the mask.
+ * @param len Number of bytes in mask.
+ * @param mask Event mask in the form of (1 << eventtype)
+ */
+int
+XISetEventMask(DeviceIntPtr dev, WindowPtr win, ClientPtr client,
+ unsigned int len, unsigned char* mask)
+{
+ OtherInputMasks *masks;
+ InputClientsPtr others = NULL;
+
+ masks = wOtherInputMasks(win);
+ if (masks)
+ {
+ for (others = wOtherInputMasks(win)->inputClients; others;
+ others = others->next) {
+ if (SameClient(others, client)) {
+ memset(others->xi2mask[dev->id], 0,
+ sizeof(others->xi2mask[dev->id]));
+ break;
+ }
+ }
+ }
+
+ len = min(len, sizeof(others->xi2mask[dev->id]));
+
+ if (len && !others)
+ {
+ if (AddExtensionClient(win, client, 0, 0) != Success)
+ return BadAlloc;
+ others= wOtherInputMasks(win)->inputClients;
+ }
+
+ if (others)
+ memset(others->xi2mask[dev->id], 0, sizeof(others->xi2mask[dev->id]));
+
+ if (len)
+ memcpy(others->xi2mask[dev->id], mask, len);
+
+ RecalculateDeviceDeliverableEvents(win);
+
+ return Success;
+}
diff --git a/xorg-server/Xi/makefile b/xorg-server/Xi/makefile new file mode 100644 index 000000000..e33f1c49a --- /dev/null +++ b/xorg-server/Xi/makefile @@ -0,0 +1,54 @@ +CSRCS=allowev.c \ + chgdctl.c \ + chgfctl.c \ + chgkbd.c \ + chgkmap.c \ + chgprop.c \ + chgptr.c \ + closedev.c \ + devbell.c \ + exevents.c \ + extinit.c \ + getbmap.c \ + getdctl.c \ + getfctl.c \ + getfocus.c \ + getkmap.c \ + getmmap.c \ + getprop.c \ + getselev.c \ + getvers.c \ + grabdev.c \ + grabdevb.c \ + grabdevk.c \ + gtmotion.c \ + listdev.c \ + opendev.c \ + queryst.c \ + selectev.c \ + sendexev.c \ + setbmap.c \ + setdval.c \ + setfocus.c \ + setmmap.c \ + setmode.c \ + ungrdev.c \ + ungrdevb.c \ + ungrdevk.c \ + xiallowev.c \ + xichangecursor.c \ + xichangehierarchy.c \ + xigetclientpointer.c \ + xigrabdev.c \ + xipassivegrab.c \ + xiproperty.c \ + xiquerydevice.c \ + xiquerypointer.c \ + xiqueryversion.c \ + xiselectev.c \ + xisetclientpointer.c \ + xisetdevfocus.c \ + xiwarppointer.c + +LIBRARY=libXi + diff --git a/xorg-server/composite/compalloc.c b/xorg-server/composite/compalloc.c index 3f427dbe1..560a1a24c 100644 --- a/xorg-server/composite/compalloc.c +++ b/xorg-server/composite/compalloc.c @@ -115,7 +115,7 @@ compRedirectWindow (ClientPtr pClient, WindowPtr pWin, int update) */ if (!cw) { - cw = xalloc (sizeof (CompWindowRec)); + cw = xcalloc (1,sizeof (CompWindowRec)); if (!cw) { xfree (ccw); diff --git a/xorg-server/composite/makefile b/xorg-server/composite/makefile new file mode 100644 index 000000000..1ab95ebba --- /dev/null +++ b/xorg-server/composite/makefile @@ -0,0 +1,9 @@ +
+LIBRARY=libcomposite
+
+CSRCS = \
+ compalloc.c \
+ compext.c \
+ compinit.c \
+ compoverlay.c \
+ compwindow.c
diff --git a/xorg-server/config/makefile b/xorg-server/config/makefile new file mode 100644 index 000000000..937785271 --- /dev/null +++ b/xorg-server/config/makefile @@ -0,0 +1,4 @@ +CSRCS=config.c
+
+LIBRARY=libconfig
+
diff --git a/xorg-server/damageext/makefile b/xorg-server/damageext/makefile new file mode 100644 index 000000000..c8481cd3c --- /dev/null +++ b/xorg-server/damageext/makefile @@ -0,0 +1,4 @@ +CSRCS=damageext.c
+
+LIBRARY=libdamageext
+
diff --git a/xorg-server/dbe/makefile b/xorg-server/dbe/makefile new file mode 100644 index 000000000..70fb81430 --- /dev/null +++ b/xorg-server/dbe/makefile @@ -0,0 +1,4 @@ +CSRCS=dbe.c midbe.c
+
+LIBRARY=libdbe
+
diff --git a/xorg-server/dix/colormap.c b/xorg-server/dix/colormap.c index a5a006e60..6fbf26c3b 100644 --- a/xorg-server/dix/colormap.c +++ b/xorg-server/dix/colormap.c @@ -65,6 +65,10 @@ SOFTWARE. #include "privates.h" #include "xace.h" +#ifdef _MSC_VER +#define UpdateColors thisUpdateColors +#endif + extern XID clientErrorValue; static Pixel FindBestPixel( diff --git a/xorg-server/dix/dispatch.c b/xorg-server/dix/dispatch.c index 414bd0404..76ed70f66 100644 --- a/xorg-server/dix/dispatch.c +++ b/xorg-server/dix/dispatch.c @@ -110,6 +110,10 @@ Equipment Corporation. #include <version-config.h> #endif +#ifdef CreateWindow +#undef CreateWindow +#endif + #ifdef PANORAMIX_DEBUG #include <stdio.h> int ProcInitialConnection(); diff --git a/xorg-server/dix/dixfonts.c b/xorg-server/dix/dixfonts.c index d0a46c744..a78864260 100644 --- a/xorg-server/dix/dixfonts.c +++ b/xorg-server/dix/dixfonts.c @@ -1,2102 +1,2104 @@ -/************************************************************************ -Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -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 Digital not be -used in advertising or publicity pertaining to distribution of the -software without specific, written prior permission. - -DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING -ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL -DIGITAL 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. - -************************************************************************/ -/* The panoramix components contained the following notice */ -/* -Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts. - -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. - -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 -DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING, -BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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 Digital Equipment Corporation -shall not be used in advertising or otherwise to promote the sale, use or other -dealings in this Software without prior written authorization from Digital -Equipment Corporation. - -******************************************************************/ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <X11/X.h> -#include <X11/Xmd.h> -#include <X11/Xproto.h> -#include "scrnintstr.h" -#include "resource.h" -#include "dixstruct.h" -#include "cursorstr.h" -#include "misc.h" -#include "opaque.h" -#include "dixfontstr.h" -#include "closestr.h" -#include "dixfont.h" -#include "xace.h" - -#ifdef DEBUG -#include <stdio.h> -#endif - -#ifdef XF86BIGFONT -#define _XF86BIGFONT_SERVER_ -#include <X11/extensions/xf86bigfont.h> -#endif - -#define QUERYCHARINFO(pci, pr) *(pr) = (pci)->metrics - -extern pointer fosNaturalParams; -extern FontPtr defaultFont; - -static FontPathElementPtr *font_path_elements = (FontPathElementPtr *) 0; -static int num_fpes = 0; -static FPEFunctions *fpe_functions = (FPEFunctions *) 0; -static int num_fpe_types = 0; - -static unsigned char *font_path_string; - -static int num_slept_fpes = 0; -static int size_slept_fpes = 0; -static FontPathElementPtr *slept_fpes = (FontPathElementPtr *) 0; -static FontPatternCachePtr patternCache; - -static int -FontToXError(int err) -{ - switch (err) { - case Successful: - return Success; - case AllocError: - return BadAlloc; - case BadFontName: - return BadName; - case BadFontPath: - case BadFontFormat: /* is there something better? */ - case BadCharRange: - return BadValue; - default: - return err; - } -} - -static int -LoadGlyphs(ClientPtr client, FontPtr pfont, unsigned nchars, int item_size, - unsigned char *data) -{ - if (fpe_functions[pfont->fpe->type].load_glyphs) - return (*fpe_functions[pfont->fpe->type].load_glyphs) - (client, pfont, 0, nchars, item_size, data); - else - return Successful; -} - -/* - * adding RT_FONT prevents conflict with default cursor font - */ -Bool -SetDefaultFont(char *defaultfontname) -{ - int err; - FontPtr pf; - XID fid; - - fid = FakeClientID(0); - err = OpenFont(serverClient, fid, FontLoadAll | FontOpenSync, - (unsigned) strlen(defaultfontname), defaultfontname); - if (err != Success) - return FALSE; - err = dixLookupResourceByType((pointer *)&pf, fid, RT_FONT, serverClient, - DixReadAccess); - if (err != Success) - return FALSE; - defaultFont = pf; - return TRUE; -} - -/* - * note that the font wakeup queue is not refcounted. this is because - * an fpe needs to be added when it's inited, and removed when it's finally - * freed, in order to handle any data that isn't requested, like FS events. - * - * since the only thing that should call these routines is the renderer's - * init_fpe() and free_fpe(), there shouldn't be any problem in using - * freed data. - */ -void -QueueFontWakeup(FontPathElementPtr fpe) -{ - int i; - FontPathElementPtr *new; - - for (i = 0; i < num_slept_fpes; i++) { - if (slept_fpes[i] == fpe) { - return; - } - } - if (num_slept_fpes == size_slept_fpes) { - new = (FontPathElementPtr *) - xrealloc(slept_fpes, - sizeof(FontPathElementPtr) * (size_slept_fpes + 4)); - if (!new) - return; - slept_fpes = new; - size_slept_fpes += 4; - } - slept_fpes[num_slept_fpes] = fpe; - num_slept_fpes++; -} - -void -RemoveFontWakeup(FontPathElementPtr fpe) -{ - int i, - j; - - for (i = 0; i < num_slept_fpes; i++) { - if (slept_fpes[i] == fpe) { - for (j = i; j < num_slept_fpes; j++) { - slept_fpes[j] = slept_fpes[j + 1]; - } - num_slept_fpes--; - return; - } - } -} - -void -FontWakeup(pointer data, int count, pointer LastSelectMask) -{ - int i; - FontPathElementPtr fpe; - - if (count < 0) - return; - /* wake up any fpe's that may be waiting for information */ - for (i = 0; i < num_slept_fpes; i++) { - fpe = slept_fpes[i]; - (void) (*fpe_functions[fpe->type].wakeup_fpe) (fpe, LastSelectMask); - } -} - -/* XXX -- these two funcs may want to be broken into macros */ -static void -UseFPE(FontPathElementPtr fpe) -{ - fpe->refcount++; -} - -static void -FreeFPE (FontPathElementPtr fpe) -{ - fpe->refcount--; - if (fpe->refcount == 0) { - (*fpe_functions[fpe->type].free_fpe) (fpe); - xfree(fpe->name); - xfree(fpe); - } -} - -static Bool -doOpenFont(ClientPtr client, OFclosurePtr c) -{ - FontPtr pfont = NullFont; - FontPathElementPtr fpe = NULL; - ScreenPtr pScr; - int err = Successful; - int i; - char *alias, - *newname; - int newlen; - int aliascount = 20; - /* - * Decide at runtime what FontFormat to use. - */ - Mask FontFormat = - - ((screenInfo.imageByteOrder == LSBFirst) ? - BitmapFormatByteOrderLSB : BitmapFormatByteOrderMSB) | - - ((screenInfo.bitmapBitOrder == LSBFirst) ? - BitmapFormatBitOrderLSB : BitmapFormatBitOrderMSB) | - - BitmapFormatImageRectMin | - -#if GLYPHPADBYTES == 1 - BitmapFormatScanlinePad8 | -#endif - -#if GLYPHPADBYTES == 2 - BitmapFormatScanlinePad16 | -#endif - -#if GLYPHPADBYTES == 4 - BitmapFormatScanlinePad32 | -#endif - -#if GLYPHPADBYTES == 8 - BitmapFormatScanlinePad64 | -#endif - - BitmapFormatScanlineUnit8; - - if (client->clientGone) - { - if (c->current_fpe < c->num_fpes) - { - fpe = c->fpe_list[c->current_fpe]; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - } - err = Successful; - goto bail; - } - while (c->current_fpe < c->num_fpes) { - fpe = c->fpe_list[c->current_fpe]; - err = (*fpe_functions[fpe->type].open_font) - ((pointer) client, fpe, c->flags, - c->fontname, c->fnamelen, FontFormat, - BitmapFormatMaskByte | - BitmapFormatMaskBit | - BitmapFormatMaskImageRectangle | - BitmapFormatMaskScanLinePad | - BitmapFormatMaskScanLineUnit, - c->fontid, &pfont, &alias, - c->non_cachable_font && c->non_cachable_font->fpe == fpe ? - c->non_cachable_font : - (FontPtr)0); - - if (err == FontNameAlias && alias) { - newlen = strlen(alias); - newname = (char *) xrealloc(c->fontname, newlen); - if (!newname) { - err = AllocError; - break; - } - memmove(newname, alias, newlen); - c->fontname = newname; - c->fnamelen = newlen; - c->current_fpe = 0; - if (--aliascount <= 0) { - /* We've tried resolving this alias 20 times, we're - * probably stuck in an infinite loop of aliases pointing - * to each other - time to take emergency exit! - */ - err = BadImplementation; - break; - } - continue; - } - if (err == BadFontName) { - c->current_fpe++; - continue; - } - if (err == Suspended) { - if (!c->slept) { - c->slept = TRUE; - ClientSleep(client, (ClientSleepProcPtr)doOpenFont, (pointer) c); - } - return TRUE; - } - break; - } - - if (err != Successful) - goto bail; - if (!pfont) { - err = BadFontName; - goto bail; - } - /* check values for firstCol, lastCol, firstRow, and lastRow */ - if (pfont->info.firstCol > pfont->info.lastCol || - pfont->info.firstRow > pfont->info.lastRow || - pfont->info.lastCol - pfont->info.firstCol > 255) { - err = AllocError; - goto bail; - } - if (!pfont->fpe) - pfont->fpe = fpe; - pfont->refcnt++; - if (pfont->refcnt == 1) { - UseFPE(pfont->fpe); - for (i = 0; i < screenInfo.numScreens; i++) { - pScr = screenInfo.screens[i]; - if (pScr->RealizeFont) - { - if (!(*pScr->RealizeFont) (pScr, pfont)) - { - CloseFont (pfont, (Font) 0); - err = AllocError; - goto bail; - } - } - } - } - if (!AddResource(c->fontid, RT_FONT, (pointer) pfont)) { - err = AllocError; - goto bail; - } - if (patternCache && pfont != c->non_cachable_font) - CacheFontPattern(patternCache, c->origFontName, c->origFontNameLen, - pfont); -bail: - if (err != Successful && c->client != serverClient) { - SendErrorToClient(c->client, X_OpenFont, 0, - c->fontid, FontToXError(err)); - } - if (c->slept) - ClientWakeup(c->client); - for (i = 0; i < c->num_fpes; i++) { - FreeFPE(c->fpe_list[i]); - } - xfree(c->fpe_list); - xfree(c->fontname); - xfree(c); - return TRUE; -} - -int -OpenFont(ClientPtr client, XID fid, Mask flags, unsigned lenfname, char *pfontname) -{ - OFclosurePtr c; - int i; - FontPtr cached = (FontPtr)0; - -#ifdef FONTDEBUG - char *f; - f = xalloc(lenfname + 1); - memmove(f, pfontname, lenfname); - f[lenfname] = '\0'; - ErrorF("[dix] OpenFont: fontname is \"%s\"\n", f); - xfree(f); -#endif - if (!lenfname || lenfname > XLFDMAXFONTNAMELEN) - return BadName; - if (patternCache) - { - - /* - ** Check name cache. If we find a cached version of this font that - ** is cachable, immediately satisfy the request with it. If we find - ** a cached version of this font that is non-cachable, we do not - ** satisfy the request with it. Instead, we pass the FontPtr to the - ** FPE's open_font code (the fontfile FPE in turn passes the - ** information to the rasterizer; the fserve FPE ignores it). - ** - ** Presumably, the font is marked non-cachable because the FPE has - ** put some licensing restrictions on it. If the FPE, using - ** whatever logic it relies on, determines that it is willing to - ** share this existing font with the client, then it has the option - ** to return the FontPtr we passed it as the newly-opened font. - ** This allows the FPE to exercise its licensing logic without - ** having to create another instance of a font that already exists. - */ - - cached = FindCachedFontPattern(patternCache, pfontname, lenfname); - if (cached && cached->info.cachable) - { - if (!AddResource(fid, RT_FONT, (pointer) cached)) - return BadAlloc; - cached->refcnt++; - return Success; - } - } - c = xalloc(sizeof(OFclosureRec)); - if (!c) - return BadAlloc; - c->fontname = xalloc(lenfname); - c->origFontName = pfontname; - c->origFontNameLen = lenfname; - if (!c->fontname) { - xfree(c); - return BadAlloc; - } - /* - * copy the current FPE list, so that if it gets changed by another client - * while we're blocking, the request still appears atomic - */ - c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes); - if (!c->fpe_list) { - xfree(c->fontname); - xfree(c); - return BadAlloc; - } - memmove(c->fontname, pfontname, lenfname); - for (i = 0; i < num_fpes; i++) { - c->fpe_list[i] = font_path_elements[i]; - UseFPE(c->fpe_list[i]); - } - c->client = client; - c->fontid = fid; - c->current_fpe = 0; - c->num_fpes = num_fpes; - c->fnamelen = lenfname; - c->slept = FALSE; - c->flags = flags; - c->non_cachable_font = cached; - - (void) doOpenFont(client, c); - return Success; -} - -/** - * Decrement font's ref count, and free storage if ref count equals zero - * - * \param value must conform to DeleteType - */ -int -CloseFont(pointer value, XID fid) -{ - int nscr; - ScreenPtr pscr; - FontPathElementPtr fpe; - FontPtr pfont = (FontPtr)value; - - if (pfont == NullFont) - return (Success); - if (--pfont->refcnt == 0) { - if (patternCache) - RemoveCachedFontPattern (patternCache, pfont); - /* - * since the last reference is gone, ask each screen to free any - * storage it may have allocated locally for it. - */ - for (nscr = 0; nscr < screenInfo.numScreens; nscr++) { - pscr = screenInfo.screens[nscr]; - if (pscr->UnrealizeFont) - (*pscr->UnrealizeFont) (pscr, pfont); - } - if (pfont == defaultFont) - defaultFont = NULL; -#ifdef XF86BIGFONT - XF86BigfontFreeFontShm(pfont); -#endif - fpe = pfont->fpe; - (*fpe_functions[fpe->type].close_font) (fpe, pfont); - FreeFPE(fpe); - } - return (Success); -} - - -/***====================================================================***/ - -/** - * Sets up pReply as the correct QueryFontReply for pFont with the first - * nProtoCCIStructs char infos. - * - * \param pReply caller must allocate this storage - */ -void -QueryFont(FontPtr pFont, xQueryFontReply *pReply, int nProtoCCIStructs) -{ - FontPropPtr pFP; - int r, - c, - i; - xFontProp *prFP; - xCharInfo *prCI; - xCharInfo *charInfos[256]; - unsigned char chars[512]; - int ninfos; - unsigned long ncols; - unsigned long count; - - /* pr->length set in dispatch */ - pReply->minCharOrByte2 = pFont->info.firstCol; - pReply->defaultChar = pFont->info.defaultCh; - pReply->maxCharOrByte2 = pFont->info.lastCol; - pReply->drawDirection = pFont->info.drawDirection; - pReply->allCharsExist = pFont->info.allExist; - pReply->minByte1 = pFont->info.firstRow; - pReply->maxByte1 = pFont->info.lastRow; - pReply->fontAscent = pFont->info.fontAscent; - pReply->fontDescent = pFont->info.fontDescent; - - pReply->minBounds = pFont->info.ink_minbounds; - pReply->maxBounds = pFont->info.ink_maxbounds; - - pReply->nFontProps = pFont->info.nprops; - pReply->nCharInfos = nProtoCCIStructs; - - for (i = 0, pFP = pFont->info.props, prFP = (xFontProp *) (&pReply[1]); - i < pFont->info.nprops; - i++, pFP++, prFP++) { - prFP->name = pFP->name; - prFP->value = pFP->value; - } - - ninfos = 0; - ncols = (unsigned long) (pFont->info.lastCol - pFont->info.firstCol + 1); - prCI = (xCharInfo *) (prFP); - for (r = pFont->info.firstRow; - ninfos < nProtoCCIStructs && r <= (int)pFont->info.lastRow; - r++) { - i = 0; - for (c = pFont->info.firstCol; c <= (int)pFont->info.lastCol; c++) { - chars[i++] = r; - chars[i++] = c; - } - (*pFont->get_metrics) (pFont, ncols, chars, - TwoD16Bit, &count, charInfos); - i = 0; - for (i = 0; i < (int) count && ninfos < nProtoCCIStructs; i++) { - *prCI = *charInfos[i]; - prCI++; - ninfos++; - } - } - return; -} - -static Bool -doListFontsAndAliases(ClientPtr client, LFclosurePtr c) -{ - FontPathElementPtr fpe; - int err = Successful; - FontNamesPtr names = NULL; - char *name, *resolved=NULL; - int namelen, resolvedlen; - int nnames; - int stringLens; - int i; - xListFontsReply reply; - char *bufptr; - char *bufferStart; - int aliascount = 0; - - if (client->clientGone) - { - if (c->current.current_fpe < c->num_fpes) - { - fpe = c->fpe_list[c->current.current_fpe]; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - } - err = Successful; - goto bail; - } - - if (!c->current.patlen) - goto finish; - - while (c->current.current_fpe < c->num_fpes) { - fpe = c->fpe_list[c->current.current_fpe]; - err = Successful; - - if (!fpe_functions[fpe->type].start_list_fonts_and_aliases) - { - /* This FPE doesn't support/require list_fonts_and_aliases */ - - err = (*fpe_functions[fpe->type].list_fonts) - ((pointer) c->client, fpe, c->current.pattern, - c->current.patlen, c->current.max_names - c->names->nnames, - c->names); - - if (err == Suspended) { - if (!c->slept) { - c->slept = TRUE; - ClientSleep(client, - (ClientSleepProcPtr)doListFontsAndAliases, - (pointer) c); - } - return TRUE; - } - - err = BadFontName; - } - else - { - /* Start of list_fonts_and_aliases functionality. Modeled - after list_fonts_with_info in that it resolves aliases, - except that the information collected from FPEs is just - names, not font info. Each list_next_font_or_alias() - returns either a name into name/namelen or an alias into - name/namelen and its target name into resolved/resolvedlen. - The code at this level then resolves the alias by polling - the FPEs. */ - - if (!c->current.list_started) { - err = (*fpe_functions[fpe->type].start_list_fonts_and_aliases) - ((pointer) c->client, fpe, c->current.pattern, - c->current.patlen, c->current.max_names - c->names->nnames, - &c->current.private); - if (err == Suspended) { - if (!c->slept) { - ClientSleep(client, - (ClientSleepProcPtr)doListFontsAndAliases, - (pointer) c); - c->slept = TRUE; - } - return TRUE; - } - if (err == Successful) - c->current.list_started = TRUE; - } - if (err == Successful) { - char *tmpname; - name = 0; - err = (*fpe_functions[fpe->type].list_next_font_or_alias) - ((pointer) c->client, fpe, &name, &namelen, &tmpname, - &resolvedlen, c->current.private); - if (err == Suspended) { - if (!c->slept) { - ClientSleep(client, - (ClientSleepProcPtr)doListFontsAndAliases, - (pointer) c); - c->slept = TRUE; - } - return TRUE; - } - if (err == FontNameAlias) { - if (resolved) xfree(resolved); - resolved = xalloc(resolvedlen + 1); - if (resolved) - memmove(resolved, tmpname, resolvedlen + 1); - } - } - - if (err == Successful) - { - if (c->haveSaved) - { - if (c->savedName) - (void)AddFontNamesName(c->names, c->savedName, - c->savedNameLen); - } - else - (void)AddFontNamesName(c->names, name, namelen); - } - - /* - * When we get an alias back, save our state and reset back to - * the start of the FPE looking for the specified name. As - * soon as a real font is found for the alias, pop back to the - * old state - */ - else if (err == FontNameAlias) { - char tmp_pattern[XLFDMAXFONTNAMELEN]; - /* - * when an alias recurses, we need to give - * the last FPE a chance to clean up; so we call - * it again, and assume that the error returned - * is BadFontName, indicating the alias resolution - * is complete. - */ - memmove(tmp_pattern, resolved, resolvedlen); - if (c->haveSaved) - { - char *tmpname; - int tmpnamelen; - - tmpname = 0; - (void) (*fpe_functions[fpe->type].list_next_font_or_alias) - ((pointer) c->client, fpe, &tmpname, &tmpnamelen, - &tmpname, &tmpnamelen, c->current.private); - if (--aliascount <= 0) - { - err = BadFontName; - goto ContBadFontName; - } - } - else - { - c->saved = c->current; - c->haveSaved = TRUE; - if (c->savedName) - xfree(c->savedName); - c->savedName = xalloc(namelen + 1); - if (c->savedName) - memmove(c->savedName, name, namelen + 1); - c->savedNameLen = namelen; - aliascount = 20; - } - memmove(c->current.pattern, tmp_pattern, resolvedlen); - c->current.patlen = resolvedlen; - c->current.max_names = c->names->nnames + 1; - c->current.current_fpe = -1; - c->current.private = 0; - err = BadFontName; - } - } - /* - * At the end of this FPE, step to the next. If we've finished - * processing an alias, pop state back. If we've collected enough - * font names, quit. - */ - if (err == BadFontName) { - ContBadFontName: ; - c->current.list_started = FALSE; - c->current.current_fpe++; - err = Successful; - if (c->haveSaved) - { - if (c->names->nnames == c->current.max_names || - c->current.current_fpe == c->num_fpes) { - c->haveSaved = FALSE; - c->current = c->saved; - /* Give the saved namelist a chance to clean itself up */ - continue; - } - } - if (c->names->nnames == c->current.max_names) - break; - } - } - - /* - * send the reply - */ - if (err != Successful) { - SendErrorToClient(client, X_ListFonts, 0, 0, FontToXError(err)); - goto bail; - } - -finish: - - names = c->names; - nnames = names->nnames; - client = c->client; - stringLens = 0; - for (i = 0; i < nnames; i++) - stringLens += (names->length[i] <= 255) ? names->length[i] : 0; - - memset(&reply, 0, sizeof(xListFontsReply)); - reply.type = X_Reply; - reply.length = bytes_to_int32(stringLens + nnames); - reply.nFonts = nnames; - reply.sequenceNumber = client->sequence; - - bufptr = bufferStart = xalloc(reply.length << 2); - - if (!bufptr && reply.length) { - SendErrorToClient(client, X_ListFonts, 0, 0, BadAlloc); - goto bail; - } - /* - * since WriteToClient long word aligns things, copy to temp buffer and - * write all at once - */ - for (i = 0; i < nnames; i++) { - if (names->length[i] > 255) - reply.nFonts--; - else - { - *bufptr++ = names->length[i]; - memmove( bufptr, names->names[i], names->length[i]); - bufptr += names->length[i]; - } - } - nnames = reply.nFonts; - reply.length = bytes_to_int32(stringLens + nnames); - client->pSwapReplyFunc = ReplySwapVector[X_ListFonts]; - WriteSwappedDataToClient(client, sizeof(xListFontsReply), &reply); - (void) WriteToClient(client, stringLens + nnames, bufferStart); - xfree(bufferStart); - -bail: - if (c->slept) - ClientWakeup(client); - for (i = 0; i < c->num_fpes; i++) - FreeFPE(c->fpe_list[i]); - xfree(c->fpe_list); - if (c->savedName) xfree(c->savedName); - FreeFontNames(names); - xfree(c); - if (resolved) xfree(resolved); - return TRUE; -} - -int -ListFonts(ClientPtr client, unsigned char *pattern, unsigned length, - unsigned max_names) -{ - int i; - LFclosurePtr c; - - /* - * The right error to return here would be BadName, however the - * specification does not allow for a Name error on this request. - * Perhaps a better solution would be to return a nil list, i.e. - * a list containing zero fontnames. - */ - if (length > XLFDMAXFONTNAMELEN) - return BadAlloc; - - i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess); - if (i != Success) - return i; - - if (!(c = xalloc(sizeof *c))) - return BadAlloc; - c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes); - if (!c->fpe_list) { - xfree(c); - return BadAlloc; - } - c->names = MakeFontNamesRecord(max_names < 100 ? max_names : 100); - if (!c->names) - { - xfree(c->fpe_list); - xfree(c); - return BadAlloc; - } - memmove( c->current.pattern, pattern, length); - for (i = 0; i < num_fpes; i++) { - c->fpe_list[i] = font_path_elements[i]; - UseFPE(c->fpe_list[i]); - } - c->client = client; - c->num_fpes = num_fpes; - c->current.patlen = length; - c->current.current_fpe = 0; - c->current.max_names = max_names; - c->current.list_started = FALSE; - c->current.private = 0; - c->haveSaved = FALSE; - c->slept = FALSE; - c->savedName = 0; - doListFontsAndAliases(client, c); - return Success; -} - -int -doListFontsWithInfo(ClientPtr client, LFWIclosurePtr c) -{ - FontPathElementPtr fpe; - int err = Successful; - char *name; - int namelen; - int numFonts; - FontInfoRec fontInfo, - *pFontInfo; - xListFontsWithInfoReply *reply; - int length; - xFontProp *pFP; - int i; - int aliascount = 0; - xListFontsWithInfoReply finalReply; - - if (client->clientGone) - { - if (c->current.current_fpe < c->num_fpes) - { - fpe = c->fpe_list[c->current.current_fpe]; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - } - err = Successful; - goto bail; - } - client->pSwapReplyFunc = ReplySwapVector[X_ListFontsWithInfo]; - if (!c->current.patlen) - goto finish; - while (c->current.current_fpe < c->num_fpes) - { - fpe = c->fpe_list[c->current.current_fpe]; - err = Successful; - if (!c->current.list_started) - { - err = (*fpe_functions[fpe->type].start_list_fonts_with_info) - (client, fpe, c->current.pattern, c->current.patlen, - c->current.max_names, &c->current.private); - if (err == Suspended) - { - if (!c->slept) - { - ClientSleep(client, (ClientSleepProcPtr)doListFontsWithInfo, c); - c->slept = TRUE; - } - return TRUE; - } - if (err == Successful) - c->current.list_started = TRUE; - } - if (err == Successful) - { - name = 0; - pFontInfo = &fontInfo; - err = (*fpe_functions[fpe->type].list_next_font_with_info) - (client, fpe, &name, &namelen, &pFontInfo, - &numFonts, c->current.private); - if (err == Suspended) - { - if (!c->slept) - { - ClientSleep(client, - (ClientSleepProcPtr)doListFontsWithInfo, - c); - c->slept = TRUE; - } - return TRUE; - } - } - /* - * When we get an alias back, save our state and reset back to the - * start of the FPE looking for the specified name. As soon as a real - * font is found for the alias, pop back to the old state - */ - if (err == FontNameAlias) - { - /* - * when an alias recurses, we need to give - * the last FPE a chance to clean up; so we call - * it again, and assume that the error returned - * is BadFontName, indicating the alias resolution - * is complete. - */ - if (c->haveSaved) - { - char *tmpname; - int tmpnamelen; - FontInfoPtr tmpFontInfo; - - tmpname = 0; - tmpFontInfo = &fontInfo; - (void) (*fpe_functions[fpe->type].list_next_font_with_info) - (client, fpe, &tmpname, &tmpnamelen, &tmpFontInfo, - &numFonts, c->current.private); - if (--aliascount <= 0) - { - err = BadFontName; - goto ContBadFontName; - } - } - else - { - c->saved = c->current; - c->haveSaved = TRUE; - c->savedNumFonts = numFonts; - if (c->savedName) - xfree(c->savedName); - c->savedName = xalloc(namelen + 1); - if (c->savedName) - memmove(c->savedName, name, namelen + 1); - aliascount = 20; - } - memmove(c->current.pattern, name, namelen); - c->current.patlen = namelen; - c->current.max_names = 1; - c->current.current_fpe = 0; - c->current.private = 0; - c->current.list_started = FALSE; - } - /* - * At the end of this FPE, step to the next. If we've finished - * processing an alias, pop state back. If we've sent enough font - * names, quit. Always wait for BadFontName to let the FPE - * have a chance to clean up. - */ - else if (err == BadFontName) - { - ContBadFontName: ; - c->current.list_started = FALSE; - c->current.current_fpe++; - err = Successful; - if (c->haveSaved) - { - if (c->current.max_names == 0 || - c->current.current_fpe == c->num_fpes) - { - c->haveSaved = FALSE; - c->saved.max_names -= (1 - c->current.max_names); - c->current = c->saved; - } - } - else if (c->current.max_names == 0) - break; - } - else if (err == Successful) - { - length = sizeof(*reply) + pFontInfo->nprops * sizeof(xFontProp); - reply = c->reply; - if (c->length < length) - { - reply = (xListFontsWithInfoReply *) xrealloc(c->reply, length); - if (!reply) - { - err = AllocError; - break; - } - memset(reply + c->length, 0, length - c->length); - c->reply = reply; - c->length = length; - } - if (c->haveSaved) - { - numFonts = c->savedNumFonts; - name = c->savedName; - namelen = strlen(name); - } - reply->type = X_Reply; - reply->length = bytes_to_int32(sizeof *reply - sizeof(xGenericReply) + - pFontInfo->nprops * sizeof(xFontProp) + - namelen); - reply->sequenceNumber = client->sequence; - reply->nameLength = namelen; - reply->minBounds = pFontInfo->ink_minbounds; - reply->maxBounds = pFontInfo->ink_maxbounds; - reply->minCharOrByte2 = pFontInfo->firstCol; - reply->maxCharOrByte2 = pFontInfo->lastCol; - reply->defaultChar = pFontInfo->defaultCh; - reply->nFontProps = pFontInfo->nprops; - reply->drawDirection = pFontInfo->drawDirection; - reply->minByte1 = pFontInfo->firstRow; - reply->maxByte1 = pFontInfo->lastRow; - reply->allCharsExist = pFontInfo->allExist; - reply->fontAscent = pFontInfo->fontAscent; - reply->fontDescent = pFontInfo->fontDescent; - reply->nReplies = numFonts; - pFP = (xFontProp *) (reply + 1); - for (i = 0; i < pFontInfo->nprops; i++) - { - pFP->name = pFontInfo->props[i].name; - pFP->value = pFontInfo->props[i].value; - pFP++; - } - WriteSwappedDataToClient(client, length, reply); - (void) WriteToClient(client, namelen, name); - if (pFontInfo == &fontInfo) - { - xfree(fontInfo.props); - xfree(fontInfo.isStringProp); - } - --c->current.max_names; - } - } -finish: - length = sizeof(xListFontsWithInfoReply); - bzero((char *) &finalReply, sizeof(xListFontsWithInfoReply)); - finalReply.type = X_Reply; - finalReply.sequenceNumber = client->sequence; - finalReply.length = bytes_to_int32(sizeof(xListFontsWithInfoReply) - - sizeof(xGenericReply)); - WriteSwappedDataToClient(client, length, &finalReply); -bail: - if (c->slept) - ClientWakeup(client); - for (i = 0; i < c->num_fpes; i++) - FreeFPE(c->fpe_list[i]); - xfree(c->reply); - xfree(c->fpe_list); - if (c->savedName) xfree(c->savedName); - xfree(c); - return TRUE; -} - -int -StartListFontsWithInfo(ClientPtr client, int length, unsigned char *pattern, - int max_names) -{ - int i; - LFWIclosurePtr c; - - /* - * The right error to return here would be BadName, however the - * specification does not allow for a Name error on this request. - * Perhaps a better solution would be to return a nil list, i.e. - * a list containing zero fontnames. - */ - if (length > XLFDMAXFONTNAMELEN) - return BadAlloc; - - i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess); - if (i != Success) - return i; - - if (!(c = xalloc(sizeof *c))) - goto badAlloc; - c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes); - if (!c->fpe_list) - { - xfree(c); - goto badAlloc; - } - memmove(c->current.pattern, pattern, length); - for (i = 0; i < num_fpes; i++) - { - c->fpe_list[i] = font_path_elements[i]; - UseFPE(c->fpe_list[i]); - } - c->client = client; - c->num_fpes = num_fpes; - c->reply = 0; - c->length = 0; - c->current.patlen = length; - c->current.current_fpe = 0; - c->current.max_names = max_names; - c->current.list_started = FALSE; - c->current.private = 0; - c->savedNumFonts = 0; - c->haveSaved = FALSE; - c->slept = FALSE; - c->savedName = 0; - doListFontsWithInfo(client, c); - return Success; -badAlloc: - return BadAlloc; -} - -#define TextEltHeader 2 -#define FontShiftSize 5 -static XID clearGC[] = { CT_NONE }; -#define clearGCmask (GCClipMask) - -int -doPolyText(ClientPtr client, PTclosurePtr c) -{ - FontPtr pFont = c->pGC->font, oldpFont; - Font fid, oldfid; - int err = Success, lgerr; /* err is in X error, not font error, space */ - enum { NEVER_SLEPT, START_SLEEP, SLEEPING } client_state = NEVER_SLEPT; - FontPathElementPtr fpe; - GC *origGC = NULL; - - if (client->clientGone) - { - fpe = c->pGC->font->fpe; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - - if (c->slept) - { - /* Client has died, but we cannot bail out right now. We - need to clean up after the work we did when going to - sleep. Setting the drawable pointer to 0 makes this - happen without any attempts to render or perform other - unnecessary activities. */ - c->pDraw = (DrawablePtr)0; - } - else - { - err = Success; - goto bail; - } - } - - /* Make sure our drawable hasn't disappeared while we slept. */ - if (c->slept && c->pDraw) - { - DrawablePtr pDraw; - dixLookupDrawable(&pDraw, c->did, client, 0, DixWriteAccess); - if (c->pDraw != pDraw) { - /* Our drawable has disappeared. Treat like client died... ask - the FPE code to clean up after client and avoid further - rendering while we clean up after ourself. */ - fpe = c->pGC->font->fpe; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - c->pDraw = (DrawablePtr)0; - } - } - - client_state = c->slept ? SLEEPING : NEVER_SLEPT; - - while (c->endReq - c->pElt > TextEltHeader) - { - if (*c->pElt == FontChange) - { - if (c->endReq - c->pElt < FontShiftSize) - { - err = BadLength; - goto bail; - } - - oldpFont = pFont; - oldfid = fid; - - fid = ((Font)*(c->pElt+4)) /* big-endian */ - | ((Font)*(c->pElt+3)) << 8 - | ((Font)*(c->pElt+2)) << 16 - | ((Font)*(c->pElt+1)) << 24; - err = dixLookupResourceByType((pointer *)&pFont, fid, RT_FONT, - client, DixReadAccess); - if (err != Success) - { - err = (err == BadValue) ? BadFont : err; - /* restore pFont and fid for step 4 (described below) */ - pFont = oldpFont; - fid = oldfid; - - /* If we're in START_SLEEP mode, the following step - shortens the request... in the unlikely event that - the fid somehow becomes valid before we come through - again to actually execute the polytext, which would - then mess up our refcounting scheme badly. */ - c->err = err; - c->endReq = c->pElt; - - goto bail; - } - - /* Step 3 (described below) on our new font */ - if (client_state == START_SLEEP) - pFont->refcnt++; - else - { - if (pFont != c->pGC->font && c->pDraw) - { - ChangeGC( c->pGC, GCFont, &fid); - ValidateGC(c->pDraw, c->pGC); - if (c->reqType == X_PolyText8) - c->polyText = (PolyTextPtr) c->pGC->ops->PolyText8; - else - c->polyText = (PolyTextPtr) c->pGC->ops->PolyText16; - } - - /* Undo the refcnt++ we performed when going to sleep */ - if (client_state == SLEEPING) - (void)CloseFont(c->pGC->font, (Font)0); - } - c->pElt += FontShiftSize; - } - else /* print a string */ - { - unsigned char *pNextElt; - pNextElt = c->pElt + TextEltHeader + (*c->pElt)*c->itemSize; - if ( pNextElt > c->endReq) - { - err = BadLength; - goto bail; - } - if (client_state == START_SLEEP) - { - c->pElt = pNextElt; - continue; - } - if (c->pDraw) - { - lgerr = LoadGlyphs(client, c->pGC->font, *c->pElt, c->itemSize, - c->pElt + TextEltHeader); - } - else lgerr = Successful; - - if (lgerr == Suspended) - { - if (!c->slept) { - int len; - GC *pGC; - PTclosurePtr new_closure; - - /* We're putting the client to sleep. We need to do a few things - to ensure successful and atomic-appearing execution of the - remainder of the request. First, copy the remainder of the - request into a safe malloc'd area. Second, create a scratch GC - to use for the remainder of the request. Third, mark all fonts - referenced in the remainder of the request to prevent their - deallocation. Fourth, make the original GC look like the - request has completed... set its font to the final font value - from this request. These GC manipulations are for the unlikely - (but possible) event that some other client is using the GC. - Steps 3 and 4 are performed by running this procedure through - the remainder of the request in a special no-render mode - indicated by client_state = START_SLEEP. */ - - /* Step 1 */ - /* Allocate a malloc'd closure structure to replace - the local one we were passed */ - new_closure = xalloc(sizeof(PTclosureRec)); - if (!new_closure) - { - err = BadAlloc; - goto bail; - } - *new_closure = *c; - c = new_closure; - - len = c->endReq - c->pElt; - c->data = xalloc(len); - if (!c->data) - { - xfree(c); - err = BadAlloc; - goto bail; - } - memmove(c->data, c->pElt, len); - c->pElt = c->data; - c->endReq = c->pElt + len; - - /* Step 2 */ - - pGC = GetScratchGC(c->pGC->depth, c->pGC->pScreen); - if (!pGC) - { - xfree(c->data); - xfree(c); - err = BadAlloc; - goto bail; - } - if ((err = CopyGC(c->pGC, pGC, GCFunction | - GCPlaneMask | GCForeground | - GCBackground | GCFillStyle | - GCTile | GCStipple | - GCTileStipXOrigin | - GCTileStipYOrigin | GCFont | - GCSubwindowMode | GCClipXOrigin | - GCClipYOrigin | GCClipMask)) != - Success) - { - FreeScratchGC(pGC); - xfree(c->data); - xfree(c); - err = BadAlloc; - goto bail; - } - origGC = c->pGC; - c->pGC = pGC; - ValidateGC(c->pDraw, c->pGC); - - c->slept = TRUE; - ClientSleep(client, - (ClientSleepProcPtr)doPolyText, - (pointer) c); - - /* Set up to perform steps 3 and 4 */ - client_state = START_SLEEP; - continue; /* on to steps 3 and 4 */ - } - return TRUE; - } - else if (lgerr != Successful) - { - err = FontToXError(lgerr); - goto bail; - } - if (c->pDraw) - { - c->xorg += *((INT8 *)(c->pElt + 1)); /* must be signed */ - c->xorg = (* c->polyText)(c->pDraw, c->pGC, c->xorg, c->yorg, - *c->pElt, c->pElt + TextEltHeader); - } - c->pElt = pNextElt; - } - } - -bail: - - if (client_state == START_SLEEP) - { - /* Step 4 */ - if (pFont != origGC->font) - { - ChangeGC(origGC, GCFont, &fid); - ValidateGC(c->pDraw, origGC); - } - - /* restore pElt pointer for execution of remainder of the request */ - c->pElt = c->data; - return TRUE; - } - - if (c->err != Success) err = c->err; - if (err != Success && c->client != serverClient) { -#ifdef PANORAMIX - if (noPanoramiXExtension || !c->pGC->pScreen->myNum) -#endif - SendErrorToClient(c->client, c->reqType, 0, 0, err); - } - if (c->slept) - { - ClientWakeup(c->client); - ChangeGC(c->pGC, clearGCmask, clearGC); - - /* Unreference the font from the scratch GC */ - CloseFont(c->pGC->font, (Font)0); - c->pGC->font = NullFont; - - FreeScratchGC(c->pGC); - xfree(c->data); - xfree(c); - } - return TRUE; -} - -int -PolyText(ClientPtr client, DrawablePtr pDraw, GC *pGC, unsigned char *pElt, - unsigned char *endReq, int xorg, int yorg, int reqType, XID did) -{ - PTclosureRec local_closure; - - local_closure.pElt = pElt; - local_closure.endReq = endReq; - local_closure.client = client; - local_closure.pDraw = pDraw; - local_closure.xorg = xorg; - local_closure.yorg = yorg; - if ((local_closure.reqType = reqType) == X_PolyText8) - { - local_closure.polyText = (PolyTextPtr) pGC->ops->PolyText8; - local_closure.itemSize = 1; - } - else - { - local_closure.polyText = (PolyTextPtr) pGC->ops->PolyText16; - local_closure.itemSize = 2; - } - local_closure.pGC = pGC; - local_closure.did = did; - local_closure.err = Success; - local_closure.slept = FALSE; - - (void) doPolyText(client, &local_closure); - return Success; -} - - -#undef TextEltHeader -#undef FontShiftSize - -int -doImageText(ClientPtr client, ITclosurePtr c) -{ - int err = Success, lgerr; /* err is in X error, not font error, space */ - FontPathElementPtr fpe; - - if (client->clientGone) - { - fpe = c->pGC->font->fpe; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - err = Success; - goto bail; - } - - /* Make sure our drawable hasn't disappeared while we slept. */ - if (c->slept && c->pDraw) - { - DrawablePtr pDraw; - dixLookupDrawable(&pDraw, c->did, client, 0, DixWriteAccess); - if (c->pDraw != pDraw) { - /* Our drawable has disappeared. Treat like client died... ask - the FPE code to clean up after client. */ - fpe = c->pGC->font->fpe; - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - err = Success; - goto bail; - } - } - - lgerr = LoadGlyphs(client, c->pGC->font, c->nChars, c->itemSize, c->data); - if (lgerr == Suspended) - { - if (!c->slept) { - GC *pGC; - unsigned char *data; - ITclosurePtr new_closure; - - /* We're putting the client to sleep. We need to - save some state. Similar problem to that handled - in doPolyText, but much simpler because the - request structure is much simpler. */ - - new_closure = xalloc(sizeof(ITclosureRec)); - if (!new_closure) - { - err = BadAlloc; - goto bail; - } - *new_closure = *c; - c = new_closure; - - data = xalloc(c->nChars * c->itemSize); - if (!data) - { - xfree(c); - err = BadAlloc; - goto bail; - } - memmove(data, c->data, c->nChars * c->itemSize); - c->data = data; - - pGC = GetScratchGC(c->pGC->depth, c->pGC->pScreen); - if (!pGC) - { - xfree(c->data); - xfree(c); - err = BadAlloc; - goto bail; - } - if ((err = CopyGC(c->pGC, pGC, GCFunction | GCPlaneMask | - GCForeground | GCBackground | GCFillStyle | - GCTile | GCStipple | GCTileStipXOrigin | - GCTileStipYOrigin | GCFont | - GCSubwindowMode | GCClipXOrigin | - GCClipYOrigin | GCClipMask)) != Success) - { - FreeScratchGC(pGC); - xfree(c->data); - xfree(c); - err = BadAlloc; - goto bail; - } - c->pGC = pGC; - ValidateGC(c->pDraw, c->pGC); - - c->slept = TRUE; - ClientSleep(client, (ClientSleepProcPtr)doImageText, (pointer) c); - } - return TRUE; - } - else if (lgerr != Successful) - { - err = FontToXError(lgerr); - goto bail; - } - if (c->pDraw) - { - (* c->imageText)(c->pDraw, c->pGC, c->xorg, c->yorg, - c->nChars, c->data); - } - -bail: - - if (err != Success && c->client != serverClient) { - SendErrorToClient(c->client, c->reqType, 0, 0, err); - } - if (c->slept) - { - ClientWakeup(c->client); - ChangeGC(c->pGC, clearGCmask, clearGC); - - /* Unreference the font from the scratch GC */ - CloseFont(c->pGC->font, (Font)0); - c->pGC->font = NullFont; - - FreeScratchGC(c->pGC); - xfree(c->data); - xfree(c); - } - return TRUE; -} - -int -ImageText(ClientPtr client, DrawablePtr pDraw, GC *pGC, int nChars, - unsigned char *data, int xorg, int yorg, int reqType, XID did) -{ - ITclosureRec local_closure; - - local_closure.client = client; - local_closure.pDraw = pDraw; - local_closure.pGC = pGC; - local_closure.nChars = nChars; - local_closure.data = data; - local_closure.xorg = xorg; - local_closure.yorg = yorg; - if ((local_closure.reqType = reqType) == X_ImageText8) - { - local_closure.imageText = (ImageTextPtr) pGC->ops->ImageText8; - local_closure.itemSize = 1; - } - else - { - local_closure.imageText = (ImageTextPtr) pGC->ops->ImageText16; - local_closure.itemSize = 2; - } - local_closure.did = did; - local_closure.slept = FALSE; - - (void) doImageText(client, &local_closure); - return Success; -} - - -/* does the necessary magic to figure out the fpe type */ -static int -DetermineFPEType(char *pathname) -{ - int i; - - for (i = 0; i < num_fpe_types; i++) { - if ((*fpe_functions[i].name_check) (pathname)) - return i; - } - return -1; -} - - -static void -FreeFontPath(FontPathElementPtr *list, int n, Bool force) -{ - int i; - - for (i = 0; i < n; i++) { - if (force) { - /* Sanity check that all refcounts will be 0 by the time - we get to the end of the list. */ - int found = 1; /* the first reference is us */ - int j; - for (j = i+1; j < n; j++) { - if (list[j] == list[i]) - found++; - } - if (list[i]->refcount != found) { - list[i]->refcount = found; /* ensure it will get freed */ - } - } - FreeFPE(list[i]); - } - xfree(list); -} - -static FontPathElementPtr -find_existing_fpe(FontPathElementPtr *list, int num, unsigned char *name, int len) -{ - FontPathElementPtr fpe; - int i; - - for (i = 0; i < num; i++) { - fpe = list[i]; - if (fpe->name_length == len && memcmp(name, fpe->name, len) == 0) - return fpe; - } - return (FontPathElementPtr) 0; -} - - -static int -SetFontPathElements(int npaths, unsigned char *paths, int *bad, Bool persist) -{ - int i, err = 0; - int valid_paths = 0; - unsigned int len; - unsigned char *cp = paths; - FontPathElementPtr fpe = NULL, *fplist; - - fplist = xalloc(sizeof(FontPathElementPtr) * npaths); - if (!fplist) { - *bad = 0; - return BadAlloc; - } - for (i = 0; i < num_fpe_types; i++) { - if (fpe_functions[i].set_path_hook) - (*fpe_functions[i].set_path_hook) (); - } - for (i = 0; i < npaths; i++) - { - len = (unsigned int) (*cp++); - - if (len == 0) - { - if (persist) - ErrorF("[dix] Removing empty element from the valid list of fontpaths\n"); - err = BadValue; - } - else - { - /* if it's already in our active list, just reset it */ - /* - * note that this can miss FPE's in limbo -- may be worth catching - * them, though it'd muck up refcounting - */ - fpe = find_existing_fpe(font_path_elements, num_fpes, cp, len); - if (fpe) - { - err = (*fpe_functions[fpe->type].reset_fpe) (fpe); - if (err == Successful) - { - UseFPE(fpe);/* since it'll be decref'd later when freed - * from the old list */ - } - else - fpe = 0; - } - /* if error or can't do it, act like it's a new one */ - if (!fpe) - { - fpe = xalloc(sizeof(FontPathElementRec)); - if (!fpe) - { - err = BadAlloc; - goto bail; - } - fpe->name = xalloc(len + 1); - if (!fpe->name) - { - xfree(fpe); - err = BadAlloc; - goto bail; - } - fpe->refcount = 1; - - strncpy(fpe->name, (char *) cp, (int) len); - fpe->name[len] = '\0'; - fpe->name_length = len; - fpe->type = DetermineFPEType(fpe->name); - if (fpe->type == -1) - err = BadValue; - else - err = (*fpe_functions[fpe->type].init_fpe) (fpe); - if (err != Successful) - { - if (persist) - { - ErrorF("[dix] Could not init font path element %s, removing from list!\n", - fpe->name); - } - xfree (fpe->name); - xfree (fpe); - } - } - } - if (err != Successful) - { - if (!persist) - goto bail; - } - else - { - fplist[valid_paths++] = fpe; - } - cp += len; - } - - FreeFontPath(font_path_elements, num_fpes, FALSE); - font_path_elements = fplist; - if (patternCache) - EmptyFontPatternCache(patternCache); - num_fpes = valid_paths; - - return Success; -bail: - *bad = i; - while (--valid_paths >= 0) - FreeFPE(fplist[valid_paths]); - xfree(fplist); - return FontToXError(err); -} - -/* XXX -- do we need to pass error down to each renderer? */ -int -SetFontPath(ClientPtr client, int npaths, unsigned char *paths, int *error) -{ - int err = XaceHook(XACE_SERVER_ACCESS, client, DixManageAccess); - if (err != Success) - return err; - - if (npaths == 0) { - if (SetDefaultFontPath(defaultFontPath) != Success) - return BadValue; - } else { - err = SetFontPathElements(npaths, paths, error, FALSE); - } - return err; -} - -int -SetDefaultFontPath(char *path) -{ - char *temp_path, - *start, - *end; - unsigned char *cp, - *pp, - *nump, - *newpath; - int num = 1, - len, - err, - size = 0, - bad; - - /* ensure temp_path contains "built-ins" */ - start = path; - while (1) { - start = strstr(start, "built-ins"); - if (start == NULL) - break; - end = start + strlen("built-ins"); - if ((start == path || start[-1] == ',') && (!*end || *end == ',')) - break; - start = end; - } - if (!start) { - temp_path = Xprintf("%s%sbuilt-ins", path, *path ? "," : ""); - } else { - temp_path = Xstrdup(path); - } - if (!temp_path) - return BadAlloc; - - /* get enough for string, plus values -- use up commas */ - len = strlen(temp_path) + 1; - nump = cp = newpath = xalloc(len); - if (!newpath) - return BadAlloc; - pp = (unsigned char *) temp_path; - cp++; - while (*pp) { - if (*pp == ',') { - *nump = (unsigned char) size; - nump = cp++; - pp++; - num++; - size = 0; - } else { - *cp++ = *pp++; - size++; - } - } - *nump = (unsigned char) size; - - err = SetFontPathElements(num, newpath, &bad, TRUE); - - xfree(newpath); - xfree(temp_path); - - return err; -} - -int -GetFontPath(ClientPtr client, int *count, int *length, unsigned char **result) -{ - int i; - unsigned char *c; - int len; - FontPathElementPtr fpe; - - i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess); - if (i != Success) - return i; - - len = 0; - for (i = 0; i < num_fpes; i++) { - fpe = font_path_elements[i]; - len += fpe->name_length + 1; - } - font_path_string = (unsigned char *) xrealloc(font_path_string, len); - if (!font_path_string) - return BadAlloc; - - c = font_path_string; - *length = 0; - for (i = 0; i < num_fpes; i++) { - fpe = font_path_elements[i]; - *c = fpe->name_length; - *length += *c++; - memmove(c, fpe->name, fpe->name_length); - c += fpe->name_length; - } - *count = num_fpes; - *result = font_path_string; - return Success; -} - -void -DeleteClientFontStuff(ClientPtr client) -{ - int i; - FontPathElementPtr fpe; - - for (i = 0; i < num_fpes; i++) - { - fpe = font_path_elements[i]; - if (fpe_functions[fpe->type].client_died) - (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe); - } -} - -void -InitFonts (void) -{ - patternCache = MakeFontPatternCache(); - - BuiltinRegisterFpeFunctions(); - FontFileRegisterFpeFunctions(); - fs_register_fpe_functions(); -} - -int -GetDefaultPointSize (void) -{ - return 120; -} - - -FontResolutionPtr -GetClientResolutions (int *num) -{ - static struct _FontResolution res; - ScreenPtr pScreen; - - pScreen = screenInfo.screens[0]; - res.x_resolution = (pScreen->width * 25.4) / pScreen->mmWidth; - /* - * XXX - we'll want this as long as bitmap instances are prevalent - so that we can match them from scalable fonts - */ - if (res.x_resolution < 88) - res.x_resolution = 75; - else - res.x_resolution = 100; - res.y_resolution = (pScreen->height * 25.4) / pScreen->mmHeight; - if (res.y_resolution < 88) - res.y_resolution = 75; - else - res.y_resolution = 100; - res.point_size = 120; - *num = 1; - return &res; -} - -/* - * returns the type index of the new fpe - * - * should be called (only once!) by each type of fpe when initialized - */ - -int -RegisterFPEFunctions(NameCheckFunc name_func, - InitFpeFunc init_func, - FreeFpeFunc free_func, - ResetFpeFunc reset_func, - OpenFontFunc open_func, - CloseFontFunc close_func, - ListFontsFunc list_func, - StartLfwiFunc start_lfwi_func, - NextLfwiFunc next_lfwi_func, - WakeupFpeFunc wakeup_func, - ClientDiedFunc client_died, - LoadGlyphsFunc load_glyphs, - StartLaFunc start_list_alias_func, - NextLaFunc next_list_alias_func, - SetPathFunc set_path_func) -{ - FPEFunctions *new; - - /* grow the list */ - new = (FPEFunctions *) xrealloc(fpe_functions, - (num_fpe_types + 1) * sizeof(FPEFunctions)); - if (!new) - return -1; - fpe_functions = new; - - fpe_functions[num_fpe_types].name_check = name_func; - fpe_functions[num_fpe_types].open_font = open_func; - fpe_functions[num_fpe_types].close_font = close_func; - fpe_functions[num_fpe_types].wakeup_fpe = wakeup_func; - fpe_functions[num_fpe_types].list_fonts = list_func; - fpe_functions[num_fpe_types].start_list_fonts_with_info = - start_lfwi_func; - fpe_functions[num_fpe_types].list_next_font_with_info = - next_lfwi_func; - fpe_functions[num_fpe_types].init_fpe = init_func; - fpe_functions[num_fpe_types].free_fpe = free_func; - fpe_functions[num_fpe_types].reset_fpe = reset_func; - fpe_functions[num_fpe_types].client_died = client_died; - fpe_functions[num_fpe_types].load_glyphs = load_glyphs; - fpe_functions[num_fpe_types].start_list_fonts_and_aliases = - start_list_alias_func; - fpe_functions[num_fpe_types].list_next_font_or_alias = - next_list_alias_func; - fpe_functions[num_fpe_types].set_path_hook = set_path_func; - - return num_fpe_types++; -} - -void -FreeFonts(void) -{ - if (patternCache) { - FreeFontPatternCache(patternCache); - patternCache = 0; - } - FreeFontPath(font_path_elements, num_fpes, TRUE); - font_path_elements = 0; - num_fpes = 0; - xfree(fpe_functions); - num_fpe_types = 0; - fpe_functions = (FPEFunctions *) 0; -} - -/* convenience functions for FS interface */ - -FontPtr -find_old_font(XID id) -{ - pointer pFont; - dixLookupResourceByType(&pFont, id, RT_NONE, serverClient, DixReadAccess); - return (FontPtr)pFont; -} - -Font -GetNewFontClientID(void) -{ - return FakeClientID(0); -} - -int -StoreFontClientFont(FontPtr pfont, Font id) -{ - return AddResource(id, RT_NONE, (pointer) pfont); -} - -void -DeleteFontClientID(Font id) -{ - FreeResource(id, RT_NONE); -} - -int -client_auth_generation(ClientPtr client) -{ - return 0; -} - -static int fs_handlers_installed = 0; -static unsigned int last_server_gen; - -int -init_fs_handlers(FontPathElementPtr fpe, BlockHandlerProcPtr block_handler) -{ - /* if server has reset, make sure the b&w handlers are reinstalled */ - if (last_server_gen < serverGeneration) { - last_server_gen = serverGeneration; - fs_handlers_installed = 0; - } - if (fs_handlers_installed == 0) { - if (!RegisterBlockAndWakeupHandlers(block_handler, - FontWakeup, (pointer) 0)) - return AllocError; - fs_handlers_installed++; - } - QueueFontWakeup(fpe); - return Successful; -} - -void -remove_fs_handlers(FontPathElementPtr fpe, BlockHandlerProcPtr block_handler, Bool all) -{ - if (all) { - /* remove the handlers if no one else is using them */ - if (--fs_handlers_installed == 0) { - RemoveBlockAndWakeupHandlers(block_handler, FontWakeup, - (pointer) 0); - } - } - RemoveFontWakeup(fpe); -} +/************************************************************************
+Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
+
+ All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+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 Digital not be
+used in advertising or publicity pertaining to distribution of the
+software without specific, written prior permission.
+
+DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
+ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
+DIGITAL 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.
+
+************************************************************************/
+/* The panoramix components contained the following notice */
+/*
+Copyright (c) 1991, 1997 Digital Equipment Corporation, Maynard, Massachusetts.
+
+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.
+
+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
+DIGITAL EQUIPMENT CORPORATION BE LIABLE FOR ANY CLAIM, DAMAGES, INCLUDING,
+BUT NOT LIMITED TO CONSEQUENTIAL OR INCIDENTAL 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 Digital Equipment Corporation
+shall not be used in advertising or otherwise to promote the sale, use or other
+dealings in this Software without prior written authorization from Digital
+Equipment Corporation.
+
+******************************************************************/
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <X11/X.h>
+#include <X11/Xmd.h>
+#include <X11/Xproto.h>
+#include "scrnintstr.h"
+#include "resource.h"
+#include "dixstruct.h"
+#include "cursorstr.h"
+#include "misc.h"
+#include "opaque.h"
+#include "dixfontstr.h"
+#include "closestr.h"
+#include "dixfont.h"
+#include "xace.h"
+
+#ifdef DEBUG
+#include <stdio.h>
+#endif
+
+#ifdef XF86BIGFONT
+#define _XF86BIGFONT_SERVER_
+#include <X11/extensions/xf86bigfont.h>
+#endif
+
+#define QUERYCHARINFO(pci, pr) *(pr) = (pci)->metrics
+
+extern pointer fosNaturalParams;
+extern FontPtr defaultFont;
+
+static FontPathElementPtr *font_path_elements = (FontPathElementPtr *) 0;
+static int num_fpes = 0;
+static FPEFunctions *fpe_functions = (FPEFunctions *) 0;
+static int num_fpe_types = 0;
+
+static unsigned char *font_path_string;
+
+static int num_slept_fpes = 0;
+static int size_slept_fpes = 0;
+static FontPathElementPtr *slept_fpes = (FontPathElementPtr *) 0;
+static FontPatternCachePtr patternCache;
+
+static int
+FontToXError(int err)
+{
+ switch (err) {
+ case Successful:
+ return Success;
+ case AllocError:
+ return BadAlloc;
+ case BadFontName:
+ return BadName;
+ case BadFontPath:
+ case BadFontFormat: /* is there something better? */
+ case BadCharRange:
+ return BadValue;
+ default:
+ return err;
+ }
+}
+
+static int
+LoadGlyphs(ClientPtr client, FontPtr pfont, unsigned nchars, int item_size,
+ unsigned char *data)
+{
+ if (fpe_functions[pfont->fpe->type].load_glyphs)
+ return (*fpe_functions[pfont->fpe->type].load_glyphs)
+ (client, pfont, 0, nchars, item_size, data);
+ else
+ return Successful;
+}
+
+/*
+ * adding RT_FONT prevents conflict with default cursor font
+ */
+Bool
+SetDefaultFont(char *defaultfontname)
+{
+ int err;
+ FontPtr pf;
+ XID fid;
+ static FontPtr last_pf;
+
+ fid = FakeClientID(0);
+ err = OpenFont(serverClient, fid, FontLoadAll | FontOpenSync,
+ (unsigned) strlen(defaultfontname), defaultfontname);
+ if (err != Success)
+ return FALSE;
+ err = dixLookupResourceByType((pointer *)&pf, fid, RT_FONT, serverClient,
+ DixReadAccess);
+ if (err == Success) last_pf = pf;
+ if (last_pf == (FontPtr) NULL)
+ return FALSE;
+ defaultFont = last_pf;
+ return TRUE;
+}
+
+/*
+ * note that the font wakeup queue is not refcounted. this is because
+ * an fpe needs to be added when it's inited, and removed when it's finally
+ * freed, in order to handle any data that isn't requested, like FS events.
+ *
+ * since the only thing that should call these routines is the renderer's
+ * init_fpe() and free_fpe(), there shouldn't be any problem in using
+ * freed data.
+ */
+void
+QueueFontWakeup(FontPathElementPtr fpe)
+{
+ int i;
+ FontPathElementPtr *new;
+
+ for (i = 0; i < num_slept_fpes; i++) {
+ if (slept_fpes[i] == fpe) {
+ return;
+ }
+ }
+ if (num_slept_fpes == size_slept_fpes) {
+ new = (FontPathElementPtr *)
+ xrealloc(slept_fpes,
+ sizeof(FontPathElementPtr) * (size_slept_fpes + 4));
+ if (!new)
+ return;
+ slept_fpes = new;
+ size_slept_fpes += 4;
+ }
+ slept_fpes[num_slept_fpes] = fpe;
+ num_slept_fpes++;
+}
+
+void
+RemoveFontWakeup(FontPathElementPtr fpe)
+{
+ int i,
+ j;
+
+ for (i = 0; i < num_slept_fpes; i++) {
+ if (slept_fpes[i] == fpe) {
+ for (j = i; j < num_slept_fpes; j++) {
+ slept_fpes[j] = slept_fpes[j + 1];
+ }
+ num_slept_fpes--;
+ return;
+ }
+ }
+}
+
+void
+FontWakeup(pointer data, int count, pointer LastSelectMask)
+{
+ int i;
+ FontPathElementPtr fpe;
+
+ if (count < 0)
+ return;
+ /* wake up any fpe's that may be waiting for information */
+ for (i = 0; i < num_slept_fpes; i++) {
+ fpe = slept_fpes[i];
+ (void) (*fpe_functions[fpe->type].wakeup_fpe) (fpe, LastSelectMask);
+ }
+}
+
+/* XXX -- these two funcs may want to be broken into macros */
+static void
+UseFPE(FontPathElementPtr fpe)
+{
+ fpe->refcount++;
+}
+
+static void
+FreeFPE (FontPathElementPtr fpe)
+{
+ fpe->refcount--;
+ if (fpe->refcount == 0) {
+ (*fpe_functions[fpe->type].free_fpe) (fpe);
+ xfree(fpe->name);
+ xfree(fpe);
+ }
+}
+
+static Bool
+doOpenFont(ClientPtr client, OFclosurePtr c)
+{
+ FontPtr pfont = NullFont;
+ FontPathElementPtr fpe = NULL;
+ ScreenPtr pScr;
+ int err = Successful;
+ int i;
+ char *alias,
+ *newname;
+ int newlen;
+ int aliascount = 20;
+ /*
+ * Decide at runtime what FontFormat to use.
+ */
+ Mask FontFormat =
+
+ ((screenInfo.imageByteOrder == LSBFirst) ?
+ BitmapFormatByteOrderLSB : BitmapFormatByteOrderMSB) |
+
+ ((screenInfo.bitmapBitOrder == LSBFirst) ?
+ BitmapFormatBitOrderLSB : BitmapFormatBitOrderMSB) |
+
+ BitmapFormatImageRectMin |
+
+#if GLYPHPADBYTES == 1
+ BitmapFormatScanlinePad8 |
+#endif
+
+#if GLYPHPADBYTES == 2
+ BitmapFormatScanlinePad16 |
+#endif
+
+#if GLYPHPADBYTES == 4
+ BitmapFormatScanlinePad32 |
+#endif
+
+#if GLYPHPADBYTES == 8
+ BitmapFormatScanlinePad64 |
+#endif
+
+ BitmapFormatScanlineUnit8;
+
+ if (client->clientGone)
+ {
+ if (c->current_fpe < c->num_fpes)
+ {
+ fpe = c->fpe_list[c->current_fpe];
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ }
+ err = Successful;
+ goto bail;
+ }
+ while (c->current_fpe < c->num_fpes) {
+ fpe = c->fpe_list[c->current_fpe];
+ err = (*fpe_functions[fpe->type].open_font)
+ ((pointer) client, fpe, c->flags,
+ c->fontname, c->fnamelen, FontFormat,
+ BitmapFormatMaskByte |
+ BitmapFormatMaskBit |
+ BitmapFormatMaskImageRectangle |
+ BitmapFormatMaskScanLinePad |
+ BitmapFormatMaskScanLineUnit,
+ c->fontid, &pfont, &alias,
+ c->non_cachable_font && c->non_cachable_font->fpe == fpe ?
+ c->non_cachable_font :
+ (FontPtr)0);
+
+ if (err == FontNameAlias && alias) {
+ newlen = strlen(alias);
+ newname = (char *) xrealloc(c->fontname, newlen);
+ if (!newname) {
+ err = AllocError;
+ break;
+ }
+ memmove(newname, alias, newlen);
+ c->fontname = newname;
+ c->fnamelen = newlen;
+ c->current_fpe = 0;
+ if (--aliascount <= 0) {
+ /* We've tried resolving this alias 20 times, we're
+ * probably stuck in an infinite loop of aliases pointing
+ * to each other - time to take emergency exit!
+ */
+ err = BadImplementation;
+ break;
+ }
+ continue;
+ }
+ if (err == BadFontName) {
+ c->current_fpe++;
+ continue;
+ }
+ if (err == Suspended) {
+ if (!c->slept) {
+ c->slept = TRUE;
+ ClientSleep(client, (ClientSleepProcPtr)doOpenFont, (pointer) c);
+ }
+ return TRUE;
+ }
+ break;
+ }
+
+ if (err != Successful)
+ goto bail;
+ if (!pfont) {
+ err = BadFontName;
+ goto bail;
+ }
+ /* check values for firstCol, lastCol, firstRow, and lastRow */
+ if (pfont->info.firstCol > pfont->info.lastCol ||
+ pfont->info.firstRow > pfont->info.lastRow ||
+ pfont->info.lastCol - pfont->info.firstCol > 255) {
+ err = AllocError;
+ goto bail;
+ }
+ if (!pfont->fpe)
+ pfont->fpe = fpe;
+ pfont->refcnt++;
+ if (pfont->refcnt == 1) {
+ UseFPE(pfont->fpe);
+ for (i = 0; i < screenInfo.numScreens; i++) {
+ pScr = screenInfo.screens[i];
+ if (pScr->RealizeFont)
+ {
+ if (!(*pScr->RealizeFont) (pScr, pfont))
+ {
+ CloseFont (pfont, (Font) 0);
+ err = AllocError;
+ goto bail;
+ }
+ }
+ }
+ }
+ if (!AddResource(c->fontid, RT_FONT, (pointer) pfont)) {
+ err = AllocError;
+ goto bail;
+ }
+ if (patternCache && pfont != c->non_cachable_font)
+ CacheFontPattern(patternCache, c->origFontName, c->origFontNameLen,
+ pfont);
+bail:
+ if (err != Successful && c->client != serverClient) {
+ SendErrorToClient(c->client, X_OpenFont, 0,
+ c->fontid, FontToXError(err));
+ }
+ if (c->slept)
+ ClientWakeup(c->client);
+ for (i = 0; i < c->num_fpes; i++) {
+ FreeFPE(c->fpe_list[i]);
+ }
+ xfree(c->fpe_list);
+ xfree(c->fontname);
+ xfree(c);
+ return TRUE;
+}
+
+int
+OpenFont(ClientPtr client, XID fid, Mask flags, unsigned lenfname, char *pfontname)
+{
+ OFclosurePtr c;
+ int i;
+ FontPtr cached = (FontPtr)0;
+
+#ifdef FONTDEBUG
+ char *f;
+ f = xalloc(lenfname + 1);
+ memmove(f, pfontname, lenfname);
+ f[lenfname] = '\0';
+ ErrorF("[dix] OpenFont: fontname is \"%s\"\n", f);
+ xfree(f);
+#endif
+ if (!lenfname || lenfname > XLFDMAXFONTNAMELEN)
+ return BadName;
+ if (patternCache)
+ {
+
+ /*
+ ** Check name cache. If we find a cached version of this font that
+ ** is cachable, immediately satisfy the request with it. If we find
+ ** a cached version of this font that is non-cachable, we do not
+ ** satisfy the request with it. Instead, we pass the FontPtr to the
+ ** FPE's open_font code (the fontfile FPE in turn passes the
+ ** information to the rasterizer; the fserve FPE ignores it).
+ **
+ ** Presumably, the font is marked non-cachable because the FPE has
+ ** put some licensing restrictions on it. If the FPE, using
+ ** whatever logic it relies on, determines that it is willing to
+ ** share this existing font with the client, then it has the option
+ ** to return the FontPtr we passed it as the newly-opened font.
+ ** This allows the FPE to exercise its licensing logic without
+ ** having to create another instance of a font that already exists.
+ */
+
+ cached = FindCachedFontPattern(patternCache, pfontname, lenfname);
+ if (cached && cached->info.cachable)
+ {
+ if (!AddResource(fid, RT_FONT, (pointer) cached))
+ return BadAlloc;
+ cached->refcnt++;
+ return Success;
+ }
+ }
+ c = xalloc(sizeof(OFclosureRec));
+ if (!c)
+ return BadAlloc;
+ c->fontname = xalloc(lenfname);
+ c->origFontName = pfontname;
+ c->origFontNameLen = lenfname;
+ if (!c->fontname) {
+ xfree(c);
+ return BadAlloc;
+ }
+ /*
+ * copy the current FPE list, so that if it gets changed by another client
+ * while we're blocking, the request still appears atomic
+ */
+ c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes);
+ if (!c->fpe_list) {
+ xfree(c->fontname);
+ xfree(c);
+ return BadAlloc;
+ }
+ memmove(c->fontname, pfontname, lenfname);
+ for (i = 0; i < num_fpes; i++) {
+ c->fpe_list[i] = font_path_elements[i];
+ UseFPE(c->fpe_list[i]);
+ }
+ c->client = client;
+ c->fontid = fid;
+ c->current_fpe = 0;
+ c->num_fpes = num_fpes;
+ c->fnamelen = lenfname;
+ c->slept = FALSE;
+ c->flags = flags;
+ c->non_cachable_font = cached;
+
+ (void) doOpenFont(client, c);
+ return Success;
+}
+
+/**
+ * Decrement font's ref count, and free storage if ref count equals zero
+ *
+ * \param value must conform to DeleteType
+ */
+int
+CloseFont(pointer value, XID fid)
+{
+ int nscr;
+ ScreenPtr pscr;
+ FontPathElementPtr fpe;
+ FontPtr pfont = (FontPtr)value;
+
+ if (pfont == NullFont)
+ return (Success);
+ if (--pfont->refcnt == 0) {
+ if (patternCache)
+ RemoveCachedFontPattern (patternCache, pfont);
+ /*
+ * since the last reference is gone, ask each screen to free any
+ * storage it may have allocated locally for it.
+ */
+ for (nscr = 0; nscr < screenInfo.numScreens; nscr++) {
+ pscr = screenInfo.screens[nscr];
+ if (pscr->UnrealizeFont)
+ (*pscr->UnrealizeFont) (pscr, pfont);
+ }
+ if (pfont == defaultFont)
+ defaultFont = NULL;
+#ifdef XF86BIGFONT
+ XF86BigfontFreeFontShm(pfont);
+#endif
+ fpe = pfont->fpe;
+ (*fpe_functions[fpe->type].close_font) (fpe, pfont);
+ FreeFPE(fpe);
+ }
+ return (Success);
+}
+
+
+/***====================================================================***/
+
+/**
+ * Sets up pReply as the correct QueryFontReply for pFont with the first
+ * nProtoCCIStructs char infos.
+ *
+ * \param pReply caller must allocate this storage
+ */
+void
+QueryFont(FontPtr pFont, xQueryFontReply *pReply, int nProtoCCIStructs)
+{
+ FontPropPtr pFP;
+ int r,
+ c,
+ i;
+ xFontProp *prFP;
+ xCharInfo *prCI;
+ xCharInfo *charInfos[256];
+ unsigned char chars[512];
+ int ninfos;
+ unsigned long ncols;
+ unsigned long count;
+
+ /* pr->length set in dispatch */
+ pReply->minCharOrByte2 = pFont->info.firstCol;
+ pReply->defaultChar = pFont->info.defaultCh;
+ pReply->maxCharOrByte2 = pFont->info.lastCol;
+ pReply->drawDirection = pFont->info.drawDirection;
+ pReply->allCharsExist = pFont->info.allExist;
+ pReply->minByte1 = pFont->info.firstRow;
+ pReply->maxByte1 = pFont->info.lastRow;
+ pReply->fontAscent = pFont->info.fontAscent;
+ pReply->fontDescent = pFont->info.fontDescent;
+
+ pReply->minBounds = pFont->info.ink_minbounds;
+ pReply->maxBounds = pFont->info.ink_maxbounds;
+
+ pReply->nFontProps = pFont->info.nprops;
+ pReply->nCharInfos = nProtoCCIStructs;
+
+ for (i = 0, pFP = pFont->info.props, prFP = (xFontProp *) (&pReply[1]);
+ i < pFont->info.nprops;
+ i++, pFP++, prFP++) {
+ prFP->name = pFP->name;
+ prFP->value = pFP->value;
+ }
+
+ ninfos = 0;
+ ncols = (unsigned long) (pFont->info.lastCol - pFont->info.firstCol + 1);
+ prCI = (xCharInfo *) (prFP);
+ for (r = pFont->info.firstRow;
+ ninfos < nProtoCCIStructs && r <= (int)pFont->info.lastRow;
+ r++) {
+ i = 0;
+ for (c = pFont->info.firstCol; c <= (int)pFont->info.lastCol; c++) {
+ chars[i++] = r;
+ chars[i++] = c;
+ }
+ (*pFont->get_metrics) (pFont, ncols, chars,
+ TwoD16Bit, &count, charInfos);
+ i = 0;
+ for (i = 0; i < (int) count && ninfos < nProtoCCIStructs; i++) {
+ *prCI = *charInfos[i];
+ prCI++;
+ ninfos++;
+ }
+ }
+ return;
+}
+
+static Bool
+doListFontsAndAliases(ClientPtr client, LFclosurePtr c)
+{
+ FontPathElementPtr fpe;
+ int err = Successful;
+ FontNamesPtr names = NULL;
+ char *name, *resolved=NULL;
+ int namelen, resolvedlen;
+ int nnames;
+ int stringLens;
+ int i;
+ xListFontsReply reply;
+ char *bufptr;
+ char *bufferStart;
+ int aliascount = 0;
+
+ if (client->clientGone)
+ {
+ if (c->current.current_fpe < c->num_fpes)
+ {
+ fpe = c->fpe_list[c->current.current_fpe];
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ }
+ err = Successful;
+ goto bail;
+ }
+
+ if (!c->current.patlen)
+ goto finish;
+
+ while (c->current.current_fpe < c->num_fpes) {
+ fpe = c->fpe_list[c->current.current_fpe];
+ err = Successful;
+
+ if (!fpe_functions[fpe->type].start_list_fonts_and_aliases)
+ {
+ /* This FPE doesn't support/require list_fonts_and_aliases */
+
+ err = (*fpe_functions[fpe->type].list_fonts)
+ ((pointer) c->client, fpe, c->current.pattern,
+ c->current.patlen, c->current.max_names - c->names->nnames,
+ c->names);
+
+ if (err == Suspended) {
+ if (!c->slept) {
+ c->slept = TRUE;
+ ClientSleep(client,
+ (ClientSleepProcPtr)doListFontsAndAliases,
+ (pointer) c);
+ }
+ return TRUE;
+ }
+
+ err = BadFontName;
+ }
+ else
+ {
+ /* Start of list_fonts_and_aliases functionality. Modeled
+ after list_fonts_with_info in that it resolves aliases,
+ except that the information collected from FPEs is just
+ names, not font info. Each list_next_font_or_alias()
+ returns either a name into name/namelen or an alias into
+ name/namelen and its target name into resolved/resolvedlen.
+ The code at this level then resolves the alias by polling
+ the FPEs. */
+
+ if (!c->current.list_started) {
+ err = (*fpe_functions[fpe->type].start_list_fonts_and_aliases)
+ ((pointer) c->client, fpe, c->current.pattern,
+ c->current.patlen, c->current.max_names - c->names->nnames,
+ &c->current.private);
+ if (err == Suspended) {
+ if (!c->slept) {
+ ClientSleep(client,
+ (ClientSleepProcPtr)doListFontsAndAliases,
+ (pointer) c);
+ c->slept = TRUE;
+ }
+ return TRUE;
+ }
+ if (err == Successful)
+ c->current.list_started = TRUE;
+ }
+ if (err == Successful) {
+ char *tmpname;
+ name = 0;
+ err = (*fpe_functions[fpe->type].list_next_font_or_alias)
+ ((pointer) c->client, fpe, &name, &namelen, &tmpname,
+ &resolvedlen, c->current.private);
+ if (err == Suspended) {
+ if (!c->slept) {
+ ClientSleep(client,
+ (ClientSleepProcPtr)doListFontsAndAliases,
+ (pointer) c);
+ c->slept = TRUE;
+ }
+ return TRUE;
+ }
+ if (err == FontNameAlias) {
+ if (resolved) xfree(resolved);
+ resolved = xalloc(resolvedlen + 1);
+ if (resolved)
+ memmove(resolved, tmpname, resolvedlen + 1);
+ }
+ }
+
+ if (err == Successful)
+ {
+ if (c->haveSaved)
+ {
+ if (c->savedName)
+ (void)AddFontNamesName(c->names, c->savedName,
+ c->savedNameLen);
+ }
+ else
+ (void)AddFontNamesName(c->names, name, namelen);
+ }
+
+ /*
+ * When we get an alias back, save our state and reset back to
+ * the start of the FPE looking for the specified name. As
+ * soon as a real font is found for the alias, pop back to the
+ * old state
+ */
+ else if (err == FontNameAlias) {
+ char tmp_pattern[XLFDMAXFONTNAMELEN];
+ /*
+ * when an alias recurses, we need to give
+ * the last FPE a chance to clean up; so we call
+ * it again, and assume that the error returned
+ * is BadFontName, indicating the alias resolution
+ * is complete.
+ */
+ memmove(tmp_pattern, resolved, resolvedlen);
+ if (c->haveSaved)
+ {
+ char *tmpname;
+ int tmpnamelen;
+
+ tmpname = 0;
+ (void) (*fpe_functions[fpe->type].list_next_font_or_alias)
+ ((pointer) c->client, fpe, &tmpname, &tmpnamelen,
+ &tmpname, &tmpnamelen, c->current.private);
+ if (--aliascount <= 0)
+ {
+ err = BadFontName;
+ goto ContBadFontName;
+ }
+ }
+ else
+ {
+ c->saved = c->current;
+ c->haveSaved = TRUE;
+ if (c->savedName)
+ xfree(c->savedName);
+ c->savedName = xalloc(namelen + 1);
+ if (c->savedName)
+ memmove(c->savedName, name, namelen + 1);
+ c->savedNameLen = namelen;
+ aliascount = 20;
+ }
+ memmove(c->current.pattern, tmp_pattern, resolvedlen);
+ c->current.patlen = resolvedlen;
+ c->current.max_names = c->names->nnames + 1;
+ c->current.current_fpe = -1;
+ c->current.private = 0;
+ err = BadFontName;
+ }
+ }
+ /*
+ * At the end of this FPE, step to the next. If we've finished
+ * processing an alias, pop state back. If we've collected enough
+ * font names, quit.
+ */
+ if (err == BadFontName) {
+ ContBadFontName: ;
+ c->current.list_started = FALSE;
+ c->current.current_fpe++;
+ err = Successful;
+ if (c->haveSaved)
+ {
+ if (c->names->nnames == c->current.max_names ||
+ c->current.current_fpe == c->num_fpes) {
+ c->haveSaved = FALSE;
+ c->current = c->saved;
+ /* Give the saved namelist a chance to clean itself up */
+ continue;
+ }
+ }
+ if (c->names->nnames == c->current.max_names)
+ break;
+ }
+ }
+
+ /*
+ * send the reply
+ */
+ if (err != Successful) {
+ SendErrorToClient(client, X_ListFonts, 0, 0, FontToXError(err));
+ goto bail;
+ }
+
+finish:
+
+ names = c->names;
+ nnames = names->nnames;
+ client = c->client;
+ stringLens = 0;
+ for (i = 0; i < nnames; i++)
+ stringLens += (names->length[i] <= 255) ? names->length[i] : 0;
+
+ memset(&reply, 0, sizeof(xListFontsReply));
+ reply.type = X_Reply;
+ reply.length = bytes_to_int32(stringLens + nnames);
+ reply.nFonts = nnames;
+ reply.sequenceNumber = client->sequence;
+
+ bufptr = bufferStart = xalloc(reply.length << 2);
+
+ if (!bufptr && reply.length) {
+ SendErrorToClient(client, X_ListFonts, 0, 0, BadAlloc);
+ goto bail;
+ }
+ /*
+ * since WriteToClient long word aligns things, copy to temp buffer and
+ * write all at once
+ */
+ for (i = 0; i < nnames; i++) {
+ if (names->length[i] > 255)
+ reply.nFonts--;
+ else
+ {
+ *bufptr++ = names->length[i];
+ memmove( bufptr, names->names[i], names->length[i]);
+ bufptr += names->length[i];
+ }
+ }
+ nnames = reply.nFonts;
+ reply.length = bytes_to_int32(stringLens + nnames);
+ client->pSwapReplyFunc = ReplySwapVector[X_ListFonts];
+ WriteSwappedDataToClient(client, sizeof(xListFontsReply), &reply);
+ (void) WriteToClient(client, stringLens + nnames, bufferStart);
+ xfree(bufferStart);
+
+bail:
+ if (c->slept)
+ ClientWakeup(client);
+ for (i = 0; i < c->num_fpes; i++)
+ FreeFPE(c->fpe_list[i]);
+ xfree(c->fpe_list);
+ if (c->savedName) xfree(c->savedName);
+ FreeFontNames(names);
+ xfree(c);
+ if (resolved) xfree(resolved);
+ return TRUE;
+}
+
+int
+ListFonts(ClientPtr client, unsigned char *pattern, unsigned length,
+ unsigned max_names)
+{
+ int i;
+ LFclosurePtr c;
+
+ /*
+ * The right error to return here would be BadName, however the
+ * specification does not allow for a Name error on this request.
+ * Perhaps a better solution would be to return a nil list, i.e.
+ * a list containing zero fontnames.
+ */
+ if (length > XLFDMAXFONTNAMELEN)
+ return BadAlloc;
+
+ i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess);
+ if (i != Success)
+ return i;
+
+ if (!(c = xalloc(sizeof *c)))
+ return BadAlloc;
+ c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes);
+ if (!c->fpe_list) {
+ xfree(c);
+ return BadAlloc;
+ }
+ c->names = MakeFontNamesRecord(max_names < 100 ? max_names : 100);
+ if (!c->names)
+ {
+ xfree(c->fpe_list);
+ xfree(c);
+ return BadAlloc;
+ }
+ memmove( c->current.pattern, pattern, length);
+ for (i = 0; i < num_fpes; i++) {
+ c->fpe_list[i] = font_path_elements[i];
+ UseFPE(c->fpe_list[i]);
+ }
+ c->client = client;
+ c->num_fpes = num_fpes;
+ c->current.patlen = length;
+ c->current.current_fpe = 0;
+ c->current.max_names = max_names;
+ c->current.list_started = FALSE;
+ c->current.private = 0;
+ c->haveSaved = FALSE;
+ c->slept = FALSE;
+ c->savedName = 0;
+ doListFontsAndAliases(client, c);
+ return Success;
+}
+
+int
+doListFontsWithInfo(ClientPtr client, LFWIclosurePtr c)
+{
+ FontPathElementPtr fpe;
+ int err = Successful;
+ char *name;
+ int namelen;
+ int numFonts;
+ FontInfoRec fontInfo,
+ *pFontInfo;
+ xListFontsWithInfoReply *reply;
+ int length;
+ xFontProp *pFP;
+ int i;
+ int aliascount = 0;
+ xListFontsWithInfoReply finalReply;
+
+ if (client->clientGone)
+ {
+ if (c->current.current_fpe < c->num_fpes)
+ {
+ fpe = c->fpe_list[c->current.current_fpe];
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ }
+ err = Successful;
+ goto bail;
+ }
+ client->pSwapReplyFunc = ReplySwapVector[X_ListFontsWithInfo];
+ if (!c->current.patlen)
+ goto finish;
+ while (c->current.current_fpe < c->num_fpes)
+ {
+ fpe = c->fpe_list[c->current.current_fpe];
+ err = Successful;
+ if (!c->current.list_started)
+ {
+ err = (*fpe_functions[fpe->type].start_list_fonts_with_info)
+ (client, fpe, c->current.pattern, c->current.patlen,
+ c->current.max_names, &c->current.private);
+ if (err == Suspended)
+ {
+ if (!c->slept)
+ {
+ ClientSleep(client, (ClientSleepProcPtr)doListFontsWithInfo, c);
+ c->slept = TRUE;
+ }
+ return TRUE;
+ }
+ if (err == Successful)
+ c->current.list_started = TRUE;
+ }
+ if (err == Successful)
+ {
+ name = 0;
+ pFontInfo = &fontInfo;
+ err = (*fpe_functions[fpe->type].list_next_font_with_info)
+ (client, fpe, &name, &namelen, &pFontInfo,
+ &numFonts, c->current.private);
+ if (err == Suspended)
+ {
+ if (!c->slept)
+ {
+ ClientSleep(client,
+ (ClientSleepProcPtr)doListFontsWithInfo,
+ c);
+ c->slept = TRUE;
+ }
+ return TRUE;
+ }
+ }
+ /*
+ * When we get an alias back, save our state and reset back to the
+ * start of the FPE looking for the specified name. As soon as a real
+ * font is found for the alias, pop back to the old state
+ */
+ if (err == FontNameAlias)
+ {
+ /*
+ * when an alias recurses, we need to give
+ * the last FPE a chance to clean up; so we call
+ * it again, and assume that the error returned
+ * is BadFontName, indicating the alias resolution
+ * is complete.
+ */
+ if (c->haveSaved)
+ {
+ char *tmpname;
+ int tmpnamelen;
+ FontInfoPtr tmpFontInfo;
+
+ tmpname = 0;
+ tmpFontInfo = &fontInfo;
+ (void) (*fpe_functions[fpe->type].list_next_font_with_info)
+ (client, fpe, &tmpname, &tmpnamelen, &tmpFontInfo,
+ &numFonts, c->current.private);
+ if (--aliascount <= 0)
+ {
+ err = BadFontName;
+ goto ContBadFontName;
+ }
+ }
+ else
+ {
+ c->saved = c->current;
+ c->haveSaved = TRUE;
+ c->savedNumFonts = numFonts;
+ if (c->savedName)
+ xfree(c->savedName);
+ c->savedName = xalloc(namelen + 1);
+ if (c->savedName)
+ memmove(c->savedName, name, namelen + 1);
+ aliascount = 20;
+ }
+ memmove(c->current.pattern, name, namelen);
+ c->current.patlen = namelen;
+ c->current.max_names = 1;
+ c->current.current_fpe = 0;
+ c->current.private = 0;
+ c->current.list_started = FALSE;
+ }
+ /*
+ * At the end of this FPE, step to the next. If we've finished
+ * processing an alias, pop state back. If we've sent enough font
+ * names, quit. Always wait for BadFontName to let the FPE
+ * have a chance to clean up.
+ */
+ else if (err == BadFontName)
+ {
+ ContBadFontName: ;
+ c->current.list_started = FALSE;
+ c->current.current_fpe++;
+ err = Successful;
+ if (c->haveSaved)
+ {
+ if (c->current.max_names == 0 ||
+ c->current.current_fpe == c->num_fpes)
+ {
+ c->haveSaved = FALSE;
+ c->saved.max_names -= (1 - c->current.max_names);
+ c->current = c->saved;
+ }
+ }
+ else if (c->current.max_names == 0)
+ break;
+ }
+ else if (err == Successful)
+ {
+ length = sizeof(*reply) + pFontInfo->nprops * sizeof(xFontProp);
+ reply = c->reply;
+ if (c->length < length)
+ {
+ reply = (xListFontsWithInfoReply *) xrealloc(c->reply, length);
+ if (!reply)
+ {
+ err = AllocError;
+ break;
+ }
+ memset(reply + c->length, 0, length - c->length);
+ c->reply = reply;
+ c->length = length;
+ }
+ if (c->haveSaved)
+ {
+ numFonts = c->savedNumFonts;
+ name = c->savedName;
+ namelen = strlen(name);
+ }
+ reply->type = X_Reply;
+ reply->length = bytes_to_int32(sizeof *reply - sizeof(xGenericReply) +
+ pFontInfo->nprops * sizeof(xFontProp) +
+ namelen);
+ reply->sequenceNumber = client->sequence;
+ reply->nameLength = namelen;
+ reply->minBounds = pFontInfo->ink_minbounds;
+ reply->maxBounds = pFontInfo->ink_maxbounds;
+ reply->minCharOrByte2 = pFontInfo->firstCol;
+ reply->maxCharOrByte2 = pFontInfo->lastCol;
+ reply->defaultChar = pFontInfo->defaultCh;
+ reply->nFontProps = pFontInfo->nprops;
+ reply->drawDirection = pFontInfo->drawDirection;
+ reply->minByte1 = pFontInfo->firstRow;
+ reply->maxByte1 = pFontInfo->lastRow;
+ reply->allCharsExist = pFontInfo->allExist;
+ reply->fontAscent = pFontInfo->fontAscent;
+ reply->fontDescent = pFontInfo->fontDescent;
+ reply->nReplies = numFonts;
+ pFP = (xFontProp *) (reply + 1);
+ for (i = 0; i < pFontInfo->nprops; i++)
+ {
+ pFP->name = pFontInfo->props[i].name;
+ pFP->value = pFontInfo->props[i].value;
+ pFP++;
+ }
+ WriteSwappedDataToClient(client, length, reply);
+ (void) WriteToClient(client, namelen, name);
+ if (pFontInfo == &fontInfo)
+ {
+ xfree(fontInfo.props);
+ xfree(fontInfo.isStringProp);
+ }
+ --c->current.max_names;
+ }
+ }
+finish:
+ length = sizeof(xListFontsWithInfoReply);
+ bzero((char *) &finalReply, sizeof(xListFontsWithInfoReply));
+ finalReply.type = X_Reply;
+ finalReply.sequenceNumber = client->sequence;
+ finalReply.length = bytes_to_int32(sizeof(xListFontsWithInfoReply)
+ - sizeof(xGenericReply));
+ WriteSwappedDataToClient(client, length, &finalReply);
+bail:
+ if (c->slept)
+ ClientWakeup(client);
+ for (i = 0; i < c->num_fpes; i++)
+ FreeFPE(c->fpe_list[i]);
+ xfree(c->reply);
+ xfree(c->fpe_list);
+ if (c->savedName) xfree(c->savedName);
+ xfree(c);
+ return TRUE;
+}
+
+int
+StartListFontsWithInfo(ClientPtr client, int length, unsigned char *pattern,
+ int max_names)
+{
+ int i;
+ LFWIclosurePtr c;
+
+ /*
+ * The right error to return here would be BadName, however the
+ * specification does not allow for a Name error on this request.
+ * Perhaps a better solution would be to return a nil list, i.e.
+ * a list containing zero fontnames.
+ */
+ if (length > XLFDMAXFONTNAMELEN)
+ return BadAlloc;
+
+ i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess);
+ if (i != Success)
+ return i;
+
+ if (!(c = xalloc(sizeof *c)))
+ goto badAlloc;
+ c->fpe_list = xalloc(sizeof(FontPathElementPtr) * num_fpes);
+ if (!c->fpe_list)
+ {
+ xfree(c);
+ goto badAlloc;
+ }
+ memmove(c->current.pattern, pattern, length);
+ for (i = 0; i < num_fpes; i++)
+ {
+ c->fpe_list[i] = font_path_elements[i];
+ UseFPE(c->fpe_list[i]);
+ }
+ c->client = client;
+ c->num_fpes = num_fpes;
+ c->reply = 0;
+ c->length = 0;
+ c->current.patlen = length;
+ c->current.current_fpe = 0;
+ c->current.max_names = max_names;
+ c->current.list_started = FALSE;
+ c->current.private = 0;
+ c->savedNumFonts = 0;
+ c->haveSaved = FALSE;
+ c->slept = FALSE;
+ c->savedName = 0;
+ doListFontsWithInfo(client, c);
+ return Success;
+badAlloc:
+ return BadAlloc;
+}
+
+#define TextEltHeader 2
+#define FontShiftSize 5
+static XID clearGC[] = { CT_NONE };
+#define clearGCmask (GCClipMask)
+
+int
+doPolyText(ClientPtr client, PTclosurePtr c)
+{
+ FontPtr pFont = c->pGC->font, oldpFont;
+ Font fid, oldfid;
+ int err = Success, lgerr; /* err is in X error, not font error, space */
+ enum { NEVER_SLEPT, START_SLEEP, SLEEPING } client_state = NEVER_SLEPT;
+ FontPathElementPtr fpe;
+ GC *origGC = NULL;
+
+ if (client->clientGone)
+ {
+ fpe = c->pGC->font->fpe;
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+
+ if (c->slept)
+ {
+ /* Client has died, but we cannot bail out right now. We
+ need to clean up after the work we did when going to
+ sleep. Setting the drawable pointer to 0 makes this
+ happen without any attempts to render or perform other
+ unnecessary activities. */
+ c->pDraw = (DrawablePtr)0;
+ }
+ else
+ {
+ err = Success;
+ goto bail;
+ }
+ }
+
+ /* Make sure our drawable hasn't disappeared while we slept. */
+ if (c->slept && c->pDraw)
+ {
+ DrawablePtr pDraw;
+ dixLookupDrawable(&pDraw, c->did, client, 0, DixWriteAccess);
+ if (c->pDraw != pDraw) {
+ /* Our drawable has disappeared. Treat like client died... ask
+ the FPE code to clean up after client and avoid further
+ rendering while we clean up after ourself. */
+ fpe = c->pGC->font->fpe;
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ c->pDraw = (DrawablePtr)0;
+ }
+ }
+
+ client_state = c->slept ? SLEEPING : NEVER_SLEPT;
+
+ while (c->endReq - c->pElt > TextEltHeader)
+ {
+ if (*c->pElt == FontChange)
+ {
+ if (c->endReq - c->pElt < FontShiftSize)
+ {
+ err = BadLength;
+ goto bail;
+ }
+
+ oldpFont = pFont;
+ oldfid = fid;
+
+ fid = ((Font)*(c->pElt+4)) /* big-endian */
+ | ((Font)*(c->pElt+3)) << 8
+ | ((Font)*(c->pElt+2)) << 16
+ | ((Font)*(c->pElt+1)) << 24;
+ err = dixLookupResourceByType((pointer *)&pFont, fid, RT_FONT,
+ client, DixReadAccess);
+ if (err != Success)
+ {
+ err = (err == BadValue) ? BadFont : err;
+ /* restore pFont and fid for step 4 (described below) */
+ pFont = oldpFont;
+ fid = oldfid;
+
+ /* If we're in START_SLEEP mode, the following step
+ shortens the request... in the unlikely event that
+ the fid somehow becomes valid before we come through
+ again to actually execute the polytext, which would
+ then mess up our refcounting scheme badly. */
+ c->err = err;
+ c->endReq = c->pElt;
+
+ goto bail;
+ }
+
+ /* Step 3 (described below) on our new font */
+ if (client_state == START_SLEEP)
+ pFont->refcnt++;
+ else
+ {
+ if (pFont != c->pGC->font && c->pDraw)
+ {
+ ChangeGC( c->pGC, GCFont, &fid);
+ ValidateGC(c->pDraw, c->pGC);
+ if (c->reqType == X_PolyText8)
+ c->polyText = (PolyTextPtr) c->pGC->ops->PolyText8;
+ else
+ c->polyText = (PolyTextPtr) c->pGC->ops->PolyText16;
+ }
+
+ /* Undo the refcnt++ we performed when going to sleep */
+ if (client_state == SLEEPING)
+ (void)CloseFont(c->pGC->font, (Font)0);
+ }
+ c->pElt += FontShiftSize;
+ }
+ else /* print a string */
+ {
+ unsigned char *pNextElt;
+ pNextElt = c->pElt + TextEltHeader + (*c->pElt)*c->itemSize;
+ if ( pNextElt > c->endReq)
+ {
+ err = BadLength;
+ goto bail;
+ }
+ if (client_state == START_SLEEP)
+ {
+ c->pElt = pNextElt;
+ continue;
+ }
+ if (c->pDraw)
+ {
+ lgerr = LoadGlyphs(client, c->pGC->font, *c->pElt, c->itemSize,
+ c->pElt + TextEltHeader);
+ }
+ else lgerr = Successful;
+
+ if (lgerr == Suspended)
+ {
+ if (!c->slept) {
+ int len;
+ GC *pGC;
+ PTclosurePtr new_closure;
+
+ /* We're putting the client to sleep. We need to do a few things
+ to ensure successful and atomic-appearing execution of the
+ remainder of the request. First, copy the remainder of the
+ request into a safe malloc'd area. Second, create a scratch GC
+ to use for the remainder of the request. Third, mark all fonts
+ referenced in the remainder of the request to prevent their
+ deallocation. Fourth, make the original GC look like the
+ request has completed... set its font to the final font value
+ from this request. These GC manipulations are for the unlikely
+ (but possible) event that some other client is using the GC.
+ Steps 3 and 4 are performed by running this procedure through
+ the remainder of the request in a special no-render mode
+ indicated by client_state = START_SLEEP. */
+
+ /* Step 1 */
+ /* Allocate a malloc'd closure structure to replace
+ the local one we were passed */
+ new_closure = xalloc(sizeof(PTclosureRec));
+ if (!new_closure)
+ {
+ err = BadAlloc;
+ goto bail;
+ }
+ *new_closure = *c;
+ c = new_closure;
+
+ len = c->endReq - c->pElt;
+ c->data = xalloc(len);
+ if (!c->data)
+ {
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ memmove(c->data, c->pElt, len);
+ c->pElt = c->data;
+ c->endReq = c->pElt + len;
+
+ /* Step 2 */
+
+ pGC = GetScratchGC(c->pGC->depth, c->pGC->pScreen);
+ if (!pGC)
+ {
+ xfree(c->data);
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ if ((err = CopyGC(c->pGC, pGC, GCFunction |
+ GCPlaneMask | GCForeground |
+ GCBackground | GCFillStyle |
+ GCTile | GCStipple |
+ GCTileStipXOrigin |
+ GCTileStipYOrigin | GCFont |
+ GCSubwindowMode | GCClipXOrigin |
+ GCClipYOrigin | GCClipMask)) !=
+ Success)
+ {
+ FreeScratchGC(pGC);
+ xfree(c->data);
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ origGC = c->pGC;
+ c->pGC = pGC;
+ ValidateGC(c->pDraw, c->pGC);
+
+ c->slept = TRUE;
+ ClientSleep(client,
+ (ClientSleepProcPtr)doPolyText,
+ (pointer) c);
+
+ /* Set up to perform steps 3 and 4 */
+ client_state = START_SLEEP;
+ continue; /* on to steps 3 and 4 */
+ }
+ return TRUE;
+ }
+ else if (lgerr != Successful)
+ {
+ err = FontToXError(lgerr);
+ goto bail;
+ }
+ if (c->pDraw)
+ {
+ c->xorg += *((INT8 *)(c->pElt + 1)); /* must be signed */
+ c->xorg = (* c->polyText)(c->pDraw, c->pGC, c->xorg, c->yorg,
+ *c->pElt, c->pElt + TextEltHeader);
+ }
+ c->pElt = pNextElt;
+ }
+ }
+
+bail:
+
+ if (client_state == START_SLEEP)
+ {
+ /* Step 4 */
+ if (pFont != origGC->font)
+ {
+ ChangeGC(origGC, GCFont, &fid);
+ ValidateGC(c->pDraw, origGC);
+ }
+
+ /* restore pElt pointer for execution of remainder of the request */
+ c->pElt = c->data;
+ return TRUE;
+ }
+
+ if (c->err != Success) err = c->err;
+ if (err != Success && c->client != serverClient) {
+#ifdef PANORAMIX
+ if (noPanoramiXExtension || !c->pGC->pScreen->myNum)
+#endif
+ SendErrorToClient(c->client, c->reqType, 0, 0, err);
+ }
+ if (c->slept)
+ {
+ ClientWakeup(c->client);
+ ChangeGC(c->pGC, clearGCmask, clearGC);
+
+ /* Unreference the font from the scratch GC */
+ CloseFont(c->pGC->font, (Font)0);
+ c->pGC->font = NullFont;
+
+ FreeScratchGC(c->pGC);
+ xfree(c->data);
+ xfree(c);
+ }
+ return TRUE;
+}
+
+int
+PolyText(ClientPtr client, DrawablePtr pDraw, GC *pGC, unsigned char *pElt,
+ unsigned char *endReq, int xorg, int yorg, int reqType, XID did)
+{
+ PTclosureRec local_closure;
+
+ local_closure.pElt = pElt;
+ local_closure.endReq = endReq;
+ local_closure.client = client;
+ local_closure.pDraw = pDraw;
+ local_closure.xorg = xorg;
+ local_closure.yorg = yorg;
+ if ((local_closure.reqType = reqType) == X_PolyText8)
+ {
+ local_closure.polyText = (PolyTextPtr) pGC->ops->PolyText8;
+ local_closure.itemSize = 1;
+ }
+ else
+ {
+ local_closure.polyText = (PolyTextPtr) pGC->ops->PolyText16;
+ local_closure.itemSize = 2;
+ }
+ local_closure.pGC = pGC;
+ local_closure.did = did;
+ local_closure.err = Success;
+ local_closure.slept = FALSE;
+
+ (void) doPolyText(client, &local_closure);
+ return Success;
+}
+
+
+#undef TextEltHeader
+#undef FontShiftSize
+
+int
+doImageText(ClientPtr client, ITclosurePtr c)
+{
+ int err = Success, lgerr; /* err is in X error, not font error, space */
+ FontPathElementPtr fpe;
+
+ if (client->clientGone)
+ {
+ fpe = c->pGC->font->fpe;
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ err = Success;
+ goto bail;
+ }
+
+ /* Make sure our drawable hasn't disappeared while we slept. */
+ if (c->slept && c->pDraw)
+ {
+ DrawablePtr pDraw;
+ dixLookupDrawable(&pDraw, c->did, client, 0, DixWriteAccess);
+ if (c->pDraw != pDraw) {
+ /* Our drawable has disappeared. Treat like client died... ask
+ the FPE code to clean up after client. */
+ fpe = c->pGC->font->fpe;
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ err = Success;
+ goto bail;
+ }
+ }
+
+ lgerr = LoadGlyphs(client, c->pGC->font, c->nChars, c->itemSize, c->data);
+ if (lgerr == Suspended)
+ {
+ if (!c->slept) {
+ GC *pGC;
+ unsigned char *data;
+ ITclosurePtr new_closure;
+
+ /* We're putting the client to sleep. We need to
+ save some state. Similar problem to that handled
+ in doPolyText, but much simpler because the
+ request structure is much simpler. */
+
+ new_closure = xalloc(sizeof(ITclosureRec));
+ if (!new_closure)
+ {
+ err = BadAlloc;
+ goto bail;
+ }
+ *new_closure = *c;
+ c = new_closure;
+
+ data = xalloc(c->nChars * c->itemSize);
+ if (!data)
+ {
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ memmove(data, c->data, c->nChars * c->itemSize);
+ c->data = data;
+
+ pGC = GetScratchGC(c->pGC->depth, c->pGC->pScreen);
+ if (!pGC)
+ {
+ xfree(c->data);
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ if ((err = CopyGC(c->pGC, pGC, GCFunction | GCPlaneMask |
+ GCForeground | GCBackground | GCFillStyle |
+ GCTile | GCStipple | GCTileStipXOrigin |
+ GCTileStipYOrigin | GCFont |
+ GCSubwindowMode | GCClipXOrigin |
+ GCClipYOrigin | GCClipMask)) != Success)
+ {
+ FreeScratchGC(pGC);
+ xfree(c->data);
+ xfree(c);
+ err = BadAlloc;
+ goto bail;
+ }
+ c->pGC = pGC;
+ ValidateGC(c->pDraw, c->pGC);
+
+ c->slept = TRUE;
+ ClientSleep(client, (ClientSleepProcPtr)doImageText, (pointer) c);
+ }
+ return TRUE;
+ }
+ else if (lgerr != Successful)
+ {
+ err = FontToXError(lgerr);
+ goto bail;
+ }
+ if (c->pDraw)
+ {
+ (* c->imageText)(c->pDraw, c->pGC, c->xorg, c->yorg,
+ c->nChars, c->data);
+ }
+
+bail:
+
+ if (err != Success && c->client != serverClient) {
+ SendErrorToClient(c->client, c->reqType, 0, 0, err);
+ }
+ if (c->slept)
+ {
+ ClientWakeup(c->client);
+ ChangeGC(c->pGC, clearGCmask, clearGC);
+
+ /* Unreference the font from the scratch GC */
+ CloseFont(c->pGC->font, (Font)0);
+ c->pGC->font = NullFont;
+
+ FreeScratchGC(c->pGC);
+ xfree(c->data);
+ xfree(c);
+ }
+ return TRUE;
+}
+
+int
+ImageText(ClientPtr client, DrawablePtr pDraw, GC *pGC, int nChars,
+ unsigned char *data, int xorg, int yorg, int reqType, XID did)
+{
+ ITclosureRec local_closure;
+
+ local_closure.client = client;
+ local_closure.pDraw = pDraw;
+ local_closure.pGC = pGC;
+ local_closure.nChars = nChars;
+ local_closure.data = data;
+ local_closure.xorg = xorg;
+ local_closure.yorg = yorg;
+ if ((local_closure.reqType = reqType) == X_ImageText8)
+ {
+ local_closure.imageText = (ImageTextPtr) pGC->ops->ImageText8;
+ local_closure.itemSize = 1;
+ }
+ else
+ {
+ local_closure.imageText = (ImageTextPtr) pGC->ops->ImageText16;
+ local_closure.itemSize = 2;
+ }
+ local_closure.did = did;
+ local_closure.slept = FALSE;
+
+ (void) doImageText(client, &local_closure);
+ return Success;
+}
+
+
+/* does the necessary magic to figure out the fpe type */
+static int
+DetermineFPEType(char *pathname)
+{
+ int i;
+
+ for (i = 0; i < num_fpe_types; i++) {
+ if ((*fpe_functions[i].name_check) (pathname))
+ return i;
+ }
+ return -1;
+}
+
+
+static void
+FreeFontPath(FontPathElementPtr *list, int n, Bool force)
+{
+ int i;
+
+ for (i = 0; i < n; i++) {
+ if (force) {
+ /* Sanity check that all refcounts will be 0 by the time
+ we get to the end of the list. */
+ int found = 1; /* the first reference is us */
+ int j;
+ for (j = i+1; j < n; j++) {
+ if (list[j] == list[i])
+ found++;
+ }
+ if (list[i]->refcount != found) {
+ list[i]->refcount = found; /* ensure it will get freed */
+ }
+ }
+ FreeFPE(list[i]);
+ }
+ xfree(list);
+}
+
+static FontPathElementPtr
+find_existing_fpe(FontPathElementPtr *list, int num, unsigned char *name, int len)
+{
+ FontPathElementPtr fpe;
+ int i;
+
+ for (i = 0; i < num; i++) {
+ fpe = list[i];
+ if (fpe->name_length == len && memcmp(name, fpe->name, len) == 0)
+ return fpe;
+ }
+ return (FontPathElementPtr) 0;
+}
+
+
+static int
+SetFontPathElements(int npaths, unsigned char *paths, int *bad, Bool persist)
+{
+ int i, err = 0;
+ int valid_paths = 0;
+ unsigned int len;
+ unsigned char *cp = paths;
+ FontPathElementPtr fpe = NULL, *fplist;
+
+ fplist = xalloc(sizeof(FontPathElementPtr) * npaths);
+ if (!fplist) {
+ *bad = 0;
+ return BadAlloc;
+ }
+ for (i = 0; i < num_fpe_types; i++) {
+ if (fpe_functions[i].set_path_hook)
+ (*fpe_functions[i].set_path_hook) ();
+ }
+ for (i = 0; i < npaths; i++)
+ {
+ len = (unsigned int) (*cp++);
+
+ if (len == 0)
+ {
+ if (persist)
+ ErrorF("[dix] Removing empty element from the valid list of fontpaths\n");
+ err = BadValue;
+ }
+ else
+ {
+ /* if it's already in our active list, just reset it */
+ /*
+ * note that this can miss FPE's in limbo -- may be worth catching
+ * them, though it'd muck up refcounting
+ */
+ fpe = find_existing_fpe(font_path_elements, num_fpes, cp, len);
+ if (fpe)
+ {
+ err = (*fpe_functions[fpe->type].reset_fpe) (fpe);
+ if (err == Successful)
+ {
+ UseFPE(fpe);/* since it'll be decref'd later when freed
+ * from the old list */
+ }
+ else
+ fpe = 0;
+ }
+ /* if error or can't do it, act like it's a new one */
+ if (!fpe)
+ {
+ fpe = xalloc(sizeof(FontPathElementRec));
+ if (!fpe)
+ {
+ err = BadAlloc;
+ goto bail;
+ }
+ fpe->name = xalloc(len + 1);
+ if (!fpe->name)
+ {
+ xfree(fpe);
+ err = BadAlloc;
+ goto bail;
+ }
+ fpe->refcount = 1;
+
+ strncpy(fpe->name, (char *) cp, (int) len);
+ fpe->name[len] = '\0';
+ fpe->name_length = len;
+ fpe->type = DetermineFPEType(fpe->name);
+ if (fpe->type == -1)
+ err = BadValue;
+ else
+ err = (*fpe_functions[fpe->type].init_fpe) (fpe);
+ if (err != Successful)
+ {
+ if (persist)
+ {
+ ErrorF("[dix] Could not init font path element %s, removing from list!\n",
+ fpe->name);
+ }
+ xfree (fpe->name);
+ xfree (fpe);
+ }
+ }
+ }
+ if (err != Successful)
+ {
+ if (!persist)
+ goto bail;
+ }
+ else
+ {
+ fplist[valid_paths++] = fpe;
+ }
+ cp += len;
+ }
+
+ FreeFontPath(font_path_elements, num_fpes, FALSE);
+ font_path_elements = fplist;
+ if (patternCache)
+ EmptyFontPatternCache(patternCache);
+ num_fpes = valid_paths;
+
+ return Success;
+bail:
+ *bad = i;
+ while (--valid_paths >= 0)
+ FreeFPE(fplist[valid_paths]);
+ xfree(fplist);
+ return FontToXError(err);
+}
+
+/* XXX -- do we need to pass error down to each renderer? */
+int
+SetFontPath(ClientPtr client, int npaths, unsigned char *paths, int *error)
+{
+ int err = XaceHook(XACE_SERVER_ACCESS, client, DixManageAccess);
+ if (err != Success)
+ return err;
+
+ if (npaths == 0) {
+ if (SetDefaultFontPath(defaultFontPath) != Success)
+ return BadValue;
+ } else {
+ err = SetFontPathElements(npaths, paths, error, FALSE);
+ }
+ return err;
+}
+
+int
+SetDefaultFontPath(char *path)
+{
+ char *temp_path,
+ *start,
+ *end;
+ unsigned char *cp,
+ *pp,
+ *nump,
+ *newpath;
+ int num = 1,
+ len,
+ err,
+ size = 0,
+ bad;
+
+ /* ensure temp_path contains "built-ins" */
+ start = path;
+ while (1) {
+ start = strstr(start, "built-ins");
+ if (start == NULL)
+ break;
+ end = start + strlen("built-ins");
+ if ((start == path || start[-1] == ',') && (!*end || *end == ','))
+ break;
+ start = end;
+ }
+ if (!start) {
+ temp_path = Xprintf("%s%sbuilt-ins", path, *path ? "," : "");
+ } else {
+ temp_path = Xstrdup(path);
+ }
+ if (!temp_path)
+ return BadAlloc;
+
+ /* get enough for string, plus values -- use up commas */
+ len = strlen(temp_path) + 1;
+ nump = cp = newpath = xalloc(len);
+ if (!newpath)
+ return BadAlloc;
+ pp = (unsigned char *) temp_path;
+ cp++;
+ while (*pp) {
+ if (*pp == ',') {
+ *nump = (unsigned char) size;
+ nump = cp++;
+ pp++;
+ num++;
+ size = 0;
+ } else {
+ *cp++ = *pp++;
+ size++;
+ }
+ }
+ *nump = (unsigned char) size;
+
+ err = SetFontPathElements(num, newpath, &bad, TRUE);
+
+ xfree(newpath);
+ xfree(temp_path);
+
+ return err;
+}
+
+int
+GetFontPath(ClientPtr client, int *count, int *length, unsigned char **result)
+{
+ int i;
+ unsigned char *c;
+ int len;
+ FontPathElementPtr fpe;
+
+ i = XaceHook(XACE_SERVER_ACCESS, client, DixGetAttrAccess);
+ if (i != Success)
+ return i;
+
+ len = 0;
+ for (i = 0; i < num_fpes; i++) {
+ fpe = font_path_elements[i];
+ len += fpe->name_length + 1;
+ }
+ font_path_string = (unsigned char *) xrealloc(font_path_string, len);
+ if (!font_path_string)
+ return BadAlloc;
+
+ c = font_path_string;
+ *length = 0;
+ for (i = 0; i < num_fpes; i++) {
+ fpe = font_path_elements[i];
+ *c = fpe->name_length;
+ *length += *c++;
+ memmove(c, fpe->name, fpe->name_length);
+ c += fpe->name_length;
+ }
+ *count = num_fpes;
+ *result = font_path_string;
+ return Success;
+}
+
+void
+DeleteClientFontStuff(ClientPtr client)
+{
+ int i;
+ FontPathElementPtr fpe;
+
+ for (i = 0; i < num_fpes; i++)
+ {
+ fpe = font_path_elements[i];
+ if (fpe_functions[fpe->type].client_died)
+ (*fpe_functions[fpe->type].client_died) ((pointer) client, fpe);
+ }
+}
+
+void
+InitFonts (void)
+{
+ patternCache = MakeFontPatternCache();
+
+ BuiltinRegisterFpeFunctions();
+ FontFileRegisterFpeFunctions();
+ fs_register_fpe_functions();
+}
+
+int
+GetDefaultPointSize (void)
+{
+ return 120;
+}
+
+
+FontResolutionPtr
+GetClientResolutions (int *num)
+{
+ static struct _FontResolution res;
+ ScreenPtr pScreen;
+
+ pScreen = screenInfo.screens[0];
+ res.x_resolution = (pScreen->width * 25.4) / pScreen->mmWidth;
+ /*
+ * XXX - we'll want this as long as bitmap instances are prevalent
+ so that we can match them from scalable fonts
+ */
+ if (res.x_resolution < 88)
+ res.x_resolution = 75;
+ else
+ res.x_resolution = 100;
+ res.y_resolution = (pScreen->height * 25.4) / pScreen->mmHeight;
+ if (res.y_resolution < 88)
+ res.y_resolution = 75;
+ else
+ res.y_resolution = 100;
+ res.point_size = 120;
+ *num = 1;
+ return &res;
+}
+
+/*
+ * returns the type index of the new fpe
+ *
+ * should be called (only once!) by each type of fpe when initialized
+ */
+
+int
+RegisterFPEFunctions(NameCheckFunc name_func,
+ InitFpeFunc init_func,
+ FreeFpeFunc free_func,
+ ResetFpeFunc reset_func,
+ OpenFontFunc open_func,
+ CloseFontFunc close_func,
+ ListFontsFunc list_func,
+ StartLfwiFunc start_lfwi_func,
+ NextLfwiFunc next_lfwi_func,
+ WakeupFpeFunc wakeup_func,
+ ClientDiedFunc client_died,
+ LoadGlyphsFunc load_glyphs,
+ StartLaFunc start_list_alias_func,
+ NextLaFunc next_list_alias_func,
+ SetPathFunc set_path_func)
+{
+ FPEFunctions *new;
+
+ /* grow the list */
+ new = (FPEFunctions *) xrealloc(fpe_functions,
+ (num_fpe_types + 1) * sizeof(FPEFunctions));
+ if (!new)
+ return -1;
+ fpe_functions = new;
+
+ fpe_functions[num_fpe_types].name_check = name_func;
+ fpe_functions[num_fpe_types].open_font = open_func;
+ fpe_functions[num_fpe_types].close_font = close_func;
+ fpe_functions[num_fpe_types].wakeup_fpe = wakeup_func;
+ fpe_functions[num_fpe_types].list_fonts = list_func;
+ fpe_functions[num_fpe_types].start_list_fonts_with_info =
+ start_lfwi_func;
+ fpe_functions[num_fpe_types].list_next_font_with_info =
+ next_lfwi_func;
+ fpe_functions[num_fpe_types].init_fpe = init_func;
+ fpe_functions[num_fpe_types].free_fpe = free_func;
+ fpe_functions[num_fpe_types].reset_fpe = reset_func;
+ fpe_functions[num_fpe_types].client_died = client_died;
+ fpe_functions[num_fpe_types].load_glyphs = load_glyphs;
+ fpe_functions[num_fpe_types].start_list_fonts_and_aliases =
+ start_list_alias_func;
+ fpe_functions[num_fpe_types].list_next_font_or_alias =
+ next_list_alias_func;
+ fpe_functions[num_fpe_types].set_path_hook = set_path_func;
+
+ return num_fpe_types++;
+}
+
+void
+FreeFonts(void)
+{
+ if (patternCache) {
+ FreeFontPatternCache(patternCache);
+ patternCache = 0;
+ }
+ FreeFontPath(font_path_elements, num_fpes, TRUE);
+ font_path_elements = 0;
+ num_fpes = 0;
+ xfree(fpe_functions);
+ num_fpe_types = 0;
+ fpe_functions = (FPEFunctions *) 0;
+}
+
+/* convenience functions for FS interface */
+
+FontPtr
+find_old_font(XID id)
+{
+ pointer pFont;
+ dixLookupResourceByType(&pFont, id, RT_NONE, serverClient, DixReadAccess);
+ return (FontPtr)pFont;
+}
+
+Font
+GetNewFontClientID(void)
+{
+ return FakeClientID(0);
+}
+
+int
+StoreFontClientFont(FontPtr pfont, Font id)
+{
+ return AddResource(id, RT_NONE, (pointer) pfont);
+}
+
+void
+DeleteFontClientID(Font id)
+{
+ FreeResource(id, RT_NONE);
+}
+
+int
+client_auth_generation(ClientPtr client)
+{
+ return 0;
+}
+
+static int fs_handlers_installed = 0;
+static unsigned int last_server_gen;
+
+int
+init_fs_handlers(FontPathElementPtr fpe, BlockHandlerProcPtr block_handler)
+{
+ /* if server has reset, make sure the b&w handlers are reinstalled */
+ if (last_server_gen < serverGeneration) {
+ last_server_gen = serverGeneration;
+ fs_handlers_installed = 0;
+ }
+ if (fs_handlers_installed == 0) {
+ if (!RegisterBlockAndWakeupHandlers(block_handler,
+ FontWakeup, (pointer) 0))
+ return AllocError;
+ fs_handlers_installed++;
+ }
+ QueueFontWakeup(fpe);
+ return Successful;
+}
+
+void
+remove_fs_handlers(FontPathElementPtr fpe, BlockHandlerProcPtr block_handler, Bool all)
+{
+ if (all) {
+ /* remove the handlers if no one else is using them */
+ if (--fs_handlers_installed == 0) {
+ RemoveBlockAndWakeupHandlers(block_handler, FontWakeup,
+ (pointer) 0);
+ }
+ }
+ RemoveFontWakeup(fpe);
+}
diff --git a/xorg-server/dix/getevents.c b/xorg-server/dix/getevents.c index 7ddf88bad..ea6aa1376 100644 --- a/xorg-server/dix/getevents.c +++ b/xorg-server/dix/getevents.c @@ -1,1190 +1,1198 @@ -/* - * Copyright © 2006 Nokia Corporation - * Copyright © 2006-2007 Daniel Stone - * Copyright © 2008 Red Hat, 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 (including the next - * paragraph) shall be included in all copies or substantial portions of the - * Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL - * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER - * DEALINGS IN THE SOFTWARE. - * - * Authors: Daniel Stone <daniel@fooishbar.org> - * Peter Hutterer <peter.hutterer@who-t.net> - */ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <X11/X.h> -#include <X11/keysym.h> -#include <X11/Xproto.h> - -#include "misc.h" -#include "resource.h" -#include "inputstr.h" -#include "scrnintstr.h" -#include "cursorstr.h" -#include "dixstruct.h" -#include "globals.h" -#include "dixevents.h" -#include "mipointer.h" -#include "eventstr.h" -#include "eventconvert.h" - -#include <X11/extensions/XKBproto.h> -#include "xkbsrv.h" - -#ifdef PANORAMIX -#include "panoramiX.h" -#include "panoramiXsrv.h" -#endif - -#include <X11/extensions/XI.h> -#include <X11/extensions/XIproto.h> -#include "exglobals.h" -#include "exevents.h" -#include "exglobals.h" -#include "extnsionst.h" -#include "listdev.h" /* for sizing up DeviceClassesChangedEvent */ - -/* Number of motion history events to store. */ -#define MOTION_HISTORY_SIZE 256 - -/* InputEventList is the container list for all input events generated by the - * DDX. The DDX is expected to call GetEventList() and then pass the list into - * Get{Pointer|Keyboard}Events. - */ -EventListPtr InputEventList = NULL; -int InputEventListLen = 0; - -int -GetEventList(EventListPtr* list) -{ - *list = InputEventList; - return InputEventListLen; -} - -/** - * Pick some arbitrary size for Xi motion history. - */ -int -GetMotionHistorySize(void) -{ - return MOTION_HISTORY_SIZE; -} - -void -set_key_down(DeviceIntPtr pDev, int key_code, int type) -{ - if (type == KEY_PROCESSED) - pDev->key->down[key_code >> 3] |= (1 << (key_code & 7)); - else - pDev->key->postdown[key_code >> 3] |= (1 << (key_code & 7)); -} - -void -set_key_up(DeviceIntPtr pDev, int key_code, int type) -{ - if (type == KEY_PROCESSED) - pDev->key->down[key_code >> 3] &= ~(1 << (key_code & 7)); - else - pDev->key->postdown[key_code >> 3] &= ~(1 << (key_code & 7)); -} - -Bool -key_is_down(DeviceIntPtr pDev, int key_code, int type) -{ - int ret = 0; - - if (type & KEY_PROCESSED) - ret |= !!(pDev->key->down[key_code >> 3] & (1 << (key_code & 7))); - else if (type & KEY_POSTED) - ret |= !!(pDev->key->postdown[key_code >> 3] & (1 << (key_code & 7))); - - return ret; -} - -static Bool -key_autorepeats(DeviceIntPtr pDev, int key_code) -{ - return !!(pDev->kbdfeed->ctrl.autoRepeats[key_code >> 3] & - (1 << (key_code & 7))); -} - -static void -init_event(DeviceIntPtr dev, DeviceEvent* event, Time ms) -{ - memset(event, 0, sizeof(DeviceEvent)); - event->header = ET_Internal; - event->length = sizeof(DeviceEvent); - event->time = ms; - event->deviceid = dev->id; - event->sourceid = dev->id; -} - -static void -init_raw(DeviceIntPtr dev, RawDeviceEvent *event, Time ms, int type, int detail) -{ - memset(event, 0, sizeof(RawDeviceEvent)); - event->header = ET_Internal; - event->length = sizeof(RawDeviceEvent); - event->type = ET_RawKeyPress - ET_KeyPress + type; - event->time = ms; - event->deviceid = dev->id; - event->sourceid = dev->id; - event->detail.button = detail; -} - -static void -set_raw_valuators(RawDeviceEvent *event, int first, int num, int *valuators, int32_t* data) -{ - int i; - for (i = first; i < first + num; i++) - SetBit(event->valuators.mask, i); - - memcpy(&data[first], valuators, num * sizeof(uint32_t)); -} - - -static void -set_valuators(DeviceIntPtr dev, DeviceEvent* event, int first_valuator, - int num_valuators, int *valuators) -{ - int i; - - for (i = first_valuator; i < first_valuator + num_valuators; i++) - { - SetBit(event->valuators.mask, i); - if (dev->valuator->mode == Absolute) - SetBit(event->valuators.mode, i); - event->valuators.data_frac[i] = - dev->last.remainder[i] * (1 << 16) * (1 << 16); - } - - memcpy(&event->valuators.data[first_valuator], - valuators, num_valuators * sizeof(uint32_t)); - -} - -void -CreateClassesChangedEvent(EventList* event, - DeviceIntPtr master, - DeviceIntPtr slave, - int type) -{ - int i; - DeviceChangedEvent *dce; - CARD32 ms = GetTimeInMillis(); - - dce = (DeviceChangedEvent*)event->event; - memset(dce, 0, sizeof(DeviceChangedEvent)); - dce->deviceid = slave->id; - dce->masterid = master->id; - dce->header = ET_Internal; - dce->length = sizeof(DeviceChangedEvent); - dce->type = ET_DeviceChanged; - dce->time = ms; - dce->flags = type; - dce->flags |= DEVCHANGE_SLAVE_SWITCH; - dce->sourceid = slave->id; - - if (slave->button) - { - dce->buttons.num_buttons = slave->button->numButtons; - for (i = 0; i < dce->buttons.num_buttons; i++) - dce->buttons.names[i] = slave->button->labels[i]; - } - if (slave->valuator) - { - dce->num_valuators = slave->valuator->numAxes; - for (i = 0; i < dce->num_valuators; i++) - { - dce->valuators[i].min = slave->valuator->axes[i].min_value; - dce->valuators[i].max = slave->valuator->axes[i].max_value; - dce->valuators[i].resolution = slave->valuator->axes[i].resolution; - /* This should, eventually, be a per-axis mode */ - dce->valuators[i].mode = slave->valuator->mode; - dce->valuators[i].name = slave->valuator->axes[i].label; - } - } - if (slave->key) - { - dce->keys.min_keycode = slave->key->xkbInfo->desc->min_key_code; - dce->keys.max_keycode = slave->key->xkbInfo->desc->max_key_code; - } -} - -/** - * Rescale the coord between the two axis ranges. - */ -static int -rescaleValuatorAxis(int coord, float remainder, float *remainder_return, AxisInfoPtr from, AxisInfoPtr to, - int defmax) -{ - int fmin = 0, tmin = 0, fmax = defmax, tmax = defmax, coord_return; - float value; - - if(from && from->min_value < from->max_value) { - fmin = from->min_value; - fmax = from->max_value; - } - if(to && to->min_value < to->max_value) { - tmin = to->min_value; - tmax = to->max_value; - } - - if(fmin == tmin && fmax == tmax) { - if (remainder_return) - *remainder_return = remainder; - return coord; - } - - if(fmax == fmin) { /* avoid division by 0 */ - if (remainder_return) - *remainder_return = 0.0; - return 0; - } - - value = (coord + remainder - fmin) * (tmax - tmin) / (fmax - fmin) + tmin; - coord_return = lroundf(value); - if (remainder_return) - *remainder_return = value - coord_return; - return coord_return; -} - -/** - * Update all coordinates when changing to a different SD - * to ensure that relative reporting will work as expected - * without loss of precision. - * - * pDev->last.valuators will be in absolute device coordinates after this - * function. - */ -static void -updateSlaveDeviceCoords(DeviceIntPtr master, DeviceIntPtr pDev) -{ - ScreenPtr scr = miPointerGetScreen(pDev); - int i; - DeviceIntPtr lastSlave; - - /* master->last.valuators[0]/[1] is in screen coords and the actual - * position of the pointer */ - pDev->last.valuators[0] = master->last.valuators[0]; - pDev->last.valuators[1] = master->last.valuators[1]; - - if (!pDev->valuator) - return; - - /* scale back to device coordinates */ - if(pDev->valuator->numAxes > 0) - pDev->last.valuators[0] = rescaleValuatorAxis(pDev->last.valuators[0], pDev->last.remainder[0], - &pDev->last.remainder[0], NULL, pDev->valuator->axes + 0, scr->width); - if(pDev->valuator->numAxes > 1) - pDev->last.valuators[1] = rescaleValuatorAxis(pDev->last.valuators[1], pDev->last.remainder[1], - &pDev->last.remainder[0], NULL, pDev->valuator->axes + 1, scr->height); - - /* calculate the other axis as well based on info from the old - * slave-device. If the old slave had less axes than this one, - * last.valuators is reset to 0. - */ - if ((lastSlave = master->last.slave) && lastSlave->valuator) { - for (i = 2; i < pDev->valuator->numAxes; i++) { - if (i >= lastSlave->valuator->numAxes) - pDev->last.valuators[i] = 0; - else - pDev->last.valuators[i] = - rescaleValuatorAxis(pDev->last.valuators[i], - pDev->last.remainder[i], - &pDev->last.remainder[i], - lastSlave->valuator->axes + i, - pDev->valuator->axes + i, 0); - } - } - -} - -/** - * Allocate the motion history buffer. - */ -void -AllocateMotionHistory(DeviceIntPtr pDev) -{ - int size; - if (pDev->valuator->motion) - xfree(pDev->valuator->motion); - - if (pDev->valuator->numMotionEvents < 1) - return; - - /* An MD must have a motion history size large enough to keep all - * potential valuators, plus the respective range of the valuators. - * 3 * INT32 for (min_val, max_val, curr_val)) - */ - if (IsMaster(pDev)) - size = sizeof(INT32) * 3 * MAX_VALUATORS; - else - size = sizeof(INT32) * pDev->valuator->numAxes; - - size += sizeof(Time); - - pDev->valuator->motion = xcalloc(pDev->valuator->numMotionEvents, size); - pDev->valuator->first_motion = 0; - pDev->valuator->last_motion = 0; - if (!pDev->valuator->motion) - ErrorF("[dix] %s: Failed to alloc motion history (%d bytes).\n", - pDev->name, size * pDev->valuator->numMotionEvents); -} - -/** - * Dump the motion history between start and stop into the supplied buffer. - * Only records the event for a given screen in theory, but in practice, we - * sort of ignore this. - * - * If core is set, we only generate x/y, in INT16, scaled to screen coords. - */ -int -GetMotionHistory(DeviceIntPtr pDev, xTimecoord **buff, unsigned long start, - unsigned long stop, ScreenPtr pScreen, BOOL core) -{ - char *ibuff = NULL, *obuff; - int i = 0, ret = 0; - int j, coord; - Time current; - /* The size of a single motion event. */ - int size; - int dflt; - AxisInfo from, *to; /* for scaling */ - INT32 *ocbuf, *icbuf; /* pointer to coordinates for copying */ - INT16 *corebuf; - AxisInfo core_axis = {0}; - - if (!pDev->valuator || !pDev->valuator->numMotionEvents) - return 0; - - if (core && !pScreen) - return 0; - - if (IsMaster(pDev)) - size = (sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(Time); - else - size = (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time); - - *buff = xalloc(size * pDev->valuator->numMotionEvents); - if (!(*buff)) - return 0; - obuff = (char *)*buff; - - for (i = pDev->valuator->first_motion; - i != pDev->valuator->last_motion; - i = (i + 1) % pDev->valuator->numMotionEvents) { - /* We index the input buffer by which element we're accessing, which - * is not monotonic, and the output buffer by how many events we've - * written so far. */ - ibuff = (char *) pDev->valuator->motion + (i * size); - memcpy(¤t, ibuff, sizeof(Time)); - - if (current > stop) { - return ret; - } - else if (current >= start) { - if (core) - { - memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */ - - icbuf = (INT32*)(ibuff + sizeof(Time)); - corebuf = (INT16*)(obuff + sizeof(Time)); - - /* fetch x coordinate + range */ - memcpy(&from.min_value, icbuf++, sizeof(INT32)); - memcpy(&from.max_value, icbuf++, sizeof(INT32)); - memcpy(&coord, icbuf++, sizeof(INT32)); - - /* scale to screen coords */ - to = &core_axis; - to->max_value = pScreen->width; - coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, pScreen->width); - - memcpy(corebuf, &coord, sizeof(INT16)); - corebuf++; - - /* fetch y coordinate + range */ - memcpy(&from.min_value, icbuf++, sizeof(INT32)); - memcpy(&from.max_value, icbuf++, sizeof(INT32)); - memcpy(&coord, icbuf++, sizeof(INT32)); - - to->max_value = pScreen->height; - coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, pScreen->height); - memcpy(corebuf, &coord, sizeof(INT16)); - - } else if (IsMaster(pDev)) - { - memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */ - - ocbuf = (INT32*)(obuff + sizeof(Time)); - icbuf = (INT32*)(ibuff + sizeof(Time)); - for (j = 0; j < MAX_VALUATORS; j++) - { - if (j >= pDev->valuator->numAxes) - break; - - /* fetch min/max/coordinate */ - memcpy(&from.min_value, icbuf++, sizeof(INT32)); - memcpy(&from.max_value, icbuf++, sizeof(INT32)); - memcpy(&coord, icbuf++, sizeof(INT32)); - - to = (j < pDev->valuator->numAxes) ? &pDev->valuator->axes[j] : NULL; - - /* x/y scaled to screen if no range is present */ - if (j == 0 && (from.max_value < from.min_value)) - from.max_value = pScreen->width; - else if (j == 1 && (from.max_value < from.min_value)) - from.max_value = pScreen->height; - - if (j == 0 && (to->max_value < to->min_value)) - dflt = pScreen->width; - else if (j == 1 && (to->max_value < to->min_value)) - dflt = pScreen->height; - else - dflt = 0; - - /* scale from stored range into current range */ - coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, 0); - memcpy(ocbuf, &coord, sizeof(INT32)); - ocbuf++; - } - } else - memcpy(obuff, ibuff, size); - - /* don't advance by size here. size may be different to the - * actually written size if the MD has less valuators than MAX */ - if (core) - obuff += sizeof(INT32) + sizeof(Time); - else - obuff += (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time); - ret++; - } - } - - return ret; -} - - -/** - * Update the motion history for a specific device, with the list of - * valuators. - * - * Layout of the history buffer: - * for SDs: [time] [val0] [val1] ... [valn] - * for MDs: [time] [min_val0] [max_val0] [val0] [min_val1] ... [valn] - * - * For events that have some valuators unset (first_valuator > 0): - * min_val == max_val == val == 0. - */ -static void -updateMotionHistory(DeviceIntPtr pDev, CARD32 ms, int first_valuator, - int num_valuators, int *valuators) -{ - char *buff = (char *) pDev->valuator->motion; - ValuatorClassPtr v; - int i; - - if (!pDev->valuator->numMotionEvents) - return; - - v = pDev->valuator; - if (IsMaster(pDev)) - { - buff += ((sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(CARD32)) * - v->last_motion; - - memcpy(buff, &ms, sizeof(Time)); - buff += sizeof(Time); - - memset(buff, 0, sizeof(INT32) * 3 * MAX_VALUATORS); - buff += 3 * sizeof(INT32) * first_valuator; - - for (i = first_valuator; i < first_valuator + num_valuators; i++) - { - if (i >= v->numAxes) - break; - memcpy(buff, &v->axes[i].min_value, sizeof(INT32)); - buff += sizeof(INT32); - memcpy(buff, &v->axes[i].max_value, sizeof(INT32)); - buff += sizeof(INT32); - memcpy(buff, &valuators[i - first_valuator], sizeof(INT32)); - buff += sizeof(INT32); - } - } else - { - - buff += ((sizeof(INT32) * pDev->valuator->numAxes) + sizeof(CARD32)) * - pDev->valuator->last_motion; - - memcpy(buff, &ms, sizeof(Time)); - buff += sizeof(Time); - - memset(buff, 0, sizeof(INT32) * pDev->valuator->numAxes); - buff += sizeof(INT32) * first_valuator; - - memcpy(buff, valuators, sizeof(INT32) * num_valuators); - } - - pDev->valuator->last_motion = (pDev->valuator->last_motion + 1) % - pDev->valuator->numMotionEvents; - /* If we're wrapping around, just keep the circular buffer going. */ - if (pDev->valuator->first_motion == pDev->valuator->last_motion) - pDev->valuator->first_motion = (pDev->valuator->first_motion + 1) % - pDev->valuator->numMotionEvents; - - return; -} - - -/** - * Returns the maximum number of events GetKeyboardEvents, - * GetKeyboardValuatorEvents, and GetPointerEvents will ever return. - * - * This MUST be absolutely constant, from init until exit. - */ -int -GetMaximumEventsNum(void) { - /* One raw event - * One device event - * One possible device changed event - */ - return 3; -} - - -/** - * Clip an axis to its bounds, which are declared in the call to - * InitValuatorAxisClassStruct. - */ -static void -clipAxis(DeviceIntPtr pDev, int axisNum, int *val) -{ - AxisInfoPtr axis = pDev->valuator->axes + axisNum; - /* InitValuatoraAxisStruct ensures that (min < max). */ - - if (axisNum >= pDev->valuator->numAxes) - return; - - /* If a value range is defined, clip. If not, do nothing */ - if (axis->max_value <= axis->min_value) - return; - - if (*val < axis->min_value) - *val = axis->min_value; - if (*val > axis->max_value) - *val = axis->max_value; -} - -/** - * Clip every axis in the list of valuators to its bounds. - */ -static void -clipValuators(DeviceIntPtr pDev, int first_valuator, int num_valuators, - int *valuators) -{ - int i; - - for (i = 0; i < num_valuators; i++) - clipAxis(pDev, i + first_valuator, &(valuators[i])); -} - -/** - * Create the DCCE event (does not update the master's device state yet, this - * is done in the event processing). - * Pull in the coordinates from the MD if necessary. - * - * @param events Pointer to a pre-allocated event list. - * @param dev The slave device that generated an event. - * @param type Either DEVCHANGE_POINTER_EVENT and/or DEVCHANGE_KEYBOARD_EVENT - * @param num_events The current number of events, returns the number of - * events if a DCCE was generated. - * @return The updated @events pointer. - */ -static EventListPtr -updateFromMaster(EventListPtr events, DeviceIntPtr dev, int type, int *num_events) -{ - DeviceIntPtr master; - - master = GetMaster(dev, (type & DEVCHANGE_POINTER_EVENT) ? MASTER_POINTER : MASTER_KEYBOARD); - - if (master && master->last.slave != dev) - { - CreateClassesChangedEvent(events, master, dev, type); - updateSlaveDeviceCoords(master, dev); - master->last.slave = dev; - master->last.numValuators = dev->last.numValuators; - (*num_events)++; - events++; - } - return events; -} - -/** - * Move the device's pointer to the position given in the valuators. - * - * @param dev The device which's pointer is to be moved. - * @param x Returns the x position of the pointer after the move. - * @param y Returns the y position of the pointer after the move. - * @param first The first valuator in @valuators - * @param num Total number of valuators in @valuators. - * @param valuators Valuator data for each axis between @first and - * @first+@num. - */ -static void -moveAbsolute(DeviceIntPtr dev, int *x, int *y, - int first, int num, int *valuators) -{ - int i; - - - if (num >= 1 && first == 0) - *x = *(valuators + 0); - else - *x = dev->last.valuators[0]; - - if (first <= 1 && num >= (2 - first)) - *y = *(valuators + 1 - first); - else - *y = dev->last.valuators[1]; - - clipAxis(dev, 0, x); - clipAxis(dev, 1, y); - - i = (first > 2) ? 0 : 2; - for (; i < num; i++) - { - dev->last.valuators[i + first] = valuators[i]; - clipAxis(dev, i, &dev->last.valuators[i + first]); - } -} - -/** - * Move the device's pointer by the values given in @valuators. - * - * @param dev The device which's pointer is to be moved. - * @param x Returns the x position of the pointer after the move. - * @param y Returns the y position of the pointer after the move. - * @param first The first valuator in @valuators - * @param num Total number of valuators in @valuators. - * @param valuators Valuator data for each axis between @first and - * @first+@num. - */ -static void -moveRelative(DeviceIntPtr dev, int *x, int *y, - int first, int num, int *valuators) -{ - int i; - - *x = dev->last.valuators[0]; - *y = dev->last.valuators[1]; - - if (num >= 1 && first == 0) - *x += *(valuators +0); - - if (first <= 1 && num >= (2 - first)) - *y += *(valuators + 1 - first); - - /* if attached, clip both x and y to the defined limits (usually - * co-ord space limit). If it is attached, we need x/y to go over the - * limits to be able to change screens. */ - if(dev->u.master) { - clipAxis(dev, 0, x); - clipAxis(dev, 1, y); - } - - /* calc other axes, clip, drop back into valuators */ - i = (first > 2) ? 0 : 2; - for (; i < num; i++) - { - dev->last.valuators[i + first] += valuators[i]; - clipAxis(dev, i, &dev->last.valuators[i + first]); - valuators[i] = dev->last.valuators[i + first]; - } -} - -/** - * Accelerate the data in valuators based on the device's acceleration scheme. - * - * @param dev The device which's pointer is to be moved. - * @param first The first valuator in @valuators - * @param num Total number of valuators in @valuators. - * @param valuators Valuator data for each axis between @first and - * @first+@num. - * @param ms Current time. - */ -static void -accelPointer(DeviceIntPtr dev, int first, int num, int *valuators, CARD32 ms) -{ - if (dev->valuator->accelScheme.AccelSchemeProc) - dev->valuator->accelScheme.AccelSchemeProc(dev, first, num, valuators, ms); -} - -/** - * If we have HW cursors, this actually moves the visible sprite. If not, we - * just do all the screen crossing, etc. - * - * We scale from device to screen coordinates here, call - * miPointerSetPosition() and then scale back into device coordinates (if - * needed). miPSP will change x/y if the screen was crossed. - * - * @param dev The device to be moved. - * @param x Pointer to current x-axis value, may be modified. - * @param y Pointer to current y-axis value, may be modified. - * @param x_frac Fractional part of current x-axis value, may be modified. - * @param y_frac Fractional part of current y-axis value, may be modified. - * @param scr Screen the device's sprite is currently on. - * @param screenx Screen x coordinate the sprite is on after the update. - * @param screeny Screen y coordinate the sprite is on after the update. - * @param screenx_frac Fractional part of screen x coordinate, as above. - * @param screeny_frac Fractional part of screen y coordinate, as above. - */ -static void -positionSprite(DeviceIntPtr dev, int *x, int *y, float x_frac, float y_frac, - ScreenPtr scr, int *screenx, int *screeny, float *screenx_frac, float *screeny_frac) -{ - int old_screenx, old_screeny; - - /* scale x&y to screen */ - if (dev->valuator->numAxes > 0) { - *screenx = rescaleValuatorAxis(*x, x_frac, screenx_frac, - dev->valuator->axes + 0, NULL, scr->width); - } else { - *screenx = dev->last.valuators[0]; - *screenx_frac = dev->last.remainder[0]; - } - - if (dev->valuator->numAxes > 1) { - *screeny = rescaleValuatorAxis(*y, y_frac, screeny_frac, - dev->valuator->axes + 1, NULL, scr->height); - } else { - *screeny = dev->last.valuators[1]; - *screeny_frac = dev->last.remainder[1]; - } - - old_screenx = *screenx; - old_screeny = *screeny; - /* This takes care of crossing screens for us, as well as clipping - * to the current screen. */ - miPointerSetPosition(dev, screenx, screeny); - - if (dev->u.master) { - dev->u.master->last.valuators[0] = *screenx; - dev->u.master->last.valuators[1] = *screeny; - dev->u.master->last.remainder[0] = *screenx_frac; - dev->u.master->last.remainder[1] = *screeny_frac; - } - - /* Crossed screen? Scale back to device coordiantes */ - if(*screenx != old_screenx) - { - scr = miPointerGetScreen(dev); - *x = rescaleValuatorAxis(*screenx, *screenx_frac, &x_frac, NULL, - dev->valuator->axes + 0, scr->width); - } - if(*screeny != old_screeny) - { - scr = miPointerGetScreen(dev); - *y = rescaleValuatorAxis(*screeny, *screeny_frac, &y_frac, NULL, - dev->valuator->axes + 1, scr->height); - } - - /* dropy x/y (device coordinates) back into valuators for next event */ - dev->last.valuators[0] = *x; - dev->last.valuators[1] = *y; - dev->last.remainder[0] = x_frac; - dev->last.remainder[1] = y_frac; -} - -/** - * Update the motion history for the device and (if appropriate) for its - * master device. - * @param dev Slave device to update. - * @param first First valuator to append to history. - * @param num Total number of valuators to append to history. - * @param ms Current time - */ -static void -updateHistory(DeviceIntPtr dev, int first, int num, CARD32 ms) -{ - updateMotionHistory(dev, ms, first, num, &dev->last.valuators[first]); - if (dev->u.master) - { - DeviceIntPtr master = GetMaster(dev, MASTER_POINTER); - updateMotionHistory(master, ms, first, num, &dev->last.valuators[first]); - } -} - -/** - * Convenience wrapper around GetKeyboardValuatorEvents, that takes no - * valuators. - */ -int -GetKeyboardEvents(EventList *events, DeviceIntPtr pDev, int type, int key_code) { - return GetKeyboardValuatorEvents(events, pDev, type, key_code, 0, 0, NULL); -} - - -/** - * Returns a set of keyboard events for KeyPress/KeyRelease, optionally - * also with valuator events. Handles Xi and XKB. - * - * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the - * event (ProcessOtherEvent). - * - * events is not NULL-terminated; the return value is the number of events. - * The DDX is responsible for allocating the event structure in the first - * place via GetMaximumEventsNum(), and for freeing it. - * - * This function does not change the core keymap to that of the device; - * that is done by SwitchCoreKeyboard, which is called from - * mieqProcessInputEvents. If replacing that function, take care to call - * SetCoreKeyboard before processInputProc, so keymaps are altered to suit. - */ -int -GetKeyboardValuatorEvents(EventList *events, DeviceIntPtr pDev, int type, - int key_code, int first_valuator, - int num_valuators, int *valuators) { - int num_events = 0; - CARD32 ms = 0; - DeviceEvent *event; - RawDeviceEvent *raw; - - /* refuse events from disabled devices */ - if (!pDev->enabled) - return 0; - - if (!events ||!pDev->key || !pDev->focus || !pDev->kbdfeed || - (type != KeyPress && type != KeyRelease) || - (key_code < 8 || key_code > 255)) - return 0; - - num_events = 1; - - events = updateFromMaster(events, pDev, DEVCHANGE_KEYBOARD_EVENT, &num_events); - - /* Handle core repeating, via press/release/press/release. */ - if (type == KeyPress && key_is_down(pDev, key_code, KEY_POSTED)) { - /* If autorepeating is disabled either globally or just for that key, - * or we have a modifier, don't generate a repeat event. */ - if (!pDev->kbdfeed->ctrl.autoRepeat || - !key_autorepeats(pDev, key_code) || - pDev->key->xkbInfo->desc->map->modmap[key_code]) - return 0; - } - - ms = GetTimeInMillis(); - - raw = (RawDeviceEvent*)events->event; - events++; - num_events++; - - init_raw(pDev, raw, ms, type, key_code); - set_raw_valuators(raw, first_valuator, num_valuators, valuators, - raw->valuators.data_raw); - - if (num_valuators) - clipValuators(pDev, first_valuator, num_valuators, valuators); - - set_raw_valuators(raw, first_valuator, num_valuators, valuators, - raw->valuators.data); - - event = (DeviceEvent*) events->event; - init_event(pDev, event, ms); - event->detail.key = key_code; - - if (type == KeyPress) { - event->type = ET_KeyPress; - set_key_down(pDev, key_code, KEY_POSTED); - } - else if (type == KeyRelease) { - event->type = ET_KeyRelease; - set_key_up(pDev, key_code, KEY_POSTED); - } - - if (num_valuators) - clipValuators(pDev, first_valuator, num_valuators, valuators); - - set_valuators(pDev, event, first_valuator, num_valuators, valuators); - - return num_events; -} - -/** - * Initialize an event list and fill with 32 byte sized events. - * This event list is to be passed into GetPointerEvents() and - * GetKeyboardEvents(). - * - * @param num_events Number of elements in list. - */ -EventListPtr -InitEventList(int num_events) -{ - EventListPtr events; - int i; - - events = (EventListPtr)xcalloc(num_events, sizeof(EventList)); - if (!events) - return NULL; - - for (i = 0; i < num_events; i++) - { - events[i].evlen = sizeof(InternalEvent); - events[i].event = xcalloc(1, sizeof(InternalEvent)); - if (!events[i].event) - { - /* rollback */ - while(i--) - xfree(events[i].event); - xfree(events); - events = NULL; - break; - } - } - - return events; -} - -/** - * Free an event list. - * - * @param list The list to be freed. - * @param num_events Number of elements in list. - */ -void -FreeEventList(EventListPtr list, int num_events) -{ - if (!list) - return; - while(num_events--) - xfree(list[num_events].event); - xfree(list); -} - -/** - * Generate a series of xEvents (filled into the EventList) representing - * pointer motion, or button presses. Xi and XKB-aware. - * - * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the - * event (ProcessOtherEvent). - * - * events is not NULL-terminated; the return value is the number of events. - * The DDX is responsible for allocating the event structure in the first - * place via InitEventList() and GetMaximumEventsNum(), and for freeing it. - * - * In the generated events rootX/Y will be in absolute screen coords and - * the valuator information in the absolute or relative device coords. - * - * last.valuators[x] of the device is always in absolute device coords. - * last.valuators[x] of the master device is in absolute screen coords. - * - * master->last.valuators[x] for x > 2 is undefined. - */ -int -GetPointerEvents(EventList *events, DeviceIntPtr pDev, int type, int buttons, - int flags, int first_valuator, int num_valuators, - int *valuators) { - int num_events = 1; - CARD32 ms; - DeviceEvent *event; - RawDeviceEvent *raw; - int x = 0, y = 0, /* device coords */ - cx, cy; /* only screen coordinates */ - float x_frac = 0.0, y_frac = 0.0, cx_frac, cy_frac; - ScreenPtr scr = miPointerGetScreen(pDev); - - /* refuse events from disabled devices */ - if (!pDev->enabled) - return 0; - - ms = GetTimeInMillis(); /* before pointer update to help precision */ - - if (!scr || !pDev->valuator || first_valuator < 0 || - ((num_valuators + first_valuator) > pDev->valuator->numAxes) || - (type != MotionNotify && type != ButtonPress && type != ButtonRelease) || - (type != MotionNotify && !pDev->button) || - ((type == ButtonPress || type == ButtonRelease) && !buttons) || - (type == MotionNotify && num_valuators <= 0)) - return 0; - - events = updateFromMaster(events, pDev, DEVCHANGE_POINTER_EVENT, &num_events); - - raw = (RawDeviceEvent*)events->event; - events++; - num_events++; - - init_raw(pDev, raw, ms, type, buttons); - set_raw_valuators(raw, first_valuator, num_valuators, valuators, - raw->valuators.data_raw); - - if (flags & POINTER_ABSOLUTE) - { - if (flags & POINTER_SCREEN) /* valuators are in screen coords */ - { - - if (num_valuators >= 1 && first_valuator == 0) - valuators[0] = rescaleValuatorAxis(valuators[0], 0.0, &x_frac, NULL, - pDev->valuator->axes + 0, - scr->width); - if (first_valuator <= 1 && num_valuators >= (2 - first_valuator)) - valuators[1 - first_valuator] = rescaleValuatorAxis(valuators[1 - first_valuator], 0.0, &y_frac, NULL, - pDev->valuator->axes + 1, - scr->height); - } - - moveAbsolute(pDev, &x, &y, first_valuator, num_valuators, valuators); - } else { - if (flags & POINTER_ACCELERATE) { - accelPointer(pDev, first_valuator, num_valuators, valuators, ms); - /* The pointer acceleration code modifies the fractional part - * in-place, so we need to extract this information first */ - x_frac = pDev->last.remainder[0]; - y_frac = pDev->last.remainder[1]; - } - moveRelative(pDev, &x, &y, first_valuator, num_valuators, valuators); - } - - set_raw_valuators(raw, first_valuator, num_valuators, valuators, - raw->valuators.data); - - positionSprite(pDev, &x, &y, x_frac, y_frac, scr, &cx, &cy, &cx_frac, &cy_frac); - updateHistory(pDev, first_valuator, num_valuators, ms); - - /* Update the valuators with the true value sent to the client*/ - if (num_valuators >= 1 && first_valuator == 0) - valuators[0] = x; - if (first_valuator <= 1 && num_valuators >= (2 - first_valuator)) - valuators[1 - first_valuator] = y; - - if (num_valuators) - clipValuators(pDev, first_valuator, num_valuators, valuators); - - event = (DeviceEvent*) events->event; - init_event(pDev, event, ms); - - if (type == MotionNotify) { - event->type = ET_Motion; - event->detail.button = 0; - } - else { - if (type == ButtonPress) { - event->type = ET_ButtonPress; - pDev->button->postdown[buttons >> 3] |= (1 << (buttons & 7)); - } - else if (type == ButtonRelease) { - event->type = ET_ButtonRelease; - pDev->button->postdown[buttons >> 3] &= ~(1 << (buttons & 7)); - } - event->detail.button = buttons; - } - - event->root_x = cx; /* root_x/y always in screen coords */ - event->root_y = cy; - event->root_x_frac = cx_frac; - event->root_y_frac = cy_frac; - - set_valuators(pDev, event, first_valuator, num_valuators, valuators); - - return num_events; -} - - -/** - * Post ProximityIn/ProximityOut events, accompanied by valuators. - * - * events is not NULL-terminated; the return value is the number of events. - * The DDX is responsible for allocating the event structure in the first - * place via GetMaximumEventsNum(), and for freeing it. - */ -int -GetProximityEvents(EventList *events, DeviceIntPtr pDev, int type, - int first_valuator, int num_valuators, int *valuators) -{ - int num_events = 1; - DeviceEvent *event; - - /* refuse events from disabled devices */ - if (!pDev->enabled) - return 0; - - /* Sanity checks. */ - if (type != ProximityIn && type != ProximityOut) - return 0; - if (!pDev->valuator) - return 0; - /* Do we need to send a DeviceValuator event? */ - if ((pDev->valuator->mode & 1) == Relative) - num_valuators = 0; - - /* You fail. */ - if (first_valuator < 0 || - (num_valuators + first_valuator) > pDev->valuator->numAxes) - return 0; - - events = updateFromMaster(events, pDev, DEVCHANGE_POINTER_EVENT, &num_events); - - event = (DeviceEvent *) events->event; - init_event(pDev, event, GetTimeInMillis()); - event->type = (type == ProximityIn) ? ET_ProximityIn : ET_ProximityOut; - - if (num_valuators) - clipValuators(pDev, first_valuator, num_valuators, valuators); - - set_valuators(pDev, event, first_valuator, num_valuators, valuators); - - return num_events; -} - -/** - * Synthesize a single motion event for the core pointer. - * - * Used in cursor functions, e.g. when cursor confinement changes, and we need - * to shift the pointer to get it inside the new bounds. - */ -void -PostSyntheticMotion(DeviceIntPtr pDev, - int x, - int y, - int screen, - unsigned long time) -{ - DeviceEvent ev; - -#ifdef PANORAMIX - /* Translate back to the sprite screen since processInputProc - will translate from sprite screen to screen 0 upon reentry - to the DIX layer. */ - if (!noPanoramiXExtension) { - x += panoramiXdataPtr[0].x - panoramiXdataPtr[screen].x; - y += panoramiXdataPtr[0].y - panoramiXdataPtr[screen].y; - } -#endif - - memset(&ev, 0, sizeof(DeviceEvent)); - init_event(pDev, &ev, time); - ev.root_x = x; - ev.root_y = y; - ev.type = ET_Motion; - ev.time = time; - - /* FIXME: MD/SD considerations? */ - (*pDev->public.processInputProc)((InternalEvent*)&ev, pDev); -} +/*
+ * Copyright © 2006 Nokia Corporation
+ * Copyright © 2006-2007 Daniel Stone
+ * Copyright © 2008 Red Hat, 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 (including the next
+ * paragraph) shall be included in all copies or substantial portions of the
+ * Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+ * DEALINGS IN THE SOFTWARE.
+ *
+ * Authors: Daniel Stone <daniel@fooishbar.org>
+ * Peter Hutterer <peter.hutterer@who-t.net>
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <X11/X.h>
+#include <X11/keysym.h>
+#include <X11/Xproto.h>
+
+#include "misc.h"
+#include "resource.h"
+#include "inputstr.h"
+#include "scrnintstr.h"
+#include "cursorstr.h"
+#include "dixstruct.h"
+#include "globals.h"
+#include "dixevents.h"
+#include "mipointer.h"
+#include "eventstr.h"
+#include "eventconvert.h"
+
+#include <X11/extensions/XKBproto.h>
+#include "xkbsrv.h"
+
+#ifdef PANORAMIX
+#include "panoramiX.h"
+#include "panoramiXsrv.h"
+#endif
+
+#include <X11/extensions/XI.h>
+#include <X11/extensions/XIproto.h>
+#include "exglobals.h"
+#include "exevents.h"
+#include "exglobals.h"
+#include "extnsionst.h"
+#include "listdev.h" /* for sizing up DeviceClassesChangedEvent */
+
+#ifdef _MSC_VER
+float roundf(float f)
+{
+ return ((f<0.0f) ? ceil(f-.5) : floor (f+.5));
+}
+#define lroundf(val) ((int)roundf(val))
+#endif
+
+/* Number of motion history events to store. */
+#define MOTION_HISTORY_SIZE 256
+
+/* InputEventList is the container list for all input events generated by the
+ * DDX. The DDX is expected to call GetEventList() and then pass the list into
+ * Get{Pointer|Keyboard}Events.
+ */
+EventListPtr InputEventList = NULL;
+int InputEventListLen = 0;
+
+int
+GetEventList(EventListPtr* list)
+{
+ *list = InputEventList;
+ return InputEventListLen;
+}
+
+/**
+ * Pick some arbitrary size for Xi motion history.
+ */
+int
+GetMotionHistorySize(void)
+{
+ return MOTION_HISTORY_SIZE;
+}
+
+void
+set_key_down(DeviceIntPtr pDev, int key_code, int type)
+{
+ if (type == KEY_PROCESSED)
+ pDev->key->down[key_code >> 3] |= (1 << (key_code & 7));
+ else
+ pDev->key->postdown[key_code >> 3] |= (1 << (key_code & 7));
+}
+
+void
+set_key_up(DeviceIntPtr pDev, int key_code, int type)
+{
+ if (type == KEY_PROCESSED)
+ pDev->key->down[key_code >> 3] &= ~(1 << (key_code & 7));
+ else
+ pDev->key->postdown[key_code >> 3] &= ~(1 << (key_code & 7));
+}
+
+Bool
+key_is_down(DeviceIntPtr pDev, int key_code, int type)
+{
+ int ret = 0;
+
+ if (type & KEY_PROCESSED)
+ ret |= !!(pDev->key->down[key_code >> 3] & (1 << (key_code & 7)));
+ else if (type & KEY_POSTED)
+ ret |= !!(pDev->key->postdown[key_code >> 3] & (1 << (key_code & 7)));
+
+ return ret;
+}
+
+static Bool
+key_autorepeats(DeviceIntPtr pDev, int key_code)
+{
+ return !!(pDev->kbdfeed->ctrl.autoRepeats[key_code >> 3] &
+ (1 << (key_code & 7)));
+}
+
+static void
+init_event(DeviceIntPtr dev, DeviceEvent* event, Time ms)
+{
+ memset(event, 0, sizeof(DeviceEvent));
+ event->header = ET_Internal;
+ event->length = sizeof(DeviceEvent);
+ event->time = ms;
+ event->deviceid = dev->id;
+ event->sourceid = dev->id;
+}
+
+static void
+init_raw(DeviceIntPtr dev, RawDeviceEvent *event, Time ms, int type, int detail)
+{
+ memset(event, 0, sizeof(RawDeviceEvent));
+ event->header = ET_Internal;
+ event->length = sizeof(RawDeviceEvent);
+ event->type = ET_RawKeyPress - ET_KeyPress + type;
+ event->time = ms;
+ event->deviceid = dev->id;
+ event->sourceid = dev->id;
+ event->detail.button = detail;
+}
+
+static void
+set_raw_valuators(RawDeviceEvent *event, int first, int num, int *valuators, int32_t* data)
+{
+ int i;
+ for (i = first; i < first + num; i++)
+ SetBit(event->valuators.mask, i);
+
+ memcpy(&data[first], valuators, num * sizeof(uint32_t));
+}
+
+
+static void
+set_valuators(DeviceIntPtr dev, DeviceEvent* event, int first_valuator,
+ int num_valuators, int *valuators)
+{
+ int i;
+
+ for (i = first_valuator; i < first_valuator + num_valuators; i++)
+ {
+ SetBit(event->valuators.mask, i);
+ if (dev->valuator->mode == Absolute)
+ SetBit(event->valuators.mode, i);
+ event->valuators.data_frac[i] =
+ dev->last.remainder[i] * (1 << 16) * (1 << 16);
+ }
+
+ memcpy(&event->valuators.data[first_valuator],
+ valuators, num_valuators * sizeof(uint32_t));
+
+}
+
+void
+CreateClassesChangedEvent(EventList* event,
+ DeviceIntPtr master,
+ DeviceIntPtr slave,
+ int type)
+{
+ int i;
+ DeviceChangedEvent *dce;
+ CARD32 ms = GetTimeInMillis();
+
+ dce = (DeviceChangedEvent*)event->event;
+ memset(dce, 0, sizeof(DeviceChangedEvent));
+ dce->deviceid = slave->id;
+ dce->masterid = master->id;
+ dce->header = ET_Internal;
+ dce->length = sizeof(DeviceChangedEvent);
+ dce->type = ET_DeviceChanged;
+ dce->time = ms;
+ dce->flags = type;
+ dce->flags |= DEVCHANGE_SLAVE_SWITCH;
+ dce->sourceid = slave->id;
+
+ if (slave->button)
+ {
+ dce->buttons.num_buttons = slave->button->numButtons;
+ for (i = 0; i < dce->buttons.num_buttons; i++)
+ dce->buttons.names[i] = slave->button->labels[i];
+ }
+ if (slave->valuator)
+ {
+ dce->num_valuators = slave->valuator->numAxes;
+ for (i = 0; i < dce->num_valuators; i++)
+ {
+ dce->valuators[i].min = slave->valuator->axes[i].min_value;
+ dce->valuators[i].max = slave->valuator->axes[i].max_value;
+ dce->valuators[i].resolution = slave->valuator->axes[i].resolution;
+ /* This should, eventually, be a per-axis mode */
+ dce->valuators[i].mode = slave->valuator->mode;
+ dce->valuators[i].name = slave->valuator->axes[i].label;
+ }
+ }
+ if (slave->key)
+ {
+ dce->keys.min_keycode = slave->key->xkbInfo->desc->min_key_code;
+ dce->keys.max_keycode = slave->key->xkbInfo->desc->max_key_code;
+ }
+}
+
+/**
+ * Rescale the coord between the two axis ranges.
+ */
+static int
+rescaleValuatorAxis(int coord, float remainder, float *remainder_return, AxisInfoPtr from, AxisInfoPtr to,
+ int defmax)
+{
+ int fmin = 0, tmin = 0, fmax = defmax, tmax = defmax, coord_return;
+ float value;
+
+ if(from && from->min_value < from->max_value) {
+ fmin = from->min_value;
+ fmax = from->max_value;
+ }
+ if(to && to->min_value < to->max_value) {
+ tmin = to->min_value;
+ tmax = to->max_value;
+ }
+
+ if(fmin == tmin && fmax == tmax) {
+ if (remainder_return)
+ *remainder_return = remainder;
+ return coord;
+ }
+
+ if(fmax == fmin) { /* avoid division by 0 */
+ if (remainder_return)
+ *remainder_return = 0.0;
+ return 0;
+ }
+
+ value = (coord + remainder - fmin) * (tmax - tmin) / (fmax - fmin) + tmin;
+ coord_return = lroundf(value);
+ if (remainder_return)
+ *remainder_return = value - coord_return;
+ return coord_return;
+}
+
+/**
+ * Update all coordinates when changing to a different SD
+ * to ensure that relative reporting will work as expected
+ * without loss of precision.
+ *
+ * pDev->last.valuators will be in absolute device coordinates after this
+ * function.
+ */
+static void
+updateSlaveDeviceCoords(DeviceIntPtr master, DeviceIntPtr pDev)
+{
+ ScreenPtr scr = miPointerGetScreen(pDev);
+ int i;
+ DeviceIntPtr lastSlave;
+
+ /* master->last.valuators[0]/[1] is in screen coords and the actual
+ * position of the pointer */
+ pDev->last.valuators[0] = master->last.valuators[0];
+ pDev->last.valuators[1] = master->last.valuators[1];
+
+ if (!pDev->valuator)
+ return;
+
+ /* scale back to device coordinates */
+ if(pDev->valuator->numAxes > 0)
+ pDev->last.valuators[0] = rescaleValuatorAxis(pDev->last.valuators[0], pDev->last.remainder[0],
+ &pDev->last.remainder[0], NULL, pDev->valuator->axes + 0, scr->width);
+ if(pDev->valuator->numAxes > 1)
+ pDev->last.valuators[1] = rescaleValuatorAxis(pDev->last.valuators[1], pDev->last.remainder[1],
+ &pDev->last.remainder[0], NULL, pDev->valuator->axes + 1, scr->height);
+
+ /* calculate the other axis as well based on info from the old
+ * slave-device. If the old slave had less axes than this one,
+ * last.valuators is reset to 0.
+ */
+ if ((lastSlave = master->last.slave) && lastSlave->valuator) {
+ for (i = 2; i < pDev->valuator->numAxes; i++) {
+ if (i >= lastSlave->valuator->numAxes)
+ pDev->last.valuators[i] = 0;
+ else
+ pDev->last.valuators[i] =
+ rescaleValuatorAxis(pDev->last.valuators[i],
+ pDev->last.remainder[i],
+ &pDev->last.remainder[i],
+ lastSlave->valuator->axes + i,
+ pDev->valuator->axes + i, 0);
+ }
+ }
+
+}
+
+/**
+ * Allocate the motion history buffer.
+ */
+void
+AllocateMotionHistory(DeviceIntPtr pDev)
+{
+ int size;
+ if (pDev->valuator->motion)
+ xfree(pDev->valuator->motion);
+
+ if (pDev->valuator->numMotionEvents < 1)
+ return;
+
+ /* An MD must have a motion history size large enough to keep all
+ * potential valuators, plus the respective range of the valuators.
+ * 3 * INT32 for (min_val, max_val, curr_val))
+ */
+ if (IsMaster(pDev))
+ size = sizeof(INT32) * 3 * MAX_VALUATORS;
+ else
+ size = sizeof(INT32) * pDev->valuator->numAxes;
+
+ size += sizeof(Time);
+
+ pDev->valuator->motion = xcalloc(pDev->valuator->numMotionEvents, size);
+ pDev->valuator->first_motion = 0;
+ pDev->valuator->last_motion = 0;
+ if (!pDev->valuator->motion)
+ ErrorF("[dix] %s: Failed to alloc motion history (%d bytes).\n",
+ pDev->name, size * pDev->valuator->numMotionEvents);
+}
+
+/**
+ * Dump the motion history between start and stop into the supplied buffer.
+ * Only records the event for a given screen in theory, but in practice, we
+ * sort of ignore this.
+ *
+ * If core is set, we only generate x/y, in INT16, scaled to screen coords.
+ */
+int
+GetMotionHistory(DeviceIntPtr pDev, xTimecoord **buff, unsigned long start,
+ unsigned long stop, ScreenPtr pScreen, BOOL core)
+{
+ char *ibuff = NULL, *obuff;
+ int i = 0, ret = 0;
+ int j, coord;
+ Time current;
+ /* The size of a single motion event. */
+ int size;
+ int dflt;
+ AxisInfo from, *to; /* for scaling */
+ INT32 *ocbuf, *icbuf; /* pointer to coordinates for copying */
+ INT16 *corebuf;
+ AxisInfo core_axis = {0};
+
+ if (!pDev->valuator || !pDev->valuator->numMotionEvents)
+ return 0;
+
+ if (core && !pScreen)
+ return 0;
+
+ if (IsMaster(pDev))
+ size = (sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(Time);
+ else
+ size = (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time);
+
+ *buff = xalloc(size * pDev->valuator->numMotionEvents);
+ if (!(*buff))
+ return 0;
+ obuff = (char *)*buff;
+
+ for (i = pDev->valuator->first_motion;
+ i != pDev->valuator->last_motion;
+ i = (i + 1) % pDev->valuator->numMotionEvents) {
+ /* We index the input buffer by which element we're accessing, which
+ * is not monotonic, and the output buffer by how many events we've
+ * written so far. */
+ ibuff = (char *) pDev->valuator->motion + (i * size);
+ memcpy(¤t, ibuff, sizeof(Time));
+
+ if (current > stop) {
+ return ret;
+ }
+ else if (current >= start) {
+ if (core)
+ {
+ memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */
+
+ icbuf = (INT32*)(ibuff + sizeof(Time));
+ corebuf = (INT16*)(obuff + sizeof(Time));
+
+ /* fetch x coordinate + range */
+ memcpy(&from.min_value, icbuf++, sizeof(INT32));
+ memcpy(&from.max_value, icbuf++, sizeof(INT32));
+ memcpy(&coord, icbuf++, sizeof(INT32));
+
+ /* scale to screen coords */
+ to = &core_axis;
+ to->max_value = pScreen->width;
+ coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, pScreen->width);
+
+ memcpy(corebuf, &coord, sizeof(INT16));
+ corebuf++;
+
+ /* fetch y coordinate + range */
+ memcpy(&from.min_value, icbuf++, sizeof(INT32));
+ memcpy(&from.max_value, icbuf++, sizeof(INT32));
+ memcpy(&coord, icbuf++, sizeof(INT32));
+
+ to->max_value = pScreen->height;
+ coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, pScreen->height);
+ memcpy(corebuf, &coord, sizeof(INT16));
+
+ } else if (IsMaster(pDev))
+ {
+ memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */
+
+ ocbuf = (INT32*)(obuff + sizeof(Time));
+ icbuf = (INT32*)(ibuff + sizeof(Time));
+ for (j = 0; j < MAX_VALUATORS; j++)
+ {
+ if (j >= pDev->valuator->numAxes)
+ break;
+
+ /* fetch min/max/coordinate */
+ memcpy(&from.min_value, icbuf++, sizeof(INT32));
+ memcpy(&from.max_value, icbuf++, sizeof(INT32));
+ memcpy(&coord, icbuf++, sizeof(INT32));
+
+ to = (j < pDev->valuator->numAxes) ? &pDev->valuator->axes[j] : NULL;
+
+ /* x/y scaled to screen if no range is present */
+ if (j == 0 && (from.max_value < from.min_value))
+ from.max_value = pScreen->width;
+ else if (j == 1 && (from.max_value < from.min_value))
+ from.max_value = pScreen->height;
+
+ if (j == 0 && (to->max_value < to->min_value))
+ dflt = pScreen->width;
+ else if (j == 1 && (to->max_value < to->min_value))
+ dflt = pScreen->height;
+ else
+ dflt = 0;
+
+ /* scale from stored range into current range */
+ coord = rescaleValuatorAxis(coord, 0.0, NULL, &from, to, 0);
+ memcpy(ocbuf, &coord, sizeof(INT32));
+ ocbuf++;
+ }
+ } else
+ memcpy(obuff, ibuff, size);
+
+ /* don't advance by size here. size may be different to the
+ * actually written size if the MD has less valuators than MAX */
+ if (core)
+ obuff += sizeof(INT32) + sizeof(Time);
+ else
+ obuff += (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time);
+ ret++;
+ }
+ }
+
+ return ret;
+}
+
+
+/**
+ * Update the motion history for a specific device, with the list of
+ * valuators.
+ *
+ * Layout of the history buffer:
+ * for SDs: [time] [val0] [val1] ... [valn]
+ * for MDs: [time] [min_val0] [max_val0] [val0] [min_val1] ... [valn]
+ *
+ * For events that have some valuators unset (first_valuator > 0):
+ * min_val == max_val == val == 0.
+ */
+static void
+updateMotionHistory(DeviceIntPtr pDev, CARD32 ms, int first_valuator,
+ int num_valuators, int *valuators)
+{
+ char *buff = (char *) pDev->valuator->motion;
+ ValuatorClassPtr v;
+ int i;
+
+ if (!pDev->valuator->numMotionEvents)
+ return;
+
+ v = pDev->valuator;
+ if (IsMaster(pDev))
+ {
+ buff += ((sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(CARD32)) *
+ v->last_motion;
+
+ memcpy(buff, &ms, sizeof(Time));
+ buff += sizeof(Time);
+
+ memset(buff, 0, sizeof(INT32) * 3 * MAX_VALUATORS);
+ buff += 3 * sizeof(INT32) * first_valuator;
+
+ for (i = first_valuator; i < first_valuator + num_valuators; i++)
+ {
+ if (i >= v->numAxes)
+ break;
+ memcpy(buff, &v->axes[i].min_value, sizeof(INT32));
+ buff += sizeof(INT32);
+ memcpy(buff, &v->axes[i].max_value, sizeof(INT32));
+ buff += sizeof(INT32);
+ memcpy(buff, &valuators[i - first_valuator], sizeof(INT32));
+ buff += sizeof(INT32);
+ }
+ } else
+ {
+
+ buff += ((sizeof(INT32) * pDev->valuator->numAxes) + sizeof(CARD32)) *
+ pDev->valuator->last_motion;
+
+ memcpy(buff, &ms, sizeof(Time));
+ buff += sizeof(Time);
+
+ memset(buff, 0, sizeof(INT32) * pDev->valuator->numAxes);
+ buff += sizeof(INT32) * first_valuator;
+
+ memcpy(buff, valuators, sizeof(INT32) * num_valuators);
+ }
+
+ pDev->valuator->last_motion = (pDev->valuator->last_motion + 1) %
+ pDev->valuator->numMotionEvents;
+ /* If we're wrapping around, just keep the circular buffer going. */
+ if (pDev->valuator->first_motion == pDev->valuator->last_motion)
+ pDev->valuator->first_motion = (pDev->valuator->first_motion + 1) %
+ pDev->valuator->numMotionEvents;
+
+ return;
+}
+
+
+/**
+ * Returns the maximum number of events GetKeyboardEvents,
+ * GetKeyboardValuatorEvents, and GetPointerEvents will ever return.
+ *
+ * This MUST be absolutely constant, from init until exit.
+ */
+int
+GetMaximumEventsNum(void) {
+ /* One raw event
+ * One device event
+ * One possible device changed event
+ */
+ return 3;
+}
+
+
+/**
+ * Clip an axis to its bounds, which are declared in the call to
+ * InitValuatorAxisClassStruct.
+ */
+static void
+clipAxis(DeviceIntPtr pDev, int axisNum, int *val)
+{
+ AxisInfoPtr axis = pDev->valuator->axes + axisNum;
+ /* InitValuatoraAxisStruct ensures that (min < max). */
+
+ if (axisNum >= pDev->valuator->numAxes)
+ return;
+
+ /* If a value range is defined, clip. If not, do nothing */
+ if (axis->max_value <= axis->min_value)
+ return;
+
+ if (*val < axis->min_value)
+ *val = axis->min_value;
+ if (*val > axis->max_value)
+ *val = axis->max_value;
+}
+
+/**
+ * Clip every axis in the list of valuators to its bounds.
+ */
+static void
+clipValuators(DeviceIntPtr pDev, int first_valuator, int num_valuators,
+ int *valuators)
+{
+ int i;
+
+ for (i = 0; i < num_valuators; i++)
+ clipAxis(pDev, i + first_valuator, &(valuators[i]));
+}
+
+/**
+ * Create the DCCE event (does not update the master's device state yet, this
+ * is done in the event processing).
+ * Pull in the coordinates from the MD if necessary.
+ *
+ * @param events Pointer to a pre-allocated event list.
+ * @param dev The slave device that generated an event.
+ * @param type Either DEVCHANGE_POINTER_EVENT and/or DEVCHANGE_KEYBOARD_EVENT
+ * @param num_events The current number of events, returns the number of
+ * events if a DCCE was generated.
+ * @return The updated @events pointer.
+ */
+static EventListPtr
+updateFromMaster(EventListPtr events, DeviceIntPtr dev, int type, int *num_events)
+{
+ DeviceIntPtr master;
+
+ master = GetMaster(dev, (type & DEVCHANGE_POINTER_EVENT) ? MASTER_POINTER : MASTER_KEYBOARD);
+
+ if (master && master->last.slave != dev)
+ {
+ CreateClassesChangedEvent(events, master, dev, type);
+ updateSlaveDeviceCoords(master, dev);
+ master->last.slave = dev;
+ master->last.numValuators = dev->last.numValuators;
+ (*num_events)++;
+ events++;
+ }
+ return events;
+}
+
+/**
+ * Move the device's pointer to the position given in the valuators.
+ *
+ * @param dev The device which's pointer is to be moved.
+ * @param x Returns the x position of the pointer after the move.
+ * @param y Returns the y position of the pointer after the move.
+ * @param first The first valuator in @valuators
+ * @param num Total number of valuators in @valuators.
+ * @param valuators Valuator data for each axis between @first and
+ * @first+@num.
+ */
+static void
+moveAbsolute(DeviceIntPtr dev, int *x, int *y,
+ int first, int num, int *valuators)
+{
+ int i;
+
+
+ if (num >= 1 && first == 0)
+ *x = *(valuators + 0);
+ else
+ *x = dev->last.valuators[0];
+
+ if (first <= 1 && num >= (2 - first))
+ *y = *(valuators + 1 - first);
+ else
+ *y = dev->last.valuators[1];
+
+ clipAxis(dev, 0, x);
+ clipAxis(dev, 1, y);
+
+ i = (first > 2) ? 0 : 2;
+ for (; i < num; i++)
+ {
+ dev->last.valuators[i + first] = valuators[i];
+ clipAxis(dev, i, &dev->last.valuators[i + first]);
+ }
+}
+
+/**
+ * Move the device's pointer by the values given in @valuators.
+ *
+ * @param dev The device which's pointer is to be moved.
+ * @param x Returns the x position of the pointer after the move.
+ * @param y Returns the y position of the pointer after the move.
+ * @param first The first valuator in @valuators
+ * @param num Total number of valuators in @valuators.
+ * @param valuators Valuator data for each axis between @first and
+ * @first+@num.
+ */
+static void
+moveRelative(DeviceIntPtr dev, int *x, int *y,
+ int first, int num, int *valuators)
+{
+ int i;
+
+ *x = dev->last.valuators[0];
+ *y = dev->last.valuators[1];
+
+ if (num >= 1 && first == 0)
+ *x += *(valuators +0);
+
+ if (first <= 1 && num >= (2 - first))
+ *y += *(valuators + 1 - first);
+
+ /* if attached, clip both x and y to the defined limits (usually
+ * co-ord space limit). If it is attached, we need x/y to go over the
+ * limits to be able to change screens. */
+ if(dev->u.master) {
+ clipAxis(dev, 0, x);
+ clipAxis(dev, 1, y);
+ }
+
+ /* calc other axes, clip, drop back into valuators */
+ i = (first > 2) ? 0 : 2;
+ for (; i < num; i++)
+ {
+ dev->last.valuators[i + first] += valuators[i];
+ clipAxis(dev, i, &dev->last.valuators[i + first]);
+ valuators[i] = dev->last.valuators[i + first];
+ }
+}
+
+/**
+ * Accelerate the data in valuators based on the device's acceleration scheme.
+ *
+ * @param dev The device which's pointer is to be moved.
+ * @param first The first valuator in @valuators
+ * @param num Total number of valuators in @valuators.
+ * @param valuators Valuator data for each axis between @first and
+ * @first+@num.
+ * @param ms Current time.
+ */
+static void
+accelPointer(DeviceIntPtr dev, int first, int num, int *valuators, CARD32 ms)
+{
+ if (dev->valuator->accelScheme.AccelSchemeProc)
+ dev->valuator->accelScheme.AccelSchemeProc(dev, first, num, valuators, ms);
+}
+
+/**
+ * If we have HW cursors, this actually moves the visible sprite. If not, we
+ * just do all the screen crossing, etc.
+ *
+ * We scale from device to screen coordinates here, call
+ * miPointerSetPosition() and then scale back into device coordinates (if
+ * needed). miPSP will change x/y if the screen was crossed.
+ *
+ * @param dev The device to be moved.
+ * @param x Pointer to current x-axis value, may be modified.
+ * @param y Pointer to current y-axis value, may be modified.
+ * @param x_frac Fractional part of current x-axis value, may be modified.
+ * @param y_frac Fractional part of current y-axis value, may be modified.
+ * @param scr Screen the device's sprite is currently on.
+ * @param screenx Screen x coordinate the sprite is on after the update.
+ * @param screeny Screen y coordinate the sprite is on after the update.
+ * @param screenx_frac Fractional part of screen x coordinate, as above.
+ * @param screeny_frac Fractional part of screen y coordinate, as above.
+ */
+static void
+positionSprite(DeviceIntPtr dev, int *x, int *y, float x_frac, float y_frac,
+ ScreenPtr scr, int *screenx, int *screeny, float *screenx_frac, float *screeny_frac)
+{
+ int old_screenx, old_screeny;
+
+ /* scale x&y to screen */
+ if (dev->valuator->numAxes > 0) {
+ *screenx = rescaleValuatorAxis(*x, x_frac, screenx_frac,
+ dev->valuator->axes + 0, NULL, scr->width);
+ } else {
+ *screenx = dev->last.valuators[0];
+ *screenx_frac = dev->last.remainder[0];
+ }
+
+ if (dev->valuator->numAxes > 1) {
+ *screeny = rescaleValuatorAxis(*y, y_frac, screeny_frac,
+ dev->valuator->axes + 1, NULL, scr->height);
+ } else {
+ *screeny = dev->last.valuators[1];
+ *screeny_frac = dev->last.remainder[1];
+ }
+
+ old_screenx = *screenx;
+ old_screeny = *screeny;
+ /* This takes care of crossing screens for us, as well as clipping
+ * to the current screen. */
+ miPointerSetPosition(dev, screenx, screeny);
+
+ if (dev->u.master) {
+ dev->u.master->last.valuators[0] = *screenx;
+ dev->u.master->last.valuators[1] = *screeny;
+ dev->u.master->last.remainder[0] = *screenx_frac;
+ dev->u.master->last.remainder[1] = *screeny_frac;
+ }
+
+ /* Crossed screen? Scale back to device coordiantes */
+ if(*screenx != old_screenx)
+ {
+ scr = miPointerGetScreen(dev);
+ *x = rescaleValuatorAxis(*screenx, *screenx_frac, &x_frac, NULL,
+ dev->valuator->axes + 0, scr->width);
+ }
+ if(*screeny != old_screeny)
+ {
+ scr = miPointerGetScreen(dev);
+ *y = rescaleValuatorAxis(*screeny, *screeny_frac, &y_frac, NULL,
+ dev->valuator->axes + 1, scr->height);
+ }
+
+ /* dropy x/y (device coordinates) back into valuators for next event */
+ dev->last.valuators[0] = *x;
+ dev->last.valuators[1] = *y;
+ dev->last.remainder[0] = x_frac;
+ dev->last.remainder[1] = y_frac;
+}
+
+/**
+ * Update the motion history for the device and (if appropriate) for its
+ * master device.
+ * @param dev Slave device to update.
+ * @param first First valuator to append to history.
+ * @param num Total number of valuators to append to history.
+ * @param ms Current time
+ */
+static void
+updateHistory(DeviceIntPtr dev, int first, int num, CARD32 ms)
+{
+ updateMotionHistory(dev, ms, first, num, &dev->last.valuators[first]);
+ if (dev->u.master)
+ {
+ DeviceIntPtr master = GetMaster(dev, MASTER_POINTER);
+ updateMotionHistory(master, ms, first, num, &dev->last.valuators[first]);
+ }
+}
+
+/**
+ * Convenience wrapper around GetKeyboardValuatorEvents, that takes no
+ * valuators.
+ */
+int
+GetKeyboardEvents(EventList *events, DeviceIntPtr pDev, int type, int key_code) {
+ return GetKeyboardValuatorEvents(events, pDev, type, key_code, 0, 0, NULL);
+}
+
+
+/**
+ * Returns a set of keyboard events for KeyPress/KeyRelease, optionally
+ * also with valuator events. Handles Xi and XKB.
+ *
+ * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the
+ * event (ProcessOtherEvent).
+ *
+ * events is not NULL-terminated; the return value is the number of events.
+ * The DDX is responsible for allocating the event structure in the first
+ * place via GetMaximumEventsNum(), and for freeing it.
+ *
+ * This function does not change the core keymap to that of the device;
+ * that is done by SwitchCoreKeyboard, which is called from
+ * mieqProcessInputEvents. If replacing that function, take care to call
+ * SetCoreKeyboard before processInputProc, so keymaps are altered to suit.
+ */
+int
+GetKeyboardValuatorEvents(EventList *events, DeviceIntPtr pDev, int type,
+ int key_code, int first_valuator,
+ int num_valuators, int *valuators) {
+ int num_events = 0;
+ CARD32 ms = 0;
+ DeviceEvent *event;
+ RawDeviceEvent *raw;
+
+ /* refuse events from disabled devices */
+ if (!pDev->enabled)
+ return 0;
+
+ if (!events ||!pDev->key || !pDev->focus || !pDev->kbdfeed ||
+ (type != KeyPress && type != KeyRelease) ||
+ (key_code < 8 || key_code > 255))
+ return 0;
+
+ num_events = 1;
+
+ events = updateFromMaster(events, pDev, DEVCHANGE_KEYBOARD_EVENT, &num_events);
+
+ /* Handle core repeating, via press/release/press/release. */
+ if (type == KeyPress && key_is_down(pDev, key_code, KEY_POSTED)) {
+ /* If autorepeating is disabled either globally or just for that key,
+ * or we have a modifier, don't generate a repeat event. */
+ if (!pDev->kbdfeed->ctrl.autoRepeat ||
+ !key_autorepeats(pDev, key_code) ||
+ pDev->key->xkbInfo->desc->map->modmap[key_code])
+ return 0;
+ }
+
+ ms = GetTimeInMillis();
+
+ raw = (RawDeviceEvent*)events->event;
+ events++;
+ num_events++;
+
+ init_raw(pDev, raw, ms, type, key_code);
+ set_raw_valuators(raw, first_valuator, num_valuators, valuators,
+ raw->valuators.data_raw);
+
+ if (num_valuators)
+ clipValuators(pDev, first_valuator, num_valuators, valuators);
+
+ set_raw_valuators(raw, first_valuator, num_valuators, valuators,
+ raw->valuators.data);
+
+ event = (DeviceEvent*) events->event;
+ init_event(pDev, event, ms);
+ event->detail.key = key_code;
+
+ if (type == KeyPress) {
+ event->type = ET_KeyPress;
+ set_key_down(pDev, key_code, KEY_POSTED);
+ }
+ else if (type == KeyRelease) {
+ event->type = ET_KeyRelease;
+ set_key_up(pDev, key_code, KEY_POSTED);
+ }
+
+ if (num_valuators)
+ clipValuators(pDev, first_valuator, num_valuators, valuators);
+
+ set_valuators(pDev, event, first_valuator, num_valuators, valuators);
+
+ return num_events;
+}
+
+/**
+ * Initialize an event list and fill with 32 byte sized events.
+ * This event list is to be passed into GetPointerEvents() and
+ * GetKeyboardEvents().
+ *
+ * @param num_events Number of elements in list.
+ */
+EventListPtr
+InitEventList(int num_events)
+{
+ EventListPtr events;
+ int i;
+
+ events = (EventListPtr)xcalloc(num_events, sizeof(EventList));
+ if (!events)
+ return NULL;
+
+ for (i = 0; i < num_events; i++)
+ {
+ events[i].evlen = sizeof(InternalEvent);
+ events[i].event = xcalloc(1, sizeof(InternalEvent));
+ if (!events[i].event)
+ {
+ /* rollback */
+ while(i--)
+ xfree(events[i].event);
+ xfree(events);
+ events = NULL;
+ break;
+ }
+ }
+
+ return events;
+}
+
+/**
+ * Free an event list.
+ *
+ * @param list The list to be freed.
+ * @param num_events Number of elements in list.
+ */
+void
+FreeEventList(EventListPtr list, int num_events)
+{
+ if (!list)
+ return;
+ while(num_events--)
+ xfree(list[num_events].event);
+ xfree(list);
+}
+
+/**
+ * Generate a series of xEvents (filled into the EventList) representing
+ * pointer motion, or button presses. Xi and XKB-aware.
+ *
+ * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the
+ * event (ProcessOtherEvent).
+ *
+ * events is not NULL-terminated; the return value is the number of events.
+ * The DDX is responsible for allocating the event structure in the first
+ * place via InitEventList() and GetMaximumEventsNum(), and for freeing it.
+ *
+ * In the generated events rootX/Y will be in absolute screen coords and
+ * the valuator information in the absolute or relative device coords.
+ *
+ * last.valuators[x] of the device is always in absolute device coords.
+ * last.valuators[x] of the master device is in absolute screen coords.
+ *
+ * master->last.valuators[x] for x > 2 is undefined.
+ */
+int
+GetPointerEvents(EventList *events, DeviceIntPtr pDev, int type, int buttons,
+ int flags, int first_valuator, int num_valuators,
+ int *valuators) {
+ int num_events = 1;
+ CARD32 ms;
+ DeviceEvent *event;
+ RawDeviceEvent *raw;
+ int x = 0, y = 0, /* device coords */
+ cx, cy; /* only screen coordinates */
+ float x_frac = 0.0, y_frac = 0.0, cx_frac, cy_frac;
+ ScreenPtr scr = miPointerGetScreen(pDev);
+
+ /* refuse events from disabled devices */
+ if (!pDev->enabled)
+ return 0;
+
+ ms = GetTimeInMillis(); /* before pointer update to help precision */
+
+ if (!scr || !pDev->valuator || first_valuator < 0 ||
+ ((num_valuators + first_valuator) > pDev->valuator->numAxes) ||
+ (type != MotionNotify && type != ButtonPress && type != ButtonRelease) ||
+ (type != MotionNotify && !pDev->button) ||
+ ((type == ButtonPress || type == ButtonRelease) && !buttons) ||
+ (type == MotionNotify && num_valuators <= 0))
+ return 0;
+
+ events = updateFromMaster(events, pDev, DEVCHANGE_POINTER_EVENT, &num_events);
+
+ raw = (RawDeviceEvent*)events->event;
+ events++;
+ num_events++;
+
+ init_raw(pDev, raw, ms, type, buttons);
+ set_raw_valuators(raw, first_valuator, num_valuators, valuators,
+ raw->valuators.data_raw);
+
+ if (flags & POINTER_ABSOLUTE)
+ {
+ if (flags & POINTER_SCREEN) /* valuators are in screen coords */
+ {
+
+ if (num_valuators >= 1 && first_valuator == 0)
+ valuators[0] = rescaleValuatorAxis(valuators[0], 0.0, &x_frac, NULL,
+ pDev->valuator->axes + 0,
+ scr->width);
+ if (first_valuator <= 1 && num_valuators >= (2 - first_valuator))
+ valuators[1 - first_valuator] = rescaleValuatorAxis(valuators[1 - first_valuator], 0.0, &y_frac, NULL,
+ pDev->valuator->axes + 1,
+ scr->height);
+ }
+
+ moveAbsolute(pDev, &x, &y, first_valuator, num_valuators, valuators);
+ } else {
+ if (flags & POINTER_ACCELERATE) {
+ accelPointer(pDev, first_valuator, num_valuators, valuators, ms);
+ /* The pointer acceleration code modifies the fractional part
+ * in-place, so we need to extract this information first */
+ x_frac = pDev->last.remainder[0];
+ y_frac = pDev->last.remainder[1];
+ }
+ moveRelative(pDev, &x, &y, first_valuator, num_valuators, valuators);
+ }
+
+ set_raw_valuators(raw, first_valuator, num_valuators, valuators,
+ raw->valuators.data);
+
+ positionSprite(pDev, &x, &y, x_frac, y_frac, scr, &cx, &cy, &cx_frac, &cy_frac);
+ updateHistory(pDev, first_valuator, num_valuators, ms);
+
+ /* Update the valuators with the true value sent to the client*/
+ if (num_valuators >= 1 && first_valuator == 0)
+ valuators[0] = x;
+ if (first_valuator <= 1 && num_valuators >= (2 - first_valuator))
+ valuators[1 - first_valuator] = y;
+
+ if (num_valuators)
+ clipValuators(pDev, first_valuator, num_valuators, valuators);
+
+ event = (DeviceEvent*) events->event;
+ init_event(pDev, event, ms);
+
+ if (type == MotionNotify) {
+ event->type = ET_Motion;
+ event->detail.button = 0;
+ }
+ else {
+ if (type == ButtonPress) {
+ event->type = ET_ButtonPress;
+ pDev->button->postdown[buttons >> 3] |= (1 << (buttons & 7));
+ }
+ else if (type == ButtonRelease) {
+ event->type = ET_ButtonRelease;
+ pDev->button->postdown[buttons >> 3] &= ~(1 << (buttons & 7));
+ }
+ event->detail.button = buttons;
+ }
+
+ event->root_x = cx; /* root_x/y always in screen coords */
+ event->root_y = cy;
+ event->root_x_frac = cx_frac;
+ event->root_y_frac = cy_frac;
+
+ set_valuators(pDev, event, first_valuator, num_valuators, valuators);
+
+ return num_events;
+}
+
+
+/**
+ * Post ProximityIn/ProximityOut events, accompanied by valuators.
+ *
+ * events is not NULL-terminated; the return value is the number of events.
+ * The DDX is responsible for allocating the event structure in the first
+ * place via GetMaximumEventsNum(), and for freeing it.
+ */
+int
+GetProximityEvents(EventList *events, DeviceIntPtr pDev, int type,
+ int first_valuator, int num_valuators, int *valuators)
+{
+ int num_events = 1;
+ DeviceEvent *event;
+
+ /* refuse events from disabled devices */
+ if (!pDev->enabled)
+ return 0;
+
+ /* Sanity checks. */
+ if (type != ProximityIn && type != ProximityOut)
+ return 0;
+ if (!pDev->valuator)
+ return 0;
+ /* Do we need to send a DeviceValuator event? */
+ if ((pDev->valuator->mode & 1) == Relative)
+ num_valuators = 0;
+
+ /* You fail. */
+ if (first_valuator < 0 ||
+ (num_valuators + first_valuator) > pDev->valuator->numAxes)
+ return 0;
+
+ events = updateFromMaster(events, pDev, DEVCHANGE_POINTER_EVENT, &num_events);
+
+ event = (DeviceEvent *) events->event;
+ init_event(pDev, event, GetTimeInMillis());
+ event->type = (type == ProximityIn) ? ET_ProximityIn : ET_ProximityOut;
+
+ if (num_valuators)
+ clipValuators(pDev, first_valuator, num_valuators, valuators);
+
+ set_valuators(pDev, event, first_valuator, num_valuators, valuators);
+
+ return num_events;
+}
+
+/**
+ * Synthesize a single motion event for the core pointer.
+ *
+ * Used in cursor functions, e.g. when cursor confinement changes, and we need
+ * to shift the pointer to get it inside the new bounds.
+ */
+void
+PostSyntheticMotion(DeviceIntPtr pDev,
+ int x,
+ int y,
+ int screen,
+ unsigned long time)
+{
+ DeviceEvent ev;
+
+#ifdef PANORAMIX
+ /* Translate back to the sprite screen since processInputProc
+ will translate from sprite screen to screen 0 upon reentry
+ to the DIX layer. */
+ if (!noPanoramiXExtension) {
+ x += panoramiXdataPtr[0].x - panoramiXdataPtr[screen].x;
+ y += panoramiXdataPtr[0].y - panoramiXdataPtr[screen].y;
+ }
+#endif
+
+ memset(&ev, 0, sizeof(DeviceEvent));
+ init_event(pDev, &ev, time);
+ ev.root_x = x;
+ ev.root_y = y;
+ ev.type = ET_Motion;
+ ev.time = time;
+
+ /* FIXME: MD/SD considerations? */
+ (*pDev->public.processInputProc)((InternalEvent*)&ev, pDev);
+}
diff --git a/xorg-server/dix/main.c b/xorg-server/dix/main.c index f96245a4b..24aa7b6c0 100644 --- a/xorg-server/dix/main.c +++ b/xorg-server/dix/main.c @@ -116,6 +116,10 @@ Equipment Corporation. #include "dpmsproc.h" #endif +#ifdef _DEBUG +#include <crtdbg.h> +#endif + extern void Dispatch(void); extern void InitProcVectors(void); @@ -134,9 +138,29 @@ int main(int argc, char *argv[], char *envp[]) { int i; HWEventQueueType alwaysCheckForInput[2]; - + #ifdef _DEBUG + //int TmpFlag=_CrtSetDbgFlag( _CRTDBG_REPORT_FLAG); + + //TmpFlag|=_CRTDBG_ALLOC_MEM_DF; + //TmpFlag|=_CRTDBG_DELAY_FREE_MEM_DF; + //TmpFlag|=_CRTDBG_CHECK_ALWAYS_DF; + //TmpFlag|=_CRTDBG_CHECK_CRT_DF; + //TmpFlag|=_CRTDBG_LEAK_CHECK_DF; + + //_CrtSetDbgFlag(TmpFlag); + #endif + + ptw32_processInitialize(); display = "0"; + #ifdef WIN32 + /* In Win32 we have different threads call Xlib functions (depending + on the commandline options given). + XInitThreads has to be called before + any xlib function is called (aoccording to the man page) */ + XInitThreads(); + #endif + InitRegions(); pixman_disable_out_of_bounds_workaround(); @@ -307,6 +331,7 @@ int main(int argc, char *argv[], char *envp[]) memset(WindowTable, 0, sizeof(WindowTable)); CloseDownDevices(); + InputDevicesClosed(); CloseDownEvents(); for (i = screenInfo.numScreens - 1; i >= 0; i--) diff --git a/xorg-server/dix/makefile b/xorg-server/dix/makefile new file mode 100644 index 000000000..4abd48a32 --- /dev/null +++ b/xorg-server/dix/makefile @@ -0,0 +1,38 @@ +DEFINES += FONTDEBUG
+
+LIBRARY=libdix
+
+CSRCS=\
+ atom.c \
+ colormap.c \
+ cursor.c \
+ deprecated.c \
+ devices.c \
+ dispatch.c \
+ dixfonts.c \
+ dixutils.c \
+ enterleave.c \
+ events.c \
+ eventconvert.c \
+ extension.c \
+ ffs.c \
+ gc.c \
+ getevents.c \
+ globals.c \
+ glyphcurs.c \
+ grabs.c \
+ initatoms.c \
+ inpututils.c \
+ main.c \
+ pixmap.c \
+ privates.c \
+ property.c \
+ ptrveloc.c \
+ registry.c \
+ resource.c \
+ selection.c \
+ swaprep.c \
+ swapreq.c \
+ tables.c \
+ window.c
+
diff --git a/xorg-server/dix/ptrveloc.c b/xorg-server/dix/ptrveloc.c index 37c8e5178..55cdb46c4 100644 --- a/xorg-server/dix/ptrveloc.c +++ b/xorg-server/dix/ptrveloc.c @@ -26,6 +26,10 @@ #include <dix-config.h> #endif +#ifdef _MSC_VER +#define _USE_MATH_DEFINES +#endif + #include <math.h> #include <ptrveloc.h> #include <exevents.h> @@ -59,6 +63,11 @@ * ****************************************************************************/ +#ifdef _MSC_VER +#define inline __inline +#define lrintf(val) ((int)val) +#endif + /* fwds */ int SetAccelerationProfile(DeviceVelocityPtr vel, int profile_num); diff --git a/xorg-server/exa/exa_accel.c b/xorg-server/exa/exa_accel.c index 7e2dd7079..8f136218f 100644 --- a/xorg-server/exa/exa_accel.c +++ b/xorg-server/exa/exa_accel.c @@ -1,1293 +1,1293 @@ -/* - * Copyright © 2001 Keith Packard - * - * Partly based on code that is Copyright © 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. - * - * Authors: - * Eric Anholt <eric@anholt.net> - * Michel Dänzer <michel@tungstengraphics.com> - * - */ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif -#include "exa_priv.h" -#include <X11/fonts/fontstruct.h> -#include "dixfontstr.h" -#include "exa.h" - -static void -exaFillSpans(DrawablePtr pDrawable, GCPtr pGC, int n, - DDXPointPtr ppt, int *pwidth, int fSorted) -{ - ScreenPtr pScreen = pDrawable->pScreen; - ExaScreenPriv (pScreen); - RegionPtr pClip = fbGetCompositeClip(pGC); - PixmapPtr pPixmap = exaGetDrawablePixmap (pDrawable); - ExaPixmapPriv (pPixmap); - BoxPtr pextent, pbox; - int nbox; - int extentX1, extentX2, extentY1, extentY2; - int fullX1, fullX2, fullY1; - int partX1, partX2; - int off_x, off_y; - - if (pExaScr->swappedOut || - pGC->fillStyle != FillSolid || - pExaPixmap->accel_blocked) - { - ExaCheckFillSpans (pDrawable, pGC, n, ppt, pwidth, fSorted); - return; - } - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[1]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pPixmap; - pixmaps[0].pReg = NULL; - - exaDoMigration (pixmaps, 1, TRUE); - } - - if (!(pPixmap = exaGetOffscreenPixmap (pDrawable, &off_x, &off_y)) || - !(*pExaScr->info->PrepareSolid) (pPixmap, - pGC->alu, - pGC->planemask, - pGC->fgPixel)) - { - ExaCheckFillSpans (pDrawable, pGC, n, ppt, pwidth, fSorted); - return; - } - - pextent = REGION_EXTENTS(pGC->pScreen, pClip); - extentX1 = pextent->x1; - extentY1 = pextent->y1; - extentX2 = pextent->x2; - extentY2 = pextent->y2; - while (n--) - { - fullX1 = ppt->x; - fullY1 = ppt->y; - fullX2 = fullX1 + (int) *pwidth; - ppt++; - pwidth++; - - if (fullY1 < extentY1 || extentY2 <= fullY1) - continue; - - if (fullX1 < extentX1) - fullX1 = extentX1; - - if (fullX2 > extentX2) - fullX2 = extentX2; - - if (fullX1 >= fullX2) - continue; - - nbox = REGION_NUM_RECTS (pClip); - if (nbox == 1) - { - (*pExaScr->info->Solid) (pPixmap, - fullX1 + off_x, fullY1 + off_y, - fullX2 + off_x, fullY1 + 1 + off_y); - } - else - { - pbox = REGION_RECTS(pClip); - while(nbox--) - { - if (pbox->y1 <= fullY1 && fullY1 < pbox->y2) - { - partX1 = pbox->x1; - if (partX1 < fullX1) - partX1 = fullX1; - partX2 = pbox->x2; - if (partX2 > fullX2) - partX2 = fullX2; - if (partX2 > partX1) { - (*pExaScr->info->Solid) (pPixmap, - partX1 + off_x, fullY1 + off_y, - partX2 + off_x, fullY1 + 1 + off_y); - } - } - pbox++; - } - } - } - (*pExaScr->info->DoneSolid) (pPixmap); - exaMarkSync(pScreen); -} - -static Bool -exaDoPutImage (DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y, - int w, int h, int format, char *bits, int src_stride) -{ - ExaScreenPriv (pDrawable->pScreen); - PixmapPtr pPix = exaGetDrawablePixmap (pDrawable); - ExaPixmapPriv(pPix); - RegionPtr pClip; - BoxPtr pbox; - int nbox; - int xoff, yoff; - int bpp = pDrawable->bitsPerPixel; - Bool ret = TRUE; - - if (pExaPixmap->accel_blocked || !pExaScr->info->UploadToScreen) - return FALSE; - - /* Don't bother with under 8bpp, XYPixmaps. */ - if (format != ZPixmap || bpp < 8) - return FALSE; - - /* Only accelerate copies: no rop or planemask. */ - if (!EXA_PM_IS_SOLID(pDrawable, pGC->planemask) || pGC->alu != GXcopy) - return FALSE; - - if (pExaScr->swappedOut) - return FALSE; - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[1]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pPix; - pixmaps[0].pReg = DamagePendingRegion(pExaPixmap->pDamage); - - exaDoMigration (pixmaps, 1, TRUE); - } - - pPix = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff); - - if (!pPix) - return FALSE; - - x += pDrawable->x; - y += pDrawable->y; - - pClip = fbGetCompositeClip(pGC); - for (nbox = REGION_NUM_RECTS(pClip), - pbox = REGION_RECTS(pClip); - nbox--; - pbox++) - { - int x1 = x; - int y1 = y; - int x2 = x + w; - int y2 = y + h; - char *src; - Bool ok; - - if (x1 < pbox->x1) - x1 = pbox->x1; - if (y1 < pbox->y1) - y1 = pbox->y1; - if (x2 > pbox->x2) - x2 = pbox->x2; - if (y2 > pbox->y2) - y2 = pbox->y2; - if (x1 >= x2 || y1 >= y2) - continue; - - src = bits + (y1 - y) * src_stride + (x1 - x) * (bpp / 8); - ok = pExaScr->info->UploadToScreen(pPix, x1 + xoff, y1 + yoff, - x2 - x1, y2 - y1, src, src_stride); - /* We have to fall back completely, and ignore what has already been completed. - * Messing with the fb layer directly like we used to is completely unacceptable. - */ - if (!ok) { - ret = FALSE; - break; - } - } - - if (ret) - exaMarkSync(pDrawable->pScreen); - - return ret; -} - -static void -exaPutImage (DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y, - int w, int h, int leftPad, int format, char *bits) -{ - if (!exaDoPutImage(pDrawable, pGC, depth, x, y, w, h, format, bits, - PixmapBytePad(w, pDrawable->depth))) - ExaCheckPutImage(pDrawable, pGC, depth, x, y, w, h, leftPad, format, - bits); -} - -static Bool inline -exaCopyNtoNTwoDir (DrawablePtr pSrcDrawable, DrawablePtr pDstDrawable, - GCPtr pGC, BoxPtr pbox, int nbox, int dx, int dy) -{ - ExaScreenPriv (pDstDrawable->pScreen); - PixmapPtr pSrcPixmap, pDstPixmap; - int src_off_x, src_off_y, dst_off_x, dst_off_y; - int dirsetup; - - /* Need to get both pixmaps to call the driver routines */ - pSrcPixmap = exaGetOffscreenPixmap (pSrcDrawable, &src_off_x, &src_off_y); - pDstPixmap = exaGetOffscreenPixmap (pDstDrawable, &dst_off_x, &dst_off_y); - if (!pSrcPixmap || !pDstPixmap) - return FALSE; - - /* - * Now the case of a chip that only supports xdir = ydir = 1 or - * xdir = ydir = -1, but we have xdir != ydir. - */ - dirsetup = 0; /* No direction set up yet. */ - for (; nbox; pbox++, nbox--) { - if (dx >= 0 && (src_off_y + pbox->y1 + dy) != pbox->y1) { - /* Do a xdir = ydir = -1 blit instead. */ - if (dirsetup != -1) { - if (dirsetup != 0) - pExaScr->info->DoneCopy(pDstPixmap); - dirsetup = -1; - if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap, - pDstPixmap, - -1, -1, - pGC ? pGC->alu : GXcopy, - pGC ? pGC->planemask : - FB_ALLONES)) - return FALSE; - } - (*pExaScr->info->Copy)(pDstPixmap, - src_off_x + pbox->x1 + dx, - src_off_y + pbox->y1 + dy, - dst_off_x + pbox->x1, - dst_off_y + pbox->y1, - pbox->x2 - pbox->x1, - pbox->y2 - pbox->y1); - } else if (dx < 0 && (src_off_y + pbox->y1 + dy) != pbox->y1) { - /* Do a xdir = ydir = 1 blit instead. */ - if (dirsetup != 1) { - if (dirsetup != 0) - pExaScr->info->DoneCopy(pDstPixmap); - dirsetup = 1; - if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap, - pDstPixmap, - 1, 1, - pGC ? pGC->alu : GXcopy, - pGC ? pGC->planemask : - FB_ALLONES)) - return FALSE; - } - (*pExaScr->info->Copy)(pDstPixmap, - src_off_x + pbox->x1 + dx, - src_off_y + pbox->y1 + dy, - dst_off_x + pbox->x1, - dst_off_y + pbox->y1, - pbox->x2 - pbox->x1, - pbox->y2 - pbox->y1); - } else if (dx >= 0) { - /* - * xdir = 1, ydir = -1. - * Perform line-by-line xdir = ydir = 1 blits, going up. - */ - int i; - if (dirsetup != 1) { - if (dirsetup != 0) - pExaScr->info->DoneCopy(pDstPixmap); - dirsetup = 1; - if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap, - pDstPixmap, - 1, 1, - pGC ? pGC->alu : GXcopy, - pGC ? pGC->planemask : - FB_ALLONES)) - return FALSE; - } - for (i = pbox->y2 - pbox->y1 - 1; i >= 0; i--) - (*pExaScr->info->Copy)(pDstPixmap, - src_off_x + pbox->x1 + dx, - src_off_y + pbox->y1 + dy + i, - dst_off_x + pbox->x1, - dst_off_y + pbox->y1 + i, - pbox->x2 - pbox->x1, 1); - } else { - /* - * xdir = -1, ydir = 1. - * Perform line-by-line xdir = ydir = -1 blits, going down. - */ - int i; - if (dirsetup != -1) { - if (dirsetup != 0) - pExaScr->info->DoneCopy(pDstPixmap); - dirsetup = -1; - if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap, - pDstPixmap, - -1, -1, - pGC ? pGC->alu : GXcopy, - pGC ? pGC->planemask : - FB_ALLONES)) - return FALSE; - } - for (i = 0; i < pbox->y2 - pbox->y1; i++) - (*pExaScr->info->Copy)(pDstPixmap, - src_off_x + pbox->x1 + dx, - src_off_y + pbox->y1 + dy + i, - dst_off_x + pbox->x1, - dst_off_y + pbox->y1 + i, - pbox->x2 - pbox->x1, 1); - } - } - if (dirsetup != 0) - pExaScr->info->DoneCopy(pDstPixmap); - exaMarkSync(pDstDrawable->pScreen); - return TRUE; -} - -Bool -exaHWCopyNtoN (DrawablePtr pSrcDrawable, - DrawablePtr pDstDrawable, - GCPtr pGC, - BoxPtr pbox, - int nbox, - int dx, - int dy, - Bool reverse, - Bool upsidedown) -{ - ExaScreenPriv (pDstDrawable->pScreen); - PixmapPtr pSrcPixmap, pDstPixmap; - ExaPixmapPrivPtr pSrcExaPixmap, pDstExaPixmap; - int src_off_x, src_off_y; - int dst_off_x, dst_off_y; - RegionPtr srcregion = NULL, dstregion = NULL; - xRectangle *rects; - Bool ret = TRUE; - - /* avoid doing copy operations if no boxes */ - if (nbox == 0) - return TRUE; - - pSrcPixmap = exaGetDrawablePixmap (pSrcDrawable); - pDstPixmap = exaGetDrawablePixmap (pDstDrawable); - - exaGetDrawableDeltas (pSrcDrawable, pSrcPixmap, &src_off_x, &src_off_y); - exaGetDrawableDeltas (pDstDrawable, pDstPixmap, &dst_off_x, &dst_off_y); - - rects = xalloc(nbox * sizeof(xRectangle)); - - if (rects) { - int i; - int ordering; - - for (i = 0; i < nbox; i++) { - rects[i].x = pbox[i].x1 + dx + src_off_x; - rects[i].y = pbox[i].y1 + dy + src_off_y; - rects[i].width = pbox[i].x2 - pbox[i].x1; - rects[i].height = pbox[i].y2 - pbox[i].y1; - } - - /* This must match the miRegionCopy() logic for reversing rect order */ - if (nbox == 1 || (dx > 0 && dy > 0) || - (pDstDrawable != pSrcDrawable && - (pDstDrawable->type != DRAWABLE_WINDOW || - pSrcDrawable->type != DRAWABLE_WINDOW))) - ordering = CT_YXBANDED; - else - ordering = CT_UNSORTED; - - srcregion = RECTS_TO_REGION(pScreen, nbox, rects, ordering); - xfree(rects); - - if (!pGC || !exaGCReadsDestination(pDstDrawable, pGC->planemask, - pGC->fillStyle, pGC->alu, - pGC->clientClipType)) { - dstregion = REGION_CREATE(pScreen, NullBox, 0); - REGION_COPY(pScreen, dstregion, srcregion); - REGION_TRANSLATE(pScreen, dstregion, dst_off_x - dx - src_off_x, - dst_off_y - dy - src_off_y); - } - } - - - pSrcExaPixmap = ExaGetPixmapPriv (pSrcPixmap); - pDstExaPixmap = ExaGetPixmapPriv (pDstPixmap); - - /* Check whether the accelerator can use this pixmap. - * If the pitch of the pixmaps is out of range, there's nothing - * we can do but fall back to software rendering. - */ - if (pSrcExaPixmap->accel_blocked & EXA_RANGE_PITCH || - pDstExaPixmap->accel_blocked & EXA_RANGE_PITCH) - goto fallback; - - /* If the width or the height of either of the pixmaps - * is out of range, check whether the boxes are actually out of the - * addressable range as well. If they aren't, we can still do - * the copying in hardware. - */ - if (pSrcExaPixmap->accel_blocked || pDstExaPixmap->accel_blocked) { - int i; - - for (i = 0; i < nbox; i++) { - /* src */ - if ((pbox[i].x2 + dx + src_off_x) >= pExaScr->info->maxX || - (pbox[i].y2 + dy + src_off_y) >= pExaScr->info->maxY) - goto fallback; - - /* dst */ - if ((pbox[i].x2 + dst_off_x) >= pExaScr->info->maxX || - (pbox[i].y2 + dst_off_y) >= pExaScr->info->maxY) - goto fallback; - } - } - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[2]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pDstPixmap; - pixmaps[0].pReg = dstregion; - pixmaps[1].as_dst = FALSE; - pixmaps[1].as_src = TRUE; - pixmaps[1].pPix = pSrcPixmap; - pixmaps[1].pReg = srcregion; - - exaDoMigration (pixmaps, 2, TRUE); - } - - /* Mixed directions must be handled specially if the card is lame */ - if ((pExaScr->info->flags & EXA_TWO_BITBLT_DIRECTIONS) && - reverse != upsidedown) { - if (exaCopyNtoNTwoDir(pSrcDrawable, pDstDrawable, pGC, pbox, nbox, - dx, dy)) - goto out; - goto fallback; - } - - if (exaPixmapIsOffscreen(pDstPixmap)) { - /* Normal blitting. */ - if (exaPixmapIsOffscreen(pSrcPixmap)) { - if (!(*pExaScr->info->PrepareCopy) (pSrcPixmap, pDstPixmap, reverse ? -1 : 1, - upsidedown ? -1 : 1, - pGC ? pGC->alu : GXcopy, - pGC ? pGC->planemask : FB_ALLONES)) { - goto fallback; - } - - while (nbox--) - { - (*pExaScr->info->Copy) (pDstPixmap, - pbox->x1 + dx + src_off_x, - pbox->y1 + dy + src_off_y, - pbox->x1 + dst_off_x, pbox->y1 + dst_off_y, - pbox->x2 - pbox->x1, pbox->y2 - pbox->y1); - pbox++; - } - - (*pExaScr->info->DoneCopy) (pDstPixmap); - exaMarkSync (pDstDrawable->pScreen); - /* UTS: mainly for SHM PutImage's secondary path. */ - } else { - int bpp = pSrcDrawable->bitsPerPixel; - int src_stride = exaGetPixmapPitch(pSrcPixmap); - CARD8 *src = NULL; - - if (!pExaScr->info->UploadToScreen) - goto fallback; - - if (pSrcDrawable->bitsPerPixel != pDstDrawable->bitsPerPixel) - goto fallback; - - if (pSrcDrawable->bitsPerPixel < 8) - goto fallback; - - if (pGC && !(pGC->alu == GXcopy && EXA_PM_IS_SOLID(pSrcDrawable, pGC->planemask))) - goto fallback; - - while (nbox--) - { - src = pSrcExaPixmap->sys_ptr + (pbox->y1 + dy + src_off_y) * src_stride + (pbox->x1 + dx + src_off_x) * (bpp / 8); - if (!pExaScr->info->UploadToScreen(pDstPixmap, pbox->x1 + dst_off_x, - pbox->y1 + dst_off_y, pbox->x2 - pbox->x1, pbox->y2 - pbox->y1, - (char *) src, src_stride)) - goto fallback; - - pbox++; - } - } - } else - goto fallback; - - goto out; - -fallback: - ret = FALSE; - -out: - if (dstregion) { - REGION_UNINIT(pScreen, dstregion); - REGION_DESTROY(pScreen, dstregion); - } - if (srcregion) { - REGION_UNINIT(pScreen, srcregion); - REGION_DESTROY(pScreen, srcregion); - } - - return ret; -} - -void -exaCopyNtoN (DrawablePtr pSrcDrawable, - DrawablePtr pDstDrawable, - GCPtr pGC, - BoxPtr pbox, - int nbox, - int dx, - int dy, - Bool reverse, - Bool upsidedown, - Pixel bitplane, - void *closure) -{ - ExaScreenPriv(pDstDrawable->pScreen); - - if (pExaScr->fallback_flags & EXA_FALLBACK_COPYWINDOW) - return; - - if (exaHWCopyNtoN(pSrcDrawable, pDstDrawable, pGC, pbox, nbox, dx, dy, reverse, upsidedown)) - return; - - /* This is a CopyWindow, it's cleaner to fallback at the original call. */ - if (pExaScr->fallback_flags & EXA_ACCEL_COPYWINDOW) { - pExaScr->fallback_flags |= EXA_FALLBACK_COPYWINDOW; - return; - } - - /* fallback */ - ExaCheckCopyNtoN(pSrcDrawable, pDstDrawable, pGC, pbox, nbox, dx, dy, reverse, upsidedown, bitplane, closure); -} - -RegionPtr -exaCopyArea(DrawablePtr pSrcDrawable, DrawablePtr pDstDrawable, GCPtr pGC, - int srcx, int srcy, int width, int height, int dstx, int dsty) -{ - ExaScreenPriv (pDstDrawable->pScreen); - - if (pExaScr->swappedOut) { - return ExaCheckCopyArea(pSrcDrawable, pDstDrawable, pGC, - srcx, srcy, width, height, dstx, dsty); - } - - return miDoCopy (pSrcDrawable, pDstDrawable, pGC, - srcx, srcy, width, height, - dstx, dsty, exaCopyNtoN, 0, NULL); -} - -static void -exaPolyPoint(DrawablePtr pDrawable, GCPtr pGC, int mode, int npt, - DDXPointPtr ppt) -{ - int i; - xRectangle *prect; - - /* If we can't reuse the current GC as is, don't bother accelerating the - * points. - */ - if (pGC->fillStyle != FillSolid) { - ExaCheckPolyPoint(pDrawable, pGC, mode, npt, ppt); - return; - } - - prect = xalloc(sizeof(xRectangle) * npt); - for (i = 0; i < npt; i++) { - prect[i].x = ppt[i].x; - prect[i].y = ppt[i].y; - if (i > 0 && mode == CoordModePrevious) { - prect[i].x += prect[i - 1].x; - prect[i].y += prect[i - 1].y; - } - prect[i].width = 1; - prect[i].height = 1; - } - pGC->ops->PolyFillRect(pDrawable, pGC, npt, prect); - xfree(prect); -} - -/** - * exaPolylines() checks if it can accelerate the lines as a group of - * horizontal or vertical lines (rectangles), and uses existing rectangle fill - * acceleration if so. - */ -static void -exaPolylines(DrawablePtr pDrawable, GCPtr pGC, int mode, int npt, - DDXPointPtr ppt) -{ - xRectangle *prect; - int x1, x2, y1, y2; - int i; - - /* Don't try to do wide lines or non-solid fill style. */ - if (pGC->lineWidth != 0 || pGC->lineStyle != LineSolid || - pGC->fillStyle != FillSolid) { - ExaCheckPolylines(pDrawable, pGC, mode, npt, ppt); - return; - } - - prect = xalloc(sizeof(xRectangle) * (npt - 1)); - x1 = ppt[0].x; - y1 = ppt[0].y; - /* If we have any non-horizontal/vertical, fall back. */ - for (i = 0; i < npt - 1; i++) { - if (mode == CoordModePrevious) { - x2 = x1 + ppt[i + 1].x; - y2 = y1 + ppt[i + 1].y; - } else { - x2 = ppt[i + 1].x; - y2 = ppt[i + 1].y; - } - - if (x1 != x2 && y1 != y2) { - xfree(prect); - ExaCheckPolylines(pDrawable, pGC, mode, npt, ppt); - return; - } - - if (x1 < x2) { - prect[i].x = x1; - prect[i].width = x2 - x1 + 1; - } else { - prect[i].x = x2; - prect[i].width = x1 - x2 + 1; - } - if (y1 < y2) { - prect[i].y = y1; - prect[i].height = y2 - y1 + 1; - } else { - prect[i].y = y2; - prect[i].height = y1 - y2 + 1; - } - - x1 = x2; - y1 = y2; - } - pGC->ops->PolyFillRect(pDrawable, pGC, npt - 1, prect); - xfree(prect); -} - -/** - * exaPolySegment() checks if it can accelerate the lines as a group of - * horizontal or vertical lines (rectangles), and uses existing rectangle fill - * acceleration if so. - */ -static void -exaPolySegment (DrawablePtr pDrawable, GCPtr pGC, int nseg, - xSegment *pSeg) -{ - xRectangle *prect; - int i; - - /* Don't try to do wide lines or non-solid fill style. */ - if (pGC->lineWidth != 0 || pGC->lineStyle != LineSolid || - pGC->fillStyle != FillSolid) - { - ExaCheckPolySegment(pDrawable, pGC, nseg, pSeg); - return; - } - - /* If we have any non-horizontal/vertical, fall back. */ - for (i = 0; i < nseg; i++) { - if (pSeg[i].x1 != pSeg[i].x2 && pSeg[i].y1 != pSeg[i].y2) { - ExaCheckPolySegment(pDrawable, pGC, nseg, pSeg); - return; - } - } - - prect = xalloc(sizeof(xRectangle) * nseg); - for (i = 0; i < nseg; i++) { - if (pSeg[i].x1 < pSeg[i].x2) { - prect[i].x = pSeg[i].x1; - prect[i].width = pSeg[i].x2 - pSeg[i].x1 + 1; - } else { - prect[i].x = pSeg[i].x2; - prect[i].width = pSeg[i].x1 - pSeg[i].x2 + 1; - } - if (pSeg[i].y1 < pSeg[i].y2) { - prect[i].y = pSeg[i].y1; - prect[i].height = pSeg[i].y2 - pSeg[i].y1 + 1; - } else { - prect[i].y = pSeg[i].y2; - prect[i].height = pSeg[i].y1 - pSeg[i].y2 + 1; - } - - /* don't paint last pixel */ - if (pGC->capStyle == CapNotLast) { - if (prect[i].width == 1) - prect[i].height--; - else - prect[i].width--; - } - } - pGC->ops->PolyFillRect(pDrawable, pGC, nseg, prect); - xfree(prect); -} - -static Bool exaFillRegionSolid (DrawablePtr pDrawable, RegionPtr pRegion, - Pixel pixel, CARD32 planemask, CARD32 alu, - unsigned int clientClipType); - -static void -exaPolyFillRect(DrawablePtr pDrawable, - GCPtr pGC, - int nrect, - xRectangle *prect) -{ - ExaScreenPriv (pDrawable->pScreen); - RegionPtr pClip = fbGetCompositeClip(pGC); - PixmapPtr pPixmap = exaGetDrawablePixmap(pDrawable); - ExaPixmapPriv (pPixmap); - register BoxPtr pbox; - BoxPtr pextent; - int extentX1, extentX2, extentY1, extentY2; - int fullX1, fullX2, fullY1, fullY2; - int partX1, partX2, partY1, partY2; - int xoff, yoff; - int xorg, yorg; - int n; - RegionPtr pReg = RECTS_TO_REGION(pScreen, nrect, prect, CT_UNSORTED); - - /* Compute intersection of rects and clip region */ - REGION_TRANSLATE(pScreen, pReg, pDrawable->x, pDrawable->y); - REGION_INTERSECT(pScreen, pReg, pClip, pReg); - - if (!REGION_NUM_RECTS(pReg)) { - goto out; - } - - exaGetDrawableDeltas(pDrawable, pPixmap, &xoff, &yoff); - - if (pExaScr->swappedOut || pExaPixmap->accel_blocked) - { - goto fallback; - } - - /* For ROPs where overlaps don't matter, convert rectangles to region and - * call exaFillRegion{Solid,Tiled}. - */ - if ((pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled) && - (nrect == 1 || pGC->alu == GXcopy || pGC->alu == GXclear || - pGC->alu == GXnoop || pGC->alu == GXcopyInverted || - pGC->alu == GXset)) { - if (((pGC->fillStyle == FillSolid || pGC->tileIsPixel) && - exaFillRegionSolid(pDrawable, pReg, pGC->fillStyle == FillSolid ? - pGC->fgPixel : pGC->tile.pixel, pGC->planemask, - pGC->alu, pGC->clientClipType)) || - (pGC->fillStyle == FillTiled && !pGC->tileIsPixel && - exaFillRegionTiled(pDrawable, pReg, pGC->tile.pixmap, &pGC->patOrg, - pGC->planemask, pGC->alu, - pGC->clientClipType))) { - goto out; - } - } - - if (pGC->fillStyle != FillSolid && - !(pGC->tileIsPixel && pGC->fillStyle == FillTiled)) - { - goto fallback; - } - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[1]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pPixmap; - pixmaps[0].pReg = NULL; - - exaDoMigration (pixmaps, 1, TRUE); - } - - if (!exaPixmapIsOffscreen (pPixmap) || - !(*pExaScr->info->PrepareSolid) (pPixmap, - pGC->alu, - pGC->planemask, - pGC->fgPixel)) - { -fallback: - ExaCheckPolyFillRect (pDrawable, pGC, nrect, prect); - goto out; - } - - xorg = pDrawable->x; - yorg = pDrawable->y; - - pextent = REGION_EXTENTS(pGC->pScreen, pClip); - extentX1 = pextent->x1; - extentY1 = pextent->y1; - extentX2 = pextent->x2; - extentY2 = pextent->y2; - while (nrect--) - { - fullX1 = prect->x + xorg; - fullY1 = prect->y + yorg; - fullX2 = fullX1 + (int) prect->width; - fullY2 = fullY1 + (int) prect->height; - prect++; - - if (fullX1 < extentX1) - fullX1 = extentX1; - - if (fullY1 < extentY1) - fullY1 = extentY1; - - if (fullX2 > extentX2) - fullX2 = extentX2; - - if (fullY2 > extentY2) - fullY2 = extentY2; - - if ((fullX1 >= fullX2) || (fullY1 >= fullY2)) - continue; - n = REGION_NUM_RECTS (pClip); - if (n == 1) - { - (*pExaScr->info->Solid) (pPixmap, - fullX1 + xoff, fullY1 + yoff, - fullX2 + xoff, fullY2 + yoff); - } - else - { - pbox = REGION_RECTS(pClip); - /* - * clip the rectangle to each box in the clip region - * this is logically equivalent to calling Intersect(), - * but rectangles may overlap each other here. - */ - while(n--) - { - partX1 = pbox->x1; - if (partX1 < fullX1) - partX1 = fullX1; - partY1 = pbox->y1; - if (partY1 < fullY1) - partY1 = fullY1; - partX2 = pbox->x2; - if (partX2 > fullX2) - partX2 = fullX2; - partY2 = pbox->y2; - if (partY2 > fullY2) - partY2 = fullY2; - - pbox++; - - if (partX1 < partX2 && partY1 < partY2) { - (*pExaScr->info->Solid) (pPixmap, - partX1 + xoff, partY1 + yoff, - partX2 + xoff, partY2 + yoff); - } - } - } - } - (*pExaScr->info->DoneSolid) (pPixmap); - exaMarkSync(pDrawable->pScreen); - -out: - REGION_UNINIT(pScreen, pReg); - REGION_DESTROY(pScreen, pReg); -} - -const GCOps exaOps = { - exaFillSpans, - ExaCheckSetSpans, - exaPutImage, - exaCopyArea, - ExaCheckCopyPlane, - exaPolyPoint, - exaPolylines, - exaPolySegment, - miPolyRectangle, - ExaCheckPolyArc, - miFillPolygon, - exaPolyFillRect, - miPolyFillArc, - miPolyText8, - miPolyText16, - miImageText8, - miImageText16, - ExaCheckImageGlyphBlt, - ExaCheckPolyGlyphBlt, - ExaCheckPushPixels, -}; - -void -exaCopyWindow(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc) -{ - RegionRec rgnDst; - int dx, dy; - PixmapPtr pPixmap = (*pWin->drawable.pScreen->GetWindowPixmap) (pWin); - ExaScreenPriv(pWin->drawable.pScreen); - - dx = ptOldOrg.x - pWin->drawable.x; - dy = ptOldOrg.y - pWin->drawable.y; - REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, -dx, -dy); - - REGION_INIT (pWin->drawable.pScreen, &rgnDst, NullBox, 0); - - REGION_INTERSECT(pWin->drawable.pScreen, &rgnDst, &pWin->borderClip, prgnSrc); -#ifdef COMPOSITE - if (pPixmap->screen_x || pPixmap->screen_y) - REGION_TRANSLATE (pWin->drawable.pScreen, &rgnDst, - -pPixmap->screen_x, -pPixmap->screen_y); -#endif - - pExaScr->fallback_flags |= EXA_ACCEL_COPYWINDOW; - miCopyRegion (&pPixmap->drawable, &pPixmap->drawable, - NULL, - &rgnDst, dx, dy, exaCopyNtoN, 0, NULL); - pExaScr->fallback_flags &= ~EXA_ACCEL_COPYWINDOW; - - REGION_UNINIT(pWin->drawable.pScreen, &rgnDst); - - if (pExaScr->fallback_flags & EXA_FALLBACK_COPYWINDOW) { - pExaScr->fallback_flags &= ~EXA_FALLBACK_COPYWINDOW; - REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, dx, dy); - ExaCheckCopyWindow(pWin, ptOldOrg, prgnSrc); - } -} - -static Bool -exaFillRegionSolid (DrawablePtr pDrawable, RegionPtr pRegion, Pixel pixel, - CARD32 planemask, CARD32 alu, unsigned int clientClipType) -{ - ExaScreenPriv(pDrawable->pScreen); - PixmapPtr pPixmap = exaGetDrawablePixmap (pDrawable); - ExaPixmapPriv (pPixmap); - int xoff, yoff; - Bool ret = FALSE; - - exaGetDrawableDeltas(pDrawable, pPixmap, &xoff, &yoff); - REGION_TRANSLATE(pScreen, pRegion, xoff, yoff); - - if (pExaPixmap->accel_blocked) - goto out; - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[1]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pPixmap; - pixmaps[0].pReg = exaGCReadsDestination(pDrawable, planemask, FillSolid, - alu, clientClipType) ? NULL : pRegion; - - exaDoMigration (pixmaps, 1, TRUE); - } - - if (exaPixmapIsOffscreen (pPixmap) && - (*pExaScr->info->PrepareSolid) (pPixmap, alu, planemask, pixel)) - { - int nbox; - BoxPtr pBox; - - nbox = REGION_NUM_RECTS (pRegion); - pBox = REGION_RECTS (pRegion); - - while (nbox--) - { - (*pExaScr->info->Solid) (pPixmap, pBox->x1, pBox->y1, pBox->x2, - pBox->y2); - pBox++; - } - (*pExaScr->info->DoneSolid) (pPixmap); - exaMarkSync(pDrawable->pScreen); - - if (pExaPixmap->pDamage && - pExaPixmap->sys_ptr && pDrawable->type == DRAWABLE_PIXMAP && - pDrawable->width == 1 && pDrawable->height == 1 && - pDrawable->bitsPerPixel != 24) { - ExaPixmapPriv(pPixmap); - - switch (pDrawable->bitsPerPixel) { - case 32: - *(CARD32*)pExaPixmap->sys_ptr = pixel; - break; - case 16: - *(CARD16*)pExaPixmap->sys_ptr = pixel; - break; - case 8: - *(CARD8*)pExaPixmap->sys_ptr = pixel; - } - - REGION_UNION(pScreen, &pExaPixmap->validSys, &pExaPixmap->validSys, - pRegion); - } - - ret = TRUE; - } - -out: - REGION_TRANSLATE(pScreen, pRegion, -xoff, -yoff); - - return ret; -} - -/* Try to do an accelerated tile of the pTile into pRegion of pDrawable. - * Based on fbFillRegionTiled(), fbTile(). - */ -Bool -exaFillRegionTiled (DrawablePtr pDrawable, RegionPtr pRegion, PixmapPtr pTile, - DDXPointPtr pPatOrg, CARD32 planemask, CARD32 alu, - unsigned int clientClipType) -{ - ExaScreenPriv(pDrawable->pScreen); - PixmapPtr pPixmap; - ExaPixmapPrivPtr pExaPixmap; - ExaPixmapPrivPtr pTileExaPixmap = ExaGetPixmapPriv(pTile); - int xoff, yoff; - int tileWidth, tileHeight; - int nbox = REGION_NUM_RECTS (pRegion); - BoxPtr pBox = REGION_RECTS (pRegion); - Bool ret = FALSE; - int i; - - tileWidth = pTile->drawable.width; - tileHeight = pTile->drawable.height; - - /* If we're filling with a solid color, grab it out and go to - * FillRegionSolid, saving numerous copies. - */ - if (tileWidth == 1 && tileHeight == 1) - return exaFillRegionSolid(pDrawable, pRegion, - exaGetPixmapFirstPixel (pTile), planemask, - alu, clientClipType); - - pPixmap = exaGetDrawablePixmap (pDrawable); - pExaPixmap = ExaGetPixmapPriv (pPixmap); - - if (pExaPixmap->accel_blocked || pTileExaPixmap->accel_blocked) - return FALSE; - - if (pExaScr->do_migration) { - ExaMigrationRec pixmaps[2]; - - pixmaps[0].as_dst = TRUE; - pixmaps[0].as_src = FALSE; - pixmaps[0].pPix = pPixmap; - pixmaps[0].pReg = exaGCReadsDestination(pDrawable, planemask, FillTiled, - alu, clientClipType) ? NULL : pRegion; - pixmaps[1].as_dst = FALSE; - pixmaps[1].as_src = TRUE; - pixmaps[1].pPix = pTile; - pixmaps[1].pReg = NULL; - - exaDoMigration (pixmaps, 2, TRUE); - } - - pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff); - - if (!pPixmap || !exaPixmapIsOffscreen(pTile)) - return FALSE; - - if ((*pExaScr->info->PrepareCopy) (pTile, pPixmap, 1, 1, alu, planemask)) - { - if (xoff || yoff) - REGION_TRANSLATE(pScreen, pRegion, xoff, yoff); - - for (i = 0; i < nbox; i++) - { - int height = pBox[i].y2 - pBox[i].y1; - int dstY = pBox[i].y1; - int tileY; - - if (alu == GXcopy) - height = min(height, tileHeight); - - modulus(dstY - yoff - pDrawable->y - pPatOrg->y, tileHeight, tileY); - - while (height > 0) { - int width = pBox[i].x2 - pBox[i].x1; - int dstX = pBox[i].x1; - int tileX; - int h = tileHeight - tileY; - - if (alu == GXcopy) - width = min(width, tileWidth); - - if (h > height) - h = height; - height -= h; - - modulus(dstX - xoff - pDrawable->x - pPatOrg->x, tileWidth, - tileX); - - while (width > 0) { - int w = tileWidth - tileX; - if (w > width) - w = width; - width -= w; - - (*pExaScr->info->Copy) (pPixmap, tileX, tileY, dstX, dstY, - w, h); - dstX += w; - tileX = 0; - } - dstY += h; - tileY = 0; - } - } - (*pExaScr->info->DoneCopy) (pPixmap); - - /* With GXcopy, we only need to do the basic algorithm up to the tile - * size; then, we can just keep doubling the destination in each - * direction until it fills the box. This way, the number of copy - * operations is O(log(rx)) + O(log(ry)) instead of O(rx * ry), where - * rx/ry is the ratio between box and tile width/height. This can make - * a big difference if each driver copy incurs a significant constant - * overhead. - */ - if (alu != GXcopy) - ret = TRUE; - else { - Bool more_copy = FALSE; - - for (i = 0; i < nbox; i++) { - int dstX = pBox[i].x1 + tileWidth; - int dstY = pBox[i].y1 + tileHeight; - - if ((dstX < pBox[i].x2) || (dstY < pBox[i].y2)) { - more_copy = TRUE; - break; - } - } - - if (more_copy == FALSE) - ret = TRUE; - - if (more_copy && (*pExaScr->info->PrepareCopy) (pPixmap, pPixmap, - 1, 1, alu, planemask)) { - for (i = 0; i < nbox; i++) - { - int dstX = pBox[i].x1 + tileWidth; - int dstY = pBox[i].y1 + tileHeight; - int width = min(pBox[i].x2 - dstX, tileWidth); - int height = min(pBox[i].y2 - pBox[i].y1, tileHeight); - - while (dstX < pBox[i].x2) { - (*pExaScr->info->Copy) (pPixmap, pBox[i].x1, pBox[i].y1, - dstX, pBox[i].y1, width, height); - dstX += width; - width = min(pBox[i].x2 - dstX, width * 2); - } - - width = pBox[i].x2 - pBox[i].x1; - height = min(pBox[i].y2 - dstY, tileHeight); - - while (dstY < pBox[i].y2) { - (*pExaScr->info->Copy) (pPixmap, pBox[i].x1, pBox[i].y1, - pBox[i].x1, dstY, width, height); - dstY += height; - height = min(pBox[i].y2 - dstY, height * 2); - } - } - - (*pExaScr->info->DoneCopy) (pPixmap); - - ret = TRUE; - } - } - - exaMarkSync(pDrawable->pScreen); - - if (xoff || yoff) - REGION_TRANSLATE(pScreen, pRegion, -xoff, -yoff); - } - - return ret; -} - - -/** - * Accelerates GetImage for solid ZPixmap downloads from framebuffer memory. - * - * This is probably the only case we actually care about. The rest fall through - * to migration and fbGetImage, which hopefully will result in migration pushing - * the pixmap out of framebuffer. - */ -void -exaGetImage (DrawablePtr pDrawable, int x, int y, int w, int h, - unsigned int format, unsigned long planeMask, char *d) -{ - ExaScreenPriv (pDrawable->pScreen); - PixmapPtr pPix = exaGetDrawablePixmap (pDrawable); - int xoff, yoff; - Bool ok; - - if (pExaScr->swappedOut) - goto fallback; - - exaGetDrawableDeltas (pDrawable, pPix, &xoff, &yoff); - - if (pExaScr->do_migration) { - BoxRec Box; - RegionRec Reg; - ExaMigrationRec pixmaps[1]; - - Box.x1 = pDrawable->y + x + xoff; - Box.y1 = pDrawable->y + y + yoff; - Box.x2 = Box.x1 + w; - Box.y2 = Box.y1 + h; - - REGION_INIT(pScreen, &Reg, &Box, 1); - - pixmaps[0].as_dst = FALSE; - pixmaps[0].as_src = TRUE; - pixmaps[0].pPix = pPix; - pixmaps[0].pReg = &Reg; - - exaDoMigration(pixmaps, 1, FALSE); - - REGION_UNINIT(pScreen, &Reg); - } - - pPix = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff); - - if (pPix == NULL || pExaScr->info->DownloadFromScreen == NULL) - goto fallback; - - /* Only cover the ZPixmap, solid copy case. */ - if (format != ZPixmap || !EXA_PM_IS_SOLID(pDrawable, planeMask)) - goto fallback; - - /* Only try to handle the 8bpp and up cases, since we don't want to think - * about <8bpp. - */ - if (pDrawable->bitsPerPixel < 8) - goto fallback; - - ok = pExaScr->info->DownloadFromScreen(pPix, pDrawable->x + x + xoff, - pDrawable->y + y + yoff, w, h, d, - PixmapBytePad(w, pDrawable->depth)); - if (ok) { - exaWaitSync(pDrawable->pScreen); - return; - } - -fallback: - ExaCheckGetImage(pDrawable, x, y, w, h, format, planeMask, d); -} +/*
+ * Copyright © 2001 Keith Packard
+ *
+ * Partly based on code that is Copyright © 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.
+ *
+ * Authors:
+ * Eric Anholt <eric@anholt.net>
+ * Michel Dänzer <michel@tungstengraphics.com>
+ *
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+#include "exa_priv.h"
+#include <X11/fonts/fontstruct.h>
+#include "dixfontstr.h"
+#include "exa.h"
+
+static void
+exaFillSpans(DrawablePtr pDrawable, GCPtr pGC, int n,
+ DDXPointPtr ppt, int *pwidth, int fSorted)
+{
+ ScreenPtr pScreen = pDrawable->pScreen;
+ ExaScreenPriv (pScreen);
+ RegionPtr pClip = fbGetCompositeClip(pGC);
+ PixmapPtr pPixmap = exaGetDrawablePixmap (pDrawable);
+ ExaPixmapPriv (pPixmap);
+ BoxPtr pextent, pbox;
+ int nbox;
+ int extentX1, extentX2, extentY1, extentY2;
+ int fullX1, fullX2, fullY1;
+ int partX1, partX2;
+ int off_x, off_y;
+
+ if (pExaScr->swappedOut ||
+ pGC->fillStyle != FillSolid ||
+ pExaPixmap->accel_blocked)
+ {
+ ExaCheckFillSpans (pDrawable, pGC, n, ppt, pwidth, fSorted);
+ return;
+ }
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[1];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pPixmap;
+ pixmaps[0].pReg = NULL;
+
+ exaDoMigration (pixmaps, 1, TRUE);
+ }
+
+ if (!(pPixmap = exaGetOffscreenPixmap (pDrawable, &off_x, &off_y)) ||
+ !(*pExaScr->info->PrepareSolid) (pPixmap,
+ pGC->alu,
+ pGC->planemask,
+ pGC->fgPixel))
+ {
+ ExaCheckFillSpans (pDrawable, pGC, n, ppt, pwidth, fSorted);
+ return;
+ }
+
+ pextent = REGION_EXTENTS(pGC->pScreen, pClip);
+ extentX1 = pextent->x1;
+ extentY1 = pextent->y1;
+ extentX2 = pextent->x2;
+ extentY2 = pextent->y2;
+ while (n--)
+ {
+ fullX1 = ppt->x;
+ fullY1 = ppt->y;
+ fullX2 = fullX1 + (int) *pwidth;
+ ppt++;
+ pwidth++;
+
+ if (fullY1 < extentY1 || extentY2 <= fullY1)
+ continue;
+
+ if (fullX1 < extentX1)
+ fullX1 = extentX1;
+
+ if (fullX2 > extentX2)
+ fullX2 = extentX2;
+
+ if (fullX1 >= fullX2)
+ continue;
+
+ nbox = REGION_NUM_RECTS (pClip);
+ if (nbox == 1)
+ {
+ (*pExaScr->info->Solid) (pPixmap,
+ fullX1 + off_x, fullY1 + off_y,
+ fullX2 + off_x, fullY1 + 1 + off_y);
+ }
+ else
+ {
+ pbox = REGION_RECTS(pClip);
+ while(nbox--)
+ {
+ if (pbox->y1 <= fullY1 && fullY1 < pbox->y2)
+ {
+ partX1 = pbox->x1;
+ if (partX1 < fullX1)
+ partX1 = fullX1;
+ partX2 = pbox->x2;
+ if (partX2 > fullX2)
+ partX2 = fullX2;
+ if (partX2 > partX1) {
+ (*pExaScr->info->Solid) (pPixmap,
+ partX1 + off_x, fullY1 + off_y,
+ partX2 + off_x, fullY1 + 1 + off_y);
+ }
+ }
+ pbox++;
+ }
+ }
+ }
+ (*pExaScr->info->DoneSolid) (pPixmap);
+ exaMarkSync(pScreen);
+}
+
+static Bool
+exaDoPutImage (DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y,
+ int w, int h, int format, char *bits, int src_stride)
+{
+ ExaScreenPriv (pDrawable->pScreen);
+ PixmapPtr pPix = exaGetDrawablePixmap (pDrawable);
+ ExaPixmapPriv(pPix);
+ RegionPtr pClip;
+ BoxPtr pbox;
+ int nbox;
+ int xoff, yoff;
+ int bpp = pDrawable->bitsPerPixel;
+ Bool ret = TRUE;
+
+ if (pExaPixmap->accel_blocked || !pExaScr->info->UploadToScreen)
+ return FALSE;
+
+ /* Don't bother with under 8bpp, XYPixmaps. */
+ if (format != ZPixmap || bpp < 8)
+ return FALSE;
+
+ /* Only accelerate copies: no rop or planemask. */
+ if (!EXA_PM_IS_SOLID(pDrawable, pGC->planemask) || pGC->alu != GXcopy)
+ return FALSE;
+
+ if (pExaScr->swappedOut)
+ return FALSE;
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[1];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pPix;
+ pixmaps[0].pReg = DamagePendingRegion(pExaPixmap->pDamage);
+
+ exaDoMigration (pixmaps, 1, TRUE);
+ }
+
+ pPix = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff);
+
+ if (!pPix)
+ return FALSE;
+
+ x += pDrawable->x;
+ y += pDrawable->y;
+
+ pClip = fbGetCompositeClip(pGC);
+ for (nbox = REGION_NUM_RECTS(pClip),
+ pbox = REGION_RECTS(pClip);
+ nbox--;
+ pbox++)
+ {
+ int x1 = x;
+ int y1 = y;
+ int x2 = x + w;
+ int y2 = y + h;
+ char *src;
+ Bool ok;
+
+ if (x1 < pbox->x1)
+ x1 = pbox->x1;
+ if (y1 < pbox->y1)
+ y1 = pbox->y1;
+ if (x2 > pbox->x2)
+ x2 = pbox->x2;
+ if (y2 > pbox->y2)
+ y2 = pbox->y2;
+ if (x1 >= x2 || y1 >= y2)
+ continue;
+
+ src = bits + (y1 - y) * src_stride + (x1 - x) * (bpp / 8);
+ ok = pExaScr->info->UploadToScreen(pPix, x1 + xoff, y1 + yoff,
+ x2 - x1, y2 - y1, src, src_stride);
+ /* We have to fall back completely, and ignore what has already been completed.
+ * Messing with the fb layer directly like we used to is completely unacceptable.
+ */
+ if (!ok) {
+ ret = FALSE;
+ break;
+ }
+ }
+
+ if (ret)
+ exaMarkSync(pDrawable->pScreen);
+
+ return ret;
+}
+
+static void
+exaPutImage (DrawablePtr pDrawable, GCPtr pGC, int depth, int x, int y,
+ int w, int h, int leftPad, int format, char *bits)
+{
+ if (!exaDoPutImage(pDrawable, pGC, depth, x, y, w, h, format, bits,
+ PixmapBytePad(w, pDrawable->depth)))
+ ExaCheckPutImage(pDrawable, pGC, depth, x, y, w, h, leftPad, format,
+ bits);
+}
+
+static Bool __inline
+exaCopyNtoNTwoDir (DrawablePtr pSrcDrawable, DrawablePtr pDstDrawable,
+ GCPtr pGC, BoxPtr pbox, int nbox, int dx, int dy)
+{
+ ExaScreenPriv (pDstDrawable->pScreen);
+ PixmapPtr pSrcPixmap, pDstPixmap;
+ int src_off_x, src_off_y, dst_off_x, dst_off_y;
+ int dirsetup;
+
+ /* Need to get both pixmaps to call the driver routines */
+ pSrcPixmap = exaGetOffscreenPixmap (pSrcDrawable, &src_off_x, &src_off_y);
+ pDstPixmap = exaGetOffscreenPixmap (pDstDrawable, &dst_off_x, &dst_off_y);
+ if (!pSrcPixmap || !pDstPixmap)
+ return FALSE;
+
+ /*
+ * Now the case of a chip that only supports xdir = ydir = 1 or
+ * xdir = ydir = -1, but we have xdir != ydir.
+ */
+ dirsetup = 0; /* No direction set up yet. */
+ for (; nbox; pbox++, nbox--) {
+ if (dx >= 0 && (src_off_y + pbox->y1 + dy) != pbox->y1) {
+ /* Do a xdir = ydir = -1 blit instead. */
+ if (dirsetup != -1) {
+ if (dirsetup != 0)
+ pExaScr->info->DoneCopy(pDstPixmap);
+ dirsetup = -1;
+ if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap,
+ pDstPixmap,
+ -1, -1,
+ pGC ? pGC->alu : GXcopy,
+ pGC ? pGC->planemask :
+ FB_ALLONES))
+ return FALSE;
+ }
+ (*pExaScr->info->Copy)(pDstPixmap,
+ src_off_x + pbox->x1 + dx,
+ src_off_y + pbox->y1 + dy,
+ dst_off_x + pbox->x1,
+ dst_off_y + pbox->y1,
+ pbox->x2 - pbox->x1,
+ pbox->y2 - pbox->y1);
+ } else if (dx < 0 && (src_off_y + pbox->y1 + dy) != pbox->y1) {
+ /* Do a xdir = ydir = 1 blit instead. */
+ if (dirsetup != 1) {
+ if (dirsetup != 0)
+ pExaScr->info->DoneCopy(pDstPixmap);
+ dirsetup = 1;
+ if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap,
+ pDstPixmap,
+ 1, 1,
+ pGC ? pGC->alu : GXcopy,
+ pGC ? pGC->planemask :
+ FB_ALLONES))
+ return FALSE;
+ }
+ (*pExaScr->info->Copy)(pDstPixmap,
+ src_off_x + pbox->x1 + dx,
+ src_off_y + pbox->y1 + dy,
+ dst_off_x + pbox->x1,
+ dst_off_y + pbox->y1,
+ pbox->x2 - pbox->x1,
+ pbox->y2 - pbox->y1);
+ } else if (dx >= 0) {
+ /*
+ * xdir = 1, ydir = -1.
+ * Perform line-by-line xdir = ydir = 1 blits, going up.
+ */
+ int i;
+ if (dirsetup != 1) {
+ if (dirsetup != 0)
+ pExaScr->info->DoneCopy(pDstPixmap);
+ dirsetup = 1;
+ if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap,
+ pDstPixmap,
+ 1, 1,
+ pGC ? pGC->alu : GXcopy,
+ pGC ? pGC->planemask :
+ FB_ALLONES))
+ return FALSE;
+ }
+ for (i = pbox->y2 - pbox->y1 - 1; i >= 0; i--)
+ (*pExaScr->info->Copy)(pDstPixmap,
+ src_off_x + pbox->x1 + dx,
+ src_off_y + pbox->y1 + dy + i,
+ dst_off_x + pbox->x1,
+ dst_off_y + pbox->y1 + i,
+ pbox->x2 - pbox->x1, 1);
+ } else {
+ /*
+ * xdir = -1, ydir = 1.
+ * Perform line-by-line xdir = ydir = -1 blits, going down.
+ */
+ int i;
+ if (dirsetup != -1) {
+ if (dirsetup != 0)
+ pExaScr->info->DoneCopy(pDstPixmap);
+ dirsetup = -1;
+ if (!(*pExaScr->info->PrepareCopy)(pSrcPixmap,
+ pDstPixmap,
+ -1, -1,
+ pGC ? pGC->alu : GXcopy,
+ pGC ? pGC->planemask :
+ FB_ALLONES))
+ return FALSE;
+ }
+ for (i = 0; i < pbox->y2 - pbox->y1; i++)
+ (*pExaScr->info->Copy)(pDstPixmap,
+ src_off_x + pbox->x1 + dx,
+ src_off_y + pbox->y1 + dy + i,
+ dst_off_x + pbox->x1,
+ dst_off_y + pbox->y1 + i,
+ pbox->x2 - pbox->x1, 1);
+ }
+ }
+ if (dirsetup != 0)
+ pExaScr->info->DoneCopy(pDstPixmap);
+ exaMarkSync(pDstDrawable->pScreen);
+ return TRUE;
+}
+
+Bool
+exaHWCopyNtoN (DrawablePtr pSrcDrawable,
+ DrawablePtr pDstDrawable,
+ GCPtr pGC,
+ BoxPtr pbox,
+ int nbox,
+ int dx,
+ int dy,
+ Bool reverse,
+ Bool upsidedown)
+{
+ ExaScreenPriv (pDstDrawable->pScreen);
+ PixmapPtr pSrcPixmap, pDstPixmap;
+ ExaPixmapPrivPtr pSrcExaPixmap, pDstExaPixmap;
+ int src_off_x, src_off_y;
+ int dst_off_x, dst_off_y;
+ RegionPtr srcregion = NULL, dstregion = NULL;
+ xRectangle *rects;
+ Bool ret = TRUE;
+
+ /* avoid doing copy operations if no boxes */
+ if (nbox == 0)
+ return TRUE;
+
+ pSrcPixmap = exaGetDrawablePixmap (pSrcDrawable);
+ pDstPixmap = exaGetDrawablePixmap (pDstDrawable);
+
+ exaGetDrawableDeltas (pSrcDrawable, pSrcPixmap, &src_off_x, &src_off_y);
+ exaGetDrawableDeltas (pDstDrawable, pDstPixmap, &dst_off_x, &dst_off_y);
+
+ rects = xalloc(nbox * sizeof(xRectangle));
+
+ if (rects) {
+ int i;
+ int ordering;
+
+ for (i = 0; i < nbox; i++) {
+ rects[i].x = pbox[i].x1 + dx + src_off_x;
+ rects[i].y = pbox[i].y1 + dy + src_off_y;
+ rects[i].width = pbox[i].x2 - pbox[i].x1;
+ rects[i].height = pbox[i].y2 - pbox[i].y1;
+ }
+
+ /* This must match the miRegionCopy() logic for reversing rect order */
+ if (nbox == 1 || (dx > 0 && dy > 0) ||
+ (pDstDrawable != pSrcDrawable &&
+ (pDstDrawable->type != DRAWABLE_WINDOW ||
+ pSrcDrawable->type != DRAWABLE_WINDOW)))
+ ordering = CT_YXBANDED;
+ else
+ ordering = CT_UNSORTED;
+
+ srcregion = RECTS_TO_REGION(pScreen, nbox, rects, ordering);
+ xfree(rects);
+
+ if (!pGC || !exaGCReadsDestination(pDstDrawable, pGC->planemask,
+ pGC->fillStyle, pGC->alu,
+ pGC->clientClipType)) {
+ dstregion = REGION_CREATE(pScreen, NullBox, 0);
+ REGION_COPY(pScreen, dstregion, srcregion);
+ REGION_TRANSLATE(pScreen, dstregion, dst_off_x - dx - src_off_x,
+ dst_off_y - dy - src_off_y);
+ }
+ }
+
+
+ pSrcExaPixmap = ExaGetPixmapPriv (pSrcPixmap);
+ pDstExaPixmap = ExaGetPixmapPriv (pDstPixmap);
+
+ /* Check whether the accelerator can use this pixmap.
+ * If the pitch of the pixmaps is out of range, there's nothing
+ * we can do but fall back to software rendering.
+ */
+ if (pSrcExaPixmap->accel_blocked & EXA_RANGE_PITCH ||
+ pDstExaPixmap->accel_blocked & EXA_RANGE_PITCH)
+ goto fallback;
+
+ /* If the width or the height of either of the pixmaps
+ * is out of range, check whether the boxes are actually out of the
+ * addressable range as well. If they aren't, we can still do
+ * the copying in hardware.
+ */
+ if (pSrcExaPixmap->accel_blocked || pDstExaPixmap->accel_blocked) {
+ int i;
+
+ for (i = 0; i < nbox; i++) {
+ /* src */
+ if ((pbox[i].x2 + dx + src_off_x) >= pExaScr->info->maxX ||
+ (pbox[i].y2 + dy + src_off_y) >= pExaScr->info->maxY)
+ goto fallback;
+
+ /* dst */
+ if ((pbox[i].x2 + dst_off_x) >= pExaScr->info->maxX ||
+ (pbox[i].y2 + dst_off_y) >= pExaScr->info->maxY)
+ goto fallback;
+ }
+ }
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[2];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pDstPixmap;
+ pixmaps[0].pReg = dstregion;
+ pixmaps[1].as_dst = FALSE;
+ pixmaps[1].as_src = TRUE;
+ pixmaps[1].pPix = pSrcPixmap;
+ pixmaps[1].pReg = srcregion;
+
+ exaDoMigration (pixmaps, 2, TRUE);
+ }
+
+ /* Mixed directions must be handled specially if the card is lame */
+ if ((pExaScr->info->flags & EXA_TWO_BITBLT_DIRECTIONS) &&
+ reverse != upsidedown) {
+ if (exaCopyNtoNTwoDir(pSrcDrawable, pDstDrawable, pGC, pbox, nbox,
+ dx, dy))
+ goto out;
+ goto fallback;
+ }
+
+ if (exaPixmapIsOffscreen(pDstPixmap)) {
+ /* Normal blitting. */
+ if (exaPixmapIsOffscreen(pSrcPixmap)) {
+ if (!(*pExaScr->info->PrepareCopy) (pSrcPixmap, pDstPixmap, reverse ? -1 : 1,
+ upsidedown ? -1 : 1,
+ pGC ? pGC->alu : GXcopy,
+ pGC ? pGC->planemask : FB_ALLONES)) {
+ goto fallback;
+ }
+
+ while (nbox--)
+ {
+ (*pExaScr->info->Copy) (pDstPixmap,
+ pbox->x1 + dx + src_off_x,
+ pbox->y1 + dy + src_off_y,
+ pbox->x1 + dst_off_x, pbox->y1 + dst_off_y,
+ pbox->x2 - pbox->x1, pbox->y2 - pbox->y1);
+ pbox++;
+ }
+
+ (*pExaScr->info->DoneCopy) (pDstPixmap);
+ exaMarkSync (pDstDrawable->pScreen);
+ /* UTS: mainly for SHM PutImage's secondary path. */
+ } else {
+ int bpp = pSrcDrawable->bitsPerPixel;
+ int src_stride = exaGetPixmapPitch(pSrcPixmap);
+ CARD8 *src = NULL;
+
+ if (!pExaScr->info->UploadToScreen)
+ goto fallback;
+
+ if (pSrcDrawable->bitsPerPixel != pDstDrawable->bitsPerPixel)
+ goto fallback;
+
+ if (pSrcDrawable->bitsPerPixel < 8)
+ goto fallback;
+
+ if (pGC && !(pGC->alu == GXcopy && EXA_PM_IS_SOLID(pSrcDrawable, pGC->planemask)))
+ goto fallback;
+
+ while (nbox--)
+ {
+ src = pSrcExaPixmap->sys_ptr + (pbox->y1 + dy + src_off_y) * src_stride + (pbox->x1 + dx + src_off_x) * (bpp / 8);
+ if (!pExaScr->info->UploadToScreen(pDstPixmap, pbox->x1 + dst_off_x,
+ pbox->y1 + dst_off_y, pbox->x2 - pbox->x1, pbox->y2 - pbox->y1,
+ (char *) src, src_stride))
+ goto fallback;
+
+ pbox++;
+ }
+ }
+ } else
+ goto fallback;
+
+ goto out;
+
+fallback:
+ ret = FALSE;
+
+out:
+ if (dstregion) {
+ REGION_UNINIT(pScreen, dstregion);
+ REGION_DESTROY(pScreen, dstregion);
+ }
+ if (srcregion) {
+ REGION_UNINIT(pScreen, srcregion);
+ REGION_DESTROY(pScreen, srcregion);
+ }
+
+ return ret;
+}
+
+void
+exaCopyNtoN (DrawablePtr pSrcDrawable,
+ DrawablePtr pDstDrawable,
+ GCPtr pGC,
+ BoxPtr pbox,
+ int nbox,
+ int dx,
+ int dy,
+ Bool reverse,
+ Bool upsidedown,
+ Pixel bitplane,
+ void *closure)
+{
+ ExaScreenPriv(pDstDrawable->pScreen);
+
+ if (pExaScr->fallback_flags & EXA_FALLBACK_COPYWINDOW)
+ return;
+
+ if (exaHWCopyNtoN(pSrcDrawable, pDstDrawable, pGC, pbox, nbox, dx, dy, reverse, upsidedown))
+ return;
+
+ /* This is a CopyWindow, it's cleaner to fallback at the original call. */
+ if (pExaScr->fallback_flags & EXA_ACCEL_COPYWINDOW) {
+ pExaScr->fallback_flags |= EXA_FALLBACK_COPYWINDOW;
+ return;
+ }
+
+ /* fallback */
+ ExaCheckCopyNtoN(pSrcDrawable, pDstDrawable, pGC, pbox, nbox, dx, dy, reverse, upsidedown, bitplane, closure);
+}
+
+RegionPtr
+exaCopyArea(DrawablePtr pSrcDrawable, DrawablePtr pDstDrawable, GCPtr pGC,
+ int srcx, int srcy, int width, int height, int dstx, int dsty)
+{
+ ExaScreenPriv (pDstDrawable->pScreen);
+
+ if (pExaScr->swappedOut) {
+ return ExaCheckCopyArea(pSrcDrawable, pDstDrawable, pGC,
+ srcx, srcy, width, height, dstx, dsty);
+ }
+
+ return miDoCopy (pSrcDrawable, pDstDrawable, pGC,
+ srcx, srcy, width, height,
+ dstx, dsty, exaCopyNtoN, 0, NULL);
+}
+
+static void
+exaPolyPoint(DrawablePtr pDrawable, GCPtr pGC, int mode, int npt,
+ DDXPointPtr ppt)
+{
+ int i;
+ xRectangle *prect;
+
+ /* If we can't reuse the current GC as is, don't bother accelerating the
+ * points.
+ */
+ if (pGC->fillStyle != FillSolid) {
+ ExaCheckPolyPoint(pDrawable, pGC, mode, npt, ppt);
+ return;
+ }
+
+ prect = xalloc(sizeof(xRectangle) * npt);
+ for (i = 0; i < npt; i++) {
+ prect[i].x = ppt[i].x;
+ prect[i].y = ppt[i].y;
+ if (i > 0 && mode == CoordModePrevious) {
+ prect[i].x += prect[i - 1].x;
+ prect[i].y += prect[i - 1].y;
+ }
+ prect[i].width = 1;
+ prect[i].height = 1;
+ }
+ pGC->ops->PolyFillRect(pDrawable, pGC, npt, prect);
+ xfree(prect);
+}
+
+/**
+ * exaPolylines() checks if it can accelerate the lines as a group of
+ * horizontal or vertical lines (rectangles), and uses existing rectangle fill
+ * acceleration if so.
+ */
+static void
+exaPolylines(DrawablePtr pDrawable, GCPtr pGC, int mode, int npt,
+ DDXPointPtr ppt)
+{
+ xRectangle *prect;
+ int x1, x2, y1, y2;
+ int i;
+
+ /* Don't try to do wide lines or non-solid fill style. */
+ if (pGC->lineWidth != 0 || pGC->lineStyle != LineSolid ||
+ pGC->fillStyle != FillSolid) {
+ ExaCheckPolylines(pDrawable, pGC, mode, npt, ppt);
+ return;
+ }
+
+ prect = xalloc(sizeof(xRectangle) * (npt - 1));
+ x1 = ppt[0].x;
+ y1 = ppt[0].y;
+ /* If we have any non-horizontal/vertical, fall back. */
+ for (i = 0; i < npt - 1; i++) {
+ if (mode == CoordModePrevious) {
+ x2 = x1 + ppt[i + 1].x;
+ y2 = y1 + ppt[i + 1].y;
+ } else {
+ x2 = ppt[i + 1].x;
+ y2 = ppt[i + 1].y;
+ }
+
+ if (x1 != x2 && y1 != y2) {
+ xfree(prect);
+ ExaCheckPolylines(pDrawable, pGC, mode, npt, ppt);
+ return;
+ }
+
+ if (x1 < x2) {
+ prect[i].x = x1;
+ prect[i].width = x2 - x1 + 1;
+ } else {
+ prect[i].x = x2;
+ prect[i].width = x1 - x2 + 1;
+ }
+ if (y1 < y2) {
+ prect[i].y = y1;
+ prect[i].height = y2 - y1 + 1;
+ } else {
+ prect[i].y = y2;
+ prect[i].height = y1 - y2 + 1;
+ }
+
+ x1 = x2;
+ y1 = y2;
+ }
+ pGC->ops->PolyFillRect(pDrawable, pGC, npt - 1, prect);
+ xfree(prect);
+}
+
+/**
+ * exaPolySegment() checks if it can accelerate the lines as a group of
+ * horizontal or vertical lines (rectangles), and uses existing rectangle fill
+ * acceleration if so.
+ */
+static void
+exaPolySegment (DrawablePtr pDrawable, GCPtr pGC, int nseg,
+ xSegment *pSeg)
+{
+ xRectangle *prect;
+ int i;
+
+ /* Don't try to do wide lines or non-solid fill style. */
+ if (pGC->lineWidth != 0 || pGC->lineStyle != LineSolid ||
+ pGC->fillStyle != FillSolid)
+ {
+ ExaCheckPolySegment(pDrawable, pGC, nseg, pSeg);
+ return;
+ }
+
+ /* If we have any non-horizontal/vertical, fall back. */
+ for (i = 0; i < nseg; i++) {
+ if (pSeg[i].x1 != pSeg[i].x2 && pSeg[i].y1 != pSeg[i].y2) {
+ ExaCheckPolySegment(pDrawable, pGC, nseg, pSeg);
+ return;
+ }
+ }
+
+ prect = xalloc(sizeof(xRectangle) * nseg);
+ for (i = 0; i < nseg; i++) {
+ if (pSeg[i].x1 < pSeg[i].x2) {
+ prect[i].x = pSeg[i].x1;
+ prect[i].width = pSeg[i].x2 - pSeg[i].x1 + 1;
+ } else {
+ prect[i].x = pSeg[i].x2;
+ prect[i].width = pSeg[i].x1 - pSeg[i].x2 + 1;
+ }
+ if (pSeg[i].y1 < pSeg[i].y2) {
+ prect[i].y = pSeg[i].y1;
+ prect[i].height = pSeg[i].y2 - pSeg[i].y1 + 1;
+ } else {
+ prect[i].y = pSeg[i].y2;
+ prect[i].height = pSeg[i].y1 - pSeg[i].y2 + 1;
+ }
+
+ /* don't paint last pixel */
+ if (pGC->capStyle == CapNotLast) {
+ if (prect[i].width == 1)
+ prect[i].height--;
+ else
+ prect[i].width--;
+ }
+ }
+ pGC->ops->PolyFillRect(pDrawable, pGC, nseg, prect);
+ xfree(prect);
+}
+
+static Bool exaFillRegionSolid (DrawablePtr pDrawable, RegionPtr pRegion,
+ Pixel pixel, CARD32 planemask, CARD32 alu,
+ unsigned int clientClipType);
+
+static void
+exaPolyFillRect(DrawablePtr pDrawable,
+ GCPtr pGC,
+ int nrect,
+ xRectangle *prect)
+{
+ ExaScreenPriv (pDrawable->pScreen);
+ RegionPtr pClip = fbGetCompositeClip(pGC);
+ PixmapPtr pPixmap = exaGetDrawablePixmap(pDrawable);
+ ExaPixmapPriv (pPixmap);
+ register BoxPtr pbox;
+ BoxPtr pextent;
+ int extentX1, extentX2, extentY1, extentY2;
+ int fullX1, fullX2, fullY1, fullY2;
+ int partX1, partX2, partY1, partY2;
+ int xoff, yoff;
+ int xorg, yorg;
+ int n;
+ RegionPtr pReg = RECTS_TO_REGION(pScreen, nrect, prect, CT_UNSORTED);
+
+ /* Compute intersection of rects and clip region */
+ REGION_TRANSLATE(pScreen, pReg, pDrawable->x, pDrawable->y);
+ REGION_INTERSECT(pScreen, pReg, pClip, pReg);
+
+ if (!REGION_NUM_RECTS(pReg)) {
+ goto out;
+ }
+
+ exaGetDrawableDeltas(pDrawable, pPixmap, &xoff, &yoff);
+
+ if (pExaScr->swappedOut || pExaPixmap->accel_blocked)
+ {
+ goto fallback;
+ }
+
+ /* For ROPs where overlaps don't matter, convert rectangles to region and
+ * call exaFillRegion{Solid,Tiled}.
+ */
+ if ((pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled) &&
+ (nrect == 1 || pGC->alu == GXcopy || pGC->alu == GXclear ||
+ pGC->alu == GXnoop || pGC->alu == GXcopyInverted ||
+ pGC->alu == GXset)) {
+ if (((pGC->fillStyle == FillSolid || pGC->tileIsPixel) &&
+ exaFillRegionSolid(pDrawable, pReg, pGC->fillStyle == FillSolid ?
+ pGC->fgPixel : pGC->tile.pixel, pGC->planemask,
+ pGC->alu, pGC->clientClipType)) ||
+ (pGC->fillStyle == FillTiled && !pGC->tileIsPixel &&
+ exaFillRegionTiled(pDrawable, pReg, pGC->tile.pixmap, &pGC->patOrg,
+ pGC->planemask, pGC->alu,
+ pGC->clientClipType))) {
+ goto out;
+ }
+ }
+
+ if (pGC->fillStyle != FillSolid &&
+ !(pGC->tileIsPixel && pGC->fillStyle == FillTiled))
+ {
+ goto fallback;
+ }
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[1];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pPixmap;
+ pixmaps[0].pReg = NULL;
+
+ exaDoMigration (pixmaps, 1, TRUE);
+ }
+
+ if (!exaPixmapIsOffscreen (pPixmap) ||
+ !(*pExaScr->info->PrepareSolid) (pPixmap,
+ pGC->alu,
+ pGC->planemask,
+ pGC->fgPixel))
+ {
+fallback:
+ ExaCheckPolyFillRect (pDrawable, pGC, nrect, prect);
+ goto out;
+ }
+
+ xorg = pDrawable->x;
+ yorg = pDrawable->y;
+
+ pextent = REGION_EXTENTS(pGC->pScreen, pClip);
+ extentX1 = pextent->x1;
+ extentY1 = pextent->y1;
+ extentX2 = pextent->x2;
+ extentY2 = pextent->y2;
+ while (nrect--)
+ {
+ fullX1 = prect->x + xorg;
+ fullY1 = prect->y + yorg;
+ fullX2 = fullX1 + (int) prect->width;
+ fullY2 = fullY1 + (int) prect->height;
+ prect++;
+
+ if (fullX1 < extentX1)
+ fullX1 = extentX1;
+
+ if (fullY1 < extentY1)
+ fullY1 = extentY1;
+
+ if (fullX2 > extentX2)
+ fullX2 = extentX2;
+
+ if (fullY2 > extentY2)
+ fullY2 = extentY2;
+
+ if ((fullX1 >= fullX2) || (fullY1 >= fullY2))
+ continue;
+ n = REGION_NUM_RECTS (pClip);
+ if (n == 1)
+ {
+ (*pExaScr->info->Solid) (pPixmap,
+ fullX1 + xoff, fullY1 + yoff,
+ fullX2 + xoff, fullY2 + yoff);
+ }
+ else
+ {
+ pbox = REGION_RECTS(pClip);
+ /*
+ * clip the rectangle to each box in the clip region
+ * this is logically equivalent to calling Intersect(),
+ * but rectangles may overlap each other here.
+ */
+ while(n--)
+ {
+ partX1 = pbox->x1;
+ if (partX1 < fullX1)
+ partX1 = fullX1;
+ partY1 = pbox->y1;
+ if (partY1 < fullY1)
+ partY1 = fullY1;
+ partX2 = pbox->x2;
+ if (partX2 > fullX2)
+ partX2 = fullX2;
+ partY2 = pbox->y2;
+ if (partY2 > fullY2)
+ partY2 = fullY2;
+
+ pbox++;
+
+ if (partX1 < partX2 && partY1 < partY2) {
+ (*pExaScr->info->Solid) (pPixmap,
+ partX1 + xoff, partY1 + yoff,
+ partX2 + xoff, partY2 + yoff);
+ }
+ }
+ }
+ }
+ (*pExaScr->info->DoneSolid) (pPixmap);
+ exaMarkSync(pDrawable->pScreen);
+
+out:
+ REGION_UNINIT(pScreen, pReg);
+ REGION_DESTROY(pScreen, pReg);
+}
+
+const GCOps exaOps = {
+ exaFillSpans,
+ ExaCheckSetSpans,
+ exaPutImage,
+ exaCopyArea,
+ ExaCheckCopyPlane,
+ exaPolyPoint,
+ exaPolylines,
+ exaPolySegment,
+ miPolyRectangle,
+ ExaCheckPolyArc,
+ miFillPolygon,
+ exaPolyFillRect,
+ miPolyFillArc,
+ miPolyText8,
+ miPolyText16,
+ miImageText8,
+ miImageText16,
+ ExaCheckImageGlyphBlt,
+ ExaCheckPolyGlyphBlt,
+ ExaCheckPushPixels,
+};
+
+void
+exaCopyWindow(WindowPtr pWin, DDXPointRec ptOldOrg, RegionPtr prgnSrc)
+{
+ RegionRec rgnDst;
+ int dx, dy;
+ PixmapPtr pPixmap = (*pWin->drawable.pScreen->GetWindowPixmap) (pWin);
+ ExaScreenPriv(pWin->drawable.pScreen);
+
+ dx = ptOldOrg.x - pWin->drawable.x;
+ dy = ptOldOrg.y - pWin->drawable.y;
+ REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, -dx, -dy);
+
+ REGION_INIT (pWin->drawable.pScreen, &rgnDst, NullBox, 0);
+
+ REGION_INTERSECT(pWin->drawable.pScreen, &rgnDst, &pWin->borderClip, prgnSrc);
+#ifdef COMPOSITE
+ if (pPixmap->screen_x || pPixmap->screen_y)
+ REGION_TRANSLATE (pWin->drawable.pScreen, &rgnDst,
+ -pPixmap->screen_x, -pPixmap->screen_y);
+#endif
+
+ pExaScr->fallback_flags |= EXA_ACCEL_COPYWINDOW;
+ miCopyRegion (&pPixmap->drawable, &pPixmap->drawable,
+ NULL,
+ &rgnDst, dx, dy, exaCopyNtoN, 0, NULL);
+ pExaScr->fallback_flags &= ~EXA_ACCEL_COPYWINDOW;
+
+ REGION_UNINIT(pWin->drawable.pScreen, &rgnDst);
+
+ if (pExaScr->fallback_flags & EXA_FALLBACK_COPYWINDOW) {
+ pExaScr->fallback_flags &= ~EXA_FALLBACK_COPYWINDOW;
+ REGION_TRANSLATE(pWin->drawable.pScreen, prgnSrc, dx, dy);
+ ExaCheckCopyWindow(pWin, ptOldOrg, prgnSrc);
+ }
+}
+
+static Bool
+exaFillRegionSolid (DrawablePtr pDrawable, RegionPtr pRegion, Pixel pixel,
+ CARD32 planemask, CARD32 alu, unsigned int clientClipType)
+{
+ ExaScreenPriv(pDrawable->pScreen);
+ PixmapPtr pPixmap = exaGetDrawablePixmap (pDrawable);
+ ExaPixmapPriv (pPixmap);
+ int xoff, yoff;
+ Bool ret = FALSE;
+
+ exaGetDrawableDeltas(pDrawable, pPixmap, &xoff, &yoff);
+ REGION_TRANSLATE(pScreen, pRegion, xoff, yoff);
+
+ if (pExaPixmap->accel_blocked)
+ goto out;
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[1];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pPixmap;
+ pixmaps[0].pReg = exaGCReadsDestination(pDrawable, planemask, FillSolid,
+ alu, clientClipType) ? NULL : pRegion;
+
+ exaDoMigration (pixmaps, 1, TRUE);
+ }
+
+ if (exaPixmapIsOffscreen (pPixmap) &&
+ (*pExaScr->info->PrepareSolid) (pPixmap, alu, planemask, pixel))
+ {
+ int nbox;
+ BoxPtr pBox;
+
+ nbox = REGION_NUM_RECTS (pRegion);
+ pBox = REGION_RECTS (pRegion);
+
+ while (nbox--)
+ {
+ (*pExaScr->info->Solid) (pPixmap, pBox->x1, pBox->y1, pBox->x2,
+ pBox->y2);
+ pBox++;
+ }
+ (*pExaScr->info->DoneSolid) (pPixmap);
+ exaMarkSync(pDrawable->pScreen);
+
+ if (pExaPixmap->pDamage &&
+ pExaPixmap->sys_ptr && pDrawable->type == DRAWABLE_PIXMAP &&
+ pDrawable->width == 1 && pDrawable->height == 1 &&
+ pDrawable->bitsPerPixel != 24) {
+ ExaPixmapPriv(pPixmap);
+
+ switch (pDrawable->bitsPerPixel) {
+ case 32:
+ *(CARD32*)pExaPixmap->sys_ptr = pixel;
+ break;
+ case 16:
+ *(CARD16*)pExaPixmap->sys_ptr = pixel;
+ break;
+ case 8:
+ *(CARD8*)pExaPixmap->sys_ptr = pixel;
+ }
+
+ REGION_UNION(pScreen, &pExaPixmap->validSys, &pExaPixmap->validSys,
+ pRegion);
+ }
+
+ ret = TRUE;
+ }
+
+out:
+ REGION_TRANSLATE(pScreen, pRegion, -xoff, -yoff);
+
+ return ret;
+}
+
+/* Try to do an accelerated tile of the pTile into pRegion of pDrawable.
+ * Based on fbFillRegionTiled(), fbTile().
+ */
+Bool
+exaFillRegionTiled (DrawablePtr pDrawable, RegionPtr pRegion, PixmapPtr pTile,
+ DDXPointPtr pPatOrg, CARD32 planemask, CARD32 alu,
+ unsigned int clientClipType)
+{
+ ExaScreenPriv(pDrawable->pScreen);
+ PixmapPtr pPixmap;
+ ExaPixmapPrivPtr pExaPixmap;
+ ExaPixmapPrivPtr pTileExaPixmap = ExaGetPixmapPriv(pTile);
+ int xoff, yoff;
+ int tileWidth, tileHeight;
+ int nbox = REGION_NUM_RECTS (pRegion);
+ BoxPtr pBox = REGION_RECTS (pRegion);
+ Bool ret = FALSE;
+ int i;
+
+ tileWidth = pTile->drawable.width;
+ tileHeight = pTile->drawable.height;
+
+ /* If we're filling with a solid color, grab it out and go to
+ * FillRegionSolid, saving numerous copies.
+ */
+ if (tileWidth == 1 && tileHeight == 1)
+ return exaFillRegionSolid(pDrawable, pRegion,
+ exaGetPixmapFirstPixel (pTile), planemask,
+ alu, clientClipType);
+
+ pPixmap = exaGetDrawablePixmap (pDrawable);
+ pExaPixmap = ExaGetPixmapPriv (pPixmap);
+
+ if (pExaPixmap->accel_blocked || pTileExaPixmap->accel_blocked)
+ return FALSE;
+
+ if (pExaScr->do_migration) {
+ ExaMigrationRec pixmaps[2];
+
+ pixmaps[0].as_dst = TRUE;
+ pixmaps[0].as_src = FALSE;
+ pixmaps[0].pPix = pPixmap;
+ pixmaps[0].pReg = exaGCReadsDestination(pDrawable, planemask, FillTiled,
+ alu, clientClipType) ? NULL : pRegion;
+ pixmaps[1].as_dst = FALSE;
+ pixmaps[1].as_src = TRUE;
+ pixmaps[1].pPix = pTile;
+ pixmaps[1].pReg = NULL;
+
+ exaDoMigration (pixmaps, 2, TRUE);
+ }
+
+ pPixmap = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff);
+
+ if (!pPixmap || !exaPixmapIsOffscreen(pTile))
+ return FALSE;
+
+ if ((*pExaScr->info->PrepareCopy) (pTile, pPixmap, 1, 1, alu, planemask))
+ {
+ if (xoff || yoff)
+ REGION_TRANSLATE(pScreen, pRegion, xoff, yoff);
+
+ for (i = 0; i < nbox; i++)
+ {
+ int height = pBox[i].y2 - pBox[i].y1;
+ int dstY = pBox[i].y1;
+ int tileY;
+
+ if (alu == GXcopy)
+ height = min(height, tileHeight);
+
+ modulus(dstY - yoff - pDrawable->y - pPatOrg->y, tileHeight, tileY);
+
+ while (height > 0) {
+ int width = pBox[i].x2 - pBox[i].x1;
+ int dstX = pBox[i].x1;
+ int tileX;
+ int h = tileHeight - tileY;
+
+ if (alu == GXcopy)
+ width = min(width, tileWidth);
+
+ if (h > height)
+ h = height;
+ height -= h;
+
+ modulus(dstX - xoff - pDrawable->x - pPatOrg->x, tileWidth,
+ tileX);
+
+ while (width > 0) {
+ int w = tileWidth - tileX;
+ if (w > width)
+ w = width;
+ width -= w;
+
+ (*pExaScr->info->Copy) (pPixmap, tileX, tileY, dstX, dstY,
+ w, h);
+ dstX += w;
+ tileX = 0;
+ }
+ dstY += h;
+ tileY = 0;
+ }
+ }
+ (*pExaScr->info->DoneCopy) (pPixmap);
+
+ /* With GXcopy, we only need to do the basic algorithm up to the tile
+ * size; then, we can just keep doubling the destination in each
+ * direction until it fills the box. This way, the number of copy
+ * operations is O(log(rx)) + O(log(ry)) instead of O(rx * ry), where
+ * rx/ry is the ratio between box and tile width/height. This can make
+ * a big difference if each driver copy incurs a significant constant
+ * overhead.
+ */
+ if (alu != GXcopy)
+ ret = TRUE;
+ else {
+ Bool more_copy = FALSE;
+
+ for (i = 0; i < nbox; i++) {
+ int dstX = pBox[i].x1 + tileWidth;
+ int dstY = pBox[i].y1 + tileHeight;
+
+ if ((dstX < pBox[i].x2) || (dstY < pBox[i].y2)) {
+ more_copy = TRUE;
+ break;
+ }
+ }
+
+ if (more_copy == FALSE)
+ ret = TRUE;
+
+ if (more_copy && (*pExaScr->info->PrepareCopy) (pPixmap, pPixmap,
+ 1, 1, alu, planemask)) {
+ for (i = 0; i < nbox; i++)
+ {
+ int dstX = pBox[i].x1 + tileWidth;
+ int dstY = pBox[i].y1 + tileHeight;
+ int width = min(pBox[i].x2 - dstX, tileWidth);
+ int height = min(pBox[i].y2 - pBox[i].y1, tileHeight);
+
+ while (dstX < pBox[i].x2) {
+ (*pExaScr->info->Copy) (pPixmap, pBox[i].x1, pBox[i].y1,
+ dstX, pBox[i].y1, width, height);
+ dstX += width;
+ width = min(pBox[i].x2 - dstX, width * 2);
+ }
+
+ width = pBox[i].x2 - pBox[i].x1;
+ height = min(pBox[i].y2 - dstY, tileHeight);
+
+ while (dstY < pBox[i].y2) {
+ (*pExaScr->info->Copy) (pPixmap, pBox[i].x1, pBox[i].y1,
+ pBox[i].x1, dstY, width, height);
+ dstY += height;
+ height = min(pBox[i].y2 - dstY, height * 2);
+ }
+ }
+
+ (*pExaScr->info->DoneCopy) (pPixmap);
+
+ ret = TRUE;
+ }
+ }
+
+ exaMarkSync(pDrawable->pScreen);
+
+ if (xoff || yoff)
+ REGION_TRANSLATE(pScreen, pRegion, -xoff, -yoff);
+ }
+
+ return ret;
+}
+
+
+/**
+ * Accelerates GetImage for solid ZPixmap downloads from framebuffer memory.
+ *
+ * This is probably the only case we actually care about. The rest fall through
+ * to migration and fbGetImage, which hopefully will result in migration pushing
+ * the pixmap out of framebuffer.
+ */
+void
+exaGetImage (DrawablePtr pDrawable, int x, int y, int w, int h,
+ unsigned int format, unsigned long planeMask, char *d)
+{
+ ExaScreenPriv (pDrawable->pScreen);
+ PixmapPtr pPix = exaGetDrawablePixmap (pDrawable);
+ int xoff, yoff;
+ Bool ok;
+
+ if (pExaScr->swappedOut)
+ goto fallback;
+
+ exaGetDrawableDeltas (pDrawable, pPix, &xoff, &yoff);
+
+ if (pExaScr->do_migration) {
+ BoxRec Box;
+ RegionRec Reg;
+ ExaMigrationRec pixmaps[1];
+
+ Box.x1 = pDrawable->y + x + xoff;
+ Box.y1 = pDrawable->y + y + yoff;
+ Box.x2 = Box.x1 + w;
+ Box.y2 = Box.y1 + h;
+
+ REGION_INIT(pScreen, &Reg, &Box, 1);
+
+ pixmaps[0].as_dst = FALSE;
+ pixmaps[0].as_src = TRUE;
+ pixmaps[0].pPix = pPix;
+ pixmaps[0].pReg = &Reg;
+
+ exaDoMigration(pixmaps, 1, FALSE);
+
+ REGION_UNINIT(pScreen, &Reg);
+ }
+
+ pPix = exaGetOffscreenPixmap (pDrawable, &xoff, &yoff);
+
+ if (pPix == NULL || pExaScr->info->DownloadFromScreen == NULL)
+ goto fallback;
+
+ /* Only cover the ZPixmap, solid copy case. */
+ if (format != ZPixmap || !EXA_PM_IS_SOLID(pDrawable, planeMask))
+ goto fallback;
+
+ /* Only try to handle the 8bpp and up cases, since we don't want to think
+ * about <8bpp.
+ */
+ if (pDrawable->bitsPerPixel < 8)
+ goto fallback;
+
+ ok = pExaScr->info->DownloadFromScreen(pPix, pDrawable->x + x + xoff,
+ pDrawable->y + y + yoff, w, h, d,
+ PixmapBytePad(w, pDrawable->depth));
+ if (ok) {
+ exaWaitSync(pDrawable->pScreen);
+ return;
+ }
+
+fallback:
+ ExaCheckGetImage(pDrawable, x, y, w, h, format, planeMask, d);
+}
diff --git a/xorg-server/exa/exa_migration_classic.c b/xorg-server/exa/exa_migration_classic.c index d8e1e86da..e096c1eac 100644 --- a/xorg-server/exa/exa_migration_classic.c +++ b/xorg-server/exa/exa_migration_classic.c @@ -368,8 +368,8 @@ exaDoMoveInPixmap (ExaMigrationPtr migrate) void exaMoveInPixmap_classic (PixmapPtr pPixmap) { - static ExaMigrationRec migrate = { .as_dst = FALSE, .as_src = TRUE, - .pReg = NULL }; + static ExaMigrationRec migrate = { FALSE, TRUE, + NULL, NULL }; migrate.pPix = pPixmap; exaDoMoveInPixmap (&migrate); @@ -409,8 +409,8 @@ exaDoMoveOutPixmap (ExaMigrationPtr migrate) void exaMoveOutPixmap_classic (PixmapPtr pPixmap) { - static ExaMigrationRec migrate = { .as_dst = FALSE, .as_src = TRUE, - .pReg = NULL }; + static ExaMigrationRec migrate = { FALSE, TRUE, + NULL, NULL }; migrate.pPix = pPixmap; exaDoMoveOutPixmap (&migrate); @@ -608,7 +608,7 @@ exaDoMigration_classic (ExaMigrationPtr pixmaps, int npixmaps, Bool can_accel) for (i = 0; i < npixmaps; i++) { if (!exaPixmapIsDirty (pixmaps[i].pPix) && !exaAssertNotDirty (pixmaps[i].pPix)) - ErrorF("%s: Pixmap %d dirty but not marked as such!\n", __func__, i); + ErrorF("%s: Pixmap %d dirty but not marked as such!\n", __FUNCTION__, i); } } /* If anything is pinned in system memory, we won't be able to diff --git a/xorg-server/exa/exa_unaccel.c b/xorg-server/exa/exa_unaccel.c index f4700adac..7e26feb83 100644 --- a/xorg-server/exa/exa_unaccel.c +++ b/xorg-server/exa/exa_unaccel.c @@ -522,7 +522,7 @@ exaGetPixmapFirstPixel (PixmapPtr pPixmap) return pixel; } default: - FatalError("%s called for invalid bpp %d\n", __func__, + FatalError("%s called for invalid bpp %d\n", __FUNCTION__, pPixmap->drawable.bitsPerPixel); } } diff --git a/xorg-server/exa/makefile b/xorg-server/exa/makefile new file mode 100644 index 000000000..5ad11a1ed --- /dev/null +++ b/xorg-server/exa/makefile @@ -0,0 +1,14 @@ +LIBRARY=libexa
+
+CSRCS = \
+ exa.c \
+ exa_classic.c \
+ exa_migration_classic.c \
+ exa_driver.c \
+ exa_mixed.c \
+ exa_migration_mixed.c \
+ exa_accel.c \
+ exa_glyphs.c \
+ exa_offscreen.c \
+ exa_render.c \
+ exa_unaccel.c
diff --git a/xorg-server/fb/fbpict.c b/xorg-server/fb/fbpict.c index 2fbef15c3..9a40443d1 100644 --- a/xorg-server/fb/fbpict.c +++ b/xorg-server/fb/fbpict.c @@ -1,542 +1,543 @@ -/* - * - * Copyright © 2000 SuSE, Inc. - * Copyright © 2007 Red Hat, 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 SuSE not be used in advertising or - * publicity pertaining to distribution of the software without specific, - * written prior permission. SuSE makes no representations about the - * suitability of this software for any purpose. It is provided "as is" - * without express or implied warranty. - * - * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE - * 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: Keith Packard, SuSE, Inc. - */ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <string.h> - -#include "fb.h" - -#ifdef RENDER - -#include "picturestr.h" -#include "mipict.h" -#include "fbpict.h" - -#define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b)) - -void -fbWalkCompositeRegion (CARD8 op, - PicturePtr pSrc, - PicturePtr pMask, - PicturePtr pDst, - INT16 xSrc, - INT16 ySrc, - INT16 xMask, - INT16 yMask, - INT16 xDst, - INT16 yDst, - CARD16 width, - CARD16 height, - Bool srcRepeat, - Bool maskRepeat, - CompositeFunc compositeRect) -{ - RegionRec region; - int n; - BoxPtr pbox; - int w, h, w_this, h_this; - int x_msk, y_msk, x_src, y_src, x_dst, y_dst; - - xDst += pDst->pDrawable->x; - yDst += pDst->pDrawable->y; - if (pSrc->pDrawable) - { - xSrc += pSrc->pDrawable->x; - ySrc += pSrc->pDrawable->y; - } - if (pMask && pMask->pDrawable) - { - xMask += pMask->pDrawable->x; - yMask += pMask->pDrawable->y; - } - - if (!miComputeCompositeRegion (®ion, pSrc, pMask, pDst, xSrc, ySrc, - xMask, yMask, xDst, yDst, width, height)) - return; - - n = REGION_NUM_RECTS (®ion); - pbox = REGION_RECTS (®ion); - while (n--) - { - h = pbox->y2 - pbox->y1; - y_src = pbox->y1 - yDst + ySrc; - y_msk = pbox->y1 - yDst + yMask; - y_dst = pbox->y1; - while (h) - { - h_this = h; - w = pbox->x2 - pbox->x1; - x_src = pbox->x1 - xDst + xSrc; - x_msk = pbox->x1 - xDst + xMask; - x_dst = pbox->x1; - if (maskRepeat) - { - y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height); - if (h_this > pMask->pDrawable->height - y_msk) - h_this = pMask->pDrawable->height - y_msk; - y_msk += pMask->pDrawable->y; - } - if (srcRepeat) - { - y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height); - if (h_this > pSrc->pDrawable->height - y_src) - h_this = pSrc->pDrawable->height - y_src; - y_src += pSrc->pDrawable->y; - } - while (w) - { - w_this = w; - if (maskRepeat) - { - x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width); - if (w_this > pMask->pDrawable->width - x_msk) - w_this = pMask->pDrawable->width - x_msk; - x_msk += pMask->pDrawable->x; - } - if (srcRepeat) - { - x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width); - if (w_this > pSrc->pDrawable->width - x_src) - w_this = pSrc->pDrawable->width - x_src; - x_src += pSrc->pDrawable->x; - } - (*compositeRect) (op, pSrc, pMask, pDst, - x_src, y_src, x_msk, y_msk, x_dst, y_dst, - w_this, h_this); - w -= w_this; - x_src += w_this; - x_msk += w_this; - x_dst += w_this; - } - h -= h_this; - y_src += h_this; - y_msk += h_this; - y_dst += h_this; - } - pbox++; - } - REGION_UNINIT (pDst->pDrawable->pScreen, ®ion); -} - -void -fbComposite (CARD8 op, - PicturePtr pSrc, - PicturePtr pMask, - PicturePtr pDst, - INT16 xSrc, - INT16 ySrc, - INT16 xMask, - INT16 yMask, - INT16 xDst, - INT16 yDst, - CARD16 width, - CARD16 height) -{ - pixman_image_t *src, *mask, *dest; - - miCompositeSourceValidate (pSrc, xSrc, ySrc, width, height); - if (pMask) - miCompositeSourceValidate (pMask, xMask, yMask, width, height); - - src = image_from_pict (pSrc, TRUE, TRUE); - mask = image_from_pict (pMask, TRUE, TRUE); - dest = image_from_pict (pDst, TRUE, FALSE); - - if (src && dest && !(pMask && !mask)) - { - pixman_image_composite (op, src, mask, dest, - xSrc, ySrc, xMask, yMask, xDst, yDst, - width, height); - } - - free_pixman_pict (pSrc, src); - free_pixman_pict (pMask, mask); - free_pixman_pict (pDst, dest); -} - -void -fbCompositeGeneral (CARD8 op, - PicturePtr pSrc, - PicturePtr pMask, - PicturePtr pDst, - INT16 xSrc, - INT16 ySrc, - INT16 xMask, - INT16 yMask, - INT16 xDst, - INT16 yDst, - CARD16 width, - CARD16 height) -{ - fbComposite (op, pSrc, pMask, pDst, - xSrc, ySrc, xMask, yMask, xDst, yDst, - width, height); -} - -#endif /* RENDER */ - -static pixman_image_t * -create_solid_fill_image (PicturePtr pict) -{ - PictSolidFill *solid = &pict->pSourcePict->solidFill; - pixman_color_t color; - CARD32 a, r, g, b; - - a = (solid->color & 0xff000000) >> 24; - r = (solid->color & 0x00ff0000) >> 16; - g = (solid->color & 0x0000ff00) >> 8; - b = (solid->color & 0x000000ff) >> 0; - - color.alpha = (a << 8) | a; - color.red = (r << 8) | r; - color.green = (g << 8) | g; - color.blue = (b << 8) | b; - - return pixman_image_create_solid_fill (&color); -} - -static pixman_image_t * -create_linear_gradient_image (PictGradient *gradient) -{ - PictLinearGradient *linear = (PictLinearGradient *)gradient; - pixman_point_fixed_t p1; - pixman_point_fixed_t p2; - - p1.x = linear->p1.x; - p1.y = linear->p1.y; - p2.x = linear->p2.x; - p2.y = linear->p2.y; - - return pixman_image_create_linear_gradient ( - &p1, &p2, (pixman_gradient_stop_t *)gradient->stops, gradient->nstops); -} - -static pixman_image_t * -create_radial_gradient_image (PictGradient *gradient) -{ - PictRadialGradient *radial = (PictRadialGradient *)gradient; - pixman_point_fixed_t c1; - pixman_point_fixed_t c2; - - c1.x = radial->c1.x; - c1.y = radial->c1.y; - c2.x = radial->c2.x; - c2.y = radial->c2.y; - - return pixman_image_create_radial_gradient ( - &c1, &c2, radial->c1.radius, - radial->c2.radius, - (pixman_gradient_stop_t *)gradient->stops, gradient->nstops); -} - -static pixman_image_t * -create_conical_gradient_image (PictGradient *gradient) -{ - PictConicalGradient *conical = (PictConicalGradient *)gradient; - pixman_point_fixed_t center; - - center.x = conical->center.x; - center.y = conical->center.y; - - return pixman_image_create_conical_gradient ( - ¢er, conical->angle, (pixman_gradient_stop_t *)gradient->stops, - gradient->nstops); -} - -static DrawablePtr -copy_drawable (DrawablePtr pDraw) -{ - ScreenPtr pScreen = pDraw->pScreen; - PixmapPtr pPixmap; - GCPtr pGC; - int width, height; - ChangeGCVal gcv[2]; - - width = pDraw->width; - height = pDraw->height; - - pPixmap = (*pScreen->CreatePixmap) (pScreen, width, height, pDraw->depth, 0); - - if (!pPixmap) - return NULL; - - pGC = GetScratchGC (pDraw->depth, pScreen); - - if (!pGC) - { - (*pScreen->DestroyPixmap) (pPixmap); - return NULL; - } - - /* First fill the pixmap with zeros */ - gcv[0].val = 0x00000000; - gcv[1].val = IncludeInferiors; - dixChangeGC (NullClient, pGC, GCBackground | GCSubwindowMode, NULL, gcv); - ValidateGC ((DrawablePtr)pPixmap, pGC); - miClearDrawable ((DrawablePtr)pPixmap, pGC); - - /* Then copy the window there */ - ValidateGC(&pPixmap->drawable, pGC); - (* pGC->ops->CopyArea) (pDraw, &pPixmap->drawable, pGC, 0, 0, width, height, 0, 0); - - FreeScratchGC (pGC); - - return &pPixmap->drawable; -} - -static void -destroy_drawable (pixman_image_t *image, void *data) -{ - DrawablePtr pDrawable = data; - ScreenPtr pScreen = pDrawable->pScreen; - - pScreen->DestroyPixmap ((PixmapPtr)pDrawable); -} - -static pixman_image_t * -create_bits_picture (PicturePtr pict, - Bool has_clip, - Bool is_src) -{ - FbBits *bits; - FbStride stride; - int bpp, xoff, yoff; - pixman_image_t *image; - DrawablePtr drawable; - - if (is_src && pict->pDrawable->type == DRAWABLE_WINDOW) - drawable = copy_drawable (pict->pDrawable); - else - drawable = pict->pDrawable; - - fbGetDrawable (drawable, bits, stride, bpp, xoff, yoff); - - bits = (FbBits*)((CARD8*)bits + - (drawable->y + yoff) * stride * sizeof(FbBits) + - (drawable->x + xoff) * (bpp / 8)); - - image = pixman_image_create_bits ( - pict->format, drawable->width, drawable->height, - (uint32_t *)bits, stride * sizeof (FbStride)); - - -#ifdef FB_ACCESS_WRAPPER -#if FB_SHIFT==5 - - pixman_image_set_accessors (image, - (pixman_read_memory_func_t)wfbReadMemory, - (pixman_write_memory_func_t)wfbWriteMemory); - -#else - -#error The pixman library only works when FbBits is 32 bits wide - -#endif -#endif - - if (has_clip) - { - if (is_src) - { - if (pict->clientClipType != CT_NONE) - { - pixman_image_set_has_client_clip (image, TRUE); - - pixman_region_translate (pict->clientClip, - pict->clipOrigin.x, - pict->clipOrigin.y); - - pixman_image_set_clip_region (image, pict->clientClip); - - pixman_region_translate (pict->clientClip, - - pict->clipOrigin.x, - - pict->clipOrigin.y); - } - } - else - { - pixman_region_translate (pict->pCompositeClip, - - pict->pDrawable->x, - - pict->pDrawable->y); - - pixman_image_set_clip_region (image, pict->pCompositeClip); - - pixman_region_translate (pict->pCompositeClip, - pict->pDrawable->x, - pict->pDrawable->y); - } - } - - /* Indexed table */ - if (pict->pFormat->index.devPrivate) - pixman_image_set_indexed (image, pict->pFormat->index.devPrivate); - - if (drawable != pict->pDrawable) - pixman_image_set_destroy_function (image, destroy_drawable, drawable); - - return image; -} - -static void -set_image_properties (pixman_image_t *image, PicturePtr pict) -{ - pixman_repeat_t repeat; - pixman_filter_t filter; - - if (pict->transform) - { - pixman_image_set_transform ( - image, (pixman_transform_t *)pict->transform); - } - - switch (pict->repeatType) - { - default: - case RepeatNone: - repeat = PIXMAN_REPEAT_NONE; - break; - - case RepeatPad: - repeat = PIXMAN_REPEAT_PAD; - break; - - case RepeatNormal: - repeat = PIXMAN_REPEAT_NORMAL; - break; - - case RepeatReflect: - repeat = PIXMAN_REPEAT_REFLECT; - break; - } - - pixman_image_set_repeat (image, repeat); - - if (pict->alphaMap) - { - pixman_image_t *alpha_map = image_from_pict (pict->alphaMap, TRUE, TRUE); - - pixman_image_set_alpha_map ( - image, alpha_map, pict->alphaOrigin.x, pict->alphaOrigin.y); - - free_pixman_pict (pict->alphaMap, alpha_map); - } - - pixman_image_set_component_alpha (image, pict->componentAlpha); - - switch (pict->filter) - { - default: - case PictFilterNearest: - case PictFilterFast: - filter = PIXMAN_FILTER_NEAREST; - break; - - case PictFilterBilinear: - case PictFilterGood: - filter = PIXMAN_FILTER_BILINEAR; - break; - - case PictFilterConvolution: - filter = PIXMAN_FILTER_CONVOLUTION; - break; - } - - pixman_image_set_filter (image, filter, (pixman_fixed_t *)pict->filter_params, pict->filter_nparams); - pixman_image_set_source_clipping (image, TRUE); -} - -pixman_image_t * -image_from_pict (PicturePtr pict, - Bool has_clip, - Bool is_src) -{ - pixman_image_t *image = NULL; - - if (!pict) - return NULL; - - if (pict->pDrawable) - { - image = create_bits_picture (pict, has_clip, is_src); - } - else if (pict->pSourcePict) - { - SourcePict *sp = pict->pSourcePict; - - if (sp->type == SourcePictTypeSolidFill) - { - image = create_solid_fill_image (pict); - } - else - { - PictGradient *gradient = &pict->pSourcePict->gradient; - - if (sp->type == SourcePictTypeLinear) - image = create_linear_gradient_image (gradient); - else if (sp->type == SourcePictTypeRadial) - image = create_radial_gradient_image (gradient); - else if (sp->type == SourcePictTypeConical) - image = create_conical_gradient_image (gradient); - } - } - - if (image) - set_image_properties (image, pict); - - return image; -} - -void -free_pixman_pict (PicturePtr pict, pixman_image_t *image) -{ - if (image && pixman_image_unref (image) && pict->pDrawable) - fbFinishAccess (pict->pDrawable); -} - -Bool -fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats) -{ - -#ifdef RENDER - - PictureScreenPtr ps; - - if (!miPictureInit (pScreen, formats, nformats)) - return FALSE; - ps = GetPictureScreen(pScreen); - ps->Composite = fbComposite; - ps->Glyphs = miGlyphs; - ps->CompositeRects = miCompositeRects; - ps->RasterizeTrapezoid = fbRasterizeTrapezoid; - ps->AddTraps = fbAddTraps; - ps->AddTriangles = fbAddTriangles; - -#endif /* RENDER */ - - return TRUE; -} +/*
+ *
+ * Copyright © 2000 SuSE, Inc.
+ * Copyright © 2007 Red Hat, 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 SuSE not be used in advertising or
+ * publicity pertaining to distribution of the software without specific,
+ * written prior permission. SuSE makes no representations about the
+ * suitability of this software for any purpose. It is provided "as is"
+ * without express or implied warranty.
+ *
+ * SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE
+ * 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: Keith Packard, SuSE, Inc.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <string.h>
+
+#include "fb.h"
+
+#include "picturestr.h"
+
+#ifdef RENDER
+
+#include "mipict.h"
+#include "fbpict.h"
+
+#define mod(a,b) ((b) == 1 ? 0 : (a) >= 0 ? (a) % (b) : (b) - (-a) % (b))
+
+void
+fbWalkCompositeRegion (CARD8 op,
+ PicturePtr pSrc,
+ PicturePtr pMask,
+ PicturePtr pDst,
+ INT16 xSrc,
+ INT16 ySrc,
+ INT16 xMask,
+ INT16 yMask,
+ INT16 xDst,
+ INT16 yDst,
+ CARD16 width,
+ CARD16 height,
+ Bool srcRepeat,
+ Bool maskRepeat,
+ CompositeFunc compositeRect)
+{
+ RegionRec region;
+ int n;
+ BoxPtr pbox;
+ int w, h, w_this, h_this;
+ int x_msk, y_msk, x_src, y_src, x_dst, y_dst;
+
+ xDst += pDst->pDrawable->x;
+ yDst += pDst->pDrawable->y;
+ if (pSrc->pDrawable)
+ {
+ xSrc += pSrc->pDrawable->x;
+ ySrc += pSrc->pDrawable->y;
+ }
+ if (pMask && pMask->pDrawable)
+ {
+ xMask += pMask->pDrawable->x;
+ yMask += pMask->pDrawable->y;
+ }
+
+ if (!miComputeCompositeRegion (®ion, pSrc, pMask, pDst, xSrc, ySrc,
+ xMask, yMask, xDst, yDst, width, height))
+ return;
+
+ n = REGION_NUM_RECTS (®ion);
+ pbox = REGION_RECTS (®ion);
+ while (n--)
+ {
+ h = pbox->y2 - pbox->y1;
+ y_src = pbox->y1 - yDst + ySrc;
+ y_msk = pbox->y1 - yDst + yMask;
+ y_dst = pbox->y1;
+ while (h)
+ {
+ h_this = h;
+ w = pbox->x2 - pbox->x1;
+ x_src = pbox->x1 - xDst + xSrc;
+ x_msk = pbox->x1 - xDst + xMask;
+ x_dst = pbox->x1;
+ if (maskRepeat)
+ {
+ y_msk = mod (y_msk - pMask->pDrawable->y, pMask->pDrawable->height);
+ if (h_this > pMask->pDrawable->height - y_msk)
+ h_this = pMask->pDrawable->height - y_msk;
+ y_msk += pMask->pDrawable->y;
+ }
+ if (srcRepeat)
+ {
+ y_src = mod (y_src - pSrc->pDrawable->y, pSrc->pDrawable->height);
+ if (h_this > pSrc->pDrawable->height - y_src)
+ h_this = pSrc->pDrawable->height - y_src;
+ y_src += pSrc->pDrawable->y;
+ }
+ while (w)
+ {
+ w_this = w;
+ if (maskRepeat)
+ {
+ x_msk = mod (x_msk - pMask->pDrawable->x, pMask->pDrawable->width);
+ if (w_this > pMask->pDrawable->width - x_msk)
+ w_this = pMask->pDrawable->width - x_msk;
+ x_msk += pMask->pDrawable->x;
+ }
+ if (srcRepeat)
+ {
+ x_src = mod (x_src - pSrc->pDrawable->x, pSrc->pDrawable->width);
+ if (w_this > pSrc->pDrawable->width - x_src)
+ w_this = pSrc->pDrawable->width - x_src;
+ x_src += pSrc->pDrawable->x;
+ }
+ (*compositeRect) (op, pSrc, pMask, pDst,
+ x_src, y_src, x_msk, y_msk, x_dst, y_dst,
+ w_this, h_this);
+ w -= w_this;
+ x_src += w_this;
+ x_msk += w_this;
+ x_dst += w_this;
+ }
+ h -= h_this;
+ y_src += h_this;
+ y_msk += h_this;
+ y_dst += h_this;
+ }
+ pbox++;
+ }
+ REGION_UNINIT (pDst->pDrawable->pScreen, ®ion);
+}
+
+void
+fbComposite (CARD8 op,
+ PicturePtr pSrc,
+ PicturePtr pMask,
+ PicturePtr pDst,
+ INT16 xSrc,
+ INT16 ySrc,
+ INT16 xMask,
+ INT16 yMask,
+ INT16 xDst,
+ INT16 yDst,
+ CARD16 width,
+ CARD16 height)
+{
+ pixman_image_t *src, *mask, *dest;
+
+ miCompositeSourceValidate (pSrc, xSrc, ySrc, width, height);
+ if (pMask)
+ miCompositeSourceValidate (pMask, xMask, yMask, width, height);
+
+ src = image_from_pict (pSrc, TRUE, TRUE);
+ mask = image_from_pict (pMask, TRUE, TRUE);
+ dest = image_from_pict (pDst, TRUE, FALSE);
+
+ if (src && dest && !(pMask && !mask))
+ {
+ pixman_image_composite (op, src, mask, dest,
+ xSrc, ySrc, xMask, yMask, xDst, yDst,
+ width, height);
+ }
+
+ free_pixman_pict (pSrc, src);
+ free_pixman_pict (pMask, mask);
+ free_pixman_pict (pDst, dest);
+}
+
+void
+fbCompositeGeneral (CARD8 op,
+ PicturePtr pSrc,
+ PicturePtr pMask,
+ PicturePtr pDst,
+ INT16 xSrc,
+ INT16 ySrc,
+ INT16 xMask,
+ INT16 yMask,
+ INT16 xDst,
+ INT16 yDst,
+ CARD16 width,
+ CARD16 height)
+{
+ fbComposite (op, pSrc, pMask, pDst,
+ xSrc, ySrc, xMask, yMask, xDst, yDst,
+ width, height);
+}
+
+#endif /* RENDER */
+
+static pixman_image_t *
+create_solid_fill_image (PicturePtr pict)
+{
+ PictSolidFill *solid = &pict->pSourcePict->solidFill;
+ pixman_color_t color;
+ CARD32 a, r, g, b;
+
+ a = (solid->color & 0xff000000) >> 24;
+ r = (solid->color & 0x00ff0000) >> 16;
+ g = (solid->color & 0x0000ff00) >> 8;
+ b = (solid->color & 0x000000ff) >> 0;
+
+ color.alpha = (a << 8) | a;
+ color.red = (r << 8) | r;
+ color.green = (g << 8) | g;
+ color.blue = (b << 8) | b;
+
+ return pixman_image_create_solid_fill (&color);
+}
+
+static pixman_image_t *
+create_linear_gradient_image (PictGradient *gradient)
+{
+ PictLinearGradient *linear = (PictLinearGradient *)gradient;
+ pixman_point_fixed_t p1;
+ pixman_point_fixed_t p2;
+
+ p1.x = linear->p1.x;
+ p1.y = linear->p1.y;
+ p2.x = linear->p2.x;
+ p2.y = linear->p2.y;
+
+ return pixman_image_create_linear_gradient (
+ &p1, &p2, (pixman_gradient_stop_t *)gradient->stops, gradient->nstops);
+}
+
+static pixman_image_t *
+create_radial_gradient_image (PictGradient *gradient)
+{
+ PictRadialGradient *radial = (PictRadialGradient *)gradient;
+ pixman_point_fixed_t c1;
+ pixman_point_fixed_t c2;
+
+ c1.x = radial->c1.x;
+ c1.y = radial->c1.y;
+ c2.x = radial->c2.x;
+ c2.y = radial->c2.y;
+
+ return pixman_image_create_radial_gradient (
+ &c1, &c2, radial->c1.radius,
+ radial->c2.radius,
+ (pixman_gradient_stop_t *)gradient->stops, gradient->nstops);
+}
+
+static pixman_image_t *
+create_conical_gradient_image (PictGradient *gradient)
+{
+ PictConicalGradient *conical = (PictConicalGradient *)gradient;
+ pixman_point_fixed_t center;
+
+ center.x = conical->center.x;
+ center.y = conical->center.y;
+
+ return pixman_image_create_conical_gradient (
+ ¢er, conical->angle, (pixman_gradient_stop_t *)gradient->stops,
+ gradient->nstops);
+}
+
+static DrawablePtr
+copy_drawable (DrawablePtr pDraw)
+{
+ ScreenPtr pScreen = pDraw->pScreen;
+ PixmapPtr pPixmap;
+ GCPtr pGC;
+ int width, height;
+ ChangeGCVal gcv[2];
+
+ width = pDraw->width;
+ height = pDraw->height;
+
+ pPixmap = (*pScreen->CreatePixmap) (pScreen, width, height, pDraw->depth, 0);
+
+ if (!pPixmap)
+ return NULL;
+
+ pGC = GetScratchGC (pDraw->depth, pScreen);
+
+ if (!pGC)
+ {
+ (*pScreen->DestroyPixmap) (pPixmap);
+ return NULL;
+ }
+
+ /* First fill the pixmap with zeros */
+ gcv[0].val = 0x00000000;
+ gcv[1].val = IncludeInferiors;
+ dixChangeGC (NullClient, pGC, GCBackground | GCSubwindowMode, NULL, gcv);
+ ValidateGC ((DrawablePtr)pPixmap, pGC);
+ miClearDrawable ((DrawablePtr)pPixmap, pGC);
+
+ /* Then copy the window there */
+ ValidateGC(&pPixmap->drawable, pGC);
+ (* pGC->ops->CopyArea) (pDraw, &pPixmap->drawable, pGC, 0, 0, width, height, 0, 0);
+
+ FreeScratchGC (pGC);
+
+ return &pPixmap->drawable;
+}
+
+static void
+destroy_drawable (pixman_image_t *image, void *data)
+{
+ DrawablePtr pDrawable = data;
+ ScreenPtr pScreen = pDrawable->pScreen;
+
+ pScreen->DestroyPixmap ((PixmapPtr)pDrawable);
+}
+
+static pixman_image_t *
+create_bits_picture (PicturePtr pict,
+ Bool has_clip,
+ Bool is_src)
+{
+ FbBits *bits;
+ FbStride stride;
+ int bpp, xoff, yoff;
+ pixman_image_t *image;
+ DrawablePtr drawable;
+
+ if (is_src && pict->pDrawable->type == DRAWABLE_WINDOW)
+ drawable = copy_drawable (pict->pDrawable);
+ else
+ drawable = pict->pDrawable;
+
+ fbGetDrawable (drawable, bits, stride, bpp, xoff, yoff);
+
+ bits = (FbBits*)((CARD8*)bits +
+ (drawable->y + yoff) * stride * sizeof(FbBits) +
+ (drawable->x + xoff) * (bpp / 8));
+
+ image = pixman_image_create_bits (
+ pict->format, drawable->width, drawable->height,
+ (uint32_t *)bits, stride * sizeof (FbStride));
+
+
+#ifdef FB_ACCESS_WRAPPER
+#if FB_SHIFT==5
+
+ pixman_image_set_accessors (image,
+ (pixman_read_memory_func_t)wfbReadMemory,
+ (pixman_write_memory_func_t)wfbWriteMemory);
+
+#else
+
+#error The pixman library only works when FbBits is 32 bits wide
+
+#endif
+#endif
+
+ if (has_clip)
+ {
+ if (is_src)
+ {
+ if (pict->clientClipType != CT_NONE)
+ {
+ pixman_image_set_has_client_clip (image, TRUE);
+
+ pixman_region_translate (pict->clientClip,
+ pict->clipOrigin.x,
+ pict->clipOrigin.y);
+
+ pixman_image_set_clip_region (image, pict->clientClip);
+
+ pixman_region_translate (pict->clientClip,
+ - pict->clipOrigin.x,
+ - pict->clipOrigin.y);
+ }
+ }
+ else
+ {
+ pixman_region_translate (pict->pCompositeClip,
+ - pict->pDrawable->x,
+ - pict->pDrawable->y);
+
+ pixman_image_set_clip_region (image, pict->pCompositeClip);
+
+ pixman_region_translate (pict->pCompositeClip,
+ pict->pDrawable->x,
+ pict->pDrawable->y);
+ }
+ }
+
+ /* Indexed table */
+ if (pict->pFormat->index.devPrivate)
+ pixman_image_set_indexed (image, pict->pFormat->index.devPrivate);
+
+ if (drawable != pict->pDrawable)
+ pixman_image_set_destroy_function (image, destroy_drawable, drawable);
+
+ return image;
+}
+
+static void
+set_image_properties (pixman_image_t *image, PicturePtr pict)
+{
+ pixman_repeat_t repeat;
+ pixman_filter_t filter;
+
+ if (pict->transform)
+ {
+ pixman_image_set_transform (
+ image, (pixman_transform_t *)pict->transform);
+ }
+
+ switch (pict->repeatType)
+ {
+ default:
+ case RepeatNone:
+ repeat = PIXMAN_REPEAT_NONE;
+ break;
+
+ case RepeatPad:
+ repeat = PIXMAN_REPEAT_PAD;
+ break;
+
+ case RepeatNormal:
+ repeat = PIXMAN_REPEAT_NORMAL;
+ break;
+
+ case RepeatReflect:
+ repeat = PIXMAN_REPEAT_REFLECT;
+ break;
+ }
+
+ pixman_image_set_repeat (image, repeat);
+
+ if (pict->alphaMap)
+ {
+ pixman_image_t *alpha_map = image_from_pict (pict->alphaMap, TRUE, TRUE);
+
+ pixman_image_set_alpha_map (
+ image, alpha_map, pict->alphaOrigin.x, pict->alphaOrigin.y);
+
+ free_pixman_pict (pict->alphaMap, alpha_map);
+ }
+
+ pixman_image_set_component_alpha (image, pict->componentAlpha);
+
+ switch (pict->filter)
+ {
+ default:
+ case PictFilterNearest:
+ case PictFilterFast:
+ filter = PIXMAN_FILTER_NEAREST;
+ break;
+
+ case PictFilterBilinear:
+ case PictFilterGood:
+ filter = PIXMAN_FILTER_BILINEAR;
+ break;
+
+ case PictFilterConvolution:
+ filter = PIXMAN_FILTER_CONVOLUTION;
+ break;
+ }
+
+ pixman_image_set_filter (image, filter, (pixman_fixed_t *)pict->filter_params, pict->filter_nparams);
+ pixman_image_set_source_clipping (image, TRUE);
+}
+
+pixman_image_t *
+image_from_pict (PicturePtr pict,
+ Bool has_clip,
+ Bool is_src)
+{
+ pixman_image_t *image = NULL;
+
+ if (!pict)
+ return NULL;
+
+ if (pict->pDrawable)
+ {
+ image = create_bits_picture (pict, has_clip, is_src);
+ }
+ else if (pict->pSourcePict)
+ {
+ SourcePict *sp = pict->pSourcePict;
+
+ if (sp->type == SourcePictTypeSolidFill)
+ {
+ image = create_solid_fill_image (pict);
+ }
+ else
+ {
+ PictGradient *gradient = &pict->pSourcePict->gradient;
+
+ if (sp->type == SourcePictTypeLinear)
+ image = create_linear_gradient_image (gradient);
+ else if (sp->type == SourcePictTypeRadial)
+ image = create_radial_gradient_image (gradient);
+ else if (sp->type == SourcePictTypeConical)
+ image = create_conical_gradient_image (gradient);
+ }
+ }
+
+ if (image)
+ set_image_properties (image, pict);
+
+ return image;
+}
+
+void
+free_pixman_pict (PicturePtr pict, pixman_image_t *image)
+{
+ if (image && pixman_image_unref (image) && pict->pDrawable)
+ fbFinishAccess (pict->pDrawable);
+}
+
+Bool
+fbPictureInit (ScreenPtr pScreen, PictFormatPtr formats, int nformats)
+{
+
+#ifdef RENDER
+
+ PictureScreenPtr ps;
+
+ if (!miPictureInit (pScreen, formats, nformats))
+ return FALSE;
+ ps = GetPictureScreen(pScreen);
+ ps->Composite = fbComposite;
+ ps->Glyphs = miGlyphs;
+ ps->CompositeRects = miCompositeRects;
+ ps->RasterizeTrapezoid = fbRasterizeTrapezoid;
+ ps->AddTraps = fbAddTraps;
+ ps->AddTriangles = fbAddTriangles;
+
+#endif /* RENDER */
+
+ return TRUE;
+}
diff --git a/xorg-server/fb/fbpixmap.c b/xorg-server/fb/fbpixmap.c index 311da9e62..c4c2c4aa7 100644 --- a/xorg-server/fb/fbpixmap.c +++ b/xorg-server/fb/fbpixmap.c @@ -323,11 +323,7 @@ fbPixmapToRegion(PixmapPtr pPix) #ifdef FB_DEBUG -#ifndef WIN32 #include <stdio.h> -#else -#include <dbg.h> -#endif static Bool fbValidateBits (FbStip *bits, int stride, FbStip data) @@ -336,12 +332,7 @@ fbValidateBits (FbStip *bits, int stride, FbStip data) { if (*bits != data) { -#ifdef WIN32 - NCD_DEBUG ((DEBUG_FAILURE, "fdValidateBits failed at 0x%x (is 0x%x want 0x%x)", - bits, *bits, data)); -#else - fprintf (stderr, "fbValidateBits failed\n"); -#endif + fprintf (stderr, "fbValidateBits failed at 0x%x (is 0x%x want 0x%x)\n",bits, *bits, data); return FALSE; } bits++; diff --git a/xorg-server/fb/makefile b/xorg-server/fb/makefile new file mode 100644 index 000000000..717c07332 --- /dev/null +++ b/xorg-server/fb/makefile @@ -0,0 +1,37 @@ +
+LIBRARY=libfb
+
+CCFLAGS:=$(CCFLAGS:-RTCc=)
+
+
+CSRCS = \
+ fb24_32.c \
+ fballpriv.c \
+ fbarc.c \
+ fbbits.c \
+ fbblt.c \
+ fbbltone.c \
+ fbcopy.c \
+ fbfill.c \
+ fbfillrect.c \
+ fbfillsp.c \
+ fbgc.c \
+ fbgetsp.c \
+ fbglyph.c \
+ fbimage.c \
+ fbline.c \
+ fboverlay.c \
+ fbpict.c \
+ fbpixmap.c \
+ fbpoint.c \
+ fbpush.c \
+ fbscreen.c \
+ fbseg.c \
+ fbsetsp.c \
+ fbsolid.c \
+ fbstipple.c \
+ fbtile.c \
+ fbtrap.c \
+ fbutil.c \
+ fbwindow.c \
+ fbcmap_mi.c
diff --git a/xorg-server/fonts.src/100dpi/makefile b/xorg-server/fonts.src/100dpi/makefile new file mode 100644 index 000000000..24057f7e6 --- /dev/null +++ b/xorg-server/fonts.src/100dpi/makefile @@ -0,0 +1,352 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +all: $(BDFTOPCF) + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\100dpi + +BDF2UCS_FONT_FILES = \ + lutBS08 \ + lutBS10 \ + lutBS12 \ + lutBS14 \ + lutBS18 \ + lutBS19 \ + lutBS24 \ + lutRS08 \ + lutRS10 \ + lutRS12 \ + lutRS14 \ + lutRS18 \ + lutRS19 \ + lutRS24 \ + lubB08 \ + lubB10 \ + lubB12 \ + lubB14 \ + lubB18 \ + lubB19 \ + lubB24 \ + lubBI08 \ + lubBI10 \ + lubBI12 \ + lubBI14 \ + lubBI18 \ + lubBI19 \ + lubBI24 \ + lubI08 \ + lubI10 \ + lubI12 \ + lubI14 \ + lubI18 \ + lubI19 \ + lubI24 \ + luBIS08 \ + luBIS10 \ + luBIS12 \ + luBIS14 \ + luBIS18 \ + luBIS19 \ + luBIS24 \ + lubR08 \ + lubR10 \ + lubR12 \ + lubR14 \ + lubR18 \ + lubR19 \ + lubR24 \ + luBS08 \ + luBS10 \ + luBS12 \ + luBS14 \ + luBS18 \ + luBS19 \ + luBS24 \ + luIS08 \ + luIS10 \ + luIS12 \ + luIS14 \ + luIS18 \ + luIS19 \ + luIS24 \ + luRS08 \ + luRS10 \ + luRS12 \ + luRS14 \ + luRS18 \ + luRS19 \ + luRS24 \ + UTB___10 \ + UTB___12 \ + UTB___14 \ + UTB___18 \ + UTB___24 \ + UTBI__10 \ + UTBI__12 \ + UTBI__14 \ + UTBI__18 \ + UTBI__24 \ + UTI___10 \ + UTI___12 \ + UTI___14 \ + UTI___18 \ + UTI___24 \ + UTRG__10 \ + UTRG__12 \ + UTRG__14 \ + UTRG__18 \ + UTRG__24 \ + courB08 \ + courB10 \ + courB12 \ + courB14 \ + courB18 \ + courB24 \ + courBO08 \ + courBO10 \ + courBO12 \ + courBO14 \ + courBO18 \ + courBO24 \ + courO08 \ + courO10 \ + courO12 \ + courO14 \ + courO18 \ + courO24 \ + courR08 \ + courR10 \ + courR12 \ + courR14 \ + courR18 \ + courR24 \ + helvB08 \ + helvB10 \ + helvB12 \ + helvB14 \ + helvB18 \ + helvB24 \ + helvBO08 \ + helvBO10 \ + helvBO12 \ + helvBO14 \ + helvBO18 \ + helvBO24 \ + helvO08 \ + helvO10 \ + helvO12 \ + helvO14 \ + helvO18 \ + helvO24 \ + helvR08 \ + helvR10 \ + helvR12 \ + helvR14 \ + helvR18 \ + helvR24 \ + ncenB08 \ + ncenB10 \ + ncenB12 \ + ncenB14 \ + ncenB18 \ + ncenB24 \ + ncenBI08 \ + ncenBI10 \ + ncenBI12 \ + ncenBI14 \ + ncenBI18 \ + ncenBI24 \ + ncenI08 \ + ncenI10 \ + ncenI12 \ + ncenI14 \ + ncenI18 \ + ncenI24 \ + ncenR08 \ + ncenR10 \ + ncenR12 \ + ncenR14 \ + ncenR18 \ + ncenR24 \ + timB08 \ + timB10 \ + timB12 \ + timB14 \ + timB18 \ + timB24 \ + timBI08 \ + timBI10 \ + timBI12 \ + timBI14 \ + timBI18 \ + timBI24 \ + timI08 \ + timI10 \ + timI12 \ + timI14 \ + timI18 \ + timI24 \ + timR08 \ + timR10 \ + timR12 \ + timR14 \ + timR18 \ + timR24 +EXTRA_FONT_FILES = \ + symb08 \ + symb10 \ + symb12 \ + symb14 \ + symb18 \ + symb24 \ + charB08 \ + charB10 \ + charB12 \ + charB14 \ + charB18 \ + charB24 \ + charBI08 \ + charBI10 \ + charBI12 \ + charBI14 \ + charBI18 \ + charBI24 \ + charI08 \ + charI10 \ + charI12 \ + charI14 \ + charI18 \ + charI24 \ + charR08 \ + charR10 \ + charR12 \ + charR14 \ + charR18 \ + charR24 \ + tech14 \ + techB14 \ + term14 \ + termB14 +FONT_FILES = $(BDF2UCS_FONT_FILES) $(EXTRA_FONT_FILES) + +BDF_FILES = $(FONT_FILES:%=%.bdf) +PCF_FILES = $(FONT_FILES:%=$(DESTDIR)\%.pcf.gz) + +ISO8859_1_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-1.pcf.gz) + +ISO8859_2_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-2.pcf.gz) + +ISO8859_3_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-3.pcf.gz) + +ISO8859_4_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-4.pcf.gz) + +ISO8859_9_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-9.pcf.gz) + +ISO8859_10_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-10.pcf.gz) + +ISO8859_13_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-13.pcf.gz) + +ISO8859_14_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-14.pcf.gz) + +ISO8859_15_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-15.pcf.gz) + +UTIL_DIR = ..\font-util +UCS2ANY = $(UTIL_DIR)\$(OBJDIR)\ucs2any.exe + +load_makefile $(UTIL_DIR)\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\%-ISO8859-1.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-1.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-1 ISO8859-1 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-1.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-1.bdf) + +$(DESTDIR)\%-ISO8859-2.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-2.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-2 ISO8859-2 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-2.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-2.bdf) + +$(DESTDIR)\%-ISO8859-3.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-3.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-3 ISO8859-3 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-3.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-3.bdf) + +$(DESTDIR)\%-ISO8859-4.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-4.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-4 ISO8859-4 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-4.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-4.bdf) + +$(DESTDIR)\%-ISO8859-9.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-9.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-9 ISO8859-9 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-9.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-9.bdf) + +$(DESTDIR)\%-ISO8859-10.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-10.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-10 ISO8859-10 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-10.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-10.bdf) + +$(DESTDIR)\%-ISO8859-13.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-13.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-13 ISO8859-13 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-13.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-13.bdf) + +$(DESTDIR)\%-ISO8859-14.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-14.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-14 ISO8859-14 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-14.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-14.bdf) + +$(DESTDIR)\%-ISO8859-15.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-15.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-15 ISO8859-15 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-15.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-15.bdf) + +font_DATA = \ + $(PCF_FILES) \ + $(ISO8859_1_PCF_FILES) \ + $(ISO8859_2_PCF_FILES) \ + $(ISO8859_3_PCF_FILES) \ + $(ISO8859_4_PCF_FILES) \ + $(ISO8859_9_PCF_FILES) \ + $(ISO8859_10_PCF_FILES) \ + $(ISO8859_13_PCF_FILES) \ + $(ISO8859_14_PCF_FILES) \ + $(ISO8859_15_PCF_FILES) + +all: $(DESTDIR) $(UCS2ANY) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir $(DESTDIR)\fonts.alias + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . + +$(DESTDIR)\fonts.alias: fonts.alias + copy $< $@ + diff --git a/xorg-server/fonts.src/75dpi/makefile b/xorg-server/fonts.src/75dpi/makefile new file mode 100644 index 000000000..e5c8002f0 --- /dev/null +++ b/xorg-server/fonts.src/75dpi/makefile @@ -0,0 +1,348 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +all: $(BDFTOPCF) + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\75dpi + +BDF2UCS_FONT_FILES = \ + lutBS08 \ + lutBS10 \ + lutBS12 \ + lutBS14 \ + lutBS18 \ + lutBS19 \ + lutBS24 \ + lutRS08 \ + lutRS10 \ + lutRS12 \ + lutRS14 \ + lutRS18 \ + lutRS19 \ + lutRS24 \ + UTB___10 \ + UTB___12 \ + UTB___14 \ + UTB___18 \ + UTB___24 \ + UTBI__10 \ + UTBI__12 \ + UTBI__14 \ + UTBI__18 \ + UTBI__24 \ + UTI___10 \ + UTI___12 \ + UTI___14 \ + UTI___18 \ + UTI___24 \ + UTRG__10 \ + UTRG__12 \ + UTRG__14 \ + UTRG__18 \ + UTRG__24 \ + courB08 \ + courB10 \ + courB12 \ + courB14 \ + courB18 \ + courB24 \ + courBO08 \ + courBO10 \ + courBO12 \ + courBO14 \ + courBO18 \ + courBO24 \ + courO08 \ + courO10 \ + courO12 \ + courO14 \ + courO18 \ + courO24 \ + courR08 \ + courR10 \ + courR12 \ + courR14 \ + courR18 \ + courR24 \ + helvB08 \ + helvB10 \ + helvB12 \ + helvB14 \ + helvB18 \ + helvB24 \ + helvBO08 \ + helvBO10 \ + helvBO12 \ + helvBO14 \ + helvBO18 \ + helvBO24 \ + helvO08 \ + helvO10 \ + helvO12 \ + helvO14 \ + helvO18 \ + helvO24 \ + helvR08 \ + helvR10 \ + helvR12 \ + helvR14 \ + helvR18 \ + helvR24 \ + ncenB08 \ + ncenB10 \ + ncenB12 \ + ncenB14 \ + ncenB18 \ + ncenB24 \ + ncenBI08 \ + ncenBI10 \ + ncenBI12 \ + ncenBI14 \ + ncenBI18 \ + ncenBI24 \ + ncenI08 \ + ncenI10 \ + ncenI12 \ + ncenI14 \ + ncenI18 \ + ncenI24 \ + ncenR08 \ + ncenR10 \ + ncenR12 \ + ncenR14 \ + ncenR18 \ + ncenR24 \ + timB08 \ + timB10 \ + timB12 \ + timB14 \ + timB18 \ + timB24 \ + timBI08 \ + timBI10 \ + timBI12 \ + timBI14 \ + timBI18 \ + timBI24 \ + timI08 \ + timI10 \ + timI12 \ + timI14 \ + timI18 \ + timI24 \ + timR08 \ + timR10 \ + timR12 \ + timR14 \ + timR18 \ + timR24 \ + lubB08 \ + lubB10 \ + lubB12 \ + lubB14 \ + lubB18 \ + lubB19 \ + lubB24 \ + lubBI08 \ + lubBI10 \ + lubBI12 \ + lubBI14 \ + lubBI18 \ + lubBI19 \ + lubBI24 \ + lubI08 \ + lubI10 \ + lubI12 \ + lubI14 \ + lubI18 \ + lubI19 \ + lubI24 \ + luBIS08 \ + luBIS10 \ + luBIS12 \ + luBIS14 \ + luBIS18 \ + luBIS19 \ + luBIS24 \ + lubR08 \ + lubR10 \ + lubR12 \ + lubR14 \ + lubR18 \ + lubR19 \ + lubR24 \ + luBS08 \ + luBS10 \ + luBS12 \ + luBS14 \ + luBS18 \ + luBS19 \ + luBS24 \ + luIS08 \ + luIS10 \ + luIS12 \ + luIS14 \ + luIS18 \ + luIS19 \ + luIS24 \ + luRS08 \ + luRS10 \ + luRS12 \ + luRS14 \ + luRS18 \ + luRS19 \ + luRS24 +EXTRA_FONT_FILES = \ + charB08 \ + charB10 \ + charB12 \ + charB14 \ + charB18 \ + charB24 \ + charBI08 \ + charBI10 \ + charBI12 \ + charBI14 \ + charBI18 \ + charBI24 \ + charI08 \ + charI10 \ + charI12 \ + charI14 \ + charI18 \ + charI24 \ + charR08 \ + charR10 \ + charR12 \ + charR14 \ + charR18 \ + charR24 \ + tech14 \ + techB14 \ + term14 \ + termB14 \ + symb08 \ + symb10 \ + symb12 \ + symb14 \ + symb18 \ + symb24 +FONT_FILES = $(BDF2UCS_FONT_FILES) $(EXTRA_FONT_FILES) + +BDF_FILES = $(FONT_FILES:%=%.bdf) +PCF_FILES = $(FONT_FILES:%=$(DESTDIR)\%.pcf.gz) + +ISO8859_1_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-1.pcf.gz) + +ISO8859_2_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-2.pcf.gz) + +ISO8859_3_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-3.pcf.gz) + +ISO8859_4_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-4.pcf.gz) + +ISO8859_9_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-9.pcf.gz) + +ISO8859_10_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-10.pcf.gz) + +ISO8859_13_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-13.pcf.gz) + +ISO8859_14_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-14.pcf.gz) + +ISO8859_15_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-15.pcf.gz) + +UTIL_DIR = ..\font-util +UCS2ANY = $(UTIL_DIR)\$(OBJDIR)\ucs2any.exe + +load_makefile $(UTIL_DIR)\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\%-ISO8859-1.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-1.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-1 ISO8859-1 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-1.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-1.bdf) + +$(DESTDIR)\%-ISO8859-2.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-2.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-2 ISO8859-2 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-2.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-2.bdf) + +$(DESTDIR)\%-ISO8859-3.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-3.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-3 ISO8859-3 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-3.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-3.bdf) + +$(DESTDIR)\%-ISO8859-4.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-4.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-4 ISO8859-4 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-4.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-4.bdf) + +$(DESTDIR)\%-ISO8859-9.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-9.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-9 ISO8859-9 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-9.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-9.bdf) + +$(DESTDIR)\%-ISO8859-10.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-10.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-10 ISO8859-10 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-10.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-10.bdf) + +$(DESTDIR)\%-ISO8859-13.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-13.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-13 ISO8859-13 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-13.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-13.bdf) + +$(DESTDIR)\%-ISO8859-14.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-14.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-14 ISO8859-14 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-14.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-14.bdf) + +$(DESTDIR)\%-ISO8859-15.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-15.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-15 ISO8859-15 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-15.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-15.bdf) + +font_DATA = \ + $(PCF_FILES) \ + $(ISO8859_1_PCF_FILES) \ + $(ISO8859_2_PCF_FILES) \ + $(ISO8859_3_PCF_FILES) \ + $(ISO8859_4_PCF_FILES) \ + $(ISO8859_9_PCF_FILES) \ + $(ISO8859_10_PCF_FILES) \ + $(ISO8859_13_PCF_FILES) \ + $(ISO8859_14_PCF_FILES) \ + $(ISO8859_15_PCF_FILES) + +all: $(DESTDIR) $(UCS2ANY) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir $(DESTDIR)\fonts.alias + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . + +$(DESTDIR)\fonts.alias: fonts.alias + copy $< $@ + diff --git a/xorg-server/fonts.src/OTF/makefile b/xorg-server/fonts.src/OTF/makefile new file mode 100644 index 000000000..e15018a64 --- /dev/null +++ b/xorg-server/fonts.src/OTF/makefile @@ -0,0 +1,52 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\OTF + +FONT_FILES = \ + SyrCOMAdiabene.otf \ + SyrCOMAntioch.otf \ + SyrCOMBatnanBold.otf \ + SyrCOMBatnan.otf \ + SyrCOMCtesiphon.otf \ + SyrCOMEdessa.otf \ + SyrCOMJerusalemBold.otf \ + SyrCOMJerusalemItalic.otf \ + SyrCOMJerusalem.otf \ + SyrCOMJerusalemOutline.otf \ + SyrCOMKharput.otf \ + SyrCOMMalankara.otf \ + SyrCOMMardinBold.otf \ + SyrCOMMardin.otf \ + SyrCOMMidyat.otf \ + SyrCOMNisibin.otf \ + SyrCOMNisibinOutline.otf \ + SyrCOMQenNeshrin.otf \ + SyrCOMTalada.otf \ + SyrCOMTurAbdin.otf \ + SyrCOMUrhoyBold.otf \ + SyrCOMUrhoy.otf + +fontdir = . +font_DATA = $(FONT_FILES:%=$(DESTDIR)\%) + +all: $(DESTDIR) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . +# $(FCCACHE) $(DESTDIR) + +$(DESTDIR)\%.otf: %.otf + copy $< $@ diff --git a/xorg-server/fonts.src/Speedo/makefile b/xorg-server/fonts.src/Speedo/makefile new file mode 100644 index 000000000..87f66559a --- /dev/null +++ b/xorg-server/fonts.src/Speedo/makefile @@ -0,0 +1,37 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\Speedo + +FONT_FILES = \ + font0419.spd \ + font0582.spd \ + font0583.spd \ + font0611.spd \ + font0648.spd \ + font0649.spd \ + font0709.spd \ + font0710.spd \ + fonts.scale + +fontdir = . +font_DATA = $(FONT_FILES:%=$(DESTDIR)\%) + +all: $(DESTDIR) $(DESTDIR)\fonts.dir $(DESTDIR)\fonts.scale + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . + +$(DESTDIR)\%.spd: %.spd + copy $< $@ + +$(DESTDIR)\%.scale: %.scale + copy $< $@ diff --git a/xorg-server/fonts.src/TTF/makefile b/xorg-server/fonts.src/TTF/makefile new file mode 100644 index 000000000..39b753ab1 --- /dev/null +++ b/xorg-server/fonts.src/TTF/makefile @@ -0,0 +1,53 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\TTF + + +FONT_FILES = \ + luximbi.ttf \ + luximb.ttf \ + luximri.ttf \ + luximr.ttf \ + luxirbi.ttf \ + luxirb.ttf \ + luxirri.ttf \ + luxirr.ttf \ + luxisbi.ttf \ + luxisb.ttf \ + luxisri.ttf \ + luxisr.ttf \ + Vera.ttf \ + VeraBd.ttf \ + VeraBI.ttf \ + VeraIt.ttf \ + VeraMoBd.ttf \ + VeraMoBI.ttf \ + VeraMoIt.ttf \ + VeraMono.ttf \ + VeraSe.ttf \ + VeraSeBd.ttf + +fontdir = . +font_DATA = $(FONT_FILES:%=$(DESTDIR)\%) + +all: $(DESTDIR) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . +# $(FCCACHE) $(DESTDIR) + +$(DESTDIR)\%.ttf: %.ttf + copy $< $@ diff --git a/xorg-server/fonts.src/Type1/makefile b/xorg-server/fonts.src/Type1/makefile new file mode 100644 index 000000000..bc2b6b06f --- /dev/null +++ b/xorg-server/fonts.src/Type1/makefile @@ -0,0 +1,93 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\Type1 + +FONT_FILES = \ + cursor.pfa \ + UTB_____.afm \ + UTBI____.afm \ + UTBI____.pfa \ + UTB_____.pfa \ + UTI_____.afm \ + UTI_____.pfa \ + UTRG____.afm \ + UTRG____.pfa \ + cour.afm \ + courb.afm \ + courbi.afm \ + courbi.pfa \ + courb.pfa \ + couri.afm \ + couri.pfa \ + cour.pfa \ + l047013t.afm \ + l047013t.pfa \ + l047016t.afm \ + l047016t.pfa \ + l047033t.afm \ + l047033t.pfa \ + l047036t.afm \ + l047036t.pfa \ + l048013t.afm \ + l048013t.pfa \ + l048016t.afm \ + l048016t.pfa \ + l048033t.afm \ + l048033t.pfa \ + l048036t.afm \ + l048036t.pfa \ + l049013t.afm \ + l049013t.pfa \ + l049016t.afm \ + l049016t.pfa \ + l049033t.afm \ + l049033t.pfa \ + l049036t.afm \ + l049036t.pfa \ + c0419bt_.afm \ + c0419bt_.pfb \ + c0582bt_.afm \ + c0582bt_.pfb \ + c0583bt_.afm \ + c0583bt_.pfb \ + c0611bt_.afm \ + c0611bt_.pfb \ + c0632bt_.afm \ + c0632bt_.pfb \ + c0633bt_.afm \ + c0633bt_.pfb \ + c0648bt_.afm \ + c0648bt_.pfb \ + c0649bt_.afm \ + c0649bt_.pfb + +fontdir = . +font_DATA = $(FONT_FILES:%=$(DESTDIR)\%) + +all: $(DESTDIR) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . +# $(FCCACHE) $(DESTDIR) + +$(DESTDIR)\%.afm: %.afm + copy $< $@ + +$(DESTDIR)\%.pfb: %.pfb + copy $< $@ + +$(DESTDIR)\%.pfa: %.pfa + copy $< $@ diff --git a/xorg-server/fonts.src/cyrillic/makefile b/xorg-server/fonts.src/cyrillic/makefile new file mode 100644 index 000000000..47a455a17 --- /dev/null +++ b/xorg-server/fonts.src/cyrillic/makefile @@ -0,0 +1,114 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\cyrillic + +FONT_FILES = \ + proof9x16 \ + koi12x24b \ + koi12x24 \ + koi5x8 \ + koi6x13b \ + koi6x13 \ + koi6x9 \ + koi7x14b \ + koi7x14 \ + koi8x13 \ + koi8x16b \ + koi8x16 \ + koi9x15b \ + koi9x15 \ + koi9x18b \ + koi9x18 \ + screen8x16b \ + screen8x16 \ + crox1cb \ + crox1c \ + crox1cbo \ + crox1co \ + crox1hb \ + crox1h \ + crox1hbo \ + crox1ho \ + crox1tb \ + crox1t \ + crox1tbo \ + crox1to \ + crox2cb \ + crox2c \ + crox2cbo \ + crox2co \ + crox2hb \ + crox2h \ + crox2hbo \ + crox2ho \ + crox2tb \ + crox2t \ + crox2tbo \ + crox2to \ + crox3cb \ + crox3c \ + crox3cbo \ + crox3co \ + crox3hb \ + crox3h \ + crox3hbo \ + crox3ho \ + crox3tb \ + crox3t \ + crox3tbo \ + crox3to \ + crox4hb \ + crox4h \ + crox4hbo \ + crox4ho \ + crox4tb \ + crox4t \ + crox4tbo \ + crox4to \ + crox5hb \ + crox5h \ + crox5hbo \ + crox5ho \ + crox5tb \ + crox5t \ + crox5tbo \ + crox5to \ + crox6hb \ + crox6h \ + crox6hbo \ + crox6ho \ + crox6tb \ + crox6t \ + crox6tbo \ + crox6to \ + koi10x16b \ + koi10x20 \ + koi6x10 \ + koinil2 + +BDF_FILES = $(FONT_FILES:%=%.bdf) +PCF_FILES = $(FONT_FILES:%=$(DESTDIR)\%.pcf.gz) + +font_DATA = $(PCF_FILES) + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +all: $(DESTDIR) $(MKFONTSCALE) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir $(DESTDIR)\fonts.alias + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . + + +$(DESTDIR)\fonts.alias: fonts.alias + copy $< $@ diff --git a/xorg-server/fonts.src/encodings/large/makefile b/xorg-server/fonts.src/encodings/large/makefile new file mode 100644 index 000000000..0f168d046 --- /dev/null +++ b/xorg-server/fonts.src/encodings/large/makefile @@ -0,0 +1,40 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\encodings\large + +ENCODING_FILES = \ + big5.eten-0.enc \ + big5hkscs-0.enc \ + cns11643-1.enc \ + cns11643-2.enc \ + cns11643-3.enc \ + gb18030-0.enc \ + gb18030.2000-0.enc \ + gb18030.2000-1.enc \ + gb2312.1980-0.enc \ + gbk-0.enc \ + jisx0201.1976-0.enc \ + jisx0208.1990-0.enc \ + jisx0212.1990-0.enc \ + ksc5601.1987-0.enc \ + ksc5601.1992-3.enc \ + sun.unicode.india-0.enc + +COMPRESSED = $(ENCODING_FILES:%=$(DESTDIR)\%.gz) + +DATA_FILES = $(COMPRESSED) + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +all: $(DESTDIR)\encodings.dir + +$(DESTDIR)\encodings.dir: $(DATA_FILES) $(MKFONTSCALE) + cd "$(DESTDIR)" & $(MKFONTSCALE) -b -s -l -n -r -p .\large -e . . + + diff --git a/xorg-server/fonts.src/encodings/makefile b/xorg-server/fonts.src/encodings/makefile new file mode 100644 index 000000000..548d56ce5 --- /dev/null +++ b/xorg-server/fonts.src/encodings/makefile @@ -0,0 +1,63 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif +load_makefile large\makefile MAKESERVER=0 DEBUG=0 + +INC_BDF_RULES=1 + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\encodings + +ENCODING_FILES = \ + adobe-dingbats.enc \ + adobe-standard.enc \ + adobe-symbol.enc \ + armscii-8.enc \ + ascii-0.enc \ + dec-special.enc \ + ibm-cp437.enc \ + ibm-cp850.enc \ + ibm-cp852.enc \ + ibm-cp866.enc \ + iso8859-11.enc \ + iso8859-13.enc \ + iso8859-16.enc \ + iso8859-6.16.enc \ + iso8859-6.8x.enc \ + microsoft-cp1250.enc \ + microsoft-cp1251.enc \ + microsoft-cp1252.enc \ + microsoft-cp1253.enc \ + microsoft-cp1254.enc \ + microsoft-cp1255.enc \ + microsoft-cp1256.enc \ + microsoft-cp1257.enc \ + microsoft-cp1258.enc \ + microsoft-win3.1.enc \ + mulearabic-0.enc \ + mulearabic-1.enc \ + mulearabic-2.enc \ + mulelao-1.enc \ + suneu-greek.enc \ + tcvn-0.enc \ + tis620-2.enc \ + viscii1.1-1.enc + +COMPRESSED = $(ENCODING_FILES:%=$(DESTDIR)\%.gz) + +DATA_FILES = $(COMPRESSED) + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\encodings.dir: $(DATA_FILES) $(DESTDIR)\large\encodings.dir $(MKFONTSCALE) + cd "$(DESTDIR)" & $(MKFONTSCALE) -b -s -l -n -r -p . -e . -e large . + +all: $(DESTDIR)\encodings.dir + +.PHONY: cleanthis +cleanthis: + del -e $(DESTDIR) + +clean: cleanthis + diff --git a/xorg-server/fonts.src/font-util/makefile b/xorg-server/fonts.src/font-util/makefile new file mode 100644 index 000000000..13e196a03 --- /dev/null +++ b/xorg-server/fonts.src/font-util/makefile @@ -0,0 +1,5 @@ +TTYAPP = ucs2any + +CSRCS = ucs2any.c + +DEFINES += NEED_BASENAME diff --git a/xorg-server/fonts.src/makefile b/xorg-server/fonts.src/makefile new file mode 100644 index 000000000..9dce92d67 --- /dev/null +++ b/xorg-server/fonts.src/makefile @@ -0,0 +1 @@ +SUBDIRS=font-util 75dpi 100dpi cyrillic encodings misc OTF Speedo TTF Type1 diff --git a/xorg-server/fonts.src/misc/makefile b/xorg-server/fonts.src/misc/makefile new file mode 100644 index 000000000..290ae173a --- /dev/null +++ b/xorg-server/fonts.src/misc/makefile @@ -0,0 +1,340 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +INC_BDF_RULES=1 + +all: $(BDFTOPCF) + +DESTDIR=$(MHMAKECONF)\xorg-server\fonts\misc + +BDF2UCS_FONT_FILES = \ + clR6x12 \ + 4x6 \ + 5x7 \ + 5x8 \ + 6x9 \ + 6x10 \ + 6x12 \ + 6x13 \ + 6x13B \ + 6x13O \ + 7x13 \ + 7x13B \ + 7x13O \ + 7x14 \ + 7x14B \ + 8x13 \ + 8x13B \ + 8x13O \ + 9x15 \ + 9x15B \ + 9x18 \ + 9x18B \ + 10x20 +BDF2UCS_8_FONT_FILES = \ + clR6x12 \ + 4x6 \ + 5x7 \ + 5x8 \ + 6x9 \ + 6x10 \ + 6x12 \ + 6x13 \ + 6x13B \ + 7x13 \ + 7x13B \ + 7x14 \ + 7x14B \ + 8x13 \ + 8x13B \ + 9x15 \ + 9x15B \ + 9x18 \ + 9x18B \ + 10x20 +BDF2UCS_11_FONT_FILES = \ + 6x13 \ + 7x13 \ + 7x13B \ + 7x13O \ + 7x14 \ + 7x14B \ + 9x15 \ + 9x15B \ + 9x18 \ + 10x20 +BDF2UCS_KOI8_FONT_FILES = \ + clR6x12 \ + 4x6 \ + 5x7 \ + 5x8 \ + 6x9 \ + 6x10 \ + 6x12 \ + 6x13 \ + 7x13 \ + 7x14 \ + 8x13 \ + 9x15 \ + 9x18 \ + 10x20 +BDF2UCS_JISX0201_FONT_FILES = \ + 7x14 +EXTRA_FONT_FILES = \ + 12x13ja \ + 18x18ja \ + 18x18ko \ + k14 \ + nil2 \ + micro \ + jiskan16 \ + jiskan24 \ + gb16fs \ + gb16st \ + gb24st \ + deccurs \ + decsess \ + arabic24 \ + cursor \ + hanglg16 \ + hanglm16 \ + hanglm24 \ + cu12 \ + cu-alt12 \ + cu-arabic12 \ + cuarabic12 \ + cu-devnag12 \ + cudevnag12 \ + cu-lig12 \ + cu-pua12 \ + clB6x10 \ + clB6x12 \ + clB8x10 \ + clB8x12 \ + clB8x13 \ + clB8x14 \ + clB8x16 \ + clB8x8 \ + clB9x15 \ + clI6x12 \ + clI8x8 \ + clR4x6 \ + clR5x10 \ + clR5x6 \ + clR5x8 \ + clR6x10 \ + clR6x13 \ + clR6x6 \ + clR6x8 \ + clR7x10 \ + clR7x12 \ + clR7x14 \ + clR7x8 \ + clR8x10 \ + clR8x12 \ + clR8x13 \ + clR8x14 \ + clR8x16 \ + clR8x8 \ + clR9x15 \ + 12x24 \ + 12x24rk \ + 8x16 \ + 8x16rk \ + olcursor \ + olgl10 \ + olgl12 \ + olgl14 \ + olgl19 + +FONT_FILES = $(BDF2UCS_FONT_FILES) $(EXTRA_FONT_FILES) + +BDF_FILES = $(FONT_FILES:%=%.bdf) +PCF_FILES = $(FONT_FILES:%=$(DESTDIR)\%.pcf.gz) + +ISO8859_1_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-1.pcf.gz) + +ISO8859_2_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-2.pcf.gz) + +ISO8859_3_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-3.pcf.gz) + +ISO8859_4_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-4.pcf.gz) + +ISO8859_5_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-5.pcf.gz) + +ISO8859_7_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-7.pcf.gz) + +ISO8859_8_PCF_FILES = $(BDF2UCS_8_FONT_FILES:%=$(DESTDIR)\%-ISO8859-8.pcf.gz) + +ISO8859_9_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-9.pcf.gz) + +ISO8859_10_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-10.pcf.gz) + +ISO8859_11_PCF_FILES = $(BDF2UCS_11_FONT_FILES:%=$(DESTDIR)\%-ISO8859-11.pcf.gz) + +ISO8859_13_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-13.pcf.gz) + +ISO8859_14_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-14.pcf.gz) + +ISO8859_15_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-15.pcf.gz) + +ISO8859_16_PCF_FILES = $(BDF2UCS_FONT_FILES:%=$(DESTDIR)\%-ISO8859-16.pcf.gz) + +KOI8_R_PCF_FILES = $(BDF2UCS_KOI8_FONT_FILES:%=$(DESTDIR)\%-KOI8-R.pcf.gz) + +JISX0201_PCF_FILES = $(BDF2UCS_JISX0201_FONT_FILES:%=$(DESTDIR)\%-JISX0201.1976-0.pcf.gz) + +UTIL_DIR = ..\font-util +UCS2ANY = $(UTIL_DIR)\$(OBJDIR)\ucs2any.exe + +load_makefile $(UTIL_DIR)\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\%-ISO8859-1.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-1.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-1 ISO8859-1 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-1.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-1.bdf) + +$(DESTDIR)\%-ISO8859-2.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-2.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-2 ISO8859-2 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-2.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-2.bdf) + +$(DESTDIR)\%-ISO8859-3.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-3.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-3 ISO8859-3 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-3.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-3.bdf) + +$(DESTDIR)\%-ISO8859-4.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-4.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-4 ISO8859-4 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-4.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-4.bdf) + +$(DESTDIR)\%-ISO8859-5.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-5.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-5 ISO8859-5 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-5.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-5.bdf) + +$(DESTDIR)\%-ISO8859-7.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-7.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-7 ISO8859-7 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-7.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-7.bdf) + +$(DESTDIR)\%-ISO8859-8.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-8.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-8 ISO8859-8 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-8.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-8.bdf) + +$(DESTDIR)\%-ISO8859-9.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-9.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-9 ISO8859-9 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-9.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-9.bdf) + +$(DESTDIR)\%-ISO8859-10.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-10.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-10 ISO8859-10 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-10.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-10.bdf) + +$(DESTDIR)\%-ISO8859-11.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-11.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-11 ISO8859-11 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-11.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-11.bdf) + +$(DESTDIR)\%-ISO8859-13.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-13.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-13 ISO8859-13 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-13.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-13.bdf) + +$(DESTDIR)\%-ISO8859-14.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-14.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-14 ISO8859-14 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-14.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-14.bdf) + +$(DESTDIR)\%-ISO8859-15.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-15.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-15 ISO8859-15 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-15.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-15.bdf) + +$(DESTDIR)\%-ISO8859-16.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-ISO8859-16.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-ISO8859-16 ISO8859-16 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-ISO8859-16.bdf) | gzip > $@ + @del $(<:%.bdf=%-ISO8859-16.bdf) + +$(DESTDIR)\%-KOI8-R.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-KOI8-R.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-KOI8-R KOI8-R + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-KOI8-R.bdf) | gzip > $@ + @del $(<:%.bdf=%-KOI8-R.bdf) + +$(DESTDIR)\%-JISX0201.1976-0.pcf.gz: %.bdf + @del -e $(<:%.bdf=%-JISX0201.1976-0.bdf) + $(UCS2ANY) $< $(UTIL_DIR)\map-JISX0201.1976-0 JISX0201.1976-0 + @del -e $@ + $(BDFTOPCF) -t $(<:%.bdf=%-JISX0201.1976-0.bdf) | gzip > $@ + @del $(<:%.bdf=%-JISX0201.1976-0.bdf) + +font_DATA = \ + $(PCF_FILES) \ + $(ISO8859_1_PCF_FILES) \ + $(ISO8859_2_PCF_FILES) \ + $(ISO8859_3_PCF_FILES) \ + $(ISO8859_4_PCF_FILES) \ + $(ISO8859_5_PCF_FILES) \ + $(ISO8859_7_PCF_FILES) \ + $(ISO8859_8_PCF_FILES) \ + $(ISO8859_9_PCF_FILES) \ + $(ISO8859_10_PCF_FILES) \ + $(ISO8859_11_PCF_FILES) \ + $(ISO8859_13_PCF_FILES) \ + $(ISO8859_14_PCF_FILES) \ + $(ISO8859_15_PCF_FILES) \ + $(ISO8859_16_PCF_FILES) \ + $(KOI8_R_PCF_FILES) \ + $(JISX0201_PCF_FILES) + +all: $(DESTDIR) $(UCS2ANY) $(DESTDIR)\fonts.scale $(DESTDIR)\fonts.dir $(DESTDIR)\fonts.alias + +MKFONTSCALE=$(MHMAKECONF)\mkfontscale\$(OBJDIR)\mkfontscale.exe + +load_makefile $(MHMAKECONF)\mkfontscale\makefile MAKESERVER=0 DEBUG=$(DEBUG) + +$(DESTDIR)\fonts.scale: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) . + +$(DESTDIR)\fonts.dir: $(font_DATA) $(MKFONTSCALE) + del -e $@ + cd $(DESTDIR) & $(MKFONTSCALE) -b -s -l . + +$(DESTDIR)\fonts.alias: fonts.alias + copy $< $@ + diff --git a/xorg-server/glx/glheader.h b/xorg-server/glx/glheader.h new file mode 100644 index 000000000..1c0ee2c9e --- /dev/null +++ b/xorg-server/glx/glheader.h @@ -0,0 +1,24 @@ +#ifndef __GLHEADER_H__
+#define __GLHEADER_H__
+
+#define STDC_HEADERS 1
+
+#include <X11/Xwinsock.h>
+#include <X11/Xwindows.h>
+#include <assert.h>
+#define strcasecmp _stricmp
+
+#undef MINSHORT
+#undef MAXSHORT
+
+#define MINSHORT -32768
+#define MAXSHORT 32767
+
+#define PUBLIC
+
+#define GL_GLEXT_PROTOTYPES
+
+#define DRI_DRIVER_PATH "/usr/lib/dri"
+
+#endif
+
diff --git a/xorg-server/glx/glxcmds.c b/xorg-server/glx/glxcmds.c index b1061a8c2..847154718 100644 --- a/xorg-server/glx/glxcmds.c +++ b/xorg-server/glx/glxcmds.c @@ -1,2418 +1,2422 @@ -/* - * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) - * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice including the dates of first publication and - * either this permission notice or a reference to - * http://oss.sgi.com/projects/FreeB/ - * 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 - * SILICON GRAPHICS, INC. 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 Silicon Graphics, Inc. - * shall not be used in advertising or otherwise to promote the sale, use or - * other dealings in this Software without prior written authorization from - * Silicon Graphics, Inc. - */ - -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <string.h> -#include <assert.h> - -#include "glxserver.h" -#include <GL/glxtokens.h> -#include <unpack.h> -#include "g_disptab.h" -#include <pixmapstr.h> -#include <windowstr.h> -#include "glxutil.h" -#include "glxext.h" -#include "glapitable.h" -#include "glapi.h" -#include "glthread.h" -#include "dispatch.h" -#include "indirect_dispatch.h" -#include "indirect_table.h" -#include "indirect_util.h" -#include "protocol-versions.h" - -static int -validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err) -{ - /* - ** Check if screen exists. - */ - if (screen >= screenInfo.numScreens) { - client->errorValue = screen; - *err = BadValue; - return FALSE; - } - *pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - - return TRUE; -} - -static int -validGlxFBConfig(ClientPtr client, __GLXscreen *pGlxScreen, XID id, - __GLXconfig **config, int *err) -{ - __GLXconfig *m; - - for (m = pGlxScreen->fbconfigs; m != NULL; m = m->next) - if (m->fbconfigID == id) { - *config = m; - return TRUE; - } - - client->errorValue = id; - *err = __glXError(GLXBadFBConfig); - - return FALSE; -} - -static int -validGlxVisual(ClientPtr client, __GLXscreen *pGlxScreen, XID id, - __GLXconfig **config, int *err) -{ - int i; - - for (i = 0; i < pGlxScreen->numVisuals; i++) - if (pGlxScreen->visuals[i]->visualID == id) { - *config = pGlxScreen->visuals[i]; - return TRUE; - } - - client->errorValue = id; - *err = BadValue; - - return FALSE; -} - -static int -validGlxFBConfigForWindow(ClientPtr client, __GLXconfig *config, - DrawablePtr pDraw, int *err) -{ - ScreenPtr pScreen = pDraw->pScreen; - VisualPtr pVisual = NULL; - XID vid; - int i; - - vid = wVisual((WindowPtr)pDraw); - for (i = 0; i < pScreen->numVisuals; i++) { - if (pScreen->visuals[i].vid == vid) { - pVisual = &pScreen->visuals[i]; - break; - } - } - - /* FIXME: What exactly should we check here... */ - if (pVisual->class != glxConvertToXVisualType(config->visualType) || - !(config->drawableType & GLX_WINDOW_BIT)) { - client->errorValue = pDraw->id; - *err = BadMatch; - return FALSE; - } - - return TRUE; -} - -static int -validGlxContext(ClientPtr client, XID id, int access_mode, - __GLXcontext **context, int *err) -{ - *err = dixLookupResourceByType((pointer *) context, id, - __glXContextRes, client, access_mode); - if (*err != Success) { - client->errorValue = id; - if (*err == BadValue) - *err = __glXError(GLXBadContext); - return FALSE; - } - - return TRUE; -} - -static int -validGlxDrawable(ClientPtr client, XID id, int type, int access_mode, - __GLXdrawable **drawable, int *err) -{ - int rc; - - rc = dixLookupResourceByType((pointer *) drawable, id, - __glXDrawableRes, client, access_mode); - if (rc != Success && rc != BadValue) { - *err = rc; - client->errorValue = id; - return FALSE; - } - - if (rc == BadValue || - (type != GLX_DRAWABLE_ANY && type != (*drawable)->type)) { - client->errorValue = id; - switch (type) { - case GLX_DRAWABLE_WINDOW: - *err = __glXError(GLXBadWindow); - return FALSE; - case GLX_DRAWABLE_PIXMAP: - *err = __glXError(GLXBadPixmap); - return FALSE; - case GLX_DRAWABLE_PBUFFER: - *err = __glXError(GLXBadPbuffer); - return FALSE; - case GLX_DRAWABLE_ANY: - *err = __glXError(GLXBadDrawable); - return FALSE; - } - } - - return TRUE; -} - -void -__glXContextDestroy(__GLXcontext *context) -{ - __glXFlushContextCache(); -} - -static void __glXdirectContextDestroy(__GLXcontext *context) -{ - __glXContextDestroy(context); - xfree(context); -} - -static __GLXcontext *__glXdirectContextCreate(__GLXscreen *screen, - __GLXconfig *modes, - __GLXcontext *shareContext) -{ - __GLXcontext *context; - - context = xcalloc (1, sizeof (__GLXcontext)); - if (context == NULL) - return NULL; - - context->destroy = __glXdirectContextDestroy; - - return context; -} - -/** - * Create a GL context with the given properties. This routine is used - * to implement \c glXCreateContext, \c glXCreateNewContext, and - * \c glXCreateContextWithConfigSGIX. This works becuase of the hack way - * that GLXFBConfigs are implemented. Basically, the FBConfigID is the - * same as the VisualID. - */ - -static int -DoCreateContext(__GLXclientState *cl, GLXContextID gcId, - GLXContextID shareList, __GLXconfig *config, - __GLXscreen *pGlxScreen, GLboolean isDirect) -{ - ClientPtr client = cl->client; - __GLXcontext *glxc, *shareglxc; - int err; - - LEGAL_NEW_RESOURCE(gcId, client); - - /* - ** Find the display list space that we want to share. - ** - ** NOTE: In a multithreaded X server, we would need to keep a reference - ** count for each display list so that if one client detroyed a list that - ** another client was using, the list would not really be freed until it - ** was no longer in use. Since this sample implementation has no support - ** for multithreaded servers, we don't do this. - */ - if (shareList == None) { - shareglxc = 0; - } else { - if (!validGlxContext(client, shareList, DixReadAccess, - &shareglxc, &err)) - return err; - - if (shareglxc->isDirect) { - /* - ** NOTE: no support for sharing display lists between direct - ** contexts, even if they are in the same address space. - */ -#if 0 - /* Disabling this code seems to allow shared display lists - * and texture objects to work. We'll leave it disabled for now. - */ - client->errorValue = shareList; - return BadMatch; -#endif - } else { - /* - ** Create an indirect context regardless of what the client asked - ** for; this way we can share display list space with shareList. - */ - isDirect = GL_FALSE; - } - } - - /* - ** Allocate memory for the new context - */ - if (!isDirect) - glxc = pGlxScreen->createContext(pGlxScreen, config, shareglxc); - else - glxc = __glXdirectContextCreate(pGlxScreen, config, shareglxc); - if (!glxc) { - return BadAlloc; - } - - /* - ** Initially, setup the part of the context that could be used by - ** a GL core that needs windowing information (e.g., Mesa). - */ - glxc->pGlxScreen = pGlxScreen; - glxc->config = config; - - /* - ** Register this context as a resource. - */ - if (!AddResource(gcId, __glXContextRes, (pointer)glxc)) { - (*glxc->destroy)(glxc); - client->errorValue = gcId; - return BadAlloc; - } - - /* - ** Finally, now that everything is working, setup the rest of the - ** context. - */ - glxc->id = gcId; - glxc->share_id = shareList; - glxc->idExists = GL_TRUE; - glxc->isCurrent = GL_FALSE; - glxc->isDirect = isDirect; - glxc->renderMode = GL_RENDER; - - __glXAddToContextList(glxc); - - return Success; -} - -int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) - return err; - - return DoCreateContext(cl, req->context, req->shareList, - config, pGlxScreen, req->isDirect); -} - -int __glXDisp_CreateNewContext(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateNewContextReq *req = (xGLXCreateNewContextReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err)) - return err; - - return DoCreateContext(cl, req->context, req->shareList, - config, pGlxScreen, req->isDirect); -} - -int __glXDisp_CreateContextWithConfigSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateContextWithConfigSGIXReq *req = - (xGLXCreateContextWithConfigSGIXReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err)) - return err; - - return DoCreateContext(cl, req->context, req->shareList, - config, pGlxScreen, req->isDirect); -} -int __glXDisp_DestroyContext(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyContextReq *req = (xGLXDestroyContextReq *) pc; - __GLXcontext *glxc; - int err; - - if (!validGlxContext(cl->client, req->context, DixDestroyAccess, - &glxc, &err)) - return err; - - FreeResourceByType(req->context, __glXContextRes, FALSE); - return Success; -} - -/*****************************************************************************/ - -/* -** For each client, the server keeps a table of all the contexts that are -** current for that client (each thread of a client may have its own current -** context). These routines add, change, and lookup contexts in the table. -*/ - -/* -** Add a current context, and return the tag that will be used to refer to it. -*/ -static int AddCurrentContext(__GLXclientState *cl, __GLXcontext *glxc) -{ - int i; - int num = cl->numCurrentContexts; - __GLXcontext **table = cl->currentContexts; - - if (!glxc) return -1; - - /* - ** Try to find an empty slot and use it. - */ - for (i=0; i < num; i++) { - if (!table[i]) { - table[i] = glxc; - return i+1; - } - } - /* - ** Didn't find a free slot, so we'll have to grow the table. - */ - if (!num) { - table = (__GLXcontext **) xalloc(sizeof(__GLXcontext *)); - } else { - table = (__GLXcontext **) xrealloc(table, - (num+1)*sizeof(__GLXcontext *)); - } - table[num] = glxc; - cl->currentContexts = table; - cl->numCurrentContexts++; - return num+1; -} - -/* -** Given a tag, change the current context for the corresponding entry. -*/ -static void ChangeCurrentContext(__GLXclientState *cl, __GLXcontext *glxc, - GLXContextTag tag) -{ - __GLXcontext **table = cl->currentContexts; - table[tag-1] = glxc; -} - -/* -** For this implementation we have chosen to simply use the index of the -** context's entry in the table as the context tag. A tag must be greater -** than 0. -*/ -__GLXcontext *__glXLookupContextByTag(__GLXclientState *cl, GLXContextTag tag) -{ - int num = cl->numCurrentContexts; - - if (tag < 1 || tag > num) { - return 0; - } else { - return cl->currentContexts[tag-1]; - } -} - -/*****************************************************************************/ - -static void StopUsingContext(__GLXcontext *glxc) -{ - if (glxc) { - if (glxc == __glXLastContext) { - /* Tell server GL library */ - __glXLastContext = 0; - } - glxc->isCurrent = GL_FALSE; - if (!glxc->idExists) { - __glXFreeContext(glxc); - } - } -} - -static void StartUsingContext(__GLXclientState *cl, __GLXcontext *glxc) -{ - glxc->isCurrent = GL_TRUE; - __glXLastContext = glxc; -} - -/** - * This is a helper function to handle the legacy (pre GLX 1.3) cases - * where passing an X window to glXMakeCurrent is valid. Given a - * resource ID, look up the GLX drawable if available, otherwise, make - * sure it's an X window and create a GLX drawable one the fly. - */ -static __GLXdrawable * -__glXGetDrawable(__GLXcontext *glxc, GLXDrawable drawId, ClientPtr client, - int *error) -{ - DrawablePtr pDraw; - __GLXdrawable *pGlxDraw; - int rc; - - if (validGlxDrawable(client, drawId, GLX_DRAWABLE_ANY, - DixWriteAccess, &pGlxDraw, &rc)) { - if (glxc != NULL && pGlxDraw->config != glxc->config) { - client->errorValue = drawId; - *error = BadMatch; - return NULL; - } - - return pGlxDraw; - } - - /* The drawId wasn't a GLX drawable. Make sure it's a window and - * create a GLXWindow for it. Check that the drawable screen - * matches the context screen and that the context fbconfig is - * compatible with the window visual. */ - - rc = dixLookupDrawable(&pDraw, drawId, client, 0, DixGetAttrAccess); - if (rc != Success || pDraw->type != DRAWABLE_WINDOW) { - client->errorValue = drawId; - *error = __glXError(GLXBadDrawable); - return NULL; - } - - if (pDraw->pScreen != glxc->pGlxScreen->pScreen) { - client->errorValue = pDraw->pScreen->myNum; - *error = BadMatch; - return NULL; - } - - if (!validGlxFBConfigForWindow(client, glxc->config, pDraw, error)) - return NULL; - - pGlxDraw = glxc->pGlxScreen->createDrawable(glxc->pGlxScreen, - pDraw, GLX_DRAWABLE_WINDOW, - drawId, glxc->config); - - /* since we are creating the drawablePrivate, drawId should be new */ - if (!AddResource(drawId, __glXDrawableRes, pGlxDraw)) { - pGlxDraw->destroy (pGlxDraw); - *error = BadAlloc; - return NULL; - } - - return pGlxDraw; -} - -/*****************************************************************************/ -/* -** Make an OpenGL context and drawable current. -*/ - -static int -DoMakeCurrent(__GLXclientState *cl, - GLXDrawable drawId, GLXDrawable readId, - GLXContextID contextId, GLXContextTag tag) -{ - ClientPtr client = cl->client; - xGLXMakeCurrentReply reply; - __GLXcontext *glxc, *prevglxc; - __GLXdrawable *drawPriv = NULL; - __GLXdrawable *readPriv = NULL; - int error; - GLuint mask; - - /* - ** If one is None and the other isn't, it's a bad match. - */ - - mask = (drawId == None) ? (1 << 0) : 0; - mask |= (readId == None) ? (1 << 1) : 0; - mask |= (contextId == None) ? (1 << 2) : 0; - - if ( (mask != 0x00) && (mask != 0x07) ) { - return BadMatch; - } - - /* - ** Lookup old context. If we have one, it must be in a usable state. - */ - if (tag != 0) { - prevglxc = __glXLookupContextByTag(cl, tag); - if (!prevglxc) { - /* - ** Tag for previous context is invalid. - */ - return __glXError(GLXBadContextTag); - } - if (prevglxc->renderMode != GL_RENDER) { - /* Oops. Not in render mode render. */ - client->errorValue = prevglxc->id; - return __glXError(GLXBadContextState); - } - } else { - prevglxc = 0; - } - - /* - ** Lookup new context. It must not be current for someone else. - */ - if (contextId != None) { - int status; - - if (!validGlxContext(client, contextId, DixUseAccess, &glxc, &error)) - return error; - if ((glxc != prevglxc) && glxc->isCurrent) { - /* Context is current to somebody else */ - return BadAccess; - } - - assert( drawId != None ); - assert( readId != None ); - - drawPriv = __glXGetDrawable(glxc, drawId, client, &status); - if (drawPriv == NULL) - return status; - - readPriv = __glXGetDrawable(glxc, readId, client, &status); - if (readPriv == NULL) - return status; - - } else { - /* Switching to no context. Ignore new drawable. */ - glxc = 0; - drawPriv = 0; - readPriv = 0; - } - - - if (prevglxc) { - /* - ** Flush the previous context if needed. - */ - if (__GLX_HAS_UNFLUSHED_CMDS(prevglxc)) { - if (__glXForceCurrent(cl, tag, (int *)&error)) { - CALL_Flush( GET_DISPATCH(), () ); - __GLX_NOTE_FLUSHED_CMDS(prevglxc); - } else { - return error; - } - } - - /* - ** Make the previous context not current. - */ - if (!(*prevglxc->loseCurrent)(prevglxc)) { - return __glXError(GLXBadContext); - } - __glXFlushContextCache(); - if (!prevglxc->isDirect) { - prevglxc->drawPriv = NULL; - prevglxc->readPriv = NULL; - } - } - - - if ((glxc != 0) && !glxc->isDirect) { - - glxc->drawPriv = drawPriv; - glxc->readPriv = readPriv; - - /* make the context current */ - if (!(*glxc->makeCurrent)(glxc)) { - glxc->drawPriv = NULL; - glxc->readPriv = NULL; - return __glXError(GLXBadContext); - } - - glxc->isCurrent = GL_TRUE; - } - - if (prevglxc) { - ChangeCurrentContext(cl, glxc, tag); - StopUsingContext(prevglxc); - } else { - tag = AddCurrentContext(cl, glxc); - } - - if (glxc) { - StartUsingContext(cl, glxc); - reply.contextTag = tag; - } else { - reply.contextTag = 0; - } - - reply.length = 0; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __glXSwapMakeCurrentReply(client, &reply); - } else { - WriteToClient(client, sz_xGLXMakeCurrentReply, (char *)&reply); - } - return Success; -} - -int __glXDisp_MakeCurrent(__GLXclientState *cl, GLbyte *pc) -{ - xGLXMakeCurrentReq *req = (xGLXMakeCurrentReq *) pc; - - return DoMakeCurrent( cl, req->drawable, req->drawable, - req->context, req->oldContextTag ); -} - -int __glXDisp_MakeContextCurrent(__GLXclientState *cl, GLbyte *pc) -{ - xGLXMakeContextCurrentReq *req = (xGLXMakeContextCurrentReq *) pc; - - return DoMakeCurrent( cl, req->drawable, req->readdrawable, - req->context, req->oldContextTag ); -} - -int __glXDisp_MakeCurrentReadSGI(__GLXclientState *cl, GLbyte *pc) -{ - xGLXMakeCurrentReadSGIReq *req = (xGLXMakeCurrentReadSGIReq *) pc; - - return DoMakeCurrent( cl, req->drawable, req->readable, - req->context, req->oldContextTag ); -} - -int __glXDisp_IsDirect(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXIsDirectReq *req = (xGLXIsDirectReq *) pc; - xGLXIsDirectReply reply; - __GLXcontext *glxc; - int err; - - if (!validGlxContext(cl->client, req->context, DixReadAccess, &glxc, &err)) - return err; - - reply.isDirect = glxc->isDirect; - reply.length = 0; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __glXSwapIsDirectReply(client, &reply); - } else { - WriteToClient(client, sz_xGLXIsDirectReply, (char *)&reply); - } - - return Success; -} - -int __glXDisp_QueryVersion(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryVersionReq *req = (xGLXQueryVersionReq *) pc; - xGLXQueryVersionReply reply; - GLuint major, minor; - - major = req->majorVersion; - minor = req->minorVersion; - (void)major; - (void)minor; - - /* - ** Server should take into consideration the version numbers sent by the - ** client if it wants to work with older clients; however, in this - ** implementation the server just returns its version number. - */ - reply.majorVersion = SERVER_GLX_MAJOR_VERSION; - reply.minorVersion = SERVER_GLX_MINOR_VERSION; - reply.length = 0; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __glXSwapQueryVersionReply(client, &reply); - } else { - WriteToClient(client, sz_xGLXQueryVersionReply, (char *)&reply); - } - return Success; -} - -int __glXDisp_WaitGL(__GLXclientState *cl, GLbyte *pc) -{ - xGLXWaitGLReq *req = (xGLXWaitGLReq *)pc; - GLXContextTag tag = req->contextTag; - __GLXcontext *glxc = NULL; - int error; - - if (tag) { - glxc = __glXLookupContextByTag(cl, tag); - if (!glxc) - return __glXError(GLXBadContextTag); - - if (!__glXForceCurrent(cl, req->contextTag, &error)) - return error; - - CALL_Finish( GET_DISPATCH(), () ); - } - - if (glxc && glxc->drawPriv->waitGL) - (*glxc->drawPriv->waitGL)(glxc->drawPriv); - - return Success; -} - -int __glXDisp_WaitX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXWaitXReq *req = (xGLXWaitXReq *)pc; - GLXContextTag tag = req->contextTag; - __GLXcontext *glxc = NULL; - int error; - - if (tag) { - glxc = __glXLookupContextByTag(cl, tag); - if (!glxc) - return __glXError(GLXBadContextTag); - - if (!__glXForceCurrent(cl, req->contextTag, &error)) - return error; - } - - if (glxc && glxc->drawPriv->waitX) - (*glxc->drawPriv->waitX)(glxc->drawPriv); - - return Success; -} - -int __glXDisp_CopyContext(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXCopyContextReq *req = (xGLXCopyContextReq *) pc; - GLXContextID source = req->source; - GLXContextID dest = req->dest; - GLXContextTag tag = req->contextTag; - unsigned long mask = req->mask; - __GLXcontext *src, *dst; - int error; - - if (!validGlxContext(cl->client, source, DixReadAccess, &src, &error)) - return error; - if (!validGlxContext(cl->client, dest, DixWriteAccess, &dst, &error)) - return error; - - /* - ** They must be in the same address space, and same screen. - ** NOTE: no support for direct rendering contexts here. - */ - if (src->isDirect || dst->isDirect || - (src->pGlxScreen != dst->pGlxScreen)) { - client->errorValue = source; - return BadMatch; - } - - /* - ** The destination context must not be current for any client. - */ - if (dst->isCurrent) { - client->errorValue = dest; - return BadAccess; - } - - if (tag) { - __GLXcontext *tagcx = __glXLookupContextByTag(cl, tag); - - if (!tagcx) { - return __glXError(GLXBadContextTag); - } - if (tagcx != src) { - /* - ** This would be caused by a faulty implementation of the client - ** library. - */ - return BadMatch; - } - /* - ** In this case, glXCopyContext is in both GL and X streams, in terms - ** of sequentiality. - */ - if (__glXForceCurrent(cl, tag, &error)) { - /* - ** Do whatever is needed to make sure that all preceding requests - ** in both streams are completed before the copy is executed. - */ - CALL_Finish( GET_DISPATCH(), () ); - __GLX_NOTE_FLUSHED_CMDS(tagcx); - } else { - return error; - } - } - /* - ** Issue copy. The only reason for failure is a bad mask. - */ - if (!(*dst->copy)(dst, src, mask)) { - client->errorValue = mask; - return BadValue; - } - return Success; -} - -enum { - GLX_VIS_CONFIG_UNPAIRED = 18, - GLX_VIS_CONFIG_PAIRED = 20 -}; - -enum { - GLX_VIS_CONFIG_TOTAL = GLX_VIS_CONFIG_UNPAIRED + GLX_VIS_CONFIG_PAIRED -}; - -int __glXDisp_GetVisualConfigs(__GLXclientState *cl, GLbyte *pc) -{ - xGLXGetVisualConfigsReq *req = (xGLXGetVisualConfigsReq *) pc; - ClientPtr client = cl->client; - xGLXGetVisualConfigsReply reply; - __GLXscreen *pGlxScreen; - __GLXconfig *modes; - CARD32 buf[GLX_VIS_CONFIG_TOTAL]; - int p, i, err; - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_DECLARE_SWAP_ARRAY_VARIABLES; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - - reply.numVisuals = pGlxScreen->numVisuals; - reply.numProps = GLX_VIS_CONFIG_TOTAL; - reply.length = (reply.numVisuals * __GLX_SIZE_CARD32 * GLX_VIS_CONFIG_TOTAL) >> 2; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __GLX_SWAP_SHORT(&reply.sequenceNumber); - __GLX_SWAP_INT(&reply.length); - __GLX_SWAP_INT(&reply.numVisuals); - __GLX_SWAP_INT(&reply.numProps); - } - - WriteToClient(client, sz_xGLXGetVisualConfigsReply, (char *)&reply); - - for (i = 0; i < pGlxScreen->numVisuals; i++) { - modes = pGlxScreen->visuals[i]; - - p = 0; - buf[p++] = modes->visualID; - buf[p++] = glxConvertToXVisualType( modes->visualType ); - buf[p++] = (modes->renderType & GLX_RGBA_BIT) ? GL_TRUE : GL_FALSE; - - buf[p++] = modes->redBits; - buf[p++] = modes->greenBits; - buf[p++] = modes->blueBits; - buf[p++] = modes->alphaBits; - buf[p++] = modes->accumRedBits; - buf[p++] = modes->accumGreenBits; - buf[p++] = modes->accumBlueBits; - buf[p++] = modes->accumAlphaBits; - - buf[p++] = modes->doubleBufferMode; - buf[p++] = modes->stereoMode; - - buf[p++] = modes->rgbBits; - buf[p++] = modes->depthBits; - buf[p++] = modes->stencilBits; - buf[p++] = modes->numAuxBuffers; - buf[p++] = modes->level; - - assert(p == GLX_VIS_CONFIG_UNPAIRED); - /* - ** Add token/value pairs for extensions. - */ - buf[p++] = GLX_VISUAL_CAVEAT_EXT; - buf[p++] = modes->visualRating; - buf[p++] = GLX_TRANSPARENT_TYPE; - buf[p++] = modes->transparentPixel; - buf[p++] = GLX_TRANSPARENT_RED_VALUE; - buf[p++] = modes->transparentRed; - buf[p++] = GLX_TRANSPARENT_GREEN_VALUE; - buf[p++] = modes->transparentGreen; - buf[p++] = GLX_TRANSPARENT_BLUE_VALUE; - buf[p++] = modes->transparentBlue; - buf[p++] = GLX_TRANSPARENT_ALPHA_VALUE; - buf[p++] = modes->transparentAlpha; - buf[p++] = GLX_TRANSPARENT_INDEX_VALUE; - buf[p++] = modes->transparentIndex; - buf[p++] = GLX_SAMPLES_SGIS; - buf[p++] = modes->samples; - buf[p++] = GLX_SAMPLE_BUFFERS_SGIS; - buf[p++] = modes->sampleBuffers; - buf[p++] = 0; /* copy over visualSelectGroup (GLX_VISUAL_SELECT_GROUP_SGIX)? */ - buf[p++] = 0; - - assert(p == GLX_VIS_CONFIG_TOTAL); - if (client->swapped) { - __GLX_SWAP_INT_ARRAY(buf, p); - } - WriteToClient(client, __GLX_SIZE_CARD32 * p, (char *)buf); - } - return Success; -} - -#define __GLX_TOTAL_FBCONFIG_ATTRIBS (36) -#define __GLX_FBCONFIG_ATTRIBS_LENGTH (__GLX_TOTAL_FBCONFIG_ATTRIBS * 2) -/** - * Send the set of GLXFBConfigs to the client. There is not currently - * and interface into the driver on the server-side to get GLXFBConfigs, - * so we "invent" some based on the \c __GLXvisualConfig structures that - * the driver does supply. - * - * The reply format for both \c glXGetFBConfigs and \c glXGetFBConfigsSGIX - * is the same, so this routine pulls double duty. - */ - -static int -DoGetFBConfigs(__GLXclientState *cl, unsigned screen) -{ - ClientPtr client = cl->client; - xGLXGetFBConfigsReply reply; - __GLXscreen *pGlxScreen; - CARD32 buf[__GLX_FBCONFIG_ATTRIBS_LENGTH]; - int p, err; - __GLXconfig *modes; - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_DECLARE_SWAP_ARRAY_VARIABLES; - - if (!validGlxScreen(cl->client, screen, &pGlxScreen, &err)) - return err; - - reply.numFBConfigs = pGlxScreen->numFBConfigs; - reply.numAttribs = __GLX_TOTAL_FBCONFIG_ATTRIBS; - reply.length = (__GLX_FBCONFIG_ATTRIBS_LENGTH * reply.numFBConfigs); - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __GLX_SWAP_SHORT(&reply.sequenceNumber); - __GLX_SWAP_INT(&reply.length); - __GLX_SWAP_INT(&reply.numFBConfigs); - __GLX_SWAP_INT(&reply.numAttribs); - } - - WriteToClient(client, sz_xGLXGetFBConfigsReply, (char *)&reply); - - for (modes = pGlxScreen->fbconfigs; modes != NULL; modes = modes->next) { - p = 0; - -#define WRITE_PAIR(tag,value) \ - do { buf[p++] = tag ; buf[p++] = value ; } while( 0 ) - - WRITE_PAIR( GLX_VISUAL_ID, modes->visualID ); - WRITE_PAIR( GLX_FBCONFIG_ID, modes->fbconfigID ); - WRITE_PAIR( GLX_X_RENDERABLE, GL_TRUE ); - - WRITE_PAIR( GLX_RGBA, - (modes->renderType & GLX_RGBA_BIT) ? GL_TRUE : GL_FALSE ); - WRITE_PAIR( GLX_RENDER_TYPE, modes->renderType ); - WRITE_PAIR( GLX_DOUBLEBUFFER, modes->doubleBufferMode ); - WRITE_PAIR( GLX_STEREO, modes->stereoMode ); - - WRITE_PAIR( GLX_BUFFER_SIZE, modes->rgbBits ); - WRITE_PAIR( GLX_LEVEL, modes->level ); - WRITE_PAIR( GLX_AUX_BUFFERS, modes->numAuxBuffers ); - WRITE_PAIR( GLX_RED_SIZE, modes->redBits ); - WRITE_PAIR( GLX_GREEN_SIZE, modes->greenBits ); - WRITE_PAIR( GLX_BLUE_SIZE, modes->blueBits ); - WRITE_PAIR( GLX_ALPHA_SIZE, modes->alphaBits ); - WRITE_PAIR( GLX_ACCUM_RED_SIZE, modes->accumRedBits ); - WRITE_PAIR( GLX_ACCUM_GREEN_SIZE, modes->accumGreenBits ); - WRITE_PAIR( GLX_ACCUM_BLUE_SIZE, modes->accumBlueBits ); - WRITE_PAIR( GLX_ACCUM_ALPHA_SIZE, modes->accumAlphaBits ); - WRITE_PAIR( GLX_DEPTH_SIZE, modes->depthBits ); - WRITE_PAIR( GLX_STENCIL_SIZE, modes->stencilBits ); - WRITE_PAIR( GLX_X_VISUAL_TYPE, modes->visualType ); - WRITE_PAIR( GLX_CONFIG_CAVEAT, modes->visualRating ); - WRITE_PAIR( GLX_TRANSPARENT_TYPE, modes->transparentPixel ); - WRITE_PAIR( GLX_TRANSPARENT_RED_VALUE, modes->transparentRed ); - WRITE_PAIR( GLX_TRANSPARENT_GREEN_VALUE, modes->transparentGreen ); - WRITE_PAIR( GLX_TRANSPARENT_BLUE_VALUE, modes->transparentBlue ); - WRITE_PAIR( GLX_TRANSPARENT_ALPHA_VALUE, modes->transparentAlpha ); - WRITE_PAIR( GLX_TRANSPARENT_INDEX_VALUE, modes->transparentIndex ); - WRITE_PAIR( GLX_SWAP_METHOD_OML, modes->swapMethod ); - WRITE_PAIR( GLX_SAMPLES_SGIS, modes->samples ); - WRITE_PAIR( GLX_SAMPLE_BUFFERS_SGIS, modes->sampleBuffers ); - /* GLX_VISUAL_SELECT_GROUP_SGIX ? */ - WRITE_PAIR( GLX_DRAWABLE_TYPE, modes->drawableType ); - WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGB_EXT, modes->bindToTextureRgb ); - WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGBA_EXT, modes->bindToTextureRgba ); - WRITE_PAIR( GLX_BIND_TO_MIPMAP_TEXTURE_EXT, modes->bindToMipmapTexture ); - WRITE_PAIR( GLX_BIND_TO_TEXTURE_TARGETS_EXT, modes->bindToTextureTargets ); - - if (client->swapped) { - __GLX_SWAP_INT_ARRAY(buf, __GLX_FBCONFIG_ATTRIBS_LENGTH); - } - WriteToClient(client, __GLX_SIZE_CARD32 * __GLX_FBCONFIG_ATTRIBS_LENGTH, - (char *)buf); - } - return Success; -} - - -int __glXDisp_GetFBConfigs(__GLXclientState *cl, GLbyte *pc) -{ - xGLXGetFBConfigsReq *req = (xGLXGetFBConfigsReq *) pc; - return DoGetFBConfigs(cl, req->screen); -} - -int __glXDisp_GetFBConfigsSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXGetFBConfigsSGIXReq *req = (xGLXGetFBConfigsSGIXReq *) pc; - return DoGetFBConfigs(cl, req->screen); -} - -GLboolean -__glXDrawableInit(__GLXdrawable *drawable, - __GLXscreen *screen, DrawablePtr pDraw, int type, - XID drawId, __GLXconfig *config) -{ - drawable->pDraw = pDraw; - drawable->type = type; - drawable->drawId = drawId; - drawable->config = config; - drawable->eventMask = 0; - - return GL_TRUE; -} - -void -__glXDrawableRelease(__GLXdrawable *drawable) -{ - ScreenPtr pScreen = drawable->pDraw->pScreen; - - switch (drawable->type) { - case GLX_DRAWABLE_PIXMAP: - case GLX_DRAWABLE_PBUFFER: - (*pScreen->DestroyPixmap)((PixmapPtr) drawable->pDraw); - break; - } -} - -static int -DoCreateGLXDrawable(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config, - DrawablePtr pDraw, XID glxDrawableId, int type) -{ - __GLXdrawable *pGlxDraw; - - LEGAL_NEW_RESOURCE(glxDrawableId, client); - - if (pGlxScreen->pScreen != pDraw->pScreen) - return BadMatch; - - pGlxDraw = pGlxScreen->createDrawable(pGlxScreen, pDraw, type, - glxDrawableId, config); - if (pGlxDraw == NULL) - return BadAlloc; - - if (!AddResource(glxDrawableId, __glXDrawableRes, pGlxDraw)) { - pGlxDraw->destroy (pGlxDraw); - return BadAlloc; - } - - return Success; -} - -static int -DoCreateGLXPixmap(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config, - XID drawableId, XID glxDrawableId) -{ - DrawablePtr pDraw; - int err; - - err = dixLookupDrawable(&pDraw, drawableId, client, 0, DixAddAccess); - if (err != Success) { - client->errorValue = drawableId; - return err; - } - if (pDraw->type != DRAWABLE_PIXMAP) { - client->errorValue = drawableId; - return BadPixmap; - } - - err = DoCreateGLXDrawable(client, pGlxScreen, config, pDraw, - glxDrawableId, GLX_DRAWABLE_PIXMAP); - - if (err == Success) - ((PixmapPtr) pDraw)->refcnt++; - - return err; -} - -static void -determineTextureTarget(ClientPtr client, XID glxDrawableID, - CARD32 *attribs, CARD32 numAttribs) -{ - GLenum target = 0; - GLenum format = 0; - int i, err; - __GLXdrawable *pGlxDraw; - - if (!validGlxDrawable(client, glxDrawableID, GLX_DRAWABLE_PIXMAP, - DixWriteAccess, &pGlxDraw, &err)) - /* We just added it in CreatePixmap, so we should never get here. */ - return; - - for (i = 0; i < numAttribs; i++) { - if (attribs[2 * i] == GLX_TEXTURE_TARGET_EXT) { - switch (attribs[2 * i + 1]) { - case GLX_TEXTURE_2D_EXT: - target = GL_TEXTURE_2D; - break; - case GLX_TEXTURE_RECTANGLE_EXT: - target = GL_TEXTURE_RECTANGLE_ARB; - break; - } - } - - if (attribs[2 * i] == GLX_TEXTURE_FORMAT_EXT) - format = attribs[2 * i + 1]; - } - - if (!target) { - int w = pGlxDraw->pDraw->width, h = pGlxDraw->pDraw->height; - - if (h & (h - 1) || w & (w - 1)) - target = GL_TEXTURE_RECTANGLE_ARB; - else - target = GL_TEXTURE_2D; - } - - pGlxDraw->target = target; - pGlxDraw->format = format; -} - -int __glXDisp_CreateGLXPixmap(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateGLXPixmapReq *req = (xGLXCreateGLXPixmapReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err)) - return err; - - return DoCreateGLXPixmap(cl->client, pGlxScreen, config, - req->pixmap, req->glxpixmap); -} - -int __glXDisp_CreatePixmap(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreatePixmapReq *req = (xGLXCreatePixmapReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err)) - return err; - - err = DoCreateGLXPixmap(cl->client, pGlxScreen, config, - req->pixmap, req->glxpixmap); - if (err != Success) - return err; - - determineTextureTarget(cl->client, req->glxpixmap, - (CARD32*) (req + 1), req->numAttribs); - - return Success; -} - -int __glXDisp_CreateGLXPixmapWithConfigSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateGLXPixmapWithConfigSGIXReq *req = - (xGLXCreateGLXPixmapWithConfigSGIXReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err)) - return err; - - return DoCreateGLXPixmap(cl->client, pGlxScreen, - config, req->pixmap, req->glxpixmap); -} - - -static int DoDestroyDrawable(__GLXclientState *cl, XID glxdrawable, int type) -{ - __GLXdrawable *pGlxDraw; - int err; - - if (!validGlxDrawable(cl->client, glxdrawable, type, - DixDestroyAccess, &pGlxDraw, &err)) - return err; - - FreeResource(glxdrawable, FALSE); - - return Success; -} - -int __glXDisp_DestroyGLXPixmap(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyGLXPixmapReq *req = (xGLXDestroyGLXPixmapReq *) pc; - - return DoDestroyDrawable(cl, req->glxpixmap, GLX_DRAWABLE_PIXMAP); -} - -int __glXDisp_DestroyPixmap(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyPixmapReq *req = (xGLXDestroyPixmapReq *) pc; - - return DoDestroyDrawable(cl, req->glxpixmap, GLX_DRAWABLE_PIXMAP); -} - -static int -DoCreatePbuffer(ClientPtr client, int screenNum, XID fbconfigId, - int width, int height, XID glxDrawableId) -{ - __GLXconfig *config; - __GLXscreen *pGlxScreen; - PixmapPtr pPixmap; - int err; - - if (!validGlxScreen(client, screenNum, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(client, pGlxScreen, fbconfigId, &config, &err)) - return err; - - __glXenterServer(GL_FALSE); - pPixmap = (*pGlxScreen->pScreen->CreatePixmap) (pGlxScreen->pScreen, - width, height, config->rgbBits, 0); - __glXleaveServer(GL_FALSE); - - return DoCreateGLXDrawable(client, pGlxScreen, config, &pPixmap->drawable, - glxDrawableId, GLX_DRAWABLE_PBUFFER); -} - -int __glXDisp_CreatePbuffer(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreatePbufferReq *req = (xGLXCreatePbufferReq *) pc; - CARD32 *attrs; - int width, height, i; - - attrs = (CARD32 *) (req + 1); - width = 0; - height = 0; - - for (i = 0; i < req->numAttribs; i++) { - switch (attrs[i * 2]) { - case GLX_PBUFFER_WIDTH: - width = attrs[i * 2 + 1]; - break; - case GLX_PBUFFER_HEIGHT: - height = attrs[i * 2 + 1]; - break; - case GLX_LARGEST_PBUFFER: - case GLX_PRESERVED_CONTENTS: - /* FIXME: huh... */ - break; - } - } - - return DoCreatePbuffer(cl->client, req->screen, req->fbconfig, - width, height, req->pbuffer); -} - -int __glXDisp_CreateGLXPbufferSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateGLXPbufferSGIXReq *req = (xGLXCreateGLXPbufferSGIXReq *) pc; - - return DoCreatePbuffer(cl->client, req->screen, req->fbconfig, - req->width, req->height, req->pbuffer); -} - -int __glXDisp_DestroyPbuffer(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyPbufferReq *req = (xGLXDestroyPbufferReq *) pc; - - return DoDestroyDrawable(cl, req->pbuffer, GLX_DRAWABLE_PBUFFER); -} - -int __glXDisp_DestroyGLXPbufferSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyGLXPbufferSGIXReq *req = (xGLXDestroyGLXPbufferSGIXReq *) pc; - - return DoDestroyDrawable(cl, req->pbuffer, GLX_DRAWABLE_PBUFFER); -} - -static int -DoChangeDrawableAttributes(ClientPtr client, XID glxdrawable, - int numAttribs, CARD32 *attribs) -{ - __GLXdrawable *pGlxDraw; - int i, err; - - if (!validGlxDrawable(client, glxdrawable, GLX_DRAWABLE_ANY, - DixSetAttrAccess, &pGlxDraw, &err)) - return err; - - for (i = 0; i < numAttribs; i++) { - switch(attribs[i * 2]) { - case GLX_EVENT_MASK: - /* All we do is to record the event mask so we can send it - * back when queried. We never actually clobber the - * pbuffers, so we never need to send out the event. */ - pGlxDraw->eventMask = attribs[i * 2 + 1]; - break; - } - } - - return Success; -} - -int __glXDisp_ChangeDrawableAttributes(__GLXclientState *cl, GLbyte *pc) -{ - xGLXChangeDrawableAttributesReq *req = - (xGLXChangeDrawableAttributesReq *) pc; - - return DoChangeDrawableAttributes(cl->client, req->drawable, - req->numAttribs, (CARD32 *) (req + 1)); -} - -int __glXDisp_ChangeDrawableAttributesSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXChangeDrawableAttributesSGIXReq *req = - (xGLXChangeDrawableAttributesSGIXReq *)pc; - - return DoChangeDrawableAttributes(cl->client, req->drawable, - req->numAttribs, (CARD32 *) (req + 1)); -} - -int __glXDisp_CreateWindow(__GLXclientState *cl, GLbyte *pc) -{ - xGLXCreateWindowReq *req = (xGLXCreateWindowReq *) pc; - __GLXconfig *config; - __GLXscreen *pGlxScreen; - ClientPtr client = cl->client; - DrawablePtr pDraw; - int err; - - if (!validGlxScreen(client, req->screen, &pGlxScreen, &err)) - return err; - if (!validGlxFBConfig(client, pGlxScreen, req->fbconfig, &config, &err)) - return err; - - err = dixLookupDrawable(&pDraw, req->window, client, 0, DixAddAccess); - if (err != Success || pDraw->type != DRAWABLE_WINDOW) { - client->errorValue = req->window; - return BadWindow; - } - - if (!validGlxFBConfigForWindow(client, config, pDraw, &err)) - return err; - - return DoCreateGLXDrawable(client, pGlxScreen, config, - pDraw, req->glxwindow, GLX_DRAWABLE_WINDOW); -} - -int __glXDisp_DestroyWindow(__GLXclientState *cl, GLbyte *pc) -{ - xGLXDestroyWindowReq *req = (xGLXDestroyWindowReq *) pc; - - return DoDestroyDrawable(cl, req->glxwindow, GLX_DRAWABLE_WINDOW); -} - - -/*****************************************************************************/ - -/* -** NOTE: There is no portable implementation for swap buffers as of -** this time that is of value. Consequently, this code must be -** implemented by somebody other than SGI. -*/ -int __glXDisp_SwapBuffers(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXSwapBuffersReq *req = (xGLXSwapBuffersReq *) pc; - GLXContextTag tag = req->contextTag; - XID drawId = req->drawable; - __GLXcontext *glxc = NULL; - __GLXdrawable *pGlxDraw; - int error; - - if (tag) { - glxc = __glXLookupContextByTag(cl, tag); - if (!glxc) { - return __glXError(GLXBadContextTag); - } - /* - ** The calling thread is swapping its current drawable. In this case, - ** glxSwapBuffers is in both GL and X streams, in terms of - ** sequentiality. - */ - if (__glXForceCurrent(cl, tag, &error)) { - /* - ** Do whatever is needed to make sure that all preceding requests - ** in both streams are completed before the swap is executed. - */ - CALL_Finish( GET_DISPATCH(), () ); - __GLX_NOTE_FLUSHED_CMDS(glxc); - } else { - return error; - } - } - - pGlxDraw = __glXGetDrawable(glxc, drawId, client, &error); - if (pGlxDraw == NULL) - return error; - - if (pGlxDraw->type == DRAWABLE_WINDOW && - (*pGlxDraw->swapBuffers)(pGlxDraw) == GL_FALSE) - return __glXError(GLXBadDrawable); - - return Success; -} - - -static int -DoQueryContext(__GLXclientState *cl, GLXContextID gcId) -{ - ClientPtr client = cl->client; - __GLXcontext *ctx; - xGLXQueryContextInfoEXTReply reply; - int nProps; - int *sendBuf, *pSendBuf; - int nReplyBytes; - int err; - - if (!validGlxContext(cl->client, gcId, DixReadAccess, &ctx, &err)) - return err; - - nProps = 3; - reply.length = nProps << 1; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.n = nProps; - - nReplyBytes = reply.length << 2; - sendBuf = (int *)xalloc((size_t)nReplyBytes); - if (sendBuf == NULL) { - return __glXError(GLXBadContext); /* XXX: Is this correct? */ - } - pSendBuf = sendBuf; - *pSendBuf++ = GLX_SHARE_CONTEXT_EXT; - *pSendBuf++ = (int)(ctx->share_id); - *pSendBuf++ = GLX_VISUAL_ID_EXT; - *pSendBuf++ = (int)(ctx->config->visualID); - *pSendBuf++ = GLX_SCREEN_EXT; - *pSendBuf++ = (int)(ctx->pGlxScreen->pScreen->myNum); - - if (client->swapped) { - __glXSwapQueryContextInfoEXTReply(client, &reply, sendBuf); - } else { - WriteToClient(client, sz_xGLXQueryContextInfoEXTReply, (char *)&reply); - WriteToClient(client, nReplyBytes, (char *)sendBuf); - } - xfree((char *)sendBuf); - - return Success; -} - -int __glXDisp_QueryContextInfoEXT(__GLXclientState *cl, GLbyte *pc) -{ - xGLXQueryContextInfoEXTReq *req = (xGLXQueryContextInfoEXTReq *) pc; - - return DoQueryContext(cl, req->context); -} - -int __glXDisp_QueryContext(__GLXclientState *cl, GLbyte *pc) -{ - xGLXQueryContextReq *req = (xGLXQueryContextReq *) pc; - - return DoQueryContext(cl, req->context); -} - -int __glXDisp_BindTexImageEXT(__GLXclientState *cl, GLbyte *pc) -{ - xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc; - ClientPtr client = cl->client; - __GLXcontext *context; - __GLXdrawable *pGlxDraw; - GLXDrawable drawId; - int buffer; - int error; - - pc += __GLX_VENDPRIV_HDR_SIZE; - - drawId = *((CARD32 *) (pc)); - buffer = *((INT32 *) (pc + 4)); - - if (buffer != GLX_FRONT_LEFT_EXT) - return __glXError(GLXBadPixmap); - - context = __glXForceCurrent (cl, req->contextTag, &error); - if (!context) - return error; - - if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_PIXMAP, - DixReadAccess, &pGlxDraw, &error)) - return error; - - if (!context->textureFromPixmap) - return __glXError(GLXUnsupportedPrivateRequest); - - return context->textureFromPixmap->bindTexImage(context, - buffer, - pGlxDraw); -} - -int __glXDisp_ReleaseTexImageEXT(__GLXclientState *cl, GLbyte *pc) -{ - xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc; - ClientPtr client = cl->client; - __GLXdrawable *pGlxDraw; - __GLXcontext *context; - GLXDrawable drawId; - int buffer; - int error; - - pc += __GLX_VENDPRIV_HDR_SIZE; - - drawId = *((CARD32 *) (pc)); - buffer = *((INT32 *) (pc + 4)); - - context = __glXForceCurrent (cl, req->contextTag, &error); - if (!context) - return error; - - if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_PIXMAP, - DixReadAccess, &pGlxDraw, &error)) - return error; - - if (!context->textureFromPixmap) - return __glXError(GLXUnsupportedPrivateRequest); - - return context->textureFromPixmap->releaseTexImage(context, - buffer, - pGlxDraw); -} - -int __glXDisp_CopySubBufferMESA(__GLXclientState *cl, GLbyte *pc) -{ - xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc; - GLXContextTag tag = req->contextTag; - __GLXcontext *glxc = NULL; - __GLXdrawable *pGlxDraw; - ClientPtr client = cl->client; - GLXDrawable drawId; - int error; - int x, y, width, height; - - (void) client; - (void) req; - - pc += __GLX_VENDPRIV_HDR_SIZE; - - drawId = *((CARD32 *) (pc)); - x = *((INT32 *) (pc + 4)); - y = *((INT32 *) (pc + 8)); - width = *((INT32 *) (pc + 12)); - height = *((INT32 *) (pc + 16)); - - if (tag) { - glxc = __glXLookupContextByTag(cl, tag); - if (!glxc) { - return __glXError(GLXBadContextTag); - } - /* - ** The calling thread is swapping its current drawable. In this case, - ** glxSwapBuffers is in both GL and X streams, in terms of - ** sequentiality. - */ - if (__glXForceCurrent(cl, tag, &error)) { - /* - ** Do whatever is needed to make sure that all preceding requests - ** in both streams are completed before the swap is executed. - */ - CALL_Finish( GET_DISPATCH(), () ); - __GLX_NOTE_FLUSHED_CMDS(glxc); - } else { - return error; - } - } - - pGlxDraw = __glXGetDrawable(glxc, drawId, client, &error); - if (!pGlxDraw) - return error; - - if (pGlxDraw == NULL || - pGlxDraw->type != GLX_DRAWABLE_WINDOW || - pGlxDraw->copySubBuffer == NULL) - return __glXError(GLXBadDrawable); - - (*pGlxDraw->copySubBuffer)(pGlxDraw, x, y, width, height); - - return Success; -} - -/* -** Get drawable attributes -*/ -static int -DoGetDrawableAttributes(__GLXclientState *cl, XID drawId) -{ - ClientPtr client = cl->client; - xGLXGetDrawableAttributesReply reply; - __GLXdrawable *pGlxDraw; - CARD32 attributes[6]; - int numAttribs, error; - - if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_ANY, - DixGetAttrAccess, &pGlxDraw, &error)) - return error; - - numAttribs = 3; - reply.length = numAttribs << 1; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.numAttribs = numAttribs; - - attributes[0] = GLX_TEXTURE_TARGET_EXT; - attributes[1] = pGlxDraw->target == GL_TEXTURE_2D ? GLX_TEXTURE_2D_EXT : - GLX_TEXTURE_RECTANGLE_EXT; - attributes[2] = GLX_Y_INVERTED_EXT; - attributes[3] = GL_FALSE; - attributes[4] = GLX_EVENT_MASK; - attributes[5] = pGlxDraw->eventMask; - - if (client->swapped) { - __glXSwapGetDrawableAttributesReply(client, &reply, attributes); - } else { - WriteToClient(client, sz_xGLXGetDrawableAttributesReply, - (char *)&reply); - WriteToClient(client, reply.length * sizeof (CARD32), - (char *)attributes); - } - - return Success; -} - -int __glXDisp_GetDrawableAttributes(__GLXclientState *cl, GLbyte *pc) -{ - xGLXGetDrawableAttributesReq *req = (xGLXGetDrawableAttributesReq *)pc; - - return DoGetDrawableAttributes(cl, req->drawable); -} - -int __glXDisp_GetDrawableAttributesSGIX(__GLXclientState *cl, GLbyte *pc) -{ - xGLXGetDrawableAttributesSGIXReq *req = - (xGLXGetDrawableAttributesSGIXReq *)pc; - - return DoGetDrawableAttributes(cl, req->drawable); -} - -/************************************************************************/ - -/* -** Render and Renderlarge are not in the GLX API. They are used by the GLX -** client library to send batches of GL rendering commands. -*/ - -/* -** Execute all the drawing commands in a request. -*/ -int __glXDisp_Render(__GLXclientState *cl, GLbyte *pc) -{ - xGLXRenderReq *req; - ClientPtr client= cl->client; - int left, cmdlen, error; - int commandsDone; - CARD16 opcode; - __GLXrenderHeader *hdr; - __GLXcontext *glxc; - __GLX_DECLARE_SWAP_VARIABLES; - - req = (xGLXRenderReq *) pc; - if (client->swapped) { - __GLX_SWAP_SHORT(&req->length); - __GLX_SWAP_INT(&req->contextTag); - } - - glxc = __glXForceCurrent(cl, req->contextTag, &error); - if (!glxc) { - return error; - } - - commandsDone = 0; - pc += sz_xGLXRenderReq; - left = (req->length << 2) - sz_xGLXRenderReq; - while (left > 0) { - __GLXrenderSizeData entry; - int extra; - __GLXdispatchRenderProcPtr proc; - int err; - - /* - ** Verify that the header length and the overall length agree. - ** Also, each command must be word aligned. - */ - hdr = (__GLXrenderHeader *) pc; - if (client->swapped) { - __GLX_SWAP_SHORT(&hdr->length); - __GLX_SWAP_SHORT(&hdr->opcode); - } - cmdlen = hdr->length; - opcode = hdr->opcode; - - /* - ** Check for core opcodes and grab entry data. - */ - err = __glXGetProtocolSizeData(& Render_dispatch_info, opcode, & entry); - proc = (__GLXdispatchRenderProcPtr) - __glXGetProtocolDecodeFunction(& Render_dispatch_info, - opcode, client->swapped); - - if ((err < 0) || (proc == NULL)) { - client->errorValue = commandsDone; - return __glXError(GLXBadRenderRequest); - } - - if (entry.varsize) { - /* variable size command */ - extra = (*entry.varsize)(pc + __GLX_RENDER_HDR_SIZE, - client->swapped); - if (extra < 0) { - extra = 0; - } - if (cmdlen != __GLX_PAD(entry.bytes + extra)) { - return BadLength; - } - } else { - /* constant size command */ - if (cmdlen != __GLX_PAD(entry.bytes)) { - return BadLength; - } - } - if (left < cmdlen) { - return BadLength; - } - - /* - ** Skip over the header and execute the command. We allow the - ** caller to trash the command memory. This is useful especially - ** for things that require double alignment - they can just shift - ** the data towards lower memory (trashing the header) by 4 bytes - ** and achieve the required alignment. - */ - (*proc)(pc + __GLX_RENDER_HDR_SIZE); - pc += cmdlen; - left -= cmdlen; - commandsDone++; - } - __GLX_NOTE_UNFLUSHED_CMDS(glxc); - return Success; -} - - -/* -** Execute a large rendering request (one that spans multiple X requests). -*/ -int __glXDisp_RenderLarge(__GLXclientState *cl, GLbyte *pc) -{ - xGLXRenderLargeReq *req; - ClientPtr client= cl->client; - size_t dataBytes; - __GLXrenderLargeHeader *hdr; - __GLXcontext *glxc; - int error; - CARD16 opcode; - __GLX_DECLARE_SWAP_VARIABLES; - - req = (xGLXRenderLargeReq *) pc; - if (client->swapped) { - __GLX_SWAP_SHORT(&req->length); - __GLX_SWAP_INT(&req->contextTag); - __GLX_SWAP_INT(&req->dataBytes); - __GLX_SWAP_SHORT(&req->requestNumber); - __GLX_SWAP_SHORT(&req->requestTotal); - } - - glxc = __glXForceCurrent(cl, req->contextTag, &error); - if (!glxc) { - /* Reset in case this isn't 1st request. */ - __glXResetLargeCommandStatus(cl); - return error; - } - dataBytes = req->dataBytes; - - /* - ** Check the request length. - */ - if ((req->length << 2) != __GLX_PAD(dataBytes) + sz_xGLXRenderLargeReq) { - client->errorValue = req->length; - /* Reset in case this isn't 1st request. */ - __glXResetLargeCommandStatus(cl); - return BadLength; - } - pc += sz_xGLXRenderLargeReq; - - if (cl->largeCmdRequestsSoFar == 0) { - __GLXrenderSizeData entry; - int extra; - size_t cmdlen; - int err; - - /* - ** This is the first request of a multi request command. - ** Make enough space in the buffer, then copy the entire request. - */ - if (req->requestNumber != 1) { - client->errorValue = req->requestNumber; - return __glXError(GLXBadLargeRequest); - } - - hdr = (__GLXrenderLargeHeader *) pc; - if (client->swapped) { - __GLX_SWAP_INT(&hdr->length); - __GLX_SWAP_INT(&hdr->opcode); - } - cmdlen = hdr->length; - opcode = hdr->opcode; - - /* - ** Check for core opcodes and grab entry data. - */ - err = __glXGetProtocolSizeData(& Render_dispatch_info, opcode, & entry); - if (err < 0) { - client->errorValue = opcode; - return __glXError(GLXBadLargeRequest); - } - - if (entry.varsize) { - /* - ** If it's a variable-size command (a command whose length must - ** be computed from its parameters), all the parameters needed - ** will be in the 1st request, so it's okay to do this. - */ - extra = (*entry.varsize)(pc + __GLX_RENDER_LARGE_HDR_SIZE, - client->swapped); - if (extra < 0) { - extra = 0; - } - /* large command's header is 4 bytes longer, so add 4 */ - if (cmdlen != __GLX_PAD(entry.bytes + 4 + extra)) { - return BadLength; - } - } else { - /* constant size command */ - if (cmdlen != __GLX_PAD(entry.bytes + 4)) { - return BadLength; - } - } - /* - ** Make enough space in the buffer, then copy the entire request. - */ - if (cl->largeCmdBufSize < cmdlen) { - if (!cl->largeCmdBuf) { - cl->largeCmdBuf = (GLbyte *) xalloc(cmdlen); - } else { - cl->largeCmdBuf = (GLbyte *) xrealloc(cl->largeCmdBuf, cmdlen); - } - if (!cl->largeCmdBuf) { - return BadAlloc; - } - cl->largeCmdBufSize = cmdlen; - } - memcpy(cl->largeCmdBuf, pc, dataBytes); - - cl->largeCmdBytesSoFar = dataBytes; - cl->largeCmdBytesTotal = cmdlen; - cl->largeCmdRequestsSoFar = 1; - cl->largeCmdRequestsTotal = req->requestTotal; - return Success; - - } else { - /* - ** We are receiving subsequent (i.e. not the first) requests of a - ** multi request command. - */ - - /* - ** Check the request number and the total request count. - */ - if (req->requestNumber != cl->largeCmdRequestsSoFar + 1) { - client->errorValue = req->requestNumber; - __glXResetLargeCommandStatus(cl); - return __glXError(GLXBadLargeRequest); - } - if (req->requestTotal != cl->largeCmdRequestsTotal) { - client->errorValue = req->requestTotal; - __glXResetLargeCommandStatus(cl); - return __glXError(GLXBadLargeRequest); - } - - /* - ** Check that we didn't get too much data. - */ - if ((cl->largeCmdBytesSoFar + dataBytes) > cl->largeCmdBytesTotal) { - client->errorValue = dataBytes; - __glXResetLargeCommandStatus(cl); - return __glXError(GLXBadLargeRequest); - } - memcpy(cl->largeCmdBuf + cl->largeCmdBytesSoFar, pc, dataBytes); - cl->largeCmdBytesSoFar += dataBytes; - cl->largeCmdRequestsSoFar++; - - if (req->requestNumber == cl->largeCmdRequestsTotal) { - __GLXdispatchRenderProcPtr proc; - - /* - ** This is the last request; it must have enough bytes to complete - ** the command. - */ - /* NOTE: the two pad macros have been added below; they are needed - ** because the client library pads the total byte count, but not - ** the per-request byte counts. The Protocol Encoding says the - ** total byte count should not be padded, so a proposal will be - ** made to the ARB to relax the padding constraint on the total - ** byte count, thus preserving backward compatibility. Meanwhile, - ** the padding done below fixes a bug that did not allow - ** large commands of odd sizes to be accepted by the server. - */ - if (__GLX_PAD(cl->largeCmdBytesSoFar) != - __GLX_PAD(cl->largeCmdBytesTotal)) { - client->errorValue = dataBytes; - __glXResetLargeCommandStatus(cl); - return __glXError(GLXBadLargeRequest); - } - hdr = (__GLXrenderLargeHeader *) cl->largeCmdBuf; - /* - ** The opcode and length field in the header had already been - ** swapped when the first request was received. - ** - ** Use the opcode to index into the procedure table. - */ - opcode = hdr->opcode; - - proc = (__GLXdispatchRenderProcPtr) - __glXGetProtocolDecodeFunction(& Render_dispatch_info, opcode, - client->swapped); - if (proc == NULL) { - client->errorValue = opcode; - return __glXError(GLXBadLargeRequest); - } - - /* - ** Skip over the header and execute the command. - */ - (*proc)(cl->largeCmdBuf + __GLX_RENDER_LARGE_HDR_SIZE); - __GLX_NOTE_UNFLUSHED_CMDS(glxc); - - /* - ** Reset for the next RenderLarge series. - */ - __glXResetLargeCommandStatus(cl); - } else { - /* - ** This is neither the first nor the last request. - */ - } - return Success; - } -} - -extern RESTYPE __glXSwapBarrierRes; - -int __glXDisp_BindSwapBarrierSGIX(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXBindSwapBarrierSGIXReq *req = (xGLXBindSwapBarrierSGIXReq *) pc; - XID drawable = req->drawable; - int barrier = req->barrier; - DrawablePtr pDraw; - int screen, rc; - __GLXscreen *pGlxScreen; - - rc = dixLookupDrawable(&pDraw, drawable, client, 0, DixGetAttrAccess); - pGlxScreen = glxGetScreen(pDraw->pScreen); - if (rc == Success && (pDraw->type == DRAWABLE_WINDOW)) { - screen = pDraw->pScreen->myNum; - if (pGlxScreen->swapBarrierFuncs) { - int ret = pGlxScreen->swapBarrierFuncs->bindSwapBarrierFunc(screen, drawable, barrier); - if (ret == Success) { - if (barrier) - /* add source for cleanup when drawable is gone */ - AddResource(drawable, __glXSwapBarrierRes, (pointer)screen); - else - /* delete source */ - FreeResourceByType(drawable, __glXSwapBarrierRes, FALSE); - } - return ret; - } - } - client->errorValue = drawable; - return __glXError(GLXBadDrawable); -} - - -int __glXDisp_QueryMaxSwapBarriersSGIX(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryMaxSwapBarriersSGIXReq *req = - (xGLXQueryMaxSwapBarriersSGIXReq *) pc; - xGLXQueryMaxSwapBarriersSGIXReply reply; - int screen = req->screen; - __GLXscreen *pGlxScreen; - - pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - if (pGlxScreen->swapBarrierFuncs) - reply.max = pGlxScreen->swapBarrierFuncs->queryMaxSwapBarriersFunc(screen); - else - reply.max = 0; - - - reply.length = 0; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - - if (client->swapped) { - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_SWAP_SHORT(&reply.sequenceNumber); - } - - WriteToClient(client, sz_xGLXQueryMaxSwapBarriersSGIXReply, - (char *) &reply); - return Success; -} - -#define GLX_BAD_HYPERPIPE_SGIX 92 - -int __glXDisp_QueryHyperpipeNetworkSGIX(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryHyperpipeNetworkSGIXReq * req = (xGLXQueryHyperpipeNetworkSGIXReq *) pc; - xGLXQueryHyperpipeNetworkSGIXReply reply; - int screen = req->screen; - void *rdata = NULL; - - int length=0; - int npipes=0; - - int n= 0; - __GLXscreen *pGlxScreen; - - pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - if (pGlxScreen->hyperpipeFuncs) { - rdata = - (pGlxScreen->hyperpipeFuncs->queryHyperpipeNetworkFunc(screen, &npipes, &n)); - } - length = __GLX_PAD(n) >> 2; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = length; - reply.n = n; - reply.npipes = npipes; - - if (client->swapped) { - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_SWAP_SHORT(&reply.sequenceNumber); - __GLX_SWAP_INT(&reply.length); - __GLX_SWAP_INT(&reply.n); - __GLX_SWAP_INT(&reply.npipes); - } - WriteToClient(client, sz_xGLXQueryHyperpipeNetworkSGIXReply, - (char *) &reply); - - WriteToClient(client, length << 2, (char *)rdata); - - return Success; -} - -int __glXDisp_DestroyHyperpipeConfigSGIX (__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXDestroyHyperpipeConfigSGIXReq * req = - (xGLXDestroyHyperpipeConfigSGIXReq *) pc; - xGLXDestroyHyperpipeConfigSGIXReply reply; - int screen = req->screen; - int success = GLX_BAD_HYPERPIPE_SGIX; - int hpId ; - __GLXscreen *pGlxScreen; - - hpId = req->hpId; - - pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - if (pGlxScreen->hyperpipeFuncs) { - success = pGlxScreen->hyperpipeFuncs->destroyHyperpipeConfigFunc(screen, hpId); - } - - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = __GLX_PAD(0) >> 2; - reply.n = 0; - reply.success = success; - - - if (client->swapped) { - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_SWAP_SHORT(&reply.sequenceNumber); - } - WriteToClient(client, - sz_xGLXDestroyHyperpipeConfigSGIXReply, - (char *) &reply); - return Success; -} - -int __glXDisp_QueryHyperpipeConfigSGIX(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryHyperpipeConfigSGIXReq * req = - (xGLXQueryHyperpipeConfigSGIXReq *) pc; - xGLXQueryHyperpipeConfigSGIXReply reply; - int screen = req->screen; - void *rdata = NULL; - int length; - int npipes=0; - int n= 0; - int hpId; - __GLXscreen *pGlxScreen; - - hpId = req->hpId; - - pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - if (pGlxScreen->hyperpipeFuncs) { - rdata = pGlxScreen->hyperpipeFuncs->queryHyperpipeConfigFunc(screen, hpId,&npipes, &n); - } - - length = __GLX_PAD(n) >> 2; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = length; - reply.n = n; - reply.npipes = npipes; - - - if (client->swapped) { - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_SWAP_SHORT(&reply.sequenceNumber); - __GLX_SWAP_INT(&reply.length); - __GLX_SWAP_INT(&reply.n); - __GLX_SWAP_INT(&reply.npipes); - } - - WriteToClient(client, sz_xGLXQueryHyperpipeConfigSGIXReply, - (char *) &reply); - - WriteToClient(client, length << 2, (char *)rdata); - - return Success; -} - -int __glXDisp_HyperpipeConfigSGIX(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXHyperpipeConfigSGIXReq * req = - (xGLXHyperpipeConfigSGIXReq *) pc; - xGLXHyperpipeConfigSGIXReply reply; - int screen = req->screen; - void *rdata; - - int npipes=0, networkId; - int hpId=-1; - __GLXscreen *pGlxScreen; - - pGlxScreen = glxGetScreen(screenInfo.screens[screen]); - networkId = (int)req->networkId; - npipes = (int)req->npipes; - rdata = (void *)(req +1); - - if (pGlxScreen->hyperpipeFuncs) { - pGlxScreen->hyperpipeFuncs->hyperpipeConfigFunc(screen,networkId, - &hpId, &npipes, - (void *) rdata); - } - - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = __GLX_PAD(0) >> 2; - reply.n = 0; - reply.npipes = npipes; - reply.hpId = hpId; - - if (client->swapped) { - __GLX_DECLARE_SWAP_VARIABLES; - __GLX_SWAP_SHORT(&reply.sequenceNumber); - __GLX_SWAP_INT(&reply.npipes); - __GLX_SWAP_INT(&reply.hpId); - } - - WriteToClient(client, sz_xGLXHyperpipeConfigSGIXReply, - (char *) &reply); - - return Success; -} - - -/************************************************************************/ - -/* -** No support is provided for the vendor-private requests other than -** allocating the entry points in the dispatch table. -*/ - -int __glXDisp_VendorPrivate(__GLXclientState *cl, GLbyte *pc) -{ - xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc; - GLint vendorcode = req->vendorCode; - __GLXdispatchVendorPrivProcPtr proc; - - - proc = (__GLXdispatchVendorPrivProcPtr) - __glXGetProtocolDecodeFunction(& VendorPriv_dispatch_info, - vendorcode, 0); - if (proc != NULL) { - (*proc)(cl, (GLbyte*)req); - return Success; - } - - cl->client->errorValue = req->vendorCode; - return __glXError(GLXUnsupportedPrivateRequest); -} - -int __glXDisp_VendorPrivateWithReply(__GLXclientState *cl, GLbyte *pc) -{ - xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc; - GLint vendorcode = req->vendorCode; - __GLXdispatchVendorPrivProcPtr proc; - - - proc = (__GLXdispatchVendorPrivProcPtr) - __glXGetProtocolDecodeFunction(& VendorPriv_dispatch_info, - vendorcode, 0); - if (proc != NULL) { - return (*proc)(cl, (GLbyte*)req); - } - - cl->client->errorValue = vendorcode; - return __glXError(GLXUnsupportedPrivateRequest); -} - -int __glXDisp_QueryExtensionsString(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryExtensionsStringReq *req = (xGLXQueryExtensionsStringReq *) pc; - xGLXQueryExtensionsStringReply reply; - __GLXscreen *pGlxScreen; - size_t n, length; - char *buf; - int err; - - if (!validGlxScreen(client, req->screen, &pGlxScreen, &err)) - return err; - - n = strlen(pGlxScreen->GLXextensions) + 1; - length = __GLX_PAD(n) >> 2; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = length; - reply.n = n; - - /* Allocate buffer to make sure it's a multiple of 4 bytes big.*/ - buf = (char *) xalloc(length << 2); - if (buf == NULL) - return BadAlloc; - memcpy(buf, pGlxScreen->GLXextensions, n); - - if (client->swapped) { - glxSwapQueryExtensionsStringReply(client, &reply, buf); - } else { - WriteToClient(client, sz_xGLXQueryExtensionsStringReply,(char *)&reply); - WriteToClient(client, (int)(length << 2), (char *)buf); - } - - xfree(buf); - return Success; -} - -int __glXDisp_QueryServerString(__GLXclientState *cl, GLbyte *pc) -{ - ClientPtr client = cl->client; - xGLXQueryServerStringReq *req = (xGLXQueryServerStringReq *) pc; - xGLXQueryServerStringReply reply; - size_t n, length; - const char *ptr; - char *buf; - __GLXscreen *pGlxScreen; - int err; - - if (!validGlxScreen(client, req->screen, &pGlxScreen, &err)) - return err; - - switch(req->name) { - case GLX_VENDOR: - ptr = pGlxScreen->GLXvendor; - break; - case GLX_VERSION: - ptr = pGlxScreen->GLXversion; - break; - case GLX_EXTENSIONS: - ptr = pGlxScreen->GLXextensions; - break; - default: - return BadValue; - } - - n = strlen(ptr) + 1; - length = __GLX_PAD(n) >> 2; - reply.type = X_Reply; - reply.sequenceNumber = client->sequence; - reply.length = length; - reply.n = n; - - buf = (char *) xalloc(length << 2); - if (buf == NULL) { - return BadAlloc; - } - memcpy(buf, ptr, n); - - if (client->swapped) { - glxSwapQueryServerStringReply(client, &reply, buf); - } else { - WriteToClient(client, sz_xGLXQueryServerStringReply, (char *)&reply); - WriteToClient(client, (int)(length << 2), buf); - } - - xfree(buf); - return Success; -} - -int __glXDisp_ClientInfo(__GLXclientState *cl, GLbyte *pc) -{ - xGLXClientInfoReq *req = (xGLXClientInfoReq *) pc; - const char *buf; - - cl->GLClientmajorVersion = req->major; - cl->GLClientminorVersion = req->minor; - if (cl->GLClientextensions) - xfree(cl->GLClientextensions); - buf = (const char *)(req+1); - cl->GLClientextensions = xstrdup(buf); - - return Success; -} +/*
+ * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
+ * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice including the dates of first publication and
+ * either this permission notice or a reference to
+ * http://oss.sgi.com/projects/FreeB/
+ * 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
+ * SILICON GRAPHICS, INC. 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 Silicon Graphics, Inc.
+ * shall not be used in advertising or otherwise to promote the sale, use or
+ * other dealings in this Software without prior written authorization from
+ * Silicon Graphics, Inc.
+ */
+
+#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+
+#include "glheader.h"
+
+#endif
+
+#include <string.h>
+#include <assert.h>
+
+#include "glxserver.h"
+#include <GL/glxtokens.h>
+#include <unpack.h>
+#include "g_disptab.h"
+#include <pixmapstr.h>
+#include <windowstr.h>
+#include "glxutil.h"
+#include "glxext.h"
+#include "glapitable.h"
+#include "glapi.h"
+#include "glthread.h"
+#include "dispatch.h"
+#include "indirect_dispatch.h"
+#include "indirect_table.h"
+#include "indirect_util.h"
+#include "protocol-versions.h"
+
+static int
+validGlxScreen(ClientPtr client, int screen, __GLXscreen **pGlxScreen, int *err)
+{
+ /*
+ ** Check if screen exists.
+ */
+ if (screen >= screenInfo.numScreens) {
+ client->errorValue = screen;
+ *err = BadValue;
+ return FALSE;
+ }
+ *pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+
+ return TRUE;
+}
+
+static int
+validGlxFBConfig(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
+ __GLXconfig **config, int *err)
+{
+ __GLXconfig *m;
+
+ for (m = pGlxScreen->fbconfigs; m != NULL; m = m->next)
+ if (m->fbconfigID == id) {
+ *config = m;
+ return TRUE;
+ }
+
+ client->errorValue = id;
+ *err = __glXError(GLXBadFBConfig);
+
+ return FALSE;
+}
+
+static int
+validGlxVisual(ClientPtr client, __GLXscreen *pGlxScreen, XID id,
+ __GLXconfig **config, int *err)
+{
+ int i;
+
+ for (i = 0; i < pGlxScreen->numVisuals; i++)
+ if (pGlxScreen->visuals[i]->visualID == id) {
+ *config = pGlxScreen->visuals[i];
+ return TRUE;
+ }
+
+ client->errorValue = id;
+ *err = BadValue;
+
+ return FALSE;
+}
+
+static int
+validGlxFBConfigForWindow(ClientPtr client, __GLXconfig *config,
+ DrawablePtr pDraw, int *err)
+{
+ ScreenPtr pScreen = pDraw->pScreen;
+ VisualPtr pVisual = NULL;
+ XID vid;
+ int i;
+
+ vid = wVisual((WindowPtr)pDraw);
+ for (i = 0; i < pScreen->numVisuals; i++) {
+ if (pScreen->visuals[i].vid == vid) {
+ pVisual = &pScreen->visuals[i];
+ break;
+ }
+ }
+
+ /* FIXME: What exactly should we check here... */
+ if (pVisual->class != glxConvertToXVisualType(config->visualType) ||
+ !(config->drawableType & GLX_WINDOW_BIT)) {
+ client->errorValue = pDraw->id;
+ *err = BadMatch;
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+static int
+validGlxContext(ClientPtr client, XID id, int access_mode,
+ __GLXcontext **context, int *err)
+{
+ *err = dixLookupResourceByType((pointer *) context, id,
+ __glXContextRes, client, access_mode);
+ if (*err != Success) {
+ client->errorValue = id;
+ if (*err == BadValue)
+ *err = __glXError(GLXBadContext);
+ return FALSE;
+ }
+
+ return TRUE;
+}
+
+static int
+validGlxDrawable(ClientPtr client, XID id, int type, int access_mode,
+ __GLXdrawable **drawable, int *err)
+{
+ int rc;
+
+ rc = dixLookupResourceByType((pointer *) drawable, id,
+ __glXDrawableRes, client, access_mode);
+ if (rc != Success && rc != BadValue) {
+ *err = rc;
+ client->errorValue = id;
+ return FALSE;
+ }
+
+ if (rc == BadValue ||
+ (type != GLX_DRAWABLE_ANY && type != (*drawable)->type)) {
+ client->errorValue = id;
+ switch (type) {
+ case GLX_DRAWABLE_WINDOW:
+ *err = __glXError(GLXBadWindow);
+ return FALSE;
+ case GLX_DRAWABLE_PIXMAP:
+ *err = __glXError(GLXBadPixmap);
+ return FALSE;
+ case GLX_DRAWABLE_PBUFFER:
+ *err = __glXError(GLXBadPbuffer);
+ return FALSE;
+ case GLX_DRAWABLE_ANY:
+ *err = __glXError(GLXBadDrawable);
+ return FALSE;
+ }
+ }
+
+ return TRUE;
+}
+
+void
+__glXContextDestroy(__GLXcontext *context)
+{
+ __glXFlushContextCache();
+}
+
+static void __glXdirectContextDestroy(__GLXcontext *context)
+{
+ __glXContextDestroy(context);
+ xfree(context);
+}
+
+static __GLXcontext *__glXdirectContextCreate(__GLXscreen *screen,
+ __GLXconfig *modes,
+ __GLXcontext *shareContext)
+{
+ __GLXcontext *context;
+
+ context = xcalloc (1, sizeof (__GLXcontext));
+ if (context == NULL)
+ return NULL;
+
+ context->destroy = __glXdirectContextDestroy;
+
+ return context;
+}
+
+/**
+ * Create a GL context with the given properties. This routine is used
+ * to implement \c glXCreateContext, \c glXCreateNewContext, and
+ * \c glXCreateContextWithConfigSGIX. This works becuase of the hack way
+ * that GLXFBConfigs are implemented. Basically, the FBConfigID is the
+ * same as the VisualID.
+ */
+
+static int
+DoCreateContext(__GLXclientState *cl, GLXContextID gcId,
+ GLXContextID shareList, __GLXconfig *config,
+ __GLXscreen *pGlxScreen, GLboolean isDirect)
+{
+ ClientPtr client = cl->client;
+ __GLXcontext *glxc, *shareglxc;
+ int err;
+
+ LEGAL_NEW_RESOURCE(gcId, client);
+
+ /*
+ ** Find the display list space that we want to share.
+ **
+ ** NOTE: In a multithreaded X server, we would need to keep a reference
+ ** count for each display list so that if one client detroyed a list that
+ ** another client was using, the list would not really be freed until it
+ ** was no longer in use. Since this sample implementation has no support
+ ** for multithreaded servers, we don't do this.
+ */
+ if (shareList == None) {
+ shareglxc = 0;
+ } else {
+ if (!validGlxContext(client, shareList, DixReadAccess,
+ &shareglxc, &err))
+ return err;
+
+ if (shareglxc->isDirect) {
+ /*
+ ** NOTE: no support for sharing display lists between direct
+ ** contexts, even if they are in the same address space.
+ */
+#if 0
+ /* Disabling this code seems to allow shared display lists
+ * and texture objects to work. We'll leave it disabled for now.
+ */
+ client->errorValue = shareList;
+ return BadMatch;
+#endif
+ } else {
+ /*
+ ** Create an indirect context regardless of what the client asked
+ ** for; this way we can share display list space with shareList.
+ */
+ isDirect = GL_FALSE;
+ }
+ }
+
+ /*
+ ** Allocate memory for the new context
+ */
+ if (!isDirect)
+ glxc = pGlxScreen->createContext(pGlxScreen, config, shareglxc);
+ else
+ glxc = __glXdirectContextCreate(pGlxScreen, config, shareglxc);
+ if (!glxc) {
+ return BadAlloc;
+ }
+
+ /*
+ ** Initially, setup the part of the context that could be used by
+ ** a GL core that needs windowing information (e.g., Mesa).
+ */
+ glxc->pGlxScreen = pGlxScreen;
+ glxc->config = config;
+
+ /*
+ ** Register this context as a resource.
+ */
+ if (!AddResource(gcId, __glXContextRes, (pointer)glxc)) {
+ (*glxc->destroy)(glxc);
+ client->errorValue = gcId;
+ return BadAlloc;
+ }
+
+ /*
+ ** Finally, now that everything is working, setup the rest of the
+ ** context.
+ */
+ glxc->id = gcId;
+ glxc->share_id = shareList;
+ glxc->idExists = GL_TRUE;
+ glxc->isCurrent = GL_FALSE;
+ glxc->isDirect = isDirect;
+ glxc->renderMode = GL_RENDER;
+
+ __glXAddToContextList(glxc);
+
+ return Success;
+}
+
+int __glXDisp_CreateContext(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateContextReq *req = (xGLXCreateContextReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err))
+ return err;
+
+ return DoCreateContext(cl, req->context, req->shareList,
+ config, pGlxScreen, req->isDirect);
+}
+
+int __glXDisp_CreateNewContext(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateNewContextReq *req = (xGLXCreateNewContextReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err))
+ return err;
+
+ return DoCreateContext(cl, req->context, req->shareList,
+ config, pGlxScreen, req->isDirect);
+}
+
+int __glXDisp_CreateContextWithConfigSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateContextWithConfigSGIXReq *req =
+ (xGLXCreateContextWithConfigSGIXReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err))
+ return err;
+
+ return DoCreateContext(cl, req->context, req->shareList,
+ config, pGlxScreen, req->isDirect);
+}
+int __glXDisp_DestroyContext(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyContextReq *req = (xGLXDestroyContextReq *) pc;
+ __GLXcontext *glxc;
+ int err;
+
+ if (!validGlxContext(cl->client, req->context, DixDestroyAccess,
+ &glxc, &err))
+ return err;
+
+ FreeResourceByType(req->context, __glXContextRes, FALSE);
+ return Success;
+}
+
+/*****************************************************************************/
+
+/*
+** For each client, the server keeps a table of all the contexts that are
+** current for that client (each thread of a client may have its own current
+** context). These routines add, change, and lookup contexts in the table.
+*/
+
+/*
+** Add a current context, and return the tag that will be used to refer to it.
+*/
+static int AddCurrentContext(__GLXclientState *cl, __GLXcontext *glxc)
+{
+ int i;
+ int num = cl->numCurrentContexts;
+ __GLXcontext **table = cl->currentContexts;
+
+ if (!glxc) return -1;
+
+ /*
+ ** Try to find an empty slot and use it.
+ */
+ for (i=0; i < num; i++) {
+ if (!table[i]) {
+ table[i] = glxc;
+ return i+1;
+ }
+ }
+ /*
+ ** Didn't find a free slot, so we'll have to grow the table.
+ */
+ if (!num) {
+ table = (__GLXcontext **) xalloc(sizeof(__GLXcontext *));
+ } else {
+ table = (__GLXcontext **) xrealloc(table,
+ (num+1)*sizeof(__GLXcontext *));
+ }
+ table[num] = glxc;
+ cl->currentContexts = table;
+ cl->numCurrentContexts++;
+ return num+1;
+}
+
+/*
+** Given a tag, change the current context for the corresponding entry.
+*/
+static void ChangeCurrentContext(__GLXclientState *cl, __GLXcontext *glxc,
+ GLXContextTag tag)
+{
+ __GLXcontext **table = cl->currentContexts;
+ table[tag-1] = glxc;
+}
+
+/*
+** For this implementation we have chosen to simply use the index of the
+** context's entry in the table as the context tag. A tag must be greater
+** than 0.
+*/
+__GLXcontext *__glXLookupContextByTag(__GLXclientState *cl, GLXContextTag tag)
+{
+ int num = cl->numCurrentContexts;
+
+ if (tag < 1 || tag > num) {
+ return 0;
+ } else {
+ return cl->currentContexts[tag-1];
+ }
+}
+
+/*****************************************************************************/
+
+static void StopUsingContext(__GLXcontext *glxc)
+{
+ if (glxc) {
+ if (glxc == __glXLastContext) {
+ /* Tell server GL library */
+ __glXLastContext = 0;
+ }
+ glxc->isCurrent = GL_FALSE;
+ if (!glxc->idExists) {
+ __glXFreeContext(glxc);
+ }
+ }
+}
+
+static void StartUsingContext(__GLXclientState *cl, __GLXcontext *glxc)
+{
+ glxc->isCurrent = GL_TRUE;
+ __glXLastContext = glxc;
+}
+
+/**
+ * This is a helper function to handle the legacy (pre GLX 1.3) cases
+ * where passing an X window to glXMakeCurrent is valid. Given a
+ * resource ID, look up the GLX drawable if available, otherwise, make
+ * sure it's an X window and create a GLX drawable one the fly.
+ */
+static __GLXdrawable *
+__glXGetDrawable(__GLXcontext *glxc, GLXDrawable drawId, ClientPtr client,
+ int *error)
+{
+ DrawablePtr pDraw;
+ __GLXdrawable *pGlxDraw;
+ int rc;
+
+ if (validGlxDrawable(client, drawId, GLX_DRAWABLE_ANY,
+ DixWriteAccess, &pGlxDraw, &rc)) {
+ if (glxc != NULL && pGlxDraw->config != glxc->config) {
+ client->errorValue = drawId;
+ *error = BadMatch;
+ return NULL;
+ }
+
+ return pGlxDraw;
+ }
+
+ /* The drawId wasn't a GLX drawable. Make sure it's a window and
+ * create a GLXWindow for it. Check that the drawable screen
+ * matches the context screen and that the context fbconfig is
+ * compatible with the window visual. */
+
+ rc = dixLookupDrawable(&pDraw, drawId, client, 0, DixGetAttrAccess);
+ if (rc != Success || pDraw->type != DRAWABLE_WINDOW) {
+ client->errorValue = drawId;
+ *error = __glXError(GLXBadDrawable);
+ return NULL;
+ }
+
+ if (pDraw->pScreen != glxc->pGlxScreen->pScreen) {
+ client->errorValue = pDraw->pScreen->myNum;
+ *error = BadMatch;
+ return NULL;
+ }
+
+ if (!validGlxFBConfigForWindow(client, glxc->config, pDraw, error))
+ return NULL;
+
+ pGlxDraw = glxc->pGlxScreen->createDrawable(glxc->pGlxScreen,
+ pDraw, GLX_DRAWABLE_WINDOW,
+ drawId, glxc->config);
+
+ /* since we are creating the drawablePrivate, drawId should be new */
+ if (!AddResource(drawId, __glXDrawableRes, pGlxDraw)) {
+ pGlxDraw->destroy (pGlxDraw);
+ *error = BadAlloc;
+ return NULL;
+ }
+
+ return pGlxDraw;
+}
+
+/*****************************************************************************/
+/*
+** Make an OpenGL context and drawable current.
+*/
+
+static int
+DoMakeCurrent(__GLXclientState *cl,
+ GLXDrawable drawId, GLXDrawable readId,
+ GLXContextID contextId, GLXContextTag tag)
+{
+ ClientPtr client = cl->client;
+ xGLXMakeCurrentReply reply;
+ __GLXcontext *glxc, *prevglxc;
+ __GLXdrawable *drawPriv = NULL;
+ __GLXdrawable *readPriv = NULL;
+ int error;
+ GLuint mask;
+
+ /*
+ ** If one is None and the other isn't, it's a bad match.
+ */
+
+ mask = (drawId == None) ? (1 << 0) : 0;
+ mask |= (readId == None) ? (1 << 1) : 0;
+ mask |= (contextId == None) ? (1 << 2) : 0;
+
+ if ( (mask != 0x00) && (mask != 0x07) ) {
+ return BadMatch;
+ }
+
+ /*
+ ** Lookup old context. If we have one, it must be in a usable state.
+ */
+ if (tag != 0) {
+ prevglxc = __glXLookupContextByTag(cl, tag);
+ if (!prevglxc) {
+ /*
+ ** Tag for previous context is invalid.
+ */
+ return __glXError(GLXBadContextTag);
+ }
+ if (prevglxc->renderMode != GL_RENDER) {
+ /* Oops. Not in render mode render. */
+ client->errorValue = prevglxc->id;
+ return __glXError(GLXBadContextState);
+ }
+ } else {
+ prevglxc = 0;
+ }
+
+ /*
+ ** Lookup new context. It must not be current for someone else.
+ */
+ if (contextId != None) {
+ int status;
+
+ if (!validGlxContext(client, contextId, DixUseAccess, &glxc, &error))
+ return error;
+ if ((glxc != prevglxc) && glxc->isCurrent) {
+ /* Context is current to somebody else */
+ return BadAccess;
+ }
+
+ assert( drawId != None );
+ assert( readId != None );
+
+ drawPriv = __glXGetDrawable(glxc, drawId, client, &status);
+ if (drawPriv == NULL)
+ return status;
+
+ readPriv = __glXGetDrawable(glxc, readId, client, &status);
+ if (readPriv == NULL)
+ return status;
+
+ } else {
+ /* Switching to no context. Ignore new drawable. */
+ glxc = 0;
+ drawPriv = 0;
+ readPriv = 0;
+ }
+
+
+ if (prevglxc) {
+ /*
+ ** Flush the previous context if needed.
+ */
+ if (__GLX_HAS_UNFLUSHED_CMDS(prevglxc)) {
+ if (__glXForceCurrent(cl, tag, (int *)&error)) {
+ CALL_Flush( GET_DISPATCH(), () );
+ __GLX_NOTE_FLUSHED_CMDS(prevglxc);
+ } else {
+ return error;
+ }
+ }
+
+ /*
+ ** Make the previous context not current.
+ */
+ if (!(*prevglxc->loseCurrent)(prevglxc)) {
+ return __glXError(GLXBadContext);
+ }
+ __glXFlushContextCache();
+ if (!prevglxc->isDirect) {
+ prevglxc->drawPriv = NULL;
+ prevglxc->readPriv = NULL;
+ }
+ }
+
+
+ if ((glxc != 0) && !glxc->isDirect) {
+
+ glxc->drawPriv = drawPriv;
+ glxc->readPriv = readPriv;
+
+ /* make the context current */
+ if (!(*glxc->makeCurrent)(glxc)) {
+ glxc->drawPriv = NULL;
+ glxc->readPriv = NULL;
+ return __glXError(GLXBadContext);
+ }
+
+ glxc->isCurrent = GL_TRUE;
+ }
+
+ if (prevglxc) {
+ ChangeCurrentContext(cl, glxc, tag);
+ StopUsingContext(prevglxc);
+ } else {
+ tag = AddCurrentContext(cl, glxc);
+ }
+
+ if (glxc) {
+ StartUsingContext(cl, glxc);
+ reply.contextTag = tag;
+ } else {
+ reply.contextTag = 0;
+ }
+
+ reply.length = 0;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __glXSwapMakeCurrentReply(client, &reply);
+ } else {
+ WriteToClient(client, sz_xGLXMakeCurrentReply, (char *)&reply);
+ }
+ return Success;
+}
+
+int __glXDisp_MakeCurrent(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXMakeCurrentReq *req = (xGLXMakeCurrentReq *) pc;
+
+ return DoMakeCurrent( cl, req->drawable, req->drawable,
+ req->context, req->oldContextTag );
+}
+
+int __glXDisp_MakeContextCurrent(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXMakeContextCurrentReq *req = (xGLXMakeContextCurrentReq *) pc;
+
+ return DoMakeCurrent( cl, req->drawable, req->readdrawable,
+ req->context, req->oldContextTag );
+}
+
+int __glXDisp_MakeCurrentReadSGI(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXMakeCurrentReadSGIReq *req = (xGLXMakeCurrentReadSGIReq *) pc;
+
+ return DoMakeCurrent( cl, req->drawable, req->readable,
+ req->context, req->oldContextTag );
+}
+
+int __glXDisp_IsDirect(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXIsDirectReq *req = (xGLXIsDirectReq *) pc;
+ xGLXIsDirectReply reply;
+ __GLXcontext *glxc;
+ int err;
+
+ if (!validGlxContext(cl->client, req->context, DixReadAccess, &glxc, &err))
+ return err;
+
+ reply.isDirect = glxc->isDirect;
+ reply.length = 0;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __glXSwapIsDirectReply(client, &reply);
+ } else {
+ WriteToClient(client, sz_xGLXIsDirectReply, (char *)&reply);
+ }
+
+ return Success;
+}
+
+int __glXDisp_QueryVersion(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryVersionReq *req = (xGLXQueryVersionReq *) pc;
+ xGLXQueryVersionReply reply;
+ GLuint major, minor;
+
+ major = req->majorVersion;
+ minor = req->minorVersion;
+ (void)major;
+ (void)minor;
+
+ /*
+ ** Server should take into consideration the version numbers sent by the
+ ** client if it wants to work with older clients; however, in this
+ ** implementation the server just returns its version number.
+ */
+ reply.majorVersion = SERVER_GLX_MAJOR_VERSION;
+ reply.minorVersion = SERVER_GLX_MINOR_VERSION;
+ reply.length = 0;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __glXSwapQueryVersionReply(client, &reply);
+ } else {
+ WriteToClient(client, sz_xGLXQueryVersionReply, (char *)&reply);
+ }
+ return Success;
+}
+
+int __glXDisp_WaitGL(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXWaitGLReq *req = (xGLXWaitGLReq *)pc;
+ GLXContextTag tag = req->contextTag;
+ __GLXcontext *glxc = NULL;
+ int error;
+
+ if (tag) {
+ glxc = __glXLookupContextByTag(cl, tag);
+ if (!glxc)
+ return __glXError(GLXBadContextTag);
+
+ if (!__glXForceCurrent(cl, req->contextTag, &error))
+ return error;
+
+ CALL_Finish( GET_DISPATCH(), () );
+ }
+
+ if (glxc && glxc->drawPriv->waitGL)
+ (*glxc->drawPriv->waitGL)(glxc->drawPriv);
+
+ return Success;
+}
+
+int __glXDisp_WaitX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXWaitXReq *req = (xGLXWaitXReq *)pc;
+ GLXContextTag tag = req->contextTag;
+ __GLXcontext *glxc = NULL;
+ int error;
+
+ if (tag) {
+ glxc = __glXLookupContextByTag(cl, tag);
+ if (!glxc)
+ return __glXError(GLXBadContextTag);
+
+ if (!__glXForceCurrent(cl, req->contextTag, &error))
+ return error;
+ }
+
+ if (glxc && glxc->drawPriv->waitX)
+ (*glxc->drawPriv->waitX)(glxc->drawPriv);
+
+ return Success;
+}
+
+int __glXDisp_CopyContext(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXCopyContextReq *req = (xGLXCopyContextReq *) pc;
+ GLXContextID source = req->source;
+ GLXContextID dest = req->dest;
+ GLXContextTag tag = req->contextTag;
+ unsigned long mask = req->mask;
+ __GLXcontext *src, *dst;
+ int error;
+
+ if (!validGlxContext(cl->client, source, DixReadAccess, &src, &error))
+ return error;
+ if (!validGlxContext(cl->client, dest, DixWriteAccess, &dst, &error))
+ return error;
+
+ /*
+ ** They must be in the same address space, and same screen.
+ ** NOTE: no support for direct rendering contexts here.
+ */
+ if (src->isDirect || dst->isDirect ||
+ (src->pGlxScreen != dst->pGlxScreen)) {
+ client->errorValue = source;
+ return BadMatch;
+ }
+
+ /*
+ ** The destination context must not be current for any client.
+ */
+ if (dst->isCurrent) {
+ client->errorValue = dest;
+ return BadAccess;
+ }
+
+ if (tag) {
+ __GLXcontext *tagcx = __glXLookupContextByTag(cl, tag);
+
+ if (!tagcx) {
+ return __glXError(GLXBadContextTag);
+ }
+ if (tagcx != src) {
+ /*
+ ** This would be caused by a faulty implementation of the client
+ ** library.
+ */
+ return BadMatch;
+ }
+ /*
+ ** In this case, glXCopyContext is in both GL and X streams, in terms
+ ** of sequentiality.
+ */
+ if (__glXForceCurrent(cl, tag, &error)) {
+ /*
+ ** Do whatever is needed to make sure that all preceding requests
+ ** in both streams are completed before the copy is executed.
+ */
+ CALL_Finish( GET_DISPATCH(), () );
+ __GLX_NOTE_FLUSHED_CMDS(tagcx);
+ } else {
+ return error;
+ }
+ }
+ /*
+ ** Issue copy. The only reason for failure is a bad mask.
+ */
+ if (!(*dst->copy)(dst, src, mask)) {
+ client->errorValue = mask;
+ return BadValue;
+ }
+ return Success;
+}
+
+enum {
+ GLX_VIS_CONFIG_UNPAIRED = 18,
+ GLX_VIS_CONFIG_PAIRED = 20
+};
+
+enum {
+ GLX_VIS_CONFIG_TOTAL = GLX_VIS_CONFIG_UNPAIRED + GLX_VIS_CONFIG_PAIRED
+};
+
+int __glXDisp_GetVisualConfigs(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXGetVisualConfigsReq *req = (xGLXGetVisualConfigsReq *) pc;
+ ClientPtr client = cl->client;
+ xGLXGetVisualConfigsReply reply;
+ __GLXscreen *pGlxScreen;
+ __GLXconfig *modes;
+ CARD32 buf[GLX_VIS_CONFIG_TOTAL];
+ int p, i, err;
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_DECLARE_SWAP_ARRAY_VARIABLES;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+
+ reply.numVisuals = pGlxScreen->numVisuals;
+ reply.numProps = GLX_VIS_CONFIG_TOTAL;
+ reply.length = (reply.numVisuals * __GLX_SIZE_CARD32 * GLX_VIS_CONFIG_TOTAL) >> 2;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ __GLX_SWAP_INT(&reply.length);
+ __GLX_SWAP_INT(&reply.numVisuals);
+ __GLX_SWAP_INT(&reply.numProps);
+ }
+
+ WriteToClient(client, sz_xGLXGetVisualConfigsReply, (char *)&reply);
+
+ for (i = 0; i < pGlxScreen->numVisuals; i++) {
+ modes = pGlxScreen->visuals[i];
+
+ p = 0;
+ buf[p++] = modes->visualID;
+ buf[p++] = glxConvertToXVisualType( modes->visualType );
+ buf[p++] = (modes->renderType & GLX_RGBA_BIT) ? GL_TRUE : GL_FALSE;
+
+ buf[p++] = modes->redBits;
+ buf[p++] = modes->greenBits;
+ buf[p++] = modes->blueBits;
+ buf[p++] = modes->alphaBits;
+ buf[p++] = modes->accumRedBits;
+ buf[p++] = modes->accumGreenBits;
+ buf[p++] = modes->accumBlueBits;
+ buf[p++] = modes->accumAlphaBits;
+
+ buf[p++] = modes->doubleBufferMode;
+ buf[p++] = modes->stereoMode;
+
+ buf[p++] = modes->rgbBits;
+ buf[p++] = modes->depthBits;
+ buf[p++] = modes->stencilBits;
+ buf[p++] = modes->numAuxBuffers;
+ buf[p++] = modes->level;
+
+ assert(p == GLX_VIS_CONFIG_UNPAIRED);
+ /*
+ ** Add token/value pairs for extensions.
+ */
+ buf[p++] = GLX_VISUAL_CAVEAT_EXT;
+ buf[p++] = modes->visualRating;
+ buf[p++] = GLX_TRANSPARENT_TYPE;
+ buf[p++] = modes->transparentPixel;
+ buf[p++] = GLX_TRANSPARENT_RED_VALUE;
+ buf[p++] = modes->transparentRed;
+ buf[p++] = GLX_TRANSPARENT_GREEN_VALUE;
+ buf[p++] = modes->transparentGreen;
+ buf[p++] = GLX_TRANSPARENT_BLUE_VALUE;
+ buf[p++] = modes->transparentBlue;
+ buf[p++] = GLX_TRANSPARENT_ALPHA_VALUE;
+ buf[p++] = modes->transparentAlpha;
+ buf[p++] = GLX_TRANSPARENT_INDEX_VALUE;
+ buf[p++] = modes->transparentIndex;
+ buf[p++] = GLX_SAMPLES_SGIS;
+ buf[p++] = modes->samples;
+ buf[p++] = GLX_SAMPLE_BUFFERS_SGIS;
+ buf[p++] = modes->sampleBuffers;
+ buf[p++] = 0; /* copy over visualSelectGroup (GLX_VISUAL_SELECT_GROUP_SGIX)? */
+ buf[p++] = 0;
+
+ assert(p == GLX_VIS_CONFIG_TOTAL);
+ if (client->swapped) {
+ __GLX_SWAP_INT_ARRAY(buf, p);
+ }
+ WriteToClient(client, __GLX_SIZE_CARD32 * p, (char *)buf);
+ }
+ return Success;
+}
+
+#define __GLX_TOTAL_FBCONFIG_ATTRIBS (36)
+#define __GLX_FBCONFIG_ATTRIBS_LENGTH (__GLX_TOTAL_FBCONFIG_ATTRIBS * 2)
+/**
+ * Send the set of GLXFBConfigs to the client. There is not currently
+ * and interface into the driver on the server-side to get GLXFBConfigs,
+ * so we "invent" some based on the \c __GLXvisualConfig structures that
+ * the driver does supply.
+ *
+ * The reply format for both \c glXGetFBConfigs and \c glXGetFBConfigsSGIX
+ * is the same, so this routine pulls double duty.
+ */
+
+static int
+DoGetFBConfigs(__GLXclientState *cl, unsigned screen)
+{
+ ClientPtr client = cl->client;
+ xGLXGetFBConfigsReply reply;
+ __GLXscreen *pGlxScreen;
+ CARD32 buf[__GLX_FBCONFIG_ATTRIBS_LENGTH];
+ int p, err;
+ __GLXconfig *modes;
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_DECLARE_SWAP_ARRAY_VARIABLES;
+
+ if (!validGlxScreen(cl->client, screen, &pGlxScreen, &err))
+ return err;
+
+ reply.numFBConfigs = pGlxScreen->numFBConfigs;
+ reply.numAttribs = __GLX_TOTAL_FBCONFIG_ATTRIBS;
+ reply.length = (__GLX_FBCONFIG_ATTRIBS_LENGTH * reply.numFBConfigs);
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ __GLX_SWAP_INT(&reply.length);
+ __GLX_SWAP_INT(&reply.numFBConfigs);
+ __GLX_SWAP_INT(&reply.numAttribs);
+ }
+
+ WriteToClient(client, sz_xGLXGetFBConfigsReply, (char *)&reply);
+
+ for (modes = pGlxScreen->fbconfigs; modes != NULL; modes = modes->next) {
+ p = 0;
+
+#define WRITE_PAIR(tag,value) \
+ do { buf[p++] = tag ; buf[p++] = value ; } while( 0 )
+
+ WRITE_PAIR( GLX_VISUAL_ID, modes->visualID );
+ WRITE_PAIR( GLX_FBCONFIG_ID, modes->fbconfigID );
+ WRITE_PAIR( GLX_X_RENDERABLE, GL_TRUE );
+
+ WRITE_PAIR( GLX_RGBA,
+ (modes->renderType & GLX_RGBA_BIT) ? GL_TRUE : GL_FALSE );
+ WRITE_PAIR( GLX_RENDER_TYPE, modes->renderType );
+ WRITE_PAIR( GLX_DOUBLEBUFFER, modes->doubleBufferMode );
+ WRITE_PAIR( GLX_STEREO, modes->stereoMode );
+
+ WRITE_PAIR( GLX_BUFFER_SIZE, modes->rgbBits );
+ WRITE_PAIR( GLX_LEVEL, modes->level );
+ WRITE_PAIR( GLX_AUX_BUFFERS, modes->numAuxBuffers );
+ WRITE_PAIR( GLX_RED_SIZE, modes->redBits );
+ WRITE_PAIR( GLX_GREEN_SIZE, modes->greenBits );
+ WRITE_PAIR( GLX_BLUE_SIZE, modes->blueBits );
+ WRITE_PAIR( GLX_ALPHA_SIZE, modes->alphaBits );
+ WRITE_PAIR( GLX_ACCUM_RED_SIZE, modes->accumRedBits );
+ WRITE_PAIR( GLX_ACCUM_GREEN_SIZE, modes->accumGreenBits );
+ WRITE_PAIR( GLX_ACCUM_BLUE_SIZE, modes->accumBlueBits );
+ WRITE_PAIR( GLX_ACCUM_ALPHA_SIZE, modes->accumAlphaBits );
+ WRITE_PAIR( GLX_DEPTH_SIZE, modes->depthBits );
+ WRITE_PAIR( GLX_STENCIL_SIZE, modes->stencilBits );
+ WRITE_PAIR( GLX_X_VISUAL_TYPE, modes->visualType );
+ WRITE_PAIR( GLX_CONFIG_CAVEAT, modes->visualRating );
+ WRITE_PAIR( GLX_TRANSPARENT_TYPE, modes->transparentPixel );
+ WRITE_PAIR( GLX_TRANSPARENT_RED_VALUE, modes->transparentRed );
+ WRITE_PAIR( GLX_TRANSPARENT_GREEN_VALUE, modes->transparentGreen );
+ WRITE_PAIR( GLX_TRANSPARENT_BLUE_VALUE, modes->transparentBlue );
+ WRITE_PAIR( GLX_TRANSPARENT_ALPHA_VALUE, modes->transparentAlpha );
+ WRITE_PAIR( GLX_TRANSPARENT_INDEX_VALUE, modes->transparentIndex );
+ WRITE_PAIR( GLX_SWAP_METHOD_OML, modes->swapMethod );
+ WRITE_PAIR( GLX_SAMPLES_SGIS, modes->samples );
+ WRITE_PAIR( GLX_SAMPLE_BUFFERS_SGIS, modes->sampleBuffers );
+ /* GLX_VISUAL_SELECT_GROUP_SGIX ? */
+ WRITE_PAIR( GLX_DRAWABLE_TYPE, modes->drawableType );
+ WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGB_EXT, modes->bindToTextureRgb );
+ WRITE_PAIR( GLX_BIND_TO_TEXTURE_RGBA_EXT, modes->bindToTextureRgba );
+ WRITE_PAIR( GLX_BIND_TO_MIPMAP_TEXTURE_EXT, modes->bindToMipmapTexture );
+ WRITE_PAIR( GLX_BIND_TO_TEXTURE_TARGETS_EXT, modes->bindToTextureTargets );
+
+ if (client->swapped) {
+ __GLX_SWAP_INT_ARRAY(buf, __GLX_FBCONFIG_ATTRIBS_LENGTH);
+ }
+ WriteToClient(client, __GLX_SIZE_CARD32 * __GLX_FBCONFIG_ATTRIBS_LENGTH,
+ (char *)buf);
+ }
+ return Success;
+}
+
+
+int __glXDisp_GetFBConfigs(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXGetFBConfigsReq *req = (xGLXGetFBConfigsReq *) pc;
+ return DoGetFBConfigs(cl, req->screen);
+}
+
+int __glXDisp_GetFBConfigsSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXGetFBConfigsSGIXReq *req = (xGLXGetFBConfigsSGIXReq *) pc;
+ return DoGetFBConfigs(cl, req->screen);
+}
+
+GLboolean
+__glXDrawableInit(__GLXdrawable *drawable,
+ __GLXscreen *screen, DrawablePtr pDraw, int type,
+ XID drawId, __GLXconfig *config)
+{
+ drawable->pDraw = pDraw;
+ drawable->type = type;
+ drawable->drawId = drawId;
+ drawable->config = config;
+ drawable->eventMask = 0;
+
+ return GL_TRUE;
+}
+
+void
+__glXDrawableRelease(__GLXdrawable *drawable)
+{
+ ScreenPtr pScreen = drawable->pDraw->pScreen;
+
+ switch (drawable->type) {
+ case GLX_DRAWABLE_PIXMAP:
+ case GLX_DRAWABLE_PBUFFER:
+ (*pScreen->DestroyPixmap)((PixmapPtr) drawable->pDraw);
+ break;
+ }
+}
+
+static int
+DoCreateGLXDrawable(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config,
+ DrawablePtr pDraw, XID glxDrawableId, int type)
+{
+ __GLXdrawable *pGlxDraw;
+
+ LEGAL_NEW_RESOURCE(glxDrawableId, client);
+
+ if (pGlxScreen->pScreen != pDraw->pScreen)
+ return BadMatch;
+
+ pGlxDraw = pGlxScreen->createDrawable(pGlxScreen, pDraw, type,
+ glxDrawableId, config);
+ if (pGlxDraw == NULL)
+ return BadAlloc;
+
+ if (!AddResource(glxDrawableId, __glXDrawableRes, pGlxDraw)) {
+ pGlxDraw->destroy (pGlxDraw);
+ return BadAlloc;
+ }
+
+ return Success;
+}
+
+static int
+DoCreateGLXPixmap(ClientPtr client, __GLXscreen *pGlxScreen, __GLXconfig *config,
+ XID drawableId, XID glxDrawableId)
+{
+ DrawablePtr pDraw;
+ int err;
+
+ err = dixLookupDrawable(&pDraw, drawableId, client, 0, DixAddAccess);
+ if (err != Success) {
+ client->errorValue = drawableId;
+ return err;
+ }
+ if (pDraw->type != DRAWABLE_PIXMAP) {
+ client->errorValue = drawableId;
+ return BadPixmap;
+ }
+
+ err = DoCreateGLXDrawable(client, pGlxScreen, config, pDraw,
+ glxDrawableId, GLX_DRAWABLE_PIXMAP);
+
+ if (err == Success)
+ ((PixmapPtr) pDraw)->refcnt++;
+
+ return err;
+}
+
+static void
+determineTextureTarget(ClientPtr client, XID glxDrawableID,
+ CARD32 *attribs, CARD32 numAttribs)
+{
+ GLenum target = 0;
+ GLenum format = 0;
+ int i, err;
+ __GLXdrawable *pGlxDraw;
+
+ if (!validGlxDrawable(client, glxDrawableID, GLX_DRAWABLE_PIXMAP,
+ DixWriteAccess, &pGlxDraw, &err))
+ /* We just added it in CreatePixmap, so we should never get here. */
+ return;
+
+ for (i = 0; i < numAttribs; i++) {
+ if (attribs[2 * i] == GLX_TEXTURE_TARGET_EXT) {
+ switch (attribs[2 * i + 1]) {
+ case GLX_TEXTURE_2D_EXT:
+ target = GL_TEXTURE_2D;
+ break;
+ case GLX_TEXTURE_RECTANGLE_EXT:
+ target = GL_TEXTURE_RECTANGLE_ARB;
+ break;
+ }
+ }
+
+ if (attribs[2 * i] == GLX_TEXTURE_FORMAT_EXT)
+ format = attribs[2 * i + 1];
+ }
+
+ if (!target) {
+ int w = pGlxDraw->pDraw->width, h = pGlxDraw->pDraw->height;
+
+ if (h & (h - 1) || w & (w - 1))
+ target = GL_TEXTURE_RECTANGLE_ARB;
+ else
+ target = GL_TEXTURE_2D;
+ }
+
+ pGlxDraw->target = target;
+ pGlxDraw->format = format;
+}
+
+int __glXDisp_CreateGLXPixmap(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateGLXPixmapReq *req = (xGLXCreateGLXPixmapReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxVisual(cl->client, pGlxScreen, req->visual, &config, &err))
+ return err;
+
+ return DoCreateGLXPixmap(cl->client, pGlxScreen, config,
+ req->pixmap, req->glxpixmap);
+}
+
+int __glXDisp_CreatePixmap(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreatePixmapReq *req = (xGLXCreatePixmapReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err))
+ return err;
+
+ err = DoCreateGLXPixmap(cl->client, pGlxScreen, config,
+ req->pixmap, req->glxpixmap);
+ if (err != Success)
+ return err;
+
+ determineTextureTarget(cl->client, req->glxpixmap,
+ (CARD32*) (req + 1), req->numAttribs);
+
+ return Success;
+}
+
+int __glXDisp_CreateGLXPixmapWithConfigSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateGLXPixmapWithConfigSGIXReq *req =
+ (xGLXCreateGLXPixmapWithConfigSGIXReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(cl->client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(cl->client, pGlxScreen, req->fbconfig, &config, &err))
+ return err;
+
+ return DoCreateGLXPixmap(cl->client, pGlxScreen,
+ config, req->pixmap, req->glxpixmap);
+}
+
+
+static int DoDestroyDrawable(__GLXclientState *cl, XID glxdrawable, int type)
+{
+ __GLXdrawable *pGlxDraw;
+ int err;
+
+ if (!validGlxDrawable(cl->client, glxdrawable, type,
+ DixDestroyAccess, &pGlxDraw, &err))
+ return err;
+
+ FreeResource(glxdrawable, FALSE);
+
+ return Success;
+}
+
+int __glXDisp_DestroyGLXPixmap(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyGLXPixmapReq *req = (xGLXDestroyGLXPixmapReq *) pc;
+
+ return DoDestroyDrawable(cl, req->glxpixmap, GLX_DRAWABLE_PIXMAP);
+}
+
+int __glXDisp_DestroyPixmap(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyPixmapReq *req = (xGLXDestroyPixmapReq *) pc;
+
+ return DoDestroyDrawable(cl, req->glxpixmap, GLX_DRAWABLE_PIXMAP);
+}
+
+static int
+DoCreatePbuffer(ClientPtr client, int screenNum, XID fbconfigId,
+ int width, int height, XID glxDrawableId)
+{
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ PixmapPtr pPixmap;
+ int err;
+
+ if (!validGlxScreen(client, screenNum, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(client, pGlxScreen, fbconfigId, &config, &err))
+ return err;
+
+ __glXenterServer(GL_FALSE);
+ pPixmap = (*pGlxScreen->pScreen->CreatePixmap) (pGlxScreen->pScreen,
+ width, height, config->rgbBits, 0);
+ __glXleaveServer(GL_FALSE);
+
+ return DoCreateGLXDrawable(client, pGlxScreen, config, &pPixmap->drawable,
+ glxDrawableId, GLX_DRAWABLE_PBUFFER);
+}
+
+int __glXDisp_CreatePbuffer(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreatePbufferReq *req = (xGLXCreatePbufferReq *) pc;
+ CARD32 *attrs;
+ int width, height, i;
+
+ attrs = (CARD32 *) (req + 1);
+ width = 0;
+ height = 0;
+
+ for (i = 0; i < req->numAttribs; i++) {
+ switch (attrs[i * 2]) {
+ case GLX_PBUFFER_WIDTH:
+ width = attrs[i * 2 + 1];
+ break;
+ case GLX_PBUFFER_HEIGHT:
+ height = attrs[i * 2 + 1];
+ break;
+ case GLX_LARGEST_PBUFFER:
+ case GLX_PRESERVED_CONTENTS:
+ /* FIXME: huh... */
+ break;
+ }
+ }
+
+ return DoCreatePbuffer(cl->client, req->screen, req->fbconfig,
+ width, height, req->pbuffer);
+}
+
+int __glXDisp_CreateGLXPbufferSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateGLXPbufferSGIXReq *req = (xGLXCreateGLXPbufferSGIXReq *) pc;
+
+ return DoCreatePbuffer(cl->client, req->screen, req->fbconfig,
+ req->width, req->height, req->pbuffer);
+}
+
+int __glXDisp_DestroyPbuffer(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyPbufferReq *req = (xGLXDestroyPbufferReq *) pc;
+
+ return DoDestroyDrawable(cl, req->pbuffer, GLX_DRAWABLE_PBUFFER);
+}
+
+int __glXDisp_DestroyGLXPbufferSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyGLXPbufferSGIXReq *req = (xGLXDestroyGLXPbufferSGIXReq *) pc;
+
+ return DoDestroyDrawable(cl, req->pbuffer, GLX_DRAWABLE_PBUFFER);
+}
+
+static int
+DoChangeDrawableAttributes(ClientPtr client, XID glxdrawable,
+ int numAttribs, CARD32 *attribs)
+{
+ __GLXdrawable *pGlxDraw;
+ int i, err;
+
+ if (!validGlxDrawable(client, glxdrawable, GLX_DRAWABLE_ANY,
+ DixSetAttrAccess, &pGlxDraw, &err))
+ return err;
+
+ for (i = 0; i < numAttribs; i++) {
+ switch(attribs[i * 2]) {
+ case GLX_EVENT_MASK:
+ /* All we do is to record the event mask so we can send it
+ * back when queried. We never actually clobber the
+ * pbuffers, so we never need to send out the event. */
+ pGlxDraw->eventMask = attribs[i * 2 + 1];
+ break;
+ }
+ }
+
+ return Success;
+}
+
+int __glXDisp_ChangeDrawableAttributes(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXChangeDrawableAttributesReq *req =
+ (xGLXChangeDrawableAttributesReq *) pc;
+
+ return DoChangeDrawableAttributes(cl->client, req->drawable,
+ req->numAttribs, (CARD32 *) (req + 1));
+}
+
+int __glXDisp_ChangeDrawableAttributesSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXChangeDrawableAttributesSGIXReq *req =
+ (xGLXChangeDrawableAttributesSGIXReq *)pc;
+
+ return DoChangeDrawableAttributes(cl->client, req->drawable,
+ req->numAttribs, (CARD32 *) (req + 1));
+}
+
+int __glXDisp_CreateWindow(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXCreateWindowReq *req = (xGLXCreateWindowReq *) pc;
+ __GLXconfig *config;
+ __GLXscreen *pGlxScreen;
+ ClientPtr client = cl->client;
+ DrawablePtr pDraw;
+ int err;
+
+ if (!validGlxScreen(client, req->screen, &pGlxScreen, &err))
+ return err;
+ if (!validGlxFBConfig(client, pGlxScreen, req->fbconfig, &config, &err))
+ return err;
+
+ err = dixLookupDrawable(&pDraw, req->window, client, 0, DixAddAccess);
+ if (err != Success || pDraw->type != DRAWABLE_WINDOW) {
+ client->errorValue = req->window;
+ return BadWindow;
+ }
+
+ if (!validGlxFBConfigForWindow(client, config, pDraw, &err))
+ return err;
+
+ return DoCreateGLXDrawable(client, pGlxScreen, config,
+ pDraw, req->glxwindow, GLX_DRAWABLE_WINDOW);
+}
+
+int __glXDisp_DestroyWindow(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXDestroyWindowReq *req = (xGLXDestroyWindowReq *) pc;
+
+ return DoDestroyDrawable(cl, req->glxwindow, GLX_DRAWABLE_WINDOW);
+}
+
+
+/*****************************************************************************/
+
+/*
+** NOTE: There is no portable implementation for swap buffers as of
+** this time that is of value. Consequently, this code must be
+** implemented by somebody other than SGI.
+*/
+int __glXDisp_SwapBuffers(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXSwapBuffersReq *req = (xGLXSwapBuffersReq *) pc;
+ GLXContextTag tag = req->contextTag;
+ XID drawId = req->drawable;
+ __GLXcontext *glxc = NULL;
+ __GLXdrawable *pGlxDraw;
+ int error;
+
+ if (tag) {
+ glxc = __glXLookupContextByTag(cl, tag);
+ if (!glxc) {
+ return __glXError(GLXBadContextTag);
+ }
+ /*
+ ** The calling thread is swapping its current drawable. In this case,
+ ** glxSwapBuffers is in both GL and X streams, in terms of
+ ** sequentiality.
+ */
+ if (__glXForceCurrent(cl, tag, &error)) {
+ /*
+ ** Do whatever is needed to make sure that all preceding requests
+ ** in both streams are completed before the swap is executed.
+ */
+ CALL_Finish( GET_DISPATCH(), () );
+ __GLX_NOTE_FLUSHED_CMDS(glxc);
+ } else {
+ return error;
+ }
+ }
+
+ pGlxDraw = __glXGetDrawable(glxc, drawId, client, &error);
+ if (pGlxDraw == NULL)
+ return error;
+
+ if (pGlxDraw->type == DRAWABLE_WINDOW &&
+ (*pGlxDraw->swapBuffers)(pGlxDraw) == GL_FALSE)
+ return __glXError(GLXBadDrawable);
+
+ return Success;
+}
+
+
+static int
+DoQueryContext(__GLXclientState *cl, GLXContextID gcId)
+{
+ ClientPtr client = cl->client;
+ __GLXcontext *ctx;
+ xGLXQueryContextInfoEXTReply reply;
+ int nProps;
+ int *sendBuf, *pSendBuf;
+ int nReplyBytes;
+ int err;
+
+ if (!validGlxContext(cl->client, gcId, DixReadAccess, &ctx, &err))
+ return err;
+
+ nProps = 3;
+ reply.length = nProps << 1;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.n = nProps;
+
+ nReplyBytes = reply.length << 2;
+ sendBuf = (int *)xalloc((size_t)nReplyBytes);
+ if (sendBuf == NULL) {
+ return __glXError(GLXBadContext); /* XXX: Is this correct? */
+ }
+ pSendBuf = sendBuf;
+ *pSendBuf++ = GLX_SHARE_CONTEXT_EXT;
+ *pSendBuf++ = (int)(ctx->share_id);
+ *pSendBuf++ = GLX_VISUAL_ID_EXT;
+ *pSendBuf++ = (int)(ctx->config->visualID);
+ *pSendBuf++ = GLX_SCREEN_EXT;
+ *pSendBuf++ = (int)(ctx->pGlxScreen->pScreen->myNum);
+
+ if (client->swapped) {
+ __glXSwapQueryContextInfoEXTReply(client, &reply, sendBuf);
+ } else {
+ WriteToClient(client, sz_xGLXQueryContextInfoEXTReply, (char *)&reply);
+ WriteToClient(client, nReplyBytes, (char *)sendBuf);
+ }
+ xfree((char *)sendBuf);
+
+ return Success;
+}
+
+int __glXDisp_QueryContextInfoEXT(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXQueryContextInfoEXTReq *req = (xGLXQueryContextInfoEXTReq *) pc;
+
+ return DoQueryContext(cl, req->context);
+}
+
+int __glXDisp_QueryContext(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXQueryContextReq *req = (xGLXQueryContextReq *) pc;
+
+ return DoQueryContext(cl, req->context);
+}
+
+int __glXDisp_BindTexImageEXT(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc;
+ ClientPtr client = cl->client;
+ __GLXcontext *context;
+ __GLXdrawable *pGlxDraw;
+ GLXDrawable drawId;
+ int buffer;
+ int error;
+
+ pc += __GLX_VENDPRIV_HDR_SIZE;
+
+ drawId = *((CARD32 *) (pc));
+ buffer = *((INT32 *) (pc + 4));
+
+ if (buffer != GLX_FRONT_LEFT_EXT)
+ return __glXError(GLXBadPixmap);
+
+ context = __glXForceCurrent (cl, req->contextTag, &error);
+ if (!context)
+ return error;
+
+ if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_PIXMAP,
+ DixReadAccess, &pGlxDraw, &error))
+ return error;
+
+ if (!context->textureFromPixmap)
+ return __glXError(GLXUnsupportedPrivateRequest);
+
+ return context->textureFromPixmap->bindTexImage(context,
+ buffer,
+ pGlxDraw);
+}
+
+int __glXDisp_ReleaseTexImageEXT(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc;
+ ClientPtr client = cl->client;
+ __GLXdrawable *pGlxDraw;
+ __GLXcontext *context;
+ GLXDrawable drawId;
+ int buffer;
+ int error;
+
+ pc += __GLX_VENDPRIV_HDR_SIZE;
+
+ drawId = *((CARD32 *) (pc));
+ buffer = *((INT32 *) (pc + 4));
+
+ context = __glXForceCurrent (cl, req->contextTag, &error);
+ if (!context)
+ return error;
+
+ if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_PIXMAP,
+ DixReadAccess, &pGlxDraw, &error))
+ return error;
+
+ if (!context->textureFromPixmap)
+ return __glXError(GLXUnsupportedPrivateRequest);
+
+ return context->textureFromPixmap->releaseTexImage(context,
+ buffer,
+ pGlxDraw);
+}
+
+int __glXDisp_CopySubBufferMESA(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc;
+ GLXContextTag tag = req->contextTag;
+ __GLXcontext *glxc = NULL;
+ __GLXdrawable *pGlxDraw;
+ ClientPtr client = cl->client;
+ GLXDrawable drawId;
+ int error;
+ int x, y, width, height;
+
+ (void) client;
+ (void) req;
+
+ pc += __GLX_VENDPRIV_HDR_SIZE;
+
+ drawId = *((CARD32 *) (pc));
+ x = *((INT32 *) (pc + 4));
+ y = *((INT32 *) (pc + 8));
+ width = *((INT32 *) (pc + 12));
+ height = *((INT32 *) (pc + 16));
+
+ if (tag) {
+ glxc = __glXLookupContextByTag(cl, tag);
+ if (!glxc) {
+ return __glXError(GLXBadContextTag);
+ }
+ /*
+ ** The calling thread is swapping its current drawable. In this case,
+ ** glxSwapBuffers is in both GL and X streams, in terms of
+ ** sequentiality.
+ */
+ if (__glXForceCurrent(cl, tag, &error)) {
+ /*
+ ** Do whatever is needed to make sure that all preceding requests
+ ** in both streams are completed before the swap is executed.
+ */
+ CALL_Finish( GET_DISPATCH(), () );
+ __GLX_NOTE_FLUSHED_CMDS(glxc);
+ } else {
+ return error;
+ }
+ }
+
+ pGlxDraw = __glXGetDrawable(glxc, drawId, client, &error);
+ if (!pGlxDraw)
+ return error;
+
+ if (pGlxDraw == NULL ||
+ pGlxDraw->type != GLX_DRAWABLE_WINDOW ||
+ pGlxDraw->copySubBuffer == NULL)
+ return __glXError(GLXBadDrawable);
+
+ (*pGlxDraw->copySubBuffer)(pGlxDraw, x, y, width, height);
+
+ return Success;
+}
+
+/*
+** Get drawable attributes
+*/
+static int
+DoGetDrawableAttributes(__GLXclientState *cl, XID drawId)
+{
+ ClientPtr client = cl->client;
+ xGLXGetDrawableAttributesReply reply;
+ __GLXdrawable *pGlxDraw;
+ CARD32 attributes[6];
+ int numAttribs, error;
+
+ if (!validGlxDrawable(client, drawId, GLX_DRAWABLE_ANY,
+ DixGetAttrAccess, &pGlxDraw, &error))
+ return error;
+
+ numAttribs = 3;
+ reply.length = numAttribs << 1;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.numAttribs = numAttribs;
+
+ attributes[0] = GLX_TEXTURE_TARGET_EXT;
+ attributes[1] = pGlxDraw->target == GL_TEXTURE_2D ? GLX_TEXTURE_2D_EXT :
+ GLX_TEXTURE_RECTANGLE_EXT;
+ attributes[2] = GLX_Y_INVERTED_EXT;
+ attributes[3] = GL_FALSE;
+ attributes[4] = GLX_EVENT_MASK;
+ attributes[5] = pGlxDraw->eventMask;
+
+ if (client->swapped) {
+ __glXSwapGetDrawableAttributesReply(client, &reply, attributes);
+ } else {
+ WriteToClient(client, sz_xGLXGetDrawableAttributesReply,
+ (char *)&reply);
+ WriteToClient(client, reply.length * sizeof (CARD32),
+ (char *)attributes);
+ }
+
+ return Success;
+}
+
+int __glXDisp_GetDrawableAttributes(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXGetDrawableAttributesReq *req = (xGLXGetDrawableAttributesReq *)pc;
+
+ return DoGetDrawableAttributes(cl, req->drawable);
+}
+
+int __glXDisp_GetDrawableAttributesSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXGetDrawableAttributesSGIXReq *req =
+ (xGLXGetDrawableAttributesSGIXReq *)pc;
+
+ return DoGetDrawableAttributes(cl, req->drawable);
+}
+
+/************************************************************************/
+
+/*
+** Render and Renderlarge are not in the GLX API. They are used by the GLX
+** client library to send batches of GL rendering commands.
+*/
+
+/*
+** Execute all the drawing commands in a request.
+*/
+int __glXDisp_Render(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXRenderReq *req;
+ ClientPtr client= cl->client;
+ int left, cmdlen, error;
+ int commandsDone;
+ CARD16 opcode;
+ __GLXrenderHeader *hdr;
+ __GLXcontext *glxc;
+ __GLX_DECLARE_SWAP_VARIABLES;
+
+ req = (xGLXRenderReq *) pc;
+ if (client->swapped) {
+ __GLX_SWAP_SHORT(&req->length);
+ __GLX_SWAP_INT(&req->contextTag);
+ }
+
+ glxc = __glXForceCurrent(cl, req->contextTag, &error);
+ if (!glxc) {
+ return error;
+ }
+
+ commandsDone = 0;
+ pc += sz_xGLXRenderReq;
+ left = (req->length << 2) - sz_xGLXRenderReq;
+ while (left > 0) {
+ __GLXrenderSizeData entry;
+ int extra;
+ __GLXdispatchRenderProcPtr proc;
+ int err;
+
+ /*
+ ** Verify that the header length and the overall length agree.
+ ** Also, each command must be word aligned.
+ */
+ hdr = (__GLXrenderHeader *) pc;
+ if (client->swapped) {
+ __GLX_SWAP_SHORT(&hdr->length);
+ __GLX_SWAP_SHORT(&hdr->opcode);
+ }
+ cmdlen = hdr->length;
+ opcode = hdr->opcode;
+
+ /*
+ ** Check for core opcodes and grab entry data.
+ */
+ err = __glXGetProtocolSizeData(& Render_dispatch_info, opcode, & entry);
+ proc = (__GLXdispatchRenderProcPtr)
+ __glXGetProtocolDecodeFunction(& Render_dispatch_info,
+ opcode, client->swapped);
+
+ if ((err < 0) || (proc == NULL)) {
+ client->errorValue = commandsDone;
+ return __glXError(GLXBadRenderRequest);
+ }
+
+ if (entry.varsize) {
+ /* variable size command */
+ extra = (*entry.varsize)(pc + __GLX_RENDER_HDR_SIZE,
+ client->swapped);
+ if (extra < 0) {
+ extra = 0;
+ }
+ if (cmdlen != __GLX_PAD(entry.bytes + extra)) {
+ return BadLength;
+ }
+ } else {
+ /* constant size command */
+ if (cmdlen != __GLX_PAD(entry.bytes)) {
+ return BadLength;
+ }
+ }
+ if (left < cmdlen) {
+ return BadLength;
+ }
+
+ /*
+ ** Skip over the header and execute the command. We allow the
+ ** caller to trash the command memory. This is useful especially
+ ** for things that require double alignment - they can just shift
+ ** the data towards lower memory (trashing the header) by 4 bytes
+ ** and achieve the required alignment.
+ */
+ (*proc)(pc + __GLX_RENDER_HDR_SIZE);
+ pc += cmdlen;
+ left -= cmdlen;
+ commandsDone++;
+ }
+ __GLX_NOTE_UNFLUSHED_CMDS(glxc);
+ return Success;
+}
+
+
+/*
+** Execute a large rendering request (one that spans multiple X requests).
+*/
+int __glXDisp_RenderLarge(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXRenderLargeReq *req;
+ ClientPtr client= cl->client;
+ size_t dataBytes;
+ __GLXrenderLargeHeader *hdr;
+ __GLXcontext *glxc;
+ int error;
+ CARD16 opcode;
+ __GLX_DECLARE_SWAP_VARIABLES;
+
+ req = (xGLXRenderLargeReq *) pc;
+ if (client->swapped) {
+ __GLX_SWAP_SHORT(&req->length);
+ __GLX_SWAP_INT(&req->contextTag);
+ __GLX_SWAP_INT(&req->dataBytes);
+ __GLX_SWAP_SHORT(&req->requestNumber);
+ __GLX_SWAP_SHORT(&req->requestTotal);
+ }
+
+ glxc = __glXForceCurrent(cl, req->contextTag, &error);
+ if (!glxc) {
+ /* Reset in case this isn't 1st request. */
+ __glXResetLargeCommandStatus(cl);
+ return error;
+ }
+ dataBytes = req->dataBytes;
+
+ /*
+ ** Check the request length.
+ */
+ if ((req->length << 2) != __GLX_PAD(dataBytes) + sz_xGLXRenderLargeReq) {
+ client->errorValue = req->length;
+ /* Reset in case this isn't 1st request. */
+ __glXResetLargeCommandStatus(cl);
+ return BadLength;
+ }
+ pc += sz_xGLXRenderLargeReq;
+
+ if (cl->largeCmdRequestsSoFar == 0) {
+ __GLXrenderSizeData entry;
+ int extra;
+ size_t cmdlen;
+ int err;
+
+ /*
+ ** This is the first request of a multi request command.
+ ** Make enough space in the buffer, then copy the entire request.
+ */
+ if (req->requestNumber != 1) {
+ client->errorValue = req->requestNumber;
+ return __glXError(GLXBadLargeRequest);
+ }
+
+ hdr = (__GLXrenderLargeHeader *) pc;
+ if (client->swapped) {
+ __GLX_SWAP_INT(&hdr->length);
+ __GLX_SWAP_INT(&hdr->opcode);
+ }
+ cmdlen = hdr->length;
+ opcode = hdr->opcode;
+
+ /*
+ ** Check for core opcodes and grab entry data.
+ */
+ err = __glXGetProtocolSizeData(& Render_dispatch_info, opcode, & entry);
+ if (err < 0) {
+ client->errorValue = opcode;
+ return __glXError(GLXBadLargeRequest);
+ }
+
+ if (entry.varsize) {
+ /*
+ ** If it's a variable-size command (a command whose length must
+ ** be computed from its parameters), all the parameters needed
+ ** will be in the 1st request, so it's okay to do this.
+ */
+ extra = (*entry.varsize)(pc + __GLX_RENDER_LARGE_HDR_SIZE,
+ client->swapped);
+ if (extra < 0) {
+ extra = 0;
+ }
+ /* large command's header is 4 bytes longer, so add 4 */
+ if (cmdlen != __GLX_PAD(entry.bytes + 4 + extra)) {
+ return BadLength;
+ }
+ } else {
+ /* constant size command */
+ if (cmdlen != __GLX_PAD(entry.bytes + 4)) {
+ return BadLength;
+ }
+ }
+ /*
+ ** Make enough space in the buffer, then copy the entire request.
+ */
+ if (cl->largeCmdBufSize < cmdlen) {
+ if (!cl->largeCmdBuf) {
+ cl->largeCmdBuf = (GLbyte *) xalloc(cmdlen);
+ } else {
+ cl->largeCmdBuf = (GLbyte *) xrealloc(cl->largeCmdBuf, cmdlen);
+ }
+ if (!cl->largeCmdBuf) {
+ return BadAlloc;
+ }
+ cl->largeCmdBufSize = cmdlen;
+ }
+ memcpy(cl->largeCmdBuf, pc, dataBytes);
+
+ cl->largeCmdBytesSoFar = dataBytes;
+ cl->largeCmdBytesTotal = cmdlen;
+ cl->largeCmdRequestsSoFar = 1;
+ cl->largeCmdRequestsTotal = req->requestTotal;
+ return Success;
+
+ } else {
+ /*
+ ** We are receiving subsequent (i.e. not the first) requests of a
+ ** multi request command.
+ */
+
+ /*
+ ** Check the request number and the total request count.
+ */
+ if (req->requestNumber != cl->largeCmdRequestsSoFar + 1) {
+ client->errorValue = req->requestNumber;
+ __glXResetLargeCommandStatus(cl);
+ return __glXError(GLXBadLargeRequest);
+ }
+ if (req->requestTotal != cl->largeCmdRequestsTotal) {
+ client->errorValue = req->requestTotal;
+ __glXResetLargeCommandStatus(cl);
+ return __glXError(GLXBadLargeRequest);
+ }
+
+ /*
+ ** Check that we didn't get too much data.
+ */
+ if ((cl->largeCmdBytesSoFar + dataBytes) > cl->largeCmdBytesTotal) {
+ client->errorValue = dataBytes;
+ __glXResetLargeCommandStatus(cl);
+ return __glXError(GLXBadLargeRequest);
+ }
+ memcpy(cl->largeCmdBuf + cl->largeCmdBytesSoFar, pc, dataBytes);
+ cl->largeCmdBytesSoFar += dataBytes;
+ cl->largeCmdRequestsSoFar++;
+
+ if (req->requestNumber == cl->largeCmdRequestsTotal) {
+ __GLXdispatchRenderProcPtr proc;
+
+ /*
+ ** This is the last request; it must have enough bytes to complete
+ ** the command.
+ */
+ /* NOTE: the two pad macros have been added below; they are needed
+ ** because the client library pads the total byte count, but not
+ ** the per-request byte counts. The Protocol Encoding says the
+ ** total byte count should not be padded, so a proposal will be
+ ** made to the ARB to relax the padding constraint on the total
+ ** byte count, thus preserving backward compatibility. Meanwhile,
+ ** the padding done below fixes a bug that did not allow
+ ** large commands of odd sizes to be accepted by the server.
+ */
+ if (__GLX_PAD(cl->largeCmdBytesSoFar) !=
+ __GLX_PAD(cl->largeCmdBytesTotal)) {
+ client->errorValue = dataBytes;
+ __glXResetLargeCommandStatus(cl);
+ return __glXError(GLXBadLargeRequest);
+ }
+ hdr = (__GLXrenderLargeHeader *) cl->largeCmdBuf;
+ /*
+ ** The opcode and length field in the header had already been
+ ** swapped when the first request was received.
+ **
+ ** Use the opcode to index into the procedure table.
+ */
+ opcode = hdr->opcode;
+
+ proc = (__GLXdispatchRenderProcPtr)
+ __glXGetProtocolDecodeFunction(& Render_dispatch_info, opcode,
+ client->swapped);
+ if (proc == NULL) {
+ client->errorValue = opcode;
+ return __glXError(GLXBadLargeRequest);
+ }
+
+ /*
+ ** Skip over the header and execute the command.
+ */
+ (*proc)(cl->largeCmdBuf + __GLX_RENDER_LARGE_HDR_SIZE);
+ __GLX_NOTE_UNFLUSHED_CMDS(glxc);
+
+ /*
+ ** Reset for the next RenderLarge series.
+ */
+ __glXResetLargeCommandStatus(cl);
+ } else {
+ /*
+ ** This is neither the first nor the last request.
+ */
+ }
+ return Success;
+ }
+}
+
+extern RESTYPE __glXSwapBarrierRes;
+
+int __glXDisp_BindSwapBarrierSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXBindSwapBarrierSGIXReq *req = (xGLXBindSwapBarrierSGIXReq *) pc;
+ XID drawable = req->drawable;
+ int barrier = req->barrier;
+ DrawablePtr pDraw;
+ int screen, rc;
+ __GLXscreen *pGlxScreen;
+
+ rc = dixLookupDrawable(&pDraw, drawable, client, 0, DixGetAttrAccess);
+ pGlxScreen = glxGetScreen(pDraw->pScreen);
+ if (rc == Success && (pDraw->type == DRAWABLE_WINDOW)) {
+ screen = pDraw->pScreen->myNum;
+ if (pGlxScreen->swapBarrierFuncs) {
+ int ret = pGlxScreen->swapBarrierFuncs->bindSwapBarrierFunc(screen, drawable, barrier);
+ if (ret == Success) {
+ if (barrier)
+ /* add source for cleanup when drawable is gone */
+ AddResource(drawable, __glXSwapBarrierRes, (pointer)screen);
+ else
+ /* delete source */
+ FreeResourceByType(drawable, __glXSwapBarrierRes, FALSE);
+ }
+ return ret;
+ }
+ }
+ client->errorValue = drawable;
+ return __glXError(GLXBadDrawable);
+}
+
+
+int __glXDisp_QueryMaxSwapBarriersSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryMaxSwapBarriersSGIXReq *req =
+ (xGLXQueryMaxSwapBarriersSGIXReq *) pc;
+ xGLXQueryMaxSwapBarriersSGIXReply reply;
+ int screen = req->screen;
+ __GLXscreen *pGlxScreen;
+
+ pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+ if (pGlxScreen->swapBarrierFuncs)
+ reply.max = pGlxScreen->swapBarrierFuncs->queryMaxSwapBarriersFunc(screen);
+ else
+ reply.max = 0;
+
+
+ reply.length = 0;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+
+ if (client->swapped) {
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ }
+
+ WriteToClient(client, sz_xGLXQueryMaxSwapBarriersSGIXReply,
+ (char *) &reply);
+ return Success;
+}
+
+#define GLX_BAD_HYPERPIPE_SGIX 92
+
+int __glXDisp_QueryHyperpipeNetworkSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryHyperpipeNetworkSGIXReq * req = (xGLXQueryHyperpipeNetworkSGIXReq *) pc;
+ xGLXQueryHyperpipeNetworkSGIXReply reply;
+ int screen = req->screen;
+ void *rdata = NULL;
+
+ int length=0;
+ int npipes=0;
+
+ int n= 0;
+ __GLXscreen *pGlxScreen;
+
+ pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+ if (pGlxScreen->hyperpipeFuncs) {
+ rdata =
+ (pGlxScreen->hyperpipeFuncs->queryHyperpipeNetworkFunc(screen, &npipes, &n));
+ }
+ length = __GLX_PAD(n) >> 2;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = length;
+ reply.n = n;
+ reply.npipes = npipes;
+
+ if (client->swapped) {
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ __GLX_SWAP_INT(&reply.length);
+ __GLX_SWAP_INT(&reply.n);
+ __GLX_SWAP_INT(&reply.npipes);
+ }
+ WriteToClient(client, sz_xGLXQueryHyperpipeNetworkSGIXReply,
+ (char *) &reply);
+
+ WriteToClient(client, length << 2, (char *)rdata);
+
+ return Success;
+}
+
+int __glXDisp_DestroyHyperpipeConfigSGIX (__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXDestroyHyperpipeConfigSGIXReq * req =
+ (xGLXDestroyHyperpipeConfigSGIXReq *) pc;
+ xGLXDestroyHyperpipeConfigSGIXReply reply;
+ int screen = req->screen;
+ int success = GLX_BAD_HYPERPIPE_SGIX;
+ int hpId ;
+ __GLXscreen *pGlxScreen;
+
+ hpId = req->hpId;
+
+ pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+ if (pGlxScreen->hyperpipeFuncs) {
+ success = pGlxScreen->hyperpipeFuncs->destroyHyperpipeConfigFunc(screen, hpId);
+ }
+
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = __GLX_PAD(0) >> 2;
+ reply.n = 0;
+ reply.success = success;
+
+
+ if (client->swapped) {
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ }
+ WriteToClient(client,
+ sz_xGLXDestroyHyperpipeConfigSGIXReply,
+ (char *) &reply);
+ return Success;
+}
+
+int __glXDisp_QueryHyperpipeConfigSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryHyperpipeConfigSGIXReq * req =
+ (xGLXQueryHyperpipeConfigSGIXReq *) pc;
+ xGLXQueryHyperpipeConfigSGIXReply reply;
+ int screen = req->screen;
+ void *rdata = NULL;
+ int length;
+ int npipes=0;
+ int n= 0;
+ int hpId;
+ __GLXscreen *pGlxScreen;
+
+ hpId = req->hpId;
+
+ pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+ if (pGlxScreen->hyperpipeFuncs) {
+ rdata = pGlxScreen->hyperpipeFuncs->queryHyperpipeConfigFunc(screen, hpId,&npipes, &n);
+ }
+
+ length = __GLX_PAD(n) >> 2;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = length;
+ reply.n = n;
+ reply.npipes = npipes;
+
+
+ if (client->swapped) {
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ __GLX_SWAP_INT(&reply.length);
+ __GLX_SWAP_INT(&reply.n);
+ __GLX_SWAP_INT(&reply.npipes);
+ }
+
+ WriteToClient(client, sz_xGLXQueryHyperpipeConfigSGIXReply,
+ (char *) &reply);
+
+ WriteToClient(client, length << 2, (char *)rdata);
+
+ return Success;
+}
+
+int __glXDisp_HyperpipeConfigSGIX(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXHyperpipeConfigSGIXReq * req =
+ (xGLXHyperpipeConfigSGIXReq *) pc;
+ xGLXHyperpipeConfigSGIXReply reply;
+ int screen = req->screen;
+ void *rdata;
+
+ int npipes=0, networkId;
+ int hpId=-1;
+ __GLXscreen *pGlxScreen;
+
+ pGlxScreen = glxGetScreen(screenInfo.screens[screen]);
+ networkId = (int)req->networkId;
+ npipes = (int)req->npipes;
+ rdata = (void *)(req +1);
+
+ if (pGlxScreen->hyperpipeFuncs) {
+ pGlxScreen->hyperpipeFuncs->hyperpipeConfigFunc(screen,networkId,
+ &hpId, &npipes,
+ (void *) rdata);
+ }
+
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = __GLX_PAD(0) >> 2;
+ reply.n = 0;
+ reply.npipes = npipes;
+ reply.hpId = hpId;
+
+ if (client->swapped) {
+ __GLX_DECLARE_SWAP_VARIABLES;
+ __GLX_SWAP_SHORT(&reply.sequenceNumber);
+ __GLX_SWAP_INT(&reply.npipes);
+ __GLX_SWAP_INT(&reply.hpId);
+ }
+
+ WriteToClient(client, sz_xGLXHyperpipeConfigSGIXReply,
+ (char *) &reply);
+
+ return Success;
+}
+
+
+/************************************************************************/
+
+/*
+** No support is provided for the vendor-private requests other than
+** allocating the entry points in the dispatch table.
+*/
+
+int __glXDisp_VendorPrivate(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc;
+ GLint vendorcode = req->vendorCode;
+ __GLXdispatchVendorPrivProcPtr proc;
+
+
+ proc = (__GLXdispatchVendorPrivProcPtr)
+ __glXGetProtocolDecodeFunction(& VendorPriv_dispatch_info,
+ vendorcode, 0);
+ if (proc != NULL) {
+ (*proc)(cl, (GLbyte*)req);
+ return Success;
+ }
+
+ cl->client->errorValue = req->vendorCode;
+ return __glXError(GLXUnsupportedPrivateRequest);
+}
+
+int __glXDisp_VendorPrivateWithReply(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXVendorPrivateReq *req = (xGLXVendorPrivateReq *) pc;
+ GLint vendorcode = req->vendorCode;
+ __GLXdispatchVendorPrivProcPtr proc;
+
+
+ proc = (__GLXdispatchVendorPrivProcPtr)
+ __glXGetProtocolDecodeFunction(& VendorPriv_dispatch_info,
+ vendorcode, 0);
+ if (proc != NULL) {
+ return (*proc)(cl, (GLbyte*)req);
+ }
+
+ cl->client->errorValue = vendorcode;
+ return __glXError(GLXUnsupportedPrivateRequest);
+}
+
+int __glXDisp_QueryExtensionsString(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryExtensionsStringReq *req = (xGLXQueryExtensionsStringReq *) pc;
+ xGLXQueryExtensionsStringReply reply;
+ __GLXscreen *pGlxScreen;
+ size_t n, length;
+ char *buf;
+ int err;
+
+ if (!validGlxScreen(client, req->screen, &pGlxScreen, &err))
+ return err;
+
+ n = strlen(pGlxScreen->GLXextensions) + 1;
+ length = __GLX_PAD(n) >> 2;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = length;
+ reply.n = n;
+
+ /* Allocate buffer to make sure it's a multiple of 4 bytes big.*/
+ buf = (char *) xalloc(length << 2);
+ if (buf == NULL)
+ return BadAlloc;
+ memcpy(buf, pGlxScreen->GLXextensions, n);
+
+ if (client->swapped) {
+ glxSwapQueryExtensionsStringReply(client, &reply, buf);
+ } else {
+ WriteToClient(client, sz_xGLXQueryExtensionsStringReply,(char *)&reply);
+ WriteToClient(client, (int)(length << 2), (char *)buf);
+ }
+
+ xfree(buf);
+ return Success;
+}
+
+int __glXDisp_QueryServerString(__GLXclientState *cl, GLbyte *pc)
+{
+ ClientPtr client = cl->client;
+ xGLXQueryServerStringReq *req = (xGLXQueryServerStringReq *) pc;
+ xGLXQueryServerStringReply reply;
+ size_t n, length;
+ const char *ptr;
+ char *buf;
+ __GLXscreen *pGlxScreen;
+ int err;
+
+ if (!validGlxScreen(client, req->screen, &pGlxScreen, &err))
+ return err;
+
+ switch(req->name) {
+ case GLX_VENDOR:
+ ptr = pGlxScreen->GLXvendor;
+ break;
+ case GLX_VERSION:
+ ptr = pGlxScreen->GLXversion;
+ break;
+ case GLX_EXTENSIONS:
+ ptr = pGlxScreen->GLXextensions;
+ break;
+ default:
+ return BadValue;
+ }
+
+ n = strlen(ptr) + 1;
+ length = __GLX_PAD(n) >> 2;
+ reply.type = X_Reply;
+ reply.sequenceNumber = client->sequence;
+ reply.length = length;
+ reply.n = n;
+
+ buf = (char *) xalloc(length << 2);
+ if (buf == NULL) {
+ return BadAlloc;
+ }
+ memcpy(buf, ptr, n);
+
+ if (client->swapped) {
+ glxSwapQueryServerStringReply(client, &reply, buf);
+ } else {
+ WriteToClient(client, sz_xGLXQueryServerStringReply, (char *)&reply);
+ WriteToClient(client, (int)(length << 2), buf);
+ }
+
+ xfree(buf);
+ return Success;
+}
+
+int __glXDisp_ClientInfo(__GLXclientState *cl, GLbyte *pc)
+{
+ xGLXClientInfoReq *req = (xGLXClientInfoReq *) pc;
+ const char *buf;
+
+ cl->GLClientmajorVersion = req->major;
+ cl->GLClientminorVersion = req->minor;
+ if (cl->GLClientextensions)
+ xfree(cl->GLClientextensions);
+ buf = (const char *)(req+1);
+ cl->GLClientextensions = xstrdup(buf);
+
+ return Success;
+}
diff --git a/xorg-server/glx/glxcmdsswap.c b/xorg-server/glx/glxcmdsswap.c index f1c0ce69f..2f74ce5ec 100644 --- a/xorg-server/glx/glxcmdsswap.c +++ b/xorg-server/glx/glxcmdsswap.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <string.h> diff --git a/xorg-server/glx/glxdri.c b/xorg-server/glx/glxdri.c index 6122653b0..e4f061c54 100644 --- a/xorg-server/glx/glxdri.c +++ b/xorg-server/glx/glxdri.c @@ -1,1196 +1,1199 @@ -/* - * Copyright © 2006 Red Hat, 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 Red Hat, - * Inc not be used in advertising or publicity pertaining to - * distribution of the software without specific, written prior - * permission. Red Hat, Inc makes no representations about the - * suitability of this software for any purpose. It is provided "as - * is" without express or implied warranty. - * - * RED HAT, INC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN - * NO EVENT SHALL RED HAT, INC 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_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <stdint.h> -#include <stdio.h> -#include <string.h> -#include <errno.h> -#include <sys/time.h> -#include <dlfcn.h> - -#include <drm.h> -#include <GL/gl.h> -#include <GL/internal/dri_interface.h> - -#include <windowstr.h> -#include <os.h> -#include <damage.h> - -#define _XF86DRI_SERVER_ -#include <drm_sarea.h> -#include <xf86drm.h> -#include <X11/dri/xf86driproto.h> -#include <xf86str.h> -#include <xf86.h> -#include <dri.h> - -#include "servermd.h" - -#define DRI_NEW_INTERFACE_ONLY -#include "glxserver.h" -#include "glxutil.h" -#include "glxdricommon.h" - -#include "g_disptab.h" -#include "glapitable.h" -#include "glapi.h" -#include "glthread.h" -#include "dispatch.h" -#include "extension_string.h" - -typedef struct __GLXDRIscreen __GLXDRIscreen; -typedef struct __GLXDRIcontext __GLXDRIcontext; -typedef struct __GLXDRIdrawable __GLXDRIdrawable; - -struct __GLXDRIscreen { - __GLXscreen base; - __DRIscreen *driScreen; - void *driver; - - xf86EnterVTProc *enterVT; - xf86LeaveVTProc *leaveVT; - - const __DRIcoreExtension *core; - const __DRIlegacyExtension *legacy; - const __DRIcopySubBufferExtension *copySubBuffer; - const __DRIswapControlExtension *swapControl; - -#ifdef __DRI_TEX_OFFSET - const __DRItexOffsetExtension *texOffset; - DRITexOffsetStartProcPtr texOffsetStart; - DRITexOffsetFinishProcPtr texOffsetFinish; - __GLXDRIdrawable *texOffsetOverride[16]; - GLuint lastTexOffsetOverride; -#endif - - unsigned char glx_enable_bits[__GLX_EXT_BYTES]; -}; - -struct __GLXDRIcontext { - __GLXcontext base; - __DRIcontext *driContext; - XID hwContextID; -}; - -struct __GLXDRIdrawable { - __GLXdrawable base; - __DRIdrawable *driDrawable; - - /* Pulled in from old __GLXpixmap */ -#ifdef __DRI_TEX_OFFSET - GLint texname; - __GLXDRIcontext *ctx; - unsigned long long offset; - DamagePtr pDamage; -#endif -}; - -static void -__glXDRIleaveServer(GLboolean rendering) -{ - int i; - - for (i = 0; rendering && i < screenInfo.numScreens; i++) { - __GLXDRIscreen * const screen = - (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]); - GLuint lastOverride = screen->lastTexOffsetOverride; - - if (lastOverride) { - __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride; - int j; - - for (j = 0; j < lastOverride; j++) { - __GLXDRIdrawable *pGlxPix = texOffsetOverride[j]; - - if (pGlxPix && pGlxPix->texname) { - pGlxPix->offset = - screen->texOffsetStart((PixmapPtr)pGlxPix->base.pDraw); - } - } - } - } - - DRIBlockHandler(NULL, NULL, NULL); - - for (i = 0; rendering && i < screenInfo.numScreens; i++) { - __GLXDRIscreen * const screen = - (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]); - GLuint lastOverride = screen->lastTexOffsetOverride; - - if (lastOverride) { - __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride; - int j; - - for (j = 0; j < lastOverride; j++) { - __GLXDRIdrawable *pGlxPix = texOffsetOverride[j]; - - if (pGlxPix && pGlxPix->texname) { - screen->texOffset->setTexOffset(pGlxPix->ctx->driContext, - pGlxPix->texname, - pGlxPix->offset, - pGlxPix->base.pDraw->depth, - ((PixmapPtr)pGlxPix->base.pDraw)->devKind); - } - } - } - } -} - -static void -__glXDRIenterServer(GLboolean rendering) -{ - int i; - - for (i = 0; rendering && i < screenInfo.numScreens; i++) { - __GLXDRIscreen * const screen = (__GLXDRIscreen *) - glxGetScreen(screenInfo.screens[i]); - - if (screen->lastTexOffsetOverride) { - CALL_Flush(GET_DISPATCH(), ()); - break; - } - } - - DRIWakeupHandler(NULL, 0, NULL); -} - - -static void -__glXDRIdoReleaseTexImage(__GLXDRIscreen *screen, __GLXDRIdrawable *drawable) -{ - GLuint lastOverride = screen->lastTexOffsetOverride; - - if (lastOverride) { - __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride; - int i; - - for (i = 0; i < lastOverride; i++) { - if (texOffsetOverride[i] == drawable) { - if (screen->texOffsetFinish) - screen->texOffsetFinish((PixmapPtr)drawable->base.pDraw); - - texOffsetOverride[i] = NULL; - - if (i + 1 == lastOverride) { - lastOverride = 0; - - while (i--) { - if (texOffsetOverride[i]) { - lastOverride = i + 1; - break; - } - } - - screen->lastTexOffsetOverride = lastOverride; - - break; - } - } - } - } -} - - -static void -__glXDRIdrawableDestroy(__GLXdrawable *drawable) -{ - __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable; - __GLXDRIscreen *screen; - int i; - - for (i = 0; i < screenInfo.numScreens; i++) { - screen = (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]); - __glXDRIdoReleaseTexImage(screen, private); - } - - /* If the X window was destroyed, the dri DestroyWindow hook will - * aready have taken care of this, so only call if pDraw isn't NULL. */ - if (drawable->pDraw != NULL) { - screen = (__GLXDRIscreen *) glxGetScreen(drawable->pDraw->pScreen); - (*screen->core->destroyDrawable)(private->driDrawable); - - __glXenterServer(GL_FALSE); - DRIDestroyDrawable(drawable->pDraw->pScreen, - serverClient, drawable->pDraw); - __glXleaveServer(GL_FALSE); - } - - __glXDrawableRelease(drawable); - - xfree(private); -} - -static GLboolean -__glXDRIdrawableSwapBuffers(__GLXdrawable *basePrivate) -{ - __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate; - __GLXDRIscreen *screen = - (__GLXDRIscreen *) glxGetScreen(basePrivate->pDraw->pScreen); - - (*screen->core->swapBuffers)(private->driDrawable); - - return TRUE; -} - - -static int -__glXDRIdrawableSwapInterval(__GLXdrawable *baseDrawable, int interval) -{ - __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseDrawable; - __GLXDRIscreen *screen = - (__GLXDRIscreen *) glxGetScreen(baseDrawable->pDraw->pScreen); - - if (screen->swapControl) - screen->swapControl->setSwapInterval(draw->driDrawable, interval); - - return 0; -} - - -static void -__glXDRIdrawableCopySubBuffer(__GLXdrawable *basePrivate, - int x, int y, int w, int h) -{ - __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate; - __GLXDRIscreen *screen = (__GLXDRIscreen *) - glxGetScreen(basePrivate->pDraw->pScreen); - - if (screen->copySubBuffer) - screen->copySubBuffer->copySubBuffer(private->driDrawable, x, y, w, h); -} - -static void -__glXDRIcontextDestroy(__GLXcontext *baseContext) -{ - __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext; - __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen; - Bool retval; - - screen->core->destroyContext(context->driContext); - - __glXenterServer(GL_FALSE); - retval = DRIDestroyContext(baseContext->pGlxScreen->pScreen, - context->hwContextID); - __glXleaveServer(GL_FALSE); - - __glXContextDestroy(&context->base); - xfree(context); -} - -static int -__glXDRIcontextMakeCurrent(__GLXcontext *baseContext) -{ - __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext; - __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen; - __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv; - __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv; - - return (*screen->core->bindContext)(context->driContext, - draw->driDrawable, - read->driDrawable); -} - -static int -__glXDRIcontextLoseCurrent(__GLXcontext *baseContext) -{ - __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext; - __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen; - - return (*screen->core->unbindContext)(context->driContext); -} - -static int -__glXDRIcontextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc, - unsigned long mask) -{ - __GLXDRIcontext *dst = (__GLXDRIcontext *) baseDst; - __GLXDRIcontext *src = (__GLXDRIcontext *) baseSrc; - __GLXDRIscreen *screen = (__GLXDRIscreen *) dst->base.pGlxScreen; - - return (*screen->core->copyContext)(dst->driContext, - src->driContext, mask); -} - -static int -__glXDRIcontextForceCurrent(__GLXcontext *baseContext) -{ - __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext; - __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv; - __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv; - __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen; - - return (*screen->core->bindContext)(context->driContext, - draw->driDrawable, - read->driDrawable); -} - -static void -glxFillAlphaChannel (CARD32 *pixels, CARD32 rowstride, int width, int height) -{ - int i; - CARD32 *p, *end; - - rowstride /= 4; - - for (i = 0; i < height; i++) - { - p = pixels; - end = p + width; - while (p < end) - *p++ |= 0xFF000000; - pixels += rowstride; - } -} - -static Bool -testTexOffset(__GLXDRIscreen * const screen, PixmapPtr pPixmap) -{ - Bool ret; - - if (!screen->texOffsetStart || !screen->texOffset) - return FALSE; - - __glXenterServer(GL_FALSE); - ret = screen->texOffsetStart(pPixmap) != ~0ULL; - __glXleaveServer(GL_FALSE); - - return ret; -} - -/* - * (sticking this here for lack of a better place) - * Known issues with the GLX_EXT_texture_from_pixmap implementation: - * - In general we ignore the fbconfig, lots of examples follow - * - No fbconfig handling for multiple mipmap levels - * - No fbconfig handling for 1D textures - * - No fbconfig handling for TEXTURE_TARGET - * - No fbconfig exposure of Y inversion state - * - No GenerateMipmapEXT support (due to no FBO support) - * - No support for anything but 16bpp and 32bpp-sparse pixmaps - */ - -static int -__glXDRIbindTexImage(__GLXcontext *baseContext, - int buffer, - __GLXdrawable *glxPixmap) -{ - RegionPtr pRegion = NULL; - PixmapPtr pixmap; - int bpp, override = 0, texname; - GLenum format, type; - ScreenPtr pScreen = glxPixmap->pDraw->pScreen; - __GLXDRIdrawable *driDraw = (__GLXDRIdrawable *) glxPixmap; - __GLXDRIscreen * const screen = (__GLXDRIscreen *) glxGetScreen(pScreen); - - CALL_GetIntegerv(GET_DISPATCH(), (glxPixmap->target == GL_TEXTURE_2D ? - GL_TEXTURE_BINDING_2D : - GL_TEXTURE_BINDING_RECTANGLE_NV, - &texname)); - - if (!texname) - return __glXError(GLXBadContextState); - - pixmap = (PixmapPtr) glxPixmap->pDraw; - - if (testTexOffset(screen, pixmap)) { - __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride; - int i, firstEmpty = 16; - - for (i = 0; i < 16; i++) { - if (texOffsetOverride[i] == driDraw) - goto alreadyin; - - if (firstEmpty == 16 && !texOffsetOverride[i]) - firstEmpty = i; - } - - if (firstEmpty == 16) { - ErrorF("%s: Failed to register texture offset override\n", __func__); - goto nooverride; - } - - if (firstEmpty >= screen->lastTexOffsetOverride) - screen->lastTexOffsetOverride = firstEmpty + 1; - - texOffsetOverride[firstEmpty] = driDraw; - -alreadyin: - override = 1; - - driDraw->ctx = (__GLXDRIcontext*)baseContext; - - if (texname == driDraw->texname) - return Success; - - driDraw->texname = texname; - - screen->texOffset->setTexOffset(driDraw->ctx->driContext, texname, 0, - pixmap->drawable.depth, - pixmap->devKind); - } -nooverride: - - if (!driDraw->pDamage) { - if (!override) { - driDraw->pDamage = DamageCreate(NULL, NULL, DamageReportNone, - TRUE, pScreen, NULL); - if (!driDraw->pDamage) - return BadAlloc; - - DamageRegister ((DrawablePtr) pixmap, driDraw->pDamage); - } - - pRegion = NULL; - } else { - pRegion = DamageRegion(driDraw->pDamage); - if (REGION_NIL(pRegion)) - return Success; - } - - /* XXX 24bpp packed, 8, etc */ - if (pixmap->drawable.depth >= 24) { - bpp = 4; - format = GL_BGRA; - type = -#if X_BYTE_ORDER == X_BIG_ENDIAN - !override ? GL_UNSIGNED_INT_8_8_8_8_REV : -#endif - GL_UNSIGNED_BYTE; - } else { - bpp = 2; - format = GL_RGB; - type = GL_UNSIGNED_SHORT_5_6_5; - } - - if (pRegion == NULL) - { - void *data = NULL; - - if (!override) { - unsigned pitch = PixmapBytePad(pixmap->drawable.width, - pixmap->drawable.depth); - - data = xalloc(pitch * pixmap->drawable.height); - - __glXenterServer(GL_FALSE); - pScreen->GetImage(&pixmap->drawable, 0 /*pixmap->drawable.x*/, - 0 /*pixmap->drawable.y*/, pixmap->drawable.width, - pixmap->drawable.height, ZPixmap, ~0, data); - __glXleaveServer(GL_FALSE); - - if (pixmap->drawable.depth == 24) - glxFillAlphaChannel(data, - pitch, - pixmap->drawable.width, - pixmap->drawable.height); - - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_ROW_LENGTH, - pitch / bpp) ); - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_PIXELS, 0) ); - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_ROWS, 0) ); - } - - CALL_TexImage2D( GET_DISPATCH(), - (glxPixmap->target, - 0, - bpp == 4 ? 4 : 3, - pixmap->drawable.width, - pixmap->drawable.height, - 0, - format, - type, - data) ); - - xfree(data); - } else if (!override) { - int i, numRects; - BoxPtr p; - - numRects = REGION_NUM_RECTS (pRegion); - p = REGION_RECTS (pRegion); - - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_PIXELS, 0) ); - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_ROWS, 0) ); - - for (i = 0; i < numRects; i++) - { - unsigned pitch = PixmapBytePad(p[i].x2 - p[i].x1, - pixmap->drawable.depth); - void *data = xalloc(pitch * (p[i].y2 - p[i].y1)); - - __glXenterServer(GL_FALSE); - pScreen->GetImage(&pixmap->drawable, /*pixmap->drawable.x +*/ p[i].x1, - /*pixmap->drawable.y*/ + p[i].y1, p[i].x2 - p[i].x1, - p[i].y2 - p[i].y1, ZPixmap, ~0, data); - __glXleaveServer(GL_FALSE); - - if (pixmap->drawable.depth == 24) - glxFillAlphaChannel(data, - pitch, - p[i].x2 - p[i].x1, - p[i].y2 - p[i].y1); - - CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_ROW_LENGTH, - pitch / bpp) ); - - CALL_TexSubImage2D( GET_DISPATCH(), - (glxPixmap->target, - 0, - p[i].x1, p[i].y1, - p[i].x2 - p[i].x1, p[i].y2 - p[i].y1, - format, - type, - data) ); - - xfree(data); - } - } - - if (!override) - DamageEmpty(driDraw->pDamage); - - return Success; -} - -static int -__glXDRIreleaseTexImage(__GLXcontext *baseContext, - int buffer, - __GLXdrawable *pixmap) -{ - __GLXDRIscreen *screen = - (__GLXDRIscreen *) glxGetScreen(pixmap->pDraw->pScreen); - __GLXDRIdrawable *drawable = (__GLXDRIdrawable *) pixmap; - - __glXDRIdoReleaseTexImage(screen, drawable); - - return Success; -} - -static __GLXtextureFromPixmap __glXDRItextureFromPixmap = { - __glXDRIbindTexImage, - __glXDRIreleaseTexImage -}; - -static void -__glXDRIscreenDestroy(__GLXscreen *baseScreen) -{ - __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen; - - screen->core->destroyScreen(screen->driScreen); - - dlclose(screen->driver); - - __glXScreenDestroy(baseScreen); - - xfree(screen); -} - -static __GLXcontext * -__glXDRIscreenCreateContext(__GLXscreen *baseScreen, - __GLXconfig *glxConfig, - __GLXcontext *baseShareContext) -{ - __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen; - __GLXDRIcontext *context, *shareContext; - __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig; - VisualPtr visual; - int i; - GLboolean retval; - __DRIcontext *driShare; - drm_context_t hwContext; - ScreenPtr pScreen = baseScreen->pScreen; - - shareContext = (__GLXDRIcontext *) baseShareContext; - if (shareContext) - driShare = shareContext->driContext; - else - driShare = NULL; - - if (baseShareContext && baseShareContext->isDirect) - return NULL; - - context = xcalloc(1, sizeof *context); - if (context == NULL) - return NULL; - - context->base.destroy = __glXDRIcontextDestroy; - context->base.makeCurrent = __glXDRIcontextMakeCurrent; - context->base.loseCurrent = __glXDRIcontextLoseCurrent; - context->base.copy = __glXDRIcontextCopy; - context->base.forceCurrent = __glXDRIcontextForceCurrent; - - context->base.textureFromPixmap = &__glXDRItextureFromPixmap; - /* Find the requested X visual */ - visual = pScreen->visuals; - for (i = 0; i < pScreen->numVisuals; i++, visual++) - if (visual->vid == glxConfig->visualID) - break; - if (i == pScreen->numVisuals) - return NULL; - - context->hwContextID = FakeClientID(0); - - __glXenterServer(GL_FALSE); - retval = DRICreateContext(baseScreen->pScreen, visual, - context->hwContextID, &hwContext); - __glXleaveServer(GL_FALSE); - - if (!retval) - return NULL; - - context->driContext = - screen->legacy->createNewContext(screen->driScreen, - config->driConfig, - 0, /* render type */ - driShare, - hwContext, - context); - - if (context->driContext == NULL) { - __glXenterServer(GL_FALSE); - retval = DRIDestroyContext(baseScreen->pScreen, context->hwContextID); - __glXleaveServer(GL_FALSE); - xfree(context); - return NULL; - } - - return &context->base; -} - -static __GLXdrawable * -__glXDRIscreenCreateDrawable(__GLXscreen *screen, - DrawablePtr pDraw, - int type, - XID drawId, - __GLXconfig *glxConfig) -{ - __GLXDRIscreen *driScreen = (__GLXDRIscreen *) screen; - __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig; - __GLXDRIdrawable *private; - GLboolean retval; - drm_drawable_t hwDrawable; - - private = xcalloc(1, sizeof *private); - if (private == NULL) - return NULL; - - if (!__glXDrawableInit(&private->base, screen, - pDraw, type, drawId, glxConfig)) { - xfree(private); - return NULL; - } - - private->base.destroy = __glXDRIdrawableDestroy; - private->base.swapBuffers = __glXDRIdrawableSwapBuffers; - private->base.copySubBuffer = __glXDRIdrawableCopySubBuffer; - private->base.waitX = NULL; - private->base.waitGL = NULL; - - __glXenterServer(GL_FALSE); - retval = DRICreateDrawable(screen->pScreen, serverClient, - pDraw, &hwDrawable); - __glXleaveServer(GL_FALSE); - - if (!retval) { - xfree(private); - return NULL; - } - - /* The last argument is 'attrs', which is used with pbuffers which - * we currently don't support. */ - - private->driDrawable = - (driScreen->legacy->createNewDrawable)(driScreen->driScreen, - config->driConfig, - hwDrawable, 0, NULL, private); - - if (private->driDrawable == NULL) { - __glXenterServer(GL_FALSE); - DRIDestroyDrawable(screen->pScreen, serverClient, pDraw); - __glXleaveServer(GL_FALSE); - xfree(private); - return NULL; - } - - return &private->base; -} - -static GLboolean -getDrawableInfo(__DRIdrawable *driDrawable, - unsigned int *index, unsigned int *stamp, - int *x, int *y, int *width, int *height, - int *numClipRects, drm_clip_rect_t **ppClipRects, - int *backX, int *backY, - int *numBackClipRects, drm_clip_rect_t **ppBackClipRects, - void *data) -{ - __GLXDRIdrawable *drawable = data; - ScreenPtr pScreen; - drm_clip_rect_t *pClipRects, *pBackClipRects; - GLboolean retval; - size_t size; - - /* If the X window has been destroyed, give up here. */ - if (drawable->base.pDraw == NULL) - return GL_FALSE; - - pScreen = drawable->base.pDraw->pScreen; - __glXenterServer(GL_FALSE); - retval = DRIGetDrawableInfo(pScreen, drawable->base.pDraw, index, stamp, - x, y, width, height, - numClipRects, &pClipRects, - backX, backY, - numBackClipRects, &pBackClipRects); - __glXleaveServer(GL_FALSE); - - if (retval && *numClipRects > 0) { - size = sizeof (drm_clip_rect_t) * *numClipRects; - *ppClipRects = xalloc (size); - - /* Clip cliprects to screen dimensions (redirected windows) */ - if (*ppClipRects != NULL) { - int i, j; - - for (i = 0, j = 0; i < *numClipRects; i++) { - (*ppClipRects)[j].x1 = max(pClipRects[i].x1, 0); - (*ppClipRects)[j].y1 = max(pClipRects[i].y1, 0); - (*ppClipRects)[j].x2 = min(pClipRects[i].x2, pScreen->width); - (*ppClipRects)[j].y2 = min(pClipRects[i].y2, pScreen->height); - - if ((*ppClipRects)[j].x1 < (*ppClipRects)[j].x2 && - (*ppClipRects)[j].y1 < (*ppClipRects)[j].y2) { - j++; - } - } - - if (*numClipRects != j) { - *numClipRects = j; - *ppClipRects = xrealloc (*ppClipRects, - sizeof (drm_clip_rect_t) * - *numClipRects); - } - } else - *numClipRects = 0; - } - else { - *ppClipRects = NULL; - *numClipRects = 0; - } - - if (retval && *numBackClipRects > 0) { - size = sizeof (drm_clip_rect_t) * *numBackClipRects; - *ppBackClipRects = xalloc (size); - if (*ppBackClipRects != NULL) - memcpy (*ppBackClipRects, pBackClipRects, size); - else - *numBackClipRects = 0; - } - else { - *ppBackClipRects = NULL; - *numBackClipRects = 0; - } - - return retval; -} - -static void __glXReportDamage(__DRIdrawable *driDraw, - int x, int y, - drm_clip_rect_t *rects, int num_rects, - GLboolean front_buffer, - void *data) -{ - __GLXDRIdrawable *drawable = data; - DrawablePtr pDraw = drawable->base.pDraw; - RegionRec region; - - __glXenterServer(GL_FALSE); - - REGION_INIT(pDraw->pScreen, ®ion, (BoxPtr) rects, num_rects); - REGION_TRANSLATE(pScreen, ®ion, pDraw->x, pDraw->y); - DamageRegionAppend(pDraw, ®ion); - /* This is wrong, this needs a seperate function. */ - DamageRegionProcessPending(pDraw); - REGION_UNINIT(pDraw->pScreen, ®ion); - - __glXleaveServer(GL_FALSE); -} - -static const __DRIgetDrawableInfoExtension getDrawableInfoExtension = { - { __DRI_GET_DRAWABLE_INFO, __DRI_GET_DRAWABLE_INFO_VERSION }, - getDrawableInfo -}; - -static const __DRIdamageExtension damageExtension = { - { __DRI_DAMAGE, __DRI_DAMAGE_VERSION }, - __glXReportDamage, -}; - -static const __DRIextension *loader_extensions[] = { - &systemTimeExtension.base, - &getDrawableInfoExtension.base, - &damageExtension.base, - NULL -}; - - - -static const char dri_driver_path[] = DRI_DRIVER_PATH; - -static Bool -glxDRIEnterVT (int index, int flags) -{ - __GLXDRIscreen *screen = (__GLXDRIscreen *) - glxGetScreen(screenInfo.screens[index]); - - LogMessage(X_INFO, "AIGLX: Resuming AIGLX clients after VT switch\n"); - - if (!(*screen->enterVT) (index, flags)) - return FALSE; - - glxResumeClients(); - - return TRUE; -} - -static void -glxDRILeaveVT (int index, int flags) -{ - __GLXDRIscreen *screen = (__GLXDRIscreen *) - glxGetScreen(screenInfo.screens[index]); - - LogMessage(X_INFO, "AIGLX: Suspending AIGLX clients for VT switch\n"); - - glxSuspendClients(); - - return (*screen->leaveVT) (index, flags); -} - -static void -initializeExtensions(__GLXDRIscreen *screen) -{ - const __DRIextension **extensions; - int i; - - extensions = screen->core->getExtensions(screen->driScreen); - - for (i = 0; extensions[i]; i++) { -#ifdef __DRI_READ_DRAWABLE - if (strcmp(extensions[i]->name, __DRI_READ_DRAWABLE) == 0) { - __glXEnableExtension(screen->glx_enable_bits, - "GLX_SGI_make_current_read"); - - LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_make_current_read\n"); - } -#endif - -#ifdef __DRI_COPY_SUB_BUFFER - if (strcmp(extensions[i]->name, __DRI_COPY_SUB_BUFFER) == 0) { - screen->copySubBuffer = (__DRIcopySubBufferExtension *) extensions[i]; - __glXEnableExtension(screen->glx_enable_bits, - "GLX_MESA_copy_sub_buffer"); - - LogMessage(X_INFO, "AIGLX: enabled GLX_MESA_copy_sub_buffer\n"); - } -#endif - -#ifdef __DRI_SWAP_CONTROL - if (strcmp(extensions[i]->name, __DRI_SWAP_CONTROL) == 0) { - screen->swapControl = (__DRIswapControlExtension *) extensions[i]; - __glXEnableExtension(screen->glx_enable_bits, - "GLX_SGI_swap_control"); - __glXEnableExtension(screen->glx_enable_bits, - "GLX_MESA_swap_control"); - - LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n"); - } -#endif - -#ifdef __DRI_TEX_OFFSET - if (strcmp(extensions[i]->name, __DRI_TEX_OFFSET) == 0) { - screen->texOffset = (__DRItexOffsetExtension *) extensions[i]; - LogMessage(X_INFO, "AIGLX: enabled GLX_texture_from_pixmap with driver support\n"); - } -#endif - /* Ignore unknown extensions */ - } -} - -extern __GLXconfig * -glxConvertConfigs(const __DRIcoreExtension *core, const __DRIconfig **configs); - -static __GLXscreen * -__glXDRIscreenProbe(ScreenPtr pScreen) -{ - drm_handle_t hSAREA; - drmAddress pSAREA = NULL; - char *BusID; - __DRIversion ddx_version; - __DRIversion dri_version; - __DRIversion drm_version; - __DRIframebuffer framebuffer; - int fd = -1; - int status; - drm_magic_t magic; - drmVersionPtr version; - int newlyopened; - char *driverName; - drm_handle_t hFB; - int junk; - __GLXDRIscreen *screen; - char filename[128]; - Bool isCapable; - size_t buffer_size; - ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum]; - const __DRIconfig **driConfigs; - const __DRIextension **extensions; - int i; - - if (!xf86LoaderCheckSymbol("DRIQueryDirectRenderingCapable") || - !DRIQueryDirectRenderingCapable(pScreen, &isCapable) || - !isCapable) { - LogMessage(X_INFO, - "AIGLX: Screen %d is not DRI capable\n", pScreen->myNum); - return NULL; - } - - screen = xcalloc(1, sizeof *screen); - if (screen == NULL) - return NULL; - - screen->base.destroy = __glXDRIscreenDestroy; - screen->base.createContext = __glXDRIscreenCreateContext; - screen->base.createDrawable = __glXDRIscreenCreateDrawable; - screen->base.swapInterval = __glXDRIdrawableSwapInterval; - screen->base.pScreen = pScreen; - - __glXInitExtensionEnableBits(screen->glx_enable_bits); - - /* DRI protocol version. */ - dri_version.major = XF86DRI_MAJOR_VERSION; - dri_version.minor = XF86DRI_MINOR_VERSION; - dri_version.patch = XF86DRI_PATCH_VERSION; - - if (!DRIOpenConnection(pScreen, &hSAREA, &BusID)) { - LogMessage(X_ERROR, "AIGLX error: DRIOpenConnection failed\n"); - goto handle_error; - } - - fd = drmOpenOnce(NULL, BusID, &newlyopened); - - if (fd < 0) { - LogMessage(X_ERROR, "AIGLX error: drmOpenOnce failed (%s)\n", - strerror(-fd)); - goto handle_error; - } - - if (drmGetMagic(fd, &magic)) { - LogMessage(X_ERROR, "AIGLX error: drmGetMagic failed\n"); - goto handle_error; - } - - version = drmGetVersion(fd); - if (version) { - drm_version.major = version->version_major; - drm_version.minor = version->version_minor; - drm_version.patch = version->version_patchlevel; - drmFreeVersion(version); - } - else { - drm_version.major = -1; - drm_version.minor = -1; - drm_version.patch = -1; - } - - if (newlyopened && !DRIAuthConnection(pScreen, magic)) { - LogMessage(X_ERROR, "AIGLX error: DRIAuthConnection failed\n"); - goto handle_error; - } - - /* Get device name (like "tdfx") and the ddx version numbers. - * We'll check the version in each DRI driver's "createNewScreen" - * function. */ - if (!DRIGetClientDriverName(pScreen, - &ddx_version.major, - &ddx_version.minor, - &ddx_version.patch, - &driverName)) { - LogMessage(X_ERROR, "AIGLX error: DRIGetClientDriverName failed\n"); - goto handle_error; - } - - snprintf(filename, sizeof filename, "%s/%s_dri.so", - dri_driver_path, driverName); - - screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL); - if (screen->driver == NULL) { - LogMessage(X_ERROR, "AIGLX error: dlopen of %s failed (%s)\n", - filename, dlerror()); - goto handle_error; - } - - extensions = dlsym(screen->driver, __DRI_DRIVER_EXTENSIONS); - if (extensions == NULL) { - LogMessage(X_ERROR, "AIGLX error: %s exports no extensions (%s)\n", - driverName, dlerror()); - goto handle_error; - } - - for (i = 0; extensions[i]; i++) { - if (strcmp(extensions[i]->name, __DRI_CORE) == 0 && - extensions[i]->version >= __DRI_CORE_VERSION) { - screen->core = (__DRIcoreExtension *) extensions[i]; - } - - if (strcmp(extensions[i]->name, __DRI_LEGACY) == 0 && - extensions[i]->version >= __DRI_LEGACY_VERSION) { - screen->legacy = (__DRIlegacyExtension *) extensions[i]; - } - } - - if (screen->core == NULL || screen->legacy == NULL) { - LogMessage(X_ERROR, - "AIGLX error: %s does not export required DRI extension\n", - driverName); - goto handle_error; - } - - /* - * Get device-specific info. pDevPriv will point to a struct - * (such as DRIRADEONRec in xfree86/driver/ati/radeon_dri.h) that - * has information about the screen size, depth, pitch, ancilliary - * buffers, DRM mmap handles, etc. - */ - if (!DRIGetDeviceInfo(pScreen, &hFB, &junk, - &framebuffer.size, &framebuffer.stride, - &framebuffer.dev_priv_size, &framebuffer.dev_priv)) { - LogMessage(X_ERROR, "AIGLX error: XF86DRIGetDeviceInfo failed\n"); - goto handle_error; - } - - framebuffer.width = pScreen->width; - framebuffer.height = pScreen->height; - - /* Map the framebuffer region. */ - status = drmMap(fd, hFB, framebuffer.size, - (drmAddressPtr)&framebuffer.base); - if (status != 0) { - LogMessage(X_ERROR, "AIGLX error: drmMap of framebuffer failed (%s)\n", - strerror(-status)); - goto handle_error; - } - - /* Map the SAREA region. Further mmap regions may be setup in - * each DRI driver's "createNewScreen" function. - */ - status = drmMap(fd, hSAREA, SAREA_MAX, &pSAREA); - if (status != 0) { - LogMessage(X_ERROR, "AIGLX error: drmMap of SAREA failed (%s)\n", - strerror(-status)); - goto handle_error; - } - - screen->driScreen = - (*screen->legacy->createNewScreen)(pScreen->myNum, - &ddx_version, - &dri_version, - &drm_version, - &framebuffer, - pSAREA, - fd, - loader_extensions, - &driConfigs, - screen); - - if (screen->driScreen == NULL) { - LogMessage(X_ERROR, - "AIGLX error: Calling driver entry point failed\n"); - goto handle_error; - } - - screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs); - - initializeExtensions(screen); - - DRIGetTexOffsetFuncs(pScreen, &screen->texOffsetStart, - &screen->texOffsetFinish); - - __glXScreenInit(&screen->base, pScreen); - - /* The first call simply determines the length of the extension string. - * This allows us to allocate some memory to hold the extension string, - * but it requires that we call __glXGetExtensionString a second time. - */ - buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL); - if (buffer_size > 0) { - if (screen->base.GLXextensions != NULL) { - xfree(screen->base.GLXextensions); - } - - screen->base.GLXextensions = xnfalloc(buffer_size); - (void) __glXGetExtensionString(screen->glx_enable_bits, - screen->base.GLXextensions); - } - - __glXsetEnterLeaveServerFuncs(__glXDRIenterServer, __glXDRIleaveServer); - - screen->enterVT = pScrn->EnterVT; - pScrn->EnterVT = glxDRIEnterVT; - screen->leaveVT = pScrn->LeaveVT; - pScrn->LeaveVT = glxDRILeaveVT; - - LogMessage(X_INFO, - "AIGLX: Loaded and initialized %s\n", filename); - - return &screen->base; - - handle_error: - if (pSAREA != NULL) - drmUnmap(pSAREA, SAREA_MAX); - - if (framebuffer.base != NULL) - drmUnmap((drmAddress)framebuffer.base, framebuffer.size); - - if (fd >= 0) - drmCloseOnce(fd); - - DRICloseConnection(pScreen); - - if (screen->driver) - dlclose(screen->driver); - - xfree(screen); - - LogMessage(X_ERROR, "AIGLX: reverting to software rendering\n"); - - return NULL; -} - -_X_EXPORT __GLXprovider __glXDRIProvider = { - __glXDRIscreenProbe, - "DRI", - NULL -}; +/*
+ * Copyright © 2006 Red Hat, 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 Red Hat,
+ * Inc not be used in advertising or publicity pertaining to
+ * distribution of the software without specific, written prior
+ * permission. Red Hat, Inc makes no representations about the
+ * suitability of this software for any purpose. It is provided "as
+ * is" without express or implied warranty.
+ *
+ * RED HAT, INC DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
+ * NO EVENT SHALL RED HAT, INC 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_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdint.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#ifndef _MSC_VER
+#include <sys/time.h>
+#include <dlfcn.h>
+
+#include <drm.h>
+#endif
+
+#include <GL/gl.h>
+#include <GL/internal/dri_interface.h>
+
+#include <windowstr.h>
+#include <os.h>
+#include <damage.h>
+
+#define _XF86DRI_SERVER_
+#include <drm_sarea.h>
+#include <xf86drm.h>
+#include <X11/dri/xf86driproto.h>
+#include <xf86str.h>
+#include <xf86.h>
+#include <dri.h>
+
+#include "servermd.h"
+
+#define DRI_NEW_INTERFACE_ONLY
+#include "glxserver.h"
+#include "glxutil.h"
+#include "glxdricommon.h"
+
+#include "g_disptab.h"
+#include "glapitable.h"
+#include "glapi.h"
+#include "glthread.h"
+#include "dispatch.h"
+#include "extension_string.h"
+
+typedef struct __GLXDRIscreen __GLXDRIscreen;
+typedef struct __GLXDRIcontext __GLXDRIcontext;
+typedef struct __GLXDRIdrawable __GLXDRIdrawable;
+
+struct __GLXDRIscreen {
+ __GLXscreen base;
+ __DRIscreen *driScreen;
+ void *driver;
+
+ xf86EnterVTProc *enterVT;
+ xf86LeaveVTProc *leaveVT;
+
+ const __DRIcoreExtension *core;
+ const __DRIlegacyExtension *legacy;
+ const __DRIcopySubBufferExtension *copySubBuffer;
+ const __DRIswapControlExtension *swapControl;
+
+#ifdef __DRI_TEX_OFFSET
+ const __DRItexOffsetExtension *texOffset;
+ DRITexOffsetStartProcPtr texOffsetStart;
+ DRITexOffsetFinishProcPtr texOffsetFinish;
+ __GLXDRIdrawable *texOffsetOverride[16];
+ GLuint lastTexOffsetOverride;
+#endif
+
+ unsigned char glx_enable_bits[__GLX_EXT_BYTES];
+};
+
+struct __GLXDRIcontext {
+ __GLXcontext base;
+ __DRIcontext *driContext;
+ XID hwContextID;
+};
+
+struct __GLXDRIdrawable {
+ __GLXdrawable base;
+ __DRIdrawable *driDrawable;
+
+ /* Pulled in from old __GLXpixmap */
+#ifdef __DRI_TEX_OFFSET
+ GLint texname;
+ __GLXDRIcontext *ctx;
+ unsigned long long offset;
+ DamagePtr pDamage;
+#endif
+};
+
+static void
+__glXDRIleaveServer(GLboolean rendering)
+{
+ int i;
+
+ for (i = 0; rendering && i < screenInfo.numScreens; i++) {
+ __GLXDRIscreen * const screen =
+ (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]);
+ GLuint lastOverride = screen->lastTexOffsetOverride;
+
+ if (lastOverride) {
+ __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride;
+ int j;
+
+ for (j = 0; j < lastOverride; j++) {
+ __GLXDRIdrawable *pGlxPix = texOffsetOverride[j];
+
+ if (pGlxPix && pGlxPix->texname) {
+ pGlxPix->offset =
+ screen->texOffsetStart((PixmapPtr)pGlxPix->base.pDraw);
+ }
+ }
+ }
+ }
+
+ DRIBlockHandler(NULL, NULL, NULL);
+
+ for (i = 0; rendering && i < screenInfo.numScreens; i++) {
+ __GLXDRIscreen * const screen =
+ (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]);
+ GLuint lastOverride = screen->lastTexOffsetOverride;
+
+ if (lastOverride) {
+ __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride;
+ int j;
+
+ for (j = 0; j < lastOverride; j++) {
+ __GLXDRIdrawable *pGlxPix = texOffsetOverride[j];
+
+ if (pGlxPix && pGlxPix->texname) {
+ screen->texOffset->setTexOffset(pGlxPix->ctx->driContext,
+ pGlxPix->texname,
+ pGlxPix->offset,
+ pGlxPix->base.pDraw->depth,
+ ((PixmapPtr)pGlxPix->base.pDraw)->devKind);
+ }
+ }
+ }
+ }
+}
+
+static void
+__glXDRIenterServer(GLboolean rendering)
+{
+ int i;
+
+ for (i = 0; rendering && i < screenInfo.numScreens; i++) {
+ __GLXDRIscreen * const screen = (__GLXDRIscreen *)
+ glxGetScreen(screenInfo.screens[i]);
+
+ if (screen->lastTexOffsetOverride) {
+ CALL_Flush(GET_DISPATCH(), ());
+ break;
+ }
+ }
+
+ DRIWakeupHandler(NULL, 0, NULL);
+}
+
+
+static void
+__glXDRIdoReleaseTexImage(__GLXDRIscreen *screen, __GLXDRIdrawable *drawable)
+{
+ GLuint lastOverride = screen->lastTexOffsetOverride;
+
+ if (lastOverride) {
+ __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride;
+ int i;
+
+ for (i = 0; i < lastOverride; i++) {
+ if (texOffsetOverride[i] == drawable) {
+ if (screen->texOffsetFinish)
+ screen->texOffsetFinish((PixmapPtr)drawable->base.pDraw);
+
+ texOffsetOverride[i] = NULL;
+
+ if (i + 1 == lastOverride) {
+ lastOverride = 0;
+
+ while (i--) {
+ if (texOffsetOverride[i]) {
+ lastOverride = i + 1;
+ break;
+ }
+ }
+
+ screen->lastTexOffsetOverride = lastOverride;
+
+ break;
+ }
+ }
+ }
+ }
+}
+
+
+static void
+__glXDRIdrawableDestroy(__GLXdrawable *drawable)
+{
+ __GLXDRIdrawable *private = (__GLXDRIdrawable *) drawable;
+ __GLXDRIscreen *screen;
+ int i;
+
+ for (i = 0; i < screenInfo.numScreens; i++) {
+ screen = (__GLXDRIscreen *) glxGetScreen(screenInfo.screens[i]);
+ __glXDRIdoReleaseTexImage(screen, private);
+ }
+
+ /* If the X window was destroyed, the dri DestroyWindow hook will
+ * aready have taken care of this, so only call if pDraw isn't NULL. */
+ if (drawable->pDraw != NULL) {
+ screen = (__GLXDRIscreen *) glxGetScreen(drawable->pDraw->pScreen);
+ (*screen->core->destroyDrawable)(private->driDrawable);
+
+ __glXenterServer(GL_FALSE);
+ DRIDestroyDrawable(drawable->pDraw->pScreen,
+ serverClient, drawable->pDraw);
+ __glXleaveServer(GL_FALSE);
+ }
+
+ __glXDrawableRelease(drawable);
+
+ xfree(private);
+}
+
+static GLboolean
+__glXDRIdrawableSwapBuffers(__GLXdrawable *basePrivate)
+{
+ __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate;
+ __GLXDRIscreen *screen =
+ (__GLXDRIscreen *) glxGetScreen(basePrivate->pDraw->pScreen);
+
+ (*screen->core->swapBuffers)(private->driDrawable);
+
+ return TRUE;
+}
+
+
+static int
+__glXDRIdrawableSwapInterval(__GLXdrawable *baseDrawable, int interval)
+{
+ __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseDrawable;
+ __GLXDRIscreen *screen =
+ (__GLXDRIscreen *) glxGetScreen(baseDrawable->pDraw->pScreen);
+
+ if (screen->swapControl)
+ screen->swapControl->setSwapInterval(draw->driDrawable, interval);
+
+ return 0;
+}
+
+
+static void
+__glXDRIdrawableCopySubBuffer(__GLXdrawable *basePrivate,
+ int x, int y, int w, int h)
+{
+ __GLXDRIdrawable *private = (__GLXDRIdrawable *) basePrivate;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *)
+ glxGetScreen(basePrivate->pDraw->pScreen);
+
+ if (screen->copySubBuffer)
+ screen->copySubBuffer->copySubBuffer(private->driDrawable, x, y, w, h);
+}
+
+static void
+__glXDRIcontextDestroy(__GLXcontext *baseContext)
+{
+ __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
+ Bool retval;
+
+ screen->core->destroyContext(context->driContext);
+
+ __glXenterServer(GL_FALSE);
+ retval = DRIDestroyContext(baseContext->pGlxScreen->pScreen,
+ context->hwContextID);
+ __glXleaveServer(GL_FALSE);
+
+ __glXContextDestroy(&context->base);
+ xfree(context);
+}
+
+static int
+__glXDRIcontextMakeCurrent(__GLXcontext *baseContext)
+{
+ __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
+ __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
+ __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
+
+ return (*screen->core->bindContext)(context->driContext,
+ draw->driDrawable,
+ read->driDrawable);
+}
+
+static int
+__glXDRIcontextLoseCurrent(__GLXcontext *baseContext)
+{
+ __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
+
+ return (*screen->core->unbindContext)(context->driContext);
+}
+
+static int
+__glXDRIcontextCopy(__GLXcontext *baseDst, __GLXcontext *baseSrc,
+ unsigned long mask)
+{
+ __GLXDRIcontext *dst = (__GLXDRIcontext *) baseDst;
+ __GLXDRIcontext *src = (__GLXDRIcontext *) baseSrc;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) dst->base.pGlxScreen;
+
+ return (*screen->core->copyContext)(dst->driContext,
+ src->driContext, mask);
+}
+
+static int
+__glXDRIcontextForceCurrent(__GLXcontext *baseContext)
+{
+ __GLXDRIcontext *context = (__GLXDRIcontext *) baseContext;
+ __GLXDRIdrawable *draw = (__GLXDRIdrawable *) baseContext->drawPriv;
+ __GLXDRIdrawable *read = (__GLXDRIdrawable *) baseContext->readPriv;
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) context->base.pGlxScreen;
+
+ return (*screen->core->bindContext)(context->driContext,
+ draw->driDrawable,
+ read->driDrawable);
+}
+
+static void
+glxFillAlphaChannel (CARD32 *pixels, CARD32 rowstride, int width, int height)
+{
+ int i;
+ CARD32 *p, *end;
+
+ rowstride /= 4;
+
+ for (i = 0; i < height; i++)
+ {
+ p = pixels;
+ end = p + width;
+ while (p < end)
+ *p++ |= 0xFF000000;
+ pixels += rowstride;
+ }
+}
+
+static Bool
+testTexOffset(__GLXDRIscreen * const screen, PixmapPtr pPixmap)
+{
+ Bool ret;
+
+ if (!screen->texOffsetStart || !screen->texOffset)
+ return FALSE;
+
+ __glXenterServer(GL_FALSE);
+ ret = screen->texOffsetStart(pPixmap) != ~0ULL;
+ __glXleaveServer(GL_FALSE);
+
+ return ret;
+}
+
+/*
+ * (sticking this here for lack of a better place)
+ * Known issues with the GLX_EXT_texture_from_pixmap implementation:
+ * - In general we ignore the fbconfig, lots of examples follow
+ * - No fbconfig handling for multiple mipmap levels
+ * - No fbconfig handling for 1D textures
+ * - No fbconfig handling for TEXTURE_TARGET
+ * - No fbconfig exposure of Y inversion state
+ * - No GenerateMipmapEXT support (due to no FBO support)
+ * - No support for anything but 16bpp and 32bpp-sparse pixmaps
+ */
+
+static int
+__glXDRIbindTexImage(__GLXcontext *baseContext,
+ int buffer,
+ __GLXdrawable *glxPixmap)
+{
+ RegionPtr pRegion = NULL;
+ PixmapPtr pixmap;
+ int bpp, override = 0, texname;
+ GLenum format, type;
+ ScreenPtr pScreen = glxPixmap->pDraw->pScreen;
+ __GLXDRIdrawable *driDraw = (__GLXDRIdrawable *) glxPixmap;
+ __GLXDRIscreen * const screen = (__GLXDRIscreen *) glxGetScreen(pScreen);
+
+ CALL_GetIntegerv(GET_DISPATCH(), (glxPixmap->target == GL_TEXTURE_2D ?
+ GL_TEXTURE_BINDING_2D :
+ GL_TEXTURE_BINDING_RECTANGLE_NV,
+ &texname));
+
+ if (!texname)
+ return __glXError(GLXBadContextState);
+
+ pixmap = (PixmapPtr) glxPixmap->pDraw;
+
+ if (testTexOffset(screen, pixmap)) {
+ __GLXDRIdrawable **texOffsetOverride = screen->texOffsetOverride;
+ int i, firstEmpty = 16;
+
+ for (i = 0; i < 16; i++) {
+ if (texOffsetOverride[i] == driDraw)
+ goto alreadyin;
+
+ if (firstEmpty == 16 && !texOffsetOverride[i])
+ firstEmpty = i;
+ }
+
+ if (firstEmpty == 16) {
+ ErrorF("%s: Failed to register texture offset override\n", __func__);
+ goto nooverride;
+ }
+
+ if (firstEmpty >= screen->lastTexOffsetOverride)
+ screen->lastTexOffsetOverride = firstEmpty + 1;
+
+ texOffsetOverride[firstEmpty] = driDraw;
+
+alreadyin:
+ override = 1;
+
+ driDraw->ctx = (__GLXDRIcontext*)baseContext;
+
+ if (texname == driDraw->texname)
+ return Success;
+
+ driDraw->texname = texname;
+
+ screen->texOffset->setTexOffset(driDraw->ctx->driContext, texname, 0,
+ pixmap->drawable.depth,
+ pixmap->devKind);
+ }
+nooverride:
+
+ if (!driDraw->pDamage) {
+ if (!override) {
+ driDraw->pDamage = DamageCreate(NULL, NULL, DamageReportNone,
+ TRUE, pScreen, NULL);
+ if (!driDraw->pDamage)
+ return BadAlloc;
+
+ DamageRegister ((DrawablePtr) pixmap, driDraw->pDamage);
+ }
+
+ pRegion = NULL;
+ } else {
+ pRegion = DamageRegion(driDraw->pDamage);
+ if (REGION_NIL(pRegion))
+ return Success;
+ }
+
+ /* XXX 24bpp packed, 8, etc */
+ if (pixmap->drawable.depth >= 24) {
+ bpp = 4;
+ format = GL_BGRA;
+ type =
+#if X_BYTE_ORDER == X_BIG_ENDIAN
+ !override ? GL_UNSIGNED_INT_8_8_8_8_REV :
+#endif
+ GL_UNSIGNED_BYTE;
+ } else {
+ bpp = 2;
+ format = GL_RGB;
+ type = GL_UNSIGNED_SHORT_5_6_5;
+ }
+
+ if (pRegion == NULL)
+ {
+ void *data = NULL;
+
+ if (!override) {
+ unsigned pitch = PixmapBytePad(pixmap->drawable.width,
+ pixmap->drawable.depth);
+
+ data = xalloc(pitch * pixmap->drawable.height);
+
+ __glXenterServer(GL_FALSE);
+ pScreen->GetImage(&pixmap->drawable, 0 /*pixmap->drawable.x*/,
+ 0 /*pixmap->drawable.y*/, pixmap->drawable.width,
+ pixmap->drawable.height, ZPixmap, ~0, data);
+ __glXleaveServer(GL_FALSE);
+
+ if (pixmap->drawable.depth == 24)
+ glxFillAlphaChannel(data,
+ pitch,
+ pixmap->drawable.width,
+ pixmap->drawable.height);
+
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_ROW_LENGTH,
+ pitch / bpp) );
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_PIXELS, 0) );
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_ROWS, 0) );
+ }
+
+ CALL_TexImage2D( GET_DISPATCH(),
+ (glxPixmap->target,
+ 0,
+ bpp == 4 ? 4 : 3,
+ pixmap->drawable.width,
+ pixmap->drawable.height,
+ 0,
+ format,
+ type,
+ data) );
+
+ xfree(data);
+ } else if (!override) {
+ int i, numRects;
+ BoxPtr p;
+
+ numRects = REGION_NUM_RECTS (pRegion);
+ p = REGION_RECTS (pRegion);
+
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_PIXELS, 0) );
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_SKIP_ROWS, 0) );
+
+ for (i = 0; i < numRects; i++)
+ {
+ unsigned pitch = PixmapBytePad(p[i].x2 - p[i].x1,
+ pixmap->drawable.depth);
+ void *data = xalloc(pitch * (p[i].y2 - p[i].y1));
+
+ __glXenterServer(GL_FALSE);
+ pScreen->GetImage(&pixmap->drawable, /*pixmap->drawable.x +*/ p[i].x1,
+ /*pixmap->drawable.y*/ + p[i].y1, p[i].x2 - p[i].x1,
+ p[i].y2 - p[i].y1, ZPixmap, ~0, data);
+ __glXleaveServer(GL_FALSE);
+
+ if (pixmap->drawable.depth == 24)
+ glxFillAlphaChannel(data,
+ pitch,
+ p[i].x2 - p[i].x1,
+ p[i].y2 - p[i].y1);
+
+ CALL_PixelStorei( GET_DISPATCH(), (GL_UNPACK_ROW_LENGTH,
+ pitch / bpp) );
+
+ CALL_TexSubImage2D( GET_DISPATCH(),
+ (glxPixmap->target,
+ 0,
+ p[i].x1, p[i].y1,
+ p[i].x2 - p[i].x1, p[i].y2 - p[i].y1,
+ format,
+ type,
+ data) );
+
+ xfree(data);
+ }
+ }
+
+ if (!override)
+ DamageEmpty(driDraw->pDamage);
+
+ return Success;
+}
+
+static int
+__glXDRIreleaseTexImage(__GLXcontext *baseContext,
+ int buffer,
+ __GLXdrawable *pixmap)
+{
+ __GLXDRIscreen *screen =
+ (__GLXDRIscreen *) glxGetScreen(pixmap->pDraw->pScreen);
+ __GLXDRIdrawable *drawable = (__GLXDRIdrawable *) pixmap;
+
+ __glXDRIdoReleaseTexImage(screen, drawable);
+
+ return Success;
+}
+
+static __GLXtextureFromPixmap __glXDRItextureFromPixmap = {
+ __glXDRIbindTexImage,
+ __glXDRIreleaseTexImage
+};
+
+static void
+__glXDRIscreenDestroy(__GLXscreen *baseScreen)
+{
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
+
+ screen->core->destroyScreen(screen->driScreen);
+
+ dlclose(screen->driver);
+
+ __glXScreenDestroy(baseScreen);
+
+ xfree(screen);
+}
+
+static __GLXcontext *
+__glXDRIscreenCreateContext(__GLXscreen *baseScreen,
+ __GLXconfig *glxConfig,
+ __GLXcontext *baseShareContext)
+{
+ __GLXDRIscreen *screen = (__GLXDRIscreen *) baseScreen;
+ __GLXDRIcontext *context, *shareContext;
+ __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
+ VisualPtr visual;
+ int i;
+ GLboolean retval;
+ __DRIcontext *driShare;
+ drm_context_t hwContext;
+ ScreenPtr pScreen = baseScreen->pScreen;
+
+ shareContext = (__GLXDRIcontext *) baseShareContext;
+ if (shareContext)
+ driShare = shareContext->driContext;
+ else
+ driShare = NULL;
+
+ if (baseShareContext && baseShareContext->isDirect)
+ return NULL;
+
+ context = xcalloc(1, sizeof *context);
+ if (context == NULL)
+ return NULL;
+
+ context->base.destroy = __glXDRIcontextDestroy;
+ context->base.makeCurrent = __glXDRIcontextMakeCurrent;
+ context->base.loseCurrent = __glXDRIcontextLoseCurrent;
+ context->base.copy = __glXDRIcontextCopy;
+ context->base.forceCurrent = __glXDRIcontextForceCurrent;
+
+ context->base.textureFromPixmap = &__glXDRItextureFromPixmap;
+ /* Find the requested X visual */
+ visual = pScreen->visuals;
+ for (i = 0; i < pScreen->numVisuals; i++, visual++)
+ if (visual->vid == glxConfig->visualID)
+ break;
+ if (i == pScreen->numVisuals)
+ return NULL;
+
+ context->hwContextID = FakeClientID(0);
+
+ __glXenterServer(GL_FALSE);
+ retval = DRICreateContext(baseScreen->pScreen, visual,
+ context->hwContextID, &hwContext);
+ __glXleaveServer(GL_FALSE);
+
+ if (!retval)
+ return NULL;
+
+ context->driContext =
+ screen->legacy->createNewContext(screen->driScreen,
+ config->driConfig,
+ 0, /* render type */
+ driShare,
+ hwContext,
+ context);
+
+ if (context->driContext == NULL) {
+ __glXenterServer(GL_FALSE);
+ retval = DRIDestroyContext(baseScreen->pScreen, context->hwContextID);
+ __glXleaveServer(GL_FALSE);
+ xfree(context);
+ return NULL;
+ }
+
+ return &context->base;
+}
+
+static __GLXdrawable *
+__glXDRIscreenCreateDrawable(__GLXscreen *screen,
+ DrawablePtr pDraw,
+ int type,
+ XID drawId,
+ __GLXconfig *glxConfig)
+{
+ __GLXDRIscreen *driScreen = (__GLXDRIscreen *) screen;
+ __GLXDRIconfig *config = (__GLXDRIconfig *) glxConfig;
+ __GLXDRIdrawable *private;
+ GLboolean retval;
+ drm_drawable_t hwDrawable;
+
+ private = xcalloc(1, sizeof *private);
+ if (private == NULL)
+ return NULL;
+
+ if (!__glXDrawableInit(&private->base, screen,
+ pDraw, type, drawId, glxConfig)) {
+ xfree(private);
+ return NULL;
+ }
+
+ private->base.destroy = __glXDRIdrawableDestroy;
+ private->base.swapBuffers = __glXDRIdrawableSwapBuffers;
+ private->base.copySubBuffer = __glXDRIdrawableCopySubBuffer;
+ private->base.waitX = NULL;
+ private->base.waitGL = NULL;
+
+ __glXenterServer(GL_FALSE);
+ retval = DRICreateDrawable(screen->pScreen, serverClient,
+ pDraw, &hwDrawable);
+ __glXleaveServer(GL_FALSE);
+
+ if (!retval) {
+ xfree(private);
+ return NULL;
+ }
+
+ /* The last argument is 'attrs', which is used with pbuffers which
+ * we currently don't support. */
+
+ private->driDrawable =
+ (driScreen->legacy->createNewDrawable)(driScreen->driScreen,
+ config->driConfig,
+ hwDrawable, 0, NULL, private);
+
+ if (private->driDrawable == NULL) {
+ __glXenterServer(GL_FALSE);
+ DRIDestroyDrawable(screen->pScreen, serverClient, pDraw);
+ __glXleaveServer(GL_FALSE);
+ xfree(private);
+ return NULL;
+ }
+
+ return &private->base;
+}
+
+static GLboolean
+getDrawableInfo(__DRIdrawable *driDrawable,
+ unsigned int *index, unsigned int *stamp,
+ int *x, int *y, int *width, int *height,
+ int *numClipRects, drm_clip_rect_t **ppClipRects,
+ int *backX, int *backY,
+ int *numBackClipRects, drm_clip_rect_t **ppBackClipRects,
+ void *data)
+{
+ __GLXDRIdrawable *drawable = data;
+ ScreenPtr pScreen;
+ drm_clip_rect_t *pClipRects, *pBackClipRects;
+ GLboolean retval;
+ size_t size;
+
+ /* If the X window has been destroyed, give up here. */
+ if (drawable->base.pDraw == NULL)
+ return GL_FALSE;
+
+ pScreen = drawable->base.pDraw->pScreen;
+ __glXenterServer(GL_FALSE);
+ retval = DRIGetDrawableInfo(pScreen, drawable->base.pDraw, index, stamp,
+ x, y, width, height,
+ numClipRects, &pClipRects,
+ backX, backY,
+ numBackClipRects, &pBackClipRects);
+ __glXleaveServer(GL_FALSE);
+
+ if (retval && *numClipRects > 0) {
+ size = sizeof (drm_clip_rect_t) * *numClipRects;
+ *ppClipRects = xalloc (size);
+
+ /* Clip cliprects to screen dimensions (redirected windows) */
+ if (*ppClipRects != NULL) {
+ int i, j;
+
+ for (i = 0, j = 0; i < *numClipRects; i++) {
+ (*ppClipRects)[j].x1 = max(pClipRects[i].x1, 0);
+ (*ppClipRects)[j].y1 = max(pClipRects[i].y1, 0);
+ (*ppClipRects)[j].x2 = min(pClipRects[i].x2, pScreen->width);
+ (*ppClipRects)[j].y2 = min(pClipRects[i].y2, pScreen->height);
+
+ if ((*ppClipRects)[j].x1 < (*ppClipRects)[j].x2 &&
+ (*ppClipRects)[j].y1 < (*ppClipRects)[j].y2) {
+ j++;
+ }
+ }
+
+ if (*numClipRects != j) {
+ *numClipRects = j;
+ *ppClipRects = xrealloc (*ppClipRects,
+ sizeof (drm_clip_rect_t) *
+ *numClipRects);
+ }
+ } else
+ *numClipRects = 0;
+ }
+ else {
+ *ppClipRects = NULL;
+ *numClipRects = 0;
+ }
+
+ if (retval && *numBackClipRects > 0) {
+ size = sizeof (drm_clip_rect_t) * *numBackClipRects;
+ *ppBackClipRects = xalloc (size);
+ if (*ppBackClipRects != NULL)
+ memcpy (*ppBackClipRects, pBackClipRects, size);
+ else
+ *numBackClipRects = 0;
+ }
+ else {
+ *ppBackClipRects = NULL;
+ *numBackClipRects = 0;
+ }
+
+ return retval;
+}
+
+static void __glXReportDamage(__DRIdrawable *driDraw,
+ int x, int y,
+ drm_clip_rect_t *rects, int num_rects,
+ GLboolean front_buffer,
+ void *data)
+{
+ __GLXDRIdrawable *drawable = data;
+ DrawablePtr pDraw = drawable->base.pDraw;
+ RegionRec region;
+
+ __glXenterServer(GL_FALSE);
+
+ REGION_INIT(pDraw->pScreen, ®ion, (BoxPtr) rects, num_rects);
+ REGION_TRANSLATE(pScreen, ®ion, pDraw->x, pDraw->y);
+ DamageRegionAppend(pDraw, ®ion);
+ /* This is wrong, this needs a seperate function. */
+ DamageRegionProcessPending(pDraw);
+ REGION_UNINIT(pDraw->pScreen, ®ion);
+
+ __glXleaveServer(GL_FALSE);
+}
+
+static const __DRIgetDrawableInfoExtension getDrawableInfoExtension = {
+ { __DRI_GET_DRAWABLE_INFO, __DRI_GET_DRAWABLE_INFO_VERSION },
+ getDrawableInfo
+};
+
+static const __DRIdamageExtension damageExtension = {
+ { __DRI_DAMAGE, __DRI_DAMAGE_VERSION },
+ __glXReportDamage,
+};
+
+static const __DRIextension *loader_extensions[] = {
+ &systemTimeExtension.base,
+ &getDrawableInfoExtension.base,
+ &damageExtension.base,
+ NULL
+};
+
+
+
+static const char dri_driver_path[] = DRI_DRIVER_PATH;
+
+static Bool
+glxDRIEnterVT (int index, int flags)
+{
+ __GLXDRIscreen *screen = (__GLXDRIscreen *)
+ glxGetScreen(screenInfo.screens[index]);
+
+ LogMessage(X_INFO, "AIGLX: Resuming AIGLX clients after VT switch\n");
+
+ if (!(*screen->enterVT) (index, flags))
+ return FALSE;
+
+ glxResumeClients();
+
+ return TRUE;
+}
+
+static void
+glxDRILeaveVT (int index, int flags)
+{
+ __GLXDRIscreen *screen = (__GLXDRIscreen *)
+ glxGetScreen(screenInfo.screens[index]);
+
+ LogMessage(X_INFO, "AIGLX: Suspending AIGLX clients for VT switch\n");
+
+ glxSuspendClients();
+
+ return (*screen->leaveVT) (index, flags);
+}
+
+static void
+initializeExtensions(__GLXDRIscreen *screen)
+{
+ const __DRIextension **extensions;
+ int i;
+
+ extensions = screen->core->getExtensions(screen->driScreen);
+
+ for (i = 0; extensions[i]; i++) {
+#ifdef __DRI_READ_DRAWABLE
+ if (strcmp(extensions[i]->name, __DRI_READ_DRAWABLE) == 0) {
+ __glXEnableExtension(screen->glx_enable_bits,
+ "GLX_SGI_make_current_read");
+
+ LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_make_current_read\n");
+ }
+#endif
+
+#ifdef __DRI_COPY_SUB_BUFFER
+ if (strcmp(extensions[i]->name, __DRI_COPY_SUB_BUFFER) == 0) {
+ screen->copySubBuffer = (__DRIcopySubBufferExtension *) extensions[i];
+ __glXEnableExtension(screen->glx_enable_bits,
+ "GLX_MESA_copy_sub_buffer");
+
+ LogMessage(X_INFO, "AIGLX: enabled GLX_MESA_copy_sub_buffer\n");
+ }
+#endif
+
+#ifdef __DRI_SWAP_CONTROL
+ if (strcmp(extensions[i]->name, __DRI_SWAP_CONTROL) == 0) {
+ screen->swapControl = (__DRIswapControlExtension *) extensions[i];
+ __glXEnableExtension(screen->glx_enable_bits,
+ "GLX_SGI_swap_control");
+ __glXEnableExtension(screen->glx_enable_bits,
+ "GLX_MESA_swap_control");
+
+ LogMessage(X_INFO, "AIGLX: enabled GLX_SGI_swap_control and GLX_MESA_swap_control\n");
+ }
+#endif
+
+#ifdef __DRI_TEX_OFFSET
+ if (strcmp(extensions[i]->name, __DRI_TEX_OFFSET) == 0) {
+ screen->texOffset = (__DRItexOffsetExtension *) extensions[i];
+ LogMessage(X_INFO, "AIGLX: enabled GLX_texture_from_pixmap with driver support\n");
+ }
+#endif
+ /* Ignore unknown extensions */
+ }
+}
+
+extern __GLXconfig *
+glxConvertConfigs(const __DRIcoreExtension *core, const __DRIconfig **configs);
+
+static __GLXscreen *
+__glXDRIscreenProbe(ScreenPtr pScreen)
+{
+ drm_handle_t hSAREA;
+ drmAddress pSAREA = NULL;
+ char *BusID;
+ __DRIversion ddx_version;
+ __DRIversion dri_version;
+ __DRIversion drm_version;
+ __DRIframebuffer framebuffer;
+ int fd = -1;
+ int status;
+ drm_magic_t magic;
+ drmVersionPtr version;
+ int newlyopened;
+ char *driverName;
+ drm_handle_t hFB;
+ int junk;
+ __GLXDRIscreen *screen;
+ char filename[128];
+ Bool isCapable;
+ size_t buffer_size;
+ ScrnInfoPtr pScrn = xf86Screens[pScreen->myNum];
+ const __DRIconfig **driConfigs;
+ const __DRIextension **extensions;
+ int i;
+
+ if (!xf86LoaderCheckSymbol("DRIQueryDirectRenderingCapable") ||
+ !DRIQueryDirectRenderingCapable(pScreen, &isCapable) ||
+ !isCapable) {
+ LogMessage(X_INFO,
+ "AIGLX: Screen %d is not DRI capable\n", pScreen->myNum);
+ return NULL;
+ }
+
+ screen = xcalloc(1, sizeof *screen);
+ if (screen == NULL)
+ return NULL;
+
+ screen->base.destroy = __glXDRIscreenDestroy;
+ screen->base.createContext = __glXDRIscreenCreateContext;
+ screen->base.createDrawable = __glXDRIscreenCreateDrawable;
+ screen->base.swapInterval = __glXDRIdrawableSwapInterval;
+ screen->base.pScreen = pScreen;
+
+ __glXInitExtensionEnableBits(screen->glx_enable_bits);
+
+ /* DRI protocol version. */
+ dri_version.major = XF86DRI_MAJOR_VERSION;
+ dri_version.minor = XF86DRI_MINOR_VERSION;
+ dri_version.patch = XF86DRI_PATCH_VERSION;
+
+ if (!DRIOpenConnection(pScreen, &hSAREA, &BusID)) {
+ LogMessage(X_ERROR, "AIGLX error: DRIOpenConnection failed\n");
+ goto handle_error;
+ }
+
+ fd = drmOpenOnce(NULL, BusID, &newlyopened);
+
+ if (fd < 0) {
+ LogMessage(X_ERROR, "AIGLX error: drmOpenOnce failed (%s)\n",
+ strerror(-fd));
+ goto handle_error;
+ }
+
+ if (drmGetMagic(fd, &magic)) {
+ LogMessage(X_ERROR, "AIGLX error: drmGetMagic failed\n");
+ goto handle_error;
+ }
+
+ version = drmGetVersion(fd);
+ if (version) {
+ drm_version.major = version->version_major;
+ drm_version.minor = version->version_minor;
+ drm_version.patch = version->version_patchlevel;
+ drmFreeVersion(version);
+ }
+ else {
+ drm_version.major = -1;
+ drm_version.minor = -1;
+ drm_version.patch = -1;
+ }
+
+ if (newlyopened && !DRIAuthConnection(pScreen, magic)) {
+ LogMessage(X_ERROR, "AIGLX error: DRIAuthConnection failed\n");
+ goto handle_error;
+ }
+
+ /* Get device name (like "tdfx") and the ddx version numbers.
+ * We'll check the version in each DRI driver's "createNewScreen"
+ * function. */
+ if (!DRIGetClientDriverName(pScreen,
+ &ddx_version.major,
+ &ddx_version.minor,
+ &ddx_version.patch,
+ &driverName)) {
+ LogMessage(X_ERROR, "AIGLX error: DRIGetClientDriverName failed\n");
+ goto handle_error;
+ }
+
+ snprintf(filename, sizeof filename, "%s/%s_dri.so",
+ dri_driver_path, driverName);
+
+ screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL);
+ if (screen->driver == NULL) {
+ LogMessage(X_ERROR, "AIGLX error: dlopen of %s failed (%s)\n",
+ filename, dlerror());
+ goto handle_error;
+ }
+
+ extensions = dlsym(screen->driver, __DRI_DRIVER_EXTENSIONS);
+ if (extensions == NULL) {
+ LogMessage(X_ERROR, "AIGLX error: %s exports no extensions (%s)\n",
+ driverName, dlerror());
+ goto handle_error;
+ }
+
+ for (i = 0; extensions[i]; i++) {
+ if (strcmp(extensions[i]->name, __DRI_CORE) == 0 &&
+ extensions[i]->version >= __DRI_CORE_VERSION) {
+ screen->core = (__DRIcoreExtension *) extensions[i];
+ }
+
+ if (strcmp(extensions[i]->name, __DRI_LEGACY) == 0 &&
+ extensions[i]->version >= __DRI_LEGACY_VERSION) {
+ screen->legacy = (__DRIlegacyExtension *) extensions[i];
+ }
+ }
+
+ if (screen->core == NULL || screen->legacy == NULL) {
+ LogMessage(X_ERROR,
+ "AIGLX error: %s does not export required DRI extension\n",
+ driverName);
+ goto handle_error;
+ }
+
+ /*
+ * Get device-specific info. pDevPriv will point to a struct
+ * (such as DRIRADEONRec in xfree86/driver/ati/radeon_dri.h) that
+ * has information about the screen size, depth, pitch, ancilliary
+ * buffers, DRM mmap handles, etc.
+ */
+ if (!DRIGetDeviceInfo(pScreen, &hFB, &junk,
+ &framebuffer.size, &framebuffer.stride,
+ &framebuffer.dev_priv_size, &framebuffer.dev_priv)) {
+ LogMessage(X_ERROR, "AIGLX error: XF86DRIGetDeviceInfo failed\n");
+ goto handle_error;
+ }
+
+ framebuffer.width = pScreen->width;
+ framebuffer.height = pScreen->height;
+
+ /* Map the framebuffer region. */
+ status = drmMap(fd, hFB, framebuffer.size,
+ (drmAddressPtr)&framebuffer.base);
+ if (status != 0) {
+ LogMessage(X_ERROR, "AIGLX error: drmMap of framebuffer failed (%s)\n",
+ strerror(-status));
+ goto handle_error;
+ }
+
+ /* Map the SAREA region. Further mmap regions may be setup in
+ * each DRI driver's "createNewScreen" function.
+ */
+ status = drmMap(fd, hSAREA, SAREA_MAX, &pSAREA);
+ if (status != 0) {
+ LogMessage(X_ERROR, "AIGLX error: drmMap of SAREA failed (%s)\n",
+ strerror(-status));
+ goto handle_error;
+ }
+
+ screen->driScreen =
+ (*screen->legacy->createNewScreen)(pScreen->myNum,
+ &ddx_version,
+ &dri_version,
+ &drm_version,
+ &framebuffer,
+ pSAREA,
+ fd,
+ loader_extensions,
+ &driConfigs,
+ screen);
+
+ if (screen->driScreen == NULL) {
+ LogMessage(X_ERROR,
+ "AIGLX error: Calling driver entry point failed\n");
+ goto handle_error;
+ }
+
+ screen->base.fbconfigs = glxConvertConfigs(screen->core, driConfigs);
+
+ initializeExtensions(screen);
+
+ DRIGetTexOffsetFuncs(pScreen, &screen->texOffsetStart,
+ &screen->texOffsetFinish);
+
+ __glXScreenInit(&screen->base, pScreen);
+
+ /* The first call simply determines the length of the extension string.
+ * This allows us to allocate some memory to hold the extension string,
+ * but it requires that we call __glXGetExtensionString a second time.
+ */
+ buffer_size = __glXGetExtensionString(screen->glx_enable_bits, NULL);
+ if (buffer_size > 0) {
+ if (screen->base.GLXextensions != NULL) {
+ xfree(screen->base.GLXextensions);
+ }
+
+ screen->base.GLXextensions = xnfalloc(buffer_size);
+ (void) __glXGetExtensionString(screen->glx_enable_bits,
+ screen->base.GLXextensions);
+ }
+
+ __glXsetEnterLeaveServerFuncs(__glXDRIenterServer, __glXDRIleaveServer);
+
+ screen->enterVT = pScrn->EnterVT;
+ pScrn->EnterVT = glxDRIEnterVT;
+ screen->leaveVT = pScrn->LeaveVT;
+ pScrn->LeaveVT = glxDRILeaveVT;
+
+ LogMessage(X_INFO,
+ "AIGLX: Loaded and initialized %s\n", filename);
+
+ return &screen->base;
+
+ handle_error:
+ if (pSAREA != NULL)
+ drmUnmap(pSAREA, SAREA_MAX);
+
+ if (framebuffer.base != NULL)
+ drmUnmap((drmAddress)framebuffer.base, framebuffer.size);
+
+ if (fd >= 0)
+ drmCloseOnce(fd);
+
+ DRICloseConnection(pScreen);
+
+ if (screen->driver)
+ dlclose(screen->driver);
+
+ xfree(screen);
+
+ LogMessage(X_ERROR, "AIGLX: reverting to software rendering\n");
+
+ return NULL;
+}
+
+_X_EXPORT __GLXprovider __glXDRIProvider = {
+ __glXDRIscreenProbe,
+ "DRI",
+ NULL
+};
diff --git a/xorg-server/glx/glxdricommon.c b/xorg-server/glx/glxdricommon.c index faaa3b7ae..028c77842 100644 --- a/xorg-server/glx/glxdricommon.c +++ b/xorg-server/glx/glxdricommon.c @@ -25,6 +25,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <stdint.h> @@ -47,12 +51,16 @@ getUST(int64_t *ust) if (ust == NULL) return -EFAULT; +#ifdef _MSC_VER + __asm int 3; +#else if (gettimeofday(&tv, NULL) == 0) { ust[0] = (tv.tv_sec * 1000000) + tv.tv_usec; return 0; } else { return -errno; } + #endif } const __DRIsystemTimeExtension systemTimeExtension = { diff --git a/xorg-server/glx/glxdriswrast.c b/xorg-server/glx/glxdriswrast.c index 44f658fa9..b5d707a21 100644 --- a/xorg-server/glx/glxdriswrast.c +++ b/xorg-server/glx/glxdriswrast.c @@ -26,6 +26,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <stdint.h> @@ -62,6 +66,10 @@ #endif #endif +#ifdef _MSC_VER +#define dlerror() "Getting loadlibrary error string not implemented" +#endif + typedef struct __GLXDRIscreen __GLXDRIscreen; typedef struct __GLXDRIcontext __GLXDRIcontext; typedef struct __GLXDRIdrawable __GLXDRIdrawable; @@ -250,7 +258,11 @@ __glXDRIscreenDestroy(__GLXscreen *baseScreen) (*screen->core->destroyScreen)(screen->driScreen); +#ifdef _MSC_VER + FreeLibrary(screen->driver); +#else dlclose(screen->driver); +#endif __glXScreenDestroy(baseScreen); @@ -461,14 +473,22 @@ __glXDRIscreenProbe(ScreenPtr pScreen) snprintf(filename, sizeof filename, "%s/%s_dri.so", dri_driver_path, driverName); +#ifdef _MSC_VER + screen->driver = LoadLibrary(filename); +#else screen->driver = dlopen(filename, RTLD_LAZY | RTLD_LOCAL); +#endif if (screen->driver == NULL) { LogMessage(X_ERROR, "AIGLX error: dlopen of %s failed (%s)\n", filename, dlerror()); goto handle_error; } +#ifdef _MSC_VER + extensions = GetProcAddress(screen->driver, __DRI_DRIVER_EXTENSIONS); +#else extensions = dlsym(screen->driver, __DRI_DRIVER_EXTENSIONS); +#endif if (extensions == NULL) { LogMessage(X_ERROR, "AIGLX error: %s exports no extensions (%s)\n", driverName, dlerror()); @@ -517,7 +537,11 @@ __glXDRIscreenProbe(ScreenPtr pScreen) handle_error: if (screen->driver) +#ifdef _MSC_VER + FreeLibrary(screen->driver); +#else dlclose(screen->driver); +#endif xfree(screen); diff --git a/xorg-server/glx/glxext.c b/xorg-server/glx/glxext.c index 19d70d495..95f09d296 100644 --- a/xorg-server/glx/glxext.c +++ b/xorg-server/glx/glxext.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <string.h> diff --git a/xorg-server/glx/glxscreens.c b/xorg-server/glx/glxscreens.c index 81faddd04..fe7b22d96 100644 --- a/xorg-server/glx/glxscreens.c +++ b/xorg-server/glx/glxscreens.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <GL/glxtokens.h> diff --git a/xorg-server/glx/glxserver.h b/xorg-server/glx/glxserver.h index 4aa8c2eec..87d7c3945 100644 --- a/xorg-server/glx/glxserver.h +++ b/xorg-server/glx/glxserver.h @@ -1,251 +1,252 @@ -#ifdef HAVE_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#ifndef _GLX_server_h_ -#define _GLX_server_h_ - -/* - * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008) - * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the "Software"), - * to deal in the Software without restriction, including without limitation - * the rights to use, copy, modify, merge, publish, distribute, sublicense, - * and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice including the dates of first publication and - * either this permission notice or a reference to - * http://oss.sgi.com/projects/FreeB/ - * 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 - * SILICON GRAPHICS, INC. 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 Silicon Graphics, Inc. - * shall not be used in advertising or otherwise to promote the sale, use or - * other dealings in this Software without prior written authorization from - * Silicon Graphics, Inc. - */ - -#include <X11/X.h> -#include <X11/Xproto.h> -#include <X11/Xmd.h> -#include <misc.h> -#include <dixstruct.h> -#include <pixmapstr.h> -#include <gcstruct.h> -#include <extnsionst.h> -#include <resource.h> -#include <scrnintstr.h> - -/* -** The X header misc.h defines these math functions. -*/ -#undef abs -#undef fabs - -#define GL_GLEXT_PROTOTYPES /* we want prototypes */ -#include <GL/gl.h> -#include <GL/glxproto.h> - -/* For glxscreens.h */ -typedef struct __GLXdrawable __GLXdrawable; -typedef struct __GLXcontext __GLXcontext; - -#include "glxscreens.h" -#include "glxdrawable.h" -#include "glxcontext.h" - -#ifndef True -#define True 1 -#endif -#ifndef False -#define False 0 -#endif - -/* -** GLX resources. -*/ -typedef XID GLXContextID; -typedef XID GLXPixmap; -typedef XID GLXDrawable; - -typedef struct __GLXclientStateRec __GLXclientState; - -extern __GLXscreen *glxGetScreen(ScreenPtr pScreen); -extern __GLXclientState *glxGetClient(ClientPtr pClient); - -/************************************************************************/ - -void GlxExtensionInit(void); - -void GlxSetVisualConfigs(int nconfigs, - void *configs, void **privates); - -void __glXScreenInitVisuals(__GLXscreen *screen); - -/* -** The last context used (from the server's persective) is cached. -*/ -extern __GLXcontext *__glXLastContext; -extern __GLXcontext *__glXForceCurrent(__GLXclientState*, GLXContextTag, int*); - -extern ClientPtr __pGlxClient; - -int __glXError(int error); - -/* -** Macros to set, unset, and retrieve the flag that says whether a context -** has unflushed commands. -*/ -#define __GLX_NOTE_UNFLUSHED_CMDS(glxc) glxc->hasUnflushedCommands = GL_TRUE -#define __GLX_NOTE_FLUSHED_CMDS(glxc) glxc->hasUnflushedCommands = GL_FALSE -#define __GLX_HAS_UNFLUSHED_CMDS(glxc) (glxc->hasUnflushedCommands) - -/************************************************************************/ - -typedef struct __GLXprovider __GLXprovider; -struct __GLXprovider { - __GLXscreen *(*screenProbe)(ScreenPtr pScreen); - const char *name; - __GLXprovider *next; -}; - -void GlxPushProvider(__GLXprovider *provider); - -enum { - GLX_MINIMAL_VISUALS, - GLX_TYPICAL_VISUALS, - GLX_ALL_VISUALS -}; - -void __glXsetEnterLeaveServerFuncs(void (*enter)(GLboolean), - void (*leave)(GLboolean)); -void __glXenterServer(GLboolean rendering); -void __glXleaveServer(GLboolean rendering); - -void glxSuspendClients(void); -void glxResumeClients(void); - -/* -** State kept per client. -*/ -struct __GLXclientStateRec { - /* - ** Whether this structure is currently being used to support a client. - */ - Bool inUse; - - /* - ** Buffer for returned data. - */ - GLbyte *returnBuf; - GLint returnBufSize; - - /* - ** Keep track of large rendering commands, which span multiple requests. - */ - GLint largeCmdBytesSoFar; /* bytes received so far */ - GLint largeCmdBytesTotal; /* total bytes expected */ - GLint largeCmdRequestsSoFar; /* requests received so far */ - GLint largeCmdRequestsTotal; /* total requests expected */ - GLbyte *largeCmdBuf; - GLint largeCmdBufSize; - - /* - ** Keep a list of all the contexts that are current for this client's - ** threads. - */ - __GLXcontext **currentContexts; - GLint numCurrentContexts; - - /* Back pointer to X client record */ - ClientPtr client; - - int GLClientmajorVersion; - int GLClientminorVersion; - char *GLClientextensions; -}; - -/************************************************************************/ - -/* -** Dispatch tables. -*/ -typedef void (*__GLXdispatchRenderProcPtr)(GLbyte *); -typedef int (*__GLXdispatchSingleProcPtr)(__GLXclientState *, GLbyte *); -typedef int (*__GLXdispatchVendorPrivProcPtr)(__GLXclientState *, GLbyte *); - -/* - * Dispatch for GLX commands. - */ -typedef int (*__GLXprocPtr)(__GLXclientState *, char *pc); - -/* - * Tables for computing the size of each rendering command. - */ -typedef int (*gl_proto_size_func)(const GLbyte *, Bool); - -typedef struct { - int bytes; - gl_proto_size_func varsize; -} __GLXrenderSizeData; - -/************************************************************************/ - -/* -** X resources. -*/ -extern RESTYPE __glXContextRes; -extern RESTYPE __glXClientRes; -extern RESTYPE __glXPixmapRes; -extern RESTYPE __glXDrawableRes; - -/************************************************************************/ - -/* -** Prototypes. -*/ - -extern char *__glXcombine_strings(const char *, const char *); - -/* -** Routines for sending swapped replies. -*/ - -extern void __glXSwapMakeCurrentReply(ClientPtr client, - xGLXMakeCurrentReply *reply); -extern void __glXSwapIsDirectReply(ClientPtr client, - xGLXIsDirectReply *reply); -extern void __glXSwapQueryVersionReply(ClientPtr client, - xGLXQueryVersionReply *reply); -extern void __glXSwapQueryContextInfoEXTReply(ClientPtr client, - xGLXQueryContextInfoEXTReply *reply, - int *buf); -extern void __glXSwapGetDrawableAttributesReply(ClientPtr client, - xGLXGetDrawableAttributesReply *reply, CARD32 *buf); -extern void glxSwapQueryExtensionsStringReply(ClientPtr client, - xGLXQueryExtensionsStringReply *reply, char *buf); -extern void glxSwapQueryServerStringReply(ClientPtr client, - xGLXQueryServerStringReply *reply, char *buf); - - -/* - * Routines for computing the size of variably-sized rendering commands. - */ - -extern int __glXTypeSize(GLenum enm); -extern int __glXImageSize(GLenum format, GLenum type, - GLenum target, GLsizei w, GLsizei h, GLsizei d, - GLint imageHeight, GLint rowLength, GLint skipImages, GLint skipRows, - GLint alignment); - -#endif /* !__GLX_server_h__ */ +#ifdef HAVE_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#ifndef _GLX_server_h_
+#define _GLX_server_h_
+
+/*
+ * SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
+ * Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the "Software"),
+ * to deal in the Software without restriction, including without limitation
+ * the rights to use, copy, modify, merge, publish, distribute, sublicense,
+ * and/or sell copies of the Software, and to permit persons to whom the
+ * Software is furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice including the dates of first publication and
+ * either this permission notice or a reference to
+ * http://oss.sgi.com/projects/FreeB/
+ * 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
+ * SILICON GRAPHICS, INC. 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 Silicon Graphics, Inc.
+ * shall not be used in advertising or otherwise to promote the sale, use or
+ * other dealings in this Software without prior written authorization from
+ * Silicon Graphics, Inc.
+ */
+
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include <X11/Xmd.h>
+#include <misc.h>
+#include <dixstruct.h>
+#include <pixmapstr.h>
+#include <gcstruct.h>
+#include <extnsionst.h>
+#include <resource.h>
+#include <scrnintstr.h>
+
+/*
+** The X header misc.h defines these math functions.
+*/
+#undef abs
+#undef fabs
+
+#define GL_GLEXT_PROTOTYPES /* we want prototypes */
+#include <GL/gl.h>
+#include <GL/glext.h>
+#include <GL/glxproto.h>
+
+/* For glxscreens.h */
+typedef struct __GLXdrawable __GLXdrawable;
+typedef struct __GLXcontext __GLXcontext;
+
+#include "glxscreens.h"
+#include "glxdrawable.h"
+#include "glxcontext.h"
+
+#ifndef True
+#define True 1
+#endif
+#ifndef False
+#define False 0
+#endif
+
+/*
+** GLX resources.
+*/
+typedef XID GLXContextID;
+typedef XID GLXPixmap;
+typedef XID GLXDrawable;
+
+typedef struct __GLXclientStateRec __GLXclientState;
+
+extern __GLXscreen *glxGetScreen(ScreenPtr pScreen);
+extern __GLXclientState *glxGetClient(ClientPtr pClient);
+
+/************************************************************************/
+
+void GlxExtensionInit(void);
+
+void GlxSetVisualConfigs(int nconfigs,
+ void *configs, void **privates);
+
+void __glXScreenInitVisuals(__GLXscreen *screen);
+
+/*
+** The last context used (from the server's persective) is cached.
+*/
+extern __GLXcontext *__glXLastContext;
+extern __GLXcontext *__glXForceCurrent(__GLXclientState*, GLXContextTag, int*);
+
+extern ClientPtr __pGlxClient;
+
+int __glXError(int error);
+
+/*
+** Macros to set, unset, and retrieve the flag that says whether a context
+** has unflushed commands.
+*/
+#define __GLX_NOTE_UNFLUSHED_CMDS(glxc) glxc->hasUnflushedCommands = GL_TRUE
+#define __GLX_NOTE_FLUSHED_CMDS(glxc) glxc->hasUnflushedCommands = GL_FALSE
+#define __GLX_HAS_UNFLUSHED_CMDS(glxc) (glxc->hasUnflushedCommands)
+
+/************************************************************************/
+
+typedef struct __GLXprovider __GLXprovider;
+struct __GLXprovider {
+ __GLXscreen *(*screenProbe)(ScreenPtr pScreen);
+ const char *name;
+ __GLXprovider *next;
+};
+
+void GlxPushProvider(__GLXprovider *provider);
+
+enum {
+ GLX_MINIMAL_VISUALS,
+ GLX_TYPICAL_VISUALS,
+ GLX_ALL_VISUALS
+};
+
+void __glXsetEnterLeaveServerFuncs(void (*enter)(GLboolean),
+ void (*leave)(GLboolean));
+void __glXenterServer(GLboolean rendering);
+void __glXleaveServer(GLboolean rendering);
+
+void glxSuspendClients(void);
+void glxResumeClients(void);
+
+/*
+** State kept per client.
+*/
+struct __GLXclientStateRec {
+ /*
+ ** Whether this structure is currently being used to support a client.
+ */
+ Bool inUse;
+
+ /*
+ ** Buffer for returned data.
+ */
+ GLbyte *returnBuf;
+ GLint returnBufSize;
+
+ /*
+ ** Keep track of large rendering commands, which span multiple requests.
+ */
+ GLint largeCmdBytesSoFar; /* bytes received so far */
+ GLint largeCmdBytesTotal; /* total bytes expected */
+ GLint largeCmdRequestsSoFar; /* requests received so far */
+ GLint largeCmdRequestsTotal; /* total requests expected */
+ GLbyte *largeCmdBuf;
+ GLint largeCmdBufSize;
+
+ /*
+ ** Keep a list of all the contexts that are current for this client's
+ ** threads.
+ */
+ __GLXcontext **currentContexts;
+ GLint numCurrentContexts;
+
+ /* Back pointer to X client record */
+ ClientPtr client;
+
+ int GLClientmajorVersion;
+ int GLClientminorVersion;
+ char *GLClientextensions;
+};
+
+/************************************************************************/
+
+/*
+** Dispatch tables.
+*/
+typedef void (*__GLXdispatchRenderProcPtr)(GLbyte *);
+typedef int (*__GLXdispatchSingleProcPtr)(__GLXclientState *, GLbyte *);
+typedef int (*__GLXdispatchVendorPrivProcPtr)(__GLXclientState *, GLbyte *);
+
+/*
+ * Dispatch for GLX commands.
+ */
+typedef int (*__GLXprocPtr)(__GLXclientState *, char *pc);
+
+/*
+ * Tables for computing the size of each rendering command.
+ */
+typedef int (*gl_proto_size_func)(const GLbyte *, Bool);
+
+typedef struct {
+ int bytes;
+ gl_proto_size_func varsize;
+} __GLXrenderSizeData;
+
+/************************************************************************/
+
+/*
+** X resources.
+*/
+extern RESTYPE __glXContextRes;
+extern RESTYPE __glXClientRes;
+extern RESTYPE __glXPixmapRes;
+extern RESTYPE __glXDrawableRes;
+
+/************************************************************************/
+
+/*
+** Prototypes.
+*/
+
+extern char *__glXcombine_strings(const char *, const char *);
+
+/*
+** Routines for sending swapped replies.
+*/
+
+extern void __glXSwapMakeCurrentReply(ClientPtr client,
+ xGLXMakeCurrentReply *reply);
+extern void __glXSwapIsDirectReply(ClientPtr client,
+ xGLXIsDirectReply *reply);
+extern void __glXSwapQueryVersionReply(ClientPtr client,
+ xGLXQueryVersionReply *reply);
+extern void __glXSwapQueryContextInfoEXTReply(ClientPtr client,
+ xGLXQueryContextInfoEXTReply *reply,
+ int *buf);
+extern void __glXSwapGetDrawableAttributesReply(ClientPtr client,
+ xGLXGetDrawableAttributesReply *reply, CARD32 *buf);
+extern void glxSwapQueryExtensionsStringReply(ClientPtr client,
+ xGLXQueryExtensionsStringReply *reply, char *buf);
+extern void glxSwapQueryServerStringReply(ClientPtr client,
+ xGLXQueryServerStringReply *reply, char *buf);
+
+
+/*
+ * Routines for computing the size of variably-sized rendering commands.
+ */
+
+extern int __glXTypeSize(GLenum enm);
+extern int __glXImageSize(GLenum format, GLenum type,
+ GLenum target, GLsizei w, GLsizei h, GLsizei d,
+ GLint imageHeight, GLint rowLength, GLint skipImages, GLint skipRows,
+ GLint alignment);
+
+#endif /* !__GLX_server_h__ */
diff --git a/xorg-server/glx/indirect_dispatch.c b/xorg-server/glx/indirect_dispatch.c index 666551903..1da14750d 100644 --- a/xorg-server/glx/indirect_dispatch.c +++ b/xorg-server/glx/indirect_dispatch.c @@ -24,6 +24,13 @@ * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#else + +#include "glheader.h" + +#endif #include <X11/Xmd.h> #include <GL/gl.h> diff --git a/xorg-server/glx/indirect_dispatch_swap.c b/xorg-server/glx/indirect_dispatch_swap.c index 3221c809d..64d9dc99b 100644 --- a/xorg-server/glx/indirect_dispatch_swap.c +++ b/xorg-server/glx/indirect_dispatch_swap.c @@ -24,6 +24,13 @@ * OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#else + +#include "glheader.h" + +#endif #include <X11/Xmd.h> #include <GL/gl.h> diff --git a/xorg-server/glx/indirect_program.c b/xorg-server/glx/indirect_program.c index 237da2908..165d12bd9 100644 --- a/xorg-server/glx/indirect_program.c +++ b/xorg-server/glx/indirect_program.c @@ -31,6 +31,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/indirect_reqsize.c b/xorg-server/glx/indirect_reqsize.c index 35bb9370f..ed64d0f46 100644 --- a/xorg-server/glx/indirect_reqsize.c +++ b/xorg-server/glx/indirect_reqsize.c @@ -25,6 +25,13 @@ * SOFTWARE. */ +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#else + +#include "glheader.h" + +#endif #include <GL/gl.h> #include "glxserver.h" diff --git a/xorg-server/glx/indirect_size_get.c b/xorg-server/glx/indirect_size_get.c index 80f81dec6..7b8fa49cd 100644 --- a/xorg-server/glx/indirect_size_get.c +++ b/xorg-server/glx/indirect_size_get.c @@ -25,6 +25,13 @@ * SOFTWARE. */ +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#else + +#include "glheader.h" + +#endif #include <GL/gl.h> #include "indirect_size_get.h" @@ -888,7 +895,9 @@ __glGetTexLevelParameterfv_size(GLenum e) case GL_TEXTURE_INTENSITY_SIZE: /* case GL_TEXTURE_INTENSITY_SIZE_EXT:*/ case GL_TEXTURE_DEPTH: +#ifndef _MSC_VER case GL_TEXTURE_INDEX_SIZE_EXT: +#endif case GL_TEXTURE_COMPRESSED_IMAGE_SIZE: /* case GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB:*/ case GL_TEXTURE_COMPRESSED: diff --git a/xorg-server/glx/indirect_table.c b/xorg-server/glx/indirect_table.c index cb3202605..b5ac86a5a 100644 --- a/xorg-server/glx/indirect_table.c +++ b/xorg-server/glx/indirect_table.c @@ -25,6 +25,10 @@ * SOFTWARE. */ +#ifndef HAVE_DIX_CONFIG_H +#include "glheader.h" +#endif + #include <inttypes.h> #include "glxserver.h" #include "glxext.h" diff --git a/xorg-server/glx/indirect_texture_compression.c b/xorg-server/glx/indirect_texture_compression.c index 25c6eb30e..f20ebc8af 100644 --- a/xorg-server/glx/indirect_texture_compression.c +++ b/xorg-server/glx/indirect_texture_compression.c @@ -25,6 +25,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/indirect_util.c b/xorg-server/glx/indirect_util.c index 44309104e..2f48ab2b0 100644 --- a/xorg-server/glx/indirect_util.c +++ b/xorg-server/glx/indirect_util.c @@ -25,6 +25,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <string.h> diff --git a/xorg-server/glx/makefile b/xorg-server/glx/makefile new file mode 100644 index 000000000..0debc92a0 --- /dev/null +++ b/xorg-server/glx/makefile @@ -0,0 +1,7 @@ +CSRCS=glapi.c glthread.c glxcmds.c glxcmdsswap.c glxdricommon.c glxext.c glxscreens.c \
+indirect_dispatch.c indirect_dispatch_swap.c indirect_program.c indirect_reqsize.c indirect_size_get.c indirect_table.c indirect_texture_compression.c \
+indirect_util.c render2.c render2swap.c renderpix.c renderpixswap.c rensize.c single2.c single2swap.c singlepix.c singlepixswap.c singlesize.c \
+swap_interval.c xfont.c glxdriswrast.c
+
+LIBRARY=libglx
+
diff --git a/xorg-server/glx/render2.c b/xorg-server/glx/render2.c index eb7c30ba0..32cee4160 100644 --- a/xorg-server/glx/render2.c +++ b/xorg-server/glx/render2.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <glxserver.h> diff --git a/xorg-server/glx/render2swap.c b/xorg-server/glx/render2swap.c index 17354c4f8..59cb93a6a 100644 --- a/xorg-server/glx/render2swap.c +++ b/xorg-server/glx/render2swap.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/renderpix.c b/xorg-server/glx/renderpix.c index 056e62c87..3e5612036 100644 --- a/xorg-server/glx/renderpix.c +++ b/xorg-server/glx/renderpix.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/renderpixswap.c b/xorg-server/glx/renderpixswap.c index 9cd57410e..a73ed1e3c 100644 --- a/xorg-server/glx/renderpixswap.c +++ b/xorg-server/glx/renderpixswap.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/rensize.c b/xorg-server/glx/rensize.c index 8a58e08d7..6b85dc116 100644 --- a/xorg-server/glx/rensize.c +++ b/xorg-server/glx/rensize.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <GL/gl.h> @@ -219,7 +223,9 @@ int __glXImageSize( GLenum format, GLenum type, GLenum target, case GL_422_AVERAGE_EXT: case GL_422_REV_AVERAGE_EXT: case GL_DEPTH_STENCIL_NV: +#ifndef _MSC_VER case GL_DEPTH_STENCIL_MESA: +#endif case GL_YCBCR_MESA: case GL_LUMINANCE_ALPHA: elementsPerGroup = 2; @@ -258,11 +264,13 @@ int __glXImageSize( GLenum format, GLenum type, GLenum target, case GL_UNSIGNED_SHORT_1_5_5_5_REV: case GL_UNSIGNED_SHORT_8_8_APPLE: case GL_UNSIGNED_SHORT_8_8_REV_APPLE: +#ifndef _MSC_VER case GL_UNSIGNED_SHORT_15_1_MESA: case GL_UNSIGNED_SHORT_1_15_REV_MESA: bytesPerElement = 2; elementsPerGroup = 1; break; +#endif case GL_INT: case GL_UNSIGNED_INT: case GL_FLOAT: @@ -273,8 +281,10 @@ int __glXImageSize( GLenum format, GLenum type, GLenum target, case GL_UNSIGNED_INT_10_10_10_2: case GL_UNSIGNED_INT_2_10_10_10_REV: case GL_UNSIGNED_INT_24_8_NV: +#ifndef _MSC_VER case GL_UNSIGNED_INT_24_8_MESA: case GL_UNSIGNED_INT_8_24_REV_MESA: +#endif bytesPerElement = 4; elementsPerGroup = 1; break; diff --git a/xorg-server/glx/single2.c b/xorg-server/glx/single2.c index 50a59ed71..f6e474c46 100644 --- a/xorg-server/glx/single2.c +++ b/xorg-server/glx/single2.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <string.h> diff --git a/xorg-server/glx/single2swap.c b/xorg-server/glx/single2swap.c index cf83bdc88..e27e97aee 100644 --- a/xorg-server/glx/single2swap.c +++ b/xorg-server/glx/single2swap.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/singlepix.c b/xorg-server/glx/singlepix.c index a0a6a7918..656f1ec5e 100644 --- a/xorg-server/glx/singlepix.c +++ b/xorg-server/glx/singlepix.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/singlepixswap.c b/xorg-server/glx/singlepixswap.c index a7febc9a6..c7d2d1562 100644 --- a/xorg-server/glx/singlepixswap.c +++ b/xorg-server/glx/singlepixswap.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/glx/singlesize.c b/xorg-server/glx/singlesize.c index 9e95dd3d3..a9a2be66b 100644 --- a/xorg-server/glx/singlesize.c +++ b/xorg-server/glx/singlesize.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include <GL/gl.h> diff --git a/xorg-server/glx/swap_interval.c b/xorg-server/glx/swap_interval.c index 3a5242022..03f83cb89 100644 --- a/xorg-server/glx/swap_interval.c +++ b/xorg-server/glx/swap_interval.c @@ -24,6 +24,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" @@ -53,7 +57,7 @@ int DoSwapInterval(__GLXclientState *cl, GLbyte *pc, int do_swap) cx = __glXLookupContextByTag(cl, tag); - LogMessage(X_ERROR, "%s: cx = %p, GLX screen = %p\n", __func__, + LogMessage(X_ERROR, "%s: cx = %p, GLX screen = %p\n", __FUNCTION__ , cx, (cx == NULL) ? NULL : cx->pGlxScreen); if ((cx == NULL) || (cx->pGlxScreen == NULL)) { client->errorValue = tag; diff --git a/xorg-server/glx/xfont.c b/xorg-server/glx/xfont.c index b8b466d87..2af5996f3 100644 --- a/xorg-server/glx/xfont.c +++ b/xorg-server/glx/xfont.c @@ -30,6 +30,10 @@ #ifdef HAVE_DIX_CONFIG_H #include <dix-config.h> +#else + +#include "glheader.h" + #endif #include "glxserver.h" diff --git a/xorg-server/hw/dmx/dmxinit.c b/xorg-server/hw/dmx/dmxinit.c index e5598e331..739c4ca7f 100644 --- a/xorg-server/hw/dmx/dmxinit.c +++ b/xorg-server/hw/dmx/dmxinit.c @@ -1,1035 +1,1042 @@ -/* - * Copyright 2001-2004 Red Hat Inc., Durham, North Carolina. - * - * All Rights Reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation on the rights to use, copy, modify, merge, - * publish, distribute, sublicense, and/or sell copies of the Software, - * and to permit persons to whom the Software is furnished to do so, - * subject to the following conditions: - * - * The above copyright notice and this permission notice (including the - * next paragraph) shall be included in all copies or substantial - * portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - */ - -/* - * Authors: - * Kevin E. Martin <kem@redhat.com> - * David H. Dawes <dawes@xfree86.org> - * Rickard E. (Rik) Faith <faith@redhat.com> - * - */ - -/** \file - * Provide expected functions for initialization from the ddx layer and - * global variables for the DMX server. */ - -#ifdef HAVE_DMX_CONFIG_H -#include <dmx-config.h> -#endif - -#include "dmx.h" -#include "dmxinit.h" -#include "dmxsync.h" -#include "dmxlog.h" -#include "dmxinput.h" -#include "dmxscrinit.h" -#include "dmxcursor.h" -#include "dmxfont.h" -#include "config/dmxconfig.h" -#include "dmxcb.h" -#include "dmxprop.h" -#include "dmxstat.h" -#ifdef RENDER -#include "dmxpict.h" -#endif - -#include <X11/Xos.h> /* For gettimeofday */ -#include "dixstruct.h" -#ifdef PANORAMIX -#include "panoramiXsrv.h" -#endif - -#include <signal.h> /* For SIGQUIT */ - -#ifdef GLXEXT -#include <GL/glx.h> -#include <GL/glxint.h> -#include "dmx_glxvisuals.h" -#include <X11/extensions/Xext.h> -#include <X11/extensions/extutil.h> - -extern void GlxSetVisualConfigs( - int nconfigs, - __GLXvisualConfig *configs, - void **configprivs -); -#endif /* GLXEXT */ - -/* Global variables available to all Xserver/hw/dmx routines. */ -int dmxNumScreens; -DMXScreenInfo *dmxScreens; - -int dmxNumInputs; -DMXInputInfo *dmxInputs; - -int dmxShadowFB = FALSE; - -XErrorEvent dmxLastErrorEvent; -Bool dmxErrorOccurred = FALSE; - -char *dmxFontPath = NULL; - -Bool dmxOffScreenOpt = TRUE; - -Bool dmxSubdividePrimitives = TRUE; - -Bool dmxLazyWindowCreation = TRUE; - -Bool dmxUseXKB = TRUE; - -int dmxDepth = 0; - -#ifndef GLXEXT -static Bool dmxGLXProxy = FALSE; -#else -Bool dmxGLXProxy = TRUE; - -Bool dmxGLXSwapGroupSupport = TRUE; - -Bool dmxGLXSyncSwap = FALSE; - -Bool dmxGLXFinishSwap = FALSE; -#endif - -Bool dmxIgnoreBadFontPaths = FALSE; - -Bool dmxAddRemoveScreens = FALSE; - -/* dmxErrorHandler catches errors that occur when calling one of the - * back-end servers. Some of this code is based on _XPrintDefaultError - * in xc/lib/X11/XlibInt.c */ -static int dmxErrorHandler(Display *dpy, XErrorEvent *ev) -{ -#define DMX_ERROR_BUF_SIZE 256 - /* RATS: these buffers are only used in - * length-limited calls. */ - char buf[DMX_ERROR_BUF_SIZE]; - char request[DMX_ERROR_BUF_SIZE]; - _XExtension *ext = NULL; - - dmxErrorOccurred = TRUE; - dmxLastErrorEvent = *ev; - - XGetErrorText(dpy, ev->error_code, buf, sizeof(buf)); - dmxLog(dmxWarning, "dmxErrorHandler: %s\n", buf); - - /* Find major opcode name */ - if (ev->request_code < 128) { - XmuSnprintf(request, sizeof(request), "%d", ev->request_code); - XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf)); - } else { - for (ext = dpy->ext_procs; - ext && ext->codes.major_opcode != ev->request_code; - ext = ext->next); - if (ext) strncpy(buf, ext->name, sizeof(buf)); - else buf[0] = '\0'; - } - dmxLog(dmxWarning, " Major opcode: %d (%s)\n", - ev->request_code, buf); - - /* Find minor opcode name */ - if (ev->request_code >= 128 && ext) { - XmuSnprintf(request, sizeof(request), "%d", ev->request_code); - XmuSnprintf(request, sizeof(request), "%s.%d", - ext->name, ev->minor_code); - XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf)); - dmxLog(dmxWarning, " Minor opcode: %d (%s)\n", - ev->minor_code, buf); - } - - /* Provide value information */ - switch (ev->error_code) { - case BadValue: - dmxLog(dmxWarning, " Value: 0x%x\n", - ev->resourceid); - break; - case BadAtom: - dmxLog(dmxWarning, " AtomID: 0x%x\n", - ev->resourceid); - break; - default: - dmxLog(dmxWarning, " ResourceID: 0x%x\n", - ev->resourceid); - break; - } - - /* Provide serial number information */ - dmxLog(dmxWarning, " Failed serial number: %d\n", - ev->serial); - dmxLog(dmxWarning, " Current serial number: %d\n", - dpy->request); - return 0; -} - -#ifdef GLXEXT -static int dmxNOPErrorHandler(Display *dpy, XErrorEvent *ev) -{ - return 0; -} -#endif - -Bool dmxOpenDisplay(DMXScreenInfo *dmxScreen) -{ - if (!(dmxScreen->beDisplay = XOpenDisplay(dmxScreen->name))) - return FALSE; - - dmxPropertyDisplay(dmxScreen); - return TRUE; -} - -void dmxSetErrorHandler(DMXScreenInfo *dmxScreen) -{ - XSetErrorHandler(dmxErrorHandler); -} - -static void dmxPrintScreenInfo(DMXScreenInfo *dmxScreen) -{ - XWindowAttributes attribs; - int ndepths = 0, *depths = NULL; - int i; - Display *dpy = dmxScreen->beDisplay; - Screen *s = DefaultScreenOfDisplay(dpy); - int scr = DefaultScreen(dpy); - - XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs); - if (!(depths = XListDepths(dpy, scr, &ndepths))) ndepths = 0; - - dmxLogOutput(dmxScreen, "Name of display: %s\n", DisplayString(dpy)); - dmxLogOutput(dmxScreen, "Version number: %d.%d\n", - ProtocolVersion(dpy), ProtocolRevision(dpy)); - dmxLogOutput(dmxScreen, "Vendor string: %s\n", ServerVendor(dpy)); - if (!strstr(ServerVendor(dpy), "XFree86")) { - dmxLogOutput(dmxScreen, "Vendor release: %d\n", VendorRelease(dpy)); - } else { - /* This code based on xdpyinfo.c */ - int v = VendorRelease(dpy); - int major = -1, minor = -1, patch = -1, subpatch = -1; - - if (v < 336) - major = v / 100, minor = (v / 10) % 10, patch = v % 10; - else if (v < 3900) { - major = v / 1000; - minor = (v / 100) % 10; - if (((v / 10) % 10) || (v % 10)) { - patch = (v / 10) % 10; - if (v % 10) subpatch = v % 10; - } - } else if (v < 40000000) { - major = v / 1000; - minor = (v / 10) % 10; - if (v % 10) patch = v % 10; - } else { - major = v / 10000000; - minor = (v / 100000) % 100; - patch = (v / 1000) % 100; - if (v % 1000) subpatch = v % 1000; - } - dmxLogOutput(dmxScreen, "Vendor release: %d (XFree86 version: %d.%d", - v, major, minor); - if (patch > 0) dmxLogOutputCont(dmxScreen, ".%d", patch); - if (subpatch > 0) dmxLogOutputCont(dmxScreen, ".%d", subpatch); - dmxLogOutputCont(dmxScreen, ")\n"); - } - - - dmxLogOutput(dmxScreen, "Dimensions: %dx%d pixels\n", - attribs.width, attribs.height); - dmxLogOutput(dmxScreen, "%d depths on screen %d: ", ndepths, scr); - for (i = 0; i < ndepths; i++) - dmxLogOutputCont(dmxScreen, "%c%d", i ? ',' : ' ', depths[i]); - dmxLogOutputCont(dmxScreen, "\n"); - dmxLogOutput(dmxScreen, "Depth of root window: %d plane%s (%d)\n", - attribs.depth, attribs.depth == 1 ? "" : "s", - DisplayPlanes(dpy, scr)); - dmxLogOutput(dmxScreen, "Number of colormaps: %d min, %d max\n", - MinCmapsOfScreen(s), MaxCmapsOfScreen(s)); - dmxLogOutput(dmxScreen, "Options: backing-store %s, save-unders %s\n", - (DoesBackingStore (s) == NotUseful) ? "no" : - ((DoesBackingStore (s) == Always) ? "yes" : "when mapped"), - DoesSaveUnders (s) ? "yes" : "no"); - dmxLogOutput(dmxScreen, "Window Manager running: %s\n", - (dmxScreen->WMRunningOnBE) ? "yes" : "no"); - - if (dmxScreen->WMRunningOnBE) { - dmxLogOutputWarning(dmxScreen, - "Window manager running " - "-- colormaps not supported\n"); - } - XFree(depths); -} - -void dmxGetScreenAttribs(DMXScreenInfo *dmxScreen) -{ - XWindowAttributes attribs; - Display *dpy = dmxScreen->beDisplay; -#ifdef GLXEXT - int dummy; -#endif - - XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs); - - dmxScreen->beWidth = attribs.width; - dmxScreen->beHeight = attribs.height; - - /* Fill in missing geometry information */ - if (dmxScreen->scrnXSign < 0) { - if (dmxScreen->scrnWidth) { - dmxScreen->scrnX = (attribs.width - dmxScreen->scrnWidth - - dmxScreen->scrnX); - } else { - dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX; - dmxScreen->scrnX = 0; - } - } - if (dmxScreen->scrnYSign < 0) { - if (dmxScreen->scrnHeight) { - dmxScreen->scrnY = (attribs.height - dmxScreen->scrnHeight - - dmxScreen->scrnY); - } else { - dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY; - dmxScreen->scrnY = 0; - } - } - if (!dmxScreen->scrnWidth) - dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX; - if (!dmxScreen->scrnHeight) - dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY; - - if (!dmxScreen->rootWidth) dmxScreen->rootWidth = dmxScreen->scrnWidth; - if (!dmxScreen->rootHeight) dmxScreen->rootHeight = dmxScreen->scrnHeight; - if (dmxScreen->rootWidth + dmxScreen->rootX > dmxScreen->scrnWidth) - dmxScreen->rootWidth = dmxScreen->scrnWidth - dmxScreen->rootX; - if (dmxScreen->rootHeight + dmxScreen->rootY > dmxScreen->scrnHeight) - dmxScreen->rootHeight = dmxScreen->scrnHeight - dmxScreen->rootY; - - /* FIXME: Get these from the back-end server */ - dmxScreen->beXDPI = 75; - dmxScreen->beYDPI = 75; - - dmxScreen->beDepth = attribs.depth; /* FIXME: verify that this - * works always. In - * particular, this will work - * well for depth=16, will fail - * because of colormap issues - * at depth 8. More work needs - * to be done here. */ - - if (dmxScreen->beDepth <= 8) dmxScreen->beBPP = 8; - else if (dmxScreen->beDepth <= 16) dmxScreen->beBPP = 16; - else dmxScreen->beBPP = 32; - -#ifdef GLXEXT - /* get the majorOpcode for the back-end GLX extension */ - XQueryExtension(dpy, "GLX", &dmxScreen->glxMajorOpcode, - &dummy, &dmxScreen->glxErrorBase); -#endif - - dmxPrintScreenInfo(dmxScreen); - dmxLogOutput(dmxScreen, "%dx%d+%d+%d on %dx%d at depth=%d, bpp=%d\n", - dmxScreen->scrnWidth, dmxScreen->scrnHeight, - dmxScreen->scrnX, dmxScreen->scrnY, - dmxScreen->beWidth, dmxScreen->beHeight, - dmxScreen->beDepth, dmxScreen->beBPP); - if (dmxScreen->beDepth == 8) - dmxLogOutputWarning(dmxScreen, - "Support for depth == 8 is not complete\n"); -} - -Bool dmxGetVisualInfo(DMXScreenInfo *dmxScreen) -{ - int i; - XVisualInfo visinfo; - - visinfo.screen = DefaultScreen(dmxScreen->beDisplay); - dmxScreen->beVisuals = XGetVisualInfo(dmxScreen->beDisplay, - VisualScreenMask, - &visinfo, - &dmxScreen->beNumVisuals); - - dmxScreen->beDefVisualIndex = -1; - - if (defaultColorVisualClass >= 0 || dmxDepth > 0) { - for (i = 0; i < dmxScreen->beNumVisuals; i++) - if (defaultColorVisualClass >= 0) { - if (dmxScreen->beVisuals[i].class == defaultColorVisualClass) { - if (dmxDepth > 0) { - if (dmxScreen->beVisuals[i].depth == dmxDepth) { - dmxScreen->beDefVisualIndex = i; - break; - } - } else { - dmxScreen->beDefVisualIndex = i; - break; - } - } - } else if (dmxScreen->beVisuals[i].depth == dmxDepth) { - dmxScreen->beDefVisualIndex = i; - break; - } - } else { - visinfo.visualid = - XVisualIDFromVisual(DefaultVisual(dmxScreen->beDisplay, - visinfo.screen)); - - for (i = 0; i < dmxScreen->beNumVisuals; i++) - if (visinfo.visualid == dmxScreen->beVisuals[i].visualid) { - dmxScreen->beDefVisualIndex = i; - break; - } - } - - for (i = 0; i < dmxScreen->beNumVisuals; i++) - dmxLogVisual(dmxScreen, &dmxScreen->beVisuals[i], - (i == dmxScreen->beDefVisualIndex)); - - return (dmxScreen->beDefVisualIndex >= 0); -} - -void dmxGetColormaps(DMXScreenInfo *dmxScreen) -{ - int i; - - dmxScreen->beNumDefColormaps = dmxScreen->beNumVisuals; - dmxScreen->beDefColormaps = xalloc(dmxScreen->beNumDefColormaps * - sizeof(*dmxScreen->beDefColormaps)); - - for (i = 0; i < dmxScreen->beNumDefColormaps; i++) - dmxScreen->beDefColormaps[i] = - XCreateColormap(dmxScreen->beDisplay, - DefaultRootWindow(dmxScreen->beDisplay), - dmxScreen->beVisuals[i].visual, - AllocNone); - - dmxScreen->beBlackPixel = BlackPixel(dmxScreen->beDisplay, - DefaultScreen(dmxScreen->beDisplay)); - dmxScreen->beWhitePixel = WhitePixel(dmxScreen->beDisplay, - DefaultScreen(dmxScreen->beDisplay)); -} - -void dmxGetPixmapFormats(DMXScreenInfo *dmxScreen) -{ - dmxScreen->beDepths = - XListDepths(dmxScreen->beDisplay, DefaultScreen(dmxScreen->beDisplay), - &dmxScreen->beNumDepths); - - dmxScreen->bePixmapFormats = - XListPixmapFormats(dmxScreen->beDisplay, - &dmxScreen->beNumPixmapFormats); -} - -static Bool dmxSetPixmapFormats(ScreenInfo *pScreenInfo, - DMXScreenInfo *dmxScreen) -{ - XPixmapFormatValues *bePixmapFormat; - PixmapFormatRec *format; - int i, j; - - pScreenInfo->imageByteOrder = ImageByteOrder(dmxScreen->beDisplay); - pScreenInfo->bitmapScanlineUnit = BitmapUnit(dmxScreen->beDisplay); - pScreenInfo->bitmapScanlinePad = BitmapPad(dmxScreen->beDisplay); - pScreenInfo->bitmapBitOrder = BitmapBitOrder(dmxScreen->beDisplay); - - pScreenInfo->numPixmapFormats = 0; - for (i = 0; i < dmxScreen->beNumPixmapFormats; i++) { - bePixmapFormat = &dmxScreen->bePixmapFormats[i]; - for (j = 0; j < dmxScreen->beNumDepths; j++) - if ((bePixmapFormat->depth == 1) || - (bePixmapFormat->depth == dmxScreen->beDepths[j])) { - format = &pScreenInfo->formats[pScreenInfo->numPixmapFormats]; - - format->depth = bePixmapFormat->depth; - format->bitsPerPixel = bePixmapFormat->bits_per_pixel; - format->scanlinePad = bePixmapFormat->scanline_pad; - - pScreenInfo->numPixmapFormats++; - break; - } - } - - return TRUE; -} - -void dmxCheckForWM(DMXScreenInfo *dmxScreen) -{ - Status status; - XWindowAttributes xwa; - - status = XGetWindowAttributes(dmxScreen->beDisplay, - DefaultRootWindow(dmxScreen->beDisplay), - &xwa); - dmxScreen->WMRunningOnBE = - (status && - ((xwa.all_event_masks & SubstructureRedirectMask) || - (xwa.all_event_masks & SubstructureNotifyMask))); -} - -/** Initialize the display and collect relevant information about the - * display properties */ -static void dmxDisplayInit(DMXScreenInfo *dmxScreen) -{ - if (!dmxOpenDisplay(dmxScreen)) - dmxLog(dmxFatal, - "dmxOpenDisplay: Unable to open display %s\n", - dmxScreen->name); - - dmxSetErrorHandler(dmxScreen); - dmxCheckForWM(dmxScreen); - dmxGetScreenAttribs(dmxScreen); - - if (!dmxGetVisualInfo(dmxScreen)) - dmxLog(dmxFatal, "dmxGetVisualInfo: No matching visuals found\n"); - - dmxGetColormaps(dmxScreen); - dmxGetPixmapFormats(dmxScreen); -} - -/* If this doesn't compile, just add || defined(yoursystem) to the line - * below. This information is to help with bug reports and is not - * critical. */ -#if !defined(_POSIX_SOURCE) -static const char *dmxExecOS(void) { return ""; } -#else -#include <sys/utsname.h> -static const char *dmxExecOS(void) -{ - static char buffer[128]; - static int initialized = 0; - struct utsname u; - - if (!initialized++) { - memset(buffer, 0, sizeof(buffer)); - uname(&u); - XmuSnprintf(buffer, sizeof(buffer)-1, "%s %s %s", - u.sysname, u.release, u.version); - } - return buffer; -} -#endif - -static const char *dmxBuildCompiler(void) -{ - static char buffer[128]; - static int initialized = 0; - - if (!initialized++) { - memset(buffer, 0, sizeof(buffer)); -#if defined(__GNUC__) && defined(__GNUC_MINOR__) &&defined(__GNUC_PATCHLEVEL__) - XmuSnprintf(buffer, sizeof(buffer)-1, "gcc %d.%d.%d", - __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); -#endif - } - return buffer; -} - -static const char *dmxExecHost(void) -{ - static char buffer[128]; - static int initialized = 0; - - if (!initialized++) { - memset(buffer, 0, sizeof(buffer)); - XmuGetHostname(buffer, sizeof(buffer) - 1); - } - return buffer; -} - -/** This routine is called in Xserver/dix/main.c from \a main(). */ -void InitOutput(ScreenInfo *pScreenInfo, int argc, char *argv[]) -{ - int i; - static unsigned long dmxGeneration = 0; -#ifdef GLXEXT - Bool glxSupported = TRUE; -#endif - - if (dmxGeneration != serverGeneration) { - int vendrel = VENDOR_RELEASE; - int major, minor, year, month, day; - - dmxGeneration = serverGeneration; - - major = vendrel / 100000000; - vendrel -= major * 100000000; - minor = vendrel / 1000000; - vendrel -= minor * 1000000; - year = vendrel / 10000; - vendrel -= year * 10000; - month = vendrel / 100; - vendrel -= month * 100; - day = vendrel; - - /* Add other epoch tests here */ - if (major > 0 && minor > 0) year += 2000; - - dmxLog(dmxInfo, "Generation: %d\n", dmxGeneration); - dmxLog(dmxInfo, "DMX version: %d.%d.%02d%02d%02d (%s)\n", - major, minor, year, month, day, VENDOR_STRING); - - SetVendorRelease(VENDOR_RELEASE); - SetVendorString(VENDOR_STRING); - - if (dmxGeneration == 1) { - dmxLog(dmxInfo, "DMX Build OS: %s (%s)\n", OSNAME, OSVENDOR); - dmxLog(dmxInfo, "DMX Build Compiler: %s\n", dmxBuildCompiler()); - dmxLog(dmxInfo, "DMX Execution OS: %s\n", dmxExecOS()); - dmxLog(dmxInfo, "DMX Execution Host: %s\n", dmxExecHost()); - } - dmxLog(dmxInfo, "MAXSCREENS: %d\n", MAXSCREENS); - - for (i = 0; i < dmxNumScreens; i++) { - if (dmxScreens[i].beDisplay) - dmxLog(dmxWarning, "Display \"%s\" still open\n", - dmxScreens[i].name); - dmxStatFree(dmxScreens[i].stat); - dmxScreens[i].stat = NULL; - } - for (i = 0; i < dmxNumInputs; i++) dmxInputFree(&dmxInputs[i]); - if (dmxScreens) free(dmxScreens); - if (dmxInputs) free(dmxInputs); - dmxScreens = NULL; - dmxInputs = NULL; - dmxNumScreens = 0; - dmxNumInputs = 0; - } - - /* Make sure that the command-line arguments are sane. */ - if (dmxAddRemoveScreens && dmxGLXProxy) { - /* Currently it is not possible to support GLX and Render - * extensions with dynamic screen addition/removal due to the - * state that each extension keeps, which cannot be restored. */ - dmxLog(dmxWarning, - "GLX Proxy and Render extensions do not yet support dynamic\n"); - dmxLog(dmxWarning, - "screen addition and removal. Please specify -noglxproxy\n"); - dmxLog(dmxWarning, - "and -norender on the command line or in the configuration\n"); - dmxLog(dmxWarning, - "file to disable these two extensions if you wish to use\n"); - dmxLog(dmxWarning, - "the dynamic addition and removal of screens support.\n"); - dmxLog(dmxFatal, - "Dynamic screen addition/removal error (see above).\n"); - } - - /* ddxProcessArgument has been called at this point, but any data - * from the configuration file has not been applied. Do so, and be - * sure we have at least one back-end display. */ - dmxConfigConfigure(); - if (!dmxNumScreens) - dmxLog(dmxFatal, "InitOutput: no back-end displays found\n"); - if (!dmxNumInputs) - dmxLog(dmxInfo, "InitOutput: no inputs found\n"); - - /* Disable lazy window creation optimization if offscreen - * optimization is disabled */ - if (!dmxOffScreenOpt && dmxLazyWindowCreation) { - dmxLog(dmxInfo, - "InitOutput: Disabling lazy window creation optimization\n"); - dmxLog(dmxInfo, - " since it requires the offscreen optimization\n"); - dmxLog(dmxInfo, - " to function properly.\n"); - dmxLazyWindowCreation = FALSE; - } - - /* Open each display and gather information about it. */ - for (i = 0; i < dmxNumScreens; i++) - dmxDisplayInit(&dmxScreens[i]); - -#if PANORAMIX - /* Register a Xinerama callback which will run from within - * PanoramiXCreateConnectionBlock. We can use the callback to - * determine if Xinerama is loaded and to check the visuals - * determined by PanoramiXConsolidate. */ - XineramaRegisterConnectionBlockCallback(dmxConnectionBlockCallback); -#endif - - /* Since we only have a single screen thus far, we only need to set - the pixmap formats to match that screen. FIXME: this isn't true.*/ - if (!dmxSetPixmapFormats(pScreenInfo, &dmxScreens[0])) return; - - /* Might want to install a signal handler to allow cleaning up after - * unexpected signals. The DIX/OS layer already handles SIGINT and - * SIGTERM, so everything is OK for expected signals. --DD - * - * SIGHUP, SIGINT, and SIGTERM are trapped in os/connection.c - * SIGQUIT is another common signal that is sent from the keyboard. - * Trap it here, to ensure that the keyboard modifier map and other - * state for the input devices are restored. (This makes the - * behavior of SIGQUIT somewhat unexpected, since it will be the - * same as the behavior of SIGINT. However, leaving the modifier - * map of the input devices empty is even more unexpected.) --RF - */ - OsSignal(SIGQUIT, GiveUp); - -#ifdef GLXEXT - /* Check if GLX extension exists on all back-end servers */ - for (i = 0; i < dmxNumScreens; i++) - glxSupported &= (dmxScreens[i].glxMajorOpcode > 0); -#endif - - /* Tell dix layer about the backend displays */ - for (i = 0; i < dmxNumScreens; i++) { - -#ifdef GLXEXT - if (glxSupported) { - /* - * Builds GLX configurations from the list of visuals - * supported by the back-end server, and give that - * configuration list to the glx layer - so that he will - * build the visuals accordingly. - */ - - DMXScreenInfo *dmxScreen = &dmxScreens[i]; - __GLXvisualConfig *configs = NULL; - dmxGlxVisualPrivate **configprivs = NULL; - int nconfigs = 0; - int (*oldErrorHandler)(Display *, XErrorEvent *); - int i; - - /* Catch errors if when using an older GLX w/o FBconfigs */ - oldErrorHandler = XSetErrorHandler(dmxNOPErrorHandler); - - /* Get FBConfigs of the back-end server */ - dmxScreen->fbconfigs = GetGLXFBConfigs(dmxScreen->beDisplay, - dmxScreen->glxMajorOpcode, - &dmxScreen->numFBConfigs); - - XSetErrorHandler(oldErrorHandler); - - dmxScreen->glxVisuals = - GetGLXVisualConfigs(dmxScreen->beDisplay, - DefaultScreen(dmxScreen->beDisplay), - &dmxScreen->numGlxVisuals); - - if (dmxScreen->fbconfigs) { - configs = - GetGLXVisualConfigsFromFBConfigs(dmxScreen->fbconfigs, - dmxScreen->numFBConfigs, - dmxScreen->beVisuals, - dmxScreen->beNumVisuals, - dmxScreen->glxVisuals, - dmxScreen->numGlxVisuals, - &nconfigs); - } else { - configs = dmxScreen->glxVisuals; - nconfigs = dmxScreen->numGlxVisuals; - } - - configprivs = xalloc(nconfigs * sizeof(dmxGlxVisualPrivate*)); - - if (configs != NULL && configprivs != NULL) { - - /* Initialize our private info for each visual - * (currently only x_visual_depth and x_visual_class) - */ - for (i = 0; i < nconfigs; i++) { - - configprivs[i] = (dmxGlxVisualPrivate *) - xalloc(sizeof(dmxGlxVisualPrivate)); - configprivs[i]->x_visual_depth = 0; - configprivs[i]->x_visual_class = 0; - - /* Find the visual depth */ - if (configs[i].vid > 0) { - int j; - for (j = 0; j < dmxScreen->beNumVisuals; j++) { - if (dmxScreen->beVisuals[j].visualid == - configs[i].vid) { - configprivs[i]->x_visual_depth = - dmxScreen->beVisuals[j].depth; - configprivs[i]->x_visual_class = - dmxScreen->beVisuals[j].class; - break; - } - } - } - } - - /* Hand out the glx configs to glx extension */ - GlxSetVisualConfigs(nconfigs, configs, (void**)configprivs); - - XFlush(dmxScreen->beDisplay); - } - } -#endif /* GLXEXT */ - - AddScreen(dmxScreenInit, argc, argv); - } - - /* Compute origin information. */ - dmxInitOrigins(); - - /* Compute overlap information. */ - dmxInitOverlap(); - - /* Make sure there is a global width/height available */ - dmxComputeWidthHeight(DMX_NO_RECOMPUTE_BOUNDING_BOX); - - /* FIXME: The following is temporarily placed here. When the DMX - * extension is available, it will be move there. - */ - dmxInitFonts(); - -#ifdef RENDER - /* Initialize the render extension */ - if (!noRenderExtension) - dmxInitRender(); -#endif - - /* Initialized things that need timer hooks */ - dmxStatInit(); - dmxSyncInit(); /* Calls RegisterBlockAndWakeupHandlers */ - - dmxLog(dmxInfo, "Shadow framebuffer support %s\n", - dmxShadowFB ? "enabled" : "disabled"); -} - -/* RATS: Assuming the fp string (which comes from the command-line argv - vector) is NULL-terminated, the buffer is large enough for the - strcpy. */ -static void dmxSetDefaultFontPath(char *fp) -{ - int fplen = strlen(fp) + 1; - - if (dmxFontPath) { - int len; - - len = strlen(dmxFontPath); - dmxFontPath = xrealloc(dmxFontPath, len+fplen+1); - dmxFontPath[len] = ','; - strncpy(&dmxFontPath[len+1], fp, fplen); - } else { - dmxFontPath = xalloc(fplen); - strncpy(dmxFontPath, fp, fplen); - } - - defaultFontPath = dmxFontPath; -} - -/** This function is called in Xserver/os/utils.c from \a AbortServer(). - * We must ensure that backend and console state is restored in the - * event the server shutdown wasn't clean. */ -void AbortDDX(void) -{ - int i; - - for (i=0; i < dmxNumScreens; i++) { - DMXScreenInfo *dmxScreen = &dmxScreens[i]; - - if (dmxScreen->beDisplay) XCloseDisplay(dmxScreen->beDisplay); - dmxScreen->beDisplay = NULL; - } -} - -/** This function is called in Xserver/dix/main.c from \a main() when - * dispatchException & DE_TERMINATE (which is the only way to exit the - * main loop without an interruption. */ -void ddxGiveUp(void) -{ - AbortDDX(); -} - -/** This function is called in Xserver/os/osinit.c from \a OsInit(). */ -void OsVendorInit(void) -{ -} - -/** This function is called in Xserver/os/utils.c from \a FatalError() - * and \a VFatalError(). (Note that setting the function pointer \a - * OsVendorVErrorFProc will cause \a VErrorF() (which is called by the - * two routines mentioned here, as well as by others) to use the - * referenced routine instead of \a vfprintf().) */ -void OsVendorFatalError(void) -{ -} - -/** Process our command line arguments. */ -int ddxProcessArgument(int argc, char *argv[], int i) -{ - int retval = 0; - - if (!strcmp(argv[i], "-display")) { - if (++i < argc) dmxConfigStoreDisplay(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-inputfrom") || !strcmp(argv[i], "-input")) { - if (++i < argc) dmxConfigStoreInput(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-xinputfrom") || !strcmp(argv[i],"-xinput")) { - if (++i < argc) dmxConfigStoreXInput(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-noshadowfb")) { - dmxLog(dmxWarning, - "-noshadowfb has been deprecated " - "since it is now the default\n"); - dmxShadowFB = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-nomulticursor")) { - dmxCursorNoMulti(); - retval = 1; - } else if (!strcmp(argv[i], "-shadowfb")) { - dmxShadowFB = TRUE; - retval = 1; - } else if (!strcmp(argv[i], "-configfile")) { - if (++i < argc) dmxConfigStoreFile(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-config")) { - if (++i < argc) dmxConfigStoreConfig(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-fontpath")) { - if (++i < argc) dmxSetDefaultFontPath(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-stat")) { - if ((i += 2) < argc) dmxStatActivate(argv[i-1], argv[i]); - retval = 3; - } else if (!strcmp(argv[i], "-syncbatch")) { - if (++i < argc) dmxSyncActivate(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-nooffscreenopt")) { - dmxOffScreenOpt = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-nosubdivprims")) { - dmxSubdividePrimitives = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-nowindowopt")) { - dmxLazyWindowCreation = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-noxkb")) { - dmxUseXKB = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-depth")) { - if (++i < argc) dmxDepth = atoi(argv[i]); - retval = 2; - } else if (!strcmp(argv[i], "-norender")) { - noRenderExtension = TRUE; - retval = 1; -#ifdef GLXEXT - } else if (!strcmp(argv[i], "-noglxproxy")) { - dmxGLXProxy = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-noglxswapgroup")) { - dmxGLXSwapGroupSupport = FALSE; - retval = 1; - } else if (!strcmp(argv[i], "-glxsyncswap")) { - dmxGLXSyncSwap = TRUE; - retval = 1; - } else if (!strcmp(argv[i], "-glxfinishswap")) { - dmxGLXFinishSwap = TRUE; - retval = 1; -#endif - } else if (!strcmp(argv[i], "-ignorebadfontpaths")) { - dmxIgnoreBadFontPaths = TRUE; - retval = 1; - } else if (!strcmp(argv[i], "-addremovescreens")) { - dmxAddRemoveScreens = TRUE; - retval = 1; - } else if (!strcmp(argv[i], "-param")) { - if ((i += 2) < argc) { - if (!strcasecmp(argv[i-1], "xkbrules")) - dmxConfigSetXkbRules(argv[i]); - else if (!strcasecmp(argv[i-1], "xkbmodel")) - dmxConfigSetXkbModel(argv[i]); - else if (!strcasecmp(argv[i-1], "xkblayout")) - dmxConfigSetXkbLayout(argv[i]); - else if (!strcasecmp(argv[i-1], "xkbvariant")) - dmxConfigSetXkbVariant(argv[i]); - else if (!strcasecmp(argv[i-1], "xkboptions")) - dmxConfigSetXkbOptions(argv[i]); - else - dmxLog(dmxWarning, - "-param requires: XkbRules, XkbModel, XkbLayout," - " XkbVariant, or XkbOptions\n"); - } - retval = 3; - } - if (!serverGeneration) dmxConfigSetMaxScreens(); - return retval; -} - -/** Provide succinct usage information for the DMX server. */ -void ddxUseMsg(void) -{ - ErrorF("\n\nDevice Dependent Usage:\n"); - ErrorF("-display string Specify the back-end display(s)\n"); - ErrorF("-input string Specify input source for core device\n"); - ErrorF("-xinput string Specify input source for XInput device\n"); - ErrorF("-shadowfb Enable shadow frame buffer\n"); - ErrorF("-configfile file Read from a configuration file\n"); - ErrorF("-config config Select a specific configuration\n"); - ErrorF("-nomulticursor Turn of multiple cursor support\n"); - ErrorF("-fontpath Sets the default font path\n"); - ErrorF("-stat inter scrns Print out performance statistics\n"); - ErrorF("-syncbatch inter Set interval for XSync batching\n"); - ErrorF("-nooffscreenopt Disable offscreen optimization\n"); - ErrorF("-nosubdivprims Disable primitive subdivision\n"); - ErrorF(" optimization\n"); - ErrorF("-nowindowopt Disable lazy window creation optimization\n"); - ErrorF("-noxkb Disable use of the XKB extension with\n"); - ErrorF(" backend displays (cf. -kb).\n"); - ErrorF("-depth Specify the default root window depth\n"); - ErrorF("-norender Disable RENDER extension support\n"); -#ifdef GLXEXT - ErrorF("-noglxproxy Disable GLX Proxy\n"); - ErrorF("-noglxswapgroup Disable swap group and swap barrier\n"); - ErrorF(" extensions in GLX proxy\n"); - ErrorF("-glxsyncswap Force XSync after swap buffers\n"); - ErrorF("-glxfinishswap Force glFinish after swap buffers\n"); -#endif - ErrorF("-ignorebadfontpaths Ignore bad font paths during initialization\n"); - ErrorF("-addremovescreens Enable dynamic screen addition/removal\n"); - ErrorF("-param ... Specify configuration parameters (e.g.,\n"); - ErrorF(" XkbRules, XkbModel, XkbLayout, etc.)\n"); - ErrorF("\n"); - ErrorF(" If the -input string matches a -display string, then input\n" - " is taken from that backend display. (XInput cannot be taken\n" - " from a backend display.) Placing \",console\" after the\n" - " display name will force a console window to be opened on\n" - " that display in addition to the backend input. This is\n" - " useful if the backend window does not cover the whole\n" - " physical display.\n\n"); - - ErrorF(" Otherwise, if the -input or -xinput string specifies another\n" - " X display, then a console window will be created on that\n" - " display. Placing \",windows\" or \",nowindows\" after the\n" - " display name will control the display of window outlines in\n" - " the console.\n\n"); - - ErrorF(" -input or -xinput dummy specifies no input.\n"); - ErrorF(" -input or -xinput local specifies the use of a raw keyboard,\n" - " mouse, or other (extension) device:\n" - " -input local,kbd,ps2 will use a ps2 mouse\n" - " -input local,kbd,ms will use a serial mouse\n" - " -input local,usb-kbd,usb-mou will use USB devices \n" - " -xinput local,usb-oth will use a non-mouse and\n" - " non-keyboard USB device with XInput\n\n"); - - ErrorF(" Special Keys:\n"); - ErrorF(" Ctrl-Alt-g Server grab/ungrab (console only)\n"); - ErrorF(" Ctrl-Alt-f Fine (1-pixel) mouse mode (console only)\n"); - ErrorF(" Ctrl-Alt-q Quit (core devices only)\n"); - ErrorF(" Ctrl-Alt-F* Switch to VC (local only)\n"); -} +/*
+ * Copyright 2001-2004 Red Hat Inc., Durham, North Carolina.
+ *
+ * All Rights Reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation on the rights to use, copy, modify, merge,
+ * publish, distribute, sublicense, and/or sell copies of the Software,
+ * and to permit persons to whom the Software is furnished to do so,
+ * subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice (including the
+ * next paragraph) shall be included in all copies or substantial
+ * portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NON-INFRINGEMENT. IN NO EVENT SHALL RED HAT AND/OR THEIR SUPPLIERS
+ * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+ * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+/*
+ * Authors:
+ * Kevin E. Martin <kem@redhat.com>
+ * David H. Dawes <dawes@xfree86.org>
+ * Rickard E. (Rik) Faith <faith@redhat.com>
+ *
+ */
+
+/** \file
+ * Provide expected functions for initialization from the ddx layer and
+ * global variables for the DMX server. */
+
+#ifdef HAVE_DMX_CONFIG_H
+#include <dmx-config.h>
+#endif
+
+#include "dmx.h"
+#include "dmxinit.h"
+#include "dmxsync.h"
+#include "dmxlog.h"
+#include "dmxinput.h"
+#include "dmxscrinit.h"
+#include "dmxcursor.h"
+#include "dmxfont.h"
+#include "config/dmxconfig.h"
+#include "dmxcb.h"
+#include "dmxprop.h"
+#include "dmxstat.h"
+#ifdef RENDER
+#include "dmxpict.h"
+#endif
+
+#include <X11/Xos.h> /* For gettimeofday */
+#include "dixstruct.h"
+#ifdef PANORAMIX
+#include "panoramiXsrv.h"
+#endif
+
+#include <signal.h> /* For SIGQUIT */
+
+#ifdef GLXEXT
+#include <GL/glx.h>
+#include <GL/glxint.h>
+#include "dmx_glxvisuals.h"
+#include <X11/extensions/Xext.h>
+#include <X11/extensions/extutil.h>
+
+extern void GlxSetVisualConfigs(
+ int nconfigs,
+ __GLXvisualConfig *configs,
+ void **configprivs
+);
+#endif /* GLXEXT */
+
+/* Global variables available to all Xserver/hw/dmx routines. */
+int dmxNumScreens;
+DMXScreenInfo *dmxScreens;
+
+int dmxNumInputs;
+DMXInputInfo *dmxInputs;
+
+int dmxShadowFB = FALSE;
+
+XErrorEvent dmxLastErrorEvent;
+Bool dmxErrorOccurred = FALSE;
+
+char *dmxFontPath = NULL;
+
+Bool dmxOffScreenOpt = TRUE;
+
+Bool dmxSubdividePrimitives = TRUE;
+
+Bool dmxLazyWindowCreation = TRUE;
+
+Bool dmxUseXKB = TRUE;
+
+int dmxDepth = 0;
+
+#ifndef GLXEXT
+static Bool dmxGLXProxy = FALSE;
+#else
+Bool dmxGLXProxy = TRUE;
+
+Bool dmxGLXSwapGroupSupport = TRUE;
+
+Bool dmxGLXSyncSwap = FALSE;
+
+Bool dmxGLXFinishSwap = FALSE;
+#endif
+
+Bool dmxIgnoreBadFontPaths = FALSE;
+
+Bool dmxAddRemoveScreens = FALSE;
+
+/* dmxErrorHandler catches errors that occur when calling one of the
+ * back-end servers. Some of this code is based on _XPrintDefaultError
+ * in xc/lib/X11/XlibInt.c */
+static int dmxErrorHandler(Display *dpy, XErrorEvent *ev)
+{
+#define DMX_ERROR_BUF_SIZE 256
+ /* RATS: these buffers are only used in
+ * length-limited calls. */
+ char buf[DMX_ERROR_BUF_SIZE];
+ char request[DMX_ERROR_BUF_SIZE];
+ _XExtension *ext = NULL;
+
+ dmxErrorOccurred = TRUE;
+ dmxLastErrorEvent = *ev;
+
+ XGetErrorText(dpy, ev->error_code, buf, sizeof(buf));
+ dmxLog(dmxWarning, "dmxErrorHandler: %s\n", buf);
+
+ /* Find major opcode name */
+ if (ev->request_code < 128) {
+ XmuSnprintf(request, sizeof(request), "%d", ev->request_code);
+ XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf));
+ } else {
+ for (ext = dpy->ext_procs;
+ ext && ext->codes.major_opcode != ev->request_code;
+ ext = ext->next);
+ if (ext) strncpy(buf, ext->name, sizeof(buf));
+ else buf[0] = '\0';
+ }
+ dmxLog(dmxWarning, " Major opcode: %d (%s)\n",
+ ev->request_code, buf);
+
+ /* Find minor opcode name */
+ if (ev->request_code >= 128 && ext) {
+ XmuSnprintf(request, sizeof(request), "%d", ev->request_code);
+ XmuSnprintf(request, sizeof(request), "%s.%d",
+ ext->name, ev->minor_code);
+ XGetErrorDatabaseText(dpy, "XRequest", request, "", buf, sizeof(buf));
+ dmxLog(dmxWarning, " Minor opcode: %d (%s)\n",
+ ev->minor_code, buf);
+ }
+
+ /* Provide value information */
+ switch (ev->error_code) {
+ case BadValue:
+ dmxLog(dmxWarning, " Value: 0x%x\n",
+ ev->resourceid);
+ break;
+ case BadAtom:
+ dmxLog(dmxWarning, " AtomID: 0x%x\n",
+ ev->resourceid);
+ break;
+ default:
+ dmxLog(dmxWarning, " ResourceID: 0x%x\n",
+ ev->resourceid);
+ break;
+ }
+
+ /* Provide serial number information */
+ dmxLog(dmxWarning, " Failed serial number: %d\n",
+ ev->serial);
+ dmxLog(dmxWarning, " Current serial number: %d\n",
+ dpy->request);
+ return 0;
+}
+
+#ifdef GLXEXT
+static int dmxNOPErrorHandler(Display *dpy, XErrorEvent *ev)
+{
+ return 0;
+}
+#endif
+
+Bool dmxOpenDisplay(DMXScreenInfo *dmxScreen)
+{
+ if (!(dmxScreen->beDisplay = XOpenDisplay(dmxScreen->name)))
+ return FALSE;
+
+ dmxPropertyDisplay(dmxScreen);
+ return TRUE;
+}
+
+void dmxSetErrorHandler(DMXScreenInfo *dmxScreen)
+{
+ XSetErrorHandler(dmxErrorHandler);
+}
+
+static void dmxPrintScreenInfo(DMXScreenInfo *dmxScreen)
+{
+ XWindowAttributes attribs;
+ int ndepths = 0, *depths = NULL;
+ int i;
+ Display *dpy = dmxScreen->beDisplay;
+ Screen *s = DefaultScreenOfDisplay(dpy);
+ int scr = DefaultScreen(dpy);
+
+ XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs);
+ if (!(depths = XListDepths(dpy, scr, &ndepths))) ndepths = 0;
+
+ dmxLogOutput(dmxScreen, "Name of display: %s\n", DisplayString(dpy));
+ dmxLogOutput(dmxScreen, "Version number: %d.%d\n",
+ ProtocolVersion(dpy), ProtocolRevision(dpy));
+ dmxLogOutput(dmxScreen, "Vendor string: %s\n", ServerVendor(dpy));
+ if (!strstr(ServerVendor(dpy), "XFree86")) {
+ dmxLogOutput(dmxScreen, "Vendor release: %d\n", VendorRelease(dpy));
+ } else {
+ /* This code based on xdpyinfo.c */
+ int v = VendorRelease(dpy);
+ int major = -1, minor = -1, patch = -1, subpatch = -1;
+
+ if (v < 336)
+ major = v / 100, minor = (v / 10) % 10, patch = v % 10;
+ else if (v < 3900) {
+ major = v / 1000;
+ minor = (v / 100) % 10;
+ if (((v / 10) % 10) || (v % 10)) {
+ patch = (v / 10) % 10;
+ if (v % 10) subpatch = v % 10;
+ }
+ } else if (v < 40000000) {
+ major = v / 1000;
+ minor = (v / 10) % 10;
+ if (v % 10) patch = v % 10;
+ } else {
+ major = v / 10000000;
+ minor = (v / 100000) % 100;
+ patch = (v / 1000) % 100;
+ if (v % 1000) subpatch = v % 1000;
+ }
+ dmxLogOutput(dmxScreen, "Vendor release: %d (XFree86 version: %d.%d",
+ v, major, minor);
+ if (patch > 0) dmxLogOutputCont(dmxScreen, ".%d", patch);
+ if (subpatch > 0) dmxLogOutputCont(dmxScreen, ".%d", subpatch);
+ dmxLogOutputCont(dmxScreen, ")\n");
+ }
+
+
+ dmxLogOutput(dmxScreen, "Dimensions: %dx%d pixels\n",
+ attribs.width, attribs.height);
+ dmxLogOutput(dmxScreen, "%d depths on screen %d: ", ndepths, scr);
+ for (i = 0; i < ndepths; i++)
+ dmxLogOutputCont(dmxScreen, "%c%d", i ? ',' : ' ', depths[i]);
+ dmxLogOutputCont(dmxScreen, "\n");
+ dmxLogOutput(dmxScreen, "Depth of root window: %d plane%s (%d)\n",
+ attribs.depth, attribs.depth == 1 ? "" : "s",
+ DisplayPlanes(dpy, scr));
+ dmxLogOutput(dmxScreen, "Number of colormaps: %d min, %d max\n",
+ MinCmapsOfScreen(s), MaxCmapsOfScreen(s));
+ dmxLogOutput(dmxScreen, "Options: backing-store %s, save-unders %s\n",
+ (DoesBackingStore (s) == NotUseful) ? "no" :
+ ((DoesBackingStore (s) == Always) ? "yes" : "when mapped"),
+ DoesSaveUnders (s) ? "yes" : "no");
+ dmxLogOutput(dmxScreen, "Window Manager running: %s\n",
+ (dmxScreen->WMRunningOnBE) ? "yes" : "no");
+
+ if (dmxScreen->WMRunningOnBE) {
+ dmxLogOutputWarning(dmxScreen,
+ "Window manager running "
+ "-- colormaps not supported\n");
+ }
+ XFree(depths);
+}
+
+void dmxGetScreenAttribs(DMXScreenInfo *dmxScreen)
+{
+ XWindowAttributes attribs;
+ Display *dpy = dmxScreen->beDisplay;
+#ifdef GLXEXT
+ int dummy;
+#endif
+
+ XGetWindowAttributes(dpy, DefaultRootWindow(dpy), &attribs);
+
+ dmxScreen->beWidth = attribs.width;
+ dmxScreen->beHeight = attribs.height;
+
+ /* Fill in missing geometry information */
+ if (dmxScreen->scrnXSign < 0) {
+ if (dmxScreen->scrnWidth) {
+ dmxScreen->scrnX = (attribs.width - dmxScreen->scrnWidth
+ - dmxScreen->scrnX);
+ } else {
+ dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX;
+ dmxScreen->scrnX = 0;
+ }
+ }
+ if (dmxScreen->scrnYSign < 0) {
+ if (dmxScreen->scrnHeight) {
+ dmxScreen->scrnY = (attribs.height - dmxScreen->scrnHeight
+ - dmxScreen->scrnY);
+ } else {
+ dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY;
+ dmxScreen->scrnY = 0;
+ }
+ }
+ if (!dmxScreen->scrnWidth)
+ dmxScreen->scrnWidth = attribs.width - dmxScreen->scrnX;
+ if (!dmxScreen->scrnHeight)
+ dmxScreen->scrnHeight = attribs.height - dmxScreen->scrnY;
+
+ if (!dmxScreen->rootWidth) dmxScreen->rootWidth = dmxScreen->scrnWidth;
+ if (!dmxScreen->rootHeight) dmxScreen->rootHeight = dmxScreen->scrnHeight;
+ if (dmxScreen->rootWidth + dmxScreen->rootX > dmxScreen->scrnWidth)
+ dmxScreen->rootWidth = dmxScreen->scrnWidth - dmxScreen->rootX;
+ if (dmxScreen->rootHeight + dmxScreen->rootY > dmxScreen->scrnHeight)
+ dmxScreen->rootHeight = dmxScreen->scrnHeight - dmxScreen->rootY;
+
+ /* FIXME: Get these from the back-end server */
+ dmxScreen->beXDPI = 75;
+ dmxScreen->beYDPI = 75;
+
+ dmxScreen->beDepth = attribs.depth; /* FIXME: verify that this
+ * works always. In
+ * particular, this will work
+ * well for depth=16, will fail
+ * because of colormap issues
+ * at depth 8. More work needs
+ * to be done here. */
+
+ if (dmxScreen->beDepth <= 8) dmxScreen->beBPP = 8;
+ else if (dmxScreen->beDepth <= 16) dmxScreen->beBPP = 16;
+ else dmxScreen->beBPP = 32;
+
+#ifdef GLXEXT
+ /* get the majorOpcode for the back-end GLX extension */
+ XQueryExtension(dpy, "GLX", &dmxScreen->glxMajorOpcode,
+ &dummy, &dmxScreen->glxErrorBase);
+#endif
+
+ dmxPrintScreenInfo(dmxScreen);
+ dmxLogOutput(dmxScreen, "%dx%d+%d+%d on %dx%d at depth=%d, bpp=%d\n",
+ dmxScreen->scrnWidth, dmxScreen->scrnHeight,
+ dmxScreen->scrnX, dmxScreen->scrnY,
+ dmxScreen->beWidth, dmxScreen->beHeight,
+ dmxScreen->beDepth, dmxScreen->beBPP);
+ if (dmxScreen->beDepth == 8)
+ dmxLogOutputWarning(dmxScreen,
+ "Support for depth == 8 is not complete\n");
+}
+
+Bool dmxGetVisualInfo(DMXScreenInfo *dmxScreen)
+{
+ int i;
+ XVisualInfo visinfo;
+
+ visinfo.screen = DefaultScreen(dmxScreen->beDisplay);
+ dmxScreen->beVisuals = XGetVisualInfo(dmxScreen->beDisplay,
+ VisualScreenMask,
+ &visinfo,
+ &dmxScreen->beNumVisuals);
+
+ dmxScreen->beDefVisualIndex = -1;
+
+ if (defaultColorVisualClass >= 0 || dmxDepth > 0) {
+ for (i = 0; i < dmxScreen->beNumVisuals; i++)
+ if (defaultColorVisualClass >= 0) {
+ if (dmxScreen->beVisuals[i].class == defaultColorVisualClass) {
+ if (dmxDepth > 0) {
+ if (dmxScreen->beVisuals[i].depth == dmxDepth) {
+ dmxScreen->beDefVisualIndex = i;
+ break;
+ }
+ } else {
+ dmxScreen->beDefVisualIndex = i;
+ break;
+ }
+ }
+ } else if (dmxScreen->beVisuals[i].depth == dmxDepth) {
+ dmxScreen->beDefVisualIndex = i;
+ break;
+ }
+ } else {
+ visinfo.visualid =
+ XVisualIDFromVisual(DefaultVisual(dmxScreen->beDisplay,
+ visinfo.screen));
+
+ for (i = 0; i < dmxScreen->beNumVisuals; i++)
+ if (visinfo.visualid == dmxScreen->beVisuals[i].visualid) {
+ dmxScreen->beDefVisualIndex = i;
+ break;
+ }
+ }
+
+ for (i = 0; i < dmxScreen->beNumVisuals; i++)
+ dmxLogVisual(dmxScreen, &dmxScreen->beVisuals[i],
+ (i == dmxScreen->beDefVisualIndex));
+
+ return (dmxScreen->beDefVisualIndex >= 0);
+}
+
+void dmxGetColormaps(DMXScreenInfo *dmxScreen)
+{
+ int i;
+
+ dmxScreen->beNumDefColormaps = dmxScreen->beNumVisuals;
+ dmxScreen->beDefColormaps = xalloc(dmxScreen->beNumDefColormaps *
+ sizeof(*dmxScreen->beDefColormaps));
+
+ for (i = 0; i < dmxScreen->beNumDefColormaps; i++)
+ dmxScreen->beDefColormaps[i] =
+ XCreateColormap(dmxScreen->beDisplay,
+ DefaultRootWindow(dmxScreen->beDisplay),
+ dmxScreen->beVisuals[i].visual,
+ AllocNone);
+
+ dmxScreen->beBlackPixel = BlackPixel(dmxScreen->beDisplay,
+ DefaultScreen(dmxScreen->beDisplay));
+ dmxScreen->beWhitePixel = WhitePixel(dmxScreen->beDisplay,
+ DefaultScreen(dmxScreen->beDisplay));
+}
+
+void dmxGetPixmapFormats(DMXScreenInfo *dmxScreen)
+{
+ dmxScreen->beDepths =
+ XListDepths(dmxScreen->beDisplay, DefaultScreen(dmxScreen->beDisplay),
+ &dmxScreen->beNumDepths);
+
+ dmxScreen->bePixmapFormats =
+ XListPixmapFormats(dmxScreen->beDisplay,
+ &dmxScreen->beNumPixmapFormats);
+}
+
+static Bool dmxSetPixmapFormats(ScreenInfo *pScreenInfo,
+ DMXScreenInfo *dmxScreen)
+{
+ XPixmapFormatValues *bePixmapFormat;
+ PixmapFormatRec *format;
+ int i, j;
+
+ pScreenInfo->imageByteOrder = ImageByteOrder(dmxScreen->beDisplay);
+ pScreenInfo->bitmapScanlineUnit = BitmapUnit(dmxScreen->beDisplay);
+ pScreenInfo->bitmapScanlinePad = BitmapPad(dmxScreen->beDisplay);
+ pScreenInfo->bitmapBitOrder = BitmapBitOrder(dmxScreen->beDisplay);
+
+ pScreenInfo->numPixmapFormats = 0;
+ for (i = 0; i < dmxScreen->beNumPixmapFormats; i++) {
+ bePixmapFormat = &dmxScreen->bePixmapFormats[i];
+ for (j = 0; j < dmxScreen->beNumDepths; j++)
+ if ((bePixmapFormat->depth == 1) ||
+ (bePixmapFormat->depth == dmxScreen->beDepths[j])) {
+ format = &pScreenInfo->formats[pScreenInfo->numPixmapFormats];
+
+ format->depth = bePixmapFormat->depth;
+ format->bitsPerPixel = bePixmapFormat->bits_per_pixel;
+ format->scanlinePad = bePixmapFormat->scanline_pad;
+
+ pScreenInfo->numPixmapFormats++;
+ break;
+ }
+ }
+
+ return TRUE;
+}
+
+void dmxCheckForWM(DMXScreenInfo *dmxScreen)
+{
+ Status status;
+ XWindowAttributes xwa;
+
+ status = XGetWindowAttributes(dmxScreen->beDisplay,
+ DefaultRootWindow(dmxScreen->beDisplay),
+ &xwa);
+ dmxScreen->WMRunningOnBE =
+ (status &&
+ ((xwa.all_event_masks & SubstructureRedirectMask) ||
+ (xwa.all_event_masks & SubstructureNotifyMask)));
+}
+
+/** Initialize the display and collect relevant information about the
+ * display properties */
+static void dmxDisplayInit(DMXScreenInfo *dmxScreen)
+{
+ if (!dmxOpenDisplay(dmxScreen))
+ dmxLog(dmxFatal,
+ "dmxOpenDisplay: Unable to open display %s\n",
+ dmxScreen->name);
+
+ dmxSetErrorHandler(dmxScreen);
+ dmxCheckForWM(dmxScreen);
+ dmxGetScreenAttribs(dmxScreen);
+
+ if (!dmxGetVisualInfo(dmxScreen))
+ dmxLog(dmxFatal, "dmxGetVisualInfo: No matching visuals found\n");
+
+ dmxGetColormaps(dmxScreen);
+ dmxGetPixmapFormats(dmxScreen);
+}
+
+/* If this doesn't compile, just add || defined(yoursystem) to the line
+ * below. This information is to help with bug reports and is not
+ * critical. */
+#if !defined(_POSIX_SOURCE)
+static const char *dmxExecOS(void) { return ""; }
+#else
+#include <sys/utsname.h>
+static const char *dmxExecOS(void)
+{
+ static char buffer[128];
+ static int initialized = 0;
+ struct utsname u;
+
+ if (!initialized++) {
+ memset(buffer, 0, sizeof(buffer));
+ uname(&u);
+ XmuSnprintf(buffer, sizeof(buffer)-1, "%s %s %s",
+ u.sysname, u.release, u.version);
+ }
+ return buffer;
+}
+#endif
+
+static const char *dmxBuildCompiler(void)
+{
+ static char buffer[128];
+ static int initialized = 0;
+
+ if (!initialized++) {
+ memset(buffer, 0, sizeof(buffer));
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) &&defined(__GNUC_PATCHLEVEL__)
+ XmuSnprintf(buffer, sizeof(buffer)-1, "gcc %d.%d.%d",
+ __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
+#endif
+ }
+ return buffer;
+}
+
+static const char *dmxExecHost(void)
+{
+ static char buffer[128];
+ static int initialized = 0;
+
+ if (!initialized++) {
+ memset(buffer, 0, sizeof(buffer));
+ XmuGetHostname(buffer, sizeof(buffer) - 1);
+ }
+ return buffer;
+}
+
+/** This routine is called in Xserver/dix/main.c from \a main(). */
+void InitOutput(ScreenInfo *pScreenInfo, int argc, char *argv[])
+{
+ int i;
+ static unsigned long dmxGeneration = 0;
+#ifdef GLXEXT
+ Bool glxSupported = TRUE;
+#endif
+
+ if (dmxGeneration != serverGeneration) {
+ int vendrel = VENDOR_RELEASE;
+ int major, minor, year, month, day;
+
+ dmxGeneration = serverGeneration;
+
+ major = vendrel / 100000000;
+ vendrel -= major * 100000000;
+ minor = vendrel / 1000000;
+ vendrel -= minor * 1000000;
+ year = vendrel / 10000;
+ vendrel -= year * 10000;
+ month = vendrel / 100;
+ vendrel -= month * 100;
+ day = vendrel;
+
+ /* Add other epoch tests here */
+ if (major > 0 && minor > 0) year += 2000;
+
+ dmxLog(dmxInfo, "Generation: %d\n", dmxGeneration);
+ dmxLog(dmxInfo, "DMX version: %d.%d.%02d%02d%02d (%s)\n",
+ major, minor, year, month, day, VENDOR_STRING);
+
+ SetVendorRelease(VENDOR_RELEASE);
+ SetVendorString(VENDOR_STRING);
+
+ if (dmxGeneration == 1) {
+ dmxLog(dmxInfo, "DMX Build OS: %s (%s)\n", OSNAME, OSVENDOR);
+ dmxLog(dmxInfo, "DMX Build Compiler: %s\n", dmxBuildCompiler());
+ dmxLog(dmxInfo, "DMX Execution OS: %s\n", dmxExecOS());
+ dmxLog(dmxInfo, "DMX Execution Host: %s\n", dmxExecHost());
+ }
+ dmxLog(dmxInfo, "MAXSCREENS: %d\n", MAXSCREENS);
+
+ for (i = 0; i < dmxNumScreens; i++) {
+ if (dmxScreens[i].beDisplay)
+ dmxLog(dmxWarning, "Display \"%s\" still open\n",
+ dmxScreens[i].name);
+ dmxStatFree(dmxScreens[i].stat);
+ dmxScreens[i].stat = NULL;
+ }
+ for (i = 0; i < dmxNumInputs; i++) dmxInputFree(&dmxInputs[i]);
+ if (dmxScreens) free(dmxScreens);
+ if (dmxInputs) free(dmxInputs);
+ dmxScreens = NULL;
+ dmxInputs = NULL;
+ dmxNumScreens = 0;
+ dmxNumInputs = 0;
+ }
+
+ /* Make sure that the command-line arguments are sane. */
+ if (dmxAddRemoveScreens && dmxGLXProxy) {
+ /* Currently it is not possible to support GLX and Render
+ * extensions with dynamic screen addition/removal due to the
+ * state that each extension keeps, which cannot be restored. */
+ dmxLog(dmxWarning,
+ "GLX Proxy and Render extensions do not yet support dynamic\n");
+ dmxLog(dmxWarning,
+ "screen addition and removal. Please specify -noglxproxy\n");
+ dmxLog(dmxWarning,
+ "and -norender on the command line or in the configuration\n");
+ dmxLog(dmxWarning,
+ "file to disable these two extensions if you wish to use\n");
+ dmxLog(dmxWarning,
+ "the dynamic addition and removal of screens support.\n");
+ dmxLog(dmxFatal,
+ "Dynamic screen addition/removal error (see above).\n");
+ }
+
+ /* ddxProcessArgument has been called at this point, but any data
+ * from the configuration file has not been applied. Do so, and be
+ * sure we have at least one back-end display. */
+ dmxConfigConfigure();
+ if (!dmxNumScreens)
+ dmxLog(dmxFatal, "InitOutput: no back-end displays found\n");
+ if (!dmxNumInputs)
+ dmxLog(dmxInfo, "InitOutput: no inputs found\n");
+
+ /* Disable lazy window creation optimization if offscreen
+ * optimization is disabled */
+ if (!dmxOffScreenOpt && dmxLazyWindowCreation) {
+ dmxLog(dmxInfo,
+ "InitOutput: Disabling lazy window creation optimization\n");
+ dmxLog(dmxInfo,
+ " since it requires the offscreen optimization\n");
+ dmxLog(dmxInfo,
+ " to function properly.\n");
+ dmxLazyWindowCreation = FALSE;
+ }
+
+ /* Open each display and gather information about it. */
+ for (i = 0; i < dmxNumScreens; i++)
+ dmxDisplayInit(&dmxScreens[i]);
+
+#if PANORAMIX
+ /* Register a Xinerama callback which will run from within
+ * PanoramiXCreateConnectionBlock. We can use the callback to
+ * determine if Xinerama is loaded and to check the visuals
+ * determined by PanoramiXConsolidate. */
+ XineramaRegisterConnectionBlockCallback(dmxConnectionBlockCallback);
+#endif
+
+ /* Since we only have a single screen thus far, we only need to set
+ the pixmap formats to match that screen. FIXME: this isn't true.*/
+ if (!dmxSetPixmapFormats(pScreenInfo, &dmxScreens[0])) return;
+
+ /* Might want to install a signal handler to allow cleaning up after
+ * unexpected signals. The DIX/OS layer already handles SIGINT and
+ * SIGTERM, so everything is OK for expected signals. --DD
+ *
+ * SIGHUP, SIGINT, and SIGTERM are trapped in os/connection.c
+ * SIGQUIT is another common signal that is sent from the keyboard.
+ * Trap it here, to ensure that the keyboard modifier map and other
+ * state for the input devices are restored. (This makes the
+ * behavior of SIGQUIT somewhat unexpected, since it will be the
+ * same as the behavior of SIGINT. However, leaving the modifier
+ * map of the input devices empty is even more unexpected.) --RF
+ */
+ OsSignal(SIGQUIT, GiveUp);
+
+#ifdef GLXEXT
+ /* Check if GLX extension exists on all back-end servers */
+ for (i = 0; i < dmxNumScreens; i++)
+ glxSupported &= (dmxScreens[i].glxMajorOpcode > 0);
+#endif
+
+ /* Tell dix layer about the backend displays */
+ for (i = 0; i < dmxNumScreens; i++) {
+
+#ifdef GLXEXT
+ if (glxSupported) {
+ /*
+ * Builds GLX configurations from the list of visuals
+ * supported by the back-end server, and give that
+ * configuration list to the glx layer - so that he will
+ * build the visuals accordingly.
+ */
+
+ DMXScreenInfo *dmxScreen = &dmxScreens[i];
+ __GLXvisualConfig *configs = NULL;
+ dmxGlxVisualPrivate **configprivs = NULL;
+ int nconfigs = 0;
+ int (*oldErrorHandler)(Display *, XErrorEvent *);
+ int i;
+
+ /* Catch errors if when using an older GLX w/o FBconfigs */
+ oldErrorHandler = XSetErrorHandler(dmxNOPErrorHandler);
+
+ /* Get FBConfigs of the back-end server */
+ dmxScreen->fbconfigs = GetGLXFBConfigs(dmxScreen->beDisplay,
+ dmxScreen->glxMajorOpcode,
+ &dmxScreen->numFBConfigs);
+
+ XSetErrorHandler(oldErrorHandler);
+
+ dmxScreen->glxVisuals =
+ GetGLXVisualConfigs(dmxScreen->beDisplay,
+ DefaultScreen(dmxScreen->beDisplay),
+ &dmxScreen->numGlxVisuals);
+
+ if (dmxScreen->fbconfigs) {
+ configs =
+ GetGLXVisualConfigsFromFBConfigs(dmxScreen->fbconfigs,
+ dmxScreen->numFBConfigs,
+ dmxScreen->beVisuals,
+ dmxScreen->beNumVisuals,
+ dmxScreen->glxVisuals,
+ dmxScreen->numGlxVisuals,
+ &nconfigs);
+ } else {
+ configs = dmxScreen->glxVisuals;
+ nconfigs = dmxScreen->numGlxVisuals;
+ }
+
+ configprivs = xalloc(nconfigs * sizeof(dmxGlxVisualPrivate*));
+
+ if (configs != NULL && configprivs != NULL) {
+
+ /* Initialize our private info for each visual
+ * (currently only x_visual_depth and x_visual_class)
+ */
+ for (i = 0; i < nconfigs; i++) {
+
+ configprivs[i] = (dmxGlxVisualPrivate *)
+ xalloc(sizeof(dmxGlxVisualPrivate));
+ configprivs[i]->x_visual_depth = 0;
+ configprivs[i]->x_visual_class = 0;
+
+ /* Find the visual depth */
+ if (configs[i].vid > 0) {
+ int j;
+ for (j = 0; j < dmxScreen->beNumVisuals; j++) {
+ if (dmxScreen->beVisuals[j].visualid ==
+ configs[i].vid) {
+ configprivs[i]->x_visual_depth =
+ dmxScreen->beVisuals[j].depth;
+ configprivs[i]->x_visual_class =
+ dmxScreen->beVisuals[j].class;
+ break;
+ }
+ }
+ }
+ }
+
+ /* Hand out the glx configs to glx extension */
+ GlxSetVisualConfigs(nconfigs, configs, (void**)configprivs);
+
+ XFlush(dmxScreen->beDisplay);
+ }
+ }
+#endif /* GLXEXT */
+
+ AddScreen(dmxScreenInit, argc, argv);
+ }
+
+ /* Compute origin information. */
+ dmxInitOrigins();
+
+ /* Compute overlap information. */
+ dmxInitOverlap();
+
+ /* Make sure there is a global width/height available */
+ dmxComputeWidthHeight(DMX_NO_RECOMPUTE_BOUNDING_BOX);
+
+ /* FIXME: The following is temporarily placed here. When the DMX
+ * extension is available, it will be move there.
+ */
+ dmxInitFonts();
+
+#ifdef RENDER
+ /* Initialize the render extension */
+ if (!noRenderExtension)
+ dmxInitRender();
+#endif
+
+ /* Initialized things that need timer hooks */
+ dmxStatInit();
+ dmxSyncInit(); /* Calls RegisterBlockAndWakeupHandlers */
+
+ dmxLog(dmxInfo, "Shadow framebuffer support %s\n",
+ dmxShadowFB ? "enabled" : "disabled");
+}
+
+/* RATS: Assuming the fp string (which comes from the command-line argv
+ vector) is NULL-terminated, the buffer is large enough for the
+ strcpy. */
+static void dmxSetDefaultFontPath(char *fp)
+{
+ int fplen = strlen(fp) + 1;
+
+ if (dmxFontPath) {
+ int len;
+
+ len = strlen(dmxFontPath);
+ dmxFontPath = xrealloc(dmxFontPath, len+fplen+1);
+ dmxFontPath[len] = ',';
+ strncpy(&dmxFontPath[len+1], fp, fplen);
+ } else {
+ dmxFontPath = xalloc(fplen);
+ strncpy(dmxFontPath, fp, fplen);
+ }
+
+ defaultFontPath = dmxFontPath;
+}
+
+/** This function is called in Xserver/os/utils.c from \a AbortServer().
+ * We must ensure that backend and console state is restored in the
+ * event the server shutdown wasn't clean. */
+void AbortDDX(void)
+{
+ int i;
+
+ for (i=0; i < dmxNumScreens; i++) {
+ DMXScreenInfo *dmxScreen = &dmxScreens[i];
+
+ if (dmxScreen->beDisplay) XCloseDisplay(dmxScreen->beDisplay);
+ dmxScreen->beDisplay = NULL;
+ }
+}
+
+#ifdef DDXBEFORERESET
+/* This function is called in Xserver/dix/dispatch.c */
+void ddxBeforeReset(void)
+{
+}
+#endif
+
+/** This function is called in Xserver/dix/main.c from \a main() when
+ * dispatchException & DE_TERMINATE (which is the only way to exit the
+ * main loop without an interruption. */
+void ddxGiveUp(void)
+{
+ AbortDDX();
+}
+
+/** This function is called in Xserver/os/osinit.c from \a OsInit(). */
+void OsVendorInit(void)
+{
+}
+
+/** This function is called in Xserver/os/utils.c from \a FatalError()
+ * and \a VFatalError(). (Note that setting the function pointer \a
+ * OsVendorVErrorFProc will cause \a VErrorF() (which is called by the
+ * two routines mentioned here, as well as by others) to use the
+ * referenced routine instead of \a vfprintf().) */
+void OsVendorFatalError(void)
+{
+}
+
+/** Process our command line arguments. */
+int ddxProcessArgument(int argc, char *argv[], int i)
+{
+ int retval = 0;
+
+ if (!strcmp(argv[i], "-display")) {
+ if (++i < argc) dmxConfigStoreDisplay(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-inputfrom") || !strcmp(argv[i], "-input")) {
+ if (++i < argc) dmxConfigStoreInput(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-xinputfrom") || !strcmp(argv[i],"-xinput")) {
+ if (++i < argc) dmxConfigStoreXInput(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-noshadowfb")) {
+ dmxLog(dmxWarning,
+ "-noshadowfb has been deprecated "
+ "since it is now the default\n");
+ dmxShadowFB = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-nomulticursor")) {
+ dmxCursorNoMulti();
+ retval = 1;
+ } else if (!strcmp(argv[i], "-shadowfb")) {
+ dmxShadowFB = TRUE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-configfile")) {
+ if (++i < argc) dmxConfigStoreFile(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-config")) {
+ if (++i < argc) dmxConfigStoreConfig(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-fontpath")) {
+ if (++i < argc) dmxSetDefaultFontPath(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-stat")) {
+ if ((i += 2) < argc) dmxStatActivate(argv[i-1], argv[i]);
+ retval = 3;
+ } else if (!strcmp(argv[i], "-syncbatch")) {
+ if (++i < argc) dmxSyncActivate(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-nooffscreenopt")) {
+ dmxOffScreenOpt = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-nosubdivprims")) {
+ dmxSubdividePrimitives = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-nowindowopt")) {
+ dmxLazyWindowCreation = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-noxkb")) {
+ dmxUseXKB = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-depth")) {
+ if (++i < argc) dmxDepth = atoi(argv[i]);
+ retval = 2;
+ } else if (!strcmp(argv[i], "-norender")) {
+ noRenderExtension = TRUE;
+ retval = 1;
+#ifdef GLXEXT
+ } else if (!strcmp(argv[i], "-noglxproxy")) {
+ dmxGLXProxy = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-noglxswapgroup")) {
+ dmxGLXSwapGroupSupport = FALSE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-glxsyncswap")) {
+ dmxGLXSyncSwap = TRUE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-glxfinishswap")) {
+ dmxGLXFinishSwap = TRUE;
+ retval = 1;
+#endif
+ } else if (!strcmp(argv[i], "-ignorebadfontpaths")) {
+ dmxIgnoreBadFontPaths = TRUE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-addremovescreens")) {
+ dmxAddRemoveScreens = TRUE;
+ retval = 1;
+ } else if (!strcmp(argv[i], "-param")) {
+ if ((i += 2) < argc) {
+ if (!strcasecmp(argv[i-1], "xkbrules"))
+ dmxConfigSetXkbRules(argv[i]);
+ else if (!strcasecmp(argv[i-1], "xkbmodel"))
+ dmxConfigSetXkbModel(argv[i]);
+ else if (!strcasecmp(argv[i-1], "xkblayout"))
+ dmxConfigSetXkbLayout(argv[i]);
+ else if (!strcasecmp(argv[i-1], "xkbvariant"))
+ dmxConfigSetXkbVariant(argv[i]);
+ else if (!strcasecmp(argv[i-1], "xkboptions"))
+ dmxConfigSetXkbOptions(argv[i]);
+ else
+ dmxLog(dmxWarning,
+ "-param requires: XkbRules, XkbModel, XkbLayout,"
+ " XkbVariant, or XkbOptions\n");
+ }
+ retval = 3;
+ }
+ if (!serverGeneration) dmxConfigSetMaxScreens();
+ return retval;
+}
+
+/** Provide succinct usage information for the DMX server. */
+void ddxUseMsg(void)
+{
+ ErrorF("\n\nDevice Dependent Usage:\n");
+ ErrorF("-display string Specify the back-end display(s)\n");
+ ErrorF("-input string Specify input source for core device\n");
+ ErrorF("-xinput string Specify input source for XInput device\n");
+ ErrorF("-shadowfb Enable shadow frame buffer\n");
+ ErrorF("-configfile file Read from a configuration file\n");
+ ErrorF("-config config Select a specific configuration\n");
+ ErrorF("-nomulticursor Turn of multiple cursor support\n");
+ ErrorF("-fontpath Sets the default font path\n");
+ ErrorF("-stat inter scrns Print out performance statistics\n");
+ ErrorF("-syncbatch inter Set interval for XSync batching\n");
+ ErrorF("-nooffscreenopt Disable offscreen optimization\n");
+ ErrorF("-nosubdivprims Disable primitive subdivision\n");
+ ErrorF(" optimization\n");
+ ErrorF("-nowindowopt Disable lazy window creation optimization\n");
+ ErrorF("-noxkb Disable use of the XKB extension with\n");
+ ErrorF(" backend displays (cf. -kb).\n");
+ ErrorF("-depth Specify the default root window depth\n");
+ ErrorF("-norender Disable RENDER extension support\n");
+#ifdef GLXEXT
+ ErrorF("-noglxproxy Disable GLX Proxy\n");
+ ErrorF("-noglxswapgroup Disable swap group and swap barrier\n");
+ ErrorF(" extensions in GLX proxy\n");
+ ErrorF("-glxsyncswap Force XSync after swap buffers\n");
+ ErrorF("-glxfinishswap Force glFinish after swap buffers\n");
+#endif
+ ErrorF("-ignorebadfontpaths Ignore bad font paths during initialization\n");
+ ErrorF("-addremovescreens Enable dynamic screen addition/removal\n");
+ ErrorF("-param ... Specify configuration parameters (e.g.,\n");
+ ErrorF(" XkbRules, XkbModel, XkbLayout, etc.)\n");
+ ErrorF("\n");
+ ErrorF(" If the -input string matches a -display string, then input\n"
+ " is taken from that backend display. (XInput cannot be taken\n"
+ " from a backend display.) Placing \",console\" after the\n"
+ " display name will force a console window to be opened on\n"
+ " that display in addition to the backend input. This is\n"
+ " useful if the backend window does not cover the whole\n"
+ " physical display.\n\n");
+
+ ErrorF(" Otherwise, if the -input or -xinput string specifies another\n"
+ " X display, then a console window will be created on that\n"
+ " display. Placing \",windows\" or \",nowindows\" after the\n"
+ " display name will control the display of window outlines in\n"
+ " the console.\n\n");
+
+ ErrorF(" -input or -xinput dummy specifies no input.\n");
+ ErrorF(" -input or -xinput local specifies the use of a raw keyboard,\n"
+ " mouse, or other (extension) device:\n"
+ " -input local,kbd,ps2 will use a ps2 mouse\n"
+ " -input local,kbd,ms will use a serial mouse\n"
+ " -input local,usb-kbd,usb-mou will use USB devices \n"
+ " -xinput local,usb-oth will use a non-mouse and\n"
+ " non-keyboard USB device with XInput\n\n");
+
+ ErrorF(" Special Keys:\n");
+ ErrorF(" Ctrl-Alt-g Server grab/ungrab (console only)\n");
+ ErrorF(" Ctrl-Alt-f Fine (1-pixel) mouse mode (console only)\n");
+ ErrorF(" Ctrl-Alt-q Quit (core devices only)\n");
+ ErrorF(" Ctrl-Alt-F* Switch to VC (local only)\n");
+}
diff --git a/xorg-server/hw/kdrive/ephyr/ephyr.c b/xorg-server/hw/kdrive/ephyr/ephyr.c index 296284a01..947a7ff1b 100644 --- a/xorg-server/hw/kdrive/ephyr/ephyr.c +++ b/xorg-server/hw/kdrive/ephyr/ephyr.c @@ -61,8 +61,11 @@ Bool EphyrWantGrayScale = 0; Bool ephyrInitialize (KdCardInfo *card, EphyrPriv *priv) { +#ifdef _MSC_VER + __asm int 3; +#else OsSignal(SIGUSR1, hostx_handle_signal); - +#endif priv->base = 0; priv->bytes_per_line = 0; return TRUE; @@ -817,21 +820,29 @@ ephyrUpdateModifierState(unsigned int state) static void ephyrBlockSigio (void) { +#ifdef _MSC_VER + __asm int 3; +#else sigset_t set; sigemptyset (&set); sigaddset (&set, SIGIO); sigprocmask (SIG_BLOCK, &set, 0); +#endif } static void ephyrUnblockSigio (void) { +#ifdef _MSC_VER + __asm int 3; +#else sigset_t set; sigemptyset (&set); sigaddset (&set, SIGIO); sigprocmask (SIG_UNBLOCK, &set, 0); +#endif } static Bool diff --git a/xorg-server/hw/kdrive/ephyr/ephyr.h b/xorg-server/hw/kdrive/ephyr/ephyr.h index 5d58a216c..dd22bd150 100644 --- a/xorg-server/hw/kdrive/ephyr/ephyr.h +++ b/xorg-server/hw/kdrive/ephyr/ephyr.h @@ -26,9 +26,11 @@ #ifndef _EPHYR_H_ #define _EPHYR_H_ #include <stdio.h> +#ifndef _MSC_VER #include <unistd.h> -#include <signal.h> #include <libgen.h> +#endif +#include <signal.h> #include "os.h" /* for OsSignal() */ #include "kdrive.h" diff --git a/xorg-server/hw/kdrive/ephyr/ephyrinit.c b/xorg-server/hw/kdrive/ephyr/ephyrinit.c index 22152ffe0..27c346dd1 100644 --- a/xorg-server/hw/kdrive/ephyr/ephyrinit.c +++ b/xorg-server/hw/kdrive/ephyr/ephyrinit.c @@ -53,6 +53,7 @@ InitCard (char *name) KdCardInfoAdd (&ephyrFuncs, &attr, 0); } +#ifndef _MSC_VER void InitOutput (ScreenInfo *pScreenInfo, int argc, char **argv) { @@ -115,6 +116,7 @@ ddxUseMsg (void) exit(1); } +#endif void processScreenArg (char *screen_size, char *parent_id) @@ -145,6 +147,7 @@ processScreenArg (char *screen_size, char *parent_id) } } +#ifndef _MSC_VER int ddxProcessArgument (int argc, char **argv, int i) { @@ -285,6 +288,13 @@ ddxProcessArgument (int argc, char **argv, int i) return KdProcessArgument (argc, argv, i); } +#ifdef DDXBEFORERESET +void +ddxBeforeReset (void) +{ +} +#endif + void OsVendorInit (void) { @@ -299,6 +309,15 @@ OsVendorInit (void) KdOsInit (&EphyrOsFuncs); } +#ifdef DDXOSFATALERROR +void +OsVendorFatalError(void) +{ +} +#endif + +#endif + /* 'Fake' cursor stuff, could be improved */ static Bool diff --git a/xorg-server/hw/kdrive/ephyr/ephyrlog.h b/xorg-server/hw/kdrive/ephyr/ephyrlog.h index a07a0a097..ba52a3bce 100644 --- a/xorg-server/hw/kdrive/ephyr/ephyrlog.h +++ b/xorg-server/hw/kdrive/ephyr/ephyrlog.h @@ -43,14 +43,14 @@ #ifndef EPHYR_LOG #define EPHYR_LOG(...) \ LogMessageVerb(X_NOTICE, INFO_LOG_LEVEL, "in %s:%d:%s: ",\ - __FILE__, __LINE__, __func__) ; \ + __FILE__, __LINE__, __FUNCTION__) ; \ LogMessageVerb(X_NOTICE, INFO_LOG_LEVEL, __VA_ARGS__) #endif /*nomadik_log*/ #ifndef EPHYR_LOG_ERROR #define EPHYR_LOG_ERROR(...) \ LogMessageVerb(X_NOTICE, ERROR_LOG_LEVEL, "Error:in %s:%d:%s: ",\ - __FILE__, __LINE__, __func__) ; \ + __FILE__, __LINE__, __FUNCTION__) ; \ LogMessageVerb(X_NOTICE, ERROR_LOG_LEVEL, __VA_ARGS__) #endif /*EPHYR_LOG_ERROR*/ diff --git a/xorg-server/hw/kdrive/ephyr/hostx.c b/xorg-server/hw/kdrive/ephyr/hostx.c index d546370ba..7a828eb31 100644 --- a/xorg-server/hw/kdrive/ephyr/hostx.c +++ b/xorg-server/hw/kdrive/ephyr/hostx.c @@ -47,9 +47,11 @@ #include <string.h> /* for memset */ #include <time.h> +#ifndef _MSC_VER #include <sys/ipc.h> #include <sys/shm.h> #include <sys/time.h> +#endif #include <X11/Xlib.h> #include <X11/Xutil.h> @@ -208,7 +210,11 @@ hostx_add_screen (EphyrScreenInfo screen, void hostx_set_display_name (char *name) { +#ifdef _MSC_VER + __asm int 3; +#else HostX.server_dpy_name = strdup (name); +#endif } void @@ -475,6 +481,9 @@ hostx_init (void) } /* Try to get share memory ximages for a little bit more speed */ +#ifdef _MSC_VER + __asm int 3; +#else if (!XShmQueryExtension(HostX.dpy) || getenv("XEPHYR_NO_SHM")) { fprintf(stderr, "\nXephyr unable to use SHM XImages\n"); @@ -505,6 +514,7 @@ hostx_init (void) shmdt(shminfo.shmaddr); shmctl(shminfo.shmid, IPC_RMID, 0); } +#endif XFlush(HostX.dpy); @@ -647,7 +657,7 @@ hostx_screen_init (EphyrScreenInfo screen, struct EphyrHostScreen *host_screen = host_screen_from_screen_info (screen); if (!host_screen) { - fprintf (stderr, "%s: Error in accessing hostx data\n", __func__ ); + fprintf (stderr, "%s: Error in accessing hostx data\n", __FUNCTION__ ); exit(1); } @@ -662,10 +672,14 @@ hostx_screen_init (EphyrScreenInfo screen, if (HostX.have_shm) { +#ifdef _MSC_VER + __asm int 3; +#else XShmDetach(HostX.dpy, &host_screen->shminfo); XDestroyImage (host_screen->ximg); shmdt(host_screen->shminfo.shmaddr); shmctl(host_screen->shminfo.shmid, IPC_RMID, 0); +#endif } else { @@ -681,6 +695,9 @@ hostx_screen_init (EphyrScreenInfo screen, if (HostX.have_shm) { +#ifdef _MSC_VER +__asm int 3; +#else host_screen->ximg = XShmCreateImage (HostX.dpy, HostX.visual, HostX.depth, ZPixmap, NULL, &host_screen->shminfo, width, buffer_height ); @@ -706,6 +723,7 @@ hostx_screen_init (EphyrScreenInfo screen, XShmAttach(HostX.dpy, &host_screen->shminfo); shm_success = True; } +#endif } if (!shm_success) @@ -834,9 +852,13 @@ hostx_paint_rect (EphyrScreenInfo screen, if (HostX.have_shm) { +#ifdef _MSC_VER + __asm int 3; +#else XShmPutImage (HostX.dpy, host_screen->win, HostX.gc, host_screen->ximg, sx, sy, dx, dy, width, height, False); +#endif } else { @@ -852,6 +874,9 @@ hostx_paint_debug_rect (struct EphyrHostScreen *host_screen, int x, int y, int width, int height) { +#ifdef _MSC_VER + __asm int 3; +#else struct timespec tspec; tspec.tv_sec = HostX.damage_debug_msec / (1000000); @@ -867,6 +892,7 @@ hostx_paint_debug_rect (struct EphyrHostScreen *host_screen, /* nanosleep seems to work better than usleep for me... */ nanosleep(&tspec, NULL); +#endif } void @@ -1288,8 +1314,12 @@ hostx_set_window_bounding_rectangles (int a_window, rects[i].width, rects[i].height) ; } /*this aways returns 1*/ +#ifdef _MSC_VER + __asm int 3; +#else XShapeCombineRectangles (dpy, a_window, ShapeBounding, 0, 0, rects, a_num_rects, ShapeSet, YXBanded) ; +#endif is_ok = TRUE ; if (rects) { @@ -1325,8 +1355,12 @@ hostx_set_window_clipping_rectangles (int a_window, rects[i].width, rects[i].height) ; } /*this aways returns 1*/ +#ifdef _MSC_VER + __asm int 3; +#else XShapeCombineRectangles (dpy, a_window, ShapeClip, 0, 0, rects, a_num_rects, ShapeSet, YXBanded) ; +#endif is_ok = TRUE ; if (rects) { @@ -1341,12 +1375,16 @@ int hostx_has_xshape (void) { int event_base=0, error_base=0 ; +#ifdef _MSC_VER + __asm int 3; +#else Display *dpy=hostx_get_display () ; if (!XShapeQueryExtension (dpy, &event_base, &error_base)) { return FALSE ; } +#endif return TRUE; } diff --git a/xorg-server/hw/kdrive/ephyr/hostx.h b/xorg-server/hw/kdrive/ephyr/hostx.h index e65e0c9bc..f455b3003 100644 --- a/xorg-server/hw/kdrive/ephyr/hostx.h +++ b/xorg-server/hw/kdrive/ephyr/hostx.h @@ -35,8 +35,12 @@ #define EPHYR_DBG(x, a...) \ fprintf(stderr, __FILE__ ":%d,%s() " x "\n", __LINE__, __func__, ##a) #else +#ifdef _MSC_VER +#define EPHYR_DBG() +#else #define EPHYR_DBG(x, a...) do {} while (0) #endif +#endif typedef struct EphyrHostXVars EphyrHostXVars; typedef struct EphyrHostXEvent EphyrHostXEvent; diff --git a/xorg-server/hw/kdrive/ephyr/makefile b/xorg-server/hw/kdrive/ephyr/makefile new file mode 100644 index 000000000..eba9a93e1 --- /dev/null +++ b/xorg-server/hw/kdrive/ephyr/makefile @@ -0,0 +1,6 @@ +LIBRARY = libxephyr + +CSRCS=ephyrinit.c ephyr.c hostx.c + +INCLUDES += ..\src ..\..\..\exa + diff --git a/xorg-server/hw/kdrive/src/kdrive.c b/xorg-server/hw/kdrive/src/kdrive.c index 5cfe54ff8..f79b96f6f 100644 --- a/xorg-server/hw/kdrive/src/kdrive.c +++ b/xorg-server/hw/kdrive/src/kdrive.c @@ -321,6 +321,7 @@ KdProcessSwitch (void) KdEnableScreens (); } +#ifndef _MSC_VER void AbortDDX(void) { @@ -343,6 +344,7 @@ ddxGiveUp (void) { AbortDDX (); } +#endif Bool kdDumbDriver; Bool kdSoftCursor; @@ -1310,11 +1312,14 @@ KdInitOutput (ScreenInfo *pScreenInfo, OsRegisterSigWrapper(KdSignalWrapper); } +#ifndef _MSC_VER void OsVendorFatalError(void) { } +#endif +#ifndef _MSC_VER int DPMSSet(ClientPtr client, int level) { @@ -1326,3 +1331,4 @@ DPMSSupported (void) { return FALSE; } +#endif diff --git a/xorg-server/hw/kdrive/src/kinput.c b/xorg-server/hw/kdrive/src/kinput.c index fb8ebd076..6f54ada1f 100644 --- a/xorg-server/hw/kdrive/src/kinput.c +++ b/xorg-server/hw/kdrive/src/kinput.c @@ -1,2351 +1,2376 @@ -/* - * Copyright © 1999 Keith Packard - * Copyright © 2006 Nokia Corporation - * - * Permission to use, copy, modify, distribute, and sell this software and its - * documentation for any purpose is hereby granted without fee, provided that - * the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of the authors not be used in - * advertising or publicity pertaining to distribution of the software without - * specific, written prior permission. The authors make no - * representations about the suitability of this software for any purpose. It - * is provided "as is" without express or implied warranty. - * - * THE AUTHORS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, - * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO - * EVENT SHALL THE AUTHORS 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_CONFIG_H -#include <kdrive-config.h> -#endif -#include "kdrive.h" -#include "inputstr.h" - -#define XK_PUBLISHING -#include <X11/keysym.h> -#if HAVE_X11_XF86KEYSYM_H -#include <X11/XF86keysym.h> -#endif -#include <signal.h> -#include <stdio.h> -#ifdef sun -#include <sys/file.h> /* needed for FNONBLOCK & FASYNC */ -#endif - -#include "xkbsrv.h" - -#include <X11/extensions/XI.h> -#include <X11/extensions/XIproto.h> -#include "XIstubs.h" /* even though we don't use stubs. cute, no? */ -#include "exevents.h" -#include "extinit.h" -#include "exglobals.h" -#include "eventstr.h" -#include "xserver-properties.h" - -#define AtomFromName(x) MakeAtom(x, strlen(x), 1) - -struct KdConfigDevice { - char *line; - struct KdConfigDevice *next; -}; - -/* kdKeyboards and kdPointers hold all the real devices. */ -static KdKeyboardInfo *kdKeyboards = NULL; -static KdPointerInfo *kdPointers = NULL; -static struct KdConfigDevice *kdConfigKeyboards = NULL; -static struct KdConfigDevice *kdConfigPointers = NULL; - -static KdKeyboardDriver *kdKeyboardDrivers = NULL; -static KdPointerDriver *kdPointerDrivers = NULL; - -static EventListPtr kdEvents = NULL; - -static Bool kdInputEnabled; -static Bool kdOffScreen; -static unsigned long kdOffScreenTime; -static KdPointerMatrix kdPointerMatrix = { - { { 1, 0, 0 }, - { 0, 1, 0 } } -}; - -void KdResetInputMachine (void); - -#define KD_MAX_INPUT_FDS 8 - -typedef struct _kdInputFd { - int fd; - void (*read) (int fd, void *closure); - int (*enable) (int fd, void *closure); - void (*disable) (int fd, void *closure); - void *closure; -} KdInputFd; - -static KdInputFd kdInputFds[KD_MAX_INPUT_FDS]; -static int kdNumInputFds; - -extern Bool kdRawPointerCoordinates; - -static void -KdSigio (int sig) -{ - int i; - - for (i = 0; i < kdNumInputFds; i++) - (*kdInputFds[i].read) (kdInputFds[i].fd, kdInputFds[i].closure); -} - -static void -KdBlockSigio (void) -{ - sigset_t set; - - sigemptyset (&set); - sigaddset (&set, SIGIO); - sigprocmask (SIG_BLOCK, &set, 0); -} - -static void -KdUnblockSigio (void) -{ - sigset_t set; - - sigemptyset (&set); - sigaddset (&set, SIGIO); - sigprocmask (SIG_UNBLOCK, &set, 0); -} - -#ifdef DEBUG_SIGIO - -void -KdAssertSigioBlocked (char *where) -{ - sigset_t set, old; - - sigemptyset (&set); - sigprocmask (SIG_BLOCK, &set, &old); - if (!sigismember (&old, SIGIO)) { - ErrorF ("SIGIO not blocked at %s\n", where); - KdBacktrace(0); - } -} - -#else - -#define KdAssertSigioBlocked(s) - -#endif - -static int kdnFds; - -#ifdef FNONBLOCK -#define NOBLOCK FNONBLOCK -#else -#define NOBLOCK FNDELAY -#endif - -void -KdResetInputMachine (void) -{ - KdPointerInfo *pi; - - for (pi = kdPointers; pi; pi = pi->next) { - pi->mouseState = start; - pi->eventHeld = FALSE; - } -} - -static void -KdNonBlockFd (int fd) -{ - int flags; - flags = fcntl (fd, F_GETFL); - flags |= FASYNC|NOBLOCK; - fcntl (fd, F_SETFL, flags); -} - -static void -KdAddFd (int fd) -{ - struct sigaction act; - sigset_t set; - - kdnFds++; - fcntl (fd, F_SETOWN, getpid()); - KdNonBlockFd (fd); - AddEnabledDevice (fd); - memset (&act, '\0', sizeof act); - act.sa_handler = KdSigio; - sigemptyset (&act.sa_mask); - sigaddset (&act.sa_mask, SIGIO); - sigaddset (&act.sa_mask, SIGALRM); - sigaddset (&act.sa_mask, SIGVTALRM); - sigaction (SIGIO, &act, 0); - sigemptyset (&set); - sigprocmask (SIG_SETMASK, &set, 0); -} - -static void -KdRemoveFd (int fd) -{ - struct sigaction act; - int flags; - - kdnFds--; - RemoveEnabledDevice (fd); - flags = fcntl (fd, F_GETFL); - flags &= ~(FASYNC|NOBLOCK); - fcntl (fd, F_SETFL, flags); - if (kdnFds == 0) - { - memset (&act, '\0', sizeof act); - act.sa_handler = SIG_IGN; - sigemptyset (&act.sa_mask); - sigaction (SIGIO, &act, 0); - } -} - -Bool -KdRegisterFd (int fd, void (*read) (int fd, void *closure), void *closure) -{ - if (kdNumInputFds == KD_MAX_INPUT_FDS) - return FALSE; - kdInputFds[kdNumInputFds].fd = fd; - kdInputFds[kdNumInputFds].read = read; - kdInputFds[kdNumInputFds].enable = 0; - kdInputFds[kdNumInputFds].disable = 0; - kdInputFds[kdNumInputFds].closure = closure; - kdNumInputFds++; - if (kdInputEnabled) - KdAddFd (fd); - return TRUE; -} - -void -KdUnregisterFd (void *closure, int fd, Bool do_close) -{ - int i, j; - - for (i = 0; i < kdNumInputFds; i++) { - if (kdInputFds[i].closure == closure && - (fd == -1 || kdInputFds[i].fd == fd)) { - if (kdInputEnabled) - KdRemoveFd (kdInputFds[i].fd); - if (do_close) - close (kdInputFds[i].fd); - kdNumInputFds--; - for (j = i; j < kdNumInputFds; j++) - kdInputFds[j] = kdInputFds[j+1]; - break; - } - } -} - -void -KdUnregisterFds (void *closure, Bool do_close) -{ - KdUnregisterFd(closure, -1, do_close); -} - -void -KdDisableInput (void) -{ - KdKeyboardInfo *ki; - KdPointerInfo *pi; - int found = 0, i = 0; - - KdBlockSigio(); - - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->driver && ki->driver->Disable) - (*ki->driver->Disable) (ki); - } - - for (pi = kdPointers; pi; pi = pi->next) { - if (pi->driver && pi->driver->Disable) - (*pi->driver->Disable) (pi); - } - - if (kdNumInputFds) { - ErrorF("[KdDisableInput] Buggy drivers: still %d input fds left!", - kdNumInputFds); - i = 0; - while (i < kdNumInputFds) { - found = 0; - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki == kdInputFds[i].closure) { - ErrorF(" fd %d belongs to keybd driver %s\n", - kdInputFds[i].fd, - ki->driver && ki->driver->name ? - ki->driver->name : "(unnamed!)"); - found = 1; - break; - } - } - - if (found) { - i++; - continue; - } - - for (pi = kdPointers; pi; pi = pi->next) { - if (pi == kdInputFds[i].closure) { - ErrorF(" fd %d belongs to pointer driver %s\n", - kdInputFds[i].fd, - pi->driver && pi->driver->name ? - pi->driver->name : "(unnamed!)"); - break; - } - } - - if (found) { - i++; - continue; - } - - ErrorF(" fd %d not claimed by any active device!\n", - kdInputFds[i].fd); - KdUnregisterFd(kdInputFds[i].closure, kdInputFds[i].fd, TRUE); - } - } - - kdInputEnabled = FALSE; -} - -void -KdEnableInput (void) -{ - InternalEvent ev; - KdKeyboardInfo *ki; - KdPointerInfo *pi; - - kdInputEnabled = TRUE; - - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->driver && ki->driver->Enable) - (*ki->driver->Enable) (ki); - } - - for (pi = kdPointers; pi; pi = pi->next) { - if (pi->driver && pi->driver->Enable) - (*pi->driver->Enable) (pi); - } - - /* reset screen saver */ - ev.any.time = GetTimeInMillis (); - NoticeEventTime (&ev); - - KdUnblockSigio (); -} - -static KdKeyboardDriver * -KdFindKeyboardDriver (char *name) -{ - KdKeyboardDriver *ret; - - /* ask a stupid question ... */ - if (!name) - return NULL; - - for (ret = kdKeyboardDrivers; ret; ret = ret->next) { - if (strcmp(ret->name, name) == 0) - return ret; - } - - return NULL; -} - -static KdPointerDriver * -KdFindPointerDriver (char *name) -{ - KdPointerDriver *ret; - - /* ask a stupid question ... */ - if (!name) - return NULL; - - for (ret = kdPointerDrivers; ret; ret = ret->next) { - if (strcmp(ret->name, name) == 0) - return ret; - } - - return NULL; -} - -static int -KdPointerProc(DeviceIntPtr pDevice, int onoff) -{ - DevicePtr pDev = (DevicePtr)pDevice; - KdPointerInfo *pi; - Atom xiclass; - Atom *btn_labels; - Atom *axes_labels; - - if (!pDev) - return BadImplementation; - - for (pi = kdPointers; pi; pi = pi->next) { - if (pi->dixdev && pi->dixdev->id == pDevice->id) - break; - } - - if (!pi || !pi->dixdev || pi->dixdev->id != pDevice->id) { - ErrorF("[KdPointerProc] Failed to find pointer for device %d!\n", - pDevice->id); - return BadImplementation; - } - - switch (onoff) - { - case DEVICE_INIT: -#ifdef DEBUG - ErrorF("initialising pointer %s ...\n", pi->name); -#endif - if (!pi->driver) { - if (!pi->driverPrivate) { - ErrorF("no driver specified for %s\n", pi->name); - return BadImplementation; - } - - pi->driver = KdFindPointerDriver(pi->driverPrivate); - if (!pi->driver) { - ErrorF("Couldn't find pointer driver %s\n", - pi->driverPrivate ? (char *) pi->driverPrivate : - "(unnamed)"); - return !Success; - } - xfree(pi->driverPrivate); - pi->driverPrivate = NULL; - } - - if (!pi->driver->Init) { - ErrorF("no init function\n"); - return BadImplementation; - } - - if ((*pi->driver->Init) (pi) != Success) { - return !Success; - } - - btn_labels = xcalloc(pi->nButtons, sizeof(Atom)); - if (!btn_labels) - return BadAlloc; - axes_labels = xcalloc(pi->nAxes, sizeof(Atom)); - if (!axes_labels) { - xfree(btn_labels); - return BadAlloc; - } - - switch(pi->nAxes) - { - default: - case 7: - btn_labels[6] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_RIGHT); - case 6: - btn_labels[5] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_LEFT); - case 5: - btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN); - case 4: - btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP); - case 3: - btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT); - case 2: - btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE); - case 1: - btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT); - case 0: - break; - } - - if (pi->nAxes >= 2) { - axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X); - axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y); - } - - InitPointerDeviceStruct(pDev, pi->map, pi->nButtons, btn_labels, - (PtrCtrlProcPtr)NoopDDA, - GetMotionHistorySize(), pi->nAxes, axes_labels); - - xfree(btn_labels); - xfree(axes_labels); - - if (pi->inputClass == KD_TOUCHSCREEN) { - InitAbsoluteClassDeviceStruct(pDevice); - xiclass = AtomFromName(XI_TOUCHSCREEN); - } - else { - xiclass = AtomFromName(XI_MOUSE); - } - - AssignTypeAndName(pi->dixdev, xiclass, - pi->name ? pi->name : "Generic KDrive Pointer"); - - return Success; - - case DEVICE_ON: - if (pDev->on == TRUE) - return Success; - - if (!pi->driver->Enable) { - ErrorF("no enable function\n"); - return BadImplementation; - } - - if ((*pi->driver->Enable) (pi) == Success) { - pDev->on = TRUE; - return Success; - } - else { - return BadImplementation; - } - - return Success; - - case DEVICE_OFF: - if (pDev->on == FALSE) { - return Success; - } - - if (!pi->driver->Disable) { - return BadImplementation; - } - else { - (*pi->driver->Disable) (pi); - pDev->on = FALSE; - return Success; - } - - return Success; - - case DEVICE_CLOSE: - if (pDev->on) { - if (!pi->driver->Disable) { - return BadImplementation; - } - (*pi->driver->Disable) (pi); - pDev->on = FALSE; - } - - if (!pi->driver->Fini) - return BadImplementation; - - (*pi->driver->Fini) (pi); - - KdRemovePointer(pi); - - return Success; - } - - /* NOTREACHED */ - return BadImplementation; -} - -Bool -LegalModifier(unsigned int key, DeviceIntPtr pDev) -{ - return TRUE; -} - -static void -KdBell (int volume, DeviceIntPtr pDev, pointer arg, int something) -{ - KeybdCtrl *ctrl = arg; - KdKeyboardInfo *ki = NULL; - - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->dixdev && ki->dixdev->id == pDev->id) - break; - } - - if (!ki || !ki->dixdev || ki->dixdev->id != pDev->id || !ki->driver) - return; - - KdRingBell(ki, volume, ctrl->bell_pitch, ctrl->bell_duration); -} - -void -DDXRingBell(int volume, int pitch, int duration) -{ - KdKeyboardInfo *ki = NULL; - - if (kdOsFuncs->Bell) { - (*kdOsFuncs->Bell)(volume, pitch, duration); - } - else { - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->dixdev->coreEvents) - KdRingBell(ki, volume, pitch, duration); - } - } -} - -void -KdRingBell(KdKeyboardInfo *ki, int volume, int pitch, int duration) -{ - if (!ki || !ki->driver || !ki->driver->Bell) - return; - - if (kdInputEnabled) - (*ki->driver->Bell) (ki, volume, pitch, duration); -} - - -static void -KdSetLeds (KdKeyboardInfo *ki, int leds) -{ - if (!ki || !ki->driver) - return; - - if (kdInputEnabled) { - if (ki->driver->Leds) - (*ki->driver->Leds) (ki, leds); - } -} - -void -KdSetLed (KdKeyboardInfo *ki, int led, Bool on) -{ - if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed) - return; - - NoteLedState (ki->dixdev, led, on); - KdSetLeds (ki, ki->dixdev->kbdfeed->ctrl.leds); -} - -void -KdSetPointerMatrix (KdPointerMatrix *matrix) -{ - kdPointerMatrix = *matrix; -} - -void -KdComputePointerMatrix (KdPointerMatrix *m, Rotation randr, int width, - int height) -{ - int x_dir = 1, y_dir = 1; - int i, j; - int size[2]; - - size[0] = width; size[1] = height; - if (randr & RR_Reflect_X) - x_dir = -1; - if (randr & RR_Reflect_Y) - y_dir = -1; - switch (randr & (RR_Rotate_All)) { - case RR_Rotate_0: - m->matrix[0][0] = x_dir; m->matrix[0][1] = 0; - m->matrix[1][0] = 0; m->matrix[1][1] = y_dir; - break; - case RR_Rotate_90: - m->matrix[0][0] = 0; m->matrix[0][1] = -x_dir; - m->matrix[1][0] = y_dir; m->matrix[1][1] = 0; - break; - case RR_Rotate_180: - m->matrix[0][0] = -x_dir; m->matrix[0][1] = 0; - m->matrix[1][0] = 0; m->matrix[1][1] = -y_dir; - break; - case RR_Rotate_270: - m->matrix[0][0] = 0; m->matrix[0][1] = x_dir; - m->matrix[1][0] = -y_dir; m->matrix[1][1] = 0; - break; - } - for (i = 0; i < 2; i++) - { - m->matrix[i][2] = 0; - for (j = 0 ; j < 2; j++) - if (m->matrix[i][j] < 0) - m->matrix[i][2] = size[j] - 1; - } -} - -void -KdScreenToPointerCoords (int *x, int *y) -{ - int (*m)[3] = kdPointerMatrix.matrix; - int div = m[0][1] * m[1][0] - m[1][1] * m[0][0]; - int sx = *x; - int sy = *y; - - *x = (m[0][1] * sy - m[0][1] * m[1][2] + m[1][1] * m[0][2] - m[1][1] * sx) / div; - *y = (m[1][0] * sx + m[0][0] * m[1][2] - m[1][0] * m[0][2] - m[0][0] * sy) / div; -} - -static void -KdKbdCtrl (DeviceIntPtr pDevice, KeybdCtrl *ctrl) -{ - KdKeyboardInfo *ki; - - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->dixdev && ki->dixdev->id == pDevice->id) - break; - } - - if (!ki || !ki->dixdev || ki->dixdev->id != pDevice->id || !ki->driver) - return; - - KdSetLeds(ki, ctrl->leds); - ki->bellPitch = ctrl->bell_pitch; - ki->bellDuration = ctrl->bell_duration; -} - -extern KeybdCtrl defaultKeyboardControl; - -static int -KdKeyboardProc(DeviceIntPtr pDevice, int onoff) -{ - Bool ret; - DevicePtr pDev = (DevicePtr)pDevice; - KdKeyboardInfo *ki; - Atom xiclass; - XkbRMLVOSet rmlvo; - - if (!pDev) - return BadImplementation; - - for (ki = kdKeyboards; ki; ki = ki->next) { - if (ki->dixdev && ki->dixdev->id == pDevice->id) - break; - } - - if (!ki || !ki->dixdev || ki->dixdev->id != pDevice->id) { - return BadImplementation; - } - - switch (onoff) - { - case DEVICE_INIT: -#ifdef DEBUG - ErrorF("initialising keyboard %s\n", ki->name); -#endif - if (!ki->driver) { - if (!ki->driverPrivate) { - ErrorF("no driver specified!\n"); - return BadImplementation; - } - - ki->driver = KdFindKeyboardDriver(ki->driverPrivate); - if (!ki->driver) { - ErrorF("Couldn't find keyboard driver %s\n", - ki->driverPrivate ? (char *) ki->driverPrivate : - "(unnamed)"); - return !Success; - } - xfree(ki->driverPrivate); - ki->driverPrivate = NULL; - } - - if (!ki->driver->Init) { - ErrorF("Keyboard %s: no init function\n", ki->name); - return BadImplementation; - } - - if ((*ki->driver->Init) (ki) != Success) { - return !Success; - } - - memset(&rmlvo, 0, sizeof(rmlvo)); - rmlvo.rules = ki->xkbRules; - rmlvo.model = ki->xkbModel; - rmlvo.layout = ki->xkbLayout; - rmlvo.variant = ki->xkbVariant; - rmlvo.options = ki->xkbOptions; - ret = InitKeyboardDeviceStruct (pDevice, &rmlvo, KdBell, KdKbdCtrl); - if (!ret) { - ErrorF("Couldn't initialise keyboard %s\n", ki->name); - return BadImplementation; - } - - xiclass = AtomFromName(XI_KEYBOARD); - AssignTypeAndName(pDevice, xiclass, - ki->name ? ki->name : "Generic KDrive Keyboard"); - - KdResetInputMachine(); - - return Success; - - case DEVICE_ON: - if (pDev->on == TRUE) - return Success; - - if (!ki->driver->Enable) - return BadImplementation; - - if ((*ki->driver->Enable) (ki) != Success) { - return BadMatch; - } - - pDev->on = TRUE; - return Success; - - case DEVICE_OFF: - if (pDev->on == FALSE) - return Success; - - if (!ki->driver->Disable) - return BadImplementation; - - (*ki->driver->Disable) (ki); - pDev->on = FALSE; - - return Success; - - break; - - case DEVICE_CLOSE: - if (pDev->on) { - if (!ki->driver->Disable) - return BadImplementation; - - (*ki->driver->Disable) (ki); - pDev->on = FALSE; - } - - if (!ki->driver->Fini) - return BadImplementation; - - (*ki->driver->Fini) (ki); - - KdRemoveKeyboard(ki); - - return Success; - } - - /* NOTREACHED */ - return BadImplementation; -} - -void -KdAddPointerDriver (KdPointerDriver *driver) -{ - KdPointerDriver **prev; - - if (!driver) - return; - - for (prev = &kdPointerDrivers; *prev; prev = &(*prev)->next) { - if (*prev == driver) - return; - } - *prev = driver; -} - -void -KdRemovePointerDriver (KdPointerDriver *driver) -{ - KdPointerDriver *tmp; - - if (!driver) - return; - - /* FIXME remove all pointers using this driver */ - for (tmp = kdPointerDrivers; tmp; tmp = tmp->next) { - if (tmp->next == driver) - tmp->next = driver->next; - } - if (tmp == driver) - tmp = NULL; -} - -void -KdAddKeyboardDriver (KdKeyboardDriver *driver) -{ - KdKeyboardDriver **prev; - - if (!driver) - return; - - for (prev = &kdKeyboardDrivers; *prev; prev = &(*prev)->next) { - if (*prev == driver) - return; - } - *prev = driver; -} - -void -KdRemoveKeyboardDriver (KdKeyboardDriver *driver) -{ - KdKeyboardDriver *tmp; - - if (!driver) - return; - - /* FIXME remove all keyboards using this driver */ - for (tmp = kdKeyboardDrivers; tmp; tmp = tmp->next) { - if (tmp->next == driver) - tmp->next = driver->next; - } - if (tmp == driver) - tmp = NULL; -} - -KdKeyboardInfo * -KdNewKeyboard (void) -{ - KdKeyboardInfo *ki = xcalloc(sizeof(KdKeyboardInfo), 1); - if (!ki) - return NULL; - - ki->minScanCode = 0; - ki->maxScanCode = 0; - ki->leds = 0; - ki->bellPitch = 1000; - ki->bellDuration = 200; - ki->next = NULL; - ki->options = NULL; - ki->xkbRules = strdup("base"); - ki->xkbModel = strdup("pc105"); - ki->xkbLayout = strdup("us"); - ki->xkbVariant = NULL; - ki->xkbOptions = NULL; - - return ki; -} - -int -KdAddConfigKeyboard (char *keyboard) -{ - struct KdConfigDevice **prev, *new; - - if (!keyboard) - return Success; - - new = (struct KdConfigDevice *) xcalloc(sizeof(struct KdConfigDevice), 1); - if (!new) - return BadAlloc; - - new->line = xstrdup(keyboard); - new->next = NULL; - - for (prev = &kdConfigKeyboards; *prev; prev = &(*prev)->next); - *prev = new; - - return Success; -} - -int -KdAddKeyboard (KdKeyboardInfo *ki) -{ - KdKeyboardInfo **prev; - - if (!ki) - return !Success; - - ki->dixdev = AddInputDevice(serverClient, KdKeyboardProc, TRUE); - if (!ki->dixdev) { - ErrorF("Couldn't register keyboard device %s\n", - ki->name ? ki->name : "(unnamed)"); - return !Success; - } - - ki->dixdev->deviceGrab.ActivateGrab = ActivateKeyboardGrab; - ki->dixdev->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab; - RegisterOtherDevice(ki->dixdev); - -#ifdef DEBUG - ErrorF("added keyboard %s with dix id %d\n", ki->name, ki->dixdev->id); -#endif - - for (prev = &kdKeyboards; *prev; prev = &(*prev)->next); - *prev = ki; - - return Success; -} - -void -KdRemoveKeyboard (KdKeyboardInfo *ki) -{ - KdKeyboardInfo **prev; - - if (!ki) - return; - - for (prev = &kdKeyboards; *prev; prev = &(*prev)->next) { - if (*prev == ki) { - *prev = ki->next; - break; - } - } - - KdFreeKeyboard(ki); -} - -int -KdAddConfigPointer (char *pointer) -{ - struct KdConfigDevice **prev, *new; - - if (!pointer) - return Success; - - new = (struct KdConfigDevice *) xcalloc(sizeof(struct KdConfigDevice), 1); - if (!new) - return BadAlloc; - - new->line = xstrdup(pointer); - new->next = NULL; - - for (prev = &kdConfigPointers; *prev; prev = &(*prev)->next); - *prev = new; - - return Success; -} - -int -KdAddPointer (KdPointerInfo *pi) -{ - KdPointerInfo **prev; - - if (!pi) - return Success; - - pi->mouseState = start; - pi->eventHeld = FALSE; - - pi->dixdev = AddInputDevice(serverClient, KdPointerProc, TRUE); - if (!pi->dixdev) { - ErrorF("Couldn't add pointer device %s\n", - pi->name ? pi->name : "(unnamed)"); - return BadDevice; - } - - pi->dixdev->deviceGrab.ActivateGrab = ActivatePointerGrab; - pi->dixdev->deviceGrab.DeactivateGrab = DeactivatePointerGrab; - RegisterOtherDevice(pi->dixdev); - - for (prev = &kdPointers; *prev; prev = &(*prev)->next); - *prev = pi; - - return Success; -} - -void -KdRemovePointer (KdPointerInfo *pi) -{ - KdPointerInfo **prev; - - if (!pi) - return; - - for (prev = &kdPointers; *prev; prev = &(*prev)->next) { - if (*prev == pi) { - *prev = pi->next; - break; - } - } - - KdFreePointer(pi); -} - -/* - * You can call your kdriver server with something like: - * $ ./hw/kdrive/yourserver/X :1 -mouse evdev,,device=/dev/input/event4 -keybd - * evdev,,device=/dev/input/event1,xkbmodel=abnt2,xkblayout=br - */ -static Bool -KdGetOptions (InputOption **options, char *string) -{ - InputOption *newopt = NULL, **tmpo = NULL; - int tam_key = 0; - - newopt = xcalloc(1, sizeof (InputOption)); - if (!newopt) - return FALSE; - - for (tmpo = options; *tmpo; tmpo = &(*tmpo)->next) - ; /* Hello, I'm here */ - *tmpo = newopt; - - if (strchr(string, '=')) - { - tam_key = (strchr(string, '=') - string); - newopt->key = (char *)xalloc(tam_key); - strncpy(newopt->key, string, tam_key); - newopt->key[tam_key] = '\0'; - newopt->value = xstrdup(strchr(string, '=') + 1); - } - else - { - newopt->key = xstrdup(string); - newopt->value = NULL; - } - newopt->next = NULL; - - return TRUE; -} - -static void -KdParseKbdOptions (KdKeyboardInfo *ki) -{ - InputOption *option = NULL; - - for (option = ki->options; option; option = option->next) - { - if (strcasecmp(option->key, "XkbRules") == 0) - ki->xkbRules = option->value; - else if (strcasecmp(option->key, "XkbModel") == 0) - ki->xkbModel = option->value; - else if (strcasecmp(option->key, "XkbLayout") == 0) - ki->xkbLayout = option->value; - else if (strcasecmp(option->key, "XkbVariant") == 0) - ki->xkbVariant = option->value; - else if (strcasecmp(option->key, "XkbOptions") == 0) - ki->xkbOptions = option->value; - else if (!strcasecmp (option->key, "device")) - ki->path = strdup(option->value); - else - ErrorF("Kbd option key (%s) of value (%s) not assigned!\n", - option->key, option->value); - } -} - -KdKeyboardInfo * -KdParseKeyboard (char *arg) -{ - char save[1024]; - char delim; - InputOption *options = NULL; - KdKeyboardInfo *ki = NULL; - - ki = KdNewKeyboard(); - if (!ki) - return NULL; - - ki->name = strdup("Unknown KDrive Keyboard"); - ki->path = NULL; - ki->driver = NULL; - ki->driverPrivate = NULL; - ki->next = NULL; - - if (!arg) - { - ErrorF("keybd: no arg\n"); - KdFreeKeyboard (ki); - return NULL; - } - - if (strlen (arg) >= sizeof (save)) - { - ErrorF("keybd: arg too long\n"); - KdFreeKeyboard (ki); - return NULL; - } - - arg = KdParseFindNext (arg, ",", save, &delim); - if (!save[0]) - { - ErrorF("keybd: failed on save[0]\n"); - KdFreeKeyboard (ki); - return NULL; - } - - if (strcmp (save, "auto") == 0) - ki->driverPrivate = NULL; - else - ki->driverPrivate = xstrdup(save); - - if (delim != ',') - { - return ki; - } - - arg = KdParseFindNext (arg, ",", save, &delim); - - while (delim == ',') - { - arg = KdParseFindNext (arg, ",", save, &delim); - - if (!KdGetOptions(&options, save)) - { - KdFreeKeyboard(ki); - return NULL; - } - } - - if (options) - { - ki->options = options; - KdParseKbdOptions(ki); - } - - return ki; -} - -static void -KdParsePointerOptions (KdPointerInfo *pi) -{ - InputOption *option = NULL; - - for (option = pi->options; option; option = option->next) - { - if (!strcmp (option->key, "emulatemiddle")) - pi->emulateMiddleButton = TRUE; - else if (!strcmp (option->key, "noemulatemiddle")) - pi->emulateMiddleButton = FALSE; - else if (!strcmp (option->key, "transformcoord")) - pi->transformCoordinates = TRUE; - else if (!strcmp (option->key, "rawcoord")) - pi->transformCoordinates = FALSE; - else if (!strcasecmp (option->key, "device")) - pi->path = strdup(option->value); - else if (!strcasecmp (option->key, "protocol")) - pi->protocol = strdup(option->value); - else - ErrorF("Pointer option key (%s) of value (%s) not assigned!\n", - option->key, option->value); - } -} - -KdPointerInfo * -KdParsePointer (char *arg) -{ - char save[1024]; - char delim; - KdPointerInfo *pi = NULL; - InputOption *options = NULL; - int i = 0; - - pi = KdNewPointer(); - if (!pi) - return NULL; - pi->emulateMiddleButton = kdEmulateMiddleButton; - pi->transformCoordinates = !kdRawPointerCoordinates; - pi->protocol = NULL; - pi->nButtons = 5; /* XXX should not be hardcoded */ - pi->inputClass = KD_MOUSE; - - if (!arg) - { - ErrorF("mouse: no arg\n"); - KdFreePointer (pi); - return NULL; - } - - if (strlen (arg) >= sizeof (save)) - { - ErrorF("mouse: arg too long\n"); - KdFreePointer (pi); - return NULL; - } - arg = KdParseFindNext (arg, ",", save, &delim); - if (!save[0]) - { - ErrorF("failed on save[0]\n"); - KdFreePointer (pi); - return NULL; - } - - if (strcmp(save, "auto") == 0) - pi->driverPrivate = NULL; - else - pi->driverPrivate = xstrdup(save); - - if (delim != ',') - { - return pi; - } - - arg = KdParseFindNext (arg, ",", save, &delim); - - while (delim == ',') - { - arg = KdParseFindNext (arg, ",", save, &delim); - if (save[0] == '{') - { - char *s = save + 1; - i = 0; - while (*s && *s != '}') - { - if ('1' <= *s && *s <= '0' + pi->nButtons) - pi->map[i] = *s - '0'; - else - UseMsg (); - s++; - } - } - else - { - if (!KdGetOptions(&options, save)) - { - KdFreePointer(pi); - return NULL; - } - } - } - - if (options) - { - pi->options = options; - KdParsePointerOptions(pi); - } - - return pi; -} - - -void -KdInitInput (void) -{ - KdPointerInfo *pi; - KdKeyboardInfo *ki; - struct KdConfigDevice *dev; - - kdInputEnabled = TRUE; - - for (dev = kdConfigPointers; dev; dev = dev->next) { - pi = KdParsePointer(dev->line); - if (!pi) - ErrorF("Failed to parse pointer\n"); - if (KdAddPointer(pi) != Success) - ErrorF("Failed to add pointer!\n"); - } - for (dev = kdConfigKeyboards; dev; dev = dev->next) { - ki = KdParseKeyboard(dev->line); - if (!ki) - ErrorF("Failed to parse keyboard\n"); - if (KdAddKeyboard(ki) != Success) - ErrorF("Failed to add keyboard!\n"); - } - - mieqInit(); -} - -/* - * Middle button emulation state machine - * - * Possible transitions: - * Button 1 press v1 - * Button 1 release ^1 - * Button 2 press v2 - * Button 2 release ^2 - * Button 3 press v3 - * Button 3 release ^3 - * Button other press vo - * Button other release ^o - * Mouse motion <> - * Keyboard event k - * timeout ... - * outside box <-> - * - * States: - * start - * button_1_pend - * button_1_down - * button_2_down - * button_3_pend - * button_3_down - * synthetic_2_down_13 - * synthetic_2_down_3 - * synthetic_2_down_1 - * - * Transition diagram - * - * start - * v1 -> (hold) (settimeout) button_1_pend - * ^1 -> (deliver) start - * v2 -> (deliver) button_2_down - * ^2 -> (deliever) start - * v3 -> (hold) (settimeout) button_3_pend - * ^3 -> (deliver) start - * vo -> (deliver) start - * ^o -> (deliver) start - * <> -> (deliver) start - * k -> (deliver) start - * - * button_1_pend (button 1 is down, timeout pending) - * ^1 -> (release) (deliver) start - * v2 -> (release) (deliver) button_1_down - * ^2 -> (release) (deliver) button_1_down - * v3 -> (cleartimeout) (generate v2) synthetic_2_down_13 - * ^3 -> (release) (deliver) button_1_down - * vo -> (release) (deliver) button_1_down - * ^o -> (release) (deliver) button_1_down - * <-> -> (release) (deliver) button_1_down - * <> -> (deliver) button_1_pend - * k -> (release) (deliver) button_1_down - * ... -> (release) button_1_down - * - * button_1_down (button 1 is down) - * ^1 -> (deliver) start - * v2 -> (deliver) button_1_down - * ^2 -> (deliver) button_1_down - * v3 -> (deliver) button_1_down - * ^3 -> (deliver) button_1_down - * vo -> (deliver) button_1_down - * ^o -> (deliver) button_1_down - * <> -> (deliver) button_1_down - * k -> (deliver) button_1_down - * - * button_2_down (button 2 is down) - * v1 -> (deliver) button_2_down - * ^1 -> (deliver) button_2_down - * ^2 -> (deliver) start - * v3 -> (deliver) button_2_down - * ^3 -> (deliver) button_2_down - * vo -> (deliver) button_2_down - * ^o -> (deliver) button_2_down - * <> -> (deliver) button_2_down - * k -> (deliver) button_2_down - * - * button_3_pend (button 3 is down, timeout pending) - * v1 -> (generate v2) synthetic_2_down - * ^1 -> (release) (deliver) button_3_down - * v2 -> (release) (deliver) button_3_down - * ^2 -> (release) (deliver) button_3_down - * ^3 -> (release) (deliver) start - * vo -> (release) (deliver) button_3_down - * ^o -> (release) (deliver) button_3_down - * <-> -> (release) (deliver) button_3_down - * <> -> (deliver) button_3_pend - * k -> (release) (deliver) button_3_down - * ... -> (release) button_3_down - * - * button_3_down (button 3 is down) - * v1 -> (deliver) button_3_down - * ^1 -> (deliver) button_3_down - * v2 -> (deliver) button_3_down - * ^2 -> (deliver) button_3_down - * ^3 -> (deliver) start - * vo -> (deliver) button_3_down - * ^o -> (deliver) button_3_down - * <> -> (deliver) button_3_down - * k -> (deliver) button_3_down - * - * synthetic_2_down_13 (button 1 and 3 are down) - * ^1 -> (generate ^2) synthetic_2_down_3 - * v2 -> synthetic_2_down_13 - * ^2 -> synthetic_2_down_13 - * ^3 -> (generate ^2) synthetic_2_down_1 - * vo -> (deliver) synthetic_2_down_13 - * ^o -> (deliver) synthetic_2_down_13 - * <> -> (deliver) synthetic_2_down_13 - * k -> (deliver) synthetic_2_down_13 - * - * synthetic_2_down_3 (button 3 is down) - * v1 -> (deliver) synthetic_2_down_3 - * ^1 -> (deliver) synthetic_2_down_3 - * v2 -> synthetic_2_down_3 - * ^2 -> synthetic_2_down_3 - * ^3 -> start - * vo -> (deliver) synthetic_2_down_3 - * ^o -> (deliver) synthetic_2_down_3 - * <> -> (deliver) synthetic_2_down_3 - * k -> (deliver) synthetic_2_down_3 - * - * synthetic_2_down_1 (button 1 is down) - * ^1 -> start - * v2 -> synthetic_2_down_1 - * ^2 -> synthetic_2_down_1 - * v3 -> (deliver) synthetic_2_down_1 - * ^3 -> (deliver) synthetic_2_down_1 - * vo -> (deliver) synthetic_2_down_1 - * ^o -> (deliver) synthetic_2_down_1 - * <> -> (deliver) synthetic_2_down_1 - * k -> (deliver) synthetic_2_down_1 - */ - -typedef enum _inputClass { - down_1, up_1, - down_2, up_2, - down_3, up_3, - down_o, up_o, - motion, outside_box, - keyboard, timeout, - num_input_class -} KdInputClass; - -typedef enum _inputAction { - noop, - hold, - setto, - deliver, - release, - clearto, - gen_down_2, - gen_up_2 -} KdInputAction; - -#define MAX_ACTIONS 2 - -typedef struct _inputTransition { - KdInputAction actions[MAX_ACTIONS]; - KdPointerState nextState; -} KdInputTransition; - -static const -KdInputTransition kdInputMachine[num_input_states][num_input_class] = { - /* start */ - { - { { hold, setto }, button_1_pend }, /* v1 */ - { { deliver, noop }, start }, /* ^1 */ - { { deliver, noop }, button_2_down }, /* v2 */ - { { deliver, noop }, start }, /* ^2 */ - { { hold, setto }, button_3_pend }, /* v3 */ - { { deliver, noop }, start }, /* ^3 */ - { { deliver, noop }, start }, /* vo */ - { { deliver, noop }, start }, /* ^o */ - { { deliver, noop }, start }, /* <> */ - { { deliver, noop }, start }, /* <-> */ - { { noop, noop }, start }, /* k */ - { { noop, noop }, start }, /* ... */ - }, - /* button_1_pend */ - { - { { noop, noop }, button_1_pend }, /* v1 */ - { { release, deliver }, start }, /* ^1 */ - { { release, deliver }, button_1_down }, /* v2 */ - { { release, deliver }, button_1_down }, /* ^2 */ - { { clearto, gen_down_2 }, synth_2_down_13 }, /* v3 */ - { { release, deliver }, button_1_down }, /* ^3 */ - { { release, deliver }, button_1_down }, /* vo */ - { { release, deliver }, button_1_down }, /* ^o */ - { { deliver, noop }, button_1_pend }, /* <> */ - { { release, deliver }, button_1_down }, /* <-> */ - { { noop, noop }, button_1_down }, /* k */ - { { release, noop }, button_1_down }, /* ... */ - }, - /* button_1_down */ - { - { { noop, noop }, button_1_down }, /* v1 */ - { { deliver, noop }, start }, /* ^1 */ - { { deliver, noop }, button_1_down }, /* v2 */ - { { deliver, noop }, button_1_down }, /* ^2 */ - { { deliver, noop }, button_1_down }, /* v3 */ - { { deliver, noop }, button_1_down }, /* ^3 */ - { { deliver, noop }, button_1_down }, /* vo */ - { { deliver, noop }, button_1_down }, /* ^o */ - { { deliver, noop }, button_1_down }, /* <> */ - { { deliver, noop }, button_1_down }, /* <-> */ - { { noop, noop }, button_1_down }, /* k */ - { { noop, noop }, button_1_down }, /* ... */ - }, - /* button_2_down */ - { - { { deliver, noop }, button_2_down }, /* v1 */ - { { deliver, noop }, button_2_down }, /* ^1 */ - { { noop, noop }, button_2_down }, /* v2 */ - { { deliver, noop }, start }, /* ^2 */ - { { deliver, noop }, button_2_down }, /* v3 */ - { { deliver, noop }, button_2_down }, /* ^3 */ - { { deliver, noop }, button_2_down }, /* vo */ - { { deliver, noop }, button_2_down }, /* ^o */ - { { deliver, noop }, button_2_down }, /* <> */ - { { deliver, noop }, button_2_down }, /* <-> */ - { { noop, noop }, button_2_down }, /* k */ - { { noop, noop }, button_2_down }, /* ... */ - }, - /* button_3_pend */ - { - { { clearto, gen_down_2 }, synth_2_down_13 }, /* v1 */ - { { release, deliver }, button_3_down }, /* ^1 */ - { { release, deliver }, button_3_down }, /* v2 */ - { { release, deliver }, button_3_down }, /* ^2 */ - { { release, deliver }, button_3_down }, /* v3 */ - { { release, deliver }, start }, /* ^3 */ - { { release, deliver }, button_3_down }, /* vo */ - { { release, deliver }, button_3_down }, /* ^o */ - { { deliver, noop }, button_3_pend }, /* <> */ - { { release, deliver }, button_3_down }, /* <-> */ - { { release, noop }, button_3_down }, /* k */ - { { release, noop }, button_3_down }, /* ... */ - }, - /* button_3_down */ - { - { { deliver, noop }, button_3_down }, /* v1 */ - { { deliver, noop }, button_3_down }, /* ^1 */ - { { deliver, noop }, button_3_down }, /* v2 */ - { { deliver, noop }, button_3_down }, /* ^2 */ - { { noop, noop }, button_3_down }, /* v3 */ - { { deliver, noop }, start }, /* ^3 */ - { { deliver, noop }, button_3_down }, /* vo */ - { { deliver, noop }, button_3_down }, /* ^o */ - { { deliver, noop }, button_3_down }, /* <> */ - { { deliver, noop }, button_3_down }, /* <-> */ - { { noop, noop }, button_3_down }, /* k */ - { { noop, noop }, button_3_down }, /* ... */ - }, - /* synthetic_2_down_13 */ - { - { { noop, noop }, synth_2_down_13 }, /* v1 */ - { { gen_up_2, noop }, synth_2_down_3 }, /* ^1 */ - { { noop, noop }, synth_2_down_13 }, /* v2 */ - { { noop, noop }, synth_2_down_13 }, /* ^2 */ - { { noop, noop }, synth_2_down_13 }, /* v3 */ - { { gen_up_2, noop }, synth_2_down_1 }, /* ^3 */ - { { deliver, noop }, synth_2_down_13 }, /* vo */ - { { deliver, noop }, synth_2_down_13 }, /* ^o */ - { { deliver, noop }, synth_2_down_13 }, /* <> */ - { { deliver, noop }, synth_2_down_13 }, /* <-> */ - { { noop, noop }, synth_2_down_13 }, /* k */ - { { noop, noop }, synth_2_down_13 }, /* ... */ - }, - /* synthetic_2_down_3 */ - { - { { deliver, noop }, synth_2_down_3 }, /* v1 */ - { { deliver, noop }, synth_2_down_3 }, /* ^1 */ - { { deliver, noop }, synth_2_down_3 }, /* v2 */ - { { deliver, noop }, synth_2_down_3 }, /* ^2 */ - { { noop, noop }, synth_2_down_3 }, /* v3 */ - { { noop, noop }, start }, /* ^3 */ - { { deliver, noop }, synth_2_down_3 }, /* vo */ - { { deliver, noop }, synth_2_down_3 }, /* ^o */ - { { deliver, noop }, synth_2_down_3 }, /* <> */ - { { deliver, noop }, synth_2_down_3 }, /* <-> */ - { { noop, noop }, synth_2_down_3 }, /* k */ - { { noop, noop }, synth_2_down_3 }, /* ... */ - }, - /* synthetic_2_down_1 */ - { - { { noop, noop }, synth_2_down_1 }, /* v1 */ - { { noop, noop }, start }, /* ^1 */ - { { deliver, noop }, synth_2_down_1 }, /* v2 */ - { { deliver, noop }, synth_2_down_1 }, /* ^2 */ - { { deliver, noop }, synth_2_down_1 }, /* v3 */ - { { deliver, noop }, synth_2_down_1 }, /* ^3 */ - { { deliver, noop }, synth_2_down_1 }, /* vo */ - { { deliver, noop }, synth_2_down_1 }, /* ^o */ - { { deliver, noop }, synth_2_down_1 }, /* <> */ - { { deliver, noop }, synth_2_down_1 }, /* <-> */ - { { noop, noop }, synth_2_down_1 }, /* k */ - { { noop, noop }, synth_2_down_1 }, /* ... */ - }, -}; - -#define EMULATION_WINDOW 10 -#define EMULATION_TIMEOUT 100 - -static int -KdInsideEmulationWindow (KdPointerInfo *pi, int x, int y, int z) -{ - pi->emulationDx = pi->heldEvent.x - x; - pi->emulationDy = pi->heldEvent.y - y; - - return (abs (pi->emulationDx) < EMULATION_WINDOW && - abs (pi->emulationDy) < EMULATION_WINDOW); -} - -static KdInputClass -KdClassifyInput (KdPointerInfo *pi, int type, int x, int y, int z, int b) -{ - switch (type) { - case ButtonPress: - switch (b) { - case 1: return down_1; - case 2: return down_2; - case 3: return down_3; - default: return down_o; - } - break; - case ButtonRelease: - switch (b) { - case 1: return up_1; - case 2: return up_2; - case 3: return up_3; - default: return up_o; - } - break; - case MotionNotify: - if (pi->eventHeld && !KdInsideEmulationWindow(pi, x, y, z)) - return outside_box; - else - return motion; - default: - return keyboard; - } - return keyboard; -} - -#ifdef DEBUG -char *kdStateNames[] = { - "start", - "button_1_pend", - "button_1_down", - "button_2_down", - "button_3_pend", - "button_3_down", - "synth_2_down_13", - "synth_2_down_3", - "synthetic_2_down_1", - "num_input_states" -}; - -char *kdClassNames[] = { - "down_1", "up_1", - "down_2", "up_2", - "down_3", "up_3", - "motion", "ouside_box", - "keyboard", "timeout", - "num_input_class" -}; - -char *kdActionNames[] = { - "noop", - "hold", - "setto", - "deliver", - "release", - "clearto", - "gen_down_2", - "gen_up_2", -}; -#endif /* DEBUG */ - -static void -KdQueueEvent (DeviceIntPtr pDev, InternalEvent *ev) -{ - KdAssertSigioBlocked ("KdQueueEvent"); - mieqEnqueue (pDev, ev); -} - -/* We return true if we're stealing the event. */ -static Bool -KdRunMouseMachine (KdPointerInfo *pi, KdInputClass c, int type, int x, int y, - int z, int b, int absrel) -{ - const KdInputTransition *t; - int a; - - c = KdClassifyInput(pi, type, x, y, z, b); - t = &kdInputMachine[pi->mouseState][c]; - for (a = 0; a < MAX_ACTIONS; a++) - { - switch (t->actions[a]) { - case noop: - break; - case hold: - pi->eventHeld = TRUE; - pi->emulationDx = 0; - pi->emulationDy = 0; - pi->heldEvent.type = type; - pi->heldEvent.x = x; - pi->heldEvent.y = y; - pi->heldEvent.z = z; - pi->heldEvent.flags = b; - pi->heldEvent.absrel = absrel; - return TRUE; - break; - case setto: - pi->emulationTimeout = GetTimeInMillis () + EMULATION_TIMEOUT; - pi->timeoutPending = TRUE; - break; - case deliver: - _KdEnqueuePointerEvent (pi, pi->heldEvent.type, pi->heldEvent.x, - pi->heldEvent.y, pi->heldEvent.z, - pi->heldEvent.flags, pi->heldEvent.absrel, - TRUE); - break; - case release: - pi->eventHeld = FALSE; - pi->timeoutPending = FALSE; - _KdEnqueuePointerEvent (pi, pi->heldEvent.type, pi->heldEvent.x, - pi->heldEvent.y, pi->heldEvent.z, - pi->heldEvent.flags, pi->heldEvent.absrel, - TRUE); - return TRUE; - break; - case clearto: - pi->timeoutPending = FALSE; - break; - case gen_down_2: - _KdEnqueuePointerEvent (pi, ButtonPress, x, y, z, 2, absrel, - TRUE); - pi->eventHeld = FALSE; - return TRUE; - break; - case gen_up_2: - _KdEnqueuePointerEvent (pi, ButtonRelease, x, y, z, 2, absrel, - TRUE); - return TRUE; - break; - } - } - pi->mouseState = t->nextState; - return FALSE; -} - -static int -KdHandlePointerEvent (KdPointerInfo *pi, int type, int x, int y, int z, int b, - int absrel) -{ - if (pi->emulateMiddleButton) - return KdRunMouseMachine (pi, KdClassifyInput(pi, type, x, y, z, b), - type, x, y, z, b, absrel); - return FALSE; -} - -static void -KdReceiveTimeout (KdPointerInfo *pi) -{ - KdRunMouseMachine (pi, timeout, 0, 0, 0, 0, 0, 0); -} - -/* - * kdCheckTermination - * - * This function checks for the key sequence that terminates the server. When - * detected, it sets the dispatchException flag and returns. The key sequence - * is: - * Control-Alt - * It's assumed that the server will be waken up by the caller when this - * function returns. - */ - -extern int nClients; - -void -KdReleaseAllKeys (void) -{ -#if 0 - int key, nEvents, i; - KdKeyboardInfo *ki; - - KdBlockSigio (); - - for (ki = kdKeyboards; ki; ki = ki->next) { - for (key = ki->keySyms.minKeyCode; key < ki->keySyms.maxKeyCode; - key++) { - if (key_is_down(ki->dixdev, key, KEY_POSTED | KEY_PROCESSED)) { - KdHandleKeyboardEvent(ki, KeyRelease, key); - GetEventList(&kdEvents); - nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, KeyRelease, key); - for (i = 0; i < nEvents; i++) - KdQueueEvent (ki->dixdev, (kdEvents + i)->event); - } - } - } - - KdUnblockSigio (); -#endif -} - -static void -KdCheckLock (void) -{ - KeyClassPtr keyc = NULL; - Bool isSet = FALSE, shouldBeSet = FALSE; - KdKeyboardInfo *tmp = NULL; - - for (tmp = kdKeyboards; tmp; tmp = tmp->next) { - if (tmp->LockLed && tmp->dixdev && tmp->dixdev->key) { - keyc = tmp->dixdev->key; - isSet = (tmp->leds & (1 << (tmp->LockLed-1))) != 0; - /* FIXME: Just use XKB indicators! */ - shouldBeSet = !!(XkbStateFieldFromRec(&keyc->xkbInfo->state) & LockMask); - if (isSet != shouldBeSet) - KdSetLed (tmp, tmp->LockLed, shouldBeSet); - } - } -} - -void -KdEnqueueKeyboardEvent(KdKeyboardInfo *ki, - unsigned char scan_code, - unsigned char is_up) -{ - unsigned char key_code; - KeyClassPtr keyc = NULL; - KeybdCtrl *ctrl = NULL; - int type, nEvents, i; - - if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed || !ki->dixdev->key) - return; - - keyc = ki->dixdev->key; - ctrl = &ki->dixdev->kbdfeed->ctrl; - - if (scan_code >= ki->minScanCode && scan_code <= ki->maxScanCode) - { - key_code = scan_code + KD_MIN_KEYCODE - ki->minScanCode; - - /* - * Set up this event -- the type may be modified below - */ - if (is_up) - type = KeyRelease; - else - type = KeyPress; - - GetEventList(&kdEvents); - - nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, type, key_code); - for (i = 0; i < nEvents; i++) - KdQueueEvent(ki->dixdev, (InternalEvent *)((kdEvents + i)->event)); - } - else { - ErrorF("driver %s wanted to post scancode %d outside of [%d, %d]!\n", - ki->name, scan_code, ki->minScanCode, ki->maxScanCode); - } -} - -/* - * kdEnqueuePointerEvent - * - * This function converts hardware mouse event information into X event - * information. A mouse movement event is passed off to MI to generate - * a MotionNotify event, if appropriate. Button events are created and - * passed off to MI for enqueueing. - */ - -/* FIXME do something a little more clever to deal with multiple axes here */ -void -KdEnqueuePointerEvent(KdPointerInfo *pi, unsigned long flags, int rx, int ry, - int rz) -{ - CARD32 ms; - unsigned char buttons; - int x, y, z; - int (*matrix)[3] = kdPointerMatrix.matrix; - unsigned long button; - int n; - int dixflags = 0; - - if (!pi) - return; - - ms = GetTimeInMillis(); - - /* we don't need to transform z, so we don't. */ - if (flags & KD_MOUSE_DELTA) { - if (pi->transformCoordinates) { - x = matrix[0][0] * rx + matrix[0][1] * ry; - y = matrix[1][0] * rx + matrix[1][1] * ry; - } - else { - x = rx; - y = ry; - } - } - else { - if (pi->transformCoordinates) { - x = matrix[0][0] * rx + matrix[0][1] * ry + matrix[0][2]; - y = matrix[1][0] * rx + matrix[1][1] * ry + matrix[1][2]; - } - else { - x = rx; - y = ry; - } - } - z = rz; - - if (flags & KD_MOUSE_DELTA) - { - if (x || y || z) - { - dixflags = POINTER_RELATIVE | POINTER_ACCELERATE; - _KdEnqueuePointerEvent(pi, MotionNotify, x, y, z, 0, dixflags, FALSE); - } - } else - { - dixflags = POINTER_ABSOLUTE; - if (x != pi->dixdev->last.valuators[0] || - y != pi->dixdev->last.valuators[1]) - _KdEnqueuePointerEvent(pi, MotionNotify, x, y, z, 0, dixflags, FALSE); - } - - buttons = flags; - - for (button = KD_BUTTON_1, n = 1; n <= pi->nButtons; - button <<= 1, n++) { - if (((pi->buttonState & button) ^ (buttons & button)) && - !(buttons & button)) { - _KdEnqueuePointerEvent(pi, ButtonRelease, x, y, z, n, - dixflags, FALSE); - } - } - for (button = KD_BUTTON_1, n = 1; n <= pi->nButtons; - button <<= 1, n++) { - if (((pi->buttonState & button) ^ (buttons & button)) && - (buttons & button)) { - _KdEnqueuePointerEvent(pi, ButtonPress, x, y, z, n, - dixflags, FALSE); - } - } - - pi->buttonState = buttons; -} - -void -_KdEnqueuePointerEvent (KdPointerInfo *pi, int type, int x, int y, int z, - int b, int absrel, Bool force) -{ - int nEvents = 0, i = 0; - int valuators[3] = { x, y, z }; - - /* TRUE from KdHandlePointerEvent, means 'we swallowed the event'. */ - if (!force && KdHandlePointerEvent(pi, type, x, y, z, b, absrel)) - return; - - GetEventList(&kdEvents); - nEvents = GetPointerEvents(kdEvents, pi->dixdev, type, b, absrel, - 0, 3, valuators); - for (i = 0; i < nEvents; i++) - KdQueueEvent(pi->dixdev, (InternalEvent *)((kdEvents + i)->event)); -} - -void -KdBlockHandler (int screen, - pointer blockData, - pointer timeout, - pointer readmask) -{ - KdPointerInfo *pi; - int myTimeout=0; - - for (pi = kdPointers; pi; pi = pi->next) - { - if (pi->timeoutPending) - { - int ms; - - ms = pi->emulationTimeout - GetTimeInMillis (); - if (ms < 1) - ms = 1; - if(ms<myTimeout || myTimeout==0) - myTimeout=ms; - } - } - /* if we need to poll for events, do that */ - if(kdOsFuncs->pollEvents) - { - (*kdOsFuncs->pollEvents)(); - myTimeout=20; - } - if(myTimeout>0) - AdjustWaitForDelay (timeout, myTimeout); -} - -void -KdWakeupHandler (int screen, - pointer data, - unsigned long lresult, - pointer readmask) -{ - int result = (int) lresult; - fd_set *pReadmask = (fd_set *) readmask; - int i; - KdPointerInfo *pi; - - if (kdInputEnabled && result > 0) - { - for (i = 0; i < kdNumInputFds; i++) - if (FD_ISSET (kdInputFds[i].fd, pReadmask)) - { - KdBlockSigio (); - (*kdInputFds[i].read) (kdInputFds[i].fd, kdInputFds[i].closure); - KdUnblockSigio (); - } - } - for (pi = kdPointers; pi; pi = pi->next) - { - if (pi->timeoutPending) - { - if ((long) (GetTimeInMillis () - pi->emulationTimeout) >= 0) - { - pi->timeoutPending = FALSE; - KdBlockSigio (); - KdReceiveTimeout (pi); - KdUnblockSigio (); - } - } - } - if (kdSwitchPending) - KdProcessSwitch (); -} - -#define KdScreenOrigin(pScreen) (&(KdGetScreenPriv(pScreen)->screen->origin)) - -static Bool -KdCursorOffScreen(ScreenPtr *ppScreen, int *x, int *y) -{ - ScreenPtr pScreen = *ppScreen; - ScreenPtr pNewScreen; - int n; - int dx, dy; - int best_x, best_y; - int n_best_x, n_best_y; - CARD32 ms; - - if (kdDisableZaphod || screenInfo.numScreens <= 1) - return FALSE; - - if (0 <= *x && *x < pScreen->width && 0 <= *y && *y < pScreen->height) - return FALSE; - - ms = GetTimeInMillis (); - if (kdOffScreen && (int) (ms - kdOffScreenTime) < 1000) - return FALSE; - kdOffScreen = TRUE; - kdOffScreenTime = ms; - n_best_x = -1; - best_x = 32767; - n_best_y = -1; - best_y = 32767; - for (n = 0; n < screenInfo.numScreens; n++) - { - pNewScreen = screenInfo.screens[n]; - if (pNewScreen == pScreen) - continue; - dx = KdScreenOrigin(pNewScreen)->x - KdScreenOrigin(pScreen)->x; - dy = KdScreenOrigin(pNewScreen)->y - KdScreenOrigin(pScreen)->y; - if (*x < 0) - { - if (dx <= 0 && -dx < best_x) - { - best_x = -dx; - n_best_x = n; - } - } - else if (*x >= pScreen->width) - { - if (dx >= 0 && dx < best_x) - { - best_x = dx; - n_best_x = n; - } - } - if (*y < 0) - { - if (dy <= 0 && -dy < best_y) - { - best_y = -dy; - n_best_y = n; - } - } - else if (*y >= pScreen->height) - { - if (dy >= 0 && dy < best_y) - { - best_y = dy; - n_best_y = n; - } - } - } - if (best_y < best_x) - n_best_x = n_best_y; - if (n_best_x == -1) - return FALSE; - pNewScreen = screenInfo.screens[n_best_x]; - - if (*x < 0) - *x += pNewScreen->width; - if (*y < 0) - *y += pNewScreen->height; - - if (*x >= pScreen->width) - *x -= pScreen->width; - if (*y >= pScreen->height) - *y -= pScreen->height; - - *ppScreen = pNewScreen; - return TRUE; -} - -static void -KdCrossScreen(ScreenPtr pScreen, Bool entering) -{ -#ifndef XIPAQ - if (entering) - KdEnableScreen (pScreen); - else - KdDisableScreen (pScreen); -#endif -} - -int KdCurScreen; /* current event screen */ - -static void -KdWarpCursor (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y) -{ - KdBlockSigio (); - KdCurScreen = pScreen->myNum; - miPointerWarpCursor(pDev, pScreen, x, y); - KdUnblockSigio (); -} - -miPointerScreenFuncRec kdPointerScreenFuncs = -{ - KdCursorOffScreen, - KdCrossScreen, - KdWarpCursor -}; - -void -ProcessInputEvents (void) -{ - mieqProcessInputEvents(); - miPointerUpdateSprite(inputInfo.pointer); - if (kdSwitchPending) - KdProcessSwitch (); - KdCheckLock (); -} - -/* FIXME use XSECURITY to work out whether the client should be allowed to - * open and close. */ -void -OpenInputDevice(DeviceIntPtr pDev, ClientPtr client, int *status) -{ - if (!pDev) - *status = BadDevice; - else - *status = Success; -} - -void -CloseInputDevice(DeviceIntPtr pDev, ClientPtr client) -{ - return; -} - -/* We initialise all input devices at startup. */ -void -AddOtherInputDevices(void) -{ - return; -} - -/* At the moment, absolute/relative is up to the client. */ -int -SetDeviceMode(register ClientPtr client, DeviceIntPtr pDev, int mode) -{ - return BadMatch; -} - -int -SetDeviceValuators(register ClientPtr client, DeviceIntPtr pDev, - int *valuators, int first_valuator, int num_valuators) -{ - return BadMatch; -} - -int -ChangeDeviceControl(register ClientPtr client, DeviceIntPtr pDev, - xDeviceCtl *control) -{ - switch (control->control) { - case DEVICE_RESOLUTION: - /* FIXME do something more intelligent here */ - return BadMatch; - - case DEVICE_ABS_CALIB: - case DEVICE_ABS_AREA: - return Success; - - case DEVICE_CORE: - return BadMatch; - case DEVICE_ENABLE: - return Success; - - default: - return BadMatch; - } - - /* NOTREACHED */ - return BadImplementation; -} - -int -NewInputDeviceRequest(InputOption *options, DeviceIntPtr *pdev) -{ - InputOption *option = NULL; - KdPointerInfo *pi = NULL; - KdKeyboardInfo *ki = NULL; - - for (option = options; option; option = option->next) { - if (strcmp(option->key, "type") == 0) { - if (strcmp(option->value, "pointer") == 0) { - pi = KdNewPointer(); - if (!pi) - return BadAlloc; - } - else if (strcmp(option->value, "keyboard") == 0) { - ki = KdNewKeyboard(); - if (!ki) - return BadAlloc; - } - else { - ErrorF("unrecognised device type!\n"); - return BadValue; - } - } -#ifdef CONFIG_HAL - else if (strcmp(option->key, "_source") == 0 && - strcmp(option->value, "server/hal") == 0) - { - ErrorF("Ignoring device from HAL.\n"); - return BadValue; - } -#endif - } - - if (!ki && !pi) { - ErrorF("unrecognised device identifier!\n"); - return BadValue; - } - - /* FIXME: change this code below to use KdParseKbdOptions and - * KdParsePointerOptions */ - for (option = options; option; option = option->next) { - if (strcmp(option->key, "device") == 0) { - if (pi && option->value) - pi->path = strdup(option->value); - else if (ki && option->value) - ki->path = strdup(option->value); - } - else if (strcmp(option->key, "driver") == 0) { - if (pi) { - pi->driver = KdFindPointerDriver(option->value); - if (!pi->driver) { - ErrorF("couldn't find driver!\n"); - KdFreePointer(pi); - return BadValue; - } - pi->options = options; - } - else if (ki) { - ki->driver = KdFindKeyboardDriver(option->value); - if (!ki->driver) { - ErrorF("couldn't find driver!\n"); - KdFreeKeyboard(ki); - return BadValue; - } - ki->options = options; - } - } - } - - if (pi) { - if (KdAddPointer(pi) != Success || - ActivateDevice(pi->dixdev, TRUE) != Success || - EnableDevice(pi->dixdev, TRUE) != TRUE) { - ErrorF("couldn't add or enable pointer\n"); - return BadImplementation; - } - } - else if (ki) { - if (KdAddKeyboard(ki) != Success || - ActivateDevice(ki->dixdev, TRUE) != Success || - EnableDevice(ki->dixdev, TRUE) != TRUE) { - ErrorF("couldn't add or enable keyboard\n"); - return BadImplementation; - } - } - - if (pi) { - *pdev = pi->dixdev; - } else if(ki) { - *pdev = ki->dixdev; - } - - return Success; -} - -void -DeleteInputDeviceRequest(DeviceIntPtr pDev) -{ - RemoveDevice(pDev, TRUE); -} +/*
+ * Copyright © 1999 Keith Packard
+ * Copyright © 2006 Nokia Corporation
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of the authors not be used in
+ * advertising or publicity pertaining to distribution of the software without
+ * specific, written prior permission. The authors make no
+ * representations about the suitability of this software for any purpose. It
+ * is provided "as is" without express or implied warranty.
+ *
+ * THE AUTHORS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
+ * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
+ * EVENT SHALL THE AUTHORS 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_CONFIG_H
+#include <kdrive-config.h>
+#endif
+#include "kdrive.h"
+#include "inputstr.h"
+
+#define XK_PUBLISHING
+#include <X11/keysym.h>
+#if HAVE_X11_XF86KEYSYM_H
+#include <X11/XF86keysym.h>
+#endif
+#include <signal.h>
+#include <stdio.h>
+#ifdef sun
+#include <sys/file.h> /* needed for FNONBLOCK & FASYNC */
+#endif
+
+#include "xkbsrv.h"
+
+#include <X11/extensions/XI.h>
+#include <X11/extensions/XIproto.h>
+#include "XIstubs.h" /* even though we don't use stubs. cute, no? */
+#include "exevents.h"
+#include "extinit.h"
+#include "exglobals.h"
+#include "eventstr.h"
+#include "xserver-properties.h"
+
+#define AtomFromName(x) MakeAtom(x, strlen(x), 1)
+
+struct KdConfigDevice {
+ char *line;
+ struct KdConfigDevice *next;
+};
+
+/* kdKeyboards and kdPointers hold all the real devices. */
+static KdKeyboardInfo *kdKeyboards = NULL;
+static KdPointerInfo *kdPointers = NULL;
+static struct KdConfigDevice *kdConfigKeyboards = NULL;
+static struct KdConfigDevice *kdConfigPointers = NULL;
+
+static KdKeyboardDriver *kdKeyboardDrivers = NULL;
+static KdPointerDriver *kdPointerDrivers = NULL;
+
+static EventListPtr kdEvents = NULL;
+
+static Bool kdInputEnabled;
+static Bool kdOffScreen;
+static unsigned long kdOffScreenTime;
+static KdPointerMatrix kdPointerMatrix = {
+ { { 1, 0, 0 },
+ { 0, 1, 0 } }
+};
+
+void KdResetInputMachine (void);
+
+#define KD_MAX_INPUT_FDS 8
+
+typedef struct _kdInputFd {
+ int fd;
+ void (*read) (int fd, void *closure);
+ int (*enable) (int fd, void *closure);
+ void (*disable) (int fd, void *closure);
+ void *closure;
+} KdInputFd;
+
+static KdInputFd kdInputFds[KD_MAX_INPUT_FDS];
+static int kdNumInputFds;
+
+extern Bool kdRawPointerCoordinates;
+
+static void
+KdSigio (int sig)
+{
+ int i;
+
+ for (i = 0; i < kdNumInputFds; i++)
+ (*kdInputFds[i].read) (kdInputFds[i].fd, kdInputFds[i].closure);
+}
+
+static void
+KdBlockSigio (void)
+{
+#ifdef _MSC_VER
+ __asm int 3;
+#else
+ sigset_t set;
+
+ sigemptyset (&set);
+ sigaddset (&set, SIGIO);
+ sigprocmask (SIG_BLOCK, &set, 0);
+#endif
+}
+
+static void
+KdUnblockSigio (void)
+{
+#ifdef _MSC_VER
+ __asm int 3;
+#else
+ sigset_t set;
+
+ sigemptyset (&set);
+ sigaddset (&set, SIGIO);
+ sigprocmask (SIG_UNBLOCK, &set, 0);
+#endif
+}
+
+#ifdef DEBUG_SIGIO
+
+void
+KdAssertSigioBlocked (char *where)
+{
+ sigset_t set, old;
+
+ sigemptyset (&set);
+ sigprocmask (SIG_BLOCK, &set, &old);
+ if (!sigismember (&old, SIGIO)) {
+ ErrorF ("SIGIO not blocked at %s\n", where);
+ KdBacktrace(0);
+ }
+}
+
+#else
+
+#define KdAssertSigioBlocked(s)
+
+#endif
+
+static int kdnFds;
+
+#ifdef FNONBLOCK
+#define NOBLOCK FNONBLOCK
+#else
+#define NOBLOCK FNDELAY
+#endif
+
+void
+KdResetInputMachine (void)
+{
+ KdPointerInfo *pi;
+
+ for (pi = kdPointers; pi; pi = pi->next) {
+ pi->mouseState = start;
+ pi->eventHeld = FALSE;
+ }
+}
+
+static void
+KdNonBlockFd (int fd)
+{
+#ifdef _MSC_VER
+ __asm int 3;
+#else
+ int flags;
+ flags = fcntl (fd, F_GETFL);
+ flags |= FASYNC|NOBLOCK;
+ fcntl (fd, F_SETFL, flags);
+#endif
+}
+
+static void
+KdAddFd (int fd)
+{
+#ifdef _MSC_VER
+ __asm int 3;
+#else
+ struct sigaction act;
+ sigset_t set;
+
+ kdnFds++;
+ fcntl (fd, F_SETOWN, getpid());
+ KdNonBlockFd (fd);
+ AddEnabledDevice (fd);
+ memset (&act, '\0', sizeof act);
+ act.sa_handler = KdSigio;
+ sigemptyset (&act.sa_mask);
+ sigaddset (&act.sa_mask, SIGIO);
+ sigaddset (&act.sa_mask, SIGALRM);
+ sigaddset (&act.sa_mask, SIGVTALRM);
+ sigaction (SIGIO, &act, 0);
+ sigemptyset (&set);
+ sigprocmask (SIG_SETMASK, &set, 0);
+#endif
+}
+
+static void
+KdRemoveFd (int fd)
+{
+#ifdef _MSC_VER
+ __asm int 3;
+#else
+ struct sigaction act;
+ int flags;
+
+ kdnFds--;
+ RemoveEnabledDevice (fd);
+ flags = fcntl (fd, F_GETFL);
+ flags &= ~(FASYNC|NOBLOCK);
+ fcntl (fd, F_SETFL, flags);
+ if (kdnFds == 0)
+ {
+ memset (&act, '\0', sizeof act);
+ act.sa_handler = SIG_IGN;
+ sigemptyset (&act.sa_mask);
+ sigaction (SIGIO, &act, 0);
+ }
+#endif
+}
+
+Bool
+KdRegisterFd (int fd, void (*read) (int fd, void *closure), void *closure)
+{
+ if (kdNumInputFds == KD_MAX_INPUT_FDS)
+ return FALSE;
+ kdInputFds[kdNumInputFds].fd = fd;
+ kdInputFds[kdNumInputFds].read = read;
+ kdInputFds[kdNumInputFds].enable = 0;
+ kdInputFds[kdNumInputFds].disable = 0;
+ kdInputFds[kdNumInputFds].closure = closure;
+ kdNumInputFds++;
+ if (kdInputEnabled)
+ KdAddFd (fd);
+ return TRUE;
+}
+
+void
+KdUnregisterFd (void *closure, int fd, Bool do_close)
+{
+ int i, j;
+
+ for (i = 0; i < kdNumInputFds; i++) {
+ if (kdInputFds[i].closure == closure &&
+ (fd == -1 || kdInputFds[i].fd == fd)) {
+ if (kdInputEnabled)
+ KdRemoveFd (kdInputFds[i].fd);
+ if (do_close)
+ close (kdInputFds[i].fd);
+ kdNumInputFds--;
+ for (j = i; j < kdNumInputFds; j++)
+ kdInputFds[j] = kdInputFds[j+1];
+ break;
+ }
+ }
+}
+
+void
+KdUnregisterFds (void *closure, Bool do_close)
+{
+ KdUnregisterFd(closure, -1, do_close);
+}
+
+void
+KdDisableInput (void)
+{
+ KdKeyboardInfo *ki;
+ KdPointerInfo *pi;
+ int found = 0, i = 0;
+
+ KdBlockSigio();
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->driver && ki->driver->Disable)
+ (*ki->driver->Disable) (ki);
+ }
+
+ for (pi = kdPointers; pi; pi = pi->next) {
+ if (pi->driver && pi->driver->Disable)
+ (*pi->driver->Disable) (pi);
+ }
+
+ if (kdNumInputFds) {
+ ErrorF("[KdDisableInput] Buggy drivers: still %d input fds left!",
+ kdNumInputFds);
+ i = 0;
+ while (i < kdNumInputFds) {
+ found = 0;
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki == kdInputFds[i].closure) {
+ ErrorF(" fd %d belongs to keybd driver %s\n",
+ kdInputFds[i].fd,
+ ki->driver && ki->driver->name ?
+ ki->driver->name : "(unnamed!)");
+ found = 1;
+ break;
+ }
+ }
+
+ if (found) {
+ i++;
+ continue;
+ }
+
+ for (pi = kdPointers; pi; pi = pi->next) {
+ if (pi == kdInputFds[i].closure) {
+ ErrorF(" fd %d belongs to pointer driver %s\n",
+ kdInputFds[i].fd,
+ pi->driver && pi->driver->name ?
+ pi->driver->name : "(unnamed!)");
+ break;
+ }
+ }
+
+ if (found) {
+ i++;
+ continue;
+ }
+
+ ErrorF(" fd %d not claimed by any active device!\n",
+ kdInputFds[i].fd);
+ KdUnregisterFd(kdInputFds[i].closure, kdInputFds[i].fd, TRUE);
+ }
+ }
+
+ kdInputEnabled = FALSE;
+}
+
+void
+KdEnableInput (void)
+{
+ InternalEvent ev;
+ KdKeyboardInfo *ki;
+ KdPointerInfo *pi;
+
+ kdInputEnabled = TRUE;
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->driver && ki->driver->Enable)
+ (*ki->driver->Enable) (ki);
+ }
+
+ for (pi = kdPointers; pi; pi = pi->next) {
+ if (pi->driver && pi->driver->Enable)
+ (*pi->driver->Enable) (pi);
+ }
+
+ /* reset screen saver */
+ ev.any.time = GetTimeInMillis ();
+ NoticeEventTime (&ev);
+
+ KdUnblockSigio ();
+}
+
+static KdKeyboardDriver *
+KdFindKeyboardDriver (char *name)
+{
+ KdKeyboardDriver *ret;
+
+ /* ask a stupid question ... */
+ if (!name)
+ return NULL;
+
+ for (ret = kdKeyboardDrivers; ret; ret = ret->next) {
+ if (strcmp(ret->name, name) == 0)
+ return ret;
+ }
+
+ return NULL;
+}
+
+static KdPointerDriver *
+KdFindPointerDriver (char *name)
+{
+ KdPointerDriver *ret;
+
+ /* ask a stupid question ... */
+ if (!name)
+ return NULL;
+
+ for (ret = kdPointerDrivers; ret; ret = ret->next) {
+ if (strcmp(ret->name, name) == 0)
+ return ret;
+ }
+
+ return NULL;
+}
+
+static int
+KdPointerProc(DeviceIntPtr pDevice, int onoff)
+{
+ DevicePtr pDev = (DevicePtr)pDevice;
+ KdPointerInfo *pi;
+ Atom xiclass;
+ Atom *btn_labels;
+ Atom *axes_labels;
+
+ if (!pDev)
+ return BadImplementation;
+
+ for (pi = kdPointers; pi; pi = pi->next) {
+ if (pi->dixdev && pi->dixdev->id == pDevice->id)
+ break;
+ }
+
+ if (!pi || !pi->dixdev || pi->dixdev->id != pDevice->id) {
+ ErrorF("[KdPointerProc] Failed to find pointer for device %d!\n",
+ pDevice->id);
+ return BadImplementation;
+ }
+
+ switch (onoff)
+ {
+ case DEVICE_INIT:
+#ifdef DEBUG
+ ErrorF("initialising pointer %s ...\n", pi->name);
+#endif
+ if (!pi->driver) {
+ if (!pi->driverPrivate) {
+ ErrorF("no driver specified for %s\n", pi->name);
+ return BadImplementation;
+ }
+
+ pi->driver = KdFindPointerDriver(pi->driverPrivate);
+ if (!pi->driver) {
+ ErrorF("Couldn't find pointer driver %s\n",
+ pi->driverPrivate ? (char *) pi->driverPrivate :
+ "(unnamed)");
+ return !Success;
+ }
+ xfree(pi->driverPrivate);
+ pi->driverPrivate = NULL;
+ }
+
+ if (!pi->driver->Init) {
+ ErrorF("no init function\n");
+ return BadImplementation;
+ }
+
+ if ((*pi->driver->Init) (pi) != Success) {
+ return !Success;
+ }
+
+ btn_labels = xcalloc(pi->nButtons, sizeof(Atom));
+ if (!btn_labels)
+ return BadAlloc;
+ axes_labels = xcalloc(pi->nAxes, sizeof(Atom));
+ if (!axes_labels) {
+ xfree(btn_labels);
+ return BadAlloc;
+ }
+
+ switch(pi->nAxes)
+ {
+ default:
+ case 7:
+ btn_labels[6] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_RIGHT);
+ case 6:
+ btn_labels[5] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_HWHEEL_LEFT);
+ case 5:
+ btn_labels[4] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_DOWN);
+ case 4:
+ btn_labels[3] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_WHEEL_UP);
+ case 3:
+ btn_labels[2] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_RIGHT);
+ case 2:
+ btn_labels[1] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_MIDDLE);
+ case 1:
+ btn_labels[0] = XIGetKnownProperty(BTN_LABEL_PROP_BTN_LEFT);
+ case 0:
+ break;
+ }
+
+ if (pi->nAxes >= 2) {
+ axes_labels[0] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_X);
+ axes_labels[1] = XIGetKnownProperty(AXIS_LABEL_PROP_REL_Y);
+ }
+
+ InitPointerDeviceStruct(pDev, pi->map, pi->nButtons, btn_labels,
+ (PtrCtrlProcPtr)NoopDDA,
+ GetMotionHistorySize(), pi->nAxes, axes_labels);
+
+ xfree(btn_labels);
+ xfree(axes_labels);
+
+ if (pi->inputClass == KD_TOUCHSCREEN) {
+ InitAbsoluteClassDeviceStruct(pDevice);
+ xiclass = AtomFromName(XI_TOUCHSCREEN);
+ }
+ else {
+ xiclass = AtomFromName(XI_MOUSE);
+ }
+
+ AssignTypeAndName(pi->dixdev, xiclass,
+ pi->name ? pi->name : "Generic KDrive Pointer");
+
+ return Success;
+
+ case DEVICE_ON:
+ if (pDev->on == TRUE)
+ return Success;
+
+ if (!pi->driver->Enable) {
+ ErrorF("no enable function\n");
+ return BadImplementation;
+ }
+
+ if ((*pi->driver->Enable) (pi) == Success) {
+ pDev->on = TRUE;
+ return Success;
+ }
+ else {
+ return BadImplementation;
+ }
+
+ return Success;
+
+ case DEVICE_OFF:
+ if (pDev->on == FALSE) {
+ return Success;
+ }
+
+ if (!pi->driver->Disable) {
+ return BadImplementation;
+ }
+ else {
+ (*pi->driver->Disable) (pi);
+ pDev->on = FALSE;
+ return Success;
+ }
+
+ return Success;
+
+ case DEVICE_CLOSE:
+ if (pDev->on) {
+ if (!pi->driver->Disable) {
+ return BadImplementation;
+ }
+ (*pi->driver->Disable) (pi);
+ pDev->on = FALSE;
+ }
+
+ if (!pi->driver->Fini)
+ return BadImplementation;
+
+ (*pi->driver->Fini) (pi);
+
+ KdRemovePointer(pi);
+
+ return Success;
+ }
+
+ /* NOTREACHED */
+ return BadImplementation;
+}
+
+#ifndef _MSC_VER
+Bool
+LegalModifier(unsigned int key, DeviceIntPtr pDev)
+{
+ return TRUE;
+}
+#endif
+
+static void
+KdBell (int volume, DeviceIntPtr pDev, pointer arg, int something)
+{
+ KeybdCtrl *ctrl = arg;
+ KdKeyboardInfo *ki = NULL;
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->dixdev && ki->dixdev->id == pDev->id)
+ break;
+ }
+
+ if (!ki || !ki->dixdev || ki->dixdev->id != pDev->id || !ki->driver)
+ return;
+
+ KdRingBell(ki, volume, ctrl->bell_pitch, ctrl->bell_duration);
+}
+
+#ifndef _MSC_VER
+void
+DDXRingBell(int volume, int pitch, int duration)
+{
+ KdKeyboardInfo *ki = NULL;
+
+ if (kdOsFuncs->Bell) {
+ (*kdOsFuncs->Bell)(volume, pitch, duration);
+ }
+ else {
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->dixdev->coreEvents)
+ KdRingBell(ki, volume, pitch, duration);
+ }
+ }
+}
+#endif
+void
+KdRingBell(KdKeyboardInfo *ki, int volume, int pitch, int duration)
+{
+ if (!ki || !ki->driver || !ki->driver->Bell)
+ return;
+
+ if (kdInputEnabled)
+ (*ki->driver->Bell) (ki, volume, pitch, duration);
+}
+
+
+static void
+KdSetLeds (KdKeyboardInfo *ki, int leds)
+{
+ if (!ki || !ki->driver)
+ return;
+
+ if (kdInputEnabled) {
+ if (ki->driver->Leds)
+ (*ki->driver->Leds) (ki, leds);
+ }
+}
+
+void
+KdSetLed (KdKeyboardInfo *ki, int led, Bool on)
+{
+ if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed)
+ return;
+
+ NoteLedState (ki->dixdev, led, on);
+ KdSetLeds (ki, ki->dixdev->kbdfeed->ctrl.leds);
+}
+
+void
+KdSetPointerMatrix (KdPointerMatrix *matrix)
+{
+ kdPointerMatrix = *matrix;
+}
+
+void
+KdComputePointerMatrix (KdPointerMatrix *m, Rotation randr, int width,
+ int height)
+{
+ int x_dir = 1, y_dir = 1;
+ int i, j;
+ int size[2];
+
+ size[0] = width; size[1] = height;
+ if (randr & RR_Reflect_X)
+ x_dir = -1;
+ if (randr & RR_Reflect_Y)
+ y_dir = -1;
+ switch (randr & (RR_Rotate_All)) {
+ case RR_Rotate_0:
+ m->matrix[0][0] = x_dir; m->matrix[0][1] = 0;
+ m->matrix[1][0] = 0; m->matrix[1][1] = y_dir;
+ break;
+ case RR_Rotate_90:
+ m->matrix[0][0] = 0; m->matrix[0][1] = -x_dir;
+ m->matrix[1][0] = y_dir; m->matrix[1][1] = 0;
+ break;
+ case RR_Rotate_180:
+ m->matrix[0][0] = -x_dir; m->matrix[0][1] = 0;
+ m->matrix[1][0] = 0; m->matrix[1][1] = -y_dir;
+ break;
+ case RR_Rotate_270:
+ m->matrix[0][0] = 0; m->matrix[0][1] = x_dir;
+ m->matrix[1][0] = -y_dir; m->matrix[1][1] = 0;
+ break;
+ }
+ for (i = 0; i < 2; i++)
+ {
+ m->matrix[i][2] = 0;
+ for (j = 0 ; j < 2; j++)
+ if (m->matrix[i][j] < 0)
+ m->matrix[i][2] = size[j] - 1;
+ }
+}
+
+void
+KdScreenToPointerCoords (int *x, int *y)
+{
+ int (*m)[3] = kdPointerMatrix.matrix;
+ int div = m[0][1] * m[1][0] - m[1][1] * m[0][0];
+ int sx = *x;
+ int sy = *y;
+
+ *x = (m[0][1] * sy - m[0][1] * m[1][2] + m[1][1] * m[0][2] - m[1][1] * sx) / div;
+ *y = (m[1][0] * sx + m[0][0] * m[1][2] - m[1][0] * m[0][2] - m[0][0] * sy) / div;
+}
+
+static void
+KdKbdCtrl (DeviceIntPtr pDevice, KeybdCtrl *ctrl)
+{
+ KdKeyboardInfo *ki;
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->dixdev && ki->dixdev->id == pDevice->id)
+ break;
+ }
+
+ if (!ki || !ki->dixdev || ki->dixdev->id != pDevice->id || !ki->driver)
+ return;
+
+ KdSetLeds(ki, ctrl->leds);
+ ki->bellPitch = ctrl->bell_pitch;
+ ki->bellDuration = ctrl->bell_duration;
+}
+
+extern KeybdCtrl defaultKeyboardControl;
+
+static int
+KdKeyboardProc(DeviceIntPtr pDevice, int onoff)
+{
+ Bool ret;
+ DevicePtr pDev = (DevicePtr)pDevice;
+ KdKeyboardInfo *ki;
+ Atom xiclass;
+ XkbRMLVOSet rmlvo;
+
+ if (!pDev)
+ return BadImplementation;
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ if (ki->dixdev && ki->dixdev->id == pDevice->id)
+ break;
+ }
+
+ if (!ki || !ki->dixdev || ki->dixdev->id != pDevice->id) {
+ return BadImplementation;
+ }
+
+ switch (onoff)
+ {
+ case DEVICE_INIT:
+#ifdef DEBUG
+ ErrorF("initialising keyboard %s\n", ki->name);
+#endif
+ if (!ki->driver) {
+ if (!ki->driverPrivate) {
+ ErrorF("no driver specified!\n");
+ return BadImplementation;
+ }
+
+ ki->driver = KdFindKeyboardDriver(ki->driverPrivate);
+ if (!ki->driver) {
+ ErrorF("Couldn't find keyboard driver %s\n",
+ ki->driverPrivate ? (char *) ki->driverPrivate :
+ "(unnamed)");
+ return !Success;
+ }
+ xfree(ki->driverPrivate);
+ ki->driverPrivate = NULL;
+ }
+
+ if (!ki->driver->Init) {
+ ErrorF("Keyboard %s: no init function\n", ki->name);
+ return BadImplementation;
+ }
+
+ if ((*ki->driver->Init) (ki) != Success) {
+ return !Success;
+ }
+
+ memset(&rmlvo, 0, sizeof(rmlvo));
+ rmlvo.rules = ki->xkbRules;
+ rmlvo.model = ki->xkbModel;
+ rmlvo.layout = ki->xkbLayout;
+ rmlvo.variant = ki->xkbVariant;
+ rmlvo.options = ki->xkbOptions;
+ ret = InitKeyboardDeviceStruct (pDevice, &rmlvo, KdBell, KdKbdCtrl);
+ if (!ret) {
+ ErrorF("Couldn't initialise keyboard %s\n", ki->name);
+ return BadImplementation;
+ }
+
+ xiclass = AtomFromName(XI_KEYBOARD);
+ AssignTypeAndName(pDevice, xiclass,
+ ki->name ? ki->name : "Generic KDrive Keyboard");
+
+ KdResetInputMachine();
+
+ return Success;
+
+ case DEVICE_ON:
+ if (pDev->on == TRUE)
+ return Success;
+
+ if (!ki->driver->Enable)
+ return BadImplementation;
+
+ if ((*ki->driver->Enable) (ki) != Success) {
+ return BadMatch;
+ }
+
+ pDev->on = TRUE;
+ return Success;
+
+ case DEVICE_OFF:
+ if (pDev->on == FALSE)
+ return Success;
+
+ if (!ki->driver->Disable)
+ return BadImplementation;
+
+ (*ki->driver->Disable) (ki);
+ pDev->on = FALSE;
+
+ return Success;
+
+ break;
+
+ case DEVICE_CLOSE:
+ if (pDev->on) {
+ if (!ki->driver->Disable)
+ return BadImplementation;
+
+ (*ki->driver->Disable) (ki);
+ pDev->on = FALSE;
+ }
+
+ if (!ki->driver->Fini)
+ return BadImplementation;
+
+ (*ki->driver->Fini) (ki);
+
+ KdRemoveKeyboard(ki);
+
+ return Success;
+ }
+
+ /* NOTREACHED */
+ return BadImplementation;
+}
+
+void
+KdAddPointerDriver (KdPointerDriver *driver)
+{
+ KdPointerDriver **prev;
+
+ if (!driver)
+ return;
+
+ for (prev = &kdPointerDrivers; *prev; prev = &(*prev)->next) {
+ if (*prev == driver)
+ return;
+ }
+ *prev = driver;
+}
+
+void
+KdRemovePointerDriver (KdPointerDriver *driver)
+{
+ KdPointerDriver *tmp;
+
+ if (!driver)
+ return;
+
+ /* FIXME remove all pointers using this driver */
+ for (tmp = kdPointerDrivers; tmp; tmp = tmp->next) {
+ if (tmp->next == driver)
+ tmp->next = driver->next;
+ }
+ if (tmp == driver)
+ tmp = NULL;
+}
+
+void
+KdAddKeyboardDriver (KdKeyboardDriver *driver)
+{
+ KdKeyboardDriver **prev;
+
+ if (!driver)
+ return;
+
+ for (prev = &kdKeyboardDrivers; *prev; prev = &(*prev)->next) {
+ if (*prev == driver)
+ return;
+ }
+ *prev = driver;
+}
+
+void
+KdRemoveKeyboardDriver (KdKeyboardDriver *driver)
+{
+ KdKeyboardDriver *tmp;
+
+ if (!driver)
+ return;
+
+ /* FIXME remove all keyboards using this driver */
+ for (tmp = kdKeyboardDrivers; tmp; tmp = tmp->next) {
+ if (tmp->next == driver)
+ tmp->next = driver->next;
+ }
+ if (tmp == driver)
+ tmp = NULL;
+}
+
+KdKeyboardInfo *
+KdNewKeyboard (void)
+{
+ KdKeyboardInfo *ki = xcalloc(sizeof(KdKeyboardInfo), 1);
+ if (!ki)
+ return NULL;
+
+ ki->minScanCode = 0;
+ ki->maxScanCode = 0;
+ ki->leds = 0;
+ ki->bellPitch = 1000;
+ ki->bellDuration = 200;
+ ki->next = NULL;
+ ki->options = NULL;
+ ki->xkbRules = strdup("base");
+ ki->xkbModel = strdup("pc105");
+ ki->xkbLayout = strdup("us");
+ ki->xkbVariant = NULL;
+ ki->xkbOptions = NULL;
+
+ return ki;
+}
+
+int
+KdAddConfigKeyboard (char *keyboard)
+{
+ struct KdConfigDevice **prev, *new;
+
+ if (!keyboard)
+ return Success;
+
+ new = (struct KdConfigDevice *) xcalloc(sizeof(struct KdConfigDevice), 1);
+ if (!new)
+ return BadAlloc;
+
+ new->line = xstrdup(keyboard);
+ new->next = NULL;
+
+ for (prev = &kdConfigKeyboards; *prev; prev = &(*prev)->next);
+ *prev = new;
+
+ return Success;
+}
+
+int
+KdAddKeyboard (KdKeyboardInfo *ki)
+{
+ KdKeyboardInfo **prev;
+
+ if (!ki)
+ return !Success;
+
+ ki->dixdev = AddInputDevice(serverClient, KdKeyboardProc, TRUE);
+ if (!ki->dixdev) {
+ ErrorF("Couldn't register keyboard device %s\n",
+ ki->name ? ki->name : "(unnamed)");
+ return !Success;
+ }
+
+ ki->dixdev->deviceGrab.ActivateGrab = ActivateKeyboardGrab;
+ ki->dixdev->deviceGrab.DeactivateGrab = DeactivateKeyboardGrab;
+ RegisterOtherDevice(ki->dixdev);
+
+#ifdef DEBUG
+ ErrorF("added keyboard %s with dix id %d\n", ki->name, ki->dixdev->id);
+#endif
+
+ for (prev = &kdKeyboards; *prev; prev = &(*prev)->next);
+ *prev = ki;
+
+ return Success;
+}
+
+void
+KdRemoveKeyboard (KdKeyboardInfo *ki)
+{
+ KdKeyboardInfo **prev;
+
+ if (!ki)
+ return;
+
+ for (prev = &kdKeyboards; *prev; prev = &(*prev)->next) {
+ if (*prev == ki) {
+ *prev = ki->next;
+ break;
+ }
+ }
+
+ KdFreeKeyboard(ki);
+}
+
+int
+KdAddConfigPointer (char *pointer)
+{
+ struct KdConfigDevice **prev, *new;
+
+ if (!pointer)
+ return Success;
+
+ new = (struct KdConfigDevice *) xcalloc(sizeof(struct KdConfigDevice), 1);
+ if (!new)
+ return BadAlloc;
+
+ new->line = xstrdup(pointer);
+ new->next = NULL;
+
+ for (prev = &kdConfigPointers; *prev; prev = &(*prev)->next);
+ *prev = new;
+
+ return Success;
+}
+
+int
+KdAddPointer (KdPointerInfo *pi)
+{
+ KdPointerInfo **prev;
+
+ if (!pi)
+ return Success;
+
+ pi->mouseState = start;
+ pi->eventHeld = FALSE;
+
+ pi->dixdev = AddInputDevice(serverClient, KdPointerProc, TRUE);
+ if (!pi->dixdev) {
+ ErrorF("Couldn't add pointer device %s\n",
+ pi->name ? pi->name : "(unnamed)");
+ return BadDevice;
+ }
+
+ pi->dixdev->deviceGrab.ActivateGrab = ActivatePointerGrab;
+ pi->dixdev->deviceGrab.DeactivateGrab = DeactivatePointerGrab;
+ RegisterOtherDevice(pi->dixdev);
+
+ for (prev = &kdPointers; *prev; prev = &(*prev)->next);
+ *prev = pi;
+
+ return Success;
+}
+
+void
+KdRemovePointer (KdPointerInfo *pi)
+{
+ KdPointerInfo **prev;
+
+ if (!pi)
+ return;
+
+ for (prev = &kdPointers; *prev; prev = &(*prev)->next) {
+ if (*prev == pi) {
+ *prev = pi->next;
+ break;
+ }
+ }
+
+ KdFreePointer(pi);
+}
+
+/*
+ * You can call your kdriver server with something like:
+ * $ ./hw/kdrive/yourserver/X :1 -mouse evdev,,device=/dev/input/event4 -keybd
+ * evdev,,device=/dev/input/event1,xkbmodel=abnt2,xkblayout=br
+ */
+static Bool
+KdGetOptions (InputOption **options, char *string)
+{
+ InputOption *newopt = NULL, **tmpo = NULL;
+ int tam_key = 0;
+
+ newopt = xcalloc(1, sizeof (InputOption));
+ if (!newopt)
+ return FALSE;
+
+ for (tmpo = options; *tmpo; tmpo = &(*tmpo)->next)
+ ; /* Hello, I'm here */
+ *tmpo = newopt;
+
+ if (strchr(string, '='))
+ {
+ tam_key = (strchr(string, '=') - string);
+ newopt->key = (char *)xalloc(tam_key);
+ strncpy(newopt->key, string, tam_key);
+ newopt->key[tam_key] = '\0';
+ newopt->value = xstrdup(strchr(string, '=') + 1);
+ }
+ else
+ {
+ newopt->key = xstrdup(string);
+ newopt->value = NULL;
+ }
+ newopt->next = NULL;
+
+ return TRUE;
+}
+
+static void
+KdParseKbdOptions (KdKeyboardInfo *ki)
+{
+ InputOption *option = NULL;
+
+ for (option = ki->options; option; option = option->next)
+ {
+ if (strcasecmp(option->key, "XkbRules") == 0)
+ ki->xkbRules = option->value;
+ else if (strcasecmp(option->key, "XkbModel") == 0)
+ ki->xkbModel = option->value;
+ else if (strcasecmp(option->key, "XkbLayout") == 0)
+ ki->xkbLayout = option->value;
+ else if (strcasecmp(option->key, "XkbVariant") == 0)
+ ki->xkbVariant = option->value;
+ else if (strcasecmp(option->key, "XkbOptions") == 0)
+ ki->xkbOptions = option->value;
+ else if (!strcasecmp (option->key, "device"))
+ ki->path = strdup(option->value);
+ else
+ ErrorF("Kbd option key (%s) of value (%s) not assigned!\n",
+ option->key, option->value);
+ }
+}
+
+KdKeyboardInfo *
+KdParseKeyboard (char *arg)
+{
+ char save[1024];
+ char delim;
+ InputOption *options = NULL;
+ KdKeyboardInfo *ki = NULL;
+
+ ki = KdNewKeyboard();
+ if (!ki)
+ return NULL;
+
+ ki->name = strdup("Unknown KDrive Keyboard");
+ ki->path = NULL;
+ ki->driver = NULL;
+ ki->driverPrivate = NULL;
+ ki->next = NULL;
+
+ if (!arg)
+ {
+ ErrorF("keybd: no arg\n");
+ KdFreeKeyboard (ki);
+ return NULL;
+ }
+
+ if (strlen (arg) >= sizeof (save))
+ {
+ ErrorF("keybd: arg too long\n");
+ KdFreeKeyboard (ki);
+ return NULL;
+ }
+
+ arg = KdParseFindNext (arg, ",", save, &delim);
+ if (!save[0])
+ {
+ ErrorF("keybd: failed on save[0]\n");
+ KdFreeKeyboard (ki);
+ return NULL;
+ }
+
+ if (strcmp (save, "auto") == 0)
+ ki->driverPrivate = NULL;
+ else
+ ki->driverPrivate = xstrdup(save);
+
+ if (delim != ',')
+ {
+ return ki;
+ }
+
+ arg = KdParseFindNext (arg, ",", save, &delim);
+
+ while (delim == ',')
+ {
+ arg = KdParseFindNext (arg, ",", save, &delim);
+
+ if (!KdGetOptions(&options, save))
+ {
+ KdFreeKeyboard(ki);
+ return NULL;
+ }
+ }
+
+ if (options)
+ {
+ ki->options = options;
+ KdParseKbdOptions(ki);
+ }
+
+ return ki;
+}
+
+static void
+KdParsePointerOptions (KdPointerInfo *pi)
+{
+ InputOption *option = NULL;
+
+ for (option = pi->options; option; option = option->next)
+ {
+ if (!strcmp (option->key, "emulatemiddle"))
+ pi->emulateMiddleButton = TRUE;
+ else if (!strcmp (option->key, "noemulatemiddle"))
+ pi->emulateMiddleButton = FALSE;
+ else if (!strcmp (option->key, "transformcoord"))
+ pi->transformCoordinates = TRUE;
+ else if (!strcmp (option->key, "rawcoord"))
+ pi->transformCoordinates = FALSE;
+ else if (!strcasecmp (option->key, "device"))
+ pi->path = strdup(option->value);
+ else if (!strcasecmp (option->key, "protocol"))
+ pi->protocol = strdup(option->value);
+ else
+ ErrorF("Pointer option key (%s) of value (%s) not assigned!\n",
+ option->key, option->value);
+ }
+}
+
+KdPointerInfo *
+KdParsePointer (char *arg)
+{
+ char save[1024];
+ char delim;
+ KdPointerInfo *pi = NULL;
+ InputOption *options = NULL;
+ int i = 0;
+
+ pi = KdNewPointer();
+ if (!pi)
+ return NULL;
+ pi->emulateMiddleButton = kdEmulateMiddleButton;
+ pi->transformCoordinates = !kdRawPointerCoordinates;
+ pi->protocol = NULL;
+ pi->nButtons = 5; /* XXX should not be hardcoded */
+ pi->inputClass = KD_MOUSE;
+
+ if (!arg)
+ {
+ ErrorF("mouse: no arg\n");
+ KdFreePointer (pi);
+ return NULL;
+ }
+
+ if (strlen (arg) >= sizeof (save))
+ {
+ ErrorF("mouse: arg too long\n");
+ KdFreePointer (pi);
+ return NULL;
+ }
+ arg = KdParseFindNext (arg, ",", save, &delim);
+ if (!save[0])
+ {
+ ErrorF("failed on save[0]\n");
+ KdFreePointer (pi);
+ return NULL;
+ }
+
+ if (strcmp(save, "auto") == 0)
+ pi->driverPrivate = NULL;
+ else
+ pi->driverPrivate = xstrdup(save);
+
+ if (delim != ',')
+ {
+ return pi;
+ }
+
+ arg = KdParseFindNext (arg, ",", save, &delim);
+
+ while (delim == ',')
+ {
+ arg = KdParseFindNext (arg, ",", save, &delim);
+ if (save[0] == '{')
+ {
+ char *s = save + 1;
+ i = 0;
+ while (*s && *s != '}')
+ {
+ if ('1' <= *s && *s <= '0' + pi->nButtons)
+ pi->map[i] = *s - '0';
+ else
+ UseMsg ();
+ s++;
+ }
+ }
+ else
+ {
+ if (!KdGetOptions(&options, save))
+ {
+ KdFreePointer(pi);
+ return NULL;
+ }
+ }
+ }
+
+ if (options)
+ {
+ pi->options = options;
+ KdParsePointerOptions(pi);
+ }
+
+ return pi;
+}
+
+
+void
+KdInitInput (void)
+{
+ KdPointerInfo *pi;
+ KdKeyboardInfo *ki;
+ struct KdConfigDevice *dev;
+
+ kdInputEnabled = TRUE;
+
+ for (dev = kdConfigPointers; dev; dev = dev->next) {
+ pi = KdParsePointer(dev->line);
+ if (!pi)
+ ErrorF("Failed to parse pointer\n");
+ if (KdAddPointer(pi) != Success)
+ ErrorF("Failed to add pointer!\n");
+ }
+ for (dev = kdConfigKeyboards; dev; dev = dev->next) {
+ ki = KdParseKeyboard(dev->line);
+ if (!ki)
+ ErrorF("Failed to parse keyboard\n");
+ if (KdAddKeyboard(ki) != Success)
+ ErrorF("Failed to add keyboard!\n");
+ }
+
+ mieqInit();
+}
+
+/*
+ * Middle button emulation state machine
+ *
+ * Possible transitions:
+ * Button 1 press v1
+ * Button 1 release ^1
+ * Button 2 press v2
+ * Button 2 release ^2
+ * Button 3 press v3
+ * Button 3 release ^3
+ * Button other press vo
+ * Button other release ^o
+ * Mouse motion <>
+ * Keyboard event k
+ * timeout ...
+ * outside box <->
+ *
+ * States:
+ * start
+ * button_1_pend
+ * button_1_down
+ * button_2_down
+ * button_3_pend
+ * button_3_down
+ * synthetic_2_down_13
+ * synthetic_2_down_3
+ * synthetic_2_down_1
+ *
+ * Transition diagram
+ *
+ * start
+ * v1 -> (hold) (settimeout) button_1_pend
+ * ^1 -> (deliver) start
+ * v2 -> (deliver) button_2_down
+ * ^2 -> (deliever) start
+ * v3 -> (hold) (settimeout) button_3_pend
+ * ^3 -> (deliver) start
+ * vo -> (deliver) start
+ * ^o -> (deliver) start
+ * <> -> (deliver) start
+ * k -> (deliver) start
+ *
+ * button_1_pend (button 1 is down, timeout pending)
+ * ^1 -> (release) (deliver) start
+ * v2 -> (release) (deliver) button_1_down
+ * ^2 -> (release) (deliver) button_1_down
+ * v3 -> (cleartimeout) (generate v2) synthetic_2_down_13
+ * ^3 -> (release) (deliver) button_1_down
+ * vo -> (release) (deliver) button_1_down
+ * ^o -> (release) (deliver) button_1_down
+ * <-> -> (release) (deliver) button_1_down
+ * <> -> (deliver) button_1_pend
+ * k -> (release) (deliver) button_1_down
+ * ... -> (release) button_1_down
+ *
+ * button_1_down (button 1 is down)
+ * ^1 -> (deliver) start
+ * v2 -> (deliver) button_1_down
+ * ^2 -> (deliver) button_1_down
+ * v3 -> (deliver) button_1_down
+ * ^3 -> (deliver) button_1_down
+ * vo -> (deliver) button_1_down
+ * ^o -> (deliver) button_1_down
+ * <> -> (deliver) button_1_down
+ * k -> (deliver) button_1_down
+ *
+ * button_2_down (button 2 is down)
+ * v1 -> (deliver) button_2_down
+ * ^1 -> (deliver) button_2_down
+ * ^2 -> (deliver) start
+ * v3 -> (deliver) button_2_down
+ * ^3 -> (deliver) button_2_down
+ * vo -> (deliver) button_2_down
+ * ^o -> (deliver) button_2_down
+ * <> -> (deliver) button_2_down
+ * k -> (deliver) button_2_down
+ *
+ * button_3_pend (button 3 is down, timeout pending)
+ * v1 -> (generate v2) synthetic_2_down
+ * ^1 -> (release) (deliver) button_3_down
+ * v2 -> (release) (deliver) button_3_down
+ * ^2 -> (release) (deliver) button_3_down
+ * ^3 -> (release) (deliver) start
+ * vo -> (release) (deliver) button_3_down
+ * ^o -> (release) (deliver) button_3_down
+ * <-> -> (release) (deliver) button_3_down
+ * <> -> (deliver) button_3_pend
+ * k -> (release) (deliver) button_3_down
+ * ... -> (release) button_3_down
+ *
+ * button_3_down (button 3 is down)
+ * v1 -> (deliver) button_3_down
+ * ^1 -> (deliver) button_3_down
+ * v2 -> (deliver) button_3_down
+ * ^2 -> (deliver) button_3_down
+ * ^3 -> (deliver) start
+ * vo -> (deliver) button_3_down
+ * ^o -> (deliver) button_3_down
+ * <> -> (deliver) button_3_down
+ * k -> (deliver) button_3_down
+ *
+ * synthetic_2_down_13 (button 1 and 3 are down)
+ * ^1 -> (generate ^2) synthetic_2_down_3
+ * v2 -> synthetic_2_down_13
+ * ^2 -> synthetic_2_down_13
+ * ^3 -> (generate ^2) synthetic_2_down_1
+ * vo -> (deliver) synthetic_2_down_13
+ * ^o -> (deliver) synthetic_2_down_13
+ * <> -> (deliver) synthetic_2_down_13
+ * k -> (deliver) synthetic_2_down_13
+ *
+ * synthetic_2_down_3 (button 3 is down)
+ * v1 -> (deliver) synthetic_2_down_3
+ * ^1 -> (deliver) synthetic_2_down_3
+ * v2 -> synthetic_2_down_3
+ * ^2 -> synthetic_2_down_3
+ * ^3 -> start
+ * vo -> (deliver) synthetic_2_down_3
+ * ^o -> (deliver) synthetic_2_down_3
+ * <> -> (deliver) synthetic_2_down_3
+ * k -> (deliver) synthetic_2_down_3
+ *
+ * synthetic_2_down_1 (button 1 is down)
+ * ^1 -> start
+ * v2 -> synthetic_2_down_1
+ * ^2 -> synthetic_2_down_1
+ * v3 -> (deliver) synthetic_2_down_1
+ * ^3 -> (deliver) synthetic_2_down_1
+ * vo -> (deliver) synthetic_2_down_1
+ * ^o -> (deliver) synthetic_2_down_1
+ * <> -> (deliver) synthetic_2_down_1
+ * k -> (deliver) synthetic_2_down_1
+ */
+
+typedef enum _inputClass {
+ down_1, up_1,
+ down_2, up_2,
+ down_3, up_3,
+ down_o, up_o,
+ motion, outside_box,
+ keyboard, timeout,
+ num_input_class
+} KdInputClass;
+
+typedef enum _inputAction {
+ noop,
+ hold,
+ setto,
+ deliver,
+ release,
+ clearto,
+ gen_down_2,
+ gen_up_2
+} KdInputAction;
+
+#define MAX_ACTIONS 2
+
+typedef struct _inputTransition {
+ KdInputAction actions[MAX_ACTIONS];
+ KdPointerState nextState;
+} KdInputTransition;
+
+static const
+KdInputTransition kdInputMachine[num_input_states][num_input_class] = {
+ /* start */
+ {
+ { { hold, setto }, button_1_pend }, /* v1 */
+ { { deliver, noop }, start }, /* ^1 */
+ { { deliver, noop }, button_2_down }, /* v2 */
+ { { deliver, noop }, start }, /* ^2 */
+ { { hold, setto }, button_3_pend }, /* v3 */
+ { { deliver, noop }, start }, /* ^3 */
+ { { deliver, noop }, start }, /* vo */
+ { { deliver, noop }, start }, /* ^o */
+ { { deliver, noop }, start }, /* <> */
+ { { deliver, noop }, start }, /* <-> */
+ { { noop, noop }, start }, /* k */
+ { { noop, noop }, start }, /* ... */
+ },
+ /* button_1_pend */
+ {
+ { { noop, noop }, button_1_pend }, /* v1 */
+ { { release, deliver }, start }, /* ^1 */
+ { { release, deliver }, button_1_down }, /* v2 */
+ { { release, deliver }, button_1_down }, /* ^2 */
+ { { clearto, gen_down_2 }, synth_2_down_13 }, /* v3 */
+ { { release, deliver }, button_1_down }, /* ^3 */
+ { { release, deliver }, button_1_down }, /* vo */
+ { { release, deliver }, button_1_down }, /* ^o */
+ { { deliver, noop }, button_1_pend }, /* <> */
+ { { release, deliver }, button_1_down }, /* <-> */
+ { { noop, noop }, button_1_down }, /* k */
+ { { release, noop }, button_1_down }, /* ... */
+ },
+ /* button_1_down */
+ {
+ { { noop, noop }, button_1_down }, /* v1 */
+ { { deliver, noop }, start }, /* ^1 */
+ { { deliver, noop }, button_1_down }, /* v2 */
+ { { deliver, noop }, button_1_down }, /* ^2 */
+ { { deliver, noop }, button_1_down }, /* v3 */
+ { { deliver, noop }, button_1_down }, /* ^3 */
+ { { deliver, noop }, button_1_down }, /* vo */
+ { { deliver, noop }, button_1_down }, /* ^o */
+ { { deliver, noop }, button_1_down }, /* <> */
+ { { deliver, noop }, button_1_down }, /* <-> */
+ { { noop, noop }, button_1_down }, /* k */
+ { { noop, noop }, button_1_down }, /* ... */
+ },
+ /* button_2_down */
+ {
+ { { deliver, noop }, button_2_down }, /* v1 */
+ { { deliver, noop }, button_2_down }, /* ^1 */
+ { { noop, noop }, button_2_down }, /* v2 */
+ { { deliver, noop }, start }, /* ^2 */
+ { { deliver, noop }, button_2_down }, /* v3 */
+ { { deliver, noop }, button_2_down }, /* ^3 */
+ { { deliver, noop }, button_2_down }, /* vo */
+ { { deliver, noop }, button_2_down }, /* ^o */
+ { { deliver, noop }, button_2_down }, /* <> */
+ { { deliver, noop }, button_2_down }, /* <-> */
+ { { noop, noop }, button_2_down }, /* k */
+ { { noop, noop }, button_2_down }, /* ... */
+ },
+ /* button_3_pend */
+ {
+ { { clearto, gen_down_2 }, synth_2_down_13 }, /* v1 */
+ { { release, deliver }, button_3_down }, /* ^1 */
+ { { release, deliver }, button_3_down }, /* v2 */
+ { { release, deliver }, button_3_down }, /* ^2 */
+ { { release, deliver }, button_3_down }, /* v3 */
+ { { release, deliver }, start }, /* ^3 */
+ { { release, deliver }, button_3_down }, /* vo */
+ { { release, deliver }, button_3_down }, /* ^o */
+ { { deliver, noop }, button_3_pend }, /* <> */
+ { { release, deliver }, button_3_down }, /* <-> */
+ { { release, noop }, button_3_down }, /* k */
+ { { release, noop }, button_3_down }, /* ... */
+ },
+ /* button_3_down */
+ {
+ { { deliver, noop }, button_3_down }, /* v1 */
+ { { deliver, noop }, button_3_down }, /* ^1 */
+ { { deliver, noop }, button_3_down }, /* v2 */
+ { { deliver, noop }, button_3_down }, /* ^2 */
+ { { noop, noop }, button_3_down }, /* v3 */
+ { { deliver, noop }, start }, /* ^3 */
+ { { deliver, noop }, button_3_down }, /* vo */
+ { { deliver, noop }, button_3_down }, /* ^o */
+ { { deliver, noop }, button_3_down }, /* <> */
+ { { deliver, noop }, button_3_down }, /* <-> */
+ { { noop, noop }, button_3_down }, /* k */
+ { { noop, noop }, button_3_down }, /* ... */
+ },
+ /* synthetic_2_down_13 */
+ {
+ { { noop, noop }, synth_2_down_13 }, /* v1 */
+ { { gen_up_2, noop }, synth_2_down_3 }, /* ^1 */
+ { { noop, noop }, synth_2_down_13 }, /* v2 */
+ { { noop, noop }, synth_2_down_13 }, /* ^2 */
+ { { noop, noop }, synth_2_down_13 }, /* v3 */
+ { { gen_up_2, noop }, synth_2_down_1 }, /* ^3 */
+ { { deliver, noop }, synth_2_down_13 }, /* vo */
+ { { deliver, noop }, synth_2_down_13 }, /* ^o */
+ { { deliver, noop }, synth_2_down_13 }, /* <> */
+ { { deliver, noop }, synth_2_down_13 }, /* <-> */
+ { { noop, noop }, synth_2_down_13 }, /* k */
+ { { noop, noop }, synth_2_down_13 }, /* ... */
+ },
+ /* synthetic_2_down_3 */
+ {
+ { { deliver, noop }, synth_2_down_3 }, /* v1 */
+ { { deliver, noop }, synth_2_down_3 }, /* ^1 */
+ { { deliver, noop }, synth_2_down_3 }, /* v2 */
+ { { deliver, noop }, synth_2_down_3 }, /* ^2 */
+ { { noop, noop }, synth_2_down_3 }, /* v3 */
+ { { noop, noop }, start }, /* ^3 */
+ { { deliver, noop }, synth_2_down_3 }, /* vo */
+ { { deliver, noop }, synth_2_down_3 }, /* ^o */
+ { { deliver, noop }, synth_2_down_3 }, /* <> */
+ { { deliver, noop }, synth_2_down_3 }, /* <-> */
+ { { noop, noop }, synth_2_down_3 }, /* k */
+ { { noop, noop }, synth_2_down_3 }, /* ... */
+ },
+ /* synthetic_2_down_1 */
+ {
+ { { noop, noop }, synth_2_down_1 }, /* v1 */
+ { { noop, noop }, start }, /* ^1 */
+ { { deliver, noop }, synth_2_down_1 }, /* v2 */
+ { { deliver, noop }, synth_2_down_1 }, /* ^2 */
+ { { deliver, noop }, synth_2_down_1 }, /* v3 */
+ { { deliver, noop }, synth_2_down_1 }, /* ^3 */
+ { { deliver, noop }, synth_2_down_1 }, /* vo */
+ { { deliver, noop }, synth_2_down_1 }, /* ^o */
+ { { deliver, noop }, synth_2_down_1 }, /* <> */
+ { { deliver, noop }, synth_2_down_1 }, /* <-> */
+ { { noop, noop }, synth_2_down_1 }, /* k */
+ { { noop, noop }, synth_2_down_1 }, /* ... */
+ },
+};
+
+#define EMULATION_WINDOW 10
+#define EMULATION_TIMEOUT 100
+
+static int
+KdInsideEmulationWindow (KdPointerInfo *pi, int x, int y, int z)
+{
+ pi->emulationDx = pi->heldEvent.x - x;
+ pi->emulationDy = pi->heldEvent.y - y;
+
+ return (abs (pi->emulationDx) < EMULATION_WINDOW &&
+ abs (pi->emulationDy) < EMULATION_WINDOW);
+}
+
+static KdInputClass
+KdClassifyInput (KdPointerInfo *pi, int type, int x, int y, int z, int b)
+{
+ switch (type) {
+ case ButtonPress:
+ switch (b) {
+ case 1: return down_1;
+ case 2: return down_2;
+ case 3: return down_3;
+ default: return down_o;
+ }
+ break;
+ case ButtonRelease:
+ switch (b) {
+ case 1: return up_1;
+ case 2: return up_2;
+ case 3: return up_3;
+ default: return up_o;
+ }
+ break;
+ case MotionNotify:
+ if (pi->eventHeld && !KdInsideEmulationWindow(pi, x, y, z))
+ return outside_box;
+ else
+ return motion;
+ default:
+ return keyboard;
+ }
+ return keyboard;
+}
+
+#ifdef DEBUG
+char *kdStateNames[] = {
+ "start",
+ "button_1_pend",
+ "button_1_down",
+ "button_2_down",
+ "button_3_pend",
+ "button_3_down",
+ "synth_2_down_13",
+ "synth_2_down_3",
+ "synthetic_2_down_1",
+ "num_input_states"
+};
+
+char *kdClassNames[] = {
+ "down_1", "up_1",
+ "down_2", "up_2",
+ "down_3", "up_3",
+ "motion", "ouside_box",
+ "keyboard", "timeout",
+ "num_input_class"
+};
+
+char *kdActionNames[] = {
+ "noop",
+ "hold",
+ "setto",
+ "deliver",
+ "release",
+ "clearto",
+ "gen_down_2",
+ "gen_up_2",
+};
+#endif /* DEBUG */
+
+static void
+KdQueueEvent (DeviceIntPtr pDev, InternalEvent *ev)
+{
+ KdAssertSigioBlocked ("KdQueueEvent");
+ mieqEnqueue (pDev, ev);
+}
+
+/* We return true if we're stealing the event. */
+static Bool
+KdRunMouseMachine (KdPointerInfo *pi, KdInputClass c, int type, int x, int y,
+ int z, int b, int absrel)
+{
+ const KdInputTransition *t;
+ int a;
+
+ c = KdClassifyInput(pi, type, x, y, z, b);
+ t = &kdInputMachine[pi->mouseState][c];
+ for (a = 0; a < MAX_ACTIONS; a++)
+ {
+ switch (t->actions[a]) {
+ case noop:
+ break;
+ case hold:
+ pi->eventHeld = TRUE;
+ pi->emulationDx = 0;
+ pi->emulationDy = 0;
+ pi->heldEvent.type = type;
+ pi->heldEvent.x = x;
+ pi->heldEvent.y = y;
+ pi->heldEvent.z = z;
+ pi->heldEvent.flags = b;
+ pi->heldEvent.absrel = absrel;
+ return TRUE;
+ break;
+ case setto:
+ pi->emulationTimeout = GetTimeInMillis () + EMULATION_TIMEOUT;
+ pi->timeoutPending = TRUE;
+ break;
+ case deliver:
+ _KdEnqueuePointerEvent (pi, pi->heldEvent.type, pi->heldEvent.x,
+ pi->heldEvent.y, pi->heldEvent.z,
+ pi->heldEvent.flags, pi->heldEvent.absrel,
+ TRUE);
+ break;
+ case release:
+ pi->eventHeld = FALSE;
+ pi->timeoutPending = FALSE;
+ _KdEnqueuePointerEvent (pi, pi->heldEvent.type, pi->heldEvent.x,
+ pi->heldEvent.y, pi->heldEvent.z,
+ pi->heldEvent.flags, pi->heldEvent.absrel,
+ TRUE);
+ return TRUE;
+ break;
+ case clearto:
+ pi->timeoutPending = FALSE;
+ break;
+ case gen_down_2:
+ _KdEnqueuePointerEvent (pi, ButtonPress, x, y, z, 2, absrel,
+ TRUE);
+ pi->eventHeld = FALSE;
+ return TRUE;
+ break;
+ case gen_up_2:
+ _KdEnqueuePointerEvent (pi, ButtonRelease, x, y, z, 2, absrel,
+ TRUE);
+ return TRUE;
+ break;
+ }
+ }
+ pi->mouseState = t->nextState;
+ return FALSE;
+}
+
+static int
+KdHandlePointerEvent (KdPointerInfo *pi, int type, int x, int y, int z, int b,
+ int absrel)
+{
+ if (pi->emulateMiddleButton)
+ return KdRunMouseMachine (pi, KdClassifyInput(pi, type, x, y, z, b),
+ type, x, y, z, b, absrel);
+ return FALSE;
+}
+
+static void
+KdReceiveTimeout (KdPointerInfo *pi)
+{
+ KdRunMouseMachine (pi, timeout, 0, 0, 0, 0, 0, 0);
+}
+
+/*
+ * kdCheckTermination
+ *
+ * This function checks for the key sequence that terminates the server. When
+ * detected, it sets the dispatchException flag and returns. The key sequence
+ * is:
+ * Control-Alt
+ * It's assumed that the server will be waken up by the caller when this
+ * function returns.
+ */
+
+extern int nClients;
+
+void
+KdReleaseAllKeys (void)
+{
+#if 0
+ int key, nEvents, i;
+ KdKeyboardInfo *ki;
+
+ KdBlockSigio ();
+
+ for (ki = kdKeyboards; ki; ki = ki->next) {
+ for (key = ki->keySyms.minKeyCode; key < ki->keySyms.maxKeyCode;
+ key++) {
+ if (key_is_down(ki->dixdev, key, KEY_POSTED | KEY_PROCESSED)) {
+ KdHandleKeyboardEvent(ki, KeyRelease, key);
+ GetEventList(&kdEvents);
+ nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, KeyRelease, key);
+ for (i = 0; i < nEvents; i++)
+ KdQueueEvent (ki->dixdev, (kdEvents + i)->event);
+ }
+ }
+ }
+
+ KdUnblockSigio ();
+#endif
+}
+
+static void
+KdCheckLock (void)
+{
+ KeyClassPtr keyc = NULL;
+ Bool isSet = FALSE, shouldBeSet = FALSE;
+ KdKeyboardInfo *tmp = NULL;
+
+ for (tmp = kdKeyboards; tmp; tmp = tmp->next) {
+ if (tmp->LockLed && tmp->dixdev && tmp->dixdev->key) {
+ keyc = tmp->dixdev->key;
+ isSet = (tmp->leds & (1 << (tmp->LockLed-1))) != 0;
+ /* FIXME: Just use XKB indicators! */
+ shouldBeSet = !!(XkbStateFieldFromRec(&keyc->xkbInfo->state) & LockMask);
+ if (isSet != shouldBeSet)
+ KdSetLed (tmp, tmp->LockLed, shouldBeSet);
+ }
+ }
+}
+
+void
+KdEnqueueKeyboardEvent(KdKeyboardInfo *ki,
+ unsigned char scan_code,
+ unsigned char is_up)
+{
+ unsigned char key_code;
+ KeyClassPtr keyc = NULL;
+ KeybdCtrl *ctrl = NULL;
+ int type, nEvents, i;
+
+ if (!ki || !ki->dixdev || !ki->dixdev->kbdfeed || !ki->dixdev->key)
+ return;
+
+ keyc = ki->dixdev->key;
+ ctrl = &ki->dixdev->kbdfeed->ctrl;
+
+ if (scan_code >= ki->minScanCode && scan_code <= ki->maxScanCode)
+ {
+ key_code = scan_code + KD_MIN_KEYCODE - ki->minScanCode;
+
+ /*
+ * Set up this event -- the type may be modified below
+ */
+ if (is_up)
+ type = KeyRelease;
+ else
+ type = KeyPress;
+
+ GetEventList(&kdEvents);
+
+ nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, type, key_code);
+ for (i = 0; i < nEvents; i++)
+ KdQueueEvent(ki->dixdev, (InternalEvent *)((kdEvents + i)->event));
+ }
+ else {
+ ErrorF("driver %s wanted to post scancode %d outside of [%d, %d]!\n",
+ ki->name, scan_code, ki->minScanCode, ki->maxScanCode);
+ }
+}
+
+/*
+ * kdEnqueuePointerEvent
+ *
+ * This function converts hardware mouse event information into X event
+ * information. A mouse movement event is passed off to MI to generate
+ * a MotionNotify event, if appropriate. Button events are created and
+ * passed off to MI for enqueueing.
+ */
+
+/* FIXME do something a little more clever to deal with multiple axes here */
+void
+KdEnqueuePointerEvent(KdPointerInfo *pi, unsigned long flags, int rx, int ry,
+ int rz)
+{
+ CARD32 ms;
+ unsigned char buttons;
+ int x, y, z;
+ int (*matrix)[3] = kdPointerMatrix.matrix;
+ unsigned long button;
+ int n;
+ int dixflags = 0;
+
+ if (!pi)
+ return;
+
+ ms = GetTimeInMillis();
+
+ /* we don't need to transform z, so we don't. */
+ if (flags & KD_MOUSE_DELTA) {
+ if (pi->transformCoordinates) {
+ x = matrix[0][0] * rx + matrix[0][1] * ry;
+ y = matrix[1][0] * rx + matrix[1][1] * ry;
+ }
+ else {
+ x = rx;
+ y = ry;
+ }
+ }
+ else {
+ if (pi->transformCoordinates) {
+ x = matrix[0][0] * rx + matrix[0][1] * ry + matrix[0][2];
+ y = matrix[1][0] * rx + matrix[1][1] * ry + matrix[1][2];
+ }
+ else {
+ x = rx;
+ y = ry;
+ }
+ }
+ z = rz;
+
+ if (flags & KD_MOUSE_DELTA)
+ {
+ if (x || y || z)
+ {
+ dixflags = POINTER_RELATIVE | POINTER_ACCELERATE;
+ _KdEnqueuePointerEvent(pi, MotionNotify, x, y, z, 0, dixflags, FALSE);
+ }
+ } else
+ {
+ dixflags = POINTER_ABSOLUTE;
+ if (x != pi->dixdev->last.valuators[0] ||
+ y != pi->dixdev->last.valuators[1])
+ _KdEnqueuePointerEvent(pi, MotionNotify, x, y, z, 0, dixflags, FALSE);
+ }
+
+ buttons = flags;
+
+ for (button = KD_BUTTON_1, n = 1; n <= pi->nButtons;
+ button <<= 1, n++) {
+ if (((pi->buttonState & button) ^ (buttons & button)) &&
+ !(buttons & button)) {
+ _KdEnqueuePointerEvent(pi, ButtonRelease, x, y, z, n,
+ dixflags, FALSE);
+ }
+ }
+ for (button = KD_BUTTON_1, n = 1; n <= pi->nButtons;
+ button <<= 1, n++) {
+ if (((pi->buttonState & button) ^ (buttons & button)) &&
+ (buttons & button)) {
+ _KdEnqueuePointerEvent(pi, ButtonPress, x, y, z, n,
+ dixflags, FALSE);
+ }
+ }
+
+ pi->buttonState = buttons;
+}
+
+void
+_KdEnqueuePointerEvent (KdPointerInfo *pi, int type, int x, int y, int z,
+ int b, int absrel, Bool force)
+{
+ int nEvents = 0, i = 0;
+ int valuators[3] = { x, y, z };
+
+ /* TRUE from KdHandlePointerEvent, means 'we swallowed the event'. */
+ if (!force && KdHandlePointerEvent(pi, type, x, y, z, b, absrel))
+ return;
+
+ GetEventList(&kdEvents);
+ nEvents = GetPointerEvents(kdEvents, pi->dixdev, type, b, absrel,
+ 0, 3, valuators);
+ for (i = 0; i < nEvents; i++)
+ KdQueueEvent(pi->dixdev, (InternalEvent *)((kdEvents + i)->event));
+}
+
+void
+KdBlockHandler (int screen,
+ pointer blockData,
+ pointer timeout,
+ pointer readmask)
+{
+ KdPointerInfo *pi;
+ int myTimeout=0;
+
+ for (pi = kdPointers; pi; pi = pi->next)
+ {
+ if (pi->timeoutPending)
+ {
+ int ms;
+
+ ms = pi->emulationTimeout - GetTimeInMillis ();
+ if (ms < 1)
+ ms = 1;
+ if(ms<myTimeout || myTimeout==0)
+ myTimeout=ms;
+ }
+ }
+ /* if we need to poll for events, do that */
+ if(kdOsFuncs->pollEvents)
+ {
+ (*kdOsFuncs->pollEvents)();
+ myTimeout=20;
+ }
+ if(myTimeout>0)
+ AdjustWaitForDelay (timeout, myTimeout);
+}
+
+void
+KdWakeupHandler (int screen,
+ pointer data,
+ unsigned long lresult,
+ pointer readmask)
+{
+ int result = (int) lresult;
+ fd_set *pReadmask = (fd_set *) readmask;
+ int i;
+ KdPointerInfo *pi;
+
+ if (kdInputEnabled && result > 0)
+ {
+ for (i = 0; i < kdNumInputFds; i++)
+ if (FD_ISSET (kdInputFds[i].fd, pReadmask))
+ {
+ KdBlockSigio ();
+ (*kdInputFds[i].read) (kdInputFds[i].fd, kdInputFds[i].closure);
+ KdUnblockSigio ();
+ }
+ }
+ for (pi = kdPointers; pi; pi = pi->next)
+ {
+ if (pi->timeoutPending)
+ {
+ if ((long) (GetTimeInMillis () - pi->emulationTimeout) >= 0)
+ {
+ pi->timeoutPending = FALSE;
+ KdBlockSigio ();
+ KdReceiveTimeout (pi);
+ KdUnblockSigio ();
+ }
+ }
+ }
+ if (kdSwitchPending)
+ KdProcessSwitch ();
+}
+
+#define KdScreenOrigin(pScreen) (&(KdGetScreenPriv(pScreen)->screen->origin))
+
+static Bool
+KdCursorOffScreen(ScreenPtr *ppScreen, int *x, int *y)
+{
+ ScreenPtr pScreen = *ppScreen;
+ ScreenPtr pNewScreen;
+ int n;
+ int dx, dy;
+ int best_x, best_y;
+ int n_best_x, n_best_y;
+ CARD32 ms;
+
+ if (kdDisableZaphod || screenInfo.numScreens <= 1)
+ return FALSE;
+
+ if (0 <= *x && *x < pScreen->width && 0 <= *y && *y < pScreen->height)
+ return FALSE;
+
+ ms = GetTimeInMillis ();
+ if (kdOffScreen && (int) (ms - kdOffScreenTime) < 1000)
+ return FALSE;
+ kdOffScreen = TRUE;
+ kdOffScreenTime = ms;
+ n_best_x = -1;
+ best_x = 32767;
+ n_best_y = -1;
+ best_y = 32767;
+ for (n = 0; n < screenInfo.numScreens; n++)
+ {
+ pNewScreen = screenInfo.screens[n];
+ if (pNewScreen == pScreen)
+ continue;
+ dx = KdScreenOrigin(pNewScreen)->x - KdScreenOrigin(pScreen)->x;
+ dy = KdScreenOrigin(pNewScreen)->y - KdScreenOrigin(pScreen)->y;
+ if (*x < 0)
+ {
+ if (dx <= 0 && -dx < best_x)
+ {
+ best_x = -dx;
+ n_best_x = n;
+ }
+ }
+ else if (*x >= pScreen->width)
+ {
+ if (dx >= 0 && dx < best_x)
+ {
+ best_x = dx;
+ n_best_x = n;
+ }
+ }
+ if (*y < 0)
+ {
+ if (dy <= 0 && -dy < best_y)
+ {
+ best_y = -dy;
+ n_best_y = n;
+ }
+ }
+ else if (*y >= pScreen->height)
+ {
+ if (dy >= 0 && dy < best_y)
+ {
+ best_y = dy;
+ n_best_y = n;
+ }
+ }
+ }
+ if (best_y < best_x)
+ n_best_x = n_best_y;
+ if (n_best_x == -1)
+ return FALSE;
+ pNewScreen = screenInfo.screens[n_best_x];
+
+ if (*x < 0)
+ *x += pNewScreen->width;
+ if (*y < 0)
+ *y += pNewScreen->height;
+
+ if (*x >= pScreen->width)
+ *x -= pScreen->width;
+ if (*y >= pScreen->height)
+ *y -= pScreen->height;
+
+ *ppScreen = pNewScreen;
+ return TRUE;
+}
+
+static void
+KdCrossScreen(ScreenPtr pScreen, Bool entering)
+{
+#ifndef XIPAQ
+ if (entering)
+ KdEnableScreen (pScreen);
+ else
+ KdDisableScreen (pScreen);
+#endif
+}
+
+int KdCurScreen; /* current event screen */
+
+static void
+KdWarpCursor (DeviceIntPtr pDev, ScreenPtr pScreen, int x, int y)
+{
+ KdBlockSigio ();
+ KdCurScreen = pScreen->myNum;
+ miPointerWarpCursor(pDev, pScreen, x, y);
+ KdUnblockSigio ();
+}
+
+miPointerScreenFuncRec kdPointerScreenFuncs =
+{
+ KdCursorOffScreen,
+ KdCrossScreen,
+ KdWarpCursor
+};
+
+#ifndef _MSC_VER
+void
+ProcessInputEvents (void)
+{
+ mieqProcessInputEvents();
+ miPointerUpdateSprite(inputInfo.pointer);
+ if (kdSwitchPending)
+ KdProcessSwitch ();
+ KdCheckLock ();
+}
+#endif
+
+/* FIXME use XSECURITY to work out whether the client should be allowed to
+ * open and close. */
+void
+OpenInputDevice(DeviceIntPtr pDev, ClientPtr client, int *status)
+{
+ if (!pDev)
+ *status = BadDevice;
+ else
+ *status = Success;
+}
+
+void
+CloseInputDevice(DeviceIntPtr pDev, ClientPtr client)
+{
+ return;
+}
+
+/* We initialise all input devices at startup. */
+void
+AddOtherInputDevices(void)
+{
+ return;
+}
+
+/* At the moment, absolute/relative is up to the client. */
+int
+SetDeviceMode(register ClientPtr client, DeviceIntPtr pDev, int mode)
+{
+ return BadMatch;
+}
+
+int
+SetDeviceValuators(register ClientPtr client, DeviceIntPtr pDev,
+ int *valuators, int first_valuator, int num_valuators)
+{
+ return BadMatch;
+}
+
+int
+ChangeDeviceControl(register ClientPtr client, DeviceIntPtr pDev,
+ xDeviceCtl *control)
+{
+ switch (control->control) {
+ case DEVICE_RESOLUTION:
+ /* FIXME do something more intelligent here */
+ return BadMatch;
+
+ case DEVICE_ABS_CALIB:
+ case DEVICE_ABS_AREA:
+ return Success;
+
+ case DEVICE_CORE:
+ return BadMatch;
+ case DEVICE_ENABLE:
+ return Success;
+
+ default:
+ return BadMatch;
+ }
+
+ /* NOTREACHED */
+ return BadImplementation;
+}
+
+int
+NewInputDeviceRequest(InputOption *options, DeviceIntPtr *pdev)
+{
+ InputOption *option = NULL;
+ KdPointerInfo *pi = NULL;
+ KdKeyboardInfo *ki = NULL;
+
+ for (option = options; option; option = option->next) {
+ if (strcmp(option->key, "type") == 0) {
+ if (strcmp(option->value, "pointer") == 0) {
+ pi = KdNewPointer();
+ if (!pi)
+ return BadAlloc;
+ }
+ else if (strcmp(option->value, "keyboard") == 0) {
+ ki = KdNewKeyboard();
+ if (!ki)
+ return BadAlloc;
+ }
+ else {
+ ErrorF("unrecognised device type!\n");
+ return BadValue;
+ }
+ }
+#ifdef CONFIG_HAL
+ else if (strcmp(option->key, "_source") == 0 &&
+ strcmp(option->value, "server/hal") == 0)
+ {
+ ErrorF("Ignoring device from HAL.\n");
+ return BadValue;
+ }
+#endif
+ }
+
+ if (!ki && !pi) {
+ ErrorF("unrecognised device identifier!\n");
+ return BadValue;
+ }
+
+ /* FIXME: change this code below to use KdParseKbdOptions and
+ * KdParsePointerOptions */
+ for (option = options; option; option = option->next) {
+ if (strcmp(option->key, "device") == 0) {
+ if (pi && option->value)
+ pi->path = strdup(option->value);
+ else if (ki && option->value)
+ ki->path = strdup(option->value);
+ }
+ else if (strcmp(option->key, "driver") == 0) {
+ if (pi) {
+ pi->driver = KdFindPointerDriver(option->value);
+ if (!pi->driver) {
+ ErrorF("couldn't find driver!\n");
+ KdFreePointer(pi);
+ return BadValue;
+ }
+ pi->options = options;
+ }
+ else if (ki) {
+ ki->driver = KdFindKeyboardDriver(option->value);
+ if (!ki->driver) {
+ ErrorF("couldn't find driver!\n");
+ KdFreeKeyboard(ki);
+ return BadValue;
+ }
+ ki->options = options;
+ }
+ }
+ }
+
+ if (pi) {
+ if (KdAddPointer(pi) != Success ||
+ ActivateDevice(pi->dixdev, TRUE) != Success ||
+ EnableDevice(pi->dixdev, TRUE) != TRUE) {
+ ErrorF("couldn't add or enable pointer\n");
+ return BadImplementation;
+ }
+ }
+ else if (ki) {
+ if (KdAddKeyboard(ki) != Success ||
+ ActivateDevice(ki->dixdev, TRUE) != Success ||
+ EnableDevice(ki->dixdev, TRUE) != TRUE) {
+ ErrorF("couldn't add or enable keyboard\n");
+ return BadImplementation;
+ }
+ }
+
+ if (pi) {
+ *pdev = pi->dixdev;
+ } else if(ki) {
+ *pdev = ki->dixdev;
+ }
+
+ return Success;
+}
+
+void
+DeleteInputDeviceRequest(DeviceIntPtr pDev)
+{
+ RemoveDevice(pDev, TRUE);
+}
diff --git a/xorg-server/hw/kdrive/src/kmap.c b/xorg-server/hw/kdrive/src/kmap.c index 60e8ae134..a10c9ec09 100644 --- a/xorg-server/hw/kdrive/src/kmap.c +++ b/xorg-server/hw/kdrive/src/kmap.c @@ -24,6 +24,7 @@ #include "kdrive.h" #include <errno.h> +#ifndef _MSC_VER #include <unistd.h> #include <sys/mman.h> #ifdef HAVE_ASM_MTRR_H @@ -31,6 +32,9 @@ #endif #include <sys/ioctl.h> +#else +#define DRAW_DEBUG(a) +#endif void * KdMapDevice (CARD32 addr, CARD32 size) @@ -39,7 +43,8 @@ KdMapDevice (CARD32 addr, CARD32 size) void *a; void *d; - d = VirtualAlloc (NULL, size, MEM_RESERVE, PAGE_NOACCESS); + d = VirtualAlloc (NULL, size, MEM_RESERVE, PAGE_READWRITE|PAGE_NOCACHE); +/* if (!d) return NULL; DRAW_DEBUG ((DEBUG_S3INIT, "Virtual address of 0x%x is 0x%x", addr, d)); @@ -53,6 +58,8 @@ KdMapDevice (CARD32 addr, CARD32 size) return NULL; } DRAW_DEBUG ((DEBUG_S3INIT, "Device mapped successfully")); +*/ + __asm int 3; return d; #endif #ifdef linux diff --git a/xorg-server/hw/kdrive/src/makefile b/xorg-server/hw/kdrive/src/makefile new file mode 100644 index 000000000..e3a826faa --- /dev/null +++ b/xorg-server/hw/kdrive/src/makefile @@ -0,0 +1,14 @@ +LIBRARY = libkdrive + +CSRCS = \ + kcmap.c \ + kcurscol.c \ + kdrive.c \ + kinfo.c \ + kinput.c \ + kmap.c \ + kmode.c \ + kshadow.c + + + diff --git a/xorg-server/hw/xfree86/common/compiler.h b/xorg-server/hw/xfree86/common/compiler.h index cdb493a23..71a94c0c8 100644 --- a/xorg-server/hw/xfree86/common/compiler.h +++ b/xorg-server/hw/xfree86/common/compiler.h @@ -1,1345 +1,1345 @@ -/* - * 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). - */ - -#ifndef _COMPILER_H - -# define _COMPILER_H - -#if defined(__SUNPRO_C) -# define DO_PROTOTYPES -#endif - -#ifndef _X_EXPORT -# include <X11/Xfuncproto.h> -#endif - -# include <pixman.h> /* for uint*_t types */ - -/* Allow drivers to use the GCC-supported __inline__ and/or __inline. */ -# ifndef __inline__ -# if defined(__GNUC__) - /* gcc has __inline__ */ -# elif defined(__HIGHC__) -# define __inline__ _Inline -# else -# define __inline__ /**/ -# endif -# endif /* __inline__ */ -# ifndef __inline -# if defined(__GNUC__) - /* gcc has __inline */ -# elif defined(__HIGHC__) -# define __inline _Inline -# else -# define __inline /**/ -# endif -# endif /* __inline */ - -/* Support gcc's __FUNCTION__ for people using other compilers */ -#if !defined(__GNUC__) && !defined(__FUNCTION__) -# define __FUNCTION__ __func__ /* C99 */ -#endif - -# if defined(NO_INLINE) || defined(DO_PROTOTYPES) - -# if !defined(__arm__) -# if !defined(__sparc__) && !defined(__sparc) && !defined(__arm32__) \ - && !(defined(__alpha__) && defined(linux)) \ - && !(defined(__ia64__) && defined(linux)) \ - -extern _X_EXPORT void outb(unsigned short, unsigned char); -extern _X_EXPORT void outw(unsigned short, unsigned short); -extern _X_EXPORT void outl(unsigned short, unsigned int); -extern _X_EXPORT unsigned int inb(unsigned short); -extern _X_EXPORT unsigned int inw(unsigned short); -extern _X_EXPORT unsigned int inl(unsigned short); - -# else /* __sparc__, __arm32__, __alpha__*/ - -extern _X_EXPORT void outb(unsigned long, unsigned char); -extern _X_EXPORT void outw(unsigned long, unsigned short); -extern _X_EXPORT void outl(unsigned long, unsigned int); -extern _X_EXPORT unsigned int inb(unsigned long); -extern _X_EXPORT unsigned int inw(unsigned long); -extern _X_EXPORT unsigned int inl(unsigned long); - -# endif /* __sparc__, __arm32__, __alpha__ */ -# endif /* __arm__ */ - -# if defined(__powerpc__) && !defined(__OpenBSD__) -extern unsigned long ldq_u(unsigned long *); -extern unsigned long ldl_u(unsigned int *); -extern unsigned long ldw_u(unsigned short *); -extern void stq_u(unsigned long, unsigned long *); -extern void stl_u(unsigned long, unsigned int *); -extern void stw_u(unsigned long, unsigned short *); -extern void mem_barrier(void); -extern void write_mem_barrier(void); -extern void stl_brx(unsigned long, volatile unsigned char *, int); -extern void stw_brx(unsigned short, volatile unsigned char *, int); -extern unsigned long ldl_brx(volatile unsigned char *, int); -extern unsigned short ldw_brx(volatile unsigned char *, int); -# endif /* __powerpc__ && !__OpenBSD */ - -# endif /* NO_INLINE || DO_PROTOTYPES */ - -# ifndef NO_INLINE -# ifdef __GNUC__ -# ifdef __i386__ - -# ifdef __SSE__ -# define write_mem_barrier() __asm__ __volatile__ ("sfence" : : : "memory") -# else -# define write_mem_barrier() __asm__ __volatile__ ("lock; addl $0,0(%%esp)" : : : "memory") -# endif - -# ifdef __SSE2__ -# define mem_barrier() __asm__ __volatile__ ("mfence" : : : "memory") -# else -# define mem_barrier() __asm__ __volatile__ ("lock; addl $0,0(%%esp)" : : : "memory") -# endif - -# elif defined __alpha__ - -# define mem_barrier() __asm__ __volatile__ ("mb" : : : "memory") -# define write_mem_barrier() __asm__ __volatile__ ("wmb" : : : "memory") - -# elif defined __amd64__ - -# define mem_barrier() __asm__ __volatile__ ("mfence" : : : "memory") -# define write_mem_barrier() __asm__ __volatile__ ("sfence" : : : "memory") - -# elif defined __ia64__ - -# ifndef __INTEL_COMPILER -# define mem_barrier() __asm__ __volatile__ ("mf" : : : "memory") -# define write_mem_barrier() __asm__ __volatile__ ("mf" : : : "memory") -# else -# include "ia64intrin.h" -# define mem_barrier() __mf() -# define write_mem_barrier() __mf() -# endif - -# elif defined __mips__ - /* Note: sync instruction requires MIPS II instruction set */ -# define mem_barrier() \ - __asm__ __volatile__( \ - ".set push\n\t" \ - ".set noreorder\n\t" \ - ".set mips2\n\t" \ - "sync\n\t" \ - ".set pop" \ - : /* no output */ \ - : /* no input */ \ - : "memory") -# define write_mem_barrier() mem_barrier() - -# elif defined __powerpc__ - -# if defined(linux) && defined(__powerpc64__) -# include <linux/version.h> -# if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 0) -# include <asm/memory.h> -# endif -# endif /* defined(linux) && defined(__powerpc64__) */ - -# ifndef eieio /* We deal with arch-specific eieio() routines above... */ -# define eieio() __asm__ __volatile__ ("eieio" ::: "memory") -# endif /* eieio */ -# define mem_barrier() eieio() -# define write_mem_barrier() eieio() - -# elif defined __sparc__ - -# define barrier() __asm__ __volatile__ (".word 0x8143e00a" : : : "memory") -# define mem_barrier() /* XXX: nop for now */ -# define write_mem_barrier() /* XXX: nop for now */ -# endif -# endif /* __GNUC__ */ -# endif /* NO_INLINE */ - -# ifndef mem_barrier -# define mem_barrier() /* NOP */ -# endif - -# ifndef write_mem_barrier -# define write_mem_barrier() /* NOP */ -# endif - - -# ifndef NO_INLINE -# ifdef __GNUC__ - -/* Define some packed structures to use with unaligned accesses */ - -struct __una_u64 { uint64_t x __attribute__((packed)); }; -struct __una_u32 { uint32_t x __attribute__((packed)); }; -struct __una_u16 { uint16_t x __attribute__((packed)); }; - -/* Elemental unaligned loads */ - -static __inline__ uint64_t ldq_u(uint64_t *p) -{ - const struct __una_u64 *ptr = (const struct __una_u64 *) p; - return ptr->x; -} - -static __inline__ uint32_t ldl_u(uint32_t *p) -{ - const struct __una_u32 *ptr = (const struct __una_u32 *) p; - return ptr->x; -} - -static __inline__ uint16_t ldw_u(uint16_t *p) -{ - const struct __una_u16 *ptr = (const struct __una_u16 *) p; - return ptr->x; -} - -/* Elemental unaligned stores */ - -static __inline__ void stq_u(uint64_t val, uint64_t *p) -{ - struct __una_u64 *ptr = (struct __una_u64 *) p; - ptr->x = val; -} - -static __inline__ void stl_u(uint32_t val, uint32_t *p) -{ - struct __una_u32 *ptr = (struct __una_u32 *) p; - ptr->x = val; -} - -static __inline__ void stw_u(uint16_t val, uint16_t *p) -{ - struct __una_u16 *ptr = (struct __una_u16 *) p; - ptr->x = val; -} -# else /* !__GNUC__ */ - -#include <string.h> /* needed for memmove */ - -static __inline__ uint64_t ldq_u(uint64_t *p) -{ - uint64_t ret; - memmove(&ret, p, sizeof(*p)); - return ret; -} - -static __inline__ uint32_t ldl_u(uint32_t *p) -{ - uint32_t ret; - memmove(&ret, p, sizeof(*p)); - return ret; -} - -static __inline__ uint16_t ldw_u(uint16_t *p) -{ - uint16_t ret; - memmove(&ret, p, sizeof(*p)); - return ret; -} - -static __inline__ void stq_u(uint64_t val, uint64_t *p) -{ - uint64_t tmp = val; - memmove(p, &tmp, sizeof(*p)); -} - -static __inline__ void stl_u(uint32_t val, uint32_t *p) -{ - uint32_t tmp = val; - memmove(p, &tmp, sizeof(*p)); -} - -static __inline__ void stw_u(uint16_t val, uint16_t *p) -{ - uint16_t tmp = val; - memmove(p, &tmp, sizeof(*p)); -} - -# endif /* __GNUC__ */ -# endif /* NO_INLINE */ - -# ifndef NO_INLINE -# ifdef __GNUC__ -# if (defined(linux) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && (defined(__alpha__)) - -# ifdef linux -/* for Linux on Alpha, we use the LIBC _inx/_outx routines */ -/* note that the appropriate setup via "ioperm" needs to be done */ -/* *before* any inx/outx is done. */ - -extern _X_EXPORT void (*_alpha_outb)(char val, unsigned long port); -static __inline__ void -outb(unsigned long port, unsigned char val) -{ - _alpha_outb(val, port); -} - -extern _X_EXPORT void (*_alpha_outw)(short val, unsigned long port); -static __inline__ void -outw(unsigned long port, unsigned short val) -{ - _alpha_outw(val, port); -} - -extern _X_EXPORT void (*_alpha_outl)(int val, unsigned long port); -static __inline__ void -outl(unsigned long port, unsigned int val) -{ - _alpha_outl(val, port); -} - -extern _X_EXPORT unsigned int (*_alpha_inb)(unsigned long port); -static __inline__ unsigned int -inb(unsigned long port) -{ - return _alpha_inb(port); -} - -extern _X_EXPORT unsigned int (*_alpha_inw)(unsigned long port); -static __inline__ unsigned int -inw(unsigned long port) -{ - return _alpha_inw(port); -} - -extern _X_EXPORT unsigned int (*_alpha_inl)(unsigned long port); -static __inline__ unsigned int -inl(unsigned long port) -{ - return _alpha_inl(port); -} - -# endif /* linux */ - -# if (defined(__FreeBSD__) || defined(__OpenBSD__)) \ - && !defined(DO_PROTOTYPES) - -/* for FreeBSD and OpenBSD on Alpha, we use the libio (resp. libalpha) */ -/* inx/outx routines */ -/* note that the appropriate setup via "ioperm" needs to be done */ -/* *before* any inx/outx is done. */ - -extern _X_EXPORT void outb(unsigned int port, unsigned char val); -extern _X_EXPORT void outw(unsigned int port, unsigned short val); -extern _X_EXPORT void outl(unsigned int port, unsigned int val); -extern _X_EXPORT unsigned char inb(unsigned int port); -extern _X_EXPORT unsigned short inw(unsigned int port); -extern _X_EXPORT unsigned int inl(unsigned int port); - -# endif /* (__FreeBSD__ || __OpenBSD__ ) && !DO_PROTOTYPES */ - - -#if defined(__NetBSD__) -#include <machine/pio.h> -#endif /* __NetBSD__ */ - -# elif defined(linux) && defined(__ia64__) - -# include <inttypes.h> - -# include <sys/io.h> - -# undef outb -# undef outw -# undef outl -# undef inb -# undef inw -# undef inl -extern _X_EXPORT void outb(unsigned long port, unsigned char val); -extern _X_EXPORT void outw(unsigned long port, unsigned short val); -extern _X_EXPORT void outl(unsigned long port, unsigned int val); -extern _X_EXPORT unsigned int inb(unsigned long port); -extern _X_EXPORT unsigned int inw(unsigned long port); -extern _X_EXPORT unsigned int inl(unsigned long port); - -# elif (defined(linux) || defined(__FreeBSD__)) && defined(__amd64__) - -# include <inttypes.h> - -static __inline__ void -outb(unsigned short port, unsigned char val) -{ - __asm__ __volatile__("outb %0,%1" : :"a" (val), "d" (port)); -} - - -static __inline__ void -outw(unsigned short port, unsigned short val) -{ - __asm__ __volatile__("outw %0,%1" : :"a" (val), "d" (port)); -} - -static __inline__ void -outl(unsigned short port, unsigned int val) -{ - __asm__ __volatile__("outl %0,%1" : :"a" (val), "d" (port)); -} - -static __inline__ unsigned int -inb(unsigned short port) -{ - unsigned char ret; - __asm__ __volatile__("inb %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inw(unsigned short port) -{ - unsigned short ret; - __asm__ __volatile__("inw %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inl(unsigned short port) -{ - unsigned int ret; - __asm__ __volatile__("inl %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -# elif (defined(linux) || defined(sun) || defined(__OpenBSD__) || defined(__FreeBSD__)) && defined(__sparc__) - -# ifndef ASI_PL -# define ASI_PL 0x88 -# endif - -static __inline__ void -outb(unsigned long port, unsigned char val) -{ - __asm__ __volatile__("stba %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (port), "i" (ASI_PL)); - barrier(); -} - -static __inline__ void -outw(unsigned long port, unsigned short val) -{ - __asm__ __volatile__("stha %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (port), "i" (ASI_PL)); - barrier(); -} - -static __inline__ void -outl(unsigned long port, unsigned int val) -{ - __asm__ __volatile__("sta %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (port), "i" (ASI_PL)); - barrier(); -} - -static __inline__ unsigned int -inb(unsigned long port) -{ - unsigned int ret; - __asm__ __volatile__("lduba [%1] %2, %0" - : "=r" (ret) - : "r" (port), "i" (ASI_PL)); - return ret; -} - -static __inline__ unsigned int -inw(unsigned long port) -{ - unsigned int ret; - __asm__ __volatile__("lduha [%1] %2, %0" - : "=r" (ret) - : "r" (port), "i" (ASI_PL)); - return ret; -} - -static __inline__ unsigned int -inl(unsigned long port) -{ - unsigned int ret; - __asm__ __volatile__("lda [%1] %2, %0" - : "=r" (ret) - : "r" (port), "i" (ASI_PL)); - return ret; -} - -static __inline__ unsigned char -xf86ReadMmio8(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned char ret; - - __asm__ __volatile__("lduba [%1] %2, %0" - : "=r" (ret) - : "r" (addr), "i" (ASI_PL)); - return ret; -} - -static __inline__ unsigned short -xf86ReadMmio16Be(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned short ret; - - __asm__ __volatile__("lduh [%1], %0" - : "=r" (ret) - : "r" (addr)); - return ret; -} - -static __inline__ unsigned short -xf86ReadMmio16Le(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned short ret; - - __asm__ __volatile__("lduha [%1] %2, %0" - : "=r" (ret) - : "r" (addr), "i" (ASI_PL)); - return ret; -} - -static __inline__ unsigned int -xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned int ret; - - __asm__ __volatile__("ld [%1], %0" - : "=r" (ret) - : "r" (addr)); - return ret; -} - -static __inline__ unsigned int -xf86ReadMmio32Le(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned int ret; - - __asm__ __volatile__("lda [%1] %2, %0" - : "=r" (ret) - : "r" (addr), "i" (ASI_PL)); - return ret; -} - -static __inline__ void -xf86WriteMmio8(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("stba %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); - barrier(); -} - -static __inline__ void -xf86WriteMmio16Be(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("sth %0, [%1]" - : /* No outputs */ - : "r" (val), "r" (addr)); - barrier(); -} - -static __inline__ void -xf86WriteMmio16Le(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("stha %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); - barrier(); -} - -static __inline__ void -xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("st %0, [%1]" - : /* No outputs */ - : "r" (val), "r" (addr)); - barrier(); -} - -static __inline__ void -xf86WriteMmio32Le(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("sta %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); - barrier(); -} - -static __inline__ void -xf86WriteMmio8NB(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("stba %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); -} - -static __inline__ void -xf86WriteMmio16BeNB(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("sth %0, [%1]" - : /* No outputs */ - : "r" (val), "r" (addr)); -} - -static __inline__ void -xf86WriteMmio16LeNB(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("stha %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); -} - -static __inline__ void -xf86WriteMmio32BeNB(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("st %0, [%1]" - : /* No outputs */ - : "r" (val), "r" (addr)); -} - -static __inline__ void -xf86WriteMmio32LeNB(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("sta %0, [%1] %2" - : /* No outputs */ - : "r" (val), "r" (addr), "i" (ASI_PL)); -} - -# elif defined(__mips__) || (defined(__arm32__) && !defined(__linux__)) -# ifdef __arm32__ -# define PORT_SIZE long -# else -# define PORT_SIZE short -# endif - -_X_EXPORT unsigned int IOPortBase; /* Memory mapped I/O port area */ - -static __inline__ void -outb(unsigned PORT_SIZE port, unsigned char val) -{ - *(volatile unsigned char*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val; -} - -static __inline__ void -outw(unsigned PORT_SIZE port, unsigned short val) -{ - *(volatile unsigned short*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val; -} - -static __inline__ void -outl(unsigned PORT_SIZE port, unsigned int val) -{ - *(volatile unsigned int*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val; -} - -static __inline__ unsigned int -inb(unsigned PORT_SIZE port) -{ - return *(volatile unsigned char*)(((unsigned PORT_SIZE)(port))+IOPortBase); -} - -static __inline__ unsigned int -inw(unsigned PORT_SIZE port) -{ - return *(volatile unsigned short*)(((unsigned PORT_SIZE)(port))+IOPortBase); -} - -static __inline__ unsigned int -inl(unsigned PORT_SIZE port) -{ - return *(volatile unsigned int*)(((unsigned PORT_SIZE)(port))+IOPortBase); -} - - -# if defined(__mips__) -# ifdef linux /* don't mess with other OSs */ -# if X_BYTE_ORDER == X_BIG_ENDIAN -static __inline__ unsigned int -xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset) -{ - unsigned long addr = ((unsigned long)base) + offset; - unsigned int ret; - - __asm__ __volatile__("lw %0, 0(%1)" - : "=r" (ret) - : "r" (addr)); - return ret; -} - -static __inline__ void -xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - unsigned long addr = ((unsigned long)base) + offset; - - __asm__ __volatile__("sw %0, 0(%1)" - : /* No outputs */ - : "r" (val), "r" (addr)); -} -# endif -# endif /* !linux */ -# endif /* __mips__ */ - -# elif (defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)) && defined(__powerpc__) - -# ifndef MAP_FAILED -# define MAP_FAILED ((void *)-1) -# endif - -extern _X_EXPORT volatile unsigned char *ioBase; - -static __inline__ unsigned char -xf86ReadMmio8(__volatile__ void *base, const unsigned long offset) -{ - register unsigned char val; - __asm__ __volatile__( - "lbzx %0,%1,%2\n\t" - "eieio" - : "=r" (val) - : "b" (base), "r" (offset), - "m" (*((volatile unsigned char *)base+offset))); - return val; -} - -static __inline__ unsigned short -xf86ReadMmio16Be(__volatile__ void *base, const unsigned long offset) -{ - register unsigned short val; - __asm__ __volatile__( - "lhzx %0,%1,%2\n\t" - "eieio" - : "=r" (val) - : "b" (base), "r" (offset), - "m" (*((volatile unsigned char *)base+offset))); - return val; -} - -static __inline__ unsigned short -xf86ReadMmio16Le(__volatile__ void *base, const unsigned long offset) -{ - register unsigned short val; - __asm__ __volatile__( - "lhbrx %0,%1,%2\n\t" - "eieio" - : "=r" (val) - : "b" (base), "r" (offset), - "m" (*((volatile unsigned char *)base+offset))); - return val; -} - -static __inline__ unsigned int -xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset) -{ - register unsigned int val; - __asm__ __volatile__( - "lwzx %0,%1,%2\n\t" - "eieio" - : "=r" (val) - : "b" (base), "r" (offset), - "m" (*((volatile unsigned char *)base+offset))); - return val; -} - -static __inline__ unsigned int -xf86ReadMmio32Le(__volatile__ void *base, const unsigned long offset) -{ - register unsigned int val; - __asm__ __volatile__( - "lwbrx %0,%1,%2\n\t" - "eieio" - : "=r" (val) - : "b" (base), "r" (offset), - "m" (*((volatile unsigned char *)base+offset))); - return val; -} - -static __inline__ void -xf86WriteMmioNB8(__volatile__ void *base, const unsigned long offset, - const unsigned char val) -{ - __asm__ __volatile__( - "stbx %1,%2,%3\n\t" - : "=m" (*((volatile unsigned char *)base+offset)) - : "r" (val), "b" (base), "r" (offset)); -} - -static __inline__ void -xf86WriteMmioNB16Le(__volatile__ void *base, const unsigned long offset, - const unsigned short val) -{ - __asm__ __volatile__( - "sthbrx %1,%2,%3\n\t" - : "=m" (*((volatile unsigned char *)base+offset)) - : "r" (val), "b" (base), "r" (offset)); -} - -static __inline__ void -xf86WriteMmioNB16Be(__volatile__ void *base, const unsigned long offset, - const unsigned short val) -{ - __asm__ __volatile__( - "sthx %1,%2,%3\n\t" - : "=m" (*((volatile unsigned char *)base+offset)) - : "r" (val), "b" (base), "r" (offset)); -} - -static __inline__ void -xf86WriteMmioNB32Le(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - __asm__ __volatile__( - "stwbrx %1,%2,%3\n\t" - : "=m" (*((volatile unsigned char *)base+offset)) - : "r" (val), "b" (base), "r" (offset)); -} - -static __inline__ void -xf86WriteMmioNB32Be(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - __asm__ __volatile__( - "stwx %1,%2,%3\n\t" - : "=m" (*((volatile unsigned char *)base+offset)) - : "r" (val), "b" (base), "r" (offset)); -} - -static __inline__ void -xf86WriteMmio8(__volatile__ void *base, const unsigned long offset, - const unsigned char val) -{ - xf86WriteMmioNB8(base, offset, val); - eieio(); -} - -static __inline__ void -xf86WriteMmio16Le(__volatile__ void *base, const unsigned long offset, - const unsigned short val) -{ - xf86WriteMmioNB16Le(base, offset, val); - eieio(); -} - -static __inline__ void -xf86WriteMmio16Be(__volatile__ void *base, const unsigned long offset, - const unsigned short val) -{ - xf86WriteMmioNB16Be(base, offset, val); - eieio(); -} - -static __inline__ void -xf86WriteMmio32Le(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - xf86WriteMmioNB32Le(base, offset, val); - eieio(); -} - -static __inline__ void -xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset, - const unsigned int val) -{ - xf86WriteMmioNB32Be(base, offset, val); - eieio(); -} - - -static __inline__ void -outb(unsigned short port, unsigned char value) -{ - if(ioBase == MAP_FAILED) return; - xf86WriteMmio8((void *)ioBase, port, value); -} - -static __inline__ void -outw(unsigned short port, unsigned short value) -{ - if(ioBase == MAP_FAILED) return; - xf86WriteMmio16Le((void *)ioBase, port, value); -} - -static __inline__ void -outl(unsigned short port, unsigned int value) -{ - if(ioBase == MAP_FAILED) return; - xf86WriteMmio32Le((void *)ioBase, port, value); -} - -static __inline__ unsigned int -inb(unsigned short port) -{ - if(ioBase == MAP_FAILED) return 0; - return xf86ReadMmio8((void *)ioBase, port); -} - -static __inline__ unsigned int -inw(unsigned short port) -{ - if(ioBase == MAP_FAILED) return 0; - return xf86ReadMmio16Le((void *)ioBase, port); -} - -static __inline__ unsigned int -inl(unsigned short port) -{ - if(ioBase == MAP_FAILED) return 0; - return xf86ReadMmio32Le((void *)ioBase, port); -} - -#elif defined(__arm__) && defined(__linux__) - -/* for Linux on ARM, we use the LIBC inx/outx routines */ -/* note that the appropriate setup via "ioperm" needs to be done */ -/* *before* any inx/outx is done. */ - -#include <sys/io.h> - -static __inline__ void -xf_outb(unsigned short port, unsigned char val) -{ - outb(val, port); -} - -static __inline__ void -xf_outw(unsigned short port, unsigned short val) -{ - outw(val, port); -} - -static __inline__ void -xf_outl(unsigned short port, unsigned int val) -{ - outl(val, port); -} - -#define outb xf_outb -#define outw xf_outw -#define outl xf_outl - -# else /* ix86 */ - -# if !defined(__SUNPRO_C) -# if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__m32r__) -# ifdef GCCUSESGAS - -/* - * If gcc uses gas rather than the native assembler, the syntax of these - * inlines has to be different. DHD - */ - -static __inline__ void -outb(unsigned short port, unsigned char val) -{ - __asm__ __volatile__("outb %0,%1" : :"a" (val), "d" (port)); -} - - -static __inline__ void -outw(unsigned short port, unsigned short val) -{ - __asm__ __volatile__("outw %0,%1" : :"a" (val), "d" (port)); -} - -static __inline__ void -outl(unsigned short port, unsigned int val) -{ - __asm__ __volatile__("outl %0,%1" : :"a" (val), "d" (port)); -} - -static __inline__ unsigned int -inb(unsigned short port) -{ - unsigned char ret; - __asm__ __volatile__("inb %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inw(unsigned short port) -{ - unsigned short ret; - __asm__ __volatile__("inw %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inl(unsigned short port) -{ - unsigned int ret; - __asm__ __volatile__("inl %1,%0" : - "=a" (ret) : - "d" (port)); - return ret; -} - -# else /* GCCUSESGAS */ - -static __inline__ void -outb(unsigned short port, unsigned char val) -{ - __asm__ __volatile__("out%B0 (%1)" : :"a" (val), "d" (port)); -} - -static __inline__ void -outw(unsigned short port, unsigned short val) -{ - __asm__ __volatile__("out%W0 (%1)" : :"a" (val), "d" (port)); -} - -static __inline__ void -outl(unsigned short port, unsigned int val) -{ - __asm__ __volatile__("out%L0 (%1)" : :"a" (val), "d" (port)); -} - -static __inline__ unsigned int -inb(unsigned short port) -{ - unsigned char ret; - __asm__ __volatile__("in%B0 (%1)" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inw(unsigned short port) -{ - unsigned short ret; - __asm__ __volatile__("in%W0 (%1)" : - "=a" (ret) : - "d" (port)); - return ret; -} - -static __inline__ unsigned int -inl(unsigned short port) -{ - unsigned int ret; - __asm__ __volatile__("in%L0 (%1)" : - "=a" (ret) : - "d" (port)); - return ret; -} - -# endif /* GCCUSESGAS */ - -# else /* !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__m32r__) */ - -static __inline__ void -outb(unsigned short port, unsigned char val) -{ -} - -static __inline__ void -outw(unsigned short port, unsigned short val) -{ -} - -static __inline__ void -outl(unsigned short port, unsigned int val) -{ -} - -static __inline__ unsigned int -inb(unsigned short port) -{ - return 0; -} - -static __inline__ unsigned int -inw(unsigned short port) -{ - return 0; -} - -static __inline__ unsigned int -inl(unsigned short port) -{ - return 0; -} - -# endif /* FAKEIT */ -# endif /* __SUNPRO_C */ - -# endif /* ix86 */ - -# else /* !GNUC */ -# if defined(__STDC__) && (__STDC__ == 1) -# ifndef asm -# define asm __asm -# endif -# endif -# ifndef SCO325 -# if defined(__UNIXWARE__) -# /* avoid including <sys/types.h> for <sys/inline.h> on UnixWare */ -# define ushort unsigned short -# define ushort_t unsigned short -# define ulong unsigned long -# define ulong_t unsigned long -# define uint_t unsigned int -# define uchar_t unsigned char -# endif /* __UNIXWARE__ */ -# if !defined(__SUNPRO_C) -# include <sys/inline.h> -# endif -# else -# include "scoasm.h" -# endif -# if !defined(__HIGHC__) && !defined(__SUNPRO_C) || \ - defined(__USLC__) -# pragma asm partial_optimization outl -# pragma asm partial_optimization outw -# pragma asm partial_optimization outb -# pragma asm partial_optimization inl -# pragma asm partial_optimization inw -# pragma asm partial_optimization inb -# endif -# endif /* __GNUC__ */ - -# endif /* NO_INLINE */ - -# ifdef __alpha__ -/* entry points for Mmio memory access routines */ -extern _X_EXPORT int (*xf86ReadMmio8)(void *, unsigned long); -extern _X_EXPORT int (*xf86ReadMmio16)(void *, unsigned long); -# ifndef STANDALONE_MMIO -extern _X_EXPORT int (*xf86ReadMmio32)(void *, unsigned long); -# else -/* Some DRI 3D drivers need MMIO_IN32. */ -static __inline__ int -xf86ReadMmio32(void *Base, unsigned long Offset) -{ - mem_barrier(); - return *(volatile unsigned int*)((unsigned long)Base+(Offset)); -} -# endif -extern _X_EXPORT void (*xf86WriteMmio8)(int, void *, unsigned long); -extern _X_EXPORT void (*xf86WriteMmio16)(int, void *, unsigned long); -extern _X_EXPORT void (*xf86WriteMmio32)(int, void *, unsigned long); -extern _X_EXPORT void (*xf86WriteMmioNB8)(int, void *, unsigned long); -extern _X_EXPORT void (*xf86WriteMmioNB16)(int, void *, unsigned long); -extern _X_EXPORT void (*xf86WriteMmioNB32)(int, void *, unsigned long); - -/* Some macros to hide the system dependencies for MMIO accesses */ -/* Changed to kill noise generated by gcc's -Wcast-align */ -# define MMIO_IN8(base, offset) (*xf86ReadMmio8)(base, offset) -# define MMIO_IN16(base, offset) (*xf86ReadMmio16)(base, offset) -# ifndef STANDALONE_MMIO -# define MMIO_IN32(base, offset) (*xf86ReadMmio32)(base, offset) -# else -# define MMIO_IN32(base, offset) xf86ReadMmio32(base, offset) -# endif - -# define MMIO_OUT32(base, offset, val) \ - do { \ - write_mem_barrier(); \ - *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val); \ - } while (0) -# define MMIO_ONB32(base, offset, val) \ - *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val) - -# define MMIO_OUT8(base, offset, val) \ - (*xf86WriteMmio8)((CARD8)(val), base, offset) -# define MMIO_OUT16(base, offset, val) \ - (*xf86WriteMmio16)((CARD16)(val), base, offset) -# define MMIO_ONB8(base, offset, val) \ - (*xf86WriteMmioNB8)((CARD8)(val), base, offset) -# define MMIO_ONB16(base, offset, val) \ - (*xf86WriteMmioNB16)((CARD16)(val), base, offset) -# define MMIO_MOVE32(base, offset, val) \ - MMIO_OUT32(base, offset, val) - -# elif defined(__powerpc__) - /* - * we provide byteswapping and no byteswapping functions here - * with byteswapping as default, - * drivers that don't need byteswapping should define PPC_MMIO_IS_BE - */ -# define MMIO_IN8(base, offset) xf86ReadMmio8(base, offset) -# define MMIO_OUT8(base, offset, val) \ - xf86WriteMmio8(base, offset, (CARD8)(val)) -# define MMIO_ONB8(base, offset, val) \ - xf86WriteMmioNB8(base, offset, (CARD8)(val)) - -# if defined(PPC_MMIO_IS_BE) /* No byteswapping */ -# define MMIO_IN16(base, offset) xf86ReadMmio16Be(base, offset) -# define MMIO_IN32(base, offset) xf86ReadMmio32Be(base, offset) -# define MMIO_OUT16(base, offset, val) \ - xf86WriteMmio16Be(base, offset, (CARD16)(val)) -# define MMIO_OUT32(base, offset, val) \ - xf86WriteMmio32Be(base, offset, (CARD32)(val)) -# define MMIO_ONB16(base, offset, val) \ - xf86WriteMmioNB16Be(base, offset, (CARD16)(val)) -# define MMIO_ONB32(base, offset, val) \ - xf86WriteMmioNB32Be(base, offset, (CARD32)(val)) -# else /* byteswapping is the default */ -# define MMIO_IN16(base, offset) xf86ReadMmio16Le(base, offset) -# define MMIO_IN32(base, offset) xf86ReadMmio32Le(base, offset) -# define MMIO_OUT16(base, offset, val) \ - xf86WriteMmio16Le(base, offset, (CARD16)(val)) -# define MMIO_OUT32(base, offset, val) \ - xf86WriteMmio32Le(base, offset, (CARD32)(val)) -# define MMIO_ONB16(base, offset, val) \ - xf86WriteMmioNB16Le(base, offset, (CARD16)(val)) -# define MMIO_ONB32(base, offset, val) \ - xf86WriteMmioNB32Le(base, offset, (CARD32)(val)) -# endif - -# define MMIO_MOVE32(base, offset, val) \ - xf86WriteMmio32Be(base, offset, (CARD32)(val)) - -# elif defined(__sparc__) || defined(sparc) || defined(__sparc) - /* - * Like powerpc, we provide byteswapping and no byteswapping functions - * here with byteswapping as default, drivers that don't need byteswapping - * should define SPARC_MMIO_IS_BE (perhaps create a generic macro so that we - * do not need to use PPC_MMIO_IS_BE and the sparc one in all the same places - * of drivers?). - */ -# define MMIO_IN8(base, offset) xf86ReadMmio8(base, offset) -# define MMIO_OUT8(base, offset, val) \ - xf86WriteMmio8(base, offset, (CARD8)(val)) -# define MMIO_ONB8(base, offset, val) \ - xf86WriteMmio8NB(base, offset, (CARD8)(val)) - -# if defined(SPARC_MMIO_IS_BE) /* No byteswapping */ -# define MMIO_IN16(base, offset) xf86ReadMmio16Be(base, offset) -# define MMIO_IN32(base, offset) xf86ReadMmio32Be(base, offset) -# define MMIO_OUT16(base, offset, val) \ - xf86WriteMmio16Be(base, offset, (CARD16)(val)) -# define MMIO_OUT32(base, offset, val) \ - xf86WriteMmio32Be(base, offset, (CARD32)(val)) -# define MMIO_ONB16(base, offset, val) \ - xf86WriteMmio16BeNB(base, offset, (CARD16)(val)) -# define MMIO_ONB32(base, offset, val) \ - xf86WriteMmio32BeNB(base, offset, (CARD32)(val)) -# else /* byteswapping is the default */ -# define MMIO_IN16(base, offset) xf86ReadMmio16Le(base, offset) -# define MMIO_IN32(base, offset) xf86ReadMmio32Le(base, offset) -# define MMIO_OUT16(base, offset, val) \ - xf86WriteMmio16Le(base, offset, (CARD16)(val)) -# define MMIO_OUT32(base, offset, val) \ - xf86WriteMmio32Le(base, offset, (CARD32)(val)) -# define MMIO_ONB16(base, offset, val) \ - xf86WriteMmio16LeNB(base, offset, (CARD16)(val)) -# define MMIO_ONB32(base, offset, val) \ - xf86WriteMmio32LeNB(base, offset, (CARD32)(val)) -# endif - -# define MMIO_MOVE32(base, offset, val) \ - xf86WriteMmio32Be(base, offset, (CARD32)(val)) - -# else /* !__alpha__ && !__powerpc__ && !__sparc__ */ - -# define MMIO_IN8(base, offset) \ - *(volatile CARD8 *)(((CARD8*)(base)) + (offset)) -# define MMIO_IN16(base, offset) \ - *(volatile CARD16 *)(void *)(((CARD8*)(base)) + (offset)) -# define MMIO_IN32(base, offset) \ - *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) -# define MMIO_OUT8(base, offset, val) \ - *(volatile CARD8 *)(((CARD8*)(base)) + (offset)) = (val) -# define MMIO_OUT16(base, offset, val) \ - *(volatile CARD16 *)(void *)(((CARD8*)(base)) + (offset)) = (val) -# define MMIO_OUT32(base, offset, val) \ - *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val) -# define MMIO_ONB8(base, offset, val) MMIO_OUT8(base, offset, val) -# define MMIO_ONB16(base, offset, val) MMIO_OUT16(base, offset, val) -# define MMIO_ONB32(base, offset, val) MMIO_OUT32(base, offset, val) - -# define MMIO_MOVE32(base, offset, val) MMIO_OUT32(base, offset, val) - -# endif /* __alpha__ */ -#endif /* _COMPILER_H */ +/*
+ * 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).
+ */
+
+#ifndef _COMPILER_H
+
+# define _COMPILER_H
+
+#if defined(__SUNPRO_C)
+# define DO_PROTOTYPES
+#endif
+
+#ifndef _X_EXPORT
+# include <X11/Xfuncproto.h>
+#endif
+
+# include <pixman.h> /* for uint*_t types */
+
+/* Allow drivers to use the GCC-supported __inline__ and/or __inline. */
+# ifndef __inline__
+# if defined(__GNUC__)
+ /* gcc has __inline__ */
+# elif defined(__HIGHC__)
+# define __inline__ _Inline
+# else
+# define __inline__ /**/
+# endif
+# endif /* __inline__ */
+# ifndef __inline
+# if defined(__GNUC__) || defined(_MSC_VER)
+ /* gcc has __inline */
+# elif defined(__HIGHC__)
+# define __inline _Inline
+# else
+# define __inline /**/
+# endif
+# endif /* __inline */
+
+/* Support gcc's __FUNCTION__ for people using other compilers */
+#if !defined(__GNUC__) && !defined(__FUNCTION__)
+# define __FUNCTION__ __func__ /* C99 */
+#endif
+
+# if defined(NO_INLINE) || defined(DO_PROTOTYPES)
+
+# if !defined(__arm__)
+# if !defined(__sparc__) && !defined(__sparc) && !defined(__arm32__) \
+ && !(defined(__alpha__) && defined(linux)) \
+ && !(defined(__ia64__) && defined(linux)) \
+
+extern _X_EXPORT void outb(unsigned short, unsigned char);
+extern _X_EXPORT void outw(unsigned short, unsigned short);
+extern _X_EXPORT void outl(unsigned short, unsigned int);
+extern _X_EXPORT unsigned int inb(unsigned short);
+extern _X_EXPORT unsigned int inw(unsigned short);
+extern _X_EXPORT unsigned int inl(unsigned short);
+
+# else /* __sparc__, __arm32__, __alpha__*/
+
+extern _X_EXPORT void outb(unsigned long, unsigned char);
+extern _X_EXPORT void outw(unsigned long, unsigned short);
+extern _X_EXPORT void outl(unsigned long, unsigned int);
+extern _X_EXPORT unsigned int inb(unsigned long);
+extern _X_EXPORT unsigned int inw(unsigned long);
+extern _X_EXPORT unsigned int inl(unsigned long);
+
+# endif /* __sparc__, __arm32__, __alpha__ */
+# endif /* __arm__ */
+
+# if defined(__powerpc__) && !defined(__OpenBSD__)
+extern unsigned long ldq_u(unsigned long *);
+extern unsigned long ldl_u(unsigned int *);
+extern unsigned long ldw_u(unsigned short *);
+extern void stq_u(unsigned long, unsigned long *);
+extern void stl_u(unsigned long, unsigned int *);
+extern void stw_u(unsigned long, unsigned short *);
+extern void mem_barrier(void);
+extern void write_mem_barrier(void);
+extern void stl_brx(unsigned long, volatile unsigned char *, int);
+extern void stw_brx(unsigned short, volatile unsigned char *, int);
+extern unsigned long ldl_brx(volatile unsigned char *, int);
+extern unsigned short ldw_brx(volatile unsigned char *, int);
+# endif /* __powerpc__ && !__OpenBSD */
+
+# endif /* NO_INLINE || DO_PROTOTYPES */
+
+# ifndef NO_INLINE
+# ifdef __GNUC__
+# ifdef __i386__
+
+# ifdef __SSE__
+# define write_mem_barrier() __asm__ __volatile__ ("sfence" : : : "memory")
+# else
+# define write_mem_barrier() __asm__ __volatile__ ("lock; addl $0,0(%%esp)" : : : "memory")
+# endif
+
+# ifdef __SSE2__
+# define mem_barrier() __asm__ __volatile__ ("mfence" : : : "memory")
+# else
+# define mem_barrier() __asm__ __volatile__ ("lock; addl $0,0(%%esp)" : : : "memory")
+# endif
+
+# elif defined __alpha__
+
+# define mem_barrier() __asm__ __volatile__ ("mb" : : : "memory")
+# define write_mem_barrier() __asm__ __volatile__ ("wmb" : : : "memory")
+
+# elif defined __amd64__
+
+# define mem_barrier() __asm__ __volatile__ ("mfence" : : : "memory")
+# define write_mem_barrier() __asm__ __volatile__ ("sfence" : : : "memory")
+
+# elif defined __ia64__
+
+# ifndef __INTEL_COMPILER
+# define mem_barrier() __asm__ __volatile__ ("mf" : : : "memory")
+# define write_mem_barrier() __asm__ __volatile__ ("mf" : : : "memory")
+# else
+# include "ia64intrin.h"
+# define mem_barrier() __mf()
+# define write_mem_barrier() __mf()
+# endif
+
+# elif defined __mips__
+ /* Note: sync instruction requires MIPS II instruction set */
+# define mem_barrier() \
+ __asm__ __volatile__( \
+ ".set push\n\t" \
+ ".set noreorder\n\t" \
+ ".set mips2\n\t" \
+ "sync\n\t" \
+ ".set pop" \
+ : /* no output */ \
+ : /* no input */ \
+ : "memory")
+# define write_mem_barrier() mem_barrier()
+
+# elif defined __powerpc__
+
+# if defined(linux) && defined(__powerpc64__)
+# include <linux/version.h>
+# if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 0)
+# include <asm/memory.h>
+# endif
+# endif /* defined(linux) && defined(__powerpc64__) */
+
+# ifndef eieio /* We deal with arch-specific eieio() routines above... */
+# define eieio() __asm__ __volatile__ ("eieio" ::: "memory")
+# endif /* eieio */
+# define mem_barrier() eieio()
+# define write_mem_barrier() eieio()
+
+# elif defined __sparc__
+
+# define barrier() __asm__ __volatile__ (".word 0x8143e00a" : : : "memory")
+# define mem_barrier() /* XXX: nop for now */
+# define write_mem_barrier() /* XXX: nop for now */
+# endif
+# endif /* __GNUC__ */
+# endif /* NO_INLINE */
+
+# ifndef mem_barrier
+# define mem_barrier() /* NOP */
+# endif
+
+# ifndef write_mem_barrier
+# define write_mem_barrier() /* NOP */
+# endif
+
+
+# ifndef NO_INLINE
+# ifdef __GNUC__
+
+/* Define some packed structures to use with unaligned accesses */
+
+struct __una_u64 { uint64_t x __attribute__((packed)); };
+struct __una_u32 { uint32_t x __attribute__((packed)); };
+struct __una_u16 { uint16_t x __attribute__((packed)); };
+
+/* Elemental unaligned loads */
+
+static __inline__ uint64_t ldq_u(uint64_t *p)
+{
+ const struct __una_u64 *ptr = (const struct __una_u64 *) p;
+ return ptr->x;
+}
+
+static __inline__ uint32_t ldl_u(uint32_t *p)
+{
+ const struct __una_u32 *ptr = (const struct __una_u32 *) p;
+ return ptr->x;
+}
+
+static __inline__ uint16_t ldw_u(uint16_t *p)
+{
+ const struct __una_u16 *ptr = (const struct __una_u16 *) p;
+ return ptr->x;
+}
+
+/* Elemental unaligned stores */
+
+static __inline__ void stq_u(uint64_t val, uint64_t *p)
+{
+ struct __una_u64 *ptr = (struct __una_u64 *) p;
+ ptr->x = val;
+}
+
+static __inline__ void stl_u(uint32_t val, uint32_t *p)
+{
+ struct __una_u32 *ptr = (struct __una_u32 *) p;
+ ptr->x = val;
+}
+
+static __inline__ void stw_u(uint16_t val, uint16_t *p)
+{
+ struct __una_u16 *ptr = (struct __una_u16 *) p;
+ ptr->x = val;
+}
+# else /* !__GNUC__ */
+
+#include <string.h> /* needed for memmove */
+
+static __inline__ uint64_t ldq_u(uint64_t *p)
+{
+ uint64_t ret;
+ memmove(&ret, p, sizeof(*p));
+ return ret;
+}
+
+static __inline__ uint32_t ldl_u(uint32_t *p)
+{
+ uint32_t ret;
+ memmove(&ret, p, sizeof(*p));
+ return ret;
+}
+
+static __inline__ uint16_t ldw_u(uint16_t *p)
+{
+ uint16_t ret;
+ memmove(&ret, p, sizeof(*p));
+ return ret;
+}
+
+static __inline__ void stq_u(uint64_t val, uint64_t *p)
+{
+ uint64_t tmp = val;
+ memmove(p, &tmp, sizeof(*p));
+}
+
+static __inline__ void stl_u(uint32_t val, uint32_t *p)
+{
+ uint32_t tmp = val;
+ memmove(p, &tmp, sizeof(*p));
+}
+
+static __inline__ void stw_u(uint16_t val, uint16_t *p)
+{
+ uint16_t tmp = val;
+ memmove(p, &tmp, sizeof(*p));
+}
+
+# endif /* __GNUC__ */
+# endif /* NO_INLINE */
+
+# ifndef NO_INLINE
+# ifdef __GNUC__
+# if (defined(linux) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)) && (defined(__alpha__))
+
+# ifdef linux
+/* for Linux on Alpha, we use the LIBC _inx/_outx routines */
+/* note that the appropriate setup via "ioperm" needs to be done */
+/* *before* any inx/outx is done. */
+
+extern _X_EXPORT void (*_alpha_outb)(char val, unsigned long port);
+static __inline__ void
+outb(unsigned long port, unsigned char val)
+{
+ _alpha_outb(val, port);
+}
+
+extern _X_EXPORT void (*_alpha_outw)(short val, unsigned long port);
+static __inline__ void
+outw(unsigned long port, unsigned short val)
+{
+ _alpha_outw(val, port);
+}
+
+extern _X_EXPORT void (*_alpha_outl)(int val, unsigned long port);
+static __inline__ void
+outl(unsigned long port, unsigned int val)
+{
+ _alpha_outl(val, port);
+}
+
+extern _X_EXPORT unsigned int (*_alpha_inb)(unsigned long port);
+static __inline__ unsigned int
+inb(unsigned long port)
+{
+ return _alpha_inb(port);
+}
+
+extern _X_EXPORT unsigned int (*_alpha_inw)(unsigned long port);
+static __inline__ unsigned int
+inw(unsigned long port)
+{
+ return _alpha_inw(port);
+}
+
+extern _X_EXPORT unsigned int (*_alpha_inl)(unsigned long port);
+static __inline__ unsigned int
+inl(unsigned long port)
+{
+ return _alpha_inl(port);
+}
+
+# endif /* linux */
+
+# if (defined(__FreeBSD__) || defined(__OpenBSD__)) \
+ && !defined(DO_PROTOTYPES)
+
+/* for FreeBSD and OpenBSD on Alpha, we use the libio (resp. libalpha) */
+/* inx/outx routines */
+/* note that the appropriate setup via "ioperm" needs to be done */
+/* *before* any inx/outx is done. */
+
+extern _X_EXPORT void outb(unsigned int port, unsigned char val);
+extern _X_EXPORT void outw(unsigned int port, unsigned short val);
+extern _X_EXPORT void outl(unsigned int port, unsigned int val);
+extern _X_EXPORT unsigned char inb(unsigned int port);
+extern _X_EXPORT unsigned short inw(unsigned int port);
+extern _X_EXPORT unsigned int inl(unsigned int port);
+
+# endif /* (__FreeBSD__ || __OpenBSD__ ) && !DO_PROTOTYPES */
+
+
+#if defined(__NetBSD__)
+#include <machine/pio.h>
+#endif /* __NetBSD__ */
+
+# elif defined(linux) && defined(__ia64__)
+
+# include <inttypes.h>
+
+# include <sys/io.h>
+
+# undef outb
+# undef outw
+# undef outl
+# undef inb
+# undef inw
+# undef inl
+extern _X_EXPORT void outb(unsigned long port, unsigned char val);
+extern _X_EXPORT void outw(unsigned long port, unsigned short val);
+extern _X_EXPORT void outl(unsigned long port, unsigned int val);
+extern _X_EXPORT unsigned int inb(unsigned long port);
+extern _X_EXPORT unsigned int inw(unsigned long port);
+extern _X_EXPORT unsigned int inl(unsigned long port);
+
+# elif (defined(linux) || defined(__FreeBSD__)) && defined(__amd64__)
+
+# include <inttypes.h>
+
+static __inline__ void
+outb(unsigned short port, unsigned char val)
+{
+ __asm__ __volatile__("outb %0,%1" : :"a" (val), "d" (port));
+}
+
+
+static __inline__ void
+outw(unsigned short port, unsigned short val)
+{
+ __asm__ __volatile__("outw %0,%1" : :"a" (val), "d" (port));
+}
+
+static __inline__ void
+outl(unsigned short port, unsigned int val)
+{
+ __asm__ __volatile__("outl %0,%1" : :"a" (val), "d" (port));
+}
+
+static __inline__ unsigned int
+inb(unsigned short port)
+{
+ unsigned char ret;
+ __asm__ __volatile__("inb %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inw(unsigned short port)
+{
+ unsigned short ret;
+ __asm__ __volatile__("inw %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inl(unsigned short port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("inl %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+# elif (defined(linux) || defined(sun) || defined(__OpenBSD__) || defined(__FreeBSD__)) && defined(__sparc__)
+
+# ifndef ASI_PL
+# define ASI_PL 0x88
+# endif
+
+static __inline__ void
+outb(unsigned long port, unsigned char val)
+{
+ __asm__ __volatile__("stba %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (port), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ void
+outw(unsigned long port, unsigned short val)
+{
+ __asm__ __volatile__("stha %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (port), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ void
+outl(unsigned long port, unsigned int val)
+{
+ __asm__ __volatile__("sta %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (port), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ unsigned int
+inb(unsigned long port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("lduba [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (port), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ unsigned int
+inw(unsigned long port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("lduha [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (port), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ unsigned int
+inl(unsigned long port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("lda [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (port), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ unsigned char
+xf86ReadMmio8(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned char ret;
+
+ __asm__ __volatile__("lduba [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (addr), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ unsigned short
+xf86ReadMmio16Be(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned short ret;
+
+ __asm__ __volatile__("lduh [%1], %0"
+ : "=r" (ret)
+ : "r" (addr));
+ return ret;
+}
+
+static __inline__ unsigned short
+xf86ReadMmio16Le(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned short ret;
+
+ __asm__ __volatile__("lduha [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (addr), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ unsigned int
+xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned int ret;
+
+ __asm__ __volatile__("ld [%1], %0"
+ : "=r" (ret)
+ : "r" (addr));
+ return ret;
+}
+
+static __inline__ unsigned int
+xf86ReadMmio32Le(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned int ret;
+
+ __asm__ __volatile__("lda [%1] %2, %0"
+ : "=r" (ret)
+ : "r" (addr), "i" (ASI_PL));
+ return ret;
+}
+
+static __inline__ void
+xf86WriteMmio8(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("stba %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ void
+xf86WriteMmio16Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("sth %0, [%1]"
+ : /* No outputs */
+ : "r" (val), "r" (addr));
+ barrier();
+}
+
+static __inline__ void
+xf86WriteMmio16Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("stha %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ void
+xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("st %0, [%1]"
+ : /* No outputs */
+ : "r" (val), "r" (addr));
+ barrier();
+}
+
+static __inline__ void
+xf86WriteMmio32Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("sta %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+ barrier();
+}
+
+static __inline__ void
+xf86WriteMmio8NB(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("stba %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+}
+
+static __inline__ void
+xf86WriteMmio16BeNB(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("sth %0, [%1]"
+ : /* No outputs */
+ : "r" (val), "r" (addr));
+}
+
+static __inline__ void
+xf86WriteMmio16LeNB(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("stha %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+}
+
+static __inline__ void
+xf86WriteMmio32BeNB(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("st %0, [%1]"
+ : /* No outputs */
+ : "r" (val), "r" (addr));
+}
+
+static __inline__ void
+xf86WriteMmio32LeNB(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("sta %0, [%1] %2"
+ : /* No outputs */
+ : "r" (val), "r" (addr), "i" (ASI_PL));
+}
+
+# elif defined(__mips__) || (defined(__arm32__) && !defined(__linux__))
+# ifdef __arm32__
+# define PORT_SIZE long
+# else
+# define PORT_SIZE short
+# endif
+
+_X_EXPORT unsigned int IOPortBase; /* Memory mapped I/O port area */
+
+static __inline__ void
+outb(unsigned PORT_SIZE port, unsigned char val)
+{
+ *(volatile unsigned char*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val;
+}
+
+static __inline__ void
+outw(unsigned PORT_SIZE port, unsigned short val)
+{
+ *(volatile unsigned short*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val;
+}
+
+static __inline__ void
+outl(unsigned PORT_SIZE port, unsigned int val)
+{
+ *(volatile unsigned int*)(((unsigned PORT_SIZE)(port))+IOPortBase) = val;
+}
+
+static __inline__ unsigned int
+inb(unsigned PORT_SIZE port)
+{
+ return *(volatile unsigned char*)(((unsigned PORT_SIZE)(port))+IOPortBase);
+}
+
+static __inline__ unsigned int
+inw(unsigned PORT_SIZE port)
+{
+ return *(volatile unsigned short*)(((unsigned PORT_SIZE)(port))+IOPortBase);
+}
+
+static __inline__ unsigned int
+inl(unsigned PORT_SIZE port)
+{
+ return *(volatile unsigned int*)(((unsigned PORT_SIZE)(port))+IOPortBase);
+}
+
+
+# if defined(__mips__)
+# ifdef linux /* don't mess with other OSs */
+# if X_BYTE_ORDER == X_BIG_ENDIAN
+static __inline__ unsigned int
+xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+ unsigned int ret;
+
+ __asm__ __volatile__("lw %0, 0(%1)"
+ : "=r" (ret)
+ : "r" (addr));
+ return ret;
+}
+
+static __inline__ void
+xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ unsigned long addr = ((unsigned long)base) + offset;
+
+ __asm__ __volatile__("sw %0, 0(%1)"
+ : /* No outputs */
+ : "r" (val), "r" (addr));
+}
+# endif
+# endif /* !linux */
+# endif /* __mips__ */
+
+# elif (defined(linux) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)) && defined(__powerpc__)
+
+# ifndef MAP_FAILED
+# define MAP_FAILED ((void *)-1)
+# endif
+
+extern _X_EXPORT volatile unsigned char *ioBase;
+
+static __inline__ unsigned char
+xf86ReadMmio8(__volatile__ void *base, const unsigned long offset)
+{
+ register unsigned char val;
+ __asm__ __volatile__(
+ "lbzx %0,%1,%2\n\t"
+ "eieio"
+ : "=r" (val)
+ : "b" (base), "r" (offset),
+ "m" (*((volatile unsigned char *)base+offset)));
+ return val;
+}
+
+static __inline__ unsigned short
+xf86ReadMmio16Be(__volatile__ void *base, const unsigned long offset)
+{
+ register unsigned short val;
+ __asm__ __volatile__(
+ "lhzx %0,%1,%2\n\t"
+ "eieio"
+ : "=r" (val)
+ : "b" (base), "r" (offset),
+ "m" (*((volatile unsigned char *)base+offset)));
+ return val;
+}
+
+static __inline__ unsigned short
+xf86ReadMmio16Le(__volatile__ void *base, const unsigned long offset)
+{
+ register unsigned short val;
+ __asm__ __volatile__(
+ "lhbrx %0,%1,%2\n\t"
+ "eieio"
+ : "=r" (val)
+ : "b" (base), "r" (offset),
+ "m" (*((volatile unsigned char *)base+offset)));
+ return val;
+}
+
+static __inline__ unsigned int
+xf86ReadMmio32Be(__volatile__ void *base, const unsigned long offset)
+{
+ register unsigned int val;
+ __asm__ __volatile__(
+ "lwzx %0,%1,%2\n\t"
+ "eieio"
+ : "=r" (val)
+ : "b" (base), "r" (offset),
+ "m" (*((volatile unsigned char *)base+offset)));
+ return val;
+}
+
+static __inline__ unsigned int
+xf86ReadMmio32Le(__volatile__ void *base, const unsigned long offset)
+{
+ register unsigned int val;
+ __asm__ __volatile__(
+ "lwbrx %0,%1,%2\n\t"
+ "eieio"
+ : "=r" (val)
+ : "b" (base), "r" (offset),
+ "m" (*((volatile unsigned char *)base+offset)));
+ return val;
+}
+
+static __inline__ void
+xf86WriteMmioNB8(__volatile__ void *base, const unsigned long offset,
+ const unsigned char val)
+{
+ __asm__ __volatile__(
+ "stbx %1,%2,%3\n\t"
+ : "=m" (*((volatile unsigned char *)base+offset))
+ : "r" (val), "b" (base), "r" (offset));
+}
+
+static __inline__ void
+xf86WriteMmioNB16Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned short val)
+{
+ __asm__ __volatile__(
+ "sthbrx %1,%2,%3\n\t"
+ : "=m" (*((volatile unsigned char *)base+offset))
+ : "r" (val), "b" (base), "r" (offset));
+}
+
+static __inline__ void
+xf86WriteMmioNB16Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned short val)
+{
+ __asm__ __volatile__(
+ "sthx %1,%2,%3\n\t"
+ : "=m" (*((volatile unsigned char *)base+offset))
+ : "r" (val), "b" (base), "r" (offset));
+}
+
+static __inline__ void
+xf86WriteMmioNB32Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ __asm__ __volatile__(
+ "stwbrx %1,%2,%3\n\t"
+ : "=m" (*((volatile unsigned char *)base+offset))
+ : "r" (val), "b" (base), "r" (offset));
+}
+
+static __inline__ void
+xf86WriteMmioNB32Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ __asm__ __volatile__(
+ "stwx %1,%2,%3\n\t"
+ : "=m" (*((volatile unsigned char *)base+offset))
+ : "r" (val), "b" (base), "r" (offset));
+}
+
+static __inline__ void
+xf86WriteMmio8(__volatile__ void *base, const unsigned long offset,
+ const unsigned char val)
+{
+ xf86WriteMmioNB8(base, offset, val);
+ eieio();
+}
+
+static __inline__ void
+xf86WriteMmio16Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned short val)
+{
+ xf86WriteMmioNB16Le(base, offset, val);
+ eieio();
+}
+
+static __inline__ void
+xf86WriteMmio16Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned short val)
+{
+ xf86WriteMmioNB16Be(base, offset, val);
+ eieio();
+}
+
+static __inline__ void
+xf86WriteMmio32Le(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ xf86WriteMmioNB32Le(base, offset, val);
+ eieio();
+}
+
+static __inline__ void
+xf86WriteMmio32Be(__volatile__ void *base, const unsigned long offset,
+ const unsigned int val)
+{
+ xf86WriteMmioNB32Be(base, offset, val);
+ eieio();
+}
+
+
+static __inline__ void
+outb(unsigned short port, unsigned char value)
+{
+ if(ioBase == MAP_FAILED) return;
+ xf86WriteMmio8((void *)ioBase, port, value);
+}
+
+static __inline__ void
+outw(unsigned short port, unsigned short value)
+{
+ if(ioBase == MAP_FAILED) return;
+ xf86WriteMmio16Le((void *)ioBase, port, value);
+}
+
+static __inline__ void
+outl(unsigned short port, unsigned int value)
+{
+ if(ioBase == MAP_FAILED) return;
+ xf86WriteMmio32Le((void *)ioBase, port, value);
+}
+
+static __inline__ unsigned int
+inb(unsigned short port)
+{
+ if(ioBase == MAP_FAILED) return 0;
+ return xf86ReadMmio8((void *)ioBase, port);
+}
+
+static __inline__ unsigned int
+inw(unsigned short port)
+{
+ if(ioBase == MAP_FAILED) return 0;
+ return xf86ReadMmio16Le((void *)ioBase, port);
+}
+
+static __inline__ unsigned int
+inl(unsigned short port)
+{
+ if(ioBase == MAP_FAILED) return 0;
+ return xf86ReadMmio32Le((void *)ioBase, port);
+}
+
+#elif defined(__arm__) && defined(__linux__)
+
+/* for Linux on ARM, we use the LIBC inx/outx routines */
+/* note that the appropriate setup via "ioperm" needs to be done */
+/* *before* any inx/outx is done. */
+
+#include <sys/io.h>
+
+static __inline__ void
+xf_outb(unsigned short port, unsigned char val)
+{
+ outb(val, port);
+}
+
+static __inline__ void
+xf_outw(unsigned short port, unsigned short val)
+{
+ outw(val, port);
+}
+
+static __inline__ void
+xf_outl(unsigned short port, unsigned int val)
+{
+ outl(val, port);
+}
+
+#define outb xf_outb
+#define outw xf_outw
+#define outl xf_outl
+
+# else /* ix86 */
+
+# if !defined(__SUNPRO_C)
+# if !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__s390__) && !defined(__m32r__)
+# ifdef GCCUSESGAS
+
+/*
+ * If gcc uses gas rather than the native assembler, the syntax of these
+ * inlines has to be different. DHD
+ */
+
+static __inline__ void
+outb(unsigned short port, unsigned char val)
+{
+ __asm__ __volatile__("outb %0,%1" : :"a" (val), "d" (port));
+}
+
+
+static __inline__ void
+outw(unsigned short port, unsigned short val)
+{
+ __asm__ __volatile__("outw %0,%1" : :"a" (val), "d" (port));
+}
+
+static __inline__ void
+outl(unsigned short port, unsigned int val)
+{
+ __asm__ __volatile__("outl %0,%1" : :"a" (val), "d" (port));
+}
+
+static __inline__ unsigned int
+inb(unsigned short port)
+{
+ unsigned char ret;
+ __asm__ __volatile__("inb %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inw(unsigned short port)
+{
+ unsigned short ret;
+ __asm__ __volatile__("inw %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inl(unsigned short port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("inl %1,%0" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+# else /* GCCUSESGAS */
+
+static __inline__ void
+outb(unsigned short port, unsigned char val)
+{
+ __asm__ __volatile__("out%B0 (%1)" : :"a" (val), "d" (port));
+}
+
+static __inline__ void
+outw(unsigned short port, unsigned short val)
+{
+ __asm__ __volatile__("out%W0 (%1)" : :"a" (val), "d" (port));
+}
+
+static __inline__ void
+outl(unsigned short port, unsigned int val)
+{
+ __asm__ __volatile__("out%L0 (%1)" : :"a" (val), "d" (port));
+}
+
+static __inline__ unsigned int
+inb(unsigned short port)
+{
+ unsigned char ret;
+ __asm__ __volatile__("in%B0 (%1)" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inw(unsigned short port)
+{
+ unsigned short ret;
+ __asm__ __volatile__("in%W0 (%1)" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+static __inline__ unsigned int
+inl(unsigned short port)
+{
+ unsigned int ret;
+ __asm__ __volatile__("in%L0 (%1)" :
+ "=a" (ret) :
+ "d" (port));
+ return ret;
+}
+
+# endif /* GCCUSESGAS */
+
+# else /* !defined(FAKEIT) && !defined(__mc68000__) && !defined(__arm__) && !defined(__sh__) && !defined(__hppa__) && !defined(__m32r__) */
+
+static __inline__ void
+outb(unsigned short port, unsigned char val)
+{
+}
+
+static __inline__ void
+outw(unsigned short port, unsigned short val)
+{
+}
+
+static __inline__ void
+outl(unsigned short port, unsigned int val)
+{
+}
+
+static __inline__ unsigned int
+inb(unsigned short port)
+{
+ return 0;
+}
+
+static __inline__ unsigned int
+inw(unsigned short port)
+{
+ return 0;
+}
+
+static __inline__ unsigned int
+inl(unsigned short port)
+{
+ return 0;
+}
+
+# endif /* FAKEIT */
+# endif /* __SUNPRO_C */
+
+# endif /* ix86 */
+
+# else /* !GNUC */
+# if defined(__STDC__) && (__STDC__ == 1)
+# ifndef asm
+# define asm __asm
+# endif
+# endif
+# ifndef SCO325
+# if defined(__UNIXWARE__)
+# /* avoid including <sys/types.h> for <sys/inline.h> on UnixWare */
+# define ushort unsigned short
+# define ushort_t unsigned short
+# define ulong unsigned long
+# define ulong_t unsigned long
+# define uint_t unsigned int
+# define uchar_t unsigned char
+# endif /* __UNIXWARE__ */
+# if !defined(__SUNPRO_C) && !defined(_MSC_VER)
+# include <sys/inline.h>
+# endif
+# else
+# include "scoasm.h"
+# endif
+# if (!defined(__HIGHC__) && !defined(__SUNPRO_C) && !defined(_MSC_VER)) || \
+ defined(__USLC__)
+# pragma asm partial_optimization outl
+# pragma asm partial_optimization outw
+# pragma asm partial_optimization outb
+# pragma asm partial_optimization inl
+# pragma asm partial_optimization inw
+# pragma asm partial_optimization inb
+# endif
+# endif /* __GNUC__ */
+
+# endif /* NO_INLINE */
+
+# ifdef __alpha__
+/* entry points for Mmio memory access routines */
+extern _X_EXPORT int (*xf86ReadMmio8)(void *, unsigned long);
+extern _X_EXPORT int (*xf86ReadMmio16)(void *, unsigned long);
+# ifndef STANDALONE_MMIO
+extern _X_EXPORT int (*xf86ReadMmio32)(void *, unsigned long);
+# else
+/* Some DRI 3D drivers need MMIO_IN32. */
+static __inline__ int
+xf86ReadMmio32(void *Base, unsigned long Offset)
+{
+ mem_barrier();
+ return *(volatile unsigned int*)((unsigned long)Base+(Offset));
+}
+# endif
+extern _X_EXPORT void (*xf86WriteMmio8)(int, void *, unsigned long);
+extern _X_EXPORT void (*xf86WriteMmio16)(int, void *, unsigned long);
+extern _X_EXPORT void (*xf86WriteMmio32)(int, void *, unsigned long);
+extern _X_EXPORT void (*xf86WriteMmioNB8)(int, void *, unsigned long);
+extern _X_EXPORT void (*xf86WriteMmioNB16)(int, void *, unsigned long);
+extern _X_EXPORT void (*xf86WriteMmioNB32)(int, void *, unsigned long);
+
+/* Some macros to hide the system dependencies for MMIO accesses */
+/* Changed to kill noise generated by gcc's -Wcast-align */
+# define MMIO_IN8(base, offset) (*xf86ReadMmio8)(base, offset)
+# define MMIO_IN16(base, offset) (*xf86ReadMmio16)(base, offset)
+# ifndef STANDALONE_MMIO
+# define MMIO_IN32(base, offset) (*xf86ReadMmio32)(base, offset)
+# else
+# define MMIO_IN32(base, offset) xf86ReadMmio32(base, offset)
+# endif
+
+# define MMIO_OUT32(base, offset, val) \
+ do { \
+ write_mem_barrier(); \
+ *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val); \
+ } while (0)
+# define MMIO_ONB32(base, offset, val) \
+ *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val)
+
+# define MMIO_OUT8(base, offset, val) \
+ (*xf86WriteMmio8)((CARD8)(val), base, offset)
+# define MMIO_OUT16(base, offset, val) \
+ (*xf86WriteMmio16)((CARD16)(val), base, offset)
+# define MMIO_ONB8(base, offset, val) \
+ (*xf86WriteMmioNB8)((CARD8)(val), base, offset)
+# define MMIO_ONB16(base, offset, val) \
+ (*xf86WriteMmioNB16)((CARD16)(val), base, offset)
+# define MMIO_MOVE32(base, offset, val) \
+ MMIO_OUT32(base, offset, val)
+
+# elif defined(__powerpc__)
+ /*
+ * we provide byteswapping and no byteswapping functions here
+ * with byteswapping as default,
+ * drivers that don't need byteswapping should define PPC_MMIO_IS_BE
+ */
+# define MMIO_IN8(base, offset) xf86ReadMmio8(base, offset)
+# define MMIO_OUT8(base, offset, val) \
+ xf86WriteMmio8(base, offset, (CARD8)(val))
+# define MMIO_ONB8(base, offset, val) \
+ xf86WriteMmioNB8(base, offset, (CARD8)(val))
+
+# if defined(PPC_MMIO_IS_BE) /* No byteswapping */
+# define MMIO_IN16(base, offset) xf86ReadMmio16Be(base, offset)
+# define MMIO_IN32(base, offset) xf86ReadMmio32Be(base, offset)
+# define MMIO_OUT16(base, offset, val) \
+ xf86WriteMmio16Be(base, offset, (CARD16)(val))
+# define MMIO_OUT32(base, offset, val) \
+ xf86WriteMmio32Be(base, offset, (CARD32)(val))
+# define MMIO_ONB16(base, offset, val) \
+ xf86WriteMmioNB16Be(base, offset, (CARD16)(val))
+# define MMIO_ONB32(base, offset, val) \
+ xf86WriteMmioNB32Be(base, offset, (CARD32)(val))
+# else /* byteswapping is the default */
+# define MMIO_IN16(base, offset) xf86ReadMmio16Le(base, offset)
+# define MMIO_IN32(base, offset) xf86ReadMmio32Le(base, offset)
+# define MMIO_OUT16(base, offset, val) \
+ xf86WriteMmio16Le(base, offset, (CARD16)(val))
+# define MMIO_OUT32(base, offset, val) \
+ xf86WriteMmio32Le(base, offset, (CARD32)(val))
+# define MMIO_ONB16(base, offset, val) \
+ xf86WriteMmioNB16Le(base, offset, (CARD16)(val))
+# define MMIO_ONB32(base, offset, val) \
+ xf86WriteMmioNB32Le(base, offset, (CARD32)(val))
+# endif
+
+# define MMIO_MOVE32(base, offset, val) \
+ xf86WriteMmio32Be(base, offset, (CARD32)(val))
+
+# elif defined(__sparc__) || defined(sparc) || defined(__sparc)
+ /*
+ * Like powerpc, we provide byteswapping and no byteswapping functions
+ * here with byteswapping as default, drivers that don't need byteswapping
+ * should define SPARC_MMIO_IS_BE (perhaps create a generic macro so that we
+ * do not need to use PPC_MMIO_IS_BE and the sparc one in all the same places
+ * of drivers?).
+ */
+# define MMIO_IN8(base, offset) xf86ReadMmio8(base, offset)
+# define MMIO_OUT8(base, offset, val) \
+ xf86WriteMmio8(base, offset, (CARD8)(val))
+# define MMIO_ONB8(base, offset, val) \
+ xf86WriteMmio8NB(base, offset, (CARD8)(val))
+
+# if defined(SPARC_MMIO_IS_BE) /* No byteswapping */
+# define MMIO_IN16(base, offset) xf86ReadMmio16Be(base, offset)
+# define MMIO_IN32(base, offset) xf86ReadMmio32Be(base, offset)
+# define MMIO_OUT16(base, offset, val) \
+ xf86WriteMmio16Be(base, offset, (CARD16)(val))
+# define MMIO_OUT32(base, offset, val) \
+ xf86WriteMmio32Be(base, offset, (CARD32)(val))
+# define MMIO_ONB16(base, offset, val) \
+ xf86WriteMmio16BeNB(base, offset, (CARD16)(val))
+# define MMIO_ONB32(base, offset, val) \
+ xf86WriteMmio32BeNB(base, offset, (CARD32)(val))
+# else /* byteswapping is the default */
+# define MMIO_IN16(base, offset) xf86ReadMmio16Le(base, offset)
+# define MMIO_IN32(base, offset) xf86ReadMmio32Le(base, offset)
+# define MMIO_OUT16(base, offset, val) \
+ xf86WriteMmio16Le(base, offset, (CARD16)(val))
+# define MMIO_OUT32(base, offset, val) \
+ xf86WriteMmio32Le(base, offset, (CARD32)(val))
+# define MMIO_ONB16(base, offset, val) \
+ xf86WriteMmio16LeNB(base, offset, (CARD16)(val))
+# define MMIO_ONB32(base, offset, val) \
+ xf86WriteMmio32LeNB(base, offset, (CARD32)(val))
+# endif
+
+# define MMIO_MOVE32(base, offset, val) \
+ xf86WriteMmio32Be(base, offset, (CARD32)(val))
+
+# else /* !__alpha__ && !__powerpc__ && !__sparc__ */
+
+# define MMIO_IN8(base, offset) \
+ *(volatile CARD8 *)(((CARD8*)(base)) + (offset))
+# define MMIO_IN16(base, offset) \
+ *(volatile CARD16 *)(void *)(((CARD8*)(base)) + (offset))
+# define MMIO_IN32(base, offset) \
+ *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset))
+# define MMIO_OUT8(base, offset, val) \
+ *(volatile CARD8 *)(((CARD8*)(base)) + (offset)) = (val)
+# define MMIO_OUT16(base, offset, val) \
+ *(volatile CARD16 *)(void *)(((CARD8*)(base)) + (offset)) = (val)
+# define MMIO_OUT32(base, offset, val) \
+ *(volatile CARD32 *)(void *)(((CARD8*)(base)) + (offset)) = (val)
+# define MMIO_ONB8(base, offset, val) MMIO_OUT8(base, offset, val)
+# define MMIO_ONB16(base, offset, val) MMIO_OUT16(base, offset, val)
+# define MMIO_ONB32(base, offset, val) MMIO_OUT32(base, offset, val)
+
+# define MMIO_MOVE32(base, offset, val) MMIO_OUT32(base, offset, val)
+
+# endif /* __alpha__ */
+#endif /* _COMPILER_H */
diff --git a/xorg-server/hw/xwin/InitInput.c b/xorg-server/hw/xwin/InitInput.c index 1e9bcad7a..d9b6ec84c 100644 --- a/xorg-server/hw/xwin/InitInput.c +++ b/xorg-server/hw/xwin/InitInput.c @@ -67,6 +67,13 @@ extern winDispatchProcPtr winProcQueryTreeOrig; #endif +void InputDevicesClosed(void) +{ + g_pwinPointer=NULL; + g_pwinKeyboard=NULL; +} + + /* Called from dix/devices.c */ /* * All of our keys generate up and down transition notifications, diff --git a/xorg-server/hw/xwin/InitOutput.c b/xorg-server/hw/xwin/InitOutput.c index 2f4b0d222..ce5bc5f92 100644 --- a/xorg-server/hw/xwin/InitOutput.c +++ b/xorg-server/hw/xwin/InitOutput.c @@ -1,6 +1,7 @@ /* Copyright 1993, 1998 The Open Group +Copyright (C) Colin Harrison 2005-2008 Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that @@ -45,14 +46,16 @@ from The Open Group. #if defined(WIN32) #include "xkbsrv.h" #endif + #ifdef RELOCATE_PROJECTROOT +#undef Status #include <shlobj.h> -typedef HRESULT (*SHGETFOLDERPATHPROC)( +typedef HRESULT (__stdcall * SHGETFOLDERPATHPROC)( HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, - LPTSTR pszPath + LPSTR pszPath ); #endif @@ -67,12 +70,13 @@ extern int g_iLastScreen; extern char * g_pszCommandLine; extern Bool g_fSilentFatalError; -extern char * g_pszLogFile; +extern const char * g_pszLogFile; extern Bool g_fLogFileChanged; extern int g_iLogVerbose; Bool g_fLogInited; extern Bool g_fXdmcpEnabled; +extern Bool g_fAuthEnabled; #ifdef HAS_DEVWINDOWS extern int g_fdMessageQueue; #endif @@ -132,6 +136,9 @@ const char * winGetBaseDir(void); #endif +static +void glx_debugging(void); + /* * For the depth 24 pixmap we default to 32 bits per pixel, but * we change this pixmap format later if we detect that the display @@ -178,9 +185,6 @@ winClipboardShutdown (void) /* Wait for the clipboard thread to exit */ pthread_join (g_ptClipboardProc, NULL); - g_fClipboardLaunched = FALSE; - g_fClipboardStarted = FALSE; - winDebug ("winClipboardShutdown - Clipboard thread has exited.\n"); } } @@ -241,7 +245,7 @@ ddxGiveUp (void) #endif if (!g_fLogInited) { - LogInit (g_pszLogFile, NULL); + g_pszLogFile = LogInit (g_pszLogFile, NULL); g_fLogInited = TRUE; } LogClose (); @@ -424,7 +428,17 @@ winFixupPaths (void) #ifdef READ_FONTDIRS { /* Open fontpath configuration file */ +#if defined WIN32 && defined __MINGW32__ + static Bool once = False; + char buffer[MAX_PATH]; + snprintf(buffer, sizeof(buffer), "%s\\font-dirs", basedir); + buffer[sizeof(buffer)-1] = 0; + FILE *fontdirs = fopen(buffer, "rt"); + if (once) fontdirs = NULL; + else once = True; +#else FILE *fontdirs = fopen(ETCX11DIR "/font-dirs", "rt"); +#endif if (fontdirs != NULL) { char buffer[256]; @@ -624,6 +638,14 @@ winFixupPaths (void) buffer[sizeof(buffer)-1] = 0; putenv(buffer); } + if (getenv("XHOSTPREFIX") == NULL) + { + char buffer[MAX_PATH]; + snprintf(buffer, sizeof(buffer), "XHOSTPREFIX=%s\\X", + basedir); + buffer[sizeof(buffer)-1] = 0; + putenv(buffer); + } if (getenv("HOME") == NULL) { HMODULE shfolder; @@ -661,16 +683,17 @@ winFixupPaths (void) if (size && size < sizeof(buffer)) { snprintf(buffer + size, sizeof(buffer) - size, - "XWin.%s.log", display); + "VCXSrv.%s.log", display); buffer[sizeof(buffer)-1] = 0; g_pszLogFile = buffer; + GetLongPathName(buffer, buffer, MAX_PATH); winMsg (X_DEFAULT, "Logfile set to \"%s\"\n", g_pszLogFile); } } { static char xkbbasedir[MAX_PATH]; - snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkb", basedir); + snprintf(xkbbasedir, sizeof(xkbbasedir), "%s\\xkbdata", basedir); if (sizeof(xkbbasedir) > 0) xkbbasedir[sizeof(xkbbasedir)-1] = 0; XkbBaseDirectory = xkbbasedir; @@ -685,9 +708,6 @@ OsVendorInit (void) /* Re-initialize global variables on server reset */ winInitializeGlobals (); - LogInit (NULL, NULL); - LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose); - winFixupPaths(); #ifdef DDXOSVERRORF @@ -702,7 +722,7 @@ OsVendorInit (void) * avoid the second call */ g_fLogInited = TRUE; - LogInit (g_pszLogFile, NULL); + g_pszLogFile = LogInit (g_pszLogFile, NULL); } LogSetParameter (XLOG_FLUSH, 1); LogSetParameter (XLOG_VERBOSITY, g_iLogVerbose); @@ -873,7 +893,7 @@ winUseMsg (void) "\tEquivalent to XKBOptions in XF86Config files.\n"); ErrorF ("-logfile filename\n" - "\tWrite logmessages to <filename> instead of /tmp/Xwin.log.\n"); + "\tWrite logmessages to <filename>.\n"); ErrorF ("-logverbose verbosity\n" "\tSet the verbosity of logmessages. [NOTE: Only a few messages\n" @@ -903,7 +923,7 @@ ddxUseMsg(void) /* Log file will not be opened for UseMsg unless we open it now */ if (!g_fLogInited) { - LogInit (g_pszLogFile, NULL); + g_pszLogFile = LogInit (g_pszLogFile, NULL); g_fLogInited = TRUE; } LogClose (); @@ -911,9 +931,9 @@ ddxUseMsg(void) /* Notify user where UseMsg text can be found.*/ if (!g_fNoHelpMessageBox) winMessageBoxF ("The " PROJECT_NAME " help text has been printed to " - "/tmp/XWin.log.\n" - "Please open /tmp/XWin.log to read the help text.\n", - MB_ICONINFORMATION); + "%s.\n" + "Please open %s to read the help text.\n", + MB_ICONINFORMATION, g_pszLogFile, g_pszLogFile); } /* See Porting Layer Definition - p. 20 */ @@ -956,9 +976,6 @@ InitOutput (ScreenInfo *screenInfo, int argc, char *argv[]) if (!winReadConfigfile ()) winErrorFVerb (1, "InitOutput - Error reading config file\n"); #else - winMsg(X_INFO, "xorg.conf is not supported\n"); - winMsg(X_INFO, "See http://x.cygwin.com/docs/faq/cygwin-x-faq.html " - "for more information\n"); winConfigFiles (); #endif @@ -1022,7 +1039,7 @@ InitOutput (ScreenInfo *screenInfo, int argc, char *argv[]) #if defined(XCSECURITY) /* Generate a cookie used by internal clients for authorization */ - if (g_fXdmcpEnabled) + if (g_fXdmcpEnabled || g_fAuthEnabled) winGenerateAuthorization (); #endif @@ -1034,6 +1051,8 @@ InitOutput (ScreenInfo *screenInfo, int argc, char *argv[]) * Apply locale specified in LANG environment variable. */ setlocale (LC_ALL, ""); + + glx_debugging(); } #endif @@ -1062,7 +1081,7 @@ winCheckDisplayNumber (void) /* Check display range */ nDisp = atoi (display); - if (nDisp < 0 || nDisp > 65535) + if (nDisp < 0 || nDisp > 59535) { ErrorF ("winCheckDisplayNumber - Bad display number: %d\n", nDisp); return FALSE; @@ -1109,10 +1128,29 @@ winCheckDisplayNumber (void) if (GetLastError () == ERROR_ALREADY_EXISTS) { ErrorF ("winCheckDisplayNumber - " - PROJECT_NAME " is already running on display %d\n", + "VCXsrv, Xming or Cygwin/X is already running on display %d\n", nDisp); return FALSE; } return TRUE; } + +/* GLX debugging helpers */ +#include <../glx/glapi.h> + +static +void warn_func(void * p1, const char *format, ...) { + va_list v; + va_start(v, format); + vfprintf(stderr, format, v); + va_end(v); + fprintf(stderr,"\n"); +} + +static +void glx_debugging(void) +{ + _glapi_set_warning_func(warn_func); + _glapi_noop_enable_warnings(TRUE); +} diff --git a/xorg-server/hw/xwin/XWin.rc b/xorg-server/hw/xwin/XWin.rc index 5a254e1ab..bc845c0b1 100644 --- a/xorg-server/hw/xwin/XWin.rc +++ b/xorg-server/hw/xwin/XWin.rc @@ -1,109 +1,103 @@ -/* - *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved. - * - *Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - *"Software"), to deal in the Software without restriction, including - *without limitation the rights to use, copy, modify, merge, publish, - *distribute, sublicense, and/or sell copies of the Software, and to - *permit persons to whom the Software is furnished to do so, subject to - *the following conditions: - * - *The above copyright notice and this permission notice shall be - *included in all copies or substantial portions of the Software. - * - *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR - *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - *Except as contained in this notice, the name of Harold L Hunt II - *shall not be used in advertising or otherwise to promote the sale, use - *or other dealings in this Software without prior written authorization - *from Harold L Hunt II. - * - * Authors: Harold L Hunt II - */ - -#include "windows.h" -#include "winresource.h" - -/* - * Dialogs - */ - -/* About */ -ABOUT_BOX DIALOG DISCARDABLE 32, 32, 240, 105 -STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE -CAPTION "About " PROJECT_NAME -FONT 8, "MS Sans Serif" -BEGIN - CONTROL PROJECT_NAME " Website", ID_ABOUT_WEBSITE, "Button", - BS_OWNERDRAW | WS_TABSTOP, 30, 45, 75, 15 - CONTROL "Change Log", ID_ABOUT_CHANGELOG, "Button", - BS_OWNERDRAW | WS_TABSTOP, 135, 45, 75, 15 - CONTROL "User's Guide", ID_ABOUT_UG, "Button", - BS_OWNERDRAW | WS_TABSTOP, 30, 65, 75, 15 - CONTROL "FAQ", ID_ABOUT_FAQ, "Button", - BS_OWNERDRAW | WS_TABSTOP, 135, 65, 75, 15 - - DEFPUSHBUTTON "&OK", IDOK, 95, 85, 50, 15 - - CTEXT PROJECT_NAME " X Server. Use the links below to learn more about the " PROJECT_NAME " project.", IDC_STATIC, 5, 5, 230, 35 -END - - -/* Depth change */ - -DEPTH_CHANGE_BOX DIALOG DISCARDABLE 32, 32, 180, 100 -STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | DS_CENTERMOUSE -FONT 8, "MS Sans Serif" -CAPTION PROJECT_NAME -BEGIN - DEFPUSHBUTTON "Dismiss", IDOK, 66, 80, 50, 14 - CTEXT PROJECT_NAME, IDC_STATIC, 40, 12, 100, 8 - CTEXT "Disruptive screen configuration change.", IDC_STATIC, 7, 40, 166, 8 - CTEXT "Restore previous resolution to use " PROJECT_NAME ".", IDC_STATIC, 7, 52, 166, 8 -END - - -/* Exit */ - -EXIT_DIALOG DIALOG DISCARDABLE 32, 32, 180, 78 -STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE -FONT 8, "MS Sans Serif" -CAPTION "Exit " PROJECT_NAME "?" -BEGIN - PUSHBUTTON "E&xit", IDOK, 55, 56, 30, 14 - DEFPUSHBUTTON "&Cancel", IDCANCEL, 95, 56, 30, 14 - CTEXT "E&xiting will close all screens running on this display.", IDC_STATIC, 7, 12, 166, 8 - CTEXT "No information about connected clients available.", IDC_CLIENTS_CONNECTED, 7, 24, 166, 8 - CTEXT "Proceed with shutdown of this display/server?", IDC_STATIC, 7, 36, 166, 8 -END - - -/* - * Menus - */ - -IDM_TRAYICON_MENU MENU DISCARDABLE -BEGIN - POPUP "TRAYICON_MENU" - BEGIN - MENUITEM "&Hide Root Window", ID_APP_HIDE_ROOT - MENUITEM "&About...", ID_APP_ABOUT - MENUITEM SEPARATOR - MENUITEM "E&xit", ID_APP_EXIT - END -END - - -/* - * Icons - */ - -IDI_XWIN ICON DISCARDABLE "X.ico" -IDI_XWIN_BOXED ICON DISCARDABLE "X-boxed.ico" +/*
+ *Copyright (C) 2002-2004 Harold L Hunt II All Rights Reserved.
+ *Copyright (C) 2008 Yaakov Selkowitz All Rights Reserved
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the names of the authors
+ *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 authors.
+ *
+ * Authors: Harold L Hunt II, Yaakov Selkowitz
+ */
+
+#include <windows.h>
+#include "winresource.h"
+#include "xwin-config.h"
+
+/*
+ * Dialogs
+ */
+
+/* About */
+ABOUT_BOX DIALOGEX DISCARDABLE 32, 32, 260, 95
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE
+CAPTION "About VcXsrv"
+FONT 8, "MS Shell Dlg 2"
+BEGIN
+ CONTROL IDI_XWIN, IDC_STATIC, "Static", SS_ICON, 8, 8, 32, 32
+ LTEXT "VcXsrv X Server ", IDC_STATIC, 36, 8, 220, 8
+ LTEXT "Version 1.1.1 (21 Sept 2009)", IDC_STATIC, 36, 18, 220, 8
+ DEFPUSHBUTTON "OK", IDOK, 105, 75, 50, 15
+END
+
+
+/* Depth change */
+
+DEPTH_CHANGE_BOX DIALOGEX DISCARDABLE 32, 32, 180, 100
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | DS_CENTERMOUSE
+FONT 8, "MS Shell Dlg 2"
+CAPTION "VcXsrv"
+BEGIN
+ DEFPUSHBUTTON "Dismiss", IDOK, 66, 80, 50, 14
+ CTEXT "VcXsrv", IDC_STATIC, 40, 12, 100, 8
+ CTEXT "Disruptive screen configuration change.", IDC_STATIC, 7, 40, 166, 8
+ CTEXT "Restore previous resolution to use VcXsrv.", IDC_STATIC, 7, 52, 166, 8
+END
+
+
+/* Exit */
+
+EXIT_DIALOG DIALOGEX DISCARDABLE 32, 32, 180, 78
+STYLE WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_VISIBLE | WS_TABSTOP | DS_CENTERMOUSE
+FONT 8, "MS Shell Dlg 2"
+CAPTION "Exit VcXsrv?"
+BEGIN
+ PUSHBUTTON "E&xit", IDOK, 55, 56, 30, 14
+ DEFPUSHBUTTON "&Cancel", IDCANCEL, 95, 56, 30, 14
+ CTEXT "E&xiting will close all screens running on this display.", IDC_STATIC, 7, 12, 166, 8
+ CTEXT "No information about connected clients available.", IDC_CLIENTS_CONNECTED, 7, 24, 166, 8
+ CTEXT "Proceed with shutdown of this display/server?", IDC_STATIC, 7, 36, 166, 8
+END
+
+
+/*
+ * Menus
+ */
+
+IDM_TRAYICON_MENU MENU DISCARDABLE
+BEGIN
+ POPUP "TRAYICON_MENU"
+ BEGIN
+ MENUITEM "&Hide Root Window", ID_APP_HIDE_ROOT
+ MENUITEM "&About...", ID_APP_ABOUT
+ MENUITEM SEPARATOR
+ MENUITEM "E&xit...", ID_APP_EXIT
+ END
+END
+
+
+/*
+ * Icons
+ */
+
+IDI_XWIN ICON DISCARDABLE "X.ico"
+IDI_XWIN_BOXED ICON DISCARDABLE "X-boxed.ico"
diff --git a/xorg-server/hw/xwin/ddraw.h b/xorg-server/hw/xwin/ddraw.h deleted file mode 100644 index 2eb7c2674..000000000 --- a/xorg-server/hw/xwin/ddraw.h +++ /dev/null @@ -1,2106 +0,0 @@ -#ifndef __XWIN_DDRAW_H -#define __XWIN_DDRAW_H - -#include <winnt.h> -#include <wingdi.h> -#include <objbase.h> - -#if defined(NONAMELESSUNION) && !defined(DUMMYUNIONNAME1) -#define DUMMYUNIONNAME1 u1 -#endif - -#define ICOM_CALL_( xfn, p, args) (p)->lpVtbl->xfn args - -# ifdef UNICODE -# define WINELIB_NAME_AW(func) func##W -# else -# define WINELIB_NAME_AW(func) func##A -# endif /* UNICODE */ -#define DECL_WINELIB_TYPE_AW(type) typedef WINELIB_NAME_AW(type) type; - -#ifdef __cplusplus -extern "C" { -#endif /* defined(__cplusplus) */ - -#ifndef DIRECTDRAW_VERSION -#define DIRECTDRAW_VERSION 0x0700 -#endif /* DIRECTDRAW_VERSION */ - -/***************************************************************************** - * Predeclare the interfaces - */ -DEFINE_GUID( CLSID_DirectDraw, 0xD7B70EE0,0x4340,0x11CF,0xB0,0x63,0x00,0x20,0xAF,0xC2,0xCD,0x35 ); -DEFINE_GUID( CLSID_DirectDraw7, 0x3C305196,0x50DB,0x11D3,0x9C,0xFE,0x00,0xC0,0x4F,0xD9,0x30,0xC5 ); -DEFINE_GUID( CLSID_DirectDrawClipper, 0x593817A0,0x7DB3,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xb9,0x33,0x56 ); -DEFINE_GUID( IID_IDirectDraw, 0x6C14DB80,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 ); -DEFINE_GUID( IID_IDirectDraw2, 0xB3A6F3E0,0x2B43,0x11CF,0xA2,0xDE,0x00,0xAA,0x00,0xB9,0x33,0x56 ); -DEFINE_GUID( IID_IDirectDraw4, 0x9c59509a,0x39bd,0x11d1,0x8c,0x4a,0x00,0xc0,0x4f,0xd9,0x30,0xc5 ); -DEFINE_GUID( IID_IDirectDraw7, 0x15e65ec0,0x3b9c,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b ); -DEFINE_GUID( IID_IDirectDrawSurface, 0x6C14DB81,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 ); -DEFINE_GUID( IID_IDirectDrawSurface2, 0x57805885,0x6eec,0x11cf,0x94,0x41,0xa8,0x23,0x03,0xc1,0x0e,0x27 ); -DEFINE_GUID( IID_IDirectDrawSurface3, 0xDA044E00,0x69B2,0x11D0,0xA1,0xD5,0x00,0xAA,0x00,0xB8,0xDF,0xBB ); -DEFINE_GUID( IID_IDirectDrawSurface4, 0x0B2B8630,0xAD35,0x11D0,0x8E,0xA6,0x00,0x60,0x97,0x97,0xEA,0x5B ); -DEFINE_GUID( IID_IDirectDrawSurface7, 0x06675a80,0x3b9b,0x11d2,0xb9,0x2f,0x00,0x60,0x97,0x97,0xea,0x5b ); -DEFINE_GUID( IID_IDirectDrawPalette, 0x6C14DB84,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 ); -DEFINE_GUID( IID_IDirectDrawClipper, 0x6C14DB85,0xA733,0x11CE,0xA5,0x21,0x00,0x20,0xAF,0x0B,0xE5,0x60 ); -DEFINE_GUID( IID_IDirectDrawColorControl,0x4B9F0EE0,0x0D7E,0x11D0,0x9B,0x06,0x00,0xA0,0xC9,0x03,0xA3,0xB8 ); -DEFINE_GUID( IID_IDirectDrawGammaControl,0x69C11C3E,0xB46B,0x11D1,0xAD,0x7A,0x00,0xC0,0x4F,0xC2,0x9B,0x4E ); - -typedef struct IDirectDraw *LPDIRECTDRAW; -typedef struct IDirectDraw2 *LPDIRECTDRAW2; -typedef struct IDirectDraw4 *LPDIRECTDRAW4; -typedef struct IDirectDraw7 *LPDIRECTDRAW7; -typedef struct IDirectDrawClipper *LPDIRECTDRAWCLIPPER; -typedef struct IDirectDrawPalette *LPDIRECTDRAWPALETTE; -typedef struct IDirectDrawSurface *LPDIRECTDRAWSURFACE; -typedef struct IDirectDrawSurface2 *LPDIRECTDRAWSURFACE2; -typedef struct IDirectDrawSurface3 *LPDIRECTDRAWSURFACE3; -typedef struct IDirectDrawSurface4 *LPDIRECTDRAWSURFACE4; -typedef struct IDirectDrawSurface7 *LPDIRECTDRAWSURFACE7; -typedef struct IDirectDrawColorControl *LPDIRECTDRAWCOLORCONTROL; -typedef struct IDirectDrawGammaControl *LPDIRECTDRAWGAMMACONTROL; - - -#define DDENUMRET_CANCEL 0 -#define DDENUMRET_OK 1 - -#define DD_OK 0 - - -#define _FACDD 0x876 -#define MAKE_DDHRESULT( code ) MAKE_HRESULT( 1, _FACDD, code ) - -#define DDERR_ALREADYINITIALIZED MAKE_DDHRESULT( 5 ) -#define DDERR_CANNOTATTACHSURFACE MAKE_DDHRESULT( 10 ) -#define DDERR_CANNOTDETACHSURFACE MAKE_DDHRESULT( 20 ) -#define DDERR_CURRENTLYNOTAVAIL MAKE_DDHRESULT( 40 ) -#define DDERR_EXCEPTION MAKE_DDHRESULT( 55 ) -#define DDERR_GENERIC E_FAIL -#define DDERR_HEIGHTALIGN MAKE_DDHRESULT( 90 ) -#define DDERR_INCOMPATIBLEPRIMARY MAKE_DDHRESULT( 95 ) -#define DDERR_INVALIDCAPS MAKE_DDHRESULT( 100 ) -#define DDERR_INVALIDCLIPLIST MAKE_DDHRESULT( 110 ) -#define DDERR_INVALIDMODE MAKE_DDHRESULT( 120 ) -#define DDERR_INVALIDOBJECT MAKE_DDHRESULT( 130 ) -#define DDERR_INVALIDPARAMS E_INVALIDARG -#define DDERR_INVALIDPIXELFORMAT MAKE_DDHRESULT( 145 ) -#define DDERR_INVALIDRECT MAKE_DDHRESULT( 150 ) -#define DDERR_LOCKEDSURFACES MAKE_DDHRESULT( 160 ) -#define DDERR_NO3D MAKE_DDHRESULT( 170 ) -#define DDERR_NOALPHAHW MAKE_DDHRESULT( 180 ) -#define DDERR_NOSTEREOHARDWARE MAKE_DDHRESULT( 181 ) -#define DDERR_NOSURFACELEFT MAKE_DDHRESULT( 182 ) -#define DDERR_NOCLIPLIST MAKE_DDHRESULT( 205 ) -#define DDERR_NOCOLORCONVHW MAKE_DDHRESULT( 210 ) -#define DDERR_NOCOOPERATIVELEVELSET MAKE_DDHRESULT( 212 ) -#define DDERR_NOCOLORKEY MAKE_DDHRESULT( 215 ) -#define DDERR_NOCOLORKEYHW MAKE_DDHRESULT( 220 ) -#define DDERR_NODIRECTDRAWSUPPORT MAKE_DDHRESULT( 222 ) -#define DDERR_NOEXCLUSIVEMODE MAKE_DDHRESULT( 225 ) -#define DDERR_NOFLIPHW MAKE_DDHRESULT( 230 ) -#define DDERR_NOGDI MAKE_DDHRESULT( 240 ) -#define DDERR_NOMIRRORHW MAKE_DDHRESULT( 250 ) -#define DDERR_NOTFOUND MAKE_DDHRESULT( 255 ) -#define DDERR_NOOVERLAYHW MAKE_DDHRESULT( 260 ) -#define DDERR_OVERLAPPINGRECTS MAKE_DDHRESULT( 270 ) -#define DDERR_NORASTEROPHW MAKE_DDHRESULT( 280 ) -#define DDERR_NOROTATIONHW MAKE_DDHRESULT( 290 ) -#define DDERR_NOSTRETCHHW MAKE_DDHRESULT( 310 ) -#define DDERR_NOT4BITCOLOR MAKE_DDHRESULT( 316 ) -#define DDERR_NOT4BITCOLORINDEX MAKE_DDHRESULT( 317 ) -#define DDERR_NOT8BITCOLOR MAKE_DDHRESULT( 320 ) -#define DDERR_NOTEXTUREHW MAKE_DDHRESULT( 330 ) -#define DDERR_NOVSYNCHW MAKE_DDHRESULT( 335 ) -#define DDERR_NOZBUFFERHW MAKE_DDHRESULT( 340 ) -#define DDERR_NOZOVERLAYHW MAKE_DDHRESULT( 350 ) -#define DDERR_OUTOFCAPS MAKE_DDHRESULT( 360 ) -#define DDERR_OUTOFMEMORY E_OUTOFMEMORY -#define DDERR_OUTOFVIDEOMEMORY MAKE_DDHRESULT( 380 ) -#define DDERR_OVERLAYCANTCLIP MAKE_DDHRESULT( 382 ) -#define DDERR_OVERLAYCOLORKEYONLYONEACTIVE MAKE_DDHRESULT( 384 ) -#define DDERR_PALETTEBUSY MAKE_DDHRESULT( 387 ) -#define DDERR_COLORKEYNOTSET MAKE_DDHRESULT( 400 ) -#define DDERR_SURFACEALREADYATTACHED MAKE_DDHRESULT( 410 ) -#define DDERR_SURFACEALREADYDEPENDENT MAKE_DDHRESULT( 420 ) -#define DDERR_SURFACEBUSY MAKE_DDHRESULT( 430 ) -#define DDERR_CANTLOCKSURFACE MAKE_DDHRESULT( 435 ) -#define DDERR_SURFACEISOBSCURED MAKE_DDHRESULT( 440 ) -#define DDERR_SURFACELOST MAKE_DDHRESULT( 450 ) -#define DDERR_SURFACENOTATTACHED MAKE_DDHRESULT( 460 ) -#define DDERR_TOOBIGHEIGHT MAKE_DDHRESULT( 470 ) -#define DDERR_TOOBIGSIZE MAKE_DDHRESULT( 480 ) -#define DDERR_TOOBIGWIDTH MAKE_DDHRESULT( 490 ) -#define DDERR_UNSUPPORTED E_NOTIMPL -#define DDERR_UNSUPPORTEDFORMAT MAKE_DDHRESULT( 510 ) -#define DDERR_UNSUPPORTEDMASK MAKE_DDHRESULT( 520 ) -#define DDERR_INVALIDSTREAM MAKE_DDHRESULT( 521 ) -#define DDERR_VERTICALBLANKINPROGRESS MAKE_DDHRESULT( 537 ) -#define DDERR_WASSTILLDRAWING MAKE_DDHRESULT( 540 ) -#define DDERR_DDSCAPSCOMPLEXREQUIRED MAKE_DDHRESULT( 542 ) -#define DDERR_XALIGN MAKE_DDHRESULT( 560 ) -#define DDERR_INVALIDDIRECTDRAWGUID MAKE_DDHRESULT( 561 ) -#define DDERR_DIRECTDRAWALREADYCREATED MAKE_DDHRESULT( 562 ) -#define DDERR_NODIRECTDRAWHW MAKE_DDHRESULT( 563 ) -#define DDERR_PRIMARYSURFACEALREADYEXISTS MAKE_DDHRESULT( 564 ) -#define DDERR_NOEMULATION MAKE_DDHRESULT( 565 ) -#define DDERR_REGIONTOOSMALL MAKE_DDHRESULT( 566 ) -#define DDERR_CLIPPERISUSINGHWND MAKE_DDHRESULT( 567 ) -#define DDERR_NOCLIPPERATTACHED MAKE_DDHRESULT( 568 ) -#define DDERR_NOHWND MAKE_DDHRESULT( 569 ) -#define DDERR_HWNDSUBCLASSED MAKE_DDHRESULT( 570 ) -#define DDERR_HWNDALREADYSET MAKE_DDHRESULT( 571 ) -#define DDERR_NOPALETTEATTACHED MAKE_DDHRESULT( 572 ) -#define DDERR_NOPALETTEHW MAKE_DDHRESULT( 573 ) -#define DDERR_BLTFASTCANTCLIP MAKE_DDHRESULT( 574 ) -#define DDERR_NOBLTHW MAKE_DDHRESULT( 575 ) -#define DDERR_NODDROPSHW MAKE_DDHRESULT( 576 ) -#define DDERR_OVERLAYNOTVISIBLE MAKE_DDHRESULT( 577 ) -#define DDERR_NOOVERLAYDEST MAKE_DDHRESULT( 578 ) -#define DDERR_INVALIDPOSITION MAKE_DDHRESULT( 579 ) -#define DDERR_NOTAOVERLAYSURFACE MAKE_DDHRESULT( 580 ) -#define DDERR_EXCLUSIVEMODEALREADYSET MAKE_DDHRESULT( 581 ) -#define DDERR_NOTFLIPPABLE MAKE_DDHRESULT( 582 ) -#define DDERR_CANTDUPLICATE MAKE_DDHRESULT( 583 ) -#define DDERR_NOTLOCKED MAKE_DDHRESULT( 584 ) -#define DDERR_CANTCREATEDC MAKE_DDHRESULT( 585 ) -#define DDERR_NODC MAKE_DDHRESULT( 586 ) -#define DDERR_WRONGMODE MAKE_DDHRESULT( 587 ) -#define DDERR_IMPLICITLYCREATED MAKE_DDHRESULT( 588 ) -#define DDERR_NOTPALETTIZED MAKE_DDHRESULT( 589 ) -#define DDERR_UNSUPPORTEDMODE MAKE_DDHRESULT( 590 ) -#define DDERR_NOMIPMAPHW MAKE_DDHRESULT( 591 ) -#define DDERR_INVALIDSURFACETYPE MAKE_DDHRESULT( 592 ) -#define DDERR_NOOPTIMIZEHW MAKE_DDHRESULT( 600 ) -#define DDERR_NOTLOADED MAKE_DDHRESULT( 601 ) -#define DDERR_NOFOCUSWINDOW MAKE_DDHRESULT( 602 ) -#define DDERR_NOTONMIPMAPSUBLEVEL MAKE_DDHRESULT( 603 ) -#define DDERR_DCALREADYCREATED MAKE_DDHRESULT( 620 ) -#define DDERR_NONONLOCALVIDMEM MAKE_DDHRESULT( 630 ) -#define DDERR_CANTPAGELOCK MAKE_DDHRESULT( 640 ) -#define DDERR_CANTPAGEUNLOCK MAKE_DDHRESULT( 660 ) -#define DDERR_NOTPAGELOCKED MAKE_DDHRESULT( 680 ) -#define DDERR_MOREDATA MAKE_DDHRESULT( 690 ) -#define DDERR_EXPIRED MAKE_DDHRESULT( 691 ) -#define DDERR_TESTFINISHED MAKE_DDHRESULT( 692 ) -#define DDERR_NEWMODE MAKE_DDHRESULT( 693 ) -#define DDERR_D3DNOTINITIALIZED MAKE_DDHRESULT( 694 ) -#define DDERR_VIDEONOTACTIVE MAKE_DDHRESULT( 695 ) -#define DDERR_NOMONITORINFORMATION MAKE_DDHRESULT( 696 ) -#define DDERR_NODRIVERSUPPORT MAKE_DDHRESULT( 697 ) -#define DDERR_DEVICEDOESNTOWNSURFACE MAKE_DDHRESULT( 699 ) -#define DDERR_NOTINITIALIZED CO_E_NOTINITIALIZED - -/* dwFlags for Blt* */ -#define DDBLT_ALPHADEST 0x00000001 -#define DDBLT_ALPHADESTCONSTOVERRIDE 0x00000002 -#define DDBLT_ALPHADESTNEG 0x00000004 -#define DDBLT_ALPHADESTSURFACEOVERRIDE 0x00000008 -#define DDBLT_ALPHAEDGEBLEND 0x00000010 -#define DDBLT_ALPHASRC 0x00000020 -#define DDBLT_ALPHASRCCONSTOVERRIDE 0x00000040 -#define DDBLT_ALPHASRCNEG 0x00000080 -#define DDBLT_ALPHASRCSURFACEOVERRIDE 0x00000100 -#define DDBLT_ASYNC 0x00000200 -#define DDBLT_COLORFILL 0x00000400 -#define DDBLT_DDFX 0x00000800 -#define DDBLT_DDROPS 0x00001000 -#define DDBLT_KEYDEST 0x00002000 -#define DDBLT_KEYDESTOVERRIDE 0x00004000 -#define DDBLT_KEYSRC 0x00008000 -#define DDBLT_KEYSRCOVERRIDE 0x00010000 -#define DDBLT_ROP 0x00020000 -#define DDBLT_ROTATIONANGLE 0x00040000 -#define DDBLT_ZBUFFER 0x00080000 -#define DDBLT_ZBUFFERDESTCONSTOVERRIDE 0x00100000 -#define DDBLT_ZBUFFERDESTOVERRIDE 0x00200000 -#define DDBLT_ZBUFFERSRCCONSTOVERRIDE 0x00400000 -#define DDBLT_ZBUFFERSRCOVERRIDE 0x00800000 -#define DDBLT_WAIT 0x01000000 -#define DDBLT_DEPTHFILL 0x02000000 -#define DDBLT_DONOTWAIT 0x08000000 - -/* dwTrans for BltFast */ -#define DDBLTFAST_NOCOLORKEY 0x00000000 -#define DDBLTFAST_SRCCOLORKEY 0x00000001 -#define DDBLTFAST_DESTCOLORKEY 0x00000002 -#define DDBLTFAST_WAIT 0x00000010 -#define DDBLTFAST_DONOTWAIT 0x00000020 - -/* dwFlags for Flip */ -#define DDFLIP_WAIT 0x00000001 -#define DDFLIP_EVEN 0x00000002 /* only valid for overlay */ -#define DDFLIP_ODD 0x00000004 /* only valid for overlay */ -#define DDFLIP_NOVSYNC 0x00000008 -#define DDFLIP_STEREO 0x00000010 -#define DDFLIP_DONOTWAIT 0x00000020 - -/* dwFlags for GetBltStatus */ -#define DDGBS_CANBLT 0x00000001 -#define DDGBS_ISBLTDONE 0x00000002 - -/* dwFlags for IDirectDrawSurface7::GetFlipStatus */ -#define DDGFS_CANFLIP 1L -#define DDGFS_ISFLIPDONE 2L - -/* dwFlags for IDirectDrawSurface7::SetPrivateData */ -#define DDSPD_IUNKNOWNPTR 1L -#define DDSPD_VOLATILE 2L - -/* DDSCAPS.dwCaps */ -/* reserved1, was 3d capable */ -#define DDSCAPS_RESERVED1 0x00000001 -/* surface contains alpha information */ -#define DDSCAPS_ALPHA 0x00000002 -/* this surface is a backbuffer */ -#define DDSCAPS_BACKBUFFER 0x00000004 -/* complex surface structure */ -#define DDSCAPS_COMPLEX 0x00000008 -/* part of surface flipping structure */ -#define DDSCAPS_FLIP 0x00000010 -/* this surface is the frontbuffer surface */ -#define DDSCAPS_FRONTBUFFER 0x00000020 -/* this is a plain offscreen surface */ -#define DDSCAPS_OFFSCREENPLAIN 0x00000040 -/* overlay */ -#define DDSCAPS_OVERLAY 0x00000080 -/* palette objects can be created and attached to us */ -#define DDSCAPS_PALETTE 0x00000100 -/* primary surface (the one the user looks at currently)(right eye)*/ -#define DDSCAPS_PRIMARYSURFACE 0x00000200 -/* primary surface for left eye */ -#define DDSCAPS_PRIMARYSURFACELEFT 0x00000400 -/* surface exists in systemmemory */ -#define DDSCAPS_SYSTEMMEMORY 0x00000800 -/* surface can be used as a texture */ -#define DDSCAPS_TEXTURE 0x00001000 -/* surface may be destination for 3d rendering */ -#define DDSCAPS_3DDEVICE 0x00002000 -/* surface exists in videomemory */ -#define DDSCAPS_VIDEOMEMORY 0x00004000 -/* surface changes immediately visible */ -#define DDSCAPS_VISIBLE 0x00008000 -/* write only surface */ -#define DDSCAPS_WRITEONLY 0x00010000 -/* zbuffer surface */ -#define DDSCAPS_ZBUFFER 0x00020000 -/* has its own DC */ -#define DDSCAPS_OWNDC 0x00040000 -/* surface should be able to receive live video */ -#define DDSCAPS_LIVEVIDEO 0x00080000 -/* should be able to have a hw codec decompress stuff into it */ -#define DDSCAPS_HWCODEC 0x00100000 -/* mode X (320x200 or 320x240) surface */ -#define DDSCAPS_MODEX 0x00200000 -/* one mipmap surface (1 level) */ -#define DDSCAPS_MIPMAP 0x00400000 -#define DDSCAPS_RESERVED2 0x00800000 -/* memory allocation delayed until Load() */ -#define DDSCAPS_ALLOCONLOAD 0x04000000 -/* Indicates that the surface will receive data from a video port */ -#define DDSCAPS_VIDEOPORT 0x08000000 -/* surface is in local videomemory */ -#define DDSCAPS_LOCALVIDMEM 0x10000000 -/* surface is in nonlocal videomemory */ -#define DDSCAPS_NONLOCALVIDMEM 0x20000000 -/* surface is a standard VGA mode surface (NOT ModeX) */ -#define DDSCAPS_STANDARDVGAMODE 0x40000000 -/* optimized? surface */ -#define DDSCAPS_OPTIMIZED 0x80000000 - -typedef struct _DDSCAPS { - DWORD dwCaps; /* capabilities of surface wanted */ -} DDSCAPS,*LPDDSCAPS; - -/* DDSCAPS2.dwCaps2 */ -/* indicates the surface will receive data from a video port using - deinterlacing hardware. */ -#define DDSCAPS2_HARDWAREDEINTERLACE 0x00000002 -/* indicates the surface will be locked very frequently. */ -#define DDSCAPS2_HINTDYNAMIC 0x00000004 -/* indicates surface can be re-ordered or retiled on load() */ -#define DDSCAPS2_HINTSTATIC 0x00000008 -/* indicates surface to be managed by directdraw/direct3D */ -#define DDSCAPS2_TEXTUREMANAGE 0x00000010 -/* reserved bits */ -#define DDSCAPS2_RESERVED1 0x00000020 -#define DDSCAPS2_RESERVED2 0x00000040 -/* indicates surface will never be locked again */ -#define DDSCAPS2_OPAQUE 0x00000080 -/* set at CreateSurface() time to indicate antialising will be used */ -#define DDSCAPS2_HINTANTIALIASING 0x00000100 -/* set at CreateSurface() time to indicate cubic environment map */ -#define DDSCAPS2_CUBEMAP 0x00000200 -/* face flags for cube maps */ -#define DDSCAPS2_CUBEMAP_POSITIVEX 0x00000400 -#define DDSCAPS2_CUBEMAP_NEGATIVEX 0x00000800 -#define DDSCAPS2_CUBEMAP_POSITIVEY 0x00001000 -#define DDSCAPS2_CUBEMAP_NEGATIVEY 0x00002000 -#define DDSCAPS2_CUBEMAP_POSITIVEZ 0x00004000 -#define DDSCAPS2_CUBEMAP_NEGATIVEZ 0x00008000 -/* specifies all faces of a cube for CreateSurface() */ -#define DDSCAPS2_CUBEMAP_ALLFACES ( DDSCAPS2_CUBEMAP_POSITIVEX |\ - DDSCAPS2_CUBEMAP_NEGATIVEX |\ - DDSCAPS2_CUBEMAP_POSITIVEY |\ - DDSCAPS2_CUBEMAP_NEGATIVEY |\ - DDSCAPS2_CUBEMAP_POSITIVEZ |\ - DDSCAPS2_CUBEMAP_NEGATIVEZ ) -/* set for mipmap sublevels on DirectX7 and later. ignored by CreateSurface() */ -#define DDSCAPS2_MIPMAPSUBLEVEL 0x00010000 -/* indicates texture surface to be managed by Direct3D *only* */ -#define DDSCAPS2_D3DTEXTUREMANAGE 0x00020000 -/* indicates managed surface that can safely be lost */ -#define DDSCAPS2_DONOTPERSIST 0x00040000 -/* indicates surface is part of a stereo flipping chain */ -#define DDSCAPS2_STEREOSURFACELEFT 0x00080000 - -typedef struct _DDSCAPS2 { - DWORD dwCaps; /* capabilities of surface wanted */ - DWORD dwCaps2; /* additional capabilities */ - DWORD dwCaps3; /* reserved capabilities */ - DWORD dwCaps4; /* more reserved capabilities */ -} DDSCAPS2,*LPDDSCAPS2; - -#define DD_ROP_SPACE (256/32) /* space required to store ROP array */ - -typedef struct _DDCAPS_DX7 /* DirectX 7 version of caps struct */ -{ - DWORD dwSize; /* size of the DDDRIVERCAPS structure */ - DWORD dwCaps; /* driver specific capabilities */ - DWORD dwCaps2; /* more driver specific capabilites */ - DWORD dwCKeyCaps; /* color key capabilities of the surface */ - DWORD dwFXCaps; /* driver specific stretching and effects capabilites */ - DWORD dwFXAlphaCaps; /* alpha driver specific capabilities */ - DWORD dwPalCaps; /* palette capabilities */ - DWORD dwSVCaps; /* stereo vision capabilities */ - DWORD dwAlphaBltConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaBltPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaBltSurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlayConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaOverlayPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwZBufferBitDepths; /* DDBD_8,16,24,32 */ - DWORD dwVidMemTotal; /* total amount of video memory */ - DWORD dwVidMemFree; /* amount of free video memory */ - DWORD dwMaxVisibleOverlays; /* maximum number of visible overlays */ - DWORD dwCurrVisibleOverlays; /* current number of visible overlays */ - DWORD dwNumFourCCCodes; /* number of four cc codes */ - DWORD dwAlignBoundarySrc; /* source rectangle alignment */ - DWORD dwAlignSizeSrc; /* source rectangle byte size */ - DWORD dwAlignBoundaryDest; /* dest rectangle alignment */ - DWORD dwAlignSizeDest; /* dest rectangle byte size */ - DWORD dwAlignStrideAlign; /* stride alignment */ - DWORD dwRops[DD_ROP_SPACE]; /* ROPS supported */ - DDSCAPS ddsOldCaps; /* old DDSCAPS - superceded for DirectX6+ */ - DWORD dwMinOverlayStretch; /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxOverlayStretch; /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinLiveVideoStretch; /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxLiveVideoStretch; /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinHwCodecStretch; /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxHwCodecStretch; /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwReserved1; - DWORD dwReserved2; - DWORD dwReserved3; - DWORD dwSVBCaps; /* driver specific capabilities for System->Vmem blts */ - DWORD dwSVBCKeyCaps; /* driver color key capabilities for System->Vmem blts */ - DWORD dwSVBFXCaps; /* driver FX capabilities for System->Vmem blts */ - DWORD dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */ - DWORD dwVSBCaps; /* driver specific capabilities for Vmem->System blts */ - DWORD dwVSBCKeyCaps; /* driver color key capabilities for Vmem->System blts */ - DWORD dwVSBFXCaps; /* driver FX capabilities for Vmem->System blts */ - DWORD dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */ - DWORD dwSSBCaps; /* driver specific capabilities for System->System blts */ - DWORD dwSSBCKeyCaps; /* driver color key capabilities for System->System blts */ - DWORD dwSSBFXCaps; /* driver FX capabilities for System->System blts */ - DWORD dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */ - DWORD dwMaxVideoPorts; /* maximum number of usable video ports */ - DWORD dwCurrVideoPorts; /* current number of video ports used */ - DWORD dwSVBCaps2; /* more driver specific capabilities for System->Vmem blts */ - DWORD dwNLVBCaps; /* driver specific capabilities for non-local->local vidmem blts */ - DWORD dwNLVBCaps2; /* more driver specific capabilities non-local->local vidmem blts */ - DWORD dwNLVBCKeyCaps; /* driver color key capabilities for non-local->local vidmem blts */ - DWORD dwNLVBFXCaps; /* driver FX capabilities for non-local->local blts */ - DWORD dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */ - DDSCAPS2 ddsCaps; /* surface capabilities */ -} DDCAPS_DX7,*LPDDCAPS_DX7; - -typedef struct _DDCAPS_DX6 /* DirectX 6 version of caps struct */ -{ - DWORD dwSize; /* size of the DDDRIVERCAPS structure */ - DWORD dwCaps; /* driver specific capabilities */ - DWORD dwCaps2; /* more driver specific capabilites */ - DWORD dwCKeyCaps; /* color key capabilities of the surface */ - DWORD dwFXCaps; /* driver specific stretching and effects capabilites */ - DWORD dwFXAlphaCaps; /* alpha driver specific capabilities */ - DWORD dwPalCaps; /* palette capabilities */ - DWORD dwSVCaps; /* stereo vision capabilities */ - DWORD dwAlphaBltConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaBltPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaBltSurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlayConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaOverlayPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwZBufferBitDepths; /* DDBD_8,16,24,32 */ - DWORD dwVidMemTotal; /* total amount of video memory */ - DWORD dwVidMemFree; /* amount of free video memory */ - DWORD dwMaxVisibleOverlays; /* maximum number of visible overlays */ - DWORD dwCurrVisibleOverlays; /* current number of visible overlays */ - DWORD dwNumFourCCCodes; /* number of four cc codes */ - DWORD dwAlignBoundarySrc; /* source rectangle alignment */ - DWORD dwAlignSizeSrc; /* source rectangle byte size */ - DWORD dwAlignBoundaryDest; /* dest rectangle alignment */ - DWORD dwAlignSizeDest; /* dest rectangle byte size */ - DWORD dwAlignStrideAlign; /* stride alignment */ - DWORD dwRops[DD_ROP_SPACE]; /* ROPS supported */ - DDSCAPS ddsOldCaps; /* old DDSCAPS - superceded for DirectX6+ */ - DWORD dwMinOverlayStretch; /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxOverlayStretch; /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinLiveVideoStretch; /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxLiveVideoStretch; /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinHwCodecStretch; /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxHwCodecStretch; /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwReserved1; - DWORD dwReserved2; - DWORD dwReserved3; - DWORD dwSVBCaps; /* driver specific capabilities for System->Vmem blts */ - DWORD dwSVBCKeyCaps; /* driver color key capabilities for System->Vmem blts */ - DWORD dwSVBFXCaps; /* driver FX capabilities for System->Vmem blts */ - DWORD dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */ - DWORD dwVSBCaps; /* driver specific capabilities for Vmem->System blts */ - DWORD dwVSBCKeyCaps; /* driver color key capabilities for Vmem->System blts */ - DWORD dwVSBFXCaps; /* driver FX capabilities for Vmem->System blts */ - DWORD dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */ - DWORD dwSSBCaps; /* driver specific capabilities for System->System blts */ - DWORD dwSSBCKeyCaps; /* driver color key capabilities for System->System blts */ - DWORD dwSSBFXCaps; /* driver FX capabilities for System->System blts */ - DWORD dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */ - DWORD dwMaxVideoPorts; /* maximum number of usable video ports */ - DWORD dwCurrVideoPorts; /* current number of video ports used */ - DWORD dwSVBCaps2; /* more driver specific capabilities for System->Vmem blts */ - DWORD dwNLVBCaps; /* driver specific capabilities for non-local->local vidmem blts */ - DWORD dwNLVBCaps2; /* more driver specific capabilities non-local->local vidmem blts */ - DWORD dwNLVBCKeyCaps; /* driver color key capabilities for non-local->local vidmem blts */ - DWORD dwNLVBFXCaps; /* driver FX capabilities for non-local->local blts */ - DWORD dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */ - /* and one new member for DirectX 6 */ - DDSCAPS2 ddsCaps; /* surface capabilities */ -} DDCAPS_DX6,*LPDDCAPS_DX6; - -typedef struct _DDCAPS_DX5 /* DirectX5 version of caps struct */ -{ - DWORD dwSize; /* size of the DDDRIVERCAPS structure */ - DWORD dwCaps; /* driver specific capabilities */ - DWORD dwCaps2; /* more driver specific capabilites */ - DWORD dwCKeyCaps; /* color key capabilities of the surface */ - DWORD dwFXCaps; /* driver specific stretching and effects capabilites */ - DWORD dwFXAlphaCaps; /* alpha driver specific capabilities */ - DWORD dwPalCaps; /* palette capabilities */ - DWORD dwSVCaps; /* stereo vision capabilities */ - DWORD dwAlphaBltConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaBltPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaBltSurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlayConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaOverlayPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwZBufferBitDepths; /* DDBD_8,16,24,32 */ - DWORD dwVidMemTotal; /* total amount of video memory */ - DWORD dwVidMemFree; /* amount of free video memory */ - DWORD dwMaxVisibleOverlays; /* maximum number of visible overlays */ - DWORD dwCurrVisibleOverlays; /* current number of visible overlays */ - DWORD dwNumFourCCCodes; /* number of four cc codes */ - DWORD dwAlignBoundarySrc; /* source rectangle alignment */ - DWORD dwAlignSizeSrc; /* source rectangle byte size */ - DWORD dwAlignBoundaryDest; /* dest rectangle alignment */ - DWORD dwAlignSizeDest; /* dest rectangle byte size */ - DWORD dwAlignStrideAlign; /* stride alignment */ - DWORD dwRops[DD_ROP_SPACE]; /* ROPS supported */ - DDSCAPS ddsCaps; /* DDSCAPS structure has all the general capabilities */ - DWORD dwMinOverlayStretch; /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxOverlayStretch; /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinLiveVideoStretch; /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxLiveVideoStretch; /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinHwCodecStretch; /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxHwCodecStretch; /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwReserved1; - DWORD dwReserved2; - DWORD dwReserved3; - DWORD dwSVBCaps; /* driver specific capabilities for System->Vmem blts */ - DWORD dwSVBCKeyCaps; /* driver color key capabilities for System->Vmem blts */ - DWORD dwSVBFXCaps; /* driver FX capabilities for System->Vmem blts */ - DWORD dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */ - DWORD dwVSBCaps; /* driver specific capabilities for Vmem->System blts */ - DWORD dwVSBCKeyCaps; /* driver color key capabilities for Vmem->System blts */ - DWORD dwVSBFXCaps; /* driver FX capabilities for Vmem->System blts */ - DWORD dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */ - DWORD dwSSBCaps; /* driver specific capabilities for System->System blts */ - DWORD dwSSBCKeyCaps; /* driver color key capabilities for System->System blts */ - DWORD dwSSBFXCaps; /* driver FX capabilities for System->System blts */ - DWORD dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */ - /* the following are the new DirectX 5 members */ - DWORD dwMaxVideoPorts; /* maximum number of usable video ports */ - DWORD dwCurrVideoPorts; /* current number of video ports used */ - DWORD dwSVBCaps2; /* more driver specific capabilities for System->Vmem blts */ - DWORD dwNLVBCaps; /* driver specific capabilities for non-local->local vidmem blts */ - DWORD dwNLVBCaps2; /* more driver specific capabilities non-local->local vidmem blts */ - DWORD dwNLVBCKeyCaps; /* driver color key capabilities for non-local->local vidmem blts */ - DWORD dwNLVBFXCaps; /* driver FX capabilities for non-local->local blts */ - DWORD dwNLVBRops[DD_ROP_SPACE]; /* ROPS supported for non-local->local blts */ -} DDCAPS_DX5,*LPDDCAPS_DX5; - -typedef struct _DDCAPS_DX3 /* DirectX3 version of caps struct */ -{ - DWORD dwSize; /* size of the DDDRIVERCAPS structure */ - DWORD dwCaps; /* driver specific capabilities */ - DWORD dwCaps2; /* more driver specific capabilites */ - DWORD dwCKeyCaps; /* color key capabilities of the surface */ - DWORD dwFXCaps; /* driver specific stretching and effects capabilites */ - DWORD dwFXAlphaCaps; /* alpha driver specific capabilities */ - DWORD dwPalCaps; /* palette capabilities */ - DWORD dwSVCaps; /* stereo vision capabilities */ - DWORD dwAlphaBltConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaBltPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaBltSurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlayConstBitDepths; /* DDBD_2,4,8 */ - DWORD dwAlphaOverlayPixelBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwAlphaOverlaySurfaceBitDepths; /* DDBD_1,2,4,8 */ - DWORD dwZBufferBitDepths; /* DDBD_8,16,24,32 */ - DWORD dwVidMemTotal; /* total amount of video memory */ - DWORD dwVidMemFree; /* amount of free video memory */ - DWORD dwMaxVisibleOverlays; /* maximum number of visible overlays */ - DWORD dwCurrVisibleOverlays; /* current number of visible overlays */ - DWORD dwNumFourCCCodes; /* number of four cc codes */ - DWORD dwAlignBoundarySrc; /* source rectangle alignment */ - DWORD dwAlignSizeSrc; /* source rectangle byte size */ - DWORD dwAlignBoundaryDest; /* dest rectangle alignment */ - DWORD dwAlignSizeDest; /* dest rectangle byte size */ - DWORD dwAlignStrideAlign; /* stride alignment */ - DWORD dwRops[DD_ROP_SPACE]; /* ROPS supported */ - DDSCAPS ddsCaps; /* DDSCAPS structure has all the general capabilities */ - DWORD dwMinOverlayStretch; /* minimum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxOverlayStretch; /* maximum overlay stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinLiveVideoStretch; /* minimum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxLiveVideoStretch; /* maximum live video stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMinHwCodecStretch; /* minimum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwMaxHwCodecStretch; /* maximum hardware codec stretch factor multiplied by 1000, eg 1000 == 1.0, 1300 == 1.3 */ - DWORD dwReserved1; - DWORD dwReserved2; - DWORD dwReserved3; - DWORD dwSVBCaps; /* driver specific capabilities for System->Vmem blts */ - DWORD dwSVBCKeyCaps; /* driver color key capabilities for System->Vmem blts */ - DWORD dwSVBFXCaps; /* driver FX capabilities for System->Vmem blts */ - DWORD dwSVBRops[DD_ROP_SPACE];/* ROPS supported for System->Vmem blts */ - DWORD dwVSBCaps; /* driver specific capabilities for Vmem->System blts */ - DWORD dwVSBCKeyCaps; /* driver color key capabilities for Vmem->System blts */ - DWORD dwVSBFXCaps; /* driver FX capabilities for Vmem->System blts */ - DWORD dwVSBRops[DD_ROP_SPACE];/* ROPS supported for Vmem->System blts */ - DWORD dwSSBCaps; /* driver specific capabilities for System->System blts */ - DWORD dwSSBCKeyCaps; /* driver color key capabilities for System->System blts */ - DWORD dwSSBFXCaps; /* driver FX capabilities for System->System blts */ - DWORD dwSSBRops[DD_ROP_SPACE];/* ROPS supported for System->System blts */ - DWORD dwReserved4; - DWORD dwReserved5; - DWORD dwReserved6; -} DDCAPS_DX3,*LPDDCAPS_DX3; - -/* set caps struct according to DIRECTDRAW_VERSION */ - -#if DIRECTDRAW_VERSION <= 0x300 -typedef DDCAPS_DX3 DDCAPS; -#elif DIRECTDRAW_VERSION <= 0x500 -typedef DDCAPS_DX5 DDCAPS; -#elif DIRECTDRAW_VERSION <= 0x600 -typedef DDCAPS_DX6 DDCAPS; -#else -typedef DDCAPS_DX7 DDCAPS; -#endif - -typedef DDCAPS *LPDDCAPS; - -/* DDCAPS.dwCaps */ -#define DDCAPS_3D 0x00000001 -#define DDCAPS_ALIGNBOUNDARYDEST 0x00000002 -#define DDCAPS_ALIGNSIZEDEST 0x00000004 -#define DDCAPS_ALIGNBOUNDARYSRC 0x00000008 -#define DDCAPS_ALIGNSIZESRC 0x00000010 -#define DDCAPS_ALIGNSTRIDE 0x00000020 -#define DDCAPS_BLT 0x00000040 -#define DDCAPS_BLTQUEUE 0x00000080 -#define DDCAPS_BLTFOURCC 0x00000100 -#define DDCAPS_BLTSTRETCH 0x00000200 -#define DDCAPS_GDI 0x00000400 -#define DDCAPS_OVERLAY 0x00000800 -#define DDCAPS_OVERLAYCANTCLIP 0x00001000 -#define DDCAPS_OVERLAYFOURCC 0x00002000 -#define DDCAPS_OVERLAYSTRETCH 0x00004000 -#define DDCAPS_PALETTE 0x00008000 -#define DDCAPS_PALETTEVSYNC 0x00010000 -#define DDCAPS_READSCANLINE 0x00020000 -#define DDCAPS_STEREOVIEW 0x00040000 -#define DDCAPS_VBI 0x00080000 -#define DDCAPS_ZBLTS 0x00100000 -#define DDCAPS_ZOVERLAYS 0x00200000 -#define DDCAPS_COLORKEY 0x00400000 -#define DDCAPS_ALPHA 0x00800000 -#define DDCAPS_COLORKEYHWASSIST 0x01000000 -#define DDCAPS_NOHARDWARE 0x02000000 -#define DDCAPS_BLTCOLORFILL 0x04000000 -#define DDCAPS_BANKSWITCHED 0x08000000 -#define DDCAPS_BLTDEPTHFILL 0x10000000 -#define DDCAPS_CANCLIP 0x20000000 -#define DDCAPS_CANCLIPSTRETCHED 0x40000000 -#define DDCAPS_CANBLTSYSMEM 0x80000000 - -/* DDCAPS.dwCaps2 */ -#define DDCAPS2_CERTIFIED 0x00000001 -#define DDCAPS2_NO2DDURING3DSCENE 0x00000002 -#define DDCAPS2_VIDEOPORT 0x00000004 -#define DDCAPS2_AUTOFLIPOVERLAY 0x00000008 -#define DDCAPS2_CANBOBINTERLEAVED 0x00000010 -#define DDCAPS2_CANBOBNONINTERLEAVED 0x00000020 -#define DDCAPS2_COLORCONTROLOVERLAY 0x00000040 -#define DDCAPS2_COLORCONTROLPRIMARY 0x00000080 -#define DDCAPS2_CANDROPZ16BIT 0x00000100 -#define DDCAPS2_NONLOCALVIDMEM 0x00000200 -#define DDCAPS2_NONLOCALVIDMEMCAPS 0x00000400 -#define DDCAPS2_NOPAGELOCKREQUIRED 0x00000800 -#define DDCAPS2_WIDESURFACES 0x00001000 -#define DDCAPS2_CANFLIPODDEVEN 0x00002000 -#define DDCAPS2_CANBOBHARDWARE 0x00004000 -#define DDCAPS2_COPYFOURCC 0x00008000 -#define DDCAPS2_PRIMARYGAMMA 0x00020000 -#define DDCAPS2_CANRENDERWINDOWED 0x00080000 -#define DDCAPS2_CANCALIBRATEGAMMA 0x00100000 -#define DDCAPS2_FLIPINTERVAL 0x00200000 -#define DDCAPS2_FLIPNOVSYNC 0x00400000 -#define DDCAPS2_CANMANAGETEXTURE 0x00800000 -#define DDCAPS2_TEXMANINNONLOCALVIDMEM 0x01000000 -#define DDCAPS2_STEREO 0x02000000 -#define DDCAPS2_SYSTONONLOCAL_AS_SYSTOLOCAL 0x04000000 - - -/* Set/Get Colour Key Flags */ -#define DDCKEY_COLORSPACE 0x00000001 /* Struct is single colour space */ -#define DDCKEY_DESTBLT 0x00000002 /* To be used as dest for blt */ -#define DDCKEY_DESTOVERLAY 0x00000004 /* To be used as dest for CK overlays */ -#define DDCKEY_SRCBLT 0x00000008 /* To be used as src for blt */ -#define DDCKEY_SRCOVERLAY 0x00000010 /* To be used as src for CK overlays */ - -typedef struct _DDCOLORKEY -{ - DWORD dwColorSpaceLowValue;/* low boundary of color space that is to - * be treated as Color Key, inclusive - */ - DWORD dwColorSpaceHighValue;/* high boundary of color space that is - * to be treated as Color Key, inclusive - */ -} DDCOLORKEY,*LPDDCOLORKEY; - -/* ddCKEYCAPS bits */ -#define DDCKEYCAPS_DESTBLT 0x00000001 -#define DDCKEYCAPS_DESTBLTCLRSPACE 0x00000002 -#define DDCKEYCAPS_DESTBLTCLRSPACEYUV 0x00000004 -#define DDCKEYCAPS_DESTBLTYUV 0x00000008 -#define DDCKEYCAPS_DESTOVERLAY 0x00000010 -#define DDCKEYCAPS_DESTOVERLAYCLRSPACE 0x00000020 -#define DDCKEYCAPS_DESTOVERLAYCLRSPACEYUV 0x00000040 -#define DDCKEYCAPS_DESTOVERLAYONEACTIVE 0x00000080 -#define DDCKEYCAPS_DESTOVERLAYYUV 0x00000100 -#define DDCKEYCAPS_SRCBLT 0x00000200 -#define DDCKEYCAPS_SRCBLTCLRSPACE 0x00000400 -#define DDCKEYCAPS_SRCBLTCLRSPACEYUV 0x00000800 -#define DDCKEYCAPS_SRCBLTYUV 0x00001000 -#define DDCKEYCAPS_SRCOVERLAY 0x00002000 -#define DDCKEYCAPS_SRCOVERLAYCLRSPACE 0x00004000 -#define DDCKEYCAPS_SRCOVERLAYCLRSPACEYUV 0x00008000 -#define DDCKEYCAPS_SRCOVERLAYONEACTIVE 0x00010000 -#define DDCKEYCAPS_SRCOVERLAYYUV 0x00020000 -#define DDCKEYCAPS_NOCOSTOVERLAY 0x00040000 - -typedef struct _DDPIXELFORMAT { - DWORD dwSize; /* 0: size of structure */ - DWORD dwFlags; /* 4: pixel format flags */ - DWORD dwFourCC; /* 8: (FOURCC code) */ - union { - DWORD dwRGBBitCount; /* C: how many bits per pixel */ - DWORD dwYUVBitCount; /* C: how many bits per pixel */ - DWORD dwZBufferBitDepth; /* C: how many bits for z buffers */ - DWORD dwAlphaBitDepth; /* C: how many bits for alpha channels*/ - DWORD dwLuminanceBitCount; - DWORD dwBumpBitCount; - } DUMMYUNIONNAME1; - union { - DWORD dwRBitMask; /* 10: mask for red bit*/ - DWORD dwYBitMask; /* 10: mask for Y bits*/ - DWORD dwStencilBitDepth; - DWORD dwLuminanceBitMask; - DWORD dwBumpDuBitMask; - } DUMMYUNIONNAME2; - union { - DWORD dwGBitMask; /* 14: mask for green bits*/ - DWORD dwUBitMask; /* 14: mask for U bits*/ - DWORD dwZBitMask; - DWORD dwBumpDvBitMask; - } DUMMYUNIONNAME3; - union { - DWORD dwBBitMask; /* 18: mask for blue bits*/ - DWORD dwVBitMask; /* 18: mask for V bits*/ - DWORD dwStencilBitMask; - DWORD dwBumpLuminanceBitMask; - } DUMMYUNIONNAME4; - union { - DWORD dwRGBAlphaBitMask; /* 1C: mask for alpha channel */ - DWORD dwYUVAlphaBitMask; /* 1C: mask for alpha channel */ - DWORD dwLuminanceAlphaBitMask; - DWORD dwRGBZBitMask; /* 1C: mask for Z channel */ - DWORD dwYUVZBitMask; /* 1C: mask for Z channel */ - } DUMMYUNIONNAME5; - /* 20: next structure */ -} DDPIXELFORMAT,*LPDDPIXELFORMAT; - -/* DDCAPS.dwFXCaps */ -#define DDFXCAPS_BLTALPHA 0x00000001 -#define DDFXCAPS_OVERLAYALPHA 0x00000004 -#define DDFXCAPS_BLTARITHSTRETCHYN 0x00000010 -#define DDFXCAPS_BLTARITHSTRETCHY 0x00000020 -#define DDFXCAPS_BLTMIRRORLEFTRIGHT 0x00000040 -#define DDFXCAPS_BLTMIRRORUPDOWN 0x00000080 -#define DDFXCAPS_BLTROTATION 0x00000100 -#define DDFXCAPS_BLTROTATION90 0x00000200 -#define DDFXCAPS_BLTSHRINKX 0x00000400 -#define DDFXCAPS_BLTSHRINKXN 0x00000800 -#define DDFXCAPS_BLTSHRINKY 0x00001000 -#define DDFXCAPS_BLTSHRINKYN 0x00002000 -#define DDFXCAPS_BLTSTRETCHX 0x00004000 -#define DDFXCAPS_BLTSTRETCHXN 0x00008000 -#define DDFXCAPS_BLTSTRETCHY 0x00010000 -#define DDFXCAPS_BLTSTRETCHYN 0x00020000 -#define DDFXCAPS_OVERLAYARITHSTRETCHY 0x00040000 -#define DDFXCAPS_OVERLAYARITHSTRETCHYN 0x00000008 -#define DDFXCAPS_OVERLAYSHRINKX 0x00080000 -#define DDFXCAPS_OVERLAYSHRINKXN 0x00100000 -#define DDFXCAPS_OVERLAYSHRINKY 0x00200000 -#define DDFXCAPS_OVERLAYSHRINKYN 0x00400000 -#define DDFXCAPS_OVERLAYSTRETCHX 0x00800000 -#define DDFXCAPS_OVERLAYSTRETCHXN 0x01000000 -#define DDFXCAPS_OVERLAYSTRETCHY 0x02000000 -#define DDFXCAPS_OVERLAYSTRETCHYN 0x04000000 -#define DDFXCAPS_OVERLAYMIRRORLEFTRIGHT 0x08000000 -#define DDFXCAPS_OVERLAYMIRRORUPDOWN 0x10000000 - -#define DDFXCAPS_OVERLAYFILTER DDFXCAPS_OVERLAYARITHSTRETCHY - -/* DDCAPS.dwFXAlphaCaps */ -#define DDFXALPHACAPS_BLTALPHAEDGEBLEND 0x00000001 -#define DDFXALPHACAPS_BLTALPHAPIXELS 0x00000002 -#define DDFXALPHACAPS_BLTALPHAPIXELSNEG 0x00000004 -#define DDFXALPHACAPS_BLTALPHASURFACES 0x00000008 -#define DDFXALPHACAPS_BLTALPHASURFACESNEG 0x00000010 -#define DDFXALPHACAPS_OVERLAYALPHAEDGEBLEND 0x00000020 -#define DDFXALPHACAPS_OVERLAYALPHAPIXELS 0x00000040 -#define DDFXALPHACAPS_OVERLAYALPHAPIXELSNEG 0x00000080 -#define DDFXALPHACAPS_OVERLAYALPHASURFACES 0x00000100 -#define DDFXALPHACAPS_OVERLAYALPHASURFACESNEG 0x00000200 - -/* DDCAPS.dwPalCaps */ -#define DDPCAPS_4BIT 0x00000001 -#define DDPCAPS_8BITENTRIES 0x00000002 -#define DDPCAPS_8BIT 0x00000004 -#define DDPCAPS_INITIALIZE 0x00000008 -#define DDPCAPS_PRIMARYSURFACE 0x00000010 -#define DDPCAPS_PRIMARYSURFACELEFT 0x00000020 -#define DDPCAPS_ALLOW256 0x00000040 -#define DDPCAPS_VSYNC 0x00000080 -#define DDPCAPS_1BIT 0x00000100 -#define DDPCAPS_2BIT 0x00000200 -#define DDPCAPS_ALPHA 0x00000400 - -/* DDCAPS.dwSVCaps */ -/* the first 4 of these are now obsolete */ -#if DIRECTDRAW_VERSION >= 0x700 /* FIXME: I'm not sure when this switch occured */ -#define DDSVCAPS_RESERVED1 0x00000001 -#define DDSVCAPS_RESERVED2 0x00000002 -#define DDSVCAPS_RESERVED3 0x00000004 -#define DDSVCAPS_RESERVED4 0x00000008 -#else -#define DDSVCAPS_ENIGMA 0x00000001 -#define DDSVCAPS_FLICKER 0x00000002 -#define DDSVCAPS_REDBLUE 0x00000004 -#define DDSVCAPS_SPLIT 0x00000008 -#endif -#define DDSVCAPS_STEREOSEQUENTIAL 0x00000010 - -/* BitDepths */ -#define DDBD_1 0x00004000 -#define DDBD_2 0x00002000 -#define DDBD_4 0x00001000 -#define DDBD_8 0x00000800 -#define DDBD_16 0x00000400 -#define DDBD_24 0x00000200 -#define DDBD_32 0x00000100 - -/* DDOVERLAYFX.dwDDFX */ -#define DDOVERFX_ARITHSTRETCHY 0x00000001 -#define DDOVERFX_MIRRORLEFTRIGHT 0x00000002 -#define DDOVERFX_MIRRORUPDOWN 0x00000004 - -/* UpdateOverlay flags */ -#define DDOVER_ALPHADEST 0x00000001 -#define DDOVER_ALPHADESTCONSTOVERRIDE 0x00000002 -#define DDOVER_ALPHADESTNEG 0x00000004 -#define DDOVER_ALPHADESTSURFACEOVERRIDE 0x00000008 -#define DDOVER_ALPHAEDGEBLEND 0x00000010 -#define DDOVER_ALPHASRC 0x00000020 -#define DDOVER_ALPHASRCCONSTOVERRIDE 0x00000040 -#define DDOVER_ALPHASRCNEG 0x00000080 -#define DDOVER_ALPHASRCSURFACEOVERRIDE 0x00000100 -#define DDOVER_HIDE 0x00000200 -#define DDOVER_KEYDEST 0x00000400 -#define DDOVER_KEYDESTOVERRIDE 0x00000800 -#define DDOVER_KEYSRC 0x00001000 -#define DDOVER_KEYSRCOVERRIDE 0x00002000 -#define DDOVER_SHOW 0x00004000 -#define DDOVER_ADDDIRTYRECT 0x00008000 -#define DDOVER_REFRESHDIRTYRECTS 0x00010000 -#define DDOVER_REFRESHALL 0x00020000 -#define DDOVER_DDFX 0x00080000 -#define DDOVER_AUTOFLIP 0x00100000 -#define DDOVER_BOB 0x00200000 -#define DDOVER_OVERRIDEBOBWEAVE 0x00400000 -#define DDOVER_INTERLEAVED 0x00800000 - -/* DDCOLORKEY.dwFlags */ -#define DDPF_ALPHAPIXELS 0x00000001 -#define DDPF_ALPHA 0x00000002 -#define DDPF_FOURCC 0x00000004 -#define DDPF_PALETTEINDEXED4 0x00000008 -#define DDPF_PALETTEINDEXEDTO8 0x00000010 -#define DDPF_PALETTEINDEXED8 0x00000020 -#define DDPF_RGB 0x00000040 -#define DDPF_COMPRESSED 0x00000080 -#define DDPF_RGBTOYUV 0x00000100 -#define DDPF_YUV 0x00000200 -#define DDPF_ZBUFFER 0x00000400 -#define DDPF_PALETTEINDEXED1 0x00000800 -#define DDPF_PALETTEINDEXED2 0x00001000 -#define DDPF_ZPIXELS 0x00002000 -#define DDPF_STENCILBUFFER 0x00004000 -#define DDPF_ALPHAPREMULT 0x00008000 -#define DDPF_LUMINANCE 0x00020000 -#define DDPF_BUMPLUMINANCE 0x00040000 -#define DDPF_BUMPDUDV 0x00080000 - -/* SetCooperativeLevel dwFlags */ -#define DDSCL_FULLSCREEN 0x00000001 -#define DDSCL_ALLOWREBOOT 0x00000002 -#define DDSCL_NOWINDOWCHANGES 0x00000004 -#define DDSCL_NORMAL 0x00000008 -#define DDSCL_EXCLUSIVE 0x00000010 -#define DDSCL_ALLOWMODEX 0x00000040 -#define DDSCL_SETFOCUSWINDOW 0x00000080 -#define DDSCL_SETDEVICEWINDOW 0x00000100 -#define DDSCL_CREATEDEVICEWINDOW 0x00000200 -#define DDSCL_MULTITHREADED 0x00000400 -#define DDSCL_FPUSETUP 0x00000800 -#define DDSCL_FPUPRESERVE 0x00001000 - - -/* DDSURFACEDESC.dwFlags */ -#define DDSD_CAPS 0x00000001 -#define DDSD_HEIGHT 0x00000002 -#define DDSD_WIDTH 0x00000004 -#define DDSD_PITCH 0x00000008 -#define DDSD_BACKBUFFERCOUNT 0x00000020 -#define DDSD_ZBUFFERBITDEPTH 0x00000040 -#define DDSD_ALPHABITDEPTH 0x00000080 -#define DDSD_LPSURFACE 0x00000800 -#define DDSD_PIXELFORMAT 0x00001000 -#define DDSD_CKDESTOVERLAY 0x00002000 -#define DDSD_CKDESTBLT 0x00004000 -#define DDSD_CKSRCOVERLAY 0x00008000 -#define DDSD_CKSRCBLT 0x00010000 -#define DDSD_MIPMAPCOUNT 0x00020000 -#define DDSD_REFRESHRATE 0x00040000 -#define DDSD_LINEARSIZE 0x00080000 -#define DDSD_TEXTURESTAGE 0x00100000 -#define DDSD_FVF 0x00200000 -#define DDSD_SRCVBHANDLE 0x00400000 -#define DDSD_ALL 0x007ff9ee - -/* EnumSurfaces flags */ -#define DDENUMSURFACES_ALL 0x00000001 -#define DDENUMSURFACES_MATCH 0x00000002 -#define DDENUMSURFACES_NOMATCH 0x00000004 -#define DDENUMSURFACES_CANBECREATED 0x00000008 -#define DDENUMSURFACES_DOESEXIST 0x00000010 - -/* SetDisplayMode flags */ -#define DDSDM_STANDARDVGAMODE 0x00000001 - -/* EnumDisplayModes flags */ -#define DDEDM_REFRESHRATES 0x00000001 -#define DDEDM_STANDARDVGAMODES 0x00000002 - -/* WaitForVerticalDisplay flags */ - -#define DDWAITVB_BLOCKBEGIN 0x00000001 -#define DDWAITVB_BLOCKBEGINEVENT 0x00000002 -#define DDWAITVB_BLOCKEND 0x00000004 - -typedef struct _DDSURFACEDESC -{ - DWORD dwSize; /* 0: size of the DDSURFACEDESC structure*/ - DWORD dwFlags; /* 4: determines what fields are valid*/ - DWORD dwHeight; /* 8: height of surface to be created*/ - DWORD dwWidth; /* C: width of input surface*/ - union { - LONG lPitch; /* 10: distance to start of next line (return value only)*/ - DWORD dwLinearSize; - } DUMMYUNIONNAME1; - DWORD dwBackBufferCount;/* 14: number of back buffers requested*/ - union { - DWORD dwMipMapCount;/* 18:number of mip-map levels requested*/ - DWORD dwZBufferBitDepth;/*18: depth of Z buffer requested*/ - DWORD dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/ - } DUMMYUNIONNAME2; - DWORD dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/ - DWORD dwReserved; /* 20:reserved*/ - LPVOID lpSurface; /* 24:pointer to the associated surface memory*/ - DDCOLORKEY ddckCKDestOverlay;/* 28: CK for dest overlay use*/ - DDCOLORKEY ddckCKDestBlt; /* 30: CK for destination blt use*/ - DDCOLORKEY ddckCKSrcOverlay;/* 38: CK for source overlay use*/ - DDCOLORKEY ddckCKSrcBlt; /* 40: CK for source blt use*/ - DDPIXELFORMAT ddpfPixelFormat;/* 48: pixel format description of the surface*/ - DDSCAPS ddsCaps; /* 68: direct draw surface caps */ -} DDSURFACEDESC,*LPDDSURFACEDESC; - -typedef struct _DDSURFACEDESC2 -{ - DWORD dwSize; /* 0: size of the DDSURFACEDESC structure*/ - DWORD dwFlags; /* 4: determines what fields are valid*/ - DWORD dwHeight; /* 8: height of surface to be created*/ - DWORD dwWidth; /* C: width of input surface*/ - union { - LONG lPitch; /*10: distance to start of next line (return value only)*/ - DWORD dwLinearSize; /*10: formless late-allocated optimized surface size */ - } DUMMYUNIONNAME1; - DWORD dwBackBufferCount;/* 14: number of back buffers requested*/ - union { - DWORD dwMipMapCount;/* 18:number of mip-map levels requested*/ - DWORD dwRefreshRate;/* 18:refresh rate (used when display mode is described)*/ - DWORD dwSrcVBHandle;/* 18:source used in VB::Optimize */ - } DUMMYUNIONNAME2; - DWORD dwAlphaBitDepth;/* 1C:depth of alpha buffer requested*/ - DWORD dwReserved; /* 20:reserved*/ - LPVOID lpSurface; /* 24:pointer to the associated surface memory*/ - union { - DDCOLORKEY ddckCKDestOverlay; /* 28: CK for dest overlay use*/ - DWORD dwEmptyFaceColor; /* 28: color for empty cubemap faces */ - } DUMMYUNIONNAME3; - DDCOLORKEY ddckCKDestBlt; /* 30: CK for destination blt use*/ - DDCOLORKEY ddckCKSrcOverlay;/* 38: CK for source overlay use*/ - DDCOLORKEY ddckCKSrcBlt; /* 40: CK for source blt use*/ - - union { - DDPIXELFORMAT ddpfPixelFormat;/* 48: pixel format description of the surface*/ - DWORD dwFVF; /* 48: vertex format description of vertex buffers */ - } DUMMYUNIONNAME4; - DDSCAPS2 ddsCaps; /* 68: DDraw surface caps */ - DWORD dwTextureStage; /* 78: stage in multitexture cascade */ -} DDSURFACEDESC2,*LPDDSURFACEDESC2; - -/* DDCOLORCONTROL.dwFlags */ -#define DDCOLOR_BRIGHTNESS 0x00000001 -#define DDCOLOR_CONTRAST 0x00000002 -#define DDCOLOR_HUE 0x00000004 -#define DDCOLOR_SATURATION 0x00000008 -#define DDCOLOR_SHARPNESS 0x00000010 -#define DDCOLOR_GAMMA 0x00000020 -#define DDCOLOR_COLORENABLE 0x00000040 - -typedef struct { - DWORD dwSize; - DWORD dwFlags; - LONG lBrightness; - LONG lContrast; - LONG lHue; - LONG lSaturation; - LONG lSharpness; - LONG lGamma; - LONG lColorEnable; - DWORD dwReserved1; -} DDCOLORCONTROL,*LPDDCOLORCONTROL; - -typedef struct { - WORD red[256]; - WORD green[256]; - WORD blue[256]; -} DDGAMMARAMP,*LPDDGAMMARAMP; - -typedef BOOL CALLBACK (*LPDDENUMCALLBACKA)(GUID *, LPSTR, LPSTR, LPVOID); -typedef BOOL CALLBACK (*LPDDENUMCALLBACKW)(GUID *, LPWSTR, LPWSTR, LPVOID); -DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACK) - -typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK)(LPDDSURFACEDESC, LPVOID); -typedef HRESULT CALLBACK (*LPDDENUMMODESCALLBACK2)(LPDDSURFACEDESC2, LPVOID); -typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK)(LPDIRECTDRAWSURFACE, LPDDSURFACEDESC, LPVOID); -typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK2)(LPDIRECTDRAWSURFACE4, LPDDSURFACEDESC2, LPVOID); -typedef HRESULT CALLBACK (*LPDDENUMSURFACESCALLBACK7)(LPDIRECTDRAWSURFACE7, LPDDSURFACEDESC2, LPVOID); - -typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXA)(GUID *, LPSTR, LPSTR, LPVOID, HMONITOR); -typedef BOOL CALLBACK (*LPDDENUMCALLBACKEXW)(GUID *, LPWSTR, LPWSTR, LPVOID, HMONITOR); -DECL_WINELIB_TYPE_AW(LPDDENUMCALLBACKEX) - -HRESULT WINAPI DirectDrawEnumerateExA( LPDDENUMCALLBACKEXA lpCallback, LPVOID lpContext, DWORD dwFlags); -HRESULT WINAPI DirectDrawEnumerateExW( LPDDENUMCALLBACKEXW lpCallback, LPVOID lpContext, DWORD dwFlags); -#define DirectDrawEnumerateEx WINELIB_NAME_AW(DirectDrawEnumerateEx) - -/* flags for DirectDrawEnumerateEx */ -#define DDENUM_ATTACHEDSECONDARYDEVICES 0x00000001 -#define DDENUM_DETACHEDSECONDARYDEVICES 0x00000002 -#define DDENUM_NONDISPLAYDEVICES 0x00000004 - -/* flags for DirectDrawCreate or IDirectDraw::Initialize */ -#define DDCREATE_HARDWAREONLY 1L -#define DDCREATE_EMULATIONONLY 2L - -typedef struct _DDBLTFX -{ - DWORD dwSize; /* size of structure */ - DWORD dwDDFX; /* FX operations */ - DWORD dwROP; /* Win32 raster operations */ - DWORD dwDDROP; /* Raster operations new for DirectDraw */ - DWORD dwRotationAngle; /* Rotation angle for blt */ - DWORD dwZBufferOpCode; /* ZBuffer compares */ - DWORD dwZBufferLow; /* Low limit of Z buffer */ - DWORD dwZBufferHigh; /* High limit of Z buffer */ - DWORD dwZBufferBaseDest; /* Destination base value */ - DWORD dwZDestConstBitDepth; /* Bit depth used to specify Z constant for destination */ - union - { - DWORD dwZDestConst; /* Constant to use as Z buffer for dest */ - LPDIRECTDRAWSURFACE lpDDSZBufferDest; /* Surface to use as Z buffer for dest */ - } DUMMYUNIONNAME1; - DWORD dwZSrcConstBitDepth; /* Bit depth used to specify Z constant for source */ - union - { - DWORD dwZSrcConst; /* Constant to use as Z buffer for src */ - LPDIRECTDRAWSURFACE lpDDSZBufferSrc; /* Surface to use as Z buffer for src */ - } DUMMYUNIONNAME2; - DWORD dwAlphaEdgeBlendBitDepth; /* Bit depth used to specify constant for alpha edge blend */ - DWORD dwAlphaEdgeBlend; /* Alpha for edge blending */ - DWORD dwReserved; - DWORD dwAlphaDestConstBitDepth; /* Bit depth used to specify alpha constant for destination */ - union - { - DWORD dwAlphaDestConst; /* Constant to use as Alpha Channel */ - LPDIRECTDRAWSURFACE lpDDSAlphaDest; /* Surface to use as Alpha Channel */ - } DUMMYUNIONNAME3; - DWORD dwAlphaSrcConstBitDepth; /* Bit depth used to specify alpha constant for source */ - union - { - DWORD dwAlphaSrcConst; /* Constant to use as Alpha Channel */ - LPDIRECTDRAWSURFACE lpDDSAlphaSrc; /* Surface to use as Alpha Channel */ - } DUMMYUNIONNAME4; - union - { - DWORD dwFillColor; /* color in RGB or Palettized */ - DWORD dwFillDepth; /* depth value for z-buffer */ - DWORD dwFillPixel; /* pixel val for RGBA or RGBZ */ - LPDIRECTDRAWSURFACE lpDDSPattern; /* Surface to use as pattern */ - } DUMMYUNIONNAME5; - DDCOLORKEY ddckDestColorkey; /* DestColorkey override */ - DDCOLORKEY ddckSrcColorkey; /* SrcColorkey override */ -} DDBLTFX,*LPDDBLTFX; - -/* dwDDFX */ -/* arithmetic stretching along y axis */ -#define DDBLTFX_ARITHSTRETCHY 0x00000001 -/* mirror on y axis */ -#define DDBLTFX_MIRRORLEFTRIGHT 0x00000002 -/* mirror on x axis */ -#define DDBLTFX_MIRRORUPDOWN 0x00000004 -/* do not tear */ -#define DDBLTFX_NOTEARING 0x00000008 -/* 180 degrees clockwise rotation */ -#define DDBLTFX_ROTATE180 0x00000010 -/* 270 degrees clockwise rotation */ -#define DDBLTFX_ROTATE270 0x00000020 -/* 90 degrees clockwise rotation */ -#define DDBLTFX_ROTATE90 0x00000040 -/* dwZBufferLow and dwZBufferHigh specify limits to the copied Z values */ -#define DDBLTFX_ZBUFFERRANGE 0x00000080 -/* add dwZBufferBaseDest to every source z value before compare */ -#define DDBLTFX_ZBUFFERBASEDEST 0x00000100 - -typedef struct _DDOVERLAYFX -{ - DWORD dwSize; /* size of structure */ - DWORD dwAlphaEdgeBlendBitDepth; /* Bit depth used to specify constant for alpha edge blend */ - DWORD dwAlphaEdgeBlend; /* Constant to use as alpha for edge blend */ - DWORD dwReserved; - DWORD dwAlphaDestConstBitDepth; /* Bit depth used to specify alpha constant for destination */ - union - { - DWORD dwAlphaDestConst; /* Constant to use as alpha channel for dest */ - LPDIRECTDRAWSURFACE lpDDSAlphaDest; /* Surface to use as alpha channel for dest */ - } DUMMYUNIONNAME1; - DWORD dwAlphaSrcConstBitDepth; /* Bit depth used to specify alpha constant for source */ - union - { - DWORD dwAlphaSrcConst; /* Constant to use as alpha channel for src */ - LPDIRECTDRAWSURFACE lpDDSAlphaSrc; /* Surface to use as alpha channel for src */ - } DUMMYUNIONNAME2; - DDCOLORKEY dckDestColorkey; /* DestColorkey override */ - DDCOLORKEY dckSrcColorkey; /* DestColorkey override */ - DWORD dwDDFX; /* Overlay FX */ - DWORD dwFlags; /* flags */ -} DDOVERLAYFX,*LPDDOVERLAYFX; - -typedef struct _DDBLTBATCH -{ - LPRECT lprDest; - LPDIRECTDRAWSURFACE lpDDSSrc; - LPRECT lprSrc; - DWORD dwFlags; - LPDDBLTFX lpDDBltFx; -} DDBLTBATCH,*LPDDBLTBATCH; - -#define MAX_DDDEVICEID_STRING 512 - -typedef struct tagDDDEVICEIDENTIFIER { - char szDriver[MAX_DDDEVICEID_STRING]; - char szDescription[MAX_DDDEVICEID_STRING]; - LARGE_INTEGER liDriverVersion; - DWORD dwVendorId; - DWORD dwDeviceId; - DWORD dwSubSysId; - DWORD dwRevision; - GUID guidDeviceIdentifier; -} DDDEVICEIDENTIFIER, * LPDDDEVICEIDENTIFIER; - -typedef struct tagDDDEVICEIDENTIFIER2 { - char szDriver[MAX_DDDEVICEID_STRING]; /* user readable driver name */ - char szDescription[MAX_DDDEVICEID_STRING]; /* user readable description */ - LARGE_INTEGER liDriverVersion; /* driver version */ - DWORD dwVendorId; /* vendor ID, zero if unknown */ - DWORD dwDeviceId; /* chipset ID, zero if unknown */ - DWORD dwSubSysId; /* board ID, zero if unknown */ - DWORD dwRevision; /* chipset version, zero if unknown */ - GUID guidDeviceIdentifier; /* unique ID for this driver/chipset combination */ - DWORD dwWHQLLevel; /* Windows Hardware Quality Lab certification level */ -} DDDEVICEIDENTIFIER2, * LPDDDEVICEIDENTIFIER2; - -/***************************************************************************** - * IDirectDrawPalette interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawPalette -DECLARE_INTERFACE_(IDirectDrawPalette,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,PVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetCaps)(THIS_ LPDWORD lpdwCaps) PURE; - STDMETHOD(GetEntries)(THIS_ DWORD dwFlags, DWORD dwBase, DWORD dwNumEntries, LPPALETTEENTRY lpEntries) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags, LPPALETTEENTRY lpDDColorTable) PURE; - STDMETHOD(SetEntries)(THIS_ DWORD dwFlags, DWORD dwStartingEntry, DWORD dwCount, LPPALETTEENTRY lpEntries) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawPalette_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawPalette_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawPalette_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDrawPalette methods ***/ -#define IDirectDrawPalette_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawPalette_GetEntries(p,a,b,c,d) ICOM_CALL_(GetEntries,p,(p,a,b,c,d)) -#define IDirectDrawPalette_Initialize(p,a,b,c) ICOM_CALL_(Initialize,p,(p,a,b,c)) -#define IDirectDrawPalette_SetEntries(p,a,b,c,d) ICOM_CALL_(SetEntries,p,(p,a,b,c,d)) - - -/***************************************************************************** - * IDirectDrawClipper interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawClipper -DECLARE_INTERFACE_(IDirectDrawClipper,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetClipList)(THIS_ LPRECT lpRect, LPRGNDATA lpClipList, LPDWORD lpdwSize) PURE; - STDMETHOD(GetHWnd)(THIS_ HWND* lphWnd) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, DWORD dwFlags) PURE; - STDMETHOD(IsClipListChanged)(THIS_ BOOL* lpbChanged) PURE; - STDMETHOD(SetClipList)(THIS_ LPRGNDATA lpClipList, DWORD dwFlags) PURE; - STDMETHOD(SetHWnd)(THIS_ DWORD dwFlags, HWND hWnd) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawClipper_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawClipper_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawClipper_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDrawClipper methods ***/ -#define IDirectDrawClipper_GetClipList(p,a,b,c) ICOM_CALL_(GetClipList,p,(p,a,b,c)) -#define IDirectDrawClipper_GetHWnd(p,a) ICOM_CALL_(GetHWnd,p,(p,a)) -#define IDirectDrawClipper_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawClipper_IsClipListChanged(p,a) ICOM_CALL_(IsClipListChanged,p,(p,a)) -#define IDirectDrawClipper_SetClipList(p,a,b) ICOM_CALL_(SetClipList,p,(p,a,b)) -#define IDirectDrawClipper_SetHWnd(p,a,b) ICOM_CALL_(SetHWnd,p,(p,a,b)) - - -/***************************************************************************** - * IDirectDraw interface - */ -#undef INTERFACE -#define INTERFACE IDirectDraw -DECLARE_INTERFACE_(IDirectDraw,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Compact)(THIS) PURE; - STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE* lplpDDSurface, IUnknown* pUnkOuter) PURE; - STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSurface, LPDIRECTDRAWSURFACE* lplpDupDDSurface) PURE; - STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE; - STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(FlipToGDISurface)(THIS) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; - STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; - STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE* lplpGDIDDSurface) PURE; - STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; - STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; - STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; - STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; - STDMETHOD(RestoreDisplayMode)(THIS) PURE; - STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; - STDMETHOD(SetDisplayMode)(THIS_ DWORD, DWORD, DWORD) PURE; - STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDraw_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDraw_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDraw_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDraw methods ***/ -#define IDirectDraw_Compact(p) ICOM_CALL_(Compact,p,(p)) -#define IDirectDraw_CreateClipper(p,a,b,c) ICOM_CALL_(CreateClipper,p,(p,a,b,c)) -#define IDirectDraw_CreatePalette(p,a,b,c,d) ICOM_CALL_(CreatePalette,p,(p,a,b,c,d)) -#define IDirectDraw_CreateSurface(p,a,b,c) ICOM_CALL_(CreateSurface,p,(p,a,b,c)) -#define IDirectDraw_DuplicateSurface(p,a,b) ICOM_CALL_(DuplicateSurface,p,(p,a,b)) -#define IDirectDraw_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d)) -#define IDirectDraw_EnumSurfaces(p,a,b,c,d) ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d)) -#define IDirectDraw_FlipToGDISurface(p) ICOM_CALL_(FlipToGDISurface,p,(p)) -#define IDirectDraw_GetCaps(p,a,b) ICOM_CALL_(GetCaps,p,(p,a,b)) -#define IDirectDraw_GetDisplayMode(p,a) ICOM_CALL_(GetDisplayMode,p,(p,a)) -#define IDirectDraw_GetFourCCCodes(p,a,b) ICOM_CALL_(GetFourCCCodes,p,(p,a,b)) -#define IDirectDraw_GetGDISurface(p,a) ICOM_CALL_(GetGDISurface,p,(p,a)) -#define IDirectDraw_GetMonitorFrequency(p,a) ICOM_CALL_(GetMonitorFrequency,p,(p,a)) -#define IDirectDraw_GetScanLine(p,a) ICOM_CALL_(GetScanLine,p,(p,a)) -#define IDirectDraw_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a)) -#define IDirectDraw_Initialize(p,a) ICOM_CALL_(Initialize,p,(p,a)) -#define IDirectDraw_RestoreDisplayMode(p) ICOM_CALL_(RestoreDisplayMode,p,(p)) -#define IDirectDraw_SetCooperativeLevel(p,a,b) ICOM_CALL_(SetCooperativeLevel,p,(p,a,b)) -#define IDirectDraw_SetDisplayMode(p,a,b,c) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c)) -#define IDirectDraw_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b)) - - -/* flags for Lock() */ -#define DDLOCK_SURFACEMEMORYPTR 0x00000000 -#define DDLOCK_WAIT 0x00000001 -#define DDLOCK_EVENT 0x00000002 -#define DDLOCK_READONLY 0x00000010 -#define DDLOCK_WRITEONLY 0x00000020 -#define DDLOCK_NOSYSLOCK 0x00000800 - - -/***************************************************************************** - * IDirectDraw2 interface - */ -/* Note: IDirectDraw2 cannot derive from IDirectDraw because the number of - * arguments of SetDisplayMode has changed ! - */ -#undef INTERFACE -#define INTERFACE IDirectDraw2 -DECLARE_INTERFACE_(IDirectDraw2,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Compact)(THIS) PURE; - STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc, LPDIRECTDRAWSURFACE2* lplpDDSurface, IUnknown* pUnkOuter) PURE; - STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurface, LPDIRECTDRAWSURFACE2* lplpDupDDSurface) PURE; - STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK lpEnumModesCallback) PURE; - STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(FlipToGDISurface)(THIS) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; - STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; - STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE2* lplpGDIDDSurface) PURE; - STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; - STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; - STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; - STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; - STDMETHOD(RestoreDisplayMode)(THIS) PURE; - STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; - STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; - STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; - - STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDraw2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDraw2_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDraw2_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDraw methods ***/ -#define IDirectDraw2_Compact(p) ICOM_CALL_(Compact,p,(p)) -#define IDirectDraw2_CreateClipper(p,a,b,c) ICOM_CALL_(CreateClipper,p,(p,a,b,c)) -#define IDirectDraw2_CreatePalette(p,a,b,c,d) ICOM_CALL_(CreatePalette,p,(p,a,b,c,d)) -#define IDirectDraw2_CreateSurface(p,a,b,c) ICOM_CALL_(CreateSurface,p,(p,a,b,c)) -#define IDirectDraw2_DuplicateSurface(p,a,b) ICOM_CALL_(DuplicateSurface,p,(p,a,b)) -#define IDirectDraw2_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d)) -#define IDirectDraw2_EnumSurfaces(p,a,b,c,d) ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d)) -#define IDirectDraw2_FlipToGDISurface(p) ICOM_CALL_(FlipToGDISurface,p,(p)) -#define IDirectDraw2_GetCaps(p,a,b) ICOM_CALL_(GetCaps,p,(p,a,b)) -#define IDirectDraw2_GetDisplayMode(p,a) ICOM_CALL_(GetDisplayMode,p,(p,a)) -#define IDirectDraw2_GetFourCCCodes(p,a,b) ICOM_CALL_(GetFourCCCodes,p,(p,a,b)) -#define IDirectDraw2_GetGDISurface(p,a) ICOM_CALL_(GetGDISurface,p,(p,a)) -#define IDirectDraw2_GetMonitorFrequency(p,a) ICOM_CALL_(GetMonitorFrequency,p,(p,a)) -#define IDirectDraw2_GetScanLine(p,a) ICOM_CALL_(GetScanLine,p,(p,a)) -#define IDirectDraw2_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a)) -#define IDirectDraw2_Initialize(p,a) ICOM_CALL_(Initialize,p,(p,a)) -#define IDirectDraw2_RestoreDisplayMode(p) ICOM_CALL_(RestoreDisplayMode,p,(p)) -#define IDirectDraw2_SetCooperativeLevel(p,a,b) ICOM_CALL_(SetCooperativeLevel,p,(p,a,b)) -#define IDirectDraw2_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e)) -#define IDirectDraw2_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b)) -/*** IDirectDraw2 methods ***/ -#define IDirectDraw2_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c)) - - -/***************************************************************************** - * IDirectDraw4 interface - */ -#undef INTERFACE -#define INTERFACE IDirectDraw4 -DECLARE_INTERFACE_(IDirectDraw4,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Compact)(THIS) PURE; - STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE4* lplpDDSurface, IUnknown* pUnkOuter) PURE; - STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurface, LPDIRECTDRAWSURFACE4* lplpDupDDSurface) PURE; - STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; - STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK2 lpEnumSurfacesCallback) PURE; - STDMETHOD(FlipToGDISurface)(THIS) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; - STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; - STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; - STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE4* lplpGDIDDSurface) PURE; - STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; - STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; - STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; - STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; - STDMETHOD(RestoreDisplayMode)(THIS) PURE; - STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; - STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; - STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; - - STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; - - STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE4* ) PURE; - STDMETHOD(RestoreAllSurfaces)(THIS) PURE; - STDMETHOD(TestCooperativeLevel)(THIS) PURE; - STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER , DWORD ) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDraw4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDraw4_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDraw4_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDraw methods ***/ -#define IDirectDraw4_Compact(p) ICOM_CALL_(Compact,p,(p)) -#define IDirectDraw4_CreateClipper(p,a,b,c) ICOM_CALL_(CreateClipper,p,(p,a,b,c)) -#define IDirectDraw4_CreatePalette(p,a,b,c,d) ICOM_CALL_(CreatePalette,p,(p,a,b,c,d)) -#define IDirectDraw4_CreateSurface(p,a,b,c) ICOM_CALL_(CreateSurface,p,(p,a,b,c)) -#define IDirectDraw4_DuplicateSurface(p,a,b) ICOM_CALL_(DuplicateSurface,p,(p,a,b)) -#define IDirectDraw4_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d)) -#define IDirectDraw4_EnumSurfaces(p,a,b,c,d) ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d)) -#define IDirectDraw4_FlipToGDISurface(p) ICOM_CALL_(FlipToGDISurface,p,(p)) -#define IDirectDraw4_GetCaps(p,a,b) ICOM_CALL_(GetCaps,p,(p,a,b)) -#define IDirectDraw4_GetDisplayMode(p,a) ICOM_CALL_(GetDisplayMode,p,(p,a)) -#define IDirectDraw4_GetFourCCCodes(p,a,b) ICOM_CALL_(GetFourCCCodes,p,(p,a,b)) -#define IDirectDraw4_GetGDISurface(p,a) ICOM_CALL_(GetGDISurface,p,(p,a)) -#define IDirectDraw4_GetMonitorFrequency(p,a) ICOM_CALL_(GetMonitorFrequency,p,(p,a)) -#define IDirectDraw4_GetScanLine(p,a) ICOM_CALL_(GetScanLine,p,(p,a)) -#define IDirectDraw4_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a)) -#define IDirectDraw4_Initialize(p,a) ICOM_CALL_(Initialize,p,(p,a)) -#define IDirectDraw4_RestoreDisplayMode(p) ICOM_CALL_(RestoreDisplayMode,p,(p)) -#define IDirectDraw4_SetCooperativeLevel(p,a,b) ICOM_CALL_(SetCooperativeLevel,p,(p,a,b)) -#define IDirectDraw4_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e)) -#define IDirectDraw4_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b)) -/*** IDirectDraw2 methods ***/ -#define IDirectDraw4_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c)) -/*** IDirectDraw4 methods ***/ -#define IDirectDraw4_GetSurfaceFromDC(p,a,b) ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b)) -#define IDirectDraw4_RestoreAllSurfaces(pc) ICOM_CALL_(RestoreAllSurfaces,p,(p)) -#define IDirectDraw4_TestCooperativeLevel(p) ICOM_CALL_(TestCooperativeLevel,p,(p)) -#define IDirectDraw4_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b)) - - -/***************************************************************************** - * IDirectDraw7 interface - */ -/* Note: IDirectDraw7 cannot derive from IDirectDraw4; it is even documented - * as not interchangeable with earlier DirectDraw interfaces. - */ -#undef INTERFACE -#define INTERFACE IDirectDraw7 -DECLARE_INTERFACE_(IDirectDraw7,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(Compact)(THIS) PURE; - STDMETHOD(CreateClipper)(THIS_ DWORD dwFlags, LPDIRECTDRAWCLIPPER* lplpDDClipper, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreatePalette)(THIS_ DWORD dwFlags, LPPALETTEENTRY lpColorTable, LPDIRECTDRAWPALETTE* lplpDDPalette, IUnknown* pUnkOuter) PURE; - STDMETHOD(CreateSurface)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc, LPDIRECTDRAWSURFACE7* lplpDDSurface, IUnknown* pUnkOuter) PURE; - STDMETHOD(DuplicateSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurface, LPDIRECTDRAWSURFACE7* lplpDupDDSurface) PURE; - STDMETHOD(EnumDisplayModes)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSurfaceDesc, LPVOID lpContext, LPDDENUMMODESCALLBACK2 lpEnumModesCallback) PURE; - STDMETHOD(EnumSurfaces)(THIS_ DWORD dwFlags, LPDDSURFACEDESC2 lpDDSD, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; - STDMETHOD(FlipToGDISurface)(THIS) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDCAPS lpDDDriverCaps, LPDDCAPS lpDDHELCaps) PURE; - STDMETHOD(GetDisplayMode)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; - STDMETHOD(GetFourCCCodes)(THIS_ LPDWORD lpNumCodes, LPDWORD lpCodes) PURE; - STDMETHOD(GetGDISurface)(THIS_ LPDIRECTDRAWSURFACE7* lplpGDIDDSurface) PURE; - STDMETHOD(GetMonitorFrequency)(THIS_ LPDWORD lpdwFrequency) PURE; - STDMETHOD(GetScanLine)(THIS_ LPDWORD lpdwScanLine) PURE; - STDMETHOD(GetVerticalBlankStatus)(THIS_ BOOL* lpbIsInVB) PURE; - STDMETHOD(Initialize)(THIS_ GUID* lpGUID) PURE; - STDMETHOD(RestoreDisplayMode)(THIS) PURE; - STDMETHOD(SetCooperativeLevel)(THIS_ HWND hWnd, DWORD dwFlags) PURE; - STDMETHOD(SetDisplayMode)(THIS_ DWORD dwWidth, DWORD dwHeight, DWORD dwBPP, DWORD dwRefreshRate, DWORD dwFlags) PURE; - STDMETHOD(WaitForVerticalBlank)(THIS_ DWORD dwFlags, HANDLE hEvent) PURE; - - STDMETHOD(GetAvailableVidMem)(THIS_ LPDDSCAPS2 lpDDCaps, LPDWORD lpdwTotal, LPDWORD lpdwFree) PURE; - - STDMETHOD(GetSurfaceFromDC)(THIS_ HDC , LPDIRECTDRAWSURFACE7* ) PURE; - STDMETHOD(RestoreAllSurfaces)(THIS) PURE; - STDMETHOD(TestCooperativeLevel)(THIS) PURE; - STDMETHOD(GetDeviceIdentifier)(THIS_ LPDDDEVICEIDENTIFIER2 , DWORD ) PURE; - - STDMETHOD(StartModeTest)(THIS_ LPSIZE , DWORD , DWORD ) PURE; - STDMETHOD(EvaluateMode)(THIS_ DWORD , DWORD * ) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDraw7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDraw7_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDraw7_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDraw methods ***/ -#define IDirectDraw7_Compact(p) ICOM_CALL_(Compact,p,(p)) -#define IDirectDraw7_CreateClipper(p,a,b,c) ICOM_CALL_(CreateClipper,p,(p,a,b,c)) -#define IDirectDraw7_CreatePalette(p,a,b,c,d) ICOM_CALL_(CreatePalette,p,(p,a,b,c,d)) -#define IDirectDraw7_CreateSurface(p,a,b,c) ICOM_CALL_(CreateSurface,p,(p,a,b,c)) -#define IDirectDraw7_DuplicateSurface(p,a,b) ICOM_CALL_(DuplicateSurface,p,(p,a,b)) -#define IDirectDraw7_EnumDisplayModes(p,a,b,c,d) ICOM_CALL_(EnumDisplayModes,p,(p,a,b,c,d)) -#define IDirectDraw7_EnumSurfaces(p,a,b,c,d) ICOM_CALL_(EnumSurfaces,p,(p,a,b,c,d)) -#define IDirectDraw7_FlipToGDISurface(p) ICOM_CALL_(FlipToGDISurface,p,(p)) -#define IDirectDraw7_GetCaps(p,a,b) ICOM_CALL_(GetCaps,p,(p,a,b)) -#define IDirectDraw7_GetDisplayMode(p,a) ICOM_CALL_(GetDisplayMode,p,(p,a)) -#define IDirectDraw7_GetFourCCCodes(p,a,b) ICOM_CALL_(GetFourCCCodes,p,(p,a,b)) -#define IDirectDraw7_GetGDISurface(p,a) ICOM_CALL_(GetGDISurface,p,(p,a)) -#define IDirectDraw7_GetMonitorFrequency(p,a) ICOM_CALL_(GetMonitorFrequency,p,(p,a)) -#define IDirectDraw7_GetScanLine(p,a) ICOM_CALL_(GetScanLine,p,(p,a)) -#define IDirectDraw7_GetVerticalBlankStatus(p,a) ICOM_CALL_(GetVerticalBlankStatus,p,(p,a)) -#define IDirectDraw7_Initialize(p,a) ICOM_CALL_(Initialize,p,(p,a)) -#define IDirectDraw7_RestoreDisplayMode(p) ICOM_CALL_(RestoreDisplayMode,p,(p)) -#define IDirectDraw7_SetCooperativeLevel(p,a,b) ICOM_CALL_(SetCooperativeLevel,p,(p,a,b)) -#define IDirectDraw7_SetDisplayMode(p,a,b,c,d,e) ICOM_CALL_(SetDisplayMode,p,(p,a,b,c,d,e)) -#define IDirectDraw7_WaitForVerticalBlank(p,a,b) ICOM_CALL_(WaitForVerticalBlank,p,(p,a,b)) -/*** added in IDirectDraw2 ***/ -#define IDirectDraw7_GetAvailableVidMem(p,a,b,c) ICOM_CALL_(GetAvailableVidMem,p,(p,a,b,c)) -/*** added in IDirectDraw4 ***/ -#define IDirectDraw7_GetSurfaceFromDC(p,a,b) ICOM_CALL_(GetSurfaceFromDC,p,(p,a,b)) -#define IDirectDraw7_RestoreAllSurfaces(p) ICOM_CALL_(RestoreAllSurfaces,p,(p)) -#define IDirectDraw7_TestCooperativeLevel(p) ICOM_CALL_(TestCooperativeLevel,p,(p)) -#define IDirectDraw7_GetDeviceIdentifier(p,a,b) ICOM_CALL_(GetDeviceIdentifier,p,(p,a,b)) -/*** added in IDirectDraw 7 ***/ -#define IDirectDraw7_StartModeTest(p,a,b,c) ICOM_CALL_(StartModeTest,p,(p,a,b,c)) -#define IDirectDraw7_EvaluateMode(p,a,b) ICOM_CALL_(EvaluateMode,p,(p,a,b)) - - -/***************************************************************************** - * IDirectDrawSurface interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawSurface -DECLARE_INTERFACE_(IDirectDrawSurface,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; - STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; - STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; - STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; - STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; - STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSAttachedSurface) PURE; - STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; - STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; - STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE* lplpDDAttachedSurface) PURE; - STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; - STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; - STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; - STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; - STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; - STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; - STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(IsLost)(THIS) PURE; - STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; - STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; - STDMETHOD(Restore)(THIS) PURE; - STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; - STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; - STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; - STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; - STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; - STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE lpDDSReference) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawSurface_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawSurface_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawSurface_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDrawSurface methods ***/ -#define IDirectDrawSurface_AddAttachedSurface(p,a) ICOM_CALL_(AddAttachedSurface,p,(p,a)) -#define IDirectDrawSurface_AddOverlayDirtyRect(p,a) ICOM_CALL_(AddOverlayDirtyRect,p,(p,a)) -#define IDirectDrawSurface_Blt(p,a,b,c,d,e) ICOM_CALL_(Blt,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface_BltBatch(p,a,b,c) ICOM_CALL_(BltBatch,p,(p,a,b,c)) -#define IDirectDrawSurface_BltFast(p,a,b,c,d,e) ICOM_CALL_(BltFast,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface_EnumAttachedSurfaces(p,a,b) ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b)) -#define IDirectDrawSurface_EnumOverlayZOrders(p,a,b,c) ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c)) -#define IDirectDrawSurface_Flip(p,a,b) ICOM_CALL_(Flip,p,(p,a,b)) -#define IDirectDrawSurface_GetAttachedSurface(p,a,b) ICOM_CALL_(GetAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface_GetBltStatus(p,a) ICOM_CALL_(GetBltStatus,p,(p,a)) -#define IDirectDrawSurface_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawSurface_GetClipper(p,a) ICOM_CALL_(GetClipper,p,(p,a)) -#define IDirectDrawSurface_GetColorKey(p,a,b) ICOM_CALL_(GetColorKey,p,(p,a,b)) -#define IDirectDrawSurface_GetDC(p,a) ICOM_CALL_(GetDC,p,(p,a)) -#define IDirectDrawSurface_GetFlipStatus(p,a) ICOM_CALL_(GetFlipStatus,p,(p,a)) -#define IDirectDrawSurface_GetOverlayPosition(p,a,b) ICOM_CALL_(GetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface_GetPalette(p,a) ICOM_CALL_(GetPalette,p,(p,a)) -#define IDirectDrawSurface_GetPixelFormat(p,a) ICOM_CALL_(GetPixelFormat,p,(p,a)) -#define IDirectDrawSurface_GetSurfaceDesc(p,a) ICOM_CALL_(GetSurfaceDesc,p,(p,a)) -#define IDirectDrawSurface_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawSurface_IsLost(p) ICOM_CALL_(IsLost,p,(p)) -#define IDirectDrawSurface_Lock(p,a,b,c,d) ICOM_CALL_(Lock,p,(p,a,b,c,d)) -#define IDirectDrawSurface_ReleaseDC(p,a) ICOM_CALL_(ReleaseDC,p,(p,a)) -#define IDirectDrawSurface_Restore(p) ICOM_CALL_(Restore,p,(p)) -#define IDirectDrawSurface_SetClipper(p,a) ICOM_CALL_(SetClipper,p,(p,a)) -#define IDirectDrawSurface_SetColorKey(p,a,b) ICOM_CALL_(SetColorKey,p,(p,a,b)) -#define IDirectDrawSurface_SetOverlayPosition(p,a,b) ICOM_CALL_(SetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface_SetPalette(p,a) ICOM_CALL_(SetPalette,p,(p,a)) -#define IDirectDrawSurface_Unlock(p,a) ICOM_CALL_(Unlock,p,(p,a)) -#define IDirectDrawSurface_UpdateOverlay(p,a,b,c,d,e) ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface_UpdateOverlayDisplay(p,a) ICOM_CALL_(UpdateOverlayDisplay,p,(p,a)) -#define IDirectDrawSurface_UpdateOverlayZOrder(p,a,b) ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b)) - - -/***************************************************************************** - * IDirectDrawSurface2 interface - */ -/* Cannot inherit from IDirectDrawSurface because the LPDIRECTDRAWSURFACE parameters - * have been converted to LPDIRECTDRAWSURFACE2. - */ -#undef INTERFACE -#define INTERFACE IDirectDrawSurface2 -DECLARE_INTERFACE_(IDirectDrawSurface2,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; - STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; - STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; - STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; - STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE2 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; - STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSAttachedSurface) PURE; - STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; - STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE2 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; - STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE2* lplpDDAttachedSurface) PURE; - STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; - STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; - STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; - STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; - STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; - STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; - STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(IsLost)(THIS) PURE; - STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; - STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; - STDMETHOD(Restore)(THIS) PURE; - STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; - STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; - STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; - STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; - STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE2 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; - STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE2 lpDDSReference) PURE; - /* added in v2 */ - STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; - STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawSurface2_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawSurface2_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawSurface2_Release(p) ICOM_CALL_(Release,p,(p)) -/*** IDirectDrawSurface methods (almost) ***/ -#define IDirectDrawSurface2_AddAttachedSurface(p,a) ICOM_CALL_(AddAttachedSurface,p,(p,a)) -#define IDirectDrawSurface2_AddOverlayDirtyRect(p,a) ICOM_CALL_(AddOverlayDirtyRect,p,(p,a)) -#define IDirectDrawSurface2_Blt(p,a,b,c,d,e) ICOM_CALL_(Blt,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface2_BltBatch(p,a,b,c) ICOM_CALL_(BltBatch,p,(p,a,b,c)) -#define IDirectDrawSurface2_BltFast(p,a,b,c,d,e) ICOM_CALL_(BltFast,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface2_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface2_EnumAttachedSurfaces(p,a,b) ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b)) -#define IDirectDrawSurface2_EnumOverlayZOrders(p,a,b,c) ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c)) -#define IDirectDrawSurface2_Flip(p,a,b) ICOM_CALL_(Flip,p,(p,a,b)) -#define IDirectDrawSurface2_GetAttachedSurface(p,a,b) ICOM_CALL_(GetAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface2_GetBltStatus(p,a) ICOM_CALL_(GetBltStatus,p,(p,a)) -#define IDirectDrawSurface2_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawSurface2_GetClipper(p,a) ICOM_CALL_(GetClipper,p,(p,a)) -#define IDirectDrawSurface2_GetColorKey(p,a,b) ICOM_CALL_(GetColorKey,p,(p,a,b)) -#define IDirectDrawSurface2_GetDC(p,a) ICOM_CALL_(GetDC,p,(p,a)) -#define IDirectDrawSurface2_GetFlipStatus(p,a) ICOM_CALL_(GetFlipStatus,p,(p,a)) -#define IDirectDrawSurface2_GetOverlayPosition(p,a,b) ICOM_CALL_(GetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface2_GetPalette(p,a) ICOM_CALL_(GetPalette,p,(p,a)) -#define IDirectDrawSurface2_GetPixelFormat(p,a) ICOM_CALL_(GetPixelFormat,p,(p,a)) -#define IDirectDrawSurface2_GetSurfaceDesc(p,a) ICOM_CALL_(GetSurfaceDesc,p,(p,a)) -#define IDirectDrawSurface2_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawSurface2_IsLost(p) ICOM_CALL_(IsLost,p,(p)) -#define IDirectDrawSurface2_Lock(p,a,b,c,d) ICOM_CALL_(Lock,p,(p,a,b,c,d)) -#define IDirectDrawSurface2_ReleaseDC(p,a) ICOM_CALL_(ReleaseDC,p,(p,a)) -#define IDirectDrawSurface2_Restore(p) ICOM_CALL_(Restore,p,(p)) -#define IDirectDrawSurface2_SetClipper(p,a) ICOM_CALL_(SetClipper,p,(p,a)) -#define IDirectDrawSurface2_SetColorKey(p,a,b) ICOM_CALL_(SetColorKey,p,(p,a,b)) -#define IDirectDrawSurface2_SetOverlayPosition(p,a,b) ICOM_CALL_(SetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface2_SetPalette(p,a) ICOM_CALL_(SetPalette,p,(p,a)) -#define IDirectDrawSurface2_Unlock(p,a) ICOM_CALL_(Unlock,p,(p,a)) -#define IDirectDrawSurface2_UpdateOverlay(p,a,b,c,d,e) ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface2_UpdateOverlayDisplay(p,a) ICOM_CALL_(UpdateOverlayDisplay,p,(p,a)) -#define IDirectDrawSurface2_UpdateOverlayZOrder(p,a,b) ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b)) -/*** IDirectDrawSurface2 methods ***/ -#define IDirectDrawSurface2_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a)) -#define IDirectDrawSurface2_PageLock(p,a) ICOM_CALL_(PageLock,p,(p,a)) -#define IDirectDrawSurface2_PageUnlock(p,a) ICOM_CALL_(PageUnlock,p,(p,a)) - - -/***************************************************************************** - * IDirectDrawSurface3 interface - */ -/* Cannot inherit from IDirectDrawSurface2 because the LPDIRECTDRAWSURFACE2 parameters - * have been converted to LPDIRECTDRAWSURFACE3. - */ -#undef INTERFACE -#define INTERFACE IDirectDrawSurface3 -DECLARE_INTERFACE_(IDirectDrawSurface3,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; - STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; - STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; - STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; - STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE3 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; - STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSAttachedSurface) PURE; - STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; - STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE3 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; - STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS lpDDSCaps, LPDIRECTDRAWSURFACE3* lplpDDAttachedSurface) PURE; - STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDSCAPS lpDDSCaps) PURE; - STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; - STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; - STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; - STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; - STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; - STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(IsLost)(THIS) PURE; - STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; - STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; - STDMETHOD(Restore)(THIS) PURE; - STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; - STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; - STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; - STDMETHOD(Unlock)(THIS_ LPVOID lpSurfaceData) PURE; - STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE3 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; - STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE3 lpDDSReference) PURE; - /* added in v2 */ - STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; - STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; - /* added in v3 */ - STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawSurface3_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawSurface3_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawSurface3_Release(p) ICOM_CALL_(Release,p,(p)) -/*** IDirectDrawSurface methods (almost) ***/ -#define IDirectDrawSurface3_AddAttachedSurface(p,a) ICOM_CALL_(AddAttachedSurface,p,(p,a)) -#define IDirectDrawSurface3_AddOverlayDirtyRect(p,a) ICOM_CALL_(AddOverlayDirtyRect,p,(p,a)) -#define IDirectDrawSurface3_Blt(p,a,b,c,d,e) ICOM_CALL_(Blt,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface3_BltBatch(p,a,b,c) ICOM_CALL_(BltBatch,p,(p,a,b,c)) -#define IDirectDrawSurface3_BltFast(p,a,b,c,d,e) ICOM_CALL_(BltFast,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface3_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface3_EnumAttachedSurfaces(p,a,b) ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b)) -#define IDirectDrawSurface3_EnumOverlayZOrders(p,a,b,c) ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c)) -#define IDirectDrawSurface3_Flip(p,a,b) ICOM_CALL_(Flip,p,(p,a,b)) -#define IDirectDrawSurface3_GetAttachedSurface(p,a,b) ICOM_CALL_(GetAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface3_GetBltStatus(p,a) ICOM_CALL_(GetBltStatus,p,(p,a)) -#define IDirectDrawSurface3_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawSurface3_GetClipper(p,a) ICOM_CALL_(GetClipper,p,(p,a)) -#define IDirectDrawSurface3_GetColorKey(p,a,b) ICOM_CALL_(GetColorKey,p,(p,a,b)) -#define IDirectDrawSurface3_GetDC(p,a) ICOM_CALL_(GetDC,p,(p,a)) -#define IDirectDrawSurface3_GetFlipStatus(p,a) ICOM_CALL_(GetFlipStatus,p,(p,a)) -#define IDirectDrawSurface3_GetOverlayPosition(p,a,b) ICOM_CALL_(GetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface3_GetPalette(p,a) ICOM_CALL_(GetPalette,p,(p,a)) -#define IDirectDrawSurface3_GetPixelFormat(p,a) ICOM_CALL_(GetPixelFormat,p,(p,a)) -#define IDirectDrawSurface3_GetSurfaceDesc(p,a) ICOM_CALL_(GetSurfaceDesc,p,(p,a)) -#define IDirectDrawSurface3_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawSurface3_IsLost(p) ICOM_CALL_(IsLost,p,(p)) -#define IDirectDrawSurface3_Lock(p,a,b,c,d) ICOM_CALL_(Lock,p,(p,a,b,c,d)) -#define IDirectDrawSurface3_ReleaseDC(p,a) ICOM_CALL_(ReleaseDC,p,(p,a)) -#define IDirectDrawSurface3_Restore(p) ICOM_CALL_(Restore,p,(p)) -#define IDirectDrawSurface3_SetClipper(p,a) ICOM_CALL_(SetClipper,p,(p,a)) -#define IDirectDrawSurface3_SetColorKey(p,a,b) ICOM_CALL_(SetColorKey,p,(p,a,b)) -#define IDirectDrawSurface3_SetOverlayPosition(p,a,b) ICOM_CALL_(SetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface3_SetPalette(p,a) ICOM_CALL_(SetPalette,p,(p,a)) -#define IDirectDrawSurface3_Unlock(p,a) ICOM_CALL_(Unlock,p,(p,a)) -#define IDirectDrawSurface3_UpdateOverlay(p,a,b,c,d,e) ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface3_UpdateOverlayDisplay(p,a) ICOM_CALL_(UpdateOverlayDisplay,p,(p,a)) -#define IDirectDrawSurface3_UpdateOverlayZOrder(p,a,b) ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b)) -/*** IDirectDrawSurface2 methods ***/ -#define IDirectDrawSurface3_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a)) -#define IDirectDrawSurface3_PageLock(p,a) ICOM_CALL_(PageLock,p,(p,a)) -#define IDirectDrawSurface3_PageUnlock(p,a) ICOM_CALL_(PageUnlock,p,(p,a)) -/*** IDirectDrawSurface3 methods ***/ -#define IDirectDrawSurface3_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b)) - - -/***************************************************************************** - * IDirectDrawSurface4 interface - */ -/* Cannot inherit from IDirectDrawSurface2 because DDSCAPS changed to DDSCAPS2. - */ -#undef INTERFACE -#define INTERFACE IDirectDrawSurface4 -DECLARE_INTERFACE_(IDirectDrawSurface4,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; - STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; - STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; - STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; - STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE4 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; - STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSAttachedSurface) PURE; - STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpEnumSurfacesCallback) PURE; - STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK lpfnCallback) PURE; - STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE4 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; - STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE4* lplpDDAttachedSurface) PURE; - STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; - STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; - STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; - STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; - STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; - STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; - STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC lpDDSurfaceDesc) PURE; - STDMETHOD(IsLost)(THIS) PURE; - STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; - STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; - STDMETHOD(Restore)(THIS) PURE; - STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; - STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; - STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; - STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; - STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE4 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; - STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE4 lpDDSReference) PURE; - /* added in v2 */ - STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; - STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; - /* added in v3 */ - STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC lpDDSD, DWORD dwFlags) PURE; - /* added in v4 */ - STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; - STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; - STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; - STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; - STDMETHOD(ChangeUniquenessValue)(THIS) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawSurface4_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawSurface4_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawSurface4_Release(p) ICOM_CALL_(Release,p,(p)) -/*** IDirectDrawSurface (almost) methods ***/ -#define IDirectDrawSurface4_AddAttachedSurface(p,a) ICOM_CALL_(AddAttachedSurface,p,(p,a)) -#define IDirectDrawSurface4_AddOverlayDirtyRect(p,a) ICOM_CALL_(AddOverlayDirtyRect,p,(p,a)) -#define IDirectDrawSurface4_Blt(p,a,b,c,d,e) ICOM_CALL_(Blt,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface4_BltBatch(p,a,b,c) ICOM_CALL_(BltBatch,p,(p,a,b,c)) -#define IDirectDrawSurface4_BltFast(p,a,b,c,d,e) ICOM_CALL_(BltFast,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface4_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface4_EnumAttachedSurfaces(p,a,b) ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b)) -#define IDirectDrawSurface4_EnumOverlayZOrders(p,a,b,c) ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c)) -#define IDirectDrawSurface4_Flip(p,a,b) ICOM_CALL_(Flip,p,(p,a,b)) -#define IDirectDrawSurface4_GetAttachedSurface(p,a,b) ICOM_CALL_(GetAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface4_GetBltStatus(p,a) ICOM_CALL_(GetBltStatus,p,(p,a)) -#define IDirectDrawSurface4_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawSurface4_GetClipper(p,a) ICOM_CALL_(GetClipper,p,(p,a)) -#define IDirectDrawSurface4_GetColorKey(p,a,b) ICOM_CALL_(GetColorKey,p,(p,a,b)) -#define IDirectDrawSurface4_GetDC(p,a) ICOM_CALL_(GetDC,p,(p,a)) -#define IDirectDrawSurface4_GetFlipStatus(p,a) ICOM_CALL_(GetFlipStatus,p,(p,a)) -#define IDirectDrawSurface4_GetOverlayPosition(p,a,b) ICOM_CALL_(GetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface4_GetPalette(p,a) ICOM_CALL_(GetPalette,p,(p,a)) -#define IDirectDrawSurface4_GetPixelFormat(p,a) ICOM_CALL_(GetPixelFormat,p,(p,a)) -#define IDirectDrawSurface4_GetSurfaceDesc(p,a) ICOM_CALL_(GetSurfaceDesc,p,(p,a)) -#define IDirectDrawSurface4_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawSurface4_IsLost(p) ICOM_CALL_(IsLost,p,(p)) -#define IDirectDrawSurface4_Lock(p,a,b,c,d) ICOM_CALL_(Lock,p,(p,a,b,c,d)) -#define IDirectDrawSurface4_ReleaseDC(p,a) ICOM_CALL_(ReleaseDC,p,(p,a)) -#define IDirectDrawSurface4_Restore(p) ICOM_CALL_(Restore,p,(p)) -#define IDirectDrawSurface4_SetClipper(p,a) ICOM_CALL_(SetClipper,p,(p,a)) -#define IDirectDrawSurface4_SetColorKey(p,a,b) ICOM_CALL_(SetColorKey,p,(p,a,b)) -#define IDirectDrawSurface4_SetOverlayPosition(p,a,b) ICOM_CALL_(SetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface4_SetPalette(p,a) ICOM_CALL_(SetPalette,p,(p,a)) -#define IDirectDrawSurface4_Unlock(p,a) ICOM_CALL_(Unlock,p,(p,a)) -#define IDirectDrawSurface4_UpdateOverlay(p,a,b,c,d,e) ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface4_UpdateOverlayDisplay(p,a) ICOM_CALL_(UpdateOverlayDisplay,p,(p,a)) -#define IDirectDrawSurface4_UpdateOverlayZOrder(p,a,b) ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b)) -/*** IDirectDrawSurface2 methods ***/ -#define IDirectDrawSurface4_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a)) -#define IDirectDrawSurface4_PageLock(p,a) ICOM_CALL_(PageLock,p,(p,a)) -#define IDirectDrawSurface4_PageUnlock(p,a) ICOM_CALL_(PageUnlock,p,(p,a)) -/*** IDirectDrawSurface3 methods ***/ -#define IDirectDrawSurface4_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b)) -/*** IDirectDrawSurface4 methods ***/ -#define IDirectDrawSurface4_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d)) -#define IDirectDrawSurface4_GetPrivateData(p,a,b,c) ICOM_CALL_(GetPrivateData,p,(p,a,b,c)) -#define IDirectDrawSurface4_FreePrivateData(p,a) ICOM_CALL_(FreePrivateData,p,(p,a)) -#define IDirectDrawSurface4_GetUniquenessValue(p,a) ICOM_CALL_(GetUniquenessValue,p,(p,a)) -#define IDirectDrawSurface4_ChangeUniquenessValue(p) ICOM_CALL_(ChangeUniquenessValue,p,(p)) - - -/***************************************************************************** - * IDirectDrawSurface7 interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawSurface7 -DECLARE_INTERFACE_(IDirectDrawSurface7,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(AddAttachedSurface)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; - STDMETHOD(AddOverlayDirtyRect)(THIS_ LPRECT lpRect) PURE; - STDMETHOD(Blt)(THIS_ LPRECT lpDestRect, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwFlags, LPDDBLTFX lpDDBltFx) PURE; - STDMETHOD(BltBatch)(THIS_ LPDDBLTBATCH lpDDBltBatch, DWORD dwCount, DWORD dwFlags) PURE; - STDMETHOD(BltFast)(THIS_ DWORD dwX, DWORD dwY, LPDIRECTDRAWSURFACE7 lpDDSrcSurface, LPRECT lpSrcRect, DWORD dwTrans) PURE; - STDMETHOD(DeleteAttachedSurface)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSAttachedSurface) PURE; - STDMETHOD(EnumAttachedSurfaces)(THIS_ LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpEnumSurfacesCallback) PURE; - STDMETHOD(EnumOverlayZOrders)(THIS_ DWORD dwFlags, LPVOID lpContext, LPDDENUMSURFACESCALLBACK7 lpfnCallback) PURE; - STDMETHOD(Flip)(THIS_ LPDIRECTDRAWSURFACE7 lpDDSurfaceTargetOverride, DWORD dwFlags) PURE; - STDMETHOD(GetAttachedSurface)(THIS_ LPDDSCAPS2 lpDDSCaps, LPDIRECTDRAWSURFACE7* lplpDDAttachedSurface) PURE; - STDMETHOD(GetBltStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetCaps)(THIS_ LPDDSCAPS2 lpDDSCaps) PURE; - STDMETHOD(GetClipper)(THIS_ LPDIRECTDRAWCLIPPER* lplpDDClipper) PURE; - STDMETHOD(GetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(GetDC)(THIS_ HDC* lphDC) PURE; - STDMETHOD(GetFlipStatus)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(GetOverlayPosition)(THIS_ LPLONG lplX, LPLONG lplY) PURE; - STDMETHOD(GetPalette)(THIS_ LPDIRECTDRAWPALETTE* lplpDDPalette) PURE; - STDMETHOD(GetPixelFormat)(THIS_ LPDDPIXELFORMAT lpDDPixelFormat) PURE; - STDMETHOD(GetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; - STDMETHOD(Initialize)(THIS_ LPDIRECTDRAW lpDD, LPDDSURFACEDESC2 lpDDSurfaceDesc) PURE; - STDMETHOD(IsLost)(THIS) PURE; - STDMETHOD(Lock)(THIS_ LPRECT lpDestRect, LPDDSURFACEDESC2 lpDDSurfaceDesc, DWORD dwFlags, HANDLE hEvent) PURE; - STDMETHOD(ReleaseDC)(THIS_ HDC hDC) PURE; - STDMETHOD(Restore)(THIS) PURE; - STDMETHOD(SetClipper)(THIS_ LPDIRECTDRAWCLIPPER lpDDClipper) PURE; - STDMETHOD(SetColorKey)(THIS_ DWORD dwFlags, LPDDCOLORKEY lpDDColorKey) PURE; - STDMETHOD(SetOverlayPosition)(THIS_ LONG lX, LONG lY) PURE; - STDMETHOD(SetPalette)(THIS_ LPDIRECTDRAWPALETTE lpDDPalette) PURE; - STDMETHOD(Unlock)(THIS_ LPRECT lpSurfaceData) PURE; - STDMETHOD(UpdateOverlay)(THIS_ LPRECT lpSrcRect, LPDIRECTDRAWSURFACE7 lpDDDestSurface, LPRECT lpDestRect, DWORD dwFlags, LPDDOVERLAYFX lpDDOverlayFx) PURE; - STDMETHOD(UpdateOverlayDisplay)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(UpdateOverlayZOrder)(THIS_ DWORD dwFlags, LPDIRECTDRAWSURFACE7 lpDDSReference) PURE; - /* added in v2 */ - STDMETHOD(GetDDInterface)(THIS_ LPVOID* lplpDD) PURE; - STDMETHOD(PageLock)(THIS_ DWORD dwFlags) PURE; - STDMETHOD(PageUnlock)(THIS_ DWORD dwFlags) PURE; - /* added in v3 */ - STDMETHOD(SetSurfaceDesc)(THIS_ LPDDSURFACEDESC2 lpDDSD, DWORD dwFlags) PURE; - /* added in v4 */ - STDMETHOD(SetPrivateData)(THIS_ REFGUID , LPVOID , DWORD , DWORD ) PURE; - STDMETHOD(GetPrivateData)(THIS_ REFGUID , LPVOID , LPDWORD ) PURE; - STDMETHOD(FreePrivateData)(THIS_ REFGUID ) PURE; - STDMETHOD(GetUniquenessValue)(THIS_ LPDWORD ) PURE; - STDMETHOD(ChangeUniquenessValue)(THIS) PURE; - /* added in v7 */ - STDMETHOD(SetPriority)(THIS_ DWORD prio) PURE; - STDMETHOD(GetPriority)(THIS_ LPDWORD prio) PURE; - STDMETHOD(SetLOD)(THIS_ DWORD lod) PURE; - STDMETHOD(GetLOD)(THIS_ LPDWORD lod) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawSurface7_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawSurface7_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawSurface7_Release(p) ICOM_CALL_(Release,p,(p)) -/*** IDirectDrawSurface (almost) methods ***/ -#define IDirectDrawSurface7_AddAttachedSurface(p,a) ICOM_CALL_(AddAttachedSurface,p,(p,a)) -#define IDirectDrawSurface7_AddOverlayDirtyRect(p,a) ICOM_CALL_(AddOverlayDirtyRect,p,(p,a)) -#define IDirectDrawSurface7_Blt(p,a,b,c,d,e) ICOM_CALL_(Blt,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface7_BltBatch(p,a,b,c) ICOM_CALL_(BltBatch,p,(p,a,b,c)) -#define IDirectDrawSurface7_BltFast(p,a,b,c,d,e) ICOM_CALL_(BltFast,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface7_DeleteAttachedSurface(p,a,b) ICOM_CALL_(DeleteAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface7_EnumAttachedSurfaces(p,a,b) ICOM_CALL_(EnumAttachedSurfaces,p,(p,a,b)) -#define IDirectDrawSurface7_EnumOverlayZOrders(p,a,b,c) ICOM_CALL_(EnumOverlayZOrders,p,(p,a,b,c)) -#define IDirectDrawSurface7_Flip(p,a,b) ICOM_CALL_(Flip,p,(p,a,b)) -#define IDirectDrawSurface7_GetAttachedSurface(p,a,b) ICOM_CALL_(GetAttachedSurface,p,(p,a,b)) -#define IDirectDrawSurface7_GetBltStatus(p,a) ICOM_CALL_(GetBltStatus,p,(p,a)) -#define IDirectDrawSurface7_GetCaps(p,a) ICOM_CALL_(GetCaps,p,(p,a)) -#define IDirectDrawSurface7_GetClipper(p,a) ICOM_CALL_(GetClipper,p,(p,a)) -#define IDirectDrawSurface7_GetColorKey(p,a,b) ICOM_CALL_(GetColorKey,p,(p,a,b)) -#define IDirectDrawSurface7_GetDC(p,a) ICOM_CALL_(GetDC,p,(p,a)) -#define IDirectDrawSurface7_GetFlipStatus(p,a) ICOM_CALL_(GetFlipStatus,p,(p,a)) -#define IDirectDrawSurface7_GetOverlayPosition(p,a,b) ICOM_CALL_(GetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface7_GetPalette(p,a) ICOM_CALL_(GetPalette,p,(p,a)) -#define IDirectDrawSurface7_GetPixelFormat(p,a) ICOM_CALL_(GetPixelFormat,p,(p,a)) -#define IDirectDrawSurface7_GetSurfaceDesc(p,a) ICOM_CALL_(GetSurfaceDesc,p,(p,a)) -#define IDirectDrawSurface7_Initialize(p,a,b) ICOM_CALL_(Initialize,p,(p,a,b)) -#define IDirectDrawSurface7_IsLost(p) ICOM_CALL_(IsLost,p,(p)) -#define IDirectDrawSurface7_Lock(p,a,b,c,d) ICOM_CALL_(Lock,p,(p,a,b,c,d)) -#define IDirectDrawSurface7_ReleaseDC(p,a) ICOM_CALL_(ReleaseDC,p,(p,a)) -#define IDirectDrawSurface7_Restore(p) ICOM_CALL_(Restore,p,(p)) -#define IDirectDrawSurface7_SetClipper(p,a) ICOM_CALL_(SetClipper,p,(p,a)) -#define IDirectDrawSurface7_SetColorKey(p,a,b) ICOM_CALL_(SetColorKey,p,(p,a,b)) -#define IDirectDrawSurface7_SetOverlayPosition(p,a,b) ICOM_CALL_(SetOverlayPosition,p,(p,a,b)) -#define IDirectDrawSurface7_SetPalette(p,a) ICOM_CALL_(SetPalette,p,(p,a)) -#define IDirectDrawSurface7_Unlock(p,a) ICOM_CALL_(Unlock,p,(p,a)) -#define IDirectDrawSurface7_UpdateOverlay(p,a,b,c,d,e) ICOM_CALL_(UpdateOverlay,p,(p,a,b,c,d,e)) -#define IDirectDrawSurface7_UpdateOverlayDisplay(p,a) ICOM_CALL_(UpdateOverlayDisplay,p,(p,a)) -#define IDirectDrawSurface7_UpdateOverlayZOrder(p,a,b) ICOM_CALL_(UpdateOverlayZOrder,p,(p,a,b)) -/*** IDirectDrawSurface2 methods ***/ -#define IDirectDrawSurface7_GetDDInterface(p,a) ICOM_CALL_(GetDDInterface,p,(p,a)) -#define IDirectDrawSurface7_PageLock(p,a) ICOM_CALL_(PageLock,p,(p,a)) -#define IDirectDrawSurface7_PageUnlock(p,a) ICOM_CALL_(PageUnlock,p,(p,a)) -/*** IDirectDrawSurface3 methods ***/ -#define IDirectDrawSurface7_SetSurfaceDesc(p,a,b) ICOM_CALL_(SetSurfaceDesc,p,(p,a,b)) -/*** IDirectDrawSurface4 methods ***/ -#define IDirectDrawSurface7_SetPrivateData(p,a,b,c,d) ICOM_CALL_(SetPrivateData,p,(p,a,b,c,d)) -#define IDirectDrawSurface7_GetPrivateData(p,a,b,c) ICOM_CALL_(GetPrivateData,p,(p,a,b,c)) -#define IDirectDrawSurface7_FreePrivateData(p,a) ICOM_CALL_(FreePrivateData,p,(p,a)) -#define IDirectDrawSurface7_GetUniquenessValue(p,a) ICOM_CALL_(GetUniquenessValue,p,(p,a)) -#define IDirectDrawSurface7_ChangeUniquenessValue(p) ICOM_CALL_(ChangeUniquenessValue,p,(p)) -/*** IDirectDrawSurface7 methods ***/ -#define IDirectDrawSurface7_SetPriority(p,a) ICOM_CALL_(SetPriority,p,(p,a)) -#define IDirectDrawSurface7_GetPriority(p,a) ICOM_CALL_(GetPriority,p,(p,a)) -#define IDirectDrawSurface7_SetLOD(p,a) ICOM_CALL_(SetLOD,p,(p,a)) -#define IDirectDrawSurface7_GetLOD(p,a) ICOM_CALL_(GetLOD,p,(p,a)) - -/***************************************************************************** - * IDirectDrawColorControl interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawColorControl -DECLARE_INTERFACE_(IDirectDrawColorControl,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE; - STDMETHOD(SetColorControls)(THIS_ LPDDCOLORCONTROL lpColorControl) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawColorControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawColorControl_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawColorControl_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDrawColorControl methods ***/ -#define IDirectDrawColorControl_GetColorControls(p,a) ICOM_CALL_(GetColorControls,p,(p,a)) -#define IDirectDrawColorControl_SetColorControls(p,a) ICOM_CALL_(SetColorControls,p,(p,a)) - -/***************************************************************************** - * IDirectDrawGammaControl interface - */ -#undef INTERFACE -#define INTERFACE IDirectDrawGammaControl -DECLARE_INTERFACE_(IDirectDrawGammaControl,IUnknown) -{ - STDMETHOD(QueryInterface)(THIS_ REFIID,LPVOID*) PURE; - STDMETHOD_(ULONG,AddRef)(THIS) PURE; - STDMETHOD_(ULONG,Release)(THIS) PURE; - STDMETHOD(GetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE; - STDMETHOD(SetGammaRamp)(THIS_ DWORD dwFlags, LPDDGAMMARAMP lpGammaRamp) PURE; -}; - - /*** IUnknown methods ***/ -#define IDirectDrawGammaControl_QueryInterface(p,a,b) ICOM_CALL_(QueryInterface,p,(p,a,b)) -#define IDirectDrawGammaControl_AddRef(p) ICOM_CALL_(AddRef,p,(p)) -#define IDirectDrawGammaControl_Release(p) ICOM_CALL_(Release,p,(p)) - /*** IDirectDrawGammaControl methods ***/ -#define IDirectDrawGammaControl_GetGammaRamp(p,a,b) ICOM_CALL_(GetGammaRamp,p,(p,a,b)) -#define IDirectDrawGammaControl_SetGammaRamp(p,a,b) ICOM_CALL_(SetGammaRamp,p,(p,a,b)) - - -HRESULT WINAPI DirectDrawCreate(LPGUID,LPDIRECTDRAW*,LPUNKNOWN); -HRESULT WINAPI DirectDrawCreateEx(LPGUID,LPVOID*,REFIID,LPUNKNOWN); -HRESULT WINAPI DirectDrawEnumerateA(LPDDENUMCALLBACKA,LPVOID); -HRESULT WINAPI DirectDrawEnumerateW(LPDDENUMCALLBACKW,LPVOID); -#define DirectDrawEnumerate WINELIB_NAME_AW(DirectDrawEnumerate) -HRESULT WINAPI DirectDrawCreateClipper(DWORD,LPDIRECTDRAWCLIPPER*,LPUNKNOWN); - - -#ifdef __cplusplus -} /* extern "C" */ -#endif /* defined(__cplusplus) */ - -#endif /* __XWIN_DDRAW_H */ diff --git a/xorg-server/hw/xwin/makefile b/xorg-server/hw/xwin/makefile new file mode 100644 index 000000000..74dcfaeed --- /dev/null +++ b/xorg-server/hw/xwin/makefile @@ -0,0 +1,107 @@ +LIBRARY = libXWin + +SRCS_CLIPBOARD = \ + winclipboardinit.c \ + winclipboardtextconv.c \ + winclipboardthread.c \ + winclipboardunicode.c \ + winclipboardwndproc.c \ + winclipboardwrappers.c \ + winclipboardxevents.c + +DEFINES += XWIN_CLIPBOARD + +SRCS_MULTIWINDOW = \ + winmultiwindowshape.c \ + winmultiwindowwindow.c \ + winmultiwindowwm.c \ + winmultiwindowwndproc.c + +DEFINES += XWIN_MULTIWINDOW + +#SRCS_MULTIWINDOWEXTWM = \ +# winwin32rootless.c \ +# winwin32rootlesswindow.c \ +# winwin32rootlesswndproc.c \ +# winwindowswm.c +#DEFINES += XWIN_MULTIWINDOWEXTWM + +SRCS_RANDR = \ + winrandr.c +DEFINES += XWIN_RANDR RELOCATE_PROJECTROOT + +CSRCS = InitInput.c \ + InitOutput.c \ + winallpriv.c \ + winauth.c \ + winblock.c \ + wincmap.c \ + winconfig.c \ + wincreatewnd.c \ + wincursor.c \ + windialogs.c \ + winengine.c \ + winerror.c \ + winglobals.c \ + winkeybd.c \ + winkeyhook.c \ + winmisc.c \ + winmouse.c \ + winmsg.c \ + winmultiwindowclass.c \ + winmultiwindowicons.c \ + winprefs.c \ + winprocarg.c \ + winregistry.c \ + winscrinit.c \ + winshaddd.c \ + winshadddnl.c \ + winshadgdi.c \ + wintrayicon.c \ + winvalargs.c \ + winwakeup.c \ + winwindow.c \ + winprefslex.c \ + winprefsyacc.c \ + winwndproc.c $(SRCS_RANDR) $(SRCS_MULTIWINDOW) $(SRCS_MULTIWINDOWEXTWM) $(SRCS_CLIPBOARD) + +DEFINES += YY_NO_UNISTD_H + +# XWin.rc \ +# $(top_srcdir)/Xext/dpmsstubs.c \ +# $(top_srcdir)/Xi/stubs.c \ +# $(top_srcdir)/mi/miinitext.c \ +# $(top_srcdir)/fb/fbcmap_mi.c \ +# $(SRCS_CLIPBOARD) \ +# $(SRCS_GLX_WINDOWS) \ +# $(SRCS_MULTIWINDOW) \ +# $(SRCS_MULTIWINDOWEXTWM) \ +# $(SRCS_NATIVEGDI) \ +# $(SRCS_PRIMARYFB) \ +# $(SRCS_RANDR) \ +# $(SRCS_XV) + +INCLUDES += ..\..\miext\rootless + +SRCS_NATIVEGDI = \ + winclip.c \ + winfillsp.c \ + winfont.c \ + wingc.c \ + wingetsp.c \ + winnativegdi.c \ + winpixmap.c \ + winpolyline.c \ + winrop.c \ + winsetsp.c +CSRCS += $(SRCS_NATIVEGDI) +DEFINES += XWIN_NATIVEGDI + +#.rc.o: + +# $(WINDRES) --use-temp-file -i $< --input-format=rc -o $@ -O coff -I $(top_builddir)/include -DPROJECT_NAME=\"$(VENDOR_NAME_SHORT)\" -DPROJECT_VERSION=\"$(PACKAGE_VERSION)\" -DBUILD_DATE=\"$(BUILD_DATE)\" + +DEFINES += HAVE_XWIN_CONFIG_H BUILD_DATE=0-0-0000 PTW32_STATIC_LIB + +#CSRCS=winkeybd.c + diff --git a/xorg-server/hw/xwin/win.h b/xorg-server/hw/xwin/win.h index 9009df29b..45ad7a8de 100644 --- a/xorg-server/hw/xwin/win.h +++ b/xorg-server/hw/xwin/win.h @@ -142,6 +142,9 @@ #include <errno.h> #if defined(XWIN_MULTIWINDOWEXTWM) || defined(XWIN_CLIPBOARD) || defined(XWIN_MULTIWINDOW) #define HANDLE void * +#ifdef _MSC_VER +typedef int pid_t; +#endif #include <pthread.h> #undef HANDLE #endif @@ -591,6 +594,11 @@ typedef struct _winPrivScreenRec MoveWindowProcPtr MoveWindow; SetShapeProcPtr SetShape; +#ifdef XWIN_NATIVEGDI + RealizeFontProcPtr RealizeFont; + UnrealizeFontProcPtr UnrealizeFont; +#endif + winCursorRec cursor; } winPrivScreenRec; @@ -833,6 +841,9 @@ winCreateBoundingWindowWindowed (ScreenPtr pScreen); * windialogs.c */ +int +GetLiveClients (winPrivScreenPtr pScreenPriv); + void winDisplayExitDialog (winPrivScreenPtr pScreenPriv); @@ -1303,7 +1314,7 @@ winTopLevelWindowProc (HWND hwnd, UINT message, */ void -winInitNotifyIcon (winPrivScreenPtr pScreenPriv); +winInitNotifyIcon (winPrivScreenPtr pScreenPriv, Bool Modify); void winDeleteNotifyIcon (winPrivScreenPtr pScreenPriv); diff --git a/xorg-server/hw/xwin/winclipboard.h b/xorg-server/hw/xwin/winclipboard.h index 089c2913b..730f57920 100644 --- a/xorg-server/hw/xwin/winclipboard.h +++ b/xorg-server/hw/xwin/winclipboard.h @@ -34,7 +34,9 @@ #include <assert.h> #include <stdio.h> #include <stdlib.h> +#ifndef _MSC_VER #include <unistd.h> +#endif #ifdef __CYGWIN__ #include <sys/select.h> #else @@ -43,6 +45,9 @@ #endif #include <fcntl.h> #include <setjmp.h> +#ifdef _MSC_VER +typedef int pid_t; +#endif #include <pthread.h> /* X headers */ @@ -145,5 +150,6 @@ int winClipboardFlushXEvents (HWND hwnd, int iWindow, Display *pDisplay, - Bool fUnicodeSupport); + Bool fUnicodeSupport, + Bool ClipboardOpened); #endif diff --git a/xorg-server/hw/xwin/winclipboardthread.c b/xorg-server/hw/xwin/winclipboardthread.c index 8eb825fa8..edade899d 100644 --- a/xorg-server/hw/xwin/winclipboardthread.c +++ b/xorg-server/hw/xwin/winclipboardthread.c @@ -1,480 +1,509 @@ -/* - *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved. - *Copyright (C) Colin Harrison 2005-2008 - * - *Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - *"Software"), to deal in the Software without restriction, including - *without limitation the rights to use, copy, modify, merge, publish, - *distribute, sublicense, and/or sell copies of the Software, and to - *permit persons to whom the Software is furnished to do so, subject to - *the following conditions: - * - *The above copyright notice and this permission notice shall be - *included in all copies or substantial portions of the Software. - * - *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR - *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - *Except as contained in this notice, the name of 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: Harold L Hunt II - * Colin Harrison - */ - -#ifdef HAVE_XWIN_CONFIG_H -#include <xwin-config.h> -#endif -#include <sys/types.h> -#include "winclipboard.h" -#ifdef __CYGWIN__ -#include <errno.h> -#endif -#include "X11/Xauth.h" -#include "misc.h" - - -/* - * Constants - */ - -#define AUTH_NAME "MIT-MAGIC-COOKIE-1" - - -/* - * References to external symbols - */ - -extern Bool g_fUnicodeClipboard; -extern unsigned long serverGeneration; -#if defined(XCSECURITY) -extern unsigned int g_uiAuthDataLen; -extern char *g_pAuthData; -#endif -extern Bool g_fClipboardStarted; -extern HWND g_hwndClipboard; -extern void *g_pClipboardDisplay; -extern Window g_iClipboardWindow; - - -/* - * Global variables - */ - -static jmp_buf g_jmpEntry; -Bool g_fUnicodeSupport = FALSE; -Bool g_fUseUnicode = FALSE; - - -/* - * Local function prototypes - */ - -static int -winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr); - -static int -winClipboardIOErrorHandler (Display *pDisplay); - - -/* - * Main thread function - */ - -void * -winClipboardProc (void *pvNotUsed) -{ - Atom atomClipboard, atomClipboardManager; - int iReturn; - HWND hwnd = NULL; - int iConnectionNumber = 0; -#ifdef HAS_DEVWINDOWS - int fdMessageQueue = 0; -#else - struct timeval tvTimeout; -#endif - fd_set fdsRead; - int iMaxDescriptor; - Display *pDisplay = NULL; - Window iWindow = None; - int iRetries; - Bool fUseUnicode; - char szDisplay[512]; - int iSelectError; - - ErrorF ("winClipboardProc - Hello\n"); - - /* Do we have Unicode support? */ - g_fUnicodeSupport = winClipboardDetectUnicodeSupport (); - - /* Do we use Unicode clipboard? */ - fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport; - - /* Save the Unicode support flag in a global */ - g_fUseUnicode = fUseUnicode; - - /* Allow multiple threads to access Xlib */ - if (XInitThreads () == 0) - { - ErrorF ("winClipboardProc - XInitThreads failed.\n"); - pthread_exit (NULL); - } - - /* See if X supports the current locale */ - if (XSupportsLocale () == False) - { - ErrorF ("winClipboardProc - Locale not supported by X. Exiting.\n"); - pthread_exit (NULL); - } - - /* Set jump point for Error exits */ - iReturn = setjmp (g_jmpEntry); - - /* Check if we should continue operations */ - if (iReturn != WIN_JMP_ERROR_IO - && iReturn != WIN_JMP_OKAY) - { - /* setjmp returned an unknown value, exit */ - ErrorF ("winClipboardProc - setjmp returned: %d exiting\n", - iReturn); - pthread_exit (NULL); - } - else if (iReturn == WIN_JMP_ERROR_IO) - { - /* TODO: Cleanup the Win32 window and free any allocated memory */ - ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n"); - pthread_exit (NULL); - } - -#if defined(XCSECURITY) - /* Use our generated cookie for authentication */ - XSetAuthorization (AUTH_NAME, - strlen (AUTH_NAME), - g_pAuthData, - g_uiAuthDataLen); -#endif - - /* Set error handler */ - XSetErrorHandler (winClipboardErrorHandler); - XSetIOErrorHandler (winClipboardIOErrorHandler); - - /* Initialize retry count */ - iRetries = 0; - - /* Setup the display connection string x */ - /* - * NOTE: Always connect to screen 0 since we require that screen - * numbers start at 0 and increase without gaps. We only need - * to connect to one screen on the display to get events - * for all screens on the display. That is why there is only - * one clipboard client thread. - */ - snprintf (szDisplay, - 512, - "127.0.0.1:%s.0", - display); - - /* Print the display connection string */ - ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay); - - /* Open the X display */ - do - { - pDisplay = XOpenDisplay (szDisplay); - if (pDisplay == NULL) - { - ErrorF ("winClipboardProc - Could not open display, " - "try: %d, sleeping: %d\n", - iRetries + 1, WIN_CONNECT_DELAY); - ++iRetries; - sleep (WIN_CONNECT_DELAY); - continue; - } - else - break; - } - while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES); - - /* Make sure that the display opened */ - if (pDisplay == NULL) - { - ErrorF ("winClipboardProc - Failed opening the display, giving up\n"); - pthread_exit (NULL); - } - - /* Save the display in the screen privates */ - g_pClipboardDisplay = pDisplay; - - ErrorF ("winClipboardProc - XOpenDisplay () returned and " - "successfully opened the display.\n"); - - /* Get our connection number */ - iConnectionNumber = ConnectionNumber (pDisplay); - -#ifdef HAS_DEVWINDOWS - /* Open a file descriptor for the windows message queue */ - fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, O_RDONLY); - if (fdMessageQueue == -1) - { - ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME); - pthread_exit (NULL); - } - - /* Find max of our file descriptors */ - iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1; -#else - iMaxDescriptor = iConnectionNumber + 1; -#endif - - /* Create atoms */ - atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False); - atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False); - - /* Create a messaging window */ - iWindow = XCreateSimpleWindow (pDisplay, - DefaultRootWindow (pDisplay), - 1, 1, - 500, 500, - 0, - BlackPixel (pDisplay, 0), - BlackPixel (pDisplay, 0)); - if (iWindow == 0) - { - ErrorF ("winClipboardProc - Could not create an X window.\n"); - pthread_exit (NULL); - } - - /* Select event types to watch */ - if (XSelectInput (pDisplay, - iWindow, - PropertyChangeMask) == BadWindow) - ErrorF ("winClipboardProc - XSelectInput generated BadWindow " - "on messaging window\n"); - - /* Save the window in the screen privates */ - g_iClipboardWindow = iWindow; - - /* Create Windows messaging window */ - hwnd = winClipboardCreateMessagingWindow (); - - /* Save copy of HWND in screen privates */ - g_hwndClipboard = hwnd; - - /* Assert ownership of selections if Win32 clipboard is owned */ - if (NULL != GetClipboardOwner ()) - { - /* PRIMARY */ - iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY, - iWindow, CurrentTime); - if (iReturn == BadAtom || iReturn == BadWindow || - XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow) - { - ErrorF ("winClipboardProc - Could not set PRIMARY owner\n"); - pthread_exit (NULL); - } - - /* CLIPBOARD */ - iReturn = XSetSelectionOwner (pDisplay, atomClipboard, - iWindow, CurrentTime); - if (iReturn == BadAtom || iReturn == BadWindow || - XGetSelectionOwner (pDisplay, atomClipboard) != iWindow) - { - ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n"); - pthread_exit (NULL); - } - } - - /* Pre-flush X events */ - /* - * NOTE: Apparently you'll freeze if you don't do this, - * because there may be events in local data structures - * already. - */ - winClipboardFlushXEvents (hwnd, - iWindow, - pDisplay, - fUseUnicode); - - /* Pre-flush Windows messages */ - if (!winClipboardFlushWindowsMessageQueue (hwnd)) - return 0; - - /* Signal that the clipboard client has started */ - g_fClipboardStarted = TRUE; - - /* Loop for X events */ - while (1) - { - /* Setup the file descriptor set */ - /* - * NOTE: You have to do this before every call to select - * because select modifies the mask to indicate - * which descriptors are ready. - */ - FD_ZERO (&fdsRead); - FD_SET (iConnectionNumber, &fdsRead); -#ifdef HAS_DEVWINDOWS - FD_SET (fdMessageQueue, &fdsRead); -#else - tvTimeout.tv_sec = 0; - tvTimeout.tv_usec = 100; -#endif - - /* Wait for a Windows event or an X event */ - iReturn = select (iMaxDescriptor, /* Highest fds number */ - &fdsRead, /* Read mask */ - NULL, /* No write mask */ - NULL, /* No exception mask */ -#ifdef HAS_DEVWINDOWS - NULL /* No timeout */ -#else - &tvTimeout /* Set timeout */ -#endif - ); - -#ifndef HAS_WINSOCK - iSelectError = errno; -#else - iSelectError = WSAGetLastError(); -#endif - - if (iReturn < 0) - { -#ifndef HAS_WINSOCK - if (iSelectError == EINTR) -#else - if (iSelectError == WSAEINTR) -#endif - continue; - - ErrorF ("winClipboardProc - Call to select () failed: %d. " - "Bailing.\n", iReturn); - break; - } - - /* Branch on which descriptor became active */ - if (FD_ISSET (iConnectionNumber, &fdsRead)) - { - /* Process X events */ - /* Exit when we see that server is shutting down */ - iReturn = winClipboardFlushXEvents (hwnd, - iWindow, - pDisplay, - fUseUnicode); - if (WIN_XEVENTS_SHUTDOWN == iReturn) - { - ErrorF ("winClipboardProc - winClipboardFlushXEvents " - "trapped shutdown event, exiting main loop.\n"); - break; - } - } - -#ifdef HAS_DEVWINDOWS - /* Check for Windows event ready */ - if (FD_ISSET (fdMessageQueue, &fdsRead)) -#else - if (1) -#endif - { - /* Process Windows messages */ - if (!winClipboardFlushWindowsMessageQueue (hwnd)) - { - ErrorF ("winClipboardProc - " - "winClipboardFlushWindowsMessageQueue trapped " - "WM_QUIT message, exiting main loop.\n"); - break; - } - } - } - - /* Close our X window */ - if (pDisplay && iWindow) - { - iReturn = XDestroyWindow (pDisplay, iWindow); - if (iReturn == BadWindow) - ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n"); - else - ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n"); - } - - -#ifdef HAS_DEVWINDOWS - /* Close our Win32 message handle */ - if (fdMessageQueue) - close (fdMessageQueue); -#endif - -#if 0 - /* - * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26. The - * XSync and XSelectInput calls did not help. - */ - - /* Discard any remaining events */ - XSync (pDisplay, TRUE); - - /* Select event types to watch */ - XSelectInput (pDisplay, - DefaultRootWindow (pDisplay), - None); - - /* Close our X display */ - if (pDisplay) - { - XCloseDisplay (pDisplay); - } -#endif - - g_iClipboardWindow = None; - g_pClipboardDisplay = NULL; - g_hwndClipboard = NULL; - - return NULL; -} - - -/* - * winClipboardErrorHandler - Our application specific error handler - */ - -static int -winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr) -{ - char pszErrorMsg[100]; - - XGetErrorText (pDisplay, - pErr->error_code, - pszErrorMsg, - sizeof (pszErrorMsg)); - ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n" - "\tSerial: %d, Request Code: %d, Minor Code: %d\n", - pszErrorMsg, - pErr->serial, - pErr->request_code, - pErr->minor_code); - return 0; -} - - -/* - * winClipboardIOErrorHandler - Our application specific IO error handler - */ - -static int -winClipboardIOErrorHandler (Display *pDisplay) -{ - ErrorF ("\nwinClipboardIOErrorHandler!\n\n"); - - /* Restart at the main entry point */ - longjmp (g_jmpEntry, WIN_JMP_ERROR_IO); - - return 0; -} +/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *Copyright (C) Colin Harrison 2005-2008
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of 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: Harold L Hunt II
+ * Colin Harrison
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <sys/types.h>
+#include "winclipboard.h"
+#ifdef __CYGWIN__
+#include <errno.h>
+#endif
+#include "X11/Xauth.h"
+#include "misc.h"
+#include "winmsg.h"
+
+#ifdef _MSC_VER
+#define snprintf _snprintf
+#endif
+
+/*
+ * Constants
+ */
+
+#define AUTH_NAME "MIT-MAGIC-COOKIE-1"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool g_fUnicodeClipboard;
+extern unsigned long serverGeneration;
+#if defined(XCSECURITY)
+extern unsigned int g_uiAuthDataLen;
+extern char *g_pAuthData;
+#endif
+extern Bool g_fClipboardLaunched;
+extern Bool g_fClipboardStarted;
+extern HWND g_hwndClipboard;
+extern void *g_pClipboardDisplay;
+extern Window g_iClipboardWindow;
+
+
+/*
+ * Global variables
+ */
+
+static jmp_buf g_jmpEntry;
+Bool g_fUnicodeSupport = FALSE;
+Bool g_fUseUnicode = FALSE;
+
+
+/*
+ * Local function prototypes
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr);
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay);
+
+
+/*
+ * Main thread function
+ */
+
+void *
+winClipboardProc (void *pvNotUsed)
+{
+ Atom atomClipboard, atomClipboardManager;
+ int iReturn;
+ HWND hwnd = NULL;
+ int iConnectionNumber = 0;
+#ifdef HAS_DEVWINDOWS
+ int fdMessageQueue = 0;
+#else
+ struct timeval tvTimeout;
+#endif
+ fd_set fdsRead;
+ int iMaxDescriptor;
+ Display *pDisplay = NULL;
+ Window iWindow = None;
+ int iRetries;
+ Bool fUseUnicode;
+ char szDisplay[512];
+ int iSelectError;
+
+ ErrorF ("winClipboardProc - Hello\n");
+
+ /* Do we have Unicode support? */
+ g_fUnicodeSupport = winClipboardDetectUnicodeSupport ();
+
+ /* Do we use Unicode clipboard? */
+ fUseUnicode = g_fUnicodeClipboard && g_fUnicodeSupport;
+
+ /* Save the Unicode support flag in a global */
+ g_fUseUnicode = fUseUnicode;
+
+ /* See if X supports the current locale */
+ if (XSupportsLocale () == False)
+ {
+ ErrorF ("winClipboardProc - Locale not supported by X. Exiting.\n");
+ goto thread_errorexit;
+ }
+
+ /* Create Windows messaging window */
+ hwnd = winClipboardCreateMessagingWindow ();
+
+ /* Save copy of HWND in screen privates */
+ g_hwndClipboard = hwnd;
+
+ /* Set jump point for Error exits */
+ iReturn = setjmp (g_jmpEntry);
+
+ /* Check if we should continue operations */
+ if (iReturn != WIN_JMP_ERROR_IO
+ && iReturn != WIN_JMP_OKAY)
+ {
+ /* setjmp returned an unknown value, exit */
+ ErrorF ("winClipboardProc - setjmp returned: %d exiting\n",
+ iReturn);
+ goto thread_errorexit;
+ }
+ else if (iReturn == WIN_JMP_ERROR_IO)
+ {
+ /* TODO: Cleanup the Win32 window and free any allocated memory */
+ ErrorF ("winClipboardProc - setjmp returned for IO Error Handler.\n");
+ //goto thread_errorexit;
+ }
+
+#if defined(XCSECURITY)
+ /* Use our generated cookie for authentication */
+ XSetAuthorization (AUTH_NAME,
+ strlen (AUTH_NAME),
+ g_pAuthData,
+ g_uiAuthDataLen);
+#endif
+
+ /* Set error handler */
+ XSetErrorHandler (winClipboardErrorHandler);
+ XSetIOErrorHandler (winClipboardIOErrorHandler);
+
+ /* Initialize retry count */
+ iRetries = 0;
+
+ /* Setup the display connection string x */
+ /*
+ * NOTE: Always connect to screen 0 since we require that screen
+ * numbers start at 0 and increase without gaps. We only need
+ * to connect to one screen on the display to get events
+ * for all screens on the display. That is why there is only
+ * one clipboard client thread.
+ */
+ snprintf (szDisplay,
+ 512,
+ "127.0.0.1:%s.0",
+ display);
+
+ /* Print the display connection string */
+ ErrorF ("winClipboardProc - DISPLAY=%s\n", szDisplay);
+
+ /* Open the X display */
+ do
+ {
+ pDisplay = XOpenDisplay (szDisplay);
+ if (pDisplay == NULL)
+ {
+ ErrorF ("winClipboardProc - Could not open display, "
+ "try: %d, sleeping: %d\n",
+ iRetries + 1, WIN_CONNECT_DELAY);
+ ++iRetries;
+ sleep (WIN_CONNECT_DELAY);
+ continue;
+ }
+ else
+ break;
+ }
+ while (pDisplay == NULL && iRetries < WIN_CONNECT_RETRIES);
+
+ /* Make sure that the display opened */
+ if (pDisplay == NULL)
+ {
+ ErrorF ("winClipboardProc - Failed opening the display, giving up\n");
+ goto thread_errorexit;
+ }
+
+ /* Save the display in the screen privates */
+ g_pClipboardDisplay = pDisplay;
+
+ ErrorF ("winClipboardProc - XOpenDisplay () returned and "
+ "successfully opened the display.\n");
+
+ /* Get our connection number */
+ iConnectionNumber = ConnectionNumber (pDisplay);
+
+ winDebug("Clipboard is using socket %d\n",iConnectionNumber);
+
+#ifdef HAS_DEVWINDOWS
+ /* Open a file descriptor for the windows message queue */
+ fdMessageQueue = open (WIN_MSG_QUEUE_FNAME, _O_RDONLY);
+ if (fdMessageQueue == -1)
+ {
+ ErrorF ("winClipboardProc - Failed opening %s\n", WIN_MSG_QUEUE_FNAME);
+ goto thread_errorexit;
+ }
+
+ /* Find max of our file descriptors */
+ iMaxDescriptor = max (fdMessageQueue, iConnectionNumber) + 1;
+#else
+ iMaxDescriptor = iConnectionNumber + 1;
+#endif
+
+ /* Create atoms */
+ atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
+ atomClipboardManager = XInternAtom (pDisplay, "CLIPBOARD_MANAGER", False);
+ XInternAtom (pDisplay, WIN_LOCAL_PROPERTY, False);
+ XInternAtom (pDisplay, "UTF8_STRING", False);
+ XInternAtom (pDisplay, "COMPOUND_TEXT", False);
+ XInternAtom (pDisplay, "TARGETS", False);
+
+ /* Create a messaging window */
+ iWindow = XCreateSimpleWindow (pDisplay,
+ DefaultRootWindow (pDisplay),
+ 1, 1,
+ 500, 500,
+ 0,
+ BlackPixel (pDisplay, 0),
+ BlackPixel (pDisplay, 0));
+ if (iWindow == 0)
+ {
+ ErrorF ("winClipboardProc - Could not create an X window.\n");
+ goto thread_errorexit;
+ }
+
+ /* Select event types to watch */
+ if (XSelectInput (pDisplay,
+ iWindow,
+ PropertyChangeMask) == BadWindow)
+ ErrorF ("winClipboardProc - XSelectInput generated BadWindow "
+ "on messaging window\n");
+
+ /* Save the window in the screen privates */
+ g_iClipboardWindow = iWindow;
+
+ /* Assert ownership of selections if Win32 clipboard is owned */
+ if (NULL != GetClipboardOwner ())
+ {
+ /* PRIMARY */
+ winDebug("winClipboardProc - asserted ownership.\n");
+ iReturn = XSetSelectionOwner (pDisplay, XA_PRIMARY,
+ iWindow, CurrentTime);
+ if (iReturn == BadAtom || iReturn == BadWindow /*||
+ XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow*/)
+ {
+ ErrorF ("winClipboardProc - Could not set PRIMARY owner\n");
+ goto thread_errorexit;
+ }
+
+ /* CLIPBOARD */
+ iReturn = XSetSelectionOwner (pDisplay, atomClipboard,
+ iWindow, CurrentTime);
+ if (iReturn == BadAtom || iReturn == BadWindow /*||
+ XGetSelectionOwner (pDisplay, atomClipboard) != iWindow*/)
+ {
+ ErrorF ("winClipboardProc - Could not set CLIPBOARD owner\n");
+ goto thread_errorexit;
+ }
+ }
+ /* Pre-flush X events */
+ /*
+ * NOTE: Apparently you'll freeze if you don't do this,
+ * because there may be events in local data structures
+ * already.
+ */
+ /*winClipboardFlushXEvents (hwnd,
+ iWindow,
+ pDisplay,
+ fUseUnicode);
+ */
+ /* Pre-flush Windows messages */
+ winDebug ("Start flushing \n");
+ if (!winClipboardFlushWindowsMessageQueue (hwnd))
+ {
+ ErrorF ("winClipboardFlushWindowsMessageQueue - returned 0\n");
+ goto thread_errorexit;
+ }
+
+ ErrorF ("winClipboardProc - Started\n");
+ /* Signal that the clipboard client has started */
+ g_fClipboardStarted = TRUE;
+
+ /* Loop for X events */
+ while (1)
+ {
+ /* Setup the file descriptor set */
+ /*
+ * NOTE: You have to do this before every call to select
+ * because select modifies the mask to indicate
+ * which descriptors are ready.
+ */
+ FD_ZERO (&fdsRead);
+ FD_SET (iConnectionNumber, &fdsRead);
+#ifdef HAS_DEVWINDOWS
+ FD_SET (fdMessageQueue, &fdsRead);
+#else
+ tvTimeout.tv_sec = 0;
+ tvTimeout.tv_usec = 100;
+#endif
+
+ /* Wait for a Windows event or an X event */
+ iReturn = select (iMaxDescriptor, /* Highest fds number */
+ &fdsRead, /* Read mask */
+ NULL, /* No write mask */
+ NULL, /* No exception mask */
+#ifdef HAS_DEVWINDOWS
+ NULL /* No timeout */
+#else
+ &tvTimeout /* Set timeout */
+#endif
+ );
+
+#ifndef HAS_WINSOCK
+ iSelectError = errno;
+#else
+ iSelectError = WSAGetLastError();
+#endif
+
+ if (iReturn < 0)
+ {
+#ifndef HAS_WINSOCK
+ if (iSelectError == EINTR)
+#else
+ if (iSelectError == WSAEINTR)
+#endif
+ continue;
+
+ ErrorF ("winClipboardProc - Call to select () failed: %d. "
+ "Bailing.\n", iReturn);
+ break;
+ }
+
+ /* Branch on which descriptor became active */
+// if (FD_ISSET (iConnectionNumber, &fdsRead))
+// { Also do it when no read since winClipboardFlushXEvents
+// is sending the output.
+ /* Process X events */
+ /* Exit when we see that server is shutting down */
+ iReturn = winClipboardFlushXEvents (hwnd,
+ iWindow,
+ pDisplay,
+ fUseUnicode,
+ FALSE
+ );
+ if (WIN_XEVENTS_SHUTDOWN == iReturn)
+ {
+ ErrorF ("winClipboardProc - winClipboardFlushXEvents "
+ "trapped shutdown event, exiting main loop.\n");
+ break;
+ }
+// }
+
+#ifdef HAS_DEVWINDOWS
+ /* Check for Windows event ready */
+ if (FD_ISSET (fdMessageQueue, &fdsRead))
+#else
+ if (1)
+#endif
+ {
+ /* Process Windows messages */
+ if (!winClipboardFlushWindowsMessageQueue (hwnd))
+ {
+ ErrorF ("winClipboardProc - "
+ "winClipboardFlushWindowsMessageQueue trapped "
+ "WM_QUIT message, exiting main loop.\n");
+ break;
+ }
+ }
+ }
+
+ /* Close our X window */
+ if (pDisplay && iWindow)
+ {
+ iReturn = XDestroyWindow (pDisplay, iWindow);
+ if (iReturn == BadWindow)
+ ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
+ else
+ ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
+ }
+
+
+#ifdef HAS_DEVWINDOWS
+ /* Close our Win32 message handle */
+ if (fdMessageQueue)
+ close (fdMessageQueue);
+#endif
+
+#if 0
+ /*
+ * FIXME: XCloseDisplay hangs if we call it, as of 2004/03/26. The
+ * XSync and XSelectInput calls did not help.
+ */
+
+ /* Discard any remaining events */
+ XSync (pDisplay, TRUE);
+
+ /* Select event types to watch */
+ XSelectInput (pDisplay,
+ DefaultRootWindow (pDisplay),
+ None);
+
+ /* Close our X display */
+ if (pDisplay)
+ {
+ XCloseDisplay (pDisplay);
+ }
+#endif
+
+ g_iClipboardWindow = None;
+ g_pClipboardDisplay = NULL;
+ g_fClipboardLaunched = FALSE;
+ g_fClipboardStarted = FALSE;
+
+ return NULL;
+thread_errorexit:
+ if (g_pClipboardDisplay && g_iClipboardWindow)
+ {
+ iReturn = XDestroyWindow (g_pClipboardDisplay, g_iClipboardWindow);
+ if (iReturn == BadWindow)
+ ErrorF ("winClipboardProc - XDestroyWindow returned BadWindow.\n");
+ else
+ ErrorF ("winClipboardProc - XDestroyWindow succeeded.\n");
+ }
+ g_iClipboardWindow = None;
+ g_pClipboardDisplay = NULL;
+ g_fClipboardLaunched = FALSE;
+ g_fClipboardStarted = FALSE;
+ //pthread_exit (NULL);
+ ErrorF ("Clipboard thread died.\n");
+ return NULL;
+}
+
+
+/*
+ * winClipboardErrorHandler - Our application specific error handler
+ */
+
+static int
+winClipboardErrorHandler (Display *pDisplay, XErrorEvent *pErr)
+{
+ char pszErrorMsg[100];
+
+ XGetErrorText (pDisplay,
+ pErr->error_code,
+ pszErrorMsg,
+ sizeof (pszErrorMsg));
+ ErrorF ("winClipboardErrorHandler - ERROR: \n\t%s\n"
+ "\tSerial: %d, Request Code: %d, Minor Code: %d\n",
+ pszErrorMsg,
+ pErr->serial,
+ pErr->request_code,
+ pErr->minor_code);
+ return 0;
+}
+
+
+/*
+ * winClipboardIOErrorHandler - Our application specific IO error handler
+ */
+
+static int
+winClipboardIOErrorHandler (Display *pDisplay)
+{
+ ErrorF ("\nwinClipboardIOErrorHandler!\n\n");
+
+ /* Restart at the main entry point */
+ longjmp (g_jmpEntry, WIN_JMP_ERROR_IO);
+
+ return 0;
+}
diff --git a/xorg-server/hw/xwin/winclipboardunicode.c b/xorg-server/hw/xwin/winclipboardunicode.c index ba86915a4..531f5703a 100644 --- a/xorg-server/hw/xwin/winclipboardunicode.c +++ b/xorg-server/hw/xwin/winclipboardunicode.c @@ -43,25 +43,43 @@ Bool winClipboardDetectUnicodeSupport (void) { Bool fReturn = FALSE; - OSVERSIONINFO osvi = {0}; + OSVERSIONINFOEX osvi = {0}; /* Get operating system version information */ osvi.dwOSVersionInfoSize = sizeof (osvi); - GetVersionEx (&osvi); + GetVersionEx ((LPOSVERSIONINFO)&osvi); /* Branch on platform ID */ switch (osvi.dwPlatformId) { case VER_PLATFORM_WIN32_NT: - /* Unicode supported on NT only */ - ErrorF ("DetectUnicodeSupport - Windows NT/2000/XP\n"); - fReturn = TRUE; + if (osvi.dwMajorVersion >= 6) + { + if (osvi.wProductType == VER_NT_WORKSTATION) + ErrorF ("OS: Windows Vista\n"); + else + ErrorF ("OS: Windows Server 2008\n"); + fReturn = TRUE; + } + else if (osvi.dwMajorVersion == 5) + { + if (osvi.dwMinorVersion == 2) + { + ErrorF ("OS: Windows 2003\n"); + fReturn = TRUE; + } + else if (osvi.dwMinorVersion == 1) + { + ErrorF ("OS: Windows XP\n"); + fReturn = TRUE; + } + else if (osvi.dwMinorVersion == 0) ErrorF ("OS: Windows 2000\n"); + } + else if (osvi.dwMajorVersion <= 4) ErrorF ("OS: Windows NT\n"); break; case VER_PLATFORM_WIN32_WINDOWS: - /* Unicode is not supported on non-NT */ - ErrorF ("DetectUnicodeSupport - Windows 95/98/Me\n"); - fReturn = FALSE; + ErrorF ("OS: Windows 95/98/Me\n"); break; } diff --git a/xorg-server/hw/xwin/winclipboardwndproc.c b/xorg-server/hw/xwin/winclipboardwndproc.c index 292ca872b..ea09f0e3a 100644 --- a/xorg-server/hw/xwin/winclipboardwndproc.c +++ b/xorg-server/hw/xwin/winclipboardwndproc.c @@ -1,627 +1,548 @@ -/* - *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved. - *Copyright (C) Colin Harrison 2005-2008 - * - *Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - *"Software"), to deal in the Software without restriction, including - *without limitation the rights to use, copy, modify, merge, publish, - *distribute, sublicense, and/or sell copies of the Software, and to - *permit persons to whom the Software is furnished to do so, subject to - *the following conditions: - * - *The above copyright notice and this permission notice shall be - *included in all copies or substantial portions of the Software. - * - *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR - *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - *Except as contained in this notice, the name of 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: Harold L Hunt II - * Colin Harrison - */ - -#ifdef HAVE_XWIN_CONFIG_H -#include <xwin-config.h> -#endif -#include <sys/types.h> -#include <sys/time.h> -#include "winclipboard.h" -#include "misc.h" - -/* - * Constants - */ - -#define WIN_CLIPBOARD_PROP "cyg_clipboard_prop" -#define WIN_POLL_TIMEOUT 1 - - -/* - * References to external symbols - */ - -extern Bool g_fUseUnicode; -extern Bool g_fUnicodeSupport; -extern void *g_pClipboardDisplay; -extern Window g_iClipboardWindow; -extern Atom g_atomLastOwnedSelection; - -/* BPS - g_hwndClipboard needed for X app->Windows paste fix */ -extern HWND g_hwndClipboard; - -/* - * Local function prototypes - */ - -static int -winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay, - Bool fUseUnicode, int iTimeoutSec); - - -/* - * Process X events up to specified timeout - */ - -static int -winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay, - Bool fUseUnicode, int iTimeoutSec) -{ - int iConnNumber; - struct timeval tv; - int iReturn; - DWORD dwStopTime = (GetTickCount () / 1000) + iTimeoutSec; - - /* We need to ensure that all pending events are processed */ - XSync (pDisplay, FALSE); - - /* Get our connection number */ - iConnNumber = ConnectionNumber (pDisplay); - - /* Loop for X events */ - while (1) - { - fd_set fdsRead; - - /* Setup the file descriptor set */ - FD_ZERO (&fdsRead); - FD_SET (iConnNumber, &fdsRead); - - /* Adjust timeout */ - tv.tv_sec = dwStopTime - (GetTickCount () / 1000); - tv.tv_usec = 0; - - /* Break out if no time left */ - if (tv.tv_sec < 0) - return WIN_XEVENTS_SUCCESS; - - /* Wait for a Windows event or an X event */ - iReturn = select (iConnNumber + 1,/* Highest fds number */ - &fdsRead, /* Read mask */ - NULL, /* No write mask */ - NULL, /* No exception mask */ - &tv); /* No timeout */ - if (iReturn <= 0) - { - ErrorF ("winProcessXEventsTimeout - Call to select () failed: %d. " - "Bailing.\n", iReturn); - break; - } - - /* Branch on which descriptor became active */ - if (FD_ISSET (iConnNumber, &fdsRead)) - { - /* Process X events */ - /* Exit when we see that server is shutting down */ - iReturn = winClipboardFlushXEvents (hwnd, - iWindow, - pDisplay, - fUseUnicode); - if (WIN_XEVENTS_NOTIFY == iReturn - || WIN_XEVENTS_CONVERT == iReturn) - { - /* Bail out if convert or notify processed */ - return iReturn; - } - } - } - - return WIN_XEVENTS_SUCCESS; -} - - -/* - * Process a given Windows message - */ - -/* BPS - Define our own message, which we'll post to ourselves to facilitate - * resetting the delayed rendering mechanism after each paste from X app to - * Windows app. TODO - Perhaps move to win.h with the other WM_USER messages. - */ -#define WM_USER_PASTE_COMPLETE (WM_USER + 1003) - -LRESULT CALLBACK -winClipboardWindowProc (HWND hwnd, UINT message, - WPARAM wParam, LPARAM lParam) -{ - static HWND s_hwndNextViewer; - static Bool s_fCBCInitialized; - - /* Branch on message type */ - switch (message) - { - case WM_DESTROY: - { - winDebug ("winClipboardWindowProc - WM_DESTROY\n"); - - /* Remove ourselves from the clipboard chain */ - ChangeClipboardChain (hwnd, s_hwndNextViewer); - - s_hwndNextViewer = NULL; - - PostQuitMessage (0); - } - return 0; - - - case WM_CREATE: - { - HWND first, next; - DWORD error_code = 0; - winDebug ("winClipboardWindowProc - WM_CREATE\n"); - - first = GetClipboardViewer(); /* Get handle to first viewer in chain. */ - if (first == hwnd) return 0; /* Make sure it's not us! */ - /* Add ourselves to the clipboard viewer chain */ - next = SetClipboardViewer (hwnd); - error_code = GetLastError(); - if (SUCCEEDED(error_code) && (next == first)) /* SetClipboardViewer must have succeeded, and the handle */ - s_hwndNextViewer = next; /* it returned must have been the first window in the chain */ - else - s_fCBCInitialized = FALSE; - } - return 0; - - - case WM_CHANGECBCHAIN: - { - winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) " - "lParam(%x) s_hwndNextViewer(%x)\n", - wParam, lParam, s_hwndNextViewer); - - if ((HWND) wParam == s_hwndNextViewer) - { - s_hwndNextViewer = (HWND) lParam; - if (s_hwndNextViewer == hwnd) - { - s_hwndNextViewer = NULL; - winErrorFVerb (1, "winClipboardWindowProc - WM_CHANGECBCHAIN: " - "attempted to set next window to ourselves."); - } - } - else if (s_hwndNextViewer) - SendMessage (s_hwndNextViewer, message, - wParam, lParam); - - } - winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n"); - return 0; - - case WM_WM_REINIT: - { - /* Ensure that we're in the clipboard chain. Some apps, - * WinXP's remote desktop for one, don't play nice with the - * chain. This message is called whenever we receive a - * WM_ACTIVATEAPP message to ensure that we continue to - * receive clipboard messages. - * - * It might be possible to detect if we're still in the chain - * by calling SendMessage (GetClipboardViewer(), - * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the - * WM_DRAWCLIPBOARD message. That, however, might be more - * expensive than just putting ourselves back into the chain. - */ - - HWND first, next; - DWORD error_code = 0; - winDebug ("winClipboardWindowProc - WM_WM_REINIT: Enter\n"); - - first = GetClipboardViewer(); /* Get handle to first viewer in chain. */ - if (first == hwnd) return 0; /* Make sure it's not us! */ - winDebug (" WM_WM_REINIT: Replacing us(%x) with %x at head " - "of chain\n", hwnd, s_hwndNextViewer); - s_fCBCInitialized = FALSE; - ChangeClipboardChain (hwnd, s_hwndNextViewer); - s_hwndNextViewer = NULL; - s_fCBCInitialized = FALSE; - winDebug (" WM_WM_REINIT: Putting us back at head of chain.\n"); - first = GetClipboardViewer(); /* Get handle to first viewer in chain. */ - if (first == hwnd) return 0; /* Make sure it's not us! */ - next = SetClipboardViewer (hwnd); - error_code = GetLastError(); - if (SUCCEEDED(error_code) && (next == first)) /* SetClipboardViewer must have succeeded, and the handle */ - s_hwndNextViewer = next; /* it returned must have been the first window in the chain */ - else - s_fCBCInitialized = FALSE; - } - winDebug ("winClipboardWindowProc - WM_WM_REINIT: Exit\n"); - return 0; - - - case WM_DRAWCLIPBOARD: - { - static Atom atomClipboard; - static int generation; - static Bool s_fProcessingDrawClipboard = FALSE; - Display *pDisplay = g_pClipboardDisplay; - Window iWindow = g_iClipboardWindow; - int iReturn; - - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Enter\n"); - - if (generation != serverGeneration) - { - generation = serverGeneration; - atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False); - } - - /* - * We've occasionally seen a loop in the clipboard chain. - * Try and fix it on the first hint of recursion. - */ - if (! s_fProcessingDrawClipboard) - { - s_fProcessingDrawClipboard = TRUE; - } - else - { - /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */ - s_fCBCInitialized = FALSE; - ChangeClipboardChain (hwnd, s_hwndNextViewer); - winFixClipboardChain(); - winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Nested calls detected. Re-initing.\n"); - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n"); - s_fProcessingDrawClipboard = FALSE; - return 0; - } - - /* Bail on first message */ - if (!s_fCBCInitialized) - { - s_fCBCInitialized = TRUE; - s_fProcessingDrawClipboard = FALSE; - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n"); - return 0; - } - - /* - * NOTE: We cannot bail out when NULL == GetClipboardOwner () - * because some applications deal with the clipboard in a manner - * that causes the clipboard owner to be NULL when they are in - * fact taking ownership. One example of this is the Win32 - * native compile of emacs. - */ - - /* Bail when we still own the clipboard */ - if (hwnd == GetClipboardOwner ()) - { - - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "We own the clipboard, returning.\n"); - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n"); - s_fProcessingDrawClipboard = FALSE; - if (s_hwndNextViewer) - SendMessage (s_hwndNextViewer, message, wParam, lParam); - return 0; - } - - /* - * Do not take ownership of the X11 selections when something - * other than CF_TEXT or CF_UNICODETEXT has been copied - * into the Win32 clipboard. - */ - if (!IsClipboardFormatAvailable (CF_TEXT) - && !IsClipboardFormatAvailable (CF_UNICODETEXT)) - { - - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Clipboard does not contain CF_TEXT nor " - "CF_UNICODETEXT.\n"); - - /* - * We need to make sure that the X Server has processed - * previous XSetSelectionOwner messages. - */ - XSync (pDisplay, FALSE); - - /* Release PRIMARY selection if owned */ - iReturn = XGetSelectionOwner (pDisplay, XA_PRIMARY); - if (iReturn == g_iClipboardWindow) - { - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "PRIMARY selection is owned by us.\n"); - XSetSelectionOwner (pDisplay, - XA_PRIMARY, - None, - CurrentTime); - } - else if (BadWindow == iReturn || BadAtom == iReturn) - winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "XGetSelection failed for PRIMARY: %d\n", iReturn); - - /* Release CLIPBOARD selection if owned */ - iReturn = XGetSelectionOwner (pDisplay, - atomClipboard); - if (iReturn == g_iClipboardWindow) - { - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "CLIPBOARD selection is owned by us.\n"); - XSetSelectionOwner (pDisplay, - atomClipboard, - None, - CurrentTime); - } - else if (BadWindow == iReturn || BadAtom == iReturn) - winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "XGetSelection failed for CLIPBOARD: %d\n", iReturn); - - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n"); - s_fProcessingDrawClipboard = FALSE; - if (s_hwndNextViewer) - SendMessage (s_hwndNextViewer, message, wParam, lParam); - return 0; - } - - /* Reassert ownership of PRIMARY */ - iReturn = XSetSelectionOwner (pDisplay, - XA_PRIMARY, - iWindow, - CurrentTime); - if (iReturn == BadAtom || iReturn == BadWindow || - XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Could not reassert ownership of PRIMARY\n"); - } - else - { - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Reasserted ownership of PRIMARY\n"); - } - - /* Reassert ownership of the CLIPBOARD */ - iReturn = XSetSelectionOwner (pDisplay, - atomClipboard, - iWindow, - CurrentTime); - - if (iReturn == BadAtom || iReturn == BadWindow || - XGetSelectionOwner (pDisplay, atomClipboard) != iWindow) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Could not reassert ownership of CLIPBOARD\n"); - } - else - { - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - " - "Reasserted ownership of CLIPBOARD\n"); - } - - /* Flush the pending SetSelectionOwner event now */ - XFlush (pDisplay); - - s_fProcessingDrawClipboard = FALSE; - } - winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n"); - /* Pass the message on the next window in the clipboard viewer chain */ - if (s_hwndNextViewer) - SendMessage (s_hwndNextViewer, message, wParam, lParam); - return 0; - - - case WM_DESTROYCLIPBOARD: - /* - * NOTE: Intentionally do nothing. - * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD - * above. We only process this message to conform to the specs - * for delayed clipboard rendering in Win32. You might think - * that we need to release ownership of the X11 selections, but - * we do not, because a WM_DRAWCLIPBOARD message will closely - * follow this message and reassert ownership of the X11 - * selections, handling the issue for us. - */ - return 0; - - - case WM_RENDERFORMAT: - case WM_RENDERALLFORMATS: - { - int iReturn; - Display *pDisplay = g_pClipboardDisplay; - Window iWindow = g_iClipboardWindow; - Bool fConvertToUnicode; - - winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n"); - - /* Flag whether to convert to Unicode or not */ - if (message == WM_RENDERALLFORMATS) - fConvertToUnicode = FALSE; - else - fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam); - - /* Request the selection contents */ - iReturn = XConvertSelection (pDisplay, - g_atomLastOwnedSelection, - XInternAtom (pDisplay, - "COMPOUND_TEXT", False), - XInternAtom (pDisplay, - "CYGX_CUT_BUFFER", False), - iWindow, - CurrentTime); - if (iReturn == BadAtom || iReturn == BadWindow) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMAT - " - "XConvertSelection () failed\n"); - break; - } - - /* Special handling for WM_RENDERALLFORMATS */ - if (message == WM_RENDERALLFORMATS) - { - /* We must open and empty the clipboard */ - - /* Close clipboard if we have it open already */ - if (GetOpenClipboardWindow () == hwnd) - { - CloseClipboard (); - } - - if (!OpenClipboard (hwnd)) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - " - "OpenClipboard () failed: %08x\n", - GetLastError ()); - break; - } - - if (!EmptyClipboard ()) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - " - "EmptyClipboard () failed: %08x\n", - GetLastError ()); - break; - } - } - - /* Process the SelectionNotify event */ - iReturn = winProcessXEventsTimeout (hwnd, - iWindow, - pDisplay, - fConvertToUnicode, - WIN_POLL_TIMEOUT); - if (WIN_XEVENTS_CONVERT == iReturn) - { - /* - * The selection was offered for conversion first, so we have - * to process a second SelectionNotify event to get the actual - * data in the selection. - */ - iReturn = winProcessXEventsTimeout (hwnd, - iWindow, - pDisplay, - fConvertToUnicode, - WIN_POLL_TIMEOUT); - } - - /* - * The last of the up-to two calls to winProcessXEventsTimeout - * from above had better have seen a notify event, or else we - * are dealing with a buggy or old X11 app. In these cases we - * have to paste some fake data to the Win32 clipboard to - * satisfy the requirement that we write something to it. - */ - if (WIN_XEVENTS_NOTIFY != iReturn) - { - /* Paste no data, to satisfy required call to SetClipboardData */ - if (g_fUnicodeSupport) - SetClipboardData (CF_UNICODETEXT, NULL); - SetClipboardData (CF_TEXT, NULL); - } - - /* BPS - Post ourselves a user message whose handler will reset the - * delayed rendering mechanism after the paste is complete. This is - * necessary because calling SetClipboardData() with a NULL argument - * here will cause the data we just put on the clipboard to be lost! - */ - PostMessage(g_hwndClipboard, WM_USER_PASTE_COMPLETE, 0, 0); - - /* Special handling for WM_RENDERALLFORMATS */ - if (message == WM_RENDERALLFORMATS) - { - /* We must close the clipboard */ - - if (!CloseClipboard ()) - { - winErrorFVerb (1, "winClipboardWindowProc - WM_RENDERALLFORMATS - " - "CloseClipboard () failed: %08x\n", - GetLastError ()); - break; - } - } - - winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n"); - return 0; - } - /* BPS - This WM_USER message is posted by us. It gives us the opportunity - * to reset the delayed rendering mechanism after each and every paste - * from an X app to a Windows app. Without such a mechanism, subsequent - * changes of selection in the X app owning the selection are not - * reflected in pastes into Windows apps, since Windows won't send us the - * WM_RENDERFORMAT message unless someone has set changed data (or NULL) - * on the clipboard. */ - case WM_USER_PASTE_COMPLETE: - { - if (hwnd != GetClipboardOwner ()) - /* In case we've lost the selection since posting the message */ - return 0; - winDebug ("winClipboardWindowProc - WM_USER_PASTE_COMPLETE\n"); - - /* Set up for another delayed rendering callback */ - OpenClipboard (g_hwndClipboard); - - /* Take ownership of the Windows clipboard */ - EmptyClipboard (); - - /* Advertise Unicode if we support it */ - if (g_fUnicodeSupport) - SetClipboardData (CF_UNICODETEXT, NULL); - - /* Always advertise regular text */ - SetClipboardData (CF_TEXT, NULL); - - /* Release the clipboard */ - CloseClipboard (); - } - return 0; - } - - /* Let Windows perform default processing for unhandled messages */ - return DefWindowProc (hwnd, message, wParam, lParam); -} - - -/* - * Process any pending Windows messages - */ - -BOOL -winClipboardFlushWindowsMessageQueue (HWND hwnd) -{ - MSG msg; - - /* Flush the messaging window queue */ - /* NOTE: Do not pass the hwnd of our messaging window to PeekMessage, - * as this will filter out many non-window-specific messages that - * are sent to our thread, such as WM_QUIT. - */ - while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE)) - { - /* Dispatch the message if not WM_QUIT */ - if (msg.message == WM_QUIT) - return FALSE; - else - DispatchMessage (&msg); - } - - return TRUE; -} +/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *Copyright (C) Colin Harrison 2005-2008
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of 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: Harold L Hunt II
+ * Colin Harrison
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include <sys/types.h>
+#include <sys/time.h>
+#include "winclipboard.h"
+#include "misc.h"
+#include "winmsg.h"
+
+/*
+ * Constants
+ */
+
+#define WIN_CLIPBOARD_PROP "cyg_clipboard_prop"
+#define WIN_POLL_TIMEOUT 1
+
+/*
+ * References to external symbols
+ */
+
+extern Bool g_fUseUnicode;
+extern Bool g_fUnicodeSupport;
+extern void *g_pClipboardDisplay;
+extern Window g_iClipboardWindow;
+extern Atom g_atomLastOwnedSelection;
+extern Bool g_fClipboardStarted;
+/* BPS - g_hwndClipboard needed for X app->Windows paste fix */
+extern HWND g_hwndClipboard;
+
+/*
+ * Local function prototypes
+ */
+
+static int
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+ Bool fUseUnicode, int iTimeoutSec);
+
+
+/*
+ * Process X events up to specified timeout
+ */
+
+static int
+winProcessXEventsTimeout (HWND hwnd, int iWindow, Display *pDisplay,
+ Bool fUseUnicode, int iTimeoutSec)
+{
+ int iConnNumber;
+ struct timeval tv;
+ int iReturn;
+ DWORD dwStopTime = (GetTickCount () / 1000) + iTimeoutSec;
+
+ /* Make sure the output messages are sent before waiting on a response. */
+ iReturn = winClipboardFlushXEvents (hwnd,
+ iWindow,
+ pDisplay,
+ fUseUnicode,
+ TRUE);
+ if (WIN_XEVENTS_NOTIFY == iReturn || WIN_XEVENTS_CONVERT == iReturn)
+ {
+ /* Bail out if convert or notify processed */
+ return iReturn;
+ }
+
+ /* Get our connection number */
+ iConnNumber = ConnectionNumber (pDisplay);
+
+ /* Loop for X events */
+ while (1)
+ {
+ fd_set fdsRead;
+
+ /* Setup the file descriptor set */
+ FD_ZERO (&fdsRead);
+ FD_SET (iConnNumber, &fdsRead);
+
+ /* Adjust timeout */
+ tv.tv_sec = dwStopTime - (GetTickCount () / 1000);
+ tv.tv_usec = 0;
+
+ /* Break out if no time left */
+ if (tv.tv_sec < 0)
+ return WIN_XEVENTS_SUCCESS;
+
+ /* Wait for a Windows event or an X event */
+ iReturn = select (iConnNumber + 1,/* Highest fds number */
+ &fdsRead, /* Read mask */
+ NULL, /* No write mask */
+ NULL, /* No exception mask */
+ &tv); /* No timeout */
+ if (iReturn <= 0)
+ {
+ ErrorF ("winProcessXEventsTimeout - Call to select () failed: %d (%x). "
+ "Bailing.\n", iReturn, WSAGetLastError());
+ break;
+ }
+
+ /* Branch on which descriptor became active */
+ if (FD_ISSET (iConnNumber, &fdsRead))
+ {
+ /* Process X events */
+ /* Exit when we see that server is shutting down */
+ iReturn = winClipboardFlushXEvents (hwnd,
+ iWindow,
+ pDisplay,
+ fUseUnicode,
+ TRUE);
+ if (WIN_XEVENTS_NOTIFY == iReturn
+ || WIN_XEVENTS_CONVERT == iReturn)
+ {
+ /* Bail out if convert or notify processed */
+ return iReturn;
+ }
+ }
+ }
+
+ return WIN_XEVENTS_SUCCESS;
+}
+
+/*
+ * Process a given Windows message
+ */
+
+LRESULT CALLBACK
+winClipboardWindowProc (HWND hwnd, UINT message,
+ WPARAM wParam, LPARAM lParam)
+{
+ static HWND s_hwndNextViewer;
+
+ /* Branch on message type */
+ switch (message)
+ {
+ case WM_DESTROY:
+ {
+ winDebug ("winClipboardWindowProc - WM_DESTROY\n");
+
+ /* Remove ourselves from the clipboard chain */
+ ChangeClipboardChain (hwnd, s_hwndNextViewer);
+
+ s_hwndNextViewer = NULL;
+ g_hwndClipboard = NULL;
+ PostQuitMessage (0);
+ }
+ return 0;
+
+
+ case WM_CREATE:
+ {
+ HWND first, next;
+ DWORD error_code = 0;
+ winDebug ("winClipboardWindowProc - WM_CREATE\n");
+
+ /* Add ourselves to the clipboard viewer chain */
+ s_hwndNextViewer = SetClipboardViewer (hwnd);
+ }
+ return 0;
+
+
+ case WM_CHANGECBCHAIN:
+ {
+ winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: wParam(%x) "
+ "lParam(%x) s_hwndNextViewer(%x)\n",
+ wParam, lParam, s_hwndNextViewer);
+
+ if ((HWND) wParam == s_hwndNextViewer)
+ {
+ s_hwndNextViewer = (HWND) lParam;
+ }
+ else if (s_hwndNextViewer)
+ SendMessage (s_hwndNextViewer, message,
+ wParam, lParam);
+
+ }
+ winDebug ("winClipboardWindowProc - WM_CHANGECBCHAIN: Exit\n");
+ return 0;
+
+ case WM_WM_REINIT:
+ {
+ /* Ensure that we're in the clipboard chain. Some apps,
+ * WinXP's remote desktop for one, don't play nice with the
+ * chain. This message is called whenever we receive a
+ * WM_ACTIVATEAPP message to ensure that we continue to
+ * receive clipboard messages.
+ *
+ * It might be possible to detect if we're still in the chain
+ * by calling SendMessage (GetClipboardViewer(),
+ * WM_DRAWCLIPBOARD, 0, 0); and then seeing if we get the
+ * WM_DRAWCLIPBOARD message. That, however, might be more
+ * expensive than just putting ourselves back into the chain.
+ */
+
+ HWND first, next;
+ DWORD error_code = 0;
+ if (!g_hwndClipboard)
+ return 0;
+ winDebug ("winClipboardWindowProc - WM_WM_REINIT: Enter\n");
+
+ first = GetClipboardViewer(); /* Get handle to first viewer in chain. */
+ if (first != hwnd)
+ {
+ winDebug (" WM_WM_REINIT: Replacing us(%x) with %x at head "
+ "of chain\n", hwnd, s_hwndNextViewer);
+ ChangeClipboardChain (hwnd, s_hwndNextViewer);
+ winDebug (" WM_WM_REINIT: Putting us back at head of chain.\n");
+ s_hwndNextViewer = SetClipboardViewer (hwnd);
+ }
+ winDebug ("winClipboardWindowProc - WM_WM_REINIT: Exit\n");
+ }
+ return 0;
+
+
+ case WM_DRAWCLIPBOARD:
+ {
+ static Atom atomClipboard;
+ static int generation;
+ static Bool s_fProcessingDrawClipboard = FALSE;
+ Display *pDisplay = g_pClipboardDisplay;
+ Window iWindow = g_iClipboardWindow;
+ int iReturn;
+
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD 0x%x 0x%x 0x%x: Enter\n",hwnd,wParam,lParam);
+
+ if (!g_fClipboardStarted)
+ {
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit with no processing\n");
+ if (s_hwndNextViewer)
+ SendMessage (s_hwndNextViewer, message, wParam, lParam);
+ return 0;
+ }
+
+ if (generation != serverGeneration)
+ {
+ generation = serverGeneration;
+ atomClipboard = XInternAtom (pDisplay, "CLIPBOARD", False);
+ }
+
+ /*
+ * We've occasionally seen a loop in the clipboard chain.
+ * Try and fix it on the first hint of recursion.
+ */
+ if (! s_fProcessingDrawClipboard)
+ {
+ s_fProcessingDrawClipboard = TRUE;
+ }
+ else
+ {
+ /* Attempt to break the nesting by getting out of the chain, twice?, and then fix and bail */
+ ChangeClipboardChain (hwnd, s_hwndNextViewer);
+ winFixClipboardChain();
+ winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Nested calls detected. Re-initing.\n");
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+ s_fProcessingDrawClipboard = FALSE;
+ return 0;
+ }
+
+ /*
+ * Do not take ownership of the X11 selections when something
+ * other than CF_TEXT or CF_UNICODETEXT has been copied
+ * into the Win32 clipboard.
+ */
+ if (!IsClipboardFormatAvailable (CF_TEXT)
+ && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+ {
+
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Clipboard does not contain CF_TEXT nor "
+ "CF_UNICODETEXT.\n");
+
+ /*
+ * We need to make sure that the X Server has processed
+ * previous XSetSelectionOwner messages.
+ */
+ XSync (pDisplay, FALSE);
+
+ /* Release PRIMARY selection if owned */
+ iReturn = XGetSelectionOwner (pDisplay, XA_PRIMARY);
+ if (iReturn == g_iClipboardWindow)
+ {
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "PRIMARY selection is owned by us.\n");
+ XSetSelectionOwner (pDisplay,
+ XA_PRIMARY,
+ None,
+ CurrentTime);
+ }
+ else if (BadWindow == iReturn || BadAtom == iReturn)
+ winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "XGetSelection failed for PRIMARY: %d\n", iReturn);
+
+ /* Release CLIPBOARD selection if owned */
+ iReturn = XGetSelectionOwner (pDisplay,
+ atomClipboard);
+ if (iReturn == g_iClipboardWindow)
+ {
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "CLIPBOARD selection is owned by us.\n");
+ XSetSelectionOwner (pDisplay,
+ atomClipboard,
+ None,
+ CurrentTime);
+ }
+ else if (BadWindow == iReturn || BadAtom == iReturn)
+ winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "XGetSelection failed for CLIPBOARD: %d\n", iReturn);
+
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+ s_fProcessingDrawClipboard = FALSE;
+ if (s_hwndNextViewer)
+ SendMessage (s_hwndNextViewer, message, wParam, lParam);
+ return 0;
+ }
+ /* Only reassert ownership when we did not change the clipboard ourselves */
+ if (hwnd!=(HWND)wParam)
+ {
+ /* Reassert ownership of PRIMARY */
+ iReturn = XSetSelectionOwner (pDisplay,
+ XA_PRIMARY,
+ iWindow,
+ CurrentTime);
+ if (iReturn == BadAtom || iReturn == BadWindow ||
+ XGetSelectionOwner (pDisplay, XA_PRIMARY) != iWindow)
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Could not reassert ownership of PRIMARY\n");
+ }
+ else
+ {
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Reasserted ownership of PRIMARY\n");
+ }
+
+ /* Reassert ownership of the CLIPBOARD */
+ iReturn = XSetSelectionOwner (pDisplay,
+ atomClipboard,
+ iWindow,
+ CurrentTime);
+
+ if (iReturn == BadAtom || iReturn == BadWindow ||
+ XGetSelectionOwner (pDisplay, atomClipboard) != iWindow)
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Could not reassert ownership of CLIPBOARD\n");
+ }
+ else
+ {
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD - "
+ "Reasserted ownership of CLIPBOARD\n");
+ }
+
+ /* Flush the pending SetSelectionOwner event now */
+ XFlush (pDisplay);
+ }
+
+ s_fProcessingDrawClipboard = FALSE;
+ winDebug ("winClipboardWindowProc - WM_DRAWCLIPBOARD: Exit\n");
+ /* Pass the message on the next window in the clipboard viewer chain */
+ if (s_hwndNextViewer)
+ SendMessage (s_hwndNextViewer, message, wParam, lParam);
+ return 0;
+
+ }
+
+ case WM_DESTROYCLIPBOARD:
+ /*
+ * NOTE: Intentionally do nothing.
+ * Changes in the Win32 clipboard are handled by WM_DRAWCLIPBOARD
+ * above. We only process this message to conform to the specs
+ * for delayed clipboard rendering in Win32. You might think
+ * that we need to release ownership of the X11 selections, but
+ * we do not, because a WM_DRAWCLIPBOARD message will closely
+ * follow this message and reassert ownership of the X11
+ * selections, handling the issue for us.
+ */
+ return 0;
+
+
+ case WM_RENDERFORMAT:
+ case WM_RENDERALLFORMATS:
+ {
+ int iReturn;
+ Display *pDisplay = g_pClipboardDisplay;
+ Window iWindow = g_iClipboardWindow;
+ Bool fConvertToUnicode;
+
+ winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Hello.\n");
+
+ /* Flag whether to convert to Unicode or not */
+ if (message == WM_RENDERALLFORMATS)
+ fConvertToUnicode = FALSE;
+ else
+ fConvertToUnicode = g_fUnicodeSupport && (CF_UNICODETEXT == wParam);
+
+ /* Request the selection contents */
+ iReturn = XConvertSelection (pDisplay,
+ g_atomLastOwnedSelection,
+ XInternAtom (pDisplay,
+ "COMPOUND_TEXT", False),
+ XInternAtom (pDisplay,
+ WIN_LOCAL_PROPERTY, False),
+ iWindow,
+ CurrentTime);
+ if (iReturn == BadAtom || iReturn == BadWindow)
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMAT - "
+ "XConvertSelection () failed\n");
+ break;
+ }
+
+ /* Special handling for WM_RENDERALLFORMATS */
+ if (message == WM_RENDERALLFORMATS)
+ {
+ /* We must open and empty the clipboard */
+ if (!OpenClipboard (hwnd))
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+ "OpenClipboard () failed: %08x\n",
+ GetLastError ());
+ break;
+ }
+
+ if (!EmptyClipboard ())
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_RENDER*FORMATS - "
+ "EmptyClipboard () failed: %08x\n",
+ GetLastError ());
+ CloseClipboard ();
+ break;
+ }
+ }
+
+ /* Process the SelectionNotify event */
+ iReturn = winProcessXEventsTimeout (hwnd,
+ iWindow,
+ pDisplay,
+ fConvertToUnicode,
+ WIN_POLL_TIMEOUT);
+ if (WIN_XEVENTS_CONVERT == iReturn)
+ {
+ /*
+ * The selection was offered for conversion first, so we have
+ * to process a second SelectionNotify event to get the actual
+ * data in the selection.
+ */
+ winDebug("winClipboardWindowProc - Previous winProcessXEventsTimeout returned WIN_XEVENTS_CONVERT, calling it again\n");
+ iReturn = winProcessXEventsTimeout (hwnd,
+ iWindow,
+ pDisplay,
+ fConvertToUnicode,
+ WIN_POLL_TIMEOUT);
+ }
+
+ /*
+ * The last of the up-to two calls to winProcessXEventsTimeout
+ * from above had better have seen a notify event, or else we
+ * are dealing with a buggy or old X11 app. In these cases we
+ * have to paste some fake data to the Win32 clipboard to
+ * satisfy the requirement that we write something to it.
+ */
+ if (WIN_XEVENTS_NOTIFY != iReturn)
+ {
+ ErrorF("winClipboardWindowProc - winProcessXEventsTimeout should have returned WIN_XEVENTS_NOTIFY was %d\n",iReturn);
+ /* Paste no data, to satisfy required call to SetClipboardData */
+ if (g_fUnicodeSupport)
+ SetClipboardData (CF_UNICODETEXT, NULL);
+ SetClipboardData (CF_TEXT, NULL);
+ }
+
+ /* Special handling for WM_RENDERALLFORMATS */
+ if (message == WM_RENDERALLFORMATS)
+ {
+ /* We must close the clipboard */
+
+ if (!CloseClipboard ())
+ {
+ winErrorFVerb (1, "winClipboardWindowProc - WM_RENDERALLFORMATS - "
+ "CloseClipboard () failed: %08x\n",
+ GetLastError ());
+ break;
+ }
+ }
+
+ winDebug ("winClipboardWindowProc - WM_RENDER*FORMAT - Returning.\n");
+ return 0;
+ }
+ }
+
+ /* Let Windows perform default processing for unhandled messages */
+ return DefWindowProc (hwnd, message, wParam, lParam);
+}
+
+
+/*
+ * Process any pending Windows messages
+ */
+
+BOOL
+winClipboardFlushWindowsMessageQueue (HWND hwnd)
+{
+ MSG msg;
+
+ /* Flush the messaging window queue */
+ /* NOTE: Do not pass the hwnd of our messaging window to PeekMessage,
+ * as this will filter out many non-window-specific messages that
+ * are sent to our thread, such as WM_QUIT.
+ */
+ while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
+ {
+ /* Dispatch the message if not WM_QUIT */
+ if (msg.message == WM_QUIT)
+ return FALSE;
+ else
+ DispatchMessage (&msg);
+ }
+
+ return TRUE;
+}
diff --git a/xorg-server/hw/xwin/winclipboardwrappers.c b/xorg-server/hw/xwin/winclipboardwrappers.c index c68d78aa3..ab4e8e43e 100644 --- a/xorg-server/hw/xwin/winclipboardwrappers.c +++ b/xorg-server/hw/xwin/winclipboardwrappers.c @@ -310,30 +310,26 @@ winProcEstablishConnection (ClientPtr client) * Wrapper for internal SetSelectionOwner function. * Grabs ownership of Windows clipboard when X11 clipboard owner changes. */ - int winProcSetSelectionOwner (ClientPtr client) { int i; DrawablePtr pDrawable; WindowPtr pWindow = None; - Bool fOwnedToNotOwned = FALSE; static Window s_iOwners[CLIP_NUM_SELECTIONS] = {None}; static unsigned long s_ulServerGeneration = 0; REQUEST(xSetSelectionOwnerReq); REQUEST_SIZE_MATCH(xSetSelectionOwnerReq); -#if 0 - ErrorF ("winProcSetSelectionOwner - Hello.\n"); -#endif + winDebug ("winProcSetSelectionOwner - Hello.\n"); /* Watch for server reset */ if (s_ulServerGeneration != serverGeneration) { /* Save new generation number */ s_ulServerGeneration = serverGeneration; - + /* Initialize static variables */ for (i = 0; i < CLIP_NUM_SELECTIONS; ++i) s_iOwners[i] = None; @@ -342,9 +338,9 @@ winProcSetSelectionOwner (ClientPtr client) /* Abort if clipboard not completely initialized yet */ if (!g_fClipboardStarted) { - /* ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, " - "aborting.\n"); */ - goto winProcSetSelectionOwner_Done; + ErrorF ("winProcSetSelectionOwner - Clipboard not yet started, " + "aborting.\n"); + goto winProcSetSelectionOwner_Done; } /* Grab window if we have one */ @@ -367,12 +363,8 @@ winProcSetSelectionOwner (ClientPtr client) if (None == stuff->window && None != s_iOwners[CLIP_OWN_PRIMARY]) { - fOwnedToNotOwned = TRUE; - -#if 0 - ErrorF ("winProcSetSelectionOwner - PRIMARY - Going from " + winDebug ("winProcSetSelectionOwner - PRIMARY - Going from " "owned to not owned.\n"); -#endif /* Adjust last owned selection */ if (None != s_iOwners[CLIP_OWN_CLIPBOARD]) @@ -384,10 +376,8 @@ winProcSetSelectionOwner (ClientPtr client) /* Save new selection owner or None */ s_iOwners[CLIP_OWN_PRIMARY] = stuff->window; -#if 0 - ErrorF ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d\n", - stuff->window); -#endif + winDebug ("winProcSetSelectionOwner - PRIMARY - Now owned by: %d (clipboard is %d)\n", + stuff->window,g_iClipboardWindow); } else if (MakeAtom ("CLIPBOARD", 9, TRUE) == stuff->selection) { @@ -395,12 +385,8 @@ winProcSetSelectionOwner (ClientPtr client) if (None == stuff->window && None != s_iOwners[CLIP_OWN_CLIPBOARD]) { - fOwnedToNotOwned = TRUE; - -#if 0 - ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Going from " + winDebug ("winProcSetSelectionOwner - CLIPBOARD - Going from " "owned to not owned.\n"); -#endif /* Adjust last owned selection */ if (None != s_iOwners[CLIP_OWN_PRIMARY]) @@ -412,10 +398,8 @@ winProcSetSelectionOwner (ClientPtr client) /* Save new selection owner or None */ s_iOwners[CLIP_OWN_CLIPBOARD] = stuff->window; -#if 0 - ErrorF ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d\n", - stuff->window); -#endif + winDebug ("winProcSetSelectionOwner - CLIPBOARD - Now owned by: %d, clipboard is %d\n", + stuff->window,g_iClipboardWindow); } else goto winProcSetSelectionOwner_Done; @@ -430,48 +414,17 @@ winProcSetSelectionOwner (ClientPtr client) if (g_iClipboardWindow == s_iOwners[CLIP_OWN_CLIPBOARD]) s_iOwners[CLIP_OWN_CLIPBOARD] = None; - /* - * Handle case when selection is being disowned, - * WM_DRAWCLIPBOARD did not do the disowning, - * both monitored selections are no longer owned, - * an owned to not owned transition was detected, - * and we currently own the Win32 clipboard. - */ - if (stuff->window == None - && s_iOwners[CLIP_OWN_PRIMARY] == None - && s_iOwners[CLIP_OWN_CLIPBOARD] == None - && fOwnedToNotOwned - && g_hwndClipboard != NULL - && g_hwndClipboard == GetClipboardOwner ()) - { -#if 0 - ErrorF ("winProcSetSelectionOwner - We currently own the " - "clipboard and neither the PRIMARY nor the CLIPBOARD " - "selections are owned, releasing ownership of Win32 " - "clipboard.\n"); -#endif - - /* Release ownership of the Windows clipboard */ - OpenClipboard (NULL); - EmptyClipboard (); - CloseClipboard (); - - goto winProcSetSelectionOwner_Done; - } - /* Abort if no window at this point */ if (None == stuff->window) { -#if 0 - ErrorF ("winProcSetSelectionOwner - No window, returning.\n"); -#endif + winDebug ("winProcSetSelectionOwner - No window, returning.\n"); goto winProcSetSelectionOwner_Done; } /* Abort if invalid selection */ if (!ValidAtom (stuff->selection)) { - ErrorF ("winProcSetSelectionOwner - Found BadAtom, aborting.\n"); + winDebug ("winProcSetSelectionOwner - Found BadAtom, aborting.\n"); goto winProcSetSelectionOwner_Done; } @@ -481,32 +434,24 @@ winProcSetSelectionOwner (ClientPtr client) /* Abort if clipboard manager is owning the selection */ if (pDrawable->id == g_iClipboardWindow) { -#if 0 - ErrorF ("winProcSetSelectionOwner - We changed ownership, " + winDebug ("winProcSetSelectionOwner - We changed ownership, " "aborting.\n"); -#endif goto winProcSetSelectionOwner_Done; } /* Abort if root window is taking ownership */ if (pDrawable->id == 0) { - ErrorF ("winProcSetSelectionOwner - Root window taking ownership, " + winDebug ("winProcSetSelectionOwner - Root window taking ownership, " "aborting\n"); goto winProcSetSelectionOwner_Done; } - /* Close clipboard if we have it open already */ - if (GetOpenClipboardWindow () == g_hwndClipboard) - { - CloseClipboard (); - } - /* Access the Windows clipboard */ if (!OpenClipboard (g_hwndClipboard)) { - ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x\n", - (int) GetLastError ()); + ErrorF ("winProcSetSelectionOwner - OpenClipboard () failed: %08x, hwnd: %08x\n", + (int) GetLastError (),g_hwndClipboard); goto winProcSetSelectionOwner_Done; } @@ -515,9 +460,12 @@ winProcSetSelectionOwner (ClientPtr client) { ErrorF ("winProcSetSelectionOwner - EmptyClipboard () failed: %08x\n", (int) GetLastError ()); + CloseClipboard (); goto winProcSetSelectionOwner_Done; } + winDebug("winProcSetSelectionOwner - SetClipboardData NULL\n"); + /* Advertise Unicode if we support it */ if (g_fUnicodeSupport) SetClipboardData (CF_UNICODETEXT, NULL); @@ -537,6 +485,6 @@ winProcSetSelectionOwner (ClientPtr client) goto winProcSetSelectionOwner_Done; } - winProcSetSelectionOwner_Done: +winProcSetSelectionOwner_Done: return (*winProcSetSelectionOwnerOrig) (client); } diff --git a/xorg-server/hw/xwin/winclipboardxevents.c b/xorg-server/hw/xwin/winclipboardxevents.c index ec40814db..11fde16b9 100644 --- a/xorg-server/hw/xwin/winclipboardxevents.c +++ b/xorg-server/hw/xwin/winclipboardxevents.c @@ -1,825 +1,859 @@ -/* - *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved. - *Copyright (C) Colin Harrison 2005-2008 - * - *Permission is hereby granted, free of charge, to any person obtaining - * a copy of this software and associated documentation files (the - *"Software"), to deal in the Software without restriction, including - *without limitation the rights to use, copy, modify, merge, publish, - *distribute, sublicense, and/or sell copies of the Software, and to - *permit persons to whom the Software is furnished to do so, subject to - *the following conditions: - * - *The above copyright notice and this permission notice shall be - *included in all copies or substantial portions of the Software. - * - *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR - *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF - *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION - *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - *Except as contained in this notice, the name of 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: Harold L Hunt II - * Colin Harrison - */ - -#ifdef HAVE_XWIN_CONFIG_H -#include <xwin-config.h> -#endif -#include "winclipboard.h" -#include "misc.h" - - -/* - * References to external symbols - */ - -extern Bool g_fUnicodeSupport; - - -/* - * Process any pending X events - */ - -int -winClipboardFlushXEvents (HWND hwnd, - int iWindow, - Display *pDisplay, - Bool fUseUnicode) -{ - static Atom atomLocalProperty; - static Atom atomCompoundText; - static Atom atomUTF8String; - static Atom atomTargets; - static int generation; - - if (generation != serverGeneration) - { - generation = serverGeneration; - atomLocalProperty = XInternAtom (pDisplay, WIN_LOCAL_PROPERTY, False); - atomUTF8String = XInternAtom (pDisplay, "UTF8_STRING", False); - atomCompoundText = XInternAtom (pDisplay, "COMPOUND_TEXT", False); - atomTargets = XInternAtom (pDisplay, "TARGETS", False); - } - - /* Process all pending events */ - while (XPending (pDisplay)) - { - XTextProperty xtpText = {0}; - XEvent event; - XSelectionEvent eventSelection; - unsigned long ulReturnBytesLeft; - unsigned char *pszReturnData = NULL; - char *pszGlobalData = NULL; - int iReturn; - HGLOBAL hGlobal = NULL; - XICCEncodingStyle xiccesStyle; - int iConvertDataLen = 0; - char *pszConvertData = NULL; - char *pszTextList[2] = {NULL}; - int iCount; - char **ppszTextList = NULL; - wchar_t *pwszUnicodeStr = NULL; - int iUnicodeLen = 0; - int iReturnDataLen = 0; - int i; - Bool fAbort = FALSE; - Bool fCloseClipboard = FALSE; - Bool fSetClipboardData = TRUE; - - /* Get the next event - will not block because one is ready */ - XNextEvent (pDisplay, &event); - - /* Branch on the event type */ - switch (event.type) - { - /* - * SelectionRequest - */ - - case SelectionRequest: -#if 0 - { - char *pszAtomName = NULL; - - ErrorF ("SelectionRequest - target %d\n", - event.xselectionrequest.target); - - pszAtomName = XGetAtomName (pDisplay, - event.xselectionrequest.target); - ErrorF ("SelectionRequest - Target atom name %s\n", pszAtomName); - XFree (pszAtomName); - pszAtomName = NULL; - } -#endif - - /* Abort if invalid target type */ - if (event.xselectionrequest.target != XA_STRING - && event.xselectionrequest.target != atomUTF8String - && event.xselectionrequest.target != atomCompoundText - && event.xselectionrequest.target != atomTargets) - { - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - /* Handle targets type of request */ - if (event.xselectionrequest.target == atomTargets) - { - Atom atomTargetArr[] = {atomTargets, - atomCompoundText, - atomUTF8String, - XA_STRING}; - - /* Try to change the property */ - iReturn = XChangeProperty (pDisplay, - event.xselectionrequest.requestor, - event.xselectionrequest.property, - XA_ATOM, - 32, - PropModeReplace, - (unsigned char *) atomTargetArr, - (sizeof (atomTargetArr) - / sizeof (atomTargetArr[0]))); - if (iReturn == BadAlloc - || iReturn == BadAtom - || iReturn == BadMatch - || iReturn == BadValue - || iReturn == BadWindow) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "XChangeProperty failed: %d\n", - iReturn); - } - - /* Setup selection notify xevent */ - eventSelection.type = SelectionNotify; - eventSelection.send_event = True; - eventSelection.display = pDisplay; - eventSelection.requestor = event.xselectionrequest.requestor; - eventSelection.selection = event.xselectionrequest.selection; - eventSelection.target = event.xselectionrequest.target; - eventSelection.property = event.xselectionrequest.property; - eventSelection.time = event.xselectionrequest.time; - - /* - * Notify the requesting window that - * the operation has completed - */ - iReturn = XSendEvent (pDisplay, - eventSelection.requestor, - False, - 0L, - (XEvent *) &eventSelection); - if (iReturn == BadValue || iReturn == BadWindow) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "XSendEvent () failed\n"); - } - break; - } - - /* Check that clipboard format is available */ - if (fUseUnicode - && !IsClipboardFormatAvailable (CF_UNICODETEXT)) - { - static int count; /* Hack to stop acroread spamming the log */ - static HWND lasthwnd; /* I've not seen any other client get here repeatedly? */ - if (hwnd != lasthwnd) count = 0; - count++; - if (count < 6) ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not " - "available from Win32 clipboard. Aborting %d.\n", count); - lasthwnd = hwnd; - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - else if (!fUseUnicode - && !IsClipboardFormatAvailable (CF_TEXT)) - { - ErrorF ("winClipboardFlushXEvents - CF_TEXT is not " - "available from Win32 clipboard. Aborting.\n"); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - /* Close clipboard if we have it open already */ - if (GetOpenClipboardWindow () == hwnd) - { - CloseClipboard (); - } - - /* Access the clipboard */ - if (!OpenClipboard (hwnd)) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "OpenClipboard () failed: %08x\n", - GetLastError ()); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - /* Indicate that clipboard was opened */ - fCloseClipboard = TRUE; - - /* Setup the string style */ - if (event.xselectionrequest.target == XA_STRING) - xiccesStyle = XStringStyle; -#ifdef X_HAVE_UTF8_STRING - else if (event.xselectionrequest.target == atomUTF8String) - xiccesStyle = XUTF8StringStyle; -#endif - else if (event.xselectionrequest.target == atomCompoundText) - xiccesStyle = XCompoundTextStyle; - else - xiccesStyle = XStringStyle; - - /* - * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me - */ - - /* Get a pointer to the clipboard text, in desired format */ - if (fUseUnicode) - { - /* Retrieve clipboard data */ - hGlobal = GetClipboardData (CF_UNICODETEXT); - } - else - { - /* Retrieve clipboard data */ - hGlobal = GetClipboardData (CF_TEXT); - } - if (!hGlobal) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "GetClipboardData () failed: %08x\n", - GetLastError ()); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - pszGlobalData = (char *) GlobalLock (hGlobal); - - /* Convert the Unicode string to UTF8 (MBCS) */ - if (fUseUnicode) - { - iConvertDataLen = WideCharToMultiByte (CP_UTF8, - 0, - (LPCWSTR)pszGlobalData, - -1, - NULL, - 0, - NULL, - NULL); - /* NOTE: iConvertDataLen includes space for null terminator */ - pszConvertData = (char *) malloc (iConvertDataLen); - WideCharToMultiByte (CP_UTF8, - 0, - (LPCWSTR)pszGlobalData, - -1, - pszConvertData, - iConvertDataLen, - NULL, - NULL); - } - else - { - pszConvertData = strdup (pszGlobalData); - iConvertDataLen = strlen (pszConvertData) + 1; - } - - /* Convert DOS string to UNIX string */ - winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData)); - - /* Setup our text list */ - pszTextList[0] = pszConvertData; - pszTextList[1] = NULL; - - /* Initialize the text property */ - xtpText.value = NULL; - xtpText.nitems = 0; - - /* Create the text property from the text list */ - if (fUseUnicode) - { -#ifdef X_HAVE_UTF8_STRING - iReturn = Xutf8TextListToTextProperty (pDisplay, - pszTextList, - 1, - xiccesStyle, - &xtpText); -#endif - } - else - { - iReturn = XmbTextListToTextProperty (pDisplay, - pszTextList, - 1, - xiccesStyle, - &xtpText); - } - if (iReturn == XNoMemory || iReturn == XLocaleNotSupported) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "X*TextListToTextProperty failed: %d\n", - iReturn); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - /* Free the converted string */ - free (pszConvertData); - pszConvertData = NULL; - - /* Copy the clipboard text to the requesting window */ - iReturn = XChangeProperty (pDisplay, - event.xselectionrequest.requestor, - event.xselectionrequest.property, - event.xselectionrequest.target, - 8, - PropModeReplace, - xtpText.value, - xtpText.nitems); - if (iReturn == BadAlloc || iReturn == BadAtom - || iReturn == BadMatch || iReturn == BadValue - || iReturn == BadWindow) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "XChangeProperty failed: %d\n", - iReturn); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - /* Release the clipboard data */ - GlobalUnlock (hGlobal); - pszGlobalData = NULL; - fCloseClipboard = FALSE; - CloseClipboard (); - - /* Clean up */ - XFree (xtpText.value); - xtpText.value = NULL; - xtpText.nitems = 0; - - /* Setup selection notify event */ - eventSelection.type = SelectionNotify; - eventSelection.send_event = True; - eventSelection.display = pDisplay; - eventSelection.requestor = event.xselectionrequest.requestor; - eventSelection.selection = event.xselectionrequest.selection; - eventSelection.target = event.xselectionrequest.target; - eventSelection.property = event.xselectionrequest.property; - eventSelection.time = event.xselectionrequest.time; - - /* Notify the requesting window that the operation has completed */ - iReturn = XSendEvent (pDisplay, - eventSelection.requestor, - False, - 0L, - (XEvent *) &eventSelection); - if (iReturn == BadValue || iReturn == BadWindow) - { - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "XSendEvent () failed\n"); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionRequest_Done; - } - - winClipboardFlushXEvents_SelectionRequest_Done: - /* Free allocated resources */ - if (xtpText.value) - { - XFree (xtpText.value); - xtpText.value = NULL; - xtpText.nitems = 0; - } - if (pszConvertData) - free (pszConvertData); - if (hGlobal && pszGlobalData) - GlobalUnlock (hGlobal); - - /* - * Send a SelectionNotify event to the requesting - * client when we abort. - */ - if (fAbort) - { - /* Setup selection notify event */ - eventSelection.type = SelectionNotify; - eventSelection.send_event = True; - eventSelection.display = pDisplay; - eventSelection.requestor = event.xselectionrequest.requestor; - eventSelection.selection = event.xselectionrequest.selection; - eventSelection.target = event.xselectionrequest.target; - eventSelection.property = None; - eventSelection.time = event.xselectionrequest.time; - - /* Notify the requesting window that the operation is complete */ - iReturn = XSendEvent (pDisplay, - eventSelection.requestor, - False, - 0L, - (XEvent *) &eventSelection); - if (iReturn == BadValue || iReturn == BadWindow) - { - /* - * Should not be a problem if XSendEvent fails because - * the client may simply have exited. - */ - ErrorF ("winClipboardFlushXEvents - SelectionRequest - " - "XSendEvent () failed for abort event.\n"); - } - } - - /* Close clipboard if it was opened */ - if (fCloseClipboard) - { - fCloseClipboard = FALSE; - CloseClipboard (); - } - break; - - - /* - * SelectionNotify - */ - - case SelectionNotify: -#if 0 - ErrorF ("winClipboardFlushXEvents - SelectionNotify\n"); - { - char *pszAtomName; - - pszAtomName = XGetAtomName (pDisplay, - event.xselection.selection); - - ErrorF ("winClipboardFlushXEvents - SelectionNotify - ATOM: %s\n", - pszAtomName); - - XFree (pszAtomName); - } -#endif - - - /* - * Request conversion of UTF8 and CompoundText targets. - */ - if (event.xselection.property == None) - { - if (event.xselection.target == XA_STRING) - { -#if 0 - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "XA_STRING\n"); -#endif - return WIN_XEVENTS_CONVERT; - } - else if (event.xselection.target == atomUTF8String) - { -#if 0 - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "Requesting conversion of UTF8 target.\n"); -#endif - iReturn = XConvertSelection (pDisplay, - event.xselection.selection, - XA_STRING, - atomLocalProperty, - iWindow, - CurrentTime); - if (iReturn != Success) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "XConvertSelection () failed for UTF8String, " - "aborting: %d\n", - iReturn); - break; - } - - /* Process the ConvertSelection event */ - XFlush (pDisplay); - return WIN_XEVENTS_CONVERT; - } -#ifdef X_HAVE_UTF8_STRING - else if (event.xselection.target == atomCompoundText) - { -#if 0 - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "Requesting conversion of CompoundText target.\n"); -#endif - iReturn = XConvertSelection (pDisplay, - event.xselection.selection, - atomUTF8String, - atomLocalProperty, - iWindow, - CurrentTime); - if (iReturn != Success) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "XConvertSelection () failed for CompoundText, " - "aborting: %d\n", - iReturn); - break; - } - - /* Process the ConvertSelection event */ - XFlush (pDisplay); - return WIN_XEVENTS_CONVERT; - } -#endif - else - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "Unknown format. Cannot request conversion, " - "aborting.\n"); - break; - } - } - - /* Retrieve the size of the stored data */ - iReturn = XGetWindowProperty (pDisplay, - iWindow, - atomLocalProperty, - 0, - 0, /* Don't get data, just size */ - False, - AnyPropertyType, - &xtpText.encoding, - &xtpText.format, - &xtpText.nitems, - &ulReturnBytesLeft, - &xtpText.value); - if (iReturn != Success) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "XGetWindowProperty () failed, aborting: %d\n", - iReturn); - break; - } - -#if 0 - ErrorF ("SelectionNotify - returned data %d left %d\n", - xtpText.nitems, ulReturnBytesLeft); -#endif - - /* Request the selection data */ - iReturn = XGetWindowProperty (pDisplay, - iWindow, - atomLocalProperty, - 0, - ulReturnBytesLeft, - False, - AnyPropertyType, - &xtpText.encoding, - &xtpText.format, - &xtpText.nitems, - &ulReturnBytesLeft, - &xtpText.value); - if (iReturn != Success) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "XGetWindowProperty () failed, aborting: %d\n", - iReturn); - break; - } - -#if 0 - { - char *pszAtomName = NULL; - - ErrorF ("SelectionNotify - returned data %d left %d\n", - xtpText.nitems, ulReturnBytesLeft); - - pszAtomName = XGetAtomName(pDisplay, xtpText.encoding); - ErrorF ("Notify atom name %s\n", pszAtomName); - XFree (pszAtomName); - pszAtomName = NULL; - } -#endif - - if (fUseUnicode) - { -#ifdef X_HAVE_UTF8_STRING - /* Convert the text property to a text list */ - iReturn = Xutf8TextPropertyToTextList (pDisplay, - &xtpText, - &ppszTextList, - &iCount); -#endif - } - else - { - iReturn = XmbTextPropertyToTextList (pDisplay, - &xtpText, - &ppszTextList, - &iCount); - } - if (iReturn == Success || iReturn > 0) - { - /* Conversion succeeded or some unconvertible characters */ - if (ppszTextList != NULL) - { - iReturnDataLen = 0; - for (i = 0; i < iCount; i++) - { - iReturnDataLen += strlen(ppszTextList[i]); - } - pszReturnData = malloc (iReturnDataLen + 1); - pszReturnData[0] = '\0'; - for (i = 0; i < iCount; i++) - { - strcat (pszReturnData, ppszTextList[i]); - } - } - else - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "X*TextPropertyToTextList list_return is NULL.\n"); - pszReturnData = malloc (1); - pszReturnData[0] = '\0'; - } - } - else - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify - " - "X*TextPropertyToTextList returned: "); - switch (iReturn) - { - case XNoMemory: - ErrorF ("XNoMemory\n"); - break; - case XConverterNotFound: - ErrorF ("XConverterNotFound\n"); - break; - default: - ErrorF ("%d", iReturn); - break; - } - pszReturnData = malloc (1); - pszReturnData[0] = '\0'; - } - - /* Free the data returned from XGetWindowProperty */ - if (ppszTextList) - XFreeStringList (ppszTextList); - ppszTextList = NULL; - XFree (xtpText.value); - xtpText.value = NULL; - xtpText.nitems = 0; - - /* Convert the X clipboard string to DOS format */ - winClipboardUNIXtoDOS (&pszReturnData, strlen (pszReturnData)); - - if (fUseUnicode) - { - /* Find out how much space needed to convert MBCS to Unicode */ - iUnicodeLen = MultiByteToWideChar (CP_UTF8, - 0, - pszReturnData, - -1, - NULL, - 0); - - /* Allocate memory for the Unicode string */ - pwszUnicodeStr - = (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1)); - if (!pwszUnicodeStr) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify " - "malloc failed for pwszUnicodeStr, aborting.\n"); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionNotify_Done; - } - - /* Do the actual conversion */ - MultiByteToWideChar (CP_UTF8, - 0, - pszReturnData, - -1, - pwszUnicodeStr, - iUnicodeLen); - - /* Allocate global memory for the X clipboard data */ - hGlobal = GlobalAlloc (GMEM_MOVEABLE, - sizeof (wchar_t) * (iUnicodeLen + 1)); - } - else - { - pszConvertData = strdup (pszReturnData); - iConvertDataLen = strlen (pszConvertData) + 1; - - /* Allocate global memory for the X clipboard data */ - hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen); - } - - free (pszReturnData); - - /* Check that global memory was allocated */ - if (!hGlobal) - { - ErrorF ("winClipboardFlushXEvents - SelectionNotify " - "GlobalAlloc failed, aborting: %ld\n", - GetLastError ()); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionNotify_Done; - } - - /* Obtain a pointer to the global memory */ - pszGlobalData = GlobalLock (hGlobal); - if (pszGlobalData == NULL) - { - ErrorF ("winClipboardFlushXEvents - Could not lock global " - "memory for clipboard transfer\n"); - - /* Abort */ - fAbort = TRUE; - goto winClipboardFlushXEvents_SelectionNotify_Done; - } - - /* Copy the returned string into the global memory */ - if (fUseUnicode) - { - memcpy (pszGlobalData, - pwszUnicodeStr, - sizeof (wchar_t) * (iUnicodeLen + 1)); - free (pwszUnicodeStr); - pwszUnicodeStr = NULL; - } - else - { - strcpy (pszGlobalData, pszConvertData); - free (pszConvertData); - pszConvertData = NULL; - } - - /* Release the pointer to the global memory */ - GlobalUnlock (hGlobal); - pszGlobalData = NULL; - - /* Push the selection data to the Windows clipboard */ - if (fUseUnicode) - SetClipboardData (CF_UNICODETEXT, hGlobal); - else - SetClipboardData (CF_TEXT, hGlobal); - - /* Flag that SetClipboardData has been called */ - fSetClipboardData = FALSE; - - /* - * NOTE: Do not try to free pszGlobalData, it is owned by - * Windows after the call to SetClipboardData (). - */ - - winClipboardFlushXEvents_SelectionNotify_Done: - /* Free allocated resources */ - if (ppszTextList) - XFreeStringList (ppszTextList); - if (xtpText.value) - { - XFree (xtpText.value); - xtpText.value = NULL; - xtpText.nitems = 0; - } - if (pszConvertData) - free (pszConvertData); - if (pwszUnicodeStr) - free (pwszUnicodeStr); - if (hGlobal && pszGlobalData) - GlobalUnlock (hGlobal); - if (fSetClipboardData && g_fUnicodeSupport) - SetClipboardData (CF_UNICODETEXT, NULL); - if (fSetClipboardData) - SetClipboardData (CF_TEXT, NULL); - return WIN_XEVENTS_NOTIFY; - - default: - break; - } - } - - return WIN_XEVENTS_SUCCESS; -} +/*
+ *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved.
+ *Copyright (C) Colin Harrison 2005-2008
+ *
+ *Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ *"Software"), to deal in the Software without restriction, including
+ *without limitation the rights to use, copy, modify, merge, publish,
+ *distribute, sublicense, and/or sell copies of the Software, and to
+ *permit persons to whom the Software is furnished to do so, subject to
+ *the following conditions:
+ *
+ *The above copyright notice and this permission notice shall be
+ *included in all copies or substantial portions of the Software.
+ *
+ *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ *MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ *NONINFRINGEMENT. IN NO EVENT SHALL HAROLD L HUNT II BE LIABLE FOR
+ *ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
+ *CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ *WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ *
+ *Except as contained in this notice, the name of 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: Harold L Hunt II
+ * Colin Harrison
+ */
+
+#ifdef HAVE_XWIN_CONFIG_H
+#include <xwin-config.h>
+#endif
+#include "winclipboard.h"
+#include "misc.h"
+#include "winmsg.h"
+
+
+/*
+ * References to external symbols
+ */
+
+extern Bool g_fUnicodeSupport;
+
+
+/*
+ * Process any pending X events
+ */
+
+int
+winClipboardFlushXEvents (HWND hwnd,
+ int iWindow,
+ Display *pDisplay,
+ Bool fUseUnicode,
+ Bool ClipboardOpened)
+{
+ static Atom atomLocalProperty;
+ static Atom atomCompoundText;
+ static Atom atomUTF8String;
+ static Atom atomTargets;
+ static int generation;
+
+ if (generation != serverGeneration)
+ {
+ generation = serverGeneration;
+ atomLocalProperty = XInternAtom (pDisplay, WIN_LOCAL_PROPERTY, False);
+ atomUTF8String = XInternAtom (pDisplay, "UTF8_STRING", False);
+ atomCompoundText = XInternAtom (pDisplay, "COMPOUND_TEXT", False);
+ atomTargets = XInternAtom (pDisplay, "TARGETS", False);
+ }
+
+ /* Process all pending events */
+ while (XPending (pDisplay))
+ {
+ XTextProperty xtpText = {0};
+ XEvent event;
+ XSelectionEvent eventSelection;
+ unsigned long ulReturnBytesLeft;
+ unsigned char *pszReturnData = NULL;
+ char *pszGlobalData = NULL;
+ int iReturn;
+ HGLOBAL hGlobal = NULL;
+ XICCEncodingStyle xiccesStyle;
+ int iConvertDataLen = 0;
+ char *pszConvertData = NULL;
+ char *pszTextList[2] = {NULL};
+ int iCount;
+ char **ppszTextList = NULL;
+ wchar_t *pwszUnicodeStr = NULL;
+ int iUnicodeLen = 0;
+ int iReturnDataLen = 0;
+ int i;
+ Bool fAbort = FALSE;
+ Bool fCloseClipboard = FALSE;
+ Bool fSetClipboardData = TRUE;
+
+ /* Get the next event - will not block because one is ready */
+ XNextEvent (pDisplay, &event);
+
+ winDebug ("Received event type %d\n",event.type);
+
+ /* Branch on the event type */
+ switch (event.type)
+ {
+ /*
+ * SelectionRequest
+ */
+
+ case SelectionRequest:
+#ifdef _DEBUG
+ {
+ char *pszAtomName = NULL;
+
+ winDebug ("SelectionRequest - target %d\n",
+ event.xselectionrequest.target);
+
+ pszAtomName = XGetAtomName (pDisplay,
+ event.xselectionrequest.target);
+ winDebug ("SelectionRequest - Target atom name %s\n", pszAtomName);
+ XFree (pszAtomName);
+ pszAtomName = NULL;
+ winDebug ("SelectionRequest - owner %d\n", event.xselectionrequest.owner);
+ winDebug ("SelectionRequest - requestor %d\n", event.xselectionrequest.requestor);
+ }
+#endif
+
+ /* Abort if invalid target type */
+ if (event.xselectionrequest.target != XA_STRING
+ && event.xselectionrequest.target != atomUTF8String
+ && event.xselectionrequest.target != atomCompoundText
+ && event.xselectionrequest.target != atomTargets)
+ {
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ /* Handle targets type of request */
+ if (event.xselectionrequest.target == atomTargets)
+ {
+ Atom atomTargetArr[] = {atomTargets,
+ atomCompoundText,
+ atomUTF8String,
+ XA_STRING};
+
+ /* Try to change the property */
+ iReturn = XChangeProperty (pDisplay,
+ event.xselectionrequest.requestor,
+ event.xselectionrequest.property,
+ XA_ATOM,
+ 32,
+ PropModeReplace,
+ (unsigned char *) atomTargetArr,
+ (sizeof (atomTargetArr)
+ / sizeof (atomTargetArr[0])));
+ if (iReturn == BadAlloc
+ || iReturn == BadAtom
+ || iReturn == BadMatch
+ || iReturn == BadValue
+ || iReturn == BadWindow)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "XChangeProperty failed: %d\n",
+ iReturn);
+ }
+
+ /* Setup selection notify xevent */
+ eventSelection.type = SelectionNotify;
+ eventSelection.send_event = True;
+ eventSelection.display = pDisplay;
+ eventSelection.requestor = event.xselectionrequest.requestor;
+ eventSelection.selection = event.xselectionrequest.selection;
+ eventSelection.target = event.xselectionrequest.target;
+ eventSelection.property = event.xselectionrequest.property;
+ eventSelection.time = event.xselectionrequest.time;
+
+ /*
+ * Notify the requesting window that
+ * the operation has completed
+ */
+ iReturn = XSendEvent (pDisplay,
+ eventSelection.requestor,
+ False,
+ 0L,
+ (XEvent *) &eventSelection);
+ if (iReturn == BadValue || iReturn == BadWindow)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "XSendEvent () failed\n");
+ }
+ break;
+ }
+
+ /* Check that clipboard format is available */
+ if (fUseUnicode
+ && !IsClipboardFormatAvailable (CF_UNICODETEXT))
+ {
+ static int count; /* Hack to stop acroread spamming the log */
+ static HWND lasthwnd; /* I've not seen any other client get here repeatedly? */
+ if (hwnd != lasthwnd) count = 0;
+ count++;
+ if (count < 6) ErrorF ("winClipboardFlushXEvents - CF_UNICODETEXT is not "
+ "available from Win32 clipboard. Aborting %d.\n", count);
+ lasthwnd = hwnd;
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+ else if (!fUseUnicode
+ && !IsClipboardFormatAvailable (CF_TEXT))
+ {
+ ErrorF ("winClipboardFlushXEvents - CF_TEXT is not "
+ "available from Win32 clipboard. Aborting.\n");
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ /* Access the clipboard */
+ if (!ClipboardOpened)
+ {
+ if (!OpenClipboard (hwnd))
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "OpenClipboard () failed: %08x\n",
+ GetLastError ());
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ /* Indicate that clipboard was opened */
+ fCloseClipboard = TRUE;
+ }
+ /* Setup the string style */
+ if (event.xselectionrequest.target == XA_STRING)
+ xiccesStyle = XStringStyle;
+#ifdef X_HAVE_UTF8_STRING
+ else if (event.xselectionrequest.target == atomUTF8String)
+ xiccesStyle = XUTF8StringStyle;
+#endif
+ else if (event.xselectionrequest.target == atomCompoundText)
+ xiccesStyle = XCompoundTextStyle;
+ else
+ xiccesStyle = XStringStyle;
+
+ /*
+ * FIXME: Can't pass CF_UNICODETEXT on Windows 95/98/Me
+ */
+
+ /* Get a pointer to the clipboard text, in desired format */
+ if (fUseUnicode)
+ {
+ /* Retrieve clipboard data */
+ hGlobal = GetClipboardData (CF_UNICODETEXT);
+ }
+ else
+ {
+ /* Retrieve clipboard data */
+ hGlobal = GetClipboardData (CF_TEXT);
+ }
+ if (!hGlobal)
+ {
+ if (GetLastError()==ERROR_CLIPBOARD_NOT_OPEN && ClipboardOpened)
+ {
+ ErrorF("We should not have received a SelectionRequest????\n"
+ "The owner is the clipboard, but in reality it was"
+ "an X window\n");
+ /* Set the owner to None */
+ XSetSelectionOwner (pDisplay, XA_PRIMARY, None, CurrentTime);
+ XSetSelectionOwner (pDisplay, XInternAtom (pDisplay, "CLIPBOARD", False), None, CurrentTime);
+ }
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "GetClipboardData () failed: %08x\n",
+ GetLastError ());
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+ pszGlobalData = (char *) GlobalLock (hGlobal);
+
+ /* Convert the Unicode string to UTF8 (MBCS) */
+ if (fUseUnicode)
+ {
+ iConvertDataLen = WideCharToMultiByte (CP_UTF8,
+ 0,
+ (LPCWSTR)pszGlobalData,
+ -1,
+ NULL,
+ 0,
+ NULL,
+ NULL);
+ /* NOTE: iConvertDataLen includes space for null terminator */
+ pszConvertData = (char *) malloc (iConvertDataLen);
+ WideCharToMultiByte (CP_UTF8,
+ 0,
+ (LPCWSTR)pszGlobalData,
+ -1,
+ pszConvertData,
+ iConvertDataLen,
+ NULL,
+ NULL);
+ }
+ else
+ {
+ pszConvertData = strdup (pszGlobalData);
+ iConvertDataLen = strlen (pszConvertData) + 1;
+ }
+
+ /* Convert DOS string to UNIX string */
+ winClipboardDOStoUNIX (pszConvertData, strlen (pszConvertData));
+
+ /* Setup our text list */
+ pszTextList[0] = pszConvertData;
+ pszTextList[1] = NULL;
+
+ /* Initialize the text property */
+ xtpText.value = NULL;
+ xtpText.nitems = 0;
+
+ /* Create the text property from the text list */
+ if (fUseUnicode)
+ {
+#ifdef X_HAVE_UTF8_STRING
+ iReturn = Xutf8TextListToTextProperty (pDisplay,
+ pszTextList,
+ 1,
+ xiccesStyle,
+ &xtpText);
+#endif
+ }
+ else
+ {
+ iReturn = XmbTextListToTextProperty (pDisplay,
+ pszTextList,
+ 1,
+ xiccesStyle,
+ &xtpText);
+ }
+ if (iReturn == XNoMemory || iReturn == XLocaleNotSupported)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "X*TextListToTextProperty failed: %d\n",
+ iReturn);
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ /* Free the converted string */
+ free (pszConvertData);
+ pszConvertData = NULL;
+
+ /* Copy the clipboard text to the requesting window */
+ iReturn = XChangeProperty (pDisplay,
+ event.xselectionrequest.requestor,
+ event.xselectionrequest.property,
+ event.xselectionrequest.target,
+ 8,
+ PropModeReplace,
+ xtpText.value,
+ xtpText.nitems);
+ if (iReturn == BadAlloc || iReturn == BadAtom
+ || iReturn == BadMatch || iReturn == BadValue
+ || iReturn == BadWindow)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "XChangeProperty failed: %d\n",
+ iReturn);
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ /* Release the clipboard data */
+ GlobalUnlock (hGlobal);
+ pszGlobalData = NULL;
+ if (fCloseClipboard)
+ {
+ fCloseClipboard = FALSE;
+ CloseClipboard ();
+ }
+ /* Clean up */
+ XFree (xtpText.value);
+ xtpText.value = NULL;
+ xtpText.nitems = 0;
+
+ /* Setup selection notify event */
+ eventSelection.type = SelectionNotify;
+ eventSelection.send_event = True;
+ eventSelection.display = pDisplay;
+ eventSelection.requestor = event.xselectionrequest.requestor;
+ eventSelection.selection = event.xselectionrequest.selection;
+ eventSelection.target = event.xselectionrequest.target;
+ eventSelection.property = event.xselectionrequest.property;
+ eventSelection.time = event.xselectionrequest.time;
+
+ /* Notify the requesting window that the operation has completed */
+ iReturn = XSendEvent (pDisplay,
+ eventSelection.requestor,
+ False,
+ 0L,
+ (XEvent *) &eventSelection);
+ if (iReturn == BadValue || iReturn == BadWindow)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "XSendEvent () failed\n");
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionRequest_Done;
+ }
+
+ winClipboardFlushXEvents_SelectionRequest_Done:
+ /* Free allocated resources */
+ if (xtpText.value)
+ {
+ XFree (xtpText.value);
+ xtpText.value = NULL;
+ xtpText.nitems = 0;
+ }
+ if (pszConvertData)
+ free (pszConvertData);
+ if (hGlobal && pszGlobalData)
+ GlobalUnlock (hGlobal);
+
+ /*
+ * Send a SelectionNotify event to the requesting
+ * client when we abort.
+ */
+ if (fAbort)
+ {
+ /* Setup selection notify event */
+ eventSelection.type = SelectionNotify;
+ eventSelection.send_event = True;
+ eventSelection.display = pDisplay;
+ eventSelection.requestor = event.xselectionrequest.requestor;
+ eventSelection.selection = event.xselectionrequest.selection;
+ eventSelection.target = event.xselectionrequest.target;
+ eventSelection.property = None;
+ eventSelection.time = event.xselectionrequest.time;
+
+ /* Notify the requesting window that the operation is complete */
+ iReturn = XSendEvent (pDisplay,
+ eventSelection.requestor,
+ False,
+ 0L,
+ (XEvent *) &eventSelection);
+ if (iReturn == BadValue || iReturn == BadWindow)
+ {
+ /*
+ * Should not be a problem if XSendEvent fails because
+ * the client may simply have exited.
+ */
+ ErrorF ("winClipboardFlushXEvents - SelectionRequest - "
+ "XSendEvent () failed for abort event.\n");
+ }
+ }
+
+ /* Close clipboard if it was opened */
+ if (fCloseClipboard)
+ {
+ fCloseClipboard = FALSE;
+ CloseClipboard ();
+ }
+ break;
+
+
+ /*
+ * SelectionClear
+ */
+ case SelectionClear:
+#ifdef _DEBUG
+ winDebug ("winClipboardFlushXEvents - SelectionClear\n");
+ {
+ char *pszAtomName;
+
+ pszAtomName = XGetAtomName (pDisplay,
+ event.xselection.selection);
+
+ winDebug ("SelectionClear - ATOM: %s\n",
+ pszAtomName);
+ winDebug ("SelectionClear - owner %d\n", event.xselectionrequest.owner);
+
+ XFree (pszAtomName);
+ }
+#endif
+ break;
+
+ /*
+ * SelectionNotify
+ */
+ case SelectionNotify:
+#ifdef _DEBUG
+ winDebug ("winClipboardFlushXEvents - SelectionNotify\n");
+ {
+ char *pszAtomName;
+
+ pszAtomName = XGetAtomName (pDisplay,
+ event.xselection.selection);
+
+ winDebug ("SelectionNotify - ATOM: %s\n",
+ pszAtomName);
+ winDebug ("SelectionNotify - requestor %d\n", event.xselectionrequest.requestor);
+
+ XFree (pszAtomName);
+ }
+#endif
+
+
+ /*
+ * Request conversion of UTF8 and CompoundText targets.
+ */
+ if (event.xselection.property == None)
+ {
+ if (event.xselection.target == XA_STRING)
+ {
+#if 0
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "XA_STRING\n");
+#endif
+ return WIN_XEVENTS_CONVERT;
+ }
+ else if (event.xselection.target == atomUTF8String)
+ {
+#if 0
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "Requesting conversion of UTF8 target.\n");
+#endif
+ iReturn = XConvertSelection (pDisplay,
+ event.xselection.selection,
+ XA_STRING,
+ atomLocalProperty,
+ iWindow,
+ CurrentTime);
+ if (iReturn != Success)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "XConvertSelection () failed for UTF8String, "
+ "aborting: %d\n",
+ iReturn);
+ break;
+ }
+
+ /* Process the ConvertSelection event */
+ XFlush (pDisplay);
+ return WIN_XEVENTS_CONVERT;
+ }
+#ifdef X_HAVE_UTF8_STRING
+ else if (event.xselection.target == atomCompoundText)
+ {
+#if 0
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "Requesting conversion of CompoundText target.\n");
+#endif
+ iReturn = XConvertSelection (pDisplay,
+ event.xselection.selection,
+ atomUTF8String,
+ atomLocalProperty,
+ iWindow,
+ CurrentTime);
+ if (iReturn != Success)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "XConvertSelection () failed for CompoundText, "
+ "aborting: %d\n",
+ iReturn);
+ break;
+ }
+
+ /* Process the ConvertSelection event */
+ XFlush (pDisplay);
+ return WIN_XEVENTS_CONVERT;
+ }
+#endif
+ else
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "Unknown format. Cannot request conversion, "
+ "aborting.\n");
+ break;
+ }
+ }
+
+ /* Retrieve the size of the stored data */
+ iReturn = XGetWindowProperty (pDisplay,
+ iWindow,
+ atomLocalProperty,
+ 0,
+ 0, /* Don't get data, just size */
+ False,
+ AnyPropertyType,
+ &xtpText.encoding,
+ &xtpText.format,
+ &xtpText.nitems,
+ &ulReturnBytesLeft,
+ &xtpText.value);
+ if (iReturn != Success)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "XGetWindowProperty () failed, aborting: %d\n",
+ iReturn);
+ break;
+ }
+
+#if 0
+ ErrorF ("SelectionNotify - returned data %d left %d\n",
+ xtpText.nitems, ulReturnBytesLeft);
+#endif
+
+ /* Request the selection data */
+ iReturn = XGetWindowProperty (pDisplay,
+ iWindow,
+ atomLocalProperty,
+ 0,
+ ulReturnBytesLeft,
+ False,
+ AnyPropertyType,
+ &xtpText.encoding,
+ &xtpText.format,
+ &xtpText.nitems,
+ &ulReturnBytesLeft,
+ &xtpText.value);
+ if (iReturn != Success)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "XGetWindowProperty () failed, aborting: %d\n",
+ iReturn);
+ break;
+ }
+
+#if 0
+ {
+ char *pszAtomName = NULL;
+
+ ErrorF ("SelectionNotify - returned data %d left %d\n",
+ xtpText.nitems, ulReturnBytesLeft);
+
+ pszAtomName = XGetAtomName(pDisplay, xtpText.encoding);
+ ErrorF ("Notify atom name %s\n", pszAtomName);
+ XFree (pszAtomName);
+ pszAtomName = NULL;
+ }
+#endif
+
+ if (fUseUnicode)
+ {
+#ifdef X_HAVE_UTF8_STRING
+ /* Convert the text property to a text list */
+ iReturn = Xutf8TextPropertyToTextList (pDisplay,
+ &xtpText,
+ &ppszTextList,
+ &iCount);
+#endif
+ }
+ else
+ {
+ iReturn = XmbTextPropertyToTextList (pDisplay,
+ &xtpText,
+ &ppszTextList,
+ &iCount);
+ }
+ if (iReturn == Success || iReturn > 0)
+ {
+ /* Conversion succeeded or some unconvertible characters */
+ if (ppszTextList != NULL)
+ {
+ iReturnDataLen = 0;
+ for (i = 0; i < iCount; i++)
+ {
+ iReturnDataLen += strlen(ppszTextList[i]);
+ }
+ pszReturnData = (char *) malloc (iReturnDataLen + 1);
+ pszReturnData[0] = '\0';
+ for (i = 0; i < iCount; i++)
+ {
+ strcat (pszReturnData, ppszTextList[i]);
+ }
+ }
+ else
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "X*TextPropertyToTextList list_return is NULL.\n");
+ pszReturnData = (char *) malloc (1);
+ pszReturnData[0] = '\0';
+ }
+ }
+ else
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify - "
+ "X*TextPropertyToTextList returned: ");
+ switch (iReturn)
+ {
+ case XNoMemory:
+ ErrorF ("XNoMemory\n");
+ break;
+ case XConverterNotFound:
+ ErrorF ("XConverterNotFound\n");
+ break;
+ default:
+ ErrorF ("%d", iReturn);
+ break;
+ }
+ pszReturnData = (char *) malloc (1);
+ pszReturnData[0] = '\0';
+ }
+
+ /* Free the data returned from XGetWindowProperty */
+ if (ppszTextList)
+ XFreeStringList (ppszTextList);
+ ppszTextList = NULL;
+ XFree (xtpText.value);
+ xtpText.value = NULL;
+ xtpText.nitems = 0;
+
+ /* Convert the X clipboard string to DOS format */
+ winClipboardUNIXtoDOS ((unsigned char **)&pszReturnData, strlen (pszReturnData));
+
+ if (fUseUnicode)
+ {
+ /* Find out how much space needed to convert MBCS to Unicode */
+ iUnicodeLen = MultiByteToWideChar (CP_UTF8,
+ 0,
+ pszReturnData,
+ -1,
+ NULL,
+ 0);
+
+ /* Allocate memory for the Unicode string */
+ pwszUnicodeStr
+ = (wchar_t*) malloc (sizeof (wchar_t) * (iUnicodeLen + 1));
+ if (!pwszUnicodeStr)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+ "malloc failed for pwszUnicodeStr, aborting.\n");
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionNotify_Done;
+ }
+
+ /* Do the actual conversion */
+ MultiByteToWideChar (CP_UTF8,
+ 0,
+ pszReturnData,
+ -1,
+ pwszUnicodeStr,
+ iUnicodeLen);
+
+ /* Allocate global memory for the X clipboard data */
+ hGlobal = GlobalAlloc (GMEM_MOVEABLE,
+ sizeof (wchar_t) * (iUnicodeLen + 1));
+ }
+ else
+ {
+ pszConvertData = strdup (pszReturnData);
+ iConvertDataLen = strlen (pszConvertData) + 1;
+
+ /* Allocate global memory for the X clipboard data */
+ hGlobal = GlobalAlloc (GMEM_MOVEABLE, iConvertDataLen);
+ }
+
+ free (pszReturnData);
+
+ /* Check that global memory was allocated */
+ if (!hGlobal)
+ {
+ ErrorF ("winClipboardFlushXEvents - SelectionNotify "
+ "GlobalAlloc failed, aborting: %ld\n",
+ GetLastError ());
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionNotify_Done;
+ }
+
+ /* Obtain a pointer to the global memory */
+ pszGlobalData = GlobalLock (hGlobal);
+ if (pszGlobalData == NULL)
+ {
+ ErrorF ("winClipboardFlushXEvents - Could not lock global "
+ "memory for clipboard transfer\n");
+
+ /* Abort */
+ fAbort = TRUE;
+ goto winClipboardFlushXEvents_SelectionNotify_Done;
+ }
+
+ /* Copy the returned string into the global memory */
+ if (fUseUnicode)
+ {
+ memcpy (pszGlobalData,
+ pwszUnicodeStr,
+ sizeof (wchar_t) * (iUnicodeLen + 1));
+ free (pwszUnicodeStr);
+ pwszUnicodeStr = NULL;
+ }
+ else
+ {
+ strcpy (pszGlobalData, pszConvertData);
+ free (pszConvertData);
+ pszConvertData = NULL;
+ }
+
+ /* Release the pointer to the global memory */
+ GlobalUnlock (hGlobal);
+ pszGlobalData = NULL;
+
+ /* Push the selection data to the Windows clipboard */
+ if (fUseUnicode)
+ SetClipboardData (CF_UNICODETEXT, hGlobal);
+ else
+ SetClipboardData (CF_TEXT, hGlobal);
+
+ /* Flag that SetClipboardData has been called */
+ fSetClipboardData = FALSE;
+
+ /*
+ * NOTE: Do not try to free pszGlobalData, it is owned by
+ * Windows after the call to SetClipboardData ().
+ */
+
+ winClipboardFlushXEvents_SelectionNotify_Done:
+ /* Free allocated resources */
+ if (ppszTextList)
+ XFreeStringList (ppszTextList);
+ if (xtpText.value)
+ {
+ XFree (xtpText.value);
+ xtpText.value = NULL;
+ xtpText.nitems = 0;
+ }
+ if (pszConvertData)
+ free (pszConvertData);
+ if (pwszUnicodeStr)
+ free (pwszUnicodeStr);
+ if (hGlobal && pszGlobalData)
+ GlobalUnlock (hGlobal);
+ if (fSetClipboardData && g_fUnicodeSupport)
+ SetClipboardData (CF_UNICODETEXT, NULL);
+ if (fSetClipboardData)
+ SetClipboardData (CF_TEXT, NULL);
+ return WIN_XEVENTS_NOTIFY;
+
+ default:
+ break;
+ }
+ }
+
+ return WIN_XEVENTS_SUCCESS;
+}
diff --git a/xorg-server/hw/xwin/wincreatewnd.c b/xorg-server/hw/xwin/wincreatewnd.c index 0c342e1ae..06c3327da 100644 --- a/xorg-server/hw/xwin/wincreatewnd.c +++ b/xorg-server/hw/xwin/wincreatewnd.c @@ -95,13 +95,17 @@ winCreateBoundingWindowFullScreen (ScreenPtr pScreen) g_pszQueryHost, display, (int) pScreenInfo->dwScreen); - else + else + { + char HostName[256]; + gethostname(HostName,256); snprintf (szTitle, sizeof (szTitle), WINDOW_TITLE, + HostName, display, (int) pScreenInfo->dwScreen); - + } /* Create the window */ *phwnd = CreateWindowExA (0, /* Extended styles */ WINDOW_CLASS, /* Class name */ @@ -344,12 +348,17 @@ winCreateBoundingWindowWindowed (ScreenPtr pScreen) g_pszQueryHost, display, (int) pScreenInfo->dwScreen); - else + else + { + char HostName[256]; + gethostname(HostName,256); snprintf (szTitle, sizeof (szTitle), WINDOW_TITLE, + HostName, display, (int) pScreenInfo->dwScreen); + } /* Create the window */ *phwnd = CreateWindowExA (0, /* Extended styles */ diff --git a/xorg-server/hw/xwin/wincursor.c b/xorg-server/hw/xwin/wincursor.c index ce98162ef..ffea2e86c 100644 --- a/xorg-server/hw/xwin/wincursor.c +++ b/xorg-server/hw/xwin/wincursor.c @@ -51,6 +51,11 @@ extern Bool g_fSoftwareCursor; # define WIN_DEBUG_MSG(...) #endif +#ifdef _MSC_VER +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + /* * Local function prototypes */ @@ -558,7 +563,7 @@ static void winDeviceCursorCleanup(DeviceIntPtr pDev, ScreenPtr pScr) { winScreenPriv(pScr); - return pScreenPriv->cursor.spriteFuncs->DeviceCursorCleanup(pDev, pScr); + pScreenPriv->cursor.spriteFuncs->DeviceCursorCleanup(pDev, pScr); } static miPointerSpriteFuncRec winSpriteFuncsRec = { @@ -617,9 +622,11 @@ winInitCursor (ScreenPtr pScreen) pPointPriv = (miPointerScreenPtr) dixLookupPrivate(&pScreen->devPrivates, miPointerScreenKey); + if (pPointPriv) + { pScreenPriv->cursor.spriteFuncs = pPointPriv->spriteFuncs; pPointPriv->spriteFuncs = &winSpriteFuncsRec; - + } pScreenPriv->cursor.handle = NULL; pScreenPriv->cursor.visible = FALSE; diff --git a/xorg-server/hw/xwin/windialogs.c b/xorg-server/hw/xwin/windialogs.c index 31a3766a6..1c7465d1e 100644 --- a/xorg-server/hw/xwin/windialogs.c +++ b/xorg-server/hw/xwin/windialogs.c @@ -116,8 +116,8 @@ winDrawURLWindow (LPARAM lParam) crText = RGB(0,0,128+64); SetTextColor (draw->hDC, crText); - /* Create underlined font 14 high, standard dialog font */ - font = CreateFont (-14, 0, 0, 0, FW_NORMAL, FALSE, TRUE, FALSE, + /* Create font 8 high, standard dialog font */ + font = CreateFont (-8, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, 0, 0, 0, 0, 0, "MS Sans Serif"); if (!font) { @@ -214,8 +214,8 @@ winInitDialog (HWND hwndDlg) */ if (GetSystemMetrics(SM_CMONITORS)>1) { /* Still need to refresh the frame change. */ - SetWindowPos (hwndDlg, HWND_TOPMOST, 0,0,0,0, - SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED); + SetWindowPos (hwndDlg, HWND_TOP, 0,0,0,0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); } else { GetWindowRect (hwndDesk, &rcDesk); GetWindowRect (hwndDlg, &rcDlg); @@ -254,12 +254,8 @@ winInitDialog (HWND hwndDlg) } -/* - * Display the Exit dialog box - */ - -void -winDisplayExitDialog (winPrivScreenPtr pScreenPriv) +int +GetLiveClients (winPrivScreenPtr pScreenPriv) { int i; int liveClients = 0; @@ -280,7 +276,21 @@ winDisplayExitDialog (winPrivScreenPtr pScreenPriv) /* A user reported that this sometimes drops below zero. just eye-candy. */ if (liveClients < 0) - liveClients = 0; + liveClients = 0; + + pScreenPriv->iConnectedClients = liveClients; + + return liveClients; +} + +/* + * Display the Exit dialog box + */ + +void +winDisplayExitDialog (winPrivScreenPtr pScreenPriv) +{ + int liveClients = GetLiveClients(pScreenPriv); /* Don't show the exit confirmation dialog if SilentExit is enabled */ if (pref.fSilentExit && liveClients <= 0) @@ -294,8 +304,6 @@ winDisplayExitDialog (winPrivScreenPtr pScreenPriv) return; } - pScreenPriv->iConnectedClients = liveClients; - /* Check if dialog already exists */ if (g_hDlgExit != NULL) { @@ -323,7 +331,7 @@ winDisplayExitDialog (winPrivScreenPtr pScreenPriv) /* Set focus to the Cancel button */ PostMessage (g_hDlgExit, WM_NEXTDLGCTL, - GetDlgItem (g_hDlgExit, IDCANCEL), TRUE); + (WPARAM)GetDlgItem (g_hDlgExit, IDCANCEL), TRUE); } #define CONNECTED_CLIENTS_FORMAT "There are currently %d clients connected." @@ -591,7 +599,7 @@ winDisplayAboutDialog (winPrivScreenPtr pScreenPriv) /* Set focus to the OK button */ PostMessage (g_hDlgAbout, WM_NEXTDLGCTL, - GetDlgItem (g_hDlgAbout, IDOK), TRUE); + (WPARAM)GetDlgItem (g_hDlgAbout, IDOK), TRUE); } @@ -672,7 +680,7 @@ winAboutDlgProc (HWND hwndDialog, UINT message, case ID_ABOUT_CHANGELOG: { - HINSTANCE iReturn; + int iReturn; #ifdef __CYGWIN__ const char * pszCygPath = "/usr/X11R6/share/doc/" "xorg-x11-xwin/changelog.html"; @@ -685,7 +693,7 @@ winAboutDlgProc (HWND hwndDialog, UINT message, "devel/server/changelog.html"; #endif - iReturn = ShellExecute (NULL, + iReturn = (int)ShellExecute (NULL, "open", pszWinPath, NULL, @@ -702,10 +710,10 @@ winAboutDlgProc (HWND hwndDialog, UINT message, case ID_ABOUT_WEBSITE: { - const char * pszPath = "http://x.cygwin.com/"; + const char * pszPath = __VENDORDWEBSUPPORT__; int iReturn; - iReturn = ShellExecute (NULL, + iReturn = (int)ShellExecute (NULL, "open", pszPath, NULL, @@ -725,7 +733,7 @@ winAboutDlgProc (HWND hwndDialog, UINT message, const char * pszPath = "http://x.cygwin.com/docs/ug/"; int iReturn; - iReturn = ShellExecute (NULL, + iReturn = (int)ShellExecute (NULL, "open", pszPath, NULL, @@ -745,7 +753,7 @@ winAboutDlgProc (HWND hwndDialog, UINT message, const char * pszPath = "http://x.cygwin.com/docs/faq/"; int iReturn; - iReturn = ShellExecute (NULL, + iReturn = (int)ShellExecute (NULL, "open", pszPath, NULL, diff --git a/xorg-server/hw/xwin/winerror.c b/xorg-server/hw/xwin/winerror.c index 72ee2cfb7..78ac15117 100644 --- a/xorg-server/hw/xwin/winerror.c +++ b/xorg-server/hw/xwin/winerror.c @@ -43,7 +43,8 @@ extern char * g_pszCommandLine; extern char * g_pszLogFile; extern Bool g_fSilentFatalError; - +extern Bool g_fSilentDupError; +extern Bool g_fLogInited; #ifdef DDXOSVERRORF /* Prototype */ @@ -62,6 +63,24 @@ OsVendorVErrorF (const char *pszFormat, va_list va_args) pthread_mutex_lock (&s_pmPrinting); #endif + /* + If we want to silence it, + detect if we are going to abort due to duplication error + */ + if (g_fSilentDupError) + { + if ((strcmp(pszFormat, + "InitOutput - Duplicate invocation on display " + "number: %s. Exiting.\n") == 0) + || (strcmp(pszFormat, + "Server is already active for display %s\n%s %s\n%s\n") == 0) + || (strcmp(pszFormat, + "MakeAllCOTSServerListeners: server already running\n") == 0)) + { + g_fSilentFatalError = TRUE; + } + } + /* Print the error message to a log file, could be stderr */ LogVWrite (0, pszFormat, va_args); @@ -87,6 +106,12 @@ OsVendorFatalError (void) if (g_fSilentFatalError) return; + if (!g_fLogInited) { + g_fLogInited = TRUE; + g_pszLogFile = LogInit (g_pszLogFile, NULL); + } + LogClose (); + winMessageBoxF ( "A fatal error has occurred and " PROJECT_NAME " will now exit.\n" \ "Please open %s for more information.\n", diff --git a/xorg-server/hw/xwin/winglobals.c b/xorg-server/hw/xwin/winglobals.c index 3eb6091e6..280761e72 100644 --- a/xorg-server/hw/xwin/winglobals.c +++ b/xorg-server/hw/xwin/winglobals.c @@ -1,5 +1,6 @@ /* *Copyright (C) 2003-2004 Harold L Hunt II All Rights Reserved. + *Copyright (C) Colin Harrison 2005-2008 * *Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the @@ -26,6 +27,7 @@ *from Harold L Hunt II. * * Authors: Harold L Hunt II + * Colin Harrison */ #ifdef HAVE_XWIN_CONFIG_H @@ -63,10 +65,11 @@ HWND g_hDlgExit = NULL; HWND g_hDlgAbout = NULL; const char * g_pszQueryHost = NULL; Bool g_fXdmcpEnabled = FALSE; +Bool g_fAuthEnabled = FALSE; HICON g_hIconX = NULL; HICON g_hSmallIconX = NULL; #ifndef RELOCATE_PROJECTROOT -char * g_pszLogFile = "/tmp/XWin.log"; +char * g_pszLogFile = DEFAULT_LOGDIR "/XWin.%s.log"; #else char * g_pszLogFile = "XWin.log"; Bool g_fLogFileChanged = FALSE; diff --git a/xorg-server/hw/xwin/winkeybd.c b/xorg-server/hw/xwin/winkeybd.c index 611ea5d55..5d0f58442 100644 --- a/xorg-server/hw/xwin/winkeybd.c +++ b/xorg-server/hw/xwin/winkeybd.c @@ -75,6 +75,20 @@ winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode) int iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2]; int iParamScanCode = LOBYTE (HIWORD (lParam)); +/* WM_ key messages faked by Vista speech recognition (WSR) don't have a + * scan code. + * + * Vocola 3 (Rick Mohr's supplement to WSR) uses + * System.Windows.Forms.SendKeys.SendWait(), which appears always to give a + * scan code of 1 + */ + if (iParamScanCode <= 1) + { + iParamScanCode = MapVirtualKeyEx(wParam, + /*MAPVK_VK_TO_VSC*/0, + GetKeyboardLayout(0)); + } + /* Branch on special extended, special non-extended, or normal key */ if ((HIWORD (lParam) & KF_EXTENDED) && iKeyFixupEx) *piScanCode = iKeyFixupEx; @@ -248,6 +262,7 @@ winKeybdProc (DeviceIntPtr pDeviceInt, int iState) winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat\n"); } + XkbSetExtension(pDeviceInt, ProcessKeyboardEvent); break; case DEVICE_ON: diff --git a/xorg-server/hw/xwin/winkeybd.h b/xorg-server/hw/xwin/winkeybd.h index 09eed1491..d5b115736 100644 --- a/xorg-server/hw/xwin/winkeybd.h +++ b/xorg-server/hw/xwin/winkeybd.h @@ -45,6 +45,11 @@ #define WIN_KEYMAP_COLS 3 +/* ASCII column, rows 33 through 40 are for Speech Recognition with + * num-lock asserted. + * Rows 160 through 165 correspond to software-generated codes, which + * may not be associated with the appropriate scan code/extended bit + */ const int g_iKeyMap [] = { /* count Windows VK, ASCII, ASCII when extended VK */ @@ -81,14 +86,14 @@ g_iKeyMap [] = { /* 30 */ 0, 0, 0, /* 31 */ 0, 0, 0, /* 32 */ 0, 0, 0, - /* 33 */ VK_PRIOR, 0, KEY_PgUp, - /* 34 */ VK_NEXT, 0, KEY_PgDown, - /* 35 */ VK_END, 0, KEY_End, - /* 36 */ VK_HOME, 0, KEY_Home, - /* 37 */ VK_LEFT, 0, KEY_Left, - /* 38 */ VK_UP, 0, KEY_Up, - /* 39 */ VK_RIGHT, 0, KEY_Right, - /* 40 */ VK_DOWN, 0, KEY_Down, + /* 33 */ VK_PRIOR, KEY_PgUp, KEY_PgUp, + /* 34 */ VK_NEXT, KEY_PgDown, KEY_PgDown, + /* 35 */ VK_END, KEY_End, KEY_End, + /* 36 */ VK_HOME, KEY_Home, KEY_Home, + /* 37 */ VK_LEFT, KEY_Left, KEY_Left, + /* 38 */ VK_UP, KEY_Up, KEY_Up, + /* 39 */ VK_RIGHT, KEY_Right, KEY_Right, + /* 40 */ VK_DOWN, KEY_Down, KEY_Down, /* 41 */ 0, 0, 0, /* 42 */ 0, 0, 0, /* 43 */ 0, 0, 0, @@ -208,12 +213,12 @@ g_iKeyMap [] = { /* 157 */ 0, 0, 0, /* 158 */ 0, 0, 0, /* 159 */ 0, 0, 0, - /* 160 */ 0, 0, 0, - /* 161 */ 0, 0, 0, - /* 162 */ 0, 0, 0, - /* 163 */ 0, 0, 0, - /* 164 */ 0, 0, 0, - /* 165 */ 0, 0, 0, + /* 160 */ VK_LSHIFT, KEY_ShiftL, KEY_ShiftL, + /* 161 */ VK_RSHIFT, KEY_ShiftR, KEY_ShiftR, + /* 162 */ VK_LCONTROL, KEY_LCtrl, KEY_LCtrl, + /* 163 */ VK_RCONTROL, KEY_RCtrl, KEY_RCtrl, + /* 164 */ VK_LMENU, KEY_Alt, KEY_Alt, + /* 165 */ VK_RMENU, KEY_AltLang, KEY_AltLang, /* 166 */ 0, 0, 0, /* 167 */ 0, 0, 0, /* 168 */ 0, 0, 0, diff --git a/xorg-server/hw/xwin/winlayouts.h b/xorg-server/hw/xwin/winlayouts.h index d1d21a12d..193cc1a41 100644 --- a/xorg-server/hw/xwin/winlayouts.h +++ b/xorg-server/hw/xwin/winlayouts.h @@ -61,6 +61,7 @@ WinKBLayoutRec winKBLayouts[] = { 0x40b, -1, "pc105", "fi", NULL, NULL, "Finnish"}, { 0x40c, -1, "pc105", "fr", NULL, NULL, "French (Standard)"}, { 0x80c, -1, "pc105", "be", NULL, NULL, "French (Belgian)"}, + {0x1080c, -1, "pc105", "be", NULL, NULL, "Belgian (Comma)"}, { 0xc0c, -1, "pc105", "ca", "fr", NULL, "French (Canada)"}, { 0x100c, -1, "pc105", "ch", "fr", NULL, "French (Switzerland)"}, { 0x40d, -1, "pc105", "il", NULL, NULL, "Hebrew"}, @@ -163,6 +164,7 @@ Support ID XKB Language Finnish (with Sami) X 0x040c fr French (Standard) X 0x080c be French (Belgian) + X 0x1080c be Belgian (Comma) . 0x0c0c French (Canadian) French (Canadian, Legacy) Canadian (Multilingual) diff --git a/xorg-server/hw/xwin/winmouse.c b/xorg-server/hw/xwin/winmouse.c index b537d3213..3c7b46d6c 100644 --- a/xorg-server/hw/xwin/winmouse.c +++ b/xorg-server/hw/xwin/winmouse.c @@ -36,14 +36,19 @@ #endif #include "win.h" -#if defined(XFree86Server) +#ifdef XKB +#ifndef XKB_IN_SERVER +#define XKB_IN_SERVER +#endif +#include <xkbsrv.h> +#endif + #include "inputstr.h" #include "exevents.h" /* for button/axes labels */ #include "xserver-properties.h" /* Peek the internal button mapping */ static CARD8 const *g_winMouseButtonMap = NULL; -#endif /* @@ -123,9 +128,7 @@ winMouseProc (DeviceIntPtr pDeviceInt, int iState) free(map); free(btn_labels); -#if defined(XFree86Server) g_winMouseButtonMap = pDeviceInt->button->map; -#endif break; case DEVICE_ON: @@ -133,9 +136,7 @@ winMouseProc (DeviceIntPtr pDeviceInt, int iState) break; case DEVICE_CLOSE: -#if defined(XFree86Server) g_winMouseButtonMap = NULL; -#endif case DEVICE_OFF: pDevice->on = FALSE; break; @@ -241,10 +242,8 @@ winMouseButtonsSendEvent (int iEventType, int iButton) EventListPtr events; int i, nevents; -#if defined(XFree86Server) if (g_winMouseButtonMap) iButton = g_winMouseButtonMap[iButton]; -#endif GetEventList(&events); nevents = GetPointerEvents(events, g_pwinPointer, iEventType, iButton, @@ -371,12 +370,12 @@ winMouseButtonsHandle (ScreenPtr pScreen, */ void winEnqueueMotion(int x, int y) { - miPointerSetPosition(g_pwinPointer, &x, &y); - int i, nevents; int valuators[2]; EventListPtr events; + + miPointerSetPosition(g_pwinPointer, &x, &y); GetEventList(&events); valuators[0] = x; diff --git a/xorg-server/hw/xwin/winmsg.c b/xorg-server/hw/xwin/winmsg.c index d0464f71b..ded641b77 100644 --- a/xorg-server/hw/xwin/winmsg.c +++ b/xorg-server/hw/xwin/winmsg.c @@ -98,6 +98,7 @@ winErrorFVerb (int verb, const char *format, ...) va_end (ap); } +#if !defined(_MSC_VER) || defined(_DEBUG) void winDebug (const char *format, ...) { @@ -106,6 +107,7 @@ winDebug (const char *format, ...) LogVMessageVerb(X_NONE, 3, format, ap); va_end (ap); } +#endif void winTrace (const char *format, ...) diff --git a/xorg-server/hw/xwin/winmsg.h b/xorg-server/hw/xwin/winmsg.h index 611dd6962..91da7ab1f 100644 --- a/xorg-server/hw/xwin/winmsg.h +++ b/xorg-server/hw/xwin/winmsg.h @@ -39,7 +39,12 @@ void winDrvMsgVerb (int scrnIndex, void winDrvMsg (int scrnIndex, MessageType type, const char *format, ...); void winMsgVerb (MessageType type, int verb, const char *format, ...); void winMsg (MessageType type, const char *format, ...); +#if !defined(_MSC_VER) || defined(_DEBUG) void winDebug (const char *format, ...); +#else +#define winDebug(...) +#endif + void winTrace (const char *format, ...); void winErrorFVerb (int verb, const char *format, ...); diff --git a/xorg-server/hw/xwin/winmultiwindowicons.c b/xorg-server/hw/xwin/winmultiwindowicons.c index e16b2a3c8..11ae40159 100644 --- a/xorg-server/hw/xwin/winmultiwindowicons.c +++ b/xorg-server/hw/xwin/winmultiwindowicons.c @@ -544,6 +544,7 @@ winUpdateIcon (Window id) pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW); if (!pWin) return; + { winWindowPriv(pWin); if (pWinPriv->hWnd) { hIcon = winOverrideIcon ((unsigned long)pWin); @@ -569,7 +570,7 @@ winUpdateIcon (Window id) hIconOld = (HICON) SendMessage (pWinPriv->hWnd, WM_SETICON, ICON_SMALL, (LPARAM) hIconSmall); winDestroyIcon(hIconOld); - + } } } diff --git a/xorg-server/hw/xwin/winmultiwindowshape.c b/xorg-server/hw/xwin/winmultiwindowshape.c index 44007027a..28870646c 100644 --- a/xorg-server/hw/xwin/winmultiwindowshape.c +++ b/xorg-server/hw/xwin/winmultiwindowshape.c @@ -71,6 +71,9 @@ winUpdateRgnMultiWindow (WindowPtr pWin) { SetWindowRgn (winGetWindowPriv(pWin)->hWnd, winGetWindowPriv(pWin)->hRgn, TRUE); + + /* The system now owns the region specified by the region handle and delete it when it is no longer needed. */ + winGetWindowPriv(pWin)->hRgn = NULL; } @@ -206,3 +209,14 @@ winReshapeMultiWindow (WindowPtr pWin) return; } + +void +winShapeRgnUpdateMultiwindow(HWND hwnd) +{ + WindowPtr pWin = GetProp (hwnd, WIN_WINDOW_PROP); + if (pWin) + { + winReshapeMultiWindow(pWin); + winUpdateRgnMultiWindow(pWin); + } +} diff --git a/xorg-server/hw/xwin/winmultiwindowwindow.c b/xorg-server/hw/xwin/winmultiwindowwindow.c index e2b5ed291..fa2e09e34 100644 --- a/xorg-server/hw/xwin/winmultiwindowwindow.c +++ b/xorg-server/hw/xwin/winmultiwindowwindow.c @@ -99,7 +99,7 @@ void winInitMultiWindowClass(void) wcx.hIconSm = g_hSmallIconX; #if CYGMULTIWINDOW_DEBUG - ErrorF ("winCreateWindowsWindow - Creating class: %s\n", WINDOW_CLASS_X); + winDebug ("winCreateWindowsWindow - Creating class: %s\n", WINDOW_CLASS_X); #endif atomXWinClass = RegisterClassEx (&wcx); @@ -119,7 +119,7 @@ winCreateWindowMultiWindow (WindowPtr pWin) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - winTrace ("winCreateWindowMultiWindow - pWin: %p\n", pWin); + winDebug ("winCreateWindowMultiWindow - pWin: %p\n", pWin); #endif WIN_UNWRAP(CreateWindow); @@ -149,7 +149,7 @@ winDestroyWindowMultiWindow (WindowPtr pWin) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winDestroyWindowMultiWindow - pWin: %p\n", pWin); + winDebug ("winDestroyWindowMultiWindow - pWin: %p\n", pWin); #endif WIN_UNWRAP(DestroyWindow); @@ -194,7 +194,7 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) DWORD dwStyle; #if CYGMULTIWINDOW_DEBUG - winTrace ("winPositionWindowMultiWindow - pWin: %p\n", pWin); + winDebug ("winPositionWindowMultiWindow - pWin: %p\n", pWin); #endif WIN_UNWRAP(PositionWindow); @@ -202,7 +202,7 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) WIN_WRAP(PositionWindow, winPositionWindowMultiWindow); #if CYGWINDOWING_DEBUG - ErrorF ("winPositionWindowMultiWindow: (x, y) = (%d, %d)\n", + winDebug ("winPositionWindowMultiWindow: (x, y) = (%d, %d)\n", x, y); #endif @@ -210,7 +210,7 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) if (!hWnd) { #if CYGWINDOWING_DEBUG - ErrorF ("\timmediately return since hWnd is NULL\n"); + winDebug ("\timmediately return since hWnd is NULL\n"); #endif return fResult; } @@ -232,7 +232,7 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) #if CYGMULTIWINDOW_DEBUG lpRc = &rcNew; - ErrorF ("winPositionWindowMultiWindow - (%d ms)drawable (%d, %d)-(%d, %d)\n", + winDebug ("winPositionWindowMultiWindow - (%d ms)drawable (%d, %d)-(%d, %d)\n", GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom); #endif @@ -250,15 +250,15 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) GetClientRect (hWnd, &rcClient); lpRc = &rcNew; - ErrorF ("winPositionWindowMultiWindow - (%d ms)rcNew (%d, %d)-(%d, %d)\n", + winDebug ("winPositionWindowMultiWindow - (%d ms)rcNew (%d, %d)-(%d, %d)\n", GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom); lpRc = &rcOld; - ErrorF ("winPositionWindowMultiWindow - (%d ms)rcOld (%d, %d)-(%d, %d)\n", + winDebug ("winPositionWindowMultiWindow - (%d ms)rcOld (%d, %d)-(%d, %d)\n", GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom); lpRc = &rcClient; - ErrorF ("(%d ms)rcClient (%d, %d)-(%d, %d)\n", + winDebug ("(%d ms)rcClient (%d, %d)-(%d, %d)\n", GetTickCount (), lpRc->left, lpRc->top, lpRc->right, lpRc->bottom); #endif @@ -266,11 +266,11 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) if (!EqualRect (&rcNew, &rcOld)) { #if CYGMULTIWINDOW_DEBUG - ErrorF ("winPositionWindowMultiWindow - Need to move\n"); + winDebug ("winPositionWindowMultiWindow - Need to move\n"); #endif #if CYGWINDOWING_DEBUG - ErrorF ("\tMoveWindow to (%ld, %ld) - %ldx%ld\n", rcNew.left, rcNew.top, + winDebug ("\tMoveWindow to (%ld, %ld) - %ldx%ld\n", rcNew.left, rcNew.top, rcNew.right - rcNew.left, rcNew.bottom - rcNew.top); #endif /* Change the position and dimensions of the Windows window */ @@ -282,7 +282,7 @@ winPositionWindowMultiWindow (WindowPtr pWin, int x, int y) else { #if CYGMULTIWINDOW_DEBUG - ErrorF ("winPositionWindowMultiWindow - Not need to move\n"); + winDebug ("winPositionWindowMultiWindow - Not need to move\n"); #endif } @@ -302,7 +302,7 @@ winChangeWindowAttributesMultiWindow (WindowPtr pWin, unsigned long mask) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winChangeWindowAttributesMultiWindow - pWin: %08x\n", pWin); + winDebug ("winChangeWindowAttributesMultiWindow - pWin: %08x\n", pWin); #endif WIN_UNWRAP(ChangeWindowAttributes); @@ -331,7 +331,7 @@ winUnmapWindowMultiWindow (WindowPtr pWin) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winUnmapWindowMultiWindow - pWin: %08x\n", pWin); + winDebug ("winUnmapWindowMultiWindow - pWin: %08x\n", pWin); #endif WIN_UNWRAP(UnrealizeWindow); @@ -362,7 +362,7 @@ winMapWindowMultiWindow (WindowPtr pWin) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winMapWindowMultiWindow - pWin: %08x\n", pWin); + winDebug ("winMapWindowMultiWindow - pWin: %08x\n", pWin); #endif WIN_UNWRAP(RealizeWindow); @@ -394,7 +394,7 @@ winReparentWindowMultiWindow (WindowPtr pWin, WindowPtr pPriorParent) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winReparentMultiWindow - pWin: %08x\n", pWin); + winDebug ("winReparentMultiWindow - pWin: %08x\n", pWin); #endif WIN_UNWRAP(ReparentWindow); @@ -424,7 +424,7 @@ winRestackWindowMultiWindow (WindowPtr pWin, WindowPtr pOldNextSib) winScreenPriv(pScreen); #if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG - winTrace ("winRestackMultiWindow - %08x\n", pWin); + winDebug ("winRestackMultiWindow - %08x\n", pWin); #endif WIN_UNWRAP(RestackWindow); @@ -518,7 +518,7 @@ winCreateWindowsWindow (WindowPtr pWin) winInitMultiWindowClass(); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winCreateWindowsWindow - pWin: %08x\n", pWin); + winDebug ("winCreateWindowsWindow - pWin: %08x\n", pWin); #endif iX = pWin->drawable.x + GetSystemMetrics (SM_XVIRTUALSCREEN); @@ -607,7 +607,7 @@ winDestroyWindowsWindow (WindowPtr pWin) BOOL oldstate = winInDestroyWindowsWindow; #if CYGMULTIWINDOW_DEBUG - ErrorF ("winDestroyWindowsWindow\n"); + winDebug ("winDestroyWindowsWindow\n"); #endif /* Bail out if the Windows window handle is invalid */ @@ -635,7 +635,7 @@ winDestroyWindowsWindow (WindowPtr pWin) winInDestroyWindowsWindow = oldstate; #if CYGMULTIWINDOW_DEBUG - ErrorF ("-winDestroyWindowsWindow\n"); + winDebug ("-winDestroyWindowsWindow\n"); #endif } @@ -652,7 +652,7 @@ winUpdateWindowsWindow (WindowPtr pWin) HWND hWnd = pWinPriv->hWnd; #if CYGMULTIWINDOW_DEBUG - ErrorF ("winUpdateWindowsWindow\n"); + winDebug ("winUpdateWindowsWindow\n"); #endif /* Check if the Windows window's parents have been destroyed */ @@ -681,7 +681,7 @@ winUpdateWindowsWindow (WindowPtr pWin) } #if CYGMULTIWINDOW_DEBUG - ErrorF ("-winUpdateWindowsWindow\n"); + winDebug ("-winUpdateWindowsWindow\n"); #endif } @@ -700,7 +700,7 @@ winGetWindowID (WindowPtr pWin) FindClientResourcesByType (c, RT_WINDOW, winFindWindow, &wi); #if CYGMULTIWINDOW_DEBUG - ErrorF ("winGetWindowID - Window ID: %d\n", wi.id); + winDebug ("winGetWindowID - Window ID: %d\n", wi.id); #endif return wi.id; @@ -739,14 +739,14 @@ winReorderWindowsMultiWindow (void) DWORD dwWindowProcessID = 0; #if CYGMULTIWINDOW_DEBUG || CYGWINDOWING_DEBUG - winTrace ("winReorderWindowsMultiWindow\n"); + winDebug ("winReorderWindowsMultiWindow\n"); #endif if (fRestacking) { /* It is a recusive call so immediately exit */ #if CYGWINDOWING_DEBUG - ErrorF ("winReorderWindowsMultiWindow - " + winDebug ("winReorderWindowsMultiWindow - " "exit because fRestacking == TRUE\n"); #endif return; @@ -807,7 +807,7 @@ winMinimizeWindow (Window id) winScreenInfo *pScreenInfo = NULL; #if CYGWINDOWING_DEBUG - ErrorF ("winMinimizeWindow\n"); + winDebug ("winMinimizeWindow\n"); #endif pWin = (WindowPtr) LookupIDByType (id, RT_WINDOW); @@ -851,7 +851,7 @@ winCopyWindowMultiWindow (WindowPtr pWin, DDXPointRec oldpt, winScreenPriv(pScreen); #if CYGWINDOWING_DEBUG - ErrorF ("CopyWindowMultiWindow\n"); + winDebug ("CopyWindowMultiWindow\n"); #endif WIN_UNWRAP(CopyWindow); (*pScreen->CopyWindow)(pWin, oldpt, oldRegion); @@ -870,7 +870,7 @@ winMoveWindowMultiWindow (WindowPtr pWin, int x, int y, winScreenPriv(pScreen); #if CYGWINDOWING_DEBUG - ErrorF ("MoveWindowMultiWindow to (%d, %d)\n", x, y); + winDebug ("MoveWindowMultiWindow to (%d, %d)\n", x, y); #endif WIN_UNWRAP(MoveWindow); @@ -890,7 +890,7 @@ winResizeWindowMultiWindow (WindowPtr pWin, int x, int y, unsigned int w, winScreenPriv(pScreen); #if CYGWINDOWING_DEBUG - ErrorF ("ResizeWindowMultiWindow to (%d, %d) - %dx%d\n", x, y, w, h); + winDebug ("ResizeWindowMultiWindow to (%d, %d) - %dx%d\n", x, y, w, h); #endif WIN_UNWRAP(ResizeWindow); (*pScreen->ResizeWindow)(pWin, x, y, w, h, pSib); @@ -922,13 +922,13 @@ winAdjustXWindow (WindowPtr pWin, HWND hwnd) #define HEIGHT(rc) (rc.bottom - rc.top) #if CYGWINDOWING_DEBUG - ErrorF ("winAdjustXWindow\n"); + winDebug ("winAdjustXWindow\n"); #endif if (IsIconic (hwnd)) { #if CYGWINDOWING_DEBUG - ErrorF ("\timmediately return because the window is iconized\n"); + winDebug ("\timmediately return because the window is iconized\n"); #endif /* * If the Windows window is minimized, its WindowRect has @@ -971,7 +971,7 @@ winAdjustXWindow (WindowPtr pWin, HWND hwnd) if (EqualRect (&rcDraw, &rcWin)) { /* Bail if no adjust is needed */ #if CYGWINDOWING_DEBUG - ErrorF ("\treturn because already adjusted\n"); + winDebug ("\treturn because already adjusted\n"); #endif return 0; } @@ -993,7 +993,7 @@ winAdjustXWindow (WindowPtr pWin, HWND hwnd) vlist[2] = pDraw->width + dW; vlist[3] = pDraw->height + dH; #if CYGWINDOWING_DEBUG - ErrorF ("\tConfigureWindow to (%ld, %ld) - %ldx%ld\n", vlist[0], vlist[1], + winDebug ("\tConfigureWindow to (%ld, %ld) - %ldx%ld\n", vlist[0], vlist[1], vlist[2], vlist[3]); #endif return ConfigureWindow (pWin, CWX | CWY | CWWidth | CWHeight, diff --git a/xorg-server/hw/xwin/winmultiwindowwm.c b/xorg-server/hw/xwin/winmultiwindowwm.c index 18d9aedc2..7d29fc5c2 100644 --- a/xorg-server/hw/xwin/winmultiwindowwm.c +++ b/xorg-server/hw/xwin/winmultiwindowwm.c @@ -36,13 +36,18 @@ #endif #include <stdio.h> #include <stdlib.h> +#ifndef _MSC_VER #include <unistd.h> +#endif #ifdef __CYGWIN__ #include <sys/select.h> #endif #include <fcntl.h> #include <setjmp.h> #define HANDLE void * +#ifdef _MSC_VER +typedef int pid_t; +#endif #include <pthread.h> #undef HANDLE #include <X11/X.h> @@ -61,6 +66,7 @@ #include "winprefs.h" #include "window.h" #include "pixmapstr.h" +#include "winmsg.h" #include "windowstr.h" #ifdef XWIN_MULTIWINDOWEXTWM @@ -90,6 +96,7 @@ extern void winUpdateRgnMultiWindow(WindowPtr pWin); #endif #define WIN_JMP_OKAY 0 #define WIN_JMP_ERROR_IO 2 +#define AUTH_NAME "MIT-MAGIC-COOKIE-1" /* @@ -139,6 +146,10 @@ typedef struct _XMsgProcArgRec { extern char *display; extern void ErrorF (const char* /*f*/, ...); +#if defined(XCSECURITY) +extern unsigned int g_uiAuthDataLen; +extern char *g_pAuthData; +#endif /* @@ -155,7 +166,7 @@ static Bool InitQueue (WMMsgQueuePtr pQueue); static void -GetWindowName (Display * pDpy, Window iWin, char **ppName); +GetWindowName (Display * pDpy, Window iWin, wchar_t **ppName); static int SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData); @@ -418,10 +429,12 @@ InitQueue (WMMsgQueuePtr pQueue) */ static void -GetWindowName (Display *pDisplay, Window iWin, char **ppName) +GetWindowName (Display *pDisplay, Window iWin, wchar_t **ppName) { int nResult, nNum; char **ppList; + char *pszReturnData; + int iLen, i; XTextProperty xtpName; #if CYGMULTIWINDOW_DEBUG @@ -440,38 +453,26 @@ GetWindowName (Display *pDisplay, Window iWin, char **ppName) #endif return; } - - /* */ - if (xtpName.encoding == XA_STRING) - { - /* */ - if (xtpName.value) - { - int size = xtpName.nitems * (xtpName.format >> 3); - *ppName = malloc(size + 1); - strncpy(*ppName, xtpName.value, size); - (*ppName)[size] = 0; - XFree (xtpName.value); - } - -#if CYGMULTIWINDOW_DEBUG - ErrorF ("GetWindowName - XA_STRING %s\n", *ppName); -#endif - } - else - { - if (XmbTextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList) - { - *ppName = strdup (*ppList); - XFreeStringList (ppList); - } - XFree (xtpName.value); -#if CYGMULTIWINDOW_DEBUG - ErrorF ("GetWindowName - %s %s\n", - XGetAtomName (pDisplay, xtpName.encoding), *ppName); -#endif - } + if (Xutf8TextPropertyToTextList (pDisplay, &xtpName, &ppList, &nNum) >= Success && nNum > 0 && *ppList) + { + iLen = 0; + for (i = 0; i < nNum; i++) iLen += strlen(ppList[i]); + pszReturnData = (char *) malloc (iLen + 1); + pszReturnData[0] = '\0'; + for (i = 0; i < nNum; i++) strcat (pszReturnData, ppList[i]); + } + else + { + pszReturnData = (char *) malloc (1); + pszReturnData[0] = '\0'; + } + iLen = MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, NULL, 0); + *ppName = (wchar_t*)malloc(sizeof(wchar_t)*(iLen + 1)); + MultiByteToWideChar (CP_UTF8, 0, pszReturnData, -1, *ppName, iLen); + XFree (xtpName.value); + if (ppList) XFreeStringList (ppList); + free (pszReturnData); #if CYGMULTIWINDOW_DEBUG ErrorF ("GetWindowName - Returning\n"); @@ -508,7 +509,7 @@ SendXMessage (Display *pDisplay, Window iWin, Atom atmType, long nData) static void UpdateName (WMInfoPtr pWMInfo, Window iWindow) { - char *pszName; + wchar_t *pszName; Atom atmType; int fmtRet; unsigned long items, remain; @@ -552,7 +553,7 @@ UpdateName (WMInfoPtr pWMInfo, Window iWindow) &attr); if (!attr.override_redirect) { - SetWindowText (hWnd, pszName); + SetWindowTextW (hWnd, pszName); winUpdateIcon (iWindow); } @@ -720,6 +721,11 @@ winMultiWindowWMProc (void *pArg) 1); UpdateName (pWMInfo, pNode->msg.iWindow); winUpdateIcon (pNode->msg.iWindow); + { + HWND zstyle = HWND_NOTOPMOST; + winApplyHints (pWMInfo->pDisplay, pNode->msg.iWindow, pNode->msg.hwndWindow, &zstyle); + winUpdateWindowPosition (pNode->msg.hwndWindow, TRUE, &zstyle); + } break; case WM_WM_MAP2: @@ -895,13 +901,6 @@ winMultiWindowXMsgProc (void *pArg) ErrorF ("winMultiWindowXMsgProc - pthread_mutex_lock () returned.\n"); - /* Allow multiple threads to access Xlib */ - if (XInitThreads () == 0) - { - ErrorF ("winMultiWindowXMsgProc - XInitThreads () failed. Exiting.\n"); - pthread_exit (NULL); - } - /* See if X supports the current locale */ if (XSupportsLocale () == False) { @@ -1224,13 +1223,6 @@ winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg) ErrorF ("winInitMultiWindowWM - pthread_mutex_lock () returned.\n"); - /* Allow multiple threads to access Xlib */ - if (XInitThreads () == 0) - { - ErrorF ("winInitMultiWindowWM - XInitThreads () failed. Exiting.\n"); - pthread_exit (NULL); - } - /* See if X supports the current locale */ if (XSupportsLocale () == False) { @@ -1274,6 +1266,14 @@ winInitMultiWindowWM (WMInfoPtr pWMInfo, WMProcArgPtr pProcArg) /* Print the display connection string */ ErrorF ("winInitMultiWindowWM - DISPLAY=%s\n", pszDisplay); + +#if defined(XCSECURITY) + /* Use our generated cookie for authentication */ + XSetAuthorization (AUTH_NAME, + strlen (AUTH_NAME), + g_pAuthData, + g_uiAuthDataLen); +#endif /* Open the X display */ do @@ -1508,6 +1508,7 @@ winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle) int format; unsigned long hint = 0, maxmin = 0, style, nitems = 0 , left = 0; WindowPtr pWin = GetProp (hWnd, WIN_WINDOW_PROP); + MwmHints *mwm_hint = NULL; if (!hWnd) return; if (!IsWindow (hWnd)) return; @@ -1539,7 +1540,6 @@ winApplyHints (Display *pDisplay, Window iWindow, HWND hWnd, HWND *zstyle) } nitems = left = 0; - MwmHints *mwm_hint = NULL; if (XGetWindowProperty(pDisplay, iWindow, motif_wm_hints, 0L, PropMwmHintsElements, False, motif_wm_hints, &type, &format, &nitems, &left, (unsigned char **)&mwm_hint) == Success) diff --git a/xorg-server/hw/xwin/winmultiwindowwndproc.c b/xorg-server/hw/xwin/winmultiwindowwndproc.c index 543a1652f..6ac6c141c 100644 --- a/xorg-server/hw/xwin/winmultiwindowwndproc.c +++ b/xorg-server/hw/xwin/winmultiwindowwndproc.c @@ -42,6 +42,13 @@ #include "winmsg.h" #include "inputstr.h" +#ifdef XKB +#ifndef XKB_IN_SERVER +#define XKB_IN_SERVER +#endif +#include <xkbsrv.h> +#endif + /* * External global variables */ @@ -282,11 +289,11 @@ static void winRaiseWindow(WindowPtr pWin) if (!winInDestroyWindowsWindow && !winInRaiseWindow) { BOOL oldstate = winInRaiseWindow; + XID vlist[1] = { 0 }; winInRaiseWindow = TRUE; /* Call configure window directly to make sure it gets processed * in time */ - XID vlist[1] = { 0 }; ConfigureWindow(pWin, CWStackMode, vlist, serverClient); winInRaiseWindow = oldstate; } @@ -397,7 +404,9 @@ winTopLevelWindowProc (HWND hwnd, UINT message, switch (message) { case WM_CREATE: - +{ + RECT rWindow; + HRGN hRgnWindow; /* */ SetProp (hwnd, WIN_WINDOW_PROP, @@ -416,15 +425,13 @@ winTopLevelWindowProc (HWND hwnd, UINT message, winReorderWindowsMultiWindow (); /* Fix a 'round title bar corner background should be transparent not black' problem when first painted */ - RECT rWindow; - HRGN hRgnWindow; GetWindowRect(hwnd, &rWindow); hRgnWindow = CreateRectRgnIndirect(&rWindow); SetWindowRgn (hwnd, hRgnWindow, TRUE); DeleteObject(hRgnWindow); - SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)XMING_SIGNATURE); - + SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)VCXSRV_SIGNATURE); +} return 0; case WM_INIT_SYS_MENU: @@ -897,13 +904,13 @@ winTopLevelWindowProc (HWND hwnd, UINT message, } else /* It is an overridden window so make it top of Z stack */ { + HWND forHwnd = GetForegroundWindow(); #if CYGWINDOWING_DEBUG ErrorF ("overridden window is shown\n"); #endif - HWND forHwnd = GetForegroundWindow(); if (forHwnd != NULL) { - if (GetWindowLongPtr(forHwnd, GWLP_USERDATA) & (LONG_PTR)XMING_SIGNATURE) + if (GetWindowLongPtr(forHwnd, GWLP_USERDATA) & (LONG_PTR)VCXSRV_SIGNATURE) { if (GetWindowLongPtr(forHwnd, GWL_EXSTYLE) & WS_EX_TOPMOST) SetWindowPos (hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); @@ -1013,8 +1020,20 @@ winTopLevelWindowProc (HWND hwnd, UINT message, #endif /* Adjust the X Window to the moved Windows window */ winAdjustXWindow (pWin, hwnd); + if (wParam == SIZE_MINIMIZED) winReorderWindowsMultiWindow(); return 0; /* end of WM_SIZE handler */ + case WM_STYLECHANGED: + /* when the style changes, adjust the window size so the client area remains the same */ + { + LONG x,y; + DrawablePtr pDraw = &pWin->drawable; + x = pDraw->x - wBorderWidth(pWin); + y = pDraw->y - wBorderWidth(pWin); + winPositionWindowMultiWindow(pWin, x, y); + } + return 0; + case WM_MOUSEACTIVATE: /* Check if this window needs to be made active when clicked */ diff --git a/xorg-server/hw/xwin/winpolyline.c b/xorg-server/hw/xwin/winpolyline.c index db9dd345b..bf98d73ec 100644 --- a/xorg-server/hw/xwin/winpolyline.c +++ b/xorg-server/hw/xwin/winpolyline.c @@ -45,7 +45,7 @@ winPolyLineNativeGDI (DrawablePtr pDrawable, { case LineSolid: if (pGC->lineWidth == 0) - return miZeroLine (pDrawable, pGC, mode, npt, ppt); + miZeroLine (pDrawable, pGC, mode, npt, ppt); else miWideLine (pDrawable, pGC, mode, npt, ppt); break; diff --git a/xorg-server/hw/xwin/winprefs.c b/xorg-server/hw/xwin/winprefs.c index d5bceb928..93901cac7 100644 --- a/xorg-server/hw/xwin/winprefs.c +++ b/xorg-server/hw/xwin/winprefs.c @@ -723,7 +723,7 @@ winIconIsOverride(unsigned hiconIn) /* - * Try and open ~/.XWinrc and /usr/X11R6/lib/X11/system.XWinrc + * Try and open ~/.XWinrc and system.XWinrc * Load it into prefs structure for use by other functions */ void @@ -763,7 +763,7 @@ LoadPreferences (void) #ifdef RELOCATE_PROJECTROOT snprintf(buffer, sizeof(buffer), "%s\\system.XWinrc", winGetBaseDir()); #else - strncpy(buffer, PROJECTROOT"/lib/X11/system.XWinrc", sizeof(buffer)); + strncpy(buffer, SYSCONFDIR"/X11/system.XWinrc", sizeof(buffer)); #endif buffer[sizeof(buffer)-1] = 0; prefFile = fopen (buffer, "r"); diff --git a/xorg-server/hw/xwin/winprefs.h b/xorg-server/hw/xwin/winprefs.h index 6d641da6a..abfc7434e 100644 --- a/xorg-server/hw/xwin/winprefs.h +++ b/xorg-server/hw/xwin/winprefs.h @@ -178,6 +178,9 @@ winOverrideIcon (unsigned long longpWin); unsigned long winOverrideStyle (unsigned long longpWin); +unsigned long +winOverrideStyle (unsigned long longpWin); + HICON winTaskbarIcon(void); diff --git a/xorg-server/hw/xwin/winprefsyacc.c b/xorg-server/hw/xwin/winprefsyacc.c index 1255887c3..3ea9e96bb 100644 --- a/xorg-server/hw/xwin/winprefsyacc.c +++ b/xorg-server/hw/xwin/winprefsyacc.c @@ -59,6 +59,9 @@ /* Pull parsers. */ #define YYPULL 1 +#ifdef DEBUG +#undef DEBUG +#endif /* Using locations. */ #define YYLSP_NEEDED 0 @@ -414,15 +417,15 @@ YYID (yyi) # endif # ifndef YYMALLOC # define YYMALLOC malloc -# if ! defined malloc && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) +# if ! defined malloc && !defined _MSC_VER && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus) void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */ # endif # endif # ifndef YYFREE # define YYFREE free -# if ! defined free && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ - || defined __cplusplus || defined _MSC_VER) +# if ! defined free && !defined _MSC_VER && ! defined _STDLIB_H && (defined __STDC__ || defined __C99__FUNC__ \ + || defined __cplusplus) void free (void *); /* INFRINGES ON USER NAME SPACE */ # endif # endif diff --git a/xorg-server/hw/xwin/winprefsyacc.h b/xorg-server/hw/xwin/winprefsyacc.h index a9e5d0c2b..920e96475 100644 --- a/xorg-server/hw/xwin/winprefsyacc.h +++ b/xorg-server/hw/xwin/winprefsyacc.h @@ -35,6 +35,10 @@ /* Tokens. */ #ifndef YYTOKENTYPE +#ifdef DEBUG +#undef DEBUG +#endif + # define YYTOKENTYPE /* Put the tokens into the symbol table, so that GDB and other debuggers know about them. */ diff --git a/xorg-server/hw/xwin/winprocarg.c b/xorg-server/hw/xwin/winprocarg.c index f20598db9..2c4999884 100644 --- a/xorg-server/hw/xwin/winprocarg.c +++ b/xorg-server/hw/xwin/winprocarg.c @@ -1,6 +1,7 @@ /* Copyright 1993, 1998 The Open Group +Copyright (C) Colin Harrison 2005-2008 Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that @@ -38,7 +39,8 @@ from The Open Group. #include "winconfig.h" #include "winprefs.h" #include "winmsg.h" - +#define COMPILE_MULTIMON_STUBS +#include <multimon.h> /* * References to external symbols */ @@ -57,6 +59,7 @@ extern char * g_pszLogFile; extern Bool g_fLogFileChanged; #endif extern Bool g_fXdmcpEnabled; +extern Bool g_fAuthEnabled; extern char * g_pszCommandLine; extern Bool g_fKeyboardHookLL; extern Bool g_fNoHelpMessageBox; @@ -75,30 +78,10 @@ struct GetMonitorInfoData { int monitorWidth; }; -typedef wBOOL (*ENUMDISPLAYMONITORSPROC)(HDC,LPCRECT,MONITORENUMPROC,LPARAM); -ENUMDISPLAYMONITORSPROC _EnumDisplayMonitors; - wBOOL CALLBACK getMonitorInfo(HMONITOR hMonitor, HDC hdc, LPRECT rect, LPARAM _data); static Bool QueryMonitor(int index, struct GetMonitorInfoData *data) { - /* Load EnumDisplayMonitors from DLL */ - HMODULE user32; - FARPROC func; - user32 = LoadLibrary("user32.dll"); - if (user32 == NULL) - { - winW32Error(2, "Could not open user32.dll"); - return FALSE; - } - func = GetProcAddress(user32, "EnumDisplayMonitors"); - if (func == NULL) - { - winW32Error(2, "Could not resolve EnumDisplayMonitors: "); - return FALSE; - } - _EnumDisplayMonitors = (ENUMDISPLAYMONITORSPROC)func; - /* prepare data */ if (data == NULL) return FALSE; @@ -106,10 +89,8 @@ static Bool QueryMonitor(int index, struct GetMonitorInfoData *data) data->requestedMonitor = index; /* query information */ - _EnumDisplayMonitors(NULL, NULL, getMonitorInfo, (LPARAM) data); + xEnumDisplayMonitors(NULL, NULL, getMonitorInfo, (LPARAM) data); - /* cleanup */ - FreeLibrary(user32); return TRUE; } @@ -1289,6 +1270,29 @@ ddxProcessArgument (int argc, char *argv[], int i) } /* + * Look for the '-auth' argument + */ + if (IS_OPTION ("-auth")) + { +#ifdef __MINGW32__ + HANDLE hFile; + char * pszFile; + CHECK_ARGS (1); + pszFile = argv[++i]; + hFile = CreateFile(pszFile,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); + if (hFile == INVALID_HANDLE_VALUE) + winMessageBoxF ("This authorization file for the -auth option could not be opened...\n" + "\"%s\"\n" + "You should use an \"Xauthority\" file in your HOME directory.\n" + "\nIgnoring and continuing.\n", + MB_ICONINFORMATION, + pszFile); +#endif + g_fAuthEnabled = TRUE; + return 0; /* Let DIX parse this again */ + } + + /* * Look for the '-indirect' or '-broadcast' arguments */ if (IS_OPTION ("-indirect") @@ -1512,7 +1516,7 @@ winLogVersionInfo (void) return; s_fBeenHere = TRUE; - ErrorF ("Welcome to the XWin X Server\n"); + ErrorF ("Welcome to the VcXsrv X Server\n"); ErrorF ("Vendor: %s\n", VENDOR_STRING); ErrorF ("Release: %d.%d.%d.%d (%d)\n\n", XORG_VERSION_MAJOR, XORG_VERSION_MINOR, XORG_VERSION_PATCH, XORG_VERSION_SNAP, XORG_VERSION_CURRENT); ErrorF ("Contact: %s\n\n", VENDOR_CONTACT); diff --git a/xorg-server/hw/xwin/winscrinit.c b/xorg-server/hw/xwin/winscrinit.c index eab0c6ccf..8c208709e 100644 --- a/xorg-server/hw/xwin/winscrinit.c +++ b/xorg-server/hw/xwin/winscrinit.c @@ -141,7 +141,7 @@ winScreenInit (int index, } /* Adjust the video mode for our engine type */ - if (!(*pScreenPriv->pwinAdjustVideoMode) (pScreen)) + if (pScreenPriv->pwinAdjustVideoMode && !(*pScreenPriv->pwinAdjustVideoMode) (pScreen)) { ErrorF ("winScreenInit - winAdjustVideoMode () failed\n"); return FALSE; @@ -175,7 +175,7 @@ winScreenInit (int index, } /* Create display window */ - if (!(*pScreenPriv->pwinCreateBoundingWindow) (pScreen)) + if (pScreenPriv->pwinCreateBoundingWindow && !(*pScreenPriv->pwinCreateBoundingWindow) (pScreen)) { ErrorF ("winScreenInit - pwinCreateBoundingWindow () " "failed\n"); @@ -226,7 +226,7 @@ winScreenInit (int index, pScreenInfo->dwBPP); /* Call the engine dependent screen initialization procedure */ - if (!((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv))) + if (pScreenPriv->pwinFinishScreenInit && !((*pScreenPriv->pwinFinishScreenInit) (index, pScreen, argc, argv))) { ErrorF ("winScreenInit - winFinishScreenInit () failed\n"); return FALSE; diff --git a/xorg-server/hw/xwin/winshaddd.c b/xorg-server/hw/xwin/winshaddd.c index 833444177..e35a1bebd 100644 --- a/xorg-server/hw/xwin/winshaddd.c +++ b/xorg-server/hw/xwin/winshaddd.c @@ -48,10 +48,12 @@ extern char *g_pszLogFile; * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly, * so we have to redefine it here. */ +#ifndef _MSC_VER #ifdef DEFINE_GUID #undef DEFINE_GUID #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif /* DEFINE_GUID */ +#endif /* @@ -646,6 +648,7 @@ winShadowUpdateDD (ScreenPtr pScreen, /* Has our memory pointer changed? */ if (pScreenInfo->pfb != pScreenPriv->pddsdShadow->lpSurface) { + extern char *g_pszLogFile; ErrorF ("winShadowUpdateDD - Memory location of the shadow " "surface has changed, trying to update the root window " "pixmap header to point to the new address. If you get " diff --git a/xorg-server/hw/xwin/winshadddnl.c b/xorg-server/hw/xwin/winshadddnl.c index ef5c21469..da40cb5ea 100644 --- a/xorg-server/hw/xwin/winshadddnl.c +++ b/xorg-server/hw/xwin/winshadddnl.c @@ -48,10 +48,12 @@ extern HWND g_hDlgExit; * FIXME: Headers are broken, DEFINE_GUID doesn't work correctly, * so we have to redefine it here. */ +#ifndef _MSC_VER #ifdef DEFINE_GUID #undef DEFINE_GUID #define DEFINE_GUID(n,l,w1,w2,b1,b2,b3,b4,b5,b6,b7,b8) const GUID n GUID_SECT = {l,w1,w2,{b1,b2,b3,b4,b5,b6,b7,b8}} #endif /* DEFINE_GUID */ +#endif /* * FIXME: Headers are broken, IID_IDirectDraw4 has to be defined diff --git a/xorg-server/hw/xwin/wintrayicon.c b/xorg-server/hw/xwin/wintrayicon.c index 895b47caf..b6ffed83f 100644 --- a/xorg-server/hw/xwin/wintrayicon.c +++ b/xorg-server/hw/xwin/wintrayicon.c @@ -36,35 +36,43 @@ #include <shellapi.h> #include "winprefs.h" +static NOTIFYICONDATA nid; /* * Initialize the tray icon */ void -winInitNotifyIcon (winPrivScreenPtr pScreenPriv) +winInitNotifyIcon (winPrivScreenPtr pScreenPriv, Bool Modify) { winScreenInfo *pScreenInfo = pScreenPriv->pScreenInfo; - NOTIFYICONDATA nid = {0}; + char HostName[256]; - nid.cbSize = sizeof (NOTIFYICONDATA); - nid.hWnd = pScreenPriv->hwndScreen; - nid.uID = pScreenInfo->dwScreen; - nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; - nid.uCallbackMessage = WM_TRAYICON; - nid.hIcon = winTaskbarIcon (); + if (!Modify) + { + nid.cbSize = sizeof (NOTIFYICONDATA); + nid.hWnd = pScreenPriv->hwndScreen; + nid.uID = pScreenInfo->dwScreen; + nid.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; + nid.uCallbackMessage = WM_TRAYICON; + nid.hIcon = winTaskbarIcon (); + + /* Save handle to the icon so it can be freed later */ + pScreenPriv->hiconNotifyIcon = nid.hIcon; + } - /* Save handle to the icon so it can be freed later */ - pScreenPriv->hiconNotifyIcon = nid.hIcon; + gethostname(HostName,256); /* Set display and screen-specific tooltip text */ snprintf (nid.szTip, sizeof (nid.szTip), - PROJECT_NAME " Server:%s.%d", + PROJECT_NAME " Server - %s:%s.%d - %d clients", + HostName, display, - (int) pScreenInfo->dwScreen); + (int) pScreenInfo->dwScreen, + pScreenPriv->iConnectedClients); /* Add the tray icon */ - if (!Shell_NotifyIcon (NIM_ADD, &nid)) + if (!Shell_NotifyIcon ((Modify) ? NIM_MODIFY : NIM_ADD, &nid)) ErrorF ("winInitNotifyIcon - Shell_NotifyIcon Failed\n"); } @@ -119,6 +127,17 @@ winHandleIconMessage (HWND hwnd, UINT message, switch (lParam) { + case WM_MOUSEMOVE: + { + static int PrevNrClients; + int NrClients=GetLiveClients(pScreenPriv); + if (NrClients!=PrevNrClients) + { + PrevNrClients=NrClients; + winInitNotifyIcon (pScreenPriv, TRUE); + } + } + break; case WM_LBUTTONUP: /* Restack and bring all windows to top */ SetForegroundWindow (hwnd); diff --git a/xorg-server/hw/xwin/winwindow.c b/xorg-server/hw/xwin/winwindow.c index 0e75a2c6a..ec5983901 100644 --- a/xorg-server/hw/xwin/winwindow.c +++ b/xorg-server/hw/xwin/winwindow.c @@ -58,6 +58,7 @@ winReshapeRootless (WindowPtr pWin); Bool winCreateWindowNativeGDI (WindowPtr pWin) { + Bool fResult; ScreenPtr pScreen = pWin->drawable.pScreen; winWindowPriv(pWin); winScreenPriv(pScreen); diff --git a/xorg-server/hw/xwin/winwindow.h b/xorg-server/hw/xwin/winwindow.h index 86c094334..0890e329c 100644 --- a/xorg-server/hw/xwin/winwindow.h +++ b/xorg-server/hw/xwin/winwindow.h @@ -41,20 +41,20 @@ /* Constant strings */ #ifndef PROJECT_NAME -# define PROJECT_NAME "Cygwin/X" +# define PROJECT_NAME "VcXsrv" #endif -#define WINDOW_CLASS "cygwin/x" -#define WINDOW_TITLE PROJECT_NAME ":%s.%d" -#define WINDOW_TITLE_XDMCP "%s:%s.%d" -#define WIN_SCR_PROP "cyg_screen_prop rl" -#define WINDOW_CLASS_X "cygwin/x X rl" +#define WINDOW_CLASS "VcXsrv/x" +#define WINDOW_TITLE PROJECT_NAME " Server - %s:%s.%d" +#define WINDOW_TITLE_XDMCP PROJECT_NAME " Server - %s:%s.%d" +#define WIN_SCR_PROP "vcxsrv_screen_prop rl" +#define WINDOW_CLASS_X "vcxsrv/x X rl" #define WINDOW_TITLE_X PROJECT_NAME " X" -#define WIN_WINDOW_PROP "cyg_window_prop_rl" +#define WIN_WINDOW_PROP "vcxsrv_window_prop_rl" #ifdef HAS_DEVWINDOWS # define WIN_MSG_QUEUE_FNAME "/dev/windows" #endif -#define WIN_WID_PROP "cyg_wid_prop_rl" -#define WIN_NEEDMANAGE_PROP "cyg_override_redirect_prop_rl" +#define WIN_WID_PROP "vcxsrv_wid_prop_rl" +#define WIN_NEEDMANAGE_PROP "vcxsrv_override_redirect_prop_rl" #ifndef CYGMULTIWINDOW_DEBUG #define CYGMULTIWINDOW_DEBUG NO #endif @@ -62,7 +62,7 @@ #define CYGWINDOWING_DEBUG NO #endif -#define XMING_SIGNATURE 0x12345678L +#define VCXSRV_SIGNATURE 0xdeaddeadL typedef struct _winPrivScreenRec *winPrivScreenPtr; diff --git a/xorg-server/hw/xwin/winwndproc.c b/xorg-server/hw/xwin/winwndproc.c index d72a5f135..8decde864 100644 --- a/xorg-server/hw/xwin/winwndproc.c +++ b/xorg-server/hw/xwin/winwndproc.c @@ -42,6 +42,10 @@ #include "winmsg.h" #include "inputstr.h" +#ifndef XKB_IN_SERVER +#define XKB_IN_SERVER +#endif +#include <xkbsrv.h> /* * Global variables */ @@ -155,7 +159,7 @@ winWindowProc (HWND hwnd, UINT message, s_pScreenPriv->hwndScreen = hwnd; - winInitNotifyIcon (s_pScreenPriv); + winInitNotifyIcon (s_pScreenPriv,FALSE); } return 0; @@ -718,7 +722,7 @@ winWindowProc (HWND hwnd, UINT message, break; /* Has the mouse pointer crossed screens? */ - if (s_pScreen != miPointerGetScreen(g_pwinPointer)) + if (g_pwinPointer && s_pScreen != miPointerGetScreen(g_pwinPointer)) miPointerSetScreen (g_pwinPointer, s_pScreenInfo->dwScreen, GET_X_LPARAM(lParam)-s_pScreenInfo->dwXOffset, GET_Y_LPARAM(lParam)-s_pScreenInfo->dwYOffset); @@ -1268,7 +1272,7 @@ winWindowProc (HWND hwnd, UINT message, default: if(message == s_uTaskbarRestart) { - winInitNotifyIcon (s_pScreenPriv); + winInitNotifyIcon (s_pScreenPriv,FALSE); } break; } diff --git a/xorg-server/hw/xwin/xlaunch/config.h b/xorg-server/hw/xwin/xlaunch/config.h new file mode 100644 index 000000000..e2774e894 --- /dev/null +++ b/xorg-server/hw/xwin/xlaunch/config.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2005 Alexander Gottwald + * + * 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 ABOVE LISTED COPYRIGHT HOLDER(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(s) of the above copyright + * holders shall not be used in advertising or otherwise to promote the sale, + * use or other dealings in this Software without prior written authorization. + * + * Authors: Alexander Gottwald, Colin Harrison + */ +#ifndef __CONFIG_H__ +#define __CONFIG_H__ +#define UNICODE +#define _UNICODE + +#define PROG_NUMBER 10 +#define HOST_NUMBER 10 +#define MAX_MESSAGE 256 +#define MAX_CAPTION 128 + +#include <windows.h> +#include <string> +#include <vector> +struct CConfig +{ + enum {MultiWindow, Fullscreen, Windowed, Nodecoration} window; + enum {NoClient, StartProgram, XDMCP} client; + enum {NoXClient, Local, PuTTY, OpenSSH} clientstart; + std::string display; + std::string protocol_path; + std::string program; + std::vector<std::string> progs; + bool compress; + bool local; + std::string protocol; + std::string host; + std::string user; + std::string password; + bool password_save; + bool password_start; + bool broadcast; + bool indirect; + std::string xdmcp_host; + std::vector<std::string> xhosts; + bool clipboard; + bool no_access_control; + std::string font_server; + std::string extra_params; + std::string extra_ssh; + CConfig() : window(MultiWindow), client(NoClient), clientstart(NoXClient), display(""), + protocol_path(""), program("xeyes"), progs(PROG_NUMBER), compress(false), host(""), user(""), + password(""), password_save(false), password_start(false), broadcast(false), + indirect(false), xdmcp_host(""), xhosts(HOST_NUMBER), clipboard(true), no_access_control(false), + font_server(), extra_params(), extra_ssh() {}; + void Load(const char * filename); + void Save(const char * filename); +}; + +#endif diff --git a/xorg-server/hw/xwin/xlaunch/main.cc b/xorg-server/hw/xwin/xlaunch/main.cc index 2247d3aaf..b3b1001ff 100644 --- a/xorg-server/hw/xwin/xlaunch/main.cc +++ b/xorg-server/hw/xwin/xlaunch/main.cc @@ -23,6 +23,10 @@ * holders shall not be used in advertising or otherwise to promote the sale, * use or other dealings in this Software without prior written authorization. */ + +#define printf _not_used_ /* Make sure that we do not use the standard printf definition because + we are going to reimplement it in this file */ + #include "window/util.h" #include "window/wizard.h" #include "resources/resources.h" @@ -34,6 +38,68 @@ #include <X11/Xlib.h> +#ifdef _MSC_VER +#define snprintf _snprintf +#endif +#include <fcntl.h> +#include <io.h> +#undef printf + +#if defined(_MSC_VER) && defined(_DLL) +#define _CRTEXP __declspec(dllexport) +#else +#define _CRTEXP +#endif + +_Check_return_opt_ _CRTEXP int __cdecl printf(_In_z_ _Printf_format_string_ const char * pFmt, ...) +{ + static int ConsoleCreated=0; + va_list arglist; + if (!ConsoleCreated) + { + int hConHandle; + long lStdHandle; + CONSOLE_SCREEN_BUFFER_INFO coninfo; + + FILE *fp; + const unsigned int MAX_CONSOLE_LINES = 500; + ConsoleCreated=1; + if (!AttachConsole(ATTACH_PARENT_PROCESS)) + AllocConsole(); + + // set the screen buffer to be big enough to let us scroll text + GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); + coninfo.dwSize.Y = MAX_CONSOLE_LINES; + SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); + + // redirect unbuffered STDOUT to the console + lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); + hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); + fp = _fdopen( hConHandle, "w" ); + *stdout = *fp; + setvbuf( stdout, NULL, _IONBF, 0 ); + + // redirect unbuffered STDIN to the console + lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); + hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); + fp = _fdopen( hConHandle, "r" ); + *stdin = *fp; + setvbuf( stdin, NULL, _IONBF, 0 ); + + // redirect unbuffered STDERR to the console + lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); + hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); + fp = _fdopen( hConHandle, "w" ); + *stderr = *fp; + setvbuf( stderr, NULL, _IONBF, 0 ); + + } + + va_start(arglist, pFmt ); + return vfprintf(stderr, pFmt, arglist); +} + + /// @brief Send WM_ENDSESSION to all program windows. /// This will shutdown the started xserver BOOL CALLBACK KillWindowsProc(HWND hwnd, LPARAM lParam) @@ -108,7 +174,10 @@ class CMyWizard : public CWizard } // Check for valid input if (config.display.empty()) + { + MessageBox(hwndDlg,"Please fill in a display number.","Error",MB_OK); SetWindowLong(hwndDlg, DWL_MSGRESULT, -1); + } else SetWindowLong(hwndDlg, DWL_MSGRESULT, IDD_CLIENTS); return TRUE; @@ -489,7 +558,7 @@ class CMyWizard : public CWizard return NULL; } - /// @brief Do the actual start of Xming and clients + /// @brief Do the actual start of VCXsrv and clients void StartUp() { std::string buffer; @@ -500,12 +569,12 @@ class CMyWizard : public CWizard std::string display = "localhost" + display_id + ":0"; #ifdef _DEBUG - // Debug only: Switch to Xming installation directory - SetCurrentDirectory("C:\\Programme\\Xming"); + // Debug only: Switch to VCXsrv installation directory + SetCurrentDirectory("C:\\Programme\\vcxsrv"); #endif - // Build Xming commandline - buffer = "Xming " + display_id + " "; + // Build Xsrv commandline + buffer = "vcxsrv " + display_id + " "; switch (config.window) { case CConfig::MultiWindow: @@ -577,7 +646,7 @@ class CMyWizard : public CWizard sic.cb = sizeof(sic); ZeroMemory( &pic, sizeof(pic) ); - // Start Xming process. + // Start VCXsrv process. #ifdef _DEBUG printf("%s\n", buffer.c_str()); #endif @@ -627,7 +696,7 @@ class CMyWizard : public CWizard #ifdef _DEBUG printf("killing process!\n"); #endif - // Check if Xming is still running + // Check if Xsrv is still running DWORD exitcode; GetExitCodeProcess(pi.hProcess, &exitcode); unsigned counter = 0; @@ -636,7 +705,7 @@ class CMyWizard : public CWizard if (++counter > 10) TerminateProcess(pi.hProcess, (DWORD)-1); else - // Shutdown Xming (the soft way!) + // Shutdown Xsrv (the soft way!) EnumThreadWindows(pi.dwThreadId, KillWindowsProc, 0); Sleep(500); GetExitCodeProcess(pi.hProcess, &exitcode); @@ -695,6 +764,42 @@ int main(int argc, char **argv) } } - +int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) +{ + int argc=1; + #define MAXNRARGS 20 + char *argv[MAXNRARGS]={"plink"}; + char *pTmp=lpCmdLine; + while (*pTmp && argc<MAXNRARGS-1) + { + char *pEnd; + if (*pTmp=='"') + { + pEnd=strchr(pTmp+1,'"'); + } + else if (*pTmp!=' ') + { + pEnd=strchr(pTmp,' '); + } + else + { + pTmp++; + continue; + } + if (pEnd) + { + *pEnd=0; + argv[argc++]=pTmp; + pTmp=pEnd+1; + } + else + { + argv[argc++]=pTmp; + break; + } + } + + return main(argc,argv); +} diff --git a/xorg-server/hw/xwin/xlaunch/makefile b/xorg-server/hw/xwin/xlaunch/makefile new file mode 100644 index 000000000..63b37dd1b --- /dev/null +++ b/xorg-server/hw/xwin/xlaunch/makefile @@ -0,0 +1,32 @@ +INCLUDELIBFILES = window\$(OBJDIR)\window.lib \
+ $(MHMAKECONF)\libx11\src\$(OBJDIR)\libx11.lib \
+ $(MHMAKECONF)\libxcb\src\$(OBJDIR)\libxcb.lib \
+ $(MHMAKECONF)\libxau\$(OBJDIR)\libxau.lib \
+ $(MHMAKECONF)\libx11\src\xlibi18n\$(OBJDIR)\libi18n.lib \
+ $(MHMAKECONF)\libx11\modules\lc\xlocale\$(OBJDIR)\libxlocale.lib \
+ $(MHMAKECONF)\libx11\modules\lc\utf8\$(OBJDIR)\libxlcUTF8Load.lib \
+ $(MHMAKECONF)\libx11\modules\lc\gen\$(OBJDIR)\liblcGenConvLoad.lib \
+ $(MHMAKECONF)\libx11\modules\lc\def\$(OBJDIR)\libxlcDef.lib \
+ $(MHMAKECONF)\libx11\src\xkb\$(OBJDIR)\libxkb.lib \
+ $(MHMAKECONF)\libx11\modules\im\ximcp\$(OBJDIR)\libximcp.lib \
+ $(MHMAKECONF)\libx11\modules\om\generic\$(OBJDIR)\libxomGeneric.lib
+
+CSRCS=config.cc main.cc
+
+WINAPP = xlaunch
+
+RESOURCES = resources.rc
+
+$(OBJDIR)\%.res : resources\%.rc
+ $(RC) $(RCFLAGS) $(RCDEFINES:%=-d "%") $(RCINCLUDES:%=-i %) -Fo$(relpath $@) $<
+
+LIBDIRS=$(dir $(INCLUDELIBFILES))
+
+load_makefile $(LIBDIRS:%$(OBJDIR)\=%makefile MAKESERVER=$(MAKESERVER) DEBUG=$(DEBUG);)
+
+ifeq ($(DEBUG),1)
+LINKLIBS += $(MHMAKECONF)\pthreads\pthreadVC2d.lib
+else
+LINKLIBS += $(MHMAKECONF)\pthreads\pthreadVC2.lib
+endif
+
diff --git a/xorg-server/hw/xwin/xlaunch/resources/resources.h b/xorg-server/hw/xwin/xlaunch/resources/resources.h index 470005192..15e733844 100644 --- a/xorg-server/hw/xwin/xlaunch/resources/resources.h +++ b/xorg-server/hw/xwin/xlaunch/resources/resources.h @@ -35,6 +35,8 @@ #define IDD_FONTPATH 106
#define IDD_CLIPBOARD 107
+#define IDI_XLAUNCH 108
+
#define IDS_DISPLAY_TITLE 300
#define IDS_DISPLAY_SUBTITLE 301
#define IDS_CLIENTS_TITLE 302
diff --git a/xorg-server/hw/xwin/xlaunch/resources/resources.rc b/xorg-server/hw/xwin/xlaunch/resources/resources.rc index 07fd52f32..e3df4610a 100644 --- a/xorg-server/hw/xwin/xlaunch/resources/resources.rc +++ b/xorg-server/hw/xwin/xlaunch/resources/resources.rc @@ -28,3 +28,5 @@ #include "resources.h" #include "images.rc" #include "dialog.rc" + +IDI_XLAUNCH ICON "..\\..\\X.ico" diff --git a/xorg-server/hw/xwin/xlaunch/resources/strings.rc b/xorg-server/hw/xwin/xlaunch/resources/strings.rc index 5a9cd281b..94db96659 100644 --- a/xorg-server/hw/xwin/xlaunch/resources/strings.rc +++ b/xorg-server/hw/xwin/xlaunch/resources/strings.rc @@ -60,15 +60,15 @@ #define STR_CAPTION_CLIPBOARD "Clipboard settings" #define STR_CLIPBOARD "Clipboard" #define STR_CLIPBOARD_DESC "Start the integrated clipboard manager" -#define STR_EXTRA_PARAMS_DESC "Additional parameters for Xming" +#define STR_EXTRA_PARAMS_DESC "Additional parameters for VcXsrv" #define STR_CAPTION_FINISH "Finish configuration" -#define STR_FINISH_DESC "Configuration is complete. Clish Finish to start Xming." +#define STR_FINISH_DESC "Configuration is complete. Clish Finish to start VcXsrv." #define STR_FINISH_SAVE_DESC "You may also save the configuration for later use." #define STR_FINISH_SAVE "Save configuration" #define STR_DISPLAY_TITLE "Select display settings" -#define STR_DISPLAY_SUBTITLE "Choose how Xming display programs" +#define STR_DISPLAY_SUBTITLE "Choose how VcXsrv display programs" #define STR_CLIENTS_TITLE "Select how to start clients" #define STR_CLIENTS_SUBTITLE "" #define STR_PROGRAM_TITLE "Specify the program to start" diff --git a/xorg-server/hw/xwin/xlaunch/window/makefile b/xorg-server/hw/xwin/xlaunch/window/makefile new file mode 100644 index 000000000..18a33e728 --- /dev/null +++ b/xorg-server/hw/xwin/xlaunch/window/makefile @@ -0,0 +1,4 @@ +CSRCS=dialog.cc util.cc window.cc wizard.cc
+
+LIBRARY = window
+
diff --git a/xorg-server/hw/xwin/xlaunch/window/util.cc b/xorg-server/hw/xwin/xlaunch/window/util.cc index fb7e87297..6f768348e 100644 --- a/xorg-server/hw/xwin/xlaunch/window/util.cc +++ b/xorg-server/hw/xwin/xlaunch/window/util.cc @@ -25,6 +25,8 @@ */ #include "util.h" +const char * MessageDebug::notify_names[NOTIFY_NAMES_LEN]; + std::string win32_error::message(DWORD errorcode) { LPVOID lpMsgBuf; diff --git a/xorg-server/hw/xwin/xlaunch/window/util.h b/xorg-server/hw/xwin/xlaunch/window/util.h index cd21da657..a1196b115 100644 --- a/xorg-server/hw/xwin/xlaunch/window/util.h +++ b/xorg-server/hw/xwin/xlaunch/window/util.h @@ -28,7 +28,7 @@ #include <windows.h> #include <stdexcept> - +#include <string> class win32_error : public std::runtime_error { @@ -39,7 +39,7 @@ class win32_error : public std::runtime_error }; #define MESSAGE_NAMES_LEN 1024 -#define NOTIFY_NAMES_LEN 0 +#define NOTIFY_NAMES_LEN 1 class MessageDebug { protected: diff --git a/xorg-server/hw/xwin/xlaunch/window/wizard.h b/xorg-server/hw/xwin/xlaunch/window/wizard.h index a2361c51c..c576cc093 100644 --- a/xorg-server/hw/xwin/xlaunch/window/wizard.h +++ b/xorg-server/hw/xwin/xlaunch/window/wizard.h @@ -29,7 +29,6 @@ #include "dialog.h"
#include <vector>
-#define _WIN32_IE 0x0500
#include <prsht.h>
class CWizard : public CBaseDialog
diff --git a/xorg-server/include/dixstruct.h b/xorg-server/include/dixstruct.h index 696b793ff..acfbe46ca 100644 --- a/xorg-server/include/dixstruct.h +++ b/xorg-server/include/dixstruct.h @@ -94,7 +94,7 @@ typedef struct _Client { Bool swapped; ReplySwapPtr pSwapReplyFunc; XID errorValue; - int sequence; + unsigned short sequence; //MH int closeDownMode; int clientGone; int noClientException; /* this client died or needs to be diff --git a/xorg-server/include/globals.h b/xorg-server/include/globals.h index 52c19a490..6aadb8bdf 100644 --- a/xorg-server/include/globals.h +++ b/xorg-server/include/globals.h @@ -41,9 +41,7 @@ extern _X_EXPORT Bool DPMSCapableFlag; extern _X_EXPORT Bool PanoramiXExtensionDisabledHack; #endif -#ifdef COMPOSITE extern _X_EXPORT Bool noCompositeExtension; -#endif #ifdef DAMAGE extern _X_EXPORT Bool noDamageExtension; diff --git a/xorg-server/include/input.h b/xorg-server/include/input.h index afcc006f8..cab91c8f5 100644 --- a/xorg-server/include/input.h +++ b/xorg-server/include/input.h @@ -1,530 +1,532 @@ -/************************************************************ - -Copyright 1987, 1998 The Open Group - -Permission to use, copy, modify, distribute, and sell this software and its -documentation for any purpose is hereby granted without fee, provided that -the above copyright notice appear in all copies and that both that -copyright notice and this permission notice appear in supporting -documentation. - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN -AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -Except as contained in this notice, the name of The Open Group shall not be -used in advertising or otherwise to promote the sale, use or other dealings -in this Software without prior written authorization from The Open Group. - - -Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts. - - All Rights Reserved - -Permission to use, copy, modify, and distribute this software and its -documentation for any purpose and without fee is hereby granted, -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 Digital not be -used in advertising or publicity pertaining to distribution of the -software without specific, written prior permission. - -DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING -ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL -DIGITAL 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. - -********************************************************/ - -#ifndef INPUT_H -#define INPUT_H - -#include "misc.h" -#include "screenint.h" -#include <X11/Xmd.h> -#include <X11/Xproto.h> -#include "window.h" /* for WindowPtr */ -#include "xkbrules.h" -#include "events.h" - -#define DEVICE_INIT 0 -#define DEVICE_ON 1 -#define DEVICE_OFF 2 -#define DEVICE_CLOSE 3 - -#define POINTER_RELATIVE (1 << 1) -#define POINTER_ABSOLUTE (1 << 2) -#define POINTER_ACCELERATE (1 << 3) -#define POINTER_SCREEN (1 << 4) /* Data in screen coordinates */ - -/*int constants for pointer acceleration schemes*/ -#define PtrAccelNoOp 0 -#define PtrAccelPredictable 1 -#define PtrAccelLightweight 2 -#define PtrAccelDefault PtrAccelPredictable - -#define MAX_VALUATORS 36 -/* Maximum number of valuators, divided by six, rounded up, to get number - * of events. */ -#define MAX_VALUATOR_EVENTS 6 -#define MAX_BUTTONS 256 /* completely arbitrarily chosen */ - -#define NO_AXIS_LIMITS -1 - -#define MAP_LENGTH 256 -#define DOWN_LENGTH 32 /* 256/8 => number of bytes to hold 256 bits */ -#define NullGrab ((GrabPtr)NULL) -#define PointerRootWin ((WindowPtr)PointerRoot) -#define NoneWin ((WindowPtr)None) -#define NullDevice ((DevicePtr)NULL) - -#ifndef FollowKeyboard -#define FollowKeyboard 3 -#endif -#ifndef FollowKeyboardWin -#define FollowKeyboardWin ((WindowPtr) FollowKeyboard) -#endif -#ifndef RevertToFollowKeyboard -#define RevertToFollowKeyboard 3 -#endif - -typedef unsigned long Leds; -typedef struct _OtherClients *OtherClientsPtr; -typedef struct _InputClients *InputClientsPtr; -typedef struct _DeviceIntRec *DeviceIntPtr; -typedef struct _ClassesRec *ClassesPtr; -typedef union _GrabMask GrabMask; - -typedef struct _EventList { - xEvent* event; - int evlen; /* length of allocated memory for event in bytes. This is not - the actual length of the event. The event's actual length is - 32 for standard events or 32 + - ((xGenericEvent*)event)->length * 4 for GenericEvents. - For events in the EQ, the length is - ((InternalEvent*)event)->u.any.length */ -} EventList, *EventListPtr; - -/* The DIX stores incoming input events in this list */ -extern EventListPtr InputEventList; -extern int InputEventListLen; - -typedef int (*DeviceProc)( - DeviceIntPtr /*device*/, - int /*what*/); - -typedef void (*ProcessInputProc)( - InternalEvent * /*event*/, - DeviceIntPtr /*device*/); - -typedef Bool (*DeviceHandleProc)( - DeviceIntPtr /*device*/, - void* /*data*/ - ); - -typedef void (*DeviceUnwrapProc)( - DeviceIntPtr /*device*/, - DeviceHandleProc /*proc*/, - void* /*data*/ - ); - -/* pointer acceleration handling */ -typedef void (*PointerAccelSchemeProc)( - DeviceIntPtr /*pDev*/, - int /*first_valuator*/, - int /*num_valuators*/, - int* /*valuators*/, - int /*evtime*/); - -typedef void (*DeviceCallbackProc)( - DeviceIntPtr /*pDev*/); - -typedef struct _DeviceRec { - pointer devicePrivate; - ProcessInputProc processInputProc; /* current */ - ProcessInputProc realInputProc; /* deliver */ - ProcessInputProc enqueueInputProc; /* enqueue */ - Bool on; /* used by DDX to keep state */ -} DeviceRec, *DevicePtr; - -typedef struct { - int click, bell, bell_pitch, bell_duration; - Bool autoRepeat; - unsigned char autoRepeats[32]; - Leds leds; - unsigned char id; -} KeybdCtrl; - -typedef struct { - KeySym *map; - KeyCode minKeyCode, - maxKeyCode; - int mapWidth; -} KeySymsRec, *KeySymsPtr; - -typedef struct { - int num, den, threshold; - unsigned char id; -} PtrCtrl; - -typedef struct { - int resolution, min_value, max_value; - int integer_displayed; - unsigned char id; -} IntegerCtrl; - -typedef struct { - int max_symbols, num_symbols_supported; - int num_symbols_displayed; - KeySym *symbols_supported; - KeySym *symbols_displayed; - unsigned char id; -} StringCtrl; - -typedef struct { - int percent, pitch, duration; - unsigned char id; -} BellCtrl; - -typedef struct { - Leds led_values; - Mask led_mask; - unsigned char id; -} LedCtrl; - -extern _X_EXPORT KeybdCtrl defaultKeyboardControl; -extern _X_EXPORT PtrCtrl defaultPointerControl; - -typedef struct _InputOption { - char *key; - char *value; - struct _InputOption *next; -} InputOption; - -/* Key has been run through all input processing and events sent to clients. */ -#define KEY_PROCESSED 1 -/* Key has not been fully processed, no events have been sent. */ -#define KEY_POSTED 2 - -extern void set_key_down(DeviceIntPtr pDev, int key_code, int type); -extern void set_key_up(DeviceIntPtr pDev, int key_code, int type); -extern int key_is_down(DeviceIntPtr pDev, int key_code, int type); - -extern void InitCoreDevices(void); -extern void InitXTestDevices(void); - -extern _X_EXPORT DeviceIntPtr AddInputDevice( - ClientPtr /*client*/, - DeviceProc /*deviceProc*/, - Bool /*autoStart*/); - -extern _X_EXPORT Bool EnableDevice( - DeviceIntPtr /*device*/, - BOOL /* sendevent */); - -extern _X_EXPORT Bool ActivateDevice( - DeviceIntPtr /*device*/, - BOOL /* sendevent */); - -extern _X_EXPORT Bool DisableDevice( - DeviceIntPtr /*device*/, - BOOL /* sendevent */); - -extern int InitAndStartDevices(void); - -extern void CloseDownDevices(void); - -extern void UndisplayDevices(void); - -extern _X_EXPORT int RemoveDevice( - DeviceIntPtr /*dev*/, - BOOL /* sendevent */); - -extern _X_EXPORT int NumMotionEvents(void); - -extern void RegisterPointerDevice( - DeviceIntPtr /*device*/); - -extern void RegisterKeyboardDevice( - DeviceIntPtr /*device*/); - -extern _X_EXPORT int dixLookupDevice( - DeviceIntPtr * /* dev */, - int /* id */, - ClientPtr /* client */, - Mask /* access_mode */); - -extern _X_EXPORT void QueryMinMaxKeyCodes( - KeyCode* /*minCode*/, - KeyCode* /*maxCode*/); - -extern _X_EXPORT Bool SetKeySymsMap( - KeySymsPtr /*dst*/, - KeySymsPtr /*src*/); - -extern _X_EXPORT Bool InitButtonClassDeviceStruct( - DeviceIntPtr /*device*/, - int /*numButtons*/, - Atom* /* labels */, - CARD8* /*map*/); - -extern _X_EXPORT Bool InitValuatorClassDeviceStruct( - DeviceIntPtr /*device*/, - int /*numAxes*/, - Atom* /* labels */, - int /*numMotionEvents*/, - int /*mode*/); - -extern _X_EXPORT Bool InitPointerAccelerationScheme( - DeviceIntPtr /*dev*/, - int /*scheme*/); - -extern _X_EXPORT Bool InitAbsoluteClassDeviceStruct( - DeviceIntPtr /*device*/); - -extern _X_EXPORT Bool InitFocusClassDeviceStruct( - DeviceIntPtr /*device*/); - -typedef void (*BellProcPtr)( - int /*percent*/, - DeviceIntPtr /*device*/, - pointer /*ctrl*/, - int); - -typedef void (*KbdCtrlProcPtr)( - DeviceIntPtr /*device*/, - KeybdCtrl * /*ctrl*/); - -typedef void (*PtrCtrlProcPtr)( - DeviceIntPtr /*device*/, - PtrCtrl * /*ctrl*/); - -extern _X_EXPORT Bool InitPtrFeedbackClassDeviceStruct( - DeviceIntPtr /*device*/, - PtrCtrlProcPtr /*controlProc*/); - -typedef void (*StringCtrlProcPtr)( - DeviceIntPtr /*device*/, - StringCtrl * /*ctrl*/); - -extern _X_EXPORT Bool InitStringFeedbackClassDeviceStruct( - DeviceIntPtr /*device*/, - StringCtrlProcPtr /*controlProc*/, - int /*max_symbols*/, - int /*num_symbols_supported*/, - KeySym* /*symbols*/); - -typedef void (*BellCtrlProcPtr)( - DeviceIntPtr /*device*/, - BellCtrl * /*ctrl*/); - -extern _X_EXPORT Bool InitBellFeedbackClassDeviceStruct( - DeviceIntPtr /*device*/, - BellProcPtr /*bellProc*/, - BellCtrlProcPtr /*controlProc*/); - -typedef void (*LedCtrlProcPtr)( - DeviceIntPtr /*device*/, - LedCtrl * /*ctrl*/); - -extern _X_EXPORT Bool InitLedFeedbackClassDeviceStruct( - DeviceIntPtr /*device*/, - LedCtrlProcPtr /*controlProc*/); - -typedef void (*IntegerCtrlProcPtr)( - DeviceIntPtr /*device*/, - IntegerCtrl * /*ctrl*/); - - -extern _X_EXPORT Bool InitIntegerFeedbackClassDeviceStruct( - DeviceIntPtr /*device*/, - IntegerCtrlProcPtr /*controlProc*/); - -extern _X_EXPORT Bool InitPointerDeviceStruct( - DevicePtr /*device*/, - CARD8* /*map*/, - int /*numButtons*/, - Atom* /* btn_labels */, - PtrCtrlProcPtr /*controlProc*/, - int /*numMotionEvents*/, - int /*numAxes*/, - Atom* /* axes_labels */); - -extern _X_EXPORT Bool InitKeyboardDeviceStruct( - DeviceIntPtr /*device*/, - XkbRMLVOSet * /*rmlvo*/, - BellProcPtr /*bellProc*/, - KbdCtrlProcPtr /*controlProc*/); - -extern int ApplyPointerMapping( - DeviceIntPtr /* pDev */, - CARD8 * /* map */, - int /* len */, - ClientPtr /* client */); - -extern Bool BadDeviceMap( - BYTE* /*buff*/, - int /*length*/, - unsigned /*low*/, - unsigned /*high*/, - XID* /*errval*/); - -extern void NoteLedState( - DeviceIntPtr /*keybd*/, - int /*led*/, - Bool /*on*/); - -extern void MaybeStopHint( - DeviceIntPtr /*device*/, - ClientPtr /*client*/); - -extern void ProcessPointerEvent( - InternalEvent* /* ev */, - DeviceIntPtr /*mouse*/); - -extern void ProcessKeyboardEvent( - InternalEvent* /*ev*/, - DeviceIntPtr /*keybd*/); - -extern Bool LegalModifier( - unsigned int /*key*/, - DeviceIntPtr /*pDev*/); - -extern _X_EXPORT void ProcessInputEvents(void); - -extern _X_EXPORT void InitInput( - int /*argc*/, - char ** /*argv*/); - -extern _X_EXPORT int GetMaximumEventsNum(void); - -extern _X_EXPORT int GetEventList(EventListPtr* list); -extern _X_EXPORT EventListPtr InitEventList(int num_events); -extern _X_EXPORT void FreeEventList(EventListPtr list, int num_events); - -extern void CreateClassesChangedEvent(EventListPtr event, - DeviceIntPtr master, - DeviceIntPtr slave, - int type); -extern int GetPointerEvents( - EventListPtr events, - DeviceIntPtr pDev, - int type, - int buttons, - int flags, - int first_valuator, - int num_valuators, - int *valuators); - -extern int GetKeyboardEvents( - EventListPtr events, - DeviceIntPtr pDev, - int type, - int key_code); - -extern int GetKeyboardValuatorEvents( - EventListPtr events, - DeviceIntPtr pDev, - int type, - int key_code, - int first_valuator, - int num_valuator, - int *valuators); - -extern int GetProximityEvents( - EventListPtr events, - DeviceIntPtr pDev, - int type, - int first_valuator, - int num_valuators, - int *valuators); - -extern void PostSyntheticMotion( - DeviceIntPtr pDev, - int x, - int y, - int screen, - unsigned long time); - -extern _X_EXPORT int GetMotionHistorySize( - void); - -extern _X_EXPORT void AllocateMotionHistory( - DeviceIntPtr pDev); - -extern _X_EXPORT int GetMotionHistory( - DeviceIntPtr pDev, - xTimecoord **buff, - unsigned long start, - unsigned long stop, - ScreenPtr pScreen, - BOOL core); - -extern int AttachDevice(ClientPtr client, - DeviceIntPtr slave, - DeviceIntPtr master); - -extern _X_EXPORT DeviceIntPtr GetPairedDevice(DeviceIntPtr kbd); -extern DeviceIntPtr GetMaster(DeviceIntPtr dev, int type); - -extern int AllocDevicePair(ClientPtr client, - char* name, - DeviceIntPtr* ptr, - DeviceIntPtr* keybd, - DeviceProc ptr_proc, - DeviceProc keybd_proc, - Bool master); -extern void DeepCopyDeviceClasses(DeviceIntPtr from, - DeviceIntPtr to, - DeviceChangedEvent *dce); - -/* Helper functions. */ -extern int generate_modkeymap(ClientPtr client, DeviceIntPtr dev, - KeyCode **modkeymap, int *max_keys_per_mod); -extern int change_modmap(ClientPtr client, DeviceIntPtr dev, KeyCode *map, - int max_keys_per_mod); -extern int AllocXTestDevice(ClientPtr client, - char* name, - DeviceIntPtr* ptr, - DeviceIntPtr* keybd, - DeviceIntPtr master_ptr, - DeviceIntPtr master_keybd); -extern BOOL IsXTestDevice(DeviceIntPtr dev, DeviceIntPtr master); -extern DeviceIntPtr GetXTestDevice(DeviceIntPtr master); -extern void SendDevicePresenceEvent(int deviceid, int type); - -/* misc event helpers */ -extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event); -extern Mask GetWindowXI2Mask(DeviceIntPtr dev, WindowPtr win, xEvent* ev); -void FixUpEventFromWindow(DeviceIntPtr pDev, - xEvent *xE, - WindowPtr pWin, - Window child, - Bool calcChild); - -/* Implemented by the DDX. */ -extern _X_EXPORT int NewInputDeviceRequest( - InputOption *options, - DeviceIntPtr *dev); -extern _X_EXPORT void DeleteInputDeviceRequest( - DeviceIntPtr dev); - -extern _X_EXPORT void DDXRingBell( - int volume, - int pitch, - int duration); - -/* Set to TRUE by default - os/utils.c sets it to FALSE on user request, - xfixes/cursor.c uses it to determine if the cursor is enabled */ -extern Bool EnableCursor; - -#endif /* INPUT_H */ +/************************************************************
+
+Copyright 1987, 1998 The Open Group
+
+Permission to use, copy, modify, distribute, and sell this software and its
+documentation for any purpose is hereby granted without fee, provided that
+the above copyright notice appear in all copies and that both that
+copyright notice and this permission notice appear in supporting
+documentation.
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
+AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+Except as contained in this notice, the name of The Open Group shall not be
+used in advertising or otherwise to promote the sale, use or other dealings
+in this Software without prior written authorization from The Open Group.
+
+
+Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
+
+ All Rights Reserved
+
+Permission to use, copy, modify, and distribute this software and its
+documentation for any purpose and without fee is hereby granted,
+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 Digital not be
+used in advertising or publicity pertaining to distribution of the
+software without specific, written prior permission.
+
+DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
+ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
+DIGITAL 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.
+
+********************************************************/
+
+#ifndef INPUT_H
+#define INPUT_H
+
+#include "misc.h"
+#include "screenint.h"
+#include <X11/Xmd.h>
+#include <X11/Xproto.h>
+#include "window.h" /* for WindowPtr */
+#include "xkbrules.h"
+#include "events.h"
+
+#define DEVICE_INIT 0
+#define DEVICE_ON 1
+#define DEVICE_OFF 2
+#define DEVICE_CLOSE 3
+
+#define POINTER_RELATIVE (1 << 1)
+#define POINTER_ABSOLUTE (1 << 2)
+#define POINTER_ACCELERATE (1 << 3)
+#define POINTER_SCREEN (1 << 4) /* Data in screen coordinates */
+
+/*int constants for pointer acceleration schemes*/
+#define PtrAccelNoOp 0
+#define PtrAccelPredictable 1
+#define PtrAccelLightweight 2
+#define PtrAccelDefault PtrAccelPredictable
+
+#define MAX_VALUATORS 36
+/* Maximum number of valuators, divided by six, rounded up, to get number
+ * of events. */
+#define MAX_VALUATOR_EVENTS 6
+#define MAX_BUTTONS 256 /* completely arbitrarily chosen */
+
+#define NO_AXIS_LIMITS -1
+
+#define MAP_LENGTH 256
+#define DOWN_LENGTH 32 /* 256/8 => number of bytes to hold 256 bits */
+#define NullGrab ((GrabPtr)NULL)
+#define PointerRootWin ((WindowPtr)PointerRoot)
+#define NoneWin ((WindowPtr)None)
+#define NullDevice ((DevicePtr)NULL)
+
+#ifndef FollowKeyboard
+#define FollowKeyboard 3
+#endif
+#ifndef FollowKeyboardWin
+#define FollowKeyboardWin ((WindowPtr) FollowKeyboard)
+#endif
+#ifndef RevertToFollowKeyboard
+#define RevertToFollowKeyboard 3
+#endif
+
+typedef unsigned long Leds;
+typedef struct _OtherClients *OtherClientsPtr;
+typedef struct _InputClients *InputClientsPtr;
+typedef struct _DeviceIntRec *DeviceIntPtr;
+typedef struct _ClassesRec *ClassesPtr;
+typedef union _GrabMask GrabMask;
+
+typedef struct _EventList {
+ xEvent* event;
+ int evlen; /* length of allocated memory for event in bytes. This is not
+ the actual length of the event. The event's actual length is
+ 32 for standard events or 32 +
+ ((xGenericEvent*)event)->length * 4 for GenericEvents.
+ For events in the EQ, the length is
+ ((InternalEvent*)event)->u.any.length */
+} EventList, *EventListPtr;
+
+/* The DIX stores incoming input events in this list */
+extern EventListPtr InputEventList;
+extern int InputEventListLen;
+
+typedef int (*DeviceProc)(
+ DeviceIntPtr /*device*/,
+ int /*what*/);
+
+typedef void (*ProcessInputProc)(
+ InternalEvent * /*event*/,
+ DeviceIntPtr /*device*/);
+
+typedef Bool (*DeviceHandleProc)(
+ DeviceIntPtr /*device*/,
+ void* /*data*/
+ );
+
+typedef void (*DeviceUnwrapProc)(
+ DeviceIntPtr /*device*/,
+ DeviceHandleProc /*proc*/,
+ void* /*data*/
+ );
+
+/* pointer acceleration handling */
+typedef void (*PointerAccelSchemeProc)(
+ DeviceIntPtr /*pDev*/,
+ int /*first_valuator*/,
+ int /*num_valuators*/,
+ int* /*valuators*/,
+ int /*evtime*/);
+
+typedef void (*DeviceCallbackProc)(
+ DeviceIntPtr /*pDev*/);
+
+typedef struct _DeviceRec {
+ pointer devicePrivate;
+ ProcessInputProc processInputProc; /* current */
+ ProcessInputProc realInputProc; /* deliver */
+ ProcessInputProc enqueueInputProc; /* enqueue */
+ Bool on; /* used by DDX to keep state */
+} DeviceRec, *DevicePtr;
+
+typedef struct {
+ int click, bell, bell_pitch, bell_duration;
+ Bool autoRepeat;
+ unsigned char autoRepeats[32];
+ Leds leds;
+ unsigned char id;
+} KeybdCtrl;
+
+typedef struct {
+ KeySym *map;
+ KeyCode minKeyCode,
+ maxKeyCode;
+ int mapWidth;
+} KeySymsRec, *KeySymsPtr;
+
+typedef struct {
+ int num, den, threshold;
+ unsigned char id;
+} PtrCtrl;
+
+typedef struct {
+ int resolution, min_value, max_value;
+ int integer_displayed;
+ unsigned char id;
+} IntegerCtrl;
+
+typedef struct {
+ int max_symbols, num_symbols_supported;
+ int num_symbols_displayed;
+ KeySym *symbols_supported;
+ KeySym *symbols_displayed;
+ unsigned char id;
+} StringCtrl;
+
+typedef struct {
+ int percent, pitch, duration;
+ unsigned char id;
+} BellCtrl;
+
+typedef struct {
+ Leds led_values;
+ Mask led_mask;
+ unsigned char id;
+} LedCtrl;
+
+extern _X_EXPORT KeybdCtrl defaultKeyboardControl;
+extern _X_EXPORT PtrCtrl defaultPointerControl;
+
+typedef struct _InputOption {
+ char *key;
+ char *value;
+ struct _InputOption *next;
+} InputOption;
+
+/* Key has been run through all input processing and events sent to clients. */
+#define KEY_PROCESSED 1
+/* Key has not been fully processed, no events have been sent. */
+#define KEY_POSTED 2
+
+extern void set_key_down(DeviceIntPtr pDev, int key_code, int type);
+extern void set_key_up(DeviceIntPtr pDev, int key_code, int type);
+extern int key_is_down(DeviceIntPtr pDev, int key_code, int type);
+
+extern void InitCoreDevices(void);
+extern void InitXTestDevices(void);
+
+extern _X_EXPORT DeviceIntPtr AddInputDevice(
+ ClientPtr /*client*/,
+ DeviceProc /*deviceProc*/,
+ Bool /*autoStart*/);
+
+extern _X_EXPORT Bool EnableDevice(
+ DeviceIntPtr /*device*/,
+ BOOL /* sendevent */);
+
+extern _X_EXPORT Bool ActivateDevice(
+ DeviceIntPtr /*device*/,
+ BOOL /* sendevent */);
+
+extern _X_EXPORT Bool DisableDevice(
+ DeviceIntPtr /*device*/,
+ BOOL /* sendevent */);
+
+extern int InitAndStartDevices(void);
+
+extern void CloseDownDevices(void);
+
+extern void UndisplayDevices(void);
+
+extern _X_EXPORT int RemoveDevice(
+ DeviceIntPtr /*dev*/,
+ BOOL /* sendevent */);
+
+extern _X_EXPORT int NumMotionEvents(void);
+
+extern void RegisterPointerDevice(
+ DeviceIntPtr /*device*/);
+
+extern void RegisterKeyboardDevice(
+ DeviceIntPtr /*device*/);
+
+extern _X_EXPORT int dixLookupDevice(
+ DeviceIntPtr * /* dev */,
+ int /* id */,
+ ClientPtr /* client */,
+ Mask /* access_mode */);
+
+extern _X_EXPORT void QueryMinMaxKeyCodes(
+ KeyCode* /*minCode*/,
+ KeyCode* /*maxCode*/);
+
+extern _X_EXPORT Bool SetKeySymsMap(
+ KeySymsPtr /*dst*/,
+ KeySymsPtr /*src*/);
+
+extern _X_EXPORT Bool InitButtonClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ int /*numButtons*/,
+ Atom* /* labels */,
+ CARD8* /*map*/);
+
+extern _X_EXPORT Bool InitValuatorClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ int /*numAxes*/,
+ Atom* /* labels */,
+ int /*numMotionEvents*/,
+ int /*mode*/);
+
+extern _X_EXPORT Bool InitPointerAccelerationScheme(
+ DeviceIntPtr /*dev*/,
+ int /*scheme*/);
+
+extern _X_EXPORT Bool InitAbsoluteClassDeviceStruct(
+ DeviceIntPtr /*device*/);
+
+extern _X_EXPORT Bool InitFocusClassDeviceStruct(
+ DeviceIntPtr /*device*/);
+
+typedef void (*BellProcPtr)(
+ int /*percent*/,
+ DeviceIntPtr /*device*/,
+ pointer /*ctrl*/,
+ int);
+
+typedef void (*KbdCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ KeybdCtrl * /*ctrl*/);
+
+typedef void (*PtrCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ PtrCtrl * /*ctrl*/);
+
+extern _X_EXPORT Bool InitPtrFeedbackClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ PtrCtrlProcPtr /*controlProc*/);
+
+typedef void (*StringCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ StringCtrl * /*ctrl*/);
+
+extern _X_EXPORT Bool InitStringFeedbackClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ StringCtrlProcPtr /*controlProc*/,
+ int /*max_symbols*/,
+ int /*num_symbols_supported*/,
+ KeySym* /*symbols*/);
+
+typedef void (*BellCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ BellCtrl * /*ctrl*/);
+
+extern _X_EXPORT Bool InitBellFeedbackClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ BellProcPtr /*bellProc*/,
+ BellCtrlProcPtr /*controlProc*/);
+
+typedef void (*LedCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ LedCtrl * /*ctrl*/);
+
+extern _X_EXPORT Bool InitLedFeedbackClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ LedCtrlProcPtr /*controlProc*/);
+
+typedef void (*IntegerCtrlProcPtr)(
+ DeviceIntPtr /*device*/,
+ IntegerCtrl * /*ctrl*/);
+
+
+extern _X_EXPORT Bool InitIntegerFeedbackClassDeviceStruct(
+ DeviceIntPtr /*device*/,
+ IntegerCtrlProcPtr /*controlProc*/);
+
+extern _X_EXPORT Bool InitPointerDeviceStruct(
+ DevicePtr /*device*/,
+ CARD8* /*map*/,
+ int /*numButtons*/,
+ Atom* /* btn_labels */,
+ PtrCtrlProcPtr /*controlProc*/,
+ int /*numMotionEvents*/,
+ int /*numAxes*/,
+ Atom* /* axes_labels */);
+
+extern _X_EXPORT Bool InitKeyboardDeviceStruct(
+ DeviceIntPtr /*device*/,
+ XkbRMLVOSet * /*rmlvo*/,
+ BellProcPtr /*bellProc*/,
+ KbdCtrlProcPtr /*controlProc*/);
+
+extern int ApplyPointerMapping(
+ DeviceIntPtr /* pDev */,
+ CARD8 * /* map */,
+ int /* len */,
+ ClientPtr /* client */);
+
+extern Bool BadDeviceMap(
+ BYTE* /*buff*/,
+ int /*length*/,
+ unsigned /*low*/,
+ unsigned /*high*/,
+ XID* /*errval*/);
+
+extern void NoteLedState(
+ DeviceIntPtr /*keybd*/,
+ int /*led*/,
+ Bool /*on*/);
+
+extern void MaybeStopHint(
+ DeviceIntPtr /*device*/,
+ ClientPtr /*client*/);
+
+extern void ProcessPointerEvent(
+ InternalEvent* /* ev */,
+ DeviceIntPtr /*mouse*/);
+
+extern void ProcessKeyboardEvent(
+ InternalEvent* /*ev*/,
+ DeviceIntPtr /*keybd*/);
+
+extern void InputDevicesClosed(void);
+
+extern Bool LegalModifier(
+ unsigned int /*key*/,
+ DeviceIntPtr /*pDev*/);
+
+extern _X_EXPORT void ProcessInputEvents(void);
+
+extern _X_EXPORT void InitInput(
+ int /*argc*/,
+ char ** /*argv*/);
+
+extern _X_EXPORT int GetMaximumEventsNum(void);
+
+extern _X_EXPORT int GetEventList(EventListPtr* list);
+extern _X_EXPORT EventListPtr InitEventList(int num_events);
+extern _X_EXPORT void FreeEventList(EventListPtr list, int num_events);
+
+extern void CreateClassesChangedEvent(EventListPtr event,
+ DeviceIntPtr master,
+ DeviceIntPtr slave,
+ int type);
+extern int GetPointerEvents(
+ EventListPtr events,
+ DeviceIntPtr pDev,
+ int type,
+ int buttons,
+ int flags,
+ int first_valuator,
+ int num_valuators,
+ int *valuators);
+
+extern int GetKeyboardEvents(
+ EventListPtr events,
+ DeviceIntPtr pDev,
+ int type,
+ int key_code);
+
+extern int GetKeyboardValuatorEvents(
+ EventListPtr events,
+ DeviceIntPtr pDev,
+ int type,
+ int key_code,
+ int first_valuator,
+ int num_valuator,
+ int *valuators);
+
+extern int GetProximityEvents(
+ EventListPtr events,
+ DeviceIntPtr pDev,
+ int type,
+ int first_valuator,
+ int num_valuators,
+ int *valuators);
+
+extern void PostSyntheticMotion(
+ DeviceIntPtr pDev,
+ int x,
+ int y,
+ int screen,
+ unsigned long time);
+
+extern _X_EXPORT int GetMotionHistorySize(
+ void);
+
+extern _X_EXPORT void AllocateMotionHistory(
+ DeviceIntPtr pDev);
+
+extern _X_EXPORT int GetMotionHistory(
+ DeviceIntPtr pDev,
+ xTimecoord **buff,
+ unsigned long start,
+ unsigned long stop,
+ ScreenPtr pScreen,
+ BOOL core);
+
+extern int AttachDevice(ClientPtr client,
+ DeviceIntPtr slave,
+ DeviceIntPtr master);
+
+extern _X_EXPORT DeviceIntPtr GetPairedDevice(DeviceIntPtr kbd);
+extern DeviceIntPtr GetMaster(DeviceIntPtr dev, int type);
+
+extern int AllocDevicePair(ClientPtr client,
+ char* name,
+ DeviceIntPtr* ptr,
+ DeviceIntPtr* keybd,
+ DeviceProc ptr_proc,
+ DeviceProc keybd_proc,
+ Bool master);
+extern void DeepCopyDeviceClasses(DeviceIntPtr from,
+ DeviceIntPtr to,
+ DeviceChangedEvent *dce);
+
+/* Helper functions. */
+extern int generate_modkeymap(ClientPtr client, DeviceIntPtr dev,
+ KeyCode **modkeymap, int *max_keys_per_mod);
+extern int change_modmap(ClientPtr client, DeviceIntPtr dev, KeyCode *map,
+ int max_keys_per_mod);
+extern int AllocXTestDevice(ClientPtr client,
+ char* name,
+ DeviceIntPtr* ptr,
+ DeviceIntPtr* keybd,
+ DeviceIntPtr master_ptr,
+ DeviceIntPtr master_keybd);
+extern BOOL IsXTestDevice(DeviceIntPtr dev, DeviceIntPtr master);
+extern DeviceIntPtr GetXTestDevice(DeviceIntPtr master);
+extern void SendDevicePresenceEvent(int deviceid, int type);
+
+/* misc event helpers */
+extern Mask GetEventFilter(DeviceIntPtr dev, xEvent *event);
+extern Mask GetWindowXI2Mask(DeviceIntPtr dev, WindowPtr win, xEvent* ev);
+void FixUpEventFromWindow(DeviceIntPtr pDev,
+ xEvent *xE,
+ WindowPtr pWin,
+ Window child,
+ Bool calcChild);
+
+/* Implemented by the DDX. */
+extern _X_EXPORT int NewInputDeviceRequest(
+ InputOption *options,
+ DeviceIntPtr *dev);
+extern _X_EXPORT void DeleteInputDeviceRequest(
+ DeviceIntPtr dev);
+
+extern _X_EXPORT void DDXRingBell(
+ int volume,
+ int pitch,
+ int duration);
+
+/* Set to TRUE by default - os/utils.c sets it to FALSE on user request,
+ xfixes/cursor.c uses it to determine if the cursor is enabled */
+extern Bool EnableCursor;
+
+#endif /* INPUT_H */
diff --git a/xorg-server/include/misc.h b/xorg-server/include/misc.h index 877c682d4..a2109e63a 100644 --- a/xorg-server/include/misc.h +++ b/xorg-server/include/misc.h @@ -166,9 +166,9 @@ typedef struct _xReq *xReqPtr; #include <math.h> #undef MAXSHORT -#define MAXSHORT SHRT_MAX +#define MAXSHORT 32767 #undef MINSHORT -#define MINSHORT SHRT_MIN +#define MINSHORT -32768 #undef MAXINT #define MAXINT INT_MAX #undef MININT @@ -185,7 +185,7 @@ typedef struct _xReq *xReqPtr; * @param bits The minimum number of bits needed. * @return The number of bytes needed to hold bits. */ -static inline int +static __inline int bits_to_bytes(const int bits) { return ((bits + 7) >> 3); } @@ -195,7 +195,7 @@ bits_to_bytes(const int bits) { * @param bytes The minimum number of bytes needed. * @return The number of 4-byte units needed to hold bytes. */ -static inline int +static __inline int bytes_to_int32(const int bytes) { return (((bytes) + 3) >> 2); } @@ -205,7 +205,7 @@ bytes_to_int32(const int bytes) { * @param bytes The minimum number of bytes needed. * @return The closest multiple of 4 that is equal or higher than bytes. */ -static inline int +static __inline int pad_to_int32(const int bytes) { return (((bytes) + 3) & ~3); } diff --git a/xorg-server/include/os.h b/xorg-server/include/os.h index 2f6b0c06f..7b99a597e 100644 --- a/xorg-server/include/os.h +++ b/xorg-server/include/os.h @@ -522,4 +522,8 @@ extern _X_EXPORT void LogPrintMarkers(void); extern _X_EXPORT void xorg_backtrace(void); +#ifdef _MSC_VER +#define snprintf _snprintf +#endif + #endif /* OS_H */ diff --git a/xorg-server/include/pixmapstr.h b/xorg-server/include/pixmapstr.h index 702faf0ac..8002b170a 100644 --- a/xorg-server/include/pixmapstr.h +++ b/xorg-server/include/pixmapstr.h @@ -76,10 +76,8 @@ typedef struct _Pixmap { int refcnt; int devKind; /* This is the pitch of the pixmap, typically width*bpp/8. */ DevUnion devPrivate; /* When !NULL, devPrivate.ptr points to the raw pixel data. */ -#ifdef COMPOSITE short screen_x; short screen_y; -#endif unsigned usage_hint; /* see CREATE_PIXMAP_USAGE_* */ } PixmapRec; diff --git a/xorg-server/include/scrnintstr.h b/xorg-server/include/scrnintstr.h index ab50e7a32..2299504c7 100644 --- a/xorg-server/include/scrnintstr.h +++ b/xorg-server/include/scrnintstr.h @@ -68,7 +68,7 @@ typedef struct _Visual { VisualID vid; short class; short bitsPerRGBValue; - short ColormapEntries; + long ColormapEntries; short nplanes;/* = log2 (ColormapEntries). This does not * imply that the screen has this many planes. * it may have more or fewer */ @@ -438,6 +438,10 @@ typedef void (* MarkUnrealizedWindowProcPtr)( WindowPtr /*pWin*/, Bool /*fromConfigure*/); +#ifdef CreateWindow +#undef CreateWindow +#endif + typedef Bool (* DeviceCursorInitializeProcPtr)( DeviceIntPtr /* pDev */, ScreenPtr /* pScreen */); diff --git a/xorg-server/include/servermd.h b/xorg-server/include/servermd.h index e1d644e00..c851d19bc 100644 --- a/xorg-server/include/servermd.h +++ b/xorg-server/include/servermd.h @@ -269,6 +269,12 @@ SOFTWARE. #define GLYPHPADBYTES 4 #endif /* linux/s390 */ +#ifdef WIN32 +#define IMAGE_BYTE_ORDER LSBFirst +#define BITMAP_BIT_ORDER LSBFirst +#define GLYPHPADBYTES 4 +#endif + /* size of buffer to use with GetImage, measured in bytes. There's obviously * a trade-off between the amount of heap used and the number of times the * ddx routine has to be called. diff --git a/xorg-server/include/site.h b/xorg-server/include/site.h index c07cbbfe6..7dcbd7e6f 100644 --- a/xorg-server/include/site.h +++ b/xorg-server/include/site.h @@ -52,7 +52,7 @@ SOFTWARE. * server executable. */ #ifndef VENDOR_STRING -#define VENDOR_STRING "The X.Org Foundation" +#define VENDOR_STRING "HMCA" #endif /* @@ -61,7 +61,7 @@ SOFTWARE. * by the vendor. */ #ifndef VENDOR_RELEASE -#define VENDOR_RELEASE 6600 +#define VENDOR_RELEASE XORG_VERSION_CURRENT #endif /* diff --git a/xorg-server/include/version-config.h b/xorg-server/include/version-config.h new file mode 100644 index 000000000..8bae75eaa --- /dev/null +++ b/xorg-server/include/version-config.h @@ -0,0 +1,16 @@ +/* version-config.h.in: not generated */ + +#ifndef VERSION_CONFIG_H +#define VERSION_CONFIG_H + +/* Vendor man version */ +#undef VENDOR_MAN_VERSION + +/* Vendor name */ +#define VENDOR_NAME "HMCA" + +/* Vendor release */ +#define VENDOR_RELEASE XORG_VERSION_CURRENT + +#endif /* VERSION_CONFIG_H */ + diff --git a/xorg-server/include/windowstr.h b/xorg-server/include/windowstr.h index 96bee9b93..94e04ead2 100644 --- a/xorg-server/include/windowstr.h +++ b/xorg-server/include/windowstr.h @@ -141,7 +141,7 @@ typedef struct _Window { RegionRec borderSize; DDXPointRec origin; /* position relative to parent */ unsigned short borderWidth; - unsigned short deliverableEvents; /* all masks from all clients */ + unsigned long deliverableEvents; /* all masks from all clients */ Mask eventMask; /* mask from the creating client */ PixUnion background; PixUnion border; diff --git a/xorg-server/include/xkb-config.h b/xorg-server/include/xkb-config.h new file mode 100644 index 000000000..9f7dac59e --- /dev/null +++ b/xorg-server/include/xkb-config.h @@ -0,0 +1,36 @@ +/* include/xkb-config.h. Generated from xkb-config.h.in by configure. */ +/* xkb-config.h.in: not at all generated. -*- c -*- + * + */ + +#ifndef _XKB_CONFIG_H_ +#define _XKB_CONFIG_H_ + +/* Default set of XKB rules. */ +#define XKB_DFLT_RULES "xorg" + +/* Default XKB model. */ +#define XKB_DFLT_MODEL "pc104" + +/* Default XKB layout. */ +#define XKB_DFLT_LAYOUT "us" + +/* Default XKB variant. */ +#define XKB_DFLT_VARIANT "" + +/* Default XKB options. */ +#define XKB_DFLT_OPTIONS "" + +/* Path to XKB definitions. */ +#define XKB_BASE_DIRECTORY "xkbdata" + +/* Path to xkbcomp. */ +#define XKB_BIN_DIRECTORY "." + +/* XKB output dir for compiled keymaps. */ +#define XKM_OUTPUT_DIR "xkbdata/compiled/" + +/* Do not have `strcasecmp'. */ +/* #undef NEED_STRCASECMP */ + +#endif /* _XKB_CONFIG_H_ */ diff --git a/xorg-server/include/xkbsrv.h b/xorg-server/include/xkbsrv.h index ebc7cdbb8..1d0041e28 100644 --- a/xorg-server/include/xkbsrv.h +++ b/xorg-server/include/xkbsrv.h @@ -1,1005 +1,1005 @@ -/************************************************************ -Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. - -Permission to use, copy, modify, and distribute this -software and its documentation for any purpose and without -fee is hereby granted, 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 Silicon Graphics not be -used in advertising or publicity pertaining to distribution -of the software without specific prior written permission. -Silicon Graphics makes no representation about the suitability -of this software for any purpose. It is provided "as is" -without any express or implied warranty. - -SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON -GRAPHICS 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. - -********************************************************/ - -#ifndef _XKBSRV_H_ -#define _XKBSRV_H_ - -#define XkbAllocClientMap SrvXkbAllocClientMap -#define XkbAllocServerMap SrvXkbAllocServerMap -#define XkbChangeTypesOfKey SrvXkbChangeTypesOfKey -#define XkbCopyKeyTypes SrvXkbCopyKeyTypes -#define XkbFreeClientMap SrvXkbFreeClientMap -#define XkbFreeServerMap SrvXkbFreeServerMap -#define XkbKeyTypesForCoreSymbols SrvXkbKeyTypesForCoreSymbols -#define XkbApplyCompatMapToKey SrvXkbApplyCompatMapToKey -#define XkbResizeKeyActions SrvXkbResizeKeyActions -#define XkbResizeKeySyms SrvXkbResizeKeySyms -#define XkbResizeKeyType SrvXkbResizeKeyType -#define XkbAllocCompatMap SrvXkbAllocCompatMap -#define XkbAllocControls SrvXkbAllocControls -#define XkbAllocIndicatorMaps SrvXkbAllocIndicatorMaps -#define XkbAllocKeyboard SrvXkbAllocKeyboard -#define XkbAllocNames SrvXkbAllocNames -#define XkbFreeCompatMap SrvXkbFreeCompatMap -#define XkbFreeKeyboard SrvXkbFreeKeyboard -#define XkbFreeNames SrvXkbFreeNames -#define XkbLatchModifiers SrvXkbLatchModifiers -#define XkbLatchGroup SrvXkbLatchGroup -#define XkbVirtualModsToReal SrvXkbVirtualModsToReal -#define XkbChangeKeycodeRange SrvXkbChangeKeycodeRange -#define XkbApplyVirtualModChanges SrvXkbApplyVirtualModChanges - -#include <X11/extensions/XKBproto.h> -#include "xkbstr.h" -#include "xkbrules.h" -#include "inputstr.h" -#include "events.h" - -typedef struct _XkbInterest { - DeviceIntPtr dev; - ClientPtr client; - XID resource; - struct _XkbInterest * next; - CARD16 extDevNotifyMask; - CARD16 stateNotifyMask; - CARD16 namesNotifyMask; - CARD32 ctrlsNotifyMask; - CARD8 compatNotifyMask; - BOOL bellNotifyMask; - BOOL actionMessageMask; - CARD16 accessXNotifyMask; - CARD32 iStateNotifyMask; - CARD32 iMapNotifyMask; - CARD16 altSymsNotifyMask; - CARD32 autoCtrls; - CARD32 autoCtrlValues; -} XkbInterestRec,*XkbInterestPtr; - -typedef struct _XkbRadioGroup { - CARD8 flags; - CARD8 nMembers; - CARD8 dfltDown; - CARD8 currentDown; - CARD8 members[XkbRGMaxMembers]; -} XkbRadioGroupRec, *XkbRadioGroupPtr; - -typedef struct _XkbEventCause { - CARD8 kc; - CARD8 event; - CARD8 mjr; - CARD8 mnr; - ClientPtr client; -} XkbEventCauseRec,*XkbEventCausePtr; -#define XkbSetCauseKey(c,k,e) { (c)->kc= (k),(c)->event= (e),\ - (c)->mjr= (c)->mnr= 0; \ - (c)->client= NULL; } -#define XkbSetCauseReq(c,j,n,cl) { (c)->kc= (c)->event= 0,\ - (c)->mjr= (j),(c)->mnr= (n);\ - (c)->client= (cl); } -#define XkbSetCauseCoreReq(c,e,cl) XkbSetCauseReq(c,e,0,cl) -#define XkbSetCauseXkbReq(c,e,cl) XkbSetCauseReq(c,XkbReqCode,e,cl) -#define XkbSetCauseUnknown(c) XkbSetCauseKey(c,0,0) - -#define _OFF_TIMER 0 -#define _KRG_WARN_TIMER 1 -#define _KRG_TIMER 2 -#define _SK_TIMEOUT_TIMER 3 -#define _ALL_TIMEOUT_TIMER 4 - -#define _BEEP_NONE 0 -#define _BEEP_FEATURE_ON 1 -#define _BEEP_FEATURE_OFF 2 -#define _BEEP_FEATURE_CHANGE 3 -#define _BEEP_SLOW_WARN 4 -#define _BEEP_SLOW_PRESS 5 -#define _BEEP_SLOW_ACCEPT 6 -#define _BEEP_SLOW_REJECT 7 -#define _BEEP_SLOW_RELEASE 8 -#define _BEEP_STICKY_LATCH 9 -#define _BEEP_STICKY_LOCK 10 -#define _BEEP_STICKY_UNLOCK 11 -#define _BEEP_LED_ON 12 -#define _BEEP_LED_OFF 13 -#define _BEEP_LED_CHANGE 14 -#define _BEEP_BOUNCE_REJECT 15 - -typedef struct _XkbFilter { - CARD16 keycode; - CARD8 what; - CARD8 active; - CARD8 filterOthers; - CARD32 priv; - XkbAction upAction; - int (*filter)( - struct _XkbSrvInfo* /* xkbi */, - struct _XkbFilter * /* filter */, - unsigned /* keycode */, - XkbAction * /* action */ - ); - struct _XkbFilter *next; -} XkbFilterRec,*XkbFilterPtr; - -typedef struct _XkbSrvInfo { - XkbStateRec prev_state; - XkbStateRec state; - XkbDescPtr desc; - - DeviceIntPtr device; - KbdCtrlProcPtr kbdProc; - - XkbRadioGroupPtr radioGroups; - CARD8 nRadioGroups; - CARD8 clearMods; - CARD8 setMods; - INT16 groupChange; - - CARD16 dfltPtrDelta; - - double mouseKeysCurve; - double mouseKeysCurveFactor; - INT16 mouseKeysDX; - INT16 mouseKeysDY; - CARD8 mouseKeysFlags; - Bool mouseKeysAccel; - CARD8 mouseKeysCounter; - - CARD8 lockedPtrButtons; - CARD8 shiftKeyCount; - KeyCode mouseKey; - KeyCode inactiveKey; - KeyCode slowKey; - KeyCode repeatKey; - CARD8 krgTimerActive; - CARD8 beepType; - CARD8 beepCount; - - CARD32 flags; - CARD32 lastPtrEventTime; - CARD32 lastShiftEventTime; - OsTimerPtr beepTimer; - OsTimerPtr mouseKeyTimer; - OsTimerPtr slowKeysTimer; - OsTimerPtr bounceKeysTimer; - OsTimerPtr repeatKeyTimer; - OsTimerPtr krgTimer; - - int szFilters; - XkbFilterPtr filters; -} XkbSrvInfoRec, *XkbSrvInfoPtr; - -#define XkbSLI_IsDefault (1L<<0) -#define XkbSLI_HasOwnState (1L<<1) - -typedef struct _XkbSrvLedInfo { - CARD16 flags; - CARD16 class; - CARD16 id; - union { - KbdFeedbackPtr kf; - LedFeedbackPtr lf; - } fb; - - CARD32 physIndicators; - CARD32 autoState; - CARD32 explicitState; - CARD32 effectiveState; - - CARD32 mapsPresent; - CARD32 namesPresent; - XkbIndicatorMapPtr maps; - Atom * names; - - CARD32 usesBase; - CARD32 usesLatched; - CARD32 usesLocked; - CARD32 usesEffective; - CARD32 usesCompat; - CARD32 usesControls; - - CARD32 usedComponents; -} XkbSrvLedInfoRec, *XkbSrvLedInfoPtr; - -/* - * Settings for xkbClientFlags field (used by DIX) - * These flags _must_ not overlap with XkbPCF_* - */ -#define _XkbClientInitialized (1<<15) - -#define _XkbWantsDetectableAutoRepeat(c)\ - ((c)->xkbClientFlags&XkbPCF_DetectableAutoRepeatMask) - -/* - * Settings for flags field - */ -#define _XkbStateNotifyInProgress (1<<0) - -typedef struct -{ - ProcessInputProc processInputProc; - /* If processInputProc is set to something different than realInputProc, - * UNWRAP and COND_WRAP will not touch processInputProc and update only - * realInputProc. This ensures that - * processInputProc == (frozen ? EnqueueEvent : realInputProc) - * - * WRAP_PROCESS_INPUT_PROC should only be called during initialization, - * since it may destroy this invariant. - */ - ProcessInputProc realInputProc; - DeviceUnwrapProc unwrapProc; -} xkbDeviceInfoRec, *xkbDeviceInfoPtr; - -#define WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ - device->public.processInputProc = proc; \ - oldprocs->processInputProc = \ - oldprocs->realInputProc = device->public.realInputProc; \ - device->public.realInputProc = proc; \ - oldprocs->unwrapProc = device->unwrapProc; \ - device->unwrapProc = unwrapproc; - -#define COND_WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \ - if (device->public.processInputProc == device->public.realInputProc)\ - device->public.processInputProc = proc; \ - oldprocs->processInputProc = \ - oldprocs->realInputProc = device->public.realInputProc; \ - device->public.realInputProc = proc; \ - oldprocs->unwrapProc = device->unwrapProc; \ - device->unwrapProc = unwrapproc; - -#define UNWRAP_PROCESS_INPUT_PROC(device, oldprocs, backupproc) \ - backupproc = device->public.realInputProc; \ - if (device->public.processInputProc == device->public.realInputProc)\ - device->public.processInputProc = oldprocs->realInputProc; \ - device->public.realInputProc = oldprocs->realInputProc; \ - device->unwrapProc = oldprocs->unwrapProc; - -extern _X_EXPORT DevPrivateKey xkbDevicePrivateKey; -#define XKBDEVICEINFO(dev) ((xkbDeviceInfoPtr)dixLookupPrivate(&(dev)->devPrivates, xkbDevicePrivateKey)) - -extern _X_EXPORT void xkbUnwrapProc(DeviceIntPtr, DeviceHandleProc, pointer); - -/***====================================================================***/ - - -/***====================================================================***/ - -#define XkbAX_KRGMask (XkbSlowKeysMask|XkbBounceKeysMask) -#define XkbAllFilteredEventsMask \ - (XkbAccessXKeysMask|XkbRepeatKeysMask|XkbMouseKeysAccelMask|XkbAX_KRGMask) - -/***====================================================================***/ - -extern _X_EXPORT int XkbReqCode; -extern _X_EXPORT int XkbEventBase; -extern _X_EXPORT int XkbKeyboardErrorCode; -extern _X_EXPORT char * XkbBaseDirectory; -extern _X_EXPORT char * XkbBinDirectory; - -extern _X_EXPORT CARD32 xkbDebugFlags; - -#define _XkbTypedAlloc(t) ((t *)xalloc(sizeof(t))) -#define _XkbTypedCalloc(n,t) ((t *)Xcalloc((n)*sizeof(t))) -#define _XkbTypedRealloc(o,n,t) \ - ((o)?(t *)Xrealloc((o),(n)*sizeof(t)):_XkbTypedCalloc(n,t)) -#define _XkbClearElems(a,f,l,t) bzero(&(a)[f],((l)-(f)+1)*sizeof(t)) - -#define _XkbLibError(c,l,d) /* Epoch fail */ -#define _XkbErrCode2(a,b) ((XID)((((unsigned int)(a))<<24)|((b)&0xffffff))) -#define _XkbErrCode3(a,b,c) _XkbErrCode2(a,(((unsigned int)(b))<<16)|(c)) -#define _XkbErrCode4(a,b,c,d) _XkbErrCode3(a,b,((((unsigned int)(c))<<8)|(d))) - -extern _X_EXPORT int DeviceKeyPress,DeviceKeyRelease,DeviceMotionNotify; -extern _X_EXPORT int DeviceButtonPress,DeviceButtonRelease; - -#define _XkbIsPressEvent(t) (((t)==KeyPress)||((t)==DeviceKeyPress)) -#define _XkbIsReleaseEvent(t) (((t)==KeyRelease)||((t)==DeviceKeyRelease)) - -#define XConvertCase(s,l,u) XkbConvertCase(s,l,u) -#undef IsKeypadKey -#define IsKeypadKey(s) XkbKSIsKeypad(s) - -#define Status int - -#ifndef True -#define True TRUE -#define False FALSE -#endif - -extern _X_EXPORT void XkbUseMsg( - void -); - -extern _X_EXPORT int XkbProcessArguments( - int /* argc */, - char ** /* argv */, - int /* i */ -); - -extern _X_EXPORT void XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc); - -extern _X_EXPORT void XkbFreeCompatMap( - XkbDescPtr /* xkb */, - unsigned int /* which */, - Bool /* freeMap */ -); - -extern _X_EXPORT void XkbFreeNames( - XkbDescPtr /* xkb */, - unsigned int /* which */, - Bool /* freeMap */ -); - -extern _X_EXPORT int _XkbLookupAnyDevice( - DeviceIntPtr *pDev, - int id, - ClientPtr client, - Mask access_mode, - int *xkb_err -); - -extern _X_EXPORT int _XkbLookupKeyboard( - DeviceIntPtr *pDev, - int id, - ClientPtr client, - Mask access_mode, - int *xkb_err -); - -extern _X_EXPORT int _XkbLookupBellDevice( - DeviceIntPtr *pDev, - int id, - ClientPtr client, - Mask access_mode, - int *xkb_err -); - -extern _X_EXPORT int _XkbLookupLedDevice( - DeviceIntPtr *pDev, - int id, - ClientPtr client, - Mask access_mode, - int *xkb_err -); - -extern _X_EXPORT int _XkbLookupButtonDevice( - DeviceIntPtr *pDev, - int id, - ClientPtr client, - Mask access_mode, - int *xkb_err -); - -extern _X_EXPORT XkbDescPtr XkbAllocKeyboard( - void -); - -extern _X_EXPORT Status XkbAllocClientMap( - XkbDescPtr /* xkb */, - unsigned int /* which */, - unsigned int /* nTypes */ -); - -extern _X_EXPORT Status XkbAllocServerMap( - XkbDescPtr /* xkb */, - unsigned int /* which */, - unsigned int /* nNewActions */ -); - -extern _X_EXPORT void XkbFreeClientMap( - XkbDescPtr /* xkb */, - unsigned int /* what */, - Bool /* freeMap */ -); - -extern _X_EXPORT void XkbFreeServerMap( - XkbDescPtr /* xkb */, - unsigned int /* what */, - Bool /* freeMap */ -); - -extern _X_EXPORT Status XkbAllocIndicatorMaps( - XkbDescPtr /* xkb */ -); - -extern _X_EXPORT Status XkbAllocCompatMap( - XkbDescPtr /* xkb */, - unsigned int /* which */, - unsigned int /* nInterpret */ -); - -extern _X_EXPORT Status XkbAllocNames( - XkbDescPtr /* xkb */, - unsigned int /* which */, - int /* nTotalRG */, - int /* nTotalAliases */ -); - -extern _X_EXPORT Status XkbAllocControls( - XkbDescPtr /* xkb */, - unsigned int /* which*/ -); - -extern _X_EXPORT Status XkbCopyKeyTypes( - XkbKeyTypePtr /* from */, - XkbKeyTypePtr /* into */, - int /* num_types */ -); - -extern _X_EXPORT Status XkbResizeKeyType( - XkbDescPtr /* xkb */, - int /* type_ndx */, - int /* map_count */, - Bool /* want_preserve */, - int /* new_num_lvls */ -); - -extern _X_EXPORT void XkbFreeKeyboard( - XkbDescPtr /* xkb */, - unsigned int /* which */, - Bool /* freeDesc */ -); - -extern _X_EXPORT void XkbSetActionKeyMods( - XkbDescPtr /* xkb */, - XkbAction * /* act */, - unsigned int /* mods */ -); - -extern _X_EXPORT unsigned int XkbMaskForVMask( - XkbDescPtr /* xkb */, - unsigned int /* vmask */ -); - -extern _X_EXPORT Bool XkbVirtualModsToReal( - XkbDescPtr /* xkb */, - unsigned int /* virtua_mask */, - unsigned int * /* mask_rtrn */ -); - -extern _X_EXPORT unsigned int XkbAdjustGroup( - int /* group */, - XkbControlsPtr /* ctrls */ -); - -extern _X_EXPORT KeySym *XkbResizeKeySyms( - XkbDescPtr /* xkb */, - int /* key */, - int /* needed */ -); - -extern _X_EXPORT XkbAction *XkbResizeKeyActions( - XkbDescPtr /* xkb */, - int /* key */, - int /* needed */ -); - -extern _X_EXPORT void XkbUpdateKeyTypesFromCore( - DeviceIntPtr /* pXDev */, - KeySymsPtr /* syms */, - KeyCode /* first */, - CARD8 /* num */, - XkbChangesPtr /* pChanges */ -); - -extern _X_EXPORT void XkbUpdateDescActions( - XkbDescPtr /* xkb */, - KeyCode /* first */, - CARD8 /* num */, - XkbChangesPtr /* changes */ -); - -extern _X_EXPORT void XkbUpdateActions( - DeviceIntPtr /* pXDev */, - KeyCode /* first */, - CARD8 /* num */, - XkbChangesPtr /* pChanges */, - unsigned int * /* needChecksRtrn */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT KeySymsPtr XkbGetCoreMap( - DeviceIntPtr /* keybd */ -); - -extern _X_EXPORT void XkbApplyMappingChange( - DeviceIntPtr /* pXDev */, - KeySymsPtr /* map */, - KeyCode /* firstKey */, - CARD8 /* num */, - CARD8 * /* modmap */, - ClientPtr /* client */ -); - -extern _X_EXPORT void XkbSetIndicators( - DeviceIntPtr /* pXDev */, - CARD32 /* affect */, - CARD32 /* values */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbUpdateIndicators( - DeviceIntPtr /* keybd */, - CARD32 /* changed */, - Bool /* check_edevs */, - XkbChangesPtr /* pChanges */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT XkbSrvLedInfoPtr XkbAllocSrvLedInfo( - DeviceIntPtr /* dev */, - KbdFeedbackPtr /* kf */, - LedFeedbackPtr /* lf */, - unsigned int /* needed_parts */ -); - -extern _X_EXPORT XkbSrvLedInfoPtr XkbCopySrvLedInfo( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* src */, - KbdFeedbackPtr /* kf */, - LedFeedbackPtr /* lf */ -); - - -extern _X_EXPORT XkbSrvLedInfoPtr XkbFindSrvLedInfo( - DeviceIntPtr /* dev */, - unsigned int /* class */, - unsigned int /* id */, - unsigned int /* needed_parts */ -); - -extern _X_EXPORT void XkbApplyLedNameChanges( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* sli */, - unsigned int /* changed_names */, - xkbExtensionDeviceNotify * /* ed */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbApplyLedMapChanges( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* sli */, - unsigned int /* changed_maps */, - xkbExtensionDeviceNotify * /* ed */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbApplyLedStateChanges( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* sli */, - unsigned int /* changed_leds */, - xkbExtensionDeviceNotify * /* ed */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbFlushLedEvents( - DeviceIntPtr /* dev */, - DeviceIntPtr /* kbd */, - XkbSrvLedInfoPtr /* sli */, - xkbExtensionDeviceNotify * /* ed */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT unsigned int XkbIndicatorsToUpdate( - DeviceIntPtr /* dev */, - unsigned long /* state_changes */, - Bool /* enabled_ctrl_changes */ -); - -extern _X_EXPORT void XkbComputeDerivedState( - XkbSrvInfoPtr /* xkbi */ -); - -extern _X_EXPORT void XkbCheckSecondaryEffects( - XkbSrvInfoPtr /* xkbi */, - unsigned int /* which */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbCheckIndicatorMaps( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* sli */, - unsigned int /* which */ -); - -extern _X_EXPORT unsigned int XkbStateChangedFlags( - XkbStatePtr /* old */, - XkbStatePtr /* new */ -); - -extern _X_EXPORT void XkbSendStateNotify( - DeviceIntPtr /* kbd */, - xkbStateNotify * /* pSN */ -); - -extern _X_EXPORT void XkbSendMapNotify( - DeviceIntPtr /* kbd */, - xkbMapNotify * /* ev */ -); - -extern _X_EXPORT int XkbComputeControlsNotify( - DeviceIntPtr /* kbd */, - XkbControlsPtr /* old */, - XkbControlsPtr /* new */, - xkbControlsNotify * /* pCN */, - Bool /* forceCtrlProc */ -); - -extern _X_EXPORT void XkbSendControlsNotify( - DeviceIntPtr /* kbd */, - xkbControlsNotify * /* ev */ -); - -extern _X_EXPORT void XkbSendCompatMapNotify( - DeviceIntPtr /* kbd */, - xkbCompatMapNotify * /* ev */ -); - -extern _X_EXPORT void XkbHandleBell( - BOOL /* force */, - BOOL /* eventOnly */, - DeviceIntPtr /* kbd */, - CARD8 /* percent */, - pointer /* ctrl */, - CARD8 /* class */, - Atom /* name */, - WindowPtr /* pWin */, - ClientPtr /* pClient */ -); - -extern _X_EXPORT void XkbSendAccessXNotify( - DeviceIntPtr /* kbd */, - xkbAccessXNotify * /* pEv */ -); - -extern _X_EXPORT void XkbSendNamesNotify( - DeviceIntPtr /* kbd */, - xkbNamesNotify * /* ev */ -); - -extern _X_EXPORT void XkbSendActionMessage( - DeviceIntPtr /* kbd */, - xkbActionMessage * /* ev */ -); - -extern _X_EXPORT void XkbSendExtensionDeviceNotify( - DeviceIntPtr /* kbd */, - ClientPtr /* client */, - xkbExtensionDeviceNotify * /* ev */ -); - -extern _X_EXPORT void XkbSendNotification( - DeviceIntPtr /* kbd */, - XkbChangesPtr /* pChanges */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbProcessKeyboardEvent( - DeviceEvent* /* event */, - DeviceIntPtr /* keybd */ -); - -extern _X_EXPORT void XkbHandleActions( - DeviceIntPtr /* dev */, - DeviceIntPtr /* kbd */, - DeviceEvent* /* event */ -); - -extern _X_EXPORT Bool XkbEnableDisableControls( - XkbSrvInfoPtr /* xkbi */, - unsigned long /* change */, - unsigned long /* newValues */, - XkbChangesPtr /* changes */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void AccessXInit( - DeviceIntPtr /* dev */ -); - -extern _X_EXPORT Bool AccessXFilterPressEvent( - DeviceEvent* /* event */, - DeviceIntPtr /* keybd */ -); - -extern _X_EXPORT Bool AccessXFilterReleaseEvent( - DeviceEvent* /* event */, - DeviceIntPtr /* keybd */ -); - -extern _X_EXPORT void AccessXCancelRepeatKey( - XkbSrvInfoPtr /* xkbi */, - KeyCode /* key */ -); - -extern _X_EXPORT void AccessXComputeCurveFactor( - XkbSrvInfoPtr /* xkbi */, - XkbControlsPtr /* ctrls */ -); - -extern _X_EXPORT XkbInterestPtr XkbFindClientResource( - DevicePtr /* inDev */, - ClientPtr /* client */ -); - -extern _X_EXPORT XkbInterestPtr XkbAddClientResource( - DevicePtr /* inDev */, - ClientPtr /* client */, - XID /* id */ -); - -extern _X_EXPORT int XkbRemoveResourceClient( - DevicePtr /* inDev */, - XID /* id */ -); - -extern _X_EXPORT int XkbDDXAccessXBeep( - DeviceIntPtr /* dev */, - unsigned int /* what */, - unsigned int /* which */ -); - -extern _X_EXPORT int XkbDDXUsesSoftRepeat( - DeviceIntPtr /* dev */ -); - -extern _X_EXPORT void XkbDDXKeybdCtrlProc( - DeviceIntPtr /* dev */, - KeybdCtrl * /* ctrl */ -); - -extern _X_EXPORT void XkbDDXChangeControls( - DeviceIntPtr /* dev */, - XkbControlsPtr /* old */, - XkbControlsPtr /* new */ -); - -extern _X_EXPORT void XkbDDXUpdateDeviceIndicators( - DeviceIntPtr /* dev */, - XkbSrvLedInfoPtr /* sli */, - CARD32 /* newState */ -); - -extern _X_EXPORT void XkbDDXFakePointerMotion( - unsigned int /* flags */, - int /* x */, - int /* y */ -); - -extern _X_EXPORT void XkbDDXFakeDeviceButton( - DeviceIntPtr /* dev */, - Bool /* press */, - int /* button */ -); - -extern _X_EXPORT int XkbDDXTerminateServer( - DeviceIntPtr /* dev */, - KeyCode /* key */, - XkbAction * /* act */ -); - -extern _X_EXPORT int XkbDDXSwitchScreen( - DeviceIntPtr /* dev */, - KeyCode /* key */, - XkbAction * /* act */ -); - -extern _X_EXPORT int XkbDDXPrivate( - DeviceIntPtr /* dev */, - KeyCode /* key */, - XkbAction * /* act */ -); - -extern _X_EXPORT void XkbDisableComputedAutoRepeats( - DeviceIntPtr /* pXDev */, - unsigned int /* key */ -); - -extern _X_EXPORT void XkbSetRepeatKeys( - DeviceIntPtr /* pXDev */, - int /* key */, - int /* onoff */ -); - -extern _X_EXPORT int XkbLatchModifiers( - DeviceIntPtr /* pXDev */, - CARD8 /* mask */, - CARD8 /* latches */ -); - -extern _X_EXPORT int XkbLatchGroup( - DeviceIntPtr /* pXDev */, - int /* group */ -); - -extern _X_EXPORT void XkbClearAllLatchesAndLocks( - DeviceIntPtr /* dev */, - XkbSrvInfoPtr /* xkbi */, - Bool /* genEv */, - XkbEventCausePtr /* cause */ -); - -extern _X_EXPORT void XkbGetRulesDflts( - XkbRMLVOSet * /* rmlvo */ -); - -extern _X_EXPORT void XkbFreeRMLVOSet( - XkbRMLVOSet * /* rmlvo */, - Bool /* freeRMLVO */ -); - -extern _X_EXPORT void XkbSetRulesDflts( - XkbRMLVOSet * /* rmlvo */ -); - -extern _X_EXPORT void XkbDeleteRulesDflts( - void -); - -extern _X_EXPORT int SProcXkbDispatch( - ClientPtr /* client */ -); - -extern _X_EXPORT XkbGeometryPtr XkbLookupNamedGeometry( - DeviceIntPtr /* dev */, - Atom /* name */, - Bool * /* shouldFree */ -); - -extern _X_EXPORT char * _XkbDupString( - const char * /* str */ -); - -extern _X_EXPORT void XkbConvertCase( - KeySym /* sym */, - KeySym * /* lower */, - KeySym * /* upper */ -); - -extern _X_EXPORT Status XkbChangeKeycodeRange( - XkbDescPtr /* xkb */, - int /* minKC */, - int /* maxKC */, - XkbChangesPtr /* changes */ -); - -extern _X_EXPORT void XkbFreeSrvLedInfo( - XkbSrvLedInfoPtr /* sli */ -); - -extern _X_EXPORT void XkbFreeInfo( - XkbSrvInfoPtr /* xkbi */ -); - -extern _X_EXPORT Status XkbChangeTypesOfKey( - XkbDescPtr /* xkb */, - int /* key */, - int /* nGroups */, - unsigned int /* groups */, - int * /* newTypesIn */, - XkbMapChangesPtr /* changes */ -); - -extern _X_EXPORT int XkbKeyTypesForCoreSymbols( - XkbDescPtr /* xkb */, - int /* map_width */, - KeySym * /* core_syms */, - unsigned int /* protected */, - int * /* types_inout */, - KeySym * /* xkb_syms_rtrn */ -); - -extern _X_EXPORT Bool XkbApplyCompatMapToKey( - XkbDescPtr /* xkb */, - KeyCode /* key */, - XkbChangesPtr /* changes */ -); - -extern _X_EXPORT Bool XkbApplyVirtualModChanges( - XkbDescPtr /* xkb */, - unsigned int /* changed */, - XkbChangesPtr /* changes */ -); - -extern _X_EXPORT void XkbSendNewKeyboardNotify( - DeviceIntPtr /* kbd */, - xkbNewKeyboardNotify * /* pNKN */ -); - -extern Bool XkbCopyKeymap( - XkbDescPtr /* dst */, - XkbDescPtr /* src */); - -extern Bool XkbCopyDeviceKeymap( - DeviceIntPtr /* dst */, - DeviceIntPtr /* src */); - -extern void XkbFilterEvents( - ClientPtr /* pClient */, - int /* nEvents */, - xEvent* /* xE */); - -extern int XkbGetEffectiveGroup( - XkbSrvInfoPtr /* xkbi */, - XkbStatePtr /* xkbstate */, - CARD8 /* keycode */); - -#include "xkbfile.h" -#include "xkbrules.h" - -#define _XkbListKeycodes 0 -#define _XkbListTypes 1 -#define _XkbListCompat 2 -#define _XkbListSymbols 3 -#define _XkbListGeometry 4 -#define _XkbListNumComponents 5 - -typedef struct _XkbSrvListInfo { - int szPool; - int nPool; - char * pool; - - int maxRtrn; - int nTotal; - - char * pattern[_XkbListNumComponents]; - int nFound[_XkbListNumComponents]; -} XkbSrvListInfoRec,*XkbSrvListInfoPtr; - -extern _X_EXPORT Status XkbDDXList( - DeviceIntPtr /* dev */, - XkbSrvListInfoPtr /* listing */, - ClientPtr /* client */ -); - -extern _X_EXPORT unsigned int XkbDDXLoadKeymapByNames( - DeviceIntPtr /* keybd */, - XkbComponentNamesPtr /* names */, - unsigned int /* want */, - unsigned int /* need */, - XkbDescPtr * /* finfoRtrn */, - char * /* keymapNameRtrn */, - int /* keymapNameRtrnLen */ -); - -extern _X_EXPORT Bool XkbDDXNamesFromRules( - DeviceIntPtr /* keybd */, - char * /* rules */, - XkbRF_VarDefsPtr /* defs */, - XkbComponentNamesPtr /* names */ -); - -extern _X_EXPORT XkbDescPtr XkbCompileKeymap( - DeviceIntPtr /* dev */, - XkbRMLVOSet * /* rmlvo */ -); - -#define XkbAtomGetString(s) NameForAtom(s) - -#endif /* _XKBSRV_H_ */ +/************************************************************
+Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
+
+Permission to use, copy, modify, and distribute this
+software and its documentation for any purpose and without
+fee is hereby granted, 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 Silicon Graphics not be
+used in advertising or publicity pertaining to distribution
+of the software without specific prior written permission.
+Silicon Graphics makes no representation about the suitability
+of this software for any purpose. It is provided "as is"
+without any express or implied warranty.
+
+SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
+GRAPHICS 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.
+
+********************************************************/
+
+#ifndef _XKBSRV_H_
+#define _XKBSRV_H_
+
+#define XkbAllocClientMap SrvXkbAllocClientMap
+#define XkbAllocServerMap SrvXkbAllocServerMap
+#define XkbChangeTypesOfKey SrvXkbChangeTypesOfKey
+#define XkbCopyKeyTypes SrvXkbCopyKeyTypes
+#define XkbFreeClientMap SrvXkbFreeClientMap
+#define XkbFreeServerMap SrvXkbFreeServerMap
+#define XkbKeyTypesForCoreSymbols SrvXkbKeyTypesForCoreSymbols
+#define XkbApplyCompatMapToKey SrvXkbApplyCompatMapToKey
+#define XkbResizeKeyActions SrvXkbResizeKeyActions
+#define XkbResizeKeySyms SrvXkbResizeKeySyms
+#define XkbResizeKeyType SrvXkbResizeKeyType
+#define XkbAllocCompatMap SrvXkbAllocCompatMap
+#define XkbAllocControls SrvXkbAllocControls
+#define XkbAllocIndicatorMaps SrvXkbAllocIndicatorMaps
+#define XkbAllocKeyboard SrvXkbAllocKeyboard
+#define XkbAllocNames SrvXkbAllocNames
+#define XkbFreeCompatMap SrvXkbFreeCompatMap
+#define XkbFreeKeyboard SrvXkbFreeKeyboard
+#define XkbFreeNames SrvXkbFreeNames
+#define XkbLatchModifiers SrvXkbLatchModifiers
+#define XkbLatchGroup SrvXkbLatchGroup
+#define XkbVirtualModsToReal SrvXkbVirtualModsToReal
+#define XkbChangeKeycodeRange SrvXkbChangeKeycodeRange
+#define XkbApplyVirtualModChanges SrvXkbApplyVirtualModChanges
+
+#include <X11/extensions/XKBproto.h>
+#include "xkbstr.h"
+#include "xkbrules.h"
+#include "inputstr.h"
+#include "events.h"
+
+typedef struct _XkbInterest {
+ DeviceIntPtr dev;
+ ClientPtr client;
+ XID resource;
+ struct _XkbInterest * next;
+ CARD16 extDevNotifyMask;
+ CARD16 stateNotifyMask;
+ CARD16 namesNotifyMask;
+ CARD32 ctrlsNotifyMask;
+ CARD8 compatNotifyMask;
+ BOOL bellNotifyMask;
+ BOOL actionMessageMask;
+ CARD16 accessXNotifyMask;
+ CARD32 iStateNotifyMask;
+ CARD32 iMapNotifyMask;
+ CARD16 altSymsNotifyMask;
+ CARD32 autoCtrls;
+ CARD32 autoCtrlValues;
+} XkbInterestRec,*XkbInterestPtr;
+
+typedef struct _XkbRadioGroup {
+ CARD8 flags;
+ CARD8 nMembers;
+ CARD8 dfltDown;
+ CARD8 currentDown;
+ CARD8 members[XkbRGMaxMembers];
+} XkbRadioGroupRec, *XkbRadioGroupPtr;
+
+typedef struct _XkbEventCause {
+ CARD8 kc;
+ CARD8 event;
+ CARD8 mjr;
+ CARD8 mnr;
+ ClientPtr client;
+} XkbEventCauseRec,*XkbEventCausePtr;
+#define XkbSetCauseKey(c,k,e) { (c)->kc= (k),(c)->event= (e),\
+ (c)->mjr= (c)->mnr= 0; \
+ (c)->client= NULL; }
+#define XkbSetCauseReq(c,j,n,cl) { (c)->kc= (c)->event= 0,\
+ (c)->mjr= (j),(c)->mnr= (n);\
+ (c)->client= (cl); }
+#define XkbSetCauseCoreReq(c,e,cl) XkbSetCauseReq(c,e,0,cl)
+#define XkbSetCauseXkbReq(c,e,cl) XkbSetCauseReq(c,XkbReqCode,e,cl)
+#define XkbSetCauseUnknown(c) XkbSetCauseKey(c,0,0)
+
+#define _OFF_TIMER 0
+#define _KRG_WARN_TIMER 1
+#define _KRG_TIMER 2
+#define _SK_TIMEOUT_TIMER 3
+#define _ALL_TIMEOUT_TIMER 4
+
+#define _BEEP_NONE 0
+#define _BEEP_FEATURE_ON 1
+#define _BEEP_FEATURE_OFF 2
+#define _BEEP_FEATURE_CHANGE 3
+#define _BEEP_SLOW_WARN 4
+#define _BEEP_SLOW_PRESS 5
+#define _BEEP_SLOW_ACCEPT 6
+#define _BEEP_SLOW_REJECT 7
+#define _BEEP_SLOW_RELEASE 8
+#define _BEEP_STICKY_LATCH 9
+#define _BEEP_STICKY_LOCK 10
+#define _BEEP_STICKY_UNLOCK 11
+#define _BEEP_LED_ON 12
+#define _BEEP_LED_OFF 13
+#define _BEEP_LED_CHANGE 14
+#define _BEEP_BOUNCE_REJECT 15
+
+typedef struct _XkbFilter {
+ CARD16 keycode;
+ CARD8 what;
+ CARD8 active;
+ CARD8 filterOthers;
+ CARD32 priv;
+ XkbAction upAction;
+ int (*filter)(
+ struct _XkbSrvInfo* /* xkbi */,
+ struct _XkbFilter * /* filter */,
+ unsigned /* keycode */,
+ XkbAction * /* action */
+ );
+ struct _XkbFilter *next;
+} XkbFilterRec,*XkbFilterPtr;
+
+typedef struct _XkbSrvInfo {
+ XkbStateRec prev_state;
+ XkbStateRec state;
+ XkbDescPtr desc;
+
+ DeviceIntPtr device;
+ KbdCtrlProcPtr kbdProc;
+
+ XkbRadioGroupPtr radioGroups;
+ CARD8 nRadioGroups;
+ CARD8 clearMods;
+ CARD8 setMods;
+ INT16 groupChange;
+
+ CARD16 dfltPtrDelta;
+
+ double mouseKeysCurve;
+ double mouseKeysCurveFactor;
+ INT16 mouseKeysDX;
+ INT16 mouseKeysDY;
+ CARD8 mouseKeysFlags;
+ Bool mouseKeysAccel;
+ CARD8 mouseKeysCounter;
+
+ CARD8 lockedPtrButtons;
+ CARD8 shiftKeyCount;
+ KeyCode mouseKey;
+ KeyCode inactiveKey;
+ KeyCode slowKey;
+ KeyCode repeatKey;
+ CARD8 krgTimerActive;
+ CARD8 beepType;
+ CARD8 beepCount;
+
+ CARD32 flags;
+ CARD32 lastPtrEventTime;
+ CARD32 lastShiftEventTime;
+ OsTimerPtr beepTimer;
+ OsTimerPtr mouseKeyTimer;
+ OsTimerPtr slowKeysTimer;
+ OsTimerPtr bounceKeysTimer;
+ OsTimerPtr repeatKeyTimer;
+ OsTimerPtr krgTimer;
+
+ int szFilters;
+ XkbFilterPtr filters;
+} XkbSrvInfoRec, *XkbSrvInfoPtr;
+
+#define XkbSLI_IsDefault (1L<<0)
+#define XkbSLI_HasOwnState (1L<<1)
+
+typedef struct _XkbSrvLedInfo {
+ CARD16 flags;
+ CARD16 class;
+ CARD16 id;
+ union {
+ KbdFeedbackPtr kf;
+ LedFeedbackPtr lf;
+ } fb;
+
+ CARD32 physIndicators;
+ CARD32 autoState;
+ CARD32 explicitState;
+ CARD32 effectiveState;
+
+ CARD32 mapsPresent;
+ CARD32 namesPresent;
+ XkbIndicatorMapPtr maps;
+ Atom * names;
+
+ CARD32 usesBase;
+ CARD32 usesLatched;
+ CARD32 usesLocked;
+ CARD32 usesEffective;
+ CARD32 usesCompat;
+ CARD32 usesControls;
+
+ CARD32 usedComponents;
+} XkbSrvLedInfoRec, *XkbSrvLedInfoPtr;
+
+/*
+ * Settings for xkbClientFlags field (used by DIX)
+ * These flags _must_ not overlap with XkbPCF_*
+ */
+#define _XkbClientInitialized (1<<15)
+
+#define _XkbWantsDetectableAutoRepeat(c)\
+ ((c)->xkbClientFlags&XkbPCF_DetectableAutoRepeatMask)
+
+/*
+ * Settings for flags field
+ */
+#define _XkbStateNotifyInProgress (1<<0)
+
+typedef struct
+{
+ ProcessInputProc processInputProc;
+ /* If processInputProc is set to something different than realInputProc,
+ * UNWRAP and COND_WRAP will not touch processInputProc and update only
+ * realInputProc. This ensures that
+ * processInputProc == (frozen ? EnqueueEvent : realInputProc)
+ *
+ * WRAP_PROCESS_INPUT_PROC should only be called during initialization,
+ * since it may destroy this invariant.
+ */
+ ProcessInputProc realInputProc;
+ DeviceUnwrapProc unwrapProc;
+} xkbDeviceInfoRec, *xkbDeviceInfoPtr;
+
+#define WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \
+ device->public.processInputProc = proc; \
+ oldprocs->processInputProc = \
+ oldprocs->realInputProc = device->public.realInputProc; \
+ device->public.realInputProc = proc; \
+ oldprocs->unwrapProc = device->unwrapProc; \
+ device->unwrapProc = unwrapproc;
+
+#define COND_WRAP_PROCESS_INPUT_PROC(device, oldprocs, proc, unwrapproc) \
+ if (device->public.processInputProc == device->public.realInputProc)\
+ device->public.processInputProc = proc; \
+ oldprocs->processInputProc = \
+ oldprocs->realInputProc = device->public.realInputProc; \
+ device->public.realInputProc = proc; \
+ oldprocs->unwrapProc = device->unwrapProc; \
+ device->unwrapProc = unwrapproc;
+
+#define UNWRAP_PROCESS_INPUT_PROC(device, oldprocs, backupproc) \
+ backupproc = device->public.realInputProc; \
+ if (device->public.processInputProc == device->public.realInputProc)\
+ device->public.processInputProc = oldprocs->realInputProc; \
+ device->public.realInputProc = oldprocs->realInputProc; \
+ device->unwrapProc = oldprocs->unwrapProc;
+
+extern _X_EXPORT DevPrivateKey xkbDevicePrivateKey;
+#define XKBDEVICEINFO(dev) ((xkbDeviceInfoPtr)dixLookupPrivate(&(dev)->devPrivates, xkbDevicePrivateKey))
+
+extern _X_EXPORT void xkbUnwrapProc(DeviceIntPtr, DeviceHandleProc, pointer);
+
+/***====================================================================***/
+
+
+/***====================================================================***/
+
+#define XkbAX_KRGMask (XkbSlowKeysMask|XkbBounceKeysMask)
+#define XkbAllFilteredEventsMask \
+ (XkbAccessXKeysMask|XkbRepeatKeysMask|XkbMouseKeysAccelMask|XkbAX_KRGMask)
+
+/***====================================================================***/
+
+extern _X_EXPORT int XkbReqCode;
+extern _X_EXPORT int XkbEventBase;
+extern _X_EXPORT int XkbKeyboardErrorCode;
+extern _X_EXPORT const char * XkbBaseDirectory;
+extern _X_EXPORT const char * XkbBinDirectory;
+
+extern _X_EXPORT CARD32 xkbDebugFlags;
+
+#define _XkbTypedAlloc(t) ((t *)xalloc(sizeof(t)))
+#define _XkbTypedCalloc(n,t) ((t *)Xcalloc((n)*sizeof(t)))
+#define _XkbTypedRealloc(o,n,t) \
+ ((o)?(t *)Xrealloc((o),(n)*sizeof(t)):_XkbTypedCalloc(n,t))
+#define _XkbClearElems(a,f,l,t) bzero(&(a)[f],((l)-(f)+1)*sizeof(t))
+
+#define _XkbLibError(c,l,d) /* Epoch fail */
+#define _XkbErrCode2(a,b) ((XID)((((unsigned int)(a))<<24)|((b)&0xffffff)))
+#define _XkbErrCode3(a,b,c) _XkbErrCode2(a,(((unsigned int)(b))<<16)|(c))
+#define _XkbErrCode4(a,b,c,d) _XkbErrCode3(a,b,((((unsigned int)(c))<<8)|(d)))
+
+extern _X_EXPORT int DeviceKeyPress,DeviceKeyRelease,DeviceMotionNotify;
+extern _X_EXPORT int DeviceButtonPress,DeviceButtonRelease;
+
+#define _XkbIsPressEvent(t) (((t)==KeyPress)||((t)==DeviceKeyPress))
+#define _XkbIsReleaseEvent(t) (((t)==KeyRelease)||((t)==DeviceKeyRelease))
+
+#define XConvertCase(s,l,u) XkbConvertCase(s,l,u)
+#undef IsKeypadKey
+#define IsKeypadKey(s) XkbKSIsKeypad(s)
+
+#define Status int
+
+#ifndef True
+#define True TRUE
+#define False FALSE
+#endif
+
+extern _X_EXPORT void XkbUseMsg(
+ void
+);
+
+extern _X_EXPORT int XkbProcessArguments(
+ int /* argc */,
+ char ** /* argv */,
+ int /* i */
+);
+
+extern _X_EXPORT void XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc);
+
+extern _X_EXPORT void XkbFreeCompatMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ Bool /* freeMap */
+);
+
+extern _X_EXPORT void XkbFreeNames(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ Bool /* freeMap */
+);
+
+extern _X_EXPORT int _XkbLookupAnyDevice(
+ DeviceIntPtr *pDev,
+ int id,
+ ClientPtr client,
+ Mask access_mode,
+ int *xkb_err
+);
+
+extern _X_EXPORT int _XkbLookupKeyboard(
+ DeviceIntPtr *pDev,
+ int id,
+ ClientPtr client,
+ Mask access_mode,
+ int *xkb_err
+);
+
+extern _X_EXPORT int _XkbLookupBellDevice(
+ DeviceIntPtr *pDev,
+ int id,
+ ClientPtr client,
+ Mask access_mode,
+ int *xkb_err
+);
+
+extern _X_EXPORT int _XkbLookupLedDevice(
+ DeviceIntPtr *pDev,
+ int id,
+ ClientPtr client,
+ Mask access_mode,
+ int *xkb_err
+);
+
+extern _X_EXPORT int _XkbLookupButtonDevice(
+ DeviceIntPtr *pDev,
+ int id,
+ ClientPtr client,
+ Mask access_mode,
+ int *xkb_err
+);
+
+extern _X_EXPORT XkbDescPtr XkbAllocKeyboard(
+ void
+);
+
+extern _X_EXPORT Status XkbAllocClientMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ unsigned int /* nTypes */
+);
+
+extern _X_EXPORT Status XkbAllocServerMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ unsigned int /* nNewActions */
+);
+
+extern _X_EXPORT void XkbFreeClientMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* what */,
+ Bool /* freeMap */
+);
+
+extern _X_EXPORT void XkbFreeServerMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* what */,
+ Bool /* freeMap */
+);
+
+extern _X_EXPORT Status XkbAllocIndicatorMaps(
+ XkbDescPtr /* xkb */
+);
+
+extern _X_EXPORT Status XkbAllocCompatMap(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ unsigned int /* nInterpret */
+);
+
+extern _X_EXPORT Status XkbAllocNames(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ int /* nTotalRG */,
+ int /* nTotalAliases */
+);
+
+extern _X_EXPORT Status XkbAllocControls(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which*/
+);
+
+extern _X_EXPORT Status XkbCopyKeyTypes(
+ XkbKeyTypePtr /* from */,
+ XkbKeyTypePtr /* into */,
+ int /* num_types */
+);
+
+extern _X_EXPORT Status XkbResizeKeyType(
+ XkbDescPtr /* xkb */,
+ int /* type_ndx */,
+ int /* map_count */,
+ Bool /* want_preserve */,
+ int /* new_num_lvls */
+);
+
+extern _X_EXPORT void XkbFreeKeyboard(
+ XkbDescPtr /* xkb */,
+ unsigned int /* which */,
+ Bool /* freeDesc */
+);
+
+extern _X_EXPORT void XkbSetActionKeyMods(
+ XkbDescPtr /* xkb */,
+ XkbAction * /* act */,
+ unsigned int /* mods */
+);
+
+extern _X_EXPORT unsigned int XkbMaskForVMask(
+ XkbDescPtr /* xkb */,
+ unsigned int /* vmask */
+);
+
+extern _X_EXPORT Bool XkbVirtualModsToReal(
+ XkbDescPtr /* xkb */,
+ unsigned int /* virtua_mask */,
+ unsigned int * /* mask_rtrn */
+);
+
+extern _X_EXPORT unsigned int XkbAdjustGroup(
+ int /* group */,
+ XkbControlsPtr /* ctrls */
+);
+
+extern _X_EXPORT KeySym *XkbResizeKeySyms(
+ XkbDescPtr /* xkb */,
+ int /* key */,
+ int /* needed */
+);
+
+extern _X_EXPORT XkbAction *XkbResizeKeyActions(
+ XkbDescPtr /* xkb */,
+ int /* key */,
+ int /* needed */
+);
+
+extern _X_EXPORT void XkbUpdateKeyTypesFromCore(
+ DeviceIntPtr /* pXDev */,
+ KeySymsPtr /* syms */,
+ KeyCode /* first */,
+ CARD8 /* num */,
+ XkbChangesPtr /* pChanges */
+);
+
+extern _X_EXPORT void XkbUpdateDescActions(
+ XkbDescPtr /* xkb */,
+ KeyCode /* first */,
+ CARD8 /* num */,
+ XkbChangesPtr /* changes */
+);
+
+extern _X_EXPORT void XkbUpdateActions(
+ DeviceIntPtr /* pXDev */,
+ KeyCode /* first */,
+ CARD8 /* num */,
+ XkbChangesPtr /* pChanges */,
+ unsigned int * /* needChecksRtrn */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT KeySymsPtr XkbGetCoreMap(
+ DeviceIntPtr /* keybd */
+);
+
+extern _X_EXPORT void XkbApplyMappingChange(
+ DeviceIntPtr /* pXDev */,
+ KeySymsPtr /* map */,
+ KeyCode /* firstKey */,
+ CARD8 /* num */,
+ CARD8 * /* modmap */,
+ ClientPtr /* client */
+);
+
+extern _X_EXPORT void XkbSetIndicators(
+ DeviceIntPtr /* pXDev */,
+ CARD32 /* affect */,
+ CARD32 /* values */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbUpdateIndicators(
+ DeviceIntPtr /* keybd */,
+ CARD32 /* changed */,
+ Bool /* check_edevs */,
+ XkbChangesPtr /* pChanges */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT XkbSrvLedInfoPtr XkbAllocSrvLedInfo(
+ DeviceIntPtr /* dev */,
+ KbdFeedbackPtr /* kf */,
+ LedFeedbackPtr /* lf */,
+ unsigned int /* needed_parts */
+);
+
+extern _X_EXPORT XkbSrvLedInfoPtr XkbCopySrvLedInfo(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* src */,
+ KbdFeedbackPtr /* kf */,
+ LedFeedbackPtr /* lf */
+);
+
+
+extern _X_EXPORT XkbSrvLedInfoPtr XkbFindSrvLedInfo(
+ DeviceIntPtr /* dev */,
+ unsigned int /* class */,
+ unsigned int /* id */,
+ unsigned int /* needed_parts */
+);
+
+extern _X_EXPORT void XkbApplyLedNameChanges(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* sli */,
+ unsigned int /* changed_names */,
+ xkbExtensionDeviceNotify * /* ed */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbApplyLedMapChanges(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* sli */,
+ unsigned int /* changed_maps */,
+ xkbExtensionDeviceNotify * /* ed */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbApplyLedStateChanges(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* sli */,
+ unsigned int /* changed_leds */,
+ xkbExtensionDeviceNotify * /* ed */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbFlushLedEvents(
+ DeviceIntPtr /* dev */,
+ DeviceIntPtr /* kbd */,
+ XkbSrvLedInfoPtr /* sli */,
+ xkbExtensionDeviceNotify * /* ed */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT unsigned int XkbIndicatorsToUpdate(
+ DeviceIntPtr /* dev */,
+ unsigned long /* state_changes */,
+ Bool /* enabled_ctrl_changes */
+);
+
+extern _X_EXPORT void XkbComputeDerivedState(
+ XkbSrvInfoPtr /* xkbi */
+);
+
+extern _X_EXPORT void XkbCheckSecondaryEffects(
+ XkbSrvInfoPtr /* xkbi */,
+ unsigned int /* which */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbCheckIndicatorMaps(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* sli */,
+ unsigned int /* which */
+);
+
+extern _X_EXPORT unsigned int XkbStateChangedFlags(
+ XkbStatePtr /* old */,
+ XkbStatePtr /* new */
+);
+
+extern _X_EXPORT void XkbSendStateNotify(
+ DeviceIntPtr /* kbd */,
+ xkbStateNotify * /* pSN */
+);
+
+extern _X_EXPORT void XkbSendMapNotify(
+ DeviceIntPtr /* kbd */,
+ xkbMapNotify * /* ev */
+);
+
+extern _X_EXPORT int XkbComputeControlsNotify(
+ DeviceIntPtr /* kbd */,
+ XkbControlsPtr /* old */,
+ XkbControlsPtr /* new */,
+ xkbControlsNotify * /* pCN */,
+ Bool /* forceCtrlProc */
+);
+
+extern _X_EXPORT void XkbSendControlsNotify(
+ DeviceIntPtr /* kbd */,
+ xkbControlsNotify * /* ev */
+);
+
+extern _X_EXPORT void XkbSendCompatMapNotify(
+ DeviceIntPtr /* kbd */,
+ xkbCompatMapNotify * /* ev */
+);
+
+extern _X_EXPORT void XkbHandleBell(
+ BOOL /* force */,
+ BOOL /* eventOnly */,
+ DeviceIntPtr /* kbd */,
+ CARD8 /* percent */,
+ pointer /* ctrl */,
+ CARD8 /* class */,
+ Atom /* name */,
+ WindowPtr /* pWin */,
+ ClientPtr /* pClient */
+);
+
+extern _X_EXPORT void XkbSendAccessXNotify(
+ DeviceIntPtr /* kbd */,
+ xkbAccessXNotify * /* pEv */
+);
+
+extern _X_EXPORT void XkbSendNamesNotify(
+ DeviceIntPtr /* kbd */,
+ xkbNamesNotify * /* ev */
+);
+
+extern _X_EXPORT void XkbSendActionMessage(
+ DeviceIntPtr /* kbd */,
+ xkbActionMessage * /* ev */
+);
+
+extern _X_EXPORT void XkbSendExtensionDeviceNotify(
+ DeviceIntPtr /* kbd */,
+ ClientPtr /* client */,
+ xkbExtensionDeviceNotify * /* ev */
+);
+
+extern _X_EXPORT void XkbSendNotification(
+ DeviceIntPtr /* kbd */,
+ XkbChangesPtr /* pChanges */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbProcessKeyboardEvent(
+ DeviceEvent* /* event */,
+ DeviceIntPtr /* keybd */
+);
+
+extern _X_EXPORT void XkbHandleActions(
+ DeviceIntPtr /* dev */,
+ DeviceIntPtr /* kbd */,
+ DeviceEvent* /* event */
+);
+
+extern _X_EXPORT Bool XkbEnableDisableControls(
+ XkbSrvInfoPtr /* xkbi */,
+ unsigned long /* change */,
+ unsigned long /* newValues */,
+ XkbChangesPtr /* changes */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void AccessXInit(
+ DeviceIntPtr /* dev */
+);
+
+extern _X_EXPORT Bool AccessXFilterPressEvent(
+ DeviceEvent* /* event */,
+ DeviceIntPtr /* keybd */
+);
+
+extern _X_EXPORT Bool AccessXFilterReleaseEvent(
+ DeviceEvent* /* event */,
+ DeviceIntPtr /* keybd */
+);
+
+extern _X_EXPORT void AccessXCancelRepeatKey(
+ XkbSrvInfoPtr /* xkbi */,
+ KeyCode /* key */
+);
+
+extern _X_EXPORT void AccessXComputeCurveFactor(
+ XkbSrvInfoPtr /* xkbi */,
+ XkbControlsPtr /* ctrls */
+);
+
+extern _X_EXPORT XkbInterestPtr XkbFindClientResource(
+ DevicePtr /* inDev */,
+ ClientPtr /* client */
+);
+
+extern _X_EXPORT XkbInterestPtr XkbAddClientResource(
+ DevicePtr /* inDev */,
+ ClientPtr /* client */,
+ XID /* id */
+);
+
+extern _X_EXPORT int XkbRemoveResourceClient(
+ DevicePtr /* inDev */,
+ XID /* id */
+);
+
+extern _X_EXPORT int XkbDDXAccessXBeep(
+ DeviceIntPtr /* dev */,
+ unsigned int /* what */,
+ unsigned int /* which */
+);
+
+extern _X_EXPORT int XkbDDXUsesSoftRepeat(
+ DeviceIntPtr /* dev */
+);
+
+extern _X_EXPORT void XkbDDXKeybdCtrlProc(
+ DeviceIntPtr /* dev */,
+ KeybdCtrl * /* ctrl */
+);
+
+extern _X_EXPORT void XkbDDXChangeControls(
+ DeviceIntPtr /* dev */,
+ XkbControlsPtr /* old */,
+ XkbControlsPtr /* new */
+);
+
+extern _X_EXPORT void XkbDDXUpdateDeviceIndicators(
+ DeviceIntPtr /* dev */,
+ XkbSrvLedInfoPtr /* sli */,
+ CARD32 /* newState */
+);
+
+extern _X_EXPORT void XkbDDXFakePointerMotion(
+ unsigned int /* flags */,
+ int /* x */,
+ int /* y */
+);
+
+extern _X_EXPORT void XkbDDXFakeDeviceButton(
+ DeviceIntPtr /* dev */,
+ Bool /* press */,
+ int /* button */
+);
+
+extern _X_EXPORT int XkbDDXTerminateServer(
+ DeviceIntPtr /* dev */,
+ KeyCode /* key */,
+ XkbAction * /* act */
+);
+
+extern _X_EXPORT int XkbDDXSwitchScreen(
+ DeviceIntPtr /* dev */,
+ KeyCode /* key */,
+ XkbAction * /* act */
+);
+
+extern _X_EXPORT int XkbDDXPrivate(
+ DeviceIntPtr /* dev */,
+ KeyCode /* key */,
+ XkbAction * /* act */
+);
+
+extern _X_EXPORT void XkbDisableComputedAutoRepeats(
+ DeviceIntPtr /* pXDev */,
+ unsigned int /* key */
+);
+
+extern _X_EXPORT void XkbSetRepeatKeys(
+ DeviceIntPtr /* pXDev */,
+ int /* key */,
+ int /* onoff */
+);
+
+extern _X_EXPORT int XkbLatchModifiers(
+ DeviceIntPtr /* pXDev */,
+ CARD8 /* mask */,
+ CARD8 /* latches */
+);
+
+extern _X_EXPORT int XkbLatchGroup(
+ DeviceIntPtr /* pXDev */,
+ int /* group */
+);
+
+extern _X_EXPORT void XkbClearAllLatchesAndLocks(
+ DeviceIntPtr /* dev */,
+ XkbSrvInfoPtr /* xkbi */,
+ Bool /* genEv */,
+ XkbEventCausePtr /* cause */
+);
+
+extern _X_EXPORT void XkbGetRulesDflts(
+ XkbRMLVOSet * /* rmlvo */
+);
+
+extern _X_EXPORT void XkbFreeRMLVOSet(
+ XkbRMLVOSet * /* rmlvo */,
+ Bool /* freeRMLVO */
+);
+
+extern _X_EXPORT void XkbSetRulesDflts(
+ XkbRMLVOSet * /* rmlvo */
+);
+
+extern _X_EXPORT void XkbDeleteRulesDflts(
+ void
+);
+
+extern _X_EXPORT int SProcXkbDispatch(
+ ClientPtr /* client */
+);
+
+extern _X_EXPORT XkbGeometryPtr XkbLookupNamedGeometry(
+ DeviceIntPtr /* dev */,
+ Atom /* name */,
+ Bool * /* shouldFree */
+);
+
+extern _X_EXPORT char * _XkbDupString(
+ const char * /* str */
+);
+
+extern _X_EXPORT void XkbConvertCase(
+ KeySym /* sym */,
+ KeySym * /* lower */,
+ KeySym * /* upper */
+);
+
+extern _X_EXPORT Status XkbChangeKeycodeRange(
+ XkbDescPtr /* xkb */,
+ int /* minKC */,
+ int /* maxKC */,
+ XkbChangesPtr /* changes */
+);
+
+extern _X_EXPORT void XkbFreeSrvLedInfo(
+ XkbSrvLedInfoPtr /* sli */
+);
+
+extern _X_EXPORT void XkbFreeInfo(
+ XkbSrvInfoPtr /* xkbi */
+);
+
+extern _X_EXPORT Status XkbChangeTypesOfKey(
+ XkbDescPtr /* xkb */,
+ int /* key */,
+ int /* nGroups */,
+ unsigned int /* groups */,
+ int * /* newTypesIn */,
+ XkbMapChangesPtr /* changes */
+);
+
+extern _X_EXPORT int XkbKeyTypesForCoreSymbols(
+ XkbDescPtr /* xkb */,
+ int /* map_width */,
+ KeySym * /* core_syms */,
+ unsigned int /* protected */,
+ int * /* types_inout */,
+ KeySym * /* xkb_syms_rtrn */
+);
+
+extern _X_EXPORT Bool XkbApplyCompatMapToKey(
+ XkbDescPtr /* xkb */,
+ KeyCode /* key */,
+ XkbChangesPtr /* changes */
+);
+
+extern _X_EXPORT Bool XkbApplyVirtualModChanges(
+ XkbDescPtr /* xkb */,
+ unsigned int /* changed */,
+ XkbChangesPtr /* changes */
+);
+
+extern _X_EXPORT void XkbSendNewKeyboardNotify(
+ DeviceIntPtr /* kbd */,
+ xkbNewKeyboardNotify * /* pNKN */
+);
+
+extern Bool XkbCopyKeymap(
+ XkbDescPtr /* dst */,
+ XkbDescPtr /* src */);
+
+extern Bool XkbCopyDeviceKeymap(
+ DeviceIntPtr /* dst */,
+ DeviceIntPtr /* src */);
+
+extern void XkbFilterEvents(
+ ClientPtr /* pClient */,
+ int /* nEvents */,
+ xEvent* /* xE */);
+
+extern int XkbGetEffectiveGroup(
+ XkbSrvInfoPtr /* xkbi */,
+ XkbStatePtr /* xkbstate */,
+ CARD8 /* keycode */);
+
+#include "xkbfile.h"
+#include "xkbrules.h"
+
+#define _XkbListKeycodes 0
+#define _XkbListTypes 1
+#define _XkbListCompat 2
+#define _XkbListSymbols 3
+#define _XkbListGeometry 4
+#define _XkbListNumComponents 5
+
+typedef struct _XkbSrvListInfo {
+ int szPool;
+ int nPool;
+ char * pool;
+
+ int maxRtrn;
+ int nTotal;
+
+ char * pattern[_XkbListNumComponents];
+ int nFound[_XkbListNumComponents];
+} XkbSrvListInfoRec,*XkbSrvListInfoPtr;
+
+extern _X_EXPORT Status XkbDDXList(
+ DeviceIntPtr /* dev */,
+ XkbSrvListInfoPtr /* listing */,
+ ClientPtr /* client */
+);
+
+extern _X_EXPORT unsigned int XkbDDXLoadKeymapByNames(
+ DeviceIntPtr /* keybd */,
+ XkbComponentNamesPtr /* names */,
+ unsigned int /* want */,
+ unsigned int /* need */,
+ XkbDescPtr * /* finfoRtrn */,
+ char * /* keymapNameRtrn */,
+ int /* keymapNameRtrnLen */
+);
+
+extern _X_EXPORT Bool XkbDDXNamesFromRules(
+ DeviceIntPtr /* keybd */,
+ char * /* rules */,
+ XkbRF_VarDefsPtr /* defs */,
+ XkbComponentNamesPtr /* names */
+);
+
+extern _X_EXPORT XkbDescPtr XkbCompileKeymap(
+ DeviceIntPtr /* dev */,
+ XkbRMLVOSet * /* rmlvo */
+);
+
+#define XkbAtomGetString(s) NameForAtom(s)
+
+#endif /* _XKBSRV_H_ */
diff --git a/xorg-server/installer/genruntimeinclude.py b/xorg-server/installer/genruntimeinclude.py new file mode 100644 index 000000000..ffc1c8d9f --- /dev/null +++ b/xorg-server/installer/genruntimeinclude.py @@ -0,0 +1,51 @@ +PublicToken="1fc8b3b9a1e18e3b"
+
+Template=r"""!define MSVC_PUBLICTOKEN "<PUBLICTOKEN>"
+!define MSVC_VERSION "<VERSION>"
+!define MSVCR90_DLL "<WINSXSDIR>\x86_Microsoft.VC90.CRT_${MSVC_PUBLICTOKEN}_9.0.${MSVC_VERSION}_<SUFFIX>\msvcr90.dll"
+!define MSVCM90_DLL "<WINSXSDIR>\x86_Microsoft.VC90.CRT_${MSVC_PUBLICTOKEN}_9.0.${MSVC_VERSION}_<SUFFIX>\msvcm90.dll"
+!define MSVCP90_DLL "<WINSXSDIR>\x86_Microsoft.VC90.CRT_${MSVC_PUBLICTOKEN}_9.0.${MSVC_VERSION}_<SUFFIX>\msvcp90.dll"
+!define MSVC_CAT "<WINSXSDIR>\manifests\x86_Microsoft.VC90.CRT_${MSVC_PUBLICTOKEN}_9.0.${MSVC_VERSION}_<SUFFIX>.cat"
+!define MSVC_MANIFEST_PART "x86_Microsoft.VC90.CRT_${MSVC_PUBLICTOKEN}_9.0.${MSVC_VERSION}_<SUFFIX>.manifest"
+!define MSVC_MANIFEST "<WINSXSDIR>\manifests\${MSVC_MANIFEST_PART}"
+"""
+
+import glob,re,sys,os
+
+Files=glob.glob(r"c:\windows\winsxs\x86_Microsoft.VC90.CRT_%s_9.0.*"%PublicToken)
+
+SearchRe=re.compile(r"c:\\windows\\winsxs\\x86_Microsoft\.VC90\.CRT_%s_9\.0\.([0-9]+)\.([0-9]+)_(.*)"%PublicToken,re.I)
+
+MajorVersion=0
+MinorVersion=0
+LatestFile=None
+#Now Select the one with the latest version
+for File in Files:
+ # Extract version
+ Search=SearchRe.search(File)
+ Major=int(Search.group(1))
+ Minor=int(Search.group(2))
+ if Major>MajorVersion:
+ MajorVersion=Major
+ MinorVersion=Minor
+ LatestFile=File
+ Suffix=Search.group(3)
+ elif Major==MajorVersion and Minor>MinorVersion:
+ MinorVersion=Minor
+ LatestFile=File
+ Suffix=Search.group(3)
+
+
+Template=re.sub("<VERSION>","%d.%d"%(MajorVersion,MinorVersion),Template)
+Template=re.sub("<PUBLICTOKEN>",PublicToken,Template)
+Template=re.sub("<SUFFIX>",Suffix,Template)
+
+WinSxsDir=os.path.join(os.getenv("systemroot"),"WinSxS")
+Template=re.sub("<WINSXSDIR>",WinSxsDir,Template)
+
+if len(sys.argv)==3 and sys.argv[2]=="1":
+ Template=re.sub("<DEBUG>","Debug",Template)
+else:
+ Template=re.sub("<DEBUG>","",Template)
+
+open("runtime","w").write(Template)
diff --git a/xorg-server/installer/packageall.bat b/xorg-server/installer/packageall.bat new file mode 100644 index 000000000..b68ffdfa1 --- /dev/null +++ b/xorg-server/installer/packageall.bat @@ -0,0 +1,3 @@ +if exist vcxsrv.*.installer.exe del vcxsrv.*.installer.exe
+python genruntimeinclude.py
+"C:\Program Files\NSIS\makensis.exe" vcxsrv.nsi
\ No newline at end of file diff --git a/xorg-server/installer/vcxsrv.nsi b/xorg-server/installer/vcxsrv.nsi new file mode 100644 index 000000000..e96408101 --- /dev/null +++ b/xorg-server/installer/vcxsrv.nsi @@ -0,0 +1,197 @@ +; example2.nsi
+;
+; This script is based on example1.nsi, but it remember the directory,
+; has uninstall support and (optionally) installs start menu shortcuts.
+;
+; It will install example2.nsi into a directory that the user selects,
+
+;--------------------------------
+
+; The name of the installer
+Name "VcXsrv"
+
+; The file to write
+OutFile "vcxsrv.1.1.1.installer.exe"
+
+; The default installation directory
+InstallDir $PROGRAMFILES\VcXsrv
+
+; Registry key to check for directory (so if you install again, it will
+; overwrite the old one automatically)
+InstallDirRegKey HKLM "Software\VcXsrv" "Install_Dir"
+
+; Request application privileges for Windows Vista
+RequestExecutionLevel admin
+
+;--------------------------------
+InstType "Full"
+InstType "Minimal"
+
+; Pages
+
+Page components
+Page directory
+Page instfiles
+
+UninstPage uninstConfirm
+UninstPage instfiles
+
+SetPluginUnload alwaysoff
+; ShowInstDetails show
+XPStyle on
+
+!define FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID {8cedc215-ac4b-488b-93c0-a50a49cb2fb8}
+
+!include runtime
+
+;--------------------------------
+
+; The stuff to install
+Section "VcXsrv (required)"
+
+ SectionIn RO
+ SectionIn 1 2
+
+ ; Set output path to the installation directory.
+ SetOutPath $INSTDIR
+
+ ; Put files there
+ File "..\obj\servrelease\vcxsrv.exe"
+ File "..\obj\servdebug\vcxsrv_dbg.exe"
+ File "..\obj\servdebug\vcxsrv_dbg.pdb"
+ File "..\protocol.txt"
+ File "..\system.XWinrc"
+ File "..\..\xkbcomp\obj\release\xkbcomp.exe"
+ File "..\xkeysymdb"
+ File "..\hw\xwin\xlaunch\obj\release\xlaunch.exe"
+ File "..\..\tools\plink\obj\release\plink.exe"
+ SetOutPath $INSTDIR\fonts
+ File /r "..\fonts\*.*"
+ SetOutPath $INSTDIR\xkbdata
+ File /r "..\xkbdata\*.*"
+ SetOutPath $INSTDIR\locale
+ File /r "..\locale\*.*"
+
+ ; Write the installation path into the registry
+ WriteRegStr HKLM SOFTWARE\VcXsrv "Install_Dir" "$INSTDIR"
+
+ ; Write the uninstall keys for Windows
+ WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\VcXsrv" "DisplayName" "VcXsrv"
+ WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\VcXsrv" "UninstallString" '"$INSTDIR\uninstall.exe"'
+ WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\VcXsrv" "NoModify" 1
+ WriteRegDWORD HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\VcXsrv" "NoRepair" 1
+ WriteUninstaller "uninstall.exe"
+
+ InitPluginsDir
+ SetOutPath $PLUGINSDIR
+ File "${MSVCR90_DLL}"
+ File "${MSVCM90_DLL}"
+ File "${MSVCP90_DLL}"
+ File "${MSVC_CAT}"
+ File "${MSVC_MANIFEST}"
+ DetailPrint "Installing CRT assembly..."
+ System::Call "sxs::CreateAssemblyCache(*i .r0, i 0) i.r1"
+ StrCmp $1 0 0 fail
+ # Fill a FUSION_INSTALL_REFERENCE.
+ # fir.cbSize = sizeof(FUSION_INSTALL_REFERENCE) == 32
+ # fir.dwFlags = 0
+ # fir.guidScheme = FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID
+ # fir.szIdentifier = "nsissxs"
+ # fir.szNonCanonicalData = 0
+ System::Call "*(i 32, i 0, i 2364391957, i 1217113163, i 178634899, i 3090139977, w 'nsissxs', w '') i.s"
+ Pop $2
+ # IAssemblyCache::InstallAssembly(0, manifestPath, fir)
+ System::Call "$0->7(i 0, w '$PLUGINSDIR\${MSVC_MANIFEST_PART}', i r2) i.r1"
+ System::Free $2
+ StrCmp $1 0 0 fail2
+ System::Call "$0->2()"
+ Goto end
+
+fail:
+ DetailPrint "CreateAssemblyCache failed."
+ DetailPrint $1
+ Goto end
+
+fail2:
+ DetailPrint "InstallAssembly failed."
+ DetailPrint $1
+ Goto end
+end:
+SectionEnd
+
+; Optional section (can be disabled by the user)
+Section "Start Menu Shortcuts"
+ SectionIn 1
+
+ SetOutPath $INSTDIR
+ CreateDirectory "$SMPROGRAMS\VcXsrv"
+ CreateShortCut "$SMPROGRAMS\VcXsrv\Uninstall VcXsrv.lnk" "$INSTDIR\uninstall.exe" "" "$INSTDIR\uninstall.exe" 0
+ CreateShortCut "$SMPROGRAMS\VcXsrv\VcXsrv.lnk" "$INSTDIR\vcxsrv.exe" " :1 -ac -terminate -lesspointer -multiwindow -clipboard +kb" "$INSTDIR\vcxsrv.exe" 0
+ CreateShortCut "$SMPROGRAMS\VcXsrv\XLaunch.lnk" "$INSTDIR\xlaunch.exe" "" "$INSTDIR\xlaunch.exe" 0
+
+SectionEnd
+
+; Optional section (can be disabled by the user)
+Section "Desktop Shortcuts"
+ SectionIn 1
+
+ SetOutPath $INSTDIR
+ CreateShortCut "$DESKTOP\VcXsrv.lnk" "$INSTDIR\vcxsrv.exe" " :1 -ac -terminate -lesspointer -multiwindow -clipboard +kb" "$INSTDIR\vcxsrv.exe" 0
+ CreateShortCut "$DESKTOP\XLaunch.lnk" "$INSTDIR\xlaunch.exe" "" "$INSTDIR\xlaunch.exe" 0
+
+SectionEnd
+
+;--------------------------------
+
+; Uninstaller
+
+Section "Uninstall"
+
+ ; Remove registry keys
+ DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\VcXsrv"
+ DeleteRegKey HKLM SOFTWARE\VcXsrv
+
+ ; Remove files and uninstaller
+ Delete "$INSTDIR\vcxsrv.exe"
+ Delete "$INSTDIR\uninstall.exe"
+ Delete "$INSTDIR\protocol.txt"
+ Delete "$INSTDIR\system.XWinrc"
+ Delete "$INSTDIR\xkbcomp.exe"
+ Delete "$INSTDIR\xkeysymdb"
+ Delete "$INSTDIR\xlaunch.exe"
+
+ RMDir /r "$INSTDIR\fonts"
+ RMDir /r "$INSTDIR\xkbdata"
+ RMDir /r "$INSTDIR\locale"
+
+ ; Remove shortcuts, if any
+ Delete "$SMPROGRAMS\VcXsrv\*.*"
+ Delete "$DESKTOP\VcXsrv.lnk"
+ Delete "$DESKTOP\XLaunch.lnk"
+
+ ; Remove directories used
+ RMDir "$SMPROGRAMS\VcXsrv"
+ RMDir "$INSTDIR"
+
+ DetailPrint "Removing CRT assembly..."
+ System::Call "sxs::CreateAssemblyCache(*i .r0, i 0) i.r1"
+ StrCmp $1 0 0 fail
+ System::Call "*(i 32, i 0, i 2364391957, i 1217113163, i 178634899, i 3090139977, w 'nsissxs', w '') i.s"
+ Pop $2
+ System::Call "$0->3(i 0, w 'Microsoft.VC90.CRT,version=$\"9.0.${MSVC_VERSION}$\",type=$\"win32$\",processorArchitecture=$\"x86$\",publicKeyToken=$\"${MSVC_PUBLICTOKEN}$\"', i r2, *i . r3) i.r1"
+ StrCmp $1 0 0 fail2
+ DetailPrint "Disposition returned is $3"
+ System::Call "$0->2()"
+ Goto end
+ fail:
+ DetailPrint "CreateAssemblyCache failed."
+ DetailPrint $1
+ Goto end
+ fail2:
+ DetailPrint "UninstallAssembly failed."
+ DetailPrint $1
+ Goto end
+end:
+
+SectionEnd
+
diff --git a/xorg-server/locale/compose.dir b/xorg-server/locale/compose.dir new file mode 100644 index 000000000..22391882f --- /dev/null +++ b/xorg-server/locale/compose.dir @@ -0,0 +1,9 @@ +# $Xorg: compose.dir,v 1.3 2000/08/17 19:46:48 cpqbld Exp $ +# +# This file contains compose table file name. +# The first word is the compose table file name and +# the second word is full locale name. +# +# $XFree86: xc/nls/compose.dir,v 1.24 2003/08/06 14:04:00 eich Exp $ +# +iso8859-1/Compose: C diff --git a/xorg-server/locale/locale.alias b/xorg-server/locale/locale.alias new file mode 100644 index 000000000..da9751406 --- /dev/null +++ b/xorg-server/locale/locale.alias @@ -0,0 +1,16 @@ +# $XdotOrg: lib/X11/nls/locale.alias.pre,v 1.12 2005-09-30 07:52:46 daniels Exp $ +# $Xorg: locale.alias,v 1.3 2000/08/17 19:46:48 cpqbld Exp $ +# +# This file contains alias name of locale. +# Each alias name is described within one line. +# The first word is the alias name (simplified locale name) +# the second word is full locale name. +# +# $XFree86: xc/nls/locale.alias,v 1.65 2004/01/03 03:31:00 dawes Exp $ +# + +POSIX: C +POSIX-UTF2: C +C_C.C: C +C.en: C +English_United-States.437: C diff --git a/xorg-server/locale/locale.dir b/xorg-server/locale/locale.dir new file mode 100644 index 000000000..116fdf818 --- /dev/null +++ b/xorg-server/locale/locale.dir @@ -0,0 +1,11 @@ +# $XdotOrg: lib/X11/nls/locale.dir.pre,v 1.10 2005-09-30 07:52:46 daniels Exp $ +# $Xorg: locale.dir,v 1.3 2000/08/17 19:46:48 cpqbld Exp $ +# +# This file contains locale database file names +# The first word is the locale database file name and +# the second word is the full locale name. +# +# $XFree86: xc/nls/locale.dir,v 1.44 2003/12/18 04:14:22 dawes Exp $ +# + +C/XLC_LOCALE: C diff --git a/xorg-server/makefile b/xorg-server/makefile new file mode 100644 index 000000000..519a5be53 --- /dev/null +++ b/xorg-server/makefile @@ -0,0 +1,113 @@ +ifneq ($(MAKESERVER),1) +$(error Please specify MAKESERVER=1 on the command line or as environment variable) +endif + +INCLUDELIBFILES = \ + composite\$(OBJDIR)\libcomposite.lib \ + config\$(OBJDIR)\libconfig.lib \ + damageext\$(OBJDIR)\libdamageext.lib \ + dbe\$(OBJDIR)\libdbe.lib \ + dix\$(OBJDIR)\libdix.lib \ + exa\$(OBJDIR)\libexa.lib \ + fb\$(OBJDIR)\libfb.lib \ + glx\$(OBJDIR)\libglx.lib \ + hw\kdrive\ephyr\$(OBJDIR)\libxephyr.lib \ + hw\kdrive\src\$(OBJDIR)\libkdrive.lib \ + hw\xwin\$(OBJDIR)\libxwin.lib \ + mi\$(OBJDIR)\libmi.lib \ + miext\damage\$(OBJDIR)\libdamage.lib \ + miext\shadow\$(OBJDIR)\libshadow.lib \ + os\$(OBJDIR)\libos.lib \ + randr\$(OBJDIR)\librandr.lib \ + record\$(OBJDIR)\librecord.lib \ + Xext\$(OBJDIR)\libxext.lib \ + xfixes\$(OBJDIR)\libxfixes.lib \ + Xi\$(OBJDIR)\libxi.lib \ + xkb\$(OBJDIR)\libxkb.lib \ + render\$(OBJDIR)\librender.lib \ + $(MHMAKECONF)\libxau\$(OBJDIR)\libxau.lib \ + $(MHMAKECONF)\libxdmcp\$(OBJDIR)\libxdmcp.lib \ + $(MHMAKECONF)\libXfont\src\util\$(OBJDIR)\libutil.lib \ + $(MHMAKECONF)\libXfont\src\fc\$(OBJDIR)\libfc.lib \ + $(MHMAKECONF)\libXfont\src\fontfile\$(OBJDIR)\libfontfile.lib \ + $(MHMAKECONF)\libXfont\src\builtins\$(OBJDIR)\libbuiltins.lib \ + $(MHMAKECONF)\libXfont\src\bitmap\$(OBJDIR)\libbitmap.lib \ + $(MHMAKECONF)\pixman\pixman\$(OBJDIR)\libpixman-1.lib \ + $(MHMAKECONF)\libx11\modules\im\ximcp\$(OBJDIR)\libximcp.lib \ + $(MHMAKECONF)\libx11\src\xlibi18n\$(OBJDIR)\libi18n.lib \ + $(MHMAKECONF)\libx11\src\$(OBJDIR)\libx11.lib \ + $(MHMAKECONF)\libx11\src\xcms\$(OBJDIR)\libxcms.lib \ + $(MHMAKECONF)\libxcb\src\$(OBJDIR)\libxcb.lib \ + $(MHMAKECONF)\libx11\src\xkb\$(OBJDIR)\libxkb.lib \ + $(MHMAKECONF)\libx11\modules\om\generic\$(OBJDIR)\libxomGeneric.lib \ + $(MHMAKECONF)\libx11\modules\lc\utf8\$(OBJDIR)\libxlcUTF8Load.lib \ + $(MHMAKECONF)\libx11\modules\lc\def\$(OBJDIR)\libxlcDef.lib \ + $(MHMAKECONF)\libx11\modules\lc\gen\$(OBJDIR)\liblcGenConvLoad.lib \ + $(MHMAKECONF)\zlib\$(OBJDIR)\libz.lib \ + $(MHMAKECONF)\libx11\modules\lc\xlocale\$(OBJDIR)\libxlocale.lib \ + $(MHMAKECONF)\libfontenc\src\$(OBJDIR)\libfontenc.lib \ + $(MHMAKECONF)\libxfont\src\freetype\$(OBJDIR)\libft.lib \ + $(MHMAKECONF)\libxfont\src\stubs\$(OBJDIR)\libstubs.lib \ + $(MHMAKECONF)\libxinerama\src\$(OBJDIR)\libxinerama.lib + +LIBDIRS=$(dir $(INCLUDELIBFILES)) + +load_makefile $(LIBDIRS:%$(OBJDIR)\=%makefile MAKESERVER=$(MAKESERVER) DEBUG=$(DEBUG);) + +OBJS = dix\$(OBJDIR)\main.obj + +ifeq ($(DEBUG),1) +TTYAPP=vcxsrv_dbg + +LINKLIBS += $(MHMAKECONF)\openssl\out32_d\libeay32.lib \ + $(MHMAKECONF)\freetype\lib\freetype200b8MT_D.lib \ + $(MHMAKECONF)\pthreads\pthreadVC2d.lib +else +TTYAPP=vcxsrv + +LINKLIBS += $(MHMAKECONF)\openssl\out32\libeay32.lib \ + $(MHMAKECONF)\freetype\lib\freetype200b8MT.lib \ + $(MHMAKECONF)\pthreads\pthreadVC2.lib +endif + +RCINCLUDES += hw\xwin $(MHMAKECONF)\include $(MHMAKECONF) + +XWin.rc: hw\xwin\XWin.rc + copy $< $@ + +RESOURCES = XWin.rc + +$(OBJDIR)\$(TTYAPP).exe: $(LINKLIBS) + +XKeysymDB: ..\libX11\src\XKeysymDB + copy $< $@ + +$(TTYAPP).exe: $(OBJDIR)\$(TTYAPP).exe + copy $< $@ + +load_makefile hw\xwin\xlaunch\makefile MAKESERVER=0 DEBUG=0 + +xlaunch.exe: hw\xwin\xlaunch\obj\release\xlaunch.exe + copy $< $@ + +load_makefile ..\xkbcomp\makefile MAKESERVER=0 DEBUG=0 + +xkbcomp.exe: ..\xkbcomp\obj\release\xkbcomp.exe + copy $< $@ + +load_makefile ..\tools\plink\makefile MAKESERVER=0 DEBUG=0 + +plink.exe: ..\tools\plink\obj\release\plink.exe + copy $< $@ + +load_makefile ..\libX11\nls\makefile MAKESERVER=0 DEBUG=0 +load_makefile fonts.src\makefile MAKESERVER=0 DEBUG=0 +load_makefile xkbdata.src\makefile MAKESERVER=0 DEBUG=0 + +all: $(TTYAPP).exe xlaunch.exe xkbcomp.exe protocol.txt XKeysymDB ..\libX11\nls\all fonts.src\all xkbdata.src\all \ + plink.exe + +protocol.txt: dix\protocol.txt + copy $< $@ + + diff --git a/xorg-server/mi/makefile b/xorg-server/mi/makefile new file mode 100644 index 000000000..bff870d6e --- /dev/null +++ b/xorg-server/mi/makefile @@ -0,0 +1,42 @@ +CSRCS=miarc.c \ + mibank.c \ + mibitblt.c \ + mibstore.c \ + micmap.c \ + micopy.c \ + micursor.c \ + midash.c \ + midispcur.c \ + mieq.c \ + miexpose.c \ + mifillarc.c \ + mifillrct.c \ + mifpolycon.c \ + migc.c \ + miglblt.c \ + mioverlay.c \ + mipointer.c \ + mipoly.c \ + mipolycon.c \ + mipolygen.c \ + mipolypnt.c \ + mipolyrect.c \ + mipolyseg.c \ + mipolytext.c \ + mipolyutil.c \ + mipushpxl.c \ + miregion.c \ + miscrinit.c \ + mispans.c \ + misprite.c \ + mivaltree.c \ + miwideline.c \ + miwindow.c \ + mizerarc.c \ + mizerclip.c \ + mizerline.c \ + miinitext.c + +LIBRARY=libmi + + diff --git a/xorg-server/mi/micoord.h b/xorg-server/mi/micoord.h index e6d814fc8..fe4adac56 100644 --- a/xorg-server/mi/micoord.h +++ b/xorg-server/mi/micoord.h @@ -55,14 +55,14 @@ #endif #if IMAGE_BYTE_ORDER == MSBFirst -#define intToCoord(i,x,y) (((x) = GetHighWord(i)), ((y) = (int) ((short) (i)))) +#define intToCoord(i,x,y) (((x) = GetHighWord(i)), ((y) = (int) ((short) ((i)&0xffff)))) #define coordToInt(x,y) (((x) << 16) | ((y) & 0xffff)) #define intToX(i) (GetHighWord(i)) -#define intToY(i) ((int) ((short) i)) +#define intToY(i) ((int) ((short) ((i)&0xffff))) #else -#define intToCoord(i,x,y) (((x) = (int) ((short) (i))), ((y) = GetHighWord(i))) +#define intToCoord(i,x,y) (((x) = (int) ((short) ((i)&0xffff))), ((y) = GetHighWord(i))) #define coordToInt(x,y) (((y) << 16) | ((x) & 0xffff)) -#define intToX(i) ((int) ((short) (i))) +#define intToX(i) ((int) ((short) ((i)&0xffff))) #define intToY(i) (GetHighWord(i)) #endif diff --git a/xorg-server/mi/mioverlay.c b/xorg-server/mi/mioverlay.c index e0aa88017..0577e8c9f 100644 --- a/xorg-server/mi/mioverlay.c +++ b/xorg-server/mi/mioverlay.c @@ -3,6 +3,10 @@ #include <dix-config.h> #endif +#ifdef CreateWindow +#undef CreateWindow +#endif + #include <X11/X.h> #include "scrnintstr.h" #include "validate.h" diff --git a/xorg-server/mi/misprite.c b/xorg-server/mi/misprite.c index 2ec67827e..714c42944 100644 --- a/xorg-server/mi/misprite.c +++ b/xorg-server/mi/misprite.c @@ -502,7 +502,7 @@ miSpriteSourceValidate (DrawablePtr pDrawable, int x, int y, int width, if (DevHasCursor(pDev)) { pCursorInfo = MISPRITE(pDev); - if (pCursorInfo->isUp && pCursorInfo->pScreen == pScreen && + if (pCursorInfo && pCursorInfo->isUp && pCursorInfo->pScreen == pScreen && ORG_OVERLAP(&pCursorInfo->saved, pDrawable->x, pDrawable->y, x, y, width, height)) { @@ -539,7 +539,7 @@ miSpriteCopyWindow (WindowPtr pWindow, DDXPointRec ptOldOrg, RegionPtr prgnSrc) /* * Damage will take care of destination check */ - if (pCursorInfo->isUp && pCursorInfo->pScreen == pScreen && + if (pCursorInfo && pCursorInfo->isUp && pCursorInfo->pScreen == pScreen && miRectIn(prgnSrc, &pCursorInfo->saved) != rgnOUT) { SPRITE_DEBUG (("CopyWindow remove\n")); @@ -622,9 +622,12 @@ miSpriteInstallColormap (ColormapPtr pMap) if (DevHasCursor(pDev)) { pCursorInfo = MISPRITE(pDev); - pCursorInfo->checkPixels = TRUE; - if (pCursorInfo->isUp && pCursorInfo->pScreen == pScreen) - miSpriteRemoveCursor(pDev, pScreen); + if (pCursorInfo) + { + pCursorInfo->checkPixels = TRUE; + if (pCursorInfo->isUp && pCursorInfo->pScreen == pScreen) + miSpriteRemoveCursor(pDev, pScreen); + } } } diff --git a/xorg-server/miext/damage/damage.c b/xorg-server/miext/damage/damage.c index b7ec92a5b..c2317178e 100644 --- a/xorg-server/miext/damage/damage.c +++ b/xorg-server/miext/damage/damage.c @@ -2140,7 +2140,7 @@ DamageRegionRendered (DrawablePtr pDrawable, DamagePtr pDamage, RegionPtr pOldDa /* This call is very odd, i'm leaving it intact for API sake, but please don't use it. */ void DamageDamageRegion (DrawablePtr pDrawable, - RegionPtr pRegion) + const RegionPtr pRegion) { damageRegionAppend (pDrawable, pRegion, FALSE, -1); diff --git a/xorg-server/miext/damage/makefile b/xorg-server/miext/damage/makefile new file mode 100644 index 000000000..e58f4a883 --- /dev/null +++ b/xorg-server/miext/damage/makefile @@ -0,0 +1,7 @@ +LIBRARY = libdamage + +#INCLUDES = -I$(srcdir)/../cw -I$(top_srcdir)/hw/xfree86/os-support + +CSRCS =damage.c + + diff --git a/xorg-server/miext/shadow/makefile b/xorg-server/miext/shadow/makefile new file mode 100644 index 000000000..0a84b506c --- /dev/null +++ b/xorg-server/miext/shadow/makefile @@ -0,0 +1,25 @@ +LIBRARY = libshadow + +#INCLUDES = -I$(top_srcdir)/hw/xfree86/os-support + +CSRCS = shadow.c \ + shalloc.c \ + shpacked.c \ + shplanar8.c \ + shplanar.c \ + shrot16pack_180.c \ + shrot16pack_270.c \ + shrot16pack_270YX.c \ + shrot16pack_90.c \ + shrot16pack_90YX.c \ + shrot16pack.c \ + shrot32pack_180.c \ + shrot32pack_270.c \ + shrot32pack_90.c \ + shrot32pack.c \ + shrot8pack_180.c \ + shrot8pack_270.c \ + shrot8pack_90.c \ + shrot8pack.c \ + shrotate.c + diff --git a/xorg-server/os/WaitFor.c b/xorg-server/os/WaitFor.c index dfe85e515..7199680cd 100644 --- a/xorg-server/os/WaitFor.c +++ b/xorg-server/os/WaitFor.c @@ -209,6 +209,12 @@ WaitForSomething(int *pClientsReady) wt = &waittime; } } + if (!wt) + { + wt = &waittime; + waittime.tv_sec = 0; + waittime.tv_usec = 100; + } XFD_COPYSET(&AllSockets, &LastSelectMask); } SmartScheduleStopTimer (); diff --git a/xorg-server/os/connection.c b/xorg-server/os/connection.c index 3ff93bbb6..1bbc8807d 100644 --- a/xorg-server/os/connection.c +++ b/xorg-server/os/connection.c @@ -111,6 +111,10 @@ SOFTWARE. #include "dixstruct.h" #include "xace.h" +#ifdef _MSC_VER +typedef int pid_t; +#endif + #define Pid_t pid_t #ifdef DNETCONN @@ -1033,6 +1037,10 @@ CloseDownConnection(ClientPtr client) { OsCommPtr oc = (OsCommPtr)client->osPrivate; +#ifdef DEBUG + ErrorF("CloseDownConnection: client index = %d, socket fd = %d\n", + client->index, oc->fd); +#endif if (oc->output && oc->output->count) FlushClient(client, oc, (char *)NULL, 0); #ifdef XDMCP diff --git a/xorg-server/os/io.c b/xorg-server/os/io.c index 64b64ae75..beccdf5b1 100644 --- a/xorg-server/os/io.c +++ b/xorg-server/os/io.c @@ -913,6 +913,7 @@ FlushClient(ClientPtr who, OsCommPtr oc, const void *__extraBuf, int extraCount) /* If we've arrived here, then the client is stuffed to the gills and not ready to accept more. Make a note of it and buffer the rest. */ + errno=0; FD_SET(connection, &ClientsWriteBlocked); AnyClientsWriteBlocked = TRUE; diff --git a/xorg-server/os/log.c b/xorg-server/os/log.c index 8108890b6..75b3375c0 100644 --- a/xorg-server/os/log.c +++ b/xorg-server/os/log.c @@ -95,8 +95,14 @@ OR PERFORMANCE OF THIS SOFTWARE. #ifdef WIN32 #include <process.h> +#ifndef _MSC_VER #define getpid(x) _getpid(x) #endif +#endif + +#ifdef _MSC_VER +#define S_ISREG(m) (((m)&_S_IFMT) == _S_IFREG) +#endif #ifdef XF86BIGFONT #define _XF86BIGFONT_SERVER_ diff --git a/xorg-server/os/makefile b/xorg-server/os/makefile new file mode 100644 index 000000000..cf9eaf53f --- /dev/null +++ b/xorg-server/os/makefile @@ -0,0 +1,4 @@ +CSRCS=access.c auth.c backtrace.c connection.c io.c log.c mitauth.c os.c oscolor.c osinit.c rpcauth.c strlcat.c strlcpy.c utils.c WaitFor.c xdmauth.c xdmcp.c xprintf.c xstrans.c
+
+LIBRARY=libos
+
diff --git a/xorg-server/os/oscolor.c b/xorg-server/os/oscolor.c index 7f6b93880..4e1513f53 100644 --- a/xorg-server/os/oscolor.c +++ b/xorg-server/os/oscolor.c @@ -49,6 +49,10 @@ SOFTWARE. #include <dix-config.h> #endif +#ifdef _MSC_VER +#define strncasecmp _strnicmp +#endif + #include <X11/keysym.h> #include "os.h" diff --git a/xorg-server/os/osinit.c b/xorg-server/os/osinit.c index e8fcd4540..23a45e5b7 100644 --- a/xorg-server/os/osinit.c +++ b/xorg-server/os/osinit.c @@ -166,6 +166,7 @@ OsInit(void) char fname[PATH_MAX]; if (!been_here) { +#ifndef _MSC_VER struct sigaction act, oact; int i; int siglist[] = { SIGSEGV, SIGQUIT, SIGILL, SIGFPE, SIGBUS, @@ -215,7 +216,7 @@ OsInit(void) int failure_signal = SIGQUIT; dlinfo(RTLD_SELF, RTLD_DI_SETSIGNAL, &failure_signal); #endif - +#endif #if !defined(__SCO__) && !defined(__CYGWIN__) && !defined(__UNIXWARE__) fclose(stdin); fclose(stdout); @@ -254,8 +255,10 @@ OsInit(void) #endif } +#ifndef _MSC_VER if (getpgrp () == 0) setpgid (0, 0); +#endif #ifdef RLIMIT_DATA if (limitDataSpace >= 0) diff --git a/xorg-server/os/utils.c b/xorg-server/os/utils.c index 3718b170c..79cca1a3a 100644 --- a/xorg-server/os/utils.c +++ b/xorg-server/os/utils.c @@ -217,6 +217,9 @@ static char *dev_tty_from_init = NULL; /* since we need to parse it anyway */ OsSigHandlerPtr OsSignal(int sig, OsSigHandlerPtr handler) { +#ifdef X_NOT_POSIX + return signal(sig, handler); +#else struct sigaction act, oact; sigemptyset(&act.sa_mask); @@ -227,6 +230,7 @@ OsSignal(int sig, OsSigHandlerPtr handler) if (sigaction(sig, &act, &oact)) perror("sigaction"); return oact.sa_handler; +#endif } /* @@ -252,7 +256,7 @@ OsSignal(int sig, OsSigHandlerPtr handler) #endif static Bool StillLocking = FALSE; -static char LockFile[PATH_MAX]; +static char szLockFile[PATH_MAX]; static Bool nolock = FALSE; /* @@ -264,26 +268,34 @@ static Bool nolock = FALSE; void LockServer(void) { +#if defined(WIN32) && !defined(__CYGWIN__) + char MutexName[100]; + sprintf(MutexName, "Global\\VcXsrv_Mutex_%d\n", getpid()); + if (!CreateMutex(NULL,TRUE,MutexName) || GetLastError()== ERROR_ALREADY_EXISTS) + { + FatalError("Server is already active for display %d\n", atoi(display)); + } +#else + char port[20]; char tmp[PATH_MAX], pid_str[12]; int lfd, i, haslock, l_pid, t; char *tmppath = NULL; int len; - char port[20]; if (nolock) return; /* * Path names */ tmppath = LOCK_DIR; - sprintf(port, "%d", atoi(display)); + len = strlen(LOCK_PREFIX) > strlen(LOCK_TMP_PREFIX) ? strlen(LOCK_PREFIX) : strlen(LOCK_TMP_PREFIX); len += strlen(tmppath) + strlen(port) + strlen(LOCK_SUFFIX) + 1; - if (len > sizeof(LockFile)) + if (len > sizeof(szLockFile)) FatalError("Display name `%s' is too long\n", port); (void)sprintf(tmp, "%s" LOCK_TMP_PREFIX "%s" LOCK_SUFFIX, tmppath, port); - (void)sprintf(LockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); + (void)sprintf(szLockFile, "%s" LOCK_PREFIX "%s" LOCK_SUFFIX, tmppath, port); /* * Create a temporary file containing our PID. Attempt three times @@ -325,7 +337,7 @@ LockServer(void) i = 0; haslock = 0; while ((!haslock) && (i++ < 3)) { - haslock = (link(tmp,LockFile) == 0); + haslock = (link(tmp,szLockFile) == 0); if (haslock) { /* * We're done. @@ -336,17 +348,17 @@ LockServer(void) /* * Read the pid from the existing file */ - lfd = open(LockFile, O_RDONLY); + lfd = open(szLockFile, O_RDONLY); if (lfd < 0) { unlink(tmp); - FatalError("Can't read lock file %s\n", LockFile); + FatalError("Can't read lock file %s\n", szLockFile); } pid_str[0] = '\0'; if (read(lfd, pid_str, 11) != 11) { /* * Bogus lock file. */ - unlink(LockFile); + unlink(szLockFile); close(lfd); continue; } @@ -363,7 +375,7 @@ LockServer(void) /* * Stale lock file. */ - unlink(LockFile); + unlink(szLockFile); continue; } else if (((t < 0) && (errno == EPERM)) || (t == 0)) { @@ -373,14 +385,15 @@ LockServer(void) unlink(tmp); FatalError("Server is already active for display %s\n%s %s\n%s\n", port, "\tIf this server is no longer running, remove", - LockFile, "\tand start again."); + szLockFile, "\tand start again."); } } } unlink(tmp); if (!haslock) - FatalError("Could not create server lock file: %s\n", LockFile); + FatalError("Could not create server lock file: %s\n", szLockFile); StillLocking = FALSE; +#endif } /* @@ -394,7 +407,7 @@ UnlockServer(void) if (!StillLocking){ - (void) unlink(LockFile); + (void) unlink(szLockFile); } } @@ -1185,7 +1198,7 @@ XNFstrdup(const char *s) } -#ifdef SIGVTALRM +#if defined(SIGVTALRM) && !defined(__CYGWIN__) #define SMART_SCHEDULE_POSSIBLE #endif @@ -1623,6 +1636,7 @@ Fclose(pointer iop) */ /* Consider LD* variables insecure? */ +#ifndef _MSC_VER #ifndef REMOVE_ENV_LD #define REMOVE_ENV_LD 1 #endif @@ -1631,6 +1645,7 @@ Fclose(pointer iop) #ifndef REMOVE_LONG_ENV #define REMOVE_LONG_ENV 1 #endif +#endif /* * Disallow stdout or stderr as pipes? It's possible to block the X server @@ -1661,7 +1676,7 @@ Fclose(pointer iop) #endif #define MAX_ARG_LENGTH 128 -#define MAX_ENV_LENGTH 256 +#define MAX_ENV_LENGTH 2048 #define MAX_ENV_PATH_LENGTH 2048 /* Limit for *PATH and TERMCAP */ #if USE_ISPRINT diff --git a/xorg-server/os/xprintf.c b/xorg-server/os/xprintf.c index 07eaa1f58..bf70661ac 100644 --- a/xorg-server/os/xprintf.c +++ b/xorg-server/os/xprintf.c @@ -39,7 +39,9 @@ # ifdef __va_copy # define va_copy __va_copy # else +# ifndef _MSC_VER # error "no working va_copy was found" +# endif # endif #endif @@ -48,11 +50,16 @@ Xvprintf(const char *format, va_list va) { char *ret; int size; + +#ifdef _MSC_VER + size = vsnprintf(NULL, 0, format, va); +#else va_list va2; va_copy(va2, va); size = vsnprintf(NULL, 0, format, va2); va_end(va2); +#endif ret = (char *)Xalloc(size + 1); if (ret == NULL) @@ -78,11 +85,16 @@ XNFvprintf(const char *format, va_list va) { char *ret; int size; + +#ifdef _MSC_VER + size = vsnprintf(NULL, 0, format, va); +#else va_list va2; va_copy(va2, va); size = vsnprintf(NULL, 0, format, va2); va_end(va2); +#endif ret = (char *)XNFalloc(size + 1); if (ret == NULL) diff --git a/xorg-server/os/xstrans.c b/xorg-server/os/xstrans.c index c086e225b..86c8688da 100644 --- a/xorg-server/os/xstrans.c +++ b/xorg-server/os/xstrans.c @@ -5,4 +5,6 @@ #define TRANS_REOPEN #define TRANS_SERVER #define XSERV_t +#define TCPCONN + #include <X11/Xtrans/transport.c> diff --git a/xorg-server/randr/makefile b/xorg-server/randr/makefile new file mode 100644 index 000000000..f72a32e9b --- /dev/null +++ b/xorg-server/randr/makefile @@ -0,0 +1,17 @@ +LIBRARY=librandr
+
+CSRCS = \
+ rrxinerama.c \
+ mirandr.c \
+ randr.c \
+ rrcrtc.c \
+ rrdispatch.c \
+ rrinfo.c \
+ rrmode.c \
+ rroutput.c \
+ rrpointer.c \
+ rrproperty.c \
+ rrscreen.c \
+ rrsdispatch.c \
+ rrtransform.c
+
diff --git a/xorg-server/randr/rrcrtc.c b/xorg-server/randr/rrcrtc.c index 0e14b36dd..d4bf342f3 100644 --- a/xorg-server/randr/rrcrtc.c +++ b/xorg-server/randr/rrcrtc.c @@ -542,7 +542,7 @@ RRModeGetScanoutSize (RRModePtr mode, PictTransformPtr transform, void RRCrtcGetScanoutSize(RRCrtcPtr crtc, int *width, int *height) { - return RRModeGetScanoutSize (crtc->mode, &crtc->transform, width, height); + RRModeGetScanoutSize (crtc->mode, &crtc->transform, width, height); } /* diff --git a/xorg-server/randr/rroutput.c b/xorg-server/randr/rroutput.c index 2eff8c183..e58eb9f74 100644 --- a/xorg-server/randr/rroutput.c +++ b/xorg-server/randr/rroutput.c @@ -24,6 +24,11 @@ #include "randrstr.h" #include "registry.h" +/* From render.h */ +#ifndef SubPixelUnknown +#define SubPixelUnknown 0 +#endif + RESTYPE RROutputType; /* diff --git a/xorg-server/randr/rrscreen.c b/xorg-server/randr/rrscreen.c index 630ff5742..e88a42816 100644 --- a/xorg-server/randr/rrscreen.c +++ b/xorg-server/randr/rrscreen.c @@ -23,6 +23,11 @@ #include "randrstr.h" static const int padlength[4] = {0, 3, 2, 1}; +/* From render.h */ +#ifndef SubPixelUnknown +#define SubPixelUnknown 0 +#endif + static CARD16 RR10CurrentSizeID (ScreenPtr pScreen); diff --git a/xorg-server/record/makefile b/xorg-server/record/makefile new file mode 100644 index 000000000..1cef2de18 --- /dev/null +++ b/xorg-server/record/makefile @@ -0,0 +1,4 @@ +CSRCS = record.c set.c + +LIBRARY=librecord + diff --git a/xorg-server/render/makefile b/xorg-server/render/makefile new file mode 100644 index 000000000..dfd905a7c --- /dev/null +++ b/xorg-server/render/makefile @@ -0,0 +1,16 @@ +
+LIBRARY=librender
+
+CSRCS = \
+ animcur.c \
+ filter.c \
+ glyph.c \
+ matrix.c \
+ miindex.c \
+ mipict.c \
+ mirect.c \
+ mitrap.c \
+ mitri.c \
+ picture.c \
+ render.c \
+ renderedge.c
diff --git a/xorg-server/render/mipict.c b/xorg-server/render/mipict.c index 71f3de718..30dd2c80f 100644 --- a/xorg-server/render/mipict.c +++ b/xorg-server/render/mipict.c @@ -266,7 +266,7 @@ miChangePictureFilter (PicturePtr pPicture, #define BOUND(v) (INT16) ((v) < MINSHORT ? MINSHORT : (v) > MAXSHORT ? MAXSHORT : (v)) -static inline pixman_bool_t +static __inline pixman_bool_t miClipPictureReg (pixman_region16_t * pRegion, pixman_region16_t * pClip, int dx, diff --git a/xorg-server/startmulti.bat b/xorg-server/startmulti.bat new file mode 100644 index 000000000..6b989d2aa --- /dev/null +++ b/xorg-server/startmulti.bat @@ -0,0 +1 @@ +vcxsrv :1 -ac -terminate -lesspointer -multiwindow -xkblayout be -xkbmodel pc105 -clipboard -logverbose 4
diff --git a/xorg-server/startxdmcp.bat b/xorg-server/startxdmcp.bat new file mode 100644 index 000000000..b2af85f53 --- /dev/null +++ b/xorg-server/startxdmcp.bat @@ -0,0 +1,2 @@ +vcxsrv :1 -query 192.168.37.20 -clipboard -ac -xkblayout be -xkbmodel pc105 -logverbose 4 -once
+
diff --git a/xorg-server/system.XWinrc b/xorg-server/system.XWinrc new file mode 100644 index 000000000..db1fd9100 --- /dev/null +++ b/xorg-server/system.XWinrc @@ -0,0 +1,124 @@ +# XWin Server Resource File - EXAMPLE +# Earle F. Philhower, III + +# Place in ~/.XWinrc or in /etc/X11/system.XWinrc + +# Keywords are case insensitive, comments legal pretty much anywhere +# you can have an end-of-line + +# Comments begin with "#" or "//" and go to the end-of-line + +# Paths to commands are **cygwin** based (i.e. /usr/local/bin/xcalc) + +# Paths to icons are **WINDOWS** based (i.e. c:\windows\icons) + +# Menus are defined as... +# MENU <name> { +# <Menu Text> EXEC <command> +# ^^ This command will have any "%display%" +# string replaced with the proper display +# variable (i.e. 127.0.0.1:<display>.0) +# or <Menu Text> MENU <name-of-some-prior-defined-menu> +# or <Menu Text> ALWAYSONTOP +# ^^ Sets the window to display above all others +# or <Menu Text> RELOAD +# ^^ Causes ~/.XWinrc or the system.XWinrc file +# to be reloaded and icons and menus regenerated +# or SEPARATOR +# ... +# } + +# Set the taskmar menu with +# ROOTMENU <name-of-some-prior-defined-menu> + +# If you want a menu to be applied to all popup window's system menu +# DEFAULTSYSMENU <name-of-some-prior-defined-menu> <atstart|atend> + +# To choose a specific menu for a specific WM_CLASS or WM_NAME use ... +# SYSMENU { +# <class-or-name-of-window> <name-of-prior-defined-menu> <atstart|atend> +# ... +# } + +# When specifying an ICONFILE in the following commands several different +# formats are allowed: +# 1. Name of a regular Windows .ico format file +# (ex: "cygwin.ico", "apple.ico") +# 2. Name and index into a Windows .DLL +# (ex: "c:\windows\system32\shell32.dll,4" gives the default folder icon +# "c:\windows\system32\shell32.dll,5" gives the floppy drive icon) +# 3. Index into XWin.EXE internal ICON resource +# (ex: ",101" is the 1st icon inside XWin.exe) + +# To define where ICO files live (** Windows path**) +# ICONDIRECTORY <windows-path i.e. c:\cygwin\usr\icons> +# NOTE: If you specify a fully qualified path to an ICON below +# (i.e. "c:\xxx" or "d:\xxxx") +# this ICONDIRECTORY will not be prepended + +# To change the taskbar icon use... +# TRAYICON <name-of-windows-ico-file-in-icondirectory> + +# To define a replacement for the standard X icon for apps w/o specified icons +# DEFAULTICON <name-of-windows-ico-file-in-icondirectory> + +# To define substitute icons on a per-window basis use... +# ICONS { +# <class-or-name-of-window> <icon-file-name.ico> +# ... +# } +# In the case where multiple matches occur, the first listed in the ICONS +# section will be chosen. + +# To disable exit confirmation dialog add the line containing SilentExit + +# DEBUG <string> prints out the string to the XWin.log file + +// Below are just some silly menus to demonstrate writing your +// own configuration file. + +// Make some menus... +menu apps { + xterm exec "xterm" + notepad exec notepad + xload exec "xload -display %display%" # Comment +} + +menu root { +// Comments fit here, too... + "Reload system.XWinrc" RELOAD + "Applications" menu apps + Separator +} + +menu aot { + Separator + "Always on Top" alwaysontop +} + +menu xtermspecial { + "Emacs" exec "emacs" + "Always on Top" alwaysontop + Separator +} + +RootMenu root + +DefaultSysMenu aot atend + +SysMenu { + "xterm" xtermspecial atstart +} + +# IconDirectory "c:\winnt\" + +# DefaultIcon "reinstall.ico" + +# Icons { +# "xterm" "uninstall.ico" +# } + +# SilentExit + +# DEBUG "Done parsing the configuration file..." + diff --git a/xorg-server/vcxsrv.sln b/xorg-server/vcxsrv.sln new file mode 100644 index 000000000..948ecfc63 --- /dev/null +++ b/xorg-server/vcxsrv.sln @@ -0,0 +1,16 @@ +
+Microsoft Visual Studio Solution File, Format Version 10.00
+# Visual C++ Express 2008
+Project("{8BC9CEB9-8B4A-11D0-8D11-00A0C91BC942}") = "vcxsrv.exe", "vcxsrv.exe", "{0A7F2844-C7BA-43E2-B7AE-48070F7AA1A7}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Default = Debug|Default
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {0A7F2844-C7BA-43E2-B7AE-48070F7AA1A7}.Debug|Default.ActiveCfg = Debug
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/xorg-server/xfixes/cursor.c b/xorg-server/xfixes/cursor.c index aac90e393..6be1761fa 100644 --- a/xorg-server/xfixes/cursor.c +++ b/xorg-server/xfixes/cursor.c @@ -1,1106 +1,1108 @@ -/* - * Copyright © 2006 Sun Microsystems, Inc. All rights reserved. - * - * Permission is hereby granted, free of charge, to any person obtaining a - * copy of this software and associated documentation files (the - * "Software"), to deal in the Software without restriction, including - * without limitation the rights to use, copy, modify, merge, publish, - * distribute, and/or sell copies of the Software, and to permit persons - * to whom the Software is furnished to do so, provided that the above - * copyright notice(s) and this permission notice appear in all copies of - * the Software and that both the above copyright notice(s) and this - * permission notice appear in supporting documentation. - * - * 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 - * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR - * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR 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. - * - * Except as contained in this notice, the name of a copyright holder - * shall not be used in advertising or otherwise to promote the sale, use - * or other dealings in this Software without prior written authorization - * of the copyright holder. - * - * Copyright © 2002 Keith Packard - * - * Permission to use, copy, modify, distribute, and sell this software and its - * documentation for any purpose is hereby granted without fee, provided that - * the above copyright notice appear in all copies and that both that - * copyright notice and this permission notice appear in supporting - * documentation, and that the name of 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_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include "xfixesint.h" -#include "scrnintstr.h" -#include "cursorstr.h" -#include "dixevents.h" -#include "servermd.h" -#include "inputstr.h" -#include "windowstr.h" -#include "xace.h" - -static RESTYPE CursorClientType; -static RESTYPE CursorHideCountType; -static RESTYPE CursorWindowType; -static CursorPtr CursorCurrent[MAXDEVICES]; -static CursorPtr pInvisibleCursor = NULL; - -static int CursorScreenPrivateKeyIndex; -static DevPrivateKey CursorScreenPrivateKey = &CursorScreenPrivateKeyIndex; - -static void deleteCursorHideCountsForScreen (ScreenPtr pScreen); - -#define VERIFY_CURSOR(pCursor, cursor, client, access) \ - do { \ - int err; \ - err = dixLookupResourceByType((pointer *) &pCursor, cursor, \ - RT_CURSOR, client, access); \ - if (err == BadValue) { \ - client->errorValue = cursor; \ - return BadCursor; \ - } else if (err != Success) { \ - client->errorValue = cursor; \ - return err; \ - } \ - } while (0) - -/* - * There is a global list of windows selecting for cursor events - */ - -typedef struct _CursorEvent *CursorEventPtr; - -typedef struct _CursorEvent { - CursorEventPtr next; - CARD32 eventMask; - ClientPtr pClient; - WindowPtr pWindow; - XID clientResource; -} CursorEventRec; - -static CursorEventPtr cursorEvents; - -/* - * Each screen has a list of clients which have requested - * that the cursor be hid, and the number of times each - * client has requested. -*/ - -typedef struct _CursorHideCountRec *CursorHideCountPtr; - -typedef struct _CursorHideCountRec { - CursorHideCountPtr pNext; - ClientPtr pClient; - ScreenPtr pScreen; - int hideCount; - XID resource; -} CursorHideCountRec; - -/* - * Wrap DisplayCursor to catch cursor change events - */ - -typedef struct _CursorScreen { - DisplayCursorProcPtr DisplayCursor; - CloseScreenProcPtr CloseScreen; - CursorHideCountPtr pCursorHideCounts; -} CursorScreenRec, *CursorScreenPtr; - -#define GetCursorScreen(s) ((CursorScreenPtr)dixLookupPrivate(&(s)->devPrivates, CursorScreenPrivateKey)) -#define GetCursorScreenIfSet(s) GetCursorScreen(s) -#define SetCursorScreen(s,p) dixSetPrivate(&(s)->devPrivates, CursorScreenPrivateKey, p) -#define Wrap(as,s,elt,func) (((as)->elt = (s)->elt), (s)->elt = func) -#define Unwrap(as,s,elt,backup) (((backup) = (s)->elt), (s)->elt = (as)->elt) - -/* The cursor doesn't show up until the first XDefineCursor() */ -static Bool CursorVisible = FALSE; - -Bool EnableCursor = TRUE; - -static Bool -CursorDisplayCursor (DeviceIntPtr pDev, - ScreenPtr pScreen, - CursorPtr pCursor) -{ - CursorScreenPtr cs = GetCursorScreen(pScreen); - Bool ret; - DisplayCursorProcPtr backupProc; - - Unwrap (cs, pScreen, DisplayCursor, backupProc); - - /* - * Have to check ConnectionInfo to distinguish client requests from - * initial root window setup. Not a great way to do it, I admit. - */ - if (ConnectionInfo) - CursorVisible = EnableCursor; - - if (cs->pCursorHideCounts != NULL || !CursorVisible) { - ret = ((*pScreen->RealizeCursor)(pDev, pScreen, pInvisibleCursor) && - (*pScreen->DisplayCursor) (pDev, pScreen, pInvisibleCursor)); - } else { - ret = (*pScreen->DisplayCursor) (pDev, pScreen, pCursor); - } - - if (pCursor != CursorCurrent[pDev->id]) - { - CursorEventPtr e; - - CursorCurrent[pDev->id] = pCursor; - for (e = cursorEvents; e; e = e->next) - { - if ((e->eventMask & XFixesDisplayCursorNotifyMask) && - !e->pClient->clientGone) - { - xXFixesCursorNotifyEvent ev; - ev.type = XFixesEventBase + XFixesCursorNotify; - ev.subtype = XFixesDisplayCursorNotify; - ev.sequenceNumber = e->pClient->sequence; - ev.window = e->pWindow->drawable.id; - ev.cursorSerial = pCursor->serialNumber; - ev.timestamp = currentTime.milliseconds; - ev.name = pCursor->name; - WriteEventsToClient (e->pClient, 1, (xEvent *) &ev); - } - } - } - Wrap (cs, pScreen, DisplayCursor, backupProc); - - return ret; -} - -static Bool -CursorCloseScreen (int index, ScreenPtr pScreen) -{ - CursorScreenPtr cs = GetCursorScreen (pScreen); - Bool ret; - CloseScreenProcPtr close_proc; - DisplayCursorProcPtr display_proc; - - Unwrap (cs, pScreen, CloseScreen, close_proc); - Unwrap (cs, pScreen, DisplayCursor, display_proc); - deleteCursorHideCountsForScreen(pScreen); - ret = (*pScreen->CloseScreen) (index, pScreen); - xfree (cs); - return ret; -} - -#define CursorAllEvents (XFixesDisplayCursorNotifyMask) - -static int -XFixesSelectCursorInput (ClientPtr pClient, - WindowPtr pWindow, - CARD32 eventMask) -{ - CursorEventPtr *prev, e; - pointer val; - int rc; - - for (prev = &cursorEvents; (e = *prev); prev = &e->next) - { - if (e->pClient == pClient && - e->pWindow == pWindow) - { - break; - } - } - if (!eventMask) - { - if (e) - { - FreeResource (e->clientResource, 0); - } - return Success; - } - if (!e) - { - e = (CursorEventPtr) xalloc (sizeof (CursorEventRec)); - if (!e) - return BadAlloc; - - e->next = 0; - e->pClient = pClient; - e->pWindow = pWindow; - e->clientResource = FakeClientID(pClient->index); - - /* - * Add a resource hanging from the window to - * catch window destroy - */ - rc = dixLookupResourceByType( &val, pWindow->drawable.id, - CursorWindowType, serverClient, - DixGetAttrAccess); - if (rc != Success) - if (!AddResource (pWindow->drawable.id, CursorWindowType, - (pointer) pWindow)) - { - xfree (e); - return BadAlloc; - } - - if (!AddResource (e->clientResource, CursorClientType, (pointer) e)) - return BadAlloc; - - *prev = e; - } - e->eventMask = eventMask; - return Success; -} - -int -ProcXFixesSelectCursorInput (ClientPtr client) -{ - REQUEST (xXFixesSelectCursorInputReq); - WindowPtr pWin; - int rc; - - REQUEST_SIZE_MATCH (xXFixesSelectCursorInputReq); - rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); - if (rc != Success) - return rc; - if (stuff->eventMask & ~CursorAllEvents) - { - client->errorValue = stuff->eventMask; - return( BadValue ); - } - return XFixesSelectCursorInput (client, pWin, stuff->eventMask); -} - -static int -GetBit (unsigned char *line, int x) -{ - unsigned char mask; - - if (screenInfo.bitmapBitOrder == LSBFirst) - mask = (1 << (x & 7)); - else - mask = (0x80 >> (x & 7)); - /* XXX assumes byte order is host byte order */ - line += (x >> 3); - if (*line & mask) - return 1; - return 0; -} - -int -SProcXFixesSelectCursorInput (ClientPtr client) -{ - register int n; - REQUEST(xXFixesSelectCursorInputReq); - - swaps(&stuff->length, n); - swapl(&stuff->window, n); - swapl(&stuff->eventMask, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -void -SXFixesCursorNotifyEvent (xXFixesCursorNotifyEvent *from, - xXFixesCursorNotifyEvent *to) -{ - to->type = from->type; - cpswaps (from->sequenceNumber, to->sequenceNumber); - cpswapl (from->window, to->window); - cpswapl (from->cursorSerial, to->cursorSerial); - cpswapl (from->timestamp, to->timestamp); - cpswapl (from->name, to->name); -} - -static void -CopyCursorToImage (CursorPtr pCursor, CARD32 *image) -{ - int width = pCursor->bits->width; - int height = pCursor->bits->height; - int npixels = width * height; - -#ifdef ARGB_CURSOR - if (pCursor->bits->argb) - memcpy (image, pCursor->bits->argb, npixels * sizeof (CARD32)); - else -#endif - { - unsigned char *srcLine = pCursor->bits->source; - unsigned char *mskLine = pCursor->bits->mask; - int stride = BitmapBytePad (width); - int x, y; - CARD32 fg, bg; - - fg = (0xff000000 | - ((pCursor->foreRed & 0xff00) << 8) | - (pCursor->foreGreen & 0xff00) | - (pCursor->foreBlue >> 8)); - bg = (0xff000000 | - ((pCursor->backRed & 0xff00) << 8) | - (pCursor->backGreen & 0xff00) | - (pCursor->backBlue >> 8)); - for (y = 0; y < height; y++) - { - for (x = 0; x < width; x++) - { - if (GetBit (mskLine, x)) - { - if (GetBit (srcLine, x)) - *image++ = fg; - else - *image++ = bg; - } - else - *image++ = 0; - } - srcLine += stride; - mskLine += stride; - } - } -} - -int -ProcXFixesGetCursorImage (ClientPtr client) -{ -/* REQUEST(xXFixesGetCursorImageReq); */ - xXFixesGetCursorImageReply *rep; - CursorPtr pCursor; - CARD32 *image; - int npixels, width, height, rc, x, y; - - REQUEST_SIZE_MATCH(xXFixesGetCursorImageReq); - pCursor = CursorCurrent[PickPointer(client)->id]; - if (!pCursor) - return BadCursor; - rc = XaceHook(XACE_RESOURCE_ACCESS, client, pCursor->id, RT_CURSOR, - pCursor, RT_NONE, NULL, DixReadAccess); - if (rc != Success) - return rc; - GetSpritePosition (PickPointer(client), &x, &y); - width = pCursor->bits->width; - height = pCursor->bits->height; - npixels = width * height; - rep = xalloc (sizeof (xXFixesGetCursorImageReply) + - npixels * sizeof (CARD32)); - if (!rep) - return BadAlloc; - - rep->type = X_Reply; - rep->sequenceNumber = client->sequence; - rep->length = npixels; - rep->width = width; - rep->height = height; - rep->x = x; - rep->y = y; - rep->xhot = pCursor->bits->xhot; - rep->yhot = pCursor->bits->yhot; - rep->cursorSerial = pCursor->serialNumber; - - image = (CARD32 *) (rep + 1); - CopyCursorToImage (pCursor, image); - if (client->swapped) - { - int n; - swaps (&rep->sequenceNumber, n); - swapl (&rep->length, n); - swaps (&rep->x, n); - swaps (&rep->y, n); - swaps (&rep->width, n); - swaps (&rep->height, n); - swaps (&rep->xhot, n); - swaps (&rep->yhot, n); - swapl (&rep->cursorSerial, n); - SwapLongs (image, npixels); - } - WriteToClient(client, sizeof (xXFixesGetCursorImageReply) + - (npixels << 2), (char *) rep); - xfree (rep); - return client->noClientException; -} - -int -SProcXFixesGetCursorImage (ClientPtr client) -{ - int n; - REQUEST(xXFixesGetCursorImageReq); - swaps (&stuff->length, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -int -ProcXFixesSetCursorName (ClientPtr client) -{ - CursorPtr pCursor; - char *tchar; - REQUEST(xXFixesSetCursorNameReq); - Atom atom; - - REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); - VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess); - tchar = (char *) &stuff[1]; - atom = MakeAtom (tchar, stuff->nbytes, TRUE); - if (atom == BAD_RESOURCE) - return BadAlloc; - - pCursor->name = atom; - return(client->noClientException); -} - -int -SProcXFixesSetCursorName (ClientPtr client) -{ - int n; - REQUEST(xXFixesSetCursorNameReq); - - swaps (&stuff->length, n); - REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq); - swapl (&stuff->cursor, n); - swaps (&stuff->nbytes, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -int -ProcXFixesGetCursorName (ClientPtr client) -{ - CursorPtr pCursor; - xXFixesGetCursorNameReply reply; - REQUEST(xXFixesGetCursorNameReq); - const char *str; - int len; - - REQUEST_SIZE_MATCH(xXFixesGetCursorNameReq); - VERIFY_CURSOR(pCursor, stuff->cursor, client, DixGetAttrAccess); - if (pCursor->name) - str = NameForAtom (pCursor->name); - else - str = ""; - len = strlen (str); - - reply.type = X_Reply; - reply.length = bytes_to_int32(len); - reply.sequenceNumber = client->sequence; - reply.atom = pCursor->name; - reply.nbytes = len; - if (client->swapped) - { - int n; - swaps (&reply.sequenceNumber, n); - swapl (&reply.length, n); - swapl (&reply.atom, n); - swaps (&reply.nbytes, n); - } - WriteReplyToClient(client, sizeof(xXFixesGetCursorNameReply), &reply); - WriteToClient(client, len, str); - - return(client->noClientException); -} - -int -SProcXFixesGetCursorName (ClientPtr client) -{ - int n; - REQUEST(xXFixesGetCursorNameReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xXFixesGetCursorNameReq); - swapl (&stuff->cursor, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -int -ProcXFixesGetCursorImageAndName (ClientPtr client) -{ -/* REQUEST(xXFixesGetCursorImageAndNameReq); */ - xXFixesGetCursorImageAndNameReply *rep; - CursorPtr pCursor; - CARD32 *image; - int npixels; - const char *name; - int nbytes, nbytesRound; - int width, height; - int rc, x, y; - - REQUEST_SIZE_MATCH(xXFixesGetCursorImageAndNameReq); - pCursor = CursorCurrent[PickPointer(client)->id]; - if (!pCursor) - return BadCursor; - rc = XaceHook(XACE_RESOURCE_ACCESS, client, pCursor->id, RT_CURSOR, - pCursor, RT_NONE, NULL, DixReadAccess|DixGetAttrAccess); - if (rc != Success) - return rc; - GetSpritePosition (PickPointer(client), &x, &y); - width = pCursor->bits->width; - height = pCursor->bits->height; - npixels = width * height; - name = pCursor->name ? NameForAtom (pCursor->name) : ""; - nbytes = strlen (name); - nbytesRound = pad_to_int32(nbytes); - rep = xalloc (sizeof (xXFixesGetCursorImageAndNameReply) + - npixels * sizeof (CARD32) + nbytesRound); - if (!rep) - return BadAlloc; - - rep->type = X_Reply; - rep->sequenceNumber = client->sequence; - rep->length = npixels + bytes_to_int32(nbytesRound); - rep->width = width; - rep->height = height; - rep->x = x; - rep->y = y; - rep->xhot = pCursor->bits->xhot; - rep->yhot = pCursor->bits->yhot; - rep->cursorSerial = pCursor->serialNumber; - rep->cursorName = pCursor->name; - rep->nbytes = nbytes; - - image = (CARD32 *) (rep + 1); - CopyCursorToImage (pCursor, image); - memcpy ((image + npixels), name, nbytes); - if (client->swapped) - { - int n; - swaps (&rep->sequenceNumber, n); - swapl (&rep->length, n); - swaps (&rep->x, n); - swaps (&rep->y, n); - swaps (&rep->width, n); - swaps (&rep->height, n); - swaps (&rep->xhot, n); - swaps (&rep->yhot, n); - swapl (&rep->cursorSerial, n); - swapl (&rep->cursorName, n); - swaps (&rep->nbytes, n); - SwapLongs (image, npixels); - } - WriteToClient(client, sizeof (xXFixesGetCursorImageAndNameReply) + - (npixels << 2) + nbytesRound, (char *) rep); - xfree (rep); - return client->noClientException; -} - -int -SProcXFixesGetCursorImageAndName (ClientPtr client) -{ - int n; - REQUEST(xXFixesGetCursorImageAndNameReq); - swaps (&stuff->length, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -/* - * Find every cursor reference in the system, ask testCursor - * whether it should be replaced with a reference to pCursor. - */ - -typedef Bool (*TestCursorFunc) (CursorPtr pOld, pointer closure); - -typedef struct { - RESTYPE type; - TestCursorFunc testCursor; - CursorPtr pNew; - pointer closure; -} ReplaceCursorLookupRec, *ReplaceCursorLookupPtr; - -static const RESTYPE CursorRestypes[] = { - RT_WINDOW, RT_PASSIVEGRAB, RT_CURSOR -}; - -#define NUM_CURSOR_RESTYPES (sizeof (CursorRestypes) / sizeof (CursorRestypes[0])) - -static Bool -ReplaceCursorLookup (pointer value, XID id, pointer closure) -{ - ReplaceCursorLookupPtr rcl = (ReplaceCursorLookupPtr) closure; - WindowPtr pWin; - GrabPtr pGrab; - CursorPtr pCursor = 0, *pCursorRef = 0; - XID cursor = 0; - - switch (rcl->type) { - case RT_WINDOW: - pWin = (WindowPtr) value; - if (pWin->optional) - { - pCursorRef = &pWin->optional->cursor; - pCursor = *pCursorRef; - } - break; - case RT_PASSIVEGRAB: - pGrab = (GrabPtr) value; - pCursorRef = &pGrab->cursor; - pCursor = *pCursorRef; - break; - case RT_CURSOR: - pCursorRef = 0; - pCursor = (CursorPtr) value; - cursor = id; - break; - } - if (pCursor && pCursor != rcl->pNew) - { - if ((*rcl->testCursor) (pCursor, rcl->closure)) - { - rcl->pNew->refcnt++; - /* either redirect reference or update resource database */ - if (pCursorRef) - *pCursorRef = rcl->pNew; - else - ChangeResourceValue (id, RT_CURSOR, rcl->pNew); - FreeCursor (pCursor, cursor); - } - } - return FALSE; /* keep walking */ -} - -static void -ReplaceCursor (CursorPtr pCursor, - TestCursorFunc testCursor, - pointer closure) -{ - int clientIndex; - int resIndex; - ReplaceCursorLookupRec rcl; - - /* - * Cursors exist only in the resource database, windows and grabs. - * All of these are always pointed at by the resource database. Walk - * the whole thing looking for cursors - */ - rcl.testCursor = testCursor; - rcl.pNew = pCursor; - rcl.closure = closure; - - /* for each client */ - for (clientIndex = 0; clientIndex < currentMaxClients; clientIndex++) - { - if (!clients[clientIndex]) - continue; - for (resIndex = 0; resIndex < NUM_CURSOR_RESTYPES; resIndex++) - { - rcl.type = CursorRestypes[resIndex]; - /* - * This function walks the entire client resource database - */ - LookupClientResourceComplex (clients[clientIndex], - rcl.type, - ReplaceCursorLookup, - (pointer) &rcl); - } - } - /* this "knows" that WindowHasNewCursor doesn't depend on it's argument */ - WindowHasNewCursor (WindowTable[0]); -} - -static Bool -TestForCursor (CursorPtr pCursor, pointer closure) -{ - return (pCursor == (CursorPtr) closure); -} - -int -ProcXFixesChangeCursor (ClientPtr client) -{ - CursorPtr pSource, pDestination; - REQUEST(xXFixesChangeCursorReq); - - REQUEST_SIZE_MATCH(xXFixesChangeCursorReq); - VERIFY_CURSOR (pSource, stuff->source, client, - DixReadAccess|DixGetAttrAccess); - VERIFY_CURSOR (pDestination, stuff->destination, client, - DixWriteAccess|DixSetAttrAccess); - - ReplaceCursor (pSource, TestForCursor, (pointer) pDestination); - return (client->noClientException); -} - -int -SProcXFixesChangeCursor (ClientPtr client) -{ - int n; - REQUEST(xXFixesChangeCursorReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH(xXFixesChangeCursorReq); - swapl (&stuff->source, n); - swapl (&stuff->destination, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -static Bool -TestForCursorName (CursorPtr pCursor, pointer closure) -{ - Atom *pName = closure; - return (pCursor->name == *pName); -} - -int -ProcXFixesChangeCursorByName (ClientPtr client) -{ - CursorPtr pSource; - Atom name; - char *tchar; - REQUEST(xXFixesChangeCursorByNameReq); - - REQUEST_FIXED_SIZE(xXFixesChangeCursorByNameReq, stuff->nbytes); - VERIFY_CURSOR(pSource, stuff->source, client, - DixReadAccess|DixGetAttrAccess); - tchar = (char *) &stuff[1]; - name = MakeAtom (tchar, stuff->nbytes, FALSE); - if (name) - ReplaceCursor (pSource, TestForCursorName, &name); - return (client->noClientException); -} - -int -SProcXFixesChangeCursorByName (ClientPtr client) -{ - int n; - REQUEST(xXFixesChangeCursorByNameReq); - - swaps (&stuff->length, n); - REQUEST_AT_LEAST_SIZE (xXFixesChangeCursorByNameReq); - swapl (&stuff->source, n); - swaps (&stuff->nbytes, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -/* - * Routines for manipulating the per-screen hide counts list. - * This list indicates which clients have requested cursor hiding - * for that screen. - */ - -/* Return the screen's hide-counts list element for the given client */ -static CursorHideCountPtr -findCursorHideCount (ClientPtr pClient, ScreenPtr pScreen) -{ - CursorScreenPtr cs = GetCursorScreen(pScreen); - CursorHideCountPtr pChc; - - for (pChc = cs->pCursorHideCounts; pChc != NULL; pChc = pChc->pNext) { - if (pChc->pClient == pClient) { - return pChc; - } - } - - return NULL; -} - -static int -createCursorHideCount (ClientPtr pClient, ScreenPtr pScreen) -{ - CursorScreenPtr cs = GetCursorScreen(pScreen); - CursorHideCountPtr pChc; - - pChc = (CursorHideCountPtr) xalloc(sizeof(CursorHideCountRec)); - if (pChc == NULL) { - return BadAlloc; - } - pChc->pClient = pClient; - pChc->pScreen = pScreen; - pChc->hideCount = 1; - pChc->resource = FakeClientID(pClient->index); - pChc->pNext = cs->pCursorHideCounts; - cs->pCursorHideCounts = pChc; - - /* - * Create a resource for this element so it can be deleted - * when the client goes away. - */ - if (!AddResource (pChc->resource, CursorHideCountType, - (pointer) pChc)) { - xfree(pChc); - return BadAlloc; - } - - return Success; -} - -/* - * Delete the given hide-counts list element from its screen list. - */ -static void -deleteCursorHideCount (CursorHideCountPtr pChcToDel, ScreenPtr pScreen) -{ - CursorScreenPtr cs = GetCursorScreen(pScreen); - CursorHideCountPtr pChc, pNext; - CursorHideCountPtr pChcLast = NULL; - - pChc = cs->pCursorHideCounts; - while (pChc != NULL) { - pNext = pChc->pNext; - if (pChc == pChcToDel) { - xfree(pChc); - if (pChcLast == NULL) { - cs->pCursorHideCounts = pNext; - } else { - pChcLast->pNext = pNext; - } - return; - } - pChcLast = pChc; - pChc = pNext; - } -} - -/* - * Delete all the hide-counts list elements for this screen. - */ -static void -deleteCursorHideCountsForScreen (ScreenPtr pScreen) -{ - CursorScreenPtr cs = GetCursorScreen(pScreen); - CursorHideCountPtr pChc, pTmp; - - pChc = cs->pCursorHideCounts; - while (pChc != NULL) { - pTmp = pChc->pNext; - FreeResource(pChc->resource, 0); - pChc = pTmp; - } - cs->pCursorHideCounts = NULL; -} - -int -ProcXFixesHideCursor (ClientPtr client) -{ - WindowPtr pWin; - CursorHideCountPtr pChc; - REQUEST(xXFixesHideCursorReq); - int ret; - - REQUEST_SIZE_MATCH (xXFixesHideCursorReq); - - ret = dixLookupResourceByType((pointer *)&pWin, stuff->window, RT_WINDOW, - client, DixGetAttrAccess); - if (ret != Success) { - client->errorValue = stuff->window; - return (ret == BadValue) ? BadWindow : ret; - } - - /* - * Has client hidden the cursor before on this screen? - * If so, just increment the count. - */ - - pChc = findCursorHideCount(client, pWin->drawable.pScreen); - if (pChc != NULL) { - pChc->hideCount++; - return client->noClientException; - } - - /* - * This is the first time this client has hid the cursor - * for this screen. - */ - ret = XaceHook(XACE_SCREEN_ACCESS, client, pWin->drawable.pScreen, - DixHideAccess); - if (ret != Success) - return ret; - - ret = createCursorHideCount(client, pWin->drawable.pScreen); - - if (ret == Success) { - DeviceIntPtr dev; - for (dev = inputInfo.devices; dev; dev = dev->next) - { - if (IsMaster(dev) && IsPointerDevice(dev)) - CursorDisplayCursor(dev, pWin->drawable.pScreen, CursorCurrent[dev->id]); - } - } - - return ret; -} - -int -SProcXFixesHideCursor (ClientPtr client) -{ - int n; - REQUEST(xXFixesHideCursorReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xXFixesHideCursorReq); - swapl (&stuff->window, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -int -ProcXFixesShowCursor (ClientPtr client) -{ - WindowPtr pWin; - CursorHideCountPtr pChc; - int rc; - REQUEST(xXFixesShowCursorReq); - - REQUEST_SIZE_MATCH (xXFixesShowCursorReq); - - rc = dixLookupResourceByType((pointer *)&pWin, stuff->window, RT_WINDOW, - client, DixGetAttrAccess); - if (rc != Success) { - client->errorValue = stuff->window; - return (rc == BadValue) ? BadWindow : rc; - } - - /* - * Has client hidden the cursor on this screen? - * If not, generate an error. - */ - pChc = findCursorHideCount(client, pWin->drawable.pScreen); - if (pChc == NULL) { - return BadMatch; - } - - rc = XaceHook(XACE_SCREEN_ACCESS, client, pWin->drawable.pScreen, - DixShowAccess); - if (rc != Success) - return rc; - - pChc->hideCount--; - if (pChc->hideCount <= 0) { - FreeResource(pChc->resource, 0); - } - - return (client->noClientException); -} - -int -SProcXFixesShowCursor (ClientPtr client) -{ - int n; - REQUEST(xXFixesShowCursorReq); - - swaps (&stuff->length, n); - REQUEST_SIZE_MATCH (xXFixesShowCursorReq); - swapl (&stuff->window, n); - return (*ProcXFixesVector[stuff->xfixesReqType]) (client); -} - -static int -CursorFreeClient (pointer data, XID id) -{ - CursorEventPtr old = (CursorEventPtr) data; - CursorEventPtr *prev, e; - - for (prev = &cursorEvents; (e = *prev); prev = &e->next) - { - if (e == old) - { - *prev = e->next; - xfree (e); - break; - } - } - return 1; -} - -static int -CursorFreeHideCount (pointer data, XID id) -{ - CursorHideCountPtr pChc = (CursorHideCountPtr) data; - ScreenPtr pScreen = pChc->pScreen; - DeviceIntPtr dev; - - deleteCursorHideCount(pChc, pChc->pScreen); - for (dev = inputInfo.devices; dev; dev = dev->next) - { - if (IsMaster(dev) && IsPointerDevice(dev)) - CursorDisplayCursor(dev, pScreen, CursorCurrent[dev->id]); - } - - return 1; -} - -static int -CursorFreeWindow (pointer data, XID id) -{ - WindowPtr pWindow = (WindowPtr) data; - CursorEventPtr e, next; - - for (e = cursorEvents; e; e = next) - { - next = e->next; - if (e->pWindow == pWindow) - { - FreeResource (e->clientResource, 0); - } - } - return 1; -} - -static CursorPtr -createInvisibleCursor (void) -{ - CursorPtr pCursor; - unsigned char *psrcbits, *pmaskbits; - CursorMetricRec cm; - - psrcbits = (unsigned char *) xcalloc(4, 1); - pmaskbits = (unsigned char *) xcalloc(4, 1); - if (psrcbits == NULL || pmaskbits == NULL) { - return NULL; - } - - cm.width = 1; - cm.height = 1; - cm.xhot = 0; - cm.yhot = 0; - - AllocARGBCursor(psrcbits, pmaskbits, - NULL, &cm, - 0, 0, 0, - 0, 0, 0, - &pCursor, serverClient, (XID)0); - - return pCursor; -} - -Bool -XFixesCursorInit (void) -{ - int i; - - if (party_like_its_1989) - CursorVisible = EnableCursor; - - for (i = 0; i < screenInfo.numScreens; i++) - { - ScreenPtr pScreen = screenInfo.screens[i]; - CursorScreenPtr cs; - - cs = (CursorScreenPtr) xalloc (sizeof (CursorScreenRec)); - if (!cs) - return FALSE; - Wrap (cs, pScreen, CloseScreen, CursorCloseScreen); - Wrap (cs, pScreen, DisplayCursor, CursorDisplayCursor); - cs->pCursorHideCounts = NULL; - SetCursorScreen (pScreen, cs); - } - CursorClientType = CreateNewResourceType(CursorFreeClient); - CursorHideCountType = CreateNewResourceType(CursorFreeHideCount); - CursorWindowType = CreateNewResourceType(CursorFreeWindow); - - if (pInvisibleCursor == NULL) { - pInvisibleCursor = createInvisibleCursor(); - if (pInvisibleCursor == NULL) { - return BadAlloc; - } - } - - return CursorClientType && CursorWindowType; -} - +/*
+ * Copyright © 2006 Sun Microsystems, Inc. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a
+ * copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, and/or sell copies of the Software, and to permit persons
+ * to whom the Software is furnished to do so, provided that the above
+ * copyright notice(s) and this permission notice appear in all copies of
+ * the Software and that both the above copyright notice(s) and this
+ * permission notice appear in supporting documentation.
+ *
+ * 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
+ * OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+ * HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR 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.
+ *
+ * Except as contained in this notice, the name of a copyright holder
+ * shall not be used in advertising or otherwise to promote the sale, use
+ * or other dealings in this Software without prior written authorization
+ * of the copyright holder.
+ *
+ * Copyright © 2002 Keith Packard
+ *
+ * Permission to use, copy, modify, distribute, and sell this software and its
+ * documentation for any purpose is hereby granted without fee, provided that
+ * the above copyright notice appear in all copies and that both that
+ * copyright notice and this permission notice appear in supporting
+ * documentation, and that the name of 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_DIX_CONFIG_H
+#include <dix-config.h>
+#else
+#define XFIXES
+#endif
+
+#include "xfixesint.h"
+#include "scrnintstr.h"
+#include "cursorstr.h"
+#include "dixevents.h"
+#include "servermd.h"
+#include "inputstr.h"
+#include "windowstr.h"
+#include "xace.h"
+
+static RESTYPE CursorClientType;
+static RESTYPE CursorHideCountType;
+static RESTYPE CursorWindowType;
+static CursorPtr CursorCurrent[MAXDEVICES];
+static CursorPtr pInvisibleCursor = NULL;
+
+static int CursorScreenPrivateKeyIndex;
+static DevPrivateKey CursorScreenPrivateKey = &CursorScreenPrivateKeyIndex;
+
+static void deleteCursorHideCountsForScreen (ScreenPtr pScreen);
+
+#define VERIFY_CURSOR(pCursor, cursor, client, access) \
+ do { \
+ int err; \
+ err = dixLookupResourceByType((pointer *) &pCursor, cursor, \
+ RT_CURSOR, client, access); \
+ if (err == BadValue) { \
+ client->errorValue = cursor; \
+ return BadCursor; \
+ } else if (err != Success) { \
+ client->errorValue = cursor; \
+ return err; \
+ } \
+ } while (0)
+
+/*
+ * There is a global list of windows selecting for cursor events
+ */
+
+typedef struct _CursorEvent *CursorEventPtr;
+
+typedef struct _CursorEvent {
+ CursorEventPtr next;
+ CARD32 eventMask;
+ ClientPtr pClient;
+ WindowPtr pWindow;
+ XID clientResource;
+} CursorEventRec;
+
+static CursorEventPtr cursorEvents;
+
+/*
+ * Each screen has a list of clients which have requested
+ * that the cursor be hid, and the number of times each
+ * client has requested.
+*/
+
+typedef struct _CursorHideCountRec *CursorHideCountPtr;
+
+typedef struct _CursorHideCountRec {
+ CursorHideCountPtr pNext;
+ ClientPtr pClient;
+ ScreenPtr pScreen;
+ int hideCount;
+ XID resource;
+} CursorHideCountRec;
+
+/*
+ * Wrap DisplayCursor to catch cursor change events
+ */
+
+typedef struct _CursorScreen {
+ DisplayCursorProcPtr DisplayCursor;
+ CloseScreenProcPtr CloseScreen;
+ CursorHideCountPtr pCursorHideCounts;
+} CursorScreenRec, *CursorScreenPtr;
+
+#define GetCursorScreen(s) ((CursorScreenPtr)dixLookupPrivate(&(s)->devPrivates, CursorScreenPrivateKey))
+#define GetCursorScreenIfSet(s) GetCursorScreen(s)
+#define SetCursorScreen(s,p) dixSetPrivate(&(s)->devPrivates, CursorScreenPrivateKey, p)
+#define Wrap(as,s,elt,func) (((as)->elt = (s)->elt), (s)->elt = func)
+#define Unwrap(as,s,elt,backup) (((backup) = (s)->elt), (s)->elt = (as)->elt)
+
+/* The cursor doesn't show up until the first XDefineCursor() */
+static Bool CursorVisible = FALSE;
+
+Bool EnableCursor = TRUE;
+
+static Bool
+CursorDisplayCursor (DeviceIntPtr pDev,
+ ScreenPtr pScreen,
+ CursorPtr pCursor)
+{
+ CursorScreenPtr cs = GetCursorScreen(pScreen);
+ Bool ret;
+ DisplayCursorProcPtr backupProc;
+
+ Unwrap (cs, pScreen, DisplayCursor, backupProc);
+
+ /*
+ * Have to check ConnectionInfo to distinguish client requests from
+ * initial root window setup. Not a great way to do it, I admit.
+ */
+ if (ConnectionInfo)
+ CursorVisible = EnableCursor;
+
+ if (cs->pCursorHideCounts != NULL || !CursorVisible) {
+ ret = ((*pScreen->RealizeCursor)(pDev, pScreen, pInvisibleCursor) &&
+ (*pScreen->DisplayCursor) (pDev, pScreen, pInvisibleCursor));
+ } else {
+ ret = (*pScreen->DisplayCursor) (pDev, pScreen, pCursor);
+ }
+
+ if (pCursor != CursorCurrent[pDev->id])
+ {
+ CursorEventPtr e;
+
+ CursorCurrent[pDev->id] = pCursor;
+ for (e = cursorEvents; e; e = e->next)
+ {
+ if ((e->eventMask & XFixesDisplayCursorNotifyMask) &&
+ !e->pClient->clientGone)
+ {
+ xXFixesCursorNotifyEvent ev;
+ ev.type = XFixesEventBase + XFixesCursorNotify;
+ ev.subtype = XFixesDisplayCursorNotify;
+ ev.sequenceNumber = e->pClient->sequence;
+ ev.window = e->pWindow->drawable.id;
+ ev.cursorSerial = pCursor->serialNumber;
+ ev.timestamp = currentTime.milliseconds;
+ ev.name = pCursor->name;
+ WriteEventsToClient (e->pClient, 1, (xEvent *) &ev);
+ }
+ }
+ }
+ Wrap (cs, pScreen, DisplayCursor, backupProc);
+
+ return ret;
+}
+
+static Bool
+CursorCloseScreen (int index, ScreenPtr pScreen)
+{
+ CursorScreenPtr cs = GetCursorScreen (pScreen);
+ Bool ret;
+ CloseScreenProcPtr close_proc;
+ DisplayCursorProcPtr display_proc;
+
+ Unwrap (cs, pScreen, CloseScreen, close_proc);
+ Unwrap (cs, pScreen, DisplayCursor, display_proc);
+ deleteCursorHideCountsForScreen(pScreen);
+ ret = (*pScreen->CloseScreen) (index, pScreen);
+ xfree (cs);
+ return ret;
+}
+
+#define CursorAllEvents (XFixesDisplayCursorNotifyMask)
+
+static int
+XFixesSelectCursorInput (ClientPtr pClient,
+ WindowPtr pWindow,
+ CARD32 eventMask)
+{
+ CursorEventPtr *prev, e;
+ pointer val;
+ int rc;
+
+ for (prev = &cursorEvents; (e = *prev); prev = &e->next)
+ {
+ if (e->pClient == pClient &&
+ e->pWindow == pWindow)
+ {
+ break;
+ }
+ }
+ if (!eventMask)
+ {
+ if (e)
+ {
+ FreeResource (e->clientResource, 0);
+ }
+ return Success;
+ }
+ if (!e)
+ {
+ e = (CursorEventPtr) xalloc (sizeof (CursorEventRec));
+ if (!e)
+ return BadAlloc;
+
+ e->next = 0;
+ e->pClient = pClient;
+ e->pWindow = pWindow;
+ e->clientResource = FakeClientID(pClient->index);
+
+ /*
+ * Add a resource hanging from the window to
+ * catch window destroy
+ */
+ rc = dixLookupResourceByType( &val, pWindow->drawable.id,
+ CursorWindowType, serverClient,
+ DixGetAttrAccess);
+ if (rc != Success)
+ if (!AddResource (pWindow->drawable.id, CursorWindowType,
+ (pointer) pWindow))
+ {
+ xfree (e);
+ return BadAlloc;
+ }
+
+ if (!AddResource (e->clientResource, CursorClientType, (pointer) e))
+ return BadAlloc;
+
+ *prev = e;
+ }
+ e->eventMask = eventMask;
+ return Success;
+}
+
+int
+ProcXFixesSelectCursorInput (ClientPtr client)
+{
+ REQUEST (xXFixesSelectCursorInputReq);
+ WindowPtr pWin;
+ int rc;
+
+ REQUEST_SIZE_MATCH (xXFixesSelectCursorInputReq);
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ if (stuff->eventMask & ~CursorAllEvents)
+ {
+ client->errorValue = stuff->eventMask;
+ return( BadValue );
+ }
+ return XFixesSelectCursorInput (client, pWin, stuff->eventMask);
+}
+
+static int
+GetBit (unsigned char *line, int x)
+{
+ unsigned char mask;
+
+ if (screenInfo.bitmapBitOrder == LSBFirst)
+ mask = (1 << (x & 7));
+ else
+ mask = (0x80 >> (x & 7));
+ /* XXX assumes byte order is host byte order */
+ line += (x >> 3);
+ if (*line & mask)
+ return 1;
+ return 0;
+}
+
+int
+SProcXFixesSelectCursorInput (ClientPtr client)
+{
+ register int n;
+ REQUEST(xXFixesSelectCursorInputReq);
+
+ swaps(&stuff->length, n);
+ swapl(&stuff->window, n);
+ swapl(&stuff->eventMask, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+void
+SXFixesCursorNotifyEvent (xXFixesCursorNotifyEvent *from,
+ xXFixesCursorNotifyEvent *to)
+{
+ to->type = from->type;
+ cpswaps (from->sequenceNumber, to->sequenceNumber);
+ cpswapl (from->window, to->window);
+ cpswapl (from->cursorSerial, to->cursorSerial);
+ cpswapl (from->timestamp, to->timestamp);
+ cpswapl (from->name, to->name);
+}
+
+static void
+CopyCursorToImage (CursorPtr pCursor, CARD32 *image)
+{
+ int width = pCursor->bits->width;
+ int height = pCursor->bits->height;
+ int npixels = width * height;
+
+#ifdef ARGB_CURSOR
+ if (pCursor->bits->argb)
+ memcpy (image, pCursor->bits->argb, npixels * sizeof (CARD32));
+ else
+#endif
+ {
+ unsigned char *srcLine = pCursor->bits->source;
+ unsigned char *mskLine = pCursor->bits->mask;
+ int stride = BitmapBytePad (width);
+ int x, y;
+ CARD32 fg, bg;
+
+ fg = (0xff000000 |
+ ((pCursor->foreRed & 0xff00) << 8) |
+ (pCursor->foreGreen & 0xff00) |
+ (pCursor->foreBlue >> 8));
+ bg = (0xff000000 |
+ ((pCursor->backRed & 0xff00) << 8) |
+ (pCursor->backGreen & 0xff00) |
+ (pCursor->backBlue >> 8));
+ for (y = 0; y < height; y++)
+ {
+ for (x = 0; x < width; x++)
+ {
+ if (GetBit (mskLine, x))
+ {
+ if (GetBit (srcLine, x))
+ *image++ = fg;
+ else
+ *image++ = bg;
+ }
+ else
+ *image++ = 0;
+ }
+ srcLine += stride;
+ mskLine += stride;
+ }
+ }
+}
+
+int
+ProcXFixesGetCursorImage (ClientPtr client)
+{
+/* REQUEST(xXFixesGetCursorImageReq); */
+ xXFixesGetCursorImageReply *rep;
+ CursorPtr pCursor;
+ CARD32 *image;
+ int npixels, width, height, rc, x, y;
+
+ REQUEST_SIZE_MATCH(xXFixesGetCursorImageReq);
+ pCursor = CursorCurrent[PickPointer(client)->id];
+ if (!pCursor)
+ return BadCursor;
+ rc = XaceHook(XACE_RESOURCE_ACCESS, client, pCursor->id, RT_CURSOR,
+ pCursor, RT_NONE, NULL, DixReadAccess);
+ if (rc != Success)
+ return rc;
+ GetSpritePosition (PickPointer(client), &x, &y);
+ width = pCursor->bits->width;
+ height = pCursor->bits->height;
+ npixels = width * height;
+ rep = xalloc (sizeof (xXFixesGetCursorImageReply) +
+ npixels * sizeof (CARD32));
+ if (!rep)
+ return BadAlloc;
+
+ rep->type = X_Reply;
+ rep->sequenceNumber = client->sequence;
+ rep->length = npixels;
+ rep->width = width;
+ rep->height = height;
+ rep->x = x;
+ rep->y = y;
+ rep->xhot = pCursor->bits->xhot;
+ rep->yhot = pCursor->bits->yhot;
+ rep->cursorSerial = pCursor->serialNumber;
+
+ image = (CARD32 *) (rep + 1);
+ CopyCursorToImage (pCursor, image);
+ if (client->swapped)
+ {
+ int n;
+ swaps (&rep->sequenceNumber, n);
+ swapl (&rep->length, n);
+ swaps (&rep->x, n);
+ swaps (&rep->y, n);
+ swaps (&rep->width, n);
+ swaps (&rep->height, n);
+ swaps (&rep->xhot, n);
+ swaps (&rep->yhot, n);
+ swapl (&rep->cursorSerial, n);
+ SwapLongs (image, npixels);
+ }
+ WriteToClient(client, sizeof (xXFixesGetCursorImageReply) +
+ (npixels << 2), (char *) rep);
+ xfree (rep);
+ return client->noClientException;
+}
+
+int
+SProcXFixesGetCursorImage (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesGetCursorImageReq);
+ swaps (&stuff->length, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+int
+ProcXFixesSetCursorName (ClientPtr client)
+{
+ CursorPtr pCursor;
+ char *tchar;
+ REQUEST(xXFixesSetCursorNameReq);
+ Atom atom;
+
+ REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq);
+ VERIFY_CURSOR(pCursor, stuff->cursor, client, DixSetAttrAccess);
+ tchar = (char *) &stuff[1];
+ atom = MakeAtom (tchar, stuff->nbytes, TRUE);
+ if (atom == BAD_RESOURCE)
+ return BadAlloc;
+
+ pCursor->name = atom;
+ return(client->noClientException);
+}
+
+int
+SProcXFixesSetCursorName (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesSetCursorNameReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_AT_LEAST_SIZE(xXFixesSetCursorNameReq);
+ swapl (&stuff->cursor, n);
+ swaps (&stuff->nbytes, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+int
+ProcXFixesGetCursorName (ClientPtr client)
+{
+ CursorPtr pCursor;
+ xXFixesGetCursorNameReply reply;
+ REQUEST(xXFixesGetCursorNameReq);
+ const char *str;
+ int len;
+
+ REQUEST_SIZE_MATCH(xXFixesGetCursorNameReq);
+ VERIFY_CURSOR(pCursor, stuff->cursor, client, DixGetAttrAccess);
+ if (pCursor->name)
+ str = NameForAtom (pCursor->name);
+ else
+ str = "";
+ len = strlen (str);
+
+ reply.type = X_Reply;
+ reply.length = bytes_to_int32(len);
+ reply.sequenceNumber = client->sequence;
+ reply.atom = pCursor->name;
+ reply.nbytes = len;
+ if (client->swapped)
+ {
+ int n;
+ swaps (&reply.sequenceNumber, n);
+ swapl (&reply.length, n);
+ swapl (&reply.atom, n);
+ swaps (&reply.nbytes, n);
+ }
+ WriteReplyToClient(client, sizeof(xXFixesGetCursorNameReply), &reply);
+ WriteToClient(client, len, str);
+
+ return(client->noClientException);
+}
+
+int
+SProcXFixesGetCursorName (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesGetCursorNameReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xXFixesGetCursorNameReq);
+ swapl (&stuff->cursor, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+int
+ProcXFixesGetCursorImageAndName (ClientPtr client)
+{
+/* REQUEST(xXFixesGetCursorImageAndNameReq); */
+ xXFixesGetCursorImageAndNameReply *rep;
+ CursorPtr pCursor;
+ CARD32 *image;
+ int npixels;
+ const char *name;
+ int nbytes, nbytesRound;
+ int width, height;
+ int rc, x, y;
+
+ REQUEST_SIZE_MATCH(xXFixesGetCursorImageAndNameReq);
+ pCursor = CursorCurrent[PickPointer(client)->id];
+ if (!pCursor)
+ return BadCursor;
+ rc = XaceHook(XACE_RESOURCE_ACCESS, client, pCursor->id, RT_CURSOR,
+ pCursor, RT_NONE, NULL, DixReadAccess|DixGetAttrAccess);
+ if (rc != Success)
+ return rc;
+ GetSpritePosition (PickPointer(client), &x, &y);
+ width = pCursor->bits->width;
+ height = pCursor->bits->height;
+ npixels = width * height;
+ name = pCursor->name ? NameForAtom (pCursor->name) : "";
+ nbytes = strlen (name);
+ nbytesRound = pad_to_int32(nbytes);
+ rep = xalloc (sizeof (xXFixesGetCursorImageAndNameReply) +
+ npixels * sizeof (CARD32) + nbytesRound);
+ if (!rep)
+ return BadAlloc;
+
+ rep->type = X_Reply;
+ rep->sequenceNumber = client->sequence;
+ rep->length = npixels + bytes_to_int32(nbytesRound);
+ rep->width = width;
+ rep->height = height;
+ rep->x = x;
+ rep->y = y;
+ rep->xhot = pCursor->bits->xhot;
+ rep->yhot = pCursor->bits->yhot;
+ rep->cursorSerial = pCursor->serialNumber;
+ rep->cursorName = pCursor->name;
+ rep->nbytes = nbytes;
+
+ image = (CARD32 *) (rep + 1);
+ CopyCursorToImage (pCursor, image);
+ memcpy ((image + npixels), name, nbytes);
+ if (client->swapped)
+ {
+ int n;
+ swaps (&rep->sequenceNumber, n);
+ swapl (&rep->length, n);
+ swaps (&rep->x, n);
+ swaps (&rep->y, n);
+ swaps (&rep->width, n);
+ swaps (&rep->height, n);
+ swaps (&rep->xhot, n);
+ swaps (&rep->yhot, n);
+ swapl (&rep->cursorSerial, n);
+ swapl (&rep->cursorName, n);
+ swaps (&rep->nbytes, n);
+ SwapLongs (image, npixels);
+ }
+ WriteToClient(client, sizeof (xXFixesGetCursorImageAndNameReply) +
+ (npixels << 2) + nbytesRound, (char *) rep);
+ xfree (rep);
+ return client->noClientException;
+}
+
+int
+SProcXFixesGetCursorImageAndName (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesGetCursorImageAndNameReq);
+ swaps (&stuff->length, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+/*
+ * Find every cursor reference in the system, ask testCursor
+ * whether it should be replaced with a reference to pCursor.
+ */
+
+typedef Bool (*TestCursorFunc) (CursorPtr pOld, pointer closure);
+
+typedef struct {
+ RESTYPE type;
+ TestCursorFunc testCursor;
+ CursorPtr pNew;
+ pointer closure;
+} ReplaceCursorLookupRec, *ReplaceCursorLookupPtr;
+
+static const RESTYPE CursorRestypes[] = {
+ RT_WINDOW, RT_PASSIVEGRAB, RT_CURSOR
+};
+
+#define NUM_CURSOR_RESTYPES (sizeof (CursorRestypes) / sizeof (CursorRestypes[0]))
+
+static Bool
+ReplaceCursorLookup (pointer value, XID id, pointer closure)
+{
+ ReplaceCursorLookupPtr rcl = (ReplaceCursorLookupPtr) closure;
+ WindowPtr pWin;
+ GrabPtr pGrab;
+ CursorPtr pCursor = 0, *pCursorRef = 0;
+ XID cursor = 0;
+
+ switch (rcl->type) {
+ case RT_WINDOW:
+ pWin = (WindowPtr) value;
+ if (pWin->optional)
+ {
+ pCursorRef = &pWin->optional->cursor;
+ pCursor = *pCursorRef;
+ }
+ break;
+ case RT_PASSIVEGRAB:
+ pGrab = (GrabPtr) value;
+ pCursorRef = &pGrab->cursor;
+ pCursor = *pCursorRef;
+ break;
+ case RT_CURSOR:
+ pCursorRef = 0;
+ pCursor = (CursorPtr) value;
+ cursor = id;
+ break;
+ }
+ if (pCursor && pCursor != rcl->pNew)
+ {
+ if ((*rcl->testCursor) (pCursor, rcl->closure))
+ {
+ rcl->pNew->refcnt++;
+ /* either redirect reference or update resource database */
+ if (pCursorRef)
+ *pCursorRef = rcl->pNew;
+ else
+ ChangeResourceValue (id, RT_CURSOR, rcl->pNew);
+ FreeCursor (pCursor, cursor);
+ }
+ }
+ return FALSE; /* keep walking */
+}
+
+static void
+ReplaceCursor (CursorPtr pCursor,
+ TestCursorFunc testCursor,
+ pointer closure)
+{
+ int clientIndex;
+ int resIndex;
+ ReplaceCursorLookupRec rcl;
+
+ /*
+ * Cursors exist only in the resource database, windows and grabs.
+ * All of these are always pointed at by the resource database. Walk
+ * the whole thing looking for cursors
+ */
+ rcl.testCursor = testCursor;
+ rcl.pNew = pCursor;
+ rcl.closure = closure;
+
+ /* for each client */
+ for (clientIndex = 0; clientIndex < currentMaxClients; clientIndex++)
+ {
+ if (!clients[clientIndex])
+ continue;
+ for (resIndex = 0; resIndex < NUM_CURSOR_RESTYPES; resIndex++)
+ {
+ rcl.type = CursorRestypes[resIndex];
+ /*
+ * This function walks the entire client resource database
+ */
+ LookupClientResourceComplex (clients[clientIndex],
+ rcl.type,
+ ReplaceCursorLookup,
+ (pointer) &rcl);
+ }
+ }
+ /* this "knows" that WindowHasNewCursor doesn't depend on it's argument */
+ WindowHasNewCursor (WindowTable[0]);
+}
+
+static Bool
+TestForCursor (CursorPtr pCursor, pointer closure)
+{
+ return (pCursor == (CursorPtr) closure);
+}
+
+int
+ProcXFixesChangeCursor (ClientPtr client)
+{
+ CursorPtr pSource, pDestination;
+ REQUEST(xXFixesChangeCursorReq);
+
+ REQUEST_SIZE_MATCH(xXFixesChangeCursorReq);
+ VERIFY_CURSOR (pSource, stuff->source, client,
+ DixReadAccess|DixGetAttrAccess);
+ VERIFY_CURSOR (pDestination, stuff->destination, client,
+ DixWriteAccess|DixSetAttrAccess);
+
+ ReplaceCursor (pSource, TestForCursor, (pointer) pDestination);
+ return (client->noClientException);
+}
+
+int
+SProcXFixesChangeCursor (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesChangeCursorReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH(xXFixesChangeCursorReq);
+ swapl (&stuff->source, n);
+ swapl (&stuff->destination, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+static Bool
+TestForCursorName (CursorPtr pCursor, pointer closure)
+{
+ Atom *pName = closure;
+ return (pCursor->name == *pName);
+}
+
+int
+ProcXFixesChangeCursorByName (ClientPtr client)
+{
+ CursorPtr pSource;
+ Atom name;
+ char *tchar;
+ REQUEST(xXFixesChangeCursorByNameReq);
+
+ REQUEST_FIXED_SIZE(xXFixesChangeCursorByNameReq, stuff->nbytes);
+ VERIFY_CURSOR(pSource, stuff->source, client,
+ DixReadAccess|DixGetAttrAccess);
+ tchar = (char *) &stuff[1];
+ name = MakeAtom (tchar, stuff->nbytes, FALSE);
+ if (name)
+ ReplaceCursor (pSource, TestForCursorName, &name);
+ return (client->noClientException);
+}
+
+int
+SProcXFixesChangeCursorByName (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesChangeCursorByNameReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_AT_LEAST_SIZE (xXFixesChangeCursorByNameReq);
+ swapl (&stuff->source, n);
+ swaps (&stuff->nbytes, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+/*
+ * Routines for manipulating the per-screen hide counts list.
+ * This list indicates which clients have requested cursor hiding
+ * for that screen.
+ */
+
+/* Return the screen's hide-counts list element for the given client */
+static CursorHideCountPtr
+findCursorHideCount (ClientPtr pClient, ScreenPtr pScreen)
+{
+ CursorScreenPtr cs = GetCursorScreen(pScreen);
+ CursorHideCountPtr pChc;
+
+ for (pChc = cs->pCursorHideCounts; pChc != NULL; pChc = pChc->pNext) {
+ if (pChc->pClient == pClient) {
+ return pChc;
+ }
+ }
+
+ return NULL;
+}
+
+static int
+createCursorHideCount (ClientPtr pClient, ScreenPtr pScreen)
+{
+ CursorScreenPtr cs = GetCursorScreen(pScreen);
+ CursorHideCountPtr pChc;
+
+ pChc = (CursorHideCountPtr) xalloc(sizeof(CursorHideCountRec));
+ if (pChc == NULL) {
+ return BadAlloc;
+ }
+ pChc->pClient = pClient;
+ pChc->pScreen = pScreen;
+ pChc->hideCount = 1;
+ pChc->resource = FakeClientID(pClient->index);
+ pChc->pNext = cs->pCursorHideCounts;
+ cs->pCursorHideCounts = pChc;
+
+ /*
+ * Create a resource for this element so it can be deleted
+ * when the client goes away.
+ */
+ if (!AddResource (pChc->resource, CursorHideCountType,
+ (pointer) pChc)) {
+ xfree(pChc);
+ return BadAlloc;
+ }
+
+ return Success;
+}
+
+/*
+ * Delete the given hide-counts list element from its screen list.
+ */
+static void
+deleteCursorHideCount (CursorHideCountPtr pChcToDel, ScreenPtr pScreen)
+{
+ CursorScreenPtr cs = GetCursorScreen(pScreen);
+ CursorHideCountPtr pChc, pNext;
+ CursorHideCountPtr pChcLast = NULL;
+
+ pChc = cs->pCursorHideCounts;
+ while (pChc != NULL) {
+ pNext = pChc->pNext;
+ if (pChc == pChcToDel) {
+ xfree(pChc);
+ if (pChcLast == NULL) {
+ cs->pCursorHideCounts = pNext;
+ } else {
+ pChcLast->pNext = pNext;
+ }
+ return;
+ }
+ pChcLast = pChc;
+ pChc = pNext;
+ }
+}
+
+/*
+ * Delete all the hide-counts list elements for this screen.
+ */
+static void
+deleteCursorHideCountsForScreen (ScreenPtr pScreen)
+{
+ CursorScreenPtr cs = GetCursorScreen(pScreen);
+ CursorHideCountPtr pChc, pTmp;
+
+ pChc = cs->pCursorHideCounts;
+ while (pChc != NULL) {
+ pTmp = pChc->pNext;
+ FreeResource(pChc->resource, 0);
+ pChc = pTmp;
+ }
+ cs->pCursorHideCounts = NULL;
+}
+
+int
+ProcXFixesHideCursor (ClientPtr client)
+{
+ WindowPtr pWin;
+ CursorHideCountPtr pChc;
+ REQUEST(xXFixesHideCursorReq);
+ int ret;
+
+ REQUEST_SIZE_MATCH (xXFixesHideCursorReq);
+
+ ret = dixLookupResourceByType((pointer *)&pWin, stuff->window, RT_WINDOW,
+ client, DixGetAttrAccess);
+ if (ret != Success) {
+ client->errorValue = stuff->window;
+ return (ret == BadValue) ? BadWindow : ret;
+ }
+
+ /*
+ * Has client hidden the cursor before on this screen?
+ * If so, just increment the count.
+ */
+
+ pChc = findCursorHideCount(client, pWin->drawable.pScreen);
+ if (pChc != NULL) {
+ pChc->hideCount++;
+ return client->noClientException;
+ }
+
+ /*
+ * This is the first time this client has hid the cursor
+ * for this screen.
+ */
+ ret = XaceHook(XACE_SCREEN_ACCESS, client, pWin->drawable.pScreen,
+ DixHideAccess);
+ if (ret != Success)
+ return ret;
+
+ ret = createCursorHideCount(client, pWin->drawable.pScreen);
+
+ if (ret == Success) {
+ DeviceIntPtr dev;
+ for (dev = inputInfo.devices; dev; dev = dev->next)
+ {
+ if (IsMaster(dev) && IsPointerDevice(dev))
+ CursorDisplayCursor(dev, pWin->drawable.pScreen, CursorCurrent[dev->id]);
+ }
+ }
+
+ return ret;
+}
+
+int
+SProcXFixesHideCursor (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesHideCursorReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xXFixesHideCursorReq);
+ swapl (&stuff->window, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+int
+ProcXFixesShowCursor (ClientPtr client)
+{
+ WindowPtr pWin;
+ CursorHideCountPtr pChc;
+ int rc;
+ REQUEST(xXFixesShowCursorReq);
+
+ REQUEST_SIZE_MATCH (xXFixesShowCursorReq);
+
+ rc = dixLookupResourceByType((pointer *)&pWin, stuff->window, RT_WINDOW,
+ client, DixGetAttrAccess);
+ if (rc != Success) {
+ client->errorValue = stuff->window;
+ return (rc == BadValue) ? BadWindow : rc;
+ }
+
+ /*
+ * Has client hidden the cursor on this screen?
+ * If not, generate an error.
+ */
+ pChc = findCursorHideCount(client, pWin->drawable.pScreen);
+ if (pChc == NULL) {
+ return BadMatch;
+ }
+
+ rc = XaceHook(XACE_SCREEN_ACCESS, client, pWin->drawable.pScreen,
+ DixShowAccess);
+ if (rc != Success)
+ return rc;
+
+ pChc->hideCount--;
+ if (pChc->hideCount <= 0) {
+ FreeResource(pChc->resource, 0);
+ }
+
+ return (client->noClientException);
+}
+
+int
+SProcXFixesShowCursor (ClientPtr client)
+{
+ int n;
+ REQUEST(xXFixesShowCursorReq);
+
+ swaps (&stuff->length, n);
+ REQUEST_SIZE_MATCH (xXFixesShowCursorReq);
+ swapl (&stuff->window, n);
+ return (*ProcXFixesVector[stuff->xfixesReqType]) (client);
+}
+
+static int
+CursorFreeClient (pointer data, XID id)
+{
+ CursorEventPtr old = (CursorEventPtr) data;
+ CursorEventPtr *prev, e;
+
+ for (prev = &cursorEvents; (e = *prev); prev = &e->next)
+ {
+ if (e == old)
+ {
+ *prev = e->next;
+ xfree (e);
+ break;
+ }
+ }
+ return 1;
+}
+
+static int
+CursorFreeHideCount (pointer data, XID id)
+{
+ CursorHideCountPtr pChc = (CursorHideCountPtr) data;
+ ScreenPtr pScreen = pChc->pScreen;
+ DeviceIntPtr dev;
+
+ deleteCursorHideCount(pChc, pChc->pScreen);
+ for (dev = inputInfo.devices; dev; dev = dev->next)
+ {
+ if (IsMaster(dev) && IsPointerDevice(dev))
+ CursorDisplayCursor(dev, pScreen, CursorCurrent[dev->id]);
+ }
+
+ return 1;
+}
+
+static int
+CursorFreeWindow (pointer data, XID id)
+{
+ WindowPtr pWindow = (WindowPtr) data;
+ CursorEventPtr e, next;
+
+ for (e = cursorEvents; e; e = next)
+ {
+ next = e->next;
+ if (e->pWindow == pWindow)
+ {
+ FreeResource (e->clientResource, 0);
+ }
+ }
+ return 1;
+}
+
+static CursorPtr
+createInvisibleCursor (void)
+{
+ CursorPtr pCursor;
+ unsigned char *psrcbits, *pmaskbits;
+ CursorMetricRec cm;
+
+ psrcbits = (unsigned char *) xcalloc(4, 1);
+ pmaskbits = (unsigned char *) xcalloc(4, 1);
+ if (psrcbits == NULL || pmaskbits == NULL) {
+ return NULL;
+ }
+
+ cm.width = 1;
+ cm.height = 1;
+ cm.xhot = 0;
+ cm.yhot = 0;
+
+ AllocARGBCursor(psrcbits, pmaskbits,
+ NULL, &cm,
+ 0, 0, 0,
+ 0, 0, 0,
+ &pCursor, serverClient, (XID)0);
+
+ return pCursor;
+}
+
+Bool
+XFixesCursorInit (void)
+{
+ int i;
+
+ if (party_like_its_1989)
+ CursorVisible = EnableCursor;
+
+ for (i = 0; i < screenInfo.numScreens; i++)
+ {
+ ScreenPtr pScreen = screenInfo.screens[i];
+ CursorScreenPtr cs;
+
+ cs = (CursorScreenPtr) xalloc (sizeof (CursorScreenRec));
+ if (!cs)
+ return FALSE;
+ Wrap (cs, pScreen, CloseScreen, CursorCloseScreen);
+ Wrap (cs, pScreen, DisplayCursor, CursorDisplayCursor);
+ cs->pCursorHideCounts = NULL;
+ SetCursorScreen (pScreen, cs);
+ }
+ CursorClientType = CreateNewResourceType(CursorFreeClient);
+ CursorHideCountType = CreateNewResourceType(CursorFreeHideCount);
+ CursorWindowType = CreateNewResourceType(CursorFreeWindow);
+
+ if (pInvisibleCursor == NULL) {
+ pInvisibleCursor = createInvisibleCursor();
+ if (pInvisibleCursor == NULL) {
+ return BadAlloc;
+ }
+ }
+
+ return CursorClientType && CursorWindowType;
+}
+
diff --git a/xorg-server/xfixes/makefile b/xorg-server/xfixes/makefile new file mode 100644 index 000000000..73df36c4e --- /dev/null +++ b/xorg-server/xfixes/makefile @@ -0,0 +1,9 @@ +CSRCS = cursor.c \ + region.c \ + saveset.c \ + select.c \ + xfixes.c + +LIBRARY=libxfixes + + diff --git a/xorg-server/xkb/makefile b/xorg-server/xkb/makefile new file mode 100644 index 000000000..643ea4d50 --- /dev/null +++ b/xorg-server/xkb/makefile @@ -0,0 +1,44 @@ +DEFINES += HAVE_XKB_CONFIG_H + +DDX_SRCS = \ + ddxBeep.c \ + ddxCtrls.c \ + ddxFakeMtn.c \ + ddxLEDs.c \ + ddxLoad.c \ + ddxList.c \ + ddxDevBtn.c + +DIX_SRCS = \ + xkb.c \ + xkbUtils.c \ + xkbEvents.c \ + xkbAccessX.c \ + xkbSwap.c \ + xkbLEDs.c \ + xkbInit.c \ + xkbActions.c \ + xkbPrKeyEv.c + +# this should be replaced by a common library or something, ideally -d +XKBFILE_SRCS = \ + maprules.c \ + xkmread.c \ + xkbtext.c \ + xkbfmisc.c \ + xkbout.c + +X11_SRCS = \ + XKBMisc.c \ + XKBAlloc.c \ + XKBGAlloc.c \ + XKBMAlloc.c + +# ends up unused... +# XI_SRCS = xkbPrOtherEv.c + +CSRCS = $(DDX_SRCS) $(DIX_SRCS) $(XI_SRCS) $(XKBFILE_SRCS) \ + $(X11_SRCS) ddxVT.c ddxPrivate.c ddxKillSrv.c + +LIBRARY=libxkb + diff --git a/xorg-server/xkb/xkb.c b/xorg-server/xkb/xkb.c index 7abbeaaff..6fcb79cd1 100644 --- a/xorg-server/xkb/xkb.c +++ b/xorg-server/xkb/xkb.c @@ -1,6715 +1,6717 @@ -/************************************************************ -Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. - -Permission to use, copy, modify, and distribute this -software and its documentation for any purpose and without -fee is hereby granted, 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 Silicon Graphics not be -used in advertising or publicity pertaining to distribution -of the software without specific prior written permission. -Silicon Graphics makes no representation about the suitability -of this software for any purpose. It is provided "as is" -without any express or implied warranty. - -SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON -GRAPHICS 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_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <stdio.h> -#include <X11/X.h> -#include <X11/Xproto.h> -#include "misc.h" -#include "inputstr.h" -#define XKBSRV_NEED_FILE_FUNCS -#include <xkbsrv.h> -#include "extnsionst.h" -#include "xace.h" -#include "xkb.h" -#include "protocol-versions.h" - -#include <X11/extensions/XI.h> -#include <X11/extensions/XKMformat.h> - -int XkbEventBase; -static int XkbErrorBase; -int XkbReqCode; -int XkbKeyboardErrorCode; -CARD32 xkbDebugFlags = 0; -static CARD32 xkbDebugCtrls = 0; - -static RESTYPE RT_XKBCLIENT; - -/***====================================================================***/ - -#define CHK_DEVICE(dev, id, client, access_mode, lf) {\ - int why;\ - int rc = lf(&(dev), id, client, access_mode, &why);\ - if (rc != Success) {\ - client->errorValue = _XkbErrCode2(why, id);\ - return rc;\ - }\ -} - -#define CHK_KBD_DEVICE(dev, id, client, mode) \ - CHK_DEVICE(dev, id, client, mode, _XkbLookupKeyboard) -#define CHK_LED_DEVICE(dev, id, client, mode) \ - CHK_DEVICE(dev, id, client, mode, _XkbLookupLedDevice) -#define CHK_BELL_DEVICE(dev, id, client, mode) \ - CHK_DEVICE(dev, id, client, mode, _XkbLookupBellDevice) -#define CHK_ANY_DEVICE(dev, id, client, mode) \ - CHK_DEVICE(dev, id, client, mode, _XkbLookupAnyDevice) - -#define CHK_ATOM_ONLY2(a,ev,er) {\ - if (((a)==None)||(!ValidAtom((a)))) {\ - (ev)= (XID)(a);\ - return er;\ - }\ -} -#define CHK_ATOM_ONLY(a) \ - CHK_ATOM_ONLY2(a,client->errorValue,BadAtom) - -#define CHK_ATOM_OR_NONE3(a,ev,er,ret) {\ - if (((a)!=None)&&(!ValidAtom((a)))) {\ - (ev)= (XID)(a);\ - (er)= BadAtom;\ - return ret;\ - }\ -} -#define CHK_ATOM_OR_NONE2(a,ev,er) {\ - if (((a)!=None)&&(!ValidAtom((a)))) {\ - (ev)= (XID)(a);\ - return er;\ - }\ -} -#define CHK_ATOM_OR_NONE(a) \ - CHK_ATOM_OR_NONE2(a,client->errorValue,BadAtom) - -#define CHK_MASK_LEGAL3(err,mask,legal,ev,er,ret) {\ - if ((mask)&(~(legal))) { \ - (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\ - (er)= BadValue;\ - return ret;\ - }\ -} -#define CHK_MASK_LEGAL2(err,mask,legal,ev,er) {\ - if ((mask)&(~(legal))) { \ - (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\ - return er;\ - }\ -} -#define CHK_MASK_LEGAL(err,mask,legal) \ - CHK_MASK_LEGAL2(err,mask,legal,client->errorValue,BadValue) - -#define CHK_MASK_MATCH(err,affect,value) {\ - if ((value)&(~(affect))) { \ - client->errorValue= _XkbErrCode2((err),((value)&(~(affect))));\ - return BadMatch;\ - }\ -} -#define CHK_MASK_OVERLAP(err,m1,m2) {\ - if ((m1)&(m2)) { \ - client->errorValue= _XkbErrCode2((err),((m1)&(m2)));\ - return BadMatch;\ - }\ -} -#define CHK_KEY_RANGE2(err,first,num,x,ev,er) {\ - if (((unsigned)(first)+(num)-1)>(x)->max_key_code) {\ - (ev)=_XkbErrCode4(err,(first),(num),(x)->max_key_code);\ - return er;\ - }\ - else if ( (first)<(x)->min_key_code ) {\ - (ev)=_XkbErrCode3(err+1,(first),xkb->min_key_code);\ - return er;\ - }\ -} -#define CHK_KEY_RANGE(err,first,num,x) \ - CHK_KEY_RANGE2(err,first,num,x,client->errorValue,BadValue) - -#define CHK_REQ_KEY_RANGE2(err,first,num,r,ev,er) {\ - if (((unsigned)(first)+(num)-1)>(r)->maxKeyCode) {\ - (ev)=_XkbErrCode4(err,(first),(num),(r)->maxKeyCode);\ - return er;\ - }\ - else if ( (first)<(r)->minKeyCode ) {\ - (ev)=_XkbErrCode3(err+1,(first),(r)->minKeyCode);\ - return er;\ - }\ -} -#define CHK_REQ_KEY_RANGE(err,first,num,r) \ - CHK_REQ_KEY_RANGE2(err,first,num,r,client->errorValue,BadValue) - -/***====================================================================***/ - -int -ProcXkbUseExtension(ClientPtr client) -{ - REQUEST(xkbUseExtensionReq); - xkbUseExtensionReply rep; - register int n; - int supported; - - REQUEST_SIZE_MATCH(xkbUseExtensionReq); - if (stuff->wantedMajor != SERVER_XKB_MAJOR_VERSION) { - /* pre-release version 0.65 is compatible with 1.00 */ - supported= ((SERVER_XKB_MAJOR_VERSION==1)&& - (stuff->wantedMajor==0)&&(stuff->wantedMinor==65)); - } - else supported = 1; - - if ((supported) && (!(client->xkbClientFlags&_XkbClientInitialized))) { - client->xkbClientFlags= _XkbClientInitialized; - client->vMajor= stuff->wantedMajor; - client->vMinor= stuff->wantedMinor; - } - else if (xkbDebugFlags&0x1) { - ErrorF("[xkb] Rejecting client %d (0x%lx) (wants %d.%02d, have %d.%02d)\n", - client->index, - (long)client->clientAsMask, - stuff->wantedMajor,stuff->wantedMinor, - SERVER_XKB_MAJOR_VERSION,SERVER_XKB_MINOR_VERSION); - } - memset(&rep, 0, sizeof(xkbUseExtensionReply)); - rep.type = X_Reply; - rep.supported = supported; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.serverMajor = SERVER_XKB_MAJOR_VERSION; - rep.serverMinor = SERVER_XKB_MINOR_VERSION; - if ( client->swapped ) { - swaps(&rep.sequenceNumber, n); - swaps(&rep.serverMajor, n); - swaps(&rep.serverMinor, n); - } - WriteToClient(client,SIZEOF(xkbUseExtensionReply), (char *)&rep); - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbSelectEvents(ClientPtr client) -{ - unsigned legal; - DeviceIntPtr dev; - XkbInterestPtr masks; - REQUEST(xkbSelectEventsReq); - - REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixUseAccess); - - if (((stuff->affectWhich&XkbMapNotifyMask)!=0)&&(stuff->affectMap)) { - client->mapNotifyMask&= ~stuff->affectMap; - client->mapNotifyMask|= (stuff->affectMap&stuff->map); - } - if ((stuff->affectWhich&(~XkbMapNotifyMask))==0) - return client->noClientException; - - masks = XkbFindClientResource((DevicePtr)dev,client); - if (!masks){ - XID id = FakeClientID(client->index); - AddResource(id,RT_XKBCLIENT,dev); - masks= XkbAddClientResource((DevicePtr)dev,client,id); - } - if (masks) { - union { - CARD8 *c8; - CARD16 *c16; - CARD32 *c32; - } from,to; - register unsigned bit,ndx,maskLeft,dataLeft,size; - - from.c8= (CARD8 *)&stuff[1]; - dataLeft= (stuff->length*4)-SIZEOF(xkbSelectEventsReq); - maskLeft= (stuff->affectWhich&(~XkbMapNotifyMask)); - for (ndx=0,bit=1; (maskLeft!=0); ndx++, bit<<=1) { - if ((bit&maskLeft)==0) - continue; - maskLeft&= ~bit; - switch (ndx) { - case XkbNewKeyboardNotify: - to.c16= &client->newKeyboardNotifyMask; - legal= XkbAllNewKeyboardEventsMask; - size= 2; - break; - case XkbStateNotify: - to.c16= &masks->stateNotifyMask; - legal= XkbAllStateEventsMask; - size= 2; - break; - case XkbControlsNotify: - to.c32= &masks->ctrlsNotifyMask; - legal= XkbAllControlEventsMask; - size= 4; - break; - case XkbIndicatorStateNotify: - to.c32= &masks->iStateNotifyMask; - legal= XkbAllIndicatorEventsMask; - size= 4; - break; - case XkbIndicatorMapNotify: - to.c32= &masks->iMapNotifyMask; - legal= XkbAllIndicatorEventsMask; - size= 4; - break; - case XkbNamesNotify: - to.c16= &masks->namesNotifyMask; - legal= XkbAllNameEventsMask; - size= 2; - break; - case XkbCompatMapNotify: - to.c8= &masks->compatNotifyMask; - legal= XkbAllCompatMapEventsMask; - size= 1; - break; - case XkbBellNotify: - to.c8= &masks->bellNotifyMask; - legal= XkbAllBellEventsMask; - size= 1; - break; - case XkbActionMessage: - to.c8= &masks->actionMessageMask; - legal= XkbAllActionMessagesMask; - size= 1; - break; - case XkbAccessXNotify: - to.c16= &masks->accessXNotifyMask; - legal= XkbAllAccessXEventsMask; - size= 2; - break; - case XkbExtensionDeviceNotify: - to.c16= &masks->extDevNotifyMask; - legal= XkbAllExtensionDeviceEventsMask; - size= 2; - break; - default: - client->errorValue = _XkbErrCode2(33,bit); - return BadValue; - } - - if (stuff->clear&bit) { - if (size==2) to.c16[0]= 0; - else if (size==4) to.c32[0]= 0; - else to.c8[0]= 0; - } - else if (stuff->selectAll&bit) { - if (size==2) to.c16[0]= ~0; - else if (size==4) to.c32[0]= ~0; - else to.c8[0]= ~0; - } - else { - if (dataLeft<(size*2)) - return BadLength; - if (size==2) { - CHK_MASK_MATCH(ndx,from.c16[0],from.c16[1]); - CHK_MASK_LEGAL(ndx,from.c16[0],legal); - to.c16[0]&= ~from.c16[0]; - to.c16[0]|= (from.c16[0]&from.c16[1]); - } - else if (size==4) { - CHK_MASK_MATCH(ndx,from.c32[0],from.c32[1]); - CHK_MASK_LEGAL(ndx,from.c32[0],legal); - to.c32[0]&= ~from.c32[0]; - to.c32[0]|= (from.c32[0]&from.c32[1]); - } - else { - CHK_MASK_MATCH(ndx,from.c8[0],from.c8[1]); - CHK_MASK_LEGAL(ndx,from.c8[0],legal); - to.c8[0]&= ~from.c8[0]; - to.c8[0]|= (from.c8[0]&from.c8[1]); - size= 2; - } - from.c8+= (size*2); - dataLeft-= (size*2); - } - } - if (dataLeft>2) { - ErrorF("[xkb] Extra data (%d bytes) after SelectEvents\n",dataLeft); - return BadLength; - } - return client->noClientException; - } - return BadAlloc; -} - -/***====================================================================***/ -/** - * Ring a bell on the given device for the given client. - */ -static int -_XkbBell(ClientPtr client, DeviceIntPtr dev, WindowPtr pWin, - int bellClass, int bellID, int pitch, int duration, - int percent, int forceSound, int eventOnly, Atom name) -{ - int base; - pointer ctrl; - int oldPitch, oldDuration; - int newPercent; - - if (bellClass == KbdFeedbackClass) { - KbdFeedbackPtr k; - if (bellID==XkbDfltXIId) - k= dev->kbdfeed; - else { - for (k=dev->kbdfeed; k; k=k->next) { - if (k->ctrl.id == bellID) - break; - } - } - if (!k) { - client->errorValue = _XkbErrCode2(0x5,bellID); - return BadValue; - } - base = k->ctrl.bell; - ctrl = (pointer) &(k->ctrl); - oldPitch= k->ctrl.bell_pitch; - oldDuration= k->ctrl.bell_duration; - if (pitch!=0) { - if (pitch==-1) - k->ctrl.bell_pitch= defaultKeyboardControl.bell_pitch; - else k->ctrl.bell_pitch= pitch; - } - if (duration!=0) { - if (duration==-1) - k->ctrl.bell_duration= defaultKeyboardControl.bell_duration; - else k->ctrl.bell_duration= duration; - } - } - else if (bellClass == BellFeedbackClass) { - BellFeedbackPtr b; - if (bellID==XkbDfltXIId) - b= dev->bell; - else { - for (b=dev->bell; b; b=b->next) { - if (b->ctrl.id == bellID) - break; - } - } - if (!b) { - client->errorValue = _XkbErrCode2(0x6,bellID); - return BadValue; - } - base = b->ctrl.percent; - ctrl = (pointer) &(b->ctrl); - oldPitch= b->ctrl.pitch; - oldDuration= b->ctrl.duration; - if (pitch!=0) { - if (pitch==-1) - b->ctrl.pitch= defaultKeyboardControl.bell_pitch; - else b->ctrl.pitch= pitch; - } - if (duration!=0) { - if (duration==-1) - b->ctrl.duration= defaultKeyboardControl.bell_duration; - else b->ctrl.duration= duration; - } - } - else { - client->errorValue = _XkbErrCode2(0x7, bellClass); - return BadValue; - } - - newPercent = (base * percent)/100; - if (percent < 0) - newPercent = base + newPercent; - else newPercent = base - newPercent + percent; - - XkbHandleBell(forceSound, eventOnly, - dev, newPercent, ctrl, bellClass, - name, pWin, client); - if ((pitch!=0)||(duration!=0)) { - if (bellClass == KbdFeedbackClass) { - KbdFeedbackPtr k; - k= (KbdFeedbackPtr)ctrl; - if (pitch!=0) - k->ctrl.bell_pitch= oldPitch; - if (duration!=0) - k->ctrl.bell_duration= oldDuration; - } - else { - BellFeedbackPtr b; - b= (BellFeedbackPtr)ctrl; - if (pitch!=0) - b->ctrl.pitch= oldPitch; - if (duration!=0) - b->ctrl.duration= oldDuration; - } - } - - return Success; -} - -int -ProcXkbBell(ClientPtr client) -{ - REQUEST(xkbBellReq); - DeviceIntPtr dev; - WindowPtr pWin; - int rc; - - REQUEST_SIZE_MATCH(xkbBellReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_BELL_DEVICE(dev, stuff->deviceSpec, client, DixBellAccess); - CHK_ATOM_OR_NONE(stuff->name); - - /* device-independent checks request for sane values */ - if ((stuff->forceSound)&&(stuff->eventOnly)) { - client->errorValue=_XkbErrCode3(0x1,stuff->forceSound,stuff->eventOnly); - return BadMatch; - } - if (stuff->percent < -100 || stuff->percent > 100) { - client->errorValue = _XkbErrCode2(0x2,stuff->percent); - return BadValue; - } - if (stuff->duration<-1) { - client->errorValue = _XkbErrCode2(0x3,stuff->duration); - return BadValue; - } - if (stuff->pitch<-1) { - client->errorValue = _XkbErrCode2(0x4,stuff->pitch); - return BadValue; - } - - if (stuff->bellClass == XkbDfltXIClass) { - if (dev->kbdfeed!=NULL) - stuff->bellClass= KbdFeedbackClass; - else stuff->bellClass= BellFeedbackClass; - } - - if (stuff->window!=None) { - rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess); - if (rc != Success) { - client->errorValue= stuff->window; - return rc; - } - } - else pWin= NULL; - - /* Client wants to ring a bell on the core keyboard? - Ring the bell on the core keyboard (which does nothing, but if that - fails the client is screwed anyway), and then on all extension devices. - Fail if the core keyboard fails but not the extension devices. this - may cause some keyboards to ding and others to stay silent. Fix - your client to use explicit keyboards to avoid this. - - dev is the device the client requested. - */ - rc = _XkbBell(client, dev, pWin, stuff->bellClass, stuff->bellID, - stuff->pitch, stuff->duration, stuff->percent, - stuff->forceSound, stuff->eventOnly, stuff->name); - - if ((rc == Success) && ((stuff->deviceSpec == XkbUseCoreKbd) || - (stuff->deviceSpec == XkbUseCorePtr))) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixBellAccess); - if (rc == Success) - _XkbBell(client, other, pWin, stuff->bellClass, - stuff->bellID, stuff->pitch, stuff->duration, - stuff->percent, stuff->forceSound, - stuff->eventOnly, stuff->name); - } - } - rc = Success; /* reset to success, that's what we got for the VCK */ - } - - return rc; -} - -/***====================================================================***/ - -int -ProcXkbGetState(ClientPtr client) -{ - REQUEST(xkbGetStateReq); - DeviceIntPtr dev; - xkbGetStateReply rep; - XkbStateRec *xkb; - - REQUEST_SIZE_MATCH(xkbGetStateReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess); - - xkb= &dev->key->xkbInfo->state; - bzero(&rep,sizeof(xkbGetStateReply)); - rep.type= X_Reply; - rep.sequenceNumber= client->sequence; - rep.length = 0; - rep.deviceID = dev->id; - rep.mods = XkbStateFieldFromRec(xkb) & 0xff; - rep.baseMods = xkb->base_mods; - rep.lockedMods = xkb->locked_mods; - rep.latchedMods = xkb->latched_mods; - rep.group = xkb->group; - rep.baseGroup = xkb->base_group; - rep.latchedGroup = xkb->latched_group; - rep.lockedGroup = xkb->locked_group; - rep.compatState = xkb->compat_state; - rep.ptrBtnState = xkb->ptr_buttons; - if (client->swapped) { - register int n; - swaps(&rep.sequenceNumber,n); - swaps(&rep.ptrBtnState,n); - } - WriteToClient(client, SIZEOF(xkbGetStateReply), (char *)&rep); - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbLatchLockState(ClientPtr client) -{ - int status; - DeviceIntPtr dev, tmpd; - XkbStateRec oldState,*newState; - CARD16 changed; - xkbStateNotify sn; - XkbEventCauseRec cause; - - REQUEST(xkbLatchLockStateReq); - REQUEST_SIZE_MATCH(xkbLatchLockStateReq); - - if (!(client->xkbClientFlags & _XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess); - CHK_MASK_MATCH(0x01, stuff->affectModLocks, stuff->modLocks); - CHK_MASK_MATCH(0x01, stuff->affectModLatches, stuff->modLatches); - - status = Success; - - for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) { - if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) { - if (!tmpd->key || !tmpd->key->xkbInfo) - continue; - - oldState = tmpd->key->xkbInfo->state; - newState = &tmpd->key->xkbInfo->state; - if (stuff->affectModLocks) { - newState->locked_mods &= ~stuff->affectModLocks; - newState->locked_mods |= (stuff->affectModLocks & stuff->modLocks); - } - if (status == Success && stuff->lockGroup) - newState->locked_group = stuff->groupLock; - if (status == Success && stuff->affectModLatches) - status = XkbLatchModifiers(tmpd, stuff->affectModLatches, - stuff->modLatches); - if (status == Success && stuff->latchGroup) - status = XkbLatchGroup(tmpd, stuff->groupLatch); - - if (status != Success) - return status; - - XkbComputeDerivedState(tmpd->key->xkbInfo); - - changed = XkbStateChangedFlags(&oldState, newState); - if (changed) { - sn.keycode = 0; - sn.eventType = 0; - sn.requestMajor = XkbReqCode; - sn.requestMinor = X_kbLatchLockState; - sn.changed = changed; - XkbSendStateNotify(tmpd, &sn); - changed = XkbIndicatorsToUpdate(tmpd, changed, False); - if (changed) { - XkbSetCauseXkbReq(&cause, X_kbLatchLockState, client); - XkbUpdateIndicators(tmpd, changed, True, NULL, &cause); - } - } - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbGetControls(ClientPtr client) -{ - xkbGetControlsReply rep; - XkbControlsPtr xkb; - DeviceIntPtr dev; - register int n; - - REQUEST(xkbGetControlsReq); - REQUEST_SIZE_MATCH(xkbGetControlsReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - - xkb = dev->key->xkbInfo->desc->ctrls; - rep.type = X_Reply; - rep.length = bytes_to_int32(SIZEOF(xkbGetControlsReply)- - SIZEOF(xGenericReply)); - rep.sequenceNumber = client->sequence; - rep.deviceID = ((DeviceIntPtr)dev)->id; - rep.numGroups = xkb->num_groups; - rep.groupsWrap = xkb->groups_wrap; - rep.internalMods = xkb->internal.mask; - rep.ignoreLockMods = xkb->ignore_lock.mask; - rep.internalRealMods = xkb->internal.real_mods; - rep.ignoreLockRealMods = xkb->ignore_lock.real_mods; - rep.internalVMods = xkb->internal.vmods; - rep.ignoreLockVMods = xkb->ignore_lock.vmods; - rep.enabledCtrls = xkb->enabled_ctrls; - rep.repeatDelay = xkb->repeat_delay; - rep.repeatInterval = xkb->repeat_interval; - rep.slowKeysDelay = xkb->slow_keys_delay; - rep.debounceDelay = xkb->debounce_delay; - rep.mkDelay = xkb->mk_delay; - rep.mkInterval = xkb->mk_interval; - rep.mkTimeToMax = xkb->mk_time_to_max; - rep.mkMaxSpeed = xkb->mk_max_speed; - rep.mkCurve = xkb->mk_curve; - rep.mkDfltBtn = xkb->mk_dflt_btn; - rep.axTimeout = xkb->ax_timeout; - rep.axtCtrlsMask = xkb->axt_ctrls_mask; - rep.axtCtrlsValues = xkb->axt_ctrls_values; - rep.axtOptsMask = xkb->axt_opts_mask; - rep.axtOptsValues = xkb->axt_opts_values; - rep.axOptions = xkb->ax_options; - memcpy(rep.perKeyRepeat,xkb->per_key_repeat,XkbPerKeyBitArraySize); - if (client->swapped) { - swaps(&rep.sequenceNumber, n); - swapl(&rep.length,n); - swaps(&rep.internalVMods, n); - swaps(&rep.ignoreLockVMods, n); - swapl(&rep.enabledCtrls, n); - swaps(&rep.repeatDelay, n); - swaps(&rep.repeatInterval, n); - swaps(&rep.slowKeysDelay, n); - swaps(&rep.debounceDelay, n); - swaps(&rep.mkDelay, n); - swaps(&rep.mkInterval, n); - swaps(&rep.mkTimeToMax, n); - swaps(&rep.mkMaxSpeed, n); - swaps(&rep.mkCurve, n); - swaps(&rep.axTimeout, n); - swapl(&rep.axtCtrlsMask, n); - swapl(&rep.axtCtrlsValues, n); - swaps(&rep.axtOptsMask, n); - swaps(&rep.axtOptsValues, n); - swaps(&rep.axOptions, n); - } - WriteToClient(client, SIZEOF(xkbGetControlsReply), (char *)&rep); - return(client->noClientException); -} - -int -ProcXkbSetControls(ClientPtr client) -{ - DeviceIntPtr dev, tmpd; - XkbSrvInfoPtr xkbi; - XkbControlsPtr ctrl; - XkbControlsRec new,old; - xkbControlsNotify cn; - XkbEventCauseRec cause; - XkbSrvLedInfoPtr sli; - - REQUEST(xkbSetControlsReq); - REQUEST_SIZE_MATCH(xkbSetControlsReq); - - if (!(client->xkbClientFlags & _XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - CHK_MASK_LEGAL(0x01, stuff->changeCtrls, XkbAllControlsMask); - - for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) { - if (!tmpd->key || !tmpd->key->xkbInfo) - continue; - if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) { - xkbi = tmpd->key->xkbInfo; - ctrl = xkbi->desc->ctrls; - new = *ctrl; - XkbSetCauseXkbReq(&cause, X_kbSetControls, client); - - if (stuff->changeCtrls & XkbInternalModsMask) { - CHK_MASK_MATCH(0x02, stuff->affectInternalMods, - stuff->internalMods); - CHK_MASK_MATCH(0x03, stuff->affectInternalVMods, - stuff->internalVMods); - - new.internal.real_mods &= ~(stuff->affectInternalMods); - new.internal.real_mods |= (stuff->affectInternalMods & - stuff->internalMods); - new.internal.vmods &= ~(stuff->affectInternalVMods); - new.internal.vmods |= (stuff->affectInternalVMods & - stuff->internalVMods); - new.internal.mask = new.internal.real_mods | - XkbMaskForVMask(xkbi->desc, - new.internal.vmods); - } - - if (stuff->changeCtrls & XkbIgnoreLockModsMask) { - CHK_MASK_MATCH(0x4, stuff->affectIgnoreLockMods, - stuff->ignoreLockMods); - CHK_MASK_MATCH(0x5, stuff->affectIgnoreLockVMods, - stuff->ignoreLockVMods); - - new.ignore_lock.real_mods &= ~(stuff->affectIgnoreLockMods); - new.ignore_lock.real_mods |= (stuff->affectIgnoreLockMods & - stuff->ignoreLockMods); - new.ignore_lock.vmods &= ~(stuff->affectIgnoreLockVMods); - new.ignore_lock.vmods |= (stuff->affectIgnoreLockVMods & - stuff->ignoreLockVMods); - new.ignore_lock.mask = new.ignore_lock.real_mods | - XkbMaskForVMask(xkbi->desc, - new.ignore_lock.vmods); - } - - CHK_MASK_MATCH(0x06, stuff->affectEnabledCtrls, - stuff->enabledCtrls); - if (stuff->affectEnabledCtrls) { - CHK_MASK_LEGAL(0x07, stuff->affectEnabledCtrls, - XkbAllBooleanCtrlsMask); - - new.enabled_ctrls &= ~(stuff->affectEnabledCtrls); - new.enabled_ctrls |= (stuff->affectEnabledCtrls & - stuff->enabledCtrls); - } - - if (stuff->changeCtrls & XkbRepeatKeysMask) { - if (stuff->repeatDelay < 1 || stuff->repeatInterval < 1) { - client->errorValue = _XkbErrCode3(0x08, stuff->repeatDelay, - stuff->repeatInterval); - return BadValue; - } - - new.repeat_delay = stuff->repeatDelay; - new.repeat_interval = stuff->repeatInterval; - } - - if (stuff->changeCtrls & XkbSlowKeysMask) { - if (stuff->slowKeysDelay < 1) { - client->errorValue = _XkbErrCode2(0x09, - stuff->slowKeysDelay); - return BadValue; - } - - new.slow_keys_delay = stuff->slowKeysDelay; - } - - if (stuff->changeCtrls & XkbBounceKeysMask) { - if (stuff->debounceDelay < 1) { - client->errorValue = _XkbErrCode2(0x0A, - stuff->debounceDelay); - return BadValue; - } - - new.debounce_delay = stuff->debounceDelay; - } - - if (stuff->changeCtrls & XkbMouseKeysMask) { - if (stuff->mkDfltBtn > XkbMaxMouseKeysBtn) { - client->errorValue = _XkbErrCode2(0x0B, stuff->mkDfltBtn); - return BadValue; - } - - new.mk_dflt_btn = stuff->mkDfltBtn; - } - - if (stuff->changeCtrls & XkbMouseKeysAccelMask) { - if (stuff->mkDelay < 1 || stuff->mkInterval < 1 || - stuff->mkTimeToMax < 1 || stuff->mkMaxSpeed < 1 || - stuff->mkCurve < -1000) { - client->errorValue = _XkbErrCode2(0x0C,0); - return BadValue; - } - - new.mk_delay = stuff->mkDelay; - new.mk_interval = stuff->mkInterval; - new.mk_time_to_max = stuff->mkTimeToMax; - new.mk_max_speed = stuff->mkMaxSpeed; - new.mk_curve = stuff->mkCurve; - AccessXComputeCurveFactor(xkbi, &new); - } - - if (stuff->changeCtrls & XkbGroupsWrapMask) { - unsigned act, num; - - act = XkbOutOfRangeGroupAction(stuff->groupsWrap); - switch (act) { - case XkbRedirectIntoRange: - num = XkbOutOfRangeGroupNumber(stuff->groupsWrap); - if (num >= new.num_groups) { - client->errorValue = _XkbErrCode3(0x0D, new.num_groups, - num); - return BadValue; - } - case XkbWrapIntoRange: - case XkbClampIntoRange: - break; - default: - client->errorValue = _XkbErrCode2(0x0E, act); - return BadValue; - } - - new.groups_wrap= stuff->groupsWrap; - } - - CHK_MASK_LEGAL(0x0F, stuff->axOptions, XkbAX_AllOptionsMask); - if (stuff->changeCtrls & XkbAccessXKeysMask) { - new.ax_options = stuff->axOptions & XkbAX_AllOptionsMask; - } - else { - if (stuff->changeCtrls & XkbStickyKeysMask) { - new.ax_options &= ~(XkbAX_SKOptionsMask); - new.ax_options |= (stuff->axOptions & XkbAX_SKOptionsMask); - } - - if (stuff->changeCtrls & XkbAccessXFeedbackMask) { - new.ax_options &= ~(XkbAX_FBOptionsMask); - new.ax_options |= (stuff->axOptions & XkbAX_FBOptionsMask); - } - } - - if (stuff->changeCtrls & XkbAccessXTimeoutMask) { - if (stuff->axTimeout < 1) { - client->errorValue = _XkbErrCode2(0x10, stuff->axTimeout); - return BadValue; - } - CHK_MASK_MATCH(0x11, stuff->axtCtrlsMask, - stuff->axtCtrlsValues); - CHK_MASK_LEGAL(0x12, stuff->axtCtrlsMask, - XkbAllBooleanCtrlsMask); - CHK_MASK_MATCH(0x13, stuff->axtOptsMask, stuff->axtOptsValues); - CHK_MASK_LEGAL(0x14, stuff->axtOptsMask, XkbAX_AllOptionsMask); - new.ax_timeout = stuff->axTimeout; - new.axt_ctrls_mask = stuff->axtCtrlsMask; - new.axt_ctrls_values = (stuff->axtCtrlsValues & - stuff->axtCtrlsMask); - new.axt_opts_mask = stuff->axtOptsMask; - new.axt_opts_values = (stuff->axtOptsValues & - stuff->axtOptsMask); - } - - if (stuff->changeCtrls & XkbPerKeyRepeatMask) - memcpy(new.per_key_repeat, stuff->perKeyRepeat, - XkbPerKeyBitArraySize); - - old= *ctrl; - *ctrl= new; - XkbDDXChangeControls(tmpd, &old, ctrl); - - if (XkbComputeControlsNotify(tmpd, &old, ctrl, &cn, False)) { - cn.keycode = 0; - cn.eventType = 0; - cn.requestMajor = XkbReqCode; - cn.requestMinor = X_kbSetControls; - XkbSendControlsNotify(tmpd, &cn); - } - - sli = XkbFindSrvLedInfo(tmpd, XkbDfltXIClass, XkbDfltXIId, 0); - if (sli) - XkbUpdateIndicators(tmpd, sli->usesControls, True, NULL, - &cause); - - /* If sticky keys were disabled, clear all locks and latches */ - if ((old.enabled_ctrls & XkbStickyKeysMask) && - !(ctrl->enabled_ctrls & XkbStickyKeysMask)) - XkbClearAllLatchesAndLocks(tmpd, xkbi, True, &cause); - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -static int -XkbSizeKeyTypes(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - XkbKeyTypeRec *type; - unsigned i,len; - - len= 0; - if (((rep->present&XkbKeyTypesMask)==0)||(rep->nTypes<1)|| - (!xkb)||(!xkb->map)||(!xkb->map->types)) { - rep->present&= ~XkbKeyTypesMask; - rep->firstType= rep->nTypes= 0; - return 0; - } - type= &xkb->map->types[rep->firstType]; - for (i=0;i<rep->nTypes;i++,type++){ - len+= SIZEOF(xkbKeyTypeWireDesc); - if (type->map_count>0) { - len+= (type->map_count*SIZEOF(xkbKTMapEntryWireDesc)); - if (type->preserve) - len+= (type->map_count*SIZEOF(xkbModsWireDesc)); - } - } - return len; -} - -static char * -XkbWriteKeyTypes( XkbDescPtr xkb, - xkbGetMapReply * rep, - char * buf, - ClientPtr client) -{ - XkbKeyTypePtr type; - unsigned i; - xkbKeyTypeWireDesc *wire; - - type= &xkb->map->types[rep->firstType]; - for (i=0;i<rep->nTypes;i++,type++) { - register unsigned n; - wire= (xkbKeyTypeWireDesc *)buf; - wire->mask = type->mods.mask; - wire->realMods = type->mods.real_mods; - wire->virtualMods = type->mods.vmods; - wire->numLevels = type->num_levels; - wire->nMapEntries = type->map_count; - wire->preserve = (type->preserve!=NULL); - if (client->swapped) { - register int n; - swaps(&wire->virtualMods,n); - } - - buf= (char *)&wire[1]; - if (wire->nMapEntries>0) { - xkbKTMapEntryWireDesc * wire; - XkbKTMapEntryPtr entry; - wire= (xkbKTMapEntryWireDesc *)buf; - entry= type->map; - for (n=0;n<type->map_count;n++,wire++,entry++) { - wire->active= entry->active; - wire->mask= entry->mods.mask; - wire->level= entry->level; - wire->realMods= entry->mods.real_mods; - wire->virtualMods= entry->mods.vmods; - if (client->swapped) { - register int n; - swaps(&wire->virtualMods,n); - } - } - buf= (char *)wire; - if (type->preserve!=NULL) { - xkbModsWireDesc * pwire; - XkbModsPtr preserve; - pwire= (xkbModsWireDesc *)buf; - preserve= type->preserve; - for (n=0;n<type->map_count;n++,pwire++,preserve++) { - pwire->mask= preserve->mask; - pwire->realMods= preserve->real_mods; - pwire->virtualMods= preserve->vmods; - if (client->swapped) { - register int n; - swaps(&pwire->virtualMods,n); - } - } - buf= (char *)pwire; - } - } - } - return buf; -} - -static int -XkbSizeKeySyms(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - XkbSymMapPtr symMap; - unsigned i,len; - unsigned nSyms,nSymsThisKey; - - if (((rep->present&XkbKeySymsMask)==0)||(rep->nKeySyms<1)|| - (!xkb)||(!xkb->map)||(!xkb->map->key_sym_map)) { - rep->present&= ~XkbKeySymsMask; - rep->firstKeySym= rep->nKeySyms= 0; - rep->totalSyms= 0; - return 0; - } - len= rep->nKeySyms*SIZEOF(xkbSymMapWireDesc); - symMap = &xkb->map->key_sym_map[rep->firstKeySym]; - for (i=nSyms=0;i<rep->nKeySyms;i++,symMap++) { - if (symMap->offset!=0) { - nSymsThisKey= XkbNumGroups(symMap->group_info)*symMap->width; - nSyms+= nSymsThisKey; - } - } - len+= nSyms*4; - rep->totalSyms= nSyms; - return len; -} - -static int -XkbSizeVirtualMods(XkbDescPtr xkb,xkbGetMapReply *rep) -{ -register unsigned i,nMods,bit; - - if (((rep->present&XkbVirtualModsMask)==0)||(rep->virtualMods==0)|| - (!xkb)||(!xkb->server)) { - rep->present&= ~XkbVirtualModsMask; - rep->virtualMods= 0; - return 0; - } - for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) { - if (rep->virtualMods&bit) - nMods++; - } - return XkbPaddedSize(nMods); -} - -static char * -XkbWriteKeySyms(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,ClientPtr client) -{ -register KeySym * pSym; -XkbSymMapPtr symMap; -xkbSymMapWireDesc * outMap; -register unsigned i; - - symMap = &xkb->map->key_sym_map[rep->firstKeySym]; - for (i=0;i<rep->nKeySyms;i++,symMap++) { - outMap = (xkbSymMapWireDesc *)buf; - outMap->ktIndex[0] = symMap->kt_index[0]; - outMap->ktIndex[1] = symMap->kt_index[1]; - outMap->ktIndex[2] = symMap->kt_index[2]; - outMap->ktIndex[3] = symMap->kt_index[3]; - outMap->groupInfo = symMap->group_info; - outMap->width= symMap->width; - outMap->nSyms = symMap->width*XkbNumGroups(symMap->group_info); - buf= (char *)&outMap[1]; - if (outMap->nSyms==0) - continue; - - pSym = &xkb->map->syms[symMap->offset]; - memcpy((char *)buf,(char *)pSym,outMap->nSyms*4); - if (client->swapped) { - register int n,nSyms= outMap->nSyms; - swaps(&outMap->nSyms,n); - while (nSyms-->0) { - swapl(buf,n); - buf+= 4; - } - } - else buf+= outMap->nSyms*4; - } - return buf; -} - -static int -XkbSizeKeyActions(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - unsigned i,len,nActs; - register KeyCode firstKey; - - if (((rep->present&XkbKeyActionsMask)==0)||(rep->nKeyActs<1)|| - (!xkb)||(!xkb->server)||(!xkb->server->key_acts)) { - rep->present&= ~XkbKeyActionsMask; - rep->firstKeyAct= rep->nKeyActs= 0; - rep->totalActs= 0; - return 0; - } - firstKey= rep->firstKeyAct; - for (nActs=i=0;i<rep->nKeyActs;i++) { - if (xkb->server->key_acts[i+firstKey]!=0) - nActs+= XkbKeyNumActions(xkb,i+firstKey); - } - len= XkbPaddedSize(rep->nKeyActs)+(nActs*SIZEOF(xkbActionWireDesc)); - rep->totalActs= nActs; - return len; -} - -static char * -XkbWriteKeyActions(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf, - ClientPtr client) -{ - unsigned i; - CARD8 * numDesc; - XkbAnyAction * actDesc; - - numDesc = (CARD8 *)buf; - for (i=0;i<rep->nKeyActs;i++) { - if (xkb->server->key_acts[i+rep->firstKeyAct]==0) - numDesc[i] = 0; - else numDesc[i] = XkbKeyNumActions(xkb,(i+rep->firstKeyAct)); - } - buf+= XkbPaddedSize(rep->nKeyActs); - - actDesc = (XkbAnyAction *)buf; - for (i=0;i<rep->nKeyActs;i++) { - if (xkb->server->key_acts[i+rep->firstKeyAct]!=0) { - unsigned int num; - num = XkbKeyNumActions(xkb,(i+rep->firstKeyAct)); - memcpy((char *)actDesc, - (char*)XkbKeyActionsPtr(xkb,(i+rep->firstKeyAct)), - num*SIZEOF(xkbActionWireDesc)); - actDesc+= num; - } - } - buf = (char *)actDesc; - return buf; -} - -static int -XkbSizeKeyBehaviors(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - unsigned i,len,nBhvr; - XkbBehavior * bhv; - - if (((rep->present&XkbKeyBehaviorsMask)==0)||(rep->nKeyBehaviors<1)|| - (!xkb)||(!xkb->server)||(!xkb->server->behaviors)) { - rep->present&= ~XkbKeyBehaviorsMask; - rep->firstKeyBehavior= rep->nKeyBehaviors= 0; - rep->totalKeyBehaviors= 0; - return 0; - } - bhv= &xkb->server->behaviors[rep->firstKeyBehavior]; - for (nBhvr=i=0;i<rep->nKeyBehaviors;i++,bhv++) { - if (bhv->type!=XkbKB_Default) - nBhvr++; - } - len= nBhvr*SIZEOF(xkbBehaviorWireDesc); - rep->totalKeyBehaviors= nBhvr; - return len; -} - -static char * -XkbWriteKeyBehaviors(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf, - ClientPtr client) -{ - unsigned i; - xkbBehaviorWireDesc *wire; - XkbBehavior *pBhvr; - - wire = (xkbBehaviorWireDesc *)buf; - pBhvr= &xkb->server->behaviors[rep->firstKeyBehavior]; - for (i=0;i<rep->nKeyBehaviors;i++,pBhvr++) { - if (pBhvr->type!=XkbKB_Default) { - wire->key= i+rep->firstKeyBehavior; - wire->type= pBhvr->type; - wire->data= pBhvr->data; - wire++; - } - } - buf = (char *)wire; - return buf; -} - -static int -XkbSizeExplicit(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - unsigned i,len,nRtrn; - - if (((rep->present&XkbExplicitComponentsMask)==0)||(rep->nKeyExplicit<1)|| - (!xkb)||(!xkb->server)||(!xkb->server->explicit)) { - rep->present&= ~XkbExplicitComponentsMask; - rep->firstKeyExplicit= rep->nKeyExplicit= 0; - rep->totalKeyExplicit= 0; - return 0; - } - for (nRtrn=i=0;i<rep->nKeyExplicit;i++) { - if (xkb->server->explicit[i+rep->firstKeyExplicit]!=0) - nRtrn++; - } - rep->totalKeyExplicit= nRtrn; - len= XkbPaddedSize(nRtrn*2); /* two bytes per non-zero explicit component */ - return len; -} - -static char * -XkbWriteExplicit(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,ClientPtr client) -{ -unsigned i; -char * start; -unsigned char * pExp; - - start= buf; - pExp= &xkb->server->explicit[rep->firstKeyExplicit]; - for (i=0;i<rep->nKeyExplicit;i++,pExp++) { - if (*pExp!=0) { - *buf++= i+rep->firstKeyExplicit; - *buf++= *pExp; - } - } - i= XkbPaddedSize(buf-start)-(buf-start); /* pad to word boundary */ - return buf+i; -} - -static int -XkbSizeModifierMap(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - unsigned i,len,nRtrn; - - if (((rep->present&XkbModifierMapMask)==0)||(rep->nModMapKeys<1)|| - (!xkb)||(!xkb->map)||(!xkb->map->modmap)) { - rep->present&= ~XkbModifierMapMask; - rep->firstModMapKey= rep->nModMapKeys= 0; - rep->totalModMapKeys= 0; - return 0; - } - for (nRtrn=i=0;i<rep->nModMapKeys;i++) { - if (xkb->map->modmap[i+rep->firstModMapKey]!=0) - nRtrn++; - } - rep->totalModMapKeys= nRtrn; - len= XkbPaddedSize(nRtrn*2); /* two bytes per non-zero modmap component */ - return len; -} - -static char * -XkbWriteModifierMap(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf, - ClientPtr client) -{ -unsigned i; -char * start; -unsigned char * pMap; - - start= buf; - pMap= &xkb->map->modmap[rep->firstModMapKey]; - for (i=0;i<rep->nModMapKeys;i++,pMap++) { - if (*pMap!=0) { - *buf++= i+rep->firstModMapKey; - *buf++= *pMap; - } - } - i= XkbPaddedSize(buf-start)-(buf-start); /* pad to word boundary */ - return buf+i; -} - -static int -XkbSizeVirtualModMap(XkbDescPtr xkb,xkbGetMapReply *rep) -{ - unsigned i,len,nRtrn; - - if (((rep->present&XkbVirtualModMapMask)==0)||(rep->nVModMapKeys<1)|| - (!xkb)||(!xkb->server)||(!xkb->server->vmodmap)) { - rep->present&= ~XkbVirtualModMapMask; - rep->firstVModMapKey= rep->nVModMapKeys= 0; - rep->totalVModMapKeys= 0; - return 0; - } - for (nRtrn=i=0;i<rep->nVModMapKeys;i++) { - if (xkb->server->vmodmap[i+rep->firstVModMapKey]!=0) - nRtrn++; - } - rep->totalVModMapKeys= nRtrn; - len= nRtrn*SIZEOF(xkbVModMapWireDesc); - return len; -} - -static char * -XkbWriteVirtualModMap(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf, - ClientPtr client) -{ -unsigned i; -xkbVModMapWireDesc * wire; -unsigned short * pMap; - - wire= (xkbVModMapWireDesc *)buf; - pMap= &xkb->server->vmodmap[rep->firstVModMapKey]; - for (i=0;i<rep->nVModMapKeys;i++,pMap++) { - if (*pMap!=0) { - wire->key= i+rep->firstVModMapKey; - wire->vmods= *pMap; - wire++; - } - } - return (char *)wire; -} - -static Status -XkbComputeGetMapReplySize(XkbDescPtr xkb,xkbGetMapReply *rep) -{ -int len; - - rep->minKeyCode= xkb->min_key_code; - rep->maxKeyCode= xkb->max_key_code; - len= XkbSizeKeyTypes(xkb,rep); - len+= XkbSizeKeySyms(xkb,rep); - len+= XkbSizeKeyActions(xkb,rep); - len+= XkbSizeKeyBehaviors(xkb,rep); - len+= XkbSizeVirtualMods(xkb,rep); - len+= XkbSizeExplicit(xkb,rep); - len+= XkbSizeModifierMap(xkb,rep); - len+= XkbSizeVirtualModMap(xkb,rep); - rep->length+= (len/4); - return Success; -} - -static int -XkbSendMap(ClientPtr client,XkbDescPtr xkb,xkbGetMapReply *rep) -{ -unsigned i,len; -char *desc,*start; - - len= (rep->length*4)-(SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply)); - start= desc= xcalloc(1, len); - if (!start) - return BadAlloc; - if ( rep->nTypes>0 ) - desc = XkbWriteKeyTypes(xkb,rep,desc,client); - if ( rep->nKeySyms>0 ) - desc = XkbWriteKeySyms(xkb,rep,desc,client); - if ( rep->nKeyActs>0 ) - desc = XkbWriteKeyActions(xkb,rep,desc,client); - if ( rep->totalKeyBehaviors>0 ) - desc = XkbWriteKeyBehaviors(xkb,rep,desc,client); - if ( rep->virtualMods ) { - register int sz,bit; - for (i=sz=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) { - if (rep->virtualMods&bit) { - desc[sz++]= xkb->server->vmods[i]; - } - } - desc+= XkbPaddedSize(sz); - } - if ( rep->totalKeyExplicit>0 ) - desc= XkbWriteExplicit(xkb,rep,desc,client); - if ( rep->totalModMapKeys>0 ) - desc= XkbWriteModifierMap(xkb,rep,desc,client); - if ( rep->totalVModMapKeys>0 ) - desc= XkbWriteVirtualModMap(xkb,rep,desc,client); - if ((desc-start)!=(len)) { - ErrorF("[xkb] BOGUS LENGTH in write keyboard desc, expected %d, got %ld\n", - len, (unsigned long)(desc-start)); - } - if (client->swapped) { - register int n; - swaps(&rep->sequenceNumber,n); - swapl(&rep->length,n); - swaps(&rep->present,n); - swaps(&rep->totalSyms,n); - swaps(&rep->totalActs,n); - } - WriteToClient(client, (i=SIZEOF(xkbGetMapReply)), (char *)rep); - WriteToClient(client, len, start); - xfree((char *)start); - return client->noClientException; -} - -int -ProcXkbGetMap(ClientPtr client) -{ - DeviceIntPtr dev; - xkbGetMapReply rep; - XkbDescRec *xkb; - int n,status; - - REQUEST(xkbGetMapReq); - REQUEST_SIZE_MATCH(xkbGetMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - CHK_MASK_OVERLAP(0x01,stuff->full,stuff->partial); - CHK_MASK_LEGAL(0x02,stuff->full,XkbAllMapComponentsMask); - CHK_MASK_LEGAL(0x03,stuff->partial,XkbAllMapComponentsMask); - - xkb= dev->key->xkbInfo->desc; - bzero(&rep,sizeof(xkbGetMapReply)); - rep.type= X_Reply; - rep.sequenceNumber= client->sequence; - rep.length = (SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply))>>2; - rep.deviceID = dev->id; - rep.present = stuff->partial|stuff->full; - rep.minKeyCode = xkb->min_key_code; - rep.maxKeyCode = xkb->max_key_code; - if ( stuff->full&XkbKeyTypesMask ) { - rep.firstType = 0; - rep.nTypes = xkb->map->num_types; - } - else if (stuff->partial&XkbKeyTypesMask) { - if (((unsigned)stuff->firstType+stuff->nTypes)>xkb->map->num_types) { - client->errorValue = _XkbErrCode4(0x04,xkb->map->num_types, - stuff->firstType,stuff->nTypes); - return BadValue; - } - rep.firstType = stuff->firstType; - rep.nTypes = stuff->nTypes; - } - else rep.nTypes = 0; - rep.totalTypes = xkb->map->num_types; - - n= XkbNumKeys(xkb); - if ( stuff->full&XkbKeySymsMask ) { - rep.firstKeySym = xkb->min_key_code; - rep.nKeySyms = n; - } - else if (stuff->partial&XkbKeySymsMask) { - CHK_KEY_RANGE(0x05,stuff->firstKeySym,stuff->nKeySyms,xkb); - rep.firstKeySym = stuff->firstKeySym; - rep.nKeySyms = stuff->nKeySyms; - } - else rep.nKeySyms = 0; - rep.totalSyms= 0; - - if ( stuff->full&XkbKeyActionsMask ) { - rep.firstKeyAct= xkb->min_key_code; - rep.nKeyActs= n; - } - else if (stuff->partial&XkbKeyActionsMask) { - CHK_KEY_RANGE(0x07,stuff->firstKeyAct,stuff->nKeyActs,xkb); - rep.firstKeyAct= stuff->firstKeyAct; - rep.nKeyActs= stuff->nKeyActs; - } - else rep.nKeyActs= 0; - rep.totalActs= 0; - - if ( stuff->full&XkbKeyBehaviorsMask ) { - rep.firstKeyBehavior = xkb->min_key_code; - rep.nKeyBehaviors = n; - } - else if (stuff->partial&XkbKeyBehaviorsMask) { - CHK_KEY_RANGE(0x09,stuff->firstKeyBehavior,stuff->nKeyBehaviors,xkb); - rep.firstKeyBehavior= stuff->firstKeyBehavior; - rep.nKeyBehaviors= stuff->nKeyBehaviors; - } - else rep.nKeyBehaviors = 0; - rep.totalKeyBehaviors= 0; - - if (stuff->full&XkbVirtualModsMask) - rep.virtualMods= ~0; - else if (stuff->partial&XkbVirtualModsMask) - rep.virtualMods= stuff->virtualMods; - - if (stuff->full&XkbExplicitComponentsMask) { - rep.firstKeyExplicit= xkb->min_key_code; - rep.nKeyExplicit= n; - } - else if (stuff->partial&XkbExplicitComponentsMask) { - CHK_KEY_RANGE(0x0B,stuff->firstKeyExplicit,stuff->nKeyExplicit,xkb); - rep.firstKeyExplicit= stuff->firstKeyExplicit; - rep.nKeyExplicit= stuff->nKeyExplicit; - } - else rep.nKeyExplicit = 0; - rep.totalKeyExplicit= 0; - - if (stuff->full&XkbModifierMapMask) { - rep.firstModMapKey= xkb->min_key_code; - rep.nModMapKeys= n; - } - else if (stuff->partial&XkbModifierMapMask) { - CHK_KEY_RANGE(0x0D,stuff->firstModMapKey,stuff->nModMapKeys,xkb); - rep.firstModMapKey= stuff->firstModMapKey; - rep.nModMapKeys= stuff->nModMapKeys; - } - else rep.nModMapKeys = 0; - rep.totalModMapKeys= 0; - - if (stuff->full&XkbVirtualModMapMask) { - rep.firstVModMapKey= xkb->min_key_code; - rep.nVModMapKeys= n; - } - else if (stuff->partial&XkbVirtualModMapMask) { - CHK_KEY_RANGE(0x0F,stuff->firstVModMapKey,stuff->nVModMapKeys,xkb); - rep.firstVModMapKey= stuff->firstVModMapKey; - rep.nVModMapKeys= stuff->nVModMapKeys; - } - else rep.nVModMapKeys = 0; - rep.totalVModMapKeys= 0; - - if ((status=XkbComputeGetMapReplySize(xkb,&rep))!=Success) - return status; - return XkbSendMap(client,xkb,&rep); -} - -/***====================================================================***/ - -static int -CheckKeyTypes( ClientPtr client, - XkbDescPtr xkb, - xkbSetMapReq * req, - xkbKeyTypeWireDesc **wireRtrn, - int * nMapsRtrn, - CARD8 * mapWidthRtrn) -{ -unsigned nMaps; -register unsigned i,n; -register CARD8 * map; -register xkbKeyTypeWireDesc *wire = *wireRtrn; - - if (req->firstType>((unsigned)xkb->map->num_types)) { - *nMapsRtrn = _XkbErrCode3(0x01,req->firstType,xkb->map->num_types); - return 0; - } - if (req->flags&XkbSetMapResizeTypes) { - nMaps = req->firstType+req->nTypes; - if (nMaps<XkbNumRequiredTypes) { /* canonical types must be there */ - *nMapsRtrn= _XkbErrCode4(0x02,req->firstType,req->nTypes,4); - return 0; - } - } - else if (req->present&XkbKeyTypesMask) { - nMaps = xkb->map->num_types; - if ((req->firstType+req->nTypes)>nMaps) { - *nMapsRtrn = req->firstType+req->nTypes; - return 0; - } - } - else { - *nMapsRtrn = xkb->map->num_types; - for (i=0;i<xkb->map->num_types;i++) { - mapWidthRtrn[i] = xkb->map->types[i].num_levels; - } - return 1; - } - - for (i=0;i<req->firstType;i++) { - mapWidthRtrn[i] = xkb->map->types[i].num_levels; - } - for (i=0;i<req->nTypes;i++) { - unsigned width; - if (client->swapped) { - register int s; - swaps(&wire->virtualMods,s); - } - n= i+req->firstType; - width= wire->numLevels; - if (width<1) { - *nMapsRtrn= _XkbErrCode3(0x04,n,width); - return 0; - } - else if ((n==XkbOneLevelIndex)&&(width!=1)) { /* must be width 1 */ - *nMapsRtrn= _XkbErrCode3(0x05,n,width); - return 0; - } - else if ((width!=2)&& - ((n==XkbTwoLevelIndex)||(n==XkbKeypadIndex)|| - (n==XkbAlphabeticIndex))) { - /* TWO_LEVEL, ALPHABETIC and KEYPAD must be width 2 */ - *nMapsRtrn= _XkbErrCode3(0x05,n,width); - return 0; - } - if (wire->nMapEntries>0) { - xkbKTSetMapEntryWireDesc * mapWire; - xkbModsWireDesc * preWire; - mapWire= (xkbKTSetMapEntryWireDesc *)&wire[1]; - preWire= (xkbModsWireDesc *)&mapWire[wire->nMapEntries]; - for (n=0;n<wire->nMapEntries;n++) { - if (client->swapped) { - register int s; - swaps(&mapWire[n].virtualMods,s); - } - if (mapWire[n].realMods&(~wire->realMods)) { - *nMapsRtrn= _XkbErrCode4(0x06,n,mapWire[n].realMods, - wire->realMods); - return 0; - } - if (mapWire[n].virtualMods&(~wire->virtualMods)) { - *nMapsRtrn= _XkbErrCode3(0x07,n,mapWire[n].virtualMods); - return 0; - } - if (mapWire[n].level>=wire->numLevels) { - *nMapsRtrn= _XkbErrCode4(0x08,n,wire->numLevels, - mapWire[n].level); - return 0; - } - if (wire->preserve) { - if (client->swapped) { - register int s; - swaps(&preWire[n].virtualMods,s); - } - if (preWire[n].realMods&(~mapWire[n].realMods)) { - *nMapsRtrn= _XkbErrCode4(0x09,n,preWire[n].realMods, - mapWire[n].realMods); - return 0; - } - if (preWire[n].virtualMods&(~mapWire[n].virtualMods)) { - *nMapsRtrn=_XkbErrCode3(0x0a,n,preWire[n].virtualMods); - return 0; - } - } - } - if (wire->preserve) - map= (CARD8 *)&preWire[wire->nMapEntries]; - else map= (CARD8 *)&mapWire[wire->nMapEntries]; - } - else map= (CARD8 *)&wire[1]; - mapWidthRtrn[i+req->firstType] = wire->numLevels; - wire= (xkbKeyTypeWireDesc *)map; - } - for (i=req->firstType+req->nTypes;i<nMaps;i++) { - mapWidthRtrn[i] = xkb->map->types[i].num_levels; - } - *nMapsRtrn = nMaps; - *wireRtrn = wire; - return 1; -} - -static int -CheckKeySyms( ClientPtr client, - XkbDescPtr xkb, - xkbSetMapReq * req, - int nTypes, - CARD8 * mapWidths, - CARD16 * symsPerKey, - xkbSymMapWireDesc ** wireRtrn, - int * errorRtrn) -{ -register unsigned i; -XkbSymMapPtr map; -xkbSymMapWireDesc* wire = *wireRtrn; - - if (!(XkbKeySymsMask&req->present)) - return 1; - CHK_REQ_KEY_RANGE2(0x11,req->firstKeySym,req->nKeySyms,req,(*errorRtrn),0); - map = &xkb->map->key_sym_map[xkb->min_key_code]; - for (i=xkb->min_key_code;i<(unsigned)req->firstKeySym;i++,map++) { - register int g,ng,w; - ng= XkbNumGroups(map->group_info); - for (w=g=0;g<ng;g++) { - if (map->kt_index[g]>=(unsigned)nTypes) { - *errorRtrn = _XkbErrCode4(0x13,i,g,map->kt_index[g]); - return 0; - } - if (mapWidths[map->kt_index[g]]>w) - w= mapWidths[map->kt_index[g]]; - } - symsPerKey[i] = w*ng; - } - for (i=0;i<req->nKeySyms;i++) { - KeySym *pSyms; - register unsigned nG; - if (client->swapped) { - swaps(&wire->nSyms,nG); - } - nG = XkbNumGroups(wire->groupInfo); - if (nG>XkbNumKbdGroups) { - *errorRtrn = _XkbErrCode3(0x14,i+req->firstKeySym,nG); - return 0; - } - if (nG>0) { - register int g,w; - for (g=w=0;g<nG;g++) { - if (wire->ktIndex[g]>=(unsigned)nTypes) { - *errorRtrn= _XkbErrCode4(0x15,i+req->firstKeySym,g, - wire->ktIndex[g]); - return 0; - } - if (mapWidths[wire->ktIndex[g]]>w) - w= mapWidths[wire->ktIndex[g]]; - } - if (wire->width!=w) { - *errorRtrn= _XkbErrCode3(0x16,i+req->firstKeySym,wire->width); - return 0; - } - w*= nG; - symsPerKey[i+req->firstKeySym] = w; - if (w!=wire->nSyms) { - *errorRtrn=_XkbErrCode4(0x16,i+req->firstKeySym,wire->nSyms,w); - return 0; - } - } - else if (wire->nSyms!=0) { - *errorRtrn = _XkbErrCode3(0x17,i+req->firstKeySym,wire->nSyms); - return 0; - } - pSyms = (KeySym *)&wire[1]; - wire = (xkbSymMapWireDesc *)&pSyms[wire->nSyms]; - } - - map = &xkb->map->key_sym_map[i]; - for (;i<=(unsigned)xkb->max_key_code;i++,map++) { - register int g,nG,w; - nG= XkbKeyNumGroups(xkb,i); - for (w=g=0;g<nG;g++) { - if (map->kt_index[g]>=(unsigned)nTypes) { - *errorRtrn = _XkbErrCode4(0x18,i,g,map->kt_index[g]); - return 0; - } - if (mapWidths[map->kt_index[g]]>w) - w= mapWidths[map->kt_index[g]]; - } - symsPerKey[i] = w*nG; - } - *wireRtrn = wire; - return 1; -} - -static int -CheckKeyActions( XkbDescPtr xkb, - xkbSetMapReq * req, - int nTypes, - CARD8 * mapWidths, - CARD16 * symsPerKey, - CARD8 ** wireRtrn, - int * nActsRtrn) -{ -int nActs; -CARD8 * wire = *wireRtrn; -register unsigned i; - - if (!(XkbKeyActionsMask&req->present)) - return 1; - CHK_REQ_KEY_RANGE2(0x21,req->firstKeyAct,req->nKeyActs,req,(*nActsRtrn),0); - for (nActs=i=0;i<req->nKeyActs;i++) { - if (wire[0]!=0) { - if (wire[0]==symsPerKey[i+req->firstKeyAct]) - nActs+= wire[0]; - else { - *nActsRtrn= _XkbErrCode3(0x23,i+req->firstKeyAct,wire[0]); - return 0; - } - } - wire++; - } - if (req->nKeyActs%4) - wire+= 4-(req->nKeyActs%4); - *wireRtrn = (CARD8 *)(((XkbAnyAction *)wire)+nActs); - *nActsRtrn = nActs; - return 1; -} - -static int -CheckKeyBehaviors( XkbDescPtr xkb, - xkbSetMapReq * req, - xkbBehaviorWireDesc ** wireRtrn, - int * errorRtrn) -{ -register xkbBehaviorWireDesc * wire = *wireRtrn; -register XkbServerMapPtr server = xkb->server; -register unsigned i; -unsigned first,last; - - if (((req->present&XkbKeyBehaviorsMask)==0)||(req->nKeyBehaviors<1)) { - req->present&= ~XkbKeyBehaviorsMask; - req->nKeyBehaviors= 0; - return 1; - } - first= req->firstKeyBehavior; - last= req->firstKeyBehavior+req->nKeyBehaviors-1; - if (first<req->minKeyCode) { - *errorRtrn = _XkbErrCode3(0x31,first,req->minKeyCode); - return 0; - } - if (last>req->maxKeyCode) { - *errorRtrn = _XkbErrCode3(0x32,last,req->maxKeyCode); - return 0; - } - - for (i=0;i<req->totalKeyBehaviors;i++,wire++) { - if ((wire->key<first)||(wire->key>last)) { - *errorRtrn = _XkbErrCode4(0x33,first,last,wire->key); - return 0; - } - if ((wire->type&XkbKB_Permanent)&& - ((server->behaviors[wire->key].type!=wire->type)|| - (server->behaviors[wire->key].data!=wire->data))) { - *errorRtrn = _XkbErrCode3(0x33,wire->key,wire->type); - return 0; - } - if ((wire->type==XkbKB_RadioGroup)&& - ((wire->data&(~XkbKB_RGAllowNone))>XkbMaxRadioGroups)) { - *errorRtrn= _XkbErrCode4(0x34,wire->key,wire->data, - XkbMaxRadioGroups); - return 0; - } - if ((wire->type==XkbKB_Overlay1)||(wire->type==XkbKB_Overlay2)) { - CHK_KEY_RANGE2(0x35,wire->key,1,xkb,*errorRtrn,0); - } - } - *wireRtrn = wire; - return 1; -} - -static int -CheckVirtualMods( XkbDescRec * xkb, - xkbSetMapReq * req, - CARD8 ** wireRtrn, - int * errorRtrn) -{ -register CARD8 *wire = *wireRtrn; -register unsigned i,nMods,bit; - - if (((req->present&XkbVirtualModsMask)==0)||(req->virtualMods==0)) - return 1; - for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) { - if (req->virtualMods&bit) - nMods++; - } - *wireRtrn= (wire+XkbPaddedSize(nMods)); - return 1; -} - -static int -CheckKeyExplicit( XkbDescPtr xkb, - xkbSetMapReq * req, - CARD8 ** wireRtrn, - int * errorRtrn) -{ -register CARD8 * wire = *wireRtrn; -CARD8 * start; -register unsigned i; -int first,last; - - if (((req->present&XkbExplicitComponentsMask)==0)||(req->nKeyExplicit<1)) { - req->present&= ~XkbExplicitComponentsMask; - req->nKeyExplicit= 0; - return 1; - } - first= req->firstKeyExplicit; - last= first+req->nKeyExplicit-1; - if (first<req->minKeyCode) { - *errorRtrn = _XkbErrCode3(0x51,first,req->minKeyCode); - return 0; - } - if (last>req->maxKeyCode) { - *errorRtrn = _XkbErrCode3(0x52,last,req->maxKeyCode); - return 0; - } - start= wire; - for (i=0;i<req->totalKeyExplicit;i++,wire+=2) { - if ((wire[0]<first)||(wire[0]>last)) { - *errorRtrn = _XkbErrCode4(0x53,first,last,wire[0]); - return 0; - } - if (wire[1]&(~XkbAllExplicitMask)) { - *errorRtrn= _XkbErrCode3(0x52,~XkbAllExplicitMask,wire[1]); - return 0; - } - } - wire+= XkbPaddedSize(wire-start)-(wire-start); - *wireRtrn= wire; - return 1; -} - -static int -CheckModifierMap(XkbDescPtr xkb,xkbSetMapReq *req,CARD8 **wireRtrn,int *errRtrn) -{ -register CARD8 * wire = *wireRtrn; -CARD8 * start; -register unsigned i; -int first,last; - - if (((req->present&XkbModifierMapMask)==0)||(req->nModMapKeys<1)) { - req->present&= ~XkbModifierMapMask; - req->nModMapKeys= 0; - return 1; - } - first= req->firstModMapKey; - last= first+req->nModMapKeys-1; - if (first<req->minKeyCode) { - *errRtrn = _XkbErrCode3(0x61,first,req->minKeyCode); - return 0; - } - if (last>req->maxKeyCode) { - *errRtrn = _XkbErrCode3(0x62,last,req->maxKeyCode); - return 0; - } - start= wire; - for (i=0;i<req->totalModMapKeys;i++,wire+=2) { - if ((wire[0]<first)||(wire[0]>last)) { - *errRtrn = _XkbErrCode4(0x63,first,last,wire[0]); - return 0; - } - } - wire+= XkbPaddedSize(wire-start)-(wire-start); - *wireRtrn= wire; - return 1; -} - -static int -CheckVirtualModMap( XkbDescPtr xkb, - xkbSetMapReq *req, - xkbVModMapWireDesc **wireRtrn, - int *errRtrn) -{ -register xkbVModMapWireDesc * wire = *wireRtrn; -register unsigned i; -int first,last; - - if (((req->present&XkbVirtualModMapMask)==0)||(req->nVModMapKeys<1)) { - req->present&= ~XkbVirtualModMapMask; - req->nVModMapKeys= 0; - return 1; - } - first= req->firstVModMapKey; - last= first+req->nVModMapKeys-1; - if (first<req->minKeyCode) { - *errRtrn = _XkbErrCode3(0x71,first,req->minKeyCode); - return 0; - } - if (last>req->maxKeyCode) { - *errRtrn = _XkbErrCode3(0x72,last,req->maxKeyCode); - return 0; - } - for (i=0;i<req->totalVModMapKeys;i++,wire++) { - if ((wire->key<first)||(wire->key>last)) { - *errRtrn = _XkbErrCode4(0x73,first,last,wire->key); - return 0; - } - } - *wireRtrn= wire; - return 1; -} - -static char * -SetKeyTypes( XkbDescPtr xkb, - xkbSetMapReq * req, - xkbKeyTypeWireDesc * wire, - XkbChangesPtr changes) -{ -register unsigned i; -unsigned first,last; -CARD8 *map; - - if ((unsigned)(req->firstType+req->nTypes)>xkb->map->size_types) { - i= req->firstType+req->nTypes; - if (XkbAllocClientMap(xkb,XkbKeyTypesMask,i)!=Success) { - return NULL; - } - } - if ((unsigned)(req->firstType+req->nTypes)>xkb->map->num_types) - xkb->map->num_types= req->firstType+req->nTypes; - - for (i=0;i<req->nTypes;i++) { - XkbKeyTypePtr pOld; - register unsigned n; - - if (XkbResizeKeyType(xkb,i+req->firstType,wire->nMapEntries, - wire->preserve,wire->numLevels)!=Success) { - return NULL; - } - pOld = &xkb->map->types[i+req->firstType]; - map = (CARD8 *)&wire[1]; - - pOld->mods.real_mods = wire->realMods; - pOld->mods.vmods= wire->virtualMods; - pOld->num_levels = wire->numLevels; - pOld->map_count= wire->nMapEntries; - - pOld->mods.mask= pOld->mods.real_mods| - XkbMaskForVMask(xkb,pOld->mods.vmods); - - if (wire->nMapEntries) { - xkbKTSetMapEntryWireDesc *mapWire; - xkbModsWireDesc *preWire; - unsigned tmp; - mapWire= (xkbKTSetMapEntryWireDesc *)map; - preWire= (xkbModsWireDesc *)&mapWire[wire->nMapEntries]; - for (n=0;n<wire->nMapEntries;n++) { - pOld->map[n].active= 1; - pOld->map[n].mods.mask= mapWire[n].realMods; - pOld->map[n].mods.real_mods= mapWire[n].realMods; - pOld->map[n].mods.vmods= mapWire[n].virtualMods; - pOld->map[n].level= mapWire[n].level; - if (mapWire[n].virtualMods!=0) { - tmp= XkbMaskForVMask(xkb,mapWire[n].virtualMods); - pOld->map[n].active= (tmp!=0); - pOld->map[n].mods.mask|= tmp; - } - if (wire->preserve) { - pOld->preserve[n].real_mods= preWire[n].realMods; - pOld->preserve[n].vmods= preWire[n].virtualMods; - tmp= XkbMaskForVMask(xkb,preWire[n].virtualMods); - pOld->preserve[n].mask= preWire[n].realMods|tmp; - } - } - if (wire->preserve) - map= (CARD8 *)&preWire[wire->nMapEntries]; - else map= (CARD8 *)&mapWire[wire->nMapEntries]; - } - else map= (CARD8 *)&wire[1]; - wire = (xkbKeyTypeWireDesc *)map; - } - first= req->firstType; - last= first+req->nTypes-1; /* last changed type */ - if (changes->map.changed&XkbKeyTypesMask) { - int oldLast; - oldLast= changes->map.first_type+changes->map.num_types-1; - if (changes->map.first_type<first) - first= changes->map.first_type; - if (oldLast>last) - last= oldLast; - } - changes->map.changed|= XkbKeyTypesMask; - changes->map.first_type = first; - changes->map.num_types = (last-first)+1; - return (char *)wire; -} - -static char * -SetKeySyms( ClientPtr client, - XkbDescPtr xkb, - xkbSetMapReq * req, - xkbSymMapWireDesc * wire, - XkbChangesPtr changes, - DeviceIntPtr dev) -{ -register unsigned i,s; -XkbSymMapPtr oldMap; -KeySym * newSyms; -KeySym * pSyms; -unsigned first,last; - - oldMap = &xkb->map->key_sym_map[req->firstKeySym]; - for (i=0;i<req->nKeySyms;i++,oldMap++) { - pSyms = (KeySym *)&wire[1]; - if (wire->nSyms>0) { - newSyms = XkbResizeKeySyms(xkb,i+req->firstKeySym,wire->nSyms); - for (s=0;s<wire->nSyms;s++) { - newSyms[s]= pSyms[s]; - } - if (client->swapped) { - int n; - for (s=0;s<wire->nSyms;s++) { - swapl(&newSyms[s],n); - } - } - } - oldMap->kt_index[0] = wire->ktIndex[0]; - oldMap->kt_index[1] = wire->ktIndex[1]; - oldMap->kt_index[2] = wire->ktIndex[2]; - oldMap->kt_index[3] = wire->ktIndex[3]; - oldMap->group_info = wire->groupInfo; - oldMap->width = wire->width; - wire= (xkbSymMapWireDesc *)&pSyms[wire->nSyms]; - } - first= req->firstKeySym; - last= first+req->nKeySyms-1; - if (changes->map.changed&XkbKeySymsMask) { - int oldLast= (changes->map.first_key_sym+changes->map.num_key_syms-1); - if (changes->map.first_key_sym<first) - first= changes->map.first_key_sym; - if (oldLast>last) - last= oldLast; - } - changes->map.changed|= XkbKeySymsMask; - changes->map.first_key_sym = first; - changes->map.num_key_syms = (last-first+1); - - s= 0; - for (i=xkb->min_key_code;i<=xkb->max_key_code;i++) { - if (XkbKeyNumGroups(xkb,i)>s) - s= XkbKeyNumGroups(xkb,i); - } - if (s!=xkb->ctrls->num_groups) { - xkbControlsNotify cn; - XkbControlsRec old; - cn.keycode= 0; - cn.eventType= 0; - cn.requestMajor= XkbReqCode; - cn.requestMinor= X_kbSetMap; - old= *xkb->ctrls; - xkb->ctrls->num_groups= s; - if (XkbComputeControlsNotify(dev,&old,xkb->ctrls,&cn,False)) - XkbSendControlsNotify(dev,&cn); - } - return (char *)wire; -} - -static char * -SetKeyActions( XkbDescPtr xkb, - xkbSetMapReq * req, - CARD8 * wire, - XkbChangesPtr changes) -{ -register unsigned i,first,last; -CARD8 * nActs = wire; -XkbAction * newActs; - - wire+= XkbPaddedSize(req->nKeyActs); - for (i=0;i<req->nKeyActs;i++) { - if (nActs[i]==0) - xkb->server->key_acts[i+req->firstKeyAct]= 0; - else { - newActs= XkbResizeKeyActions(xkb,i+req->firstKeyAct,nActs[i]); - memcpy((char *)newActs,(char *)wire, - nActs[i]*SIZEOF(xkbActionWireDesc)); - wire+= nActs[i]*SIZEOF(xkbActionWireDesc); - } - } - first= req->firstKeyAct; - last= (first+req->nKeyActs-1); - if (changes->map.changed&XkbKeyActionsMask) { - int oldLast; - oldLast= changes->map.first_key_act+changes->map.num_key_acts-1; - if (changes->map.first_key_act<first) - first= changes->map.first_key_act; - if (oldLast>last) - last= oldLast; - } - changes->map.changed|= XkbKeyActionsMask; - changes->map.first_key_act= first; - changes->map.num_key_acts= (last-first+1); - return (char *)wire; -} - -static char * -SetKeyBehaviors( XkbSrvInfoPtr xkbi, - xkbSetMapReq *req, - xkbBehaviorWireDesc *wire, - XkbChangesPtr changes) -{ -register unsigned i; -int maxRG = -1; -XkbDescPtr xkb = xkbi->desc; -XkbServerMapPtr server = xkb->server; -unsigned first,last; - - first= req->firstKeyBehavior; - last= req->firstKeyBehavior+req->nKeyBehaviors-1; - bzero(&server->behaviors[first],req->nKeyBehaviors*sizeof(XkbBehavior)); - for (i=0;i<req->totalKeyBehaviors;i++) { - if ((server->behaviors[wire->key].type&XkbKB_Permanent)==0) { - server->behaviors[wire->key].type= wire->type; - server->behaviors[wire->key].data= wire->data; - if ((wire->type==XkbKB_RadioGroup)&&(((int)wire->data)>maxRG)) - maxRG= wire->data + 1; - } - wire++; - } - - if (maxRG>(int)xkbi->nRadioGroups) { - int sz = maxRG*sizeof(XkbRadioGroupRec); - if (xkbi->radioGroups) - xkbi->radioGroups= xrealloc(xkbi->radioGroups,sz); - else xkbi->radioGroups= xcalloc(1, sz); - if (xkbi->radioGroups) { - if (xkbi->nRadioGroups) - bzero(&xkbi->radioGroups[xkbi->nRadioGroups], - (maxRG-xkbi->nRadioGroups)*sizeof(XkbRadioGroupRec)); - xkbi->nRadioGroups= maxRG; - } - else xkbi->nRadioGroups= 0; - /* should compute members here */ - } - if (changes->map.changed&XkbKeyBehaviorsMask) { - unsigned oldLast; - oldLast= changes->map.first_key_behavior+ - changes->map.num_key_behaviors-1; - if (changes->map.first_key_behavior<req->firstKeyBehavior) - first= changes->map.first_key_behavior; - if (oldLast>last) - last= oldLast; - } - changes->map.changed|= XkbKeyBehaviorsMask; - changes->map.first_key_behavior = first; - changes->map.num_key_behaviors = (last-first+1); - return (char *)wire; -} - -static char * -SetVirtualMods(XkbSrvInfoPtr xkbi,xkbSetMapReq *req,CARD8 *wire, - XkbChangesPtr changes) -{ -register int i,bit,nMods; -XkbServerMapPtr srv = xkbi->desc->server; - - if (((req->present&XkbVirtualModsMask)==0)||(req->virtualMods==0)) - return (char *)wire; - for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) { - if (req->virtualMods&bit) { - if (srv->vmods[i]!=wire[nMods]) { - changes->map.changed|= XkbVirtualModsMask; - changes->map.vmods|= bit; - srv->vmods[i]= wire[nMods]; - } - nMods++; - } - } - return (char *)(wire+XkbPaddedSize(nMods)); -} - -static char * -SetKeyExplicit(XkbSrvInfoPtr xkbi,xkbSetMapReq *req,CARD8 *wire, - XkbChangesPtr changes) -{ -register unsigned i,first,last; -XkbServerMapPtr xkb = xkbi->desc->server; -CARD8 * start; - - start= wire; - first= req->firstKeyExplicit; - last= req->firstKeyExplicit+req->nKeyExplicit-1; - bzero(&xkb->explicit[first],req->nKeyExplicit); - for (i=0;i<req->totalKeyExplicit;i++,wire+= 2) { - xkb->explicit[wire[0]]= wire[1]; - } - if (first>0) { - if (changes->map.changed&XkbExplicitComponentsMask) { - int oldLast; - oldLast= changes->map.first_key_explicit+ - changes->map.num_key_explicit-1; - if (changes->map.first_key_explicit<first) - first= changes->map.first_key_explicit; - if (oldLast>last) - last= oldLast; - } - changes->map.first_key_explicit= first; - changes->map.num_key_explicit= (last-first)+1; - } - wire+= XkbPaddedSize(wire-start)-(wire-start); - return (char *)wire; -} - -static char * -SetModifierMap( XkbSrvInfoPtr xkbi, - xkbSetMapReq * req, - CARD8 * wire, - XkbChangesPtr changes) -{ -register unsigned i,first,last; -XkbClientMapPtr xkb = xkbi->desc->map; -CARD8 * start; - - start= wire; - first= req->firstModMapKey; - last= req->firstModMapKey+req->nModMapKeys-1; - bzero(&xkb->modmap[first],req->nModMapKeys); - for (i=0;i<req->totalModMapKeys;i++,wire+= 2) { - xkb->modmap[wire[0]]= wire[1]; - } - if (first>0) { - if (changes->map.changed&XkbModifierMapMask) { - int oldLast; - oldLast= changes->map.first_modmap_key+ - changes->map.num_modmap_keys-1; - if (changes->map.first_modmap_key<first) - first= changes->map.first_modmap_key; - if (oldLast>last) - last= oldLast; - } - changes->map.first_modmap_key= first; - changes->map.num_modmap_keys= (last-first)+1; - } - wire+= XkbPaddedSize(wire-start)-(wire-start); - return (char *)wire; -} - -static char * -SetVirtualModMap( XkbSrvInfoPtr xkbi, - xkbSetMapReq * req, - xkbVModMapWireDesc * wire, - XkbChangesPtr changes) -{ -register unsigned i,first,last; -XkbServerMapPtr srv = xkbi->desc->server; - - first= req->firstVModMapKey; - last= req->firstVModMapKey+req->nVModMapKeys-1; - bzero(&srv->vmodmap[first],req->nVModMapKeys*sizeof(unsigned short)); - for (i=0;i<req->totalVModMapKeys;i++,wire++) { - srv->vmodmap[wire->key]= wire->vmods; - } - if (first>0) { - if (changes->map.changed&XkbVirtualModMapMask) { - int oldLast; - oldLast= changes->map.first_vmodmap_key+ - changes->map.num_vmodmap_keys-1; - if (changes->map.first_vmodmap_key<first) - first= changes->map.first_vmodmap_key; - if (oldLast>last) - last= oldLast; - } - changes->map.first_vmodmap_key= first; - changes->map.num_vmodmap_keys= (last-first)+1; - } - return (char *)wire; -} - -/** - * Check if the given request can be applied to the given device but don't - * actually do anything.. - */ -static int -_XkbSetMapChecks(ClientPtr client, DeviceIntPtr dev, xkbSetMapReq *req, char* values) -{ - XkbSrvInfoPtr xkbi; - XkbDescPtr xkb; - int error; - int nTypes = 0, nActions; - CARD8 mapWidths[XkbMaxLegalKeyCode + 1]; - CARD16 symsPerKey[XkbMaxLegalKeyCode + 1]; - - xkbi= dev->key->xkbInfo; - xkb = xkbi->desc; - - if ((xkb->min_key_code != req->minKeyCode)|| - (xkb->max_key_code != req->maxKeyCode)) { - if (client->vMajor!=1) { /* pre 1.0 versions of Xlib have a bug */ - req->minKeyCode= xkb->min_key_code; - req->maxKeyCode= xkb->max_key_code; - } - else { - if (!XkbIsLegalKeycode(req->minKeyCode)) { - client->errorValue = _XkbErrCode3(2, req->minKeyCode, req->maxKeyCode); - return BadValue; - } - if (req->minKeyCode > req->maxKeyCode) { - client->errorValue = _XkbErrCode3(3, req->minKeyCode, req->maxKeyCode); - return BadMatch; - } - } - } - - if ((req->present & XkbKeyTypesMask) && - (!CheckKeyTypes(client,xkb,req,(xkbKeyTypeWireDesc **)&values, - &nTypes,mapWidths))) { - client->errorValue = nTypes; - return BadValue; - } - if ((req->present & XkbKeySymsMask) && - (!CheckKeySyms(client,xkb,req,nTypes,mapWidths,symsPerKey, - (xkbSymMapWireDesc **)&values,&error))) { - client->errorValue = error; - return BadValue; - } - - if ((req->present & XkbKeyActionsMask) && - (!CheckKeyActions(xkb,req,nTypes,mapWidths,symsPerKey, - (CARD8 **)&values,&nActions))) { - client->errorValue = nActions; - return BadValue; - } - - if ((req->present & XkbKeyBehaviorsMask) && - (!CheckKeyBehaviors(xkb,req,(xkbBehaviorWireDesc**)&values,&error))) { - client->errorValue = error; - return BadValue; - } - - if ((req->present & XkbVirtualModsMask) && - (!CheckVirtualMods(xkb,req,(CARD8 **)&values,&error))) { - client->errorValue= error; - return BadValue; - } - if ((req->present&XkbExplicitComponentsMask) && - (!CheckKeyExplicit(xkb,req,(CARD8 **)&values,&error))) { - client->errorValue= error; - return BadValue; - } - if ((req->present&XkbModifierMapMask) && - (!CheckModifierMap(xkb,req,(CARD8 **)&values,&error))) { - client->errorValue= error; - return BadValue; - } - if ((req->present&XkbVirtualModMapMask) && - (!CheckVirtualModMap(xkb,req,(xkbVModMapWireDesc **)&values,&error))) { - client->errorValue= error; - return BadValue; - } - - if (((values-((char *)req))/4)!= req->length) { - ErrorF("[xkb] Internal error! Bad length in XkbSetMap (after check)\n"); - client->errorValue = values-((char *)&req[1]); - return BadLength; - } - - return Success; -} - -/** - * Apply the given request on the given device. - */ -static int -_XkbSetMap(ClientPtr client, DeviceIntPtr dev, xkbSetMapReq *req, char *values) -{ - XkbEventCauseRec cause; - XkbChangesRec change; - Bool sentNKN; - XkbSrvInfoPtr xkbi; - XkbDescPtr xkb; - - xkbi= dev->key->xkbInfo; - xkb = xkbi->desc; - - XkbSetCauseXkbReq(&cause,X_kbSetMap,client); - bzero(&change, sizeof(change)); - sentNKN = False; - if ((xkb->min_key_code!=req->minKeyCode)|| - (xkb->max_key_code!=req->maxKeyCode)) { - Status status; - xkbNewKeyboardNotify nkn; - nkn.deviceID = nkn.oldDeviceID = dev->id; - nkn.oldMinKeyCode = xkb->min_key_code; - nkn.oldMaxKeyCode = xkb->max_key_code; - status= XkbChangeKeycodeRange(xkb, req->minKeyCode, - req->maxKeyCode, &change); - if (status != Success) - return status; /* oh-oh. what about the other keyboards? */ - nkn.minKeyCode = xkb->min_key_code; - nkn.maxKeyCode = xkb->max_key_code; - nkn.requestMajor = XkbReqCode; - nkn.requestMinor = X_kbSetMap; - nkn.changed = XkbNKN_KeycodesMask; - XkbSendNewKeyboardNotify(dev,&nkn); - sentNKN = True; - } - - if (req->present&XkbKeyTypesMask) { - values = SetKeyTypes(xkb,req,(xkbKeyTypeWireDesc *)values,&change); - if (!values) goto allocFailure; - } - if (req->present&XkbKeySymsMask) { - values = SetKeySyms(client,xkb,req,(xkbSymMapWireDesc *)values,&change,dev); - if (!values) goto allocFailure; - } - if (req->present&XkbKeyActionsMask) { - values = SetKeyActions(xkb,req,(CARD8 *)values,&change); - if (!values) goto allocFailure; - } - if (req->present&XkbKeyBehaviorsMask) { - values= SetKeyBehaviors(xkbi,req,(xkbBehaviorWireDesc *)values,&change); - if (!values) goto allocFailure; - } - if (req->present&XkbVirtualModsMask) - values= SetVirtualMods(xkbi,req,(CARD8 *)values,&change); - if (req->present&XkbExplicitComponentsMask) - values= SetKeyExplicit(xkbi,req,(CARD8 *)values,&change); - if (req->present&XkbModifierMapMask) - values= SetModifierMap(xkbi,req,(CARD8 *)values,&change); - if (req->present&XkbVirtualModMapMask) - values= SetVirtualModMap(xkbi,req,(xkbVModMapWireDesc *)values,&change); - if (((values-((char *)req))/4)!=req->length) { - ErrorF("[xkb] Internal error! Bad length in XkbSetMap (after set)\n"); - client->errorValue = values-((char *)&req[1]); - return BadLength; - } - if (req->flags&XkbSetMapRecomputeActions) { - KeyCode first,last,firstMM,lastMM; - if (change.map.num_key_syms>0) { - first= change.map.first_key_sym; - last= first+change.map.num_key_syms-1; - } - else first= last= 0; - if (change.map.num_modmap_keys>0) { - firstMM= change.map.first_modmap_key; - lastMM= first+change.map.num_modmap_keys-1; - } - else firstMM= lastMM= 0; - if ((last>0) && (lastMM>0)) { - if (firstMM<first) - first= firstMM; - if (lastMM>last) - last= lastMM; - } - else if (lastMM>0) { - first= firstMM; - last= lastMM; - } - if (last>0) { - unsigned check= 0; - XkbUpdateActions(dev,first,(last-first+1),&change,&check,&cause); - if (check) - XkbCheckSecondaryEffects(xkbi,check,&change,&cause); - } - } - if (!sentNKN) - XkbSendNotification(dev,&change,&cause); - - return Success; -allocFailure: - return BadAlloc; -} - - -int -ProcXkbSetMap(ClientPtr client) -{ - DeviceIntPtr dev; - char * tmp; - int rc; - - REQUEST(xkbSetMapReq); - REQUEST_AT_LEAST_SIZE(xkbSetMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - CHK_MASK_LEGAL(0x01,stuff->present,XkbAllMapComponentsMask); - - tmp = (char *)&stuff[1]; - - /* Check if we can to the SetMap on the requested device. If this - succeeds, do the same thing for all extension devices (if needed). - If any of them fails, fail. */ - rc = _XkbSetMapChecks(client, dev, stuff, tmp); - - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - rc = _XkbSetMapChecks(client, other, stuff, tmp); - if (rc != Success) - return rc; - } - } - } - } - - /* We know now that we will succed with the SetMap. In theory anyway. */ - rc = _XkbSetMap(client, dev, stuff, tmp); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - _XkbSetMap(client, other, stuff, tmp); - /* ignore rc. if the SetMap failed although the check above - reported true there isn't much we can do. we still need to - set all other devices, hoping that at least they stay in - sync. */ - } - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -static Status -XkbComputeGetCompatMapReplySize( XkbCompatMapPtr compat, - xkbGetCompatMapReply * rep) -{ -unsigned size,nGroups; - - nGroups= 0; - if (rep->groups!=0) { - register int i,bit; - for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) { - if (rep->groups&bit) - nGroups++; - } - } - size= nGroups*SIZEOF(xkbModsWireDesc); - size+= (rep->nSI*SIZEOF(xkbSymInterpretWireDesc)); - rep->length= size/4; - return Success; -} - -static int -XkbSendCompatMap( ClientPtr client, - XkbCompatMapPtr compat, - xkbGetCompatMapReply * rep) -{ -char * data; -int size; - - size= rep->length*4; - if (size>0) { - data = xalloc(size); - if (data) { - register unsigned i,bit; - xkbModsWireDesc * grp; - XkbSymInterpretPtr sym= &compat->sym_interpret[rep->firstSI]; - xkbSymInterpretWireDesc *wire = (xkbSymInterpretWireDesc *)data; - for (i=0;i<rep->nSI;i++,sym++,wire++) { - wire->sym= sym->sym; - wire->mods= sym->mods; - wire->match= sym->match; - wire->virtualMod= sym->virtual_mod; - wire->flags= sym->flags; - memcpy((char*)&wire->act,(char*)&sym->act,sz_xkbActionWireDesc); - if (client->swapped) { - register int n; - swapl(&wire->sym,n); - } - } - if (rep->groups) { - grp = (xkbModsWireDesc *)wire; - for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) { - if (rep->groups&bit) { - grp->mask= compat->groups[i].mask; - grp->realMods= compat->groups[i].real_mods; - grp->virtualMods= compat->groups[i].vmods; - if (client->swapped) { - register int n; - swaps(&grp->virtualMods,n); - } - grp++; - } - } - wire= (xkbSymInterpretWireDesc*)grp; - } - } - else return BadAlloc; - } - else data= NULL; - - if (client->swapped) { - register int n; - swaps(&rep->sequenceNumber,n); - swapl(&rep->length,n); - swaps(&rep->firstSI,n); - swaps(&rep->nSI,n); - swaps(&rep->nTotalSI,n); - } - - WriteToClient(client, SIZEOF(xkbGetCompatMapReply), (char *)rep); - if (data) { - WriteToClient(client, size, data); - xfree((char *)data); - } - return client->noClientException; -} - -int -ProcXkbGetCompatMap(ClientPtr client) -{ - xkbGetCompatMapReply rep; - DeviceIntPtr dev; - XkbDescPtr xkb; - XkbCompatMapPtr compat; - - REQUEST(xkbGetCompatMapReq); - REQUEST_SIZE_MATCH(xkbGetCompatMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - - xkb = dev->key->xkbInfo->desc; - compat= xkb->compat; - - rep.type = X_Reply; - rep.deviceID = dev->id; - rep.sequenceNumber = client->sequence; - rep.length = 0; - rep.firstSI = stuff->firstSI; - rep.nSI = stuff->nSI; - if (stuff->getAllSI) { - rep.firstSI = 0; - rep.nSI = compat->num_si; - } - else if ((((unsigned)stuff->nSI)>0)&& - ((unsigned)(stuff->firstSI+stuff->nSI-1)>=compat->num_si)) { - client->errorValue = _XkbErrCode2(0x05,compat->num_si); - return BadValue; - } - rep.nTotalSI = compat->num_si; - rep.groups= stuff->groups; - XkbComputeGetCompatMapReplySize(compat,&rep); - return XkbSendCompatMap(client,compat,&rep); -} - -/** - * Apply the given request on the given device. - * If dryRun is True, then value checks are performed, but the device isn't - * modified. - */ -static int -_XkbSetCompatMap(ClientPtr client, DeviceIntPtr dev, - xkbSetCompatMapReq *req, char* data, BOOL dryRun) -{ - XkbSrvInfoPtr xkbi; - XkbDescPtr xkb; - XkbCompatMapPtr compat; - int nGroups; - unsigned i,bit; - - xkbi = dev->key->xkbInfo; - xkb = xkbi->desc; - compat = xkb->compat; - - if ((req->nSI>0)||(req->truncateSI)) { - xkbSymInterpretWireDesc *wire; - if (req->firstSI>compat->num_si) { - client->errorValue = _XkbErrCode2(0x02,compat->num_si); - return BadValue; - } - wire= (xkbSymInterpretWireDesc *)data; - wire+= req->nSI; - data = (char *)wire; - } - - nGroups= 0; - if (req->groups!=0) { - for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) { - if ( req->groups&bit ) - nGroups++; - } - } - data+= nGroups*SIZEOF(xkbModsWireDesc); - if (((data-((char *)req))/4)!=req->length) { - return BadLength; - } - - /* Done all the checks we can do */ - if (dryRun) - return Success; - - data = (char *)&req[1]; - if (req->nSI>0) { - xkbSymInterpretWireDesc *wire = (xkbSymInterpretWireDesc *)data; - XkbSymInterpretPtr sym; - if ((unsigned)(req->firstSI+req->nSI)>compat->num_si) { - compat->num_si= req->firstSI+req->nSI; - compat->sym_interpret= _XkbTypedRealloc(compat->sym_interpret, - compat->num_si, - XkbSymInterpretRec); - if (!compat->sym_interpret) { - compat->num_si= 0; - return BadAlloc; - } - } - else if (req->truncateSI) { - compat->num_si = req->firstSI+req->nSI; - } - sym = &compat->sym_interpret[req->firstSI]; - for (i=0;i<req->nSI;i++,wire++,sym++) { - if (client->swapped) { - int n; - swapl(&wire->sym,n); - } - sym->sym= wire->sym; - sym->mods= wire->mods; - sym->match= wire->match; - sym->flags= wire->flags; - sym->virtual_mod= wire->virtualMod; - memcpy((char *)&sym->act,(char *)&wire->act, - SIZEOF(xkbActionWireDesc)); - } - data = (char *)wire; - } - else if (req->truncateSI) { - compat->num_si = req->firstSI; - } - - if (req->groups!=0) { - unsigned i, bit; - xkbModsWireDesc *wire = (xkbModsWireDesc *)data; - for (i = 0, bit = 1; i < XkbNumKbdGroups; i++, bit <<= 1) { - if (req->groups & bit) { - if (client->swapped) { - int n; - swaps(&wire->virtualMods,n); - } - compat->groups[i].mask= wire->realMods; - compat->groups[i].real_mods= wire->realMods; - compat->groups[i].vmods= wire->virtualMods; - if (wire->virtualMods!=0) { - unsigned tmp; - tmp= XkbMaskForVMask(xkb,wire->virtualMods); - compat->groups[i].mask|= tmp; - } - data+= SIZEOF(xkbModsWireDesc); - wire= (xkbModsWireDesc *)data; - } - } - } - i= XkbPaddedSize((data-((char *)req))); - if ((i/4)!=req->length) { - ErrorF("[xkb] Internal length error on read in _XkbSetCompatMap\n"); - return BadLength; - } - - if (dev->xkb_interest) { - xkbCompatMapNotify ev; - ev.deviceID = dev->id; - ev.changedGroups = req->groups; - ev.firstSI = req->firstSI; - ev.nSI = req->nSI; - ev.nTotalSI = compat->num_si; - XkbSendCompatMapNotify(dev,&ev); - } - - if (req->recomputeActions) { - XkbChangesRec change; - unsigned check; - XkbEventCauseRec cause; - - XkbSetCauseXkbReq(&cause,X_kbSetCompatMap,client); - bzero(&change,sizeof(XkbChangesRec)); - XkbUpdateActions(dev,xkb->min_key_code,XkbNumKeys(xkb),&change,&check, - &cause); - if (check) - XkbCheckSecondaryEffects(xkbi,check,&change,&cause); - XkbSendNotification(dev,&change,&cause); - } - return Success; -} - -int -ProcXkbSetCompatMap(ClientPtr client) -{ - DeviceIntPtr dev; - char *data; - int rc; - - REQUEST(xkbSetCompatMapReq); - REQUEST_AT_LEAST_SIZE(xkbSetCompatMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - - data = (char *)&stuff[1]; - - /* check first using a dry-run */ - rc = _XkbSetCompatMap(client, dev, stuff, data, TRUE); - if (rc != Success) - return rc; - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - /* dry-run */ - rc = _XkbSetCompatMap(client, other, stuff, data, TRUE); - if (rc != Success) - return rc; - } - } - } - } - - /* Yay, the dry-runs succeed. Let's apply */ - rc = _XkbSetCompatMap(client, dev, stuff, data, FALSE); - if (rc != Success) - return rc; - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - rc = _XkbSetCompatMap(client, other, stuff, data, FALSE); - if (rc != Success) - return rc; - } - } - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbGetIndicatorState(ClientPtr client) -{ - xkbGetIndicatorStateReply rep; - XkbSrvLedInfoPtr sli; - DeviceIntPtr dev; - register int i; - - REQUEST(xkbGetIndicatorStateReq); - REQUEST_SIZE_MATCH(xkbGetIndicatorStateReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess); - - sli= XkbFindSrvLedInfo(dev,XkbDfltXIClass,XkbDfltXIId, - XkbXI_IndicatorStateMask); - if (!sli) - return BadAlloc; - - rep.type = X_Reply; - rep.sequenceNumber = client->sequence; - rep.length = 0; - rep.deviceID = dev->id; - rep.state = sli->effectiveState; - - if (client->swapped) { - swaps(&rep.sequenceNumber,i); - swapl(&rep.state,i); - } - WriteToClient(client, SIZEOF(xkbGetIndicatorStateReply), (char *)&rep); - return client->noClientException; -} - -/***====================================================================***/ - -static Status -XkbComputeGetIndicatorMapReplySize( - XkbIndicatorPtr indicators, - xkbGetIndicatorMapReply *rep) -{ -register int i,bit; -int nIndicators; - - rep->realIndicators = indicators->phys_indicators; - for (i=nIndicators=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (rep->which&bit) - nIndicators++; - } - rep->length = (nIndicators*SIZEOF(xkbIndicatorMapWireDesc))/4; - return Success; -} - -static int -XkbSendIndicatorMap( ClientPtr client, - XkbIndicatorPtr indicators, - xkbGetIndicatorMapReply * rep) -{ -int length; -CARD8 * map; -register int i; -register unsigned bit; - - length = rep->length*4; - if (length>0) { - CARD8 *to; - to= map= xalloc(length); - if (map) { - xkbIndicatorMapWireDesc *wire = (xkbIndicatorMapWireDesc *)to; - for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (rep->which&bit) { - wire->flags= indicators->maps[i].flags; - wire->whichGroups= indicators->maps[i].which_groups; - wire->groups= indicators->maps[i].groups; - wire->whichMods= indicators->maps[i].which_mods; - wire->mods= indicators->maps[i].mods.mask; - wire->realMods= indicators->maps[i].mods.real_mods; - wire->virtualMods= indicators->maps[i].mods.vmods; - wire->ctrls= indicators->maps[i].ctrls; - if (client->swapped) { - register int n; - swaps(&wire->virtualMods,n); - swapl(&wire->ctrls,n); - } - wire++; - } - } - to = (CARD8 *)wire; - if ((to-map)!=length) { - client->errorValue = _XkbErrCode2(0xff,length); - return BadLength; - } - } - else return BadAlloc; - } - else map = NULL; - if (client->swapped) { - swaps(&rep->sequenceNumber,i); - swapl(&rep->length,i); - swapl(&rep->which,i); - swapl(&rep->realIndicators,i); - } - WriteToClient(client, SIZEOF(xkbGetIndicatorMapReply), (char *)rep); - if (map) { - WriteToClient(client, length, (char *)map); - xfree((char *)map); - } - return client->noClientException; -} - -int -ProcXkbGetIndicatorMap(ClientPtr client) -{ -xkbGetIndicatorMapReply rep; -DeviceIntPtr dev; -XkbDescPtr xkb; -XkbIndicatorPtr leds; - - REQUEST(xkbGetIndicatorMapReq); - REQUEST_SIZE_MATCH(xkbGetIndicatorMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - - xkb= dev->key->xkbInfo->desc; - leds= xkb->indicators; - - rep.type = X_Reply; - rep.sequenceNumber = client->sequence; - rep.length = 0; - rep.deviceID = dev->id; - rep.which = stuff->which; - XkbComputeGetIndicatorMapReplySize(leds,&rep); - return XkbSendIndicatorMap(client,leds,&rep); -} - -/** - * Apply the given map to the given device. Which specifies which components - * to apply. - */ -static int -_XkbSetIndicatorMap(ClientPtr client, DeviceIntPtr dev, - int which, xkbIndicatorMapWireDesc *desc) -{ - XkbSrvInfoPtr xkbi; - XkbSrvLedInfoPtr sli; - XkbEventCauseRec cause; - int i, bit; - - xkbi = dev->key->xkbInfo; - - sli= XkbFindSrvLedInfo(dev, XkbDfltXIClass, XkbDfltXIId, - XkbXI_IndicatorMapsMask); - if (!sli) - return BadAlloc; - - for (i = 0, bit = 1; i < XkbNumIndicators; i++, bit <<= 1) { - if (which & bit) { - sli->maps[i].flags = desc->flags; - sli->maps[i].which_groups = desc->whichGroups; - sli->maps[i].groups = desc->groups; - sli->maps[i].which_mods = desc->whichMods; - sli->maps[i].mods.mask = desc->mods; - sli->maps[i].mods.real_mods = desc->mods; - sli->maps[i].mods.vmods= desc->virtualMods; - sli->maps[i].ctrls = desc->ctrls; - if (desc->virtualMods!=0) { - unsigned tmp; - tmp= XkbMaskForVMask(xkbi->desc,desc->virtualMods); - sli->maps[i].mods.mask= desc->mods|tmp; - } - desc++; - } - } - - XkbSetCauseXkbReq(&cause,X_kbSetIndicatorMap,client); - XkbApplyLedMapChanges(dev,sli,which,NULL,NULL,&cause); - - return Success; -} - -int -ProcXkbSetIndicatorMap(ClientPtr client) -{ - int i, bit; - int nIndicators; - DeviceIntPtr dev; - xkbIndicatorMapWireDesc *from; - int rc; - - REQUEST(xkbSetIndicatorMapReq); - REQUEST_AT_LEAST_SIZE(xkbSetIndicatorMapReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess); - - if (stuff->which==0) - return client->noClientException; - - for (nIndicators=i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (stuff->which&bit) - nIndicators++; - } - if (stuff->length!=((SIZEOF(xkbSetIndicatorMapReq)+ - (nIndicators*SIZEOF(xkbIndicatorMapWireDesc)))/4)) { - return BadLength; - } - - from = (xkbIndicatorMapWireDesc *)&stuff[1]; - for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (stuff->which&bit) { - if (client->swapped) { - int n; - swaps(&from->virtualMods,n); - swapl(&from->ctrls,n); - } - CHK_MASK_LEGAL(i,from->whichGroups,XkbIM_UseAnyGroup); - CHK_MASK_LEGAL(i,from->whichMods,XkbIM_UseAnyMods); - from++; - } - } - - from = (xkbIndicatorMapWireDesc *)&stuff[1]; - rc = _XkbSetIndicatorMap(client, dev, stuff->which, from); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess); - if (rc == Success) - _XkbSetIndicatorMap(client, other, stuff->which, from); - } - } - } - - return Success; -} - -/***====================================================================***/ - -int -ProcXkbGetNamedIndicator(ClientPtr client) -{ - DeviceIntPtr dev; - xkbGetNamedIndicatorReply rep; - register int i = 0; - XkbSrvLedInfoPtr sli; - XkbIndicatorMapPtr map = NULL; - - REQUEST(xkbGetNamedIndicatorReq); - REQUEST_SIZE_MATCH(xkbGetNamedIndicatorReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_LED_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess); - CHK_ATOM_ONLY(stuff->indicator); - - sli= XkbFindSrvLedInfo(dev,stuff->ledClass,stuff->ledID,0); - if (!sli) - return BadAlloc; - - i= 0; - map= NULL; - if ((sli->names)&&(sli->maps)) { - for (i=0;i<XkbNumIndicators;i++) { - if (stuff->indicator==sli->names[i]) { - map= &sli->maps[i]; - break; - } - } - } - - rep.type= X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.deviceID = dev->id; - rep.indicator= stuff->indicator; - if (map!=NULL) { - rep.found= True; - rep.on= ((sli->effectiveState&(1<<i))!=0); - rep.realIndicator= ((sli->physIndicators&(1<<i))!=0); - rep.ndx= i; - rep.flags= map->flags; - rep.whichGroups= map->which_groups; - rep.groups= map->groups; - rep.whichMods= map->which_mods; - rep.mods= map->mods.mask; - rep.realMods= map->mods.real_mods; - rep.virtualMods= map->mods.vmods; - rep.ctrls= map->ctrls; - rep.supported= True; - } - else { - rep.found= False; - rep.on= False; - rep.realIndicator= False; - rep.ndx= XkbNoIndicator; - rep.flags= 0; - rep.whichGroups= 0; - rep.groups= 0; - rep.whichMods= 0; - rep.mods= 0; - rep.realMods= 0; - rep.virtualMods= 0; - rep.ctrls= 0; - rep.supported= True; - } - if ( client->swapped ) { - register int n; - swapl(&rep.length,n); - swaps(&rep.sequenceNumber,n); - swapl(&rep.indicator,n); - swaps(&rep.virtualMods,n); - swapl(&rep.ctrls,n); - } - - WriteToClient(client,SIZEOF(xkbGetNamedIndicatorReply), (char *)&rep); - return client->noClientException; -} - - -/** - * Find the IM on the device. - * Returns the map, or NULL if the map doesn't exist. - * If the return value is NULL, led_return is undefined. Otherwise, led_return - * is set to the led index of the map. - */ -static XkbIndicatorMapPtr -_XkbFindNamedIndicatorMap(XkbSrvLedInfoPtr sli, Atom indicator, - int *led_return) -{ - XkbIndicatorMapPtr map; - int led; - - /* search for the right indicator */ - map = NULL; - if (sli->names && sli->maps) { - for (led = 0; (led < XkbNumIndicators) && (map == NULL); led++) { - if (sli->names[led] == indicator) { - map= &sli->maps[led]; - break; - } - } - } - - *led_return = led; - return map; -} - -/** - * Creates an indicator map on the device. If dryRun is True, it only checks - * if creation is possible, but doesn't actually create it. - */ -static int -_XkbCreateIndicatorMap(DeviceIntPtr dev, Atom indicator, - int ledClass, int ledID, - XkbIndicatorMapPtr *map_return, int *led_return, - Bool dryRun) -{ - XkbSrvLedInfoPtr sli; - XkbIndicatorMapPtr map; - int led; - - sli = XkbFindSrvLedInfo(dev, ledClass, ledID, XkbXI_IndicatorsMask); - if (!sli) - return BadAlloc; - - map = _XkbFindNamedIndicatorMap(sli, indicator, &led); - - if (!map) - { - /* find first unused indicator maps and assign the name to it */ - for (led = 0, map = NULL; (led < XkbNumIndicators) && (map == NULL); led++) { - if ((sli->names) && (sli->maps) && (sli->names[led] == None) && - (!XkbIM_InUse(&sli->maps[led]))) - { - map = &sli->maps[led]; - if (!dryRun) - sli->names[led] = indicator; - break; - } - } - } - - if (!map) - return BadAlloc; - - *led_return = led; - *map_return = map; - return Success; -} - -static int -_XkbSetNamedIndicator(ClientPtr client, DeviceIntPtr dev, - xkbSetNamedIndicatorReq *stuff) -{ - unsigned int extDevReason; - unsigned int statec, namec, mapc; - XkbSrvLedInfoPtr sli; - int led = 0; - XkbIndicatorMapPtr map; - DeviceIntPtr kbd; - XkbEventCauseRec cause; - xkbExtensionDeviceNotify ed; - XkbChangesRec changes; - int rc; - - rc = _XkbCreateIndicatorMap(dev, stuff->indicator, stuff->ledClass, - stuff->ledID, &map, &led, FALSE); - if (rc != Success || !map) /* oh-oh */ - return rc; - - sli = XkbFindSrvLedInfo(dev, stuff->ledClass, stuff->ledID, - XkbXI_IndicatorsMask); - if (!sli) - return BadAlloc; - - namec = mapc = statec = 0; - extDevReason = 0; - - namec |= (1<<led); - sli->namesPresent |= ((stuff->indicator != None) ? (1 << led) : 0); - extDevReason |= XkbXI_IndicatorNamesMask; - - if (stuff->setMap) { - map->flags = stuff->flags; - map->which_groups = stuff->whichGroups; - map->groups = stuff->groups; - map->which_mods = stuff->whichMods; - map->mods.mask = stuff->realMods; - map->mods.real_mods = stuff->realMods; - map->mods.vmods= stuff->virtualMods; - map->ctrls = stuff->ctrls; - mapc|= (1<<led); - } - - if ((stuff->setState) && ((map->flags & XkbIM_NoExplicit) == 0)) - { - if (stuff->on) sli->explicitState |= (1<<led); - else sli->explicitState &= ~(1<<led); - statec |= ((sli->effectiveState ^ sli->explicitState) & (1 << led)); - } - - bzero((char *)&ed,sizeof(xkbExtensionDeviceNotify)); - bzero((char *)&changes,sizeof(XkbChangesRec)); - XkbSetCauseXkbReq(&cause,X_kbSetNamedIndicator,client); - if (namec) - XkbApplyLedNameChanges(dev,sli,namec,&ed,&changes,&cause); - if (mapc) - XkbApplyLedMapChanges(dev,sli,mapc,&ed,&changes,&cause); - if (statec) - XkbApplyLedStateChanges(dev,sli,statec,&ed,&changes,&cause); - - kbd = dev; - if ((sli->flags&XkbSLI_HasOwnState)==0) - kbd = inputInfo.keyboard; - XkbFlushLedEvents(dev, kbd, sli, &ed, &changes, &cause); - - return Success; -} - -int -ProcXkbSetNamedIndicator(ClientPtr client) -{ - int rc; - DeviceIntPtr dev; - int led = 0; - XkbIndicatorMapPtr map; - - REQUEST(xkbSetNamedIndicatorReq); - REQUEST_SIZE_MATCH(xkbSetNamedIndicatorReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_LED_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess); - CHK_ATOM_ONLY(stuff->indicator); - CHK_MASK_LEGAL(0x10,stuff->whichGroups,XkbIM_UseAnyGroup); - CHK_MASK_LEGAL(0x11,stuff->whichMods,XkbIM_UseAnyMods); - - /* Dry-run for checks */ - rc = _XkbCreateIndicatorMap(dev, stuff->indicator, - stuff->ledClass, stuff->ledID, - &map, &led, TRUE); - if (rc != Success || !map) /* couldn't be created or didn't exist */ - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd || - stuff->deviceSpec == XkbUseCorePtr) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && !IsMaster(other) && (other->u.master == dev) && - (other->kbdfeed || other->leds) && - (XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess) == Success)) - { - rc = _XkbCreateIndicatorMap(other, stuff->indicator, - stuff->ledClass, stuff->ledID, - &map, &led, TRUE); - if (rc != Success || !map) - return rc; - } - } - } - - /* All checks passed, let's do it */ - rc = _XkbSetNamedIndicator(client, dev, stuff); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd || - stuff->deviceSpec == XkbUseCorePtr) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && !IsMaster(other) && (other->u.master == dev) && - (other->kbdfeed || other->leds) && - (XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess) == Success)) - { - _XkbSetNamedIndicator(client, other, stuff); - } - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -static CARD32 -_XkbCountAtoms(Atom *atoms,int maxAtoms,int *count) -{ -register unsigned int i,bit,nAtoms; -register CARD32 atomsPresent; - - for (i=nAtoms=atomsPresent=0,bit=1;i<maxAtoms;i++,bit<<=1) { - if (atoms[i]!=None) { - atomsPresent|= bit; - nAtoms++; - } - } - if (count) - *count= nAtoms; - return atomsPresent; -} - -static char * -_XkbWriteAtoms(char *wire,Atom *atoms,int maxAtoms,int swap) -{ -register unsigned int i; -Atom *atm; - - atm = (Atom *)wire; - for (i=0;i<maxAtoms;i++) { - if (atoms[i]!=None) { - *atm= atoms[i]; - if (swap) { - register int n; - swapl(atm,n); - } - atm++; - } - } - return (char *)atm; -} - -static Status -XkbComputeGetNamesReplySize(XkbDescPtr xkb,xkbGetNamesReply *rep) -{ -register unsigned which,length; -register int i; - - rep->minKeyCode= xkb->min_key_code; - rep->maxKeyCode= xkb->max_key_code; - which= rep->which; - length= 0; - if (xkb->names!=NULL) { - if (which&XkbKeycodesNameMask) length++; - if (which&XkbGeometryNameMask) length++; - if (which&XkbSymbolsNameMask) length++; - if (which&XkbPhysSymbolsNameMask) length++; - if (which&XkbTypesNameMask) length++; - if (which&XkbCompatNameMask) length++; - } - else which&= ~XkbComponentNamesMask; - - if (xkb->map!=NULL) { - if (which&XkbKeyTypeNamesMask) - length+= xkb->map->num_types; - rep->nTypes= xkb->map->num_types; - if (which&XkbKTLevelNamesMask) { - XkbKeyTypePtr pType = xkb->map->types; - int nKTLevels = 0; - - length+= XkbPaddedSize(xkb->map->num_types)/4; - for (i=0;i<xkb->map->num_types;i++,pType++) { - if (pType->level_names!=NULL) - nKTLevels+= pType->num_levels; - } - rep->nKTLevels= nKTLevels; - length+= nKTLevels; - } - } - else { - rep->nTypes= 0; - rep->nKTLevels= 0; - which&= ~(XkbKeyTypeNamesMask|XkbKTLevelNamesMask); - } - - rep->minKeyCode= xkb->min_key_code; - rep->maxKeyCode= xkb->max_key_code; - rep->indicators= 0; - rep->virtualMods= 0; - rep->groupNames= 0; - if (xkb->names!=NULL) { - if (which&XkbIndicatorNamesMask) { - int nLeds; - rep->indicators= - _XkbCountAtoms(xkb->names->indicators,XkbNumIndicators,&nLeds); - length+= nLeds; - if (nLeds==0) - which&= ~XkbIndicatorNamesMask; - } - - if (which&XkbVirtualModNamesMask) { - int nVMods; - rep->virtualMods= - _XkbCountAtoms(xkb->names->vmods,XkbNumVirtualMods,&nVMods); - length+= nVMods; - if (nVMods==0) - which&= ~XkbVirtualModNamesMask; - } - - if (which&XkbGroupNamesMask) { - int nGroups; - rep->groupNames= - _XkbCountAtoms(xkb->names->groups,XkbNumKbdGroups,&nGroups); - length+= nGroups; - if (nGroups==0) - which&= ~XkbGroupNamesMask; - } - - if ((which&XkbKeyNamesMask)&&(xkb->names->keys)) - length+= rep->nKeys; - else which&= ~XkbKeyNamesMask; - - if ((which&XkbKeyAliasesMask)&& - (xkb->names->key_aliases)&&(xkb->names->num_key_aliases>0)) { - rep->nKeyAliases= xkb->names->num_key_aliases; - length+= rep->nKeyAliases*2; - } - else { - which&= ~XkbKeyAliasesMask; - rep->nKeyAliases= 0; - } - - if ((which&XkbRGNamesMask)&&(xkb->names->num_rg>0)) - length+= xkb->names->num_rg; - else which&= ~XkbRGNamesMask; - } - else { - which&= ~(XkbIndicatorNamesMask|XkbVirtualModNamesMask); - which&= ~(XkbGroupNamesMask|XkbKeyNamesMask|XkbKeyAliasesMask); - which&= ~XkbRGNamesMask; - } - - rep->length= length; - rep->which= which; - return Success; -} - -static int -XkbSendNames(ClientPtr client,XkbDescPtr xkb,xkbGetNamesReply *rep) -{ -register unsigned i,length,which; -char * start; -char * desc; -register int n; - - length= rep->length*4; - which= rep->which; - if (client->swapped) { - swaps(&rep->sequenceNumber,n); - swapl(&rep->length,n); - swapl(&rep->which,n); - swaps(&rep->virtualMods,n); - swapl(&rep->indicators,n); - } - - start = desc = xalloc(length); - if ( !start ) - return BadAlloc; - if (xkb->names) { - if (which&XkbKeycodesNameMask) { - *((CARD32 *)desc)= xkb->names->keycodes; - if (client->swapped) { - swapl(desc,n); - } - desc+= 4; - } - if (which&XkbGeometryNameMask) { - *((CARD32 *)desc)= xkb->names->geometry; - if (client->swapped) { - swapl(desc,n); - } - desc+= 4; - } - if (which&XkbSymbolsNameMask) { - *((CARD32 *)desc)= xkb->names->symbols; - if (client->swapped) { - swapl(desc,n); - } - desc+= 4; - } - if (which&XkbPhysSymbolsNameMask) { - register CARD32 *atm= (CARD32 *)desc; - atm[0]= (CARD32)xkb->names->phys_symbols; - if (client->swapped) { - swapl(&atm[0],n); - } - desc+= 4; - } - if (which&XkbTypesNameMask) { - *((CARD32 *)desc)= (CARD32)xkb->names->types; - if (client->swapped) { - swapl(desc,n); - } - desc+= 4; - } - if (which&XkbCompatNameMask) { - *((CARD32 *)desc)= (CARD32)xkb->names->compat; - if (client->swapped) { - swapl(desc,n); - } - desc+= 4; - } - if (which&XkbKeyTypeNamesMask) { - register CARD32 *atm= (CARD32 *)desc; - register XkbKeyTypePtr type= xkb->map->types; - - for (i=0;i<xkb->map->num_types;i++,atm++,type++) { - *atm= (CARD32)type->name; - if (client->swapped) { - swapl(atm,n); - } - } - desc= (char *)atm; - } - if (which&XkbKTLevelNamesMask && xkb->map) { - XkbKeyTypePtr type = xkb->map->types; - register CARD32 *atm; - for (i=0;i<rep->nTypes;i++,type++) { - *desc++ = type->num_levels; - } - desc+= XkbPaddedSize(rep->nTypes)-rep->nTypes; - - atm= (CARD32 *)desc; - type = xkb->map->types; - for (i=0;i<xkb->map->num_types;i++,type++) { - register unsigned l; - if (type->level_names) { - for (l=0;l<type->num_levels;l++,atm++) { - *atm= type->level_names[l]; - if (client->swapped) { - swapl(atm,n); - } - } - desc+= type->num_levels*4; - } - } - } - if (which&XkbIndicatorNamesMask) { - desc= _XkbWriteAtoms(desc,xkb->names->indicators,XkbNumIndicators, - client->swapped); - } - if (which&XkbVirtualModNamesMask) { - desc= _XkbWriteAtoms(desc,xkb->names->vmods,XkbNumVirtualMods, - client->swapped); - } - if (which&XkbGroupNamesMask) { - desc= _XkbWriteAtoms(desc,xkb->names->groups,XkbNumKbdGroups, - client->swapped); - } - if (which&XkbKeyNamesMask) { - for (i=0;i<rep->nKeys;i++,desc+= sizeof(XkbKeyNameRec)) { - *((XkbKeyNamePtr)desc)= xkb->names->keys[i+rep->firstKey]; - } - } - if (which&XkbKeyAliasesMask) { - XkbKeyAliasPtr pAl; - pAl= xkb->names->key_aliases; - for (i=0;i<rep->nKeyAliases;i++,pAl++,desc+=2*XkbKeyNameLength) { - *((XkbKeyAliasPtr)desc)= *pAl; - } - } - if ((which&XkbRGNamesMask)&&(rep->nRadioGroups>0)) { - register CARD32 *atm= (CARD32 *)desc; - for (i=0;i<rep->nRadioGroups;i++,atm++) { - *atm= (CARD32)xkb->names->radio_groups[i]; - if (client->swapped) { - swapl(atm,n); - } - } - desc+= rep->nRadioGroups*4; - } - } - - if ((desc-start)!=(length)) { - ErrorF("[xkb] BOGUS LENGTH in write names, expected %d, got %ld\n", - length, (unsigned long)(desc-start)); - } - WriteToClient(client, SIZEOF(xkbGetNamesReply), (char *)rep); - WriteToClient(client, length, start); - xfree((char *)start); - return client->noClientException; -} - -int -ProcXkbGetNames(ClientPtr client) -{ - DeviceIntPtr dev; - XkbDescPtr xkb; - xkbGetNamesReply rep; - - REQUEST(xkbGetNamesReq); - REQUEST_SIZE_MATCH(xkbGetNamesReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - CHK_MASK_LEGAL(0x01,stuff->which,XkbAllNamesMask); - - xkb = dev->key->xkbInfo->desc; - memset(&rep, 0, sizeof(xkbGetNamesReply)); - rep.type= X_Reply; - rep.sequenceNumber= client->sequence; - rep.length = 0; - rep.deviceID = dev->id; - rep.which = stuff->which; - rep.nTypes = xkb->map->num_types; - rep.firstKey = xkb->min_key_code; - rep.nKeys = XkbNumKeys(xkb); - if (xkb->names!=NULL) { - rep.nKeyAliases= xkb->names->num_key_aliases; - rep.nRadioGroups = xkb->names->num_rg; - } - else { - rep.nKeyAliases= rep.nRadioGroups= 0; - } - XkbComputeGetNamesReplySize(xkb,&rep); - return XkbSendNames(client,xkb,&rep); -} - -/***====================================================================***/ - -static CARD32 * -_XkbCheckAtoms(CARD32 *wire,int nAtoms,int swapped,Atom *pError) -{ -register int i; - - for (i=0;i<nAtoms;i++,wire++) { - if (swapped) { - register int n; - swapl(wire,n); - } - if ((((Atom)*wire)!=None)&&(!ValidAtom((Atom)*wire))) { - *pError= ((Atom)*wire); - return NULL; - } - } - return wire; -} - -static CARD32 * -_XkbCheckMaskedAtoms(CARD32 *wire,int nAtoms,CARD32 present,int swapped, - Atom *pError) -{ -register unsigned i,bit; - - for (i=0,bit=1;(i<nAtoms)&&(present);i++,bit<<=1) { - if ((present&bit)==0) - continue; - if (swapped) { - register int n; - swapl(wire,n); - } - if ((((Atom)*wire)!=None)&&(!ValidAtom(((Atom)*wire)))) { - *pError= (Atom)*wire; - return NULL; - } - wire++; - } - return wire; -} - -static Atom * -_XkbCopyMaskedAtoms( Atom *wire, - Atom *dest, - int nAtoms, - CARD32 present) -{ -register int i,bit; - - for (i=0,bit=1;(i<nAtoms)&&(present);i++,bit<<=1) { - if ((present&bit)==0) - continue; - dest[i]= *wire++; - } - return wire; -} - -static Bool -_XkbCheckTypeName(Atom name,int typeNdx) -{ -const char * str; - - str= NameForAtom(name); - if ((strcmp(str,"ONE_LEVEL")==0)||(strcmp(str,"TWO_LEVEL")==0)|| - (strcmp(str,"ALPHABETIC")==0)||(strcmp(str,"KEYPAD")==0)) - return False; - return True; -} - -/** - * Check the device-dependent data in the request against the device. Returns - * Success, or the appropriate error code. - */ -static int -_XkbSetNamesCheck(ClientPtr client, DeviceIntPtr dev, - xkbSetNamesReq *stuff, CARD32 *data) -{ - XkbDescRec *xkb; - XkbNamesRec *names; - CARD32 *tmp; - Atom bad; - - tmp = data; - xkb = dev->key->xkbInfo->desc; - names = xkb->names; - - - if (stuff->which & XkbKeyTypeNamesMask) { - int i; - CARD32 *old; - if ( stuff->nTypes<1 ) { - client->errorValue = _XkbErrCode2(0x02,stuff->nTypes); - return BadValue; - } - if ((unsigned)(stuff->firstType+stuff->nTypes-1)>=xkb->map->num_types) { - client->errorValue = _XkbErrCode4(0x03,stuff->firstType, - stuff->nTypes, - xkb->map->num_types); - return BadValue; - } - if (((unsigned)stuff->firstType)<=XkbLastRequiredType) { - client->errorValue = _XkbErrCode2(0x04,stuff->firstType); - return BadAccess; - } - old= tmp; - tmp= _XkbCheckAtoms(tmp,stuff->nTypes,client->swapped,&bad); - if (!tmp) { - client->errorValue= bad; - return BadAtom; - } - for (i=0;i<stuff->nTypes;i++,old++) { - if (!_XkbCheckTypeName((Atom)*old,stuff->firstType+i)) - client->errorValue= _XkbErrCode2(0x05,i); - } - } - if (stuff->which&XkbKTLevelNamesMask) { - unsigned i; - XkbKeyTypePtr type; - CARD8 * width; - if ( stuff->nKTLevels<1 ) { - client->errorValue = _XkbErrCode2(0x05,stuff->nKTLevels); - return BadValue; - } - if ((unsigned)(stuff->firstKTLevel+stuff->nKTLevels-1)>= - xkb->map->num_types) { - client->errorValue = _XkbErrCode4(0x06,stuff->firstKTLevel, - stuff->nKTLevels,xkb->map->num_types); - return BadValue; - } - width = (CARD8 *)tmp; - tmp= (CARD32 *)(((char *)tmp)+XkbPaddedSize(stuff->nKTLevels)); - type = &xkb->map->types[stuff->firstKTLevel]; - for (i=0;i<stuff->nKTLevels;i++,type++) { - if (width[i]==0) - continue; - else if (width[i]!=type->num_levels) { - client->errorValue= _XkbErrCode4(0x07,i+stuff->firstKTLevel, - type->num_levels,width[i]); - return BadMatch; - } - tmp= _XkbCheckAtoms(tmp,width[i],client->swapped,&bad); - if (!tmp) { - client->errorValue= bad; - return BadAtom; - } - } - } - if (stuff->which&XkbIndicatorNamesMask) { - if (stuff->indicators==0) { - client->errorValue= 0x08; - return BadMatch; - } - tmp= _XkbCheckMaskedAtoms(tmp,XkbNumIndicators,stuff->indicators, - client->swapped,&bad); - if (!tmp) { - client->errorValue= bad; - return BadAtom; - } - } - if (stuff->which&XkbVirtualModNamesMask) { - if (stuff->virtualMods==0) { - client->errorValue= 0x09; - return BadMatch; - } - tmp= _XkbCheckMaskedAtoms(tmp,XkbNumVirtualMods, - (CARD32)stuff->virtualMods, - client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbGroupNamesMask) { - if (stuff->groupNames==0) { - client->errorValue= 0x0a; - return BadMatch; - } - tmp= _XkbCheckMaskedAtoms(tmp,XkbNumKbdGroups, - (CARD32)stuff->groupNames, - client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbKeyNamesMask) { - if (stuff->firstKey<(unsigned)xkb->min_key_code) { - client->errorValue= _XkbErrCode3(0x0b,xkb->min_key_code, - stuff->firstKey); - return BadValue; - } - if (((unsigned)(stuff->firstKey+stuff->nKeys-1)>xkb->max_key_code)|| - (stuff->nKeys<1)) { - client->errorValue= _XkbErrCode4(0x0c,xkb->max_key_code, - stuff->firstKey,stuff->nKeys); - return BadValue; - } - tmp+= stuff->nKeys; - } - if ((stuff->which&XkbKeyAliasesMask)&&(stuff->nKeyAliases>0)) { - tmp+= stuff->nKeyAliases*2; - } - if (stuff->which&XkbRGNamesMask) { - if ( stuff->nRadioGroups<1 ) { - client->errorValue= _XkbErrCode2(0x0d,stuff->nRadioGroups); - return BadValue; - } - tmp= _XkbCheckAtoms(tmp,stuff->nRadioGroups,client->swapped,&bad); - if (!tmp) { - client->errorValue= bad; - return BadAtom; - } - } - if ((tmp-((CARD32 *)stuff))!=stuff->length) { - client->errorValue = stuff->length; - return BadLength; - } - - - - return Success; -} - -static int -_XkbSetNames(ClientPtr client, DeviceIntPtr dev, xkbSetNamesReq *stuff) -{ - XkbDescRec *xkb; - XkbNamesRec *names; - CARD32 *tmp; - xkbNamesNotify nn; - - tmp = (CARD32 *)&stuff[1]; - xkb = dev->key->xkbInfo->desc; - names = xkb->names; - - if (XkbAllocNames(xkb,stuff->which,stuff->nRadioGroups, - stuff->nKeyAliases)!=Success) { - return BadAlloc; - } - - bzero(&nn,sizeof(xkbNamesNotify)); - nn.changed= stuff->which; - tmp = (CARD32 *)&stuff[1]; - if (stuff->which&XkbKeycodesNameMask) - names->keycodes= *tmp++; - if (stuff->which&XkbGeometryNameMask) - names->geometry= *tmp++; - if (stuff->which&XkbSymbolsNameMask) - names->symbols= *tmp++; - if (stuff->which&XkbPhysSymbolsNameMask) - names->phys_symbols= *tmp++; - if (stuff->which&XkbTypesNameMask) - names->types= *tmp++; - if (stuff->which&XkbCompatNameMask) - names->compat= *tmp++; - if ((stuff->which&XkbKeyTypeNamesMask)&&(stuff->nTypes>0)) { - register unsigned i; - register XkbKeyTypePtr type; - - type= &xkb->map->types[stuff->firstType]; - for (i=0;i<stuff->nTypes;i++,type++) { - type->name= *tmp++; - } - nn.firstType= stuff->firstType; - nn.nTypes= stuff->nTypes; - } - if (stuff->which&XkbKTLevelNamesMask) { - register XkbKeyTypePtr type; - register unsigned i; - CARD8 *width; - - width = (CARD8 *)tmp; - tmp= (CARD32 *)(((char *)tmp)+XkbPaddedSize(stuff->nKTLevels)); - type= &xkb->map->types[stuff->firstKTLevel]; - for (i=0;i<stuff->nKTLevels;i++,type++) { - if (width[i]>0) { - if (type->level_names) { - register unsigned n; - for (n=0;n<width[i];n++) { - type->level_names[n]= tmp[n]; - } - } - tmp+= width[i]; - } - } - nn.firstLevelName= 0; - nn.nLevelNames= stuff->nTypes; - } - if (stuff->which&XkbIndicatorNamesMask) { - tmp= _XkbCopyMaskedAtoms(tmp,names->indicators,XkbNumIndicators, - stuff->indicators); - nn.changedIndicators= stuff->indicators; - } - if (stuff->which&XkbVirtualModNamesMask) { - tmp= _XkbCopyMaskedAtoms(tmp,names->vmods,XkbNumVirtualMods, - stuff->virtualMods); - nn.changedVirtualMods= stuff->virtualMods; - } - if (stuff->which&XkbGroupNamesMask) { - tmp= _XkbCopyMaskedAtoms(tmp,names->groups,XkbNumKbdGroups, - stuff->groupNames); - nn.changedVirtualMods= stuff->groupNames; - } - if (stuff->which&XkbKeyNamesMask) { - memcpy((char*)&names->keys[stuff->firstKey],(char *)tmp, - stuff->nKeys*XkbKeyNameLength); - tmp+= stuff->nKeys; - nn.firstKey= stuff->firstKey; - nn.nKeys= stuff->nKeys; - } - if (stuff->which&XkbKeyAliasesMask) { - if (stuff->nKeyAliases>0) { - register int na= stuff->nKeyAliases; - if (XkbAllocNames(xkb,XkbKeyAliasesMask,0,na)!=Success) - return BadAlloc; - memcpy((char *)names->key_aliases,(char *)tmp, - stuff->nKeyAliases*sizeof(XkbKeyAliasRec)); - tmp+= stuff->nKeyAliases*2; - } - else if (names->key_aliases!=NULL) { - xfree(names->key_aliases); - names->key_aliases= NULL; - names->num_key_aliases= 0; - } - nn.nAliases= names->num_key_aliases; - } - if (stuff->which&XkbRGNamesMask) { - if (stuff->nRadioGroups>0) { - register unsigned i,nrg; - nrg= stuff->nRadioGroups; - if (XkbAllocNames(xkb,XkbRGNamesMask,nrg,0)!=Success) - return BadAlloc; - - for (i=0;i<stuff->nRadioGroups;i++) { - names->radio_groups[i]= tmp[i]; - } - tmp+= stuff->nRadioGroups; - } - else if (names->radio_groups) { - xfree(names->radio_groups); - names->radio_groups= NULL; - names->num_rg= 0; - } - nn.nRadioGroups= names->num_rg; - } - if (nn.changed) { - Bool needExtEvent; - needExtEvent= (nn.changed&XkbIndicatorNamesMask)!=0; - XkbSendNamesNotify(dev,&nn); - if (needExtEvent) { - XkbSrvLedInfoPtr sli; - xkbExtensionDeviceNotify edev; - register int i; - register unsigned bit; - - sli= XkbFindSrvLedInfo(dev,XkbDfltXIClass,XkbDfltXIId, - XkbXI_IndicatorsMask); - sli->namesPresent= 0; - for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (names->indicators[i]!=None) - sli->namesPresent|= bit; - } - bzero(&edev,sizeof(xkbExtensionDeviceNotify)); - edev.reason= XkbXI_IndicatorNamesMask; - edev.ledClass= KbdFeedbackClass; - edev.ledID= dev->kbdfeed->ctrl.id; - edev.ledsDefined= sli->namesPresent|sli->mapsPresent; - edev.ledState= sli->effectiveState; - edev.firstBtn= 0; - edev.nBtns= 0; - edev.supported= XkbXI_AllFeaturesMask; - edev.unsupported= 0; - XkbSendExtensionDeviceNotify(dev,client,&edev); - } - } - return Success; -} - -int -ProcXkbSetNames(ClientPtr client) -{ - DeviceIntPtr dev; - CARD32 *tmp; - Atom bad; - int rc; - - REQUEST(xkbSetNamesReq); - REQUEST_AT_LEAST_SIZE(xkbSetNamesReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - CHK_MASK_LEGAL(0x01,stuff->which,XkbAllNamesMask); - - /* check device-independent stuff */ - tmp = (CARD32 *)&stuff[1]; - - if (stuff->which&XkbKeycodesNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbGeometryNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbSymbolsNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbPhysSymbolsNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue= bad; - return BadAtom; - } - } - if (stuff->which&XkbTypesNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - if (stuff->which&XkbCompatNameMask) { - tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad); - if (!tmp) { - client->errorValue = bad; - return BadAtom; - } - } - - /* start of device-dependent tests */ - rc = _XkbSetNamesCheck(client, dev, stuff, tmp); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - rc = _XkbSetNamesCheck(client, other, stuff, tmp); - if (rc != Success) - return rc; - } - } - } - } - - /* everything is okay -- update names */ - - rc = _XkbSetNames(client, dev, stuff); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - _XkbSetNames(client, other, stuff); - } - } - } - - /* everything is okay -- update names */ - - return client->noClientException; -} - -/***====================================================================***/ - -#include "xkbgeom.h" - -#define XkbSizeCountedString(s) ((s)?((((2+strlen(s))+3)/4)*4):4) - -static char * -XkbWriteCountedString(char *wire,char *str,Bool swap) -{ -CARD16 len,*pLen; - - len= (str?strlen(str):0); - pLen= (CARD16 *)wire; - *pLen= len; - if (swap) { - register int n; - swaps(pLen,n); - } - memcpy(&wire[2],str,len); - wire+= ((2+len+3)/4)*4; - return wire; -} - -static int -XkbSizeGeomProperties(XkbGeometryPtr geom) -{ -register int i,size; -XkbPropertyPtr prop; - - for (size=i=0,prop=geom->properties;i<geom->num_properties;i++,prop++) { - size+= XkbSizeCountedString(prop->name); - size+= XkbSizeCountedString(prop->value); - } - return size; -} - -static char * -XkbWriteGeomProperties(char *wire,XkbGeometryPtr geom,Bool swap) -{ -register int i; -register XkbPropertyPtr prop; - - for (i=0,prop=geom->properties;i<geom->num_properties;i++,prop++) { - wire= XkbWriteCountedString(wire,prop->name,swap); - wire= XkbWriteCountedString(wire,prop->value,swap); - } - return wire; -} - -static int -XkbSizeGeomKeyAliases(XkbGeometryPtr geom) -{ - return geom->num_key_aliases*(2*XkbKeyNameLength); -} - -static char * -XkbWriteGeomKeyAliases(char *wire,XkbGeometryPtr geom,Bool swap) -{ -register int sz; - - sz= geom->num_key_aliases*(XkbKeyNameLength*2); - if (sz>0) { - memcpy(wire,(char *)geom->key_aliases,sz); - wire+= sz; - } - return wire; -} - -static int -XkbSizeGeomColors(XkbGeometryPtr geom) -{ -register int i,size; -register XkbColorPtr color; - - for (i=size=0,color=geom->colors;i<geom->num_colors;i++,color++) { - size+= XkbSizeCountedString(color->spec); - } - return size; -} - -static char * -XkbWriteGeomColors(char *wire,XkbGeometryPtr geom,Bool swap) -{ -register int i; -register XkbColorPtr color; - - for (i=0,color=geom->colors;i<geom->num_colors;i++,color++) { - wire= XkbWriteCountedString(wire,color->spec,swap); - } - return wire; -} - -static int -XkbSizeGeomShapes(XkbGeometryPtr geom) -{ -register int i,size; -register XkbShapePtr shape; - - for (i=size=0,shape=geom->shapes;i<geom->num_shapes;i++,shape++) { - register int n; - register XkbOutlinePtr ol; - size+= SIZEOF(xkbShapeWireDesc); - for (n=0,ol=shape->outlines;n<shape->num_outlines;n++,ol++) { - size+= SIZEOF(xkbOutlineWireDesc); - size+= ol->num_points*SIZEOF(xkbPointWireDesc); - } - } - return size; -} - -static char * -XkbWriteGeomShapes(char *wire,XkbGeometryPtr geom,Bool swap) -{ -int i; -XkbShapePtr shape; -xkbShapeWireDesc * shapeWire; - - for (i=0,shape=geom->shapes;i<geom->num_shapes;i++,shape++) { - register int o; - XkbOutlinePtr ol; - xkbOutlineWireDesc * olWire; - shapeWire= (xkbShapeWireDesc *)wire; - shapeWire->name= shape->name; - shapeWire->nOutlines= shape->num_outlines; - if (shape->primary!=NULL) - shapeWire->primaryNdx= XkbOutlineIndex(shape,shape->primary); - else shapeWire->primaryNdx= XkbNoShape; - if (shape->approx!=NULL) - shapeWire->approxNdx= XkbOutlineIndex(shape,shape->approx); - else shapeWire->approxNdx= XkbNoShape; - if (swap) { - register int n; - swapl(&shapeWire->name,n); - } - wire= (char *)&shapeWire[1]; - for (o=0,ol=shape->outlines;o<shape->num_outlines;o++,ol++) { - register int p; - XkbPointPtr pt; - xkbPointWireDesc * ptWire; - olWire= (xkbOutlineWireDesc *)wire; - olWire->nPoints= ol->num_points; - olWire->cornerRadius= ol->corner_radius; - wire= (char *)&olWire[1]; - ptWire= (xkbPointWireDesc *)wire; - for (p=0,pt=ol->points;p<ol->num_points;p++,pt++) { - ptWire[p].x= pt->x; - ptWire[p].y= pt->y; - if (swap) { - register int n; - swaps(&ptWire[p].x,n); - swaps(&ptWire[p].y,n); - } - } - wire= (char *)&ptWire[ol->num_points]; - } - } - return wire; -} - -static int -XkbSizeGeomDoodads(int num_doodads,XkbDoodadPtr doodad) -{ -register int i,size; - - for (i=size=0;i<num_doodads;i++,doodad++) { - size+= SIZEOF(xkbAnyDoodadWireDesc); - if (doodad->any.type==XkbTextDoodad) { - size+= XkbSizeCountedString(doodad->text.text); - size+= XkbSizeCountedString(doodad->text.font); - } - else if (doodad->any.type==XkbLogoDoodad) { - size+= XkbSizeCountedString(doodad->logo.logo_name); - } - } - return size; -} - -static char * -XkbWriteGeomDoodads(char *wire,int num_doodads,XkbDoodadPtr doodad,Bool swap) -{ -register int i; -xkbDoodadWireDesc * doodadWire; - - for (i=0;i<num_doodads;i++,doodad++) { - doodadWire= (xkbDoodadWireDesc *)wire; - wire= (char *)&doodadWire[1]; - bzero(doodadWire,SIZEOF(xkbDoodadWireDesc)); - doodadWire->any.name= doodad->any.name; - doodadWire->any.type= doodad->any.type; - doodadWire->any.priority= doodad->any.priority; - doodadWire->any.top= doodad->any.top; - doodadWire->any.left= doodad->any.left; - if (swap) { - register int n; - swapl(&doodadWire->any.name,n); - swaps(&doodadWire->any.top,n); - swaps(&doodadWire->any.left,n); - } - switch (doodad->any.type) { - case XkbOutlineDoodad: - case XkbSolidDoodad: - doodadWire->shape.angle= doodad->shape.angle; - doodadWire->shape.colorNdx= doodad->shape.color_ndx; - doodadWire->shape.shapeNdx= doodad->shape.shape_ndx; - if (swap) { - register int n; - swaps(&doodadWire->shape.angle,n); - } - break; - case XkbTextDoodad: - doodadWire->text.angle= doodad->text.angle; - doodadWire->text.width= doodad->text.width; - doodadWire->text.height= doodad->text.height; - doodadWire->text.colorNdx= doodad->text.color_ndx; - if (swap) { - register int n; - swaps(&doodadWire->text.angle,n); - swaps(&doodadWire->text.width,n); - swaps(&doodadWire->text.height,n); - } - wire= XkbWriteCountedString(wire,doodad->text.text,swap); - wire= XkbWriteCountedString(wire,doodad->text.font,swap); - break; - case XkbIndicatorDoodad: - doodadWire->indicator.shapeNdx= doodad->indicator.shape_ndx; - doodadWire->indicator.onColorNdx=doodad->indicator.on_color_ndx; - doodadWire->indicator.offColorNdx= - doodad->indicator.off_color_ndx; - break; - case XkbLogoDoodad: - doodadWire->logo.angle= doodad->logo.angle; - doodadWire->logo.colorNdx= doodad->logo.color_ndx; - doodadWire->logo.shapeNdx= doodad->logo.shape_ndx; - wire= XkbWriteCountedString(wire,doodad->logo.logo_name,swap); - break; - default: - ErrorF("[xkb] Unknown doodad type %d in XkbWriteGeomDoodads\n", - doodad->any.type); - ErrorF("[xkb] Ignored\n"); - break; - } - } - return wire; -} - -static char * -XkbWriteGeomOverlay(char *wire,XkbOverlayPtr ol,Bool swap) -{ -register int r; -XkbOverlayRowPtr row; -xkbOverlayWireDesc * olWire; - - olWire= (xkbOverlayWireDesc *)wire; - olWire->name= ol->name; - olWire->nRows= ol->num_rows; - if (swap) { - register int n; - swapl(&olWire->name,n); - } - wire= (char *)&olWire[1]; - for (r=0,row=ol->rows;r<ol->num_rows;r++,row++) { - unsigned int k; - XkbOverlayKeyPtr key; - xkbOverlayRowWireDesc * rowWire; - rowWire= (xkbOverlayRowWireDesc *)wire; - rowWire->rowUnder= row->row_under; - rowWire->nKeys= row->num_keys; - wire= (char *)&rowWire[1]; - for (k=0,key=row->keys;k<row->num_keys;k++,key++) { - xkbOverlayKeyWireDesc * keyWire; - keyWire= (xkbOverlayKeyWireDesc *)wire; - memcpy(keyWire->over,key->over.name,XkbKeyNameLength); - memcpy(keyWire->under,key->under.name,XkbKeyNameLength); - wire= (char *)&keyWire[1]; - } - } - return wire; -} - -static int -XkbSizeGeomSections(XkbGeometryPtr geom) -{ -register int i,size; -XkbSectionPtr section; - - for (i=size=0,section=geom->sections;i<geom->num_sections;i++,section++) { - size+= SIZEOF(xkbSectionWireDesc); - if (section->rows) { - int r; - XkbRowPtr row; - for (r=0,row=section->rows;r<section->num_rows;row++,r++) { - size+= SIZEOF(xkbRowWireDesc); - size+= row->num_keys*SIZEOF(xkbKeyWireDesc); - } - } - if (section->doodads) - size+= XkbSizeGeomDoodads(section->num_doodads,section->doodads); - if (section->overlays) { - int o; - XkbOverlayPtr ol; - for (o=0,ol=section->overlays;o<section->num_overlays;o++,ol++) { - int r; - XkbOverlayRowPtr row; - size+= SIZEOF(xkbOverlayWireDesc); - for (r=0,row=ol->rows;r<ol->num_rows;r++,row++) { - size+= SIZEOF(xkbOverlayRowWireDesc); - size+= row->num_keys*SIZEOF(xkbOverlayKeyWireDesc); - } - } - } - } - return size; -} - -static char * -XkbWriteGeomSections(char *wire,XkbGeometryPtr geom,Bool swap) -{ -register int i; -XkbSectionPtr section; -xkbSectionWireDesc * sectionWire; - - for (i=0,section=geom->sections;i<geom->num_sections;i++,section++) { - sectionWire= (xkbSectionWireDesc *)wire; - sectionWire->name= section->name; - sectionWire->top= section->top; - sectionWire->left= section->left; - sectionWire->width= section->width; - sectionWire->height= section->height; - sectionWire->angle= section->angle; - sectionWire->priority= section->priority; - sectionWire->nRows= section->num_rows; - sectionWire->nDoodads= section->num_doodads; - sectionWire->nOverlays= section->num_overlays; - sectionWire->pad= 0; - if (swap) { - register int n; - swapl(§ionWire->name,n); - swaps(§ionWire->top,n); - swaps(§ionWire->left,n); - swaps(§ionWire->width,n); - swaps(§ionWire->height,n); - swaps(§ionWire->angle,n); - } - wire= (char *)§ionWire[1]; - if (section->rows) { - int r; - XkbRowPtr row; - xkbRowWireDesc * rowWire; - for (r=0,row=section->rows;r<section->num_rows;r++,row++) { - rowWire= (xkbRowWireDesc *)wire; - rowWire->top= row->top; - rowWire->left= row->left; - rowWire->nKeys= row->num_keys; - rowWire->vertical= row->vertical; - rowWire->pad= 0; - if (swap) { - register int n; - swaps(&rowWire->top,n); - swaps(&rowWire->left,n); - } - wire= (char *)&rowWire[1]; - if (row->keys) { - int k; - XkbKeyPtr key; - xkbKeyWireDesc * keyWire; - keyWire= (xkbKeyWireDesc *)wire; - for (k=0,key=row->keys;k<row->num_keys;k++,key++) { - memcpy(keyWire[k].name,key->name.name,XkbKeyNameLength); - keyWire[k].gap= key->gap; - keyWire[k].shapeNdx= key->shape_ndx; - keyWire[k].colorNdx= key->color_ndx; - if (swap) { - register int n; - swaps(&keyWire[k].gap,n); - } - } - wire= (char *)&keyWire[row->num_keys]; - } - } - } - if (section->doodads) { - wire= XkbWriteGeomDoodads(wire, - section->num_doodads,section->doodads, - swap); - } - if (section->overlays) { - register int o; - for (o=0;o<section->num_overlays;o++) { - wire= XkbWriteGeomOverlay(wire,§ion->overlays[o],swap); - } - } - } - return wire; -} - -static Status -XkbComputeGetGeometryReplySize( XkbGeometryPtr geom, - xkbGetGeometryReply * rep, - Atom name) -{ -int len; - - if (geom!=NULL) { - len= XkbSizeCountedString(geom->label_font); - len+= XkbSizeGeomProperties(geom); - len+= XkbSizeGeomColors(geom); - len+= XkbSizeGeomShapes(geom); - len+= XkbSizeGeomSections(geom); - len+= XkbSizeGeomDoodads(geom->num_doodads,geom->doodads); - len+= XkbSizeGeomKeyAliases(geom); - rep->length= len/4; - rep->found= True; - rep->name= geom->name; - rep->widthMM= geom->width_mm; - rep->heightMM= geom->height_mm; - rep->nProperties= geom->num_properties; - rep->nColors= geom->num_colors; - rep->nShapes= geom->num_shapes; - rep->nSections= geom->num_sections; - rep->nDoodads= geom->num_doodads; - rep->nKeyAliases= geom->num_key_aliases; - rep->baseColorNdx= XkbGeomColorIndex(geom,geom->base_color); - rep->labelColorNdx= XkbGeomColorIndex(geom,geom->label_color); - } - else { - rep->length= 0; - rep->found= False; - rep->name= name; - rep->widthMM= rep->heightMM= 0; - rep->nProperties= rep->nColors= rep->nShapes= 0; - rep->nSections= rep->nDoodads= 0; - rep->nKeyAliases= 0; - rep->labelColorNdx= rep->baseColorNdx= 0; - } - return Success; -} - -static int -XkbSendGeometry( ClientPtr client, - XkbGeometryPtr geom, - xkbGetGeometryReply * rep, - Bool freeGeom) -{ - char *desc,*start; - int len; - - if (geom!=NULL) { - len= rep->length*4; - start= desc= xalloc(len); - if (!start) - return BadAlloc; - desc= XkbWriteCountedString(desc,geom->label_font,client->swapped); - if ( rep->nProperties>0 ) - desc = XkbWriteGeomProperties(desc,geom,client->swapped); - if ( rep->nColors>0 ) - desc = XkbWriteGeomColors(desc,geom,client->swapped); - if ( rep->nShapes>0 ) - desc = XkbWriteGeomShapes(desc,geom,client->swapped); - if ( rep->nSections>0 ) - desc = XkbWriteGeomSections(desc,geom,client->swapped); - if ( rep->nDoodads>0 ) - desc = XkbWriteGeomDoodads(desc,geom->num_doodads,geom->doodads, - client->swapped); - if ( rep->nKeyAliases>0 ) - desc = XkbWriteGeomKeyAliases(desc,geom,client->swapped); - if ((desc-start)!=(len)) { - ErrorF("[xkb] BOGUS LENGTH in XkbSendGeometry, expected %d, got %ld\n", - len, (unsigned long)(desc-start)); - } - } - else { - len= 0; - start= NULL; - } - if (client->swapped) { - register int n; - swaps(&rep->sequenceNumber,n); - swapl(&rep->length,n); - swapl(&rep->name,n); - swaps(&rep->widthMM,n); - swaps(&rep->heightMM,n); - swaps(&rep->nProperties,n); - swaps(&rep->nColors,n); - swaps(&rep->nShapes,n); - swaps(&rep->nSections,n); - swaps(&rep->nDoodads,n); - swaps(&rep->nKeyAliases,n); - } - WriteToClient(client, SIZEOF(xkbGetGeometryReply), (char *)rep); - if (len>0) - WriteToClient(client, len, start); - if (start!=NULL) - xfree((char *)start); - if (freeGeom) - XkbFreeGeometry(geom,XkbGeomAllMask,True); - return client->noClientException; -} - -int -ProcXkbGetGeometry(ClientPtr client) -{ - DeviceIntPtr dev; - xkbGetGeometryReply rep; - XkbGeometryPtr geom; - Bool shouldFree; - Status status; - - REQUEST(xkbGetGeometryReq); - REQUEST_SIZE_MATCH(xkbGetGeometryReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - CHK_ATOM_OR_NONE(stuff->name); - - geom= XkbLookupNamedGeometry(dev,stuff->name,&shouldFree); - rep.type= X_Reply; - rep.deviceID= dev->id; - rep.sequenceNumber= client->sequence; - rep.length= 0; - status= XkbComputeGetGeometryReplySize(geom,&rep,stuff->name); - if (status!=Success) - return status; - else return XkbSendGeometry(client,geom,&rep,shouldFree); -} - -/***====================================================================***/ - -static char * -_GetCountedString(char **wire_inout,Bool swap) -{ -char * wire,*str; -CARD16 len,*plen; - - wire= *wire_inout; - plen= (CARD16 *)wire; - if (swap) { - register int n; - swaps(plen,n); - } - len= *plen; - str= xalloc(len+1); - if (str) { - memcpy(str,&wire[2],len); - str[len]= '\0'; - } - wire+= XkbPaddedSize(len+2); - *wire_inout= wire; - return str; -} - -static Status -_CheckSetDoodad( char ** wire_inout, - XkbGeometryPtr geom, - XkbSectionPtr section, - ClientPtr client) -{ -char * wire; -xkbDoodadWireDesc * dWire; -XkbDoodadPtr doodad; - - dWire= (xkbDoodadWireDesc *)(*wire_inout); - wire= (char *)&dWire[1]; - if (client->swapped) { - register int n; - swapl(&dWire->any.name,n); - swaps(&dWire->any.top,n); - swaps(&dWire->any.left,n); - swaps(&dWire->any.angle,n); - } - CHK_ATOM_ONLY(dWire->any.name); - doodad= XkbAddGeomDoodad(geom,section,dWire->any.name); - if (!doodad) - return BadAlloc; - doodad->any.type= dWire->any.type; - doodad->any.priority= dWire->any.priority; - doodad->any.top= dWire->any.top; - doodad->any.left= dWire->any.left; - doodad->any.angle= dWire->any.angle; - switch (doodad->any.type) { - case XkbOutlineDoodad: - case XkbSolidDoodad: - if (dWire->shape.colorNdx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x40,geom->num_colors, - dWire->shape.colorNdx); - return BadMatch; - } - if (dWire->shape.shapeNdx>=geom->num_shapes) { - client->errorValue= _XkbErrCode3(0x41,geom->num_shapes, - dWire->shape.shapeNdx); - return BadMatch; - } - doodad->shape.color_ndx= dWire->shape.colorNdx; - doodad->shape.shape_ndx= dWire->shape.shapeNdx; - break; - case XkbTextDoodad: - if (dWire->text.colorNdx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x42,geom->num_colors, - dWire->text.colorNdx); - return BadMatch; - } - if (client->swapped) { - register int n; - swaps(&dWire->text.width,n); - swaps(&dWire->text.height,n); - } - doodad->text.width= dWire->text.width; - doodad->text.height= dWire->text.height; - doodad->text.color_ndx= dWire->text.colorNdx; - doodad->text.text= _GetCountedString(&wire,client->swapped); - doodad->text.font= _GetCountedString(&wire,client->swapped); - break; - case XkbIndicatorDoodad: - if (dWire->indicator.onColorNdx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x43,geom->num_colors, - dWire->indicator.onColorNdx); - return BadMatch; - } - if (dWire->indicator.offColorNdx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x44,geom->num_colors, - dWire->indicator.offColorNdx); - return BadMatch; - } - if (dWire->indicator.shapeNdx>=geom->num_shapes) { - client->errorValue= _XkbErrCode3(0x45,geom->num_shapes, - dWire->indicator.shapeNdx); - return BadMatch; - } - doodad->indicator.shape_ndx= dWire->indicator.shapeNdx; - doodad->indicator.on_color_ndx= dWire->indicator.onColorNdx; - doodad->indicator.off_color_ndx= dWire->indicator.offColorNdx; - break; - case XkbLogoDoodad: - if (dWire->logo.colorNdx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x46,geom->num_colors, - dWire->logo.colorNdx); - return BadMatch; - } - if (dWire->logo.shapeNdx>=geom->num_shapes) { - client->errorValue= _XkbErrCode3(0x47,geom->num_shapes, - dWire->logo.shapeNdx); - return BadMatch; - } - doodad->logo.color_ndx= dWire->logo.colorNdx; - doodad->logo.shape_ndx= dWire->logo.shapeNdx; - doodad->logo.logo_name= _GetCountedString(&wire,client->swapped); - break; - default: - client->errorValue= _XkbErrCode2(0x4F,dWire->any.type); - return BadValue; - } - *wire_inout= wire; - return Success; -} - -static Status -_CheckSetOverlay( char ** wire_inout, - XkbGeometryPtr geom, - XkbSectionPtr section, - ClientPtr client) -{ -register int r; -char * wire; -XkbOverlayPtr ol; -xkbOverlayWireDesc * olWire; -xkbOverlayRowWireDesc * rWire; - - wire= *wire_inout; - olWire= (xkbOverlayWireDesc *)wire; - if (client->swapped) { - register int n; - swapl(&olWire->name,n); - } - CHK_ATOM_ONLY(olWire->name); - ol= XkbAddGeomOverlay(section,olWire->name,olWire->nRows); - rWire= (xkbOverlayRowWireDesc *)&olWire[1]; - for (r=0;r<olWire->nRows;r++) { - register int k; - xkbOverlayKeyWireDesc * kWire; - XkbOverlayRowPtr row; - - if (rWire->rowUnder>section->num_rows) { - client->errorValue= _XkbErrCode4(0x20,r,section->num_rows, - rWire->rowUnder); - return BadMatch; - } - row= XkbAddGeomOverlayRow(ol,rWire->rowUnder,rWire->nKeys); - kWire= (xkbOverlayKeyWireDesc *)&rWire[1]; - for (k=0;k<rWire->nKeys;k++,kWire++) { - if (XkbAddGeomOverlayKey(ol,row, - (char *)kWire->over,(char *)kWire->under)==NULL) { - client->errorValue= _XkbErrCode3(0x21,r,k); - return BadMatch; - } - } - rWire= (xkbOverlayRowWireDesc *)kWire; - } - olWire= (xkbOverlayWireDesc *)rWire; - wire= (char *)olWire; - *wire_inout= wire; - return Success; -} - -static Status -_CheckSetSections( XkbGeometryPtr geom, - xkbSetGeometryReq * req, - char ** wire_inout, - ClientPtr client) -{ -Status status; -register int s; -char * wire; -xkbSectionWireDesc * sWire; -XkbSectionPtr section; - - wire= *wire_inout; - if (req->nSections<1) - return Success; - sWire= (xkbSectionWireDesc *)wire; - for (s=0;s<req->nSections;s++) { - register int r; - xkbRowWireDesc * rWire; - if (client->swapped) { - register int n; - swapl(&sWire->name,n); - swaps(&sWire->top,n); - swaps(&sWire->left,n); - swaps(&sWire->width,n); - swaps(&sWire->height,n); - swaps(&sWire->angle,n); - } - CHK_ATOM_ONLY(sWire->name); - section= XkbAddGeomSection(geom,sWire->name,sWire->nRows, - sWire->nDoodads,sWire->nOverlays); - if (!section) - return BadAlloc; - section->priority= sWire->priority; - section->top= sWire->top; - section->left= sWire->left; - section->width= sWire->width; - section->height= sWire->height; - section->angle= sWire->angle; - rWire= (xkbRowWireDesc *)&sWire[1]; - for (r=0;r<sWire->nRows;r++) { - register int k; - XkbRowPtr row; - xkbKeyWireDesc * kWire; - if (client->swapped) { - register int n; - swaps(&rWire->top,n); - swaps(&rWire->left,n); - } - row= XkbAddGeomRow(section,rWire->nKeys); - if (!row) - return BadAlloc; - row->top= rWire->top; - row->left= rWire->left; - row->vertical= rWire->vertical; - kWire= (xkbKeyWireDesc *)&rWire[1]; - for (k=0;k<rWire->nKeys;k++) { - XkbKeyPtr key; - key= XkbAddGeomKey(row); - if (!key) - return BadAlloc; - memcpy(key->name.name,kWire[k].name,XkbKeyNameLength); - key->gap= kWire[k].gap; - key->shape_ndx= kWire[k].shapeNdx; - key->color_ndx= kWire[k].colorNdx; - if (key->shape_ndx>=geom->num_shapes) { - client->errorValue= _XkbErrCode3(0x10,key->shape_ndx, - geom->num_shapes); - return BadMatch; - } - if (key->color_ndx>=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x11,key->color_ndx, - geom->num_colors); - return BadMatch; - } - } - rWire= (xkbRowWireDesc *)&kWire[rWire->nKeys]; - } - wire= (char *)rWire; - if (sWire->nDoodads>0) { - register int d; - for (d=0;d<sWire->nDoodads;d++) { - status=_CheckSetDoodad(&wire,geom,section,client); - if (status!=Success) - return status; - } - } - if (sWire->nOverlays>0) { - register int o; - for (o=0;o<sWire->nOverlays;o++) { - status= _CheckSetOverlay(&wire,geom,section,client); - if (status!=Success) - return status; - } - } - sWire= (xkbSectionWireDesc *)wire; - } - wire= (char *)sWire; - *wire_inout= wire; - return Success; -} - -static Status -_CheckSetShapes( XkbGeometryPtr geom, - xkbSetGeometryReq * req, - char ** wire_inout, - ClientPtr client) -{ -register int i; -char * wire; - - wire= *wire_inout; - if (req->nShapes<1) { - client->errorValue= _XkbErrCode2(0x06,req->nShapes); - return BadValue; - } - else { - xkbShapeWireDesc * shapeWire; - XkbShapePtr shape; - register int o; - shapeWire= (xkbShapeWireDesc *)wire; - for (i=0;i<req->nShapes;i++) { - xkbOutlineWireDesc * olWire; - XkbOutlinePtr ol; - shape= XkbAddGeomShape(geom,shapeWire->name,shapeWire->nOutlines); - if (!shape) - return BadAlloc; - olWire= (xkbOutlineWireDesc *)(&shapeWire[1]); - for (o=0;o<shapeWire->nOutlines;o++) { - register int p; - XkbPointPtr pt; - xkbPointWireDesc * ptWire; - - ol= XkbAddGeomOutline(shape,olWire->nPoints); - if (!ol) - return BadAlloc; - ol->corner_radius= olWire->cornerRadius; - ptWire= (xkbPointWireDesc *)&olWire[1]; - for (p=0,pt=ol->points;p<olWire->nPoints;p++,pt++) { - pt->x= ptWire[p].x; - pt->y= ptWire[p].y; - if (client->swapped) { - register int n; - swaps(&pt->x,n); - swaps(&pt->y,n); - } - } - ol->num_points= olWire->nPoints; - olWire= (xkbOutlineWireDesc *)(&ptWire[olWire->nPoints]); - } - if (shapeWire->primaryNdx!=XkbNoShape) - shape->primary= &shape->outlines[shapeWire->primaryNdx]; - if (shapeWire->approxNdx!=XkbNoShape) - shape->approx= &shape->outlines[shapeWire->approxNdx]; - shapeWire= (xkbShapeWireDesc *)olWire; - } - wire= (char *)shapeWire; - } - if (geom->num_shapes!=req->nShapes) { - client->errorValue= _XkbErrCode3(0x07,geom->num_shapes,req->nShapes); - return BadMatch; - } - - *wire_inout= wire; - return Success; -} - -static Status -_CheckSetGeom( XkbGeometryPtr geom, - xkbSetGeometryReq * req, - ClientPtr client) -{ -register int i; -Status status; -char * wire; - - wire= (char *)&req[1]; - geom->label_font= _GetCountedString(&wire,client->swapped); - - for (i=0;i<req->nProperties;i++) { - char *name,*val; - name= _GetCountedString(&wire,client->swapped); - if (!name) - return BadAlloc; - val= _GetCountedString(&wire,client->swapped); - if (!val) { - xfree(name); - return BadAlloc; - } - if (XkbAddGeomProperty(geom,name,val)==NULL) { - xfree(name); - xfree(val); - return BadAlloc; - } - xfree(name); - xfree(val); - } - - if (req->nColors<2) { - client->errorValue= _XkbErrCode3(0x01,2,req->nColors); - return BadValue; - } - if (req->baseColorNdx>req->nColors) { - client->errorValue=_XkbErrCode3(0x03,req->nColors,req->baseColorNdx); - return BadMatch; - } - if (req->labelColorNdx>req->nColors) { - client->errorValue= _XkbErrCode3(0x03,req->nColors,req->labelColorNdx); - return BadMatch; - } - if (req->labelColorNdx==req->baseColorNdx) { - client->errorValue= _XkbErrCode3(0x04,req->baseColorNdx, - req->labelColorNdx); - return BadMatch; - } - - for (i=0;i<req->nColors;i++) { - char *name; - name= _GetCountedString(&wire,client->swapped); - if (!name) - return BadAlloc; - if (!XkbAddGeomColor(geom,name,geom->num_colors)) { - xfree(name); - return BadAlloc; - } - xfree(name); - } - if (req->nColors!=geom->num_colors) { - client->errorValue= _XkbErrCode3(0x05,req->nColors,geom->num_colors); - return BadMatch; - } - geom->label_color= &geom->colors[req->labelColorNdx]; - geom->base_color= &geom->colors[req->baseColorNdx]; - - if ((status=_CheckSetShapes(geom,req,&wire,client))!=Success) - return status; - - if ((status=_CheckSetSections(geom,req,&wire,client))!=Success) - return status; - - for (i=0;i<req->nDoodads;i++) { - status=_CheckSetDoodad(&wire,geom,NULL,client); - if (status!=Success) - return status; - } - - for (i=0;i<req->nKeyAliases;i++) { - if (XkbAddGeomKeyAlias(geom,&wire[XkbKeyNameLength],wire)==NULL) - return BadAlloc; - wire+= 2*XkbKeyNameLength; - } - return Success; -} - -static int -_XkbSetGeometry(ClientPtr client, DeviceIntPtr dev, xkbSetGeometryReq *stuff) -{ - XkbDescPtr xkb; - Bool new_name; - xkbNewKeyboardNotify nkn; - XkbGeometryPtr geom,old; - XkbGeometrySizesRec sizes; - Status status; - - xkb= dev->key->xkbInfo->desc; - old= xkb->geom; - xkb->geom= NULL; - - sizes.which= XkbGeomAllMask; - sizes.num_properties= stuff->nProperties; - sizes.num_colors= stuff->nColors; - sizes.num_shapes= stuff->nShapes; - sizes.num_sections= stuff->nSections; - sizes.num_doodads= stuff->nDoodads; - sizes.num_key_aliases= stuff->nKeyAliases; - if ((status= XkbAllocGeometry(xkb,&sizes))!=Success) { - xkb->geom= old; - return status; - } - geom= xkb->geom; - geom->name= stuff->name; - geom->width_mm= stuff->widthMM; - geom->height_mm= stuff->heightMM; - if ((status= _CheckSetGeom(geom,stuff,client))!=Success) { - XkbFreeGeometry(geom,XkbGeomAllMask,True); - xkb->geom= old; - return status; - } - new_name= (xkb->names->geometry!=geom->name); - xkb->names->geometry= geom->name; - if (old) - XkbFreeGeometry(old,XkbGeomAllMask,True); - if (new_name) { - xkbNamesNotify nn; - bzero(&nn,sizeof(xkbNamesNotify)); - nn.changed= XkbGeometryNameMask; - XkbSendNamesNotify(dev,&nn); - } - nkn.deviceID= nkn.oldDeviceID= dev->id; - nkn.minKeyCode= nkn.oldMinKeyCode= xkb->min_key_code; - nkn.maxKeyCode= nkn.oldMaxKeyCode= xkb->max_key_code; - nkn.requestMajor= XkbReqCode; - nkn.requestMinor= X_kbSetGeometry; - nkn.changed= XkbNKN_GeometryMask; - XkbSendNewKeyboardNotify(dev,&nkn); - return Success; -} - -int -ProcXkbSetGeometry(ClientPtr client) -{ - DeviceIntPtr dev; - int rc; - - REQUEST(xkbSetGeometryReq); - REQUEST_AT_LEAST_SIZE(xkbSetGeometryReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - CHK_ATOM_OR_NONE(stuff->name); - - rc = _XkbSetGeometry(client, dev, stuff); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev)) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - _XkbSetGeometry(client, other, stuff); - } - } - } - - return Success; -} - -/***====================================================================***/ - -int -ProcXkbPerClientFlags(ClientPtr client) -{ - DeviceIntPtr dev; - xkbPerClientFlagsReply rep; - XkbInterestPtr interest; - Mask access_mode = DixGetAttrAccess | DixSetAttrAccess; - - REQUEST(xkbPerClientFlagsReq); - REQUEST_SIZE_MATCH(xkbPerClientFlagsReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, access_mode); - CHK_MASK_LEGAL(0x01,stuff->change,XkbPCF_AllFlagsMask); - CHK_MASK_MATCH(0x02,stuff->change,stuff->value); - - interest = XkbFindClientResource((DevicePtr)dev,client); - memset(&rep, 0, sizeof(xkbPerClientFlagsReply)); - rep.type= X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - if (stuff->change) { - client->xkbClientFlags&= ~stuff->change; - client->xkbClientFlags|= stuff->value; - } - if (stuff->change&XkbPCF_AutoResetControlsMask) { - Bool want; - want= stuff->value&XkbPCF_AutoResetControlsMask; - if (interest && !want) { - interest->autoCtrls= interest->autoCtrlValues= 0; - } - else if (want && (!interest)) { - XID id = FakeClientID(client->index); - AddResource(id,RT_XKBCLIENT,dev); - interest= XkbAddClientResource((DevicePtr)dev,client,id); - if (!interest) - return BadAlloc; - } - if (interest && want ) { - register unsigned affect; - affect= stuff->ctrlsToChange; - - CHK_MASK_LEGAL(0x03,affect,XkbAllBooleanCtrlsMask); - CHK_MASK_MATCH(0x04,affect,stuff->autoCtrls); - CHK_MASK_MATCH(0x05,stuff->autoCtrls,stuff->autoCtrlValues); - - interest->autoCtrls&= ~affect; - interest->autoCtrlValues&= ~affect; - interest->autoCtrls|= stuff->autoCtrls&affect; - interest->autoCtrlValues|= stuff->autoCtrlValues&affect; - } - } - rep.supported = XkbPCF_AllFlagsMask; - rep.value= client->xkbClientFlags&XkbPCF_AllFlagsMask; - if (interest) { - rep.autoCtrls= interest->autoCtrls; - rep.autoCtrlValues= interest->autoCtrlValues; - } - else { - rep.autoCtrls= rep.autoCtrlValues= 0; - } - if ( client->swapped ) { - register int n; - swaps(&rep.sequenceNumber, n); - swapl(&rep.supported,n); - swapl(&rep.value,n); - swapl(&rep.autoCtrls,n); - swapl(&rep.autoCtrlValues,n); - } - WriteToClient(client,SIZEOF(xkbPerClientFlagsReply), (char *)&rep); - return client->noClientException; -} - -/***====================================================================***/ - -/* all latin-1 alphanumerics, plus parens, minus, underscore, slash */ -/* and wildcards */ -static unsigned char componentSpecLegal[] = { - 0x00, 0x00, 0x00, 0x00, 0x00, 0xa7, 0xff, 0x87, - 0xfe, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x07, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0xff -}; - -/* same as above but accepts percent, plus and bar too */ -static unsigned char componentExprLegal[] = { - 0x00, 0x00, 0x00, 0x00, 0x20, 0xaf, 0xff, 0x87, - 0xfe, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x17, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0xff -}; - -static char * -GetComponentSpec(unsigned char **pWire,Bool allowExpr,int *errRtrn) -{ -int len; -register int i; -unsigned char *wire,*str,*tmp,*legal; - - if (allowExpr) legal= &componentExprLegal[0]; - else legal= &componentSpecLegal[0]; - - wire= *pWire; - len= (*(unsigned char *)wire++); - if (len>0) { - str= xcalloc(1, len+1); - if (str) { - tmp= str; - for (i=0;i<len;i++) { - if (legal[(*wire)/8]&(1<<((*wire)%8))) - *tmp++= *wire++; - else wire++; - } - if (tmp!=str) - *tmp++= '\0'; - else { - xfree(str); - str= NULL; - } - } - else { - *errRtrn= BadAlloc; - } - } - else { - str= NULL; - } - *pWire= wire; - return (char *)str; -} - -/***====================================================================***/ - -int -ProcXkbListComponents(ClientPtr client) -{ - DeviceIntPtr dev; - xkbListComponentsReply rep; - unsigned len; - int status; - unsigned char * str; - XkbSrvListInfoRec list; - - REQUEST(xkbListComponentsReq); - REQUEST_AT_LEAST_SIZE(xkbListComponentsReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - - status= Success; - str= (unsigned char *)&stuff[1]; - bzero(&list,sizeof(XkbSrvListInfoRec)); - list.maxRtrn= stuff->maxNames; - list.pattern[_XkbListKeycodes]= GetComponentSpec(&str,False,&status); - list.pattern[_XkbListTypes]= GetComponentSpec(&str,False,&status); - list.pattern[_XkbListCompat]= GetComponentSpec(&str,False,&status); - list.pattern[_XkbListSymbols]= GetComponentSpec(&str,False,&status); - list.pattern[_XkbListGeometry]= GetComponentSpec(&str,False,&status); - if (status!=Success) - return status; - len= str-((unsigned char *)stuff); - if ((XkbPaddedSize(len)/4)!=stuff->length) - return BadLength; - if ((status=XkbDDXList(dev,&list,client))!=Success) { - if (list.pool) { - xfree(list.pool); - list.pool= NULL; - } - return status; - } - bzero(&rep,sizeof(xkbListComponentsReply)); - rep.type= X_Reply; - rep.deviceID = dev->id; - rep.sequenceNumber = client->sequence; - rep.length = XkbPaddedSize(list.nPool)/4; - rep.nKeymaps = 0; - rep.nKeycodes = list.nFound[_XkbListKeycodes]; - rep.nTypes = list.nFound[_XkbListTypes]; - rep.nCompatMaps = list.nFound[_XkbListCompat]; - rep.nSymbols = list.nFound[_XkbListSymbols]; - rep.nGeometries = list.nFound[_XkbListGeometry]; - rep.extra= 0; - if (list.nTotal>list.maxRtrn) - rep.extra = (list.nTotal-list.maxRtrn); - if (client->swapped) { - register int n; - swaps(&rep.sequenceNumber,n); - swapl(&rep.length,n); - swaps(&rep.nKeymaps,n); - swaps(&rep.nKeycodes,n); - swaps(&rep.nTypes,n); - swaps(&rep.nCompatMaps,n); - swaps(&rep.nSymbols,n); - swaps(&rep.nGeometries,n); - swaps(&rep.extra,n); - } - WriteToClient(client,SIZEOF(xkbListComponentsReply),(char *)&rep); - if (list.nPool && list.pool) { - WriteToClient(client,XkbPaddedSize(list.nPool), (char *)list.pool); - xfree(list.pool); - list.pool= NULL; - } - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbGetKbdByName(ClientPtr client) -{ - DeviceIntPtr dev; - DeviceIntPtr tmpd; - xkbGetKbdByNameReply rep; - xkbGetMapReply mrep; - xkbGetCompatMapReply crep; - xkbGetIndicatorMapReply irep; - xkbGetNamesReply nrep; - xkbGetGeometryReply grep; - XkbComponentNamesRec names; - XkbDescPtr xkb, new; - unsigned char * str; - char mapFile[PATH_MAX]; - unsigned len; - unsigned fwant,fneed,reported; - int status; - Bool geom_changed; - XkbSrvLedInfoPtr old_sli; - XkbSrvLedInfoPtr sli; - Mask access_mode = DixGetAttrAccess | DixManageAccess; - - REQUEST(xkbGetKbdByNameReq); - REQUEST_AT_LEAST_SIZE(xkbGetKbdByNameReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, access_mode); - - xkb = dev->key->xkbInfo->desc; - status= Success; - str= (unsigned char *)&stuff[1]; - if (GetComponentSpec(&str,True,&status)) /* keymap, unsupported */ - return BadMatch; - names.keycodes= GetComponentSpec(&str,True,&status); - names.types= GetComponentSpec(&str,True,&status); - names.compat= GetComponentSpec(&str,True,&status); - names.symbols= GetComponentSpec(&str,True,&status); - names.geometry= GetComponentSpec(&str,True,&status); - if (status!=Success) - return status; - len= str-((unsigned char *)stuff); - if ((XkbPaddedSize(len)/4)!=stuff->length) - return BadLength; - - CHK_MASK_LEGAL(0x01,stuff->want,XkbGBN_AllComponentsMask); - CHK_MASK_LEGAL(0x02,stuff->need,XkbGBN_AllComponentsMask); - - if (stuff->load) - fwant= XkbGBN_AllComponentsMask; - else fwant= stuff->want|stuff->need; - if ((!names.compat)&& - (fwant&(XkbGBN_CompatMapMask|XkbGBN_IndicatorMapMask))) { - names.compat= _XkbDupString("%"); - } - if ((!names.types)&&(fwant&(XkbGBN_TypesMask))) { - names.types= _XkbDupString("%"); - } - if ((!names.symbols)&&(fwant&XkbGBN_SymbolsMask)) { - names.symbols= _XkbDupString("%"); - } - geom_changed= ((names.geometry!=NULL)&&(strcmp(names.geometry,"%")!=0)); - if ((!names.geometry)&&(fwant&XkbGBN_GeometryMask)) { - names.geometry= _XkbDupString("%"); - geom_changed= False; - } - - bzero(mapFile,PATH_MAX); - rep.type= X_Reply; - rep.deviceID = dev->id; - rep.sequenceNumber = client->sequence; - rep.length = 0; - rep.minKeyCode = xkb->min_key_code; - rep.maxKeyCode = xkb->max_key_code; - rep.loaded= False; - fwant= XkbConvertGetByNameComponents(True,stuff->want)|XkmVirtualModsMask; - fneed= XkbConvertGetByNameComponents(True,stuff->need); - rep.reported= XkbConvertGetByNameComponents(False,fwant|fneed); - if (stuff->load) { - fneed|= XkmKeymapRequired; - fwant|= XkmKeymapLegal; - } - if ((fwant|fneed)&XkmSymbolsMask) { - fneed|= XkmKeyNamesIndex|XkmTypesIndex; - fwant|= XkmIndicatorsIndex; - } - - /* We pass dev in here so we can get the old names out if needed. */ - rep.found = XkbDDXLoadKeymapByNames(dev,&names,fwant,fneed,&new, - mapFile,PATH_MAX); - rep.newKeyboard= False; - rep.pad1= rep.pad2= rep.pad3= rep.pad4= 0; - - stuff->want|= stuff->need; - if (new==NULL) - rep.reported= 0; - else { - if (stuff->load) - rep.loaded= True; - if (stuff->load || - ((rep.reported&XkbGBN_SymbolsMask) && (new->compat))) { - XkbChangesRec changes; - bzero(&changes,sizeof(changes)); - XkbUpdateDescActions(new, - new->min_key_code,XkbNumKeys(new), - &changes); - } - - if (new->map==NULL) - rep.reported&= ~(XkbGBN_SymbolsMask|XkbGBN_TypesMask); - else if (rep.reported&(XkbGBN_SymbolsMask|XkbGBN_TypesMask)) { - mrep.type= X_Reply; - mrep.deviceID = dev->id; - mrep.sequenceNumber= client->sequence; - mrep.length = ((SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply))>>2); - mrep.minKeyCode = new->min_key_code; - mrep.maxKeyCode = new->max_key_code; - mrep.present = 0; - mrep.totalSyms = mrep.totalActs = - mrep.totalKeyBehaviors= mrep.totalKeyExplicit= - mrep.totalModMapKeys= mrep.totalVModMapKeys= 0; - if (rep.reported&(XkbGBN_TypesMask|XkbGBN_ClientSymbolsMask)) { - mrep.present|= XkbKeyTypesMask; - mrep.firstType = 0; - mrep.nTypes = mrep.totalTypes= new->map->num_types; - } - else { - mrep.firstType = mrep.nTypes= 0; - mrep.totalTypes= 0; - } - if (rep.reported&XkbGBN_ClientSymbolsMask) { - mrep.present|= (XkbKeySymsMask|XkbModifierMapMask); - mrep.firstKeySym = mrep.firstModMapKey= new->min_key_code; - mrep.nKeySyms = mrep.nModMapKeys= XkbNumKeys(new); - } - else { - mrep.firstKeySym= mrep.firstModMapKey= 0; - mrep.nKeySyms= mrep.nModMapKeys= 0; - } - if (rep.reported&XkbGBN_ServerSymbolsMask) { - mrep.present|= XkbAllServerInfoMask; - mrep.virtualMods= ~0; - mrep.firstKeyAct = mrep.firstKeyBehavior = - mrep.firstKeyExplicit = new->min_key_code; - mrep.nKeyActs = mrep.nKeyBehaviors = - mrep.nKeyExplicit = XkbNumKeys(new); - mrep.firstVModMapKey= new->min_key_code; - mrep.nVModMapKeys= XkbNumKeys(new); - } - else { - mrep.virtualMods= 0; - mrep.firstKeyAct= mrep.firstKeyBehavior= - mrep.firstKeyExplicit = 0; - mrep.nKeyActs= mrep.nKeyBehaviors= mrep.nKeyExplicit= 0; - } - XkbComputeGetMapReplySize(new,&mrep); - rep.length+= SIZEOF(xGenericReply)/4+mrep.length; - } - if (new->compat==NULL) - rep.reported&= ~XkbGBN_CompatMapMask; - else if (rep.reported&XkbGBN_CompatMapMask) { - crep.type= X_Reply; - crep.deviceID= dev->id; - crep.sequenceNumber= client->sequence; - crep.length= 0; - crep.groups= XkbAllGroupsMask; - crep.firstSI= 0; - crep.nSI= crep.nTotalSI= new->compat->num_si; - XkbComputeGetCompatMapReplySize(new->compat,&crep); - rep.length+= SIZEOF(xGenericReply)/4+crep.length; - } - if (new->indicators==NULL) - rep.reported&= ~XkbGBN_IndicatorMapMask; - else if (rep.reported&XkbGBN_IndicatorMapMask) { - irep.type= X_Reply; - irep.deviceID= dev->id; - irep.sequenceNumber= client->sequence; - irep.length= 0; - irep.which= XkbAllIndicatorsMask; - XkbComputeGetIndicatorMapReplySize(new->indicators,&irep); - rep.length+= SIZEOF(xGenericReply)/4+irep.length; - } - if (new->names==NULL) - rep.reported&= ~(XkbGBN_OtherNamesMask|XkbGBN_KeyNamesMask); - else if (rep.reported&(XkbGBN_OtherNamesMask|XkbGBN_KeyNamesMask)) { - nrep.type= X_Reply; - nrep.deviceID= dev->id; - nrep.sequenceNumber= client->sequence; - nrep.length= 0; - nrep.minKeyCode= new->min_key_code; - nrep.maxKeyCode= new->max_key_code; - if (rep.reported&XkbGBN_OtherNamesMask) { - nrep.which= XkbAllNamesMask; - if (new->map!=NULL) - nrep.nTypes= new->map->num_types; - else nrep.nTypes= 0; - nrep.nKTLevels= 0; - nrep.groupNames= XkbAllGroupsMask; - nrep.virtualMods= XkbAllVirtualModsMask; - nrep.indicators= XkbAllIndicatorsMask; - nrep.nRadioGroups= new->names->num_rg; - } - else { - nrep.which= 0; - nrep.nTypes= 0; - nrep.nKTLevels= 0; - nrep.groupNames= 0; - nrep.virtualMods= 0; - nrep.indicators= 0; - nrep.nRadioGroups= 0; - } - if (rep.reported&XkbGBN_KeyNamesMask) { - nrep.which|= XkbKeyNamesMask; - nrep.firstKey= new->min_key_code; - nrep.nKeys= XkbNumKeys(new); - nrep.nKeyAliases= new->names->num_key_aliases; - if (nrep.nKeyAliases) - nrep.which|= XkbKeyAliasesMask; - } - else { - nrep.which&= ~(XkbKeyNamesMask|XkbKeyAliasesMask); - nrep.firstKey= nrep.nKeys= 0; - nrep.nKeyAliases= 0; - } - XkbComputeGetNamesReplySize(new,&nrep); - rep.length+= SIZEOF(xGenericReply)/4+nrep.length; - } - if (new->geom==NULL) - rep.reported&= ~XkbGBN_GeometryMask; - else if (rep.reported&XkbGBN_GeometryMask) { - grep.type= X_Reply; - grep.deviceID= dev->id; - grep.sequenceNumber= client->sequence; - grep.length= 0; - grep.found= True; - grep.pad= 0; - grep.widthMM= grep.heightMM= 0; - grep.nProperties= grep.nColors= grep.nShapes= 0; - grep.nSections= grep.nDoodads= 0; - grep.baseColorNdx= grep.labelColorNdx= 0; - XkbComputeGetGeometryReplySize(new->geom,&grep,None); - rep.length+= SIZEOF(xGenericReply)/4+grep.length; - } - } - - reported= rep.reported; - if ( client->swapped ) { - register int n; - swaps(&rep.sequenceNumber,n); - swapl(&rep.length,n); - swaps(&rep.found,n); - swaps(&rep.reported,n); - } - WriteToClient(client,SIZEOF(xkbGetKbdByNameReply), (char *)&rep); - if (reported&(XkbGBN_SymbolsMask|XkbGBN_TypesMask)) - XkbSendMap(client,new,&mrep); - if (reported&XkbGBN_CompatMapMask) - XkbSendCompatMap(client,new->compat,&crep); - if (reported&XkbGBN_IndicatorMapMask) - XkbSendIndicatorMap(client,new->indicators,&irep); - if (reported&(XkbGBN_KeyNamesMask|XkbGBN_OtherNamesMask)) - XkbSendNames(client,new,&nrep); - if (reported&XkbGBN_GeometryMask) - XkbSendGeometry(client,new->geom,&grep,False); - if (rep.loaded) { - XkbDescPtr old_xkb; - xkbNewKeyboardNotify nkn; - int i,nG,nTG; - old_xkb= xkb; - xkb= new; - dev->key->xkbInfo->desc= xkb; - new= old_xkb; /* so it'll get freed automatically */ - - *xkb->ctrls= *old_xkb->ctrls; - for (nG=nTG=0,i=xkb->min_key_code;i<=xkb->max_key_code;i++) { - nG= XkbKeyNumGroups(xkb,i); - if (nG>=XkbNumKbdGroups) { - nTG= XkbNumKbdGroups; - break; - } - if (nG>nTG) { - nTG= nG; - } - } - xkb->ctrls->num_groups= nTG; - - for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) { - if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) { - if (tmpd != dev) - XkbCopyDeviceKeymap(tmpd, dev); - - if (tmpd->kbdfeed && tmpd->kbdfeed->xkb_sli) { - old_sli = tmpd->kbdfeed->xkb_sli; - tmpd->kbdfeed->xkb_sli = NULL; - sli = XkbAllocSrvLedInfo(tmpd, tmpd->kbdfeed, NULL, 0); - if (sli) { - sli->explicitState = old_sli->explicitState; - sli->effectiveState = old_sli->effectiveState; - } - tmpd->kbdfeed->xkb_sli = sli; - XkbFreeSrvLedInfo(old_sli); - } - } - } - - nkn.deviceID= nkn.oldDeviceID= dev->id; - nkn.minKeyCode= new->min_key_code; - nkn.maxKeyCode= new->max_key_code; - nkn.oldMinKeyCode= xkb->min_key_code; - nkn.oldMaxKeyCode= xkb->max_key_code; - nkn.requestMajor= XkbReqCode; - nkn.requestMinor= X_kbGetKbdByName; - nkn.changed= XkbNKN_KeycodesMask; - if (geom_changed) - nkn.changed|= XkbNKN_GeometryMask; - XkbSendNewKeyboardNotify(dev,&nkn); - - if (!IsMaster(dev) && dev->u.master) - { - DeviceIntPtr master = dev->u.master; - if (master->u.lastSlave == dev) - { - XkbCopyDeviceKeymap(dev->u.master, dev); - XkbSendNewKeyboardNotify(dev,&nkn); - } - } - } - if ((new!=NULL)&&(new!=xkb)) { - XkbFreeKeyboard(new,XkbAllComponentsMask,True); - new= NULL; - } - if (names.keycodes) { xfree(names.keycodes); names.keycodes= NULL; } - if (names.types) { xfree(names.types); names.types= NULL; } - if (names.compat) { xfree(names.compat); names.compat= NULL; } - if (names.symbols) { xfree(names.symbols); names.symbols= NULL; } - if (names.geometry) { xfree(names.geometry); names.geometry= NULL; } - return client->noClientException; -} - -/***====================================================================***/ - -static int -ComputeDeviceLedInfoSize( DeviceIntPtr dev, - unsigned int what, - XkbSrvLedInfoPtr sli) -{ -int nNames,nMaps; -register unsigned n,bit; - - if (sli==NULL) - return 0; - nNames= nMaps= 0; - if ((what&XkbXI_IndicatorNamesMask)==0) - sli->namesPresent= 0; - if ((what&XkbXI_IndicatorMapsMask)==0) - sli->mapsPresent= 0; - - for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) { - if (sli->names && sli->names[n]!=None) { - sli->namesPresent|= bit; - nNames++; - } - if (sli->maps && XkbIM_InUse(&sli->maps[n])) { - sli->mapsPresent|= bit; - nMaps++; - } - } - return (nNames*4)+(nMaps*SIZEOF(xkbIndicatorMapWireDesc)); -} - -static int -CheckDeviceLedFBs( DeviceIntPtr dev, - int class, - int id, - xkbGetDeviceInfoReply * rep, - ClientPtr client) -{ -int nFBs= 0; -int length= 0; -Bool classOk; - - if (class==XkbDfltXIClass) { - if (dev->kbdfeed) class= KbdFeedbackClass; - else if (dev->leds) class= LedFeedbackClass; - else { - client->errorValue= _XkbErrCode2(XkbErr_BadClass,class); - return XkbKeyboardErrorCode; - } - } - classOk= False; - if ((dev->kbdfeed)&&((class==KbdFeedbackClass)||(class==XkbAllXIClasses))) { - KbdFeedbackPtr kf; - classOk= True; - for (kf= dev->kbdfeed;(kf);kf=kf->next) { - if ((id!=XkbAllXIIds)&&(id!=XkbDfltXIId)&&(id!=kf->ctrl.id)) - continue; - nFBs++; - length+= SIZEOF(xkbDeviceLedsWireDesc); - if (!kf->xkb_sli) - kf->xkb_sli= XkbAllocSrvLedInfo(dev,kf,NULL,0); - length+= ComputeDeviceLedInfoSize(dev,rep->present,kf->xkb_sli); - if (id!=XkbAllXIIds) - break; - } - } - if ((dev->leds)&&((class==LedFeedbackClass)||(class==XkbAllXIClasses))) { - LedFeedbackPtr lf; - classOk= True; - for (lf= dev->leds;(lf);lf=lf->next) { - if ((id!=XkbAllXIIds)&&(id!=XkbDfltXIId)&&(id!=lf->ctrl.id)) - continue; - nFBs++; - length+= SIZEOF(xkbDeviceLedsWireDesc); - if (!lf->xkb_sli) - lf->xkb_sli= XkbAllocSrvLedInfo(dev,NULL,lf,0); - length+= ComputeDeviceLedInfoSize(dev,rep->present,lf->xkb_sli); - if (id!=XkbAllXIIds) - break; - } - } - if (nFBs>0) { - rep->nDeviceLedFBs= nFBs; - rep->length+= (length/4); - return Success; - } - if (classOk) client->errorValue= _XkbErrCode2(XkbErr_BadId,id); - else client->errorValue= _XkbErrCode2(XkbErr_BadClass,class); - return XkbKeyboardErrorCode; -} - -static int -SendDeviceLedInfo( XkbSrvLedInfoPtr sli, - ClientPtr client) -{ -xkbDeviceLedsWireDesc wire; -int length; - - length= 0; - wire.ledClass= sli->class; - wire.ledID= sli->id; - wire.namesPresent= sli->namesPresent; - wire.mapsPresent= sli->mapsPresent; - wire.physIndicators= sli->physIndicators; - wire.state= sli->effectiveState; - if (client->swapped) { - register int n; - swaps(&wire.ledClass,n); - swaps(&wire.ledID,n); - swapl(&wire.namesPresent,n); - swapl(&wire.mapsPresent,n); - swapl(&wire.physIndicators,n); - swapl(&wire.state,n); - } - WriteToClient(client,SIZEOF(xkbDeviceLedsWireDesc),(char *)&wire); - length+= SIZEOF(xkbDeviceLedsWireDesc); - if (sli->namesPresent|sli->mapsPresent) { - register unsigned i,bit; - if (sli->namesPresent) { - CARD32 awire; - for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - if (sli->namesPresent&bit) { - awire= (CARD32)sli->names[i]; - if (client->swapped) { - register int n; - swapl(&awire,n); - } - WriteToClient(client,4,(char *)&awire); - length+= 4; - } - } - } - if (sli->mapsPresent) { - for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) { - xkbIndicatorMapWireDesc iwire; - if (sli->mapsPresent&bit) { - iwire.flags= sli->maps[i].flags; - iwire.whichGroups= sli->maps[i].which_groups; - iwire.groups= sli->maps[i].groups; - iwire.whichMods= sli->maps[i].which_mods; - iwire.mods= sli->maps[i].mods.mask; - iwire.realMods= sli->maps[i].mods.real_mods; - iwire.virtualMods= sli->maps[i].mods.vmods; - iwire.ctrls= sli->maps[i].ctrls; - if (client->swapped) { - register int n; - swaps(&iwire.virtualMods,n); - swapl(&iwire.ctrls,n); - } - WriteToClient(client,SIZEOF(xkbIndicatorMapWireDesc), - (char *)&iwire); - length+= SIZEOF(xkbIndicatorMapWireDesc); - } - } - } - } - return length; -} - -static int -SendDeviceLedFBs( DeviceIntPtr dev, - int class, - int id, - unsigned wantLength, - ClientPtr client) -{ -int length= 0; - - if (class==XkbDfltXIClass) { - if (dev->kbdfeed) class= KbdFeedbackClass; - else if (dev->leds) class= LedFeedbackClass; - } - if ((dev->kbdfeed)&& - ((class==KbdFeedbackClass)||(class==XkbAllXIClasses))) { - KbdFeedbackPtr kf; - for (kf= dev->kbdfeed;(kf);kf=kf->next) { - if ((id==XkbAllXIIds)||(id==XkbDfltXIId)||(id==kf->ctrl.id)) { - length+= SendDeviceLedInfo(kf->xkb_sli,client); - if (id!=XkbAllXIIds) - break; - } - } - } - if ((dev->leds)&& - ((class==LedFeedbackClass)||(class==XkbAllXIClasses))) { - LedFeedbackPtr lf; - for (lf= dev->leds;(lf);lf=lf->next) { - if ((id==XkbAllXIIds)||(id==XkbDfltXIId)||(id==lf->ctrl.id)) { - length+= SendDeviceLedInfo(lf->xkb_sli,client); - if (id!=XkbAllXIIds) - break; - } - } - } - if (length==wantLength) - return Success; - else return BadLength; -} - -int -ProcXkbGetDeviceInfo(ClientPtr client) -{ -DeviceIntPtr dev; -xkbGetDeviceInfoReply rep; -int status,nDeviceLedFBs; -unsigned length,nameLen; -CARD16 ledClass,ledID; -unsigned wanted; -char * str; - - REQUEST(xkbGetDeviceInfoReq); - REQUEST_SIZE_MATCH(xkbGetDeviceInfoReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - wanted= stuff->wanted; - - CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess); - CHK_MASK_LEGAL(0x01,wanted,XkbXI_AllDeviceFeaturesMask); - - if ((!dev->button)||((stuff->nBtns<1)&&(!stuff->allBtns))) - wanted&= ~XkbXI_ButtonActionsMask; - if ((!dev->kbdfeed)&&(!dev->leds)) - wanted&= ~XkbXI_IndicatorsMask; - - nameLen= XkbSizeCountedString(dev->name); - bzero((char *)&rep,SIZEOF(xkbGetDeviceInfoReply)); - rep.type = X_Reply; - rep.deviceID= dev->id; - rep.sequenceNumber = client->sequence; - rep.length = nameLen/4; - rep.present = wanted; - rep.supported = XkbXI_AllDeviceFeaturesMask; - rep.unsupported = 0; - rep.firstBtnWanted = rep.nBtnsWanted = 0; - rep.firstBtnRtrn = rep.nBtnsRtrn = 0; - if (dev->button) - rep.totalBtns= dev->button->numButtons; - else rep.totalBtns= 0; - rep.devType= dev->xinput_type; - rep.hasOwnState= (dev->key && dev->key->xkbInfo); - rep.nDeviceLedFBs = 0; - if (dev->kbdfeed) rep.dfltKbdFB= dev->kbdfeed->ctrl.id; - else rep.dfltKbdFB= XkbXINone; - if (dev->leds) rep.dfltLedFB= dev->leds->ctrl.id; - else rep.dfltLedFB= XkbXINone; - - ledClass= stuff->ledClass; - ledID= stuff->ledID; - - rep.firstBtnWanted= rep.nBtnsWanted= 0; - rep.firstBtnRtrn= rep.nBtnsRtrn= 0; - if (wanted&XkbXI_ButtonActionsMask) { - if (stuff->allBtns) { - stuff->firstBtn= 0; - stuff->nBtns= dev->button->numButtons; - } - - if ((stuff->firstBtn+stuff->nBtns)>dev->button->numButtons) { - client->errorValue = _XkbErrCode4(0x02,dev->button->numButtons, - stuff->firstBtn, - stuff->nBtns); - return BadValue; - } - else { - rep.firstBtnWanted= stuff->firstBtn; - rep.nBtnsWanted= stuff->nBtns; - if (dev->button->xkb_acts!=NULL) { - XkbAction *act; - register int i; - - rep.firstBtnRtrn= stuff->firstBtn; - rep.nBtnsRtrn= stuff->nBtns; - act= &dev->button->xkb_acts[rep.firstBtnWanted]; - for (i=0;i<rep.nBtnsRtrn;i++,act++) { - if (act->type!=XkbSA_NoAction) - break; - } - rep.firstBtnRtrn+= i; - rep.nBtnsRtrn-= i; - act= &dev->button->xkb_acts[rep.firstBtnRtrn+rep.nBtnsRtrn-1]; - for (i=0;i<rep.nBtnsRtrn;i++,act--) { - if (act->type!=XkbSA_NoAction) - break; - } - rep.nBtnsRtrn-= i; - } - rep.length+= (rep.nBtnsRtrn*SIZEOF(xkbActionWireDesc))/4; - } - } - - if (wanted&XkbXI_IndicatorsMask) { - status= CheckDeviceLedFBs(dev,ledClass,ledID,&rep,client); - if (status!=Success) - return status; - } - length= rep.length*4; - nDeviceLedFBs = rep.nDeviceLedFBs; - if (client->swapped) { - register int n; - swaps(&rep.sequenceNumber,n); - swapl(&rep.length,n); - swaps(&rep.present,n); - swaps(&rep.supported,n); - swaps(&rep.unsupported,n); - swaps(&rep.nDeviceLedFBs,n); - swapl(&rep.type,n); - } - WriteToClient(client,SIZEOF(xkbGetDeviceInfoReply), (char *)&rep); - - str= xalloc(nameLen); - if (!str) - return BadAlloc; - XkbWriteCountedString(str,dev->name,client->swapped); - WriteToClient(client,nameLen,str); - xfree(str); - length-= nameLen; - - if (rep.nBtnsRtrn>0) { - int sz; - xkbActionWireDesc * awire; - sz= rep.nBtnsRtrn*SIZEOF(xkbActionWireDesc); - awire= (xkbActionWireDesc *)&dev->button->xkb_acts[rep.firstBtnRtrn]; - WriteToClient(client,sz,(char *)awire); - length-= sz; - } - if (nDeviceLedFBs>0) { - status= SendDeviceLedFBs(dev,ledClass,ledID,length,client); - if (status!=Success) - return status; - } - else if (length!=0) { - ErrorF("[xkb] Internal Error! BadLength in ProcXkbGetDeviceInfo\n"); - ErrorF("[xkb] Wrote %d fewer bytes than expected\n",length); - return BadLength; - } - return client->noClientException; -} - -static char * -CheckSetDeviceIndicators( char * wire, - DeviceIntPtr dev, - int num, - int * status_rtrn, - ClientPtr client) -{ -xkbDeviceLedsWireDesc * ledWire; -int i; -XkbSrvLedInfoPtr sli; - - ledWire= (xkbDeviceLedsWireDesc *)wire; - for (i=0;i<num;i++) { - if (client->swapped) { - register int n; - swaps(&ledWire->ledClass,n); - swaps(&ledWire->ledID,n); - swapl(&ledWire->namesPresent,n); - swapl(&ledWire->mapsPresent,n); - swapl(&ledWire->physIndicators,n); - } - - sli= XkbFindSrvLedInfo(dev,ledWire->ledClass,ledWire->ledID, - XkbXI_IndicatorsMask); - if (sli!=NULL) { - register int n; - register unsigned bit; - int nMaps,nNames; - CARD32 *atomWire; - xkbIndicatorMapWireDesc *mapWire; - - nMaps= nNames= 0; - for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) { - if (ledWire->namesPresent&bit) - nNames++; - if (ledWire->mapsPresent&bit) - nMaps++; - } - atomWire= (CARD32 *)&ledWire[1]; - if (nNames>0) { - for (n=0;n<nNames;n++) { - if (client->swapped) { - register int t; - swapl(atomWire,t); - } - CHK_ATOM_OR_NONE3(((Atom)(*atomWire)),client->errorValue, - *status_rtrn,NULL); - atomWire++; - } - } - mapWire= (xkbIndicatorMapWireDesc *)atomWire; - if (nMaps>0) { - for (n=0;n<nMaps;n++) { - if (client->swapped) { - register int t; - swaps(&mapWire->virtualMods,t); - swapl(&mapWire->ctrls,t); - } - CHK_MASK_LEGAL3(0x21,mapWire->whichGroups, - XkbIM_UseAnyGroup, - client->errorValue, - *status_rtrn,NULL); - CHK_MASK_LEGAL3(0x22,mapWire->whichMods,XkbIM_UseAnyMods, - client->errorValue, - *status_rtrn,NULL); - mapWire++; - } - } - ledWire= (xkbDeviceLedsWireDesc *)mapWire; - } - else { - /* SHOULD NEVER HAPPEN */ - return (char *)ledWire; - } - } - return (char *)ledWire; -} - -static char * -SetDeviceIndicators( char * wire, - DeviceIntPtr dev, - unsigned changed, - int num, - int * status_rtrn, - ClientPtr client, - xkbExtensionDeviceNotify *ev) -{ -xkbDeviceLedsWireDesc * ledWire; -int i; -XkbEventCauseRec cause; -unsigned namec,mapc,statec; -xkbExtensionDeviceNotify ed; -XkbChangesRec changes; -DeviceIntPtr kbd; - - bzero((char *)&ed,sizeof(xkbExtensionDeviceNotify)); - bzero((char *)&changes,sizeof(XkbChangesRec)); - XkbSetCauseXkbReq(&cause,X_kbSetDeviceInfo,client); - ledWire= (xkbDeviceLedsWireDesc *)wire; - for (i=0;i<num;i++) { - register int n; - register unsigned bit; - CARD32 * atomWire; - xkbIndicatorMapWireDesc * mapWire; - XkbSrvLedInfoPtr sli; - - namec= mapc= statec= 0; - sli= XkbFindSrvLedInfo(dev,ledWire->ledClass,ledWire->ledID, - XkbXI_IndicatorMapsMask); - if (!sli) { - /* SHOULD NEVER HAPPEN!! */ - return (char *)ledWire; - } - - atomWire= (CARD32 *)&ledWire[1]; - if (changed&XkbXI_IndicatorNamesMask) { - namec= sli->namesPresent|ledWire->namesPresent; - bzero((char *)sli->names,XkbNumIndicators*sizeof(Atom)); - } - if (ledWire->namesPresent) { - sli->namesPresent= ledWire->namesPresent; - bzero((char *)sli->names,XkbNumIndicators*sizeof(Atom)); - for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) { - if (ledWire->namesPresent&bit) { - sli->names[n]= (Atom)*atomWire; - if (sli->names[n]==None) - ledWire->namesPresent&= ~bit; - atomWire++; - } - } - } - mapWire= (xkbIndicatorMapWireDesc *)atomWire; - if (changed&XkbXI_IndicatorMapsMask) { - mapc= sli->mapsPresent|ledWire->mapsPresent; - sli->mapsPresent= ledWire->mapsPresent; - bzero((char*)sli->maps,XkbNumIndicators*sizeof(XkbIndicatorMapRec)); - } - if (ledWire->mapsPresent) { - for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) { - if (ledWire->mapsPresent&bit) { - sli->maps[n].flags= mapWire->flags; - sli->maps[n].which_groups= mapWire->whichGroups; - sli->maps[n].groups= mapWire->groups; - sli->maps[n].which_mods= mapWire->whichMods; - sli->maps[n].mods.mask= mapWire->mods; - sli->maps[n].mods.real_mods=mapWire->realMods; - sli->maps[n].mods.vmods= mapWire->virtualMods; - sli->maps[n].ctrls= mapWire->ctrls; - mapWire++; - } - } - } - if (changed&XkbXI_IndicatorStateMask) { - statec= sli->effectiveState^ledWire->state; - sli->explicitState&= ~statec; - sli->explicitState|= (ledWire->state&statec); - } - if (namec) - XkbApplyLedNameChanges(dev,sli,namec,&ed,&changes,&cause); - if (mapc) - XkbApplyLedMapChanges(dev,sli,mapc,&ed,&changes,&cause); - if (statec) - XkbApplyLedStateChanges(dev,sli,statec,&ed,&changes,&cause); - - kbd= dev; - if ((sli->flags&XkbSLI_HasOwnState)==0) - kbd = inputInfo.keyboard; - - XkbFlushLedEvents(dev,kbd,sli,&ed,&changes,&cause); - ledWire= (xkbDeviceLedsWireDesc *)mapWire; - } - return (char *)ledWire; -} - - -static int -_XkbSetDeviceInfo(ClientPtr client, DeviceIntPtr dev, - xkbSetDeviceInfoReq *stuff) -{ - char *wire; - - wire= (char *)&stuff[1]; - if (stuff->change&XkbXI_ButtonActionsMask) { - if (!dev->button) { - client->errorValue = _XkbErrCode2(XkbErr_BadClass,ButtonClass); - return XkbKeyboardErrorCode; - } - if ((stuff->firstBtn+stuff->nBtns)>dev->button->numButtons) { - client->errorValue= _XkbErrCode4(0x02,stuff->firstBtn,stuff->nBtns, - dev->button->numButtons); - return BadMatch; - } - wire+= (stuff->nBtns*SIZEOF(xkbActionWireDesc)); - } - if (stuff->change&XkbXI_IndicatorsMask) { - int status= Success; - wire= CheckSetDeviceIndicators(wire,dev,stuff->nDeviceLedFBs, - &status,client); - if (status!=Success) - return status; - } - if (((wire-((char *)stuff))/4)!=stuff->length) - return BadLength; - - return Success; -} - -static int -_XkbSetDeviceInfoCheck(ClientPtr client, DeviceIntPtr dev, - xkbSetDeviceInfoReq *stuff) -{ - char *wire; - xkbExtensionDeviceNotify ed; - - bzero((char *)&ed,SIZEOF(xkbExtensionDeviceNotify)); - ed.deviceID= dev->id; - wire= (char *)&stuff[1]; - if (stuff->change&XkbXI_ButtonActionsMask) { - int nBtns,sz,i; - XkbAction * acts; - DeviceIntPtr kbd; - - nBtns= dev->button->numButtons; - acts= dev->button->xkb_acts; - if (acts==NULL) { - acts= _XkbTypedCalloc(nBtns,XkbAction); - if (!acts) - return BadAlloc; - dev->button->xkb_acts= acts; - } - sz= stuff->nBtns*SIZEOF(xkbActionWireDesc); - memcpy((char *)&acts[stuff->firstBtn],(char *)wire,sz); - wire+= sz; - ed.reason|= XkbXI_ButtonActionsMask; - ed.firstBtn= stuff->firstBtn; - ed.nBtns= stuff->nBtns; - - if (dev->key) kbd= dev; - else kbd= inputInfo.keyboard; - acts= &dev->button->xkb_acts[stuff->firstBtn]; - for (i=0;i<stuff->nBtns;i++,acts++) { - if (acts->type!=XkbSA_NoAction) - XkbSetActionKeyMods(kbd->key->xkbInfo->desc,acts,0); - } - } - if (stuff->change&XkbXI_IndicatorsMask) { - int status= Success; - wire= SetDeviceIndicators(wire,dev,stuff->change, - stuff->nDeviceLedFBs, &status,client,&ed); - if (status!=Success) - return status; - } - if ((stuff->change)&&(ed.reason)) - XkbSendExtensionDeviceNotify(dev,client,&ed); - return Success; -} - -int -ProcXkbSetDeviceInfo(ClientPtr client) -{ - DeviceIntPtr dev; - int rc; - - REQUEST(xkbSetDeviceInfoReq); - REQUEST_AT_LEAST_SIZE(xkbSetDeviceInfoReq); - - if (!(client->xkbClientFlags&_XkbClientInitialized)) - return BadAccess; - - CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess); - CHK_MASK_LEGAL(0x01,stuff->change,XkbXI_AllFeaturesMask); - - rc = _XkbSetDeviceInfoCheck(client, dev, stuff); - - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd || stuff->deviceSpec == XkbUseCorePtr) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if (((other != dev) && !IsMaster(other) && (other->u.master == dev)) && - ((stuff->deviceSpec == XkbUseCoreKbd && other->key) || - (stuff->deviceSpec == XkbUseCorePtr && other->button))) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - rc = _XkbSetDeviceInfoCheck(client, other, stuff); - if (rc != Success) - return rc; - } - } - } - } - - /* checks done, apply */ - rc = _XkbSetDeviceInfo(client, dev, stuff); - if (rc != Success) - return rc; - - if (stuff->deviceSpec == XkbUseCoreKbd || stuff->deviceSpec == XkbUseCorePtr) - { - DeviceIntPtr other; - for (other = inputInfo.devices; other; other = other->next) - { - if (((other != dev) && !IsMaster(other) && (other->u.master == dev)) && - ((stuff->deviceSpec == XkbUseCoreKbd && other->key) || - (stuff->deviceSpec == XkbUseCorePtr && other->button))) - { - rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess); - if (rc == Success) - { - rc = _XkbSetDeviceInfo(client, other, stuff); - if (rc != Success) - return rc; - } - } - } - } - - return client->noClientException; -} - -/***====================================================================***/ - -int -ProcXkbSetDebuggingFlags(ClientPtr client) -{ -CARD32 newFlags,newCtrls,extraLength; -xkbSetDebuggingFlagsReply rep; -int rc; - - REQUEST(xkbSetDebuggingFlagsReq); - REQUEST_AT_LEAST_SIZE(xkbSetDebuggingFlagsReq); - - rc = XaceHook(XACE_SERVER_ACCESS, client, DixDebugAccess); - if (rc != Success) - return rc; - - newFlags= xkbDebugFlags&(~stuff->affectFlags); - newFlags|= (stuff->flags&stuff->affectFlags); - newCtrls= xkbDebugCtrls&(~stuff->affectCtrls); - newCtrls|= (stuff->ctrls&stuff->affectCtrls); - if (xkbDebugFlags || newFlags || stuff->msgLength) { - ErrorF("[xkb] XkbDebug: Setting debug flags to 0x%lx\n",(long)newFlags); - if (newCtrls!=xkbDebugCtrls) - ErrorF("[xkb] XkbDebug: Setting debug controls to 0x%lx\n",(long)newCtrls); - } - extraLength= (stuff->length<<2)-sz_xkbSetDebuggingFlagsReq; - if (stuff->msgLength>0) { - char *msg; - if (extraLength<XkbPaddedSize(stuff->msgLength)) { - ErrorF("[xkb] XkbDebug: msgLength= %d, length= %ld (should be %d)\n", - stuff->msgLength,(long)extraLength, - XkbPaddedSize(stuff->msgLength)); - return BadLength; - } - msg= (char *)&stuff[1]; - if (msg[stuff->msgLength-1]!='\0') { - ErrorF("[xkb] XkbDebug: message not null-terminated\n"); - return BadValue; - } - ErrorF("[xkb] XkbDebug: %s\n",msg); - } - xkbDebugFlags = newFlags; - xkbDebugCtrls = newCtrls; - - rep.type= X_Reply; - rep.length = 0; - rep.sequenceNumber = client->sequence; - rep.currentFlags = newFlags; - rep.currentCtrls = newCtrls; - rep.supportedFlags = ~0; - rep.supportedCtrls = ~0; - if ( client->swapped ) { - register int n; - swaps(&rep.sequenceNumber, n); - swapl(&rep.currentFlags, n); - swapl(&rep.currentCtrls, n); - swapl(&rep.supportedFlags, n); - swapl(&rep.supportedCtrls, n); - } - WriteToClient(client,SIZEOF(xkbSetDebuggingFlagsReply), (char *)&rep); - return client->noClientException; -} - -/***====================================================================***/ - -static int -ProcXkbDispatch (ClientPtr client) -{ - REQUEST(xReq); - switch (stuff->data) - { - case X_kbUseExtension: - return ProcXkbUseExtension(client); - case X_kbSelectEvents: - return ProcXkbSelectEvents(client); - case X_kbBell: - return ProcXkbBell(client); - case X_kbGetState: - return ProcXkbGetState(client); - case X_kbLatchLockState: - return ProcXkbLatchLockState(client); - case X_kbGetControls: - return ProcXkbGetControls(client); - case X_kbSetControls: - return ProcXkbSetControls(client); - case X_kbGetMap: - return ProcXkbGetMap(client); - case X_kbSetMap: - return ProcXkbSetMap(client); - case X_kbGetCompatMap: - return ProcXkbGetCompatMap(client); - case X_kbSetCompatMap: - return ProcXkbSetCompatMap(client); - case X_kbGetIndicatorState: - return ProcXkbGetIndicatorState(client); - case X_kbGetIndicatorMap: - return ProcXkbGetIndicatorMap(client); - case X_kbSetIndicatorMap: - return ProcXkbSetIndicatorMap(client); - case X_kbGetNamedIndicator: - return ProcXkbGetNamedIndicator(client); - case X_kbSetNamedIndicator: - return ProcXkbSetNamedIndicator(client); - case X_kbGetNames: - return ProcXkbGetNames(client); - case X_kbSetNames: - return ProcXkbSetNames(client); - case X_kbGetGeometry: - return ProcXkbGetGeometry(client); - case X_kbSetGeometry: - return ProcXkbSetGeometry(client); - case X_kbPerClientFlags: - return ProcXkbPerClientFlags(client); - case X_kbListComponents: - return ProcXkbListComponents(client); - case X_kbGetKbdByName: - return ProcXkbGetKbdByName(client); - case X_kbGetDeviceInfo: - return ProcXkbGetDeviceInfo(client); - case X_kbSetDeviceInfo: - return ProcXkbSetDeviceInfo(client); - case X_kbSetDebuggingFlags: - return ProcXkbSetDebuggingFlags(client); - default: - return BadRequest; - } -} - -static int -XkbClientGone(pointer data,XID id) -{ - DevicePtr pXDev = (DevicePtr)data; - - if (!XkbRemoveResourceClient(pXDev,id)) { - ErrorF("[xkb] Internal Error! bad RemoveResourceClient in XkbClientGone\n"); - } - return 1; -} - -void -XkbExtensionInit(void) -{ - ExtensionEntry *extEntry; - - if ((extEntry = AddExtension(XkbName, XkbNumberEvents, XkbNumberErrors, - ProcXkbDispatch, SProcXkbDispatch, - NULL, StandardMinorOpcode))) { - XkbReqCode = (unsigned char)extEntry->base; - XkbEventBase = (unsigned char)extEntry->eventBase; - XkbErrorBase = (unsigned char)extEntry->errorBase; - XkbKeyboardErrorCode = XkbErrorBase+XkbKeyboard; - RT_XKBCLIENT = CreateNewResourceType(XkbClientGone); - } - return; -} - - +/************************************************************
+Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
+
+Permission to use, copy, modify, and distribute this
+software and its documentation for any purpose and without
+fee is hereby granted, 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 Silicon Graphics not be
+used in advertising or publicity pertaining to distribution
+of the software without specific prior written permission.
+Silicon Graphics makes no representation about the suitability
+of this software for any purpose. It is provided "as is"
+without any express or implied warranty.
+
+SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
+GRAPHICS 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_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdio.h>
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include "misc.h"
+#include "inputstr.h"
+#define XKBSRV_NEED_FILE_FUNCS
+#include <xkbsrv.h>
+#include "extnsionst.h"
+#include "xace.h"
+#include "xkb.h"
+#include "protocol-versions.h"
+
+#include <X11/extensions/XI.h>
+#include <X11/extensions/XKMformat.h>
+
+int XkbEventBase;
+static int XkbErrorBase;
+int XkbReqCode;
+int XkbKeyboardErrorCode;
+CARD32 xkbDebugFlags = 0;
+static CARD32 xkbDebugCtrls = 0;
+
+static RESTYPE RT_XKBCLIENT;
+
+/***====================================================================***/
+
+#define CHK_DEVICE(dev, id, client, access_mode, lf) {\
+ int why;\
+ int rc = lf(&(dev), id, client, access_mode, &why);\
+ if (rc != Success) {\
+ client->errorValue = _XkbErrCode2(why, id);\
+ return rc;\
+ }\
+}
+
+#define CHK_KBD_DEVICE(dev, id, client, mode) \
+ CHK_DEVICE(dev, id, client, mode, _XkbLookupKeyboard)
+#define CHK_LED_DEVICE(dev, id, client, mode) \
+ CHK_DEVICE(dev, id, client, mode, _XkbLookupLedDevice)
+#define CHK_BELL_DEVICE(dev, id, client, mode) \
+ CHK_DEVICE(dev, id, client, mode, _XkbLookupBellDevice)
+#define CHK_ANY_DEVICE(dev, id, client, mode) \
+ CHK_DEVICE(dev, id, client, mode, _XkbLookupAnyDevice)
+
+#define CHK_ATOM_ONLY2(a,ev,er) {\
+ if (((a)==None)||(!ValidAtom((a)))) {\
+ (ev)= (XID)(a);\
+ return er;\
+ }\
+}
+#define CHK_ATOM_ONLY(a) \
+ CHK_ATOM_ONLY2(a,client->errorValue,BadAtom)
+
+#define CHK_ATOM_OR_NONE3(a,ev,er,ret) {\
+ if (((a)!=None)&&(!ValidAtom((a)))) {\
+ (ev)= (XID)(a);\
+ (er)= BadAtom;\
+ return ret;\
+ }\
+}
+#define CHK_ATOM_OR_NONE2(a,ev,er) {\
+ if (((a)!=None)&&(!ValidAtom((a)))) {\
+ (ev)= (XID)(a);\
+ return er;\
+ }\
+}
+#define CHK_ATOM_OR_NONE(a) \
+ CHK_ATOM_OR_NONE2(a,client->errorValue,BadAtom)
+
+#define CHK_MASK_LEGAL3(err,mask,legal,ev,er,ret) {\
+ if ((mask)&(~(legal))) { \
+ (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\
+ (er)= BadValue;\
+ return ret;\
+ }\
+}
+#define CHK_MASK_LEGAL2(err,mask,legal,ev,er) {\
+ if ((mask)&(~(legal))) { \
+ (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\
+ return er;\
+ }\
+}
+#define CHK_MASK_LEGAL(err,mask,legal) \
+ CHK_MASK_LEGAL2(err,mask,legal,client->errorValue,BadValue)
+
+#define CHK_MASK_MATCH(err,affect,value) {\
+ if ((value)&(~(affect))) { \
+ client->errorValue= _XkbErrCode2((err),((value)&(~(affect))));\
+ return BadMatch;\
+ }\
+}
+#define CHK_MASK_OVERLAP(err,m1,m2) {\
+ if ((m1)&(m2)) { \
+ client->errorValue= _XkbErrCode2((err),((m1)&(m2)));\
+ return BadMatch;\
+ }\
+}
+#define CHK_KEY_RANGE2(err,first,num,x,ev,er) {\
+ if (((unsigned)(first)+(num)-1)>(x)->max_key_code) {\
+ (ev)=_XkbErrCode4(err,(first),(num),(x)->max_key_code);\
+ return er;\
+ }\
+ else if ( (first)<(x)->min_key_code ) {\
+ (ev)=_XkbErrCode3(err+1,(first),xkb->min_key_code);\
+ return er;\
+ }\
+}
+#define CHK_KEY_RANGE(err,first,num,x) \
+ CHK_KEY_RANGE2(err,first,num,x,client->errorValue,BadValue)
+
+#define CHK_REQ_KEY_RANGE2(err,first,num,r,ev,er) {\
+ if (((unsigned)(first)+(num)-1)>(r)->maxKeyCode) {\
+ (ev)=_XkbErrCode4(err,(first),(num),(r)->maxKeyCode);\
+ return er;\
+ }\
+ else if ( (first)<(r)->minKeyCode ) {\
+ (ev)=_XkbErrCode3(err+1,(first),(r)->minKeyCode);\
+ return er;\
+ }\
+}
+#define CHK_REQ_KEY_RANGE(err,first,num,r) \
+ CHK_REQ_KEY_RANGE2(err,first,num,r,client->errorValue,BadValue)
+
+/***====================================================================***/
+
+int
+ProcXkbUseExtension(ClientPtr client)
+{
+ REQUEST(xkbUseExtensionReq);
+ xkbUseExtensionReply rep;
+ register int n;
+ int supported;
+
+ REQUEST_SIZE_MATCH(xkbUseExtensionReq);
+ if (stuff->wantedMajor != SERVER_XKB_MAJOR_VERSION) {
+ /* pre-release version 0.65 is compatible with 1.00 */
+ supported= ((SERVER_XKB_MAJOR_VERSION==1)&&
+ (stuff->wantedMajor==0)&&(stuff->wantedMinor==65));
+ }
+ else supported = 1;
+
+ if ((supported) && (!(client->xkbClientFlags&_XkbClientInitialized))) {
+ client->xkbClientFlags= _XkbClientInitialized;
+ client->vMajor= stuff->wantedMajor;
+ client->vMinor= stuff->wantedMinor;
+ }
+ else if (xkbDebugFlags&0x1) {
+ ErrorF("[xkb] Rejecting client %d (0x%lx) (wants %d.%02d, have %d.%02d)\n",
+ client->index,
+ (long)client->clientAsMask,
+ stuff->wantedMajor,stuff->wantedMinor,
+ SERVER_XKB_MAJOR_VERSION,SERVER_XKB_MINOR_VERSION);
+ }
+ memset(&rep, 0, sizeof(xkbUseExtensionReply));
+ rep.type = X_Reply;
+ rep.supported = supported;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.serverMajor = SERVER_XKB_MAJOR_VERSION;
+ rep.serverMinor = SERVER_XKB_MINOR_VERSION;
+ if ( client->swapped ) {
+ swaps(&rep.sequenceNumber, n);
+ swaps(&rep.serverMajor, n);
+ swaps(&rep.serverMinor, n);
+ }
+ WriteToClient(client,SIZEOF(xkbUseExtensionReply), (char *)&rep);
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbSelectEvents(ClientPtr client)
+{
+ unsigned legal;
+ DeviceIntPtr dev;
+ XkbInterestPtr masks;
+ REQUEST(xkbSelectEventsReq);
+
+ REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixUseAccess);
+
+ if (((stuff->affectWhich&XkbMapNotifyMask)!=0)&&(stuff->affectMap)) {
+ client->mapNotifyMask&= ~stuff->affectMap;
+ client->mapNotifyMask|= (stuff->affectMap&stuff->map);
+ }
+ if ((stuff->affectWhich&(~XkbMapNotifyMask))==0)
+ return client->noClientException;
+
+ masks = XkbFindClientResource((DevicePtr)dev,client);
+ if (!masks){
+ XID id = FakeClientID(client->index);
+ AddResource(id,RT_XKBCLIENT,dev);
+ masks= XkbAddClientResource((DevicePtr)dev,client,id);
+ }
+ if (masks) {
+ union {
+ CARD8 *c8;
+ CARD16 *c16;
+ CARD32 *c32;
+ } from,to;
+ register unsigned bit,ndx,maskLeft,dataLeft,size;
+
+ from.c8= (CARD8 *)&stuff[1];
+ dataLeft= (stuff->length*4)-SIZEOF(xkbSelectEventsReq);
+ maskLeft= (stuff->affectWhich&(~XkbMapNotifyMask));
+ for (ndx=0,bit=1; (maskLeft!=0); ndx++, bit<<=1) {
+ if ((bit&maskLeft)==0)
+ continue;
+ maskLeft&= ~bit;
+ switch (ndx) {
+ case XkbNewKeyboardNotify:
+ to.c16= &client->newKeyboardNotifyMask;
+ legal= XkbAllNewKeyboardEventsMask;
+ size= 2;
+ break;
+ case XkbStateNotify:
+ to.c16= &masks->stateNotifyMask;
+ legal= XkbAllStateEventsMask;
+ size= 2;
+ break;
+ case XkbControlsNotify:
+ to.c32= &masks->ctrlsNotifyMask;
+ legal= XkbAllControlEventsMask;
+ size= 4;
+ break;
+ case XkbIndicatorStateNotify:
+ to.c32= &masks->iStateNotifyMask;
+ legal= XkbAllIndicatorEventsMask;
+ size= 4;
+ break;
+ case XkbIndicatorMapNotify:
+ to.c32= &masks->iMapNotifyMask;
+ legal= XkbAllIndicatorEventsMask;
+ size= 4;
+ break;
+ case XkbNamesNotify:
+ to.c16= &masks->namesNotifyMask;
+ legal= XkbAllNameEventsMask;
+ size= 2;
+ break;
+ case XkbCompatMapNotify:
+ to.c8= &masks->compatNotifyMask;
+ legal= XkbAllCompatMapEventsMask;
+ size= 1;
+ break;
+ case XkbBellNotify:
+ to.c8= &masks->bellNotifyMask;
+ legal= XkbAllBellEventsMask;
+ size= 1;
+ break;
+ case XkbActionMessage:
+ to.c8= &masks->actionMessageMask;
+ legal= XkbAllActionMessagesMask;
+ size= 1;
+ break;
+ case XkbAccessXNotify:
+ to.c16= &masks->accessXNotifyMask;
+ legal= XkbAllAccessXEventsMask;
+ size= 2;
+ break;
+ case XkbExtensionDeviceNotify:
+ to.c16= &masks->extDevNotifyMask;
+ legal= XkbAllExtensionDeviceEventsMask;
+ size= 2;
+ break;
+ default:
+ client->errorValue = _XkbErrCode2(33,bit);
+ return BadValue;
+ }
+
+ if (stuff->clear&bit) {
+ if (size==2) to.c16[0]= 0;
+ else if (size==4) to.c32[0]= 0;
+ else to.c8[0]= 0;
+ }
+ else if (stuff->selectAll&bit) {
+ if (size==2) to.c16[0]= ~0;
+ else if (size==4) to.c32[0]= ~0;
+ else to.c8[0]= ~0;
+ }
+ else {
+ if (dataLeft<(size*2))
+ return BadLength;
+ if (size==2) {
+ CHK_MASK_MATCH(ndx,from.c16[0],from.c16[1]);
+ CHK_MASK_LEGAL(ndx,from.c16[0],legal);
+ to.c16[0]&= ~from.c16[0];
+ to.c16[0]|= (from.c16[0]&from.c16[1]);
+ }
+ else if (size==4) {
+ CHK_MASK_MATCH(ndx,from.c32[0],from.c32[1]);
+ CHK_MASK_LEGAL(ndx,from.c32[0],legal);
+ to.c32[0]&= ~from.c32[0];
+ to.c32[0]|= (from.c32[0]&from.c32[1]);
+ }
+ else {
+ CHK_MASK_MATCH(ndx,from.c8[0],from.c8[1]);
+ CHK_MASK_LEGAL(ndx,from.c8[0],legal);
+ to.c8[0]&= ~from.c8[0];
+ to.c8[0]|= (from.c8[0]&from.c8[1]);
+ size= 2;
+ }
+ from.c8+= (size*2);
+ dataLeft-= (size*2);
+ }
+ }
+ if (dataLeft>2) {
+ ErrorF("[xkb] Extra data (%d bytes) after SelectEvents\n",dataLeft);
+ return BadLength;
+ }
+ return client->noClientException;
+ }
+ return BadAlloc;
+}
+
+/***====================================================================***/
+/**
+ * Ring a bell on the given device for the given client.
+ */
+static int
+_XkbBell(ClientPtr client, DeviceIntPtr dev, WindowPtr pWin,
+ int bellClass, int bellID, int pitch, int duration,
+ int percent, int forceSound, int eventOnly, Atom name)
+{
+ int base;
+ pointer ctrl;
+ int oldPitch, oldDuration;
+ int newPercent;
+
+ if (bellClass == KbdFeedbackClass) {
+ KbdFeedbackPtr k;
+ if (bellID==XkbDfltXIId)
+ k= dev->kbdfeed;
+ else {
+ for (k=dev->kbdfeed; k; k=k->next) {
+ if (k->ctrl.id == bellID)
+ break;
+ }
+ }
+ if (!k) {
+ client->errorValue = _XkbErrCode2(0x5,bellID);
+ return BadValue;
+ }
+ base = k->ctrl.bell;
+ ctrl = (pointer) &(k->ctrl);
+ oldPitch= k->ctrl.bell_pitch;
+ oldDuration= k->ctrl.bell_duration;
+ if (pitch!=0) {
+ if (pitch==-1)
+ k->ctrl.bell_pitch= defaultKeyboardControl.bell_pitch;
+ else k->ctrl.bell_pitch= pitch;
+ }
+ if (duration!=0) {
+ if (duration==-1)
+ k->ctrl.bell_duration= defaultKeyboardControl.bell_duration;
+ else k->ctrl.bell_duration= duration;
+ }
+ }
+ else if (bellClass == BellFeedbackClass) {
+ BellFeedbackPtr b;
+ if (bellID==XkbDfltXIId)
+ b= dev->bell;
+ else {
+ for (b=dev->bell; b; b=b->next) {
+ if (b->ctrl.id == bellID)
+ break;
+ }
+ }
+ if (!b) {
+ client->errorValue = _XkbErrCode2(0x6,bellID);
+ return BadValue;
+ }
+ base = b->ctrl.percent;
+ ctrl = (pointer) &(b->ctrl);
+ oldPitch= b->ctrl.pitch;
+ oldDuration= b->ctrl.duration;
+ if (pitch!=0) {
+ if (pitch==-1)
+ b->ctrl.pitch= defaultKeyboardControl.bell_pitch;
+ else b->ctrl.pitch= pitch;
+ }
+ if (duration!=0) {
+ if (duration==-1)
+ b->ctrl.duration= defaultKeyboardControl.bell_duration;
+ else b->ctrl.duration= duration;
+ }
+ }
+ else {
+ client->errorValue = _XkbErrCode2(0x7, bellClass);
+ return BadValue;
+ }
+
+ newPercent = (base * percent)/100;
+ if (percent < 0)
+ newPercent = base + newPercent;
+ else newPercent = base - newPercent + percent;
+
+ XkbHandleBell(forceSound, eventOnly,
+ dev, newPercent, ctrl, bellClass,
+ name, pWin, client);
+ if ((pitch!=0)||(duration!=0)) {
+ if (bellClass == KbdFeedbackClass) {
+ KbdFeedbackPtr k;
+ k= (KbdFeedbackPtr)ctrl;
+ if (pitch!=0)
+ k->ctrl.bell_pitch= oldPitch;
+ if (duration!=0)
+ k->ctrl.bell_duration= oldDuration;
+ }
+ else {
+ BellFeedbackPtr b;
+ b= (BellFeedbackPtr)ctrl;
+ if (pitch!=0)
+ b->ctrl.pitch= oldPitch;
+ if (duration!=0)
+ b->ctrl.duration= oldDuration;
+ }
+ }
+
+ return Success;
+}
+
+int
+ProcXkbBell(ClientPtr client)
+{
+ REQUEST(xkbBellReq);
+ DeviceIntPtr dev;
+ WindowPtr pWin;
+ int rc;
+
+ REQUEST_SIZE_MATCH(xkbBellReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_BELL_DEVICE(dev, stuff->deviceSpec, client, DixBellAccess);
+ CHK_ATOM_OR_NONE(stuff->name);
+
+ /* device-independent checks request for sane values */
+ if ((stuff->forceSound)&&(stuff->eventOnly)) {
+ client->errorValue=_XkbErrCode3(0x1,stuff->forceSound,stuff->eventOnly);
+ return BadMatch;
+ }
+ if (stuff->percent < -100 || stuff->percent > 100) {
+ client->errorValue = _XkbErrCode2(0x2,stuff->percent);
+ return BadValue;
+ }
+ if (stuff->duration<-1) {
+ client->errorValue = _XkbErrCode2(0x3,stuff->duration);
+ return BadValue;
+ }
+ if (stuff->pitch<-1) {
+ client->errorValue = _XkbErrCode2(0x4,stuff->pitch);
+ return BadValue;
+ }
+
+ if (stuff->bellClass == XkbDfltXIClass) {
+ if (dev->kbdfeed!=NULL)
+ stuff->bellClass= KbdFeedbackClass;
+ else stuff->bellClass= BellFeedbackClass;
+ }
+
+ if (stuff->window!=None) {
+ rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
+ if (rc != Success) {
+ client->errorValue= stuff->window;
+ return rc;
+ }
+ }
+ else pWin= NULL;
+
+ /* Client wants to ring a bell on the core keyboard?
+ Ring the bell on the core keyboard (which does nothing, but if that
+ fails the client is screwed anyway), and then on all extension devices.
+ Fail if the core keyboard fails but not the extension devices. this
+ may cause some keyboards to ding and others to stay silent. Fix
+ your client to use explicit keyboards to avoid this.
+
+ dev is the device the client requested.
+ */
+ rc = _XkbBell(client, dev, pWin, stuff->bellClass, stuff->bellID,
+ stuff->pitch, stuff->duration, stuff->percent,
+ stuff->forceSound, stuff->eventOnly, stuff->name);
+
+ if ((rc == Success) && ((stuff->deviceSpec == XkbUseCoreKbd) ||
+ (stuff->deviceSpec == XkbUseCorePtr)))
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixBellAccess);
+ if (rc == Success)
+ _XkbBell(client, other, pWin, stuff->bellClass,
+ stuff->bellID, stuff->pitch, stuff->duration,
+ stuff->percent, stuff->forceSound,
+ stuff->eventOnly, stuff->name);
+ }
+ }
+ rc = Success; /* reset to success, that's what we got for the VCK */
+ }
+
+ return rc;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbGetState(ClientPtr client)
+{
+ REQUEST(xkbGetStateReq);
+ DeviceIntPtr dev;
+ xkbGetStateReply rep;
+ XkbStateRec *xkb;
+
+ REQUEST_SIZE_MATCH(xkbGetStateReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess);
+
+ xkb= &dev->key->xkbInfo->state;
+ bzero(&rep,sizeof(xkbGetStateReply));
+ rep.type= X_Reply;
+ rep.sequenceNumber= client->sequence;
+ rep.length = 0;
+ rep.deviceID = dev->id;
+ rep.mods = XkbStateFieldFromRec(xkb) & 0xff;
+ rep.baseMods = xkb->base_mods;
+ rep.lockedMods = xkb->locked_mods;
+ rep.latchedMods = xkb->latched_mods;
+ rep.group = xkb->group;
+ rep.baseGroup = xkb->base_group;
+ rep.latchedGroup = xkb->latched_group;
+ rep.lockedGroup = xkb->locked_group;
+ rep.compatState = xkb->compat_state;
+ rep.ptrBtnState = xkb->ptr_buttons;
+ if (client->swapped) {
+ register int n;
+ swaps(&rep.sequenceNumber,n);
+ swaps(&rep.ptrBtnState,n);
+ }
+ WriteToClient(client, SIZEOF(xkbGetStateReply), (char *)&rep);
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbLatchLockState(ClientPtr client)
+{
+ int status;
+ DeviceIntPtr dev, tmpd;
+ XkbStateRec oldState,*newState;
+ CARD16 changed;
+ xkbStateNotify sn;
+ XkbEventCauseRec cause;
+
+ REQUEST(xkbLatchLockStateReq);
+ REQUEST_SIZE_MATCH(xkbLatchLockStateReq);
+
+ if (!(client->xkbClientFlags & _XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess);
+ CHK_MASK_MATCH(0x01, stuff->affectModLocks, stuff->modLocks);
+ CHK_MASK_MATCH(0x01, stuff->affectModLatches, stuff->modLatches);
+
+ status = Success;
+
+ for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) {
+ if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) {
+ if (!tmpd->key || !tmpd->key->xkbInfo)
+ continue;
+
+ oldState = tmpd->key->xkbInfo->state;
+ newState = &tmpd->key->xkbInfo->state;
+ if (stuff->affectModLocks) {
+ newState->locked_mods &= ~stuff->affectModLocks;
+ newState->locked_mods |= (stuff->affectModLocks & stuff->modLocks);
+ }
+ if (status == Success && stuff->lockGroup)
+ newState->locked_group = stuff->groupLock;
+ if (status == Success && stuff->affectModLatches)
+ status = XkbLatchModifiers(tmpd, stuff->affectModLatches,
+ stuff->modLatches);
+ if (status == Success && stuff->latchGroup)
+ status = XkbLatchGroup(tmpd, stuff->groupLatch);
+
+ if (status != Success)
+ return status;
+
+ XkbComputeDerivedState(tmpd->key->xkbInfo);
+
+ changed = XkbStateChangedFlags(&oldState, newState);
+ if (changed) {
+ sn.keycode = 0;
+ sn.eventType = 0;
+ sn.requestMajor = XkbReqCode;
+ sn.requestMinor = X_kbLatchLockState;
+ sn.changed = changed;
+ XkbSendStateNotify(tmpd, &sn);
+ changed = XkbIndicatorsToUpdate(tmpd, changed, False);
+ if (changed) {
+ XkbSetCauseXkbReq(&cause, X_kbLatchLockState, client);
+ XkbUpdateIndicators(tmpd, changed, True, NULL, &cause);
+ }
+ }
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbGetControls(ClientPtr client)
+{
+ xkbGetControlsReply rep;
+ XkbControlsPtr xkb;
+ DeviceIntPtr dev;
+ register int n;
+
+ REQUEST(xkbGetControlsReq);
+ REQUEST_SIZE_MATCH(xkbGetControlsReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+
+ xkb = dev->key->xkbInfo->desc->ctrls;
+ rep.type = X_Reply;
+ rep.length = bytes_to_int32(SIZEOF(xkbGetControlsReply)-
+ SIZEOF(xGenericReply));
+ rep.sequenceNumber = client->sequence;
+ rep.deviceID = ((DeviceIntPtr)dev)->id;
+ rep.numGroups = xkb->num_groups;
+ rep.groupsWrap = xkb->groups_wrap;
+ rep.internalMods = xkb->internal.mask;
+ rep.ignoreLockMods = xkb->ignore_lock.mask;
+ rep.internalRealMods = xkb->internal.real_mods;
+ rep.ignoreLockRealMods = xkb->ignore_lock.real_mods;
+ rep.internalVMods = xkb->internal.vmods;
+ rep.ignoreLockVMods = xkb->ignore_lock.vmods;
+ rep.enabledCtrls = xkb->enabled_ctrls;
+ rep.repeatDelay = xkb->repeat_delay;
+ rep.repeatInterval = xkb->repeat_interval;
+ rep.slowKeysDelay = xkb->slow_keys_delay;
+ rep.debounceDelay = xkb->debounce_delay;
+ rep.mkDelay = xkb->mk_delay;
+ rep.mkInterval = xkb->mk_interval;
+ rep.mkTimeToMax = xkb->mk_time_to_max;
+ rep.mkMaxSpeed = xkb->mk_max_speed;
+ rep.mkCurve = xkb->mk_curve;
+ rep.mkDfltBtn = xkb->mk_dflt_btn;
+ rep.axTimeout = xkb->ax_timeout;
+ rep.axtCtrlsMask = xkb->axt_ctrls_mask;
+ rep.axtCtrlsValues = xkb->axt_ctrls_values;
+ rep.axtOptsMask = xkb->axt_opts_mask;
+ rep.axtOptsValues = xkb->axt_opts_values;
+ rep.axOptions = xkb->ax_options;
+ memcpy(rep.perKeyRepeat,xkb->per_key_repeat,XkbPerKeyBitArraySize);
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.length,n);
+ swaps(&rep.internalVMods, n);
+ swaps(&rep.ignoreLockVMods, n);
+ swapl(&rep.enabledCtrls, n);
+ swaps(&rep.repeatDelay, n);
+ swaps(&rep.repeatInterval, n);
+ swaps(&rep.slowKeysDelay, n);
+ swaps(&rep.debounceDelay, n);
+ swaps(&rep.mkDelay, n);
+ swaps(&rep.mkInterval, n);
+ swaps(&rep.mkTimeToMax, n);
+ swaps(&rep.mkMaxSpeed, n);
+ swaps(&rep.mkCurve, n);
+ swaps(&rep.axTimeout, n);
+ swapl(&rep.axtCtrlsMask, n);
+ swapl(&rep.axtCtrlsValues, n);
+ swaps(&rep.axtOptsMask, n);
+ swaps(&rep.axtOptsValues, n);
+ swaps(&rep.axOptions, n);
+ }
+ WriteToClient(client, SIZEOF(xkbGetControlsReply), (char *)&rep);
+ return(client->noClientException);
+}
+
+int
+ProcXkbSetControls(ClientPtr client)
+{
+ DeviceIntPtr dev, tmpd;
+ XkbSrvInfoPtr xkbi;
+ XkbControlsPtr ctrl;
+ XkbControlsRec new,old;
+ xkbControlsNotify cn;
+ XkbEventCauseRec cause;
+ XkbSrvLedInfoPtr sli;
+
+ REQUEST(xkbSetControlsReq);
+ REQUEST_SIZE_MATCH(xkbSetControlsReq);
+
+ if (!(client->xkbClientFlags & _XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+ CHK_MASK_LEGAL(0x01, stuff->changeCtrls, XkbAllControlsMask);
+
+ for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) {
+ if (!tmpd->key || !tmpd->key->xkbInfo)
+ continue;
+ if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) {
+ xkbi = tmpd->key->xkbInfo;
+ ctrl = xkbi->desc->ctrls;
+ new = *ctrl;
+ XkbSetCauseXkbReq(&cause, X_kbSetControls, client);
+
+ if (stuff->changeCtrls & XkbInternalModsMask) {
+ CHK_MASK_MATCH(0x02, stuff->affectInternalMods,
+ stuff->internalMods);
+ CHK_MASK_MATCH(0x03, stuff->affectInternalVMods,
+ stuff->internalVMods);
+
+ new.internal.real_mods &= ~(stuff->affectInternalMods);
+ new.internal.real_mods |= (stuff->affectInternalMods &
+ stuff->internalMods);
+ new.internal.vmods &= ~(stuff->affectInternalVMods);
+ new.internal.vmods |= (stuff->affectInternalVMods &
+ stuff->internalVMods);
+ new.internal.mask = new.internal.real_mods |
+ XkbMaskForVMask(xkbi->desc,
+ new.internal.vmods);
+ }
+
+ if (stuff->changeCtrls & XkbIgnoreLockModsMask) {
+ CHK_MASK_MATCH(0x4, stuff->affectIgnoreLockMods,
+ stuff->ignoreLockMods);
+ CHK_MASK_MATCH(0x5, stuff->affectIgnoreLockVMods,
+ stuff->ignoreLockVMods);
+
+ new.ignore_lock.real_mods &= ~(stuff->affectIgnoreLockMods);
+ new.ignore_lock.real_mods |= (stuff->affectIgnoreLockMods &
+ stuff->ignoreLockMods);
+ new.ignore_lock.vmods &= ~(stuff->affectIgnoreLockVMods);
+ new.ignore_lock.vmods |= (stuff->affectIgnoreLockVMods &
+ stuff->ignoreLockVMods);
+ new.ignore_lock.mask = new.ignore_lock.real_mods |
+ XkbMaskForVMask(xkbi->desc,
+ new.ignore_lock.vmods);
+ }
+
+ CHK_MASK_MATCH(0x06, stuff->affectEnabledCtrls,
+ stuff->enabledCtrls);
+ if (stuff->affectEnabledCtrls) {
+ CHK_MASK_LEGAL(0x07, stuff->affectEnabledCtrls,
+ XkbAllBooleanCtrlsMask);
+
+ new.enabled_ctrls &= ~(stuff->affectEnabledCtrls);
+ new.enabled_ctrls |= (stuff->affectEnabledCtrls &
+ stuff->enabledCtrls);
+ }
+
+ if (stuff->changeCtrls & XkbRepeatKeysMask) {
+ if (stuff->repeatDelay < 1 || stuff->repeatInterval < 1) {
+ client->errorValue = _XkbErrCode3(0x08, stuff->repeatDelay,
+ stuff->repeatInterval);
+ return BadValue;
+ }
+
+ new.repeat_delay = stuff->repeatDelay;
+ new.repeat_interval = stuff->repeatInterval;
+ }
+
+ if (stuff->changeCtrls & XkbSlowKeysMask) {
+ if (stuff->slowKeysDelay < 1) {
+ client->errorValue = _XkbErrCode2(0x09,
+ stuff->slowKeysDelay);
+ return BadValue;
+ }
+
+ new.slow_keys_delay = stuff->slowKeysDelay;
+ }
+
+ if (stuff->changeCtrls & XkbBounceKeysMask) {
+ if (stuff->debounceDelay < 1) {
+ client->errorValue = _XkbErrCode2(0x0A,
+ stuff->debounceDelay);
+ return BadValue;
+ }
+
+ new.debounce_delay = stuff->debounceDelay;
+ }
+
+ if (stuff->changeCtrls & XkbMouseKeysMask) {
+ if (stuff->mkDfltBtn > XkbMaxMouseKeysBtn) {
+ client->errorValue = _XkbErrCode2(0x0B, stuff->mkDfltBtn);
+ return BadValue;
+ }
+
+ new.mk_dflt_btn = stuff->mkDfltBtn;
+ }
+
+ if (stuff->changeCtrls & XkbMouseKeysAccelMask) {
+ if (stuff->mkDelay < 1 || stuff->mkInterval < 1 ||
+ stuff->mkTimeToMax < 1 || stuff->mkMaxSpeed < 1 ||
+ stuff->mkCurve < -1000) {
+ client->errorValue = _XkbErrCode2(0x0C,0);
+ return BadValue;
+ }
+
+ new.mk_delay = stuff->mkDelay;
+ new.mk_interval = stuff->mkInterval;
+ new.mk_time_to_max = stuff->mkTimeToMax;
+ new.mk_max_speed = stuff->mkMaxSpeed;
+ new.mk_curve = stuff->mkCurve;
+ AccessXComputeCurveFactor(xkbi, &new);
+ }
+
+ if (stuff->changeCtrls & XkbGroupsWrapMask) {
+ unsigned act, num;
+
+ act = XkbOutOfRangeGroupAction(stuff->groupsWrap);
+ switch (act) {
+ case XkbRedirectIntoRange:
+ num = XkbOutOfRangeGroupNumber(stuff->groupsWrap);
+ if (num >= new.num_groups) {
+ client->errorValue = _XkbErrCode3(0x0D, new.num_groups,
+ num);
+ return BadValue;
+ }
+ case XkbWrapIntoRange:
+ case XkbClampIntoRange:
+ break;
+ default:
+ client->errorValue = _XkbErrCode2(0x0E, act);
+ return BadValue;
+ }
+
+ new.groups_wrap= stuff->groupsWrap;
+ }
+
+ CHK_MASK_LEGAL(0x0F, stuff->axOptions, XkbAX_AllOptionsMask);
+ if (stuff->changeCtrls & XkbAccessXKeysMask) {
+ new.ax_options = stuff->axOptions & XkbAX_AllOptionsMask;
+ }
+ else {
+ if (stuff->changeCtrls & XkbStickyKeysMask) {
+ new.ax_options &= ~(XkbAX_SKOptionsMask);
+ new.ax_options |= (stuff->axOptions & XkbAX_SKOptionsMask);
+ }
+
+ if (stuff->changeCtrls & XkbAccessXFeedbackMask) {
+ new.ax_options &= ~(XkbAX_FBOptionsMask);
+ new.ax_options |= (stuff->axOptions & XkbAX_FBOptionsMask);
+ }
+ }
+
+ if (stuff->changeCtrls & XkbAccessXTimeoutMask) {
+ if (stuff->axTimeout < 1) {
+ client->errorValue = _XkbErrCode2(0x10, stuff->axTimeout);
+ return BadValue;
+ }
+ CHK_MASK_MATCH(0x11, stuff->axtCtrlsMask,
+ stuff->axtCtrlsValues);
+ CHK_MASK_LEGAL(0x12, stuff->axtCtrlsMask,
+ XkbAllBooleanCtrlsMask);
+ CHK_MASK_MATCH(0x13, stuff->axtOptsMask, stuff->axtOptsValues);
+ CHK_MASK_LEGAL(0x14, stuff->axtOptsMask, XkbAX_AllOptionsMask);
+ new.ax_timeout = stuff->axTimeout;
+ new.axt_ctrls_mask = stuff->axtCtrlsMask;
+ new.axt_ctrls_values = (stuff->axtCtrlsValues &
+ stuff->axtCtrlsMask);
+ new.axt_opts_mask = stuff->axtOptsMask;
+ new.axt_opts_values = (stuff->axtOptsValues &
+ stuff->axtOptsMask);
+ }
+
+ if (stuff->changeCtrls & XkbPerKeyRepeatMask)
+ memcpy(new.per_key_repeat, stuff->perKeyRepeat,
+ XkbPerKeyBitArraySize);
+
+ old= *ctrl;
+ *ctrl= new;
+ XkbDDXChangeControls(tmpd, &old, ctrl);
+
+ if (XkbComputeControlsNotify(tmpd, &old, ctrl, &cn, False)) {
+ cn.keycode = 0;
+ cn.eventType = 0;
+ cn.requestMajor = XkbReqCode;
+ cn.requestMinor = X_kbSetControls;
+ XkbSendControlsNotify(tmpd, &cn);
+ }
+
+ sli = XkbFindSrvLedInfo(tmpd, XkbDfltXIClass, XkbDfltXIId, 0);
+ if (sli)
+ XkbUpdateIndicators(tmpd, sli->usesControls, True, NULL,
+ &cause);
+
+ /* If sticky keys were disabled, clear all locks and latches */
+ if ((old.enabled_ctrls & XkbStickyKeysMask) &&
+ !(ctrl->enabled_ctrls & XkbStickyKeysMask))
+ XkbClearAllLatchesAndLocks(tmpd, xkbi, True, &cause);
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static int
+XkbSizeKeyTypes(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ XkbKeyTypeRec *type;
+ unsigned i,len;
+
+ len= 0;
+ if (((rep->present&XkbKeyTypesMask)==0)||(rep->nTypes<1)||
+ (!xkb)||(!xkb->map)||(!xkb->map->types)) {
+ rep->present&= ~XkbKeyTypesMask;
+ rep->firstType= rep->nTypes= 0;
+ return 0;
+ }
+ type= &xkb->map->types[rep->firstType];
+ for (i=0;i<rep->nTypes;i++,type++){
+ len+= SIZEOF(xkbKeyTypeWireDesc);
+ if (type->map_count>0) {
+ len+= (type->map_count*SIZEOF(xkbKTMapEntryWireDesc));
+ if (type->preserve)
+ len+= (type->map_count*SIZEOF(xkbModsWireDesc));
+ }
+ }
+ return len;
+}
+
+static char *
+XkbWriteKeyTypes( XkbDescPtr xkb,
+ xkbGetMapReply * rep,
+ char * buf,
+ ClientPtr client)
+{
+ XkbKeyTypePtr type;
+ unsigned i;
+ xkbKeyTypeWireDesc *wire;
+
+ type= &xkb->map->types[rep->firstType];
+ for (i=0;i<rep->nTypes;i++,type++) {
+ register unsigned n;
+ wire= (xkbKeyTypeWireDesc *)buf;
+ wire->mask = type->mods.mask;
+ wire->realMods = type->mods.real_mods;
+ wire->virtualMods = type->mods.vmods;
+ wire->numLevels = type->num_levels;
+ wire->nMapEntries = type->map_count;
+ wire->preserve = (type->preserve!=NULL);
+ if (client->swapped) {
+ register int n;
+ swaps(&wire->virtualMods,n);
+ }
+
+ buf= (char *)&wire[1];
+ if (wire->nMapEntries>0) {
+ xkbKTMapEntryWireDesc * wire;
+ XkbKTMapEntryPtr entry;
+ wire= (xkbKTMapEntryWireDesc *)buf;
+ entry= type->map;
+ for (n=0;n<type->map_count;n++,wire++,entry++) {
+ wire->active= entry->active;
+ wire->mask= entry->mods.mask;
+ wire->level= entry->level;
+ wire->realMods= entry->mods.real_mods;
+ wire->virtualMods= entry->mods.vmods;
+ if (client->swapped) {
+ register int n;
+ swaps(&wire->virtualMods,n);
+ }
+ }
+ buf= (char *)wire;
+ if (type->preserve!=NULL) {
+ xkbModsWireDesc * pwire;
+ XkbModsPtr preserve;
+ pwire= (xkbModsWireDesc *)buf;
+ preserve= type->preserve;
+ for (n=0;n<type->map_count;n++,pwire++,preserve++) {
+ pwire->mask= preserve->mask;
+ pwire->realMods= preserve->real_mods;
+ pwire->virtualMods= preserve->vmods;
+ if (client->swapped) {
+ register int n;
+ swaps(&pwire->virtualMods,n);
+ }
+ }
+ buf= (char *)pwire;
+ }
+ }
+ }
+ return buf;
+}
+
+static int
+XkbSizeKeySyms(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ XkbSymMapPtr symMap;
+ unsigned i,len;
+ unsigned nSyms,nSymsThisKey;
+
+ if (((rep->present&XkbKeySymsMask)==0)||(rep->nKeySyms<1)||
+ (!xkb)||(!xkb->map)||(!xkb->map->key_sym_map)) {
+ rep->present&= ~XkbKeySymsMask;
+ rep->firstKeySym= rep->nKeySyms= 0;
+ rep->totalSyms= 0;
+ return 0;
+ }
+ len= rep->nKeySyms*SIZEOF(xkbSymMapWireDesc);
+ symMap = &xkb->map->key_sym_map[rep->firstKeySym];
+ for (i=nSyms=0;i<rep->nKeySyms;i++,symMap++) {
+ if (symMap->offset!=0) {
+ nSymsThisKey= XkbNumGroups(symMap->group_info)*symMap->width;
+ nSyms+= nSymsThisKey;
+ }
+ }
+ len+= nSyms*4;
+ rep->totalSyms= nSyms;
+ return len;
+}
+
+static int
+XkbSizeVirtualMods(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+register unsigned i,nMods,bit;
+
+ if (((rep->present&XkbVirtualModsMask)==0)||(rep->virtualMods==0)||
+ (!xkb)||(!xkb->server)) {
+ rep->present&= ~XkbVirtualModsMask;
+ rep->virtualMods= 0;
+ return 0;
+ }
+ for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) {
+ if (rep->virtualMods&bit)
+ nMods++;
+ }
+ return XkbPaddedSize(nMods);
+}
+
+static char *
+XkbWriteKeySyms(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,ClientPtr client)
+{
+register KeySym * pSym;
+XkbSymMapPtr symMap;
+xkbSymMapWireDesc * outMap;
+register unsigned i;
+
+ symMap = &xkb->map->key_sym_map[rep->firstKeySym];
+ for (i=0;i<rep->nKeySyms;i++,symMap++) {
+ outMap = (xkbSymMapWireDesc *)buf;
+ outMap->ktIndex[0] = symMap->kt_index[0];
+ outMap->ktIndex[1] = symMap->kt_index[1];
+ outMap->ktIndex[2] = symMap->kt_index[2];
+ outMap->ktIndex[3] = symMap->kt_index[3];
+ outMap->groupInfo = symMap->group_info;
+ outMap->width= symMap->width;
+ outMap->nSyms = symMap->width*XkbNumGroups(symMap->group_info);
+ buf= (char *)&outMap[1];
+ if (outMap->nSyms==0)
+ continue;
+
+ pSym = &xkb->map->syms[symMap->offset];
+ memcpy((char *)buf,(char *)pSym,outMap->nSyms*4);
+ if (client->swapped) {
+ register int n,nSyms= outMap->nSyms;
+ swaps(&outMap->nSyms,n);
+ while (nSyms-->0) {
+ swapl(buf,n);
+ buf+= 4;
+ }
+ }
+ else buf+= outMap->nSyms*4;
+ }
+ return buf;
+}
+
+static int
+XkbSizeKeyActions(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ unsigned i,len,nActs;
+ register KeyCode firstKey;
+
+ if (((rep->present&XkbKeyActionsMask)==0)||(rep->nKeyActs<1)||
+ (!xkb)||(!xkb->server)||(!xkb->server->key_acts)) {
+ rep->present&= ~XkbKeyActionsMask;
+ rep->firstKeyAct= rep->nKeyActs= 0;
+ rep->totalActs= 0;
+ return 0;
+ }
+ firstKey= rep->firstKeyAct;
+ for (nActs=i=0;i<rep->nKeyActs;i++) {
+ if (xkb->server->key_acts[i+firstKey]!=0)
+ nActs+= XkbKeyNumActions(xkb,i+firstKey);
+ }
+ len= XkbPaddedSize(rep->nKeyActs)+(nActs*SIZEOF(xkbActionWireDesc));
+ rep->totalActs= nActs;
+ return len;
+}
+
+static char *
+XkbWriteKeyActions(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,
+ ClientPtr client)
+{
+ unsigned i;
+ CARD8 * numDesc;
+ XkbAnyAction * actDesc;
+
+ numDesc = (CARD8 *)buf;
+ for (i=0;i<rep->nKeyActs;i++) {
+ if (xkb->server->key_acts[i+rep->firstKeyAct]==0)
+ numDesc[i] = 0;
+ else numDesc[i] = XkbKeyNumActions(xkb,(i+rep->firstKeyAct));
+ }
+ buf+= XkbPaddedSize(rep->nKeyActs);
+
+ actDesc = (XkbAnyAction *)buf;
+ for (i=0;i<rep->nKeyActs;i++) {
+ if (xkb->server->key_acts[i+rep->firstKeyAct]!=0) {
+ unsigned int num;
+ num = XkbKeyNumActions(xkb,(i+rep->firstKeyAct));
+ memcpy((char *)actDesc,
+ (char*)XkbKeyActionsPtr(xkb,(i+rep->firstKeyAct)),
+ num*SIZEOF(xkbActionWireDesc));
+ actDesc+= num;
+ }
+ }
+ buf = (char *)actDesc;
+ return buf;
+}
+
+static int
+XkbSizeKeyBehaviors(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ unsigned i,len,nBhvr;
+ XkbBehavior * bhv;
+
+ if (((rep->present&XkbKeyBehaviorsMask)==0)||(rep->nKeyBehaviors<1)||
+ (!xkb)||(!xkb->server)||(!xkb->server->behaviors)) {
+ rep->present&= ~XkbKeyBehaviorsMask;
+ rep->firstKeyBehavior= rep->nKeyBehaviors= 0;
+ rep->totalKeyBehaviors= 0;
+ return 0;
+ }
+ bhv= &xkb->server->behaviors[rep->firstKeyBehavior];
+ for (nBhvr=i=0;i<rep->nKeyBehaviors;i++,bhv++) {
+ if (bhv->type!=XkbKB_Default)
+ nBhvr++;
+ }
+ len= nBhvr*SIZEOF(xkbBehaviorWireDesc);
+ rep->totalKeyBehaviors= nBhvr;
+ return len;
+}
+
+static char *
+XkbWriteKeyBehaviors(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,
+ ClientPtr client)
+{
+ unsigned i;
+ xkbBehaviorWireDesc *wire;
+ XkbBehavior *pBhvr;
+
+ wire = (xkbBehaviorWireDesc *)buf;
+ pBhvr= &xkb->server->behaviors[rep->firstKeyBehavior];
+ for (i=0;i<rep->nKeyBehaviors;i++,pBhvr++) {
+ if (pBhvr->type!=XkbKB_Default) {
+ wire->key= i+rep->firstKeyBehavior;
+ wire->type= pBhvr->type;
+ wire->data= pBhvr->data;
+ wire++;
+ }
+ }
+ buf = (char *)wire;
+ return buf;
+}
+
+static int
+XkbSizeExplicit(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ unsigned i,len,nRtrn;
+
+ if (((rep->present&XkbExplicitComponentsMask)==0)||(rep->nKeyExplicit<1)||
+ (!xkb)||(!xkb->server)||(!xkb->server->explicit)) {
+ rep->present&= ~XkbExplicitComponentsMask;
+ rep->firstKeyExplicit= rep->nKeyExplicit= 0;
+ rep->totalKeyExplicit= 0;
+ return 0;
+ }
+ for (nRtrn=i=0;i<rep->nKeyExplicit;i++) {
+ if (xkb->server->explicit[i+rep->firstKeyExplicit]!=0)
+ nRtrn++;
+ }
+ rep->totalKeyExplicit= nRtrn;
+ len= XkbPaddedSize(nRtrn*2); /* two bytes per non-zero explicit component */
+ return len;
+}
+
+static char *
+XkbWriteExplicit(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,ClientPtr client)
+{
+unsigned i;
+char * start;
+unsigned char * pExp;
+
+ start= buf;
+ pExp= &xkb->server->explicit[rep->firstKeyExplicit];
+ for (i=0;i<rep->nKeyExplicit;i++,pExp++) {
+ if (*pExp!=0) {
+ *buf++= i+rep->firstKeyExplicit;
+ *buf++= *pExp;
+ }
+ }
+ i= XkbPaddedSize(buf-start)-(buf-start); /* pad to word boundary */
+ return buf+i;
+}
+
+static int
+XkbSizeModifierMap(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ unsigned i,len,nRtrn;
+
+ if (((rep->present&XkbModifierMapMask)==0)||(rep->nModMapKeys<1)||
+ (!xkb)||(!xkb->map)||(!xkb->map->modmap)) {
+ rep->present&= ~XkbModifierMapMask;
+ rep->firstModMapKey= rep->nModMapKeys= 0;
+ rep->totalModMapKeys= 0;
+ return 0;
+ }
+ for (nRtrn=i=0;i<rep->nModMapKeys;i++) {
+ if (xkb->map->modmap[i+rep->firstModMapKey]!=0)
+ nRtrn++;
+ }
+ rep->totalModMapKeys= nRtrn;
+ len= XkbPaddedSize(nRtrn*2); /* two bytes per non-zero modmap component */
+ return len;
+}
+
+static char *
+XkbWriteModifierMap(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,
+ ClientPtr client)
+{
+unsigned i;
+char * start;
+unsigned char * pMap;
+
+ start= buf;
+ pMap= &xkb->map->modmap[rep->firstModMapKey];
+ for (i=0;i<rep->nModMapKeys;i++,pMap++) {
+ if (*pMap!=0) {
+ *buf++= i+rep->firstModMapKey;
+ *buf++= *pMap;
+ }
+ }
+ i= XkbPaddedSize(buf-start)-(buf-start); /* pad to word boundary */
+ return buf+i;
+}
+
+static int
+XkbSizeVirtualModMap(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+ unsigned i,len,nRtrn;
+
+ if (((rep->present&XkbVirtualModMapMask)==0)||(rep->nVModMapKeys<1)||
+ (!xkb)||(!xkb->server)||(!xkb->server->vmodmap)) {
+ rep->present&= ~XkbVirtualModMapMask;
+ rep->firstVModMapKey= rep->nVModMapKeys= 0;
+ rep->totalVModMapKeys= 0;
+ return 0;
+ }
+ for (nRtrn=i=0;i<rep->nVModMapKeys;i++) {
+ if (xkb->server->vmodmap[i+rep->firstVModMapKey]!=0)
+ nRtrn++;
+ }
+ rep->totalVModMapKeys= nRtrn;
+ len= nRtrn*SIZEOF(xkbVModMapWireDesc);
+ return len;
+}
+
+static char *
+XkbWriteVirtualModMap(XkbDescPtr xkb,xkbGetMapReply *rep,char *buf,
+ ClientPtr client)
+{
+unsigned i;
+xkbVModMapWireDesc * wire;
+unsigned short * pMap;
+
+ wire= (xkbVModMapWireDesc *)buf;
+ pMap= &xkb->server->vmodmap[rep->firstVModMapKey];
+ for (i=0;i<rep->nVModMapKeys;i++,pMap++) {
+ if (*pMap!=0) {
+ wire->key= i+rep->firstVModMapKey;
+ wire->vmods= *pMap;
+ wire++;
+ }
+ }
+ return (char *)wire;
+}
+
+static Status
+XkbComputeGetMapReplySize(XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+int len;
+
+ rep->minKeyCode= xkb->min_key_code;
+ rep->maxKeyCode= xkb->max_key_code;
+ len= XkbSizeKeyTypes(xkb,rep);
+ len+= XkbSizeKeySyms(xkb,rep);
+ len+= XkbSizeKeyActions(xkb,rep);
+ len+= XkbSizeKeyBehaviors(xkb,rep);
+ len+= XkbSizeVirtualMods(xkb,rep);
+ len+= XkbSizeExplicit(xkb,rep);
+ len+= XkbSizeModifierMap(xkb,rep);
+ len+= XkbSizeVirtualModMap(xkb,rep);
+ rep->length+= (len/4);
+ return Success;
+}
+
+static int
+XkbSendMap(ClientPtr client,XkbDescPtr xkb,xkbGetMapReply *rep)
+{
+unsigned i,len;
+char *desc,*start;
+
+ len= (rep->length*4)-(SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply));
+ start= desc= xcalloc(1, len);
+ if (!start)
+ return BadAlloc;
+ if ( rep->nTypes>0 )
+ desc = XkbWriteKeyTypes(xkb,rep,desc,client);
+ if ( rep->nKeySyms>0 )
+ desc = XkbWriteKeySyms(xkb,rep,desc,client);
+ if ( rep->nKeyActs>0 )
+ desc = XkbWriteKeyActions(xkb,rep,desc,client);
+ if ( rep->totalKeyBehaviors>0 )
+ desc = XkbWriteKeyBehaviors(xkb,rep,desc,client);
+ if ( rep->virtualMods ) {
+ register int sz,bit;
+ for (i=sz=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) {
+ if (rep->virtualMods&bit) {
+ desc[sz++]= xkb->server->vmods[i];
+ }
+ }
+ desc+= XkbPaddedSize(sz);
+ }
+ if ( rep->totalKeyExplicit>0 )
+ desc= XkbWriteExplicit(xkb,rep,desc,client);
+ if ( rep->totalModMapKeys>0 )
+ desc= XkbWriteModifierMap(xkb,rep,desc,client);
+ if ( rep->totalVModMapKeys>0 )
+ desc= XkbWriteVirtualModMap(xkb,rep,desc,client);
+ if ((desc-start)!=(len)) {
+ ErrorF("[xkb] BOGUS LENGTH in write keyboard desc, expected %d, got %ld\n",
+ len, (unsigned long)(desc-start));
+ }
+ if (client->swapped) {
+ register int n;
+ swaps(&rep->sequenceNumber,n);
+ swapl(&rep->length,n);
+ swaps(&rep->present,n);
+ swaps(&rep->totalSyms,n);
+ swaps(&rep->totalActs,n);
+ }
+ WriteToClient(client, (i=SIZEOF(xkbGetMapReply)), (char *)rep);
+ WriteToClient(client, len, start);
+ xfree((char *)start);
+ return client->noClientException;
+}
+
+int
+ProcXkbGetMap(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ xkbGetMapReply rep;
+ XkbDescRec *xkb;
+ int n,status;
+
+ REQUEST(xkbGetMapReq);
+ REQUEST_SIZE_MATCH(xkbGetMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+ CHK_MASK_OVERLAP(0x01,stuff->full,stuff->partial);
+ CHK_MASK_LEGAL(0x02,stuff->full,XkbAllMapComponentsMask);
+ CHK_MASK_LEGAL(0x03,stuff->partial,XkbAllMapComponentsMask);
+
+ xkb= dev->key->xkbInfo->desc;
+ bzero(&rep,sizeof(xkbGetMapReply));
+ rep.type= X_Reply;
+ rep.sequenceNumber= client->sequence;
+ rep.length = (SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply))>>2;
+ rep.deviceID = dev->id;
+ rep.present = stuff->partial|stuff->full;
+ rep.minKeyCode = xkb->min_key_code;
+ rep.maxKeyCode = xkb->max_key_code;
+ if ( stuff->full&XkbKeyTypesMask ) {
+ rep.firstType = 0;
+ rep.nTypes = xkb->map->num_types;
+ }
+ else if (stuff->partial&XkbKeyTypesMask) {
+ if (((unsigned)stuff->firstType+stuff->nTypes)>xkb->map->num_types) {
+ client->errorValue = _XkbErrCode4(0x04,xkb->map->num_types,
+ stuff->firstType,stuff->nTypes);
+ return BadValue;
+ }
+ rep.firstType = stuff->firstType;
+ rep.nTypes = stuff->nTypes;
+ }
+ else rep.nTypes = 0;
+ rep.totalTypes = xkb->map->num_types;
+
+ n= XkbNumKeys(xkb);
+ if ( stuff->full&XkbKeySymsMask ) {
+ rep.firstKeySym = xkb->min_key_code;
+ rep.nKeySyms = n;
+ }
+ else if (stuff->partial&XkbKeySymsMask) {
+ CHK_KEY_RANGE(0x05,stuff->firstKeySym,stuff->nKeySyms,xkb);
+ rep.firstKeySym = stuff->firstKeySym;
+ rep.nKeySyms = stuff->nKeySyms;
+ }
+ else rep.nKeySyms = 0;
+ rep.totalSyms= 0;
+
+ if ( stuff->full&XkbKeyActionsMask ) {
+ rep.firstKeyAct= xkb->min_key_code;
+ rep.nKeyActs= n;
+ }
+ else if (stuff->partial&XkbKeyActionsMask) {
+ CHK_KEY_RANGE(0x07,stuff->firstKeyAct,stuff->nKeyActs,xkb);
+ rep.firstKeyAct= stuff->firstKeyAct;
+ rep.nKeyActs= stuff->nKeyActs;
+ }
+ else rep.nKeyActs= 0;
+ rep.totalActs= 0;
+
+ if ( stuff->full&XkbKeyBehaviorsMask ) {
+ rep.firstKeyBehavior = xkb->min_key_code;
+ rep.nKeyBehaviors = n;
+ }
+ else if (stuff->partial&XkbKeyBehaviorsMask) {
+ CHK_KEY_RANGE(0x09,stuff->firstKeyBehavior,stuff->nKeyBehaviors,xkb);
+ rep.firstKeyBehavior= stuff->firstKeyBehavior;
+ rep.nKeyBehaviors= stuff->nKeyBehaviors;
+ }
+ else rep.nKeyBehaviors = 0;
+ rep.totalKeyBehaviors= 0;
+
+ if (stuff->full&XkbVirtualModsMask)
+ rep.virtualMods= ~0;
+ else if (stuff->partial&XkbVirtualModsMask)
+ rep.virtualMods= stuff->virtualMods;
+
+ if (stuff->full&XkbExplicitComponentsMask) {
+ rep.firstKeyExplicit= xkb->min_key_code;
+ rep.nKeyExplicit= n;
+ }
+ else if (stuff->partial&XkbExplicitComponentsMask) {
+ CHK_KEY_RANGE(0x0B,stuff->firstKeyExplicit,stuff->nKeyExplicit,xkb);
+ rep.firstKeyExplicit= stuff->firstKeyExplicit;
+ rep.nKeyExplicit= stuff->nKeyExplicit;
+ }
+ else rep.nKeyExplicit = 0;
+ rep.totalKeyExplicit= 0;
+
+ if (stuff->full&XkbModifierMapMask) {
+ rep.firstModMapKey= xkb->min_key_code;
+ rep.nModMapKeys= n;
+ }
+ else if (stuff->partial&XkbModifierMapMask) {
+ CHK_KEY_RANGE(0x0D,stuff->firstModMapKey,stuff->nModMapKeys,xkb);
+ rep.firstModMapKey= stuff->firstModMapKey;
+ rep.nModMapKeys= stuff->nModMapKeys;
+ }
+ else rep.nModMapKeys = 0;
+ rep.totalModMapKeys= 0;
+
+ if (stuff->full&XkbVirtualModMapMask) {
+ rep.firstVModMapKey= xkb->min_key_code;
+ rep.nVModMapKeys= n;
+ }
+ else if (stuff->partial&XkbVirtualModMapMask) {
+ CHK_KEY_RANGE(0x0F,stuff->firstVModMapKey,stuff->nVModMapKeys,xkb);
+ rep.firstVModMapKey= stuff->firstVModMapKey;
+ rep.nVModMapKeys= stuff->nVModMapKeys;
+ }
+ else rep.nVModMapKeys = 0;
+ rep.totalVModMapKeys= 0;
+
+ if ((status=XkbComputeGetMapReplySize(xkb,&rep))!=Success)
+ return status;
+ return XkbSendMap(client,xkb,&rep);
+}
+
+/***====================================================================***/
+
+static int
+CheckKeyTypes( ClientPtr client,
+ XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ xkbKeyTypeWireDesc **wireRtrn,
+ int * nMapsRtrn,
+ CARD8 * mapWidthRtrn)
+{
+unsigned nMaps;
+register unsigned i,n;
+register CARD8 * map;
+register xkbKeyTypeWireDesc *wire = *wireRtrn;
+
+ if (req->firstType>((unsigned)xkb->map->num_types)) {
+ *nMapsRtrn = _XkbErrCode3(0x01,req->firstType,xkb->map->num_types);
+ return 0;
+ }
+ if (req->flags&XkbSetMapResizeTypes) {
+ nMaps = req->firstType+req->nTypes;
+ if (nMaps<XkbNumRequiredTypes) { /* canonical types must be there */
+ *nMapsRtrn= _XkbErrCode4(0x02,req->firstType,req->nTypes,4);
+ return 0;
+ }
+ }
+ else if (req->present&XkbKeyTypesMask) {
+ nMaps = xkb->map->num_types;
+ if ((req->firstType+req->nTypes)>nMaps) {
+ *nMapsRtrn = req->firstType+req->nTypes;
+ return 0;
+ }
+ }
+ else {
+ *nMapsRtrn = xkb->map->num_types;
+ for (i=0;i<xkb->map->num_types;i++) {
+ mapWidthRtrn[i] = xkb->map->types[i].num_levels;
+ }
+ return 1;
+ }
+
+ for (i=0;i<req->firstType;i++) {
+ mapWidthRtrn[i] = xkb->map->types[i].num_levels;
+ }
+ for (i=0;i<req->nTypes;i++) {
+ unsigned width;
+ if (client->swapped) {
+ register int s;
+ swaps(&wire->virtualMods,s);
+ }
+ n= i+req->firstType;
+ width= wire->numLevels;
+ if (width<1) {
+ *nMapsRtrn= _XkbErrCode3(0x04,n,width);
+ return 0;
+ }
+ else if ((n==XkbOneLevelIndex)&&(width!=1)) { /* must be width 1 */
+ *nMapsRtrn= _XkbErrCode3(0x05,n,width);
+ return 0;
+ }
+ else if ((width!=2)&&
+ ((n==XkbTwoLevelIndex)||(n==XkbKeypadIndex)||
+ (n==XkbAlphabeticIndex))) {
+ /* TWO_LEVEL, ALPHABETIC and KEYPAD must be width 2 */
+ *nMapsRtrn= _XkbErrCode3(0x05,n,width);
+ return 0;
+ }
+ if (wire->nMapEntries>0) {
+ xkbKTSetMapEntryWireDesc * mapWire;
+ xkbModsWireDesc * preWire;
+ mapWire= (xkbKTSetMapEntryWireDesc *)&wire[1];
+ preWire= (xkbModsWireDesc *)&mapWire[wire->nMapEntries];
+ for (n=0;n<wire->nMapEntries;n++) {
+ if (client->swapped) {
+ register int s;
+ swaps(&mapWire[n].virtualMods,s);
+ }
+ if (mapWire[n].realMods&(~wire->realMods)) {
+ *nMapsRtrn= _XkbErrCode4(0x06,n,mapWire[n].realMods,
+ wire->realMods);
+ return 0;
+ }
+ if (mapWire[n].virtualMods&(~wire->virtualMods)) {
+ *nMapsRtrn= _XkbErrCode3(0x07,n,mapWire[n].virtualMods);
+ return 0;
+ }
+ if (mapWire[n].level>=wire->numLevels) {
+ *nMapsRtrn= _XkbErrCode4(0x08,n,wire->numLevels,
+ mapWire[n].level);
+ return 0;
+ }
+ if (wire->preserve) {
+ if (client->swapped) {
+ register int s;
+ swaps(&preWire[n].virtualMods,s);
+ }
+ if (preWire[n].realMods&(~mapWire[n].realMods)) {
+ *nMapsRtrn= _XkbErrCode4(0x09,n,preWire[n].realMods,
+ mapWire[n].realMods);
+ return 0;
+ }
+ if (preWire[n].virtualMods&(~mapWire[n].virtualMods)) {
+ *nMapsRtrn=_XkbErrCode3(0x0a,n,preWire[n].virtualMods);
+ return 0;
+ }
+ }
+ }
+ if (wire->preserve)
+ map= (CARD8 *)&preWire[wire->nMapEntries];
+ else map= (CARD8 *)&mapWire[wire->nMapEntries];
+ }
+ else map= (CARD8 *)&wire[1];
+ mapWidthRtrn[i+req->firstType] = wire->numLevels;
+ wire= (xkbKeyTypeWireDesc *)map;
+ }
+ for (i=req->firstType+req->nTypes;i<nMaps;i++) {
+ mapWidthRtrn[i] = xkb->map->types[i].num_levels;
+ }
+ *nMapsRtrn = nMaps;
+ *wireRtrn = wire;
+ return 1;
+}
+
+static int
+CheckKeySyms( ClientPtr client,
+ XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ int nTypes,
+ CARD8 * mapWidths,
+ CARD16 * symsPerKey,
+ xkbSymMapWireDesc ** wireRtrn,
+ int * errorRtrn)
+{
+register unsigned i;
+XkbSymMapPtr map;
+xkbSymMapWireDesc* wire = *wireRtrn;
+
+ if (!(XkbKeySymsMask&req->present))
+ return 1;
+ CHK_REQ_KEY_RANGE2(0x11,req->firstKeySym,req->nKeySyms,req,(*errorRtrn),0);
+ map = &xkb->map->key_sym_map[xkb->min_key_code];
+ for (i=xkb->min_key_code;i<(unsigned)req->firstKeySym;i++,map++) {
+ register int g,ng,w;
+ ng= XkbNumGroups(map->group_info);
+ for (w=g=0;g<ng;g++) {
+ if (map->kt_index[g]>=(unsigned)nTypes) {
+ *errorRtrn = _XkbErrCode4(0x13,i,g,map->kt_index[g]);
+ return 0;
+ }
+ if (mapWidths[map->kt_index[g]]>w)
+ w= mapWidths[map->kt_index[g]];
+ }
+ symsPerKey[i] = w*ng;
+ }
+ for (i=0;i<req->nKeySyms;i++) {
+ KeySym *pSyms;
+ register unsigned nG;
+ if (client->swapped) {
+ swaps(&wire->nSyms,nG);
+ }
+ nG = XkbNumGroups(wire->groupInfo);
+ if (nG>XkbNumKbdGroups) {
+ *errorRtrn = _XkbErrCode3(0x14,i+req->firstKeySym,nG);
+ return 0;
+ }
+ if (nG>0) {
+ register int g,w;
+ for (g=w=0;g<nG;g++) {
+ if (wire->ktIndex[g]>=(unsigned)nTypes) {
+ *errorRtrn= _XkbErrCode4(0x15,i+req->firstKeySym,g,
+ wire->ktIndex[g]);
+ return 0;
+ }
+ if (mapWidths[wire->ktIndex[g]]>w)
+ w= mapWidths[wire->ktIndex[g]];
+ }
+ if (wire->width!=w) {
+ *errorRtrn= _XkbErrCode3(0x16,i+req->firstKeySym,wire->width);
+ return 0;
+ }
+ w*= nG;
+ symsPerKey[i+req->firstKeySym] = w;
+ if (w!=wire->nSyms) {
+ *errorRtrn=_XkbErrCode4(0x16,i+req->firstKeySym,wire->nSyms,w);
+ return 0;
+ }
+ }
+ else if (wire->nSyms!=0) {
+ *errorRtrn = _XkbErrCode3(0x17,i+req->firstKeySym,wire->nSyms);
+ return 0;
+ }
+ pSyms = (KeySym *)&wire[1];
+ wire = (xkbSymMapWireDesc *)&pSyms[wire->nSyms];
+ }
+
+ map = &xkb->map->key_sym_map[i];
+ for (;i<=(unsigned)xkb->max_key_code;i++,map++) {
+ register int g,nG,w;
+ nG= XkbKeyNumGroups(xkb,i);
+ for (w=g=0;g<nG;g++) {
+ if (map->kt_index[g]>=(unsigned)nTypes) {
+ *errorRtrn = _XkbErrCode4(0x18,i,g,map->kt_index[g]);
+ return 0;
+ }
+ if (mapWidths[map->kt_index[g]]>w)
+ w= mapWidths[map->kt_index[g]];
+ }
+ symsPerKey[i] = w*nG;
+ }
+ *wireRtrn = wire;
+ return 1;
+}
+
+static int
+CheckKeyActions( XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ int nTypes,
+ CARD8 * mapWidths,
+ CARD16 * symsPerKey,
+ CARD8 ** wireRtrn,
+ int * nActsRtrn)
+{
+int nActs;
+CARD8 * wire = *wireRtrn;
+register unsigned i;
+
+ if (!(XkbKeyActionsMask&req->present))
+ return 1;
+ CHK_REQ_KEY_RANGE2(0x21,req->firstKeyAct,req->nKeyActs,req,(*nActsRtrn),0);
+ for (nActs=i=0;i<req->nKeyActs;i++) {
+ if (wire[0]!=0) {
+ if (wire[0]==symsPerKey[i+req->firstKeyAct])
+ nActs+= wire[0];
+ else {
+ *nActsRtrn= _XkbErrCode3(0x23,i+req->firstKeyAct,wire[0]);
+ return 0;
+ }
+ }
+ wire++;
+ }
+ if (req->nKeyActs%4)
+ wire+= 4-(req->nKeyActs%4);
+ *wireRtrn = (CARD8 *)(((XkbAnyAction *)wire)+nActs);
+ *nActsRtrn = nActs;
+ return 1;
+}
+
+static int
+CheckKeyBehaviors( XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ xkbBehaviorWireDesc ** wireRtrn,
+ int * errorRtrn)
+{
+register xkbBehaviorWireDesc * wire = *wireRtrn;
+register XkbServerMapPtr server = xkb->server;
+register unsigned i;
+unsigned first,last;
+
+ if (((req->present&XkbKeyBehaviorsMask)==0)||(req->nKeyBehaviors<1)) {
+ req->present&= ~XkbKeyBehaviorsMask;
+ req->nKeyBehaviors= 0;
+ return 1;
+ }
+ first= req->firstKeyBehavior;
+ last= req->firstKeyBehavior+req->nKeyBehaviors-1;
+ if (first<req->minKeyCode) {
+ *errorRtrn = _XkbErrCode3(0x31,first,req->minKeyCode);
+ return 0;
+ }
+ if (last>req->maxKeyCode) {
+ *errorRtrn = _XkbErrCode3(0x32,last,req->maxKeyCode);
+ return 0;
+ }
+
+ for (i=0;i<req->totalKeyBehaviors;i++,wire++) {
+ if ((wire->key<first)||(wire->key>last)) {
+ *errorRtrn = _XkbErrCode4(0x33,first,last,wire->key);
+ return 0;
+ }
+ if ((wire->type&XkbKB_Permanent)&&
+ ((server->behaviors[wire->key].type!=wire->type)||
+ (server->behaviors[wire->key].data!=wire->data))) {
+ *errorRtrn = _XkbErrCode3(0x33,wire->key,wire->type);
+ return 0;
+ }
+ if ((wire->type==XkbKB_RadioGroup)&&
+ ((wire->data&(~XkbKB_RGAllowNone))>XkbMaxRadioGroups)) {
+ *errorRtrn= _XkbErrCode4(0x34,wire->key,wire->data,
+ XkbMaxRadioGroups);
+ return 0;
+ }
+ if ((wire->type==XkbKB_Overlay1)||(wire->type==XkbKB_Overlay2)) {
+ CHK_KEY_RANGE2(0x35,wire->key,1,xkb,*errorRtrn,0);
+ }
+ }
+ *wireRtrn = wire;
+ return 1;
+}
+
+static int
+CheckVirtualMods( XkbDescRec * xkb,
+ xkbSetMapReq * req,
+ CARD8 ** wireRtrn,
+ int * errorRtrn)
+{
+register CARD8 *wire = *wireRtrn;
+register unsigned i,nMods,bit;
+
+ if (((req->present&XkbVirtualModsMask)==0)||(req->virtualMods==0))
+ return 1;
+ for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) {
+ if (req->virtualMods&bit)
+ nMods++;
+ }
+ *wireRtrn= (wire+XkbPaddedSize(nMods));
+ return 1;
+}
+
+static int
+CheckKeyExplicit( XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ CARD8 ** wireRtrn,
+ int * errorRtrn)
+{
+register CARD8 * wire = *wireRtrn;
+CARD8 * start;
+register unsigned i;
+int first,last;
+
+ if (((req->present&XkbExplicitComponentsMask)==0)||(req->nKeyExplicit<1)) {
+ req->present&= ~XkbExplicitComponentsMask;
+ req->nKeyExplicit= 0;
+ return 1;
+ }
+ first= req->firstKeyExplicit;
+ last= first+req->nKeyExplicit-1;
+ if (first<req->minKeyCode) {
+ *errorRtrn = _XkbErrCode3(0x51,first,req->minKeyCode);
+ return 0;
+ }
+ if (last>req->maxKeyCode) {
+ *errorRtrn = _XkbErrCode3(0x52,last,req->maxKeyCode);
+ return 0;
+ }
+ start= wire;
+ for (i=0;i<req->totalKeyExplicit;i++,wire+=2) {
+ if ((wire[0]<first)||(wire[0]>last)) {
+ *errorRtrn = _XkbErrCode4(0x53,first,last,wire[0]);
+ return 0;
+ }
+ if (wire[1]&(~XkbAllExplicitMask)) {
+ *errorRtrn= _XkbErrCode3(0x52,~XkbAllExplicitMask,wire[1]);
+ return 0;
+ }
+ }
+ wire+= XkbPaddedSize(wire-start)-(wire-start);
+ *wireRtrn= wire;
+ return 1;
+}
+
+static int
+CheckModifierMap(XkbDescPtr xkb,xkbSetMapReq *req,CARD8 **wireRtrn,int *errRtrn)
+{
+register CARD8 * wire = *wireRtrn;
+CARD8 * start;
+register unsigned i;
+int first,last;
+
+ if (((req->present&XkbModifierMapMask)==0)||(req->nModMapKeys<1)) {
+ req->present&= ~XkbModifierMapMask;
+ req->nModMapKeys= 0;
+ return 1;
+ }
+ first= req->firstModMapKey;
+ last= first+req->nModMapKeys-1;
+ if (first<req->minKeyCode) {
+ *errRtrn = _XkbErrCode3(0x61,first,req->minKeyCode);
+ return 0;
+ }
+ if (last>req->maxKeyCode) {
+ *errRtrn = _XkbErrCode3(0x62,last,req->maxKeyCode);
+ return 0;
+ }
+ start= wire;
+ for (i=0;i<req->totalModMapKeys;i++,wire+=2) {
+ if ((wire[0]<first)||(wire[0]>last)) {
+ *errRtrn = _XkbErrCode4(0x63,first,last,wire[0]);
+ return 0;
+ }
+ }
+ wire+= XkbPaddedSize(wire-start)-(wire-start);
+ *wireRtrn= wire;
+ return 1;
+}
+
+static int
+CheckVirtualModMap( XkbDescPtr xkb,
+ xkbSetMapReq *req,
+ xkbVModMapWireDesc **wireRtrn,
+ int *errRtrn)
+{
+register xkbVModMapWireDesc * wire = *wireRtrn;
+register unsigned i;
+int first,last;
+
+ if (((req->present&XkbVirtualModMapMask)==0)||(req->nVModMapKeys<1)) {
+ req->present&= ~XkbVirtualModMapMask;
+ req->nVModMapKeys= 0;
+ return 1;
+ }
+ first= req->firstVModMapKey;
+ last= first+req->nVModMapKeys-1;
+ if (first<req->minKeyCode) {
+ *errRtrn = _XkbErrCode3(0x71,first,req->minKeyCode);
+ return 0;
+ }
+ if (last>req->maxKeyCode) {
+ *errRtrn = _XkbErrCode3(0x72,last,req->maxKeyCode);
+ return 0;
+ }
+ for (i=0;i<req->totalVModMapKeys;i++,wire++) {
+ if ((wire->key<first)||(wire->key>last)) {
+ *errRtrn = _XkbErrCode4(0x73,first,last,wire->key);
+ return 0;
+ }
+ }
+ *wireRtrn= wire;
+ return 1;
+}
+
+static char *
+SetKeyTypes( XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ xkbKeyTypeWireDesc * wire,
+ XkbChangesPtr changes)
+{
+register unsigned i;
+unsigned first,last;
+CARD8 *map;
+
+ if ((unsigned)(req->firstType+req->nTypes)>xkb->map->size_types) {
+ i= req->firstType+req->nTypes;
+ if (XkbAllocClientMap(xkb,XkbKeyTypesMask,i)!=Success) {
+ return NULL;
+ }
+ }
+ if ((unsigned)(req->firstType+req->nTypes)>xkb->map->num_types)
+ xkb->map->num_types= req->firstType+req->nTypes;
+
+ for (i=0;i<req->nTypes;i++) {
+ XkbKeyTypePtr pOld;
+ register unsigned n;
+
+ if (XkbResizeKeyType(xkb,i+req->firstType,wire->nMapEntries,
+ wire->preserve,wire->numLevels)!=Success) {
+ return NULL;
+ }
+ pOld = &xkb->map->types[i+req->firstType];
+ map = (CARD8 *)&wire[1];
+
+ pOld->mods.real_mods = wire->realMods;
+ pOld->mods.vmods= wire->virtualMods;
+ pOld->num_levels = wire->numLevels;
+ pOld->map_count= wire->nMapEntries;
+
+ pOld->mods.mask= pOld->mods.real_mods|
+ XkbMaskForVMask(xkb,pOld->mods.vmods);
+
+ if (wire->nMapEntries) {
+ xkbKTSetMapEntryWireDesc *mapWire;
+ xkbModsWireDesc *preWire;
+ unsigned tmp;
+ mapWire= (xkbKTSetMapEntryWireDesc *)map;
+ preWire= (xkbModsWireDesc *)&mapWire[wire->nMapEntries];
+ for (n=0;n<wire->nMapEntries;n++) {
+ pOld->map[n].active= 1;
+ pOld->map[n].mods.mask= mapWire[n].realMods;
+ pOld->map[n].mods.real_mods= mapWire[n].realMods;
+ pOld->map[n].mods.vmods= mapWire[n].virtualMods;
+ pOld->map[n].level= mapWire[n].level;
+ if (mapWire[n].virtualMods!=0) {
+ tmp= XkbMaskForVMask(xkb,mapWire[n].virtualMods);
+ pOld->map[n].active= (tmp!=0);
+ pOld->map[n].mods.mask|= tmp;
+ }
+ if (wire->preserve) {
+ pOld->preserve[n].real_mods= preWire[n].realMods;
+ pOld->preserve[n].vmods= preWire[n].virtualMods;
+ tmp= XkbMaskForVMask(xkb,preWire[n].virtualMods);
+ pOld->preserve[n].mask= preWire[n].realMods|tmp;
+ }
+ }
+ if (wire->preserve)
+ map= (CARD8 *)&preWire[wire->nMapEntries];
+ else map= (CARD8 *)&mapWire[wire->nMapEntries];
+ }
+ else map= (CARD8 *)&wire[1];
+ wire = (xkbKeyTypeWireDesc *)map;
+ }
+ first= req->firstType;
+ last= first+req->nTypes-1; /* last changed type */
+ if (changes->map.changed&XkbKeyTypesMask) {
+ int oldLast;
+ oldLast= changes->map.first_type+changes->map.num_types-1;
+ if (changes->map.first_type<first)
+ first= changes->map.first_type;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.changed|= XkbKeyTypesMask;
+ changes->map.first_type = first;
+ changes->map.num_types = (last-first)+1;
+ return (char *)wire;
+}
+
+static char *
+SetKeySyms( ClientPtr client,
+ XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ xkbSymMapWireDesc * wire,
+ XkbChangesPtr changes,
+ DeviceIntPtr dev)
+{
+register unsigned i,s;
+XkbSymMapPtr oldMap;
+KeySym * newSyms;
+KeySym * pSyms;
+unsigned first,last;
+
+ oldMap = &xkb->map->key_sym_map[req->firstKeySym];
+ for (i=0;i<req->nKeySyms;i++,oldMap++) {
+ pSyms = (KeySym *)&wire[1];
+ if (wire->nSyms>0) {
+ newSyms = XkbResizeKeySyms(xkb,i+req->firstKeySym,wire->nSyms);
+ for (s=0;s<wire->nSyms;s++) {
+ newSyms[s]= pSyms[s];
+ }
+ if (client->swapped) {
+ int n;
+ for (s=0;s<wire->nSyms;s++) {
+ swapl(&newSyms[s],n);
+ }
+ }
+ }
+ oldMap->kt_index[0] = wire->ktIndex[0];
+ oldMap->kt_index[1] = wire->ktIndex[1];
+ oldMap->kt_index[2] = wire->ktIndex[2];
+ oldMap->kt_index[3] = wire->ktIndex[3];
+ oldMap->group_info = wire->groupInfo;
+ oldMap->width = wire->width;
+ wire= (xkbSymMapWireDesc *)&pSyms[wire->nSyms];
+ }
+ first= req->firstKeySym;
+ last= first+req->nKeySyms-1;
+ if (changes->map.changed&XkbKeySymsMask) {
+ int oldLast= (changes->map.first_key_sym+changes->map.num_key_syms-1);
+ if (changes->map.first_key_sym<first)
+ first= changes->map.first_key_sym;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.changed|= XkbKeySymsMask;
+ changes->map.first_key_sym = first;
+ changes->map.num_key_syms = (last-first+1);
+
+ s= 0;
+ for (i=xkb->min_key_code;i<=xkb->max_key_code;i++) {
+ if (XkbKeyNumGroups(xkb,i)>s)
+ s= XkbKeyNumGroups(xkb,i);
+ }
+ if (s!=xkb->ctrls->num_groups) {
+ xkbControlsNotify cn;
+ XkbControlsRec old;
+ cn.keycode= 0;
+ cn.eventType= 0;
+ cn.requestMajor= XkbReqCode;
+ cn.requestMinor= X_kbSetMap;
+ old= *xkb->ctrls;
+ xkb->ctrls->num_groups= s;
+ if (XkbComputeControlsNotify(dev,&old,xkb->ctrls,&cn,False))
+ XkbSendControlsNotify(dev,&cn);
+ }
+ return (char *)wire;
+}
+
+static char *
+SetKeyActions( XkbDescPtr xkb,
+ xkbSetMapReq * req,
+ CARD8 * wire,
+ XkbChangesPtr changes)
+{
+register unsigned i,first,last;
+CARD8 * nActs = wire;
+XkbAction * newActs;
+
+ wire+= XkbPaddedSize(req->nKeyActs);
+ for (i=0;i<req->nKeyActs;i++) {
+ if (nActs[i]==0)
+ xkb->server->key_acts[i+req->firstKeyAct]= 0;
+ else {
+ newActs= XkbResizeKeyActions(xkb,i+req->firstKeyAct,nActs[i]);
+ memcpy((char *)newActs,(char *)wire,
+ nActs[i]*SIZEOF(xkbActionWireDesc));
+ wire+= nActs[i]*SIZEOF(xkbActionWireDesc);
+ }
+ }
+ first= req->firstKeyAct;
+ last= (first+req->nKeyActs-1);
+ if (changes->map.changed&XkbKeyActionsMask) {
+ int oldLast;
+ oldLast= changes->map.first_key_act+changes->map.num_key_acts-1;
+ if (changes->map.first_key_act<first)
+ first= changes->map.first_key_act;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.changed|= XkbKeyActionsMask;
+ changes->map.first_key_act= first;
+ changes->map.num_key_acts= (last-first+1);
+ return (char *)wire;
+}
+
+static char *
+SetKeyBehaviors( XkbSrvInfoPtr xkbi,
+ xkbSetMapReq *req,
+ xkbBehaviorWireDesc *wire,
+ XkbChangesPtr changes)
+{
+register unsigned i;
+int maxRG = -1;
+XkbDescPtr xkb = xkbi->desc;
+XkbServerMapPtr server = xkb->server;
+unsigned first,last;
+
+ first= req->firstKeyBehavior;
+ last= req->firstKeyBehavior+req->nKeyBehaviors-1;
+ bzero(&server->behaviors[first],req->nKeyBehaviors*sizeof(XkbBehavior));
+ for (i=0;i<req->totalKeyBehaviors;i++) {
+ if ((server->behaviors[wire->key].type&XkbKB_Permanent)==0) {
+ server->behaviors[wire->key].type= wire->type;
+ server->behaviors[wire->key].data= wire->data;
+ if ((wire->type==XkbKB_RadioGroup)&&(((int)wire->data)>maxRG))
+ maxRG= wire->data + 1;
+ }
+ wire++;
+ }
+
+ if (maxRG>(int)xkbi->nRadioGroups) {
+ int sz = maxRG*sizeof(XkbRadioGroupRec);
+ if (xkbi->radioGroups)
+ xkbi->radioGroups= xrealloc(xkbi->radioGroups,sz);
+ else xkbi->radioGroups= xcalloc(1, sz);
+ if (xkbi->radioGroups) {
+ if (xkbi->nRadioGroups)
+ bzero(&xkbi->radioGroups[xkbi->nRadioGroups],
+ (maxRG-xkbi->nRadioGroups)*sizeof(XkbRadioGroupRec));
+ xkbi->nRadioGroups= maxRG;
+ }
+ else xkbi->nRadioGroups= 0;
+ /* should compute members here */
+ }
+ if (changes->map.changed&XkbKeyBehaviorsMask) {
+ unsigned oldLast;
+ oldLast= changes->map.first_key_behavior+
+ changes->map.num_key_behaviors-1;
+ if (changes->map.first_key_behavior<req->firstKeyBehavior)
+ first= changes->map.first_key_behavior;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.changed|= XkbKeyBehaviorsMask;
+ changes->map.first_key_behavior = first;
+ changes->map.num_key_behaviors = (last-first+1);
+ return (char *)wire;
+}
+
+static char *
+SetVirtualMods(XkbSrvInfoPtr xkbi,xkbSetMapReq *req,CARD8 *wire,
+ XkbChangesPtr changes)
+{
+register int i,bit,nMods;
+XkbServerMapPtr srv = xkbi->desc->server;
+
+ if (((req->present&XkbVirtualModsMask)==0)||(req->virtualMods==0))
+ return (char *)wire;
+ for (i=nMods=0,bit=1;i<XkbNumVirtualMods;i++,bit<<=1) {
+ if (req->virtualMods&bit) {
+ if (srv->vmods[i]!=wire[nMods]) {
+ changes->map.changed|= XkbVirtualModsMask;
+ changes->map.vmods|= bit;
+ srv->vmods[i]= wire[nMods];
+ }
+ nMods++;
+ }
+ }
+ return (char *)(wire+XkbPaddedSize(nMods));
+}
+
+static char *
+SetKeyExplicit(XkbSrvInfoPtr xkbi,xkbSetMapReq *req,CARD8 *wire,
+ XkbChangesPtr changes)
+{
+register unsigned i,first,last;
+XkbServerMapPtr xkb = xkbi->desc->server;
+CARD8 * start;
+
+ start= wire;
+ first= req->firstKeyExplicit;
+ last= req->firstKeyExplicit+req->nKeyExplicit-1;
+ bzero(&xkb->explicit[first],req->nKeyExplicit);
+ for (i=0;i<req->totalKeyExplicit;i++,wire+= 2) {
+ xkb->explicit[wire[0]]= wire[1];
+ }
+ if (first>0) {
+ if (changes->map.changed&XkbExplicitComponentsMask) {
+ int oldLast;
+ oldLast= changes->map.first_key_explicit+
+ changes->map.num_key_explicit-1;
+ if (changes->map.first_key_explicit<first)
+ first= changes->map.first_key_explicit;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.first_key_explicit= first;
+ changes->map.num_key_explicit= (last-first)+1;
+ }
+ wire+= XkbPaddedSize(wire-start)-(wire-start);
+ return (char *)wire;
+}
+
+static char *
+SetModifierMap( XkbSrvInfoPtr xkbi,
+ xkbSetMapReq * req,
+ CARD8 * wire,
+ XkbChangesPtr changes)
+{
+register unsigned i,first,last;
+XkbClientMapPtr xkb = xkbi->desc->map;
+CARD8 * start;
+
+ start= wire;
+ first= req->firstModMapKey;
+ last= req->firstModMapKey+req->nModMapKeys-1;
+ bzero(&xkb->modmap[first],req->nModMapKeys);
+ for (i=0;i<req->totalModMapKeys;i++,wire+= 2) {
+ xkb->modmap[wire[0]]= wire[1];
+ }
+ if (first>0) {
+ if (changes->map.changed&XkbModifierMapMask) {
+ int oldLast;
+ oldLast= changes->map.first_modmap_key+
+ changes->map.num_modmap_keys-1;
+ if (changes->map.first_modmap_key<first)
+ first= changes->map.first_modmap_key;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.first_modmap_key= first;
+ changes->map.num_modmap_keys= (last-first)+1;
+ }
+ wire+= XkbPaddedSize(wire-start)-(wire-start);
+ return (char *)wire;
+}
+
+static char *
+SetVirtualModMap( XkbSrvInfoPtr xkbi,
+ xkbSetMapReq * req,
+ xkbVModMapWireDesc * wire,
+ XkbChangesPtr changes)
+{
+register unsigned i,first,last;
+XkbServerMapPtr srv = xkbi->desc->server;
+
+ first= req->firstVModMapKey;
+ last= req->firstVModMapKey+req->nVModMapKeys-1;
+ bzero(&srv->vmodmap[first],req->nVModMapKeys*sizeof(unsigned short));
+ for (i=0;i<req->totalVModMapKeys;i++,wire++) {
+ srv->vmodmap[wire->key]= wire->vmods;
+ }
+ if (first>0) {
+ if (changes->map.changed&XkbVirtualModMapMask) {
+ int oldLast;
+ oldLast= changes->map.first_vmodmap_key+
+ changes->map.num_vmodmap_keys-1;
+ if (changes->map.first_vmodmap_key<first)
+ first= changes->map.first_vmodmap_key;
+ if (oldLast>last)
+ last= oldLast;
+ }
+ changes->map.first_vmodmap_key= first;
+ changes->map.num_vmodmap_keys= (last-first)+1;
+ }
+ return (char *)wire;
+}
+
+/**
+ * Check if the given request can be applied to the given device but don't
+ * actually do anything..
+ */
+static int
+_XkbSetMapChecks(ClientPtr client, DeviceIntPtr dev, xkbSetMapReq *req, char* values)
+{
+ XkbSrvInfoPtr xkbi;
+ XkbDescPtr xkb;
+ int error;
+ int nTypes = 0, nActions;
+ CARD8 mapWidths[XkbMaxLegalKeyCode + 1];
+ CARD16 symsPerKey[XkbMaxLegalKeyCode + 1];
+
+ xkbi= dev->key->xkbInfo;
+ xkb = xkbi->desc;
+
+ if ((xkb->min_key_code != req->minKeyCode)||
+ (xkb->max_key_code != req->maxKeyCode)) {
+ if (client->vMajor!=1) { /* pre 1.0 versions of Xlib have a bug */
+ req->minKeyCode= xkb->min_key_code;
+ req->maxKeyCode= xkb->max_key_code;
+ }
+ else {
+ if (!XkbIsLegalKeycode(req->minKeyCode)) {
+ client->errorValue = _XkbErrCode3(2, req->minKeyCode, req->maxKeyCode);
+ return BadValue;
+ }
+ if (req->minKeyCode > req->maxKeyCode) {
+ client->errorValue = _XkbErrCode3(3, req->minKeyCode, req->maxKeyCode);
+ return BadMatch;
+ }
+ }
+ }
+
+ if ((req->present & XkbKeyTypesMask) &&
+ (!CheckKeyTypes(client,xkb,req,(xkbKeyTypeWireDesc **)&values,
+ &nTypes,mapWidths))) {
+ client->errorValue = nTypes;
+ return BadValue;
+ }
+ if ((req->present & XkbKeySymsMask) &&
+ (!CheckKeySyms(client,xkb,req,nTypes,mapWidths,symsPerKey,
+ (xkbSymMapWireDesc **)&values,&error))) {
+ client->errorValue = error;
+ return BadValue;
+ }
+
+ if ((req->present & XkbKeyActionsMask) &&
+ (!CheckKeyActions(xkb,req,nTypes,mapWidths,symsPerKey,
+ (CARD8 **)&values,&nActions))) {
+ client->errorValue = nActions;
+ return BadValue;
+ }
+
+ if ((req->present & XkbKeyBehaviorsMask) &&
+ (!CheckKeyBehaviors(xkb,req,(xkbBehaviorWireDesc**)&values,&error))) {
+ client->errorValue = error;
+ return BadValue;
+ }
+
+ if ((req->present & XkbVirtualModsMask) &&
+ (!CheckVirtualMods(xkb,req,(CARD8 **)&values,&error))) {
+ client->errorValue= error;
+ return BadValue;
+ }
+ if ((req->present&XkbExplicitComponentsMask) &&
+ (!CheckKeyExplicit(xkb,req,(CARD8 **)&values,&error))) {
+ client->errorValue= error;
+ return BadValue;
+ }
+ if ((req->present&XkbModifierMapMask) &&
+ (!CheckModifierMap(xkb,req,(CARD8 **)&values,&error))) {
+ client->errorValue= error;
+ return BadValue;
+ }
+ if ((req->present&XkbVirtualModMapMask) &&
+ (!CheckVirtualModMap(xkb,req,(xkbVModMapWireDesc **)&values,&error))) {
+ client->errorValue= error;
+ return BadValue;
+ }
+
+ if (((values-((char *)req))/4)!= req->length) {
+ ErrorF("[xkb] Internal error! Bad length in XkbSetMap (after check)\n");
+ client->errorValue = values-((char *)&req[1]);
+ return BadLength;
+ }
+
+ return Success;
+}
+
+/**
+ * Apply the given request on the given device.
+ */
+static int
+_XkbSetMap(ClientPtr client, DeviceIntPtr dev, xkbSetMapReq *req, char *values)
+{
+ XkbEventCauseRec cause;
+ XkbChangesRec change;
+ Bool sentNKN;
+ XkbSrvInfoPtr xkbi;
+ XkbDescPtr xkb;
+
+ xkbi= dev->key->xkbInfo;
+ xkb = xkbi->desc;
+
+ XkbSetCauseXkbReq(&cause,X_kbSetMap,client);
+ bzero(&change, sizeof(change));
+ sentNKN = False;
+ if ((xkb->min_key_code!=req->minKeyCode)||
+ (xkb->max_key_code!=req->maxKeyCode)) {
+ Status status;
+ xkbNewKeyboardNotify nkn;
+ nkn.deviceID = nkn.oldDeviceID = dev->id;
+ nkn.oldMinKeyCode = xkb->min_key_code;
+ nkn.oldMaxKeyCode = xkb->max_key_code;
+ status= XkbChangeKeycodeRange(xkb, req->minKeyCode,
+ req->maxKeyCode, &change);
+ if (status != Success)
+ return status; /* oh-oh. what about the other keyboards? */
+ nkn.minKeyCode = xkb->min_key_code;
+ nkn.maxKeyCode = xkb->max_key_code;
+ nkn.requestMajor = XkbReqCode;
+ nkn.requestMinor = X_kbSetMap;
+ nkn.changed = XkbNKN_KeycodesMask;
+ XkbSendNewKeyboardNotify(dev,&nkn);
+ sentNKN = True;
+ }
+
+ if (req->present&XkbKeyTypesMask) {
+ values = SetKeyTypes(xkb,req,(xkbKeyTypeWireDesc *)values,&change);
+ if (!values) goto allocFailure;
+ }
+ if (req->present&XkbKeySymsMask) {
+ values = SetKeySyms(client,xkb,req,(xkbSymMapWireDesc *)values,&change,dev);
+ if (!values) goto allocFailure;
+ }
+ if (req->present&XkbKeyActionsMask) {
+ values = SetKeyActions(xkb,req,(CARD8 *)values,&change);
+ if (!values) goto allocFailure;
+ }
+ if (req->present&XkbKeyBehaviorsMask) {
+ values= SetKeyBehaviors(xkbi,req,(xkbBehaviorWireDesc *)values,&change);
+ if (!values) goto allocFailure;
+ }
+ if (req->present&XkbVirtualModsMask)
+ values= SetVirtualMods(xkbi,req,(CARD8 *)values,&change);
+ if (req->present&XkbExplicitComponentsMask)
+ values= SetKeyExplicit(xkbi,req,(CARD8 *)values,&change);
+ if (req->present&XkbModifierMapMask)
+ values= SetModifierMap(xkbi,req,(CARD8 *)values,&change);
+ if (req->present&XkbVirtualModMapMask)
+ values= SetVirtualModMap(xkbi,req,(xkbVModMapWireDesc *)values,&change);
+ if (((values-((char *)req))/4)!=req->length) {
+ ErrorF("[xkb] Internal error! Bad length in XkbSetMap (after set)\n");
+ client->errorValue = values-((char *)&req[1]);
+ return BadLength;
+ }
+ if (req->flags&XkbSetMapRecomputeActions) {
+ KeyCode first,last,firstMM,lastMM;
+ if (change.map.num_key_syms>0) {
+ first= change.map.first_key_sym;
+ last= first+change.map.num_key_syms-1;
+ }
+ else first= last= 0;
+ if (change.map.num_modmap_keys>0) {
+ firstMM= change.map.first_modmap_key;
+ lastMM= first+change.map.num_modmap_keys-1;
+ }
+ else firstMM= lastMM= 0;
+ if ((last>0) && (lastMM>0)) {
+ if (firstMM<first)
+ first= firstMM;
+ if (lastMM>last)
+ last= lastMM;
+ }
+ else if (lastMM>0) {
+ first= firstMM;
+ last= lastMM;
+ }
+ if (last>0) {
+ unsigned check= 0;
+ XkbUpdateActions(dev,first,(last-first+1),&change,&check,&cause);
+ if (check)
+ XkbCheckSecondaryEffects(xkbi,check,&change,&cause);
+ }
+ }
+ if (!sentNKN)
+ XkbSendNotification(dev,&change,&cause);
+
+ return Success;
+allocFailure:
+ return BadAlloc;
+}
+
+
+int
+ProcXkbSetMap(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ char * tmp;
+ int rc;
+
+ REQUEST(xkbSetMapReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+ CHK_MASK_LEGAL(0x01,stuff->present,XkbAllMapComponentsMask);
+
+ tmp = (char *)&stuff[1];
+
+ /* Check if we can to the SetMap on the requested device. If this
+ succeeds, do the same thing for all extension devices (if needed).
+ If any of them fails, fail. */
+ rc = _XkbSetMapChecks(client, dev, stuff, tmp);
+
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ rc = _XkbSetMapChecks(client, other, stuff, tmp);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ /* We know now that we will succed with the SetMap. In theory anyway. */
+ rc = _XkbSetMap(client, dev, stuff, tmp);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ _XkbSetMap(client, other, stuff, tmp);
+ /* ignore rc. if the SetMap failed although the check above
+ reported true there isn't much we can do. we still need to
+ set all other devices, hoping that at least they stay in
+ sync. */
+ }
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static Status
+XkbComputeGetCompatMapReplySize( XkbCompatMapPtr compat,
+ xkbGetCompatMapReply * rep)
+{
+unsigned size,nGroups;
+
+ nGroups= 0;
+ if (rep->groups!=0) {
+ register int i,bit;
+ for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) {
+ if (rep->groups&bit)
+ nGroups++;
+ }
+ }
+ size= nGroups*SIZEOF(xkbModsWireDesc);
+ size+= (rep->nSI*SIZEOF(xkbSymInterpretWireDesc));
+ rep->length= size/4;
+ return Success;
+}
+
+static int
+XkbSendCompatMap( ClientPtr client,
+ XkbCompatMapPtr compat,
+ xkbGetCompatMapReply * rep)
+{
+char * data;
+int size;
+
+ size= rep->length*4;
+ if (size>0) {
+ data = xalloc(size);
+ if (data) {
+ register unsigned i,bit;
+ xkbModsWireDesc * grp;
+ XkbSymInterpretPtr sym= &compat->sym_interpret[rep->firstSI];
+ xkbSymInterpretWireDesc *wire = (xkbSymInterpretWireDesc *)data;
+ for (i=0;i<rep->nSI;i++,sym++,wire++) {
+ wire->sym= sym->sym;
+ wire->mods= sym->mods;
+ wire->match= sym->match;
+ wire->virtualMod= sym->virtual_mod;
+ wire->flags= sym->flags;
+ memcpy((char*)&wire->act,(char*)&sym->act,sz_xkbActionWireDesc);
+ if (client->swapped) {
+ register int n;
+ swapl(&wire->sym,n);
+ }
+ }
+ if (rep->groups) {
+ grp = (xkbModsWireDesc *)wire;
+ for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) {
+ if (rep->groups&bit) {
+ grp->mask= compat->groups[i].mask;
+ grp->realMods= compat->groups[i].real_mods;
+ grp->virtualMods= compat->groups[i].vmods;
+ if (client->swapped) {
+ register int n;
+ swaps(&grp->virtualMods,n);
+ }
+ grp++;
+ }
+ }
+ wire= (xkbSymInterpretWireDesc*)grp;
+ }
+ }
+ else return BadAlloc;
+ }
+ else data= NULL;
+
+ if (client->swapped) {
+ register int n;
+ swaps(&rep->sequenceNumber,n);
+ swapl(&rep->length,n);
+ swaps(&rep->firstSI,n);
+ swaps(&rep->nSI,n);
+ swaps(&rep->nTotalSI,n);
+ }
+
+ WriteToClient(client, SIZEOF(xkbGetCompatMapReply), (char *)rep);
+ if (data) {
+ WriteToClient(client, size, data);
+ xfree((char *)data);
+ }
+ return client->noClientException;
+}
+
+int
+ProcXkbGetCompatMap(ClientPtr client)
+{
+ xkbGetCompatMapReply rep;
+ DeviceIntPtr dev;
+ XkbDescPtr xkb;
+ XkbCompatMapPtr compat;
+
+ REQUEST(xkbGetCompatMapReq);
+ REQUEST_SIZE_MATCH(xkbGetCompatMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+
+ xkb = dev->key->xkbInfo->desc;
+ compat= xkb->compat;
+
+ rep.type = X_Reply;
+ rep.deviceID = dev->id;
+ rep.sequenceNumber = client->sequence;
+ rep.length = 0;
+ rep.firstSI = stuff->firstSI;
+ rep.nSI = stuff->nSI;
+ if (stuff->getAllSI) {
+ rep.firstSI = 0;
+ rep.nSI = compat->num_si;
+ }
+ else if ((((unsigned)stuff->nSI)>0)&&
+ ((unsigned)(stuff->firstSI+stuff->nSI-1)>=compat->num_si)) {
+ client->errorValue = _XkbErrCode2(0x05,compat->num_si);
+ return BadValue;
+ }
+ rep.nTotalSI = compat->num_si;
+ rep.groups= stuff->groups;
+ XkbComputeGetCompatMapReplySize(compat,&rep);
+ return XkbSendCompatMap(client,compat,&rep);
+}
+
+/**
+ * Apply the given request on the given device.
+ * If dryRun is True, then value checks are performed, but the device isn't
+ * modified.
+ */
+static int
+_XkbSetCompatMap(ClientPtr client, DeviceIntPtr dev,
+ xkbSetCompatMapReq *req, char* data, BOOL dryRun)
+{
+ XkbSrvInfoPtr xkbi;
+ XkbDescPtr xkb;
+ XkbCompatMapPtr compat;
+ int nGroups;
+ unsigned i,bit;
+
+ xkbi = dev->key->xkbInfo;
+ xkb = xkbi->desc;
+ compat = xkb->compat;
+
+ if ((req->nSI>0)||(req->truncateSI)) {
+ xkbSymInterpretWireDesc *wire;
+ if (req->firstSI>compat->num_si) {
+ client->errorValue = _XkbErrCode2(0x02,compat->num_si);
+ return BadValue;
+ }
+ wire= (xkbSymInterpretWireDesc *)data;
+ wire+= req->nSI;
+ data = (char *)wire;
+ }
+
+ nGroups= 0;
+ if (req->groups!=0) {
+ for (i=0,bit=1;i<XkbNumKbdGroups;i++,bit<<=1) {
+ if ( req->groups&bit )
+ nGroups++;
+ }
+ }
+ data+= nGroups*SIZEOF(xkbModsWireDesc);
+ if (((data-((char *)req))/4)!=req->length) {
+ return BadLength;
+ }
+
+ /* Done all the checks we can do */
+ if (dryRun)
+ return Success;
+
+ data = (char *)&req[1];
+ if (req->nSI>0) {
+ xkbSymInterpretWireDesc *wire = (xkbSymInterpretWireDesc *)data;
+ XkbSymInterpretPtr sym;
+ if ((unsigned)(req->firstSI+req->nSI)>compat->num_si) {
+ compat->num_si= req->firstSI+req->nSI;
+ compat->sym_interpret= _XkbTypedRealloc(compat->sym_interpret,
+ compat->num_si,
+ XkbSymInterpretRec);
+ if (!compat->sym_interpret) {
+ compat->num_si= 0;
+ return BadAlloc;
+ }
+ }
+ else if (req->truncateSI) {
+ compat->num_si = req->firstSI+req->nSI;
+ }
+ sym = &compat->sym_interpret[req->firstSI];
+ for (i=0;i<req->nSI;i++,wire++,sym++) {
+ if (client->swapped) {
+ int n;
+ swapl(&wire->sym,n);
+ }
+ sym->sym= wire->sym;
+ sym->mods= wire->mods;
+ sym->match= wire->match;
+ sym->flags= wire->flags;
+ sym->virtual_mod= wire->virtualMod;
+ memcpy((char *)&sym->act,(char *)&wire->act,
+ SIZEOF(xkbActionWireDesc));
+ }
+ data = (char *)wire;
+ }
+ else if (req->truncateSI) {
+ compat->num_si = req->firstSI;
+ }
+
+ if (req->groups!=0) {
+ unsigned i, bit;
+ xkbModsWireDesc *wire = (xkbModsWireDesc *)data;
+ for (i = 0, bit = 1; i < XkbNumKbdGroups; i++, bit <<= 1) {
+ if (req->groups & bit) {
+ if (client->swapped) {
+ int n;
+ swaps(&wire->virtualMods,n);
+ }
+ compat->groups[i].mask= wire->realMods;
+ compat->groups[i].real_mods= wire->realMods;
+ compat->groups[i].vmods= wire->virtualMods;
+ if (wire->virtualMods!=0) {
+ unsigned tmp;
+ tmp= XkbMaskForVMask(xkb,wire->virtualMods);
+ compat->groups[i].mask|= tmp;
+ }
+ data+= SIZEOF(xkbModsWireDesc);
+ wire= (xkbModsWireDesc *)data;
+ }
+ }
+ }
+ i= XkbPaddedSize((data-((char *)req)));
+ if ((i/4)!=req->length) {
+ ErrorF("[xkb] Internal length error on read in _XkbSetCompatMap\n");
+ return BadLength;
+ }
+
+ if (dev->xkb_interest) {
+ xkbCompatMapNotify ev;
+ ev.deviceID = dev->id;
+ ev.changedGroups = req->groups;
+ ev.firstSI = req->firstSI;
+ ev.nSI = req->nSI;
+ ev.nTotalSI = compat->num_si;
+ XkbSendCompatMapNotify(dev,&ev);
+ }
+
+ if (req->recomputeActions) {
+ XkbChangesRec change;
+ unsigned check;
+ XkbEventCauseRec cause;
+
+ XkbSetCauseXkbReq(&cause,X_kbSetCompatMap,client);
+ bzero(&change,sizeof(XkbChangesRec));
+ XkbUpdateActions(dev,xkb->min_key_code,XkbNumKeys(xkb),&change,&check,
+ &cause);
+ if (check)
+ XkbCheckSecondaryEffects(xkbi,check,&change,&cause);
+ XkbSendNotification(dev,&change,&cause);
+ }
+ return Success;
+}
+
+int
+ProcXkbSetCompatMap(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ char *data;
+ int rc;
+
+ REQUEST(xkbSetCompatMapReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetCompatMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+
+ data = (char *)&stuff[1];
+
+ /* check first using a dry-run */
+ rc = _XkbSetCompatMap(client, dev, stuff, data, TRUE);
+ if (rc != Success)
+ return rc;
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ /* dry-run */
+ rc = _XkbSetCompatMap(client, other, stuff, data, TRUE);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ /* Yay, the dry-runs succeed. Let's apply */
+ rc = _XkbSetCompatMap(client, dev, stuff, data, FALSE);
+ if (rc != Success)
+ return rc;
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ rc = _XkbSetCompatMap(client, other, stuff, data, FALSE);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbGetIndicatorState(ClientPtr client)
+{
+ xkbGetIndicatorStateReply rep;
+ XkbSrvLedInfoPtr sli;
+ DeviceIntPtr dev;
+ register int i;
+
+ REQUEST(xkbGetIndicatorStateReq);
+ REQUEST_SIZE_MATCH(xkbGetIndicatorStateReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess);
+
+ sli= XkbFindSrvLedInfo(dev,XkbDfltXIClass,XkbDfltXIId,
+ XkbXI_IndicatorStateMask);
+ if (!sli)
+ return BadAlloc;
+
+ rep.type = X_Reply;
+ rep.sequenceNumber = client->sequence;
+ rep.length = 0;
+ rep.deviceID = dev->id;
+ rep.state = sli->effectiveState;
+
+ if (client->swapped) {
+ swaps(&rep.sequenceNumber,i);
+ swapl(&rep.state,i);
+ }
+ WriteToClient(client, SIZEOF(xkbGetIndicatorStateReply), (char *)&rep);
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static Status
+XkbComputeGetIndicatorMapReplySize(
+ XkbIndicatorPtr indicators,
+ xkbGetIndicatorMapReply *rep)
+{
+register int i,bit;
+int nIndicators;
+
+ rep->realIndicators = indicators->phys_indicators;
+ for (i=nIndicators=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (rep->which&bit)
+ nIndicators++;
+ }
+ rep->length = (nIndicators*SIZEOF(xkbIndicatorMapWireDesc))/4;
+ return Success;
+}
+
+static int
+XkbSendIndicatorMap( ClientPtr client,
+ XkbIndicatorPtr indicators,
+ xkbGetIndicatorMapReply * rep)
+{
+int length;
+CARD8 * map;
+register int i;
+register unsigned bit;
+
+ length = rep->length*4;
+ if (length>0) {
+ CARD8 *to;
+ to= map= xalloc(length);
+ if (map) {
+ xkbIndicatorMapWireDesc *wire = (xkbIndicatorMapWireDesc *)to;
+ for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (rep->which&bit) {
+ wire->flags= indicators->maps[i].flags;
+ wire->whichGroups= indicators->maps[i].which_groups;
+ wire->groups= indicators->maps[i].groups;
+ wire->whichMods= indicators->maps[i].which_mods;
+ wire->mods= indicators->maps[i].mods.mask;
+ wire->realMods= indicators->maps[i].mods.real_mods;
+ wire->virtualMods= indicators->maps[i].mods.vmods;
+ wire->ctrls= indicators->maps[i].ctrls;
+ if (client->swapped) {
+ register int n;
+ swaps(&wire->virtualMods,n);
+ swapl(&wire->ctrls,n);
+ }
+ wire++;
+ }
+ }
+ to = (CARD8 *)wire;
+ if ((to-map)!=length) {
+ client->errorValue = _XkbErrCode2(0xff,length);
+ return BadLength;
+ }
+ }
+ else return BadAlloc;
+ }
+ else map = NULL;
+ if (client->swapped) {
+ swaps(&rep->sequenceNumber,i);
+ swapl(&rep->length,i);
+ swapl(&rep->which,i);
+ swapl(&rep->realIndicators,i);
+ }
+ WriteToClient(client, SIZEOF(xkbGetIndicatorMapReply), (char *)rep);
+ if (map) {
+ WriteToClient(client, length, (char *)map);
+ xfree((char *)map);
+ }
+ return client->noClientException;
+}
+
+int
+ProcXkbGetIndicatorMap(ClientPtr client)
+{
+xkbGetIndicatorMapReply rep;
+DeviceIntPtr dev;
+XkbDescPtr xkb;
+XkbIndicatorPtr leds;
+
+ REQUEST(xkbGetIndicatorMapReq);
+ REQUEST_SIZE_MATCH(xkbGetIndicatorMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+
+ xkb= dev->key->xkbInfo->desc;
+ leds= xkb->indicators;
+
+ rep.type = X_Reply;
+ rep.sequenceNumber = client->sequence;
+ rep.length = 0;
+ rep.deviceID = dev->id;
+ rep.which = stuff->which;
+ XkbComputeGetIndicatorMapReplySize(leds,&rep);
+ return XkbSendIndicatorMap(client,leds,&rep);
+}
+
+/**
+ * Apply the given map to the given device. Which specifies which components
+ * to apply.
+ */
+static int
+_XkbSetIndicatorMap(ClientPtr client, DeviceIntPtr dev,
+ int which, xkbIndicatorMapWireDesc *desc)
+{
+ XkbSrvInfoPtr xkbi;
+ XkbSrvLedInfoPtr sli;
+ XkbEventCauseRec cause;
+ int i, bit;
+
+ xkbi = dev->key->xkbInfo;
+
+ sli= XkbFindSrvLedInfo(dev, XkbDfltXIClass, XkbDfltXIId,
+ XkbXI_IndicatorMapsMask);
+ if (!sli)
+ return BadAlloc;
+
+ for (i = 0, bit = 1; i < XkbNumIndicators; i++, bit <<= 1) {
+ if (which & bit) {
+ sli->maps[i].flags = desc->flags;
+ sli->maps[i].which_groups = desc->whichGroups;
+ sli->maps[i].groups = desc->groups;
+ sli->maps[i].which_mods = desc->whichMods;
+ sli->maps[i].mods.mask = desc->mods;
+ sli->maps[i].mods.real_mods = desc->mods;
+ sli->maps[i].mods.vmods= desc->virtualMods;
+ sli->maps[i].ctrls = desc->ctrls;
+ if (desc->virtualMods!=0) {
+ unsigned tmp;
+ tmp= XkbMaskForVMask(xkbi->desc,desc->virtualMods);
+ sli->maps[i].mods.mask= desc->mods|tmp;
+ }
+ desc++;
+ }
+ }
+
+ XkbSetCauseXkbReq(&cause,X_kbSetIndicatorMap,client);
+ XkbApplyLedMapChanges(dev,sli,which,NULL,NULL,&cause);
+
+ return Success;
+}
+
+int
+ProcXkbSetIndicatorMap(ClientPtr client)
+{
+ int i, bit;
+ int nIndicators;
+ DeviceIntPtr dev;
+ xkbIndicatorMapWireDesc *from;
+ int rc;
+
+ REQUEST(xkbSetIndicatorMapReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetIndicatorMapReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess);
+
+ if (stuff->which==0)
+ return client->noClientException;
+
+ for (nIndicators=i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (stuff->which&bit)
+ nIndicators++;
+ }
+ if (stuff->length!=((SIZEOF(xkbSetIndicatorMapReq)+
+ (nIndicators*SIZEOF(xkbIndicatorMapWireDesc)))/4)) {
+ return BadLength;
+ }
+
+ from = (xkbIndicatorMapWireDesc *)&stuff[1];
+ for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (stuff->which&bit) {
+ if (client->swapped) {
+ int n;
+ swaps(&from->virtualMods,n);
+ swapl(&from->ctrls,n);
+ }
+ CHK_MASK_LEGAL(i,from->whichGroups,XkbIM_UseAnyGroup);
+ CHK_MASK_LEGAL(i,from->whichMods,XkbIM_UseAnyMods);
+ from++;
+ }
+ }
+
+ from = (xkbIndicatorMapWireDesc *)&stuff[1];
+ rc = _XkbSetIndicatorMap(client, dev, stuff->which, from);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess);
+ if (rc == Success)
+ _XkbSetIndicatorMap(client, other, stuff->which, from);
+ }
+ }
+ }
+
+ return Success;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbGetNamedIndicator(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ xkbGetNamedIndicatorReply rep;
+ register int i = 0;
+ XkbSrvLedInfoPtr sli;
+ XkbIndicatorMapPtr map = NULL;
+
+ REQUEST(xkbGetNamedIndicatorReq);
+ REQUEST_SIZE_MATCH(xkbGetNamedIndicatorReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_LED_DEVICE(dev, stuff->deviceSpec, client, DixReadAccess);
+ CHK_ATOM_ONLY(stuff->indicator);
+
+ sli= XkbFindSrvLedInfo(dev,stuff->ledClass,stuff->ledID,0);
+ if (!sli)
+ return BadAlloc;
+
+ i= 0;
+ map= NULL;
+ if ((sli->names)&&(sli->maps)) {
+ for (i=0;i<XkbNumIndicators;i++) {
+ if (stuff->indicator==sli->names[i]) {
+ map= &sli->maps[i];
+ break;
+ }
+ }
+ }
+
+ rep.type= X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.deviceID = dev->id;
+ rep.indicator= stuff->indicator;
+ if (map!=NULL) {
+ rep.found= True;
+ rep.on= ((sli->effectiveState&(1<<i))!=0);
+ rep.realIndicator= ((sli->physIndicators&(1<<i))!=0);
+ rep.ndx= i;
+ rep.flags= map->flags;
+ rep.whichGroups= map->which_groups;
+ rep.groups= map->groups;
+ rep.whichMods= map->which_mods;
+ rep.mods= map->mods.mask;
+ rep.realMods= map->mods.real_mods;
+ rep.virtualMods= map->mods.vmods;
+ rep.ctrls= map->ctrls;
+ rep.supported= True;
+ }
+ else {
+ rep.found= False;
+ rep.on= False;
+ rep.realIndicator= False;
+ rep.ndx= XkbNoIndicator;
+ rep.flags= 0;
+ rep.whichGroups= 0;
+ rep.groups= 0;
+ rep.whichMods= 0;
+ rep.mods= 0;
+ rep.realMods= 0;
+ rep.virtualMods= 0;
+ rep.ctrls= 0;
+ rep.supported= True;
+ }
+ if ( client->swapped ) {
+ register int n;
+ swapl(&rep.length,n);
+ swaps(&rep.sequenceNumber,n);
+ swapl(&rep.indicator,n);
+ swaps(&rep.virtualMods,n);
+ swapl(&rep.ctrls,n);
+ }
+
+ WriteToClient(client,SIZEOF(xkbGetNamedIndicatorReply), (char *)&rep);
+ return client->noClientException;
+}
+
+
+/**
+ * Find the IM on the device.
+ * Returns the map, or NULL if the map doesn't exist.
+ * If the return value is NULL, led_return is undefined. Otherwise, led_return
+ * is set to the led index of the map.
+ */
+static XkbIndicatorMapPtr
+_XkbFindNamedIndicatorMap(XkbSrvLedInfoPtr sli, Atom indicator,
+ int *led_return)
+{
+ XkbIndicatorMapPtr map;
+ int led;
+
+ /* search for the right indicator */
+ map = NULL;
+ if (sli->names && sli->maps) {
+ for (led = 0; (led < XkbNumIndicators) && (map == NULL); led++) {
+ if (sli->names[led] == indicator) {
+ map= &sli->maps[led];
+ break;
+ }
+ }
+ }
+
+ *led_return = led;
+ return map;
+}
+
+/**
+ * Creates an indicator map on the device. If dryRun is True, it only checks
+ * if creation is possible, but doesn't actually create it.
+ */
+static int
+_XkbCreateIndicatorMap(DeviceIntPtr dev, Atom indicator,
+ int ledClass, int ledID,
+ XkbIndicatorMapPtr *map_return, int *led_return,
+ Bool dryRun)
+{
+ XkbSrvLedInfoPtr sli;
+ XkbIndicatorMapPtr map;
+ int led;
+
+ sli = XkbFindSrvLedInfo(dev, ledClass, ledID, XkbXI_IndicatorsMask);
+ if (!sli)
+ return BadAlloc;
+
+ map = _XkbFindNamedIndicatorMap(sli, indicator, &led);
+
+ if (!map)
+ {
+ /* find first unused indicator maps and assign the name to it */
+ for (led = 0, map = NULL; (led < XkbNumIndicators) && (map == NULL); led++) {
+ if ((sli->names) && (sli->maps) && (sli->names[led] == None) &&
+ (!XkbIM_InUse(&sli->maps[led])))
+ {
+ map = &sli->maps[led];
+ if (!dryRun)
+ sli->names[led] = indicator;
+ break;
+ }
+ }
+ }
+
+ if (!map)
+ return BadAlloc;
+
+ *led_return = led;
+ *map_return = map;
+ return Success;
+}
+
+static int
+_XkbSetNamedIndicator(ClientPtr client, DeviceIntPtr dev,
+ xkbSetNamedIndicatorReq *stuff)
+{
+ unsigned int extDevReason;
+ unsigned int statec, namec, mapc;
+ XkbSrvLedInfoPtr sli;
+ int led = 0;
+ XkbIndicatorMapPtr map;
+ DeviceIntPtr kbd;
+ XkbEventCauseRec cause;
+ xkbExtensionDeviceNotify ed;
+ XkbChangesRec changes;
+ int rc;
+
+ rc = _XkbCreateIndicatorMap(dev, stuff->indicator, stuff->ledClass,
+ stuff->ledID, &map, &led, FALSE);
+ if (rc != Success || !map) /* oh-oh */
+ return rc;
+
+ sli = XkbFindSrvLedInfo(dev, stuff->ledClass, stuff->ledID,
+ XkbXI_IndicatorsMask);
+ if (!sli)
+ return BadAlloc;
+
+ namec = mapc = statec = 0;
+ extDevReason = 0;
+
+ namec |= (1<<led);
+ sli->namesPresent |= ((stuff->indicator != None) ? (1 << led) : 0);
+ extDevReason |= XkbXI_IndicatorNamesMask;
+
+ if (stuff->setMap) {
+ map->flags = stuff->flags;
+ map->which_groups = stuff->whichGroups;
+ map->groups = stuff->groups;
+ map->which_mods = stuff->whichMods;
+ map->mods.mask = stuff->realMods;
+ map->mods.real_mods = stuff->realMods;
+ map->mods.vmods= stuff->virtualMods;
+ map->ctrls = stuff->ctrls;
+ mapc|= (1<<led);
+ }
+
+ if ((stuff->setState) && ((map->flags & XkbIM_NoExplicit) == 0))
+ {
+ if (stuff->on) sli->explicitState |= (1<<led);
+ else sli->explicitState &= ~(1<<led);
+ statec |= ((sli->effectiveState ^ sli->explicitState) & (1 << led));
+ }
+
+ bzero((char *)&ed,sizeof(xkbExtensionDeviceNotify));
+ bzero((char *)&changes,sizeof(XkbChangesRec));
+ XkbSetCauseXkbReq(&cause,X_kbSetNamedIndicator,client);
+ if (namec)
+ XkbApplyLedNameChanges(dev,sli,namec,&ed,&changes,&cause);
+ if (mapc)
+ XkbApplyLedMapChanges(dev,sli,mapc,&ed,&changes,&cause);
+ if (statec)
+ XkbApplyLedStateChanges(dev,sli,statec,&ed,&changes,&cause);
+
+ kbd = dev;
+ if ((sli->flags&XkbSLI_HasOwnState)==0)
+ kbd = inputInfo.keyboard;
+ XkbFlushLedEvents(dev, kbd, sli, &ed, &changes, &cause);
+
+ return Success;
+}
+
+int
+ProcXkbSetNamedIndicator(ClientPtr client)
+{
+ int rc;
+ DeviceIntPtr dev;
+ int led = 0;
+ XkbIndicatorMapPtr map;
+
+ REQUEST(xkbSetNamedIndicatorReq);
+ REQUEST_SIZE_MATCH(xkbSetNamedIndicatorReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_LED_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess);
+ CHK_ATOM_ONLY(stuff->indicator);
+ CHK_MASK_LEGAL(0x10,stuff->whichGroups,XkbIM_UseAnyGroup);
+ CHK_MASK_LEGAL(0x11,stuff->whichMods,XkbIM_UseAnyMods);
+
+ /* Dry-run for checks */
+ rc = _XkbCreateIndicatorMap(dev, stuff->indicator,
+ stuff->ledClass, stuff->ledID,
+ &map, &led, TRUE);
+ if (rc != Success || !map) /* couldn't be created or didn't exist */
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd ||
+ stuff->deviceSpec == XkbUseCorePtr)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && !IsMaster(other) && (other->u.master == dev) &&
+ (other->kbdfeed || other->leds) &&
+ (XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess) == Success))
+ {
+ rc = _XkbCreateIndicatorMap(other, stuff->indicator,
+ stuff->ledClass, stuff->ledID,
+ &map, &led, TRUE);
+ if (rc != Success || !map)
+ return rc;
+ }
+ }
+ }
+
+ /* All checks passed, let's do it */
+ rc = _XkbSetNamedIndicator(client, dev, stuff);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd ||
+ stuff->deviceSpec == XkbUseCorePtr)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && !IsMaster(other) && (other->u.master == dev) &&
+ (other->kbdfeed || other->leds) &&
+ (XaceHook(XACE_DEVICE_ACCESS, client, other, DixSetAttrAccess) == Success))
+ {
+ _XkbSetNamedIndicator(client, other, stuff);
+ }
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static CARD32
+_XkbCountAtoms(Atom *atoms,int maxAtoms,int *count)
+{
+register unsigned int i,bit,nAtoms;
+register CARD32 atomsPresent;
+
+ for (i=nAtoms=atomsPresent=0,bit=1;i<maxAtoms;i++,bit<<=1) {
+ if (atoms[i]!=None) {
+ atomsPresent|= bit;
+ nAtoms++;
+ }
+ }
+ if (count)
+ *count= nAtoms;
+ return atomsPresent;
+}
+
+static char *
+_XkbWriteAtoms(char *wire,Atom *atoms,int maxAtoms,int swap)
+{
+register unsigned int i;
+Atom *atm;
+
+ atm = (Atom *)wire;
+ for (i=0;i<maxAtoms;i++) {
+ if (atoms[i]!=None) {
+ *atm= atoms[i];
+ if (swap) {
+ register int n;
+ swapl(atm,n);
+ }
+ atm++;
+ }
+ }
+ return (char *)atm;
+}
+
+static Status
+XkbComputeGetNamesReplySize(XkbDescPtr xkb,xkbGetNamesReply *rep)
+{
+register unsigned which,length;
+register int i;
+
+ rep->minKeyCode= xkb->min_key_code;
+ rep->maxKeyCode= xkb->max_key_code;
+ which= rep->which;
+ length= 0;
+ if (xkb->names!=NULL) {
+ if (which&XkbKeycodesNameMask) length++;
+ if (which&XkbGeometryNameMask) length++;
+ if (which&XkbSymbolsNameMask) length++;
+ if (which&XkbPhysSymbolsNameMask) length++;
+ if (which&XkbTypesNameMask) length++;
+ if (which&XkbCompatNameMask) length++;
+ }
+ else which&= ~XkbComponentNamesMask;
+
+ if (xkb->map!=NULL) {
+ if (which&XkbKeyTypeNamesMask)
+ length+= xkb->map->num_types;
+ rep->nTypes= xkb->map->num_types;
+ if (which&XkbKTLevelNamesMask) {
+ XkbKeyTypePtr pType = xkb->map->types;
+ int nKTLevels = 0;
+
+ length+= XkbPaddedSize(xkb->map->num_types)/4;
+ for (i=0;i<xkb->map->num_types;i++,pType++) {
+ if (pType->level_names!=NULL)
+ nKTLevels+= pType->num_levels;
+ }
+ rep->nKTLevels= nKTLevels;
+ length+= nKTLevels;
+ }
+ }
+ else {
+ rep->nTypes= 0;
+ rep->nKTLevels= 0;
+ which&= ~(XkbKeyTypeNamesMask|XkbKTLevelNamesMask);
+ }
+
+ rep->minKeyCode= xkb->min_key_code;
+ rep->maxKeyCode= xkb->max_key_code;
+ rep->indicators= 0;
+ rep->virtualMods= 0;
+ rep->groupNames= 0;
+ if (xkb->names!=NULL) {
+ if (which&XkbIndicatorNamesMask) {
+ int nLeds;
+ rep->indicators=
+ _XkbCountAtoms(xkb->names->indicators,XkbNumIndicators,&nLeds);
+ length+= nLeds;
+ if (nLeds==0)
+ which&= ~XkbIndicatorNamesMask;
+ }
+
+ if (which&XkbVirtualModNamesMask) {
+ int nVMods;
+ rep->virtualMods=
+ _XkbCountAtoms(xkb->names->vmods,XkbNumVirtualMods,&nVMods);
+ length+= nVMods;
+ if (nVMods==0)
+ which&= ~XkbVirtualModNamesMask;
+ }
+
+ if (which&XkbGroupNamesMask) {
+ int nGroups;
+ rep->groupNames=
+ _XkbCountAtoms(xkb->names->groups,XkbNumKbdGroups,&nGroups);
+ length+= nGroups;
+ if (nGroups==0)
+ which&= ~XkbGroupNamesMask;
+ }
+
+ if ((which&XkbKeyNamesMask)&&(xkb->names->keys))
+ length+= rep->nKeys;
+ else which&= ~XkbKeyNamesMask;
+
+ if ((which&XkbKeyAliasesMask)&&
+ (xkb->names->key_aliases)&&(xkb->names->num_key_aliases>0)) {
+ rep->nKeyAliases= xkb->names->num_key_aliases;
+ length+= rep->nKeyAliases*2;
+ }
+ else {
+ which&= ~XkbKeyAliasesMask;
+ rep->nKeyAliases= 0;
+ }
+
+ if ((which&XkbRGNamesMask)&&(xkb->names->num_rg>0))
+ length+= xkb->names->num_rg;
+ else which&= ~XkbRGNamesMask;
+ }
+ else {
+ which&= ~(XkbIndicatorNamesMask|XkbVirtualModNamesMask);
+ which&= ~(XkbGroupNamesMask|XkbKeyNamesMask|XkbKeyAliasesMask);
+ which&= ~XkbRGNamesMask;
+ }
+
+ rep->length= length;
+ rep->which= which;
+ return Success;
+}
+
+static int
+XkbSendNames(ClientPtr client,XkbDescPtr xkb,xkbGetNamesReply *rep)
+{
+register unsigned i,length,which;
+char * start;
+char * desc;
+register int n;
+
+ length= rep->length*4;
+ which= rep->which;
+ if (client->swapped) {
+ swaps(&rep->sequenceNumber,n);
+ swapl(&rep->length,n);
+ swapl(&rep->which,n);
+ swaps(&rep->virtualMods,n);
+ swapl(&rep->indicators,n);
+ }
+
+ start = desc = xalloc(length);
+ if ( !start )
+ return BadAlloc;
+ if (xkb->names) {
+ if (which&XkbKeycodesNameMask) {
+ *((CARD32 *)desc)= xkb->names->keycodes;
+ if (client->swapped) {
+ swapl(desc,n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbGeometryNameMask) {
+ *((CARD32 *)desc)= xkb->names->geometry;
+ if (client->swapped) {
+ swapl(desc,n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbSymbolsNameMask) {
+ *((CARD32 *)desc)= xkb->names->symbols;
+ if (client->swapped) {
+ swapl(desc,n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbPhysSymbolsNameMask) {
+ register CARD32 *atm= (CARD32 *)desc;
+ atm[0]= (CARD32)xkb->names->phys_symbols;
+ if (client->swapped) {
+ swapl(&atm[0],n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbTypesNameMask) {
+ *((CARD32 *)desc)= (CARD32)xkb->names->types;
+ if (client->swapped) {
+ swapl(desc,n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbCompatNameMask) {
+ *((CARD32 *)desc)= (CARD32)xkb->names->compat;
+ if (client->swapped) {
+ swapl(desc,n);
+ }
+ desc+= 4;
+ }
+ if (which&XkbKeyTypeNamesMask) {
+ register CARD32 *atm= (CARD32 *)desc;
+ register XkbKeyTypePtr type= xkb->map->types;
+
+ for (i=0;i<xkb->map->num_types;i++,atm++,type++) {
+ *atm= (CARD32)type->name;
+ if (client->swapped) {
+ swapl(atm,n);
+ }
+ }
+ desc= (char *)atm;
+ }
+ if (which&XkbKTLevelNamesMask && xkb->map) {
+ XkbKeyTypePtr type = xkb->map->types;
+ register CARD32 *atm;
+ for (i=0;i<rep->nTypes;i++,type++) {
+ *desc++ = type->num_levels;
+ }
+ desc+= XkbPaddedSize(rep->nTypes)-rep->nTypes;
+
+ atm= (CARD32 *)desc;
+ type = xkb->map->types;
+ for (i=0;i<xkb->map->num_types;i++,type++) {
+ register unsigned l;
+ if (type->level_names) {
+ for (l=0;l<type->num_levels;l++,atm++) {
+ *atm= type->level_names[l];
+ if (client->swapped) {
+ swapl(atm,n);
+ }
+ }
+ desc+= type->num_levels*4;
+ }
+ }
+ }
+ if (which&XkbIndicatorNamesMask) {
+ desc= _XkbWriteAtoms(desc,xkb->names->indicators,XkbNumIndicators,
+ client->swapped);
+ }
+ if (which&XkbVirtualModNamesMask) {
+ desc= _XkbWriteAtoms(desc,xkb->names->vmods,XkbNumVirtualMods,
+ client->swapped);
+ }
+ if (which&XkbGroupNamesMask) {
+ desc= _XkbWriteAtoms(desc,xkb->names->groups,XkbNumKbdGroups,
+ client->swapped);
+ }
+ if (which&XkbKeyNamesMask) {
+ for (i=0;i<rep->nKeys;i++,desc+= sizeof(XkbKeyNameRec)) {
+ *((XkbKeyNamePtr)desc)= xkb->names->keys[i+rep->firstKey];
+ }
+ }
+ if (which&XkbKeyAliasesMask) {
+ XkbKeyAliasPtr pAl;
+ pAl= xkb->names->key_aliases;
+ for (i=0;i<rep->nKeyAliases;i++,pAl++,desc+=2*XkbKeyNameLength) {
+ *((XkbKeyAliasPtr)desc)= *pAl;
+ }
+ }
+ if ((which&XkbRGNamesMask)&&(rep->nRadioGroups>0)) {
+ register CARD32 *atm= (CARD32 *)desc;
+ for (i=0;i<rep->nRadioGroups;i++,atm++) {
+ *atm= (CARD32)xkb->names->radio_groups[i];
+ if (client->swapped) {
+ swapl(atm,n);
+ }
+ }
+ desc+= rep->nRadioGroups*4;
+ }
+ }
+
+ if ((desc-start)!=(length)) {
+ ErrorF("[xkb] BOGUS LENGTH in write names, expected %d, got %ld\n",
+ length, (unsigned long)(desc-start));
+ }
+ WriteToClient(client, SIZEOF(xkbGetNamesReply), (char *)rep);
+ WriteToClient(client, length, start);
+ xfree((char *)start);
+ return client->noClientException;
+}
+
+int
+ProcXkbGetNames(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ XkbDescPtr xkb;
+ xkbGetNamesReply rep;
+
+ REQUEST(xkbGetNamesReq);
+ REQUEST_SIZE_MATCH(xkbGetNamesReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+ CHK_MASK_LEGAL(0x01,stuff->which,XkbAllNamesMask);
+
+ xkb = dev->key->xkbInfo->desc;
+ memset(&rep, 0, sizeof(xkbGetNamesReply));
+ rep.type= X_Reply;
+ rep.sequenceNumber= client->sequence;
+ rep.length = 0;
+ rep.deviceID = dev->id;
+ rep.which = stuff->which;
+ rep.nTypes = xkb->map->num_types;
+ rep.firstKey = xkb->min_key_code;
+ rep.nKeys = XkbNumKeys(xkb);
+ if (xkb->names!=NULL) {
+ rep.nKeyAliases= xkb->names->num_key_aliases;
+ rep.nRadioGroups = xkb->names->num_rg;
+ }
+ else {
+ rep.nKeyAliases= rep.nRadioGroups= 0;
+ }
+ XkbComputeGetNamesReplySize(xkb,&rep);
+ return XkbSendNames(client,xkb,&rep);
+}
+
+/***====================================================================***/
+
+static CARD32 *
+_XkbCheckAtoms(CARD32 *wire,int nAtoms,int swapped,Atom *pError)
+{
+register int i;
+
+ for (i=0;i<nAtoms;i++,wire++) {
+ if (swapped) {
+ register int n;
+ swapl(wire,n);
+ }
+ if ((((Atom)*wire)!=None)&&(!ValidAtom((Atom)*wire))) {
+ *pError= ((Atom)*wire);
+ return NULL;
+ }
+ }
+ return wire;
+}
+
+static CARD32 *
+_XkbCheckMaskedAtoms(CARD32 *wire,int nAtoms,CARD32 present,int swapped,
+ Atom *pError)
+{
+register unsigned i,bit;
+
+ for (i=0,bit=1;(i<nAtoms)&&(present);i++,bit<<=1) {
+ if ((present&bit)==0)
+ continue;
+ if (swapped) {
+ register int n;
+ swapl(wire,n);
+ }
+ if ((((Atom)*wire)!=None)&&(!ValidAtom(((Atom)*wire)))) {
+ *pError= (Atom)*wire;
+ return NULL;
+ }
+ wire++;
+ }
+ return wire;
+}
+
+static Atom *
+_XkbCopyMaskedAtoms( Atom *wire,
+ Atom *dest,
+ int nAtoms,
+ CARD32 present)
+{
+register int i,bit;
+
+ for (i=0,bit=1;(i<nAtoms)&&(present);i++,bit<<=1) {
+ if ((present&bit)==0)
+ continue;
+ dest[i]= *wire++;
+ }
+ return wire;
+}
+
+static Bool
+_XkbCheckTypeName(Atom name,int typeNdx)
+{
+const char * str;
+
+ str= NameForAtom(name);
+ if ((strcmp(str,"ONE_LEVEL")==0)||(strcmp(str,"TWO_LEVEL")==0)||
+ (strcmp(str,"ALPHABETIC")==0)||(strcmp(str,"KEYPAD")==0))
+ return False;
+ return True;
+}
+
+/**
+ * Check the device-dependent data in the request against the device. Returns
+ * Success, or the appropriate error code.
+ */
+static int
+_XkbSetNamesCheck(ClientPtr client, DeviceIntPtr dev,
+ xkbSetNamesReq *stuff, CARD32 *data)
+{
+ XkbDescRec *xkb;
+ XkbNamesRec *names;
+ CARD32 *tmp;
+ Atom bad;
+
+ tmp = data;
+ xkb = dev->key->xkbInfo->desc;
+ names = xkb->names;
+
+
+ if (stuff->which & XkbKeyTypeNamesMask) {
+ int i;
+ CARD32 *old;
+ if ( stuff->nTypes<1 ) {
+ client->errorValue = _XkbErrCode2(0x02,stuff->nTypes);
+ return BadValue;
+ }
+ if ((unsigned)(stuff->firstType+stuff->nTypes-1)>=xkb->map->num_types) {
+ client->errorValue = _XkbErrCode4(0x03,stuff->firstType,
+ stuff->nTypes,
+ xkb->map->num_types);
+ return BadValue;
+ }
+ if (((unsigned)stuff->firstType)<=XkbLastRequiredType) {
+ client->errorValue = _XkbErrCode2(0x04,stuff->firstType);
+ return BadAccess;
+ }
+ old= tmp;
+ tmp= _XkbCheckAtoms(tmp,stuff->nTypes,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue= bad;
+ return BadAtom;
+ }
+ for (i=0;i<stuff->nTypes;i++,old++) {
+ if (!_XkbCheckTypeName((Atom)*old,stuff->firstType+i))
+ client->errorValue= _XkbErrCode2(0x05,i);
+ }
+ }
+ if (stuff->which&XkbKTLevelNamesMask) {
+ unsigned i;
+ XkbKeyTypePtr type;
+ CARD8 * width;
+ if ( stuff->nKTLevels<1 ) {
+ client->errorValue = _XkbErrCode2(0x05,stuff->nKTLevels);
+ return BadValue;
+ }
+ if ((unsigned)(stuff->firstKTLevel+stuff->nKTLevels-1)>=
+ xkb->map->num_types) {
+ client->errorValue = _XkbErrCode4(0x06,stuff->firstKTLevel,
+ stuff->nKTLevels,xkb->map->num_types);
+ return BadValue;
+ }
+ width = (CARD8 *)tmp;
+ tmp= (CARD32 *)(((char *)tmp)+XkbPaddedSize(stuff->nKTLevels));
+ type = &xkb->map->types[stuff->firstKTLevel];
+ for (i=0;i<stuff->nKTLevels;i++,type++) {
+ if (width[i]==0)
+ continue;
+ else if (width[i]!=type->num_levels) {
+ client->errorValue= _XkbErrCode4(0x07,i+stuff->firstKTLevel,
+ type->num_levels,width[i]);
+ return BadMatch;
+ }
+ tmp= _XkbCheckAtoms(tmp,width[i],client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue= bad;
+ return BadAtom;
+ }
+ }
+ }
+ if (stuff->which&XkbIndicatorNamesMask) {
+ if (stuff->indicators==0) {
+ client->errorValue= 0x08;
+ return BadMatch;
+ }
+ tmp= _XkbCheckMaskedAtoms(tmp,XkbNumIndicators,stuff->indicators,
+ client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue= bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbVirtualModNamesMask) {
+ if (stuff->virtualMods==0) {
+ client->errorValue= 0x09;
+ return BadMatch;
+ }
+ tmp= _XkbCheckMaskedAtoms(tmp,XkbNumVirtualMods,
+ (CARD32)stuff->virtualMods,
+ client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbGroupNamesMask) {
+ if (stuff->groupNames==0) {
+ client->errorValue= 0x0a;
+ return BadMatch;
+ }
+ tmp= _XkbCheckMaskedAtoms(tmp,XkbNumKbdGroups,
+ (CARD32)stuff->groupNames,
+ client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbKeyNamesMask) {
+ if (stuff->firstKey<(unsigned)xkb->min_key_code) {
+ client->errorValue= _XkbErrCode3(0x0b,xkb->min_key_code,
+ stuff->firstKey);
+ return BadValue;
+ }
+ if (((unsigned)(stuff->firstKey+stuff->nKeys-1)>xkb->max_key_code)||
+ (stuff->nKeys<1)) {
+ client->errorValue= _XkbErrCode4(0x0c,xkb->max_key_code,
+ stuff->firstKey,stuff->nKeys);
+ return BadValue;
+ }
+ tmp+= stuff->nKeys;
+ }
+ if ((stuff->which&XkbKeyAliasesMask)&&(stuff->nKeyAliases>0)) {
+ tmp+= stuff->nKeyAliases*2;
+ }
+ if (stuff->which&XkbRGNamesMask) {
+ if ( stuff->nRadioGroups<1 ) {
+ client->errorValue= _XkbErrCode2(0x0d,stuff->nRadioGroups);
+ return BadValue;
+ }
+ tmp= _XkbCheckAtoms(tmp,stuff->nRadioGroups,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue= bad;
+ return BadAtom;
+ }
+ }
+ if ((tmp-((CARD32 *)stuff))!=stuff->length) {
+ client->errorValue = stuff->length;
+ return BadLength;
+ }
+
+
+
+ return Success;
+}
+
+static int
+_XkbSetNames(ClientPtr client, DeviceIntPtr dev, xkbSetNamesReq *stuff)
+{
+ XkbDescRec *xkb;
+ XkbNamesRec *names;
+ CARD32 *tmp;
+ xkbNamesNotify nn;
+
+ tmp = (CARD32 *)&stuff[1];
+ xkb = dev->key->xkbInfo->desc;
+ names = xkb->names;
+
+ if (XkbAllocNames(xkb,stuff->which,stuff->nRadioGroups,
+ stuff->nKeyAliases)!=Success) {
+ return BadAlloc;
+ }
+
+ bzero(&nn,sizeof(xkbNamesNotify));
+ nn.changed= stuff->which;
+ tmp = (CARD32 *)&stuff[1];
+ if (stuff->which&XkbKeycodesNameMask)
+ names->keycodes= *tmp++;
+ if (stuff->which&XkbGeometryNameMask)
+ names->geometry= *tmp++;
+ if (stuff->which&XkbSymbolsNameMask)
+ names->symbols= *tmp++;
+ if (stuff->which&XkbPhysSymbolsNameMask)
+ names->phys_symbols= *tmp++;
+ if (stuff->which&XkbTypesNameMask)
+ names->types= *tmp++;
+ if (stuff->which&XkbCompatNameMask)
+ names->compat= *tmp++;
+ if ((stuff->which&XkbKeyTypeNamesMask)&&(stuff->nTypes>0)) {
+ register unsigned i;
+ register XkbKeyTypePtr type;
+
+ type= &xkb->map->types[stuff->firstType];
+ for (i=0;i<stuff->nTypes;i++,type++) {
+ type->name= *tmp++;
+ }
+ nn.firstType= stuff->firstType;
+ nn.nTypes= stuff->nTypes;
+ }
+ if (stuff->which&XkbKTLevelNamesMask) {
+ register XkbKeyTypePtr type;
+ register unsigned i;
+ CARD8 *width;
+
+ width = (CARD8 *)tmp;
+ tmp= (CARD32 *)(((char *)tmp)+XkbPaddedSize(stuff->nKTLevels));
+ type= &xkb->map->types[stuff->firstKTLevel];
+ for (i=0;i<stuff->nKTLevels;i++,type++) {
+ if (width[i]>0) {
+ if (type->level_names) {
+ register unsigned n;
+ for (n=0;n<width[i];n++) {
+ type->level_names[n]= tmp[n];
+ }
+ }
+ tmp+= width[i];
+ }
+ }
+ nn.firstLevelName= 0;
+ nn.nLevelNames= stuff->nTypes;
+ }
+ if (stuff->which&XkbIndicatorNamesMask) {
+ tmp= _XkbCopyMaskedAtoms(tmp,names->indicators,XkbNumIndicators,
+ stuff->indicators);
+ nn.changedIndicators= stuff->indicators;
+ }
+ if (stuff->which&XkbVirtualModNamesMask) {
+ tmp= _XkbCopyMaskedAtoms(tmp,names->vmods,XkbNumVirtualMods,
+ stuff->virtualMods);
+ nn.changedVirtualMods= stuff->virtualMods;
+ }
+ if (stuff->which&XkbGroupNamesMask) {
+ tmp= _XkbCopyMaskedAtoms(tmp,names->groups,XkbNumKbdGroups,
+ stuff->groupNames);
+ nn.changedVirtualMods= stuff->groupNames;
+ }
+ if (stuff->which&XkbKeyNamesMask) {
+ memcpy((char*)&names->keys[stuff->firstKey],(char *)tmp,
+ stuff->nKeys*XkbKeyNameLength);
+ tmp+= stuff->nKeys;
+ nn.firstKey= stuff->firstKey;
+ nn.nKeys= stuff->nKeys;
+ }
+ if (stuff->which&XkbKeyAliasesMask) {
+ if (stuff->nKeyAliases>0) {
+ register int na= stuff->nKeyAliases;
+ if (XkbAllocNames(xkb,XkbKeyAliasesMask,0,na)!=Success)
+ return BadAlloc;
+ memcpy((char *)names->key_aliases,(char *)tmp,
+ stuff->nKeyAliases*sizeof(XkbKeyAliasRec));
+ tmp+= stuff->nKeyAliases*2;
+ }
+ else if (names->key_aliases!=NULL) {
+ xfree(names->key_aliases);
+ names->key_aliases= NULL;
+ names->num_key_aliases= 0;
+ }
+ nn.nAliases= names->num_key_aliases;
+ }
+ if (stuff->which&XkbRGNamesMask) {
+ if (stuff->nRadioGroups>0) {
+ register unsigned i,nrg;
+ nrg= stuff->nRadioGroups;
+ if (XkbAllocNames(xkb,XkbRGNamesMask,nrg,0)!=Success)
+ return BadAlloc;
+
+ for (i=0;i<stuff->nRadioGroups;i++) {
+ names->radio_groups[i]= tmp[i];
+ }
+ tmp+= stuff->nRadioGroups;
+ }
+ else if (names->radio_groups) {
+ xfree(names->radio_groups);
+ names->radio_groups= NULL;
+ names->num_rg= 0;
+ }
+ nn.nRadioGroups= names->num_rg;
+ }
+ if (nn.changed) {
+ Bool needExtEvent;
+ needExtEvent= (nn.changed&XkbIndicatorNamesMask)!=0;
+ XkbSendNamesNotify(dev,&nn);
+ if (needExtEvent) {
+ XkbSrvLedInfoPtr sli;
+ xkbExtensionDeviceNotify edev;
+ register int i;
+ register unsigned bit;
+
+ sli= XkbFindSrvLedInfo(dev,XkbDfltXIClass,XkbDfltXIId,
+ XkbXI_IndicatorsMask);
+ sli->namesPresent= 0;
+ for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (names->indicators[i]!=None)
+ sli->namesPresent|= bit;
+ }
+ bzero(&edev,sizeof(xkbExtensionDeviceNotify));
+ edev.reason= XkbXI_IndicatorNamesMask;
+ edev.ledClass= KbdFeedbackClass;
+ edev.ledID= dev->kbdfeed->ctrl.id;
+ edev.ledsDefined= sli->namesPresent|sli->mapsPresent;
+ edev.ledState= sli->effectiveState;
+ edev.firstBtn= 0;
+ edev.nBtns= 0;
+ edev.supported= XkbXI_AllFeaturesMask;
+ edev.unsupported= 0;
+ XkbSendExtensionDeviceNotify(dev,client,&edev);
+ }
+ }
+ return Success;
+}
+
+int
+ProcXkbSetNames(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ CARD32 *tmp;
+ Atom bad;
+ int rc;
+
+ REQUEST(xkbSetNamesReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetNamesReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+ CHK_MASK_LEGAL(0x01,stuff->which,XkbAllNamesMask);
+
+ /* check device-independent stuff */
+ tmp = (CARD32 *)&stuff[1];
+
+ if (stuff->which&XkbKeycodesNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbGeometryNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbSymbolsNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbPhysSymbolsNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue= bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbTypesNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+ if (stuff->which&XkbCompatNameMask) {
+ tmp= _XkbCheckAtoms(tmp,1,client->swapped,&bad);
+ if (!tmp) {
+ client->errorValue = bad;
+ return BadAtom;
+ }
+ }
+
+ /* start of device-dependent tests */
+ rc = _XkbSetNamesCheck(client, dev, stuff, tmp);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ rc = _XkbSetNamesCheck(client, other, stuff, tmp);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ /* everything is okay -- update names */
+
+ rc = _XkbSetNames(client, dev, stuff);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ _XkbSetNames(client, other, stuff);
+ }
+ }
+ }
+
+ /* everything is okay -- update names */
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+#include "xkbgeom.h"
+
+#define XkbSizeCountedString(s) ((s)?((((2+strlen(s))+3)/4)*4):4)
+
+static char *
+XkbWriteCountedString(char *wire,char *str,Bool swap)
+{
+CARD16 len,*pLen;
+
+ len= (str?strlen(str):0);
+ pLen= (CARD16 *)wire;
+ *pLen= len;
+ if (swap) {
+ register int n;
+ swaps(pLen,n);
+ }
+ memcpy(&wire[2],str,len);
+ wire+= ((2+len+3)/4)*4;
+ return wire;
+}
+
+static int
+XkbSizeGeomProperties(XkbGeometryPtr geom)
+{
+register int i,size;
+XkbPropertyPtr prop;
+
+ for (size=i=0,prop=geom->properties;i<geom->num_properties;i++,prop++) {
+ size+= XkbSizeCountedString(prop->name);
+ size+= XkbSizeCountedString(prop->value);
+ }
+ return size;
+}
+
+static char *
+XkbWriteGeomProperties(char *wire,XkbGeometryPtr geom,Bool swap)
+{
+register int i;
+register XkbPropertyPtr prop;
+
+ for (i=0,prop=geom->properties;i<geom->num_properties;i++,prop++) {
+ wire= XkbWriteCountedString(wire,prop->name,swap);
+ wire= XkbWriteCountedString(wire,prop->value,swap);
+ }
+ return wire;
+}
+
+static int
+XkbSizeGeomKeyAliases(XkbGeometryPtr geom)
+{
+ return geom->num_key_aliases*(2*XkbKeyNameLength);
+}
+
+static char *
+XkbWriteGeomKeyAliases(char *wire,XkbGeometryPtr geom,Bool swap)
+{
+register int sz;
+
+ sz= geom->num_key_aliases*(XkbKeyNameLength*2);
+ if (sz>0) {
+ memcpy(wire,(char *)geom->key_aliases,sz);
+ wire+= sz;
+ }
+ return wire;
+}
+
+static int
+XkbSizeGeomColors(XkbGeometryPtr geom)
+{
+register int i,size;
+register XkbColorPtr color;
+
+ for (i=size=0,color=geom->colors;i<geom->num_colors;i++,color++) {
+ size+= XkbSizeCountedString(color->spec);
+ }
+ return size;
+}
+
+static char *
+XkbWriteGeomColors(char *wire,XkbGeometryPtr geom,Bool swap)
+{
+register int i;
+register XkbColorPtr color;
+
+ for (i=0,color=geom->colors;i<geom->num_colors;i++,color++) {
+ wire= XkbWriteCountedString(wire,color->spec,swap);
+ }
+ return wire;
+}
+
+static int
+XkbSizeGeomShapes(XkbGeometryPtr geom)
+{
+register int i,size;
+register XkbShapePtr shape;
+
+ for (i=size=0,shape=geom->shapes;i<geom->num_shapes;i++,shape++) {
+ register int n;
+ register XkbOutlinePtr ol;
+ size+= SIZEOF(xkbShapeWireDesc);
+ for (n=0,ol=shape->outlines;n<shape->num_outlines;n++,ol++) {
+ size+= SIZEOF(xkbOutlineWireDesc);
+ size+= ol->num_points*SIZEOF(xkbPointWireDesc);
+ }
+ }
+ return size;
+}
+
+static char *
+XkbWriteGeomShapes(char *wire,XkbGeometryPtr geom,Bool swap)
+{
+int i;
+XkbShapePtr shape;
+xkbShapeWireDesc * shapeWire;
+
+ for (i=0,shape=geom->shapes;i<geom->num_shapes;i++,shape++) {
+ register int o;
+ XkbOutlinePtr ol;
+ xkbOutlineWireDesc * olWire;
+ shapeWire= (xkbShapeWireDesc *)wire;
+ shapeWire->name= shape->name;
+ shapeWire->nOutlines= shape->num_outlines;
+ if (shape->primary!=NULL)
+ shapeWire->primaryNdx= XkbOutlineIndex(shape,shape->primary);
+ else shapeWire->primaryNdx= XkbNoShape;
+ if (shape->approx!=NULL)
+ shapeWire->approxNdx= XkbOutlineIndex(shape,shape->approx);
+ else shapeWire->approxNdx= XkbNoShape;
+ if (swap) {
+ register int n;
+ swapl(&shapeWire->name,n);
+ }
+ wire= (char *)&shapeWire[1];
+ for (o=0,ol=shape->outlines;o<shape->num_outlines;o++,ol++) {
+ register int p;
+ XkbPointPtr pt;
+ xkbPointWireDesc * ptWire;
+ olWire= (xkbOutlineWireDesc *)wire;
+ olWire->nPoints= ol->num_points;
+ olWire->cornerRadius= ol->corner_radius;
+ wire= (char *)&olWire[1];
+ ptWire= (xkbPointWireDesc *)wire;
+ for (p=0,pt=ol->points;p<ol->num_points;p++,pt++) {
+ ptWire[p].x= pt->x;
+ ptWire[p].y= pt->y;
+ if (swap) {
+ register int n;
+ swaps(&ptWire[p].x,n);
+ swaps(&ptWire[p].y,n);
+ }
+ }
+ wire= (char *)&ptWire[ol->num_points];
+ }
+ }
+ return wire;
+}
+
+static int
+XkbSizeGeomDoodads(int num_doodads,XkbDoodadPtr doodad)
+{
+register int i,size;
+
+ for (i=size=0;i<num_doodads;i++,doodad++) {
+ size+= SIZEOF(xkbAnyDoodadWireDesc);
+ if (doodad->any.type==XkbTextDoodad) {
+ size+= XkbSizeCountedString(doodad->text.text);
+ size+= XkbSizeCountedString(doodad->text.font);
+ }
+ else if (doodad->any.type==XkbLogoDoodad) {
+ size+= XkbSizeCountedString(doodad->logo.logo_name);
+ }
+ }
+ return size;
+}
+
+static char *
+XkbWriteGeomDoodads(char *wire,int num_doodads,XkbDoodadPtr doodad,Bool swap)
+{
+register int i;
+xkbDoodadWireDesc * doodadWire;
+
+ for (i=0;i<num_doodads;i++,doodad++) {
+ doodadWire= (xkbDoodadWireDesc *)wire;
+ wire= (char *)&doodadWire[1];
+ bzero(doodadWire,SIZEOF(xkbDoodadWireDesc));
+ doodadWire->any.name= doodad->any.name;
+ doodadWire->any.type= doodad->any.type;
+ doodadWire->any.priority= doodad->any.priority;
+ doodadWire->any.top= doodad->any.top;
+ doodadWire->any.left= doodad->any.left;
+ if (swap) {
+ register int n;
+ swapl(&doodadWire->any.name,n);
+ swaps(&doodadWire->any.top,n);
+ swaps(&doodadWire->any.left,n);
+ }
+ switch (doodad->any.type) {
+ case XkbOutlineDoodad:
+ case XkbSolidDoodad:
+ doodadWire->shape.angle= doodad->shape.angle;
+ doodadWire->shape.colorNdx= doodad->shape.color_ndx;
+ doodadWire->shape.shapeNdx= doodad->shape.shape_ndx;
+ if (swap) {
+ register int n;
+ swaps(&doodadWire->shape.angle,n);
+ }
+ break;
+ case XkbTextDoodad:
+ doodadWire->text.angle= doodad->text.angle;
+ doodadWire->text.width= doodad->text.width;
+ doodadWire->text.height= doodad->text.height;
+ doodadWire->text.colorNdx= doodad->text.color_ndx;
+ if (swap) {
+ register int n;
+ swaps(&doodadWire->text.angle,n);
+ swaps(&doodadWire->text.width,n);
+ swaps(&doodadWire->text.height,n);
+ }
+ wire= XkbWriteCountedString(wire,doodad->text.text,swap);
+ wire= XkbWriteCountedString(wire,doodad->text.font,swap);
+ break;
+ case XkbIndicatorDoodad:
+ doodadWire->indicator.shapeNdx= doodad->indicator.shape_ndx;
+ doodadWire->indicator.onColorNdx=doodad->indicator.on_color_ndx;
+ doodadWire->indicator.offColorNdx=
+ doodad->indicator.off_color_ndx;
+ break;
+ case XkbLogoDoodad:
+ doodadWire->logo.angle= doodad->logo.angle;
+ doodadWire->logo.colorNdx= doodad->logo.color_ndx;
+ doodadWire->logo.shapeNdx= doodad->logo.shape_ndx;
+ wire= XkbWriteCountedString(wire,doodad->logo.logo_name,swap);
+ break;
+ default:
+ ErrorF("[xkb] Unknown doodad type %d in XkbWriteGeomDoodads\n",
+ doodad->any.type);
+ ErrorF("[xkb] Ignored\n");
+ break;
+ }
+ }
+ return wire;
+}
+
+static char *
+XkbWriteGeomOverlay(char *wire,XkbOverlayPtr ol,Bool swap)
+{
+register int r;
+XkbOverlayRowPtr row;
+xkbOverlayWireDesc * olWire;
+
+ olWire= (xkbOverlayWireDesc *)wire;
+ olWire->name= ol->name;
+ olWire->nRows= ol->num_rows;
+ if (swap) {
+ register int n;
+ swapl(&olWire->name,n);
+ }
+ wire= (char *)&olWire[1];
+ for (r=0,row=ol->rows;r<ol->num_rows;r++,row++) {
+ unsigned int k;
+ XkbOverlayKeyPtr key;
+ xkbOverlayRowWireDesc * rowWire;
+ rowWire= (xkbOverlayRowWireDesc *)wire;
+ rowWire->rowUnder= row->row_under;
+ rowWire->nKeys= row->num_keys;
+ wire= (char *)&rowWire[1];
+ for (k=0,key=row->keys;k<row->num_keys;k++,key++) {
+ xkbOverlayKeyWireDesc * keyWire;
+ keyWire= (xkbOverlayKeyWireDesc *)wire;
+ memcpy(keyWire->over,key->over.name,XkbKeyNameLength);
+ memcpy(keyWire->under,key->under.name,XkbKeyNameLength);
+ wire= (char *)&keyWire[1];
+ }
+ }
+ return wire;
+}
+
+static int
+XkbSizeGeomSections(XkbGeometryPtr geom)
+{
+register int i,size;
+XkbSectionPtr section;
+
+ for (i=size=0,section=geom->sections;i<geom->num_sections;i++,section++) {
+ size+= SIZEOF(xkbSectionWireDesc);
+ if (section->rows) {
+ int r;
+ XkbRowPtr row;
+ for (r=0,row=section->rows;r<section->num_rows;row++,r++) {
+ size+= SIZEOF(xkbRowWireDesc);
+ size+= row->num_keys*SIZEOF(xkbKeyWireDesc);
+ }
+ }
+ if (section->doodads)
+ size+= XkbSizeGeomDoodads(section->num_doodads,section->doodads);
+ if (section->overlays) {
+ int o;
+ XkbOverlayPtr ol;
+ for (o=0,ol=section->overlays;o<section->num_overlays;o++,ol++) {
+ int r;
+ XkbOverlayRowPtr row;
+ size+= SIZEOF(xkbOverlayWireDesc);
+ for (r=0,row=ol->rows;r<ol->num_rows;r++,row++) {
+ size+= SIZEOF(xkbOverlayRowWireDesc);
+ size+= row->num_keys*SIZEOF(xkbOverlayKeyWireDesc);
+ }
+ }
+ }
+ }
+ return size;
+}
+
+static char *
+XkbWriteGeomSections(char *wire,XkbGeometryPtr geom,Bool swap)
+{
+register int i;
+XkbSectionPtr section;
+xkbSectionWireDesc * sectionWire;
+
+ for (i=0,section=geom->sections;i<geom->num_sections;i++,section++) {
+ sectionWire= (xkbSectionWireDesc *)wire;
+ sectionWire->name= section->name;
+ sectionWire->top= section->top;
+ sectionWire->left= section->left;
+ sectionWire->width= section->width;
+ sectionWire->height= section->height;
+ sectionWire->angle= section->angle;
+ sectionWire->priority= section->priority;
+ sectionWire->nRows= section->num_rows;
+ sectionWire->nDoodads= section->num_doodads;
+ sectionWire->nOverlays= section->num_overlays;
+ sectionWire->pad= 0;
+ if (swap) {
+ register int n;
+ swapl(§ionWire->name,n);
+ swaps(§ionWire->top,n);
+ swaps(§ionWire->left,n);
+ swaps(§ionWire->width,n);
+ swaps(§ionWire->height,n);
+ swaps(§ionWire->angle,n);
+ }
+ wire= (char *)§ionWire[1];
+ if (section->rows) {
+ int r;
+ XkbRowPtr row;
+ xkbRowWireDesc * rowWire;
+ for (r=0,row=section->rows;r<section->num_rows;r++,row++) {
+ rowWire= (xkbRowWireDesc *)wire;
+ rowWire->top= row->top;
+ rowWire->left= row->left;
+ rowWire->nKeys= row->num_keys;
+ rowWire->vertical= row->vertical;
+ rowWire->pad= 0;
+ if (swap) {
+ register int n;
+ swaps(&rowWire->top,n);
+ swaps(&rowWire->left,n);
+ }
+ wire= (char *)&rowWire[1];
+ if (row->keys) {
+ int k;
+ XkbKeyPtr key;
+ xkbKeyWireDesc * keyWire;
+ keyWire= (xkbKeyWireDesc *)wire;
+ for (k=0,key=row->keys;k<row->num_keys;k++,key++) {
+ memcpy(keyWire[k].name,key->name.name,XkbKeyNameLength);
+ keyWire[k].gap= key->gap;
+ keyWire[k].shapeNdx= key->shape_ndx;
+ keyWire[k].colorNdx= key->color_ndx;
+ if (swap) {
+ register int n;
+ swaps(&keyWire[k].gap,n);
+ }
+ }
+ wire= (char *)&keyWire[row->num_keys];
+ }
+ }
+ }
+ if (section->doodads) {
+ wire= XkbWriteGeomDoodads(wire,
+ section->num_doodads,section->doodads,
+ swap);
+ }
+ if (section->overlays) {
+ register int o;
+ for (o=0;o<section->num_overlays;o++) {
+ wire= XkbWriteGeomOverlay(wire,§ion->overlays[o],swap);
+ }
+ }
+ }
+ return wire;
+}
+
+static Status
+XkbComputeGetGeometryReplySize( XkbGeometryPtr geom,
+ xkbGetGeometryReply * rep,
+ Atom name)
+{
+int len;
+
+ if (geom!=NULL) {
+ len= XkbSizeCountedString(geom->label_font);
+ len+= XkbSizeGeomProperties(geom);
+ len+= XkbSizeGeomColors(geom);
+ len+= XkbSizeGeomShapes(geom);
+ len+= XkbSizeGeomSections(geom);
+ len+= XkbSizeGeomDoodads(geom->num_doodads,geom->doodads);
+ len+= XkbSizeGeomKeyAliases(geom);
+ rep->length= len/4;
+ rep->found= True;
+ rep->name= geom->name;
+ rep->widthMM= geom->width_mm;
+ rep->heightMM= geom->height_mm;
+ rep->nProperties= geom->num_properties;
+ rep->nColors= geom->num_colors;
+ rep->nShapes= geom->num_shapes;
+ rep->nSections= geom->num_sections;
+ rep->nDoodads= geom->num_doodads;
+ rep->nKeyAliases= geom->num_key_aliases;
+ rep->baseColorNdx= XkbGeomColorIndex(geom,geom->base_color);
+ rep->labelColorNdx= XkbGeomColorIndex(geom,geom->label_color);
+ }
+ else {
+ rep->length= 0;
+ rep->found= False;
+ rep->name= name;
+ rep->widthMM= rep->heightMM= 0;
+ rep->nProperties= rep->nColors= rep->nShapes= 0;
+ rep->nSections= rep->nDoodads= 0;
+ rep->nKeyAliases= 0;
+ rep->labelColorNdx= rep->baseColorNdx= 0;
+ }
+ return Success;
+}
+
+static int
+XkbSendGeometry( ClientPtr client,
+ XkbGeometryPtr geom,
+ xkbGetGeometryReply * rep,
+ Bool freeGeom)
+{
+ char *desc,*start;
+ int len;
+
+ if (geom!=NULL) {
+ len= rep->length*4;
+ start= desc= xalloc(len);
+ if (!start)
+ return BadAlloc;
+ desc= XkbWriteCountedString(desc,geom->label_font,client->swapped);
+ if ( rep->nProperties>0 )
+ desc = XkbWriteGeomProperties(desc,geom,client->swapped);
+ if ( rep->nColors>0 )
+ desc = XkbWriteGeomColors(desc,geom,client->swapped);
+ if ( rep->nShapes>0 )
+ desc = XkbWriteGeomShapes(desc,geom,client->swapped);
+ if ( rep->nSections>0 )
+ desc = XkbWriteGeomSections(desc,geom,client->swapped);
+ if ( rep->nDoodads>0 )
+ desc = XkbWriteGeomDoodads(desc,geom->num_doodads,geom->doodads,
+ client->swapped);
+ if ( rep->nKeyAliases>0 )
+ desc = XkbWriteGeomKeyAliases(desc,geom,client->swapped);
+ if ((desc-start)!=(len)) {
+ ErrorF("[xkb] BOGUS LENGTH in XkbSendGeometry, expected %d, got %ld\n",
+ len, (unsigned long)(desc-start));
+ }
+ }
+ else {
+ len= 0;
+ start= NULL;
+ }
+ if (client->swapped) {
+ register int n;
+ swaps(&rep->sequenceNumber,n);
+ swapl(&rep->length,n);
+ swapl(&rep->name,n);
+ swaps(&rep->widthMM,n);
+ swaps(&rep->heightMM,n);
+ swaps(&rep->nProperties,n);
+ swaps(&rep->nColors,n);
+ swaps(&rep->nShapes,n);
+ swaps(&rep->nSections,n);
+ swaps(&rep->nDoodads,n);
+ swaps(&rep->nKeyAliases,n);
+ }
+ WriteToClient(client, SIZEOF(xkbGetGeometryReply), (char *)rep);
+ if (len>0)
+ WriteToClient(client, len, start);
+ if (start!=NULL)
+ xfree((char *)start);
+ if (freeGeom)
+ XkbFreeGeometry(geom,XkbGeomAllMask,True);
+ return client->noClientException;
+}
+
+int
+ProcXkbGetGeometry(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ xkbGetGeometryReply rep;
+ XkbGeometryPtr geom;
+ Bool shouldFree;
+ Status status;
+
+ REQUEST(xkbGetGeometryReq);
+ REQUEST_SIZE_MATCH(xkbGetGeometryReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+ CHK_ATOM_OR_NONE(stuff->name);
+
+ geom= XkbLookupNamedGeometry(dev,stuff->name,&shouldFree);
+ rep.type= X_Reply;
+ rep.deviceID= dev->id;
+ rep.sequenceNumber= client->sequence;
+ rep.length= 0;
+ status= XkbComputeGetGeometryReplySize(geom,&rep,stuff->name);
+ if (status!=Success)
+ return status;
+ else return XkbSendGeometry(client,geom,&rep,shouldFree);
+}
+
+/***====================================================================***/
+
+static char *
+_GetCountedString(char **wire_inout,Bool swap)
+{
+char * wire,*str;
+CARD16 len,*plen;
+
+ wire= *wire_inout;
+ plen= (CARD16 *)wire;
+ if (swap) {
+ register int n;
+ swaps(plen,n);
+ }
+ len= *plen;
+ str= xalloc(len+1);
+ if (str) {
+ memcpy(str,&wire[2],len);
+ str[len]= '\0';
+ }
+ wire+= XkbPaddedSize(len+2);
+ *wire_inout= wire;
+ return str;
+}
+
+static Status
+_CheckSetDoodad( char ** wire_inout,
+ XkbGeometryPtr geom,
+ XkbSectionPtr section,
+ ClientPtr client)
+{
+char * wire;
+xkbDoodadWireDesc * dWire;
+XkbDoodadPtr doodad;
+
+ dWire= (xkbDoodadWireDesc *)(*wire_inout);
+ wire= (char *)&dWire[1];
+ if (client->swapped) {
+ register int n;
+ swapl(&dWire->any.name,n);
+ swaps(&dWire->any.top,n);
+ swaps(&dWire->any.left,n);
+ swaps(&dWire->any.angle,n);
+ }
+ CHK_ATOM_ONLY(dWire->any.name);
+ doodad= XkbAddGeomDoodad(geom,section,dWire->any.name);
+ if (!doodad)
+ return BadAlloc;
+ doodad->any.type= dWire->any.type;
+ doodad->any.priority= dWire->any.priority;
+ doodad->any.top= dWire->any.top;
+ doodad->any.left= dWire->any.left;
+ doodad->any.angle= dWire->any.angle;
+ switch (doodad->any.type) {
+ case XkbOutlineDoodad:
+ case XkbSolidDoodad:
+ if (dWire->shape.colorNdx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x40,geom->num_colors,
+ dWire->shape.colorNdx);
+ return BadMatch;
+ }
+ if (dWire->shape.shapeNdx>=geom->num_shapes) {
+ client->errorValue= _XkbErrCode3(0x41,geom->num_shapes,
+ dWire->shape.shapeNdx);
+ return BadMatch;
+ }
+ doodad->shape.color_ndx= dWire->shape.colorNdx;
+ doodad->shape.shape_ndx= dWire->shape.shapeNdx;
+ break;
+ case XkbTextDoodad:
+ if (dWire->text.colorNdx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x42,geom->num_colors,
+ dWire->text.colorNdx);
+ return BadMatch;
+ }
+ if (client->swapped) {
+ register int n;
+ swaps(&dWire->text.width,n);
+ swaps(&dWire->text.height,n);
+ }
+ doodad->text.width= dWire->text.width;
+ doodad->text.height= dWire->text.height;
+ doodad->text.color_ndx= dWire->text.colorNdx;
+ doodad->text.text= _GetCountedString(&wire,client->swapped);
+ doodad->text.font= _GetCountedString(&wire,client->swapped);
+ break;
+ case XkbIndicatorDoodad:
+ if (dWire->indicator.onColorNdx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x43,geom->num_colors,
+ dWire->indicator.onColorNdx);
+ return BadMatch;
+ }
+ if (dWire->indicator.offColorNdx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x44,geom->num_colors,
+ dWire->indicator.offColorNdx);
+ return BadMatch;
+ }
+ if (dWire->indicator.shapeNdx>=geom->num_shapes) {
+ client->errorValue= _XkbErrCode3(0x45,geom->num_shapes,
+ dWire->indicator.shapeNdx);
+ return BadMatch;
+ }
+ doodad->indicator.shape_ndx= dWire->indicator.shapeNdx;
+ doodad->indicator.on_color_ndx= dWire->indicator.onColorNdx;
+ doodad->indicator.off_color_ndx= dWire->indicator.offColorNdx;
+ break;
+ case XkbLogoDoodad:
+ if (dWire->logo.colorNdx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x46,geom->num_colors,
+ dWire->logo.colorNdx);
+ return BadMatch;
+ }
+ if (dWire->logo.shapeNdx>=geom->num_shapes) {
+ client->errorValue= _XkbErrCode3(0x47,geom->num_shapes,
+ dWire->logo.shapeNdx);
+ return BadMatch;
+ }
+ doodad->logo.color_ndx= dWire->logo.colorNdx;
+ doodad->logo.shape_ndx= dWire->logo.shapeNdx;
+ doodad->logo.logo_name= _GetCountedString(&wire,client->swapped);
+ break;
+ default:
+ client->errorValue= _XkbErrCode2(0x4F,dWire->any.type);
+ return BadValue;
+ }
+ *wire_inout= wire;
+ return Success;
+}
+
+static Status
+_CheckSetOverlay( char ** wire_inout,
+ XkbGeometryPtr geom,
+ XkbSectionPtr section,
+ ClientPtr client)
+{
+register int r;
+char * wire;
+XkbOverlayPtr ol;
+xkbOverlayWireDesc * olWire;
+xkbOverlayRowWireDesc * rWire;
+
+ wire= *wire_inout;
+ olWire= (xkbOverlayWireDesc *)wire;
+ if (client->swapped) {
+ register int n;
+ swapl(&olWire->name,n);
+ }
+ CHK_ATOM_ONLY(olWire->name);
+ ol= XkbAddGeomOverlay(section,olWire->name,olWire->nRows);
+ rWire= (xkbOverlayRowWireDesc *)&olWire[1];
+ for (r=0;r<olWire->nRows;r++) {
+ register int k;
+ xkbOverlayKeyWireDesc * kWire;
+ XkbOverlayRowPtr row;
+
+ if (rWire->rowUnder>section->num_rows) {
+ client->errorValue= _XkbErrCode4(0x20,r,section->num_rows,
+ rWire->rowUnder);
+ return BadMatch;
+ }
+ row= XkbAddGeomOverlayRow(ol,rWire->rowUnder,rWire->nKeys);
+ kWire= (xkbOverlayKeyWireDesc *)&rWire[1];
+ for (k=0;k<rWire->nKeys;k++,kWire++) {
+ if (XkbAddGeomOverlayKey(ol,row,
+ (char *)kWire->over,(char *)kWire->under)==NULL) {
+ client->errorValue= _XkbErrCode3(0x21,r,k);
+ return BadMatch;
+ }
+ }
+ rWire= (xkbOverlayRowWireDesc *)kWire;
+ }
+ olWire= (xkbOverlayWireDesc *)rWire;
+ wire= (char *)olWire;
+ *wire_inout= wire;
+ return Success;
+}
+
+static Status
+_CheckSetSections( XkbGeometryPtr geom,
+ xkbSetGeometryReq * req,
+ char ** wire_inout,
+ ClientPtr client)
+{
+Status status;
+register int s;
+char * wire;
+xkbSectionWireDesc * sWire;
+XkbSectionPtr section;
+
+ wire= *wire_inout;
+ if (req->nSections<1)
+ return Success;
+ sWire= (xkbSectionWireDesc *)wire;
+ for (s=0;s<req->nSections;s++) {
+ register int r;
+ xkbRowWireDesc * rWire;
+ if (client->swapped) {
+ register int n;
+ swapl(&sWire->name,n);
+ swaps(&sWire->top,n);
+ swaps(&sWire->left,n);
+ swaps(&sWire->width,n);
+ swaps(&sWire->height,n);
+ swaps(&sWire->angle,n);
+ }
+ CHK_ATOM_ONLY(sWire->name);
+ section= XkbAddGeomSection(geom,sWire->name,sWire->nRows,
+ sWire->nDoodads,sWire->nOverlays);
+ if (!section)
+ return BadAlloc;
+ section->priority= sWire->priority;
+ section->top= sWire->top;
+ section->left= sWire->left;
+ section->width= sWire->width;
+ section->height= sWire->height;
+ section->angle= sWire->angle;
+ rWire= (xkbRowWireDesc *)&sWire[1];
+ for (r=0;r<sWire->nRows;r++) {
+ register int k;
+ XkbRowPtr row;
+ xkbKeyWireDesc * kWire;
+ if (client->swapped) {
+ register int n;
+ swaps(&rWire->top,n);
+ swaps(&rWire->left,n);
+ }
+ row= XkbAddGeomRow(section,rWire->nKeys);
+ if (!row)
+ return BadAlloc;
+ row->top= rWire->top;
+ row->left= rWire->left;
+ row->vertical= rWire->vertical;
+ kWire= (xkbKeyWireDesc *)&rWire[1];
+ for (k=0;k<rWire->nKeys;k++) {
+ XkbKeyPtr key;
+ key= XkbAddGeomKey(row);
+ if (!key)
+ return BadAlloc;
+ memcpy(key->name.name,kWire[k].name,XkbKeyNameLength);
+ key->gap= kWire[k].gap;
+ key->shape_ndx= kWire[k].shapeNdx;
+ key->color_ndx= kWire[k].colorNdx;
+ if (key->shape_ndx>=geom->num_shapes) {
+ client->errorValue= _XkbErrCode3(0x10,key->shape_ndx,
+ geom->num_shapes);
+ return BadMatch;
+ }
+ if (key->color_ndx>=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x11,key->color_ndx,
+ geom->num_colors);
+ return BadMatch;
+ }
+ }
+ rWire= (xkbRowWireDesc *)&kWire[rWire->nKeys];
+ }
+ wire= (char *)rWire;
+ if (sWire->nDoodads>0) {
+ register int d;
+ for (d=0;d<sWire->nDoodads;d++) {
+ status=_CheckSetDoodad(&wire,geom,section,client);
+ if (status!=Success)
+ return status;
+ }
+ }
+ if (sWire->nOverlays>0) {
+ register int o;
+ for (o=0;o<sWire->nOverlays;o++) {
+ status= _CheckSetOverlay(&wire,geom,section,client);
+ if (status!=Success)
+ return status;
+ }
+ }
+ sWire= (xkbSectionWireDesc *)wire;
+ }
+ wire= (char *)sWire;
+ *wire_inout= wire;
+ return Success;
+}
+
+static Status
+_CheckSetShapes( XkbGeometryPtr geom,
+ xkbSetGeometryReq * req,
+ char ** wire_inout,
+ ClientPtr client)
+{
+register int i;
+char * wire;
+
+ wire= *wire_inout;
+ if (req->nShapes<1) {
+ client->errorValue= _XkbErrCode2(0x06,req->nShapes);
+ return BadValue;
+ }
+ else {
+ xkbShapeWireDesc * shapeWire;
+ XkbShapePtr shape;
+ register int o;
+ shapeWire= (xkbShapeWireDesc *)wire;
+ for (i=0;i<req->nShapes;i++) {
+ xkbOutlineWireDesc * olWire;
+ XkbOutlinePtr ol;
+ shape= XkbAddGeomShape(geom,shapeWire->name,shapeWire->nOutlines);
+ if (!shape)
+ return BadAlloc;
+ olWire= (xkbOutlineWireDesc *)(&shapeWire[1]);
+ for (o=0;o<shapeWire->nOutlines;o++) {
+ register int p;
+ XkbPointPtr pt;
+ xkbPointWireDesc * ptWire;
+
+ ol= XkbAddGeomOutline(shape,olWire->nPoints);
+ if (!ol)
+ return BadAlloc;
+ ol->corner_radius= olWire->cornerRadius;
+ ptWire= (xkbPointWireDesc *)&olWire[1];
+ for (p=0,pt=ol->points;p<olWire->nPoints;p++,pt++) {
+ pt->x= ptWire[p].x;
+ pt->y= ptWire[p].y;
+ if (client->swapped) {
+ register int n;
+ swaps(&pt->x,n);
+ swaps(&pt->y,n);
+ }
+ }
+ ol->num_points= olWire->nPoints;
+ olWire= (xkbOutlineWireDesc *)(&ptWire[olWire->nPoints]);
+ }
+ if (shapeWire->primaryNdx!=XkbNoShape)
+ shape->primary= &shape->outlines[shapeWire->primaryNdx];
+ if (shapeWire->approxNdx!=XkbNoShape)
+ shape->approx= &shape->outlines[shapeWire->approxNdx];
+ shapeWire= (xkbShapeWireDesc *)olWire;
+ }
+ wire= (char *)shapeWire;
+ }
+ if (geom->num_shapes!=req->nShapes) {
+ client->errorValue= _XkbErrCode3(0x07,geom->num_shapes,req->nShapes);
+ return BadMatch;
+ }
+
+ *wire_inout= wire;
+ return Success;
+}
+
+static Status
+_CheckSetGeom( XkbGeometryPtr geom,
+ xkbSetGeometryReq * req,
+ ClientPtr client)
+{
+register int i;
+Status status;
+char * wire;
+
+ wire= (char *)&req[1];
+ geom->label_font= _GetCountedString(&wire,client->swapped);
+
+ for (i=0;i<req->nProperties;i++) {
+ char *name,*val;
+ name= _GetCountedString(&wire,client->swapped);
+ if (!name)
+ return BadAlloc;
+ val= _GetCountedString(&wire,client->swapped);
+ if (!val) {
+ xfree(name);
+ return BadAlloc;
+ }
+ if (XkbAddGeomProperty(geom,name,val)==NULL) {
+ xfree(name);
+ xfree(val);
+ return BadAlloc;
+ }
+ xfree(name);
+ xfree(val);
+ }
+
+ if (req->nColors<2) {
+ client->errorValue= _XkbErrCode3(0x01,2,req->nColors);
+ return BadValue;
+ }
+ if (req->baseColorNdx>req->nColors) {
+ client->errorValue=_XkbErrCode3(0x03,req->nColors,req->baseColorNdx);
+ return BadMatch;
+ }
+ if (req->labelColorNdx>req->nColors) {
+ client->errorValue= _XkbErrCode3(0x03,req->nColors,req->labelColorNdx);
+ return BadMatch;
+ }
+ if (req->labelColorNdx==req->baseColorNdx) {
+ client->errorValue= _XkbErrCode3(0x04,req->baseColorNdx,
+ req->labelColorNdx);
+ return BadMatch;
+ }
+
+ for (i=0;i<req->nColors;i++) {
+ char *name;
+ name= _GetCountedString(&wire,client->swapped);
+ if (!name)
+ return BadAlloc;
+ if (!XkbAddGeomColor(geom,name,geom->num_colors)) {
+ xfree(name);
+ return BadAlloc;
+ }
+ xfree(name);
+ }
+ if (req->nColors!=geom->num_colors) {
+ client->errorValue= _XkbErrCode3(0x05,req->nColors,geom->num_colors);
+ return BadMatch;
+ }
+ geom->label_color= &geom->colors[req->labelColorNdx];
+ geom->base_color= &geom->colors[req->baseColorNdx];
+
+ if ((status=_CheckSetShapes(geom,req,&wire,client))!=Success)
+ return status;
+
+ if ((status=_CheckSetSections(geom,req,&wire,client))!=Success)
+ return status;
+
+ for (i=0;i<req->nDoodads;i++) {
+ status=_CheckSetDoodad(&wire,geom,NULL,client);
+ if (status!=Success)
+ return status;
+ }
+
+ for (i=0;i<req->nKeyAliases;i++) {
+ if (XkbAddGeomKeyAlias(geom,&wire[XkbKeyNameLength],wire)==NULL)
+ return BadAlloc;
+ wire+= 2*XkbKeyNameLength;
+ }
+ return Success;
+}
+
+static int
+_XkbSetGeometry(ClientPtr client, DeviceIntPtr dev, xkbSetGeometryReq *stuff)
+{
+ XkbDescPtr xkb;
+ Bool new_name;
+ xkbNewKeyboardNotify nkn;
+ XkbGeometryPtr geom,old;
+ XkbGeometrySizesRec sizes;
+ Status status;
+
+ xkb= dev->key->xkbInfo->desc;
+ old= xkb->geom;
+ xkb->geom= NULL;
+
+ sizes.which= XkbGeomAllMask;
+ sizes.num_properties= stuff->nProperties;
+ sizes.num_colors= stuff->nColors;
+ sizes.num_shapes= stuff->nShapes;
+ sizes.num_sections= stuff->nSections;
+ sizes.num_doodads= stuff->nDoodads;
+ sizes.num_key_aliases= stuff->nKeyAliases;
+ if ((status= XkbAllocGeometry(xkb,&sizes))!=Success) {
+ xkb->geom= old;
+ return status;
+ }
+ geom= xkb->geom;
+ geom->name= stuff->name;
+ geom->width_mm= stuff->widthMM;
+ geom->height_mm= stuff->heightMM;
+ if ((status= _CheckSetGeom(geom,stuff,client))!=Success) {
+ XkbFreeGeometry(geom,XkbGeomAllMask,True);
+ xkb->geom= old;
+ return status;
+ }
+ new_name= (xkb->names->geometry!=geom->name);
+ xkb->names->geometry= geom->name;
+ if (old)
+ XkbFreeGeometry(old,XkbGeomAllMask,True);
+ if (new_name) {
+ xkbNamesNotify nn;
+ bzero(&nn,sizeof(xkbNamesNotify));
+ nn.changed= XkbGeometryNameMask;
+ XkbSendNamesNotify(dev,&nn);
+ }
+ nkn.deviceID= nkn.oldDeviceID= dev->id;
+ nkn.minKeyCode= nkn.oldMinKeyCode= xkb->min_key_code;
+ nkn.maxKeyCode= nkn.oldMaxKeyCode= xkb->max_key_code;
+ nkn.requestMajor= XkbReqCode;
+ nkn.requestMinor= X_kbSetGeometry;
+ nkn.changed= XkbNKN_GeometryMask;
+ XkbSendNewKeyboardNotify(dev,&nkn);
+ return Success;
+}
+
+int
+ProcXkbSetGeometry(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ int rc;
+
+ REQUEST(xkbSetGeometryReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetGeometryReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+ CHK_ATOM_OR_NONE(stuff->name);
+
+ rc = _XkbSetGeometry(client, dev, stuff);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if ((other != dev) && other->key && !IsMaster(other) && (other->u.master == dev))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ _XkbSetGeometry(client, other, stuff);
+ }
+ }
+ }
+
+ return Success;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbPerClientFlags(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ xkbPerClientFlagsReply rep;
+ XkbInterestPtr interest;
+ Mask access_mode = DixGetAttrAccess | DixSetAttrAccess;
+
+ REQUEST(xkbPerClientFlagsReq);
+ REQUEST_SIZE_MATCH(xkbPerClientFlagsReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, access_mode);
+ CHK_MASK_LEGAL(0x01,stuff->change,XkbPCF_AllFlagsMask);
+ CHK_MASK_MATCH(0x02,stuff->change,stuff->value);
+
+ interest = XkbFindClientResource((DevicePtr)dev,client);
+ memset(&rep, 0, sizeof(xkbPerClientFlagsReply));
+ rep.type= X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ if (stuff->change) {
+ client->xkbClientFlags&= ~stuff->change;
+ client->xkbClientFlags|= stuff->value;
+ }
+ if (stuff->change&XkbPCF_AutoResetControlsMask) {
+ Bool want;
+ want= stuff->value&XkbPCF_AutoResetControlsMask;
+ if (interest && !want) {
+ interest->autoCtrls= interest->autoCtrlValues= 0;
+ }
+ else if (want && (!interest)) {
+ XID id = FakeClientID(client->index);
+ AddResource(id,RT_XKBCLIENT,dev);
+ interest= XkbAddClientResource((DevicePtr)dev,client,id);
+ if (!interest)
+ return BadAlloc;
+ }
+ if (interest && want ) {
+ register unsigned affect;
+ affect= stuff->ctrlsToChange;
+
+ CHK_MASK_LEGAL(0x03,affect,XkbAllBooleanCtrlsMask);
+ CHK_MASK_MATCH(0x04,affect,stuff->autoCtrls);
+ CHK_MASK_MATCH(0x05,stuff->autoCtrls,stuff->autoCtrlValues);
+
+ interest->autoCtrls&= ~affect;
+ interest->autoCtrlValues&= ~affect;
+ interest->autoCtrls|= stuff->autoCtrls&affect;
+ interest->autoCtrlValues|= stuff->autoCtrlValues&affect;
+ }
+ }
+ rep.supported = XkbPCF_AllFlagsMask;
+ rep.value= client->xkbClientFlags&XkbPCF_AllFlagsMask;
+ if (interest) {
+ rep.autoCtrls= interest->autoCtrls;
+ rep.autoCtrlValues= interest->autoCtrlValues;
+ }
+ else {
+ rep.autoCtrls= rep.autoCtrlValues= 0;
+ }
+ if ( client->swapped ) {
+ register int n;
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.supported,n);
+ swapl(&rep.value,n);
+ swapl(&rep.autoCtrls,n);
+ swapl(&rep.autoCtrlValues,n);
+ }
+ WriteToClient(client,SIZEOF(xkbPerClientFlagsReply), (char *)&rep);
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+/* all latin-1 alphanumerics, plus parens, minus, underscore, slash */
+/* and wildcards */
+static unsigned char componentSpecLegal[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0xa7, 0xff, 0x87,
+ 0xfe, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x07,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0xff
+};
+
+/* same as above but accepts percent, plus and bar too */
+static unsigned char componentExprLegal[] = {
+ 0x00, 0x00, 0x00, 0x00, 0x20, 0xaf, 0xff, 0x87,
+ 0xfe, 0xff, 0xff, 0x87, 0xfe, 0xff, 0xff, 0x17,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0xff, 0x7f, 0xff, 0xff, 0xff, 0x7f, 0xff
+};
+
+static char *
+GetComponentSpec(unsigned char **pWire,Bool allowExpr,int *errRtrn)
+{
+int len;
+register int i;
+unsigned char *wire,*str,*tmp,*legal;
+
+ if (allowExpr) legal= &componentExprLegal[0];
+ else legal= &componentSpecLegal[0];
+
+ wire= *pWire;
+ len= (*(unsigned char *)wire++);
+ if (len>0) {
+ str= xcalloc(1, len+1);
+ if (str) {
+ tmp= str;
+ for (i=0;i<len;i++) {
+ if (legal[(*wire)/8]&(1<<((*wire)%8)))
+ *tmp++= *wire++;
+ else wire++;
+ }
+ if (tmp!=str)
+ *tmp++= '\0';
+ else {
+ xfree(str);
+ str= NULL;
+ }
+ }
+ else {
+ *errRtrn= BadAlloc;
+ }
+ }
+ else {
+ str= NULL;
+ }
+ *pWire= wire;
+ return (char *)str;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbListComponents(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ xkbListComponentsReply rep;
+ unsigned len;
+ int status;
+ unsigned char * str;
+ XkbSrvListInfoRec list;
+
+ REQUEST(xkbListComponentsReq);
+ REQUEST_AT_LEAST_SIZE(xkbListComponentsReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+
+ status= Success;
+ str= (unsigned char *)&stuff[1];
+ bzero(&list,sizeof(XkbSrvListInfoRec));
+ list.maxRtrn= stuff->maxNames;
+ list.pattern[_XkbListKeycodes]= GetComponentSpec(&str,False,&status);
+ list.pattern[_XkbListTypes]= GetComponentSpec(&str,False,&status);
+ list.pattern[_XkbListCompat]= GetComponentSpec(&str,False,&status);
+ list.pattern[_XkbListSymbols]= GetComponentSpec(&str,False,&status);
+ list.pattern[_XkbListGeometry]= GetComponentSpec(&str,False,&status);
+ if (status!=Success)
+ return status;
+ len= str-((unsigned char *)stuff);
+ if ((XkbPaddedSize(len)/4)!=stuff->length)
+ return BadLength;
+ if ((status=XkbDDXList(dev,&list,client))!=Success) {
+ if (list.pool) {
+ xfree(list.pool);
+ list.pool= NULL;
+ }
+ return status;
+ }
+ bzero(&rep,sizeof(xkbListComponentsReply));
+ rep.type= X_Reply;
+ rep.deviceID = dev->id;
+ rep.sequenceNumber = client->sequence;
+ rep.length = XkbPaddedSize(list.nPool)/4;
+ rep.nKeymaps = 0;
+ rep.nKeycodes = list.nFound[_XkbListKeycodes];
+ rep.nTypes = list.nFound[_XkbListTypes];
+ rep.nCompatMaps = list.nFound[_XkbListCompat];
+ rep.nSymbols = list.nFound[_XkbListSymbols];
+ rep.nGeometries = list.nFound[_XkbListGeometry];
+ rep.extra= 0;
+ if (list.nTotal>list.maxRtrn)
+ rep.extra = (list.nTotal-list.maxRtrn);
+ if (client->swapped) {
+ register int n;
+ swaps(&rep.sequenceNumber,n);
+ swapl(&rep.length,n);
+ swaps(&rep.nKeymaps,n);
+ swaps(&rep.nKeycodes,n);
+ swaps(&rep.nTypes,n);
+ swaps(&rep.nCompatMaps,n);
+ swaps(&rep.nSymbols,n);
+ swaps(&rep.nGeometries,n);
+ swaps(&rep.extra,n);
+ }
+ WriteToClient(client,SIZEOF(xkbListComponentsReply),(char *)&rep);
+ if (list.nPool && list.pool) {
+ WriteToClient(client,XkbPaddedSize(list.nPool), (char *)list.pool);
+ xfree(list.pool);
+ list.pool= NULL;
+ }
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbGetKbdByName(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ DeviceIntPtr tmpd;
+ xkbGetKbdByNameReply rep;
+ xkbGetMapReply mrep;
+ xkbGetCompatMapReply crep;
+ xkbGetIndicatorMapReply irep;
+ xkbGetNamesReply nrep;
+ xkbGetGeometryReply grep;
+ XkbComponentNamesRec names;
+ XkbDescPtr xkb, new;
+ unsigned char * str;
+ char mapFile[PATH_MAX];
+ unsigned len;
+ unsigned fwant,fneed,reported;
+ int status;
+ Bool geom_changed;
+ XkbSrvLedInfoPtr old_sli;
+ XkbSrvLedInfoPtr sli;
+ Mask access_mode = DixGetAttrAccess | DixManageAccess;
+
+ REQUEST(xkbGetKbdByNameReq);
+ REQUEST_AT_LEAST_SIZE(xkbGetKbdByNameReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ memset(&mrep,0,sizeof(mrep)); //MH
+
+ CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, access_mode);
+
+ xkb = dev->key->xkbInfo->desc;
+ status= Success;
+ str= (unsigned char *)&stuff[1];
+ if (GetComponentSpec(&str,True,&status)) /* keymap, unsupported */
+ return BadMatch;
+ names.keycodes= GetComponentSpec(&str,True,&status);
+ names.types= GetComponentSpec(&str,True,&status);
+ names.compat= GetComponentSpec(&str,True,&status);
+ names.symbols= GetComponentSpec(&str,True,&status);
+ names.geometry= GetComponentSpec(&str,True,&status);
+ if (status!=Success)
+ return status;
+ len= str-((unsigned char *)stuff);
+ if ((XkbPaddedSize(len)/4)!=stuff->length)
+ return BadLength;
+
+ CHK_MASK_LEGAL(0x01,stuff->want,XkbGBN_AllComponentsMask);
+ CHK_MASK_LEGAL(0x02,stuff->need,XkbGBN_AllComponentsMask);
+
+ if (stuff->load)
+ fwant= XkbGBN_AllComponentsMask;
+ else fwant= stuff->want|stuff->need;
+ if ((!names.compat)&&
+ (fwant&(XkbGBN_CompatMapMask|XkbGBN_IndicatorMapMask))) {
+ names.compat= _XkbDupString("%");
+ }
+ if ((!names.types)&&(fwant&(XkbGBN_TypesMask))) {
+ names.types= _XkbDupString("%");
+ }
+ if ((!names.symbols)&&(fwant&XkbGBN_SymbolsMask)) {
+ names.symbols= _XkbDupString("%");
+ }
+ geom_changed= ((names.geometry!=NULL)&&(strcmp(names.geometry,"%")!=0));
+ if ((!names.geometry)&&(fwant&XkbGBN_GeometryMask)) {
+ names.geometry= _XkbDupString("%");
+ geom_changed= False;
+ }
+
+ bzero(mapFile,PATH_MAX);
+ rep.type= X_Reply;
+ rep.deviceID = dev->id;
+ rep.sequenceNumber = client->sequence;
+ rep.length = 0;
+ rep.minKeyCode = xkb->min_key_code;
+ rep.maxKeyCode = xkb->max_key_code;
+ rep.loaded= False;
+ fwant= XkbConvertGetByNameComponents(True,stuff->want)|XkmVirtualModsMask;
+ fneed= XkbConvertGetByNameComponents(True,stuff->need);
+ rep.reported= XkbConvertGetByNameComponents(False,fwant|fneed);
+ if (stuff->load) {
+ fneed|= XkmKeymapRequired;
+ fwant|= XkmKeymapLegal;
+ }
+ if ((fwant|fneed)&XkmSymbolsMask) {
+ fneed|= XkmKeyNamesIndex|XkmTypesIndex;
+ fwant|= XkmIndicatorsIndex;
+ }
+
+ /* We pass dev in here so we can get the old names out if needed. */
+ rep.found = XkbDDXLoadKeymapByNames(dev,&names,fwant,fneed,&new,
+ mapFile,PATH_MAX);
+ rep.newKeyboard= False;
+ rep.pad1= rep.pad2= rep.pad3= rep.pad4= 0;
+
+ stuff->want|= stuff->need;
+ if (new==NULL)
+ rep.reported= 0;
+ else {
+ if (stuff->load)
+ rep.loaded= True;
+ if (stuff->load ||
+ ((rep.reported&XkbGBN_SymbolsMask) && (new->compat))) {
+ XkbChangesRec changes;
+ bzero(&changes,sizeof(changes));
+ XkbUpdateDescActions(new,
+ new->min_key_code,XkbNumKeys(new),
+ &changes);
+ }
+
+ if (new->map==NULL)
+ rep.reported&= ~(XkbGBN_SymbolsMask|XkbGBN_TypesMask);
+ else if (rep.reported&(XkbGBN_SymbolsMask|XkbGBN_TypesMask)) {
+ mrep.type= X_Reply;
+ mrep.deviceID = dev->id;
+ mrep.sequenceNumber= client->sequence;
+ mrep.length = ((SIZEOF(xkbGetMapReply)-SIZEOF(xGenericReply))>>2);
+ mrep.minKeyCode = new->min_key_code;
+ mrep.maxKeyCode = new->max_key_code;
+ mrep.present = 0;
+ mrep.totalSyms = mrep.totalActs =
+ mrep.totalKeyBehaviors= mrep.totalKeyExplicit=
+ mrep.totalModMapKeys= mrep.totalVModMapKeys= 0;
+ if (rep.reported&(XkbGBN_TypesMask|XkbGBN_ClientSymbolsMask)) {
+ mrep.present|= XkbKeyTypesMask;
+ mrep.firstType = 0;
+ mrep.nTypes = mrep.totalTypes= new->map->num_types;
+ }
+ else {
+ mrep.firstType = mrep.nTypes= 0;
+ mrep.totalTypes= 0;
+ }
+ if (rep.reported&XkbGBN_ClientSymbolsMask) {
+ mrep.present|= (XkbKeySymsMask|XkbModifierMapMask);
+ mrep.firstKeySym = mrep.firstModMapKey= new->min_key_code;
+ mrep.nKeySyms = mrep.nModMapKeys= XkbNumKeys(new);
+ }
+ else {
+ mrep.firstKeySym= mrep.firstModMapKey= 0;
+ mrep.nKeySyms= mrep.nModMapKeys= 0;
+ }
+ if (rep.reported&XkbGBN_ServerSymbolsMask) {
+ mrep.present|= XkbAllServerInfoMask;
+ mrep.virtualMods= ~0;
+ mrep.firstKeyAct = mrep.firstKeyBehavior =
+ mrep.firstKeyExplicit = new->min_key_code;
+ mrep.nKeyActs = mrep.nKeyBehaviors =
+ mrep.nKeyExplicit = XkbNumKeys(new);
+ mrep.firstVModMapKey= new->min_key_code;
+ mrep.nVModMapKeys= XkbNumKeys(new);
+ }
+ else {
+ mrep.virtualMods= 0;
+ mrep.firstKeyAct= mrep.firstKeyBehavior=
+ mrep.firstKeyExplicit = 0;
+ mrep.nKeyActs= mrep.nKeyBehaviors= mrep.nKeyExplicit= 0;
+ }
+ XkbComputeGetMapReplySize(new,&mrep);
+ rep.length+= SIZEOF(xGenericReply)/4+mrep.length;
+ }
+ if (new->compat==NULL)
+ rep.reported&= ~XkbGBN_CompatMapMask;
+ else if (rep.reported&XkbGBN_CompatMapMask) {
+ crep.type= X_Reply;
+ crep.deviceID= dev->id;
+ crep.sequenceNumber= client->sequence;
+ crep.length= 0;
+ crep.groups= XkbAllGroupsMask;
+ crep.firstSI= 0;
+ crep.nSI= crep.nTotalSI= new->compat->num_si;
+ XkbComputeGetCompatMapReplySize(new->compat,&crep);
+ rep.length+= SIZEOF(xGenericReply)/4+crep.length;
+ }
+ if (new->indicators==NULL)
+ rep.reported&= ~XkbGBN_IndicatorMapMask;
+ else if (rep.reported&XkbGBN_IndicatorMapMask) {
+ irep.type= X_Reply;
+ irep.deviceID= dev->id;
+ irep.sequenceNumber= client->sequence;
+ irep.length= 0;
+ irep.which= XkbAllIndicatorsMask;
+ XkbComputeGetIndicatorMapReplySize(new->indicators,&irep);
+ rep.length+= SIZEOF(xGenericReply)/4+irep.length;
+ }
+ if (new->names==NULL)
+ rep.reported&= ~(XkbGBN_OtherNamesMask|XkbGBN_KeyNamesMask);
+ else if (rep.reported&(XkbGBN_OtherNamesMask|XkbGBN_KeyNamesMask)) {
+ nrep.type= X_Reply;
+ nrep.deviceID= dev->id;
+ nrep.sequenceNumber= client->sequence;
+ nrep.length= 0;
+ nrep.minKeyCode= new->min_key_code;
+ nrep.maxKeyCode= new->max_key_code;
+ if (rep.reported&XkbGBN_OtherNamesMask) {
+ nrep.which= XkbAllNamesMask;
+ if (new->map!=NULL)
+ nrep.nTypes= new->map->num_types;
+ else nrep.nTypes= 0;
+ nrep.nKTLevels= 0;
+ nrep.groupNames= XkbAllGroupsMask;
+ nrep.virtualMods= XkbAllVirtualModsMask;
+ nrep.indicators= XkbAllIndicatorsMask;
+ nrep.nRadioGroups= new->names->num_rg;
+ }
+ else {
+ nrep.which= 0;
+ nrep.nTypes= 0;
+ nrep.nKTLevels= 0;
+ nrep.groupNames= 0;
+ nrep.virtualMods= 0;
+ nrep.indicators= 0;
+ nrep.nRadioGroups= 0;
+ }
+ if (rep.reported&XkbGBN_KeyNamesMask) {
+ nrep.which|= XkbKeyNamesMask;
+ nrep.firstKey= new->min_key_code;
+ nrep.nKeys= XkbNumKeys(new);
+ nrep.nKeyAliases= new->names->num_key_aliases;
+ if (nrep.nKeyAliases)
+ nrep.which|= XkbKeyAliasesMask;
+ }
+ else {
+ nrep.which&= ~(XkbKeyNamesMask|XkbKeyAliasesMask);
+ nrep.firstKey= nrep.nKeys= 0;
+ nrep.nKeyAliases= 0;
+ }
+ XkbComputeGetNamesReplySize(new,&nrep);
+ rep.length+= SIZEOF(xGenericReply)/4+nrep.length;
+ }
+ if (new->geom==NULL)
+ rep.reported&= ~XkbGBN_GeometryMask;
+ else if (rep.reported&XkbGBN_GeometryMask) {
+ grep.type= X_Reply;
+ grep.deviceID= dev->id;
+ grep.sequenceNumber= client->sequence;
+ grep.length= 0;
+ grep.found= True;
+ grep.pad= 0;
+ grep.widthMM= grep.heightMM= 0;
+ grep.nProperties= grep.nColors= grep.nShapes= 0;
+ grep.nSections= grep.nDoodads= 0;
+ grep.baseColorNdx= grep.labelColorNdx= 0;
+ XkbComputeGetGeometryReplySize(new->geom,&grep,None);
+ rep.length+= SIZEOF(xGenericReply)/4+grep.length;
+ }
+ }
+
+ reported= rep.reported;
+ if ( client->swapped ) {
+ register int n;
+ swaps(&rep.sequenceNumber,n);
+ swapl(&rep.length,n);
+ swaps(&rep.found,n);
+ swaps(&rep.reported,n);
+ }
+ WriteToClient(client,SIZEOF(xkbGetKbdByNameReply), (char *)&rep);
+ if (reported&(XkbGBN_SymbolsMask|XkbGBN_TypesMask))
+ XkbSendMap(client,new,&mrep);
+ if (reported&XkbGBN_CompatMapMask)
+ XkbSendCompatMap(client,new->compat,&crep);
+ if (reported&XkbGBN_IndicatorMapMask)
+ XkbSendIndicatorMap(client,new->indicators,&irep);
+ if (reported&(XkbGBN_KeyNamesMask|XkbGBN_OtherNamesMask))
+ XkbSendNames(client,new,&nrep);
+ if (reported&XkbGBN_GeometryMask)
+ XkbSendGeometry(client,new->geom,&grep,False);
+ if (rep.loaded) {
+ XkbDescPtr old_xkb;
+ xkbNewKeyboardNotify nkn;
+ int i,nG,nTG;
+ old_xkb= xkb;
+ xkb= new;
+ dev->key->xkbInfo->desc= xkb;
+ new= old_xkb; /* so it'll get freed automatically */
+
+ *xkb->ctrls= *old_xkb->ctrls;
+ for (nG=nTG=0,i=xkb->min_key_code;i<=xkb->max_key_code;i++) {
+ nG= XkbKeyNumGroups(xkb,i);
+ if (nG>=XkbNumKbdGroups) {
+ nTG= XkbNumKbdGroups;
+ break;
+ }
+ if (nG>nTG) {
+ nTG= nG;
+ }
+ }
+ xkb->ctrls->num_groups= nTG;
+
+ for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) {
+ if ((tmpd == dev) || (!IsMaster(tmpd) && tmpd->u.master == dev)) {
+ if (tmpd != dev)
+ XkbCopyDeviceKeymap(tmpd, dev);
+
+ if (tmpd->kbdfeed && tmpd->kbdfeed->xkb_sli) {
+ old_sli = tmpd->kbdfeed->xkb_sli;
+ tmpd->kbdfeed->xkb_sli = NULL;
+ sli = XkbAllocSrvLedInfo(tmpd, tmpd->kbdfeed, NULL, 0);
+ if (sli) {
+ sli->explicitState = old_sli->explicitState;
+ sli->effectiveState = old_sli->effectiveState;
+ }
+ tmpd->kbdfeed->xkb_sli = sli;
+ XkbFreeSrvLedInfo(old_sli);
+ }
+ }
+ }
+
+ nkn.deviceID= nkn.oldDeviceID= dev->id;
+ nkn.minKeyCode= new->min_key_code;
+ nkn.maxKeyCode= new->max_key_code;
+ nkn.oldMinKeyCode= xkb->min_key_code;
+ nkn.oldMaxKeyCode= xkb->max_key_code;
+ nkn.requestMajor= XkbReqCode;
+ nkn.requestMinor= X_kbGetKbdByName;
+ nkn.changed= XkbNKN_KeycodesMask;
+ if (geom_changed)
+ nkn.changed|= XkbNKN_GeometryMask;
+ XkbSendNewKeyboardNotify(dev,&nkn);
+
+ if (!IsMaster(dev) && dev->u.master)
+ {
+ DeviceIntPtr master = dev->u.master;
+ if (master->u.lastSlave == dev)
+ {
+ XkbCopyDeviceKeymap(dev->u.master, dev);
+ XkbSendNewKeyboardNotify(dev,&nkn);
+ }
+ }
+ }
+ if ((new!=NULL)&&(new!=xkb)) {
+ XkbFreeKeyboard(new,XkbAllComponentsMask,True);
+ new= NULL;
+ }
+ if (names.keycodes) { xfree(names.keycodes); names.keycodes= NULL; }
+ if (names.types) { xfree(names.types); names.types= NULL; }
+ if (names.compat) { xfree(names.compat); names.compat= NULL; }
+ if (names.symbols) { xfree(names.symbols); names.symbols= NULL; }
+ if (names.geometry) { xfree(names.geometry); names.geometry= NULL; }
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static int
+ComputeDeviceLedInfoSize( DeviceIntPtr dev,
+ unsigned int what,
+ XkbSrvLedInfoPtr sli)
+{
+int nNames,nMaps;
+register unsigned n,bit;
+
+ if (sli==NULL)
+ return 0;
+ nNames= nMaps= 0;
+ if ((what&XkbXI_IndicatorNamesMask)==0)
+ sli->namesPresent= 0;
+ if ((what&XkbXI_IndicatorMapsMask)==0)
+ sli->mapsPresent= 0;
+
+ for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) {
+ if (sli->names && sli->names[n]!=None) {
+ sli->namesPresent|= bit;
+ nNames++;
+ }
+ if (sli->maps && XkbIM_InUse(&sli->maps[n])) {
+ sli->mapsPresent|= bit;
+ nMaps++;
+ }
+ }
+ return (nNames*4)+(nMaps*SIZEOF(xkbIndicatorMapWireDesc));
+}
+
+static int
+CheckDeviceLedFBs( DeviceIntPtr dev,
+ int class,
+ int id,
+ xkbGetDeviceInfoReply * rep,
+ ClientPtr client)
+{
+int nFBs= 0;
+int length= 0;
+Bool classOk;
+
+ if (class==XkbDfltXIClass) {
+ if (dev->kbdfeed) class= KbdFeedbackClass;
+ else if (dev->leds) class= LedFeedbackClass;
+ else {
+ client->errorValue= _XkbErrCode2(XkbErr_BadClass,class);
+ return XkbKeyboardErrorCode;
+ }
+ }
+ classOk= False;
+ if ((dev->kbdfeed)&&((class==KbdFeedbackClass)||(class==XkbAllXIClasses))) {
+ KbdFeedbackPtr kf;
+ classOk= True;
+ for (kf= dev->kbdfeed;(kf);kf=kf->next) {
+ if ((id!=XkbAllXIIds)&&(id!=XkbDfltXIId)&&(id!=kf->ctrl.id))
+ continue;
+ nFBs++;
+ length+= SIZEOF(xkbDeviceLedsWireDesc);
+ if (!kf->xkb_sli)
+ kf->xkb_sli= XkbAllocSrvLedInfo(dev,kf,NULL,0);
+ length+= ComputeDeviceLedInfoSize(dev,rep->present,kf->xkb_sli);
+ if (id!=XkbAllXIIds)
+ break;
+ }
+ }
+ if ((dev->leds)&&((class==LedFeedbackClass)||(class==XkbAllXIClasses))) {
+ LedFeedbackPtr lf;
+ classOk= True;
+ for (lf= dev->leds;(lf);lf=lf->next) {
+ if ((id!=XkbAllXIIds)&&(id!=XkbDfltXIId)&&(id!=lf->ctrl.id))
+ continue;
+ nFBs++;
+ length+= SIZEOF(xkbDeviceLedsWireDesc);
+ if (!lf->xkb_sli)
+ lf->xkb_sli= XkbAllocSrvLedInfo(dev,NULL,lf,0);
+ length+= ComputeDeviceLedInfoSize(dev,rep->present,lf->xkb_sli);
+ if (id!=XkbAllXIIds)
+ break;
+ }
+ }
+ if (nFBs>0) {
+ rep->nDeviceLedFBs= nFBs;
+ rep->length+= (length/4);
+ return Success;
+ }
+ if (classOk) client->errorValue= _XkbErrCode2(XkbErr_BadId,id);
+ else client->errorValue= _XkbErrCode2(XkbErr_BadClass,class);
+ return XkbKeyboardErrorCode;
+}
+
+static int
+SendDeviceLedInfo( XkbSrvLedInfoPtr sli,
+ ClientPtr client)
+{
+xkbDeviceLedsWireDesc wire;
+int length;
+
+ length= 0;
+ wire.ledClass= sli->class;
+ wire.ledID= sli->id;
+ wire.namesPresent= sli->namesPresent;
+ wire.mapsPresent= sli->mapsPresent;
+ wire.physIndicators= sli->physIndicators;
+ wire.state= sli->effectiveState;
+ if (client->swapped) {
+ register int n;
+ swaps(&wire.ledClass,n);
+ swaps(&wire.ledID,n);
+ swapl(&wire.namesPresent,n);
+ swapl(&wire.mapsPresent,n);
+ swapl(&wire.physIndicators,n);
+ swapl(&wire.state,n);
+ }
+ WriteToClient(client,SIZEOF(xkbDeviceLedsWireDesc),(char *)&wire);
+ length+= SIZEOF(xkbDeviceLedsWireDesc);
+ if (sli->namesPresent|sli->mapsPresent) {
+ register unsigned i,bit;
+ if (sli->namesPresent) {
+ CARD32 awire;
+ for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ if (sli->namesPresent&bit) {
+ awire= (CARD32)sli->names[i];
+ if (client->swapped) {
+ register int n;
+ swapl(&awire,n);
+ }
+ WriteToClient(client,4,(char *)&awire);
+ length+= 4;
+ }
+ }
+ }
+ if (sli->mapsPresent) {
+ for (i=0,bit=1;i<XkbNumIndicators;i++,bit<<=1) {
+ xkbIndicatorMapWireDesc iwire;
+ if (sli->mapsPresent&bit) {
+ iwire.flags= sli->maps[i].flags;
+ iwire.whichGroups= sli->maps[i].which_groups;
+ iwire.groups= sli->maps[i].groups;
+ iwire.whichMods= sli->maps[i].which_mods;
+ iwire.mods= sli->maps[i].mods.mask;
+ iwire.realMods= sli->maps[i].mods.real_mods;
+ iwire.virtualMods= sli->maps[i].mods.vmods;
+ iwire.ctrls= sli->maps[i].ctrls;
+ if (client->swapped) {
+ register int n;
+ swaps(&iwire.virtualMods,n);
+ swapl(&iwire.ctrls,n);
+ }
+ WriteToClient(client,SIZEOF(xkbIndicatorMapWireDesc),
+ (char *)&iwire);
+ length+= SIZEOF(xkbIndicatorMapWireDesc);
+ }
+ }
+ }
+ }
+ return length;
+}
+
+static int
+SendDeviceLedFBs( DeviceIntPtr dev,
+ int class,
+ int id,
+ unsigned wantLength,
+ ClientPtr client)
+{
+int length= 0;
+
+ if (class==XkbDfltXIClass) {
+ if (dev->kbdfeed) class= KbdFeedbackClass;
+ else if (dev->leds) class= LedFeedbackClass;
+ }
+ if ((dev->kbdfeed)&&
+ ((class==KbdFeedbackClass)||(class==XkbAllXIClasses))) {
+ KbdFeedbackPtr kf;
+ for (kf= dev->kbdfeed;(kf);kf=kf->next) {
+ if ((id==XkbAllXIIds)||(id==XkbDfltXIId)||(id==kf->ctrl.id)) {
+ length+= SendDeviceLedInfo(kf->xkb_sli,client);
+ if (id!=XkbAllXIIds)
+ break;
+ }
+ }
+ }
+ if ((dev->leds)&&
+ ((class==LedFeedbackClass)||(class==XkbAllXIClasses))) {
+ LedFeedbackPtr lf;
+ for (lf= dev->leds;(lf);lf=lf->next) {
+ if ((id==XkbAllXIIds)||(id==XkbDfltXIId)||(id==lf->ctrl.id)) {
+ length+= SendDeviceLedInfo(lf->xkb_sli,client);
+ if (id!=XkbAllXIIds)
+ break;
+ }
+ }
+ }
+ if (length==wantLength)
+ return Success;
+ else return BadLength;
+}
+
+int
+ProcXkbGetDeviceInfo(ClientPtr client)
+{
+DeviceIntPtr dev;
+xkbGetDeviceInfoReply rep;
+int status,nDeviceLedFBs;
+unsigned length,nameLen;
+CARD16 ledClass,ledID;
+unsigned wanted;
+char * str;
+
+ REQUEST(xkbGetDeviceInfoReq);
+ REQUEST_SIZE_MATCH(xkbGetDeviceInfoReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ wanted= stuff->wanted;
+
+ CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
+ CHK_MASK_LEGAL(0x01,wanted,XkbXI_AllDeviceFeaturesMask);
+
+ if ((!dev->button)||((stuff->nBtns<1)&&(!stuff->allBtns)))
+ wanted&= ~XkbXI_ButtonActionsMask;
+ if ((!dev->kbdfeed)&&(!dev->leds))
+ wanted&= ~XkbXI_IndicatorsMask;
+
+ nameLen= XkbSizeCountedString(dev->name);
+ bzero((char *)&rep,SIZEOF(xkbGetDeviceInfoReply));
+ rep.type = X_Reply;
+ rep.deviceID= dev->id;
+ rep.sequenceNumber = client->sequence;
+ rep.length = nameLen/4;
+ rep.present = wanted;
+ rep.supported = XkbXI_AllDeviceFeaturesMask;
+ rep.unsupported = 0;
+ rep.firstBtnWanted = rep.nBtnsWanted = 0;
+ rep.firstBtnRtrn = rep.nBtnsRtrn = 0;
+ if (dev->button)
+ rep.totalBtns= dev->button->numButtons;
+ else rep.totalBtns= 0;
+ rep.devType= dev->xinput_type;
+ rep.hasOwnState= (dev->key && dev->key->xkbInfo);
+ rep.nDeviceLedFBs = 0;
+ if (dev->kbdfeed) rep.dfltKbdFB= dev->kbdfeed->ctrl.id;
+ else rep.dfltKbdFB= XkbXINone;
+ if (dev->leds) rep.dfltLedFB= dev->leds->ctrl.id;
+ else rep.dfltLedFB= XkbXINone;
+
+ ledClass= stuff->ledClass;
+ ledID= stuff->ledID;
+
+ rep.firstBtnWanted= rep.nBtnsWanted= 0;
+ rep.firstBtnRtrn= rep.nBtnsRtrn= 0;
+ if (wanted&XkbXI_ButtonActionsMask) {
+ if (stuff->allBtns) {
+ stuff->firstBtn= 0;
+ stuff->nBtns= dev->button->numButtons;
+ }
+
+ if ((stuff->firstBtn+stuff->nBtns)>dev->button->numButtons) {
+ client->errorValue = _XkbErrCode4(0x02,dev->button->numButtons,
+ stuff->firstBtn,
+ stuff->nBtns);
+ return BadValue;
+ }
+ else {
+ rep.firstBtnWanted= stuff->firstBtn;
+ rep.nBtnsWanted= stuff->nBtns;
+ if (dev->button->xkb_acts!=NULL) {
+ XkbAction *act;
+ register int i;
+
+ rep.firstBtnRtrn= stuff->firstBtn;
+ rep.nBtnsRtrn= stuff->nBtns;
+ act= &dev->button->xkb_acts[rep.firstBtnWanted];
+ for (i=0;i<rep.nBtnsRtrn;i++,act++) {
+ if (act->type!=XkbSA_NoAction)
+ break;
+ }
+ rep.firstBtnRtrn+= i;
+ rep.nBtnsRtrn-= i;
+ act= &dev->button->xkb_acts[rep.firstBtnRtrn+rep.nBtnsRtrn-1];
+ for (i=0;i<rep.nBtnsRtrn;i++,act--) {
+ if (act->type!=XkbSA_NoAction)
+ break;
+ }
+ rep.nBtnsRtrn-= i;
+ }
+ rep.length+= (rep.nBtnsRtrn*SIZEOF(xkbActionWireDesc))/4;
+ }
+ }
+
+ if (wanted&XkbXI_IndicatorsMask) {
+ status= CheckDeviceLedFBs(dev,ledClass,ledID,&rep,client);
+ if (status!=Success)
+ return status;
+ }
+ length= rep.length*4;
+ nDeviceLedFBs = rep.nDeviceLedFBs;
+ if (client->swapped) {
+ register int n;
+ swaps(&rep.sequenceNumber,n);
+ swapl(&rep.length,n);
+ swaps(&rep.present,n);
+ swaps(&rep.supported,n);
+ swaps(&rep.unsupported,n);
+ swaps(&rep.nDeviceLedFBs,n);
+ swapl(&rep.type,n);
+ }
+ WriteToClient(client,SIZEOF(xkbGetDeviceInfoReply), (char *)&rep);
+
+ str= xalloc(nameLen);
+ if (!str)
+ return BadAlloc;
+ XkbWriteCountedString(str,dev->name,client->swapped);
+ WriteToClient(client,nameLen,str);
+ xfree(str);
+ length-= nameLen;
+
+ if (rep.nBtnsRtrn>0) {
+ int sz;
+ xkbActionWireDesc * awire;
+ sz= rep.nBtnsRtrn*SIZEOF(xkbActionWireDesc);
+ awire= (xkbActionWireDesc *)&dev->button->xkb_acts[rep.firstBtnRtrn];
+ WriteToClient(client,sz,(char *)awire);
+ length-= sz;
+ }
+ if (nDeviceLedFBs>0) {
+ status= SendDeviceLedFBs(dev,ledClass,ledID,length,client);
+ if (status!=Success)
+ return status;
+ }
+ else if (length!=0) {
+ ErrorF("[xkb] Internal Error! BadLength in ProcXkbGetDeviceInfo\n");
+ ErrorF("[xkb] Wrote %d fewer bytes than expected\n",length);
+ return BadLength;
+ }
+ return client->noClientException;
+}
+
+static char *
+CheckSetDeviceIndicators( char * wire,
+ DeviceIntPtr dev,
+ int num,
+ int * status_rtrn,
+ ClientPtr client)
+{
+xkbDeviceLedsWireDesc * ledWire;
+int i;
+XkbSrvLedInfoPtr sli;
+
+ ledWire= (xkbDeviceLedsWireDesc *)wire;
+ for (i=0;i<num;i++) {
+ if (client->swapped) {
+ register int n;
+ swaps(&ledWire->ledClass,n);
+ swaps(&ledWire->ledID,n);
+ swapl(&ledWire->namesPresent,n);
+ swapl(&ledWire->mapsPresent,n);
+ swapl(&ledWire->physIndicators,n);
+ }
+
+ sli= XkbFindSrvLedInfo(dev,ledWire->ledClass,ledWire->ledID,
+ XkbXI_IndicatorsMask);
+ if (sli!=NULL) {
+ register int n;
+ register unsigned bit;
+ int nMaps,nNames;
+ CARD32 *atomWire;
+ xkbIndicatorMapWireDesc *mapWire;
+
+ nMaps= nNames= 0;
+ for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) {
+ if (ledWire->namesPresent&bit)
+ nNames++;
+ if (ledWire->mapsPresent&bit)
+ nMaps++;
+ }
+ atomWire= (CARD32 *)&ledWire[1];
+ if (nNames>0) {
+ for (n=0;n<nNames;n++) {
+ if (client->swapped) {
+ register int t;
+ swapl(atomWire,t);
+ }
+ CHK_ATOM_OR_NONE3(((Atom)(*atomWire)),client->errorValue,
+ *status_rtrn,NULL);
+ atomWire++;
+ }
+ }
+ mapWire= (xkbIndicatorMapWireDesc *)atomWire;
+ if (nMaps>0) {
+ for (n=0;n<nMaps;n++) {
+ if (client->swapped) {
+ register int t;
+ swaps(&mapWire->virtualMods,t);
+ swapl(&mapWire->ctrls,t);
+ }
+ CHK_MASK_LEGAL3(0x21,mapWire->whichGroups,
+ XkbIM_UseAnyGroup,
+ client->errorValue,
+ *status_rtrn,NULL);
+ CHK_MASK_LEGAL3(0x22,mapWire->whichMods,XkbIM_UseAnyMods,
+ client->errorValue,
+ *status_rtrn,NULL);
+ mapWire++;
+ }
+ }
+ ledWire= (xkbDeviceLedsWireDesc *)mapWire;
+ }
+ else {
+ /* SHOULD NEVER HAPPEN */
+ return (char *)ledWire;
+ }
+ }
+ return (char *)ledWire;
+}
+
+static char *
+SetDeviceIndicators( char * wire,
+ DeviceIntPtr dev,
+ unsigned changed,
+ int num,
+ int * status_rtrn,
+ ClientPtr client,
+ xkbExtensionDeviceNotify *ev)
+{
+xkbDeviceLedsWireDesc * ledWire;
+int i;
+XkbEventCauseRec cause;
+unsigned namec,mapc,statec;
+xkbExtensionDeviceNotify ed;
+XkbChangesRec changes;
+DeviceIntPtr kbd;
+
+ bzero((char *)&ed,sizeof(xkbExtensionDeviceNotify));
+ bzero((char *)&changes,sizeof(XkbChangesRec));
+ XkbSetCauseXkbReq(&cause,X_kbSetDeviceInfo,client);
+ ledWire= (xkbDeviceLedsWireDesc *)wire;
+ for (i=0;i<num;i++) {
+ register int n;
+ register unsigned bit;
+ CARD32 * atomWire;
+ xkbIndicatorMapWireDesc * mapWire;
+ XkbSrvLedInfoPtr sli;
+
+ namec= mapc= statec= 0;
+ sli= XkbFindSrvLedInfo(dev,ledWire->ledClass,ledWire->ledID,
+ XkbXI_IndicatorMapsMask);
+ if (!sli) {
+ /* SHOULD NEVER HAPPEN!! */
+ return (char *)ledWire;
+ }
+
+ atomWire= (CARD32 *)&ledWire[1];
+ if (changed&XkbXI_IndicatorNamesMask) {
+ namec= sli->namesPresent|ledWire->namesPresent;
+ bzero((char *)sli->names,XkbNumIndicators*sizeof(Atom));
+ }
+ if (ledWire->namesPresent) {
+ sli->namesPresent= ledWire->namesPresent;
+ bzero((char *)sli->names,XkbNumIndicators*sizeof(Atom));
+ for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) {
+ if (ledWire->namesPresent&bit) {
+ sli->names[n]= (Atom)*atomWire;
+ if (sli->names[n]==None)
+ ledWire->namesPresent&= ~bit;
+ atomWire++;
+ }
+ }
+ }
+ mapWire= (xkbIndicatorMapWireDesc *)atomWire;
+ if (changed&XkbXI_IndicatorMapsMask) {
+ mapc= sli->mapsPresent|ledWire->mapsPresent;
+ sli->mapsPresent= ledWire->mapsPresent;
+ bzero((char*)sli->maps,XkbNumIndicators*sizeof(XkbIndicatorMapRec));
+ }
+ if (ledWire->mapsPresent) {
+ for (n=0,bit=1;n<XkbNumIndicators;n++,bit<<=1) {
+ if (ledWire->mapsPresent&bit) {
+ sli->maps[n].flags= mapWire->flags;
+ sli->maps[n].which_groups= mapWire->whichGroups;
+ sli->maps[n].groups= mapWire->groups;
+ sli->maps[n].which_mods= mapWire->whichMods;
+ sli->maps[n].mods.mask= mapWire->mods;
+ sli->maps[n].mods.real_mods=mapWire->realMods;
+ sli->maps[n].mods.vmods= mapWire->virtualMods;
+ sli->maps[n].ctrls= mapWire->ctrls;
+ mapWire++;
+ }
+ }
+ }
+ if (changed&XkbXI_IndicatorStateMask) {
+ statec= sli->effectiveState^ledWire->state;
+ sli->explicitState&= ~statec;
+ sli->explicitState|= (ledWire->state&statec);
+ }
+ if (namec)
+ XkbApplyLedNameChanges(dev,sli,namec,&ed,&changes,&cause);
+ if (mapc)
+ XkbApplyLedMapChanges(dev,sli,mapc,&ed,&changes,&cause);
+ if (statec)
+ XkbApplyLedStateChanges(dev,sli,statec,&ed,&changes,&cause);
+
+ kbd= dev;
+ if ((sli->flags&XkbSLI_HasOwnState)==0)
+ kbd = inputInfo.keyboard;
+
+ XkbFlushLedEvents(dev,kbd,sli,&ed,&changes,&cause);
+ ledWire= (xkbDeviceLedsWireDesc *)mapWire;
+ }
+ return (char *)ledWire;
+}
+
+
+static int
+_XkbSetDeviceInfo(ClientPtr client, DeviceIntPtr dev,
+ xkbSetDeviceInfoReq *stuff)
+{
+ char *wire;
+
+ wire= (char *)&stuff[1];
+ if (stuff->change&XkbXI_ButtonActionsMask) {
+ if (!dev->button) {
+ client->errorValue = _XkbErrCode2(XkbErr_BadClass,ButtonClass);
+ return XkbKeyboardErrorCode;
+ }
+ if ((stuff->firstBtn+stuff->nBtns)>dev->button->numButtons) {
+ client->errorValue= _XkbErrCode4(0x02,stuff->firstBtn,stuff->nBtns,
+ dev->button->numButtons);
+ return BadMatch;
+ }
+ wire+= (stuff->nBtns*SIZEOF(xkbActionWireDesc));
+ }
+ if (stuff->change&XkbXI_IndicatorsMask) {
+ int status= Success;
+ wire= CheckSetDeviceIndicators(wire,dev,stuff->nDeviceLedFBs,
+ &status,client);
+ if (status!=Success)
+ return status;
+ }
+ if (((wire-((char *)stuff))/4)!=stuff->length)
+ return BadLength;
+
+ return Success;
+}
+
+static int
+_XkbSetDeviceInfoCheck(ClientPtr client, DeviceIntPtr dev,
+ xkbSetDeviceInfoReq *stuff)
+{
+ char *wire;
+ xkbExtensionDeviceNotify ed;
+
+ bzero((char *)&ed,SIZEOF(xkbExtensionDeviceNotify));
+ ed.deviceID= dev->id;
+ wire= (char *)&stuff[1];
+ if (stuff->change&XkbXI_ButtonActionsMask) {
+ int nBtns,sz,i;
+ XkbAction * acts;
+ DeviceIntPtr kbd;
+
+ nBtns= dev->button->numButtons;
+ acts= dev->button->xkb_acts;
+ if (acts==NULL) {
+ acts= _XkbTypedCalloc(nBtns,XkbAction);
+ if (!acts)
+ return BadAlloc;
+ dev->button->xkb_acts= acts;
+ }
+ sz= stuff->nBtns*SIZEOF(xkbActionWireDesc);
+ memcpy((char *)&acts[stuff->firstBtn],(char *)wire,sz);
+ wire+= sz;
+ ed.reason|= XkbXI_ButtonActionsMask;
+ ed.firstBtn= stuff->firstBtn;
+ ed.nBtns= stuff->nBtns;
+
+ if (dev->key) kbd= dev;
+ else kbd= inputInfo.keyboard;
+ acts= &dev->button->xkb_acts[stuff->firstBtn];
+ for (i=0;i<stuff->nBtns;i++,acts++) {
+ if (acts->type!=XkbSA_NoAction)
+ XkbSetActionKeyMods(kbd->key->xkbInfo->desc,acts,0);
+ }
+ }
+ if (stuff->change&XkbXI_IndicatorsMask) {
+ int status= Success;
+ wire= SetDeviceIndicators(wire,dev,stuff->change,
+ stuff->nDeviceLedFBs, &status,client,&ed);
+ if (status!=Success)
+ return status;
+ }
+ if ((stuff->change)&&(ed.reason))
+ XkbSendExtensionDeviceNotify(dev,client,&ed);
+ return Success;
+}
+
+int
+ProcXkbSetDeviceInfo(ClientPtr client)
+{
+ DeviceIntPtr dev;
+ int rc;
+
+ REQUEST(xkbSetDeviceInfoReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetDeviceInfoReq);
+
+ if (!(client->xkbClientFlags&_XkbClientInitialized))
+ return BadAccess;
+
+ CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
+ CHK_MASK_LEGAL(0x01,stuff->change,XkbXI_AllFeaturesMask);
+
+ rc = _XkbSetDeviceInfoCheck(client, dev, stuff);
+
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd || stuff->deviceSpec == XkbUseCorePtr)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if (((other != dev) && !IsMaster(other) && (other->u.master == dev)) &&
+ ((stuff->deviceSpec == XkbUseCoreKbd && other->key) ||
+ (stuff->deviceSpec == XkbUseCorePtr && other->button)))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ rc = _XkbSetDeviceInfoCheck(client, other, stuff);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ /* checks done, apply */
+ rc = _XkbSetDeviceInfo(client, dev, stuff);
+ if (rc != Success)
+ return rc;
+
+ if (stuff->deviceSpec == XkbUseCoreKbd || stuff->deviceSpec == XkbUseCorePtr)
+ {
+ DeviceIntPtr other;
+ for (other = inputInfo.devices; other; other = other->next)
+ {
+ if (((other != dev) && !IsMaster(other) && (other->u.master == dev)) &&
+ ((stuff->deviceSpec == XkbUseCoreKbd && other->key) ||
+ (stuff->deviceSpec == XkbUseCorePtr && other->button)))
+ {
+ rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixManageAccess);
+ if (rc == Success)
+ {
+ rc = _XkbSetDeviceInfo(client, other, stuff);
+ if (rc != Success)
+ return rc;
+ }
+ }
+ }
+ }
+
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+int
+ProcXkbSetDebuggingFlags(ClientPtr client)
+{
+CARD32 newFlags,newCtrls,extraLength;
+xkbSetDebuggingFlagsReply rep;
+int rc;
+
+ REQUEST(xkbSetDebuggingFlagsReq);
+ REQUEST_AT_LEAST_SIZE(xkbSetDebuggingFlagsReq);
+
+ rc = XaceHook(XACE_SERVER_ACCESS, client, DixDebugAccess);
+ if (rc != Success)
+ return rc;
+
+ newFlags= xkbDebugFlags&(~stuff->affectFlags);
+ newFlags|= (stuff->flags&stuff->affectFlags);
+ newCtrls= xkbDebugCtrls&(~stuff->affectCtrls);
+ newCtrls|= (stuff->ctrls&stuff->affectCtrls);
+ if (xkbDebugFlags || newFlags || stuff->msgLength) {
+ ErrorF("[xkb] XkbDebug: Setting debug flags to 0x%lx\n",(long)newFlags);
+ if (newCtrls!=xkbDebugCtrls)
+ ErrorF("[xkb] XkbDebug: Setting debug controls to 0x%lx\n",(long)newCtrls);
+ }
+ extraLength= (stuff->length<<2)-sz_xkbSetDebuggingFlagsReq;
+ if (stuff->msgLength>0) {
+ char *msg;
+ if (extraLength<XkbPaddedSize(stuff->msgLength)) {
+ ErrorF("[xkb] XkbDebug: msgLength= %d, length= %ld (should be %d)\n",
+ stuff->msgLength,(long)extraLength,
+ XkbPaddedSize(stuff->msgLength));
+ return BadLength;
+ }
+ msg= (char *)&stuff[1];
+ if (msg[stuff->msgLength-1]!='\0') {
+ ErrorF("[xkb] XkbDebug: message not null-terminated\n");
+ return BadValue;
+ }
+ ErrorF("[xkb] XkbDebug: %s\n",msg);
+ }
+ xkbDebugFlags = newFlags;
+ xkbDebugCtrls = newCtrls;
+
+ rep.type= X_Reply;
+ rep.length = 0;
+ rep.sequenceNumber = client->sequence;
+ rep.currentFlags = newFlags;
+ rep.currentCtrls = newCtrls;
+ rep.supportedFlags = ~0;
+ rep.supportedCtrls = ~0;
+ if ( client->swapped ) {
+ register int n;
+ swaps(&rep.sequenceNumber, n);
+ swapl(&rep.currentFlags, n);
+ swapl(&rep.currentCtrls, n);
+ swapl(&rep.supportedFlags, n);
+ swapl(&rep.supportedCtrls, n);
+ }
+ WriteToClient(client,SIZEOF(xkbSetDebuggingFlagsReply), (char *)&rep);
+ return client->noClientException;
+}
+
+/***====================================================================***/
+
+static int
+ProcXkbDispatch (ClientPtr client)
+{
+ REQUEST(xReq);
+ switch (stuff->data)
+ {
+ case X_kbUseExtension:
+ return ProcXkbUseExtension(client);
+ case X_kbSelectEvents:
+ return ProcXkbSelectEvents(client);
+ case X_kbBell:
+ return ProcXkbBell(client);
+ case X_kbGetState:
+ return ProcXkbGetState(client);
+ case X_kbLatchLockState:
+ return ProcXkbLatchLockState(client);
+ case X_kbGetControls:
+ return ProcXkbGetControls(client);
+ case X_kbSetControls:
+ return ProcXkbSetControls(client);
+ case X_kbGetMap:
+ return ProcXkbGetMap(client);
+ case X_kbSetMap:
+ return ProcXkbSetMap(client);
+ case X_kbGetCompatMap:
+ return ProcXkbGetCompatMap(client);
+ case X_kbSetCompatMap:
+ return ProcXkbSetCompatMap(client);
+ case X_kbGetIndicatorState:
+ return ProcXkbGetIndicatorState(client);
+ case X_kbGetIndicatorMap:
+ return ProcXkbGetIndicatorMap(client);
+ case X_kbSetIndicatorMap:
+ return ProcXkbSetIndicatorMap(client);
+ case X_kbGetNamedIndicator:
+ return ProcXkbGetNamedIndicator(client);
+ case X_kbSetNamedIndicator:
+ return ProcXkbSetNamedIndicator(client);
+ case X_kbGetNames:
+ return ProcXkbGetNames(client);
+ case X_kbSetNames:
+ return ProcXkbSetNames(client);
+ case X_kbGetGeometry:
+ return ProcXkbGetGeometry(client);
+ case X_kbSetGeometry:
+ return ProcXkbSetGeometry(client);
+ case X_kbPerClientFlags:
+ return ProcXkbPerClientFlags(client);
+ case X_kbListComponents:
+ return ProcXkbListComponents(client);
+ case X_kbGetKbdByName:
+ return ProcXkbGetKbdByName(client);
+ case X_kbGetDeviceInfo:
+ return ProcXkbGetDeviceInfo(client);
+ case X_kbSetDeviceInfo:
+ return ProcXkbSetDeviceInfo(client);
+ case X_kbSetDebuggingFlags:
+ return ProcXkbSetDebuggingFlags(client);
+ default:
+ return BadRequest;
+ }
+}
+
+static int
+XkbClientGone(pointer data,XID id)
+{
+ DevicePtr pXDev = (DevicePtr)data;
+
+ if (!XkbRemoveResourceClient(pXDev,id)) {
+ ErrorF("[xkb] Internal Error! bad RemoveResourceClient in XkbClientGone\n");
+ }
+ return 1;
+}
+
+void
+XkbExtensionInit(void)
+{
+ ExtensionEntry *extEntry;
+
+ if ((extEntry = AddExtension(XkbName, XkbNumberEvents, XkbNumberErrors,
+ ProcXkbDispatch, SProcXkbDispatch,
+ NULL, StandardMinorOpcode))) {
+ XkbReqCode = (unsigned char)extEntry->base;
+ XkbEventBase = (unsigned char)extEntry->eventBase;
+ XkbErrorBase = (unsigned char)extEntry->errorBase;
+ XkbKeyboardErrorCode = XkbErrorBase+XkbKeyboard;
+ RT_XKBCLIENT = CreateNewResourceType(XkbClientGone);
+ }
+ return;
+}
+
+
diff --git a/xorg-server/xkb/xkbActions.c b/xorg-server/xkb/xkbActions.c index b0ab427b6..49c1de21b 100644 --- a/xorg-server/xkb/xkbActions.c +++ b/xorg-server/xkb/xkbActions.c @@ -1,1319 +1,1319 @@ -/************************************************************ -Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc. - -Permission to use, copy, modify, and distribute this -software and its documentation for any purpose and without -fee is hereby granted, 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 Silicon Graphics not be -used in advertising or publicity pertaining to distribution -of the software without specific prior written permission. -Silicon Graphics makes no representation about the suitability -of this software for any purpose. It is provided "as is" -without any express or implied warranty. - -SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS -SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON -GRAPHICS 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_DIX_CONFIG_H -#include <dix-config.h> -#endif - -#include <stdio.h> -#include <math.h> -#include <X11/X.h> -#include <X11/Xproto.h> -#include <X11/keysym.h> -#include "misc.h" -#include "inputstr.h" -#include "exevents.h" -#include "eventstr.h" -#include <xkbsrv.h> -#include "xkb.h" -#include <ctype.h> -#define EXTENSION_EVENT_BASE 64 - -static int xkbDevicePrivateKeyIndex; -DevPrivateKey xkbDevicePrivateKey = &xkbDevicePrivateKeyIndex; - -void -xkbUnwrapProc(DeviceIntPtr device, DeviceHandleProc proc, - pointer data) -{ - xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(device); - ProcessInputProc backupproc; - if(xkbPrivPtr->unwrapProc) - xkbPrivPtr->unwrapProc = NULL; - - UNWRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr, backupproc); - proc(device,data); - COND_WRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr, - backupproc,xkbUnwrapProc); -} - - -void -XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc) -{ - xkbDeviceInfoPtr xkbPrivPtr; - - xkbPrivPtr = (xkbDeviceInfoPtr) xcalloc(1, sizeof(xkbDeviceInfoRec)); - if (!xkbPrivPtr) - return; - xkbPrivPtr->unwrapProc = NULL; - - dixSetPrivate(&device->devPrivates, xkbDevicePrivateKey, xkbPrivPtr); - WRAP_PROCESS_INPUT_PROC(device, xkbPrivPtr, proc, xkbUnwrapProc); -} - -/***====================================================================***/ - -static XkbAction -_FixUpAction(XkbDescPtr xkb,XkbAction *act) -{ -static XkbAction fake; - - if (XkbIsPtrAction(act)&&(!(xkb->ctrls->enabled_ctrls&XkbMouseKeysMask))) { - fake.type = XkbSA_NoAction; - return fake; - } - if (xkb->ctrls->enabled_ctrls&XkbStickyKeysMask) { - if (act->any.type==XkbSA_SetMods) { - fake.mods.type = XkbSA_LatchMods; - fake.mods.mask = act->mods.mask; - if (XkbAX_NeedOption(xkb->ctrls,XkbAX_LatchToLockMask)) - fake.mods.flags= XkbSA_ClearLocks|XkbSA_LatchToLock; - else fake.mods.flags= XkbSA_ClearLocks; - return fake; - } - if (act->any.type==XkbSA_SetGroup) { - fake.group.type = XkbSA_LatchGroup; - if (XkbAX_NeedOption(xkb->ctrls,XkbAX_LatchToLockMask)) - fake.group.flags= XkbSA_ClearLocks|XkbSA_LatchToLock; - else fake.group.flags= XkbSA_ClearLocks; - XkbSASetGroup(&fake.group,XkbSAGroup(&act->group)); - return fake; - } - } - return *act; -} - -static XkbAction -XkbGetKeyAction(XkbSrvInfoPtr xkbi,XkbStatePtr xkbState,CARD8 key) -{ -int effectiveGroup; -int col; -XkbDescPtr xkb; -XkbKeyTypePtr type; -XkbAction * pActs; -static XkbAction fake; - - xkb= xkbi->desc; - if (!XkbKeyHasActions(xkb,key) || !XkbKeycodeInRange(xkb,key)) { - fake.type = XkbSA_NoAction; - return fake; - } - pActs= XkbKeyActionsPtr(xkb,key); - col= 0; - - effectiveGroup = XkbGetEffectiveGroup(xkbi, xkbState, key); - if (effectiveGroup != XkbGroup1Index) - col += (effectiveGroup * XkbKeyGroupsWidth(xkb, key)); - - type= XkbKeyKeyType(xkb,key,effectiveGroup); - if (type->map!=NULL) { - register unsigned i,mods; - register XkbKTMapEntryPtr entry; - mods= xkbState->mods&type->mods.mask; - for (entry= type->map,i=0;i<type->map_count;i++,entry++) { - if ((entry->active)&&(entry->mods.mask==mods)) { - col+= entry->level; - break; - } - } - } - if (pActs[col].any.type==XkbSA_NoAction) - return pActs[col]; - fake= _FixUpAction(xkb,&pActs[col]); - return fake; -} - -static XkbAction -XkbGetButtonAction(DeviceIntPtr kbd,DeviceIntPtr dev,int button) -{ -XkbAction fake; - if ((dev->button)&&(dev->button->xkb_acts)) { - if (dev->button->xkb_acts[button-1].any.type!=XkbSA_NoAction) { - fake= _FixUpAction(kbd->key->xkbInfo->desc, - &dev->button->xkb_acts[button-1]); - return fake; - } - } - fake.any.type= XkbSA_NoAction; - return fake; -} - -/***====================================================================***/ - -#define SYNTHETIC_KEYCODE 1 -#define BTN_ACT_FLAG 0x100 - -static int -_XkbFilterSetState( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction *pAction) -{ - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = ((pAction->mods.mask&XkbSA_ClearLocks)!=0); - filter->priv = 0; - filter->filter = _XkbFilterSetState; - if (pAction->type==XkbSA_SetMods) { - filter->upAction = *pAction; - xkbi->setMods= pAction->mods.mask; - } - else { - xkbi->groupChange = XkbSAGroup(&pAction->group); - if (pAction->group.flags&XkbSA_GroupAbsolute) - xkbi->groupChange-= xkbi->state.base_group; - filter->upAction= *pAction; - XkbSASetGroup(&filter->upAction.group,xkbi->groupChange); - } - } - else if (filter->keycode==keycode) { - if (filter->upAction.type==XkbSA_SetMods) { - xkbi->clearMods = filter->upAction.mods.mask; - if (filter->upAction.mods.flags&XkbSA_ClearLocks) { - xkbi->state.locked_mods&= ~filter->upAction.mods.mask; - } - } - else { - if (filter->upAction.group.flags&XkbSA_ClearLocks) { - xkbi->state.locked_group = 0; - } - xkbi->groupChange = -XkbSAGroup(&filter->upAction.group); - } - filter->active = 0; - } - else { - filter->upAction.mods.flags&= ~XkbSA_ClearLocks; - filter->filterOthers = 0; - } - return 1; -} - -#define LATCH_KEY_DOWN 1 -#define LATCH_PENDING 2 -#define NO_LATCH 3 - -static int -_XkbFilterLatchState( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 1; - filter->priv = LATCH_KEY_DOWN; - filter->filter = _XkbFilterLatchState; - if (pAction->type==XkbSA_LatchMods) { - filter->upAction = *pAction; - xkbi->setMods = pAction->mods.mask; - } - else { - xkbi->groupChange = XkbSAGroup(&pAction->group); - if (pAction->group.flags&XkbSA_GroupAbsolute) - xkbi->groupChange-= xkbi->state.base_group; - filter->upAction= *pAction; - XkbSASetGroup(&filter->upAction.group,xkbi->groupChange); - } - } - else if ( pAction && (filter->priv==LATCH_PENDING) ) { - if (((1<<pAction->type)&XkbSA_BreakLatch)!=0) { - filter->active = 0; - if (filter->upAction.type==XkbSA_LatchMods) - xkbi->state.latched_mods&= ~filter->upAction.mods.mask; - else xkbi->state.latched_group-=XkbSAGroup(&filter->upAction.group); - } - else if ((pAction->type==filter->upAction.type)&& - (pAction->mods.flags==filter->upAction.mods.flags)&& - (pAction->mods.mask==filter->upAction.mods.mask)) { - if (filter->upAction.mods.flags&XkbSA_LatchToLock) { - XkbControlsPtr ctrls= xkbi->desc->ctrls; - if (filter->upAction.type==XkbSA_LatchMods) - pAction->mods.type= XkbSA_LockMods; - else pAction->group.type= XkbSA_LockGroup; - if (XkbAX_NeedFeedback(ctrls,XkbAX_StickyKeysFBMask)&& - (ctrls->enabled_ctrls&XkbStickyKeysMask)) { - XkbDDXAccessXBeep(xkbi->device,_BEEP_STICKY_LOCK, - XkbStickyKeysMask); - } - } - else { - if (filter->upAction.type==XkbSA_LatchMods) - pAction->mods.type= XkbSA_SetMods; - else pAction->group.type= XkbSA_SetGroup; - } - if (filter->upAction.type==XkbSA_LatchMods) - xkbi->state.latched_mods&= ~filter->upAction.mods.mask; - else xkbi->state.latched_group-=XkbSAGroup(&filter->upAction.group); - filter->active = 0; - } - } - else if (filter->keycode==keycode) { /* release */ - XkbControlsPtr ctrls= xkbi->desc->ctrls; - int needBeep; - int beepType= _BEEP_NONE; - - needBeep= ((ctrls->enabled_ctrls&XkbStickyKeysMask)&& - XkbAX_NeedFeedback(ctrls,XkbAX_StickyKeysFBMask)); - if (filter->upAction.type==XkbSA_LatchMods) { - xkbi->clearMods = filter->upAction.mods.mask; - if ((filter->upAction.mods.flags&XkbSA_ClearLocks)&& - (xkbi->clearMods&xkbi->state.locked_mods)==xkbi->clearMods) { - xkbi->state.locked_mods&= ~xkbi->clearMods; - filter->priv= NO_LATCH; - beepType= _BEEP_STICKY_UNLOCK; - } - } - else { - xkbi->groupChange = -XkbSAGroup(&filter->upAction.group); - if ((filter->upAction.group.flags&XkbSA_ClearLocks)&& - (xkbi->state.locked_group)) { - xkbi->state.locked_group = 0; - filter->priv = NO_LATCH; - beepType= _BEEP_STICKY_UNLOCK; - } - } - if (filter->priv==NO_LATCH) { - filter->active= 0; - } - else { - filter->priv= LATCH_PENDING; - if (filter->upAction.type==XkbSA_LatchMods) { - xkbi->state.latched_mods |= filter->upAction.mods.mask; - needBeep = xkbi->state.latched_mods ? needBeep : 0; - xkbi->state.latched_mods |= filter->upAction.mods.mask; - } - else { - xkbi->state.latched_group+= XkbSAGroup(&filter->upAction.group); - } - if (needBeep && (beepType==_BEEP_NONE)) - beepType= _BEEP_STICKY_LATCH; - } - if (needBeep && (beepType!=_BEEP_NONE)) - XkbDDXAccessXBeep(xkbi->device,beepType,XkbStickyKeysMask); - } - else if (filter->priv==LATCH_KEY_DOWN) { - filter->priv= NO_LATCH; - filter->filterOthers = 0; - } - return 1; -} - -static int -_XkbFilterLockState( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - if (pAction&&(pAction->type==XkbSA_LockGroup)) { - if (pAction->group.flags&XkbSA_GroupAbsolute) - xkbi->state.locked_group= XkbSAGroup(&pAction->group); - else xkbi->state.locked_group+= XkbSAGroup(&pAction->group); - return 1; - } - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv = 0; - filter->filter = _XkbFilterLockState; - filter->upAction = *pAction; - xkbi->state.locked_mods^= pAction->mods.mask; - xkbi->setMods = pAction->mods.mask; - } - else if (filter->keycode==keycode) { - filter->active = 0; - xkbi->clearMods = filter->upAction.mods.mask; - } - return 1; -} - -#define ISO_KEY_DOWN 0 -#define NO_ISO_LOCK 1 - -static int -_XkbFilterISOLock( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - - if (filter->keycode==0) { /* initial press */ - CARD8 flags= pAction->iso.flags; - - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 1; - filter->priv = ISO_KEY_DOWN; - filter->upAction = *pAction; - filter->filter = _XkbFilterISOLock; - if (flags&XkbSA_ISODfltIsGroup) { - xkbi->groupChange = XkbSAGroup(&pAction->iso); - xkbi->setMods = 0; - } - else { - xkbi->setMods = pAction->iso.mask; - xkbi->groupChange = 0; - } - if ((!(flags&XkbSA_ISONoAffectMods))&&(xkbi->state.base_mods)) { - filter->priv= NO_ISO_LOCK; - xkbi->state.locked_mods^= xkbi->state.base_mods; - } - if ((!(flags&XkbSA_ISONoAffectGroup))&&(xkbi->state.base_group)) { -/* 6/22/93 (ef) -- lock groups if group key is down first */ - } - if (!(flags&XkbSA_ISONoAffectPtr)) { -/* 6/22/93 (ef) -- lock mouse buttons if they're down */ - } - } - else if (filter->keycode==keycode) { - CARD8 flags= filter->upAction.iso.flags; - - if (flags&XkbSA_ISODfltIsGroup) { - xkbi->groupChange = -XkbSAGroup(&filter->upAction.iso); - xkbi->clearMods = 0; - if (filter->priv==ISO_KEY_DOWN) - xkbi->state.locked_group+= XkbSAGroup(&filter->upAction.iso); - } - else { - xkbi->clearMods= filter->upAction.iso.mask; - xkbi->groupChange= 0; - if (filter->priv==ISO_KEY_DOWN) - xkbi->state.locked_mods^= filter->upAction.iso.mask; - } - filter->active = 0; - } - else if (pAction) { - CARD8 flags= filter->upAction.iso.flags; - - switch (pAction->type) { - case XkbSA_SetMods: case XkbSA_LatchMods: - if (!(flags&XkbSA_ISONoAffectMods)) { - pAction->type= XkbSA_LockMods; - filter->priv= NO_ISO_LOCK; - } - break; - case XkbSA_SetGroup: case XkbSA_LatchGroup: - if (!(flags&XkbSA_ISONoAffectGroup)) { - pAction->type= XkbSA_LockGroup; - filter->priv= NO_ISO_LOCK; - } - break; - case XkbSA_PtrBtn: - if (!(flags&XkbSA_ISONoAffectPtr)) { - pAction->type= XkbSA_LockPtrBtn; - filter->priv= NO_ISO_LOCK; - } - break; - case XkbSA_SetControls: - if (!(flags&XkbSA_ISONoAffectCtrls)) { - pAction->type= XkbSA_LockControls; - filter->priv= NO_ISO_LOCK; - } - break; - } - } - return 1; -} - - -static CARD32 -_XkbPtrAccelExpire(OsTimerPtr timer,CARD32 now,pointer arg) -{ -XkbSrvInfoPtr xkbi= (XkbSrvInfoPtr)arg; -XkbControlsPtr ctrls= xkbi->desc->ctrls; -int dx,dy; - - if (xkbi->mouseKey==0) - return 0; - - if (xkbi->mouseKeysAccel) { - if ((xkbi->mouseKeysCounter)<ctrls->mk_time_to_max) { - double step; - xkbi->mouseKeysCounter++; - step= xkbi->mouseKeysCurveFactor* - pow((double)xkbi->mouseKeysCounter,xkbi->mouseKeysCurve); - if (xkbi->mouseKeysDX<0) - dx= floor( ((double)xkbi->mouseKeysDX)*step ); - else dx= ceil( ((double)xkbi->mouseKeysDX)*step ); - if (xkbi->mouseKeysDY<0) - dy= floor( ((double)xkbi->mouseKeysDY)*step ); - else dy= ceil( ((double)xkbi->mouseKeysDY)*step ); - } - else { - dx= xkbi->mouseKeysDX*ctrls->mk_max_speed; - dy= xkbi->mouseKeysDY*ctrls->mk_max_speed; - } - if (xkbi->mouseKeysFlags&XkbSA_MoveAbsoluteX) - dx= xkbi->mouseKeysDX; - if (xkbi->mouseKeysFlags&XkbSA_MoveAbsoluteY) - dy= xkbi->mouseKeysDY; - } - else { - dx= xkbi->mouseKeysDX; - dy= xkbi->mouseKeysDY; - } - XkbDDXFakePointerMotion(xkbi->mouseKeysFlags,dx,dy); - return xkbi->desc->ctrls->mk_interval; -} - -static int -_XkbFilterPointerMove( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ -int x,y; -Bool accel; - - if (xkbi->device == inputInfo.keyboard) - return 0; - - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv=0; - filter->filter = _XkbFilterPointerMove; - filter->upAction= *pAction; - xkbi->mouseKeysCounter= 0; - xkbi->mouseKey= keycode; - accel= ((pAction->ptr.flags&XkbSA_NoAcceleration)==0); - x= XkbPtrActionX(&pAction->ptr); - y= XkbPtrActionY(&pAction->ptr); - XkbDDXFakePointerMotion(pAction->ptr.flags,x,y); - AccessXCancelRepeatKey(xkbi,keycode); - xkbi->mouseKeysAccel= accel&& - (xkbi->desc->ctrls->enabled_ctrls&XkbMouseKeysAccelMask); - xkbi->mouseKeysFlags= pAction->ptr.flags; - xkbi->mouseKeysDX= XkbPtrActionX(&pAction->ptr); - xkbi->mouseKeysDY= XkbPtrActionY(&pAction->ptr); - xkbi->mouseKeyTimer= TimerSet(xkbi->mouseKeyTimer, 0, - xkbi->desc->ctrls->mk_delay, - _XkbPtrAccelExpire,(pointer)xkbi); - } - else if (filter->keycode==keycode) { - filter->active = 0; - if (xkbi->mouseKey==keycode) { - xkbi->mouseKey= 0; - xkbi->mouseKeyTimer= TimerSet(xkbi->mouseKeyTimer, 0, 0, - NULL, NULL); - } - } - return 0; -} - -static int -_XkbFilterPointerBtn( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - if (filter->keycode==0) { /* initial press */ - int button= pAction->btn.button; - - if (button==XkbSA_UseDfltButton) - button = xkbi->desc->ctrls->mk_dflt_btn; - - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv=0; - filter->filter = _XkbFilterPointerBtn; - filter->upAction= *pAction; - filter->upAction.btn.button= button; - switch (pAction->type) { - case XkbSA_LockPtrBtn: - if (((xkbi->lockedPtrButtons&(1<<button))==0)&& - ((pAction->btn.flags&XkbSA_LockNoLock)==0)) { - xkbi->lockedPtrButtons|= (1<<button); - AccessXCancelRepeatKey(xkbi,keycode); - XkbDDXFakeDeviceButton(xkbi->device, 1, button); - filter->upAction.type= XkbSA_NoAction; - } - break; - case XkbSA_PtrBtn: - { - register int i,nClicks; - AccessXCancelRepeatKey(xkbi,keycode); - if (pAction->btn.count>0) { - nClicks= pAction->btn.count; - for (i=0;i<nClicks;i++) { - XkbDDXFakeDeviceButton(xkbi->device, 1, button); - XkbDDXFakeDeviceButton(xkbi->device, 0, button); - } - filter->upAction.type= XkbSA_NoAction; - } - else XkbDDXFakeDeviceButton(xkbi->device, 1, button); - } - break; - case XkbSA_SetPtrDflt: - { - XkbControlsPtr ctrls= xkbi->desc->ctrls; - XkbControlsRec old; - xkbControlsNotify cn; - - old= *ctrls; - AccessXCancelRepeatKey(xkbi,keycode); - switch (pAction->dflt.affect) { - case XkbSA_AffectDfltBtn: - if (pAction->dflt.flags&XkbSA_DfltBtnAbsolute) - ctrls->mk_dflt_btn= - XkbSAPtrDfltValue(&pAction->dflt); - else { - ctrls->mk_dflt_btn+= - XkbSAPtrDfltValue(&pAction->dflt); - if (ctrls->mk_dflt_btn>5) - ctrls->mk_dflt_btn= 5; - else if (ctrls->mk_dflt_btn<1) - ctrls->mk_dflt_btn= 1; - } - break; - default: - ErrorF( - "Attempt to change unknown pointer default (%d) ignored\n", - pAction->dflt.affect); - break; - } - if (XkbComputeControlsNotify(xkbi->device, - &old,xkbi->desc->ctrls, - &cn,False)) { - cn.keycode = keycode; - /* XXX: what about DeviceKeyPress? */ - cn.eventType = KeyPress; - cn.requestMajor = 0; - cn.requestMinor = 0; - XkbSendControlsNotify(xkbi->device,&cn); - } - } - break; - } - } - else if (filter->keycode==keycode) { - int button= filter->upAction.btn.button; - - switch (filter->upAction.type) { - case XkbSA_LockPtrBtn: - if (((filter->upAction.btn.flags&XkbSA_LockNoUnlock)!=0)|| - ((xkbi->lockedPtrButtons&(1<<button))==0)) { - break; - } - xkbi->lockedPtrButtons&= ~(1<<button); - case XkbSA_PtrBtn: - XkbDDXFakeDeviceButton(xkbi->device, 0, button); - break; - } - filter->active = 0; - } - return 0; -} - -static int -_XkbFilterControls( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ -XkbControlsRec old; -XkbControlsPtr ctrls; -DeviceIntPtr kbd; -unsigned int change; -XkbEventCauseRec cause; - - kbd= xkbi->device; - ctrls= xkbi->desc->ctrls; - old= *ctrls; - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - change= XkbActionCtrls(&pAction->ctrls); - filter->priv = change; - filter->filter = _XkbFilterControls; - filter->upAction = *pAction; - - if (pAction->type==XkbSA_LockControls) { - filter->priv= (ctrls->enabled_ctrls&change); - change&= ~ctrls->enabled_ctrls; - } - - if (change) { - xkbControlsNotify cn; - XkbSrvLedInfoPtr sli; - - ctrls->enabled_ctrls|= change; - if (XkbComputeControlsNotify(kbd,&old,ctrls,&cn,False)) { - cn.keycode = keycode; - /* XXX: what about DeviceKeyPress? */ - cn.eventType = KeyPress; - cn.requestMajor = 0; - cn.requestMinor = 0; - XkbSendControlsNotify(kbd,&cn); - } - - XkbSetCauseKey(&cause,keycode,KeyPress); - - /* If sticky keys were disabled, clear all locks and latches */ - if ((old.enabled_ctrls&XkbStickyKeysMask)&& - (!(ctrls->enabled_ctrls&XkbStickyKeysMask))) { - XkbClearAllLatchesAndLocks(kbd,xkbi,False,&cause); - } - sli= XkbFindSrvLedInfo(kbd,XkbDfltXIClass,XkbDfltXIId,0); - XkbUpdateIndicators(kbd,sli->usesControls,True,NULL,&cause); - if (XkbAX_NeedFeedback(ctrls,XkbAX_FeatureFBMask)) - XkbDDXAccessXBeep(kbd,_BEEP_FEATURE_ON,change); - } - } - else if (filter->keycode==keycode) { - change= filter->priv; - if (change) { - xkbControlsNotify cn; - XkbSrvLedInfoPtr sli; - - ctrls->enabled_ctrls&= ~change; - if (XkbComputeControlsNotify(kbd,&old,ctrls,&cn,False)) { - cn.keycode = keycode; - cn.eventType = KeyRelease; - cn.requestMajor = 0; - cn.requestMinor = 0; - XkbSendControlsNotify(kbd,&cn); - } - - XkbSetCauseKey(&cause,keycode,KeyRelease); - /* If sticky keys were disabled, clear all locks and latches */ - if ((old.enabled_ctrls&XkbStickyKeysMask)&& - (!(ctrls->enabled_ctrls&XkbStickyKeysMask))) { - XkbClearAllLatchesAndLocks(kbd,xkbi,False,&cause); - } - sli= XkbFindSrvLedInfo(kbd,XkbDfltXIClass,XkbDfltXIId,0); - XkbUpdateIndicators(kbd,sli->usesControls,True,NULL,&cause); - if (XkbAX_NeedFeedback(ctrls,XkbAX_FeatureFBMask)) - XkbDDXAccessXBeep(kbd,_BEEP_FEATURE_OFF,change); - } - filter->keycode= 0; - filter->active= 0; - } - return 1; -} - -static int -_XkbFilterActionMessage(XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ -XkbMessageAction * pMsg; -DeviceIntPtr kbd; - - kbd= xkbi->device; - if (filter->keycode==0) { /* initial press */ - pMsg= &pAction->msg; - if ((pMsg->flags&XkbSA_MessageOnRelease)|| - ((pMsg->flags&XkbSA_MessageGenKeyEvent)==0)) { - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv = 0; - filter->filter = _XkbFilterActionMessage; - filter->upAction = *pAction; - } - if (pMsg->flags&XkbSA_MessageOnPress) { - xkbActionMessage msg; - - msg.keycode= keycode; - msg.press= 1; - msg.keyEventFollows=((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0); - memcpy((char *)msg.message, - (char *)pMsg->message,XkbActionMessageLength); - XkbSendActionMessage(kbd,&msg); - } - return ((pAction->msg.flags&XkbSA_MessageGenKeyEvent)!=0); - } - else if (filter->keycode==keycode) { - pMsg= &filter->upAction.msg; - if (pMsg->flags&XkbSA_MessageOnRelease) { - xkbActionMessage msg; - - msg.keycode= keycode; - msg.press= 0; - msg.keyEventFollows=((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0); - memcpy((char *)msg.message,(char *)pMsg->message, - XkbActionMessageLength); - XkbSendActionMessage(kbd,&msg); - } - filter->keycode= 0; - filter->active= 0; - return ((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0); - } - return 0; -} - -static int -_XkbFilterRedirectKey( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ -DeviceEvent ev; -int x,y; -XkbStateRec old; -unsigned mods,mask; -xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(xkbi->device); -ProcessInputProc backupproc; - - /* never actually used uninitialised, but gcc isn't smart enough - * to work that out. */ - memset(&old, 0, sizeof(old)); - - if ((filter->keycode!=0)&&(filter->keycode!=keycode)) - return 1; - - GetSpritePosition(xkbi->device, &x,&y); - ev.header = ET_Internal; - ev.length = sizeof(DeviceEvent); - ev.time = GetTimeInMillis(); - ev.root_x = x; - ev.root_y = y; - - if (filter->keycode==0) { /* initial press */ - if ((pAction->redirect.new_key<xkbi->desc->min_key_code)|| - (pAction->redirect.new_key>xkbi->desc->max_key_code)) { - return 1; - } - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv = 0; - filter->filter = _XkbFilterRedirectKey; - filter->upAction = *pAction; - - ev.type = ET_KeyPress; - ev.detail.key = pAction->redirect.new_key; - - mask= XkbSARedirectVModsMask(&pAction->redirect); - mods= XkbSARedirectVMods(&pAction->redirect); - if (mask) XkbVirtualModsToReal(xkbi->desc,mask,&mask); - if (mods) XkbVirtualModsToReal(xkbi->desc,mods,&mods); - mask|= pAction->redirect.mods_mask; - mods|= pAction->redirect.mods; - - if ( mask || mods ) { - old= xkbi->state; - xkbi->state.base_mods&= ~mask; - xkbi->state.base_mods|= (mods&mask); - xkbi->state.latched_mods&= ~mask; - xkbi->state.latched_mods|= (mods&mask); - xkbi->state.locked_mods&= ~mask; - xkbi->state.locked_mods|= (mods&mask); - XkbComputeDerivedState(xkbi); - } - - UNWRAP_PROCESS_INPUT_PROC(xkbi->device,xkbPrivPtr, backupproc); - xkbi->device->public.processInputProc((InternalEvent*)&ev, xkbi->device); - COND_WRAP_PROCESS_INPUT_PROC(xkbi->device, xkbPrivPtr, - backupproc,xkbUnwrapProc); - - if ( mask || mods ) - xkbi->state= old; - } - else if (filter->keycode==keycode) { - - ev.type = ET_KeyRelease; - ev.detail.key = filter->upAction.redirect.new_key; - - mask= XkbSARedirectVModsMask(&filter->upAction.redirect); - mods= XkbSARedirectVMods(&filter->upAction.redirect); - if (mask) XkbVirtualModsToReal(xkbi->desc,mask,&mask); - if (mods) XkbVirtualModsToReal(xkbi->desc,mods,&mods); - mask|= filter->upAction.redirect.mods_mask; - mods|= filter->upAction.redirect.mods; - - if ( mask || mods ) { - old= xkbi->state; - xkbi->state.base_mods&= ~mask; - xkbi->state.base_mods|= (mods&mask); - xkbi->state.latched_mods&= ~mask; - xkbi->state.latched_mods|= (mods&mask); - xkbi->state.locked_mods&= ~mask; - xkbi->state.locked_mods|= (mods&mask); - XkbComputeDerivedState(xkbi); - } - - UNWRAP_PROCESS_INPUT_PROC(xkbi->device,xkbPrivPtr, backupproc); - xkbi->device->public.processInputProc((InternalEvent*)&ev, xkbi->device); - COND_WRAP_PROCESS_INPUT_PROC(xkbi->device, xkbPrivPtr, - backupproc,xkbUnwrapProc); - - if ( mask || mods ) - xkbi->state= old; - - filter->keycode= 0; - filter->active= 0; - } - return 0; -} - -static int -_XkbFilterSwitchScreen( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - DeviceIntPtr dev = xkbi->device; - if (dev == inputInfo.keyboard) - return 0; - - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->filter = _XkbFilterSwitchScreen; - AccessXCancelRepeatKey(xkbi, keycode); - XkbDDXSwitchScreen(dev,keycode,pAction); - return 0; - } - else if (filter->keycode==keycode) { - filter->active= 0; - return 0; - } - return 1; -} - -static int -_XkbFilterXF86Private( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ - DeviceIntPtr dev = xkbi->device; - if (dev == inputInfo.keyboard) - return 0; - - if (filter->keycode==0) { /* initial press */ - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->filter = _XkbFilterXF86Private; - XkbDDXPrivate(dev,keycode,pAction); - return 0; - } - else if (filter->keycode==keycode) { - filter->active= 0; - return 0; - } - return 1; -} - - -static int -_XkbFilterDeviceBtn( XkbSrvInfoPtr xkbi, - XkbFilterPtr filter, - unsigned keycode, - XkbAction * pAction) -{ -DeviceIntPtr dev; -int button; - - if (xkbi->device == inputInfo.keyboard) - return 0; - - if (filter->keycode==0) { /* initial press */ - _XkbLookupButtonDevice(&dev, pAction->devbtn.device, serverClient, - DixUnknownAccess, &button); - if (!dev || !dev->public.on) - return 1; - - button= pAction->devbtn.button; - if ((button<1)||(button>dev->button->numButtons)) - return 1; - - filter->keycode = keycode; - filter->active = 1; - filter->filterOthers = 0; - filter->priv=0; - filter->filter = _XkbFilterDeviceBtn; - filter->upAction= *pAction; - switch (pAction->type) { - case XkbSA_LockDeviceBtn: - if ((pAction->devbtn.flags&XkbSA_LockNoLock)|| - BitIsOn(dev->button->down, button)) - return 0; - XkbDDXFakeDeviceButton(dev,True,button); - filter->upAction.type= XkbSA_NoAction; - break; - case XkbSA_DeviceBtn: - if (pAction->devbtn.count>0) { - int nClicks,i; - nClicks= pAction->btn.count; - for (i=0;i<nClicks;i++) { - XkbDDXFakeDeviceButton(dev,True,button); - XkbDDXFakeDeviceButton(dev,False,button); - } - filter->upAction.type= XkbSA_NoAction; - } - else XkbDDXFakeDeviceButton(dev,True,button); - break; - } - } - else if (filter->keycode==keycode) { - int button; - - filter->active= 0; - _XkbLookupButtonDevice(&dev, filter->upAction.devbtn.device, - serverClient, DixUnknownAccess, &button); - if (!dev || !dev->public.on) - return 1; - - button= filter->upAction.btn.button; - switch (filter->upAction.type) { - case XkbSA_LockDeviceBtn: - if ((filter->upAction.devbtn.flags&XkbSA_LockNoUnlock)|| - !BitIsOn(dev->button->down, button)) - return 0; - XkbDDXFakeDeviceButton(dev,False,button); - break; - case XkbSA_DeviceBtn: - XkbDDXFakeDeviceButton(dev,False,button); - break; - } - filter->active = 0; - } - return 0; -} - -static XkbFilterPtr -_XkbNextFreeFilter( - XkbSrvInfoPtr xkbi -) -{ -register int i; - - if (xkbi->szFilters==0) { - xkbi->szFilters = 4; - xkbi->filters = _XkbTypedCalloc(xkbi->szFilters,XkbFilterRec); - /* 6/21/93 (ef) -- XXX! deal with allocation failure */ - } - for (i=0;i<xkbi->szFilters;i++) { - if (!xkbi->filters[i].active) { - xkbi->filters[i].keycode = 0; - return &xkbi->filters[i]; - } - } - xkbi->szFilters*=2; - xkbi->filters= _XkbTypedRealloc(xkbi->filters, - xkbi->szFilters, - XkbFilterRec); - /* 6/21/93 (ef) -- XXX! deal with allocation failure */ - bzero(&xkbi->filters[xkbi->szFilters/2], - (xkbi->szFilters/2)*sizeof(XkbFilterRec)); - return &xkbi->filters[xkbi->szFilters/2]; -} - -static int -_XkbApplyFilters(XkbSrvInfoPtr xkbi,unsigned kc,XkbAction *pAction) -{ -register int i,send; - - send= 1; - for (i=0;i<xkbi->szFilters;i++) { - if ((xkbi->filters[i].active)&&(xkbi->filters[i].filter)) - send= ((*xkbi->filters[i].filter)(xkbi,&xkbi->filters[i],kc,pAction) - && send); - } - return send; -} - -void -XkbHandleActions(DeviceIntPtr dev, DeviceIntPtr kbd, DeviceEvent* event) -{ -int key,bit,i; -XkbSrvInfoPtr xkbi; -KeyClassPtr keyc; -int changed,sendEvent; -Bool genStateNotify; -XkbAction act; -XkbFilterPtr filter; -Bool keyEvent; -Bool pressEvent; -ProcessInputProc backupproc; - -xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(dev); - - keyc= kbd->key; - xkbi= keyc->xkbInfo; - key= event->detail.key; - /* The state may change, so if we're not in the middle of sending a state - * notify, prepare for it */ - if ((xkbi->flags&_XkbStateNotifyInProgress)==0) { - xkbi->prev_state = xkbi->state; - xkbi->flags|= _XkbStateNotifyInProgress; - genStateNotify= True; - } - else genStateNotify= False; - - xkbi->clearMods = xkbi->setMods = 0; - xkbi->groupChange = 0; - - sendEvent = 1; - keyEvent= ((event->type == ET_KeyPress) || (event->type == ET_KeyRelease)); - pressEvent= ((event->type == ET_KeyPress)|| (event->type == ET_ButtonPress)); - - if (pressEvent) { - if (keyEvent) - act = XkbGetKeyAction(xkbi,&xkbi->state,key); - else { - act = XkbGetButtonAction(kbd,dev,key); - key|= BTN_ACT_FLAG; - } - sendEvent = _XkbApplyFilters(xkbi,key,&act); - if (sendEvent) { - switch (act.type) { - case XkbSA_SetMods: - case XkbSA_SetGroup: - filter = _XkbNextFreeFilter(xkbi); - sendEvent = _XkbFilterSetState(xkbi,filter,key,&act); - break; - case XkbSA_LatchMods: - case XkbSA_LatchGroup: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterLatchState(xkbi,filter,key,&act); - break; - case XkbSA_LockMods: - case XkbSA_LockGroup: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterLockState(xkbi,filter,key,&act); - break; - case XkbSA_ISOLock: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterISOLock(xkbi,filter,key,&act); - break; - case XkbSA_MovePtr: - filter = _XkbNextFreeFilter(xkbi); - sendEvent= _XkbFilterPointerMove(xkbi,filter,key,&act); - break; - case XkbSA_PtrBtn: - case XkbSA_LockPtrBtn: - case XkbSA_SetPtrDflt: - filter = _XkbNextFreeFilter(xkbi); - sendEvent= _XkbFilterPointerBtn(xkbi,filter,key,&act); - break; - case XkbSA_Terminate: - sendEvent= XkbDDXTerminateServer(dev,key,&act); - break; - case XkbSA_SwitchScreen: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterSwitchScreen(xkbi,filter,key,&act); - break; - case XkbSA_SetControls: - case XkbSA_LockControls: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterControls(xkbi,filter,key,&act); - break; - case XkbSA_ActionMessage: - filter = _XkbNextFreeFilter(xkbi); - sendEvent=_XkbFilterActionMessage(xkbi,filter,key,&act); - break; - case XkbSA_RedirectKey: - filter = _XkbNextFreeFilter(xkbi); - sendEvent= _XkbFilterRedirectKey(xkbi,filter,key,&act); - break; - case XkbSA_DeviceBtn: - case XkbSA_LockDeviceBtn: - filter = _XkbNextFreeFilter(xkbi); - sendEvent= _XkbFilterDeviceBtn(xkbi,filter,key,&act); - break; - case XkbSA_XFree86Private: - filter = _XkbNextFreeFilter(xkbi); - sendEvent= _XkbFilterXF86Private(xkbi,filter,key,&act); - break; - } - } - } - else { - if (!keyEvent) - key|= BTN_ACT_FLAG; - sendEvent = _XkbApplyFilters(xkbi,key,NULL); - } - - if (xkbi->groupChange!=0) - xkbi->state.base_group+= xkbi->groupChange; - if (xkbi->setMods) { - for (i=0,bit=1; xkbi->setMods; i++,bit<<=1 ) { - if (xkbi->setMods&bit) { - keyc->modifierKeyCount[i]++; - xkbi->state.base_mods|= bit; - xkbi->setMods&= ~bit; - } - } - } - if (xkbi->clearMods) { - for (i=0,bit=1; xkbi->clearMods; i++,bit<<=1 ) { - if (xkbi->clearMods&bit) { - keyc->modifierKeyCount[i]--; - if (keyc->modifierKeyCount[i]<=0) { - xkbi->state.base_mods&= ~bit; - keyc->modifierKeyCount[i] = 0; - } - xkbi->clearMods&= ~bit; - } - } - } - - if (sendEvent) { - DeviceIntPtr tmpdev; - if (keyEvent) - tmpdev = dev; - else - tmpdev = GetPairedDevice(dev); - - UNWRAP_PROCESS_INPUT_PROC(tmpdev,xkbPrivPtr, backupproc); - dev->public.processInputProc((InternalEvent*)event, tmpdev); - COND_WRAP_PROCESS_INPUT_PROC(tmpdev, xkbPrivPtr, - backupproc,xkbUnwrapProc); - } - else if (keyEvent) { - FixKeyState(event, dev); - } - - XkbComputeDerivedState(xkbi); - changed = XkbStateChangedFlags(&xkbi->prev_state,&xkbi->state); - if (genStateNotify) { - if (changed) { - xkbStateNotify sn; - sn.keycode= key; - sn.eventType= event->type; - sn.requestMajor = sn.requestMinor = 0; - sn.changed= changed; - XkbSendStateNotify(dev,&sn); - } - xkbi->flags&= ~_XkbStateNotifyInProgress; - } - changed= XkbIndicatorsToUpdate(dev,changed,False); - if (changed) { - XkbEventCauseRec cause; - XkbSetCauseKey(&cause, key, event->type); - XkbUpdateIndicators(dev,changed,False,NULL,&cause); - } - return; -} - -int -XkbLatchModifiers(DeviceIntPtr pXDev,CARD8 mask,CARD8 latches) -{ -XkbSrvInfoPtr xkbi; -XkbFilterPtr filter; -XkbAction act; -unsigned clear; - - if ( pXDev && pXDev->key && pXDev->key->xkbInfo ) { - xkbi = pXDev->key->xkbInfo; - clear= (mask&(~latches)); - xkbi->state.latched_mods&= ~clear; - /* Clear any pending latch to locks. - */ - act.type = XkbSA_NoAction; - _XkbApplyFilters(xkbi,SYNTHETIC_KEYCODE,&act); - act.type = XkbSA_LatchMods; - act.mods.flags = 0; - act.mods.mask = mask&latches; - filter = _XkbNextFreeFilter(xkbi); - _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,&act); - _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,(XkbAction *)NULL); - return Success; - } - return BadValue; -} - -int -XkbLatchGroup(DeviceIntPtr pXDev,int group) -{ -XkbSrvInfoPtr xkbi; -XkbFilterPtr filter; -XkbAction act; - - if ( pXDev && pXDev->key && pXDev->key->xkbInfo ) { - xkbi = pXDev->key->xkbInfo; - act.type = XkbSA_LatchGroup; - act.group.flags = 0; - XkbSASetGroup(&act.group,group); - filter = _XkbNextFreeFilter(xkbi); - _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,&act); - _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,(XkbAction *)NULL); - return Success; - } - return BadValue; -} - -/***====================================================================***/ - -void -XkbClearAllLatchesAndLocks( DeviceIntPtr dev, - XkbSrvInfoPtr xkbi, - Bool genEv, - XkbEventCausePtr cause) -{ -XkbStateRec os; -xkbStateNotify sn; - - sn.changed= 0; - os= xkbi->state; - if (os.latched_mods) { /* clear all latches */ - XkbLatchModifiers(dev,~0,0); - sn.changed|= XkbModifierLatchMask; - } - if (os.latched_group) { - XkbLatchGroup(dev,0); - sn.changed|= XkbGroupLatchMask; - } - if (os.locked_mods) { - xkbi->state.locked_mods= 0; - sn.changed|= XkbModifierLockMask; - } - if (os.locked_group) { - xkbi->state.locked_group= 0; - sn.changed|= XkbGroupLockMask; - } - if ( genEv && sn.changed) { - CARD32 changed; - - XkbComputeDerivedState(xkbi); - sn.keycode= cause->kc; - sn.eventType= cause->event; - sn.requestMajor= cause->mjr; - sn.requestMinor= cause->mnr; - sn.changed= XkbStateChangedFlags(&os,&xkbi->state); - XkbSendStateNotify(dev,&sn); - changed= XkbIndicatorsToUpdate(dev,sn.changed,False); - if (changed) { - XkbUpdateIndicators(dev,changed,True,NULL,cause); - } - } - return; -} - +/************************************************************
+Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
+
+Permission to use, copy, modify, and distribute this
+software and its documentation for any purpose and without
+fee is hereby granted, 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 Silicon Graphics not be
+used in advertising or publicity pertaining to distribution
+of the software without specific prior written permission.
+Silicon Graphics makes no representation about the suitability
+of this software for any purpose. It is provided "as is"
+without any express or implied warranty.
+
+SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
+SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
+GRAPHICS 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_DIX_CONFIG_H
+#include <dix-config.h>
+#endif
+
+#include <stdio.h>
+#include <math.h>
+#include <X11/X.h>
+#include <X11/Xproto.h>
+#include <X11/keysym.h>
+#include "misc.h"
+#include "inputstr.h"
+#include "exevents.h"
+#include "eventstr.h"
+#include <xkbsrv.h>
+#include "xkb.h"
+#include <ctype.h>
+#define EXTENSION_EVENT_BASE 64
+
+static int xkbDevicePrivateKeyIndex;
+DevPrivateKey xkbDevicePrivateKey = &xkbDevicePrivateKeyIndex;
+
+void
+xkbUnwrapProc(DeviceIntPtr device, DeviceHandleProc proc,
+ pointer data)
+{
+ xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(device);
+ ProcessInputProc backupproc;
+ if(xkbPrivPtr->unwrapProc)
+ xkbPrivPtr->unwrapProc = NULL;
+
+ UNWRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr, backupproc);
+ proc(device,data);
+ COND_WRAP_PROCESS_INPUT_PROC(device,xkbPrivPtr,
+ backupproc,xkbUnwrapProc);
+}
+
+
+void
+XkbSetExtension(DeviceIntPtr device, ProcessInputProc proc)
+{
+ xkbDeviceInfoPtr xkbPrivPtr;
+
+ xkbPrivPtr = (xkbDeviceInfoPtr) xcalloc(1, sizeof(xkbDeviceInfoRec));
+ if (!xkbPrivPtr)
+ return;
+ xkbPrivPtr->unwrapProc = NULL;
+
+ dixSetPrivate(&device->devPrivates, xkbDevicePrivateKey, xkbPrivPtr);
+ WRAP_PROCESS_INPUT_PROC(device, xkbPrivPtr, proc, xkbUnwrapProc);
+}
+
+/***====================================================================***/
+
+static XkbAction
+_FixUpAction(XkbDescPtr xkb,XkbAction *act)
+{
+static XkbAction fake;
+
+ if (XkbIsPtrAction(act)&&(!(xkb->ctrls->enabled_ctrls&XkbMouseKeysMask))) {
+ fake.type = XkbSA_NoAction;
+ return fake;
+ }
+ if (xkb->ctrls->enabled_ctrls&XkbStickyKeysMask) {
+ if (act->any.type==XkbSA_SetMods) {
+ fake.mods.type = XkbSA_LatchMods;
+ fake.mods.mask = act->mods.mask;
+ if (XkbAX_NeedOption(xkb->ctrls,XkbAX_LatchToLockMask))
+ fake.mods.flags= XkbSA_ClearLocks|XkbSA_LatchToLock;
+ else fake.mods.flags= XkbSA_ClearLocks;
+ return fake;
+ }
+ if (act->any.type==XkbSA_SetGroup) {
+ fake.group.type = XkbSA_LatchGroup;
+ if (XkbAX_NeedOption(xkb->ctrls,XkbAX_LatchToLockMask))
+ fake.group.flags= XkbSA_ClearLocks|XkbSA_LatchToLock;
+ else fake.group.flags= XkbSA_ClearLocks;
+ XkbSASetGroup(&fake.group,XkbSAGroup(&act->group));
+ return fake;
+ }
+ }
+ return *act;
+}
+
+static XkbAction
+XkbGetKeyAction(XkbSrvInfoPtr xkbi,XkbStatePtr xkbState,CARD8 key)
+{
+int effectiveGroup;
+int col;
+XkbDescPtr xkb;
+XkbKeyTypePtr type;
+XkbAction * pActs;
+static XkbAction fake;
+
+ xkb= xkbi->desc;
+ if (!XkbKeyHasActions(xkb,key) || !XkbKeycodeInRange(xkb,key)) {
+ fake.type = XkbSA_NoAction;
+ return fake;
+ }
+ pActs= XkbKeyActionsPtr(xkb,key);
+ col= 0;
+
+ effectiveGroup = XkbGetEffectiveGroup(xkbi, xkbState, key);
+ if (effectiveGroup != XkbGroup1Index)
+ col += (effectiveGroup * XkbKeyGroupsWidth(xkb, key));
+
+ type= XkbKeyKeyType(xkb,key,effectiveGroup);
+ if (type->map!=NULL) {
+ register unsigned i,mods;
+ register XkbKTMapEntryPtr entry;
+ mods= xkbState->mods&type->mods.mask;
+ for (entry= type->map,i=0;i<type->map_count;i++,entry++) {
+ if ((entry->active)&&(entry->mods.mask==mods)) {
+ col+= entry->level;
+ break;
+ }
+ }
+ }
+ if (pActs[col].any.type==XkbSA_NoAction)
+ return pActs[col];
+ fake= _FixUpAction(xkb,&pActs[col]);
+ return fake;
+}
+
+static XkbAction
+XkbGetButtonAction(DeviceIntPtr kbd,DeviceIntPtr dev,int button)
+{
+XkbAction fake;
+ if ((dev->button)&&(dev->button->xkb_acts)) {
+ if (dev->button->xkb_acts[button-1].any.type!=XkbSA_NoAction) {
+ fake= _FixUpAction(kbd->key->xkbInfo->desc,
+ &dev->button->xkb_acts[button-1]);
+ return fake;
+ }
+ }
+ fake.any.type= XkbSA_NoAction;
+ return fake;
+}
+
+/***====================================================================***/
+
+#define SYNTHETIC_KEYCODE 1
+#define BTN_ACT_FLAG 0x100
+
+static int
+_XkbFilterSetState( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction *pAction)
+{
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = ((pAction->mods.mask&XkbSA_ClearLocks)!=0);
+ filter->priv = 0;
+ filter->filter = _XkbFilterSetState;
+ if (pAction->type==XkbSA_SetMods) {
+ filter->upAction = *pAction;
+ xkbi->setMods= pAction->mods.mask;
+ }
+ else {
+ xkbi->groupChange = XkbSAGroup(&pAction->group);
+ if (pAction->group.flags&XkbSA_GroupAbsolute)
+ xkbi->groupChange-= xkbi->state.base_group;
+ filter->upAction= *pAction;
+ XkbSASetGroup(&filter->upAction.group,xkbi->groupChange);
+ }
+ }
+ else if (filter->keycode==keycode) {
+ if (filter->upAction.type==XkbSA_SetMods) {
+ xkbi->clearMods = filter->upAction.mods.mask;
+ if (filter->upAction.mods.flags&XkbSA_ClearLocks) {
+ xkbi->state.locked_mods&= ~filter->upAction.mods.mask;
+ }
+ }
+ else {
+ if (filter->upAction.group.flags&XkbSA_ClearLocks) {
+ xkbi->state.locked_group = 0;
+ }
+ xkbi->groupChange = -XkbSAGroup(&filter->upAction.group);
+ }
+ filter->active = 0;
+ }
+ else {
+ filter->upAction.mods.flags&= ~XkbSA_ClearLocks;
+ filter->filterOthers = 0;
+ }
+ return 1;
+}
+
+#define LATCH_KEY_DOWN 1
+#define LATCH_PENDING 2
+#define NO_LATCH 3
+
+static int
+_XkbFilterLatchState( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 1;
+ filter->priv = LATCH_KEY_DOWN;
+ filter->filter = _XkbFilterLatchState;
+ if (pAction->type==XkbSA_LatchMods) {
+ filter->upAction = *pAction;
+ xkbi->setMods = pAction->mods.mask;
+ }
+ else {
+ xkbi->groupChange = XkbSAGroup(&pAction->group);
+ if (pAction->group.flags&XkbSA_GroupAbsolute)
+ xkbi->groupChange-= xkbi->state.base_group;
+ filter->upAction= *pAction;
+ XkbSASetGroup(&filter->upAction.group,xkbi->groupChange);
+ }
+ }
+ else if ( pAction && (filter->priv==LATCH_PENDING) ) {
+ if (((1<<pAction->type)&XkbSA_BreakLatch)!=0) {
+ filter->active = 0;
+ if (filter->upAction.type==XkbSA_LatchMods)
+ xkbi->state.latched_mods&= ~filter->upAction.mods.mask;
+ else xkbi->state.latched_group-=XkbSAGroup(&filter->upAction.group);
+ }
+ else if ((pAction->type==filter->upAction.type)&&
+ (pAction->mods.flags==filter->upAction.mods.flags)&&
+ (pAction->mods.mask==filter->upAction.mods.mask)) {
+ if (filter->upAction.mods.flags&XkbSA_LatchToLock) {
+ XkbControlsPtr ctrls= xkbi->desc->ctrls;
+ if (filter->upAction.type==XkbSA_LatchMods)
+ pAction->mods.type= XkbSA_LockMods;
+ else pAction->group.type= XkbSA_LockGroup;
+ if (XkbAX_NeedFeedback(ctrls,XkbAX_StickyKeysFBMask)&&
+ (ctrls->enabled_ctrls&XkbStickyKeysMask)) {
+ XkbDDXAccessXBeep(xkbi->device,_BEEP_STICKY_LOCK,
+ XkbStickyKeysMask);
+ }
+ }
+ else {
+ if (filter->upAction.type==XkbSA_LatchMods)
+ pAction->mods.type= XkbSA_SetMods;
+ else pAction->group.type= XkbSA_SetGroup;
+ }
+ if (filter->upAction.type==XkbSA_LatchMods)
+ xkbi->state.latched_mods&= ~filter->upAction.mods.mask;
+ else xkbi->state.latched_group-=XkbSAGroup(&filter->upAction.group);
+ filter->active = 0;
+ }
+ }
+ else if (filter->keycode==keycode) { /* release */
+ XkbControlsPtr ctrls= xkbi->desc->ctrls;
+ int needBeep;
+ int beepType= _BEEP_NONE;
+
+ needBeep= ((ctrls->enabled_ctrls&XkbStickyKeysMask)&&
+ XkbAX_NeedFeedback(ctrls,XkbAX_StickyKeysFBMask));
+ if (filter->upAction.type==XkbSA_LatchMods) {
+ xkbi->clearMods = filter->upAction.mods.mask;
+ if ((filter->upAction.mods.flags&XkbSA_ClearLocks)&&
+ (xkbi->clearMods&xkbi->state.locked_mods)==xkbi->clearMods) {
+ xkbi->state.locked_mods&= ~xkbi->clearMods;
+ filter->priv= NO_LATCH;
+ beepType= _BEEP_STICKY_UNLOCK;
+ }
+ }
+ else {
+ xkbi->groupChange = -XkbSAGroup(&filter->upAction.group);
+ if ((filter->upAction.group.flags&XkbSA_ClearLocks)&&
+ (xkbi->state.locked_group)) {
+ xkbi->state.locked_group = 0;
+ filter->priv = NO_LATCH;
+ beepType= _BEEP_STICKY_UNLOCK;
+ }
+ }
+ if (filter->priv==NO_LATCH) {
+ filter->active= 0;
+ }
+ else {
+ filter->priv= LATCH_PENDING;
+ if (filter->upAction.type==XkbSA_LatchMods) {
+ xkbi->state.latched_mods |= filter->upAction.mods.mask;
+ needBeep = xkbi->state.latched_mods ? needBeep : 0;
+ xkbi->state.latched_mods |= filter->upAction.mods.mask;
+ }
+ else {
+ xkbi->state.latched_group+= XkbSAGroup(&filter->upAction.group);
+ }
+ if (needBeep && (beepType==_BEEP_NONE))
+ beepType= _BEEP_STICKY_LATCH;
+ }
+ if (needBeep && (beepType!=_BEEP_NONE))
+ XkbDDXAccessXBeep(xkbi->device,beepType,XkbStickyKeysMask);
+ }
+ else if (filter->priv==LATCH_KEY_DOWN) {
+ filter->priv= NO_LATCH;
+ filter->filterOthers = 0;
+ }
+ return 1;
+}
+
+static int
+_XkbFilterLockState( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+ if (pAction&&(pAction->type==XkbSA_LockGroup)) {
+ if (pAction->group.flags&XkbSA_GroupAbsolute)
+ xkbi->state.locked_group= XkbSAGroup(&pAction->group);
+ else xkbi->state.locked_group+= XkbSAGroup(&pAction->group);
+ return 1;
+ }
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv = 0;
+ filter->filter = _XkbFilterLockState;
+ filter->upAction = *pAction;
+ xkbi->state.locked_mods^= pAction->mods.mask;
+ xkbi->setMods = pAction->mods.mask;
+ }
+ else if (filter->keycode==keycode) {
+ filter->active = 0;
+ xkbi->clearMods = filter->upAction.mods.mask;
+ }
+ return 1;
+}
+
+#define ISO_KEY_DOWN 0
+#define NO_ISO_LOCK 1
+
+static int
+_XkbFilterISOLock( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+
+ if (filter->keycode==0) { /* initial press */
+ CARD8 flags= pAction->iso.flags;
+
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 1;
+ filter->priv = ISO_KEY_DOWN;
+ filter->upAction = *pAction;
+ filter->filter = _XkbFilterISOLock;
+ if (flags&XkbSA_ISODfltIsGroup) {
+ xkbi->groupChange = XkbSAGroup(&pAction->iso);
+ xkbi->setMods = 0;
+ }
+ else {
+ xkbi->setMods = pAction->iso.mask;
+ xkbi->groupChange = 0;
+ }
+ if ((!(flags&XkbSA_ISONoAffectMods))&&(xkbi->state.base_mods)) {
+ filter->priv= NO_ISO_LOCK;
+ xkbi->state.locked_mods^= xkbi->state.base_mods;
+ }
+ if ((!(flags&XkbSA_ISONoAffectGroup))&&(xkbi->state.base_group)) {
+/* 6/22/93 (ef) -- lock groups if group key is down first */
+ }
+ if (!(flags&XkbSA_ISONoAffectPtr)) {
+/* 6/22/93 (ef) -- lock mouse buttons if they're down */
+ }
+ }
+ else if (filter->keycode==keycode) {
+ CARD8 flags= filter->upAction.iso.flags;
+
+ if (flags&XkbSA_ISODfltIsGroup) {
+ xkbi->groupChange = -XkbSAGroup(&filter->upAction.iso);
+ xkbi->clearMods = 0;
+ if (filter->priv==ISO_KEY_DOWN)
+ xkbi->state.locked_group+= XkbSAGroup(&filter->upAction.iso);
+ }
+ else {
+ xkbi->clearMods= filter->upAction.iso.mask;
+ xkbi->groupChange= 0;
+ if (filter->priv==ISO_KEY_DOWN)
+ xkbi->state.locked_mods^= filter->upAction.iso.mask;
+ }
+ filter->active = 0;
+ }
+ else if (pAction) {
+ CARD8 flags= filter->upAction.iso.flags;
+
+ switch (pAction->type) {
+ case XkbSA_SetMods: case XkbSA_LatchMods:
+ if (!(flags&XkbSA_ISONoAffectMods)) {
+ pAction->type= XkbSA_LockMods;
+ filter->priv= NO_ISO_LOCK;
+ }
+ break;
+ case XkbSA_SetGroup: case XkbSA_LatchGroup:
+ if (!(flags&XkbSA_ISONoAffectGroup)) {
+ pAction->type= XkbSA_LockGroup;
+ filter->priv= NO_ISO_LOCK;
+ }
+ break;
+ case XkbSA_PtrBtn:
+ if (!(flags&XkbSA_ISONoAffectPtr)) {
+ pAction->type= XkbSA_LockPtrBtn;
+ filter->priv= NO_ISO_LOCK;
+ }
+ break;
+ case XkbSA_SetControls:
+ if (!(flags&XkbSA_ISONoAffectCtrls)) {
+ pAction->type= XkbSA_LockControls;
+ filter->priv= NO_ISO_LOCK;
+ }
+ break;
+ }
+ }
+ return 1;
+}
+
+
+static CARD32
+_XkbPtrAccelExpire(OsTimerPtr timer,CARD32 now,pointer arg)
+{
+XkbSrvInfoPtr xkbi= (XkbSrvInfoPtr)arg;
+XkbControlsPtr ctrls= xkbi->desc->ctrls;
+int dx,dy;
+
+ if (xkbi->mouseKey==0)
+ return 0;
+
+ if (xkbi->mouseKeysAccel) {
+ if ((xkbi->mouseKeysCounter)<ctrls->mk_time_to_max) {
+ double step;
+ xkbi->mouseKeysCounter++;
+ step= xkbi->mouseKeysCurveFactor*
+ pow((double)xkbi->mouseKeysCounter,xkbi->mouseKeysCurve);
+ if (xkbi->mouseKeysDX<0)
+ dx= floor( ((double)xkbi->mouseKeysDX)*step );
+ else dx= ceil( ((double)xkbi->mouseKeysDX)*step );
+ if (xkbi->mouseKeysDY<0)
+ dy= floor( ((double)xkbi->mouseKeysDY)*step );
+ else dy= ceil( ((double)xkbi->mouseKeysDY)*step );
+ }
+ else {
+ dx= xkbi->mouseKeysDX*ctrls->mk_max_speed;
+ dy= xkbi->mouseKeysDY*ctrls->mk_max_speed;
+ }
+ if (xkbi->mouseKeysFlags&XkbSA_MoveAbsoluteX)
+ dx= xkbi->mouseKeysDX;
+ if (xkbi->mouseKeysFlags&XkbSA_MoveAbsoluteY)
+ dy= xkbi->mouseKeysDY;
+ }
+ else {
+ dx= xkbi->mouseKeysDX;
+ dy= xkbi->mouseKeysDY;
+ }
+ XkbDDXFakePointerMotion(xkbi->mouseKeysFlags,dx,dy);
+ return xkbi->desc->ctrls->mk_interval;
+}
+
+static int
+_XkbFilterPointerMove( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+int x,y;
+Bool accel;
+
+ if (xkbi->device == inputInfo.keyboard)
+ return 0;
+
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv=0;
+ filter->filter = _XkbFilterPointerMove;
+ filter->upAction= *pAction;
+ xkbi->mouseKeysCounter= 0;
+ xkbi->mouseKey= keycode;
+ accel= ((pAction->ptr.flags&XkbSA_NoAcceleration)==0);
+ x= XkbPtrActionX(&pAction->ptr);
+ y= XkbPtrActionY(&pAction->ptr);
+ XkbDDXFakePointerMotion(pAction->ptr.flags,x,y);
+ AccessXCancelRepeatKey(xkbi,keycode);
+ xkbi->mouseKeysAccel= accel&&
+ (xkbi->desc->ctrls->enabled_ctrls&XkbMouseKeysAccelMask);
+ xkbi->mouseKeysFlags= pAction->ptr.flags;
+ xkbi->mouseKeysDX= XkbPtrActionX(&pAction->ptr);
+ xkbi->mouseKeysDY= XkbPtrActionY(&pAction->ptr);
+ xkbi->mouseKeyTimer= TimerSet(xkbi->mouseKeyTimer, 0,
+ xkbi->desc->ctrls->mk_delay,
+ _XkbPtrAccelExpire,(pointer)xkbi);
+ }
+ else if (filter->keycode==keycode) {
+ filter->active = 0;
+ if (xkbi->mouseKey==keycode) {
+ xkbi->mouseKey= 0;
+ xkbi->mouseKeyTimer= TimerSet(xkbi->mouseKeyTimer, 0, 0,
+ NULL, NULL);
+ }
+ }
+ return 0;
+}
+
+static int
+_XkbFilterPointerBtn( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+ if (filter->keycode==0) { /* initial press */
+ int button= pAction->btn.button;
+
+ if (button==XkbSA_UseDfltButton)
+ button = xkbi->desc->ctrls->mk_dflt_btn;
+
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv=0;
+ filter->filter = _XkbFilterPointerBtn;
+ filter->upAction= *pAction;
+ filter->upAction.btn.button= button;
+ switch (pAction->type) {
+ case XkbSA_LockPtrBtn:
+ if (((xkbi->lockedPtrButtons&(1<<button))==0)&&
+ ((pAction->btn.flags&XkbSA_LockNoLock)==0)) {
+ xkbi->lockedPtrButtons|= (1<<button);
+ AccessXCancelRepeatKey(xkbi,keycode);
+ XkbDDXFakeDeviceButton(xkbi->device, 1, button);
+ filter->upAction.type= XkbSA_NoAction;
+ }
+ break;
+ case XkbSA_PtrBtn:
+ {
+ register int i,nClicks;
+ AccessXCancelRepeatKey(xkbi,keycode);
+ if (pAction->btn.count>0) {
+ nClicks= pAction->btn.count;
+ for (i=0;i<nClicks;i++) {
+ XkbDDXFakeDeviceButton(xkbi->device, 1, button);
+ XkbDDXFakeDeviceButton(xkbi->device, 0, button);
+ }
+ filter->upAction.type= XkbSA_NoAction;
+ }
+ else XkbDDXFakeDeviceButton(xkbi->device, 1, button);
+ }
+ break;
+ case XkbSA_SetPtrDflt:
+ {
+ XkbControlsPtr ctrls= xkbi->desc->ctrls;
+ XkbControlsRec old;
+ xkbControlsNotify cn;
+
+ old= *ctrls;
+ AccessXCancelRepeatKey(xkbi,keycode);
+ switch (pAction->dflt.affect) {
+ case XkbSA_AffectDfltBtn:
+ if (pAction->dflt.flags&XkbSA_DfltBtnAbsolute)
+ ctrls->mk_dflt_btn=
+ XkbSAPtrDfltValue(&pAction->dflt);
+ else {
+ ctrls->mk_dflt_btn+=
+ XkbSAPtrDfltValue(&pAction->dflt);
+ if (ctrls->mk_dflt_btn>5)
+ ctrls->mk_dflt_btn= 5;
+ else if (ctrls->mk_dflt_btn<1)
+ ctrls->mk_dflt_btn= 1;
+ }
+ break;
+ default:
+ ErrorF(
+ "Attempt to change unknown pointer default (%d) ignored\n",
+ pAction->dflt.affect);
+ break;
+ }
+ if (XkbComputeControlsNotify(xkbi->device,
+ &old,xkbi->desc->ctrls,
+ &cn,False)) {
+ cn.keycode = keycode;
+ /* XXX: what about DeviceKeyPress? */
+ cn.eventType = KeyPress;
+ cn.requestMajor = 0;
+ cn.requestMinor = 0;
+ XkbSendControlsNotify(xkbi->device,&cn);
+ }
+ }
+ break;
+ }
+ }
+ else if (filter->keycode==keycode) {
+ int button= filter->upAction.btn.button;
+
+ switch (filter->upAction.type) {
+ case XkbSA_LockPtrBtn:
+ if (((filter->upAction.btn.flags&XkbSA_LockNoUnlock)!=0)||
+ ((xkbi->lockedPtrButtons&(1<<button))==0)) {
+ break;
+ }
+ xkbi->lockedPtrButtons&= ~(1<<button);
+ case XkbSA_PtrBtn:
+ XkbDDXFakeDeviceButton(xkbi->device, 0, button);
+ break;
+ }
+ filter->active = 0;
+ }
+ return 0;
+}
+
+static int
+_XkbFilterControls( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+XkbControlsRec old;
+XkbControlsPtr ctrls;
+DeviceIntPtr kbd;
+unsigned int change;
+XkbEventCauseRec cause;
+
+ kbd= xkbi->device;
+ ctrls= xkbi->desc->ctrls;
+ old= *ctrls;
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ change= XkbActionCtrls(&pAction->ctrls);
+ filter->priv = change;
+ filter->filter = _XkbFilterControls;
+ filter->upAction = *pAction;
+
+ if (pAction->type==XkbSA_LockControls) {
+ filter->priv= (ctrls->enabled_ctrls&change);
+ change&= ~ctrls->enabled_ctrls;
+ }
+
+ if (change) {
+ xkbControlsNotify cn;
+ XkbSrvLedInfoPtr sli;
+
+ ctrls->enabled_ctrls|= change;
+ if (XkbComputeControlsNotify(kbd,&old,ctrls,&cn,False)) {
+ cn.keycode = keycode;
+ /* XXX: what about DeviceKeyPress? */
+ cn.eventType = KeyPress;
+ cn.requestMajor = 0;
+ cn.requestMinor = 0;
+ XkbSendControlsNotify(kbd,&cn);
+ }
+
+ XkbSetCauseKey(&cause,keycode,KeyPress);
+
+ /* If sticky keys were disabled, clear all locks and latches */
+ if ((old.enabled_ctrls&XkbStickyKeysMask)&&
+ (!(ctrls->enabled_ctrls&XkbStickyKeysMask))) {
+ XkbClearAllLatchesAndLocks(kbd,xkbi,False,&cause);
+ }
+ sli= XkbFindSrvLedInfo(kbd,XkbDfltXIClass,XkbDfltXIId,0);
+ XkbUpdateIndicators(kbd,sli->usesControls,True,NULL,&cause);
+ if (XkbAX_NeedFeedback(ctrls,XkbAX_FeatureFBMask))
+ XkbDDXAccessXBeep(kbd,_BEEP_FEATURE_ON,change);
+ }
+ }
+ else if (filter->keycode==keycode) {
+ change= filter->priv;
+ if (change) {
+ xkbControlsNotify cn;
+ XkbSrvLedInfoPtr sli;
+
+ ctrls->enabled_ctrls&= ~change;
+ if (XkbComputeControlsNotify(kbd,&old,ctrls,&cn,False)) {
+ cn.keycode = keycode;
+ cn.eventType = KeyRelease;
+ cn.requestMajor = 0;
+ cn.requestMinor = 0;
+ XkbSendControlsNotify(kbd,&cn);
+ }
+
+ XkbSetCauseKey(&cause,keycode,KeyRelease);
+ /* If sticky keys were disabled, clear all locks and latches */
+ if ((old.enabled_ctrls&XkbStickyKeysMask)&&
+ (!(ctrls->enabled_ctrls&XkbStickyKeysMask))) {
+ XkbClearAllLatchesAndLocks(kbd,xkbi,False,&cause);
+ }
+ sli= XkbFindSrvLedInfo(kbd,XkbDfltXIClass,XkbDfltXIId,0);
+ XkbUpdateIndicators(kbd,sli->usesControls,True,NULL,&cause);
+ if (XkbAX_NeedFeedback(ctrls,XkbAX_FeatureFBMask))
+ XkbDDXAccessXBeep(kbd,_BEEP_FEATURE_OFF,change);
+ }
+ filter->keycode= 0;
+ filter->active= 0;
+ }
+ return 1;
+}
+
+static int
+_XkbFilterActionMessage(XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+XkbMessageAction * pMsg;
+DeviceIntPtr kbd;
+
+ kbd= xkbi->device;
+ if (filter->keycode==0) { /* initial press */
+ pMsg= &pAction->msg;
+ if ((pMsg->flags&XkbSA_MessageOnRelease)||
+ ((pMsg->flags&XkbSA_MessageGenKeyEvent)==0)) {
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv = 0;
+ filter->filter = _XkbFilterActionMessage;
+ filter->upAction = *pAction;
+ }
+ if (pMsg->flags&XkbSA_MessageOnPress) {
+ xkbActionMessage msg;
+
+ msg.keycode= keycode;
+ msg.press= 1;
+ msg.keyEventFollows=((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0);
+ memcpy((char *)msg.message,
+ (char *)pMsg->message,XkbActionMessageLength);
+ XkbSendActionMessage(kbd,&msg);
+ }
+ return ((pAction->msg.flags&XkbSA_MessageGenKeyEvent)!=0);
+ }
+ else if (filter->keycode==keycode) {
+ pMsg= &filter->upAction.msg;
+ if (pMsg->flags&XkbSA_MessageOnRelease) {
+ xkbActionMessage msg;
+
+ msg.keycode= keycode;
+ msg.press= 0;
+ msg.keyEventFollows=((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0);
+ memcpy((char *)msg.message,(char *)pMsg->message,
+ XkbActionMessageLength);
+ XkbSendActionMessage(kbd,&msg);
+ }
+ filter->keycode= 0;
+ filter->active= 0;
+ return ((pMsg->flags&XkbSA_MessageGenKeyEvent)!=0);
+ }
+ return 0;
+}
+
+static int
+_XkbFilterRedirectKey( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+DeviceEvent ev;
+int x,y;
+XkbStateRec old;
+unsigned mods,mask;
+xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(xkbi->device);
+ProcessInputProc backupproc;
+
+ /* never actually used uninitialised, but gcc isn't smart enough
+ * to work that out. */
+ memset(&old, 0, sizeof(old));
+
+ if ((filter->keycode!=0)&&(filter->keycode!=keycode))
+ return 1;
+
+ GetSpritePosition(xkbi->device, &x,&y);
+ ev.header = ET_Internal;
+ ev.length = sizeof(DeviceEvent);
+ ev.time = GetTimeInMillis();
+ ev.root_x = x;
+ ev.root_y = y;
+
+ if (filter->keycode==0) { /* initial press */
+ if ((pAction->redirect.new_key<xkbi->desc->min_key_code)||
+ (pAction->redirect.new_key>xkbi->desc->max_key_code)) {
+ return 1;
+ }
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv = 0;
+ filter->filter = _XkbFilterRedirectKey;
+ filter->upAction = *pAction;
+
+ ev.type = ET_KeyPress;
+ ev.detail.key = pAction->redirect.new_key;
+
+ mask= XkbSARedirectVModsMask(&pAction->redirect);
+ mods= XkbSARedirectVMods(&pAction->redirect);
+ if (mask) XkbVirtualModsToReal(xkbi->desc,mask,&mask);
+ if (mods) XkbVirtualModsToReal(xkbi->desc,mods,&mods);
+ mask|= pAction->redirect.mods_mask;
+ mods|= pAction->redirect.mods;
+
+ if ( mask || mods ) {
+ old= xkbi->state;
+ xkbi->state.base_mods&= ~mask;
+ xkbi->state.base_mods|= (mods&mask);
+ xkbi->state.latched_mods&= ~mask;
+ xkbi->state.latched_mods|= (mods&mask);
+ xkbi->state.locked_mods&= ~mask;
+ xkbi->state.locked_mods|= (mods&mask);
+ XkbComputeDerivedState(xkbi);
+ }
+
+ UNWRAP_PROCESS_INPUT_PROC(xkbi->device,xkbPrivPtr, backupproc);
+ xkbi->device->public.processInputProc((InternalEvent*)&ev, xkbi->device);
+ COND_WRAP_PROCESS_INPUT_PROC(xkbi->device, xkbPrivPtr,
+ backupproc,xkbUnwrapProc);
+
+ if ( mask || mods )
+ xkbi->state= old;
+ }
+ else if (filter->keycode==keycode) {
+
+ ev.type = ET_KeyRelease;
+ ev.detail.key = filter->upAction.redirect.new_key;
+
+ mask= XkbSARedirectVModsMask(&filter->upAction.redirect);
+ mods= XkbSARedirectVMods(&filter->upAction.redirect);
+ if (mask) XkbVirtualModsToReal(xkbi->desc,mask,&mask);
+ if (mods) XkbVirtualModsToReal(xkbi->desc,mods,&mods);
+ mask|= filter->upAction.redirect.mods_mask;
+ mods|= filter->upAction.redirect.mods;
+
+ if ( mask || mods ) {
+ old= xkbi->state;
+ xkbi->state.base_mods&= ~mask;
+ xkbi->state.base_mods|= (mods&mask);
+ xkbi->state.latched_mods&= ~mask;
+ xkbi->state.latched_mods|= (mods&mask);
+ xkbi->state.locked_mods&= ~mask;
+ xkbi->state.locked_mods|= (mods&mask);
+ XkbComputeDerivedState(xkbi);
+ }
+
+ UNWRAP_PROCESS_INPUT_PROC(xkbi->device,xkbPrivPtr, backupproc);
+ xkbi->device->public.processInputProc((InternalEvent*)&ev, xkbi->device);
+ COND_WRAP_PROCESS_INPUT_PROC(xkbi->device, xkbPrivPtr,
+ backupproc,xkbUnwrapProc);
+
+ if ( mask || mods )
+ xkbi->state= old;
+
+ filter->keycode= 0;
+ filter->active= 0;
+ }
+ return 0;
+}
+
+static int
+_XkbFilterSwitchScreen( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+ DeviceIntPtr dev = xkbi->device;
+ if (dev == inputInfo.keyboard)
+ return 0;
+
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->filter = _XkbFilterSwitchScreen;
+ AccessXCancelRepeatKey(xkbi, keycode);
+ XkbDDXSwitchScreen(dev,keycode,pAction);
+ return 0;
+ }
+ else if (filter->keycode==keycode) {
+ filter->active= 0;
+ return 0;
+ }
+ return 1;
+}
+
+static int
+_XkbFilterXF86Private( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+ DeviceIntPtr dev = xkbi->device;
+ if (dev == inputInfo.keyboard)
+ return 0;
+
+ if (filter->keycode==0) { /* initial press */
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->filter = _XkbFilterXF86Private;
+ XkbDDXPrivate(dev,keycode,pAction);
+ return 0;
+ }
+ else if (filter->keycode==keycode) {
+ filter->active= 0;
+ return 0;
+ }
+ return 1;
+}
+
+
+static int
+_XkbFilterDeviceBtn( XkbSrvInfoPtr xkbi,
+ XkbFilterPtr filter,
+ unsigned keycode,
+ XkbAction * pAction)
+{
+DeviceIntPtr dev;
+int button;
+
+ if (filter->keycode==0) { /* initial press */
+ _XkbLookupButtonDevice(&dev, pAction->devbtn.device, serverClient,
+ DixUnknownAccess, &button);
+ if (!dev || !dev->public.on)
+ return 1;
+
+ if (xkbi->device == inputInfo.keyboard)
+ return 0;
+
+ button= pAction->devbtn.button;
+ if ((button<1)||(button>dev->button->numButtons))
+ return 1;
+
+ filter->keycode = keycode;
+ filter->active = 1;
+ filter->filterOthers = 0;
+ filter->priv=0;
+ filter->filter = _XkbFilterDeviceBtn;
+ filter->upAction= *pAction;
+ switch (pAction->type) {
+ case XkbSA_LockDeviceBtn:
+ if ((pAction->devbtn.flags&XkbSA_LockNoLock)||
+ BitIsOn(dev->button->down, button))
+ return 0;
+ XkbDDXFakeDeviceButton(dev,True,button);
+ filter->upAction.type= XkbSA_NoAction;
+ break;
+ case XkbSA_DeviceBtn:
+ if (pAction->devbtn.count>0) {
+ int nClicks,i;
+ nClicks= pAction->btn.count;
+ for (i=0;i<nClicks;i++) {
+ XkbDDXFakeDeviceButton(dev,True,button);
+ XkbDDXFakeDeviceButton(dev,False,button);
+ }
+ filter->upAction.type= XkbSA_NoAction;
+ }
+ else XkbDDXFakeDeviceButton(dev,True,button);
+ break;
+ }
+ }
+ else if (filter->keycode==keycode) {
+ int button;
+
+ filter->active= 0;
+ _XkbLookupButtonDevice(&dev, filter->upAction.devbtn.device,
+ serverClient, DixUnknownAccess, &button);
+ if (!dev || !dev->public.on)
+ return 1;
+
+ button= filter->upAction.btn.button;
+ switch (filter->upAction.type) {
+ case XkbSA_LockDeviceBtn:
+ if ((filter->upAction.devbtn.flags&XkbSA_LockNoUnlock)||
+ !BitIsOn(dev->button->down, button))
+ return 0;
+ XkbDDXFakeDeviceButton(dev,False,button);
+ break;
+ case XkbSA_DeviceBtn:
+ XkbDDXFakeDeviceButton(dev,False,button);
+ break;
+ }
+ filter->active = 0;
+ }
+ return 0;
+}
+
+static XkbFilterPtr
+_XkbNextFreeFilter(
+ XkbSrvInfoPtr xkbi
+)
+{
+register int i;
+
+ if (xkbi->szFilters==0) {
+ xkbi->szFilters = 4;
+ xkbi->filters = _XkbTypedCalloc(xkbi->szFilters,XkbFilterRec);
+ /* 6/21/93 (ef) -- XXX! deal with allocation failure */
+ }
+ for (i=0;i<xkbi->szFilters;i++) {
+ if (!xkbi->filters[i].active) {
+ xkbi->filters[i].keycode = 0;
+ return &xkbi->filters[i];
+ }
+ }
+ xkbi->szFilters*=2;
+ xkbi->filters= _XkbTypedRealloc(xkbi->filters,
+ xkbi->szFilters,
+ XkbFilterRec);
+ /* 6/21/93 (ef) -- XXX! deal with allocation failure */
+ bzero(&xkbi->filters[xkbi->szFilters/2],
+ (xkbi->szFilters/2)*sizeof(XkbFilterRec));
+ return &xkbi->filters[xkbi->szFilters/2];
+}
+
+static int
+_XkbApplyFilters(XkbSrvInfoPtr xkbi,unsigned kc,XkbAction *pAction)
+{
+register int i,send;
+
+ send= 1;
+ for (i=0;i<xkbi->szFilters;i++) {
+ if ((xkbi->filters[i].active)&&(xkbi->filters[i].filter))
+ send= ((*xkbi->filters[i].filter)(xkbi,&xkbi->filters[i],kc,pAction)
+ && send);
+ }
+ return send;
+}
+
+void
+XkbHandleActions(DeviceIntPtr dev, DeviceIntPtr kbd, DeviceEvent* event)
+{
+int key,bit,i;
+XkbSrvInfoPtr xkbi;
+KeyClassPtr keyc;
+int changed,sendEvent;
+Bool genStateNotify;
+XkbAction act;
+XkbFilterPtr filter;
+Bool keyEvent;
+Bool pressEvent;
+ProcessInputProc backupproc;
+
+xkbDeviceInfoPtr xkbPrivPtr = XKBDEVICEINFO(dev);
+
+ keyc= kbd->key;
+ xkbi= keyc->xkbInfo;
+ key= event->detail.key;
+ /* The state may change, so if we're not in the middle of sending a state
+ * notify, prepare for it */
+ if ((xkbi->flags&_XkbStateNotifyInProgress)==0) {
+ xkbi->prev_state = xkbi->state;
+ xkbi->flags|= _XkbStateNotifyInProgress;
+ genStateNotify= True;
+ }
+ else genStateNotify= False;
+
+ xkbi->clearMods = xkbi->setMods = 0;
+ xkbi->groupChange = 0;
+
+ sendEvent = 1;
+ keyEvent= ((event->type == ET_KeyPress) || (event->type == ET_KeyRelease));
+ pressEvent= ((event->type == ET_KeyPress)|| (event->type == ET_ButtonPress));
+
+ if (pressEvent) {
+ if (keyEvent)
+ act = XkbGetKeyAction(xkbi,&xkbi->state,key);
+ else {
+ act = XkbGetButtonAction(kbd,dev,key);
+ key|= BTN_ACT_FLAG;
+ }
+ sendEvent = _XkbApplyFilters(xkbi,key,&act);
+ if (sendEvent) {
+ switch (act.type) {
+ case XkbSA_SetMods:
+ case XkbSA_SetGroup:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent = _XkbFilterSetState(xkbi,filter,key,&act);
+ break;
+ case XkbSA_LatchMods:
+ case XkbSA_LatchGroup:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterLatchState(xkbi,filter,key,&act);
+ break;
+ case XkbSA_LockMods:
+ case XkbSA_LockGroup:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterLockState(xkbi,filter,key,&act);
+ break;
+ case XkbSA_ISOLock:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterISOLock(xkbi,filter,key,&act);
+ break;
+ case XkbSA_MovePtr:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent= _XkbFilterPointerMove(xkbi,filter,key,&act);
+ break;
+ case XkbSA_PtrBtn:
+ case XkbSA_LockPtrBtn:
+ case XkbSA_SetPtrDflt:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent= _XkbFilterPointerBtn(xkbi,filter,key,&act);
+ break;
+ case XkbSA_Terminate:
+ sendEvent= XkbDDXTerminateServer(dev,key,&act);
+ break;
+ case XkbSA_SwitchScreen:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterSwitchScreen(xkbi,filter,key,&act);
+ break;
+ case XkbSA_SetControls:
+ case XkbSA_LockControls:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterControls(xkbi,filter,key,&act);
+ break;
+ case XkbSA_ActionMessage:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent=_XkbFilterActionMessage(xkbi,filter,key,&act);
+ break;
+ case XkbSA_RedirectKey:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent= _XkbFilterRedirectKey(xkbi,filter,key,&act);
+ break;
+ case XkbSA_DeviceBtn:
+ case XkbSA_LockDeviceBtn:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent= _XkbFilterDeviceBtn(xkbi,filter,key,&act);
+ break;
+ case XkbSA_XFree86Private:
+ filter = _XkbNextFreeFilter(xkbi);
+ sendEvent= _XkbFilterXF86Private(xkbi,filter,key,&act);
+ break;
+ }
+ }
+ }
+ else {
+ if (!keyEvent)
+ key|= BTN_ACT_FLAG;
+ sendEvent = _XkbApplyFilters(xkbi,key,NULL);
+ }
+
+ if (xkbi->groupChange!=0)
+ xkbi->state.base_group+= xkbi->groupChange;
+ if (xkbi->setMods) {
+ for (i=0,bit=1; xkbi->setMods; i++,bit<<=1 ) {
+ if (xkbi->setMods&bit) {
+ keyc->modifierKeyCount[i]++;
+ xkbi->state.base_mods|= bit;
+ xkbi->setMods&= ~bit;
+ }
+ }
+ }
+ if (xkbi->clearMods) {
+ for (i=0,bit=1; xkbi->clearMods; i++,bit<<=1 ) {
+ if (xkbi->clearMods&bit) {
+ keyc->modifierKeyCount[i]--;
+ if (keyc->modifierKeyCount[i]<=0) {
+ xkbi->state.base_mods&= ~bit;
+ keyc->modifierKeyCount[i] = 0;
+ }
+ xkbi->clearMods&= ~bit;
+ }
+ }
+ }
+
+ if (sendEvent) {
+ DeviceIntPtr tmpdev;
+ if (keyEvent)
+ tmpdev = dev;
+ else
+ tmpdev = GetPairedDevice(dev);
+
+ UNWRAP_PROCESS_INPUT_PROC(tmpdev,xkbPrivPtr, backupproc);
+ dev->public.processInputProc((InternalEvent*)event, tmpdev);
+ COND_WRAP_PROCESS_INPUT_PROC(tmpdev, xkbPrivPtr,
+ backupproc,xkbUnwrapProc);
+ }
+ else if (keyEvent) {
+ FixKeyState(event, dev);
+ }
+
+ XkbComputeDerivedState(xkbi);
+ changed = XkbStateChangedFlags(&xkbi->prev_state,&xkbi->state);
+ if (genStateNotify) {
+ if (changed) {
+ xkbStateNotify sn;
+ sn.keycode= key;
+ sn.eventType= event->type;
+ sn.requestMajor = sn.requestMinor = 0;
+ sn.changed= changed;
+ XkbSendStateNotify(dev,&sn);
+ }
+ xkbi->flags&= ~_XkbStateNotifyInProgress;
+ }
+ changed= XkbIndicatorsToUpdate(dev,changed,False);
+ if (changed) {
+ XkbEventCauseRec cause;
+ XkbSetCauseKey(&cause, key, event->type);
+ XkbUpdateIndicators(dev,changed,False,NULL,&cause);
+ }
+ return;
+}
+
+int
+XkbLatchModifiers(DeviceIntPtr pXDev,CARD8 mask,CARD8 latches)
+{
+XkbSrvInfoPtr xkbi;
+XkbFilterPtr filter;
+XkbAction act;
+unsigned clear;
+
+ if ( pXDev && pXDev->key && pXDev->key->xkbInfo ) {
+ xkbi = pXDev->key->xkbInfo;
+ clear= (mask&(~latches));
+ xkbi->state.latched_mods&= ~clear;
+ /* Clear any pending latch to locks.
+ */
+ act.type = XkbSA_NoAction;
+ _XkbApplyFilters(xkbi,SYNTHETIC_KEYCODE,&act);
+ act.type = XkbSA_LatchMods;
+ act.mods.flags = 0;
+ act.mods.mask = mask&latches;
+ filter = _XkbNextFreeFilter(xkbi);
+ _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,&act);
+ _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,(XkbAction *)NULL);
+ return Success;
+ }
+ return BadValue;
+}
+
+int
+XkbLatchGroup(DeviceIntPtr pXDev,int group)
+{
+XkbSrvInfoPtr xkbi;
+XkbFilterPtr filter;
+XkbAction act;
+
+ if ( pXDev && pXDev->key && pXDev->key->xkbInfo ) {
+ xkbi = pXDev->key->xkbInfo;
+ act.type = XkbSA_LatchGroup;
+ act.group.flags = 0;
+ XkbSASetGroup(&act.group,group);
+ filter = _XkbNextFreeFilter(xkbi);
+ _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,&act);
+ _XkbFilterLatchState(xkbi,filter,SYNTHETIC_KEYCODE,(XkbAction *)NULL);
+ return Success;
+ }
+ return BadValue;
+}
+
+/***====================================================================***/
+
+void
+XkbClearAllLatchesAndLocks( DeviceIntPtr dev,
+ XkbSrvInfoPtr xkbi,
+ Bool genEv,
+ XkbEventCausePtr cause)
+{
+XkbStateRec os;
+xkbStateNotify sn;
+
+ sn.changed= 0;
+ os= xkbi->state;
+ if (os.latched_mods) { /* clear all latches */
+ XkbLatchModifiers(dev,~0,0);
+ sn.changed|= XkbModifierLatchMask;
+ }
+ if (os.latched_group) {
+ XkbLatchGroup(dev,0);
+ sn.changed|= XkbGroupLatchMask;
+ }
+ if (os.locked_mods) {
+ xkbi->state.locked_mods= 0;
+ sn.changed|= XkbModifierLockMask;
+ }
+ if (os.locked_group) {
+ xkbi->state.locked_group= 0;
+ sn.changed|= XkbGroupLockMask;
+ }
+ if ( genEv && sn.changed) {
+ CARD32 changed;
+
+ XkbComputeDerivedState(xkbi);
+ sn.keycode= cause->kc;
+ sn.eventType= cause->event;
+ sn.requestMajor= cause->mjr;
+ sn.requestMinor= cause->mnr;
+ sn.changed= XkbStateChangedFlags(&os,&xkbi->state);
+ XkbSendStateNotify(dev,&sn);
+ changed= XkbIndicatorsToUpdate(dev,sn.changed,False);
+ if (changed) {
+ XkbUpdateIndicators(dev,changed,True,NULL,cause);
+ }
+ }
+ return;
+}
+
diff --git a/xorg-server/xkb/xkbInit.c b/xorg-server/xkb/xkbInit.c index 747c913f3..7e0a8a90a 100644 --- a/xorg-server/xkb/xkbInit.c +++ b/xorg-server/xkb/xkbInit.c @@ -89,8 +89,8 @@ typedef struct _SrvXkmInfo { #define XKB_DFLT_RULES_PROP True #endif -char * XkbBaseDirectory= XKB_BASE_DIRECTORY; -char * XkbBinDirectory= XKB_BIN_DIRECTORY; +const char * XkbBaseDirectory= XKB_BASE_DIRECTORY; +const char * XkbBinDirectory= XKB_BIN_DIRECTORY; static int XkbWantAccessX= 0; static char * XkbRulesDflt= NULL; diff --git a/xorg-server/xkbdata.src/compat/default b/xorg-server/xkbdata.src/compat/default.in index 5355e1318..5355e1318 100644 --- a/xorg-server/xkbdata.src/compat/default +++ b/xorg-server/xkbdata.src/compat/default.in diff --git a/xorg-server/xkbdata.src/compat/makefile b/xorg-server/xkbdata.src/compat/makefile new file mode 100644 index 000000000..486ca5541 --- /dev/null +++ b/xorg-server/xkbdata.src/compat/makefile @@ -0,0 +1,20 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=compat + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +dist_xkbdata_compat_DATA = \ +accessx basic complete \ +default iso9995 \ +japan keypad ledcaps \ +lednum ledscroll level5 \ +misc mousekeys norepeat \ +olpc pc pc98 xfree86 \ +xtest README + +DATA_FILES=$(dist_xkbdata_compat_DATA:%=$(DESTDIR)\%) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/geometry/digital_vndr/makefile b/xorg-server/xkbdata.src/geometry/digital_vndr/makefile new file mode 100644 index 000000000..12d4c37fc --- /dev/null +++ b/xorg-server/xkbdata.src/geometry/digital_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\geometry\digital_vndr + +dist_geom_DATA = \ +lk pc unix + +DATA_FILES=$(dist_geom_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/geometry/makefile b/xorg-server/xkbdata.src/geometry/makefile new file mode 100644 index 000000000..a0664ee89 --- /dev/null +++ b/xorg-server/xkbdata.src/geometry/makefile @@ -0,0 +1,25 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=geometry + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +dist_xkbdata_geometry_DATA = \ +amiga ataritt chicony \ +dell everex fujitsu \ +hhk hp keytronic kinesis \ +macintosh microsoft nec \ +northgate pc sony thinkpad \ +sun winbook README + +DATA_FILES=$(dist_xkbdata_geometry_DATA:%=$(DESTDIR)\%) + +SUBDIRS = digital_vndr sgi_vndr + +load_makefile $(SUBDIRS:%=%\makefile MAKESERVER=0 DEBUG=$(DEBUG);) + +extrastuff: $(SUBDIRS:%=%\all) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/geometry/sgi_vndr/makefile b/xorg-server/xkbdata.src/geometry/sgi_vndr/makefile new file mode 100644 index 000000000..285067802 --- /dev/null +++ b/xorg-server/xkbdata.src/geometry/sgi_vndr/makefile @@ -0,0 +1,13 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\geometry\sgi_vndr + + +dist_geom_DATA = \ +indigo indy O2 + +DATA_FILES=$(dist_geom_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keycodes/digital_vndr/makefile b/xorg-server/xkbdata.src/keycodes/digital_vndr/makefile new file mode 100644 index 000000000..9cf1180e5 --- /dev/null +++ b/xorg-server/xkbdata.src/keycodes/digital_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\keycodes\digital_vndr + +dist_keycodes_DATA = \ +lk pc + +DATA_FILES=$(dist_keycodes_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keycodes/makefile b/xorg-server/xkbdata.src/keycodes/makefile new file mode 100644 index 000000000..cdc1dde71 --- /dev/null +++ b/xorg-server/xkbdata.src/keycodes/makefile @@ -0,0 +1,32 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=keycodes + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +SUBDIRS = digital_vndr sgi_vndr + +dist_xkbdata_keycodes_DATA = \ + aliases \ + amiga \ + ataritt \ + evdev \ + fujitsu \ + hp \ + ibm \ + macintosh \ + sony \ + sun \ + xfree86 \ + xfree98 \ + README + +DATA_FILES=$(dist_xkbdata_keycodes_DATA:%=$(DESTDIR)\%) + +load_makefile $(SUBDIRS:%=%\makefile MAKESERVER=0 DEBUG=$(DEBUG);) + +extrastuff: $(SUBDIRS:%=%\all) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keycodes/sgi_vndr/makefile b/xorg-server/xkbdata.src/keycodes/sgi_vndr/makefile new file mode 100644 index 000000000..e6c1defda --- /dev/null +++ b/xorg-server/xkbdata.src/keycodes/sgi_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\keycodes\sgi_vndr + +dist_keycodes_DATA = \ +indigo indy iris + +DATA_FILES=$(dist_keycodes_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keymap/digital_vndr/makefile b/xorg-server/xkbdata.src/keymap/digital_vndr/makefile new file mode 100644 index 000000000..09dd6f797 --- /dev/null +++ b/xorg-server/xkbdata.src/keymap/digital_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\keymap\digital_vndr + +dist_keymap_DATA = \ +us + +DATA_FILES=$(dist_keymap_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keymap/makefile b/xorg-server/xkbdata.src/keymap/makefile new file mode 100644 index 000000000..1b549a08f --- /dev/null +++ b/xorg-server/xkbdata.src/keymap/makefile @@ -0,0 +1,22 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=keymap + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +SUBDIRS = digital_vndr sgi_vndr sun_vndr + +dist_xkbdata_keymap_DATA = \ +amiga ataritt macintosh \ +sony xfree86 xfree98 \ +README + +DATA_FILES=$(dist_xkbdata_keymap_DATA:%=$(DESTDIR)\%) + +load_makefile $(SUBDIRS:%=%\makefile MAKESERVER=0 DEBUG=$(DEBUG);) + +extrastuff: $(SUBDIRS:%=%\all) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keymap/sgi_vndr/makefile b/xorg-server/xkbdata.src/keymap/sgi_vndr/makefile new file mode 100644 index 000000000..d2cb6083e --- /dev/null +++ b/xorg-server/xkbdata.src/keymap/sgi_vndr/makefile @@ -0,0 +1,20 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\keymap\sgi_vndr + +dist_keymap_DATA = \ +be bg ca \ +ch cz de \ +dk dvorak \ +es fi \ +fr gb \ +hu it jp \ +no pl pt \ +ru se sk \ +th us + +DATA_FILES=$(dist_keymap_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/keymap/sun_vndr/all b/xorg-server/xkbdata.src/keymap/sun_vndr/all.in index 047ae7bc4..047ae7bc4 100644 --- a/xorg-server/xkbdata.src/keymap/sun_vndr/all +++ b/xorg-server/xkbdata.src/keymap/sun_vndr/all.in diff --git a/xorg-server/xkbdata.src/keymap/sun_vndr/makefile b/xorg-server/xkbdata.src/keymap/sun_vndr/makefile new file mode 100644 index 000000000..1dd8b4c45 --- /dev/null +++ b/xorg-server/xkbdata.src/keymap/sun_vndr/makefile @@ -0,0 +1,20 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\keymap\sun_vndr + +dist_keymap_DATA = \ +all de es fi \ +fr no pl \ +ru se uk \ +us + +DATA_FILES=$(dist_keymap_DATA:%=$(DESTDIR)\%) + +# We need to make the rule for all explicit since searching it in the implicit rules doesn't work for all +$(DESTDIR)\all: all.in + copy $< $@ + + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/makefile b/xorg-server/xkbdata.src/makefile new file mode 100644 index 000000000..94c550947 --- /dev/null +++ b/xorg-server/xkbdata.src/makefile @@ -0,0 +1,9 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +SUBDIRS = compat geometry keycodes keymap rules semantics symbols types + +load_makefile $(SUBDIRS:%=%\makefile MAKESERVER=0 DEBUG=$(DEBUG);) + +all: $(SUBDIRS:%=%\all) diff --git a/xorg-server/xkbdata.src/rules/bin/ln_s.sh b/xorg-server/xkbdata.src/rules/bin/ln_s.sh index 07ac2f087..78e557d8f 100644 --- a/xorg-server/xkbdata.src/rules/bin/ln_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/ln_s.sh @@ -1,20 +1,10 @@ -#!/bin/sh +@echo off +set variant=%1 -variant=$1 +set OUTFILE=base.l%variant%_s.part -INDIR=$2 -OUTFILE=base.l${variant}_s.part +if exist %OUTFILE% del %OUTFILE% -> $OUTFILE +gawk "{ if (index($2, """(""") == 0) { printf """ %%s = +%%s%%%%(v[%variant%]):%variant%\n""", $1, $2; } else { printf """ %%s = +%%s:%variant%\n""", $1, $2; }}" < layoutsMapping.lst >> %OUTFILE% -awk '{ - if (index($2, "(") == 0) { - printf " %s = +%s%%(v['${variant}']):'${variant}'\n", $1, $2; - } else { - printf " %s = +%s:'${variant}'\n", $1, $2; - } -}' < $INDIR/layoutsMapping.lst >> $OUTFILE - -awk '{ - printf " %s(%s) = +%s(%s):'${variant}'\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ %%s(%%s) = +%%s(%%s):%variant%\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/lnv_s.sh b/xorg-server/xkbdata.src/rules/bin/lnv_s.sh index fc0d42020..6bbf285e7 100644 --- a/xorg-server/xkbdata.src/rules/bin/lnv_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/lnv_s.sh @@ -1,12 +1,8 @@ -#!/bin/sh +@echo off +set variant=%1 -variant=$1 +set OUTFILE=base.l%variant%v%variant%_s.part -INDIR=$2 -OUTFILE=base.l${variant}v${variant}_s.part +if exist %OUTFILE% del %OUTFILE% -> $OUTFILE - -awk '{ - printf " %s %s = +%s(%s):'${variant}'\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ %%s %%s = +%%s(%%s):%variant%\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/ml1_s.sh b/xorg-server/xkbdata.src/rules/bin/ml1_s.sh index b2d222432..b09459a5d 100644 --- a/xorg-server/xkbdata.src/rules/bin/ml1_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/ml1_s.sh @@ -1,18 +1,9 @@ -#!/bin/sh +@echo off -INDIR=$1 -OUTFILE=base.ml1_s.part +set OUTFILE=base.ml1_s.part -> $OUTFILE +if exist %OUTFILE% del %OUTFILE% -awk '{ - if (index($2, "(") == 0) { - printf " * %s = pc+%s%%(v[1])\n", $1, $2; - } else { - printf " * %s = pc+%s\n", $1, $2; - } -}' < $INDIR/layoutsMapping.lst >> $OUTFILE +gawk "{ if (index($2, """(""") == 0) { printf """ * %%s = pc+%%s%%%%(v[1])\n""", $1, $2; } else { printf """ * %%s = pc+%%s\n""", $1, $2; }}" < layoutsMapping.lst >> %OUTFILE% -awk '{ - printf " * %s(%s) = pc+%s(%s)\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s(%%s) = pc+%%s(%%s)\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/ml1v1_s.sh b/xorg-server/xkbdata.src/rules/bin/ml1v1_s.sh index 7c2b1a84c..4d492e02b 100644 --- a/xorg-server/xkbdata.src/rules/bin/ml1v1_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/ml1v1_s.sh @@ -1,10 +1,7 @@ -#!/bin/sh +@echo off -INDIR=$1 -OUTFILE=base.ml1v1_s.part +set OUTFILE=base.ml1v1_s.part -> $OUTFILE +if exist %OUTFILE% del %OUTFILE% -awk '{ - printf " * %s %s = pc+%s(%s)\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s %%s = pc+%%s(%%s)\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/ml1v_s.sh b/xorg-server/xkbdata.src/rules/bin/ml1v_s.sh index 084d4c0be..cec1334c0 100644 --- a/xorg-server/xkbdata.src/rules/bin/ml1v_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/ml1v_s.sh @@ -1,10 +1,7 @@ -#!/bin/sh +@echo off -INDIR=$1 -OUTFILE=base.ml1v_s.part +set OUTFILE=base.ml1v_s.part -> $OUTFILE +if exist %OUTFILE% del %OUTFILE% -awk '{ - printf " * %s %s = pc+%s(%s)\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s %%s = pc+%%s(%%s)\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/ml_s.sh b/xorg-server/xkbdata.src/rules/bin/ml_s.sh index 666ba870f..b7f0d9c46 100644 --- a/xorg-server/xkbdata.src/rules/bin/ml_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/ml_s.sh @@ -1,14 +1,9 @@ -#!/bin/sh +@echo off -INDIR=$1 -OUTFILE=base.ml_s.part +set OUTFILE=base.ml_s.part -> $OUTFILE +if exist %OUTFILE% del %OUTFILE% -awk '{ - printf " * %s = pc+%s\n", $1, $2; -}' < $INDIR/layoutsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s = pc+%%s\n""", $1, $2; }" < layoutsMapping.lst >> %OUTFILE% -awk '{ - printf " * %s(%s) = pc+%s(%s)\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s(%%s) = pc+%%s(%%s)\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/bin/mlv_s.sh b/xorg-server/xkbdata.src/rules/bin/mlv_s.sh index 5b466d59c..573cb930f 100644 --- a/xorg-server/xkbdata.src/rules/bin/mlv_s.sh +++ b/xorg-server/xkbdata.src/rules/bin/mlv_s.sh @@ -1,10 +1,7 @@ -#!/bin/sh +@echo off -INDIR=$1 -OUTFILE=base.mlv_s.part +set OUTFILE=base.mlv_s.part -> $OUTFILE +if exist %OUTFILE% del %OUTFILE% -awk '{ - printf " * %s %s = pc+%s(%s)\n", $1, $2, $3, $4; -}' < $INDIR/variantsMapping.lst >> $OUTFILE +gawk "{ printf """ * %%s %%s = pc+%%s(%%s)\n""", $1, $2, $3, $4; }" < variantsMapping.lst >> %OUTFILE% diff --git a/xorg-server/xkbdata.src/rules/compat/makefile b/xorg-server/xkbdata.src/rules/compat/makefile new file mode 100644 index 000000000..4a1a7b832 --- /dev/null +++ b/xorg-server/xkbdata.src/rules/compat/makefile @@ -0,0 +1,53 @@ +TRANSFORM_FILES=layoutsMapping.lst variantsMapping.lst + +scripts_dir=..\bin + +SCRIPTS= \ +base.l2_s.part \ +base.l3_s.part \ +base.l4_s.part \ +base.l2v2_s.part \ +base.l3v3_s.part \ +base.l4v4_s.part \ +base.ml_s.part \ +base.ml1_s.part \ +base.mlv_s.part \ +base.ml1v1_s.part \ +base.ml_s.part + +SH=cmd /c + +%.bat: $(scripts_dir)\%.sh + copy $< $@ + +base.l2_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 2 + +base.l3_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 3 + +base.l4_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 4 + +base.l2v2_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 2 + +base.l3v3_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 3 + +base.l4v4_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 4 + +base.ml_s.part: ml_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.ml1_s.part: ml1_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.mlv_s.part: mlv_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.ml1v1_s.part: ml1v1_s.bat $(TRANSFORM_FILES) + $(SH) $< + +all: $(SCRIPTS) diff --git a/xorg-server/xkbdata.src/rules/extras/makefile b/xorg-server/xkbdata.src/rules/extras/makefile new file mode 100644 index 000000000..f5753f674 --- /dev/null +++ b/xorg-server/xkbdata.src/rules/extras/makefile @@ -0,0 +1,53 @@ +TRANSFORM_FILES=layoutsMapping.lst variantsMapping.lst + +scripts_dir=..\bin + +SCRIPTS= \ +base.l2_s.part \ +base.l3_s.part \ +base.l4_s.part \ +base.l2v2_s.part \ +base.l3v3_s.part \ +base.l4v4_s.part \ +base.ml_s.part \ +base.ml1_s.part \ +base.mlv_s.part \ +base.ml1v1_s.part \ +base.ml_s.part + +SH=cmd /c + +%.bat: $(scripts_dir)\%.sh + copy $< $@ + +base.l2_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 2 + +base.l3_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 3 + +base.l4_s.part: ln_s.bat $(TRANSFORM_FILES) + $(SH) $< 4 + +base.l2v2_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 2 + +base.l3v3_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 3 + +base.l4v4_s.part: lnv_s.bat $(TRANSFORM_FILES) + $(SH) $< 4 + +base.ml_s.part: ml_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.ml1_s.part: ml1_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.mlv_s.part: mlv_s.bat $(TRANSFORM_FILES) + $(SH) $< + +base.ml1v1_s.part: ml1v1_s.bat $(TRANSFORM_FILES) + $(SH) $< + +all=$(SCRIPTS) diff --git a/xorg-server/xkbdata.src/rules/makefile b/xorg-server/xkbdata.src/rules/makefile new file mode 100644 index 000000000..65cd8378e --- /dev/null +++ b/xorg-server/xkbdata.src/rules/makefile @@ -0,0 +1,166 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +load_makefile compat\makefile DEBUG=$(DEBUG) +load_makefile extras\makefile DEBUG=$(DEBUG) + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\rules + +BASE_PARTS_NO_COMPAT = base.hdr.part base.lists.part \ +compat/base.lists.part \ +HDR base.m_k.part \ +HDR base.l1_k.part \ +HDR base.l_k.part \ +HDR base.o_k.part \ +HDR base.ml_g.part \ +HDR base.m_g.part \ +HDR compat/base.mlv_s.part extras/base.mlv_s.part base.mlv_s.part \ +HDR compat/base.ml_s.part extras/base.ml_s.part base.ml_s.part \ +HDR compat/base.ml1_s.part extras/base.ml1_s.part base.ml1_s.part \ +HDR compat/base.ml1v1_s.part extras/base.ml1v1_s.part \ +HDR compat/base.l2_s.part extras/base.l2_s.part base.l2_s.part \ +HDR compat/base.l3_s.part extras/base.l3_s.part base.l3_s.part \ +HDR compat/base.l4_s.part extras/base.l4_s.part base.l4_s.part \ +HDR compat/base.l2v2_s.part extras/base.l2v2_s.part \ +HDR compat/base.l3v3_s.part extras/base.l3v3_s.part \ +HDR compat/base.l4v4_s.part extras/base.l4v4_s.part \ +HDR base.m_s.part \ +HDR base.ml_c.part \ +HDR base.ml1_c.part \ +HDR base.m_t.part \ +HDR base.lo_s.part \ +HDR base.l1o_s.part \ +HDR base.l2o_s.part \ +HDR base.l3o_s.part \ +HDR base.l4o_s.part \ +HDR compat/base.o_s.part base.o_s.part \ +HDR base.o_c.part \ +HDR base.o_t.part + +EVDEV_PARTS_NO_COMPAT = base.hdr.part base.lists.part \ +compat/base.lists.part \ +HDR evdev.m_k.part \ +HDR base.l1_k.part \ +HDR base.l_k.part \ +HDR base.o_k.part \ +HDR base.ml_g.part \ +HDR base.m_g.part \ +HDR compat/base.mlv_s.part extras/base.mlv_s.part base.mlv_s.part \ +HDR compat/base.ml_s.part extras/base.ml_s.part base.ml_s.part \ +HDR compat/base.ml1_s.part extras/base.ml1_s.part base.ml1_s.part \ +HDR compat/base.ml1v1_s.part extras/base.ml1v1_s.part \ +HDR compat/base.l2_s.part extras/base.l2_s.part base.l2_s.part \ +HDR compat/base.l3_s.part extras/base.l3_s.part base.l3_s.part \ +HDR compat/base.l4_s.part extras/base.l4_s.part base.l4_s.part \ +HDR compat/base.l2v2_s.part extras/base.l2v2_s.part \ +HDR compat/base.l3v3_s.part extras/base.l3v3_s.part \ +HDR compat/base.l4v4_s.part extras/base.l4v4_s.part \ +HDR evdev.m_s.part \ +HDR base.ml_c.part \ +HDR base.ml1_c.part \ +HDR base.m_t.part \ +HDR base.lo_s.part \ +HDR base.l1o_s.part \ +HDR base.l2o_s.part \ +HDR base.l3o_s.part \ +HDR base.l4o_s.part \ +HDR compat/base.o_s.part base.o_s.part \ +HDR base.o_c.part \ +HDR base.o_t.part + +BASE_PARTS = base.hdr.part base.lists.part \ +HDR base.m_k.part \ +HDR base.l1_k.part \ +HDR base.l_k.part \ +HDR \ +HDR base.ml_g.part \ +HDR base.m_g.part \ +HDR extras/base.mlv_s.part base.mlv_s.part \ +HDR extras/base.ml_s.part base.ml_s.part \ +HDR extras/base.ml1_s.part base.ml1_s.part \ +HDR extras/base.ml1v1_s.part \ +HDR extras/base.l2_s.part base.l2_s.part \ +HDR extras/base.l3_s.part base.l3_s.part \ +HDR extras/base.l4_s.part base.l4_s.part \ +HDR extras/base.l2v2_s.part \ +HDR extras/base.l3v3_s.part \ +HDR extras/base.l4v4_s.part \ +HDR base.m_s.part \ +HDR base.ml_c.part \ +HDR base.ml1_c.part \ +HDR base.m_t.part \ +HDR \ +HDR base.l1o_s.part \ +HDR base.l2o_s.part \ +HDR base.l3o_s.part \ +HDR base.l4o_s.part \ +HDR base.o_s.part \ +HDR base.o_c.part \ +HDR base.o_t.part + +EVDEV_PARTS = base.hdr.part base.lists.part \ +HDR evdev.m_k.part \ +HDR base.l1_k.part \ +HDR base.l_k.part \ +HDR \ +HDR base.ml_g.part \ +HDR base.m_g.part \ +HDR extras/base.mlv_s.part base.mlv_s.part \ +HDR extras/base.ml_s.part base.ml_s.part \ +HDR extras/base.ml1_s.part base.ml1_s.part \ +HDR extras/base.ml1v1_s.part \ +HDR extras/base.l2_s.part base.l2_s.part \ +HDR extras/base.l3_s.part base.l3_s.part \ +HDR extras/base.l4_s.part base.l4_s.part \ +HDR extras/base.l2v2_s.part \ +HDR extras/base.l3v3_s.part \ +HDR extras/base.l4v4_s.part \ +HDR evdev.m_s.part \ +HDR base.ml_c.part \ +HDR base.ml1_c.part \ +HDR base.m_t.part \ +HDR \ +HDR base.l1o_s.part \ +HDR base.l2o_s.part \ +HDR base.l3o_s.part \ +HDR base.l4o_s.part \ +HDR base.o_s.part \ +HDR base.o_c.part \ +HDR base.o_t.part + +RULES_FILES = base evdev xfree98 + +LST_FILES = base.lst evdev.lst + +$(DESTDIR)\%.lst: $(DESTDIR)\%.xml + perl xml2lst.pl < $< > $@ + +$(DESTDIR)\base: compat\all $(BASE_PARTS_NO_COMPAT) + merge $@ $(BASE_PARTS) + +$(DESTDIR)\evdev: compat\all $(EVDEV_PARTS_NO_COMPAT) + merge $@ $(EVDEV_PARTS) + +ALL_RULES_FILES = $(RULES_FILES) $(LST_FILES) \ +xkb.dtd README + +COMPATFILES=xorg xorg.xml xorg.lst +$(DESTDIR)\xorg: $(DESTDIR)\base + copy $< $@ +$(DESTDIR)\xorg%: $(DESTDIR)\base% + copy $< $@ + +rules_DATA = $(ALL_RULES_FILES) $(COMPATFILES) + +XML_IN_FILES = base.xml.in evdev.xml.in base.extras.xml.in evdev.extras.xml.in +xml_DATA = $(XML_IN_FILES:%.xml.in=%.xml) + +$(DESTDIR)\%.xml: %.xml.in + copy $< $@ + + + +DATA_FILES=$(rules_DATA:%=$(DESTDIR)\%) $(xml_DATA:%=$(DESTDIR)\%) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/rules/merge.py b/xorg-server/xkbdata.src/rules/merge.py new file mode 100644 index 000000000..442a866f2 --- /dev/null +++ b/xorg-server/xkbdata.src/rules/merge.py @@ -0,0 +1,13 @@ +import sys + +pOUT=open(sys.argv[1],"wb") +pHDR=open("HDR","r") +for item in sys.argv[2:]: + if item == 'HDR': + pOUT.write("\n") + pOUT.write(pHDR.readline()) + else: + pOUT.write(open(item,"rb").read()) + +pOUT.close() + diff --git a/xorg-server/xkbdata.src/semantics/default b/xorg-server/xkbdata.src/semantics/default.in index 42e755e3c..42e755e3c 100644 --- a/xorg-server/xkbdata.src/semantics/default +++ b/xorg-server/xkbdata.src/semantics/default.in diff --git a/xorg-server/xkbdata.src/semantics/makefile b/xorg-server/xkbdata.src/semantics/makefile new file mode 100644 index 000000000..0181c169f --- /dev/null +++ b/xorg-server/xkbdata.src/semantics/makefile @@ -0,0 +1,17 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=semantics + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +dist_xkbdata_semantics_DATA = \ + basic \ + complete \ + default \ + xtest + +DATA_FILES=$(dist_xkbdata_semantics_DATA:%=$(DESTDIR)\%) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/digital_vndr/makefile b/xorg-server/xkbdata.src/symbols/digital_vndr/makefile new file mode 100644 index 000000000..cdfa2ef28 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/digital_vndr/makefile @@ -0,0 +1,13 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\digital_vndr + +dist_symbols_DATA = \ +lk pc us \ +vt + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/fujitsu_vndr/makefile b/xorg-server/xkbdata.src/symbols/fujitsu_vndr/makefile new file mode 100644 index 000000000..841c123d8 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/fujitsu_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\fujitsu_vndr + +dist_symbols_DATA = \ +jp us + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/hp_vndr/makefile b/xorg-server/xkbdata.src/symbols/hp_vndr/makefile new file mode 100644 index 000000000..3e6a64f47 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/hp_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\hp_vndr + +dist_symbols_DATA = \ +us + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/level3 b/xorg-server/xkbdata.src/symbols/level3 index 79fdcea03..a52708e2e 100644 --- a/xorg-server/xkbdata.src/symbols/level3 +++ b/xorg-server/xkbdata.src/symbols/level3 @@ -11,7 +11,7 @@ default partial modifier_keys xkb_symbols "ralt_switch" { key <RALT> { - type[Group1]="ONE_LEVEL", + type[Group1]="TWO_LEVEL", symbols[Group1] = [ ISO_Level3_Shift ] }; modifier_map Mod5 { ISO_Level3_Shift }; diff --git a/xorg-server/xkbdata.src/symbols/macintosh_vndr/makefile b/xorg-server/xkbdata.src/symbols/macintosh_vndr/makefile new file mode 100644 index 000000000..542b7a665 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/macintosh_vndr/makefile @@ -0,0 +1,16 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\macintosh_vndr + +dist_symbols_DATA = \ +apple ch de dk \ +es fi fr \ +gb is it \ +latam nl no pt \ +se us + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/makefile b/xorg-server/xkbdata.src/symbols/makefile new file mode 100644 index 000000000..fdb281ab7 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/makefile @@ -0,0 +1,49 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=symbols + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +SUBDIRS = digital_vndr fujitsu_vndr hp_vndr macintosh_vndr nec_vndr sgi_vndr sony_vndr sun_vndr xfree68_vndr + +dist_xkbdata_symbols_DATA = \ +ad af al \ +am ara az \ +be bd \ +bg br ba \ +bt by brai \ +ca cd \ +ch cn cz \ +de dk \ +ee es et epo \ +fi fo fr \ +gb ge gh gn \ +gr hr hu \ +ie il in iq \ +ir is it jp \ +kg kh kr kz \ +la latam latin \ +lk lt lv \ +ma mao me mk \ +mm mn mt mv \ +ng nl no np \ +pc pk pl pt \ +ro rs ru \ +se si sk sn \ +sy th \ +terminate \ +tj tm tr \ +ua us uz vn \ +za \ +altwin capslock compose ctrl eurosign group inet \ +keypad kpdl level3 level5 nbsp olpc shift srvr_ctrl typo + +DATA_FILES=$(dist_xkbdata_symbols_DATA:%=$(DESTDIR)\%) + +load_makefile $(SUBDIRS:%=%\makefile MAKESERVER=0 DEBUG=$(DEBUG);) + +extrastuff: $(SUBDIRS:%=%\all) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/nec_vndr/makefile b/xorg-server/xkbdata.src/symbols/nec_vndr/makefile new file mode 100644 index 000000000..6ab523a2b --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/nec_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\nec_vndr + +dist_symbols_DATA = \ +jp + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/sgi_vndr/makefile b/xorg-server/xkbdata.src/symbols/sgi_vndr/makefile new file mode 100644 index 000000000..79a27fead --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/sgi_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\sgi_vndr + +dist_symbols_DATA = \ +jp + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/sony_vndr/makefile b/xorg-server/xkbdata.src/symbols/sony_vndr/makefile new file mode 100644 index 000000000..c2c1fa757 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/sony_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\sony_vndr + +dist_symbols_DATA = \ +us + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/sun_vndr/makefile b/xorg-server/xkbdata.src/symbols/sun_vndr/makefile new file mode 100644 index 000000000..5741501b3 --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/sun_vndr/makefile @@ -0,0 +1,17 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\sun_vndr + +dist_symbols_DATA = \ + cs cz de dk es \ + fi fr gb gr hu \ + it jp ko lt lv \ + nl no pl pt ru \ + se solaris sw tr tuv \ + tw us usb + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/symbols/xfree68_vndr/makefile b/xorg-server/xkbdata.src/symbols/xfree68_vndr/makefile new file mode 100644 index 000000000..c9c1b3ede --- /dev/null +++ b/xorg-server/xkbdata.src/symbols/xfree68_vndr/makefile @@ -0,0 +1,12 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\symbols\xfree68_vndr + +dist_symbols_DATA = \ +amiga ataritt + +DATA_FILES=$(dist_symbols_DATA:%=$(DESTDIR)\%) + +include ..\..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/types/default b/xorg-server/xkbdata.src/types/default.in index 18859b742..18859b742 100644 --- a/xorg-server/xkbdata.src/types/default +++ b/xorg-server/xkbdata.src/types/default.in diff --git a/xorg-server/xkbdata.src/types/makefile b/xorg-server/xkbdata.src/types/makefile new file mode 100644 index 000000000..cef304543 --- /dev/null +++ b/xorg-server/xkbdata.src/types/makefile @@ -0,0 +1,25 @@ +ifeq ($(MAKESERVER),1) +$(error Please do not specify MAKESERVER=1) +endif + +THISDIR=types + +DESTDIR=$(MHMAKECONF)\xorg-server\xkbdata\$(THISDIR) + +dist_xkbdata_types_DATA = \ + basic \ + cancel \ + caps \ + complete \ + default \ + extra \ + iso9995 \ + mousekeys \ + numpad \ + level5 \ + pc \ + README + +DATA_FILES=$(dist_xkbdata_types_DATA:%=$(DESTDIR)\%) + +include ..\xkbrules.mak diff --git a/xorg-server/xkbdata.src/xkbrules.mak b/xorg-server/xkbdata.src/xkbrules.mak new file mode 100644 index 000000000..3b5480e46 --- /dev/null +++ b/xorg-server/xkbdata.src/xkbrules.mak @@ -0,0 +1,16 @@ +DIRFILE=$(THISDIR:%=$(DESTDIR)\..\%.dir) +all: $(DESTDIR) $(DATA_FILES) $(DIRFILE) + +$(DESTDIR)\default: default.in + copy $< $@ + +$(DESTDIR)\%: % + copy $< $@ + +ifneq ($(DIRFILE),) +.PHONY: extrastuff + +$(DIRFILE): extrastuff $(DATA_FILES) + -del -e $@ + cd $(DESTDIR) & ..\..\xkbcomp.exe -lfhlpR -o $(relpath $@) * +endif |