Adding upstream version 0.6.0+20150709.

upstream/0.6.0+20150709
Alf Gaida 9 years ago
parent c44b7c83a0
commit 3d7ff0b035

@ -15,7 +15,6 @@ set(QTERMWIDGET_VERSION_PATCH "0")
set(QTERMWIDGET_VERSION "${QTERMWIDGET_VERSION_MAJOR}.${QTERMWIDGET_VERSION_MINOR}.${QTERMWIDGET_VERSION_PATCH}") set(QTERMWIDGET_VERSION "${QTERMWIDGET_VERSION_MAJOR}.${QTERMWIDGET_VERSION_MINOR}.${QTERMWIDGET_VERSION_PATCH}")
include(CheckFunctionExists) include(CheckFunctionExists)
include(GNUInstallDirs) include(GNUInstallDirs)
@ -92,15 +91,15 @@ set(HDRS_DISTRIB
) )
# dirs # 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}") 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}" ) 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 #| Defines
add_definitions(-DHAVE_POSIX_OPENPT -DHAVE_SYS_TIME_H) add_definitions(-DHAVE_POSIX_OPENPT -DHAVE_SYS_TIME_H)
@ -133,7 +132,7 @@ set_target_properties( ${QTERMWIDGET_LIBRARY_NAME} PROPERTIES
if(APPLE) if(APPLE)
set (CMAKE_SKIP_RPATH 1) set (CMAKE_SKIP_RPATH 1)
# this is a must to load the lib correctly # 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() endif()
install(TARGETS ${QTERMWIDGET_LIBRARY_NAME} DESTINATION "${CMAKE_INSTALL_LIBDIR}") install(TARGETS ${QTERMWIDGET_LIBRARY_NAME} DESTINATION "${CMAKE_INSTALL_LIBDIR}")
@ -195,11 +194,11 @@ if (BUILD_DESIGNER_PLUGIN)
if(APPLE) if(APPLE)
# this is a must to load the lib correctly # this is a must to load the lib correctly
set_target_properties(qtermwidget4plugin PROPERTIES 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() 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) endif (BUILD_DESIGNER_PLUGIN)
# end of designer plugin # end of designer plugin

@ -1,6 +1,6 @@
/* /*
This file is part of Konsole, KDE's terminal. This file is part of Konsole, KDE's terminal.
Copyright 2007-2008 by Robert Knight <robertknight@gmail.com> Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -56,7 +56,7 @@ static const int LINE_DOUBLEHEIGHT = (1 << 2);
class Character class Character
{ {
public: public:
/** /**
* Constructs a new character. * Constructs a new character.
* *
* @param _c The unicode character value of this character. * @param _c The unicode character value of this character.
@ -74,25 +74,25 @@ public:
{ {
/** The unicode character value for this character. */ /** The unicode character value for this character. */
quint16 character; quint16 character;
/** /**
* Experimental addition which allows a single Character instance to contain more than * Experimental addition which allows a single Character instance to contain more than
* one unicode character. * one unicode character.
* *
* charSequence is a hash code which can be used to look up the unicode * charSequence is a hash code which can be used to look up the unicode
* character sequence in the ExtendedCharTable used to create the sequence. * 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. */ /** A combination of RENDITION flags which specify options for drawing the character. */
quint8 rendition; quint8 rendition;
/** The foreground color used to draw this character. */ /** The foreground color used to draw this character. */
CharacterColor foregroundColor; CharacterColor foregroundColor;
/** The color used to draw this character's background. */ /** The color used to draw this character's background. */
CharacterColor backgroundColor; CharacterColor backgroundColor;
/** /**
* Returns true if this character has a transparent background when * Returns true if this character has a transparent background when
* it is drawn with the specified @p palette. * 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 * Returns true if this character should always be drawn in bold when
* it is drawn with the specified @p palette, independent of whether * 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; ColorEntry::FontWeight fontWeight(const ColorEntry* base) const;
/** /**
* returns true if the format (color, rendition flag) of the compared characters is equal * returns true if the format (color, rendition flag) of the compared characters is equal
*/ */
bool equalsFormat(const Character &other) const; bool equalsFormat(const Character &other) const;
/** /**
* Compares two characters and returns true if they have the same unicode character value, * Compares two characters and returns true if they have the same unicode character value,
* rendition and colors. * rendition and colors.
*/ */
@ -122,36 +122,36 @@ public:
}; };
inline bool operator == (const Character& a, const Character& b) inline bool operator == (const Character& a, const Character& b)
{ {
return a.character == b.character && return a.character == b.character &&
a.rendition == b.rendition && a.rendition == b.rendition &&
a.foregroundColor == b.foregroundColor && a.foregroundColor == b.foregroundColor &&
a.backgroundColor == b.backgroundColor; a.backgroundColor == b.backgroundColor;
} }
inline bool operator != (const Character& a, const Character& b) inline bool operator != (const Character& a, const Character& b)
{ {
return a.character != b.character || return a.character != b.character ||
a.rendition != b.rendition || a.rendition != b.rendition ||
a.foregroundColor != b.foregroundColor || a.foregroundColor != b.foregroundColor ||
a.backgroundColor != b.backgroundColor; a.backgroundColor != b.backgroundColor;
} }
inline bool Character::isTransparent(const ColorEntry* base) const 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) 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); base[backgroundColor._u+2+(backgroundColor._v?BASE_COLORS:0)].transparent);
} }
inline bool Character::equalsFormat(const Character& other) const inline bool Character::equalsFormat(const Character& other) const
{ {
return return
backgroundColor==other.backgroundColor && backgroundColor==other.backgroundColor &&
foregroundColor==other.foregroundColor && foregroundColor==other.foregroundColor &&
rendition==other.rendition; rendition==other.rendition;
} }
inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const inline ColorEntry::FontWeight Character::fontWeight(const ColorEntry* base) const
{ {
@ -196,7 +196,7 @@ public:
* which was added to the table using createExtendedChar(). * which was added to the table using createExtendedChar().
* *
* @param hash The hash key returned by 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. * character sequence.
* *
* @return A unicode character sequence of size @p length. * @return A unicode character sequence of size @p length.
@ -208,7 +208,7 @@ public:
private: private:
// calculates the hash key of a sequence of unicode points of size 'length' // calculates the hash key of a sequence of unicode points of size 'length'
ushort extendedCharHash(ushort* unicodePoints , ushort length) const; 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' // character sequence 'unicodePoints' of size 'length'
bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const; bool extendedCharMatch(ushort hash , ushort* unicodePoints , ushort length) const;
// internal, maps hash keys to character sequence buffers. The first ushort // internal, maps hash keys to character sequence buffers. The first ushort

@ -1,6 +1,6 @@
/* /*
This file is part of Konsole, KDE's terminal. This file is part of Konsole, KDE's terminal.
Copyright 2007-2008 by Robert Knight <robertknight@gmail.com> Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -32,14 +32,14 @@
namespace Konsole 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 * A color palette is an array of 16 ColorEntry instances which map
* system color indexes (from 0 to 15) into actual colors. * system color indexes (from 0 to 15) into actual colors.
* *
* Each entry can be set as bold, in which case any text * 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 * Each entry can also be transparent, in which case the terminal
* display should avoid drawing the background for any characters * display should avoid drawing the background for any characters
@ -49,58 +49,58 @@ class ColorEntry
{ {
public: public:
/** Specifies the weight to use when drawing text with this color. */ /** 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. */ /** Always draw text in this color with a bold weight. */
Bold, Bold,
/** Always draw text in this color with a normal weight. */ /** Always draw text in this color with a normal weight. */
Normal, 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. * This is the default behavior.
*/ */
UseCurrentFormat UseCurrentFormat
}; };
/** /**
* Constructs a new color palette entry. * Constructs a new color palette entry.
* *
* @param c The color value for this 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 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) {} : color(c), transparent(tr), fontWeight(weight) {}
/** /**
* Constructs a new color palette entry with an undefined color, and * Constructs a new color palette entry with an undefined color, and
* with the transparent and bold flags set to false. * 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. * Sets the color, transparency and boldness of this color to those of @p rhs.
*/ */
void operator=(const ColorEntry& rhs) void operator=(const ColorEntry& rhs)
{ {
color = rhs.color; color = rhs.color;
transparent = rhs.transparent; transparent = rhs.transparent;
fontWeight = rhs.fontWeight; fontWeight = rhs.fontWeight;
} }
/** The color value of this entry for display. */ /** The color value of this entry for display. */
QColor color; 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. * This is not applicable when the color is used to render text.
*/ */
bool transparent; 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. * 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: public:
/** Constructs a new CharacterColor whoose color and color space are undefined. */ /** Constructs a new CharacterColor whoose color and color space are undefined. */
CharacterColor() CharacterColor()
: _colorSpace(COLOR_SPACE_UNDEFINED), : _colorSpace(COLOR_SPACE_UNDEFINED),
_u(0), _u(0),
_v(0), _v(0),
_w(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 * color value @p co
* *
* The meaning of @p co depends on the @p colorSpace used. * The meaning of @p co depends on the @p colorSpace used.
@ -168,10 +168,10 @@ public:
* *
* TODO : Add documentation about available color spaces. * TODO : Add documentation about available color spaces.
*/ */
CharacterColor(quint8 colorSpace, int co) CharacterColor(quint8 colorSpace, int co)
: _colorSpace(colorSpace), : _colorSpace(colorSpace),
_u(0), _u(0),
_v(0), _v(0),
_w(0) _w(0)
{ {
switch (colorSpace) switch (colorSpace)
@ -183,7 +183,7 @@ public:
_u = co & 7; _u = co & 7;
_v = (co >> 3) & 1; _v = (co >> 3) & 1;
break; break;
case COLOR_SPACE_256: case COLOR_SPACE_256:
_u = co & 255; _u = co & 255;
break; break;
case COLOR_SPACE_RGB: case COLOR_SPACE_RGB:
@ -196,32 +196,32 @@ public:
} }
} }
/** /**
* Returns true if this character color entry is valid. * Returns true if this character color entry is valid.
*/ */
bool isValid() bool isValid()
{ {
return _colorSpace != COLOR_SPACE_UNDEFINED; return _colorSpace != COLOR_SPACE_UNDEFINED;
} }
/** /**
* Toggles the value of this color between a normal system color and the corresponding intensive * Toggles the value of this color between a normal system color and the corresponding intensive
* system color. * system color.
* *
* This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM * This is only applicable if the color is using the COLOR_SPACE_DEFAULT or COLOR_SPACE_SYSTEM
* color spaces. * color spaces.
*/ */
void toggleIntensive(); void toggleIntensive();
/** /**
* Returns the color within the specified color @p palette * 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 * The @p palette is only used if this color is one of the 16 system colors, otherwise
* it is ignored. * it is ignored.
*/ */
QColor color(const ColorEntry* palette) const; QColor color(const ColorEntry* palette) const;
/** /**
* Compares two colors and returns true if they represent the same color value and * Compares two colors and returns true if they represent the same color value and
* use the same color space. * use the same color space.
*/ */
@ -235,14 +235,14 @@ public:
private: private:
quint8 _colorSpace; quint8 _colorSpace;
// bytes storing the character color // bytes storing the character color
quint8 _u; quint8 _u;
quint8 _v; quint8 _v;
quint8 _w; quint8 _w;
}; };
inline bool operator == (const CharacterColor& a, const CharacterColor& b) inline bool operator == (const CharacterColor& a, const CharacterColor& b)
{ {
return a._colorSpace == b._colorSpace && return a._colorSpace == b._colorSpace &&
a._u == b._u && a._u == b._u &&
a._v == b._v && 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, if (u < 216) return QColor(((u/36)%6) ? (40*((u/36)%6)+55) : 0,
((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0, ((u/ 6)%6) ? (40*((u/ 6)%6)+55) : 0,
((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216; ((u/ 1)%6) ? (40*((u/ 1)%6)+55) : 0); u -= 216;
// 232..255: gray, leaving out black and white // 232..255: gray, leaving out black and white
int gray = u*10+8; return QColor(gray,gray,gray); int gray = u*10+8; return QColor(gray,gray,gray);
} }

@ -164,15 +164,15 @@ void ColorScheme::setColorTableEntry(int index , const ColorEntry& entry)
{ {
Q_ASSERT( index >= 0 && index < TABLE_COLORS ); Q_ASSERT( index >= 0 && index < TABLE_COLORS );
if ( !_table ) if ( !_table )
{ {
_table = new ColorEntry[TABLE_COLORS]; _table = new ColorEntry[TABLE_COLORS];
for (int i=0;i<TABLE_COLORS;i++) for (int i=0;i<TABLE_COLORS;i++)
_table[i] = defaultTable[i]; _table[i] = defaultTable[i];
} }
_table[index] = entry; _table[index] = entry;
} }
ColorEntry ColorScheme::colorEntry(int index , uint randomSeed) const ColorEntry ColorScheme::colorEntry(int index , uint randomSeed) const
{ {
@ -183,19 +183,19 @@ ColorEntry ColorScheme::colorEntry(int index , uint randomSeed) const
ColorEntry entry = colorTable()[index]; ColorEntry entry = colorTable()[index];
if ( randomSeed != 0 && if ( randomSeed != 0 &&
_randomTable != 0 && _randomTable != 0 &&
!_randomTable[index].isNull() ) !_randomTable[index].isNull() )
{ {
const RandomizationRange& range = _randomTable[index]; const RandomizationRange& range = _randomTable[index];
int hueDifference = range.hue ? (qrand() % range.hue) - range.hue/2 : 0; int hueDifference = range.hue ? (qrand() % range.hue) - range.hue/2 : 0;
int saturationDifference = range.saturation ? (qrand() % range.saturation) - range.saturation/2 : 0; int saturationDifference = range.saturation ? (qrand() % range.saturation) - range.saturation/2 : 0;
int valueDifference = range.value ? (qrand() % range.value) - range.value/2 : 0; int valueDifference = range.value ? (qrand() % range.value) - range.value/2 : 0;
QColor& color = entry.color; QColor& color = entry.color;
int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE ); int newHue = qAbs( (color.hue() + hueDifference) % MAX_HUE );
int newValue = qMin( qAbs(color.value() + valueDifference) , 255 ); int newValue = qMin( qAbs(color.value() + valueDifference) , 255 );
int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 ); int newSaturation = qMin( qAbs(color.saturation() + saturationDifference) , 255 );
@ -216,13 +216,13 @@ bool ColorScheme::randomizedBackgroundColor() const
} }
void ColorScheme::setRandomizedBackgroundColor(bool randomize) void ColorScheme::setRandomizedBackgroundColor(bool randomize)
{ {
// the hue of the background colour is allowed to be randomly // the hue of the background colour is allowed to be randomly
// adjusted as much as possible. // adjusted as much as possible.
// //
// the value and saturation are left alone to maintain read-ability // the value and saturation are left alone to maintain read-ability
if ( randomize ) if ( randomize )
{ {
setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 ); setRandomizationRange( 1 /* background color index */ , MAX_HUE , 255 , 0 );
} }
else else
{ {
@ -305,7 +305,7 @@ void ColorScheme::write(KConfig& config) const
configGroup.writeEntry("Description",_description); configGroup.writeEntry("Description",_description);
configGroup.writeEntry("Opacity",_opacity); configGroup.writeEntry("Opacity",_opacity);
for (int i=0 ; i < TABLE_COLORS ; i++) for (int i=0 ; i < TABLE_COLORS ; i++)
{ {
RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange(); RandomizationRange random = _randomTable != 0 ? _randomTable[i] : RandomizationRange();
@ -314,13 +314,13 @@ void ColorScheme::write(KConfig& config) const
} }
#endif #endif
QString ColorScheme::colorNameForIndex(int index) QString ColorScheme::colorNameForIndex(int index)
{ {
Q_ASSERT( index >= 0 && index < TABLE_COLORS ); Q_ASSERT( index >= 0 && index < TABLE_COLORS );
return QString(colorNames[index]); return QString(colorNames[index]);
} }
QString ColorScheme::translatedColorNameForIndex(int index) QString ColorScheme::translatedColorNameForIndex(int index)
{ {
Q_ASSERT( index >= 0 && index < TABLE_COLORS ); Q_ASSERT( index >= 0 && index < TABLE_COLORS );
@ -330,7 +330,7 @@ QString ColorScheme::translatedColorNameForIndex(int index)
void ColorScheme::readColorEntry(QSettings * s , int index) void ColorScheme::readColorEntry(QSettings * s , int index)
{ {
s->beginGroup(colorNameForIndex(index)); s->beginGroup(colorNameForIndex(index));
ColorEntry entry; ColorEntry entry;
QStringList rgbList = s->value("Color", QStringList()).toStringList(); QStringList rgbList = s->value("Color", QStringList()).toStringList();
@ -343,7 +343,7 @@ void ColorScheme::readColorEntry(QSettings * s , int index)
g = rgbList[1].toInt(); g = rgbList[1].toInt();
b = rgbList[2].toInt(); b = rgbList[2].toInt();
entry.color = QColor(r, g, b); entry.color = QColor(r, g, b);
entry.transparent = s->value("Transparent",false).toBool(); entry.transparent = s->value("Transparent",false).toBool();
// Deprecated key from KDE 4.0 which set 'Bold' to true to force // 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 ); setColorTableEntry( index , entry );
if ( hue != 0 || value != 0 || saturation != 0 ) if ( hue != 0 || value != 0 || saturation != 0 )
setRandomizationRange( index , hue , saturation , value ); setRandomizationRange( index , hue , saturation , value );
s->endGroup(); s->endGroup();
} }
@ -379,8 +379,8 @@ void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, co
configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold); configGroup.writeEntry("Bold",entry.fontWeight == ColorEntry::Bold);
} }
// record randomization if this color has randomization or // record randomization if this color has randomization or
// if one of the keys already exists // if one of the keys already exists
if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") ) if ( !random.isNull() || configGroup.hasKey("MaxRandomHue") )
{ {
configGroup.writeEntry("MaxRandomHue",(int)random.hue); configGroup.writeEntry("MaxRandomHue",(int)random.hue);
@ -390,28 +390,28 @@ void ColorScheme::writeColorEntry(KConfig& config , const QString& colorName, co
} }
#endif #endif
// //
// Work In Progress - A color scheme for use on KDE setups for users // Work In Progress - A color scheme for use on KDE setups for users
// with visual disabilities which means that they may have trouble // with visual disabilities which means that they may have trouble
// reading text with the supplied color schemes. // reading text with the supplied color schemes.
// //
// This color scheme uses only the 'safe' colors defined by the // 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. // 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. // only background colors are allowed to be used for backgrounds.
// //
// The ColorEntry and TerminalDisplay classes do not currently // The ColorEntry and TerminalDisplay classes do not currently
// support this restriction. // support this restriction.
// //
// Requirements: // Requirements:
// - A color scheme which uses only colors from the KColorScheme class // - 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 // uses as foreground and background color
// - Make use of KGlobalSettings::allowDefaultBackgroundImages() as // - 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. // be used by default.
// //
// //
@ -444,13 +444,13 @@ AccessibleColorScheme::AccessibleColorScheme()
colorScheme.foreground( colorScheme.NeutralText ) colorScheme.foreground( colorScheme.NeutralText )
}; };
for ( int i = 0 ; i < TABLE_COLORS ; i++ ) for ( int i = 0 ; i < TABLE_COLORS ; i++ )
{ {
ColorEntry entry; ColorEntry entry;
entry.color = colors[ i % ColorRoleCount ].color(); entry.color = colors[ i % ColorRoleCount ].color();
setColorTableEntry( i , entry ); setColorTableEntry( i , entry );
} }
#endif #endif
} }
@ -458,7 +458,7 @@ KDE3ColorSchemeReader::KDE3ColorSchemeReader( QIODevice* device ) :
_device(device) _device(device)
{ {
} }
ColorScheme* KDE3ColorSchemeReader::read() ColorScheme* KDE3ColorSchemeReader::read()
{ {
Q_ASSERT( _device->openMode() == QIODevice::ReadOnly || Q_ASSERT( _device->openMode() == QIODevice::ReadOnly ||
_device->openMode() == QIODevice::ReadWrite ); _device->openMode() == QIODevice::ReadWrite );
@ -489,7 +489,7 @@ ColorScheme* KDE3ColorSchemeReader::read()
{ {
qDebug() << "KDE 3 color scheme contains an unsupported feature, '" << qDebug() << "KDE 3 color scheme contains an unsupported feature, '" <<
line << "'"; line << "'";
} }
} }
return scheme; return scheme;
@ -502,7 +502,7 @@ bool KDE3ColorSchemeReader::readColorLine(const QString& line,ColorScheme* schem
return false; return false;
if (list.first() != "color") if (list.first() != "color")
return false; return false;
int index = list[1].toInt(); int index = list[1].toInt();
int red = list[2].toInt(); int red = list[2].toInt();
int green = list[3].toInt(); int green = list[3].toInt();
@ -613,7 +613,7 @@ bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath)
delete scheme; delete scheme;
return false; return false;
} }
QFileInfo info(filePath); QFileInfo info(filePath);
if ( !_colorSchemes.contains(info.baseName()) ) if ( !_colorSchemes.contains(info.baseName()) )
@ -628,7 +628,7 @@ bool ColorSchemeManager::loadKDE3ColorScheme(const QString& filePath)
return true; return true;
} }
#if 0 #if 0
void ColorSchemeManager::addColorScheme(ColorScheme* scheme) void ColorSchemeManager::addColorScheme(ColorScheme* scheme)
{ {
_colorSchemes.insert(scheme->name(),scheme); _colorSchemes.insert(scheme->name(),scheme);
@ -658,17 +658,17 @@ bool ColorSchemeManager::loadColorScheme(const QString& filePath)
QFileInfo info(filePath); QFileInfo info(filePath);
const QString& schemeName = info.baseName(); const QString& schemeName = info.baseName();
ColorScheme* scheme = new ColorScheme(); ColorScheme* scheme = new ColorScheme();
scheme->setName(schemeName); scheme->setName(schemeName);
scheme->read(filePath); 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."; qDebug() << "Color scheme in" << filePath << "does not have a valid name and was not loaded.";
delete scheme; delete scheme;
return false; return false;
} }
if ( !_colorSchemes.contains(schemeName) ) if ( !_colorSchemes.contains(schemeName) )
{ {
@ -678,11 +678,11 @@ bool ColorSchemeManager::loadColorScheme(const QString& filePath)
{ {
qDebug() << "color scheme with name" << schemeName << "has already been" << qDebug() << "color scheme with name" << schemeName << "has already been" <<
"found, ignoring."; "found, ignoring.";
delete scheme; delete scheme;
} }
return true; return true;
} }
QList<QString> ColorSchemeManager::listKDE3ColorSchemes() QList<QString> ColorSchemeManager::listKDE3ColorSchemes()
{ {
@ -691,7 +691,7 @@ QList<QString> ColorSchemeManager::listKDE3ColorSchemes()
QStringList filters; QStringList filters;
filters << "*.schema"; filters << "*.schema";
dir.setNameFilters(filters); dir.setNameFilters(filters);
QStringList list = dir.entryList(filters); QStringList list = dir.entryList(filters);
QStringList ret; QStringList ret;
foreach(QString i, list) foreach(QString i, list)
ret << dname + "/" + i; ret << dname + "/" + i;
@ -726,7 +726,7 @@ bool ColorSchemeManager::deleteColorScheme(const QString& name)
{ {
Q_ASSERT( _colorSchemes.contains(name) ); Q_ASSERT( _colorSchemes.contains(name) );
// lookup the path and delete // lookup the path and delete
QString path = findColorSchemePath(name); QString path = findColorSchemePath(name);
if ( QFile::remove(path) ) 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 = KStandardDirs::locate("data","konsole/"+name+".colorscheme");
QString path(get_color_schemes_dir() + "/"+ name + ".colorscheme"); QString path(get_color_schemes_dir() + "/"+ name + ".colorscheme");
if ( !path.isEmpty() ) if ( !path.isEmpty() )
return path; return path;
//path = KStandardDirs::locate("data","konsole/"+name+".schema"); //path = KStandardDirs::locate("data","konsole/"+name+".schema");
path = get_color_schemes_dir() + "/"+ name + ".schema"; path = get_color_schemes_dir() + "/"+ name + ".schema";
return path; return path;
} }
const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name) const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name)
{ {
if ( name.isEmpty() ) if ( name.isEmpty() )
return defaultColorScheme(); return defaultColorScheme();
@ -761,12 +761,12 @@ const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name)
else else
{ {
// look for this color scheme // look for this color scheme
QString path = findColorSchemePath(name); QString path = findColorSchemePath(name);
if ( !path.isEmpty() && loadColorScheme(path) ) if ( !path.isEmpty() && loadColorScheme(path) )
{ {
return findColorScheme(name); return findColorScheme(name);
} }
else else
{ {
if (!path.isEmpty() && loadKDE3ColorScheme(path)) if (!path.isEmpty() && loadKDE3ColorScheme(path))
return findColorScheme(name); return findColorScheme(name);
@ -774,7 +774,7 @@ const ColorScheme* ColorSchemeManager::findColorScheme(const QString& name)
qDebug() << "Could not find color scheme - " << name; qDebug() << "Could not find color scheme - " << name;
return 0; return 0;
} }
} }

@ -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 * 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 class ColorScheme
{ {
public: 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. * for Konsole.
*/ */
ColorScheme(); ColorScheme();
@ -78,7 +78,7 @@ public:
/** Sets a single entry within the color palette. */ /** Sets a single entry within the color palette. */
void setColorTableEntry(int index , const ColorEntry& entry); void setColorTableEntry(int index , const ColorEntry& entry);
/** /**
* Copies the color entries which form the palette for this color scheme * 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. * 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. * palette to be randomized. The seed is used to pick the random color.
*/ */
void getColorTable(ColorEntry* table, uint randomSeed = 0) const; void getColorTable(ColorEntry* table, uint randomSeed = 0) const;
/** /**
* Retrieves a single color entry from the table. * Retrieves a single color entry from the table.
* *
@ -96,28 +96,28 @@ public:
*/ */
ColorEntry colorEntry(int index , uint randomSeed = 0) const; ColorEntry colorEntry(int index , uint randomSeed = 0) const;
/** /**
* Convenience method. Returns the * Convenience method. Returns the
* foreground color for this scheme, * foreground color for this scheme,
* this is the primary color used to draw the * this is the primary color used to draw the
* text in this scheme. * text in this scheme.
*/ */
QColor foregroundColor() const; QColor foregroundColor() const;
/** /**
* Convenience method. Returns the background color for * Convenience method. Returns the background color for
* this scheme, this is the primary color used to * this scheme, this is the primary color used to
* draw the terminal background in this scheme. * draw the terminal background in this scheme.
*/ */
QColor backgroundColor() const; QColor backgroundColor() const;
/** /**
* Returns true if this color scheme has a dark background. * 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 * The background color is said to be dark if it has a value of less than 127
* in the HSV color space. * in the HSV color space.
*/ */
bool hasDarkBackground() const; bool hasDarkBackground() const;
/** /**
* Sets the opacity level of the display background. @p opacity ranges * Sets the opacity level of the display background. @p opacity ranges
* between 0 (completely transparent background) and 1 (completely * between 0 (completely transparent background) and 1 (completely
* opaque background). * opaque background).
@ -127,18 +127,18 @@ public:
* TODO: More documentation * TODO: More documentation
*/ */
void setOpacity(qreal opacity); void setOpacity(qreal opacity);
/** /**
* Returns the opacity level for this color scheme, see setOpacity() * Returns the opacity level for this color scheme, see setOpacity()
* TODO: More documentation * TODO: More documentation
*/ */
qreal opacity() const; qreal opacity() const;
/** /**
* Enables randomization of the background color. This will cause * Enables randomization of the background color. This will cause
* the palette returned by getColorTable() and colorEntry() to * the palette returned by getColorTable() and colorEntry() to
* be adjusted depending on the value of the random seed argument * be adjusted depending on the value of the random seed argument
* to them. * to them.
*/ */
void setRandomizedBackgroundColor(bool randomize); void setRandomizedBackgroundColor(bool randomize);
/** Returns true if the background color is randomized. */ /** Returns true if the background color is randomized. */
@ -154,7 +154,7 @@ private:
public: public:
RandomizationRange() : hue(0) , saturation(0) , value(0) {} RandomizationRange() : hue(0) , saturation(0) , value(0) {}
bool isNull() const bool isNull() const
{ {
return ( hue == 0 && saturation == 0 && value == 0 ); return ( hue == 0 && saturation == 0 && value == 0 );
} }
@ -172,14 +172,14 @@ private:
// implemented upstream - user apps // implemented upstream - user apps
// reads a single colour entry from a KConfig source // reads a single colour entry from a KConfig source
// and sets the palette entry at 'index' to the entry read. // 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 // writes a single colour entry to a KConfig source
void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const; void writeColorEntry(KConfig& config , const QString& colorName, const ColorEntry& entry,const RandomizationRange& range) const;
#endif #endif
void readColorEntry(QSettings *s, int index); void readColorEntry(QSettings *s, int index);
// sets the amount of randomization allowed for a particular color // sets the amount of randomization allowed for a particular color
// in the palette. creates the randomization table if // in the palette. creates the randomization table if
// it does not already exist // it does not already exist
void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value ); void setRandomizationRange( int index , quint16 hue , quint8 saturation , quint8 value );
@ -202,7 +202,7 @@ private:
static const ColorEntry defaultTable[]; // table of default color entries static const ColorEntry defaultTable[]; // table of default color entries
}; };
/** /**
* A color scheme which uses colors from the standard KDE color palette. * 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 * This is designed primarily for the benefit of users who are using specially
@ -228,13 +228,13 @@ public:
class KDE3ColorSchemeReader class KDE3ColorSchemeReader
{ {
public: public:
/** /**
* Constructs a new reader which reads from the specified device. * Constructs a new reader which reads from the specified device.
* The device should be open in read-only mode. * The device should be open in read-only mode.
*/ */
KDE3ColorSchemeReader( QIODevice* device ); KDE3ColorSchemeReader( QIODevice* device );
/** /**
* Reads and parses the contents of the .schema file from the input * Reads and parses the contents of the .schema file from the input
* device and returns the ColorScheme defined within it. * device and returns the ColorScheme defined within it.
* *
@ -277,7 +277,7 @@ public:
* Returns the default color scheme for Konsole * Returns the default color scheme for Konsole
*/ */
const ColorScheme* defaultColorScheme() const; const ColorScheme* defaultColorScheme() const;
/** /**
* Returns the color scheme with the given name or 0 if no * Returns the color scheme with the given name or 0 if no
* scheme with that name exists. If @p name is empty, the * scheme with that name exists. If @p name is empty, the
@ -298,18 +298,18 @@ public:
void addColorScheme(ColorScheme* scheme); void addColorScheme(ColorScheme* scheme);
#endif #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); 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 * This may be slow when first called because all of the color
* scheme resources on disk must be located, read and parsed. * scheme resources on disk must be located, read and parsed.
* *
* Subsequent calls will be inexpensive. * Subsequent calls will be inexpensive.
*/ */
QList<const ColorScheme*> allColorSchemes(); QList<const ColorScheme*> allColorSchemes();
/** Returns the global color scheme manager instance. */ /** Returns the global color scheme manager instance. */
static ColorSchemeManager* instance(); static ColorSchemeManager* instance();

@ -1,5 +1,5 @@
/* /*
Copyright 2007-2008 Robert Knight <robertknight@gmail.com> Copyright 2007-2008 Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
Copyright 1996 by Matthias Ettrich <ettrich@kde.org> Copyright 1996 by Matthias Ettrich <ettrich@kde.org>
@ -64,9 +64,9 @@ Emulation::Emulation() :
QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) ); QObject::connect(&_bulkTimer1, SIGNAL(timeout()), this, SLOT(showBulk()) );
QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) ); QObject::connect(&_bulkTimer2, SIGNAL(timeout()), this, SLOT(showBulk()) );
// listen for mouse status changes // listen for mouse status changes
connect( this , SIGNAL(programUsesMouseChanged(bool)) , connect( this , SIGNAL(programUsesMouseChanged(bool)) ,
SLOT(usesMouseChanged(bool)) ); SLOT(usesMouseChanged(bool)) );
} }
@ -112,7 +112,7 @@ void Emulation::setScreen(int n)
{ {
Screen *old = _currentScreen; Screen *old = _currentScreen;
_currentScreen = _screen[n & 1]; _currentScreen = _screen[n & 1];
if (_currentScreen != old) if (_currentScreen != old)
{ {
// tell all windows onto this emulation to switch to the newly active screen // tell all windows onto this emulation to switch to the newly active screen
foreach(ScreenWindow* window,_windows) foreach(ScreenWindow* window,_windows)
@ -191,7 +191,7 @@ void Emulation::receiveChar(int c)
void Emulation::sendKeyEvent( QKeyEvent* ev ) void Emulation::sendKeyEvent( QKeyEvent* ev )
{ {
emit stateSet(NOTIFYNORMAL); emit stateSet(NOTIFYNORMAL);
if (!ev->text().isEmpty()) if (!ev->text().isEmpty())
{ // A block of text { // A block of text
// Note that the text is proper unicode. // Note that the text is proper unicode.
@ -220,7 +220,7 @@ void Emulation::receiveData(const char* text, int length)
emit stateSet(NOTIFYACTIVITY); emit stateSet(NOTIFYACTIVITY);
bufferedUpdate(); bufferedUpdate();
QString unicodeText = _decoder->toUnicode(text,length); QString unicodeText = _decoder->toUnicode(text,length);
//send characters to terminal emulator //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) //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 //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) /*void Emulation::onRcvBlock(const char *s, int len)
{ {
emit notifySessionState(NOTIFYACTIVITY); emit notifySessionState(NOTIFYACTIVITY);
bufferedUpdate(); bufferedUpdate();
for (int i = 0; i < len; i++) 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 startLine ,
int endLine) int endLine)
{ {
_currentScreen->writeLinesToStream(_decoder,startLine,endLine); _currentScreen->writeLinesToStream(_decoder,startLine,endLine);
} }
@ -334,7 +334,7 @@ char Emulation::eraseChar() const
void Emulation::setImageSize(int lines, int columns) void Emulation::setImageSize(int lines, int columns)
{ {
if ((lines < 1) || (columns < 1)) if ((lines < 1) || (columns < 1))
return; return;
QSize screenSize[2] = { QSize(_screen[0]->getColumns(), QSize screenSize[2] = { QSize(_screen[0]->getColumns(),
@ -344,7 +344,7 @@ void Emulation::setImageSize(int lines, int columns)
QSize newSize(columns,lines); QSize newSize(columns,lines);
if (newSize == screenSize[0] && newSize == screenSize[1]) if (newSize == screenSize[0] && newSize == screenSize[1])
return; return;
_screen[0]->resizeImage(lines,columns); _screen[0]->resizeImage(lines,columns);
_screen[1]->resizeImage(lines,columns); _screen[1]->resizeImage(lines,columns);
@ -372,17 +372,17 @@ bool ExtendedCharTable::extendedCharMatch(ushort hash , ushort* unicodePoints ,
{ {
ushort* entry = extendedCharTable[hash]; ushort* entry = extendedCharTable[hash];
// compare given length with stored sequence length ( given as the first ushort in the // compare given length with stored sequence length ( given as the first ushort in the
// stored buffer ) // stored buffer )
if ( entry == 0 || entry[0] != length ) if ( entry == 0 || entry[0] != length )
return false; return false;
// if the lengths match, each character must be checked. the stored buffer starts at // if the lengths match, each character must be checked. the stored buffer starts at
// entry[1] // entry[1]
for ( int i = 0 ; i < length ; i++ ) for ( int i = 0 ; i < length ; i++ )
{ {
if ( entry[i+1] != unicodePoints[i] ) if ( entry[i+1] != unicodePoints[i] )
return false; return false;
} }
return true; return true;
} }
ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length) ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort length)
@ -395,7 +395,7 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng
{ {
if ( extendedCharMatch(hash,unicodePoints,length) ) 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 its hash
return hash; return hash;
} }
@ -405,16 +405,16 @@ ushort ExtendedCharTable::createExtendedChar(ushort* unicodePoints , ushort leng
// points then try next hash // points then try next hash
hash++; hash++;
} }
} }
// add the new sequence to the table and // add the new sequence to the table and
// return that index // return that index
ushort* buffer = new ushort[length+1]; ushort* buffer = new ushort[length+1];
buffer[0] = length; buffer[0] = length;
for ( int i = 0 ; i < length ; i++ ) for ( int i = 0 ; i < length ; i++ )
buffer[i+1] = unicodePoints[i]; buffer[i+1] = unicodePoints[i];
extendedCharTable.insert(hash,buffer); extendedCharTable.insert(hash,buffer);
return hash; return hash;

@ -1,6 +1,6 @@
/* /*
This file is part of Konsole, an X terminal. This file is part of Konsole, an X terminal.
Copyright 2007-2008 by Robert Knight <robertknight@gmail.com> Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -26,7 +26,7 @@
// System // System
#include <stdio.h> #include <stdio.h>
// Qt // Qt
#include <QKeyEvent> #include <QKeyEvent>
//#include <QPointer> //#include <QPointer>
#include <QTextCodec> #include <QTextCodec>
@ -46,56 +46,56 @@ class Screen;
class ScreenWindow; class ScreenWindow;
class TerminalCharacterDecoder; class TerminalCharacterDecoder;
/** /**
* This enum describes the available states which * This enum describes the available states which
* the terminal emulation may be set to. * 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. */ /** The emulation is currently receiving user input. */
NOTIFYNORMAL=0, NOTIFYNORMAL=0,
/** /**
* The terminal program has triggered a bell event * The terminal program has triggered a bell event
* to get the user's attention. * to get the user's attention.
*/ */
NOTIFYBELL=1, NOTIFYBELL=1,
/** /**
* The emulation is currently receiving data from its * The emulation is currently receiving data from its
* terminal input. * terminal input.
*/ */
NOTIFYACTIVITY=2, NOTIFYACTIVITY=2,
// unused here? // unused here?
NOTIFYSILENCE=3 NOTIFYSILENCE=3
}; };
/** /**
* Base class for terminal emulation back-ends. * 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. * producing an output image of characters.
* *
* When input from the terminal is received, the receiveData() slot should be called with * 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 * 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 * 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 * 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 * 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 * 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 * 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 * previous output. The screen windows emit an outputChanged signal
* when the section of the image they are looking at changes. * 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 * 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 * of output changes from the screen window which they are associated with and updating
* accordingly. * accordingly.
* *
* The emulation also is also responsible for converting input from the connected views such * 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 * 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 * character sequences. The name of the key bindings set used can be specified using
* setKeyBindings() * setKeyBindings()
* *
* The emulation maintains certain state information which changes depending on the * 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 * input received. The emulation can be reset back to its starting state by calling
* reset(). * reset().
* *
* The emulation also maintains an activity state, which specifies whether * The emulation also maintains an activity state, which specifies whether
* terminal is currently active ( when data is received ), normal * terminal is currently active ( when data is received ), normal
@ -121,12 +121,12 @@ enum
* a 'bell' event in different ways. * a 'bell' event in different ways.
*/ */
class KONSOLEPRIVATE_EXPORT Emulation : public QObject class KONSOLEPRIVATE_EXPORT Emulation : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
/** Constructs a new terminal emulation */ /** Constructs a new terminal emulation */
Emulation(); Emulation();
~Emulation(); ~Emulation();
@ -142,15 +142,15 @@ public:
/** /**
* Returns the total number of lines, including those stored in the history. * Returns the total number of lines, including those stored in the history.
*/ */
int lineCount() const; int lineCount() const;
/** /**
* Sets the history store used by this emulation. When new lines * 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 * 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. * type of store.
*/ */
void setHistory(const HistoryType&); void setHistory(const HistoryType&);
@ -159,49 +159,49 @@ public:
/** Clears the history scroll. */ /** Clears the history scroll. */
void clearHistory(); 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 * 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 * appearance attributes into output text. PlainTextDecoder is the most commonly
* used decoder. * used decoder.
* @param startLine Index of first line to copy * @param startLine Index of first line to copy
* @param endLine Index of last line to copy * @param endLine Index of last line to copy
*/ */
virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine); virtual void writeToStream(TerminalCharacterDecoder* decoder,int startLine,int endLine);
/** Returns the codec used to decode incoming characters. See setCodec() */ /** Returns the codec used to decode incoming characters. See setCodec() */
const QTextCodec* codec() const { return _codec; } const QTextCodec* codec() const { return _codec; }
/** Sets the codec used to decode incoming characters. */ /** Sets the codec used to decode incoming characters. */
void setCodec(const QTextCodec*); void setCodec(const QTextCodec*);
/** /**
* Convenience method. * Convenience method.
* Returns true if the current codec used to decode incoming * Returns true if the current codec used to decode incoming
* characters is UTF-8 * characters is UTF-8
*/ */
bool utf8() const bool utf8() const
{ Q_ASSERT(_codec); return _codec->mibEnum() == 106; } { Q_ASSERT(_codec); return _codec->mibEnum() == 106; }
/** TODO Document me */ /** TODO Document me */
virtual char eraseChar() const; virtual char eraseChar() const;
/** /**
* Sets the key bindings used to key events * Sets the key bindings used to key events
* ( received through sendKeyEvent() ) into character * ( received through sendKeyEvent() ) into character
* streams to send to the terminal. * streams to send to the terminal.
*/ */
void setKeyBindings(const QString& name); void setKeyBindings(const QString& name);
/** /**
* Returns the name of the emulation's current key bindings. * Returns the name of the emulation's current key bindings.
* See setKeyBindings() * See setKeyBindings()
*/ */
QString keyBindings() const; QString keyBindings() const;
/** /**
* Copies the current image into the history and clears the screen. * Copies the current image into the history and clears the screen.
*/ */
virtual void clearEntireScreen() =0; virtual void clearEntireScreen() =0;
@ -209,7 +209,7 @@ public:
/** Resets the state of the terminal. */ /** Resets the state of the terminal. */
virtual void reset() =0; virtual void reset() =0;
/** /**
* Returns true if the active terminal program wants * Returns true if the active terminal program wants
* mouse input events. * mouse input events.
* *
@ -218,42 +218,42 @@ public:
*/ */
bool programUsesMouse() const; bool programUsesMouse() const;
public slots: public slots:
/** Change the size of the emulation's image */ /** Change the size of the emulation's image */
virtual void setImageSize(int lines, int columns); virtual void setImageSize(int lines, int columns);
/** /**
* Interprets a sequence of characters and sends the result to the terminal. * 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. * This is equivalent to calling sendKeyEvent() for each character in @p text in succession.
*/ */
virtual void sendText(const QString& text) = 0; virtual void sendText(const QString& text) = 0;
/** /**
* Interprets a key press event and emits the sendData() signal with * Interprets a key press event and emits the sendData() signal with
* the resulting character stream. * the resulting character stream.
*/ */
virtual void sendKeyEvent(QKeyEvent*); virtual void sendKeyEvent(QKeyEvent*);
/** /**
* Converts information about a mouse event into an xterm-compatible escape * Converts information about a mouse event into an xterm-compatible escape
* sequence and emits the character sequence via sendData() * sequence and emits the character sequence via sendData()
*/ */
virtual void sendMouseEvent(int buttons, int column, int line, int eventType); 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 * @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. * be treated as a null-terminated string and its length will be determined automatically.
*/ */
virtual void sendString(const char* string, int length = -1) = 0; virtual void sendString(const char* string, int length = -1) = 0;
/** /**
* Processes an incoming stream of characters. receiveData() decodes the incoming * Processes an incoming stream of characters. receiveData() decodes the incoming
* character buffer using the current codec(), and then calls receiveChar() for * 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 * receiveData() also starts a timer which causes the outputChanged() signal
* to be emitted when it expires. The timer allows multiple updates in quick * to be emitted when it expires. The timer allows multiple updates in quick
@ -266,8 +266,8 @@ public slots:
signals: 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. * standard input of the terminal.
* *
* @param data The buffer of data ready to be sent * @param data The buffer of data ready to be sent
@ -275,20 +275,20 @@ signals:
*/ */
void sendData(const char* data,int len); void sendData(const char* data,int len);
/** /**
* Requests that sending of input to the emulation * Requests that sending of input to the emulation
* from the terminal process be suspended or resumed. * from the terminal process be suspended or resumed.
* *
* @param suspend If true, requests that sending of * @param suspend If true, requests that sending of
* input from the terminal process' stdout be * input from the terminal process' stdout be
* suspended. Otherwise requests that sending of * suspended. Otherwise requests that sending of
* input be resumed. * input be resumed.
*/ */
void lockPtyRequest(bool suspend); void lockPtyRequest(bool suspend);
/** /**
* Requests that the pty used by the terminal process * Requests that the pty used by the terminal process
* be set to UTF 8 mode. * be set to UTF 8 mode.
* *
* TODO: More documentation * TODO: More documentation
*/ */
@ -316,7 +316,7 @@ signals:
*/ */
void changeTabTextColorRequest(int color); void changeTabTextColorRequest(int color);
/** /**
* This is emitted when the program running in the shell indicates whether or * This is emitted when the program running in the shell indicates whether or
* not it is interested in mouse events. * not it is interested in mouse events.
* *
@ -325,7 +325,7 @@ signals:
*/ */
void programUsesMouseChanged(bool usesMouse); void programUsesMouseChanged(bool usesMouse);
/** /**
* Emitted when the contents of the screen image change. * Emitted when the contents of the screen image change.
* The emulation buffers the updates from successive image changes, * The emulation buffers the updates from successive image changes,
* and only emits outputChanged() at sensible intervals when * and only emits outputChanged() at sensible intervals when
@ -335,14 +335,14 @@ signals:
* created with createWindow() to listen for this signal. * created with createWindow() to listen for this signal.
* *
* ScreenWindow objects created using createWindow() will emit their * 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(); 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 * 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" * 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 * 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 * 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 * 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. * @param title Specifies what to change.
* <ul> * <ul>
@ -359,16 +359,16 @@ signals:
* <li>2 - Set session title to @p newTitle</li> * <li>2 - Set session title to @p newTitle</li>
* <li>11 - Set the session's default background color to @p newTitle, * <li>11 - Set the session's default background color to @p newTitle,
* where @p newTitle can be an HTML-style string ("#RRGGBB") or a named * 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 * See http://doc.trolltech.com/4.2/qcolor.html#setNamedColor for more
* details. * details.
* </li> * </li>
* <li>31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)</li> * <li>31 - Supposedly treats @p newTitle as a URL and opens it (NOT IMPLEMENTED)</li>
* <li>32 - Sets the icon associated with the session. @p newTitle is the name * <li>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 * of the icon to use, which can be the name of any icon in the current KDE icon
* theme (eg: 'konsole', 'kate', 'folder_home')</li> * theme (eg: 'konsole', 'kate', 'folder_home')</li>
* </ul> * </ul>
* @param newTitle Specifies the new title * @param newTitle Specifies the new title
*/ */
void titleChanged(int title,const QString& newTitle); void titleChanged(int title,const QString& newTitle);
@ -379,9 +379,9 @@ signals:
*/ */
void imageSizeChanged(int lineCount , int columnCount); void imageSizeChanged(int lineCount , int columnCount);
/** /**
* Emitted when the terminal program requests to change various properties * 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 * A profile change command occurs when a special escape sequence, followed
* by a string containing a series of name and value pairs is received. * by a string containing a series of name and value pairs is received.
@ -392,7 +392,7 @@ signals:
*/ */
void profileChangeCommandReceived(const QString& text); void profileChangeCommandReceived(const QString& text);
/** /**
* Emitted when a flow control key combination ( Ctrl+S or Ctrl+Q ) is pressed. * 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 * @param suspendKeyPressed True if Ctrl+S was pressed to suspend output or Ctrl+Q to
* resume output. * resume output.
@ -402,21 +402,21 @@ signals:
protected: protected:
virtual void setMode(int mode) = 0; virtual void setMode(int mode) = 0;
virtual void resetMode(int mode) = 0; virtual void resetMode(int mode) = 0;
/** /**
* Processes an incoming character. See receiveData() * Processes an incoming character. See receiveData()
* @p ch A unicode character code. * @p ch A unicode character code.
*/ */
virtual void receiveChar(int ch); virtual void receiveChar(int ch);
/** /**
* Sets the active screen. The terminal has two screens, primary and alternate. * Sets the active screen. The terminal has two screens, primary and alternate.
* The primary screen is used by default. When certain interactive programs such * The primary screen is used by default. When certain interactive programs such
* as Vim are run, they trigger a switch to the alternate screen. * 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 * @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 enum EmulationCodec
{ {
@ -427,35 +427,35 @@ protected:
QList<ScreenWindow*> _windows; QList<ScreenWindow*> _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 // this is one of the elements in the screen[] array
Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell Screen* _screen[2]; // 0 = primary screen ( used by most programs, including the shell
// scrollbars are enabled in this mode ) // scrollbars are enabled in this mode )
// 1 = alternate ( used by vi , emacs etc. // 1 = alternate ( used by vi , emacs etc.
// scrollbars are not enabled in this mode ) // 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.) //the current text codec. (this allows for rendering of non-ASCII characters in text files etc.)
const QTextCodec* _codec; const QTextCodec* _codec;
QTextDecoder* _decoder; QTextDecoder* _decoder;
const KeyboardTranslator* _keyTranslator; // the keyboard layout const KeyboardTranslator* _keyTranslator; // the keyboard layout
protected slots: protected slots:
/** /**
* Schedules an update of attached views. * Schedules an update of attached views.
* Repeated calls to bufferedUpdate() in close succession will result in only a single update, * 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(); void bufferedUpdate();
private slots: private slots:
// triggered by timer, causes the emulation to send an updated screen image to each // triggered by timer, causes the emulation to send an updated screen image to each
// view // view
void showBulk(); void showBulk();
void usesMouseChanged(bool usesMouse); void usesMouseChanged(bool usesMouse);
@ -463,7 +463,7 @@ private:
bool _usesMouse; bool _usesMouse;
QTimer _bulkTimer1; QTimer _bulkTimer1;
QTimer _bulkTimer2; QTimer _bulkTimer2;
}; };
} }

@ -47,7 +47,7 @@ using namespace Konsole;
FilterChain::~FilterChain() FilterChain::~FilterChain()
{ {
QMutableListIterator<Filter*> iter(*this); QMutableListIterator<Filter*> iter(*this);
while ( iter.hasNext() ) while ( iter.hasNext() )
{ {
Filter* filter = iter.next(); Filter* filter = iter.next();
@ -141,7 +141,7 @@ void TerminalImageFilterChain::setImage(const Character* const image , int lines
PlainTextDecoder decoder; PlainTextDecoder decoder;
decoder.setTrailingWhitespace(false); decoder.setTrailingWhitespace(false);
// setup new shared buffers for the filters to process on // setup new shared buffers for the filters to process on
QString* newBuffer = new QString(); QString* newBuffer = new QString();
QList<int>* newLinePositions = new QList<int>(); QList<int>* newLinePositions = new QList<int>();
@ -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 // 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 // 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 // TODO - Use the "line wrapped" attribute associated with lines in a
// terminal image to avoid adding this imaginary character for wrapped // terminal image to avoid adding this imaginary character for wrapped
@ -219,7 +219,7 @@ void Filter::getLineColumn(int position , int& startLine , int& startColumn)
else else
nextLine = _linePositions->value(i+1); nextLine = _linePositions->value(i+1);
if ( _linePositions->value(i) <= position && position < nextLine ) if ( _linePositions->value(i) <= position && position < nextLine )
{ {
startLine = i; startLine = i;
startColumn = string_width(buffer()->mid(_linePositions->value(i),position - _linePositions->value(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) /*void Filter::addLine(const QString& text)
{ {
@ -249,7 +249,7 @@ void Filter::addHotSpot(HotSpot* spot)
for (int line = spot->startLine() ; line <= spot->endLine() ; line++) for (int line = spot->startLine() ; line <= spot->endLine() ; line++)
{ {
_hotspots.insert(line,spot); _hotspots.insert(line,spot);
} }
} }
QList<Filter::HotSpot*> Filter::hotSpots() const QList<Filter::HotSpot*> Filter::hotSpots() const
{ {
@ -267,12 +267,12 @@ Filter::HotSpot* Filter::hotSpotAt(int line , int column) const
while (spotIter.hasNext()) while (spotIter.hasNext())
{ {
HotSpot* spot = spotIter.next(); HotSpot* spot = spotIter.next();
if ( spot->startLine() == line && spot->startColumn() > column ) if ( spot->startLine() == line && spot->startColumn() > column )
continue; continue;
if ( spot->endLine() == line && spot->endColumn() < column ) if ( spot->endLine() == line && spot->endColumn() < column )
continue; continue;
return spot; return spot;
} }
@ -343,7 +343,7 @@ QStringList RegExpFilter::HotSpot::capturedTexts() const
return _capturedTexts; return _capturedTexts;
} }
void RegExpFilter::setRegExp(const QRegExp& regExp) void RegExpFilter::setRegExp(const QRegExp& regExp)
{ {
_searchText = regExp; _searchText = regExp;
} }
@ -386,14 +386,14 @@ void RegExpFilter::process()
endLine,endColumn); endLine,endColumn);
spot->setCapturedTexts(_searchText.capturedTexts()); spot->setCapturedTexts(_searchText.capturedTexts());
addHotSpot( spot ); addHotSpot( spot );
pos += _searchText.matchedLength(); pos += _searchText.matchedLength();
// if matchedLength == 0, the program will get stuck in an infinite loop // if matchedLength == 0, the program will get stuck in an infinite loop
if ( _searchText.matchedLength() == 0 ) if ( _searchText.matchedLength() == 0 )
pos = -1; pos = -1;
} }
} }
} }
RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn, RegExpFilter::HotSpot* RegExpFilter::newHotSpot(int startLine,int startColumn,
@ -425,16 +425,16 @@ QString UrlFilter::HotSpot::tooltip() const
const UrlType kind = urlType(); const UrlType kind = urlType();
if ( kind == StandardUrl ) if ( kind == StandardUrl )
return QString(); return QString();
else if ( kind == Email ) else if ( kind == Email )
return QString(); return QString();
else else
return QString(); return QString();
} }
UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const UrlFilter::HotSpot::UrlType UrlFilter::HotSpot::urlType() const
{ {
QString url = capturedTexts().first(); QString url = capturedTexts().first();
if ( FullUrlRegExp.exactMatch(url) ) if ( FullUrlRegExp.exactMatch(url) )
return StandardUrl; return StandardUrl;
else if ( EmailAddressRegExp.exactMatch(url) ) else if ( EmailAddressRegExp.exactMatch(url) )
@ -465,23 +465,23 @@ void UrlFilter::HotSpot::activate(const QString& actionName)
{ {
url.prepend("http://"); url.prepend("http://");
} }
} }
else if ( kind == Email ) else if ( kind == Email )
{ {
url.prepend("mailto:"); url.prepend("mailto:");
} }
_urlObject->emitActivated(url); _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 // used for finding URLs in the text, especially if they are very general and could match very long
// pieces of text. // pieces of text.
// Please be careful when altering them. // Please be careful when altering them.
//regexp matches: //regexp matches:
// full url: // full url:
// protocolname:// or www. followed by anything other than whitespaces, <, >, ' or ", and ends before whitespaces, <, >, ', ", ], !, comma and dot // 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<>'\"\\]]"); const QRegExp UrlFilter::FullUrlRegExp("(www\\.(?!\\.)|[a-z][a-z0-9+.-]*://)[^\\s<>'\"]+[^!,\\.\\s<>'\"\\]]");
// email address: // email address:
@ -551,7 +551,7 @@ QList<QAction*> UrlFilter::HotSpot::actions()
list << openAction; list << openAction;
list << copyAction; list << copyAction;
return list; return list;
} }
//#include "Filter.moc" //#include "Filter.moc"

@ -46,7 +46,7 @@ class Character;
* activate() method should be called. Depending on the type of hotspot this will trigger a suitable response. * 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. * 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. * actions() method.
* *
* Different subclasses of filter will return different types of hotspot. * 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. * 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. * 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. These actions may then be displayed in a popup menu or toolbar for example. * actions() method. These actions may then be displayed in a popup menu or toolbar for example.
*/ */
class HotSpot class HotSpot
{ {
public: public:
/** /**
* Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn) * Constructs a new hotspot which covers the area from (@p startLine,@p startColumn) to (@p endLine,@p endColumn)
* in a block of text. * in a block of text.
*/ */
@ -87,7 +87,7 @@ public:
Link, Link,
// this hotspot represents a marker // this hotspot represents a marker
Marker Marker
}; };
/** Returns the line when the hotspot area starts */ /** Returns the line when the hotspot area starts */
int startLine() const; int startLine() const;
@ -97,31 +97,31 @@ public:
int startColumn() const; int startColumn() const;
/** Returns the column on endLine() where the hotspot area ends */ /** Returns the column on endLine() where the hotspot area ends */
int endColumn() const; int endColumn() const;
/** /**
* Returns the type of the hotspot. This is usually used as a hint for views on how to represent * 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 * the hotspot graphically. eg. Link hotspots are typically underlined when the user mouses over them
*/ */
Type type() const; 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 * @param action The action to trigger. This is
* typically empty ( in which case the default action should be performed ) or * 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 * 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; virtual void activate(const QString& action = QString()) = 0;
/** /**
* Returns a list of actions associated with the hotspot which can be used in a * Returns a list of actions associated with the hotspot which can be used in a
* menu or toolbar * menu or toolbar
*/ */
virtual QList<QAction*> actions(); virtual QList<QAction*> actions();
/** /**
* Returns the text of a tooltip to be shown when the mouse moves over the hotspot, or * 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. * 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; virtual QString tooltip() const;
@ -135,7 +135,7 @@ public:
int _endLine; int _endLine;
int _endColumn; int _endColumn;
Type _type; Type _type;
}; };
/** Constructs a new filter. */ /** Constructs a new filter. */
@ -145,9 +145,9 @@ public:
/** Causes the filter to process the block of text currently in its internal buffer */ /** Causes the filter to process the block of text currently in its internal buffer */
virtual void process() = 0; virtual void process() = 0;
/** /**
* Empties the filters internal buffer and resets the line count back to 0. * Empties the filters internal buffer and resets the line count back to 0.
* All hotspots are deleted. * All hotspots are deleted.
*/ */
void reset(); void reset();
@ -163,7 +163,7 @@ public:
/** Returns the list of hotspots identified by the filter which occur on a given line */ /** Returns the list of hotspots identified by the filter which occur on a given line */
QList<HotSpot*> hotSpotsAtLine(int line) const; QList<HotSpot*> hotSpotsAtLine(int line) const;
/** /**
* TODO: Document me * TODO: Document me
*/ */
void setBuffer(const QString* buffer , const QList<int>* linePositions); void setBuffer(const QString* buffer , const QList<int>* linePositions);
@ -179,22 +179,22 @@ protected:
private: private:
QMultiHash<int,HotSpot*> _hotspots; QMultiHash<int,HotSpot*> _hotspots;
QList<HotSpot*> _hotspotList; QList<HotSpot*> _hotspotList;
const QList<int>* _linePositions; const QList<int>* _linePositions;
const QString* _buffer; 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. * instance for them.
* *
* Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression * Subclasses can reimplement newHotSpot() to return custom hotspot types when matches for the regular expression
* are found. * are found.
*/ */
class RegExpFilter : public Filter class RegExpFilter : public Filter
{ {
public: public:
/** /**
* Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text * Type of hotspot created by RegExpFilter. The capturedTexts() method can be used to find the text
* matched by the filter's regular expression. * matched by the filter's regular expression.
*/ */
@ -215,26 +215,26 @@ public:
/** Constructs a new regular expression filter */ /** Constructs a new regular expression filter */
RegExpFilter(); 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 * Regular expressions which match the empty string are treated as not matching
* anything. * anything.
*/ */
void setRegExp(const QRegExp& text); void setRegExp(const QRegExp& text);
/** Returns the regular expression which the filter searches for in blocks of text */ /** Returns the regular expression which the filter searches for in blocks of text */
QRegExp regExp() const; 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 * If regexp matches the empty string, then process() will return immediately
* without finding results. * without finding results.
*/ */
virtual void process(); virtual void process();
protected: protected:
/** /**
* Called when a match for the regular expression is encountered. Subclasses should reimplement this * Called when a match for the regular expression is encountered. Subclasses should reimplement this
* to return custom hotspot types * to return custom hotspot types
*/ */
@ -248,15 +248,15 @@ private:
class FilterObject; class FilterObject;
/** A filter which matches URLs in blocks of text */ /** A filter which matches URLs in blocks of text */
class UrlFilter : public RegExpFilter class UrlFilter : public RegExpFilter
{ {
Q_OBJECT Q_OBJECT
public: 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. * at the given URL when called.
*/ */
class HotSpot : public RegExpFilter::HotSpot class HotSpot : public RegExpFilter::HotSpot
{ {
public: public:
HotSpot(int startLine,int startColumn,int endLine,int endColumn); HotSpot(int startLine,int startColumn,int endLine,int endColumn);
@ -266,7 +266,7 @@ public:
virtual QList<QAction*> actions(); virtual QList<QAction*> actions();
/** /**
* Open a web browser at the current URL. The url itself can be determined using * Open a web browser at the current URL. The url itself can be determined using
* the capturedTexts() method. * the capturedTexts() method.
*/ */
@ -291,12 +291,12 @@ protected:
virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int); virtual RegExpFilter::HotSpot* newHotSpot(int,int,int,int);
private: private:
static const QRegExp FullUrlRegExp; static const QRegExp FullUrlRegExp;
static const QRegExp EmailAddressRegExp; static const QRegExp EmailAddressRegExp;
// combined OR of FullUrlRegExp and EmailAddressRegExp // combined OR of FullUrlRegExp and EmailAddressRegExp
static const QRegExp CompleteUrlRegExp; static const QRegExp CompleteUrlRegExp;
signals: signals:
void activated(const QUrl& url); void activated(const QUrl& url);
}; };
@ -316,11 +316,11 @@ signals:
void activated(const QUrl& url); 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. * 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 * 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 * 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. * process() to cause each filter in the chain to process the text.
@ -350,12 +350,12 @@ public:
/** Resets each filter in the chain */ /** Resets each filter in the chain */
void reset(); void reset();
/** /**
* Processes each filter in the chain * Processes each filter in the chain
*/ */
void process(); void process();
/** Sets the buffer for each filter in the chain to process. */ /** Sets the buffer for each filter in the chain to process. */
void setBuffer(const QString* buffer , const QList<int>* linePositions); void setBuffer(const QString* buffer , const QList<int>* linePositions);
/** Returns the first hotspot which occurs at @p line, @p column or 0 if no hotspot was found */ /** 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; Filter::HotSpot* hotSpotAt(int line , int column) const;
@ -382,7 +382,7 @@ public:
* @param lineProperties The line properties to set for image * @param lineProperties The line properties to set for image
*/ */
void setImage(const Character* const image , int lines , int columns, void setImage(const Character* const image , int lines , int columns,
const QVector<LineProperty>& lineProperties); const QVector<LineProperty>& lineProperties);
private: private:
QString* _buffer; QString* _buffer;

@ -93,7 +93,7 @@ HistoryFile::HistoryFile()
fileMap(0) fileMap(0)
{ {
if (tmpFile.open()) if (tmpFile.open())
{ {
tmpFile.setAutoRemove(true); tmpFile.setAutoRemove(true);
ion = tmpFile.handle(); ion = tmpFile.handle();
} }
@ -117,7 +117,7 @@ void HistoryFile::map()
//if mmap'ing fails, fall back to the read-lseek combination //if mmap'ing fails, fall back to the read-lseek combination
if ( fileMap == MAP_FAILED ) if ( fileMap == MAP_FAILED )
{ {
readWriteBalance = 0; readWriteBalance = 0;
fileMap = 0; fileMap = 0;
qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno; qDebug() << __FILE__ << __LINE__ << ": mmap'ing history failed. errno = " << errno;
} }
@ -140,7 +140,7 @@ void HistoryFile::add(const unsigned char* bytes, int len)
{ {
if ( fileMap ) if ( fileMap )
unmap(); unmap();
readWriteBalance++; readWriteBalance++;
int rc = 0; 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) void HistoryFile::get(unsigned char* bytes, int len, int loc)
{ {
//count number of get() calls vs. number of add() calls. //count number of get() calls vs. number of add() calls.
//If there are many more get() calls compared with add() //If there are many more get() calls compared with add()
//calls (decided by using MAP_THRESHOLD) then mmap the log //calls (decided by using MAP_THRESHOLD) then mmap the log
//file to improve performance. //file to improve performance.
readWriteBalance--; readWriteBalance--;
@ -166,7 +166,7 @@ void HistoryFile::get(unsigned char* bytes, int len, int loc)
bytes[i]=fileMap[loc+i]; bytes[i]=fileMap[loc+i];
} }
else else
{ {
int rc = 0; int rc = 0;
if (loc < 0 || len < 0 || loc + len > length) if (loc < 0 || len < 0 || loc + len > length)
@ -202,7 +202,7 @@ bool HistoryScroll::hasScroll()
// History Scroll File ////////////////////////////////////// // History Scroll File //////////////////////////////////////
/* /*
The history scroll makes a Row(Row(Cell)) from The history scroll makes a Row(Row(Cell)) from
two history buffers. The index buffer contains two history buffers. The index buffer contains
start of line positions which refere to the cells start of line positions which refere to the cells
@ -222,7 +222,7 @@ HistoryScrollFile::HistoryScrollFile(const QString &logFileName)
HistoryScrollFile::~HistoryScrollFile() HistoryScrollFile::~HistoryScrollFile()
{ {
} }
int HistoryScrollFile::getLines() int HistoryScrollFile::getLines()
{ {
return index.len() / sizeof(int); return index.len() / sizeof(int);
@ -247,11 +247,11 @@ int HistoryScrollFile::startOfLine(int lineno)
{ {
if (lineno <= 0) return 0; if (lineno <= 0) return 0;
if (lineno <= getLines()) if (lineno <= getLines())
{ {
if (!index.isMapped()) if (!index.isMapped())
index.map(); index.map();
int res; int res;
index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int)); index.get((unsigned char*)&res,sizeof(int),(lineno-1)*sizeof(int));
return res; return res;
@ -346,7 +346,7 @@ int HistoryScrollBuffer::getLineLen(int lineNumber)
bool HistoryScrollBuffer::isWrappedLine(int lineNumber) bool HistoryScrollBuffer::isWrappedLine(int lineNumber)
{ {
Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount ); Q_ASSERT( lineNumber >= 0 && lineNumber < _maxLineCount );
if (lineNumber < _usedLines) if (lineNumber < _usedLines)
{ {
//kDebug() << "Line" << lineNumber << "wrapped is" << _wrappedLine[bufferIndex(lineNumber)]; //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 ); Q_ASSERT( lineNumber < _maxLineCount );
if (lineNumber >= _usedLines) if (lineNumber >= _usedLines)
{ {
memset(buffer, 0, count * sizeof(Character)); memset(buffer, 0, count * sizeof(Character));
return; return;
} }
const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)]; const HistoryLine& line = _historyBuffer[bufferIndex(lineNumber)];
//kDebug() << "startCol " << startColumn; //kDebug() << "startCol " << startColumn;
@ -375,7 +375,7 @@ void HistoryScrollBuffer::getCells(int lineNumber, int startColumn, int count, C
//kDebug() << "count " << count; //kDebug() << "count " << count;
Q_ASSERT( startColumn <= line.size() - count ); Q_ASSERT( startColumn <= line.size() - count );
memcpy(buffer, line.constData() + startColumn , count * sizeof(Character)); memcpy(buffer, line.constData() + startColumn , count * sizeof(Character));
} }
@ -383,12 +383,12 @@ void HistoryScrollBuffer::setMaxNbLines(unsigned int lineCount)
{ {
HistoryLine* oldBuffer = _historyBuffer; HistoryLine* oldBuffer = _historyBuffer;
HistoryLine* newBuffer = new HistoryLine[lineCount]; HistoryLine* newBuffer = new HistoryLine[lineCount];
for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ ) for ( int i = 0 ; i < qMin(_usedLines,(int)lineCount) ; i++ )
{ {
newBuffer[i] = oldBuffer[bufferIndex(i)]; newBuffer[i] = oldBuffer[bufferIndex(i)];
} }
_usedLines = qMin(_usedLines,(int)lineCount); _usedLines = qMin(_usedLines,(int)lineCount);
_maxLineCount = lineCount; _maxLineCount = lineCount;
_head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1; _head = ( _usedLines == _maxLineCount ) ? 0 : _usedLines-1;
@ -411,7 +411,7 @@ int HistoryScrollBuffer::bufferIndex(int lineNumber)
return (_head+lineNumber+1) % _maxLineCount; return (_head+lineNumber+1) % _maxLineCount;
} }
else else
{ {
return lineNumber; return lineNumber;
} }
} }
@ -509,7 +509,7 @@ void HistoryScrollBlockArray::getCells(int lineno, int colno,
void HistoryScrollBlockArray::addCells(const Character a[], int count) void HistoryScrollBlockArray::addCells(const Character a[], int count)
{ {
Block *b = m_blockArray.lastBlock(); Block *b = m_blockArray.lastBlock();
if (!b) return; if (!b) return;
// put cells in block's data // put cells in block's data
@ -573,17 +573,17 @@ void* CompactHistoryBlockList::allocate(size_t size)
void CompactHistoryBlockList::deallocate(void* ptr) void CompactHistoryBlockList::deallocate(void* ptr)
{ {
Q_ASSERT( !list.isEmpty()); Q_ASSERT( !list.isEmpty());
int i=0; int i=0;
CompactHistoryBlock *block = list.at(i); CompactHistoryBlock *block = list.at(i);
while ( i<list.size() && !block->contains(ptr) ) while ( i<list.size() && !block->contains(ptr) )
{ {
i++; i++;
block=list.at(i); block=list.at(i);
} }
Q_ASSERT( i<list.size() ); Q_ASSERT( i<list.size() );
block->deallocate(); block->deallocate();
if (!block->isInUse()) if (!block->isInUse())
@ -605,16 +605,16 @@ void* CompactHistoryLine::operator new (size_t size, CompactHistoryBlockList& bl
return blockList.allocate(size); return blockList.allocate(size);
} }
CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList ) CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlockList& bList )
: blockList(bList), : blockList(bList),
formatLength(0) formatLength(0)
{ {
length=line.size(); length=line.size();
if (line.size() > 0) { if (line.size() > 0) {
formatLength=1; formatLength=1;
int k=1; int k=1;
// count number of different formats in this text line // count number of different formats in this text line
Character c = line[0]; Character c = line[0];
while ( k<length ) while ( k<length )
@ -626,22 +626,22 @@ CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlo
} }
k++; k++;
} }
//kDebug() << "number of different formats in string: " << formatLength; //kDebug() << "number of different formats in string: " << formatLength;
formatArray = (CharacterFormat*) blockList.allocate(sizeof(CharacterFormat)*formatLength); formatArray = (CharacterFormat*) blockList.allocate(sizeof(CharacterFormat)*formatLength);
Q_ASSERT (formatArray!=NULL); Q_ASSERT (formatArray!=NULL);
text = (quint16*) blockList.allocate(sizeof(quint16)*line.size()); text = (quint16*) blockList.allocate(sizeof(quint16)*line.size());
Q_ASSERT (text!=NULL); Q_ASSERT (text!=NULL);
length=line.size(); length=line.size();
formatLength=formatLength; formatLength=formatLength;
wrapped=false; wrapped=false;
// record formats and their positions in the format array // record formats and their positions in the format array
c=line[0]; c=line[0];
formatArray[0].setFormat ( c ); formatArray[0].setFormat ( c );
formatArray[0].startPos=0; // there's always at least 1 format (for the entire line, unless a change happens) formatArray[0].startPos=0; // there's always at least 1 format (for the entire line, unless a change happens)
k=1; // look for possible format changes k=1; // look for possible format changes
int j=1; int j=1;
while ( k<length && j<formatLength ) while ( k<length && j<formatLength )
@ -656,7 +656,7 @@ CompactHistoryLine::CompactHistoryLine ( const TextLine& line, CompactHistoryBlo
} }
k++; k++;
} }
// copy character values // copy character values
for ( int i=0; i<line.size(); i++ ) for ( int i=0; i<line.size(); i++ )
{ {
@ -674,7 +674,7 @@ CompactHistoryLine::~CompactHistoryLine()
blockList.deallocate(text); blockList.deallocate(text);
blockList.deallocate(formatArray); blockList.deallocate(formatArray);
} }
blockList.deallocate(this); blockList.deallocate(this);
} }
void CompactHistoryLine::getCharacter ( int index, Character &r ) void CompactHistoryLine::getCharacter ( int index, Character &r )
@ -919,7 +919,7 @@ const QString& HistoryTypeFile::getFileName() const
HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const
{ {
if (dynamic_cast<HistoryFile *>(old)) if (dynamic_cast<HistoryFile *>(old))
return old; // Unchanged. return old; // Unchanged.
HistoryScroll *newScroll = new HistoryScrollFile(m_fileName); HistoryScroll *newScroll = new HistoryScrollFile(m_fileName);
@ -946,7 +946,7 @@ HistoryScroll* HistoryTypeFile::scroll(HistoryScroll *old) const
} }
delete old; delete old;
return newScroll; return newScroll;
} }
int HistoryTypeFile::maximumLineCount() const int HistoryTypeFile::maximumLineCount() const

@ -70,7 +70,7 @@ private:
//pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed //pointer to start of mmap'ed file data, or 0 if the file is not mmap'ed
char* fileMap; char* fileMap;
//incremented whenver 'add' is called and decremented whenever //incremented whenver 'add' is called and decremented whenever
//'get' is called. //'get' is called.
//this is used to detect when a large number of lines are being read and processed from the history //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); void setMaxNbLines(unsigned int nbLines);
unsigned int maxNbLines() { return _maxLineCount; } unsigned int maxNbLines() { return _maxLineCount; }
private: private:
int bufferIndex(int lineNumber); int bufferIndex(int lineNumber);
@ -189,9 +189,9 @@ private:
HistoryLine* _historyBuffer; HistoryLine* _historyBuffer;
QBitArray _wrappedLine; QBitArray _wrappedLine;
int _maxLineCount; int _maxLineCount;
int _usedLines; int _usedLines;
int _head; int _head;
//QVector<histline*> m_histBuffer; //QVector<histline*> m_histBuffer;
//QBitArray m_wrappedLine; //QBitArray m_wrappedLine;
//unsigned int m_maxNbLines; //unsigned int m_maxNbLines;
@ -290,7 +290,7 @@ public:
class CompactHistoryBlock class CompactHistoryBlock
{ {
public: public:
CompactHistoryBlock(){ CompactHistoryBlock(){
blockLength = 4096*64; // 256kb blockLength = 4096*64; // 256kb
head = (quint8*) mmap(0, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0); head = (quint8*) mmap(0, blockLength, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
@ -299,12 +299,12 @@ public:
tail = blockStart = head; tail = blockStart = head;
allocCount=0; allocCount=0;
} }
virtual ~CompactHistoryBlock(){ virtual ~CompactHistoryBlock(){
//free(blockStart); //free(blockStart);
munmap(blockStart, blockLength); munmap(blockStart, blockLength);
} }
virtual unsigned int remaining(){ return blockStart+blockLength-tail;} virtual unsigned int remaining(){ return blockStart+blockLength-tail;}
virtual unsigned length() { return blockLength; } virtual unsigned length() { return blockLength; }
virtual void* allocate(size_t length); virtual void* allocate(size_t length);
@ -381,7 +381,7 @@ private:
bool hasDifferentColors(const TextLine& line) const; bool hasDifferentColors(const TextLine& line) const;
HistoryArray lines; HistoryArray lines;
CompactHistoryBlockList blockList; CompactHistoryBlockList blockList;
unsigned int _maxLineCount; unsigned int _maxLineCount;
}; };
@ -397,7 +397,7 @@ public:
/** /**
* Returns true if the history is enabled ( can store lines of output ) * Returns true if the history is enabled ( can store lines of output )
* or false otherwise. * or false otherwise.
*/ */
virtual bool isEnabled() const = 0; virtual bool isEnabled() const = 0;
/** /**
@ -428,7 +428,7 @@ class HistoryTypeBlockArray : public HistoryType
{ {
public: public:
HistoryTypeBlockArray(size_t size); HistoryTypeBlockArray(size_t size);
virtual bool isEnabled() const; virtual bool isEnabled() const;
virtual int maximumLineCount() const; virtual int maximumLineCount() const;
@ -438,7 +438,7 @@ protected:
size_t m_size; size_t m_size;
}; };
#if 1 #if 1
class HistoryTypeFile : public HistoryType class HistoryTypeFile : public HistoryType
{ {
public: public:
@ -461,10 +461,10 @@ class HistoryTypeBuffer : public HistoryType
public: public:
HistoryTypeBuffer(unsigned int nbLines); HistoryTypeBuffer(unsigned int nbLines);
virtual bool isEnabled() const; virtual bool isEnabled() const;
virtual int maximumLineCount() const; virtual int maximumLineCount() const;
virtual HistoryScroll* scroll(HistoryScroll *) const; virtual HistoryScroll* scroll(HistoryScroll *) const;
protected: protected:
@ -475,7 +475,7 @@ class CompactHistoryType : public HistoryType
{ {
public: public:
CompactHistoryType(unsigned int size); CompactHistoryType(unsigned int size);
virtual bool isEnabled() const; virtual bool isEnabled() const;
virtual int maximumLineCount() const; virtual int maximumLineCount() const;

@ -40,7 +40,7 @@ HistorySearch::~HistorySearch() {
void HistorySearch::search() { void HistorySearch::search() {
bool found = false; bool found = false;
if (! m_regExp.isEmpty()) if (! m_regExp.isEmpty())
{ {
if (m_forwards) { if (m_forwards) {
@ -48,10 +48,10 @@ void HistorySearch::search() {
} else { } else {
found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount()); found = search(0, 0, m_startColumn, m_startLine) || search(m_startColumn, m_startLine, -1, m_emulation->lineCount());
} }
if (found) { if (found) {
emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine); emit matchFound(m_foundStartColumn, m_foundStartLine, m_foundEndColumn, m_foundEndLine);
} }
else { else {
emit noMatchFound(); emit noMatchFound();
} }
@ -61,43 +61,43 @@ void HistorySearch::search() {
} }
bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) { bool HistorySearch::search(int startColumn, int startLine, int endColumn, int endLine) {
qDebug() << "search from" << startColumn << "," << startLine qDebug() << "search from" << startColumn << "," << startLine
<< "to" << endColumn << "," << endLine; << "to" << endColumn << "," << endLine;
int linesRead = 0; int linesRead = 0;
int linesToRead = endLine - startLine + 1; int linesToRead = endLine - startLine + 1;
qDebug() << "linesToRead:" << linesToRead; 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 // blocks of at most 10K lines so that we do not use unhealthy amounts of memory
int blockSize; int blockSize;
while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) { while ((blockSize = qMin(10000, linesToRead - linesRead)) > 0) {
QString string; QString string;
QTextStream searchStream(&string); QTextStream searchStream(&string);
PlainTextDecoder decoder; PlainTextDecoder decoder;
decoder.begin(&searchStream); decoder.begin(&searchStream);
decoder.setRecordLinePositions(true); decoder.setRecordLinePositions(true);
// Calculate lines to read and read them // Calculate lines to read and read them
int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1; int blockStartLine = m_forwards ? startLine + linesRead : endLine - linesRead - blockSize + 1;
int chunkEndLine = blockStartLine + blockSize - 1; int chunkEndLine = blockStartLine + blockSize - 1;
m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine); m_emulation->writeToStream(&decoder, blockStartLine, chunkEndLine);
// We search between startColumn in the first line of the string and endColumn in the last // 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 // line of the string. First we calculate the position (in the string) of endColumn in the
// last line of the string // last line of the string
int endPosition; 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. // empty line - we ignore that.
int numberOfLinesInString = decoder.linePositions().size() - 1; int numberOfLinesInString = decoder.linePositions().size() - 1;
if (numberOfLinesInString > 0 && endColumn > -1 ) if (numberOfLinesInString > 0 && endColumn > -1 )
{ {
endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn; endPosition = decoder.linePositions().at(numberOfLinesInString - 1) + endColumn;
} }
else else
{ {
endPosition = string.size(); endPosition = string.size();
} }
@ -116,12 +116,12 @@ bool HistorySearch::search(int startColumn, int startLine, int endColumn, int en
if (matchStart < startColumn) if (matchStart < startColumn)
matchStart = -1; matchStart = -1;
} }
if (matchStart > -1) if (matchStart > -1)
{ {
int matchEnd = matchStart + m_regExp.matchedLength() - 1; int matchEnd = matchStart + m_regExp.matchedLength() - 1;
qDebug() << "Found in string from" << matchStart << "to" << matchEnd; qDebug() << "Found in string from" << matchStart << "to" << matchEnd;
// Translate startPos and endPos to startColum, startLine, endColumn and endLine in history. // Translate startPos and endPos to startColum, startLine, endColumn and endLine in history.
int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart); int startLineNumberInString = findLineNumberInString(decoder.linePositions(), matchStart);
m_foundStartColumn = matchStart - decoder.linePositions().at(startLineNumberInString); 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_foundEndColumn" << m_foundEndColumn
<< "m_foundEndLine" << m_foundEndLine; << "m_foundEndLine" << m_foundEndLine;
return true; return true;
} }
linesRead += blockSize; linesRead += blockSize;
} }
qDebug() << "Not found"; qDebug() << "Not found";
return false; return false;
} }
int HistorySearch::findLineNumberInString(QList<int> linePositions, int position) { int HistorySearch::findLineNumberInString(QList<int> linePositions, int position) {
int lineNum = 0; int lineNum = 0;
@ -154,4 +154,4 @@ int HistorySearch::findLineNumberInString(QList<int> linePositions, int position
lineNum++; lineNum++;
return lineNum; return lineNum;
} }

@ -38,7 +38,7 @@ class HistorySearch : public QObject
Q_OBJECT Q_OBJECT
public: public:
explicit HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards, explicit HistorySearch(EmulationPtr emulation, QRegExp regExp, bool forwards,
int startColumn, int startLine, QObject* parent); int startColumn, int startLine, QObject* parent);
~HistorySearch(); ~HistorySearch();
@ -49,11 +49,11 @@ signals:
void matchFound(int startColumn, int startLine, int endColumn, int endLine); void matchFound(int startColumn, int startLine, int endColumn, int endLine);
void noMatchFound(); void noMatchFound();
private: private:
bool search(int startColumn, int startLine, int endColumn, int endLine); bool search(int startColumn, int startLine, int endColumn, int endLine);
int findLineNumberInString(QList<int> linePositions, int position); int findLineNumberInString(QList<int> linePositions, int position);
EmulationPtr m_emulation; EmulationPtr m_emulation;
QRegExp m_regExp; QRegExp m_regExp;
bool m_forwards; bool m_forwards;

@ -85,8 +85,8 @@ void KeyboardTranslatorManager::findTranslators()
QString translatorPath = listIter.next(); QString translatorPath = listIter.next();
QString name = QFileInfo(translatorPath).baseName(); QString name = QFileInfo(translatorPath).baseName();
if ( !_translators.contains(name) ) if ( !_translators.contains(name) )
_translators.insert(name,0); _translators.insert(name,0);
} }
@ -124,7 +124,7 @@ Q_UNUSED(translator);
QFile destination(path); QFile destination(path);
if (!destination.open(QIODevice::WriteOnly | QIODevice::Text)) if (!destination.open(QIODevice::WriteOnly | QIODevice::Text))
{ {
qDebug() << "Unable to save keyboard translation:" qDebug() << "Unable to save keyboard translation:"
<< destination.errorString(); << destination.errorString();
return false; return false;
} }
@ -132,7 +132,7 @@ Q_UNUSED(translator);
{ {
KeyboardTranslatorWriter writer(&destination); KeyboardTranslatorWriter writer(&destination);
writer.writeHeader(translator->description()); writer.writeHeader(translator->description());
QListIterator<KeyboardTranslator::Entry> iter(translator->entries()); QListIterator<KeyboardTranslator::Entry> iter(translator->entries());
while ( iter.hasNext() ) while ( iter.hasNext() )
writer.writeEntry(iter.next()); writer.writeEntry(iter.next());
@ -147,7 +147,7 @@ KeyboardTranslator* KeyboardTranslatorManager::loadTranslator(const QString& nam
{ {
const QString& path = findTranslatorPath(name); const QString& path = findTranslatorPath(name);
QFile source(path); QFile source(path);
if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text)) if (name.isEmpty() || !source.open(QIODevice::ReadOnly | QIODevice::Text))
return 0; 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 ) // 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 // 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 // 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 // assumed not to be a part of the sequence. The key sequence may contain whitespace
// //
// eg: "key Up+Shift : scrollLineUp" // eg: "key Up+Shift : scrollLineUp"
@ -250,7 +250,7 @@ KeyboardTranslatorReader::KeyboardTranslatorReader( QIODevice* source )
// read first entry (if any) // read first entry (if any)
readNext(); readNext();
} }
void KeyboardTranslatorReader::readNext() void KeyboardTranslatorReader::readNext()
{ {
// find next entry // find next entry
while ( !_source->atEnd() ) while ( !_source->atEnd() )
@ -270,7 +270,7 @@ void KeyboardTranslatorReader::readNext()
modifiers, modifiers,
modifierMask, modifierMask,
flags, flags,
flagMask); flagMask);
KeyboardTranslator::Command command = KeyboardTranslator::NoCommand; KeyboardTranslator::Command command = KeyboardTranslator::NoCommand;
QByteArray text; QByteArray text;
@ -302,12 +302,12 @@ void KeyboardTranslatorReader::readNext()
return; return;
} }
} }
_hasNext = false; _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 ) if ( text.compare("erase",Qt::CaseInsensitive) == 0 )
command = KeyboardTranslator::EraseCommand; command = KeyboardTranslator::EraseCommand;
@ -334,7 +334,7 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text,
KeyboardTranslator::States& flags, KeyboardTranslator::States& flags,
KeyboardTranslator::States& flagMask) KeyboardTranslator::States& flagMask)
{ {
bool isWanted = true; bool isWanted = true;
bool endOfItem = false; bool endOfItem = false;
QString buffer; QString buffer;
@ -386,13 +386,13 @@ bool KeyboardTranslatorReader::decodeSequence(const QString& text,
buffer.clear(); 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 // state ready for the next item
if ( ch == '+' ) if ( ch == '+' )
isWanted = true; isWanted = true;
else if ( ch == '-' ) else if ( ch == '-' )
isWanted = false; isWanted = false;
} }
modifiers = tempModifiers; modifiers = tempModifiers;
modifierMask = tempModifierMask; modifierMask = tempModifierMask;
@ -469,7 +469,7 @@ bool KeyboardTranslatorReader::hasNextEntry()
{ {
return _hasNext; return _hasNext;
} }
KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition , KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString& condition ,
const QString& result ) const QString& result )
{ {
QString entryString("keyboard \"temporary\"\nkey "); QString entryString("keyboard \"temporary\"\nkey ");
@ -497,7 +497,7 @@ KeyboardTranslator::Entry KeyboardTranslatorReader::createEntry( const QString&
return entry; return entry;
} }
KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry() KeyboardTranslator::Entry KeyboardTranslatorReader::nextEntry()
{ {
Q_ASSERT( _hasNext ); Q_ASSERT( _hasNext );
KeyboardTranslator::Entry entry = _nextEntry; KeyboardTranslator::Entry entry = _nextEntry;
@ -512,7 +512,7 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
{ {
QString text = line; QString text = line;
// remove comments // remove comments
bool inQuotes = false; bool inQuotes = false;
int commentPos = -1; int commentPos = -1;
for (int i=text.length()-1;i>=0;i--) for (int i=text.length()-1;i>=0;i--)
@ -527,7 +527,7 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
text.remove(commentPos,text.length()); text.remove(commentPos,text.length());
text = text.simplified(); text = text.simplified();
// title line: keyboard "title" // title line: keyboard "title"
static QRegExp title("keyboard\\s+\"(.*)\""); static QRegExp title("keyboard\\s+\"(.*)\"");
// key line: key KeySequence : "output" // key line: key KeySequence : "output"
@ -535,7 +535,7 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
static QRegExp key("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)"); static QRegExp key("key\\s+([\\w\\+\\s\\-\\*\\.]+)\\s*:\\s*(\"(.*)\"|\\w+)");
QList<Token> list; QList<Token> list;
if ( text.isEmpty() ) if ( text.isEmpty() )
{ {
return list; return list;
} }
@ -544,7 +544,7 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
{ {
Token titleToken = { Token::TitleKeyword , QString() }; Token titleToken = { Token::TitleKeyword , QString() };
Token textToken = { Token::TitleText , title.capturedTexts()[1] }; Token textToken = { Token::TitleText , title.capturedTexts()[1] };
list << titleToken << textToken; list << titleToken << textToken;
} }
else if ( key.exactMatch(text) ) else if ( key.exactMatch(text) )
@ -558,14 +558,14 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
{ {
// capturedTexts()[2] is a command // capturedTexts()[2] is a command
Token commandToken = { Token::Command , key.capturedTexts()[2] }; Token commandToken = { Token::Command , key.capturedTexts()[2] };
list << commandToken; list << commandToken;
} }
else else
{ {
// capturedTexts()[3] is the output string // capturedTexts()[3] is the output string
Token outputToken = { Token::OutputText , key.capturedTexts()[3] }; Token outputToken = { Token::OutputText , key.capturedTexts()[3] };
list << outputToken; list << outputToken;
} }
} }
else else
{ {
@ -575,7 +575,7 @@ QList<KeyboardTranslatorReader::Token> KeyboardTranslatorReader::tokenize(const
return list; return list;
} }
QList<QString> KeyboardTranslatorManager::allTranslators() QList<QString> KeyboardTranslatorManager::allTranslators()
{ {
if ( !_haveLoadedAll ) if ( !_haveLoadedAll )
{ {
@ -606,14 +606,14 @@ bool KeyboardTranslator::Entry::operator==(const Entry& rhs) const
_text == rhs._text; _text == rhs._text;
} }
bool KeyboardTranslator::Entry::matches(int keyCode , bool KeyboardTranslator::Entry::matches(int keyCode ,
Qt::KeyboardModifiers modifiers, Qt::KeyboardModifiers modifiers,
States testState) const States testState) const
{ {
if ( _keyCode != keyCode ) if ( _keyCode != keyCode )
return false; return false;
if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) ) if ( (modifiers & _modifierMask) != (_modifiers & _modifierMask) )
return false; return false;
// if modifiers is non-zero, the 'any modifier' state is implicit // 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) ) if ( (testState & _stateMask) != (_state & _stateMask) )
return false; 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. // any or no modifiers. In this context, the 'keypad' modifier does not count.
bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier; bool anyModifiersSet = modifiers != 0 && modifiers != Qt::KeypadModifier;
bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState; bool wantAnyModifier = _state & KeyboardTranslator::AnyModifierState;
@ -632,7 +632,7 @@ bool KeyboardTranslator::Entry::matches(int keyCode ,
if ( wantAnyModifier != anyModifiersSet ) if ( wantAnyModifier != anyModifiersSet )
return false; return false;
} }
return true; return true;
} }
QByteArray KeyboardTranslator::Entry::escapedText(bool expandWildCards,Qt::KeyboardModifiers modifiers) const 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' ) 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 ) } else if ( replacement != 0 )
{ {
result.remove(i,1); result.remove(i,1);
@ -709,7 +709,7 @@ QByteArray KeyboardTranslator::Entry::unescape(const QByteArray& input) const
unsigned charValue = 0; unsigned charValue = 0;
sscanf(hexDigits,"%x",&charValue); sscanf(hexDigits,"%x",&charValue);
replacement[0] = (char)charValue; replacement[0] = (char)charValue;
charsToRemove = 2 + strlen(hexDigits); charsToRemove = 2 + strlen(hexDigits);
} }
break; break;
@ -813,7 +813,7 @@ KeyboardTranslator::KeyboardTranslator(const QString& name)
{ {
} }
void KeyboardTranslator::setDescription(const QString& description) void KeyboardTranslator::setDescription(const QString& description)
{ {
_description = description; _description = description;
} }
@ -876,7 +876,7 @@ bool KeyboardTranslatorManager::deleteTranslator(const QString& name)
if ( QFile::remove(path) ) if ( QFile::remove(path) )
{ {
_translators.remove(name); _translators.remove(name);
return true; return true;
} }
else else
{ {

@ -39,7 +39,7 @@ class QTextStream;
namespace Konsole namespace Konsole
{ {
/** /**
* A convertor which maps between key sequences pressed by the user and the * A convertor which maps between key sequences pressed by the user and the
* character strings which should be sent to the terminal and commands * character strings which should be sent to the terminal and commands
* which should be invoked when those character sequences are pressed. * which should be invoked when those character sequences are pressed.
@ -55,7 +55,7 @@ namespace Konsole
class KeyboardTranslator class KeyboardTranslator
{ {
public: public:
/** /**
* The meaning of a particular key sequence may depend upon the state which * The meaning of a particular key sequence may depend upon the state which
* the terminal emulation is in. Therefore findEntry() may return a different * the terminal emulation is in. Therefore findEntry() may return a different
* Entry depending upon the state flags supplied. * Entry depending upon the state flags supplied.
@ -71,7 +71,7 @@ public:
* TODO More documentation * TODO More documentation
*/ */
NewLineState = 1, NewLineState = 1,
/** /**
* Indicates that the terminal is in 'Ansi' mode. * Indicates that the terminal is in 'Ansi' mode.
* TODO: More documentation * TODO: More documentation
*/ */
@ -82,10 +82,10 @@ public:
CursorKeysState = 4, CursorKeysState = 4,
/** /**
* Indicates that the alternate screen ( typically used by interactive programs * 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, AlternateScreenState = 8,
/** Indicates that any of the modifier keys is active. */ /** Indicates that any of the modifier keys is active. */
AnyModifierState = 16, AnyModifierState = 16,
/** Indicates that the numpad is in application mode. */ /** Indicates that the numpad is in application mode. */
ApplicationKeypadState = 32 ApplicationKeypadState = 32
@ -124,14 +124,14 @@ public:
class Entry class Entry
{ {
public: public:
/** /**
* Constructs a new entry for a keyboard translator. * Constructs a new entry for a keyboard translator.
*/ */
Entry(); Entry();
/** /**
* Returns true if this entry is null. * 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; bool isNull() const;
@ -140,15 +140,15 @@ public:
/** Sets the command associated with this entry. */ /** Sets the command associated with this entry. */
void setCommand(Command command); 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. * 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. * 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 * @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. * @param modifiers The keyboard modifiers being pressed.
*/ */
@ -158,7 +158,7 @@ public:
/** Sets the character sequence associated with this entry */ /** Sets the character sequence associated with this entry */
void setText(const QByteArray& text); void setText(const QByteArray& text);
/** /**
* Returns the character sequence associated with this entry, * Returns the character sequence associated with this entry,
* with any non-printable characters replaced with escape sequences. * with any non-printable characters replaced with escape sequences.
* *
@ -175,13 +175,13 @@ public:
/** Sets the character code associated with this entry */ /** Sets the character code associated with this entry */
void setKeyCode(int keyCode); 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 * If a modifier is set in modifierMask() but not in modifiers(), this means that the entry
* only matches when that modifier is NOT pressed. * only matches when that modifier is NOT pressed.
* *
* If a modifier is not set in modifierMask() then the entry matches whether the modifier * 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; Qt::KeyboardModifiers modifiers() const;
@ -193,13 +193,13 @@ public:
/** See modifierMask() and modifiers() */ /** See modifierMask() and modifiers() */
void setModifierMask( Qt::KeyboardModifiers modifiers ); void setModifierMask( Qt::KeyboardModifiers modifiers );
/** /**
* Returns a bitwise-OR of the enabled state flags associated with this entry. * 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 * 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. * matches when the terminal is NOT in that state.
* *
* If a state is not set in stateMask() then the entry matches whether the terminal * 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; States state() const;
@ -211,13 +211,13 @@ public:
/** See stateMask() */ /** See stateMask() */
void setStateMask( States mask ); 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 * as a QKeySequence
*/ */
//QKeySequence keySequence() const; //QKeySequence keySequence() const;
/** /**
* Returns this entry's conditions ( ie. its key code, modifier and state criteria ) * Returns this entry's conditions ( ie. its key code, modifier and state criteria )
* as a string. * as a string.
*/ */
@ -233,16 +233,16 @@ public:
QString resultToString(bool expandWildCards = false, QString resultToString(bool expandWildCards = false,
Qt::KeyboardModifiers modifiers = Qt::NoModifier) const; Qt::KeyboardModifiers modifiers = Qt::NoModifier) const;
/** /**
* Returns true if this entry matches the given key sequence, specified * Returns true if this entry matches the given key sequence, specified
* as a combination of @p keyCode , @p modifiers and @p state. * as a combination of @p keyCode , @p modifiers and @p state.
*/ */
bool matches( int keyCode , bool matches( int keyCode ,
Qt::KeyboardModifiers modifiers , Qt::KeyboardModifiers modifiers ,
States flags ) const; States flags ) const;
bool operator==(const Entry& rhs) const; bool operator==(const Entry& rhs) const;
private: private:
void insertModifier( QString& item , int modifier ) const; void insertModifier( QString& item , int modifier ) const;
void insertState( QString& item , int state ) const; void insertState( QString& item , int state ) const;
@ -260,7 +260,7 @@ public:
/** Constructs a new keyboard translator with the given @p name */ /** Constructs a new keyboard translator with the given @p name */
KeyboardTranslator(const QString& name); KeyboardTranslator(const QString& name);
//KeyboardTranslator(const KeyboardTranslator& other); //KeyboardTranslator(const KeyboardTranslator& other);
/** Returns the name of this keyboard translator */ /** Returns the name of this keyboard translator */
@ -278,7 +278,7 @@ public:
/** /**
* Looks for an entry in this keyboard translator which matches the given * Looks for an entry in this keyboard translator which matches the given
* key code, keyboard modifiers and state flags. * key code, keyboard modifiers and state flags.
* *
* Returns the matching entry if found or a null Entry otherwise ( ie. * Returns the matching entry if found or a null Entry otherwise ( ie.
* entry.isNull() will return true ) * entry.isNull() will return true )
* *
@ -286,11 +286,11 @@ public:
* @param modifiers A combination of modifiers * @param modifiers A combination of modifiers
* @param state Optional flags which specify the current state of the terminal * @param state Optional flags which specify the current state of the terminal
*/ */
Entry findEntry(int keyCode , Entry findEntry(int keyCode ,
Qt::KeyboardModifiers modifiers , Qt::KeyboardModifiers modifiers ,
States state = NoState) const; States state = NoState) const;
/** /**
* Adds an entry to this keyboard translator's table. Entries can be looked up according * Adds an entry to this keyboard translator's table. Entries can be looked up according
* to their key sequence using findEntry() * to their key sequence using findEntry()
*/ */
@ -321,8 +321,8 @@ private:
Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States) Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::States)
Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands) 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. * returns the entries found in it.
* *
* Usage example: * Usage example:
@ -342,7 +342,7 @@ Q_DECLARE_OPERATORS_FOR_FLAGS(KeyboardTranslator::Commands)
* if ( !reader.parseError() ) * if ( !reader.parseError() )
* { * {
* // parsing succeeded, do something with the translator * // parsing succeeded, do something with the translator
* } * }
* else * else
* { * {
* // parsing failed * // parsing failed
@ -355,18 +355,18 @@ public:
/** Constructs a new reader which parses the given @p source */ /** Constructs a new reader which parses the given @p source */
KeyboardTranslatorReader( QIODevice* source ); KeyboardTranslatorReader( QIODevice* source );
/** /**
* Returns the description text. * Returns the description text.
* TODO: More documentation * TODO: More documentation
*/ */
QString description() const; QString description() const;
/** Returns true if there is another entry in the source stream */ /** Returns true if there is another entry in the source stream */
bool hasNextEntry(); bool hasNextEntry();
/** Returns the next entry found in the source stream */ /** 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 * Returns true if an error occurred whilst parsing the input or
* false if no error occurred. * false if no error occurred.
*/ */
@ -376,7 +376,7 @@ public:
* Parses a condition and result string for a translator entry * Parses a condition and result string for a translator entry
* and produces a keyboard 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 , static KeyboardTranslator::Entry createEntry( const QString& condition ,
const QString& result ); const QString& result );
@ -397,7 +397,7 @@ private:
}; };
QList<Token> tokenize(const QString&); QList<Token> tokenize(const QString&);
void readNext(); void readNext();
bool decodeSequence(const QString& , bool decodeSequence(const QString& ,
int& keyCode, int& keyCode,
Qt::KeyboardModifiers& modifiers, Qt::KeyboardModifiers& modifiers,
Qt::KeyboardModifiers& modifierMask, Qt::KeyboardModifiers& modifierMask,
@ -419,23 +419,23 @@ private:
class KeyboardTranslatorWriter class KeyboardTranslatorWriter
{ {
public: public:
/** /**
* Constructs a new writer which saves data into @p destination. * Constructs a new writer which saves data into @p destination.
* The caller is responsible for closing the device when writing is complete. * The caller is responsible for closing the device when writing is complete.
*/ */
KeyboardTranslatorWriter(QIODevice* destination); KeyboardTranslatorWriter(QIODevice* destination);
~KeyboardTranslatorWriter(); ~KeyboardTranslatorWriter();
/** /**
* Writes the header for the keyboard translator. * Writes the header for the keyboard translator.
* @param description Description of the keyboard translator. * @param description Description of the keyboard translator.
*/ */
void writeHeader( const QString& description ); void writeHeader( const QString& description );
/** Writes a translator entry. */ /** Writes a translator entry. */
void writeEntry( const KeyboardTranslator::Entry& entry ); void writeEntry( const KeyboardTranslator::Entry& entry );
private: private:
QIODevice* _destination; QIODevice* _destination;
QTextStream* _writer; QTextStream* _writer;
}; };
@ -446,7 +446,7 @@ private:
class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager class KONSOLEPRIVATE_EXPORT KeyboardTranslatorManager
{ {
public: public:
/** /**
* Constructs a new KeyboardTranslatorManager and loads the list of * Constructs a new KeyboardTranslatorManager and loads the list of
* available keyboard translations. * available keyboard translations.
* *
@ -457,7 +457,7 @@ public:
~KeyboardTranslatorManager(); ~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. * already exists, it will be replaced by the new translator.
* *
* TODO: More documentation. * TODO: More documentation.
@ -474,18 +474,18 @@ public:
/** Returns the default translator for Konsole. */ /** Returns the default translator for Konsole. */
const KeyboardTranslator* defaultTranslator(); const KeyboardTranslator* defaultTranslator();
/** /**
* Returns the keyboard translator with the given name or 0 if no translator * Returns the keyboard translator with the given name or 0 if no translator
* with that name exists. * with that name exists.
* *
* The first time that a translator with a particular name is requested, * 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); const KeyboardTranslator* findTranslator(const QString& name);
/** /**
* Returns a list of the names of available keyboard translators. * 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. * translators is started.
*/ */
QList<QString> allTranslators(); QList<QString> allTranslators();
@ -495,15 +495,15 @@ public:
private: private:
static const QByteArray defaultTranslatorText; static const QByteArray defaultTranslatorText;
void findTranslators(); // locate the available translators 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 // with the given name
KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name); KeyboardTranslator* loadTranslator(QIODevice* device,const QString& name);
bool saveTranslator(const KeyboardTranslator* translator); bool saveTranslator(const KeyboardTranslator* translator);
QString findTranslatorPath(const QString& name); QString findTranslatorPath(const QString& name);
QHash<QString,KeyboardTranslator*> _translators; // maps translator-name -> KeyboardTranslator QHash<QString,KeyboardTranslator*> _translators; // maps translator-name -> KeyboardTranslator
// instance // instance
bool _haveLoadedAll; bool _haveLoadedAll;
@ -514,15 +514,15 @@ private:
inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; } inline int KeyboardTranslator::Entry::keyCode() const { return _keyCode; }
inline void KeyboardTranslator::Entry::setKeyCode(int keyCode) { _keyCode = 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; _modifiers = modifier;
} }
inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; } inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifiers() const { return _modifiers; }
inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask ) inline void KeyboardTranslator::Entry::setModifierMask( Qt::KeyboardModifiers mask )
{ {
_modifierMask = mask; _modifierMask = mask;
} }
inline Qt::KeyboardModifiers KeyboardTranslator::Entry::modifierMask() const { return _modifierMask; } 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 ) inline void KeyboardTranslator::Entry::setCommand( Command command )
{ {
_command = command; _command = command;
} }
inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; } inline KeyboardTranslator::Command KeyboardTranslator::Entry::command() const { return _command; }
inline void KeyboardTranslator::Entry::setText( const QByteArray& text ) inline void KeyboardTranslator::Entry::setText( const QByteArray& text )
{ {
_text = unescape(text); _text = unescape(text);
} }
inline int oneOrZero(int value) inline int oneOrZero(int value)
{ {
return value ? 1 : 0; 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; QByteArray expandedText = _text;
if (expandWildCards) if (expandWildCards)
{ {
int modifierValue = 1; 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::AltModifier) << 1;
modifierValue += oneOrZero(modifiers & Qt::ControlModifier) << 2; 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] == '*') if (expandedText[i] == '*')
expandedText[i] = '0' + modifierValue; expandedText[i] = '0' + modifierValue;
} }
} }
return expandedText; return expandedText;
} }
inline void KeyboardTranslator::Entry::setState( States state ) inline void KeyboardTranslator::Entry::setState( States state )
{ {
_state = state; _state = state;
} }
inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; } inline KeyboardTranslator::States KeyboardTranslator::Entry::state() const { return _state; }
inline void KeyboardTranslator::Entry::setStateMask( States stateMask ) inline void KeyboardTranslator::Entry::setStateMask( States stateMask )
{ {
_stateMask = stateMask; _stateMask = stateMask;
} }
inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; } inline KeyboardTranslator::States KeyboardTranslator::Entry::stateMask() const { return _stateMask; }

