Esempio n. 1
0
def write_release(ui: UInput, *codes: int) -> None:
    """
    Inject specified key codes into UInput with key_up.
    """
    for code in codes:
        ui.write(ecodes.EV_KEY, code, KeyEvent.key_up)
    ui.syn()
Esempio n. 2
0
    def __init__(self,
                 dev,
                 dev_mouse,
                 activeLog=False,
                 configFile='keyboardrc.ini',
                 logFile='keyboardlogrc.ini'):
        self.__device = evdev.InputDevice(dev)
        self.__device_mouse = evdev.InputDevice(dev_mouse)

        self.leds = KeyboardLeds(self.__device)
        self.leds.reset()

        self.notify = Notify('Keyboard Macros')
        self.notify.send('Running and connected to <b>{}</b>'.format(dev))

        self.__activeLog = activeLog
        if self.__activeLog:
            logging.config.fileConfig(logFile)
            self.__logger = logging.getLogger('root')

        self.__recording_buffer = []
        self.__recording = False
        self.__attribute_key = False
        self.__protect = False
        self.__unprotect = False
        self.__recording_mouse_buffer = []
        self.__recording_mouse = False

        self.__configFile = configFile
        self.__macros = {}  # defined in readConfig()
        self.readConfig()

        self.__ui = UInput()
Esempio n. 3
0
def write_tap(ui: UInput, code: int) -> None:
    """
    Write press and release.
    """
    write_press(ui, code)
    write_release(ui, code)
    ui.syn()
Esempio n. 4
0
def write_press(ui: UInput, *codes: int) -> None:
    """
    Inject specified key codes into UInput with key_down.
    """
    for code in codes:
        ui.write(ecodes.EV_KEY, code, KeyEvent.key_down)
    ui.syn()
Esempio n. 5
0
def register_device(device, device_number):
    input = find_input(device)
    if input is None:
        print("Can't find input device '%s'. Ignoring." %
              (device.get('input_name', None) or
               device.get('input_phys', None) or
               device.get('input_fn', None)))
        return
    input.grab()
    input.number = device_number

    caps = input.capabilities()
    # EV_SYN is automatically added to uinput devices
    del caps[ecodes.EV_SYN]

    remappings = device['remappings']
    extended = set(caps[ecodes.EV_KEY])

    def flatmap(lst):
        return [l2 for l1 in lst for l2 in l1]
    extended.update([remapping['code'] for remapping in flatmap(remappings.values())])
    caps[ecodes.EV_KEY] = list(extended)

    output = UInput(caps, name=device['output_name'])
    output.number = device_number

    active_remapped_keys[output.number] = set()
    active_output_keys[output.number] = set()
    active_input_keys[input.number] = set()

    asyncio.ensure_future(handle_events(input, output, remappings))
Esempio n. 6
0
class Mouse:
    def __init__(self, mul=(20, 20)):
        cap = {
            e.EV_REL: (e.REL_X, e.REL_Y),
            e.EV_KEY: (e.BTN_LEFT, e.BTN_RIGHT),
        }
        self.ui = UInput(cap)
        # , name='Microsoft X-Box pad v1 (US)', product=0x0202, vendor=0x045e)
        self.prev = {}
        self.mul = mul

    def callback(self, data):
        euler = data["eulerData"]
        prev = self.prev.get("eulerData", (0, 0, 0))

        self.ui.write(e.EV_REL, e.REL_X, int(
            (euler[0] - prev[0]) * self.mul[0]))
        self.ui.write(e.EV_REL, e.REL_Y, int(
            (euler[1] - prev[1]) * self.mul[1]))

        self.ui.write(e.EV_KEY, e.BTN_LEFT, data["trigger"] == 2)
        self.ui.write(e.EV_KEY, e.BTN_RIGHT, data["trigger"] == 4)

        self.prev = data
        self.ui.syn()
Esempio n. 7
0
def main(argv):
    thumb_board = identify_thumb_board()
    if thumb_board is None:
        print("could not find a Thumb Keyboard")
        return 1
    print(
        "binding to %s (%x %x)" %
        (thumb_board.path, thumb_board.info.vendor, thumb_board.info.product))

    alias_map = AliasMap(open("halfquerty-v2.bin", "rb").read())
    event_buffer = CircleBuffer(5)
    print("forward_aliases", alias_map.forward_aliases)
    print("alias_target_keys", alias_map.alias_target_keys)

    try:
        ui = UInput()
        for event in thumb_board.read_loop():
            if event.type == ecodes.EV_KEY:
                process_ev(
                    event_buffer,
                    alias_map.forward_aliases,
                    event,
                    ui,
                    alias_map.alias_target_keys,
                )
    except KeyboardInterrupt as e:
        return 0
    except Exception as e:
        print(full_stack())
    finally:
        ui.close()
        return 1
Esempio n. 8
0
    def __init__(self, rate):
        """
        Parameters
        ----------
        rate : int
            sample rate
        """
        self._rate = float(rate)
        self._lf = None
        self._threshold = 15000
        self._last_edge = None
        self._ch = None

        # Size in sampling intervals, of the frame space marker
        self._marker = int(2.0 * 0.0025 * self._rate)

        # Mapping of channels to events
        self._mapping = {
            0: ecodes.ABS_X,
            1: ecodes.ABS_Y,
            2: ecodes.ABS_Z,
            3: ecodes.ABS_THROTTLE
        }

        events = [(v, (0, 255, 5, 0)) for v in self._mapping.values()]

        self._ev = UInput(name='ppmadapter',
                          events={
                              ecodes.EV_ABS: events,
                              ecodes.EV_KEY: {
                                  288: 'BTN_JOYSTICK'
                              }
                          })
Esempio n. 9
0
 def __init__(self, thNo):
     Thread.__init__(self)
     self.thNo = thNo
     self.ui = UInput()
     self.keep_running = True
     self.waitingOnKey = True
     self.key = ecodes.KEY_Q
Esempio n. 10
0
def pointer_handler():
    global ui2
    global xFactor
    global yFactor
    xFactor = yFactor = 0

    #capture current mouse coordinates. TODO If user uses a real mouse/touchpad input could confuses
    x = 0
    y = 0
    try:
        ui2 = UInput(cap, name='virtual-mouse', version=0x3)
        #it's unknown but needs 2 times to work :S
        ui2 = UInput(cap, name='virtual-mouse', version=0x3)
    except:
        logger.warning("no uinput was defined (MOUSE)")


    #just to avoid init effect of cursor, joystick.py puts the cursor
    #ui2.write(e.EV_ABS, e.ABS_X, 0)
    #ui2.write(e.EV_ABS, e.ABS_Y, HEIGHT)
    #ui2.syn()

    while True:
        if x+xFactor<WIDTH and x+xFactor >=0:
            x=x+xFactor
        if y+yFactor<HEIGHT and y+yFactor >=0:
            y=y+yFactor
        ui2.write(e.EV_ABS, e.ABS_X, x)
        ui2.write(e.EV_ABS, e.ABS_Y, HEIGHT-y)
        ui2.syn()
        #logger.debug("x: %s y: %s, xF: %s yF: %s" % (x,y,xFactor,yFactor))
        time.sleep(0.01)
Esempio n. 11
0
 def __init__(self, id):
     print('Creating emulated touch device #%d' % id)
     self.id = id
     self.dev = UInput(self.cap, name='pytouchd-emutouchdev-%d' % id, version=0x0001)
     self.state = (0, 0, 0)  # (x, y, which key pressed)
     self.keydownstamp = None
     self.movebuffer = []
Esempio n. 12
0
 def createUInputDev(self, fd):
     if not self.env['runtime']['settingsManager'].getSettingAsBool(
             'keyboard', 'grabDevices'):
         self.uDevices[fd] = None
         return
     try:
         test = self.uDevices[fd]
         return
     except KeyError:
         self.uDevices[fd] = None
     if self.uDevices[fd] != None:
         return
     try:
         self.uDevices[fd] = UInput.from_device(self.iDevices[fd],
                                                name='fenrir-uinput',
                                                phys='fenrir-uinput')
     except Exception as e:
         try:
             self.env['runtime']['debug'].writeDebugOut(
                 'InputDriver evdev: compat fallback:  ' + str(e),
                 debug.debugLevel.WARNING)
             dev = self.iDevices[fd]
             cap = dev.capabilities()
             del cap[0]
             self.uDevices[fd] = UInput(cap,
                                        name='fenrir-uinput',
                                        phys='fenrir-uinput')
         except Exception as e:
             self.env['runtime']['debug'].writeDebugOut(
                 'InputDriver evdev: init Uinput not possible:  ' + str(e),
                 debug.debugLevel.ERROR)
             return
Esempio n. 13
0
async def handle_events(input: InputDevice, output: UInput, remappings,
                        modifier_groups):
    active_group = {}
    try:
        async for event in input.async_read_loop():
            if not active_group:
                active_mappings = remappings
            else:
                active_mappings = modifier_groups[active_group['name']]

            if (event.code == active_group.get('code') or
                (event.code in active_mappings
                 and 'modifier_group' in active_mappings.get(event.code)[0])):
                if event.value == 1:
                    active_group['name'] = \
                        active_mappings[event.code][0]['modifier_group']
                    active_group['code'] = event.code
                elif event.value == 0:
                    active_group = {}
            else:
                if event.code in active_mappings:
                    remap_event(output, event, active_mappings[event.code])
                else:
                    output.write_event(event)
                    output.syn()
    finally:
        del registered_devices[input.path]
        print('Unregistered: %s, %s, %s' %
              (input.name, input.path, input.phys),
              flush=True)
        input.close()
Esempio n. 14
0
class Input:
    def __init__(self):
        self._ui = UInput()

    def inject_event(self, keycode, typ):
	print "Injecting keycode: %s\n" % keycode
        self._ui.write(ecodes.EV_KEY, keycode, typ)
        self._ui.syn()
Esempio n. 15
0
 def __init__(self):
     self.ui = UInput()
     cap = {e.EV_REL: [e.REL_X, e.REL_Y]}
     cap = {
         e.EV_REL : (e.REL_X, e.REL_Y),
         e.EV_KEY : (e.BTN_MOUSE,),
     }
     self.mouse = UInput(cap)
Esempio n. 16
0
class Input:
    def __init__(self):
        self._ui = UInput()

    def inject_event(self, keycode, typ):
        print "Injecting keycode: %s\n" % keycode
        self._ui.write(ecodes.EV_KEY, keycode, typ)
        self._ui.syn()
Esempio n. 17
0
 def __init__(self):
     self.ui = UInput()
     cap = {e.EV_REL: [e.REL_X, e.REL_Y]}
     cap = {
         e.EV_REL: (e.REL_X, e.REL_Y),
         e.EV_KEY: (e.BTN_MOUSE, ),
     }
     self.mouse = UInput(cap)
Esempio n. 18
0
 def __init__(self, mul=(20, 20)):
     cap = {
         e.EV_REL: (e.REL_X, e.REL_Y),
         e.EV_KEY: (e.BTN_LEFT, e.BTN_RIGHT),
     }
     self.ui = UInput(cap)
     # , name='Microsoft X-Box pad v1 (US)', product=0x0202, vendor=0x045e)
     self.prev = {}
     self.mul = mul
Esempio n. 19
0
    def create(self):
        self.input_dev = UInput(self.capabilities,
                                self.name,
                                vendor=self.vendor,
                                product=self.product,
                                version=self.version,
                                phys=self.phys)

        return self
Esempio n. 20
0
    def __init__(self, target, threshold, density):
        self.__moving = False
        self.__device = UInput(self.capabilities)
        self.__target = target
        self.__target_pos = self.__target.geometry().center()
        self.__current_pos = None

        self.__threshold = threshold
        self.__density = density
Esempio n. 21
0
    def create_device(self, layout):
        """Creates a uinput device using the specified layout."""
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
                  ecodes.EV_REL: []}

        # Joystick device
        if layout.axes or layout.buttons or layout.hats:
            self.joystick_dev = next_joystick_device()

        for name in layout.axes:
            params = layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS)
            if not absInfoUsesValue:
                params = params[1:]
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.hats:
            params = (0, -1, 1, 0, 0)
            if not absInfoUsesValue:
                params = params[1:]
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.buttons:
            events[ecodes.EV_KEY].append(name)

        if layout.mouse:
            self.mouse_pos = {}
            self.mouse_rel = {}
            self.mouse_analog_sensitivity = float(
                layout.mouse_options.get("MOUSE_SENSITIVITY",
                                         DEFAULT_MOUSE_SENSITIVTY)
            )
            self.mouse_analog_deadzone = int(
                layout.mouse_options.get("MOUSE_DEADZONE",
                                         DEFAULT_MOUSE_DEADZONE)
            )
            self.scroll_repeat_delay = float(
                layout.mouse_options.get("MOUSE_SCROLL_REPEAT_DELAY",
                                         DEFAULT_SCROLL_REPEAT_DELAY)
            )
            self.scroll_delay = float(
                layout.mouse_options.get("MOUSE_SCROLL_DELAY",
                                         DEFAULT_SCROLL_DELAY)
            )

            for name in layout.mouse:
                if name in (ecodes.REL_WHEELUP, ecodes.REL_WHEELDOWN):
                    if ecodes.REL_WHEEL not in events[ecodes.EV_REL]:
                        # This ensures that scroll wheel events can work
                        events[ecodes.EV_REL].append(ecodes.REL_WHEEL)
                else:
                    events[ecodes.EV_REL].append(name)
                self.mouse_rel[name] = 0.0

        self.device = UInput(name=layout.name, events=events,
                             bustype=layout.bustype, vendor=layout.vendor,
                             product=layout.product, version=layout.version)
        self.layout = layout
