KeyboardManager: a class to manage the polling of a switch-matrix keyboard

Dependents:   KeyboardTest

Revision:
3:1310c57aca77
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/KeyMapper.cpp	Thu Feb 03 22:01:57 2011 +0000
@@ -0,0 +1,57 @@
+#include "kbd_mgr/KeyMapper.h"
+#include <algorithm>
+#include <functional>
+
+namespace kbd_mgr {
+
+void KeyMap::addMapping(KeyEvent::EventType event, int key, char ch)
+{
+    const KeyMapping *mapping = getMapping(event, key);
+    if (mapping) {
+        KeyMapping *updatable = const_cast<KeyMapping*>(mapping);
+        updatable->ch = ch;
+    }
+    else {
+        KeyMapping o(event, key, ch);
+        this->map_.push_back(o);
+    }
+}
+
+void KeyMap::addMappings(KeyEvent::EventType event, const std::string &str)
+{
+    for(int key = 0; key < str.size(); ++key) {
+        addMapping(event, key, str[key]);
+    }
+}
+
+char KeyMap::map(KeyEvent::EventType event, int key) const
+{
+    const KeyMapping *mapping = getMapping(event, key);
+    if (!mapping) {
+        mapping = getMapping(KeyEvent::NoEvent, key);
+    }
+    return (mapping ? mapping->ch : '\0');
+}
+
+const KeyMap::KeyMapping * KeyMap::getMapping(KeyEvent::EventType event, int key) const
+{
+    std::pair<KeyEvent::EventType, int> criteria = std::make_pair(event, key);
+    Map::const_iterator p = this->map_.begin();
+    while (p != this->map_.end() && !p->matches(criteria)) {
+        ++p;
+    }
+    
+    if (p == this->map_.end()) {
+        return NULL;
+    }
+    return &(*p);
+}
+
+void KeyMapper::handleKeyPress(const KeyEvent &keypress)
+{
+    char ch = map(keypress.event, keypress.keyCode);
+    KeyEvent mapped(keypress, ch);
+    invokeHandler(mapped);
+}
+
+} // kbd_mgr