code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
console.info('Creating context with name: {0}'.format(name)) res = zap_helper.zap.context.new_context(contextname=name) console.info('Context "{0}" created with ID: {1}'.format(name, res))
def context_new(zap_helper, name)
Create a new context.
3.382013
3.47925
0.972052
console.info('Including regex {0} in context with name: {1}'.format(pattern, name)) with zap_error_handler(): result = zap_helper.zap.context.include_in_context(contextname=name, regex=pattern) if result != 'OK': raise ZAPError('Including regex from context failed: {}'.format(result))
def context_include(zap_helper, name, pattern)
Include a pattern in a given context.
4.92065
4.705128
1.045806
console.info('Excluding regex {0} from context with name: {1}'.format(pattern, name)) with zap_error_handler(): result = zap_helper.zap.context.exclude_from_context(contextname=name, regex=pattern) if result != 'OK': raise ZAPError('Excluding regex from context failed: {}'.format(result))
def context_exclude(zap_helper, name, pattern)
Exclude a pattern from a given context.
4.454234
4.31201
1.032983
with zap_error_handler(): info = zap_helper.get_context_info(context_name) console.info('ID: {}'.format(info['id'])) console.info('Name: {}'.format(info['name'])) console.info('Authentication type: {}'.format(info['authType'])) console.info('Included regexes: {}'.format(info['includeRegexs'])) console.info('Excluded regexes: {}'.format(info['excludeRegexs']))
def context_info(zap_helper, context_name)
Get info about the given context.
2.61355
2.613784
0.999911
with zap_error_handler(): info = zap_helper.get_context_info(context_name) users = zap_helper.zap.users.users_list(info['id']) if len(users): user_list = ', '.join([user['name'] for user in users]) console.info('Available users for the context {0}: {1}'.format(context_name, user_list)) else: console.info('No users configured for the context {}'.format(context_name))
def context_list_users(zap_helper, context_name)
List the users available for a given context.
3.167642
3.045555
1.040087
with zap_error_handler(): result = zap_helper.zap.context.import_context(file_path) if not result.isdigit(): raise ZAPError('Importing context from file failed: {}'.format(result)) console.info('Imported context from {}'.format(file_path))
def context_import(zap_helper, file_path)
Import a saved context file.
4.429796
4.298279
1.030598
with zap_error_handler(): result = zap_helper.zap.context.export_context(name, file_path) if result != 'OK': raise ZAPError('Exporting context to file failed: {}'.format(result)) console.info('Exported context {0} to {1}'.format(name, file_path))
def context_export(zap_helper, name, file_path)
Export a given context to a file.
3.76941
3.613074
1.04327
if "." in key: return _get_value_for_keys(obj, key.split("."), default) else: return _get_value_for_key(obj, key, default)
def _get_value(obj, key, default=missing)
Slightly-modified version of marshmallow.utils.get_value. If a dot-delimited ``key`` is passed and any attribute in the path is `None`, return `None`.
2.902224
2.929841
0.990574
if isinstance(d, (tuple, list)): return [_rapply(each, func, *args, **kwargs) for each in d] if isinstance(d, dict): return { key: _rapply(value, func, *args, **kwargs) for key, value in iteritems(d) } else: return func(d, *args, **kwargs)
def _rapply(d, func, *args, **kwargs)
Apply a function to all values in a dictionary or list of dictionaries, recursively.
1.806785
1.741258
1.037632
if isinstance(val, URLFor): return val.serialize(key, obj, **kwargs) else: return val
def _url_val(val, key, obj, **kwargs)
Function applied by `HyperlinksField` to get the correct value in the schema.
5.481846
6.294133
0.870945
param_values = {} for name, attr_tpl in iteritems(self.params): attr_name = _tpl(str(attr_tpl)) if attr_name: attribute_value = _get_value(obj, attr_name, default=missing) if attribute_value is None: return None if attribute_value is not missing: param_values[name] = attribute_value else: raise AttributeError( "{attr_name!r} is not a valid " "attribute of {obj!r}".format(attr_name=attr_name, obj=obj) ) else: param_values[name] = attr_tpl return url_for(self.endpoint, **param_values)
def _serialize(self, value, key, obj)
Output the URL for the endpoint, given the kwargs passed to ``__init__``.
3.339758
3.366786
0.991972
for attr in base_fields.__all__: if not hasattr(obj, attr): setattr(obj, attr, getattr(base_fields, attr)) for attr in fields.__all__: setattr(obj, attr, getattr(fields, attr))
def _attach_fields(obj)
Attach all the marshmallow fields classes to ``obj``, including Flask-Marshmallow's custom fields.
2.64444
2.609644
1.013334
app.extensions = getattr(app, "extensions", {}) # If using Flask-SQLAlchemy, attach db.session to ModelSchema if has_sqla and "sqlalchemy" in app.extensions: db = app.extensions["sqlalchemy"].db self.ModelSchema.OPTIONS_CLASS.session = db.session app.extensions[EXTENSION_NAME] = self
def init_app(self, app)
Initializes the application with the extension. :param Flask app: The Flask application object.
5.568193
6.762403
0.823404
if many is sentinel: many = self.many if _MARSHMALLOW_VERSION_INFO[0] >= 3: data = self.dump(obj, many=many) else: data = self.dump(obj, many=many).data return flask.jsonify(data, *args, **kwargs)
def jsonify(self, obj, many=sentinel, *args, **kwargs)
Return a JSON response containing the serialized data. :param obj: Object to serialize. :param bool many: Whether `obj` should be serialized as an instance or as a collection. If unset, defaults to the value of the `many` attribute on this Schema. :param kwargs: Additional keyword arguments passed to `flask.jsonify`. .. versionchanged:: 0.6.0 Takes the same arguments as `marshmallow.Schema.dump`. Additional keyword arguments are passed to `flask.jsonify`. .. versionchanged:: 0.6.3 The `many` argument for this method defaults to the value of the `many` attribute on the Schema. Previously, the `many` argument of this method defaulted to False, regardless of the value of `Schema.many`.
2.450508
2.622198
0.934524
cstrings = [string.split("\n") for string in strings] max_num_lines = max(len(item) for item in cstrings) pp = [] for k in range(max_num_lines): p = [cstring[k] for cstring in cstrings] pp.append(join_char + join_char.join(p) + join_char) return "\n".join([p.rstrip() for p in pp])
def _hjoin_multiline(join_char, strings)
Horizontal join of multiline strings
3.137379
3.089825
1.015391
for i in range(0, len(raw), EVENT_SIZE): yield struct.unpack(EVENT_FORMAT, raw[i:i+EVENT_SIZE])
def chunks(raw)
Yield successive EVENT_SIZE sized chunks from raw.
3.280335
2.007276
1.634223
frac, whole = math.modf(seconds_since_epoch) microseconds = math.floor(frac * 1000000) seconds = math.floor(whole) return seconds, microseconds
def convert_timeval(seconds_since_epoch)
Convert time into C style timeval.
2.906332
2.762332
1.05213
# Quartz only on the mac, so don't warn about Quartz # pylint: disable=import-error import Quartz # pylint: disable=no-member class QuartzMouseListener(QuartzMouseBaseListener): def install_handle_input(self): # Keep Mac Names to make it easy to find the documentation # pylint: disable=invalid-name NSMachPort = Quartz.CGEventTapCreate( Quartz.kCGSessionEventTap, Quartz.kCGHeadInsertEventTap, Quartz.kCGEventTapOptionDefault, Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDown) | Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseUp) | Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDown) | Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseUp) | Quartz.CGEventMaskBit(Quartz.kCGEventMouseMoved) | Quartz.CGEventMaskBit(Quartz.kCGEventLeftMouseDragged) | Quartz.CGEventMaskBit(Quartz.kCGEventRightMouseDragged) | Quartz.CGEventMaskBit(Quartz.kCGEventScrollWheel) | Quartz.CGEventMaskBit(Quartz.kCGEventTabletPointer) | Quartz.CGEventMaskBit(Quartz.kCGEventTabletProximity) | Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDown) | Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseUp) | Quartz.CGEventMaskBit(Quartz.kCGEventOtherMouseDragged), self.handle_input, None) CFRunLoopSourceRef = Quartz.CFMachPortCreateRunLoopSource( None, NSMachPort, 0) CFRunLoopRef = Quartz.CFRunLoopGetCurrent() Quartz.CFRunLoopAddSource( CFRunLoopRef, CFRunLoopSourceRef, Quartz.kCFRunLoopDefaultMode) Quartz.CGEventTapEnable( NSMachPort, True) def listen(self): while self.active: Quartz.CFRunLoopRunInMode( Quartz.kCFRunLoopDefaultMode, 5, False) def uninstall_handle_input(self): self.active = False def _get_mouse_button_number(self, event): return Quartz.CGEventGetIntegerValueField( event, Quartz.kCGMouseEventButtonNumber) def _get_click_state(self, event): return Quartz.CGEventGetIntegerValueField( event, Quartz.kCGMouseEventClickState) def _get_scroll(self, event): scroll_y = Quartz.CGEventGetIntegerValueField( event, Quartz.kCGScrollWheelEventDeltaAxis1) scroll_x = Quartz.CGEventGetIntegerValueField( event, Quartz.kCGScrollWheelEventDeltaAxis2) return scroll_x, scroll_y def _get_absolute(self, event): return Quartz.CGEventGetLocation(event) def _get_relative(self, event): delta_x = Quartz.CGEventGetIntegerValueField( event, Quartz.kCGMouseEventDeltaX) delta_y = Quartz.CGEventGetIntegerValueField( event, Quartz.kCGMouseEventDeltaY) return delta_x, delta_y mouse = QuartzMouseListener(pipe) mouse.listen()
def quartz_mouse_process(pipe)
Single subprocess for reading mouse events on Mac using newer Quartz.
2.052624
2.040675
1.005855
# pylint: disable=import-error,too-many-locals # Note Objective C does not support a Unix style fork. # So these imports have to be inside the child subprocess since # otherwise the child process cannot use them. # pylint: disable=no-member, no-name-in-module from Foundation import NSObject from AppKit import NSApplication, NSApp from Cocoa import (NSEvent, NSLeftMouseDownMask, NSLeftMouseUpMask, NSRightMouseDownMask, NSRightMouseUpMask, NSMouseMovedMask, NSLeftMouseDraggedMask, NSRightMouseDraggedMask, NSMouseEnteredMask, NSMouseExitedMask, NSScrollWheelMask, NSOtherMouseDownMask, NSOtherMouseUpMask) from PyObjCTools import AppHelper import objc class MacMouseSetup(NSObject): @objc.python_method def init_with_handler(self, handler): # ALWAYS call the super's designated initializer. # Also, make sure to re-bind "self" just in case it # returns something else! # pylint: disable=self-cls-assignment self = super(MacMouseSetup, self).init() self.handler = handler # Unlike Python's __init__, initializers MUST return self, # because they are allowed to return any object! return self # pylint: disable=invalid-name, unused-argument def applicationDidFinishLaunching_(self, notification): mask = (NSLeftMouseDownMask | NSLeftMouseUpMask | NSRightMouseDownMask | NSRightMouseUpMask | NSMouseMovedMask | NSLeftMouseDraggedMask | NSRightMouseDraggedMask | NSScrollWheelMask | NSMouseEnteredMask | NSMouseExitedMask | NSOtherMouseDownMask | NSOtherMouseUpMask) NSEvent.addGlobalMonitorForEventsMatchingMask_handler_( mask, self.handler) class MacMouseListener(AppKitMouseBaseListener): def install_handle_input(self): self.app = NSApplication.sharedApplication() # pylint: disable=no-member delegate = MacMouseSetup.alloc().init_with_handler( self.handle_input) NSApp().setDelegate_(delegate) AppHelper.runEventLoop() def __del__(self): AppHelper.stopEventLoop() # pylint: disable=unused-variable mouse = MacMouseListener(pipe, events=[])
def appkit_mouse_process(pipe)
Single subprocess for reading mouse events on Mac using older AppKit.
3.751957
3.684724
1.018247
# pylint: disable=import-error,too-many-locals # Note Objective C does not support a Unix style fork. # So these imports have to be inside the child subprocess since # otherwise the child process cannot use them. # pylint: disable=no-member, no-name-in-module from AppKit import NSApplication, NSApp from Foundation import NSObject from Cocoa import (NSEvent, NSKeyDownMask, NSKeyUpMask, NSFlagsChangedMask) from PyObjCTools import AppHelper import objc class MacKeyboardSetup(NSObject): @objc.python_method def init_with_handler(self, handler): # ALWAYS call the super's designated initializer. # Also, make sure to re-bind "self" just in case it # returns something else! # pylint: disable=self-cls-assignment self = super(MacKeyboardSetup, self).init() self.handler = handler # Unlike Python's __init__, initializers MUST return self, # because they are allowed to return any object! return self # pylint: disable=invalid-name, unused-argument def applicationDidFinishLaunching_(self, notification): mask = NSKeyDownMask | NSKeyUpMask | NSFlagsChangedMask NSEvent.addGlobalMonitorForEventsMatchingMask_handler_( mask, self.handler) class MacKeyboardListener(AppKitKeyboardListener): def install_handle_input(self): self.app = NSApplication.sharedApplication() # pylint: disable=no-member delegate = MacKeyboardSetup.alloc().init_with_handler( self.handle_input) NSApp().setDelegate_(delegate) AppHelper.runEventLoop() def __del__(self): AppHelper.stopEventLoop() # pylint: disable=unused-variable keyboard = MacKeyboardListener(pipe)
def mac_keyboard_process(pipe)
Single subprocesses for reading keyboard on Mac.
4.850185
4.827495
1.0047
xinput = getattr(ctypes.windll, dll) time.sleep(duration/1000) xinput_set_state = xinput.XInputSetState xinput_set_state.argtypes = [ ctypes.c_uint, ctypes.POINTER(XinputVibration)] xinput_set_state.restype = ctypes.c_uint vibration = XinputVibration(0, 0) xinput_set_state(device_number, ctypes.byref(vibration))
def delay_and_stop(duration, dll, device_number)
Stop vibration aka force feedback aka rumble on Windows after duration miliseconds.
2.653566
2.4438
1.085836
if not timeval: self.update_timeval() timeval = self.timeval try: event_code = self.type_codes[event_type] except KeyError: raise UnknownEventType( "We don't know what kind of event a %s is." % event_type) event = struct.pack(EVENT_FORMAT, timeval[0], timeval[1], event_code, code, value) return event
def create_event_object(self, event_type, code, value, timeval=None)
Create an evdev style structure.
2.825553
2.868657
0.984974
if direction == 'x': code = 0x06 elif direction == 'z': # Not enitely sure if this exists code = 0x07 else: code = 0x08 if WIN: data = data // 120 return self.create_event_object( "Relative", code, data, timeval)
def emulate_wheel(self, data, direction, timeval)
Emulate rel values for the mouse wheel. In evdev, a single click forwards of the mouse wheel is 1 and a click back is -1. Windows uses 120 and -120. We floor divide the Windows number by 120. This is fine for the digital scroll wheels found on the vast majority of mice. It also works on the analogue ball on the top of the Apple mouse. What do the analogue scroll wheels found on 200 quid high end gaming mice do? If the lowest unit is 120 then we are okay. If they report changes of less than 120 units Windows, then this might be an unacceptable loss of precision. Needless to say, I don't have such a mouse to test one way or the other.
8.992509
7.869359
1.142724
return self.create_event_object( "Relative", key_code, value, timeval)
def emulate_rel(self, key_code, value, timeval)
Emulate the relative changes of the mouse cursor.
7.515693
6.961037
1.07968
scan_event = self.create_event_object( "Misc", 0x04, scan_code, timeval) key_event = self.create_event_object( "Key", key_code, value, timeval) return scan_event, key_event
def emulate_press(self, key_code, scan_code, value, timeval)
Emulate a button press. Currently supports 5 buttons. The Microsoft documentation does not define what happens with a mouse with more than five buttons, and I don't have such a mouse. From reading the Linux sources, I guess evdev can support up to 255 buttons. Therefore, I guess we could support more buttons quite easily, if we had any useful hardware.
3.494269
4.075068
0.857475
repeat_event = self.create_event_object( "Repeat", 2, value, timeval) return repeat_event
def emulate_repeat(self, value, timeval)
The repeat press of a key/mouse button, e.g. double click.
7.28412
5.672478
1.284116
x_event = self.create_event_object( "Absolute", 0x00, x_val, timeval) y_event = self.create_event_object( "Absolute", 0x01, y_val, timeval) return x_event, y_event
def emulate_abs(self, x_val, y_val, timeval)
Emulate the absolute co-ordinates of the mouse cursor.
2.858979
2.679396
1.067024
msg = MSG() ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0)
def listen()
Listen for keyboard input.
3.679585
3.296692
1.116145
cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int, WPARAM, LPARAM, ctypes.POINTER(KBDLLHookStruct)) return cmpfunc(self.handle_input)
def get_fptr(self)
Get the function pointer.
7.520774
6.587742
1.141632
self.pointer = self.get_fptr() self.hooked = ctypes.windll.user32.SetWindowsHookExA( 13, self.pointer, ctypes.windll.kernel32.GetModuleHandleW(None), 0 ) if not self.hooked: return False return True
def install_handle_input(self)
Install the hook.
3.915029
3.413736
1.146846
if self.hooked is None: return ctypes.windll.user32.UnhookWindowsHookEx(self.hooked) self.hooked = None
def uninstall_handle_input(self)
Remove the hook.
3.235301
2.621395
1.234191
value = WIN_KEYBOARD_CODES[wparam] scan_code = lparam.contents.scan_code vk_code = lparam.contents.vk_code self.update_timeval() events = [] # Add key event scan_key, key_event = self.emulate_press( vk_code, scan_code, value, self.timeval) events.append(scan_key) events.append(key_event) # End with a sync marker events.append(self.sync_marker(self.timeval)) # We are done self.write_to_pipe(events) return ctypes.windll.user32.CallNextHookEx( self.hooked, ncode, wparam, lparam)
def handle_input(self, ncode, wparam, lparam)
Process the key input.
5.145589
4.953414
1.038796
x_pos = lparam.contents.x_pos y_pos = lparam.contents.y_pos data = lparam.contents.mousedata # This is how we can distinguish mouse 1 from mouse 2 # extrainfo = lparam.contents.extrainfo # The way windows seems to do it is there is primary mouse # and all other mouses report as mouse 2 # Also useful later will be to support the flags field # flags = lparam.contents.flags # This shows if the event was from a real device or whether it # was injected somehow via software self.emulate_mouse(wparam, x_pos, y_pos, data) # Give back control to Windows to wait for and process the # next event return ctypes.windll.user32.CallNextHookEx( self.hooked, ncode, wparam, lparam)
def handle_input(self, ncode, wparam, lparam)
Process the key input.
7.781733
7.700971
1.010487
# Once again ignore Windows' relative time (since system # startup) and use the absolute time (since epoch i.e. 1st Jan # 1970). self.update_timeval() events = [] if key_code == 0x0200: # We have a mouse move alone. # So just pass through to below pass elif key_code == 0x020A: # We have a vertical mouse wheel turn events.append(self.emulate_wheel(data, 'y', self.timeval)) elif key_code == 0x020E: # We have a horizontal mouse wheel turn # https://msdn.microsoft.com/en-us/library/windows/desktop/ # ms645614%28v=vs.85%29.aspx events.append(self.emulate_wheel(data, 'x', self.timeval)) else: # We have a button press. # Distinguish the second extra button if key_code == 0x020B and data == 2: key_code = 0x020B2 elif key_code == 0x020C and data == 2: key_code = 0x020C2 # Get the mouse codes code, value, scan_code = self.mouse_codes[key_code] # Add in the press events scan_event, key_event = self.emulate_press( code, scan_code, value, self.timeval) events.append(scan_event) events.append(key_event) # Add in the absolute position of the mouse cursor x_event, y_event = self.emulate_abs(x_val, y_val, self.timeval) events.append(x_event) events.append(y_event) # End with a sync marker events.append(self.sync_marker(self.timeval)) # We are done self.write_to_pipe(events)
def emulate_mouse(self, key_code, x_val, y_val, data)
Emulate the ev codes using the data Windows has given us. Note that by default in Windows, to recognise a double click, you just notice two clicks in a row within a reasonablely short time period. However, if the application developer sets the application window's class style to CS_DBLCLKS, the operating system will notice the four button events (down, up, down, up), intercept them and then send a single key code instead. There are no such special double click codes on other platforms, so not obvious what to do with them. It might be best to just convert them back to four events. Currently we do nothing. ((0x0203, 'WM_LBUTTONDBLCLK'), (0x0206, 'WM_RBUTTONDBLCLK'), (0x0209, 'WM_MBUTTONDBLCLK'), (0x020D, 'WM_XBUTTONDBLCLK'))
3.5979
3.540208
1.016296
# 0 for left # 1 for right # 2 for middle/center # 3 for side mouse_button_number = self._get_mouse_button_number(event) # Identify buttons 3,4,5 if event_type in (25, 26): event_type = event_type + (mouse_button_number * 0.1) # Add buttons to events event_type_string, event_code, value, scan = self.codes[event_type] if event_type_string == "Key": scan_event, key_event = self.emulate_press( event_code, scan, value, self.timeval) self.events.append(scan_event) self.events.append(key_event) # doubleclick/n-click of button click_state = self._get_click_state(event) repeat = self.emulate_repeat(click_state, self.timeval) self.events.append(repeat)
def handle_button(self, event, event_type)
Convert the button information from quartz into evdev format.
4.930861
4.771038
1.033499
# relative Scrollwheel scroll_x, scroll_y = self._get_scroll(event) if scroll_x: self.events.append( self.emulate_wheel(scroll_x, 'x', self.timeval)) if scroll_y: self.events.append( self.emulate_wheel(scroll_y, 'y', self.timeval))
def handle_scrollwheel(self, event)
Handle the scrollwheel (it is a ball on the mighty mouse).
4.020021
3.934023
1.02186
(x_val, y_val) = self._get_absolute(event) x_event, y_event = self.emulate_abs( int(x_val), int(y_val), self.timeval) self.events.append(x_event) self.events.append(y_event)
def handle_absolute(self, event)
Absolute mouse position on the screen.
4.282457
3.939492
1.087058
delta_x, delta_y = self._get_relative(event) if delta_x: self.events.append( self.emulate_rel(0x00, delta_x, self.timeval)) if delta_y: self.events.append( self.emulate_rel(0x01, delta_y, self.timeval))
def handle_relative(self, event)
Relative mouse movement.
3.501132
3.321868
1.053965
self.update_timeval() self.events = [] if event_type in (1, 2, 3, 4, 25, 26, 27): self.handle_button(event, event_type) if event_type == 22: self.handle_scrollwheel(event) # Add in the absolute position of the mouse cursor self.handle_absolute(event) # Add in the relative position of the mouse cursor self.handle_relative(event) # End with a sync marker self.events.append(self.sync_marker(self.timeval)) # We are done self.write_to_pipe(self.events)
def handle_input(self, proxy, event_type, event, refcon)
Handle an input event.
4.122465
4.025911
1.023983
delta_x = round(event.deltaX()) delta_y = round(event.deltaY()) delta_z = round(event.deltaZ()) return delta_x, delta_y, delta_z
def _get_deltas(event)
Get the changes from the appkit event.
2.376679
2.107238
1.127865
mouse_button_number = self._get_mouse_button_number(event) # Identify buttons 3,4,5 if event_type in (25, 26): event_type = event_type + (mouse_button_number * 0.1) # Add buttons to events event_type_name, event_code, value, scan = self.codes[event_type] if event_type_name == "Key": scan_event, key_event = self.emulate_press( event_code, scan, value, self.timeval) self.events.append(scan_event) self.events.append(key_event)
def handle_button(self, event, event_type)
Handle mouse click.
4.938295
4.772997
1.034632
point = self._get_absolute(event) x_pos = round(point.x) y_pos = round(point.y) x_event, y_event = self.emulate_abs(x_pos, y_pos, self.timeval) self.events.append(x_event) self.events.append(y_event)
def handle_absolute(self, event)
Absolute mouse position on the screen.
4.013962
3.614331
1.110569
delta_x, delta_y, delta_z = self._get_deltas(event) if delta_x: self.events.append( self.emulate_wheel(delta_x, 'x', self.timeval)) if delta_y: self.events.append( self.emulate_wheel(delta_y, 'y', self.timeval)) if delta_z: self.events.append( self.emulate_wheel(delta_z, 'z', self.timeval))
def handle_scrollwheel(self, event)
Make endev from appkit scroll wheel event.
2.297653
2.233997
1.028494
delta_x, delta_y, delta_z = self._get_deltas(event) if delta_x: self.events.append( self.emulate_rel(0x00, delta_x, self.timeval)) if delta_y: self.events.append( self.emulate_rel(0x01, delta_y, self.timeval)) if delta_z: self.events.append( self.emulate_rel(0x02, delta_z, self.timeval))
def handle_relative(self, event)
Get the position of the mouse on the screen.
2.424166
2.417863
1.002607
self.update_timeval() self.events = [] code = self._get_event_type(event) # Deal with buttons self.handle_button(event, code) # Mouse wheel if code == 22: self.handle_scrollwheel(event) # Other relative mouse movements else: self.handle_relative(event) # Add in the absolute position of the mouse cursor self.handle_absolute(event) # End with a sync marker self.events.append(self.sync_marker(self.timeval)) # We are done self.write_to_pipe(self.events)
def handle_input(self, event)
Process the mouse event.
6.091667
5.816135
1.047374
if event_type == 10: value = 1 elif event_type == 11: value = 0 elif event_type == 12: value = self._get_flag_value(event) else: value = -1 return value
def _get_key_value(self, event, event_type)
Get the key value.
2.784922
2.563125
1.086534
self.update_timeval() self.events = [] code = self._get_event_key_code(event) if code in self.codes: new_code = self.codes[code] else: new_code = 0 event_type = self._get_event_type(event) value = self._get_key_value(event, event_type) scan_event, key_event = self.emulate_press( new_code, code, value, self.timeval) self.events.append(scan_event) self.events.append(key_event) # End with a sync marker self.events.append(self.sync_marker(self.timeval)) # We are done self.write_to_pipe(self.events)
def handle_input(self, event)
Process they keyboard input.
4.302382
4.205549
1.023025
long_identifier = self._device_path.split('/')[4] protocol, remainder = long_identifier.split('-', 1) identifier, _, device_type = remainder.rsplit('-', 2) return (protocol, identifier, device_type)
def _get_path_infomation(self)
Get useful infomation from the device path.
6.30066
4.737284
1.330015
if self.read_size: read_size = EVENT_SIZE * self.read_size else: read_size = EVENT_SIZE return read_size
def _get_total_read_size(self)
How much event data to process at once.
4.382607
3.185424
1.375831
event_type = self.manager.get_event_type(ev_type) eventinfo = { "ev_type": event_type, "state": value, "timestamp": tv_sec + (tv_usec / 1000000), "code": self.manager.get_event_string(event_type, code) } return InputEvent(self, eventinfo)
def _make_event(self, tv_sec, tv_usec, ev_type, code, value)
Create a friendly Python object from an evdev style event.
3.446446
3.122564
1.103723
if self._evdev: return None if not self.__pipe: target_function = self._get_target_function() if not target_function: return None self.__pipe, child_conn = Pipe(duplex=False) self._listener = Process(target=target_function, args=(child_conn,), daemon=True) self._listener.start() return self.__pipe
def _pipe(self)
On Windows we use a pipe to emulate a Linux style character buffer.
4.057148
3.839104
1.056796
if NIX: return super(Keyboard, self)._get_data(read_size) return self._pipe.recv_bytes()
def _get_data(self, read_size)
Get data from the character device.
11.24156
8.589618
1.308738
if NIX: return super(Mouse, self)._get_data(read_size) return self._pipe.recv_bytes()
def _get_data(self, read_size)
Get data from the character device.
11.327472
8.834011
1.282257
js_path = self._device_path.replace('-event', '') js_chardev = os.path.realpath(js_path) try: number_text = js_chardev.split('js')[1] except IndexError: return try: number = int(number_text) except ValueError: return self.__device_number = number
def _number_xpad(self)
Get the number of the joystick.
6.612404
5.46695
1.209523
state = self.__read_device() if not state: raise UnpluggedError( "Gamepad %d is not connected" % self.__device_number) if state.packet_number != self.__last_state.packet_number: # state has changed, handle the change self.__handle_changed_state(state) self.__last_state = state
def __check_state(self)
On Windows, check the state and fill the event character device.
5.201456
4.645361
1.11971
if not timeval: timeval = self.__get_timeval() try: event_code = self.manager.codes['type_codes'][event_type] except KeyError: raise UnknownEventType( "We don't know what kind of event a %s is." % event_type) event = struct.pack(EVENT_FORMAT, timeval[0], timeval[1], event_code, code, value) return event
def create_event_object(self, event_type, code, value, timeval=None)
Create an evdev style object.
3.26891
3.378635
0.967524
# Remember the position of the stream pos = self._character_device.tell() # Go to the end of the stream self._character_device.seek(0, 2) # Write the new data to the end for event in event_list: self._character_device.write(event) # Add a sync marker sync = self.create_event_object("Sync", 0, 0, timeval) self._character_device.write(sync) # Put the stream back to its original position self._character_device.seek(pos)
def __write_to_character_device(self, event_list, timeval=None)
Emulate the Linux character device on other platforms such as Windows.
3.304067
3.304011
1.000017
timeval = self.__get_timeval() events = self.__get_button_events(state, timeval) events.extend(self.__get_axis_events(state, timeval)) if events: self.__write_to_character_device(events, timeval)
def __handle_changed_state(self, state)
we need to pack a struct with the following five numbers: tv_sec, tv_usec, ev_type, code, value then write it using __write_to_character_device seconds, mircroseconds, ev_type, code, value time we just use now ev_type we look up code we look up value is 0 or 1 for the buttons axis value is maybe the same as Linux? Hope so!
4.718544
3.287682
1.435219
_, start_code, start_value = button value = start_value ev_type = "Key" code = self.manager.codes['xpad'][start_code] if 1 <= start_code <= 4: ev_type = "Absolute" if start_code == 1 and start_value == 1: value = -1 elif start_code == 3 and start_value == 1: value = -1 return code, value, ev_type
def __map_button(self, button)
Get the linux xpad code from the Windows xinput code.
4.535906
3.826613
1.185358
start_code, start_value = axis value = start_value code = self.manager.codes['xpad'][start_code] return code, value
def __map_axis(self, axis)
Get the linux xpad code from the Windows xinput code.
13.868705
6.859156
2.021926
changed_buttons = self.__detect_button_events(state) events = self.__emulate_buttons(changed_buttons, timeval) return events
def __get_button_events(self, state, timeval=None)
Get the button events from xinput.
5.807684
5.46781
1.062159
axis_changes = self.__detect_axis_events(state) events = self.__emulate_axis(axis_changes, timeval) return events
def __get_axis_events(self, state, timeval=None)
Get the stick events from xinput.
5.760212
5.676331
1.014777
events = [] for axis in axis_changes: code, value = self.__map_axis(axis) event = self.create_event_object( "Absolute", code, value, timeval=timeval) events.append(event) return events
def __emulate_axis(self, axis_changes, timeval=None)
Make the axis events use the Linux style format.
4.033557
3.603242
1.119425
events = [] for button in changed_buttons: code, value, ev_type = self.__map_button(button) event = self.create_event_object( ev_type, code, value, timeval=timeval) events.append(event) return events
def __emulate_buttons(self, changed_buttons, timeval=None)
Make the button events use the Linux style format.
3.578553
3.290546
1.087526
res = list(self.__gen_bit_values(number)) res.reverse() # 0-pad the most significant bit res = [0] * (size - len(res)) + res return res
def __get_bit_values(self, number, size=32)
Get bit values as a list for a given number >>> get_bit_values(1) == [0]*31 + [1] True >>> get_bit_values(0xDEADBEEF) [1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L] You may override the default word size of 32-bits to match your actual application. >>> get_bit_values(0x3, 2) [1L, 1L] >>> get_bit_values(0x3, 4) [0L, 0L, 1L, 1L]
4.945362
7.064464
0.700034
state = XinputState() res = self.manager.xinput.XInputGetState( self.__device_number, ctypes.byref(state)) if res == XINPUT_ERROR_SUCCESS: return state if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED: raise RuntimeError( "Unknown error %d attempting to get state of device %d" % ( res, self.__device_number)) # else (device is not connected) return None
def __read_device(self)
Read the state of the gamepad.
4.150308
3.753345
1.105762
xinput_set_state = self.manager.xinput.XInputSetState xinput_set_state.argtypes = [ ctypes.c_uint, ctypes.POINTER(XinputVibration)] xinput_set_state.restype = ctypes.c_uint vibration = XinputVibration( int(left_motor * 65535), int(right_motor * 65535)) xinput_set_state(self.__device_number, ctypes.byref(vibration))
def _start_vibration_win(self, left_motor, right_motor)
Start the vibration, which will run until stopped.
3.115516
3.092477
1.00745
xinput_set_state = self.manager.xinput.XInputSetState xinput_set_state.argtypes = [ ctypes.c_uint, ctypes.POINTER(XinputVibration)] xinput_set_state.restype = ctypes.c_uint stop_vibration = ctypes.byref(XinputVibration(0, 0)) xinput_set_state(self.__device_number, stop_vibration)
def _stop_vibration_win(self)
Stop the vibration.
3.816259
3.525315
1.08253
self._start_vibration_win(left_motor, right_motor) stop_process = Process(target=delay_and_stop, args=(duration, self.manager.xinput_dll, self.__device_number)) stop_process.start()
def _set_vibration_win(self, left_motor, right_motor, duration)
Control the motors on Windows.
7.07515
6.835594
1.035045
inner_event = struct.pack( '2h6x2h2x2H28x', 0x50, -1, duration, 0, int(left_motor * 65535), int(right_motor * 65535)) buf_conts = ioctl(self._write_device, 1076905344, inner_event) return int(codecs.encode(buf_conts[1:3], 'hex'), 16)
def __get_vibration_code(self, left_motor, right_motor, duration)
This is some crazy voodoo, if you can simplify it, please do.
5.540098
5.390866
1.027682
code = self.__get_vibration_code(left_motor, right_motor, duration) secs, msecs = convert_timeval(time.time()) outer_event = struct.pack(EVENT_FORMAT, secs, msecs, 0x15, code, 1) self._write_device.write(outer_event) self._write_device.flush()
def _set_vibration_nix(self, left_motor, right_motor, duration)
Control the motors on Linux. Duration is in miliseconds.
5.668537
5.630414
1.006771
if WIN: self._set_vibration_win(left_motor, right_motor, duration) elif NIX: self._set_vibration_nix(left_motor, right_motor, duration) else: raise NotImplementedError
def set_vibration(self, left_motor, right_motor, duration)
Control the speed of both motors seperately or together. left_motor and right_motor arguments require a number between 0 (off) and 1 (full). duration is miliseconds, e.g. 1000 for a second.
2.397475
2.58291
0.928207
status_filename = os.path.join(self.path, 'max_brightness') with open(status_filename) as status_fp: result = status_fp.read() status_text = result.strip() try: status = int(status_text) except ValueError: return status_text return status
def max_brightness(self)
Get the device's maximum brightness level.
3.618191
3.303147
1.095377
if not self._write_file: if not NIX: return None try: self._write_file = io.open( self._character_device_path, 'wb') except PermissionError: # Python 3 raise PermissionError(PERMISSIONS_ERROR_TEXT) except IOError as err: # Python 2 only if err.errno == 13: # pragma: no cover raise PermissionError(PERMISSIONS_ERROR_TEXT) else: raise return self._write_file
def _write_device(self)
The output device.
4.150392
3.804034
1.09105
secs, msecs = convert_timeval(time.time()) data = struct.pack(EVENT_FORMAT, secs, msecs, event_type, code, value) self._write_device.write(data) self._write_device.flush()
def _make_event(self, event_type, code, value)
Make a new event and send it to the character device.
4.298486
3.778768
1.137536
self._led_type_code = self.manager.get_typecode('LED') self.device_path = os.path.realpath(os.path.join(self.path, 'device')) if '::' in self.name: chardev, code_name = self.name.split('::') if code_name in self.manager.codes['LED_type_codes']: self.code = self.manager.codes['LED_type_codes'][code_name] try: event_number = chardev.split('input')[1] except IndexError: print("Failed with", self.name) raise else: self._character_device_path = '/dev/input/event' + event_number self._match_device()
def _post_init(self)
Set up the device path and type code.
5.136889
4.577518
1.1222
def _make_event(self, value): # pylint: disable=arguments-differ super(SystemLED, self)._make_event( self._led_type_code, self.code, value)
Make a new event and send it to the character device.
null
null
null
for device in self.manager.all_devices: if (device.get_char_device_path() == self._character_device_path): self.device = device device.leds.append(self) break
def _match_device(self)
If the LED is connected to an input device, associate the objects.
6.897842
5.207258
1.324659
if WIN: self._find_devices_win() elif MAC: self._find_devices_mac() else: self._find_devices() self._update_all_devices() if NIX: self._find_leds()
def _post_init(self)
Call the find devices method for the relevant platform.
5.830817
3.83116
1.521946
self.all_devices = [] self.all_devices.extend(self.keyboards) self.all_devices.extend(self.mice) self.all_devices.extend(self.gamepads) self.all_devices.extend(self.other_devices)
def _update_all_devices(self)
Update the all_devices list.
2.300272
1.926256
1.194168
# 1. Make sure that we can parse the device path. try: device_type = device_path.rsplit('-', 1)[1] except IndexError: warn("The following device path was skipped as it could " "not be parsed: %s" % device_path, RuntimeWarning) return # 2. Make sure each device is only added once. realpath = os.path.realpath(device_path) if realpath in self._raw: return self._raw.append(realpath) # 3. All seems good, append the device to the relevant list. if device_type == 'kbd': self.keyboards.append(Keyboard(self, device_path, char_path_override)) elif device_type == 'mouse': self.mice.append(Mouse(self, device_path, char_path_override)) elif device_type == 'joystick': self.gamepads.append(GamePad(self, device_path, char_path_override)) else: self.other_devices.append(OtherDevice(self, device_path, char_path_override))
def _parse_device_path(self, device_path, char_path_override=None)
Parse each device and add to the approriate list.
2.682596
2.585675
1.037484
for dll in XINPUT_DLL_NAMES: try: self.xinput = getattr(ctypes.windll, dll) except OSError: pass else: # We found an xinput driver self.xinput_dll = dll break else: # We didn't find an xinput library warn( "No xinput driver dll found, gamepads not supported.", RuntimeWarning)
def _find_xinput(self)
Find most recent xinput library.
4.555227
4.256048
1.070295
self._find_xinput() self._detect_gamepads() self._count_devices() if self._raw_device_counts['keyboards'] > 0: self.keyboards.append(Keyboard( self, "/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd")) if self._raw_device_counts['mice'] > 0: self.mice.append(Mouse( self, "/dev/input/by-id/usb-A_Nice_Mouse_called_Arthur-event-mouse"))
def _find_devices_win(self)
Find devices on Windows.
4.196503
4.162168
1.008249
self.keyboards.append(Keyboard(self)) self.mice.append(MightyMouse(self)) self.mice.append(Mouse(self))
def _find_devices_mac(self)
Find devices on Mac.
5.356867
4.561016
1.17449
state = XinputState() # Windows allows up to 4 gamepads. for device_number in range(4): res = self.xinput.XInputGetState( device_number, ctypes.byref(state)) if res == XINPUT_ERROR_SUCCESS: # We found a gamepad device_path = ( "/dev/input/by_id/" + "usb-Microsoft_Corporation_Controller_%s-event-joystick" % device_number) self.gamepads.append(GamePad(self, device_path)) continue if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED: raise RuntimeError( "Unknown error %d attempting to get state of device %d" % (res, device_number))
def _detect_gamepads(self)
Find gamepads.
4.393589
4.235354
1.037361
number_of_devices = ctypes.c_uint() if ctypes.windll.user32.GetRawInputDeviceList( ctypes.POINTER(ctypes.c_int)(), ctypes.byref(number_of_devices), ctypes.sizeof(RawInputDeviceList)) == -1: warn("Call to GetRawInputDeviceList was unsuccessful." "We have no idea if a mouse or keyboard is attached.", RuntimeWarning) return devices_found = (RawInputDeviceList * number_of_devices.value)() if ctypes.windll.user32.GetRawInputDeviceList( devices_found, ctypes.byref(number_of_devices), ctypes.sizeof(RawInputDeviceList)) == -1: warn("Call to GetRawInputDeviceList was unsuccessful." "We have no idea if a mouse or keyboard is attached.", RuntimeWarning) return for device in devices_found: if device.dwType == 0: self._raw_device_counts['mice'] += 1 elif device.dwType == 1: self._raw_device_counts['keyboards'] += 1 elif device.dwType == 2: self._raw_device_counts['otherhid'] += 1 else: self._raw_device_counts['unknown'] += 1
def _count_devices(self)
See what Windows' GetRawInputDeviceList wants to tell us. For now, we are just seeing if there is at least one keyboard and/or mouse attached. GetRawInputDeviceList could be used to help distinguish between different keyboards and mice on the system in the way Linux can. However, Roma uno die non est condita.
2.36867
2.123247
1.115588
by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key)) for device_path in by_path: self._parse_device_path(device_path)
def _find_by(self, key)
Find devices.
5.829183
5.183161
1.124639
charnames = self._get_char_names() for eventdir in glob.glob('/sys/class/input/event*'): char_name = os.path.split(eventdir)[1] if char_name in charnames: continue name_file = os.path.join(eventdir, 'device', 'name') with open(name_file) as name_file: device_name = name_file.read().strip() if device_name in self.codes['specials']: self._parse_device_path( self.codes['specials'][device_name], os.path.join('/dev/input', char_name))
def _find_special(self)
Look for special devices.
3.28675
3.071805
1.069974
if WIN and evtype == 'Key': # If we can map the code to a common one then do it try: code = self.codes['wincodes'][code] except KeyError: pass try: return self.codes[evtype][code] except KeyError: raise UnknownEventCode("We don't know this event.", evtype, code)
def get_event_string(self, evtype, code)
Get the string name of the event.
6.324956
6.405153
0.987479
try: gpad = MicroBitPad(self) except ModuleNotFoundError: warn( "The microbit library could not be found in the pythonpath. \n" "For more information, please visit \n" "https://inputs.readthedocs.io/en/latest/user/microbit.html", RuntimeWarning) else: self.microbits.append(gpad) self.gamepads.append(gpad)
def detect_microbit(self)
Detect a microbit.
4.833882
4.897276
0.987055
# pylint: disable=no-member if index: image = self.microbit.Image.STD_IMAGES[index] else: image = self.default_image self.microbit.display.show(image)
def set_display(self, index=None)
Show an image on the display.
5.894104
5.206373
1.132094
self.left_rumble = self._get_ready_to('99500') self.right_rumble = self._get_ready_to('00599') self.double_rumble = self._get_ready_to('99599')
def _setup_rumble(self)
Setup the three animations which simulate a rumble.
4.869462
3.851462
1.264315
# pylint: disable=no-member return [self.microbit.Image(':'.join( [rumble if char == '1' else '00500' for char in code])) for code in SPIN_UP_MOTOR]
def _get_ready_to(self, rumble)
Watch us wreck the mike! PSYCHE!
16.022324
14.731172
1.087648
while duration > 0: self.microbit.display.show(images[0]) # pylint: disable=no-member time.sleep(0.04) self.microbit.display.show(images[1]) # pylint: disable=no-member time.sleep(0.04) duration -= 0.08
def _full_speed_rumble(self, images, duration)
Simulate the motors running at full.
2.147835
2.145923
1.000891
total = 0 # pylint: disable=no-member for image in images: self.microbit.display.show(image) time.sleep(0.05) total += 0.05 if total >= duration: return remaining = duration - total self._full_speed_rumble(images[-2:], remaining) self.set_display()
def _spin_up(self, images, duration)
Simulate the motors getting warmed up.
5.577645
5.157049
1.081558
if left_motor and right_motor: return self._spin_up(self.double_rumble, duration/1000) if left_motor: return self._spin_up(self.left_rumble, duration/1000) if right_motor: return self._spin_up(self.right_rumble, duration/1000) return -1
def set_vibration(self, left_motor, right_motor, duration)
Control the speed of both motors seperately or together. left_motor and right_motor arguments require a number: 0 (off) or 1 (full). duration is miliseconds, e.g. 1000 for a second.
2.679235
2.685603
0.997629
for event in events: self.events.append( self.create_event_object( event[0], event[1], int(event[2])))
def handle_new_events(self, events)
Add each new events to the event queue.
4.173106
3.7913
1.100706
# pylint: disable=no-member x_raw = self.microbit.accelerometer.get_x() y_raw = self.microbit.accelerometer.get_y() x_abs = ('Absolute', 0x00, x_raw) y_abs = ('Absolute', 0x01, y_raw) return x_abs, y_abs
def handle_abs(self)
Gets the state as the raw abolute numbers.
3.475924
3.06093
1.135578
# pylint: disable=no-member x_raw = self.microbit.accelerometer.get_x() y_raw = self.microbit.accelerometer.get_y() minus_sens = self.sensitivity * -1 if x_raw < minus_sens: x_state = ('Absolute', 0x10, -1) elif x_raw > self.sensitivity: x_state = ('Absolute', 0x10, 1) else: x_state = ('Absolute', 0x10, 0) if y_raw < minus_sens: y_state = ('Absolute', 0x11, -1) elif y_raw > self.sensitivity: y_state = ('Absolute', 0x11, 1) else: y_state = ('Absolute', 0x11, 1) return x_state, y_state
def handle_dpad(self)
Gets the state of the virtual dpad.
2.164242
2.141927
1.010418
if self.dpad: x_state, y_state = self.handle_dpad() else: x_state, y_state = self.handle_abs() # pylint: disable=no-member new_state = set(( x_state, y_state, ('Key', 0x130, int(self.microbit.button_a.is_pressed())), ('Key', 0x131, int(self.microbit.button_b.is_pressed())), ('Key', 0x13a, int(self.microbit.pin0.is_touched())), ('Key', 0x133, int(self.microbit.pin1.is_touched())), ('Key', 0x134, int(self.microbit.pin2.is_touched())), )) events = new_state - self.state self.state = new_state return events
def check_state(self)
Tracks differences in the device state.
2.727758
2.632026
1.036372