Esempio n. 22
0
 def __init__(self,ppins,keys,name):
     self._name=name
     self._pins={}
     self.ui = ""
     for x in range(len(ppins)):
         self._pins[ppins[x]]=keys[x]
     self.setup()
     os.system("sudo modprobe uinput")
     self.ui = UInput(name="fex",vendor=9999,product=8888)
     self.addEvents()
Esempio n. 23
0
 def __init__(self):
     inputDriver.__init__(self)
     self._manager = multiprocessing.Manager()
     self.iDevices = {}
     self.iDevicesFD = self._manager.list()
     self.uDevices = {}
     self.gDevices = {}
     self.iDeviceNo = 0
     self.watchDog = Value(c_bool, True)
     self.UInputinject = UInput()
def read_data(ep_in):
    """
    Read the transmitted android keycodes from the input endpoint and trigger the corresponding key presses in linux.
    :param ep_in: input endpoint of the accessory device.
    """
    ui = UInput()
    while True:
        try:
            data = ep_in.read(3)
            keycode = data[1] * 0xFF + data[2]
            evdev_keycode = get_evdev_keycode(keycode)
            if data[0] == 0:
                print("Key down {}".format(keycode))
                if evdev_keycode != -1:
                    ui.write(ecodes.EV_KEY, evdev_keycode, 1)
                    ui.syn()
            elif data[0] == 1:
                print("Key up {}".format(keycode))
                if evdev_keycode != -1:
                    ui.write(ecodes.EV_KEY, evdev_keycode, 0)
                    ui.syn()
        except usb.core.USBError as e:
            # ignore exceptions caused by read timeout
            if e.errno == 110:
                pass
            else:
                print("failed to read input")
                print(e)
                break
Esempio n. 25
0
class DeviceWriter:
    def __init__(self, scale):
        self.scale = scale
        # most values were taken from running
        # InputDevice('/dev/input/event$N').capabilities()
        vendor = 1133
        product = 0
        version = 273
        bustype = 3
        caps = {
            e.EV_KEY: [e.BTN_0, e.BTN_1],
            e.EV_REL: [e.REL_X, e.REL_Y, e.REL_Z, e.REL_RX, e.REL_RY, e.REL_RZ],
        }
        device_name = 'Virtual SpaceNav'
        self.state = True
        self.ui = UInput(caps, vendor=vendor, product=product,
                         version=version, bustype=bustype, name=device_name)

    def make_event(self, data):
        if not self.state:
            return
        for v in (data.linear, data.angular):
            # We don't want to write zeroes because the real spacenav never does,
            # instead write a small value inside Earth's gutter to prevent drift.
            if v.x == 0:
                v.x = 1.0 / self.scale
            if v.y == 0:
                v.y = 1.0 / self.scale
            if v.z == 0:
                v.z = 1.0 / self.scale
        # write some event to self.ui based off of the twist data
        _time = time.time()
        stime = int(_time)
        utime = int((float(_time) - stime) * 10 ** 6)
        x = InputEvent(stime, utime, e.EV_REL, e.REL_X, -self.translate(data.linear.y))
        y = InputEvent(stime, utime, e.EV_REL, e.REL_Y, -self.translate(data.linear.x))
        z = InputEvent(stime, utime, e.EV_REL, e.REL_Z, -self.translate(data.linear.z))
        ax = InputEvent(stime, utime, e.EV_REL, e.REL_RX, -self.translate(data.angular.y))
        ay = InputEvent(stime, utime, e.EV_REL, e.REL_RY, -self.translate(data.angular.x))
        az = InputEvent(stime, utime, e.EV_REL, e.REL_RZ, -self.translate(data.angular.z))
        # write all events
        self.ui.write_event(x)
        self.ui.write_event(y)
        self.ui.write_event(z)
        self.ui.write_event(ax)
        self.ui.write_event(ay)
        self.ui.write_event(az)
        # syn to alert input subsystem
        self.ui.syn()

    def translate(self, n):
        return int(n * self.scale)  # TODO find the translation...

    def set_state(self, msg):
        self.state = msg.state == ApplicationState.VISIBLE
Esempio n. 26
0
 def __init__(self):
     logger.info('Plugin evdev_keyboard initializing...')
     super().__init__()
     cap = {}
     self.__keyboard = UInput(cap,
                              name='xHID evdev keyboard',
                              version=0x1,
                              vendor=0x1,
                              product=0x1,
                              props=[])
     self.__onscreen = False
Esempio n. 27
0
 def __init__(self, device, addr):
     super().__init__(device, addr)
     self.type = "Xbox 360 Controller"
     self._ui = UInput(
         events=self.capabilities,
         name=self.type,
         vendor=0x045e,
         product=0x028e,
         version=0x0110,
         bustype=e.BUS_USB,
     )
Esempio n. 28
0
 def __init__(self, device, addr):
     super().__init__(device, addr)
     self.type = "Sony Computer Entertainment Wireless Controller"
     self._ui = UInput(
         events=self.capabilities,
         name=self.type,
         vendor=1356,
         product=1476,
         version=273,
         bustype=e.BUS_USB,
     )
Esempio n. 29
0
 def __init__(self):
     print('initializing udev_evdev_emit')
     #several of these cap mappings are fake and just intended to ensure that Godot sees us as a valid controller
     #actual mappings: volup = BTN_0; voldown = BTN_1; app button = BTN_2; daydream button = BTN_3; touchpad button = BTN_4 
     cap = { e.EV_KEY : [e.BTN_A, e.BTN_THUMBL, e.BTN_TRIGGER, e.BTN_0, e.BTN_1, e.BTN_2, e.BTN_3, e.BTN_4], 
            e.EV_ABS : [(e.ABS_X, AbsInfo(value=0, min=0, max=255, fuzz=0, flat=0, resolution=0)), 
                        (e.ABS_Y, AbsInfo(value=0, min=0, max=255, fuzz=0, flat=0, resolution=0)), 
                        (e.ABS_HAT0X, AbsInfo(value=0, min=0, max=255, fuzz=0, flat=0, resolution=0)), 
                        (e.ABS_GAS, AbsInfo(value=0, min=0, max=255, fuzz=0, flat=0, resolution=0)),
                        (e.ABS_RUDDER, AbsInfo(value=0, min=0, max=255, fuzz=0, flat=0, resolution=0))]}
     self.ui = UInput(cap, name="daydream controller", version=0x3)
