xkb.c 220 KB
Newer Older
1 2 3 4 5 6 7 8
/************************************************************
Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.

Permission to use, copy, modify, and distribute this
software and its documentation for any purpose and without
fee is hereby granted, provided that the above copyright
notice appear in all copies and that both that copyright
notice and this permission notice appear in supporting
9 10
documentation, and that the name of Silicon Graphics not be
used in advertising or publicity pertaining to distribution
11
of the software without specific prior written permission.
12
Silicon Graphics makes no representation about the suitability
13 14 15
of this software for any purpose. It is provided "as is"
without any express or implied warranty.

16 17
SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
19 20 21
GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
22 23 24 25 26
OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
THE USE OR PERFORMANCE OF THIS SOFTWARE.

********************************************************/

27 28 29 30
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

31
#include <stdio.h>
32 33
#include <X11/X.h>
#include <X11/Xproto.h>
34
#include "misc.h"
35 36
#include "inputstr.h"
#define	XKBSRV_NEED_FILE_FUNCS
37
#include <xkbsrv.h>
38
#include "extnsionst.h"
39
#include "extinit.h"
40
#include "xace.h"
41
#include "xkb.h"
42
#include "protocol-versions.h"
43

44
#include <X11/extensions/XI.h>
45
#include <X11/extensions/XKMformat.h>
46

47 48 49 50 51 52
int XkbEventBase;
static int XkbErrorBase;
int XkbReqCode;
int XkbKeyboardErrorCode;
CARD32 xkbDebugFlags = 0;
static CARD32 xkbDebugCtrls = 0;
53

54
static RESTYPE RT_XKBCLIENT;
55 56 57

/***====================================================================***/

58
#define	CHK_DEVICE(dev, id, client, access_mode, lf) {\
59
    int why;\
60 61
    int tmprc = lf(&(dev), id, client, access_mode, &why);\
    if (tmprc != Success) {\
62
	client->errorValue = _XkbErrCode2(why, id);\
63
	return tmprc;\
64 65 66
    }\
}

67 68 69 70 71 72 73 74
#define	CHK_KBD_DEVICE(dev, id, client, mode) \
    CHK_DEVICE(dev, id, client, mode, _XkbLookupKeyboard)
#define	CHK_LED_DEVICE(dev, id, client, mode) \
    CHK_DEVICE(dev, id, client, mode, _XkbLookupLedDevice)
#define	CHK_BELL_DEVICE(dev, id, client, mode) \
    CHK_DEVICE(dev, id, client, mode, _XkbLookupBellDevice)
#define	CHK_ANY_DEVICE(dev, id, client, mode) \
    CHK_DEVICE(dev, id, client, mode, _XkbLookupAnyDevice)
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160

#define	CHK_ATOM_ONLY2(a,ev,er) {\
	if (((a)==None)||(!ValidAtom((a)))) {\
	    (ev)= (XID)(a);\
	    return er;\
	}\
}
#define	CHK_ATOM_ONLY(a) \
	CHK_ATOM_ONLY2(a,client->errorValue,BadAtom)

#define	CHK_ATOM_OR_NONE3(a,ev,er,ret) {\
	if (((a)!=None)&&(!ValidAtom((a)))) {\
	    (ev)= (XID)(a);\
	    (er)= BadAtom;\
	    return ret;\
	}\
}
#define	CHK_ATOM_OR_NONE2(a,ev,er) {\
	if (((a)!=None)&&(!ValidAtom((a)))) {\
	    (ev)= (XID)(a);\
	    return er;\
	}\
}
#define	CHK_ATOM_OR_NONE(a) \
	CHK_ATOM_OR_NONE2(a,client->errorValue,BadAtom)

#define	CHK_MASK_LEGAL3(err,mask,legal,ev,er,ret)	{\
	if ((mask)&(~(legal))) { \
	    (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\
	    (er)= BadValue;\
	    return ret;\
	}\
}
#define	CHK_MASK_LEGAL2(err,mask,legal,ev,er)	{\
	if ((mask)&(~(legal))) { \
	    (ev)= _XkbErrCode2((err),((mask)&(~(legal))));\
	    return er;\
	}\
}
#define	CHK_MASK_LEGAL(err,mask,legal) \
	CHK_MASK_LEGAL2(err,mask,legal,client->errorValue,BadValue)

#define	CHK_MASK_MATCH(err,affect,value) {\
	if ((value)&(~(affect))) { \
	    client->errorValue= _XkbErrCode2((err),((value)&(~(affect))));\
	    return BadMatch;\
	}\
}
#define	CHK_MASK_OVERLAP(err,m1,m2) {\
	if ((m1)&(m2)) { \
	    client->errorValue= _XkbErrCode2((err),((m1)&(m2)));\
	    return BadMatch;\
	}\
}
#define	CHK_KEY_RANGE2(err,first,num,x,ev,er) {\
	if (((unsigned)(first)+(num)-1)>(x)->max_key_code) {\
	    (ev)=_XkbErrCode4(err,(first),(num),(x)->max_key_code);\
	    return er;\
	}\
	else if ( (first)<(x)->min_key_code ) {\
	    (ev)=_XkbErrCode3(err+1,(first),xkb->min_key_code);\
	    return er;\
	}\
}
#define	CHK_KEY_RANGE(err,first,num,x)  \
	CHK_KEY_RANGE2(err,first,num,x,client->errorValue,BadValue)

#define	CHK_REQ_KEY_RANGE2(err,first,num,r,ev,er) {\
	if (((unsigned)(first)+(num)-1)>(r)->maxKeyCode) {\
	    (ev)=_XkbErrCode4(err,(first),(num),(r)->maxKeyCode);\
	    return er;\
	}\
	else if ( (first)<(r)->minKeyCode ) {\
	    (ev)=_XkbErrCode3(err+1,(first),(r)->minKeyCode);\
	    return er;\
	}\
}
#define	CHK_REQ_KEY_RANGE(err,first,num,r)  \
	CHK_REQ_KEY_RANGE2(err,first,num,r,client->errorValue,BadValue)

/***====================================================================***/

int
ProcXkbUseExtension(ClientPtr client)
{
    REQUEST(xkbUseExtensionReq);
161 162
    xkbUseExtensionReply rep;
    int supported;
163 164

    REQUEST_SIZE_MATCH(xkbUseExtensionReq);
165
    if (stuff->wantedMajor != SERVER_XKB_MAJOR_VERSION) {
166 167 168
        /* pre-release version 0.65 is compatible with 1.00 */
        supported = ((SERVER_XKB_MAJOR_VERSION == 1) &&
                     (stuff->wantedMajor == 0) && (stuff->wantedMinor == 65));
169
    }
170 171
    else
        supported = 1;
172

173 174 175 176
    if ((supported) && (!(client->xkbClientFlags & _XkbClientInitialized))) {
        client->xkbClientFlags = _XkbClientInitialized;
        client->vMajor = stuff->wantedMajor;
        client->vMinor = stuff->wantedMinor;
177
    }
178 179 180 181 182 183
    else if (xkbDebugFlags & 0x1) {
        ErrorF
            ("[xkb] Rejecting client %d (0x%lx) (wants %d.%02d, have %d.%02d)\n",
             client->index, (long) client->clientAsMask, stuff->wantedMajor,
             stuff->wantedMinor, SERVER_XKB_MAJOR_VERSION,
             SERVER_XKB_MINOR_VERSION);
184
    }
185 186 187 188 189 190 191 192
    rep = (xkbUseExtensionReply) {
        .type = X_Reply,
        .supported = supported,
        .sequenceNumber = client->sequence,
        .length = 0,
        .serverMajor = SERVER_XKB_MAJOR_VERSION,
        .serverMinor = SERVER_XKB_MINOR_VERSION
    };
193 194 195 196
    if (client->swapped) {
        swaps(&rep.sequenceNumber);
        swaps(&rep.serverMajor);
        swaps(&rep.serverMinor);
197
    }
198
    WriteToClient(client, SIZEOF(xkbUseExtensionReply), &rep);
199
    return Success;
200 201 202 203 204 205 206
}

/***====================================================================***/

