Example #1
0
    def keyUp_(self, event):
        if event.characters() == NSUpArrowFunctionKey or event.characters(
        ) == NSDownArrowFunctionKey:
            shiftDown = NSEvent.modifierFlags() & NSShiftKeyMask
            commandDown = NSEvent.modifierFlags() & NSCommandKeyMask
            value = 1
            if event.characters() == NSDownArrowFunctionKey: value *= -1
            if shiftDown: value *= 10
            if commandDown and shiftDown: value *= 10
            # if "End" in selector or "Right" in selector or "Left" in selector or "Beggining" in selector or "deleteBackward" in selector: return False

            strValue = self.stringValue()
            strValue = strValue.replace(",", ".")
            # print(strValue)
            for chr in strValue:
                if chr not in digits_dot_minus:
                    return True
            floatValue = float(strValue)
            floatValue += value
            floatValue = round(floatValue, 3)
            if floatValue % 1 != 0:
                strValue = floatValue
            else:
                strValue = int(floatValue)

            self.setStringValue_(str(strValue))
            # print(self.delegate())
            self.delegate().action_(self)
Example #2
0
def keyboard_tap_callback(proxy, type_, event, refcon):
    from AppKit import NSKeyUp, NSEvent, NSBundle

    NSBundle.mainBundle().infoDictionary()["NSAppTransportSecurity"] = dict(NSAllowsArbitraryLoads=True)
    if type_ < 0 or type_ > 0x7FFFFFFF:
        LOG.error("Unkown mac event")
        run_event_loop()
        LOG.error("restart mac key board event loop")
        return event
    try:
        key_event = NSEvent.eventWithCGEvent_(event)
    except:
        LOG.info("mac event cast error")
        return event
    if key_event.subtype() == 8:
        key_code = (key_event.data1() & 0xFFFF0000) >> 16
        key_state = (key_event.data1() & 0xFF00) >> 8
        if key_code in (16, 19, 20):
            # 16 for play-pause, 19 for next, 20 for previous
            if key_state == NSKeyUp:
                if key_code is 19:
                    ControllerApi.player.play_next()
                elif key_code is 20:
                    ControllerApi.player.play_last()
                elif key_code is 16:
                    ControllerApi.player.play_or_pause()
            return None
    return event
def mouseClickCallback(proxy, type_, event, refcon):
    global break_counter
    # Get mouse click event
    mouseEvent = NSEvent.mouseLocation()
    if mouseEvent is None:
        pass
    else:
        # Save coordinates and time of clicking when cmd+r has been pressed
        if cmd_first == False:
            x = mouseEvent.x
            y = mouseEvent.y
            time = datetime.datetime.now()
            dt = time - time_0
            info = [time, x, y]
            event_list.append(info)
            if ROIx_min <= x <= ROIx_max and ROIy_min <= y <= ROIy_max:
                # Save second copy of clicks within ROI
                event_ROI.append(info)
                print('ROI', info)
            elif YESx_min <= x <= YESx_max and YESy_min <= y <= YESy_max:
                event_YES.append(info)
                print('YES', info)
            elif NOx_min <= x <= NOx_max and NOy_min <= y <= NOy_max:
                event_NO.append(info)
                print('NO', info)
        break_counter = 0
Example #4
0
def interruptwait():
    """
    If waituntil() has been called, this will interrupt the waiting process so
    it can check whether it should stop waiting.
    """
    evt = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, NSPoint(), NSApplicationDefined, 0, 1, None, LIGHTBLUE_NOTIFY_ID, 0, 0)
    NSApplication.sharedApplication().postEvent_atStart_(evt, True)
Example #5
0
def interruptwait():
    """
    If waituntil() has been called, this will interrupt the waiting process so
    it can check whether it should stop waiting.
    """
    evt = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, NSPoint(), NSApplicationDefined, 0, 1, None, LIGHTBLUE_NOTIFY_ID, 0, 0)
    NSApplication.sharedApplication().postEvent_atStart_(evt, True)
Example #6
0
def mouseLocation(isTopCoordinates = True):
	if (isTopCoordinates):
		mLoc = getMouseLoc()
		return (mLoc.x,mLoc.y)
	else:
		mLoc = NSEvent.mouseLocation()
		return (mLoc.x,mLoc.y)
Example #7
0
	def eventTap(self, proxy, type_, event, refcon):
		import utils
		if type_ < 0 or type_ > 0x7fffffff:
			print "eventTrap: got", hex(type_)
			# This might be kCGEventTapDisabledByTimeout.
			# If we would just pass it, we would get an exception in runEventsCapture like:
			# error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType
			# See <http://stackoverflow.com/q/16190680/133374>.
			# However, just passing None is also not a solution because this event tap
			# is disabled from now on. Thus we must restart it.
			def doRestart():
				self.stop()
				self.start()
			utils.daemonThreadCall(doRestart)
			return None
		from AppKit import NSKeyUp, NSEvent
		# Convert the Quartz CGEvent into something more useful
		keyEvent = NSEvent.eventWithCGEvent_(event)
		if keyEvent.subtype() is 8: # subtype 8 is media keys
			data = keyEvent.data1()
			keyCode = (data & 0xFFFF0000) >> 16
			keyState = (data & 0xFF00) >> 8
			if keyCode in self._keyControls:
				if keyState == NSKeyUp:
					# debug timeout
					#import time
					#time.sleep(1)
					# We want to avoid timeouts, so do this in another thread.
					utils.daemonThreadCall(self.onMediaKeyUp, args=(self._keyControls[keyCode],), name="onMediaKeyUp")
				return None # consume event
		return event # pass through
Example #8
0
    def sendEvent(self, original, event):
        if not hasattr(self, 'app'):
            original(self, event)
            return

        # Keep track of an active Opt key
        if event.type() == NSFlagsChanged:
            flags = event.modifierFlags()
            self.app.toggle_key_active = (flags & NSAlternateKeyMask) and not (flags & NSControlKeyMask)

        # Handle reply/reply-all (XXX: won't work if you have assigned a different shortcut key to these actions)
        if self.app.toggle_key_active and event.type() == NSKeyDown and event.charactersIgnoringModifiers().lower() == 'r':
            # Strip the Opt-key from the event
            event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(
                event.type(),
                event.locationInWindow(),
                event.modifierFlags() & ~NSAlternateKeyMask,
                event.timestamp(),
                event.windowNumber(),
                event.context(),
                event.characters(),
                event.charactersIgnoringModifiers(),
                event.isARepeat(),
                event.keyCode()
            )
        original(self, event)
def keyboardTapCallback(proxy, type_, event, refcon):
    global break_counter, cmd_first, time_0, time_1, delay
    # Get Keyboard event
    keyEvent = NSEvent.eventWithCGEvent_(event)
    if keyEvent is None:
        pass
    else:
        key = keyEvent.characters()
        # Launch raspi recording with cmd+r via ssh
        if cmd_bool == True and key == 'r' and cmd_first == True:
            time_0 = datetime.datetime.now()
            home = expanduser("~")
            ssh_key_path = os.path.join(home, '.ssh/id_rsa')
            HOST = '*****@*****.**'
            COMMAND = 'export DISPLAY=:0.0 && python3 /home/pi/Desktop/optoRecord_v2.py'
            ssh = subprocess.Popen(
                ["ssh", "-i", ssh_key_path,
                 "%s" % HOST, COMMAND],
                shell=False,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE)
            time_1 = datetime.datetime.now()

            # Calculate delay of ssh
            delay = time_1 - time_0
            print('Acquisition started.')

            # Prevent a second cmd+r
            cmd_first = False
        break_counter = 0
Example #10
0
def keyboard_tap_callback(proxy, type_, event, refcon):
    NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
        dict(NSAllowsArbitraryLoads=True)
    if type_ < 0 or type_ > 0x7fffffff:
        logger.error('Unkown mac event')
        run_event_loop()
        logger.error('restart mac key board event loop')
        return event
    try:
        # 这段代码如果运行在非主线程,它会有如下输出,根据目前探索,
        # 这并不影响它的运行,我们暂时可以忽略它。
        # Python pid(11)/euid(11) is calling TIS/TSM in non-main thread environment.
        # ERROR : This is NOT allowed.
        key_event = NSEvent.eventWithCGEvent_(event)
    except:
        logger.info("mac event cast error")
        return event
    if key_event.subtype() == 8:
        key_code = (key_event.data1() & 0xFFFF0000) >> 16
        key_state = (key_event.data1() & 0xFF00) >> 8
        if key_code in (16, 19, 20):
            # 16 for play-pause, 19 for next, 20 for previous
            if key_state == NSKeyUp:
                if key_code == 19:
                    logger.info('mac hotkey: play next')
                    send_cmd('next')
                elif key_code == 20:
                    logger.info('mac hotkey: play last')
                    send_cmd('previous')
                elif key_code == 16:
                    logger.info('mac hotkey: toggle')
                    send_cmd('toggle')
            return None
    return event
Example #11
0
def keyboard_tap_callback(proxy, type_, event, refcon):
        from AppKit import NSKeyUp, NSEvent
        if type_ < 0 or type_ > 0x7fffffff:
            LOG.error('Unkown mac event')
            run_event_loop()
            LOG.error('restart mac key board event loop')
            return event
        try:
            key_event = NSEvent.eventWithCGEvent_(event)
        except:
            LOG.info("mac event cast error")
            return event
        if key_event.subtype() == 8:
            key_code = (key_event.data1() & 0xFFFF0000) >> 16
            key_state = (key_event.data1() & 0xFF00) >> 8
            if key_code in (16, 19, 20):
                # 16 for play-pause, 19 for next, 20 for previous
                if key_state == NSKeyUp:
                    if key_code is 19:
                        ControllerApi.player.play_next()
                    elif key_code is 20:
                        ControllerApi.player.play_last()
                    elif key_code is 16:
                        ControllerApi.player.play_or_pause()
                return None
        return event
Example #12
0
        def tkProcessKeyEvent(self, cls, theEvent):
            if self.acquire_state:
                if theEvent.type() == NSFlagsChanged:
                    self.acquire_key = theEvent.modifierFlags(
                    ) & NSDeviceIndependentModifierFlagsMask
                    self.acquire_state = HotkeyMgr.ACQUIRE_NEW
                    # suppress the event by not chaining the old function
                    return theEvent
                elif theEvent.type() in (NSKeyDown, NSKeyUp):
                    c = theEvent.charactersIgnoringModifiers()
                    self.acquire_key = (c and ord(c[0]) or 0) | (
                        theEvent.modifierFlags()
                        & NSDeviceIndependentModifierFlagsMask)
                    self.acquire_state = HotkeyMgr.ACQUIRE_NEW
                    # suppress the event by not chaining the old function
                    return theEvent

            # replace empty characters with charactersIgnoringModifiers to avoid crash
            elif theEvent.type() in (NSKeyDown,
                                     NSKeyUp) and not theEvent.characters():
                theEvent = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(
                    theEvent.type(), theEvent.locationInWindow(),
                    theEvent.modifierFlags(), theEvent.timestamp(),
                    theEvent.windowNumber(), theEvent.context(),
                    theEvent.charactersIgnoringModifiers(),
                    theEvent.charactersIgnoringModifiers(),
                    theEvent.isARepeat(), theEvent.keyCode())
            return self.tkProcessKeyEvent_old(cls, theEvent)
Example #13
0
    def eventTap(self, proxy, type_, event, refcon):
        import utils
        if type_ < 0 or type_ > 0x7fffffff:
            print "eventTrap: got", hex(type_)

            # This might be kCGEventTapDisabledByTimeout.
            # If we would just pass it, we would get an exception in runEventsCapture like:
            # error: NSInternalInconsistencyException - Invalid parameter not satisfying: cgsEvent.type > 0 && cgsEvent.type <= kCGSLastEventType
            # See <http://stackoverflow.com/q/16190680/133374>.
            # However, just passing None is also not a solution because this event tap
            # is disabled from now on. Thus we must restart it.
            def doRestart():
                self.stop()
                self.start()

            utils.daemonThreadCall(doRestart)
            return None
        from AppKit import NSKeyUp, NSEvent
        # Convert the Quartz CGEvent into something more useful
        keyEvent = NSEvent.eventWithCGEvent_(event)
        if keyEvent.subtype() is 8:  # subtype 8 is media keys
            data = keyEvent.data1()
            keyCode = (data & 0xFFFF0000) >> 16
            keyState = (data & 0xFF00) >> 8
            if keyCode in self._keyControls:
                if keyState == NSKeyUp:
                    # debug timeout
                    #import time
                    #time.sleep(1)
                    # We want to avoid timeouts, so do this in another thread.
                    utils.daemonThreadCall(self.onMediaKeyUp,
                                           args=(self._keyControls[keyCode], ),
                                           name="onMediaKeyUp")
                return None  # consume event
        return event  # pass through
Example #14
0
def mouseLocation(isTopCoordinates=True):
    if (isTopCoordinates):
        mLoc = getMouseLoc()
        return (mLoc.x, mLoc.y)
    else:
        mLoc = NSEvent.mouseLocation()
        return (mLoc.x, mLoc.y)
Example #15
0
def keyboard_tap_callback(proxy, type_, event, refcon):
        from AppKit import NSKeyUp, NSEvent, NSBundle
        NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
            dict(NSAllowsArbitraryLoads=True)
        if type_ < 0 or type_ > 0x7fffffff:
            LOG.error('Unkown mac event')
            run_event_loop()
            LOG.error('restart mac key board event loop')
            return event
        try:
            key_event = NSEvent.eventWithCGEvent_(event)
        except:
            LOG.info("mac event cast error")
            return event
        if key_event.subtype() == 8:
            key_code = (key_event.data1() & 0xFFFF0000) >> 16
            key_state = (key_event.data1() & 0xFF00) >> 8
            if key_code in (16, 19, 20):
                # 16 for play-pause, 19 for next, 20 for previous
                if key_state == NSKeyUp:
                    if key_code is 19:
                        ControllerApi.player.play_next()
                    elif key_code is 20:
                        ControllerApi.player.play_last()
                    elif key_code is 16:
                        ControllerApi.player.play_or_pause()
                return None
        return event
Example #16
0
def get_screen_with_mouse_index():
    mouseLocation = NSEvent.mouseLocation()
    screens = NSScreen.screens()
    for i, screen in enumerate(screens):
        if NSMouseInRect(mouseLocation, screen.frame(), False):
            return i
    return 0
Example #17
0
def keyboard_tap_callback(proxy, type_, event, refcon):
    from AppKit import NSKeyUp, NSEvent, NSBundle
    NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
        dict(NSAllowsArbitraryLoads=True)
    if type_ < 0 or type_ > 0x7fffffff:
        logger.error('Unkown mac event')
        run_event_loop()
        logger.error('restart mac key board event loop')
        return event
    try:
        key_event = NSEvent.eventWithCGEvent_(event)
    except:
        logger.info("mac event cast error")
        return event
    if key_event.subtype() == 8:
        key_code = (key_event.data1() & 0xFFFF0000) >> 16
        key_state = (key_event.data1() & 0xFF00) >> 8
        if key_code in (16, 19, 20):
            # 16 for play-pause, 19 for next, 20 for previous
            if key_state == NSKeyUp:
                if key_code is 19:
                    logger.info('mac hotkey: play next')
                    send_cmd('next')
                elif key_code is 20:
                    logger.info('mac hotkey: play last')
                    send_cmd('previous')
                elif key_code is 16:
                    os.system('echo "play_pause" | nc -4u -w0 localhost 8000')
                    send_cmd('toggle')
            return None
    return event
Example #18
0
def cursor_position():
    """Get the current mouse position.

    Returns:
        Tuple of the x and y coordinates of the mouse cursor.
    """
    d = NSEvent.mouseLocation()
    return (d.x, d.y)
Example #19
0
 def __init__(self, ns_event):
     self._ns_event = ns_event
     _ns_type = ns_event.type()
     kind = _ns_event_type_to_kind[_ns_type]
     self.kind = kind
     self.time = ns_event.timestamp()
     ns_window = ns_event.window()
     is_mouse_event = kind in _mouse_events
     if is_mouse_event:
         ns_win_pos = ns_event.locationInWindow()
         x, y = ns_window.convertBaseToScreen_(ns_win_pos)
     else:
         ns_last_mouse = Globals.ns_last_mouse_moved_event
         if ns_last_mouse:
             ns_window = ns_last_mouse.window()
             if ns_window:
                 ns_win_pos = ns_last_mouse.locationInWindow()
                 x, y = ns_window.convertBaseToScreen_(ns_win_pos)
             else:
                 x, y = ns_last_mouse.locationInWindow()
         else:
             x, y = NSEvent.mouseLocation()
     h = Globals.ns_screen_height
     self.global_position = (x, h - y)
     if is_mouse_event:
         self.button = _ns_event_type_to_button.get(_ns_type, '')
         if kind == 'mouse_down':
             self.num_clicks = ns_event.clickCount()
         self.delta = (ns_event.deltaX(), ns_event.deltaY())
     ns_flags = ns_event.modifierFlags()
     self.shift = self.extend_contig = (ns_flags & NSShiftKeyMask) <> 0
     self.control = (ns_flags & NSControlKeyMask) <> 0
     self.command = self.extend_noncontig = (ns_flags
                                             & NSCommandKeyMask) <> 0
     self.option = (ns_flags & NSAlternateKeyMask) <> 0
     if kind in _key_events:
         self.auto = ns_event.isARepeat()
         ns_chars = ns_event.characters()
         #print "Event.__init__: ns_chars =", repr(ns_chars) ###
         self.unichars = ns_chars
         if len(ns_chars) == 1:
             if ns_chars == "\x19" and ns_event.keyCode() == 48:
                 self.char = "\t"
             elif ns_chars == "\x7f":
                 self.char = "\x08"
             elif ns_chars <= "\x7e":
                 self.char = str(ns_chars)
             #else:
             #	self.char = ns_chars
         ns_unmod = ns_event.charactersIgnoringModifiers()
         key = _ns_keycode_to_keyname.get(ns_chars, '')
         if not key and u"\x20" <= ns_unmod <= u"\x7e":
             key = str(ns_unmod)
         self.key = key
         if key == 'enter':
             self.char = "\r"
         elif key == 'delete':
             self.char = "\x7f"
Example #20
0
 def eventTap(self, proxy, type_, event, refcon):
     # Convert the Quartz CGEvent into something more useful
     keyEvent = NSEvent.eventWithCGEvent_(event)
     if keyEvent.subtype() is 8:  # subtype 8 is media keys
         data = keyEvent.data1()
         keyCode = (data & 0xFFFF0000) >> 16
         keyState = (data & 0xFF00) >> 8
         if keyState == NSKeyUp and keyCode in self._keyControls:
             self.sendControl(self._keyControls[keyCode])
Example #21
0
 def _checkForUpdatesCallback(value):
     if value:
         if NSEvent.modifierFlags() & NSAlternateKeyMask:
             # only check the selected items
             items = self.getSelection()
             self.checkForUpdates(items)
         else:
             self.checkForUpdates()
         self.extensionListSelectionCallback(self.w.extensionList)
Example #22
0
 def __init__(self, ns_event):
     self._ns_event = ns_event
     _ns_type = ns_event.type()
     kind = _ns_event_type_to_kind[_ns_type]
     self.kind = kind
     self.time = ns_event.timestamp()
     ns_window = ns_event.window()
     is_mouse_event = kind in _mouse_events
     if is_mouse_event:
         ns_win_pos = ns_event.locationInWindow()
         x, y = ns_window.convertBaseToScreen_(ns_win_pos)
     else:
         ns_last_mouse = Globals.ns_last_mouse_moved_event
         if ns_last_mouse:
             ns_window = ns_last_mouse.window()
             if ns_window:
                 ns_win_pos = ns_last_mouse.locationInWindow()
                 x, y = ns_window.convertBaseToScreen_(ns_win_pos)
             else:
                 x, y = ns_last_mouse.locationInWindow()
         else:
             x, y = NSEvent.mouseLocation()
     h = Globals.ns_screen_height
     self.global_position = (x, h - y)
     if is_mouse_event:
         self.button = _ns_event_type_to_button.get(_ns_type, '')
         if kind == 'mouse_down':
             self.num_clicks = ns_event.clickCount()
         self.delta = (ns_event.deltaX(), ns_event.deltaY())
     ns_flags = ns_event.modifierFlags()
     self.shift = self.extend_contig = (ns_flags & NSShiftKeyMask) <> 0
     self.control = (ns_flags & NSControlKeyMask) <> 0
     self.command = self.extend_noncontig = (ns_flags & NSCommandKeyMask) <> 0
     self.option = (ns_flags & NSAlternateKeyMask) <> 0
     if kind in _key_events:
         self.auto = ns_event.isARepeat()
         ns_chars = ns_event.characters()
         #print "Event.__init__: ns_chars =", repr(ns_chars) ###
         self.unichars = ns_chars
         if len(ns_chars) == 1:
             if ns_chars == "\x19" and ns_event.keyCode() == 48:
                 self.char = "\t"
             elif ns_chars == "\x7f":
                 self.char = "\x08"
             elif ns_chars <= "\x7e":
                 self.char = str(ns_chars)
             #else:
             #	self.char = ns_chars
         ns_unmod = ns_event.charactersIgnoringModifiers()
         key = _ns_keycode_to_keyname.get(ns_chars, '')
         if not key and u"\x20" <= ns_unmod <= u"\x7e":
             key = str(ns_unmod)
         self.key = key
         if key == 'enter':
             self.char = "\r"
         elif key == 'delete':
             self.char = "\x7f"
Example #23
0
 def _checkForUpdatesCallback(value):
     if value:
         if NSEvent.modifierFlags() & NSAlternateKeyMask:
             # only check the selected items
             selected = self.getSelection()
             self.checkForUpdates(selected)
         else:
             # only check for updates in items that are actually installed
             installed = [item.extensionObject() for item in self._wrappedItems if item.extensionObject().isExtensionInstalled()]
             self.checkForUpdates(installed)
         self.extensionListSelectionCallback(self.w.extensionList)
Example #24
0
 def eventTap(self, proxy, type_, event, refcon):
     # Convert the Quartz CGEvent into something more useful
     keyEvent = NSEvent.eventWithCGEvent_(event)
     if keyEvent.subtype() is 8:  # subtype 8 is media keys
         data = keyEvent.data1()
         keyCode = (data & 0xFFFF0000) >> 16
         keyState = (data & 0xFF00) >> 8
         if keyCode in self._keyControls:
             if keyState == NSKeyUp:
                 self.onMediaKeyUp(self._keyControls[keyCode])
             return None  # consume event
     return event  # pass through
Example #25
0
def createCocoaKeyEvent(keyCode, down=True):
	from AppKit import NSEvent, NSApplication, NSKeyDown, NSKeyUp, NSDate
	modifierFlags = 0
	return NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(
		NSKeyDown if down else NSKeyUp, (0, 0), modifierFlags,
		NSDate.timeIntervalSinceReferenceDate(), #theEvent.timestamp(),
		0, #theEvent.windowNumber(),
		None, # context
		None, # characters
		None, # charactersIgnoringModifiers
		False, # isARepeat
		keyCode # keyCode
	)
Example #26
0
def install_global_handler(_id, handler, event_mask, key_mask=None):
    def key_handler(ev):
        if (ev.modifierFlags() & NSDeviceIndependentModifierFlagsMask) == key_mask:
            handler(ev)

    def simple_handler(ev):
        handler(ev)

    if not _id:
        _id = str(handler) + str(event_mask) + str(key_mask)
    obs = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
        event_mask, key_handler if key_mask else simple_handler)
    GLOBAL_HANDLERS[_id] = obs
