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 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696
  
     | 
    
      /*
    Modified by Ran Lu <hephooey@fastmail.fm> for QTerm.
    This source file is part of Konsole, a terminal emulator.
    Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
    02110-1301  USA.
*/
// Own
#include "keyboardtranslator.h"
// System
#include <ctype.h>
#include <stdio.h>
// Qt
#include <QtCore/QBuffer>
#include <QtCore/QFile>
#include <QtCore/QFileInfo>
#include <QtCore/QTextStream>
#include <QtCore/QRegExp>
#include <QtCore/QStringList>
#include <QtGui/QKeySequence>
#include <QtDebug>
namespace QTerm
{
// each line of the keyboard translation file is one of:
//
// - keyboard "name"
// - key KeySequence : "characters"
// - key KeySequence : CommandName
//
// KeySequence begins with the name of the key ( taken from the Qt::Key enum )
// and is followed by the keyboard modifiers and state flags ( with + or - in front
// of each modifier or flag to indicate whether it is required ).  All keyboard modifiers
// and flags are optional, if a particular modifier or state is not specified it is 
// assumed not to be a part of the sequence.  The key sequence may contain whitespace
//
// eg:  "key Up+Shift : scrollLineUp"
//      "key Next-Shift : "\E[6~"
//
// (lines containing only whitespace are ignored, parseLine assumes that comments have
// already been removed)
//
KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source )
    : _source(source)
    , _hasNext(false)
{
   // read input until we find the description
   while ( _description.isEmpty() && !source->atEnd() )
   {
        QList<Token> tokens = tokenize( QString(source->readLine()) );
        if ( !tokens.isEmpty() && tokens.first().type == Token::TitleKeyword )
            _description = tokens[1].text.toUtf8();
   }
   // read first entry (if any)
   readNext();
}
void KeyboardTranslatorReader::readNext() 
{
    // find next entry
    while ( !_source->atEnd() )
    {
        const QList<Token>& tokens = tokenize( QString(_source->readLine()) );
        if ( !tokens.isEmpty() && tokens.first().type == Token::KeyKeyword )
        {
            KeyboardTranslator::States flags = KeyboardTranslator::NoState;
            KeyboardTranslator::States flagMask = KeyboardTranslator::NoState;
            Qt::KeyboardModifiers modifiers = Qt::NoModifier;
            Qt::KeyboardModifiers modifierMask = Qt::NoModifier;
            int keyCode = Qt::Key_unknown;
            decodeSequence(tokens[1].text.toLower(),
                           keyCode,
                           modifiers,
                           modifierMask,
                           flags,
                           flagMask); 
            KeyboardTranslator::Command command = KeyboardTranslator::NoCommand;
            QByteArray text;
            // get text or command
            if ( tokens[2].type == Token::OutputText )
            {
                text = tokens[2].text.toLocal8Bit();
            }
            else if ( tokens[2].type == Token::Command )
            {
                // identify command
                if (!parseAsCommand(tokens[2].text,command))
                    qWarning() << "Command" << tokens[2].text << "not understood.";
            }
            KeyboardTranslator::Entry newEntry;
            newEntry.setKeyCode( keyCode );
            newEntry.setState( flags );
            newEntry.setStateMask( flagMask );
            newEntry.setModifiers( modifiers );
            newEntry.setModifierMask( modifierMask );
            newEntry.setText( text );
            newEntry.setCommand( command );
            _nextEntry = newEntry;
            _hasNext = true;
            return;
        }
    } 
    _hasNext = false;
}
bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) 
{
    if ( text.compare("erase",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::EraseCommand;
    else if ( text.compare("scrollpageup",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::ScrollPageUpCommand;
    else if ( text.compare("scrollpagedown",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::ScrollPageDownCommand;
    else if ( text.compare("scrolllineup",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::ScrollLineUpCommand;
    else if ( text.compare("scrolllinedown",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::ScrollLineDownCommand;
    else if ( text.compare("scrolllock",Qt::CaseInsensitive) == 0 )
        command = KeyboardTranslator::ScrollLockCommand;
    else
        return false;
    return true;
}
bool KeyboardTranslatorReader::decodeSequence(const QString& text,
                                              int& keyCode,
                                              Qt::KeyboardModifiers& modifiers,
                                              Qt::KeyboardModifiers& modifierMask,
                                              KeyboardTranslator::States& flags,
                                              KeyboardTranslator::States& flagMask)
{
    bool isWanted = true; 
    bool endOfItem = false;
    QString buffer;
    Qt::KeyboardModifiers tempModifiers = modifiers;
    Qt::KeyboardModifiers tempModifierMask = modifierMask;
    KeyboardTranslator::States tempFlags = flags;
    KeyboardTranslator::States tempFlagMask = flagMask;
    for ( int i = 0 ; i < text.count() ; i++ )
    {
        const QChar& ch = text[i];
        bool isFirstLetter = i == 0;
        bool isLastLetter = ( i == text.count()-1 );
        endOfItem = true;
        if ( ch.isLetterOrNumber() )
        {
            endOfItem = false;
            buffer.append(ch);
        } else if ( isFirstLetter )
        {
            buffer.append(ch);
        }
        if ( (endOfItem || isLastLetter) && !buffer.isEmpty() )
        {
            Qt::KeyboardModifier itemModifier = Qt::NoModifier;
            int itemKeyCode = 0;
            KeyboardTranslator::State itemFlag = KeyboardTranslator::NoState;
            if ( parseAsModifier(buffer,itemModifier) )
            {
                tempModifierMask |= itemModifier;
                if ( isWanted )
                    tempModifiers |= itemModifier;
            }
            else if ( parseAsStateFlag(buffer,itemFlag) )
            {
                tempFlagMask |= itemFlag;
                if ( isWanted )
                    tempFlags |= itemFlag;
            }
            else if ( parseAsKeyCode(buffer,itemKeyCode) )
                keyCode = itemKeyCode;
            else
                qDebug() << "Unable to parse key binding item:" << buffer;
            buffer.clear();
        }
        // check if this is a wanted / not-wanted flag and update the 
        // state ready for the next item
        if ( ch == '+' )
           isWanted = true;
        else if ( ch == '-' )
           isWanted = false; 
    } 
    modifiers = tempModifiers;
    modifierMask = tempModifierMask;
    flags = tempFlags;
    flagMask = tempFlagMask;
    return true;
}
bool KeyboardTranslatorReader::parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier)
{
    if ( item == "shift" )
        modifier = Qt::ShiftModifier;
    else if ( item == "ctrl" || item == "control" )
        modifier = Qt::ControlModifier;
    else if ( item == "alt" )
        modifier = Qt::AltModifier;
    else if ( item == "meta" )
        modifier = Qt::MetaModifier;
    else if ( item == "keypad" )
        modifier = Qt::KeypadModifier;
    else
        return false;
    return true;
}
bool KeyboardTranslatorReader::parseAsStateFlag(const QString& item , KeyboardTranslator::State& flag)
{
    if ( item == "appcukeys" || item == "appcursorkeys" )
        flag = KeyboardTranslator::CursorKeysState;
    else if ( item == "ansi" )
        flag = KeyboardTranslator::AnsiState;
    else if ( item == "newline" )
        flag = KeyboardTranslator::NewLineState;
    else if ( item == "appscreen" )
        flag = KeyboardTranslator::AlternateScreenState;
    else if ( item == "anymod" || item == "anymodifier" )
        flag = KeyboardTranslator::AnyModifierState;
    else if ( item == "appkeypad" )
        flag = KeyboardTranslator::ApplicationKeypadState;
    else
        return false;
    return true;
}
bool KeyboardTranslatorReader::parseAsKeyCode(const QString& item , int& keyCode)
{
    QKeySequence sequence = QKeySequence::fromString(item);
    if ( !sequence.isEmpty() )
    {
        keyCode = sequence[0];
        if ( sequence.count() > 1 )
        {
            qDebug() << "Unhandled key codes in sequence: " << item;
        }
    }
    // additional cases implemented for backwards compatibility with KDE 3
    else if ( item == "prior" )
        keyCode = Qt::Key_PageUp;
    else if ( item == "next" )
        keyCode = Qt::Key_PageDown;
    else
        return false;
    return true;
}
QString KeyboardTranslatorReader::description() const
{
    return _description;
}
bool KeyboardTranslatorReader::hasNextEntry()
{
    return _hasNext;
}
KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , 
                                                                 const QString& result )
{
    QString entryString("keyboard \"temporary\"\nkey ");
    entryString.append(condition);
    entryString.append(" : ");
    // if 'result' is the name of a command then the entry result will be that command,
    // otherwise the result will be treated as a string to echo when the key sequence
    // specified by 'condition' is pressed
    KeyboardTranslator::Command command;
    if (parseAsCommand(result,command))
        entryString.append(result);
    else
        entryString.append('\"' + result + '\"');
    QByteArray array = entryString.toUtf8();
    QBuffer buffer(&array);
    buffer.open(QIODevice::ReadOnly);
    KeyboardTranslatorReader reader(&buffer);
    KeyboardTranslator::Entry entry;
    if ( reader.hasNextEntry() )
        entry = reader.nextEntry();
    return entry;
}
KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() 
{
    Q_ASSERT( _hasNext );
    KeyboardTranslator::Entry entry = _nextEntry;
    readNext();
    return entry;
}
bool KeyboardTranslatorReader::parseError()
{
    return false;
}
QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const QString& line)
{
    QString text = line;
    // remove comments 
    bool inQuotes = false;
    int commentPos = -1;
    for (int i=text.length()-1;i>=0;i--)
    {
        QChar ch = text[i];
        if (ch == '\"')
            inQuotes = !inQuotes;
        else if (ch == '#' && !inQuotes)
            commentPos = i;
    }
    if (commentPos != -1)
        text.remove(commentPos,text.length());
    text = text.simplified();
   
    // title line: keyboard "title"
    static QRegExp title("keyboard\\s+\"(.*)\"");
    // key line: key KeySequence : "output"
    // key line: key KeySequence : command
    static QRegExp key("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)");
    QList<Token> list;
    if ( text.isEmpty() ) 
    {
        return list;
    }
    if ( title.exactMatch(text) )
    {
        Token titleToken = { Token::TitleKeyword , QString() };
        Token textToken = { Token::TitleText , title.capturedTexts()[1] };
    
        list << titleToken << textToken;
    }
    else if  ( key.exactMatch(text) )
    {
        Token keyToken = { Token::KeyKeyword , QString() };
        Token sequenceToken = { Token::KeySequence , key.capturedTexts()[1].remove(' ') };
        list << keyToken << sequenceToken;
        if ( key.capturedTexts()[3].isEmpty() )
        {
            // capturedTexts()[2] is a command
            Token commandToken = { Token::Command , key.capturedTexts()[2] };
            list << commandToken;    
        }   
        else
        {
            // capturedTexts()[3] is the output string
           Token outputToken = { Token::OutputText , key.capturedTexts()[3] };
           list << outputToken;
        }    
    }
    else
    {
        qWarning() << "Line in keyboard translator file could not be understood:" << text;
    }
    return list;
}
KeyboardTranslator::Entry::Entry()
: _keyCode(0)
, _modifiers(Qt::NoModifier)
, _modifierMask(Qt::NoModifier)
, _state(NoState)
, _stateMask(NoState)
, _command(NoCommand)
{
}
bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const
{
    return _keyCode == rhs._keyCode &&
           _modifiers == rhs._modifiers &&
           _modifierMask == rhs._modifierMask &&
           _state == rhs._state &&
           _stateMask == rhs._stateMask &&
           _command == rhs._command &&
           _text == rhs._text;
}
bool KeyboardTranslator::Entry::matches(int keyCode , 
                                        Qt::KeyboardModifiers modifiers,
                                        States testState) const
{
    if ( _keyCode != keyCode )
        return false;
    if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) 
        return false;
    // if modifiers is non-zero, the 'any modifier' state is implicit
    if ( modifiers != 0 )
        testState |= AnyModifierState;
    if ( (testState & _stateMask) != (_state & _stateMask) )
        return false;
    // special handling for the 'Any Modifier' state, which checks for the presence of 
    // any or no modifiers.  In this context, the 'keypad' modifier does not count.
    bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier;
    bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState;
    if ( _stateMask & KeyboardTranslator::AnyModifierState )
    {
        if ( wantAnyModifier != anyModifiersSet )
           return false;
    }
    
    return true;
}
QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
{
    QByteArray result(text(expandWildCards,modifiers));
    for ( int i = 0 ; i < result.count() ; i++ )
    {
        char ch = result[i];
        char replacement = 0;
        switch ( ch )
        {
            case 27 : replacement = 'E'; break;
            case 8  : replacement = 'b'; break;
            case 12 : replacement = 'f'; break;
            case 9  : replacement = 't'; break;
            case 13 : replacement = 'r'; break;
            case 10 : replacement = 'n'; break;
            default:
                // any character which is not printable is replaced by an equivalent
                // \xhh escape sequence (where 'hh' are the corresponding hex digits)
                if ( !QChar(ch).isPrint() )
                    replacement = 'x';
        }
        if ( replacement == 'x' )
        {
            result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); 
        } else if ( replacement != 0 )
        {
            result.remove(i,1);
            result.insert(i,'\\');
            result.insert(i+1,replacement);
        }
    }
    return result;
}
QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const
{
    QByteArray result(input);
    for ( int i = 0 ; i < result.count()-1 ; i++ )
    {
        QByteRef ch = result[i];
        if ( ch == '\\' )
        {
           char replacement[2] = {0,0};
           int charsToRemove = 2;
           bool escapedChar = true;
           switch ( result[i+1] )
           {
              case 'E' : replacement[0] = 27; break;
              case 'b' : replacement[0] = 8 ; break;
              case 'f' : replacement[0] = 12; break;
              case 't' : replacement[0] = 9 ; break;
              case 'r' : replacement[0] = 13; break;
              case 'n' : replacement[0] = 10; break;
              case 'x' :
                 {
                    // format is \xh or \xhh where 'h' is a hexadecimal
                    // digit from 0-9 or A-F which should be replaced
                    // with the corresponding character value
                    char hexDigits[3] = {0};
                    if ( (i < result.count()-2) && isxdigit(result[i+2]) )
                            hexDigits[0] = result[i+2];
                    if ( (i < result.count()-3) && isxdigit(result[i+3]) )
                            hexDigits[1] = result[i+3];
                    unsigned charValue = 0;
                    sscanf(hexDigits,"%x",&charValue);
                    replacement[0] = (char)charValue; 
                    charsToRemove = 2 + strlen(hexDigits);
                  }
              break;
              default:
                  escapedChar = false;
           }
           if ( escapedChar )
               result.replace(i,charsToRemove,replacement);
        }
    }
    return result;
}
void KeyboardTranslator::Entry::insertModifier( QString& item , int modifier ) const
{
    if ( !(modifier & _modifierMask) )
        return;
    if ( modifier & _modifiers )
        item += '+';
    else
        item += '-';
    if ( modifier == Qt::ShiftModifier )
        item += "Shift";
    else if ( modifier == Qt::ControlModifier )
        item += "Ctrl";
    else if ( modifier == Qt::AltModifier )
        item += "Alt";
    else if ( modifier == Qt::MetaModifier )
        item += "Meta";
    else if ( modifier == Qt::KeypadModifier )
        item += "KeyPad";
}
void KeyboardTranslator::Entry::insertState( QString& item , int state ) const
{
    if ( !(state & _stateMask) )
        return;
    if ( state & _state )
        item += '+' ;
    else
        item += '-' ;
    if ( state == KeyboardTranslator::AlternateScreenState )
        item += "AppScreen";
    else if ( state == KeyboardTranslator::NewLineState )
        item += "NewLine";
    else if ( state == KeyboardTranslator::AnsiState )
        item += "Ansi";
    else if ( state == KeyboardTranslator::CursorKeysState )
        item += "AppCursorKeys";
    else if ( state == KeyboardTranslator::AnyModifierState )
        item += "AnyModifier";
    else if ( state == KeyboardTranslator::ApplicationKeypadState )
        item += "AppKeypad";
}
QString KeyboardTranslator::Entry::resultToString(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
{
    if ( !_text.isEmpty() )
        return escapedText(expandWildCards,modifiers);
    else if ( _command == EraseCommand )
        return "Erase";
    else if ( _command == ScrollPageUpCommand )
        return "ScrollPageUp";
    else if ( _command == ScrollPageDownCommand )
        return "ScrollPageDown";
    else if ( _command == ScrollLineUpCommand )
        return "ScrollLineUp";
    else if ( _command == ScrollLineDownCommand )
        return "ScrollLineDown";
    else if ( _command == ScrollLockCommand )
        return "ScrollLock";
    return QString();
}
QString KeyboardTranslator::Entry::conditionToString() const
{
    QString result = QKeySequence(_keyCode).toString();
    insertModifier( result , Qt::ShiftModifier );
    insertModifier( result , Qt::ControlModifier );
    insertModifier( result , Qt::AltModifier );
    insertModifier( result , Qt::MetaModifier );
    insertModifier( result , Qt::KeypadModifier );
    insertState( result , KeyboardTranslator::AlternateScreenState );
    insertState( result , KeyboardTranslator::NewLineState );
    insertState( result , KeyboardTranslator::AnsiState );
    insertState( result , KeyboardTranslator::CursorKeysState );
    insertState( result , KeyboardTranslator::AnyModifierState );
    insertState( result , KeyboardTranslator::ApplicationKeypadState );
    return result;
}
KeyboardTranslator::KeyboardTranslator(const QString& name)
: _name(name)
{
}
void KeyboardTranslator::setDescription(const QString& description) 
{
    _description = description;
}
QString KeyboardTranslator::description() const
{
    return _description;
}
void KeyboardTranslator::setName(const QString& name)
{
    _name = name;
}
QString KeyboardTranslator::name() const
{
    return _name;
}
QList<KeyboardTranslator::Entry> KeyboardTranslator::entries() const
{
    return _entries.values();
}
void KeyboardTranslator::addEntry(const Entry& entry)
{
    const int keyCode = entry.keyCode();
    _entries.insert(keyCode,entry);
}
void KeyboardTranslator::replaceEntry(const Entry& existing , const Entry& replacement)
{
    if ( !existing.isNull() )
        _entries.remove(existing.keyCode(),existing);
    _entries.insert(replacement.keyCode(),replacement);
}
void KeyboardTranslator::removeEntry(const Entry& entry)
{
    _entries.remove(entry.keyCode(),entry);
}
KeyboardTranslator::Entry KeyboardTranslator::findEntry(int keyCode, Qt::KeyboardModifiers modifiers, States state) const
{
    foreach(const Entry& entry, _entries.values(keyCode))
    {
        if ( entry.matches(keyCode,modifiers,state) )
            return entry;
    }
    return Entry(); // entry not found
}
} // namespace QTerm
 
     |