diff --git a/CMakeLists.txt b/CMakeLists.txt index bef40ee..db60068 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -15,7 +15,6 @@ set(QTERMWIDGET_VERSION_PATCH "0") set(QTERMWIDGET_VERSION "${QTERMWIDGET_VERSION_MAJOR}.${QTERMWIDGET_VERSION_MINOR}.${QTERMWIDGET_VERSION_PATCH}") - include(CheckFunctionExists) include(GNUInstallDirs) @@ -92,15 +91,15 @@ set(HDRS_DISTRIB ) # dirs -set(KB_LAYOUT_DIR "${CMAKE_INSTALL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/kb-layouts/") +set(KB_LAYOUT_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/kb-layouts") message(STATUS "Keyboard layouts will be installed in: ${KB_LAYOUT_DIR}") -add_definitions(-DKB_LAYOUT_DIR="${CMAKE_INSTALL_PREFIX}/${KB_LAYOUT_DIR}") +add_definitions(-DKB_LAYOUT_DIR="${KB_LAYOUT_DIR}") -set(COLORSCHEMES_DIR "${CMAKE_INSTALL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/color-schemes/") +set(COLORSCHEMES_DIR "${CMAKE_INSTALL_FULL_DATADIR}/${QTERMWIDGET_LIBRARY_NAME}/color-schemes") message(STATUS "Color schemes will be installed in: ${COLORSCHEMES_DIR}" ) -add_definitions(-DCOLORSCHEMES_DIR="${CMAKE_INSTALL_PREFIX}/${COLORSCHEMES_DIR}") +add_definitions(-DCOLORSCHEMES_DIR="${COLORSCHEMES_DIR}") -set(QTERMWIDGET_INCLUDE_DIR "${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_INCLUDEDIR}/${QTERMWIDGET_LIBRARY_NAME}") +set(QTERMWIDGET_INCLUDE_DIR "${CMAKE_INSTALL_FULL_INCLUDEDIR}/${QTERMWIDGET_LIBRARY_NAME}") #| Defines add_definitions(-DHAVE_POSIX_OPENPT -DHAVE_SYS_TIME_H) @@ -133,7 +132,7 @@ set_target_properties( ${QTERMWIDGET_LIBRARY_NAME} PROPERTIES if(APPLE) set (CMAKE_SKIP_RPATH 1) # this is a must to load the lib correctly - set_target_properties( ${QTERMWIDGET_LIBRARY_NAME} PROPERTIES INSTALL_NAME_DIR ${CMAKE_INSTALL_PREFIX}/${CMAKE_INSTALL_LIBDIR} ) + set_target_properties(${QTERMWIDGET_LIBRARY_NAME} PROPERTIES INSTALL_NAME_DIR ${CMAKE_INSTALL_FULL_LIBDIR}) endif() install(TARGETS ${QTERMWIDGET_LIBRARY_NAME} DESTINATION "${CMAKE_INSTALL_LIBDIR}") @@ -195,11 +194,11 @@ if (BUILD_DESIGNER_PLUGIN) if(APPLE) # this is a must to load the lib correctly set_target_properties(qtermwidget4plugin PROPERTIES - INSTALL_NAME_DIR "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/qt4/plugins/designer" + INSTALL_NAME_DIR "${CMAKE_INSTALL_FULL_LIBDIR}/qt4/plugins/designer" ) endif() - install(TARGETS qtermwidget4plugin DESTINATION "${CMAKE_INSTALL_PREFIX}/lib${LIB_SUFFIX}/qt4/plugins/designer") + install(TARGETS qtermwidget4plugin DESTINATION "${CMAKE_INSTALL_FULL_LIBDIR}/qt4/plugins/designer") endif (BUILD_DESIGNER_PLUGIN) # end of designer plugin diff --git a/lib/Character.h b/lib/Character.h index ce0f1b3..9a0a42d 100644 --- a/lib/Character.h +++ b/lib/Character.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, KDE's terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -56,7 +56,7 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2); class Character { public: - /** + /** * Constructs a new character. * * @param _c The unicode character value of this character. @@ -74,25 +74,25 @@ public: { /** The unicode character value for this character. */ quint16 character; - /** + /** * Experimental addition which allows a single Character instance to contain more than * one unicode character. * * charSequence is a hash code which can be used to look up the unicode * character sequence in the ExtendedCharTable used to create the sequence. */ - quint16 charSequence; + quint16 charSequence; }; /** A combination of RENDITION flags which specify options for drawing the character. */ quint8 rendition; /** The foreground color used to draw this character. */ - CharacterColor foregroundColor; + CharacterColor foregroundColor; /** The color used to draw this character's background. */ CharacterColor backgroundColor; - /** + /** * Returns true if this character has a transparent background when * it is drawn with the specified @p palette. */ @@ -100,16 +100,16 @@ public: /** * Returns true if this character should always be drawn in bold when * it is drawn with the specified @p palette, independent of whether - * or not the character has the RE_BOLD rendition flag. + * or not the character has the RE_BOLD rendition flag. */ ColorEntry::FontWeight fontWeight(const ColorEntry* base) const; - - /** + + /** * returns true if the format (color, rendition flag) of the compared characters is equal */ bool equalsFormat(const Character &other) const; - /** + /** * Compares two characters and returns true if they have the same unicode character value, * rendition and colors. */ @@ -122,36 +122,36 @@ public: }; inline bool operator == (const Character& a, const Character& b) -{ - return a.character == b.character && - a.rendition == b.rendition && - a.foregroundColor == b.foregroundColor && +{ + return a.character == b.character && + a.rendition == b.rendition && + a.foregroundColor == b.foregroundColor && a.backgroundColor == b.backgroundColor; } inline bool operator != (const Character& a, const Character& b) { - return a.character != b.character || - a.rendition != b.rendition || - a.foregroundColor != b.foregroundColor || + return a.character != b.character || + a.rendition != b.rendition || + a.foregroundColor != b.foregroundColor || a.backgroundColor != b.backgroundColor; } inline bool Character::isTransparent(const ColorEntry* base) const { - return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && + return ((backgroundColor._colorSpace == COLOR_SPACE_DEFAULT) && base[backgroundColor._u+0+(backgroundColor._v?BASE_COLORS:0)].transparent) - || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && + || ((backgroundColor._colorSpace == COLOR_SPACE_SYSTEM) && base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent); } inline bool Character::equalsFormat(const Character& other) const { - return + return backgroundColor==other.backgroundColor && foregroundColor==other.foregroundColor && rendition==other.rendition; -} +} inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const { @@ -196,7 +196,7 @@ public: * which was added to the table using createExtendedChar(). * * @param hash The hash key returned by createExtendedChar() - * @param length This variable is set to the length of the + * @param length This variable is set to the length of the * character sequence. * * @return A unicode character sequence of size @p length. @@ -208,7 +208,7 @@ public: private: // calculates the hash key of a sequence of unicode points of size 'length' ushort extendedCharHash(ushort* unicodePoints , ushort length) const; - // tests whether the entry in the table specified by 'hash' matches the + // tests whether the entry in the table specified by 'hash' matches the // character sequence 'unicodePoints' of size 'length' bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; // internal, maps hash keys to character sequence buffers. The first ushort diff --git a/lib/CharacterColor.h b/lib/CharacterColor.h index a17c5ce..08f44c8 100644 --- a/lib/CharacterColor.h +++ b/lib/CharacterColor.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, KDE's terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -32,14 +32,14 @@ namespace Konsole { -/** - * An entry in a terminal display's color palette. +/** + * An entry in a terminal display's color palette. * * A color palette is an array of 16 ColorEntry instances which map * system color indexes (from 0 to 15) into actual colors. * * Each entry can be set as bold, in which case any text - * drawn using the color should be drawn in bold. + * drawn using the color should be drawn in bold. * * Each entry can also be transparent, in which case the terminal * display should avoid drawing the background for any characters @@ -49,58 +49,58 @@ class ColorEntry { public: /** Specifies the weight to use when drawing text with this color. */ - enum FontWeight + enum FontWeight { /** Always draw text in this color with a bold weight. */ Bold, /** Always draw text in this color with a normal weight. */ Normal, - /** - * Use the current font weight set by the terminal application. + /** + * Use the current font weight set by the terminal application. * This is the default behavior. */ UseCurrentFormat }; - /** + /** * Constructs a new color palette entry. * * @param c The color value for this entry. * @param tr Specifies that the color should be transparent when used as a background color. - * @param weight Specifies the font weight to use when drawing text with this color. + * @param weight Specifies the font weight to use when drawing text with this color. */ - ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) + ColorEntry(QColor c, bool tr, FontWeight weight = UseCurrentFormat) : color(c), transparent(tr), fontWeight(weight) {} /** * Constructs a new color palette entry with an undefined color, and * with the transparent and bold flags set to false. - */ - ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} - + */ + ColorEntry() : transparent(false), fontWeight(UseCurrentFormat) {} + /** * Sets the color, transparency and boldness of this color to those of @p rhs. - */ - void operator=(const ColorEntry& rhs) - { - color = rhs.color; - transparent = rhs.transparent; - fontWeight = rhs.fontWeight; + */ + void operator=(const ColorEntry& rhs) + { + color = rhs.color; + transparent = rhs.transparent; + fontWeight = rhs.fontWeight; } /** The color value of this entry for display. */ QColor color; - /** - * If true character backgrounds using this color should be transparent. + /** + * If true character backgrounds using this color should be transparent. * This is not applicable when the color is used to render text. */ bool transparent; /** - * Specifies the font weight to use when drawing text with this color. + * Specifies the font weight to use when drawing text with this color. * This is not applicable when the color is used to draw a character's background. */ - FontWeight fontWeight; + FontWeight fontWeight; }; @@ -151,15 +151,15 @@ class CharacterColor public: /** Constructs a new CharacterColor whoose color and color space are undefined. */ - CharacterColor() - : _colorSpace(COLOR_SPACE_UNDEFINED), - _u(0), - _v(0), - _w(0) + CharacterColor() + : _colorSpace(COLOR_SPACE_UNDEFINED), + _u(0), + _v(0), + _w(0) {} - /** - * Constructs a new CharacterColor using the specified @p colorSpace and with + /** + * Constructs a new CharacterColor using the specified @p colorSpace and with * color value @p co * * The meaning of @p co depends on the @p colorSpace used. @@ -168,10 +168,10 @@ public: * * TODO : Add documentation about available color spaces. */ - CharacterColor(quint8 colorSpace, int co) - : _colorSpace(colorSpace), - _u(0), - _v(0), + CharacterColor(quint8 colorSpace, int co) + : _colorSpace(colorSpace), + _u(0), + _v(0), _w(0) { switch (colorSpace) @@ -183,7 +183,7 @@ public: _u = co & 7; _v = (co >> 3) & 1; break; - case COLOR_SPACE_256: + case COLOR_SPACE_256: _u = co & 255; break; case COLOR_SPACE_RGB: @@ -196,32 +196,32 @@ public: } } - /** + /** * Returns true if this character color entry is valid. */ - bool isValid() + bool isValid() { return _colorSpace != COLOR_SPACE_UNDEFINED; } - - /** + + /** * Toggles the value of this color between a normal system color and the corresponding intensive * system color. - * + * * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM * color spaces. */ void toggleIntensive(); - /** + /** * Returns the color within the specified color @p palette * * The @p palette is only used if this color is one of the 16 system colors, otherwise * it is ignored. */ QColor color(const ColorEntry* palette) const; - - /** + + /** * Compares two colors and returns true if they represent the same color value and * use the same color space. */ @@ -235,14 +235,14 @@ public: private: quint8 _colorSpace; - // bytes storing the character color - quint8 _u; - quint8 _v; - quint8 _w; + // bytes storing the character color + quint8 _u; + quint8 _v; + quint8 _w; }; inline bool operator == (const CharacterColor& a, const CharacterColor& b) -{ +{ return a._colorSpace == b._colorSpace && a._u == b._u && a._v == b._v && @@ -263,7 +263,7 @@ inline const QColor color256(quint8 u, const ColorEntry* base) if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0, ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216; - + // 232..255: gray, leaving out black and white int gray = u*10+8; return QColor(gray,gray,gray); } diff --git a/lib/ColorScheme.cpp b/lib/ColorScheme.cpp index fc17cad..200b991 100644 --- a/lib/ColorScheme.cpp +++ b/lib/ColorScheme.cpp @@ -164,15 +164,15 @@ void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry) { Q_ASSERT( index >= 0 && index < TABLE_COLORS ); - if ( !_table ) + if ( !_table ) { _table = new ColorEntry[TABLE_COLORS]; for (int i=0;i= 0 && index < TABLE_COLORS ); return QString(colorNames[index]); } -QString ColorScheme::translatedColorNameForIndex(int index) +QString ColorScheme::translatedColorNameForIndex(int index) { Q_ASSERT( index >= 0 && index < TABLE_COLORS ); @@ -330,7 +330,7 @@ QString ColorScheme::translatedColorNameForIndex(int index) void ColorScheme::readColorEntry(QSettings * s , int index) { s->beginGroup(colorNameForIndex(index)); - + ColorEntry entry; QStringList rgbList = s->value("Color", QStringList()).toStringList(); @@ -343,7 +343,7 @@ void ColorScheme::readColorEntry(QSettings * s , int index) g = rgbList[1].toInt(); b = rgbList[2].toInt(); entry.color = QColor(r, g, b); - + entry.transparent = s->value("Transparent",false).toBool(); // Deprecated key from KDE 4.0 which set 'Bold' to true to force @@ -362,7 +362,7 @@ void ColorScheme::readColorEntry(QSettings * s , int index) setColorTableEntry( index , entry ); if ( hue != 0 || value != 0 || saturation != 0 ) - setRandomizationRange( index , hue , saturation , value ); + setRandomizationRange( index , hue , saturation , value ); s->endGroup(); } @@ -379,8 +379,8 @@ void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, co configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); } - // record randomization if this color has randomization or - // if one of the keys already exists + // record randomization if this color has randomization or + // if one of the keys already exists if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) { configGroup.writeEntry("MaxRandomHue",(int)random.hue); @@ -390,28 +390,28 @@ void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, co } #endif -// +// // Work In Progress - A color scheme for use on KDE setups for users // with visual disabilities which means that they may have trouble // reading text with the supplied color schemes. // // This color scheme uses only the 'safe' colors defined by the -// KColorScheme class. +// KColorScheme class. // -// A complication this introduces is that each color provided by +// A complication this introduces is that each color provided by // KColorScheme is defined as a 'background' or 'foreground' color. -// Only foreground colors are allowed to be used to render text and +// Only foreground colors are allowed to be used to render text and // only background colors are allowed to be used for backgrounds. // // The ColorEntry and TerminalDisplay classes do not currently -// support this restriction. +// support this restriction. // // Requirements: // - A color scheme which uses only colors from the KColorScheme class -// - Ability to restrict which colors the TerminalDisplay widget +// - Ability to restrict which colors the TerminalDisplay widget // uses as foreground and background color // - Make use of KGlobalSettings::allowDefaultBackgroundImages() as -// a hint to determine whether this accessible color scheme should +// a hint to determine whether this accessible color scheme should // be used by default. // // @@ -444,13 +444,13 @@ AccessibleColorScheme::AccessibleColorScheme() colorScheme.foreground( colorScheme.NeutralText ) }; - for ( int i = 0 ; i < TABLE_COLORS ; i++ ) + for ( int i = 0 ; i < TABLE_COLORS ; i++ ) { ColorEntry entry; entry.color = colors[ i % ColorRoleCount ].color(); - setColorTableEntry( i , entry ); - } + setColorTableEntry( i , entry ); + } #endif } @@ -458,7 +458,7 @@ KDE3ColorSchemeReader::KDE3ColorSchemeReader( QIODevice* device ) : _device(device) { } -ColorScheme* KDE3ColorSchemeReader::read() +ColorScheme* KDE3ColorSchemeReader::read() { Q_ASSERT( _device->openMode() == QIODevice::ReadOnly || _device->openMode() == QIODevice::ReadWrite ); @@ -489,7 +489,7 @@ ColorScheme* KDE3ColorSchemeReader::read() { qDebug() << "KDE 3 color scheme contains an unsupported feature, '" << line << "'"; - } + } } return scheme; @@ -502,7 +502,7 @@ bool KDE3ColorSchemeReader::readColorLine(const QString& line,ColorScheme* schem return false; if (list.first() != "color") return false; - + int index = list[1].toInt(); int red = list[2].toInt(); int green = list[3].toInt(); @@ -613,7 +613,7 @@ bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath) delete scheme; return false; } - + QFileInfo info(filePath); if ( !_colorSchemes.contains(info.baseName()) ) @@ -628,7 +628,7 @@ bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath) return true; } #if 0 -void ColorSchemeManager::addColorScheme(ColorScheme* scheme) +void ColorSchemeManager::addColorScheme(ColorScheme* scheme) { _colorSchemes.insert(scheme->name(),scheme); @@ -658,17 +658,17 @@ bool ColorSchemeManager::loadColorScheme(const QString& filePath) QFileInfo info(filePath); const QString& schemeName = info.baseName(); - + ColorScheme* scheme = new ColorScheme(); scheme->setName(schemeName); scheme->read(filePath); - if (scheme->name().isEmpty()) + if (scheme->name().isEmpty()) { qDebug() << "Color scheme in" << filePath << "does not have a valid name and was not loaded."; delete scheme; return false; - } + } if ( !_colorSchemes.contains(schemeName) ) { @@ -678,11 +678,11 @@ bool ColorSchemeManager::loadColorScheme(const QString& filePath) { qDebug() << "color scheme with name" << schemeName << "has already been" << "found, ignoring."; - + delete scheme; } - return true; + return true; } QList ColorSchemeManager::listKDE3ColorSchemes() { @@ -691,7 +691,7 @@ QList ColorSchemeManager::listKDE3ColorSchemes() QStringList filters; filters << "*.schema"; dir.setNameFilters(filters); - QStringList list = dir.entryList(filters); + QStringList list = dir.entryList(filters); QStringList ret; foreach(QString i, list) ret << dname + "/" + i; @@ -726,7 +726,7 @@ bool ColorSchemeManager::deleteColorScheme(const QString& name) { Q_ASSERT( _colorSchemes.contains(name) ); - // lookup the path and delete + // lookup the path and delete QString path = findColorSchemePath(name); if ( QFile::remove(path) ) { @@ -744,14 +744,14 @@ QString ColorSchemeManager::findColorSchemePath(const QString& name) const // QString path = KStandardDirs::locate("data","konsole/"+name+".colorscheme"); QString path(get_color_schemes_dir() + "/"+ name + ".colorscheme"); if ( !path.isEmpty() ) - return path; + return path; //path = KStandardDirs::locate("data","konsole/"+name+".schema"); path = get_color_schemes_dir() + "/"+ name + ".schema"; return path; } -const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) +const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) { if ( name.isEmpty() ) return defaultColorScheme(); @@ -761,12 +761,12 @@ const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) else { // look for this color scheme - QString path = findColorSchemePath(name); + QString path = findColorSchemePath(name); if ( !path.isEmpty() && loadColorScheme(path) ) { - return findColorScheme(name); - } - else + return findColorScheme(name); + } + else { if (!path.isEmpty() && loadKDE3ColorScheme(path)) return findColorScheme(name); @@ -774,7 +774,7 @@ const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) qDebug() << "Could not find color scheme - " << name; - return 0; + return 0; } } diff --git a/lib/ColorScheme.h b/lib/ColorScheme.h index 3b5c211..5f2b77e 100644 --- a/lib/ColorScheme.h +++ b/lib/ColorScheme.h @@ -40,16 +40,16 @@ namespace Konsole { /** - * Represents a color scheme for a terminal display. + * Represents a color scheme for a terminal display. * * The color scheme includes the palette of colors used to draw the text and character backgrounds - * in the display and the opacity level of the display background. + * in the display and the opacity level of the display background. */ class ColorScheme { public: - /** - * Constructs a new color scheme which is initialised to the default color set + /** + * Constructs a new color scheme which is initialised to the default color set * for Konsole. */ ColorScheme(); @@ -78,7 +78,7 @@ public: /** Sets a single entry within the color palette. */ void setColorTableEntry(int index , const ColorEntry& entry); - /** + /** * Copies the color entries which form the palette for this color scheme * into @p table. @p table should be an array with TABLE_COLORS entries. * @@ -88,7 +88,7 @@ public: * palette to be randomized. The seed is used to pick the random color. */ void getColorTable(ColorEntry* table, uint randomSeed = 0) const; - + /** * Retrieves a single color entry from the table. * @@ -96,28 +96,28 @@ public: */ ColorEntry colorEntry(int index , uint randomSeed = 0) const; - /** - * Convenience method. Returns the - * foreground color for this scheme, - * this is the primary color used to draw the + /** + * Convenience method. Returns the + * foreground color for this scheme, + * this is the primary color used to draw the * text in this scheme. */ QColor foregroundColor() const; /** - * Convenience method. Returns the background color for - * this scheme, this is the primary color used to + * Convenience method. Returns the background color for + * this scheme, this is the primary color used to * draw the terminal background in this scheme. */ QColor backgroundColor() const; - /** + /** * Returns true if this color scheme has a dark background. * The background color is said to be dark if it has a value of less than 127 * in the HSV color space. */ bool hasDarkBackground() const; - /** + /** * Sets the opacity level of the display background. @p opacity ranges * between 0 (completely transparent background) and 1 (completely * opaque background). @@ -127,18 +127,18 @@ public: * TODO: More documentation */ void setOpacity(qreal opacity); - /** + /** * Returns the opacity level for this color scheme, see setOpacity() * TODO: More documentation */ qreal opacity() const; - /** + /** * Enables randomization of the background color. This will cause * the palette returned by getColorTable() and colorEntry() to * be adjusted depending on the value of the random seed argument * to them. - */ + */ void setRandomizedBackgroundColor(bool randomize); /** Returns true if the background color is randomized. */ @@ -154,7 +154,7 @@ private: public: RandomizationRange() : hue(0) , saturation(0) , value(0) {} - bool isNull() const + bool isNull() const { return ( hue == 0 && saturation == 0 && value == 0 ); } @@ -172,14 +172,14 @@ private: // implemented upstream - user apps // reads a single colour entry from a KConfig source // and sets the palette entry at 'index' to the entry read. - void readColorEntry(KConfig& config , int index); + void readColorEntry(KConfig& config , int index); // writes a single colour entry to a KConfig source void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const; #endif void readColorEntry(QSettings *s, int index); - // sets the amount of randomization allowed for a particular color - // in the palette. creates the randomization table if + // sets the amount of randomization allowed for a particular color + // in the palette. creates the randomization table if // it does not already exist void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ); @@ -202,7 +202,7 @@ private: static const ColorEntry defaultTable[]; // table of default color entries }; -/** +/** * A color scheme which uses colors from the standard KDE color palette. * * This is designed primarily for the benefit of users who are using specially @@ -228,13 +228,13 @@ public: class KDE3ColorSchemeReader { public: - /** - * Constructs a new reader which reads from the specified device. - * The device should be open in read-only mode. + /** + * Constructs a new reader which reads from the specified device. + * The device should be open in read-only mode. */ KDE3ColorSchemeReader( QIODevice* device ); - /** + /** * Reads and parses the contents of the .schema file from the input * device and returns the ColorScheme defined within it. * @@ -277,7 +277,7 @@ public: * Returns the default color scheme for Konsole */ const ColorScheme* defaultColorScheme() const; - + /** * Returns the color scheme with the given name or 0 if no * scheme with that name exists. If @p name is empty, the @@ -298,18 +298,18 @@ public: void addColorScheme(ColorScheme* scheme); #endif /** - * Deletes a color scheme. Returns true on successful deletion or false otherwise. + * Deletes a color scheme. Returns true on successful deletion or false otherwise. */ bool deleteColorScheme(const QString& name); - /** - * Returns a list of the all the available color schemes. + /** + * Returns a list of the all the available color schemes. * This may be slow when first called because all of the color * scheme resources on disk must be located, read and parsed. * - * Subsequent calls will be inexpensive. + * Subsequent calls will be inexpensive. */ - QList allColorSchemes(); + QList allColorSchemes(); /** Returns the global color scheme manager instance. */ static ColorSchemeManager* instance(); diff --git a/lib/Emulation.cpp b/lib/Emulation.cpp index 8cc32ef..cbfdbf8 100644 --- a/lib/Emulation.cpp +++ b/lib/Emulation.cpp @@ -1,5 +1,5 @@ /* - Copyright 2007-2008 Robert Knight + Copyright 2007-2008 Robert Knight Copyright 1997,1998 by Lars Doelle Copyright 1996 by Matthias Ettrich @@ -64,9 +64,9 @@ Emulation::Emulation() : QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); - + // listen for mouse status changes - connect( this , SIGNAL(programUsesMouseChanged(bool)) , + connect( this , SIGNAL(programUsesMouseChanged(bool)) , SLOT(usesMouseChanged(bool)) ); } @@ -112,7 +112,7 @@ void Emulation::setScreen(int n) { Screen *old = _currentScreen; _currentScreen = _screen[n & 1]; - if (_currentScreen != old) + if (_currentScreen != old) { // tell all windows onto this emulation to switch to the newly active screen foreach(ScreenWindow* window,_windows) @@ -191,7 +191,7 @@ void Emulation::receiveChar(int c) void Emulation::sendKeyEvent( QKeyEvent* ev ) { emit stateSet(NOTIFYNORMAL); - + if (!ev->text().isEmpty()) { // A block of text // Note that the text is proper unicode. @@ -220,7 +220,7 @@ void Emulation::receiveData(const char* text, int length) emit stateSet(NOTIFYACTIVITY); bufferedUpdate(); - + QString unicodeText = _decoder->toUnicode(text,length); //send characters to terminal emulator @@ -248,13 +248,13 @@ void Emulation::receiveData(const char* text, int length) // //There is something about stopping the _decoder if "we get a control code halfway a multi-byte sequence" (see below) //which hasn't been ported into the newer function (above). Hopefully someone who understands this better -//can find an alternative way of handling the check. +//can find an alternative way of handling the check. /*void Emulation::onRcvBlock(const char *s, int len) { emit notifySessionState(NOTIFYACTIVITY); - + bufferedUpdate(); for (int i = 0; i < len; i++) { @@ -289,9 +289,9 @@ void Emulation::receiveData(const char* text, int length) } }*/ -void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , +void Emulation::writeToStream( TerminalCharacterDecoder* _decoder , int startLine , - int endLine) + int endLine) { _currentScreen->writeLinesToStream(_decoder,startLine,endLine); } @@ -334,7 +334,7 @@ char Emulation::eraseChar() const void Emulation::setImageSize(int lines, int columns) { - if ((lines < 1) || (columns < 1)) + if ((lines < 1) || (columns < 1)) return; QSize screenSize[2] = { QSize(_screen[0]->getColumns(), @@ -344,7 +344,7 @@ void Emulation::setImageSize(int lines, int columns) QSize newSize(columns,lines); if (newSize == screenSize[0] && newSize == screenSize[1]) - return; + return; _screen[0]->resizeImage(lines,columns); _screen[1]->resizeImage(lines,columns); @@ -372,17 +372,17 @@ bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints , { ushort* entry = extendedCharTable[hash]; - // compare given length with stored sequence length ( given as the first ushort in the - // stored buffer ) - if ( entry == 0 || entry[0] != length ) + // compare given length with stored sequence length ( given as the first ushort in the + // stored buffer ) + if ( entry == 0 || entry[0] != length ) return false; // if the lengths match, each character must be checked. the stored buffer starts at // entry[1] for ( int i = 0 ; i < length ; i++ ) { if ( entry[i+1] != unicodePoints[i] ) - return false; - } + return false; + } return true; } ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) @@ -395,7 +395,7 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng { if ( extendedCharMatch(hash,unicodePoints,length) ) { - // this sequence already has an entry in the table, + // this sequence already has an entry in the table, // return its hash return hash; } @@ -405,16 +405,16 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng // points then try next hash hash++; } - } + } + - // add the new sequence to the table and // return that index ushort* buffer = new ushort[length+1]; buffer[0] = length; for ( int i = 0 ; i < length ; i++ ) - buffer[i+1] = unicodePoints[i]; - + buffer[i+1] = unicodePoints[i]; + extendedCharTable.insert(hash,buffer); return hash; diff --git a/lib/Emulation.h b/lib/Emulation.h index feecdf0..3037a04 100644 --- a/lib/Emulation.h +++ b/lib/Emulation.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -26,7 +26,7 @@ // System #include -// Qt +// Qt #include //#include #include @@ -46,56 +46,56 @@ class Screen; class ScreenWindow; class TerminalCharacterDecoder; -/** - * This enum describes the available states which +/** + * This enum describes the available states which * the terminal emulation may be set to. * - * These are the values used by Emulation::stateChanged() + * These are the values used by Emulation::stateChanged() */ -enum -{ +enum +{ /** The emulation is currently receiving user input. */ - NOTIFYNORMAL=0, - /** + NOTIFYNORMAL=0, + /** * The terminal program has triggered a bell event * to get the user's attention. */ - NOTIFYBELL=1, - /** - * The emulation is currently receiving data from its + NOTIFYBELL=1, + /** + * The emulation is currently receiving data from its * terminal input. */ NOTIFYACTIVITY=2, - // unused here? - NOTIFYSILENCE=3 + // unused here? + NOTIFYSILENCE=3 }; /** * Base class for terminal emulation back-ends. * - * The back-end is responsible for decoding an incoming character stream and + * The back-end is responsible for decoding an incoming character stream and * producing an output image of characters. * * When input from the terminal is received, the receiveData() slot should be called with - * the data which has arrived. The emulation will process the data and update the + * the data which has arrived. The emulation will process the data and update the * screen image accordingly. The codec used to decode the incoming character stream - * into the unicode characters used internally can be specified using setCodec() + * into the unicode characters used internally can be specified using setCodec() * - * The size of the screen image can be specified by calling setImageSize() with the + * The size of the screen image can be specified by calling setImageSize() with the * desired number of lines and columns. When new lines are added, old content - * is moved into a history store, which can be set by calling setHistory(). + * is moved into a history store, which can be set by calling setHistory(). * - * The screen image can be accessed by creating a ScreenWindow onto this emulation - * by calling createWindow(). Screen windows provide access to a section of the - * output. Each screen window covers the same number of lines and columns as the + * The screen image can be accessed by creating a ScreenWindow onto this emulation + * by calling createWindow(). Screen windows provide access to a section of the + * output. Each screen window covers the same number of lines and columns as the * image size returned by imageSize(). The screen window can be moved up and down - * and provides transparent access to both the current on-screen image and the + * and provides transparent access to both the current on-screen image and the * previous output. The screen windows emit an outputChanged signal * when the section of the image they are looking at changes. * Graphical views can then render the contents of a screen window, listening for notifications - * of output changes from the screen window which they are associated with and updating - * accordingly. + * of output changes from the screen window which they are associated with and updating + * accordingly. * * The emulation also is also responsible for converting input from the connected views such * as keypresses and mouse activity into a character string which can be sent @@ -108,9 +108,9 @@ enum * character sequences. The name of the key bindings set used can be specified using * setKeyBindings() * - * The emulation maintains certain state information which changes depending on the - * input received. The emulation can be reset back to its starting state by calling - * reset(). + * The emulation maintains certain state information which changes depending on the + * input received. The emulation can be reset back to its starting state by calling + * reset(). * * The emulation also maintains an activity state, which specifies whether * terminal is currently active ( when data is received ), normal @@ -121,12 +121,12 @@ enum * a 'bell' event in different ways. */ class KONSOLEPRIVATE_EXPORT Emulation : public QObject -{ +{ Q_OBJECT public: - - /** Constructs a new terminal emulation */ + + /** Constructs a new terminal emulation */ Emulation(); ~Emulation(); @@ -142,15 +142,15 @@ public: /** * Returns the total number of lines, including those stored in the history. - */ + */ int lineCount() const; - /** + /** * Sets the history store used by this emulation. When new lines * are added to the output, older lines at the top of the screen are transferred to a history - * store. + * store. * - * The number of lines which are kept and the storage location depend on the + * The number of lines which are kept and the storage location depend on the * type of store. */ void setHistory(const HistoryType&); @@ -159,49 +159,49 @@ public: /** Clears the history scroll. */ void clearHistory(); - /** - * Copies the output history from @p startLine to @p endLine + /** + * Copies the output history from @p startLine to @p endLine * into @p stream, using @p decoder to convert the terminal - * characters into text. + * characters into text. * - * @param decoder A decoder which converts lines of terminal characters with + * @param decoder A decoder which converts lines of terminal characters with * appearance attributes into output text. PlainTextDecoder is the most commonly * used decoder. * @param startLine Index of first line to copy * @param endLine Index of last line to copy */ virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); - + /** Returns the codec used to decode incoming characters. See setCodec() */ const QTextCodec* codec() const { return _codec; } /** Sets the codec used to decode incoming characters. */ void setCodec(const QTextCodec*); - /** - * Convenience method. + /** + * Convenience method. * Returns true if the current codec used to decode incoming * characters is UTF-8 */ bool utf8() const { Q_ASSERT(_codec); return _codec->mibEnum() == 106; } - + /** TODO Document me */ virtual char eraseChar() const; - /** + /** * Sets the key bindings used to key events * ( received through sendKeyEvent() ) into character * streams to send to the terminal. */ void setKeyBindings(const QString& name); - /** + /** * Returns the name of the emulation's current key bindings. * See setKeyBindings() */ QString keyBindings() const; - /** + /** * Copies the current image into the history and clears the screen. */ virtual void clearEntireScreen() =0; @@ -209,7 +209,7 @@ public: /** Resets the state of the terminal. */ virtual void reset() =0; - /** + /** * Returns true if the active terminal program wants * mouse input events. * @@ -218,42 +218,42 @@ public: */ bool programUsesMouse() const; -public slots: +public slots: /** Change the size of the emulation's image */ virtual void setImageSize(int lines, int columns); - - /** + + /** * Interprets a sequence of characters and sends the result to the terminal. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession. */ virtual void sendText(const QString& text) = 0; - /** + /** * Interprets a key press event and emits the sendData() signal with - * the resulting character stream. + * the resulting character stream. */ virtual void sendKeyEvent(QKeyEvent*); - - /** + + /** * Converts information about a mouse event into an xterm-compatible escape * sequence and emits the character sequence via sendData() */ virtual void sendMouseEvent(int buttons, int column, int line, int eventType); - + /** - * Sends a string of characters to the foreground terminal process. + * Sends a string of characters to the foreground terminal process. * - * @param string The characters to send. + * @param string The characters to send. * @param length Length of @p string or if set to a negative value, @p string will * be treated as a null-terminated string and its length will be determined automatically. */ virtual void sendString(const char* string, int length = -1) = 0; - /** + /** * Processes an incoming stream of characters. receiveData() decodes the incoming * character buffer using the current codec(), and then calls receiveChar() for - * each unicode character in the resulting buffer. + * each unicode character in the resulting buffer. * * receiveData() also starts a timer which causes the outputChanged() signal * to be emitted when it expires. The timer allows multiple updates in quick @@ -266,8 +266,8 @@ public slots: signals: - /** - * Emitted when a buffer of data is ready to send to the + /** + * Emitted when a buffer of data is ready to send to the * standard input of the terminal. * * @param data The buffer of data ready to be sent @@ -275,20 +275,20 @@ signals: */ void sendData(const char* data,int len); - /** + /** * Requests that sending of input to the emulation * from the terminal process be suspended or resumed. * - * @param suspend If true, requests that sending of - * input from the terminal process' stdout be + * @param suspend If true, requests that sending of + * input from the terminal process' stdout be * suspended. Otherwise requests that sending of - * input be resumed. + * input be resumed. */ void lockPtyRequest(bool suspend); /** * Requests that the pty used by the terminal process - * be set to UTF 8 mode. + * be set to UTF 8 mode. * * TODO: More documentation */ @@ -316,7 +316,7 @@ signals: */ void changeTabTextColorRequest(int color); - /** + /** * This is emitted when the program running in the shell indicates whether or * not it is interested in mouse events. * @@ -325,7 +325,7 @@ signals: */ void programUsesMouseChanged(bool usesMouse); - /** + /** * Emitted when the contents of the screen image change. * The emulation buffers the updates from successive image changes, * and only emits outputChanged() at sensible intervals when @@ -335,14 +335,14 @@ signals: * created with createWindow() to listen for this signal. * * ScreenWindow objects created using createWindow() will emit their - * own outputChanged() signal in response to this signal. + * own outputChanged() signal in response to this signal. */ void outputChanged(); /** - * Emitted when the program running in the terminal wishes to update the + * Emitted when the program running in the terminal wishes to update the * session's title. This also allows terminal programs to customize other - * aspects of the terminal emulation display. + * aspects of the terminal emulation display. * * This signal is emitted when the escape sequence "\033]ARG;VALUE\007" * is received in the input string, where ARG is a number specifying what @@ -350,7 +350,7 @@ signals: * * TODO: The name of this method is not very accurate since this method * is used to perform a whole range of tasks besides just setting - * the user-title of the session. + * the user-title of the session. * * @param title Specifies what to change. *
    @@ -359,16 +359,16 @@ signals: *
  • 2 - Set session title to @p newTitle
  • *
  • 11 - Set the session's default background color to @p newTitle, * where @p newTitle can be an HTML-style string ("#RRGGBB") or a named - * color (eg 'red', 'blue'). + * color (eg 'red', 'blue'). * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more * details. *
  • *
  • 31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)
  • - *
  • 32 - Sets the icon associated with the session. @p newTitle is the name + *
  • 32 - Sets the icon associated with the session. @p newTitle is the name * of the icon to use, which can be the name of any icon in the current KDE icon * theme (eg: 'konsole', 'kate', 'folder_home')
  • *
