diff --git a/src/Character.h b/src/Character.h index b7e2702d..35dec93f 100644 --- a/src/Character.h +++ b/src/Character.h @@ -1,179 +1,179 @@ /* This file is part of Konsole, KDE's terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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. */ #ifndef CHARACTER_H #define CHARACTER_H // Konsole #include "CharacterColor.h" namespace Konsole { typedef unsigned char LineProperty; typedef quint16 RenditionFlags; const int LINE_DEFAULT = 0; const int LINE_WRAPPED = (1 << 0); const int LINE_DOUBLEWIDTH = (1 << 1); const int LINE_DOUBLEHEIGHT = (1 << 2); const RenditionFlags DEFAULT_RENDITION = 0; const RenditionFlags RE_BOLD = (1 << 0); const RenditionFlags RE_BLINK = (1 << 1); const RenditionFlags RE_UNDERLINE = (1 << 2); const RenditionFlags RE_REVERSE = (1 << 3); // Screen only const RenditionFlags RE_ITALIC = (1 << 4); const RenditionFlags RE_CURSOR = (1 << 5); const RenditionFlags RE_EXTENDED_CHAR = (1 << 6); const RenditionFlags RE_FAINT = (1 << 7); const RenditionFlags RE_STRIKEOUT = (1 << 8); const RenditionFlags RE_CONCEAL = (1 << 9); const RenditionFlags RE_OVERLINE = (1 << 10); /** * Unicode character in the range of U+2500 ~ U+257F are known as line * characters, or box-drawing characters. Currently, konsole draws those * characters itself, instead of using the glyph provided by the font. * Unfortunately, the triple and quadruple dash lines (┄┅┆┇┈┉┊┋) are too * detailed too be drawn cleanly at normal font scales without anti * -aliasing, so those are drawn as regular characters. */ -inline bool isSupportedLineChar(quint16 codePoint) +inline bool isSupportedLineChar(uint codePoint) { return (codePoint & 0xFF80) == 0x2500 // Unicode block: Mathematical Symbols - Box Drawing && !(0x2504 <= codePoint && codePoint <= 0x250B); // Triple and quadruple dash range } /** * A single character in the terminal which consists of a unicode character * value, foreground and background colors and a set of rendition attributes * which specify how it should be drawn. */ class Character { public: /** * Constructs a new character. * * @param _c The unicode character value of this character. * @param _f The foreground color used to draw the character. * @param _b The color used to draw the character's background. * @param _r A set of rendition flags which specify how this character * is to be drawn. * @param _real Indicate whether this character really exists, or exists * simply as place holder. */ - explicit inline Character(quint16 _c = ' ', + explicit inline Character(uint _c = ' ', CharacterColor _f = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), CharacterColor _b = CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), RenditionFlags _r = DEFAULT_RENDITION, bool _real = true) : character(_c) , rendition(_r) , foregroundColor(_f) , backgroundColor(_b) , isRealCharacter(_real) { } /** The unicode character value for this character. * * if RE_EXTENDED_CHAR is set, character is a hash code which can be used to * look up the unicode character sequence in the ExtendedCharTable used to * create the sequence. */ - quint16 character; + uint character; /** A combination of RENDITION flags which specify options for drawing the character. */ RenditionFlags rendition; /** The foreground color used to draw this character. */ CharacterColor foregroundColor; /** The color used to draw this character's background. */ CharacterColor backgroundColor; /** Indicate whether this character really exists, or exists simply as place holder. * * TODO: this boolean filed can be further improved to become a enum filed, which * indicates different roles: * * RealCharacter: a character which really exists * PlaceHolderCharacter: a character which exists as place holder * TabStopCharacter: a special place holder for HT("\t") */ bool isRealCharacter; /** * returns true if the format (color, rendition flag) of the compared characters is equal */ bool equalsFormat(const Character &other) const; /** * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ friend bool operator ==(const Character &a, const Character &b); /** * Compares two characters and returns true if they have different unicode character values, * renditions or colors. */ friend bool operator !=(const Character &a, const Character &b); inline bool isLineChar() const { if (rendition & RE_EXTENDED_CHAR) { return false; } else { return isSupportedLineChar(character); } } inline bool isSpace() const { if (rendition & RE_EXTENDED_CHAR) { return false; } else { return QChar(character).isSpace(); } } }; inline bool operator ==(const Character &a, const Character &b) { return a.character == b.character && a.equalsFormat(b); } inline bool operator !=(const Character &a, const Character &b) { return !operator==(a, b); } inline bool Character::equalsFormat(const Character &other) const { return backgroundColor == other.backgroundColor && foregroundColor == other.foregroundColor && rendition == other.rendition; } } Q_DECLARE_TYPEINFO(Konsole::Character, Q_MOVABLE_TYPE); #endif // CHARACTER_H diff --git a/src/Emulation.cpp b/src/Emulation.cpp index b1bc9050..4c620806 100644 --- a/src/Emulation.cpp +++ b/src/Emulation.cpp @@ -1,346 +1,346 @@ /* Copyright 2007-2008 Robert Knight Copyright 1997,1998 by Lars Doelle Copyright 1996 by Matthias Ettrich 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 "Emulation.h" // Qt #include // Konsole #include "KeyboardTranslator.h" #include "KeyboardTranslatorManager.h" #include "Screen.h" #include "ScreenWindow.h" using namespace Konsole; Emulation::Emulation() : _windows(QList()), _currentScreen(nullptr), _codec(nullptr), _decoder(nullptr), _keyTranslator(nullptr), _usesMouse(false), _bracketedPasteMode(false), _bulkTimer1(new QTimer(this)), _bulkTimer2(new QTimer(this)), _imageSizeInitialized(false) { // create screens with a default size _screen[0] = new Screen(40, 80); _screen[1] = new Screen(40, 80); _currentScreen = _screen[0]; QObject::connect(&_bulkTimer1, &QTimer::timeout, this, &Konsole::Emulation::showBulk); QObject::connect(&_bulkTimer2, &QTimer::timeout, this, &Konsole::Emulation::showBulk); // listen for mouse status changes connect(this, &Konsole::Emulation::programUsesMouseChanged, this, &Konsole::Emulation::usesMouseChanged); connect(this, &Konsole::Emulation::programBracketedPasteModeChanged, this, &Konsole::Emulation::bracketedPasteModeChanged); } bool Emulation::programUsesMouse() const { return _usesMouse; } void Emulation::usesMouseChanged(bool usesMouse) { _usesMouse = usesMouse; } bool Emulation::programBracketedPasteMode() const { return _bracketedPasteMode; } void Emulation::bracketedPasteModeChanged(bool bracketedPasteMode) { _bracketedPasteMode = bracketedPasteMode; } ScreenWindow *Emulation::createWindow() { auto window = new ScreenWindow(_currentScreen); _windows << window; connect(window, &Konsole::ScreenWindow::selectionChanged, this, &Konsole::Emulation::bufferedUpdate); connect(window, &Konsole::ScreenWindow::selectionChanged, this, &Konsole::Emulation::checkSelectedText); connect(this, &Konsole::Emulation::outputChanged, window, &Konsole::ScreenWindow::notifyOutputChanged); return window; } void Emulation::checkScreenInUse() { emit primaryScreenInUse(_currentScreen == _screen[0]); } void Emulation::checkSelectedText() { QString text = _currentScreen->selectedText(Screen::PreserveLineBreaks); emit selectionChanged(text); } Emulation::~Emulation() { foreach (ScreenWindow *window, _windows) { delete window; } delete _screen[0]; delete _screen[1]; delete _decoder; } void Emulation::setScreen(int index) { Screen *oldScreen = _currentScreen; _currentScreen = _screen[index & 1]; if (_currentScreen != oldScreen) { // tell all windows onto this emulation to switch to the newly active screen foreach (ScreenWindow *window, _windows) { window->setScreen(_currentScreen); } checkScreenInUse(); checkSelectedText(); } } void Emulation::clearHistory() { _screen[0]->setScroll(_screen[0]->getScroll(), false); } void Emulation::setHistory(const HistoryType &history) { _screen[0]->setScroll(history); showBulk(); } const HistoryType &Emulation::history() const { return _screen[0]->getScroll(); } void Emulation::setCodec(const QTextCodec *codec) { if (codec != nullptr) { _codec = codec; delete _decoder; _decoder = _codec->makeDecoder(); emit useUtf8Request(utf8()); } else { setCodec(LocaleCodec); } } void Emulation::setCodec(EmulationCodec codec) { if (codec == Utf8Codec) { setCodec(QTextCodec::codecForName("utf8")); } else if (codec == LocaleCodec) { setCodec(QTextCodec::codecForLocale()); } } void Emulation::setKeyBindings(const QString &name) { _keyTranslator = KeyboardTranslatorManager::instance()->findTranslator(name); if (_keyTranslator == nullptr) { _keyTranslator = KeyboardTranslatorManager::instance()->defaultTranslator(); } } QString Emulation::keyBindings() const { return _keyTranslator->name(); } // process application unicode input to terminal // this is a trivial scanner -void Emulation::receiveChar(int c) +void Emulation::receiveChar(uint c) { c &= 0xff; switch (c) { case '\b': _currentScreen->backspace(); break; case '\t': _currentScreen->tab(); break; case '\n': _currentScreen->newLine(); break; case '\r': _currentScreen->toStartOfLine(); break; case 0x07: emit stateSet(NOTIFYBELL); break; default: - _currentScreen->displayCharacter(static_cast(c)); + _currentScreen->displayCharacter(c); break; } } void Emulation::sendKeyEvent(QKeyEvent *ev) { emit stateSet(NOTIFYNORMAL); if (!ev->text().isEmpty()) { // A block of text // Note that the text is proper unicode. // We should do a conversion here emit sendData(ev->text().toLocal8Bit()); } } void Emulation::sendMouseEvent(int /*buttons*/, int /*column*/, int /*row*/, int /*eventType*/) { // default implementation does nothing } /* We are doing code conversion from locale to unicode first. */ void Emulation::receiveData(const char *text, int length) { emit stateSet(NOTIFYACTIVITY); bufferedUpdate(); - QString unicodeText = _decoder->toUnicode(text, length); + QVector unicodeText = _decoder->toUnicode(text, length).toUcs4(); //send characters to terminal emulator for (auto &&i : unicodeText) { - receiveChar(i.unicode()); + receiveChar(i); } //look for z-modem indicator //-- someone who understands more about z-modems that I do may be able to move //this check into the above for loop? for (int i = 0; i < length; i++) { if (text[i] == '\030') { if (length - i - 1 > 3) { if (qstrncmp(text + i + 1, "B00", 3) == 0) { emit zmodemDownloadDetected(); } else if (qstrncmp(text + i + 1, "B01", 3) == 0) { emit zmodemUploadDetected(); } } } } } void Emulation::writeToStream(TerminalCharacterDecoder *decoder, int startLine, int endLine) { _currentScreen->writeLinesToStream(decoder, startLine, endLine); } int Emulation::lineCount() const { // sum number of lines currently on _screen plus number of lines in history return _currentScreen->getLines() + _currentScreen->getHistLines(); } void Emulation::showBulk() { _bulkTimer1.stop(); _bulkTimer2.stop(); emit outputChanged(); _currentScreen->resetScrolledLines(); _currentScreen->resetDroppedLines(); } void Emulation::bufferedUpdate() { static const int BULK_TIMEOUT1 = 10; static const int BULK_TIMEOUT2 = 40; _bulkTimer1.setSingleShot(true); _bulkTimer1.start(BULK_TIMEOUT1); if (!_bulkTimer2.isActive()) { _bulkTimer2.setSingleShot(true); _bulkTimer2.start(BULK_TIMEOUT2); } } char Emulation::eraseChar() const { return '\b'; } void Emulation::setImageSize(int lines, int columns) { if ((lines < 1) || (columns < 1)) { return; } QSize screenSize[2] = { QSize(_screen[0]->getColumns(), _screen[0]->getLines()), QSize(_screen[1]->getColumns(), _screen[1]->getLines()) }; QSize newSize(columns, lines); if (newSize == screenSize[0] && newSize == screenSize[1]) { // If this method is called for the first time, always emit // SIGNAL(imageSizeChange()), even if the new size is the same as the // current size. See #176902 if (!_imageSizeInitialized) { emit imageSizeChanged(lines, columns); } } else { _screen[0]->resizeImage(lines, columns); _screen[1]->resizeImage(lines, columns); emit imageSizeChanged(lines, columns); bufferedUpdate(); } if (!_imageSizeInitialized) { _imageSizeInitialized = true; emit imageSizeInitialized(); } } QSize Emulation::imageSize() const { return QSize(_currentScreen->getColumns(), _currentScreen->getLines()); } diff --git a/src/Emulation.h b/src/Emulation.h index 73087ead..37aee533 100644 --- a/src/Emulation.h +++ b/src/Emulation.h @@ -1,522 +1,522 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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. */ #ifndef EMULATION_H #define EMULATION_H // Qt #include #include #include // Konsole #include "Enumeration.h" #include "konsoleprivate_export.h" class QKeyEvent; namespace Konsole { class KeyboardTranslator; class HistoryType; class Screen; class ScreenWindow; class TerminalCharacterDecoder; /** * This enum describes the available states which * the terminal emulation may be set to. * * These are the values used by Emulation::stateChanged() */ enum { /** The emulation is currently receiving user input. */ NOTIFYNORMAL = 0, /** * The terminal program has triggered a bell event * to get the user's attention. */ NOTIFYBELL = 1, /** * The emulation is currently receiving data from its * terminal input. */ NOTIFYACTIVITY = 2, // unused here? NOTIFYSILENCE = 3 }; /** * Base class for terminal emulation back-ends. * * The back-end is responsible for decoding an incoming character stream and * producing an output image of characters. * * When input from the terminal is received, the receiveData() slot should be called with * the data which has arrived. The emulation will process the data and update the * screen image accordingly. The codec used to decode the incoming character stream * into the unicode characters used internally can be specified using setCodec() * * The size of the screen image can be specified by calling setImageSize() with the * desired number of lines and columns. When new lines are added, old content * is moved into a history store, which can be set by calling setHistory(). * * The screen image can be accessed by creating a ScreenWindow onto this emulation * by calling createWindow(). Screen windows provide access to a section of the * output. Each screen window covers the same number of lines and columns as the * image size returned by imageSize(). The screen window can be moved up and down * and provides transparent access to both the current on-screen image and the * previous output. The screen windows emit an outputChanged signal * when the section of the image they are looking at changes. * Graphical views can then render the contents of a screen window, listening for notifications * of output changes from the screen window which they are associated with and updating * accordingly. * * The emulation also is also responsible for converting input from the connected views such * as keypresses and mouse activity into a character string which can be sent * to the terminal program. Key presses can be processed by calling the sendKeyEvent() slot, * while mouse events can be processed using the sendMouseEvent() slot. When the character * stream has been produced, the emulation will emit a sendData() signal with a pointer * to the character buffer. This data should be fed to the standard input of the terminal * process. The translation of key presses into an output character stream is performed * using a lookup in a set of key bindings which map key sequences to output * character sequences. The name of the key bindings set used can be specified using * setKeyBindings() * * The emulation maintains certain state information which changes depending on the * input received. The emulation can be reset back to its starting state by calling * reset(). * * The emulation also maintains an activity state, which specifies whether * terminal is currently active ( when data is received ), normal * ( when the terminal is idle or receiving user input ) or trying * to alert the user ( also known as a "Bell" event ). The stateSet() signal * is emitted whenever the activity state is set. This can be used to determine * how long the emulation has been active/idle for and also respond to * a 'bell' event in different ways. */ class KONSOLEPRIVATE_EXPORT Emulation : public QObject { Q_OBJECT public: /** Constructs a new terminal emulation */ Emulation(); ~Emulation() Q_DECL_OVERRIDE; /** * Creates a new window onto the output from this emulation. The contents * of the window are then rendered by views which are set to use this window using the * TerminalDisplay::setScreenWindow() method. */ ScreenWindow *createWindow(); /** Returns the size of the screen image which the emulation produces */ QSize imageSize() const; /** * Returns the total number of lines, including those stored in the history. */ int lineCount() const; /** * Sets the history store used by this emulation. When new lines * are added to the output, older lines at the top of the screen are transferred to a history * store. * * The number of lines which are kept and the storage location depend on the * type of store. */ void setHistory(const HistoryType &); /** Returns the history store used by this emulation. See setHistory() */ const HistoryType &history() const; /** Clears the history scroll. */ void clearHistory(); /** * Copies the output history from @p startLine to @p endLine * into @p stream, using @p decoder to convert the terminal * characters into text. * * @param decoder A decoder which converts lines of terminal characters with * appearance attributes into output text. PlainTextDecoder is the most commonly * used decoder. * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ virtual void writeToStream(TerminalCharacterDecoder *decoder, int startLine, int endLine); /** Returns the codec used to decode incoming characters. See setCodec() */ const QTextCodec *codec() const { return _codec; } /** Sets the codec used to decode incoming characters. */ void setCodec(const QTextCodec *); /** * Convenience method. * Returns true if the current codec used to decode incoming * characters is UTF-8 */ bool utf8() const { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } /** Returns the special character used for erasing character. */ virtual char eraseChar() const; /** * Sets the key bindings used to key events * ( received through sendKeyEvent() ) into character * streams to send to the terminal. */ void setKeyBindings(const QString &name); /** * Returns the name of the emulation's current key bindings. * See setKeyBindings() */ QString keyBindings() const; /** * Copies the current image into the history and clears the screen. */ virtual void clearEntireScreen() = 0; /** Resets the state of the terminal. */ virtual void reset() = 0; /** * Returns true if the active terminal program wants * mouse input events. * * The programUsesMouseChanged() signal is emitted when this * changes. */ bool programUsesMouse() const; bool programBracketedPasteMode() const; public Q_SLOTS: /** Change the size of the emulation's image */ virtual void setImageSize(int lines, int columns); /** * Interprets a sequence of characters and sends the result to the terminal. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. */ virtual void sendText(const QString &text) = 0; /** * Interprets a key press event and emits the sendData() signal with * the resulting character stream. */ virtual void sendKeyEvent(QKeyEvent *); /** * Converts information about a mouse event into an xterm-compatible escape * sequence and emits the character sequence via sendData() */ virtual void sendMouseEvent(int buttons, int column, int line, int eventType); /** * Sends a string of characters to the foreground terminal process. * * @param string The characters to send. */ virtual void sendString(const QByteArray &string) = 0; /** * Processes an incoming stream of characters. receiveData() decodes the incoming * character buffer using the current codec(), and then calls receiveChar() for * each unicode character in the resulting buffer. * * receiveData() also starts a timer which causes the outputChanged() signal * to be emitted when it expires. The timer allows multiple updates in quick * succession to be buffered into a single outputChanged() signal emission. * * @param text A string of characters received from the terminal program. * @param length The length of @p text */ void receiveData(const char *text, int length); /** * Sends information about the focus lost event to the terminal. */ virtual void focusLost() = 0; /** * Sends information about the focus gained event to the terminal. */ virtual void focusGained() = 0; Q_SIGNALS: /** * Emitted when a buffer of data is ready to send to the * standard input of the terminal. * * @param data The buffer of data ready to be sent */ void sendData(const QByteArray &data); /** * Requests that the pty used by the terminal process * be set to UTF 8 mode. * * Refer to the IUTF8 entry in termios(3) for more information. */ void useUtf8Request(bool); /** * Emitted when the activity state of the emulation is set. * * @param state The new activity state, one of NOTIFYNORMAL, NOTIFYACTIVITY * or NOTIFYBELL */ void stateSet(int state); /** * Emitted when the special sequence indicating the request for data * transmission through ZModem protocol is detected. */ void zmodemDownloadDetected(); void zmodemUploadDetected(); /** * Requests that the color of the text used * to represent the tabs associated with this * emulation be changed. This is a Konsole-specific * extension from pre-KDE 4 times. * * TODO: Document how the parameter works. */ void changeTabTextColorRequest(int color); /** * This is emitted when the program running in the shell indicates whether or * not it is interested in mouse events. * * @param usesMouse This will be true if the program wants to be informed about * mouse events or false otherwise. */ void programUsesMouseChanged(bool usesMouse); void enableAlternateScrolling(bool enable); void programBracketedPasteModeChanged(bool bracketedPasteMode); /** * Emitted when the contents of the screen image change. * The emulation buffers the updates from successive image changes, * and only emits outputChanged() at sensible intervals when * there is a lot of terminal activity. * * Normally there is no need for objects other than the screen windows * created with createWindow() to listen for this signal. * * ScreenWindow objects created using createWindow() will emit their * own outputChanged() signal in response to this signal. */ void outputChanged(); /** * Emitted when the program running in the terminal wishes to update the * session's title. This also allows terminal programs to customize other * aspects of the terminal emulation display. * * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" * is received in the input string, where ARG is a number specifying what * should change and VALUE is a string specifying the new value. * * TODO: The name of this method is not very accurate since this method * is used to perform a whole range of tasks besides just setting * the user-title of the session. * * @param title Specifies what to change. *
    *
  • 0 - Set window icon text and session title to @p newTitle
  • *
  • 1 - Set window icon text to @p newTitle
  • *
  • 2 - Set session title to @p newTitle
  • *
  • 11 - Set the session's default background color to @p newTitle, * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named * color (eg 'red', 'blue'). * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more * details. *
  • *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • *
  • 32 - Sets the icon associated with the session. @p newTitle is the name * of the icon to use, which can be the name of any icon in the current KDE icon * theme (eg: 'konsole', 'kate', 'folder_home')
  • *
