Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import asyncio
  4. import evdev
  5. import evdev.ecodes as e
  6. import os
  7. import re
  8. import sys
  9. from subprocess import run, check_output
  10.  
  11. source_devices = sys.argv[1:]
  12.  
  13. # Listen to events from the following device.
  14. real_devices = [
  15.     evdev.InputDevice(device)
  16.     for device in source_devices
  17. ]
  18.  
  19. # Then create our own device for our own events.
  20. host_devices = [
  21.     evdev.UInput.from_device(device)
  22.     for device in real_devices
  23. ]
  24. guest_devices = [
  25.     evdev.UInput.from_device(device)
  26.     for device in real_devices
  27. ]
  28. host_device_paths = [
  29.     os.path.join("/dev/input/by-id", "host-%s" % os.path.basename(path))
  30.     for path in source_devices
  31. ]
  32. guest_device_paths = [
  33.     os.path.join("/dev/input/by-id", "guest-%s" % os.path.basename(path))
  34.     for path in source_devices
  35. ]
  36.  
  37. virtual_devices = host_devices + guest_devices
  38. virtual_device_paths = host_device_paths + guest_device_paths
  39.  
  40. # Unlink all old devices so you don't have any phantom guest-* devices from launching previous VMs.
  41. for devname in os.listdir("/dev/input/by-id"):
  42.     if re.match("^(host|guest)\\-", devname):
  43.         run(["unlink", "--", os.path.join("/dev/input/by-id", devname)])
  44.  
  45. for (device, path) in zip(virtual_devices, virtual_device_paths):
  46.     if os.path.exists(path):
  47.         run(["unlink", "--", path])
  48.     run(["ln", "-s", device.device, path])
  49.  
  50. # Now we monopolize the original devices.
  51. for device in real_devices:
  52.     device.grab()
  53.  
  54. async def replicate(source_device, host_device, guest_device):
  55.     global hooks
  56.  
  57.     async for event in source_device.async_read_loop():
  58.         if event.type == e.EV_SYN:
  59.             continue
  60.  
  61.         mode = "guest" if event.code not in [e.KEY_GRAVE] else "host"
  62.  
  63.         target_device = {
  64.             "host": host_device,
  65.             "guest": guest_device,
  66.         }[mode]
  67.  
  68.         target_device.write_event(event)
  69.         target_device.syn()
  70.  
  71.  
  72. for source_device, host_device, guest_device in zip(real_devices, host_devices, guest_devices):
  73.     asyncio.ensure_future(replicate(source_device, host_device, guest_device))
  74.  
  75. event_loop = asyncio.get_event_loop()
  76. event_loop.run_forever()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement