1 /****************************************************************************
2 **
3 ** Copyright (C) 2016 The Qt Company Ltd.
4 ** Contact: https://www.qt.io/licensing/
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:GPL-EXCEPT$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and The Qt Company. For licensing terms
14 ** and conditions see https://www.qt.io/terms-conditions. For further
15 ** information use the contact form at https://www.qt.io/contact-us.
16 **
17 ** GNU General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU
19 ** General Public License version 3 as published by the Free Software
20 ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
21 ** included in the packaging of this file. Please review the following
22 ** information to ensure the GNU General Public License requirements will
23 ** be met: https://www.gnu.org/licenses/gpl-3.0.html.
24 **
25 ** $QT_END_LICENSE$
26 **
27 ****************************************************************************/
28 
29 #include <cstdio>
30 
31 #include <QFile>
32 #include <QFileInfo>
33 #include <QDir>
34 #include <QTextCodec>
35 #include <QList>
36 #include <QVector>
37 #include <QByteArray>
38 #include <QStringList>
39 #include <QTextStream>
40 
41 #include <QtInputSupport/private/qevdevkeyboardhandler_p.h>
42 
43 using namespace std;
44 
45 
46 struct modifier_map_t {
47     const char *symbol;
48     quint8      modifier;
49     quint32     qtmodifier;
50 };
51 
52 static const struct modifier_map_t modifier_map[] = {
53     { "plain",   QEvdevKeyboardMap::ModPlain,   Qt::NoModifier },
54     { "shift",   QEvdevKeyboardMap::ModShift,   Qt::ShiftModifier },
55     { "altgr",   QEvdevKeyboardMap::ModAltGr,   Qt::AltModifier },
56     { "control", QEvdevKeyboardMap::ModControl, Qt::ControlModifier },
57     { "alt",     QEvdevKeyboardMap::ModAlt,     Qt::AltModifier },
58     { "meta",    QEvdevKeyboardMap::ModAlt,     Qt::AltModifier },
59     { "shiftl",  QEvdevKeyboardMap::ModShiftL,  Qt::ShiftModifier },
60     { "shiftr",  QEvdevKeyboardMap::ModShiftR,  Qt::ShiftModifier },
61     { "ctrll",   QEvdevKeyboardMap::ModCtrlL,   Qt::ControlModifier },
62     { "ctrlr",   QEvdevKeyboardMap::ModCtrlR,   Qt::ControlModifier },
63 };
64 
65 static const int modifier_map_size = sizeof(modifier_map)/sizeof(modifier_map_t);
66 
67 
68 struct symbol_map_t {
69     const char *symbol;
70     quint32     qtcode;
71 };
72 
73 static const struct symbol_map_t symbol_map[] = {
74     { "space", Qt::Key_Space },
75     { "exclam", Qt::Key_Exclam },
76     { "quotedbl", Qt::Key_QuoteDbl },
77     { "numbersign", Qt::Key_NumberSign },
78     { "dollar", Qt::Key_Dollar },
79     { "percent", Qt::Key_Percent },
80     { "ampersand", Qt::Key_Ampersand },
81     { "apostrophe", Qt::Key_Apostrophe },
82     { "parenleft", Qt::Key_ParenLeft },
83     { "parenright", Qt::Key_ParenRight },
84     { "asterisk", Qt::Key_Asterisk },
85     { "plus", Qt::Key_Plus },
86     { "comma", Qt::Key_Comma },
87     { "minus", Qt::Key_Minus },
88     { "period", Qt::Key_Period },
89     { "slash", Qt::Key_Slash },
90     { "zero", Qt::Key_0 },
91     { "one", Qt::Key_1 },
92     { "two", Qt::Key_2 },
93     { "three", Qt::Key_3 },
94     { "four", Qt::Key_4 },
95     { "five", Qt::Key_5 },
96     { "six", Qt::Key_6 },
97     { "seven", Qt::Key_7 },
98     { "eight", Qt::Key_8 },
99     { "nine", Qt::Key_9 },
100     { "colon", Qt::Key_Colon },
101     { "semicolon", Qt::Key_Semicolon },
102     { "less", Qt::Key_Less },
103     { "equal", Qt::Key_Equal },
104     { "greater", Qt::Key_Greater },
105     { "question", Qt::Key_Question },
106     { "at", Qt::Key_At },
107     { "bracketleft", Qt::Key_BracketLeft },
108     { "backslash", Qt::Key_Backslash },
109     { "bracketright", Qt::Key_BracketRight },
110     { "asciicircum", Qt::Key_AsciiCircum },
111     { "underscore", Qt::Key_Underscore },
112     { "grave", Qt::Key_QuoteLeft },
113     { "braceleft", Qt::Key_BraceLeft },
114     { "bar", Qt::Key_Bar },
115     { "braceright", Qt::Key_BraceRight },
116     { "asciitilde", Qt::Key_AsciiTilde },
117     { "nobreakspace", Qt::Key_nobreakspace },
118     { "exclamdown", Qt::Key_exclamdown },
119     { "cent", Qt::Key_cent },
120     { "sterling", Qt::Key_sterling },
121     { "currency", Qt::Key_currency },
122     { "yen", Qt::Key_yen },
123     { "brokenbar", Qt::Key_brokenbar },
124     { "section", Qt::Key_section },
125     { "diaeresis", Qt::Key_diaeresis },
126     { "copyright", Qt::Key_copyright },
127     { "ordfeminine", Qt::Key_ordfeminine },
128     { "guillemotleft", Qt::Key_guillemotleft },
129     { "notsign", Qt::Key_notsign },
130     { "hyphen", Qt::Key_hyphen },
131     { "registered", Qt::Key_registered },
132     { "macron", Qt::Key_macron },
133     { "degree", Qt::Key_degree },
134     { "plusminus", Qt::Key_plusminus },
135     { "twosuperior", Qt::Key_twosuperior },
136     { "threesuperior", Qt::Key_threesuperior },
137     { "acute", Qt::Key_acute },
138     { "mu", Qt::Key_mu },
139     { "paragraph", Qt::Key_paragraph },
140     { "periodcentered", Qt::Key_periodcentered },
141     { "cedilla", Qt::Key_cedilla },
142     { "onesuperior", Qt::Key_onesuperior },
143     { "masculine", Qt::Key_masculine },
144     { "guillemotright", Qt::Key_guillemotright },
145     { "onequarter", Qt::Key_onequarter },
146     { "onehalf", Qt::Key_onehalf },
147     { "threequarters", Qt::Key_threequarters },
148     { "questiondown", Qt::Key_questiondown },
149     { "Agrave", Qt::Key_Agrave },
150     { "Aacute", Qt::Key_Aacute },
151     { "Acircumflex", Qt::Key_Acircumflex },
152     { "Atilde", Qt::Key_Atilde },
153     { "Adiaeresis", Qt::Key_Adiaeresis },
154     { "Aring", Qt::Key_Aring },
155     { "AE", Qt::Key_AE },
156     { "Ccedilla", Qt::Key_Ccedilla },
157     { "Egrave", Qt::Key_Egrave },
158     { "Eacute", Qt::Key_Eacute },
159     { "Ecircumflex", Qt::Key_Ecircumflex },
160     { "Ediaeresis", Qt::Key_Ediaeresis },
161     { "Igrave", Qt::Key_Igrave },
162     { "Iacute", Qt::Key_Iacute },
163     { "Icircumflex", Qt::Key_Icircumflex },
164     { "Idiaeresis", Qt::Key_Idiaeresis },
165     { "ETH", Qt::Key_ETH },
166     { "Ntilde", Qt::Key_Ntilde },
167     { "Ograve", Qt::Key_Ograve },
168     { "Oacute", Qt::Key_Oacute },
169     { "Ocircumflex", Qt::Key_Ocircumflex },
170     { "Otilde", Qt::Key_Otilde },
171     { "Odiaeresis", Qt::Key_Odiaeresis },
172     { "multiply", Qt::Key_multiply },
173     { "Ooblique", Qt::Key_Ooblique },
174     { "Ugrave", Qt::Key_Ugrave },
175     { "Uacute", Qt::Key_Uacute },
176     { "Ucircumflex", Qt::Key_Ucircumflex },
177     { "Udiaeresis", Qt::Key_Udiaeresis },
178     { "Yacute", Qt::Key_Yacute },
179     { "THORN", Qt::Key_THORN },
180     { "ssharp", Qt::Key_ssharp },
181 
182     { "agrave", 0xe0 /*Qt::Key_agrave*/ },
183     { "aacute", 0xe1 /*Qt::Key_aacute*/ },
184     { "acircumflex", 0xe2 /*Qt::Key_acircumflex*/ },
185     { "atilde", 0xe3 /*Qt::Key_atilde*/ },
186     { "adiaeresis", 0xe4 /*Qt::Key_adiaeresis*/ },
187     { "aring", 0xe5 /*Qt::Key_aring*/ },
188     { "ae", 0xe6 /*Qt::Key_ae*/ },
189     { "ccedilla", 0xe7 /*Qt::Key_ccedilla*/ },
190     { "egrave", 0xe8 /*Qt::Key_egrave*/ },
191     { "eacute", 0xe9 /*Qt::Key_eacute*/ },
192     { "ecircumflex", 0xea /*Qt::Key_ecircumflex*/ },
193     { "ediaeresis", 0xeb /*Qt::Key_ediaeresis*/ },
194     { "igrave", 0xec /*Qt::Key_igrave*/ },
195     { "iacute", 0xed /*Qt::Key_iacute*/ },
196     { "icircumflex", 0xee /*Qt::Key_icircumflex*/ },
197     { "idiaeresis", 0xef /*Qt::Key_idiaeresis*/ },
198     { "eth", 0xf0 /*Qt::Key_eth*/ },
199     { "ntilde", 0xf1 /*Qt::Key_ntilde*/ },
200     { "ograve", 0xf2 /*Qt::Key_ograve*/ },
201     { "oacute", 0xf3 /*Qt::Key_oacute*/ },
202     { "ocircumflex", 0xf4 /*Qt::Key_ocircumflex*/ },
203     { "otilde", 0xf5 /*Qt::Key_otilde*/ },
204     { "odiaeresis", 0xf6 /*Qt::Key_odiaeresis*/ },
205     { "division", Qt::Key_division },
206     { "oslash", 0xf8 /*Qt::Key_oslash*/ },
207     { "ugrave", 0xf9 /*Qt::Key_ugrave*/ },
208     { "uacute", 0xfa /*Qt::Key_uacute*/ },
209     { "ucircumflex", 0xfb /*Qt::Key_ucircumflex*/ },
210     { "udiaeresis", 0xfc /*Qt::Key_udiaeresis*/ },
211     { "yacute", 0xfd /*Qt::Key_yacute*/ },
212     { "thorn", 0xfe /*Qt::Key_thorn*/ },
213     { "ydiaeresis", Qt::Key_ydiaeresis },
214 
215     { "F1",  Qt::Key_F1 },
216     { "F2",  Qt::Key_F2 },
217     { "F3",  Qt::Key_F3 },
218     { "F4",  Qt::Key_F4 },
219     { "F5",  Qt::Key_F5 },
220     { "F6",  Qt::Key_F6 },
221     { "F7",  Qt::Key_F7 },
222     { "F8",  Qt::Key_F8 },
223     { "F9",  Qt::Key_F9 },
224     { "F10", Qt::Key_F10 },
225     { "F11", Qt::Key_F11 },
226     { "F12", Qt::Key_F12 },
227     { "F13", Qt::Key_F13 },
228     { "F14", Qt::Key_F14 },
229     { "F15", Qt::Key_F15 },
230     { "F16", Qt::Key_F16 },
231     { "F17", Qt::Key_F17 },
232     { "F18", Qt::Key_F18 },
233     { "F19", Qt::Key_F19 },
234     { "F20", Qt::Key_F20 },
235     { "F21", Qt::Key_F21 },
236     { "F22", Qt::Key_F22 },
237     { "F23", Qt::Key_F23 },
238     { "F24", Qt::Key_F24 },
239     { "F25", Qt::Key_F25 },
240     { "F26", Qt::Key_F26 },
241     { "F27", Qt::Key_F27 },
242     { "F28", Qt::Key_F28 },
243     { "F29", Qt::Key_F29 },
244     { "F30", Qt::Key_F30 },
245     { "F31", Qt::Key_F31 },
246     { "F32", Qt::Key_F32 },
247     { "F33", Qt::Key_F33 },
248     { "F34", Qt::Key_F34 },
249     { "F35", Qt::Key_F35 },
250 
251     { "BackSpace",     Qt::Key_Backspace },
252     { "Tab",           Qt::Key_Tab },
253     { "Escape",        Qt::Key_Escape },
254     { "Delete",        Qt::Key_Backspace }, // what's the difference between "Delete" and "BackSpace"??
255     { "Return",        Qt::Key_Return },
256     { "Break",         Qt::Key_unknown }, //TODO: why doesn't Qt support the 'Break' key?
257     { "Caps_Lock",     Qt::Key_CapsLock },
258     { "Num_Lock",      Qt::Key_NumLock },
259     { "Scroll_Lock",   Qt::Key_ScrollLock },
260     { "Caps_On",       Qt::Key_CapsLock },
261     { "Compose",       Qt::Key_Multi_key },
262     { "Bare_Num_Lock", Qt::Key_NumLock },
263     { "Find",          Qt::Key_Home },
264     { "Insert",        Qt::Key_Insert },
265     { "Remove",        Qt::Key_Delete },
266     { "Select",        Qt::Key_End },
267     { "Prior",         Qt::Key_PageUp },
268     { "Next",          Qt::Key_PageDown },
269     { "Help",          Qt::Key_Help },
270     { "Pause",         Qt::Key_Pause },
271     { "VolumeDown",    Qt::Key_VolumeDown },
272     { "VolumeUp",      Qt::Key_VolumeUp },
273     { "MediaTogglePlayPause", Qt::Key_MediaTogglePlayPause },
274     { "MediaPlay",     Qt::Key_MediaPlay },
275     { "MediaPause",    Qt::Key_MediaPause },
276     { "MediaStop",     Qt::Key_MediaStop },
277     { "MediaNext",     Qt::Key_MediaNext },
278     { "MediaPrevious", Qt::Key_MediaPrevious },
279     { "AudioForward",  Qt::Key_AudioForward },
280     { "AudioRewind",   Qt::Key_AudioRewind },
281     { "Camera",        Qt::Key_Camera },
282     { "CameraFocus",   Qt::Key_CameraFocus },
283 
284     { "Call",             Qt::Key_Call },
285     { "Hangup",           Qt::Key_Hangup },
286     { "ToggleCallHangup", Qt::Key_ToggleCallHangup },
287     { "VoiceDial"       , Qt::Key_VoiceDial },
288     { "LastNumberRedial", Qt::Key_LastNumberRedial },
289 
290     { "KP_0",        Qt::Key_0 | Qt::KeypadModifier },
291     { "KP_1",        Qt::Key_1 | Qt::KeypadModifier },
292     { "KP_2",        Qt::Key_2 | Qt::KeypadModifier },
293     { "KP_3",        Qt::Key_3 | Qt::KeypadModifier },
294     { "KP_4",        Qt::Key_4 | Qt::KeypadModifier },
295     { "KP_5",        Qt::Key_5 | Qt::KeypadModifier },
296     { "KP_6",        Qt::Key_6 | Qt::KeypadModifier },
297     { "KP_7",        Qt::Key_7 | Qt::KeypadModifier },
298     { "KP_8",        Qt::Key_8 | Qt::KeypadModifier },
299     { "KP_9",        Qt::Key_9 | Qt::KeypadModifier },
300     { "KP_Add",      Qt::Key_Plus | Qt::KeypadModifier },
301     { "KP_Subtract", Qt::Key_Minus | Qt::KeypadModifier },
302     { "KP_Multiply", Qt::Key_Asterisk | Qt::KeypadModifier },
303     { "KP_Divide",   Qt::Key_Slash | Qt::KeypadModifier },
304     { "KP_Enter",    Qt::Key_Enter | Qt::KeypadModifier },
305     { "KP_Comma",    Qt::Key_Comma | Qt::KeypadModifier },
306     { "KP_Period",   Qt::Key_Period | Qt::KeypadModifier },
307     { "KP_MinPlus",  Qt::Key_plusminus | Qt::KeypadModifier },
308 
309     { "dead_grave",      Qt::Key_Dead_Grave },
310     { "dead_acute",      Qt::Key_Dead_Acute },
311     { "dead_circumflex", Qt::Key_Dead_Circumflex },
312     { "dead_tilde",      Qt::Key_Dead_Tilde },
313     { "dead_diaeresis",  Qt::Key_Dead_Diaeresis },
314     { "dead_cedilla",    Qt::Key_Dead_Cedilla },
315 
316     { "Down",    Qt::Key_Down },
317     { "Left",    Qt::Key_Left },
318     { "Right",   Qt::Key_Right },
319     { "Up",      Qt::Key_Up },
320     { "Shift",   Qt::Key_Shift },
321     { "AltGr",   Qt::Key_AltGr },
322     { "Control", Qt::Key_Control },
323     { "Alt",     Qt::Key_Alt },
324     { "ShiftL",  Qt::Key_Shift },
325     { "ShiftR",  Qt::Key_Shift },
326     { "CtrlL",   Qt::Key_Control },
327     { "CtrlR",   Qt::Key_Control },
328 };
329 
330 static const int symbol_map_size = sizeof(symbol_map)/sizeof(symbol_map_t);
331 
332 
333 struct symbol_dead_unicode_t {
334     quint32 dead;
335     quint16 unicode;
336 };
337 
338 static const symbol_dead_unicode_t symbol_dead_unicode[] = {
339     { Qt::Key_Dead_Grave,      '`' },
340     { Qt::Key_Dead_Acute,      '\'' },
341     { Qt::Key_Dead_Circumflex, '^' },
342     { Qt::Key_Dead_Tilde,      '~' },
343     { Qt::Key_Dead_Diaeresis,  '"' },
344     { Qt::Key_Dead_Cedilla,    ',' },
345 };
346 
347 static const int symbol_dead_unicode_size = sizeof(symbol_dead_unicode)/sizeof(symbol_dead_unicode_t);
348 
349 
350 struct symbol_synonyms_t {
351     const char *from;
352     const char *to;
353 };
354 
355 static const symbol_synonyms_t symbol_synonyms[] = {
356     { "Control_h", "BackSpace" },
357     { "Control_i", "Tab" },
358     { "Control_j", "Linefeed" },
359     { "Home", "Find" },
360     { "End", "Select" },
361     { "PageUp", "Prior" },
362     { "PageDown", "Next" },
363     { "multiplication", "multiply" },
364     { "pound", "sterling" },
365     { "pilcrow", "paragraph" },
366     { "Oslash", "Ooblique" },
367     { "Shift_L", "ShiftL" },
368     { "Shift_R", "ShiftR" },
369     { "Control_L", "CtrlL" },
370     { "Control_R", "CtrlR" },
371     { "AltL", "Alt" },
372     { "AltR", "AltGr" },
373     { "Alt_L", "Alt" },
374     { "Alt_R", "AltGr" },
375     { "AltGr_L", "Alt" },
376     { "AltGr_R", "AltGr" },
377     { "tilde", "asciitilde" },
378     { "circumflex", "asciicircum" },
379     { "dead_ogonek", "dead_cedilla" },
380     { "dead_caron", "dead_circumflex" },
381     { "dead_breve", "dead_tilde" },
382     { "dead_doubleacute", "dead_tilde" },
383     { "no-break_space", "nobreakspace" },
384     { "paragraph_sign", "section" },
385     { "soft_hyphen", "hyphen" },
386     { "rightanglequote", "guillemotright" },
387 };
388 
389 static const int symbol_synonyms_size = sizeof(symbol_synonyms)/sizeof(symbol_synonyms_t);
390 
391 // makes the generated array in --header mode a bit more human readable
392 QT_BEGIN_NAMESPACE
393 namespace QEvdevKeyboardMap {
operator <(const Mapping & m1,const Mapping & m2)394     static bool operator<(const Mapping &m1, const Mapping &m2)
395     {
396         return m1.keycode != m2.keycode ? m1.keycode < m2.keycode : m1.modifiers < m2.modifiers;
397     }
398 }
399 QT_END_NAMESPACE
400 
401 class KeymapParser {
402 public:
403     KeymapParser();
404     ~KeymapParser();
405 
406     bool parseKmap(QFile *kmap);
407     bool generateQmap(QFile *qmap);
408     bool generateHeader(QFile *qmap);
409 
parseWarningCount() const410     int parseWarningCount() const   { return m_warning_count; }
411 
412 private:
413     bool parseSymbol(const QByteArray &str, const QTextCodec *codec, quint16 &unicode, quint32 &qtcode, quint8 &flags, quint16 &special);
414     bool parseCompose(const QByteArray &str, const QTextCodec *codec, quint16 &unicode);
415     bool parseModifier(const QByteArray &str, quint8 &modifier);
416 
417     void updateMapping(quint16 keycode = 0, quint8 modifiers = 0, quint16 unicode = 0xffff, quint32 qtcode = Qt::Key_unknown, quint8 flags = 0, quint16 = 0);
418 
419     static quint32 toQtModifiers(quint8 modifiers);
420     static QList<QByteArray> tokenize(const QByteArray &line);
421 
422 
423 private:
424     QList<QEvdevKeyboardMap::Mapping> m_keymap;
425     QList<QEvdevKeyboardMap::Composing> m_keycompose;
426 
427     int m_warning_count;
428 };
429 
430 
431 
main(int argc,char ** argv)432 int main(int argc, char **argv)
433 {
434     int header = 0;
435     if (argc >= 2 && !qstrcmp(argv[1], "--header"))
436         header = 1;
437 
438     if (argc < (3 + header)) {
439         fprintf(stderr, "Usage: kmap2qmap [--header] <kmap> [<additional kmaps> ...] <qmap>\n");
440         fprintf(stderr, "  --header   can be used to generate Qt's default compiled in qmap.\n");
441         return 1;
442     }
443 
444     QVector<QFile *> kmaps(argc - header - 2);
445     for (int i = 0; i < kmaps.size(); ++i) {
446         kmaps [i] = new QFile(QString::fromLocal8Bit(argv[i + 1 + header]));
447 
448         if (!kmaps[i]->open(QIODevice::ReadOnly)) {
449             fprintf(stderr, "Could not read from '%s'.\n", argv[i + 1 + header]);
450             return 2;
451         }
452     }
453     QFile *qmap = new QFile(QString::fromLocal8Bit(argv[argc - 1]));
454 
455     if (!qmap->open(QIODevice::WriteOnly)) {
456         fprintf(stderr, "Could not write to '%s'.\n", argv[argc - 1]);
457         return 3;
458     }
459 
460     KeymapParser p;
461 
462     for (int i = 0; i < kmaps.size(); ++i) {
463         if (!p.parseKmap(kmaps[i])) {
464             fprintf(stderr, "Parsing kmap '%s' failed.\n", qPrintable(kmaps[i]->fileName()));
465             return 4;
466         }
467     }
468 
469     if (p.parseWarningCount()) {
470         fprintf(stderr, "\nParsing the specified keymap(s) produced %d warning(s).\n" \
471                         "Your generated qmap might not be complete.\n", \
472                         p.parseWarningCount());
473     }
474     if (!(header ? p.generateHeader(qmap) : p.generateQmap(qmap))) {
475         fprintf(stderr, "Generating the qmap failed.\n");
476         return 5;
477     }
478 
479     qDeleteAll(kmaps);
480     delete qmap;
481 
482     return 0;
483 }
484 
485 
KeymapParser()486 KeymapParser::KeymapParser()
487      : m_warning_count(0)
488 { }
489 
490 
~KeymapParser()491 KeymapParser::~KeymapParser()
492 { }
493 
494 
generateHeader(QFile * f)495 bool KeymapParser::generateHeader(QFile *f)
496 {
497     QTextStream ts(f);
498 
499     ts << "#ifndef QEVDEVKEYBOARDHANDLER_DEFAULTMAP_H" << Qt::endl;
500     ts << "#define QEVDEVKEYBOARDHANDLER_DEFAULTMAP_H" << Qt::endl << Qt::endl;
501 
502     ts << "const QEvdevKeyboardMap::Mapping QEvdevKeyboardHandler::s_keymap_default[] = {" << Qt::endl;
503 
504     for (int i = 0; i < m_keymap.size(); ++i) {
505         const QEvdevKeyboardMap::Mapping &m = m_keymap.at(i);
506         ts << QString::asprintf("    { %3d, 0x%04x, 0x%08x, 0x%02x, 0x%02x, 0x%04x },\n", m.keycode, m.unicode, m.qtcode, m.modifiers, m.flags, m.special);
507     }
508 
509     ts << "};" << Qt::endl << Qt::endl;
510 
511     ts << "const QEvdevKeyboardMap::Composing QEvdevKeyboardHandler::s_keycompose_default[] = {" << Qt::endl;
512 
513     for (int i = 0; i < m_keycompose.size(); ++i) {
514         const QEvdevKeyboardMap::Composing &c = m_keycompose.at(i);
515         ts << QString::asprintf("    { 0x%04x, 0x%04x, 0x%04x },\n", c.first, c.second, c.result);
516     }
517     ts << "};" << Qt::endl << Qt::endl;
518 
519     ts << "#endif" << Qt::endl;
520 
521     return (ts.status() == QTextStream::Ok);
522 }
523 
524 
generateQmap(QFile * f)525 bool KeymapParser::generateQmap(QFile *f)
526 {
527     QDataStream ds(f);
528 
529     ds << quint32(QEvdevKeyboardMap::FileMagic) << quint32(1 /* version */) << quint32(m_keymap.size()) << quint32(m_keycompose.size());
530 
531     if (ds.status() != QDataStream::Ok)
532         return false;
533 
534     for (int i = 0; i < m_keymap.size(); ++i)
535         ds << m_keymap[i];
536 
537     for (int i = 0; i < m_keycompose.size(); ++i)
538         ds << m_keycompose[i];
539 
540     return (ds.status() == QDataStream::Ok);
541 }
542 
543 
tokenize(const QByteArray & line)544 QList<QByteArray> KeymapParser::tokenize(const QByteArray &line)
545 {
546     bool quoted = false, separator = true;
547     QList<QByteArray> result;
548     QByteArray token;
549 
550     for (int i = 0; i < line.length(); ++i) {
551         QChar c = line.at(i);
552 
553         if (!quoted && c == '#' && separator)
554             break;
555         else if (!quoted && c == '"' && separator)
556             quoted = true;
557         else if (quoted && c == '"')
558             quoted = false;
559         else if (!quoted && c.isSpace()) {
560             separator = true;
561             if (!token.isEmpty()) {
562                 result.append(token);
563                 token.truncate(0);
564             }
565         }
566         else {
567             separator = false;
568             token.append(c);
569         }
570     }
571     if (!token.isEmpty())
572         result.append(token);
573     return result;
574 }
575 
576 
577 #define parseWarning(s)  do { qWarning("Warning: keymap file '%s', line %d: %s", qPrintable(f->fileName()), lineno, s); ++m_warning_count; } while (false)
578 
parseKmap(QFile * f)579 bool KeymapParser::parseKmap(QFile *f)
580 {
581     QByteArray line;
582     int lineno = 0;
583     QList<int> keymaps;
584     QTextCodec *codec = QTextCodec::codecForName("iso8859-1");
585 
586     for (int i = 0; i <= 256; ++i)
587         keymaps << i;
588 
589     while (!f->atEnd() && !f->error()) {
590         line = f->readLine();
591         lineno++;
592 
593         QList<QByteArray> tokens = tokenize(line);
594 
595         if (tokens.isEmpty())
596             continue;
597 
598         if (tokens[0] == "keymaps") {
599             keymaps.clear();
600 
601             if (tokens.count() > 1) {
602                 const QByteArrayList tokenList = tokens[1].split(',');
603                 for (const QByteArray &section : tokenList) {
604                     int dashpos = section.indexOf('-');
605 
606                     //qWarning("Section %s", section.constData());
607                     int end = section.mid(dashpos + 1).toInt();
608                     int start = end;
609                     if (dashpos > 0)
610                         start = section.left(dashpos).toInt();
611 
612                     if (start <= end && start >=0 && end <= 256) {
613                         for (int i = start; i <= end; ++i) {
614                             //qWarning("appending keymap %d", i);
615                             keymaps.append(i);
616                         }
617                     }
618                     else
619                         parseWarning("keymaps has an invalid range");
620                 }
621                 std::sort(keymaps.begin(), keymaps.end());
622             }
623             else
624                 parseWarning("keymaps with more than one argument");
625         }
626         else if (tokens[0] == "alt_is_meta") {
627             // simply ignore it for now
628         }
629         else if (tokens[0] == "include") {
630             if (tokens.count() == 2) {
631                 QString incname = QString::fromLocal8Bit(tokens[1]);
632                 bool found = false;
633                 QList<QDir> searchpath;
634                 QFileInfo fi(*f);
635 
636                 if (!incname.endsWith(QLatin1String(".kmap")) && !incname.endsWith(QLatin1String(".inc")))
637                     incname.append(QLatin1String(".inc"));
638 
639                 QDir d = fi.dir();
640                 searchpath << d;
641                 if (d.cdUp() && d.cd(QLatin1String("include")))
642                     searchpath << d;
643                 searchpath << QDir::current();
644 
645                 for (const QDir &path : qAsConst(searchpath)) {
646                     QFile f2(path.filePath(incname));
647                     //qWarning("  -- trying to include %s", qPrintable(f2.fileName()));
648                     if (f2.open(QIODevice::ReadOnly)) {
649                         if (!parseKmap(&f2))
650                             parseWarning("could not parse keymap include");
651                         found = true;
652                     }
653                 }
654 
655                 if (!found)
656                     parseWarning("could not locate keymap include");
657             } else
658                 parseWarning("include doesn't have exactly one argument");
659         }
660         else if (tokens[0] == "charset") {
661             if (tokens.count() == 2) {
662                 codec = QTextCodec::codecForName(tokens[1]);
663                 if (!codec) {
664                     parseWarning("could not parse codec definition");
665                     codec = QTextCodec::codecForName("iso8859-1");
666                 }
667             } else
668                 parseWarning("codec doesn't habe exactly one argument");
669         }
670         else if (tokens[0] == "strings") {
671             // simply ignore those - they have no meaning for us
672         }
673         else if (tokens[0] == "compose") {
674             if (tokens.count() == 5 && tokens[3] == "to") {
675                 QEvdevKeyboardMap::Composing c = { 0xffff, 0xffff, 0xffff };
676 
677                 if (!parseCompose(tokens[1], codec, c.first))
678                     parseWarning("could not parse first compose symbol");
679                 if (!parseCompose(tokens[2], codec, c.second))
680                     parseWarning("could not parse second compose symbol");
681                 if (!parseCompose(tokens[4], codec, c.result))
682                     parseWarning("could not parse resulting compose symbol");
683 
684                 if (c.first != 0xffff && c.second != 0xffff && c.result != 0xffff) {
685                     m_keycompose << c;
686                 }
687             } else
688                 parseWarning("non-standard compose line");
689         }
690         else {
691             int kcpos = tokens.indexOf("keycode");
692 
693             if (kcpos >= 0 && kcpos < (tokens.count()-3) && tokens[kcpos+2] == "=") {
694                 quint16 keycode = tokens[kcpos+1].toInt();
695 
696                 if (keycode <= 0 || keycode > 0x2ff /* KEY_MAX */) {
697                     parseWarning("keycode out of range [0..0x2ff]");
698                     break;
699                 }
700 
701                 bool line_modifiers = (kcpos > 0);
702 
703                 quint8 modifiers = 0; //, modifiers_mask = 0xff;
704                 for (int i = 0; i < kcpos; ++i) {
705                     quint8 mod;
706                     if (!parseModifier(tokens[i], mod)) {
707                         parseWarning("unknown modifier prefix for keycode");
708                         continue;
709                     }
710                     modifiers |= mod;
711                 }
712 
713                 int kccount = tokens.count() - kcpos - 3; // 3 : 'keycode' 'X' '='
714 
715                 if (line_modifiers && kccount > 1) {
716                     parseWarning("line has modifiers, but more than one keycode");
717                     break;
718                 }
719 
720                 // only process one symbol when a prefix modifer was specified
721                 for (int i = 0; i < (line_modifiers ? 1 : kccount); ++i) {
722                     if (!line_modifiers)
723                         modifiers = keymaps[i];
724 
725                     quint32 qtcode;
726                     quint16 unicode;
727                     quint16 special;
728                     quint8 flags;
729                     if (!parseSymbol(tokens[i + kcpos + 3], codec, unicode, qtcode, flags, special)) {
730                         parseWarning((QByteArray("symbol could not be parsed: ") + tokens[i + kcpos + 3]).constData());
731                         break;
732                     }
733 
734                     if (qtcode == Qt::Key_unknown && unicode == 0xffff) // VoidSymbol
735                         continue;
736 
737                     if (!line_modifiers && kccount == 1) {
738                         if ((unicode >= 'A' && unicode <= 'Z') || (unicode >= 'a' && unicode <= 'z')) {
739                             quint16 other_unicode = (unicode >= 'A' && unicode <= 'Z') ? unicode - 'A' + 'a' : unicode - 'a' + 'A';
740                             quint16 lower_unicode = (unicode >= 'A' && unicode <= 'Z') ? unicode - 'A' + 'a' : unicode;
741 
742                             // a single a-z|A-Z value results in a very flags mapping: see below
743 
744                             updateMapping(keycode, QEvdevKeyboardMap::ModPlain, unicode, qtcode, flags, 0);
745 
746                             updateMapping(keycode, QEvdevKeyboardMap::ModShift, other_unicode, qtcode, flags, 0);
747 
748                             updateMapping(keycode, QEvdevKeyboardMap::ModAltGr,                         unicode, qtcode, flags, 0);
749                             updateMapping(keycode, QEvdevKeyboardMap::ModAltGr | QEvdevKeyboardMap::ModShift, other_unicode, qtcode, flags, 0);
750 
751                             updateMapping(keycode, QEvdevKeyboardMap::ModControl,                                                 lower_unicode, qtcode | Qt::ControlModifier, flags, 0);
752                             updateMapping(keycode, QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModShift,                         lower_unicode, qtcode | Qt::ControlModifier, flags, 0);
753                             updateMapping(keycode, QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModAltGr,                         lower_unicode, qtcode | Qt::ControlModifier, flags, 0);
754                             updateMapping(keycode, QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModAltGr | QEvdevKeyboardMap::ModShift, lower_unicode, qtcode | Qt::ControlModifier, flags, 0);
755 
756                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt,                                                 unicode, qtcode | Qt::AltModifier, flags, 0);
757                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModShift,                         unicode, qtcode | Qt::AltModifier, flags, 0);
758                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModAltGr,                         unicode, qtcode | Qt::AltModifier, flags, 0);
759                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModAltGr | QEvdevKeyboardMap::ModShift, unicode, qtcode | Qt::AltModifier, flags, 0);
760 
761                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModControl,                                                 lower_unicode, qtcode | Qt::ControlModifier | Qt::AltModifier, flags, 0);
762                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModShift,                         lower_unicode, qtcode | Qt::ControlModifier | Qt::AltModifier, flags, 0);
763                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModAltGr,                         lower_unicode, qtcode | Qt::ControlModifier | Qt::AltModifier, flags, 0);
764                             updateMapping(keycode, QEvdevKeyboardMap::ModAlt | QEvdevKeyboardMap::ModControl | QEvdevKeyboardMap::ModAltGr | QEvdevKeyboardMap::ModShift, lower_unicode, qtcode | Qt::ControlModifier | Qt::AltModifier, flags, 0);
765                         }
766                         else {
767                             // a single value results in that mapping regardless of the modifier
768                             //for (int mod = 0; mod <= 255; ++mod)
769                             //    updateMapping(keycode, quint8(mod), unicode, qtcode | toQtModifiers(mod), flags, special);
770 
771                             // we can save a lot of space in the qmap, since we do that anyway in the kbd handler:
772                             updateMapping(keycode, QEvdevKeyboardMap::ModPlain, unicode, qtcode, flags, special);
773                         }
774                     }
775                     else {
776                         // "normal" mapping
777                         updateMapping(keycode, modifiers, unicode, qtcode, flags, special);
778                     }
779                 }
780             }
781         }
782     }
783     std::sort(m_keymap.begin(), m_keymap.end());
784     return !m_keymap.isEmpty();
785 }
786 
787 
788 
updateMapping(quint16 keycode,quint8 modifiers,quint16 unicode,quint32 qtcode,quint8 flags,quint16 special)789 void KeymapParser::updateMapping(quint16 keycode, quint8 modifiers, quint16 unicode, quint32 qtcode, quint8 flags, quint16 special)
790 {
791     for (int i = 0; i < m_keymap.size(); ++i) {
792         QEvdevKeyboardMap::Mapping &m = m_keymap[i];
793 
794         if (m.keycode == keycode && m.modifiers == modifiers) {
795             m.unicode = unicode;
796             m.qtcode  = qtcode;
797             m.flags   = flags;
798             m.special = special;
799             return;
800         }
801     }
802     QEvdevKeyboardMap::Mapping m = { keycode, unicode, qtcode, modifiers, flags, special };
803     m_keymap << m;
804 }
805 
806 
toQtModifiers(quint8 modifiers)807 quint32 KeymapParser::toQtModifiers(quint8 modifiers)
808 {
809     quint32 qtmodifiers = Qt::NoModifier;
810 
811     for (int i = 0; i < modifier_map_size; ++i) {
812         if (modifiers & modifier_map[i].modifier)
813             qtmodifiers |= modifier_map[i].qtmodifier;
814     }
815     return qtmodifiers;
816 }
817 
818 
parseModifier(const QByteArray & str,quint8 & modifier)819 bool KeymapParser::parseModifier(const QByteArray &str, quint8 &modifier)
820 {
821     QByteArray lstr = str.toLower();
822 
823     for (int i = 0; i < modifier_map_size; ++i) {
824         if (lstr == modifier_map[i].symbol) {
825             modifier = modifier_map[i].modifier;
826             return true;
827         }
828     }
829     return false;
830 }
831 
832 
parseCompose(const QByteArray & str,const QTextCodec * codec,quint16 & unicode)833 bool KeymapParser::parseCompose(const QByteArray &str, const QTextCodec *codec, quint16 &unicode)
834 {
835     if (str == "'\\''") {
836         unicode = '\'';
837         return true;
838     } else if (str.length() == 3 && str.startsWith('\'') && str.endsWith('\'')) {
839         QString temp = codec->toUnicode(str.constData() + 1, str.length() - 2);
840         if (temp.length() != 1)
841             return false;
842         unicode = temp[0].unicode();
843         return true;
844     } else {
845         quint32 code = str.toUInt();
846         if (code > 255)
847             return false;
848         char c[2];
849         c[0] = char(code);
850         c[1] = 0;
851         QString temp = codec->toUnicode(c);
852         if (temp.length() != 1)
853             return false;
854         unicode = temp[0].unicode();
855         return true;
856     }
857 }
858 
859 
parseSymbol(const QByteArray & str,const QTextCodec *,quint16 & unicode,quint32 & qtcode,quint8 & flags,quint16 & special)860 bool KeymapParser::parseSymbol(const QByteArray &str, const QTextCodec * /*codec*/, quint16 &unicode, quint32 &qtcode, quint8 &flags, quint16 &special)
861 {
862     flags = (str[0] == '+') ? QEvdevKeyboardMap::IsLetter : 0;
863     QByteArray sym = (flags & QEvdevKeyboardMap::IsLetter) ? str.right(str.length() - 1) : str;
864 
865     special = 0;
866     qtcode = Qt::Key_unknown;
867     unicode = 0xffff;
868 
869     if (sym == "VoidSymbol" || sym == "nul")
870         return true;
871 
872     if (sym[0] >= '0' && sym[0] <= '9') {  // kernel internal action number
873         return false;
874     } else if (sym.length() == 6 && sym[1] == '+' && (sym[0] == 'U' || sym[0] == 'u')) { // unicode
875         bool ok;
876         unicode = sym.mid(2).toUInt(&ok, 16);
877         if (!ok)
878             return false;
879     } else { // symbolic
880         for (int i = 0; i < symbol_synonyms_size; ++i) {
881             if (sym == symbol_synonyms[i].from) {
882                 sym = symbol_synonyms[i].to;
883                 break;
884             }
885         }
886 
887         quint32 qtmod = 0;
888 
889         // parse prepended modifiers
890         forever {
891             int underpos = sym.indexOf('_');
892 
893             if (underpos <= 0)
894                 break;
895             QByteArray modsym = sym.left(underpos);
896             QByteArray nomodsym = sym.mid(underpos + 1);
897             quint8 modifier = 0;
898 
899             if (!parseModifier(modsym, modifier))
900                 break;
901 
902             qtmod |= toQtModifiers(modifier);
903             sym = nomodsym;
904         }
905 
906         if (qtcode == Qt::Key_unknown) {
907             quint8 modcode;
908             // check if symbol is a modifier
909             if (parseModifier(sym, modcode)) {
910                 special = modcode;
911                 flags |= QEvdevKeyboardMap::IsModifier;
912             }
913 
914             // map symbol to Qt key code
915             for  (int i = 0; i < symbol_map_size; ++i) {
916                 if (sym == symbol_map[i].symbol) {
917                     qtcode = symbol_map[i].qtcode;
918                     break;
919                 }
920             }
921 
922             // a-zA-Z is not in the table to save space
923             if (qtcode == Qt::Key_unknown && sym.length() == 1) {
924                 char letter = sym.at(0);
925 
926                 if (letter >= 'a' && letter <= 'z') {
927                     qtcode = Qt::Key_A + letter - 'a';
928                     unicode = letter;
929                 }
930                 else if (letter >= 'A' && letter <= 'Z') {
931                     qtcode = Qt::Key_A + letter - 'A';
932                     unicode = letter;
933                 }
934             }
935             // System keys
936             if (qtcode == Qt::Key_unknown) {
937                 quint16 sys = 0;
938 
939                 if (sym == "Decr_Console") {
940                     sys = QEvdevKeyboardMap::SystemConsolePrevious;
941                 } else if (sym == "Incr_Console") {
942                     sys = QEvdevKeyboardMap::SystemConsoleNext;
943                 } else if (sym.startsWith("Console_")) {
944                     int console = sym.mid(8).toInt() - 1;
945                     if (console >= 0 && console <= (QEvdevKeyboardMap::SystemConsoleLast - QEvdevKeyboardMap::SystemConsoleFirst)) {
946                         sys = QEvdevKeyboardMap::SystemConsoleFirst + console;
947                     }
948                 } else if (sym == "Boot") {
949                     sys = QEvdevKeyboardMap::SystemReboot;
950                 } else if (sym == "QtZap") {
951                     sys = QEvdevKeyboardMap::SystemZap;
952                 }
953 
954                 if (sys) {
955                     flags |= QEvdevKeyboardMap::IsSystem;
956                     special = sys;
957                     qtcode = Qt::Key_Escape; // just a dummy
958                 }
959             }
960 
961             // map Qt key codes in the iso-8859-1 range to unicode
962             if (qtcode != Qt::Key_unknown && unicode == 0xffff) {
963                 quint32 qtcode_no_mod = qtcode & ~(Qt::ShiftModifier | Qt::ControlModifier | Qt::AltModifier | Qt::MetaModifier | Qt::KeypadModifier);
964                  if (qtcode_no_mod <= 0x000000ff) // iso-8859-1
965                      unicode = quint16(qtcode_no_mod);
966             }
967 
968             // flag dead keys
969             if (qtcode >= Qt::Key_Dead_Grave && qtcode <= Qt::Key_Dead_Horn) {
970                 flags = QEvdevKeyboardMap::IsDead;
971 
972                 for (int i = 0; i < symbol_dead_unicode_size; ++i) {
973                     if (symbol_dead_unicode[i].dead == qtcode) {
974                         unicode = symbol_dead_unicode[i].unicode;
975                         break;
976                     }
977                 }
978             }
979         }
980         if ((qtcode == Qt::Key_unknown) && (unicode == 0xffff))
981             return false;
982 
983         qtcode |= qtmod;
984     }
985 
986     // map unicode in the iso-8859-1 range to Qt key codes
987     if (unicode >= 0x0020 && unicode <= 0x00ff && qtcode == Qt::Key_unknown)
988         qtcode = unicode; // iso-8859-1
989 
990     return true;
991 }
992 
993