int
ProcXkbSelectEvents(ClientPtr client)
{
207 208 209 210
    unsigned legal;
    DeviceIntPtr dev;
    XkbInterestPtr masks;

211 212 213 214
    REQUEST(xkbSelectEventsReq);

    REQUEST_AT_LEAST_SIZE(xkbSelectEventsReq);

215 216
    if (!(client->xkbClientFlags & _XkbClientInitialized))
        return BadAccess;
217

218
    CHK_ANY_DEVICE(dev, stuff->deviceSpec, client, DixUseAccess);
219

220 221 222
    if (((stuff->affectWhich & XkbMapNotifyMask) != 0) && (stuff->affectMap)) {
        client->mapNotifyMask &= ~stuff->affectMap;
        client->mapNotifyMask |= (stuff->affectMap & stuff->map);
223
    }
224 225 226 227 228 229
    if ((stuff->affectWhich & (~XkbMapNotifyMask)) == 0)
        return Success;

    masks = XkbFindClientResource((DevicePtr) dev, client);
    if (!masks) {
        XID id = FakeClientID(client->index);
230

231 232 233
        if (!AddResource(id, RT_XKBCLIENT, dev))
            return BadAlloc;
        masks = XkbAddClientResource((DevicePtr) dev, client, id);
234 235
    }
    if (masks) {
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
        union {
            CARD8 *c8;
            CARD16 *c16;
            CARD32 *c32;
        } from, to;
        register unsigned bit, ndx, maskLeft, dataLeft, size;

        from.c8 = (CARD8 *) &stuff[1];
        dataLeft = (stuff->length * 4) - SIZEOF(xkbSelectEventsReq);
        maskLeft = (stuff->affectWhich & (~XkbMapNotifyMask));
        for (ndx = 0, bit = 1; (maskLeft != 0); ndx++, bit <<= 1) {
            if ((bit & maskLeft) == 0)
                continue;
            maskLeft &= ~bit;
            switch (ndx) {
            case XkbNewKeyboardNotify:
                to.c16 = &client->newKeyboardNotifyMask;
                legal = XkbAllNewKeyboardEventsMask;
                size = 2;
                break;
            case XkbStateNotify:
                to.c16 = &masks->stateNotifyMask;
                legal = XkbAllStateEventsMask;
                size = 2;
                break;
            case XkbControlsNotify:
                to.c32 = &masks->ctrlsNotifyMask;
                legal = XkbAllControlEventsMask;
                size = 4;
                break;
            case XkbIndicatorStateNotify:
                to.c32 = &masks->iStateNotifyMask;
                legal = XkbAllIndicatorEventsMask;
                size = 4;
                break;
            case XkbIndicatorMapNotify:
                to.c32 = &masks->iMapNotifyMask;
                legal = XkbAllIndicatorEventsMask;
                size = 4;
                break;
            case XkbNamesNotify:
                to.c16 = &masks->namesNotifyMask;
                legal = XkbAllNameEventsMask;
                size = 2;
                break;
            case XkbCompatMapNotify:
                to.c8 = &masks->compatNotifyMask;
                legal = XkbAllCompatMapEventsMask;
                size = 1;
                break;
            case XkbBellNotify:
                to.c8 = &masks->bellNotifyMask;
                legal = XkbAllBellEventsMask;
                size = 1;
                break;
            case XkbActionMessage:
                to.c8 = &masks->actionMessageMask;
                legal = XkbAllActionMessagesMask;
                size = 1;
                break;
            case XkbAccessXNotify:
                to.c16 = &masks->accessXNotifyMask;
                legal = XkbAllAccessXEventsMask;
                size = 2;
                break;
            case XkbExtensionDeviceNotify:
                to.c16 = &masks->extDevNotifyMask;
                legal = XkbAllExtensionDeviceEventsMask;
                size = 2;
                break;
            default:
                client->errorValue = _XkbErrCode2(33, bit);
                return BadValue;
            }

            if (stuff->clear & bit) {
                if (size == 2)
                    to.c16[0] = 0;
                else if (size == 4)
                    to.c32[0] = 0;
                else
                    to.c8[0] = 0;
            }
            else if (stuff->selectAll & bit) {
                if (size == 2)
                    to.c16[0] = ~0;
                else if (size == 4)
                    to.c32[0] = ~0;
                else
                    to.c8[0] = ~0;
            }
            else {
                if (dataLeft < (size * 2))
                    return BadLength;
                if (size == 2) {
                    CHK_MASK_MATCH(ndx, from.c16[0], from.c16[1]);
                    CHK_MASK_LEGAL(ndx, from.c16[0], legal);
                    to.c16[0] &= ~from.c16[0];
                    to.c16[0] |= (from.c16[0] & from.c16[1]);
                }
                else if (size == 4) {
                    CHK_MASK_MATCH(ndx, from.c32[0], from.c32[1]);
                    CHK_MASK_LEGAL(ndx, from.c32[0], legal);
                    to.c32[0] &= ~from.c32[0];
                    to.c32[0] |= (from.c32[0] & from.c32[1]);
                }
                else {
                    CHK_MASK_MATCH(ndx, from.c8[0], from.c8[1]);
                    CHK_MASK_LEGAL(ndx, from.c8[0], legal);
                    to.c8[0] &= ~from.c8[0];
                    to.c8[0] |= (from.c8[0] & from.c8[1]);
                    size = 2;
                }
                from.c8 += (size * 2);
                dataLeft -= (size * 2);
            }
        }
        if (dataLeft > 2) {
            ErrorF("[xkb] Extra data (%d bytes) after SelectEvents\n",
                   dataLeft);
            return BadLength;
        }
        return Success;
359 360 361 362 363
    }
    return BadAlloc;
}

/***====================================================================***/
364 365 366 367 368 369 370 371
/**
 * Ring a bell on the given device for the given client.
 */
static int
_XkbBell(ClientPtr client, DeviceIntPtr dev, WindowPtr pWin,
         int bellClass, int bellID, int pitch, int duration,
         int percent, int forceSound, int eventOnly, Atom name)
{
372
    int base;
373
    void *ctrl;
374 375
    int oldPitch, oldDuration;
    int newPercent;
376 377

    if (bellClass == KbdFeedbackClass) {
378 379 380 381
        KbdFeedbackPtr k;

        if (bellID == XkbDfltXIId)
            k = dev->kbdfeed;
382
        else {
383
            for (k = dev->kbdfeed; k; k = k->next) {
384 385 386 387 388
                if (k->ctrl.id == bellID)
                    break;
            }
        }
        if (!k) {
389
            client->errorValue = _XkbErrCode2(0x5, bellID);
390 391 392
            return BadValue;
        }
        base = k->ctrl.bell;
393
        ctrl = (void *) &(k->ctrl);
394 395 396 397 398 399 400
        oldPitch = k->ctrl.bell_pitch;
        oldDuration = k->ctrl.bell_duration;
        if (pitch != 0) {
            if (pitch == -1)
                k->ctrl.bell_pitch = defaultKeyboardControl.bell_pitch;
            else
                k->ctrl.bell_pitch = pitch;
401
        }
402 403 404 405 406
        if (duration != 0) {
            if (duration == -1)
                k->ctrl.bell_duration = defaultKeyboardControl.bell_duration;
            else
                k->ctrl.bell_duration = duration;
407 408 409
        }
    }
    else if (bellClass == BellFeedbackClass) {
410 411 412 413
        BellFeedbackPtr b;

        if (bellID == XkbDfltXIId)
            b = dev->bell;
414
        else {
415
            for (b = dev->bell; b; b = b->next) {
416 417 418 419 420
                if (b->ctrl.id == bellID)
                    break;
            }
        }
        if (!b) {
421
            client->errorValue = _XkbErrCode2(0x6, bellID);
422 423 424
            return BadValue;
        }
        base = b->ctrl.percent;
425
        ctrl = (void *) &(b->ctrl);
426 427 428 429 430 431 432
        oldPitch = b->ctrl.pitch;
        oldDuration = b->ctrl.duration;
        if (pitch != 0) {
            if (pitch == -1)
                b->ctrl.pitch = defaultKeyboardControl.bell_pitch;
            else
                b->ctrl.pitch = pitch;
433
        }
434 435 436 437 438
        if (duration != 0) {
            if (duration == -1)
                b->ctrl.duration = defaultKeyboardControl.bell_duration;
            else
                b->ctrl.duration = duration;
439 440 441
        }
    }
    else {
442
        client->errorValue = _XkbErrCode2(0x7, bellClass);
443 444 445
        return BadValue;
    }

446
    newPercent = (base * percent) / 100;
447
    if (percent < 0)
448 449 450
        newPercent = base + newPercent;
    else
        newPercent = base - newPercent + percent;
451 452

    XkbHandleBell(forceSound, eventOnly,
453 454
                  dev, newPercent, ctrl, bellClass, name, pWin, client);
    if ((pitch != 0) || (duration != 0)) {
455
        if (bellClass == KbdFeedbackClass) {
456 457 458 459 460 461 462
            KbdFeedbackPtr k;

            k = (KbdFeedbackPtr) ctrl;
            if (pitch != 0)
                k->ctrl.bell_pitch = oldPitch;
            if (duration != 0)
                k->ctrl.bell_duration = oldDuration;
463 464
        }
        else {
465 466 467 468 469 470 471
            BellFeedbackPtr b;

            b = (BellFeedbackPtr) ctrl;
            if (pitch != 0)
                b->ctrl.pitch = oldPitch;
            if (duration != 0)
                b->ctrl.duration = oldDuration;
472 473 474 475 476
        }
    }

    return Success;
}
477 478 479 480 481 482

int
ProcXkbBell(ClientPtr client)
{
    REQUEST(xkbBellReq);
    DeviceIntPtr dev;
483
    WindowPtr pWin;
484
    int rc;
485 486 487

    REQUEST_SIZE_MATCH(xkbBellReq);

488 489
    if (!(client->xkbClientFlags & _XkbClientInitialized))
        return BadAccess;
490

491
    CHK_BELL_DEVICE(dev, stuff->deviceSpec, client, DixBellAccess);
492 493
    CHK_ATOM_OR_NONE(stuff->name);

494
    /* device-independent checks request for sane values */
495 496 497 498
    if ((stuff->forceSound) && (stuff->eventOnly)) {
        client->errorValue =
            _XkbErrCode3(0x1, stuff->forceSound, stuff->eventOnly);
        return BadMatch;
499 500
    }
    if (stuff->percent < -100 || stuff->percent > 100) {
501 502
        client->errorValue = _XkbErrCode2(0x2, stuff->percent);
        return BadValue;
503
    }
504 505 506
    if (stuff->duration < -1) {
        client->errorValue = _XkbErrCode2(0x3, stuff->duration);
        return BadValue;
507
    }
508 509 510
    if (stuff->pitch < -1) {
        client->errorValue = _XkbErrCode2(0x4, stuff->pitch);
        return BadValue;
511 512 513
    }

    if (stuff->bellClass == XkbDfltXIClass) {
514 515 516 517
        if (dev->kbdfeed != NULL)
            stuff->bellClass = KbdFeedbackClass;
        else
            stuff->bellClass = BellFeedbackClass;
518
    }
519

520 521 522 523 524 525
    if (stuff->window != None) {
        rc = dixLookupWindow(&pWin, stuff->window, client, DixGetAttrAccess);
        if (rc != Success) {
            client->errorValue = stuff->window;
            return rc;
        }
526
    }
527 528
    else
        pWin = NULL;
529

530 531 532 533 534 535 536 537 538 539 540 541 542 543
    /* Client wants to ring a bell on the core keyboard?
       Ring the bell on the core keyboard (which does nothing, but if that
       fails the client is screwed anyway), and then on all extension devices.
       Fail if the core keyboard fails but not the extension devices.  this
       may cause some keyboards to ding and others to stay silent. Fix
       your client to use explicit keyboards to avoid this.

       dev is the device the client requested.
     */
    rc = _XkbBell(client, dev, pWin, stuff->bellClass, stuff->bellID,
                  stuff->pitch, stuff->duration, stuff->percent,
                  stuff->forceSound, stuff->eventOnly, stuff->name);

    if ((rc == Success) && ((stuff->deviceSpec == XkbUseCoreKbd) ||
544
                            (stuff->deviceSpec == XkbUseCorePtr))) {
545
        DeviceIntPtr other;
546 547 548 549

        for (other = inputInfo.devices; other; other = other->next) {
            if ((other != dev) && other->key && !IsMaster(other) &&
                GetMaster(other, MASTER_KEYBOARD) == dev) {
550 551 552 553 554 555 556 557
                rc = XaceHook(XACE_DEVICE_ACCESS, client, other, DixBellAccess);
                if (rc == Success)
                    _XkbBell(client, other, pWin, stuff->bellClass,
                             stuff->bellID, stuff->pitch, stuff->duration,
                             stuff->percent, stuff->forceSound,
                             stuff->eventOnly, stuff->name);
            }
        }
558
        rc = Success;           /* reset to success, that's what we got for the VCK */
559
    }
560 561

    return rc;
562 563 564 565 566 567 568 569
}

/***====================================================================***/

int
ProcXkbGetState(ClientPtr client)
{
    REQUEST(xkbGetStateReq);
570 571 572
    DeviceIntPtr dev;
    xkbGetStateReply rep;
    XkbStateRec *xkb;
573 574 575

    REQUEST_SIZE_MATCH(xkbGetStateReq);

576 577
    if (!(client->xkbClientFlags & _XkbClientInitialized))
        return BadAccess;
578

579
    CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
580

581
    xkb = &dev->key->xkbInfo->state;
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
    rep = (xkbGetStateReply) {
        .type = X_Reply,
        .deviceID = dev->id,
        .sequenceNumber = client->sequence,
        .length = 0,
        .mods = XkbStateFieldFromRec(xkb) & 0xff,
        .baseMods = xkb->base_mods,
        .latchedMods = xkb->latched_mods,
        .lockedMods = xkb->locked_mods,
        .group = xkb->group,
        .lockedGroup = xkb->locked_group,
        .baseGroup = xkb->base_group,
        .latchedGroup = xkb->latched_group,
        .compatState = xkb->compat_state,
        .ptrBtnState = xkb->ptr_buttons
    };
598
    if (client->swapped) {
599 600
        swaps(&rep.sequenceNumber);
        swaps(&rep.ptrBtnState);
601
    }
602
    WriteToClient(client, SIZEOF(xkbGetStateReply), &rep);
603
    return Success;
604 605 606 607 608 609 610 611
}

/***====================================================================***/

int
ProcXkbLatchLockState(ClientPtr client)
{
    int status;
612
    DeviceIntPtr dev, tmpd;
613
    XkbStateRec oldState, *newState;
614
    CARD16 changed;
615 616
    xkbStateNotify sn;
    XkbEventCauseRec cause;
617 618 619 620

    REQUEST(xkbLatchLockStateReq);
    REQUEST_SIZE_MATCH(xkbLatchLockStateReq);

621
    if (!(client->xkbClientFlags & _XkbClientInitialized))
622
        return BadAccess;
623

624
    CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixSetAttrAccess);
625 626
    CHK_MASK_MATCH(0x01, stuff->affectModLocks, stuff->modLocks);
    CHK_MASK_MATCH(0x01, stuff->affectModLatches, stuff->modLatches);
627 628

    status = Success;
629 630

    for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) {
631 632
        if ((tmpd == dev) ||
            (!IsMaster(tmpd) && GetMaster(tmpd, MASTER_KEYBOARD) == dev)) {
633
            if (!tmpd->key || !tmpd->key->xkbInfo)
634 635 636 637 638 639
                continue;

            oldState = tmpd->key->xkbInfo->state;
            newState = &tmpd->key->xkbInfo->state;
            if (stuff->affectModLocks) {
                newState->locked_mods &= ~stuff->affectModLocks;
640 641
                newState->locked_mods |=
                    (stuff->affectModLocks & stuff->modLocks);
642 643 644 645 646 647 648
            }
            if (status == Success && stuff->lockGroup)
                newState->locked_group = stuff->groupLock;
            if (status == Success && stuff->affectModLatches)
                status = XkbLatchModifiers(tmpd, stuff->affectModLatches,
                                           stuff->modLatches);
            if (status == Success && stuff->latchGroup)
649
                status = XkbLatchGroup(tmpd, stuff->groupLatch);
650 651 652 653 654 655 656 657 658 659 660 661 662 663

            if (status != Success)
                return status;

            XkbComputeDerivedState(tmpd->key->xkbInfo);

            changed = XkbStateChangedFlags(&oldState, newState);
            if (changed) {
                sn.keycode = 0;
                sn.eventType = 0;
                sn.requestMajor = XkbReqCode;
                sn.requestMinor = X_kbLatchLockState;
                sn.changed = changed;
                XkbSendStateNotify(tmpd, &sn);
664
                changed = XkbIndicatorsToUpdate(tmpd, changed, FALSE);
665 666
                if (changed) {
                    XkbSetCauseXkbReq(&cause, X_kbLatchLockState, client);
667
                    XkbUpdateIndicators(tmpd, changed, TRUE, NULL, &cause);
668
                }
669 670
            }
        }
671
    }
