1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtGui module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qevdevkeyboardhandler_p.h"
44 #include <qplatformdefs.h>
46 #include <QSocketNotifier>
47 #include <QStringList>
48 #include <QtGui/qwindowsysteminterface.h>
49 #include <QCoreApplication>
50 #include <private/qcore_unix_p.h>
52 #include <linux/input.h>
54 //#define QT_QPA_KEYMAP_DEBUG
56 #ifdef QT_QPA_KEYMAP_DEBUG
62 // simple builtin US keymap
63 #include "qevdevkeyboard_defaultmap_p.h"
65 QEvdevKeyboardHandler::QEvdevKeyboardHandler(const QString &device, int fd, bool disableZap, bool enableCompose, const QString &keymapFile)
66 : m_device(device), m_fd(fd),
67 m_modifiers(0), m_composing(0), m_dead_unicode(0xffff),
68 m_no_zap(disableZap), m_do_compose(enableCompose),
69 m_keymap(0), m_keymap_size(0), m_keycompose(0), m_keycompose_size(0)
71 #ifdef QT_QPA_KEYMAP_DEBUG
72 qWarning() << "Create keyboard handler with for device" << device;
75 setObjectName(QLatin1String("LinuxInput Keyboard Handler"));
77 memset(m_locks, 0, sizeof(m_locks));
79 if (keymapFile.isEmpty() || !loadKeymap(keymapFile))
82 // socket notifier for events on the keyboard device
83 QSocketNotifier *notifier;
84 notifier = new QSocketNotifier(m_fd, QSocketNotifier::Read, this);
85 connect(notifier, SIGNAL(activated(int)), this, SLOT(readKeycode()));
88 QEvdevKeyboardHandler::~QEvdevKeyboardHandler()
96 QEvdevKeyboardHandler *QEvdevKeyboardHandler::create(const QString &device, const QString &specification)
98 #ifdef QT_QPA_KEYMAP_DEBUG
99 qWarning() << "Try to create keyboard handler for" << device << specification;
103 int repeatDelay = 400;
105 bool disableZap = false;
106 bool enableCompose = false;
108 QStringList args = specification.split(QLatin1Char(':'));
109 foreach (const QString &arg, args) {
110 if (arg.startsWith(QLatin1String("keymap=")))
111 keymapFile = arg.mid(7);
112 else if (arg == QLatin1String("disable-zap"))
114 else if (arg == QLatin1String("enable-compose"))
115 enableCompose = true;
116 else if (arg.startsWith(QLatin1String("repeat-delay=")))
117 repeatDelay = arg.mid(13).toInt();
118 else if (arg.startsWith(QLatin1String("repeat-rate=")))
119 repeatRate = arg.mid(12).toInt();
122 #ifdef QT_QPA_KEYMAP_DEBUG
123 qWarning() << "Opening keyboard at" << device;
127 fd = qt_safe_open(device.toLocal8Bit().constData(), O_RDONLY | O_NDELAY, 0);
129 if (repeatDelay > 0 && repeatRate > 0) {
130 int kbdrep[2] = { repeatDelay, repeatRate };
131 ::ioctl(fd, EVIOCSREP, kbdrep);
134 return new QEvdevKeyboardHandler(device, fd, disableZap, enableCompose, keymapFile);
136 qWarning("Cannot open keyboard input device '%s': %s", qPrintable(device), strerror(errno));
141 void QEvdevKeyboardHandler::switchLed(int led, bool state)
143 #ifdef QT_QPA_KEYMAP_DEBUG
144 qWarning() << "switchLed" << led << state;
147 struct ::input_event led_ie;
148 ::gettimeofday(&led_ie.time, 0);
149 led_ie.type = EV_LED;
151 led_ie.value = state;
153 qt_safe_write(m_fd, &led_ie, sizeof(led_ie));
156 void QEvdevKeyboardHandler::readKeycode()
158 #ifdef QT_QPA_KEYMAP_DEBUG
159 qWarning() << "Read new keycode on" << m_device;
162 struct ::input_event buffer[32];
166 int result = qt_safe_read(m_fd, reinterpret_cast<char *>(buffer) + n, sizeof(buffer) - n);
169 qWarning("Got EOF from the input device.");
171 } else if (result < 0) {
172 if (errno != EINTR && errno != EAGAIN) {
173 qWarning("Could not read from input device: %s", strerror(errno));
178 if (n % sizeof(buffer[0]) == 0)
183 n /= sizeof(buffer[0]);
185 for (int i = 0; i < n; ++i) {
186 if (buffer[i].type != EV_KEY)
189 quint16 code = buffer[i].code;
190 qint32 value = buffer[i].value;
192 QEvdevKeyboardHandler::KeycodeAction ka;
193 ka = processKeycode(code, value != 0, value == 2);
196 case QEvdevKeyboardHandler::CapsLockOn:
197 case QEvdevKeyboardHandler::CapsLockOff:
198 switchLed(LED_CAPSL, ka == QEvdevKeyboardHandler::CapsLockOn);
201 case QEvdevKeyboardHandler::NumLockOn:
202 case QEvdevKeyboardHandler::NumLockOff:
203 switchLed(LED_NUML, ka == QEvdevKeyboardHandler::NumLockOn);
206 case QEvdevKeyboardHandler::ScrollLockOn:
207 case QEvdevKeyboardHandler::ScrollLockOff:
208 switchLed(LED_SCROLLL, ka == QEvdevKeyboardHandler::ScrollLockOn);
212 // ignore console switching and reboot
218 void QEvdevKeyboardHandler::processKeyEvent(int nativecode, int unicode, int qtcode,
219 Qt::KeyboardModifiers modifiers, bool isPress, bool autoRepeat)
221 QWindowSystemInterface::handleExtendedKeyEvent(0, (isPress ? QEvent::KeyPress : QEvent::KeyRelease),
222 qtcode, modifiers, nativecode + 8, 0, int(modifiers),
223 QString(unicode), autoRepeat);
226 QEvdevKeyboardHandler::KeycodeAction QEvdevKeyboardHandler::processKeycode(quint16 keycode, bool pressed, bool autorepeat)
228 KeycodeAction result = None;
229 bool first_press = pressed && !autorepeat;
231 const QEvdevKeyboardMap::Mapping *map_plain = 0;
232 const QEvdevKeyboardMap::Mapping *map_withmod = 0;
234 // get a specific and plain mapping for the keycode and the current modifiers
235 for (int i = 0; i < m_keymap_size && !(map_plain && map_withmod); ++i) {
236 const QEvdevKeyboardMap::Mapping *m = m_keymap + i;
237 if (m->keycode == keycode) {
238 if (m->modifiers == 0)
241 quint8 testmods = m_modifiers;
242 if (m_locks[0] /*CapsLock*/ && (m->flags & QEvdevKeyboardMap::IsLetter))
243 testmods ^= QEvdevKeyboardMap::ModShift;
244 if (m->modifiers == testmods)
249 #ifdef QT_QPA_KEYMAP_DEBUG
250 qWarning("Processing key event: keycode=%3d, modifiers=%02x pressed=%d, autorepeat=%d | plain=%d, withmod=%d, size=%d", \
251 keycode, m_modifiers, pressed ? 1 : 0, autorepeat ? 1 : 0, \
252 map_plain ? map_plain - m_keymap : -1, \
253 map_withmod ? map_withmod - m_keymap : -1, \
257 const QEvdevKeyboardMap::Mapping *it = map_withmod ? map_withmod : map_plain;
260 #ifdef QT_QPA_KEYMAP_DEBUG
261 // we couldn't even find a plain mapping
262 qWarning("Could not find a suitable mapping for keycode: %3d, modifiers: %02x", keycode, m_modifiers);
268 quint16 unicode = it->unicode;
269 quint32 qtcode = it->qtcode;
271 if ((it->flags & QEvdevKeyboardMap::IsModifier) && it->special) {
272 // this is a modifier, i.e. Shift, Alt, ...
274 m_modifiers |= quint8(it->special);
276 m_modifiers &= ~quint8(it->special);
277 } else if (qtcode >= Qt::Key_CapsLock && qtcode <= Qt::Key_ScrollLock) {
278 // (Caps|Num|Scroll)Lock
280 quint8 &lock = m_locks[qtcode - Qt::Key_CapsLock];
284 case Qt::Key_CapsLock : result = lock ? CapsLockOn : CapsLockOff; m_modifiers ^= QEvdevKeyboardMap::ModShift; break;
285 case Qt::Key_NumLock : result = lock ? NumLockOn : NumLockOff; break;
286 case Qt::Key_ScrollLock: result = lock ? ScrollLockOn : ScrollLockOff; break;
290 } else if ((it->flags & QEvdevKeyboardMap::IsSystem) && it->special && first_press) {
291 switch (it->special) {
292 case QEvdevKeyboardMap::SystemReboot:
296 case QEvdevKeyboardMap::SystemZap:
301 case QEvdevKeyboardMap::SystemConsolePrevious:
302 result = PreviousConsole;
305 case QEvdevKeyboardMap::SystemConsoleNext:
306 result = NextConsole;
310 if (it->special >= QEvdevKeyboardMap::SystemConsoleFirst &&
311 it->special <= QEvdevKeyboardMap::SystemConsoleLast) {
312 result = KeycodeAction(SwitchConsoleFirst + ((it->special & QEvdevKeyboardMap::SystemConsoleMask) & SwitchConsoleMask));
317 skip = true; // no need to tell Qt about it
318 } else if ((qtcode == Qt::Key_Multi_key) && m_do_compose) {
319 // the Compose key was pressed
323 } else if ((it->flags & QEvdevKeyboardMap::IsDead) && m_do_compose) {
324 // a Dead key was pressed
325 if (first_press && m_composing == 1 && m_dead_unicode == unicode) { // twice
327 qtcode = Qt::Key_unknown; // otherwise it would be Qt::Key_Dead...
328 } else if (first_press && unicode != 0xffff) {
329 m_dead_unicode = unicode;
338 // a normal key was pressed
339 const int modmask = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier;
341 // we couldn't find a specific mapping for the current modifiers,
342 // or that mapping didn't have special modifiers:
343 // so just report the plain mapping with additional modifiers.
344 if ((it == map_plain && it != map_withmod) ||
345 (map_withmod && !(map_withmod->qtcode & modmask))) {
346 qtcode |= QEvdevKeyboardHandler::toQtModifiers(m_modifiers);
349 if (m_composing == 2 && first_press && !(it->flags & QEvdevKeyboardMap::IsModifier)) {
350 // the last key press was the Compose key
351 if (unicode != 0xffff) {
353 // check if this code is in the compose table at all
354 for ( ; idx < m_keycompose_size; ++idx) {
355 if (m_keycompose[idx].first == unicode)
358 if (idx < m_keycompose_size) {
359 // found it -> simulate a Dead key press
360 m_dead_unicode = unicode;
370 } else if (m_composing == 1 && first_press && !(it->flags & QEvdevKeyboardMap::IsModifier)) {
371 // the last key press was a Dead key
373 if (unicode != 0xffff) {
375 // check if this code is in the compose table at all
376 for ( ; idx < m_keycompose_size; ++idx) {
377 if (m_keycompose[idx].first == m_dead_unicode && m_keycompose[idx].second == unicode)
380 if (idx < m_keycompose_size) {
381 quint16 composed = m_keycompose[idx].result;
382 if (composed != 0xffff) {
384 qtcode = Qt::Key_unknown;
390 unicode = m_dead_unicode;
391 qtcode = Qt::Key_unknown;
397 #ifdef QT_QPA_KEYMAP_DEBUG
398 qWarning("Processing: uni=%04x, qt=%08x, qtmod=%08x", unicode, qtcode & ~modmask, (qtcode & modmask));
401 // send the result to the server
402 processKeyEvent(keycode, unicode, qtcode & ~modmask, Qt::KeyboardModifiers(qtcode & modmask), pressed, autorepeat);
408 void QEvdevKeyboardHandler::unloadKeymap()
410 #ifdef QT_QPA_KEYMAP_DEBUG
411 qWarning() << "Unload current keymap and restore built-in";
414 if (m_keymap && m_keymap != s_keymap_default)
416 if (m_keycompose && m_keycompose != s_keycompose_default)
417 delete [] m_keycompose;
419 m_keymap = s_keymap_default;
420 m_keymap_size = sizeof(s_keymap_default) / sizeof(s_keymap_default[0]);
421 m_keycompose = s_keycompose_default;
422 m_keycompose_size = sizeof(s_keycompose_default) / sizeof(s_keycompose_default[0]);
424 // reset state, so we could switch keymaps at runtime
426 memset(m_locks, 0, sizeof(m_locks));
428 m_dead_unicode = 0xffff;
431 bool QEvdevKeyboardHandler::loadKeymap(const QString &file)
433 #ifdef QT_QPA_KEYMAP_DEBUG
434 qWarning() << "Load keymap" << file;
439 if (!f.open(QIODevice::ReadOnly)) {
440 qWarning("Could not open keymap file '%s'", qPrintable(file));
444 // .qmap files have a very simple structure:
445 // quint32 magic (QKeyboard::FileMagic)
446 // quint32 version (1)
447 // quint32 keymap_size (# of struct QKeyboard::Mappings)
448 // quint32 keycompose_size (# of struct QKeyboard::Composings)
449 // all QKeyboard::Mappings via QDataStream::operator(<<|>>)
450 // all QKeyboard::Composings via QDataStream::operator(<<|>>)
452 quint32 qmap_magic, qmap_version, qmap_keymap_size, qmap_keycompose_size;
456 ds >> qmap_magic >> qmap_version >> qmap_keymap_size >> qmap_keycompose_size;
458 if (ds.status() != QDataStream::Ok || qmap_magic != QEvdevKeyboardMap::FileMagic || qmap_version != 1 || qmap_keymap_size == 0) {
459 qWarning("'%s' is ot a valid.qmap keymap file.", qPrintable(file));
463 QEvdevKeyboardMap::Mapping *qmap_keymap = new QEvdevKeyboardMap::Mapping[qmap_keymap_size];
464 QEvdevKeyboardMap::Composing *qmap_keycompose = qmap_keycompose_size ? new QEvdevKeyboardMap::Composing[qmap_keycompose_size] : 0;
466 for (quint32 i = 0; i < qmap_keymap_size; ++i)
467 ds >> qmap_keymap[i];
468 for (quint32 i = 0; i < qmap_keycompose_size; ++i)
469 ds >> qmap_keycompose[i];
471 if (ds.status() != QDataStream::Ok) {
472 delete [] qmap_keymap;
473 delete [] qmap_keycompose;
475 qWarning("Keymap file '%s' can not be loaded.", qPrintable(file));
479 // unload currently active and clear state
482 m_keymap = qmap_keymap;
483 m_keymap_size = qmap_keymap_size;
484 m_keycompose = qmap_keycompose;
485 m_keycompose_size = qmap_keycompose_size;