Source

pyGAP / game / src / input / x11 / keyboard.cpp

Full commit
#include "input/x11/keyboard.h"

#include "common/log.h"
#include <X11/Xlib.h>
#include <X11/keysym.h>

#include <cstring>


namespace input {

#if defined(DEBUG)
common::Log* InputDevice::log_ = NULL;
#endif

namespace x11 {


Keyboard::Keyboard(::Display* display, unsigned char key_map[]):
    display_(display),
    key_map_(key_map)
{
#if defined(DEBUG)
    if (!log_)
        log_ = common::Log::get(__FUNCTION__);
#endif
    LOG("Keyboard created\n")
}


Keyboard::~Keyboard()
{}


int Keyboard::get_value(int index)
{
    //TODO: define what is the range of value depending on various input devices
    return is_pressed(index) ? 1 : 0;
}


int Keyboard::get_key_code(int key)
{
//TODO: precalculate all keycode/keysym at init so there's no need for having
// display_ in the Keyboard class (if compatible with both azerty/qwerty support)
    return ::XKeysymToKeycode(display_, key_code_[key]);
}


int Keyboard::get_pressed_key()
{
    char bit;
    int b;

    for (int i = 0; i < 32; i++) {
        if (key_map_[i]) {
            for (b = 0; b < 8; b++) {
                bit = key_map_[i] >> b;
                if (1 & bit)
                    break;
            }
            return ((i << 3) | b);
        }
    }
    return -1;
}


void Keyboard::get_key_symbol(int key, char* name)
{
//TODO: precalculate all keycode/keysym at init so there's no need for having
// display_ in the Keyboard class (if compatible with both azerty/qwerty support)
    KeyCode key_code = key;

    KeySym key_symbol = ::XKeycodeToKeysym(display_, key_code, 0);
    char* key_symbol_string = ::XKeysymToString(key_symbol);

    strcpy(name, key_symbol_string);

    LOG("Key code: 0x%02x\n", key_code)
    LOG("Key symbol: %s (0x%02x)(len: %i)\n", key_symbol_string, key_symbol, strlen(key_symbol_string))
}


bool Keyboard::is_pressed(int key)
{
    KeyCode key_code = key;
    bool pressed = 1 & (key_map_[key_code >> 3] >> (key_code & 0x07));
    return pressed ? true : false;
}


} // namespace x11
} // namespace input