@ -83,7 +83,7 @@ bool Pty::flowControlEnabled() const
pty()->tcGetAttr(&ttmode); pty()->tcGetAttr(&ttmode);
return ttmode.c_iflag & IXOFF && return ttmode.c_iflag & IXOFF &&
ttmode.c_iflag & IXON; ttmode.c_iflag & IXON;
} }
qWarning() << "Unable to get flow control status, terminal not connected."; qWarning() << "Unable to get flow control status, terminal not connected.";
return false; return false;
} }
@ -110,7 +110,7 @@ void Pty::setUtf8Mode(bool enable)
void Pty::setErase(char erase) void Pty::setErase(char erase)
{ {
_eraseChar = erase; _eraseChar = erase;
if (pty()->masterFd() >= 0) if (pty()->masterFd() >= 0)
{ {
struct ::termios ttmode; struct ::termios ttmode;
@ -142,7 +142,7 @@ void Pty::addEnvironmentVariables(const QStringList& environment)
// split on the first '=' character // split on the first '=' character
int pos = pair.indexOf('='); int pos = pair.indexOf('=');
if ( pos >= 0 ) if ( pos >= 0 )
{ {
QString variable = pair.left(pos); QString variable = pair.left(pos);
@ -153,10 +153,10 @@ void Pty::addEnvironmentVariables(const QStringList& environment)
} }
} }
int Pty::start(const QString& program, int Pty::start(const QString& program,
const QStringList& programArguments, const QStringList& programArguments,
const QStringList& environment, const QStringList& environment,
ulong winid, ulong winid,
bool addToUtmp bool addToUtmp
//const QString& dbusService, //const QString& dbusService,
//const QString& dbusSession //const QString& dbusSession
@ -164,7 +164,7 @@ int Pty::start(const QString& program,
{ {
clearProgram(); 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 // name of the program to execute, so create a list consisting of all
// but the first argument to pass to setProgram() // but the first argument to pass to setProgram()
Q_ASSERT(programArguments.count() >= 1); Q_ASSERT(programArguments.count() >= 1);
@ -204,10 +204,10 @@ int Pty::start(const QString& program,
if (_eraseChar != 0) if (_eraseChar != 0)
ttmode.c_cc[VERASE] = _eraseChar; ttmode.c_cc[VERASE] = _eraseChar;
if (!pty()->tcSetAttr(&ttmode)) if (!pty()->tcSetAttr(&ttmode))
qWarning() << "Unable to set terminal attributes."; qWarning() << "Unable to set terminal attributes.";
pty()->setWinSize(_windowLines, _windowColumns); pty()->setWinSize(_windowLines, _windowColumns);
KProcess::start(); KProcess::start();
@ -218,6 +218,28 @@ int Pty::start(const QString& program,
return 0; 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) void Pty::setWriteable(bool writeable)
{ {
struct stat sbuf; struct stat sbuf;
@ -258,15 +280,15 @@ void Pty::sendData(const char* data, int length)
{ {
if (!length) if (!length)
return; return;
if (!pty()->write(data,length)) if (!pty()->write(data,length))
{ {
qWarning() << "Pty::doSendJobs - Could not send input data to terminal process."; qWarning() << "Pty::doSendJobs - Could not send input data to terminal process.";
return; return;
} }
} }
void Pty::dataReceived() void Pty::dataReceived()
{ {
QByteArray data = pty()->readAll(); QByteArray data = pty()->readAll();
emit receivedData(data.constData(),data.count()); emit receivedData(data.constData(),data.count());
@ -290,7 +312,7 @@ int Pty::foregroundProcessGroup() const
if ( pid != -1 ) if ( pid != -1 )
{ {
return pid; return pid;
} }
return 0; return 0;
} }
@ -298,9 +320,9 @@ int Pty::foregroundProcessGroup() const
void Pty::setupChildProcess() void Pty::setupChildProcess()
{ {
KPtyProcess::setupChildProcess(); KPtyProcess::setupChildProcess();
// reset all signal handlers // 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 // signals generated via key sequences such as Ctrl+C
// (which sends SIGINT) // (which sends SIGINT)
struct sigaction action; struct sigaction action;

@ -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 <robertknight@gmail.com> Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -43,8 +43,8 @@
namespace Konsole { namespace Konsole {
/** /**
* The Pty class is used to start the terminal process, * The Pty class is used to start the terminal process,
* send data to it, receive data from it and manipulate * send data to it, receive data from it and manipulate
* various properties of the pseudo-teletype interface * various properties of the pseudo-teletype interface
* used to communicate with the process. * used to communicate with the process.
* *
@ -53,26 +53,26 @@ namespace Konsole {
* send data to or receive data from the process. * send data to or receive data from the process.
* *
* To start the terminal process, call the start() method * 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 class Pty: public KPtyProcess
{ {
Q_OBJECT Q_OBJECT
public: public:
/** /**
* Constructs a new Pty. * Constructs a new Pty.
* *
* Connect to the sendData() slot and receivedData() signal to prepare * Connect to the sendData() slot and receivedData() signal to prepare
* for sending and receiving data from the terminal process. * 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. * name of the program to start and appropriate arguments.
*/ */
explicit Pty(QObject* parent = 0); explicit Pty(QObject* parent = 0);
/** /**
* Construct a process using an open pty master. * Construct a process using an open pty master.
* See KPtyProcess::KPtyProcess() * See KPtyProcess::KPtyProcess()
*/ */
@ -81,7 +81,7 @@ Q_OBJECT
~Pty(); ~Pty();
/** /**
* Starts the terminal process. * Starts the terminal process.
* *
* Returns 0 if the process was started successfully or non-zero * Returns 0 if the process was started successfully or non-zero
* otherwise. * otherwise.
@ -94,23 +94,28 @@ Q_OBJECT
* @param winid Specifies the value of the WINDOWID environment variable * @param winid Specifies the value of the WINDOWID environment variable
* in the process's environment. * in the process's environment.
* @param addToUtmp Specifies whether a utmp entry should be created for * @param addToUtmp Specifies whether a utmp entry should be created for
* the pty used. See K3Process::setUsePty() * the pty used. See K3Process::setUsePty()
* @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE * @param dbusService Specifies the value of the KONSOLE_DBUS_SERVICE
* environment variable in the process's environment. * environment variable in the process's environment.
* @param dbusSession Specifies the value of the KONSOLE_DBUS_SESSION * @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, int start( const QString& program,
const QStringList& arguments, const QStringList& arguments,
const QStringList& environment, const QStringList& environment,
ulong winid, ulong winid,
bool addToUtmp bool addToUtmp
); );
/**
* set properties for "EmptyPTY"
*/
void setEmptyPTYProperties();
/** TODO: Document me */ /** TODO: Document me */
void setWriteable(bool writeable); void setWriteable(bool writeable);
/** /**
* Enables or disables Xon/Xoff flow control. The flow control setting * Enables or disables Xon/Xoff flow control. The flow control setting
* may be changed later by a terminal application, so flowControlEnabled() * may be changed later by a terminal application, so flowControlEnabled()
* may not equal the value of @p on in the previous call to setFlowControlEnabled() * 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. */ /** Queries the terminal state and returns true if Xon/Xoff flow control is enabled. */
bool flowControlEnabled() const; 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. * used by this teletype.
*/ */
void setWindowSize(int lines, int cols); void setWindowSize(int lines, int cols);
/** Returns the size of the window used by this teletype. See setWindowSize() */ /** Returns the size of the window used by this teletype. See setWindowSize() */
QSize windowSize() const; QSize windowSize() const;
@ -144,7 +149,7 @@ Q_OBJECT
* 0 will be returned. * 0 will be returned.
*/ */
int foregroundProcessGroup() const; int foregroundProcessGroup() const;
public slots: public slots:
/** /**
@ -153,7 +158,7 @@ Q_OBJECT
void setUtf8Mode(bool on); 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. * output of the terminal process.
* *
* See K3Process::suspend() and K3Process::resume() * See K3Process::suspend() and K3Process::resume()
@ -162,9 +167,9 @@ Q_OBJECT
* otherwise processing is resumed. * otherwise processing is resumed.
*/ */
void lockPty(bool lock); 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() ) * teletype ( whose id is returned by foregroundProcessGroup() )
* *
* @param buffer Pointer to the data to send. * @param buffer Pointer to the data to send.
@ -182,14 +187,14 @@ Q_OBJECT
* @param length Length of @p buffer * @param length Length of @p buffer
*/ */
void receivedData(const char* buffer, int length); void receivedData(const char* buffer, int length);
protected: protected:
void setupChildProcess(); void setupChildProcess();
private slots: private slots:
// called when data is received from the terminal process // called when data is received from the terminal process
void dataReceived(); void dataReceived();
private: private:
void init(); void init();
@ -197,7 +202,7 @@ Q_OBJECT
// to the environment for the process // to the environment for the process
void addEnvironmentVariables(const QStringList& environment); void addEnvironmentVariables(const QStringList& environment);
int _windowColumns; int _windowColumns;
int _windowLines; int _windowLines;
char _eraseChar; char _eraseChar;
bool _xonXoff; bool _xonXoff;

@ -50,10 +50,10 @@ using namespace Konsole;
//Macro to convert x,y position on screen to position within an image. //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 //memory, so a position within the image could be represented as an
//offset from the beginning of the block. For efficiency reasons this //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, //Many internal parts of this class still use this representation for parameters and so on,
//notably moveImage() and clearImage(). //notably moveImage() and clearImage().
//This macro converts from an X,Y position into an image offset. //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 ); Q_ASSERT( n >= 0 );
// always delete at least one char // always delete at least one char
if (n == 0) if (n == 0)
n = 1; n = 1;
// if cursor is beyond the end of the line there is nothing to do // if cursor is beyond the end of the line there is nothing to do
if ( cuX >= screenLines[cuY].count() ) if ( cuX >= screenLines[cuY].count() )
return; return;
if ( cuX+n > screenLines[cuY].count() ) if ( cuX+n > screenLines[cuY].count() )
n = screenLines[cuY].count() - cuX; n = screenLines[cuY].count() - cuX;
Q_ASSERT( n >= 0 ); Q_ASSERT( n >= 0 );
@ -285,7 +285,7 @@ void Screen::restoreCursor()
{ {
cuX = qMin(savedState.cursorColumn,columns-1); cuX = qMin(savedState.cursorColumn,columns-1);
cuY = qMin(savedState.cursorLine,lines-1); cuY = qMin(savedState.cursorLine,lines-1);
currentRendition = savedState.rendition; currentRendition = savedState.rendition;
currentForeground = savedState.foreground; currentForeground = savedState.foreground;
currentBackground = savedState.background; currentBackground = savedState.background;
updateEffectiveRendition(); updateEffectiveRendition();
@ -307,7 +307,7 @@ void Screen::resizeImage(int new_lines, int new_columns)
// create new screen lines and copy from old to new // create new screen lines and copy from old to new
ImageLine* newScreenLines = new ImageLine[new_lines+1]; 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]; newScreenLines[i]=screenLines[i];
for (int i=lines;(i > 0) && (i<new_lines+1);i++) for (int i=lines;(i > 0) && (i<new_lines+1);i++)
newScreenLines[i].resize( new_columns ); newScreenLines[i].resize( new_columns );
@ -318,7 +318,7 @@ void Screen::resizeImage(int new_lines, int new_columns)
clearSelection(); clearSelection();
delete[] screenLines; delete[] screenLines;
screenLines = newScreenLines; screenLines = newScreenLines;
lines = new_lines; lines = new_lines;
@ -375,11 +375,11 @@ void Screen::setDefaultMargins()
*/ */
void Screen::reverseRendition(Character& p) const void Screen::reverseRendition(Character& p) const
{ {
CharacterColor f = p.foregroundColor; CharacterColor f = p.foregroundColor;
CharacterColor b = p.backgroundColor; CharacterColor b = p.backgroundColor;
p.foregroundColor = b; p.foregroundColor = b;
p.backgroundColor = f; //p->r &= ~RE_TRANSPARENT; p.backgroundColor = f; //p->r &= ~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() ); 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 length = qMin(columns,history->getLineLen(line));
const int destLineOffset = (line-startLine)*columns; const int destLineOffset = (line-startLine)*columns;
history->getCells(line,0,length,dest + destLineOffset); 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; dest[destLineOffset+column] = defaultChar;
// invert selected text // invert selected text
@ -420,9 +420,9 @@ void Screen::copyFromHistory(Character* dest, int startLine, int count) const
{ {
for (int column = 0; column < columns; column++) 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; int destLineStartIndex = (line-startLine)*columns;
for (int column = 0; column < columns; column++) for (int column = 0; column < columns; column++)
{ {
int srcIndex = srcLineStartIndex + column; int srcIndex = srcLineStartIndex + column;
int destIndex = destLineStartIndex + column; int destIndex = destLineStartIndex + column;
dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar); dest[destIndex] = screenLines[srcIndex/columns].value(srcIndex%columns,defaultChar);
// invert selected text // invert selected text
if (selBegin != -1 && isSelected(column,line + history->getLines())) 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; const int mergedLines = endLine - startLine + 1;
Q_ASSERT( size >= mergedLines * columns ); Q_ASSERT( size >= mergedLines * columns );
Q_UNUSED( size ); Q_UNUSED( size );
const int linesInHistoryBuffer = qBound(0,history->getLines()-startLine,mergedLines); 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 // copy lines from history buffer
if (linesInHistoryBuffer > 0) if (linesInHistoryBuffer > 0)
copyFromHistory(dest,startLine,linesInHistoryBuffer); copyFromHistory(dest,startLine,linesInHistoryBuffer);
// copy lines from screen buffer // copy lines from screen buffer
if (linesInScreenBuffer > 0) if (linesInScreenBuffer > 0)
@ -491,7 +491,7 @@ void Screen::getImage( Character* dest, int size, int startLine, int endLine ) c
QVector<LineProperty> Screen::getLineProperties( int startLine , int endLine ) const QVector<LineProperty> Screen::getLineProperties( int startLine , int endLine ) const
{ {
Q_ASSERT( startLine >= 0 ); Q_ASSERT( startLine >= 0 );
Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines ); Q_ASSERT( endLine >= startLine && endLine < history->getLines() + lines );
const int mergedLines = endLine-startLine+1; const int mergedLines = endLine-startLine+1;
@ -502,7 +502,7 @@ QVector<LineProperty> Screen::getLineProperties( int startLine , int endLine ) c
int index = 0; int index = 0;
// copy properties for lines in history // 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 //TODO Support for line properties other than wrapped lines
if (history->isWrappedLine(line)) if (history->isWrappedLine(line))
@ -556,7 +556,7 @@ void Screen::backspace()
if (screenLines[cuY].size() < cuX+1) if (screenLines[cuY].size() < cuX+1)
screenLines[cuY].resize(cuX+1); screenLines[cuY].resize(cuX+1);
if (BS_CLEARS) if (BS_CLEARS)
screenLines[cuY][cuX].character = ' '; screenLines[cuY][cuX].character = ' ';
} }
@ -566,8 +566,8 @@ void Screen::tab(int n)
if (n == 0) n = 1; if (n == 0) n = 1;
while((n > 0) && (cuX < columns-1)) while((n > 0) && (cuX < columns-1))
{ {
cursorRight(1); cursorRight(1);
while((cuX < columns-1) && !tabStops[cuX]) while((cuX < columns-1) && !tabStops[cuX])
cursorRight(1); cursorRight(1);
n--; n--;
} }
@ -602,20 +602,20 @@ void Screen::initTabStops()
// Arrg! The 1st tabstop has to be one longer than the other. // Arrg! The 1st tabstop has to be one longer than the other.
// i.e. the kids start counting from 0 instead of 1. // i.e. the kids start counting from 0 instead of 1.
// Other programs might behave correctly. Be aware. // 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); tabStops[i] = (i%8 == 0 && i != 0);
} }
void Screen::newLine() void Screen::newLine()
{ {
if (getMode(MODE_NewLine)) if (getMode(MODE_NewLine))
toStartOfLine(); toStartOfLine();
index(); index();
} }
void Screen::checkSelection(int from, int to) void Screen::checkSelection(int from, int to)
{ {
if (selBegin == -1) if (selBegin == -1)
return; return;
int scr_TL = loc(0, history->getLines()); int scr_TL = loc(0, history->getLines());
//Clear entire selection if it overlaps region [from, to] //Clear entire selection if it overlaps region [from, to]
@ -749,11 +749,11 @@ void Screen::scrollDown(int from, int n)
_scrolledLines += n; _scrolledLines += n;
//FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds. //FIXME: make sure `topMargin', `bottomMargin', `from', `n' is in bounds.
if (n <= 0) if (n <= 0)
return; return;
if (from > _bottomMargin) if (from > _bottomMargin)
return; return;
if (from + n > _bottomMargin) if (from + n > _bottomMargin)
n = _bottomMargin - from; n = _bottomMargin - from;
moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n)); moveImage(loc(0,from+n),loc(0,from),loc(columns-1,_bottomMargin-n));
clearImage(loc(0,from),loc(columns-1,from+n-1),' '); 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) void Screen::clearImage(int loca, int loce, char c)
{ {
int scr_TL=loc(0,history->getLines()); int scr_TL=loc(0,history->getLines());
//FIXME: check positions //FIXME: check positions
@ -851,8 +851,8 @@ void Screen::moveImage(int dest, int sourceBegin, int sourceEnd)
int lines=(sourceEnd-sourceBegin)/columns; int lines=(sourceEnd-sourceBegin)/columns;
//move screen image and line properties: //move screen image and line properties:
//the source and destination areas of the image may overlap, //the source and destination areas of the image may overlap,
//so it matters that we do the copy in the right order - //so it matters that we do the copy in the right order -
//forwards if dest < sourceBegin or backwards otherwise. //forwards if dest < sourceBegin or backwards otherwise.
//(search the web for 'memmove implementation' for details) //(search the web for 'memmove implementation' for details)
if (dest < sourceBegin) if (dest < sourceBegin)
@ -987,9 +987,9 @@ void Screen::setForeColor(int space, int color)
{ {
currentForeground = CharacterColor(space, color); currentForeground = CharacterColor(space, color);
if ( currentForeground.isValid() ) if ( currentForeground.isValid() )
updateEffectiveRendition(); updateEffectiveRendition();
else else
setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR); setForeColor(COLOR_SPACE_DEFAULT,DEFAULT_FORE_COLOR);
} }
@ -997,13 +997,13 @@ void Screen::setBackColor(int space, int color)
{ {
currentBackground = CharacterColor(space, color); currentBackground = CharacterColor(space, color);
if ( currentBackground.isValid() ) if ( currentBackground.isValid() )
updateEffectiveRendition(); updateEffectiveRendition();
else else
setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR); setBackColor(COLOR_SPACE_DEFAULT,DEFAULT_BACK_COLOR);
} }
void Screen::clearSelection() void Screen::clearSelection()
{ {
selBottomRight = -1; selBottomRight = -1;
selTopLeft = -1; selTopLeft = -1;
@ -1015,7 +1015,7 @@ void Screen::getSelectionStart(int& column , int& line) const
if ( selTopLeft != -1 ) if ( selTopLeft != -1 )
{ {
column = selTopLeft % columns; column = selTopLeft % columns;
line = selTopLeft / columns; line = selTopLeft / columns;
} }
else else
{ {
@ -1034,11 +1034,11 @@ void Screen::getSelectionEnd(int& column , int& line) const
{ {
column = cuX + getHistLines(); column = cuX + getHistLines();
line = cuY + getHistLines(); line = cuY + getHistLines();
} }
} }
void Screen::setSelectionStart(const int x, const int y, const bool mode) 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... */ /* FIXME, HACK to correct for x too far to the right... */
if (x == columns) selBegin--; 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) void Screen::setSelectionEnd( const int x, const int y)
{ {
if (selBegin == -1) if (selBegin == -1)
return; return;
int endPos = loc(x,y); int endPos = loc(x,y);
if (endPos < selBegin) if (endPos < selBegin)
{ {
@ -1062,7 +1062,7 @@ void Screen::setSelectionEnd( const int x, const int y)
else else
{ {
/* FIXME, HACK to correct for x too far to the right... */ /* FIXME, HACK to correct for x too far to the right... */
if (x == columns) if (x == columns)
endPos--; endPos--;
selTopLeft = selBegin; selTopLeft = selBegin;
@ -1113,7 +1113,7 @@ bool Screen::isSelectionValid() const
return selTopLeft >= 0 && selBottomRight >= 0; return selTopLeft >= 0 && selBottomRight >= 0;
} }
void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder , void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder ,
bool preserveLineBreaks) const bool preserveLineBreaks) const
{ {
if (!isSelectionValid()) if (!isSelectionValid())
@ -1121,11 +1121,11 @@ void Screen::writeSelectionToStream(TerminalCharacterDecoder* decoder ,
writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks); writeToStream(decoder,selTopLeft,selBottomRight,preserveLineBreaks);
} }
void Screen::writeToStream(TerminalCharacterDecoder* decoder, void Screen::writeToStream(TerminalCharacterDecoder* decoder,
int startIndex, int endIndex, int startIndex, int endIndex,
bool preserveLineBreaks) const bool preserveLineBreaks) const
{ {
int top = startIndex / columns; int top = startIndex / columns;
int left = startIndex % columns; int left = startIndex % columns;
int bottom = endIndex / columns; int bottom = endIndex / columns;
@ -1145,7 +1145,7 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder,
int copied = copyLineToStream( y, int copied = copyLineToStream( y,
start, start,
count, count,
decoder, decoder,
appendNewLine, appendNewLine,
preserveLineBreaks ); preserveLineBreaks );
@ -1153,25 +1153,25 @@ void Screen::writeToStream(TerminalCharacterDecoder* decoder,
// append a new line character. // append a new line character.
// //
// this makes it possible to 'select' a trailing new line character after // this makes it possible to 'select' a trailing new line character after
// the text on a line. // the text on a line.
if ( y == bottom && if ( y == bottom &&
copied < count ) copied < count )
{ {
Character newLineChar('\n'); Character newLineChar('\n');
decoder->decodeLine(&newLineChar,1,0); decoder->decodeLine(&newLineChar,1,0);
} }
} }
} }
int Screen::copyLineToStream(int line , int Screen::copyLineToStream(int line ,
int start, int start,
int count, int count,
TerminalCharacterDecoder* decoder, TerminalCharacterDecoder* decoder,
bool appendNewLine, bool appendNewLine,
bool preserveLineBreaks) const bool preserveLineBreaks) const
{ {
//buffer to hold characters for decoding //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 //element on each call to copyLineToStream
//(which is unnecessary since all elements will be overwritten anyway) //(which is unnecessary since all elements will be overwritten anyway)
static const int MAX_CHARS = 1024; static const int MAX_CHARS = 1024;
@ -1191,7 +1191,7 @@ int Screen::copyLineToStream(int line ,
// retrieve line from history buffer. It is assumed // retrieve line from history buffer. It is assumed
// that the history buffer does not store trailing white space // 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) if (count == -1)
{ {
count = lineLength-start; count = lineLength-start;
@ -1203,7 +1203,7 @@ int Screen::copyLineToStream(int line ,
// safety checks // safety checks
assert( start >= 0 ); assert( start >= 0 );
assert( count >= 0 ); assert( count >= 0 );
assert( (start+count) <= history->getLineLen(line) ); assert( (start+count) <= history->getLineLen(line) );
history->getCells(line,start,count,characterBuffer); history->getCells(line,start,count,characterBuffer);
@ -1233,7 +1233,7 @@ int Screen::copyLineToStream(int line ,
count = qBound(0,count,length-start); count = qBound(0,count,length-start);
Q_ASSERT( screenLine < lineProperties.count() ); Q_ASSERT( screenLine < lineProperties.count() );
currentLineProperties |= lineProperties[screenLine]; currentLineProperties |= lineProperties[screenLine];
} }
// add new line character at end // add new line character at end
@ -1246,8 +1246,8 @@ int Screen::copyLineToStream(int line ,
count++; count++;
} }
//decode line and write to text stream //decode line and write to text stream
decoder->decodeLine( (Character*) characterBuffer , decoder->decodeLine( (Character*) characterBuffer ,
count, currentLineProperties ); count, currentLineProperties );
return count; return count;

@ -52,21 +52,21 @@ class TerminalCharacterDecoder;
characters from the program currently running in the terminal. characters from the program currently running in the terminal.
From this stream it creates an image of characters which is ultimately From this stream it creates an image of characters which is ultimately
rendered by the display widget ( TerminalDisplay ). Some types of emulation 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 getImage() is used to retrieve the currently visible image
which is then used by the display widget to draw the output from the 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 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 scroll is specified using setScroll()
The output history can be retrieved using writeToStream() 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 setSelectionStart() and setSelectionEnd(). The selected text can be retrieved
using selectedText(). When getImage() is used to retrieve the visible image, 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 class Screen
{ {
@ -75,25 +75,25 @@ public:
Screen(int lines, int columns); Screen(int lines, int columns);
~Screen(); ~Screen();
// VT100/2 Operations // VT100/2 Operations
// Cursor Movement // 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. * top margin.
*/ */
void cursorUp(int n); void cursorUp(int n);
/** /**
* Move the cursor down by @p n lines. The cursor will stop at the * Move the cursor down by @p n lines. The cursor will stop at the
* bottom margin. * bottom margin.
*/ */
void cursorDown(int n); void cursorDown(int n);
/** /**
* Move the cursor to the left by @p n columns. * Move the cursor to the left by @p n columns.
* The cursor will stop at the first column. * The cursor will stop at the first column.
*/ */
void cursorLeft(int n); void cursorLeft(int n);
/** /**
* Move the cursor to the right by @p n columns. * Move the cursor to the right by @p n columns.
* The cursor will stop at the right-most column. * The cursor will stop at the right-most column.
*/ */
@ -107,28 +107,28 @@ public:
/** /**
* Sets the margins for scrolling the screen. * Sets the margins for scrolling the screen.
* *
* @param topLine The top 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. * @param bottomLine The bottom line of the new scrolling margin.
*/ */
void setMargins(int topLine , int bottomLine); 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; int topMargin() const;
/** Returns the bottom line of the scrolling region. */ /** Returns the bottom line of the scrolling region. */
int bottomMargin() const; int bottomMargin() const;
/** /**
* Resets the scrolling margins back to the top and bottom lines * Resets the scrolling margins back to the top and bottom lines
* of the screen. * of the screen.
*/ */
void setDefaultMargins(); 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 * flag is enabled then the cursor is returned to the leftmost
* column first. * column first.
* *
* Equivalent to NextLine() if the MODE_NewLine flag is set * Equivalent to NextLine() if the MODE_NewLine flag is set
* or index() otherwise. * or index() otherwise.
*/ */
void newLine(); void newLine();
/** /**
@ -137,7 +137,7 @@ public:
*/ */
void nextLine(); void nextLine();
/** /**
* Move the cursor down one line. If the cursor is on the bottom * Move the cursor down one line. If the cursor is on the bottom
* line of the scrolling region (as returned by bottomMargin()) the * line of the scrolling region (as returned by bottomMargin()) the
* scrolling region is scrolled up by one line instead. * scrolling region is scrolled up by one line instead.
@ -149,12 +149,12 @@ public:
* region is scrolled down by one line instead. * region is scrolled down by one line instead.
*/ */
void reverseIndex(); void reverseIndex();
/** /**
* Scroll the scrolling region of the screen up by @p n lines. * Scroll the scrolling region of the screen up by @p n lines.
* The scrolling region is initially the whole screen, but can be changed * The scrolling region is initially the whole screen, but can be changed
* using setMargins() * using setMargins()
*/ */
void scrollUp(int n); void scrollUp(int n);
/** /**
* Scroll the scrolling region of the screen down by @p n lines. * Scroll the scrolling region of the screen down by @p n lines.
@ -162,12 +162,12 @@ public:
* using setMargins() * using setMargins()
*/ */
void scrollDown(int n); 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) * Equivalent to setCursorX(0)
*/ */
void toStartOfLine(); void toStartOfLine();
/** /**
* Moves the cursor one column to the left and erases the character * Moves the cursor one column to the left and erases the character
* at the new cursor position. * at the new cursor position.
*/ */
@ -176,28 +176,28 @@ public:
void tab(int n = 1); void tab(int n = 1);
/** Moves the cursor @p n tab-stops to the left. */ /** Moves the cursor @p n tab-stops to the left. */
void backtab(int n); void backtab(int n);
// Editing // 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 * This is equivalent to over-writing @p n characters starting with the current
* cursor position with spaces. * 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); void eraseChars(int n);
/** /**
* Delete @p n characters beginning from the current cursor position. * Delete @p n characters beginning from the current cursor position.
* If @p n is 0 then one character is deleted. * If @p n is 0 then one character is deleted.
*/ */
void deleteChars(int n); void deleteChars(int n);
/** /**
* Insert @p n blank characters beginning from the current cursor position. * 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. * If @p n is 0 then one character is inserted.
*/ */
void insertChars(int n); void insertChars(int n);
/** /**
* Removes @p n lines beginning from the current cursor position. * Removes @p n lines 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 line is removed. * If @p n is 0 then one line is removed.
@ -211,14 +211,14 @@ public:
void insertLines(int n); void insertLines(int n);
/** Clears all the tab stops. */ /** Clears all the tab stops. */
void clearTabStops(); 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); void changeTabStop(bool set);
/** Resets (clears) the specified screen @p mode. */ /** Resets (clears) the specified screen @p mode. */
void resetMode(int mode); void resetMode(int mode);
/** Sets (enables) the specified screen @p mode. */ /** Sets (enables) the specified screen @p mode. */
void setMode(int mode); void setMode(int mode);
/** /**
* Saves the state of the specified screen @p mode. It can be restored * Saves the state of the specified screen @p mode. It can be restored
* using restoreMode() * using restoreMode()
*/ */
@ -227,19 +227,19 @@ public:
void restoreMode(int mode); void restoreMode(int mode);
/** Returns whether the specified screen @p mode is enabled or not .*/ /** Returns whether the specified screen @p mode is enabled or not .*/
bool getMode(int mode) const; bool getMode(int mode) const;
/** /**
* Saves the current position and appearance (text color and style) of the cursor. * Saves the current position and appearance (text color and style) of the cursor.
* It can be restored by calling restoreCursor() * It can be restored by calling restoreCursor()
*/ */
void saveCursor(); void saveCursor();
/** Restores the position and appearance of the cursor. See saveCursor() */ /** Restores the position and appearance of the cursor. See saveCursor() */
void restoreCursor(); 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(); 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. * the screen.
*/ */
void clearToEndOfScreen(); void clearToEndOfScreen();
@ -254,16 +254,16 @@ public:
void clearToEndOfLine(); void clearToEndOfLine();
/** Clears from the current cursor position to the beginning of the line. */ /** Clears from the current cursor position to the beginning of the line. */
void clearToBeginOfLine(); void clearToBeginOfLine();
/** Fills the entire screen with the letter 'E' */ /** Fills the entire screen with the letter 'E' */
void helpAlign(); 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. * of characters on the screen.
* *
* @see Character::rendition * @see Character::rendition
*/ */
void setRendition(int rendition); void setRendition(int rendition);
/** /**
* Disables the given @p rendition flag. Rendition flags control the appearance * Disables the given @p rendition flag. Rendition flags control the appearance
@ -272,8 +272,8 @@ public:
* @see Character::rendition * @see Character::rendition
*/ */
void resetRendition(int rendition); void resetRendition(int rendition);
/** /**
* Sets the cursor's foreground color. * Sets the cursor's foreground color.
* @param space The color space used by the @p color argument * @param space The color space used by the @p color argument
* @param color The new foreground color. The meaning of this depends on * @param color The new foreground color. The meaning of this depends on
@ -291,24 +291,24 @@ public:
* @see CharacterColor * @see CharacterColor
*/ */
void setBackColor(int space, int color); 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. * character's rendition flags back to the default settings.
*/ */
void setDefaultRendition(); void setDefaultRendition();
/** Returns the column which the cursor is positioned at. */ /** Returns the column which the cursor is positioned at. */
int getCursorX() const; int getCursorX() const;
/** Returns the line which the cursor is positioned on. */ /** Returns the line which the cursor is positioned on. */
int getCursorY() const; int getCursorY() const;
/** Clear the entire screen and move the cursor to the home position. /** Clear the entire screen and move the cursor to the home position.
* Equivalent to calling clearEntireScreen() followed by home(). * Equivalent to calling clearEntireScreen() followed by home().
*/ */
void clear(); void clear();
/** /**
* Sets the position of the cursor to the 'home' position at the top-left * 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(); void home();
/** /**
@ -325,41 +325,41 @@ public:
* <li>New line mode is disabled. TODO Document me</li> * <li>New line mode is disabled. TODO Document me</li>
* </ul> * </ul>
* *
* 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. * otherwise they are unaltered.
*/ */
void reset(bool clearScreen = true); 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 * 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. * line below the current one.
* *
* If the MODE_Insert screen mode is currently enabled then the character * If the MODE_Insert screen mode is currently enabled then the character
* is inserted at the current cursor position, otherwise it will replace the * is inserted at the current cursor position, otherwise it will replace the
* character already at the current cursor position. * character already at the current cursor position.
*/ */
void displayCharacter(unsigned short c); void displayCharacter(unsigned short c);
// Do composition with last shown character FIXME: Not implemented yet for KDE 4 // Do composition with last shown character FIXME: Not implemented yet for KDE 4
void compose(const QString& compose); 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, * 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 * existing lines are not truncated. This prevents characters from being lost
* if the terminal display is resized smaller and then larger again. * 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 * screen size. Tab stops are also reset and the current selection is
* cleared. * cleared.
*/ */
void resizeImage(int new_lines, int new_columns); 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 * The result is an array of Characters of size [getLines()][getColumns()] which
* must be freed by the caller after use. * must be freed by the caller after use.
* *
@ -370,38 +370,38 @@ public:
*/ */
void getImage( Character* dest , int size , int startLine , int endLine ) const; void getImage( Character* dest , int size , int startLine , int endLine ) const;
/** /**
* Returns the additional attributes associated with lines in the image. * 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, * line is wrapped,
* other attributes control the size of characters in the line. * other attributes control the size of characters in the line.
*/ */
QVector<LineProperty> getLineProperties( int startLine , int endLine ) const; QVector<LineProperty> getLineProperties( int startLine , int endLine ) const;
/** Return the number of lines. */ /** Return the number of lines. */
int getLines() const int getLines() const
{ return lines; } { return lines; }
/** Return the number of columns. */ /** Return the number of columns. */
int getColumns() const int getColumns() const
{ return columns; } { return columns; }
/** Return the number of lines in the history buffer. */ /** Return the number of lines in the history buffer. */
int getHistLines() const; int getHistLines() const;
/** /**
* Sets the type of storage used to keep lines in the history. * Sets the type of storage used to keep lines in the history.
* If @p copyPreviousScroll is true then the contents of the previous * If @p copyPreviousScroll is true then the contents of the previous
* history buffer are copied into the new scroll. * history buffer are copied into the new scroll.
*/ */
void setScroll(const HistoryType& , bool copyPreviousScroll = true); void setScroll(const HistoryType& , bool copyPreviousScroll = true);
/** Returns the type of storage used to keep lines in the history. */ /** Returns the type of storage used to keep lines in the history. */
const HistoryType& getScroll() const; const HistoryType& getScroll() const;
/** /**
* Returns true if this screen keeps lines that are scrolled off the screen * Returns true if this screen keeps lines that are scrolled off the screen
* in a history buffer. * in a history buffer.
*/ */
bool hasScroll() const; bool hasScroll() const;
/** /**
* Sets the start of the selection. * Sets the start of the selection.
* *
* @param column The column index of the first character in 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. * @param blockSelectionMode True if the selection is in column mode.
*/ */
void setSelectionStart(const int column, const int line, const bool blockSelectionMode); void setSelectionStart(const int column, const int line, const bool blockSelectionMode);
/** /**
* Sets the end of the current selection. * Sets the end of the current selection.
* *
* @param column The column index of the last character in the 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); void setSelectionEnd(const int column, const int line);
/** /**
* Retrieves the start of the selection or the cursor position if there * Retrieves the start of the selection or the cursor position if there
* is no selection. * is no selection.
*/ */
void getSelectionStart(int& column , int& line) const; void getSelectionStart(int& column , int& line) const;
/** /**
* Retrieves the end of the selection or the cursor position if there * Retrieves the end of the selection or the cursor position if there
* is no selection. * is no selection.
@ -433,19 +433,19 @@ public:
/** Clears the current selection */ /** Clears the current selection */
void clearSelection(); void clearSelection();
/** /**
* Returns true if the character at (@p column, @p line) is part of the * 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; bool isSelected(const int column,const int line) const;
/** /**
* Convenience method. Returns the currently selected text. * Convenience method. Returns the currently selected text.
* @param preserveLineBreaks Specifies whether new line characters should * @param preserveLineBreaks Specifies whether new line characters should
* be inserted into the returned text at the end of each terminal line. * be inserted into the returned text at the end of each terminal line.
*/ */
QString selectedText(bool preserveLineBreaks) const; QString selectedText(bool preserveLineBreaks) const;
/** /**
* Copies part of the output to a stream. * Copies part of the output to a stream.
* *
@ -459,11 +459,11 @@ public:
* Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY * Copies the selected characters, set using @see setSelBeginXY and @see setSelExtentXY
* into a stream. * into a stream.
* *
* @param decoder A decoder which converts terminal characters into text. * @param decoder A decoder which converts terminal characters into text.
* PlainTextDecoder is the most commonly used decoder which converts characters * PlainTextDecoder is the most commonly used decoder which converts characters
* into plain text with no formatting. * into plain text with no formatting.
* @param preserveLineBreaks Specifies whether new line characters should * @param preserveLineBreaks Specifies whether new line characters should
* be inserted into the returned text at the end of each terminal line. * be inserted into the returned text at the end of each terminal line.
*/ */
void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool void writeSelectionToStream(TerminalCharacterDecoder* decoder , bool
preserveLineBreaks = true) const; preserveLineBreaks = true) const;
@ -480,15 +480,15 @@ public:
*/ */
void checkSelection(int from, int to); void checkSelection(int from, int to);
/** /**
* Sets or clears an attribute of the current line. * Sets or clears an attribute of the current line.
* *
* @param property The attribute to set or clear * @param property The attribute to set or clear
* Possible properties are: * Possible properties are:
* LINE_WRAPPED: Specifies that the line is wrapped. * LINE_WRAPPED: Specifies that the line is wrapped.
* LINE_DOUBLEWIDTH: Specifies that the characters in the current line * LINE_DOUBLEWIDTH: Specifies that the characters in the current line
* should be double the normal width. * 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. * should be double the normal height.
* Double-height lines are formed of two lines containing the same characters, * Double-height lines are formed of two lines containing the same characters,
* with both having the LINE_DOUBLEHEIGHT attribute. * with both having the LINE_DOUBLEHEIGHT attribute.
@ -499,24 +499,24 @@ public:
*/ */
void setLineProperty(LineProperty property , bool enable); void setLineProperty(LineProperty property , bool enable);
/** /**
* Returns the number of lines that the image has been scrolled up or down by, * Returns the number of lines that the image has been scrolled up or down by,
* since the last call to resetScrolledLines(). * since the last call to resetScrolledLines().
* *
* a positive return value indicates that the image has been scrolled up, * 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; int scrolledLines() const;
/** /**
* Returns the region of the image which was last scrolled. * 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. * bottom margin when the last scroll occurred.
*/ */
QRect lastScrolledRegion() const; QRect lastScrolledRegion() const;
/** /**
* Resets the count of the number of lines that the image has been scrolled up or down by, * Resets the count of the number of lines that the image has been scrolled up or down by,
* see scrolledLines() * see scrolledLines()
*/ */
@ -529,7 +529,7 @@ public:
* *
* If the history is not unlimited then it will drop * If the history is not unlimited then it will drop
* the oldest lines of output if new lines are added when * the oldest lines of output if new lines are added when
* it is full. * it is full.
*/ */
int droppedLines() const; int droppedLines() const;
@ -539,32 +539,32 @@ public:
*/ */
void resetDroppedLines(); void resetDroppedLines();
/** /**
* Fills the buffer @p dest with @p count instances of the default (ie. blank) * Fills the buffer @p dest with @p count instances of the default (ie. blank)
* Character style. * Character style.
*/ */
static void fillWithDefaultChar(Character* dest, int count); 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, //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 //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 // history->getLines() + lines - 1
//start - the first column on the line to copy //start - the first column on the line to copy
//count - the number of characters 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 //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 //appendNewLine - if true a new line character (\n) is appended to the end of the line
int copyLineToStream(int line, int copyLineToStream(int line,
int start, int start,
int count, int count,
TerminalCharacterDecoder* decoder, TerminalCharacterDecoder* decoder,
bool appendNewLine, bool appendNewLine,
bool preserveLineBreaks) const; bool preserveLineBreaks) const;
//fills a section of the screen image with the character 'c' //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 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. //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 //NOTE: moveImage() can only move whole lines
void moveImage(int dest, int sourceBegin, int sourceEnd); 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); void scrollUp(int from, int i);
// scroll down 'i' lines in current region, clearing the top 'i' lines // scroll down 'i' lines in current region, clearing the top 'i' lines
void scrollDown(int from, int i); void scrollDown(int from, int i);
@ -591,7 +591,7 @@ private:
bool isSelectionValid() const; bool isSelectionValid() const;
// copies text from 'startIndex' to 'endIndex' to a stream // copies text from 'startIndex' to 'endIndex' to a stream
// startIndex and endIndex are positions generated using the loc(x,y) macro // 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; int endIndex, bool preserveLineBreaks = true) const;
// copies 'count' lines from the screen buffer into 'dest', // copies 'count' lines from the screen buffer into 'dest',
// starting from 'startLine', where 0 is the first line in the screen buffer // starting from 'startLine', where 0 is the first line in the screen buffer
@ -613,11 +613,11 @@ private:
int _droppedLines; int _droppedLines;
QVarLengthArray<LineProperty,64> lineProperties; QVarLengthArray<LineProperty,64> lineProperties;
// history buffer --------------- // history buffer ---------------
HistoryScroll* history; HistoryScroll* history;
// cursor location // cursor location
int cuX; int cuX;
int cuY; int cuY;
@ -625,7 +625,7 @@ private:
// cursor color and rendition info // cursor color and rendition info
CharacterColor currentForeground; CharacterColor currentForeground;
CharacterColor currentBackground; CharacterColor currentBackground;
quint8 currentRendition; quint8 currentRendition;
// margins ---------------- // margins ----------------
int _topMargin; int _topMargin;
@ -650,7 +650,7 @@ private:
CharacterColor effectiveBackground; // the cu_* variables above CharacterColor effectiveBackground; // the cu_* variables above
quint8 effectiveRendition; // to speed up operation quint8 effectiveRendition; // to speed up operation
class SavedState class SavedState
{ {
public: public:
SavedState() SavedState()
@ -663,7 +663,7 @@ private:
CharacterColor background; CharacterColor background;
}; };
SavedState savedState; SavedState savedState;
// last position where we added a character // last position where we added a character
int lastPos; int lastPos;

@ -59,7 +59,7 @@ Character* ScreenWindow::getImage()
{ {
// reallocate internal buffer if the window size has changed // reallocate internal buffer if the window size has changed
int size = windowLines() * windowColumns(); int size = windowLines() * windowColumns();
if (_windowBuffer == 0 || _windowBufferSize != size) if (_windowBuffer == 0 || _windowBufferSize != size)
{ {
delete[] _windowBuffer; delete[] _windowBuffer;
_windowBufferSize = size; _windowBufferSize = size;
@ -69,11 +69,11 @@ Character* ScreenWindow::getImage()
if (!_bufferNeedsUpdate) if (!_bufferNeedsUpdate)
return _windowBuffer; return _windowBuffer;
_screen->getImage(_windowBuffer,size, _screen->getImage(_windowBuffer,size,
currentLine(),endWindowLine()); 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 // case there will be an unused area which needs to be filled
// with blank characters // with blank characters
fillUnusedArea(); fillUnusedArea();
@ -90,10 +90,10 @@ void ScreenWindow::fillUnusedArea()
int unusedLines = windowEndLine - screenEndLine; int unusedLines = windowEndLine - screenEndLine;
int charsToFill = unusedLines * windowColumns(); 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 // goes beyond the end of the screen, the index of the line at the end
// of the screen. // of the screen.
// //
@ -108,7 +108,7 @@ int ScreenWindow::endWindowLine() const
QVector<LineProperty> ScreenWindow::getLineProperties() QVector<LineProperty> ScreenWindow::getLineProperties()
{ {
QVector<LineProperty> result = _screen->getLineProperties(currentLine(),endWindowLine()); QVector<LineProperty> result = _screen->getLineProperties(currentLine(),endWindowLine());
if (result.count() != windowLines()) if (result.count() != windowLines())
result.resize(windowLines()); result.resize(windowLines());
@ -133,7 +133,7 @@ void ScreenWindow::getSelectionEnd( int& column , int& line )
void ScreenWindow::setSelectionStart( int column , int line , bool columnMode ) void ScreenWindow::setSelectionStart( int column , int line , bool columnMode )
{ {
_screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode); _screen->setSelectionStart( column , qMin(line + currentLine(),endWindowLine()) , columnMode);
_bufferNeedsUpdate = true; _bufferNeedsUpdate = true;
emit selectionChanged(); emit selectionChanged();
} }
@ -165,7 +165,7 @@ void ScreenWindow::setWindowLines(int lines)
} }
int ScreenWindow::windowLines() const int ScreenWindow::windowLines() const
{ {
return _windowLines; return _windowLines;
} }
int ScreenWindow::windowColumns() const int ScreenWindow::windowColumns() const
@ -186,11 +186,11 @@ int ScreenWindow::columnCount() const
QPoint ScreenWindow::cursorPosition() const QPoint ScreenWindow::cursorPosition() const
{ {
QPoint position; QPoint position;
position.setX( _screen->getCursorX() ); position.setX( _screen->getCursorX() );
position.setY( _screen->getCursorY() ); position.setY( _screen->getCursorY() );
return position; return position;
} }
int ScreenWindow::currentLine() const int ScreenWindow::currentLine() const
@ -206,7 +206,7 @@ void ScreenWindow::scrollBy( RelativeScrollMode mode , int amount )
} }
else if ( mode == ScrollPages ) else if ( mode == ScrollPages )
{ {
scrollTo( currentLine() + amount * ( windowLines() / 2 ) ); scrollTo( currentLine() + amount * ( windowLines() / 2 ) );
} }
} }
@ -247,7 +247,7 @@ int ScreenWindow::scrollCount() const
return _scrollCount; return _scrollCount;
} }
void ScreenWindow::resetScrollCount() void ScreenWindow::resetScrollCount()
{ {
_scrollCount = 0; _scrollCount = 0;
} }
@ -267,18 +267,18 @@ void ScreenWindow::notifyOutputChanged()
// move window to the bottom of the screen and update scroll count // move window to the bottom of the screen and update scroll count
// if this window is currently tracking the bottom of the screen // if this window is currently tracking the bottom of the screen
if ( _trackOutput ) if ( _trackOutput )
{ {
_scrollCount -= _screen->scrolledLines(); _scrollCount -= _screen->scrolledLines();
_currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines())); _currentLine = qMax(0,_screen->getHistLines() - (windowLines()-_screen->getLines()));
} }
else 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 // have run out of space and dropped the oldest
// lines of output - in this case the screen // 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 // be adjusted - otherwise the output will scroll
_currentLine = qMax(0,_currentLine - _currentLine = qMax(0,_currentLine -
_screen->droppedLines()); _screen->droppedLines());
// ensure that the screen window's current position does // ensure that the screen window's current position does
@ -288,7 +288,7 @@ void ScreenWindow::notifyOutputChanged()
_bufferNeedsUpdate = true; _bufferNeedsUpdate = true;
emit outputChanged(); emit outputChanged();
} }
//#include "ScreenWindow.moc" //#include "ScreenWindow.moc"

@ -35,7 +35,7 @@ class Screen;
/** /**
* Provides a window onto a section of a terminal screen. A terminal widget can then render * 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. * in response to mouse or keyboard input.
* *
* A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow() * A new ScreenWindow for a terminal session can be created by calling Emulation::createWindow()
@ -55,7 +55,7 @@ class ScreenWindow : public QObject
Q_OBJECT Q_OBJECT
public: public:
/** /**
* Constructs a new screen window with the given parent. * Constructs a new screen window with the given parent.
* A screen must be specified by calling setScreen() before calling getImage() or getLineProperties(). * 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 */ /** Returns the screen which this window looks onto */
Screen* screen() const; Screen* screen() const;
/** /**
* Returns the image of characters which are currently visible through this window * Returns the image of characters which are currently visible through this window
* onto the screen. * onto the screen.
* *
@ -89,14 +89,14 @@ public:
/** /**
* Returns the number of lines which the region of the window * Returns the number of lines which the region of the window
* specified by scrollRegion() has been scrolled by since the last call * specified by scrollRegion() has been scrolled by since the last call
* to resetScrollCount(). scrollRegion() is in most cases the * to resetScrollCount(). scrollRegion() is in most cases the
* whole window, but will be a smaller area in, for example, applications * whole window, but will be a smaller area in, for example, applications
* which provide split-screen facilities. * which provide split-screen facilities.
* *
* This is not guaranteed to be accurate, but allows views to optimize * This is not guaranteed to be accurate, but allows views to optimize
* rendering by reducing the amount of costly text rendering that * 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; int scrollCount() const;
@ -106,7 +106,7 @@ public:
void resetScrollCount(); 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. * usually the whole window area.
* *
* Like scrollCount(), this is not guaranteed to be accurate, * Like scrollCount(), this is not guaranteed to be accurate,
@ -114,8 +114,8 @@ public:
*/ */
QRect scrollRegion() const; 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. * the window.
*/ */
void setSelectionStart( int column , int line , bool columnMode ); 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 * Sets the end of the selection to the given @p line and @p column within
* the window. * the window.
*/ */
void setSelectionEnd( int column , int line ); void setSelectionEnd( int column , int line );
/** /**
* Retrieves the start of the selection within the window. * 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. * Returns true if the character at @p line , @p column is part of the selection.
*/ */
bool isSelected( int column , int line ); bool isSelected( int column , int line );
/** /**
* Clears the current selection * Clears the current selection
*/ */
void clearSelection(); void clearSelection();
@ -147,7 +147,7 @@ public:
int windowLines() const; int windowLines() const;
/** Returns the number of columns in the window */ /** Returns the number of columns in the window */
int windowColumns() const; int windowColumns() const;
/** Returns the total number of lines in the screen */ /** Returns the total number of lines in the screen */
int lineCount() const; int lineCount() const;
/** Returns the total number of columns in the screen */ /** 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 */ /** Returns the index of the line which is currently at the top of this window */
int currentLine() const; int currentLine() const;
/** /**
* Returns the position of the cursor * Returns the position of the cursor
* within the window. * within the window.
*/ */
QPoint cursorPosition() const; QPoint cursorPosition() const;
/** /**
* Convenience method. Returns true if the window is currently at the bottom * Convenience method. Returns true if the window is currently at the bottom
* of the screen. * of the screen.
*/ */
@ -176,33 +176,33 @@ public:
{ {
/** Scroll the window down by a given number of lines. */ /** Scroll the window down by a given number of lines. */
ScrollLines, ScrollLines,
/** /**
* Scroll the window down by a given number of pages, where * Scroll the window down by a given number of pages, where
* one page is windowLines() lines * one page is windowLines() lines
*/ */
ScrollPages ScrollPages
}; };
/** /**
* Scrolls the window relative to its current position on the screen. * 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 * @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 * @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 * this number is positive, the view is scrolled down. If this number is negative, the view
* is scrolled up. * is scrolled up.
*/ */
void scrollBy( RelativeScrollMode mode , int amount ); void scrollBy( RelativeScrollMode mode , int amount );
/** /**
* Specifies whether the window should automatically move to the bottom * Specifies whether the window should automatically move to the bottom
* of the screen when new output is added. * 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. * screen() ) when the notifyOutputChanged() method is called.
*/ */
void setTrackOutput(bool trackOutput); void setTrackOutput(bool trackOutput);
/** /**
* Returns whether the window automatically moves to the bottom of the screen as * Returns whether the window automatically moves to the bottom of the screen as
* new output is added. See setTrackOutput() * new output is added. See setTrackOutput()
*/ */
@ -216,7 +216,7 @@ public:
QString selectedText( bool preserveLineBreaks ) const; QString selectedText( bool preserveLineBreaks ) const;
public slots: public slots:
/** /**
* Notifies the window that the contents of the associated terminal screen have changed. * 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 * This moves the window to the bottom of the screen if trackOutput() is true and causes
* the outputChanged() signal to be emitted. * the outputChanged() signal to be emitted.
@ -225,13 +225,13 @@ public slots:
signals: 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(); void outputChanged();
/** /**
* Emitted when the screen window is scrolled to a different position. * Emitted when the screen window is scrolled to a different position.
* *
* @param line The line which is now at the top of the window. * @param line The line which is now at the top of the window.
*/ */
void scrolled(int line); void scrolled(int line);
@ -250,7 +250,7 @@ private:
int _windowLines; int _windowLines;
int _currentLine; // see scrollTo() , currentLine() 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 int _scrollCount; // count of lines which the window has been scrolled by since
// the last call to resetScrollCount() // the last call to resetScrollCount()
}; };

@ -30,18 +30,18 @@ SearchBar::SearchBar(QWidget *parent) : QWidget(parent)
connect(widget.searchTextEdit, SIGNAL(textChanged(QString)), this, SIGNAL(searchCriteriaChanged())); connect(widget.searchTextEdit, SIGNAL(textChanged(QString)), this, SIGNAL(searchCriteriaChanged()));
connect(widget.findPreviousButton, SIGNAL(clicked()), this, SIGNAL(findPrevious())); connect(widget.findPreviousButton, SIGNAL(clicked()), this, SIGNAL(findPrevious()));
connect(widget.findNextButton, SIGNAL(clicked()), this, SIGNAL(findNext())); connect(widget.findNextButton, SIGNAL(clicked()), this, SIGNAL(findNext()));
connect(this, SIGNAL(searchCriteriaChanged()), this, SLOT(clearBackgroundColor())); connect(this, SIGNAL(searchCriteriaChanged()), this, SLOT(clearBackgroundColor()));
QMenu *optionsMenu = new QMenu(widget.optionsButton); QMenu *optionsMenu = new QMenu(widget.optionsButton);
widget.optionsButton->setMenu(optionsMenu); widget.optionsButton->setMenu(optionsMenu);
m_matchCaseMenuEntry = optionsMenu->addAction(tr("Match case")); m_matchCaseMenuEntry = optionsMenu->addAction(tr("Match case"));
m_matchCaseMenuEntry->setCheckable(true); m_matchCaseMenuEntry->setCheckable(true);
m_matchCaseMenuEntry->setChecked(true); m_matchCaseMenuEntry->setChecked(true);
connect(m_matchCaseMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); connect(m_matchCaseMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged()));
m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression")); m_useRegularExpressionMenuEntry = optionsMenu->addAction(tr("Regular expression"));
m_useRegularExpressionMenuEntry->setCheckable(true); m_useRegularExpressionMenuEntry->setCheckable(true);
connect(m_useRegularExpressionMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged())); connect(m_useRegularExpressionMenuEntry, SIGNAL(toggled(bool)), this, SIGNAL(searchCriteriaChanged()));
@ -92,20 +92,20 @@ void SearchBar::noMatchFound()
void SearchBar::keyReleaseEvent(QKeyEvent* keyEvent) 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) if (keyEvent->modifiers() == Qt::ShiftModifier)
{ {
findPrevious(); findPrevious();
} }
else else
{ {
findNext(); findNext();
} }
} }
else if (keyEvent->key() == Qt::Key_Escape) else if (keyEvent->key() == Qt::Key_Escape)
{ {
hide(); hide();
} }
} }
@ -115,4 +115,4 @@ void SearchBar::clearBackgroundColor()
p.setColor(QPalette::Base, Qt::white); p.setColor(QPalette::Base, Qt::white);
widget.searchTextEdit->setPalette(p); widget.searchTextEdit->setPalette(p);
} }

@ -33,7 +33,7 @@ public:
QString searchText(); QString searchText();
bool useRegularExpression(); bool useRegularExpression();
bool matchCase(); bool matchCase();
bool highlightAllMatches(); bool highlightAllMatches();
public slots: public slots:
void noMatchFound(); void noMatchFound();

@ -49,7 +49,7 @@ using namespace Konsole;
int Session::lastSessionId = 0; int Session::lastSessionId = 0;
Session::Session(QObject* parent) : Session::Session(QObject* parent) :
QObject(parent), QObject(parent),
_shellProcess(0) _shellProcess(0)
, _emulation(0) , _emulation(0)
@ -79,6 +79,7 @@ Session::Session(QObject* parent) :
//create teletype for I/O with shell process //create teletype for I/O with shell process
_shellProcess = new Pty(); _shellProcess = new Pty();
ptySlaveFd = _shellProcess->pty()->slaveFd();
//create emulation backend //create emulation backend
_emulation = new Vt102Emulation(); _emulation = new Vt102Emulation();
@ -129,7 +130,17 @@ WId Session::windowId() const
// there are multiple views, then the window ID for the // there are multiple views, then the window ID for the
// top-level window which contains the first view is // top-level window which contains the first view is
// returned // 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 ) { if ( _views.count() == 0 ) {
return 0; return 0;
} else { } else {
@ -143,6 +154,7 @@ WId Session::windowId() const
return window->winId(); return window->winId();
} }
#endif
} }
void Session::setDarkBackground(bool darkBackground) void Session::setDarkBackground(bool darkBackground)
@ -341,6 +353,22 @@ void Session::run()
emit started(); 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 ) void Session::setUserTitle( int what, const QString & caption )
{ {
//set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle ) //set to true if anything is actually changed (eg. old _nameTitle != new _nameTitle )
@ -469,8 +497,8 @@ void Session::activityStateSet(int state)
if ( _monitorActivity ) { if ( _monitorActivity ) {
//FIXME: See comments in Session::monitorTimerDone() //FIXME: See comments in Session::monitorTimerDone()
if (!_notifiedActivity) { if (!_notifiedActivity) {
emit activity();
_notifiedActivity=true; _notifiedActivity=true;
emit activity();
} }
} }
} }
@ -928,6 +956,10 @@ int Session::processId() const
{ {
return _shellProcess->pid(); return _shellProcess->pid();
} }
int Session::getPtySlaveFd() const
{
return ptySlaveFd;
}
SessionGroup::SessionGroup() SessionGroup::SessionGroup()
: _masterMode(0) : _masterMode(0)

