summaryrefslogtreecommitdiff
path: root/dix/getevents.c
blob: 6d7d47e0d300319f78f31e108a3de67bd05274f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
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
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
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
902
903
904
905
906
907
908
909
910
911
912
913
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
/*
 * Copyright © 2006 Nokia Corporation
 * Copyright © 2006-2007 Daniel Stone
 * Copyright © 2008 Red Hat, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 *
 * Authors: Daniel Stone <daniel@fooishbar.org>
 *          Peter Hutterer <peter.hutterer@who-t.net>
 */

#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif

#include <X11/X.h>
#include <X11/keysym.h>
#include <X11/Xproto.h>

#include "misc.h"
#include "resource.h"
#include "inputstr.h"
#include "scrnintstr.h"
#include "cursorstr.h"
#include "dixstruct.h"
#include "globals.h"
#include "dixevents.h"
#include "mipointer.h"
#include "events.h"

#include <X11/extensions/XKBproto.h>
#include "xkbsrv.h"

#ifdef PANORAMIX
#include "panoramiX.h"
#include "panoramiXsrv.h"
#endif

#include <X11/extensions/XI.h>
#include <X11/extensions/XIproto.h>
#include "exglobals.h"
#include "exevents.h"
#include "exglobals.h"
#include "extnsionst.h"
#include "listdev.h" /* for sizing up DeviceClassesChangedEvent */

/* Number of motion history events to store. */
#define MOTION_HISTORY_SIZE 256

/* InputEventList is the container list for all input events generated by the
 * DDX. The DDX is expected to call GetEventList() and then pass the list into
 * Get{Pointer|Keyboard}Events.
 */
EventListPtr InputEventList = NULL;
int InputEventListLen = 0;

int
GetEventList(EventListPtr* list)
{
    *list = InputEventList;
    return InputEventListLen;
}

/**
 * Pick some arbitrary size for Xi motion history.
 */
int
GetMotionHistorySize(void)
{
    return MOTION_HISTORY_SIZE;
}

void
set_key_down(DeviceIntPtr pDev, int key_code, int type)
{
    if (type == KEY_PROCESSED)
        pDev->key->down[key_code >> 3] |= (1 << (key_code & 7));
    else
        pDev->key->postdown[key_code >> 3] |= (1 << (key_code & 7));
}

void
set_key_up(DeviceIntPtr pDev, int key_code, int type)
{
    if (type == KEY_PROCESSED)
        pDev->key->down[key_code >> 3] &= ~(1 << (key_code & 7));
    else
        pDev->key->postdown[key_code >> 3] &= ~(1 << (key_code & 7));
}

Bool
key_is_down(DeviceIntPtr pDev, int key_code, int type)
{
    int ret = 0;

    if (type & KEY_PROCESSED)
        ret |= !!(pDev->key->down[key_code >> 3] & (1 << (key_code & 7)));
    else if (type & KEY_POSTED)
        ret |= !!(pDev->key->postdown[key_code >> 3] & (1 << (key_code & 7)));

    return ret;
}

static Bool
key_autorepeats(DeviceIntPtr pDev, int key_code)
{
    return !!(pDev->kbdfeed->ctrl.autoRepeats[key_code >> 3] &
              (1 << (key_code & 7)));
}

static void
init_event(DeviceIntPtr dev, DeviceEvent* event, Time ms)
{
    memset(event, 0, sizeof(DeviceEvent));
    event->header = ET_Internal;
    event->length = sizeof(DeviceEvent);
    event->time = ms;
    event->deviceid = dev->id;
    event->sourceid = dev->id;
}

static void
set_valuators(DeviceIntPtr dev, DeviceEvent* event, int first_valuator,
              int num_valuators, int *valuators)
{
    int i;

    for (i = first_valuator; i < num_valuators; i++)
        SetBit(event->valuators.mask, i);

    /* FIXME: Set the current mode */

    memcpy(&event->valuators.data[first_valuator],
           valuators, num_valuators * sizeof(uint32_t));
}

