diff options
Diffstat (limited to 'xorg-server/hw')
-rw-r--r-- | xorg-server/hw/dmx/input/dmxevents.c | 1600 | ||||
-rw-r--r-- | xorg-server/hw/kdrive/src/kinput.c | 4 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Configure.c | 1517 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Events.c | 2 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/common/xf86Xinput.c | 15 | ||||
-rw-r--r-- | xorg-server/hw/xfree86/os-support/linux/lnx_init.c | 675 | ||||
-rw-r--r-- | xorg-server/hw/xnest/Events.c | 466 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/X11Application.m | 78 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/darwin.c | 3 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/darwin.h | 1 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/darwinEvents.c | 50 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/darwinEvents.h | 3 | ||||
-rw-r--r-- | xorg-server/hw/xquartz/mach-startup/bundle-main.c | 1389 | ||||
-rw-r--r-- | xorg-server/hw/xwin/winkeybd.c | 1062 |
14 files changed, 3467 insertions, 3398 deletions
diff --git a/xorg-server/hw/dmx/input/dmxevents.c b/xorg-server/hw/dmx/input/dmxevents.c index efcd07da3..15d80f5bb 100644 --- a/xorg-server/hw/dmx/input/dmxevents.c +++ b/xorg-server/hw/dmx/input/dmxevents.c @@ -1,800 +1,800 @@ -/*
- * Copyright 2002-2003 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:
- * Rickard E. (Rik) Faith <faith@redhat.com>
- *
- */
-
-/** \file
- * Provide support and helper functions for enqueing events received by
- * the low-level input drivers. */
-
-#ifdef HAVE_DMX_CONFIG_H
-#include <dmx-config.h>
-#endif
-
-#define DMX_EVENTS_DEBUG 0
-
-#include "dmxinputinit.h"
-#include "dmxevents.h"
-#include "dmxcb.h"
-#include "dmxcommon.h"
-#include "dmxcursor.h"
-#include "dmxmotion.h"
-#include "dmxsigio.h"
-#include "dmxmap.h"
-
-#include <X11/keysym.h>
-#include "opaque.h"
-#include "inputstr.h"
-#include "inpututils.h"
-#include "mipointer.h"
-#include "mi.h"
-#include "exglobals.h"
-
-#include "xkbsrv.h"
-#include "XIstubs.h"
-
-static int dmxGlobalX, dmxGlobalY; /* Global cursor position */
-static int dmxGlobalInvalid; /* Flag indicating dmxCoreMotion
- * should move the mouse anyway. */
-
-#if DMX_EVENTS_DEBUG
-#define DMXDBG0(f) dmxLog(dmxDebug,f)
-#define DMXDBG1(f,a) dmxLog(dmxDebug,f,a)
-#define DMXDBG2(f,a,b) dmxLog(dmxDebug,f,a,b)
-#define DMXDBG3(f,a,b,c) dmxLog(dmxDebug,f,a,b,c)
-#define DMXDBG4(f,a,b,c,d) dmxLog(dmxDebug,f,a,b,c,d)
-#define DMXDBG5(f,a,b,c,d,e) dmxLog(dmxDebug,f,a,b,c,d,e)
-#define DMXDBG6(f,a,b,c,d,e,g) dmxLog(dmxDebug,f,a,b,c,d,e,g)
-#define DMXDBG7(f,a,b,c,d,e,g,h) dmxLog(dmxDebug,f,a,b,c,d,e,g,h)
-#else
-#define DMXDBG0(f)
-#define DMXDBG1(f,a)
-#define DMXDBG2(f,a,b)
-#define DMXDBG3(f,a,b,c)
-#define DMXDBG4(f,a,b,c,d)
-#define DMXDBG5(f,a,b,c,d,e)
-#define DMXDBG6(f,a,b,c,d,e,g)
-#define DMXDBG7(f,a,b,c,d,e,g,h)
-#endif
-
-static int dmxApplyFunctions(DMXInputInfo *dmxInput, DMXFunctionType f)
-{
- int i;
- int rc = 0;
-
- for (i = 0; i < dmxInput->numDevs; i+= dmxInput->devs[i]->binding)
- if (dmxInput->devs[i]->functions)
- rc += dmxInput->devs[i]->functions(dmxInput->devs[i]->private, f);
- return rc;
-}
-
-static int dmxCheckFunctionKeys(DMXLocalInputInfoPtr dmxLocal,
- int type,
- KeySym keySym)
-{
- DMXInputInfo *dmxInput = &dmxInputs[dmxLocal->inputIdx];
-
-#if 1 /* hack to detect ctrl-alt-q, etc */
- static int ctrl = 0, alt = 0;
- /* keep track of ctrl/alt key status */
- if (type == KeyPress && keySym == 0xffe3) {
- ctrl = 1;
- }
- else if (type == KeyRelease && keySym == 0xffe3) {
- ctrl = 0;
- }
- else if (type == KeyPress && keySym == 0xffe9) {
- alt = 1;
- }
- else if (type == KeyRelease && keySym == 0xffe9) {
- alt = 0;
- }
- if (!ctrl || !alt)
- return 0;
-#else
- unsigned short state = 0;
-
- if (dmxLocal->sendsCore)
- state = dmxLocalCoreKeyboard->pDevice->key->state;
- else if (dmxLocal->pDevice->key)
- state = dmxLocal->pDevice->key->state;
-
- DMXDBG3("dmxCheckFunctionKeys: keySym=0x%04x %s state=0x%04x\n",
- keySym, type == KeyPress ? "press" : "release", state);
-
- if ((state & (ControlMask|Mod1Mask)) != (ControlMask|Mod1Mask))
- return 0;
-#endif
-
- switch (keySym) {
- case XK_g:
- if (type == KeyPress)
- dmxApplyFunctions(dmxInput, DMX_FUNCTION_GRAB);
- return 1;
- case XK_f:
- if (type == KeyPress)
- dmxApplyFunctions(dmxInput, DMX_FUNCTION_FINE);
- return 1;
- case XK_q:
- if (type == KeyPress && dmxLocal->sendsCore)
- if (dmxApplyFunctions(dmxInput, DMX_FUNCTION_TERMINATE)) {
- dmxLog(dmxInfo, "User request for termination\n");
- dispatchException |= DE_TERMINATE;
- }
- return 1;
- }
-
- return 0;
-}
-
-
-DMXScreenInfo *dmxFindFirstScreen(int x, int y)
-{
- int i;
-
- for (i = 0; i < dmxNumScreens; i++) {
- DMXScreenInfo *dmxScreen = &dmxScreens[i];
- if (dmxOnScreen(x, y, dmxScreen))
- return dmxScreen;
- }
- return NULL;
-}
-
-
-/**
- * Enqueue a motion event.
- */
-static void enqueueMotion(DevicePtr pDev, int x, int y)
-{
- GETDMXLOCALFROMPDEV;
- DeviceIntPtr p = dmxLocal->pDevice;
- int i, nevents, valuators[3];
- EventListPtr events;
- int detail = 0; /* XXX should this be mask of pressed buttons? */
- ValuatorMask mask;
- valuators[0] = x;
- valuators[1] = y;
-
- valuator_mask_set_range(&mask, 0, 2, valuators);
- GetEventList(&events);
- nevents = GetPointerEvents(events, p, MotionNotify, detail,
- POINTER_ABSOLUTE | POINTER_SCREEN, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(p, (InternalEvent*)(events + i)->event);
- return;
-}
-
-
-void
-dmxCoreMotion(DevicePtr pDev, int x, int y, int delta, DMXBlockType block)
-{
- DMXScreenInfo *dmxScreen;
- DMXInputInfo *dmxInput;
- ScreenPtr pScreen;
- int localX;
- int localY;
- int i;
-
- if (!dmxGlobalInvalid && dmxGlobalX == x && dmxGlobalY == y)
- return;
-
- DMXDBG5("dmxCoreMotion(%d,%d,%d) dmxGlobalX=%d dmxGlobalY=%d\n",
- x, y, delta, dmxGlobalX, dmxGlobalY);
-
- dmxGlobalInvalid = 0;
- dmxGlobalX = x;
- dmxGlobalY = y;
-
- if (dmxGlobalX < 0)
- dmxGlobalX = 0;
- if (dmxGlobalY < 0)
- dmxGlobalY = 0;
- if (dmxGlobalX >= dmxGlobalWidth)
- dmxGlobalX = dmxGlobalWidth + delta -1;
- if (dmxGlobalY >= dmxGlobalHeight)
- dmxGlobalY = dmxGlobalHeight + delta -1;
-
- if ((dmxScreen = dmxFindFirstScreen(dmxGlobalX, dmxGlobalY))) {
- localX = dmxGlobalX - dmxScreen->rootXOrigin;
- localY = dmxGlobalY - dmxScreen->rootYOrigin;
- if ((pScreen = miPointerGetScreen(inputInfo.pointer))
- && pScreen->myNum == dmxScreen->index) {
- /* Screen is old screen */
- if (block)
- dmxSigioBlock();
- if (pDev)
- enqueueMotion(pDev, localX, localY);
- if (block)
- dmxSigioUnblock();
- } else {
- /* Screen is new */
- DMXDBG4(" New screen: old=%d new=%d localX=%d localY=%d\n",
- pScreen->myNum, dmxScreen->index, localX, localY);
- if (block)
- dmxSigioBlock();
- mieqProcessInputEvents();
- miPointerSetScreen(inputInfo.pointer, dmxScreen->index,
- localX, localY);
- if (pDev)
- enqueueMotion(pDev, localX, localY);
- if (block)
- dmxSigioUnblock();
- }
-#if 00
- miPointerGetPosition(inputInfo.pointer, &localX, &localY);
-
- if ((pScreen = miPointerGetScreen(inputInfo.pointer))) {
- dmxGlobalX = localX + dmxScreens[pScreen->myNum].rootXOrigin;
- dmxGlobalY = localY + dmxScreens[pScreen->myNum].rootYOrigin;
- ErrorF("Global is now %d, %d %d, %d\n", dmxGlobalX, dmxGlobalY,
- localX, localY);
- DMXDBG6(" Moved to dmxGlobalX=%d dmxGlobalY=%d"
- " on screen index=%d/%d localX=%d localY=%d\n",
- dmxGlobalX, dmxGlobalY,
- dmxScreen ? dmxScreen->index : -1, pScreen->myNum,
- localX, localY);
- }
-#endif
- }
- /* Send updates down to all core input
- * drivers */
- for (i = 0, dmxInput = &dmxInputs[0]; i < dmxNumInputs; i++, dmxInput++) {
- int j;
- for (j = 0; j < dmxInput->numDevs; j += dmxInput->devs[j]->binding)
- if (!dmxInput->detached
- && dmxInput->devs[j]->sendsCore
- && dmxInput->devs[j]->update_position)
- dmxInput->devs[j]->update_position(dmxInput->devs[j]->private,
- dmxGlobalX, dmxGlobalY);
- }
- if (!dmxScreen) ProcessInputEvents();
-}
-
-
-
-#define DMX_MAX_AXES 32 /* Max axes reported by this routine */
-static void dmxExtMotion(DMXLocalInputInfoPtr dmxLocal,
- int *v, int firstAxis, int axesCount,
- DMXMotionType type, DMXBlockType block)
-{
- DeviceIntPtr pDevice = dmxLocal->pDevice;
- xEvent xE[2 * DMX_MAX_AXES/6];
- deviceKeyButtonPointer *xev = (deviceKeyButtonPointer *)xE;
- deviceValuator *xv = (deviceValuator *)xev+1;
- int thisX = 0;
- int thisY = 0;
- int i;
- int count;
- EventListPtr events;
- int nevents;
- ValuatorMask mask;
-
- memset(xE, 0, sizeof(xE));
-
- if (axesCount > DMX_MAX_AXES) axesCount = DMX_MAX_AXES;
-
- if ((valuator_get_mode(pDevice,0) == Relative) && axesCount == 2) {
- /* The dmx console is a relative mode
- * device that sometimes reports
- * absolute motion. It only has two
- * axes. */
- if (type == DMX_RELATIVE) {
- thisX = -v[0];
- thisY = -v[1];
- dmxLocal->lastX += thisX;
- dmxLocal->lastY += thisY;
- if (dmxLocal->update_position)
- dmxLocal->update_position(dmxLocal->private,
- dmxLocal->lastX, dmxLocal->lastY);
- } else { /* Convert to relative */
- if (dmxLocal->lastX || dmxLocal->lastY) {
- thisX = v[0] - dmxLocal->lastX;
- thisY = v[1] - dmxLocal->lastY;
- }
- dmxLocal->lastX = v[0];
- dmxLocal->lastY = v[1];
- }
- v[0] = thisX;
- v[1] = thisY;
- }
-
- if (axesCount <= 6) {
- /* Optimize for the common case when
- * only 1 or 2 axes change. */
- xev->time = GetTimeInMillis();
- xev->type = DeviceMotionNotify;
- xev->detail = 0;
- xev->deviceid = pDevice->id | MORE_EVENTS;
-
- xv->type = DeviceValuator;
- xv->deviceid = pDevice->id;
- xv->num_valuators = axesCount;
- xv->first_valuator = firstAxis;
- switch (xv->num_valuators) {
- case 6: xv->valuator5 = v[5];
- case 5: xv->valuator4 = v[4];
- case 4: xv->valuator3 = v[3];
- case 3: xv->valuator2 = v[2];
- case 2: xv->valuator1 = v[1];
- case 1: xv->valuator0 = v[0];
- }
- count = 2;
- } else {
- for (i = 0, count = 0; i < axesCount; i += 6) {
- xev->time = GetTimeInMillis();
- xev->type = DeviceMotionNotify;
- xev->detail = 0;
- xev->deviceid = pDevice->id | MORE_EVENTS;
- xev += 2;
-
- xv->type = DeviceValuator;
- xv->deviceid = pDevice->id;
- xv->num_valuators = (i+6 >= axesCount ? axesCount - i : 6);
- xv->first_valuator = firstAxis + i;
- switch (xv->num_valuators) {
- case 6: xv->valuator5 = v[i+5];
- case 5: xv->valuator4 = v[i+4];
- case 4: xv->valuator3 = v[i+3];
- case 3: xv->valuator2 = v[i+2];
- case 2: xv->valuator1 = v[i+1];
- case 1: xv->valuator0 = v[i+0];
- }
- xv += 2;
- count += 2;
- }
- }
-
- if (block)
- dmxSigioBlock();
- valuator_mask_set_range(&mask, firstAxis, axesCount, v);
- GetEventList(&events);
- nevents = GetPointerEvents(events, pDevice, MotionNotify, 0,
- POINTER_ABSOLUTE, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event);
-
- if (block)
- dmxSigioUnblock();
-}
-
-static int dmxTranslateAndEnqueueExtEvent(DMXLocalInputInfoPtr dmxLocal,
- XEvent *e, DMXBlockType block)
-{
- int type;
- int event = -1;
- XDeviceKeyEvent *ke = (XDeviceKeyEvent *)e;
- XDeviceMotionEvent *me = (XDeviceMotionEvent *)e;
- DeviceIntPtr pDevice = dmxLocal->pDevice;
- int valuators[MAX_VALUATORS];
- EventListPtr events;
- int nevents, i;
- ValuatorMask mask;
-
- if (!e)
- return -1; /* No extended event passed, cannot handle */
-
- if ((XID)dmxLocal->deviceId != ke->deviceid) {
- /* Search for the correct dmxLocal,
- * since backend and console events are
- * picked up for the first device on
- * that X server. */
- int i;
- DMXInputInfo *dmxInput = &dmxInputs[dmxLocal->inputIdx];
- for (i = 0; i < dmxInput->numDevs; i++) {
- dmxLocal = dmxInput->devs[i];
- if ((XID)dmxLocal->deviceId == ke->deviceid)
- break;
- }
- }
-
- if ((XID)dmxLocal->deviceId != ke->deviceid
- || (type = dmxMapLookup(dmxLocal, e->type)) < 0)
- return -1; /* No mapping, so this event is unhandled */
-
- switch (type) {
- case XI_DeviceValuator: event = DeviceValuator; break;
- case XI_DeviceKeyPress: event = KeyPress; break;
- case XI_DeviceKeyRelease: event = KeyRelease; break;
- case XI_DeviceButtonPress: event = ButtonPress; break;
- case XI_DeviceButtonRelease: event = ButtonRelease; break;
- case XI_DeviceMotionNotify: event = MotionNotify; break;
- case XI_DeviceFocusIn: event = DeviceFocusIn; break;
- case XI_DeviceFocusOut: event = DeviceFocusOut; break;
- case XI_ProximityIn: event = ProximityIn; break;
- case XI_ProximityOut: event = ProximityOut; break;
- case XI_DeviceStateNotify: event = DeviceStateNotify; break;
- case XI_DeviceMappingNotify: event = DeviceMappingNotify; break;
- case XI_ChangeDeviceNotify: event = ChangeDeviceNotify; break;
- case XI_DeviceKeystateNotify: event = DeviceStateNotify; break;
- case XI_DeviceButtonstateNotify: event = DeviceStateNotify; break;
- }
-
-#define EXTRACT_VALUATORS(ke, valuators) \
- valuators[0] = ke->axis_data[0]; \
- valuators[1] = ke->axis_data[1]; \
- valuators[2] = ke->axis_data[2]; \
- valuators[3] = ke->axis_data[3]; \
- valuators[4] = ke->axis_data[4]; \
- valuators[5] = ke->axis_data[5]; \
-
- switch (type) {
- case XI_DeviceKeyPress:
- case XI_DeviceKeyRelease:
- EXTRACT_VALUATORS(ke, valuators);
- valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators);
- if (block)
- dmxSigioBlock();
- GetEventList(&events);
- nevents = GetKeyboardValuatorEvents(events, pDevice, event,
- ke->keycode, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event);
-
- if (block)
- dmxSigioUnblock();
- break;
- case XI_DeviceButtonPress:
- case XI_DeviceButtonRelease:
- EXTRACT_VALUATORS(ke, valuators);
- valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators);
- if (block)
- dmxSigioBlock();
- GetEventList(&events);
- nevents = GetPointerEvents(events, pDevice, event, ke->keycode,
- POINTER_ABSOLUTE, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event);
-
- if (block)
- dmxSigioUnblock();
- break;
- case XI_ProximityIn:
- case XI_ProximityOut:
- EXTRACT_VALUATORS(ke, valuators);
- valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators);
- if (block)
- dmxSigioBlock();
- GetEventList(&events);
- nevents = GetProximityEvents(events, pDevice, event, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event);
-
- if (block)
- dmxSigioUnblock();
- break;
-
- break;
-
- case XI_DeviceMotionNotify:
- dmxExtMotion(dmxLocal, me->axis_data, me->first_axis, me->axes_count,
- DMX_ABSOLUTE, block);
- break;
- case XI_DeviceFocusIn:
- case XI_DeviceFocusOut:
- case XI_DeviceStateNotify:
- case XI_DeviceMappingNotify:
- case XI_ChangeDeviceNotify:
- case XI_DeviceKeystateNotify:
- case XI_DeviceButtonstateNotify:
- /* These are ignored, since DMX will
- * generate its own events of these
- * types, as necessary.
-
- * Perhaps ChangeDeviceNotify should
- * generate an error, because it is
- * unexpected? */
- break;
- case XI_DeviceValuator:
- default:
- dmxLog(dmxWarning,
- "XInput extension event (remote=%d -> zero-based=%d)"
- " not supported yet\n", e->type, type);
- return -1;
- }
- return 0;
-}
-
-static int dmxGetButtonMapping(DMXLocalInputInfoPtr dmxLocal, int button)
-{
- ButtonClassPtr b = dmxLocal->pDevice->button;
-
- if (button > b->numButtons) { /* This shouldn't happen. */
- dmxLog(dmxWarning, "Button %d pressed, but only %d buttons?!?\n",
- button, b->numButtons);
- return button;
- }
- return b->map[button];
-}
-
-/** Return DMX's notion of the pointer position in the global coordinate
- * space. */
-void dmxGetGlobalPosition(int *x, int *y)
-{
- *x = dmxGlobalX;
- *y = dmxGlobalY;
-}
-
-/** Invalidate the global position for #dmxCoreMotion. */
-void dmxInvalidateGlobalPosition(void)
-{
- dmxGlobalInvalid = 1;
-}
-
-/** Enqueue a motion event for \a pDev. The \a v vector has length \a
- * axesCount, and contains values for each of the axes, starting at \a
- * firstAxes.
- *
- * The \a type of the motion may be \a DMX_RELATIVE, \a DMX_ABSOLUTE, or
- * \a DMX_ABSOLUTE_CONFINED (in the latter case, the pointer will not be
- * allowed to move outside the global boundaires).
- *
- * If \a block is set to \a DMX_BLOCK, then the SIGIO handler will be
- * blocked around calls to \a enqueueMotion(). */
-void dmxMotion(DevicePtr pDev, int *v, int firstAxes, int axesCount,
- DMXMotionType type, DMXBlockType block)
-{
- GETDMXLOCALFROMPDEV;
-
- if (!dmxLocal->sendsCore) {
- dmxExtMotion(dmxLocal, v, firstAxes, axesCount, type, block);
- return;
- }
- if (axesCount == 2) {
- switch (type) {
- case DMX_RELATIVE:
- dmxCoreMotion(pDev, dmxGlobalX - v[0], dmxGlobalY - v[1], 0, block);
- break;
- case DMX_ABSOLUTE:
- dmxCoreMotion(pDev, v[0], v[1], 0, block);
- break;
- case DMX_ABSOLUTE_CONFINED:
- dmxCoreMotion(pDev, v[0], v[1], -1, block);
- break;
- }
- }
-}
-
-static KeySym dmxKeyCodeToKeySym(DMXLocalInputInfoPtr dmxLocal,
- KeyCode keyCode)
-{
- KeySym keysym = NoSymbol;
- int effectiveGroup;
- XkbSrvInfoPtr xkbi;
-
- if (!dmxLocal || !dmxLocal->pDevice || !dmxLocal->pDevice->key)
- goto out;
-
- xkbi = dmxLocal->pDevice->key->xkbInfo;
- effectiveGroup = XkbGetEffectiveGroup(xkbi, &xkbi->state, keyCode);
-
- if (effectiveGroup == -1)
- goto out;
-
- keysym = XkbKeySym(xkbi->desc, keyCode, effectiveGroup);
- DMXDBG2("dmxKeyCodeToKeySym: Translated keyCode=%d to keySym=0x%04x\n",
- keyCode, keysym);
-
-out:
- return keysym;
-}
-
-static KeyCode dmxKeySymToKeyCode(DMXLocalInputInfoPtr dmxLocal, KeySym keySym,
- int tryFirst)
-{
- /* FIXME: this is quite ineffective, converting to a core map first and
- * then extracting the info from there. It'd be better to run the actual
- * xkb map */
- XkbSrvInfoPtr xkbi = dmxLocal->pDevice->key->xkbInfo;
- KeySymsPtr pKeySyms = XkbGetCoreMap(dmxLocal->pDevice);
- int i;
-
- /* Optimize for similar maps */
- if (XkbKeycodeInRange(xkbi->desc, tryFirst)
- && pKeySyms->map[(tryFirst - xkbi->desc->min_key_code)
- * pKeySyms->mapWidth] == keySym)
- return tryFirst;
-
- for (i = pKeySyms->minKeyCode; i <= pKeySyms->maxKeyCode; i++) {
- if (pKeySyms->map[(i - pKeySyms->minKeyCode)
- * pKeySyms->mapWidth] == keySym) {
- DMXDBG3("dmxKeySymToKeyCode: Translated keySym=0x%04x to"
- " keyCode=%d (reverses to core keySym=0x%04x)\n",
- keySym, i, dmxKeyCodeToKeySym(dmxLocalCoreKeyboard,i));
- return i;
- }
- }
- return 0;
-}
-
-static int dmxFixup(DevicePtr pDev, int detail, KeySym keySym)
-{
- GETDMXLOCALFROMPDEV;
- int keyCode;
-
- if (!dmxLocal->pDevice->key) {
- dmxLog(dmxWarning, "dmxFixup: not a keyboard device (%s)\n",
- dmxLocal->pDevice->name);
- return NoSymbol;
- }
- if (!keySym)
- keySym = dmxKeyCodeToKeySym(dmxLocal, detail);
- if (keySym == NoSymbol)
- return detail;
- keyCode = dmxKeySymToKeyCode(dmxLocalCoreKeyboard, keySym, detail);
-
- return keyCode ? keyCode : detail;
-}
-
-/** Enqueue an event from the \a pDev device with the
- * specified \a type and \a detail. If the event is a KeyPress or
- * KeyRelease event, then the \a keySym is also specified.
- *
- * FIXME: make the code do what the comment says, or remove this comment.
- * If \a block is set to \a DMX_BLOCK, then the SIGIO handler will be
- * blocked around calls to dmxeqEnqueue(). */
-
-void dmxEnqueue(DevicePtr pDev, int type, int detail, KeySym keySym,
- XEvent *e, DMXBlockType block)
-{
- GETDMXINPUTFROMPDEV;
- xEvent xE;
- DeviceIntPtr p = dmxLocal->pDevice;
- int i, nevents, valuators[3];
- EventListPtr events;
- ValuatorMask mask;
-
- DMXDBG2("dmxEnqueue: Enqueuing type=%d detail=0x%0x\n", type, detail);
-
- switch (type) {
- case KeyPress:
- case KeyRelease:
- if (!keySym)
- keySym = dmxKeyCodeToKeySym(dmxLocal, detail);
- if (dmxCheckFunctionKeys(dmxLocal, type, keySym))
- return;
- if (dmxLocal->sendsCore && dmxLocal != dmxLocalCoreKeyboard)
- xE.u.u.detail = dmxFixup(pDev, detail, keySym);
-
- GetEventList(&events);
- /*ErrorF("KEY %d sym %d\n", detail, (int) keySym);*/
- nevents = GetKeyboardEvents(events, p, type, detail);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(p, (InternalEvent*)(events + i)->event);
- return;
-
- case ButtonPress:
- case ButtonRelease:
- detail = dmxGetButtonMapping(dmxLocal, detail);
- valuator_mask_zero(&mask);
- GetEventList(&events);
- nevents = GetPointerEvents(events, p, type, detail,
- POINTER_ABSOLUTE | POINTER_SCREEN, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(p, (InternalEvent*)(events + i)->event);
- return;
-
- case MotionNotify:
- GetEventList(&events);
- valuators[0] = e->xmotion.x;
- valuators[1] = e->xmotion.y;
- valuators[2] = e->xmotion.state; /* FIXME: WTF?? */
- valuator_mask_set_range(&mask, 0, 3, valuators);
- nevents = GetPointerEvents(events, p, type, detail,
- POINTER_ABSOLUTE | POINTER_SCREEN, &mask);
- for (i = 0; i < nevents; i++)
- mieqEnqueue(p, (InternalEvent*)(events + i)->event);
- return;
-
- case EnterNotify:
- case LeaveNotify:
- case KeymapNotify:
- case MappingNotify: /* This is sent because we change the
- * modifier map on the backend/console
- * input device so that we have complete
- * control of the input device LEDs. */
- return;
- default:
- if (type == ProximityIn || type == ProximityOut) {
- if (dmxLocal->sendsCore)
- return; /* Not a core event */
- break;
- }
- if (type >= LASTEvent) {
- if (dmxTranslateAndEnqueueExtEvent(dmxLocal, e, block))
- dmxLogInput(dmxInput, "Unhandled extension event: %d\n", type);
- } else {
- dmxLogInput(dmxInput, "Unhandled event: %d (%s)\n",
- type, dmxEventName(type));
- }
- return;
- }
-
-}
-
-/** A pointer to this routine is passed to low-level input drivers so
- * that all special keychecking is unified to this file. This function
- * returns 0 if no special keys have been pressed. If the user has
- * requested termination of the DMX server, -1 is returned. If the user
- * has requested a switch to a VT, then the (1-based) number of that VT
- * is returned. */
-int dmxCheckSpecialKeys(DevicePtr pDev, KeySym keySym)
-{
- GETDMXINPUTFROMPDEV;
- int vt = 0;
- unsigned short state = 0;
-
- if (dmxLocal->sendsCore)
- state = XkbStateFieldFromRec(&dmxLocalCoreKeyboard->pDevice->key->xkbInfo->state);
- else if (dmxLocal->pDevice->key)
- state = XkbStateFieldFromRec(&dmxLocal->pDevice->key->xkbInfo->state);
-
- if (!dmxLocal->sendsCore) return 0; /* Only for core devices */
-
- DMXDBG2("dmxCheckSpecialKeys: keySym=0x%04x state=0x%04x\n", keySym,state);
-
- if ((state & (ControlMask|Mod1Mask)) != (ControlMask|Mod1Mask)) return 0;
-
- switch (keySym) {
- case XK_F1:
- case XK_F2:
- case XK_F3:
- case XK_F4:
- case XK_F5:
- case XK_F6:
- case XK_F7:
- case XK_F8:
- case XK_F9:
- case XK_F10:
- vt = keySym - XK_F1 + 1;
- break;
-
- case XK_F11:
- case XK_F12:
- vt = keySym - XK_F11 + 11;
- break;
-
- case XK_q: /* To avoid confusion */
- case XK_BackSpace:
- case XK_Delete:
- case XK_KP_Delete:
- dmxLog(dmxInfo, "User request for termination\n");
- dispatchException |= DE_TERMINATE;
- return -1; /* Terminate */
- }
-
- if (vt) {
- dmxLog(dmxInfo, "Request to switch to VT %d\n", vt);
- dmxInput->vt_switch_pending = vt;
- return vt;
- }
-
- return 0; /* Do nothing */
-}
+/* + * Copyright 2002-2003 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: + * Rickard E. (Rik) Faith <faith@redhat.com> + * + */ + +/** \file + * Provide support and helper functions for enqueing events received by + * the low-level input drivers. */ + +#ifdef HAVE_DMX_CONFIG_H +#include <dmx-config.h> +#endif + +#define DMX_EVENTS_DEBUG 0 + +#include "dmxinputinit.h" +#include "dmxevents.h" +#include "dmxcb.h" +#include "dmxcommon.h" +#include "dmxcursor.h" +#include "dmxmotion.h" +#include "dmxsigio.h" +#include "dmxmap.h" + +#include <X11/keysym.h> +#include "opaque.h" +#include "inputstr.h" +#include "inpututils.h" +#include "mipointer.h" +#include "mi.h" +#include "exglobals.h" + +#include "xkbsrv.h" +#include "XIstubs.h" + +static int dmxGlobalX, dmxGlobalY; /* Global cursor position */ +static int dmxGlobalInvalid; /* Flag indicating dmxCoreMotion + * should move the mouse anyway. */ + +#if DMX_EVENTS_DEBUG +#define DMXDBG0(f) dmxLog(dmxDebug,f) +#define DMXDBG1(f,a) dmxLog(dmxDebug,f,a) +#define DMXDBG2(f,a,b) dmxLog(dmxDebug,f,a,b) +#define DMXDBG3(f,a,b,c) dmxLog(dmxDebug,f,a,b,c) +#define DMXDBG4(f,a,b,c,d) dmxLog(dmxDebug,f,a,b,c,d) +#define DMXDBG5(f,a,b,c,d,e) dmxLog(dmxDebug,f,a,b,c,d,e) +#define DMXDBG6(f,a,b,c,d,e,g) dmxLog(dmxDebug,f,a,b,c,d,e,g) +#define DMXDBG7(f,a,b,c,d,e,g,h) dmxLog(dmxDebug,f,a,b,c,d,e,g,h) +#else +#define DMXDBG0(f) +#define DMXDBG1(f,a) +#define DMXDBG2(f,a,b) +#define DMXDBG3(f,a,b,c) +#define DMXDBG4(f,a,b,c,d) +#define DMXDBG5(f,a,b,c,d,e) +#define DMXDBG6(f,a,b,c,d,e,g) +#define DMXDBG7(f,a,b,c,d,e,g,h) +#endif + +static int dmxApplyFunctions(DMXInputInfo *dmxInput, DMXFunctionType f) +{ + int i; + int rc = 0; + + for (i = 0; i < dmxInput->numDevs; i+= dmxInput->devs[i]->binding) + if (dmxInput->devs[i]->functions) + rc += dmxInput->devs[i]->functions(dmxInput->devs[i]->private, f); + return rc; +} + +static int dmxCheckFunctionKeys(DMXLocalInputInfoPtr dmxLocal, + int type, + KeySym keySym) +{ + DMXInputInfo *dmxInput = &dmxInputs[dmxLocal->inputIdx]; + +#if 1 /* hack to detect ctrl-alt-q, etc */ + static int ctrl = 0, alt = 0; + /* keep track of ctrl/alt key status */ + if (type == KeyPress && keySym == 0xffe3) { + ctrl = 1; + } + else if (type == KeyRelease && keySym == 0xffe3) { + ctrl = 0; + } + else if (type == KeyPress && keySym == 0xffe9) { + alt = 1; + } + else if (type == KeyRelease && keySym == 0xffe9) { + alt = 0; + } + if (!ctrl || !alt) + return 0; +#else + unsigned short state = 0; + + if (dmxLocal->sendsCore) + state = dmxLocalCoreKeyboard->pDevice->key->state; + else if (dmxLocal->pDevice->key) + state = dmxLocal->pDevice->key->state; + + DMXDBG3("dmxCheckFunctionKeys: keySym=0x%04x %s state=0x%04x\n", + keySym, type == KeyPress ? "press" : "release", state); + + if ((state & (ControlMask|Mod1Mask)) != (ControlMask|Mod1Mask)) + return 0; +#endif + + switch (keySym) { + case XK_g: + if (type == KeyPress) + dmxApplyFunctions(dmxInput, DMX_FUNCTION_GRAB); + return 1; + case XK_f: + if (type == KeyPress) + dmxApplyFunctions(dmxInput, DMX_FUNCTION_FINE); + return 1; + case XK_q: + if (type == KeyPress && dmxLocal->sendsCore) + if (dmxApplyFunctions(dmxInput, DMX_FUNCTION_TERMINATE)) { + dmxLog(dmxInfo, "User request for termination\n"); + dispatchException |= DE_TERMINATE; + } + return 1; + } + + return 0; +} + + +DMXScreenInfo *dmxFindFirstScreen(int x, int y) +{ + int i; + + for (i = 0; i < dmxNumScreens; i++) { + DMXScreenInfo *dmxScreen = &dmxScreens[i]; + if (dmxOnScreen(x, y, dmxScreen)) + return dmxScreen; + } + return NULL; +} + + +/** + * Enqueue a motion event. + */ +static void enqueueMotion(DevicePtr pDev, int x, int y) +{ + GETDMXLOCALFROMPDEV; + DeviceIntPtr p = dmxLocal->pDevice; + int i, nevents, valuators[3]; + EventListPtr events; + int detail = 0; /* XXX should this be mask of pressed buttons? */ + ValuatorMask mask; + valuators[0] = x; + valuators[1] = y; + + valuator_mask_set_range(&mask, 0, 2, valuators); + GetEventList(&events); + nevents = GetPointerEvents(events, p, MotionNotify, detail, + POINTER_ABSOLUTE | POINTER_SCREEN, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(p, (InternalEvent*)(events + i)->event); + return; +} + + +void +dmxCoreMotion(DevicePtr pDev, int x, int y, int delta, DMXBlockType block) +{ + DMXScreenInfo *dmxScreen; + DMXInputInfo *dmxInput; + ScreenPtr pScreen; + int localX; + int localY; + int i; + + if (!dmxGlobalInvalid && dmxGlobalX == x && dmxGlobalY == y) + return; + + DMXDBG5("dmxCoreMotion(%d,%d,%d) dmxGlobalX=%d dmxGlobalY=%d\n", + x, y, delta, dmxGlobalX, dmxGlobalY); + + dmxGlobalInvalid = 0; + dmxGlobalX = x; + dmxGlobalY = y; + + if (dmxGlobalX < 0) + dmxGlobalX = 0; + if (dmxGlobalY < 0) + dmxGlobalY = 0; + if (dmxGlobalX >= dmxGlobalWidth) + dmxGlobalX = dmxGlobalWidth + delta -1; + if (dmxGlobalY >= dmxGlobalHeight) + dmxGlobalY = dmxGlobalHeight + delta -1; + + if ((dmxScreen = dmxFindFirstScreen(dmxGlobalX, dmxGlobalY))) { + localX = dmxGlobalX - dmxScreen->rootXOrigin; + localY = dmxGlobalY - dmxScreen->rootYOrigin; + if ((pScreen = miPointerGetScreen(inputInfo.pointer)) + && pScreen->myNum == dmxScreen->index) { + /* Screen is old screen */ + if (block) + dmxSigioBlock(); + if (pDev) + enqueueMotion(pDev, localX, localY); + if (block) + dmxSigioUnblock(); + } else { + /* Screen is new */ + DMXDBG4(" New screen: old=%d new=%d localX=%d localY=%d\n", + pScreen->myNum, dmxScreen->index, localX, localY); + if (block) + dmxSigioBlock(); + mieqProcessInputEvents(); + miPointerSetScreen(inputInfo.pointer, dmxScreen->index, + localX, localY); + if (pDev) + enqueueMotion(pDev, localX, localY); + if (block) + dmxSigioUnblock(); + } +#if 00 + miPointerGetPosition(inputInfo.pointer, &localX, &localY); + + if ((pScreen = miPointerGetScreen(inputInfo.pointer))) { + dmxGlobalX = localX + dmxScreens[pScreen->myNum].rootXOrigin; + dmxGlobalY = localY + dmxScreens[pScreen->myNum].rootYOrigin; + ErrorF("Global is now %d, %d %d, %d\n", dmxGlobalX, dmxGlobalY, + localX, localY); + DMXDBG6(" Moved to dmxGlobalX=%d dmxGlobalY=%d" + " on screen index=%d/%d localX=%d localY=%d\n", + dmxGlobalX, dmxGlobalY, + dmxScreen ? dmxScreen->index : -1, pScreen->myNum, + localX, localY); + } +#endif + } + /* Send updates down to all core input + * drivers */ + for (i = 0, dmxInput = &dmxInputs[0]; i < dmxNumInputs; i++, dmxInput++) { + int j; + for (j = 0; j < dmxInput->numDevs; j += dmxInput->devs[j]->binding) + if (!dmxInput->detached + && dmxInput->devs[j]->sendsCore + && dmxInput->devs[j]->update_position) + dmxInput->devs[j]->update_position(dmxInput->devs[j]->private, + dmxGlobalX, dmxGlobalY); + } + if (!dmxScreen) ProcessInputEvents(); +} + + + +#define DMX_MAX_AXES 32 /* Max axes reported by this routine */ +static void dmxExtMotion(DMXLocalInputInfoPtr dmxLocal, + int *v, int firstAxis, int axesCount, + DMXMotionType type, DMXBlockType block) +{ + DeviceIntPtr pDevice = dmxLocal->pDevice; + xEvent xE[2 * DMX_MAX_AXES/6]; + deviceKeyButtonPointer *xev = (deviceKeyButtonPointer *)xE; + deviceValuator *xv = (deviceValuator *)xev+1; + int thisX = 0; + int thisY = 0; + int i; + int count; + EventListPtr events; + int nevents; + ValuatorMask mask; + + memset(xE, 0, sizeof(xE)); + + if (axesCount > DMX_MAX_AXES) axesCount = DMX_MAX_AXES; + + if ((valuator_get_mode(pDevice,0) == Relative) && axesCount == 2) { + /* The dmx console is a relative mode + * device that sometimes reports + * absolute motion. It only has two + * axes. */ + if (type == DMX_RELATIVE) { + thisX = -v[0]; + thisY = -v[1]; + dmxLocal->lastX += thisX; + dmxLocal->lastY += thisY; + if (dmxLocal->update_position) + dmxLocal->update_position(dmxLocal->private, + dmxLocal->lastX, dmxLocal->lastY); + } else { /* Convert to relative */ + if (dmxLocal->lastX || dmxLocal->lastY) { + thisX = v[0] - dmxLocal->lastX; + thisY = v[1] - dmxLocal->lastY; + } + dmxLocal->lastX = v[0]; + dmxLocal->lastY = v[1]; + } + v[0] = thisX; + v[1] = thisY; + } + + if (axesCount <= 6) { + /* Optimize for the common case when + * only 1 or 2 axes change. */ + xev->time = GetTimeInMillis(); + xev->type = DeviceMotionNotify; + xev->detail = 0; + xev->deviceid = pDevice->id | MORE_EVENTS; + + xv->type = DeviceValuator; + xv->deviceid = pDevice->id; + xv->num_valuators = axesCount; + xv->first_valuator = firstAxis; + switch (xv->num_valuators) { + case 6: xv->valuator5 = v[5]; + case 5: xv->valuator4 = v[4]; + case 4: xv->valuator3 = v[3]; + case 3: xv->valuator2 = v[2]; + case 2: xv->valuator1 = v[1]; + case 1: xv->valuator0 = v[0]; + } + count = 2; + } else { + for (i = 0, count = 0; i < axesCount; i += 6) { + xev->time = GetTimeInMillis(); + xev->type = DeviceMotionNotify; + xev->detail = 0; + xev->deviceid = pDevice->id | MORE_EVENTS; + xev += 2; + + xv->type = DeviceValuator; + xv->deviceid = pDevice->id; + xv->num_valuators = (i+6 >= axesCount ? axesCount - i : 6); + xv->first_valuator = firstAxis + i; + switch (xv->num_valuators) { + case 6: xv->valuator5 = v[i+5]; + case 5: xv->valuator4 = v[i+4]; + case 4: xv->valuator3 = v[i+3]; + case 3: xv->valuator2 = v[i+2]; + case 2: xv->valuator1 = v[i+1]; + case 1: xv->valuator0 = v[i+0]; + } + xv += 2; + count += 2; + } + } + + if (block) + dmxSigioBlock(); + valuator_mask_set_range(&mask, firstAxis, axesCount, v); + GetEventList(&events); + nevents = GetPointerEvents(events, pDevice, MotionNotify, 0, + POINTER_ABSOLUTE, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event); + + if (block) + dmxSigioUnblock(); +} + +static int dmxTranslateAndEnqueueExtEvent(DMXLocalInputInfoPtr dmxLocal, + XEvent *e, DMXBlockType block) +{ + int type; + int event = -1; + XDeviceKeyEvent *ke = (XDeviceKeyEvent *)e; + XDeviceMotionEvent *me = (XDeviceMotionEvent *)e; + DeviceIntPtr pDevice = dmxLocal->pDevice; + int valuators[MAX_VALUATORS]; + EventListPtr events; + int nevents, i; + ValuatorMask mask; + + if (!e) + return -1; /* No extended event passed, cannot handle */ + + if ((XID)dmxLocal->deviceId != ke->deviceid) { + /* Search for the correct dmxLocal, + * since backend and console events are + * picked up for the first device on + * that X server. */ + int i; + DMXInputInfo *dmxInput = &dmxInputs[dmxLocal->inputIdx]; + for (i = 0; i < dmxInput->numDevs; i++) { + dmxLocal = dmxInput->devs[i]; + if ((XID)dmxLocal->deviceId == ke->deviceid) + break; + } + } + + if ((XID)dmxLocal->deviceId != ke->deviceid + || (type = dmxMapLookup(dmxLocal, e->type)) < 0) + return -1; /* No mapping, so this event is unhandled */ + + switch (type) { + case XI_DeviceValuator: event = DeviceValuator; break; + case XI_DeviceKeyPress: event = KeyPress; break; + case XI_DeviceKeyRelease: event = KeyRelease; break; + case XI_DeviceButtonPress: event = ButtonPress; break; + case XI_DeviceButtonRelease: event = ButtonRelease; break; + case XI_DeviceMotionNotify: event = MotionNotify; break; + case XI_DeviceFocusIn: event = DeviceFocusIn; break; + case XI_DeviceFocusOut: event = DeviceFocusOut; break; + case XI_ProximityIn: event = ProximityIn; break; + case XI_ProximityOut: event = ProximityOut; break; + case XI_DeviceStateNotify: event = DeviceStateNotify; break; + case XI_DeviceMappingNotify: event = DeviceMappingNotify; break; + case XI_ChangeDeviceNotify: event = ChangeDeviceNotify; break; + case XI_DeviceKeystateNotify: event = DeviceStateNotify; break; + case XI_DeviceButtonstateNotify: event = DeviceStateNotify; break; + } + +#define EXTRACT_VALUATORS(ke, valuators) \ + valuators[0] = ke->axis_data[0]; \ + valuators[1] = ke->axis_data[1]; \ + valuators[2] = ke->axis_data[2]; \ + valuators[3] = ke->axis_data[3]; \ + valuators[4] = ke->axis_data[4]; \ + valuators[5] = ke->axis_data[5]; \ + + switch (type) { + case XI_DeviceKeyPress: + case XI_DeviceKeyRelease: + EXTRACT_VALUATORS(ke, valuators); + valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators); + if (block) + dmxSigioBlock(); + GetEventList(&events); + nevents = GetKeyboardEvents(events, pDevice, event, + ke->keycode, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event); + + if (block) + dmxSigioUnblock(); + break; + case XI_DeviceButtonPress: + case XI_DeviceButtonRelease: + EXTRACT_VALUATORS(ke, valuators); + valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators); + if (block) + dmxSigioBlock(); + GetEventList(&events); + nevents = GetPointerEvents(events, pDevice, event, ke->keycode, + POINTER_ABSOLUTE, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event); + + if (block) + dmxSigioUnblock(); + break; + case XI_ProximityIn: + case XI_ProximityOut: + EXTRACT_VALUATORS(ke, valuators); + valuator_mask_set_range(&mask, ke->first_axis, ke->axes_count, valuators); + if (block) + dmxSigioBlock(); + GetEventList(&events); + nevents = GetProximityEvents(events, pDevice, event, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(pDevice, (InternalEvent*)(events + i)->event); + + if (block) + dmxSigioUnblock(); + break; + + break; + + case XI_DeviceMotionNotify: + dmxExtMotion(dmxLocal, me->axis_data, me->first_axis, me->axes_count, + DMX_ABSOLUTE, block); + break; + case XI_DeviceFocusIn: + case XI_DeviceFocusOut: + case XI_DeviceStateNotify: + case XI_DeviceMappingNotify: + case XI_ChangeDeviceNotify: + case XI_DeviceKeystateNotify: + case XI_DeviceButtonstateNotify: + /* These are ignored, since DMX will + * generate its own events of these + * types, as necessary. + + * Perhaps ChangeDeviceNotify should + * generate an error, because it is + * unexpected? */ + break; + case XI_DeviceValuator: + default: + dmxLog(dmxWarning, + "XInput extension event (remote=%d -> zero-based=%d)" + " not supported yet\n", e->type, type); + return -1; + } + return 0; +} + +static int dmxGetButtonMapping(DMXLocalInputInfoPtr dmxLocal, int button) +{ + ButtonClassPtr b = dmxLocal->pDevice->button; + + if (button > b->numButtons) { /* This shouldn't happen. */ + dmxLog(dmxWarning, "Button %d pressed, but only %d buttons?!?\n", + button, b->numButtons); + return button; + } + return b->map[button]; +} + +/** Return DMX's notion of the pointer position in the global coordinate + * space. */ +void dmxGetGlobalPosition(int *x, int *y) +{ + *x = dmxGlobalX; + *y = dmxGlobalY; +} + +/** Invalidate the global position for #dmxCoreMotion. */ +void dmxInvalidateGlobalPosition(void) +{ + dmxGlobalInvalid = 1; +} + +/** Enqueue a motion event for \a pDev. The \a v vector has length \a + * axesCount, and contains values for each of the axes, starting at \a + * firstAxes. + * + * The \a type of the motion may be \a DMX_RELATIVE, \a DMX_ABSOLUTE, or + * \a DMX_ABSOLUTE_CONFINED (in the latter case, the pointer will not be + * allowed to move outside the global boundaires). + * + * If \a block is set to \a DMX_BLOCK, then the SIGIO handler will be + * blocked around calls to \a enqueueMotion(). */ +void dmxMotion(DevicePtr pDev, int *v, int firstAxes, int axesCount, + DMXMotionType type, DMXBlockType block) +{ + GETDMXLOCALFROMPDEV; + + if (!dmxLocal->sendsCore) { + dmxExtMotion(dmxLocal, v, firstAxes, axesCount, type, block); + return; + } + if (axesCount == 2) { + switch (type) { + case DMX_RELATIVE: + dmxCoreMotion(pDev, dmxGlobalX - v[0], dmxGlobalY - v[1], 0, block); + break; + case DMX_ABSOLUTE: + dmxCoreMotion(pDev, v[0], v[1], 0, block); + break; + case DMX_ABSOLUTE_CONFINED: + dmxCoreMotion(pDev, v[0], v[1], -1, block); + break; + } + } +} + +static KeySym dmxKeyCodeToKeySym(DMXLocalInputInfoPtr dmxLocal, + KeyCode keyCode) +{ + KeySym keysym = NoSymbol; + int effectiveGroup; + XkbSrvInfoPtr xkbi; + + if (!dmxLocal || !dmxLocal->pDevice || !dmxLocal->pDevice->key) + goto out; + + xkbi = dmxLocal->pDevice->key->xkbInfo; + effectiveGroup = XkbGetEffectiveGroup(xkbi, &xkbi->state, keyCode); + + if (effectiveGroup == -1) + goto out; + + keysym = XkbKeySym(xkbi->desc, keyCode, effectiveGroup); + DMXDBG2("dmxKeyCodeToKeySym: Translated keyCode=%d to keySym=0x%04x\n", + keyCode, keysym); + +out: + return keysym; +} + +static KeyCode dmxKeySymToKeyCode(DMXLocalInputInfoPtr dmxLocal, KeySym keySym, + int tryFirst) +{ + /* FIXME: this is quite ineffective, converting to a core map first and + * then extracting the info from there. It'd be better to run the actual + * xkb map */ + XkbSrvInfoPtr xkbi = dmxLocal->pDevice->key->xkbInfo; + KeySymsPtr pKeySyms = XkbGetCoreMap(dmxLocal->pDevice); + int i; + + /* Optimize for similar maps */ + if (XkbKeycodeInRange(xkbi->desc, tryFirst) + && pKeySyms->map[(tryFirst - xkbi->desc->min_key_code) + * pKeySyms->mapWidth] == keySym) + return tryFirst; + + for (i = pKeySyms->minKeyCode; i <= pKeySyms->maxKeyCode; i++) { + if (pKeySyms->map[(i - pKeySyms->minKeyCode) + * pKeySyms->mapWidth] == keySym) { + DMXDBG3("dmxKeySymToKeyCode: Translated keySym=0x%04x to" + " keyCode=%d (reverses to core keySym=0x%04x)\n", + keySym, i, dmxKeyCodeToKeySym(dmxLocalCoreKeyboard,i)); + return i; + } + } + return 0; +} + +static int dmxFixup(DevicePtr pDev, int detail, KeySym keySym) +{ + GETDMXLOCALFROMPDEV; + int keyCode; + + if (!dmxLocal->pDevice->key) { + dmxLog(dmxWarning, "dmxFixup: not a keyboard device (%s)\n", + dmxLocal->pDevice->name); + return NoSymbol; + } + if (!keySym) + keySym = dmxKeyCodeToKeySym(dmxLocal, detail); + if (keySym == NoSymbol) + return detail; + keyCode = dmxKeySymToKeyCode(dmxLocalCoreKeyboard, keySym, detail); + + return keyCode ? keyCode : detail; +} + +/** Enqueue an event from the \a pDev device with the + * specified \a type and \a detail. If the event is a KeyPress or + * KeyRelease event, then the \a keySym is also specified. + * + * FIXME: make the code do what the comment says, or remove this comment. + * If \a block is set to \a DMX_BLOCK, then the SIGIO handler will be + * blocked around calls to dmxeqEnqueue(). */ + +void dmxEnqueue(DevicePtr pDev, int type, int detail, KeySym keySym, + XEvent *e, DMXBlockType block) +{ + GETDMXINPUTFROMPDEV; + xEvent xE; + DeviceIntPtr p = dmxLocal->pDevice; + int i, nevents, valuators[3]; + EventListPtr events; + ValuatorMask mask; + + DMXDBG2("dmxEnqueue: Enqueuing type=%d detail=0x%0x\n", type, detail); + + switch (type) { + case KeyPress: + case KeyRelease: + if (!keySym) + keySym = dmxKeyCodeToKeySym(dmxLocal, detail); + if (dmxCheckFunctionKeys(dmxLocal, type, keySym)) + return; + if (dmxLocal->sendsCore && dmxLocal != dmxLocalCoreKeyboard) + xE.u.u.detail = dmxFixup(pDev, detail, keySym); + + GetEventList(&events); + /*ErrorF("KEY %d sym %d\n", detail, (int) keySym);*/ + nevents = GetKeyboardEvents(events, p, type, detail, NULL); + for (i = 0; i < nevents; i++) + mieqEnqueue(p, (InternalEvent*)(events + i)->event); + return; + + case ButtonPress: + case ButtonRelease: + detail = dmxGetButtonMapping(dmxLocal, detail); + valuator_mask_zero(&mask); + GetEventList(&events); + nevents = GetPointerEvents(events, p, type, detail, + POINTER_ABSOLUTE | POINTER_SCREEN, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(p, (InternalEvent*)(events + i)->event); + return; + + case MotionNotify: + GetEventList(&events); + valuators[0] = e->xmotion.x; + valuators[1] = e->xmotion.y; + valuators[2] = e->xmotion.state; /* FIXME: WTF?? */ + valuator_mask_set_range(&mask, 0, 3, valuators); + nevents = GetPointerEvents(events, p, type, detail, + POINTER_ABSOLUTE | POINTER_SCREEN, &mask); + for (i = 0; i < nevents; i++) + mieqEnqueue(p, (InternalEvent*)(events + i)->event); + return; + + case EnterNotify: + case LeaveNotify: + case KeymapNotify: + case MappingNotify: /* This is sent because we change the + * modifier map on the backend/console + * input device so that we have complete + * control of the input device LEDs. */ + return; + default: + if (type == ProximityIn || type == ProximityOut) { + if (dmxLocal->sendsCore) + return; /* Not a core event */ + break; + } + if (type >= LASTEvent) { + if (dmxTranslateAndEnqueueExtEvent(dmxLocal, e, block)) + dmxLogInput(dmxInput, "Unhandled extension event: %d\n", type); + } else { + dmxLogInput(dmxInput, "Unhandled event: %d (%s)\n", + type, dmxEventName(type)); + } + return; + } + +} + +/** A pointer to this routine is passed to low-level input drivers so + * that all special keychecking is unified to this file. This function + * returns 0 if no special keys have been pressed. If the user has + * requested termination of the DMX server, -1 is returned. If the user + * has requested a switch to a VT, then the (1-based) number of that VT + * is returned. */ +int dmxCheckSpecialKeys(DevicePtr pDev, KeySym keySym) +{ + GETDMXINPUTFROMPDEV; + int vt = 0; + unsigned short state = 0; + + if (dmxLocal->sendsCore) + state = XkbStateFieldFromRec(&dmxLocalCoreKeyboard->pDevice->key->xkbInfo->state); + else if (dmxLocal->pDevice->key) + state = XkbStateFieldFromRec(&dmxLocal->pDevice->key->xkbInfo->state); + + if (!dmxLocal->sendsCore) return 0; /* Only for core devices */ + + DMXDBG2("dmxCheckSpecialKeys: keySym=0x%04x state=0x%04x\n", keySym,state); + + if ((state & (ControlMask|Mod1Mask)) != (ControlMask|Mod1Mask)) return 0; + + switch (keySym) { + case XK_F1: + case XK_F2: + case XK_F3: + case XK_F4: + case XK_F5: + case XK_F6: + case XK_F7: + case XK_F8: + case XK_F9: + case XK_F10: + vt = keySym - XK_F1 + 1; + break; + + case XK_F11: + case XK_F12: + vt = keySym - XK_F11 + 11; + break; + + case XK_q: /* To avoid confusion */ + case XK_BackSpace: + case XK_Delete: + case XK_KP_Delete: + dmxLog(dmxInfo, "User request for termination\n"); + dispatchException |= DE_TERMINATE; + return -1; /* Terminate */ + } + + if (vt) { + dmxLog(dmxInfo, "Request to switch to VT %d\n", vt); + dmxInput->vt_switch_pending = vt; + return vt; + } + + return 0; /* Do nothing */ +} diff --git a/xorg-server/hw/kdrive/src/kinput.c b/xorg-server/hw/kdrive/src/kinput.c index e3bc4c523..f21475fb6 100644 --- a/xorg-server/hw/kdrive/src/kinput.c +++ b/xorg-server/hw/kdrive/src/kinput.c @@ -1804,7 +1804,7 @@ KdReleaseAllKeys (void) if (key_is_down(ki->dixdev, key, KEY_POSTED | KEY_PROCESSED)) { KdHandleKeyboardEvent(ki, KeyRelease, key); GetEventList(&kdEvents); - nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, KeyRelease, key); + nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, KeyRelease, key, NULL); for (i = 0; i < nEvents; i++) KdQueueEvent (ki->dixdev, (kdEvents + i)->event); } @@ -1864,7 +1864,7 @@ KdEnqueueKeyboardEvent(KdKeyboardInfo *ki, GetEventList(&kdEvents); - nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, type, key_code); + nEvents = GetKeyboardEvents(kdEvents, ki->dixdev, type, key_code, NULL); for (i = 0; i < nEvents; i++) KdQueueEvent(ki->dixdev, (InternalEvent *)((kdEvents + i)->event)); } diff --git a/xorg-server/hw/xfree86/common/xf86Configure.c b/xorg-server/hw/xfree86/common/xf86Configure.c index bccdd403c..975266943 100644 --- a/xorg-server/hw/xfree86/common/xf86Configure.c +++ b/xorg-server/hw/xfree86/common/xf86Configure.c @@ -1,762 +1,755 @@ -/*
- * Copyright 2000-2002 by Alan Hourihane, Flint Mountain, North Wales.
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the name of Alan Hourihane not be used in
- * advertising or publicity pertaining to distribution of the software without
- * specific, written prior permission. Alan Hourihane makes no representations
- * about the suitability of this software for any purpose. It is provided
- * "as is" without express or implied warranty.
- *
- * ALAN HOURIHANE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
- * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
- * EVENT SHALL ALAN HOURIHANE BE LIABLE FOR ANY SPECIAL, INDIRECT OR
- * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
- * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
- * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
- * PERFORMANCE OF THIS SOFTWARE.
- *
- * Author: Alan Hourihane, alanh@fairlite.demon.co.uk
- *
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include "xf86.h"
-#include "xf86Config.h"
-#include "xf86_OSlib.h"
-#include "xf86Priv.h"
-#define IN_XSERVER
-#include "Configint.h"
-#include "xf86DDC.h"
-#include "xf86pciBus.h"
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
-#include "xf86Bus.h"
-#include "xf86Sbus.h"
-#endif
-#include "misc.h"
-
-typedef struct _DevToConfig {
- GDevRec GDev;
- struct pci_device * pVideo;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- sbusDevicePtr sVideo;
-#endif
- int iDriver;
-} DevToConfigRec, *DevToConfigPtr;
-
-static DevToConfigPtr DevToConfig = NULL;
-static int nDevToConfig = 0, CurrentDriver;
-
-xf86MonPtr ConfiguredMonitor;
-Bool xf86DoConfigurePass1 = TRUE;
-static Bool foundMouse = FALSE;
-
-#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
-static char *DFLT_MOUSE_DEV = "/dev/sysmouse";
-static char *DFLT_MOUSE_PROTO = "auto";
-#elif defined(linux)
-static char DFLT_MOUSE_DEV[] = "/dev/input/mice";
-static char DFLT_MOUSE_PROTO[] = "auto";
-#else
-static char *DFLT_MOUSE_DEV = "/dev/mouse";
-static char *DFLT_MOUSE_PROTO = "auto";
-#endif
-
-/*
- * This is called by the driver, either through xf86Match???Instances() or
- * directly. We allocate a GDevRec and fill it in as much as we can, letting
- * the caller fill in the rest and/or change it as it sees fit.
- */
-GDevPtr
-xf86AddBusDeviceToConfigure(const char *driver, BusType bus, void *busData, int chipset)
-{
- int ret, i, j;
-
- if (!xf86DoConfigure || !xf86DoConfigurePass1)
- return NULL;
-
- /* Check for duplicates */
- for (i = 0; i < nDevToConfig; i++) {
- switch (bus) {
- case BUS_PCI:
- ret = xf86PciConfigure(busData, DevToConfig[i].pVideo);
- break;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- case BUS_SBUS:
- ret = xf86SbusConfigure(busData, DevToConfig[i].sVideo);
- break;
-#endif
- default:
- return NULL;
- }
- if (ret == 0)
- goto out;
- }
-
- /* Allocate new structure occurrence */
- i = nDevToConfig++;
- DevToConfig =
- xnfrealloc(DevToConfig, nDevToConfig * sizeof(DevToConfigRec));
- memset(DevToConfig + i, 0, sizeof(DevToConfigRec));
-
- DevToConfig[i].GDev.chipID =
- DevToConfig[i].GDev.chipRev = DevToConfig[i].GDev.irq = -1;
-
- DevToConfig[i].iDriver = CurrentDriver;
-
- /* Fill in what we know, converting the driver name to lower case */
- DevToConfig[i].GDev.driver = xnfalloc(strlen(driver) + 1);
- for (j = 0; (DevToConfig[i].GDev.driver[j] = tolower(driver[j])); j++);
-
- switch (bus) {
- case BUS_PCI:
- xf86PciConfigureNewDev(busData, DevToConfig[i].pVideo,
- &DevToConfig[i].GDev, &chipset);
- break;
-#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__)
- case BUS_SBUS:
- xf86SbusConfigureNewDev(busData, DevToConfig[i].sVideo,
- &DevToConfig[i].GDev);
- break;
-#endif
- default:
- break;
- }
-
- /* Get driver's available options */
- if (xf86DriverList[CurrentDriver]->AvailableOptions)
- DevToConfig[i].GDev.options = (OptionInfoPtr)
- (*xf86DriverList[CurrentDriver]->AvailableOptions)(chipset,
- bus);
-
- return &DevToConfig[i].GDev;
-
-out:
- return NULL;
-}
-
-static XF86ConfInputPtr
-configureInputSection (void)
-{
- XF86ConfInputPtr mouse = NULL;
- parsePrologue (XF86ConfInputPtr, XF86ConfInputRec)
-
- ptr->inp_identifier = "Keyboard0";
- ptr->inp_driver = "kbd";
- ptr->list.next = NULL;
-
- /* Crude mechanism to auto-detect mouse (os dependent) */
- {
- int fd;
-#ifdef WSCONS_SUPPORT
- fd = open("/dev/wsmouse", 0);
- if (fd >= 0) {
- DFLT_MOUSE_DEV = "/dev/wsmouse";
- DFLT_MOUSE_PROTO = "wsmouse";
- close(fd);
- } else {
- ErrorF("cannot open /dev/wsmouse\n");
- }
-#endif
-
- fd = open(DFLT_MOUSE_DEV, 0);
- if (fd != -1) {
- foundMouse = TRUE;
- close(fd);
- }
- }
-
- mouse = calloc(1, sizeof(XF86ConfInputRec));
- mouse->inp_identifier = "Mouse0";
- mouse->inp_driver = "mouse";
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("Protocol"),
- strdup(DFLT_MOUSE_PROTO));
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("Device"),
- strdup(DFLT_MOUSE_DEV));
- mouse->inp_option_lst =
- xf86addNewOption(mouse->inp_option_lst, strdup("ZAxisMapping"),
- strdup("4 5 6 7"));
- ptr = (XF86ConfInputPtr)xf86addListItem((glp)ptr, (glp)mouse);
- return ptr;
-}
-
-static XF86ConfScreenPtr
-configureScreenSection (int screennum)
-{
- int i;
- int depths[] = { 1, 4, 8, 15, 16, 24/*, 32*/ };
- parsePrologue (XF86ConfScreenPtr, XF86ConfScreenRec)
-
- XNFasprintf(&ptr->scrn_identifier, "Screen%d", screennum);
- XNFasprintf(&ptr->scrn_monitor_str, "Monitor%d", screennum);
- XNFasprintf(&ptr->scrn_device_str, "Card%d", screennum);
-
- for (i=0; i<sizeof(depths)/sizeof(depths[0]); i++)
- {
- XF86ConfDisplayPtr display;
-
- display = calloc(1, sizeof(XF86ConfDisplayRec));
- display->disp_depth = depths[i];
- display->disp_black.red = display->disp_white.red = -1;
- display->disp_black.green = display->disp_white.green = -1;
- display->disp_black.blue = display->disp_white.blue = -1;
- ptr->scrn_display_lst = (XF86ConfDisplayPtr)xf86addListItem(
- (glp)ptr->scrn_display_lst, (glp)display);
- }
-
- return ptr;
-}
-
-static const char*
-optionTypeToString(OptionValueType type)
-{
- switch (type) {
- case OPTV_NONE:
- return "";
- case OPTV_INTEGER:
- return "<i>";
- case OPTV_STRING:
- return "<str>";
- case OPTV_ANYSTR:
- return "[<str>]";
- case OPTV_REAL:
- return "<f>";
- case OPTV_BOOLEAN:
- return "[<bool>]";
- case OPTV_FREQ:
- return "<freq>";
- case OPTV_PERCENT:
- return "<percent>";
- default:
- return "";
- }
-}
-
-static XF86ConfDevicePtr
-configureDeviceSection (int screennum)
-{
- OptionInfoPtr p;
- int i = 0;
- parsePrologue (XF86ConfDevicePtr, XF86ConfDeviceRec)
-
- /* Move device info to parser structure */
- if (asprintf(&ptr->dev_identifier, "Card%d", screennum) == -1)
- ptr->dev_identifier = NULL;
- ptr->dev_chipset = DevToConfig[screennum].GDev.chipset;
- ptr->dev_busid = DevToConfig[screennum].GDev.busID;
- ptr->dev_driver = DevToConfig[screennum].GDev.driver;
- ptr->dev_ramdac = DevToConfig[screennum].GDev.ramdac;
- for (i = 0; (i < MAXDACSPEEDS) && (i < CONF_MAXDACSPEEDS); i++)
- ptr->dev_dacSpeeds[i] = DevToConfig[screennum].GDev.dacSpeeds[i];
- ptr->dev_videoram = DevToConfig[screennum].GDev.videoRam;
- ptr->dev_textclockfreq = DevToConfig[screennum].GDev.textClockFreq;
- ptr->dev_bios_base = DevToConfig[screennum].GDev.BiosBase;
- ptr->dev_mem_base = DevToConfig[screennum].GDev.MemBase;
- ptr->dev_io_base = DevToConfig[screennum].GDev.IOBase;
- ptr->dev_clockchip = DevToConfig[screennum].GDev.clockchip;
- for (i = 0; (i < MAXCLOCKS) && (i < DevToConfig[screennum].GDev.numclocks); i++)
- ptr->dev_clock[i] = DevToConfig[screennum].GDev.clock[i];
- ptr->dev_clocks = i;
- ptr->dev_chipid = DevToConfig[screennum].GDev.chipID;
- ptr->dev_chiprev = DevToConfig[screennum].GDev.chipRev;
- ptr->dev_irq = DevToConfig[screennum].GDev.irq;
-
- /* Make sure older drivers don't segv */
- if (DevToConfig[screennum].GDev.options) {
- /* Fill in the available driver options for people to use */
- const char *descrip =
- " ### Available Driver options are:-\n"
- " ### Values: <i>: integer, <f>: float, "
- "<bool>: \"True\"/\"False\",\n"
- " ### <string>: \"String\", <freq>: \"<f> Hz/kHz/MHz\",\n"
- " ### <percent>: \"<f>%\"\n"
- " ### [arg]: arg optional\n";
- ptr->dev_comment = strdup(descrip);
- if (ptr->dev_comment) {
- for (p = DevToConfig[screennum].GDev.options;
- p->name != NULL; p++) {
- char *p_e;
- const char *prefix = " #Option ";
- const char *middle = " \t# ";
- const char *suffix = "\n";
- const char *opttype = optionTypeToString(p->type);
- char *optname;
- int len = strlen(ptr->dev_comment) + strlen(prefix) +
- strlen(middle) + strlen(suffix) + 1;
-
- if (asprintf(&optname, "\"%s\"", p->name) == -1)
- break;
-
- len += max(20, strlen(optname));
- len += strlen(opttype);
-
- ptr->dev_comment = realloc(ptr->dev_comment, len);
- if (!ptr->dev_comment)
- break;
- p_e = ptr->dev_comment + strlen(ptr->dev_comment);
- sprintf(p_e, "%s%-20s%s%s%s", prefix, optname, middle,
- opttype, suffix);
- free(optname);
- }
- }
- }
-
- return ptr;
-}
-
-static XF86ConfLayoutPtr
-configureLayoutSection (void)
-{
- int scrnum = 0;
- parsePrologue (XF86ConfLayoutPtr, XF86ConfLayoutRec)
-
- ptr->lay_identifier = "X.org Configured";
-
- {
- XF86ConfInputrefPtr iptr;
-
- iptr = malloc (sizeof (XF86ConfInputrefRec));
- iptr->list.next = NULL;
- iptr->iref_option_lst = NULL;
- iptr->iref_inputdev_str = "Mouse0";
- iptr->iref_option_lst =
- xf86addNewOption (iptr->iref_option_lst, strdup("CorePointer"), NULL);
- ptr->lay_input_lst = (XF86ConfInputrefPtr)
- xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr);
- }
-
- {
- XF86ConfInputrefPtr iptr;
-
- iptr = malloc (sizeof (XF86ConfInputrefRec));
- iptr->list.next = NULL;
- iptr->iref_option_lst = NULL;
- iptr->iref_inputdev_str = "Keyboard0";
- iptr->iref_option_lst =
- xf86addNewOption (iptr->iref_option_lst, strdup("CoreKeyboard"), NULL);
- ptr->lay_input_lst = (XF86ConfInputrefPtr)
- xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr);
- }
-
- for (scrnum = 0; scrnum < nDevToConfig; scrnum++) {
- XF86ConfAdjacencyPtr aptr;
-
- aptr = malloc (sizeof (XF86ConfAdjacencyRec));
- aptr->list.next = NULL;
- aptr->adj_x = 0;
- aptr->adj_y = 0;
- aptr->adj_scrnum = scrnum;
- XNFasprintf(&aptr->adj_screen_str, "Screen%d", scrnum);
- if (scrnum == 0) {
- aptr->adj_where = CONF_ADJ_ABSOLUTE;
- aptr->adj_refscreen = NULL;
- }
- else {
- aptr->adj_where = CONF_ADJ_RIGHTOF;
- XNFasprintf(&aptr->adj_refscreen, "Screen%d", scrnum - 1);
- }
- ptr->lay_adjacency_lst =
- (XF86ConfAdjacencyPtr)xf86addListItem((glp)ptr->lay_adjacency_lst,
- (glp)aptr);
- }
-
- return ptr;
-}
-
-static XF86ConfFlagsPtr
-configureFlagsSection (void)
-{
- parsePrologue (XF86ConfFlagsPtr, XF86ConfFlagsRec)
-
- return ptr;
-}
-
-static XF86ConfModulePtr
-configureModuleSection (void)
-{
- char **elist, **el;
- /* Find the list of extension & font modules. */
- const char *esubdirs[] = {
- "extensions",
- "fonts",
- NULL
- };
- parsePrologue (XF86ConfModulePtr, XF86ConfModuleRec)
-
- elist = LoaderListDirs(esubdirs, NULL);
- if (elist) {
- for (el = elist; *el; el++) {
- XF86LoadPtr module;
-
- module = calloc(1, sizeof(XF86LoadRec));
- module->load_name = *el;
- ptr->mod_load_lst = (XF86LoadPtr)xf86addListItem(
- (glp)ptr->mod_load_lst, (glp)module);
- }
- free(elist);
- }
-
- return ptr;
-}
-
-static XF86ConfFilesPtr
-configureFilesSection (void)
-{
- parsePrologue (XF86ConfFilesPtr, XF86ConfFilesRec)
-
- if (xf86ModulePath)
- ptr->file_modulepath = strdup(xf86ModulePath);
- if (defaultFontPath)
- ptr->file_fontpath = strdup(defaultFontPath);
-
- return ptr;
-}
-
-static XF86ConfMonitorPtr
-configureMonitorSection (int screennum)
-{
- parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec)
-
- XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum);
- ptr->mon_vendor = strdup("Monitor Vendor");
- ptr->mon_modelname = strdup("Monitor Model");
-
- return ptr;
-}
-
-/* Initialize Configure Monitor from Detailed Timing Block */
-static void handle_detailed_input(struct detailed_monitor_section *det_mon,
- void *data)
-{
- XF86ConfMonitorPtr ptr = (XF86ConfMonitorPtr) data;
-
- switch (det_mon->type) {
- case DS_NAME:
- ptr->mon_modelname = realloc(ptr->mon_modelname,
- strlen((char*)(det_mon->section.name)) +
- 1);
- strcpy(ptr->mon_modelname,
- (char*)(det_mon->section.name));
- break;
- case DS_RANGES:
- ptr->mon_hsync[ptr->mon_n_hsync].lo =
- det_mon->section.ranges.min_h;
- ptr->mon_hsync[ptr->mon_n_hsync].hi =
- det_mon->section.ranges.max_h;
- ptr->mon_n_vrefresh = 1;
- ptr->mon_vrefresh[ptr->mon_n_hsync].lo =
- det_mon->section.ranges.min_v;
- ptr->mon_vrefresh[ptr->mon_n_hsync].hi =
- det_mon->section.ranges.max_v;
- ptr->mon_n_hsync++;
- default:
- break;
- }
-}
-
-static XF86ConfMonitorPtr
-configureDDCMonitorSection (int screennum)
-{
- int len, mon_width, mon_height;
-#define displaySizeMaxLen 80
- char displaySize_string[displaySizeMaxLen];
- int displaySizeLen;
-
- parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec)
-
- XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum);
- ptr->mon_vendor = strdup(ConfiguredMonitor->vendor.name);
- XNFasprintf(&ptr->mon_modelname, "%x", ConfiguredMonitor->vendor.prod_id);
-
- /* features in centimetres, we want millimetres */
- mon_width = 10 * ConfiguredMonitor->features.hsize ;
- mon_height = 10 * ConfiguredMonitor->features.vsize ;
-
-#ifdef CONFIGURE_DISPLAYSIZE
- ptr->mon_width = mon_width;
- ptr->mon_height = mon_height;
-#else
- if (mon_width && mon_height) {
- /* when values available add DisplaySize option AS A COMMENT */
-
- displaySizeLen = snprintf(displaySize_string, displaySizeMaxLen,
- "\t#DisplaySize\t%5d %5d\t# mm\n",
- mon_width, mon_height);
-
- if (displaySizeLen>0 && displaySizeLen<displaySizeMaxLen) {
- if (ptr->mon_comment) {
- len = strlen(ptr->mon_comment);
- } else {
- len = 0;
- }
- if ((ptr->mon_comment =
- realloc(ptr->mon_comment, len + strlen(displaySize_string) + 1))) {
- strcpy(ptr->mon_comment + len, displaySize_string);
- }
- }
- }
-#endif /* def CONFIGURE_DISPLAYSIZE */
-
- xf86ForEachDetailedBlock(ConfiguredMonitor, handle_detailed_input,
- ptr);
-
- if (ConfiguredMonitor->features.dpms) {
- ptr->mon_option_lst = xf86addNewOption(ptr->mon_option_lst, strdup("DPMS"), NULL);
- }
-
- return ptr;
-}
-
-void
-DoConfigure(void)
-{
- int i,j, screennum = -1;
- char *home = NULL;
- char filename[PATH_MAX];
- char *addslash = "";
- XF86ConfigPtr xf86config = NULL;
- char **vlist, **vl;
- int *dev2screen;
-
- vlist = xf86DriverlistFromCompile();
-
- if (!vlist) {
- ErrorF("Missing output drivers. Configuration failed.\n");
- goto bail;
- }
-
- ErrorF("List of video drivers:\n");
- for (vl = vlist; *vl; vl++)
- ErrorF("\t%s\n", *vl);
-
- /* Load all the drivers that were found. */
- xf86LoadModules(vlist, NULL);
-
- free(vlist);
-
- for (i = 0; i < xf86NumDrivers; i++) {
- xorgHWFlags flags;
- if (!xf86DriverList[i]->driverFunc
- || !xf86DriverList[i]->driverFunc(NULL,
- GET_REQUIRED_HW_INTERFACES,
- &flags)
- || NEED_IO_ENABLED(flags)) {
- xorgHWAccess = TRUE;
- break;
- }
- }
- /* Enable full I/O access */
- if (xorgHWAccess) {
- if(!xf86EnableIO())
- /* oops, we have failed */
- xorgHWAccess = FALSE;
- }
-
- /* Create XF86Config file structure */
- xf86config = calloc(1, sizeof(XF86ConfigRec));
-
- /* Call all of the probe functions, reporting the results. */
- for (CurrentDriver = 0; CurrentDriver < xf86NumDrivers; CurrentDriver++) {
- xorgHWFlags flags;
- Bool found_screen;
- DriverRec * const drv = xf86DriverList[CurrentDriver];
-
- if (!xorgHWAccess) {
- if (!drv->driverFunc
- || !drv->driverFunc( NULL, GET_REQUIRED_HW_INTERFACES, &flags )
- || NEED_IO_ENABLED(flags))
- continue;
- }
-
- found_screen = xf86CallDriverProbe( drv, TRUE );
- if ( found_screen && drv->Identify ) {
- (*drv->Identify)(0);
- }
- }
-
- if (nDevToConfig <= 0) {
- ErrorF("No devices to configure. Configuration failed.\n");
- goto bail;
- }
-
- /* Add device, monitor and screen sections for detected devices */
- for (screennum = 0; screennum < nDevToConfig; screennum++) {
- XF86ConfDevicePtr DevicePtr;
- XF86ConfMonitorPtr MonitorPtr;
- XF86ConfScreenPtr ScreenPtr;
-
- DevicePtr = configureDeviceSection(screennum);
- xf86config->conf_device_lst = (XF86ConfDevicePtr)xf86addListItem(
- (glp)xf86config->conf_device_lst, (glp)DevicePtr);
- MonitorPtr = configureMonitorSection(screennum);
- xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem(
- (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr);
- ScreenPtr = configureScreenSection(screennum);
- xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem(
- (glp)xf86config->conf_screen_lst, (glp)ScreenPtr);
- }
-
- xf86config->conf_files = configureFilesSection();
- xf86config->conf_modules = configureModuleSection();
- xf86config->conf_flags = configureFlagsSection();
- xf86config->conf_videoadaptor_lst = NULL;
- xf86config->conf_modes_lst = NULL;
- xf86config->conf_vendor_lst = NULL;
- xf86config->conf_dri = NULL;
- xf86config->conf_input_lst = configureInputSection();
- xf86config->conf_layout_lst = configureLayoutSection();
-
- home = getenv("HOME");
- if ((home == NULL) || (home[0] == '\0')) {
- home = "/";
- } else {
- /* Determine if trailing slash is present or needed */
- int l = strlen(home);
-
- if (home[l-1] != '/') {
- addslash = "/";
- }
- }
-
- snprintf(filename, sizeof(filename), "%s%s" XF86CONFIGFILE ".new",
- home, addslash);
-
- if (xf86writeConfigFile(filename, xf86config) == 0) {
- xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n",
- filename, strerror(errno));
- goto bail;
- }
-
- xf86DoConfigurePass1 = FALSE;
- /* Try to get DDC information filled in */
- xf86ConfigFile = filename;
- if (xf86HandleConfigFile(FALSE) != CONFIG_OK) {
- goto bail;
- }
-
- xf86DoConfigurePass1 = FALSE;
-
- dev2screen = xnfcalloc(1,xf86NumDrivers*sizeof(int));
-
- {
- Bool *driverProbed = xnfcalloc(1,xf86NumDrivers*sizeof(Bool));
- for (screennum = 0; screennum < nDevToConfig; screennum++) {
- int k,l,n,oldNumScreens;
-
- i = DevToConfig[screennum].iDriver;
-
- if (driverProbed[i]) continue;
- driverProbed[i] = TRUE;
-
- oldNumScreens = xf86NumScreens;
-
- xf86CallDriverProbe( xf86DriverList[i], FALSE );
-
- /* reorder */
- k = screennum > 0 ? screennum : 1;
- for (l = oldNumScreens; l < xf86NumScreens; l++) {
- /* is screen primary? */
- Bool primary = FALSE;
- for (n = 0; n<xf86Screens[l]->numEntities; n++) {
- if (xf86IsEntityPrimary(xf86Screens[l]->entityList[n])) {
- dev2screen[0] = l;
- primary = TRUE;
- break;
- }
- }
- if (primary) continue;
- /* not primary: assign it to next device of same driver */
- /*
- * NOTE: we assume that devices in DevToConfig
- * and xf86Screens[] have the same order except
- * for the primary device which always comes first.
- */
- for (; k < nDevToConfig; k++) {
- if (DevToConfig[k].iDriver == i) {
- dev2screen[k++] = l;
- break;
- }
- }
- }
- }
- free(driverProbed);
- }
-
-
- if (nDevToConfig != xf86NumScreens) {
- ErrorF("Number of created screens does not match number of detected"
- " devices.\n Configuration failed.\n");
- goto bail;
- }
-
- xf86PostProbe();
-
- for (j = 0; j < xf86NumScreens; j++) {
- xf86Screens[j]->scrnIndex = j;
- }
-
- xf86freeMonitorList(xf86config->conf_monitor_lst);
- xf86config->conf_monitor_lst = NULL;
- xf86freeScreenList(xf86config->conf_screen_lst);
- xf86config->conf_screen_lst = NULL;
- for (j = 0; j < xf86NumScreens; j++) {
- XF86ConfMonitorPtr MonitorPtr;
- XF86ConfScreenPtr ScreenPtr;
-
- ConfiguredMonitor = NULL;
-
- if ((*xf86Screens[dev2screen[j]]->PreInit)(xf86Screens[dev2screen[j]],
- PROBE_DETECT) &&
- ConfiguredMonitor) {
- MonitorPtr = configureDDCMonitorSection(j);
- } else {
- MonitorPtr = configureMonitorSection(j);
- }
- ScreenPtr = configureScreenSection(j);
- xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem(
- (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr);
- xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem(
- (glp)xf86config->conf_screen_lst, (glp)ScreenPtr);
- }
-
- if (xf86writeConfigFile(filename, xf86config) == 0) {
- xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n",
- filename, strerror(errno));
- goto bail;
- }
-
- ErrorF("\n");
-
- if (!foundMouse) {
- ErrorF("\n"__XSERVERNAME__" is not able to detect your mouse.\n"
- "Edit the file and correct the Device.\n");
- } else {
- ErrorF("\n"__XSERVERNAME__" detected your mouse at device %s.\n"
- "Please check your config if the mouse is still not\n"
- "operational, as by default "__XSERVERNAME__
- " tries to autodetect\n"
- "the protocol.\n",DFLT_MOUSE_DEV);
- }
-
- if (xf86NumScreens > 1) {
- ErrorF("\n"__XSERVERNAME__
- " has configured a multihead system, please check your config.\n");
- }
-
- ErrorF("\nYour %s file is %s\n\n", XF86CONFIGFILE ,filename);
- ErrorF("To test the server, run 'X -config %s'\n\n", filename);
-
-bail:
- OsCleanup(TRUE);
- AbortDDX();
- fflush(stderr);
- exit(0);
-}
+/* + * Copyright 2000-2002 by Alan Hourihane, Flint Mountain, North Wales. + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Alan Hourihane not be used in + * advertising or publicity pertaining to distribution of the software without + * specific, written prior permission. Alan Hourihane makes no representations + * about the suitability of this software for any purpose. It is provided + * "as is" without express or implied warranty. + * + * ALAN HOURIHANE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, + * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO + * EVENT SHALL ALAN HOURIHANE BE LIABLE FOR ANY SPECIAL, INDIRECT OR + * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THIS SOFTWARE. + * + * Author: Alan Hourihane, alanh@fairlite.demon.co.uk + * + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include "xf86.h" +#include "xf86Config.h" +#include "xf86_OSlib.h" +#include "xf86Priv.h" +#define IN_XSERVER +#include "Configint.h" +#include "xf86DDC.h" +#include "xf86pciBus.h" +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) +#include "xf86Bus.h" +#include "xf86Sbus.h" +#endif +#include "misc.h" + +typedef struct _DevToConfig { + GDevRec GDev; + struct pci_device * pVideo; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + sbusDevicePtr sVideo; +#endif + int iDriver; +} DevToConfigRec, *DevToConfigPtr; + +static DevToConfigPtr DevToConfig = NULL; +static int nDevToConfig = 0, CurrentDriver; + +xf86MonPtr ConfiguredMonitor; +Bool xf86DoConfigurePass1 = TRUE; +static Bool foundMouse = FALSE; + +#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) +static char *DFLT_MOUSE_DEV = "/dev/sysmouse"; +static char *DFLT_MOUSE_PROTO = "auto"; +#elif defined(linux) +static char DFLT_MOUSE_DEV[] = "/dev/input/mice"; +static char DFLT_MOUSE_PROTO[] = "auto"; +#elif defined(WSCONS_SUPPORT) +static char *DFLT_MOUSE_DEV = "/dev/wsmouse"; +static char *DFLT_MOUSE_PROTO = "wsmouse"; +#else +static char *DFLT_MOUSE_DEV = "/dev/mouse"; +static char *DFLT_MOUSE_PROTO = "auto"; +#endif + +/* + * This is called by the driver, either through xf86Match???Instances() or + * directly. We allocate a GDevRec and fill it in as much as we can, letting + * the caller fill in the rest and/or change it as it sees fit. + */ +GDevPtr +xf86AddBusDeviceToConfigure(const char *driver, BusType bus, void *busData, int chipset) +{ + int ret, i, j; + + if (!xf86DoConfigure || !xf86DoConfigurePass1) + return NULL; + + /* Check for duplicates */ + for (i = 0; i < nDevToConfig; i++) { + switch (bus) { + case BUS_PCI: + ret = xf86PciConfigure(busData, DevToConfig[i].pVideo); + break; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + case BUS_SBUS: + ret = xf86SbusConfigure(busData, DevToConfig[i].sVideo); + break; +#endif + default: + return NULL; + } + if (ret == 0) + goto out; + } + + /* Allocate new structure occurrence */ + i = nDevToConfig++; + DevToConfig = + xnfrealloc(DevToConfig, nDevToConfig * sizeof(DevToConfigRec)); + memset(DevToConfig + i, 0, sizeof(DevToConfigRec)); + + DevToConfig[i].GDev.chipID = + DevToConfig[i].GDev.chipRev = DevToConfig[i].GDev.irq = -1; + + DevToConfig[i].iDriver = CurrentDriver; + + /* Fill in what we know, converting the driver name to lower case */ + DevToConfig[i].GDev.driver = xnfalloc(strlen(driver) + 1); + for (j = 0; (DevToConfig[i].GDev.driver[j] = tolower(driver[j])); j++); + + switch (bus) { + case BUS_PCI: + xf86PciConfigureNewDev(busData, DevToConfig[i].pVideo, + &DevToConfig[i].GDev, &chipset); + break; +#if (defined(__sparc__) || defined(__sparc)) && !defined(__OpenBSD__) + case BUS_SBUS: + xf86SbusConfigureNewDev(busData, DevToConfig[i].sVideo, + &DevToConfig[i].GDev); + break; +#endif + default: + break; + } + + /* Get driver's available options */ + if (xf86DriverList[CurrentDriver]->AvailableOptions) + DevToConfig[i].GDev.options = (OptionInfoPtr) + (*xf86DriverList[CurrentDriver]->AvailableOptions)(chipset, + bus); + + return &DevToConfig[i].GDev; + +out: + return NULL; +} + +static XF86ConfInputPtr +configureInputSection (void) +{ + XF86ConfInputPtr mouse = NULL; + parsePrologue (XF86ConfInputPtr, XF86ConfInputRec) + + ptr->inp_identifier = "Keyboard0"; + ptr->inp_driver = "kbd"; + ptr->list.next = NULL; + + /* Crude mechanism to auto-detect mouse (os dependent) */ + { + int fd; + + fd = open(DFLT_MOUSE_DEV, 0); + if (fd != -1) { + foundMouse = TRUE; + close(fd); + } + } + + mouse = calloc(1, sizeof(XF86ConfInputRec)); + mouse->inp_identifier = "Mouse0"; + mouse->inp_driver = "mouse"; + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("Protocol"), + strdup(DFLT_MOUSE_PROTO)); + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("Device"), + strdup(DFLT_MOUSE_DEV)); + mouse->inp_option_lst = + xf86addNewOption(mouse->inp_option_lst, strdup("ZAxisMapping"), + strdup("4 5 6 7")); + ptr = (XF86ConfInputPtr)xf86addListItem((glp)ptr, (glp)mouse); + return ptr; +} + +static XF86ConfScreenPtr +configureScreenSection (int screennum) +{ + int i; + int depths[] = { 1, 4, 8, 15, 16, 24/*, 32*/ }; + parsePrologue (XF86ConfScreenPtr, XF86ConfScreenRec) + + XNFasprintf(&ptr->scrn_identifier, "Screen%d", screennum); + XNFasprintf(&ptr->scrn_monitor_str, "Monitor%d", screennum); + XNFasprintf(&ptr->scrn_device_str, "Card%d", screennum); + + for (i=0; i<sizeof(depths)/sizeof(depths[0]); i++) + { + XF86ConfDisplayPtr display; + + display = calloc(1, sizeof(XF86ConfDisplayRec)); + display->disp_depth = depths[i]; + display->disp_black.red = display->disp_white.red = -1; + display->disp_black.green = display->disp_white.green = -1; + display->disp_black.blue = display->disp_white.blue = -1; + ptr->scrn_display_lst = (XF86ConfDisplayPtr)xf86addListItem( + (glp)ptr->scrn_display_lst, (glp)display); + } + + return ptr; +} + +static const char* +optionTypeToString(OptionValueType type) +{ + switch (type) { + case OPTV_NONE: + return ""; + case OPTV_INTEGER: + return "<i>"; + case OPTV_STRING: + return "<str>"; + case OPTV_ANYSTR: + return "[<str>]"; + case OPTV_REAL: + return "<f>"; + case OPTV_BOOLEAN: + return "[<bool>]"; + case OPTV_FREQ: + return "<freq>"; + case OPTV_PERCENT: + return "<percent>"; + default: + return ""; + } +} + +static XF86ConfDevicePtr +configureDeviceSection (int screennum) +{ + OptionInfoPtr p; + int i = 0; + parsePrologue (XF86ConfDevicePtr, XF86ConfDeviceRec) + + /* Move device info to parser structure */ + if (asprintf(&ptr->dev_identifier, "Card%d", screennum) == -1) + ptr->dev_identifier = NULL; + ptr->dev_chipset = DevToConfig[screennum].GDev.chipset; + ptr->dev_busid = DevToConfig[screennum].GDev.busID; + ptr->dev_driver = DevToConfig[screennum].GDev.driver; + ptr->dev_ramdac = DevToConfig[screennum].GDev.ramdac; + for (i = 0; (i < MAXDACSPEEDS) && (i < CONF_MAXDACSPEEDS); i++) + ptr->dev_dacSpeeds[i] = DevToConfig[screennum].GDev.dacSpeeds[i]; + ptr->dev_videoram = DevToConfig[screennum].GDev.videoRam; + ptr->dev_textclockfreq = DevToConfig[screennum].GDev.textClockFreq; + ptr->dev_bios_base = DevToConfig[screennum].GDev.BiosBase; + ptr->dev_mem_base = DevToConfig[screennum].GDev.MemBase; + ptr->dev_io_base = DevToConfig[screennum].GDev.IOBase; + ptr->dev_clockchip = DevToConfig[screennum].GDev.clockchip; + for (i = 0; (i < MAXCLOCKS) && (i < DevToConfig[screennum].GDev.numclocks); i++) + ptr->dev_clock[i] = DevToConfig[screennum].GDev.clock[i]; + ptr->dev_clocks = i; + ptr->dev_chipid = DevToConfig[screennum].GDev.chipID; + ptr->dev_chiprev = DevToConfig[screennum].GDev.chipRev; + ptr->dev_irq = DevToConfig[screennum].GDev.irq; + + /* Make sure older drivers don't segv */ + if (DevToConfig[screennum].GDev.options) { + /* Fill in the available driver options for people to use */ + const char *descrip = + " ### Available Driver options are:-\n" + " ### Values: <i>: integer, <f>: float, " + "<bool>: \"True\"/\"False\",\n" + " ### <string>: \"String\", <freq>: \"<f> Hz/kHz/MHz\",\n" + " ### <percent>: \"<f>%\"\n" + " ### [arg]: arg optional\n"; + ptr->dev_comment = strdup(descrip); + if (ptr->dev_comment) { + for (p = DevToConfig[screennum].GDev.options; + p->name != NULL; p++) { + char *p_e; + const char *prefix = " #Option "; + const char *middle = " \t# "; + const char *suffix = "\n"; + const char *opttype = optionTypeToString(p->type); + char *optname; + int len = strlen(ptr->dev_comment) + strlen(prefix) + + strlen(middle) + strlen(suffix) + 1; + + if (asprintf(&optname, "\"%s\"", p->name) == -1) + break; + + len += max(20, strlen(optname)); + len += strlen(opttype); + + ptr->dev_comment = realloc(ptr->dev_comment, len); + if (!ptr->dev_comment) + break; + p_e = ptr->dev_comment + strlen(ptr->dev_comment); + sprintf(p_e, "%s%-20s%s%s%s", prefix, optname, middle, + opttype, suffix); + free(optname); + } + } + } + + return ptr; +} + +static XF86ConfLayoutPtr +configureLayoutSection (void) +{ + int scrnum = 0; + parsePrologue (XF86ConfLayoutPtr, XF86ConfLayoutRec) + + ptr->lay_identifier = "X.org Configured"; + + { + XF86ConfInputrefPtr iptr; + + iptr = malloc (sizeof (XF86ConfInputrefRec)); + iptr->list.next = NULL; + iptr->iref_option_lst = NULL; + iptr->iref_inputdev_str = "Mouse0"; + iptr->iref_option_lst = + xf86addNewOption (iptr->iref_option_lst, strdup("CorePointer"), NULL); + ptr->lay_input_lst = (XF86ConfInputrefPtr) + xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr); + } + + { + XF86ConfInputrefPtr iptr; + + iptr = malloc (sizeof (XF86ConfInputrefRec)); + iptr->list.next = NULL; + iptr->iref_option_lst = NULL; + iptr->iref_inputdev_str = "Keyboard0"; + iptr->iref_option_lst = + xf86addNewOption (iptr->iref_option_lst, strdup("CoreKeyboard"), NULL); + ptr->lay_input_lst = (XF86ConfInputrefPtr) + xf86addListItem ((glp) ptr->lay_input_lst, (glp) iptr); + } + + for (scrnum = 0; scrnum < nDevToConfig; scrnum++) { + XF86ConfAdjacencyPtr aptr; + + aptr = malloc (sizeof (XF86ConfAdjacencyRec)); + aptr->list.next = NULL; + aptr->adj_x = 0; + aptr->adj_y = 0; + aptr->adj_scrnum = scrnum; + XNFasprintf(&aptr->adj_screen_str, "Screen%d", scrnum); + if (scrnum == 0) { + aptr->adj_where = CONF_ADJ_ABSOLUTE; + aptr->adj_refscreen = NULL; + } + else { + aptr->adj_where = CONF_ADJ_RIGHTOF; + XNFasprintf(&aptr->adj_refscreen, "Screen%d", scrnum - 1); + } + ptr->lay_adjacency_lst = + (XF86ConfAdjacencyPtr)xf86addListItem((glp)ptr->lay_adjacency_lst, + (glp)aptr); + } + + return ptr; +} + +static XF86ConfFlagsPtr +configureFlagsSection (void) +{ + parsePrologue (XF86ConfFlagsPtr, XF86ConfFlagsRec) + + return ptr; +} + +static XF86ConfModulePtr +configureModuleSection (void) +{ + char **elist, **el; + /* Find the list of extension & font modules. */ + const char *esubdirs[] = { + "extensions", + "fonts", + NULL + }; + parsePrologue (XF86ConfModulePtr, XF86ConfModuleRec) + + elist = LoaderListDirs(esubdirs, NULL); + if (elist) { + for (el = elist; *el; el++) { + XF86LoadPtr module; + + module = calloc(1, sizeof(XF86LoadRec)); + module->load_name = *el; + ptr->mod_load_lst = (XF86LoadPtr)xf86addListItem( + (glp)ptr->mod_load_lst, (glp)module); + } + free(elist); + } + + return ptr; +} + +static XF86ConfFilesPtr +configureFilesSection (void) +{ + parsePrologue (XF86ConfFilesPtr, XF86ConfFilesRec) + + if (xf86ModulePath) + ptr->file_modulepath = strdup(xf86ModulePath); + if (defaultFontPath) + ptr->file_fontpath = strdup(defaultFontPath); + + return ptr; +} + +static XF86ConfMonitorPtr +configureMonitorSection (int screennum) +{ + parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec) + + XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum); + ptr->mon_vendor = strdup("Monitor Vendor"); + ptr->mon_modelname = strdup("Monitor Model"); + + return ptr; +} + +/* Initialize Configure Monitor from Detailed Timing Block */ +static void handle_detailed_input(struct detailed_monitor_section *det_mon, + void *data) +{ + XF86ConfMonitorPtr ptr = (XF86ConfMonitorPtr) data; + + switch (det_mon->type) { + case DS_NAME: + ptr->mon_modelname = realloc(ptr->mon_modelname, + strlen((char*)(det_mon->section.name)) + + 1); + strcpy(ptr->mon_modelname, + (char*)(det_mon->section.name)); + break; + case DS_RANGES: + ptr->mon_hsync[ptr->mon_n_hsync].lo = + det_mon->section.ranges.min_h; + ptr->mon_hsync[ptr->mon_n_hsync].hi = + det_mon->section.ranges.max_h; + ptr->mon_n_vrefresh = 1; + ptr->mon_vrefresh[ptr->mon_n_hsync].lo = + det_mon->section.ranges.min_v; + ptr->mon_vrefresh[ptr->mon_n_hsync].hi = + det_mon->section.ranges.max_v; + ptr->mon_n_hsync++; + default: + break; + } +} + +static XF86ConfMonitorPtr +configureDDCMonitorSection (int screennum) +{ + int len, mon_width, mon_height; +#define displaySizeMaxLen 80 + char displaySize_string[displaySizeMaxLen]; + int displaySizeLen; + + parsePrologue (XF86ConfMonitorPtr, XF86ConfMonitorRec) + + XNFasprintf(&ptr->mon_identifier, "Monitor%d", screennum); + ptr->mon_vendor = strdup(ConfiguredMonitor->vendor.name); + XNFasprintf(&ptr->mon_modelname, "%x", ConfiguredMonitor->vendor.prod_id); + + /* features in centimetres, we want millimetres */ + mon_width = 10 * ConfiguredMonitor->features.hsize ; + mon_height = 10 * ConfiguredMonitor->features.vsize ; + +#ifdef CONFIGURE_DISPLAYSIZE + ptr->mon_width = mon_width; + ptr->mon_height = mon_height; +#else + if (mon_width && mon_height) { + /* when values available add DisplaySize option AS A COMMENT */ + + displaySizeLen = snprintf(displaySize_string, displaySizeMaxLen, + "\t#DisplaySize\t%5d %5d\t# mm\n", + mon_width, mon_height); + + if (displaySizeLen>0 && displaySizeLen<displaySizeMaxLen) { + if (ptr->mon_comment) { + len = strlen(ptr->mon_comment); + } else { + len = 0; + } + if ((ptr->mon_comment = + realloc(ptr->mon_comment, len + strlen(displaySize_string) + 1))) { + strcpy(ptr->mon_comment + len, displaySize_string); + } + } + } +#endif /* def CONFIGURE_DISPLAYSIZE */ + + xf86ForEachDetailedBlock(ConfiguredMonitor, handle_detailed_input, + ptr); + + if (ConfiguredMonitor->features.dpms) { + ptr->mon_option_lst = xf86addNewOption(ptr->mon_option_lst, strdup("DPMS"), NULL); + } + + return ptr; +} + +void +DoConfigure(void) +{ + int i,j, screennum = -1; + char *home = NULL; + char filename[PATH_MAX]; + char *addslash = ""; + XF86ConfigPtr xf86config = NULL; + char **vlist, **vl; + int *dev2screen; + + vlist = xf86DriverlistFromCompile(); + + if (!vlist) { + ErrorF("Missing output drivers. Configuration failed.\n"); + goto bail; + } + + ErrorF("List of video drivers:\n"); + for (vl = vlist; *vl; vl++) + ErrorF("\t%s\n", *vl); + + /* Load all the drivers that were found. */ + xf86LoadModules(vlist, NULL); + + free(vlist); + + for (i = 0; i < xf86NumDrivers; i++) { + xorgHWFlags flags; + if (!xf86DriverList[i]->driverFunc + || !xf86DriverList[i]->driverFunc(NULL, + GET_REQUIRED_HW_INTERFACES, + &flags) + || NEED_IO_ENABLED(flags)) { + xorgHWAccess = TRUE; + break; + } + } + /* Enable full I/O access */ + if (xorgHWAccess) { + if(!xf86EnableIO()) + /* oops, we have failed */ + xorgHWAccess = FALSE; + } + + /* Create XF86Config file structure */ + xf86config = calloc(1, sizeof(XF86ConfigRec)); + + /* Call all of the probe functions, reporting the results. */ + for (CurrentDriver = 0; CurrentDriver < xf86NumDrivers; CurrentDriver++) { + xorgHWFlags flags; + Bool found_screen; + DriverRec * const drv = xf86DriverList[CurrentDriver]; + + if (!xorgHWAccess) { + if (!drv->driverFunc + || !drv->driverFunc( NULL, GET_REQUIRED_HW_INTERFACES, &flags ) + || NEED_IO_ENABLED(flags)) + continue; + } + + found_screen = xf86CallDriverProbe( drv, TRUE ); + if ( found_screen && drv->Identify ) { + (*drv->Identify)(0); + } + } + + if (nDevToConfig <= 0) { + ErrorF("No devices to configure. Configuration failed.\n"); + goto bail; + } + + /* Add device, monitor and screen sections for detected devices */ + for (screennum = 0; screennum < nDevToConfig; screennum++) { + XF86ConfDevicePtr DevicePtr; + XF86ConfMonitorPtr MonitorPtr; + XF86ConfScreenPtr ScreenPtr; + + DevicePtr = configureDeviceSection(screennum); + xf86config->conf_device_lst = (XF86ConfDevicePtr)xf86addListItem( + (glp)xf86config->conf_device_lst, (glp)DevicePtr); + MonitorPtr = configureMonitorSection(screennum); + xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem( + (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr); + ScreenPtr = configureScreenSection(screennum); + xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem( + (glp)xf86config->conf_screen_lst, (glp)ScreenPtr); + } + + xf86config->conf_files = configureFilesSection(); + xf86config->conf_modules = configureModuleSection(); + xf86config->conf_flags = configureFlagsSection(); + xf86config->conf_videoadaptor_lst = NULL; + xf86config->conf_modes_lst = NULL; + xf86config->conf_vendor_lst = NULL; + xf86config->conf_dri = NULL; + xf86config->conf_input_lst = configureInputSection(); + xf86config->conf_layout_lst = configureLayoutSection(); + + home = getenv("HOME"); + if ((home == NULL) || (home[0] == '\0')) { + home = "/"; + } else { + /* Determine if trailing slash is present or needed */ + int l = strlen(home); + + if (home[l-1] != '/') { + addslash = "/"; + } + } + + snprintf(filename, sizeof(filename), "%s%s" XF86CONFIGFILE ".new", + home, addslash); + + if (xf86writeConfigFile(filename, xf86config) == 0) { + xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n", + filename, strerror(errno)); + goto bail; + } + + xf86DoConfigurePass1 = FALSE; + /* Try to get DDC information filled in */ + xf86ConfigFile = filename; + if (xf86HandleConfigFile(FALSE) != CONFIG_OK) { + goto bail; + } + + xf86DoConfigurePass1 = FALSE; + + dev2screen = xnfcalloc(1,xf86NumDrivers*sizeof(int)); + + { + Bool *driverProbed = xnfcalloc(1,xf86NumDrivers*sizeof(Bool)); + for (screennum = 0; screennum < nDevToConfig; screennum++) { + int k,l,n,oldNumScreens; + + i = DevToConfig[screennum].iDriver; + + if (driverProbed[i]) continue; + driverProbed[i] = TRUE; + + oldNumScreens = xf86NumScreens; + + xf86CallDriverProbe( xf86DriverList[i], FALSE ); + + /* reorder */ + k = screennum > 0 ? screennum : 1; + for (l = oldNumScreens; l < xf86NumScreens; l++) { + /* is screen primary? */ + Bool primary = FALSE; + for (n = 0; n<xf86Screens[l]->numEntities; n++) { + if (xf86IsEntityPrimary(xf86Screens[l]->entityList[n])) { + dev2screen[0] = l; + primary = TRUE; + break; + } + } + if (primary) continue; + /* not primary: assign it to next device of same driver */ + /* + * NOTE: we assume that devices in DevToConfig + * and xf86Screens[] have the same order except + * for the primary device which always comes first. + */ + for (; k < nDevToConfig; k++) { + if (DevToConfig[k].iDriver == i) { + dev2screen[k++] = l; + break; + } + } + } + } + free(driverProbed); + } + + + if (nDevToConfig != xf86NumScreens) { + ErrorF("Number of created screens does not match number of detected" + " devices.\n Configuration failed.\n"); + goto bail; + } + + xf86PostProbe(); + + for (j = 0; j < xf86NumScreens; j++) { + xf86Screens[j]->scrnIndex = j; + } + + xf86freeMonitorList(xf86config->conf_monitor_lst); + xf86config->conf_monitor_lst = NULL; + xf86freeScreenList(xf86config->conf_screen_lst); + xf86config->conf_screen_lst = NULL; + for (j = 0; j < xf86NumScreens; j++) { + XF86ConfMonitorPtr MonitorPtr; + XF86ConfScreenPtr ScreenPtr; + + ConfiguredMonitor = NULL; + + if ((*xf86Screens[dev2screen[j]]->PreInit)(xf86Screens[dev2screen[j]], + PROBE_DETECT) && + ConfiguredMonitor) { + MonitorPtr = configureDDCMonitorSection(j); + } else { + MonitorPtr = configureMonitorSection(j); + } + ScreenPtr = configureScreenSection(j); + xf86config->conf_monitor_lst = (XF86ConfMonitorPtr)xf86addListItem( + (glp)xf86config->conf_monitor_lst, (glp)MonitorPtr); + xf86config->conf_screen_lst = (XF86ConfScreenPtr)xf86addListItem( + (glp)xf86config->conf_screen_lst, (glp)ScreenPtr); + } + + if (xf86writeConfigFile(filename, xf86config) == 0) { + xf86Msg(X_ERROR, "Unable to write config file: \"%s\": %s\n", + filename, strerror(errno)); + goto bail; + } + + ErrorF("\n"); + + if (!foundMouse) { + ErrorF("\n"__XSERVERNAME__" is not able to detect your mouse.\n" + "Edit the file and correct the Device.\n"); + } else { + ErrorF("\n"__XSERVERNAME__" detected your mouse at device %s.\n" + "Please check your config if the mouse is still not\n" + "operational, as by default "__XSERVERNAME__ + " tries to autodetect\n" + "the protocol.\n",DFLT_MOUSE_DEV); + } + + if (xf86NumScreens > 1) { + ErrorF("\n"__XSERVERNAME__ + " has configured a multihead system, please check your config.\n"); + } + + ErrorF("\nYour %s file is %s\n\n", XF86CONFIGFILE ,filename); + ErrorF("To test the server, run 'X -config %s'\n\n", filename); + +bail: + OsCleanup(TRUE); + AbortDDX(); + fflush(stderr); + exit(0); +} diff --git a/xorg-server/hw/xfree86/common/xf86Events.c b/xorg-server/hw/xfree86/common/xf86Events.c index 84c0d182a..3006ad183 100644 --- a/xorg-server/hw/xfree86/common/xf86Events.c +++ b/xorg-server/hw/xfree86/common/xf86Events.c @@ -399,7 +399,7 @@ xf86ReleaseKeys(DeviceIntPtr pDev) i++) { if (key_is_down(pDev, i, KEY_POSTED)) { sigstate = xf86BlockSIGIO (); - nevents = GetKeyboardEvents(xf86Events, pDev, KeyRelease, i); + nevents = GetKeyboardEvents(xf86Events, pDev, KeyRelease, i, NULL); for (j = 0; j < nevents; j++) mieqEnqueue(pDev, (InternalEvent*)(xf86Events + j)->event); xf86UnblockSIGIO(sigstate); diff --git a/xorg-server/hw/xfree86/common/xf86Xinput.c b/xorg-server/hw/xfree86/common/xf86Xinput.c index ae22ef268..ef4542c5f 100644 --- a/xorg-server/hw/xfree86/common/xf86Xinput.c +++ b/xorg-server/hw/xfree86/common/xf86Xinput.c @@ -1013,7 +1013,6 @@ xf86PostMotionEventM(DeviceIntPtr device, const ValuatorMask *mask) { int i = 0, nevents = 0; - DeviceEvent *event; int flags = 0; if (valuator_mask_num_valuators(mask) > 0) @@ -1054,7 +1053,6 @@ xf86PostMotionEventM(DeviceIntPtr device, nevents = GetPointerEvents(xf86Events, device, MotionNotify, 0, flags, mask); for (i = 0; i < nevents; i++) { - event = (DeviceEvent*)((xf86Events + i)->event); mieqEnqueue(device, (InternalEvent*)((xf86Events + i)->event)); } } @@ -1252,16 +1250,9 @@ xf86PostKeyEventM(DeviceIntPtr device, } #endif - if (is_absolute) { - nevents = GetKeyboardValuatorEvents(xf86Events, device, - is_down ? KeyPress : KeyRelease, - key_code, mask); - } - else { - nevents = GetKeyboardEvents(xf86Events, device, - is_down ? KeyPress : KeyRelease, - key_code); - } + nevents = GetKeyboardEvents(xf86Events, device, + is_down ? KeyPress : KeyRelease, + key_code, mask); for (i = 0; i < nevents; i++) mieqEnqueue(device, (InternalEvent*)((xf86Events + i)->event)); diff --git a/xorg-server/hw/xfree86/os-support/linux/lnx_init.c b/xorg-server/hw/xfree86/os-support/linux/lnx_init.c index d1f29d909..77dfb2f16 100644 --- a/xorg-server/hw/xfree86/os-support/linux/lnx_init.c +++ b/xorg-server/hw/xfree86/os-support/linux/lnx_init.c @@ -1,330 +1,345 @@ -/*
- * Copyright 1992 by Orest Zborowski <obz@Kodak.com>
- * Copyright 1993 by David Wexelblat <dwex@goblin.org>
- *
- * Permission to use, copy, modify, distribute, and sell this software and its
- * documentation for any purpose is hereby granted without fee, provided that
- * the above copyright notice appear in all copies and that both that
- * copyright notice and this permission notice appear in supporting
- * documentation, and that the names of Orest Zborowski and David Wexelblat
- * not be used in advertising or publicity pertaining to distribution of
- * the software without specific, written prior permission. Orest Zborowski
- * and David Wexelblat make no representations about the suitability of this
- * software for any purpose. It is provided "as is" without express or
- * implied warranty.
- *
- * OREST ZBOROWSKI AND DAVID WEXELBLAT DISCLAIMS ALL WARRANTIES WITH REGARD
- * TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
- * FITNESS, IN NO EVENT SHALL OREST ZBOROWSKI OR DAVID WEXELBLAT BE LIABLE
- * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- *
- */
-
-#ifdef HAVE_XORG_CONFIG_H
-#include <xorg-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xmd.h>
-
-#include "compiler.h"
-
-#include "xf86.h"
-#include "xf86Priv.h"
-#include "xf86_OSlib.h"
-
-#include <sys/stat.h>
-
-static Bool KeepTty = FALSE;
-static Bool VTSwitch = TRUE;
-static Bool ShareVTs = FALSE;
-static int activeVT = -1;
-
-static char vtname[11];
-static struct termios tty_attr; /* tty state to restore */
-static int tty_mode; /* kbd mode to restore */
-
-static void *console_handler;
-
-static void
-drain_console(int fd, void *closure)
-{
- errno = 0;
- if (tcflush(fd, TCIOFLUSH) == -1 && errno == EIO) {
- xf86RemoveGeneralHandler(console_handler);
- console_handler = NULL;
- }
-}
-
-static void
-switch_to(int vt, const char *from)
-{
- if (ioctl(xf86Info.consoleFd, VT_ACTIVATE, vt) < 0)
- FatalError("%s: VT_ACTIVATE failed: %s\n", from, strerror(errno));
-
- if (ioctl(xf86Info.consoleFd, VT_WAITACTIVE, vt) < 0)
- FatalError("%s: VT_WAITACTIVE failed: %s\n", from, strerror(errno));
-}
-
-void
-xf86OpenConsole(void)
-{
- int i, fd = -1;
- struct vt_mode VT;
- struct vt_stat vts;
- MessageType from = X_PROBED;
- char *tty0[] = { "/dev/tty0", "/dev/vc/0", NULL };
- char *vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL };
-
- if (serverGeneration == 1) {
-
- /* when KeepTty check if we're run with euid==0 */
- if (KeepTty && geteuid() != 0)
- FatalError("xf86OpenConsole:"
- " Server must be suid root for option \"KeepTTY\"\n");
-
- /*
- * setup the virtual terminal manager
- */
- if (xf86Info.vtno != -1) {
- from = X_CMDLINE;
- } else {
-
- i=0;
- while (tty0[i] != NULL) {
- if ((fd = open(tty0[i],O_WRONLY,0)) >= 0)
- break;
- i++;
- }
-
- if (fd < 0)
- FatalError(
- "xf86OpenConsole: Cannot open /dev/tty0 (%s)\n",
- strerror(errno));
-
- if (ShareVTs)
- {
- if (ioctl(fd, VT_GETSTATE, &vts) == 0)
- xf86Info.vtno = vts.v_active;
- else
- FatalError("xf86OpenConsole: Cannot find the current"
- " VT (%s)\n", strerror(errno));
- } else {
- if ((ioctl(fd, VT_OPENQRY, &xf86Info.vtno) < 0) ||
- (xf86Info.vtno == -1))
- FatalError("xf86OpenConsole: Cannot find a free VT: %s\n",
- strerror(errno));
- }
- close(fd);
- }
-
- xf86Msg(from, "using VT number %d\n\n", xf86Info.vtno);
-
- if (!KeepTty) {
- pid_t ppid = getppid();
- pid_t ppgid;
- ppgid = getpgid(ppid);
-
- /*
- * change to parent process group that pgid != pid so
- * that setsid() doesn't fail and we become process
- * group leader
- */
- if (setpgid(0,ppgid) < 0)
- xf86Msg(X_WARNING, "xf86OpenConsole: setpgid failed: %s\n",
- strerror(errno));
-
- /* become process group leader */
- if ((setsid() < 0))
- xf86Msg(X_WARNING, "xf86OpenConsole: setsid failed: %s\n",
- strerror(errno));
- }
-
- i=0;
- while (vcs[i] != NULL) {
- sprintf(vtname, vcs[i], xf86Info.vtno); /* /dev/tty1-64 */
- if ((xf86Info.consoleFd = open(vtname, O_RDWR|O_NDELAY, 0)) >= 0)
- break;
- i++;
- }
-
- if (xf86Info.consoleFd < 0)
- FatalError("xf86OpenConsole: Cannot open virtual console"
- " %d (%s)\n", xf86Info.vtno, strerror(errno));
-
- /*
- * Linux doesn't switch to an active vt after the last close of a vt,
- * so we do this ourselves by remembering which is active now.
- */
- if (ioctl(xf86Info.consoleFd, VT_GETSTATE, &vts) < 0)
- xf86Msg(X_WARNING,"xf86OpenConsole: VT_GETSTATE failed: %s\n",
- strerror(errno));
- else
- activeVT = vts.v_active;
-
-#if 0
- if (!KeepTty) {
- /*
- * Detach from the controlling tty to avoid char loss
- */
- if ((i = open("/dev/tty",O_RDWR)) >= 0) {
- ioctl(i, TIOCNOTTY, 0);
- close(i);
- }
- }
-#endif
-
- if (!ShareVTs)
- {
- struct termios nTty;
-
- /*
- * now get the VT. This _must_ succeed, or else fail completely.
- */
- switch_to(xf86Info.vtno, "xf86OpenConsole");
-
- if (ioctl(xf86Info.consoleFd, VT_GETMODE, &VT) < 0)
- FatalError("xf86OpenConsole: VT_GETMODE failed %s\n",
- strerror(errno));
-
- signal(SIGUSR1, xf86VTRequest);
-
- VT.mode = VT_PROCESS;
- VT.relsig = SIGUSR1;
- VT.acqsig = SIGUSR1;
-
- if (ioctl(xf86Info.consoleFd, VT_SETMODE, &VT) < 0)
- FatalError("xf86OpenConsole: VT_SETMODE VT_PROCESS failed: %s\n",
- strerror(errno));
-
- if (ioctl(xf86Info.consoleFd, KDSETMODE, KD_GRAPHICS) < 0)
- FatalError("xf86OpenConsole: KDSETMODE KD_GRAPHICS failed %s\n",
- strerror(errno));
-
- tcgetattr(xf86Info.consoleFd, &tty_attr);
- ioctl(xf86Info.consoleFd, KDGKBMODE, &tty_mode);
-
- if (ioctl(xf86Info.consoleFd, KDSKBMODE, K_RAW) < 0)
- FatalError("xf86OpenConsole: KDSKBMODE K_RAW failed %s\n",
- strerror(errno));
-
- nTty = tty_attr;
- nTty.c_iflag = (IGNPAR | IGNBRK) & (~PARMRK) & (~ISTRIP);
- nTty.c_oflag = 0;
- nTty.c_cflag = CREAD | CS8;
- nTty.c_lflag = 0;
- nTty.c_cc[VTIME]=0;
- nTty.c_cc[VMIN]=1;
- cfsetispeed(&nTty, 9600);
- cfsetospeed(&nTty, 9600);
- tcsetattr(xf86Info.consoleFd, TCSANOW, &nTty);
-
- /* need to keep the buffer clean, else the kernel gets angry */
- xf86SetConsoleHandler(drain_console, NULL);
-
- /* we really should have a InitOSInputDevices() function instead
- * of Init?$#*&Device(). So I just place it here */
- }
- } else { /* serverGeneration != 1 */
- if (!ShareVTs && VTSwitch)
- {
- /* now get the VT */
- switch_to(xf86Info.vtno, "xf86OpenConsole");
- }
- }
-}
-
-void
-xf86CloseConsole(void)
-{
- struct vt_mode VT;
-
- if (ShareVTs) {
- close(xf86Info.consoleFd);
- return;
- }
-
- if (console_handler) {
- xf86RemoveGeneralHandler(console_handler);
- console_handler = NULL;
- };
-
- /* Back to text mode ... */
- if (ioctl(xf86Info.consoleFd, KDSETMODE, KD_TEXT) < 0)
- xf86Msg(X_WARNING, "xf86CloseConsole: KDSETMODE failed: %s\n",
- strerror(errno));
-
- ioctl(xf86Info.consoleFd, KDSKBMODE, tty_mode);
- tcsetattr(xf86Info.consoleFd, TCSANOW, &tty_attr);
-
- if (ioctl(xf86Info.consoleFd, VT_GETMODE, &VT) < 0)
- xf86Msg(X_WARNING, "xf86CloseConsole: VT_GETMODE failed: %s\n",
- strerror(errno));
- else {
- /* set dflt vt handling */
- VT.mode = VT_AUTO;
- if (ioctl(xf86Info.consoleFd, VT_SETMODE, &VT) < 0)
- xf86Msg(X_WARNING, "xf86CloseConsole: VT_SETMODE failed: %s\n",
- strerror(errno));
- }
-
- if (VTSwitch)
- {
- /*
- * Perform a switch back to the active VT when we were started
- */
- if (activeVT >= 0) {
- switch_to(activeVT, "xf86CloseConsole");
- activeVT = -1;
- }
- }
- close(xf86Info.consoleFd); /* make the vt-manager happy */
-}
-
-int
-xf86ProcessArgument(int argc, char *argv[], int i)
-{
- /*
- * Keep server from detaching from controlling tty. This is useful
- * when debugging (so the server can receive keyboard signals.
- */
- if (!strcmp(argv[i], "-keeptty"))
- {
- KeepTty = TRUE;
- return 1;
- }
- if (!strcmp(argv[i], "-novtswitch"))
- {
- VTSwitch = FALSE;
- return 1;
- }
- if (!strcmp(argv[i], "-sharevts"))
- {
- ShareVTs = TRUE;
- return 1;
- }
- if ((argv[i][0] == 'v') && (argv[i][1] == 't'))
- {
- if (sscanf(argv[i], "vt%2d", &xf86Info.vtno) == 0)
- {
- UseMsg();
- xf86Info.vtno = -1;
- return 0;
- }
- return 1;
- }
- return 0;
-}
-
-void
-xf86UseMsg(void)
-{
- ErrorF("vtXX use the specified VT number\n");
- ErrorF("-keeptty ");
- ErrorF("don't detach controlling tty (for debugging only)\n");
- ErrorF("-novtswitch don't immediately switch to new VT\n");
- ErrorF("-sharevts share VTs with another X server\n");
-}
+/* + * Copyright 1992 by Orest Zborowski <obz@Kodak.com> + * Copyright 1993 by David Wexelblat <dwex@goblin.org> + * + * Permission to use, copy, modify, distribute, and sell this software and its + * documentation for any purpose is hereby granted without fee, provided that + * the above copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the names of Orest Zborowski and David Wexelblat + * not be used in advertising or publicity pertaining to distribution of + * the software without specific, written prior permission. Orest Zborowski + * and David Wexelblat make no representations about the suitability of this + * software for any purpose. It is provided "as is" without express or + * implied warranty. + * + * OREST ZBOROWSKI AND DAVID WEXELBLAT DISCLAIMS ALL WARRANTIES WITH REGARD + * TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS, IN NO EVENT SHALL OREST ZBOROWSKI OR DAVID WEXELBLAT BE LIABLE + * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + * + */ + +#ifdef HAVE_XORG_CONFIG_H +#include <xorg-config.h> +#endif + +#include <X11/X.h> +#include <X11/Xmd.h> + +#include "compiler.h" + +#include "xf86.h" +#include "xf86Priv.h" +#include "xf86_OSlib.h" + +#include <sys/stat.h> + +static Bool KeepTty = FALSE; +static Bool VTSwitch = TRUE; +static Bool ShareVTs = FALSE; +static int activeVT = -1; + +static char vtname[11]; +static struct termios tty_attr; /* tty state to restore */ +static int tty_mode; /* kbd mode to restore */ + +static void *console_handler; + +static void +drain_console(int fd, void *closure) +{ + errno = 0; + if (tcflush(fd, TCIOFLUSH) == -1 && errno == EIO) { + xf86RemoveGeneralHandler(console_handler); + console_handler = NULL; + } +} + +static void +switch_to(int vt, const char *from) +{ + int ret; + + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_ACTIVATE, vt)); + if (ret < 0) + FatalError("%s: VT_ACTIVATE failed: %s\n", from, strerror(errno)); + + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_WAITACTIVE, vt)); + if (ret < 0) + FatalError("%s: VT_WAITACTIVE failed: %s\n", from, strerror(errno)); +} + +void +xf86OpenConsole(void) +{ + int i, fd = -1, ret; + struct vt_mode VT; + struct vt_stat vts; + MessageType from = X_PROBED; + char *tty0[] = { "/dev/tty0", "/dev/vc/0", NULL }; + char *vcs[] = { "/dev/vc/%d", "/dev/tty%d", NULL }; + + if (serverGeneration == 1) { + + /* when KeepTty check if we're run with euid==0 */ + if (KeepTty && geteuid() != 0) + FatalError("xf86OpenConsole:" + " Server must be suid root for option \"KeepTTY\"\n"); + + /* + * setup the virtual terminal manager + */ + if (xf86Info.vtno != -1) { + from = X_CMDLINE; + } else { + + i=0; + while (tty0[i] != NULL) { + if ((fd = open(tty0[i],O_WRONLY,0)) >= 0) + break; + i++; + } + + if (fd < 0) + FatalError( + "xf86OpenConsole: Cannot open /dev/tty0 (%s)\n", + strerror(errno)); + + if (ShareVTs) + { + SYSCALL(ret = ioctl(fd, VT_GETSTATE, &vts)); + if (ret < 0) + FatalError("xf86OpenConsole: Cannot find the current" + " VT (%s)\n", strerror(errno)); + xf86Info.vtno = vts.v_active; + } else { + SYSCALL(ret = ioctl(fd, VT_OPENQRY, &xf86Info.vtno)); + if (ret < 0) + FatalError("xf86OpenConsole: Cannot find a free VT: " + "%s\n", strerror(errno)); + if (xf86Info.vtno == -1) + FatalError("xf86OpenConsole: Cannot find a free VT\n"); + } + close(fd); + } + + xf86Msg(from, "using VT number %d\n\n", xf86Info.vtno); + + if (!KeepTty) { + pid_t ppid = getppid(); + pid_t ppgid; + ppgid = getpgid(ppid); + + /* + * change to parent process group that pgid != pid so + * that setsid() doesn't fail and we become process + * group leader + */ + if (setpgid(0,ppgid) < 0) + xf86Msg(X_WARNING, "xf86OpenConsole: setpgid failed: %s\n", + strerror(errno)); + + /* become process group leader */ + if ((setsid() < 0)) + xf86Msg(X_WARNING, "xf86OpenConsole: setsid failed: %s\n", + strerror(errno)); + } + + i=0; + while (vcs[i] != NULL) { + sprintf(vtname, vcs[i], xf86Info.vtno); /* /dev/tty1-64 */ + if ((xf86Info.consoleFd = open(vtname, O_RDWR|O_NDELAY, 0)) >= 0) + break; + i++; + } + + if (xf86Info.consoleFd < 0) + FatalError("xf86OpenConsole: Cannot open virtual console" + " %d (%s)\n", xf86Info.vtno, strerror(errno)); + + /* + * Linux doesn't switch to an active vt after the last close of a vt, + * so we do this ourselves by remembering which is active now. + */ + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_GETSTATE, &vts)); + if (ret < 0) + xf86Msg(X_WARNING,"xf86OpenConsole: VT_GETSTATE failed: %s\n", + strerror(errno)); + else + activeVT = vts.v_active; + +#if 0 + if (!KeepTty) { + /* + * Detach from the controlling tty to avoid char loss + */ + if ((i = open("/dev/tty",O_RDWR)) >= 0) { + SYSCALL(ioctl(i, TIOCNOTTY, 0)); + close(i); + } + } +#endif + + if (!ShareVTs) + { + struct termios nTty; + + /* + * now get the VT. This _must_ succeed, or else fail completely. + */ + switch_to(xf86Info.vtno, "xf86OpenConsole"); + + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_GETMODE, &VT)); + if (ret < 0) + FatalError("xf86OpenConsole: VT_GETMODE failed %s\n", + strerror(errno)); + + signal(SIGUSR1, xf86VTRequest); + + VT.mode = VT_PROCESS; + VT.relsig = SIGUSR1; + VT.acqsig = SIGUSR1; + + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_SETMODE, &VT)); + if (ret < 0) + FatalError("xf86OpenConsole: VT_SETMODE VT_PROCESS failed: %s\n", + strerror(errno)); + + SYSCALL(ret = ioctl(xf86Info.consoleFd, KDSETMODE, KD_GRAPHICS)); + if (ret < 0) + FatalError("xf86OpenConsole: KDSETMODE KD_GRAPHICS failed %s\n", + strerror(errno)); + + tcgetattr(xf86Info.consoleFd, &tty_attr); + SYSCALL(ioctl(xf86Info.consoleFd, KDGKBMODE, &tty_mode)); + + SYSCALL(ret = ioctl(xf86Info.consoleFd, KDSKBMODE, K_RAW)); + if (ret < 0) + FatalError("xf86OpenConsole: KDSKBMODE K_RAW failed %s\n", + strerror(errno)); + + nTty = tty_attr; + nTty.c_iflag = (IGNPAR | IGNBRK) & (~PARMRK) & (~ISTRIP); + nTty.c_oflag = 0; + nTty.c_cflag = CREAD | CS8; + nTty.c_lflag = 0; + nTty.c_cc[VTIME]=0; + nTty.c_cc[VMIN]=1; + cfsetispeed(&nTty, 9600); + cfsetospeed(&nTty, 9600); + tcsetattr(xf86Info.consoleFd, TCSANOW, &nTty); + + /* need to keep the buffer clean, else the kernel gets angry */ + xf86SetConsoleHandler(drain_console, NULL); + + /* we really should have a InitOSInputDevices() function instead + * of Init?$#*&Device(). So I just place it here */ + } + } else { /* serverGeneration != 1 */ + if (!ShareVTs && VTSwitch) + { + /* now get the VT */ + switch_to(xf86Info.vtno, "xf86OpenConsole"); + } + } +} + +void +xf86CloseConsole(void) +{ + struct vt_mode VT; + int ret; + + if (ShareVTs) { + close(xf86Info.consoleFd); + return; + } + + if (console_handler) { + xf86RemoveGeneralHandler(console_handler); + console_handler = NULL; + }; + + /* Back to text mode ... */ + SYSCALL(ret = ioctl(xf86Info.consoleFd, KDSETMODE, KD_TEXT)); + if (ret < 0) + xf86Msg(X_WARNING, "xf86CloseConsole: KDSETMODE failed: %s\n", + strerror(errno)); + + SYSCALL(ioctl(xf86Info.consoleFd, KDSKBMODE, tty_mode)); + tcsetattr(xf86Info.consoleFd, TCSANOW, &tty_attr); + + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_GETMODE, &VT)); + if (ret < 0) + xf86Msg(X_WARNING, "xf86CloseConsole: VT_GETMODE failed: %s\n", + strerror(errno)); + else { + /* set dflt vt handling */ + VT.mode = VT_AUTO; + SYSCALL(ret = ioctl(xf86Info.consoleFd, VT_SETMODE, &VT)); + if (ret < 0) + xf86Msg(X_WARNING, "xf86CloseConsole: VT_SETMODE failed: %s\n", + strerror(errno)); + } + + if (VTSwitch) + { + /* + * Perform a switch back to the active VT when we were started + */ + if (activeVT >= 0) { + switch_to(activeVT, "xf86CloseConsole"); + activeVT = -1; + } + } + close(xf86Info.consoleFd); /* make the vt-manager happy */ +} + +int +xf86ProcessArgument(int argc, char *argv[], int i) +{ + /* + * Keep server from detaching from controlling tty. This is useful + * when debugging (so the server can receive keyboard signals. + */ + if (!strcmp(argv[i], "-keeptty")) + { + KeepTty = TRUE; + return 1; + } + if (!strcmp(argv[i], "-novtswitch")) + { + VTSwitch = FALSE; + return 1; + } + if (!strcmp(argv[i], "-sharevts")) + { + ShareVTs = TRUE; + return 1; + } + if ((argv[i][0] == 'v') && (argv[i][1] == 't')) + { + if (sscanf(argv[i], "vt%2d", &xf86Info.vtno) == 0) + { + UseMsg(); + xf86Info.vtno = -1; + return 0; + } + return 1; + } + return 0; +} + +void +xf86UseMsg(void) +{ + ErrorF("vtXX use the specified VT number\n"); + ErrorF("-keeptty "); + ErrorF("don't detach controlling tty (for debugging only)\n"); + ErrorF("-novtswitch don't immediately switch to new VT\n"); + ErrorF("-sharevts share VTs with another X server\n"); +} diff --git a/xorg-server/hw/xnest/Events.c b/xorg-server/hw/xnest/Events.c index 6b8edf143..5c800860a 100644 --- a/xorg-server/hw/xnest/Events.c +++ b/xorg-server/hw/xnest/Events.c @@ -1,233 +1,233 @@ -/*
-
-Copyright 1993 by Davor Matic
-
-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. Davor Matic makes no representations about
-the suitability of this software for any purpose. It is provided "as
-is" without express or implied warranty.
-
-*/
-
-#ifdef HAVE_XNEST_CONFIG_H
-#include <xnest-config.h>
-#endif
-
-#include <X11/X.h>
-#include <X11/Xproto.h>
-#include "screenint.h"
-#include "input.h"
-#include "misc.h"
-#include "scrnintstr.h"
-#include "windowstr.h"
-#include "servermd.h"
-#include "inputstr.h"
-#include "inpututils.h"
-
-#include "mi.h"
-
-#include "Xnest.h"
-
-#include "Args.h"
-#include "Color.h"
-#include "Display.h"
-#include "Screen.h"
-#include "XNWindow.h"
-#include "Events.h"
-#include "Keyboard.h"
-#include "Pointer.h"
-#include "mipointer.h"
-
-CARD32 lastEventTime = 0;
-
-extern EventList *xnestEvents;
-
-void
-ProcessInputEvents(void)
-{
- mieqProcessInputEvents();
-}
-
-int
-TimeSinceLastInputEvent(void)
-{
- if (lastEventTime == 0)
- lastEventTime = GetTimeInMillis();
- return GetTimeInMillis() - lastEventTime;
-}
-
-void
-SetTimeSinceLastInputEvent(void)
-{
- lastEventTime = GetTimeInMillis();
-}
-
-static Bool
-xnestExposurePredicate(Display *display, XEvent *event, char *args)
-{
- return event->type == Expose || event->type == ProcessedExpose;
-}
-
-static Bool
-xnestNotExposurePredicate(Display *display, XEvent *event, char *args)
-{
- return !xnestExposurePredicate(display, event, args);
-}
-
-void
-xnestCollectExposures(void)
-{
- XEvent X;
- WindowPtr pWin;
- RegionRec Rgn;
- BoxRec Box;
-
- while (XCheckIfEvent(xnestDisplay, &X, xnestExposurePredicate, NULL)) {
- pWin = xnestWindowPtr(X.xexpose.window);
-
- if (pWin && X.xexpose.width && X.xexpose.height) {
- Box.x1 = pWin->drawable.x + wBorderWidth(pWin) + X.xexpose.x;
- Box.y1 = pWin->drawable.y + wBorderWidth(pWin) + X.xexpose.y;
- Box.x2 = Box.x1 + X.xexpose.width;
- Box.y2 = Box.y1 + X.xexpose.height;
-
- RegionInit(&Rgn, &Box, 1);
-
- miSendExposures(pWin, &Rgn, Box.x2, Box.y2);
- }
- }
-}
-
-void
-xnestQueueKeyEvent(int type, unsigned int keycode)
-{
- int i, n;
-
- GetEventList(&xnestEvents);
- lastEventTime = GetTimeInMillis();
- n = GetKeyboardEvents(xnestEvents, xnestKeyboardDevice, type, keycode);
- for (i = 0; i < n; i++)
- mieqEnqueue(xnestKeyboardDevice, (InternalEvent*)(xnestEvents + i)->event);
-}
-
-void
-xnestCollectEvents(void)
-{
- XEvent X;
- int i, n, valuators[2];
- ValuatorMask mask;
- ScreenPtr pScreen;
- GetEventList(&xnestEvents);
-
- while (XCheckIfEvent(xnestDisplay, &X, xnestNotExposurePredicate, NULL)) {
- switch (X.type) {
- case KeyPress:
- xnestUpdateModifierState(X.xkey.state);
- xnestQueueKeyEvent(KeyPress, X.xkey.keycode);
- break;
-
- case KeyRelease:
- xnestUpdateModifierState(X.xkey.state);
- xnestQueueKeyEvent(KeyRelease, X.xkey.keycode);
- break;
-
- case ButtonPress:
- valuator_mask_set_range(&mask, 0, 0, NULL);
- xnestUpdateModifierState(X.xkey.state);
- lastEventTime = GetTimeInMillis();
- n = GetPointerEvents(xnestEvents, xnestPointerDevice, ButtonPress,
- X.xbutton.button, POINTER_RELATIVE, &mask);
- for (i = 0; i < n; i++)
- mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event);
- break;
-
- case ButtonRelease:
- valuator_mask_set_range(&mask, 0, 0, NULL);
- xnestUpdateModifierState(X.xkey.state);
- lastEventTime = GetTimeInMillis();
- n = GetPointerEvents(xnestEvents, xnestPointerDevice, ButtonRelease,
- X.xbutton.button, POINTER_RELATIVE, &mask);
- for (i = 0; i < n; i++)
- mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event);
- break;
-
- case MotionNotify:
- valuators[0] = X.xmotion.x;
- valuators[1] = X.xmotion.y;
- valuator_mask_set_range(&mask, 0, 2, valuators);
- lastEventTime = GetTimeInMillis();
- n = GetPointerEvents(xnestEvents, xnestPointerDevice, MotionNotify,
- 0, POINTER_ABSOLUTE, &mask);
- for (i = 0; i < n; i++)
- mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event);
- break;
-
- case FocusIn:
- if (X.xfocus.detail != NotifyInferior) {
- pScreen = xnestScreen(X.xfocus.window);
- if (pScreen)
- xnestDirectInstallColormaps(pScreen);
- }
- break;
-
- case FocusOut:
- if (X.xfocus.detail != NotifyInferior) {
- pScreen = xnestScreen(X.xfocus.window);
- if (pScreen)
- xnestDirectUninstallColormaps(pScreen);
- }
- break;
-
- case KeymapNotify:
- break;
-
- case EnterNotify:
- if (X.xcrossing.detail != NotifyInferior) {
- pScreen = xnestScreen(X.xcrossing.window);
- if (pScreen) {
- NewCurrentScreen(inputInfo.pointer, pScreen, X.xcrossing.x, X.xcrossing.y);
- valuators[0] = X.xcrossing.x;
- valuators[1] = X.xcrossing.y;
- valuator_mask_set_range(&mask, 0, 2, valuators);
- lastEventTime = GetTimeInMillis();
- n = GetPointerEvents(xnestEvents, xnestPointerDevice, MotionNotify,
- 0, POINTER_ABSOLUTE, &mask);
- for (i = 0; i < n; i++)
- mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event);
- xnestDirectInstallColormaps(pScreen);
- }
- }
- break;
-
- case LeaveNotify:
- if (X.xcrossing.detail != NotifyInferior) {
- pScreen = xnestScreen(X.xcrossing.window);
- if (pScreen) {
- xnestDirectUninstallColormaps(pScreen);
- }
- }
- break;
-
- case DestroyNotify:
- if (xnestParentWindow != (Window) 0 &&
- X.xdestroywindow.window == xnestParentWindow)
- exit (0);
- break;
-
- case CirculateNotify:
- case ConfigureNotify:
- case GravityNotify:
- case MapNotify:
- case ReparentNotify:
- case UnmapNotify:
- break;
-
- default:
- ErrorF("xnest warning: unhandled event\n");
- break;
- }
- }
-}
+/* + +Copyright 1993 by Davor Matic + +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. Davor Matic makes no representations about +the suitability of this software for any purpose. It is provided "as +is" without express or implied warranty. + +*/ + +#ifdef HAVE_XNEST_CONFIG_H +#include <xnest-config.h> +#endif + +#include <X11/X.h> +#include <X11/Xproto.h> +#include "screenint.h" +#include "input.h" +#include "misc.h" +#include "scrnintstr.h" +#include "windowstr.h" +#include "servermd.h" +#include "inputstr.h" +#include "inpututils.h" + +#include "mi.h" + +#include "Xnest.h" + +#include "Args.h" +#include "Color.h" +#include "Display.h" +#include "Screen.h" +#include "XNWindow.h" +#include "Events.h" +#include "Keyboard.h" +#include "Pointer.h" +#include "mipointer.h" + +CARD32 lastEventTime = 0; + +extern EventList *xnestEvents; + +void +ProcessInputEvents(void) +{ + mieqProcessInputEvents(); +} + +int +TimeSinceLastInputEvent(void) +{ + if (lastEventTime == 0) + lastEventTime = GetTimeInMillis(); + return GetTimeInMillis() - lastEventTime; +} + +void +SetTimeSinceLastInputEvent(void) +{ + lastEventTime = GetTimeInMillis(); +} + +static Bool +xnestExposurePredicate(Display *display, XEvent *event, char *args) +{ + return event->type == Expose || event->type == ProcessedExpose; +} + +static Bool +xnestNotExposurePredicate(Display *display, XEvent *event, char *args) +{ + return !xnestExposurePredicate(display, event, args); +} + +void +xnestCollectExposures(void) +{ + XEvent X; + WindowPtr pWin; + RegionRec Rgn; + BoxRec Box; + + while (XCheckIfEvent(xnestDisplay, &X, xnestExposurePredicate, NULL)) { + pWin = xnestWindowPtr(X.xexpose.window); + + if (pWin && X.xexpose.width && X.xexpose.height) { + Box.x1 = pWin->drawable.x + wBorderWidth(pWin) + X.xexpose.x; + Box.y1 = pWin->drawable.y + wBorderWidth(pWin) + X.xexpose.y; + Box.x2 = Box.x1 + X.xexpose.width; + Box.y2 = Box.y1 + X.xexpose.height; + + RegionInit(&Rgn, &Box, 1); + + miSendExposures(pWin, &Rgn, Box.x2, Box.y2); + } + } +} + +void +xnestQueueKeyEvent(int type, unsigned int keycode) +{ + int i, n; + + GetEventList(&xnestEvents); + lastEventTime = GetTimeInMillis(); + n = GetKeyboardEvents(xnestEvents, xnestKeyboardDevice, type, keycode, NULL); + for (i = 0; i < n; i++) + mieqEnqueue(xnestKeyboardDevice, (InternalEvent*)(xnestEvents + i)->event); +} + +void +xnestCollectEvents(void) +{ + XEvent X; + int i, n, valuators[2]; + ValuatorMask mask; + ScreenPtr pScreen; + GetEventList(&xnestEvents); + + while (XCheckIfEvent(xnestDisplay, &X, xnestNotExposurePredicate, NULL)) { + switch (X.type) { + case KeyPress: + xnestUpdateModifierState(X.xkey.state); + xnestQueueKeyEvent(KeyPress, X.xkey.keycode); + break; + + case KeyRelease: + xnestUpdateModifierState(X.xkey.state); + xnestQueueKeyEvent(KeyRelease, X.xkey.keycode); + break; + + case ButtonPress: + valuator_mask_set_range(&mask, 0, 0, NULL); + xnestUpdateModifierState(X.xkey.state); + lastEventTime = GetTimeInMillis(); + n = GetPointerEvents(xnestEvents, xnestPointerDevice, ButtonPress, + X.xbutton.button, POINTER_RELATIVE, &mask); + for (i = 0; i < n; i++) + mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event); + break; + + case ButtonRelease: + valuator_mask_set_range(&mask, 0, 0, NULL); + xnestUpdateModifierState(X.xkey.state); + lastEventTime = GetTimeInMillis(); + n = GetPointerEvents(xnestEvents, xnestPointerDevice, ButtonRelease, + X.xbutton.button, POINTER_RELATIVE, &mask); + for (i = 0; i < n; i++) + mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event); + break; + + case MotionNotify: + valuators[0] = X.xmotion.x; + valuators[1] = X.xmotion.y; + valuator_mask_set_range(&mask, 0, 2, valuators); + lastEventTime = GetTimeInMillis(); + n = GetPointerEvents(xnestEvents, xnestPointerDevice, MotionNotify, + 0, POINTER_ABSOLUTE, &mask); + for (i = 0; i < n; i++) + mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event); + break; + + case FocusIn: + if (X.xfocus.detail != NotifyInferior) { + pScreen = xnestScreen(X.xfocus.window); + if (pScreen) + xnestDirectInstallColormaps(pScreen); + } + break; + + case FocusOut: + if (X.xfocus.detail != NotifyInferior) { + pScreen = xnestScreen(X.xfocus.window); + if (pScreen) + xnestDirectUninstallColormaps(pScreen); + } + break; + + case KeymapNotify: + break; + + case EnterNotify: + if (X.xcrossing.detail != NotifyInferior) { + pScreen = xnestScreen(X.xcrossing.window); + if (pScreen) { + NewCurrentScreen(inputInfo.pointer, pScreen, X.xcrossing.x, X.xcrossing.y); + valuators[0] = X.xcrossing.x; + valuators[1] = X.xcrossing.y; + valuator_mask_set_range(&mask, 0, 2, valuators); + lastEventTime = GetTimeInMillis(); + n = GetPointerEvents(xnestEvents, xnestPointerDevice, MotionNotify, + 0, POINTER_ABSOLUTE, &mask); + for (i = 0; i < n; i++) + mieqEnqueue(xnestPointerDevice, (InternalEvent*)(xnestEvents + i)->event); + xnestDirectInstallColormaps(pScreen); + } + } + break; + + case LeaveNotify: + if (X.xcrossing.detail != NotifyInferior) { + pScreen = xnestScreen(X.xcrossing.window); + if (pScreen) { + xnestDirectUninstallColormaps(pScreen); + } + } + break; + + case DestroyNotify: + if (xnestParentWindow != (Window) 0 && + X.xdestroywindow.window == xnestParentWindow) + exit (0); + break; + + case CirculateNotify: + case ConfigureNotify: + case GravityNotify: + case MapNotify: + case ReparentNotify: + case UnmapNotify: + break; + + default: + ErrorF("xnest warning: unhandled event\n"); + break; + } + } +} diff --git a/xorg-server/hw/xquartz/X11Application.m b/xorg-server/hw/xquartz/X11Application.m index 3521517a2..e56bf0cf3 100644 --- a/xorg-server/hw/xquartz/X11Application.m +++ b/xorg-server/hw/xquartz/X11Application.m @@ -61,6 +61,12 @@ extern int xpbproxy_run (void); #define XSERVER_VERSION "?" #endif +#ifdef HAVE_LIBDISPATCH +#include <dispatch/dispatch.h> + +static dispatch_queue_t eventTranslationQueue; +#endif + /* Stuck modifier / button state... force release when we context switch */ static NSEventType keyState[NUM_KEYCODES]; @@ -385,7 +391,15 @@ static void message_kit_thread (SEL selector, NSObject *arg) { if (for_appkit) [super sendEvent:e]; - if (for_x) [self sendX11NSEvent:e]; + if (for_x) { +#ifdef HAVE_LIBDISPATCH + dispatch_async(eventTranslationQueue, ^{ +#endif + [self sendX11NSEvent:e]; +#ifdef HAVE_LIBDISPATCH + }); +#endif + } } - (void) set_window_menu:(NSArray *)list { @@ -950,7 +964,7 @@ environment the next time you start X11?", @"Startup xinitrc dialog"); [X11App prefs_synchronize]; } -static inline pthread_t create_thread(void *func, void *arg) { +static inline pthread_t create_thread(void *(*func)(void *), void *arg) { pthread_attr_t attr; pthread_t tid; @@ -999,6 +1013,11 @@ void X11ApplicationMain (int argc, char **argv, char **envp) { aquaMenuBarHeight = NSHeight([[NSScreen mainScreen] frame]) - NSMaxY([[NSScreen mainScreen] visibleFrame]); +#ifdef HAVE_LIBDISPATCH + eventTranslationQueue = dispatch_queue_create(LAUNCHD_ID_PREFIX".X11.NSEventsToX11EventsQueue", NULL); + assert(eventTranslationQueue != NULL); +#endif + /* Set the key layout seed before we start the server */ #if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 last_key_layout = TISCopyCurrentKeyboardLayoutInputSource(); @@ -1079,13 +1098,29 @@ static const char *untrusted_str(NSEvent *e) { #endif - (void) sendX11NSEvent:(NSEvent *)e { - NSPoint location = NSZeroPoint, tilt = NSZeroPoint; + NSPoint location = NSZeroPoint; int ev_button, ev_type; - float pressure = 0.0; + static float pressure = 0.0; // static so ProximityOut will have the value from the previous tablet event + static NSPoint tilt; // static so ProximityOut will have the value from the previous tablet event + static DeviceIntPtr darwinTabletCurrent = NULL; + static BOOL needsProximityIn = NO; // Do we do need to handle a pending ProximityIn once we have pressure/tilt? DeviceIntPtr pDev; int modifierFlags; BOOL isMouseOrTabletEvent, isTabletEvent; +#ifdef HAVE_LIBDISPATCH + static dispatch_once_t once_pred; + dispatch_once(&once_pred, ^{ + tilt = NSZeroPoint; + darwinTabletCurrent = darwinTabletStylus; + }); +#else + if(!darwinTabletCurrent) { + tilt = NSZeroPoint; + darwinTabletCurrent = darwinTabletStylus; + } +#endif + isMouseOrTabletEvent = [e type] == NSLeftMouseDown || [e type] == NSOtherMouseDown || [e type] == NSRightMouseDown || [e type] == NSLeftMouseUp || [e type] == NSOtherMouseUp || [e type] == NSRightMouseUp || [e type] == NSLeftMouseDragged || [e type] == NSOtherMouseDragged || [e type] == NSRightMouseDragged || @@ -1207,19 +1242,14 @@ static const char *untrusted_str(NSEvent *e) { darwinTabletCurrent=darwinTabletCursor; break; } - - /* NSTabletProximityEventSubtype doesn't encode pressure ant tilt - * So we just pretend the motion was caused by the mouse. Hopefully - * we'll have a better solution for this in the future (like maybe - * NSTabletProximityEventSubtype will come from NSTabletPoint - * rather than NSMouseMoved. - pressure = [e pressure]; - tilt = [e tilt]; - pDev = darwinTabletCurrent; - */ - DarwinSendProximityEvents([e isEnteringProximity] ? ProximityIn : ProximityOut, - location.x, location.y); + if([e isEnteringProximity]) + needsProximityIn = YES; + else + DarwinSendProximityEvents(darwinTabletCurrent, ProximityOut, + location.x, location.y, pressure, + tilt.x, tilt.y); + return; } if ([e type] == NSTabletPoint || [e subtype] == NSTabletPointEventSubtype) { @@ -1227,6 +1257,14 @@ static const char *untrusted_str(NSEvent *e) { tilt = [e tilt]; pDev = darwinTabletCurrent; + + if(needsProximityIn) { + DarwinSendProximityEvents(darwinTabletCurrent, ProximityIn, + location.x, location.y, pressure, + tilt.x, tilt.y); + + needsProximityIn = NO; + } } if(!XQuartzServerVisible && noTestExtensions) { @@ -1280,8 +1318,12 @@ static const char *untrusted_str(NSEvent *e) { break; } - DarwinSendProximityEvents([e isEnteringProximity] ? ProximityIn : ProximityOut, - location.x, location.y); + if([e isEnteringProximity]) + needsProximityIn = YES; + else + DarwinSendProximityEvents(darwinTabletCurrent, ProximityOut, + location.x, location.y, pressure, + tilt.x, tilt.y); break; case NSScrollWheel: diff --git a/xorg-server/hw/xquartz/darwin.c b/xorg-server/hw/xquartz/darwin.c index 3b6f0a29e..00be74ba0 100644 --- a/xorg-server/hw/xquartz/darwin.c +++ b/xorg-server/hw/xquartz/darwin.c @@ -117,7 +117,6 @@ unsigned int windowItemModMask = NX_COMMANDMASK; // devices DeviceIntPtr darwinKeyboard = NULL; DeviceIntPtr darwinPointer = NULL; -DeviceIntPtr darwinTabletCurrent = NULL; DeviceIntPtr darwinTabletStylus = NULL; DeviceIntPtr darwinTabletCursor = NULL; DeviceIntPtr darwinTabletEraser = NULL; @@ -492,8 +491,6 @@ void InitInput( int argc, char **argv ) darwinTabletEraser = AddInputDevice(serverClient, DarwinTabletProc, TRUE); darwinTabletEraser->name = strdup("eraser"); - darwinTabletCurrent = darwinTabletStylus; - DarwinEQInit(); QuartzInitInput(argc, argv); diff --git a/xorg-server/hw/xquartz/darwin.h b/xorg-server/hw/xquartz/darwin.h index e874af24c..360225742 100644 --- a/xorg-server/hw/xquartz/darwin.h +++ b/xorg-server/hw/xquartz/darwin.h @@ -56,7 +56,6 @@ extern io_connect_t darwinParamConnect; extern int darwinEventReadFD; extern int darwinEventWriteFD; extern DeviceIntPtr darwinPointer; -extern DeviceIntPtr darwinTabletCurrent; extern DeviceIntPtr darwinTabletCursor; extern DeviceIntPtr darwinTabletStylus; extern DeviceIntPtr darwinTabletEraser; diff --git a/xorg-server/hw/xquartz/darwinEvents.c b/xorg-server/hw/xquartz/darwinEvents.c index 16fec4a01..40d8a4e9e 100644 --- a/xorg-server/hw/xquartz/darwinEvents.c +++ b/xorg-server/hw/xquartz/darwinEvents.c @@ -61,6 +61,7 @@ in this Software without prior written authorization from The Open Group. #include <unistd.h> #include <pthread.h> #include <errno.h> +#include <time.h> #include <IOKit/hidsystem/IOLLEvent.h> @@ -93,7 +94,7 @@ static pthread_mutex_t mieq_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t mieq_ready_cond = PTHREAD_COND_INITIALIZER; /*** Pthread Magics ***/ -static pthread_t create_thread(void *func, void *arg) { +static pthread_t create_thread(void *(*func)(void *), void *arg) { pthread_attr_t attr; pthread_t tid; @@ -304,7 +305,28 @@ void DarwinListenOnOpenFD(int fd) { pthread_mutex_unlock(&fd_add_lock); } -static void DarwinProcessFDAdditionQueue_thread(void *args) { +static void *DarwinProcessFDAdditionQueue_thread(void *args) { + /* TODO: Possibly adjust this to no longer be a race... maybe trigger this + * once a client connects and claims to be the WM. + * + * From ajax: + * There's already an internal callback chain for setting selection [in 1.5] + * ownership. See the CallSelectionCallback at the bottom of + * ProcSetSelectionOwner, and xfixes/select.c for an example of how to hook + * into it. + */ + + struct timespec sleep_for; + struct timespec sleep_remaining; + + sleep_for.tv_sec = 3; + sleep_for.tv_nsec = 0; + + ErrorF("X11.app: DarwinProcessFDAdditionQueue_thread: Sleeping to allow xinitrc to catchup.\n"); + while(nanosleep(&sleep_for, &sleep_remaining) != 0) { + sleep_for = sleep_remaining; + } + pthread_mutex_lock(&fd_add_lock); while(true) { while(fd_add_count) { @@ -312,6 +334,8 @@ static void DarwinProcessFDAdditionQueue_thread(void *args) { } pthread_cond_wait(&fd_add_ready_cond, &fd_add_lock); } + + return NULL; } Bool DarwinEQInit(void) { @@ -465,7 +489,7 @@ void DarwinSendPointerEvents(DeviceIntPtr pDev, int ev_type, int ev_button, floa DarwinPrepareValuators(pDev, valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y); darwinEvents_lock(); { ValuatorMask mask; - valuator_mask_set_range(&mask, 0, (pDev == darwinTabletCurrent) ? 5 : 2, valuators); + valuator_mask_set_range(&mask, 0, (pDev == darwinPointer) ? 2 : 5, valuators); num_events = GetPointerEvents(darwinEvents, pDev, ev_type, ev_button, POINTER_ABSOLUTE, &mask); for(i=0; i<num_events; i++) mieqEnqueue (pDev, (InternalEvent*)darwinEvents[i].event); @@ -482,24 +506,24 @@ void DarwinSendKeyboardEvents(int ev_type, int keycode) { } darwinEvents_lock(); { - num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE); + num_events = GetKeyboardEvents(darwinEvents, darwinKeyboard, ev_type, keycode + MIN_KEYCODE, NULL); for(i=0; i<num_events; i++) mieqEnqueue(darwinKeyboard, (InternalEvent*)darwinEvents[i].event); if(num_events > 0) DarwinPokeEQ(); } darwinEvents_unlock(); } -void DarwinSendProximityEvents(int ev_type, float pointer_x, float pointer_y) { - int i, num_events; +void DarwinSendProximityEvents(DeviceIntPtr pDev, int ev_type, float pointer_x, float pointer_y, + float pressure, float tilt_x, float tilt_y) { + int i, num_events; ScreenPtr screen; - DeviceIntPtr pDev = darwinTabletCurrent; int valuators[5]; - DEBUG_LOG("DarwinSendProximityEvents(%d, %f, %f)\n", ev_type, pointer_x, pointer_y); + DEBUG_LOG("DarwinSendProximityEvents: %d l:%f,%f p:%f t:%f,%f\n", ev_type, pointer_x, pointer_y, pressure, tilt_x, tilt_y); - if(!darwinEvents) { - DEBUG_LOG("DarwinSendProximityEvents called before darwinEvents was initialized\n"); - return; - } + if(!darwinEvents) { + DEBUG_LOG("DarwinSendProximityEvents called before darwinEvents was initialized\n"); + return; + } screen = miPointerGetScreen(pDev); if(!screen) { @@ -507,7 +531,7 @@ void DarwinSendProximityEvents(int ev_type, float pointer_x, float pointer_y) { return; } - DarwinPrepareValuators(pDev, valuators, screen, pointer_x, pointer_y, 0.0f, 0.0f, 0.0f); + DarwinPrepareValuators(pDev, valuators, screen, pointer_x, pointer_y, pressure, tilt_x, tilt_y); darwinEvents_lock(); { ValuatorMask mask; valuator_mask_set_range(&mask, 0, 5, valuators); diff --git a/xorg-server/hw/xquartz/darwinEvents.h b/xorg-server/hw/xquartz/darwinEvents.h index 590305f3e..6769c8bd8 100644 --- a/xorg-server/hw/xquartz/darwinEvents.h +++ b/xorg-server/hw/xquartz/darwinEvents.h @@ -37,7 +37,8 @@ void DarwinEQPointerPost(DeviceIntPtr pDev, xEventPtr e); void DarwinEQSwitchScreen(ScreenPtr pScreen, Bool fromDIX); void DarwinSendPointerEvents(DeviceIntPtr pDev, int ev_type, int ev_button, float pointer_x, float pointer_y, float pressure, float tilt_x, float tilt_y); -void DarwinSendProximityEvents(int ev_type, float pointer_x, float pointer_y); +void DarwinSendProximityEvents(DeviceIntPtr pDev, int ev_type, float pointer_x, float pointer_y, + float pressure, float tilt_x, float tilt_y); void DarwinSendKeyboardEvents(int ev_type, int keycode); void DarwinSendScrollEvents(float count_x, float count_y, float pointer_x, float pointer_y, float pressure, float tilt_x, float tilt_y); diff --git a/xorg-server/hw/xquartz/mach-startup/bundle-main.c b/xorg-server/hw/xquartz/mach-startup/bundle-main.c index aaff1c625..6a6c01c3b 100644 --- a/xorg-server/hw/xquartz/mach-startup/bundle-main.c +++ b/xorg-server/hw/xquartz/mach-startup/bundle-main.c @@ -1,691 +1,698 @@ -/* main.c -- X application launcher
-
- Copyright (c) 2007 Jeremy Huddleston
- Copyright (c) 2007 Apple 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 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. */
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <AvailabilityMacros.h>
-
-#ifdef HAVE_DIX_CONFIG_H
-#include <dix-config.h>
-#endif
-
-#include <X11/Xlib.h>
-#include <unistd.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include <pthread.h>
-#include <stdbool.h>
-#include <signal.h>
-
-#include <sys/socket.h>
-#include <sys/un.h>
-
-#include <sys/time.h>
-#include <fcntl.h>
-
-#include <mach/mach.h>
-#include <mach/mach_error.h>
-#include <servers/bootstrap.h>
-#include "mach_startup.h"
-#include "mach_startupServer.h"
-
-#include "launchd_fd.h"
-/* From darwinEvents.c ... but don't want to pull in all the server cruft */
-void DarwinListenOnOpenFD(int fd);
-
-extern int noPanoramiXExtension;
-
-#define DEFAULT_CLIENT X11BINDIR "/xterm"
-#define DEFAULT_STARTX X11BINDIR "/startx"
-#define DEFAULT_SHELL "/bin/sh"
-
-#ifndef BUILD_DATE
-#define BUILD_DATE ""
-#endif
-#ifndef XSERVER_VERSION
-#define XSERVER_VERSION "?"
-#endif
-
-static char __crashreporter_info_buff__[4096] = {0};
-static const char *__crashreporter_info__ __attribute__((__used__)) = &__crashreporter_info_buff__[0];
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
-// This is actually a toolchain requirement, but I'm not sure the correct check,
-// but it should be fine to just only include it for Leopard and later. This line
-// just tells the linker to never strip this symbol (such as for space optimization)
-asm (".desc ___crashreporter_info__, 0x10");
-#endif
-
-static const char *__crashreporter_info__base = "X.Org X Server " XSERVER_VERSION " Build Date: " BUILD_DATE;
-
-static char *launchd_id_prefix = NULL;
-static char *server_bootstrap_name = NULL;
-
-#define DEBUG 1
-
-/* This is in quartzStartup.c */
-int server_main(int argc, char **argv, char **envp);
-
-static int execute(const char *command);
-static char *command_from_prefs(const char *key, const char *default_value);
-
-/*** Pthread Magics ***/
-static pthread_t create_thread(void *func, void *arg) {
- pthread_attr_t attr;
- pthread_t tid;
-
- pthread_attr_init (&attr);
- pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
- pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
- pthread_create (&tid, &attr, func, arg);
- pthread_attr_destroy (&attr);
-
- return tid;
-}
-
-/*** Mach-O IPC Stuffs ***/
-
-union MaxMsgSize {
- union __RequestUnion__mach_startup_subsystem req;
- union __ReplyUnion__mach_startup_subsystem rep;
-};
-
-static mach_port_t checkin_or_register(char *bname) {
- kern_return_t kr;
- mach_port_t mp;
-
- /* If we're started by launchd or the old mach_init */
- kr = bootstrap_check_in(bootstrap_port, bname, &mp);
- if (kr == KERN_SUCCESS)
- return mp;
-
- /* We probably were not started by launchd or the old mach_init */
- kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &mp);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "mach_port_allocate(): %s\n", mach_error_string(kr));
- exit(EXIT_FAILURE);
- }
-
- kr = mach_port_insert_right(mach_task_self(), mp, mp, MACH_MSG_TYPE_MAKE_SEND);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "mach_port_insert_right(): %s\n", mach_error_string(kr));
- exit(EXIT_FAILURE);
- }
-
- kr = bootstrap_register(bootstrap_port, bname, mp);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "bootstrap_register(): %s\n", mach_error_string(kr));
- exit(EXIT_FAILURE);
- }
-
- return mp;
-}
-
-/*** $DISPLAY handoff ***/
-static int accept_fd_handoff(int connected_fd) {
- int launchd_fd;
-
- char databuf[] = "display";
- struct iovec iov[1];
-
- union {
- struct cmsghdr hdr;
- char bytes[CMSG_SPACE(sizeof(int))];
- } buf;
-
- struct msghdr msg;
- struct cmsghdr *cmsg;
-
- iov[0].iov_base = databuf;
- iov[0].iov_len = sizeof(databuf);
-
- msg.msg_iov = iov;
- msg.msg_iovlen = 1;
- msg.msg_control = buf.bytes;
- msg.msg_controllen = sizeof(buf);
- msg.msg_name = 0;
- msg.msg_namelen = 0;
- msg.msg_flags = 0;
-
- cmsg = CMSG_FIRSTHDR (&msg);
- cmsg->cmsg_level = SOL_SOCKET;
- cmsg->cmsg_type = SCM_RIGHTS;
- cmsg->cmsg_len = CMSG_LEN(sizeof(int));
-
- msg.msg_controllen = cmsg->cmsg_len;
-
- *((int*)CMSG_DATA(cmsg)) = -1;
-
- if(recvmsg(connected_fd, &msg, 0) < 0) {
- fprintf(stderr, "X11.app: Error receiving $DISPLAY file descriptor. recvmsg() error: %s\n", strerror(errno));
- return -1;
- }
-
- launchd_fd = *((int*)CMSG_DATA(cmsg));
-
- return launchd_fd;
-}
-
-typedef struct {
- int fd;
- string_t filename;
-} socket_handoff_t;
-
-/* This thread accepts an incoming connection and hands off the file
- * descriptor for the new connection to accept_fd_handoff()
- */
-static void socket_handoff_thread(void *arg) {
- socket_handoff_t *handoff_data = (socket_handoff_t *)arg;
- int launchd_fd = -1;
- int connected_fd;
- unsigned remain;
-
- /* Now actually get the passed file descriptor from this connection
- * If we encounter an error, keep listening.
- */
- while(launchd_fd == -1) {
- connected_fd = accept(handoff_data->fd, NULL, NULL);
- if(connected_fd == -1) {
- fprintf(stderr, "X11.app: Failed to accept incoming connection on socket (fd=%d): %s\n", handoff_data->fd, strerror(errno));
- sleep(2);
- continue;
- }
-
- launchd_fd = accept_fd_handoff(connected_fd);
- if(launchd_fd == -1)
- fprintf(stderr, "X11.app: Error receiving $DISPLAY file descriptor, no descriptor received? Waiting for another connection.\n");
-
- close(connected_fd);
- }
-
- close(handoff_data->fd);
- unlink(handoff_data->filename);
- free(handoff_data);
-
- /* TODO: Clean up this race better... giving xinitrc time to run... need to wait for 1.5 branch:
- *
- * From ajax:
- * There's already an internal callback chain for setting selection [in 1.5]
- * ownership. See the CallSelectionCallback at the bottom of
- * ProcSetSelectionOwner, and xfixes/select.c for an example of how to hook
- * into it.
- */
-
- remain = 3000000;
- fprintf(stderr, "X11.app: Received new $DISPLAY fd: %d ... sleeping to allow xinitrc to catchup.\n", launchd_fd);
- while((remain = usleep(remain)) > 0);
-
- fprintf(stderr, "X11.app Handing off fd to server thread via DarwinListenOnOpenFD(%d)\n", launchd_fd);
- DarwinListenOnOpenFD(launchd_fd);
-}
-
-static int create_socket(char *filename_out) {
- struct sockaddr_un servaddr_un;
- struct sockaddr *servaddr;
- socklen_t servaddr_len;
- int ret_fd;
- size_t try, try_max;
-
- for(try=0, try_max=5; try < try_max; try++) {
- tmpnam(filename_out);
-
- /* Setup servaddr_un */
- memset (&servaddr_un, 0, sizeof (struct sockaddr_un));
- servaddr_un.sun_family = AF_UNIX;
- strlcpy(servaddr_un.sun_path, filename_out, sizeof(servaddr_un.sun_path));
-
- servaddr = (struct sockaddr *) &servaddr_un;
- servaddr_len = sizeof(struct sockaddr_un) - sizeof(servaddr_un.sun_path) + strlen(filename_out);
-
- ret_fd = socket(PF_UNIX, SOCK_STREAM, 0);
- if(ret_fd == -1) {
- fprintf(stderr, "X11.app: Failed to create socket (try %d / %d): %s - %s\n", (int)try+1, (int)try_max, filename_out, strerror(errno));
- continue;
- }
-
- if(bind(ret_fd, servaddr, servaddr_len) != 0) {
- fprintf(stderr, "X11.app: Failed to bind socket: %d - %s\n", errno, strerror(errno));
- close(ret_fd);
- return 0;
- }
-
- if(listen(ret_fd, 10) != 0) {
- fprintf(stderr, "X11.app: Failed to listen to socket: %s - %d - %s\n", filename_out, errno, strerror(errno));
- close(ret_fd);
- return 0;
- }
-
-#ifdef DEBUG
- fprintf(stderr, "X11.app: Listening on socket for fd handoff: (%d) %s\n", ret_fd, filename_out);
-#endif
-
- return ret_fd;
- }
-
- return 0;
-}
-
-static int launchd_socket_handed_off = 0;
-
-kern_return_t do_request_fd_handoff_socket(mach_port_t port, string_t filename) {
- socket_handoff_t *handoff_data;
-
- launchd_socket_handed_off = 1;
-
- handoff_data = (socket_handoff_t *)calloc(1,sizeof(socket_handoff_t));
- if(!handoff_data) {
- fprintf(stderr, "X11.app: Error allocating memory for handoff_data\n");
- return KERN_FAILURE;
- }
-
- handoff_data->fd = create_socket(handoff_data->filename);
- if(!handoff_data->fd) {
- free(handoff_data);
- return KERN_FAILURE;
- }
-
- strlcpy(filename, handoff_data->filename, STRING_T_SIZE);
-
- create_thread(socket_handoff_thread, handoff_data);
-
-#ifdef DEBUG
- fprintf(stderr, "X11.app: Thread created for handoff. Returning success to tell caller to connect and push the fd.\n");
-#endif
-
- return KERN_SUCCESS;
-}
-
-kern_return_t do_request_pid(mach_port_t port, int *my_pid) {
- *my_pid = getpid();
- return KERN_SUCCESS;
-}
-
-/*** Server Startup ***/
-kern_return_t do_start_x11_server(mach_port_t port, string_array_t argv,
- mach_msg_type_number_t argvCnt,
- string_array_t envp,
- mach_msg_type_number_t envpCnt) {
- /* And now back to char ** */
- char **_argv = alloca((argvCnt + 1) * sizeof(char *));
- char **_envp = alloca((envpCnt + 1) * sizeof(char *));
- size_t i;
-
- /* If we didn't get handed a launchd DISPLAY socket, we should
- * unset DISPLAY or we can run into problems with pbproxy
- */
- if(!launchd_socket_handed_off) {
- fprintf(stderr, "X11.app: No launchd socket handed off, unsetting DISPLAY\n");
- unsetenv("DISPLAY");
- }
-
- if(!_argv || !_envp) {
- return KERN_FAILURE;
- }
-
- fprintf(stderr, "X11.app: do_start_x11_server(): argc=%d\n", argvCnt);
- for(i=0; i < argvCnt; i++) {
- _argv[i] = argv[i];
- fprintf(stderr, "\targv[%u] = %s\n", (unsigned)i, argv[i]);
- }
- _argv[argvCnt] = NULL;
-
- for(i=0; i < envpCnt; i++) {
- _envp[i] = envp[i];
- }
- _envp[envpCnt] = NULL;
-
- if(server_main(argvCnt, _argv, _envp) == 0)
- return KERN_SUCCESS;
- else
- return KERN_FAILURE;
-}
-
-static int startup_trigger(int argc, char **argv, char **envp) {
- Display *display;
- const char *s;
-
- /* Take care of the case where we're called like a normal DDX */
- if(argc > 1 && argv[1][0] == ':') {
- size_t i;
- kern_return_t kr;
- mach_port_t mp;
- string_array_t newenvp;
- string_array_t newargv;
-
- /* We need to count envp */
- int envpc;
- for(envpc=0; envp[envpc]; envpc++);
-
- /* We have fixed-size string lengths due to limitations in IPC,
- * so we need to copy our argv and envp.
- */
- newargv = (string_array_t)alloca(argc * sizeof(string_t));
- newenvp = (string_array_t)alloca(envpc * sizeof(string_t));
-
- if(!newargv || !newenvp) {
- fprintf(stderr, "Memory allocation failure\n");
- exit(EXIT_FAILURE);
- }
-
- for(i=0; i < argc; i++) {
- strlcpy(newargv[i], argv[i], STRING_T_SIZE);
- }
- for(i=0; i < envpc; i++) {
- strlcpy(newenvp[i], envp[i], STRING_T_SIZE);
- }
-
- kr = bootstrap_look_up(bootstrap_port, server_bootstrap_name, &mp);
- if (kr != KERN_SUCCESS) {
-#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050
- fprintf(stderr, "bootstrap_look_up(%s): %s\n", server_bootstrap_name, bootstrap_strerror(kr));
-#else
- fprintf(stderr, "bootstrap_look_up(%s): %ul\n", server_bootstrap_name, (unsigned long)kr);
-#endif
- exit(EXIT_FAILURE);
- }
-
- kr = start_x11_server(mp, newargv, argc, newenvp, envpc);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "start_x11_server: %s\n", mach_error_string(kr));
- exit(EXIT_FAILURE);
- }
- exit(EXIT_SUCCESS);
- }
-
- /* If we have a process serial number and it's our only arg, act as if
- * the user double clicked the app bundle: launch app_to_run if possible
- */
- if(argc == 1 || (argc == 2 && !strncmp(argv[1], "-psn_", 5))) {
- /* Now, try to open a display, if so, run the launcher */
- display = XOpenDisplay(NULL);
- if(display) {
- /* Could open the display, start the launcher */
- XCloseDisplay(display);
-
- return execute(command_from_prefs("app_to_run", DEFAULT_CLIENT));
- }
- }
-
- /* Start the server */
- if((s = getenv("DISPLAY"))) {
- fprintf(stderr, "X11.app: Could not connect to server (DISPLAY=\"%s\", unsetting). Starting X server.\n", s);
- unsetenv("DISPLAY");
- } else {
- fprintf(stderr, "X11.app: Could not connect to server (DISPLAY is not set). Starting X server.\n");
- }
- return execute(command_from_prefs("startx_script", DEFAULT_STARTX));
-}
-
-/** Setup the environment we want our child processes to inherit */
-static void ensure_path(const char *dir) {
- char buf[1024], *temp;
-
- /* Make sure /usr/X11/bin is in the $PATH */
- temp = getenv("PATH");
- if(temp == NULL || temp[0] == 0) {
- snprintf(buf, sizeof(buf), "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:%s", dir);
- setenv("PATH", buf, TRUE);
- } else if(strnstr(temp, X11BINDIR, sizeof(temp)) == NULL) {
- snprintf(buf, sizeof(buf), "%s:%s", temp, dir);
- setenv("PATH", buf, TRUE);
- }
-}
-
-static void setup_env(void) {
- char *temp;
- const char *pds = NULL;
- const char *disp = getenv("DISPLAY");
- size_t len;
-
- /* Pass on our prefs domain to startx and its inheritors (mainly for
- * quartz-wm and the Xquartz stub's MachIPC)
- */
- CFBundleRef bundle = CFBundleGetMainBundle();
- if(bundle) {
- CFStringRef pd = CFBundleGetIdentifier(bundle);
- if(pd) {
- pds = CFStringGetCStringPtr(pd, 0);
- }
- }
-
- /* fallback to hardcoded value if we can't discover it */
- if(!pds) {
- pds = LAUNCHD_ID_PREFIX".X11";
- }
-
- server_bootstrap_name = strdup(pds);
- if(!server_bootstrap_name) {
- fprintf(stderr, "X11.app: Memory allocation error.\n");
- exit(1);
- }
- setenv("X11_PREFS_DOMAIN", server_bootstrap_name, 1);
-
- len = strlen(server_bootstrap_name);
- launchd_id_prefix = malloc(sizeof(char) * (len - 3));
- if(!launchd_id_prefix) {
- fprintf(stderr, "X11.app: Memory allocation error.\n");
- exit(1);
- }
- strlcpy(launchd_id_prefix, server_bootstrap_name, len - 3);
-
- /* We need to unset DISPLAY if it is not our socket */
- if(disp) {
- /* s = basename(disp) */
- const char *d, *s;
- for(s = NULL, d = disp; *d; d++) {
- if(*d == '/')
- s = d + 1;
- }
-
- if(s && *s) {
- if(strcmp(launchd_id_prefix, "org.x") == 0 && strcmp(s, ":0") == 0) {
- fprintf(stderr, "X11.app: Detected old style launchd DISPLAY, please update xinit.\n");
- } else {
- temp = (char *)malloc(sizeof(char) * len);
- if(!temp) {
- fprintf(stderr, "X11.app: Memory allocation error creating space for socket name test.\n");
- exit(1);
- }
- strlcpy(temp, launchd_id_prefix, len);
- strlcat(temp, ":0", len);
-
- if(strcmp(temp, s) != 0) {
- /* If we don't have a match, unset it. */
- fprintf(stderr, "X11.app: DISPLAY (\"%s\") does not match our id (\"%s\"), unsetting.\n", disp, launchd_id_prefix);
- unsetenv("DISPLAY");
- }
- free(temp);
- }
- } else {
- /* The DISPLAY environment variable is not formatted like a launchd socket, so reset. */
- fprintf(stderr, "X11.app: DISPLAY does not look like a launchd set variable, unsetting.\n");
- unsetenv("DISPLAY");
- }
- }
-
- /* Make sure PATH is right */
- ensure_path(X11BINDIR);
-
- /* cd $HOME */
- temp = getenv("HOME");
- if(temp != NULL && temp[0] != '\0')
- chdir(temp);
-}
-
-/*** Main ***/
-int main(int argc, char **argv, char **envp) {
- Bool listenOnly = FALSE;
- int i;
- mach_msg_size_t mxmsgsz = sizeof(union MaxMsgSize) + MAX_TRAILER_SIZE;
- mach_port_t mp;
- kern_return_t kr;
-
- /* Setup our environment for our children */
- setup_env();
-
- /* The server must not run the PanoramiX operations. */
- noPanoramiXExtension = TRUE;
-
- /* Setup the initial crasherporter info */
- strlcpy(__crashreporter_info_buff__, __crashreporter_info__base, sizeof(__crashreporter_info_buff__));
-
- fprintf(stderr, "X11.app: main(): argc=%d\n", argc);
- for(i=0; i < argc; i++) {
- fprintf(stderr, "\targv[%u] = %s\n", (unsigned)i, argv[i]);
- if(!strcmp(argv[i], "--listenonly")) {
- listenOnly = TRUE;
- }
- }
-
- mp = checkin_or_register(server_bootstrap_name);
- if(mp == MACH_PORT_NULL) {
- fprintf(stderr, "NULL mach service: %s", server_bootstrap_name);
- return EXIT_FAILURE;
- }
-
- /* Check if we need to do something other than listen, and make another
- * thread handle it.
- */
- if(!listenOnly) {
- pid_t child1, child2;
- int status;
-
- /* Do the fork-twice trick to avoid having to reap zombies */
- child1 = fork();
- switch (child1) {
- case -1: /* error */
- break;
-
- case 0: /* child1 */
- child2 = fork();
-
- switch (child2) {
- int max_files, i;
-
- case -1: /* error */
- break;
-
- case 0: /* child2 */
- /* close all open files except for standard streams */
- max_files = sysconf(_SC_OPEN_MAX);
- for(i = 3; i < max_files; i++)
- close(i);
-
- /* ensure stdin is on /dev/null */
- close(0);
- open("/dev/null", O_RDONLY);
-
- return startup_trigger(argc, argv, envp);
-
- default: /* parent (child1) */
- _exit(0);
- }
- break;
-
- default: /* parent */
- waitpid(child1, &status, 0);
- }
- }
-
- /* Main event loop */
- fprintf(stderr, "Waiting for startup parameters via Mach IPC.\n");
- kr = mach_msg_server(mach_startup_server, mxmsgsz, mp, 0);
- if (kr != KERN_SUCCESS) {
- fprintf(stderr, "%s.X11(mp): %s\n", LAUNCHD_ID_PREFIX, mach_error_string(kr));
- return EXIT_FAILURE;
- }
-
- return EXIT_SUCCESS;
-}
-
-static int execute(const char *command) {
- const char *newargv[4];
- const char **p;
-
- newargv[0] = command_from_prefs("login_shell", DEFAULT_SHELL);
- newargv[1] = "-c";
- newargv[2] = command;
- newargv[3] = NULL;
-
- fprintf(stderr, "X11.app: Launching %s:\n", command);
- for(p=newargv; *p; p++) {
- fprintf(stderr, "\targv[%ld] = %s\n", (long int)(p - newargv), *p);
- }
-
- execvp (newargv[0], (char * const *) newargv);
- perror ("X11.app: Couldn't exec.");
- return 1;
-}
-
-static char *command_from_prefs(const char *key, const char *default_value) {
- char *command = NULL;
-
- CFStringRef cfKey;
- CFPropertyListRef PlistRef;
-
- if(!key)
- return NULL;
-
- cfKey = CFStringCreateWithCString(NULL, key, kCFStringEncodingASCII);
-
- if(!cfKey)
- return NULL;
-
- PlistRef = CFPreferencesCopyAppValue(cfKey, kCFPreferencesCurrentApplication);
-
- if ((PlistRef == NULL) || (CFGetTypeID(PlistRef) != CFStringGetTypeID())) {
- CFStringRef cfDefaultValue = CFStringCreateWithCString(NULL, default_value, kCFStringEncodingASCII);
- int len = strlen(default_value) + 1;
-
- if(!cfDefaultValue)
- goto command_from_prefs_out;
-
- CFPreferencesSetAppValue(cfKey, cfDefaultValue, kCFPreferencesCurrentApplication);
- CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
- CFRelease(cfDefaultValue);
-
- command = (char *)malloc(len * sizeof(char));
- if(!command)
- goto command_from_prefs_out;
- strcpy(command, default_value);
- } else {
- int len = CFStringGetLength((CFStringRef)PlistRef) + 1;
- command = (char *)malloc(len * sizeof(char));
- if(!command)
- goto command_from_prefs_out;
- CFStringGetCString((CFStringRef)PlistRef, command, len, kCFStringEncodingASCII);
- }
-
-command_from_prefs_out:
- if (PlistRef)
- CFRelease(PlistRef);
- if(cfKey)
- CFRelease(cfKey);
- return command;
-}
+/* main.c -- X application launcher + + Copyright (c) 2007 Jeremy Huddleston + Copyright (c) 2007 Apple 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 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. */ + +#include <CoreFoundation/CoreFoundation.h> +#include <AvailabilityMacros.h> + +#ifdef HAVE_DIX_CONFIG_H +#include <dix-config.h> +#endif + +#include <X11/Xlib.h> +#include <unistd.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include <stdbool.h> +#include <signal.h> + +#ifdef HAVE_LIBDISPATCH +#include <dispatch/dispatch.h> +#else +#include <pthread.h> +#endif + +#include <sys/socket.h> +#include <sys/un.h> + +#include <fcntl.h> + +#include <mach/mach.h> +#include <mach/mach_error.h> +#include <servers/bootstrap.h> +#include "mach_startup.h" +#include "mach_startupServer.h" + +#include "launchd_fd.h" +/* From darwinEvents.c ... but don't want to pull in all the server cruft */ +void DarwinListenOnOpenFD(int fd); + +extern int noPanoramiXExtension; + +#define DEFAULT_CLIENT X11BINDIR "/xterm" +#define DEFAULT_STARTX X11BINDIR "/startx" +#define DEFAULT_SHELL "/bin/sh" + +#ifndef BUILD_DATE +#define BUILD_DATE "" +#endif +#ifndef XSERVER_VERSION +#define XSERVER_VERSION "?" +#endif + +static char __crashreporter_info_buff__[4096] = {0}; +static const char *__crashreporter_info__ __attribute__((__used__)) = &__crashreporter_info_buff__[0]; +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 +// This is actually a toolchain requirement, but I'm not sure the correct check, +// but it should be fine to just only include it for Leopard and later. This line +// just tells the linker to never strip this symbol (such as for space optimization) +asm (".desc ___crashreporter_info__, 0x10"); +#endif + +static const char *__crashreporter_info__base = "X.Org X Server " XSERVER_VERSION " Build Date: " BUILD_DATE; + +static char *launchd_id_prefix = NULL; +static char *server_bootstrap_name = NULL; + +#define DEBUG 1 + +/* This is in quartzStartup.c */ +int server_main(int argc, char **argv, char **envp); + +static int execute(const char *command); +static char *command_from_prefs(const char *key, const char *default_value); + +#ifndef HAVE_LIBDISPATCH +/*** Pthread Magics ***/ +static pthread_t create_thread(void *(*func)(void *), void *arg) { + pthread_attr_t attr; + pthread_t tid; + + pthread_attr_init (&attr); + pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM); + pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); + pthread_create (&tid, &attr, func, arg); + pthread_attr_destroy (&attr); + + return tid; +} +#endif + +/*** Mach-O IPC Stuffs ***/ + +union MaxMsgSize { + union __RequestUnion__mach_startup_subsystem req; + union __ReplyUnion__mach_startup_subsystem rep; +}; + +static mach_port_t checkin_or_register(char *bname) { + kern_return_t kr; + mach_port_t mp; + + /* If we're started by launchd or the old mach_init */ + kr = bootstrap_check_in(bootstrap_port, bname, &mp); + if (kr == KERN_SUCCESS) + return mp; + + /* We probably were not started by launchd or the old mach_init */ + kr = mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &mp); + if (kr != KERN_SUCCESS) { + fprintf(stderr, "mach_port_allocate(): %s\n", mach_error_string(kr)); + exit(EXIT_FAILURE); + } + + kr = mach_port_insert_right(mach_task_self(), mp, mp, MACH_MSG_TYPE_MAKE_SEND); + if (kr != KERN_SUCCESS) { + fprintf(stderr, "mach_port_insert_right(): %s\n", mach_error_string(kr)); + exit(EXIT_FAILURE); + } + + kr = bootstrap_register(bootstrap_port, bname, mp); + if (kr != KERN_SUCCESS) { + fprintf(stderr, "bootstrap_register(): %s\n", mach_error_string(kr)); + exit(EXIT_FAILURE); + } + + return mp; +} + +/*** $DISPLAY handoff ***/ +static int accept_fd_handoff(int connected_fd) { + int launchd_fd; + + char databuf[] = "display"; + struct iovec iov[1]; + + union { + struct cmsghdr hdr; + char bytes[CMSG_SPACE(sizeof(int))]; + } buf; + + struct msghdr msg; + struct cmsghdr *cmsg; + + iov[0].iov_base = databuf; + iov[0].iov_len = sizeof(databuf); + + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = buf.bytes; + msg.msg_controllen = sizeof(buf); + msg.msg_name = 0; + msg.msg_namelen = 0; + msg.msg_flags = 0; + + cmsg = CMSG_FIRSTHDR (&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + + msg.msg_controllen = cmsg->cmsg_len; + + *((int*)CMSG_DATA(cmsg)) = -1; + + if(recvmsg(connected_fd, &msg, 0) < 0) { + fprintf(stderr, "X11.app: Error receiving $DISPLAY file descriptor. recvmsg() error: %s\n", strerror(errno)); + return -1; + } + + launchd_fd = *((int*)CMSG_DATA(cmsg)); + + return launchd_fd; +} + +typedef struct { + int fd; + string_t filename; +} socket_handoff_t; + +/* This thread accepts an incoming connection and hands off the file + * descriptor for the new connection to accept_fd_handoff() + */ +#ifdef HAVE_LIBDISPATCH +static void socket_handoff(socket_handoff_t *handoff_data) { +#else +static void *socket_handoff_thread(void *arg) { + socket_handoff_t *handoff_data = (socket_handoff_t *)arg; +#endif + + int launchd_fd = -1; + int connected_fd; + + /* Now actually get the passed file descriptor from this connection + * If we encounter an error, keep listening. + */ + while(launchd_fd == -1) { + connected_fd = accept(handoff_data->fd, NULL, NULL); + if(connected_fd == -1) { + fprintf(stderr, "X11.app: Failed to accept incoming connection on socket (fd=%d): %s\n", handoff_data->fd, strerror(errno)); + sleep(2); + continue; + } + + launchd_fd = accept_fd_handoff(connected_fd); + if(launchd_fd == -1) + fprintf(stderr, "X11.app: Error receiving $DISPLAY file descriptor, no descriptor received? Waiting for another connection.\n"); + + close(connected_fd); + } + + close(handoff_data->fd); + unlink(handoff_data->filename); + free(handoff_data); + + fprintf(stderr, "X11.app Handing off fd to server thread via DarwinListenOnOpenFD(%d)\n", launchd_fd); + DarwinListenOnOpenFD(launchd_fd); + +#ifndef HAVE_LIBDISPATCH + return NULL; +#endif +} + +static int create_socket(char *filename_out) { + struct sockaddr_un servaddr_un; + struct sockaddr *servaddr; + socklen_t servaddr_len; + int ret_fd; + size_t try, try_max; + + for(try=0, try_max=5; try < try_max; try++) { + tmpnam(filename_out); + + /* Setup servaddr_un */ + memset (&servaddr_un, 0, sizeof (struct sockaddr_un)); + servaddr_un.sun_family = AF_UNIX; + strlcpy(servaddr_un.sun_path, filename_out, sizeof(servaddr_un.sun_path)); + + servaddr = (struct sockaddr *) &servaddr_un; + servaddr_len = sizeof(struct sockaddr_un) - sizeof(servaddr_un.sun_path) + strlen(filename_out); + + ret_fd = socket(PF_UNIX, SOCK_STREAM, 0); + if(ret_fd == -1) { + fprintf(stderr, "X11.app: Failed to create socket (try %d / %d): %s - %s\n", (int)try+1, (int)try_max, filename_out, strerror(errno)); + continue; + } + + if(bind(ret_fd, servaddr, servaddr_len) != 0) { + fprintf(stderr, "X11.app: Failed to bind socket: %d - %s\n", errno, strerror(errno)); + close(ret_fd); + return 0; + } + + if(listen(ret_fd, 10) != 0) { + fprintf(stderr, "X11.app: Failed to listen to socket: %s - %d - %s\n", filename_out, errno, strerror(errno)); + close(ret_fd); + return 0; + } + +#ifdef DEBUG + fprintf(stderr, "X11.app: Listening on socket for fd handoff: (%d) %s\n", ret_fd, filename_out); +#endif + + return ret_fd; + } + + return 0; +} + +static int launchd_socket_handed_off = 0; + +kern_return_t do_request_fd_handoff_socket(mach_port_t port, string_t filename) { + socket_handoff_t *handoff_data; + + launchd_socket_handed_off = 1; + + handoff_data = (socket_handoff_t *)calloc(1,sizeof(socket_handoff_t)); + if(!handoff_data) { + fprintf(stderr, "X11.app: Error allocating memory for handoff_data\n"); + return KERN_FAILURE; + } + + handoff_data->fd = create_socket(handoff_data->filename); + if(!handoff_data->fd) { + free(handoff_data); + return KERN_FAILURE; + } + + strlcpy(filename, handoff_data->filename, STRING_T_SIZE); + +#ifdef HAVE_LIBDISPATCH + dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{ + socket_handoff(handoff_data); + }); +#else + create_thread(socket_handoff_thread, handoff_data); +#endif + +#ifdef DEBUG + fprintf(stderr, "X11.app: Thread created for handoff. Returning success to tell caller to connect and push the fd.\n"); +#endif + + return KERN_SUCCESS; +} + +kern_return_t do_request_pid(mach_port_t port, int *my_pid) { + *my_pid = getpid(); + return KERN_SUCCESS; +} + +/*** Server Startup ***/ +kern_return_t do_start_x11_server(mach_port_t port, string_array_t argv, + mach_msg_type_number_t argvCnt, + string_array_t envp, + mach_msg_type_number_t envpCnt) { + /* And now back to char ** */ + char **_argv = alloca((argvCnt + 1) * sizeof(char *)); + char **_envp = alloca((envpCnt + 1) * sizeof(char *)); + size_t i; + + /* If we didn't get handed a launchd DISPLAY socket, we should + * unset DISPLAY or we can run into problems with pbproxy + */ + if(!launchd_socket_handed_off) { + fprintf(stderr, "X11.app: No launchd socket handed off, unsetting DISPLAY\n"); + unsetenv("DISPLAY"); + } + + if(!_argv || !_envp) { + return KERN_FAILURE; + } + + fprintf(stderr, "X11.app: do_start_x11_server(): argc=%d\n", argvCnt); + for(i=0; i < argvCnt; i++) { + _argv[i] = argv[i]; + fprintf(stderr, "\targv[%u] = %s\n", (unsigned)i, argv[i]); + } + _argv[argvCnt] = NULL; + + for(i=0; i < envpCnt; i++) { + _envp[i] = envp[i]; + } + _envp[envpCnt] = NULL; + + if(server_main(argvCnt, _argv, _envp) == 0) + return KERN_SUCCESS; + else + return KERN_FAILURE; +} + +static int startup_trigger(int argc, char **argv, char **envp) { + Display *display; + const char *s; + + /* Take care of the case where we're called like a normal DDX */ + if(argc > 1 && argv[1][0] == ':') { + size_t i; + kern_return_t kr; + mach_port_t mp; + string_array_t newenvp; + string_array_t newargv; + + /* We need to count envp */ + int envpc; + for(envpc=0; envp[envpc]; envpc++); + + /* We have fixed-size string lengths due to limitations in IPC, + * so we need to copy our argv and envp. + */ + newargv = (string_array_t)alloca(argc * sizeof(string_t)); + newenvp = (string_array_t)alloca(envpc * sizeof(string_t)); + + if(!newargv || !newenvp) { + fprintf(stderr, "Memory allocation failure\n"); + exit(EXIT_FAILURE); + } + + for(i=0; i < argc; i++) { + strlcpy(newargv[i], argv[i], STRING_T_SIZE); + } + for(i=0; i < envpc; i++) { + strlcpy(newenvp[i], envp[i], STRING_T_SIZE); + } + + kr = bootstrap_look_up(bootstrap_port, server_bootstrap_name, &mp); + if (kr != KERN_SUCCESS) { +#if MAC_OS_X_VERSION_MIN_REQUIRED >= 1050 + fprintf(stderr, "bootstrap_look_up(%s): %s\n", server_bootstrap_name, bootstrap_strerror(kr)); +#else + fprintf(stderr, "bootstrap_look_up(%s): %ul\n", server_bootstrap_name, (unsigned long)kr); +#endif + exit(EXIT_FAILURE); + } + + kr = start_x11_server(mp, newargv, argc, newenvp, envpc); + if (kr != KERN_SUCCESS) { + fprintf(stderr, "start_x11_server: %s\n", mach_error_string(kr)); + exit(EXIT_FAILURE); + } + exit(EXIT_SUCCESS); + } + + /* If we have a process serial number and it's our only arg, act as if + * the user double clicked the app bundle: launch app_to_run if possible + */ + if(argc == 1 || (argc == 2 && !strncmp(argv[1], "-psn_", 5))) { + /* Now, try to open a display, if so, run the launcher */ + display = XOpenDisplay(NULL); + if(display) { + /* Could open the display, start the launcher */ + XCloseDisplay(display); + + return execute(command_from_prefs("app_to_run", DEFAULT_CLIENT)); + } + } + + /* Start the server */ + if((s = getenv("DISPLAY"))) { + fprintf(stderr, "X11.app: Could not connect to server (DISPLAY=\"%s\", unsetting). Starting X server.\n", s); + unsetenv("DISPLAY"); + } else { + fprintf(stderr, "X11.app: Could not connect to server (DISPLAY is not set). Starting X server.\n"); + } + return execute(command_from_prefs("startx_script", DEFAULT_STARTX)); +} + +/** Setup the environment we want our child processes to inherit */ +static void ensure_path(const char *dir) { + char buf[1024], *temp; + + /* Make sure /usr/X11/bin is in the $PATH */ + temp = getenv("PATH"); + if(temp == NULL || temp[0] == 0) { + snprintf(buf, sizeof(buf), "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:%s", dir); + setenv("PATH", buf, TRUE); + } else if(strnstr(temp, X11BINDIR, sizeof(temp)) == NULL) { + snprintf(buf, sizeof(buf), "%s:%s", temp, dir); + setenv("PATH", buf, TRUE); + } +} + +static void setup_env(void) { + char *temp; + const char *pds = NULL; + const char *disp = getenv("DISPLAY"); + size_t len; + + /* Pass on our prefs domain to startx and its inheritors (mainly for + * quartz-wm and the Xquartz stub's MachIPC) + */ + CFBundleRef bundle = CFBundleGetMainBundle(); + if(bundle) { + CFStringRef pd = CFBundleGetIdentifier(bundle); + if(pd) { + pds = CFStringGetCStringPtr(pd, 0); + } + } + + /* fallback to hardcoded value if we can't discover it */ + if(!pds) { + pds = LAUNCHD_ID_PREFIX".X11"; + } + + server_bootstrap_name = strdup(pds); + if(!server_bootstrap_name) { + fprintf(stderr, "X11.app: Memory allocation error.\n"); + exit(1); + } + setenv("X11_PREFS_DOMAIN", server_bootstrap_name, 1); + + len = strlen(server_bootstrap_name); + launchd_id_prefix = malloc(sizeof(char) * (len - 3)); + if(!launchd_id_prefix) { + fprintf(stderr, "X11.app: Memory allocation error.\n"); + exit(1); + } + strlcpy(launchd_id_prefix, server_bootstrap_name, len - 3); + + /* We need to unset DISPLAY if it is not our socket */ + if(disp) { + /* s = basename(disp) */ + const char *d, *s; + for(s = NULL, d = disp; *d; d++) { + if(*d == '/') + s = d + 1; + } + + if(s && *s) { + if(strcmp(launchd_id_prefix, "org.x") == 0 && strcmp(s, ":0") == 0) { + fprintf(stderr, "X11.app: Detected old style launchd DISPLAY, please update xinit.\n"); + } else { + temp = (char *)malloc(sizeof(char) * len); + if(!temp) { + fprintf(stderr, "X11.app: Memory allocation error creating space for socket name test.\n"); + exit(1); + } + strlcpy(temp, launchd_id_prefix, len); + strlcat(temp, ":0", len); + + if(strcmp(temp, s) != 0) { + /* If we don't have a match, unset it. */ + fprintf(stderr, "X11.app: DISPLAY (\"%s\") does not match our id (\"%s\"), unsetting.\n", disp, launchd_id_prefix); + unsetenv("DISPLAY"); + } + free(temp); + } + } else { + /* The DISPLAY environment variable is not formatted like a launchd socket, so reset. */ + fprintf(stderr, "X11.app: DISPLAY does not look like a launchd set variable, unsetting.\n"); + unsetenv("DISPLAY"); + } + } + + /* Make sure PATH is right */ + ensure_path(X11BINDIR); + + /* cd $HOME */ + temp = getenv("HOME"); + if(temp != NULL && temp[0] != '\0') + chdir(temp); +} + +/*** Main ***/ +int main(int argc, char **argv, char **envp) { + Bool listenOnly = FALSE; + int i; + mach_msg_size_t mxmsgsz = sizeof(union MaxMsgSize) + MAX_TRAILER_SIZE; + mach_port_t mp; + kern_return_t kr; + + /* Setup our environment for our children */ + setup_env(); + + /* The server must not run the PanoramiX operations. */ + noPanoramiXExtension = TRUE; + + /* Setup the initial crasherporter info */ + strlcpy(__crashreporter_info_buff__, __crashreporter_info__base, sizeof(__crashreporter_info_buff__)); + + fprintf(stderr, "X11.app: main(): argc=%d\n", argc); + for(i=0; i < argc; i++) { + fprintf(stderr, "\targv[%u] = %s\n", (unsigned)i, argv[i]); + if(!strcmp(argv[i], "--listenonly")) { + listenOnly = TRUE; + } + } + + mp = checkin_or_register(server_bootstrap_name); + if(mp == MACH_PORT_NULL) { + fprintf(stderr, "NULL mach service: %s", server_bootstrap_name); + return EXIT_FAILURE; + } + + /* Check if we need to do something other than listen, and make another + * thread handle it. + */ + if(!listenOnly) { + pid_t child1, child2; + int status; + + /* Do the fork-twice trick to avoid having to reap zombies */ + child1 = fork(); + switch (child1) { + case -1: /* error */ + break; + + case 0: /* child1 */ + child2 = fork(); + + switch (child2) { + int max_files, i; + + case -1: /* error */ + break; + + case 0: /* child2 */ + /* close all open files except for standard streams */ + max_files = sysconf(_SC_OPEN_MAX); + for(i = 3; i < max_files; i++) + close(i); + + /* ensure stdin is on /dev/null */ + close(0); + open("/dev/null", O_RDONLY); + + return startup_trigger(argc, argv, envp); + + default: /* parent (child1) */ + _exit(0); + } + break; + + default: /* parent */ + waitpid(child1, &status, 0); + } + } + + /* Main event loop */ + fprintf(stderr, "Waiting for startup parameters via Mach IPC.\n"); + kr = mach_msg_server(mach_startup_server, mxmsgsz, mp, 0); + if (kr != KERN_SUCCESS) { + fprintf(stderr, "%s.X11(mp): %s\n", LAUNCHD_ID_PREFIX, mach_error_string(kr)); + return EXIT_FAILURE; + } + + return EXIT_SUCCESS; +} + +static int execute(const char *command) { + const char *newargv[4]; + const char **p; + + newargv[0] = command_from_prefs("login_shell", DEFAULT_SHELL); + newargv[1] = "-c"; + newargv[2] = command; + newargv[3] = NULL; + + fprintf(stderr, "X11.app: Launching %s:\n", command); + for(p=newargv; *p; p++) { + fprintf(stderr, "\targv[%ld] = %s\n", (long int)(p - newargv), *p); + } + + execvp (newargv[0], (char * const *) newargv); + perror ("X11.app: Couldn't exec."); + return 1; +} + +static char *command_from_prefs(const char *key, const char *default_value) { + char *command = NULL; + + CFStringRef cfKey; + CFPropertyListRef PlistRef; + + if(!key) + return NULL; + + cfKey = CFStringCreateWithCString(NULL, key, kCFStringEncodingASCII); + + if(!cfKey) + return NULL; + + PlistRef = CFPreferencesCopyAppValue(cfKey, kCFPreferencesCurrentApplication); + + if ((PlistRef == NULL) || (CFGetTypeID(PlistRef) != CFStringGetTypeID())) { + CFStringRef cfDefaultValue = CFStringCreateWithCString(NULL, default_value, kCFStringEncodingASCII); + int len = strlen(default_value) + 1; + + if(!cfDefaultValue) + goto command_from_prefs_out; + + CFPreferencesSetAppValue(cfKey, cfDefaultValue, kCFPreferencesCurrentApplication); + CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication); + CFRelease(cfDefaultValue); + + command = (char *)malloc(len * sizeof(char)); + if(!command) + goto command_from_prefs_out; + strcpy(command, default_value); + } else { + int len = CFStringGetLength((CFStringRef)PlistRef) + 1; + command = (char *)malloc(len * sizeof(char)); + if(!command) + goto command_from_prefs_out; + CFStringGetCString((CFStringRef)PlistRef, command, len, kCFStringEncodingASCII); + } + +command_from_prefs_out: + if (PlistRef) + CFRelease(PlistRef); + if(cfKey) + CFRelease(cfKey); + return command; +} diff --git a/xorg-server/hw/xwin/winkeybd.c b/xorg-server/hw/xwin/winkeybd.c index 94318969f..912e2de1c 100644 --- a/xorg-server/hw/xwin/winkeybd.c +++ b/xorg-server/hw/xwin/winkeybd.c @@ -1,531 +1,531 @@ -/*
- *Copyright (C) 1994-2000 The XFree86 Project, 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 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 XFREE86 PROJECT 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 XFree86 Project
- *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 XFree86 Project.
- *
- * Authors: Dakshinamurthy Karra
- * Suhaib M Siddiqi
- * Peter Busch
- * Harold L Hunt II
- */
-
-
-#ifdef HAVE_XWIN_CONFIG_H
-#include <xwin-config.h>
-#endif
-#include "win.h"
-#include "winkeybd.h"
-#include "winconfig.h"
-#include "winmsg.h"
-
-#include "xkbsrv.h"
-
-static Bool g_winKeyState[NUM_KEYCODES];
-
-/*
- * Local prototypes
- */
-
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
- pointer pCtrl, int iClass);
-
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl);
-
-
-/*
- * Translate a Windows WM_[SYS]KEY(UP/DOWN) message
- * into an ASCII scan code.
- *
- * We do this ourselves, rather than letting Windows handle it,
- * because Windows tends to munge the handling of special keys,
- * like AltGr on European keyboards.
- */
-
-void
-winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode)
-{
- int iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1];
- int iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2];
- int iParam = HIWORD (lParam);
- int iParamScanCode = LOBYTE (iParam);
-
- winDebug("winTranslateKey: wParam %08x lParam %08x\n", wParam, 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)
- {
- if (VK_PRIOR <= wParam && wParam <= VK_DOWN)
- /* Trigger special case table to translate to extended
- * keycode, otherwise if num_lock is on, we can get keypad
- * numbers instead of navigation keys. */
- iParam |= KF_EXTENDED;
- else
- iParamScanCode = MapVirtualKeyEx(wParam,
- /*MAPVK_VK_TO_VSC*/0,
- GetKeyboardLayout(0));
- }
-
- /* Branch on special extended, special non-extended, or normal key */
- if ((iParam & KF_EXTENDED) && iKeyFixupEx)
- *piScanCode = iKeyFixupEx;
- else if (iKeyFixup)
- *piScanCode = iKeyFixup;
- else if (wParam == 0 && iParamScanCode == 0x70)
- *piScanCode = KEY_HKTG;
- else
- switch (iParamScanCode)
- {
- case 0x70:
- *piScanCode = KEY_HKTG;
- break;
- case 0x73:
- *piScanCode = KEY_BSlash2;
- break;
- default:
- *piScanCode = iParamScanCode;
- break;
- }
-}
-
-
-/* Ring the keyboard bell (system speaker on PCs) */
-static void
-winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt,
- pointer pCtrl, int iClass)
-{
- /*
- * We can't use Beep () here because it uses the PC speaker
- * on NT/2000. MessageBeep (MB_OK) will play the default system
- * sound on systems with a sound card or it will beep the PC speaker
- * on systems that do not have a sound card.
- */
- MessageBeep (MB_OK);
-}
-
-
-/* Change some keyboard configuration parameters */
-static void
-winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl)
-{
-}
-
-
-/*
- * See Porting Layer Definition - p. 18
- * winKeybdProc is known as a DeviceProc.
- */
-
-int
-winKeybdProc (DeviceIntPtr pDeviceInt, int iState)
-{
- DevicePtr pDevice = (DevicePtr) pDeviceInt;
- XkbSrvInfoPtr xkbi;
- XkbControlsPtr ctrl;
-
- switch (iState)
- {
- case DEVICE_INIT:
- winConfigKeyboard (pDeviceInt);
-
- /* FIXME: Maybe we should use winGetKbdLeds () here? */
- defaultKeyboardControl.leds = g_winInfo.keyboard.leds;
-
- winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\""
- " Variant = \"%s\" Options = \"%s\"\n",
- g_winInfo.xkb.rules ? g_winInfo.xkb.rules : "none",
- g_winInfo.xkb.model ? g_winInfo.xkb.model : "none",
- g_winInfo.xkb.layout ? g_winInfo.xkb.layout : "none",
- g_winInfo.xkb.variant ? g_winInfo.xkb.variant : "none",
- g_winInfo.xkb.options ? g_winInfo.xkb.options : "none");
-
- InitKeyboardDeviceStruct (pDeviceInt,
- &g_winInfo.xkb,
- winKeybdBell,
- winKeybdCtrl);
-
- xkbi = pDeviceInt->key->xkbInfo;
- if ((xkbi != NULL) && (xkbi->desc != NULL))
- {
- ctrl = xkbi->desc->ctrls;
- ctrl->repeat_delay = g_winInfo.keyboard.delay;
- ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate;
- }
- else
- {
- winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat\n");
- }
-
- break;
-
- case DEVICE_ON:
- pDevice->on = TRUE;
-
- // immediately copy the state of this keyboard device to the VCK
- // (which otherwise happens lazily after the first keypress)
- CopyKeyClass(pDeviceInt, inputInfo.keyboard);
- break;
-
- case DEVICE_CLOSE:
- case DEVICE_OFF:
- pDevice->on = FALSE;
- break;
- }
-
- return Success;
-}
-
-
-/*
- * Detect current mode key states upon server startup.
- *
- * Simulate a press and release of any key that is currently
- * toggled.
- */
-
-void
-winInitializeModeKeyStates (void)
-{
- /* Restore NumLock */
- if (GetKeyState (VK_NUMLOCK) & 0x0001)
- {
- winSendKeyEvent (KEY_NumLock, TRUE);
- winSendKeyEvent (KEY_NumLock, FALSE);
- }
-
- /* Restore CapsLock */
- if (GetKeyState (VK_CAPITAL) & 0x0001)
- {
- winSendKeyEvent (KEY_CapsLock, TRUE);
- winSendKeyEvent (KEY_CapsLock, FALSE);
- }
-
- /* Restore ScrollLock */
- if (GetKeyState (VK_SCROLL) & 0x0001)
- {
- winSendKeyEvent (KEY_ScrollLock, TRUE);
- winSendKeyEvent (KEY_ScrollLock, FALSE);
- }
-
- /* Restore KanaLock */
- if (GetKeyState (VK_KANA) & 0x0001)
- {
- winSendKeyEvent (KEY_HKTG, TRUE);
- winSendKeyEvent (KEY_HKTG, FALSE);
- }
-}
-
-
-/*
- * Upon regaining the keyboard focus we must
- * resynchronize our internal mode key states
- * with the actual state of the keys.
- */
-
-void
-winRestoreModeKeyStates (void)
-{
- DWORD dwKeyState;
- BOOL processEvents = TRUE;
- unsigned short internalKeyStates;
-
- /* X server is being initialized */
- if (!inputInfo.keyboard)
- return;
-
- /* Only process events if the rootwindow is mapped. The keyboard events
- * will cause segfaults otherwise */
- if (screenInfo.screens[0]->root && screenInfo.screens[0]->root->mapped == FALSE)
- processEvents = FALSE;
-
- /* Force to process all pending events in the mi event queue */
- if (processEvents)
- mieqProcessInputEvents ();
-
- /* Read the mode key states of our X server */
- /* (stored in the virtual core keyboard) */
- internalKeyStates = XkbStateFieldFromRec(&inputInfo.keyboard->key->xkbInfo->state);
- winDebug("winRestoreModeKeyStates: state %d\n", internalKeyStates);
-
- /*
- * NOTE: The C XOR operator, ^, will not work here because it is
- * a bitwise operator, not a logical operator. C does not
- * have a logical XOR operator, so we use a macro instead.
- */
-
- /* Has the key state changed? */
- dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001;
- if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState))
- {
- winSendKeyEvent (KEY_NumLock, TRUE);
- winSendKeyEvent (KEY_NumLock, FALSE);
- }
-
- /* Has the key state changed? */
- dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001;
- if (WIN_XOR (internalKeyStates & LockMask, dwKeyState))
- {
- winSendKeyEvent (KEY_CapsLock, TRUE);
- winSendKeyEvent (KEY_CapsLock, FALSE);
- }
-
- /* Has the key state changed? */
- dwKeyState = GetKeyState (VK_SCROLL) & 0x0001;
- if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState))
- {
- winSendKeyEvent (KEY_ScrollLock, TRUE);
- winSendKeyEvent (KEY_ScrollLock, FALSE);
- }
-
- /* Has the key state changed? */
- dwKeyState = GetKeyState (VK_KANA) & 0x0001;
- if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState))
- {
- winSendKeyEvent (KEY_HKTG, TRUE);
- winSendKeyEvent (KEY_HKTG, FALSE);
- }
-}
-
-
-/*
- * Look for the lovely fake Control_L press/release generated by Windows
- * when AltGr is pressed/released on a non-U.S. keyboard.
- */
-
-Bool
-winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam)
-{
- MSG msgNext;
- LONG lTime;
- Bool fReturn;
-
- /*
- * Fake Ctrl_L presses will be followed by an Alt_R keypress
- * with the same timestamp as the Ctrl_L press.
- */
- if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN)
- && wParam == VK_CONTROL
- && (HIWORD (lParam) & KF_EXTENDED) == 0)
- {
- /* Got a Ctrl_L press */
-
- /* Get time of current message */
- lTime = GetMessageTime ();
-
- /* Look for fake Ctrl_L preceeding an Alt_R press. */
- fReturn = PeekMessage (&msgNext, NULL,
- WM_KEYDOWN, WM_SYSKEYDOWN,
- PM_NOREMOVE);
-
- /*
- * Try again if the first call fails.
- * NOTE: This usually happens when TweakUI is enabled.
- */
- if (!fReturn)
- {
- /* Voodoo to make sure that the Alt_R message has posted */
- Sleep (0);
-
- /* Look for fake Ctrl_L preceeding an Alt_R press. */
- fReturn = PeekMessage (&msgNext, NULL,
- WM_KEYDOWN, WM_SYSKEYDOWN,
- PM_NOREMOVE);
- }
- if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN)
- fReturn = 0;
-
- /* Is next press an Alt_R with the same timestamp? */
- if (fReturn && msgNext.wParam == VK_MENU
- && msgNext.time == lTime
- && (HIWORD (msgNext.lParam) & KF_EXTENDED))
- {
- /*
- * Next key press is Alt_R with same timestamp as current
- * Ctrl_L message. Therefore, this Ctrl_L press is a fake
- * event, so discard it.
- */
- return TRUE;
- }
- }
-
- /*
- * Fake Ctrl_L releases will be followed by an Alt_R release
- * with the same timestamp as the Ctrl_L release.
- */
- if ((message == WM_KEYUP || message == WM_SYSKEYUP)
- && wParam == VK_CONTROL
- && (HIWORD (lParam) & KF_EXTENDED) == 0)
- {
- /* Got a Ctrl_L release */
-
- /* Get time of current message */
- lTime = GetMessageTime ();
-
- /* Look for fake Ctrl_L release preceeding an Alt_R release. */
- fReturn = PeekMessage (&msgNext, NULL,
- WM_KEYUP, WM_SYSKEYUP,
- PM_NOREMOVE);
-
- /*
- * Try again if the first call fails.
- * NOTE: This usually happens when TweakUI is enabled.
- */
- if (!fReturn)
- {
- /* Voodoo to make sure that the Alt_R message has posted */
- Sleep (0);
-
- /* Look for fake Ctrl_L release preceeding an Alt_R release. */
- fReturn = PeekMessage (&msgNext, NULL,
- WM_KEYUP, WM_SYSKEYUP,
- PM_NOREMOVE);
- }
-
- if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP)
- fReturn = 0;
-
- /* Is next press an Alt_R with the same timestamp? */
- if (fReturn
- && (msgNext.message == WM_KEYUP
- || msgNext.message == WM_SYSKEYUP)
- && msgNext.wParam == VK_MENU
- && msgNext.time == lTime
- && (HIWORD (msgNext.lParam) & KF_EXTENDED))
- {
- /*
- * Next key release is Alt_R with same timestamp as current
- * Ctrl_L message. Therefore, this Ctrl_L release is a fake
- * event, so discard it.
- */
- return TRUE;
- }
- }
-
- /* Not a fake control left press/release */
- return FALSE;
-}
-
-
-/*
- * Lift any modifier keys that are pressed
- */
-
-void
-winKeybdReleaseKeys (void)
-{
- int i;
-
-#ifdef HAS_DEVWINDOWS
- /* Verify that the mi input system has been initialized */
- if (g_fdMessageQueue == WIN_FD_INVALID)
- return;
-#endif
-
- /* Loop through all keys */
- for (i = 0; i < NUM_KEYCODES; ++i)
- {
- /* Pop key if pressed */
- if (g_winKeyState[i])
- winSendKeyEvent (i, FALSE);
-
- /* Reset pressed flag for keys */
- g_winKeyState[i] = FALSE;
- }
-}
-
-
-/*
- * Take a raw X key code and send an up or down event for it.
- *
- * Thanks to VNC for inspiration, though it is a simple function.
- */
-
-void
-winSendKeyEvent (DWORD dwKey, Bool fDown)
-{
- EventListPtr events;
- int i, nevents;
-
- /*
- * When alt-tabing between screens we can get phantom key up messages
- * Here we only pass them through it we think we should!
- */
- if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return;
-
- /* Update the keyState map */
- g_winKeyState[dwKey] = fDown;
-
- GetEventList(&events);
- nevents = GetKeyboardEvents(events, g_pwinKeyboard, fDown ? KeyPress : KeyRelease, dwKey + MIN_KEYCODE);
-
- for (i = 0; i < nevents; i++)
- mieqEnqueue(g_pwinKeyboard, (InternalEvent*)events[i].event);
-
- winDebug("winSendKeyEvent: dwKey: %d, fDown: %d, nEvents %d\n",
- dwKey, fDown, nevents);
-}
-
-BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam)
-{
- switch (wParam)
- {
- case VK_CONTROL:
- if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl])
- return TRUE;
- if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl])
- return TRUE;
- break;
- case VK_SHIFT:
- if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR])
- return TRUE;
- if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL])
- return TRUE;
- break;
- default:
- return TRUE;
- }
- return FALSE;
-}
-
-/* Only on shift release message is sent even if both are pressed.
- * Fix this here
- */
-void winFixShiftKeys (int iScanCode)
-{
- if (GetKeyState (VK_SHIFT) & 0x8000)
- return;
-
- if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR])
- winSendKeyEvent (KEY_ShiftR, FALSE);
- if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL])
- winSendKeyEvent (KEY_ShiftL, FALSE);
-}
+/* + *Copyright (C) 1994-2000 The XFree86 Project, 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 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 XFREE86 PROJECT 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 XFree86 Project + *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 XFree86 Project. + * + * Authors: Dakshinamurthy Karra + * Suhaib M Siddiqi + * Peter Busch + * Harold L Hunt II + */ + + +#ifdef HAVE_XWIN_CONFIG_H +#include <xwin-config.h> +#endif +#include "win.h" +#include "winkeybd.h" +#include "winconfig.h" +#include "winmsg.h" + +#include "xkbsrv.h" + +static Bool g_winKeyState[NUM_KEYCODES]; + +/* + * Local prototypes + */ + +static void +winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt, + pointer pCtrl, int iClass); + +static void +winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl); + + +/* + * Translate a Windows WM_[SYS]KEY(UP/DOWN) message + * into an ASCII scan code. + * + * We do this ourselves, rather than letting Windows handle it, + * because Windows tends to munge the handling of special keys, + * like AltGr on European keyboards. + */ + +void +winTranslateKey (WPARAM wParam, LPARAM lParam, int *piScanCode) +{ + int iKeyFixup = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 1]; + int iKeyFixupEx = g_iKeyMap[wParam * WIN_KEYMAP_COLS + 2]; + int iParam = HIWORD (lParam); + int iParamScanCode = LOBYTE (iParam); + + winDebug("winTranslateKey: wParam %08x lParam %08x\n", wParam, 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) + { + if (VK_PRIOR <= wParam && wParam <= VK_DOWN) + /* Trigger special case table to translate to extended + * keycode, otherwise if num_lock is on, we can get keypad + * numbers instead of navigation keys. */ + iParam |= KF_EXTENDED; + else + iParamScanCode = MapVirtualKeyEx(wParam, + /*MAPVK_VK_TO_VSC*/0, + GetKeyboardLayout(0)); + } + + /* Branch on special extended, special non-extended, or normal key */ + if ((iParam & KF_EXTENDED) && iKeyFixupEx) + *piScanCode = iKeyFixupEx; + else if (iKeyFixup) + *piScanCode = iKeyFixup; + else if (wParam == 0 && iParamScanCode == 0x70) + *piScanCode = KEY_HKTG; + else + switch (iParamScanCode) + { + case 0x70: + *piScanCode = KEY_HKTG; + break; + case 0x73: + *piScanCode = KEY_BSlash2; + break; + default: + *piScanCode = iParamScanCode; + break; + } +} + + +/* Ring the keyboard bell (system speaker on PCs) */ +static void +winKeybdBell (int iPercent, DeviceIntPtr pDeviceInt, + pointer pCtrl, int iClass) +{ + /* + * We can't use Beep () here because it uses the PC speaker + * on NT/2000. MessageBeep (MB_OK) will play the default system + * sound on systems with a sound card or it will beep the PC speaker + * on systems that do not have a sound card. + */ + MessageBeep (MB_OK); +} + + +/* Change some keyboard configuration parameters */ +static void +winKeybdCtrl (DeviceIntPtr pDevice, KeybdCtrl *pCtrl) +{ +} + + +/* + * See Porting Layer Definition - p. 18 + * winKeybdProc is known as a DeviceProc. + */ + +int +winKeybdProc (DeviceIntPtr pDeviceInt, int iState) +{ + DevicePtr pDevice = (DevicePtr) pDeviceInt; + XkbSrvInfoPtr xkbi; + XkbControlsPtr ctrl; + + switch (iState) + { + case DEVICE_INIT: + winConfigKeyboard (pDeviceInt); + + /* FIXME: Maybe we should use winGetKbdLeds () here? */ + defaultKeyboardControl.leds = g_winInfo.keyboard.leds; + + winErrorFVerb(2, "Rules = \"%s\" Model = \"%s\" Layout = \"%s\"" + " Variant = \"%s\" Options = \"%s\"\n", + g_winInfo.xkb.rules ? g_winInfo.xkb.rules : "none", + g_winInfo.xkb.model ? g_winInfo.xkb.model : "none", + g_winInfo.xkb.layout ? g_winInfo.xkb.layout : "none", + g_winInfo.xkb.variant ? g_winInfo.xkb.variant : "none", + g_winInfo.xkb.options ? g_winInfo.xkb.options : "none"); + + InitKeyboardDeviceStruct (pDeviceInt, + &g_winInfo.xkb, + winKeybdBell, + winKeybdCtrl); + + xkbi = pDeviceInt->key->xkbInfo; + if ((xkbi != NULL) && (xkbi->desc != NULL)) + { + ctrl = xkbi->desc->ctrls; + ctrl->repeat_delay = g_winInfo.keyboard.delay; + ctrl->repeat_interval = 1000/g_winInfo.keyboard.rate; + } + else + { + winErrorFVerb (1, "winKeybdProc - Error initializing keyboard AutoRepeat\n"); + } + + break; + + case DEVICE_ON: + pDevice->on = TRUE; + + // immediately copy the state of this keyboard device to the VCK + // (which otherwise happens lazily after the first keypress) + CopyKeyClass(pDeviceInt, inputInfo.keyboard); + break; + + case DEVICE_CLOSE: + case DEVICE_OFF: + pDevice->on = FALSE; + break; + } + + return Success; +} + + +/* + * Detect current mode key states upon server startup. + * + * Simulate a press and release of any key that is currently + * toggled. + */ + +void +winInitializeModeKeyStates (void) +{ + /* Restore NumLock */ + if (GetKeyState (VK_NUMLOCK) & 0x0001) + { + winSendKeyEvent (KEY_NumLock, TRUE); + winSendKeyEvent (KEY_NumLock, FALSE); + } + + /* Restore CapsLock */ + if (GetKeyState (VK_CAPITAL) & 0x0001) + { + winSendKeyEvent (KEY_CapsLock, TRUE); + winSendKeyEvent (KEY_CapsLock, FALSE); + } + + /* Restore ScrollLock */ + if (GetKeyState (VK_SCROLL) & 0x0001) + { + winSendKeyEvent (KEY_ScrollLock, TRUE); + winSendKeyEvent (KEY_ScrollLock, FALSE); + } + + /* Restore KanaLock */ + if (GetKeyState (VK_KANA) & 0x0001) + { + winSendKeyEvent (KEY_HKTG, TRUE); + winSendKeyEvent (KEY_HKTG, FALSE); + } +} + + +/* + * Upon regaining the keyboard focus we must + * resynchronize our internal mode key states + * with the actual state of the keys. + */ + +void +winRestoreModeKeyStates (void) +{ + DWORD dwKeyState; + BOOL processEvents = TRUE; + unsigned short internalKeyStates; + + /* X server is being initialized */ + if (!inputInfo.keyboard) + return; + + /* Only process events if the rootwindow is mapped. The keyboard events + * will cause segfaults otherwise */ + if (screenInfo.screens[0]->root && screenInfo.screens[0]->root->mapped == FALSE) + processEvents = FALSE; + + /* Force to process all pending events in the mi event queue */ + if (processEvents) + mieqProcessInputEvents (); + + /* Read the mode key states of our X server */ + /* (stored in the virtual core keyboard) */ + internalKeyStates = XkbStateFieldFromRec(&inputInfo.keyboard->key->xkbInfo->state); + winDebug("winRestoreModeKeyStates: state %d\n", internalKeyStates); + + /* + * NOTE: The C XOR operator, ^, will not work here because it is + * a bitwise operator, not a logical operator. C does not + * have a logical XOR operator, so we use a macro instead. + */ + + /* Has the key state changed? */ + dwKeyState = GetKeyState (VK_NUMLOCK) & 0x0001; + if (WIN_XOR (internalKeyStates & NumLockMask, dwKeyState)) + { + winSendKeyEvent (KEY_NumLock, TRUE); + winSendKeyEvent (KEY_NumLock, FALSE); + } + + /* Has the key state changed? */ + dwKeyState = GetKeyState (VK_CAPITAL) & 0x0001; + if (WIN_XOR (internalKeyStates & LockMask, dwKeyState)) + { + winSendKeyEvent (KEY_CapsLock, TRUE); + winSendKeyEvent (KEY_CapsLock, FALSE); + } + + /* Has the key state changed? */ + dwKeyState = GetKeyState (VK_SCROLL) & 0x0001; + if (WIN_XOR (internalKeyStates & ScrollLockMask, dwKeyState)) + { + winSendKeyEvent (KEY_ScrollLock, TRUE); + winSendKeyEvent (KEY_ScrollLock, FALSE); + } + + /* Has the key state changed? */ + dwKeyState = GetKeyState (VK_KANA) & 0x0001; + if (WIN_XOR (internalKeyStates & KanaMask, dwKeyState)) + { + winSendKeyEvent (KEY_HKTG, TRUE); + winSendKeyEvent (KEY_HKTG, FALSE); + } +} + + +/* + * Look for the lovely fake Control_L press/release generated by Windows + * when AltGr is pressed/released on a non-U.S. keyboard. + */ + +Bool +winIsFakeCtrl_L (UINT message, WPARAM wParam, LPARAM lParam) +{ + MSG msgNext; + LONG lTime; + Bool fReturn; + + /* + * Fake Ctrl_L presses will be followed by an Alt_R keypress + * with the same timestamp as the Ctrl_L press. + */ + if ((message == WM_KEYDOWN || message == WM_SYSKEYDOWN) + && wParam == VK_CONTROL + && (HIWORD (lParam) & KF_EXTENDED) == 0) + { + /* Got a Ctrl_L press */ + + /* Get time of current message */ + lTime = GetMessageTime (); + + /* Look for fake Ctrl_L preceeding an Alt_R press. */ + fReturn = PeekMessage (&msgNext, NULL, + WM_KEYDOWN, WM_SYSKEYDOWN, + PM_NOREMOVE); + + /* + * Try again if the first call fails. + * NOTE: This usually happens when TweakUI is enabled. + */ + if (!fReturn) + { + /* Voodoo to make sure that the Alt_R message has posted */ + Sleep (0); + + /* Look for fake Ctrl_L preceeding an Alt_R press. */ + fReturn = PeekMessage (&msgNext, NULL, + WM_KEYDOWN, WM_SYSKEYDOWN, + PM_NOREMOVE); + } + if (msgNext.message != WM_KEYDOWN && msgNext.message != WM_SYSKEYDOWN) + fReturn = 0; + + /* Is next press an Alt_R with the same timestamp? */ + if (fReturn && msgNext.wParam == VK_MENU + && msgNext.time == lTime + && (HIWORD (msgNext.lParam) & KF_EXTENDED)) + { + /* + * Next key press is Alt_R with same timestamp as current + * Ctrl_L message. Therefore, this Ctrl_L press is a fake + * event, so discard it. + */ + return TRUE; + } + } + + /* + * Fake Ctrl_L releases will be followed by an Alt_R release + * with the same timestamp as the Ctrl_L release. + */ + if ((message == WM_KEYUP || message == WM_SYSKEYUP) + && wParam == VK_CONTROL + && (HIWORD (lParam) & KF_EXTENDED) == 0) + { + /* Got a Ctrl_L release */ + + /* Get time of current message */ + lTime = GetMessageTime (); + + /* Look for fake Ctrl_L release preceeding an Alt_R release. */ + fReturn = PeekMessage (&msgNext, NULL, + WM_KEYUP, WM_SYSKEYUP, + PM_NOREMOVE); + + /* + * Try again if the first call fails. + * NOTE: This usually happens when TweakUI is enabled. + */ + if (!fReturn) + { + /* Voodoo to make sure that the Alt_R message has posted */ + Sleep (0); + + /* Look for fake Ctrl_L release preceeding an Alt_R release. */ + fReturn = PeekMessage (&msgNext, NULL, + WM_KEYUP, WM_SYSKEYUP, + PM_NOREMOVE); + } + + if (msgNext.message != WM_KEYUP && msgNext.message != WM_SYSKEYUP) + fReturn = 0; + + /* Is next press an Alt_R with the same timestamp? */ + if (fReturn + && (msgNext.message == WM_KEYUP + || msgNext.message == WM_SYSKEYUP) + && msgNext.wParam == VK_MENU + && msgNext.time == lTime + && (HIWORD (msgNext.lParam) & KF_EXTENDED)) + { + /* + * Next key release is Alt_R with same timestamp as current + * Ctrl_L message. Therefore, this Ctrl_L release is a fake + * event, so discard it. + */ + return TRUE; + } + } + + /* Not a fake control left press/release */ + return FALSE; +} + + +/* + * Lift any modifier keys that are pressed + */ + +void +winKeybdReleaseKeys (void) +{ + int i; + +#ifdef HAS_DEVWINDOWS + /* Verify that the mi input system has been initialized */ + if (g_fdMessageQueue == WIN_FD_INVALID) + return; +#endif + + /* Loop through all keys */ + for (i = 0; i < NUM_KEYCODES; ++i) + { + /* Pop key if pressed */ + if (g_winKeyState[i]) + winSendKeyEvent (i, FALSE); + + /* Reset pressed flag for keys */ + g_winKeyState[i] = FALSE; + } +} + + +/* + * Take a raw X key code and send an up or down event for it. + * + * Thanks to VNC for inspiration, though it is a simple function. + */ + +void +winSendKeyEvent (DWORD dwKey, Bool fDown) +{ + EventListPtr events; + int i, nevents; + + /* + * When alt-tabing between screens we can get phantom key up messages + * Here we only pass them through it we think we should! + */ + if (g_winKeyState[dwKey] == FALSE && fDown == FALSE) return; + + /* Update the keyState map */ + g_winKeyState[dwKey] = fDown; + + GetEventList(&events); + nevents = GetKeyboardEvents(events, g_pwinKeyboard, fDown ? KeyPress : KeyRelease, dwKey + MIN_KEYCODE, NULL); + + for (i = 0; i < nevents; i++) + mieqEnqueue(g_pwinKeyboard, (InternalEvent*)events[i].event); + + winDebug("winSendKeyEvent: dwKey: %d, fDown: %d, nEvents %d\n", + dwKey, fDown, nevents); +} + +BOOL winCheckKeyPressed(WPARAM wParam, LPARAM lParam) +{ + switch (wParam) + { + case VK_CONTROL: + if ((lParam & 0x1ff0000) == 0x11d0000 && g_winKeyState[KEY_RCtrl]) + return TRUE; + if ((lParam & 0x1ff0000) == 0x01d0000 && g_winKeyState[KEY_LCtrl]) + return TRUE; + break; + case VK_SHIFT: + if ((lParam & 0x1ff0000) == 0x0360000 && g_winKeyState[KEY_ShiftR]) + return TRUE; + if ((lParam & 0x1ff0000) == 0x02a0000 && g_winKeyState[KEY_ShiftL]) + return TRUE; + break; + default: + return TRUE; + } + return FALSE; +} + +/* Only on shift release message is sent even if both are pressed. + * Fix this here + */ +void winFixShiftKeys (int iScanCode) +{ + if (GetKeyState (VK_SHIFT) & 0x8000) + return; + + if (iScanCode == KEY_ShiftL && g_winKeyState[KEY_ShiftR]) + winSendKeyEvent (KEY_ShiftR, FALSE); + if (iScanCode == KEY_ShiftR && g_winKeyState[KEY_ShiftL]) + winSendKeyEvent (KEY_ShiftL, FALSE); +} |