Esempio n. 30
0
 def __init__(self, device, addr):
     super().__init__(device, addr)
     self.type = "Microsoft X-Box One pad"
     self._ui = UInput(
         events=self.capabilities,
         name=self.type,
         vendor=0x045e,
         product=0x02d1,  #0x028e,
         version=0x0110,
         bustype=e.BUS_USB,
     )
Esempio n. 31
0
 def __init__(self, can_id):
     self.can_id = can_id
     axis_cap = AbsInfo(-32700, 32700, 0, 0, 0, 0)
     self._ev = UInput(
         name='vjoy',
         events={
             ecodes.EV_ABS: [(ecodes.ABS_X, axis_cap),
                             (ecodes.ABS_Y, axis_cap),
                             (ecodes.ABS_Z, axis_cap)],
             ecodes.EV_KEY:
             [ecodes.BTN_TRIGGER, ecodes.BTN_TOP, ecodes.BTN_TOP2]
         })
Esempio n. 32
0
async def translate_input(device: InputDevice, ui: UInput,
                          disabled: Sequence[int],
                          mapping: Mapping[int, int]) -> None:
    """Read inputs from device, filter out disabled, apply mapping, and write to ui."""
    async for ev in device.async_read_loop():
        if ev.type == e.EV_KEY:
            if ev.code in disabled:
                continue
            if ev.code in mapping:
                ev.code = mapping[ev.code]
        ui.write_event(ev)
        ui.syn()
Esempio n. 33
0
class Device(object):
    def __init__(self):
        self.ui = UInput()

    def send(self, data):
        for d in data:
            self.ui.write(e.EV_KEY, keydict[d], 1)
            self.ui.syn()
            self.ui.write(e.EV_KEY, keydict[d], 0)
            self.ui.syn()

    def close(self):
        self.ui.close()
Esempio n. 34
0
 def __init__(self, ppins, keys, name):
     self._name = name
     self._pins = {}
     self._prevStatus = {}
     self.ui=""
     self._mcp= MCP23017()
     self.active=True
     for x in range(len(ppins)):
         self._pins[ppins[x]] = keys[x]
         self._prevStatus[ppins[x]]=True
     os.system("sudo modprobe uinput")
     self.ui = UInput({e.EV_KEY:self._pins.values()},name="retrogame",bustype=e.BUS_USB)
     self.setup()
     self.loop()
Esempio n. 35
0
 def create_mouse(self):
     events = {
         ecodes.EV_REL: (ecodes.REL_X, ecodes.REL_Y),
         ecodes.EV_KEY: (ecodes.BTN_LEFT, ecodes.BTN_RIGHT)
     }
     self.mouse = UInput(events)
     self.mouse_pos = None
Esempio n. 36
0
    def create_device(self, layout):
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
                  ecodes.EV_REL: []}

        # Joystick device
        if layout.axes or layout.buttons or layout.hats:
            self.joystick_dev = next_joystick_device()

        for name in layout.axes:
            params = layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS)
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.hats:
            params = (-1, 1, 0, 0)
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.buttons:
            events[ecodes.EV_KEY].append(name)

        if layout.mouse:
            self.mouse_pos = {}
            self.mouse_rel = {}
            self.mouse_analog_sensitivity = float(layout.mouse_options.get("MOUSE_SENSITIVITY", 0.3))
            self.mouse_analog_deadzone = int(layout.mouse_options.get("MOUSE_DEADZONE", 5))

            for name in layout.mouse:
                events[ecodes.EV_REL].append(name)
                self.mouse_rel[name] = 0.0

        self.device = UInput(name=layout.name, events=events,
                             bustype=layout.bustype, vendor=layout.vendor,
                             product=layout.product, version=layout.version)
        self.layout = layout
Esempio n. 37
0
    def __init__(self, rate):
        """
        Parameters
        ----------
        rate : int
            sample rate
        """
        self._rate = float(rate)
        self._lf = None
        self._threshold = 15000
        self._last_edge = None
        self._ch = None

        # Size in sampling intervals, of the frame space marker
        self._marker = int(2.0 * 0.0025 * self._rate)

        # Mapping of channels to events
        self._mapping = {0: ecodes.ABS_X,
                         1: ecodes.ABS_Y,
                         2: ecodes.ABS_Z,
                         3: ecodes.ABS_THROTTLE}

        events = [(v, (0, 255, 5, 0)) for v in self._mapping.values()]

        self._ev = UInput(name='ppmadapter',
                          events={
                               ecodes.EV_ABS: events,
                               ecodes.EV_KEY: {288: 'BTN_JOYSTICK'}
                          })
Esempio n. 38
0
    def create_device(self, layout):
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
                  ecodes.EV_REL: []}

        # Joystick device
        if layout.axes or layout.buttons or layout.hats:
            self.joystick_dev = next_joystick_device()

        for name in layout.axes:
            key = getattr(ecodes, name)
            params = layout.axes_options.get(name, (0, 255, 0, 15))
            events[ecodes.EV_ABS].append((key, params))

        for name in layout.hats:
            key = getattr(ecodes, name)
            params = (-1, 1, 0, 0)
            events[ecodes.EV_ABS].append((key, params))

        for name in layout.buttons:
            events[ecodes.EV_KEY].append(getattr(ecodes, name))

        if layout.mouse:
            self.mouse_pos = {}
            for name in layout.mouse:
                events[ecodes.EV_REL].append(getattr(ecodes, name))

        self.device = UInput(name=layout.name, events=events,
                             bustype=layout.bustype, vendor=layout.vendor,
                             product=layout.product, version=layout.version)
        self.layout = layout
Esempio n. 39
0
 def __init__(self, n, m):
     Thread.__init__(self)
     self.n = n
     self.stop = False
     self.sleep = False
     self.ui = UInput()
     self.m = m