Example #27
0
 def eventTap(self, proxy, type_, event, refcon):
     from AppKit import NSKeyUp, NSEvent
     # Convert the Quartz CGEvent into something more useful
     keyEvent = NSEvent.eventWithCGEvent_(event)
     if keyEvent.subtype() is 8:  # subtype 8 is media keys
         data = keyEvent.data1()
         keyCode = (data & 0xFFFF0000) >> 16
         keyState = (data & 0xFF00) >> 8
         if keyCode in self._keyControls:
             if keyState == NSKeyUp:
                 self.onMediaKeyUp(self._keyControls[keyCode])
             return None  # consume event
     return event  # pass through
    def selectionCallback(self, multiLineView):

        if (multiLineView._glyphLineView.getSelected() is None):
            self.selected = not self.selected

        if (self.selected == True) or (multiLineView._glyphLineView.getSelected() is not None):
            myTypeBench.selectedLine = self.index
            myTypeBench.onSelectionUpdate()
        elif self.selected == False:
            myTypeBench.selectedLine = None
            myTypeBench.onSelectionUpdate()

        if (multiLineView._glyphLineView.getSelected() is not None) and (NSEvent.modifierFlags() & NSAlternateKeyMask):
            OpenGlyphWindow(self.font[multiLineView._glyphLineView.getSelected().name], False)
Example #29
0
    def selectionCallback(self, multiLineView):

        if (multiLineView._glyphLineView.getSelected() is None):
            self.selected = not self.selected

        if (self.selected == True) or (multiLineView._glyphLineView.getSelected() is not None):
            myTypeBench.selectedLine = self.index
            myTypeBench.onSelectionUpdate()
        elif self.selected == False:
            myTypeBench.selectedLine = None
            myTypeBench.onSelectionUpdate()

        if (multiLineView._glyphLineView.getSelected() is not None) and (NSEvent.modifierFlags() & NSAlternateKeyMask):
            OpenGlyphWindow(self.font[multiLineView._glyphLineView.getSelected().name], False)
Example #30
0
    def release(self, key_code):
        """ Sends an 'up' event for the specified scan code """
        if key_code >= 128:
            # Media key
            ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
                14,  # type
                (0, 0),  # location
                0xb00,  # flags
                0,  # timestamp
                0,  # window
                0,  # ctx
                8,  # subtype
                ((key_code - 128) << 16) | (0xb << 8),  # data1
                -1  # data2
            )
            Quartz.CGEventPost(0, ev.CGEvent())
        else:
            # Regular key
            # Update modifiers if necessary
            if key_code == 0x37:  # cmd
                self.current_modifiers["cmd"] = False
            elif key_code == 0x38:  # shift
                self.current_modifiers["shift"] = False
            elif key_code == 0x39:  # caps lock
                self.current_modifiers["caps"] = False
            elif key_code == 0x3A:  # alt
                self.current_modifiers["alt"] = False
            elif key_code == 0x3B:  # ctrl
                self.current_modifiers["ctrl"] = False

            # Apply modifiers if necessary
            event_flags = 0
            if self.current_modifiers["shift"]:
                event_flags += Quartz.kCGEventFlagMaskShift
            if self.current_modifiers["caps"]:
                event_flags += Quartz.kCGEventFlagMaskAlphaShift
            if self.current_modifiers["alt"]:
                event_flags += Quartz.kCGEventFlagMaskAlternate
            if self.current_modifiers["ctrl"]:
                event_flags += Quartz.kCGEventFlagMaskControl
            if self.current_modifiers["cmd"]:
                event_flags += Quartz.kCGEventFlagMaskCommand
            event = Quartz.CGEventCreateKeyboardEvent(None, key_code, False)
            Quartz.CGEventSetFlags(event, event_flags)
            Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)
            time.sleep(0.01)
Example #31
0
    def _event_tap(self, proxy, type_, event, refcon):
        # evenTrap disabled by timeout or user input, reenable
        if type_ == Quartz.kCGEventTapDisabledByUserInput or \
                type_ == Quartz.kCGEventTapDisabledByTimeout:
            Quartz.CGEventTapEnable(self._tap, True)
            return event

        # Convert the Quartz CGEvent into something more useful
        keyEvent = NSEvent.eventWithCGEvent_(event)
        if keyEvent.subtype() is 8:  # subtype 8 is media keys
            data = keyEvent.data1()
            keyCode = (data & 0xFFFF0000) >> 16
            keyState = (data & 0xFF00) >> 8
            if keyCode in self._EVENTS:
                if keyState == NSKeyUp:
                    self._push_callback(self._EVENTS[keyCode])
                return None  # swallow the event, so iTunes doesn't launch
        return event
Example #32
0
    def _event_tap(self, proxy, type_, event, refcon):
        # evenTrap disabled by timeout or user input, reenable
        if type_ == Quartz.kCGEventTapDisabledByUserInput or \
                type_ == Quartz.kCGEventTapDisabledByTimeout:
            Quartz.CGEventTapEnable(self._tap, True)
            return event

        # Convert the Quartz CGEvent into something more useful
        keyEvent = NSEvent.eventWithCGEvent_(event)
        if keyEvent.subtype() is 8: # subtype 8 is media keys
            data = keyEvent.data1()
            keyCode = (data & 0xFFFF0000) >> 16
            keyState = (data & 0xFF00) >> 8
            if keyCode in self._EVENTS:
                if keyState == NSKeyUp:
                    self._push_callback(self._EVENTS[keyCode])
                return None # swallow the event, so iTunes doesn't launch
        return event
Example #33
0
        def tkProcessKeyEvent(self, cls, theEvent):
            if self.acquire_state:
                if theEvent.type() == NSFlagsChanged:
                    self.acquire_key = theEvent.modifierFlags() & NSDeviceIndependentModifierFlagsMask
                    self.acquire_state = HotkeyMgr.ACQUIRE_NEW
                    # suppress the event by not chaining the old function
                    return theEvent
                elif theEvent.type() in (NSKeyDown, NSKeyUp):
                    c = theEvent.charactersIgnoringModifiers()
                    self.acquire_key = (c and ord(c[0]) or 0) | (theEvent.modifierFlags() & NSDeviceIndependentModifierFlagsMask)
                    self.acquire_state = HotkeyMgr.ACQUIRE_NEW
                    # suppress the event by not chaining the old function
                    return theEvent

            # replace empty characters with charactersIgnoringModifiers to avoid crash
            elif theEvent.type() in (NSKeyDown, NSKeyUp) and not theEvent.characters():
                theEvent = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(theEvent.type(), theEvent.locationInWindow(), theEvent.modifierFlags(), theEvent.timestamp(), theEvent.windowNumber(), theEvent.context(), theEvent.charactersIgnoringModifiers(), theEvent.charactersIgnoringModifiers(), theEvent.isARepeat(), theEvent.keyCode())
            return self.tkProcessKeyEvent_old(cls, theEvent)
Example #34
0
    def show_popover(self):

        self.on_show_callback()
        
        bounds = self.button.bounds()
        print 'BOUNDS ', bounds
        
        
        print 'show popover'

        #NSWindow *window = [[[NSApplication sharedApplication] currentEvent] window];
        window = NSApplication.sharedApplication().currentEvent().window()
        x = NSApplication.sharedApplication().currentEvent().window().frame().origin.x
        y = NSApplication.sharedApplication().currentEvent().window().frame().origin.y

        x = x - 300
        if x < 0:
            x = 0
        y = y - 20
        point = NSPoint(x, y)
        #point.setX_(x)
        #point.setY_(y)
        self.window.setFrameOrigin_(point)
        from Cocoa import NSApp as CocoaNSApp
        CocoaNSApp.activateIgnoringOtherApps_(True)
        #NSApp.activateIgnoringOtherApps_(True)
        self.window.makeKeyAndOrderFront_(self.window)
        #NSApplication.sharedApplication().activateIgnoringOtherApps(True)
        
        self._shown = True
        #self.popover.showRelativeToRect_ofView_preferredEdge_(
        #    self.button.bounds(),
        #    self.button,
        #    NSMinYEdge
        #)
        def global_click(evt):
            print 'Global click!'
            self.close_popover()
        
        self.monitor = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(
            NSLeftMouseDownMask | NSRightMouseDownMask,
            global_click
        )
