1
0
mirror of https://github.com/EDCD/EDMarketConnector.git synced 2025-06-18 07:53:11 +03:00

hotkey: Basic conversion to Abstract class, and implementation per platform

This commit is contained in:
Athanasius 2021-04-07 17:16:54 +01:00
parent 8aa0337ff4
commit e0a3f1ad53

861
hotkey.py
View File

@ -1,9 +1,11 @@
"""Handle keyboard input for manual update triggering.""" """Handle keyboard input for manual update triggering."""
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import abc
import pathlib import pathlib
import sys
import tkinter as tk import tkinter as tk
from sys import platform from abc import abstractmethod
from typing import Optional, Tuple, Union from typing import Optional, Tuple, Union
from config import config from config import config
@ -11,7 +13,32 @@ from EDMCLogging import get_main_logger
logger = get_main_logger() logger = get_main_logger()
if platform == 'darwin': # noqa: C901
class AbstractHotkeyMgr(abc.abstractmethod):
"""Abstract root class of all platforms specific HotKeyMgr."""
@abstractmethod
def register(self, root, keycode, modifiers) -> None:
"""Register the hotkey handler."""
pass
@abstractmethod
def unregister(self) -> None:
"""Unregister the hotkey handling."""
pass
@abstractmethod
def play_good(self) -> None:
"""Play the 'good' sound."""
pass
@abstractmethod
def play_bad(self) -> None:
"""Play the 'bad' sound."""
pass
if sys.platform == 'darwin':
import objc import objc
from AppKit import ( from AppKit import (
@ -20,257 +47,258 @@ if platform == 'darwin': # noqa: C901
NSFlagsChanged, NSKeyDown, NSKeyDownMask, NSKeyUp, NSNumericPadKeyMask, NSShiftKeyMask, NSSound, NSWorkspace NSFlagsChanged, NSKeyDown, NSKeyDownMask, NSKeyUp, NSNumericPadKeyMask, NSShiftKeyMask, NSSound, NSWorkspace
) )
class HotkeyMgr:
"""Hot key management."""
MODIFIERMASK = NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask | NSNumericPadKeyMask class MacHotkeyMgr(AbstractHotkeyMgr):
POLL = 250 """Hot key management."""
# https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/#//apple_ref/doc/constant_group/Function_Key_Unicodes
DISPLAY = {
0x03: u'', 0x09: u'', 0xd: u'', 0x19: u'', 0x1b: u'esc', 0x20: u'', 0x7f: u'',
0xf700: u'', 0xf701: u'', 0xf702: u'', 0xf703: u'',
0xf727: u'Ins',
0xf728: u'', 0xf729: u'', 0xf72a: u'Fn', 0xf72b: u'',
0xf72c: u'', 0xf72d: u'', 0xf72e: u'PrtScr', 0xf72f: u'ScrollLock',
0xf730: u'Pause', 0xf731: u'SysReq', 0xf732: u'Break', 0xf733: u'Reset',
0xf739: u'',
}
(ACQUIRE_INACTIVE, ACQUIRE_ACTIVE, ACQUIRE_NEW) = range(3)
def __init__(self): MODIFIERMASK = NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask | NSNumericPadKeyMask
self.root = None POLL = 250
# https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/#//apple_ref/doc/constant_group/Function_Key_Unicodes
DISPLAY = {
0x03: u'', 0x09: u'', 0xd: u'', 0x19: u'', 0x1b: u'esc', 0x20: u'', 0x7f: u'',
0xf700: u'', 0xf701: u'', 0xf702: u'', 0xf703: u'',
0xf727: u'Ins',
0xf728: u'', 0xf729: u'', 0xf72a: u'Fn', 0xf72b: u'',
0xf72c: u'', 0xf72d: u'', 0xf72e: u'PrtScr', 0xf72f: u'ScrollLock',
0xf730: u'Pause', 0xf731: u'SysReq', 0xf732: u'Break', 0xf733: u'Reset',
0xf739: u'',
}
(ACQUIRE_INACTIVE, ACQUIRE_ACTIVE, ACQUIRE_NEW) = range(3)
self.keycode = 0 def __init__(self):
self.modifiers = 0 self.root = None
self.activated = False
self.observer = None
self.acquire_key = 0 self.keycode = 0
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE self.modifiers = 0
self.activated = False
self.observer = None
self.tkProcessKeyEvent_old = None self.acquire_key = 0
self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE
self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_( self.tkProcessKeyEvent_old = None
pathlib.Path(config.respath_path) / 'snd_good.wav', False
self.snd_good = NSSound.alloc().initWithContentsOfFile_byReference_(
pathlib.Path(config.respath_path) / 'snd_good.wav', False
)
self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_(
pathlib.Path(config.respath_path) / 'snd_bad.wav', False
)
def register(self, root: tk.Tk, keycode, modifiers) -> None:
"""
Register current hotkey for monitoring.
:param root: parent window.
:param keycode: Key to monitor.
:param modifiers: Any modifiers to take into account.
"""
self.root = root
self.keycode = keycode
self.modifiers = modifiers
self.activated = False
if keycode:
if not self.observer:
self.root.after_idle(self._observe)
self.root.after(MacHotkeyMgr.POLL, self._poll)
# Monkey-patch tk (tkMacOSXKeyEvent.c)
if not self.tkProcessKeyEvent_old:
sel = b'tkProcessKeyEvent:'
cls = NSApplication.sharedApplication().class__()
self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel)
newmethod = objc.selector(
self.tkProcessKeyEvent,
selector=self.tkProcessKeyEvent_old.selector,
signature=self.tkProcessKeyEvent_old.signature
) )
self.snd_bad = NSSound.alloc().initWithContentsOfFile_byReference_( objc.classAddMethod(cls, sel, newmethod)
pathlib.Path(config.respath_path) / 'snd_bad.wav', False
def tkProcessKeyEvent(self, cls, the_event): # noqa: N802
"""
Monkey-patch tk (tkMacOSXKeyEvent.c).
- workaround crash on OSX 10.9 & 10.10 on seeing a composing character
- notice when modifier key state changes
- keep a copy of NSEvent.charactersIgnoringModifiers, which is what we need for the hotkey
(Would like to use a decorator but need to ensure the application is created before this is installed)
:param cls: ???
:param the_event: tk event
:return: ???
"""
if self.acquire_state:
if the_event.type() == NSFlagsChanged:
self.acquire_key = the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask
self.acquire_state = MacHotkeyMgr.ACQUIRE_NEW
# suppress the event by not chaining the old function
return the_event
elif the_event.type() in (NSKeyDown, NSKeyUp):
c = the_event.charactersIgnoringModifiers()
self.acquire_key = (c and ord(c[0]) or 0) | \
(the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask)
self.acquire_state = MacHotkeyMgr.ACQUIRE_NEW
# suppress the event by not chaining the old function
return the_event
# replace empty characters with charactersIgnoringModifiers to avoid crash
elif the_event.type() in (NSKeyDown, NSKeyUp) and not the_event.characters():
the_event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_( # noqa: E501
# noqa: E501
the_event.type(),
the_event.locationInWindow(),
the_event.modifierFlags(),
the_event.timestamp(),
the_event.windowNumber(),
the_event.context(),
the_event.charactersIgnoringModifiers(),
the_event.charactersIgnoringModifiers(),
the_event.isARepeat(),
the_event.keyCode()
) )
return self.tkProcessKeyEvent_old(cls, the_event)
def register(self, root: tk.Tk, keycode, modifiers) -> None: def _observe(self):
""" # Must be called after root.mainloop() so that the app's message loop has been created
Register current hotkey for monitoring. self.observer = NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, self._handler)
:param root: parent window. def _poll(self):
:param keycode: Key to monitor. if config.shutting_down:
:param modifiers: Any modifiers to take into account. return
"""
self.root = root # No way of signalling to Tkinter from within the callback handler block that doesn't
self.keycode = keycode # cause Python to crash, so poll.
self.modifiers = modifiers if self.activated:
self.activated = False self.activated = False
self.root.event_generate('<<Invoke>>', when="tail")
if keycode: if self.keycode or self.modifiers:
if not self.observer: self.root.after(MacHotkeyMgr.POLL, self._poll)
self.root.after_idle(self._observe)
self.root.after(HotkeyMgr.POLL, self._poll)
# Monkey-patch tk (tkMacOSXKeyEvent.c) def unregister(self) -> None:
if not self.tkProcessKeyEvent_old: """Remove hotkey registration."""
sel = b'tkProcessKeyEvent:' self.keycode = None
cls = NSApplication.sharedApplication().class__() self.modifiers = None
self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel)
newmethod = objc.selector(
self.tkProcessKeyEvent,
selector=self.tkProcessKeyEvent_old.selector,
signature=self.tkProcessKeyEvent_old.signature
)
objc.classAddMethod(cls, sel, newmethod)
def tkProcessKeyEvent(self, cls, the_event): # noqa: N802 @objc.callbackFor(NSEvent.addGlobalMonitorForEventsMatchingMask_handler_)
""" def _handler(self, event) -> None:
Monkey-patch tk (tkMacOSXKeyEvent.c). # use event.charactersIgnoringModifiers to handle composing characters like Alt-e
if ((event.modifierFlags() & MacHotkeyMgr.MODIFIERMASK) == self.modifiers
and ord(event.charactersIgnoringModifiers()[0]) == self.keycode):
if config.get_int('hotkey_always'):
self.activated = True
- workaround crash on OSX 10.9 & 10.10 on seeing a composing character else: # Only trigger if game client is front process
- notice when modifier key state changes front = NSWorkspace.sharedWorkspace().frontmostApplication()
- keep a copy of NSEvent.charactersIgnoringModifiers, which is what we need for the hotkey if front and front.bundleIdentifier() == 'uk.co.frontier.EliteDangerous':
(Would like to use a decorator but need to ensure the application is created before this is installed)
:param cls: ???
:param the_event: tk event
:return: ???
"""
if self.acquire_state:
if the_event.type() == NSFlagsChanged:
self.acquire_key = the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask
self.acquire_state = HotkeyMgr.ACQUIRE_NEW
# suppress the event by not chaining the old function
return the_event
elif the_event.type() in (NSKeyDown, NSKeyUp):
c = the_event.charactersIgnoringModifiers()
self.acquire_key = (c and ord(c[0]) or 0) | \
(the_event.modifierFlags() & NSDeviceIndependentModifierFlagsMask)
self.acquire_state = HotkeyMgr.ACQUIRE_NEW
# suppress the event by not chaining the old function
return the_event
# replace empty characters with charactersIgnoringModifiers to avoid crash
elif the_event.type() in (NSKeyDown, NSKeyUp) and not the_event.characters():
the_event = NSEvent.keyEventWithType_location_modifierFlags_timestamp_windowNumber_context_characters_charactersIgnoringModifiers_isARepeat_keyCode_( # noqa: E501
# noqa: E501
the_event.type(),
the_event.locationInWindow(),
the_event.modifierFlags(),
the_event.timestamp(),
the_event.windowNumber(),
the_event.context(),
the_event.charactersIgnoringModifiers(),
the_event.charactersIgnoringModifiers(),
the_event.isARepeat(),
the_event.keyCode()
)
return self.tkProcessKeyEvent_old(cls, the_event)
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)
def _poll(self):
if config.shutting_down:
return
# No way of signalling to Tkinter from within the callback handler block that doesn't
# cause Python to crash, so poll.
if self.activated:
self.activated = False
self.root.event_generate('<<Invoke>>', when="tail")
if self.keycode or self.modifiers:
self.root.after(HotkeyMgr.POLL, self._poll)
def unregister(self) -> None:
"""Remove hotkey registration."""
self.keycode = None
self.modifiers = None
@objc.callbackFor(NSEvent.addGlobalMonitorForEventsMatchingMask_handler_)
def _handler(self, event) -> None:
# use event.charactersIgnoringModifiers to handle composing characters like Alt-e
if ((event.modifierFlags() & HotkeyMgr.MODIFIERMASK) == self.modifiers
and ord(event.charactersIgnoringModifiers()[0]) == self.keycode):
if config.get_int('hotkey_always'):
self.activated = True self.activated = True
else: # Only trigger if game client is front process def acquire_start(self) -> None:
front = NSWorkspace.sharedWorkspace().frontmostApplication() """Start acquiring hotkey state via polling."""
if front and front.bundleIdentifier() == 'uk.co.frontier.EliteDangerous': self.acquire_state = MacHotkeyMgr.ACQUIRE_ACTIVE
self.activated = True self.root.after_idle(self._acquire_poll)
def acquire_start(self) -> None: def acquire_stop(self) -> None:
"""Start acquiring hotkey state via polling.""" """Stop acquiring hotkey state."""
self.acquire_state = HotkeyMgr.ACQUIRE_ACTIVE self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE
self.root.after_idle(self._acquire_poll)
def acquire_stop(self) -> None: def _acquire_poll(self) -> None:
"""Stop acquiring hotkey state.""" """Perform a poll of current hotkey state."""
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE if config.shutting_down:
return
def _acquire_poll(self) -> None: # No way of signalling to Tkinter from within the monkey-patched event handler that doesn't
"""Perform a poll of current hotkey state.""" # cause Python to crash, so poll.
if config.shutting_down: if self.acquire_state:
return if self.acquire_state == MacHotkeyMgr.ACQUIRE_NEW:
# Abuse tkEvent's keycode field to hold our acquired key & modifier
self.root.event_generate('<KeyPress>', keycode=self.acquire_key)
self.acquire_state = MacHotkeyMgr.ACQUIRE_ACTIVE
self.root.after(50, self._acquire_poll)
# No way of signalling to Tkinter from within the monkey-patched event handler that doesn't def fromevent(self, event) -> Optional[Union[bool, Tuple]]:
# cause Python to crash, so poll. """
if self.acquire_state: Return configuration (keycode, modifiers) or None=clear or False=retain previous.
if self.acquire_state == HotkeyMgr.ACQUIRE_NEW:
# Abuse tkEvent's keycode field to hold our acquired key & modifier
self.root.event_generate('<KeyPress>', keycode=self.acquire_key)
self.acquire_state = HotkeyMgr.ACQUIRE_ACTIVE
self.root.after(50, self._acquire_poll)
def fromevent(self, event) -> Optional[Union[bool, Tuple]]: :param event: tk event ?
""" :return: False to retain previous, None to not use, else (keycode, modifiers)
Return configuration (keycode, modifiers) or None=clear or False=retain previous. """
(keycode, modifiers) = (event.keycode & 0xffff, event.keycode & 0xffff0000) # Set by _acquire_poll()
if (keycode
and not (modifiers & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask))):
if keycode == 0x1b: # Esc = retain previous
self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE
return False
:param event: tk event ? # BkSp, Del, Clear = clear hotkey
:return: False to retain previous, None to not use, else (keycode, modifiers) elif keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]:
""" self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE
(keycode, modifiers) = (event.keycode & 0xffff, event.keycode & 0xffff0000) # Set by _acquire_poll() return None
if (keycode
and not (modifiers & (NSShiftKeyMask | NSControlKeyMask | NSAlternateKeyMask | NSCommandKeyMask))):
if keycode == 0x1b: # Esc = retain previous
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE
return False
# BkSp, Del, Clear = clear hotkey # don't allow keys needed for typing in System Map
elif keycode in [0x7f, ord(NSDeleteFunctionKey), ord(NSClearLineFunctionKey)]: elif keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a:
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE NSBeep()
return None self.acquire_state = MacHotkeyMgr.ACQUIRE_INACTIVE
return None
# don't allow keys needed for typing in System Map return (keycode, modifiers)
elif keycode in [0x13, 0x20, 0x2d] or 0x61 <= keycode <= 0x7a:
NSBeep()
self.acquire_state = HotkeyMgr.ACQUIRE_INACTIVE
return None
return (keycode, modifiers) def display(self, keycode, modifiers) -> str:
"""
Return displayable form of given hotkey + modifiers.
def display(self, keycode, modifiers) -> str: :param keycode:
""" :param modifiers:
Return displayable form of given hotkey + modifiers. :return: string form
"""
text = ''
if modifiers & NSControlKeyMask:
text += u''
:param keycode: if modifiers & NSAlternateKeyMask:
:param modifiers: text += u''
:return: string form
"""
text = ''
if modifiers & NSControlKeyMask:
text += u''
if modifiers & NSAlternateKeyMask: if modifiers & NSShiftKeyMask:
text += u'' text += u''
if modifiers & NSShiftKeyMask: if modifiers & NSCommandKeyMask:
text += u'' text += u''
if modifiers & NSCommandKeyMask: if (modifiers & NSNumericPadKeyMask) and keycode <= 0x7f:
text += u'' text += u''
if (modifiers & NSNumericPadKeyMask) and keycode <= 0x7f: if not keycode:
text += u'' pass
if not keycode: elif ord(NSF1FunctionKey) <= keycode <= ord(NSF35FunctionKey):
pass text += f'F{keycode + 1 - ord(NSF1FunctionKey)}'
elif ord(NSF1FunctionKey) <= keycode <= ord(NSF35FunctionKey): elif keycode in MacHotkeyMgr.DISPLAY: # specials
text += f'F{keycode + 1 - ord(NSF1FunctionKey)}' text += MacHotkeyMgr.DISPLAY[keycode]
elif keycode in HotkeyMgr.DISPLAY: # specials elif keycode < 0x20: # control keys
text += HotkeyMgr.DISPLAY[keycode] text += chr(keycode + 0x40)
elif keycode < 0x20: # control keys elif keycode < 0xf700: # key char
text += chr(keycode + 0x40) text += chr(keycode).upper()
elif keycode < 0xf700: # key char else:
text += chr(keycode).upper() text += u''
else: return text
text += u''
return text def play_good(self):
"""Play the 'good' sound."""
self.snd_good.play()
def play_good(self): def play_bad(self):
"""Play the 'good' sound.""" """Play the 'bad' sound."""
self.snd_good.play() self.snd_bad.play()
def play_bad(self):
"""Play the 'bad' sound."""
self.snd_bad.play()
elif platform == 'win32': if sys.platform == 'win32':
import atexit import atexit
import ctypes import ctypes
@ -397,250 +425,259 @@ elif platform == 'win32':
INPUT_KEYBOARD = 1 INPUT_KEYBOARD = 1
INPUT_HARDWARE = 2 INPUT_HARDWARE = 2
class HotkeyMgr:
"""Hot key management."""
# https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx class WindowsHotkeyMgr(AbstractHotkeyMgr):
# Limit ourselves to symbols in Windows 7 Segoe UI """Hot key management."""
DISPLAY = {
0x03: 'Break', 0x08: 'Bksp', 0x09: u'', 0x0c: 'Clear', 0x0d: u'', 0x13: 'Pause',
0x14: u'', 0x1b: 'Esc',
0x20: u'', 0x21: 'PgUp', 0x22: 'PgDn', 0x23: 'End', 0x24: 'Home',
0x25: u'', 0x26: u'', 0x27: u'', 0x28: u'',
0x2c: 'PrtScn', 0x2d: 'Ins', 0x2e: 'Del', 0x2f: 'Help',
0x5d: u'', 0x5f: u'',
0x90: u'', 0x91: 'ScrLk',
0xa6: u'', 0xa7: u'', 0xa9: u'', 0xab: u'', 0xac: u'', 0xb4: u'',
}
def __init__(self): # https://msdn.microsoft.com/en-us/library/windows/desktop/dd375731%28v=vs.85%29.aspx
self.root = None # Limit ourselves to symbols in Windows 7 Segoe UI
self.thread = None DISPLAY = {
with open(pathlib.Path(config.respath) / 'snd_good.wav', 'rb') as sg: 0x03: 'Break', 0x08: 'Bksp', 0x09: u'', 0x0c: 'Clear', 0x0d: u'', 0x13: 'Pause',
self.snd_good = sg.read() 0x14: u'', 0x1b: 'Esc',
with open(pathlib.Path(config.respath) / 'snd_bad.wav', 'rb') as sb: 0x20: u'', 0x21: 'PgUp', 0x22: 'PgDn', 0x23: 'End', 0x24: 'Home',
self.snd_bad = sb.read() 0x25: u'', 0x26: u'', 0x27: u'', 0x28: u'',
atexit.register(self.unregister) 0x2c: 'PrtScn', 0x2d: 'Ins', 0x2e: 'Del', 0x2f: 'Help',
0x5d: u'', 0x5f: u'',
0x90: u'', 0x91: 'ScrLk',
0xa6: u'', 0xa7: u'', 0xa9: u'', 0xab: u'', 0xac: u'', 0xb4: u'',
}
def register(self, root: tk.Tk, keycode, modifiers) -> None: def __init__(self):
"""Register the hotkey handler.""" self.root = None
self.root = root self.thread = None
with open(pathlib.Path(config.respath) / 'snd_good.wav', 'rb') as sg:
self.snd_good = sg.read()
with open(pathlib.Path(config.respath) / 'snd_bad.wav', 'rb') as sb:
self.snd_bad = sb.read()
atexit.register(self.unregister)
if self.thread: def register(self, root: tk.Tk, keycode, modifiers) -> None:
logger.debug('Was already registered, unregistering...') """Register the hotkey handler."""
self.unregister() self.root = root
if keycode or modifiers: if self.thread:
logger.debug('Creating thread worker...') logger.debug('Was already registered, unregistering...')
self.thread = threading.Thread( self.unregister()
target=self.worker,
name=f'Hotkey "{keycode}:{modifiers}"',
args=(keycode, modifiers)
)
self.thread.daemon = True
logger.debug('Starting thread worker...')
self.thread.start()
logger.debug('Done.')
def unregister(self) -> None:
"""Unregister the hotkey handling."""
thread = self.thread
if thread:
logger.debug('Thread is/was running')
self.thread = None
logger.debug('Telling thread WM_QUIT')
PostThreadMessage(thread.ident, WM_QUIT, 0, 0)
logger.debug('Joining thread')
thread.join() # Wait for it to unregister hotkey and quit
else:
logger.debug('No thread')
if keycode or modifiers:
logger.debug('Creating thread worker...')
self.thread = threading.Thread(
target=self.worker,
name=f'Hotkey "{keycode}:{modifiers}"',
args=(keycode, modifiers)
)
self.thread.daemon = True
logger.debug('Starting thread worker...')
self.thread.start()
logger.debug('Done.') logger.debug('Done.')
def worker(self, keycode, modifiers) -> None: # noqa: CCR001 def unregister(self) -> None:
"""Handle hotkeys.""" """Unregister the hotkey handling."""
logger.debug('Begin...') thread = self.thread
# Hotkey must be registered by the thread that handles it
if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode):
logger.debug("We're not the right thread?")
self.thread = None
return
fake = INPUT(INPUT_KEYBOARD, INPUTUNION(ki=KEYBDINPUT(keycode, keycode, 0, 0, None))) if thread:
logger.debug('Thread is/was running')
self.thread = None
logger.debug('Telling thread WM_QUIT')
PostThreadMessage(thread.ident, WM_QUIT, 0, 0)
logger.debug('Joining thread')
thread.join() # Wait for it to unregister hotkey and quit
msg = MSG() else:
logger.debug('Entering GetMessage() loop...') logger.debug('No thread')
while GetMessage(ctypes.byref(msg), None, 0, 0) != 0:
logger.debug('Got message')
if msg.message == WM_HOTKEY:
logger.debug('WM_HOTKEY')
if ( logger.debug('Done.')
config.get_int('hotkey_always')
or window_title(GetForegroundWindow()).startswith('Elite - Dangerous')
):
if not config.shutting_down:
logger.debug('Sending event <<Invoke>>')
self.root.event_generate('<<Invoke>>', when="tail")
else: def worker(self, keycode, modifiers) -> None: # noqa: CCR001
logger.debug('Passing key on') """Handle hotkeys."""
UnregisterHotKey(None, 1) logger.debug('Begin...')
SendInput(1, fake, ctypes.sizeof(INPUT)) # Hotkey must be registered by the thread that handles it
if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode): if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode):
logger.debug("We aren't registered for this ?") logger.debug("We're not the right thread?")
break self.thread = None
return
elif msg.message == WM_SND_GOOD: fake = INPUT(INPUT_KEYBOARD, INPUTUNION(ki=KEYBDINPUT(keycode, keycode, 0, 0, None)))
logger.debug('WM_SND_GOOD')
winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) # synchronous
elif msg.message == WM_SND_BAD: msg = MSG()
logger.debug('WM_SND_BAD') logger.debug('Entering GetMessage() loop...')
winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) # synchronous while GetMessage(ctypes.byref(msg), None, 0, 0) != 0:
logger.debug('Got message')
if msg.message == WM_HOTKEY:
logger.debug('WM_HOTKEY')
if (
config.get_int('hotkey_always')
or window_title(GetForegroundWindow()).startswith('Elite - Dangerous')
):
if not config.shutting_down:
logger.debug('Sending event <<Invoke>>')
self.root.event_generate('<<Invoke>>', when="tail")
else: else:
logger.debug('Something else') logger.debug('Passing key on')
TranslateMessage(ctypes.byref(msg)) UnregisterHotKey(None, 1)
DispatchMessage(ctypes.byref(msg)) SendInput(1, fake, ctypes.sizeof(INPUT))
if not RegisterHotKey(None, 1, modifiers | MOD_NOREPEAT, keycode):
logger.debug("We aren't registered for this ?")
break
logger.debug('Exited GetMessage() loop.') elif msg.message == WM_SND_GOOD:
UnregisterHotKey(None, 1) logger.debug('WM_SND_GOOD')
self.thread = None winsound.PlaySound(self.snd_good, winsound.SND_MEMORY) # synchronous
logger.debug('Done.')
def acquire_start(self) -> None: elif msg.message == WM_SND_BAD:
"""Start acquiring hotkey state via polling.""" logger.debug('WM_SND_BAD')
pass winsound.PlaySound(self.snd_bad, winsound.SND_MEMORY) # synchronous
def acquire_stop(self) -> None:
"""Stop acquiring hotkey state."""
pass
def fromevent(self, event) -> Optional[Union[bool, Tuple]]: # noqa: CCR001
"""
Return configuration (keycode, modifiers) or None=clear or False=retain previous.
event.state is a pain - it shows the state of the modifiers *before* a modifier key was pressed.
event.state *does* differentiate between left and right Ctrl and Alt and between Return and Enter
by putting KF_EXTENDED in bit 18, but RegisterHotKey doesn't differentiate.
:param event: tk event ?
:return: False to retain previous, None to not use, else (keycode, modifiers)
"""
modifiers = ((GetKeyState(VK_MENU) & 0x8000) and MOD_ALT) \
| ((GetKeyState(VK_CONTROL) & 0x8000) and MOD_CONTROL) \
| ((GetKeyState(VK_SHIFT) & 0x8000) and MOD_SHIFT) \
| ((GetKeyState(VK_LWIN) & 0x8000) and MOD_WIN) \
| ((GetKeyState(VK_RWIN) & 0x8000) and MOD_WIN)
keycode = event.keycode
if keycode in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN]:
return (0, modifiers)
if not modifiers:
if keycode == VK_ESCAPE: # Esc = retain previous
return False
elif keycode in [VK_BACK, VK_DELETE, VK_CLEAR, VK_OEM_CLEAR]: # BkSp, Del, Clear = clear hotkey
return None
elif keycode in [VK_RETURN, VK_SPACE, VK_OEM_MINUS] or ord('A') <= keycode <= ord(
'Z'): # don't allow keys needed for typing in System Map
winsound.MessageBeep()
return None
elif (keycode in [VK_NUMLOCK, VK_SCROLL, VK_PROCESSKEY]
or VK_CAPITAL <= keycode <= VK_MODECHANGE): # ignore unmodified mode switch keys
return (0, modifiers)
# See if the keycode is usable and available
if RegisterHotKey(None, 2, modifiers | MOD_NOREPEAT, keycode):
UnregisterHotKey(None, 2)
return (keycode, modifiers)
else: else:
logger.debug('Something else')
TranslateMessage(ctypes.byref(msg))
DispatchMessage(ctypes.byref(msg))
logger.debug('Exited GetMessage() loop.')
UnregisterHotKey(None, 1)
self.thread = None
logger.debug('Done.')
def acquire_start(self) -> None:
"""Start acquiring hotkey state via polling."""
pass
def acquire_stop(self) -> None:
"""Stop acquiring hotkey state."""
pass
def fromevent(self, event) -> Optional[Union[bool, Tuple]]: # noqa: CCR001
"""
Return configuration (keycode, modifiers) or None=clear or False=retain previous.
event.state is a pain - it shows the state of the modifiers *before* a modifier key was pressed.
event.state *does* differentiate between left and right Ctrl and Alt and between Return and Enter
by putting KF_EXTENDED in bit 18, but RegisterHotKey doesn't differentiate.
:param event: tk event ?
:return: False to retain previous, None to not use, else (keycode, modifiers)
"""
modifiers = ((GetKeyState(VK_MENU) & 0x8000) and MOD_ALT) \
| ((GetKeyState(VK_CONTROL) & 0x8000) and MOD_CONTROL) \
| ((GetKeyState(VK_SHIFT) & 0x8000) and MOD_SHIFT) \
| ((GetKeyState(VK_LWIN) & 0x8000) and MOD_WIN) \
| ((GetKeyState(VK_RWIN) & 0x8000) and MOD_WIN)
keycode = event.keycode
if keycode in [VK_SHIFT, VK_CONTROL, VK_MENU, VK_LWIN, VK_RWIN]:
return (0, modifiers)
if not modifiers:
if keycode == VK_ESCAPE: # Esc = retain previous
return False
elif keycode in [VK_BACK, VK_DELETE, VK_CLEAR, VK_OEM_CLEAR]: # BkSp, Del, Clear = clear hotkey
return None
elif keycode in [VK_RETURN, VK_SPACE, VK_OEM_MINUS] or ord('A') <= keycode <= ord(
'Z'): # don't allow keys needed for typing in System Map
winsound.MessageBeep() winsound.MessageBeep()
return None return None
def display(self, keycode, modifiers) -> str: elif (keycode in [VK_NUMLOCK, VK_SCROLL, VK_PROCESSKEY]
""" or VK_CAPITAL <= keycode <= VK_MODECHANGE): # ignore unmodified mode switch keys
Return displayable form of given hotkey + modifiers. return (0, modifiers)
:param keycode: # See if the keycode is usable and available
:param modifiers: if RegisterHotKey(None, 2, modifiers | MOD_NOREPEAT, keycode):
:return: string form UnregisterHotKey(None, 2)
""" return (keycode, modifiers)
text = ''
if modifiers & MOD_WIN:
text += u'❖+'
if modifiers & MOD_CONTROL: else:
text += u'Ctrl+' winsound.MessageBeep()
return None
if modifiers & MOD_ALT: def display(self, keycode, modifiers) -> str:
text += u'Alt+' """
Return displayable form of given hotkey + modifiers.
if modifiers & MOD_SHIFT: :param keycode:
text += u'⇧+' :param modifiers:
:return: string form
"""
text = ''
if modifiers & MOD_WIN:
text += u'❖+'
if VK_NUMPAD0 <= keycode <= VK_DIVIDE: if modifiers & MOD_CONTROL:
text += u'' text += u'Ctrl+'
if not keycode: if modifiers & MOD_ALT:
pass text += u'Alt+'
elif VK_F1 <= keycode <= VK_F24: if modifiers & MOD_SHIFT:
text += f'F{keycode + 1 - VK_F1}' text += u'⇧+'
elif keycode in HotkeyMgr.DISPLAY: # specials if VK_NUMPAD0 <= keycode <= VK_DIVIDE:
text += HotkeyMgr.DISPLAY[keycode] text += u''
if not keycode:
pass
elif VK_F1 <= keycode <= VK_F24:
text += f'F{keycode + 1 - VK_F1}'
elif keycode in WindowsHotkeyMgr.DISPLAY: # specials
text += WindowsHotkeyMgr.DISPLAY[keycode]
else:
c = MapVirtualKey(keycode, 2) # printable ?
if not c: # oops not printable
text += u''
elif c < 0x20: # control keys
text += chr(c + 0x40)
else: else:
c = MapVirtualKey(keycode, 2) # printable ? text += chr(c).upper()
if not c: # oops not printable
text += u''
elif c < 0x20: # control keys return text
text += chr(c + 0x40)
else: def play_good(self) -> None:
text += chr(c).upper() """Play the 'good' sound."""
if self.thread:
PostThreadMessage(self.thread.ident, WM_SND_GOOD, 0, 0)
return text def play_bad(self) -> None:
"""Play the 'bad' sound."""
if self.thread:
PostThreadMessage(self.thread.ident, WM_SND_BAD, 0, 0)
def play_good(self) -> None:
"""Play the 'good' sound."""
if self.thread:
PostThreadMessage(self.thread.ident, WM_SND_GOOD, 0, 0)
def play_bad(self) -> None: class LinuxHotKeyMgr(AbstractHotkeyMgr):
"""Play the 'bad' sound.""" """Hot key management."""
if self.thread:
PostThreadMessage(self.thread.ident, WM_SND_BAD, 0, 0)
else: # Linux pass
class HotkeyMgr:
"""Hot key management."""
def register(self, root, keycode, modifiers) -> None: def get_hotkeymgr(*args, **kwargs) -> AbstractHotkeyMgr:
"""Register the hotkey handler.""" """
pass Determine platform-specific HotkeyMgr.
def unregister(self) -> None: :param args:
"""Unregister the hotkey handling.""" :param kwargs:
pass :return: Appropriate class instance.
:raises ValueError: If unsupported platform.
"""
if sys.platform == 'darwin':
return MacHotkeyMgr(*args, **kwargs)
def play_good(self) -> None: elif sys.platform == 'win32':
"""Play the 'good' sound.""" return WindowsHotkeyMgr(*args, **kwargs)
pass
elif sys.platform == 'linux':
return LinuxHotKeyMgr(*args, **kwargs)
else:
raise ValueError(f'Unknown platform: {sys.platform}')
def play_bad(self) -> None:
"""Play the 'bad' sound."""
pass
# singleton # singleton
hotkeymgr = HotkeyMgr() hotkeymgr = get_hotkeymgr()