autotyper/xkeyhandler.cpp

88 lines
2.3 KiB
C++

#include "xkeyhandler.h"
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
std::map<SpecialKey, KeySym> XKeyHandler::s_keymap = {
{ SpecialKey::UP, XK_Up },
{ SpecialKey::DOWN, XK_Down },
{ SpecialKey::LEFT, XK_Left },
{ SpecialKey::RIGHT, XK_Right },
{ SpecialKey::HOME, XK_Home },
{ SpecialKey::END, XK_End },
{ SpecialKey::RETURN, XK_Return },
{ SpecialKey::ESCAPE, XK_Escape },
};
XKeyHandler::XKeyHandler()
{
m_disp = XOpenDisplay(nullptr);
}
XKeyHandler::~XKeyHandler()
{
XCloseDisplay(m_disp);
}
void XKeyHandler::Key(SpecialKey key, KeyModifiers mods)
{
WaitUntilNotPaused();
HandleModifierKeys(mods, true);
KeyCode keyCode = XKeysymToKeycode(m_disp, s_keymap.at(key));
XTestFakeKeyEvent(m_disp, keyCode, true, 0);
XTestFakeKeyEvent(m_disp, keyCode, false, 0);
HandleModifierKeys(mods, false);
XFlush(m_disp);
}
void XKeyHandler::Key(char key, KeyModifiers mods)
{
WaitUntilNotPaused();
if (key >= 0x20) {
HandleModifierKeys(mods, true);
KeyCode keyCode = XKeysymToKeycode(m_disp, static_cast<KeySym>(key));
XTestFakeKeyEvent(m_disp, keyCode, true, 0);
XTestFakeKeyEvent(m_disp, keyCode, false, 0);
HandleModifierKeys(mods, false);
XFlush(m_disp);
}
}
void XKeyHandler::HandleModifierKeys(KeyModifiers mods, bool press)
{
// Modifier key up
if (mods & KM_LMETA) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Meta_L), press, 0);
}
if (mods & KM_RMETA) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Meta_R), press, 0);
}
if (mods & KM_LCTRL) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Control_L), press, 0);
}
if (mods & KM_RCTRL) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Control_R), press, 0);
}
if (mods & KM_LALT) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Alt_L), press, 0);
}
if (mods & KM_RALT) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Alt_R), press, 0);
}
if (mods & KM_LSHIFT) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Shift_L), press, 0);
}
if (mods & KM_RSHIFT) {
XTestFakeKeyEvent(m_disp, XKeysymToKeycode(m_disp, XK_Shift_R), press, 0);
}
}