672

673
    return Success;
674 675 676 677 678 679 680 681
}

/***====================================================================***/

int
ProcXkbGetControls(ClientPtr client)
{
    xkbGetControlsReply rep;
682 683
    XkbControlsPtr xkb;
    DeviceIntPtr dev;
684 685 686 687

    REQUEST(xkbGetControlsReq);
    REQUEST_SIZE_MATCH(xkbGetControlsReq);

688 689
    if (!(client->xkbClientFlags & _XkbClientInitialized))
        return BadAccess;
690

691
    CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
692

693
    xkb = dev->key->xkbInfo->desc->ctrls;
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725
    rep = (xkbGetControlsReply) {
        .type = X_Reply,
        .deviceID = ((DeviceIntPtr) dev)->id,
        .sequenceNumber = client->sequence,
        .length = bytes_to_int32(SIZEOF(xkbGetControlsReply) -
                                 SIZEOF(xGenericReply)),
        .mkDfltBtn = xkb->mk_dflt_btn,
        .numGroups = xkb->num_groups,
        .groupsWrap = xkb->groups_wrap,
        .internalMods = xkb->internal.mask,
        .ignoreLockMods = xkb->ignore_lock.mask,
        .internalRealMods = xkb->internal.real_mods,
        .ignoreLockRealMods = xkb->ignore_lock.real_mods,
        .internalVMods = xkb->internal.vmods,
        .ignoreLockVMods = xkb->ignore_lock.vmods,
        .repeatDelay = xkb->repeat_delay,
        .repeatInterval = xkb->repeat_interval,
        .slowKeysDelay = xkb->slow_keys_delay,
        .debounceDelay = xkb->debounce_delay,
        .mkDelay = xkb->mk_delay,
        .mkInterval = xkb->mk_interval,
        .mkTimeToMax = xkb->mk_time_to_max,
        .mkMaxSpeed = xkb->mk_max_speed,
        .mkCurve = xkb->mk_curve,
        .axOptions = xkb->ax_options,
        .axTimeout = xkb->ax_timeout,
        .axtOptsMask = xkb->axt_opts_mask,
        .axtOptsValues = xkb->axt_opts_values,
        .axtCtrlsMask = xkb->axt_ctrls_mask,
        .axtCtrlsValues = xkb->axt_ctrls_values,
        .enabledCtrls = xkb->enabled_ctrls,
    };
726
    memcpy(rep.perKeyRepeat, xkb->per_key_repeat, XkbPerKeyBitArraySize);
727
    if (client->swapped) {
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
        swaps(&rep.sequenceNumber);
        swapl(&rep.length);
        swaps(&rep.internalVMods);
        swaps(&rep.ignoreLockVMods);
        swapl(&rep.enabledCtrls);
        swaps(&rep.repeatDelay);
        swaps(&rep.repeatInterval);
        swaps(&rep.slowKeysDelay);
        swaps(&rep.debounceDelay);
        swaps(&rep.mkDelay);
        swaps(&rep.mkInterval);
        swaps(&rep.mkTimeToMax);
        swaps(&rep.mkMaxSpeed);
        swaps(&rep.mkCurve);
        swaps(&rep.axTimeout);
        swapl(&rep.axtCtrlsMask);
        swapl(&rep.axtCtrlsValues);
        swaps(&rep.axtOptsMask);
        swaps(&rep.axtOptsValues);
        swaps(&rep.axOptions);
    }
749
    WriteToClient(client, SIZEOF(xkbGetControlsReply), &rep);
750
    return Success;
751 752 753 754 755
}

int
ProcXkbSetControls(ClientPtr client)
{
756 757 758 759 760 761 762
    DeviceIntPtr dev, tmpd;
    XkbSrvInfoPtr xkbi;
    XkbControlsPtr ctrl;
    XkbControlsRec new, old;
    xkbControlsNotify cn;
    XkbEventCauseRec cause;
    XkbSrvLedInfoPtr sli;
763 764 765 766

    REQUEST(xkbSetControlsReq);
    REQUEST_SIZE_MATCH(xkbSetControlsReq);

767
    if (!(client->xkbClientFlags & _XkbClientInitialized))
768
        return BadAccess;
769

770
    CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixManageAccess);
771
    CHK_MASK_LEGAL(0x01, stuff->changeCtrls, XkbAllControlsMask);
772

