Created
February 28, 2015 17:26
-
-
Save pabzdzdzwiagief/c243be5a2eaf0a71ce39 to your computer and use it in GitHub Desktop.
Example of using /dev/input/event* (piped to stdin) for handling keyboard shortcuts.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python3 | |
| from json import load | |
| from os import read | |
| from struct import Struct | |
| from subprocess import call | |
| from sys import argv, stdin | |
| from time import sleep | |
| def main(config_file): | |
| struct = Struct('llHHI') | |
| with open(config_file, 'r') as config_file: | |
| config = load(config_file) | |
| with stdin as input: | |
| events, per_round, latest_event_time, pressed = '', 2 ** 10 , 0, set() | |
| while events or latest_event_time == 0: | |
| sleep(3) | |
| events = read(input.fileno(), struct.size * per_round) | |
| if len(events) == struct.size * per_round and per_round < 2 ** 20: | |
| per_round *= 2 | |
| for event in partitions(events, struct.size): | |
| tv_sec, _, type, code, value = struct.unpack(event) | |
| if latest_event_time + 3 < tv_sec: | |
| pressed = set() | |
| latest_event_time = tv_sec | |
| previous = pressed.copy() | |
| if type == 1 and value != 0: | |
| pressed.add(code) | |
| elif type == 1 and value == 0: | |
| pressed.discard(code) | |
| key_sequence = ' + '.join(map(str, sorted(pressed))) | |
| if previous != pressed and key_sequence in config: | |
| call(config.get(key_sequence)) | |
| def partitions(list, chunk_size): | |
| assert len(list) % chunk_size == 0, "Equal partitons" | |
| return (list[i:i + chunk_size] for i in range(0, len(list), chunk_size)) | |
| if __name__ == '__main__': | |
| assert len(argv) > 1, "Usage:\t%s <configuration file>" % argv[0] | |
| main(argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment