swift
Loading...
Searching...
No Matches
keyboardlinux.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "keyboardlinux.h"
5
6#include <X11/XKBlib.h>
7#include <X11/keysym.h>
8#include <fcntl.h>
9#include <linux/input.h>
10
11#include <utility>
12
13#include <QDebug>
14#include <QHash>
15#include <QSocketNotifier>
16
17#include "misc/logmessage.h"
18
19using namespace swift::misc;
20using namespace swift::misc::input;
21
22namespace swift::input
23{
24 // https://www.cl.cam.ac.uk/~mgk25/ucs/keysymdef.h
25 static QHash<int, misc::input::KeyCode> keyMapping {
26 { XK_0, Key_0 },
27 { XK_1, Key_1 },
28 { XK_2, Key_2 },
29 { XK_3, Key_3 },
30 { XK_4, Key_4 },
31 { XK_5, Key_5 },
32 { XK_6, Key_6 },
33 { XK_7, Key_7 },
34 { XK_8, Key_8 },
35 { XK_9, Key_9 },
36 { XK_a, Key_A },
37 { XK_b, Key_B },
38 { XK_c, Key_C },
39 { XK_d, Key_D },
40 { XK_e, Key_E },
41 { XK_f, Key_F },
42 { XK_g, Key_G },
43 { XK_h, Key_H },
44 { XK_i, Key_I },
45 { XK_j, Key_J },
46 { XK_k, Key_K },
47 { XK_l, Key_L },
48 { XK_m, Key_M },
49 { XK_n, Key_N },
50 { XK_o, Key_O },
51 { XK_p, Key_P },
52 { XK_q, Key_Q },
53 { XK_r, Key_R },
54 { XK_s, Key_S },
55 { XK_t, Key_T },
56 { XK_u, Key_U },
57 { XK_v, Key_V },
58 { XK_w, Key_W },
59 { XK_x, Key_X },
60 { XK_y, Key_Y },
61 { XK_z, Key_Z },
62 { XK_Shift_L, Key_ShiftLeft },
63 { XK_Shift_R, Key_ShiftRight },
64 { XK_Control_L, Key_ControlLeft },
65 { XK_Control_R, Key_ControlRight },
66 { XK_Alt_L, Key_AltLeft },
67 { XK_Alt_R, Key_AltRight },
68 { XK_KP_Add, Key_Plus },
69 { XK_plus, Key_Plus },
70 { XK_KP_Subtract, Key_Minus },
71 { XK_minus, Key_Minus },
72 { XK_period, Key_Period },
73 { XK_KP_Divide, Key_Divide },
74 { XK_KP_Multiply, Key_Multiply },
75 { XK_KP_Subtract, Key_NumpadMinus },
76 { XK_KP_Add, Key_NumpadPlus },
77 { XK_KP_Delete, Key_NumpadDelete },
78 { XK_BackSpace, Key_Back },
79 { XK_Tab, Key_Tab },
80 { XK_Escape, Key_Esc },
81 { XK_space, Key_Space },
82 { XK_dead_grave, Key_DeadGrave },
83 { XK_comma, Key_Comma },
84 { XK_Delete, Key_Delete },
85 { XK_Insert, Key_Insert },
86 { XK_Home, Key_Home },
87 { XK_End, Key_End },
88 { XK_Page_Up, Key_PageUp },
89 { XK_Page_Down, Key_PageDown },
90 { XK_Caps_Lock, Key_CapsLock },
91 { XK_Return, Key_Enter },
92 { XK_F1, Key_Function1 },
93 { XK_F2, Key_Function2 },
94 { XK_F3, Key_Function3 },
95 { XK_F4, Key_Function4 },
96 { XK_F5, Key_Function5 },
97 { XK_F6, Key_Function6 },
98 { XK_F7, Key_Function7 },
99 { XK_F8, Key_Function8 },
100 { XK_F9, Key_Function9 },
101 { XK_F10, Key_Function10 },
102 { XK_F11, Key_Function11 },
103 { XK_F12, Key_Function12 },
104 { XK_F13, Key_Function13 },
105 { XK_F14, Key_Function14 },
106 { XK_F15, Key_Function15 },
107 { XK_F16, Key_Function16 },
108 { XK_F17, Key_Function17 },
109 { XK_F18, Key_Function18 },
110 { XK_F19, Key_Function19 },
111 { XK_F20, Key_Function20 },
112 { XK_F21, Key_Function21 },
113 { XK_F22, Key_Function22 },
114 { XK_F23, Key_Function23 },
115 { XK_F24, Key_Function24 },
116
129 };
130
131 CKeyboardLinux::CKeyboardLinux(QObject *parent) : IKeyboard(parent) { m_display = XOpenDisplay(nullptr); }
132
134 {
135 if (m_display) XCloseDisplay(m_display);
136 }
137
139 {
140 QString dir = QLatin1String("/dev/input");
141 m_devInputWatcher = new QFileSystemWatcher(QStringList(dir), this);
142 connect(m_devInputWatcher, &QFileSystemWatcher::directoryChanged, this,
143 &CKeyboardLinux::deviceDirectoryChanged);
144 deviceDirectoryChanged(dir);
145
146 return true;
147 }
148
149 void CKeyboardLinux::deviceDirectoryChanged(const QString &dir)
150 {
151 QDir eventFiles(dir, QLatin1String("event*"), QDir::Name, QDir::System);
152
153 foreach (QFileInfo fileInfo, eventFiles.entryInfoList())
154 {
155 QString path = fileInfo.absoluteFilePath();
156 if (!m_keyboardDevices.contains(path)) addRawInputDevice(path);
157 }
158 }
159
160 void CKeyboardLinux::inputReadyRead(int)
161 {
162 struct input_event eventInput;
163
164 auto fileInput = qobject_cast<QFile *>(sender()->parent());
165 if (!fileInput) return;
166
167 bool found = false;
168
169 while (std::cmp_equal(fileInput->read(reinterpret_cast<char *>(&eventInput), sizeof(eventInput)),
170 sizeof(eventInput)))
171 {
172 found = true;
173 if (eventInput.type != EV_KEY) continue;
174 bool isPressed = false;
175 switch (eventInput.value)
176 {
177 case 0: isPressed = false; break;
178 case 1: isPressed = true; break;
179 default: continue;
180 }
181
182 // The + 8 offset is required for XkbKeycodeToKeysym to output the correct Keysym
183 int keyCode = eventInput.code + 8;
184 keyEvent(keyCode, isPressed);
185 }
186
187 if (!found)
188 {
189 int fd = fileInput->handle();
190 int version = 0;
191 if ((ioctl(fd, EVIOCGVERSION, &version) < 0) || (((version >> 16) & 0xFF) < 1))
192 {
193 qWarning("CKeyboardLinux: Removing dead input device %s", qPrintable(fileInput->fileName()));
194 m_keyboardDevices.remove(fileInput->fileName());
195 }
196 }
197 }
198
199 void CKeyboardLinux::addRawInputDevice(const QString &filePath)
200 {
201 QSharedPointer<QFile> inputFile(new QFile(filePath));
202 if (inputFile->open(QIODevice::ReadOnly))
203 {
204 int fd = inputFile->handle();
205 if (fd < 0)
206 {
207 return;
208 }
209
210 int version = 0;
211 if (ioctl(fd, EVIOCGVERSION, &version) < 0)
212 {
213 return;
214 }
215
216 char deviceName[255];
217 if (ioctl(fd, EVIOCGNAME(sizeof(deviceName)), deviceName) < 0)
218 {
219 return;
220 }
221
222 uint8_t bitmask[EV_MAX / 8 + 1];
223 memset(bitmask, 0, sizeof(bitmask));
224 if (ioctl(fd, EVIOCGBIT(0, sizeof(bitmask)), &bitmask) < 0)
225 {
226 return;
227 }
228
229 // Keyboards support EV_SYN and EV_KEY
230 // but do NOT support EV_REL and EV_ABS
231 if (!(bitmask[EV_SYN / 8] & (1 << (EV_SYN % 8))) && !(bitmask[EV_KEY / 8] & (1 << (EV_KEY % 8))) &&
232 (bitmask[EV_REL / 8] & (1 << (EV_REL % 8))) && (bitmask[EV_ABS / 8] & (1 << (EV_ABS % 8))))
233 {
234 return;
235 }
236
237 // Is it grabbed by someone else?
238 if ((ioctl(fd, EVIOCGRAB, 1) < 0))
239 {
241 u"Device exclusively grabbed by someone else (X11 using exclusive-mode evdev?)")
242 << deviceName;
243 }
244 else
245 {
246 ioctl(fd, EVIOCGRAB, 0);
247 uint8_t keys[KEY_MAX / 8 + 1];
248 if ((ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keys)), &keys) >= 0) &&
249 (keys[KEY_SPACE / 8] & (1 << (KEY_SPACE % 8))))
250 {
251 swift::misc::CLogMessage(this).info(u"Found keyboard: %1") << deviceName;
252
253 fcntl(inputFile->handle(), F_SETFL, O_NONBLOCK);
254 connect(new QSocketNotifier(inputFile->handle(), QSocketNotifier::Read, inputFile.data()),
255 &QSocketNotifier::activated, this, &CKeyboardLinux::inputReadyRead);
256
257 m_keyboardDevices.insert(filePath, inputFile);
258 }
259 }
260 }
261 else
262 {
263 swift::misc::CLogMessage(this).error(u"Failed to open keyboard device %1: %2")
264 << inputFile->fileName() << inputFile->errorString();
265 }
266 }
267
268 void CKeyboardLinux::keyEvent(int keyCode, bool isPressed)
269 {
270 if (isMouseButton(keyCode))
271 {
272 return;
273 }
274
275 swift::misc::input::CHotkeyCombination oldCombination(m_keyCombination);
276 if (isPressed)
277 {
278 auto key = convertToKey(keyCode);
279 if (key == Key_Unknown)
280 {
281 return;
282 }
283
284 m_keyCombination.addKeyboardKey(key);
285 }
286 else
287 {
288 auto key = convertToKey(keyCode);
289 if (key == Key_Unknown)
290 {
291 return;
292 }
293
294 m_keyCombination.removeKeyboardKey(key);
295 }
296
297 if (oldCombination != m_keyCombination)
298 {
299 emit keyCombinationChanged(m_keyCombination);
300 }
301 }
302
303 swift::misc::input::KeyCode CKeyboardLinux::convertToKey(int keyCode)
304 {
305 // The keycode received from kernel does not take keyboard layouts into account.
306 // It always defaults to US keyboards. In contrast to kernel devices, X11 is aware
307 // of user keyboard layouts. The magic below translates the key code
308 // into the correct symbol via a X11 connection.
309 // Summary of translations:
310 // Kernel key code -> X11 key symbol -> swift key code
311
312 auto keySym = XkbKeycodeToKeysym(m_display, keyCode, 0, 0);
313 return keyMapping.value(keySym, Key_Unknown);
314 }
315
316 bool CKeyboardLinux::isModifier(int keyCode)
317 {
318 auto keySym = XkbKeycodeToKeysym(m_display, keyCode, 0, 0);
319 switch (keySym)
320 {
321 case XK_Shift_L:
322 case XK_Shift_R:
323 case XK_Control_L:
324 case XK_Control_R:
325 case XK_Alt_L:
326 case XK_Alt_R: return true;
327 default: return false;
328 }
329
330 return false;
331 }
332
333 bool CKeyboardLinux::isMouseButton(int keyCode)
334 {
335 switch (keyCode)
336 {
337 case BTN_LEFT:
338 case BTN_RIGHT:
339 case BTN_MIDDLE: return true;
340 default: return false;
341 }
342 }
343} // namespace swift::input
bool init()
Initializes the platform keyboard device.
CKeyboardLinux(CKeyboardLinux const &)=delete
Copy Constructor.
Abstract interface for native keyboard handling.
Definition keyboard.h:23
Class for emitting a log message.
Definition logmessage.h:27
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
Value object representing hotkey sequence.
KeyCode
Key code http://www.kbdlayout.info/.
Definition keycodes.h:16
Free functions in swift::misc.
QString absoluteFilePath() const const
void directoryChanged(const QString &path)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void activated(QSocketDescriptor socket, QSocketNotifier::Type type)
void keyEvent(QTest::KeyAction action, QWidget *widget, Qt::Key key, Qt::KeyboardModifiers modifier, int delay)
QFuture< QtFuture::ArgsType< Signal > > connect(Sender *sender, Signal signal)