pax_global_header00006660000000000000000000000064132674676400014531gustar00rootroot0000000000000052 comment=2caaa68c223ce58bd8aa27377db7fce9896e2a22 python-libevdev-0.5/000077500000000000000000000000001326746764000145145ustar00rootroot00000000000000python-libevdev-0.5/.gitignore000066400000000000000000000000261326746764000165020ustar00rootroot00000000000000doc/html/ *.swp *.pyc python-libevdev-0.5/COPYING000066400000000000000000000021051326746764000155450ustar00rootroot00000000000000Copyright © 2016-2018 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. python-libevdev-0.5/Makefile000066400000000000000000000002411326746764000161510ustar00rootroot00000000000000all: doc test doc: sphinx-apidoc -f -o doc/source libevdev sphinx-build -b html doc/source doc/html test: PYTHONPATH=. pytest-3 test/*.py .PHONY: doc test python-libevdev-0.5/README.md000066400000000000000000000024441326746764000157770ustar00rootroot00000000000000python-libevdev - Python wrapper for libevdev ============================================= This project is a Python wrapper around libevdev, taking advantage of libevdev's advanced event handling. Documentation is available here: https://python-libevdev.readthedocs.io/en/latest/ libevdev makes it easy to * read and parse events from an input device * create a virtual input device and make it send events * duplicate an existing device and modify the event stream For information about libevdev see here: https://freedesktop.org/wiki/Software/libevdev/ Source code ----------- The source code of python-libevdev can be found at: http://github.com/whot/python-libevdev License ------- python-libevdev is licensed under the MIT license. > 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: [...] See the [COPYING](http://github.com/whot/python-libevdev/blob/master/COPYING) file for the full license information. python-libevdev-0.5/doc/000077500000000000000000000000001326746764000152615ustar00rootroot00000000000000python-libevdev-0.5/doc/source/000077500000000000000000000000001326746764000165615ustar00rootroot00000000000000python-libevdev-0.5/doc/source/conf.py000066400000000000000000000206351326746764000200660ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # libevdev Python wrapper documentation build configuration file, created by # sphinx-quickstart on Fri Feb 26 08:28:42 2016. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) sys.path.insert(0, os.path.abspath("../../")) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.ifconfig', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'libevdev Python wrapper' copyright = u'2016-2017, Red Hat Inc. ' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.4' # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). add_module_names = False # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'libevdevPythonwrapperdoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ('index', 'libevdevPythonwrapper.tex', u'libevdev Python wrapper Documentation', u'Peter Hutterer', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'libevdevpythonwrapper', u'libevdev Python wrapper Documentation', [u'Peter Hutterer'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'libevdevPythonwrapper', u'libevdev Python wrapper Documentation', u'Peter Hutterer', 'libevdevPythonwrapper', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'http://docs.python.org/': None} python-libevdev-0.5/doc/source/examples.rst000066400000000000000000000013071326746764000211320ustar00rootroot00000000000000Examples ======== The examples included here available in the `examples/` directory of the git source. .. contents:: :local: Printing the capabilities of a device and its events **************************************************** .. literalinclude:: ../../examples/evtest.py Creating a uinput device and sending events ******************************************* .. literalinclude:: ../../examples/uinput.py Filtering and re-routing events from a device ********************************************* .. literalinclude:: ../../examples/filter-device-events.py Updating the kernel device's axis ranges **************************************** .. literalinclude:: ../../examples/kernel-device-update.py python-libevdev-0.5/doc/source/index.rst000066400000000000000000000126041326746764000204250ustar00rootroot00000000000000libevdev Python wrapper ======================= **python-libevdev** is a wrapper around the libevdev C library, with a pythonic API. libevdev makes it easy to * read and parse events from an input device * create a virtual input device and make it send events * duplicate an existing device and modify the event stream See the `Basic examples`_ section below for simple code or the :doc:`examples` page for more detailed examples. Source code ----------- The source code for this project is available at http://github.com/whot/python-libevdev Installation ------------ A requirement for **python-libevdev** to work is that the libevdev C library is installed on your system. Install through your favourite package managers, but you almost certainly already have it installed anyway. The recommended way of installing **python-libevdev** is to use your distribution's package manager (``dnf``, ``yum``, ``apt``, ``pacman``, ...). If it isn't packaged for your distribution, you should use ``pip3``:: sudo pip3 install libevdev For more details on using pip and the PyPI, please see https://pypi.python.org/pypi Otherwise, you can install it from the git repository:: git clone http://github.com/whot/python-libevdev cd python-libevdev sudo ./setup.py install Finally, **python-libevdev** can be used directly from the source by simply setting ``PYTHONPATH``:: $> export PYTHONPATH=/path/to/source:$PYTHONPATH $> python3 -c 'import libevdev; print(libevdev.EV_ABS)' EV_ABS:3 Once installed, the ``import libevdev`` statement will work and you can go from there. Why libevdev? ------------- **python-libevdev** uses libevdev for most operations. This provides a number of advantages over direct evdev event handling, libevdev hides some of the quirks of the evdev protocol. For example libevdev provides * access to the state of the device (rather than just the events) * correct handling of fake multitouch devices * synching of slots and per-slot state * transparent generation of missing tracking ids after SYN_DROPPED * disabling/enabling events on a per-context basis, so one can disable/enable ABS_FOO and then not care about quirks in the client-side code. * transparent handling of the UI_GET_SYSNAME and UI_DEV_SETUP ioctls The above are all features that were added to libevdev (the C library) over time because of a need for it in projects like the Xorg drivers, libinput, evemu and others. Unfortunately, the evdev kernel API is very simple, but getting the *behavior* of the API correct is hard. Even kernel drivers frequently do it wrong. libevdev (the C library) does hide a lot of that and thus makes consuming evdev safer. For the precise behavior of the libevdev C library refer to the offical documentation at http://www.freedesktop.org/software/libevdev/doc/latest/ Basic examples -------------- Below are examples that cover the most common cases that need to be done with libevdev. More specific examples can be found on the :doc:`examples` page. To read events from an existing device:: import libevdev fd = open('/dev/input/event0', 'rb') d = libevdev.Device(fd) if not d.has(libevdev.EV_KEY.BTN_LEFT): print('This does not look like a mouse device') sys.exit(0) # Loop indefinitely while pulling the currently available events off # the file descriptor while True: for e in d.events(): if not e.matches(libevdev.EV_KEY): continue if e.matches(libevdev.EV_KEY.BTN_LEFT): print('Left button event') elif e.matches(libevdev.EV_KEY.BTN_RIGHT): print('Right button event') .. note:: Reading from and writing to input devices requires root access to the device node. Any programs using libevdev need to run as root. To create a new uinput device with a specific set of events:: import libevdev d = libevdev.Device() d.name = 'some test device' d.enable(libevdev.EV_REL.REL_X) d.enable(libevdev.EV_REL.REL_Y) d.enable(libevdev.EV_KEY.BTN_LEFT) d.enable(libevdev.EV_KEY.BTN_MIDDLE) d.enable(libevdev.EV_KEY.BTN_RIGHT) uinput = d.create_uinput_device() print('new uinput test device at {}'.format(uinput.devnode)) events = [InputEvent(libevdev.EV_REL.REL_X, 1), InputEvent(libevdev.EV_REL.REL_Y, 1), InputEvent(libevdev.EV_SYN.SYN_REPORT, 0)] uinput.send_events(events) .. note:: Creating uinput devices requires root access. Any programs using libevdev need to run as root. It's common to read events or device descriptions from some file (e.g. evemu recordings). libevdev makes it easy to convert numbers or strings into a correct event code:: >>> import libevdev >>> print(libevdev.evbit(0)) EV_SYN:0 >>> print(libevdev.evbit(2)) EV_REL:2 >>> print(libevdev.evbit(3, 4)) ABS_RY:4 >>> print(libevdev.evbit('EV_ABS')) EV_ABS:3 >>> print(libevdev.evbit('EV_ABS', 'ABS_X')) ABS_X:0 >>> print(libevdev.evbit('ABS_X')) ABS_X:0 .. toctree:: :caption: Table of Contents :maxdepth: 2 tutorial API documentation examples python-evdev Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` python-libevdev-0.5/doc/source/libevdev.rst000066400000000000000000000011111326746764000211050ustar00rootroot00000000000000libevdev package ================ Submodules ---------- libevdev\.const module ---------------------- .. automodule:: libevdev.const :members: :undoc-members: :show-inheritance: libevdev\.device module ----------------------- .. automodule:: libevdev.device :members: :undoc-members: :show-inheritance: libevdev\.event module ---------------------- .. automodule:: libevdev.event :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: libevdev :members: :undoc-members: :show-inheritance: python-libevdev-0.5/doc/source/modules.rst000066400000000000000000000000751326746764000207650ustar00rootroot00000000000000libevdev ======== .. toctree:: :maxdepth: 4 libevdev python-libevdev-0.5/doc/source/python-evdev.rst000066400000000000000000000026701326746764000217500ustar00rootroot00000000000000Difference between python-libevdev and python-evdev =================================================== python-evdev is an existing package that provides python access to the evdev protocol. Its documentation is found here: https://python-evdev.readthedocs.io/en/latest/ They both wrap the same kernel protocol, so there is a large overlap between the two projects. The biggest difference and motivation for python-libevdev was that it wraps libevdev rather than just using the kernel directly. This provides a number of advantages, see **Why libevdev?** on the :doc:`index page ` for details. From an API perspective, python-libevdev and python-evdev have two slightly different approaches. For example, * python-evdev opens the device directly and provides multiple ways of reading events from that device (using ``asyncore``, ``select``, ``selectors``, ``asyncio``, etc.). python-libevdev requires that the caller opens the file descriptor and monitors it, it merely pulls the events off when requested to do so. * python-libevdev requires the conversion into `EventCode` and `EventType` early on, the rest of the API only deals with those. python-evdev largely sticks to integers instead (e.g. `dev.leds()` returns an integer array). This makes python-evdev less type-safe than python-libevdev. There are other differences as well, but, unsurprisingly, we think that python-libevdev is the better API and the safer choice. YMMV :) python-libevdev-0.5/doc/source/tutorial.rst000066400000000000000000000233751326746764000211700ustar00rootroot00000000000000Tutorial ======== This is a tutorial on using libevdev's Python wrapper. It is not a tutorial on the evdev protocol, basic knowledge of how evdev works is assumed. Specifically, you're expected to know what an event type and an event code is. If you don't, read https://who-t.blogspot.com.au/2016/09/understanding-evdev.html first. The basic building blocks ------------------------- The most important building blocks are the :class:`Device `, :class:`InputEvent ` and the :func:`evbit() ` function. A :class:`Device ` object refers to any libevdev device, whether it's backed by a real device or not. :class:`InputEvent ` represents an event from that device. libevdev relies on the caller using wrapped event code objects rather than just strings and numbers, :func:`evbit() ` converts from one to the other. Event types and codes --------------------- In raw evdev, each event has an event type and an event code. These are just numbers with overlapping ranges, so it's possible to mix them up. libevdev takes this away by providing objects for both types and codes. These objects are required in all API calls, so the chances of mixing things up are reduced. All event codes and types are exposed in the libevdev module namespace:: >>> t = libevdev.EV_ABS >>> print(t) EV_ABS:3 >>> print(t.value) 3 >>> print(t.name) EV_ABS >>> c = libevdev.EV_ABS.ABS_X >>> print(c) ABS_X:0 >>> print(c.value) 0 >>> print(c.name) ABS_X As you can see, each type or code has a ``value`` and ``name`` attribute. Each type and code also references each other, so you can go from one to the other easily:: >>> c = libevdev.EV_ABS.ABS_X >>> print(c.type) EV_ABS:3 >>> c.type == libevdev.EV_ABS True >>> t = libevdev.EV_ABS >>> print(t.codes[:3]) [ABS_X:0, ABS_Y:1, ABS_Z:2] >>> t.codes[0] == libevdev.EV_ABS.ABS_X True Converting to and from a event code ----------------------------------- When parsing text files with device descriptions, the data is usually in the form of numeric values or text strings for each event type or event code. The :func:`evbit() ` function is the conversion function to get the real event types and codes from that data. Using it is easy: just pass the numbers or strings in and use the object that comes out:: >>> print(libevdev.evbit(3)) EV_ABS:3 >>> libevdev.evbit(3) == libevdev.EV_ABS True >>> print(libevdev.evbit(3, 0)) ABS_X:0 >>> libevdev.evbit(3, 0) == libevdev.EV_ABS.ABS_X True For the cases where the data is strings, it works much in the same way:: >>> print(libevdev.evbit('EV_ABS')) EV_ABS:3 >>> libevdev.evbit('EV_ABS') == libevdev.EV_ABS True >>> print(libevdev.evbit('EV_ABS', 'ABS_X')) ABS_X:0 >>> libevdev.evbit('EV_ABS', 'ABS_X') == libevdev.EV_ABS.ABS_X True >>> print(libevdev.evbit('ABS_X')) ABS_X:0 >>> libevdev.evbit('ABS_X') == libevdev.EV_ABS.ABS_X True Most of the event code strings are unique, so as you can see in the third example above, the event type isn't needed when converting from string. Ok, now that we know how to deal with event codes and types, we can move on to actually using those. Opening a device ---------------- Opening and closing devices is left to the caller. libevdev merely makes use of any file objects that it is given. It also relies on the caller to figure out when events are available on the file object - all libevdev does is use the file descriptor when asked to do so. libevdev doesn't give you a list of devices either - you can easily figure that out yourself by looping through the file system or using libudev. The simplest case (and good enough for most applications) is a mere call to ``open``:: >>> fd = open("/dev/input/event0", "rb") >>> device = libevdev.Device(fd) >>> print(device.name) Lid Switch This creates a device that is backed by a file descriptior - we can read events from it later or even modify the kernel device. That's it. libevdev doesn't really care how you opened the device, as long as ``fileno()`` works on it it'll take it. Now we can move on to actually handling the device Querying and modifying device capabilities ------------------------------------------ The :func:`has ` function returns True when a device has a given event type or event code. So let's check whether this device is a mouse:: if not device.has(libevdev.EV_REL): print('I expected relative axes from a mouse...') sys.exit(0) if device.has(libevdev.EV_KEY.BTN_MIDDLE): print('Fancy, a mouse with a middle button!') device.disable(libevdev.EV_KEY.BTN_MIDDLE) print('... but you do not get to use it') The :func:`has ` calls are self-explanatory. The call to :func:`disable ` disables the given event code or event type. When disabled, no events from this code or type are forwarded to the caller and future calls to :func:`has ` return ``False``. The inverse is possible too, enabling a non-existing event code:: if not device.has(libevdev.EV_KEY.BTN_MIDDLE): device.enable(libevdev.EV_KEY.BTN_MIDDLE) print('Free middle buttons for everyone!') Unsurprisingly, the physical device won't generate events for axes it doesn't have. Enabling event codes is generally only useful to fix device-specific quirks in one place and then assume that devices are behaving correctly. .. note:: Enabling absolute axes requires extra data. See :func:`disable ` for details. Reading events -------------- libevdev does not have a concept of an event loop, it relies on the caller to monitor the file descriptor for events. Thus, the concept of "availablable events" means "events available right now" and the :func:`events ` function returns exactly that:: while True: for e in device.events(): print(e) # now do some other stuff, like rendering things The events returned are of class :class:`InputEvent ` and represent the C ``struct input_event``, but they're type-safer. Every event has a :func:`type ` and a :func:`code ` representing its event type and code. And of course a :func:`value `. The most useful method on the input events is :func:`matches ` which can be used to compare for types, codes and/or values:: for e in device.events(): if e.matches(libevdev.EV_MSC): continue # don't care about those if e.matches(libevdev.EV_REL.REL_X: move_by(e.value, 0) elif e.matches(libevdev.EV_REL.REL_Y): move_by(0, e.value) elif e.matches(libevdev.EV_KEY.BTN_MIDDLE, value=1): printf('How did we manage to get a middle button press?') Alternatively, you can create input events and use those for comparisons:: btn = InputEvent(libevdev.EV_KEY.BTN_MIDDLE, value=1) if btn in device.events(): print('There is a button event in there') Creating uinput devices ----------------------- .. note:: Creating uinput devices requires root access. Creating virtual devices through uinput is a common case for users that want to inject input events into the system. libevdev makes this easy by creating a device from an existing libevdev context:: device = libevdev.Device() device.name = 'my fake device' device.enable(libevdev.EV_KEY.BTN_LEFT) device.enable(libevdev.EV_KEY.BTN_MIDDLE) device.enable(libevdev.EV_KEY.BTN_RIGHT) uinput = device.create_uinput_device() print('device is now at {}'.format(uinput.devnode)) press = [libevdev.InputEvent(libevdev.EV_KEY.BTN_MIDDLE, value=1) libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT, value=0)] uinput.send_events(press) release = [libevdev.InputEvent(libevdev.EV_KEY.BTN_MIDDLE, value=0) libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT, value=0)] uinput.send_events(release) In the example above, we create an empty uinput device, set a name and enable a few event codes. Then we create the uinput device and write a middle click press, followed by a release. .. warning:: An event sequence must always be terminated by with a ``libevdev.EV_SYN.SYN_REPORT`` event or the kernel may not process the events. That's really it. The uinput device can be created from any context. By using a real device as source context it's easy to duplicate an existing device with exactly the same attributes. The resulting uinput device is a libevdev context too, so all the previously mentioned methods work on it - it just won't ever send events. Usually you'd create a new libevdev context from the device at the uinput's device node:: uinput = device.create_uinput_device() fd = open(uinput.devnode, 'rb') newdev = libevdev.Device(fd) ... Summary ------- This tutorial provided an overview on how to initialize libevdev and handle basic properties and events. Full examples for some use-cases are available on the :doc:`examples` page. The :doc:`API documentation ` explains all functions available to the caller. python-libevdev-0.5/examples/000077500000000000000000000000001326746764000163325ustar00rootroot00000000000000python-libevdev-0.5/examples/evtest.py000077500000000000000000000062141326746764000202240ustar00rootroot00000000000000#!/usr/bin/env python3 import sys import libevdev def print_capabilities(l): v = l.driver_version print("Input driver version is {}.{}.{}".format(v >> 16, (v >> 8) & 0xff, v & 0xff)) id = l.id print("Input device ID: bus {:#x} vendor {:#x} product {:#x} version {:#x}".format( id["bustype"], id["vendor"], id["product"], id["version"], )) print("Input device name: {}".format(l.name)) print("Supported events:") for t, cs in l.evbits.items(): print(" Event type {} ({})".format(t.value, t.name)) for c in cs: if t in [libevdev.EV_LED, libevdev.EV_SND, libevdev.EV_SW]: v = l.event_value(t, c) print(" Event code {} ({}) state {}".format(c.value, c.name, v)) else: print(" Event code {} ({})".format(c.value, c.name)) if t == libevdev.EV_ABS: a = l.absinfo[c] print(" {:10s} {:6d}".format('Value', a.value)) print(" {:10s} {:6d}".format('Minimum', a.minimum)) print(" {:10s} {:6d}".format('Maximum', a.maximum)) print(" {:10s} {:6d}".format('Fuzz', a.fuzz)) print(" {:10s} {:6d}".format('Flat', a.flat)) print(" {:10s} {:6d}".format('Resolution', a.resolution)) print("Properties:") for p in l.properties: print(" Property type {} ({})".format(p.value, p.name)) def print_event(e): print("Event: time {}.{:06d}, ".format(e.sec, e.usec), end='') if e.matches(libevdev.EV_SYN): if e.matches(libevdev.EV_SYN.SYN_MT_REPORT): print("++++++++++++++ {} ++++++++++++".format(e.code.name)) elif e.matches(libevdev.EV_SYN.SYN_DROPPED): print(">>>>>>>>>>>>>> {} >>>>>>>>>>>>".format(e.code.name)) else: print("-------------- {} ------------".format(e.code.name)) else: print("type {:02x} {} code {:03x} {:20s} value {:4d}".format(e.type.value, e.type.name, e.code.value, e.code.name, e.value)) def main(args): path = args[1] try: with open(path, "rb") as fd: l = libevdev.Device(fd) print_capabilities(l) print("################################\n" "# Waiting for events #\n" "################################") while True: try: for e in l.events(): print_event(e) except libevdev.EventsDroppedException: for e in l.sync(): print_event(e) except KeyboardInterrupt: pass except IOError as e: import errno if e.errno == errno.EACCES: print("Insufficient permissions to access {}".format(path)) elif e.errno == errno.ENOENT: print("Device {} does not exist".format(path)) else: raise e if __name__ == "__main__": if len(sys.argv) < 2: print("Usage: {} /dev/input/eventX".format(sys.argv[0])) sys.exit(1) main(sys.argv) python-libevdev-0.5/examples/filter-device-events.py000077500000000000000000000024211326746764000227320ustar00rootroot00000000000000#!/usr/bin/env python3 # # This example shows how to 'filter' device events from a device node. # While real filtering is not possible, we can duplicate the input device as # a new virtual input device and replay all events of the input events on # our virtual one. import sys import libevdev def main(args): path = args[1] code_from = libevdev.evbit(args[2]) code_to = libevdev.evbit(args[3]) print('Remapping {} to {}'.format(code_from, code_to)) fd = open(path, 'rb') d = libevdev.Device(fd) d.grab() # create a duplicate of our input device d.enable(code_to) # make sure the code we map to is available uidev = d.create_uinput_device() print('Device is at {}'.format(uidev.devnode)) while True: for e in d.events(): # change any event with our event code to # the one we want to map to, but pass all other events # through if e.code == code_from: e = libevdev.InputEvent(code_to, e.value) uidev.send_events([e]) if __name__ == "__main__": if len(sys.argv) < 4: print("Usage: {} /dev/input/eventX ".format(sys.argv[0])) print(" where and are event codes, e.g. REL_X") sys.exit(1) main(sys.argv) python-libevdev-0.5/examples/kernel-device-update.py000077500000000000000000000022531326746764000227060ustar00rootroot00000000000000#!/usr/bin/env python3 # # This example shows how to update a kernel device's axis range # This can be useful to e.g. change the resolution on a touchpad. # Note that this is an example only, there are a lot of race conditions to # be considered when using this as a proper solution. import sys import libevdev def main(args): path = args[1] axis = args[2] field = args[3] value = int(args[4]) assert field in ['minimum', 'maximum', 'resolution'] axis = libevdev.evbit(axis) assert axis is not None fd = open(path, 'rb') d = libevdev.Device(fd) if not d.has(axis): print('Device does not have axis {}'.format(axis)) sys.exit(1) a = d.absinfo[axis] setattr(a, field, value) d.absinfo[axis] = a d.sync_absinfo_to_kernel(axis) if __name__ == "__main__": if len(sys.argv) < 5: print("Usage: {} /dev/input/eventX ".format(sys.argv[0])) print(" ... an EV_ABS event code, e.g. ABS_X") print(" .. one of 'minimum', 'maximum', 'resolution'") print(" .. the numeric value to set the axis field to") sys.exit(1) main(sys.argv) python-libevdev-0.5/examples/uinput.py000077500000000000000000000012311326746764000202300ustar00rootroot00000000000000#!/usr/bin/env python3 import sys import libevdev from libevdev import InputEvent def main(args): dev = libevdev.Device() dev.name = "test device" dev.enable(libevdev.EV_REL.REL_X) dev.enable(libevdev.EV_REL.REL_Y) try: uinput = dev.create_uinput_device() print("New device at {} ({})".format(uinput.devnode, uinput.syspath)) events = [InputEvent(libevdev.EV_REL.REL_X, -1), InputEvent(libevdev.EV_REL.REL_Y, 1), InputEvent(libevdev.EV_SYN.SYN_REPORT, 0)] uinput.send_events(events) except OSError as e: print(e) if __name__ == "__main__": main(sys.argv) python-libevdev-0.5/libevdev/000077500000000000000000000000001326746764000163145ustar00rootroot00000000000000python-libevdev-0.5/libevdev/__init__.py000066400000000000000000000025451326746764000204330ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2016 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. from .device import Device, InputAbsInfo from .device import InvalidFileError, EventsDroppedException, InvalidArgumentException from .event import InputEvent from .const import evbit, propbit, EventType, EventCode, InputProperty python-libevdev-0.5/libevdev/_clib.py000066400000000000000000001002211326746764000177320ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2016 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. import libevdev import os import ctypes import errno from ctypes import c_char_p from ctypes import c_int from ctypes import c_uint from ctypes import c_void_p from ctypes import c_long from ctypes import c_int32 from ctypes import c_uint16 READ_FLAG_SYNC = 0x1 READ_FLAG_NORMAL = 0x2 READ_FLAG_FORCE_SYNC = 0x4 READ_FLAG_BLOCKING = 0x8 class _InputAbsinfo(ctypes.Structure): _fields_ = [("value", c_int32), ("minimum", c_int32), ("maximum", c_int32), ("fuzz", c_int32), ("flat", c_int32), ("resolution", c_int32)] class _InputEvent(ctypes.Structure): _fields_ = [("sec", c_long), ("usec", c_long), ("type", c_uint16), ("code", c_uint16), ("value", c_int32)] class _LibraryWrapper(object): """ Base class for wrapping a shared library. Do not use directly. """ _lib = None # The shared library, shared between instances of the class # List of API prototypes, must be set by the subclass _api_prototypes = { # "function_name" : { # "argtypes": [c_void_p, c_char_p, etc. ], # arguments # "restype": c_void_p, # return type # "restype": c_void_p, # return type # } } def __init__(self): super(_LibraryWrapper, self).__init__() self._load() @classmethod def _load(cls): if cls._lib is not None: return cls._lib cls._lib = cls._cdll() for (name, attrs) in cls._api_prototypes.items(): func = getattr(cls._lib, name) func.argtypes = attrs["argtypes"] func.restype = attrs["restype"] # default name is the libevdev name minus the libevdev prefix # This makes all functions hidden and require # one-by-one-mapping prefix = len("libevdev") pyname = dict.get(attrs, "name", name[prefix:]) setattr(cls, pyname, func) return cls._lib @staticmethod def _cdll(): """Override in subclass""" raise NotImplementedError class Libevdev(_LibraryWrapper): """ This class provides a wrapper around the libevdev C library. The API is modelled closely after the C API. API documentation in this document only lists the specific behavior of the Phython API. For information on the behavior of libevdev itself, see https://www.freedesktop.org/software/libevdev/doc/latest/ Properties in this class are read-write unless specified otherwise. .. warning:: Do not use this class directly """ @staticmethod def _cdll(): return ctypes.CDLL("libevdev.so.2", use_errno=True) _api_prototypes = { # const char *libevdev_event_type_get_name(unsigned int type); "libevdev_event_type_get_name": { "argtypes": (c_uint,), "restype": c_char_p }, # int libevdev_event_type_from_name(const char *name); "libevdev_event_type_from_name": { "argtypes": (c_char_p,), "restype": c_int }, # const char *libevdev_event_code_get_name(unsigned int type, unsigned int code); "libevdev_event_code_get_name": { "argtypes": (c_uint, c_uint,), "restype": c_char_p }, # int libevdev_event_code_from_name(unsigned int type, const char *name); "libevdev_event_code_from_name": { "argtypes": (c_uint, c_char_p,), "restype": c_int }, # const char *libevdev_property_get_name(unsigned int prop); "libevdev_property_get_name": { "argtypes": (c_uint,), "restype": c_char_p, }, # int libevdev_property_from_name(const char *name); "libevdev_property_from_name": { "argtypes": (c_char_p,), "restype": c_int }, # void libevdev_event_type_get_max(int) "libevdev_event_type_get_max": { "argtypes": (c_int, ), "restype": c_int, }, # struct libevdev *libevdev_new(void); "libevdev_new": { "argtypes": (), "restype": c_void_p, }, # struct libevdev *libevdev_free(struct libevdev *); "libevdev_free": { "argtypes": (c_void_p,), "restype": None, }, ############################### # Simple getters and setters # ############################### # const char * libevdev_get_name(struct libevdev *); "libevdev_get_name": { "argtypes": (c_void_p,), "restype": c_char_p, }, # void libevdev_set_name(struct libevdev *, const char*); "libevdev_set_name": { "argtypes": (c_void_p, c_char_p), "restype": None, }, # const char * libevdev_get_phys(struct libevdev *); "libevdev_get_phys": { "argtypes": (c_void_p,), "restype": c_char_p, }, # void libevdev_set_phys(struct libevdev *, const char*); "libevdev_set_phys": { "argtypes": (c_void_p, c_char_p), "restype": None, }, # const char * libevdev_get_uniq(struct libevdev *); "libevdev_get_uniq": { "argtypes": (c_void_p,), "restype": c_char_p, }, # void libevdev_set_uniq(struct libevdev *, const char*); "libevdev_set_uniq": { "argtypes": (c_void_p, c_char_p), "restype": None, }, # int libevdev_get_driver_version(struct libevdev *); "libevdev_get_driver_version": { "argtypes": (c_void_p, ), "restype": c_int, }, # void libevdev_set_clock_id(struct libevdev *, int) "libevdev_set_clock_id": { "argtypes": (c_void_p, c_int), "restype": c_int, }, ############################### # Custom getters and setters # ############################### # int libevdev_get_id_bustype(struct libevdev *) "libevdev_get_id_bustype": { "argtypes": (c_void_p,), "restype": c_int, }, # int libevdev_get_id_vendor(struct libevdev *) "libevdev_get_id_vendor": { "argtypes": (c_void_p,), "restype": c_int, }, # int libevdev_get_id_product(struct libevdev *) "libevdev_get_id_product": { "argtypes": (c_void_p,), "restype": c_int, }, # int libevdev_get_id_version(struct libevdev *) "libevdev_get_id_version": { "argtypes": (c_void_p,), "restype": c_int, }, # void libevdev_set_id_bustype(struct libevdev *, int) "libevdev_set_id_bustype": { "argtypes": (c_void_p, c_int), "restype": None, }, # void libevdev_set_id_vendor(struct libevdev *, int) "libevdev_set_id_vendor": { "argtypes": (c_void_p, c_int), "restype": None, }, # void libevdev_set_id_product(struct libevdev *, int) "libevdev_set_id_product": { "argtypes": (c_void_p, c_int), "restype": None, }, # void libevdev_set_id_version(struct libevdev *, int) "libevdev_set_id_version": { "argtypes": (c_void_p, c_int), "restype": None, }, # int libevdev_set_fd(struct libevdev *, int) "libevdev_set_fd": { "argtypes": (c_void_p, c_int), "restype": c_int, }, # int libevdev_change_fd(struct libevdev *, int) "libevdev_change_fd": { "argtypes": (c_void_p, c_int), "restype": c_int, }, # int libevdev_get_fd(struct libevdev *) "libevdev_get_fd": { "argtypes": (c_void_p, ), "restype": c_int, }, # int libevdev_grab(struct libevdev *) "libevdev_grab": { "argtypes": (c_void_p, c_int), "restype": c_int, }, # const struct input_absinfo *libevdev_get_abs_info(struct libevdev*, int code) "libevdev_get_abs_info": { "argtypes": (c_void_p, c_int), "restype": ctypes.POINTER(_InputAbsinfo), }, # We don't need to wrap libevdev_set_abs_info(), we get the same # using get_abs_info and overwrite the values. # # const struct input_absinfo *libevdev_get_abs_info(struct libevdev*, int code) "libevdev_kernel_set_abs_info": { "argtypes": (c_void_p, c_int, ctypes.POINTER(_InputAbsinfo)), "restype": (c_int) }, ########################## # Various has_ functions # ########################## "libevdev_has_property": { "argtypes": (c_void_p, c_int), "restype": (c_int) }, "libevdev_has_event_type": { "argtypes": (c_void_p, c_int), "restype": (c_int) }, "libevdev_has_event_code": { "argtypes": (c_void_p, c_int, c_int), "restype": (c_int) }, ########################## # Other functions # ########################## "libevdev_set_event_value": { "argtypes": (c_void_p, c_int, c_int, c_int), "restype": (c_int) }, "libevdev_get_event_value": { "argtypes": (c_void_p, c_int, c_int), "restype": (c_int), }, "libevdev_enable_event_type": { "argtypes": (c_void_p, c_int), "restype": (c_int), }, "libevdev_enable_event_code": { "argtypes": (c_void_p, c_int, c_int, c_void_p), "restype": (c_int), }, "libevdev_disable_event_type": { "argtypes": (c_void_p, c_int), "restype": (c_int), }, "libevdev_disable_event_code": { "argtypes": (c_void_p, c_int, c_int), "restype": (c_int), }, "libevdev_enable_property": { "argtypes": (c_void_p, c_int), "restype": (c_int), }, "libevdev_next_event": { "argtypes": (c_void_p, c_uint, ctypes.POINTER(_InputEvent)), "restype": c_int, }, "libevdev_get_num_slots": { "argtypes": (c_void_p,), "restype": c_int, }, "libevdev_get_current_slot": { "argtypes": (c_void_p,), "restype": c_int, }, "libevdev_get_slot_value": { "argtypes": (c_void_p, c_uint, c_uint), "restype": c_int, }, "libevdev_set_slot_value": { "argtypes": (c_void_p, c_uint, c_uint, c_int), "restype": c_int, }, "libevdev_has_event_pending": { "argtypes": (c_void_p,), "restype": c_int, }, } def __init__(self, fd=None): """ :param fd: A file-like object Create a new libevdev instance. If a file is given this call is equivalent to ``libevdev_new_from_fd()``, otherwise it is equivalent to ``libevdev_new()``:: fd = open("/dev/input/event0", "rb") l = libevdev.Libevdev(fd) # l now represents the device on event0 l2 = libevdev.Libevdev() l2.name = "test device" l2.enable("EV_REL", "REL_X") # l2 is an unbound device with the REL_X bit set """ super(Libevdev, self).__init__() self._ctx = self._new() self._file = None if fd is not None: self.fd = fd def __del__(self): if hasattr(self, "_ctx"): self._free(self._ctx) @property def name(self): """ :return: A string with the device's kernel name. """ return self._get_name(self._ctx).decode("iso8859-1") @name.setter def name(self, name): if name is None: name = '' return self._set_name(self._ctx, name.encode("iso8859-1")) @property def phys(self): """ :return: A string with the device's kernel phys or None. """ phys = self._get_phys(self._ctx) if not phys: return None return phys.decode("iso8859-1") @phys.setter def phys(self, phys): # libevdev issue: phys may be NULL, but can't be set to NULL if phys is None: phys = '' return self._set_phys(self._ctx, phys.encode("iso8859-1")) @property def uniq(self): """ :return: A string with the device's kernel uniq or None. """ uniq = self._get_uniq(self._ctx) if not uniq: return None return uniq.decode("iso8859-1") @uniq.setter def uniq(self, uniq): # libevdev issue: uniq may be NULL, but can't be set to NULL if uniq is None: uniq = '' return self._set_uniq(self._ctx, uniq.encode("iso8859-1")) @property def driver_version(self): """ :note: Read-only """ return self._get_driver_version(self._ctx) @property def id(self): """ :return: A dict with the keys 'bustype', 'vendor', 'product', 'version'. When used as a setter, only existing keys are applied to the device. For example, to update the product ID only:: ctx = Libevdev() id["property"] = 1234 ctx.id = id This is a combined version of the libevdev calls ``libevdev_get_id_busytype()``, ``libevdev_get_id_vendor()``, ``libevdev_get_id_product()``, ``libevdev_get_id_version()`` and the respective setters. """ bus = self._get_id_bustype(self._ctx) vdr = self._get_id_vendor(self._ctx) pro = self._get_id_product(self._ctx) ver = self._get_id_version(self._ctx) return {"bustype": bus, "vendor": vdr, "product": pro, "version": ver} @id.setter def id(self, vals): if "bustype" in vals: self._set_id_bustype(self._ctx, vals["bustype"]) if "vendor" in vals: self._set_id_vendor(self._ctx, vals["vendor"]) if "product" in vals: self._set_id_product(self._ctx, vals["product"]) if "version" in vals: self._set_id_version(self._ctx, vals["version"]) def set_clock_id(self, clock): """ :param clock: time.CLOCK_MONOTONIC :return: a negative errno on failure or 0 on success. """ return self._set_clock_id(self._ctx, clock) @property def fd(self): """ :return: The file-like object used during constructor or in the most recent assignment to self.fd. When assigned the first time and no file has been passed to the constructor, the assignment is equivalent to ``libevdev_set_fd()``. Subsequently, any assignments are equivalent to ``libevdev_change_fd``:: fd = open("/dev/input/event0", "rb") l = libevdev.Libevdev(fd) assert(l.fd == fd) fd2 = open("/dev/input/event0", "rb") l.fd = fd2 assert(l.fd == fd2) l = libevdev.Libevdev() l.fd = fd assert(l.fd == fd) l.fd = fd2 assert(l.fd == fd2) :note: libevdev uses the ``fileno()`` of the object. """ return self._file @fd.setter def fd(self, fileobj): try: fd = fileobj.fileno() except AttributeError: raise libevdev.InvalidFileError if self._file is None: r = self._set_fd(self._ctx, fd) else: r = self._change_fd(self._ctx, fd) if r != 0: raise OSError(-r, os.strerror(-r)) # sanity check: if self._get_fd(self._ctx) != fd: print("FIXME: fileno() != get_fd()") self._file = fileobj def grab(self, enable_grab=True): """ :param enable_grab: True to grab, False to ungrab :return: 0 on success or a negative errno on failure """ # libevdev doesn't use 0/1 here but numbered values if enable_grab: mode = 3 else: mode = 4 r = self._grab(self._ctx, mode) if r != 0: raise OSError(-r, os.strerror(-r)) def absinfo(self, code, new_values=None, kernel=False): """ :param code: the ABS_<*> code as integer or as string :param new_values: a dict with the same keys as the return values. :param kernel: If True, assigning new values corresponds to ``libevdev_kernel_set_abs_info`` :return: a dictionary with the keys "value", "min", "max", "resolution", "fuzz", "flat"; ``None`` if the code does not exist on this device :note: The returned value is a copy of the value returned by libevdev. Changing a value in the dictionary does not change the matching property. To change the device, reassign the dictionary to the absinfo code. This is different to the libevdev behavior. """ if not isinstance(code, int): if not code.startswith("ABS_"): raise ValueError() code = self.event_to_value("EV_ABS", code) absinfo = self._get_abs_info(self._ctx, code) if not absinfo: return None if new_values is not None: if "minimum" in new_values: absinfo.contents.minimum = new_values["minimum"] if "maximum" in new_values: absinfo.contents.maximum = new_values["maximum"] if "value" in new_values: absinfo.contents.value = new_values["value"] if "fuzz" in new_values: absinfo.contents.fuzz = new_values["fuzz"] if "flat" in new_values: absinfo.contents.flat = new_values["flat"] if "resolution" in new_values: absinfo.contents.resolution = new_values["resolution"] if kernel: rc = self._kernel_set_abs_info(self._ctx, code, absinfo) if rc != 0: raise OSError(-rc, os.strerror(-rc)) return {"value": absinfo.contents.value, "minimum": absinfo.contents.minimum, "maximum": absinfo.contents.maximum, "fuzz": absinfo.contents.fuzz, "flat": absinfo.contents.flat, "resolution": absinfo.contents.resolution} @classmethod def property_to_name(cls, prop): """ :param prop: the numerical property value :return: A string with the property name or ``None`` This function is the equivalent to ``libevdev_property_get_name()`` """ name = cls._property_get_name(prop) if not name: return None return name.decode("iso8859-1") @classmethod def property_to_value(cls, prop): """ :param prop: the property name as string :return: The numerical property value or ``None`` This function is the equivalent to ``libevdev_property_from_name()`` """ v = cls._property_from_name(prop.encode("iso8859-1")) if v == -1: return None return v @classmethod def type_max(cls, type): """ :param type: the EV_<*> event type :return: the maximum code for this type or ``None`` if the type is invalid """ if not isinstance(type, int): type = cls.event_to_value(type) m = cls._event_type_get_max(type) return m if m > -1 else None @classmethod def event_to_name(cls, event_type, event_code=None): """ :param event_type: the numerical event type value :param event_code: optional, the numerical event code value :return: the event code name if a code is given otherwise the event type name. This function is the equivalent to ``libevdev_event_code_get_name()`` and ``libevdev_event_type_get_name()`` """ if event_code is not None: name = cls._event_code_get_name(event_type, event_code) else: name = cls._event_type_get_name(event_type) if not name: return None return name.decode("iso8859-1") @classmethod def event_to_value(cls, event_type, event_code=None): """ :param event_type: the event type as string :param event_code: optional, the event code as string :return: the event code value if a code is given otherwise the event type value. This function is the equivalent to ``libevdev_event_code_from_name()`` and ``libevdev_event_type_from_name()`` """ if event_code is not None: if not isinstance(event_type, int): event_type = cls.event_to_value(event_type) v = cls._event_code_from_name(event_type, event_code.encode("iso8859-1")) else: v = cls._event_type_from_name(event_type.encode("iso8859-1")) if v == -1: return None return v def has_property(self, prop): """ :param prop: a property, either as integer or string :return: True if the device has the property, False otherwise """ if not isinstance(prop, int): prop = self.property_to_value(prop) r = self._has_property(self._ctx, prop) return bool(r) def has_event(self, event_type, event_code=None): """ :param event_type: the event type, either as integer or as string :param event_code: optional, the event code, either as integer or as string :return: True if the device has the type and/or code, False otherwise """ if not isinstance(event_type, int): event_type = self.event_to_value(event_type) if event_code is None: r = self._has_event_type(self._ctx, event_type) else: if not isinstance(event_code, int): event_code = self.event_to_value(event_type, event_code) r = self._has_event_code(self._ctx, event_type, event_code) return bool(r) def _code(self, t, c): """ Resolves a type+code tuple, either of which could be integer or string. Returns a (t, c) tuple in integers """ if not isinstance(t, int): t = self.event_to_value(t) if c is not None and not isinstance(c, int): c = self.event_to_value(t, c) return (t, c) def event_value(self, event_type, event_code, new_value=None): """ :param event_type: the event type, either as integer or as string :param event_code: the event code, either as integer or as string :param new_value: optional, the value to set to :return: the current value of type + code, or ``None`` if it doesn't exist on this device """ t, c = self._code(event_type, event_code) if not self.has_event(t, c): return None if new_value is not None: self._set_event_value(self._ctx, t, c, new_value) v = self._get_event_value(self._ctx, t, c) return v @property def num_slots(self): """ :return: the number of slots on this device or ``None`` if this device does not support slots :note: Read-only """ s = self._get_num_slots(self._ctx) return s if s >= 0 else None @property def current_slot(self): """ :return: the current of slots on this device or ``None`` if this device does not support slots :note: Read-only """ s = self._get_current_slot(self._ctx) return s if s >= 0 else None def slot_value(self, slot, event_code, new_value=None): """ :param slot: the numeric slot number :param event_code: the ABS_<*> event code, either as integer or string :param new_value: optional, the value to set this slot to :return: the current value of the slot's code, or ``None`` if it doesn't exist on this device """ t, c = self._code("EV_ABS", event_code) if new_value is not None: self._set_slot_value(self._ctx, slot, c, new_value) v = self._get_slot_value(self._ctx, slot, c) return v def enable(self, event_type, event_code=None, data=None): """ :param event_type: the event type, either as integer or as string :param event_code: optional, the event code, either as integer or as string :param data: if event_code is not ``None``, data points to the code-specific information. If event_type is EV_ABS, then data must be a dictionary as returned from absinfo. Any keys missing are replaced with 0, i.e. the following example is valid and results in a fuzz/flat/resolution of zero:: ctx = Libevdev() abs = { "minimum" : 0, "maximum" : 100 } ctx.enable("EV_ABS", "ABS_X", data) If event_type is EV_REP, then data must be an integer. """ t, c = self._code(event_type, event_code) if c is None: self._enable_event_type(self._ctx, t) else: if t == 0x03: # EV_ABS data = _InputAbsinfo(data.get("value", 0), data.get("minimum", 0), data.get("maximum", 0), data.get("fuzz", 0), data.get("flat", 0), data.get("resolution", 0)) data = ctypes.pointer(data) elif t == 0x14: # EV_REP data = ctypes.pointer(c_int(data)) self._enable_event_code(self._ctx, t, c, data) def disable(self, event_type, event_code=None): """ :param event_type: the event type, either as integer or as string :param event_code: optional, the event code, either as integer or as string """ t, c = self._code(event_type, event_code) if c is None: self._disable_event_type(self._ctx, t) else: self._disable_event_code(self._ctx, t, c) def enable_property(self, prop): """ :param prop: the property as integer or string """ if not isinstance(prop, int): prop = self.property_to_value(prop) self._enable_property(self._ctx, prop) def set_led(self, led, on): """ :param led: the LED_<*> name :on: True to turn the LED on, False to turn it off """ t, c = self._code("EV_LED", led) which = 3 if on else 4 self._set_led_value(self._ctx, c, which) def next_event(self, flags=READ_FLAG_NORMAL): """ :param flags: a set of libevdev read flags. May be omitted to use the normal mode. :return: the next event or ``None`` if no event is available Event processing should look like this:: fd = open("/dev/input/event0", "rb") ctx = libevdev.Libevdev(fd) ev = ctx.next_event() if ev is None: print("no event available right now") elif ev.matches("EV_SYN", "SYN_DROPPED"): sync_ev = ctx.next_event(libevdev.READ_FLAG_SYNC) while ev is not None: print("First event in sync sequence") sync_ev = ctx.next_event(libevdev.READ_FLAG_SYNC) print("sync complete") """ ev = _InputEvent() rc = self._next_event(self._ctx, flags, ctypes.byref(ev)) if rc == -errno.EAGAIN: return None return ev class _UinputDevice(ctypes.Structure): pass class UinputDevice(_LibraryWrapper): """ This class provides a wrapper around the libevdev C library .. warning:: Do not use this class directly """ @staticmethod def _cdll(): return ctypes.CDLL("libevdev.so.2", use_errno=True) _api_prototypes = { # int libevdev_uinput_create_from_device(const struct libevdev *, int, struct libevdev_uinput **) "libevdev_uinput_create_from_device": { "argtypes": (c_void_p, c_int, ctypes.POINTER(ctypes.POINTER(_UinputDevice))), "restype": c_int }, # int libevdev_uinput_destroy(const struct libevdev *) "libevdev_uinput_destroy": { "argtypes": (c_void_p,), "restype": None, }, # const char* libevdev_uinput_get_devnode(const struct libevdev *) "libevdev_uinput_get_devnode": { "argtypes": (c_void_p,), "restype": c_char_p, }, # const char* libevdev_uinput_get_syspath(const struct libevdev *) "libevdev_uinput_get_syspath": { "argtypes": (c_void_p,), "restype": c_char_p, }, # int libevdev_uinput_write_event(const struct libevdev *, uint, uint, int) "libevdev_uinput_write_event": { "argtypes": (c_void_p, c_uint, c_uint, c_int), "restype": c_int }, } def __init__(self, source, fileobj=None): """ Create a new uinput device based on the source libevdev device. The uinput device will mirror all capabilities from the source device. :param source: A libevdev device with all capabilities set. :param fileobj: A file-like object to the /dev/uinput node. If None, libevdev will open the device in managed mode. See the libevdev documentation for details. """ super(UinputDevice, self).__init__() self._fileobj = fileobj if fileobj is None: fd = -2 # UINPUT_OPEN_MANAGED else: fd = fileobj.fileno() self._uinput_device = ctypes.POINTER(_UinputDevice)() rc = self._uinput_create_from_device(source._ctx, fd, ctypes.byref(self._uinput_device)) if rc != 0: raise OSError(-rc, os.strerror(-rc)) def __del__(self): if self._uinput_device is not None: self._uinput_destroy(self._uinput_device) @property def fd(self): """ :return: the file-like object used in the constructor. """ return self.fileobj def write_event(self, type, code, value): self._uinput_write_event(self._uinput_device, type, code, value) @property def devnode(self): """ Return a string with the /dev/input/eventX device node """ devnode = self._uinput_get_devnode(self._uinput_device) return devnode.decode("iso8859-1") @property def syspath(self): """ Return a string with the /dev/input/eventX device node """ syspath = self._uinput_get_syspath(self._uinput_device) return syspath.decode("iso8859-1") python-libevdev-0.5/libevdev/const.py000066400000000000000000000262361326746764000200250ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. import os from functools import total_ordering from ._clib import Libevdev import libevdev @total_ordering class EvdevBit: """ Base class representing an evdev bit, comprised of a name and a value. These two properties are guaranteed to exist on anything describing an event code, event type or input property that comes out of libevdev:: >>> print(libevdev.EV_ABS.name) EV_ABS >>> print(libevdev.EV_ABS.value) 3 >>> print(libevdev.EV_SYN.SYN_REPORT.name) SYN_REPORT >>> print(libevdev.EV_SYN.SYN_REPORT.value) 0 >>> print(libevdev.INPUT_PROP_DIRECT.name) INPUT_PROP_DIRECT >>> print(libevdev.INPUT_PROP_DIRECT.value) 1 .. attribute:: value The numeric value of the event code .. attribute:: name The string name of this event code """ def __repr__(self): return '{}:{}'.format(self.name, self.value) def __eq__(self, other): return self.value == other.value def __lt__(self, other): return self.value < other.value class EventCode(EvdevBit): """ .. warning :: Do not instantiate an object of this class, all objects you'll ever need are already present in the libevdev namespace. Use :func:`evbit()` to get an :class:`EventCode` from numerical or string values. A class representing an evdev event code, e.g. libevdev.EV_ABS.ABS_X. To use a :class:`EventCode`, use the namespaced name directly:: >>> print(libevdev.EV_ABS.ABS_X) ABS_X:0 >>> print(libevdev.EV_ABS.ABS_Y) ABS_X:1 >>> code = libevdev.EV_REL.REL_X >>> print(code.type) EV_REL:2 .. attribute:: value The numeric value of the event code .. attribute:: name The string name of this event code .. attribute:: type The :class:`EventType` for this event code """ __hash__ = super.__hash__ def __eq__(self, other): if not isinstance(other, EventCode): return False return self.value == other.value and self.type == other.type class EventType(EvdevBit): """ .. warning :: Do not instantiate an object of this class, all objects you'll ever need are already present in the libevdev namespace. Use :func:`evbit()` to get an :class:`EventType` from numerical or string values. A class represending an evdev event type (e.g. EV_ABS). All event codes within this type are available as class constants:: >>> print(libevdev.EV_ABS) EV_ABS:3 >>> print(libevdev.EV_ABS.ABS_X) ABS_X:0 >>> print(libevdev.EV_ABS.max) 63 >>> print(libevdev.EV_ABS.ABS_MAX) 63 >>> for code in libevdev.EV_ABS.codes[:3]: ... print(code) ... ABS_X:0 ABS_Y:1 ABS_Z:2 .. attribute:: value The numeric value of the event type .. attribute:: name The string name of this event type .. attribute:: codes A list of :class:`EventCode` objects for this type .. attribute:: max The maximum event code permitted in this type as integer """ __hash__ = super.__hash__ def __eq__(self, other): assert isinstance(other, EventType) return self.value == other.value class InputProperty(EvdevBit): """ .. warning :: Do not instantiate an object of this class, all objects you'll ever need are already present in the libevdev namespace. Use :func:`propbit()` to get an :class:`InputProperty` from numerical or string values. A class representing an evdev input property:: >>> print(libevdev.INPUT_PROP_DIRECT) INPUT_PROP_DIRECT:1 .. attribute:: value The numeric value of the property .. attribute:: name The string name of this property """ __hash__ = super.__hash__ def __eq__(self, other): assert isinstance(other, InputProperty) return self.value == other.value def evbit(evtype, evcode=None): """ Takes an event type and an (optional) event code and returns the Enum representing that type or code, whichever applies. For example:: >>> print(libevdev.evbit(0)) EV_SYN:0 >>> print(libevdev.evbit(2)) EV_REL:2 >>> print(libevdev.evbit(2, 1)) REL_Y:1 >>> print(libevdev.evbit(3, 4)) ABS_RY:4 >>> print(libevdev.evbit('EV_ABS')) EV_ABS:3 >>> print(libevdev.evbit('EV_ABS', 'ABS_X')) ABS_X:0 A special case is the lookup of an string-based event code without the type. Where the string identifier is unique, this will return the right value. >>> print(libevdev.evbit('ABS_X')) ABS_X:0 The return value can be used in the libevdev API wherever an :class:`EventCode` or :class:`EventType` is expected. Notable behavior for invalid types or names: * If the type does not exist, this function returns None * If the type exists but the event code's numeric value does not have a symbolic name (and is within the allowed max of the type), this function returns a valid event code * If the code is outside the allowed maximum for the given type, this function returns None * If the type name exists but the string value is not a code name, this function returns None Examples for the above behaviour:: >>> print(libevdev.evbit(8)) None >>> print(libevdev.evbit('INVALID')) None >>> print(libevdev.evbit('EV_ABS', 62)) ABS_3E:62 >>> print(libevdev.evbit('EV_ABS', 5000)) None >>> print(libevdev.evbit('EV_ABS', 'INVALID')) None :param evtype: the numeric value or string identifying the event type :param evcode: the numeric value or string identifying the event code :return: An event code value representing the code :rtype: EventCode or EventType """ etype = None for t in libevdev.types: if t.value == evtype or t.name == evtype: etype = t break if evcode is None and isinstance(evtype, str) and not evtype.startswith('EV_'): for t in libevdev.types: for c in t.codes: if c.name == evtype: return c if etype is None or evcode is None: return etype ecode = None for c in etype.codes: if c.value == evcode or c.name == evcode: ecode = c return ecode def propbit(prop): """ Takes a property value and returns the :class:`InputProperty` representing that property:: >>> print(libevdev.propbit(0)) INPUT_PROP_POINTER:0 >>> print(libevdev.propbit('INPUT_PROP_POINTER')) INPUT_PROP_POINTER:0 >>> print(libevdev.propbit(1000)) None >>> print(libevdev.propbit('Invalid')) None :param prop: the numeric value or string identifying the property :return: the converted :class:`InputProperty` or None if it does not exist :rtype: InputProperty """ try: return [p for p in libevdev.props if p.value == prop or p.name == prop][0] except IndexError: return None def _load_consts(): """ Loads all event type, code and property names and makes them available as enums in the module. Use as e.g. libevdev.EV_SYN.SYN_REPORT. Available are:: libevdev.types ... an list containing all event types, e.g. libevdev.EV_TYPES.EV_REL libevdev.EV_REL ... an enum containing all REL event types, e.g. libevdev.EV_REL.REL_X. The name of each enum value is the string of the code ('REL_X'), the value is the integer value of that code. libevdev.EV_ABS ... as above, but for EV_ABS libevdev.EV_BITS ... libevdev.EV_FOO as an enum Special attributes are (an apply to all EV_foo enums): libevdev.EV_REL.type ... the EV_TYPES entry of the event type libevdev.EV_REL.max ... the maximum code in this event type """ Libevdev() # classmethods, need to make sure it's loaded at once tmax = Libevdev.event_to_value("EV_MAX") assert tmax is not None types = [] for t in range(tmax + 1): tname = Libevdev.event_to_name(t) if tname is None: continue cmax = Libevdev.type_max(t) new_class = type(tname, (EventType, ), {'value': t, 'name': tname, 'max': cmax}) type_object = new_class() # libevdev.EV_REL, libevdev.EV_ABS, etc. setattr(libevdev, tname, type_object) types.append(type_object) if cmax is None: setattr(type_object, 'codes', []) continue codes = [] for c in range(cmax + 1): cname = Libevdev.event_to_name(t, c) # For those without names, we just use the type name plus # hexcode if cname is None: cname = "{}_{:02X}".format(tname[3:], c) new_class = type(cname, (EventCode, ), {'type': type_object, 'name': cname, 'value': c}) code_object = new_class() setattr(type_object, cname, code_object) codes.append(code_object) setattr(type_object, 'codes', codes) # list of all types setattr(libevdev, 'types', types) pmax = Libevdev.property_to_value("INPUT_PROP_MAX") assert pmax is not None props = [] for p in range(pmax + 1): pname = Libevdev.property_to_name(p) if pname is None: continue new_class = type(pname, (InputProperty, ), {'value': p, 'name': pname}) prop_object = new_class() setattr(libevdev, pname, prop_object) props.append(prop_object) setattr(libevdev, 'props', props) if not os.environ.get('READTHEDOCS'): _load_consts() python-libevdev-0.5/libevdev/device.py000066400000000000000000000665141326746764000201410ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. import time import os import libevdev from ._clib import Libevdev, UinputDevice from ._clib import READ_FLAG_SYNC, READ_FLAG_NORMAL, READ_FLAG_FORCE_SYNC, READ_FLAG_BLOCKING from .event import InputEvent from .const import InputProperty class InvalidFileError(Exception): """ A file provided is not a valid file descriptor for libevdev or this device must not have a file descriptor """ pass class InvalidArgumentException(Exception): """ A function was called with an invalid argument. This indicates a bug in the calling program. .. attribute:: message A human-readable error message """ def __init__(self, msg=None): self.message = msg def __repr__(self): return self.message class DeviceGrabError(Exception): """ A device grab failed to be issued. A caller must not assume that it has exclusive access to the events on the device. """ class EventsDroppedException(Exception): """ Notification that the device has dropped events, raised in response to a EV_SYN SYN_DROPPED event. This exception is raised AFTER the EV_SYN, SYN_DROPPED event has been passed on. If SYN_DROPPED events are processed manually, then this exception can be ignored. Once received (or in response to a SYN_DROPPED event) a caller should call device.sync() and process the events accordingly (if any). Example:: fd = open("/dev/input/event0", "rb") ctx = libevdev.Device(fd) while True: try: for e in ctx.events(): print(e): except EventsDroppedException: print('State lost, re-synching:') for e in ctx.sync(): print(e) """ pass class InputAbsInfo(object): """ A class representing the struct input_absinfo for a given EV_ABS code. Any of the attributes may be set to None, those that are None are simply ignored by libevdev. .. attribute:: minimum the minimum value of this axis :property minimum: the minimum value for this axis :property maximum: the maximum value for this axis :property fuzz: the fuzz value for this axis :property flat: the flat value for this axis :property resolution: the resolution for this axis :property value: the current value of this axis """ def __init__(self, minimum=None, maximum=None, fuzz=None, flat=None, resolution=None, value=None): self.minimum = minimum self.maximum = maximum self.fuzz = fuzz self.flat = flat self.resolution = resolution self.value = value def __repr__(self): return 'min:{} max:{} fuzz:{} flat:{} resolution:{} value:{}'.format( self.minimum, self.maximum, self.fuzz, self.flat, self.resolution, self.value) def __eq__(self, other): return (self.minimum == other.minimum and self.maximum == other.maximum and self.value == other.value and self.resolution == other.resolution and self.fuzz == other.fuzz and self.flat == other.flat) class Device(object): """ This class represents an evdev device backed by libevdev. The device may represent a real device in the system or a constructed device where the caller supplies all properties of the device. If a file is given, the device initializes from that file, otherwise the device is uninitialized and needs to be set up by the caller:: fd = open("/dev/input/event0", "rb") l = libevdev.Device(fd) # l now represents the device on event0 l2 = libevdev.Device() l2.name = "test device" l2.enable(libevdev.EV_REL.REL_X) # l2 is an unbound device with the REL_X bit set Note that if a device is constructed manually, the fd of the device is always None. .. note:: The device is always set to CLOCK_MONOTONIC. :param fd: fd pointing to a ``/dev/input/eventX`` event node :type fd: A file-like object """ class _EventValueSet: def __init__(self, parent_device): self._device = parent_device def __getitem__(self, code): # calling device.value[slot axis] is a bug on MT devices if (code.type == libevdev.EV_ABS and code >= libevdev.EV_ABS.ABS_MT_SLOT and self._device.num_slots is not None): raise InvalidArgumentException('Cannot fetch value for MT axes') return self._device._libevdev.event_value(code.type.value, code.value) class _InputAbsInfoSet: def __init__(self, parent_device): self._device = parent_device def __getitem__(self, code): assert code.type == libevdev.EV_ABS r = self._device._libevdev.absinfo(code.value) if r is None: return r return InputAbsInfo(r['minimum'], r['maximum'], r['fuzz'], r['flat'], r['resolution'], r['value']) def __setitem__(self, code, absinfo): assert code.type == libevdev.EV_ABS if not self._device.has(code): raise InvalidArgumentException('Device does not have event code') data = {} if absinfo.minimum is not None: data['minimum'] = absinfo.minimum if absinfo.maximum is not None: data['maximum'] = absinfo.maximum if absinfo.fuzz is not None: data['fuzz'] = absinfo.fuzz if absinfo.flat is not None: data['flat'] = absinfo.flat if absinfo.resolution is not None: data['resolution'] = absinfo.resolution if absinfo.value is not None: data['value'] = absinfo.value self._device._libevdev.absinfo(code.value, data) class _SlotValue: def __init__(self, device, slot): self._device = device self._slot = slot def __getitem__(self, code): if (code.type is not libevdev.EV_ABS or code <= libevdev.EV_ABS.ABS_MT_SLOT): raise InvalidArgumentException('Event code must be one of EV_ABS.ABS_MT_*') if not self._device.has(code): return None return self._device._libevdev.slot_value(self._slot, code.value) def __setitem__(self, code, value): if (code.type is not libevdev.EV_ABS or code <= libevdev.EV_ABS.ABS_MT_SLOT): raise InvalidArgumentException('Event code must be one of EV_ABS.ABS_MT_*') if not self._device.has(code): raise InvalidArgumentException('Event code does not exist') self._device._libevdev.slot_value(self._slot, code.value, new_value=value) def __init__(self, fd=None): self._libevdev = Libevdev(fd) self._uinput = None self._is_grabbed = False self._values = Device._EventValueSet(self) self._absinfos = Device._InputAbsInfoSet(self) if fd is not None: try: self._libevdev.set_clock_id(time.CLOCK_MONOTONIC) except AttributeError: self._libevdev.set_clock_id(1) @property def name(self): """ :returns: the device name """ return self._libevdev.name @name.setter def name(self, name): self._libevdev.name = name @property def phys(self): """ :returns: the device's kernel phys or None. """ return self._libevdev.phys @phys.setter def phys(self, phys): self._libevdev.phys = phys @property def uniq(self): """ :returns: the device's uniq string or None """ return self._libevdev.uniq @uniq.setter def uniq(self, uniq): self._libevdev.uniq = uniq @property def driver_version(self): """ :returns: the device's driver version """ return self._libevdev.driver_version @property def id(self): """ :returns: A dict with the keys 'bustype', 'vendor', 'product', 'version'. When used as a setter, only existing keys are applied to the device. For example, to update the product ID only:: ctx = Device() id["property"] = 1234 ctx.id = id """ return self._libevdev.id @id.setter def id(self, vals): self._libevdev.id = vals @property def fd(self): """ This fd represents the file descriptor to this device, if any. If no fd was provided in the constructor, None is returned. If the device was used to create a uinput device, None is returned. The fd may only be changed if it was not initially None and then it overwrites the file object provided in the constructor (or a previous call to this function). The new file object becomes the object referencing this device, further events are polled from that file. .. warning:: A device initialized without a file descriptor may not change its fd. Note that libevdev does not synchronize the device and relies on the caller to ensure that the new file object points to the same device as this context. If the underlying device changes, the behavior is undefined. :raises: InvalidFileError - the file is invalid or this device does not allow a file to be set """ return self._libevdev.fd @fd.setter def fd(self, fileobj): if self._libevdev.fd is None: raise InvalidFileError() self._libevdev.fd = fileobj try: self._libevdev.set_clock_id(time.CLOCK_MONOTONIC) except AttributeError: self._libevdev.set_clock_id(1) if self._is_grabbed: self.grab() @property def evbits(self): """ Returns a dict with all supported event types and event codes, in the form of:: { libevdev.EV_ABS: [libevdev.EV_ABS.ABS_X, ...], libevdev.EV_KEY: [libevdev.EV_KEY.BTN_LEFT, ...], } """ types = {} for t in libevdev.types: if not self.has(t): continue codes = [] for c in t.codes: if not self.has(c): continue codes.append(c) types[t] = codes return types @property def properties(self): """ Returns a list of all supported input properties """ return [p for p in libevdev.props if self.has_property(p)] def has_property(self, prop): """ :param prop: a property :returns: True if the device has the property, False otherwise """ return self._libevdev.has_property(prop.value) def has(self, evcode): """ :param evcode: the event type or event code :type evcode: EventType or EventCode :returns: True if the device has the type and/or code, False otherwise """ try: return self._libevdev.has_event(evcode.type.value, evcode.value) except AttributeError: return self._libevdev.has_event(evcode.value) @property def num_slots(self): """ :returns: the number of slots on this device or ``None`` if this device does not support slots :note: Read-only """ return self._libevdev.num_slots @property def current_slot(self): """ :returns: the current slot on this device or ``None`` if this device does not support slots :note: Read-only """ return self._libevdev.current_slot @property def absinfo(self): """ Query the device's absinfo for the given event code. This attribute can both query and modify the :class:`InputAbsInfo` values of this device:: >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X] >>> print(f'Resolution is {ai.resolution}') Resolution is 33 >>> ai = d.absinfo[libevdev.EV_ABS.ABS_Z] >>> print(ai) None The returned object is a dict-like object that only accepts event codes of type `EV_ABS` as keys. No other operation than key-based access is supported. When used as a setter, the provided :class:`InputAbsInfo` becomes the new absinfo of this axis:: >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X] >>> print(f'Resolution is {ai.resolution}') Resolution is 33 >>> ai.resolution = 45 >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X] >>> print(f'Resolution is now {ai.resolution}') Resolution is now 45 When used as a setter, any attribute of :class:`InputAbsInfo` that is ``None`` is ignored:: >>> ai = InputAbsInfo(resolution=72) >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai >>> ai = d.absinfo[libevdev.EV_ABS.ABS_X] >>> print(f'Resolution is now {ai.resolution}') Resolution is now 72 .. warning:: Setting the absinfo for a non-existing EV_ABS code is invalid. Use :func:`enable()` instead. :returns: an class:`InputAbsInfo` struct or None if the device does not have the event code :raises: :class:`InvalidArgumentException` when trying to set an axis that is not enabled. """ return self._absinfos def sync_absinfo_to_kernel(self, code): """ Synchronizes our view of an absinfo axis to the kernel, thus updating the the device for every other client. This function should be used with care. Not only does it change the kernel device and thus may affect the behavior of other processes but it is racy: any client that has this device node open already may never see the updates. To use this function, update the absinfo for the desired axis first:: >>> fd = open('/dev/input/event0', 'rb') >>> d = libevdev.Device(fd) >>> ai = InputAbsInfo(resolution=72) >>> d.absinfo[libevdev.EV_ABS.ABS_X] = ai >>> d.sync_absinfo_to_kernel(libevdev.EV_ABS.ABS_X) """ a = self.absinfo[code] data = {"minimum": a.minimum, "maximum": a.maximum, "fuzz": a.fuzz, "flat": a.flat, "resolution": a.resolution} self._libevdev.absinfo(code.value, new_values=data, kernel=True) def events(self): """ Returns an iterable with currently pending events. Event processing should look like this:: fd = open("/dev/input/event0", "rb") ctx = libevdev.Device(fd) while True: for e in ctx.events(): print(e): This function detects if the file descriptor is in blocking or non-blocking mode and adjusts its behavior accordingly. If the file descriptor is in nonblocking mode and no events are available, this function returns immediately. If the file descriptor is blocking, this function blocks if there are no events available. :returns: an iterable with the currently pending events """ if self._libevdev.fd is None: return [] if os.get_blocking(self._libevdev.fd.fileno()): flags = READ_FLAG_BLOCKING else: flags = READ_FLAG_NORMAL ev = self._libevdev.next_event(flags) while ev is not None: code = libevdev.evbit(ev.type, ev.code) yield InputEvent(code, ev.value, ev.sec, ev.usec) if code == libevdev.EV_SYN.SYN_DROPPED: raise EventsDroppedException() ev = self._libevdev.next_event(flags) def sync(self, force=False): """ Returns an iterator with events pending to re-sync the caller's view of the device with the one from libevdev. :param force: if set, the device forces an internal sync. This is required after changing the fd of the device when the device state may have changed while libevdev was not processing events. """ if self._libevdev.fd is None: return [] if force: flags = READ_FLAG_FORCE_SYNC else: flags = READ_FLAG_SYNC ev = self._libevdev.next_event(flags) while ev is not None: code = libevdev.evbit(ev.type, ev.code) yield InputEvent(code, ev.value, ev.sec, ev.usec) ev = self._libevdev.next_event(flags) @property def value(self): """ Returns the current value for a given event code or None where the event code does not exist on the device:: >>> d = libevdev.Device(fd) >>> print(d.value[libevdev.EV_ABS.ABS_X]) 1024 >>> print(d.value[libevdev.EV_ABS.ABS_Y]) 512 >>> print(d.value[libevdev.EV_ABS.ABS_Z]) None The returned object is a dict-like object that only accepts event codes as keys. No other operation than key-based access is supported. The default value for all codes is 0. State-less axes like the ``EV_REL`` range always return 0 for all supported event codes. """ return self._values @property def slots(self): """ Returns a tuple with the available slots, each of which contains a wrapper object to access a slot value:: >>> d = libevdev.Device(fd) >>> print(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X]) 1000 >>> print(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_Y]) 500 >>> print(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_X]) 200 >>> print(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_Y]) 300 Alternatively, the tuple can be iterated on:: xcode = libevdev.EV_ABS.ABS_MT_POSITION_X ycode = libevdev.EV_ABS.ABS_MT_POSITION_Y for s in d.slots: position = (s[xcode], s[ycode]) The only values available for each slot are the ones in the ``libevdev.EV_ABS.ABS_MT_*`` range (but not ``libevdev.EV_ABS.ABS_MT_SLOT``). """ if self.num_slots is None: raise InvalidArgumentException('Device has no slots') return tuple(Device._SlotValue(self, slot) for slot in range(self.num_slots)) def enable(self, event_code, data=None): """ Enable an event type or event code on this device, even if not supported by this device. If event_code is an :class:`EventType`, that type is enabled and data is ignored. If event_code is one of ``libevdev.EV_ABS.ABS_*``, then data must be a :class:`InputAbsInfo`. Any unset fields of the :class:`InputAbsInfo` are replaced with 0, i.e. the following example is valid and results in a fuzz/flat/resolution of zero:: ctx = libevdev.Device() abs = InputAbsInfo(minimum=0, maximum=100) ctx.enable(libevdev.EV_ABS.ABS_X, data) If event_code is one of ``libevdev.EV_REP.REP_``, then data must be an integer. If event_code is one of ``libevdev.INPUT_PROP_``, then the given input property is enabled. :param event_code: the event code :type event_code: EventCode or EventType :param data: if event_code is not ``None``, data points to the code-specific information. """ if isinstance(event_code, InputProperty): self._libevdev.enable_property(event_code.value) return try: if event_code.type == libevdev.EV_ABS: if data is None or not isinstance(data, InputAbsInfo): raise InvalidArgumentException('enabling EV_ABS codes requires an InputAbsInfo') data = {"minimum": data.minimum or 0, "maximum": data.maximum or 0, "fuzz": data.fuzz or 0, "flat": data.flat or 0, "resolution": data.resolution or 0} elif event_code.type == libevdev.EV_REP: if data is None: raise InvalidArgumentException('enabling EV_REP codes requires an integer') self._libevdev.enable(event_code.type.value, event_code.value, data) except AttributeError: self._libevdev.enable(event_code.value) def disable(self, event_code): """ Disable the given event type or event code on this device. If the device does not support this type or code, this function does nothing. Otherwise, all future events from this device that match this type or code will be discarded:: >>> d.disable(libevdev.EV_ABS) # All EV_ABS events are filtered now >>> d.disable(libevdev.EV_KEY.BTN_LEFT) # All BTN_LEFt events are filtered now To re-enable an event type or code, use :func:`enable()` :param event_code: the event type or code :type event_code: EventType or EventCode """ if isinstance(event_code, InputProperty): raise NotImplementedError() try: self._libevdev.disable(event_code.type.value, event_code.value) except AttributeError: self._libevdev.disable(event_code.value) @property def devnode(self): """ Returns the device node for this device. The device node is None if this device has not been created as uinput device. """ if not self._uinput: return None return self._uinput.devnode @property def syspath(self): """ Returns the syspath for this device. The syspath is None if this device has not been created as uinput device. """ if not self._uinput: return None return self._uinput.syspath def create_uinput_device(self, uinput_fd=None): """ Creates and returns a new :class:`Device` based on this libevdev device. The new device is equivalent to one created with ``libevdev.Device()``, i.e. it is one that does not have a file descriptor associated. To create a uinput device from an existing device:: fd = open('/dev/input/event0', 'rb') d = libevdev.Device(fd) d.name = 'duplicated device' d.create_uinput_device() # d is now a duplicate of the event0 device with a custom name fd.close() Or to create a new device from scratch:: d = libevdev.Device() d.name = 'test device' d.enable(libevdev.EV_KEY.BTN_LEFT) d.create_uinput_device() # d is now a device with a single button :param uinput_fd: A file descriptor to the /dev/input/uinput device. If None, the device is opened and closed automatically. :raises: OSError """ d = libevdev.Device() d.name = self.name d.id = self.id for t, cs in self.evbits.items(): for c in cs: if t == libevdev.EV_ABS: data = self.absinfo[c] elif t == libevdev.EV_REP: data = self.value[c] else: data = None d.enable(c, data) for p in self.properties: self.enable(p) d._uinput = UinputDevice(self._libevdev, uinput_fd) return d def send_events(self, events): """ Send the list of :class:`InputEvent` events through this device. All events must have a valid :class:`EventCode` and value, the timestamp in the event is ignored and the kernel fills in its own timestamp. This function may only be called on a uinput device, not on a normal device. .. warning:: an event list must always be terminated with a ``libevdev.EV_SYN.SYN_REPORT`` event or the kernel may delay processing. :param events: a list of :class:`InputEvent` events """ if not self._uinput: raise InvalidFileError() if None in [e.code for e in events]: raise InvalidArgumentException('All events must have an event code') if None in [e.value for e in events]: raise InvalidArgumentException('All events must have a value') for e in events: self._uinput.write_event(e.type.value, e.code.value, e.value) def grab(self): """ Exclusively grabs the device, preventing events from being seen by anyone else. This includes in-kernel consumers of the events (e.g. for rfkill) and should be used with care. A grab is valid until the file descriptor is closed or until :func:`ungrab` is called, whichever happens earlier. libevdev re-issues the grab on the device after changing the fd. If the original file descriptor is still open when changing the fd on the device, re-issuing the grab will fail silently:: fd1 = open("/dev/input/event0", "rb") d = libevdev.Device(fd1) d.grab() # device is now exclusively grabbed fd.close() fd2 = open("/dev/input/event0", "rb") d.fd = fd2 # device is now exclusively grabbed fd3 = open("/dev/input/event0", "rb") d.fd = fd3 # ERROR: fd2 is still open and the grab fails """ try: self._libevdev.grab() except OSError: raise DeviceGrabError() self._is_grabbed = True def ungrab(self): """ Removes an exclusive grabs on the device, see :func:`grab`. """ self._libevdev.grab(False) self._is_grabbed = False python-libevdev-0.5/libevdev/event.py000066400000000000000000000110151326746764000200050ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. from .const import EventType, EventCode class InputEvent(object): """ Represents one input event of type struct input_event as defined in ``linux/input.h`` and returned by ``libevdev_next_event()``. Comparison between events can be done via the :func:`matches()` function or by comparing two input events. Two events match when their most precise attribute match and all other attributes are None:: >>> e = InputEvent(libevdev.EV_REL.REL_X, value=1) >>> e == InputEvent(libevdev.EV_REL) True >>> e == InputEvent(libevdev.EV_ABS) True >>> e == InputEvent(libevdev.EV_REL.REL_X) True >>> e == InputEvent(libevdev.EV_REL.REL_Y) False >>> e == InputEvent(libevdev.EV_REL.REL_X, value=1) True >>> e == InputEvent(libevdev.EV_REL.REL_X, value=2) False .. attribute:: code The :class:`EventCode` or :class:`EventType` for this input event .. attribute:: value The (optional) value for the event's axis .. attribute:: sec The timestamp, seconds .. attribute:: usec The timestamp, microseconds """ def __init__(self, code, value=None, sec=0, usec=0): assert isinstance(code, EventCode) or isinstance(code, EventType) if isinstance(code, EventCode): self._type = code.type self._code = code else: self._type = code self._code = None self.sec = sec self.usec = usec self.value = value @property def code(self): """ :return: the EventCode for this event or None :rtype: EventCode """ return self._code @property def type(self): """ :return: the event type for this event :rtype: EventType """ return self._type def matches(self, code, value=None): """ :param code: the event type or code :type code: EventType or EventCode :param value: optional, the event value :return: True if the type matches this event's type and this event's code matches the given code (if any) and this event's value matches the given value (if any) Check if an event matches a given event type and/or code. The following invocations show how to match on an event type, an event code and an event code with a specific value:: if ev.matches(libevdev.EV_REL): pass if ev.matches(libevdev.EV_REL.REL_X): pass if ev.matches(libevdev.EV_REL.REL_X, 1): pass """ if value is not None and self.value is not None and self.value != value: return False if isinstance(code, EventType): return self._type == code else: return self._code == code def __eq__(self, other): if not isinstance(other, InputEvent): return False if self.code is None or other.code is None: return self.matches(other.type, other.value) return self.matches(other.code, other.value) def __repr__(self): tname = self.type.name cname = None if self.code is not None: cname = self.code.name return 'InputEvent({}, {}, {})'.format(tname, cname, self.value) python-libevdev-0.5/setup.cfg000066400000000000000000000000501326746764000163300ustar00rootroot00000000000000[metadata] description-file = README.md python-libevdev-0.5/setup.py000077500000000000000000000017351326746764000162370ustar00rootroot00000000000000#!/usr/bin/env python3 from distutils.core import setup long_description = ''' python-libevdev is a Python wrapper arround the libevdev C library. It provides a Pythonic API to read events from the Linux kernel's input device nodes and to read and/or modify the device's state and capabilities. The documentation is available here: https://python-evdev.readthedocs.io/en/latest/ ''' setup(name='libevdev', version='0.5', description='Python wrapper for libevdev', long_description=long_description, author='Peter Hutterer', author_email='peter.hutterer@who-t.net', url='https://www.github.com/whot/python-libevdev/', packages=['libevdev'], classifiers=[ 'Development Status :: 3 - Alpha', 'Topic :: Software Development', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 3', ], python_requires='>=3', ) python-libevdev-0.5/test/000077500000000000000000000000001326746764000154735ustar00rootroot00000000000000python-libevdev-0.5/test/test-clib.py000066400000000000000000000436251326746764000177450ustar00rootroot00000000000000import os import unittest import ctypes from libevdev._clib import Libevdev, UinputDevice # Note: these tests test for the correct functioning of the python bindings, # not of libevdev underneath. Some ranges are hardcoded for simplicity, e.g. # if properties 1-4 work the others will work too if libevdev works # correctly def is_root(): return os.getuid() == 0 class TestNameConversion(unittest.TestCase): def test_type_max(self): for t in ["REL", "ABS"]: c = Libevdev.event_to_value("EV_{}".format(t), "{}_MAX".format(t)) max = Libevdev.type_max("EV_{}".format(t)) self.assertEqual(c, max) def test_prop_name(self): name = Libevdev.property_to_name(0) self.assertEqual(name, "INPUT_PROP_POINTER") prevname = None for i in range(5): name = Libevdev.property_to_name(i) self.assertIsNotNone(name) self.assertTrue(name.startswith("INPUT_PROP_")) self.assertNotEqual(prevname, name) prevname = name def test_prop_to_name_invalid(self): name = Libevdev.property_to_name(-1) self.assertIsNone(name) name = Libevdev.property_to_name(100) self.assertIsNone(name) with self.assertRaises(ctypes.ArgumentError): name = Libevdev.property_to_name("foo") def test_type_to_name(self): name = Libevdev.event_to_name(1) self.assertEqual(name, "EV_KEY") prevname = None for i in range(5): name = Libevdev.event_to_name(i) self.assertIsNotNone(name) self.assertTrue(name.startswith("EV_")) self.assertNotEqual(prevname, name) prevname = name def test_type_to_name_invalid(self): name = Libevdev.event_to_name(-1) self.assertIsNone(name) name = Libevdev.event_to_name(100) self.assertIsNone(name) with self.assertRaises(ctypes.ArgumentError): name = Libevdev.event_to_name("foo") def test_code_to_name(self): name = Libevdev.event_to_name(0, 0) self.assertEqual(name, "SYN_REPORT") name = Libevdev.event_to_name(1, 1) self.assertEqual(name, "KEY_ESC") def test_code_to_name_invalid(self): name = Libevdev.event_to_name(0, 1000) self.assertIsNone(name) name = Libevdev.event_to_name(0, -1) self.assertIsNone(name) with self.assertRaises(ctypes.ArgumentError): name = Libevdev.event_to_name(0, "foo") def test_type_to_value(self): v = Libevdev.event_to_value("EV_REL") self.assertEqual(v, 2) def test_type_value_invalid(self): v = Libevdev.event_to_value("foo") self.assertIsNone(v) with self.assertRaises(AttributeError): v = Libevdev.event_to_value(0) def test_code_value(self): v = Libevdev.event_to_value("EV_REL", "REL_Y") self.assertEqual(v, 1) v = Libevdev.event_to_value(0, "SYN_DROPPED") self.assertEqual(v, 3) def test_code_value_invalid(self): v = Libevdev.event_to_value("EV_REL", "KEY_ESC") self.assertIsNone(v) class TestLibevdevDevice(unittest.TestCase): def test_ctx_init(self): l = Libevdev() del l def test_set_get_name(self): l = Libevdev() name = l.name self.assertEqual(name, '') l.name = "foo" name = l.name self.assertEqual(name, "foo") l.name = None name = l.name self.assertEqual(name, "") def test_set_get_uniq(self): l = Libevdev() uniq = l.uniq self.assertIsNone(uniq) l.uniq = "foo" uniq = l.uniq self.assertEqual(uniq, "foo") # libevdev issue: phys may be NULL (unlike the name) but we can't # set it to NULL. But the conversion code returns None for the empty # string, so let's test for that l.uniq = None uniq = l.uniq self.assertEqual(uniq, None) def test_set_get_phys(self): l = Libevdev() phys = l.phys self.assertIsNone(phys) l.phys = "foo" phys = l.phys self.assertEqual(phys, "foo") # libevdev issue: phys may be NULL (unlike the name) but we can't # set it to NULL. But the conversion code returns None for the empty # string, so let's test for that l.phys = None phys = l.phys self.assertEqual(phys, None) def test_get_driver_version(self): l = Libevdev() v = l.driver_version self.assertEqual(v, 0) # we can't set this, nothing else we can test def test_set_get_id(self): l = Libevdev() id = l.id self.assertEqual(id["bustype"], 0) self.assertEqual(id["vendor"], 0) self.assertEqual(id["product"], 0) self.assertEqual(id["version"], 0) id["bustype"] = 1 id["vendor"] = 2 id["product"] = 3 id["version"] = 4 l.id = id id = l.id self.assertEqual(id["bustype"], 1) self.assertEqual(id["vendor"], 2) self.assertEqual(id["product"], 3) self.assertEqual(id["version"], 4) del id["bustype"] del id["vendor"] del id["product"] id["version"] = 5 l.id = id id = l.id self.assertEqual(id["bustype"], 1) self.assertEqual(id["vendor"], 2) self.assertEqual(id["product"], 3) self.assertEqual(id["version"], 5) class TestRealDevice(unittest.TestCase): """ Tests various things against /dev/input/event3 which is usually the keyboard. Requires root rights though. """ def setUp(self): self.fd = open("/dev/input/event3", "rb") def tearDown(self): self.fd.close() @unittest.skipUnless(is_root(), 'Test requires root') def test_set_fd(self): l = Libevdev() l.fd = self.fd fd = l.fd self.assertEqual(self.fd, fd) fd2 = open("/dev/input/event3", "rb") l.fd = fd2 fd = l.fd self.assertEqual(fd, fd2) fd2.close() @unittest.skipUnless(is_root(), 'Test requires root') def test_init_fd(self): l = Libevdev(self.fd) fd = l.fd self.assertEqual(self.fd, fd) fd2 = open("/dev/input/event3", "rb") l.fd = fd2 fd = l.fd self.assertEqual(fd, fd2) fd2.close() @unittest.skipUnless(is_root(), 'Test requires root') def test_ids(self): l = Libevdev(self.fd) id = l.id self.assertNotEqual(id["bustype"], 0) self.assertNotEqual(id["vendor"], 0) self.assertNotEqual(id["product"], 0) self.assertNotEqual(id["version"], 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_name(self): l = Libevdev(self.fd) name = l.name self.assertNotEqual(name, "") @unittest.skipUnless(is_root(), 'Test requires root') def test_driver_version(self): l = Libevdev(self.fd) v = l.driver_version self.assertEqual(v, 0x010001) @unittest.skipUnless(is_root(), 'Test requires root') def test_set_clock_id(self): l = Libevdev(self.fd) try: import time clock = time.CLOCK_MONOTONIC except AttributeError: clock = 1 rc = l.set_clock_id(clock) self.assertEqual(rc, 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_grab(self): l = Libevdev(self.fd) # no exception == success l.grab() l.grab(False) l.grab(True) @unittest.skipUnless(is_root(), 'Test requires root') def test_has_event(self): l = Libevdev(self.fd) self.assertTrue(l.has_event("EV_SYN", "SYN_REPORT")) type_supported = -1 for i in range(1, 5): if l.has_event(i): type_supported = i break self.assertGreater(type_supported, 0) codes_supported = 0 for i in range(150): if l.has_event(type_supported, i): codes_supported += 1 self.assertGreater(codes_supported, 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_has_property(self): """ Let's assume at least one between event0 and event10 is a device with at least one property set. May cause false negatives. """ props_supported = 0 for i in range(10): try: with open("/dev/input/event{}".format(i), "rb") as fd: l = Libevdev(fd) for p in range(6): if l.has_property(p): props_supported += 1 except IOError: # Not all eventX nodes are guaranteed to exist pass self.assertGreater(props_supported, 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_num_slots(self): """ Let's assume that our device doesn't have slots """ l = Libevdev(self.fd) self.assertIsNone(l.num_slots) class TestAbsDevice(unittest.TestCase): """ Tests various things against the first device with EV_ABS. We're relying on that this device has ABS_Y, this tests against a code that's nonzero and is the most common ABS anyway. Requires root rights. """ def setUp(self): want_fd = None for i in range(20): try: fd = open("/dev/input/event{}".format(i), "rb") l = Libevdev(fd) if l.has_event("EV_ABS", "ABS_Y"): want_fd = fd break fd.close() except IOError: # Not all eventX nodes are guaranteed to exist pass self.assertIsNotNone(want_fd) self.fd = want_fd def tearDown(self): self.fd.close() @unittest.skipUnless(is_root(), 'Test requires root') def test_absinfo(self): l = Libevdev(self.fd) a = l.absinfo("ABS_Y") self.assertTrue("minimum" in a) self.assertTrue("maximum" in a) self.assertTrue("resolution" in a) self.assertTrue("fuzz" in a) self.assertTrue("flat" in a) self.assertTrue("value" in a) @unittest.skipUnless(is_root(), 'Test requires root') def test_set_absinfo(self): l = Libevdev(self.fd) real_a = l.absinfo("ABS_Y") a = l.absinfo("ABS_Y") a["minimum"] = 100 a["maximum"] = 200 a["fuzz"] = 300 a["flat"] = 400 a["resolution"] = 500 a["value"] = 600 a = l.absinfo("ABS_Y", new_values=a) self.assertEqual(a["minimum"], 100) self.assertEqual(a["maximum"], 200) self.assertEqual(a["fuzz"], 300) self.assertEqual(a["flat"], 400) self.assertEqual(a["resolution"], 500) self.assertEqual(a["value"], 600) l2 = Libevdev(self.fd) a2 = l2.absinfo("ABS_Y") self.assertNotEqual(a["minimum"], real_a["minimum"]) self.assertNotEqual(a["maximum"], real_a["maximum"]) self.assertNotEqual(a["fuzz"], real_a["fuzz"]) self.assertNotEqual(a["flat"], real_a["flat"]) self.assertNotEqual(a["resolution"], real_a["resolution"]) self.assertEqual(a2["value"], real_a["value"]) self.assertEqual(a2["minimum"], real_a["minimum"]) self.assertEqual(a2["maximum"], real_a["maximum"]) self.assertEqual(a2["fuzz"], real_a["fuzz"]) self.assertEqual(a2["flat"], real_a["flat"]) self.assertEqual(a2["resolution"], real_a["resolution"]) self.assertEqual(a2["value"], real_a["value"]) @unittest.skipUnless(is_root(), 'Test requires root') def test_set_absinfo_invalid(self): l = Libevdev(self.fd) with self.assertRaises(ValueError): l.absinfo("REL_X") @unittest.skipUnless(is_root(), 'Test requires root') def test_set_absinfo_kernel(self): # FIXME: yeah, nah, not testing that on a random device... pass @unittest.skipUnless(is_root(), 'Test requires root') def test_get_set_event_value(self): l = Libevdev(self.fd) v = l.event_value("EV_ABS", "ABS_Y") self.assertIsNotNone(v) v = l.event_value(0x03, 0x01, new_value=300) self.assertEqual(v, 300) v = l.event_value(0x03, 0x01) self.assertEqual(v, 300) @unittest.skipUnless(is_root(), 'Test requires root') def test_get_set_event_value_invalid(self): l = Libevdev(self.fd) v = l.event_value("EV_ABS", 0x600) self.assertIsNone(v) v = l.event_value(0x03, 0x600, new_value=300) self.assertIsNone(v) @unittest.skipUnless(is_root(), 'Test requires root') def test_enable_event_code(self): l = Libevdev(self.fd) self.assertFalse(l.has_event("EV_REL", "REL_RY")) l.enable("EV_REL", "REL_RY") self.assertTrue(l.has_event("EV_REL", "REL_RY")) l.disable("EV_REL", "REL_RY") self.assertFalse(l.has_event("EV_REL", "REL_RY")) data = {"minimum": 100, "maximum": 200, "value": 300, "fuzz": 400, "flat": 500, "resolution": 600} self.assertFalse(l.has_event("EV_ABS", "ABS_RY")) l.enable("EV_ABS", "ABS_RY", data) self.assertTrue(l.has_event("EV_ABS", "ABS_RY")) l.disable("EV_ABS", "ABS_RY") self.assertFalse(l.has_event("EV_ABS", "ABS_RY")) @unittest.skipUnless(is_root(), 'Test requires root') def test_enable_property(self): l = Libevdev(self.fd) self.assertFalse(l.has_property("INPUT_PROP_ACCELEROMETER")) l.enable_property("INPUT_PROP_ACCELEROMETER") self.assertTrue(l.has_property("INPUT_PROP_ACCELEROMETER")) class TestMTDevice(unittest.TestCase): """ Tests various things against the first MT device found. Requires root rights. """ def setUp(self): want_fd = None for i in range(20): try: fd = open("/dev/input/event{}".format(i), "rb") l = Libevdev(fd) if l.num_slots is not None: want_fd = fd break fd.close() except IOError: # Not all eventX nodes are guaranteed to exist pass self.assertIsNotNone(want_fd) self.fd = want_fd def tearDown(self): self.fd.close() @unittest.skipUnless(is_root(), 'Test requires root') def test_num_slots(self): l = Libevdev(self.fd) self.assertGreater(l.num_slots, 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_current_slot(self): l = Libevdev(self.fd) self.assertGreaterEqual(l.current_slot, 0) @unittest.skipUnless(is_root(), 'Test requires root') def test_slot_value(self): l = Libevdev(self.fd) a = l.absinfo("ABS_MT_POSITION_X") v = l.slot_value(l.current_slot, "ABS_MT_POSITION_X") self.assertLessEqual(a["minimum"], v) self.assertGreaterEqual(a["maximum"], v) @unittest.skipUnless(is_root(), 'Test requires root') def test_set_slot_value(self): l = Libevdev(self.fd) v = l.slot_value(l.current_slot, "ABS_MT_POSITION_X") v += 10 v2 = l.slot_value(l.current_slot, "ABS_MT_POSITION_X", v) self.assertEqual(v, v2) v2 = l.slot_value(l.current_slot, "ABS_MT_POSITION_X") self.assertEqual(v, v2) class TestUinput(unittest.TestCase): """ Tests uinput device creation. Requires root rights. """ def is_identical(self, d1, d2): for t in range(Libevdev.event_to_value("EV_MAX")): max = Libevdev.type_max(t) if max is None: continue for c in range(max): if d1.has_event(t, c) != d1.has_event(t, c): return False return True @unittest.skipUnless(is_root(), 'Test requires root') def testRelative(self): dev = Libevdev() dev.name = "test device" dev.enable("EV_REL", "REL_X") dev.enable("EV_REL", "REL_Y") uinput = UinputDevice(dev) self.assertIsNotNone(uinput.devnode) with open(uinput.devnode) as f: newdev = Libevdev(f) self.assertTrue(self.is_identical(dev, newdev)) @unittest.skipUnless(is_root(), 'Test requires root') def testButton(self): dev = Libevdev() dev.name = "test device" dev.enable("EV_KEY", "BTN_LEFT") dev.enable("EV_KEY", "KEY_A") uinput = UinputDevice(dev) self.assertIsNotNone(uinput.devnode) with open(uinput.devnode) as f: newdev = Libevdev(f) self.assertTrue(self.is_identical(dev, newdev)) @unittest.skipUnless(is_root(), 'Test requires root') def testAbsolute(self): absinfo = {"minimum": 0, "maximum": 1} dev = Libevdev() dev.name = "test device" dev.enable("EV_ABS", "ABS_X", absinfo) dev.enable("EV_ABS", "ABS_Y", absinfo) uinput = UinputDevice(dev) self.assertIsNotNone(uinput.devnode) with open(uinput.devnode) as f: newdev = Libevdev(f) self.assertTrue(self.is_identical(dev, newdev)) @unittest.skipUnless(is_root(), 'Test requires root') def testDeviceNode(self): dev = Libevdev() dev.name = "test device" dev.enable("EV_REL", "REL_X") dev.enable("EV_REL", "REL_Y") uinput = UinputDevice(dev) self.assertTrue(uinput.devnode.startswith("/dev/input/event")) @unittest.skipUnless(is_root(), 'Test requires root') def testSyspath(self): dev = Libevdev() dev.name = "test device" dev.enable("EV_REL", "REL_X") dev.enable("EV_REL", "REL_Y") uinput = UinputDevice(dev) self.assertTrue(uinput.syspath.startswith("/sys/devices/virtual/input/input")) if __name__ == '__main__': unittest.main() python-libevdev-0.5/test/test-const.py000066400000000000000000000101401326746764000201440ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. import unittest import libevdev from libevdev import evbit, propbit class TestEventBits(unittest.TestCase): def test_ev_types(self): self.assertIn(libevdev.EV_SYN, libevdev.types) self.assertIn(libevdev.EV_REL, libevdev.types) self.assertIn(libevdev.EV_ABS, libevdev.types) self.assertEqual(len(libevdev.types), 13) def test_EV_REL(self): self.assertIn(libevdev.EV_REL.REL_X, libevdev.EV_REL.codes) self.assertIn(libevdev.EV_REL.REL_Y, libevdev.EV_REL.codes) self.assertNotIn(libevdev.EV_ABS.ABS_X, libevdev.EV_REL.codes) def test_type_max(self): self.assertEqual(libevdev.EV_REL.max, libevdev.EV_REL.REL_MAX.value) self.assertEqual(libevdev.EV_ABS.max, libevdev.EV_ABS.ABS_MAX.value) self.assertEqual(libevdev.EV_KEY.max, libevdev.EV_KEY.KEY_MAX.value) self.assertEqual(libevdev.EV_REL.max, 0x0f) self.assertEqual(libevdev.EV_ABS.max, 0x3f) self.assertEqual(libevdev.EV_KEY.max, 0x2ff) def test_evcode_compare(self): self.assertNotEqual(libevdev.EV_REL.REL_X, libevdev.EV_REL.REL_Y) self.assertNotEqual(libevdev.EV_REL.REL_X, libevdev.EV_ABS.ABS_X) self.assertNotEqual(libevdev.EV_REL, libevdev.EV_ABS) self.assertNotEqual(libevdev.EV_REL.REL_X, libevdev.EV_REL) self.assertNotEqual(libevdev.EV_ABS.ABS_X, libevdev.EV_ABS) def test_evbit(self): self.assertEqual(evbit(0, 0), libevdev.EV_SYN.SYN_REPORT) self.assertEqual(evbit(1, 30), libevdev.EV_KEY.KEY_A) self.assertEqual(evbit(2, 1), libevdev.EV_REL.REL_Y) self.assertEqual(evbit(0), libevdev.EV_SYN) self.assertEqual(evbit(1), libevdev.EV_KEY) self.assertEqual(evbit(2), libevdev.EV_REL) for t in libevdev.types: self.assertEqual(evbit(t.value), t) def test_propbit(self): self.assertEqual(propbit(0), libevdev.INPUT_PROP_POINTER) self.assertEqual(propbit(1), libevdev.INPUT_PROP_DIRECT) for p in libevdev.props: self.assertEqual(propbit(p.value), p) def test_evbit_string(self): self.assertEqual(evbit('EV_SYN'), libevdev.EV_SYN) self.assertEqual(evbit('EV_KEY'), libevdev.EV_KEY) self.assertEqual(evbit('EV_REL'), libevdev.EV_REL) self.assertEqual(evbit('EV_REP'), libevdev.EV_REP) for t in libevdev.types: self.assertEqual(evbit(t.name), t) def test_evcode_string(self): self.assertEqual(evbit('ABS_X'), libevdev.EV_ABS.ABS_X) self.assertEqual(evbit('REL_X'), libevdev.EV_REL.REL_X) self.assertEqual(evbit('SYN_REPORT'), libevdev.EV_SYN.SYN_REPORT) self.assertEqual(evbit('REP_PERIOD'), libevdev.EV_REP.REP_PERIOD) def test_propbit_string(self): self.assertEqual(propbit('INPUT_PROP_POINTER'), libevdev.INPUT_PROP_POINTER) self.assertEqual(propbit('INPUT_PROP_DIRECT'), libevdev.INPUT_PROP_DIRECT) for p in libevdev.props: self.assertEqual(propbit(p.value), p) python-libevdev-0.5/test/test-device.py000066400000000000000000000411521326746764000202640ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. import os import unittest import libevdev from libevdev import evbit, propbit, InputEvent, Device, InvalidFileError, InvalidArgumentException def is_root(): return os.getuid() == 0 class TestDevice(unittest.TestCase): def test_device_empty(self): d = libevdev.Device() id = {'bustype': 0, 'vendor': 0, 'product': 0, 'version': 0} syns = { libevdev.EV_SYN : libevdev.EV_SYN.codes } self.assertEqual(d.name, '') self.assertEqual(d.id, id) self.assertIsNone(d.fd) self.assertIsNone(d.phys) self.assertIsNone(d.uniq) self.assertEqual(d.driver_version, 0) self.assertIsNone(d.syspath) self.assertIsNone(d.devnode) self.assertEqual(d.evbits, syns) self.assertEqual(d.properties, []) for t in libevdev.types: if t == libevdev.EV_SYN: continue self.assertFalse(d.has(t)) for c in t.codes: self.assertFalse(d.has(c)) self.assertIsNone(d.value[c]) d.disable(c) # noop d.disable(t) # noop for p in libevdev.props: self.assertFalse(d.has_property(p)) self.assertIsNone(d.num_slots) self.assertIsNone(d.current_slot) for c in libevdev.EV_ABS.codes: self.assertIsNone(d.absinfo[c]) self.assertEqual([e for e in d.events()], []) self.assertEqual([e for e in d.sync()], []) with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X] def test_device_name(self): d = libevdev.Device() d.name = 'test device' self.assertEqual(d.name, 'test device') def test_device_id(self): d = libevdev.Device() id = {'bustype': 1, 'vendor': 2, 'product': 3, 'version': 4} d.id = id self.assertEqual(d.id, id) d.id = {'vendor': 3, 'product': 4, 'version': 5} id = {'bustype': 1, 'vendor': 3, 'product': 4, 'version': 5} self.assertEqual(d.id, id) d.id = {'bustype': 8, 'product': 5, 'version': 6} id = {'bustype': 8, 'vendor': 3, 'product': 5, 'version': 6} self.assertEqual(d.id, id) d.id = {'bustype': 8, 'vendor': 9, 'version': 10} id = {'bustype': 8, 'vendor': 9, 'product': 5, 'version': 10} self.assertEqual(d.id, id) d.id = {'bustype': 8, 'vendor': 9, 'product': 12} id = {'bustype': 8, 'vendor': 9, 'product': 12, 'version': 10} self.assertEqual(d.id, id) def test_device_phys(self): d = libevdev.Device() d.phys = 'foo' self.assertEqual(d.phys, 'foo') d.phys = None self.assertIsNone(d.phys) def test_device_uniq(self): d = libevdev.Device() d.uniq = 'bar' self.assertEqual(d.uniq, 'bar') d.uniq = None self.assertIsNone(d.uniq) def test_driver_version(self): d = libevdev.Device() # read-only with self.assertRaises(AttributeError): d.driver_version = 1 def test_garbage_fd(self): with self.assertRaises(InvalidFileError): libevdev.Device(fd=1) with self.assertRaises(InvalidFileError): d = libevdev.Device() d.fd = 2 @unittest.skipUnless(is_root(), 'Test requires root') def test_fd_on_init(self): fd = open('/dev/input/event0', 'rb') d = libevdev.Device(fd) self.assertEqual(d.fd, fd) @unittest.skipUnless(is_root(), 'Test requires root') def test_fd_too_late(self): fd = open('/dev/input/event0', 'rb') d = libevdev.Device() with self.assertRaises(InvalidFileError): d.fd = fd @unittest.skipUnless(is_root(), 'Test requires root') def test_fd_change(self): fd1 = open('/dev/input/event0', 'rb') fd2 = open('/dev/input/event1', 'rb') d = libevdev.Device(fd1) self.assertEqual(d.fd, fd1) d.fd = fd2 self.assertEqual(d.fd, fd2) @unittest.skipUnless(is_root(), 'Test requires root') def test_has_bits(self): fd = open('/dev/input/event0', 'rb') d = libevdev.Device(fd) bits = d.evbits # assume at least 2 event types self.assertGreater(len(bits.keys()), 1) for t, cs in bits.items(): if t == libevdev.EV_SYN: continue # assume at least one code self.assertGreater(len(cs), 0) def test_set_bits(self): d = libevdev.Device() # read-only with self.assertRaises(AttributeError): d.evbits = {} def test_bits_change_after_enable(self): d = libevdev.Device() bits = d.evbits self.assertIn(libevdev.EV_SYN, bits) self.assertNotIn(libevdev.EV_REL, bits) d.enable(libevdev.EV_REL.REL_X) d.enable(libevdev.EV_REL.REL_Y) bits = d.evbits self.assertIn(libevdev.EV_SYN, bits) self.assertIn(libevdev.EV_REL, bits) self.assertNotIn(libevdev.EV_ABS, bits) self.assertNotIn(libevdev.EV_KEY, bits) self.assertIn(libevdev.EV_REL.REL_X, bits[libevdev.EV_REL]) self.assertIn(libevdev.EV_REL.REL_Y, bits[libevdev.EV_REL]) def test_bits_change_after_disable(self): d = libevdev.Device() d.enable(libevdev.EV_REL.REL_X) d.enable(libevdev.EV_REL.REL_Y) d.enable(libevdev.EV_KEY.KEY_A) d.enable(libevdev.EV_KEY.KEY_B) bits = d.evbits self.assertIn(libevdev.EV_SYN, bits) self.assertIn(libevdev.EV_REL, bits) self.assertIn(libevdev.EV_KEY, bits) self.assertNotIn(libevdev.EV_ABS, bits) self.assertIn(libevdev.EV_REL.REL_X, bits[libevdev.EV_REL]) self.assertIn(libevdev.EV_REL.REL_Y, bits[libevdev.EV_REL]) self.assertIn(libevdev.EV_KEY.KEY_A, bits[libevdev.EV_KEY]) self.assertIn(libevdev.EV_KEY.KEY_B, bits[libevdev.EV_KEY]) d.disable(libevdev.EV_REL.REL_Y) d.disable(libevdev.EV_KEY) bits = d.evbits self.assertNotIn(libevdev.EV_KEY, bits) self.assertIn(libevdev.EV_REL, bits) self.assertIn(libevdev.EV_REL.REL_X, bits[libevdev.EV_REL]) self.assertNotIn(libevdev.EV_REL.REL_Y, bits[libevdev.EV_REL]) def test_properties(self): d = libevdev.Device() self.assertEqual(d.properties, []) for p in libevdev.props: self.assertFalse(d.has_property(p)) props = sorted([libevdev.INPUT_PROP_BUTTONPAD, libevdev.INPUT_PROP_DIRECT]) for p in props: d.enable(p) self.assertEqual(d.properties, props) for p in libevdev.props: if not p in props: self.assertFalse(d.has_property(p)) else: self.assertTrue(d.has_property(p)) with self.assertRaises(NotImplementedError): d.disable(libevdev.INPUT_PROP_BUTTONPAD) def test_has(self): d = libevdev.Device() d.enable(libevdev.EV_REL.REL_X) d.enable(libevdev.EV_REL.REL_Y) d.enable(libevdev.EV_KEY.KEY_A) d.enable(libevdev.EV_KEY.KEY_B) self.assertTrue(d.has(libevdev.EV_REL)) self.assertTrue(d.has(libevdev.EV_REL.REL_X)) self.assertTrue(d.has(libevdev.EV_REL.REL_Y)) self.assertFalse(d.has(libevdev.EV_REL.REL_Z)) self.assertTrue(d.has(libevdev.EV_KEY)) self.assertTrue(d.has(libevdev.EV_KEY.KEY_A)) self.assertTrue(d.has(libevdev.EV_KEY.KEY_B)) self.assertFalse(d.has(libevdev.EV_KEY.KEY_C)) self.assertFalse(d.has(libevdev.EV_ABS)) def test_enable_abs(self): d = libevdev.Device() with self.assertRaises(InvalidArgumentException): d.enable(libevdev.EV_ABS.ABS_X) def test_value(self): d = libevdev.Device() d.enable(libevdev.EV_REL.REL_X) self.assertEqual(d.value[libevdev.EV_REL.REL_X], 0) self.assertIsNone(d.value[libevdev.EV_REL.REL_Y]) @unittest.skipUnless(is_root(), 'Test requires root') def test_mt_value(self): # Unable to set ABS_MT_SLOT on a libevdev device, see # https://bugs.freedesktop.org/show_bug.cgi?id=104270 d = libevdev.Device() a = libevdev.InputAbsInfo(minimum=0, maximum=100) d.name = 'test device' d.enable(libevdev.EV_ABS.ABS_X, a) d.enable(libevdev.EV_ABS.ABS_Y, a) d.enable(libevdev.EV_ABS.ABS_MT_SLOT, a) d.enable(libevdev.EV_ABS.ABS_MT_POSITION_X, a) d.enable(libevdev.EV_ABS.ABS_MT_POSITION_Y, a) d.enable(libevdev.EV_ABS.ABS_MT_TRACKING_ID, a) uinput = d.create_uinput_device() fd = open(uinput.devnode, 'rb') d = libevdev.Device(fd) self.assertEqual(d.num_slots, 101) self.assertEqual(d.value[libevdev.EV_ABS.ABS_X], 0) self.assertEqual(d.value[libevdev.EV_ABS.ABS_Y], 0) with self.assertRaises(libevdev.InvalidArgumentException): d.value[libevdev.EV_ABS.ABS_MT_POSITION_X] with self.assertRaises(libevdev.InvalidArgumentException): d.value[libevdev.EV_ABS.ABS_MT_POSITION_Y] with self.assertRaises(libevdev.InvalidArgumentException): d.value[libevdev.EV_ABS.ABS_MT_SLOT] with self.assertRaises(libevdev.InvalidArgumentException): d.value[libevdev.EV_ABS.ABS_MT_TRACKING_ID] # also raises for non-existing axes with self.assertRaises(libevdev.InvalidArgumentException): d.value[libevdev.EV_ABS.ABS_MT_ORIENTATION] @unittest.skipUnless(is_root(), 'Test requires root') def test_slot_value(self): # Unable to set ABS_MT_SLOT on a libevdev device, see # https://bugs.freedesktop.org/show_bug.cgi?id=104270 d = libevdev.Device() a = libevdev.InputAbsInfo(minimum=0, maximum=100) d.name = 'test device' d.enable(libevdev.EV_ABS.ABS_X, a) d.enable(libevdev.EV_ABS.ABS_Y, a) d.enable(libevdev.EV_ABS.ABS_MT_SLOT, a) d.enable(libevdev.EV_ABS.ABS_MT_POSITION_X, a) d.enable(libevdev.EV_ABS.ABS_MT_POSITION_Y, a) d.enable(libevdev.EV_ABS.ABS_MT_TRACKING_ID, a) uinput = d.create_uinput_device() events = [libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_SLOT, 0), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_TRACKING_ID, 1), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_POSITION_X, 100), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_POSITION_Y, 110), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_SLOT, 1), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_TRACKING_ID, 2), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_POSITION_X, 200), libevdev.InputEvent(libevdev.EV_ABS.ABS_MT_POSITION_Y, 210), libevdev.InputEvent(libevdev.EV_SYN.SYN_REPORT, 0)] uinput.send_events(events) fd = open(uinput.devnode, 'rb') d = libevdev.Device(fd) self.assertEqual(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X], 100) self.assertEqual(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_X], 200) self.assertEqual(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_Y], 110) self.assertEqual(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_Y], 210) self.assertIsNone(d.slots[0][libevdev.EV_ABS.ABS_MT_ORIENTATION]) for idx, s in enumerate(d.slots[:2]): idx += 1 self.assertEqual(s[libevdev.EV_ABS.ABS_MT_POSITION_X], idx * 100) self.assertEqual(s[libevdev.EV_ABS.ABS_MT_POSITION_Y], idx * 100 + 10) for s in d.slots[2:]: self.assertEqual(s[libevdev.EV_ABS.ABS_MT_POSITION_X], 0) self.assertEqual(s[libevdev.EV_ABS.ABS_MT_POSITION_Y], 0) with self.assertRaises(IndexError): d.slots[200] with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_X] with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_MT_SLOT] with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_REL.REL_X] with self.assertRaises(AttributeError): d.slots[0][libevdev.EV_ABS] d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X] = 10 self.assertEqual(d.slots[0][libevdev.EV_ABS.ABS_MT_POSITION_X], 10) d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_Y] = 50 self.assertEqual(d.slots[1][libevdev.EV_ABS.ABS_MT_POSITION_Y], 50) with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_MT_ORIENTATION] = 50 with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_X] = 10 with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_ABS.ABS_MT_SLOT] = 10 with self.assertRaises(libevdev.InvalidArgumentException): d.slots[0][libevdev.EV_REL.REL_X] = 10 with self.assertRaises(AttributeError): d.slots[0][libevdev.EV_ABS] = 10 def test_absinfo(self): d = libevdev.Device() a = libevdev.InputAbsInfo(minimum=100, maximum=1000, resolution=50) d.enable(libevdev.EV_ABS.ABS_X, a) # we expect these to be filled in a.fuzz = 0 a.flat = 0 a.value = 0 a2 = d.absinfo[libevdev.EV_ABS.ABS_X] self.assertEqual(a, a2) self.assertIsNone(d.absinfo[libevdev.EV_ABS.ABS_Y]) a.fuzz = 10 d.absinfo[libevdev.EV_ABS.ABS_X] = a a2 = d.absinfo[libevdev.EV_ABS.ABS_X] self.assertEqual(a, a2) a = libevdev.InputAbsInfo(minimum=500) d.absinfo[libevdev.EV_ABS.ABS_X] = a a2 = d.absinfo[libevdev.EV_ABS.ABS_X] self.assertEqual(a.minimum, a2.minimum) self.assertIsNotNone(a2.minimum) self.assertIsNotNone(a2.maximum) self.assertIsNotNone(a2.fuzz) self.assertIsNotNone(a2.flat) self.assertIsNotNone(a2.resolution) self.assertIsNotNone(a2.value) def test_absinfo_set_invalid(self): a = libevdev.InputAbsInfo(minimum=500) d = libevdev.Device() with self.assertRaises(InvalidArgumentException): d.absinfo[libevdev.EV_ABS.ABS_Y] = a with self.assertRaises(AssertionError): d.absinfo[libevdev.EV_REL.REL_X] with self.assertRaises(AssertionError): d.absinfo[libevdev.EV_REL.REL_X] = a @unittest.skipUnless(is_root(), 'Test requires root') def test_absinfo_sync_kernel(self): d = libevdev.Device() d.name = 'sync test device' a = libevdev.InputAbsInfo(minimum=0, maximum=1000, resolution=50, fuzz=0, flat=0, value=0) d.enable(libevdev.EV_ABS.ABS_X, a) d.enable(libevdev.EV_ABS.ABS_Y, a) uinput = d.create_uinput_device() fd = open(uinput.devnode, 'rb') d = libevdev.Device(fd) a2 = d.absinfo[libevdev.EV_ABS.ABS_X] self.assertEquals(a, a2) a2.resolution = 100 d.absinfo[libevdev.EV_ABS.ABS_X] = a2 d.sync_absinfo_to_kernel(libevdev.EV_ABS.ABS_X) fd.close() fd = open(uinput.devnode, 'rb') d = libevdev.Device(fd) a3 = d.absinfo[libevdev.EV_ABS.ABS_X] print(a3) self.assertEquals(a2, a3) a3 = d.absinfo[libevdev.EV_ABS.ABS_Y] self.assertEquals(a, a3) @unittest.skipUnless(is_root(), 'Test requires root') def test_uinput_empty(self): d = libevdev.Device() with self.assertRaises(OSError): d.create_uinput_device() python-libevdev-0.5/test/test-events.py000066400000000000000000000043401326746764000203270ustar00rootroot00000000000000# -*- coding: latin-1 -*- # Copyright © 2017 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. import unittest import libevdev from libevdev import evbit, propbit, InputEvent class TestEvents(unittest.TestCase): def test_event_matches_type(self): ev = InputEvent(libevdev.EV_REL) self.assertTrue(ev.matches(libevdev.EV_REL)) self.assertFalse(ev.matches(libevdev.EV_REL.REL_X)) self.assertFalse(ev.matches(libevdev.EV_ABS)) self.assertFalse(ev.matches(libevdev.EV_ABS.ABS_X)) def test_event_matches_code(self): ev = InputEvent(libevdev.EV_REL.REL_X) self.assertTrue(ev.matches(libevdev.EV_REL.REL_X)) self.assertTrue(ev.matches(libevdev.EV_REL)) self.assertFalse(ev.matches(libevdev.EV_ABS)) self.assertFalse(ev.matches(libevdev.EV_ABS.ABS_X)) def test_event_matches_self(self): e1 = InputEvent(libevdev.EV_REL.REL_X) e2 = InputEvent(libevdev.EV_REL) self.assertEqual(e1, e1) self.assertEqual(e2, e2) self.assertEqual(e2, e1) self.assertEqual(e1, e2) e2 = InputEvent(libevdev.EV_REL.REL_Y) self.assertNotEqual(e2, e1) self.assertNotEqual(e1, e2)