773
    for (tmpd = inputInfo.devices; tmpd; tmpd = tmpd->next) {
774 775
        if (!tmpd->key || !tmpd->key->xkbInfo)
            continue;
776 777
        if ((tmpd == dev) ||
            (!IsMaster(tmpd) && GetMaster(tmpd, MASTER_KEYBOARD) == dev)) {
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795
            xkbi = tmpd->key->xkbInfo;
            ctrl = xkbi->desc->ctrls;
            new = *ctrl;
            XkbSetCauseXkbReq(&cause, X_kbSetControls, client);

            if (stuff->changeCtrls & XkbInternalModsMask) {
                CHK_MASK_MATCH(0x02, stuff->affectInternalMods,
                               stuff->internalMods);
                CHK_MASK_MATCH(0x03, stuff->affectInternalVMods,
                               stuff->internalVMods);

                new.internal.real_mods &= ~(stuff->affectInternalMods);
                new.internal.real_mods |= (stuff->affectInternalMods &
                                           stuff->internalMods);
                new.internal.vmods &= ~(stuff->affectInternalVMods);
                new.internal.vmods |= (stuff->affectInternalVMods &
                                       stuff->internalVMods);
                new.internal.mask = new.internal.real_mods |
796
                    XkbMaskForVMask(xkbi->desc, new.internal.vmods);
797
            }
798

799 800 801 802 803 804 805 806 807 808 809 810 811
            if (stuff->changeCtrls & XkbIgnoreLockModsMask) {
                CHK_MASK_MATCH(0x4, stuff->affectIgnoreLockMods,
                               stuff->ignoreLockMods);
                CHK_MASK_MATCH(0x5, stuff->affectIgnoreLockVMods,
                               stuff->ignoreLockVMods);

                new.ignore_lock.real_mods &= ~(stuff->affectIgnoreLockMods);
                new.ignore_lock.real_mods |= (stuff->affectIgnoreLockMods &
                                              stuff->ignoreLockMods);
                new.ignore_lock.vmods &= ~(stuff->affectIgnoreLockVMods);
                new.ignore_lock.vmods |= (stuff->affectIgnoreLockVMods &
                                          stuff->ignoreLockVMods);
                new.ignore_lock.mask = new.ignore_lock.real_mods |
812
                    XkbMaskForVMask(xkbi->desc, new.ignore_lock.vmods);
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
            }

            CHK_MASK_MATCH(0x06, stuff->affectEnabledCtrls,
                           stuff->enabledCtrls);
            if (stuff->affectEnabledCtrls) {
                CHK_MASK_LEGAL(0x07, stuff->affectEnabledCtrls,
                               XkbAllBooleanCtrlsMask);

                new.enabled_ctrls &= ~(stuff->affectEnabledCtrls);
                new.enabled_ctrls |= (stuff->affectEnabledCtrls &
                                      stuff->enabledCtrls);
            }

            if (stuff->changeCtrls & XkbRepeatKeysMask) {
                if (stuff->repeatDelay < 1 || stuff->repeatInterval < 1) {
                    client->errorValue = _XkbErrCode3(0x08, stuff->repeatDelay,
                                                      stuff->repeatInterval);
                    return BadValue;
                }

                new.repeat_delay = stuff->repeatDelay;
                new.repeat_interval = stuff->repeatInterval;
            }

            if (stuff->changeCtrls & XkbSlowKeysMask) {
                if (stuff->slowKeysDelay < 1) {
                    client->errorValue = _XkbErrCode2(0x09,
                                                      stuff->slowKeysDelay);
                    return BadValue;
                }

                new.slow_keys_delay = stuff->slowKeysDelay;
            }

            if (stuff->changeCtrls & XkbBounceKeysMask) {
                if (stuff->debounceDelay < 1) {
                    client->errorValue = _XkbErrCode2(0x0A,
                                                      stuff->debounceDelay);
                    return BadValue;
                }

                new.debounce_delay = stuff->debounceDelay;
            }
856

857 858 859 860 861
            if (stuff->changeCtrls & XkbMouseKeysMask) {
                if (stuff->mkDfltBtn > XkbMaxMouseKeysBtn) {
                    client->errorValue = _XkbErrCode2(0x0B, stuff->mkDfltBtn);
                    return BadValue;
                }
862

863 864 865 866 867 868 869
                new.mk_dflt_btn = stuff->mkDfltBtn;
            }

            if (stuff->changeCtrls & XkbMouseKeysAccelMask) {
                if (stuff->mkDelay < 1 || stuff->mkInterval < 1 ||
                    stuff->mkTimeToMax < 1 || stuff->mkMaxSpeed < 1 ||
                    stuff->mkCurve < -1000) {
870
                    client->errorValue = _XkbErrCode2(0x0C, 0);
871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
                    return BadValue;
                }

                new.mk_delay = stuff->mkDelay;
                new.mk_interval = stuff->mkInterval;
                new.mk_time_to_max = stuff->mkTimeToMax;
                new.mk_max_speed = stuff->mkMaxSpeed;
                new.mk_curve = stuff->mkCurve;
                AccessXComputeCurveFactor(xkbi, &new);
            }

            if (stuff->changeCtrls & XkbGroupsWrapMask) {
                unsigned act, num;

                act = XkbOutOfRangeGroupAction(stuff->groupsWrap);
                switch (act) {
                case XkbRedirectIntoRange:
                    num = XkbOutOfRangeGroupNumber(stuff->groupsWrap);
                    if (num >= new.num_groups) {
                        client->errorValue = _XkbErrCode3(0x0D, new.num_groups,
                                                          num);
                        return BadValue;
                    }
                case XkbWrapIntoRange:
                case XkbClampIntoRange:
                    break;
                default:
                    client->errorValue = _XkbErrCode2(0x0E, act);
                    return BadValue;
                }

902
                new.groups_wrap = stuff->groupsWrap;
903 904 905 906 907 908 909 910 911 912 913
            }

            CHK_MASK_LEGAL(0x0F, stuff->axOptions, XkbAX_AllOptionsMask);
            if (stuff->changeCtrls & XkbAccessXKeysMask) {
                new.ax_options = stuff->axOptions & XkbAX_AllOptionsMask;
            }
            else {
                if (stuff->changeCtrls & XkbStickyKeysMask) {
                    new.ax_options &= ~(XkbAX_SKOptionsMask);
                    new.ax_options |= (stuff->axOptions & XkbAX_SKOptionsMask);
                }
914

915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
                if (stuff->changeCtrls & XkbAccessXFeedbackMask) {
                    new.ax_options &= ~(XkbAX_FBOptionsMask);
                    new.ax_options |= (stuff->axOptions & XkbAX_FBOptionsMask);
                }
            }

            if (stuff->changeCtrls & XkbAccessXTimeoutMask) {
                if (stuff->axTimeout < 1) {
                    client->errorValue = _XkbErrCode2(0x10, stuff->axTimeout);
                    return BadValue;
                }
                CHK_MASK_MATCH(0x11, stuff->axtCtrlsMask,
                               stuff->axtCtrlsValues);
                CHK_MASK_LEGAL(0x12, stuff->axtCtrlsMask,
                               XkbAllBooleanCtrlsMask);
                CHK_MASK_MATCH(0x13, stuff->axtOptsMask, stuff->axtOptsValues);
                CHK_MASK_LEGAL(0x14, stuff->axtOptsMask, XkbAX_AllOptionsMask);
                new.ax_timeout = stuff->axTimeout;
                new.axt_ctrls_mask = stuff->axtCtrlsMask;
                new.axt_ctrls_values = (stuff->axtCtrlsValues &
                                        stuff->axtCtrlsMask);
                new.axt_opts_mask = stuff->axtOptsMask;
                new.axt_opts_values = (stuff->axtOptsValues &
                                       stuff->axtOptsMask);
            }

941
            if (stuff->changeCtrls & XkbPerKeyRepeatMask) {
942 943
                memcpy(new.per_key_repeat, stuff->perKeyRepeat,
                       XkbPerKeyBitArraySize);
944 945 946 947 948
                if (xkbi->repeatKey &&
                    !BitIsOn(new.per_key_repeat, xkbi->repeatKey)) {
                    AccessXCancelRepeatKey(xkbi, xkbi->repeatKey);
                }
            }
949

950 951
            old = *ctrl;
            *ctrl = new;
952 953
            XkbDDXChangeControls(tmpd, &old, ctrl);

954
            if (XkbComputeControlsNotify(tmpd, &old, ctrl, &cn, FALSE)) {
955 956 957 958 959 960 961 962 963
                cn.keycode = 0;
                cn.eventType = 0;
                cn.requestMajor = XkbReqCode;
                cn.requestMinor = X_kbSetControls;
                XkbSendControlsNotify(tmpd, &cn);
            }

            sli = XkbFindSrvLedInfo(tmpd, XkbDfltXIClass, XkbDfltXIId, 0);
            if (sli)
964
                XkbUpdateIndicators(tmpd, sli->usesControls, TRUE, NULL,
965 966 967 968 969
                                    &cause);

            /* If sticky keys were disabled, clear all locks and latches */
            if ((old.enabled_ctrls & XkbStickyKeysMask) &&
                !(ctrl->enabled_ctrls & XkbStickyKeysMask))
970
                XkbClearAllLatchesAndLocks(tmpd, xkbi, TRUE, &cause);
971
        }
972
    }
973

974
    return Success;
975 976 977 978 979
}

/***====================================================================***/

static int
980
XkbSizeKeyTypes(XkbDescPtr xkb, xkbGetMapReply * rep)
981
{
982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
    XkbKeyTypeRec *type;
    unsigned i, len;

    len = 0;
    if (((rep->present & XkbKeyTypesMask) == 0) || (rep->nTypes < 1) ||
        (!xkb) || (!xkb->map) || (!xkb->map->types)) {
        rep->present &= ~XkbKeyTypesMask;
        rep->firstType = rep->nTypes = 0;
        return 0;
    }
    type = &xkb->map->types[rep->firstType];
    for (i = 0; i < rep->nTypes; i++, type++) {
        len += SIZEOF(xkbKeyTypeWireDesc);
        if (type->map_count > 0) {
            len += (type->map_count * SIZEOF(xkbKTMapEntryWireDesc));
            if (type->preserve)
                len += (type->map_count * SIZEOF(xkbModsWireDesc));
        }
1000 1001 1002 1003 1004
    }
    return len;
}

static char *
1005 1006
XkbWriteKeyTypes(XkbDescPtr xkb,
                 xkbGetMapReply * rep, char *buf, ClientPtr client)
1007
{
1008 1009
    XkbKeyTypePtr type;
    unsigned i;
1010 1011
    xkbKeyTypeWireDesc *wire;

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028
    type = &xkb->map->types[rep->firstType];
    for (i = 0; i < rep->nTypes; i++, type++) {
        register unsigned n;

        wire = (xkbKeyTypeWireDesc *) buf;
        wire->mask = type->mods.mask;
        wire->realMods = type->mods.real_mods;
        wire->virtualMods = type->mods.vmods;
        wire->numLevels = type->num_levels;
        wire->nMapEntries = type->map_count;
        wire->preserve = (type->preserve != NULL);
        if (client->swapped) {
            swaps(&wire->virtualMods);
        }

        buf = (char *) &wire[1];
        if (wire->nMapEntries > 0) {
1029
            xkbKTMapEntryWireDesc *ewire;
1030 1031
            XkbKTMapEntryPtr entry;

1032
            ewire = (xkbKTMapEntryWireDesc *) buf;
1033
            entry = type->map;
1034 1035 1036 1037 1038 1039
            for (n = 0; n < type->map_count; n++, ewire++, entry++) {
                ewire->active = entry->active;
                ewire->mask = entry->mods.mask;
                ewire->level = entry->level;
                ewire->realMods = entry->mods.real_mods;
                ewire->virtualMods = entry->mods.vmods;
1040
                if (client->swapped) {
1041
                    swaps(&ewire->virtualMods);
1042 1043
                }
            }
1044
            buf = (char *) ewire;
1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
            if (type->preserve != NULL) {
                xkbModsWireDesc *pwire;
                XkbModsPtr preserve;

                pwire = (xkbModsWireDesc *) buf;
                preserve = type->preserve;
                for (n = 0; n < type->map_count; n++, pwire++, preserve++) {
                    pwire->mask = preserve->mask;
                    pwire->realMods = preserve->real_mods;
                    pwire->virtualMods = preserve->vmods;
                    if (client->swapped) {
                        swaps(&pwire->virtualMods);
                    }
                }
                buf = (char *) pwire;
            }
        }
1062 1063 1064 1065 1066
    }
    return buf;
}