void
CreateClassesChangedEvent(EventList* event,
                          DeviceIntPtr master,
                          DeviceIntPtr slave)
{
    DeviceChangedEvent *dce;
    CARD32 ms = GetTimeInMillis();

    dce = (DeviceChangedEvent*)event->event;
    memset(dce, 0, sizeof(DeviceChangedEvent));
    dce->header = ET_Internal;
    dce->length = sizeof(DeviceChangedEvent);
    dce->type = ET_DeviceChanged;
    dce->time = ms;
    if (master->u.lastSlave)
    {
        dce->flags |= HAS_OLD_SLAVE;
        dce->old_slaveid = master->u.lastSlave->id;
    }
    dce->flags |= HAS_NEW_SLAVE;
    dce->new_slaveid = slave->id;

    /* FIXME: fill in new information about the device. We need to do this
     * here to avoid race conditions if the device changes while the event
     * slumbers in the EQ.
     */

}

/**
 * Rescale the coord between the two axis ranges.
 */
static int
rescaleValuatorAxis(int coord, AxisInfoPtr from, AxisInfoPtr to,
                    int defmax)
{
    int fmin = 0, tmin = 0, fmax = defmax, tmax = defmax;

    if(from && from->min_value < from->max_value) {
        fmin = from->min_value;
        fmax = from->max_value;
    }
    if(to && to->min_value < to->max_value) {
        tmin = to->min_value;
        tmax = to->max_value;
    }

    if(fmin == tmin && fmax == tmax)
        return coord;

    if(fmax == fmin) /* avoid division by 0 */
        return 0;

    return roundf(((float)(coord - fmin)) * (tmax - tmin) /
                 (fmax - fmin)) + tmin;
}

/**
 * Update all coordinates when changing to a different SD
 * to ensure that relative reporting will work as expected
 * without loss of precision.
 *
 * pDev->last.valuators will be in absolute device coordinates after this
 * function.
 */
static void
updateSlaveDeviceCoords(DeviceIntPtr master, DeviceIntPtr pDev)
{
    ScreenPtr scr = miPointerGetScreen(pDev);
    int i;
    DeviceIntPtr lastSlave;

    /* master->last.valuators[0]/[1] is in screen coords and the actual
     * position of the pointer */
    pDev->last.valuators[0] = master->last.valuators[0];
    pDev->last.valuators[1] = master->last.valuators[1];

    if (!pDev->valuator)
        return;

    /* scale back to device coordinates */
    if(pDev->valuator->numAxes > 0)
        pDev->last.valuators[0] = rescaleValuatorAxis(pDev->last.valuators[0], NULL, pDev->valuator->axes + 0, scr->width);
    if(pDev->valuator->numAxes > 1)
        pDev->last.valuators[1] = rescaleValuatorAxis(pDev->last.valuators[1], NULL, pDev->valuator->axes + 1, scr->height);

    /* calculate the other axis as well based on info from the old
     * slave-device. If the old slave had less axes than this one,
     * last.valuators is reset to 0.
     */
    if ((lastSlave = master->u.lastSlave) && lastSlave->valuator) {
        for (i = 2; i < pDev->valuator->numAxes; i++) {
            if (i >= lastSlave->valuator->numAxes)
                pDev->last.valuators[i] = 0;
            else
                pDev->last.valuators[i] =
                    rescaleValuatorAxis(pDev->last.valuators[i],
                            lastSlave->valuator->axes + i,
                            pDev->valuator->axes + i, 0);
        }
    }

}

/**
 * Allocate the motion history buffer.
 */
void
AllocateMotionHistory(DeviceIntPtr pDev)
{
    int size;
    if (pDev->valuator->motion)
        xfree(pDev->valuator->motion);

    if (pDev->valuator->numMotionEvents < 1)
        return;

    /* An MD must have a motion history size large enough to keep all
     * potential valuators, plus the respective range of the valuators.
     * 3 * INT32 for (min_val, max_val, curr_val))
     */
    if (pDev->isMaster)
        size = sizeof(INT32) * 3 * MAX_VALUATORS;
    else
        size = sizeof(INT32) * pDev->valuator->numAxes;

    size += sizeof(Time);

    pDev->valuator->motion = xcalloc(pDev->valuator->numMotionEvents, size);
    pDev->valuator->first_motion = 0;
    pDev->valuator->last_motion = 0;
    if (!pDev->valuator->motion)
        ErrorF("[dix] %s: Failed to alloc motion history (%d bytes).\n",
                pDev->name, size * pDev->valuator->numMotionEvents);
}

/**
 * Dump the motion history between start and stop into the supplied buffer.
 * Only records the event for a given screen in theory, but in practice, we
 * sort of ignore this.
 *
 * If core is set, we only generate x/y, in INT16, scaled to screen coords.
 */
