summaryrefslogtreecommitdiffstats
path: root/src/plugins/generic/bsdkeyboard/qbsdkeyboard.cpp
blob: f2f177e9a2b8704968e2ffe1d296eea4553ec375 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Copyright (C) 2015-2016 Oleksandr Tymoshenko <gonzo@bluezbox.com>
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qbsdkeyboard.h"

#include <QByteArray>
#include <QFile>
#include <QGuiApplication>
#include <QPoint>
#include <QSocketNotifier>
#include <QString>
#include <QStringList>

#include <QtCore/qglobal.h>
#include <qpa/qwindowsysteminterface.h>
#include <private/qcore_unix_p.h>
#include <private/qguiapplication_p.h>
#include <private/qinputdevicemanager_p_p.h>

#include <qdebug.h>
#include <cstdio>

#include <cerrno>
#include <fcntl.h>
#include <unistd.h>

#include <termios.h>
#include <sys/kbio.h>

// #define QT_BSD_KEYBOARD_DEBUG

#ifdef QT_BSD_KEYBOARD_DEBUG
#include <qdebug.h>
#endif

QT_BEGIN_NAMESPACE

enum {
    Bsd_KeyCodeMask     = 0x7f,
    Bsd_KeyPressedMask  = 0x80
};

#include "qbsdkeyboard_defaultmap.h"

QBsdKeyboardHandler::QBsdKeyboardHandler(const QString &key, const QString &specification)
{
    Q_UNUSED(key);

    setObjectName(QLatin1String("BSD Keyboard Handler"));

    QByteArray device;
    if (specification.startsWith("/dev/"))
        device = QFile::encodeName(specification);

    if (device.isEmpty()) {
        device = QByteArrayLiteral("STDIN");
        m_fd = fileno(stdin);
    }
    else {
        m_fd = QT_OPEN(device.constData(), O_RDONLY);
        if (!m_fd) {
            qErrnoWarning(errno, "open(%s) failed", device.constData());
            return;
        }
        m_shouldClose = true;
    }

    if (ioctl(m_fd, KDGKBMODE, &m_origKbdMode)) {
        qErrnoWarning(errno, "ioctl(%s, KDGKBMODE) failed", device.constData());
        revertTTYSettings();
        return;
    }

    if (ioctl(m_fd, KDSKBMODE, K_CODE) < 0) {
        qErrnoWarning(errno, "ioctl(%s, KDSKBMODE) failed", device.constData());
        revertTTYSettings();
        return;
    }

    termios kbdtty;
    if (tcgetattr(m_fd, &kbdtty) == 0) {

        m_kbdOrigTty.reset(new termios);
        *m_kbdOrigTty = kbdtty;

        kbdtty.c_iflag = IGNPAR | IGNBRK;
        kbdtty.c_oflag = 0;
        kbdtty.c_cflag = CREAD | CS8;
        kbdtty.c_lflag = 0;
        kbdtty.c_cc[VTIME] = 0;
        kbdtty.c_cc[VMIN] = 0;
        cfsetispeed(&kbdtty, 9600);
        cfsetospeed(&kbdtty, 9600);
        if (tcsetattr(m_fd, TCSANOW, &kbdtty) < 0) {
            qErrnoWarning(errno, "tcsetattr(%s) failed", device.constData());

            // TTY is still at old settings so we can
            // dispose of original termios data
            m_kbdOrigTty.reset();

            revertTTYSettings();
            return;
        }
    } else {
        qErrnoWarning(errno, "tcgetattr(%s) failed", device.constData());
        revertTTYSettings();
        return;
    }

    if (fcntl(m_fd, F_SETFL, O_NONBLOCK)) {
        qErrnoWarning(errno, "fcntl(%s, F_SETFL, O_NONBLOCK) failed", device.constData());
        revertTTYSettings();
        return;
    }

    resetKeymap();

    m_notifier.reset(new QSocketNotifier(m_fd, QSocketNotifier::Read, this));
    connect(m_notifier.data(), &QSocketNotifier::activated, this, &QBsdKeyboardHandler::readKeyboardData);
    QInputDeviceManagerPrivate::get(QGuiApplicationPrivate::inputDeviceManager())->setDeviceCount(
        QInputDeviceManager::DeviceTypeKeyboard, 1);
}

QBsdKeyboardHandler::~QBsdKeyboardHandler()
{
    revertTTYSettings();
}

void QBsdKeyboardHandler::revertTTYSettings()
{
    if (m_fd >= 0) {
        if (m_kbdOrigTty) {
            tcsetattr(m_fd, TCSANOW, m_kbdOrigTty.data());
            m_kbdOrigTty.reset();
        }

        if (m_origKbdMode != Bsd_NoKeyMode) {
            ioctl(m_fd, KDSKBMODE, m_origKbdMode);
            m_origKbdMode = Bsd_NoKeyMode;
        }

        if (m_shouldClose)
            close(m_fd);
        m_fd = -1;
    }
}

void QBsdKeyboardHandler::readKeyboardData()
{

    for (;;) {
        uint8_t buffer[32];
        int bytesRead = qt_safe_read(m_fd, buffer, sizeof(buffer));

        if (!bytesRead) {
            qWarning("Got EOF from the input device.");
            return;
        } else if (bytesRead < 0) {
            if (errno != EINTR && errno != EAGAIN)
                qWarning("Could not read from input device: %s", strerror(errno));
            return;
        }

        for (int i = 0; i < bytesRead; ++i) {
            const quint16 code = buffer[i] & Bsd_KeyCodeMask;
            const bool pressed = (buffer[i] & Bsd_KeyPressedMask) ? false : true;

            processKeycode(code, pressed, false);
        }
    }
}

void QBsdKeyboardHandler::processKeyEvent(int nativecode, int unicode, int qtcode,
                                          Qt::KeyboardModifiers modifiers, bool isPress,
                                          bool autoRepeat)
{
    const QString text = (unicode != 0xffff ) ? QString(unicode) : QString();
    const QEvent::Type eventType = isPress ? QEvent::KeyPress : QEvent::KeyRelease;

    QWindowSystemInterface::handleExtendedKeyEvent(0, eventType, qtcode, modifiers, nativecode, 0,
                                                   int(modifiers), text, autoRepeat);
}

void QBsdKeyboardHandler::processKeycode(quint16 keycode, bool pressed, bool autorepeat)
{
    const bool first_press = pressed && !autorepeat;

    const QBsdKeyboardMap::Mapping *map_plain = nullptr;
    const QBsdKeyboardMap::Mapping *map_withmod = nullptr;

    quint8 modifiers = m_modifiers;

    // get a specific and plain mapping for the keycode and the current modifiers
    for (const QBsdKeyboardMap::Mapping &m : m_keymap) {
        if (m.keycode == keycode) {
            if (m.modifiers == 0)
                map_plain = &m;

            quint8 testmods = m_modifiers;
            if (m_capsLock && (m.flags & QBsdKeyboardMap::IsLetter))
                testmods ^= QBsdKeyboardMap::ModShift;
            if (m.modifiers == testmods)
                map_withmod = &m;
        }
    }

    if (m_capsLock && map_withmod && (map_withmod->flags & QBsdKeyboardMap::IsLetter))
        modifiers ^= QBsdKeyboardMap::ModShift;

#ifdef QT_BSD_KEYBOARD_DEBUG
    qWarning("Processing key event: keycode=%3d, modifiers=%02x pressed=%d, autorepeat=%d", \
             keycode, modifiers, pressed ? 1 : 0, autorepeat ? 1 : 0);
#endif

    const QBsdKeyboardMap::Mapping *it = map_withmod ? map_withmod : map_plain;

    if (!it) {
#ifdef QT_BSD_KEYBOARD_DEBUG
        // we couldn't even find a plain mapping
        qWarning("Could not find a suitable mapping for keycode: %3d, modifiers: %02x", keycode, modifiers);
#endif
        return;
    }

    bool skip = false;
    quint16 unicode = it->unicode;
    quint32 qtcode = it->qtcode;

    if ((it->flags & QBsdKeyboardMap::IsModifier) && it->special) {
        // this is a modifier, i.e. Shift, Alt, ...
        if (pressed)
            m_modifiers |= quint8(it->special);
        else
            m_modifiers &= ~quint8(it->special);
    } else if (qtcode >= Qt::Key_CapsLock && qtcode <= Qt::Key_ScrollLock) {
        // (Caps|Num|Scroll)Lock
        if (first_press) {
            switch (qtcode) {
            case Qt::Key_CapsLock:
                m_capsLock = !m_capsLock;
                switchLed(LED_CAP, m_capsLock);
                break;
            case Qt::Key_NumLock:
                m_numLock = !m_numLock;
                switchLed(LED_NUM, m_numLock);
                break;
            case Qt::Key_ScrollLock:
                m_scrollLock = !m_scrollLock;
                switchLed(LED_SCR, m_scrollLock);
                break;
            default:
                break;
            }
        }
    }

    if (!skip) {
        // a normal key was pressed
        const int modmask = Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier
            | Qt::MetaModifier | Qt::KeypadModifier;

        // we couldn't find a specific mapping for the current modifiers,
        // or that mapping didn't have special modifiers:
        // so just report the plain mapping with additional modifiers.
        if ((it == map_plain && it != map_withmod) ||
            (map_withmod && !(map_withmod->qtcode & modmask))) {
            qtcode |= QBsdKeyboardHandler::toQtModifiers(modifiers);
        }

#ifdef QT_BSD_KEYBOARD_DEBUG
        qWarning("Processing: uni=%04x, qt=%08x, qtmod=%08x", unicode, qtcode & ~modmask, (qtcode & modmask));
#endif
        //If NumLockOff and keypad key pressed remap event sent
        if (!m_numLock &&
             (qtcode & Qt::KeypadModifier)) {
            unicode = 0xffff;
            const int oldMask = (qtcode & modmask);
            switch (qtcode & ~modmask) {
            case Qt::Key_7: //7 --> Home
                qtcode = Qt::Key_Home;
                break;
            case Qt::Key_8: //8 --> Up
                qtcode = Qt::Key_Up;
                break;
            case Qt::Key_9: //9 --> PgUp
                qtcode = Qt::Key_PageUp;
                break;
            case Qt::Key_4: //4 --> Left
                qtcode = Qt::Key_Left;
                break;
            case Qt::Key_5: //5 --> Clear
                qtcode = Qt::Key_Clear;
                break;
            case Qt::Key_6: //6 --> right
                qtcode = Qt::Key_Right;
                break;
            case Qt::Key_1: //1 --> End
                qtcode = Qt::Key_End;
                break;
            case Qt::Key_2: //2 --> Down
                qtcode = Qt::Key_Down;
                break;
            case Qt::Key_3: //3 --> PgDn
                qtcode = Qt::Key_PageDown;
                break;
            case Qt::Key_0: //0 --> Ins
                qtcode = Qt::Key_Insert;
                break;
            case Qt::Key_Period: //. --> Del
                qtcode = Qt::Key_Delete;
                break;
            }
            qtcode |= oldMask;
        }

        // send the result to the server
        processKeyEvent(keycode, unicode, qtcode & ~modmask,
                        Qt::KeyboardModifiers(qtcode & modmask), pressed, autorepeat);
    }
}

void QBsdKeyboardHandler::switchLed(int led, bool state)
{
#ifdef QT_BSD_KEYBOARD_DEBUG
    qWarning() << "switchLed" << led << state;
#endif
    int leds = 0;
    if (ioctl(m_fd, KDGETLED, &leds) < 0) {
        qWarning("switchLed: Failed to query led states.");
        return;
    }

    if (state)
        leds |= led;
    else
        leds &= ~led;

    if (ioctl(m_fd, KDSETLED, leds) < 0)
        qWarning("switchLed: Failed to set led states.");
}

void QBsdKeyboardHandler::resetKeymap()
{
#ifdef QT_BSD_KEYBOARD_DEBUG
    qWarning() << "Unload current keymap and restore built-in";
#endif

    m_keymap.clear();

    const size_t mappingSize = sizeof(keymapDefault) / sizeof(keymapDefault[0]);
    m_keymap.resize(mappingSize);
    std::copy_n( &keymapDefault[0], mappingSize, m_keymap.begin() );

    // reset state, so we could switch keymaps at runtime
    m_modifiers = 0;
    m_capsLock = false;
    m_numLock = false;
    m_scrollLock = false;

    //Set locks according to keyboard leds
    int leds = 0;
    if (ioctl(m_fd, KDGETLED, &leds) < 0) {
        qWarning("Failed to query led states. Settings numlock & capslock off");
        switchLed(LED_NUM, false);
        switchLed(LED_CAP, false);
        switchLed(LED_SCR, false);
    } else {
        if ((leds & LED_CAP) > 0)
            m_capsLock = true;
        if ((leds & LED_NUM) > 0)
            m_numLock = true;
        if ((leds & LED_SCR) > 0)
            m_scrollLock = true;
#ifdef QT_BSD_KEYBOARD_DEBUG
        qWarning("numlock=%d , capslock=%d, scrolllock=%d",m_numLock, m_capsLock, m_scrollLock);
#endif
    }
}