static int
1067
XkbSizeKeySyms(XkbDescPtr xkb, xkbGetMapReply * rep)
1068
{
1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
    XkbSymMapPtr symMap;
    unsigned i, len;
    unsigned nSyms, nSymsThisKey;

    if (((rep->present & XkbKeySymsMask) == 0) || (rep->nKeySyms < 1) ||
        (!xkb) || (!xkb->map) || (!xkb->map->key_sym_map)) {
        rep->present &= ~XkbKeySymsMask;
        rep->firstKeySym = rep->nKeySyms = 0;
        rep->totalSyms = 0;
        return 0;
    }
    len = rep->nKeySyms * SIZEOF(xkbSymMapWireDesc);
1081
    symMap = &xkb->map->key_sym_map[rep->firstKeySym];
1082 1083 1084 1085 1086 1087 1088 1089
    for (i = nSyms = 0; i < rep->nKeySyms; i++, symMap++) {
        if (symMap->offset != 0) {
            nSymsThisKey = XkbNumGroups(symMap->group_info) * symMap->width;
            nSyms += nSymsThisKey;
        }
    }
    len += nSyms * 4;
    rep->totalSyms = nSyms;
1090 1091 1092 1093
    return len;
}

static int
1094
XkbSizeVirtualMods(XkbDescPtr xkb, xkbGetMapReply * rep)
1095
{
1096
    register unsigned i, nMods, bit;
1097

1098 1099 1100 1101 1102
    if (((rep->present & XkbVirtualModsMask) == 0) || (rep->virtualMods == 0) ||
        (!xkb) || (!xkb->server)) {
        rep->present &= ~XkbVirtualModsMask;
        rep->virtualMods = 0;
        return 0;
1103
    }
1104 1105 1106
    for (i = nMods = 0, bit = 1; i < XkbNumVirtualMods; i++, bit <<= 1) {
        if (rep->virtualMods & bit)
            nMods++;
1107 1108 1109 1110 1111
    }
    return XkbPaddedSize(nMods);
}

static char *
1112 1113
XkbWriteKeySyms(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                ClientPtr client)
1114
{
1115 1116 1117 1118
    register KeySym *pSym;
    XkbSymMapPtr symMap;
    xkbSymMapWireDesc *outMap;
    register unsigned i;
1119 1120

    symMap = &xkb->map->key_sym_map[rep->firstKeySym];
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    for (i = 0; i < rep->nKeySyms; i++, symMap++) {
        outMap = (xkbSymMapWireDesc *) buf;
        outMap->ktIndex[0] = symMap->kt_index[0];
        outMap->ktIndex[1] = symMap->kt_index[1];
        outMap->ktIndex[2] = symMap->kt_index[2];
        outMap->ktIndex[3] = symMap->kt_index[3];
        outMap->groupInfo = symMap->group_info;
        outMap->width = symMap->width;
        outMap->nSyms = symMap->width * XkbNumGroups(symMap->group_info);
        buf = (char *) &outMap[1];
        if (outMap->nSyms == 0)
            continue;

        pSym = &xkb->map->syms[symMap->offset];
        memcpy((char *) buf, (char *) pSym, outMap->nSyms * 4);
        if (client->swapped) {
            register int nSyms = outMap->nSyms;

            swaps(&outMap->nSyms);
            while (nSyms-- > 0) {
                swapl((int *) buf);
                buf += 4;
            }
        }
        else
            buf += outMap->nSyms * 4;
1147 1148 1149 1150 1151
    }
    return buf;
}

static int
1152
XkbSizeKeyActions(XkbDescPtr xkb, xkbGetMapReply * rep)
1153
{
1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
    unsigned i, len, nActs;
    register KeyCode firstKey;

    if (((rep->present & XkbKeyActionsMask) == 0) || (rep->nKeyActs < 1) ||
        (!xkb) || (!xkb->server) || (!xkb->server->key_acts)) {
        rep->present &= ~XkbKeyActionsMask;
        rep->firstKeyAct = rep->nKeyActs = 0;
        rep->totalActs = 0;
        return 0;
    }
    firstKey = rep->firstKeyAct;
    for (nActs = i = 0; i < rep->nKeyActs; i++) {
        if (xkb->server->key_acts[i + firstKey] != 0)
            nActs += XkbKeyNumActions(xkb, i + firstKey);
    }
    len = XkbPaddedSize(rep->nKeyActs) + (nActs * SIZEOF(xkbActionWireDesc));
    rep->totalActs = nActs;
1171 1172 1173 1174
    return len;
}

static char *
1175 1176
XkbWriteKeyActions(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                   ClientPtr client)
1177
{
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    unsigned i;
    CARD8 *numDesc;
    XkbAnyAction *actDesc;

    numDesc = (CARD8 *) buf;
    for (i = 0; i < rep->nKeyActs; i++) {
        if (xkb->server->key_acts[i + rep->firstKeyAct] == 0)
            numDesc[i] = 0;
        else
            numDesc[i] = XkbKeyNumActions(xkb, (i + rep->firstKeyAct));
    }
    buf += XkbPaddedSize(rep->nKeyActs);

    actDesc = (XkbAnyAction *) buf;
    for (i = 0; i < rep->nKeyActs; i++) {
        if (xkb->server->key_acts[i + rep->firstKeyAct] != 0) {
            unsigned int num;

            num = XkbKeyNumActions(xkb, (i + rep->firstKeyAct));
            memcpy((char *) actDesc,
                   (char *) XkbKeyActionsPtr(xkb, (i + rep->firstKeyAct)),
                   num * SIZEOF(xkbActionWireDesc));
            actDesc += num;
        }
    }
    buf = (char *) actDesc;
1204 1205 1206 1207
    return buf;
}

static int
1208
XkbSizeKeyBehaviors(XkbDescPtr xkb, xkbGetMapReply * rep)
1209
{
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
    unsigned i, len, nBhvr;
    XkbBehavior *bhv;

    if (((rep->present & XkbKeyBehaviorsMask) == 0) || (rep->nKeyBehaviors < 1)
        || (!xkb) || (!xkb->server) || (!xkb->server->behaviors)) {
        rep->present &= ~XkbKeyBehaviorsMask;
        rep->firstKeyBehavior = rep->nKeyBehaviors = 0;
        rep->totalKeyBehaviors = 0;
        return 0;
    }
    bhv = &xkb->server->behaviors[rep->firstKeyBehavior];
    for (nBhvr = i = 0; i < rep->nKeyBehaviors; i++, bhv++) {
        if (bhv->type != XkbKB_Default)
            nBhvr++;
    }
    len = nBhvr * SIZEOF(xkbBehaviorWireDesc);
    rep->totalKeyBehaviors = nBhvr;
1227 1228 1229 1230
    return len;
}

static char *
1231 1232
XkbWriteKeyBehaviors(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                     ClientPtr client)
1233
{
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
    unsigned i;
    xkbBehaviorWireDesc *wire;
    XkbBehavior *pBhvr;

    wire = (xkbBehaviorWireDesc *) buf;
    pBhvr = &xkb->server->behaviors[rep->firstKeyBehavior];
    for (i = 0; i < rep->nKeyBehaviors; i++, pBhvr++) {
        if (pBhvr->type != XkbKB_Default) {
            wire->key = i + rep->firstKeyBehavior;
            wire->type = pBhvr->type;
            wire->data = pBhvr->data;
            wire++;
        }
    }
    buf = (char *) wire;
1249 1250 1251 1252
    return buf;
}

static int
1253
XkbSizeExplicit(XkbDescPtr xkb, xkbGetMapReply * rep)
1254
{
1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270
    unsigned i, len, nRtrn;

    if (((rep->present & XkbExplicitComponentsMask) == 0) ||
        (rep->nKeyExplicit < 1) || (!xkb) || (!xkb->server) ||
        (!xkb->server->explicit)) {
        rep->present &= ~XkbExplicitComponentsMask;
        rep->firstKeyExplicit = rep->nKeyExplicit = 0;
        rep->totalKeyExplicit = 0;
        return 0;
    }
    for (nRtrn = i = 0; i < rep->nKeyExplicit; i++) {
        if (xkb->server->explicit[i + rep->firstKeyExplicit] != 0)
            nRtrn++;
    }
    rep->totalKeyExplicit = nRtrn;
    len = XkbPaddedSize(nRtrn * 2);     /* two bytes per non-zero explicit component */
1271 1272 1273 1274
    return len;
}

