summaryrefslogtreecommitdiff
path: root/python/evemu/__init__.py
blob: a9b768aacfe23d751b271bd199b043b033bde99d (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
"""
The evemu module provides the Python interface to the kernel-level input device
raw events.
"""

# Copyright 2011-2012 Canonical Ltd.
# Copyright 2014 Red Hat, Inc.
#
# This library is free software: you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License version 3
# as published by the Free Software Foundation.
#
# This library is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import ctypes
import glob
import os
import re
import stat
import tempfile

import evemu.base

__all__ = ["Device",
           "InputEvent",
           "event_get_value",
           "event_get_name",
           "input_prop_get_value",
           "input_prop_get_name"]

_libevdev = evemu.base.LibEvdev()

def event_get_value(event_type, event_code = None):
    """
    Return the integer-value for the given event type and/or code string
    e.g. "EV_ABS" returns 0x03, ("EV_ABS", "ABS_Y") returns 0x01.
    Unknown event types or type/code combinations return None.

    If an event code is passed, the event type may be given as integer or
    string.
    """
    t = -1
    c = -1

    if isinstance(event_type, int):
        event_type = _libevdev.libevdev_event_type_get_name(event_type)
        if event_type is None:
            return None

    t = _libevdev.libevdev_event_type_from_name(str(event_type))
    if event_code is None:
        return None if t < 0 else t

    if isinstance(event_code, int):
        event_code = _libevdev.libevdev_event_code_get_name(t, event_code)
        if event_code is None:
            return None

    c = _libevdev.libevdev_event_code_from_name(t, str(event_code))

    return None if c < 0 else c

def event_get_name(event_type, event_code = None):
    """
    Return the string-value for the given event type and/or code value
    e.g. 0x03 returns "EV_ABS", ("EV_ABS", 0x01) returns "ABS_Y"
    Unknown event types or type/code combinations return None.

    If an event code is passed, the event type may be given as integer or
    string.
    """
    if not isinstance(event_type, int):
        event_type = event_get_value(event_type)

    if event_type is None:
        return None

    if event_code is None:
        type_name = _libevdev.libevdev_event_type_get_name(event_type)
        return type_name

    if not isinstance(event_code, int):
        event_code = event_get_value(event_type, event_code)

    if event_code is None:
        return None

    code_name = _libevdev.libevdev_event_code_get_name(event_type, event_code)

    return code_name

def input_prop_get_name(prop):
    """
    Return the name of the input property, or None if undefined.
    """
    if not isinstance(prop, int):
        prop = input_prop_get_value(prop)

    if prop is None:
        return None

    prop = _libevdev.libevdev_property_get_name(prop)
    return prop

def input_prop_get_value(prop):
    """
    Return the value of the input property, or None if undefined.
    """
    if isinstance(prop, int):
        prop = input_prop_get_name(prop)

    if prop is None:
        return None

    prop = _libevdev.libevdev_property_from_name(str(prop))
    return None if prop < 0 else prop

class InputEvent(object):
    __slots__ = 'sec', 'usec', 'type', 'code', 'value'

    def __init__(self, sec, usec, type, code, value):
        self.sec = sec
        self.usec = usec
        self.type = type
        self.code = code
        self.value = value

    def matches(self, type, code = None):
        """
        If code is None, return True if the event matches the given event
        type. If code is not None, return True if the event matches the
        given type/code pair.

        type and code may be ints or string-like ("EV_ABS", "ABS_X").
        """
        if event_get_value(type) != self.type:
            return False

        if code != None and event_get_value(self.type, code) != self.code:
            return False

        return True

    def __str__(self):
        f = tempfile.TemporaryFile()
        libc = evemu.base.LibC()
        fp = libc.fdopen(f.fileno(), b"w+")

        event = evemu.base.InputEvent()
        event.sec = self.sec
        event.usec = self.usec
        event.type = self.type
        event.code = self.code
        event.value = self.value

        libevemu = evemu.base.LibEvemu()
        libevemu.evemu_write_event(fp, ctypes.byref(event))
        libc.fflush(fp)
        f.seek(0)
        return f.readline().rstrip()

class Device(object):
    """
    Encapsulates a raw kernel input event device, either an existing one as
    reported by the kernel or a pseudodevice as created through a .prop file.
    """

    def __init__(self, f, create=True):
        """
        Initialize an evemu Device.

        args:
        f -- a file object or filename string for either an existing input
        device node (/dev/input/eventNN) or an evemu prop file that can be used
        to create a pseudo-device node.
        create -- If f points to an evemu prop file, 'create' specifies if a
        uinput device should be created
        """

        if type(f) == str:
            self._file = open(f)
        elif hasattr(f, "read"):
            self._file = f
        else:
            raise TypeError("expected file or file name")

        self._is_propfile = self._check_is_propfile(self._file)
        self._libc = evemu.base.LibC()
        self._libevemu = evemu.base.LibEvemu()

        self._evemu_device = self._libevemu.evemu_new(b"")

        if self._is_propfile:
            fs = self._libc.fdopen(self._file.fileno(), b"r")
            self._libevemu.evemu_read(self._evemu_device, fs)
            if create:
                self._file = self._create_devnode()
        else:
            self._libevemu.evemu_extract(self._evemu_device,
                                         self._file.fileno())

    def __del__(self):
        if hasattr(self, "_is_propfile") and self._is_propfile:
            self._file.close()
            self._libevemu.evemu_destroy(self._evemu_device)

    def _create_devnode(self):
        self._libevemu.evemu_create_managed(self._evemu_device)
        return open(self._find_newest_devnode(self.name), 'r+b', buffering=0)

    def _find_newest_devnode(self, target_name):
        newest_node = (None, float(0))
        for sysname in glob.glob("/sys/class/input/event*/device/name"):
            with open(sysname) as f:
                name = f.read().rstrip()
                if name == target_name:
                    ev = re.search("(event\d+)", sysname)
                    if ev:
                       devname = os.path.join("/dev/input", ev.group(1))
                       ctime = os.stat(devname).st_ctime
                       if ctime > newest_node[1]:
                           newest_node = (devname, ctime)
        return newest_node[0]

    def _check_is_propfile(self, f):
        if stat.S_ISCHR(os.fstat(f.fileno()).st_mode):
            return False

        result = False
        for line in f.readlines():
            if line.startswith("N:"):
                result = True
                break
            elif line.startswith("# EVEMU"):
                result = True
                break
            elif line[0] != "#":
                raise TypeError("file must be a device special or prop file")

        f.seek(0)
        return result

    def describe(self, prop_file):
        """
        Gathers information about the input device and prints it
        to prop_file. This information can be parsed later when constructing
        a Device to create a virtual input device with the same properties.

        You need the required permissions to access the device file to
        succeed (usually root).

        prop_file must be a real file with fileno(), not file-like.
        """
        if not hasattr(prop_file, "fileno"):
            raise TypeError("expected file")

        fs = self._libc.fdopen(prop_file.fileno(), b"w")
        self._libevemu.evemu_write(self._evemu_device, fs)
        self._libc.fflush(fs)

    def events(self, events_file=None):
        """
        Reads the events from the given file and returns them as a list of
        dicts.

        If not None, events_file must be a real file with fileno(), not
        file-like. If None, the file used for creating this device is used.
        """
        if events_file:
            if not hasattr(events_file, "fileno"):
                raise TypeError("expected file")
        else:
            events_file = self._file

        fs = self._libc.fdopen(events_file.fileno(), b"r")
        event = evemu.base.InputEvent()
        while self._libevemu.evemu_read_event(fs, ctypes.byref(event)) > 0:
            yield InputEvent(event.sec, event.usec, event.type, event.code, event.value)

        self._libc.rewind(fs)

    def play(self, events_file):
        """
        Replays an event sequence, as provided by the events_file,
        through the input device. The event sequence must be in
        the form created by the record method.

        You need the required permissions to access the device file to
        succeed (usually root).

        events_file must be a real file with fileno(), not file-like.
        """
        if not hasattr(events_file, "fileno"):
            raise TypeError("expected file")

        fs = self._libc.fdopen(events_file.fileno(), b"r")
        self._libevemu.evemu_play(fs, self._file.fileno())

    def record(self, events_file, timeout=10000):
        """
        Captures events from the input device and prints them to the
        events_file. The events can be parsed by the play method,
        allowing a virtual input device to emit the exact same event
        sequence.

        You need the required permissions to access the device file to
        succeed (usually root).

        events_file must be a real file with fileno(), not file-like.
        """
        if not hasattr(events_file, "fileno"):
            raise TypeError("expected file")

        fs = self._libc.fdopen(events_file.fileno(), b"w")
        self._libevemu.evemu_record(fs, self._file.fileno(), timeout)
        self._libc.fflush(fs)

    @property
    def version(self):
        """
        Gets the version of the evemu library used to create the Device.
        """
        return self._libevemu.evemu_get_version(self._evemu_device)

    @property
    def devnode(self):
        """
        Gets the name of the /dev node of the input device.
        """
        return self._file.name

    @property
    def name(self):
        """
        Gets the name of the input device (as reported by the device).
        """
        result = self._libevemu.evemu_get_name(self._evemu_device)
        return result.decode("iso8859-1")

    @property
    def id_bustype(self):
        """
        Identifies the kernel device bustype.
        """
        return self._libevemu.evemu_get_id_bustype(self._evemu_device)

    @property
    def id_vendor(self):
        """
        Identifies the kernel device vendor.
        """
        return self._libevemu.evemu_get_id_vendor(self._evemu_device)

    @property
    def id_product(self):
        """
        Identifies the kernel device product.
        """
        return self._libevemu.evemu_get_id_product(self._evemu_device)

    @property
    def id_version(self):
        """
        Identifies the kernel device version.
        """
        return self._libevemu.evemu_get_id_version(self._evemu_device)

    def get_abs_minimum(self, event_code):
        """
        Return the axis minimum for the given EV_ABS value.

        event_code may be an int or string-like ("ABS_X").
        """
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value("EV_ABS", event_code)
        return self._libevemu.evemu_get_abs_minimum(self._evemu_device,
                                                    event_code)

    def get_abs_maximum(self, event_code):
        """
        Return the axis maximum for the given EV_ABS value.

        event_code may be an int or string-like ("ABS_X").
        """
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value("EV_ABS", event_code)
        return self._libevemu.evemu_get_abs_maximum(self._evemu_device,
                                                    event_code)

    def get_abs_fuzz(self, event_code):
        """
        Return the abs fuzz for the given EV_ABS value.

        event_code may be an int or string-like ("ABS_X").
        """
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value("EV_ABS", event_code)
        return self._libevemu.evemu_get_abs_fuzz(self._evemu_device,
                                                 event_code)

    def get_abs_flat(self, event_code):
        """
        Return the abs flat for the given EV_ABS value.

        event_code may be an int or string-like ("ABS_X").
        """
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value("EV_ABS", event_code)
        return self._libevemu.evemu_get_abs_flat(self._evemu_device,
                                                 event_code)

    def get_abs_resolution(self, event_code):
        """
        Return the resolution for the given EV_ABS value.

        event_code may be an int or string-like ("ABS_X").
        """
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value("EV_ABS", event_code)
        return self._libevemu.evemu_get_abs_resolution(self._evemu_device,
                                                       event_code)

    # don't change 'event_code' to prop, it breaks API
    def has_prop(self, event_code):
        """
        Return True if the device supports the given input property,
        or False otherwise.

        event_code may be an int or string-like ("INPUT_PROP_DIRECT").
        """
        if not isinstance(event_code, int):
            event_code = evemu.input_prop_get_value(event_code)
        result = self._libevemu.evemu_has_prop(self._evemu_device, event_code)
        return bool(result)

    def has_event(self, event_type, event_code):
        """
        Return True if the device supports the given event type/code
        pair, or False otherwise.

        event_type and event_code may be ints or string-like ("EV_REL",
        "REL_X").
        """
        if not isinstance(event_type, int):
            event_type = evemu.event_get_value(event_type)
        if not isinstance(event_code, int):
            event_code = evemu.event_get_value(event_type, event_code)
        result = self._libevemu.evemu_has_event(self._evemu_device,
                                                event_type,
                                                event_code)
        return bool(result)