#!/usr/bin/python from rgbkbd.core import Keyboard from rgbkbd.geometry import Keys # Keyboard Modes from rgbkbd.modes.basicmodes import StaticMode from rgbkbd.modes.commandmode import CommandMode class KeyboardManager(object): def __init__(self, device): self.keyboard = Keyboard(device=device) self.active_modes = [] # Initialize variables for key chord tracking self.key_state = {} self.chord = [] self.notifier_number, notify_filename = self.keyboard.alloc_notify() self.notifier = open(notify_filename) # CommandMode is always the last thing available self.mode_start(CommandMode(self, self.keyboard)) # Setup default keyboard mode and start it. self.mode_start(StaticMode(self, self.keyboard)) def shutdown(self): # Set the keyboard to a reasonable default mode self.mode_start(StaticMode(self, self.keyboard)) self.keyboard.free_notify(self.notifier_number) def mode_return(self): """Discards the currently active KeyboardMode mode and initializes the previously active mode. """ prev_mode = self.active_modes.pop() self.current_mode().start(prev_mode) def mode_start(self, mode): """Makes the given mode the current mode and initializes it""" self.active_modes.append(mode) self.current_mode().start() def current_mode(self): """Returns the currently active KeyboardMode object""" # Never goes empty because the CommandMode doesn't go away return self.active_modes[-1] def key_event(self, key, state): """Dispatches key up, key down, and chord events to the current mode. """ #print key, state # DEBUG # Directly pass on up/down key events self.current_mode().event(key, state) # Then track key chords. (Individual typed keys count as a single-key # chord.) self.key_state[key] = state if state == '+': # key down self.chord.append(key) else: # key up if set(self.key_state.values()) != set('-'): # There are still keys that are being held down, so this is an # incomplete chord return # All keys are up chord = self.chord self.chord = [] self.current_mode().chord_event(chord) def tick_rate(self): return self.current_mode().tick_rate