static char *
1275 1276
XkbWriteExplicit(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                 ClientPtr client)
1277
{
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291
    unsigned i;
    char *start;
    unsigned char *pExp;

    start = buf;
    pExp = &xkb->server->explicit[rep->firstKeyExplicit];
    for (i = 0; i < rep->nKeyExplicit; i++, pExp++) {
        if (*pExp != 0) {
            *buf++ = i + rep->firstKeyExplicit;
            *buf++ = *pExp;
        }
    }
    i = XkbPaddedSize(buf - start) - (buf - start);     /* pad to word boundary */
    return buf + i;
1292 1293 1294
}

static int
1295
XkbSizeModifierMap(XkbDescPtr xkb, xkbGetMapReply * rep)
1296
{
1297
    unsigned i, len, nRtrn;
1298

1299 1300 1301 1302 1303 1304
    if (((rep->present & XkbModifierMapMask) == 0) || (rep->nModMapKeys < 1) ||
        (!xkb) || (!xkb->map) || (!xkb->map->modmap)) {
        rep->present &= ~XkbModifierMapMask;
        rep->firstModMapKey = rep->nModMapKeys = 0;
        rep->totalModMapKeys = 0;
        return 0;
1305
    }
1306 1307 1308
    for (nRtrn = i = 0; i < rep->nModMapKeys; i++) {
        if (xkb->map->modmap[i + rep->firstModMapKey] != 0)
            nRtrn++;
1309
    }
1310 1311
    rep->totalModMapKeys = nRtrn;
    len = XkbPaddedSize(nRtrn * 2);     /* two bytes per non-zero modmap component */
1312 1313 1314 1315
    return len;
}

static char *
1316 1317
XkbWriteModifierMap(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                    ClientPtr client)
1318
{
1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    unsigned i;
    char *start;
    unsigned char *pMap;

    start = buf;
    pMap = &xkb->map->modmap[rep->firstModMapKey];
    for (i = 0; i < rep->nModMapKeys; i++, pMap++) {
        if (*pMap != 0) {
            *buf++ = i + rep->firstModMapKey;
            *buf++ = *pMap;
        }
    }
    i = XkbPaddedSize(buf - start) - (buf - start);     /* pad to word boundary */
    return buf + i;
1333 1334 1335
}

static int
1336
XkbSizeVirtualModMap(XkbDescPtr xkb, xkbGetMapReply * rep)
1337
{
1338
    unsigned i, len, nRtrn;
1339

1340 1341 1342 1343 1344 1345
    if (((rep->present & XkbVirtualModMapMask) == 0) || (rep->nVModMapKeys < 1)
        || (!xkb) || (!xkb->server) || (!xkb->server->vmodmap)) {
        rep->present &= ~XkbVirtualModMapMask;
        rep->firstVModMapKey = rep->nVModMapKeys = 0;
        rep->totalVModMapKeys = 0;
        return 0;
1346
    }
1347 1348 1349
    for (nRtrn = i = 0; i < rep->nVModMapKeys; i++) {
        if (xkb->server->vmodmap[i + rep->firstVModMapKey] != 0)
            nRtrn++;
1350
    }
1351 1352
    rep->totalVModMapKeys = nRtrn;
    len = nRtrn * SIZEOF(xkbVModMapWireDesc);
1353 1354 1355 1356
    return len;
}

static char *
1357 1358
XkbWriteVirtualModMap(XkbDescPtr xkb, xkbGetMapReply * rep, char *buf,
                      ClientPtr client)
1359
{
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
    unsigned i;
    xkbVModMapWireDesc *wire;
    unsigned short *pMap;

    wire = (xkbVModMapWireDesc *) buf;
    pMap = &xkb->server->vmodmap[rep->firstVModMapKey];
    for (i = 0; i < rep->nVModMapKeys; i++, pMap++) {
        if (*pMap != 0) {
            wire->key = i + rep->firstVModMapKey;
            wire->vmods = *pMap;
            wire++;
        }
    }
    return (char *) wire;
1374 1375 1376
}

static Status
1377
XkbComputeGetMapReplySize(XkbDescPtr xkb, xkbGetMapReply * rep)
1378
{
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391
    int len;

    rep->minKeyCode = xkb->min_key_code;
    rep->maxKeyCode = xkb->max_key_code;
    len = XkbSizeKeyTypes(xkb, rep);
    len += XkbSizeKeySyms(xkb, rep);
    len += XkbSizeKeyActions(xkb, rep);
    len += XkbSizeKeyBehaviors(xkb, rep);
    len += XkbSizeVirtualMods(xkb, rep);
    len += XkbSizeExplicit(xkb, rep);
    len += XkbSizeModifierMap(xkb, rep);
    len += XkbSizeVirtualModMap(xkb, rep);
    rep->length += (len / 4);
1392 1393 1394 1395
    return Success;
}

static int
1396
XkbSendMap(ClientPtr client, XkbDescPtr xkb, xkbGetMapReply * rep)
1397
{
1398 1399
    unsigned i, len;
    char *desc, *start;
1400

1401 1402
    len = (rep->length * 4) - (SIZEOF(xkbGetMapReply) - SIZEOF(xGenericReply));
    start = desc = calloc(1, len);
1403
    if (!start)
1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        return BadAlloc;
    if (rep->nTypes > 0)
        desc = XkbWriteKeyTypes(xkb, rep, desc, client);
    if (rep->nKeySyms > 0)
        desc = XkbWriteKeySyms(xkb, rep, desc, client);
    if (rep->nKeyActs > 0)
        desc = XkbWriteKeyActions(xkb, rep, desc, client);
    if (rep->totalKeyBehaviors > 0)
        desc = XkbWriteKeyBehaviors(xkb, rep, desc, client);
    if (rep->virtualMods) {
        register int sz, bit;

        for (i = sz = 0, bit = 1; i < XkbNumVirtualMods; i++, bit <<= 1) {
            if (rep->virtualMods & bit) {
                desc[sz++] = xkb->server->vmods[i];
            }
        }
        desc += XkbPaddedSize(sz);
    }
    if (rep->totalKeyExplicit > 0)
        desc = XkbWriteExplicit(xkb, rep, desc, client);
    if (rep->totalModMapKeys > 0)
        desc = XkbWriteModifierMap(xkb, rep, desc, client);
    if (rep->totalVModMapKeys > 0)
        desc = XkbWriteVirtualModMap(xkb, rep, desc, client);
    if ((desc - start) != (len)) {
        ErrorF
            ("[xkb] BOGUS LENGTH in write keyboard desc, expected %d, got %ld\n",
             len, (unsigned long) (desc - start));
1433 1434
    }
    if (client->swapped) {
1435 1436 1437 1438 1439
        swaps(&rep->sequenceNumber);
        swapl(&rep->length);
        swaps(&rep->present);
        swaps(&rep->totalSyms);
        swaps(&rep->totalActs);
1440
    }
1441
    WriteToClient(client, (i = SIZEOF(xkbGetMapReply)), rep);
1442
    WriteToClient(client, len, start);
1443
    free((char *) start);
1444
    return Success;
1445 1446 1447 1448 1449
}