Esempio n. 40
0
    def _prepare_device (self):
        #print("device: %s" % self._profile.device.name)
        self._event_status = {key:0 for key in self._profile.device.get_events_supported()}
        #print("Events supported",self._event_status)
        self._allowed_event_types = set([getattr(ecodes,i[-1].split(':')[0]) for i in self._event_status])
        self._input_devices = map(InputDevice, self._profile.device.devices)
        self._file_descriptors = { dev.fd: i for i, dev in enumerate(self._input_devices) }
        
        print("Mappings for '" + self._profile.name+"' " + '-'*30)
        for k,v in sorted(self._profile.mapping.items()):
            print(str(k.replace("EV_KEY:KEY_","").replace("ENTER","<-'").replace("APOSTROPHE","'").replace(",","")).lower().rjust(20)+" as "+(', '.join(v)).replace("r_hand_tap_", "").replace("_vs_thumb", ""))
            
        # Prepare virtual device for event injection
        capabilities = {}
        for ev_chain in self._profile.mapping:
            for k in re.split('[+,]', ev_chain):
                et, ec = k.split(':', 1)
                etype = ecodes.ecodes[et]
                if etype in capabilities:
                    capabilities[etype].append(ecodes.ecodes[ec])
                else:
                    capabilities[etype] = [ ecodes.ecodes[ec] ]
        #print("Capabilities", capabilities)
        self._virtual_input = UInput(events = capabilities)

        # Prepare matcher
        self._matcher = Matcher(self._profile)
Esempio n. 41
0
def writeWord(word):
    listOfLetters = list(word)
    
    
    ui = UInput()
    
    for letter in listOfLetters:
        if letter.isupper():
            letter = letter.lower()
            case = 'upper'
        else:
            case = 'lower'

        writeUiCase(letter, ui, case)

    ui.syn()
    ui.close()
Esempio n. 42
0
 def __init__(self, listener=MouseListener()):
     Thread.__init__(self)
     self.m = PyMouse()
     self.ui = UInput()
     self.devices = []
     self.running = True
     self.lastPosition = None
     self.device_search()
     self.listener = listener
Esempio n. 43
0
    def create_device(self, layout):
        """Creates a uinput device using the specified layout."""
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
                  ecodes.EV_REL: []}

        # Joystick device
        if layout.axes or layout.buttons or layout.hats:
            self.joystick_dev = next_joystick_device()

        for name in layout.axes:
            params = layout.axes_options.get(name, DEFAULT_AXIS_OPTIONS)
            if not absInfoUsesValue:
                params = params[1:]
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.hats:
            params = (0, -1, 1, 0, 0)
            if not absInfoUsesValue:
                params = params[1:]
            events[ecodes.EV_ABS].append((name, params))

        for name in layout.buttons:
            events[ecodes.EV_KEY].append(name)

        if layout.mouse:
            self.mouse_pos = {}
            self.mouse_rel = {}
            self.mouse_analog_sensitivity = float(
                layout.mouse_options.get("MOUSE_SENSITIVITY",
                                         DEFAULT_MOUSE_SENSITIVTY)
            )
            self.mouse_analog_deadzone = int(
                layout.mouse_options.get("MOUSE_DEADZONE",
                                         DEFAULT_MOUSE_DEADZONE)
            )
            self.scroll_repeat_delay = float(
                layout.mouse_options.get("MOUSE_SCROLL_REPEAT_DELAY",
                                         DEFAULT_SCROLL_REPEAT_DELAY)
            )
            self.scroll_delay = float(
                layout.mouse_options.get("MOUSE_SCROLL_DELAY",
                                         DEFAULT_SCROLL_DELAY)
            )

            for name in layout.mouse:
                if name in (ecodes.REL_WHEELUP, ecodes.REL_WHEELDOWN):
                    if ecodes.REL_WHEEL not in events[ecodes.EV_REL]:
                        # This ensures that scroll wheel events can work
                        events[ecodes.EV_REL].append(ecodes.REL_WHEEL)
                else:
                    events[ecodes.EV_REL].append(name)
                self.mouse_rel[name] = 0.0

        self.device = UInput(name=layout.name, events=events,
                             bustype=layout.bustype, vendor=layout.vendor,
                             product=layout.product, version=layout.version)
        self.layout = layout
Esempio n. 44
0
    def execute(self):
        print "Executing " + e.KEY[self.macroKey] + " macro."
        ui = UInput()

        for i in range(len(self.keySequence)):
            ui.write(e.EV_KEY, self.keySequence[i], self.keyState[i]);
        ui.syn()
        ui.close()
Esempio n. 45
0
 def __init__(self):
     Thread.__init__(self)
     self.n = 0
     self.st = True     # Stop
     self.sl = False     # Sleep
     self.ui = UInput()
     self.history = []
     self.m = PyMouse()
     self.flag = True
     self.rec = False
Esempio n. 46
0
class MouseWatcher(Thread):
    def __init__(self, listener=MouseListener()):
        Thread.__init__(self)
        self.m = PyMouse()
        self.ui = UInput()
        self.devices = []
        self.running = True
        self.lastPosition = None
        self.device_search()
        self.listener = listener

    def stop(self):
        print "Desligando mouse."
        self.running = False

    def device_search(self):
        devices_list = []
        files = []
        for (dirpath, dirnames, filenames) in walk(INPUTDIR):
            files.extend(filenames)
            break
        for f in files:
            try:
                dev = InputDevice(path.join(INPUTDIR, f))
                keymap = dev.capabilities().get(1)
                if ecodes.BTN_MOUSE in keymap and ecodes.BTN_LEFT in keymap:
                    devices_list.append(dev)
            except (IOError, OSError, TypeError):
                pass
        self.devices = {dev.fd: dev for dev in devices_list}

    def run(self):
        while self.running:
            r,w,x = select(self.devices, [], [])
            for fd in r:
                if not self.running:
                    break
                for event in self.devices[fd].read():
                    if event.type == ecodes.EV_KEY and event.value == 1:
                        self.lastPosition = self.m.position()
                        if self.listener.__class__ != MouseListener:
                            self.listener.call_me(self.lastPosition)
        self.ui.close()
Esempio n. 47
0
def call(k, conf=False):
    if conf:
        keys = defns._k[k]
    else:
        keys = defns.default[k]
    try:
        ui = UInput()
        for key in keys:
            ui.write(defns.k["EV_KEY"], defns.k["KEY_" + key.upper()], 1)
        defns._k[k].reverse()
        for key in keys:
            ui.write(defns.k["EV_KEY"], defns.k["KEY_" + key.upper()], 0)
        ui.syn()
        ui.close()
    except err:
        print "Not enough permissions. Are you root?"
Esempio n. 48
0
class Player(Thread):
    def __init__(self, n, m):
        Thread.__init__(self)
        self.n = n
        self.stop = False
        self.sleep = False
        self.ui = UInput()
        self.m = m
    
    def sendEvent(self):
        i = 0
        while i < len(history):
            now = history[i]
            if i < len(history)-1: after = history[i+1]
                
            if self.stop: break
            if not self.sleep:
                m.move( now.get("mouse")[0], now.get("mouse")[1])
                if now.get("event").type == ecodes.EV_KEY:
                    self.ui.write(ecodes.EV_KEY, now.get("event").code, now.get("event").value)
                    self.ui.syn()
                if i < len(history):
                    time.sleep(float(after.get("event").sec - now.get("event").sec)+float(after.get("event").usec - now.get("event").usec)/1000000)
                i += 1
    
    # sobrescrevendo o metodo run()
    def run(self):
        if self.n == 0:
            while not self.stop:
                self.sendEvent()
        elif self.n > 0:
            for i in range(self.n):
                self.sendEvent()
        self.stop = True
        print "\rEnd               "
        ui.close()
    
    def Stop(self):
        self.stop = True
    
    def Sleep(self):
        self.sleep = not self.sleep
