Created
September 8, 2020 16:51
-
-
Save dmgl/a5d9a6747a85828c9e947d67031b49d6 to your computer and use it in GitHub Desktop.
Switch layout by CapsLock (added to startup)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import subprocess | |
from pynput import keyboard | |
# Switch layout - Disable | |
# Compose key - Disable | |
# ⌘ key behavior - Shortcut Overlay | |
# Caps Lock bevahior - Disable | |
# The shortcuts triggering switch | |
SWITCH_SHORTCUTS = [ | |
# {keyboard.Key.caps_lock}, | |
# {keyboard.KeyCode(66)}, | |
{keyboard.KeyCode(16777215)}, | |
] | |
# How many layouts do you have? | |
LAYOUTS_COUNT = 2 | |
class Switcher: | |
def __init__(self): | |
self.current_keys = set() | |
self.keys_pressed = 0 | |
# print(self.current_keys) | |
# print(self.keys_pressed) | |
self.monitored_keys = set() | |
for shortcut in SWITCH_SHORTCUTS: | |
self.monitored_keys |= shortcut | |
print(self.monitored_keys) | |
pass | |
self.current_layout = 0 | |
def on_press(self, key): | |
if key not in self.monitored_keys: | |
# print("Need to detect - ", self.monitored_keys) # this section | |
# print("Detected key - ", key) # this section | |
return | |
self.current_keys.add(key) | |
self.keys_pressed += 1 | |
if self.is_switch_shortcut(): | |
self.on_switch() | |
def on_release(self, key): | |
self.keys_pressed -= 1 | |
# Sometimes one key is pressed and another is released. | |
# Blame X server. | |
if key in self.current_keys: | |
self.current_keys.remove(key) | |
if self.keys_pressed <= 0: | |
# print(".") | |
self.keys_pressed = 0 | |
self.current_keys = set() | |
# print(".") | |
def is_switch_shortcut(self): | |
for shortcut in SWITCH_SHORTCUTS: | |
if self.current_keys.issuperset(shortcut): | |
return True | |
return False | |
def on_switch(self): | |
self.current_layout += 1 | |
if self.current_layout >= LAYOUTS_COUNT: | |
self.current_layout = 0 | |
command = [ | |
"gsettings", | |
"set", | |
"org.gnome.desktop.input-sources", | |
"current", | |
str(self.current_layout), | |
] | |
print(command) | |
_exitcode = subprocess.call( | |
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
def main(): | |
switcher = Switcher() | |
with keyboard.Listener( | |
on_press=switcher.on_press, | |
on_release=switcher.on_release) as listener: | |
listener.join() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment