foxygit / TV-Launcher Log in
commits tags

/src/virtualinput.cpp · 5.14 KB

raw
#include "virtualinput.h"

#include <QHash>
#include <QtGlobal>

#include <cstring>
#include <fcntl.h>
#include <linux/uinput.h>
#include <sys/ioctl.h>
#include <unistd.h>

VirtualInput::~VirtualInput()
{
    if (m_fd >= 0) {
        releaseAll();
        ioctl(m_fd, UI_DEV_DESTROY);
        ::close(m_fd);
    }
}

bool VirtualInput::open()
{
    if (m_fd >= 0)
        return true;
    const int fd = ::open("/dev/uinput", O_WRONLY | O_NONBLOCK | O_CLOEXEC);
    if (fd < 0)
        return false;

    ioctl(fd, UI_SET_EVBIT, EV_KEY);
    // Alla vanliga tangenter (KEY_ESC..KEY_102ND) samt navigering och musknappar.
    for (int code = KEY_ESC; code <= KEY_102ND; ++code)
        ioctl(fd, UI_SET_KEYBIT, code);
    for (int code : {KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_RIGHTALT, KEY_PAGEUP,
                     KEY_PAGEDOWN, KEY_HOME, KEY_END, KEY_DELETE, BTN_LEFT, BTN_RIGHT, BTN_MIDDLE})
        ioctl(fd, UI_SET_KEYBIT, code);
    ioctl(fd, UI_SET_EVBIT, EV_REL);
    for (int code : {REL_X, REL_Y, REL_WHEEL, REL_HWHEEL})
        ioctl(fd, UI_SET_RELBIT, code);

    uinput_setup setup;
    std::memset(&setup, 0, sizeof(setup));
    setup.id.bustype = BUS_VIRTUAL;
    setup.id.vendor = 0x1209;
    setup.id.product = 0x7476;
    std::strncpy(setup.name, "tv-launcher virtual input", UINPUT_MAX_NAME_SIZE - 1);
    if (ioctl(fd, UI_DEV_SETUP, &setup) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) {
        ::close(fd);
        return false;
    }
    m_fd = fd;
    return true;
}

void VirtualInput::write(int type, int code, int value)
{
    input_event ev;
    std::memset(&ev, 0, sizeof(ev));
    ev.type = type;
    ev.code = code;
    ev.value = value;
    if (::write(m_fd, &ev, sizeof(ev)) < 0) {
        // Ignorera; nästa händelse försöker igen.
    }
}

void VirtualInput::sync() { write(EV_SYN, SYN_REPORT, 0); }

void VirtualInput::key(int code, bool down)
{
    if (m_fd < 0 || down == m_down.contains(code))
        return;
    if (down) m_down.insert(code); else m_down.remove(code);
    write(EV_KEY, code, down ? 1 : 0);
    sync();
}

void VirtualInput::move(int dx, int dy)
{
    if (m_fd < 0 || (dx == 0 && dy == 0))
        return;
    if (dx) write(EV_REL, REL_X, dx);
    if (dy) write(EV_REL, REL_Y, dy);
    sync();
}

void VirtualInput::wheel(int steps, bool horizontal)
{
    if (m_fd < 0 || steps == 0)
        return;
    write(EV_REL, horizontal ? REL_HWHEEL : REL_WHEEL, steps);
    sync();
}

void VirtualInput::releaseAll()
{
    const auto down = m_down;
    for (int code : down)
        key(code, false);
}

namespace {
struct KeyStroke { int code; bool shift; bool altgr; };

// Svensk layout (xkb "se").
const QHash<QChar, KeyStroke> &swedishMap()
{
    static const QHash<QChar, KeyStroke> map = [] {
        QHash<QChar, KeyStroke> m;
        auto row = [&m](const char *chars, int first) {
            for (int i = 0; chars[i]; ++i) {
                m.insert(QChar(chars[i]), {first + i, false, false});
                m.insert(QChar(chars[i]).toUpper(), {first + i, true, false});
            }
        };
        row("qwertyuiop", KEY_Q);
        row("asdfghjkl", KEY_A);
        row("zxcvbnm", KEY_Z);
        const char *digits = "1234567890";
        const char *shifted = "!\"#\0%&/()=";   // ¤ på 4 hoppas över
        for (int i = 0; i < 10; ++i) {
            m.insert(QChar(digits[i]), {KEY_1 + i, false, false});
            if (shifted[i]) m.insert(QChar(shifted[i]), {KEY_1 + i, true, false});
        }
        auto add = [&m](QChar c, int code, bool shift = false, bool altgr = false) {
            m.insert(c, {code, shift, altgr});
        };
        add(QChar(0xe5), KEY_LEFTBRACE); add(QChar(0xc5), KEY_LEFTBRACE, true);   // å Å
        add(QChar(0xe4), KEY_APOSTROPHE); add(QChar(0xc4), KEY_APOSTROPHE, true); // ä Ä
        add(QChar(0xf6), KEY_SEMICOLON); add(QChar(0xd6), KEY_SEMICOLON, true);   // ö Ö
        add('+', KEY_MINUS); add('?', KEY_MINUS, true); add('\\', KEY_MINUS, false, true);
        add('\'', KEY_BACKSLASH); add('*', KEY_BACKSLASH, true);
        add(',', KEY_COMMA); add(';', KEY_COMMA, true);
        add('.', KEY_DOT); add(':', KEY_DOT, true);
        add('-', KEY_SLASH); add('_', KEY_SLASH, true);
        add('<', KEY_102ND); add('>', KEY_102ND, true); add('|', KEY_102ND, false, true);
        add('@', KEY_2, false, true); add(QChar(0xa3), KEY_3, false, true);        // @ £
        add('$', KEY_4, false, true); add(QChar(0x20ac), KEY_E, false, true);      // $ €
        add('{', KEY_7, false, true); add('[', KEY_8, false, true);
        add(']', KEY_9, false, true); add('}', KEY_0, false, true);
        add(' ', KEY_SPACE); add('\n', KEY_ENTER); add('\t', KEY_TAB);
        return m;
    }();
    return map;
}
} // namespace

void VirtualInput::typeText(const QString &text)
{
    if (m_fd < 0)
        return;
    const auto &map = swedishMap();
    for (const QChar c : text) {
        const auto it = map.constFind(c);
        if (it == map.cend())
            continue;
        if (it->shift) key(KEY_LEFTSHIFT, true);
        if (it->altgr) key(KEY_RIGHTALT, true);
        key(it->code, true);
        key(it->code, false);
        if (it->altgr) key(KEY_RIGHTALT, false);
        if (it->shift) key(KEY_LEFTSHIFT, false);
    }
}