source: ogBrowser-Git/qtermwidget/lib/KeyboardTranslator.cpp @ 9004d96

jenkinsmain
Last change on this file since 9004d96 was 64efc22, checked in by Vadim Troshchinskiy <vtroshchinskiy@…>, 19 months ago

Update qtermwidget to modern version

  • Property mode set to 100644
File size: 28.7 KB
Line 
1/*
2    This source file is part of Konsole, a terminal emulator.
3
4    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 2 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program; if not, write to the Free Software
18    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19    02110-1301  USA.
20*/
21
22// Own
23#include "KeyboardTranslator.h"
24
25// System
26#include <cctype>
27#include <cstdio>
28
29// Qt
30#include <QBuffer>
31#include <QFile>
32#include <QFileInfo>
33#include <QTextStream>
34#include <QKeySequence>
35#include <QDir>
36#include <QtDebug>
37
38#include "tools.h"
39
40// KDE
41//#include <KDebug>
42//#include <KLocale>
43//#include <KStandardDirs>
44
45using namespace Konsole;
46
47
48const QByteArray KeyboardTranslatorManager::defaultTranslatorText(
49"keyboard \"Fallback Key Translator\"\n"
50"key Tab : \"\\t\""
51);
52
53#ifdef Q_OS_MAC
54// On Mac, Qt::ControlModifier means Cmd, and MetaModifier means Ctrl
55const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::MetaModifier;
56#else
57const Qt::KeyboardModifier KeyboardTranslator::CTRL_MOD = Qt::ControlModifier;
58#endif
59
60KeyboardTranslatorManager::KeyboardTranslatorManager()
61    : _haveLoadedAll(false)
62{
63}
64KeyboardTranslatorManager::~KeyboardTranslatorManager()
65{
66    qDeleteAll(_translators);
67}
68QString KeyboardTranslatorManager::findTranslatorPath(const QString& name)
69{
70    return QString(get_kb_layout_dir() + name + QLatin1String(".keytab"));
71    //return KGlobal::dirs()->findResource("data","konsole/"+name+".keytab");
72}
73
74void KeyboardTranslatorManager::findTranslators()
75{
76    QDir dir(get_kb_layout_dir());
77    QStringList filters;
78    filters << QLatin1String("*.keytab");
79    dir.setNameFilters(filters);
80    QStringList list = dir.entryList(filters);
81//    QStringList list = KGlobal::dirs()->findAllResources("data",
82//                                                         "konsole/*.keytab",
83//                                                        KStandardDirs::NoDuplicates);
84
85    // add the name of each translator to the list and associated
86    // the name with a null pointer to indicate that the translator
87    // has not yet been loaded from disk
88    QStringListIterator listIter(list);
89    while (listIter.hasNext())
90    {
91        QString translatorPath = listIter.next();
92
93        QString name = QFileInfo(translatorPath).baseName();
94
95        if ( !_translators.contains(name) )
96            _translators.insert(name,0);
97    }
98
99    _haveLoadedAll = true;
100}
101
102const KeyboardTranslator* KeyboardTranslatorManager::findTranslator(const QString& name)
103{
104    if ( name.isEmpty() )
105        return defaultTranslator();
106
107    if ( _translators.contains(name) && _translators[name] != 0 )
108        return _translators[name];
109
110    KeyboardTranslator* translator = loadTranslator(name);
111
112    if ( translator != nullptr )
113        _translators[name] = translator;
114    else if ( !name.isEmpty() )
115        qDebug() << "Unable to load translator" << name;
116
117    return translator;
118}
119
120bool KeyboardTranslatorManager::saveTranslator(const KeyboardTranslator* translator)
121{
122qDebug() << "KeyboardTranslatorManager::saveTranslator" << "unimplemented";
123Q_UNUSED(translator);
124#if 0
125    const QString path = KGlobal::dirs()->saveLocation("data","konsole/")+translator->name()
126           +".keytab";
127
128    //kDebug() << "Saving translator to" << path;
129
130    QFile destination(path);
131    if (!destination.open(QIODevice::WriteOnly | QIODevice::Text))
132    {
133        qDebug() << "Unable to save keyboard translation:"
134                   << destination.errorString();
135        return false;
136    }
137
138    {
139        KeyboardTranslatorWriter writer(&destination);
140        writer.writeHeader(translator->description());
141
142        QListIterator<KeyboardTranslator::Entry> iter(translator->entries());
143        while ( iter.hasNext() )
144            writer.writeEntry(iter.next());
145    }
146
147    destination.close();
148#endif
149    return true;
150}
151
152KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& name)
153{
154    const QString& path = findTranslatorPath(name);
155
156    QFile source(path);
157    if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text))
158        return nullptr;
159
160    return loadTranslator(&source,name);
161}
162
163const KeyboardTranslator* KeyboardTranslatorManager::defaultTranslator()
164{
165    // Try to find the default.keytab file if it exists, otherwise
166    // fall back to the hard-coded one
167    const KeyboardTranslator* translator = findTranslator(QLatin1String("default"));
168    if (!translator)
169    {
170        QBuffer textBuffer;
171        textBuffer.setData(defaultTranslatorText);
172        textBuffer.open(QIODevice::ReadOnly);
173        translator = loadTranslator(&textBuffer,QLatin1String("fallback"));
174    }
175    return translator;
176}
177
178KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(QIODevice* source,const QString& name)
179{
180    KeyboardTranslator* translator = new KeyboardTranslator(name);
181    KeyboardTranslatorReader reader(source);
182    translator->setDescription( reader.description() );
183    while ( reader.hasNextEntry() )
184        translator->addEntry(reader.nextEntry());
185
186    source->close();
187
188    if ( !reader.parseError() )
189    {
190        return translator;
191    }
192    else
193    {
194        delete translator;
195        return nullptr;
196    }
197}
198
199KeyboardTranslatorWriter::KeyboardTranslatorWriter(QIODevice* destination)
200: _destination(destination)
201{
202    Q_ASSERT( destination && destination->isWritable() );
203
204    _writer = new QTextStream(_destination);
205}
206KeyboardTranslatorWriter::~KeyboardTranslatorWriter()
207{
208    delete _writer;
209}
210void KeyboardTranslatorWriter::writeHeader( const QString& description )
211{
212    *_writer << "keyboard \"" << description << '\"' << '\n';
213}
214void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entry )
215{
216    QString result;
217    if ( entry.command() != KeyboardTranslator::NoCommand )
218        result = entry.resultToString();
219    else
220        result = QLatin1Char('\"') + entry.resultToString() + QLatin1Char('\"');
221
222    *_writer << QLatin1String("key ") << entry.conditionToString() << QLatin1String(" : ") << result << QLatin1Char('\n');
223}
224
225
226// each line of the keyboard translation file is one of:
227//
228// - keyboard "name"
229// - key KeySequence : "characters"
230// - key KeySequence : CommandName
231//
232// KeySequence begins with the name of the key ( taken from the Qt::Key enum )
233// and is followed by the keyboard modifiers and state flags ( with + or - in front
234// of each modifier or flag to indicate whether it is required ).  All keyboard modifiers
235// and flags are optional, if a particular modifier or state is not specified it is
236// assumed not to be a part of the sequence.  The key sequence may contain whitespace
237//
238// eg:  "key Up+Shift : scrollLineUp"
239//      "key Next-Shift : "\E[6~"
240//
241// (lines containing only whitespace are ignored, parseLine assumes that comments have
242// already been removed)
243//
244
245KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source )
246    : _source(source)
247    , _hasNext(false)
248{
249   // read input until we find the description
250   while ( _description.isEmpty() && !source->atEnd() )
251   {
252        QList<Token> tokens = tokenize( QString::fromUtf8(source->readLine()) );
253        if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword )
254            _description = tokens[1].text;
255   }
256   // read first entry (if any)
257   readNext();
258}
259void KeyboardTranslatorReader::readNext()
260{
261    // find next entry
262    while ( !_source->atEnd() )
263    {
264        const QList<Token>& tokens = tokenize( QString::fromUtf8(_source->readLine()) );
265        if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword )
266        {
267            KeyboardTranslator::States flags = KeyboardTranslator::NoState;
268            KeyboardTranslator::States flagMask = KeyboardTranslator::NoState;
269            Qt::KeyboardModifiers modifiers = Qt::NoModifier;
270            Qt::KeyboardModifiers modifierMask = Qt::NoModifier;
271
272            int keyCode = Qt::Key_unknown;
273
274            decodeSequence(tokens[1].text.toLower(),
275                           keyCode,
276                           modifiers,
277                           modifierMask,
278                           flags,
279                           flagMask);
280
281            KeyboardTranslator::Command command = KeyboardTranslator::NoCommand;
282            QByteArray text;
283
284            // get text or command
285            if ( tokens[2].type == Token::OutputText )
286            {
287                text = tokens[2].text.toLocal8Bit();
288            }
289            else if ( tokens[2].type == Token::Command )
290            {
291                // identify command
292                if (!parseAsCommand(tokens[2].text,command))
293                    qDebug() << "Command" << tokens[2].text << "not understood.";
294            }
295
296            KeyboardTranslator::Entry newEntry;
297            newEntry.setKeyCode( keyCode );
298            newEntry.setState( flags );
299            newEntry.setStateMask( flagMask );
300            newEntry.setModifiers( modifiers );
301            newEntry.setModifierMask( modifierMask );
302            newEntry.setText( text );
303            newEntry.setCommand( command );
304
305            _nextEntry = newEntry;
306
307            _hasNext = true;
308
309            return;
310        }
311    }
312
313    _hasNext = false;
314}
315
316bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command)
317{
318    if ( text.compare(QLatin1String("erase"),Qt::CaseInsensitive) == 0 )
319        command = KeyboardTranslator::EraseCommand;
320    else if ( text.compare(QLatin1String("scrollpageup"),Qt::CaseInsensitive) == 0 )
321        command = KeyboardTranslator::ScrollPageUpCommand;
322    else if ( text.compare(QLatin1String("scrollpagedown"),Qt::CaseInsensitive) == 0 )
323        command = KeyboardTranslator::ScrollPageDownCommand;
324    else if ( text.compare(QLatin1String("scrolllineup"),Qt::CaseInsensitive) == 0 )
325        command = KeyboardTranslator::ScrollLineUpCommand;
326    else if ( text.compare(QLatin1String("scrolllinedown"),Qt::CaseInsensitive) == 0 )
327        command = KeyboardTranslator::ScrollLineDownCommand;
328    else if ( text.compare(QLatin1String("scrolllock"),Qt::CaseInsensitive) == 0 )
329        command = KeyboardTranslator::ScrollLockCommand;
330    else if ( text.compare(QLatin1String("scrolluptotop"),Qt::CaseInsensitive) == 0)
331        command = KeyboardTranslator::ScrollUpToTopCommand;
332    else if ( text.compare(QLatin1String("scrolldowntobottom"),Qt::CaseInsensitive) == 0)
333        command = KeyboardTranslator::ScrollDownToBottomCommand;
334    else
335        return false;
336
337    return true;
338}
339
340bool KeyboardTranslatorReader::decodeSequence(const QString& text,
341                                              int& keyCode,
342                                              Qt::KeyboardModifiers& modifiers,
343                                              Qt::KeyboardModifiers& modifierMask,
344                                              KeyboardTranslator::States& flags,
345                                              KeyboardTranslator::States& flagMask)
346{
347    bool isWanted = true;
348    bool endOfItem = false;
349    QString buffer;
350
351    Qt::KeyboardModifiers tempModifiers = modifiers;
352    Qt::KeyboardModifiers tempModifierMask = modifierMask;
353    KeyboardTranslator::States tempFlags = flags;
354    KeyboardTranslator::States tempFlagMask = flagMask;
355
356    for ( int i = 0 ; i < text.count() ; i++ )
357    {
358        const QChar& ch = text[i];
359        bool isFirstLetter = i == 0;
360        bool isLastLetter = ( i == text.count()-1 );
361        endOfItem = true;
362        if ( ch.isLetterOrNumber() )
363        {
364            endOfItem = false;
365            buffer.append(ch);
366        } else if ( isFirstLetter )
367        {
368            buffer.append(ch);
369        }
370
371        if ( (endOfItem || isLastLetter) && !buffer.isEmpty() )
372        {
373            Qt::KeyboardModifier itemModifier = Qt::NoModifier;
374            int itemKeyCode = 0;
375            KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState;
376
377            if ( parseAsModifier(buffer,itemModifier) )
378            {
379                tempModifierMask |= itemModifier;
380
381                if ( isWanted )
382                    tempModifiers |= itemModifier;
383            }
384            else if ( parseAsStateFlag(buffer,itemFlag) )
385            {
386                tempFlagMask |= itemFlag;
387
388                if ( isWanted )
389                    tempFlags |= itemFlag;
390            }
391            else if ( parseAsKeyCode(buffer,itemKeyCode) )
392                keyCode = itemKeyCode;
393            else
394                qDebug() << "Unable to parse key binding item:" << buffer;
395
396            buffer.clear();
397        }
398
399        // check if this is a wanted / not-wanted flag and update the
400        // state ready for the next item
401        if ( ch == QLatin1Char('+') )
402           isWanted = true;
403        else if ( ch == QLatin1Char('-') )
404           isWanted = false;
405    }
406
407    modifiers = tempModifiers;
408    modifierMask = tempModifierMask;
409    flags = tempFlags;
410    flagMask = tempFlagMask;
411
412    return true;
413}
414
415bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier)
416{
417    if ( item == QLatin1String("shift") )
418        modifier = Qt::ShiftModifier;
419    else if ( item == QLatin1String("ctrl") || item == QLatin1String("control") )
420        modifier = Qt::ControlModifier;
421    else if ( item == QLatin1String("alt") )
422        modifier = Qt::AltModifier;
423    else if ( item == QLatin1String("meta") )
424        modifier = Qt::MetaModifier;
425    else if ( item == QLatin1String("keypad") )
426        modifier = Qt::KeypadModifier;
427    else
428        return false;
429
430    return true;
431}
432bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag)
433{
434    if ( item == QLatin1String("appcukeys") || item == QLatin1String("appcursorkeys") )
435        flag = KeyboardTranslator::CursorKeysState;
436    else if ( item == QLatin1String("ansi") )
437        flag = KeyboardTranslator::AnsiState;
438    else if ( item == QLatin1String("newline") )
439        flag = KeyboardTranslator::NewLineState;
440    else if ( item == QLatin1String("appscreen") )
441        flag = KeyboardTranslator::AlternateScreenState;
442    else if ( item == QLatin1String("anymod") || item == QLatin1String("anymodifier") )
443        flag = KeyboardTranslator::AnyModifierState;
444    else if ( item == QLatin1String("appkeypad") )
445        flag = KeyboardTranslator::ApplicationKeypadState;
446    else
447        return false;
448
449    return true;
450}
451bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode)
452{
453    QKeySequence sequence = QKeySequence::fromString(item);
454    if ( !sequence.isEmpty() )
455    {
456        keyCode = sequence[0];
457
458        if ( sequence.count() > 1 )
459        {
460            qDebug() << "Unhandled key codes in sequence: " << item;
461        }
462    }
463    // additional cases implemented for backwards compatibility with KDE 3
464    else if ( item == QLatin1String("prior") )
465        keyCode = Qt::Key_PageUp;
466    else if ( item == QLatin1String("next") )
467        keyCode = Qt::Key_PageDown;
468    else
469        return false;
470
471    return true;
472}
473
474QString KeyboardTranslatorReader::description() const
475{
476    return _description;
477}
478bool KeyboardTranslatorReader::hasNextEntry() const
479{
480    return _hasNext;
481}
482KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition ,
483                                                                 const QString& result )
484{
485    QString entryString = QString::fromLatin1("keyboard \"temporary\"\nkey ");
486    entryString.append(condition);
487    entryString.append(QLatin1String(" : "));
488
489    // if 'result' is the name of a command then the entry result will be that command,
490    // otherwise the result will be treated as a string to echo when the key sequence
491    // specified by 'condition' is pressed
492    KeyboardTranslator::Command command;
493    if (parseAsCommand(result,command))
494        entryString.append(result);
495    else
496        entryString.append(QLatin1Char('\"') + result + QLatin1Char('\"'));
497
498    QByteArray array = entryString.toUtf8();
499    QBuffer buffer(&array);
500    buffer.open(QIODevice::ReadOnly);
501    KeyboardTranslatorReader reader(&buffer);
502
503    KeyboardTranslator::Entry entry;
504    if ( reader.hasNextEntry() )
505        entry = reader.nextEntry();
506
507    return entry;
508}
509
510KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry()
511{
512    Q_ASSERT( _hasNext );
513    KeyboardTranslator::Entry entry = _nextEntry;
514    readNext();
515    return entry;
516}
517bool KeyboardTranslatorReader::parseError()
518{
519    return false;
520}
521QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const QString& line)
522{
523    QString text = line;
524
525    // remove comments
526    bool inQuotes = false;
527    int commentPos = -1;
528    for (int i=text.length()-1;i>=0;i--)
529    {
530        QChar ch = text[i];
531        if (ch == QLatin1Char('\"'))
532            inQuotes = !inQuotes;
533        else if (ch == QLatin1Char('#') && !inQuotes)
534            commentPos = i;
535    }
536    if (commentPos != -1)
537        text.remove(commentPos,text.length());
538
539    text = text.simplified();
540
541    // title line: keyboard "title"
542    static QRegExp title(QLatin1String("keyboard\\s+\"(.*)\""));
543    // key line: key KeySequence : "output"
544    // key line: key KeySequence : command
545    static QRegExp key(QLatin1String("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)"));
546
547    QList<Token> list;
548    if ( text.isEmpty() )
549    {
550        return list;
551    }
552
553    if ( title.exactMatch(text) )
554    {
555        Token titleToken = { Token::TitleKeyword , QString() };
556        Token textToken = { Token::TitleText , title.capturedTexts().at(1) };
557
558        list << titleToken << textToken;
559    }
560    else if  ( key.exactMatch(text) )
561    {
562        Token keyToken = { Token::KeyKeyword , QString() };
563        Token sequenceToken = { Token::KeySequence , key.capturedTexts().value(1).remove(QLatin1Char(' ')) };
564
565        list << keyToken << sequenceToken;
566
567        if ( key.capturedTexts().at(3).isEmpty() )
568        {
569            // capturedTexts()[2] is a command
570            Token commandToken = { Token::Command , key.capturedTexts().at(2) };
571            list << commandToken;
572        }
573        else
574        {
575            // capturedTexts()[3] is the output string
576           Token outputToken = { Token::OutputText , key.capturedTexts().at(3) };
577           list << outputToken;
578        }
579    }
580    else
581    {
582        qDebug() << "Line in keyboard translator file could not be understood:" << text;
583    }
584
585    return list;
586}
587
588QList<QString> KeyboardTranslatorManager::allTranslators()
589{
590    if ( !_haveLoadedAll )
591    {
592        findTranslators();
593    }
594
595    return _translators.keys();
596}
597
598KeyboardTranslator::Entry::Entry()
599: _keyCode(0)
600, _modifiers(Qt::NoModifier)
601, _modifierMask(Qt::NoModifier)
602, _state(NoState)
603, _stateMask(NoState)
604, _command(NoCommand)
605{
606}
607
608bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const
609{
610    return _keyCode == rhs._keyCode &&
611           _modifiers == rhs._modifiers &&
612           _modifierMask == rhs._modifierMask &&
613           _state == rhs._state &&
614           _stateMask == rhs._stateMask &&
615           _command == rhs._command &&
616           _text == rhs._text;
617}
618
619bool KeyboardTranslator::Entry::matches(int keyCode ,
620                                        Qt::KeyboardModifiers modifiers,
621                                        States testState) const
622{
623#ifdef Q_OS_MAC
624    // On Mac, arrow keys are considered part of keypad. Ignore that.
625    modifiers &= ~Qt::KeypadModifier;
626#endif
627
628    if ( _keyCode != keyCode )
629        return false;
630
631    if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) )
632        return false;
633
634    // if modifiers is non-zero, the 'any modifier' state is implicit
635    if ( (modifiers & ~Qt::KeypadModifier) != 0 )
636        testState |= AnyModifierState;
637
638    if ( (testState & _stateMask) != (_state & _stateMask) )
639        return false;
640
641    // special handling for the 'Any Modifier' state, which checks for the presence of
642    // any or no modifiers.  In this context, the 'keypad' modifier does not count.
643    bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier;
644    bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState;
645    if ( _stateMask & KeyboardTranslator::AnyModifierState )
646    {
647        if ( wantAnyModifier != anyModifiersSet )
648           return false;
649    }
650
651    return true;
652}
653QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
654{
655    QByteArray result(text(expandWildCards,modifiers));
656
657    for ( int i = 0 ; i < result.count() ; i++ )
658    {
659        char ch = result[i];
660        char replacement = 0;
661
662        switch ( ch )
663        {
664            case 27 : replacement = 'E'; break;
665            case 8  : replacement = 'b'; break;
666            case 12 : replacement = 'f'; break;
667            case 9  : replacement = 't'; break;
668            case 13 : replacement = 'r'; break;
669            case 10 : replacement = 'n'; break;
670            default:
671                // any character which is not printable is replaced by an equivalent
672                // \xhh escape sequence (where 'hh' are the corresponding hex digits)
673                if ( !QChar(QLatin1Char(ch)).isPrint() )
674                    replacement = 'x';
675        }
676
677        if ( replacement == 'x' )
678        {
679            result.replace(i,1,"\\x"+QByteArray(1,ch).toHex());
680        } else if ( replacement != 0 )
681        {
682            result.remove(i,1);
683            result.insert(i,'\\');
684            result.insert(i+1,replacement);
685        }
686    }
687
688    return result;
689}
690QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const
691{
692    QByteArray result(input);
693
694    for ( int i = 0 ; i < result.count()-1 ; i++ )
695    {
696
697        QByteRef ch = result[i];
698        if ( ch == '\\' )
699        {
700           char replacement[2] = {0,0};
701           int charsToRemove = 2;
702           bool escapedChar = true;
703
704           switch ( result[i+1] )
705           {
706              case 'E' : replacement[0] = 27; break;
707              case 'b' : replacement[0] = 8 ; break;
708              case 'f' : replacement[0] = 12; break;
709              case 't' : replacement[0] = 9 ; break;
710              case 'r' : replacement[0] = 13; break;
711              case 'n' : replacement[0] = 10; break;
712              case 'x' :
713                 {
714                    // format is \xh or \xhh where 'h' is a hexadecimal
715                    // digit from 0-9 or A-F which should be replaced
716                    // with the corresponding character value
717                    char hexDigits[3] = {0};
718
719                    if ( (i < result.count()-2) && isxdigit(result[i+2]) )
720                            hexDigits[0] = result[i+2];
721                    if ( (i < result.count()-3) && isxdigit(result[i+3]) )
722                            hexDigits[1] = result[i+3];
723
724                    unsigned charValue = 0;
725                    sscanf(hexDigits,"%x",&charValue);
726
727                    replacement[0] = (char)charValue;
728                    charsToRemove = 2 + strlen(hexDigits);
729                  }
730              break;
731              default:
732                  escapedChar = false;
733           }
734
735           if ( escapedChar )
736               result.replace(i,charsToRemove,replacement);
737        }
738    }
739
740    return result;
741}
742
743void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const
744{
745    if ( !(modifier & _modifierMask) )
746        return;
747
748    if ( modifier & _modifiers )
749        item += QLatin1Char('+');
750    else
751        item += QLatin1Char('-');
752
753    if ( modifier == Qt::ShiftModifier )
754        item += QLatin1String("Shift");
755    else if ( modifier == Qt::ControlModifier )
756        item += QLatin1String("Ctrl");
757    else if ( modifier == Qt::AltModifier )
758        item += QLatin1String("Alt");
759    else if ( modifier == Qt::MetaModifier )
760        item += QLatin1String("Meta");
761    else if ( modifier == Qt::KeypadModifier )
762        item += QLatin1String("KeyPad");
763}
764void KeyboardTranslator::Entry::insertState( QString& item , int state ) const
765{
766    if ( !(state & _stateMask) )
767        return;
768
769    if ( state & _state )
770        item += QLatin1Char('+') ;
771    else
772        item += QLatin1Char('-') ;
773
774    if ( state == KeyboardTranslator::AlternateScreenState )
775        item += QLatin1String("AppScreen");
776    else if ( state == KeyboardTranslator::NewLineState )
777        item += QLatin1String("NewLine");
778    else if ( state == KeyboardTranslator::AnsiState )
779        item += QLatin1String("Ansi");
780    else if ( state == KeyboardTranslator::CursorKeysState )
781        item += QLatin1String("AppCursorKeys");
782    else if ( state == KeyboardTranslator::AnyModifierState )
783        item += QLatin1String("AnyModifier");
784    else if ( state == KeyboardTranslator::ApplicationKeypadState )
785        item += QLatin1String("AppKeypad");
786}
787QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
788{
789    if ( !_text.isEmpty() )
790        return QString::fromLatin1(escapedText(expandWildCards,modifiers));
791    else if ( _command == EraseCommand )
792        return QLatin1String("Erase");
793    else if ( _command == ScrollPageUpCommand )
794        return QLatin1String("ScrollPageUp");
795    else if ( _command == ScrollPageDownCommand )
796        return QLatin1String("ScrollPageDown");
797    else if ( _command == ScrollLineUpCommand )
798        return QLatin1String("ScrollLineUp");
799    else if ( _command == ScrollLineDownCommand )
800        return QLatin1String("ScrollLineDown");
801    else if ( _command == ScrollLockCommand )
802        return QLatin1String("ScrollLock");
803    else if (_command == ScrollUpToTopCommand)
804        return QLatin1String("ScrollUpToTop");
805    else if (_command == ScrollDownToBottomCommand)
806        return QLatin1String("ScrollDownToBottom");
807
808    return QString();
809}
810QString KeyboardTranslator::Entry::conditionToString() const
811{
812    QString result = QKeySequence(_keyCode).toString();
813
814    insertModifier( result , Qt::ShiftModifier );
815    insertModifier( result , Qt::ControlModifier );
816    insertModifier( result , Qt::AltModifier );
817    insertModifier( result , Qt::MetaModifier );
818    insertModifier( result , Qt::KeypadModifier );
819
820    insertState( result , KeyboardTranslator::AlternateScreenState );
821    insertState( result , KeyboardTranslator::NewLineState );
822    insertState( result , KeyboardTranslator::AnsiState );
823    insertState( result , KeyboardTranslator::CursorKeysState );
824    insertState( result , KeyboardTranslator::AnyModifierState );
825    insertState( result , KeyboardTranslator::ApplicationKeypadState );
826
827    return result;
828}
829
830KeyboardTranslator::KeyboardTranslator(const QString& name)
831: _name(name)
832{
833}
834
835void KeyboardTranslator::setDescription(const QString& description)
836{
837    _description = description;
838}
839QString KeyboardTranslator::description() const
840{
841    return _description;
842}
843void KeyboardTranslator::setName(const QString& name)
844{
845    _name = name;
846}
847QString KeyboardTranslator::name() const
848{
849    return _name;
850}
851
852QList<KeyboardTranslator::Entry> KeyboardTranslator::entries() const
853{
854    return _entries.values();
855}
856
857void KeyboardTranslator::addEntry(const Entry& entry)
858{
859    const int keyCode = entry.keyCode();
860    _entries.insert(keyCode,entry);
861}
862void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement)
863{
864    if ( !existing.isNull() )
865        _entries.remove(existing.keyCode(),existing);
866    _entries.insert(replacement.keyCode(),replacement);
867}
868void KeyboardTranslator::removeEntry(const Entry& entry)
869{
870    _entries.remove(entry.keyCode(),entry);
871}
872KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const
873{
874    for (auto it = _entries.cbegin(), end = _entries.cend(); it != end; ++it)
875    {
876        if (it.key() == keyCode)
877            if ( it.value().matches(keyCode,modifiers,state) )
878                return *it;
879    }
880    return Entry(); // entry not found
881}
882void KeyboardTranslatorManager::addTranslator(KeyboardTranslator* translator)
883{
884    _translators.insert(translator->name(),translator);
885
886    if ( !saveTranslator(translator) )
887        qDebug() << "Unable to save translator" << translator->name()
888                   << "to disk.";
889}
890bool KeyboardTranslatorManager::deleteTranslator(const QString& name)
891{
892    Q_ASSERT( _translators.contains(name) );
893
894    // locate and delete
895    QString path = findTranslatorPath(name);
896    if ( QFile::remove(path) )
897    {
898        _translators.remove(name);
899        return true;
900    }
901    else
902    {
903        qDebug() << "Failed to remove translator - " << path;
904        return false;
905    }
906}
907Q_GLOBAL_STATIC( KeyboardTranslatorManager , theKeyboardTranslatorManager )
908KeyboardTranslatorManager* KeyboardTranslatorManager::instance()
909{
910    return theKeyboardTranslatorManager;
911}
Note: See TracBrowser for help on using the repository browser.