@ -25,7 +25,6 @@
#ifndef SESSION_H #ifndef SESSION_H
#define SESSION_H #define SESSION_H
#include <QStringList> #include <QStringList>
#include <QWidget> #include <QWidget>
@ -363,6 +362,13 @@ public:
// void cancelZModem(); // void cancelZModem();
// bool isZModemBusy() { return _zmodemBusy; } // 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: public slots:
/** /**
@ -372,6 +378,13 @@ public slots:
*/ */
void run(); 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 * Closes the terminal session. This sends a hangup signal
* (SIGHUP) to the terminal process and causes the done(Session*) * (SIGHUP) to the terminal process and causes the done(Session*)
@ -543,6 +556,8 @@ private:
static int lastSessionId; static int lastSessionId;
int ptySlaveFd;
}; };
/** /**

@ -1,8 +1,8 @@
/* /*
This file is part of Konsole, an X terminal. This file is part of Konsole, an X terminal.
Copyright 2006-2008 by Robert Knight <robertknight@gmail.com> Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
This program is free software; you can redistribute it and/or modify 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 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 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) //(since QTextStream always deals with QStrings internally anyway)
QString plainText; QString plainText;
plainText.reserve(count); plainText.reserve(count);
int outputCount = count; int outputCount = count;
// if inclusion of trailing whitespace is disabled then find the end of the // 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--; outputCount--;
} }
} }
for (int i=0;i<outputCount;) for (int i=0;i<outputCount;)
{ {
plainText.append( QChar(characters[i].character) ); plainText.append( QChar(characters[i].character) );
@ -114,7 +114,7 @@ HTMLDecoder::HTMLDecoder() :
,_innerSpanOpen(false) ,_innerSpanOpen(false)
,_lastRendition(DEFAULT_RENDITION) ,_lastRendition(DEFAULT_RENDITION)
{ {
} }
void HTMLDecoder::begin(QTextStream* output) void HTMLDecoder::begin(QTextStream* output)
@ -152,7 +152,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
QString text; QString text;
int spaceCount = 0; int spaceCount = 0;
for (int i=0;i<count;i++) for (int i=0;i<count;i++)
{ {
QChar ch(characters[i].character); QChar ch(characters[i].character);
@ -168,7 +168,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
_lastRendition = characters[i].rendition; _lastRendition = characters[i].rendition;
_lastForeColor = characters[i].foregroundColor; _lastForeColor = characters[i].foregroundColor;
_lastBackColor = characters[i].backgroundColor; _lastBackColor = characters[i].backgroundColor;
//build up style string //build up style string
QString style; QString style;
@ -178,15 +178,15 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
useBold = _lastRendition & RE_BOLD; useBold = _lastRendition & RE_BOLD;
else else
useBold = weight == ColorEntry::Bold; useBold = weight == ColorEntry::Bold;
if (useBold) if (useBold)
style.append("font-weight:bold;"); style.append("font-weight:bold;");
if ( _lastRendition & RE_UNDERLINE ) if ( _lastRendition & RE_UNDERLINE )
style.append("font-decoration:underline;"); style.append("font-decoration:underline;");
//colours - a colour table must have been defined first //colours - a colour table must have been defined first
if ( _colorTable ) if ( _colorTable )
{ {
style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) ); style.append( QString("color:%1;").arg(_lastForeColor.color(_colorTable).name() ) );
@ -195,8 +195,8 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) ); style.append( QString("background-color:%1;").arg(_lastBackColor.color(_colorTable).name() ) );
} }
} }
//open the span with the current style //open the span with the current style
openSpan(text,style); openSpan(text,style);
_innerSpanOpen = true; _innerSpanOpen = true;
} }
@ -206,7 +206,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
spaceCount++; spaceCount++;
else else
spaceCount = 0; spaceCount = 0;
//output current character //output current character
if (spaceCount < 2) if (spaceCount < 2)
@ -216,14 +216,14 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
text.append("&lt;"); text.append("&lt;");
else if (ch == '>') else if (ch == '>')
text.append("&gt;"); text.append("&gt;");
else else
text.append(ch); text.append(ch);
} }
else else
{ {
text.append("&nbsp;"); //HTML truncates multiple spaces, so use a space marker instead text.append("&nbsp;"); //HTML truncates multiple spaces, so use a space marker instead
} }
} }
//close any remaining open inner spans //close any remaining open inner spans
@ -232,7 +232,7 @@ void HTMLDecoder::decodeLine(const Character* const characters, int count, LineP
//start new line //start new line
text.append("<br>"); text.append("<br>");
*_output << text; *_output << text;
} }
void HTMLDecoder::openSpan(QString& text , const QString& style) void HTMLDecoder::openSpan(QString& text , const QString& style)

@ -1,8 +1,8 @@
/* /*
This file is part of Konsole, an X terminal. This file is part of Konsole, an X terminal.
Copyright 2006-2008 by Robert Knight <robertknight@gmail.com> Copyright 2006-2008 by Robert Knight <robertknight@gmail.com>
This program is free software; you can redistribute it and/or modify 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 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 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. * 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 * 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 class TerminalCharacterDecoder
{ {
@ -58,9 +58,9 @@ public:
* @param count The number of characters * @param count The number of characters
* @param properties Additional properties which affect all characters in the line * @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, int count,
LineProperty properties) = 0; LineProperty properties) = 0;
}; };
/** /**
@ -70,10 +70,10 @@ public:
class PlainTextDecoder : public TerminalCharacterDecoder class PlainTextDecoder : public TerminalCharacterDecoder
{ {
public: 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. * in the output.
* Defaults to true. * Defaults to true.
*/ */
@ -83,9 +83,9 @@ public:
* in the output. * in the output.
*/ */
bool trailingWhitespace() const; bool trailingWhitespace() const;
/** /**
* Returns of character positions in the output stream * 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. * the output device is not a string.
*/ */
QList<int> linePositions() const; QList<int> linePositions() const;
@ -97,9 +97,9 @@ public:
virtual void decodeLine(const Character* const characters, virtual void decodeLine(const Character* const characters,
int count, int count,
LineProperty properties); LineProperty properties);
private: private:
QTextStream* _output; QTextStream* _output;
bool _includeTrailingWhitespace; bool _includeTrailingWhitespace;
@ -114,7 +114,7 @@ private:
class HTMLDecoder : public TerminalCharacterDecoder class HTMLDecoder : public TerminalCharacterDecoder
{ {
public: public:
/** /**
* Constructs an HTML decoder using a default black-on-white color scheme. * Constructs an HTML decoder using a default black-on-white color scheme.
*/ */
HTMLDecoder(); HTMLDecoder();
@ -124,7 +124,7 @@ public:
* output * output
*/ */
void setColorTable( const ColorEntry* table ); void setColorTable( const ColorEntry* table );
virtual void decodeLine(const Character* const characters, virtual void decodeLine(const Character* const characters,
int count, int count,
LineProperty properties); LineProperty properties);
@ -138,7 +138,7 @@ private:
QTextStream* _output; QTextStream* _output;
const ColorEntry* _colorTable; const ColorEntry* _colorTable;
bool _innerSpanOpen; bool _innerSpanOpen;
quint8 _lastRendition; quint8 _lastRendition;
CharacterColor _lastForeColor; CharacterColor _lastForeColor;
CharacterColor _lastBackColor; CharacterColor _lastBackColor;

File diff suppressed because it is too large Load Diff

@ -70,7 +70,7 @@ class ScreenWindow;
* A widget which displays output from a terminal emulation and sends input keypresses and mouse activity * A widget which displays output from a terminal emulation and sends input keypresses and mouse activity
* to the terminal. * 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(). * it will update the display by calling updateImage().
* *
* TODO More documentation * TODO More documentation
@ -102,25 +102,25 @@ public:
/** Sets the opacity of the terminal display. */ /** Sets the opacity of the terminal display. */
void setOpacity(qreal opacity); void setOpacity(qreal opacity);
/** /**
* This enum describes the location where the scroll bar is positioned in the display widget. * 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. */ /** Do not show the scroll bar. */
NoScrollBar=0, NoScrollBar=0,
/** Show the scroll bar on the left side of the display. */ /** 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. */ /** 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 * 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. * is shown on the left or right side of the display.
*/ */
void setScrollBarPosition(ScrollBarPosition position); void setScrollBarPosition(ScrollBarPosition position);
/** /**
* Sets the current position and range of the display's scroll bar. * Sets the current position and range of the display's scroll bar.
* *
* @param cursor The position of the scroll bar's thumb. * @param cursor The position of the scroll bar's thumb.
@ -133,7 +133,7 @@ public:
*/ */
void scrollToEnd(); void scrollToEnd();
/** /**
* Returns the display's filter chain. When the image for the display is updated, * 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 * 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). * hotspots which correspond to certain strings (such as URLs or particular words).
@ -146,11 +146,11 @@ public:
*/ */
FilterChain* filterChain() const; FilterChain* filterChain() const;
/** /**
* Updates the filters in the display's filter chain. This will cause * Updates the filters in the display's filter chain. This will cause
* the hotspots to be updated to match the current image. * 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() * image size and number of filters in the filterChain()
* *
* TODO - This API does not really allow efficient usage. Revise it so * TODO - This API does not really allow efficient usage. Revise it so
@ -159,10 +159,10 @@ public:
* eg: * eg:
* - Area of interest may be known ( eg. mouse cursor hovering * - Area of interest may be known ( eg. mouse cursor hovering
* over an area ) * over an area )
*/ */
void processFilters(); void processFilters();
/** /**
* Returns a list of menu actions created by the filters for the content * Returns a list of menu actions created by the filters for the content
* at the given @p position. * at the given @p position.
*/ */
@ -179,9 +179,9 @@ public:
void setCtrlDrag(bool enable) { _ctrlDrag=enable; } void setCtrlDrag(bool enable) { _ctrlDrag=enable; }
bool ctrlDrag() { return _ctrlDrag; } bool ctrlDrag() { return _ctrlDrag; }
/** /**
* This enum describes the methods for selecting text when * 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 enum TripleClickMode
{ {
@ -190,7 +190,7 @@ public:
/** Select from the current cursor position to the end of the line. */ /** Select from the current cursor position to the end of the line. */
SelectForwardsFromCursor 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; } void setTripleClickMode(TripleClickMode mode) { _tripleClickMode = mode; }
/** See setTripleClickSelectionMode() */ /** See setTripleClickSelectionMode() */
TripleClickMode tripleClickMode() { return _tripleClickMode; } TripleClickMode tripleClickMode() { return _tripleClickMode; }
@ -208,22 +208,22 @@ public:
{ {
/** A rectangular block which covers the entire area of the cursor character. */ /** A rectangular block which covers the entire area of the cursor character. */
BlockCursor, BlockCursor,
/** /**
* A single flat line which occupies the space at the bottom of the cursor * A single flat line which occupies the space at the bottom of the cursor
* character's area. * character's area.
*/ */
UnderlineCursor, 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. * cursor used in Qt/KDE text editors.
*/ */
IBeamCursor 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. * 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() * the mouse pointer, which can be set using the QWidget::setCursor()
* method. * method.
* *
@ -236,7 +236,7 @@ public:
KeyboardCursorShape keyboardCursorShape() const; 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 * The keyboard cursor defaults to using the foreground color of the character
* underneath it. * underneath it.
@ -250,10 +250,10 @@ public:
*/ */
void setKeyboardCursorColor(bool useForegroundColor , const QColor& color); void setKeyboardCursorColor(bool useForegroundColor , const QColor& color);
/** /**
* Returns the color of the keyboard cursor, or an invalid color if the keyboard * 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 * cursor color is set to change according to the foreground color of the character
* underneath it. * underneath it.
*/ */
QColor keyboardCursorColor() const; QColor keyboardCursorColor() const;
@ -278,19 +278,19 @@ public:
*/ */
int fontHeight() { return _fontHeight; } 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. * This assumes the use of a fixed-width font.
*/ */
int fontWidth() { return _fontWidth; } int fontWidth() { return _fontWidth; }
void setSize(int cols, int lins); void setSize(int cols, int lins);
void setFixedSize(int cols, int lins); void setFixedSize(int cols, int lins);
// reimplemented // reimplemented
QSize sizeHint() const; 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 * are regarded as being part of a word for the purposes
* of selecting words in the display by double clicking on them. * 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 ). * of a word ( in addition to letters and numbers ).
*/ */
void setWordCharacters(const QString& wc); 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. * purpose of selecting words in the display with the mouse.
* *
* @see setWordCharacters() * @see setWordCharacters()
*/ */
QString wordCharacters() { return _wordCharacters; } 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. * terminal session.
* *
* The terminal session can trigger the bell effect by calling bell() with * The terminal session can trigger the bell effect by calling bell() with
* the alert message. * the alert message.
*/ */
void setBellMode(int mode); void setBellMode(int mode);
/** /**
* Returns the type of effect used to alert the user when a 'bell' occurs in * Returns the type of effect used to alert the user when a 'bell' occurs in
* the terminal session. * the terminal session.
* *
* See setBellMode() * See setBellMode()
*/ */
int bellMode() { return _bellMode; } int bellMode() { return _bellMode; }
@ -331,23 +331,23 @@ public:
* session. * session.
*/ */
enum BellMode enum BellMode
{ {
/** A system beep. */ /** A system beep. */
SystemBeepBell=0, SystemBeepBell=0,
/** /**
* KDE notification. This may play a sound, show a passive popup * KDE notification. This may play a sound, show a passive popup
* or perform some other action depending on the user's settings. * 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) */ /** A silent, visual bell (eg. inverting the display's colors briefly) */
VisualBell=2, VisualBell=2,
/** No bell effects */ /** No bell effects */
NoBell=3 NoBell=3
}; };
void setSelection(const QString &t); void setSelection(const QString &t);
/** /**
* Reimplemented. Has no effect. Use setVTFont() to change the font * Reimplemented. Has no effect. Use setVTFont() to change the font
* used to draw characters in the display. * used to draw characters in the display.
*/ */
@ -356,9 +356,9 @@ public:
/** Returns the font used to draw characters in the display */ /** Returns the font used to draw characters in the display */
QFont getVTFont() { return font(); } QFont getVTFont() { return font(); }
/** /**
* Sets the font used to draw the display. Has no effect if @p 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); void setVTFont(const QFont& font);
@ -367,7 +367,7 @@ public:
* is enabled or not. Defaults to enabled. * is enabled or not. Defaults to enabled.
*/ */
static void setAntialias( bool antialias ) { _antialiasText = antialias; } static void setAntialias( bool antialias ) { _antialiasText = antialias; }
/** /**
* Returns true if anti-aliasing of text in the terminal is enabled. * Returns true if anti-aliasing of text in the terminal is enabled.
*/ */
static bool antialias() { return _antialiasText; } static bool antialias() { return _antialiasText; }
@ -381,20 +381,20 @@ public:
* Returns true if characters with intense colors are rendered in bold. * Returns true if characters with intense colors are rendered in bold.
*/ */
bool getBoldIntense() { return _boldIntense; } 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 * terminal in lines and columns is displayed whilst the widget
* is being resized. * is being resized.
*/ */
void setTerminalSizeHint(bool on) { _terminalSizeHint=on; } void setTerminalSizeHint(bool on) { _terminalSizeHint=on; }
/** /**
* Returns whether or not the current height and width of * Returns whether or not the current height and width of
* the terminal in lines and columns is displayed whilst the widget * the terminal in lines and columns is displayed whilst the widget
* is being resized. * is being resized.
*/ */
bool terminalSizeHint() { return _terminalSizeHint; } bool terminalSizeHint() { return _terminalSizeHint; }
/** /**
* Sets whether the terminal size display is shown briefly * Sets whether the terminal size display is shown briefly
* after the widget is first shown. * after the widget is first shown.
* *
@ -425,36 +425,36 @@ public:
ScreenWindow* screenWindow() const; ScreenWindow* screenWindow() const;
static bool HAVE_TRANSPARENCY; static bool HAVE_TRANSPARENCY;
void setMotionAfterPasting(MotionAfterPasting action); void setMotionAfterPasting(MotionAfterPasting action);
int motionAfterPasting(); int motionAfterPasting();
// maps a point on the widget to the position ( ie. line and column ) // maps a point on the widget to the position ( ie. line and column )
// of the character at that point. // of the character at that point.
void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const; void getCharacterPosition(const QPoint& widgetPoint,int& line,int& column) const;
public slots: public slots:
/** /**
* Causes the terminal display to fetch the latest character image from the associated * Causes the terminal display to fetch the latest character image from the associated
* terminal screen ( see setScreenWindow() ) and redraw the display. * terminal screen ( see setScreenWindow() ) and redraw the display.
*/ */
void updateImage(); void updateImage();
/** Essentially calles processFilters(). /** Essentially calles processFilters().
*/ */
void updateFilters(); void updateFilters();
/** /**
* Causes the terminal display to fetch the latest line status flags from the * Causes the terminal display to fetch the latest line status flags from the
* associated terminal screen ( see setScreenWindow() ). * associated terminal screen ( see setScreenWindow() ).
*/ */
void updateLineProperties(); void updateLineProperties();
/** Copies the selected text to the clipboard. */ /** Copies the selected text to the clipboard. */
void copyClipboard(); void copyClipboard();
/** /**
* Pastes the content of the clipboard into the * Pastes the content of the clipboard into the
* display. * display.
*/ */
void pasteClipboard(); void pasteClipboard();
@ -464,26 +464,26 @@ public slots:
*/ */
void pasteSelection(); void pasteSelection();
/** /**
* Changes whether the flow control warning box should be shown when the flow control * Changes whether the flow control warning box should be shown when the flow control
* stop key (Ctrl+S) are pressed. * stop key (Ctrl+S) are pressed.
*/ */
void setFlowControlWarningEnabled(bool enabled); 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() * See outputSuspended() and setFlowControlWarningEnabled()
*/ */
bool flowControlWarningEnabled() const bool flowControlWarningEnabled() const
{ return _flowControlWarningEnabled; } { return _flowControlWarningEnabled; }
/** /**
* Causes the widget to display or hide a message informing the user that terminal * 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) * 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 * @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 * be shown or false to indicate that terminal output has been resumed and that
* the warning message should disappear. * the warning message should disappear.
*/ */
void outputSuspended(bool suspended); 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 * 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. * or otherwise moves the mouse inside the view.
* The user interaction needed to create selections will also change, and the user will be required * 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 * view area - since the program running in the terminal is being allowed to handle normal mouse
* events itself. * events itself.
* *
@ -501,28 +501,28 @@ public slots:
* or false otherwise. * or false otherwise.
*/ */
void setUsesMouse(bool usesMouse); void setUsesMouse(bool usesMouse);
/** See setUsesMouse() */ /** See setUsesMouse() */
bool usesMouse() const; bool usesMouse() const;
/** /**
* Shows a notification that a bell event has occurred in the terminal. * Shows a notification that a bell event has occurred in the terminal.
* TODO: More documentation here * TODO: More documentation here
*/ */
void bell(const QString& message); void bell(const QString& message);
/** /**
* Sets the background of the display to the specified color. * Sets the background of the display to the specified color.
* @see setColorTable(), setForegroundColor() * @see setColorTable(), setForegroundColor()
*/ */
void setBackgroundColor(const QColor& color); 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() * @see setColorTable(), setBackgroundColor()
*/ */
void setForegroundColor(const QColor& color); void setForegroundColor(const QColor& color);
void selectionChanged(); void selectionChanged();
signals: signals:
@ -532,7 +532,7 @@ signals:
*/ */
void keyPressedSignal(QKeyEvent *e); void keyPressedSignal(QKeyEvent *e);
/** /**
* A mouse event occurred. * 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 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 * @param column The character column where the event occurred
@ -543,7 +543,7 @@ signals:
void changedFontMetricSignal(int height, int width); void changedFontMetricSignal(int height, int width);
void changedContentSizeSignal(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 * Emitted when the user right clicks on the display, or right-clicks with the Shift
* key held down if usesMouse() is true. * key held down if usesMouse() is true.
* *
@ -552,9 +552,9 @@ signals:
void configureRequest(const QPoint& position); void configureRequest(const QPoint& position);
/** /**
* When a shortcut which is also a valid terminal key sequence is pressed while * 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 * the terminal widget has focus, this signal is emitted to allow the host to decide
* whether the shortcut should be overridden. * whether the shortcut should be overridden.
* When the shortcut is overridden, the key sequence will be sent to the terminal emulation instead * 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. * and the action associated with the shortcut will not be triggered.
* *
@ -564,13 +564,14 @@ signals:
void isBusySelecting(bool); void isBusySelecting(bool);
void sendStringToEmu(const char*); void sendStringToEmu(const char*);
// qtermwidget signals // qtermwidget signals
void copyAvailable(bool); void copyAvailable(bool);
void termGetFocus(); void termGetFocus();
void termLostFocus(); void termLostFocus();
void notifyBell(const QString&); void notifyBell(const QString&);
void usesMouseChanged();
protected: protected:
virtual bool event( QEvent * ); virtual bool event( QEvent * );
@ -593,7 +594,7 @@ protected:
virtual void wheelEvent( QWheelEvent* ); virtual void wheelEvent( QWheelEvent* );
virtual bool focusNextPrevChild( bool next ); virtual bool focusNextPrevChild( bool next );
// drag and drop // drag and drop
virtual void dragEnterEvent(QDragEnterEvent* event); virtual void dragEnterEvent(QDragEnterEvent* event);
virtual void dropEvent(QDropEvent* event); virtual void dropEvent(QDropEvent* event);
@ -609,7 +610,7 @@ protected:
// classifies the 'ch' into one of three categories // classifies the 'ch' into one of three categories
// and returns a character to indicate which category it is in // and returns a character to indicate which category it is in
// //
// - A space (returns ' ') // - A space (returns ' ')
// - Part of a word (returns 'a') // - Part of a word (returns 'a')
// - Other characters (returns the input character) // - Other characters (returns the input character)
QChar charClass(QChar ch) const; QChar charClass(QChar ch) const;
@ -627,7 +628,7 @@ protected slots:
void scrollBarPositionChanged(int value); void scrollBarPositionChanged(int value);
void blinkEvent(); void blinkEvent();
void blinkCursorEvent(); void blinkCursorEvent();
//Renables bell noises and visuals. Used to disable further bells for a short period of time //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. //after emitting the first in a sequence of bell events.
void enableBell(); void enableBell();
@ -641,14 +642,19 @@ private:
// -- Drawing helpers -- // -- 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 // divides the part of the display specified by 'rect' into
// fragments according to their colors and styles and calls // 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); void drawContents(QPainter &paint, const QRect &rect);
// draws a section of text, all the text in this section // draws a section of text, all the text in this section
// has a common color and style // has a common color and style
void drawTextFragment(QPainter& painter, const QRect& rect, void drawTextFragment(QPainter& painter, const QRect& rect,
const QString& text, const Character* style); const QString& text, const Character* style);
// draws the background for a text fragment // draws the background for a text fragment
// if useOpacitySetting is true then the color's alpha value will be set to // if useOpacitySetting is true then the color's alpha value will be set to
// the display's transparency (set with setOpacity()), otherwise the background // 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, void drawBackground(QPainter& painter, const QRect& rect, const QColor& color,
bool useOpacitySetting); bool useOpacitySetting);
// draws the cursor character // 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); const QColor& backgroundColor , bool& invertColors);
// draws the characters or line graphics in a text fragment // 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); const Character* style, bool invertCharacterColor);
// draws a string of line graphics // 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); const QString& str, const Character* attributes);
// draws the preedit string for input methods // 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; QRect imageToWidget(const QRect& imageArea) const;
// the area where the preedit string for input methods will be draw // the area where the preedit string for input methods will be draw
@ -680,8 +686,8 @@ private:
// current size in columns and lines // current size in columns and lines
void showResizeNotification(); void showResizeNotification();
// scrolls the image by a number of lines. // scrolls the image by a number of lines.
// 'lines' may be positive ( to scroll the image down ) // 'lines' may be positive ( to scroll the image down )
// or negative ( to scroll the image up ) // or negative ( to scroll the image up )
// 'region' is the part of the image to scroll - currently only // 'region' is the part of the image to scroll - currently only
// the top, bottom and height of 'region' are taken into account, // the top, bottom and height of 'region' are taken into account,
@ -692,7 +698,7 @@ private:
void propagateSize(); void propagateSize();
void updateImageSize(); void updateImageSize();
void makeImage(); void makeImage();
void paintFilters(QPainter& painter); void paintFilters(QPainter& painter);
// returns a region covering all of the areas of the widget which contain // returns a region covering all of the areas of the widget which contain
@ -708,7 +714,7 @@ private:
bool handleShortcutOverrideEvent(QKeyEvent* event); bool handleShortcutOverrideEvent(QKeyEvent* event);
// the window onto the terminal screen which this display // the window onto the terminal screen which this display
// is currently showing. // is currently showing.
QPointer<ScreenWindow> _screenWindow; QPointer<ScreenWindow> _screenWindow;
bool _allowBell; bool _allowBell;
@ -726,7 +732,7 @@ private:
int _lines; // the number of lines that can be displayed in the widget 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 _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 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 'lines' if the character image provided with setImage() is smaller
// than the maximum image size which can be displayed // 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 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 'columns' if the character image provided with setImage() is smaller
// than the maximum image size which can be displayed // than the maximum image size which can be displayed
int _contentHeight; int _contentHeight;
int _contentWidth; int _contentWidth;
Character* _image; // [lines][columns] 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 //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 //terminal output - informing them what has happened and how to resume output
QLabel* _outputSuspendedLabel; QLabel* _outputSuspendedLabel;
uint _lineSpacing; uint _lineSpacing;
bool _colorsInverted; // true during visual bell bool _colorsInverted; // true during visual bell
QSize _size; QSize _size;
QRgb _blendColor; QRgb _blendColor;
// list of filters currently applied to the display. used for links and // 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 // custom cursor color. if this is invalid then the foreground
// color of the character under the cursor is used // color of the character under the cursor is used
QColor _cursorColor; QColor _cursorColor;
MotionAfterPasting mMotionAfterPasting; MotionAfterPasting mMotionAfterPasting;

@ -1,6 +1,6 @@
/* /*
This file is part of Konsole, an X terminal. This file is part of Konsole, an X terminal.
Copyright 2007-2008 by Robert Knight <robert.knight@gmail.com> Copyright 2007-2008 by Robert Knight <robert.knight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -37,7 +37,7 @@
void scrolllock_set_on(); void scrolllock_set_on();
#endif #endif
// Standard // Standard
#include <stdio.h> #include <stdio.h>
#include <unistd.h> #include <unistd.h>
#include <assert.h> #include <assert.h>
@ -58,7 +58,7 @@
using namespace Konsole; using namespace Konsole;
Vt102Emulation::Vt102Emulation() Vt102Emulation::Vt102Emulation()
: Emulation(), : Emulation(),
_titleUpdateTimer(new QTimer(this)) _titleUpdateTimer(new QTimer(this))
{ {
@ -75,7 +75,7 @@ Vt102Emulation::~Vt102Emulation()
void Vt102Emulation::clearEntireScreen() void Vt102Emulation::clearEntireScreen()
{ {
_currentScreen->clearEntireScreen(); _currentScreen->clearEntireScreen();
bufferedUpdate(); bufferedUpdate();
} }
void Vt102Emulation::reset() void Vt102Emulation::reset()
@ -87,7 +87,7 @@ void Vt102Emulation::reset()
resetCharset(1); resetCharset(1);
_screen[1]->reset(); _screen[1]->reset();
setCodec(LocaleCodec); setCodec(LocaleCodec);
bufferedUpdate(); bufferedUpdate();
} }
@ -138,7 +138,7 @@ void Vt102Emulation::reset()
- VT52 - VT52 escape codes - VT52 - VT52 escape codes
- <ESC><Chr> - <ESC><Chr>
- <ESC>'Y'{Pc}{Pc} - <ESC>'Y'{Pc}{Pc}
- XTE_HA - Xterm window/terminal attribute commands - XTE_HA - Xterm window/terminal attribute commands
of the form <ESC>`]' {Pn} `;' {Text} <BEL> of the form <ESC>`]' {Pn} `;' {Text} <BEL>
(Note that these are handled differently to the other formats) (Note that these are handled differently to the other formats)
@ -178,9 +178,9 @@ void Vt102Emulation::reset()
void Vt102Emulation::resetTokenizer() void Vt102Emulation::resetTokenizer()
{ {
tokenBufferPos = 0; tokenBufferPos = 0;
argc = 0; argc = 0;
argv[0] = 0; argv[0] = 0;
argv[1] = 0; argv[1] = 0;
} }
@ -206,33 +206,33 @@ void Vt102Emulation::addToCurrentToken(int cc)
#define CTL 1 // Control character #define CTL 1 // Control character
#define CHR 2 // Printable character #define CHR 2 // Printable character
#define CPN 4 // TODO: Document me #define CPN 4 // TODO: Document me
#define DIG 8 // Digit #define DIG 8 // Digit
#define SCS 16 // TODO: Document me #define SCS 16 // TODO: Document me
#define GRP 32 // TODO: Document me #define GRP 32 // TODO: Document me
#define CPS 64 // Character which indicates end of window resize #define CPS 64 // Character which indicates end of window resize
// escape sequence '\e[8;<row>;<col>t' // escape sequence '\e[8;<row>;<col>t'
void Vt102Emulation::initTokenizer() void Vt102Emulation::initTokenizer()
{ {
int i; int i;
quint8* s; quint8* s;
for(i = 0;i < 256; ++i) for(i = 0;i < 256; ++i)
charClass[i] = 0; charClass[i] = 0;
for(i = 0;i < 32; ++i) for(i = 0;i < 32; ++i)
charClass[i] |= CTL; charClass[i] |= CTL;
for(i = 32;i < 256; ++i) for(i = 32;i < 256; ++i)
charClass[i] |= CHR; charClass[i] |= CHR;
for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s) for(s = (quint8*)"@ABCDGHILMPSTXZcdfry"; *s; ++s)
charClass[*s] |= CPN; charClass[*s] |= CPN;
// resize = \e[8;<row>;<col>t // resize = \e[8;<row>;<col>t
for(s = (quint8*)"t"; *s; ++s) for(s = (quint8*)"t"; *s; ++s)
charClass[*s] |= CPS; charClass[*s] |= CPS;
for(s = (quint8*)"0123456789"; *s; ++s) for(s = (quint8*)"0123456789"; *s; ++s)
charClass[*s] |= DIG; charClass[*s] |= DIG;
for(s = (quint8*)"()+*%"; *s; ++s) for(s = (quint8*)"()+*%"; *s; ++s)
charClass[*s] |= SCS; charClass[*s] |= SCS;
for(s = (quint8*)"()+*#[]%"; *s; ++s) for(s = (quint8*)"()+*#[]%"; *s; ++s)
charClass[*s] |= GRP; charClass[*s] |= GRP;
resetTokenizer(); resetTokenizer();
@ -249,10 +249,10 @@ void Vt102Emulation::initTokenizer()
- P is the length of the token scanned so far. - P is the length of the token scanned so far.
- L (often P-1) is the position on which contents we base a decision. - 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'). - C is a character or a group of characters (taken from 'charClass').
- 'cc' is the current character - 'cc' is the current character
- 's' is a pointer to the start of the token buffer - '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. Note that they need to applied in proper order.
*/ */
@ -275,31 +275,31 @@ void Vt102Emulation::initTokenizer()
// process an incoming unicode character // process an incoming unicode character
void Vt102Emulation::receiveChar(int cc) void Vt102Emulation::receiveChar(int cc)
{ {
if (cc == 127) if (cc == 127)
return; //VT100: ignore. return; //VT100: ignore.
if (ces(CTL)) if (ces(CTL))
{ {
// DEC HACK ALERT! Control Characters are allowed *within* esc sequences in VT100 // 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 // 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 // of course. Guess this originates from a weakly layered handling of the X-on
// X-off protocol, which comes really below this level. // 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 resetTokenizer(); //VT100: CAN or SUB
if (cc != ESC) if (cc != ESC)
{ {
processToken(TY_CTL(cc+'@' ),0,0); processToken(TY_CTL(cc+'@' ),0,0);
return; return;
} }
} }
// advance the state // advance the state
addToCurrentToken(cc); addToCurrentToken(cc);
int* s = tokenBuffer; int* s = tokenBuffer;
int p = tokenBufferPos; int p = tokenBufferPos;
if (getMode(MODE_Ansi)) if (getMode(MODE_Ansi))
{ {
if (lec(1,0,ESC)) { return; } if (lec(1,0,ESC)) { return; }
if (lec(1,0,ESC+128)) { s[0] = ESC; receiveChar('['); 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; } if (eps( CPN)) { processToken( TY_CSI_PN(cc), argv[0],argv[1]); resetTokenizer(); return; }
// resize = \e[8;<row>;<col>t // resize = \e[8;<row>;<col>t
if (eps(CPS)) if (eps(CPS))
{ {
processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]); processToken( TY_CSI_PS(cc, argv[0]), argv[1], argv[2]);
resetTokenizer(); resetTokenizer();
return; return;
} }
if (epe( )) { processToken( TY_CSI_PE(cc), 0, 0); 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; } if (eec(';')) { addArgument(); return; }
for (int i=0;i<=argc;i++) for (int i=0;i<=argc;i++)
{ {
if (epp()) if (epp())
processToken( TY_CSI_PR(cc,argv[i]), 0, 0); 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 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) else if (cc == 'm' && argc - i >= 4 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 2)
{ {
// ESC[ ... 48;2;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... m // ESC[ ... 48;2;<red>;<green>;<blue> ... m -or- ESC[ ... 38;2;<red>;<green>;<blue> ... m
i += 2; i += 2;
processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_RGB, (argv[i] << 16) | (argv[i+1] << 8) | argv[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; i += 2;
} }
else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5) else if (cc == 'm' && argc - i >= 2 && (argv[i] == 38 || argv[i] == 48) && argv[i+1] == 5)
{ {
// ESC[ ... 48;5;<index> ... m -or- ESC[ ... 38;5;<index> ... m // ESC[ ... 48;5;<index> ... m -or- ESC[ ... 38;5;<index> ... m
i += 2; i += 2;
processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]); processToken( TY_CSI_PS(cc, argv[i-2]), COLOR_SPACE_256, argv[i]);
@ -350,29 +350,29 @@ void Vt102Emulation::receiveChar(int cc)
} }
resetTokenizer(); resetTokenizer();
} }
else else
{ {
// VT52 Mode // 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; 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; return;
if (lec(3,1,'Y')) if (lec(3,1,'Y'))
return;
if (p < 4)
{
processToken( TY_VT52(s[1] ), 0, 0);
resetTokenizer();
return; return;
if (p < 4)
{
processToken( TY_VT52(s[1] ), 0, 0);
resetTokenizer();
return;
} }
processToken( TY_VT52(s[1]), s[2], s[3]); processToken( TY_VT52(s[1]), s[2], s[3]);
resetTokenizer(); resetTokenizer();
return; return;
} }
} }
@ -382,24 +382,24 @@ void Vt102Emulation::processWindowAttributeChange()
// See Session::UserTitleChange for possible values // See Session::UserTitleChange for possible values
int attributeToChange = 0; int attributeToChange = 0;
int i; int i;
for (i = 2; i < tokenBufferPos && for (i = 2; i < tokenBufferPos &&
tokenBuffer[i] >= '0' && tokenBuffer[i] >= '0' &&
tokenBuffer[i] <= '9'; i++) tokenBuffer[i] <= '9'; i++)
{ {
attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0'); attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0');
} }
if (tokenBuffer[i] != ';') if (tokenBuffer[i] != ';')
{ {
reportDecodingError(); reportDecodingError();
return; return;
} }
QString newValue; QString newValue;
newValue.reserve(tokenBufferPos-i-2); newValue.reserve(tokenBufferPos-i-2);
for (int j = 0; j < tokenBufferPos-i-2; j++) for (int j = 0; j < tokenBufferPos-i-2; j++)
newValue[j] = tokenBuffer[i+1+j]; newValue[j] = tokenBuffer[i+1+j];
_pendingTitleUpdates[attributeToChange] = newValue; _pendingTitleUpdates[attributeToChange] = newValue;
_titleUpdateTimer->start(20); _titleUpdateTimer->start(20);
} }
@ -409,9 +409,9 @@ void Vt102Emulation::updateTitle()
QListIterator<int> iter( _pendingTitleUpdates.keys() ); QListIterator<int> iter( _pendingTitleUpdates.keys() );
while (iter.hasNext()) { while (iter.hasNext()) {
int arg = iter.next(); int arg = iter.next();
emit titleChanged( arg , _pendingTitleUpdates[arg] ); emit titleChanged( arg , _pendingTitleUpdates[arg] );
} }
_pendingTitleUpdates.clear(); _pendingTitleUpdates.clear();
} }
// Interpreting Codes --------------------------------------------------------- // 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('%', 'G') : setCodec (Utf8Codec ); break; //LINUX
case TY_ESC_CS('%', '@') : setCodec (LocaleCodec ); 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_DOUBLEWIDTH , true );
_currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true );
break; 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_DOUBLEWIDTH , true );
_currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true ); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , true );
break; break;
@ -524,8 +524,8 @@ void Vt102Emulation::processToken(int token, int p, int q)
_currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false); _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , false);
_currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false);
break; break;
case TY_ESC_DE('6' ) : /* Double width, single height line*/ case TY_ESC_DE('6' ) : /* Double width, single height line*/
_currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true); _currentScreen->setLineProperty( LINE_DOUBLEWIDTH , true);
_currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false); _currentScreen->setLineProperty( LINE_DOUBLEHEIGHT , false);
break; break;
case TY_ESC_DE('8' ) : _currentScreen->helpAlign ( ); 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_BTN_EVENT_MOUSE 1002
// SET_ANY_EVENT_MOUSE 1003 // SET_ANY_EVENT_MOUSE 1003
// //
//Note about mouse modes: //Note about mouse modes:
//There are four mouse modes which xterm-compatible terminals can support - 1000,1001,1002,1003 //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). //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) //1003 (a slight variation on dragging the mouse)
// //
case TY_CSI_PR('h', 1000) : setMode (MODE_Mouse1000); break; //XTERM 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('l', 1000) : resetMode (MODE_Mouse1000); break; //XTERM
case TY_CSI_PR('s', 1000) : saveMode (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 case TY_CSI_PG('c' ) : reportSecondaryAttributes( ); break; //VT100
default: default:
reportDecodingError(); reportDecodingError();
break; break;
}; };
} }
void Vt102Emulation::clearScreenAndSetColumns(int columnCount) void Vt102Emulation::clearScreenAndSetColumns(int columnCount)
{ {
setImageSize(_currentScreen->getLines(),columnCount); setImageSize(_currentScreen->getLines(),columnCount);
clearEntireScreen(); clearEntireScreen();
setDefaultMargins(); setDefaultMargins();
_currentScreen->setCursorYX(0,0); _currentScreen->setCursorYX(0,0);
} }
@ -804,7 +804,7 @@ void Vt102Emulation::sendString(const char* s , int length)
} }
void Vt102Emulation::reportCursorPosition() void Vt102Emulation::reportCursorPosition()
{ {
char tmp[20]; char tmp[20];
sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1); sprintf(tmp,"\033[%d;%dR",_currentScreen->getCursorY()+1,_currentScreen->getCursorX()+1);
sendString(tmp); sendString(tmp);
@ -835,7 +835,7 @@ void Vt102Emulation::reportSecondaryAttributes()
void Vt102Emulation::reportTerminalParms(int p) void Vt102Emulation::reportTerminalParms(int p)
// DECREPTPARM // DECREPTPARM
{ {
char tmp[100]; char tmp[100];
sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true. sprintf(tmp,"\033[%d;1;1;112;112;1;0x",p); // not really true.
sendString(tmp); sendString(tmp);
@ -865,13 +865,13 @@ void Vt102Emulation::reportAnswerBack()
*/ */
void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType ) void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType )
{ {
if (cx < 1 || cy < 1) if (cx < 1 || cy < 1)
return; return;
// normal buttons are passed as 0x20 + button, // normal buttons are passed as 0x20 + button,
// mouse wheel (buttons 4,5) as 0x5c + button // mouse wheel (buttons 4,5) as 0x5c + button
if (cb >= 4) if (cb >= 4)
cb += 0x3c; cb += 0x3c;
//Mouse motion handling //Mouse motion handling
@ -885,11 +885,11 @@ void Vt102Emulation::sendMouseEvent( int cb, int cx, int cy , int eventType )
void Vt102Emulation::sendText( const QString& text ) void Vt102Emulation::sendText( const QString& text )
{ {
if (!text.isEmpty()) if (!text.isEmpty())
{ {
QKeyEvent event(QEvent::KeyPress, QKeyEvent event(QEvent::KeyPress,
0, 0,
Qt::NoModifier, Qt::NoModifier,
text); text);
sendKeyEvent(&event); // expose as a big fat keypress event 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_Ansi) ) states |= KeyboardTranslator::AnsiState;
if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState; if (getMode(MODE_AppCuKeys)) states |= KeyboardTranslator::CursorKeysState;
if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState; if (getMode(MODE_AppScreen)) states |= KeyboardTranslator::AlternateScreenState;
if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier)) if (getMode(MODE_AppKeyPad) && (modifiers & Qt::KeypadModifier))
states |= KeyboardTranslator::ApplicationKeypadState; states |= KeyboardTranslator::ApplicationKeypadState;
// check flow control state // check flow control state
@ -919,8 +919,8 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
// lookup key binding // lookup key binding
if ( _keyTranslator ) if ( _keyTranslator )
{ {
KeyboardTranslator::Entry entry = _keyTranslator->findEntry( KeyboardTranslator::Entry entry = _keyTranslator->findEntry(
event->key() , event->key() ,
modifiers, modifiers,
states ); states );
@ -932,10 +932,10 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
// (unless there is an entry defined for this particular combination // (unless there is an entry defined for this particular combination
// in the keyboard modifier) // in the keyboard modifier)
bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier; bool wantsAltModifier = entry.modifiers() & entry.modifierMask() & Qt::AltModifier;
bool wantsAnyModifier = entry.state() & bool wantsAnyModifier = entry.state() &
entry.stateMask() & KeyboardTranslator::AnyModifierState; entry.stateMask() & KeyboardTranslator::AnyModifierState;
if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier) if ( modifiers & Qt::AltModifier && !(wantsAltModifier || wantsAnyModifier)
&& !event->text().isEmpty() ) && !event->text().isEmpty() )
{ {
textToSend.prepend("\033"); textToSend.prepend("\033");
@ -948,7 +948,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
// TODO command handling // TODO command handling
} }
else if ( !entry.text().isEmpty() ) else if ( !entry.text().isEmpty() )
{ {
textToSend += _codec->fromUnicode(entry.text(true,modifiers)); textToSend += _codec->fromUnicode(entry.text(true,modifiers));
} }
@ -976,7 +976,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
// set // set
QString translatorError = tr("No keyboard translator available. " QString translatorError = tr("No keyboard translator available. "
"The information needed to convert key presses " "The information needed to convert key presses "
"into characters to send to the terminal " "into characters to send to the terminal "
"is missing."); "is missing.");
reset(); reset();
receiveData( translatorError.toUtf8().constData() , translatorError.count() ); receiveData( translatorError.toUtf8().constData() , translatorError.count() );
@ -991,7 +991,7 @@ void Vt102Emulation::sendKeyEvent( QKeyEvent* event )
// Character Set Conversion ------------------------------------------------ -- // Character Set Conversion ------------------------------------------------ --
/* /*
The processing contains a VT100 specific code translation layer. The processing contains a VT100 specific code translation layer.
It's still in use and mainly responsible for the line drawing graphics. 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 in the pipeline. It only applies to tokens, which represent
plain characters. 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 it might involve VT100 enhanced fonts, which have these
particular glyphs allocated in (0x00-0x1f) in their code page. particular glyphs allocated in (0x00-0x1f) in their code page.
*/ */
@ -1137,7 +1137,7 @@ void Vt102Emulation::setMode(int m)
case MODE_Mouse1001: case MODE_Mouse1001:
case MODE_Mouse1002: case MODE_Mouse1002:
case MODE_Mouse1003: case MODE_Mouse1003:
emit programUsesMouseChanged(false); emit programUsesMouseChanged(false);
break; break;
case MODE_AppScreen : _screen[1]->clearSelection(); case MODE_AppScreen : _screen[1]->clearSelection();
@ -1160,14 +1160,14 @@ void Vt102Emulation::resetMode(int m)
if (getMode(MODE_Allow132Columns)) if (getMode(MODE_Allow132Columns))
clearScreenAndSetColumns(80); clearScreenAndSetColumns(80);
break; break;
case MODE_Mouse1000 : case MODE_Mouse1000 :
case MODE_Mouse1001 : case MODE_Mouse1001 :
case MODE_Mouse1002 : case MODE_Mouse1002 :
case MODE_Mouse1003 : case MODE_Mouse1003 :
emit programUsesMouseChanged(true); emit programUsesMouseChanged(true);
break; break;
case MODE_AppScreen : case MODE_AppScreen :
_screen[0]->clearSelection(); _screen[0]->clearSelection();
setScreen(0); setScreen(0);
break; break;
@ -1186,9 +1186,9 @@ void Vt102Emulation::saveMode(int m)
void Vt102Emulation::restoreMode(int m) void Vt102Emulation::restoreMode(int m)
{ {
if (_savedModes.mode[m]) if (_savedModes.mode[m])
setMode(m); setMode(m);
else else
resetMode(m); resetMode(m);
} }
@ -1226,10 +1226,10 @@ static void hexdump(int* s, int len)
void Vt102Emulation::reportDecodingError() void Vt102Emulation::reportDecodingError()
{ {
if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) ) if (tokenBufferPos == 0 || ( tokenBufferPos == 1 && (tokenBuffer[0] & 0xff) >= 32) )
return; return;
printf("Undecodable sequence: "); printf("Undecodable sequence: ");
hexdump(tokenBuffer,tokenBufferPos); hexdump(tokenBuffer,tokenBufferPos);
printf("\n"); printf("\n");
} }

@ -1,6 +1,6 @@
/* /*
This file is part of Konsole, an X terminal. This file is part of Konsole, an X terminal.
Copyright 2007-2008 by Robert Knight <robertknight@gmail.com> Copyright 2007-2008 by Robert Knight <robertknight@gmail.com>
Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de> Copyright 1997,1998 by Lars Doelle <lars.doelle@on-line.de>
@ -26,7 +26,7 @@
// Standard Library // Standard Library
#include <stdio.h> #include <stdio.h>
// Qt // Qt
#include <QKeyEvent> #include <QKeyEvent>
#include <QHash> #include <QHash>
#include <QTimer> #include <QTimer>
@ -37,12 +37,12 @@
#define MODE_AppScreen (MODES_SCREEN+0) // Mode #1 #define MODE_AppScreen (MODES_SCREEN+0) // Mode #1
#define MODE_AppCuKeys (MODES_SCREEN+1) // Application cursor keys (DECCKM) #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_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_Mouse1001 (MODES_SCREEN+4) // Use Hilight mouse tracking
#define MODE_Mouse1002 (MODES_SCREEN+5) // Use cell motion 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_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_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_132Columns (MODES_SCREEN+8) // 80 <-> 132 column mode switch (DECCOLM)
#define MODE_Allow132Columns (MODES_SCREEN+9) // Allow DECCOLM mode #define MODE_Allow132Columns (MODES_SCREEN+9) // Allow DECCOLM mode
#define MODE_total (MODES_SCREEN+10) #define MODE_total (MODES_SCREEN+10)
@ -64,40 +64,40 @@ struct CharCodes
/** /**
* Provides an xterm compatible terminal emulation based on the DEC VT102 terminal. * 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/ * 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. * features such as mouse input handling.
* See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape * See http://rtfm.etla.org/xterm/ctlseq.html for a description of xterm's escape
* sequences. * sequences.
* *
*/ */
class Vt102Emulation : public Emulation class Vt102Emulation : public Emulation
{ {
Q_OBJECT Q_OBJECT
public: public:
/** Constructs a new emulation */ /** Constructs a new emulation */
Vt102Emulation(); Vt102Emulation();
~Vt102Emulation(); ~Vt102Emulation();
// reimplemented from Emulation // reimplemented from Emulation
virtual void clearEntireScreen(); virtual void clearEntireScreen();
virtual void reset(); virtual void reset();
virtual char eraseChar() const; virtual char eraseChar() const;
public slots: public slots:
// reimplemented from Emulation // reimplemented from Emulation
virtual void sendString(const char*,int length = -1); virtual void sendString(const char*,int length = -1);
virtual void sendText(const QString& text); virtual void sendText(const QString& text);
virtual void sendKeyEvent(QKeyEvent*); virtual void sendKeyEvent(QKeyEvent*);
virtual void sendMouseEvent(int buttons, int column, int line, int eventType); virtual void sendMouseEvent(int buttons, int column, int line, int eventType);
protected: protected:
// reimplemented from Emulation // reimplemented from Emulation
virtual void setMode(int mode); virtual void setMode(int mode);
virtual void resetMode(int mode); virtual void resetMode(int mode);
virtual void receiveChar(int cc); virtual void receiveChar(int cc);
private slots: private slots:
//causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates //causes changeTitle() to be emitted for each (int,QString) pair in pendingTitleUpdates
//used to buffer multiple title updates //used to buffer multiple title updates
@ -120,7 +120,7 @@ private:
bool getMode (int mode); bool getMode (int mode);
// saves the current boolean value of 'mode' // saves the current boolean value of 'mode'
void saveMode (int mode); void saveMode (int mode);
// restores the boolean value of 'mode' // restores the boolean value of 'mode'
void restoreMode(int mode); void restoreMode(int mode);
// resets all modes // resets all modes
// (except MODE_Allow132Columns) // (except MODE_Allow132Columns)
@ -143,7 +143,7 @@ private:
// for the purposes of decoding terminal output // for the purposes of decoding terminal output
int charClass[256]; int charClass[256];
void reportDecodingError(); void reportDecodingError();
void processToken(int code, int p, int q); void processToken(int code, int p, int q);
void processWindowAttributeChange(); void processWindowAttributeChange();
@ -177,10 +177,10 @@ private:
TerminalState _currentModes; TerminalState _currentModes;
TerminalState _savedModes; 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 //to update the name of the session
//or window title. //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 //output from the terminal
QHash<int,QString> _pendingTitleUpdates; QHash<int,QString> _pendingTitleUpdates;
QTimer* _titleUpdateTimer; QTimer* _titleUpdateTimer;

@ -38,7 +38,7 @@ class KProcessPrivate;
/** /**
* \class KProcess kprocess.h <KProcess> * \class KProcess kprocess.h <KProcess>
* *
* Child process invocation, monitoring and control. * Child process invocation, monitoring and control.
* *
* This class extends QProcess by some useful functionality, overrides * This class extends QProcess by some useful functionality, overrides

@ -145,7 +145,7 @@ void QTermWidget::findPrevious()
void QTermWidget::search(bool forwards, bool next) void QTermWidget::search(bool forwards, bool next)
{ {
int startColumn, startLine; int startColumn, startLine;
if (next) // search from just after current selection if (next) // search from just after current selection
{ {
m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionEnd(startColumn, startLine); 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); m_impl->m_terminalDisplay->screenWindow()->screen()->getSelectionStart(startColumn, startLine);
} }
qDebug() << "current selection starts at: " << 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()); QRegExp regExp(m_searchBar->searchText());
regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString); regExp.setPatternSyntax(m_searchBar->useRegularExpression() ? QRegExp::RegExp : QRegExp::FixedString);
regExp.setCaseSensitivity(m_searchBar->matchCase() ? Qt::CaseSensitive : Qt::CaseInsensitive); 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); 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(matchFound(int, int, int, int)), this, SLOT(matchFound(int, int, int, int)));
connect(historySearch, SIGNAL(noMatchFound()), this, SLOT(noMatchFound())); 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()); sw->setSelectionEnd(endColumn, endLine - sw->currentLine());
} }
void QTermWidget::noMatchFound() void QTermWidget::noMatchFound()
{ {
m_impl->m_terminalDisplay->screenWindow()->clearSelection(); m_impl->m_terminalDisplay->screenWindow()->clearSelection();
} }
@ -228,12 +228,24 @@ void QTermWidget::startShellProgram()
m_impl->m_session->run(); 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) void QTermWidget::init(int startnow)
{ {
m_layout = new QVBoxLayout(); m_layout = new QVBoxLayout();
m_layout->setMargin(0); m_layout->setMargin(0);
setLayout(m_layout); setLayout(m_layout);
m_impl = new TermWidgetImpl(this); m_impl = new TermWidgetImpl(this);
m_impl->m_terminalDisplay->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); m_impl->m_terminalDisplay->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
m_layout->addWidget(m_impl->m_terminalDisplay); m_layout->addWidget(m_impl->m_terminalDisplay);
@ -347,7 +359,7 @@ QString QTermWidget::workingDirectory()
if (!d.exists()) if (!d.exists())
{ {
qDebug() << "Cannot find" << d.dirName(); qDebug() << "Cannot find" << d.dirName();
goto fallback; goto fallback;
} }
return d.canonicalPath(); return d.canonicalPath();
#endif #endif
@ -485,9 +497,9 @@ void QTermWidget::setZoom(int step)
{ {
if (!m_impl->m_terminalDisplay) if (!m_impl->m_terminalDisplay)
return; return;
QFont font = m_impl->m_terminalDisplay->getVTFont(); QFont font = m_impl->m_terminalDisplay->getVTFont();
font.setPointSize(font.pointSize() + step); font.setPointSize(font.pointSize() + step);
setTerminalFont(font); setTerminalFont(font);
} }
@ -567,6 +579,11 @@ int QTermWidget::screenColumnsCount()
return m_impl->m_terminalDisplay->screenWindow()->screen()->getColumns(); 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) void QTermWidget::setSelectionStart(int row, int column)
{ {
m_impl->m_terminalDisplay->screenWindow()->screen()->setSelectionStart(column, row, true); 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); 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) 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); return m_impl->m_terminalDisplay->filterChain()->hotSpotAt(row, column);
} }
int QTermWidget::getPtySlaveFd() const
{
return m_impl->m_session->getPtySlaveFd();
}

@ -55,6 +55,13 @@ public:
//start shell program if it was not started in constructor //start shell program if it was not started in constructor
void startShellProgram(); 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(); int getShellPID();
void changeDir(const QString & dir); void changeDir(const QString & dir);
@ -63,8 +70,7 @@ public:
// Terminal font // Terminal font
// Default is application font with family Monospace, size 10 // Default is application font with family Monospace, size 10
// USE ONLY FIXED-PITCH FONT! // Beware of a performance penalty and display/alignment issues when using a proportional font.
// otherwise symbols' position could be incorrect
void setTerminalFont(const QFont & font); void setTerminalFont(const QFont & font);
QFont getTerminalFont(); QFont getTerminalFont();
void setTerminalOpacity(qreal level); void setTerminalOpacity(qreal level);
@ -126,18 +132,19 @@ public:
//! Return current key bindings //! Return current key bindings
QString keyBindings(); QString keyBindings();
void setMotionAfterPasting(int); void setMotionAfterPasting(int);
/** Return the number of lines in the history buffer. */ /** Return the number of lines in the history buffer. */
int historyLinesCount(); int historyLinesCount();
int screenColumnsCount(); int screenColumnsCount();
int screenLinesCount();
void setSelectionStart(int row, int column); void setSelectionStart(int row, int column);
void setSelectionEnd(int row, int column); void setSelectionEnd(int row, int column);
void getSelectionStart(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. * Returns the currently selected text.
@ -165,6 +172,13 @@ public:
*/ */
Filter::HotSpot* getHotSpotAt(int row, int column) const; 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: signals:
void finished(); void finished();
void copyAvailable(bool); void copyAvailable(bool);
@ -181,6 +195,13 @@ signals:
void activity(); void activity();
void silence(); 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: public slots:
// Copy selection to clipboard // Copy selection to clipboard
void copyClipboard(); void copyClipboard();
@ -188,13 +209,13 @@ public slots:
// Paste clipboard to terminal // Paste clipboard to terminal
void pasteClipboard(); void pasteClipboard();
// Paste selection to terminal // Paste selection to terminal
void pasteSelection(); void pasteSelection();
// Set zoom // Set zoom
void zoomIn(); void zoomIn();
void zoomOut(); void zoomOut();
/*! Set named key binding for given widget /*! Set named key binding for given widget
*/ */
void setKeyBindings(const QString & kb); void setKeyBindings(const QString & kb);

@ -61,7 +61,7 @@ makefile = pyqtconfig.QtGuiModuleMakefile(
# specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the # specific prefixes or extensions (e.g. the "lib" prefix on UNIX, or the
# ".dll" extension on Windows). # ".dll" extension on Windows).
makefile.extra_lib_dirs.append("..") makefile.extra_lib_dirs.append("..")
makefile.extra_libs = ["qtermwidget"] makefile.extra_libs = ["qtermwidget4"]
# Generate the Makefile itself. # Generate the Makefile itself.
makefile.generate() makefile.generate()

@ -11,25 +11,73 @@ class QTermWidget : QWidget {
%End %End
public: public:
QTermWidget(int startnow = 1, QWidget *parent = 0); enum ScrollBarPosition
~QTermWidget();
enum ScrollBarPosition
{ {
NoScrollBar=0, NoScrollBar=0,
ScrollBarLeft=1, ScrollBarLeft=1,
ScrollBarRight=2 ScrollBarRight=2
}; };
void setTerminalFont(QFont &font);
void setArgs(QStringList &args); QTermWidget(int startnow = 1, QWidget *parent = 0);
void setTextCodec(QTextCodec *codec); ~QTermWidget();
void setColorScheme(int scheme);
void setSize(int h, int v); QSize sizeHint() const;
void setHistorySize(int lines); void startShellProgram();
void setScrollBarPosition(ScrollBarPosition); int getShellPID();
void sendText(QString &text); 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: protected:
void resizeEvent(QResizeEvent *e); void resizeEvent(QResizeEvent *e);
private: private:
void *createTermWidget(int startnow, void *parent); void *createTermWidget(int startnow, void *parent);
}; };

@ -19,12 +19,16 @@
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>. # along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys import sys, signal
from PyQt4 import Qt from PyQt4 import Qt
from PyQt4.QtCore import SIGNAL, SLOT
import QTermWidget import QTermWidget
signal.signal(signal.SIGINT, signal.SIG_DFL)
a = Qt.QApplication(sys.argv) a = Qt.QApplication(sys.argv)
w = QTermWidget.QTermWidget() w = QTermWidget.QTermWidget()
w.show() w.show()
w.connect(w, SIGNAL('finished()'), a, SLOT('quit()'))
a.exec_() a.exec_()

Loading…
Cancel
Save