1 /*
2  * Copyright © 2008 Daniel Stone
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  *
23  * Author: Daniel Stone <daniel@fooishbar.org>
24  */
25 
26 #ifdef HAVE_DIX_CONFIG_H
27 #include "dix-config.h"
28 #endif
29 
30 #include "exevents.h"
31 #include "exglobals.h"
32 #include "misc.h"
33 #include "input.h"
34 #include "inputstr.h"
35 #include "xace.h"
36 #include "xkbsrv.h"
37 #include "xkbstr.h"
38 #include "inpututils.h"
39 #include "eventstr.h"
40 #include "scrnintstr.h"
41 #include "optionstr.h"
42 
43 /* Check if a button map change is okay with the device.
44  * Returns -1 for BadValue, as it collides with MappingBusy. */
45 static int
check_butmap_change(DeviceIntPtr dev,CARD8 * map,int len,CARD32 * errval_out,ClientPtr client)46 check_butmap_change(DeviceIntPtr dev, CARD8 *map, int len, CARD32 *errval_out,
47                     ClientPtr client)
48 {
49     int i, ret;
50 
51     if (!dev || !dev->button) {
52         client->errorValue = (dev) ? dev->id : 0;
53         return BadDevice;
54     }
55 
56     ret = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixManageAccess);
57     if (ret != Success) {
58         client->errorValue = dev->id;
59         return ret;
60     }
61 
62     for (i = 0; i < len; i++) {
63         if (dev->button->map[i + 1] != map[i] &&
64             button_is_down(dev, i + 1, BUTTON_PROCESSED))
65             return MappingBusy;
66     }
67 
68     return Success;
69 }
70 
71 static void
do_butmap_change(DeviceIntPtr dev,CARD8 * map,int len,ClientPtr client)72 do_butmap_change(DeviceIntPtr dev, CARD8 *map, int len, ClientPtr client)
73 {
74     int i;
75     xEvent core_mn = { .u.u.type = MappingNotify };
76     deviceMappingNotify xi_mn;
77 
78     /* The map in ButtonClassRec refers to button numbers, whereas the
79      * protocol is zero-indexed.  Sigh. */
80     memcpy(&(dev->button->map[1]), map, len);
81 
82     core_mn.u.mappingNotify.request = MappingPointer;
83 
84     /* 0 is the server client. */
85     for (i = 1; i < currentMaxClients; i++) {
86         /* Don't send irrelevant events to naïve clients. */
87         if (!clients[i] || clients[i]->clientState != ClientStateRunning)
88             continue;
89 
90         if (!XIShouldNotify(clients[i], dev))
91             continue;
92 
93         WriteEventsToClient(clients[i], 1, &core_mn);
94     }
95 
96     xi_mn = (deviceMappingNotify) {
97         .type = DeviceMappingNotify,
98         .request = MappingPointer,
99         .deviceid = dev->id,
100         .time = GetTimeInMillis()
101     };
102 
103     SendEventToAllWindows(dev, DeviceMappingNotifyMask, (xEvent *) &xi_mn, 1);
104 }
105 
106 /*
107  * Does what it says on the box, both for core and Xi.
108  *
109  * Faithfully reports any errors encountered while trying to apply the map
110  * to the requested device, faithfully ignores any errors encountered while
111  * trying to apply the map to its master/slaves.
112  */
113 int
ApplyPointerMapping(DeviceIntPtr dev,CARD8 * map,int len,ClientPtr client)114 ApplyPointerMapping(DeviceIntPtr dev, CARD8 *map, int len, ClientPtr client)
115 {
116     int ret;
117 
118     /* If we can't perform the change on the requested device, bail out. */
119     ret = check_butmap_change(dev, map, len, &client->errorValue, client);
120     if (ret != Success)
121         return ret;
122     do_butmap_change(dev, map, len, client);
123 
124     return Success;
125 }
126 
127 /* Check if a modifier map change is okay with the device.
128  * Returns -1 for BadValue, as it collides with MappingBusy; this particular
129  * caveat can be removed with LegalModifier, as we have no other reason to
130  * set MappingFailed.  Sigh. */
131 static int
check_modmap_change(ClientPtr client,DeviceIntPtr dev,KeyCode * modmap)132 check_modmap_change(ClientPtr client, DeviceIntPtr dev, KeyCode *modmap)
133 {
134     int ret, i;
135     XkbDescPtr xkb;
136 
137     ret = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixManageAccess);
138     if (ret != Success)
139         return ret;
140 
141     if (!dev->key)
142         return BadMatch;
143     xkb = dev->key->xkbInfo->desc;
144 
145     for (i = 0; i < MAP_LENGTH; i++) {
146         if (!modmap[i])
147             continue;
148 
149         /* Check that all the new modifiers fall within the advertised
150          * keycode range. */
151         if (i < xkb->min_key_code || i > xkb->max_key_code) {
152             client->errorValue = i;
153             return -1;
154         }
155 
156         /* Make sure the mapping is okay with the DDX. */
157         if (!LegalModifier(i, dev)) {
158             client->errorValue = i;
159             return MappingFailed;
160         }
161 
162         /* None of the new modifiers may be down while we change the
163          * map. */
164         if (key_is_down(dev, i, KEY_POSTED | KEY_PROCESSED)) {
165             client->errorValue = i;
166             return MappingBusy;
167         }
168     }
169 
170     /* None of the old modifiers may be down while we change the map,
171      * either. */
172     for (i = xkb->min_key_code; i < xkb->max_key_code; i++) {
173         if (!xkb->map->modmap[i])
174             continue;
175         if (key_is_down(dev, i, KEY_POSTED | KEY_PROCESSED)) {
176             client->errorValue = i;
177             return MappingBusy;
178         }
179     }
180 
181     return Success;
182 }
183 
184 static int
check_modmap_change_slave(ClientPtr client,DeviceIntPtr master,DeviceIntPtr slave,CARD8 * modmap)185 check_modmap_change_slave(ClientPtr client, DeviceIntPtr master,
186                           DeviceIntPtr slave, CARD8 *modmap)
187 {
188     XkbDescPtr master_xkb, slave_xkb;
189     int i, j;
190 
191     if (!slave->key || !master->key)
192         return 0;
193 
194     master_xkb = master->key->xkbInfo->desc;
195     slave_xkb = slave->key->xkbInfo->desc;
196 
197     /* Ignore devices with a clearly different keymap. */
198     if (slave_xkb->min_key_code != master_xkb->min_key_code ||
199         slave_xkb->max_key_code != master_xkb->max_key_code)
200         return 0;
201 
202     for (i = 0; i < MAP_LENGTH; i++) {
203         if (!modmap[i])
204             continue;
205 
206         /* If we have different symbols for any modifier on an
207          * extended keyboard, ignore the whole remap request. */
208         for (j = 0;
209              j < XkbKeyNumSyms(slave_xkb, i) &&
210              j < XkbKeyNumSyms(master_xkb, i); j++)
211             if (XkbKeySymsPtr(slave_xkb, i)[j] !=
212                 XkbKeySymsPtr(master_xkb, i)[j])
213                 return 0;
214     }
215 
216     if (check_modmap_change(client, slave, modmap) != Success)
217         return 0;
218 
219     return 1;
220 }
221 
222 /* Actually change the modifier map, and send notifications.  Cannot fail. */
223 static void
do_modmap_change(ClientPtr client,DeviceIntPtr dev,CARD8 * modmap)224 do_modmap_change(ClientPtr client, DeviceIntPtr dev, CARD8 *modmap)
225 {
226     XkbApplyMappingChange(dev, NULL, 0, 0, modmap, serverClient);
227 }
228 
229 /* Rebuild modmap (key -> mod) from map (mod -> key). */
230 static int
build_modmap_from_modkeymap(CARD8 * modmap,KeyCode * modkeymap,int max_keys_per_mod)231 build_modmap_from_modkeymap(CARD8 *modmap, KeyCode *modkeymap,
232                             int max_keys_per_mod)
233 {
234     int i, len = max_keys_per_mod * 8;
235 
236     memset(modmap, 0, MAP_LENGTH);
237 
238     for (i = 0; i < len; i++) {
239         if (!modkeymap[i])
240             continue;
241 
242 #if MAP_LENGTH < 256
243         if (modkeymap[i] >= MAP_LENGTH)
244             return BadValue;
245 #endif
246 
247         if (modmap[modkeymap[i]])
248             return BadValue;
249 
250         modmap[modkeymap[i]] = 1 << (i / max_keys_per_mod);
251     }
252 
253     return Success;
254 }
255 
256 int
change_modmap(ClientPtr client,DeviceIntPtr dev,KeyCode * modkeymap,int max_keys_per_mod)257 change_modmap(ClientPtr client, DeviceIntPtr dev, KeyCode *modkeymap,
258               int max_keys_per_mod)
259 {
260     int ret;
261     CARD8 modmap[MAP_LENGTH];
262     DeviceIntPtr tmp;
263 
264     ret = build_modmap_from_modkeymap(modmap, modkeymap, max_keys_per_mod);
265     if (ret != Success)
266         return ret;
267 
268     /* If we can't perform the change on the requested device, bail out. */
269     ret = check_modmap_change(client, dev, modmap);
270     if (ret != Success)
271         return ret;
272     do_modmap_change(client, dev, modmap);
273 
274     /* Change any attached masters/slaves. */
275     if (IsMaster(dev)) {
276         for (tmp = inputInfo.devices; tmp; tmp = tmp->next) {
277             if (!IsMaster(tmp) && GetMaster(tmp, MASTER_KEYBOARD) == dev)
278                 if (check_modmap_change_slave(client, dev, tmp, modmap))
279                     do_modmap_change(client, tmp, modmap);
280         }
281     }
282     else if (!IsFloating(dev) &&
283              GetMaster(dev, MASTER_KEYBOARD)->lastSlave == dev) {
284         /* If this fails, expect the results to be weird. */
285         if (check_modmap_change(client, dev->master, modmap) == Success)
286             do_modmap_change(client, dev->master, modmap);
287     }
288 
289     return Success;
290 }
291 
292 int
generate_modkeymap(ClientPtr client,DeviceIntPtr dev,KeyCode ** modkeymap_out,int * max_keys_per_mod_out)293 generate_modkeymap(ClientPtr client, DeviceIntPtr dev,
294                    KeyCode **modkeymap_out, int *max_keys_per_mod_out)
295 {
296     CARD8 keys_per_mod[8];
297     int max_keys_per_mod;
298     KeyCode *modkeymap = NULL;
299     int i, j, ret;
300 
301     ret = XaceHook(XACE_DEVICE_ACCESS, client, dev, DixGetAttrAccess);
302     if (ret != Success)
303         return ret;
304 
305     if (!dev->key)
306         return BadMatch;
307 
308     /* Count the number of keys per modifier to determine how wide we
309      * should make the map. */
310     max_keys_per_mod = 0;
311     for (i = 0; i < 8; i++)
312         keys_per_mod[i] = 0;
313     for (i = 8; i < MAP_LENGTH; i++) {
314         for (j = 0; j < 8; j++) {
315             if (dev->key->xkbInfo->desc->map->modmap[i] & (1 << j)) {
316                 if (++keys_per_mod[j] > max_keys_per_mod)
317                     max_keys_per_mod = keys_per_mod[j];
318             }
319         }
320     }
321 
322     if (max_keys_per_mod != 0) {
323         modkeymap = calloc(max_keys_per_mod * 8, sizeof(KeyCode));
324         if (!modkeymap)
325             return BadAlloc;
326 
327         for (i = 0; i < 8; i++)
328             keys_per_mod[i] = 0;
329 
330         for (i = 8; i < MAP_LENGTH; i++) {
331             for (j = 0; j < 8; j++) {
332                 if (dev->key->xkbInfo->desc->map->modmap[i] & (1 << j)) {
333                     modkeymap[(j * max_keys_per_mod) + keys_per_mod[j]] = i;
334                     keys_per_mod[j]++;
335                 }
336             }
337         }
338     }
339 
340     *max_keys_per_mod_out = max_keys_per_mod;
341     *modkeymap_out = modkeymap;
342 
343     return Success;
344 }
345 
346 /**
347  * Duplicate the InputAttributes in the most obvious way.
348  * No special memory handling is used to give drivers the maximum
349  * flexibility with the data. Drivers should be able to call realloc on the
350  * product string if needed and perform similar operations.
351  */
352 InputAttributes *
DuplicateInputAttributes(InputAttributes * attrs)353 DuplicateInputAttributes(InputAttributes * attrs)
354 {
355     InputAttributes *new_attr;
356     int ntags = 0;
357     char **tags, **new_tags;
358 
359     if (!attrs)
360         return NULL;
361 
362     if (!(new_attr = calloc(1, sizeof(InputAttributes))))
363         goto unwind;
364 
365     if (attrs->product && !(new_attr->product = strdup(attrs->product)))
366         goto unwind;
367     if (attrs->vendor && !(new_attr->vendor = strdup(attrs->vendor)))
368         goto unwind;
369     if (attrs->device && !(new_attr->device = strdup(attrs->device)))
370         goto unwind;
371     if (attrs->pnp_id && !(new_attr->pnp_id = strdup(attrs->pnp_id)))
372         goto unwind;
373     if (attrs->usb_id && !(new_attr->usb_id = strdup(attrs->usb_id)))
374         goto unwind;
375 
376     new_attr->flags = attrs->flags;
377 
378     if ((tags = attrs->tags)) {
379         while (*tags++)
380             ntags++;
381 
382         new_attr->tags = calloc(ntags + 1, sizeof(char *));
383         if (!new_attr->tags)
384             goto unwind;
385 
386         tags = attrs->tags;
387         new_tags = new_attr->tags;
388 
389         while (*tags) {
390             *new_tags = strdup(*tags);
391             if (!*new_tags)
392                 goto unwind;
393 
394             tags++;
395             new_tags++;
396         }
397     }
398 
399     return new_attr;
400 
401  unwind:
402     FreeInputAttributes(new_attr);
403     return NULL;
404 }
405 
406 void
FreeInputAttributes(InputAttributes * attrs)407 FreeInputAttributes(InputAttributes * attrs)
408 {
409     char **tags;
410 
411     if (!attrs)
412         return;
413 
414     free(attrs->product);
415     free(attrs->vendor);
416     free(attrs->device);
417     free(attrs->pnp_id);
418     free(attrs->usb_id);
419 
420     if ((tags = attrs->tags))
421         while (*tags)
422             free(*tags++);
423 
424     free(attrs->tags);
425     free(attrs);
426 }
427 
428 /**
429  * Alloc a valuator mask large enough for num_valuators.
430  */
431 ValuatorMask *
valuator_mask_new(int num_valuators)432 valuator_mask_new(int num_valuators)
433 {
434     /* alloc a fixed size mask for now and ignore num_valuators. in the
435      * flying-car future, when we can dynamically alloc the masks and are
436      * not constrained by signals, we can start using num_valuators */
437     ValuatorMask *mask = calloc(1, sizeof(ValuatorMask));
438 
439     if (mask == NULL)
440         return NULL;
441 
442     mask->last_bit = -1;
443     return mask;
444 }
445 
446 void
valuator_mask_free(ValuatorMask ** mask)447 valuator_mask_free(ValuatorMask **mask)
448 {
449     free(*mask);
450     *mask = NULL;
451 }
452 
453 /**
454  * Sets a range of valuators between first_valuator and num_valuators with
455  * the data in the valuators array. All other values are set to 0.
456  */
457 void
valuator_mask_set_range(ValuatorMask * mask,int first_valuator,int num_valuators,const int * valuators)458 valuator_mask_set_range(ValuatorMask *mask, int first_valuator,
459                         int num_valuators, const int *valuators)
460 {
461     int i;
462 
463     valuator_mask_zero(mask);
464 
465     for (i = first_valuator;
466          i < min(first_valuator + num_valuators, MAX_VALUATORS); i++)
467         valuator_mask_set(mask, i, valuators[i - first_valuator]);
468 }
469 
470 /**
471  * Reset mask to zero.
472  */
473 void
valuator_mask_zero(ValuatorMask * mask)474 valuator_mask_zero(ValuatorMask *mask)
475 {
476     memset(mask, 0, sizeof(*mask));
477     mask->last_bit = -1;
478 }
479 
480 /**
481  * Returns the current size of the mask (i.e. the highest number of
482  * valuators currently set + 1).
483  */
484 int
valuator_mask_size(const ValuatorMask * mask)485 valuator_mask_size(const ValuatorMask *mask)
486 {
487     return mask->last_bit + 1;
488 }
489 
490 /**
491  * Returns the number of valuators set in the given mask.
492  */
493 int
valuator_mask_num_valuators(const ValuatorMask * mask)494 valuator_mask_num_valuators(const ValuatorMask *mask)
495 {
496     return CountBits(mask->mask, min(mask->last_bit + 1, MAX_VALUATORS));
497 }
498 
499 /**
500  * Return true if the valuator is set in the mask, or false otherwise.
501  */
502 int
valuator_mask_isset(const ValuatorMask * mask,int valuator)503 valuator_mask_isset(const ValuatorMask *mask, int valuator)
504 {
505     return mask->last_bit >= valuator && BitIsOn(mask->mask, valuator);
506 }
507 
508 static inline void
_valuator_mask_set_double(ValuatorMask * mask,int valuator,double data)509 _valuator_mask_set_double(ValuatorMask *mask, int valuator, double data)
510 {
511     mask->last_bit = max(valuator, mask->last_bit);
512     SetBit(mask->mask, valuator);
513     mask->valuators[valuator] = data;
514 }
515 
516 /**
517  * Set the valuator to the given floating-point data.
518  */
519 void
valuator_mask_set_double(ValuatorMask * mask,int valuator,double data)520 valuator_mask_set_double(ValuatorMask *mask, int valuator, double data)
521 {
522     BUG_WARN_MSG(mask->has_unaccelerated,
523                  "Do not mix valuator types, zero mask first\n");
524     _valuator_mask_set_double(mask, valuator, data);
525 }
526 
527 /**
528  * Set the valuator to the given integer data.
529  */
530 void
valuator_mask_set(ValuatorMask * mask,int valuator,int data)531 valuator_mask_set(ValuatorMask *mask, int valuator, int data)
532 {
533     valuator_mask_set_double(mask, valuator, data);
534 }
535 
536 /**
537  * Return the requested valuator value as a double. If the mask bit is not
538  * set for the given valuator, the returned value is undefined.
539  */
540 double
valuator_mask_get_double(const ValuatorMask * mask,int valuator)541 valuator_mask_get_double(const ValuatorMask *mask, int valuator)
542 {
543     return mask->valuators[valuator];
544 }
545 
546 /**
547  * Return the requested valuator value as an integer, rounding towards zero.
548  * If the mask bit is not set for the given valuator, the returned value is
549  * undefined.
550  */
551 int
valuator_mask_get(const ValuatorMask * mask,int valuator)552 valuator_mask_get(const ValuatorMask *mask, int valuator)
553 {
554     return trunc(valuator_mask_get_double(mask, valuator));
555 }
556 
557 /**
558  * Set value to the requested valuator. If the mask bit is set for this
559  * valuator, value contains the requested valuator value and TRUE is
560  * returned.
561  * If the mask bit is not set for this valuator, value is unchanged and
562  * FALSE is returned.
563  */
564 Bool
valuator_mask_fetch_double(const ValuatorMask * mask,int valuator,double * value)565 valuator_mask_fetch_double(const ValuatorMask *mask, int valuator,
566                            double *value)
567 {
568     if (valuator_mask_isset(mask, valuator)) {
569         *value = valuator_mask_get_double(mask, valuator);
570         return TRUE;
571     }
572     else
573         return FALSE;
574 }
575 
576 /**
577  * Set value to the requested valuator. If the mask bit is set for this
578  * valuator, value contains the requested valuator value and TRUE is
579  * returned.
580  * If the mask bit is not set for this valuator, value is unchanged and
581  * FALSE is returned.
582  */
583 Bool
valuator_mask_fetch(const ValuatorMask * mask,int valuator,int * value)584 valuator_mask_fetch(const ValuatorMask *mask, int valuator, int *value)
585 {
586     if (valuator_mask_isset(mask, valuator)) {
587         *value = valuator_mask_get(mask, valuator);
588         return TRUE;
589     }
590     else
591         return FALSE;
592 }
593 
594 /**
595  * Remove the valuator from the mask.
596  */
597 void
valuator_mask_unset(ValuatorMask * mask,int valuator)598 valuator_mask_unset(ValuatorMask *mask, int valuator)
599 {
600     if (mask->last_bit >= valuator) {
601         int i, lastbit = -1;
602 
603         ClearBit(mask->mask, valuator);
604         mask->valuators[valuator] = 0.0;
605         mask->unaccelerated[valuator] = 0.0;
606 
607         for (i = 0; i <= mask->last_bit; i++)
608             if (valuator_mask_isset(mask, i))
609                 lastbit = max(lastbit, i);
610         mask->last_bit = lastbit;
611 
612         if (mask->last_bit == -1)
613             mask->has_unaccelerated = FALSE;
614     }
615 }
616 
617 void
valuator_mask_copy(ValuatorMask * dest,const ValuatorMask * src)618 valuator_mask_copy(ValuatorMask *dest, const ValuatorMask *src)
619 {
620     if (src)
621         memcpy(dest, src, sizeof(*dest));
622     else
623         valuator_mask_zero(dest);
624 }
625 
626 Bool
valuator_mask_has_unaccelerated(const ValuatorMask * mask)627 valuator_mask_has_unaccelerated(const ValuatorMask *mask)
628 {
629     return mask->has_unaccelerated;
630 }
631 
632 void
valuator_mask_drop_unaccelerated(ValuatorMask * mask)633 valuator_mask_drop_unaccelerated(ValuatorMask *mask)
634 {
635     memset(mask->unaccelerated, 0, sizeof(mask->unaccelerated));
636     mask->has_unaccelerated = FALSE;
637 }
638 
639 void
valuator_mask_set_absolute_unaccelerated(ValuatorMask * mask,int valuator,int absolute,double unaccel)640 valuator_mask_set_absolute_unaccelerated(ValuatorMask *mask,
641                                          int valuator,
642                                          int absolute,
643                                          double unaccel)
644 {
645     BUG_WARN_MSG(mask->last_bit != -1 && !mask->has_unaccelerated,
646                  "Do not mix valuator types, zero mask first\n");
647     _valuator_mask_set_double(mask, valuator, absolute);
648     mask->has_unaccelerated = TRUE;
649     mask->unaccelerated[valuator] = unaccel;
650 }
651 
652 /**
653  * Set both accelerated and unaccelerated value for this mask.
654  */
655 void
valuator_mask_set_unaccelerated(ValuatorMask * mask,int valuator,double accel,double unaccel)656 valuator_mask_set_unaccelerated(ValuatorMask *mask,
657                                 int valuator,
658                                 double accel,
659                                 double unaccel)
660 {
661     BUG_WARN_MSG(mask->last_bit != -1 && !mask->has_unaccelerated,
662                  "Do not mix valuator types, zero mask first\n");
663     _valuator_mask_set_double(mask, valuator, accel);
664     mask->has_unaccelerated = TRUE;
665     mask->unaccelerated[valuator] = unaccel;
666 }
667 
668 double
valuator_mask_get_accelerated(const ValuatorMask * mask,int valuator)669 valuator_mask_get_accelerated(const ValuatorMask *mask,
670                               int valuator)
671 {
672     return valuator_mask_get_double(mask, valuator);
673 }
674 
675 double
valuator_mask_get_unaccelerated(const ValuatorMask * mask,int valuator)676 valuator_mask_get_unaccelerated(const ValuatorMask *mask,
677                                 int valuator)
678 {
679     return mask->unaccelerated[valuator];
680 }
681 
682 Bool
valuator_mask_fetch_unaccelerated(const ValuatorMask * mask,int valuator,double * accel,double * unaccel)683 valuator_mask_fetch_unaccelerated(const ValuatorMask *mask,
684                                   int valuator,
685                                   double *accel,
686                                   double *unaccel)
687 {
688     if (valuator_mask_isset(mask, valuator)) {
689         if (accel)
690             *accel = valuator_mask_get_accelerated(mask, valuator);
691         if (unaccel)
692             *unaccel = valuator_mask_get_unaccelerated(mask, valuator);
693         return TRUE;
694     }
695     else
696         return FALSE;
697 }
698 
699 int
CountBits(const uint8_t * mask,int len)700 CountBits(const uint8_t * mask, int len)
701 {
702     int i;
703     int ret = 0;
704 
705     for (i = 0; i < len; i++)
706         if (BitIsOn(mask, i))
707             ret++;
708 
709     return ret;
710 }
711 
712 /**
713  * Verifies sanity of the event. If the event is not an internal event,
714  * memdumps the first 32 bytes of event to the log, a backtrace, then kill
715  * the server.
716  */
717 void
verify_internal_event(const InternalEvent * ev)718 verify_internal_event(const InternalEvent *ev)
719 {
720     if (ev && ev->any.header != ET_Internal) {
721         int i;
722         const unsigned char *data = (const unsigned char *) ev;
723 
724         ErrorF("dix: invalid event type %d\n", ev->any.header);
725 
726         for (i = 0; i < sizeof(xEvent); i++, data++) {
727             ErrorF("%02hhx ", *data);
728 
729             if ((i % 8) == 7)
730                 ErrorF("\n");
731         }
732 
733         xorg_backtrace();
734         FatalError("Wrong event type %d. Aborting server\n", ev->any.header);
735     }
736 }
737 
738 /**
739  * Initializes the given event to zero (or default values), for the given
740  * device.
741  */
742 void
init_device_event(DeviceEvent * event,DeviceIntPtr dev,Time ms,enum DeviceEventSource source_type)743 init_device_event(DeviceEvent *event, DeviceIntPtr dev, Time ms,
744                   enum DeviceEventSource source_type)
745 {
746     memset(event, 0, sizeof(DeviceEvent));
747     event->header = ET_Internal;
748     event->length = sizeof(DeviceEvent);
749     event->time = ms;
750     event->deviceid = dev->id;
751     event->sourceid = dev->id;
752     event->source_type = source_type;
753 }
754 
755 int
event_get_corestate(DeviceIntPtr mouse,DeviceIntPtr kbd)756 event_get_corestate(DeviceIntPtr mouse, DeviceIntPtr kbd)
757 {
758     int corestate;
759 
760     /* core state needs to be assembled BEFORE the device is updated. */
761     corestate = (kbd &&
762                  kbd->key) ? XkbStateFieldFromRec(&kbd->key->xkbInfo->
763                                                   state) : 0;
764     corestate |= (mouse && mouse->button) ? (mouse->button->state) : 0;
765     corestate |= (mouse && mouse->touch) ? (mouse->touch->state) : 0;
766 
767     return corestate;
768 }
769 
770 void
event_set_state(DeviceIntPtr mouse,DeviceIntPtr kbd,DeviceEvent * event)771 event_set_state(DeviceIntPtr mouse, DeviceIntPtr kbd, DeviceEvent *event)
772 {
773     int i;
774 
775     for (i = 0; mouse && mouse->button && i < mouse->button->numButtons; i++)
776         if (BitIsOn(mouse->button->down, i))
777             SetBit(event->buttons, mouse->button->map[i]);
778 
779     if (mouse && mouse->touch && mouse->touch->buttonsDown > 0)
780         SetBit(event->buttons, mouse->button->map[1]);
781 
782     if (kbd && kbd->key) {
783         XkbStatePtr state;
784 
785         /* we need the state before the event happens */
786         if (event->type == ET_KeyPress || event->type == ET_KeyRelease)
787             state = &kbd->key->xkbInfo->prev_state;
788         else
789             state = &kbd->key->xkbInfo->state;
790 
791         event->mods.base = state->base_mods;
792         event->mods.latched = state->latched_mods;
793         event->mods.locked = state->locked_mods;
794         event->mods.effective = state->mods;
795 
796         event->group.base = state->base_group;
797         event->group.latched = state->latched_group;
798         event->group.locked = state->locked_group;
799         event->group.effective = state->group;
800     }
801 }
802 
803 /**
804  * Return the event filter mask for the given device and the given core or
805  * XI1 protocol type.
806  */
807 Mask
event_get_filter_from_type(DeviceIntPtr dev,int evtype)808 event_get_filter_from_type(DeviceIntPtr dev, int evtype)
809 {
810     return event_filters[dev ? dev->id : 0][evtype];
811 }
812 
813 /**
814  * Return the event filter mask for the given device and the given core or
815  * XI2 protocol type.
816  */
817 Mask
event_get_filter_from_xi2type(int evtype)818 event_get_filter_from_xi2type(int evtype)
819 {
820     return (1 << (evtype % 8));
821 }
822 
823 Bool
point_on_screen(ScreenPtr pScreen,int x,int y)824 point_on_screen(ScreenPtr pScreen, int x, int y)
825 {
826     return x >= pScreen->x && x < pScreen->x + pScreen->width &&
827         y >= pScreen->y && y < pScreen->y + pScreen->height;
828 }
829 
830 /**
831  * Update desktop dimensions on the screenInfo struct.
832  */
833 void
update_desktop_dimensions(void)834 update_desktop_dimensions(void)
835 {
836     int i;
837     int x1 = INT_MAX, y1 = INT_MAX;     /* top-left */
838     int x2 = INT_MIN, y2 = INT_MIN;     /* bottom-right */
839 
840     for (i = 0; i < screenInfo.numScreens; i++) {
841         ScreenPtr screen = screenInfo.screens[i];
842 
843         x1 = min(x1, screen->x);
844         y1 = min(y1, screen->y);
845         x2 = max(x2, screen->x + screen->width);
846         y2 = max(y2, screen->y + screen->height);
847     }
848 
849     screenInfo.x = x1;
850     screenInfo.y = y1;
851     screenInfo.width = x2 - x1;
852     screenInfo.height = y2 - y1;
853 }
854 
855 /*
856  * Delete the element with the key from the list, freeing all memory
857  * associated with the element..
858  */
859 static void
input_option_free(InputOption * o)860 input_option_free(InputOption *o)
861 {
862     free(o->opt_name);
863     free(o->opt_val);
864     free(o->opt_comment);
865     free(o);
866 }
867 
868 /*
869  * Create a new InputOption with the key/value pair provided.
870  * If a list is provided, the new options is added to the list and the list
871  * is returned.
872  *
873  * If a new option is added to a list that already contains that option, the
874  * previous option is overwritten.
875  *
876  * @param list The list to add to.
877  * @param key Option key, will be copied.
878  * @param value Option value, will be copied.
879  *
880  * @return If list is not NULL, the list with the new option added. If list
881  * is NULL, a new option list with one element. On failure, NULL is
882  * returned.
883  */
884 InputOption *
input_option_new(InputOption * list,const char * key,const char * value)885 input_option_new(InputOption *list, const char *key, const char *value)
886 {
887     InputOption *opt = NULL;
888 
889     if (!key)
890         return NULL;
891 
892     if (list) {
893         nt_list_for_each_entry(opt, list, list.next) {
894             if (strcmp(input_option_get_key(opt), key) == 0) {
895                 input_option_set_value(opt, value);
896                 return list;
897             }
898         }
899     }
900 
901     opt = calloc(1, sizeof(InputOption));
902     if (!opt)
903         return NULL;
904 
905     nt_list_init(opt, list.next);
906     input_option_set_key(opt, key);
907     input_option_set_value(opt, value);
908 
909     if (list) {
910         nt_list_append(opt, list, InputOption, list.next);
911 
912         return list;
913     }
914     else
915         return opt;
916 }
917 
918 InputOption *
input_option_free_element(InputOption * list,const char * key)919 input_option_free_element(InputOption *list, const char *key)
920 {
921     InputOption *element;
922 
923     nt_list_for_each_entry(element, list, list.next) {
924         if (strcmp(input_option_get_key(element), key) == 0) {
925             nt_list_del(element, list, InputOption, list.next);
926 
927             input_option_free(element);
928             break;
929         }
930     }
931     return list;
932 }
933 
934 /**
935  * Free the list pointed at by opt.
936  */
937 void
input_option_free_list(InputOption ** opt)938 input_option_free_list(InputOption **opt)
939 {
940     InputOption *element, *tmp;
941 
942     nt_list_for_each_entry_safe(element, tmp, *opt, list.next) {
943         nt_list_del(element, *opt, InputOption, list.next);
944 
945         input_option_free(element);
946     }
947     *opt = NULL;
948 }
949 
950 /**
951  * Find the InputOption with the given option name.
952  *
953  * @return The InputOption or NULL if not present.
954  */
955 InputOption *
input_option_find(InputOption * list,const char * key)956 input_option_find(InputOption *list, const char *key)
957 {
958     InputOption *element;
959 
960     nt_list_for_each_entry(element, list, list.next) {
961         if (strcmp(input_option_get_key(element), key) == 0)
962             return element;
963     }
964 
965     return NULL;
966 }
967 
968 const char *
input_option_get_key(const InputOption * opt)969 input_option_get_key(const InputOption *opt)
970 {
971     return opt->opt_name;
972 }
973 
974 const char *
input_option_get_value(const InputOption * opt)975 input_option_get_value(const InputOption *opt)
976 {
977     return opt->opt_val;
978 }
979 
980 void
input_option_set_key(InputOption * opt,const char * key)981 input_option_set_key(InputOption *opt, const char *key)
982 {
983     free(opt->opt_name);
984     if (key)
985         opt->opt_name = strdup(key);
986 }
987 
988 void
input_option_set_value(InputOption * opt,const char * value)989 input_option_set_value(InputOption *opt, const char *value)
990 {
991     free(opt->opt_val);
992     if (value)
993         opt->opt_val = strdup(value);
994 }
995 
996 /* FP1616/FP3232 conversion functions.
997  * Fixed point types are encoded as signed integral and unsigned frac. So any
998  * negative number -n.m is encoded as floor(n) + (1 - 0.m).
999  */
1000 double
fp1616_to_double(FP1616 in)1001 fp1616_to_double(FP1616 in)
1002 {
1003     return pixman_fixed_to_double(in);
1004 }
1005 
1006 double
fp3232_to_double(FP3232 in)1007 fp3232_to_double(FP3232 in)
1008 {
1009     double ret;
1010 
1011     ret = (double) in.integral;
1012     ret += (double) in.frac * (1.0 / (1ULL << 32));     /* Optimized: ldexp((double)in.frac, -32); */
1013     return ret;
1014 }
1015 
1016 FP1616
double_to_fp1616(double in)1017 double_to_fp1616(double in)
1018 {
1019     return pixman_double_to_fixed(in);
1020 }
1021 
1022 FP3232
double_to_fp3232(double in)1023 double_to_fp3232(double in)
1024 {
1025     FP3232 ret;
1026     int32_t integral;
1027     double tmp;
1028     uint32_t frac_d;
1029 
1030     tmp = floor(in);
1031     integral = (int32_t) tmp;
1032 
1033     tmp = (in - integral) * (1ULL << 32);       /* Optimized: ldexp(in - integral, 32) */
1034     frac_d = (uint32_t) tmp;
1035 
1036     ret.integral = integral;
1037     ret.frac = frac_d;
1038     return ret;
1039 }
1040 
1041 /**
1042  * DO NOT USE THIS FUNCTION. It only exists for the test cases. Use
1043  * xi2mask_new() instead to get the standard sized masks.
1044  *
1045  * @param nmasks The number of masks (== number of devices)
1046  * @param size The size of the masks in bytes
1047  * @return The new mask or NULL on allocation error.
1048  */
1049 XI2Mask *
xi2mask_new_with_size(size_t nmasks,size_t size)1050 xi2mask_new_with_size(size_t nmasks, size_t size)
1051 {
1052     int i;
1053     int alloc_size;
1054     unsigned char *cursor;
1055     XI2Mask *mask;
1056 
1057     alloc_size = sizeof(struct _XI2Mask)
1058 	       + nmasks * sizeof(unsigned char *)
1059 	       + nmasks * size;
1060 
1061     mask = calloc(1, alloc_size);
1062 
1063     if (!mask)
1064         return NULL;
1065 
1066     mask->nmasks = nmasks;
1067     mask->mask_size = size;
1068 
1069     mask->masks = (unsigned char **)(mask + 1);
1070     cursor = (unsigned char *)(mask + 1) + nmasks * sizeof(unsigned char *);
1071 
1072     for (i = 0; i < nmasks; i++) {
1073         mask->masks[i] = cursor;
1074 	cursor += size;
1075     }
1076     return mask;
1077 }
1078 
1079 /**
1080  * Create a new XI2 mask of the standard size, i.e. for all devices + fake
1081  * devices and for the highest supported XI2 event type.
1082  *
1083  * @return The new mask or NULL on allocation error.
1084  */
1085 XI2Mask *
xi2mask_new(void)1086 xi2mask_new(void)
1087 {
1088     return xi2mask_new_with_size(EMASKSIZE, XI2MASKSIZE);
1089 }
1090 
1091 /**
1092  * Frees memory associated with mask and resets mask to NULL.
1093  */
1094 void
xi2mask_free(XI2Mask ** mask)1095 xi2mask_free(XI2Mask **mask)
1096 {
1097     if (!(*mask))
1098         return;
1099 
1100     free((*mask));
1101     *mask = NULL;
1102 }
1103 
1104 /**
1105  * Test if the bit for event type is set for this device only.
1106  *
1107  * @return TRUE if the bit is set, FALSE otherwise
1108  */
1109 Bool
xi2mask_isset_for_device(XI2Mask * mask,const DeviceIntPtr dev,int event_type)1110 xi2mask_isset_for_device(XI2Mask *mask, const DeviceIntPtr dev, int event_type)
1111 {
1112     BUG_WARN(dev->id < 0);
1113     BUG_WARN(dev->id >= mask->nmasks);
1114     BUG_WARN(bits_to_bytes(event_type + 1) > mask->mask_size);
1115 
1116     return BitIsOn(mask->masks[dev->id], event_type);
1117 }
1118 
1119 /**
1120  * Test if the bit for event type is set for this device, or the
1121  * XIAllDevices/XIAllMasterDevices (if applicable) is set.
1122  *
1123  * @return TRUE if the bit is set, FALSE otherwise
1124  */
1125 Bool
xi2mask_isset(XI2Mask * mask,const DeviceIntPtr dev,int event_type)1126 xi2mask_isset(XI2Mask *mask, const DeviceIntPtr dev, int event_type)
1127 {
1128     int set = 0;
1129 
1130     if (xi2mask_isset_for_device(mask, inputInfo.all_devices, event_type))
1131         set = 1;
1132     else if (xi2mask_isset_for_device(mask, dev, event_type))
1133         set = 1;
1134     else if (IsMaster(dev) && xi2mask_isset_for_device(mask, inputInfo.all_master_devices, event_type))
1135         set = 1;
1136 
1137     return set;
1138 }
1139 
1140 /**
1141  * Set the mask bit for this event type for this device.
1142  */
1143 void
xi2mask_set(XI2Mask * mask,int deviceid,int event_type)1144 xi2mask_set(XI2Mask *mask, int deviceid, int event_type)
1145 {
1146     BUG_WARN(deviceid < 0);
1147     BUG_WARN(deviceid >= mask->nmasks);
1148     BUG_WARN(bits_to_bytes(event_type + 1) > mask->mask_size);
1149 
1150     SetBit(mask->masks[deviceid], event_type);
1151 }
1152 
1153 /**
1154  * Zero out the xi2mask, for the deviceid given. If the deviceid is < 0, all
1155  * masks are zeroed.
1156  */
1157 void
xi2mask_zero(XI2Mask * mask,int deviceid)1158 xi2mask_zero(XI2Mask *mask, int deviceid)
1159 {
1160     int i;
1161 
1162     BUG_WARN(deviceid > 0 && deviceid >= mask->nmasks);
1163 
1164     if (deviceid >= 0)
1165         memset(mask->masks[deviceid], 0, mask->mask_size);
1166     else
1167         for (i = 0; i < mask->nmasks; i++)
1168             memset(mask->masks[i], 0, mask->mask_size);
1169 }
1170 
1171 /**
1172  * Merge source into dest, i.e. dest |= source.
1173  * If the masks are of different size, only the overlapping section is merged.
1174  */
1175 void
xi2mask_merge(XI2Mask * dest,const XI2Mask * source)1176 xi2mask_merge(XI2Mask *dest, const XI2Mask *source)
1177 {
1178     int i, j;
1179 
1180     for (i = 0; i < min(dest->nmasks, source->nmasks); i++)
1181         for (j = 0; j < min(dest->mask_size, source->mask_size); j++)
1182             dest->masks[i][j] |= source->masks[i][j];
1183 }
1184 
1185 /**
1186  * @return The number of masks in mask
1187  */
1188 size_t
xi2mask_num_masks(const XI2Mask * mask)1189 xi2mask_num_masks(const XI2Mask *mask)
1190 {
1191     return mask->nmasks;
1192 }
1193 
1194 /**
1195  * @return The size of each mask in bytes
1196  */
1197 size_t
xi2mask_mask_size(const XI2Mask * mask)1198 xi2mask_mask_size(const XI2Mask *mask)
1199 {
1200     return mask->mask_size;
1201 }
1202 
1203 /**
1204  * Set the mask for the given deviceid to the source mask.
1205  * If the mask given is larger than the target memory, only the overlapping
1206  * parts are copied.
1207  */
1208 void
xi2mask_set_one_mask(XI2Mask * xi2mask,int deviceid,const unsigned char * mask,size_t mask_size)1209 xi2mask_set_one_mask(XI2Mask *xi2mask, int deviceid, const unsigned char *mask,
1210                      size_t mask_size)
1211 {
1212     BUG_WARN(deviceid < 0);
1213     BUG_WARN(deviceid >= xi2mask->nmasks);
1214 
1215     memcpy(xi2mask->masks[deviceid], mask, min(xi2mask->mask_size, mask_size));
1216 }
1217 
1218 /**
1219  * Get a reference to the XI2mask for this particular device.
1220  */
1221 const unsigned char *
xi2mask_get_one_mask(const XI2Mask * mask,int deviceid)1222 xi2mask_get_one_mask(const XI2Mask *mask, int deviceid)
1223 {
1224     BUG_WARN(deviceid < 0);
1225     BUG_WARN(deviceid >= mask->nmasks);
1226 
1227     return mask->masks[deviceid];
1228 }
1229