* @param newTitle Specifies the new title */ void titleChanged(int title, const QString &newTitle); /** * Emitted when the terminal emulator's size has changed */ void imageSizeChanged(int lineCount, int columnCount); /** * Emitted when the setImageSize() is called on this emulation for * the first time. */ void imageSizeInitialized(); /** * Emitted after receiving the escape sequence which asks to change * the terminal emulator's size */ void imageResizeRequest(const QSize &sizz); /** * Emitted when the terminal program requests to change various properties * of the terminal display. * * A profile change command occurs when a special escape sequence, followed * by a string containing a series of name and value pairs is received. * This string can be parsed using a ProfileCommandParser instance. * * @param text A string expected to contain a series of key and value pairs in * the form: name=value;name2=value2 ... */ void profileChangeCommandReceived(const QString &text); /** * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to * resume output. */ void flowControlKeyPressed(bool suspendKeyPressed); /** * Emitted when the active screen is switched, to indicate whether the primary * screen is in use. */ void primaryScreenInUse(bool use); /** * Emitted when the text selection is changed */ void selectionChanged(const QString &text); /** * Emitted when terminal code requiring terminal's response received. */ void sessionAttributeRequest(int id); /** * Emitted when Set Cursor Style (DECSCUSR) escape sequences are sent * to the terminal. * @p shape cursor shape * @p isBlinking if true, the cursor will be set to blink */ void setCursorStyleRequest(Enum::CursorShapeEnum shape = Enum::BlockCursor, bool isBlinking = false); /** * Emitted when reset() is called to reset the cursor style to the * current profile cursor shape and blinking settings. */ void resetCursorStyleRequest(); protected: virtual void setMode(int mode) = 0; virtual void resetMode(int mode) = 0; /** * Processes an incoming character. See receiveData() * @p c A unicode character code. */ - virtual void receiveChar(int c); + virtual void receiveChar(uint c); /** * Sets the active screen. The terminal has two screens, primary and alternate. * The primary screen is used by default. When certain interactive programs such * as Vim are run, they trigger a switch to the alternate screen. * * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen */ void setScreen(int index); enum EmulationCodec { LocaleCodec = 0, Utf8Codec = 1 }; void setCodec(EmulationCodec codec); QList _windows; Screen *_currentScreen; // pointer to the screen which is currently active, // this is one of the elements in the screen[] array Screen *_screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) //decodes an incoming C-style character stream into a unicode QString using //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) const QTextCodec *_codec; QTextDecoder *_decoder; const KeyboardTranslator *_keyTranslator; // the keyboard layout protected Q_SLOTS: /** * Schedules an update of attached views. * Repeated calls to bufferedUpdate() in close succession will result in only a single update, * much like the Qt buffered update of widgets. */ void bufferedUpdate(); // used to emit the primaryScreenInUse(bool) signal void checkScreenInUse(); // used to emit the selectionChanged(QString) signal void checkSelectedText(); private Q_SLOTS: // triggered by timer, causes the emulation to send an updated screen image to each // view void showBulk(); void usesMouseChanged(bool usesMouse); void bracketedPasteModeChanged(bool bracketedPasteMode); private: Q_DISABLE_COPY(Emulation) bool _usesMouse; bool _bracketedPasteMode; QTimer _bulkTimer1; QTimer _bulkTimer2; bool _imageSizeInitialized; }; } #endif // ifndef EMULATION_H diff --git a/src/ExtendedCharTable.cpp b/src/ExtendedCharTable.cpp index 7eaf35b9..181eca60 100644 --- a/src/ExtendedCharTable.cpp +++ b/src/ExtendedCharTable.cpp @@ -1,156 +1,156 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight 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 "ExtendedCharTable.h" #include "konsoledebug.h" // Konsole #include "TerminalDisplay.h" #include "SessionManager.h" #include "Session.h" #include "Screen.h" using namespace Konsole; ExtendedCharTable::ExtendedCharTable() : - _extendedCharTable(QHash()) + _extendedCharTable(QHash()) { } ExtendedCharTable::~ExtendedCharTable() { // free all allocated character buffers - QHashIterator iter(_extendedCharTable); + QHashIterator iter(_extendedCharTable); while (iter.hasNext()) { iter.next(); delete[] iter.value(); } } // global instance ExtendedCharTable ExtendedCharTable::instance; -ushort ExtendedCharTable::createExtendedChar(const ushort *unicodePoints, ushort length) +uint ExtendedCharTable::createExtendedChar(const uint *unicodePoints, ushort length) { // look for this sequence of points in the table - ushort hash = extendedCharHash(unicodePoints, length); - const ushort initialHash = hash; + uint hash = extendedCharHash(unicodePoints, length); + const uint initialHash = hash; bool triedCleaningSolution = false; // check existing entry for match while (_extendedCharTable.contains(hash) && hash != 0) { // 0 has a special meaning for chars so we don't use it if (extendedCharMatch(hash, unicodePoints, length)) { // this sequence already has an entry in the table, // return its hash return hash; } else { // if hash is already used by another, different sequence of unicode character // points then try next hash hash++; if (hash == initialHash) { if (!triedCleaningSolution) { triedCleaningSolution = true; // All the hashes are full, go to all Screens and try to free any // This is slow but should happen very rarely - QSet usedExtendedChars; + QSet usedExtendedChars; const SessionManager *sm = SessionManager::instance(); foreach (const Session *s, sm->sessions()) { foreach (const TerminalDisplay *td, s->views()) { usedExtendedChars += td->screenWindow()->screen()->usedExtendedChars(); } } - QHash::iterator it = _extendedCharTable.begin(); - QHash::iterator itEnd = _extendedCharTable.end(); + QHash::iterator it = _extendedCharTable.begin(); + QHash::iterator itEnd = _extendedCharTable.end(); while (it != itEnd) { if (usedExtendedChars.contains(it.key())) { ++it; } else { it = _extendedCharTable.erase(it); } } } else { qCDebug(KonsoleDebug) << "Using all the extended char hashes, going to miss this extended character"; return 0; } } } } // add the new sequence to the table and // return that index - auto buffer = new ushort[length + 1]; + auto buffer = new uint[length + 1]; buffer[0] = length; for (int i = 0; i < length; i++) { buffer[i + 1] = unicodePoints[i]; } _extendedCharTable.insert(hash, buffer); return hash; } -ushort *ExtendedCharTable::lookupExtendedChar(ushort hash, ushort &length) const +uint *ExtendedCharTable::lookupExtendedChar(uint hash, ushort &length) const { // look up index in table and if found, set the length // argument and return a pointer to the character sequence - ushort *buffer = _extendedCharTable[hash]; + uint *buffer = _extendedCharTable[hash]; if (buffer != nullptr) { - length = buffer[0]; + length = ushort(buffer[0]); return buffer + 1; } else { length = 0; return nullptr; } } -ushort ExtendedCharTable::extendedCharHash(const ushort *unicodePoints, ushort length) const +uint ExtendedCharTable::extendedCharHash(const uint *unicodePoints, ushort length) const { - ushort hash = 0; + uint hash = 0; for (ushort i = 0; i < length; i++) { hash = 31 * hash + unicodePoints[i]; } return hash; } -bool ExtendedCharTable::extendedCharMatch(ushort hash, const ushort *unicodePoints, +bool ExtendedCharTable::extendedCharMatch(uint hash, const uint *unicodePoints, ushort length) const { - ushort *entry = _extendedCharTable[hash]; + uint *entry = _extendedCharTable[hash]; // compare given length with stored sequence length ( given as the first ushort in the // stored buffer ) if (entry == nullptr || entry[0] != length) { return false; } // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] for (int i = 0; i < length; i++) { if (entry[i + 1] != unicodePoints[i]) { return false; } } return true; } diff --git a/src/ExtendedCharTable.h b/src/ExtendedCharTable.h index 90382b75..ce78a2e7 100644 --- a/src/ExtendedCharTable.h +++ b/src/ExtendedCharTable.h @@ -1,80 +1,80 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight 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. */ #ifndef EXTENDEDCHARTABLE_H #define EXTENDEDCHARTABLE_H // Qt #include namespace Konsole { /** * A table which stores sequences of unicode characters, referenced * by hash keys. The hash key itself is the same size as a unicode - * character ( ushort ) so that it can occupy the same space in + * character ( uint ) so that it can occupy the same space in * a structure. */ class ExtendedCharTable { public: /** Constructs a new character table. */ ExtendedCharTable(); ~ExtendedCharTable(); /** * Adds a sequences of unicode characters to the table and returns * a hash code which can be used later to look up the sequence * using lookupExtendedChar() * * If the same sequence already exists in the table, the hash * of the existing sequence will be returned. * * @param unicodePoints An array of unicode character points * @param length Length of @p unicodePoints */ - ushort createExtendedChar(const ushort *unicodePoints, ushort length); + uint createExtendedChar(const uint *unicodePoints, ushort length); /** * Looks up and returns a pointer to a sequence of unicode characters * which was added to the table using createExtendedChar(). * * @param hash The hash key returned by createExtendedChar() * @param length This variable is set to the length of the * character sequence. * * @return A unicode character sequence of size @p length. */ - ushort *lookupExtendedChar(ushort hash, ushort &length) const; + uint *lookupExtendedChar(uint hash, ushort &length) const; /** The global ExtendedCharTable instance. */ static ExtendedCharTable instance; private: // calculates the hash key of a sequence of unicode points of size 'length' - ushort extendedCharHash(const ushort *unicodePoints, ushort length) const; + uint extendedCharHash(const uint *unicodePoints, ushort length) const; // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' - bool extendedCharMatch(ushort hash, const ushort *unicodePoints, ushort length) const; - // internal, maps hash keys to character sequence buffers. The first ushort - // in each value is the length of the buffer, followed by the ushorts in the buffer + bool extendedCharMatch(uint hash, const uint *unicodePoints, ushort length) const; + // internal, maps hash keys to character sequence buffers. The first uint + // in each value is the length of the buffer, followed by the uints in the buffer // themselves. - QHash _extendedCharTable; + QHash _extendedCharTable; }; } #endif // end of EXTENDEDCHARTABLE_H diff --git a/src/History.cpp b/src/History.cpp index 545680aa..fa8cfd19 100644 --- a/src/History.cpp +++ b/src/History.cpp @@ -1,710 +1,710 @@ /* This file is part of Konsole, an X terminal. Copyright 1997,1998 by Lars Doelle 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 "History.h" #include "konsoledebug.h" #include "KonsoleSettings.h" // System #include #include #include #include // KDE #include #include #include #include #include // Reasonable line size static const int LINE_SIZE = 1024; using namespace Konsole; Q_GLOBAL_STATIC(QString, historyFileLocation) /* An arbitrary long scroll. One can modify the scroll only by adding either cells or newlines, but access it randomly. The model is that of an arbitrary wide typewriter scroll in that the scroll is a series of lines and each line is a series of cells with no overwriting permitted. The implementation provides arbitrary length and numbers of cells and line/column indexed read access to the scroll at constant costs. */ // History File /////////////////////////////////////////// HistoryFile::HistoryFile() : _length(0), _fileMap(nullptr), _readWriteBalance(0) { // Determine the temp directory once // This class is called 3 times for each "unlimited" scrollback. // This has the down-side that users must restart to // load changes. if (!historyFileLocation.exists()) { QString fileLocation; KSharedConfigPtr appConfig = KSharedConfig::openConfig(); if (qApp->applicationName() != QLatin1String("konsole")) { // Check if "kpart"rc has "FileLocation" group; AFAIK // only possible if user manually added it. If not // found, use konsole's config. if (!appConfig->hasGroup("FileLocation")) { appConfig = KSharedConfig::openConfig(QStringLiteral("konsolerc")); } } KConfigGroup configGroup = appConfig->group("FileLocation"); if (configGroup.readEntry("scrollbackUseCacheLocation", false)) { fileLocation = QStandardPaths::writableLocation(QStandardPaths::CacheLocation); } else if (configGroup.readEntry("scrollbackUseSpecifiedLocation", false)) { const QUrl specifiedUrl = KonsoleSettings::scrollbackUseSpecifiedLocationDirectory(); fileLocation = specifiedUrl.path(); } else { fileLocation = QDir::tempPath(); } // Validate file location const QFileInfo fi(fileLocation); if (fileLocation.isEmpty() || !fi.exists() || !fi.isDir() || !fi.isWritable()) { qCWarning(KonsoleDebug)<<"Invalid scrollback folder "<= _length); _fileMap = _tmpFile.map(0, _length); } //if mmap'ing fails, fall back to the read-lseek combination if (_fileMap == nullptr) { _readWriteBalance = 0; qCDebug(KonsoleDebug) << "mmap'ing history failed. errno = " << errno; } } void HistoryFile::unmap() { Q_ASSERT(_fileMap != nullptr); if (_tmpFile.unmap(_fileMap)) { _fileMap = nullptr; } Q_ASSERT(_fileMap == nullptr); } bool HistoryFile::isMapped() const { return _fileMap != nullptr; } void HistoryFile::add(const char *buffer, qint64 count) { if (_fileMap != nullptr) { unmap(); } if (_readWriteBalance < INT_MAX) { _readWriteBalance++; } qint64 rc = 0; if (!_tmpFile.seek(_length)) { perror("HistoryFile::add.seek"); return; } rc = _tmpFile.write(buffer, count); if (rc < 0) { perror("HistoryFile::add.write"); return; } _length += rc; } void HistoryFile::get(char *buffer, qint64 size, qint64 loc) { if (loc < 0 || size < 0 || loc + size > _length) { fprintf(stderr, "getHist(...,%lld,%lld): invalid args.\n", size, loc); return; } //count number of get() calls vs. number of add() calls. //If there are many more get() calls compared with add() //calls (decided by using MAP_THRESHOLD) then mmap the log //file to improve performance. if (_readWriteBalance > INT_MIN) { _readWriteBalance--; } if ((_fileMap == nullptr) && _readWriteBalance < MAP_THRESHOLD) { map(); } if (_fileMap != nullptr) { memcpy(buffer, _fileMap + loc, size); } else { qint64 rc = 0; if (!_tmpFile.seek(loc)) { perror("HistoryFile::get.seek"); return; } rc = _tmpFile.read(buffer, size); if (rc < 0) { perror("HistoryFile::get.read"); return; } } } qint64 HistoryFile::len() const { return _length; } // History Scroll abstract base class ////////////////////////////////////// HistoryScroll::HistoryScroll(HistoryType *t) : _historyType(t) { } HistoryScroll::~HistoryScroll() { delete _historyType; } bool HistoryScroll::hasScroll() { return true; } // History Scroll File ////////////////////////////////////// /* The history scroll makes a Row(Row(Cell)) from two history buffers. The index buffer contains start of line positions which refer to the cells buffer. Note that index[0] addresses the second line (line #1), while the first line (line #0) starts at 0 in cells. */ HistoryScrollFile::HistoryScrollFile(const QString &logFileName) : HistoryScroll(new HistoryTypeFile(logFileName)) { } HistoryScrollFile::~HistoryScrollFile() = default; int HistoryScrollFile::getLines() { return _index.len() / sizeof(qint64); } int HistoryScrollFile::getLineLen(int lineno) { return (startOfLine(lineno + 1) - startOfLine(lineno)) / sizeof(Character); } bool HistoryScrollFile::isWrappedLine(int lineno) { if (lineno >= 0 && lineno <= getLines()) { unsigned char flag = 0; _lineflags.get(reinterpret_cast(&flag), sizeof(unsigned char), (lineno)*sizeof(unsigned char)); return flag != 0u; } return false; } qint64 HistoryScrollFile::startOfLine(int lineno) { if (lineno <= 0) { return 0; } if (lineno <= getLines()) { qint64 res = 0; _index.get(reinterpret_cast(&res), sizeof(qint64), (lineno - 1)*sizeof(qint64)); return res; } return _cells.len(); } void HistoryScrollFile::getCells(int lineno, int colno, int count, Character res[]) { _cells.get(reinterpret_cast(res), count * sizeof(Character), startOfLine(lineno) + colno * sizeof(Character)); } void HistoryScrollFile::addCells(const Character text[], int count) { _cells.add(reinterpret_cast(text), count * sizeof(Character)); } void HistoryScrollFile::addLine(bool previousWrapped) { qint64 locn = _cells.len(); _index.add(reinterpret_cast(&locn), sizeof(qint64)); unsigned char flags = previousWrapped ? 0x01 : 0x00; _lineflags.add(reinterpret_cast(&flags), sizeof(char)); } // History Scroll None ////////////////////////////////////// HistoryScrollNone::HistoryScrollNone() : HistoryScroll(new HistoryTypeNone()) { } HistoryScrollNone::~HistoryScrollNone() = default; bool HistoryScrollNone::hasScroll() { return false; } int HistoryScrollNone::getLines() { return 0; } int HistoryScrollNone::getLineLen(int) { return 0; } bool HistoryScrollNone::isWrappedLine(int /*lineno*/) { return false; } void HistoryScrollNone::getCells(int, int, int, Character []) { } void HistoryScrollNone::addCells(const Character [], int) { } void HistoryScrollNone::addLine(bool) { } //////////////////////////////////////////////////////////////// // Compact History Scroll ////////////////////////////////////// //////////////////////////////////////////////////////////////// void *CompactHistoryBlock::allocate(size_t size) { Q_ASSERT(size > 0); if (_tail - _blockStart + size > _blockLength) { return nullptr; } void *block = _tail; _tail += size; ////qDebug() << "allocated " << length << " bytes at address " << block; _allocCount++; return block; } void CompactHistoryBlock::deallocate() { _allocCount--; Q_ASSERT(_allocCount >= 0); } void *CompactHistoryBlockList::allocate(size_t size) { CompactHistoryBlock *block; if (list.isEmpty() || list.last()->remaining() < size) { block = new CompactHistoryBlock(); list.append(block); ////qDebug() << "new block created, remaining " << block->remaining() << "number of blocks=" << list.size(); } else { block = list.last(); ////qDebug() << "old block used, remaining " << block->remaining(); } return block->allocate(size); } void CompactHistoryBlockList::deallocate(void *ptr) { Q_ASSERT(!list.isEmpty()); int i = 0; CompactHistoryBlock *block = list.at(i); while (i < list.size() && !block->contains(ptr)) { i++; block = list.at(i); } Q_ASSERT(i < list.size()); block->deallocate(); if (!block->isInUse()) { list.removeAt(i); delete block; ////qDebug() << "block deleted, new size = " << list.size(); } } CompactHistoryBlockList::~CompactHistoryBlockList() { qDeleteAll(list.begin(), list.end()); list.clear(); } void *CompactHistoryLine::operator new(size_t size, CompactHistoryBlockList &blockList) { return blockList.allocate(size); } CompactHistoryLine::CompactHistoryLine(const TextLine &line, CompactHistoryBlockList &bList) : _blockListRef(bList), _formatArray(nullptr), _text(nullptr), _formatLength(0), _wrapped(false) { _length = line.size(); if (line.size() > 0) { _formatLength = 1; int k = 1; // count number of different formats in this text line Character c = line[0]; while (k < _length) { if (!(line[k].equalsFormat(c))) { _formatLength++; // format change detected c = line[k]; } k++; } ////qDebug() << "number of different formats in string: " << _formatLength; _formatArray = static_cast(_blockListRef.allocate(sizeof(CharacterFormat) * _formatLength)); Q_ASSERT(_formatArray != nullptr); - _text = static_cast(_blockListRef.allocate(sizeof(quint16) * line.size())); + _text = static_cast(_blockListRef.allocate(sizeof(uint) * line.size())); Q_ASSERT(_text != nullptr); _length = line.size(); _wrapped = false; // record formats and their positions in the format array c = line[0]; _formatArray[0].setFormat(c); _formatArray[0].startPos = 0; // there's always at least 1 format (for the entire line, unless a change happens) k = 1; // look for possible format changes int j = 1; while (k < _length && j < _formatLength) { if (!(line[k].equalsFormat(c))) { c = line[k]; _formatArray[j].setFormat(c); _formatArray[j].startPos = k; ////qDebug() << "format entry " << j << " at pos " << _formatArray[j].startPos << " " << &(_formatArray[j].startPos) ; j++; } k++; } // copy character values for (int i = 0; i < line.size(); i++) { _text[i] = line[i].character; ////qDebug() << "char " << i << " at mem " << &(text[i]); } } ////qDebug() << "line created, length " << length << " at " << &(length); } CompactHistoryLine::~CompactHistoryLine() { if (_length > 0) { _blockListRef.deallocate(_text); _blockListRef.deallocate(_formatArray); } _blockListRef.deallocate(this); } void CompactHistoryLine::getCharacter(int index, Character &r) { Q_ASSERT(index < _length); int formatPos = 0; while ((formatPos + 1) < _formatLength && index >= _formatArray[formatPos + 1].startPos) { formatPos++; } r.character = _text[index]; r.rendition = _formatArray[formatPos].rendition; r.foregroundColor = _formatArray[formatPos].fgColor; r.backgroundColor = _formatArray[formatPos].bgColor; r.isRealCharacter = _formatArray[formatPos].isRealCharacter; } void CompactHistoryLine::getCharacters(Character *array, int size, int startColumn) { Q_ASSERT(startColumn >= 0 && size >= 0); Q_ASSERT(startColumn + size <= static_cast(getLength())); for (int i = startColumn; i < size + startColumn; i++) { getCharacter(i, array[i - startColumn]); } } CompactHistoryScroll::CompactHistoryScroll(unsigned int maxLineCount) : HistoryScroll(new CompactHistoryType(maxLineCount)), _lines(), _blockList() { ////qDebug() << "scroll of length " << maxLineCount << " created"; setMaxNbLines(maxLineCount); } CompactHistoryScroll::~CompactHistoryScroll() { qDeleteAll(_lines.begin(), _lines.end()); _lines.clear(); } void CompactHistoryScroll::addCellsVector(const TextLine &cells) { CompactHistoryLine *line; line = new(_blockList) CompactHistoryLine(cells, _blockList); if (_lines.size() > static_cast(_maxLineCount)) { delete _lines.takeAt(0); } _lines.append(line); } void CompactHistoryScroll::addCells(const Character a[], int count) { TextLine newLine(count); qCopy(a, a + count, newLine.begin()); addCellsVector(newLine); } void CompactHistoryScroll::addLine(bool previousWrapped) { CompactHistoryLine *line = _lines.last(); ////qDebug() << "last line at address " << line; line->setWrapped(previousWrapped); } int CompactHistoryScroll::getLines() { return _lines.size(); } int CompactHistoryScroll::getLineLen(int lineNumber) { if ((lineNumber < 0) || (lineNumber >= _lines.size())) { //qDebug() << "requested line invalid: 0 < " << lineNumber << " < " <<_lines.size(); //Q_ASSERT(lineNumber >= 0 && lineNumber < _lines.size()); return 0; } CompactHistoryLine *line = _lines[lineNumber]; ////qDebug() << "request for line at address " << line; return line->getLength(); } void CompactHistoryScroll::getCells(int lineNumber, int startColumn, int count, Character buffer[]) { if (count == 0) { return; } Q_ASSERT(lineNumber < _lines.size()); CompactHistoryLine *line = _lines[lineNumber]; Q_ASSERT(startColumn >= 0); Q_ASSERT(static_cast(startColumn) <= line->getLength() - count); line->getCharacters(buffer, count, startColumn); } void CompactHistoryScroll::setMaxNbLines(unsigned int lineCount) { _maxLineCount = lineCount; while (_lines.size() > static_cast(lineCount)) { delete _lines.takeAt(0); } ////qDebug() << "set max lines to: " << _maxLineCount; } bool CompactHistoryScroll::isWrappedLine(int lineNumber) { Q_ASSERT(lineNumber < _lines.size()); return _lines[lineNumber]->isWrapped(); } ////////////////////////////////////////////////////////////////////// // History Types ////////////////////////////////////////////////////////////////////// HistoryType::HistoryType() = default; HistoryType::~HistoryType() = default; ////////////////////////////// HistoryTypeNone::HistoryTypeNone() { } bool HistoryTypeNone::isEnabled() const { return false; } HistoryScroll *HistoryTypeNone::scroll(HistoryScroll *old) const { delete old; return new HistoryScrollNone(); } int HistoryTypeNone::maximumLineCount() const { return 0; } ////////////////////////////// HistoryTypeFile::HistoryTypeFile(const QString &fileName) : _fileName(fileName) { } bool HistoryTypeFile::isEnabled() const { return true; } HistoryScroll *HistoryTypeFile::scroll(HistoryScroll *old) const { if (dynamic_cast(old) != nullptr) { return old; // Unchanged. } HistoryScroll *newScroll = new HistoryScrollFile(_fileName); Character line[LINE_SIZE]; int lines = (old != nullptr) ? old->getLines() : 0; for (int i = 0; i < lines; i++) { int size = old->getLineLen(i); if (size > LINE_SIZE) { auto tmp_line = new Character[size]; old->getCells(i, 0, size, tmp_line); newScroll->addCells(tmp_line, size); newScroll->addLine(old->isWrappedLine(i)); delete [] tmp_line; } else { old->getCells(i, 0, size, line); newScroll->addCells(line, size); newScroll->addLine(old->isWrappedLine(i)); } } delete old; return newScroll; } int HistoryTypeFile::maximumLineCount() const { return -1; } ////////////////////////////// CompactHistoryType::CompactHistoryType(unsigned int nbLines) : _maxLines(nbLines) { } bool CompactHistoryType::isEnabled() const { return true; } int CompactHistoryType::maximumLineCount() const { return _maxLines; } HistoryScroll *CompactHistoryType::scroll(HistoryScroll *old) const { if (old != nullptr) { CompactHistoryScroll *oldBuffer = dynamic_cast(old); if (oldBuffer != nullptr) { oldBuffer->setMaxNbLines(_maxLines); return oldBuffer; } delete old; } return new CompactHistoryScroll(_maxLines); } diff --git a/src/History.h b/src/History.h index 670a0fc1..27e9f6f8 100644 --- a/src/History.h +++ b/src/History.h @@ -1,415 +1,415 @@ /* This file is part of Konsole, an X terminal. Copyright 1997,1998 by Lars Doelle 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. */ #ifndef HISTORY_H #define HISTORY_H // System #include // Qt #include #include #include #include "konsoleprivate_export.h" // Konsole #include "Character.h" namespace Konsole { /* An extendable tmpfile(1) based buffer. */ class HistoryFile { public: HistoryFile(); virtual ~HistoryFile(); virtual void add(const char *buffer, qint64 count); virtual void get(char *buffer, qint64 size, qint64 loc); virtual qint64 len() const; //mmaps the file in read-only mode void map(); //un-mmaps the file void unmap(); //returns true if the file is mmap'ed bool isMapped() const; private: qint64 _length; QTemporaryFile _tmpFile; //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed uchar *_fileMap; //incremented whenever 'add' is called and decremented whenever //'get' is called. //this is used to detect when a large number of lines are being read and processed from the history //and automatically mmap the file for better performance (saves the overhead of many lseek-read calls). int _readWriteBalance; //when _readWriteBalance goes below this threshold, the file will be mmap'ed automatically static const int MAP_THRESHOLD = -1000; }; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // Abstract base class for file and buffer versions ////////////////////////////////////////////////////////////////////// class HistoryType; class KONSOLEPRIVATE_EXPORT HistoryScroll { public: explicit HistoryScroll(HistoryType *); virtual ~HistoryScroll(); virtual bool hasScroll(); // access to history virtual int getLines() = 0; virtual int getLineLen(int lineno) = 0; virtual void getCells(int lineno, int colno, int count, Character res[]) = 0; virtual bool isWrappedLine(int lineNumber) = 0; // adding lines. virtual void addCells(const Character a[], int count) = 0; // convenience method - this is virtual so that subclasses can take advantage // of QVector's implicit copying virtual void addCellsVector(const QVector &cells) { addCells(cells.data(), cells.size()); } virtual void addLine(bool previousWrapped = false) = 0; // // FIXME: Passing around constant references to HistoryType instances // is very unsafe, because those references will no longer // be valid if the history scroll is deleted. // const HistoryType &getType() const { return *_historyType; } protected: HistoryType *_historyType; }; ////////////////////////////////////////////////////////////////////// // File-based history (e.g. file log, no limitation in length) ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryScrollFile : public HistoryScroll { public: explicit HistoryScrollFile(const QString &logFileName); ~HistoryScrollFile() Q_DECL_OVERRIDE; int getLines() Q_DECL_OVERRIDE; int getLineLen(int lineno) Q_DECL_OVERRIDE; void getCells(int lineno, int colno, int count, Character res[]) Q_DECL_OVERRIDE; bool isWrappedLine(int lineno) Q_DECL_OVERRIDE; void addCells(const Character text[], int count) Q_DECL_OVERRIDE; void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; private: qint64 startOfLine(int lineno); HistoryFile _index; // lines Row(qint64) HistoryFile _cells; // text Row(Character) HistoryFile _lineflags; // flags Row(unsigned char) }; ////////////////////////////////////////////////////////////////////// // Nothing-based history (no history :-) ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryScrollNone : public HistoryScroll { public: HistoryScrollNone(); ~HistoryScrollNone() Q_DECL_OVERRIDE; bool hasScroll() Q_DECL_OVERRIDE; int getLines() Q_DECL_OVERRIDE; int getLineLen(int lineno) Q_DECL_OVERRIDE; void getCells(int lineno, int colno, int count, Character res[]) Q_DECL_OVERRIDE; bool isWrappedLine(int lineno) Q_DECL_OVERRIDE; void addCells(const Character a[], int count) Q_DECL_OVERRIDE; void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; }; ////////////////////////////////////////////////////////////////////// // History using compact storage // This implementation uses a list of fixed-sized blocks // where history lines are allocated in (avoids heap fragmentation) ////////////////////////////////////////////////////////////////////// typedef QVector TextLine; class CharacterFormat { public: bool equalsFormat(const CharacterFormat &other) const { return (other.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && other.fgColor == fgColor && other.bgColor == bgColor; } bool equalsFormat(const Character &c) const { return (c.rendition & ~RE_EXTENDED_CHAR) == (rendition & ~RE_EXTENDED_CHAR) && c.foregroundColor == fgColor && c.backgroundColor == bgColor; } void setFormat(const Character &c) { rendition = c.rendition; fgColor = c.foregroundColor; bgColor = c.backgroundColor; isRealCharacter = c.isRealCharacter; } CharacterColor fgColor, bgColor; quint16 startPos; RenditionFlags rendition; bool isRealCharacter; }; class CompactHistoryBlock { public: CompactHistoryBlock() : _blockLength(4096 * 64), // 256kb _head(static_cast(mmap(nullptr, _blockLength, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0))), _tail(nullptr), _blockStart(nullptr), _allocCount(0) { Q_ASSERT(_head != MAP_FAILED); _tail = _blockStart = _head; } virtual ~CompactHistoryBlock() { //free(_blockStart); munmap(_blockStart, _blockLength); } virtual unsigned int remaining() { return _blockStart + _blockLength - _tail; } virtual unsigned length() { return _blockLength; } virtual void *allocate(size_t size); virtual bool contains(void *addr) { return addr >= _blockStart && addr < (_blockStart + _blockLength); } virtual void deallocate(); virtual bool isInUse() { return _allocCount != 0; } private: size_t _blockLength; quint8 *_head; quint8 *_tail; quint8 *_blockStart; int _allocCount; }; class CompactHistoryBlockList { public: CompactHistoryBlockList() : list(QList()) { } ~CompactHistoryBlockList(); void *allocate(size_t size); void deallocate(void *); int length() { return list.size(); } private: QList list; }; class CompactHistoryLine { public: CompactHistoryLine(const TextLine &, CompactHistoryBlockList &blockList); virtual ~CompactHistoryLine(); // custom new operator to allocate memory from custom pool instead of heap static void *operator new(size_t size, CompactHistoryBlockList &blockList); static void operator delete(void *) { /* do nothing, deallocation from pool is done in destructor*/ } virtual void getCharacters(Character *array, int size, int startColumn); virtual void getCharacter(int index, Character &r); virtual bool isWrapped() const { return _wrapped; } virtual void setWrapped(bool value) { _wrapped = value; } virtual unsigned int getLength() const { return _length; } protected: CompactHistoryBlockList &_blockListRef; CharacterFormat *_formatArray; quint16 _length; - quint16 *_text; + uint *_text; quint16 _formatLength; bool _wrapped; }; class KONSOLEPRIVATE_EXPORT CompactHistoryScroll : public HistoryScroll { typedef QList HistoryArray; public: explicit CompactHistoryScroll(unsigned int maxNbLines = 1000); ~CompactHistoryScroll() Q_DECL_OVERRIDE; int getLines() Q_DECL_OVERRIDE; int getLineLen(int lineNumber) Q_DECL_OVERRIDE; void getCells(int lineNumber, int startColumn, int count, Character buffer[]) Q_DECL_OVERRIDE; bool isWrappedLine(int lineNumber) Q_DECL_OVERRIDE; void addCells(const Character a[], int count) Q_DECL_OVERRIDE; void addCellsVector(const TextLine &cells) Q_DECL_OVERRIDE; void addLine(bool previousWrapped = false) Q_DECL_OVERRIDE; void setMaxNbLines(unsigned int lineCount); private: bool hasDifferentColors(const TextLine &line) const; HistoryArray _lines; CompactHistoryBlockList _blockList; unsigned int _maxLineCount; }; ////////////////////////////////////////////////////////////////////// // History type ////////////////////////////////////////////////////////////////////// class KONSOLEPRIVATE_EXPORT HistoryType { public: HistoryType(); virtual ~HistoryType(); /** * Returns true if the history is enabled ( can store lines of output ) * or false otherwise. */ virtual bool isEnabled() const = 0; /** * Returns the maximum number of lines which this history type * can store or -1 if the history can store an unlimited number of lines. */ virtual int maximumLineCount() const = 0; /** * Converts from one type of HistoryScroll to another or if given the * same type, returns it. */ virtual HistoryScroll *scroll(HistoryScroll *) const = 0; /** * Returns true if the history size is unlimited. */ bool isUnlimited() const { return maximumLineCount() == -1; } }; class KONSOLEPRIVATE_EXPORT HistoryTypeNone : public HistoryType { public: HistoryTypeNone(); bool isEnabled() const Q_DECL_OVERRIDE; int maximumLineCount() const Q_DECL_OVERRIDE; HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; }; class KONSOLEPRIVATE_EXPORT HistoryTypeFile : public HistoryType { public: explicit HistoryTypeFile(const QString &fileName = QString()); bool isEnabled() const Q_DECL_OVERRIDE; int maximumLineCount() const Q_DECL_OVERRIDE; HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; protected: QString _fileName; }; class KONSOLEPRIVATE_EXPORT CompactHistoryType : public HistoryType { public: explicit CompactHistoryType(unsigned int nbLines); bool isEnabled() const Q_DECL_OVERRIDE; int maximumLineCount() const Q_DECL_OVERRIDE; HistoryScroll *scroll(HistoryScroll *) const Q_DECL_OVERRIDE; protected: unsigned int _maxLines; }; } #endif // HISTORY_H diff --git a/src/Screen.cpp b/src/Screen.cpp index f2b935d5..bd9569ff 100644 --- a/src/Screen.cpp +++ b/src/Screen.cpp @@ -1,1521 +1,1521 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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 "Screen.h" // Qt #include // Konsole #include "konsole_wcwidth.h" #include "TerminalCharacterDecoder.h" #include "History.h" #include "ExtendedCharTable.h" using namespace Konsole; //Macro to convert x,y position on screen to position within an image. // //Originally the image was stored as one large contiguous block of //memory, so a position within the image could be represented as an //offset from the beginning of the block. For efficiency reasons this //is no longer the case. //Many internal parts of this class still use this representation for parameters and so on, //notably moveImage() and clearImage(). //This macro converts from an X,Y position into an image offset. #ifndef loc #define loc(X,Y) ((Y)*_columns+(X)) #endif const Character Screen::DefaultChar = Character(' ', CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR), CharacterColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR), DEFAULT_RENDITION, false); Screen::Screen(int lines, int columns): _currentTerminalDisplay(nullptr), _lines(lines), _columns(columns), _screenLines(new ImageLine[_lines + 1]), _screenLinesSize(_lines), _scrolledLines(0), _lastScrolledRegion(QRect()), _droppedLines(0), _lineProperties(QVarLengthArray()), _history(new HistoryScrollNone()), _cuX(0), _cuY(0), _currentForeground(CharacterColor()), _currentBackground(CharacterColor()), _currentRendition(DEFAULT_RENDITION), _topMargin(0), _bottomMargin(0), _tabStops(QBitArray()), _selBegin(0), _selTopLeft(0), _selBottomRight(0), _blockSelectionMode(false), _effectiveForeground(CharacterColor()), _effectiveBackground(CharacterColor()), _effectiveRendition(DEFAULT_RENDITION), _lastPos(-1), _lastDrawnChar(0) { _lineProperties.resize(_lines + 1); for (int i = 0; i < _lines + 1; i++) { _lineProperties[i] = LINE_DEFAULT; } initTabStops(); clearSelection(); reset(); } Screen::~Screen() { delete[] _screenLines; delete _history; } void Screen::cursorUp(int n) //=CUU { if (n == 0) { n = 1; // Default } const int stop = _cuY < _topMargin ? 0 : _topMargin; _cuX = qMin(_columns - 1, _cuX); // nowrap! _cuY = qMax(stop, _cuY - n); } void Screen::cursorDown(int n) //=CUD { if (n == 0) { n = 1; // Default } const int stop = _cuY > _bottomMargin ? _lines - 1 : _bottomMargin; _cuX = qMin(_columns - 1, _cuX); // nowrap! _cuY = qMin(stop, _cuY + n); } void Screen::cursorLeft(int n) //=CUB { if (n == 0) { n = 1; // Default } _cuX = qMin(_columns - 1, _cuX); // nowrap! _cuX = qMax(0, _cuX - n); } void Screen::cursorRight(int n) //=CUF { if (n == 0) { n = 1; // Default } _cuX = qMin(_columns - 1, _cuX + n); } void Screen::setMargins(int top, int bot) //=STBM { if (top == 0) { top = 1; // Default } if (bot == 0) { bot = _lines; // Default } top = top - 1; // Adjust to internal lineno bot = bot - 1; // Adjust to internal lineno if (!(0 <= top && top < bot && bot < _lines)) { //Debug()<<" setRegion("< 0) { _cuY -= 1; } } void Screen::nextLine() //=NEL { toStartOfLine(); index(); } void Screen::eraseChars(int n) { if (n == 0) { n = 1; // Default } const int p = qMax(0, qMin(_cuX + n - 1, _columns - 1)); clearImage(loc(_cuX, _cuY), loc(p, _cuY), ' '); } void Screen::deleteChars(int n) { Q_ASSERT(n >= 0); // always delete at least one char if (n == 0) { n = 1; } // if cursor is beyond the end of the line there is nothing to do if (_cuX >= _screenLines[_cuY].count()) { return; } if (_cuX + n > _screenLines[_cuY].count()) { n = _screenLines[_cuY].count() - _cuX; } Q_ASSERT(n >= 0); Q_ASSERT(_cuX + n <= _screenLines[_cuY].count()); _screenLines[_cuY].remove(_cuX, n); // Append space(s) with current attributes Character spaceWithCurrentAttrs(' ', _effectiveForeground, _effectiveBackground, _effectiveRendition, false); for (int i = 0; i < n; i++) { _screenLines[_cuY].append(spaceWithCurrentAttrs); } } void Screen::insertChars(int n) { if (n == 0) { n = 1; // Default } if (_screenLines[_cuY].size() < _cuX) { _screenLines[_cuY].resize(_cuX); } _screenLines[_cuY].insert(_cuX, n, Character(' ')); if (_screenLines[_cuY].count() > _columns) { _screenLines[_cuY].resize(_columns); } } void Screen::repeatChars(int n) { if (n == 0) { n = 1; // Default } // From ECMA-48 version 5, section 8.3.103: // "If the character preceding REP is a control function or part of a // control function, the effect of REP is not defined by this Standard." // // So, a "normal" program should always use REP immediately after a visible // character (those other than escape sequences). So, _lastDrawnChar can be // safely used. for (int i = 0; i < n; i++) { displayCharacter(_lastDrawnChar); } } void Screen::deleteLines(int n) { if (n == 0) { n = 1; // Default } scrollUp(_cuY, n); } void Screen::insertLines(int n) { if (n == 0) { n = 1; // Default } scrollDown(_cuY, n); } void Screen::setMode(int m) { _currentModes[m] = 1; switch (m) { case MODE_Origin : _cuX = 0; _cuY = _topMargin; break; //FIXME: home } } void Screen::resetMode(int m) { _currentModes[m] = 0; switch (m) { case MODE_Origin : _cuX = 0; _cuY = 0; break; //FIXME: home } } void Screen::saveMode(int m) { _savedModes[m] = _currentModes[m]; } void Screen::restoreMode(int m) { _currentModes[m] = _savedModes[m]; } bool Screen::getMode(int m) const { return _currentModes[m] != 0; } void Screen::saveCursor() { _savedState.cursorColumn = _cuX; _savedState.cursorLine = _cuY; _savedState.rendition = _currentRendition; _savedState.foreground = _currentForeground; _savedState.background = _currentBackground; } void Screen::restoreCursor() { _cuX = qMin(_savedState.cursorColumn, _columns - 1); _cuY = qMin(_savedState.cursorLine, _lines - 1); _currentRendition = _savedState.rendition; _currentForeground = _savedState.foreground; _currentBackground = _savedState.background; updateEffectiveRendition(); } void Screen::resizeImage(int new_lines, int new_columns) { if ((new_lines == _lines) && (new_columns == _columns)) { return; } if (_cuY > new_lines - 1) { // attempt to preserve focus and _lines _bottomMargin = _lines - 1; //FIXME: margin lost for (int i = 0; i < _cuY - (new_lines - 1); i++) { addHistLine(); scrollUp(0, 1); } } // create new screen _lines and copy from old to new auto newScreenLines = new ImageLine[new_lines + 1]; for (int i = 0; i < qMin(_lines, new_lines + 1) ; i++) { newScreenLines[i] = _screenLines[i]; } _lineProperties.resize(new_lines + 1); for (int i = _lines; (i > 0) && (i < new_lines + 1); i++) { _lineProperties[i] = LINE_DEFAULT; } clearSelection(); delete[] _screenLines; _screenLines = newScreenLines; _screenLinesSize = new_lines; _lines = new_lines; _columns = new_columns; _cuX = qMin(_cuX, _columns - 1); _cuY = qMin(_cuY, _lines - 1); // FIXME: try to keep values, evtl. _topMargin = 0; _bottomMargin = _lines - 1; initTabStops(); clearSelection(); } void Screen::setDefaultMargins() { _topMargin = 0; _bottomMargin = _lines - 1; } /* Clarifying rendition here and in the display. The rendition attributes are attribute -------------- RE_UNDERLINE RE_BLINK RE_BOLD RE_REVERSE RE_TRANSPARENT RE_FAINT RE_STRIKEOUT RE_CONCEAL RE_OVERLINE Depending on settings, bold may be rendered as a heavier font in addition to a different color. */ void Screen::reverseRendition(Character& p) const { CharacterColor f = p.foregroundColor; CharacterColor b = p.backgroundColor; p.foregroundColor = b; p.backgroundColor = f; //p->r &= ~RE_TRANSPARENT; } void Screen::updateEffectiveRendition() { _effectiveRendition = _currentRendition; if ((_currentRendition & RE_REVERSE) != 0) { _effectiveForeground = _currentBackground; _effectiveBackground = _currentForeground; } else { _effectiveForeground = _currentForeground; _effectiveBackground = _currentBackground; } if ((_currentRendition & RE_BOLD) != 0) { if ((_currentRendition & RE_FAINT) == 0) { _effectiveForeground.setIntensive(); } } else { if ((_currentRendition & RE_FAINT) != 0) { _effectiveForeground.setFaint(); } } } void Screen::copyFromHistory(Character* dest, int startLine, int count) const { Q_ASSERT(startLine >= 0 && count > 0 && startLine + count <= _history->getLines()); for (int line = startLine; line < startLine + count; line++) { const int length = qMin(_columns, _history->getLineLen(line)); const int destLineOffset = (line - startLine) * _columns; _history->getCells(line, 0, length, dest + destLineOffset); for (int column = length; column < _columns; column++) { dest[destLineOffset + column] = Screen::DefaultChar; } // invert selected text if (_selBegin != -1) { for (int column = 0; column < _columns; column++) { if (isSelected(column, line)) { reverseRendition(dest[destLineOffset + column]); } } } } } void Screen::copyFromScreen(Character* dest , int startLine , int count) const { Q_ASSERT(startLine >= 0 && count > 0 && startLine + count <= _lines); for (int line = startLine; line < (startLine + count) ; line++) { int srcLineStartIndex = line * _columns; int destLineStartIndex = (line - startLine) * _columns; for (int column = 0; column < _columns; column++) { int srcIndex = srcLineStartIndex + column; int destIndex = destLineStartIndex + column; dest[destIndex] = _screenLines[srcIndex / _columns].value(srcIndex % _columns, Screen::DefaultChar); // invert selected text if (_selBegin != -1 && isSelected(column, line + _history->getLines())) { reverseRendition(dest[destIndex]); } } } } void Screen::getImage(Character* dest, int size, int startLine, int endLine) const { Q_ASSERT(startLine >= 0); Q_ASSERT(endLine >= startLine && endLine < _history->getLines() + _lines); const int mergedLines = endLine - startLine + 1; Q_ASSERT(size >= mergedLines * _columns); Q_UNUSED(size); const int linesInHistoryBuffer = qBound(0, _history->getLines() - startLine, mergedLines); const int linesInScreenBuffer = mergedLines - linesInHistoryBuffer; // copy _lines from history buffer if (linesInHistoryBuffer > 0) { copyFromHistory(dest, startLine, linesInHistoryBuffer); } // copy _lines from screen buffer if (linesInScreenBuffer > 0) { copyFromScreen(dest + linesInHistoryBuffer * _columns, startLine + linesInHistoryBuffer - _history->getLines(), linesInScreenBuffer); } // invert display when in screen mode if (getMode(MODE_Screen)) { for (int i = 0; i < mergedLines * _columns; i++) { reverseRendition(dest[i]); // for reverse display } } int visX = qMin(_cuX, _columns - 1); // mark the character at the current cursor position int cursorIndex = loc(visX, _cuY + linesInHistoryBuffer); if (getMode(MODE_Cursor) && cursorIndex < _columns * mergedLines) { dest[cursorIndex].rendition |= RE_CURSOR; } } QVector Screen::getLineProperties(int startLine , int endLine) const { Q_ASSERT(startLine >= 0); Q_ASSERT(endLine >= startLine && endLine < _history->getLines() + _lines); const int mergedLines = endLine - startLine + 1; const int linesInHistory = qBound(0, _history->getLines() - startLine, mergedLines); const int linesInScreen = mergedLines - linesInHistory; QVector result(mergedLines); int index = 0; // copy properties for _lines in history for (int line = startLine; line < startLine + linesInHistory; line++) { //TODO Support for line properties other than wrapped _lines if (_history->isWrappedLine(line)) { result[index] = static_cast(result[index] | LINE_WRAPPED); } index++; } // copy properties for _lines in screen buffer const int firstScreenLine = startLine + linesInHistory - _history->getLines(); for (int line = firstScreenLine; line < firstScreenLine + linesInScreen; line++) { result[index] = _lineProperties[line]; index++; } return result; } void Screen::reset() { // Clear screen, but preserve the current line scrollUp(0, _cuY); _cuY = 0; _currentModes[MODE_Origin] = 0; _savedModes[MODE_Origin] = 0; setMode(MODE_Wrap); saveMode(MODE_Wrap); // wrap at end of margin resetMode(MODE_Insert); saveMode(MODE_Insert); // overstroke setMode(MODE_Cursor); // cursor visible resetMode(MODE_Screen); // screen not inverse resetMode(MODE_NewLine); _topMargin = 0; _bottomMargin = _lines - 1; // Other terminal emulators reset the entire scroll history during a reset // setScroll(getScroll(), false); setDefaultRendition(); saveCursor(); } void Screen::backspace() { _cuX = qMin(_columns - 1, _cuX); // nowrap! _cuX = qMax(0, _cuX - 1); if (_screenLines[_cuY].size() < _cuX + 1) { _screenLines[_cuY].resize(_cuX + 1); } } void Screen::tab(int n) { // note that TAB is a format effector (does not write ' '); if (n == 0) { n = 1; } while ((n > 0) && (_cuX < _columns - 1)) { cursorRight(1); while ((_cuX < _columns - 1) && !_tabStops[_cuX]) { cursorRight(1); } n--; } } void Screen::backtab(int n) { // note that TAB is a format effector (does not write ' '); if (n == 0) { n = 1; } while ((n > 0) && (_cuX > 0)) { cursorLeft(1); while ((_cuX > 0) && !_tabStops[_cuX]) { cursorLeft(1); } n--; } } void Screen::clearTabStops() { for (int i = 0; i < _columns; i++) { _tabStops[i] = false; } } void Screen::changeTabStop(bool set) { if (_cuX >= _columns) { return; } _tabStops[_cuX] = set; } void Screen::initTabStops() { _tabStops.resize(_columns); // The 1st tabstop has to be one longer than the other. // i.e. the kids start counting from 0 instead of 1. // Other programs might behave correctly. Be aware. for (int i = 0; i < _columns; i++) { _tabStops[i] = (i % 8 == 0 && i != 0); } } void Screen::newLine() { if (getMode(MODE_NewLine)) { toStartOfLine(); } index(); } void Screen::checkSelection(int from, int to) { if (_selBegin == -1) { return; } const int scr_TL = loc(0, _history->getLines()); //Clear entire selection if it overlaps region [from, to] if ((_selBottomRight >= (from + scr_TL)) && (_selTopLeft <= (to + scr_TL))) { clearSelection(); } } -void Screen::displayCharacter(unsigned short c) +void Screen::displayCharacter(uint c) { // Note that VT100 does wrapping BEFORE putting the character. // This has impact on the assumption of valid cursor positions. // We indicate the fact that a newline has to be triggered by // putting the cursor one right to the last column of the screen. int w = konsole_wcwidth(c); if (w < 0) { // Non-printable character return; } else if (w == 0) { - const QChar::Category category = QChar(c).category(); - if (category != QChar::Mark_NonSpacing && category != QChar::Letter_Other && !QChar::isLowSurrogate(c)) { + const QChar::Category category = QChar::category(c); + if (category != QChar::Mark_NonSpacing && category != QChar::Letter_Other) { return; } // Find previous "real character" to try to combine with int charToCombineWithX = qMin(_cuX, _screenLines[_cuY].length()); int charToCombineWithY = _cuY; do { if (charToCombineWithX > 0) { charToCombineWithX--; } else if (charToCombineWithY > 0) { // Try previous line charToCombineWithY--; charToCombineWithX = _screenLines[charToCombineWithY].length() - 1; } else { // Give up return; } // Failsafe if (charToCombineWithX < 0) { return; } } while(!_screenLines[charToCombineWithY][charToCombineWithX].isRealCharacter); Character& currentChar = _screenLines[charToCombineWithY][charToCombineWithX]; if ((currentChar.rendition & RE_EXTENDED_CHAR) == 0) { - const ushort chars[2] = { currentChar.character, c }; + const uint chars[2] = { currentChar.character, c }; currentChar.rendition |= RE_EXTENDED_CHAR; currentChar.character = ExtendedCharTable::instance.createExtendedChar(chars, 2); } else { ushort extendedCharLength; - const ushort* oldChars = ExtendedCharTable::instance.lookupExtendedChar(currentChar.character, extendedCharLength); + const uint* oldChars = ExtendedCharTable::instance.lookupExtendedChar(currentChar.character, extendedCharLength); Q_ASSERT(oldChars); if (((oldChars) != nullptr) && extendedCharLength < 3) { Q_ASSERT(extendedCharLength > 1); Q_ASSERT(extendedCharLength < 65535); - auto chars = new ushort[extendedCharLength + 1]; - memcpy(chars, oldChars, sizeof(ushort) * extendedCharLength); + auto chars = new uint[extendedCharLength + 1]; + memcpy(chars, oldChars, sizeof(uint) * extendedCharLength); chars[extendedCharLength] = c; currentChar.character = ExtendedCharTable::instance.createExtendedChar(chars, extendedCharLength + 1); delete[] chars; } } return; } if (_cuX + w > _columns) { if (getMode(MODE_Wrap)) { _lineProperties[_cuY] = static_cast(_lineProperties[_cuY] | LINE_WRAPPED); nextLine(); } else { _cuX = qMax(_columns - w, 0); } } // ensure current line vector has enough elements if (_screenLines[_cuY].size() < _cuX + w) { _screenLines[_cuY].resize(_cuX + w); } if (getMode(MODE_Insert)) { insertChars(w); } _lastPos = loc(_cuX, _cuY); // check if selection is still valid. checkSelection(_lastPos, _lastPos); Character& currentChar = _screenLines[_cuY][_cuX]; currentChar.character = c; currentChar.foregroundColor = _effectiveForeground; currentChar.backgroundColor = _effectiveBackground; currentChar.rendition = _effectiveRendition; currentChar.isRealCharacter = true; _lastDrawnChar = c; int i = 0; const int newCursorX = _cuX + w--; while (w != 0) { i++; if (_screenLines[_cuY].size() < _cuX + i + 1) { _screenLines[_cuY].resize(_cuX + i + 1); } Character& ch = _screenLines[_cuY][_cuX + i]; ch.character = 0; ch.foregroundColor = _effectiveForeground; ch.backgroundColor = _effectiveBackground; ch.rendition = _effectiveRendition; ch.isRealCharacter = false; w--; } _cuX = newCursorX; } int Screen::scrolledLines() const { return _scrolledLines; } int Screen::droppedLines() const { return _droppedLines; } void Screen::resetDroppedLines() { _droppedLines = 0; } void Screen::resetScrolledLines() { _scrolledLines = 0; } void Screen::scrollUp(int n) { if (n == 0) { n = 1; // Default } if (_topMargin == 0) { addHistLine(); // history.history } scrollUp(_topMargin, n); } QRect Screen::lastScrolledRegion() const { return _lastScrolledRegion; } void Screen::scrollUp(int from, int n) { if (n <= 0) { return; } if (from > _bottomMargin) { return; } if (from + n > _bottomMargin) { n = _bottomMargin + 1 - from; } _scrolledLines -= n; _lastScrolledRegion = QRect(0, _topMargin, _columns - 1, (_bottomMargin - _topMargin)); //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. moveImage(loc(0, from), loc(0, from + n), loc(_columns, _bottomMargin)); clearImage(loc(0, _bottomMargin - n + 1), loc(_columns - 1, _bottomMargin), ' '); } void Screen::scrollDown(int n) { if (n == 0) { n = 1; // Default } scrollDown(_topMargin, n); } void Screen::scrollDown(int from, int n) { _scrolledLines += n; //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. if (n <= 0) { return; } if (from > _bottomMargin) { return; } if (from + n > _bottomMargin) { n = _bottomMargin - from; } moveImage(loc(0, from + n), loc(0, from), loc(_columns - 1, _bottomMargin - n)); clearImage(loc(0, from), loc(_columns - 1, from + n - 1), ' '); } void Screen::setCursorYX(int y, int x) { setCursorY(y); setCursorX(x); } void Screen::setCursorX(int x) { if (x == 0) { x = 1; // Default } x -= 1; // Adjust _cuX = qMax(0, qMin(_columns - 1, x)); } void Screen::setCursorY(int y) { if (y == 0) { y = 1; // Default } y -= 1; // Adjust _cuY = qMax(0, qMin(_lines - 1, y + (getMode(MODE_Origin) ? _topMargin : 0))); } void Screen::toStartOfLine() { _cuX = 0; } int Screen::getCursorX() const { return qMin(_cuX, _columns - 1); } int Screen::getCursorY() const { return _cuY; } void Screen::clearImage(int loca, int loce, char c) { const int scr_TL = loc(0, _history->getLines()); //FIXME: check positions //Clear entire selection if it overlaps region to be moved... if ((_selBottomRight > (loca + scr_TL)) && (_selTopLeft < (loce + scr_TL))) { clearSelection(); } const int topLine = loca / _columns; const int bottomLine = loce / _columns; - Character clearCh(c, _currentForeground, _currentBackground, DEFAULT_RENDITION, false); + Character clearCh(uint(c), _currentForeground, _currentBackground, DEFAULT_RENDITION, false); //if the character being used to clear the area is the same as the //default character, the affected _lines can simply be shrunk. const bool isDefaultCh = (clearCh == Screen::DefaultChar); for (int y = topLine; y <= bottomLine; y++) { _lineProperties[y] = 0; const int endCol = (y == bottomLine) ? loce % _columns : _columns - 1; const int startCol = (y == topLine) ? loca % _columns : 0; QVector& line = _screenLines[y]; if (isDefaultCh && endCol == _columns - 1) { line.resize(startCol); } else { if (line.size() < endCol + 1) { line.resize(endCol + 1); } Character* data = line.data(); for (int i = startCol; i <= endCol; i++) { data[i] = clearCh; } } } } void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) { Q_ASSERT(sourceBegin <= sourceEnd); const int lines = (sourceEnd - sourceBegin) / _columns; //move screen image and line properties: //the source and destination areas of the image may overlap, //so it matters that we do the copy in the right order - //forwards if dest < sourceBegin or backwards otherwise. //(search the web for 'memmove implementation' for details) if (dest < sourceBegin) { for (int i = 0; i <= lines; i++) { _screenLines[(dest / _columns) + i ] = _screenLines[(sourceBegin / _columns) + i ]; _lineProperties[(dest / _columns) + i] = _lineProperties[(sourceBegin / _columns) + i]; } } else { for (int i = lines; i >= 0; i--) { _screenLines[(dest / _columns) + i ] = _screenLines[(sourceBegin / _columns) + i ]; _lineProperties[(dest / _columns) + i] = _lineProperties[(sourceBegin / _columns) + i]; } } if (_lastPos != -1) { const int diff = dest - sourceBegin; // Scroll by this amount _lastPos += diff; if ((_lastPos < 0) || (_lastPos >= (lines * _columns))) { _lastPos = -1; } } // Adjust selection to follow scroll. if (_selBegin != -1) { const bool beginIsTL = (_selBegin == _selTopLeft); const int diff = dest - sourceBegin; // Scroll by this amount const int scr_TL = loc(0, _history->getLines()); const int srca = sourceBegin + scr_TL; // Translate index from screen to global const int srce = sourceEnd + scr_TL; // Translate index from screen to global const int desta = srca + diff; const int deste = srce + diff; if ((_selTopLeft >= srca) && (_selTopLeft <= srce)) { _selTopLeft += diff; } else if ((_selTopLeft >= desta) && (_selTopLeft <= deste)) { _selBottomRight = -1; // Clear selection (see below) } if ((_selBottomRight >= srca) && (_selBottomRight <= srce)) { _selBottomRight += diff; } else if ((_selBottomRight >= desta) && (_selBottomRight <= deste)) { _selBottomRight = -1; // Clear selection (see below) } if (_selBottomRight < 0) { clearSelection(); } else { if (_selTopLeft < 0) { _selTopLeft = 0; } } if (beginIsTL) { _selBegin = _selTopLeft; } else { _selBegin = _selBottomRight; } } } void Screen::clearToEndOfScreen() { clearImage(loc(_cuX, _cuY), loc(_columns - 1, _lines - 1), ' '); } void Screen::clearToBeginOfScreen() { clearImage(loc(0, 0), loc(_cuX, _cuY), ' '); } void Screen::clearEntireScreen() { // Add entire screen to history for (int i = 0; i < (_lines - 1); i++) { addHistLine(); scrollUp(0, 1); } clearImage(loc(0, 0), loc(_columns - 1, _lines - 1), ' '); } /*! fill screen with 'E' This is to aid screen alignment */ void Screen::helpAlign() { clearImage(loc(0, 0), loc(_columns - 1, _lines - 1), 'E'); } void Screen::clearToEndOfLine() { clearImage(loc(_cuX, _cuY), loc(_columns - 1, _cuY), ' '); } void Screen::clearToBeginOfLine() { clearImage(loc(0, _cuY), loc(_cuX, _cuY), ' '); } void Screen::clearEntireLine() { clearImage(loc(0, _cuY), loc(_columns - 1, _cuY), ' '); } void Screen::setRendition(RenditionFlags rendition) { _currentRendition |= rendition; updateEffectiveRendition(); } void Screen::resetRendition(RenditionFlags rendition) { _currentRendition &= ~rendition; updateEffectiveRendition(); } void Screen::setDefaultRendition() { setForeColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); setBackColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); _currentRendition = DEFAULT_RENDITION; updateEffectiveRendition(); } void Screen::setForeColor(int space, int color) { - _currentForeground = CharacterColor(space, color); + _currentForeground = CharacterColor(quint8(space), color); if (_currentForeground.isValid()) { updateEffectiveRendition(); } else { setForeColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); } } void Screen::setBackColor(int space, int color) { - _currentBackground = CharacterColor(space, color); + _currentBackground = CharacterColor(quint8(space), color); if (_currentBackground.isValid()) { updateEffectiveRendition(); } else { setBackColor(COLOR_SPACE_DEFAULT, DEFAULT_BACK_COLOR); } } void Screen::clearSelection() { _selBottomRight = -1; _selTopLeft = -1; _selBegin = -1; } void Screen::getSelectionStart(int& column , int& line) const { if (_selTopLeft != -1) { column = _selTopLeft % _columns; line = _selTopLeft / _columns; } else { column = _cuX + getHistLines(); line = _cuY + getHistLines(); } } void Screen::getSelectionEnd(int& column , int& line) const { if (_selBottomRight != -1) { column = _selBottomRight % _columns; line = _selBottomRight / _columns; } else { column = _cuX + getHistLines(); line = _cuY + getHistLines(); } } void Screen::setSelectionStart(const int x, const int y, const bool blockSelectionMode) { _selBegin = loc(x, y); /* FIXME, HACK to correct for x too far to the right... */ if (x == _columns) { _selBegin--; } _selBottomRight = _selBegin; _selTopLeft = _selBegin; _blockSelectionMode = blockSelectionMode; } void Screen::setSelectionEnd(const int x, const int y) { if (_selBegin == -1) { return; } int endPos = loc(x, y); if (endPos < _selBegin) { _selTopLeft = endPos; _selBottomRight = _selBegin; } else { /* FIXME, HACK to correct for x too far to the right... */ if (x == _columns) { endPos--; } _selTopLeft = _selBegin; _selBottomRight = endPos; } // Normalize the selection in column mode if (_blockSelectionMode) { const int topRow = _selTopLeft / _columns; const int topColumn = _selTopLeft % _columns; const int bottomRow = _selBottomRight / _columns; const int bottomColumn = _selBottomRight % _columns; _selTopLeft = loc(qMin(topColumn, bottomColumn), topRow); _selBottomRight = loc(qMax(topColumn, bottomColumn), bottomRow); } } bool Screen::isSelected(const int x, const int y) const { bool columnInSelection = true; if (_blockSelectionMode) { columnInSelection = x >= (_selTopLeft % _columns) && x <= (_selBottomRight % _columns); } const int pos = loc(x, y); return pos >= _selTopLeft && pos <= _selBottomRight && columnInSelection; } QString Screen::selectedText(const DecodingOptions options) const { if (!isSelectionValid()) { return QString(); } return text(_selTopLeft, _selBottomRight, options); } QString Screen::text(int startIndex, int endIndex, const DecodingOptions options) const { QString result; QTextStream stream(&result, QIODevice::ReadWrite); HTMLDecoder htmlDecoder; PlainTextDecoder plainTextDecoder; TerminalCharacterDecoder *decoder; if((options & ConvertToHtml) != 0u) { decoder = &htmlDecoder; } else { decoder = &plainTextDecoder; } decoder->begin(&stream); writeToStream(decoder, startIndex, endIndex, options); decoder->end(); return result; } bool Screen::isSelectionValid() const { return _selTopLeft >= 0 && _selBottomRight >= 0; } void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , const DecodingOptions options) const { if (!isSelectionValid()) { return; } writeToStream(decoder, _selTopLeft, _selBottomRight, options); } void Screen::writeToStream(TerminalCharacterDecoder* decoder, int startIndex, int endIndex, const DecodingOptions options) const { const int top = startIndex / _columns; const int left = startIndex % _columns; const int bottom = endIndex / _columns; const int right = endIndex % _columns; Q_ASSERT(top >= 0 && left >= 0 && bottom >= 0 && right >= 0); for (int y = top; y <= bottom; y++) { int start = 0; if (y == top || _blockSelectionMode) { start = left; } int count = -1; if (y == bottom || _blockSelectionMode) { count = right - start + 1; } const bool appendNewLine = (y != bottom); int copied = copyLineToStream(y, start, count, decoder, appendNewLine, options); // if the selection goes beyond the end of the last line then // append a new line character. // // this makes it possible to 'select' a trailing new line character after // the text on a line. if (y == bottom && copied < count && !options.testFlag(TrimTrailingWhitespace)) { Character newLineChar('\n'); decoder->decodeLine(&newLineChar, 1, 0); } } } int Screen::copyLineToStream(int line , int start, int count, TerminalCharacterDecoder* decoder, bool appendNewLine, const DecodingOptions options) const { //buffer to hold characters for decoding //the buffer is static to avoid initializing every //element on each call to copyLineToStream //(which is unnecessary since all elements will be overwritten anyway) static const int MAX_CHARS = 1024; static Character characterBuffer[MAX_CHARS]; Q_ASSERT(count < MAX_CHARS); LineProperty currentLineProperties = 0; //determine if the line is in the history buffer or the screen image if (line < _history->getLines()) { const int lineLength = _history->getLineLen(line); // ensure that start position is before end of line start = qMin(start, qMax(0, lineLength - 1)); // retrieve line from history buffer. It is assumed // that the history buffer does not store trailing white space // at the end of the line, so it does not need to be trimmed here if (count == -1) { count = lineLength - start; } else { count = qMin(start + count, lineLength) - start; } // safety checks Q_ASSERT(start >= 0); Q_ASSERT(count >= 0); Q_ASSERT((start + count) <= _history->getLineLen(line)); _history->getCells(line, start, count, characterBuffer); if (_history->isWrappedLine(line)) { currentLineProperties |= LINE_WRAPPED; } } else { if (count == -1) { count = _columns - start; } Q_ASSERT(count >= 0); int screenLine = line - _history->getLines(); // FIXME: This can be triggered when clearing history // while having the searchbar open and selecting next/prev Q_ASSERT(screenLine <= _screenLinesSize); screenLine = qMin(screenLine, _screenLinesSize); Character* data = _screenLines[screenLine].data(); int length = _screenLines[screenLine].count(); // Don't remove end spaces in lines that wrap if (options.testFlag(TrimTrailingWhitespace) && ((_lineProperties[screenLine] & LINE_WRAPPED) == 0)) { // ignore trailing white space at the end of the line for (int i = length-1; i >= 0; i--) { if (QChar(data[i].character).isSpace()) { length--; } else { break; } } } //retrieve line from screen image for (int i = start; i < qMin(start + count, length); i++) { characterBuffer[i - start] = data[i]; } // count cannot be any greater than length count = qBound(0, count, length - start); Q_ASSERT(screenLine < _lineProperties.count()); currentLineProperties |= _lineProperties[screenLine]; } if (appendNewLine && (count + 1 < MAX_CHARS)) { if ((currentLineProperties & LINE_WRAPPED) != 0) { // do nothing extra when this line is wrapped. } else { // When users ask not to preserve the linebreaks, they usually mean: // `treat LINEBREAK as SPACE, thus joining multiple _lines into // single line in the same way as 'J' does in VIM.` characterBuffer[count] = options.testFlag(PreserveLineBreaks) ? Character('\n') : Character(' '); count++; } } if ((options & TrimLeadingWhitespace) != 0u) { int spacesCount = 0; for (spacesCount = 0; spacesCount < count; spacesCount++) { if (!QChar(characterBuffer[spacesCount].character).isSpace()) { break; } } if (spacesCount >= count) { return 0; } for (int i=0; i < count - spacesCount; i++) { characterBuffer[i] = characterBuffer[i + spacesCount]; } count -= spacesCount; } //decode line and write to text stream decoder->decodeLine(characterBuffer, count, currentLineProperties); return count; } void Screen::writeLinesToStream(TerminalCharacterDecoder* decoder, int fromLine, int toLine) const { writeToStream(decoder, loc(0, fromLine), loc(_columns - 1, toLine), PreserveLineBreaks); } void Screen::addHistLine() { // add line to history buffer // we have to take care about scrolling, too... if (hasScroll()) { const int oldHistLines = _history->getLines(); _history->addCellsVector(_screenLines[0]); _history->addLine((_lineProperties[0] & LINE_WRAPPED) != 0); const int newHistLines = _history->getLines(); const bool beginIsTL = (_selBegin == _selTopLeft); // If the history is full, increment the count // of dropped _lines if (newHistLines == oldHistLines) { _droppedLines++; } // Adjust selection for the new point of reference if (newHistLines > oldHistLines) { if (_selBegin != -1) { _selTopLeft += _columns; _selBottomRight += _columns; } } if (_selBegin != -1) { // Scroll selection in history up const int top_BR = loc(0, 1 + newHistLines); if (_selTopLeft < top_BR) { _selTopLeft -= _columns; } if (_selBottomRight < top_BR) { _selBottomRight -= _columns; } if (_selBottomRight < 0) { clearSelection(); } else { if (_selTopLeft < 0) { _selTopLeft = 0; } } if (beginIsTL) { _selBegin = _selTopLeft; } else { _selBegin = _selBottomRight; } } } } int Screen::getHistLines() const { return _history->getLines(); } void Screen::setScroll(const HistoryType& t , bool copyPreviousScroll) { clearSelection(); if (copyPreviousScroll) { _history = t.scroll(_history); } else { HistoryScroll* oldScroll = _history; _history = t.scroll(nullptr); delete oldScroll; } } bool Screen::hasScroll() const { return _history->hasScroll(); } const HistoryType& Screen::getScroll() const { return _history->getType(); } void Screen::setLineProperty(LineProperty property , bool enable) { if (enable) { _lineProperties[_cuY] = static_cast(_lineProperties[_cuY] | property); } else { _lineProperties[_cuY] = static_cast(_lineProperties[_cuY] & ~property); } } void Screen::fillWithDefaultChar(Character* dest, int count) { for (int i = 0; i < count; i++) { dest[i] = Screen::DefaultChar; } } diff --git a/src/Screen.h b/src/Screen.h index 6d6c22b6..93a337b5 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,736 +1,736 @@ /* This file is part of Konsole, KDE's terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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. */ #ifndef SCREEN_H #define SCREEN_H // Qt #include #include #include #include #include // Konsole #include "Character.h" #define MODE_Origin 0 #define MODE_Wrap 1 #define MODE_Insert 2 #define MODE_Screen 3 #define MODE_Cursor 4 #define MODE_NewLine 5 #define MODES_SCREEN 6 namespace Konsole { class TerminalCharacterDecoder; class TerminalDisplay; class HistoryType; class HistoryScroll; /** \brief An image of characters with associated attributes. The terminal emulation ( Emulation ) receives a serial stream of characters from the program currently running in the terminal. From this stream it creates an image of characters which is ultimately rendered by the display widget ( TerminalDisplay ). Some types of emulation may have more than one screen image. getImage() is used to retrieve the currently visible image which is then used by the display widget to draw the output from the terminal. The number of lines of output history which are kept in addition to the current screen image depends on the history scroll being used to store the output. The scroll is specified using setScroll() The output history can be retrieved using writeToStream() The screen image has a selection associated with it, specified using setSelectionStart() and setSelectionEnd(). The selected text can be retrieved using selectedText(). When getImage() is used to retrieve the visible image, characters which are part of the selection have their colors inverted. */ class Screen { public: /* PlainText: Return plain text (default) * ConvertToHtml: Specifies if returned text should have HTML tags. * PreserveLineBreaks: Specifies whether new line characters should be * inserted into the returned text at the end of each terminal line. * TrimLeadingWhitespace: Specifies whether leading spaces should be * trimmed in the returned text. * TrimTrailingWhitespace: Specifies whether trailing spaces should be * trimmed in the returned text. */ enum DecodingOption { PlainText = 0x0, ConvertToHtml = 0x1, PreserveLineBreaks = 0x2, TrimLeadingWhitespace = 0x4, TrimTrailingWhitespace = 0x8 }; Q_DECLARE_FLAGS(DecodingOptions, DecodingOption) /** Construct a new screen image of size @p lines by @p columns. */ Screen(int lines, int columns); ~Screen(); Screen(const Screen &) = delete; Screen &operator=(const Screen &) = delete; // VT100/2 Operations // Cursor Movement /** * Move the cursor up by @p n lines. The cursor will stop at the * top margin. */ void cursorUp(int n); /** * Move the cursor down by @p n lines. The cursor will stop at the * bottom margin. */ void cursorDown(int n); /** * Move the cursor to the left by @p n columns. * The cursor will stop at the first column. */ void cursorLeft(int n); /** * Move the cursor to the right by @p n columns. * The cursor will stop at the right-most column. */ void cursorRight(int n); /** Position the cursor on line @p y. */ void setCursorY(int y); /** Position the cursor at column @p x. */ void setCursorX(int x); /** Position the cursor at line @p y, column @p x. */ void setCursorYX(int y, int x); /** * Sets the margins for scrolling the screen. * * @param top The top line of the new scrolling margin. * @param bot The bottom line of the new scrolling margin. */ void setMargins(int top, int bot); /** Returns the top line of the scrolling region. */ int topMargin() const; /** Returns the bottom line of the scrolling region. */ int bottomMargin() const; /** * Resets the scrolling margins back to the top and bottom lines * of the screen. */ void setDefaultMargins(); /** * Moves the cursor down one line, if the MODE_NewLine mode * flag is enabled then the cursor is returned to the leftmost * column first. * * Equivalent to NextLine() if the MODE_NewLine flag is set * or index() otherwise. */ void newLine(); /** * Moves the cursor down one line and positions it at the beginning * of the line. Equivalent to calling Return() followed by index() */ void nextLine(); /** * Move the cursor down one line. If the cursor is on the bottom * line of the scrolling region (as returned by bottomMargin()) the * scrolling region is scrolled up by one line instead. */ void index(); /** * Move the cursor up one line. If the cursor is on the top line * of the scrolling region (as returned by topMargin()) the scrolling * region is scrolled down by one line instead. */ void reverseIndex(); /** * Scroll the scrolling region of the screen up by @p n lines. * The scrolling region is initially the whole screen, but can be changed * using setMargins() */ void scrollUp(int n); /** * Scroll the scrolling region of the screen down by @p n lines. * The scrolling region is initially the whole screen, but can be changed * using setMargins() */ void scrollDown(int n); /** * Moves the cursor to the beginning of the current line. * Equivalent to setCursorX(0) */ void toStartOfLine(); /** * Moves the cursor one column to the left and erases the character * at the new cursor position. */ void backspace(); /** Moves the cursor @p n tab-stops to the right. */ void tab(int n = 1); /** Moves the cursor @p n tab-stops to the left. */ void backtab(int n); // Editing /** * Erase @p n characters beginning from the current cursor position. * This is equivalent to over-writing @p n characters starting with the current * cursor position with spaces. * If @p n is 0 then one character is erased. */ void eraseChars(int n); /** * Delete @p n characters beginning from the current cursor position. * If @p n is 0 then one character is deleted. */ void deleteChars(int n); /** * Insert @p n blank characters beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one character is inserted. */ void insertChars(int n); /** * Repeat the preceding graphic character @n times, including SPACE. * If @n is 0 then the character is repeated once. */ void repeatChars(int n); /** * Removes @p n lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is removed. */ void deleteLines(int n); /** * Inserts @p lines beginning from the current cursor position. * The position of the cursor is not altered. * If @p n is 0 then one line is inserted. */ void insertLines(int n); /** Clears all the tab stops. */ void clearTabStops(); /** Sets or removes a tab stop at the cursor's current column. */ void changeTabStop(bool set); /** Resets (clears) the specified screen @p m. */ void resetMode(int m); /** Sets (enables) the specified screen @p m. */ void setMode(int m); /** * Saves the state of the specified screen @p m. It can be restored * using restoreMode() */ void saveMode(int m); /** Restores the state of a screen @p m saved by calling saveMode() */ void restoreMode(int m); /** Returns whether the specified screen @p me is enabled or not .*/ bool getMode(int m) const; /** * Saves the current position and appearance (text color and style) of the cursor. * It can be restored by calling restoreCursor() */ void saveCursor(); /** Restores the position and appearance of the cursor. See saveCursor() */ void restoreCursor(); /** Clear the whole screen, moving the current screen contents into the history first. */ void clearEntireScreen(); /** * Clear the area of the screen from the current cursor position to the end of * the screen. */ void clearToEndOfScreen(); /** * Clear the area of the screen from the current cursor position to the start * of the screen. */ void clearToBeginOfScreen(); /** Clears the whole of the line on which the cursor is currently positioned. */ void clearEntireLine(); /** Clears from the current cursor position to the end of the line. */ void clearToEndOfLine(); /** Clears from the current cursor position to the beginning of the line. */ void clearToBeginOfLine(); /** Fills the entire screen with the letter 'E' */ void helpAlign(); /** * Enables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void setRendition(RenditionFlags rendition); /** * Disables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition */ void resetRendition(RenditionFlags rendition); /** * Sets the cursor's foreground color. * @param space The color space used by the @p color argument * @param color The new foreground color. The meaning of this depends on * the color @p space used. * * @see CharacterColor */ void setForeColor(int space, int color); /** * Sets the cursor's background color. * @param space The color space used by the @p color argument. * @param color The new background color. The meaning of this depends on * the color @p space used. * * @see CharacterColor */ void setBackColor(int space, int color); /** * Resets the cursor's color back to the default and sets the * character's rendition flags back to the default settings. */ void setDefaultRendition(); /** Returns the column which the cursor is positioned at. */ int getCursorX() const; /** Returns the line which the cursor is positioned on. */ int getCursorY() const; /** * Resets the state of the screen. This resets the various screen modes * back to their default states. The cursor style and colors are reset * (as if setDefaultRendition() had been called) * *
    *
  • Line wrapping is enabled.
  • *
  • Origin mode is disabled.
  • *
  • Insert mode is disabled.
  • *
  • Cursor mode is enabled. TODO Document me
  • *
  • Screen mode is disabled. TODO Document me
  • *
  • New line mode is disabled. TODO Document me
  • *