- * @param newTitle Specifies the new title + * @param newTitle Specifies the new title */ void titleChanged(int title,const QString& newTitle); @@ -379,9 +379,9 @@ signals: */ void imageSizeChanged(int lineCount , int columnCount); - /** + /** * Emitted when the terminal program requests to change various properties - * of the terminal display. + * of the terminal display. * * A profile change command occurs when a special escape sequence, followed * by a string containing a series of name and value pairs is received. @@ -392,7 +392,7 @@ signals: */ void profileChangeCommandReceived(const QString& text); - /** + /** * Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to * resume output. @@ -402,21 +402,21 @@ signals: protected: virtual void setMode(int mode) = 0; virtual void resetMode(int mode) = 0; - - /** + + /** * Processes an incoming character. See receiveData() - * @p ch A unicode character code. + * @p ch A unicode character code. */ virtual void receiveChar(int ch); - /** + /** * Sets the active screen. The terminal has two screens, primary and alternate. * The primary screen is used by default. When certain interactive programs such * as Vim are run, they trigger a switch to the alternate screen. * * @param index 0 to switch to the primary screen, or 1 to switch to the alternate screen */ - void setScreen(int index); + void setScreen(int index); enum EmulationCodec { @@ -427,35 +427,35 @@ protected: QList _windows; - - Screen* _currentScreen; // pointer to the screen which is currently active, + + Screen* _currentScreen; // pointer to the screen which is currently active, // this is one of the elements in the screen[] array Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell // scrollbars are enabled in this mode ) // 1 = alternate ( used by vi , emacs etc. // scrollbars are not enabled in this mode ) - - - //decodes an incoming C-style character stream into a unicode QString using + + + //decodes an incoming C-style character stream into a unicode QString using //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.) const QTextCodec* _codec; QTextDecoder* _decoder; const KeyboardTranslator* _keyTranslator; // the keyboard layout protected slots: - /** + /** * Schedules an update of attached views. * Repeated calls to bufferedUpdate() in close succession will result in only a single update, - * much like the Qt buffered update of widgets. + * much like the Qt buffered update of widgets. */ void bufferedUpdate(); -private slots: +private slots: // triggered by timer, causes the emulation to send an updated screen image to each // view - void showBulk(); + void showBulk(); void usesMouseChanged(bool usesMouse); @@ -463,7 +463,7 @@ private: bool _usesMouse; QTimer _bulkTimer1; QTimer _bulkTimer2; - + }; } diff --git a/lib/Filter.cpp b/lib/Filter.cpp index 93de72c..c113eb3 100644 --- a/lib/Filter.cpp +++ b/lib/Filter.cpp @@ -47,7 +47,7 @@ using namespace Konsole; FilterChain::~FilterChain() { QMutableListIterator iter(*this); - + while ( iter.hasNext() ) { Filter* filter = iter.next(); @@ -141,7 +141,7 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines PlainTextDecoder decoder; decoder.setTrailingWhitespace(false); - + // setup new shared buffers for the filters to process on QString* newBuffer = new QString(); QList* newLinePositions = new QList(); @@ -167,7 +167,7 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines // being treated as part of a link that occurs at the start of the next line // // the downside is that links which are spread over more than one line are not - // highlighted. + // highlighted. // // TODO - Use the "line wrapped" attribute associated with lines in a // terminal image to avoid adding this imaginary character for wrapped @@ -219,7 +219,7 @@ void Filter::getLineColumn(int position , int& startLine , int& startColumn) else nextLine = _linePositions->value(i+1); - if ( _linePositions->value(i) <= position && position < nextLine ) + if ( _linePositions->value(i) <= position && position < nextLine ) { startLine = i; startColumn = string_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(i))); @@ -227,7 +227,7 @@ void Filter::getLineColumn(int position , int& startLine , int& startColumn) } } } - + /*void Filter::addLine(const QString& text) { @@ -249,7 +249,7 @@ void Filter::addHotSpot(HotSpot* spot) for (int line = spot->startLine() ; line <= spot->endLine() ; line++) { _hotspots.insert(line,spot); - } + } } QList Filter::hotSpots() const { @@ -267,12 +267,12 @@ Filter::HotSpot* Filter::hotSpotAt(int line , int column) const while (spotIter.hasNext()) { HotSpot* spot = spotIter.next(); - + if ( spot->startLine() == line && spot->startColumn() > column ) continue; if ( spot->endLine() == line && spot->endColumn() < column ) continue; - + return spot; } @@ -343,7 +343,7 @@ QStringList RegExpFilter::HotSpot::capturedTexts() const return _capturedTexts; } -void RegExpFilter::setRegExp(const QRegExp& regExp) +void RegExpFilter::setRegExp(const QRegExp& regExp) { _searchText = regExp; } @@ -386,14 +386,14 @@ void RegExpFilter::process() endLine,endColumn); spot->setCapturedTexts(_searchText.capturedTexts()); - addHotSpot( spot ); + addHotSpot( spot ); pos += _searchText.matchedLength(); // if matchedLength == 0, the program will get stuck in an infinite loop if ( _searchText.matchedLength() == 0 ) pos = -1; } - } + } } RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, @@ -425,16 +425,16 @@ QString UrlFilter::HotSpot::tooltip() const const UrlType kind = urlType(); if ( kind == StandardUrl ) - return QString(); + return QString(); else if ( kind == Email ) - return QString(); + return QString(); else return QString(); } UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const { QString url = capturedTexts().first(); - + if ( FullUrlRegExp.exactMatch(url) ) return StandardUrl; else if ( EmailAddressRegExp.exactMatch(url) ) @@ -465,23 +465,23 @@ void UrlFilter::HotSpot::activate(const QString& actionName) { url.prepend("http://"); } - } + } else if ( kind == Email ) { url.prepend("mailto:"); } - + _urlObject->emitActivated(url); } } -// Note: Altering these regular expressions can have a major effect on the performance of the filters +// Note: Altering these regular expressions can have a major effect on the performance of the filters // used for finding URLs in the text, especially if they are very general and could match very long // pieces of text. // Please be careful when altering them. //regexp matches: -// full url: +// full url: // protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]"); // email address: @@ -551,7 +551,7 @@ QList UrlFilter::HotSpot::actions() list << openAction; list << copyAction; - return list; + return list; } //#include "Filter.moc" diff --git a/lib/Filter.h b/lib/Filter.h index 161773b..4c3b8ef 100644 --- a/lib/Filter.h +++ b/lib/Filter.h @@ -46,7 +46,7 @@ class Character; * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * Hotspots may have more than one action, in which case the list of actions can be obtained using the * actions() method. * * Different subclasses of filter will return different types of hotspot. @@ -66,13 +66,13 @@ public: * activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * * For example, if a hotspot represents a URL then a suitable action would be opening that URL in a web browser. - * Hotspots may have more than one action, in which case the list of actions can be obtained using the - * actions() method. These actions may then be displayed in a popup menu or toolbar for example. + * Hotspots may have more than one action, in which case the list of actions can be obtained using the + * actions() method. These actions may then be displayed in a popup menu or toolbar for example. */ class HotSpot { public: - /** + /** * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) * in a block of text. */ @@ -87,7 +87,7 @@ public: Link, // this hotspot represents a marker Marker - }; + }; /** Returns the line when the hotspot area starts */ int startLine() const; @@ -97,31 +97,31 @@ public: int startColumn() const; /** Returns the column on endLine() where the hotspot area ends */ int endColumn() const; - /** + /** * Returns the type of the hotspot. This is usually used as a hint for views on how to represent * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them */ Type type() const; - /** - * Causes the an action associated with a hotspot to be triggered. + /** + * Causes the an action associated with a hotspot to be triggered. * * @param action The action to trigger. This is * typically empty ( in which case the default action should be performed ) or * one of the object names from the actions() list. In which case the associated - * action should be performed. + * action should be performed. */ virtual void activate(const QString& action = QString()) = 0; - /** - * Returns a list of actions associated with the hotspot which can be used in a - * menu or toolbar + /** + * Returns a list of actions associated with the hotspot which can be used in a + * menu or toolbar */ virtual QList actions(); - /** + /** * Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or * an empty string if there is no tooltip associated with this hotspot. * - * The default implementation returns an empty string. + * The default implementation returns an empty string. */ virtual QString tooltip() const; @@ -135,7 +135,7 @@ public: int _endLine; int _endColumn; Type _type; - + }; /** Constructs a new filter. */ @@ -145,9 +145,9 @@ public: /** Causes the filter to process the block of text currently in its internal buffer */ virtual void process() = 0; - /** + /** * Empties the filters internal buffer and resets the line count back to 0. - * All hotspots are deleted. + * All hotspots are deleted. */ void reset(); @@ -163,7 +163,7 @@ public: /** Returns the list of hotspots identified by the filter which occur on a given line */ QList hotSpotsAtLine(int line) const; - /** + /** * TODO: Document me */ void setBuffer(const QString* buffer , const QList* linePositions); @@ -179,22 +179,22 @@ protected: private: QMultiHash _hotspots; QList _hotspotList; - + const QList* _linePositions; const QString* _buffer; }; -/** - * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot +/** + * A filter which searches for sections of text matching a regular expression and creates a new RegExpFilter::HotSpot * instance for them. * * Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression - * are found. + * are found. */ class RegExpFilter : public Filter { public: - /** + /** * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * matched by the filter's regular expression. */ @@ -215,26 +215,26 @@ public: /** Constructs a new regular expression filter */ RegExpFilter(); - /** - * Sets the regular expression which the filter searches for in blocks of text. + /** + * Sets the regular expression which the filter searches for in blocks of text. * * Regular expressions which match the empty string are treated as not matching - * anything. + * anything. */ void setRegExp(const QRegExp& text); /** Returns the regular expression which the filter searches for in blocks of text */ QRegExp regExp() const; - /** - * Reimplemented to search the filter's text buffer for text matching regExp() + /** + * Reimplemented to search the filter's text buffer for text matching regExp() * * If regexp matches the empty string, then process() will return immediately - * without finding results. + * without finding results. */ virtual void process(); protected: - /** + /** * Called when a match for the regular expression is encountered. Subclasses should reimplement this * to return custom hotspot types */ @@ -248,15 +248,15 @@ private: class FilterObject; /** A filter which matches URLs in blocks of text */ -class UrlFilter : public RegExpFilter +class UrlFilter : public RegExpFilter { Q_OBJECT public: - /** - * Hotspot type created by UrlFilter instances. The activate() method opens a web browser + /** + * Hotspot type created by UrlFilter instances. The activate() method opens a web browser * at the given URL when called. */ - class HotSpot : public RegExpFilter::HotSpot + class HotSpot : public RegExpFilter::HotSpot { public: HotSpot(int startLine,int startColumn,int endLine,int endColumn); @@ -266,7 +266,7 @@ public: virtual QList actions(); - /** + /** * Open a web browser at the current URL. The url itself can be determined using * the capturedTexts() method. */ @@ -291,12 +291,12 @@ protected: virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int); private: - + static const QRegExp FullUrlRegExp; static const QRegExp EmailAddressRegExp; // combined OR of FullUrlRegExp and EmailAddressRegExp - static const QRegExp CompleteUrlRegExp; + static const QRegExp CompleteUrlRegExp; signals: void activated(const QUrl& url); }; @@ -316,11 +316,11 @@ signals: void activated(const QUrl& url); }; -/** - * A chain which allows a group of filters to be processed as one. +/** + * A chain which allows a group of filters to be processed as one. * The chain owns the filters added to it and deletes them when the chain itself is destroyed. * - * Use addFilter() to add a new filter to the chain. + * Use addFilter() to add a new filter to the chain. * When new text to be filtered arrives, use addLine() to add each additional * line of text which needs to be processed and then after adding the last line, use * process() to cause each filter in the chain to process the text. @@ -350,12 +350,12 @@ public: /** Resets each filter in the chain */ void reset(); /** - * Processes each filter in the chain + * Processes each filter in the chain */ void process(); /** Sets the buffer for each filter in the chain to process. */ - void setBuffer(const QString* buffer , const QList* linePositions); + void setBuffer(const QString* buffer , const QList* linePositions); /** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ Filter::HotSpot* hotSpotAt(int line , int column) const; @@ -382,7 +382,7 @@ public: * @param lineProperties The line properties to set for image */ void setImage(const Character* const image , int lines , int columns, - const QVector& lineProperties); + const QVector& lineProperties); private: QString* _buffer; diff --git a/lib/History.cpp b/lib/History.cpp index 0f9c13f..476d616 100644 --- a/lib/History.cpp +++ b/lib/History.cpp @@ -93,7 +93,7 @@ HistoryFile::HistoryFile() fileMap(0) { if (tmpFile.open()) - { + { tmpFile.setAutoRemove(true); ion = tmpFile.handle(); } @@ -117,7 +117,7 @@ void HistoryFile::map() //if mmap'ing fails, fall back to the read-lseek combination if ( fileMap == MAP_FAILED ) { - readWriteBalance = 0; + readWriteBalance = 0; fileMap = 0; qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno; } @@ -140,7 +140,7 @@ void HistoryFile::add(const unsigned char* bytes, int len) { if ( fileMap ) unmap(); - + readWriteBalance++; int rc = 0; @@ -152,8 +152,8 @@ void HistoryFile::add(const unsigned char* bytes, int len) void HistoryFile::get(unsigned char* bytes, int len, int loc) { - //count number of get() calls vs. number of add() calls. - //If there are many more get() calls compared with add() + //count number of get() calls vs. number of add() calls. + //If there are many more get() calls compared with add() //calls (decided by using MAP_THRESHOLD) then mmap the log //file to improve performance. readWriteBalance--; @@ -166,7 +166,7 @@ void HistoryFile::get(unsigned char* bytes, int len, int loc) bytes[i]=fileMap[loc+i]; } else - { + { int rc = 0; if (loc < 0 || len < 0 || loc + len > length) @@ -202,7 +202,7 @@ bool HistoryScroll::hasScroll() // History Scroll File ////////////////////////////////////// -/* +/* The history scroll makes a Row(Row(Cell)) from two history buffers. The index buffer contains start of line positions which refere to the cells @@ -222,7 +222,7 @@ HistoryScrollFile::HistoryScrollFile(const QString &logFileName) HistoryScrollFile::~HistoryScrollFile() { } - + int HistoryScrollFile::getLines() { return index.len() / sizeof(int); @@ -247,11 +247,11 @@ int HistoryScrollFile::startOfLine(int lineno) { if (lineno <= 0) return 0; if (lineno <= getLines()) - { - + { + if (!index.isMapped()) index.map(); - + int res; index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); return res; @@ -346,7 +346,7 @@ int HistoryScrollBuffer::getLineLen(int lineNumber) bool HistoryScrollBuffer::isWrappedLine(int lineNumber) { Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); - + if (lineNumber < _usedLines) { //kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; @@ -362,12 +362,12 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C Q_ASSERT( lineNumber < _maxLineCount ); - if (lineNumber >= _usedLines) + if (lineNumber >= _usedLines) { memset(buffer, 0, count * sizeof(Character)); return; } - + const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; //kDebug() << "startCol " << startColumn; @@ -375,7 +375,7 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C //kDebug() << "count " << count; Q_ASSERT( startColumn <= line.size() - count ); - + memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); } @@ -383,12 +383,12 @@ void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount) { HistoryLine* oldBuffer = _historyBuffer; HistoryLine* newBuffer = new HistoryLine[lineCount]; - + for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) { newBuffer[i] = oldBuffer[bufferIndex(i)]; } - + _usedLines = qMin(_usedLines,(int)lineCount); _maxLineCount = lineCount; _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; @@ -411,7 +411,7 @@ int HistoryScrollBuffer::bufferIndex(int lineNumber) return (_head+lineNumber+1) % _maxLineCount; } else - { + { return lineNumber; } } @@ -509,7 +509,7 @@ void HistoryScrollBlockArray::getCells(int lineno, int colno, void HistoryScrollBlockArray::addCells(const Character a[], int count) { Block *b = m_blockArray.lastBlock(); - + if (!b) return; // put cells in block's data @@ -573,17 +573,17 @@ void* CompactHistoryBlockList::allocate(size_t size) void CompactHistoryBlockList::deallocate(void* ptr) { Q_ASSERT( !list.isEmpty()); - - int i=0; + + int i=0; CompactHistoryBlock *block = list.at(i); while ( icontains(ptr) ) - { + { i++; block=list.at(i); } Q_ASSERT( ideallocate(); if (!block->isInUse()) @@ -605,16 +605,16 @@ void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& bl return blockList.allocate(size); } -CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) +CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) : blockList(bList), formatLength(0) { length=line.size(); - + if (line.size() > 0) { formatLength=1; int k=1; - + // count number of different formats in this text line Character c = line[0]; while ( k(old)) + if (dynamic_cast(old)) return old; // Unchanged. HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); @@ -946,7 +946,7 @@ HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const } delete old; - return newScroll; + return newScroll; } int HistoryTypeFile::maximumLineCount() const diff --git a/lib/History.h b/lib/History.h index 3f2a134..912aa4a 100644 --- a/lib/History.h +++ b/lib/History.h @@ -70,7 +70,7 @@ private: //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed char* fileMap; - + //incremented whenver 'add' is called and decremented whenever //'get' is called. //this is used to detect when a large number of lines are being read and processed from the history @@ -181,7 +181,7 @@ public: void setMaxNbLines(unsigned int nbLines); unsigned int maxNbLines() { return _maxLineCount; } - + private: int bufferIndex(int lineNumber); @@ -189,9 +189,9 @@ private: HistoryLine* _historyBuffer; QBitArray _wrappedLine; int _maxLineCount; - int _usedLines; + int _usedLines; int _head; - + //QVector m_histBuffer; //QBitArray m_wrappedLine; //unsigned int m_maxNbLines; @@ -290,7 +290,7 @@ public: class CompactHistoryBlock { public: - + CompactHistoryBlock(){ blockLength = 4096*64; // 256kb head = (quint8*) mmap(0, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); @@ -299,12 +299,12 @@ public: tail = blockStart = head; allocCount=0; } - + virtual ~CompactHistoryBlock(){ //free(blockStart); munmap(blockStart, blockLength); } - + virtual unsigned int remaining(){ return blockStart+blockLength-tail;} virtual unsigned length() { return blockLength; } virtual void* allocate(size_t length); @@ -381,7 +381,7 @@ private: bool hasDifferentColors(const TextLine& line) const; HistoryArray lines; CompactHistoryBlockList blockList; - + unsigned int _maxLineCount; }; @@ -397,7 +397,7 @@ public: /** * Returns true if the history is enabled ( can store lines of output ) - * or false otherwise. + * or false otherwise. */ virtual bool isEnabled() const = 0; /** @@ -428,7 +428,7 @@ class HistoryTypeBlockArray : public HistoryType { public: HistoryTypeBlockArray(size_t size); - + virtual bool isEnabled() const; virtual int maximumLineCount() const; @@ -438,7 +438,7 @@ protected: size_t m_size; }; -#if 1 +#if 1 class HistoryTypeFile : public HistoryType { public: @@ -461,10 +461,10 @@ class HistoryTypeBuffer : public HistoryType public: HistoryTypeBuffer(unsigned int nbLines); - + virtual bool isEnabled() const; virtual int maximumLineCount() const; - + virtual HistoryScroll* scroll(HistoryScroll *) const; protected: @@ -475,7 +475,7 @@ class CompactHistoryType : public HistoryType { public: CompactHistoryType(unsigned int size); - + virtual bool isEnabled() const; virtual int maximumLineCount() const; diff --git a/lib/HistorySearch.cpp b/lib/HistorySearch.cpp index 05bedf3..41c514f 100644 --- a/lib/HistorySearch.cpp +++ b/lib/HistorySearch.cpp @@ -40,7 +40,7 @@ HistorySearch::~HistorySearch() { void HistorySearch::search() { bool found = false; - + if (! m_regExp.isEmpty()) { if (m_forwards) { @@ -48,10 +48,10 @@ void HistorySearch::search() { } else { found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); } - + if (found) { emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine); - } + } else { emit noMatchFound(); } @@ -61,43 +61,43 @@ void HistorySearch::search() { } bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) { - qDebug() << "search from" << startColumn << "," << startLine + qDebug() << "search from" << startColumn << "," << startLine << "to" << endColumn << "," << endLine; - + int linesRead = 0; int linesToRead = endLine - startLine + 1; - + qDebug() << "linesToRead:" << linesToRead; - - // We read process history from (and including) startLine to (and including) endLine in + + // We read process history from (and including) startLine to (and including) endLine in // blocks of at most 10K lines so that we do not use unhealthy amounts of memory int blockSize; while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) { - + QString string; - QTextStream searchStream(&string); - PlainTextDecoder decoder; + QTextStream searchStream(&string); + PlainTextDecoder decoder; decoder.begin(&searchStream); decoder.setRecordLinePositions(true); - // Calculate lines to read and read them - int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; + // Calculate lines to read and read them + int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; int chunkEndLine = blockStartLine + blockSize - 1; m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine); - - // We search between startColumn in the first line of the string and endColumn in the last - // line of the string. First we calculate the position (in the string) of endColumn in the + + // We search between startColumn in the first line of the string and endColumn in the last + // line of the string. First we calculate the position (in the string) of endColumn in the // last line of the string int endPosition; - - // The String that Emulator.writeToStream produces has a newline at the end, and so ends with an + + // The String that Emulator.writeToStream produces has a newline at the end, and so ends with an // empty line - we ignore that. - int numberOfLinesInString = decoder.linePositions().size() - 1; + int numberOfLinesInString = decoder.linePositions().size() - 1; if (numberOfLinesInString > 0 && endColumn > -1 ) { endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; } - else + else { endPosition = string.size(); } @@ -116,12 +116,12 @@ bool HistorySearch::search(int startColumn, int startLine, int endColumn, int en if (matchStart < startColumn) matchStart = -1; } - - if (matchStart > -1) + + if (matchStart > -1) { int matchEnd = matchStart + m_regExp.matchedLength() - 1; qDebug() << "Found in string from" << matchStart << "to" << matchEnd; - + // Translate startPos and endPos to startColum, startLine, endColumn and endLine in history. int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart); m_foundStartColumn = matchStart - decoder.linePositions().at(startLineNumberInString); @@ -136,17 +136,17 @@ bool HistorySearch::search(int startColumn, int startLine, int endColumn, int en << "m_foundEndColumn" << m_foundEndColumn << "m_foundEndLine" << m_foundEndLine; - return true; + return true; } - - + + linesRead += blockSize; } - + qDebug() << "Not found"; return false; } - + int HistorySearch::findLineNumberInString(QList linePositions, int position) { int lineNum = 0; @@ -154,4 +154,4 @@ int HistorySearch::findLineNumberInString(QList linePositions, int position lineNum++; return lineNum; -} \ No newline at end of file +} diff --git a/lib/HistorySearch.h b/lib/HistorySearch.h index c315299..e019650 100644 --- a/lib/HistorySearch.h +++ b/lib/HistorySearch.h @@ -38,7 +38,7 @@ class HistorySearch : public QObject Q_OBJECT public: - explicit HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards, + explicit HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards, int startColumn, int startLine, QObject* parent); ~HistorySearch(); @@ -49,11 +49,11 @@ signals: void matchFound(int startColumn, int startLine, int endColumn, int endLine); void noMatchFound(); -private: +private: bool search(int startColumn, int startLine, int endColumn, int endLine); int findLineNumberInString(QList linePositions, int position); - - + + EmulationPtr m_emulation; QRegExp m_regExp; bool m_forwards; diff --git a/lib/KeyboardTranslator.cpp b/lib/KeyboardTranslator.cpp index 7530421..66e1a4e 100644 --- a/lib/KeyboardTranslator.cpp +++ b/lib/KeyboardTranslator.cpp @@ -85,8 +85,8 @@ void KeyboardTranslatorManager::findTranslators() QString translatorPath = listIter.next(); QString name = QFileInfo(translatorPath).baseName(); - - if ( !_translators.contains(name) ) + + if ( !_translators.contains(name) ) _translators.insert(name,0); } @@ -124,7 +124,7 @@ Q_UNUSED(translator); QFile destination(path); if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) { - qDebug() << "Unable to save keyboard translation:" + qDebug() << "Unable to save keyboard translation:" << destination.errorString(); return false; } @@ -132,7 +132,7 @@ Q_UNUSED(translator); { KeyboardTranslatorWriter writer(&destination); writer.writeHeader(translator->description()); - + QListIterator iter(translator->entries()); while ( iter.hasNext() ) writer.writeEntry(iter.next()); @@ -147,7 +147,7 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& nam { const QString& path = findTranslatorPath(name); - QFile source(path); + QFile source(path); if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) return 0; @@ -226,7 +226,7 @@ void KeyboardTranslatorWriter::writeEntry( const KeyboardTranslator::Entry& entr // KeySequence begins with the name of the key ( taken from the Qt::Key enum ) // and is followed by the keyboard modifiers and state flags ( with + or - in front // of each modifier or flag to indicate whether it is required ). All keyboard modifiers -// and flags are optional, if a particular modifier or state is not specified it is +// and flags are optional, if a particular modifier or state is not specified it is // assumed not to be a part of the sequence. The key sequence may contain whitespace // // eg: "key Up+Shift : scrollLineUp" @@ -250,7 +250,7 @@ KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source ) // read first entry (if any) readNext(); } -void KeyboardTranslatorReader::readNext() +void KeyboardTranslatorReader::readNext() { // find next entry while ( !_source->atEnd() ) @@ -270,7 +270,7 @@ void KeyboardTranslatorReader::readNext() modifiers, modifierMask, flags, - flagMask); + flagMask); KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; QByteArray text; @@ -302,12 +302,12 @@ void KeyboardTranslatorReader::readNext() return; } - } + } _hasNext = false; } -bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) +bool KeyboardTranslatorReader::parseAsCommand(const QString& text,KeyboardTranslator::Command& command) { if ( text.compare("erase",Qt::CaseInsensitive) == 0 ) command = KeyboardTranslator::EraseCommand; @@ -334,7 +334,7 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, KeyboardTranslator::States& flags, KeyboardTranslator::States& flagMask) { - bool isWanted = true; + bool isWanted = true; bool endOfItem = false; QString buffer; @@ -386,13 +386,13 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text, buffer.clear(); } - // check if this is a wanted / not-wanted flag and update the + // check if this is a wanted / not-wanted flag and update the // state ready for the next item if ( ch == '+' ) isWanted = true; else if ( ch == '-' ) - isWanted = false; - } + isWanted = false; + } modifiers = tempModifiers; modifierMask = tempModifierMask; @@ -469,7 +469,7 @@ bool KeyboardTranslatorReader::hasNextEntry() { return _hasNext; } -KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , +KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , const QString& result ) { QString entryString("keyboard \"temporary\"\nkey "); @@ -497,7 +497,7 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& return entry; } -KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() +KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() { Q_ASSERT( _hasNext ); KeyboardTranslator::Entry entry = _nextEntry; @@ -512,7 +512,7 @@ QList KeyboardTranslatorReader::tokenize(const { QString text = line; - // remove comments + // remove comments bool inQuotes = false; int commentPos = -1; for (int i=text.length()-1;i>=0;i--) @@ -527,7 +527,7 @@ QList KeyboardTranslatorReader::tokenize(const text.remove(commentPos,text.length()); text = text.simplified(); - + // title line: keyboard "title" static QRegExp title("keyboard\\s+\"(.*)\""); // key line: key KeySequence : "output" @@ -535,7 +535,7 @@ QList KeyboardTranslatorReader::tokenize(const static QRegExp key("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)"); QList list; - if ( text.isEmpty() ) + if ( text.isEmpty() ) { return list; } @@ -544,7 +544,7 @@ QList KeyboardTranslatorReader::tokenize(const { Token titleToken = { Token::TitleKeyword , QString() }; Token textToken = { Token::TitleText , title.capturedTexts()[1] }; - + list << titleToken << textToken; } else if ( key.exactMatch(text) ) @@ -558,14 +558,14 @@ QList KeyboardTranslatorReader::tokenize(const { // capturedTexts()[2] is a command Token commandToken = { Token::Command , key.capturedTexts()[2] }; - list << commandToken; - } + list << commandToken; + } else { // capturedTexts()[3] is the output string Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; list << outputToken; - } + } } else { @@ -575,7 +575,7 @@ QList KeyboardTranslatorReader::tokenize(const return list; } -QList KeyboardTranslatorManager::allTranslators() +QList KeyboardTranslatorManager::allTranslators() { if ( !_haveLoadedAll ) { @@ -606,14 +606,14 @@ bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const _text == rhs._text; } -bool KeyboardTranslator::Entry::matches(int keyCode , +bool KeyboardTranslator::Entry::matches(int keyCode , Qt::KeyboardModifiers modifiers, States testState) const { if ( _keyCode != keyCode ) return false; - if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) + if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) return false; // if modifiers is non-zero, the 'any modifier' state is implicit @@ -623,7 +623,7 @@ bool KeyboardTranslator::Entry::matches(int keyCode , if ( (testState & _stateMask) != (_state & _stateMask) ) return false; - // special handling for the 'Any Modifier' state, which checks for the presence of + // special handling for the 'Any Modifier' state, which checks for the presence of // any or no modifiers. In this context, the 'keypad' modifier does not count. bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; @@ -632,7 +632,7 @@ bool KeyboardTranslator::Entry::matches(int keyCode , if ( wantAnyModifier != anyModifiersSet ) return false; } - + return true; } QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const @@ -661,7 +661,7 @@ QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::Keybo if ( replacement == 'x' ) { - result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); + result.replace(i,1,"\\x"+QByteArray(1,ch).toHex()); } else if ( replacement != 0 ) { result.remove(i,1); @@ -709,7 +709,7 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const unsigned charValue = 0; sscanf(hexDigits,"%x",&charValue); - replacement[0] = (char)charValue; + replacement[0] = (char)charValue; charsToRemove = 2 + strlen(hexDigits); } break; @@ -813,7 +813,7 @@ KeyboardTranslator::KeyboardTranslator(const QString& name) { } -void KeyboardTranslator::setDescription(const QString& description) +void KeyboardTranslator::setDescription(const QString& description) { _description = description; } @@ -876,7 +876,7 @@ bool KeyboardTranslatorManager::deleteTranslator(const QString& name) if ( QFile::remove(path) ) { _translators.remove(name); - return true; + return true; } else { diff --git a/lib/KeyboardTranslator.h b/lib/KeyboardTranslator.h index 15a2980..c63060d 100644 --- a/lib/KeyboardTranslator.h +++ b/lib/KeyboardTranslator.h @@ -39,7 +39,7 @@ class QTextStream; namespace Konsole { -/** +/** * A convertor which maps between key sequences pressed by the user and the * character strings which should be sent to the terminal and commands * which should be invoked when those character sequences are pressed. @@ -55,7 +55,7 @@ namespace Konsole class KeyboardTranslator { public: - /** + /** * The meaning of a particular key sequence may depend upon the state which * the terminal emulation is in. Therefore findEntry() may return a different * Entry depending upon the state flags supplied. @@ -71,7 +71,7 @@ public: * TODO More documentation */ NewLineState = 1, - /** + /** * Indicates that the terminal is in 'Ansi' mode. * TODO: More documentation */ @@ -82,10 +82,10 @@ public: CursorKeysState = 4, /** * Indicates that the alternate screen ( typically used by interactive programs - * such as screen or vim ) is active + * such as screen or vim ) is active */ AlternateScreenState = 8, - /** Indicates that any of the modifier keys is active. */ + /** Indicates that any of the modifier keys is active. */ AnyModifierState = 16, /** Indicates that the numpad is in application mode. */ ApplicationKeypadState = 32 @@ -124,14 +124,14 @@ public: class Entry { public: - /** + /** * Constructs a new entry for a keyboard translator. */ Entry(); - /** + /** * Returns true if this entry is null. - * This is true for newly constructed entries which have no properties set. + * This is true for newly constructed entries which have no properties set. */ bool isNull() const; @@ -140,15 +140,15 @@ public: /** Sets the command associated with this entry. */ void setCommand(Command command); - /** - * Returns the character sequence associated with this entry, optionally replacing + /** + * Returns the character sequence associated with this entry, optionally replacing * wildcard '*' characters with numbers to indicate the keyboard modifiers being pressed. * * TODO: The numbers used to replace '*' characters are taken from the Konsole/KDE 3 code. - * Document them. + * Document them. * * @param expandWildCards Specifies whether wild cards (occurrences of the '*' character) in - * the entry should be replaced with a number to indicate the modifier keys being pressed. + * the entry should be replaced with a number to indicate the modifier keys being pressed. * * @param modifiers The keyboard modifiers being pressed. */ @@ -158,7 +158,7 @@ public: /** Sets the character sequence associated with this entry */ void setText(const QByteArray& text); - /** + /** * Returns the character sequence associated with this entry, * with any non-printable characters replaced with escape sequences. * @@ -175,13 +175,13 @@ public: /** Sets the character code associated with this entry */ void setKeyCode(int keyCode); - /** - * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. + /** + * Returns a bitwise-OR of the enabled keyboard modifiers associated with this entry. * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry * only matches when that modifier is NOT pressed. * * If a modifier is not set in modifierMask() then the entry matches whether the modifier - * is pressed or not. + * is pressed or not. */ Qt::KeyboardModifiers modifiers() const; @@ -193,13 +193,13 @@ public: /** See modifierMask() and modifiers() */ void setModifierMask( Qt::KeyboardModifiers modifiers ); - /** - * Returns a bitwise-OR of the enabled state flags associated with this entry. - * If flag is set in stateMask() but not in state(), this means that the entry only + /** + * Returns a bitwise-OR of the enabled state flags associated with this entry. + * If flag is set in stateMask() but not in state(), this means that the entry only * matches when the terminal is NOT in that state. * * If a state is not set in stateMask() then the entry matches whether the terminal - * is in that state or not. + * is in that state or not. */ States state() const; @@ -211,13 +211,13 @@ public: /** See stateMask() */ void setStateMask( States mask ); - /** - * Returns the key code and modifiers associated with this entry + /** + * Returns the key code and modifiers associated with this entry * as a QKeySequence */ //QKeySequence keySequence() const; - /** + /** * Returns this entry's conditions ( ie. its key code, modifier and state criteria ) * as a string. */ @@ -233,16 +233,16 @@ public: QString resultToString(bool expandWildCards = false, Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; - /** + /** * Returns true if this entry matches the given key sequence, specified * as a combination of @p keyCode , @p modifiers and @p state. */ - bool matches( int keyCode , - Qt::KeyboardModifiers modifiers , + bool matches( int keyCode , + Qt::KeyboardModifiers modifiers , States flags ) const; bool operator==(const Entry& rhs) const; - + private: void insertModifier( QString& item , int modifier ) const; void insertState( QString& item , int state ) const; @@ -260,7 +260,7 @@ public: /** Constructs a new keyboard translator with the given @p name */ KeyboardTranslator(const QString& name); - + //KeyboardTranslator(const KeyboardTranslator& other); /** Returns the name of this keyboard translator */ @@ -278,7 +278,7 @@ public: /** * Looks for an entry in this keyboard translator which matches the given * key code, keyboard modifiers and state flags. - * + * * Returns the matching entry if found or a null Entry otherwise ( ie. * entry.isNull() will return true ) * @@ -286,11 +286,11 @@ public: * @param modifiers A combination of modifiers * @param state Optional flags which specify the current state of the terminal */ - Entry findEntry(int keyCode , - Qt::KeyboardModifiers modifiers , + Entry findEntry(int keyCode , + Qt::KeyboardModifiers modifiers , States state = NoState) const; - /** + /** * Adds an entry to this keyboard translator's table. Entries can be looked up according * to their key sequence using findEntry() */ @@ -321,8 +321,8 @@ private: Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States) Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) -/** - * Parses the contents of a Keyboard Translator (.keytab) file and +/** + * Parses the contents of a Keyboard Translator (.keytab) file and * returns the entries found in it. * * Usage example: @@ -342,7 +342,7 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) * if ( !reader.parseError() ) * { * // parsing succeeded, do something with the translator - * } + * } * else * { * // parsing failed @@ -355,18 +355,18 @@ public: /** Constructs a new reader which parses the given @p source */ KeyboardTranslatorReader( QIODevice* source ); - /** - * Returns the description text. - * TODO: More documentation + /** + * Returns the description text. + * TODO: More documentation */ QString description() const; /** Returns true if there is another entry in the source stream */ bool hasNextEntry(); /** Returns the next entry found in the source stream */ - KeyboardTranslator::Entry nextEntry(); + KeyboardTranslator::Entry nextEntry(); - /** + /** * Returns true if an error occurred whilst parsing the input or * false if no error occurred. */ @@ -376,7 +376,7 @@ public: * Parses a condition and result string for a translator entry * and produces a keyboard translator entry. * - * The condition and result strings are in the same format as in + * The condition and result strings are in the same format as in */ static KeyboardTranslator::Entry createEntry( const QString& condition , const QString& result ); @@ -397,7 +397,7 @@ private: }; QList tokenize(const QString&); void readNext(); - bool decodeSequence(const QString& , + bool decodeSequence(const QString& , int& keyCode, Qt::KeyboardModifiers& modifiers, Qt::KeyboardModifiers& modifierMask, @@ -419,23 +419,23 @@ private: class KeyboardTranslatorWriter { public: - /** + /** * Constructs a new writer which saves data into @p destination. * The caller is responsible for closing the device when writing is complete. */ KeyboardTranslatorWriter(QIODevice* destination); ~KeyboardTranslatorWriter(); - /** - * Writes the header for the keyboard translator. - * @param description Description of the keyboard translator. + /** + * Writes the header for the keyboard translator. + * @param description Description of the keyboard translator. */ void writeHeader( const QString& description ); /** Writes a translator entry. */ - void writeEntry( const KeyboardTranslator::Entry& entry ); + void writeEntry( const KeyboardTranslator::Entry& entry ); private: - QIODevice* _destination; + QIODevice* _destination; QTextStream* _writer; }; @@ -446,7 +446,7 @@ private: class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager { public: - /** + /** * Constructs a new KeyboardTranslatorManager and loads the list of * available keyboard translations. * @@ -457,7 +457,7 @@ public: ~KeyboardTranslatorManager(); /** - * Adds a new translator. If a translator with the same name + * Adds a new translator. If a translator with the same name * already exists, it will be replaced by the new translator. * * TODO: More documentation. @@ -474,18 +474,18 @@ public: /** Returns the default translator for Konsole. */ const KeyboardTranslator* defaultTranslator(); - /** + /** * Returns the keyboard translator with the given name or 0 if no translator * with that name exists. * * The first time that a translator with a particular name is requested, - * the on-disk .keyboard file is loaded and parsed. + * the on-disk .keyboard file is loaded and parsed. */ const KeyboardTranslator* findTranslator(const QString& name); /** * Returns a list of the names of available keyboard translators. * - * The first time this is called, a search for available + * The first time this is called, a search for available * translators is started. */ QList allTranslators(); @@ -495,15 +495,15 @@ public: private: static const QByteArray defaultTranslatorText; - + void findTranslators(); // locate the available translators - KeyboardTranslator* loadTranslator(const QString& name); // loads the translator + KeyboardTranslator* loadTranslator(const QString& name); // loads the translator // with the given name KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); bool saveTranslator(const KeyboardTranslator* translator); QString findTranslatorPath(const QString& name); - + QHash _translators; // maps translator-name -> KeyboardTranslator // instance bool _haveLoadedAll; @@ -514,15 +514,15 @@ private: inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = keyCode; } -inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) -{ +inline void KeyboardTranslator::Entry::setModifiers( Qt::KeyboardModifiers modifier ) +{ _modifiers = modifier; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } -inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) -{ - _modifierMask = mask; +inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) +{ + _modifierMask = mask; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } @@ -532,23 +532,23 @@ inline bool KeyboardTranslator::Entry::isNull() const } inline void KeyboardTranslator::Entry::setCommand( Command command ) -{ - _command = command; +{ + _command = command; } inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; } inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) -{ +{ _text = unescape(text); } inline int oneOrZero(int value) { return value ? 1 : 0; } -inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const +inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::KeyboardModifiers modifiers) const { QByteArray expandedText = _text; - + if (expandWildCards) { int modifierValue = 1; @@ -556,25 +556,25 @@ inline QByteArray KeyboardTranslator::Entry::text(bool expandWildCards,Qt::Keybo modifierValue += oneOrZero(modifiers & Qt::AltModifier) << 1; modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2; - for (int i=0;i<_text.length();i++) + for (int i=0;i<_text.length();i++) { if (expandedText[i] == '*') expandedText[i] = '0' + modifierValue; } } - return expandedText; + return expandedText; } inline void KeyboardTranslator::Entry::setState( States state ) -{ - _state = state; +{ + _state = state; } inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) -{ - _stateMask = stateMask; +{ + _stateMask = stateMask; } inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } diff --git a/lib/Pty.cpp b/lib/Pty.cpp index c986d93..bec018e 100644 --- a/lib/Pty.cpp +++ b/lib/Pty.cpp @@ -83,7 +83,7 @@ bool Pty::flowControlEnabled() const pty()->tcGetAttr(&ttmode); return ttmode.c_iflag & IXOFF && ttmode.c_iflag & IXON; - } + } qWarning() << "Unable to get flow control status, terminal not connected."; return false; } @@ -110,7 +110,7 @@ void Pty::setUtf8Mode(bool enable) void Pty::setErase(char erase) { _eraseChar = erase; - + if (pty()->masterFd() >= 0) { struct ::termios ttmode; @@ -142,7 +142,7 @@ void Pty::addEnvironmentVariables(const QStringList& environment) // split on the first '=' character int pos = pair.indexOf('='); - + if ( pos >= 0 ) { QString variable = pair.left(pos); @@ -153,10 +153,10 @@ void Pty::addEnvironmentVariables(const QStringList& environment) } } -int Pty::start(const QString& program, - const QStringList& programArguments, - const QStringList& environment, - ulong winid, +int Pty::start(const QString& program, + const QStringList& programArguments, + const QStringList& environment, + ulong winid, bool addToUtmp //const QString& dbusService, //const QString& dbusSession @@ -164,7 +164,7 @@ int Pty::start(const QString& program, { clearProgram(); - // For historical reasons, the first argument in programArguments is the + // For historical reasons, the first argument in programArguments is the // name of the program to execute, so create a list consisting of all // but the first argument to pass to setProgram() Q_ASSERT(programArguments.count() >= 1); @@ -204,10 +204,10 @@ int Pty::start(const QString& program, if (_eraseChar != 0) ttmode.c_cc[VERASE] = _eraseChar; - + if (!pty()->tcSetAttr(&ttmode)) qWarning() << "Unable to set terminal attributes."; - + pty()->setWinSize(_windowLines, _windowColumns); KProcess::start(); @@ -218,6 +218,28 @@ int Pty::start(const QString& program, return 0; } +void Pty::setEmptyPTYProperties() +{ + struct ::termios ttmode; + pty()->tcGetAttr(&ttmode); + if (!_xonXoff) + ttmode.c_iflag &= ~(IXOFF | IXON); + else + ttmode.c_iflag |= (IXOFF | IXON); + #ifdef IUTF8 // XXX not a reasonable place to check it. + if (!_utf8) + ttmode.c_iflag &= ~IUTF8; + else + ttmode.c_iflag |= IUTF8; + #endif + + if (_eraseChar != 0) + ttmode.c_cc[VERASE] = _eraseChar; + + if (!pty()->tcSetAttr(&ttmode)) + qWarning() << "Unable to set terminal attributes."; +} + void Pty::setWriteable(bool writeable) { struct stat sbuf; @@ -258,15 +280,15 @@ void Pty::sendData(const char* data, int length) { if (!length) return; - - if (!pty()->write(data,length)) + + if (!pty()->write(data,length)) { qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; return; } } -void Pty::dataReceived() +void Pty::dataReceived() { QByteArray data = pty()->readAll(); emit receivedData(data.constData(),data.count()); @@ -290,7 +312,7 @@ int Pty::foregroundProcessGroup() const if ( pid != -1 ) { return pid; - } + } return 0; } @@ -298,9 +320,9 @@ int Pty::foregroundProcessGroup() const void Pty::setupChildProcess() { KPtyProcess::setupChildProcess(); - + // reset all signal handlers - // this ensures that terminal applications respond to + // this ensures that terminal applications respond to // signals generated via key sequences such as Ctrl+C // (which sends SIGINT) struct sigaction action; diff --git a/lib/Pty.h b/lib/Pty.h index 0d28fe7..e5f6ceb 100644 --- a/lib/Pty.h +++ b/lib/Pty.h @@ -7,8 +7,8 @@ */ /* - This file is part of Konsole, KDE's terminal emulator. - + This file is part of Konsole, KDE's terminal emulator. + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -43,8 +43,8 @@ namespace Konsole { /** - * The Pty class is used to start the terminal process, - * send data to it, receive data from it and manipulate + * The Pty class is used to start the terminal process, + * send data to it, receive data from it and manipulate * various properties of the pseudo-teletype interface * used to communicate with the process. * @@ -53,26 +53,26 @@ namespace Konsole { * send data to or receive data from the process. * * To start the terminal process, call the start() method - * with the program name and appropriate arguments. + * with the program name and appropriate arguments. */ class Pty: public KPtyProcess { Q_OBJECT public: - - /** + + /** * Constructs a new Pty. - * + * * Connect to the sendData() slot and receivedData() signal to prepare * for sending and receiving data from the terminal process. * - * To start the terminal process, call the run() method with the + * To start the terminal process, call the run() method with the * name of the program to start and appropriate arguments. */ explicit Pty(QObject* parent = 0); - /** + /** * Construct a process using an open pty master. * See KPtyProcess::KPtyProcess() */ @@ -81,7 +81,7 @@ Q_OBJECT ~Pty(); /** - * Starts the terminal process. + * Starts the terminal process. * * Returns 0 if the process was started successfully or non-zero * otherwise. @@ -94,23 +94,28 @@ Q_OBJECT * @param winid Specifies the value of the WINDOWID environment variable * in the process's environment. * @param addToUtmp Specifies whether a utmp entry should be created for - * the pty used. See K3Process::setUsePty() - * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE + * the pty used. See K3Process::setUsePty() + * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE * environment variable in the process's environment. * @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION - * environment variable in the process's environment. + * environment variable in the process's environment. */ - int start( const QString& program, - const QStringList& arguments, - const QStringList& environment, - ulong winid, + int start( const QString& program, + const QStringList& arguments, + const QStringList& environment, + ulong winid, bool addToUtmp ); + /** + * set properties for "EmptyPTY" + */ + void setEmptyPTYProperties(); + /** TODO: Document me */ void setWriteable(bool writeable); - /** + /** * Enables or disables Xon/Xoff flow control. The flow control setting * may be changed later by a terminal application, so flowControlEnabled() * may not equal the value of @p on in the previous call to setFlowControlEnabled() @@ -120,12 +125,12 @@ Q_OBJECT /** Queries the terminal state and returns true if Xon/Xoff flow control is enabled. */ bool flowControlEnabled() const; - /** - * Sets the size of the window (in lines and columns of characters) + /** + * Sets the size of the window (in lines and columns of characters) * used by this teletype. */ void setWindowSize(int lines, int cols); - + /** Returns the size of the window used by this teletype. See setWindowSize() */ QSize windowSize() const; @@ -144,7 +149,7 @@ Q_OBJECT * 0 will be returned. */ int foregroundProcessGroup() const; - + public slots: /** @@ -153,7 +158,7 @@ Q_OBJECT void setUtf8Mode(bool on); /** - * Suspend or resume processing of data from the standard + * Suspend or resume processing of data from the standard * output of the terminal process. * * See K3Process::suspend() and K3Process::resume() @@ -162,9 +167,9 @@ Q_OBJECT * otherwise processing is resumed. */ void lockPty(bool lock); - - /** - * Sends data to the process currently controlling the + + /** + * Sends data to the process currently controlling the * teletype ( whose id is returned by foregroundProcessGroup() ) * * @param buffer Pointer to the data to send. @@ -182,14 +187,14 @@ Q_OBJECT * @param length Length of @p buffer */ void receivedData(const char* buffer, int length); - + protected: void setupChildProcess(); private slots: - // called when data is received from the terminal process - void dataReceived(); - + // called when data is received from the terminal process + void dataReceived(); + private: void init(); @@ -197,7 +202,7 @@ Q_OBJECT // to the environment for the process void addEnvironmentVariables(const QStringList& environment); - int _windowColumns; + int _windowColumns; int _windowLines; char _eraseChar; bool _xonXoff; diff --git a/lib/Screen.cpp b/lib/Screen.cpp index acc5f81..9ba0768 100644 --- a/lib/Screen.cpp +++ b/lib/Screen.cpp @@ -50,10 +50,10 @@ 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 +//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. +//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. @@ -198,14 +198,14 @@ void Screen::deleteChars(int n) Q_ASSERT( n >= 0 ); // always delete at least one char - if (n == 0) - n = 1; + 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() ) + if ( cuX+n > screenLines[cuY].count() ) n = screenLines[cuY].count() - cuX; Q_ASSERT( n >= 0 ); @@ -285,7 +285,7 @@ void Screen::restoreCursor() { cuX = qMin(savedState.cursorColumn,columns-1); cuY = qMin(savedState.cursorLine,lines-1); - currentRendition = savedState.rendition; + currentRendition = savedState.rendition; currentForeground = savedState.foreground; currentBackground = savedState.background; updateEffectiveRendition(); @@ -307,7 +307,7 @@ void Screen::resizeImage(int new_lines, int new_columns) // create new screen lines and copy from old to new ImageLine* newScreenLines = new ImageLine[new_lines+1]; - for (int i=0; i < qMin(lines-1,new_lines+1) ;i++) + for (int i=0; i < qMin(lines,new_lines+1) ;i++) newScreenLines[i]=screenLines[i]; for (int i=lines;(i > 0) && (ir &= ~RE_TRANSPARENT; } @@ -405,14 +405,14 @@ 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++) + 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++) + for (int column = length; column < columns; column++) dest[destLineOffset+column] = defaultChar; // invert selected text @@ -420,9 +420,9 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const { for (int column = 0; column < columns; column++) { - if (isSelected(column,line)) + if (isSelected(column,line)) { - reverseRendition(dest[destLineOffset + column]); + reverseRendition(dest[destLineOffset + column]); } } } @@ -439,15 +439,15 @@ void Screen::copyFromScreen(Character* dest , int startLine , int count) const int destLineStartIndex = (line-startLine)*columns; for (int column = 0; column < columns; column++) - { - int srcIndex = srcLineStartIndex + column; + { + int srcIndex = srcLineStartIndex + column; int destIndex = destLineStartIndex + column; dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); // invert selected text if (selBegin != -1 && isSelected(column,line + history->getLines())) - reverseRendition(dest[destIndex]); + reverseRendition(dest[destIndex]); } } @@ -460,7 +460,7 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c const int mergedLines = endLine - startLine + 1; - Q_ASSERT( size >= mergedLines * columns ); + Q_ASSERT( size >= mergedLines * columns ); Q_UNUSED( size ); const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); @@ -468,7 +468,7 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c // copy lines from history buffer if (linesInHistoryBuffer > 0) - copyFromHistory(dest,startLine,linesInHistoryBuffer); + copyFromHistory(dest,startLine,linesInHistoryBuffer); // copy lines from screen buffer if (linesInScreenBuffer > 0) @@ -491,7 +491,7 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c QVector Screen::getLineProperties( int startLine , int endLine ) const { - Q_ASSERT( startLine >= 0 ); + Q_ASSERT( startLine >= 0 ); Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); const int mergedLines = endLine-startLine+1; @@ -502,7 +502,7 @@ QVector Screen::getLineProperties( int startLine , int endLine ) c int index = 0; // copy properties for lines in history - for (int line = startLine; line < startLine + linesInHistory; line++) + for (int line = startLine; line < startLine + linesInHistory; line++) { //TODO Support for line properties other than wrapped lines if (history->isWrappedLine(line)) @@ -556,7 +556,7 @@ void Screen::backspace() if (screenLines[cuY].size() < cuX+1) screenLines[cuY].resize(cuX+1); - if (BS_CLEARS) + if (BS_CLEARS) screenLines[cuY][cuX].character = ' '; } @@ -566,8 +566,8 @@ void Screen::tab(int n) if (n == 0) n = 1; while((n > 0) && (cuX < columns-1)) { - cursorRight(1); - while((cuX < columns-1) && !tabStops[cuX]) + cursorRight(1); + while((cuX < columns-1) && !tabStops[cuX]) cursorRight(1); n--; } @@ -602,20 +602,20 @@ void Screen::initTabStops() // Arrg! 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++) + for (int i = 0; i < columns; i++) tabStops[i] = (i%8 == 0 && i != 0); } void Screen::newLine() { - if (getMode(MODE_NewLine)) + if (getMode(MODE_NewLine)) toStartOfLine(); index(); } void Screen::checkSelection(int from, int to) { - if (selBegin == -1) + if (selBegin == -1) return; int scr_TL = loc(0, history->getLines()); //Clear entire selection if it overlaps region [from, to] @@ -749,11 +749,11 @@ void Screen::scrollDown(int from, int n) _scrolledLines += n; //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. - if (n <= 0) + if (n <= 0) return; - if (from > _bottomMargin) + if (from > _bottomMargin) return; - if (from + n > _bottomMargin) + 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),' '); @@ -800,7 +800,7 @@ int Screen::getCursorY() const } void Screen::clearImage(int loca, int loce, char c) -{ +{ int scr_TL=loc(0,history->getLines()); //FIXME: check positions @@ -851,8 +851,8 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd) 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 - + //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) @@ -987,9 +987,9 @@ void Screen::setForeColor(int space, int color) { currentForeground = CharacterColor(space, color); - if ( currentForeground.isValid() ) + if ( currentForeground.isValid() ) updateEffectiveRendition(); - else + else setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); } @@ -997,13 +997,13 @@ void Screen::setBackColor(int space, int color) { currentBackground = CharacterColor(space, color); - if ( currentBackground.isValid() ) + if ( currentBackground.isValid() ) updateEffectiveRendition(); else setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); } -void Screen::clearSelection() +void Screen::clearSelection() { selBottomRight = -1; selTopLeft = -1; @@ -1015,7 +1015,7 @@ void Screen::getSelectionStart(int& column , int& line) const if ( selTopLeft != -1 ) { column = selTopLeft % columns; - line = selTopLeft / columns; + line = selTopLeft / columns; } else { @@ -1034,11 +1034,11 @@ void Screen::getSelectionEnd(int& column , int& line) const { column = cuX + getHistLines(); line = cuY + getHistLines(); - } + } } void Screen::setSelectionStart(const int x, const int y, const bool mode) { - selBegin = loc(x,y); + selBegin = loc(x,y); /* FIXME, HACK to correct for x too far to the right... */ if (x == columns) selBegin--; @@ -1049,10 +1049,10 @@ void Screen::setSelectionStart(const int x, const int y, const bool mode) void Screen::setSelectionEnd( const int x, const int y) { - if (selBegin == -1) + if (selBegin == -1) return; - int endPos = loc(x,y); + int endPos = loc(x,y); if (endPos < selBegin) { @@ -1062,7 +1062,7 @@ void Screen::setSelectionEnd( const int x, const int y) else { /* FIXME, HACK to correct for x too far to the right... */ - if (x == columns) + if (x == columns) endPos--; selTopLeft = selBegin; @@ -1113,7 +1113,7 @@ bool Screen::isSelectionValid() const return selTopLeft >= 0 && selBottomRight >= 0; } -void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , +void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , bool preserveLineBreaks) const { if (!isSelectionValid()) @@ -1121,11 +1121,11 @@ void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); } -void Screen::writeToStream(TerminalCharacterDecoder* decoder, +void Screen::writeToStream(TerminalCharacterDecoder* decoder, int startIndex, int endIndex, bool preserveLineBreaks) const { - int top = startIndex / columns; + int top = startIndex / columns; int left = startIndex % columns; int bottom = endIndex / columns; @@ -1145,7 +1145,7 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder, int copied = copyLineToStream( y, start, count, - decoder, + decoder, appendNewLine, preserveLineBreaks ); @@ -1153,25 +1153,25 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder, // 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 && + // the text on a line. + if ( y == bottom && copied < count ) { Character newLineChar('\n'); decoder->decodeLine(&newLineChar,1,0); } - } + } } -int Screen::copyLineToStream(int line , - int start, +int Screen::copyLineToStream(int line , + int start, int count, TerminalCharacterDecoder* decoder, bool appendNewLine, bool preserveLineBreaks) const { //buffer to hold characters for decoding - //the buffer is static to avoid initialising every + //the buffer is static to avoid initialising every //element on each call to copyLineToStream //(which is unnecessary since all elements will be overwritten anyway) static const int MAX_CHARS = 1024; @@ -1191,7 +1191,7 @@ int Screen::copyLineToStream(int line , // 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 + // at the end of the line, so it does not need to be trimmed here if (count == -1) { count = lineLength-start; @@ -1203,7 +1203,7 @@ int Screen::copyLineToStream(int line , // safety checks assert( start >= 0 ); - assert( count >= 0 ); + assert( count >= 0 ); assert( (start+count) <= history->getLineLen(line) ); history->getCells(line,start,count,characterBuffer); @@ -1233,7 +1233,7 @@ int Screen::copyLineToStream(int line , count = qBound(0,count,length-start); Q_ASSERT( screenLine < lineProperties.count() ); - currentLineProperties |= lineProperties[screenLine]; + currentLineProperties |= lineProperties[screenLine]; } // add new line character at end @@ -1246,8 +1246,8 @@ int Screen::copyLineToStream(int line , count++; } - //decode line and write to text stream - decoder->decodeLine( (Character*) characterBuffer , + //decode line and write to text stream + decoder->decodeLine( (Character*) characterBuffer , count, currentLineProperties ); return count; diff --git a/lib/Screen.h b/lib/Screen.h index b59c4bb..6316ad4 100644 --- a/lib/Screen.h +++ b/lib/Screen.h @@ -52,21 +52,21 @@ class TerminalCharacterDecoder; 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. + 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. + 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. + 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 + 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 colours inverted. + characters which are part of the selection have their colours inverted. */ class Screen { @@ -75,25 +75,25 @@ public: Screen(int lines, int columns); ~Screen(); - // VT100/2 Operations + // VT100/2 Operations // Cursor Movement - - /** - * Move the cursor up by @p n lines. The cursor will stop at the + + /** + * 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. */ @@ -107,28 +107,28 @@ public: /** * Sets the margins for scrolling the screen. * - * @param topLine The top line of the new scrolling margin. - * @param bottomLine The bottom line of the new scrolling margin. + * @param topLine The top line of the new scrolling margin. + * @param bottomLine The bottom line of the new scrolling margin. */ void setMargins(int topLine , int bottomLine); - /** Returns the top line of the scrolling region. */ + /** 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 + + /** + * 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. + * or index() otherwise. */ void newLine(); /** @@ -137,7 +137,7 @@ public: */ 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. @@ -149,12 +149,12 @@ public: * 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 + + /** + * 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. @@ -162,12 +162,12 @@ public: * using setMargins() */ void scrollDown(int n); - /** - * Moves the cursor to the beginning of the current line. + /** + * 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. */ @@ -176,28 +176,28 @@ public: 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. + + /** + * 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. + * 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. + /** + * 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. + * The position of the cursor is not altered. * If @p n is 0 then one character is inserted. */ void insertChars(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. @@ -211,14 +211,14 @@ public: void insertLines(int n); /** Clears all the tab stops. */ void clearTabStops(); - /** Sets or removes a tab stop at the cursor's current column. */ + /** Sets or removes a tab stop at the cursor's current column. */ void changeTabStop(bool set); - + /** Resets (clears) the specified screen @p mode. */ void resetMode(int mode); /** Sets (enables) the specified screen @p mode. */ void setMode(int mode); - /** + /** * Saves the state of the specified screen @p mode. It can be restored * using restoreMode() */ @@ -227,19 +227,19 @@ public: void restoreMode(int mode); /** Returns whether the specified screen @p mode is enabled or not .*/ bool getMode(int mode) const; - - /** - * Saves the current position and appearance (text color and style) of the cursor. - * It can be restored by calling restoreCursor() - */ + + /** + * 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. */ + + /** 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 + /** + * Clear the area of the screen from the current cursor position to the end of * the screen. */ void clearToEndOfScreen(); @@ -254,16 +254,16 @@ public: 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 + + /** + * Enables the given @p rendition flag. Rendition flags control the appearance * of characters on the screen. * * @see Character::rendition - */ + */ void setRendition(int rendition); /** * Disables the given @p rendition flag. Rendition flags control the appearance @@ -272,8 +272,8 @@ public: * @see Character::rendition */ void resetRendition(int 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 @@ -291,24 +291,24 @@ public: * @see CharacterColor */ void setBackColor(int space, int color); - /** - * Resets the cursor's color back to the default and sets the + /** + * 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; - + /** Clear the entire screen and move the cursor to the home position. * Equivalent to calling clearEntireScreen() followed by home(). */ void clear(); - /** + /** * Sets the position of the cursor to the 'home' position at the top-left - * corner of the screen (0,0) + * corner of the screen (0,0) */ void home(); /** @@ -325,41 +325,41 @@ public: *
  • New line mode is disabled. TODO Document me
  • * * - * If @p clearScreen is true then the screen contents are erased entirely, + * If @p clearScreen is true then the screen contents are erased entirely, * otherwise they are unaltered. */ void reset(bool clearScreen = true); - - /** - * Displays a new character at the current cursor position. - * + + /** + * 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 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. - */ + * 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); - + // Do composition with last shown character FIXME: Not implemented yet for KDE 4 void compose(const QString& compose); - - /** - * Resizes the image to a new fixed size of @p new_lines by @p new_columns. + + /** + * 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 + * 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. + * 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. * @@ -370,38 +370,38 @@ public: */ 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 + * 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 + int getLines() const { return lines; } /** Return the number of columns. */ - int getColumns() const + 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 + /** + * 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 column The column index of the first character in the selection. @@ -409,21 +409,21 @@ public: * @param blockSelectionMode True if the selection is in column mode. */ void setSelectionStart(const int column, const int line, const bool blockSelectionMode); - + /** * Sets the end of the current selection. * * @param column The column index of the last character in the selection. - * @param line The line index of the last character in the selection. - */ + * @param line The line index of the last character in the selection. + */ void setSelectionEnd(const int column, const int line); - + /** * 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. @@ -433,19 +433,19 @@ public: /** Clears the current selection */ void clearSelection(); - /** + /** * Returns true if the character at (@p column, @p line) is part of the - * current selection. - */ + * current selection. + */ bool isSelected(const int column,const int line) const; - /** - * Convenience method. Returns the currently selected text. - * @param preserveLineBreaks Specifies whether new line characters should + /** + * Convenience method. Returns the currently selected text. + * @param preserveLineBreaks Specifies whether new line characters should * be inserted into the returned text at the end of each terminal line. */ QString selectedText(bool preserveLineBreaks) const; - + /** * Copies part of the output to a stream. * @@ -459,11 +459,11 @@ public: * 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 + * @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 preserveLineBreaks Specifies whether new line characters should - * be inserted into the returned text at the end of each terminal line. + * @param preserveLineBreaks Specifies whether new line characters should + * be inserted into the returned text at the end of each terminal line. */ void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool preserveLineBreaks = true) const; @@ -480,15 +480,15 @@ public: */ 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 + * 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. @@ -499,24 +499,24 @@ public: */ 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. + * 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 + * 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() */ @@ -529,7 +529,7 @@ public: * * If the history is not unlimited then it will drop * the oldest lines of output if new lines are added when - * it is full. + * it is full. */ int droppedLines() const; @@ -539,32 +539,32 @@ public: */ 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); -private: +private: - //copies a line of text from the screen or history into a stream using a + //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 + //the line // - //line - the line number to copy, from 0 (the earliest line in the history) up to + //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, + int copyLineToStream(int line, + int start, + int count, TerminalCharacterDecoder* decoder, bool appendNewLine, bool preserveLineBreaks) 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. @@ -576,7 +576,7 @@ private: // //NOTE: moveImage() can only move whole lines void moveImage(int dest, int sourceBegin, int sourceEnd); - // scroll up 'i' lines in current region, clearing the bottom 'i' lines + // scroll up 'i' lines in current region, clearing the bottom 'i' lines void scrollUp(int from, int i); // scroll down 'i' lines in current region, clearing the top 'i' lines void scrollDown(int from, int i); @@ -591,7 +591,7 @@ private: 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, + void writeToStream(TerminalCharacterDecoder* decoder, int startIndex, int endIndex, bool preserveLineBreaks = true) const; // copies 'count' lines from the screen buffer into 'dest', // starting from 'startLine', where 0 is the first line in the screen buffer @@ -613,11 +613,11 @@ private: int _droppedLines; - QVarLengthArray lineProperties; - + QVarLengthArray lineProperties; + // history buffer --------------- HistoryScroll* history; - + // cursor location int cuX; int cuY; @@ -625,7 +625,7 @@ private: // cursor color and rendition info CharacterColor currentForeground; CharacterColor currentBackground; - quint8 currentRendition; + quint8 currentRendition; // margins ---------------- int _topMargin; @@ -650,7 +650,7 @@ private: CharacterColor effectiveBackground; // the cu_* variables above quint8 effectiveRendition; // to speed up operation - class SavedState + class SavedState { public: SavedState() @@ -663,7 +663,7 @@ private: CharacterColor background; }; SavedState savedState; - + // last position where we added a character int lastPos; diff --git a/lib/ScreenWindow.cpp b/lib/ScreenWindow.cpp index 1d3fadd..640465f 100644 --- a/lib/ScreenWindow.cpp +++ b/lib/ScreenWindow.cpp @@ -59,7 +59,7 @@ Character* ScreenWindow::getImage() { // reallocate internal buffer if the window size has changed int size = windowLines() * windowColumns(); - if (_windowBuffer == 0 || _windowBufferSize != size) + if (_windowBuffer == 0 || _windowBufferSize != size) { delete[] _windowBuffer; _windowBufferSize = size; @@ -69,11 +69,11 @@ Character* ScreenWindow::getImage() if (!_bufferNeedsUpdate) return _windowBuffer; - + _screen->getImage(_windowBuffer,size, currentLine(),endWindowLine()); - // this window may look beyond the end of the screen, in which + // this window may look beyond the end of the screen, in which // case there will be an unused area which needs to be filled // with blank characters fillUnusedArea(); @@ -90,10 +90,10 @@ void ScreenWindow::fillUnusedArea() int unusedLines = windowEndLine - screenEndLine; int charsToFill = unusedLines * windowColumns(); - Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); + Screen::fillWithDefaultChar(_windowBuffer + _windowBufferSize - charsToFill,charsToFill); } -// return the index of the line at the end of this window, or if this window +// return the index of the line at the end of this window, or if this window // goes beyond the end of the screen, the index of the line at the end // of the screen. // @@ -108,7 +108,7 @@ int ScreenWindow::endWindowLine() const QVector ScreenWindow::getLineProperties() { QVector result = _screen->getLineProperties(currentLine(),endWindowLine()); - + if (result.count() != windowLines()) result.resize(windowLines()); @@ -133,7 +133,7 @@ void ScreenWindow::getSelectionEnd( int& column , int& line ) void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) { _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); - + _bufferNeedsUpdate = true; emit selectionChanged(); } @@ -165,7 +165,7 @@ void ScreenWindow::setWindowLines(int lines) } int ScreenWindow::windowLines() const { - return _windowLines; + return _windowLines; } int ScreenWindow::windowColumns() const @@ -186,11 +186,11 @@ int ScreenWindow::columnCount() const QPoint ScreenWindow::cursorPosition() const { QPoint position; - + position.setX( _screen->getCursorX() ); position.setY( _screen->getCursorY() ); - return position; + return position; } int ScreenWindow::currentLine() const @@ -206,7 +206,7 @@ void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount ) } else if ( mode == ScrollPages ) { - scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); + scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); } } @@ -247,7 +247,7 @@ int ScreenWindow::scrollCount() const return _scrollCount; } -void ScreenWindow::resetScrollCount() +void ScreenWindow::resetScrollCount() { _scrollCount = 0; } @@ -267,18 +267,18 @@ void ScreenWindow::notifyOutputChanged() // move window to the bottom of the screen and update scroll count // if this window is currently tracking the bottom of the screen if ( _trackOutput ) - { + { _scrollCount -= _screen->scrolledLines(); _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); } else { - // if the history is not unlimited then it may + // if the history is not unlimited then it may // have run out of space and dropped the oldest // lines of output - in this case the screen - // window's current line number will need to + // window's current line number will need to // be adjusted - otherwise the output will scroll - _currentLine = qMax(0,_currentLine - + _currentLine = qMax(0,_currentLine - _screen->droppedLines()); // ensure that the screen window's current position does @@ -288,7 +288,7 @@ void ScreenWindow::notifyOutputChanged() _bufferNeedsUpdate = true; - emit outputChanged(); + emit outputChanged(); } //#include "ScreenWindow.moc" diff --git a/lib/ScreenWindow.h b/lib/ScreenWindow.h index 3ef2675..87d0840 100644 --- a/lib/ScreenWindow.h +++ b/lib/ScreenWindow.h @@ -35,7 +35,7 @@ class Screen; /** * Provides a window onto a section of a terminal screen. A terminal widget can then render - * the contents of the window and use the window to change the terminal screen's selection + * the contents of the window and use the window to change the terminal screen's selection * in response to mouse or keyboard input. * * A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow() @@ -55,7 +55,7 @@ class ScreenWindow : public QObject Q_OBJECT public: - /** + /** * Constructs a new screen window with the given parent. * A screen must be specified by calling setScreen() before calling getImage() or getLineProperties(). * @@ -72,7 +72,7 @@ public: /** Returns the screen which this window looks onto */ Screen* screen() const; - /** + /** * Returns the image of characters which are currently visible through this window * onto the screen. * @@ -89,14 +89,14 @@ public: /** * Returns the number of lines which the region of the window - * specified by scrollRegion() has been scrolled by since the last call - * to resetScrollCount(). scrollRegion() is in most cases the + * specified by scrollRegion() has been scrolled by since the last call + * to resetScrollCount(). scrollRegion() is in most cases the * whole window, but will be a smaller area in, for example, applications * which provide split-screen facilities. * * This is not guaranteed to be accurate, but allows views to optimize * rendering by reducing the amount of costly text rendering that - * needs to be done when the output is scrolled. + * needs to be done when the output is scrolled. */ int scrollCount() const; @@ -106,7 +106,7 @@ public: void resetScrollCount(); /** - * Returns the area of the window which was last scrolled, this is + * Returns the area of the window which was last scrolled, this is * usually the whole window area. * * Like scrollCount(), this is not guaranteed to be accurate, @@ -114,8 +114,8 @@ public: */ QRect scrollRegion() const; - /** - * Sets the start of the selection to the given @p line and @p column within + /** + * Sets the start of the selection to the given @p line and @p column within * the window. */ void setSelectionStart( int column , int line , bool columnMode ); @@ -123,7 +123,7 @@ public: * Sets the end of the selection to the given @p line and @p column within * the window. */ - void setSelectionEnd( int column , int line ); + void setSelectionEnd( int column , int line ); /** * Retrieves the start of the selection within the window. */ @@ -136,7 +136,7 @@ public: * Returns true if the character at @p line , @p column is part of the selection. */ bool isSelected( int column , int line ); - /** + /** * Clears the current selection */ void clearSelection(); @@ -147,7 +147,7 @@ public: int windowLines() const; /** Returns the number of columns in the window */ int windowColumns() const; - + /** Returns the total number of lines in the screen */ int lineCount() const; /** Returns the total number of columns in the screen */ @@ -156,13 +156,13 @@ public: /** Returns the index of the line which is currently at the top of this window */ int currentLine() const; - /** - * Returns the position of the cursor + /** + * Returns the position of the cursor * within the window. */ QPoint cursorPosition() const; - /** + /** * Convenience method. Returns true if the window is currently at the bottom * of the screen. */ @@ -176,33 +176,33 @@ public: { /** Scroll the window down by a given number of lines. */ ScrollLines, - /** + /** * Scroll the window down by a given number of pages, where * one page is windowLines() lines */ ScrollPages }; - /** + /** * Scrolls the window relative to its current position on the screen. * * @param mode Specifies whether @p amount refers to the number of lines or the number - * of pages to scroll. + * of pages to scroll. * @param amount The number of lines or pages ( depending on @p mode ) to scroll by. If * this number is positive, the view is scrolled down. If this number is negative, the view * is scrolled up. */ void scrollBy( RelativeScrollMode mode , int amount ); - /** + /** * Specifies whether the window should automatically move to the bottom * of the screen when new output is added. * - * If this is set to true, the window will be moved to the bottom of the associated screen ( see + * If this is set to true, the window will be moved to the bottom of the associated screen ( see * screen() ) when the notifyOutputChanged() method is called. */ void setTrackOutput(bool trackOutput); - /** + /** * Returns whether the window automatically moves to the bottom of the screen as * new output is added. See setTrackOutput() */ @@ -216,7 +216,7 @@ public: QString selectedText( bool preserveLineBreaks ) const; public slots: - /** + /** * Notifies the window that the contents of the associated terminal screen have changed. * This moves the window to the bottom of the screen if trackOutput() is true and causes * the outputChanged() signal to be emitted. @@ -225,13 +225,13 @@ public slots: signals: /** - * Emitted when the contents of the associated terminal screen (see screen()) changes. + * Emitted when the contents of the associated terminal screen (see screen()) changes. */ void outputChanged(); /** * Emitted when the screen window is scrolled to a different position. - * + * * @param line The line which is now at the top of the window. */ void scrolled(int line); @@ -250,7 +250,7 @@ private: int _windowLines; int _currentLine; // see scrollTo() , currentLine() - bool _trackOutput; // see setTrackOutput() , trackOutput() + bool _trackOutput; // see setTrackOutput() , trackOutput() int _scrollCount; // count of lines which the window has been scrolled by since // the last call to resetScrollCount() }; diff --git a/lib/SearchBar.cpp b/lib/SearchBar.cpp index 21e7325..6ce4cd0 100644 --- a/lib/SearchBar.cpp +++ b/lib/SearchBar.cpp @@ -30,18 +30,18 @@ SearchBar::SearchBar(QWidget *parent) : QWidget(parent) connect(widget.searchTextEdit, SIGNAL(textChanged(QString)), this, SIGNAL(searchCriteriaChanged())); connect(widget.findPreviousButton, SIGNAL(clicked()), this, SIGNAL(findPrevious())); connect(widget.findNextButton, SIGNAL(clicked()), this, SIGNAL(findNext())); - + connect(this, SIGNAL(searchCriteriaChanged()), this, SLOT(clearBackgroundColor())); QMenu *optionsMenu = new QMenu(widget.optionsButton); widget.optionsButton->setMenu(optionsMenu); - + m_matchCaseMenuEntry = optionsMenu->addAction(tr("Match case")); m_matchCaseMenuEntry->setCheckable(true); m_matchCaseMenuEntry->setChecked(true); connect(m_matchCaseMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); - + m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression")); m_useRegularExpressionMenuEntry->setCheckable(true); connect(m_useRegularExpressionMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); @@ -92,20 +92,20 @@ void SearchBar::noMatchFound() void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) { - if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) + if (keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Enter) { if (keyEvent->modifiers() == Qt::ShiftModifier) { findPrevious(); } - else + else { findNext(); } } else if (keyEvent->key() == Qt::Key_Escape) { - hide(); + hide(); } } @@ -115,4 +115,4 @@ void SearchBar::clearBackgroundColor() p.setColor(QPalette::Base, Qt::white); widget.searchTextEdit->setPalette(p); -} \ No newline at end of file +} diff --git a/lib/SearchBar.h b/lib/SearchBar.h index 3eb751f..0201173 100644 --- a/lib/SearchBar.h +++ b/lib/SearchBar.h @@ -33,7 +33,7 @@ public: QString searchText(); bool useRegularExpression(); bool matchCase(); - bool highlightAllMatches(); + bool highlightAllMatches(); public slots: void noMatchFound(); diff --git a/lib/Session.cpp b/lib/Session.cpp index e6eca88..9e29377 100644 --- a/lib/Session.cpp +++ b/lib/Session.cpp @@ -49,7 +49,7 @@ using namespace Konsole; int Session::lastSessionId = 0; -Session::Session(QObject* parent) : +Session::Session(QObject* parent) : QObject(parent), _shellProcess(0) , _emulation(0) @@ -79,6 +79,7 @@ Session::Session(QObject* parent) : //create teletype for I/O with shell process _shellProcess = new Pty(); + ptySlaveFd = _shellProcess->pty()->slaveFd(); //create emulation backend _emulation = new Vt102Emulation(); @@ -129,7 +130,17 @@ WId Session::windowId() const // there are multiple views, then the window ID for the // top-level window which contains the first view is // returned - + // + // On Qt5, requesting window IDs breaks QQuickWidget and the likes, + // for example, see the following bug reports: + // + // https://bugreports.qt-project.org/browse/QTBUG-41779 + // https://bugreports.qt-project.org/browse/QTBUG-40765 + // https://bugreports.qt-project.org/browse/QTBUG-41942 + +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + return 0; +#else if ( _views.count() == 0 ) { return 0; } else { @@ -143,6 +154,7 @@ WId Session::windowId() const return window->winId(); } +#endif } void Session::setDarkBackground(bool darkBackground) @@ -341,6 +353,22 @@ void Session::run() emit started(); } +void Session::runEmptyPTY() +{ + _shellProcess->setFlowControlEnabled(_flowControl); + _shellProcess->setErase(_emulation->eraseChar()); + _shellProcess->setWriteable(false); + + // disconnet send data from emulator to internal terminal process + disconnect( _emulation,SIGNAL(sendData(const char *,int)), + _shellProcess, SLOT(sendData(const char *,int)) ); + + _shellProcess->setEmptyPTYProperties(); + + qDebug() << "started!"; + emit started(); +} + void Session::setUserTitle( int what, const QString & caption ) { //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) @@ -469,8 +497,8 @@ void Session::activityStateSet(int state) if ( _monitorActivity ) { //FIXME: See comments in Session::monitorTimerDone() if (!_notifiedActivity) { - emit activity(); _notifiedActivity=true; + emit activity(); } } } @@ -928,6 +956,10 @@ int Session::processId() const { return _shellProcess->pid(); } +int Session::getPtySlaveFd() const +{ + return ptySlaveFd; +} SessionGroup::SessionGroup() : _masterMode(0) diff --git a/lib/Session.h b/lib/Session.h index b3a389f..5cdae55 100644 --- a/lib/Session.h +++ b/lib/Session.h @@ -25,7 +25,6 @@ #ifndef SESSION_H #define SESSION_H - #include #include @@ -363,6 +362,13 @@ public: // void cancelZModem(); // bool isZModemBusy() { return _zmodemBusy; } + /** + * Returns a pty slave file descriptor. + * This can be used for display and control + * a remote terminal. + */ + int getPtySlaveFd() const; + public slots: /** @@ -372,6 +378,13 @@ public slots: */ void run(); + /** + * Starts the terminal session for "as is" PTY + * (without the direction a data to internal terminal process). + * It can be used for control or display a remote/external terminal. + */ + void runEmptyPTY(); + /** * Closes the terminal session. This sends a hangup signal * (SIGHUP) to the terminal process and causes the done(Session*) @@ -543,6 +556,8 @@ private: static int lastSessionId; + int ptySlaveFd; + }; /** diff --git a/lib/TerminalCharacterDecoder.cpp b/lib/TerminalCharacterDecoder.cpp index d5469f6..b267b37 100644 --- a/lib/TerminalCharacterDecoder.cpp +++ b/lib/TerminalCharacterDecoder.cpp @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2006-2008 by Robert Knight - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -84,7 +84,7 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, //(since QTextStream always deals with QStrings internally anyway) QString plainText; plainText.reserve(count); - + int outputCount = count; // if inclusion of trailing whitespace is disabled then find the end of the @@ -99,7 +99,7 @@ void PlainTextDecoder::decodeLine(const Character* const characters, int count, outputCount--; } } - + for (int i=0;i') text.append(">"); - else + else text.append(ch); } else { text.append(" "); //HTML truncates multiple spaces, so use a space marker instead } - + } //close any remaining open inner spans @@ -232,7 +232,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP //start new line text.append("
    "); - + *_output << text; } void HTMLDecoder::openSpan(QString& text , const QString& style) diff --git a/lib/TerminalCharacterDecoder.h b/lib/TerminalCharacterDecoder.h index 5bdc035..75d40c3 100644 --- a/lib/TerminalCharacterDecoder.h +++ b/lib/TerminalCharacterDecoder.h @@ -1,8 +1,8 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2006-2008 by Robert Knight - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -38,7 +38,7 @@ namespace Konsole * and background colours and other appearance-related properties into text strings. * * Derived classes may produce either plain text with no other colour or appearance information, or - * they may produce text which incorporates these additional properties. + * they may produce text which incorporates these additional properties. */ class TerminalCharacterDecoder { @@ -58,9 +58,9 @@ public: * @param count The number of characters * @param properties Additional properties which affect all characters in the line */ - virtual void decodeLine(const Character* const characters, + virtual void decodeLine(const Character* const characters, int count, - LineProperty properties) = 0; + LineProperty properties) = 0; }; /** @@ -70,10 +70,10 @@ public: class PlainTextDecoder : public TerminalCharacterDecoder { public: - PlainTextDecoder(); + PlainTextDecoder(); - /** - * Set whether trailing whitespace at the end of lines should be included + /** + * Set whether trailing whitespace at the end of lines should be included * in the output. * Defaults to true. */ @@ -83,9 +83,9 @@ public: * in the output. */ bool trailingWhitespace() const; - /** + /** * Returns of character positions in the output stream - * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if + * at which new lines where added. Returns an empty if setTrackLinePositions() is false or if * the output device is not a string. */ QList linePositions() const; @@ -97,9 +97,9 @@ public: virtual void decodeLine(const Character* const characters, int count, - LineProperty properties); + LineProperty properties); + - private: QTextStream* _output; bool _includeTrailingWhitespace; @@ -114,7 +114,7 @@ private: class HTMLDecoder : public TerminalCharacterDecoder { public: - /** + /** * Constructs an HTML decoder using a default black-on-white color scheme. */ HTMLDecoder(); @@ -124,7 +124,7 @@ public: * output */ void setColorTable( const ColorEntry* table ); - + virtual void decodeLine(const Character* const characters, int count, LineProperty properties); @@ -138,7 +138,7 @@ private: QTextStream* _output; const ColorEntry* _colorTable; - bool _innerSpanOpen; + bool _innerSpanOpen; quint8 _lastRendition; CharacterColor _lastForeColor; CharacterColor _lastBackColor; diff --git a/lib/TerminalDisplay.cpp b/lib/TerminalDisplay.cpp index c5997c7..18b0f47 100644 --- a/lib/TerminalDisplay.cpp +++ b/lib/TerminalDisplay.cpp @@ -1,9 +1,9 @@ /* This file is part of Konsole, a terminal emulator for KDE. - + Copyright 2006-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle - + This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or @@ -103,7 +103,7 @@ bool TerminalDisplay::_antialiasText = true; bool TerminalDisplay::HAVE_TRANSPARENCY = true; // we use this to force QPainter to display text in LTR mode -// more information can be found in: http://unicode.org/reports/tr9/ +// more information can be found in: http://unicode.org/reports/tr9/ const QChar LTR_OVERRIDE_CHAR( 0x202D ); /* ------------------------------------------------------------------------- */ @@ -155,11 +155,11 @@ void TerminalDisplay::setBackgroundColor(const QColor& color) { _colorTable[DEFAULT_BACK_COLOR].color = color; QPalette p = palette(); - p.setColor( backgroundRole(), color ); + p.setColor( backgroundRole(), color ); setPalette( p ); - // Avoid propagating the palette change to the scroll bar - _scrollBar->setPalette( QApplication::palette() ); + // Avoid propagating the palette change to the scroll bar + _scrollBar->setPalette( QApplication::palette() ); update(); } @@ -200,7 +200,7 @@ static inline bool isLineCharString(const QString& string) { return (string.length() > 0) && (isLineChar(string.at(0).unicode())); } - + // assert for i in [0..31] : vt100extended(vt100_graphics[i]) == i. @@ -249,7 +249,7 @@ void TerminalDisplay::setVTFont(const QFont& f) { QFont font = f; - // This was originally set for OS X only: + // This was originally set for OS X only: // mac uses floats for font width specification. // this ensures the same handling for all platforms // but then there was revealed that various Linux distros @@ -260,19 +260,19 @@ void TerminalDisplay::setVTFont(const QFont& f) if ( !QFontInfo(font).fixedPitch() ) { - qDebug() << "Using an unsupported variable-width font in the terminal. This may produce display errors."; + qDebug() << "Using a variable-width font in the terminal. This may cause performance degradation and display/alignment errors."; } if ( metrics.height() < height() && metrics.maxWidth() < width() ) { - // hint that text should be drawn without anti-aliasing. + // hint that text should be drawn without anti-aliasing. // depending on the user's font configuration, this may not be respected if (!_antialiasText) font.setStyleStrategy( QFont::NoAntialias ); - - // experimental optimization. Konsole assumes that the terminal is using a + + // experimental optimization. Konsole assumes that the terminal is using a // mono-spaced font, in which case kerning information should have an effect. - // Disabling kerning saves some computation when rendering text. + // Disabling kerning saves some computation when rendering text. font.setKerning(false); QWidget::setFont(font); @@ -353,9 +353,9 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) // create scroll bar for scrolling output up and down // set the scroll bar's slider to occupy the whole area of the scroll bar initially _scrollBar = new QScrollBar(this); - setScroll(0,0); + setScroll(0,0); _scrollBar->setCursor( Qt::ArrowCursor ); - connect(_scrollBar, SIGNAL(valueChanged(int)), this, + connect(_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(scrollBarPositionChanged(int))); // qtermwidget: we have to hide it here due the _scrollbarLocation==NoScrollBar // check in TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) @@ -368,12 +368,12 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) connect(_blinkCursorTimer, SIGNAL(timeout()), this, SLOT(blinkCursorEvent())); // KCursor::setAutoHideCursor( this, true ); - + setUsesMouse(true); setColorTable(base_color_table); setMouseTracking(true); - // Enable drag and drop + // Enable drag and drop setAcceptDrops(true); // attempt dragInfo.state = diNone; @@ -389,7 +389,7 @@ TerminalDisplay::TerminalDisplay(QWidget *parent) _gridLayout = new QGridLayout(this); _gridLayout->setContentsMargins(0, 0, 0, 0); - setLayout( _gridLayout ); + setLayout( _gridLayout ); new AutoScrollHandler(this); } @@ -399,7 +399,7 @@ TerminalDisplay::~TerminalDisplay() disconnect(_blinkTimer); disconnect(_blinkCursorTimer); qApp->removeEventFilter( this ); - + delete[] _image; delete _gridLayout; @@ -529,18 +529,18 @@ static void drawLineChar(QPainter& paint, int x, int y, int w, int h, uchar code } -void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, +void TerminalDisplay::drawLineCharString( QPainter& painter, int x, int y, const QString& str, const Character* attributes) { const QPen& currentPen = painter.pen(); - + if ( (attributes->rendition & RE_BOLD) && _boldIntense ) { QPen boldPen(currentPen); boldPen.setWidth(3); painter.setPen( boldPen ); - } - + } + for (int i=0 ; i < str.length(); i++) { uchar code = str[i].cell(); @@ -582,7 +582,7 @@ void TerminalDisplay::setOpacity(qreal opacity) // enable automatic background filling to prevent the display // flickering if there is no transparency - /*if ( color.alpha() == 255 ) + /*if ( color.alpha() == 255 ) { setAutoFillBackground(true); } @@ -602,15 +602,15 @@ void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const // the area of the widget behind the scroll-bar is drawn using the background // brush from the scroll-bar's palette, to give the effect of the scroll-bar // being outside of the terminal display and visual consistency with other KDE - // applications. + // applications. // - QRect scrollBarArea = _scrollBar->isVisible() ? + QRect scrollBarArea = _scrollBar->isVisible() ? rect.intersected(_scrollBar->geometry()) : QRect(); QRegion contentsRegion = QRegion(rect).subtracted(scrollBarArea); QRect contentsRect = contentsRegion.boundingRect(); - if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) + if ( HAVE_TRANSPARENCY && qAlpha(_blendColor) < 0xff && useOpacitySetting ) { QColor color(backgroundColor); color.setAlpha(qAlpha(_blendColor)); @@ -619,14 +619,14 @@ void TerminalDisplay::drawBackground(QPainter& painter, const QRect& rect, const painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect(contentsRect, color); painter.restore(); - } + } else painter.fillRect(contentsRect, backgroundColor); painter.fillRect(scrollBarArea,_scrollBar->palette().background()); } -void TerminalDisplay::drawCursor(QPainter& painter, +void TerminalDisplay::drawCursor(QPainter& painter, const QRect& rect, const QColor& foregroundColor, const QColor& /*backgroundColor*/, @@ -634,7 +634,7 @@ void TerminalDisplay::drawCursor(QPainter& painter, { QRect cursorRect = rect; cursorRect.setHeight(_fontHeight - _lineSpacing - 1); - + if (!_cursorBlinking) { if ( _cursorColor.isValid() ) @@ -655,7 +655,7 @@ void TerminalDisplay::drawCursor(QPainter& painter, if ( hasFocus() ) { painter.fillRect(cursorRect, _cursorColor.isValid() ? _cursorColor : foregroundColor); - + if ( !_cursorColor.isValid() ) { // invert the colour used to draw the text to ensure that the character at @@ -674,7 +674,7 @@ void TerminalDisplay::drawCursor(QPainter& painter, cursorRect.top(), cursorRect.left(), cursorRect.bottom()); - + } } @@ -687,10 +687,10 @@ void TerminalDisplay::drawCharacters(QPainter& painter, // don't draw text which is currently blinking if ( _blinking && (style->rendition & RE_BLINK) ) return; - + // setup bold and underline bool useBold; - ColorEntry::FontWeight weight = style->fontWeight(_colorTable); + ColorEntry::FontWeight weight = style->fontWeight(_colorTable); if (weight == ColorEntry::UseCurrentFormat) useBold = ((style->rendition & RE_BOLD) && _boldIntense) || font().bold(); else @@ -698,7 +698,7 @@ void TerminalDisplay::drawCharacters(QPainter& painter, bool useUnderline = style->rendition & RE_UNDERLINE || font().underline(); QFont font = painter.font(); - if ( font.bold() != useBold + if ( font.bold() != useBold || font.underline() != useUnderline ) { font.setBold(useBold); @@ -722,8 +722,8 @@ void TerminalDisplay::drawCharacters(QPainter& painter, else { // the drawText(rect,flags,string) overload is used here with null flags - // instead of drawText(rect,string) because the (rect,string) overload causes - // the application's default layout direction to be used instead of + // instead of drawText(rect,string) because the (rect,string) overload causes + // the application's default layout direction to be used instead of // the widget-specific layout direction, which should always be // Qt::LeftToRight for this widget // This was discussed in: http://lists.kde.org/?t=120552223600002&r=1&w=2 @@ -738,17 +738,17 @@ void TerminalDisplay::drawCharacters(QPainter& painter, } } -void TerminalDisplay::drawTextFragment(QPainter& painter , +void TerminalDisplay::drawTextFragment(QPainter& painter , const QRect& rect, - const QString& text, + const QString& text, const Character* style) { painter.save(); - // setup painter + // setup painter const QColor foregroundColor = style->foregroundColor.color(_colorTable); const QColor backgroundColor = style->backgroundColor.color(_colorTable); - + // draw background if different from the display's background color if ( backgroundColor != palette().background().color() ) drawBackground(painter,rect,backgroundColor, @@ -791,15 +791,15 @@ void TerminalDisplay::setCursorPos(const int curx, const int cury) // scrolls the image by 'lines', down if lines > 0 or up otherwise. // -// the terminal emulation keeps track of the scrolling of the character -// image as it receives input, and when the view is updated, it calls scrollImage() -// with the final scroll amount. this improves performance because scrolling the -// display is much cheaper than re-rendering all the text for the -// part of the image which has moved up or down. +// the terminal emulation keeps track of the scrolling of the character +// image as it receives input, and when the view is updated, it calls scrollImage() +// with the final scroll amount. this improves performance because scrolling the +// display is much cheaper than re-rendering all the text for the +// part of the image which has moved up or down. // Instead only new lines have to be drawn void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) { - // if the flow control warning is enabled this will interfere with the + // if the flow control warning is enabled this will interfere with the // scrolling optimizations and cause artifacts. the simple solution here // is to just disable the optimization whilst it is visible if ( _outputSuspendedLabel && _outputSuspendedLabel->isVisible() ) @@ -810,13 +810,13 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // internal image - 2, so that the height of 'region' is strictly less // than the height of the internal image. QRect region = screenWindowRegion; - region.setBottom( qMin(region.bottom(),this->_lines-2) ); + region.setBottom( qMin(region.bottom(),this->_lines-2) ); // return if there is nothing to do - if ( lines == 0 + if ( lines == 0 || _image == 0 - || !region.isValid() - || (region.top() + abs(lines)) >= region.bottom() + || !region.isValid() + || (region.top() + abs(lines)) >= region.bottom() || this->_lines <= region.height() ) return; // hide terminal size label to prevent it being scrolled @@ -826,8 +826,8 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) // Note: With Qt 4.4 the left edge of the scrolled area must be at 0 // to get the correct (newly exposed) part of the widget repainted. // - // The right edge must be before the left edge of the scroll bar to - // avoid triggering a repaint of the entire widget, the distance is + // The right edge must be before the left edge of the scroll bar to + // avoid triggering a repaint of the entire widget, the distance is // given by SCROLLBAR_CONTENT_GAP // // Set the QT_FLUSH_PAINT environment variable to '1' before starting the @@ -851,7 +851,7 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) int top = _topMargin + (region.top() * _fontHeight); int linesToMove = region.height() - abs(lines); - int bytesToMove = linesToMove * + int bytesToMove = linesToMove * this->_columns * sizeof(Character); @@ -862,28 +862,28 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) if ( lines > 0 ) { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)lastCharPos + bytesToMove < + Q_ASSERT( (char*)lastCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); - - Q_ASSERT( (lines*this->_columns) < _imageSize ); + + Q_ASSERT( (lines*this->_columns) < _imageSize ); //scroll internal image down - memmove( firstCharPos , lastCharPos , bytesToMove ); - + memmove( firstCharPos , lastCharPos , bytesToMove ); + //set region of display to scroll scrollRect.setTop(top); } else { // check that the memory areas that we are going to move are valid - Q_ASSERT( (char*)firstCharPos + bytesToMove < + Q_ASSERT( (char*)firstCharPos + bytesToMove < (char*)(_image + (this->_lines * this->_columns)) ); //scroll internal image up - memmove( lastCharPos , firstCharPos , bytesToMove ); - + memmove( lastCharPos , firstCharPos , bytesToMove ); + //set region of the display to scroll - scrollRect.setTop(top + abs(lines) * _fontHeight); + scrollRect.setTop(top + abs(lines) * _fontHeight); } scrollRect.setHeight(linesToMove * _fontHeight ); @@ -893,7 +893,7 @@ void TerminalDisplay::scrollImage(int lines , const QRect& screenWindowRegion) scroll( 0 , _fontHeight * (-lines) , scrollRect ); } -QRegion TerminalDisplay::hotSpotRegion() const +QRegion TerminalDisplay::hotSpotRegion() const { QRegion region; foreach( Filter::HotSpot* hotSpot , _filterChain->hotSpots() ) @@ -928,7 +928,7 @@ QRegion TerminalDisplay::hotSpotRegion() const return region; } -void TerminalDisplay::processFilters() +void TerminalDisplay::processFilters() { if (!_screenWindow) return; @@ -938,7 +938,7 @@ void TerminalDisplay::processFilters() // use _screenWindow->getImage() here rather than _image because // other classes may call processFilters() when this display's // ScreenWindow emits a scrolled() signal - which will happen before - // updateImage() is called on the display and therefore _image is + // updateImage() is called on the display and therefore _image is // out of date at this point _filterChain->setImage( _screenWindow->getImage(), _screenWindow->windowLines(), @@ -951,13 +951,13 @@ void TerminalDisplay::processFilters() update( preUpdateHotSpots | postUpdateHotSpots ); } -void TerminalDisplay::updateImage() +void TerminalDisplay::updateImage() { if ( !_screenWindow ) return; - // optimization - scroll the existing image where possible and - // avoid expensive text drawing for parts of the image that + // optimization - scroll the existing image where possible and + // avoid expensive text drawing for parts of the image that // can simply be moved up or down scrollImage( _screenWindow->scrollCount() , _screenWindow->scrollRegion() ); @@ -993,7 +993,7 @@ void TerminalDisplay::updateImage() const int columnsToUpdate = qMin(this->_columns,qMax(0,columns)); QChar *disstrU = new QChar[columnsToUpdate]; - char *dirtyMask = new char[columnsToUpdate+2]; + char *dirtyMask = new char[columnsToUpdate+2]; QRegion dirtyRegion; // debugging variable, this records the number of lines that are found to @@ -1007,15 +1007,15 @@ void TerminalDisplay::updateImage() const Character* const newLine = &newimg[y*columns]; bool updateLine = false; - + // The dirty mask indicates which characters need repainting. We also // mark surrounding neighbours dirty, in case the character exceeds // its cell boundaries memset(dirtyMask, 0, columnsToUpdate+2); - + for( x = 0 ; x < columnsToUpdate ; ++x) { - if ( newLine[x] != currentLine[x] ) + if ( newLine[x] != currentLine[x] ) { dirtyMask[x] = true; } @@ -1025,7 +1025,7 @@ void TerminalDisplay::updateImage() for (x = 0; x < columnsToUpdate; ++x) { _hasBlinker |= (newLine[x].rendition & RE_BLINK); - + // Start drawing if this character or the next one differs. // We also take the next one into account to handle the situation // where characters exceed their cell width. @@ -1051,11 +1051,11 @@ void TerminalDisplay::updateImage() bool nextIsDoubleWidth = (x+len+1 == columnsToUpdate) ? false : (newLine[x+len+1].character == 0); - if ( ch.foregroundColor != cf || - ch.backgroundColor != _clipboard || + if ( ch.foregroundColor != cf || + ch.backgroundColor != _clipboard || ch.rendition != cr || - !dirtyMask[x+len] || - isLineChar(c) != lineDraw || + !dirtyMask[x+len] || + isLineChar(c) != lineDraw || nextIsDoubleWidth != doubleWidth ) break; @@ -1075,53 +1075,53 @@ void TerminalDisplay::updateImage() _fixedFont = saveFixedFont; x += len - 1; } - + } //both the top and bottom halves of double height _lines must always be redrawn - //although both top and bottom halves contain the same characters, only - //the top one is actually + //although both top and bottom halves contain the same characters, only + //the top one is actually //drawn. if (_lineProperties.count() > y) updateLine |= (_lineProperties[y] & LINE_DOUBLEHEIGHT); // if the characters on the line are different in the old and the new _image - // then this line must be repainted. + // then this line must be repainted. if (updateLine) { dirtyLineCount++; // add the area occupied by this line to the region which needs to be // repainted - QRect dirtyRect = QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*y , - _fontWidth * columnsToUpdate , - _fontHeight ); + QRect dirtyRect = QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*y , + _fontWidth * columnsToUpdate , + _fontHeight ); dirtyRegion |= dirtyRect; } - // replace the line of characters in the old _image with the - // current line of the new _image + // replace the line of characters in the old _image with the + // current line of the new _image memcpy((void*)currentLine,(const void*)newLine,columnsToUpdate*sizeof(Character)); } // if the new _image is smaller than the previous _image, then ensure that the area - // outside the new _image is cleared + // outside the new _image is cleared if ( linesToUpdate < _usedLines ) { - dirtyRegion |= QRect( _leftMargin+tLx , - _topMargin+tLy+_fontHeight*linesToUpdate , - _fontWidth * this->_columns , + dirtyRegion |= QRect( _leftMargin+tLx , + _topMargin+tLy+_fontHeight*linesToUpdate , + _fontWidth * this->_columns , _fontHeight * (_usedLines-linesToUpdate) ); } _usedLines = linesToUpdate; - + if ( columnsToUpdate < _usedColumns ) { - dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , - _topMargin+tLy , - _fontWidth * (_usedColumns-columnsToUpdate) , + dirtyRegion |= QRect( _leftMargin+tLx+columnsToUpdate*_fontWidth , + _topMargin+tLy , + _fontWidth * (_usedColumns-columnsToUpdate) , _fontHeight * this->_lines ); } _usedColumns = columnsToUpdate; @@ -1131,7 +1131,7 @@ void TerminalDisplay::updateImage() // update the parts of the display which have changed update(dirtyRegion); - if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); + if ( _hasBlinker && !_blinkTimer->isActive()) _blinkTimer->start( TEXT_BLINK_DELAY ); if (!_hasBlinker && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; } delete[] dirtyMask; delete[] disstrU; @@ -1171,11 +1171,11 @@ void TerminalDisplay::showResizeNotification() void TerminalDisplay::setBlinkingCursor(bool blink) { _hasBlinkingCursor=blink; - - if (blink && !_blinkCursorTimer->isActive()) + + if (blink && !_blinkCursorTimer->isActive()) _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); - - if (!blink && _blinkCursorTimer->isActive()) + + if (!blink && _blinkCursorTimer->isActive()) { _blinkCursorTimer->stop(); if (_cursorBlinking) @@ -1189,10 +1189,10 @@ void TerminalDisplay::setBlinkingTextEnabled(bool blink) { _allowBlinkingText = blink; - if (blink && !_blinkTimer->isActive()) + if (blink && !_blinkTimer->isActive()) _blinkTimer->start(TEXT_BLINK_DELAY); - - if (!blink && _blinkTimer->isActive()) + + if (!blink && _blinkTimer->isActive()) { _blinkTimer->stop(); _blinking = false; @@ -1260,14 +1260,14 @@ QRect TerminalDisplay::preeditRect() const _topMargin + _fontHeight*cursorPosition().y(), _fontWidth*preeditLength, _fontHeight); -} +} void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRect& rect) { if ( _inputMethodData.preeditString.isEmpty() ) return; - const QPoint cursorPos = cursorPosition(); + const QPoint cursorPos = cursorPosition(); bool invertColors = false; const QColor background = _colorTable[DEFAULT_BACK_COLOR].color; @@ -1278,7 +1278,7 @@ void TerminalDisplay::drawInputMethodPreeditString(QPainter& painter , const QRe drawCursor(painter,rect,foreground,background,invertColors); drawCharacters(painter,rect,_inputMethodData.preeditString,style,invertColors); - _inputMethodData.previousPreeditRect = rect; + _inputMethodData.previousPreeditRect = rect; } FilterChain* TerminalDisplay::filterChain() const @@ -1300,7 +1300,7 @@ void TerminalDisplay::paintFilters(QPainter& painter) painter.setPen( QPen(cursorCharacter.foregroundColor.color(colorTable())) ); - // iterate over hotspots identified by the display's currently active filters + // iterate over hotspots identified by the display's currently active filters // and draw appropriate visuals to indicate the presence of the hotspot QList spots = _filterChain->hotSpots(); @@ -1313,28 +1313,28 @@ void TerminalDisplay::paintFilters(QPainter& painter) if ( spot->type() == Filter::HotSpot::Link ) { QRect r; if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, + r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, spot->startLine()*_fontHeight + 1, - (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); + (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, + (spot->endLine()+1)*_fontHeight - 1 ); region |= r; } else { - r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, + r.setCoords( spot->startColumn()*_fontWidth + 1 + scrollBarWidth, spot->startLine()*_fontHeight + 1, - (_columns-1)*_fontWidth - 1 + scrollBarWidth, - (spot->startLine()+1)*_fontHeight - 1 ); + (_columns-1)*_fontWidth - 1 + scrollBarWidth, + (spot->startLine()+1)*_fontHeight - 1 ); region |= r; for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, + r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, line*_fontHeight + 1, (_columns-1)*_fontWidth - 1 + scrollBarWidth, - (line+1)*_fontHeight - 1 ); + (line+1)*_fontHeight - 1 ); region |= r; } r.setCoords( 0*_fontWidth + 1 + scrollBarWidth, spot->endLine()*_fontHeight + 1, (spot->endColumn()-1)*_fontWidth - 1 + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); + (spot->endLine()+1)*_fontHeight - 1 ); region |= r; } } @@ -1342,14 +1342,14 @@ void TerminalDisplay::paintFilters(QPainter& painter) for ( int line = spot->startLine() ; line <= spot->endLine() ; line++ ) { int startColumn = 0; - int endColumn = _columns-1; // TODO use number of _columns which are actually - // occupied on this line rather than the width of the + int endColumn = _columns-1; // TODO use number of _columns which are actually + // occupied on this line rather than the width of the // display in _columns // ignore whitespace at the end of the lines while ( QChar(_image[loc(endColumn,line)].character).isSpace() && endColumn > 0 ) endColumn--; - + // increment here because the column which we want to set 'endColumn' to // is the first whitespace character at the end of the line endColumn++; @@ -1365,26 +1365,26 @@ void TerminalDisplay::paintFilters(QPainter& painter) // hotspots // // subtracting one pixel from all sides also prevents an edge case where - // moving the mouse outside a link could still leave it underlined + // moving the mouse outside a link could still leave it underlined // because the check below for the position of the cursor // finds it on the border of the target area QRect r; r.setCoords( startColumn*_fontWidth + 1 + scrollBarWidth, line*_fontHeight + 1, endColumn*_fontWidth - 1 + scrollBarWidth, - (line+1)*_fontHeight - 1 ); - // Underline link hotspots + (line+1)*_fontHeight - 1 ); + // Underline link hotspots if ( spot->type() == Filter::HotSpot::Link ) { QFontMetrics metrics(font()); - + // find the baseline (which is the invisible line that the characters in the font sit on, // with some having tails dangling below) int baseline = r.bottom() - metrics.descent(); // find the position of the underline below that int underlinePos = baseline + metrics.underlinePos(); if ( region.contains( mapFromGlobal(QCursor::pos()) ) ){ - painter.drawLine( r.left() , underlinePos , + painter.drawLine( r.left() , underlinePos , r.right() , underlinePos ); } } @@ -1398,6 +1398,27 @@ void TerminalDisplay::paintFilters(QPainter& painter) } } } + +int TerminalDisplay::textWidth(const int startColumn, const int length, const int line) const +{ + QFontMetrics fm(font()); + int result = 0; + for (int column = 0; column < length; column++) { + result += fm.width(_image[loc(startColumn + column, line)].character); + } + return result; +} + +QRect TerminalDisplay::calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length) { + int left = _fixedFont ? _fontWidth * startColumn : textWidth(0, startColumn, line); + int top = _fontHeight * line; + int width = _fixedFont ? _fontWidth * length : textWidth(startColumn, length, line); + return QRect(_leftMargin + topLeftX + left, + _topMargin + topLeftY + top, + width, + _fontHeight); +} + void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) { QPoint tL = contentsRect().topLeft(); @@ -1405,9 +1426,9 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) int tLy = tL.y(); int lux = qMin(_usedColumns-1, qMax(0,(rect.left() - tLx - _leftMargin ) / _fontWidth)); - int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); + int luy = qMin(_usedLines-1, qMax(0,(rect.top() - tLy - _topMargin ) / _fontHeight)); int rlx = qMin(_usedColumns-1, qMax(0,(rect.right() - tLx - _leftMargin ) / _fontWidth)); - int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); + int rly = qMin(_usedLines-1, qMax(0,(rect.bottom() - tLy - _topMargin ) / _fontHeight)); const int bufferSize = _usedColumns; QString unistr; @@ -1434,7 +1455,7 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) ushort extendedCharLength = 0; ushort* chars = ExtendedCharTable::instance .lookupExtendedChar(_image[loc(x,y)].charSequence,extendedCharLength); - for ( int index = 0 ; index < extendedCharLength ; index++ ) + for ( int index = 0 ; index < extendedCharLength ; index++ ) { Q_ASSERT( p < bufferSize ); disstrU[p++] = chars[index]; @@ -1456,7 +1477,7 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) CharacterColor currentForeground = _image[loc(x,y)].foregroundColor; CharacterColor currentBackground = _image[loc(x,y)].backgroundColor; quint8 currentRendition = _image[loc(x,y)].rendition; - + while (x+len <= rlx && _image[loc(x+len,y)].foregroundColor == currentForeground && _image[loc(x+len,y)].backgroundColor == currentBackground && @@ -1496,40 +1517,40 @@ void TerminalDisplay::drawContents(QPainter &paint, const QRect &rect) paint.setWorldMatrix(textScale, true); //calculate the area in which the text will be drawn - QRect textArea = QRect( _leftMargin+tLx+_fontWidth*x , _topMargin+tLy+_fontHeight*y , _fontWidth*len , _fontHeight); - + QRect textArea = calculateTextArea(tLx, tLy, x, y, len); + //move the calculated area to take account of scaling applied to the painter. - //the position of the area from the origin (0,0) is scaled + //the position of the area from the origin (0,0) is scaled //by the opposite of whatever - //transformation has been applied to the painter. this ensures that - //painting does actually start from textArea.topLeft() - //(instead of textArea.topLeft() * painter-scale) + //transformation has been applied to the painter. this ensures that + //painting does actually start from textArea.topLeft() + //(instead of textArea.topLeft() * painter-scale) textArea.moveTopLeft( textScale.inverted().map(textArea.topLeft()) ); - + //paint text fragment drawTextFragment( paint, textArea, - unistr, - &_image[loc(x,y)] ); //, - //0, + unistr, + &_image[loc(x,y)] ); //, + //0, //!_isPrinting ); - + _fixedFont = save__fixedFont; - - //reset back to single-width, single-height _lines + + //reset back to single-width, single-height _lines paint.setWorldMatrix(textScale.inverted(), true); if (y < _lineProperties.size()-1) { - //double-height _lines are represented by two adjacent _lines + //double-height _lines are represented by two adjacent _lines //containing the same characters - //both _lines will have the LINE_DOUBLEHEIGHT attribute. - //If the current line has the LINE_DOUBLEHEIGHT attribute, + //both _lines will have the LINE_DOUBLEHEIGHT attribute. + //If the current line has the LINE_DOUBLEHEIGHT attribute, //we can therefore skip the next line if (_lineProperties[y] & LINE_DOUBLEHEIGHT) y++; } - + x += len - 1; } } @@ -1541,7 +1562,7 @@ void TerminalDisplay::blinkEvent() _blinking = !_blinking; - //TODO: Optimize to only repaint the areas of the widget + //TODO: Optimize to only repaint the areas of the widget // where there is blinking text // rather than repainting the whole widget. update(); @@ -1560,7 +1581,7 @@ QRect TerminalDisplay::imageToWidget(const QRect& imageArea) const void TerminalDisplay::updateCursor() { - QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); + QRect cursorRect = imageToWidget( QRect(cursorPosition(),QSize(1,1)) ); update(cursorRect); } @@ -1603,14 +1624,14 @@ void TerminalDisplay::updateImageSize() int oldcol = _columns; makeImage(); - + // copy the old image to reduce flicker int lines = qMin(oldlin,_lines); int columns = qMin(oldcol,_columns); if (oldimg) { - for (int line = 0; line < lines; line++) + for (int line = 0; line < lines; line++) { memcpy((void*)&_image[_columns*line], (void*)&oldimg[oldcol*line],columns*sizeof(Character)); @@ -1628,15 +1649,15 @@ void TerminalDisplay::updateImageSize() showResizeNotification(); emit changedContentSizeSignal(_contentHeight, _contentWidth); // expose resizeEvent } - + _resizing = false; } -//showEvent and hideEvent are reimplemented here so that it appears to other classes that the +//showEvent and hideEvent are reimplemented here so that it appears to other classes that the //display has been resized when the display is hidden or shown. // //TODO: Perhaps it would be better to have separate signals for show and hide instead of using -//the same signal as the one for a content size change +//the same signal as the one for a content size change void TerminalDisplay::showEvent(QShowEvent*) { emit changedContentSizeSignal(_contentHeight,_contentWidth); @@ -1654,13 +1675,13 @@ void TerminalDisplay::hideEvent(QHideEvent*) void TerminalDisplay::scrollBarPositionChanged(int) { - if ( !_screenWindow ) + if ( !_screenWindow ) return; _screenWindow->scrollTo( _scrollBar->value() ); // if the thumb has been moved to the bottom of the _scrollBar then set - // the display to automatically track new output, + // the display to automatically track new output, // that is, scroll down automatically // to how new _lines as they are added const bool atEndOfOutput = (_scrollBar->value() == _scrollBar->maximum()); @@ -1703,17 +1724,17 @@ void TerminalDisplay::scrollToEnd() void TerminalDisplay::setScrollBarPosition(ScrollBarPosition position) { - if (_scrollbarLocation == position) - return; - + if (_scrollbarLocation == position) + return; + if ( position == NoScrollBar ) _scrollBar->hide(); - else - _scrollBar->show(); + else + _scrollBar->show(); _topMargin = _leftMargin = 1; _scrollbarLocation = position; - + propagateSize(); update(); } @@ -1726,7 +1747,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } if ( !contentsRect().contains(ev->pos()) ) return; - + if ( !_screenWindow ) return; int charLine; @@ -1742,11 +1763,11 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) emit isBusySelecting(true); // Keep it steady... // Drag only when the Control key is hold bool selected = false; - + // The receiver of the testIsSelected() signal will adjust // 'selected' accordingly. //emit testIsSelected(pos.x(), pos.y(), selected); - + selected = _screenWindow->isSelected(pos.x(),pos.y()); if ((!_ctrlDrag || ev->modifiers() & Qt::ControlModifier) && selected ) { @@ -1769,7 +1790,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) pos.ry() += _scrollBar->value(); _iPntSel = _pntSel = pos; _actSel = 1; // left mouse button pressed but nothing selected yet. - + } else { @@ -1790,7 +1811,7 @@ void TerminalDisplay::mousePressEvent(QMouseEvent* ev) } else if ( ev->button() == Qt::RightButton ) { - if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) + if (_mouseMarks || (ev->modifiers() & Qt::ShiftModifier)) emit configureRequest(ev->pos()); else emit mouseSignal( 2, charColumn +1, charLine +1 +_scrollBar->value() -_scrollBar->maximum() , 0); @@ -1813,7 +1834,7 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) int charColumn = 0; int scrollBarWidth = (_scrollbarLocation == ScrollBarLeft) ? _scrollBar->width() : 0; - getCharacterPosition(ev->pos(),charLine,charColumn); + getCharacterPosition(ev->pos(),charLine,charColumn); // handle filters // change link hot-spot appearance on mouse-over @@ -1824,28 +1845,28 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) _mouseOverHotspotArea = QRegion(); QRect r; if (spot->startLine()==spot->endLine()) { - r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, + r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, spot->startLine()*_fontHeight, - spot->endColumn()*_fontWidth + scrollBarWidth, - (spot->endLine()+1)*_fontHeight - 1 ); + spot->endColumn()*_fontWidth + scrollBarWidth, + (spot->endLine()+1)*_fontHeight - 1 ); _mouseOverHotspotArea |= r; } else { r.setCoords( spot->startColumn()*_fontWidth + scrollBarWidth, spot->startLine()*_fontHeight, _columns*_fontWidth - 1 + scrollBarWidth, - (spot->startLine()+1)*_fontHeight ); + (spot->startLine()+1)*_fontHeight ); _mouseOverHotspotArea |= r; for ( int line = spot->startLine()+1 ; line < spot->endLine() ; line++ ) { - r.setCoords( 0*_fontWidth + scrollBarWidth, + r.setCoords( 0*_fontWidth + scrollBarWidth, line*_fontHeight, _columns*_fontWidth + scrollBarWidth, - (line+1)*_fontHeight ); + (line+1)*_fontHeight ); _mouseOverHotspotArea |= r; } - r.setCoords( 0*_fontWidth + scrollBarWidth, + r.setCoords( 0*_fontWidth + scrollBarWidth, spot->endLine()*_fontHeight, - spot->endColumn()*_fontWidth + scrollBarWidth, - (spot->endLine()+1)*_fontHeight ); + spot->endColumn()*_fontWidth + scrollBarWidth, + (spot->endLine()+1)*_fontHeight ); _mouseOverHotspotArea |= r; } // display tooltips when mousing over links @@ -1864,11 +1885,11 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // set hotspot area to an invalid rectangle _mouseOverHotspotArea = QRegion(); } - + // for auto-hiding the cursor, we need mouseTracking if (ev->buttons() == Qt::NoButton ) return; - // if the terminal is interested in mouse movements + // if the terminal is interested in mouse movements // then emit a mouse movement signal, unless the shift // key is being held down, which overrides this. if (!_mouseMarks && !(ev->modifiers() & Qt::ShiftModifier)) @@ -1881,16 +1902,16 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) if (ev->buttons() & Qt::RightButton) button = 2; - - emit mouseSignal( button, + + emit mouseSignal( button, charColumn + 1, charLine + 1 +_scrollBar->value() -_scrollBar->maximum(), 1 ); - + return; } - - if (dragInfo.state == diPending) + + if (dragInfo.state == diPending) { // we had a mouse down, but haven't confirmed a drag yet // if the mouse has moved sufficiently, we will confirm @@ -1898,17 +1919,17 @@ void TerminalDisplay::mouseMoveEvent(QMouseEvent* ev) // int distance = KGlobalSettings::dndEventDelay(); int distance = QApplication::startDragDistance(); if ( ev->x() > dragInfo.start.x() + distance || ev->x() < dragInfo.start.x() - distance || - ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) + ev->y() > dragInfo.start.y() + distance || ev->y() < dragInfo.start.y() - distance) { // we've left the drag square, we can start a real drag operation now emit isBusySelecting(false); // Ok.. we can breath again. - + _screenWindow->clearSelection(); doDrag(); } return; - } - else if (dragInfo.state == diDragging) + } + else if (dragInfo.state == diDragging) { // this isn't technically needed because mouseMoveEvent is suppressed during // Qt drag operations, replaced by dragMoveEvent @@ -1949,11 +1970,11 @@ void TerminalDisplay::extendSelection( const QPoint& position ) // Adjust position within text area bounds. QPoint oldpos = pos; - + pos.setX( qBound(textBounds.left(),pos.x(),textBounds.right()) ); pos.setY( qBound(textBounds.top(),pos.y(),textBounds.bottom()) ); - if ( oldpos.y() > textBounds.bottom() ) + if ( oldpos.y() > textBounds.bottom() ) { linesBeyondWidget = (oldpos.y()-textBounds.bottom()) / _fontHeight; _scrollBar->setValue(_scrollBar->value()+linesBeyondWidget+1); // scrollforward @@ -1993,7 +2014,7 @@ void TerminalDisplay::extendSelection( const QPoint& position ) i = loc(left.x(),left.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); - while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) + while ( ((left.x()>0) || (left.y()>0 && (_lineProperties[left.y()-1] & LINE_WRAPPED) )) && charClass(_image[i-1].character) == selClass ) { i--; if (left.x()>0) left.rx()--; else {left.rx()=_usedColumns-1; left.ry()--;} } } @@ -2003,7 +2024,7 @@ void TerminalDisplay::extendSelection( const QPoint& position ) i = loc(right.x(),right.y()); if (i>=0 && i<=_imageSize) { selClass = charClass(_image[i].character); - while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) + while( ((right.x()<_usedColumns-1) || (right.y()<_usedLines-1 && (_lineProperties[right.y()] & LINE_WRAPPED) )) && charClass(_image[i+1].character) == selClass ) { i++; if (right.x()<_usedColumns-1) right.rx()++; else {right.rx()=0; right.ry()++; } } } @@ -2077,7 +2098,7 @@ void TerminalDisplay::extendSelection( const QPoint& position ) selClass = charClass(_image[i-1].character); /* if (selClass == ' ') { - while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && + while ( right.x() < _usedColumns-1 && charClass(_image[i+1].character) == selClass && (right.y()<_usedLines-1) && !(_lineProperties[right.y()] & LINE_WRAPPED)) { i++; right.rx()++; } if (right.x() < _usedColumns-1) @@ -2142,7 +2163,7 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) if ( ev->button() == Qt::LeftButton) { - emit isBusySelecting(false); + emit isBusySelecting(false); if(dragInfo.state == diPending) { // We had a drag event pending but never confirmed. Kill selection @@ -2169,24 +2190,34 @@ void TerminalDisplay::mouseReleaseEvent(QMouseEvent* ev) } dragInfo.state = diNone; } - - - if ( !_mouseMarks && + + + if ( !_mouseMarks && ((ev->button() == Qt::RightButton && !(ev->modifiers() & Qt::ShiftModifier)) - || ev->button() == Qt::MidButton) ) + || ev->button() == Qt::MidButton) ) { - emit mouseSignal( 3, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + emit mouseSignal( 3, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } } void TerminalDisplay::getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const { - column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth; line = (widgetPoint.y()-contentsRect().top()-_topMargin) / _fontHeight; + if ( _fixedFont ) + column = (widgetPoint.x() + _fontWidth/2 -contentsRect().left()-_leftMargin) / _fontWidth; + else + { + int x = contentsRect().left() + widgetPoint.x() - _fontWidth/2; + column = 0; + + while(x > textWidth(0, column, line)) + column++; + } + if ( line < 0 ) line = 0; if ( column < 0 ) @@ -2214,10 +2245,10 @@ void TerminalDisplay::updateFilters() void TerminalDisplay::updateLineProperties() { - if ( !_screenWindow ) + if ( !_screenWindow ) return; - _lineProperties = _screenWindow->getLineProperties(); + _lineProperties = _screenWindow->getLineProperties(); } void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) @@ -2237,8 +2268,8 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { // Send just _ONE_ click event, since the first click of the double click // was already sent by the click handler - emit mouseSignal( 0, - pos.x()+1, + emit mouseSignal( 0, + pos.x()+1, pos.y()+1 +_scrollBar->value() -_scrollBar->maximum(), 0 ); // left button return; @@ -2258,17 +2289,17 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) { // find the start of the word int x = bgnSel.x(); - while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) + while ( ((x>0) || (bgnSel.y()>0 && (_lineProperties[bgnSel.y()-1] & LINE_WRAPPED) )) && charClass(_image[i-1].character) == selClass ) - { - i--; - if (x>0) - x--; - else + { + i--; + if (x>0) + x--; + else { - x=_usedColumns-1; + x=_usedColumns-1; bgnSel.ry()--; - } + } } bgnSel.setX(x); @@ -2277,17 +2308,17 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) // find the end of the word i = loc( endSel.x(), endSel.y() ); x = endSel.x(); - while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) + while( ((x<_usedColumns-1) || (endSel.y()<_usedLines-1 && (_lineProperties[endSel.y()] & LINE_WRAPPED) )) && charClass(_image[i+1].character) == selClass ) - { - i++; - if (x<_usedColumns-1) - x++; - else - { - x=0; - endSel.ry()++; - } + { + i++; + if (x<_usedColumns-1) + x++; + else + { + x=0; + endSel.ry()++; + } } endSel.setX(x); @@ -2298,10 +2329,10 @@ void TerminalDisplay::mouseDoubleClickEvent(QMouseEvent* ev) _actSel = 2; // within selection - + _screenWindow->setSelectionEnd( endSel.x() , endSel.y() ); - - setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); + + setSelection( _screenWindow->selectedText(_preserveLineBreaks) ); } _possibleTripleClick=true; @@ -2327,7 +2358,7 @@ void TerminalDisplay::wheelEvent( QWheelEvent* ev ) else { // assume that each Up / Down key event will cause the terminal application - // to scroll by one line. + // to scroll by one line. // // to get a reasonable scrolling speed, scroll by one line for every 5 degrees // of mouse wheel rotation. Mouse wheels typically move in steps of 15 degrees, @@ -2347,14 +2378,14 @@ void TerminalDisplay::wheelEvent( QWheelEvent* ev ) else { // terminal program wants notification of mouse activity - + int charLine; int charColumn; getCharacterPosition( ev->pos() , charLine , charColumn ); - - emit mouseSignal( ev->delta() > 0 ? 4 : 5, - charColumn + 1, - charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , + + emit mouseSignal( ev->delta() > 0 ? 4 : 5, + charColumn + 1, + charLine + 1 +_scrollBar->value() -_scrollBar->maximum() , 0); } } @@ -2383,26 +2414,26 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) while (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) _iPntSel.ry()--; - + if (_tripleClickMode == SelectForwardsFromCursor) { // find word boundary start int i = loc(_iPntSel.x(),_iPntSel.y()); QChar selClass = charClass(_image[i].character); int x = _iPntSel.x(); - - while ( ((x>0) || + + while ( ((x>0) || (_iPntSel.y()>0 && (_lineProperties[_iPntSel.y()-1] & LINE_WRAPPED) ) - ) + ) && charClass(_image[i-1].character) == selClass ) { - i--; - if (x>0) - x--; - else + i--; + if (x>0) + x--; + else { - x=_columns-1; + x=_columns-1; _iPntSel.ry()--; - } + } } _screenWindow->setSelectionStart( x , _iPntSel.y() , false ); @@ -2415,7 +2446,7 @@ void TerminalDisplay::mouseTripleClickEvent(QMouseEvent* ev) while (_iPntSel.y()<_lines-1 && (_lineProperties[_iPntSel.y()] & LINE_WRAPPED) ) _iPntSel.ry()++; - + _screenWindow->setSelectionEnd( _columns - 1 , _iPntSel.y() ); setSelection(_screenWindow->selectedText(_preserveLineBreaks)); @@ -2450,8 +2481,11 @@ void TerminalDisplay::setWordCharacters(const QString& wc) void TerminalDisplay::setUsesMouse(bool on) { - _mouseMarks = on; - setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + if (_mouseMarks != on) { + _mouseMarks = on; + setCursor( _mouseMarks ? Qt::IBeamCursor : Qt::ArrowCursor ); + emit usesMouseChanged(); + } } bool TerminalDisplay::usesMouse() const { @@ -2468,7 +2502,7 @@ bool TerminalDisplay::usesMouse() const void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) { - if ( !_screenWindow ) + if ( !_screenWindow ) return; // Paste Clipboard by simulating keypress events @@ -2481,7 +2515,7 @@ void TerminalDisplay::emitSelection(bool useXselection,bool appendReturn) text.replace('\n', '\r'); QKeyEvent e(QEvent::KeyPress, 0, Qt::NoModifier, text); emit keyPressedSignal(&e); // expose as a big fat keypress event - + _screenWindow->clearSelection(); } } @@ -2520,8 +2554,8 @@ void TerminalDisplay::pasteSelection() void TerminalDisplay::setFlowControlWarningEnabled( bool enable ) { _flowControlWarningEnabled = enable; - - // if the dialog is currently visible and the flow control warning has + + // if the dialog is currently visible and the flow control warning has // been disabled then hide the dialog if (!enable) outputSuspended(false); @@ -2576,7 +2610,7 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) if ( update ) { _screenWindow->setTrackOutput( _screenWindow->atEndOfOutput() ); - + updateLineProperties(); updateImage(); @@ -2588,7 +2622,7 @@ void TerminalDisplay::keyPressEvent( QKeyEvent* event ) _actSel=0; // Key stroke implies a screen update, so TerminalDisplay won't // know where the current selection is. - if (_hasBlinkingCursor) + if (_hasBlinkingCursor) { _blinkCursorTimer->start(QApplication::cursorFlashTime() / 2); if (_cursorBlinking) @@ -2633,13 +2667,13 @@ void TerminalDisplay::inputMethodEvent( QInputMethodEvent* event ) _inputMethodData.preeditString = event->preeditString(); update(preeditRect() | _inputMethodData.previousPreeditRect); - + event->accept(); } QVariant TerminalDisplay::inputMethodQuery( Qt::InputMethodQuery query ) const { const QPoint cursorPos = _screenWindow ? _screenWindow->cursorPosition() : QPoint(0,0); - switch ( query ) + switch ( query ) { case Qt::ImMicroFocus: return imageToWidget(QRect(cursorPos.x(),cursorPos.y(),1,1)); @@ -2677,10 +2711,10 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) { int modifiers = keyEvent->modifiers(); - // When a possible shortcut combination is pressed, + // When a possible shortcut combination is pressed, // emit the overrideShortcutCheck() signal to allow the host // to decide whether the terminal should override it or not. - if (modifiers != Qt::NoModifier) + if (modifiers != Qt::NoModifier) { int modifierCount = 0; unsigned int currentModifier = Qt::ShiftModifier; @@ -2691,7 +2725,7 @@ bool TerminalDisplay::handleShortcutOverrideEvent(QKeyEvent* keyEvent) modifierCount++; currentModifier <<= 1; } - if (modifierCount < 2) + if (modifierCount < 2) { bool override = false; emit overrideShortcutCheck(keyEvent,override); @@ -2738,7 +2772,7 @@ bool TerminalDisplay::event(QEvent* event) default: break; } - return eventHandled ? true : QWidget::event(event); + return eventHandled ? true : QWidget::event(event); } void TerminalDisplay::setBellMode(int mode) @@ -2755,23 +2789,23 @@ void TerminalDisplay::bell(const QString& message) { if (_bellMode==NoBell) return; - //limit the rate at which bells can occur - //...mainly for sound effects where rapid bells in sequence + //limit the rate at which bells can occur + //...mainly for sound effects where rapid bells in sequence //produce a horrible noise if ( _allowBell ) { _allowBell = false; QTimer::singleShot(500,this,SLOT(enableBell())); - - if (_bellMode==SystemBeepBell) + + if (_bellMode==SystemBeepBell) { QApplication::beep(); - } - else if (_bellMode==NotifyBell) + } + else if (_bellMode==NotifyBell) { emit notifyBell(message); - } - else if (_bellMode==VisualBell) + } + else if (_bellMode==VisualBell) { swapColorTable(); QTimer::singleShot(200,this,SLOT(swapColorTable())); @@ -2830,13 +2864,13 @@ void TerminalDisplay::calcGeometry() _topMargin = DEFAULT_TOP_MARGIN; _contentHeight = contentsRect().height() - 2 * DEFAULT_TOP_MARGIN + /* mysterious */ 1; - + if (!_isFixedSize) { // ensure that display is always at least one column wide _columns = qMax(1,_contentWidth / _fontWidth); _usedColumns = qMin(_usedColumns,_columns); - + // ensure that display is always at least one line high _lines = qMax(1,_contentHeight / _fontHeight); _usedLines = qMin(_usedLines,_lines); @@ -2847,13 +2881,13 @@ void TerminalDisplay::makeImage() { calcGeometry(); - // confirm that array will be of non-zero size, since the painting code + // confirm that array will be of non-zero size, since the painting code // assumes a non-zero array length Q_ASSERT( _lines > 0 && _columns > 0 ); Q_ASSERT( _usedLines <= _lines && _usedColumns <= _columns ); _imageSize=_lines*_columns; - + // We over-commit one character so that we can be more relaxed in dealing with // certain boundary conditions: _image[_imageSize] is a valid but unused position _image = new Character[_imageSize+1]; @@ -2881,7 +2915,7 @@ void TerminalDisplay::setSize(int columns, int lines) void TerminalDisplay::setFixedSize(int cols, int lins) { _isFixedSize = true; - + //ensure that display is at least one line by one column in size _columns = qMax(1,cols); _lines = qMax(1,lins); @@ -2913,7 +2947,7 @@ void TerminalDisplay::dragEnterEvent(QDragEnterEvent* event) { if (event->mimeData()->hasFormat("text/plain")) event->acceptProposedAction(); - if (event->mimeData()->urls().count()); + if (event->mimeData()->urls().count()) event->acceptProposedAction(); } @@ -2923,11 +2957,11 @@ void TerminalDisplay::dropEvent(QDropEvent* event) QList urls = event->mimeData()->urls(); QString dropText; - if (!urls.isEmpty()) + if (!urls.isEmpty()) { // TODO/FIXME: escape or quote pasted things if neccessary... qDebug() << "TerminalDisplay: handling urls. It can be broken. Report any errors, please"; - for ( int i = 0 ; i < urls.count() ; i++ ) + for ( int i = 0 ; i < urls.count() ; i++ ) { //KUrl url = KIO::NetAccess::mostLocalUrl( urls[i] , 0 ); QUrl url = urls[i]; @@ -2935,21 +2969,21 @@ void TerminalDisplay::dropEvent(QDropEvent* event) QString urlText; if (url.isLocalFile()) - urlText = url.path(); + urlText = url.path(); else urlText = url.toString(); - + // in future it may be useful to be able to insert file names with drag-and-drop - // without quoting them (this only affects paths with spaces in) + // without quoting them (this only affects paths with spaces in) //urlText = KShell::quoteArg(urlText); - + dropText += urlText; - if ( i != urls.count()-1 ) + if ( i != urls.count()-1 ) dropText += ' '; } } - else + else { dropText = event->mimeData()->text(); } @@ -2974,7 +3008,7 @@ void TerminalDisplay::outputSuspended(bool suspended) if (!_outputSuspendedLabel) { //This label includes a link to an English language website - //describing the 'flow control' (Xon/Xoff) feature found in almost + //describing the 'flow control' (Xon/Xoff) feature found in almost //all terminal emulators. //If there isn't a suitable article available in the target language the link //can simply be removed. @@ -2993,12 +3027,12 @@ void TerminalDisplay::outputSuspended(bool suspended) _outputSuspendedLabel->setContentsMargins(5, 5, 5, 5); //enable activation of "Xon/Xoff" link in label - _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | + _outputSuspendedLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse | Qt::LinksAccessibleByKeyboard); _outputSuspendedLabel->setOpenExternalLinks(true); _outputSuspendedLabel->setVisible(false); - _gridLayout->addWidget(_outputSuspendedLabel); + _gridLayout->addWidget(_outputSuspendedLabel); _gridLayout->addItem( new QSpacerItem(0,0,QSizePolicy::Expanding, QSizePolicy::Expanding), 1,0); @@ -3036,7 +3070,7 @@ void AutoScrollHandler::timerEvent(QTimerEvent* event) Qt::LeftButton, Qt::NoModifier); - QApplication::sendEvent(widget(),&mouseEvent); + QApplication::sendEvent(widget(),&mouseEvent); } bool AutoScrollHandler::eventFilter(QObject* watched,QEvent* event) { diff --git a/lib/TerminalDisplay.h b/lib/TerminalDisplay.h index c32d799..cf4e4bb 100644 --- a/lib/TerminalDisplay.h +++ b/lib/TerminalDisplay.h @@ -70,7 +70,7 @@ class ScreenWindow; * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity * to the terminal. * - * When the terminal emulation receives new output from the program running in the terminal, + * When the terminal emulation receives new output from the program running in the terminal, * it will update the display by calling updateImage(). * * TODO More documentation @@ -102,25 +102,25 @@ public: /** Sets the opacity of the terminal display. */ void setOpacity(qreal opacity); - /** + /** * This enum describes the location where the scroll bar is positioned in the display widget. */ - enum ScrollBarPosition - { + enum ScrollBarPosition + { /** Do not show the scroll bar. */ - NoScrollBar=0, + NoScrollBar=0, /** Show the scroll bar on the left side of the display. */ - ScrollBarLeft=1, + ScrollBarLeft=1, /** Show the scroll bar on the right side of the display. */ - ScrollBarRight=2 + ScrollBarRight=2 }; - /** + /** * Specifies whether the terminal display has a vertical scroll bar, and if so whether it * is shown on the left or right side of the display. */ void setScrollBarPosition(ScrollBarPosition position); - /** + /** * Sets the current position and range of the display's scroll bar. * * @param cursor The position of the scroll bar's thumb. @@ -133,7 +133,7 @@ public: */ void scrollToEnd(); - /** + /** * Returns the display's filter chain. When the image for the display is updated, * the text is passed through each filter in the chain. Each filter can define * hotspots which correspond to certain strings (such as URLs or particular words). @@ -146,11 +146,11 @@ public: */ FilterChain* filterChain() const; - /** + /** * Updates the filters in the display's filter chain. This will cause * the hotspots to be updated to match the current image. * - * WARNING: This function can be expensive depending on the + * WARNING: This function can be expensive depending on the * image size and number of filters in the filterChain() * * TODO - This API does not really allow efficient usage. Revise it so @@ -159,10 +159,10 @@ public: * eg: * - Area of interest may be known ( eg. mouse cursor hovering * over an area ) - */ + */ void processFilters(); - /** + /** * Returns a list of menu actions created by the filters for the content * at the given @p position. */ @@ -179,9 +179,9 @@ public: void setCtrlDrag(bool enable) { _ctrlDrag=enable; } bool ctrlDrag() { return _ctrlDrag; } - /** + /** * This enum describes the methods for selecting text when - * the user triple-clicks within the display. + * the user triple-clicks within the display. */ enum TripleClickMode { @@ -190,7 +190,7 @@ public: /** Select from the current cursor position to the end of the line. */ SelectForwardsFromCursor }; - /** Sets how the text is selected when the user triple clicks within the display. */ + /** Sets how the text is selected when the user triple clicks within the display. */ void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; } /** See setTripleClickSelectionMode() */ TripleClickMode tripleClickMode() { return _tripleClickMode; } @@ -208,22 +208,22 @@ public: { /** A rectangular block which covers the entire area of the cursor character. */ BlockCursor, - /** + /** * A single flat line which occupies the space at the bottom of the cursor * character's area. */ UnderlineCursor, - /** - * An cursor shaped like the capital letter 'I', similar to the IBeam + /** + * An cursor shaped like the capital letter 'I', similar to the IBeam * cursor used in Qt/KDE text editors. */ IBeamCursor }; - /** - * Sets the shape of the keyboard cursor. This is the cursor drawn + /** + * Sets the shape of the keyboard cursor. This is the cursor drawn * at the position in the terminal where keyboard input will appear. * - * In addition the terminal display widget also has a cursor for + * In addition the terminal display widget also has a cursor for * the mouse pointer, which can be set using the QWidget::setCursor() * method. * @@ -236,7 +236,7 @@ public: KeyboardCursorShape keyboardCursorShape() const; /** - * Sets the color used to draw the keyboard cursor. + * Sets the color used to draw the keyboard cursor. * * The keyboard cursor defaults to using the foreground color of the character * underneath it. @@ -250,10 +250,10 @@ public: */ void setKeyboardCursorColor(bool useForegroundColor , const QColor& color); - /** + /** * Returns the color of the keyboard cursor, or an invalid color if the keyboard * cursor color is set to change according to the foreground color of the character - * underneath it. + * underneath it. */ QColor keyboardCursorColor() const; @@ -278,19 +278,19 @@ public: */ int fontHeight() { return _fontHeight; } /** - * Returns the width of the characters in the display. + * Returns the width of the characters in the display. * This assumes the use of a fixed-width font. */ int fontWidth() { return _fontWidth; } void setSize(int cols, int lins); void setFixedSize(int cols, int lins); - + // reimplemented QSize sizeHint() const; /** - * Sets which characters, in addition to letters and numbers, + * Sets which characters, in addition to letters and numbers, * are regarded as being part of a word for the purposes * of selecting words in the display by double clicking on them. * @@ -301,26 +301,26 @@ public: * of a word ( in addition to letters and numbers ). */ void setWordCharacters(const QString& wc); - /** - * Returns the characters which are considered part of a word for the + /** + * Returns the characters which are considered part of a word for the * purpose of selecting words in the display with the mouse. * * @see setWordCharacters() */ QString wordCharacters() { return _wordCharacters; } - /** - * Sets the type of effect used to alert the user when a 'bell' occurs in the + /** + * Sets the type of effect used to alert the user when a 'bell' occurs in the * terminal session. * * The terminal session can trigger the bell effect by calling bell() with * the alert message. */ void setBellMode(int mode); - /** + /** * Returns the type of effect used to alert the user when a 'bell' occurs in * the terminal session. - * + * * See setBellMode() */ int bellMode() { return _bellMode; } @@ -331,23 +331,23 @@ public: * session. */ enum BellMode - { + { /** A system beep. */ - SystemBeepBell=0, - /** + SystemBeepBell=0, + /** * KDE notification. This may play a sound, show a passive popup * or perform some other action depending on the user's settings. */ - NotifyBell=1, + NotifyBell=1, /** A silent, visual bell (eg. inverting the display's colors briefly) */ - VisualBell=2, + VisualBell=2, /** No bell effects */ - NoBell=3 + NoBell=3 }; void setSelection(const QString &t); - /** + /** * Reimplemented. Has no effect. Use setVTFont() to change the font * used to draw characters in the display. */ @@ -356,9 +356,9 @@ public: /** Returns the font used to draw characters in the display */ QFont getVTFont() { return font(); } - /** + /** * Sets the font used to draw the display. Has no effect if @p font - * is larger than the size of the display itself. + * is larger than the size of the display itself. */ void setVTFont(const QFont& font); @@ -367,7 +367,7 @@ public: * is enabled or not. Defaults to enabled. */ static void setAntialias( bool antialias ) { _antialiasText = antialias; } - /** + /** * Returns true if anti-aliasing of text in the terminal is enabled. */ static bool antialias() { return _antialiasText; } @@ -381,20 +381,20 @@ public: * Returns true if characters with intense colors are rendered in bold. */ bool getBoldIntense() { return _boldIntense; } - + /** - * Sets whether or not the current height and width of the + * Sets whether or not the current height and width of the * terminal in lines and columns is displayed whilst the widget * is being resized. */ void setTerminalSizeHint(bool on) { _terminalSizeHint=on; } - /** + /** * Returns whether or not the current height and width of * the terminal in lines and columns is displayed whilst the widget * is being resized. */ bool terminalSizeHint() { return _terminalSizeHint; } - /** + /** * Sets whether the terminal size display is shown briefly * after the widget is first shown. * @@ -425,36 +425,36 @@ public: ScreenWindow* screenWindow() const; static bool HAVE_TRANSPARENCY; - + void setMotionAfterPasting(MotionAfterPasting action); int motionAfterPasting(); // maps a point on the widget to the position ( ie. line and column ) // of the character at that point. void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; - + public slots: - /** + /** * Causes the terminal display to fetch the latest character image from the associated * terminal screen ( see setScreenWindow() ) and redraw the display. */ - void updateImage(); + void updateImage(); /** Essentially calles processFilters(). */ void updateFilters(); /** - * Causes the terminal display to fetch the latest line status flags from the - * associated terminal screen ( see setScreenWindow() ). - */ + * Causes the terminal display to fetch the latest line status flags from the + * associated terminal screen ( see setScreenWindow() ). + */ void updateLineProperties(); /** Copies the selected text to the clipboard. */ void copyClipboard(); - /** - * Pastes the content of the clipboard into the + /** + * Pastes the content of the clipboard into the * display. */ void pasteClipboard(); @@ -464,26 +464,26 @@ public slots: */ void pasteSelection(); - /** + /** * Changes whether the flow control warning box should be shown when the flow control * stop key (Ctrl+S) are pressed. */ void setFlowControlWarningEnabled(bool enabled); - /** - * Returns true if the flow control warning box is enabled. + /** + * Returns true if the flow control warning box is enabled. * See outputSuspended() and setFlowControlWarningEnabled() */ bool flowControlWarningEnabled() const { return _flowControlWarningEnabled; } - /** + /** * Causes the widget to display or hide a message informing the user that terminal * output has been suspended (by using the flow control key combination Ctrl+S) * * @param suspended True if terminal output has been suspended and the warning message should * be shown or false to indicate that terminal output has been resumed and that * the warning message should disappear. - */ + */ void outputSuspended(bool suspended); /** @@ -493,7 +493,7 @@ public slots: * If this is set to true, mouse signals will be emitted by the view when the user clicks, drags * or otherwise moves the mouse inside the view. * The user interaction needed to create selections will also change, and the user will be required - * to hold down the shift key to create a selection or perform other mouse activities inside the + * to hold down the shift key to create a selection or perform other mouse activities inside the * view area - since the program running in the terminal is being allowed to handle normal mouse * events itself. * @@ -501,28 +501,28 @@ public slots: * or false otherwise. */ void setUsesMouse(bool usesMouse); - + /** See setUsesMouse() */ bool usesMouse() const; - /** + /** * Shows a notification that a bell event has occurred in the terminal. * TODO: More documentation here */ void bell(const QString& message); - /** - * Sets the background of the display to the specified color. - * @see setColorTable(), setForegroundColor() + /** + * Sets the background of the display to the specified color. + * @see setColorTable(), setForegroundColor() */ void setBackgroundColor(const QColor& color); - /** - * Sets the text of the display to the specified color. + /** + * Sets the text of the display to the specified color. * @see setColorTable(), setBackgroundColor() */ void setForegroundColor(const QColor& color); - + void selectionChanged(); signals: @@ -532,7 +532,7 @@ signals: */ void keyPressedSignal(QKeyEvent *e); - /** + /** * A mouse event occurred. * @param button The mouse button (0 for left button, 1 for middle button, 2 for right button, 3 for release) * @param column The character column where the event occurred @@ -543,7 +543,7 @@ signals: void changedFontMetricSignal(int height, int width); void changedContentSizeSignal(int height, int width); - /** + /** * Emitted when the user right clicks on the display, or right-clicks with the Shift * key held down if usesMouse() is true. * @@ -552,9 +552,9 @@ signals: void configureRequest(const QPoint& position); /** - * When a shortcut which is also a valid terminal key sequence is pressed while - * the terminal widget has focus, this signal is emitted to allow the host to decide - * whether the shortcut should be overridden. + * When a shortcut which is also a valid terminal key sequence is pressed while + * the terminal widget has focus, this signal is emitted to allow the host to decide + * whether the shortcut should be overridden. * When the shortcut is overridden, the key sequence will be sent to the terminal emulation instead * and the action associated with the shortcut will not be triggered. * @@ -564,13 +564,14 @@ signals: void isBusySelecting(bool); void sendStringToEmu(const char*); - + // qtermwidget signals void copyAvailable(bool); void termGetFocus(); void termLostFocus(); void notifyBell(const QString&); + void usesMouseChanged(); protected: virtual bool event( QEvent * ); @@ -593,7 +594,7 @@ protected: virtual void wheelEvent( QWheelEvent* ); virtual bool focusNextPrevChild( bool next ); - + // drag and drop virtual void dragEnterEvent(QDragEnterEvent* event); virtual void dropEvent(QDropEvent* event); @@ -609,7 +610,7 @@ protected: // classifies the 'ch' into one of three categories // and returns a character to indicate which category it is in // - // - A space (returns ' ') + // - A space (returns ' ') // - Part of a word (returns 'a') // - Other characters (returns the input character) QChar charClass(QChar ch) const; @@ -627,7 +628,7 @@ protected slots: void scrollBarPositionChanged(int value); void blinkEvent(); void blinkCursorEvent(); - + //Renables bell noises and visuals. Used to disable further bells for a short period of time //after emitting the first in a sequence of bell events. void enableBell(); @@ -641,14 +642,19 @@ private: // -- Drawing helpers -- + // determine the width of this text + int textWidth(int startColumn, int length, int line) const; + // determine the area that encloses this series of characters + QRect calculateTextArea(int topLeftX, int topLeftY, int startColumn, int line, int length); + // divides the part of the display specified by 'rect' into // fragments according to their colors and styles and calls - // drawTextFragment() to draw the fragments + // drawTextFragment() to draw the fragments void drawContents(QPainter &paint, const QRect &rect); // draws a section of text, all the text in this section // has a common color and style - void drawTextFragment(QPainter& painter, const QRect& rect, - const QString& text, const Character* style); + void drawTextFragment(QPainter& painter, const QRect& rect, + const QString& text, const Character* style); // draws the background for a text fragment // if useOpacitySetting is true then the color's alpha value will be set to // the display's transparency (set with setOpacity()), otherwise the background @@ -656,13 +662,13 @@ private: void drawBackground(QPainter& painter, const QRect& rect, const QColor& color, bool useOpacitySetting); // draws the cursor character - void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, + void drawCursor(QPainter& painter, const QRect& rect , const QColor& foregroundColor, const QColor& backgroundColor , bool& invertColors); // draws the characters or line graphics in a text fragment - void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, + void drawCharacters(QPainter& painter, const QRect& rect, const QString& text, const Character* style, bool invertCharacterColor); // draws a string of line graphics - void drawLineCharString(QPainter& painter, int x, int y, + void drawLineCharString(QPainter& painter, int x, int y, const QString& str, const Character* attributes); // draws the preedit string for input methods @@ -670,7 +676,7 @@ private: // -- - // maps an area in the character image to an area on the widget + // maps an area in the character image to an area on the widget QRect imageToWidget(const QRect& imageArea) const; // the area where the preedit string for input methods will be draw @@ -680,8 +686,8 @@ private: // current size in columns and lines void showResizeNotification(); - // scrolls the image by a number of lines. - // 'lines' may be positive ( to scroll the image down ) + // scrolls the image by a number of lines. + // 'lines' may be positive ( to scroll the image down ) // or negative ( to scroll the image up ) // 'region' is the part of the image to scroll - currently only // the top, bottom and height of 'region' are taken into account, @@ -692,7 +698,7 @@ private: void propagateSize(); void updateImageSize(); void makeImage(); - + void paintFilters(QPainter& painter); // returns a region covering all of the areas of the widget which contain @@ -708,7 +714,7 @@ private: bool handleShortcutOverrideEvent(QKeyEvent* event); // the window onto the terminal screen which this display - // is currently showing. + // is currently showing. QPointer _screenWindow; bool _allowBell; @@ -726,7 +732,7 @@ private: int _lines; // the number of lines that can be displayed in the widget int _columns; // the number of columns that can be displayed in the widget - + int _usedLines; // the number of lines that are actually being used, this will be less // than 'lines' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed @@ -734,7 +740,7 @@ private: int _usedColumns; // the number of columns that are actually being used, this will be less // than 'columns' if the character image provided with setImage() is smaller // than the maximum image size which can be displayed - + int _contentHeight; int _contentWidth; Character* _image; // [lines][columns] @@ -793,14 +799,14 @@ private: //widgets related to the warning message that appears when the user presses Ctrl+S to suspend //terminal output - informing them what has happened and how to resume output - QLabel* _outputSuspendedLabel; - + QLabel* _outputSuspendedLabel; + uint _lineSpacing; bool _colorsInverted; // true during visual bell QSize _size; - + QRgb _blendColor; // list of filters currently applied to the display. used for links and @@ -812,7 +818,7 @@ private: // custom cursor color. if this is invalid then the foreground // color of the character under the cursor is used - QColor _cursorColor; + QColor _cursorColor; MotionAfterPasting mMotionAfterPasting; diff --git a/lib/Vt102Emulation.cpp b/lib/Vt102Emulation.cpp index cb92363..da2e223 100644 --- a/lib/Vt102Emulation.cpp +++ b/lib/Vt102Emulation.cpp @@ -1,6 +1,6 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -37,7 +37,7 @@ void scrolllock_set_on(); #endif -// Standard +// Standard #include #include #include @@ -58,7 +58,7 @@ using namespace Konsole; -Vt102Emulation::Vt102Emulation() +Vt102Emulation::Vt102Emulation() : Emulation(), _titleUpdateTimer(new QTimer(this)) { @@ -75,7 +75,7 @@ Vt102Emulation::~Vt102Emulation() void Vt102Emulation::clearEntireScreen() { _currentScreen->clearEntireScreen(); - bufferedUpdate(); + bufferedUpdate(); } void Vt102Emulation::reset() @@ -87,7 +87,7 @@ void Vt102Emulation::reset() resetCharset(1); _screen[1]->reset(); setCodec(LocaleCodec); - + bufferedUpdate(); } @@ -138,7 +138,7 @@ void Vt102Emulation::reset() - VT52 - VT52 escape codes - - 'Y'{Pc}{Pc} - - XTE_HA - Xterm window/terminal attribute commands + - XTE_HA - Xterm window/terminal attribute commands of the form `]' {Pn} `;' {Text} (Note that these are handled differently to the other formats) @@ -178,9 +178,9 @@ void Vt102Emulation::reset() void Vt102Emulation::resetTokenizer() { - tokenBufferPos = 0; - argc = 0; - argv[0] = 0; + tokenBufferPos = 0; + argc = 0; + argv[0] = 0; argv[1] = 0; } @@ -206,33 +206,33 @@ void Vt102Emulation::addToCurrentToken(int cc) #define CTL 1 // Control character #define CHR 2 // Printable character -#define CPN 4 // TODO: Document me +#define CPN 4 // TODO: Document me #define DIG 8 // Digit -#define SCS 16 // TODO: Document me +#define SCS 16 // TODO: Document me #define GRP 32 // TODO: Document me #define CPS 64 // Character which indicates end of window resize // escape sequence '\e[8;;t' void Vt102Emulation::initTokenizer() -{ - int i; +{ + int i; quint8* s; - for(i = 0;i < 256; ++i) + for(i = 0;i < 256; ++i) charClass[i] = 0; - for(i = 0;i < 32; ++i) + for(i = 0;i < 32; ++i) charClass[i] |= CTL; - for(i = 32;i < 256; ++i) + for(i = 32;i < 256; ++i) charClass[i] |= CHR; - for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s) + for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s) charClass[*s] |= CPN; // resize = \e[8;;t - for(s = (quint8*)"t"; *s; ++s) + for(s = (quint8*)"t"; *s; ++s) charClass[*s] |= CPS; - for(s = (quint8*)"0123456789"; *s; ++s) + for(s = (quint8*)"0123456789"; *s; ++s) charClass[*s] |= DIG; - for(s = (quint8*)"()+*%"; *s; ++s) + for(s = (quint8*)"()+*%"; *s; ++s) charClass[*s] |= SCS; - for(s = (quint8*)"()+*#[]%"; *s; ++s) + for(s = (quint8*)"()+*#[]%"; *s; ++s) charClass[*s] |= GRP; resetTokenizer(); @@ -249,10 +249,10 @@ void Vt102Emulation::initTokenizer() - 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 + - 'p' is the current position within the token buffer Note that they need to applied in proper order. */ @@ -275,31 +275,31 @@ void Vt102Emulation::initTokenizer() // process an incoming unicode character void Vt102Emulation::receiveChar(int cc) -{ - if (cc == 127) +{ + if (cc == 127) 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) + if (cc == CNTL('X') || cc == CNTL('Z') || cc == ESC) resetTokenizer(); //VT100: CAN or SUB - if (cc != ESC) - { - processToken(TY_CTL(cc+'@' ),0,0); - return; + if (cc != ESC) + { + processToken(TY_CTL(cc+'@' ),0,0); + return; } } // advance the state - addToCurrentToken(cc); + addToCurrentToken(cc); int* s = tokenBuffer; int p = tokenBufferPos; - if (getMode(MODE_Ansi)) + if (getMode(MODE_Ansi)) { if (lec(1,0,ESC)) { return; } if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); return; } @@ -316,11 +316,11 @@ void Vt102Emulation::receiveChar(int cc) 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 (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; } @@ -328,19 +328,19 @@ void Vt102Emulation::receiveChar(int cc) if (eec(';')) { addArgument(); return; } for (int i=0;i<=argc;i++) { - if (epp()) + if (epp()) processToken( TY_CSI_PR(cc,argv[i]), 0, 0); - else if (egt()) + 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]); @@ -350,29 +350,29 @@ void Vt102Emulation::receiveChar(int cc) } resetTokenizer(); } - else + else { // VT52 Mode - if (lec(1,0,ESC)) + if (lec(1,0,ESC)) + return; + if (les(1,0,CHR)) + { + processToken( TY_CHR(), s[0], 0); + resetTokenizer(); return; - if (les(1,0,CHR)) - { - processToken( TY_CHR(), s[0], 0); - resetTokenizer(); - return; } - if (lec(2,1,'Y')) + if (lec(2,1,'Y')) return; - if (lec(3,1,'Y')) + if (lec(3,1,'Y')) + return; + if (p < 4) + { + processToken( TY_VT52(s[1] ), 0, 0); + resetTokenizer(); return; - if (p < 4) - { - processToken( TY_VT52(s[1] ), 0, 0); - resetTokenizer(); - return; } - processToken( TY_VT52(s[1]), s[2], s[3]); - resetTokenizer(); + processToken( TY_VT52(s[1]), s[2], s[3]); + resetTokenizer(); return; } } @@ -382,24 +382,24 @@ void Vt102Emulation::processWindowAttributeChange() // See Session::UserTitleChange for possible values int attributeToChange = 0; int i; - for (i = 2; i < tokenBufferPos && - tokenBuffer[i] >= '0' && + for (i = 2; i < tokenBufferPos && + tokenBuffer[i] >= '0' && tokenBuffer[i] <= '9'; i++) { attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); } - if (tokenBuffer[i] != ';') - { - reportDecodingError(); - return; + if (tokenBuffer[i] != ';') + { + reportDecodingError(); + return; } - + QString newValue; newValue.reserve(tokenBufferPos-i-2); for (int j = 0; j < tokenBufferPos-i-2; j++) newValue[j] = tokenBuffer[i+1+j]; - + _pendingTitleUpdates[attributeToChange] = newValue; _titleUpdateTimer->start(20); } @@ -409,9 +409,9 @@ void Vt102Emulation::updateTitle() QListIterator iter( _pendingTitleUpdates.keys() ); while (iter.hasNext()) { int arg = iter.next(); - emit titleChanged( arg , _pendingTitleUpdates[arg] ); + emit titleChanged( arg , _pendingTitleUpdates[arg] ); } - _pendingTitleUpdates.clear(); + _pendingTitleUpdates.clear(); } // Interpreting Codes --------------------------------------------------------- @@ -512,11 +512,11 @@ void Vt102Emulation::processToken(int token, int p, int q) 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 */ + 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 */ + case TY_ESC_DE('4' ) : /* Double height line, bottom half */ _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); break; @@ -524,8 +524,8 @@ void Vt102Emulation::processToken(int token, int p, int q) _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); + 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; @@ -711,14 +711,14 @@ void Vt102Emulation::processToken(int token, int p, int q) // 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 + //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 @@ -781,17 +781,17 @@ void Vt102Emulation::processToken(int token, int p, int q) case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100 - default: - reportDecodingError(); + default: + reportDecodingError(); break; }; } void Vt102Emulation::clearScreenAndSetColumns(int columnCount) { - setImageSize(_currentScreen->getLines(),columnCount); + setImageSize(_currentScreen->getLines(),columnCount); clearEntireScreen(); - setDefaultMargins(); + setDefaultMargins(); _currentScreen->setCursorYX(0,0); } @@ -804,7 +804,7 @@ void Vt102Emulation::sendString(const char* s , int length) } void Vt102Emulation::reportCursorPosition() -{ +{ char tmp[20]; sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); sendString(tmp); @@ -835,7 +835,7 @@ void Vt102Emulation::reportSecondaryAttributes() void Vt102Emulation::reportTerminalParms(int p) // DECREPTPARM -{ +{ char tmp[100]; sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. sendString(tmp); @@ -865,13 +865,13 @@ void Vt102Emulation::reportAnswerBack() */ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) -{ - if (cx < 1 || cy < 1) +{ + if (cx < 1 || cy < 1) return; // normal buttons are passed as 0x20 + button, // mouse wheel (buttons 4,5) as 0x5c + button - if (cb >= 4) + if (cb >= 4) cb += 0x3c; //Mouse motion handling @@ -885,11 +885,11 @@ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) void Vt102Emulation::sendText( const QString& text ) { - if (!text.isEmpty()) + if (!text.isEmpty()) { - QKeyEvent event(QEvent::KeyPress, - 0, - Qt::NoModifier, + QKeyEvent event(QEvent::KeyPress, + 0, + Qt::NoModifier, text); sendKeyEvent(&event); // expose as a big fat keypress event } @@ -904,7 +904,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) 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)) + if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) states |= KeyboardTranslator::ApplicationKeypadState; // check flow control state @@ -919,8 +919,8 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // lookup key binding if ( _keyTranslator ) { - KeyboardTranslator::Entry entry = _keyTranslator->findEntry( - event->key() , + KeyboardTranslator::Entry entry = _keyTranslator->findEntry( + event->key() , modifiers, states ); @@ -932,10 +932,10 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // (unless there is an entry defined for this particular combination // in the keyboard modifier) bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; - bool wantsAnyModifier = entry.state() & + bool wantsAnyModifier = entry.state() & entry.stateMask() & KeyboardTranslator::AnyModifierState; - if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) + if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) && !event->text().isEmpty() ) { textToSend.prepend("\033"); @@ -948,7 +948,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // TODO command handling } - else if ( !entry.text().isEmpty() ) + else if ( !entry.text().isEmpty() ) { textToSend += _codec->fromUnicode(entry.text(true,modifiers)); } @@ -976,7 +976,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // set QString translatorError = tr("No keyboard translator available. " "The information needed to convert key presses " - "into characters to send to the terminal " + "into characters to send to the terminal " "is missing."); reset(); receiveData( translatorError.toUtf8().constData() , translatorError.count() ); @@ -991,7 +991,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) // 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. @@ -1002,7 +1002,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event ) in the pipeline. It only applies to tokens, which represent plain characters. - This conversion it eventually continued in TerminalDisplay.C, since + 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. */ @@ -1137,7 +1137,7 @@ void Vt102Emulation::setMode(int m) case MODE_Mouse1001: case MODE_Mouse1002: case MODE_Mouse1003: - emit programUsesMouseChanged(false); + emit programUsesMouseChanged(false); break; case MODE_AppScreen : _screen[1]->clearSelection(); @@ -1160,14 +1160,14 @@ void Vt102Emulation::resetMode(int m) if (getMode(MODE_Allow132Columns)) clearScreenAndSetColumns(80); break; - case MODE_Mouse1000 : + case MODE_Mouse1000 : case MODE_Mouse1001 : case MODE_Mouse1002 : case MODE_Mouse1003 : - emit programUsesMouseChanged(true); + emit programUsesMouseChanged(true); break; - case MODE_AppScreen : + case MODE_AppScreen : _screen[0]->clearSelection(); setScreen(0); break; @@ -1186,9 +1186,9 @@ void Vt102Emulation::saveMode(int m) void Vt102Emulation::restoreMode(int m) { - if (_savedModes.mode[m]) - setMode(m); - else + if (_savedModes.mode[m]) + setMode(m); + else resetMode(m); } @@ -1226,10 +1226,10 @@ static void hexdump(int* s, int len) void Vt102Emulation::reportDecodingError() { - if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) + if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) return; - printf("Undecodable sequence: "); - hexdump(tokenBuffer,tokenBufferPos); + printf("Undecodable sequence: "); + hexdump(tokenBuffer,tokenBufferPos); printf("\n"); } diff --git a/lib/Vt102Emulation.h b/lib/Vt102Emulation.h index 504d941..802cfc5 100644 --- a/lib/Vt102Emulation.h +++ b/lib/Vt102Emulation.h @@ -1,6 +1,6 @@ /* This file is part of Konsole, an X terminal. - + Copyright 2007-2008 by Robert Knight Copyright 1997,1998 by Lars Doelle @@ -26,7 +26,7 @@ // Standard Library #include -// Qt +// Qt #include #include #include @@ -37,12 +37,12 @@ #define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 #define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) -#define MODE_AppKeyPad (MODES_SCREEN+2) // +#define MODE_AppKeyPad (MODES_SCREEN+2) // #define MODE_Mouse1000 (MODES_SCREEN+3) // Send mouse X,Y position on press and release #define MODE_Mouse1001 (MODES_SCREEN+4) // Use Hilight mouse tracking #define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion mouse tracking -#define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking -#define MODE_Ansi (MODES_SCREEN+7) // Use US Ascii for character sets G0-G3 (DECANM) +#define MODE_Mouse1003 (MODES_SCREEN+6) // Use all motion mouse tracking +#define MODE_Ansi (MODES_SCREEN+7) // Use US Ascii for character sets G0-G3 (DECANM) #define MODE_132Columns (MODES_SCREEN+8) // 80 <-> 132 column mode switch (DECCOLM) #define MODE_Allow132Columns (MODES_SCREEN+9) // Allow DECCOLM mode #define MODE_total (MODES_SCREEN+10) @@ -64,40 +64,40 @@ struct CharCodes /** * Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * A full description of this terminal can be found at http://vt100.net/docs/vt102-ug/ - * - * In addition, various additional xterm escape sequences are supported to provide + * + * In addition, various additional xterm escape sequences are supported to provide * features such as mouse input handling. * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape - * sequences. + * sequences. * */ class Vt102Emulation : public Emulation -{ +{ Q_OBJECT public: /** Constructs a new emulation */ Vt102Emulation(); ~Vt102Emulation(); - + // reimplemented from Emulation virtual void clearEntireScreen(); virtual void reset(); virtual char eraseChar() const; - -public slots: - // reimplemented from Emulation + +public slots: + // reimplemented from Emulation virtual void sendString(const char*,int length = -1); virtual void sendText(const QString& text); virtual void sendKeyEvent(QKeyEvent*); virtual void sendMouseEvent(int buttons, int column, int line, int eventType); - + protected: // reimplemented from Emulation virtual void setMode(int mode); virtual void resetMode(int mode); virtual void receiveChar(int cc); - + private slots: //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates //used to buffer multiple title updates @@ -120,7 +120,7 @@ private: bool getMode (int mode); // saves the current boolean value of 'mode' void saveMode (int mode); - // restores the boolean value of 'mode' + // restores the boolean value of 'mode' void restoreMode(int mode); // resets all modes // (except MODE_Allow132Columns) @@ -143,7 +143,7 @@ private: // for the purposes of decoding terminal output int charClass[256]; - void reportDecodingError(); + void reportDecodingError(); void processToken(int code, int p, int q); void processWindowAttributeChange(); @@ -177,10 +177,10 @@ private: TerminalState _currentModes; TerminalState _savedModes; - //hash table and timer for buffering calls to the session instance + //hash table and timer for buffering calls to the session instance //to update the name of the session //or window title. - //these calls occur when certain escape sequences are seen in the + //these calls occur when certain escape sequences are seen in the //output from the terminal QHash _pendingTitleUpdates; QTimer* _titleUpdateTimer; diff --git a/lib/kprocess.h b/lib/kprocess.h index 2d3bcca..babcc2a 100644 --- a/lib/kprocess.h +++ b/lib/kprocess.h @@ -38,7 +38,7 @@ class KProcessPrivate; /** * \class KProcess kprocess.h - * + * * Child process invocation, monitoring and control. * * This class extends QProcess by some useful functionality, overrides diff --git a/lib/qtermwidget.cpp b/lib/qtermwidget.cpp index dd8b867..9245a16 100644 --- a/lib/qtermwidget.cpp +++ b/lib/qtermwidget.cpp @@ -145,7 +145,7 @@ void QTermWidget::findPrevious() void QTermWidget::search(bool forwards, bool next) { int startColumn, startLine; - + if (next) // search from just after current selection { m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); @@ -155,15 +155,15 @@ void QTermWidget::search(bool forwards, bool next) { m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine); } - + qDebug() << "current selection starts at: " << startColumn << startLine; - qDebug() << "current cursor position: " << m_impl->m_terminalDisplay->screenWindow()->cursorPosition(); + qDebug() << "current cursor position: " << m_impl->m_terminalDisplay->screenWindow()->cursorPosition(); QRegExp regExp(m_searchBar->searchText()); regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString); regExp.setCaseSensitivity(m_searchBar->matchCase() ? Qt::CaseSensitive : Qt::CaseInsensitive); - HistorySearch *historySearch = + HistorySearch *historySearch = new HistorySearch(m_impl->m_session->emulation(), regExp, forwards, startColumn, startLine, this); connect(historySearch, SIGNAL(matchFound(int, int, int, int)), this, SLOT(matchFound(int, int, int, int))); connect(historySearch, SIGNAL(noMatchFound()), this, SLOT(noMatchFound())); @@ -183,7 +183,7 @@ void QTermWidget::matchFound(int startColumn, int startLine, int endColumn, int sw->setSelectionEnd(endColumn, endLine - sw->currentLine()); } -void QTermWidget::noMatchFound() +void QTermWidget::noMatchFound() { m_impl->m_terminalDisplay->screenWindow()->clearSelection(); } @@ -228,12 +228,24 @@ void QTermWidget::startShellProgram() m_impl->m_session->run(); } +void QTermWidget::startTerminalTeletype() +{ + if ( m_impl->m_session->isRunning() ) { + return; + } + + m_impl->m_session->runEmptyPTY(); + // redirect data from TTY to external recipient + connect( m_impl->m_session->emulation(), SIGNAL(sendData(const char *,int)), + this, SIGNAL(sendData(const char *,int)) ); +} + void QTermWidget::init(int startnow) { m_layout = new QVBoxLayout(); m_layout->setMargin(0); setLayout(m_layout); - + m_impl = new TermWidgetImpl(this); m_impl->m_terminalDisplay->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_layout->addWidget(m_impl->m_terminalDisplay); @@ -347,7 +359,7 @@ QString QTermWidget::workingDirectory() if (!d.exists()) { qDebug() << "Cannot find" << d.dirName(); - goto fallback; + goto fallback; } return d.canonicalPath(); #endif @@ -485,9 +497,9 @@ void QTermWidget::setZoom(int step) { if (!m_impl->m_terminalDisplay) return; - + QFont font = m_impl->m_terminalDisplay->getVTFont(); - + font.setPointSize(font.pointSize() + step); setTerminalFont(font); } @@ -567,6 +579,11 @@ int QTermWidget::screenColumnsCount() return m_impl->m_terminalDisplay->screenWindow()->screen()->getColumns(); } +int QTermWidget::screenLinesCount() +{ + return m_impl->m_terminalDisplay->screenWindow()->screen()->getLines(); +} + void QTermWidget::setSelectionStart(int row, int column) { m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionStart(column, row, true); @@ -582,9 +599,9 @@ void QTermWidget::getSelectionStart(int& row, int& column) m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(column, row); } -void QTermWidget::setSelectionEnd(int& row, int& column) +void QTermWidget::getSelectionEnd(int& row, int& column) { - m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionEnd(column, row); + m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(column, row); } QString QTermWidget::selectedText(bool preserveLineBreaks) @@ -619,3 +636,7 @@ Filter::HotSpot* QTermWidget::getHotSpotAt(int row, int column) const return m_impl->m_terminalDisplay->filterChain()->hotSpotAt(row, column); } +int QTermWidget::getPtySlaveFd() const +{ + return m_impl->m_session->getPtySlaveFd(); +} diff --git a/lib/qtermwidget.h b/lib/qtermwidget.h index 9c550ee..d8a1e46 100644 --- a/lib/qtermwidget.h +++ b/lib/qtermwidget.h @@ -55,6 +55,13 @@ public: //start shell program if it was not started in constructor void startShellProgram(); + /** + * Start terminal teletype as is + * and redirect data for external recipient. + * It can be used for display and control a remote terminal. + */ + void startTerminalTeletype(); + int getShellPID(); void changeDir(const QString & dir); @@ -63,8 +70,7 @@ public: // Terminal font // Default is application font with family Monospace, size 10 - // USE ONLY FIXED-PITCH FONT! - // otherwise symbols' position could be incorrect + // Beware of a performance penalty and display/alignment issues when using a proportional font. void setTerminalFont(const QFont & font); QFont getTerminalFont(); void setTerminalOpacity(qreal level); @@ -126,18 +132,19 @@ public: //! Return current key bindings QString keyBindings(); - + void setMotionAfterPasting(int); /** Return the number of lines in the history buffer. */ int historyLinesCount(); int screenColumnsCount(); + int screenLinesCount(); void setSelectionStart(int row, int column); void setSelectionEnd(int row, int column); void getSelectionStart(int& row, int& column); - void setSelectionEnd(int& row, int& column); + void getSelectionEnd(int& row, int& column); /** * Returns the currently selected text. @@ -165,6 +172,13 @@ public: */ Filter::HotSpot* getHotSpotAt(int row, int column) const; + /** + * Returns a pty slave file descriptor. + * This can be used for display and control + * a remote terminal. + */ + int getPtySlaveFd() const; + signals: void finished(); void copyAvailable(bool); @@ -181,6 +195,13 @@ signals: void activity(); void silence(); + /** + * Emitted when emulator send data to the terminal process + * (redirected for external recipient). It can be used for + * control and display the remote terminal. + */ + void sendData(const char *,int); + public slots: // Copy selection to clipboard void copyClipboard(); @@ -188,13 +209,13 @@ public slots: // Paste clipboard to terminal void pasteClipboard(); - // Paste selection to terminal + // Paste selection to terminal void pasteSelection(); // Set zoom void zoomIn(); void zoomOut(); - + /*! Set named key binding for given widget */ void setKeyBindings(const QString & kb); diff --git a/pyqt4/config.py b/pyqt4/config.py index b133b5b..b5eb76e 100755 --- a/pyqt4/config.py +++ b/pyqt4/config.py @@ -61,7 +61,7 @@ makefile = pyqtconfig.QtGuiModuleMakefile( # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the # ".dll" extension on Windows). makefile.extra_lib_dirs.append("..") -makefile.extra_libs = ["qtermwidget"] +makefile.extra_libs = ["qtermwidget4"] # Generate the Makefile itself. makefile.generate() diff --git a/pyqt4/qtermwidget.sip b/pyqt4/qtermwidget.sip index b9b0181..f57ccc9 100644 --- a/pyqt4/qtermwidget.sip +++ b/pyqt4/qtermwidget.sip @@ -11,25 +11,73 @@ class QTermWidget : QWidget { %End public: - QTermWidget(int startnow = 1, QWidget *parent = 0); - ~QTermWidget(); - enum ScrollBarPosition + enum ScrollBarPosition { NoScrollBar=0, ScrollBarLeft=1, ScrollBarRight=2 }; - void setTerminalFont(QFont &font); - void setArgs(QStringList &args); - void setTextCodec(QTextCodec *codec); - void setColorScheme(int scheme); - void setSize(int h, int v); - void setHistorySize(int lines); - void setScrollBarPosition(ScrollBarPosition); - void sendText(QString &text); + + QTermWidget(int startnow = 1, QWidget *parent = 0); + ~QTermWidget(); + + QSize sizeHint() const; + void startShellProgram(); + int getShellPID(); + void changeDir(const QString & dir); + void setTerminalFont(QFont &font); + QFont getTerminalFont(); + void setTerminalOpacity(qreal level); + void setEnvironment(const QStringList & environment); + void setShellProgram(const QString & progname); + void setWorkingDirectory(const QString & dir); + QString workingDirectory(); + void setArgs(QStringList &args); + void setTextCodec(QTextCodec *codec); + void setColorScheme(const QString & name); + static QStringList availableColorSchemes(); + void setSize(int h, int v); + void setHistorySize(int lines); + void setScrollBarPosition(ScrollBarPosition); + void scrollToEnd(); + void sendText(QString &text); + void setFlowControlEnabled(bool enabled); + bool flowControlEnabled(); + void setFlowControlWarningEnabled(bool enabled); + static QStringList availableKeyBindings(); + QString keyBindings(); + void setMotionAfterPasting(int); + int historyLinesCount(); + int screenColumnsCount(); + void setSelectionStart(int row, int column); + void setSelectionEnd(int row, int column); + void getSelectionStart(int& row, int& column); + void getSelectionEnd(int& row, int& column); + QString selectedText(bool preserveLineBreaks = true); + void setMonitorActivity(bool); + void setMonitorSilence(bool); + void setSilenceTimeout(int seconds); +signals: + void finished(); + void copyAvailable(bool); + void termGetFocus(); + void termLostFocus(); + void termKeyPressed(QKeyEvent *); + void urlActivated(const QUrl&); + void bell(const QString& message); + void activity(); + void silence(); +public slots: + void copyClipboard(); + void pasteClipboard(); + void pasteSelection(); + void zoomIn(); + void zoomOut(); + void setKeyBindings(const QString & kb); + void clear(); + void toggleShowSearchBar(); protected: - void resizeEvent(QResizeEvent *e); + void resizeEvent(QResizeEvent *e); private: - void *createTermWidget(int startnow, void *parent); - + void *createTermWidget(int startnow, void *parent); }; diff --git a/pyqt4/test.py b/pyqt4/test.py index 1045f8c..59bfb10 100755 --- a/pyqt4/test.py +++ b/pyqt4/test.py @@ -19,12 +19,16 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . -import sys +import sys, signal from PyQt4 import Qt +from PyQt4.QtCore import SIGNAL, SLOT import QTermWidget +signal.signal(signal.SIGINT, signal.SIG_DFL) + a = Qt.QApplication(sys.argv) w = QTermWidget.QTermWidget() w.show() +w.connect(w, SIGNAL('finished()'), a, SLOT('quit()')) a.exec_()