int
ProcXkbGetMap(ClientPtr client)
{
1450 1451 1452 1453
    DeviceIntPtr dev;
    xkbGetMapReply rep;
    XkbDescRec *xkb;
    int n, status;
1454 1455 1456

    REQUEST(xkbGetMapReq);
    REQUEST_SIZE_MATCH(xkbGetMapReq);
1457 1458 1459

    if (!(client->xkbClientFlags & _XkbClientInitialized))
        return BadAccess;
1460

1461
    CHK_KBD_DEVICE(dev, stuff->deviceSpec, client, DixGetAttrAccess);
1462 1463 1464
    CHK_MASK_OVERLAP(0x01, stuff->full, stuff->partial);
    CHK_MASK_LEGAL(0x02, stuff->full, XkbAllMapComponentsMask);
    CHK_MASK_LEGAL(0x03, stuff->partial, XkbAllMapComponentsMask);
1465

1466
    xkb = dev->key->xkbInfo->desc;
1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
    rep = (xkbGetMapReply) {
        .type = X_Reply,
        .deviceID = dev->id,
        .sequenceNumber = client->sequence,
        .length = (SIZEOF(xkbGetMapReply) - SIZEOF(xGenericReply)) >> 2,
        .present = stuff->partial | stuff->full,
        .minKeyCode = xkb->min_key_code,
        .maxKeyCode = xkb->max_key_code
    };

1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
    if (stuff->full & XkbKeyTypesMask) {
        rep.firstType = 0;
        rep.nTypes = xkb->map->num_types;
    }
    else if (stuff->partial & XkbKeyTypesMask) {
        if (((unsigned) stuff->firstType + stuff->nTypes) > xkb->map->num_types) {
            client->errorValue = _XkbErrCode4(0x04, xkb->map->num_types,
                                              stuff->firstType, stuff->nTypes);
            return BadValue;
        }
        rep.firstType = stuff->firstType;
        rep.nTypes = stuff->nTypes;
    }
    else
        rep.nTypes = 0;
1492 1493
    rep.totalTypes = xkb->map->num_types;

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    n = XkbNumKeys(xkb);
    if (stuff->full & XkbKeySymsMask) {
        rep.firstKeySym = xkb->min_key_code;
        rep.nKeySyms = n;
    }
    else if (stuff->partial & XkbKeySymsMask) {
        CHK_KEY_RANGE(0x05, stuff->firstKeySym, stuff->nKeySyms, xkb);
        rep.firstKeySym = stuff->firstKeySym;
        rep.nKeySyms = stuff->nKeySyms;
    }
    else
        rep.nKeySyms = 0;
    rep.totalSyms = 0;

    if (stuff->full & XkbKeyActionsMask) {
        rep.firstKeyAct = xkb->min_key_code;
        rep.nKeyActs = n;
    }
    else if (stuff->partial & XkbKeyActionsMask) {
        CHK_KEY_RANGE(0x07, stuff->firstKeyAct, stuff->nKeyActs, xkb);
        rep.firstKeyAct = stuff->firstKeyAct;
        rep.nKeyActs = stuff->nKeyActs;
    }
    else
        rep.nKeyActs = 0;
    rep.totalActs = 0;

    if (stuff->full & XkbKeyBehaviorsMask) {
        rep.firstKeyBehavior = xkb->min_key_code;
        rep.nKeyBehaviors = n;
    }
    else if (stuff->partial & XkbKeyBehaviorsMask) {
        CHK_KEY_RANGE(0x09, stuff->firstKeyBehavior, stuff->nKeyBehaviors, xkb);
        rep.firstKeyBehavior = stuff->firstKeyBehavior;
        rep.nKeyBehaviors = stuff->nKeyBehaviors;
    }
    else
        rep.nKeyBehaviors = 0;
    rep.totalKeyBehaviors = 0;

    if (stuff->full & XkbVirtualModsMask)
        rep.virtualMods = ~0;
    else if (stuff->partial & XkbVirtualModsMask)
        rep.virtualMods = stuff->virtualMods;

    if (stuff->full & XkbExplicitComponentsMask) {
        rep.firstKeyExplicit = xkb->min_key_code;
        rep.nKeyExplicit = n;
    }
    else if (stuff->partial & XkbExplicitComponentsMask) {
        CHK_KEY_RANGE(0x0B, stuff->firstKeyExplicit, stuff->nKeyExplicit, xkb);
        rep.firstKeyExplicit = stuff->firstKeyExplicit;
        rep.nKeyExplicit = stuff->nKeyExplicit;
    }
    else
        rep.nKeyExplicit = 0;
    rep.totalKeyExplicit = 0;

    if (stuff->full & XkbModifierMapMask) {
        rep.firstModMapKey = xkb->min_key_code;
        rep.nModMapKeys = n;
    }
    else if (stuff->partial & XkbModifierMapMask) {
        CHK_KEY_RANGE(0x0D, stuff->firstModMapKey, stuff->nModMapKeys, xkb);
        rep.firstModMapKey = stuff->firstModMapKey;
        rep.nModMapKeys = stuff->nModMapKeys;
    }
    else
        rep.nModMapKeys = 0;
    rep.totalModMapKeys = 0;

    if (stuff->full & XkbVirtualModMapMask) {
        rep.firstVModMapKey = xkb->min_key_code;
        rep.nVModMapKeys = n;
    }
    else if (stuff->partial & XkbVirtualModMapMask) {
        CHK_KEY_RANGE(0x0F, stuff->firstVModMapKey, stuff->nVModMapKeys, xkb);
        rep.firstVModMapKey = stuff->firstVModMapKey;
        rep.nVModMapKeys = stuff->nVModMapKeys;
    }
    else
        rep.nVModMapKeys = 0;
    rep.totalVModMapKeys = 0;

    if ((status = XkbComputeGetMapReplySize(xkb, &rep)) != Success)
        return status;
    return XkbSendMap(client, xkb, &rep);
1581 1582 1583 1584 1585
}

/***====================================================================***/

static int
1586 1587 1588 1589 1590
CheckKeyTypes(ClientPtr client,
              XkbDescPtr xkb,
              xkbSetMapReq * req,
              xkbKeyTypeWireDesc ** wireRtrn,
              int *nMapsRtrn, CARD8 *mapWidthRtrn)
1591
{
1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613
    unsigned nMaps;
    register unsigned i, n;
    register CARD8 *map;
    register xkbKeyTypeWireDesc *wire = *wireRtrn;

    if (req->firstType > ((unsigned) xkb->map->num_types)) {
        *nMapsRtrn = _XkbErrCode3(0x01, req->firstType, xkb->map->num_types);
        return 0;
    }
    if (req->flags & XkbSetMapResizeTypes) {
        nMaps = req->firstType + req->nTypes;
        if (nMaps < XkbNumRequiredTypes) {      /* canonical types must be there */
            *nMapsRtrn = _XkbErrCode4(0x02, req->firstType, req->nTypes, 4);
            return 0;
        }
    }
    else if (req->present & XkbKeyTypesMask) {
        nMaps = xkb->map->num_types;
        if ((req->firstType + req->nTypes) > nMaps) {
            *nMapsRtrn = req->firstType + req->nTypes;
            return 0;
        }
1614 1615
    }
    else {
1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652
        *nMapsRtrn = xkb->map->num_types;
        for (i = 0; i < xkb->map->num_types; i++) {
            mapWidthRtrn[i] = xkb->map->types[i].num_levels;
        }
        return 1;
    }

    for (i = 0; i < req->firstType; i++) {
        mapWidthRtrn[i] = xkb->map->types[i].num_levels;
    }
    for (i = 0; i < req->nTypes; i++) {
        unsigned width;

        if (client->swapped) {
            swaps(&wire->virtualMods);
        }
        n = i + req->firstType;
        width = wire->numLevels;
        if (width < 1) {
            *nMapsRtrn = _XkbErrCode3(0x04, n, width);
            return 0;
        }
        else if ((n == XkbOneLevelIndex) && (width != 1)) {     /* must be width 1 */
            *nMapsRtrn = _XkbErrCode3(0x05, n, width);
            return 0;
        }
        else if ((width != 2) &&
                 ((n == XkbTwoLevelIndex) || (n == XkbKeypadIndex) ||
                  (n == XkbAlphabeticIndex))) {
            /* TWO_LEVEL, ALPHABETIC and KEYPAD must be width 2 */
            *nMapsRtrn = _XkbErrCode3(0x05, n, width);
            return 0;
        }
        if (wire->nMapEntries > 0) {
            xkbKTSetMapEntryWireDesc *mapWire;
            xkbModsWireDesc *preWire;

1653 1654
            mapWire = (xkbKTSetMapEntryWireDesc *) &wire[1];
            preWire = (xkbModsWireDesc *) &mapWire[wire->nMapEntries];
1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
            for (n = 0; n < wire->nMapEntries; n++) {
                if (client->swapped) {
                    swaps(&mapWire[n].virtualMods);
                }
                if (mapWire[n].realMods & (~wire->realMods)) {
                    *nMapsRtrn = _XkbErrCode4(0x06, n, mapWire[n].realMods,
                                              wire->realMods);
                    return 0;
                }
                if (mapWire[n].virtualMods & (~wire->virtualMods)) {
                    *nMapsRtrn = _XkbErrCode3(0x07, n, mapWire[n].virtualMods);
                    return 0;
                }
                if (mapWire[n].level >=<