Esempio n. 49
0
def call(vals):
    """
  The call function receives a list of keys to be pressed and loops over
  them switching them to pressed state, then loops over the reversed list
  unpressing them. That way it can process key combinations.
  """
    try:
        ui = UInput()
        for k in vals:
            ui.write(ecodes["EV_KEY"], ecodes["KEY_" + keys[k]], 1)
        vals.reverse()
        for k in vals:
            ui.write(ecodes["EV_KEY"], ecodes["KEY_" + keys[k]], 0)
        ui.syn()
        ui.close()
    except err:
        print "Not enough permissions. Are you root?"
Esempio n. 50
0
class TestListener(Leap.Listener):
    hand_id = 0
    spread_win = False
    curtime = 0
    ui = None
    
    def on_init(self, controller):
        self.ui = UInput()
        print "Initialized"

    def on_connect(self, controller):
        print "Connected"

    def on_disconnect(self, controller):
        print "Disconnected"

    def on_exit(self, controller):
        print "Exited"

    def on_frame(self, controller):
        frame = controller.frame() 

        if not frame.hands.is_empty:
            hand = frame.hands[0]

            fingers = hand.fingers
            if not fingers.is_empty:
                if hand.id == self.hand_id and not self.spread_win and len(fingers) >= 4 and (frame.timestamp - self.curtime) <= 1000000:
                    #print "(Spread) Old timestamp is %d, current is %d (%d)" % (self.curtime, frame.timestamp, (frame.timestamp - self.curtime))
                    self.spread_windows()
                    #print "Spread windows"
                    self.spread_win = True
                    self.curtime = frame.timestamp
                    #print "Hand open timestamp is %d" % self.curtime
            else:
                if hand.id == self.hand_id and self.spread_win and (frame.timestamp - self.curtime) <= 1000000:
                    #print "(Unspread) Old timestamp is %d, current is %d (%d)" % (self.curtime, frame.timestamp, (frame.timestamp - self.curtime))
                    self.spread_windows()
                    #print "Unspread windows"
                    self.spread_win = False
                else:
                    self.hand_id = hand.id
                    self.curtime = frame.timestamp
                    #print "Fist timestamp is %d" % self.curtime

    def spread_windows(self):
        self.ui.write(e.EV_KEY, e.KEY_LEFTMETA, 1) # <super> key down
        self.ui.write(e.EV_KEY, e.KEY_W, 1) # 'W' key down
        self.ui.write(e.EV_KEY, e.KEY_W, 0) # 'W' key up
        self.ui.write(e.EV_KEY, e.KEY_LEFTMETA, 0) # <super> key up
        self.ui.syn()
Esempio n. 51
0
 def __init__(self, port = "/dev/ttyAMA0", name="xbox_chatpad_input", keycode_callback = None, ecode_callback = None):
     self.keycode_callback = keycode_callback
     self.ecode_callback = ecode_callback
     if ecode_callback == None and name: #If we don't have any external callback provided, we should be using a built-in one that uses uinput
         self.ecode_callback = self.uinput_callback
         self.uinput = UInput(name=name, devnode='/dev/uinput')
     if self.keycode_callback == None: #If keycode_callback is not provided
         self.keycode_callback = lambda *args: None #Setting callback to empty function to avoid exceptions 
     if self.ecode_callback == None: #If ecode_callback is not provided
         self.ecode_callback = lambda *args: None #Setting callback to empty function to avoid exceptions 
     self.name = name
     self.port = port
     self.serial = Serial(port, 19200)
Esempio n. 52
0
 def __init__(self, scale):
     self.scale = scale
     # most values were taken from running
     # InputDevice('/dev/input/event$N').capabilities()
     vendor = 1133
     product = 0
     version = 273
     bustype = 3
     caps = {
         e.EV_KEY: [e.BTN_0, e.BTN_1],
         e.EV_REL: [e.REL_X, e.REL_Y, e.REL_Z, e.REL_RX, e.REL_RY, e.REL_RZ],
     }
     device_name = 'Virtual SpaceNav'
     self.state = True
     self.ui = UInput(caps, vendor=vendor, product=product,
                      version=version, bustype=bustype, name=device_name)
Esempio n. 53
0
    def create_joystick(self, name, axes, buttons, hats, axes_options={}):
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: []}
        device_name = name

        for name in axes:
            key = getattr(ecodes, name)
            params = axes_options.get(name, (0, 255, 0, 15))
            events[ecodes.EV_ABS].append((key, params))

        for name in hats:
            key = getattr(ecodes, name)
            params = (-1, 1, 0, 0)
            events[ecodes.EV_ABS].append((key, params))

        for name in buttons:
            events[ecodes.EV_KEY].append(getattr(ecodes, name))

        self.joystick = UInput(name=device_name, events=events)
        self.axes = axes
        self.buttons = buttons
        self.hats = hats
Esempio n. 54
0
class Keyboard:

    def __init__(self):
        self.ui = UInput()

    def press_key(self, list_ecodes):
        """
        Write events to keyboard based on a list of ecodes
        :param list_ecodes
        """

        # key down event (press)
        for code in list_ecodes:
            self.ui.write(ecodes.EV_KEY, code, 1)

        # key up event (release)
        for code in list_ecodes:
            self.ui.write(ecodes.EV_KEY, code, 0)

        # after all keys are writen sync
        self.ui.syn()
Esempio n. 55
0
class KeyHandler:

    def __init__(self, mod_mapping, key_mapping):
        self._ui = UInput()
        self._mod_mapping = mod_mapping
        self._key_mapping = key_mapping

    def chord_event(self, mods, virtual_mods, chord, value):
        chord_keys = self.map_chord(virtual_mods, chord)
        if value == 0:
            chord_keys = chord_keys + self.map_mods(mods)
        else:
            chord_keys = self.map_mods(mods) + chord_keys

        for key in chord_keys:
            self._ui.write(EV_KEY, key, value)
        self._ui.syn()

    def map_chord(self, virtual_mods, chord):
        frozen_vmods = frozenset(virtual_mods)
        if frozen_vmods not in self._key_mapping:
            return []
        current_mapping = self._key_mapping[frozen_vmods]
        frozen_chord = frozenset(chord)
        if frozen_chord not in current_mapping:
            return []
        return current_mapping[frozen_chord]

    def map_mods(self, keys):
        mods = []
        for key in keys:
            mods.append(self._mod_mapping[key])
        return mods

    def close(self):
        self._ui.close()