* * If @p clearScreen is true then the screen contents are erased entirely, * otherwise they are unaltered. */ void reset(); /** * Displays a new character at the current cursor position. * * If the cursor is currently positioned at the right-edge of the screen and * line wrapping is enabled then the character is added at the start of a new * line below the current one. * * If the MODE_Insert screen mode is currently enabled then the character * is inserted at the current cursor position, otherwise it will replace the * character already at the current cursor position. */ - void displayCharacter(unsigned short c); + void displayCharacter(uint c); /** * Resizes the image to a new fixed size of @p new_lines by @p new_columns. * In the case that @p new_columns is smaller than the current number of columns, * existing lines are not truncated. This prevents characters from being lost * if the terminal display is resized smaller and then larger again. * * The top and bottom margins are reset to the top and bottom of the new * screen size. Tab stops are also reset and the current selection is * cleared. */ void resizeImage(int new_lines, int new_columns); /** * Returns the current screen image. * The result is an array of Characters of size [getLines()][getColumns()] which * must be freed by the caller after use. * * @param dest Buffer to copy the characters into * @param size Size of @p dest in Characters * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ void getImage(Character *dest, int size, int startLine, int endLine) const; /** * Returns the additional attributes associated with lines in the image. * The most important attribute is LINE_WRAPPED which specifies that the * line is wrapped, * other attributes control the size of characters in the line. */ QVector getLineProperties(int startLine, int endLine) const; /** Return the number of lines. */ int getLines() const { return _lines; } /** Return the number of columns. */ int getColumns() const { return _columns; } /** Return the number of lines in the history buffer. */ int getHistLines() const; /** * Sets the type of storage used to keep lines in the history. * If @p copyPreviousScroll is true then the contents of the previous * history buffer are copied into the new scroll. */ void setScroll(const HistoryType &, bool copyPreviousScroll = true); /** Returns the type of storage used to keep lines in the history. */ const HistoryType &getScroll() const; /** * Returns true if this screen keeps lines that are scrolled off the screen * in a history buffer. */ bool hasScroll() const; /** * Sets the start of the selection. * * @param x The column index of the first character in the selection. * @param y The line index of the first character in the selection. * @param blockSelectionMode True if the selection is in column mode. */ void setSelectionStart(const int x, const int y, const bool blockSelectionMode); /** * Sets the end of the current selection. * * @param x The column index of the last character in the selection. * @param y The line index of the last character in the selection. */ void setSelectionEnd(const int x, const int y); /** * Retrieves the start of the selection or the cursor position if there * is no selection. */ void getSelectionStart(int &column, int &line) const; /** * Retrieves the end of the selection or the cursor position if there * is no selection. */ void getSelectionEnd(int &column, int &line) const; /** Clears the current selection */ void clearSelection(); /** * Returns true if the character at (@p x, @p y) is part of the * current selection. */ bool isSelected(const int x, const int y) const; /** * Convenience method. Returns the currently selected text. * @param options See Screen::DecodingOptions */ QString selectedText(const DecodingOptions options) const; /** * Convenience method. Returns the text between two indices. * @param startIndex Specifies the starting text index * @param endIndex Specifies the ending text index * @param options See Screen::DecodingOptions */ QString text(int startIndex, int endIndex, const DecodingOptions options) const; /** * Copies part of the output to a stream. * * @param decoder A decoder which converts terminal characters into text * @param fromLine The first line in the history to retrieve * @param toLine The last line in the history to retrieve */ void writeLinesToStream(TerminalCharacterDecoder *decoder, int fromLine, int toLine) const; /** * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY * into a stream. * * @param decoder A decoder which converts terminal characters into text. * PlainTextDecoder is the most commonly used decoder which converts characters * into plain text with no formatting. * @param options See Screen::DecodingOptions */ void writeSelectionToStream(TerminalCharacterDecoder *decoder, const DecodingOptions options) const; /** * Checks if the text between from and to is inside the current * selection. If this is the case, the selection is cleared. The * from and to are coordinates in the current viewable window. * The loc(x,y) macro can be used to generate these values from a * column,line pair. * * @param from The start of the area to check. * @param to The end of the area to check */ void checkSelection(int from, int to); /** * Sets or clears an attribute of the current line. * * @param property The attribute to set or clear * Possible properties are: * LINE_WRAPPED: Specifies that the line is wrapped. * LINE_DOUBLEWIDTH: Specifies that the characters in the current line * should be double the normal width. * LINE_DOUBLEHEIGHT:Specifies that the characters in the current line * should be double the normal height. * Double-height lines are formed of two lines containing the same characters, * with both having the LINE_DOUBLEHEIGHT attribute. * This allows other parts of the code to work on the * assumption that all lines are the same height. * * @param enable true to apply the attribute to the current line or false to remove it */ void setLineProperty(LineProperty property, bool enable); /** * Returns the number of lines that the image has been scrolled up or down by, * since the last call to resetScrolledLines(). * * a positive return value indicates that the image has been scrolled up, * a negative return value indicates that the image has been scrolled down. */ int scrolledLines() const; /** * Returns the region of the image which was last scrolled. * * This is the area of the image from the top margin to the * bottom margin when the last scroll occurred. */ QRect lastScrolledRegion() const; /** * Resets the count of the number of lines that the image has been scrolled up or down by, * see scrolledLines() */ void resetScrolledLines(); /** * Returns the number of lines of output which have been * dropped from the history since the last call * to resetDroppedLines() * * If the history is not unlimited then it will drop * the oldest lines of output if new lines are added when * it is full. */ int droppedLines() const; /** * Resets the count of the number of lines dropped from * the history. */ void resetDroppedLines(); /** * Fills the buffer @p dest with @p count instances of the default (ie. blank) * Character style. */ static void fillWithDefaultChar(Character *dest, int count); void setCurrentTerminalDisplay(TerminalDisplay *display) { _currentTerminalDisplay = display; } TerminalDisplay *currentTerminalDisplay() { return _currentTerminalDisplay; } - QSet usedExtendedChars() const + QSet usedExtendedChars() const { - QSet result; + QSet result; for (int i = 0; i < _lines; ++i) { const ImageLine &il = _screenLines[i]; for (int j = 0; j < il.length(); ++j) { if (il[j].rendition & RE_EXTENDED_CHAR) { result << il[j].character; } } } return result; } static const Character DefaultChar; private: //copies a line of text from the screen or history into a stream using a //specified character decoder. Returns the number of lines actually copied, //which may be less than 'count' if (start+count) is more than the number of characters on //the line // //line - the line number to copy, from 0 (the earliest line in the history) up to // history->getLines() + lines - 1 //start - the first column on the line to copy //count - the number of characters on the line to copy //decoder - a decoder which converts terminal characters (an Character array) into text //appendNewLine - if true a new line character (\n) is appended to the end of the line int copyLineToStream(int line, int start, int count, TerminalCharacterDecoder *decoder, bool appendNewLine, const DecodingOptions options) const; //fills a section of the screen image with the character 'c' //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. void clearImage(int loca, int loce, char c); //move screen image between 'sourceBegin' and 'sourceEnd' to 'dest'. //the parameters are specified as offsets from the start of the screen image. //the loc(x,y) macro can be used to generate these values from a column,line pair. // //NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); // scroll up 'n' lines in current region, clearing the bottom 'n' lines void scrollUp(int from, int n); // scroll down 'n' lines in current region, clearing the top 'n' lines void scrollDown(int from, int n); //when we handle scroll commands, we need to know which screenwindow will scroll TerminalDisplay *_currentTerminalDisplay; void addHistLine(); void initTabStops(); void updateEffectiveRendition(); void reverseRendition(Character &p) const; bool isSelectionValid() const; // copies text from 'startIndex' to 'endIndex' to a stream // startIndex and endIndex are positions generated using the loc(x,y) macro void writeToStream(TerminalCharacterDecoder *decoder, int startIndex, int endIndex, const DecodingOptions options) const; // copies 'count' lines from the screen buffer into 'dest', // starting from 'startLine', where 0 is the first line in the screen buffer void copyFromScreen(Character *dest, int startLine, int count) const; // copies 'count' lines from the history buffer into 'dest', // starting from 'startLine', where 0 is the first line in the history void copyFromHistory(Character *dest, int startLine, int count) const; // screen image ---------------- int _lines; int _columns; typedef QVector ImageLine; // [0..columns] ImageLine *_screenLines; // [lines] int _screenLinesSize; // _screenLines.size() int _scrolledLines; QRect _lastScrolledRegion; int _droppedLines; QVarLengthArray _lineProperties; // history buffer --------------- HistoryScroll *_history; // cursor location int _cuX; int _cuY; // cursor color and rendition info CharacterColor _currentForeground; CharacterColor _currentBackground; RenditionFlags _currentRendition; // margins ---------------- int _topMargin; int _bottomMargin; // states ---------------- int _currentModes[MODES_SCREEN]; int _savedModes[MODES_SCREEN]; // ---------------------------- QBitArray _tabStops; // selection ------------------- int _selBegin; // The first location selected. int _selTopLeft; // TopLeft Location. int _selBottomRight; // Bottom Right Location. bool _blockSelectionMode; // Column selection mode // effective colors and rendition ------------ CharacterColor _effectiveForeground; // These are derived from CharacterColor _effectiveBackground; // the cu_* variables above RenditionFlags _effectiveRendition; // to speed up operation class SavedState { public: SavedState() : cursorColumn(0), cursorLine(0), rendition(0), foreground(CharacterColor()), background(CharacterColor()) { } int cursorColumn; int cursorLine; RenditionFlags rendition; CharacterColor foreground; CharacterColor background; }; SavedState _savedState; // last position where we added a character int _lastPos; // used in REP (repeating char) - unsigned short _lastDrawnChar; + quint32 _lastDrawnChar; }; Q_DECLARE_OPERATORS_FOR_FLAGS(Screen::DecodingOptions) } #endif // SCREEN_H diff --git a/src/TerminalCharacterDecoder.cpp b/src/TerminalCharacterDecoder.cpp index ffcb8e61..8888dcc4 100644 --- a/src/TerminalCharacterDecoder.cpp +++ b/src/TerminalCharacterDecoder.cpp @@ -1,308 +1,308 @@ /* This file is part of Konsole, an X terminal. Copyright 2006-2008 by Robert Knight This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser 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 Lesser 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 "TerminalCharacterDecoder.h" // Qt #include // Konsole #include "konsole_wcwidth.h" #include "ExtendedCharTable.h" #include "ColorScheme.h" using namespace Konsole; PlainTextDecoder::PlainTextDecoder() : _output(nullptr) , _includeLeadingWhitespace(true) , _includeTrailingWhitespace(true) , _recordLinePositions(false) , _linePositions(QList()) { } void PlainTextDecoder::setLeadingWhitespace(bool enable) { _includeLeadingWhitespace = enable; } bool PlainTextDecoder::leadingWhitespace() const { return _includeLeadingWhitespace; } void PlainTextDecoder::setTrailingWhitespace(bool enable) { _includeTrailingWhitespace = enable; } bool PlainTextDecoder::trailingWhitespace() const { return _includeTrailingWhitespace; } void PlainTextDecoder::begin(QTextStream* output) { _output = output; if (!_linePositions.isEmpty()) { _linePositions.clear(); } } void PlainTextDecoder::end() { _output = nullptr; } void PlainTextDecoder::setRecordLinePositions(bool record) { _recordLinePositions = record; } QList PlainTextDecoder::linePositions() const { return _linePositions; } void PlainTextDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ ) { Q_ASSERT(_output); if (_recordLinePositions && (_output->string() != nullptr)) { int pos = _output->string()->count(); _linePositions << pos; } //TODO should we ignore or respect the LINE_WRAPPED line property? //note: we build up a QString and send it to the text stream rather writing into the text //stream a character at a time because it is more efficient. //(since QTextStream always deals with QStrings internally anyway) QString plainText; plainText.reserve(count); // If we should remove leading whitespace find the first non-space character int start = 0; if (!_includeLeadingWhitespace) { for (start = 0; start < count; start++) { if (!characters[start].isSpace()) { break; } } } int outputCount = count - start; if (outputCount <= 0) { return; } // if inclusion of trailing whitespace is disabled then find the end of the // line if (!_includeTrailingWhitespace) { for (int i = count - 1 ; i >= start ; i--) { if (!characters[i].isSpace()) { break; } else { outputCount--; } } } // find out the last technically real character in the line int realCharacterGuard = -1; for (int i = count - 1 ; i >= start ; i--) { // FIXME: the special case of '\n' here is really ugly // Maybe the '\n' should be added after calling this method in // Screen::copyLineToStream() if (characters[i].isRealCharacter && characters[i].character != '\n') { realCharacterGuard = i; break; } } for (int i = start; i < outputCount;) { if ((characters[i].rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); if (chars != nullptr) { - const QString s = QString::fromUtf16(chars, extendedCharLength); + const QString s = QString::fromUcs4(chars, extendedCharLength); plainText.append(s); i += qMax(1, string_width(s)); } else { ++i; } } else { // All characters which appear before the last real character are // seen as real characters, even when they are technically marked as // non-real. // // This feels tricky, but otherwise leading "whitespaces" may be // lost in some situation. One typical example is copying the result // of `dialog --infobox "qwe" 10 10` . if (characters[i].isRealCharacter || i <= realCharacterGuard) { - plainText.append(QChar(characters[i].character)); + plainText.append(QString::fromUcs4(&characters[i].character, 1)); i += qMax(1, konsole_wcwidth(characters[i].character)); } else { ++i; // should we 'break' directly here? } } } *_output << plainText; } HTMLDecoder::HTMLDecoder() : _output(nullptr) , _colorTable(ColorScheme::defaultTable) , _innerSpanOpen(false) , _lastRendition(DEFAULT_RENDITION) , _lastForeColor(CharacterColor()) , _lastBackColor(CharacterColor()) { } void HTMLDecoder::begin(QTextStream* output) { _output = output; QString text; //open monospace span openSpan(text, QStringLiteral("font-family:monospace")); *output << text; } void HTMLDecoder::end() { Q_ASSERT(_output); QString text; closeSpan(text); *_output << text; _output = nullptr; } //TODO: Support for LineProperty (mainly double width , double height) void HTMLDecoder::decodeLine(const Character* const characters, int count, LineProperty /*properties*/ ) { Q_ASSERT(_output); QString text; int spaceCount = 0; for (int i = 0; i < count; i++) { //check if appearance of character is different from previous char if (characters[i].rendition != _lastRendition || characters[i].foregroundColor != _lastForeColor || characters[i].backgroundColor != _lastBackColor) { if (_innerSpanOpen) { closeSpan(text); _innerSpanOpen = false; } _lastRendition = characters[i].rendition; _lastForeColor = characters[i].foregroundColor; _lastBackColor = characters[i].backgroundColor; //build up style string QString style; //colors - a color table must have been defined first if (_colorTable != nullptr) { bool useBold = (_lastRendition & RE_BOLD) != 0; if (useBold) { style.append(QLatin1String("font-weight:bold;")); } if ((_lastRendition & RE_UNDERLINE) != 0) { style.append(QLatin1String("font-decoration:underline;")); } style.append(QStringLiteral("color:%1;").arg(_lastForeColor.color(_colorTable).name())); style.append(QStringLiteral("background-color:%1;").arg(_lastBackColor.color(_colorTable).name())); } //open the span with the current style openSpan(text, style); _innerSpanOpen = true; } //handle whitespace if (characters[i].isSpace()) { spaceCount++; } else { spaceCount = 0; } //output current character if (spaceCount < 2) { if ((characters[i].rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(characters[i].character, extendedCharLength); if (chars != nullptr) { - text.append(QString::fromUtf16(chars, extendedCharLength)); + text.append(QString::fromUcs4(chars, extendedCharLength)); } } else { //escape HTML tag characters and just display others as they are const QChar ch = characters[i].character; if (ch == QLatin1Char('<')) { text.append(QLatin1String("<")); } else if (ch == QLatin1Char('>')) { text.append(QLatin1String(">")); } else if (ch == QLatin1Char('&')) { text.append(QLatin1String("&")); } else { text.append(ch); } } } else { // HTML truncates multiple spaces, so use a space marker instead // Use   instead of   so xmllint will work. text.append(QLatin1String(" ")); } } //close any remaining open inner spans if (_innerSpanOpen) { closeSpan(text); _innerSpanOpen = false; } //start new line text.append(QLatin1String("
")); *_output << text; } void HTMLDecoder::openSpan(QString& text , const QString& style) { text.append(QStringLiteral("").arg(style)); } void HTMLDecoder::closeSpan(QString& text) { text.append(QLatin1String("")); } void HTMLDecoder::setColorTable(const ColorEntry* table) { _colorTable = table; } diff --git a/src/TerminalDisplay.cpp b/src/TerminalDisplay.cpp index bc4487c5..d44c9d40 100644 --- a/src/TerminalDisplay.cpp +++ b/src/TerminalDisplay.cpp @@ -1,3927 +1,3929 @@ /* This file is part of Konsole, a terminal emulator for KDE. Copyright 2006-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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 "TerminalDisplay.h" // Config #include // Qt #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include // KDE #include #include #include #include #include #include #include #include #include #include // Konsole #include "Filter.h" #include "konsoledebug.h" #include "konsole_wcwidth.h" #include "TerminalCharacterDecoder.h" #include "Screen.h" #include "LineFont.h" #include "SessionController.h" #include "ExtendedCharTable.h" #include "TerminalDisplayAccessible.h" #include "SessionManager.h" #include "Session.h" #include "WindowSystemInfo.h" using namespace Konsole; #ifndef loc #define loc(X,Y) ((Y)*_columns+(X)) #endif #define REPCHAR "ABCDEFGHIJKLMNOPQRSTUVWXYZ" \ "abcdefgjijklmnopqrstuvwxyz" \ "0123456789./+@" // we use this to force QPainter to display text in LTR mode // more information can be found in: http://unicode.org/reports/tr9/ const QChar LTR_OVERRIDE_CHAR(0x202D); /* ------------------------------------------------------------------------- */ /* */ /* Colors */ /* */ /* ------------------------------------------------------------------------- */ /* Note that we use ANSI color order (bgr), while IBMPC color order is (rgb) Code 0 1 2 3 4 5 6 7 ----------- ------- ------- ------- ------- ------- ------- ------- ------- ANSI (bgr) Black Red Green Yellow Blue Magenta Cyan White IBMPC (rgb) Black Blue Green Cyan Red Magenta Yellow White */ ScreenWindow* TerminalDisplay::screenWindow() const { return _screenWindow; } void TerminalDisplay::setScreenWindow(ScreenWindow* window) { // disconnect existing screen window if any if (!_screenWindow.isNull()) { disconnect(_screenWindow , nullptr , this , nullptr); } _screenWindow = window; if (!_screenWindow.isNull()) { connect(_screenWindow.data() , &Konsole::ScreenWindow::outputChanged , this , &Konsole::TerminalDisplay::updateLineProperties); connect(_screenWindow.data() , &Konsole::ScreenWindow::outputChanged , this , &Konsole::TerminalDisplay::updateImage); connect(_screenWindow.data() , &Konsole::ScreenWindow::currentResultLineChanged , this , &Konsole::TerminalDisplay::updateImage); connect(_screenWindow.data(), &Konsole::ScreenWindow::outputChanged, this, [this]() { _filterUpdateRequired = true; }); connect(_screenWindow.data(), &Konsole::ScreenWindow::scrolled, this, [this]() { _filterUpdateRequired = true; }); _screenWindow->setWindowLines(_lines); } } const ColorEntry* TerminalDisplay::colorTable() const { return _colorTable; } void TerminalDisplay::updateScrollBarPalette() { QColor backgroundColor = _colorTable[DEFAULT_BACK_COLOR]; backgroundColor.setAlphaF(_opacity); QPalette p = palette(); p.setColor(QPalette::Window, backgroundColor); //this is a workaround to add some readability to old themes like Fusion //changing the light value for button a bit makes themes like fusion, windows and oxygen way more readable and pleasing QColor buttonColor; buttonColor.setHsvF(backgroundColor.hueF(), backgroundColor.saturationF(), backgroundColor.valueF() + (backgroundColor.valueF() < 0.5 ? 0.2 : -0.2)); p.setColor(QPalette::Button, buttonColor); p.setColor(QPalette::WindowText, _colorTable[DEFAULT_FORE_COLOR]); p.setColor(QPalette::ButtonText, _colorTable[DEFAULT_FORE_COLOR]); _scrollBar->setPalette(p); } void TerminalDisplay::setBackgroundColor(const QColor& color) { _colorTable[DEFAULT_BACK_COLOR] = color; QPalette p = palette(); p.setColor(backgroundRole(), color); setPalette(p); updateScrollBarPalette(); update(); } QColor TerminalDisplay::getBackgroundColor() const { QPalette p = palette(); return p.color(backgroundRole()); } void TerminalDisplay::setForegroundColor(const QColor& color) { _colorTable[DEFAULT_FORE_COLOR] = color; updateScrollBarPalette(); update(); } void TerminalDisplay::setColorTable(const ColorEntry table[]) { for (int i = 0; i < TABLE_COLORS; i++) { _colorTable[i] = table[i]; } setBackgroundColor(_colorTable[DEFAULT_BACK_COLOR]); } /* ------------------------------------------------------------------------- */ /* */ /* Font */ /* */ /* ------------------------------------------------------------------------- */ static inline bool isLineCharString(const QString& string) { if (string.length() == 0) { return false; } return isSupportedLineChar(string.at(0).unicode()); } void TerminalDisplay::fontChange(const QFont&) { QFontMetrics fm(font()); _fontHeight = fm.height() + _lineSpacing; // waba TerminalDisplay 1.123: // "Base character width on widest ASCII character. This prevents too wide // characters in the presence of double wide (e.g. Japanese) characters." // Get the width from representative normal width characters _fontWidth = qRound((static_cast(fm.width(QStringLiteral(REPCHAR))) / static_cast(qstrlen(REPCHAR)))); _fixedFont = true; const int fw = fm.width(QLatin1Char(REPCHAR[0])); for (unsigned int i = 1; i < qstrlen(REPCHAR); i++) { if (fw != fm.width(QLatin1Char(REPCHAR[i]))) { _fixedFont = false; break; } } if (_fontWidth < 1) { _fontWidth = 1; } _fontAscent = fm.ascent(); emit changedFontMetricSignal(_fontHeight, _fontWidth); propagateSize(); update(); } void TerminalDisplay::setVTFont(const QFont& f) { QFont newFont(f); // In case the provided font doesn't have some specific characters it should // fall back to a Monospace fonts. newFont.setStyleHint(QFont::TypeWriter); QFontMetrics fontMetrics(newFont); // This check seems extreme and semi-random if ((fontMetrics.height() > height()) || (fontMetrics.maxWidth() > width())) { return; } // hint that text should be drawn without anti-aliasing. // depending on the user's font configuration, this may not be respected if (!_antialiasText) { newFont.setStyleStrategy(QFont::StyleStrategy(newFont.styleStrategy() | QFont::NoAntialias)); } // experimental optimization. Konsole assumes that the terminal is using a // mono-spaced font, in which case kerning information should have an effect. // Disabling kerning saves some computation when rendering text. newFont.setKerning(false); // Konsole cannot handle non-integer font metrics newFont.setStyleStrategy(QFont::StyleStrategy(newFont.styleStrategy() | QFont::ForceIntegerMetrics)); QFontInfo fontInfo(newFont); // if (!fontInfo.fixedPitch()) { // qWarning() << "Using a variable-width font - this might cause display problems"; // } // QFontInfo::fixedPitch() appears to not match QFont::fixedPitch() // related? https://bugreports.qt.io/browse/QTBUG-34082 if (!fontInfo.exactMatch()) { const QChar comma(QLatin1Char(',')); QString nonMatching = fontInfo.family() % comma % QString::number(fontInfo.pointSizeF()) % comma % QString::number(fontInfo.pixelSize()) % comma % QString::number(static_cast(fontInfo.styleHint())) % comma % QString::number(fontInfo.weight()) % comma % QString::number(static_cast(fontInfo.style())) % comma % QString::number(static_cast(fontInfo.underline())) % comma % QString::number(static_cast(fontInfo.strikeOut())) % comma % QString::number(static_cast(fontInfo.fixedPitch())) % comma % QString::number(static_cast(fontInfo.rawMode())); qCDebug(KonsoleDebug) << "The font to use in the terminal can not be matched exactly on your system."; qCDebug(KonsoleDebug)<<" Selected: "<(object)) { return new TerminalDisplayAccessible(display); } return nullptr; } #endif } /* ------------------------------------------------------------------------- */ /* */ /* Constructor / Destructor */ /* */ /* ------------------------------------------------------------------------- */ TerminalDisplay::TerminalDisplay(QWidget* parent) : QWidget(parent) , _screenWindow(nullptr) , _bellMasked(false) , _verticalLayout(new QVBoxLayout(this)) , _fixedFont(true) , _fontHeight(1) , _fontWidth(1) , _fontAscent(1) , _boldIntense(true) , _lines(1) , _columns(1) , _usedLines(1) , _usedColumns(1) , _contentRect(QRect()) , _image(nullptr) , _imageSize(0) , _lineProperties(QVector()) , _randomSeed(0) , _resizing(false) , _showTerminalSizeHint(true) , _bidiEnabled(false) , _mouseMarks(false) , _alternateScrolling(true) , _isPrimaryScreen(true) , _bracketedPasteMode(false) , _iPntSel(QPoint()) , _pntSel(QPoint()) , _tripleSelBegin(QPoint()) , _actSel(0) , _wordSelectionMode(false) , _lineSelectionMode(false) , _preserveLineBreaks(true) , _columnSelectionMode(false) , _autoCopySelectedText(false) , _copyTextAsHTML(true) , _middleClickPasteMode(Enum::PasteFromX11Selection) , _scrollBar(nullptr) , _scrollbarLocation(Enum::ScrollBarRight) , _scrollFullPage(false) , _wordCharacters(QStringLiteral(":@-./_~")) , _bellMode(Enum::NotifyBell) , _allowBlinkingText(true) , _allowBlinkingCursor(false) , _textBlinking(false) , _cursorBlinking(false) , _hasTextBlinker(false) , _urlHintsModifiers(Qt::NoModifier) , _showUrlHint(false) , _openLinksByDirectClick(false) , _ctrlRequiredForDrag(true) , _dropUrlsAsText(false) , _tripleClickMode(Enum::SelectWholeLine) , _possibleTripleClick(false) , _resizeWidget(nullptr) , _resizeTimer(nullptr) , _flowControlWarningEnabled(false) , _outputSuspendedMessageWidget(nullptr) , _lineSpacing(0) , _size(QSize()) , _blendColor(qRgba(0, 0, 0, 0xff)) , _wallpaper(nullptr) , _filterChain(new TerminalImageFilterChain()) , _mouseOverHotspotArea(QRegion()) , _filterUpdateRequired(true) , _cursorShape(Enum::BlockCursor) , _cursorColor(QColor()) , _antialiasText(true) , _useFontLineCharacters(false) , _printerFriendly(false) , _sessionController(nullptr) , _trimLeadingSpaces(false) , _trimTrailingSpaces(false) , _mouseWheelZoom(false) , _margin(1) , _centerContents(false) , _readOnlyMessageWidget(nullptr) , _readOnly(false) , _opacity(1.0) , _scrollWheelState(ScrollState()) { // terminal applications are not designed with Right-To-Left in mind, // so the layout is forced to Left-To-Right setLayoutDirection(Qt::LeftToRight); _contentRect = QRect(_margin, _margin, 1, 1); // create scroll bar for scrolling output up and down _scrollBar = new QScrollBar(this); _scrollBar->setAutoFillBackground(false); // set the scroll bar's slider to occupy the whole area of the scroll bar initially setScroll(0, 0); _scrollBar->setCursor(Qt::ArrowCursor); connect(_scrollBar, &QScrollBar::valueChanged, this, &Konsole::TerminalDisplay::scrollBarPositionChanged); connect(_scrollBar, &QScrollBar::sliderMoved, this, &Konsole::TerminalDisplay::viewScrolledByUser); // setup timers for blinking text _blinkTextTimer = new QTimer(this); _blinkTextTimer->setInterval(TEXT_BLINK_DELAY); connect(_blinkTextTimer, &QTimer::timeout, this, &Konsole::TerminalDisplay::blinkTextEvent); // setup timers for blinking cursor _blinkCursorTimer = new QTimer(this); _blinkCursorTimer->setInterval(QApplication::cursorFlashTime() / 2); connect(_blinkCursorTimer, &QTimer::timeout, this, &Konsole::TerminalDisplay::blinkCursorEvent); // hide mouse cursor on keystroke or idle KCursor::setAutoHideCursor(this, true); setMouseTracking(true); setUsesMouse(true); setBracketedPasteMode(false); setColorTable(ColorScheme::defaultTable); // Enable drag and drop support setAcceptDrops(true); _dragInfo.state = diNone; setFocusPolicy(Qt::WheelFocus); // enable input method support setAttribute(Qt::WA_InputMethodEnabled, true); // this is an important optimization, it tells Qt // that TerminalDisplay will handle repainting its entire area. setAttribute(Qt::WA_OpaquePaintEvent); // Add the stretch item once, the KMessageWidgets are inserted at index 0. _verticalLayout->addStretch(); _verticalLayout->setSpacing(0); setLayout(_verticalLayout); // Take the scrollbar into account and add a margin to the layout. Without the timer the scrollbar width // is garbage. QTimer::singleShot(0, this, [this]() { const int scrollBarWidth = _scrollBar->isVisible() ? geometry().intersected(_scrollBar->geometry()).width() : 0; _verticalLayout->setContentsMargins(0, 0, scrollBarWidth, 0); }); new AutoScrollHandler(this); #ifndef QT_NO_ACCESSIBILITY QAccessible::installFactory(Konsole::accessibleInterfaceFactory); #endif } TerminalDisplay::~TerminalDisplay() { disconnect(_blinkTextTimer); disconnect(_blinkCursorTimer); delete _readOnlyMessageWidget; delete _outputSuspendedMessageWidget; delete[] _image; delete _filterChain; _readOnlyMessageWidget = nullptr; _outputSuspendedMessageWidget = nullptr; } /* ------------------------------------------------------------------------- */ /* */ /* Display Operations */ /* */ /* ------------------------------------------------------------------------- */ /** A table for emulating the simple (single width) unicode drawing chars. It represents the 250x - 257x glyphs. If it's zero, we can't use it. if it's not, it's encoded as follows: imagine a 5x5 grid where the points are numbered 0 to 24 left to top, top to bottom. Each point is represented by the corresponding bit. Then, the pixels basically have the following interpretation: _|||_ -...- -...- -...- _|||_ where _ = none | = vertical line. - = horizontal line. */ enum LineEncode { TopL = (1 << 1), TopC = (1 << 2), TopR = (1 << 3), LeftT = (1 << 5), Int11 = (1 << 6), Int12 = (1 << 7), Int13 = (1 << 8), RightT = (1 << 9), LeftC = (1 << 10), Int21 = (1 << 11), Int22 = (1 << 12), Int23 = (1 << 13), RightC = (1 << 14), LeftB = (1 << 15), Int31 = (1 << 16), Int32 = (1 << 17), Int33 = (1 << 18), RightB = (1 << 19), BotL = (1 << 21), BotC = (1 << 22), BotR = (1 << 23) }; static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code) { //Calculate cell midpoints, end points. const int cx = x + w / 2; const int cy = y + h / 2; const int ex = x + w - 1; const int ey = y + h - 1; const quint32 toDraw = LineChars[code]; //Top _lines: if ((toDraw & TopL) != 0u) { paint.drawLine(cx - 1, y, cx - 1, cy - 2); } if ((toDraw & TopC) != 0u) { paint.drawLine(cx, y, cx, cy - 2); } if ((toDraw & TopR) != 0u) { paint.drawLine(cx + 1, y, cx + 1, cy - 2); } //Bot _lines: if ((toDraw & BotL) != 0u) { paint.drawLine(cx - 1, cy + 2, cx - 1, ey); } if ((toDraw & BotC) != 0u) { paint.drawLine(cx, cy + 2, cx, ey); } if ((toDraw & BotR) != 0u) { paint.drawLine(cx + 1, cy + 2, cx + 1, ey); } //Left _lines: if ((toDraw & LeftT) != 0u) { paint.drawLine(x, cy - 1, cx - 2, cy - 1); } if ((toDraw & LeftC) != 0u) { paint.drawLine(x, cy, cx - 2, cy); } if ((toDraw & LeftB) != 0u) { paint.drawLine(x, cy + 1, cx - 2, cy + 1); } //Right _lines: if ((toDraw & RightT) != 0u) { paint.drawLine(cx + 2, cy - 1, ex, cy - 1); } if ((toDraw & RightC) != 0u) { paint.drawLine(cx + 2, cy, ex, cy); } if ((toDraw & RightB) != 0u) { paint.drawLine(cx + 2, cy + 1, ex, cy + 1); } //Intersection points. if ((toDraw & Int11) != 0u) { paint.drawPoint(cx - 1, cy - 1); } if ((toDraw & Int12) != 0u) { paint.drawPoint(cx, cy - 1); } if ((toDraw & Int13) != 0u) { paint.drawPoint(cx + 1, cy - 1); } if ((toDraw & Int21) != 0u) { paint.drawPoint(cx - 1, cy); } if ((toDraw & Int22) != 0u) { paint.drawPoint(cx, cy); } if ((toDraw & Int23) != 0u) { paint.drawPoint(cx + 1, cy); } if ((toDraw & Int31) != 0u) { paint.drawPoint(cx - 1, cy + 1); } if ((toDraw & Int32) != 0u) { paint.drawPoint(cx, cy + 1); } if ((toDraw & Int33) != 0u) { paint.drawPoint(cx + 1, cy + 1); } } static void drawOtherChar(QPainter& paint, int x, int y, int w, int h, uchar code) { //Calculate cell midpoints, end points. const int cx = x + w / 2; const int cy = y + h / 2; const int ex = x + w - 1; const int ey = y + h - 1; // Double dashes if (0x4C <= code && code <= 0x4F) { const int xHalfGap = qMax(w / 15, 1); const int yHalfGap = qMax(h / 15, 1); switch (code) { case 0x4D: // BOX DRAWINGS HEAVY DOUBLE DASH HORIZONTAL paint.drawLine(x, cy - 1, cx - xHalfGap - 1, cy - 1); paint.drawLine(x, cy + 1, cx - xHalfGap - 1, cy + 1); paint.drawLine(cx + xHalfGap, cy - 1, ex, cy - 1); paint.drawLine(cx + xHalfGap, cy + 1, ex, cy + 1); // No break! #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)) Q_FALLTHROUGH(); #endif case 0x4C: // BOX DRAWINGS LIGHT DOUBLE DASH HORIZONTAL paint.drawLine(x, cy, cx - xHalfGap - 1, cy); paint.drawLine(cx + xHalfGap, cy, ex, cy); break; case 0x4F: // BOX DRAWINGS HEAVY DOUBLE DASH VERTICAL paint.drawLine(cx - 1, y, cx - 1, cy - yHalfGap - 1); paint.drawLine(cx + 1, y, cx + 1, cy - yHalfGap - 1); paint.drawLine(cx - 1, cy + yHalfGap, cx - 1, ey); paint.drawLine(cx + 1, cy + yHalfGap, cx + 1, ey); // No break! #if (QT_VERSION >= QT_VERSION_CHECK(5, 8, 0)) Q_FALLTHROUGH(); #endif case 0x4E: // BOX DRAWINGS LIGHT DOUBLE DASH VERTICAL paint.drawLine(cx, y, cx, cy - yHalfGap - 1); paint.drawLine(cx, cy + yHalfGap, cx, ey); break; } } // Rounded corner characters else if (0x6D <= code && code <= 0x70) { const int r = w * 3 / 8; const int d = 2 * r; switch (code) { case 0x6D: // BOX DRAWINGS LIGHT ARC DOWN AND RIGHT paint.drawLine(cx, cy + r, cx, ey); paint.drawLine(cx + r, cy, ex, cy); paint.drawArc(cx, cy, d, d, 90 * 16, 90 * 16); break; case 0x6E: // BOX DRAWINGS LIGHT ARC DOWN AND LEFT paint.drawLine(cx, cy + r, cx, ey); paint.drawLine(x, cy, cx - r, cy); paint.drawArc(cx - d, cy, d, d, 0 * 16, 90 * 16); break; case 0x6F: // BOX DRAWINGS LIGHT ARC UP AND LEFT paint.drawLine(cx, y, cx, cy - r); paint.drawLine(x, cy, cx - r, cy); paint.drawArc(cx - d, cy - d, d, d, 270 * 16, 90 * 16); break; case 0x70: // BOX DRAWINGS LIGHT ARC UP AND RIGHT paint.drawLine(cx, y, cx, cy - r); paint.drawLine(cx + r, cy, ex, cy); paint.drawArc(cx, cy - d, d, d, 180 * 16, 90 * 16); break; } } // Diagonals else if (0x71 <= code && code <= 0x73) { switch (code) { case 0x71: // BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT paint.drawLine(ex, y, x, ey); break; case 0x72: // BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT paint.drawLine(x, y, ex, ey); break; case 0x73: // BOX DRAWINGS LIGHT DIAGONAL CROSS paint.drawLine(ex, y, x, ey); paint.drawLine(x, y, ex, ey); break; } } } void TerminalDisplay::drawLineCharString(QPainter& painter, int x, int y, const QString& str, const Character* attributes) { const QPen& originalPen = painter.pen(); if (((attributes->rendition & RE_BOLD) != 0) && _boldIntense) { QPen boldPen(originalPen); boldPen.setWidth(3); painter.setPen(boldPen); } for (int i = 0 ; i < str.length(); i++) { const uchar code = str[i].cell(); if (LineChars[code] != 0u) { drawLineChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code); } else { drawOtherChar(painter, x + (_fontWidth * i), y, _fontWidth, _fontHeight, code); } } painter.setPen(originalPen); } void TerminalDisplay::setKeyboardCursorShape(Enum::CursorShapeEnum shape) { _cursorShape = shape; } Enum::CursorShapeEnum TerminalDisplay::keyboardCursorShape() const { return _cursorShape; } void TerminalDisplay::setCursorStyle(Enum::CursorShapeEnum shape, bool isBlinking) { setKeyboardCursorShape(shape); setBlinkingCursorEnabled(isBlinking); // when the cursor shape and blinking state are changed via the // Set Cursor Style (DECSCUSR) escape sequences in vim, and if the // cursor isn't set to blink, the cursor shape doesn't actually // change until the cursor is moved by the user; calling update() // makes the cursor shape get updated sooner. if (!isBlinking) { update(); } } void TerminalDisplay::resetCursorStyle() { if (sessionController() != nullptr) { Profile::Ptr currentProfile = SessionManager::instance()->sessionProfile(sessionController()->session()); if (currentProfile != nullptr) { Enum::CursorShapeEnum shape = static_cast(currentProfile->property(Profile::CursorShape)); setKeyboardCursorShape(shape); setBlinkingCursorEnabled(currentProfile->blinkingCursorEnabled()); } } } void TerminalDisplay::setKeyboardCursorColor(const QColor& color) { _cursorColor = color; } QColor TerminalDisplay::keyboardCursorColor() const { return _cursorColor; } void TerminalDisplay::setOpacity(qreal opacity) { QColor color(_blendColor); color.setAlphaF(opacity); _opacity = opacity; // enable automatic background filling to prevent the display // flickering if there is no transparency /*if ( color.alpha() == 255 ) { setAutoFillBackground(true); } else { setAutoFillBackground(false); }*/ _blendColor = color.rgba(); updateScrollBarPalette(); } void TerminalDisplay::setWallpaper(ColorSchemeWallpaper::Ptr p) { _wallpaper = p; } void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const QColor& backgroundColor, bool useOpacitySetting) { // the area of the widget showing the contents of the terminal display is drawn // using the background color from the color scheme set with setColorTable() // // the area of the widget behind the scroll-bar is drawn using the background // brush from the scroll-bar's palette, to give the effect of the scroll-bar // being outside of the terminal display and visual consistency with other KDE // applications. if (useOpacitySetting && !_wallpaper->isNull() && _wallpaper->draw(painter, rect, _opacity)) { } else if (qAlpha(_blendColor) < 0xff && useOpacitySetting) { #if defined(Q_OS_MACOS) // TODO - On MacOS, using CompositionMode doesn't work. Altering the // transparency in the color scheme alters the brightness. painter.fillRect(rect, backgroundColor); #else QColor color(backgroundColor); color.setAlpha(qAlpha(_blendColor)); painter.save(); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect(rect, color); painter.restore(); #endif } else { painter.fillRect(rect, backgroundColor); } } void TerminalDisplay::drawCursor(QPainter& painter, const QRect& rect, const QColor& foregroundColor, const QColor& /*backgroundColor*/, bool& invertCharacterColor) { // don't draw cursor which is currently blinking if (_cursorBlinking) { return; } // shift rectangle top down one pixel to leave some space // between top and bottom QRect cursorRect = rect.adjusted(0, 1, 0, 0); QColor cursorColor = _cursorColor.isValid() ? _cursorColor : foregroundColor; painter.setPen(cursorColor); if (_cursorShape == Enum::BlockCursor) { // draw the cursor outline, adjusting the area so that // it is draw entirely inside 'rect' int penWidth = qMax(1, painter.pen().width()); painter.drawRect(cursorRect.adjusted(penWidth / 2, penWidth / 2, - penWidth / 2 - penWidth % 2, - penWidth / 2 - penWidth % 2)); // draw the cursor body only when the widget has focus if (hasFocus()) { painter.fillRect(cursorRect, cursorColor); if (!_cursorColor.isValid()) { // invert the color used to draw the text to ensure that the character at // the cursor position is readable invertCharacterColor = true; } } } else if (_cursorShape == Enum::UnderlineCursor) { painter.drawLine(cursorRect.left(), cursorRect.bottom(), cursorRect.right(), cursorRect.bottom()); } else if (_cursorShape == Enum::IBeamCursor) { painter.drawLine(cursorRect.left(), cursorRect.top(), cursorRect.left(), cursorRect.bottom()); } } void TerminalDisplay::drawCharacters(QPainter& painter, const QRect& rect, const QString& text, const Character* style, bool invertCharacterColor) { // don't draw text which is currently blinking if (_textBlinking && ((style->rendition & RE_BLINK) != 0)) { return; } // don't draw concealed characters if ((style->rendition & RE_CONCEAL) != 0) { return; } // setup bold and underline bool useBold = (((style->rendition & RE_BOLD) != 0) && _boldIntense) || font().bold(); const bool useUnderline = ((style->rendition & RE_UNDERLINE) != 0) || font().underline(); const bool useItalic = ((style->rendition & RE_ITALIC) != 0) || font().italic(); const bool useStrikeOut = ((style->rendition & RE_STRIKEOUT) != 0) || font().strikeOut(); const bool useOverline = ((style->rendition & RE_OVERLINE) != 0) || font().overline(); QFont font = painter.font(); if (font.bold() != useBold || font.underline() != useUnderline || font.italic() != useItalic || font.strikeOut() != useStrikeOut || font.overline() != useOverline) { font.setBold(useBold); font.setUnderline(useUnderline); font.setItalic(useItalic); font.setStrikeOut(useStrikeOut); font.setOverline(useOverline); painter.setFont(font); } // setup pen const CharacterColor& textColor = (invertCharacterColor ? style->backgroundColor : style->foregroundColor); const QColor color = textColor.color(_colorTable); QPen pen = painter.pen(); if (pen.color() != color) { pen.setColor(color); painter.setPen(color); } // draw text if (isLineCharString(text) && !_useFontLineCharacters) { drawLineCharString(painter, rect.x(), rect.y(), text, style); } else { // Force using LTR as the document layout for the terminal area, because // there is no use cases for RTL emulator and RTL terminal application. // // This still allows RTL characters to be rendered in the RTL way. painter.setLayoutDirection(Qt::LeftToRight); painter.setClipRect(rect); if (_bidiEnabled) { painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, text); } else { painter.drawText(rect.x(), rect.y() + _fontAscent + _lineSpacing, LTR_OVERRIDE_CHAR + text); } painter.setClipping(false); } } void TerminalDisplay::drawTextFragment(QPainter& painter , const QRect& rect, const QString& text, const Character* style) { painter.save(); // setup painter const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); // draw background if different from the display's background color if (backgroundColor != palette().background().color()) { drawBackground(painter, rect, backgroundColor, false /* do not use transparency */); } // draw cursor shape if the current character is the cursor // this may alter the foreground and background colors bool invertCharacterColor = false; if ((style->rendition & RE_CURSOR) != 0) { drawCursor(painter, rect, foregroundColor, backgroundColor, invertCharacterColor); } // draw text drawCharacters(painter, rect, text, style, invertCharacterColor); painter.restore(); } void TerminalDisplay::drawPrinterFriendlyTextFragment(QPainter& painter, const QRect& rect, const QString& text, const Character* style) { painter.save(); // Set the colors used to draw to black foreground and white // background for printer friendly output when printing Character print_style = *style; print_style.foregroundColor = CharacterColor(COLOR_SPACE_RGB, 0x00000000); print_style.backgroundColor = CharacterColor(COLOR_SPACE_RGB, 0xFFFFFFFF); // draw text drawCharacters(painter, rect, text, &print_style, false); painter.restore(); } void TerminalDisplay::setRandomSeed(uint randomSeed) { _randomSeed = randomSeed; } uint TerminalDisplay::randomSeed() const { return _randomSeed; } // scrolls the image by 'lines', down if lines > 0 or up otherwise. // // the terminal emulation keeps track of the scrolling of the character // image as it receives input, and when the view is updated, it calls scrollImage() // with the final scroll amount. this improves performance because scrolling the // display is much cheaper than re-rendering all the text for the // part of the image which has moved up or down. // Instead only new lines have to be drawn void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) { // return if there is nothing to do if ((lines == 0) || (_image == nullptr)) { return; } // if the flow control warning is enabled this will interfere with the // scrolling optimizations and cause artifacts. the simple solution here // is to just disable the optimization whilst it is visible if ((_outputSuspendedMessageWidget != nullptr) && _outputSuspendedMessageWidget->isVisible()) { return; } if ((_readOnlyMessageWidget != nullptr) && _readOnlyMessageWidget->isVisible()) { return; } // constrain the region to the display // the bottom of the region is capped to the number of lines in the display's // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; region.setBottom(qMin(region.bottom(), this->_lines - 2)); // return if there is nothing to do if (!region.isValid() || (region.top() + abs(lines)) >= region.bottom() || this->_lines <= region.height()) { return; } // hide terminal size label to prevent it being scrolled if ((_resizeWidget != nullptr) && _resizeWidget->isVisible()) { _resizeWidget->hide(); } // Note: With Qt 4.4 the left edge of the scrolled area must be at 0 // to get the correct (newly exposed) part of the widget repainted. // // The right edge must be before the left edge of the scroll bar to // avoid triggering a repaint of the entire widget, the distance is // given by SCROLLBAR_CONTENT_GAP // // Set the QT_FLUSH_PAINT environment variable to '1' before starting the // application to monitor repainting. // const int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->width(); const int SCROLLBAR_CONTENT_GAP = 1; QRect scrollRect; if (_scrollbarLocation == Enum::ScrollBarLeft) { scrollRect.setLeft(scrollBarWidth + SCROLLBAR_CONTENT_GAP); scrollRect.setRight(width()); } else { scrollRect.setLeft(0); scrollRect.setRight(width() - scrollBarWidth - SCROLLBAR_CONTENT_GAP); } void* firstCharPos = &_image[ region.top() * this->_columns ]; void* lastCharPos = &_image[(region.top() + abs(lines)) * this->_columns ]; const int top = _contentRect.top() + (region.top() * _fontHeight); const int linesToMove = region.height() - abs(lines); const int bytesToMove = linesToMove * this->_columns * sizeof(Character); Q_ASSERT(linesToMove > 0); Q_ASSERT(bytesToMove > 0); //scroll internal image if (lines > 0) { // check that the memory areas that we are going to move are valid Q_ASSERT((char*)lastCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns))); Q_ASSERT((lines * this->_columns) < _imageSize); //scroll internal image down memmove(firstCharPos , lastCharPos , bytesToMove); //set region of display to scroll scrollRect.setTop(top); } else { // check that the memory areas that we are going to move are valid Q_ASSERT((char*)firstCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns))); //scroll internal image up memmove(lastCharPos , firstCharPos , bytesToMove); //set region of the display to scroll scrollRect.setTop(top + abs(lines) * _fontHeight); } scrollRect.setHeight(linesToMove * _fontHeight); Q_ASSERT(scrollRect.isValid() && !scrollRect.isEmpty()); //scroll the display vertically to match internal _image scroll(0 , _fontHeight * (-lines) , scrollRect); } QRegion TerminalDisplay::hotSpotRegion() const { QRegion region; foreach(Filter::HotSpot * hotSpot , _filterChain->hotSpots()) { QRect r; if (hotSpot->startLine() == hotSpot->endLine()) { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); region |= imageToWidget(r); } else { r.setLeft(hotSpot->startColumn()); r.setTop(hotSpot->startLine()); r.setRight(_columns); r.setBottom(hotSpot->startLine()); region |= imageToWidget(r); for (int line = hotSpot->startLine() + 1 ; line < hotSpot->endLine() ; line++) { r.setLeft(0); r.setTop(line); r.setRight(_columns); r.setBottom(line); region |= imageToWidget(r); } r.setLeft(0); r.setTop(hotSpot->endLine()); r.setRight(hotSpot->endColumn()); r.setBottom(hotSpot->endLine()); region |= imageToWidget(r); } } return region; } void TerminalDisplay::processFilters() { if (_screenWindow.isNull()) { return; } if (!_filterUpdateRequired) { return; } QRegion preUpdateHotSpots = hotSpotRegion(); // use _screenWindow->getImage() here rather than _image because // other classes may call processFilters() when this display's // ScreenWindow emits a scrolled() signal - which will happen before // updateImage() is called on the display and therefore _image is // out of date at this point _filterChain->setImage(_screenWindow->getImage(), _screenWindow->windowLines(), _screenWindow->windowColumns(), _screenWindow->getLineProperties()); _filterChain->process(); QRegion postUpdateHotSpots = hotSpotRegion(); update(preUpdateHotSpots | postUpdateHotSpots); _filterUpdateRequired = false; } void TerminalDisplay::updateImage() { if (_screenWindow.isNull()) { return; } // optimization - scroll the existing image where possible and // avoid expensive text drawing for parts of the image that // can simply be moved up or down // disable this shortcut for transparent konsole with scaled pixels, otherwise we get rendering artefacts, see BUG 350651 if (!(WindowSystemInfo::HAVE_TRANSPARENCY && (qApp->devicePixelRatio() > 1.0)) && _wallpaper->isNull()) { scrollImage(_screenWindow->scrollCount() , _screenWindow->scrollRegion()); _screenWindow->resetScrollCount(); } if (_image == nullptr) { // Create _image. // The emitted changedContentSizeSignal also leads to getImage being recreated, so do this first. updateImageSize(); } Character* const newimg = _screenWindow->getImage(); const int lines = _screenWindow->windowLines(); const int columns = _screenWindow->windowColumns(); setScroll(_screenWindow->currentLine() , _screenWindow->lineCount()); Q_ASSERT(this->_usedLines <= this->_lines); Q_ASSERT(this->_usedColumns <= this->_columns); int y, x, len; const QPoint tL = contentsRect().topLeft(); const int tLx = tL.x(); const int tLy = tL.y(); _hasTextBlinker = false; CharacterColor cf; // undefined const int linesToUpdate = qMin(this->_lines, qMax(0, lines)); const int columnsToUpdate = qMin(this->_columns, qMax(0, columns)); auto dirtyMask = new char[columnsToUpdate + 2]; QRegion dirtyRegion; // debugging variable, this records the number of lines that are found to // be 'dirty' ( ie. have changed from the old _image to the new _image ) and // which therefore need to be repainted int dirtyLineCount = 0; for (y = 0; y < linesToUpdate; ++y) { const Character* currentLine = &_image[y * this->_columns]; const Character* const newLine = &newimg[y * columns]; bool updateLine = false; // The dirty mask indicates which characters need repainting. We also // mark surrounding neighbors dirty, in case the character exceeds // its cell boundaries memset(dirtyMask, 0, columnsToUpdate + 2); for (x = 0 ; x < columnsToUpdate ; ++x) { if (newLine[x] != currentLine[x]) { dirtyMask[x] = 1; } } if (!_resizing) { // not while _resizing, we're expecting a paintEvent for (x = 0; x < columnsToUpdate; ++x) { _hasTextBlinker |= (newLine[x].rendition & RE_BLINK); // Start drawing if this character or the next one differs. // We also take the next one into account to handle the situation // where characters exceed their cell width. if (dirtyMask[x] != 0) { if (newLine[x + 0].character == 0u) { continue; } const bool lineDraw = newLine[x + 0].isLineChar(); const bool doubleWidth = (x + 1 == columnsToUpdate) ? false : (newLine[x + 1].character == 0); const RenditionFlags cr = newLine[x].rendition; const CharacterColor clipboard = newLine[x].backgroundColor; if (newLine[x].foregroundColor != cf) { cf = newLine[x].foregroundColor; } const int lln = columnsToUpdate - x; for (len = 1; len < lln; ++len) { const Character& ch = newLine[x + len]; if (ch.character == 0u) { continue; // Skip trailing part of multi-col chars. } const bool nextIsDoubleWidth = (x + len + 1 == columnsToUpdate) ? false : (newLine[x + len + 1].character == 0); if (ch.foregroundColor != cf || ch.backgroundColor != clipboard || (ch.rendition & ~RE_EXTENDED_CHAR) != (cr & ~RE_EXTENDED_CHAR) || (dirtyMask[x + len] == 0) || ch.isLineChar() != lineDraw || nextIsDoubleWidth != doubleWidth) { break; } } const bool saveFixedFont = _fixedFont; if (lineDraw) { _fixedFont = false; } if (doubleWidth) { _fixedFont = false; } updateLine = true; _fixedFont = saveFixedFont; x += len - 1; } } } //both the top and bottom halves of double height _lines must always be redrawn //although both top and bottom halves contain the same characters, only //the top one is actually //drawn. if (_lineProperties.count() > y) { updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); } // if the characters on the line are different in the old and the new _image // then this line must be repainted. if (updateLine) { dirtyLineCount++; // add the area occupied by this line to the region which needs to be // repainted QRect dirtyRect = QRect(_contentRect.left() + tLx , _contentRect.top() + tLy + _fontHeight * y , _fontWidth * columnsToUpdate , _fontHeight); dirtyRegion |= dirtyRect; } // replace the line of characters in the old _image with the // current line of the new _image memcpy((void*)currentLine, (const void*)newLine, columnsToUpdate * sizeof(Character)); } // if the new _image is smaller than the previous _image, then ensure that the area // outside the new _image is cleared if (linesToUpdate < _usedLines) { dirtyRegion |= QRect(_contentRect.left() + tLx , _contentRect.top() + tLy + _fontHeight * linesToUpdate , _fontWidth * this->_columns , _fontHeight * (_usedLines - linesToUpdate)); } _usedLines = linesToUpdate; if (columnsToUpdate < _usedColumns) { dirtyRegion |= QRect(_contentRect.left() + tLx + columnsToUpdate * _fontWidth , _contentRect.top() + tLy , _fontWidth * (_usedColumns - columnsToUpdate) , _fontHeight * this->_lines); } _usedColumns = columnsToUpdate; dirtyRegion |= _inputMethodData.previousPreeditRect; // update the parts of the display which have changed update(dirtyRegion); if (_allowBlinkingText && _hasTextBlinker && !_blinkTextTimer->isActive()) { _blinkTextTimer->start(); } if (!_hasTextBlinker && _blinkTextTimer->isActive()) { _blinkTextTimer->stop(); _textBlinking = false; } delete[] dirtyMask; #ifndef QT_NO_ACCESSIBILITY QAccessibleEvent dataChangeEvent(this, QAccessible::VisibleDataChanged); QAccessible::updateAccessibility(&dataChangeEvent); QAccessibleTextCursorEvent cursorEvent(this, _usedColumns * screenWindow()->screen()->getCursorY() + screenWindow()->screen()->getCursorX()); QAccessible::updateAccessibility(&cursorEvent); #endif } void TerminalDisplay::showResizeNotification() { if (_showTerminalSizeHint && isVisible()) { if (_resizeWidget == nullptr) { _resizeWidget = new QLabel(i18n("Size: XXX x XXX"), this); _resizeWidget->setMinimumWidth(_resizeWidget->fontMetrics().width(i18n("Size: XXX x XXX"))); _resizeWidget->setMinimumHeight(_resizeWidget->sizeHint().height()); _resizeWidget->setAlignment(Qt::AlignCenter); _resizeWidget->setStyleSheet(QStringLiteral("background-color:palette(window);border-style:solid;border-width:1px;border-color:palette(dark)")); _resizeTimer = new QTimer(this); _resizeTimer->setInterval(SIZE_HINT_DURATION); _resizeTimer->setSingleShot(true); connect(_resizeTimer, &QTimer::timeout, _resizeWidget, &QLabel::hide); } QString sizeStr = i18n("Size: %1 x %2", _columns, _lines); _resizeWidget->setText(sizeStr); _resizeWidget->move((width() - _resizeWidget->width()) / 2, (height() - _resizeWidget->height()) / 2 + 20); _resizeWidget->show(); _resizeTimer->start(); } } void TerminalDisplay::paintEvent(QPaintEvent* pe) { QPainter paint(this); foreach(const QRect & rect, (pe->region() & contentsRect()).rects()) { drawBackground(paint, rect, palette().background().color(), true /* use opacity setting */); drawContents(paint, rect); } drawCurrentResultRect(paint); drawInputMethodPreeditString(paint, preeditRect()); paintFilters(paint); } void TerminalDisplay::printContent(QPainter& painter, bool friendly) { // Reinitialize the font with the printers paint device so the font // measurement calculations will be done correctly QFont savedFont = getVTFont(); QFont font(savedFont, painter.device()); painter.setFont(font); setVTFont(font); QRect rect(0, 0, size().width(), size().height()); _printerFriendly = friendly; if (!friendly) { drawBackground(painter, rect, getBackgroundColor(), true /* use opacity setting */); } drawContents(painter, rect); _printerFriendly = false; setVTFont(savedFont); } QPoint TerminalDisplay::cursorPosition() const { if (!_screenWindow.isNull()) { return _screenWindow->cursorPosition(); } else { return QPoint(0, 0); } } inline bool TerminalDisplay::isCursorOnDisplay() const { return cursorPosition().x() < _columns && cursorPosition().y() < _lines; } FilterChain* TerminalDisplay::filterChain() const { return _filterChain; } void TerminalDisplay::paintFilters(QPainter& painter) { if (_filterUpdateRequired) { return; } // get color of character under mouse and use it to draw // lines for filters QPoint cursorPos = mapFromGlobal(QCursor::pos()); int cursorLine; int cursorColumn; getCharacterPosition(cursorPos, cursorLine, cursorColumn, false); Character cursorCharacter = _image[loc(qMin(cursorColumn, _columns - 1), cursorLine)]; painter.setPen(QPen(cursorCharacter.foregroundColor.color(colorTable()))); // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot int urlNumber = 0; QList spots = _filterChain->hotSpots(); foreach(Filter::HotSpot* spot, spots) { urlNumber++; QRegion region; if (spot->type() == Filter::HotSpot::Link) { QRect r; if (spot->startLine() == spot->endLine()) { r.setCoords(spot->startColumn()*_fontWidth + _contentRect.left(), spot->startLine()*_fontHeight + _contentRect.top(), (spot->endColumn())*_fontWidth + _contentRect.left() - 1, (spot->endLine() + 1)*_fontHeight + _contentRect.top() - 1); region |= r; } else { r.setCoords(spot->startColumn()*_fontWidth + _contentRect.left(), spot->startLine()*_fontHeight + _contentRect.top(), (_columns)*_fontWidth + _contentRect.left() - 1, (spot->startLine() + 1)*_fontHeight + _contentRect.top() - 1); region |= r; for (int line = spot->startLine() + 1 ; line < spot->endLine() ; line++) { r.setCoords(0 * _fontWidth + _contentRect.left(), line * _fontHeight + _contentRect.top(), (_columns)*_fontWidth + _contentRect.left() - 1, (line + 1)*_fontHeight + _contentRect.top() - 1); region |= r; } r.setCoords(0 * _fontWidth + _contentRect.left(), spot->endLine()*_fontHeight + _contentRect.top(), (spot->endColumn())*_fontWidth + _contentRect.left() - 1, (spot->endLine() + 1)*_fontHeight + _contentRect.top() - 1); region |= r; } if (_showUrlHint && urlNumber < 10) { // Position at the beginning of the URL const QVector regionRects = region.rects(); QRect hintRect(regionRects.first()); hintRect.setWidth(r.height()); painter.fillRect(hintRect, QColor(0, 0, 0, 128)); painter.setPen(Qt::white); painter.drawRect(hintRect.adjusted(0, 0, -1, -1)); painter.drawText(hintRect, Qt::AlignCenter, QString::number(urlNumber)); } } for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { int startColumn = 0; int endColumn = _columns - 1; // TODO use number of _columns which are actually // occupied on this line rather than the width of the // display in _columns // Check image size so _image[] is valid (see makeImage) if (endColumn >= _columns || line >= _lines) { break; } // ignore whitespace at the end of the lines while (_image[loc(endColumn, line)].isSpace() && endColumn > 0) { endColumn--; } // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; if (line == spot->startLine()) { startColumn = spot->startColumn(); } if (line == spot->endLine()) { endColumn = spot->endColumn(); } // TODO: resolve this comment with the new margin/center code // subtract one pixel from // the right and bottom so that // we do not overdraw adjacent // hotspots // // subtracting one pixel from all sides also prevents an edge case where // moving the mouse outside a link could still leave it underlined // because the check below for the position of the cursor // finds it on the border of the target area QRect r; r.setCoords(startColumn * _fontWidth + _contentRect.left(), line * _fontHeight + _contentRect.top(), endColumn * _fontWidth + _contentRect.left() - 1, (line + 1)*_fontHeight + _contentRect.top() - 1); // Underline link hotspots if (spot->type() == Filter::HotSpot::Link) { QFontMetrics metrics(font()); // find the baseline (which is the invisible line that the characters in the font sit on, // with some having tails dangling below) const int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that const int underlinePos = baseline + metrics.underlinePos(); if (_showUrlHint || region.contains(mapFromGlobal(QCursor::pos()))) { painter.drawLine(r.left() , underlinePos , r.right() , underlinePos); } // Marker hotspots simply have a transparent rectangular shape // drawn on top of them } else if (spot->type() == Filter::HotSpot::Marker) { //TODO - Do not use a hardcoded color for this const bool isCurrentResultLine = (_screenWindow->currentResultLine() == (spot->startLine() + _screenWindow->currentLine())); QColor color = isCurrentResultLine ? QColor(255, 255, 0, 120) : QColor(255, 0, 0, 120); painter.fillRect(r, color); } } } } inline static bool isRtl(const Character &chr) { - ushort c = 0; + uint c = 0; if ((chr.rendition & RE_EXTENDED_CHAR) == 0) { c = chr.character; } else { ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(chr.character, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(chr.character, extendedCharLength); if (chars != nullptr) { c = chars[0]; } } switch(QChar::direction(c)) { case QChar::DirR: case QChar::DirAL: case QChar::DirRLE: case QChar::DirRLI: case QChar::DirRLO: return true; default: return false; } } void TerminalDisplay::drawContents(QPainter& paint, const QRect& rect) { const QPoint tL = contentsRect().topLeft(); const int tLx = tL.x(); const int tLy = tL.y(); const int lux = qMin(_usedColumns - 1, qMax(0, (rect.left() - tLx - _contentRect.left()) / _fontWidth)); const int luy = qMin(_usedLines - 1, qMax(0, (rect.top() - tLy - _contentRect.top()) / _fontHeight)); const int rlx = qMin(_usedColumns - 1, qMax(0, (rect.right() - tLx - _contentRect.left()) / _fontWidth)); const int rly = qMin(_usedLines - 1, qMax(0, (rect.bottom() - tLy - _contentRect.top()) / _fontHeight)); const int numberOfColumns = _usedColumns; - QString unistr; - unistr.reserve(numberOfColumns); + QVector univec; + univec.reserve(numberOfColumns); for (int y = luy; y <= rly; y++) { int x = lux; if ((_image[loc(lux, y)].character == 0u) && (x != 0)) { x--; // Search for start of multi-column character } for (; x <= rlx; x++) { int len = 1; int p = 0; // reset our buffer to the number of columns int bufferSize = numberOfColumns; - unistr.resize(bufferSize); - QChar *disstrU = unistr.data(); + univec.resize(bufferSize); + uint *disstrU = univec.data(); // is this a single character or a sequence of characters ? if ((_image[loc(x, y)].rendition & RE_EXTENDED_CHAR) != 0) { // sequence of characters ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(_image[loc(x, y)].character, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(_image[loc(x, y)].character, extendedCharLength); if (chars != nullptr) { Q_ASSERT(extendedCharLength > 1); bufferSize += extendedCharLength - 1; - unistr.resize(bufferSize); - disstrU = unistr.data(); + univec.resize(bufferSize); + disstrU = univec.data(); for (int index = 0 ; index < extendedCharLength ; index++) { Q_ASSERT(p < bufferSize); disstrU[p++] = chars[index]; } } } else { // single character - const quint16 c = _image[loc(x, y)].character; + const uint c = _image[loc(x, y)].character; if (c != 0u) { Q_ASSERT(p < bufferSize); - disstrU[p++] = c; //fontMap(c); + disstrU[p++] = c; } } const bool lineDraw = _image[loc(x, y)].isLineChar(); const bool doubleWidth = (_image[qMin(loc(x, y) + 1, _imageSize - 1)].character == 0); const CharacterColor currentForeground = _image[loc(x, y)].foregroundColor; const CharacterColor currentBackground = _image[loc(x, y)].backgroundColor; const RenditionFlags currentRendition = _image[loc(x, y)].rendition; const bool rtl = isRtl(_image[loc(x, y)]); if(_image[loc(x, y)].character <= 0x7e || rtl) { while (x + len <= rlx && _image[loc(x + len, y)].foregroundColor == currentForeground && _image[loc(x + len, y)].backgroundColor == currentBackground && (_image[loc(x + len, y)].rendition & ~RE_EXTENDED_CHAR) == (currentRendition & ~RE_EXTENDED_CHAR) && (_image[qMin(loc(x + len, y) + 1, _imageSize - 1)].character == 0) == doubleWidth && _image[loc(x + len, y)].isLineChar() == lineDraw && (_image[loc(x + len, y)].character <= 0x7e || rtl)) { - const quint16 c = _image[loc(x + len, y)].character; + const uint c = _image[loc(x + len, y)].character; if ((_image[loc(x + len, y)].rendition & RE_EXTENDED_CHAR) != 0) { // sequence of characters ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(c, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(c, extendedCharLength); if (chars != nullptr) { Q_ASSERT(extendedCharLength > 1); bufferSize += extendedCharLength - 1; - unistr.resize(bufferSize); - disstrU = unistr.data(); + univec.resize(bufferSize); + disstrU = univec.data(); for (int index = 0 ; index < extendedCharLength ; index++) { Q_ASSERT(p < bufferSize); disstrU[p++] = chars[index]; } } } else { // single character if (c != 0u) { Q_ASSERT(p < bufferSize); - disstrU[p++] = c; //fontMap(c); + disstrU[p++] = c; } } if (doubleWidth) { // assert((_image[loc(x+len,y)+1].character == 0)), see above if condition len++; // Skip trailing part of multi-column character } len++; } } if ((x + len < _usedColumns) && (_image[loc(x + len, y)].character == 0u)) { len++; // Adjust for trailing part of multi-column character } const bool save__fixedFont = _fixedFont; if (lineDraw) { _fixedFont = false; } if (doubleWidth) { _fixedFont = false; } - unistr.resize(p); + univec.resize(p); // Create a text scaling matrix for double width and double height lines. QMatrix textScale; if (y < _lineProperties.size()) { if ((_lineProperties[y] & LINE_DOUBLEWIDTH) != 0) { textScale.scale(2, 1); } if ((_lineProperties[y] & LINE_DOUBLEHEIGHT) != 0) { textScale.scale(1, 2); } } //Apply text scaling matrix. paint.setWorldMatrix(textScale, true); //calculate the area in which the text will be drawn QRect textArea = QRect(_contentRect.left() + tLx + _fontWidth * x , _contentRect.top() + tLy + _fontHeight * y , _fontWidth * len , _fontHeight); //move the calculated area to take account of scaling applied to the painter. //the position of the area from the origin (0,0) is scaled //by the opposite of whatever //transformation has been applied to the painter. this ensures that //painting does actually start from textArea.topLeft() //(instead of textArea.topLeft() * painter-scale) textArea.moveTopLeft(textScale.inverted().map(textArea.topLeft())); + QString unistr = QString::fromUcs4(univec.data(), univec.length()); + //paint text fragment if (_printerFriendly) { drawPrinterFriendlyTextFragment(paint, textArea, unistr, &_image[loc(x, y)]); } else { drawTextFragment(paint, textArea, unistr, &_image[loc(x, y)]); } _fixedFont = save__fixedFont; //reset back to single-width, single-height _lines paint.setWorldMatrix(textScale.inverted(), true); if (y < _lineProperties.size() - 1) { //double-height _lines are represented by two adjacent _lines //containing the same characters //both _lines will have the LINE_DOUBLEHEIGHT attribute. //If the current line has the LINE_DOUBLEHEIGHT attribute, //we can therefore skip the next line if ((_lineProperties[y] & LINE_DOUBLEHEIGHT) != 0) { y++; } } x += len - 1; } } } void TerminalDisplay::drawCurrentResultRect(QPainter& painter) { if(_screenWindow->currentResultLine() == -1) { return; } QRect r(0, _contentRect.top() + (_screenWindow->currentResultLine() - _screenWindow->currentLine()) * _fontHeight, contentsRect().width(), _fontHeight); painter.fillRect(r, QColor(0, 0, 255, 80)); } QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const { QRect result; result.setLeft(_contentRect.left() + _fontWidth * imageArea.left()); result.setTop(_contentRect.top() + _fontHeight * imageArea.top()); result.setWidth(_fontWidth * imageArea.width()); result.setHeight(_fontHeight * imageArea.height()); return result; } /* ------------------------------------------------------------------------- */ /* */ /* Blinking Text & Cursor */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::setBlinkingCursorEnabled(bool blink) { _allowBlinkingCursor = blink; if (blink && !_blinkCursorTimer->isActive()) { _blinkCursorTimer->start(); } if (!blink && _blinkCursorTimer->isActive()) { _blinkCursorTimer->stop(); if (_cursorBlinking) { // if cursor is blinking(hidden), blink it again to make it show blinkCursorEvent(); } Q_ASSERT(!_cursorBlinking); } } void TerminalDisplay::setBlinkingTextEnabled(bool blink) { _allowBlinkingText = blink; if (blink && !_blinkTextTimer->isActive()) { _blinkTextTimer->start(); } if (!blink && _blinkTextTimer->isActive()) { _blinkTextTimer->stop(); _textBlinking = false; } } void TerminalDisplay::focusOutEvent(QFocusEvent*) { // trigger a repaint of the cursor so that it is both: // // * visible (in case it was hidden during blinking) // * drawn in a focused out state _cursorBlinking = false; updateCursor(); // suppress further cursor blinking _blinkCursorTimer->stop(); Q_ASSERT(!_cursorBlinking); // if text is blinking (hidden), blink it again to make it shown if (_textBlinking) { blinkTextEvent(); } // suppress further text blinking _blinkTextTimer->stop(); Q_ASSERT(!_textBlinking); _showUrlHint = false; emit focusLost(); } void TerminalDisplay::focusInEvent(QFocusEvent*) { if (_allowBlinkingCursor) { _blinkCursorTimer->start(); } updateCursor(); if (_allowBlinkingText && _hasTextBlinker) { _blinkTextTimer->start(); } emit focusGained(); } void TerminalDisplay::blinkTextEvent() { Q_ASSERT(_allowBlinkingText); _textBlinking = !_textBlinking; // TODO: Optimize to only repaint the areas of the widget where there is // blinking text rather than repainting the whole widget. update(); } void TerminalDisplay::blinkCursorEvent() { Q_ASSERT(_allowBlinkingCursor); _cursorBlinking = !_cursorBlinking; updateCursor(); } void TerminalDisplay::updateCursor() { if (!isCursorOnDisplay()){ return; } const int cursorLocation = loc(cursorPosition().x(), cursorPosition().y()); Q_ASSERT(cursorLocation < _imageSize); int charWidth = konsole_wcwidth(_image[cursorLocation].character); QRect cursorRect = imageToWidget(QRect(cursorPosition(), QSize(charWidth, 1))); update(cursorRect); } /* ------------------------------------------------------------------------- */ /* */ /* Geometry & Resizing */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::resizeEvent(QResizeEvent*) { if (contentsRect().isValid()) { updateImageSize(); } } void TerminalDisplay::propagateSize() { if (_image != nullptr) { updateImageSize(); } } void TerminalDisplay::updateImageSize() { Character* oldImage = _image; const int oldLines = _lines; const int oldColumns = _columns; makeImage(); if (oldImage != nullptr) { // copy the old image to reduce flicker int lines = qMin(oldLines, _lines); int columns = qMin(oldColumns, _columns); for (int line = 0; line < lines; line++) { memcpy((void*)&_image[_columns * line], (void*)&oldImage[oldColumns * line], columns * sizeof(Character)); } delete[] oldImage; } if (!_screenWindow.isNull()) { _screenWindow->setWindowLines(_lines); } _resizing = (oldLines != _lines) || (oldColumns != _columns); if (_resizing) { showResizeNotification(); emit changedContentSizeSignal(_contentRect.height(), _contentRect.width()); // expose resizeEvent } _resizing = false; } void TerminalDisplay::makeImage() { _wallpaper->load(); calcGeometry(); // confirm that array will be of non-zero size, since the painting code // assumes a non-zero array length Q_ASSERT(_lines > 0 && _columns > 0); Q_ASSERT(_usedLines <= _lines && _usedColumns <= _columns); _imageSize = _lines * _columns; _image = new Character[_imageSize]; clearImage(); } void TerminalDisplay::clearImage() { for (int i = 0; i < _imageSize; ++i) { _image[i] = Screen::DefaultChar; } } void TerminalDisplay::calcGeometry() { _scrollBar->resize(_scrollBar->sizeHint().width(), contentsRect().height()); _contentRect = contentsRect().adjusted(_margin, _margin, -_margin, -_margin); switch (_scrollbarLocation) { case Enum::ScrollBarHidden : break; case Enum::ScrollBarLeft : _contentRect.setLeft(_contentRect.left() + _scrollBar->width()); _scrollBar->move(contentsRect().topLeft()); break; case Enum::ScrollBarRight: _contentRect.setRight(_contentRect.right() - _scrollBar->width()); _scrollBar->move(contentsRect().topRight() - QPoint(_scrollBar->width() - 1, 0)); break; } // ensure that display is always at least one column wide _columns = qMax(1, _contentRect.width() / _fontWidth); _usedColumns = qMin(_usedColumns, _columns); // ensure that display is always at least one line high _lines = qMax(1, _contentRect.height() / _fontHeight); _usedLines = qMin(_usedLines, _lines); if(_centerContents) { QSize unusedPixels = _contentRect.size() - QSize(_columns * _fontWidth, _lines * _fontHeight); _contentRect.adjust(unusedPixels.width() / 2, unusedPixels.height() / 2, 0, 0); } } // calculate the needed size, this must be synced with calcGeometry() void TerminalDisplay::setSize(int columns, int lines) { const int scrollBarWidth = _scrollBar->isHidden() ? 0 : _scrollBar->sizeHint().width(); const int horizontalMargin = _margin * 2; const int verticalMargin = _margin * 2; QSize newSize = QSize(horizontalMargin + scrollBarWidth + (columns * _fontWidth) , verticalMargin + (lines * _fontHeight)); if (newSize != size()) { _size = newSize; updateGeometry(); } } QSize TerminalDisplay::sizeHint() const { return _size; } //showEvent and hideEvent are reimplemented here so that it appears to other classes that the //display has been resized when the display is hidden or shown. // //TODO: Perhaps it would be better to have separate signals for show and hide instead of using //the same signal as the one for a content size change void TerminalDisplay::showEvent(QShowEvent*) { emit changedContentSizeSignal(_contentRect.height(), _contentRect.width()); } void TerminalDisplay::hideEvent(QHideEvent*) { emit changedContentSizeSignal(_contentRect.height(), _contentRect.width()); } void TerminalDisplay::setMargin(int margin) { if (margin < 0) { margin = 0; } _margin = margin; updateImageSize(); } void TerminalDisplay::setCenterContents(bool enable) { _centerContents = enable; calcGeometry(); update(); } /* ------------------------------------------------------------------------- */ /* */ /* Scrollbar */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::setScrollBarPosition(Enum::ScrollBarPositionEnum position) { if (_scrollbarLocation == position) { return; } if (position == Enum::ScrollBarHidden) { _scrollBar->hide(); } else { _scrollBar->show(); } _scrollbarLocation = position; propagateSize(); update(); } void TerminalDisplay::scrollBarPositionChanged(int) { if (_screenWindow.isNull()) { return; } _screenWindow->scrollTo(_scrollBar->value()); // if the thumb has been moved to the bottom of the _scrollBar then set // the display to automatically track new output, // that is, scroll down automatically // to how new _lines as they are added const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); _screenWindow->setTrackOutput(atEndOfOutput); updateImage(); } void TerminalDisplay::setScroll(int cursor, int slines) { // update _scrollBar if the range or value has changed, // otherwise return // // setting the range or value of a _scrollBar will always trigger // a repaint, so it should be avoided if it is not necessary if (_scrollBar->minimum() == 0 && _scrollBar->maximum() == (slines - _lines) && _scrollBar->value() == cursor) { return; } disconnect(_scrollBar, &QScrollBar::valueChanged, this, &Konsole::TerminalDisplay::scrollBarPositionChanged); _scrollBar->setRange(0, slines - _lines); _scrollBar->setSingleStep(1); _scrollBar->setPageStep(_lines); _scrollBar->setValue(cursor); connect(_scrollBar, &QScrollBar::valueChanged, this, &Konsole::TerminalDisplay::scrollBarPositionChanged); } void TerminalDisplay::setScrollFullPage(bool fullPage) { _scrollFullPage = fullPage; } bool TerminalDisplay::scrollFullPage() const { return _scrollFullPage; } /* ------------------------------------------------------------------------- */ /* */ /* Mouse */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) { if (_possibleTripleClick && (ev->button() == Qt::LeftButton)) { mouseTripleClickEvent(ev); return; } if (!contentsRect().contains(ev->pos())) { return; } if (_screenWindow.isNull()) { return; } // Ignore clicks on the message widget if (_readOnlyMessageWidget != nullptr) { if (_readOnlyMessageWidget->isVisible() && _readOnlyMessageWidget->frameGeometry().contains(ev->pos())) { return; } } if (_outputSuspendedMessageWidget != nullptr) { if (_outputSuspendedMessageWidget->isVisible() && _outputSuspendedMessageWidget->frameGeometry().contains(ev->pos())) { return; } } int charLine; int charColumn; getCharacterPosition(ev->pos(), charLine, charColumn); QPoint pos = QPoint(charColumn, charLine); if (ev->button() == Qt::LeftButton) { // request the software keyboard, if any if (qApp->autoSipEnabled()) { QStyle::RequestSoftwareInputPanel behavior = QStyle::RequestSoftwareInputPanel( style()->styleHint(QStyle::SH_RequestSoftwareInputPanel)); if (hasFocus() || behavior == QStyle::RSIP_OnMouseClick) { QEvent event(QEvent::RequestSoftwareInputPanel); QApplication::sendEvent(this, &event); } } _lineSelectionMode = false; _wordSelectionMode = false; // The user clicked inside selected text bool selected = _screenWindow->isSelected(pos.x(), pos.y()); // Drag only when the Control key is held if ((!_ctrlRequiredForDrag || ((ev->modifiers() & Qt::ControlModifier) != 0u)) && selected) { _dragInfo.state = diPending; _dragInfo.start = ev->pos(); } else { // No reason to ever start a drag event _dragInfo.state = diNone; _preserveLineBreaks = !(((ev->modifiers() & Qt::ControlModifier) != 0u) && !(ev->modifiers() & Qt::AltModifier)); _columnSelectionMode = ((ev->modifiers() & Qt::AltModifier) != 0u) && ((ev->modifiers() & Qt::ControlModifier) != 0u); if (_mouseMarks || (ev->modifiers() == Qt::ShiftModifier)) { // Only extend selection for programs not interested in mouse if (_mouseMarks && (ev->modifiers() == Qt::ShiftModifier)) { extendSelection(ev->pos()); } else { _screenWindow->clearSelection(); pos.ry() += _scrollBar->value(); _iPntSel = _pntSel = pos; _actSel = 1; // left mouse button pressed but nothing selected yet. } } else { if(!_readOnly) { emit mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); } } if ((_openLinksByDirectClick || ((ev->modifiers() & Qt::ControlModifier) != 0u))) { Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine, charColumn); if ((spot != nullptr) && spot->type() == Filter::HotSpot::Link) { QObject action; action.setObjectName(QStringLiteral("open-action")); spot->activate(&action); } } } } else if (ev->button() == Qt::MidButton) { processMidButtonClick(ev); } else if (ev->button() == Qt::RightButton) { if (_mouseMarks || ((ev->modifiers() & Qt::ShiftModifier) != 0u)) { emit configureRequest(ev->pos()); } else { if(!_readOnly) { emit mouseSignal(2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); } } } } QList TerminalDisplay::filterActions(const QPoint& position) { int charLine, charColumn; getCharacterPosition(position, charLine, charColumn, false); Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine, charColumn); return spot != nullptr ? spot->actions() : QList(); } void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) { int charLine = 0; int charColumn = 0; getCharacterPosition(ev->pos(), charLine, charColumn); processFilters(); // handle filters // change link hot-spot appearance on mouse-over Filter::HotSpot* spot = _filterChain->hotSpotAt(charLine, charColumn); if ((spot != nullptr) && spot->type() == Filter::HotSpot::Link) { QRegion previousHotspotArea = _mouseOverHotspotArea; _mouseOverHotspotArea = QRegion(); QRect r; if (spot->startLine() == spot->endLine()) { r.setCoords(spot->startColumn()*_fontWidth + _contentRect.left(), spot->startLine()*_fontHeight + _contentRect.top(), (spot->endColumn())*_fontWidth + _contentRect.left() - 1, (spot->endLine() + 1)*_fontHeight + _contentRect.top() - 1); _mouseOverHotspotArea |= r; } else { r.setCoords(spot->startColumn()*_fontWidth + _contentRect.left(), spot->startLine()*_fontHeight + _contentRect.top(), (_columns)*_fontWidth + _contentRect.left() - 1, (spot->startLine() + 1)*_fontHeight + _contentRect.top() - 1); _mouseOverHotspotArea |= r; for (int line = spot->startLine() + 1 ; line < spot->endLine() ; line++) { r.setCoords(0 * _fontWidth + _contentRect.left(), line * _fontHeight + _contentRect.top(), (_columns)*_fontWidth + _contentRect.left() - 1, (line + 1)*_fontHeight + _contentRect.top() - 1); _mouseOverHotspotArea |= r; } r.setCoords(0 * _fontWidth + _contentRect.left(), spot->endLine()*_fontHeight + _contentRect.top(), (spot->endColumn())*_fontWidth + _contentRect.left() - 1, (spot->endLine() + 1)*_fontHeight + _contentRect.top() - 1); _mouseOverHotspotArea |= r; } if ((_openLinksByDirectClick || ((ev->modifiers() & Qt::ControlModifier) != 0u)) && (cursor().shape() != Qt::PointingHandCursor)) { setCursor(Qt::PointingHandCursor); } update(_mouseOverHotspotArea | previousHotspotArea); } else if (!_mouseOverHotspotArea.isEmpty()) { if ((_openLinksByDirectClick || ((ev->modifiers() & Qt::ControlModifier) != 0u)) || (cursor().shape() == Qt::PointingHandCursor)) { setCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor); } update(_mouseOverHotspotArea); // set hotspot area to an invalid rectangle _mouseOverHotspotArea = QRegion(); } // for auto-hiding the cursor, we need mouseTracking if (ev->buttons() == Qt::NoButton) { return; } // if the terminal is interested in mouse movements // then emit a mouse movement signal, unless the shift // key is being held down, which overrides this. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { int button = 3; if ((ev->buttons() & Qt::LeftButton) != 0u) { button = 0; } if ((ev->buttons() & Qt::MidButton) != 0u) { button = 1; } if ((ev->buttons() & Qt::RightButton) != 0u) { button = 2; } emit mouseSignal(button, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 1); return; } if (_dragInfo.state == diPending) { // we had a mouse down, but haven't confirmed a drag yet // if the mouse has moved sufficiently, we will confirm const int distance = QApplication::startDragDistance(); if (ev->x() > _dragInfo.start.x() + distance || ev->x() < _dragInfo.start.x() - distance || ev->y() > _dragInfo.start.y() + distance || ev->y() < _dragInfo.start.y() - distance) { // we've left the drag square, we can start a real drag operation now _screenWindow->clearSelection(); doDrag(); } return; } else if (_dragInfo.state == diDragging) { // this isn't technically needed because mouseMoveEvent is suppressed during // Qt drag operations, replaced by dragMoveEvent return; } if (_actSel == 0) { return; } // don't extend selection while pasting if ((ev->buttons() & Qt::MidButton) != 0u) { return; } extendSelection(ev->pos()); } void TerminalDisplay::leaveEvent(QEvent *) { // remove underline from an active link when cursor leaves the widget area if(!_mouseOverHotspotArea.isEmpty()) { update(_mouseOverHotspotArea); _mouseOverHotspotArea = QRegion(); } } void TerminalDisplay::extendSelection(const QPoint& position) { if (_screenWindow.isNull()) { return; } //if ( !contentsRect().contains(ev->pos()) ) return; const QPoint tL = contentsRect().topLeft(); const int tLx = tL.x(); const int tLy = tL.y(); const int scroll = _scrollBar->value(); // we're in the process of moving the mouse with the left button pressed // the mouse cursor will kept caught within the bounds of the text in // this widget. int linesBeyondWidget = 0; QRect textBounds(tLx + _contentRect.left(), tLy + _contentRect.top(), _usedColumns * _fontWidth - 1, _usedLines * _fontHeight - 1); QPoint pos = position; // Adjust position within text area bounds. const QPoint oldpos = pos; pos.setX(qBound(textBounds.left(), pos.x(), textBounds.right())); pos.setY(qBound(textBounds.top(), pos.y(), textBounds.bottom())); if (oldpos.y() > textBounds.bottom()) { linesBeyondWidget = (oldpos.y() - textBounds.bottom()) / _fontHeight; _scrollBar->setValue(_scrollBar->value() + linesBeyondWidget + 1); // scrollforward } if (oldpos.y() < textBounds.top()) { linesBeyondWidget = (textBounds.top() - oldpos.y()) / _fontHeight; _scrollBar->setValue(_scrollBar->value() - linesBeyondWidget - 1); // history } int charColumn = 0; int charLine = 0; getCharacterPosition(pos, charLine, charColumn); QPoint here = QPoint(charColumn, charLine); QPoint ohere; QPoint _iPntSelCorr = _iPntSel; _iPntSelCorr.ry() -= _scrollBar->value(); QPoint _pntSelCorr = _pntSel; _pntSelCorr.ry() -= _scrollBar->value(); bool swapping = false; if (_wordSelectionMode) { // Extend to word boundaries int i; QChar selClass; const bool left_not_right = (here.y() < _iPntSelCorr.y() || (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x())); const bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() || (_pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x())); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) QPoint left = left_not_right ? here : _iPntSelCorr; i = loc(qBound(0, left.x(), _columns - 1), qBound(0, left.y(), _lines - 1)); if (i >= 0 && i < _imageSize) { selClass = charClass(_image[qMin(i, _imageSize - 1)]); while (((left.x() > 0) || (left.y() > 0 && ((_lineProperties[left.y() - 1] & LINE_WRAPPED) != 0))) && charClass(_image[i - 1]) == selClass) { i--; if (left.x() > 0) { left.rx()--; } else { left.rx() = _usedColumns - 1; left.ry()--; } } } // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? _iPntSelCorr : here; i = loc(qBound(0, left.x(), _columns - 1), qBound(0, left.y(), _lines - 1)); if (i >= 0 && i < _imageSize) { selClass = charClass(_image[qMin(i, _imageSize - 1)]); while (((right.x() < _usedColumns - 1) || (right.y() < _usedLines - 1 && ((_lineProperties[right.y()] & LINE_WRAPPED) != 0))) && charClass(_image[i + 1]) == selClass) { i++; if (right.x() < _usedColumns - 1) { right.rx()++; } else { right.rx() = 0; right.ry()++; } } } // Pick which is start (ohere) and which is extension (here) if (left_not_right) { here = left; ohere = right; } else { here = right; ohere = left; } ohere.rx()++; } if (_lineSelectionMode) { // Extend to complete line const bool above_not_below = (here.y() < _iPntSelCorr.y()); if (above_not_below) { ohere = findLineEnd(_iPntSelCorr); here = findLineStart(here); } else { ohere = findLineStart(_iPntSelCorr); here = findLineEnd(here); } swapping = !(_tripleSelBegin == ohere); _tripleSelBegin = ohere; ohere.rx()++; } int offset = 0; if (!_wordSelectionMode && !_lineSelectionMode) { QChar selClass; const bool left_not_right = (here.y() < _iPntSelCorr.y() || (here.y() == _iPntSelCorr.y() && here.x() < _iPntSelCorr.x())); const bool old_left_not_right = (_pntSelCorr.y() < _iPntSelCorr.y() || (_pntSelCorr.y() == _iPntSelCorr.y() && _pntSelCorr.x() < _iPntSelCorr.x())); swapping = left_not_right != old_left_not_right; // Find left (left_not_right ? from here : from start) const QPoint left = left_not_right ? here : _iPntSelCorr; // Find left (left_not_right ? from start : from here) QPoint right = left_not_right ? _iPntSelCorr : here; if (right.x() > 0 && !_columnSelectionMode) { if (right.x() - 1 < _columns && right.y() < _lines) { selClass = charClass(_image[loc(right.x() - 1, right.y())]); } } // Pick which is start (ohere) and which is extension (here) if (left_not_right) { here = left; ohere = right; offset = 0; } else { here = right; ohere = left; offset = -1; } } if ((here == _pntSelCorr) && (scroll == _scrollBar->value())) { return; // not moved } if (here == ohere) { return; // It's not left, it's not right. } if (_actSel < 2 || swapping) { if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { _screenWindow->setSelectionStart(ohere.x() , ohere.y() , true); } else { _screenWindow->setSelectionStart(ohere.x() - 1 - offset , ohere.y() , false); } } _actSel = 2; // within selection _pntSel = here; _pntSel.ry() += _scrollBar->value(); if (_columnSelectionMode && !_lineSelectionMode && !_wordSelectionMode) { _screenWindow->setSelectionEnd(here.x() , here.y()); } else { _screenWindow->setSelectionEnd(here.x() + offset , here.y()); } } void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) { if (_screenWindow.isNull()) { return; } int charLine; int charColumn; getCharacterPosition(ev->pos(), charLine, charColumn); if (ev->button() == Qt::LeftButton) { if (_dragInfo.state == diPending) { // We had a drag event pending but never confirmed. Kill selection _screenWindow->clearSelection(); } else { if (_actSel > 1) { copyToX11Selection(); } _actSel = 0; //FIXME: emits a release event even if the mouse is // outside the range. The procedure used in `mouseMoveEvent' // applies here, too. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { emit mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 2); } } _dragInfo.state = diNone; } if (!_mouseMarks && (ev->button() == Qt::RightButton || ev->button() == Qt::MidButton) && !(ev->modifiers() & Qt::ShiftModifier)) { emit mouseSignal(ev->button() == Qt::MidButton ? 1 : 2, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 2); } } void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint, int& line, int& column, bool edge) const { // the column value returned can be equal to _usedColumns (when edge == true), // which is the position just after the last character displayed in a line. // // this is required so that the user can select characters in the right-most // column (or left-most for right-to-left input) const int columnMax = edge ? _usedColumns : _usedColumns - 1; const int xOffset = edge ? _fontWidth / 2 : 0; column = qBound(0, (widgetPoint.x() + xOffset - contentsRect().left() - _contentRect.left()) / _fontWidth, columnMax); line = qBound(0, (widgetPoint.y() - contentsRect().top() - _contentRect.top()) / _fontHeight, _usedLines - 1); } void TerminalDisplay::updateLineProperties() { if (_screenWindow.isNull()) { return; } _lineProperties = _screenWindow->getLineProperties(); } void TerminalDisplay::processMidButtonClick(QMouseEvent* ev) { if (_mouseMarks || ((ev->modifiers() & Qt::ShiftModifier) != 0u)) { const bool appendEnter = (ev->modifiers() & Qt::ControlModifier) != 0u; if (_middleClickPasteMode == Enum::PasteFromX11Selection) { pasteFromX11Selection(appendEnter); } else if (_middleClickPasteMode == Enum::PasteFromClipboard) { pasteFromClipboard(appendEnter); } else { Q_ASSERT(false); } } else { if(!_readOnly) { int charLine = 0; int charColumn = 0; getCharacterPosition(ev->pos(), charLine, charColumn); emit mouseSignal(1, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); } } } void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { // Yes, successive middle click can trigger this event if (ev->button() == Qt::MidButton) { processMidButtonClick(ev); return; } if (ev->button() != Qt::LeftButton) { return; } if (_screenWindow.isNull()) { return; } int charLine = 0; int charColumn = 0; getCharacterPosition(ev->pos(), charLine, charColumn); QPoint pos(qMin(charColumn, _columns - 1), qMin(charLine, _lines - 1)); // pass on double click as two clicks. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) { if(!_readOnly) { // Send just _ONE_ click event, since the first click of the double click // was already sent by the click handler emit mouseSignal(0, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum(), 0); // left button } return; } _screenWindow->clearSelection(); QPoint bgnSel = pos; QPoint endSel = pos; int i = loc(bgnSel.x(), bgnSel.y()); _iPntSel = bgnSel; _iPntSel.ry() += _scrollBar->value(); _wordSelectionMode = true; _actSel = 2; // within selection // find word boundaries... const QChar selClass = charClass(_image[i]); { // find the start of the word int x = bgnSel.x(); while (((x > 0) || (bgnSel.y() > 0 && ((_lineProperties[bgnSel.y() - 1] & LINE_WRAPPED) != 0))) && charClass(_image[i - 1]) == selClass) { i--; if (x > 0) { x--; } else { x = _usedColumns - 1; bgnSel.ry()--; } } bgnSel.setX(x); _screenWindow->setSelectionStart(bgnSel.x() , bgnSel.y() , false); // find the end of the word i = loc(endSel.x(), endSel.y()); x = endSel.x(); while (((x < _usedColumns - 1) || (endSel.y() < _usedLines - 1 && ((_lineProperties[endSel.y()] & LINE_WRAPPED) != 0))) && charClass(_image[i + 1]) == selClass) { i++; if (x < _usedColumns - 1) { x++; } else { x = 0; endSel.ry()++; } } endSel.setX(x); // In word selection mode don't select @ (64) if at end of word. if (((_image[i].rendition & RE_EXTENDED_CHAR) == 0) && (QChar(_image[i].character) == QLatin1Char('@')) && ((endSel.x() - bgnSel.x()) > 0)) { endSel.setX(x - 1); } _actSel = 2; // within selection _screenWindow->setSelectionEnd(endSel.x() , endSel.y()); copyToX11Selection(); } _possibleTripleClick = true; QTimer::singleShot(QApplication::doubleClickInterval(), [this]() { _possibleTripleClick = false; }); } void TerminalDisplay::wheelEvent(QWheelEvent* ev) { // Only vertical scrolling is supported if (ev->orientation() != Qt::Vertical) { return; } const int modifiers = ev->modifiers(); // ctrl+ for zooming, like in konqueror and firefox if (((modifiers & Qt::ControlModifier) != 0u) && mouseWheelZoom()) { _scrollWheelState.addWheelEvent(ev); int steps = _scrollWheelState.consumeLegacySteps(ScrollState::DEFAULT_ANGLE_SCROLL_LINE); for (;steps > 0; --steps) { // wheel-up for increasing font size increaseFontSize(); } for (;steps < 0; ++steps) { // wheel-down for decreasing font size decreaseFontSize(); } } else if (_mouseMarks && (_scrollBar->maximum() > 0)) { // If the program running in the terminal is not interested in mouse events, // send the event to the scrollbar if the slider has room to move _scrollWheelState.addWheelEvent(ev); _scrollBar->event(ev); _sessionController->setSearchStartToWindowCurrentLine(); _scrollWheelState.clearAll(); } else if (!_readOnly) { _scrollWheelState.addWheelEvent(ev); if(_mouseMarks && !_isPrimaryScreen && _alternateScrolling) { // Send simulated up / down key presses to the terminal program // for the benefit of programs such as 'less' (which use the alternate screen) // assume that each Up / Down key event will cause the terminal application // to scroll by one line. // // to get a reasonable scrolling speed, scroll by one line for every 5 degrees // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, // giving a scroll of 3 lines const int lines = _scrollWheelState.consumeSteps(static_cast(_fontHeight * qApp->devicePixelRatio()), ScrollState::degreesToAngle(5)); const int keyCode = lines > 0 ? Qt::Key_Up : Qt::Key_Down; QKeyEvent keyEvent(QEvent::KeyPress, keyCode, Qt::NoModifier); for (int i = 0; i < abs(lines); i++) { _screenWindow->screen()->setCurrentTerminalDisplay(this); emit keyPressedSignal(&keyEvent); } } else if (!_mouseMarks) { // terminal program wants notification of mouse activity int charLine; int charColumn; getCharacterPosition(ev->pos() , charLine , charColumn); const int steps = _scrollWheelState.consumeLegacySteps(ScrollState::DEFAULT_ANGLE_SCROLL_LINE); const int button = (steps > 0) ? 4 : 5; for (int i = 0; i < abs(steps); ++i) { emit mouseSignal(button, charColumn + 1, charLine + 1 + _scrollBar->value() - _scrollBar->maximum() , 0); } } } } void TerminalDisplay::viewScrolledByUser() { _sessionController->setSearchStartToWindowCurrentLine(); } /* Moving left/up from the line containing pnt, return the starting offset point which the given line is continiously wrapped (top left corner = 0,0; previous line not visible = 0,-1). */ QPoint TerminalDisplay::findLineStart(const QPoint &pnt) { const int visibleScreenLines = _lineProperties.size(); const int topVisibleLine = _screenWindow->currentLine(); Screen *screen = _screenWindow->screen(); int line = pnt.y(); int lineInHistory= line + topVisibleLine; QVector lineProperties = _lineProperties; while (lineInHistory > 0) { for (; line > 0; line--, lineInHistory--) { // Does previous line wrap around? if ((lineProperties[line - 1] & LINE_WRAPPED) == 0) { return QPoint(0, lineInHistory - topVisibleLine); } } if (lineInHistory < 1) { break; } // _lineProperties is only for the visible screen, so grab new data int newRegionStart = qMax(0, lineInHistory - visibleScreenLines); lineProperties = screen->getLineProperties(newRegionStart, lineInHistory - 1); line = lineInHistory - newRegionStart; } return QPoint(0, lineInHistory - topVisibleLine); } /* Moving right/down from the line containing pnt, return the ending offset point which the given line is continiously wrapped. */ QPoint TerminalDisplay::findLineEnd(const QPoint &pnt) { const int visibleScreenLines = _lineProperties.size(); const int topVisibleLine = _screenWindow->currentLine(); const int maxY = _screenWindow->lineCount() - 1; Screen *screen = _screenWindow->screen(); int line = pnt.y(); int lineInHistory= line + topVisibleLine; QVector lineProperties = _lineProperties; while (lineInHistory < maxY) { for (; line < lineProperties.count() && lineInHistory < maxY; line++, lineInHistory++) { // Does current line wrap around? if ((lineProperties[line] & LINE_WRAPPED) == 0) { return QPoint(_columns - 1, lineInHistory - topVisibleLine); } } line = 0; lineProperties = screen->getLineProperties(lineInHistory, qMin(lineInHistory + visibleScreenLines, maxY)); } return QPoint(_columns - 1, lineInHistory - topVisibleLine); } QPoint TerminalDisplay::findWordStart(const QPoint &pnt) { const int regSize = qMax(_screenWindow->windowLines(), 10); const int curLine = _screenWindow->currentLine(); int i = pnt.y(); int x = pnt.x(); int y = i + curLine; int j = loc(x, i); QVector lineProperties = _lineProperties; Screen *screen = _screenWindow->screen(); Character *image = _image; Character *tmp_image = nullptr; const QChar selClass = charClass(image[j]); const int imageSize = regSize * _columns; while (true) { for (;;j--, x--) { if (x > 0) { if (charClass(image[j - 1]) == selClass) { continue; } goto out; } else if (i > 0) { if (((lineProperties[i - 1] & LINE_WRAPPED) != 0) && charClass(image[j - 1]) == selClass) { x = _columns; i--; y--; continue; } goto out; } else if (y > 0) { break; } else { goto out; } } int newRegStart = qMax(0, y - regSize); lineProperties = screen->getLineProperties(newRegStart, y - 1); i = y - newRegStart; if (tmp_image == nullptr) { tmp_image = new Character[imageSize]; image = tmp_image; } screen->getImage(tmp_image, imageSize, newRegStart, y - 1); j = loc(x, i); } out: if (tmp_image != nullptr) { delete[] tmp_image; } return QPoint(x, y - curLine); } QPoint TerminalDisplay::findWordEnd(const QPoint &pnt) { const int regSize = qMax(_screenWindow->windowLines(), 10); const int curLine = _screenWindow->currentLine(); int i = pnt.y(); int x = pnt.x(); int y = i + curLine; int j = loc(x, i); QVector lineProperties = _lineProperties; Screen *screen = _screenWindow->screen(); Character *image = _image; Character *tmp_image = nullptr; const QChar selClass = charClass(image[j]); const int imageSize = regSize * _columns; const int maxY = _screenWindow->lineCount() - 1; const int maxX = _columns - 1; while (true) { const int lineCount = lineProperties.count(); for (;;j++, x++) { if (x < maxX) { if (charClass(image[j + 1]) == selClass) { continue; } goto out; } else if (i < lineCount - 1) { if (((lineProperties[i] & LINE_WRAPPED) != 0) && charClass(image[j + 1]) == selClass) { x = -1; i++; y++; continue; } goto out; } else if (y < maxY) { if (i < lineCount && ((lineProperties[i] & LINE_WRAPPED) == 0)) { goto out; } break; } else { goto out; } } int newRegEnd = qMin(y + regSize - 1, maxY); lineProperties = screen->getLineProperties(y, newRegEnd); i = 0; if (tmp_image == nullptr) { tmp_image = new Character[imageSize]; image = tmp_image; } screen->getImage(tmp_image, imageSize, y, newRegEnd); x--; j = loc(x, i); } out: y -= curLine; // In word selection mode don't select @ (64) if at end of word. if (((image[j].rendition & RE_EXTENDED_CHAR) == 0) && (QChar(image[j].character) == QLatin1Char('@')) && (y > pnt.y() || x > pnt.x())) { if (x > 0) { x--; } else { y--; } } if (tmp_image != nullptr) { delete[] tmp_image; } return QPoint(x, y); } Screen::DecodingOptions TerminalDisplay::currentDecodingOptions() { Screen::DecodingOptions decodingOptions; if (_preserveLineBreaks) { decodingOptions |= Screen::PreserveLineBreaks; } if (_trimLeadingSpaces) { decodingOptions |= Screen::TrimLeadingWhitespace; } if (_trimTrailingSpaces) { decodingOptions |= Screen::TrimTrailingWhitespace; } return decodingOptions; } void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) { if (_screenWindow.isNull()) { return; } int charLine; int charColumn; getCharacterPosition(ev->pos(), charLine, charColumn); selectLine(QPoint(charColumn, charLine), _tripleClickMode == Enum::SelectWholeLine); } void TerminalDisplay::selectLine(QPoint pos, bool entireLine) { _iPntSel = pos; _screenWindow->clearSelection(); _lineSelectionMode = true; _wordSelectionMode = false; _actSel = 2; // within selection if (!entireLine) { // Select from cursor to end of line _tripleSelBegin = findWordStart(_iPntSel); _screenWindow->setSelectionStart(_tripleSelBegin.x(), _tripleSelBegin.y() , false); } else { _tripleSelBegin = findLineStart(_iPntSel); _screenWindow->setSelectionStart(0 , _tripleSelBegin.y() , false); } _iPntSel = findLineEnd(_iPntSel); _screenWindow->setSelectionEnd(_iPntSel.x() , _iPntSel.y()); copyToX11Selection(); _iPntSel.ry() += _scrollBar->value(); } void TerminalDisplay::selectCurrentLine() { if (_screenWindow.isNull()) { return; } selectLine(cursorPosition(), true); } void TerminalDisplay::selectAll() { if (_screenWindow.isNull()) { return; } _preserveLineBreaks = true; _screenWindow->setSelectionByLineRange(0, _screenWindow->lineCount()); copyToX11Selection(); } bool TerminalDisplay::focusNextPrevChild(bool next) { // for 'Tab', always disable focus switching among widgets // for 'Shift+Tab', leave the decision to higher level if (next) { return false; } else { return QWidget::focusNextPrevChild(next); } } QChar TerminalDisplay::charClass(const Character& ch) const { if ((ch.rendition & RE_EXTENDED_CHAR) != 0) { ushort extendedCharLength = 0; - const ushort* chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); + const uint* chars = ExtendedCharTable::instance.lookupExtendedChar(ch.character, extendedCharLength); if ((chars != nullptr) && extendedCharLength > 0) { - const QString s = QString::fromUtf16(chars, extendedCharLength); + const QString s = QString::fromUcs4(chars, extendedCharLength); if (_wordCharacters.contains(s, Qt::CaseInsensitive)) { return QLatin1Char('a'); } bool letterOrNumber = false; for (int i = 0; !letterOrNumber && i < s.size(); ++i) { letterOrNumber = s.at(i).isLetterOrNumber(); } return letterOrNumber ? QLatin1Char('a') : s.at(0); } return 0; } else { const QChar qch(ch.character); if (qch.isSpace()) { return QLatin1Char(' '); } if (qch.isLetterOrNumber() || _wordCharacters.contains(qch, Qt::CaseInsensitive)) { return QLatin1Char('a'); } return qch; } } void TerminalDisplay::setWordCharacters(const QString& wc) { _wordCharacters = wc; } // FIXME: the actual value of _mouseMarks is the opposite of its semantic. // When using programs not interested with mouse(shell, less), it is true. // When using programs interested with mouse(vim,mc), it is false. void TerminalDisplay::setUsesMouse(bool on) { _mouseMarks = on; setCursor(_mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor); } bool TerminalDisplay::usesMouse() const { return _mouseMarks; } void TerminalDisplay::setAlternateScrolling(bool enable) { _alternateScrolling = enable; } bool TerminalDisplay::alternateScrolling() const { return _alternateScrolling; } void TerminalDisplay::usingPrimaryScreen(bool use) { _isPrimaryScreen = use; } void TerminalDisplay::setBracketedPasteMode(bool on) { _bracketedPasteMode = on; } bool TerminalDisplay::bracketedPasteMode() const { return _bracketedPasteMode; } /* ------------------------------------------------------------------------- */ /* */ /* Clipboard */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::doPaste(QString text, bool appendReturn) { if (_screenWindow.isNull()) { return; } if (_readOnly) { return; } if (appendReturn) { text.append(QLatin1String("\r")); } if (text.length() > 8000) { if (KMessageBox::warningContinueCancel(window(), i18np("Are you sure you want to paste %1 character?", "Are you sure you want to paste %1 characters?", text.length()), i18n("Confirm Paste"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(), QStringLiteral("ShowPasteHugeTextWarning")) == KMessageBox::Cancel) { return; } } if (!text.isEmpty()) { text.replace(QLatin1Char('\n'), QLatin1Char('\r')); if (bracketedPasteMode()) { text.remove(QLatin1String("\033")); text.prepend(QLatin1String("\033[200~")); text.append(QLatin1String("\033[201~")); } // perform paste by simulating keypress events QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); emit keyPressedSignal(&e); } } void TerminalDisplay::setAutoCopySelectedText(bool enabled) { _autoCopySelectedText = enabled; } void TerminalDisplay::setMiddleClickPasteMode(Enum::MiddleClickPasteModeEnum mode) { _middleClickPasteMode = mode; } void TerminalDisplay::setCopyTextAsHTML(bool enabled) { _copyTextAsHTML = enabled; } void TerminalDisplay::copyToX11Selection() { if (_screenWindow.isNull()) { return; } const QString &text = _screenWindow->selectedText(currentDecodingOptions()); if (text.isEmpty()) { return; } auto mimeData = new QMimeData; mimeData->setText(text); if (_copyTextAsHTML) { mimeData->setHtml(_screenWindow->selectedText(currentDecodingOptions() | Screen::ConvertToHtml)); } if (QApplication::clipboard()->supportsSelection()) { QApplication::clipboard()->setMimeData(mimeData, QClipboard::Selection); } if (_autoCopySelectedText) { QApplication::clipboard()->setMimeData(mimeData, QClipboard::Clipboard); } } void TerminalDisplay::copyToClipboard() { if (_screenWindow.isNull()) { return; } const QString &text = _screenWindow->selectedText(currentDecodingOptions()); if (text.isEmpty()) { return; } auto mimeData = new QMimeData; mimeData->setText(text); if (_copyTextAsHTML) { mimeData->setHtml(_screenWindow->selectedText(currentDecodingOptions() | Screen::ConvertToHtml)); } QApplication::clipboard()->setMimeData(mimeData, QClipboard::Clipboard); } void TerminalDisplay::pasteFromClipboard(bool appendEnter) { QString text = QApplication::clipboard()->text(QClipboard::Clipboard); doPaste(text, appendEnter); } void TerminalDisplay::pasteFromX11Selection(bool appendEnter) { if (QApplication::clipboard()->supportsSelection()) { QString text = QApplication::clipboard()->text(QClipboard::Selection); doPaste(text, appendEnter); } } /* ------------------------------------------------------------------------- */ /* */ /* Input Method */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::inputMethodEvent(QInputMethodEvent* event) { if (!event->commitString().isEmpty()) { QKeyEvent keyEvent(QEvent::KeyPress, 0, Qt::NoModifier, event->commitString()); emit keyPressedSignal(&keyEvent); } if (!_readOnly && isCursorOnDisplay()) { _inputMethodData.preeditString = event->preeditString(); update(preeditRect() | _inputMethodData.previousPreeditRect); } event->accept(); } QVariant TerminalDisplay::inputMethodQuery(Qt::InputMethodQuery query) const { const QPoint cursorPos = cursorPosition(); switch (query) { case Qt::ImMicroFocus: return imageToWidget(QRect(cursorPos.x(), cursorPos.y(), 1, 1)); case Qt::ImFont: return font(); case Qt::ImCursorPosition: // return the cursor position within the current line return cursorPos.x(); case Qt::ImSurroundingText: { // return the text from the current line QString lineText; QTextStream stream(&lineText); PlainTextDecoder decoder; decoder.begin(&stream); if (isCursorOnDisplay()) { decoder.decodeLine(&_image[loc(0, cursorPos.y())], _usedColumns, LINE_DEFAULT); } decoder.end(); return lineText; } case Qt::ImCurrentSelection: return QString(); default: break; } return QVariant(); } QRect TerminalDisplay::preeditRect() const { const int preeditLength = string_width(_inputMethodData.preeditString); if (preeditLength == 0) { return QRect(); } const QRect stringRect(_contentRect.left() + _fontWidth * cursorPosition().x(), _contentRect.top() + _fontHeight * cursorPosition().y(), _fontWidth * preeditLength, _fontHeight); return stringRect.intersected(_contentRect); } void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) { if (_inputMethodData.preeditString.isEmpty() || !isCursorOnDisplay()) { return; } const QPoint cursorPos = cursorPosition(); bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR]; const QColor foreground = _colorTable[DEFAULT_FORE_COLOR]; const Character* style = &_image[loc(cursorPos.x(), cursorPos.y())]; drawBackground(painter, rect, background, true); drawCursor(painter, rect, foreground, background, invertColors); drawCharacters(painter, rect, _inputMethodData.preeditString, style, invertColors); _inputMethodData.previousPreeditRect = rect; } /* ------------------------------------------------------------------------- */ /* */ /* Keyboard */ /* */ /* ------------------------------------------------------------------------- */ void TerminalDisplay::setFlowControlWarningEnabled(bool enable) { _flowControlWarningEnabled = enable; // if the dialog is currently visible and the flow control warning has // been disabled then hide the dialog if (!enable) { outputSuspended(false); } } void TerminalDisplay::outputSuspended(bool suspended) { //create the label when this function is first called if (_outputSuspendedMessageWidget == nullptr) { //This label includes a link to an English language website //describing the 'flow control' (Xon/Xoff) feature found in almost //all terminal emulators. //If there isn't a suitable article available in the target language the link //can simply be removed. _outputSuspendedMessageWidget = createMessageWidget(i18n("Output has been " "suspended" " by pressing Ctrl+S." " Press Ctrl+Q to resume.")); connect(_outputSuspendedMessageWidget, &KMessageWidget::linkActivated, this, [](const QString &url) { QDesktopServices::openUrl(QUrl(url)); }); _outputSuspendedMessageWidget->setMessageType(KMessageWidget::Warning); } suspended ? _outputSuspendedMessageWidget->animatedShow() : _outputSuspendedMessageWidget->animatedHide(); } void TerminalDisplay::dismissOutputSuspendedMessage() { outputSuspended(false); } KMessageWidget* TerminalDisplay::createMessageWidget(const QString &text) { auto widget = new KMessageWidget(text); widget->setWordWrap(true); widget->setFocusProxy(this); widget->setCursor(Qt::ArrowCursor); _verticalLayout->insertWidget(0, widget); return widget; } void TerminalDisplay::updateReadOnlyState(bool readonly) { if (_readOnly == readonly) { return; } if (readonly) { // Lazy create the readonly messagewidget if (_readOnlyMessageWidget == nullptr) { _readOnlyMessageWidget = createMessageWidget(i18n("This terminal is read-only.")); _readOnlyMessageWidget->setIcon(QIcon::fromTheme(QStringLiteral("object-locked"))); } } if (_readOnlyMessageWidget != nullptr) { readonly ? _readOnlyMessageWidget->animatedShow() : _readOnlyMessageWidget->animatedHide(); } _readOnly = readonly; } void TerminalDisplay::scrollScreenWindow(enum ScreenWindow::RelativeScrollMode mode, int amount) { _screenWindow->scrollBy(mode, amount, _scrollFullPage); _screenWindow->setTrackOutput(_screenWindow->atEndOfOutput()); updateLineProperties(); updateImage(); viewScrolledByUser(); } void TerminalDisplay::keyPressEvent(QKeyEvent* event) { if ((_urlHintsModifiers != 0u) && event->modifiers() == _urlHintsModifiers) { int hintSelected = event->key() - 0x31; if (hintSelected >= 0 && hintSelected < 10 && hintSelected < _filterChain->hotSpots().count()) { _filterChain->hotSpots().at(hintSelected)->activate(); _showUrlHint = false; update(); return; } if (!_showUrlHint) { processFilters(); _showUrlHint = true; update(); } } _screenWindow->screen()->setCurrentTerminalDisplay(this); if (!_readOnly) { _actSel = 0; // Key stroke implies a screen update, so TerminalDisplay won't // know where the current selection is. if (_allowBlinkingCursor) { _blinkCursorTimer->start(); if (_cursorBlinking) { // if cursor is blinking(hidden), blink it again to show it blinkCursorEvent(); } Q_ASSERT(!_cursorBlinking); } } emit keyPressedSignal(event); #ifndef QT_NO_ACCESSIBILITY if (!_readOnly) { QAccessibleTextCursorEvent textCursorEvent(this, _usedColumns * screenWindow()->screen()->getCursorY() + screenWindow()->screen()->getCursorX()); QAccessible::updateAccessibility(&textCursorEvent); } #endif event->accept(); } void TerminalDisplay::keyReleaseEvent(QKeyEvent *event) { if (_showUrlHint) { _showUrlHint = false; update(); } if (_readOnly) { event->accept(); return; } QWidget::keyReleaseEvent(event); } bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) { const int modifiers = keyEvent->modifiers(); // When a possible shortcut combination is pressed, // emit the overrideShortcutCheck() signal to allow the host // to decide whether the terminal should override it or not. if (modifiers != Qt::NoModifier) { int modifierCount = 0; unsigned int currentModifier = Qt::ShiftModifier; while (currentModifier <= Qt::KeypadModifier) { if ((modifiers & currentModifier) != 0u) { modifierCount++; } currentModifier <<= 1; } if (modifierCount < 2) { bool override = false; emit overrideShortcutCheck(keyEvent, override); if (override) { keyEvent->accept(); return true; } } } // Override any of the following shortcuts because // they are needed by the terminal int keyCode = keyEvent->key() | modifiers; switch (keyCode) { // list is taken from the QLineEdit::event() code case Qt::Key_Tab: case Qt::Key_Delete: case Qt::Key_Home: case Qt::Key_End: case Qt::Key_Backspace: case Qt::Key_Left: case Qt::Key_Right: case Qt::Key_Slash: case Qt::Key_Period: case Qt::Key_Space: keyEvent->accept(); return true; } return false; } bool TerminalDisplay::event(QEvent* event) { bool eventHandled = false; switch (event->type()) { case QEvent::ShortcutOverride: eventHandled = handleShortcutOverrideEvent(static_cast(event)); break; case QEvent::PaletteChange: case QEvent::ApplicationPaletteChange: _scrollBar->setPalette(QApplication::palette()); break; default: break; } return eventHandled ? true : QWidget::event(event); } void TerminalDisplay::contextMenuEvent(QContextMenuEvent* event) { // the logic for the mouse case is within MousePressEvent() if (event->reason() != QContextMenuEvent::Mouse) { emit configureRequest(mapFromGlobal(QCursor::pos())); } } /* --------------------------------------------------------------------- */ /* */ /* Bell */ /* */ /* --------------------------------------------------------------------- */ void TerminalDisplay::setBellMode(int mode) { _bellMode = mode; } int TerminalDisplay::bellMode() const { return _bellMode; } void TerminalDisplay::bell(const QString& message) { if (_bellMasked) { return; } switch (_bellMode) { case Enum::SystemBeepBell: KNotification::beep(); break; case Enum::NotifyBell: // STABLE API: // Please note that these event names, "BellVisible" and "BellInvisible", // should not change and should be kept stable, because other applications // that use this code via KPart rely on these names for notifications. KNotification::event(hasFocus() ? QStringLiteral("BellVisible") : QStringLiteral("BellInvisible"), message, QPixmap(), this); break; case Enum::VisualBell: visualBell(); break; default: break; } // limit the rate at which bells can occur. // ...mainly for sound effects where rapid bells in sequence // produce a horrible noise. _bellMasked = true; QTimer::singleShot(500, [this]() { _bellMasked = false; }); } void TerminalDisplay::visualBell() { swapFGBGColors(); QTimer::singleShot(200, this, &Konsole::TerminalDisplay::swapFGBGColors); } void TerminalDisplay::swapFGBGColors() { // swap the default foreground & background color ColorEntry color = _colorTable[DEFAULT_BACK_COLOR]; _colorTable[DEFAULT_BACK_COLOR] = _colorTable[DEFAULT_FORE_COLOR]; _colorTable[DEFAULT_FORE_COLOR] = color; update(); } /* --------------------------------------------------------------------- */ /* */ /* Drag & Drop */ /* */ /* --------------------------------------------------------------------- */ void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { // text/plain alone is enough for KDE-apps // text/uri-list is for supporting some non-KDE apps, such as thunar // and pcmanfm // That also applies in dropEvent() const auto mimeData = event->mimeData(); if ((!_readOnly) && (mimeData != nullptr) && (mimeData->hasFormat(QStringLiteral("text/plain")) || mimeData->hasFormat(QStringLiteral("text/uri-list")))) { event->acceptProposedAction(); } } void TerminalDisplay::dropEvent(QDropEvent* event) { if (_readOnly) { event->accept(); return; } const auto mimeData = event->mimeData(); if (mimeData == nullptr) { return; } auto urls = mimeData->urls(); QString dropText; if (!urls.isEmpty()) { for (int i = 0 ; i < urls.count() ; i++) { KIO::StatJob* job = KIO::mostLocalUrl(urls[i], KIO::HideProgressInfo); bool ok = job->exec(); if (!ok) { continue; } QUrl url = job->mostLocalUrl(); QString urlText; if (url.isLocalFile()) { urlText = url.path(); } else { urlText = url.url(); } // in future it may be useful to be able to insert file names with drag-and-drop // without quoting them (this only affects paths with spaces in) urlText = KShell::quoteArg(urlText); dropText += urlText; // Each filename(including the last) should be followed by one space. dropText += QLatin1Char(' '); } // If our target is local we will open a popup - otherwise the fallback kicks // in and the URLs will simply be pasted as text. if (!_dropUrlsAsText && (_sessionController != nullptr) && _sessionController->url().isLocalFile()) { // A standard popup with Copy, Move and Link as options - // plus an additional Paste option. QAction* pasteAction = new QAction(i18n("&Paste Location"), this); pasteAction->setData(dropText); connect(pasteAction, &QAction::triggered, this, &TerminalDisplay::dropMenuPasteActionTriggered); QList additionalActions; additionalActions.append(pasteAction); if (urls.count() == 1) { KIO::StatJob* job = KIO::mostLocalUrl(urls[0], KIO::HideProgressInfo); bool ok = job->exec(); if (ok) { const QUrl url = job->mostLocalUrl(); if (url.isLocalFile()) { const QFileInfo fileInfo(url.path()); if (fileInfo.isDir()) { QAction* cdAction = new QAction(i18n("Change &Directory To"), this); dropText = QLatin1String(" cd ") + dropText + QLatin1Char('\n'); cdAction->setData(dropText); connect(cdAction, &QAction::triggered, this, &TerminalDisplay::dropMenuCdActionTriggered); additionalActions.append(cdAction); } } } } QUrl target = QUrl::fromLocalFile(_sessionController->currentDir()); KIO::DropJob* job = KIO::drop(event, target); KJobWidgets::setWindow(job, this); job->setApplicationActions(additionalActions); return; } } else { dropText = mimeData->text(); } if (mimeData->hasFormat(QStringLiteral("text/plain")) || mimeData->hasFormat(QStringLiteral("text/uri-list"))) { emit sendStringToEmu(dropText.toLocal8Bit()); } } void TerminalDisplay::dropMenuPasteActionTriggered() { if (sender() != nullptr) { const QAction* action = qobject_cast(sender()); if (action != nullptr) { emit sendStringToEmu(action->data().toString().toLocal8Bit()); } } } void TerminalDisplay::dropMenuCdActionTriggered() { if (sender() != nullptr) { const QAction* action = qobject_cast(sender()); if (action != nullptr) { emit sendStringToEmu(action->data().toString().toLocal8Bit()); } } } void TerminalDisplay::doDrag() { _dragInfo.state = diDragging; _dragInfo.dragObject = new QDrag(this); auto mimeData = new QMimeData(); mimeData->setText(QApplication::clipboard()->mimeData(QClipboard::Selection)->text()); mimeData->setHtml(QApplication::clipboard()->mimeData(QClipboard::Selection)->html()); _dragInfo.dragObject->setMimeData(mimeData); _dragInfo.dragObject->exec(Qt::CopyAction); } void TerminalDisplay::setSessionController(SessionController* controller) { _sessionController = controller; } SessionController* TerminalDisplay::sessionController() { return _sessionController; } AutoScrollHandler::AutoScrollHandler(QWidget* parent) : QObject(parent) , _timerId(0) { parent->installEventFilter(this); } void AutoScrollHandler::timerEvent(QTimerEvent* event) { if (event->timerId() != _timerId) { return; } QMouseEvent mouseEvent(QEvent::MouseMove, widget()->mapFromGlobal(QCursor::pos()), Qt::NoButton, Qt::LeftButton, Qt::NoModifier); QApplication::sendEvent(widget(), &mouseEvent); } bool AutoScrollHandler::eventFilter(QObject* watched, QEvent* event) { Q_ASSERT(watched == parent()); Q_UNUSED(watched); switch (event->type()) { case QEvent::MouseMove: { QMouseEvent* mouseEvent = static_cast(event); bool mouseInWidget = widget()->rect().contains(mouseEvent->pos()); if (mouseInWidget) { if (_timerId != 0) { killTimer(_timerId); } _timerId = 0; } else { if ((_timerId == 0) && ((mouseEvent->buttons() & Qt::LeftButton) != 0u)) { _timerId = startTimer(100); } } break; } case QEvent::MouseButtonRelease: { QMouseEvent* mouseEvent = static_cast(event); if ((_timerId != 0) && ((mouseEvent->buttons() & ~Qt::LeftButton) != 0u)) { killTimer(_timerId); _timerId = 0; } break; } default: break; }; return false; } diff --git a/src/Vt102Emulation.cpp b/src/Vt102Emulation.cpp index 8599110e..486444ae 100644 --- a/src/Vt102Emulation.cpp +++ b/src/Vt102Emulation.cpp @@ -1,1541 +1,1541 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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 "Vt102Emulation.h" // Standard #include #include // Qt #include #include #include // KDE #include // Konsole #include "KeyboardTranslator.h" #include "SessionController.h" #include "TerminalDisplay.h" using Konsole::Vt102Emulation; /* The VT100 has 32 special graphical characters. The usual vt100 extended xterm fonts have these at 0x00..0x1f. QT's iso mapping leaves 0x00..0x7f without any changes. But the graphicals come in here as proper unicode characters. We treat non-iso10646 fonts as VT100 extended and do the required mapping from unicode to 0x00..0x1f. The remaining translation is then left to the QCodec. */ // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. unsigned short Konsole::vt100_graphics[32] = { // 0/8 1/9 2/10 3/11 4/12 5/13 6/14 7/15 0x0020, 0x25C6, 0x2592, 0x2409, 0x240c, 0x240d, 0x240a, 0x00b0, 0x00b1, 0x2424, 0x240b, 0x2518, 0x2510, 0x250c, 0x2514, 0x253c, 0xF800, 0xF801, 0x2500, 0xF803, 0xF804, 0x251c, 0x2524, 0x2534, 0x252c, 0x2502, 0x2264, 0x2265, 0x03C0, 0x2260, 0x00A3, 0x00b7 }; Vt102Emulation::Vt102Emulation() : Emulation(), _currentModes(TerminalState()), _savedModes(TerminalState()), _pendingTitleUpdates(QHash()), _titleUpdateTimer(new QTimer(this)), _reportFocusEvents(false) { _titleUpdateTimer->setSingleShot(true); QObject::connect(_titleUpdateTimer, &QTimer::timeout, this, &Konsole::Vt102Emulation::updateTitle); initTokenizer(); reset(); } Vt102Emulation::~Vt102Emulation() = default; void Vt102Emulation::clearEntireScreen() { _currentScreen->clearEntireScreen(); bufferedUpdate(); } void Vt102Emulation::reset() { // Save the current codec so we can set it later. // Ideally we would want to use the profile setting const QTextCodec *currentCodec = codec(); resetTokenizer(); resetModes(); resetCharset(0); _screen[0]->reset(); resetCharset(1); _screen[1]->reset(); if (currentCodec != nullptr) { setCodec(currentCodec); } else { setCodec(LocaleCodec); } emit resetCursorStyleRequest(); bufferedUpdate(); } /* ------------------------------------------------------------------------- */ /* */ /* Processing the incoming byte stream */ /* */ /* ------------------------------------------------------------------------- */ /* Incoming Bytes Event pipeline This section deals with decoding the incoming character stream. Decoding means here, that the stream is first separated into `tokens' which are then mapped to a `meaning' provided as operations by the `Screen' class or by the emulation class itself. The pipeline proceeds as follows: - Tokenizing the ESC codes (onReceiveChar) - VT100 code page translation of plain characters (applyCharset) - Interpretation of ESC codes (processToken) The escape codes and their meaning are described in the technical reference of this program. */ // Tokens ------------------------------------------------------------------ -- /* Since the tokens are the central notion if this section, we've put them in front. They provide the syntactical elements used to represent the terminals operations as byte sequences. They are encodes here into a single machine word, so that we can later switch over them easily. Depending on the token itself, additional argument variables are filled with parameter values. The tokens are defined below: - CHR - Printable characters (32..255 but DEL (=127)) - CTL - Control characters (0..31 but ESC (= 27), DEL) - ESC - Escape codes of the form - ESC_DE - Escape codes of the form C - CSI_PN - Escape codes of the form '[' {Pn} ';' {Pn} C - CSI_PS - Escape codes of the form '[' {Pn} ';' ... C - CSI_PR - Escape codes of the form '[' '?' {Pn} ';' ... C - CSI_PE - Escape codes of the form '[' '!' {Pn} ';' ... C - CSI_SP - Escape codes of the form '[' ' ' C (3rd field is a space) - CSI_PSP - Escape codes of the form '[' '{Pn}' ' ' C (4th field is a space) - VT52 - VT52 escape codes - - 'Y'{Pc}{Pc} - XTE_HA - Xterm window/terminal attribute commands of the form `]' {Pn} `;' {Text} (Note that these are handled differently to the other formats) The last two forms allow list of arguments. Since the elements of the lists are treated individually the same way, they are passed as individual tokens to the interpretation. Further, because the meaning of the parameters are names (although represented as numbers), they are includes within the token ('N'). */ constexpr int token_construct(int t, int a, int n) { return (((n & 0xffff) << 16) | ((a & 0xff) << 8) | (t & 0xff)); } constexpr int token_chr() { return token_construct(0, 0, 0); } constexpr int token_ctl(int a) { return token_construct(1, a, 0); } constexpr int token_esc(int a) { return token_construct(2, a, 0); } constexpr int token_esc_cs(int a, int b) { return token_construct(3, a, b); } constexpr int token_esc_de(int a) { return token_construct(4, a, 0); } constexpr int token_csi_ps(int a, int n) { return token_construct(5, a, n); } constexpr int token_csi_pn(int a) { return token_construct(6, a, 0); } constexpr int token_csi_pr(int a, int n) { return token_construct(7, a, n); } constexpr int token_vt52(int a) { return token_construct(8, a, 0); } constexpr int token_csi_pg(int a) { return token_construct(9, a, 0); } constexpr int token_csi_pe(int a) { return token_construct(10, a, 0); } constexpr int token_csi_sp(int a) { return token_construct(11, a, 0); } constexpr int token_csi_psp(int a, int n) { return token_construct(12, a, n); } const int MAX_ARGUMENT = 4096; // Tokenizer --------------------------------------------------------------- -- /* The tokenizer's state The state is represented by the buffer (tokenBuffer, tokenBufferPos), and accompanied by decoded arguments kept in (argv,argc). Note that they are kept internal in the tokenizer. */ void Vt102Emulation::resetTokenizer() { tokenBufferPos = 0; argc = 0; argv[0] = 0; argv[1] = 0; } void Vt102Emulation::addDigit(int digit) { if (argv[argc] < MAX_ARGUMENT) { argv[argc] = 10 * argv[argc] + digit; } } void Vt102Emulation::addArgument() { argc = qMin(argc + 1, MAXARGS - 1); argv[argc] = 0; } void Vt102Emulation::addToCurrentToken(int cc) { tokenBuffer[tokenBufferPos] = cc; tokenBufferPos = qMin(tokenBufferPos + 1, MAX_TOKEN_LENGTH - 1); } // Character Class flags used while decoding const int CTL = 1; // Control character const int CHR = 2; // Printable character const int CPN = 4; // TODO: Document me const int DIG = 8; // Digit const int SCS = 16; // Select Character Set const int GRP = 32; // TODO: Document me const int CPS = 64; // Character which indicates end of window resize void Vt102Emulation::initTokenizer() { int i; quint8 *s; for (i = 0; i < 256; ++i) { charClass[i] = 0; } for (i = 0; i < 32; ++i) { charClass[i] |= CTL; } for (i = 32; i < 256; ++i) { charClass[i] |= CHR; } for (s = (quint8 *)"@ABCDGHILMPSTXZbcdfry"; *s != 0u; ++s) { charClass[*s] |= CPN; } // resize = \e[8;;t for (s = (quint8 *)"t"; *s != 0u; ++s) { charClass[*s] |= CPS; } for (s = (quint8 *)"0123456789"; *s != 0u; ++s) { charClass[*s] |= DIG; } for (s = (quint8 *)"()+*%"; *s != 0u; ++s) { charClass[*s] |= SCS; } for (s = (quint8 *)"()+*#[]%"; *s != 0u; ++s) { charClass[*s] |= GRP; } resetTokenizer(); } /* Ok, here comes the nasty part of the decoder. Instead of keeping an explicit state, we deduce it from the token scanned so far. It is then immediately combined with the current character to form a scanning decision. This is done by the following defines. - P is the length of the token scanned so far. - L (often P-1) is the position on which contents we base a decision. - C is a character or a group of characters (taken from 'charClass'). - 'cc' is the current character - 's' is a pointer to the start of the token buffer - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ #define lec(P,L,C) (p == (P) && s[(L)] == (C)) #define lun( ) (p == 1 && cc >= 32 ) #define les(P,L,C) (p == (P) && s[L] < 256 && (charClass[s[(L)]] & (C)) == (C)) #define eec(C) (p >= 3 && cc == (C)) #define ees(C) (p >= 3 && cc < 256 && (charClass[cc] & (C)) == (C)) #define eps(C) (p >= 3 && s[2] != '?' && s[2] != '!' && s[2] != '>' && cc < 256 && (charClass[cc] & (C)) == (C)) #define epp( ) (p >= 3 && s[2] == '?') #define epe( ) (p >= 3 && s[2] == '!') #define egt( ) (p >= 3 && s[2] == '>') #define esp( ) (p >= 4 && s[2] == SP ) #define epsp( ) (p >= 5 && s[3] == SP ) #define Xpe (tokenBufferPos >= 2 && tokenBuffer[1] == ']') #define Xte (Xpe && (cc == 7 || cc == 27)) #define ces(C) (cc < 256 && (charClass[cc] & (C)) == (C) && !Xte) #define dcs (p >= 2 && s[0] == ESC && s[1] == 'P') #define CNTL(c) ((c)-'@') const int ESC = 27; const int DEL = 127; const int SP = 32; // process an incoming unicode character -void Vt102Emulation::receiveChar(int cc) +void Vt102Emulation::receiveChar(uint cc) { if (cc == DEL) { return; //VT100: ignore. } if (ces(CTL)) { // DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 // This means, they do neither a resetTokenizer() nor a pushToToken(). Some of them, do // of course. Guess this originates from a weakly layered handling of the X-on // X-off protocol, which comes really below this level. if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) { resetTokenizer(); //VT100: CAN or SUB } if (cc != ESC) { processToken(token_ctl(cc+'@'), 0, 0); return; } } // advance the state addToCurrentToken(cc); int* s = tokenBuffer; const int p = tokenBufferPos; if (getMode(MODE_Ansi)) { if (lec(1,0,ESC)) { return; } if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } if (les(2,1,GRP)) { return; } if (Xte ) { processWindowAttributeRequest(); resetTokenizer(); return; } if (Xpe ) { return; } if (lec(3,2,'?')) { return; } if (lec(3,2,'>')) { return; } if (lec(3,2,'!')) { return; } if (lec(3,2,SP )) { return; } if (lec(4,3,SP )) { return; } if (lun( )) { processToken(token_chr(), applyCharset(cc), 0); resetTokenizer(); return; } if (dcs ) { return; /* TODO We don't xterm DCS, so we just eat it */ } if (lec(2,0,ESC)) { processToken(token_esc(s[1]), 0, 0); resetTokenizer(); return; } if (les(3,1,SCS)) { processToken(token_esc_cs(s[1],s[2]), 0, 0); resetTokenizer(); return; } if (lec(3,1,'#')) { processToken(token_esc_de(s[2]), 0, 0); resetTokenizer(); return; } if (eps( CPN)) { processToken(token_csi_pn(cc), argv[0],argv[1]); resetTokenizer(); return; } // resize = \e[8;;t if (eps(CPS)) { processToken(token_csi_ps(cc, argv[0]), argv[1], argv[2]); resetTokenizer(); return; } if (epe( )) { processToken(token_csi_pe(cc), 0, 0); resetTokenizer(); return; } if (esp ( )) { processToken(token_csi_sp(cc), 0, 0); resetTokenizer(); return; } if (epsp( )) { processToken(token_csi_psp(cc, argv[0]), 0, 0); resetTokenizer(); return; } if (ees(DIG)) { addDigit(cc-'0'); return; } if (eec(';')) { addArgument(); return; } for (int i = 0; i <= argc; i++) { if (epp()) { processToken(token_csi_pr(cc,argv[i]), 0, 0); } else if (egt()) { processToken(token_csi_pg(cc), 0, 0); // spec. case for ESC]>0c or ESC]>c } else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2) { // ESC[ ... 48;2;;; ... m -or- ESC[ ... 38;2;;; ... m i += 2; processToken(token_csi_ps(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[i+2]); i += 2; } else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) { // ESC[ ... 48;5; ... m -or- ESC[ ... 38;5; ... m i += 2; processToken(token_csi_ps(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } else { processToken(token_csi_ps(cc,argv[i]), 0, 0); } } resetTokenizer(); } else { // VT52 Mode if (lec(1,0,ESC)) { return; } if (les(1,0,CHR)) { processToken(token_chr(), s[0], 0); resetTokenizer(); return; } if (lec(2,1,'Y')) { return; } if (lec(3,1,'Y')) { return; } if (p < 4) { processToken(token_vt52(s[1] ), 0, 0); resetTokenizer(); return; } processToken(token_vt52(s[1]), s[2], s[3]); resetTokenizer(); return; } } void Vt102Emulation::processWindowAttributeRequest() { // Describes the window or terminal session attribute to change // See Session::UserTitleChange for possible values int attribute = 0; int i; for (i = 2; i < tokenBufferPos && tokenBuffer[i] >= '0' && tokenBuffer[i] <= '9'; i++) { attribute = 10 * attribute + (tokenBuffer[i]-'0'); } if (tokenBuffer[i] != ';') { reportDecodingError(); return; } QString value; value.reserve(tokenBufferPos-i-2); for (int j = 0; j < tokenBufferPos-i-2; j++) { value[j] = tokenBuffer[i+1+j]; } if (value == QLatin1String("?")) { emit sessionAttributeRequest(attribute); return; } _pendingTitleUpdates[attribute] = value; _titleUpdateTimer->start(20); } void Vt102Emulation::updateTitle() { QListIterator iter( _pendingTitleUpdates.keys() ); while (iter.hasNext()) { int arg = iter.next(); emit titleChanged( arg , _pendingTitleUpdates[arg] ); } _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- /* Now that the incoming character stream is properly tokenized, meaning is assigned to them. These are either operations of the current _screen, or of the emulation class itself. The token to be interpreted comes in as a machine word possibly accompanied by two parameters. Likewise, the operations assigned to, come with up to two arguments. One could consider to make up a proper table from the function below. The technical reference manual provides more information about this mapping. */ void Vt102Emulation::processToken(int token, int p, int q) { switch (token) { case token_chr( ) : _currentScreen->displayCharacter (p ); break; //UTF16 // 127 DEL : ignored on input case token_ctl('@' ) : /* NUL: ignored */ break; case token_ctl('A' ) : /* SOH: ignored */ break; case token_ctl('B' ) : /* STX: ignored */ break; case token_ctl('C' ) : /* ETX: ignored */ break; case token_ctl('D' ) : /* EOT: ignored */ break; case token_ctl('E' ) : reportAnswerBack ( ); break; //VT100 case token_ctl('F' ) : /* ACK: ignored */ break; case token_ctl('G' ) : emit stateSet(NOTIFYBELL); break; //VT100 case token_ctl('H' ) : _currentScreen->backspace ( ); break; //VT100 case token_ctl('I' ) : _currentScreen->tab ( ); break; //VT100 case token_ctl('J' ) : _currentScreen->newLine ( ); break; //VT100 case token_ctl('K' ) : _currentScreen->newLine ( ); break; //VT100 case token_ctl('L' ) : _currentScreen->newLine ( ); break; //VT100 case token_ctl('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 case token_ctl('N' ) : useCharset ( 1); break; //VT100 case token_ctl('O' ) : useCharset ( 0); break; //VT100 case token_ctl('P' ) : /* DLE: ignored */ break; case token_ctl('Q' ) : /* DC1: XON continue */ break; //VT100 case token_ctl('R' ) : /* DC2: ignored */ break; case token_ctl('S' ) : /* DC3: XOFF halt */ break; //VT100 case token_ctl('T' ) : /* DC4: ignored */ break; case token_ctl('U' ) : /* NAK: ignored */ break; case token_ctl('V' ) : /* SYN: ignored */ break; case token_ctl('W' ) : /* ETB: ignored */ break; case token_ctl('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case token_ctl('Y' ) : /* EM : ignored */ break; case token_ctl('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case token_ctl('[' ) : /* ESC: cannot be seen here. */ break; case token_ctl('\\' ) : /* FS : ignored */ break; case token_ctl(']' ) : /* GS : ignored */ break; case token_ctl('^' ) : /* RS : ignored */ break; case token_ctl('_' ) : /* US : ignored */ break; case token_esc('D' ) : _currentScreen->index ( ); break; //VT100 case token_esc('E' ) : _currentScreen->nextLine ( ); break; //VT100 case token_esc('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 case token_esc('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 case token_esc('Z' ) : reportTerminalType ( ); break; case token_esc('c' ) : reset ( ); break; case token_esc('n' ) : useCharset ( 2); break; case token_esc('o' ) : useCharset ( 3); break; case token_esc('7' ) : saveCursor ( ); break; case token_esc('8' ) : restoreCursor ( ); break; case token_esc('=' ) : setMode (MODE_AppKeyPad); break; case token_esc('>' ) : resetMode (MODE_AppKeyPad); break; case token_esc('<' ) : setMode (MODE_Ansi ); break; //VT100 case token_esc_cs('(', '0') : setCharset (0, '0'); break; //VT100 case token_esc_cs('(', 'A') : setCharset (0, 'A'); break; //VT100 case token_esc_cs('(', 'B') : setCharset (0, 'B'); break; //VT100 case token_esc_cs(')', '0') : setCharset (1, '0'); break; //VT100 case token_esc_cs(')', 'A') : setCharset (1, 'A'); break; //VT100 case token_esc_cs(')', 'B') : setCharset (1, 'B'); break; //VT100 case token_esc_cs('*', '0') : setCharset (2, '0'); break; //VT100 case token_esc_cs('*', 'A') : setCharset (2, 'A'); break; //VT100 case token_esc_cs('*', 'B') : setCharset (2, 'B'); break; //VT100 case token_esc_cs('+', '0') : setCharset (3, '0'); break; //VT100 case token_esc_cs('+', 'A') : setCharset (3, 'A'); break; //VT100 case token_esc_cs('+', 'B') : setCharset (3, 'B'); break; //VT100 case token_esc_cs('%', 'G') : setCodec (Utf8Codec ); break; //LINUX case token_esc_cs('%', '@') : setCodec (LocaleCodec ); break; //LINUX case token_esc_de('3' ) : /* Double height line, top half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case token_esc_de('4' ) : /* Double height line, bottom half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case token_esc_de('5' ) : /* Single width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case token_esc_de('6' ) : /* Double width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case token_esc_de('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;;t case token_csi_ps('t', 8) : setImageSize( p /*lines */, q /* columns */ ); emit imageResizeRequest(QSize(q, p)); break; // change tab text color : \e[28;t color: 0-16,777,215 case token_csi_ps('t', 28) : emit changeTabTextColorRequest ( p ); break; case token_csi_ps('K', 0) : _currentScreen->clearToEndOfLine ( ); break; case token_csi_ps('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; case token_csi_ps('K', 2) : _currentScreen->clearEntireLine ( ); break; case token_csi_ps('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; case token_csi_ps('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; case token_csi_ps('J', 2) : _currentScreen->clearEntireScreen ( ); break; case token_csi_ps('J', 3) : clearHistory(); break; case token_csi_ps('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 case token_csi_ps('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 case token_csi_ps('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; case token_csi_ps('h', 20) : setMode (MODE_NewLine ); break; case token_csi_ps('i', 0) : /* IGNORE: attached printer */ break; //VT100 case token_csi_ps('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; case token_csi_ps('l', 20) : resetMode (MODE_NewLine ); break; case token_csi_ps('s', 0) : saveCursor ( ); break; case token_csi_ps('u', 0) : restoreCursor ( ); break; case token_csi_ps('m', 0) : _currentScreen->setDefaultRendition ( ); break; case token_csi_ps('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 case token_csi_ps('m', 2) : _currentScreen-> setRendition (RE_FAINT ); break; case token_csi_ps('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); break; //VT100 case token_csi_ps('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 case token_csi_ps('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 case token_csi_ps('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; case token_csi_ps('m', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; case token_csi_ps('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; case token_csi_ps('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); break; case token_csi_ps('m', 10) : /* IGNORED: mapping related */ break; //LINUX case token_csi_ps('m', 11) : /* IGNORED: mapping related */ break; //LINUX case token_csi_ps('m', 12) : /* IGNORED: mapping related */ break; //LINUX case token_csi_ps('m', 21) : _currentScreen->resetRendition (RE_BOLD ); break; case token_csi_ps('m', 22) : _currentScreen->resetRendition (RE_BOLD ); _currentScreen->resetRendition (RE_FAINT ); break; case token_csi_ps('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 case token_csi_ps('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; case token_csi_ps('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; case token_csi_ps('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; case token_csi_ps('m', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; case token_csi_ps('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; case token_csi_ps('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); break; case token_csi_ps('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; case token_csi_ps('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; case token_csi_ps('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; case token_csi_ps('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; case token_csi_ps('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; case token_csi_ps('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; case token_csi_ps('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; case token_csi_ps('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; case token_csi_ps('m', 38) : _currentScreen->setForeColor (p, q); break; case token_csi_ps('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; case token_csi_ps('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; case token_csi_ps('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; case token_csi_ps('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; case token_csi_ps('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; case token_csi_ps('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; case token_csi_ps('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; case token_csi_ps('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; case token_csi_ps('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; case token_csi_ps('m', 48) : _currentScreen->setBackColor (p, q); break; case token_csi_ps('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; case token_csi_ps('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; case token_csi_ps('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; case token_csi_ps('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; case token_csi_ps('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; case token_csi_ps('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; case token_csi_ps('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; case token_csi_ps('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; case token_csi_ps('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; case token_csi_ps('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; case token_csi_ps('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; case token_csi_ps('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; case token_csi_ps('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; case token_csi_ps('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; case token_csi_ps('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; case token_csi_ps('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; case token_csi_ps('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; case token_csi_ps('n', 5) : reportStatus ( ); break; case token_csi_ps('n', 6) : reportCursorPosition ( ); break; case token_csi_ps('q', 0) : /* IGNORED: LEDs off */ break; //VT100 case token_csi_ps('q', 1) : /* IGNORED: LED1 on */ break; //VT100 case token_csi_ps('q', 2) : /* IGNORED: LED2 on */ break; //VT100 case token_csi_ps('q', 3) : /* IGNORED: LED3 on */ break; //VT100 case token_csi_ps('q', 4) : /* IGNORED: LED4 on */ break; //VT100 case token_csi_ps('x', 0) : reportTerminalParms ( 2); break; //VT100 case token_csi_ps('x', 1) : reportTerminalParms ( 3); break; //VT100 case token_csi_pn('@' ) : _currentScreen->insertChars (p ); break; case token_csi_pn('A' ) : _currentScreen->cursorUp (p ); break; //VT100 case token_csi_pn('B' ) : _currentScreen->cursorDown (p ); break; //VT100 case token_csi_pn('C' ) : _currentScreen->cursorRight (p ); break; //VT100 case token_csi_pn('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 case token_csi_pn('E' ) : /* Not implemented: cursor next p lines */ break; //VT100 case token_csi_pn('F' ) : /* Not implemented: cursor preceding p lines */ break; //VT100 case token_csi_pn('G' ) : _currentScreen->setCursorX (p ); break; //LINUX case token_csi_pn('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case token_csi_pn('I' ) : _currentScreen->tab (p ); break; case token_csi_pn('L' ) : _currentScreen->insertLines (p ); break; case token_csi_pn('M' ) : _currentScreen->deleteLines (p ); break; case token_csi_pn('P' ) : _currentScreen->deleteChars (p ); break; case token_csi_pn('S' ) : _currentScreen->scrollUp (p ); break; case token_csi_pn('T' ) : _currentScreen->scrollDown (p ); break; case token_csi_pn('X' ) : _currentScreen->eraseChars (p ); break; case token_csi_pn('Z' ) : _currentScreen->backtab (p ); break; case token_csi_pn('b' ) : _currentScreen->repeatChars (p ); break; case token_csi_pn('c' ) : reportTerminalType ( ); break; //VT100 case token_csi_pn('d' ) : _currentScreen->setCursorY (p ); break; //LINUX case token_csi_pn('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case token_csi_pn('r' ) : setMargins (p, q); break; //VT100 case token_csi_pn('y' ) : /* IGNORED: Confidence test */ break; //VT100 case token_csi_pr('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 case token_csi_pr('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 case token_csi_pr('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME case token_csi_pr('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME case token_csi_pr('l', 2) : resetMode (MODE_Ansi ); break; //VT100 case token_csi_pr('h', 3) : setMode (MODE_132Columns); break; //VT100 case token_csi_pr('l', 3) : resetMode (MODE_132Columns); break; //VT100 case token_csi_pr('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 case token_csi_pr('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 case token_csi_pr('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 case token_csi_pr('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 case token_csi_pr('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 case token_csi_pr('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 case token_csi_pr('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME case token_csi_pr('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME case token_csi_pr('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 case token_csi_pr('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 case token_csi_pr('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME case token_csi_pr('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME case token_csi_pr('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 case token_csi_pr('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 case token_csi_pr('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 case token_csi_pr('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 case token_csi_pr('h', 9) : /* IGNORED: interlace */ break; //VT100 case token_csi_pr('l', 9) : /* IGNORED: interlace */ break; //VT100 case token_csi_pr('s', 9) : /* IGNORED: interlace */ break; //VT100 case token_csi_pr('r', 9) : /* IGNORED: interlace */ break; //VT100 case token_csi_pr('h', 12) : /* IGNORED: Cursor blink */ break; //att610 case token_csi_pr('l', 12) : /* IGNORED: Cursor blink */ break; //att610 case token_csi_pr('s', 12) : /* IGNORED: Cursor blink */ break; //att610 case token_csi_pr('r', 12) : /* IGNORED: Cursor blink */ break; //att610 case token_csi_pr('h', 25) : setMode (MODE_Cursor ); break; //VT100 case token_csi_pr('l', 25) : resetMode (MODE_Cursor ); break; //VT100 case token_csi_pr('s', 25) : saveMode (MODE_Cursor ); break; //VT100 case token_csi_pr('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 case token_csi_pr('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM case token_csi_pr('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM case token_csi_pr('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case token_csi_pr('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case token_csi_pr('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case token_csi_pr('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case token_csi_pr('h', 47) : setMode (MODE_AppScreen); break; //VT100 case token_csi_pr('l', 47) : resetMode (MODE_AppScreen); break; //VT100 case token_csi_pr('s', 47) : saveMode (MODE_AppScreen); break; //XTERM case token_csi_pr('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM case token_csi_pr('h', 67) : /* IGNORED: DECBKM */ break; //XTERM case token_csi_pr('l', 67) : /* IGNORED: DECBKM */ break; //XTERM case token_csi_pr('s', 67) : /* IGNORED: DECBKM */ break; //XTERM case token_csi_pr('r', 67) : /* IGNORED: DECBKM */ break; //XTERM // XTerm defines the following modes: // SET_VT200_MOUSE 1000 // SET_VT200_HIGHLIGHT_MOUSE 1001 // SET_BTN_EVENT_MOUSE 1002 // SET_ANY_EVENT_MOUSE 1003 // //Note about mouse modes: //There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 //Konsole currently supports mode 1000 (basic mouse press and release) and mode 1002 (dragging the mouse). //TODO: Implementation of mouse modes 1001 (something called hilight tracking) and //1003 (a slight variation on dragging the mouse) // case token_csi_pr('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM case token_csi_pr('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM case token_csi_pr('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM case token_csi_pr('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM case token_csi_pr('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case token_csi_pr('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM case token_csi_pr('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case token_csi_pr('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case token_csi_pr('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM case token_csi_pr('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM case token_csi_pr('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM case token_csi_pr('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM case token_csi_pr('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM case token_csi_pr('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM case token_csi_pr('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM case token_csi_pr('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM case token_csi_pr('h', 1004) : _reportFocusEvents = true; break; case token_csi_pr('l', 1004) : _reportFocusEvents = false; break; case token_csi_pr('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM case token_csi_pr('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM case token_csi_pr('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM case token_csi_pr('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM case token_csi_pr('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM case token_csi_pr('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM case token_csi_pr('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM case token_csi_pr('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM case token_csi_pr('h', 1007) : setMode (MODE_Mouse1007); break; //XTERM case token_csi_pr('l', 1007) : resetMode (MODE_Mouse1007); break; //XTERM case token_csi_pr('s', 1007) : saveMode (MODE_Mouse1007); break; //XTERM case token_csi_pr('r', 1007) : restoreMode (MODE_Mouse1007); break; //XTERM case token_csi_pr('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT case token_csi_pr('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT case token_csi_pr('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT case token_csi_pr('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT case token_csi_pr('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM case token_csi_pr('h', 1047) : setMode (MODE_AppScreen); break; //XTERM case token_csi_pr('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM case token_csi_pr('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM case token_csi_pr('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM //FIXME: Unitoken: save translations case token_csi_pr('h', 1048) : saveCursor ( ); break; //XTERM case token_csi_pr('l', 1048) : restoreCursor ( ); break; //XTERM case token_csi_pr('s', 1048) : saveCursor ( ); break; //XTERM case token_csi_pr('r', 1048) : restoreCursor ( ); break; //XTERM //FIXME: every once new sequences like this pop up in xterm. // Here's a guess of what they could mean. case token_csi_pr('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM case token_csi_pr('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM case token_csi_pr('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM case token_csi_pr('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM case token_csi_pr('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM case token_csi_pr('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM // Set Cursor Style (DECSCUSR), VT520, with the extra xterm sequences // the first one is a special case, 'ESC[ q', which mimics 'ESC[1 q' case token_csi_sp ('q' ) : emit setCursorStyleRequest(Enum::BlockCursor, true); break; case token_csi_psp('q', 0) : emit setCursorStyleRequest(Enum::BlockCursor, true); break; case token_csi_psp('q', 1) : emit setCursorStyleRequest(Enum::BlockCursor, true); break; case token_csi_psp('q', 2) : emit setCursorStyleRequest(Enum::BlockCursor, false); break; case token_csi_psp('q', 3) : emit setCursorStyleRequest(Enum::UnderlineCursor, true); break; case token_csi_psp('q', 4) : emit setCursorStyleRequest(Enum::UnderlineCursor, false); break; case token_csi_psp('q', 5) : emit setCursorStyleRequest(Enum::IBeamCursor, true); break; case token_csi_psp('q', 6) : emit setCursorStyleRequest(Enum::IBeamCursor, false); break; //FIXME: weird DEC reset sequence case token_csi_pe('p' ) : /* IGNORED: reset ( ) */ break; //FIXME: when changing between vt52 and ansi mode evtl do some resetting. case token_vt52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 case token_vt52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 case token_vt52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 case token_vt52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 case token_vt52('F' ) : setAndUseCharset (0, '0'); break; //VT52 case token_vt52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 case token_vt52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 case token_vt52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 case token_vt52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 case token_vt52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 case token_vt52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 case token_vt52('Z' ) : reportTerminalType ( ); break; //VT52 case token_vt52('<' ) : setMode (MODE_Ansi ); break; //VT52 case token_vt52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 case token_vt52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 case token_csi_pg('c' ) : reportSecondaryAttributes( ); break; //VT100 default: reportDecodingError(); break; }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); setDefaultMargins(); _currentScreen->setCursorYX(0,0); } void Vt102Emulation::sendString(const QByteArray& s) { emit sendData(s); } void Vt102Emulation::reportCursorPosition() { char tmp[20]; snprintf(tmp, sizeof(tmp), "\033[%d;%dR", _currentScreen->getCursorY()+1, _currentScreen->getCursorX()+1); sendString(tmp); } void Vt102Emulation::reportTerminalType() { // Primary device attribute response (Request was: ^[[0c or ^[[c (from TT321 Users Guide)) // VT220: ^[[?63;1;2;3;6;7;8c (list deps on emul. capabilities) // VT100: ^[[?1;2c // VT101: ^[[?1;0c // VT102: ^[[?6v if (getMode(MODE_Ansi)) { sendString("\033[?1;2c"); // I'm a VT100 } else { sendString("\033/Z"); // I'm a VT52 } } void Vt102Emulation::reportSecondaryAttributes() { // Secondary device attribute response (Request was: ^[[>0c or ^[[>c) if (getMode(MODE_Ansi)) { sendString("\033[>0;115;0c"); // Why 115? ;) } else { sendString("\033/Z"); // FIXME I don't think VT52 knows about it but kept for } // konsoles backward compatibility. } /* DECREPTPARM – Report Terminal Parameters ESC [ ; ; ; ; ; ; x http://vt100.net/docs/vt100-ug/chapter3.html */ void Vt102Emulation::reportTerminalParms(int p) { char tmp[100]; /* sol=1: This message is a request; report in response to a request. par=1: No parity set nbits=1: 8 bits per character xspeed=112: 9600 rspeed=112: 9600 clkmul=1: The bit rate multiplier is 16. flags=0: None */ snprintf(tmp, sizeof(tmp), "\033[%d;1;1;112;112;1;0x", p); // not really true. sendString(tmp); } void Vt102Emulation::reportStatus() { sendString("\033[0n"); //VT100. Device status report. 0 = Ready. } void Vt102Emulation::reportAnswerBack() { // FIXME - Test this with VTTEST // This is really obsolete VT100 stuff. const char *ANSWER_BACK = ""; sendString(ANSWER_BACK); } /*! `cx',`cy' are 1-based. `cb' indicates the button pressed or released (0-2) or scroll event (4-5). eventType represents the kind of mouse action that occurred: 0 = Mouse button press 1 = Mouse drag 2 = Mouse button release */ void Vt102Emulation::sendMouseEvent(int cb, int cx, int cy, int eventType) { if (cx < 1 || cy < 1) { return; } // With the exception of the 1006 mode, button release is encoded in cb. // Note that if multiple extensions are enabled, the 1006 is used, so it's okay to check for only that. if (eventType == 2 && !getMode(MODE_Mouse1006)) { cb = 3; } // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button if (cb >= 4) { cb += 0x3c; } //Mouse motion handling if ((getMode(MODE_Mouse1002) || getMode(MODE_Mouse1003)) && eventType == 1) { cb += 0x20; //add 32 to signify motion event } char command[32]; command[0] = '\0'; // Check the extensions in decreasing order of preference. Encoding the release event above assumes that 1006 comes first. if (getMode(MODE_Mouse1006)) { snprintf(command, sizeof(command), "\033[<%d;%d;%d%c", cb, cx, cy, eventType == 2 ? 'm' : 'M'); } else if (getMode(MODE_Mouse1015)) { snprintf(command, sizeof(command), "\033[%d;%d;%dM", cb + 0x20, cx, cy); } else if (getMode(MODE_Mouse1005)) { if (cx <= 2015 && cy <= 2015) { // The xterm extension uses UTF-8 (up to 2 bytes) to encode // coordinate+32, no matter what the locale is. We could easily // convert manually, but QString can also do it for us. QChar coords[2]; coords[0] = cx + 0x20; coords[1] = cy + 0x20; QString coordsStr = QString(coords, 2); QByteArray utf8 = coordsStr.toUtf8(); snprintf(command, sizeof(command), "\033[M%c%s", cb + 0x20, utf8.constData()); } } else if (cx <= 223 && cy <= 223) { snprintf(command, sizeof(command), "\033[M%c%c%c", cb + 0x20, cx + 0x20, cy + 0x20); } sendString(command); } /** * The focus lost event can be used by Vim (or other terminal applications) * to recognize that the konsole window has lost focus. * The escape sequence is also used by iTerm2. * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusLost autocmd: https://github.com/sjl/vitality.vim */ void Vt102Emulation::focusLost() { if (_reportFocusEvents) { sendString("\033[O"); } } /** * The focus gained event can be used by Vim (or other terminal applications) * to recognize that the konsole window has gained focus again. * The escape sequence is also used by iTerm2. * Vim needs the following plugin to be installed to convert the escape * sequence into the FocusGained autocmd: https://github.com/sjl/vitality.vim */ void Vt102Emulation::focusGained() { if (_reportFocusEvents) { sendString("\033[I"); } } void Vt102Emulation::sendText(const QString &text) { if (!text.isEmpty()) { QKeyEvent event(QEvent::KeyPress, 0, Qt::NoModifier, text); sendKeyEvent(&event); // expose as a big fat keypress event } } void Vt102Emulation::sendKeyEvent(QKeyEvent *event) { const Qt::KeyboardModifiers modifiers = event->modifiers(); KeyboardTranslator::States states = KeyboardTranslator::NoState; TerminalDisplay * currentView = _currentScreen->currentTerminalDisplay(); bool isReadOnly = false; if (currentView != nullptr && currentView->sessionController() != nullptr) { isReadOnly = currentView->sessionController()->isReadOnly(); } // get current states if (getMode(MODE_NewLine)) { states |= KeyboardTranslator::NewLineState; } if (getMode(MODE_Ansi)) { states |= KeyboardTranslator::AnsiState; } if (getMode(MODE_AppCuKeys)) { states |= KeyboardTranslator::CursorKeysState; } if (getMode(MODE_AppScreen)) { states |= KeyboardTranslator::AlternateScreenState; } if (getMode(MODE_AppKeyPad) && ((modifiers &Qt::KeypadModifier) != 0u)) { states |= KeyboardTranslator::ApplicationKeypadState; } if (!isReadOnly) { // check flow control state if ((modifiers &Qt::ControlModifier) != 0u) { switch (event->key()) { case Qt::Key_S: emit flowControlKeyPressed(true); break; case Qt::Key_Q: case Qt::Key_C: // cancel flow control emit flowControlKeyPressed(false); break; } } } // look up key binding if (_keyTranslator != nullptr) { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( event->key(), modifiers, states); // send result to terminal QByteArray textToSend; // special handling for the Alt (aka. Meta) modifier. pressing // Alt+[Character] results in Esc+[Character] being sent // (unless there is an entry defined for this particular combination // in the keyboard modifier) const bool wantsAltModifier = ((entry.modifiers() & entry.modifierMask() & Qt::AltModifier) != 0u); const bool wantsMetaModifier = ((entry.modifiers() & entry.modifierMask() & Qt::MetaModifier) != 0u); const bool wantsAnyModifier = ((entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState) != 0); if ( ((modifiers & Qt::AltModifier) != 0u) && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\033"); } if ( ((modifiers & Qt::MetaModifier) != 0u) && !(wantsMetaModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\030@s"); } if ( entry.command() != KeyboardTranslator::NoCommand ) { if ((entry.command() & KeyboardTranslator::EraseCommand) != 0) { textToSend += eraseChar(); } if (currentView != nullptr) { if ((entry.command() & KeyboardTranslator::ScrollPageUpCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollPages, -1); } else if ((entry.command() & KeyboardTranslator::ScrollPageDownCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollPages, 1); } else if ((entry.command() & KeyboardTranslator::ScrollLineUpCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, -1); } else if ((entry.command() & KeyboardTranslator::ScrollLineDownCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, 1); } else if ((entry.command() & KeyboardTranslator::ScrollUpToTopCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, - currentView->screenWindow()->currentLine()); } else if ((entry.command() & KeyboardTranslator::ScrollDownToBottomCommand) != 0) { currentView->scrollScreenWindow(ScreenWindow::ScrollLines, lineCount()); } } } else if (!entry.text().isEmpty()) { textToSend += entry.text(true,modifiers); } else { textToSend += _codec->fromUnicode(event->text()); } if (!isReadOnly) { emit sendData(textToSend); } } else { if (!isReadOnly) { // print an error message to the terminal if no key translator has been // set QString translatorError = i18n("No keyboard translator available. " "The information needed to convert key presses " "into characters to send to the terminal " "is missing."); reset(); receiveData(translatorError.toLatin1().constData(), translatorError.count()); } } } /* ------------------------------------------------------------------------- */ /* */ /* VT100 Charsets */ /* */ /* ------------------------------------------------------------------------- */ // Character Set Conversion ------------------------------------------------ -- /* The processing contains a VT100 specific code translation layer. It's still in use and mainly responsible for the line drawing graphics. These and some other glyphs are assigned to codes (0x5f-0xfe) normally occupied by the latin letters. Since this codes also appear within control sequences, the extra code conversion does not permute with the tokenizer and is placed behind it in the pipeline. It only applies to tokens, which represent plain characters. This conversion it eventually continued in TerminalDisplay.C, since it might involve VT100 enhanced fonts, which have these particular glyphs allocated in (0x00-0x1f) in their code page. */ #define CHARSET _charset[_currentScreen == _screen[1]] // Apply current character map. -unsigned short Vt102Emulation::applyCharset(unsigned short c) +unsigned int Vt102Emulation::applyCharset(uint c) { if (CHARSET.graphic && 0x5f <= c && c <= 0x7e) { return vt100_graphics[c - 0x5f]; } if (CHARSET.pound && c == '#') { return 0xa3; //This mode is obsolete } return c; } /* "Charset" related part of the emulation state. This configures the VT100 charset filter. While most operation work on the current _screen, the following two are different. */ void Vt102Emulation::resetCharset(int scrno) { _charset[scrno].cu_cs = 0; qstrncpy(_charset[scrno].charset, "BBBB", 4); _charset[scrno].sa_graphic = false; _charset[scrno].sa_pound = false; _charset[scrno].graphic = false; _charset[scrno].pound = false; } void Vt102Emulation::setCharset(int n, int cs) // on both screens. { _charset[0].charset[n & 3] = cs; useCharset(_charset[0].cu_cs); _charset[1].charset[n & 3] = cs; useCharset(_charset[1].cu_cs); } void Vt102Emulation::setAndUseCharset(int n, int cs) { CHARSET.charset[n & 3] = cs; useCharset(n & 3); } void Vt102Emulation::useCharset(int n) { CHARSET.cu_cs = n & 3; CHARSET.graphic = (CHARSET.charset[n & 3] == '0'); CHARSET.pound = (CHARSET.charset[n & 3] == 'A'); //This mode is obsolete } void Vt102Emulation::setDefaultMargins() { _screen[0]->setDefaultMargins(); _screen[1]->setDefaultMargins(); } void Vt102Emulation::setMargins(int t, int b) { _screen[0]->setMargins(t, b); _screen[1]->setMargins(t, b); } void Vt102Emulation::saveCursor() { CHARSET.sa_graphic = CHARSET.graphic; CHARSET.sa_pound = CHARSET.pound; //This mode is obsolete // we are not clear about these //sa_charset = charsets[cScreen->_charset]; //sa_charset_num = cScreen->_charset; _currentScreen->saveCursor(); } void Vt102Emulation::restoreCursor() { CHARSET.graphic = CHARSET.sa_graphic; CHARSET.pound = CHARSET.sa_pound; //This mode is obsolete _currentScreen->restoreCursor(); } /* ------------------------------------------------------------------------- */ /* */ /* Mode Operations */ /* */ /* ------------------------------------------------------------------------- */ /* Some of the emulations state is either added to the state of the screens. This causes some scoping problems, since different emulations choose to located the mode either to the current _screen or to both. For strange reasons, the extend of the rendition attributes ranges over all screens and not over the actual _screen. We decided on the precise precise extend, somehow. */ // "Mode" related part of the state. These are all booleans. void Vt102Emulation::resetModes() { // MODE_Allow132Columns is not reset here // to match Xterm's behavior (see Xterm's VTReset() function) resetMode(MODE_132Columns); saveMode(MODE_132Columns); resetMode(MODE_Mouse1000); saveMode(MODE_Mouse1000); resetMode(MODE_Mouse1001); saveMode(MODE_Mouse1001); resetMode(MODE_Mouse1002); saveMode(MODE_Mouse1002); resetMode(MODE_Mouse1003); saveMode(MODE_Mouse1003); resetMode(MODE_Mouse1005); saveMode(MODE_Mouse1005); resetMode(MODE_Mouse1006); saveMode(MODE_Mouse1006); resetMode(MODE_Mouse1007); saveMode(MODE_Mouse1007); resetMode(MODE_Mouse1015); saveMode(MODE_Mouse1015); resetMode(MODE_BracketedPaste); saveMode(MODE_BracketedPaste); resetMode(MODE_AppScreen); saveMode(MODE_AppScreen); resetMode(MODE_AppCuKeys); saveMode(MODE_AppCuKeys); resetMode(MODE_AppKeyPad); saveMode(MODE_AppKeyPad); resetMode(MODE_NewLine); setMode(MODE_Ansi); } void Vt102Emulation::setMode(int m) { _currentModes.mode[m] = true; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) { clearScreenAndSetColumns(132); } else { _currentModes.mode[m] = false; } break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: emit programUsesMouseChanged(false); break; case MODE_Mouse1007: emit enableAlternateScrolling(true); break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(true); break; case MODE_AppScreen: _screen[1]->setDefaultRendition(); _screen[1]->clearSelection(); setScreen(1); break; } // FIXME: Currently this has a redundant condition as MODES_SCREEN is 6 // and MODE_NewLine is 5 if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->setMode(m); _screen[1]->setMode(m); } } void Vt102Emulation::resetMode(int m) { _currentModes.mode[m] = false; switch (m) { case MODE_132Columns: if (getMode(MODE_Allow132Columns)) { clearScreenAndSetColumns(80); } break; case MODE_Mouse1000: case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: emit programUsesMouseChanged(true); break; case MODE_Mouse1007: emit enableAlternateScrolling(false); break; case MODE_BracketedPaste: emit programBracketedPasteModeChanged(false); break; case MODE_AppScreen: _screen[0]->clearSelection(); setScreen(0); break; } // FIXME: Currently this has a redundant condition as MODES_SCREEN is 6 // and MODE_NewLine is 5 if (m < MODES_SCREEN || m == MODE_NewLine) { _screen[0]->resetMode(m); _screen[1]->resetMode(m); } } void Vt102Emulation::saveMode(int m) { _savedModes.mode[m] = _currentModes.mode[m]; } void Vt102Emulation::restoreMode(int m) { if (_savedModes.mode[m]) { setMode(m); } else { resetMode(m); } } bool Vt102Emulation::getMode(int m) { return _currentModes.mode[m]; } char Vt102Emulation::eraseChar() const { KeyboardTranslator::Entry entry = _keyTranslator->findEntry( Qt::Key_Backspace, nullptr, nullptr); if (entry.text().count() > 0) { return entry.text().at(0); } else { return '\b'; } } #if 0 // print contents of the scan buffer static void hexdump(int *s, int len) { int i; for (i = 0; i < len; i++) { if (s[i] == '\\') { printf("\\\\"); } else if ((s[i]) > 32 && s[i] < 127) { printf("%c", s[i]); } else { printf("\\%04x(hex)", s[i]); } } } #endif // return contents of the scan buffer static QString hexdump2(int *s, int len) { int i; char dump[128]; QString returnDump; for (i = 0; i < len; i++) { if (s[i] == '\\') { snprintf(dump, sizeof(dump), "%s", "\\\\"); } else if ((s[i]) > 32 && s[i] < 127) { snprintf(dump, sizeof(dump), "%c", s[i]); } else { snprintf(dump, sizeof(dump), "\\%04x(hex)", s[i]); } returnDump.append(QLatin1String(dump)); } return returnDump; } void Vt102Emulation::reportDecodingError() { if (tokenBufferPos == 0 || (tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32)) { return; } // printf("Undecodable sequence: "); // hexdump(tokenBuffer, tokenBufferPos); // printf("\n"); QString outputError = QStringLiteral("Undecodable sequence: "); outputError.append(hexdump2(tokenBuffer, tokenBufferPos)); //qDebug() << outputError; } diff --git a/src/Vt102Emulation.h b/src/Vt102Emulation.h index 65c61da7..0136ce82 100644 --- a/src/Vt102Emulation.h +++ b/src/Vt102Emulation.h @@ -1,196 +1,196 @@ /* This file is part of Konsole, an X terminal. Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle 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. */ #ifndef VT102EMULATION_H #define VT102EMULATION_H // Qt #include // Konsole #include "Emulation.h" #include "Screen.h" class QTimer; class QKeyEvent; #define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 #define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) #define MODE_AppKeyPad (MODES_SCREEN+2) // #define MODE_Mouse1000 (MODES_SCREEN+3) // Send mouse X,Y position on press and release #define MODE_Mouse1001 (MODES_SCREEN+4) // Use Hilight mouse tracking #define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion mouse tracking #define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking #define MODE_Mouse1005 (MODES_SCREEN+7) // Xterm-style extended coordinates #define MODE_Mouse1006 (MODES_SCREEN+8) // 2nd Xterm-style extended coordinates #define MODE_Mouse1007 (MODES_SCREEN+9) // XTerm Alternate Scroll mode; also check AlternateScrolling profile property #define MODE_Mouse1015 (MODES_SCREEN+10) // Urxvt-style extended coordinates #define MODE_Ansi (MODES_SCREEN+11) // Use US Ascii for character sets G0-G3 (DECANM) #define MODE_132Columns (MODES_SCREEN+12) // 80 <-> 132 column mode switch (DECCOLM) #define MODE_Allow132Columns (MODES_SCREEN+13) // Allow DECCOLM mode #define MODE_BracketedPaste (MODES_SCREEN+14) // Xterm-style bracketed paste mode #define MODE_total (MODES_SCREEN+15) namespace Konsole { extern unsigned short vt100_graphics[32]; struct CharCodes { // coding info char charset[4]; // int cu_cs; // actual charset. bool graphic; // Some VT100 tricks bool pound; // Some VT100 tricks bool sa_graphic; // saved graphic bool sa_pound; // saved pound }; /** * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * A full description of this terminal can be found at http://vt100.net/docs/vt102-ug/ * * In addition, various additional xterm escape sequences are supported to provide * features such as mouse input handling. * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape * sequences. * */ class Vt102Emulation : public Emulation { Q_OBJECT public: /** Constructs a new emulation */ Vt102Emulation(); ~Vt102Emulation() Q_DECL_OVERRIDE; // reimplemented from Emulation void clearEntireScreen() Q_DECL_OVERRIDE; void reset() Q_DECL_OVERRIDE; char eraseChar() const Q_DECL_OVERRIDE; public Q_SLOTS: // reimplemented from Emulation void sendString(const QByteArray &string) Q_DECL_OVERRIDE; void sendText(const QString &text) Q_DECL_OVERRIDE; void sendKeyEvent(QKeyEvent *) Q_DECL_OVERRIDE; void sendMouseEvent(int buttons, int column, int line, int eventType) Q_DECL_OVERRIDE; void focusLost() Q_DECL_OVERRIDE; void focusGained() Q_DECL_OVERRIDE; protected: // reimplemented from Emulation void setMode(int mode) Q_DECL_OVERRIDE; void resetMode(int mode) Q_DECL_OVERRIDE; - void receiveChar(int cc) Q_DECL_OVERRIDE; + void receiveChar(uint cc) Q_DECL_OVERRIDE; private Q_SLOTS: //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates //used to buffer multiple title updates void updateTitle(); private: - unsigned short applyCharset(unsigned short c); + unsigned int applyCharset(uint c); void setCharset(int n, int cs); void useCharset(int n); void setAndUseCharset(int n, int cs); void saveCursor(); void restoreCursor(); void resetCharset(int scrno); void setMargins(int top, int bottom); //set margins for all screens back to their defaults void setDefaultMargins(); // returns true if 'mode' is set or false otherwise bool getMode(int mode); // saves the current boolean value of 'mode' void saveMode(int mode); // restores the boolean value of 'mode' void restoreMode(int mode); // resets all modes // (except MODE_Allow132Columns) void resetModes(); void resetTokenizer(); #define MAX_TOKEN_LENGTH 256 // Max length of tokens (e.g. window title) void addToCurrentToken(int cc); int tokenBuffer[MAX_TOKEN_LENGTH]; //FIXME: overflow? int tokenBufferPos; #define MAXARGS 15 void addDigit(int dig); void addArgument(); int argv[MAXARGS]; int argc; void initTokenizer(); // Set of flags for each of the ASCII characters which indicates // what category they fall into (printable character, control, digit etc.) // for the purposes of decoding terminal output int charClass[256]; void reportDecodingError(); void processToken(int code, int p, int q); void processWindowAttributeRequest(); void requestWindowAttribute(int); void reportTerminalType(); void reportSecondaryAttributes(); void reportStatus(); void reportAnswerBack(); void reportCursorPosition(); void reportTerminalParms(int p); // clears the screen and resizes it to the specified // number of columns void clearScreenAndSetColumns(int columnCount); CharCodes _charset[2]; class TerminalState { public: // Initializes all modes to false TerminalState() { memset(&mode, 0, MODE_total * sizeof(bool)); } bool mode[MODE_total]; }; TerminalState _currentModes; TerminalState _savedModes; //hash table and timer for buffering calls to the session instance //to update the name of the session //or window title. //these calls occur when certain escape sequences are seen in the //output from the terminal QHash _pendingTitleUpdates; QTimer *_titleUpdateTimer; bool _reportFocusEvents; }; } #endif // VT102EMULATION_H diff --git a/src/autotests/CharacterWidthTest.cpp b/src/autotests/CharacterWidthTest.cpp index 93529e13..b5709361 100644 --- a/src/autotests/CharacterWidthTest.cpp +++ b/src/autotests/CharacterWidthTest.cpp @@ -1,70 +1,70 @@ /* Copyright 2014 by Kurt Hindenburg 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 "CharacterWidthTest.h" // KDE #include #include "../konsole_wcwidth.h" #include "konsoleprivate_export.h" using namespace Konsole; void CharacterWidthTest::testWidth_data() { - QTest::addColumn("character"); + QTest::addColumn("character"); QTest::addColumn("width"); /* This is a work in progress.... */ /* konsole_wcwidth uses -1 C0/C1 and DEL */ - QTest::newRow("0xE007F") << quint16(0xE007F) << -1; - - QTest::newRow("0x0300") << quint16(0x0300) << 0; - QTest::newRow("0x070F") << quint16(0x070F) << 0; - QTest::newRow("0x1160") << quint16(0x1160) << 0; - QTest::newRow("0x10300") << quint16(0x10300) << 0; - - QTest::newRow("a") << quint16('a') << 1; - QTest::newRow("0x00AD") << quint16(0x00AD) << 1; - QTest::newRow("0x00A0") << quint16(0x00A0) << 1; - QTest::newRow("0x10FB") << quint16(0x10FB) << 1; - QTest::newRow("0xFF76") << quint16(0xFF76) << 1; - QTest::newRow("0x103A0") << quint16(0x103A0) << 1; - QTest::newRow("0x10A06") << quint16(0x10A06) << 1; - - QTest::newRow("0x3000") << quint16(0x3000) << 2; - QTest::newRow("0x300a") << quint16(0x300a) << 2; - QTest::newRow("0x300b") << quint16(0x300b) << 2; - QTest::newRow("0xFF01") << quint16(0xFF01) << 2; - QTest::newRow("0xFF5F") << quint16(0xFF5F) << 2; - QTest::newRow("0xFF60") << quint16(0xFF60) << 2; - QTest::newRow("0xFFe0") << quint16(0xFFe6) << 2; + QTest::newRow("0x007F") << uint(0x007F) << -1; + + QTest::newRow("0x0300") << uint(0x0300) << 0; + QTest::newRow("0x070F") << uint(0x070F) << 0; + QTest::newRow("0x1160") << uint(0x1160) << 0; + QTest::newRow("0x10300") << uint(0x10300) << 1; + + QTest::newRow("a") << uint('a') << 1; + QTest::newRow("0x00AD") << uint(0x00AD) << 1; + QTest::newRow("0x00A0") << uint(0x00A0) << 1; + QTest::newRow("0x10FB") << uint(0x10FB) << 1; + QTest::newRow("0xFF76") << uint(0xFF76) << 1; + QTest::newRow("0x103A0") << uint(0x103A0) << 1; + QTest::newRow("0x10A06") << uint(0x10A06) << 0; + + QTest::newRow("0x3000") << uint(0x3000) << 2; + QTest::newRow("0x300a") << uint(0x300a) << 2; + QTest::newRow("0x300b") << uint(0x300b) << 2; + QTest::newRow("0xFF01") << uint(0xFF01) << 2; + QTest::newRow("0xFF5F") << uint(0xFF5F) << 2; + QTest::newRow("0xFF60") << uint(0xFF60) << 2; + QTest::newRow("0xFFe0") << uint(0xFFe6) << 2; } void CharacterWidthTest::testWidth() { - QFETCH(quint16, character); + QFETCH(uint, character); QTEST(konsole_wcwidth(character), "width"); } QTEST_GUILESS_MAIN(CharacterWidthTest) diff --git a/src/konsole_wcwidth.cpp b/src/konsole_wcwidth.cpp index 322e3257..9316db17 100644 --- a/src/konsole_wcwidth.cpp +++ b/src/konsole_wcwidth.cpp @@ -1,238 +1,238 @@ // krazy:excludeall=copyright,license // krazy does not recognize Unicode License/Copyright see COPYING.Unicode /* $XFree86: xc/programs/xterm/wcwidth.characters,v 1.9 2006/06/19 00:36:52 dickey Exp $ */ /* * This is an implementation of wcwidth() and wcswidth() (defined in * IEEE Std 1002.1-2001) for Unicode. * * http://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html * http://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html * * In fixed-width output devices, Latin characters all occupy a single * "cell" position of equal width, whereas ideographic CJK characters * occupy two such cells. Interoperability between terminal-line * applications and (teletype-style) character terminals using the * UTF-8 encoding requires agreement on which character should advance * the cursor by how many cell positions. No established formal * standards exist at present on which Unicode character shall occupy * how many cell positions on character terminals. These routines are * a first attempt of defining such behavior based on simple rules * applied to data provided by the Unicode Consortium. * * For some graphical characters, the Unicode standard explicitly * defines a character-cell width via the definition of the East Asian * FullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes. * In all these cases, there is no ambiguity about which width a * terminal shall use. For characters in the East Asian Ambiguous (A) * class, the width choice depends purely on a preference of backward * compatibility with either historic CJK or Western practice. * Choosing single-width for these characters is easy to justify as * the appropriate long-term solution, as the CJK practice of * displaying these characters as double-width comes from historic * implementation simplicity (8-bit encoded characters were displayed * single-width and 16-bit ones double-width, even for Greek, * Cyrillic, etc.) and not any typographic considerations. * * Much less clear is the choice of width for the Not East Asian * (Neutral) class. Existing practice does not dictate a width for any * of these characters. It would nevertheless make sense * typographically to allocate two character cells to characters such * as for instance EM SPACE or VOLUME INTEGRAL, which cannot be * represented adequately with a single-width glyph. The following * routines at present merely assign a single-cell width to all * neutral characters, in the interest of simplicity. This is not * entirely satisfactory and should be reconsidered before * establishing a formal standard in this area. At the moment, the * decision which Not East Asian (Neutral) characters should be * represented by double-width glyphs cannot yet be answered by * applying a simple rule from the Unicode database content. Setting * up a proper standard for the behavior of UTF-8 character terminals * will require a careful analysis not only of each Unicode character, * but also of each presentation form, something the author of these * routines has avoided to do so far. * * http://www.unicode.org/unicode/reports/tr11/ * * Markus Kuhn -- 2007-05-25 (Unicode 5.0) * * Permission to use, copy, modify, and distribute this software * for any purpose and without fee is hereby granted. The author * disclaims all warranties with regard to this software. * * Latest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c */ /* * Adaptions for KDE by Waldo Bastian and * Francesco Cecconi * See COPYING.Unicode for the license for the original wcwidth.c */ // Own #include "konsole_wcwidth.h" #include "konsoleprivate_export.h" +// Qt +#include + struct interval { unsigned long first; unsigned long last; }; /* auxiliary function for binary search in interval table */ static int bisearch(unsigned long ucs, const struct interval* table, int max) { int min = 0; if (ucs < table[0].first || ucs > table[max].last) { return 0; } while (max >= min) { const int mid = (min + max) / 2; if (ucs > table[mid].last) { min = mid + 1; } else if (ucs < table[mid].first) { max = mid - 1; } else { return 1; } } return 0; } /* The following functions define the column width of an ISO 10646 * character as follows: * * - The null character (U+0000) has a column width of 0. * * - Other C0/C1 control characters and DEL will lead to a return * value of -1. * * - Non-spacing and enclosing combining characters (general * category code Mn or Me in the Unicode database) have a * column width of 0. * * - Other format characters (general category code Cf in the Unicode * database) and ZERO WIDTH SPACE (U+200B) have a column width of 0. * * - Hangul Jamo medial vowels and final consonants (U+1160-U+11FF) * have a column width of 0. * * - Spacing characters in the East Asian Wide (W) or East Asian * FullWidth (F) category as defined in Unicode Technical * Report #11 have a column width of 2. * * - All remaining characters (including all printable * ISO 8859-1 and WGL4 characters, Unicode control characters, * etc.) have a column width of 1. * * This implementation assumes that quint16 characters are encoded * in ISO 10646. */ -int KONSOLEPRIVATE_EXPORT konsole_wcwidth(quint16 oucs) +int KONSOLEPRIVATE_EXPORT konsole_wcwidth(uint ucs) { - /* NOTE: It is not possible to compare quint16 with the new last four lines of characters, - * therefore this cast is now necessary. - */ - unsigned long ucs = static_cast(oucs); /* sorted list of non-overlapping intervals of non-spacing characters */ /* generated by "uniset +cat=Me +cat=Mn +cat=Cf -00AD +1160-11FF +200B c" */ static const struct interval combining[] = { { 0x0300, 0x036F }, { 0x0483, 0x0486 }, { 0x0488, 0x0489 }, { 0x0591, 0x05BD }, { 0x05BF, 0x05BF }, { 0x05C1, 0x05C2 }, { 0x05C4, 0x05C5 }, { 0x05C7, 0x05C7 }, { 0x0600, 0x0603 }, { 0x0610, 0x0615 }, { 0x064B, 0x065E }, { 0x0670, 0x0670 }, { 0x06D6, 0x06E4 }, { 0x06E7, 0x06E8 }, { 0x06EA, 0x06ED }, { 0x070F, 0x070F }, { 0x0711, 0x0711 }, { 0x0730, 0x074A }, { 0x07A6, 0x07B0 }, { 0x07EB, 0x07F3 }, { 0x0901, 0x0902 }, { 0x093C, 0x093C }, { 0x0941, 0x0948 }, { 0x094D, 0x094D }, { 0x0951, 0x0954 }, { 0x0962, 0x0963 }, { 0x0981, 0x0981 }, { 0x09BC, 0x09BC }, { 0x09C1, 0x09C4 }, { 0x09CD, 0x09CD }, { 0x09E2, 0x09E3 }, { 0x0A01, 0x0A02 }, { 0x0A3C, 0x0A3C }, { 0x0A41, 0x0A42 }, { 0x0A47, 0x0A48 }, { 0x0A4B, 0x0A4D }, { 0x0A70, 0x0A71 }, { 0x0A81, 0x0A82 }, { 0x0ABC, 0x0ABC }, { 0x0AC1, 0x0AC5 }, { 0x0AC7, 0x0AC8 }, { 0x0ACD, 0x0ACD }, { 0x0AE2, 0x0AE3 }, { 0x0B01, 0x0B01 }, { 0x0B3C, 0x0B3C }, { 0x0B3F, 0x0B3F }, { 0x0B41, 0x0B43 }, { 0x0B4D, 0x0B4D }, { 0x0B56, 0x0B56 }, { 0x0B82, 0x0B82 }, { 0x0BC0, 0x0BC0 }, { 0x0BCD, 0x0BCD }, { 0x0C3E, 0x0C40 }, { 0x0C46, 0x0C48 }, { 0x0C4A, 0x0C4D }, { 0x0C55, 0x0C56 }, { 0x0CBC, 0x0CBC }, { 0x0CBF, 0x0CBF }, { 0x0CC6, 0x0CC6 }, { 0x0CCC, 0x0CCD }, { 0x0CE2, 0x0CE3 }, { 0x0D41, 0x0D43 }, { 0x0D4D, 0x0D4D }, { 0x0DCA, 0x0DCA }, { 0x0DD2, 0x0DD4 }, { 0x0DD6, 0x0DD6 }, { 0x0E31, 0x0E31 }, { 0x0E34, 0x0E3A }, { 0x0E47, 0x0E4E }, { 0x0EB1, 0x0EB1 }, { 0x0EB4, 0x0EB9 }, { 0x0EBB, 0x0EBC }, { 0x0EC8, 0x0ECD }, { 0x0F18, 0x0F19 }, { 0x0F35, 0x0F35 }, { 0x0F37, 0x0F37 }, { 0x0F39, 0x0F39 }, { 0x0F71, 0x0F7E }, { 0x0F80, 0x0F84 }, { 0x0F86, 0x0F87 }, { 0x0F90, 0x0F97 }, { 0x0F99, 0x0FBC }, { 0x0FC6, 0x0FC6 }, { 0x102D, 0x1030 }, { 0x1032, 0x1032 }, { 0x1036, 0x1037 }, { 0x1039, 0x1039 }, { 0x1058, 0x1059 }, { 0x1160, 0x11FF }, { 0x135F, 0x135F }, { 0x1712, 0x1714 }, { 0x1732, 0x1734 }, { 0x1752, 0x1753 }, { 0x1772, 0x1773 }, { 0x17B4, 0x17B5 }, { 0x17B7, 0x17BD }, { 0x17C6, 0x17C6 }, { 0x17C9, 0x17D3 }, { 0x17DD, 0x17DD }, { 0x180B, 0x180D }, { 0x18A9, 0x18A9 }, { 0x1920, 0x1922 }, { 0x1927, 0x1928 }, { 0x1932, 0x1932 }, { 0x1939, 0x193B }, { 0x1A17, 0x1A18 }, { 0x1B00, 0x1B03 }, { 0x1B34, 0x1B34 }, { 0x1B36, 0x1B3A }, { 0x1B3C, 0x1B3C }, { 0x1B42, 0x1B42 }, { 0x1B6B, 0x1B73 }, { 0x1DC0, 0x1DCA }, { 0x1DFE, 0x1DFF }, { 0x200B, 0x200F }, { 0x202A, 0x202E }, { 0x2060, 0x2063 }, { 0x206A, 0x206F }, { 0x20D0, 0x20EF }, { 0x302A, 0x302F }, { 0x3099, 0x309A }, { 0xA806, 0xA806 }, { 0xA80B, 0xA80B }, { 0xA825, 0xA826 }, { 0xFB1E, 0xFB1E }, { 0xFE00, 0xFE0F }, { 0xFE20, 0xFE23 }, { 0xFEFF, 0xFEFF }, { 0xFFF9, 0xFFFB }, { 0x10A01, 0x10A03 }, { 0x10A05, 0x10A06 }, { 0x10A0C, 0x10A0F }, { 0x10A38, 0x10A3A }, { 0x10A3F, 0x10A3F }, { 0x1D167, 0x1D169 }, { 0x1D173, 0x1D182 }, { 0x1D185, 0x1D18B }, { 0x1D1AA, 0x1D1AD }, { 0x1D242, 0x1D244 }, { 0xE0001, 0xE0001 }, { 0xE0020, 0xE007F }, { 0xE0100, 0xE01EF } }; /* test for 8-bit control characters */ if (ucs == 0 || QChar::isLowSurrogate(ucs)) { return 0; } /* Always assume double width, otherwise we have to go back and move characters */ if (QChar::isHighSurrogate(ucs)) { return 2; } if (ucs < 32 || (ucs >= 0x7f && ucs < 0xa0)) { return -1; } /* binary search in table of non-spacing characters */ if (bisearch(ucs, combining, sizeof(combining) / sizeof(struct interval) - 1) != 0) { return 0; } /* if we arrive here, ucs is not a combining or C0/C1 control character */ return 1 + static_cast(ucs >= 0x1100 && (ucs <= 0x115f || /* Hangul Jamo init. consonants */ ucs == 0x2329 || ucs == 0x232a || (ucs >= 0x2e80 && ucs <= 0xa4cf && ucs != 0x303f) || /* CJK ... Yi */ (ucs >= 0xac00 && ucs <= 0xd7a3) || /* Hangul Syllables */ (ucs >= 0xf900 && ucs <= 0xfaff) || /* CJK Compatibility Ideographs */ (ucs >= 0xfe10 && ucs <= 0xfe19) || /* Vertical forms */ (ucs >= 0xfe30 && ucs <= 0xfe6f) || /* CJK Compatibility Forms */ (ucs >= 0xff00 && ucs <= 0xff60) || /* Fullwidth Forms */ (ucs >= 0xffe0 && ucs <= 0xffe6) || (ucs >= 0x20000 && ucs <= 0x2fffd) || (ucs >= 0x30000 && ucs <= 0x3fffd))); } int string_width(const QString& text) { int w = 0; - for (auto i : text) { - w += konsole_wcwidth(i.unicode()); + auto ucs4 = text.toUcs4(); + for (auto i : ucs4) { + w += konsole_wcwidth(i); } return w; } diff --git a/src/konsole_wcwidth.h b/src/konsole_wcwidth.h index 30ff8cad..600621c6 100644 --- a/src/konsole_wcwidth.h +++ b/src/konsole_wcwidth.h @@ -1,16 +1,16 @@ /* $XFree86: xc/programs/xterm/wcwidth.h,v 1.5 2005/05/03 00:38:25 dickey Exp $ */ /* Markus Kuhn -- 2001-01-12 -- public domain */ /* Adaptions for KDE by Waldo Bastian */ #ifndef KONSOLE_WCWIDTH_H #define KONSOLE_WCWIDTH_H // Qt #include -int konsole_wcwidth(quint16 oucs); +int konsole_wcwidth(uint ucs); int string_width(const QString &text); #endif