int
GetMotionHistory(DeviceIntPtr pDev, xTimecoord **buff, unsigned long start,
                 unsigned long stop, ScreenPtr pScreen, BOOL core)
{
    char *ibuff = NULL, *obuff;
    int i = 0, ret = 0;
    int j, coord;
    Time current;
    /* The size of a single motion event. */
    int size;
    int dflt;
    AxisInfo from, *to; /* for scaling */
    INT32 *ocbuf, *icbuf; /* pointer to coordinates for copying */
    INT16 *corebuf;
    AxisInfo core_axis = {0};

    if (!pDev->valuator || !pDev->valuator->numMotionEvents)
        return 0;

    if (core && !pScreen)
        return 0;

    if (pDev->isMaster)
        size = (sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(Time);
    else
        size = (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time);

    *buff = xalloc(size * pDev->valuator->numMotionEvents);
    if (!(*buff))
        return 0;
    obuff = (char *)*buff;

    for (i = pDev->valuator->first_motion;
         i != pDev->valuator->last_motion;
         i = (i + 1) % pDev->valuator->numMotionEvents) {
        /* We index the input buffer by which element we're accessing, which
         * is not monotonic, and the output buffer by how many events we've
         * written so far. */
        ibuff = (char *) pDev->valuator->motion + (i * size);
        memcpy(&current, ibuff, sizeof(Time));

        if (current > stop) {
            return ret;
        }
        else if (current >= start) {
            if (core)
            {
                memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */

                icbuf = (INT32*)(ibuff + sizeof(Time));
                corebuf = (INT16*)(obuff + sizeof(Time));

                /* fetch x coordinate + range */
                memcpy(&from.min_value, icbuf++, sizeof(INT32));
                memcpy(&from.max_value, icbuf++, sizeof(INT32));
                memcpy(&coord, icbuf++, sizeof(INT32));

                /* scale to screen coords */
                to = &core_axis;
                to->max_value = pScreen->width;
                coord = rescaleValuatorAxis(coord, &from, to, pScreen->width);

                memcpy(corebuf, &coord, sizeof(INT16));
                corebuf++;

                /* fetch y coordinate + range */
                memcpy(&from.min_value, icbuf++, sizeof(INT32));
                memcpy(&from.max_value, icbuf++, sizeof(INT32));
                memcpy(&coord, icbuf++, sizeof(INT32));

                to->max_value = pScreen->height;
                coord = rescaleValuatorAxis(coord, &from, to, pScreen->height);
                memcpy(corebuf, &coord, sizeof(INT16));

            } else if (pDev->isMaster)
            {
                memcpy(obuff, ibuff, sizeof(Time)); /* copy timestamp */

                ocbuf = (INT32*)(obuff + sizeof(Time));
                icbuf = (INT32*)(ibuff + sizeof(Time));
                for (j = 0; j < MAX_VALUATORS; j++)
                {
                    if (j >= pDev->valuator->numAxes)
                        break;

                    /* fetch min/max/coordinate */
                    memcpy(&from.min_value, icbuf++, sizeof(INT32));
                    memcpy(&from.max_value, icbuf++, sizeof(INT32));
                    memcpy(&coord, icbuf++, sizeof(INT32));

                    to = (j < pDev->valuator->numAxes) ? &pDev->valuator->axes[j] : NULL;

                    /* x/y scaled to screen if no range is present */
                    if (j == 0 && (from.max_value < from.min_value))
                        from.max_value = pScreen->width;
                    else if (j == 1 && (from.max_value < from.min_value))
                        from.max_value = pScreen->height;

                    if (j == 0 && (to->max_value < to->min_value))
                        dflt = pScreen->width;
                    else if (j == 1 && (to->max_value < to->min_value))
                        dflt = pScreen->height;
                    else
                        dflt = 0;

                    /* scale from stored range into current range */
                    coord = rescaleValuatorAxis(coord, &from, to, 0);
                    memcpy(ocbuf, &coord, sizeof(INT32));
                    ocbuf++;
                }
            } else
                memcpy(obuff, ibuff, size);

            /* don't advance by size here. size may be different to the
             * actually written size if the MD has less valuators than MAX */
            if (core)
                obuff += sizeof(INT32) + sizeof(Time);
            else
                obuff += (sizeof(INT32) * pDev->valuator->numAxes) + sizeof(Time);
            ret++;
        }
    }

    return ret;
}


/**
 * Update the motion history for a specific device, with the list of
 * valuators.
 *
 * Layout of the history buffer:
 *   for SDs: [time] [val0] [val1] ... [valn]
 *   for MDs: [time] [min_val0] [max_val0] [val0] [min_val1] ... [valn]
 *
 * For events that have some valuators unset (first_valuator > 0):
 *      min_val == max_val == val == 0.
 */
static void
updateMotionHistory(DeviceIntPtr pDev, CARD32 ms, int first_valuator,
                    int num_valuators, int *valuators)
{
    char *buff = (char *) pDev->valuator->motion;
    ValuatorClassPtr v;
    int i;

    if (!pDev->valuator->numMotionEvents)
        return;

    v = pDev->valuator;
    if (pDev->isMaster)
    {
        buff += ((sizeof(INT32) * 3 * MAX_VALUATORS) + sizeof(CARD32)) *
                v->last_motion;

        memcpy(buff, &ms, sizeof(Time));
        buff += sizeof(Time);

        memset(buff, 0, sizeof(INT32) * 3 * MAX_VALUATORS);
        buff += 3 * sizeof(INT32) * first_valuator;

        for (i = first_valuator; i < first_valuator + num_valuators; i++)
        {
            if (i >= v->numAxes)
                break;
            memcpy(buff, &v->axes[i].min_value, sizeof(INT32));
            buff += sizeof(INT32);
            memcpy(buff, &v->axes[i].max_value, sizeof(INT32));
            buff += sizeof(INT32);
            memcpy(buff, &valuators[i - first_valuator], sizeof(INT32));
            buff += sizeof(INT32);
        }
    } else
    {

        buff += ((sizeof(INT32) * pDev->valuator->numAxes) + sizeof(CARD32)) *
            pDev->valuator->last_motion;

        memcpy(buff, &ms, sizeof(Time));
        buff += sizeof(Time);

        memset(buff, 0, sizeof(INT32) * pDev->valuator->numAxes);
        buff += sizeof(INT32) * first_valuator;

        memcpy(buff, valuators, sizeof(INT32) * num_valuators);
    }

    pDev->valuator->last_motion = (pDev->valuator->last_motion + 1) %
        pDev->valuator->numMotionEvents;
    /* If we're wrapping around, just keep the circular buffer going. */
    if (pDev->valuator->first_motion == pDev->valuator->last_motion)
        pDev->valuator->first_motion = (pDev->valuator->first_motion + 1) %
                                       pDev->valuator->numMotionEvents;

    return;
}


/**
 * Returns the maximum number of events GetKeyboardEvents,
 * GetKeyboardValuatorEvents, and GetPointerEvents will ever return.
 *
 * This MUST be absolutely constant, from init until exit.
 */
int
GetMaximumEventsNum(void) {
    /* One base event -- device, plus valuator events. */
    int ret = 1 + MAX_VALUATOR_EVENTS;

    /* One possible DeviceClassesChangedEvent */
    ret++;

    return ret;
}


/**
 * Clip an axis to its bounds, which are declared in the call to
 * InitValuatorAxisClassStruct.
 */
static void
clipAxis(DeviceIntPtr pDev, int axisNum, int *val)
{
    AxisInfoPtr axis = pDev->valuator->axes + axisNum;
    /* InitValuatoraAxisStruct ensures that (min < max). */

    /* If a value range is defined, clip. If not, do nothing */
    if (axis->max_value <= axis->min_value)
        return;

    if (*val < axis->min_value)
        *val = axis->min_value;
    if (*val > axis->max_value)
        *val = axis->max_value;
}

/**
 * Clip every axis in the list of valuators to its bounds.
 */
static void
clipValuators(DeviceIntPtr pDev, int first_valuator, int num_valuators,
              int *valuators)
{
    AxisInfoPtr axes = pDev->valuator->axes + first_valuator;
    int i;

    for (i = 0; i < num_valuators; i++, axes++)
        clipAxis(pDev, i + first_valuator, &(valuators[i]));
}

/**
 * Create the DCCE event (does not update the master's device state yet, this
 * is done in the event processing).
 * Pull in the coordinates from the MD if necessary.
 *
 * @param events Pointer to a pre-allocated event list.
 * @param dev The slave device that generated an event.
 * @param num_events The current number of events, returns the number of
 *        events if a DCCE was generated.
 * @return The updated @events pointer.
 */
static EventListPtr
updateFromMaster(EventListPtr events, DeviceIntPtr dev, int *num_events)
{
    DeviceIntPtr master = dev->u.master;
    if (master && master->u.lastSlave != dev)
    {
        CreateClassesChangedEvent(events, master, dev);
        updateSlaveDeviceCoords(master, dev);
        master->u.lastSlave = dev;
        master->last.numValuators = dev->last.numValuators;
        (*num_events)++;
        events++;
    }
    return events;
}

/**
 * Move the device's pointer to the position given in the valuators.
 *
 * @param dev The device which's pointer is to be moved.
 * @param x Returns the x position of the pointer after the move.
 * @param y Returns the y position of the pointer after the move.
 * @param first The first valuator in @valuators
 * @param num Total number of valuators in @valuators.
 * @param valuators Valuator data for each axis between @first and
 *        @first+@num.
 */
static void
moveAbsolute(DeviceIntPtr dev, int *x, int *y,
             int first, int num, int *valuators)
{
    int i;


    if (num >= 1 && first == 0)
        *x = *(valuators + 0);
    else
        *x = dev->last.valuators[0];

    if (first <= 1 && num >= (2 - first))
        *y = *(valuators + 1 - first);
    else
        *y = dev->last.valuators[1];

    clipAxis(dev, 0, x);
    clipAxis(dev, 1, y);

    i = (first > 2) ? 0 : 2;
    for (; i < num; i++)
    {
        dev->last.valuators[i + first] = valuators[i];
        clipAxis(dev, i, &dev->last.valuators[i + first]);
    }
}

/**
 * Move the device's pointer by the values given in @valuators.
 *
 * @param dev The device which's pointer is to be moved.
 * @param x Returns the x position of the pointer after the move.
 * @param y Returns the y position of the pointer after the move.
 * @param first The first valuator in @valuators
 * @param num Total number of valuators in @valuators.
 * @param valuators Valuator data for each axis between @first and
 *        @first+@num.
 */
static void
moveRelative(DeviceIntPtr dev, int *x, int *y,
             int first, int num, int *valuators)
{
    int i;

    *x = dev->last.valuators[0];
    *y = dev->last.valuators[1];

    if (num >= 1 && first == 0)
        *x += *(valuators +0);

    if (first <= 1 && num >= (2 - first))
        *y += *(valuators + 1 - first);

    /* if attached, clip both x and y to the defined limits (usually
     * co-ord space limit). If it is attached, we need x/y to go over the
     * limits to be able to change screens. */
    if(dev->u.master) {
        clipAxis(dev, 0, x);
        clipAxis(dev, 1, y);
    }

    /* calc other axes, clip, drop back into valuators */
    i = (first > 2) ? 0 : 2;
    for (; i < num; i++)
    {
        dev->last.valuators[i + first] += valuators[i];
        clipAxis(dev, i, &dev->last.valuators[i + first]);
        valuators[i] = dev->last.valuators[i + first];
    }
}

/**
 * Accelerate the data in valuators based on the device's acceleration scheme.
 *
 * @param dev The device which's pointer is to be moved.
 * @param first The first valuator in @valuators
 * @param num Total number of valuators in @valuators.
 * @param valuators Valuator data for each axis between @first and
 *        @first+@num.
 * @param ms Current time.
 */
static void
accelPointer(DeviceIntPtr dev, int first, int num, int *valuators, CARD32 ms)
{
    if (dev->valuator->accelScheme.AccelSchemeProc)
        dev->valuator->accelScheme.AccelSchemeProc(dev, first, num, valuators, ms);
}

/**
 * If we have HW cursors, this actually moves the visible sprite. If not, we
 * just do all the screen crossing, etc.
 *
 * We scale from device to screen coordinates here, call
 * miPointerSetPosition() and then scale back into device coordinates (if
 * needed). miPSP will change x/y if the screen was crossed.
 *
 * @param dev The device to be moved.
 * @param x Pointer to current x-axis value, may be modified.
 * @param y Pointer to current y-axis value, may be modified.
 * @param scr Screen the device's sprite is currently on.
 * @param screenx Screen x coordinate the sprite is on after the update.
 * @param screeny Screen y coordinate the sprite is on after the update.
 */
static void
positionSprite(DeviceIntPtr dev, int *x, int *y,
               ScreenPtr scr, int *screenx, int *screeny)
{
    /* scale x&y to screen */
    *screenx = rescaleValuatorAxis(*x, dev->valuator->axes + 0, NULL, scr->width);
    *screeny = rescaleValuatorAxis(*y, dev->valuator->axes + 1, NULL, scr->height);
    dev->last.valuators[0] = *screenx;
    dev->last.valuators[1] = *screeny;

    /* This takes care of crossing screens for us, as well as clipping
     * to the current screen. */
    miPointerSetPosition(dev, &dev->last.valuators[0], &dev->last.valuators[1]);

    if (dev->u.master) {
        dev->u.master->last.valuators[0] = dev->last.valuators[0];
        dev->u.master->last.valuators[1] = dev->last.valuators[1];
    }

    /* Crossed screen? Scale back to device coordiantes */
    if(*screenx != dev->last.valuators[0])
    {
        scr = miPointerGetScreen(dev);
        *x = rescaleValuatorAxis(dev->last.valuators[0], NULL,
                                dev->valuator->axes + 0, scr->width);
        *screenx = dev->last.valuators[0];
    }
    if(*screeny != dev->last.valuators[1])
    {
        scr = miPointerGetScreen(dev);
        *screeny = dev->last.valuators[1];
        *y = rescaleValuatorAxis(dev->last.valuators[1], NULL,
                                 dev->valuator->axes + 1, scr->height);
    }

    /* dropy x/y (device coordinates) back into valuators for next event */
    dev->last.valuators[0] = *x;
    dev->last.valuators[1] = *y;
}

/**
 * Update the motion history for the device and (if appropriate) for its
 * master device.
 * @param dev Slave device to update.
 * @param first First valuator to append to history.
 * @param num Total number of valuators to append to history.
 * @param ms Current time
 */
static void
updateHistory(DeviceIntPtr dev, int first, int num, CARD32 ms)
{
    updateMotionHistory(dev, ms, first, num, &dev->last.valuators[first]);
    if (dev->u.master)
        updateMotionHistory(dev->u.master, ms, first, num,
                            &dev->last.valuators[first]);
}

/**
 * Convenience wrapper around GetKeyboardValuatorEvents, that takes no
 * valuators.
 */
int
GetKeyboardEvents(EventList *events, DeviceIntPtr pDev, int type, int key_code) {
    return GetKeyboardValuatorEvents(events, pDev, type, key_code, 0, 0, NULL);
}


/**
 * Returns a set of keyboard events for KeyPress/KeyRelease, optionally
 * also with valuator events.  Handles Xi and XKB.
 *
 * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the
 * event (ProcessOtherEvent).
 *
 * events is not NULL-terminated; the return value is the number of events.
 * The DDX is responsible for allocating the event structure in the first
 * place via GetMaximumEventsNum(), and for freeing it.
 *
 * This function does not change the core keymap to that of the device;
 * that is done by SwitchCoreKeyboard, which is called from
 * mieqProcessInputEvents.  If replacing that function, take care to call
 * SetCoreKeyboard before processInputProc, so keymaps are altered to suit.
 *
 * Note that this function recurses!  If called for non-XKB, a repeating
 * key press will trigger a matching KeyRelease, as well as the
 * KeyPresses.
 */
int
GetKeyboardValuatorEvents(EventList *events, DeviceIntPtr pDev, int type,
                          int key_code, int first_valuator,
                          int num_valuators, int *valuators) {
    int numEvents = 0;
    CARD32 ms = 0;
    DeviceEvent *event;

    if (!events ||!pDev->key || !pDev->focus || !pDev->kbdfeed ||
       (type != KeyPress && type != KeyRelease) ||
       (key_code < 8 || key_code > 255))
        return 0;

    numEvents = 1;

    events = updateFromMaster(events, pDev, &numEvents);

    /* Handle core repeating, via press/release/press/release. */
    if (type == KeyPress && key_is_down(pDev, key_code, KEY_POSTED)) {
        /* If autorepeating is disabled either globally or just for that key,
         * or we have a modifier, don't generate a repeat event. */
        if (!pDev->kbdfeed->ctrl.autoRepeat ||
            !key_autorepeats(pDev, key_code) ||
            pDev->key->xkbInfo->desc->map->modmap[key_code])
            return 0;
    }

    if (num_valuators)
        clipValuators(pDev, first_valuator, num_valuators, valuators);

    ms = GetTimeInMillis();

    event = (DeviceEvent*) events->event;
    init_event(pDev, event, ms);
    event->detail.key = key_code;

    if (type == KeyPress) {
        event->type = ET_KeyPress;
	set_key_down(pDev, key_code, KEY_POSTED);
    }
    else if (type == KeyRelease) {
        event->type = ET_KeyRelease;
	set_key_up(pDev, key_code, KEY_POSTED);
    }

    if (num_valuators)
        clipValuators(pDev, first_valuator, num_valuators, valuators);

    set_valuators(pDev, event, first_valuator, num_valuators, valuators);

    return numEvents;
}

/**
 * Initialize an event list and fill with 32 byte sized events.
 * This event list is to be passed into GetPointerEvents() and
 * GetKeyboardEvents().
 *
 * @param num_events Number of elements in list.
 */
EventListPtr
InitEventList(int num_events)
{
    EventListPtr events;
    int i;

    events = (EventListPtr)xcalloc(num_events, sizeof(EventList));
    if (!events)
        return NULL;

    for (i = 0; i < num_events; i++)
    {
        events[i].evlen = sizeof(InternalEvent);
        events[i].event = xcalloc(1, sizeof(InternalEvent));
        if (!events[i].event)
        {
            /* rollback */
            while(i--)
                xfree(events[i].event);
            xfree(events);
            events = NULL;
            break;
        }
    }

    return events;
}

/**
 * Allocs min_size memory for each event in the list.
 */
void
SetMinimumEventSize(EventListPtr list, int num_events, int min_size)
{
    if (!list)
        return;

    while(num_events--)
    {
        if (list[num_events].evlen < min_size)
        {
            list[num_events].evlen = min_size;
            list[num_events].event = realloc(list[num_events].event, min_size);
            if (!list[num_events].event)
            {
                FatalError("[dix] Failed to set event list's "
                        "min_size to %d.\n", min_size);
            }
        }
    }
}

/**
 * Free an event list.
 *
 * @param list The list to be freed.
 * @param num_events Number of elements in list.
 */
void
FreeEventList(EventListPtr list, int num_events)
{
    if (!list)
        return;
    while(num_events--)
        xfree(list[num_events].event);
    xfree(list);
}

/**
 * Generate a series of xEvents (filled into the EventList) representing
 * pointer motion, or button presses.  Xi and XKB-aware.
 *
 * DOES NOT GENERATE CORE EVENTS! Core events are created when processing the
 * event (ProcessOtherEvent).
 *
 * events is not NULL-terminated; the return value is the number of events.
 * The DDX is responsible for allocating the event structure in the first
 * place via InitEventList() and GetMaximumEventsNum(), and for freeing it.
 *
 * In the generated events rootX/Y will be in absolute screen coords and
 * the valuator information in the absolute or relative device coords.
 *
 * last.valuators[x] of the device is always in absolute device coords.
 * last.valuators[x] of the master device is in absolute screen coords.
 *
 * master->last.valuators[x] for x > 2 is undefined.
 */
int
GetPointerEvents(EventList *events, DeviceIntPtr pDev, int type, int buttons,
                 int flags, int first_valuator, int num_valuators,
                 int *valuators) {
    int num_events = 1;
    CARD32 ms;
    DeviceEvent *event;
    int x, y, /* switches between device and screen coords */
        cx, cy; /* only screen coordinates */
    ScreenPtr scr = miPointerGetScreen(pDev);

    ms = GetTimeInMillis(); /* before pointer update to help precision */

    if (!scr || !pDev->valuator || first_valuator < 0 ||
        ((num_valuators + first_valuator) > pDev->valuator->numAxes) ||
        (type != MotionNotify && type != ButtonPress && type != ButtonRelease) ||
        (type != MotionNotify && !pDev->button) ||
        ((type == ButtonPress || type == ButtonRelease) && !buttons) ||
        (type == MotionNotify && num_valuators <= 0))
        return 0;

    events = updateFromMaster(events, pDev, &num_events);

    if (flags & POINTER_ABSOLUTE)
    {
        if (flags & POINTER_SCREEN) /* valuators are in screen coords */
        {

            valuators[0] = rescaleValuatorAxis(valuators[0], NULL,
                                               pDev->valuator->axes + 0,
                                               scr->width);
            valuators[1] = rescaleValuatorAxis(valuators[1], NULL,
                                               pDev->valuator->axes + 1,
                                               scr->height);
        }

        moveAbsolute(pDev, &x, &y, first_valuator, num_valuators, valuators);
    } else {
        if (flags & POINTER_ACCELERATE)
            accelPointer(pDev, first_valuator, num_valuators, valuators, ms);
        moveRelative(pDev, &x, &y, first_valuator, num_valuators, valuators);
    }

    positionSprite(pDev, &x, &y, scr, &cx, &cy);
    updateHistory(pDev, first_valuator, num_valuators, ms);


    /* Update the valuators with the true value sent to the client*/
    if (num_valuators >= 1 && first_valuator == 0)
        valuators[0] = x;
    if (first_valuator <= 1 && num_valuators >= (2 - first_valuator))
        valuators[1 - first_valuator] = y;

    if (num_valuators)
        clipValuators(pDev, first_valuator, num_valuators, valuators);

    event = (DeviceEvent*) events->event;
    init_event(pDev, event, ms);

    if (type == MotionNotify) {
        event->type = ET_Motion;
        event->detail.button = 0;
    }
    else {
        if (type == ButtonPress) {
            event->type = ET_ButtonPress;
            pDev->button->postdown[buttons >> 3] |= (1 << (buttons & 7));
        }
        else if (type == ButtonRelease) {
            event->type = ET_ButtonRelease;
            pDev->button->postdown[buttons >> 3] &= ~(1 << (buttons & 7));
        }
        event->detail.button = buttons;
    }

    /* XXX: this should be 16.16 fixed point */
    event->root_x = cx; /* root_x/y always in screen coords */
    event->root_y = cy;

    set_valuators(pDev, event, first_valuator, num_valuators, valuators);


    return num_events;
}


/**
 * Post ProximityIn/ProximityOut events, accompanied by valuators.
 *
 * events is not NULL-terminated; the return value is the number of events.
 * The DDX is responsible for allocating the event structure in the first
 * place via GetMaximumEventsNum(), and for freeing it.
 */
int
GetProximityEvents(EventList *events, DeviceIntPtr pDev, int type,
                   int first_valuator, int num_valuators, int *valuators)
{
    int num_events = 1;
    DeviceEvent *event;

    /* Sanity checks. */
    if (type != ProximityIn && type != ProximityOut)
        return 0;
    if (!pDev->valuator)
        return 0;
    /* Do we need to send a DeviceValuator event? */
    if ((pDev->valuator->mode & 1) == Relative)
        num_valuators = 0;

    if (num_valuators) {
        if ((((num_valuators - 1) / 6) + 1) > MAX_VALUATOR_EVENTS)
            num_valuators = MAX_VALUATOR_EVENTS * 6;
        num_events += ((num_valuators - 1) / 6) + 1;
    }

    /* You fail. */
    if (first_valuator < 0 ||
        (num_valuators + first_valuator) > pDev->valuator->numAxes)
        return 0;

    events = updateFromMaster(events, pDev, &num_events);

    event = (DeviceEvent *) events->event;
    init_event(pDev, event, GetTimeInMillis());
    event->type = (type == ProximityIn) ? ET_ProximityIn : ET_ProximityOut;

    if (num_valuators)
        clipValuators(pDev, first_valuator, num_valuators, valuators);

    set_valuators(pDev, event, first_valuator, num_valuators, valuators);

    return num_events;
}

/**
 * Synthesize a single motion event for the core pointer.
 *
 * Used in cursor functions, e.g. when cursor confinement changes, and we need
 * to shift the pointer to get it inside the new bounds.
 */
void
PostSyntheticMotion(DeviceIntPtr pDev,
                    int x,
                    int y,
                    int screen,
                    unsigned long time)
{
    DeviceEvent ev;

#ifdef PANORAMIX
    /* Translate back to the sprite screen since processInputProc
       will translate from sprite screen to screen 0 upon reentry
       to the DIX layer. */
    if (!noPanoramiXExtension) {
        x += panoramiXdataPtr[0].x - panoramiXdataPtr[screen].x;
        y += panoramiXdataPtr[0].y - panoramiXdataPtr[screen].y;
    }
#endif

    memset(&ev, 0, sizeof(DeviceEvent));
    init_event(pDev, &ev, time);
    ev.root_x = x;
    ev.root_y = y;
    ev.type = time;

    /* FIXME: MD/SD considerations? */
    (*pDev->public.processInputProc)((InternalEvent*)&ev, pDev);
}