Esempio n. 56
0
class K:
  __space_mode_map = {
    ecodes.KEY_1: [ecodes.KEY_1, True],
    ecodes.KEY_2: [ecodes.KEY_2, True],
    ecodes.KEY_3: [ecodes.KEY_3, True],
    ecodes.KEY_4: [ecodes.KEY_4, True],
    ecodes.KEY_5: [ecodes.KEY_5, True],
    ecodes.KEY_6: [ecodes.KEY_6, True],
    ecodes.KEY_7: [ecodes.KEY_7, True],
    ecodes.KEY_8: [ecodes.KEY_8, True],
    ecodes.KEY_9: [ecodes.KEY_9, True],
    ecodes.KEY_0: [ecodes.KEY_0, True],

    ecodes.KEY_Q: [ecodes.KEY_1, True],
    ecodes.KEY_W: [ecodes.KEY_2, True],
    ecodes.KEY_E: [ecodes.KEY_3, True],
    ecodes.KEY_R: [ecodes.KEY_4, True],
    ecodes.KEY_T: [ecodes.KEY_5, True],
    ecodes.KEY_Y: [ecodes.KEY_6, True],
    ecodes.KEY_U: [ecodes.KEY_7, True],
    ecodes.KEY_I: [ecodes.KEY_8, True],
    ecodes.KEY_O: [ecodes.KEY_9, True],
    ecodes.KEY_P: [ecodes.KEY_0, True],

    ecodes.KEY_A: [ecodes.KEY_MINUS, True],
    ecodes.KEY_S: [ecodes.KEY_MINUS, False],
    ecodes.KEY_D: [ecodes.KEY_LEFTBRACE, False],
    ecodes.KEY_F: [ecodes.KEY_RIGHTBRACE, False],
    ecodes.KEY_G: [ecodes.KEY_APOSTROPHE, False],
    ecodes.KEY_H: [ecodes.KEY_APOSTROPHE, True],
    ecodes.KEY_J: [ecodes.KEY_LEFTBRACE, True],
    ecodes.KEY_K: [ecodes.KEY_RIGHTBRACE, True],
    ecodes.KEY_L: [ecodes.KEY_GRAVE, True],
    ecodes.KEY_SEMICOLON: [ecodes.KEY_SEMICOLON, True],

    #ecodes.KEY_Z: used for control mode!
    ecodes.KEY_X: [ecodes.KEY_GRAVE, False],
    ecodes.KEY_C: [ecodes.KEY_BACKSLASH, False],
    ecodes.KEY_V: [ecodes.KEY_EQUAL, False],
    ecodes.KEY_B: [ecodes.KEY_BACKSLASH, True],

    ecodes.KEY_N: [ecodes.KEY_EQUAL, True],
    ecodes.KEY_M: [ecodes.KEY_SPACE, False],
    ecodes.KEY_COMMA: [ecodes.KEY_COMMA, True],
    ecodes.KEY_DOT: [ecodes.KEY_DOT, True],
    ecodes.KEY_SLASH: [ecodes.KEY_SLASH, True],
  }

  __tenkey_mode_map = {
    ecodes.KEY_Q: [ecodes.KEY_1, False],
    ecodes.KEY_W: [ecodes.KEY_2, False],
    ecodes.KEY_E: [ecodes.KEY_3, False],
    ecodes.KEY_R: [ecodes.KEY_4, False],
    ecodes.KEY_T: [ecodes.KEY_5, False],
    ecodes.KEY_Y: [ecodes.KEY_6, False],
    ecodes.KEY_U: [ecodes.KEY_7, False],
    ecodes.KEY_I: [ecodes.KEY_8, False],
    ecodes.KEY_O: [ecodes.KEY_9, False],
    ecodes.KEY_P: [ecodes.KEY_0, False],

    ecodes.KEY_A: [ecodes.KEY_TAB, False],
    ecodes.KEY_S: [ecodes.KEY_DELETE, False],
    ecodes.KEY_D: [ecodes.KEY_BACKSPACE, False],
    ecodes.KEY_F: [ecodes.KEY_ESC, False],
    ecodes.KEY_G: [ecodes.KEY_F1, False],
    ecodes.KEY_H: [ecodes.KEY_LEFT, False],
    ecodes.KEY_J: [ecodes.KEY_DOWN, False],
    ecodes.KEY_K: [ecodes.KEY_UP, False],
    ecodes.KEY_L: [ecodes.KEY_RIGHT, False],
    ecodes.KEY_SEMICOLON: [ecodes.KEY_ENTER, False],
  }

  def __init__(self):
    self.sink = UInput()
    self.reset_state()
    self.buffered_event = None

  def set_state(self, state):
    self.__state = state

  def pop_state(self):
    self.__state.state_exit()
    self.__state.popState()

  def emit_with_space_mode(self, event):
    if event.event.scancode in self.__space_mode_map:
      translated_event = self.__space_mode_map[event.event.scancode]
      if translated_event[1]:
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1)
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 2)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 1)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 0)
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)
      else:
        self.sink.write(ecodes.EV_KEY, translated_event[0], 1)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 0)
    else:
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 1)
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 0)

  def emit_with_tenkey_mode(self, event):
    if event.event.scancode in self.__tenkey_mode_map:
      translated_event = self.__tenkey_mode_map[event.event.scancode]
      if translated_event[1]:
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1)
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 2)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 1)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 0)
        self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)
      else:
        self.sink.write(ecodes.EV_KEY, translated_event[0], 1)
        self.sink.write(ecodes.EV_KEY, translated_event[0], 0)
    else:
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 1)
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 0)

  def emit_with_control_mode(self, event):
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 1)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 2)
    if self.__space_mode:
      self.emit_with_space_mode(event)
    elif self.__tenkey_mode:
      #print("control tenkey")
      self.emit_with_tenkey_mode(event)
    else:
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 1)
      self.sink.write(ecodes.EV_KEY, event.event.scancode, 0)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTCTRL, 0)

  def emit_with_shift_mode(self, event):
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 2)
    self.sink.write(ecodes.EV_KEY, event.event.scancode, 1)
    self.sink.write(ecodes.EV_KEY, event.event.scancode, 0)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)

  def emit_with_normal_mode(self, event):
    self.sink.write(ecodes.EV_KEY, event.event.scancode, event.event.keystate)

  def emit(self, event):
    #if event.event.scancode == ecodes.KEY_CAPSLOCK:# or event.event.scancode == ecodes.KEY_SYSRQ:
    #  self.sink.write(ecodes.EV_KEY, ecodes.KEY_F1, event.event.keystate)
    #elif event.event.scancode == ecodes.KEY_LEFTMETA and event.event.keystate == events.KeyEvent.key_hold:
    #  pass
    #  #self.sink.write(ecodes.EV_KEY, ecodes.KEY_F1, event.event.keystate)
    if self.__control_mode and event.event.keystate != events.KeyEvent.key_up:
      self.emit_with_control_mode(event)
    elif self.__space_mode and event.event.keystate != events.KeyEvent.key_up:
      self.emit_with_space_mode(event)
    elif self.__shift_mode and event.event.keystate != events.KeyEvent.key_up:
      self.emit_with_shift_mode(event)
    elif self.__tenkey_mode and event.event.keystate != events.KeyEvent.key_up:
      self.emit_with_tenkey_mode(event)
    else:
      self.emit_with_normal_mode(event)

    self.sink.syn()

  def emit_space(self):
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_SPACE, 1)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_SPACE, 0)
    self.sink.syn()

  def emit_z(self):
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_Z, 1)
    self.sink.write(ecodes.EV_KEY, ecodes.KEY_Z, 0)
    self.sink.syn()

  def emit_slash(self):
    if self.__space_mode:
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 1)
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 2)
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_SLASH, 1)
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_SLASH, 0)
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_LEFTSHIFT, 0)
    else:
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_SLASH, 1)
      self.sink.write(ecodes.EV_KEY, ecodes.KEY_SLASH, 0)

    self.sink.syn()

  def emit_as_buffered(self, event):
    self.buffered_event = event

  def emit_buffered(self):
    self.emit(self.buffered_event)
    self.buffered_event = None

  def buffer(self, event):
    self.emit_as_buffered(event)

  def flush(self):
    self.emit_buffered()

  def reset_state(self):
    self.__buffer = None
    self.__space_mode = False
    self.__control_mode = False
    self.__meta_mode = False
    self.__tenkey_mode = False
    self.__shift_mode = False

  def space_mode(self, flag):
    self.__space_mode = flag

  def control_mode(self, flag):
    self.__control_mode = flag

  def meta_mode(self, flag):
    self.__meta_mode = flag

  def shift_mode(self, flag):
    self.__shift_mode = flag

  def tenkey_mode(self, flag):
    self.__tenkey_mode = flag

  def close(self):
    self.sink.close()
