KeyboardManager: a class to manage the polling of a switch-matrix keyboard
Diff: kbd_mgr/KeyPressEventHandler.h
- Revision:
- 3:1310c57aca77
- Parent:
- 2:eb4cc53ff33d
--- a/kbd_mgr/KeyPressEventHandler.h Sun Jan 23 23:15:36 2011 +0000 +++ b/kbd_mgr/KeyPressEventHandler.h Thu Feb 03 22:01:57 2011 +0000 @@ -1,21 +1,82 @@ -#ifndef KEY_PRESS_EVENT_HANDLER_H_ -#define KEY_PRESS_EVENT_HANDLER_H_ - -namespace kbd_mgr { - -/** - * @brief Interface used to report key presses and releases. - */ -class KeyPressEventHandler { -public: - enum { - NoKey = -1 - }; - - virtual void operator()(int key, bool keyDown) = 0; - virtual ~KeyPressEventHandler() { } -}; - -} // kbd_mgr - -#endif // KEY_PRESS_EVENT_HANDLER_H_ +#ifndef KEY_PRESS_EVENT_HANDLER_H_ +#define KEY_PRESS_EVENT_HANDLER_H_ + +namespace kbd_mgr { + +struct KeyEvent { + enum KeyId { + NoKey = -1 + }; + + enum EventType { + NoEvent, KeyDown, KeyPress, RepeatedKeyPress, LongKeyPress, KeyUp + }; + + int keyCode; + char keyChar; + EventType event; + + KeyEvent() : keyCode(NoKey), keyChar(0), event(NoEvent) { } + + /** + * @brief Creates a raw key event (no char). + */ + KeyEvent(int key, EventType event) : keyCode(key), keyChar(0), event(event) { } + + /** + * @brief Converts a raw key event into a mapped key. + */ + KeyEvent(const KeyEvent &raw, char ch) : keyCode(raw.keyCode), keyChar(ch), event(raw.event) { } + + /** + * @brief Creates a key event with a different event code. + */ + KeyEvent(const KeyEvent &other, EventType event) : keyCode(other.keyCode), keyChar(other.keyChar), event(event) { } +}; + +/** + * @brief Interface used to report key presses and releases. + */ +class KeyPressEventHandler { +public: + virtual void handleKeyPress(const KeyEvent &keypress) = 0; + virtual ~KeyPressEventHandler() { } +}; + +template <class T> +class MemberKeyPressEventHandler : public KeyPressEventHandler { +public: + typedef void (T::*MemberFunction)(const KeyEvent &keypress); + + MemberKeyPressEventHandler(T *obj, MemberFunction fn) : + object(obj), func(fn) + { } + + virtual void handleKeyPress(const KeyEvent &keypress) { + (object->*func)(keypress); + } + +private: + T *object; + MemberFunction func; +}; + +class FunctionKeyPressEventHandler : public KeyPressEventHandler { +public: + typedef void (*HandlerFunction)(const KeyEvent &keypress); + + FunctionKeyPressEventHandler(HandlerFunction fn) : + func(fn) + { } + + virtual void handleKeyPress(const KeyEvent &keypress) { + func(keypress); + } + +private: + HandlerFunction func; +}; + +} // kbd_mgr + +#endif // KEY_PRESS_EVENT_HANDLER_H_