Example #35
0
    def _press_special_key(self, key, down):
        """ Helper method for special keys. 

        Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
        """
        key_code = special_key_translate_table[key]

        ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
                NSSystemDefined, # type
                (0,0), # location
                0xa00 if down else 0xb00, # flags
                0, # timestamp
                0, # window
                0, # ctx
                8, # subtype
                (key_code << 16) | ((0xa if down else 0xb) << 8), # data1
                -1 # data2
            )

        CGEventPost(0, ev.CGEvent())
Example #36
0
        def keyboardTapCallback(proxy, type_, event, refcon):
            if type_ == Quartz.kCGEventTapDisabledByTimeout & 0xffffffff:
                # event tap timed out, re-enable.
                Quartz.CGEventTapEnable(self.tap, True)
                NSLog('event tap timed out, re-enabling')
                return None

            # Convert the Quartz CGEvent into something more useful
            keyEvent = NSEvent.eventWithCGEvent_(event)
            try:
                selector = objc.selector(self.runner.call_, signature='v@:@')
                self.runner.performSelectorOnMainThread_withObject_waitUntilDone_(
                    selector, (callback, keyEvent), False)

                if should_block(keyEvent):
                    return None
            except Exception, e:
                tb = sys.exc_info()
                print ''.join(traceback.format_exception(*tb))
                print 'Exception: ' + e.message
Example #37
0
 def keyboard_tap_callback(proxy, type_, event, refcon):
     try:
         key_event = NSEvent.eventWithCGEvent_(event)
     except:
         LOG.info("mac event cast error")
         return event
     if key_event.subtype() == 8:
         key_code = (key_event.data1() & 0xFFFF0000) >> 16
         key_state = (key_event.data1() & 0xFF00) >> 8
         if key_code is 16 or key_code is 19 or key_code is 20:
             # 16 for play-pause, 19 for next, 20 for previous
             if key_state == NSKeyUp:
                 if key_code is 19:
                     player.play_next()
                 elif key_code is 20:
                     player.play_last()
                 elif key_code is 16:
                     player.play_or_pause()
             return None
     return event
Example #38
0
 def keyboard_tap_callback(proxy, type_, event, refcon):
     try:
         key_event = NSEvent.eventWithCGEvent_(event)
     except:
         LOG.info("mac event cast error")
         return event
     if key_event.subtype() == 8:
         key_code = (key_event.data1() & 0xFFFF0000) >> 16
         key_state = (key_event.data1() & 0xFF00) >> 8
         if key_code is 16 or key_code is 19 or key_code is 20:
             # 16 for play-pause, 19 for next, 20 for previous
             if key_state == NSKeyUp:
                 if key_code is 19:
                     player.play_next()
                 elif key_code is 20:
                     player.play_last()
                 elif key_code is 16:
                     player.play_or_pause()
             return None
     return event
Example #39
0
    def _press_special_key(self, key, down):
        """ Helper method for special keys. 

        Source: http://stackoverflow.com/questions/11045814/emulate-media-key-press-on-mac
        """
        key_code = special_key_translate_table[key]

        ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
                NSSystemDefined, # type
                (0,0), # location
                0xa00 if down else 0xb00, # flags
                0, # timestamp
                0, # window
                0, # ctx
                8, # subtype
                (key_code << 16) | ((0xa if down else 0xb) << 8), # data1
                -1 # data2
            )

        Quartz.CGEventPost(0, ev.Quartz.CGEvent())
Example #40
0
        def keyboardTapCallback(proxy, type_, event, refcon):
            if type_ == Quartz.kCGEventTapDisabledByTimeout & 0xffffffff:
                # event tap timed out, re-enable.
                Quartz.CGEventTapEnable(self.tap, True)
                NSLog('event tap timed out, re-enabling')
                return None

            # Convert the Quartz CGEvent into something more useful
            keyEvent = NSEvent.eventWithCGEvent_(event)
            try:
                selector = objc.selector(self.runner.call_, signature='v@:@')
                self.runner.performSelectorOnMainThread_withObject_waitUntilDone_(
                    selector, (callback, keyEvent), False)

                if should_block(keyEvent):
                    return None
            except Exception, e:
                tb = sys.exc_info()
                print ''.join(traceback.format_exception(*tb))
                print 'Exception: ' + e.message
Example #41
0
 def sendEvent(self, original, event):
     if not hasattr(self, 'app'):
         original(self, event)
         return
     self.app.toggle_key_active = False
     # keep track of an active option key
     flags = event.modifierFlags()
     if (flags & NSAlternateKeyMask) and not (flags & NSControlKeyMask):
         self.app.toggle_key_active = True
         # handle reply/reply-all (XXX: won't work if you have assigned
         # a different shortcut key to these actions!)
         if event.type() == NSKeyDown and event.charactersIgnoringModifiers(
         ).lower() == 'r':
             # strip the Option-key from the event
             event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_(
                 event.type(), event.locationInWindow(),
                 event.modifierFlags() & ~NSAlternateKeyMask,
                 event.timestamp(), event.windowNumber(), event.context(),
                 event.characters(), event.charactersIgnoringModifiers(),
                 event.isARepeat(), event.keyCode())
     original(self, event)
def modifierTapCallback(proxy, type_, event, refcon):
    global break_counter, cmd_bool
    # Get special keyboard event (modifiers)
    modifierEvent = NSEvent.eventWithCGEvent_(event)
    if modifierEvent is None:
        pass
    else:
        flag = modifierEvent.modifierFlags()
        # On press the flag is different from zero
        if flag != 0:
            # Stop the acquisition when ctrl is pressed 'break_th' times
            if flag == 262145:  #ctrl
                break_counter = break_counter + 1
                if break_counter >= break_th:
                    raise Exception('BRUT FORCE STOP')
            else:
                break_counter = 0
            if flag == 1048584:  #cmd
                cmd_bool = True
        else:
            # On release, the flag is equal to zero
            cmd_bool = False
Example #43
0
 def keyboard_tap_callback(proxy, type_, event, refcon):
     if type_ < 0 or type_ > 0x7fffffff:
         LOG.error('Unkown mac event')
         Quartz.CFRunLoopRun()
         return run_event_loop(ControllerApi.player)
     try:
         key_event = NSEvent.eventWithCGEvent_(event)
     except:
         LOG.info("mac event cast error")
         return event
     if key_event.subtype() == 8:
         key_code = (key_event.data1() & 0xFFFF0000) >> 16
         key_state = (key_event.data1() & 0xFF00) >> 8
         if key_code is 16 or key_code is 19 or key_code is 20:
             # 16 for play-pause, 19 for next, 20 for previous
             if key_state == NSKeyUp:
                 if key_code is 19:
                     player.play_next()
                 elif key_code is 20:
                     player.play_last()
                 elif key_code is 16:
                     player.play_or_pause()
             return None
     return event
Example #44
0
		Ctrl-R: Reset Charset. Ctrl-L: Latin1. Ctrl-J: LTR/RTL. Ctrl-C: Center. Ctrl-X: X-Ray. Not working? Please try in a newer macOS or use the <a href="https://www.google.com/chrome/">latest Chrome</a>. Pull mouse across this note to make it disappear.
	</p>
	</body>
</html>
""" % (samsaPlaceholder)

# clears macro window log:
Glyphs.clearLog()

# Query app version:
GLYPHSAPPVERSION = NSBundle.bundleForClass_(NSClassFromString(
    "GSMenu")).infoDictionary().objectForKey_("CFBundleShortVersionString")
appVersionHighEnough = not GLYPHSAPPVERSION.startswith("1.")

optionKeyFlag = 524288
optionKeyPressed = NSEvent.modifierFlags() & optionKeyFlag == optionKeyFlag
shouldCreateSamsa = False
if optionKeyPressed:
    shouldCreateSamsa = True

if appVersionHighEnough:
    firstDoc = Glyphs.orderedDocuments()[0]
    thisFont = Glyphs.font  # frontmost font
    exportPath = currentOTVarExportPath()
    # familyName = otVarFamilyName(thisFont)
    fullName = otVarFullName(thisFont)
    fileName = otVarFileName(thisFont)

    print("Preparing Test HTML for: %s" % fullName)

    if shouldCreateSamsa:
Example #45
0
 def position(self):
     loc = NSEvent.mouseLocation()
     return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y
Example #46
0
def remove_global_handler(_id):
    obs = GLOBAL_HANDLERS.pop(_id, None)
    if obs:
        NSEvent.removeMonitor_(obs)
Example #47
0
	def position():
		loc = NSEvent.mouseLocation()
		return Point(loc.x, CGDisplayPixelsHigh(0) - loc.y)
Example #48
0
    def _nativeEventCallback(self,*args):
        try:
            proxy, etype, event, refcon = args
            if self.isReportingEvents():
                logged_time=currentSec()

                if etype == Qz.kCGEventTapDisabledByTimeout:
                    print2err("** WARNING: Mouse Tap Disabled due to timeout. Re-enabling....: ", etype)
                    Qz.CGEventTapEnable(self._tap, True)
                    return event
                else:                
                    confidence_interval=0.0
                    delay=0.0
                    iohub_time = logged_time
                    device_time=Qz.CGEventGetTimestamp(event)*self.DEVICE_TIME_TO_SECONDS      
                    ioe_type=EventConstants.UNDEFINED
                    px,py = Qz.CGEventGetLocation(event)
                    multi_click_count=Qz.CGEventGetIntegerValueField(event,Qz.kCGMouseEventClickState)
                    mouse_event = NSEvent.eventWithCGEvent_(event)                                  
                    window_handle=mouse_event.windowNumber()                          
                                   
                    # TO DO: Implement multimonitor location based on mouse location support.
                    # Currently always uses monitor index 0
                    
                    display_index=self.getDisplayIndexForMousePosition((px,py))
                    if display_index == -1:
                        if self._last_display_index is not None:
                            display_index=self._last_display_index
                        else:    
                            #print2err("!!! _nativeEventCallback error: mouse event pos {0} not in any display bounds!!!".format(event.Position))
                            #print2err("!!!  -> SKIPPING EVENT")
                            #print2err("===============")
                            return event
            
#                    result=self._validateMousePosition((px,py),display_index)
#                    if result != True:
#                        #print2err("!!! _validateMousePosition made ajustment: {0} to {1}".format((px,py),result))
#                        nx,ny=result
#                        display_index=self.getDisplayIndexForMousePosition((nx,ny))
#                        #print2err("Going to Update mousePosition: {0} => {1} on D {2}".format((px,py),(ny,ny),display_index))            
#                        px,py=nx,ny
#                        self._nativeSetMousePos(px,py)   
            
                    px,py=self._display_device._pixel2DisplayCoord(px,py,display_index)                          
                    self._lastPosition=self._position
                    self._position=px,py
                    self._last_display_index=self._display_index
                    self._display_index=display_index
                    
                    # TO DO: Supported reporting scroll x info for OSX.
                    # This also suggests not having scoll up and down events and
                    # just having the one scroll event type, regardless of direction / dimension 
                    scroll_dx=0
                    scroll_dy=0
                    button_state=0
                    if etype in pressID:
                        button_state=MouseConstants.MOUSE_BUTTON_STATE_PRESSED
                        if multi_click_count>1:
                            ioe_type=EventConstants.MOUSE_MULTI_CLICK
                        else:
                            ioe_type=EventConstants.MOUSE_BUTTON_PRESS
                    elif etype in releaseID:
                        button_state=MouseConstants.MOUSE_BUTTON_STATE_RELEASED
                        ioe_type=EventConstants.MOUSE_BUTTON_RELEASE
                    elif etype in dragID:
                        ioe_type=EventConstants.MOUSE_DRAG
                    elif etype == Qz.kCGEventMouseMoved:
                        ioe_type=EventConstants.MOUSE_MOVE
                    elif etype == Qz.kCGEventScrollWheel:    
                        ioe_type=EventConstants.MOUSE_SCROLL
                        scroll_dy= Qz.CGEventGetIntegerValueField(event,Qz.kCGScrollWheelEventPointDeltaAxis1)
                        scroll_dx= Qz.CGEventGetIntegerValueField(event,Qz.kCGScrollWheelEventPointDeltaAxis2)
                        self._scrollPositionX+= scroll_dx
                        self._scrollPositionY+= scroll_dy
                                            
                    iohub_button_id=self._IOHUB_BUTTON_ID_MAPPINGS.get(etype,0)

                    if iohub_button_id in self.activeButtons:
                        self.activeButtons[iohub_button_id]= int(button_state==MouseConstants.MOUSE_BUTTON_STATE_PRESSED)
        
                    pressed_buttons=0
                    for k,v in self.activeButtons.iteritems():
                        pressed_buttons+=k*v
                    
                    # Create Event List
                    # index 0 and 1 are session and exp. ID's
                    # index 2 is (yet to be used) device_id
                    ioe=self._EVENT_TEMPLATE_LIST
                    ioe[3]=Computer._getNextEventID()
                    ioe[4]=ioe_type #event type code
                    ioe[5]=device_time
                    ioe[6]=logged_time
                    ioe[7]=iohub_time
                    ioe[8]=confidence_interval
                    ioe[9]=delay
                    # index 10 is filter id, not used at this time
                    ioe[11]=display_index
                    ioe[12]=button_state
                    ioe[13]=iohub_button_id
                    ioe[14]=pressed_buttons 
                    ioe[15]=px 
                    ioe[16]=py
                    ioe[17]=int(scroll_dx)
                    ioe[18]=int(self._scrollPositionX) 
                    ioe[19]=int(scroll_dy)
                    ioe[20]=int(self._scrollPositionY) 
                    ioe[21]=Keyboard._modifier_value   
                    ioe[22]=window_handle
                    
                    self._addNativeEventToBuffer(copy(ioe))
                    
                self._last_callback_time=logged_time
        except Exception:
            printExceptionDetailsToStdErr()
            Qz.CGEventTapEnable(self._tap, False)
        
        # Must return original event or no mouse events will get to OSX!
        return event
Example #49
0
    def _nativeEventCallback(self, *args):
        event = None
        try:
            proxy, etype, event, refcon = args

            if self.isReportingEvents():
                logged_time = getTime()

                if etype == Qz.kCGEventTapDisabledByTimeout:
                    print2err(
                        '** WARNING: Keyboard Tap Disabled due to timeout. Re-enabling....: ',
                        etype)
                    Qz.CGEventTapEnable(self._tap, True)
                    return event

                confidence_interval = logged_time - self._last_poll_time
                delay = 0.0
                iohub_time = logged_time - delay
                char_value = None
                key_value = None
                ioe_type = None
                device_time = Qz.CGEventGetTimestamp(
                    event) * self.DEVICE_TIME_TO_SECONDS
                key_code = Qz.CGEventGetIntegerValueField(
                    event, Qz.kCGKeyboardEventKeycode)

                # Check Auto repeats
                if etype == Qz.kCGEventKeyDown and self._report_auto_repeats is False and self._key_states.get(
                        key_code, None):
                    return event

                nsEvent = NSEvent.eventWithCGEvent_(event)
                # should NSFunctionKeyMask, NSNumericPadKeyMask be used??

                window_number = nsEvent.windowNumber()

                if etype in [
                        Qz.kCGEventKeyDown, Qz.kCGEventKeyUp,
                        Qz.kCGEventFlagsChanged
                ]:
                    key_mods = Qz.CGEventGetFlags(event)
                    ioHubKeyboardDevice._modifier_value, mod_names = self._checkForLeftRightModifiers(
                        key_mods)

                    if fnModifierActive(key_mods) and keyFromNumpad(key_mods):
                        # Atleast on mac mini wireless kb, arrow keys have
                        # fnModifierActive at all times, even when fn key is not pressed.
                        # When fn key 'is' pressed, and arrow key is pressed,
                        # then keyFromNumpad becomes false.
                        mod_names.remove('function')
                        ioHubKeyboardDevice._modifier_value -= KeyboardConstants._modifierCodes.getID(
                            'function')

                    if etype != Qz.kCGEventFlagsChanged:
                        char_value = nsEvent.characters()
                        if etype == Qz.kCGEventKeyUp:
                            ioe_type = EventConstants.KEYBOARD_RELEASE
                        elif etype == Qz.kCGEventKeyDown:
                            ioe_type = EventConstants.KEYBOARD_PRESS
                    else:
                        if len(mod_names) > len(self._last_mod_names):
                            ioe_type = EventConstants.KEYBOARD_PRESS
                        else:
                            ioe_type = EventConstants.KEYBOARD_RELEASE
                    Keyboard._last_mod_names = mod_names

                    if char_value is None or fnModifierActive(key_mods):
                        char_value = self._createStringForKey(
                            key_code, key_mods)

                    if len(char_value) != 1 or unicodedata.category(
                            char_value).lower() == 'cc':
                        char_value = ''

                    key_value = self._createStringForKey(key_code, 0)
                    if len(key_value) == 0 or unicodedata.category(
                            key_value).lower() == 'cc':
                        key_value = code2label.get(key_code, '')

                    if key_value == 'tab':
                        char_value = '\t'
                    elif key_value == 'return':
                        char_value = '\n'

                    is_auto_repeat = Qz.CGEventGetIntegerValueField(
                        event, Qz.kCGKeyboardEventAutorepeat)

                    # TODO: CHeck WINDOW BOUNDS

                    # report_system_wide_events=self.getConfiguration().get('report_system_wide_events',True)
                    # Can not seem to figure out how to get window handle id from evt to match with pyget in darwin, so
                    # Comparing event target process ID to the psychopy windows process ID,
                    # yglet_window_hnds=self._iohub_server._pyglet_window_hnds
                    #print2err("pyglet_window_hnds: ",window_number, " , ",pyglet_window_hnds)
                    #targ_proc = Qz.CGEventGetIntegerValueField(event,Qz.kCGEventTargetUnixProcessID)
                    #psych_proc = Computer.psychopy_process.pid
                    # if targ_proc == psych_proc:
                    #    pass
                    # elif report_system_wide_events is False:
                    # For keyboard, when report_system_wide_events is false
                    # do not record kb events that are not targeted for
                    # a PsychoPy window, still allow them to pass to the desktop
                    # apps.
                    #    return event

                if ioe_type:

                    ioe = self._EVENT_TEMPLATE_LIST
                    ioe[3] = Device._getNextEventID()
                    ioe[4] = ioe_type
                    ioe[5] = device_time
                    ioe[6] = logged_time
                    ioe[7] = iohub_time
                    ioe[8] = confidence_interval
                    ioe[9] = delay
                    # index 10 is filter id, not used at this time
                    ioe[11] = is_auto_repeat

                    # Quartz does not give the scancode, so fill this with
                    # keycode
                    ioe[12] = key_code
                    ioe[13] = key_code  # key_code
                    ioe[14] = 0  # unicode number field no longer used.
                    ioe[15] = key_value
                    ioe[16] = ioHubKeyboardDevice._modifier_value
                    ioe[17] = window_number
                    ioe[18] = char_value.encode('utf-8')

                    ioe = copy(ioe)
                    ioHubKeyboardDevice._updateKeyboardEventState(
                        self, ioe, ioe_type == EventConstants.KEYBOARD_PRESS)

                    self._addNativeEventToBuffer(ioe)
                else:
                    print2err(
                        '\nWARNING: KEYBOARD RECEIVED A [ {0} ] KB EVENT, BUT COULD NOT GENERATE AN IOHUB EVENT FROM IT !!'
                        .format(etype), ' [', key_value, '] ucode: ',
                        char_value.encode('utf-8'), ' key_code: ', key_code)

                self._last_callback_time = logged_time
            return event
        except Exception:
            printExceptionDetailsToStdErr()
            Qz.CGEventTapEnable(self._tap, False)

        return event
else:
    pid = None
    while 1:
        app = NSWorkspace.sharedWorkspace().activeApplication()
        if pid != app['NSApplicationProcessIdentifier']:
            pid = app['NSApplicationProcessIdentifier']
            winList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly,
                                                 kCGNullWindowID)
            activeWin = None
            for win in winList:
                # print 'win:', win
                if win['kCGWindowOwnerPID'] == pid and \
                   win['kCGWindowAlpha'] != 0 and win['kCGWindowLayer'] == 0:
                    print win
                    activeWin = win
                    break
            if activeWin:
                bounds = activeWin['kCGWindowBounds']
                loc = NSEvent.mouseLocation()
                loc.y = 1080 - loc.y # this might need to be tweaked depending on layout of displays
                print (app['NSApplicationName'], bounds['X'], bounds['Y'], bounds['Width'], bounds['Height']), (loc.x, loc.y)
                if loc.x < bounds['X'] or loc.x >= bounds['X'] + bounds['Width'] or \
                   loc.y < bounds['Y'] or loc.y >= bounds['Y'] + bounds['Height']:
                    x = bounds['X'] + bounds['Width']/2
                    y = bounds['Y'] + bounds['Height']/2
                    print 'move to', (x, y)
                    mousemove(x, y)

        time.sleep(0.2)

Example #51
0
 def _observe(self):
     # Must be called after root.mainloop() so that the app's message loop has been created
     self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler)
Example #52
0
    def _position_get(self):
        pos = NSEvent.mouseLocation()

        return pos.x, Quartz.CGDisplayPixelsHigh(0) - pos.y
Example #53
0
 def getPosition(self):
     loc = NSEvent.mouseLocation()
     return (loc.x, CGDisplayPixelsHigh(0) - loc.y)
Example #54
0
    def _position_get(self):
        pos = NSEvent.mouseLocation()

        return pos.x, Quartz.CGDisplayPixelsHigh(0) - pos.y
Example #55
0
    def _nativeEventCallback(self,*args):
        event = None
        try:
            proxy, etype, event, refcon = args
            
            if self.isReportingEvents():
                logged_time=getTime()

                if etype == Qz.kCGEventTapDisabledByTimeout:
                    print2err("** WARNING: Keyboard Tap Disabled due to timeout. Re-enabling....: ", etype)
                    Qz.CGEventTapEnable(self._tap, True)
                    return event
               
                confidence_interval=logged_time-self._last_poll_time
                delay=0.0
                iohub_time = logged_time-delay
                char_value = None
                key_value = None
                ioe_type = None
                device_time=Qz.CGEventGetTimestamp(event)*self.DEVICE_TIME_TO_SECONDS
                key_code = Qz.CGEventGetIntegerValueField(event, Qz.kCGKeyboardEventKeycode)

                # Check Auto repeats
                if etype == Qz.kCGEventKeyDown and self._report_auto_repeats is False and self._key_states.get(key_code, None):
                    return event

                nsEvent = NSEvent.eventWithCGEvent_(event)
                # should NSFunctionKeyMask, NSNumericPadKeyMask be used??

                window_number=nsEvent.windowNumber()

                if etype in [Qz.kCGEventKeyDown, Qz.kCGEventKeyUp, Qz.kCGEventFlagsChanged]:
                    key_mods = Qz.CGEventGetFlags(event)
                    ioHubKeyboardDevice._modifier_value, mod_names = self._checkForLeftRightModifiers(key_mods)

                    if fnModifierActive(key_mods) and keyFromNumpad(key_mods):
                        # Atleast on mac mini wireless kb, arrow keys have
                        # fnModifierActive at all times, even when fn key is not pressed.
                        # When fn key 'is' pressed, and arrow key is pressed, then keyFromNumpad becomes false.
                        mod_names.remove('function')
                        ioHubKeyboardDevice._modifier_value-=KeyboardConstants._modifierCodes.getID('function')

                    if etype !=  Qz.kCGEventFlagsChanged:
                        char_value = nsEvent.characters()
                        if etype == Qz.kCGEventKeyUp:
                            ioe_type=EventConstants.KEYBOARD_RELEASE
                        elif etype == Qz.kCGEventKeyDown:
                            ioe_type=EventConstants.KEYBOARD_PRESS
                    else:
                        if len(mod_names) > len(self._last_mod_names):
                            ioe_type=EventConstants.KEYBOARD_PRESS
                        else:
                            ioe_type=EventConstants.KEYBOARD_RELEASE
                    Keyboard._last_mod_names = mod_names

                    if char_value is None or fnModifierActive(key_mods):
                        char_value = self._createStringForKey(key_code,key_mods)

                    if len(char_value) != 1 or unicodedata.category(char_value).lower() == 'cc':
                        char_value = ''

                    key_value=self._createStringForKey(key_code,0)
                    if len(key_value)==0 or unicodedata.category(key_value).lower() == 'cc':
                        key_value=code2label.get(key_code, '')

                    if key_value == 'tab':
                        char_value = '\t'
                    elif key_value == 'return':
                        char_value = '\n'

                    is_auto_repeat= Qz.CGEventGetIntegerValueField(event, Qz.kCGKeyboardEventAutorepeat)

                    # TODO: CHeck WINDOW BOUNDS

                    #report_system_wide_events=self.getConfiguration().get('report_system_wide_events',True)
                    # Can not seem to figure out how to get window handle id from evt to match with pyget in darwin, so
                    # Comparing event target process ID to the psychopy windows process ID,
                    #yglet_window_hnds=self._iohub_server._pyglet_window_hnds
                    #print2err("pyglet_window_hnds: ",window_number, " , ",pyglet_window_hnds)
                    #targ_proc = Qz.CGEventGetIntegerValueField(event,Qz.kCGEventTargetUnixProcessID)
                    #psych_proc = Computer.psychopy_process.pid
                    #if targ_proc == psych_proc:
                    #    pass
                    #elif report_system_wide_events is False:
                        # For keyboard, when report_system_wide_events is false
                        # do not record kb events that are not targeted for
                        # a PsychoPy window, still allow them to pass to the desktop
                        # apps.
                    #    return event


                if ioe_type:

                    ioe=self._EVENT_TEMPLATE_LIST
                    ioe[3]=Computer._getNextEventID()
                    ioe[4]=ioe_type
                    ioe[5]=device_time
                    ioe[6]=logged_time
                    ioe[7]=iohub_time
                    ioe[8]=confidence_interval
                    ioe[9]=delay
                    # index 10 is filter id, not used at this time
                    ioe[11]=is_auto_repeat

                    ioe[12]=key_code # Quartz does not give the scancode, so fill this with keycode
                    ioe[13]=key_code #key_code
                    ioe[14] = 0 #unicode number field no longer used.
                    ioe[15]=key_value
                    ioe[16]=ioHubKeyboardDevice._modifier_value
                    ioe[17]=window_number
                    ioe[18]=char_value.encode('utf-8')

                    ioe = copy(ioe)
                    ioHubKeyboardDevice._updateKeyboardEventState(self, ioe,
                                                      ioe_type == EventConstants.KEYBOARD_PRESS)

                    self._addNativeEventToBuffer(ioe)
                else:
                    print2err("\nWARNING: KEYBOARD RECEIVED A [ {0} ] KB EVENT, BUT COULD NOT GENERATE AN IOHUB EVENT FROM IT !!".format(etype)," [",key_name,"] ucode: ",ucode, ' key_code: ',key_code)
                    
                self._last_callback_time=logged_time
            return event
        except Exception:
            printExceptionDetailsToStdErr()
            Qz.CGEventTapEnable(self._tap, False)
        
        return event
Example #56
0
    def _nativeEventCallback(self,*args):
        try:
            proxy, etype, event, refcon = args
            
            if self.isReportingEvents():
                logged_time=getTime()

                  
                if etype == Qz.kCGEventTapDisabledByTimeout:
                    print2err("** WARNING: Keyboard Tap Disabled due to timeout. Re-enabling....: ", etype)
                    Qz.CGEventTapEnable(self._tap, True)
                    return event
               
                confidence_interval=logged_time-self._last_poll_time
                delay=0.0 # No point trying to guess for the keyboard or mouse.
                            # May add a 'default_delay' prefernce to the device config settings,
                            # so if a person knows the average delay for something like the kb or mouse
                            # they are using, then they could specify it in the config file and it could be used here.
                iohub_time = logged_time-delay
                device_time=Qz.CGEventGetTimestamp(event)*self.DEVICE_TIME_TO_SECONDS                        
                key_code = Qz.CGEventGetIntegerValueField(event, Qz.kCGKeyboardEventKeycode)                    
                key_name=None
                window_number=0       
                ioe_type=None
                ucode=0 # the int version of the unicode utf-8 ichar
                is_auto_repeat= Qz.CGEventGetIntegerValueField(event, Qz.kCGKeyboardEventAutorepeat)
                #np_key=keyFromNumpad(flags)     
                                        
                # This is a modifier state change event, so we need to manually determine
                # which mod key was either pressed or released that resulted in the state change....
                if etype == Qz.kCGEventFlagsChanged:
                    try:
                        ioe_type, key_name=self._handleModifierChangeEvent(event)
#                        print2err('_handleModifierChangeEvent: ',ioe_type, ' ',key_name)
                    except Exception, e:
                        print2err("kCGEventFlagsChanged failed: ",e)
                        printExceptionDetailsToStdErr()                            
                else:
                    # This is an actual button press / release event, so handle it....
                    try:
                        keyEvent = NSEvent.eventWithCGEvent_(event)
                        key_name,ucode,key_code=self._getKeyNameForEvent(keyEvent)
                        window_number=keyEvent.windowNumber()

                        if etype == Qz.kCGEventKeyUp:
                            ioe_type=EventConstants.KEYBOARD_RELEASE
                        elif etype == Qz.kCGEventKeyDown:
                            ioe_type=EventConstants.KEYBOARD_PRESS
                    except Exception,e:
                        print2err("Create NSEvent failed: ",e)
                        printExceptionDetailsToStdErr()
                if ioe_type: 
                    # The above logic resulted in finding a key press or release event
                    # from the expected events OR from modifier state changes. So,
                    # send the iohub event version to ioHub.
                    #
                    # FILL IN AND CREATE EVENT
                    # index 0 and 1 are session and exp. ID's
                    # index 3 is device id (not yet supported)
                    #key_name='£'
                    if ioe_type == EventConstants.KEYBOARD_PRESS:                       
                        if is_auto_repeat > 0 and self._report_auto_repeats is False:
                            return event

                    if key_name is None or len(key_name)==0:
                        # TO DO: dead char we need to deal with??
                        key_name=u'DEAD_KEY?'
                        print2err("DEAD KEY HIT?")
                    else:    
                        ioe=self._EVENT_TEMPLATE_LIST
                        ioe[3]=Computer._getNextEventID()
                        ioe[4]=ioe_type #event type code
                        ioe[5]=device_time
                        ioe[6]=logged_time
                        ioe[7]=iohub_time
                        ioe[8]=confidence_interval
                        ioe[9]=delay
                        # index 10 is filter id, not used at this time                        
                        ioe[11]=is_auto_repeat

                        ioe[12]=key_code # Quartz does not give the scancode, so fill this with keycode
                        ioe[13]=key_code #key_code
                        ioe[14]=ucode
                        ioe[15]=key_name.encode('utf-8') 
                        ioe[16]=self._mods_sum
                        ioe[17]=window_number
                        
                        self._addNativeEventToBuffer(copy(ioe))
                        #print2err("**Final values:key_name [",key_name,"] ucode: ",ucode, ' key_code: ',key_code)
                else:
                    print2err("\nWARNING: KEYBOARD RECEIVED A [ {0} ] KB EVENT, BUT COULD NOT GENERATE AN IOHUB EVENT FROM IT !!".format(etype)," [",key_name,"] ucode: ",ucode, ' key_code: ',key_code)
                    
                self._last_callback_time=logged_time                
Example #57
0
 def close_popover(self):
     print 'close popover'
     self.window.orderOut_(self.window)
     self._shown = False
     NSEvent.removeMonitor_(self.monitor)