add more spacing
[personal-kdebase.git] / apps / konsole / src / KeyboardTranslator.h
blob300d139cf3877bf1df907edbd071940bfbf7655f
1 /*
2 This source file is part of Konsole, a terminal emulator.
4 Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
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.
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.
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.
22 #ifndef KEYBOARDTRANSLATOR_H
23 #define KEYBOARDTRANSLATOR_H
25 // Qt
26 #include <QtCore/QHash>
27 #include <QtCore/QList>
28 #include <QtGui/QKeySequence>
29 #include <QtCore/QMetaType>
30 #include <QtCore/QVarLengthArray>
32 // KDE
33 #include <kdemacros.h>
35 class QIODevice;
36 class QTextStream;
38 namespace Konsole
41 /**
42 * A convertor which maps between key sequences pressed by the user and the
43 * character strings which should be sent to the terminal and commands
44 * which should be invoked when those character sequences are pressed.
46 * Konsole supports multiple keyboard translators, allowing the user to
47 * specify the character sequences which are sent to the terminal
48 * when particular key sequences are pressed.
50 * A key sequence is defined as a key code, associated keyboard modifiers
51 * (Shift,Ctrl,Alt,Meta etc.) and state flags which indicate the state
52 * which the terminal must be in for the key sequence to apply.
54 class KeyboardTranslator
56 public:
57 /**
58 * The meaning of a particular key sequence may depend upon the state which
59 * the terminal emulation is in. Therefore findEntry() may return a different
60 * Entry depending upon the state flags supplied.
62 * This enum describes the states which may be associated with with a particular
63 * entry in the keyboard translation entry.
65 enum State
67 /** Indicates that no special state is active */
68 NoState = 0,
69 /**
70 * TODO More documentation
72 NewLineState = 1,
73 /**
74 * Indicates that the terminal is in 'Ansi' mode.
75 * TODO: More documentation
77 AnsiState = 2,
78 /**
79 * TODO More documentation
81 CursorKeysState = 4,
82 /**
83 * Indicates that the alternate screen ( typically used by interactive programs
84 * such as screen or vim ) is active
86 AlternateScreenState = 8,
87 /** Indicates that any of the modifier keys is active. */
88 AnyModifierState = 16,
89 /** Indicates that the numpad is in application mode. */
90 ApplicationKeypadState = 32
92 Q_DECLARE_FLAGS(States,State)
94 /**
95 * This enum describes commands which are associated with particular key sequences.
97 enum Command
99 /** Indicates that no command is associated with this command sequence */
100 NoCommand = 0,
101 /** TODO Document me */
102 SendCommand = 1,
103 /** Scroll the terminal display up one page */
104 ScrollPageUpCommand = 2,
105 /** Scroll the terminal display down one page */
106 ScrollPageDownCommand = 4,
107 /** Scroll the terminal display up one line */
108 ScrollLineUpCommand = 8,
109 /** Scroll the terminal display down one line */
110 ScrollLineDownCommand = 16,
111 /** Toggles scroll lock mode */
112 ScrollLockCommand = 32,
113 /** Echos the operating system specific erase character. */
114 EraseCommand = 64
116 Q_DECLARE_FLAGS(Commands,Command)
119 * Represents an association between a key sequence pressed by the user
120 * and the character sequence and commands associated with it for a particular
121 * KeyboardTranslator.
123 class Entry
125 public:
126 /**
127 * Constructs a new entry for a keyboard translator.
129 Entry();
131 /**
132 * Returns true if this entry is null.
133 * This is true for newly constructed entries which have no properties set.
135 bool isNull() const;
137 /** Returns the commands associated with this entry */
138 Command command() const;
139 /** Sets the command associated with this entry. */
140 void setCommand(Command command);
142 /**
143 * Returns the character sequence associated with this entry, optionally replacing
144 * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed.
146 * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code.
147 * Document them.
149 * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in
150 * the entry should be replaced with a number to indicate the modifier keys being pressed.
152 * @param modifiers The keyboard modifiers being pressed.
154 QByteArray text(bool expandWildCards = false,
155 Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
157 /** Sets the character sequence associated with this entry */
158 void setText(const QByteArray& text);
160 /**
161 * Returns the character sequence associated with this entry,
162 * with any non-printable characters replaced with escape sequences.
164 * eg. \\E for Escape, \\t for tab, \\n for new line.
166 * @param expandWildCards See text()
167 * @param modifiers See text()
169 QByteArray escapedText(bool expandWildCards = false,
170 Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
172 /** Returns the character code ( from the Qt::Key enum ) associated with this entry */
173 int keyCode() const;
174 /** Sets the character code associated with this entry */
175 void setKeyCode(int keyCode);
177 /**
178 * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry.
179 * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry
180 * only matches when that modifier is NOT pressed.
182 * If a modifier is not set in modifierMask() then the entry matches whether the modifier
183 * is pressed or not.
185 Qt::KeyboardModifiers modifiers() const;
187 /** Returns the keyboard modifiers which are valid in this entry. See modifiers() */
188 Qt::KeyboardModifiers modifierMask() const;
190 /** See modifiers() */
191 void setModifiers( Qt::KeyboardModifiers modifiers );
192 /** See modifierMask() and modifiers() */
193 void setModifierMask( Qt::KeyboardModifiers modifiers );
195 /**
196 * Returns a bitwise-OR of the enabled state flags associated with this entry.
197 * If flag is set in stateMask() but not in state(), this means that the entry only
198 * matches when the terminal is NOT in that state.
200 * If a state is not set in stateMask() then the entry matches whether the terminal
201 * is in that state or not.
203 States state() const;
205 /** Returns the state flags which are valid in this entry. See state() */
206 States stateMask() const;
208 /** See state() */
209 void setState( States state );
210 /** See stateMask() */
211 void setStateMask( States mask );
213 /**
214 * Returns the key code and modifiers associated with this entry
215 * as a QKeySequence
217 //QKeySequence keySequence() const;
219 /**
220 * Returns this entry's conditions ( ie. its key code, modifier and state criteria )
221 * as a string.
223 QString conditionToString() const;
226 * Returns this entry's result ( ie. its command or character sequence )
227 * as a string.
229 * @param expandWildCards See text()
230 * @param modifiers See text()
232 QString resultToString(bool expandWildCards = false,
233 Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
235 /**
236 * Returns true if this entry matches the given key sequence, specified
237 * as a combination of @p keyCode , @p modifiers and @p state.
239 bool matches( int keyCode ,
240 Qt::KeyboardModifiers modifiers ,
241 States flags ) const;
243 bool operator==(const Entry& rhs) const;
245 private:
246 void insertModifier( QString& item , int modifier ) const;
247 void insertState( QString& item , int state ) const;
248 QByteArray unescape(const QByteArray& text) const;
250 int _keyCode;
251 Qt::KeyboardModifiers _modifiers;
252 Qt::KeyboardModifiers _modifierMask;
253 States _state;
254 States _stateMask;
256 Command _command;
257 QByteArray _text;
260 /** Constructs a new keyboard translator with the given @p name */
261 KeyboardTranslator(const QString& name);
263 //KeyboardTranslator(const KeyboardTranslator& other);
265 /** Returns the name of this keyboard translator */
266 QString name() const;
268 /** Sets the name of this keyboard translator */
269 void setName(const QString& name);
271 /** Returns the descriptive name of this keyboard translator */
272 QString description() const;
274 /** Sets the descriptive name of this keyboard translator */
275 void setDescription(const QString& description);
278 * Looks for an entry in this keyboard translator which matches the given
279 * key code, keyboard modifiers and state flags.
281 * Returns the matching entry if found or a null Entry otherwise ( ie.
282 * entry.isNull() will return true )
284 * @param keyCode A key code from the Qt::Key enum
285 * @param modifiers A combination of modifiers
286 * @param state Optional flags which specify the current state of the terminal
288 Entry findEntry(int keyCode ,
289 Qt::KeyboardModifiers modifiers ,
290 States state = NoState) const;
292 /**
293 * Adds an entry to this keyboard translator's table. Entries can be looked up according
294 * to their key sequence using findEntry()
296 void addEntry(const Entry& entry);
299 * Replaces an entry in the translator. If the @p existing entry is null,
300 * then this is equivalent to calling addEntry(@p replacement)
302 void replaceEntry(const Entry& existing , const Entry& replacement);
305 * Removes an entry from the table.
307 void removeEntry(const Entry& entry);
309 /** Returns a list of all entries in the translator. */
310 QList<Entry> entries() const;
312 private:
314 QMultiHash<int,Entry> _entries; // entries in this keyboard translation,
315 // entries are indexed according to
316 // their keycode
317 QString _name;
318 QString _description;
320 Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States)
321 Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands)
323 /**
324 * Parses the contents of a Keyboard Translator (.keytab) file and
325 * returns the entries found in it.
327 * Usage example:
329 * @code
330 * QFile source( "/path/to/keytab" );
331 * source.open( QIODevice::ReadOnly );
333 * KeyboardTranslator* translator = new KeyboardTranslator( "name-of-translator" );
335 * KeyboardTranslatorReader reader(source);
336 * while ( reader.hasNextEntry() )
337 * translator->addEntry(reader.nextEntry());
339 * source.close();
341 * if ( !reader.parseError() )
343 * // parsing succeeded, do something with the translator
344 * }
345 * else
347 * // parsing failed
349 * @endcode
351 class KeyboardTranslatorReader
353 public:
354 /** Constructs a new reader which parses the given @p source */
355 KeyboardTranslatorReader( QIODevice* source );
357 /**
358 * Returns the description text.
359 * TODO: More documentation
361 QString description() const;
363 /** Returns true if there is another entry in the source stream */
364 bool hasNextEntry();
365 /** Returns the next entry found in the source stream */
366 KeyboardTranslator::Entry nextEntry();
368 /**
369 * Returns true if an error occurred whilst parsing the input or
370 * false if no error occurred.
372 bool parseError();
375 * Parses a condition and result string for a translator entry
376 * and produces a keyboard translator entry.
378 * The condition and result strings are in the same format as in
380 static KeyboardTranslator::Entry createEntry( const QString& condition ,
381 const QString& result );
382 private:
383 struct Token
385 enum Type
387 TitleKeyword,
388 TitleText,
389 KeyKeyword,
390 KeySequence,
391 Command,
392 OutputText
394 Type type;
395 QString text;
397 QList<Token> tokenize(const QString&);
398 void readNext();
399 bool decodeSequence(const QString& ,
400 int& keyCode,
401 Qt::KeyboardModifiers& modifiers,
402 Qt::KeyboardModifiers& modifierMask,
403 KeyboardTranslator::States& state,
404 KeyboardTranslator::States& stateFlags);
406 static bool parseAsModifier(const QString& item , Qt::KeyboardModifier& modifier);
407 static bool parseAsStateFlag(const QString& item , KeyboardTranslator::State& state);
408 static bool parseAsKeyCode(const QString& item , int& keyCode);
409 static bool parseAsCommand(const QString& text , KeyboardTranslator::Command& command);
411 QIODevice* _source;
412 QString _description;
413 KeyboardTranslator::Entry _nextEntry;
414 bool _hasNext;
417 /** Writes a keyboard translation to disk. */
418 class KeyboardTranslatorWriter
420 public:
421 /**
422 * Constructs a new writer which saves data into @p destination.
423 * The caller is responsible for closing the device when writing is complete.
425 KeyboardTranslatorWriter(QIODevice* destination);
426 ~KeyboardTranslatorWriter();
428 /**
429 * Writes the header for the keyboard translator.
430 * @param description Description of the keyboard translator.
432 void writeHeader( const QString& description );
433 /** Writes a translator entry. */
434 void writeEntry( const KeyboardTranslator::Entry& entry );
436 private:
437 QIODevice* _destination;
438 QTextStream* _writer;
442 * Manages the keyboard translations available for use by terminal sessions,
443 * see KeyboardTranslator.
445 class KDE_EXPORT KeyboardTranslatorManager
447 public:
448 /**
449 * Constructs a new KeyboardTranslatorManager and loads the list of
450 * available keyboard translations.
452 * The keyboard translations themselves are not loaded until they are
453 * first requested via a call to findTranslator()
455 KeyboardTranslatorManager();
456 ~KeyboardTranslatorManager();
459 * Adds a new translator. If a translator with the same name
460 * already exists, it will be replaced by the new translator.
462 * TODO: More documentation.
464 void addTranslator(KeyboardTranslator* translator);
467 * Deletes a translator. Returns true on successful deletion or false otherwise.
469 * TODO: More documentation
471 bool deleteTranslator(const QString& name);
473 /** Returns the default translator for Konsole. */
474 const KeyboardTranslator* defaultTranslator();
476 /**
477 * Returns the keyboard translator with the given name or 0 if no translator
478 * with that name exists.
480 * The first time that a translator with a particular name is requested,
481 * the on-disk .keyboard file is loaded and parsed.
483 const KeyboardTranslator* findTranslator(const QString& name);
485 * Returns a list of the names of available keyboard translators.
487 * The first time this is called, a search for available
488 * translators is started.
490 QList<QString> allTranslators();
492 /** Returns the global KeyboardTranslatorManager instance. */
493 static KeyboardTranslatorManager* instance();
495 private:
496 static const char* defaultTranslatorText;
498 void findTranslators(); // locate the available translators
499 KeyboardTranslator* loadTranslator(const QString& name); // loads the translator
500 // with the given name
501 KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name);
503 bool saveTranslator(const KeyboardTranslator* translator);
504 QString findTranslatorPath(const QString& name);
506 QHash<QString,KeyboardTranslator*> _translators; // maps translator-name -> KeyboardTranslator
507 // instance
508 bool _haveLoadedAll;
511 inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; }
512 inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; }
514 inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier )
516 _modifiers = modifier;
518 inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; }
520 inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask )
522 _modifierMask = mask;
524 inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; }
526 inline bool KeyboardTranslator::Entry::isNull() const
528 return ( *this == Entry() );
531 inline void KeyboardTranslator::Entry::setCommand( Command command )
533 _command = command;
535 inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; }
537 inline void KeyboardTranslator::Entry::setText( const QByteArray& text )
539 _text = unescape(text);
541 inline int oneOrZero(int value)
543 return value ? 1 : 0;
545 inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const
547 QByteArray expandedText = _text;
549 if (expandWildCards)
551 int modifierValue = 1;
552 modifierValue += oneOrZero(modifiers & Qt::ShiftModifier);
553 modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1;
554 modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2;
556 for (int i=0;i<_text.length();i++)
558 if (expandedText[i] == '*')
559 expandedText[i] = '0' + modifierValue;
563 return expandedText;
566 inline void KeyboardTranslator::Entry::setState( States state )
568 _state = state;
570 inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; }
572 inline void KeyboardTranslator::Entry::setStateMask( States stateMask )
574 _stateMask = stateMask;
576 inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; }
580 Q_DECLARE_METATYPE(Konsole::KeyboardTranslator::Entry)
581 Q_DECLARE_METATYPE(const Konsole::KeyboardTranslator*)
583 #endif // KEYBOARDTRANSLATOR_H