Esempio n. 57
0
 def __init__(self):
   self.sink = UInput()
   self.reset_state()
   self.buffered_event = None
Esempio n. 58
0

i = 5
moves = 100000

print("Go to 2048 window. ["+str(i)+"] secs.")
while i != 0:
	print(" " + str(i))
	time.sleep(1)
	i -= 1

print("Commencing...\n")

keys = ["e.KEY_UP", "e.KEY_DOWN", "e.KEY_LEFT", "e.KEY_RIGHT"]
keys = [105, 106, 103, 108]

# random.choice(foo)
ui = UInput()
current_title = GetActiveWindowTitle()
if 'Firefox' in current_title:
    while moves != 0:
        temp_key = random.choice(keys)
        send_keys(ui, temp_key)
        time.sleep(0.1)
        moves -= 1
    print("Done")
else:
	print("You're not on the firefox window.")

ui.close()
Esempio n. 59
0
class UInputDevice(object):
    def __init__(self, layout):
        self.joystick_dev = None
        self.evdev_dev = None
        self.ignored_buttons = set()
        self.create_device(layout)

    def create_mouse(self):
        events = {
            ecodes.EV_REL: (ecodes.REL_X, ecodes.REL_Y),
            ecodes.EV_KEY: (ecodes.BTN_LEFT, ecodes.BTN_RIGHT)
        }
        self.mouse = UInput(events)
        self.mouse_pos = None

    def create_device(self, layout):
        events = {ecodes.EV_ABS: [], ecodes.EV_KEY: [],
                  ecodes.EV_REL: []}

        # Joystick device
        if layout.axes or layout.buttons or layout.hats:
            self.joystick_dev = next_joystick_device()

        for name in layout.axes:
            key = getattr(ecodes, name)
            params = layout.axes_options.get(name, (0, 255, 0, 15))
            events[ecodes.EV_ABS].append((key, params))

        for name in layout.hats:
            key = getattr(ecodes, name)
            params = (-1, 1, 0, 0)
            events[ecodes.EV_ABS].append((key, params))

        for name in layout.buttons:
            events[ecodes.EV_KEY].append(getattr(ecodes, name))

        if layout.mouse:
            self.mouse_pos = {}
            for name in layout.mouse:
                events[ecodes.EV_REL].append(getattr(ecodes, name))

        self.device = UInput(name=layout.name, events=events,
                             bustype=layout.bustype, vendor=layout.vendor,
                             product=layout.product, version=layout.version)
        self.layout = layout

    def emit(self, report):
        for name, attr in self.layout.axes.items():
            name = getattr(ecodes, name)
            value = getattr(report, attr)
            self.device.write(ecodes.EV_ABS, name, value)

        for name, attr in self.layout.buttons.items():
            name = getattr(ecodes, name)
            if attr in self.ignored_buttons:
                value = False
            else:
                value = getattr(report, attr)
            self.device.write(ecodes.EV_KEY, name, value)

        for name, attr in self.layout.hats.items():
            name = getattr(ecodes, name)
            if getattr(report, attr[0]):
                value = -1
            elif getattr(report, attr[1]):
                value = 1
            else:
                value = 0

            self.device.write(ecodes.EV_ABS, name, value)

        if self.layout.mouse:
            self.emit_mouse(report)

        self.device.syn()

    def emit_mouse(self, report):
        for name, attr in self.layout.mouse.items():
            if attr.startswith("trackpad_touch"):
                active_attr = attr[:16] + "active"
                if not getattr(report, active_attr):
                    self.mouse_pos.pop(name, None)
                    continue

            pos = getattr(report, attr)
            if name not in self.mouse_pos:
                self.mouse_pos[name] = pos

            sensitivity = 0.5
            rel = (pos - self.mouse_pos[name]) * sensitivity
            self.device.write(ecodes.EV_REL, getattr(ecodes, name), int(rel))
            self.mouse_pos[name] = pos
Esempio n. 60
-3
def executaAcao(tecla):
        ui = UInput()
        print tecla
        ui.write(e.EV_KEY, e.ecodes[tecla], 1) #key down
        ui.write(e.EV_KEY, e.ecodes[tecla], 0) #key up
        ui.syn()
        ui.close()