diff --git a/src/Screen.cpp b/src/Screen.cpp index 5642df8f..a58e6dd2 100644 --- a/src/Screen.cpp +++ b/src/Screen.cpp @@ -1,1496 +1,1517 @@ /* 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): _lines(lines), _columns(columns), _screenLines(new ImageLine[_lines + 1]), _screenLinesSize(_lines), _scrolledLines(0), _droppedLines(0), _history(new HistoryScrollNone()), _cuX(0), _cuY(0), _currentRendition(DEFAULT_RENDITION), _topMargin(0), _bottomMargin(0), _selBegin(0), _selTopLeft(0), _selBottomRight(0), _blockSelectionMode(false), _effectiveForeground(CharacterColor()), _effectiveBackground(CharacterColor()), _effectiveRendition(DEFAULT_RENDITION), - _lastPos(-1) + _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]; } for (int i = _lines; (i > 0) && (i < new_lines + 1); i++) { newScreenLines[i].resize(new_columns); } _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 } } // mark the character at the current cursor position int cursorIndex = loc(_cuX, _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) { // 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)) { 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 }; currentChar.rendition |= RE_EXTENDED_CHAR; currentChar.character = ExtendedCharTable::instance.createExtendedChar(chars, 2); } else { ushort extendedCharLength; const ushort* 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); 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 = _columns - w; } } // 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 _cuX; } 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); //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); if (_currentForeground.isValid()) { updateEffectiveRendition(); } else { setForeColor(COLOR_SPACE_DEFAULT, DEFAULT_FORE_COLOR); } } void Screen::setBackColor(int space, int color) { _currentBackground = CharacterColor(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 868508f7..3aedf4f2 100644 --- a/src/Screen.h +++ b/src/Screen.h @@ -1,727 +1,735 @@ /* 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 preceeding 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); /** * 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 Konsole::Screen::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 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 Konsole::Screen::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 Konsole::Screen::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; }; } Q_DECLARE_OPERATORS_FOR_FLAGS(Konsole::Screen::DecodingOptions) #endif // SCREEN_H diff --git a/src/Vt102Emulation.cpp b/src/Vt102Emulation.cpp index a75e03b2..b07fb073 100644 --- a/src/Vt102Emulation.cpp +++ b/src/Vt102Emulation.cpp @@ -1,1443 +1,1444 @@ /* 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 "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(), _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); } 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 - 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'). */ #define TY_CONSTRUCT(T,A,N) ( ((((int)(N)) & 0xffff) << 16) | ((((int)(A)) & 0xff) << 8) | (((int)(T)) & 0xff) ) #define TY_CHR( ) TY_CONSTRUCT(0,0,0) #define TY_CTL(A ) TY_CONSTRUCT(1,A,0) #define TY_ESC(A ) TY_CONSTRUCT(2,A,0) #define TY_ESC_CS(A,B) TY_CONSTRUCT(3,A,B) #define TY_ESC_DE(A ) TY_CONSTRUCT(4,A,0) #define TY_CSI_PS(A,N) TY_CONSTRUCT(5,A,N) #define TY_CSI_PN(A ) TY_CONSTRUCT(6,A,0) #define TY_CSI_PR(A,N) TY_CONSTRUCT(7,A,N) #define TY_VT52(A) TY_CONSTRUCT(8,A,0) #define TY_CSI_PG(A) TY_CONSTRUCT(9,A,0) #define TY_CSI_PE(A) TY_CONSTRUCT(10,A,0) 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 *)"@ABCDGHILMPSTXZcdfry"; *s != 0u; ++s) { + 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 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; // process an incoming unicode character void Vt102Emulation::receiveChar(int 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(TY_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 (lun( )) { processToken( TY_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( TY_ESC(s[1]), 0, 0); resetTokenizer(); return; } if (les(3,1,SCS)) { processToken( TY_ESC_CS(s[1],s[2]), 0, 0); resetTokenizer(); return; } if (lec(3,1,'#')) { processToken( TY_ESC_DE(s[2]), 0, 0); resetTokenizer(); return; } if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; } // resize = \e[8;;t if (eps(CPS)) { processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); resetTokenizer(); return; } if (epe( )) { processToken( TY_CSI_PE(cc), 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(TY_CSI_PR(cc,argv[i]), 0, 0); } else if (egt()) { processToken(TY_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(TY_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(TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); } else { processToken(TY_CSI_PS(cc,argv[i]), 0, 0); } } resetTokenizer(); } else { // VT52 Mode if (lec(1,0,ESC)) { return; } if (les(1,0,CHR)) { processToken( TY_CHR(), s[0], 0); resetTokenizer(); return; } if (lec(2,1,'Y')) { return; } if (lec(3,1,'Y')) { return; } if (p < 4) { processToken(TY_VT52(s[1] ), 0, 0); resetTokenizer(); return; } processToken(TY_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 TY_CHR( ) : _currentScreen->displayCharacter (p ); break; //UTF16 // 127 DEL : ignored on input case TY_CTL('@' ) : /* NUL: ignored */ break; case TY_CTL('A' ) : /* SOH: ignored */ break; case TY_CTL('B' ) : /* STX: ignored */ break; case TY_CTL('C' ) : /* ETX: ignored */ break; case TY_CTL('D' ) : /* EOT: ignored */ break; case TY_CTL('E' ) : reportAnswerBack ( ); break; //VT100 case TY_CTL('F' ) : /* ACK: ignored */ break; case TY_CTL('G' ) : emit stateSet(NOTIFYBELL); break; //VT100 case TY_CTL('H' ) : _currentScreen->backspace ( ); break; //VT100 case TY_CTL('I' ) : _currentScreen->tab ( ); break; //VT100 case TY_CTL('J' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('K' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('L' ) : _currentScreen->newLine ( ); break; //VT100 case TY_CTL('M' ) : _currentScreen->toStartOfLine ( ); break; //VT100 case TY_CTL('N' ) : useCharset ( 1); break; //VT100 case TY_CTL('O' ) : useCharset ( 0); break; //VT100 case TY_CTL('P' ) : /* DLE: ignored */ break; case TY_CTL('Q' ) : /* DC1: XON continue */ break; //VT100 case TY_CTL('R' ) : /* DC2: ignored */ break; case TY_CTL('S' ) : /* DC3: XOFF halt */ break; //VT100 case TY_CTL('T' ) : /* DC4: ignored */ break; case TY_CTL('U' ) : /* NAK: ignored */ break; case TY_CTL('V' ) : /* SYN: ignored */ break; case TY_CTL('W' ) : /* ETB: ignored */ break; case TY_CTL('X' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('Y' ) : /* EM : ignored */ break; case TY_CTL('Z' ) : _currentScreen->displayCharacter ( 0x2592); break; //VT100 case TY_CTL('[' ) : /* ESC: cannot be seen here. */ break; case TY_CTL('\\' ) : /* FS : ignored */ break; case TY_CTL(']' ) : /* GS : ignored */ break; case TY_CTL('^' ) : /* RS : ignored */ break; case TY_CTL('_' ) : /* US : ignored */ break; case TY_ESC('D' ) : _currentScreen->index ( ); break; //VT100 case TY_ESC('E' ) : _currentScreen->nextLine ( ); break; //VT100 case TY_ESC('H' ) : _currentScreen->changeTabStop (true ); break; //VT100 case TY_ESC('M' ) : _currentScreen->reverseIndex ( ); break; //VT100 case TY_ESC('Z' ) : reportTerminalType ( ); break; case TY_ESC('c' ) : reset ( ); break; case TY_ESC('n' ) : useCharset ( 2); break; case TY_ESC('o' ) : useCharset ( 3); break; case TY_ESC('7' ) : saveCursor ( ); break; case TY_ESC('8' ) : restoreCursor ( ); break; case TY_ESC('=' ) : setMode (MODE_AppKeyPad); break; case TY_ESC('>' ) : resetMode (MODE_AppKeyPad); break; case TY_ESC('<' ) : setMode (MODE_Ansi ); break; //VT100 case TY_ESC_CS('(', '0') : setCharset (0, '0'); break; //VT100 case TY_ESC_CS('(', 'A') : setCharset (0, 'A'); break; //VT100 case TY_ESC_CS('(', 'B') : setCharset (0, 'B'); break; //VT100 case TY_ESC_CS(')', '0') : setCharset (1, '0'); break; //VT100 case TY_ESC_CS(')', 'A') : setCharset (1, 'A'); break; //VT100 case TY_ESC_CS(')', 'B') : setCharset (1, 'B'); break; //VT100 case TY_ESC_CS('*', '0') : setCharset (2, '0'); break; //VT100 case TY_ESC_CS('*', 'A') : setCharset (2, 'A'); break; //VT100 case TY_ESC_CS('*', 'B') : setCharset (2, 'B'); break; //VT100 case TY_ESC_CS('+', '0') : setCharset (3, '0'); break; //VT100 case TY_ESC_CS('+', 'A') : setCharset (3, 'A'); break; //VT100 case TY_ESC_CS('+', 'B') : setCharset (3, 'B'); break; //VT100 case TY_ESC_CS('%', 'G') : setCodec (Utf8Codec ); break; //LINUX case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); break; //LINUX case TY_ESC_DE('3' ) : /* Double height line, top half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('4' ) : /* Double height line, bottom half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; case TY_ESC_DE('5' ) : /* Single width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('6' ) : /* Double width, single height line*/ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); break; case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); break; // resize = \e[8;;t case TY_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 TY_CSI_PS('t', 28) : emit changeTabTextColorRequest ( p ); break; case TY_CSI_PS('K', 0) : _currentScreen->clearToEndOfLine ( ); break; case TY_CSI_PS('K', 1) : _currentScreen->clearToBeginOfLine ( ); break; case TY_CSI_PS('K', 2) : _currentScreen->clearEntireLine ( ); break; case TY_CSI_PS('J', 0) : _currentScreen->clearToEndOfScreen ( ); break; case TY_CSI_PS('J', 1) : _currentScreen->clearToBeginOfScreen ( ); break; case TY_CSI_PS('J', 2) : _currentScreen->clearEntireScreen ( ); break; case TY_CSI_PS('J', 3) : clearHistory(); break; case TY_CSI_PS('g', 0) : _currentScreen->changeTabStop (false ); break; //VT100 case TY_CSI_PS('g', 3) : _currentScreen->clearTabStops ( ); break; //VT100 case TY_CSI_PS('h', 4) : _currentScreen-> setMode (MODE_Insert ); break; case TY_CSI_PS('h', 20) : setMode (MODE_NewLine ); break; case TY_CSI_PS('i', 0) : /* IGNORE: attached printer */ break; //VT100 case TY_CSI_PS('l', 4) : _currentScreen-> resetMode (MODE_Insert ); break; case TY_CSI_PS('l', 20) : resetMode (MODE_NewLine ); break; case TY_CSI_PS('s', 0) : saveCursor ( ); break; case TY_CSI_PS('u', 0) : restoreCursor ( ); break; case TY_CSI_PS('m', 0) : _currentScreen->setDefaultRendition ( ); break; case TY_CSI_PS('m', 1) : _currentScreen-> setRendition (RE_BOLD ); break; //VT100 case TY_CSI_PS('m', 2) : _currentScreen-> setRendition (RE_FAINT ); break; case TY_CSI_PS('m', 3) : _currentScreen-> setRendition (RE_ITALIC ); break; //VT100 case TY_CSI_PS('m', 4) : _currentScreen-> setRendition (RE_UNDERLINE); break; //VT100 case TY_CSI_PS('m', 5) : _currentScreen-> setRendition (RE_BLINK ); break; //VT100 case TY_CSI_PS('m', 7) : _currentScreen-> setRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 8) : _currentScreen-> setRendition (RE_CONCEAL ); break; case TY_CSI_PS('m', 9) : _currentScreen-> setRendition (RE_STRIKEOUT); break; case TY_CSI_PS('m', 53) : _currentScreen-> setRendition (RE_OVERLINE ); break; case TY_CSI_PS('m', 10) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 11) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 12) : /* IGNORED: mapping related */ break; //LINUX case TY_CSI_PS('m', 21) : _currentScreen->resetRendition (RE_BOLD ); break; case TY_CSI_PS('m', 22) : _currentScreen->resetRendition (RE_BOLD ); _currentScreen->resetRendition (RE_FAINT ); break; case TY_CSI_PS('m', 23) : _currentScreen->resetRendition (RE_ITALIC ); break; //VT100 case TY_CSI_PS('m', 24) : _currentScreen->resetRendition (RE_UNDERLINE); break; case TY_CSI_PS('m', 25) : _currentScreen->resetRendition (RE_BLINK ); break; case TY_CSI_PS('m', 27) : _currentScreen->resetRendition (RE_REVERSE ); break; case TY_CSI_PS('m', 28) : _currentScreen->resetRendition (RE_CONCEAL ); break; case TY_CSI_PS('m', 29) : _currentScreen->resetRendition (RE_STRIKEOUT); break; case TY_CSI_PS('m', 55) : _currentScreen->resetRendition (RE_OVERLINE ); break; case TY_CSI_PS('m', 30) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 31) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 32) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 33) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 34) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 35) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 36) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 37) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 38) : _currentScreen->setForeColor (p, q); break; case TY_CSI_PS('m', 39) : _currentScreen->setForeColor (COLOR_SPACE_DEFAULT, 0); break; case TY_CSI_PS('m', 40) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 0); break; case TY_CSI_PS('m', 41) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 1); break; case TY_CSI_PS('m', 42) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 2); break; case TY_CSI_PS('m', 43) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 3); break; case TY_CSI_PS('m', 44) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 4); break; case TY_CSI_PS('m', 45) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 5); break; case TY_CSI_PS('m', 46) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 6); break; case TY_CSI_PS('m', 47) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 7); break; case TY_CSI_PS('m', 48) : _currentScreen->setBackColor (p, q); break; case TY_CSI_PS('m', 49) : _currentScreen->setBackColor (COLOR_SPACE_DEFAULT, 1); break; case TY_CSI_PS('m', 90) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 91) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 92) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 93) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 94) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 95) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 96) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 97) : _currentScreen->setForeColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('m', 100) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 8); break; case TY_CSI_PS('m', 101) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 9); break; case TY_CSI_PS('m', 102) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 10); break; case TY_CSI_PS('m', 103) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 11); break; case TY_CSI_PS('m', 104) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 12); break; case TY_CSI_PS('m', 105) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 13); break; case TY_CSI_PS('m', 106) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 14); break; case TY_CSI_PS('m', 107) : _currentScreen->setBackColor (COLOR_SPACE_SYSTEM, 15); break; case TY_CSI_PS('n', 5) : reportStatus ( ); break; case TY_CSI_PS('n', 6) : reportCursorPosition ( ); break; case TY_CSI_PS('q', 0) : /* IGNORED: LEDs off */ break; //VT100 case TY_CSI_PS('q', 1) : /* IGNORED: LED1 on */ break; //VT100 case TY_CSI_PS('q', 2) : /* IGNORED: LED2 on */ break; //VT100 case TY_CSI_PS('q', 3) : /* IGNORED: LED3 on */ break; //VT100 case TY_CSI_PS('q', 4) : /* IGNORED: LED4 on */ break; //VT100 case TY_CSI_PS('x', 0) : reportTerminalParms ( 2); break; //VT100 case TY_CSI_PS('x', 1) : reportTerminalParms ( 3); break; //VT100 case TY_CSI_PN('@' ) : _currentScreen->insertChars (p ); break; case TY_CSI_PN('A' ) : _currentScreen->cursorUp (p ); break; //VT100 case TY_CSI_PN('B' ) : _currentScreen->cursorDown (p ); break; //VT100 case TY_CSI_PN('C' ) : _currentScreen->cursorRight (p ); break; //VT100 case TY_CSI_PN('D' ) : _currentScreen->cursorLeft (p ); break; //VT100 case TY_CSI_PN('E' ) : /* Not implemented: cursor next p lines */ break; //VT100 case TY_CSI_PN('F' ) : /* Not implemented: cursor preceding p lines */ break; //VT100 case TY_CSI_PN('G' ) : _currentScreen->setCursorX (p ); break; //LINUX case TY_CSI_PN('H' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('I' ) : _currentScreen->tab (p ); break; case TY_CSI_PN('L' ) : _currentScreen->insertLines (p ); break; case TY_CSI_PN('M' ) : _currentScreen->deleteLines (p ); break; case TY_CSI_PN('P' ) : _currentScreen->deleteChars (p ); break; case TY_CSI_PN('S' ) : _currentScreen->scrollUp (p ); break; case TY_CSI_PN('T' ) : _currentScreen->scrollDown (p ); break; case TY_CSI_PN('X' ) : _currentScreen->eraseChars (p ); break; case TY_CSI_PN('Z' ) : _currentScreen->backtab (p ); break; + case TY_CSI_PN('b' ) : _currentScreen->repeatChars (p ); break; case TY_CSI_PN('c' ) : reportTerminalType ( ); break; //VT100 case TY_CSI_PN('d' ) : _currentScreen->setCursorY (p ); break; //LINUX case TY_CSI_PN('f' ) : _currentScreen->setCursorYX (p, q); break; //VT100 case TY_CSI_PN('r' ) : setMargins (p, q); break; //VT100 case TY_CSI_PN('y' ) : /* IGNORED: Confidence test */ break; //VT100 case TY_CSI_PR('h', 1) : setMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('l', 1) : resetMode (MODE_AppCuKeys); break; //VT100 case TY_CSI_PR('s', 1) : saveMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('r', 1) : restoreMode (MODE_AppCuKeys); break; //FIXME case TY_CSI_PR('l', 2) : resetMode (MODE_Ansi ); break; //VT100 case TY_CSI_PR('h', 3) : setMode (MODE_132Columns); break; //VT100 case TY_CSI_PR('l', 3) : resetMode (MODE_132Columns); break; //VT100 case TY_CSI_PR('h', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('l', 4) : /* IGNORED: soft scrolling */ break; //VT100 case TY_CSI_PR('h', 5) : _currentScreen-> setMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('l', 5) : _currentScreen-> resetMode (MODE_Screen ); break; //VT100 case TY_CSI_PR('h', 6) : _currentScreen-> setMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('l', 6) : _currentScreen-> resetMode (MODE_Origin ); break; //VT100 case TY_CSI_PR('s', 6) : _currentScreen-> saveMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('r', 6) : _currentScreen->restoreMode (MODE_Origin ); break; //FIXME case TY_CSI_PR('h', 7) : _currentScreen-> setMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('l', 7) : _currentScreen-> resetMode (MODE_Wrap ); break; //VT100 case TY_CSI_PR('s', 7) : _currentScreen-> saveMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('r', 7) : _currentScreen->restoreMode (MODE_Wrap ); break; //FIXME case TY_CSI_PR('h', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('l', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('s', 8) : /* IGNORED: autorepeat on */ break; //VT100 case TY_CSI_PR('r', 8) : /* IGNORED: autorepeat off */ break; //VT100 case TY_CSI_PR('h', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('l', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('s', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('r', 9) : /* IGNORED: interlace */ break; //VT100 case TY_CSI_PR('h', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('l', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('s', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('r', 12) : /* IGNORED: Cursor blink */ break; //att610 case TY_CSI_PR('h', 25) : setMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('l', 25) : resetMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('s', 25) : saveMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('r', 25) : restoreMode (MODE_Cursor ); break; //VT100 case TY_CSI_PR('h', 40) : setMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('l', 40) : resetMode(MODE_Allow132Columns ); break; // XTERM case TY_CSI_PR('h', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('l', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('s', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('r', 41) : /* IGNORED: obsolete more(1) fix */ break; //XTERM case TY_CSI_PR('h', 47) : setMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('l', 47) : resetMode (MODE_AppScreen); break; //VT100 case TY_CSI_PR('s', 47) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 47) : restoreMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('h', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('l', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_CSI_PR('s', 67) : /* IGNORED: DECBKM */ break; //XTERM case TY_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 TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('s', 1000) : saveMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('r', 1000) : restoreMode (MODE_Mouse1000); break; //XTERM case TY_CSI_PR('h', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('l', 1001) : resetMode (MODE_Mouse1001); break; //XTERM case TY_CSI_PR('s', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('r', 1001) : /* IGNORED: hilite mouse tracking */ break; //XTERM case TY_CSI_PR('h', 1002) : setMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('l', 1002) : resetMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('s', 1002) : saveMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('r', 1002) : restoreMode (MODE_Mouse1002); break; //XTERM case TY_CSI_PR('h', 1003) : setMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('l', 1003) : resetMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('s', 1003) : saveMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('r', 1003) : restoreMode (MODE_Mouse1003); break; //XTERM case TY_CSI_PR('h', 1004) : _reportFocusEvents = true; break; case TY_CSI_PR('l', 1004) : _reportFocusEvents = false; break; case TY_CSI_PR('h', 1005) : setMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('l', 1005) : resetMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('s', 1005) : saveMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('r', 1005) : restoreMode (MODE_Mouse1005); break; //XTERM case TY_CSI_PR('h', 1006) : setMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('l', 1006) : resetMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('s', 1006) : saveMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('r', 1006) : restoreMode (MODE_Mouse1006); break; //XTERM case TY_CSI_PR('h', 1015) : setMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('l', 1015) : resetMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('s', 1015) : saveMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('r', 1015) : restoreMode (MODE_Mouse1015); break; //URXVT case TY_CSI_PR('h', 1034) : /* IGNORED: 8bitinput activation */ break; //XTERM case TY_CSI_PR('h', 1047) : setMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1047) : _screen[1]->clearEntireScreen(); resetMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('s', 1047) : saveMode (MODE_AppScreen); break; //XTERM case TY_CSI_PR('r', 1047) : restoreMode (MODE_AppScreen); break; //XTERM //FIXME: Unitoken: save translations case TY_CSI_PR('h', 1048) : saveCursor ( ); break; //XTERM case TY_CSI_PR('l', 1048) : restoreCursor ( ); break; //XTERM case TY_CSI_PR('s', 1048) : saveCursor ( ); break; //XTERM case TY_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 TY_CSI_PR('h', 1049) : saveCursor(); _screen[1]->clearEntireScreen(); setMode(MODE_AppScreen); break; //XTERM case TY_CSI_PR('l', 1049) : resetMode(MODE_AppScreen); restoreCursor(); break; //XTERM case TY_CSI_PR('h', 2004) : setMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('l', 2004) : resetMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('s', 2004) : saveMode (MODE_BracketedPaste); break; //XTERM case TY_CSI_PR('r', 2004) : restoreMode (MODE_BracketedPaste); break; //XTERM //FIXME: weird DEC reset sequence case TY_CSI_PE('p' ) : /* IGNORED: reset ( ) */ break; //FIXME: when changing between vt52 and ansi mode evtl do some resetting. case TY_VT52('A' ) : _currentScreen->cursorUp ( 1); break; //VT52 case TY_VT52('B' ) : _currentScreen->cursorDown ( 1); break; //VT52 case TY_VT52('C' ) : _currentScreen->cursorRight ( 1); break; //VT52 case TY_VT52('D' ) : _currentScreen->cursorLeft ( 1); break; //VT52 case TY_VT52('F' ) : setAndUseCharset (0, '0'); break; //VT52 case TY_VT52('G' ) : setAndUseCharset (0, 'B'); break; //VT52 case TY_VT52('H' ) : _currentScreen->setCursorYX (1,1 ); break; //VT52 case TY_VT52('I' ) : _currentScreen->reverseIndex ( ); break; //VT52 case TY_VT52('J' ) : _currentScreen->clearToEndOfScreen ( ); break; //VT52 case TY_VT52('K' ) : _currentScreen->clearToEndOfLine ( ); break; //VT52 case TY_VT52('Y' ) : _currentScreen->setCursorYX (p-31,q-31 ); break; //VT52 case TY_VT52('Z' ) : reportTerminalType ( ); break; //VT52 case TY_VT52('<' ) : setMode (MODE_Ansi ); break; //VT52 case TY_VT52('=' ) : setMode (MODE_AppKeyPad); break; //VT52 case TY_VT52('>' ) : resetMode (MODE_AppKeyPad); break; //VT52 case TY_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; // 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; } // 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 ) { TerminalDisplay * currentView = _currentScreen->currentTerminalDisplay(); if ((entry.command() & KeyboardTranslator::EraseCommand) != 0) { textToSend += eraseChar(); } else 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()); } emit sendData(textToSend); } else { // 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) { 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_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_BracketedPaste: emit programBracketedPasteModeChanged(true); break; case MODE_AppScreen: _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_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; }